@north-light/crouter 0.3.348 → 0.3.350

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 (634) hide show
  1. package/bin/crtr-launcher +4 -0
  2. package/bin/runtime-generation-manifest.mjs +12 -2
  3. package/dist/api/client.d.ts +50 -7
  4. package/dist/api/client.js +2 -2
  5. package/dist/api/command-manifest/schema.js +1 -1
  6. package/dist/api/dto/analytics.d.ts +184 -0
  7. package/dist/api/dto/analytics.js +0 -0
  8. package/dist/api/dto/broker-ops.d.ts +43 -1
  9. package/dist/api/dto/config.d.ts +11 -0
  10. package/dist/api/dto/grants.d.ts +14 -0
  11. package/dist/api/dto/grants.js +0 -0
  12. package/dist/api/dto/human-requests.d.ts +14 -0
  13. package/dist/api/dto/memory.d.ts +6 -0
  14. package/dist/api/dto/modelauth.d.ts +35 -0
  15. package/dist/api/dto/node-records.d.ts +35 -0
  16. package/dist/api/dto/node-records.js +0 -0
  17. package/dist/api/dto/nodes.d.ts +5 -0
  18. package/dist/api/dto/profiles.d.ts +38 -3
  19. package/dist/api/dto/worktree.d.ts +11 -0
  20. package/dist/api/errors.d.ts +23 -1
  21. package/dist/api/errors.js +1 -1
  22. package/dist/api/index.d.ts +2 -0
  23. package/dist/api/index.js +1 -1
  24. package/dist/api/node-transport.js +1 -1
  25. package/dist/api/routes.d.ts +22 -0
  26. package/dist/api/routes.js +1 -1
  27. package/dist/build-root.d.ts +6 -1
  28. package/dist/build-root.js +1 -1
  29. package/dist/builtin-memory/crouter-sdk/client.md +34 -0
  30. package/dist/builtin-memory/crouter-sdk/errors.md +2 -0
  31. package/dist/builtin-memory/crouter-sdk/memory.md +2 -2
  32. package/dist/builtin-memory/crouter-sdk/streaming.md +21 -0
  33. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/claude-plugin-commands.ts +8 -4
  34. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +39 -118
  35. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.d.ts +6 -1
  36. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.js +41 -27
  37. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.ts +52 -29
  38. package/dist/cli.js +9 -8
  39. package/dist/clients/attach/chrome/inbox-strip.js +1 -1
  40. package/dist/clients/attach/chrome/roster.js +1 -1
  41. package/dist/clients/attach/config.js +1 -1
  42. package/dist/clients/attach/overlays/auth.js +2 -2
  43. package/dist/clients/attach/overlays/graph.js +1 -1
  44. package/dist/clients/attach/render/tool-calls.js +3 -3
  45. package/dist/clients/attach/session/connection.js +1 -1
  46. package/dist/clients/attach/session/profile-files.js +1 -1
  47. package/dist/clients/attach/viewer.js +1569 -816
  48. package/dist/commands/api-client.js +3 -3
  49. package/dist/commands/broker-permissions.d.ts +2 -0
  50. package/dist/commands/broker-permissions.js +1 -0
  51. package/dist/commands/canvas-analytics/chart.d.ts +52 -0
  52. package/dist/commands/canvas-analytics/chart.js +1 -0
  53. package/dist/commands/canvas-analytics/drilldown.d.ts +34 -0
  54. package/dist/commands/canvas-analytics/drilldown.js +1 -0
  55. package/dist/commands/canvas-analytics/format.d.ts +29 -0
  56. package/dist/commands/canvas-analytics/format.js +1 -0
  57. package/dist/commands/canvas-analytics/graph-detail.d.ts +2 -0
  58. package/dist/commands/canvas-analytics/graph-detail.js +2 -0
  59. package/dist/commands/canvas-analytics/graphs.d.ts +9 -0
  60. package/dist/commands/canvas-analytics/graphs.js +1 -0
  61. package/dist/commands/canvas-analytics/memory.d.ts +2 -0
  62. package/dist/commands/canvas-analytics/memory.js +1 -0
  63. package/dist/commands/canvas-analytics/overview.d.ts +2 -0
  64. package/dist/commands/canvas-analytics/overview.js +1 -0
  65. package/dist/commands/canvas-analytics/shell.d.ts +60 -0
  66. package/dist/commands/canvas-analytics/shell.js +2 -0
  67. package/dist/commands/canvas-analytics/time.d.ts +2 -0
  68. package/dist/commands/canvas-analytics/time.js +1 -0
  69. package/dist/commands/canvas-analytics/usage.d.ts +2 -0
  70. package/dist/commands/canvas-analytics/usage.js +1 -0
  71. package/dist/commands/canvas-analytics/view.d.ts +85 -0
  72. package/dist/commands/canvas-analytics/view.js +1 -0
  73. package/dist/commands/canvas-analytics.d.ts +2 -0
  74. package/dist/commands/canvas-analytics.js +1 -0
  75. package/dist/commands/canvas-prune.js +1 -1
  76. package/dist/commands/canvas.js +1 -1
  77. package/dist/commands/cron.js +5 -5
  78. package/dist/commands/human/components.d.ts +2 -0
  79. package/dist/commands/human/components.js +2 -2
  80. package/dist/commands/human/prompts.js +1 -1
  81. package/dist/commands/human/queue.js +1 -1
  82. package/dist/commands/memory/client.d.ts +11 -0
  83. package/dist/commands/memory/client.js +1 -0
  84. package/dist/commands/memory/delete.js +1 -1
  85. package/dist/commands/memory/edit.js +3 -3
  86. package/dist/commands/memory/find.js +1 -1
  87. package/dist/commands/memory/history.js +4 -4
  88. package/dist/commands/memory/lint.js +1 -1
  89. package/dist/commands/memory/list.d.ts +0 -2
  90. package/dist/commands/memory/list.js +1 -1
  91. package/dist/commands/memory/move.js +1 -1
  92. package/dist/commands/memory/origin.js +1 -1
  93. package/dist/commands/memory/read.d.ts +0 -5
  94. package/dist/commands/memory/read.js +3 -3
  95. package/dist/commands/memory/shared.d.ts +0 -178
  96. package/dist/commands/memory/shared.js +1 -12
  97. package/dist/commands/memory/write.js +5 -5
  98. package/dist/commands/node/bash.js +5 -5
  99. package/dist/commands/node/create.d.ts +0 -17
  100. package/dist/commands/node/create.js +2 -3
  101. package/dist/commands/node/inspect.js +6 -6
  102. package/dist/commands/node/lifecycle.js +2 -2
  103. package/dist/commands/node-context.js +2 -2
  104. package/dist/commands/node-inspect-artifacts.js +6 -6
  105. package/dist/commands/pkg/browse/catalog.js +1 -1
  106. package/dist/commands/pkg/browse/model.d.ts +1 -1
  107. package/dist/commands/pkg/market-manage.js +1 -1
  108. package/dist/commands/pkg/plugin-manage.js +10 -10
  109. package/dist/commands/profile/daemon-profiles.d.ts +13 -0
  110. package/dist/commands/profile/daemon-profiles.js +4 -0
  111. package/dist/commands/profile/delete.js +1 -1
  112. package/dist/commands/profile/env.d.ts +6 -0
  113. package/dist/commands/profile/env.js +2 -2
  114. package/dist/commands/profile/kind.js +1 -2
  115. package/dist/commands/profile/list.js +1 -1
  116. package/dist/commands/profile/meta.js +1 -1
  117. package/dist/commands/profile/new.js +1 -1
  118. package/dist/commands/profile/pause.js +1 -1
  119. package/dist/commands/profile/project.js +1 -1
  120. package/dist/commands/profile/rename.js +1 -1
  121. package/dist/commands/profile/show.js +1 -1
  122. package/dist/commands/profile.js +1 -1
  123. package/dist/commands/push.js +3 -3
  124. package/dist/commands/surface-inspect.js +1 -1
  125. package/dist/commands/sys/branch.js +1 -1
  126. package/dist/commands/sys/config.js +1 -1
  127. package/dist/commands/sys/connect.js +3 -3
  128. package/dist/commands/sys/context/admin/actions.js +1 -1
  129. package/dist/commands/sys/context/admin/model.d.ts +1 -0
  130. package/dist/commands/sys/context/admin/model.js +1 -1
  131. package/dist/commands/sys/context/admin.js +1 -1
  132. package/dist/commands/sys/context/expose.js +2 -1
  133. package/dist/commands/sys/context/prompt-review.js +2 -2
  134. package/dist/commands/sys/context/resolve.js +7 -7
  135. package/dist/commands/sys/context/sysprompt.js +1 -1
  136. package/dist/commands/sys/join.d.ts +1 -0
  137. package/dist/commands/sys/join.js +1 -0
  138. package/dist/commands/sys/migrate.js +1 -1
  139. package/dist/commands/sys/panels/models-panel.js +1 -1
  140. package/dist/commands/sys/panels/profiles-panel.d.ts +0 -1
  141. package/dist/commands/sys/panels/profiles-panel.js +1 -1
  142. package/dist/commands/sys/provider-login.js +6 -6
  143. package/dist/commands/sys/setup-core.d.ts +1 -1
  144. package/dist/commands/sys/setup-core.js +6 -6
  145. package/dist/commands/sys/setup-settings-runner.js +1 -1
  146. package/dist/commands/sys/setup.js +1 -1
  147. package/dist/commands/sys/spaces.d.ts +1 -0
  148. package/dist/commands/sys/spaces.js +2 -0
  149. package/dist/commands/sys/sync-deps.js +2 -2
  150. package/dist/commands/sys/sync-project-guidance.js +4 -4
  151. package/dist/commands/sys/sync-skills.js +2 -2
  152. package/dist/commands/sys/worktrees.d.ts +1 -0
  153. package/dist/commands/sys/worktrees.js +1 -1
  154. package/dist/commands/sys.js +1 -1
  155. package/dist/core/auth-file.js +2 -2
  156. package/dist/core/bash-job-supervisor.d.ts +6 -0
  157. package/dist/core/bash-job-supervisor.js +4 -0
  158. package/dist/core/bash-jobs.d.ts +13 -6
  159. package/dist/core/bash-jobs.js +8 -7
  160. package/dist/core/broker-client/transport-relay.d.ts +6 -3
  161. package/dist/core/broker-client/transport-relay.js +1 -1
  162. package/dist/core/broker-client/transport-socket.d.ts +6 -1
  163. package/dist/core/broker-client/transport-socket.js +1 -1
  164. package/dist/core/canvas/canvas.d.ts +39 -18
  165. package/dist/core/canvas/canvas.js +21 -20
  166. package/dist/core/canvas/context-strip.d.ts +20 -0
  167. package/dist/core/canvas/context-strip.js +5 -0
  168. package/dist/core/canvas/crons.d.ts +12 -20
  169. package/dist/core/canvas/crons.js +15 -13
  170. package/dist/core/canvas/db.js +2 -2
  171. package/dist/core/canvas/deliveries.d.ts +4 -1
  172. package/dist/core/canvas/deliveries.js +1 -1
  173. package/dist/core/canvas/executions.js +1 -1
  174. package/dist/core/canvas/history.d.ts +2 -1
  175. package/dist/core/canvas/history.js +17 -18
  176. package/dist/core/canvas/memory-reads.d.ts +19 -0
  177. package/dist/core/canvas/memory-reads.js +1 -0
  178. package/dist/core/canvas/migrations.d.ts +0 -4
  179. package/dist/core/canvas/migrations.js +99 -32
  180. package/dist/core/canvas/nav-render.js +1 -1
  181. package/dist/core/canvas/node-agent-paths.d.ts +8 -0
  182. package/dist/core/canvas/node-agent-paths.js +1 -0
  183. package/dist/core/canvas/node-recap.d.ts +2 -2
  184. package/dist/core/canvas/node-recap.js +2 -2
  185. package/dist/core/canvas/node-tokens.d.ts +24 -0
  186. package/dist/core/canvas/node-tokens.js +5 -0
  187. package/dist/core/canvas/paths.d.ts +16 -19
  188. package/dist/core/canvas/paths.js +1 -1
  189. package/dist/core/canvas/render-source.d.ts +2 -2
  190. package/dist/core/canvas/render-source.js +6 -9
  191. package/dist/core/canvas/sessions.d.ts +18 -0
  192. package/dist/core/canvas/sessions.js +4 -1
  193. package/dist/core/canvas/types.d.ts +22 -6
  194. package/dist/core/command-hooks/compose.js +1 -1
  195. package/dist/core/command-hooks/discovery.d.ts +15 -1
  196. package/dist/core/command-hooks/discovery.js +1 -1
  197. package/dist/core/command-hooks/help.d.ts +2 -2
  198. package/dist/core/command-hooks/lifecycle-create.d.ts +1 -1
  199. package/dist/core/command-hooks/lifecycle-create.js +1 -1
  200. package/dist/core/command-hooks/transport/exec-invoke.d.ts +2 -0
  201. package/dist/core/command-hooks/transport/exec-invoke.js +1 -1
  202. package/dist/core/command-hooks/transport/exec-lifecycle.d.ts +1 -0
  203. package/dist/core/command-hooks/transport/exec-lifecycle.js +1 -1
  204. package/dist/core/command-hooks/transport/plan.d.ts +3 -0
  205. package/dist/core/command-hooks/transport/plan.js +1 -0
  206. package/dist/core/command-plugins/discovery.js +1 -1
  207. package/dist/core/command-plugins/transport/http-invoke.js +2 -2
  208. package/dist/core/command.d.ts +6 -2
  209. package/dist/core/command.js +6 -6
  210. package/dist/core/config.d.ts +8 -5
  211. package/dist/core/config.js +1 -1
  212. package/dist/core/conversation-store/client-worker.d.ts +1 -0
  213. package/dist/core/conversation-store/client-worker.js +1 -0
  214. package/dist/core/conversation-store/client.d.ts +2 -0
  215. package/dist/core/conversation-store/client.js +2 -0
  216. package/dist/core/conversation-store/file-store.d.ts +37 -0
  217. package/dist/core/conversation-store/file-store.js +9 -0
  218. package/dist/core/conversation-store/index.d.ts +50 -0
  219. package/dist/core/conversation-store/index.js +1 -0
  220. package/dist/core/conversation-store/listener.d.ts +4 -0
  221. package/dist/core/conversation-store/listener.js +3 -0
  222. package/dist/core/conversation-store/patch.d.ts +1 -0
  223. package/dist/core/conversation-store/patch.js +1 -0
  224. package/dist/core/directory/join.d.ts +27 -0
  225. package/dist/core/directory/join.js +1 -0
  226. package/dist/core/disk-usage.d.ts +4 -0
  227. package/dist/core/disk-usage.js +1 -0
  228. package/dist/core/events/emit.d.ts +2 -0
  229. package/dist/core/events/emit.js +3 -1
  230. package/dist/core/feed/feed.js +4 -4
  231. package/dist/core/feed/messages.d.ts +3 -0
  232. package/dist/core/feed/messages.js +6 -6
  233. package/dist/core/fs-utils.d.ts +2 -0
  234. package/dist/core/fs-utils.js +3 -3
  235. package/dist/core/grants/local.d.ts +4 -0
  236. package/dist/core/grants/local.js +1 -0
  237. package/dist/core/grants/mirror.d.ts +44 -0
  238. package/dist/core/grants/mirror.js +4 -0
  239. package/dist/core/grants/on-sync.d.ts +22 -0
  240. package/dist/core/grants/on-sync.js +1 -0
  241. package/dist/core/grants/remove.d.ts +7 -0
  242. package/dist/core/grants/remove.js +1 -0
  243. package/dist/core/grants/sandboxes.d.ts +7 -0
  244. package/dist/core/grants/sandboxes.js +1 -0
  245. package/dist/core/grants/sync.d.ts +12 -0
  246. package/dist/core/grants/sync.js +1 -0
  247. package/dist/core/help/memory-extensions.d.ts +3 -0
  248. package/dist/core/help/memory-extensions.js +2 -0
  249. package/dist/core/help.d.ts +14 -0
  250. package/dist/core/help.js +7 -7
  251. package/dist/core/host-exports/builtins.js +3 -3
  252. package/dist/core/host-exports/export.js +3 -3
  253. package/dist/core/human/action-binding.d.ts +2 -0
  254. package/dist/core/human/action-binding.js +1 -1
  255. package/dist/core/human/feedback-companion.d.ts +0 -1
  256. package/dist/core/human/feedback-companion.js +1 -1
  257. package/dist/core/human/page-schema.d.ts +1 -1
  258. package/dist/core/inspector/core.d.ts +2 -0
  259. package/dist/core/inspector/core.js +1 -1
  260. package/dist/core/inspector/tui.js +2 -2
  261. package/dist/core/installed-plugins.js +1 -1
  262. package/dist/core/io.js +6 -6
  263. package/dist/core/keybindings/catalog.d.ts +1 -1
  264. package/dist/core/keybindings/catalog.js +1 -1
  265. package/dist/core/layout-migrate/index.d.ts +15 -0
  266. package/dist/core/layout-migrate/index.js +4 -0
  267. package/dist/core/layout-migrate/paths.d.ts +26 -0
  268. package/dist/core/layout-migrate/paths.js +1 -0
  269. package/dist/core/layout-migrate/stored-paths.d.ts +2 -0
  270. package/dist/core/layout-migrate/stored-paths.js +11 -0
  271. package/dist/core/layout-migrate/stores.d.ts +17 -0
  272. package/dist/core/layout-migrate/stores.js +4 -0
  273. package/dist/core/layout.d.ts +26 -0
  274. package/dist/core/layout.js +2 -0
  275. package/dist/core/llm/run.d.ts +60 -0
  276. package/dist/core/llm/run.js +4 -0
  277. package/dist/core/memory/cli-selector.d.ts +13 -0
  278. package/dist/core/memory/cli-selector.js +1 -0
  279. package/dist/core/memory/history.d.ts +5 -4
  280. package/dist/core/memory/history.js +6 -6
  281. package/dist/core/memory/inline-ref-inventory.d.ts +2 -1
  282. package/dist/core/memory/inline-ref-inventory.js +1 -1
  283. package/dist/core/memory/lint.js +2 -2
  284. package/dist/core/memory/mutation-domain.d.ts +2 -2
  285. package/dist/core/memory/mutation-domain.js +8 -7
  286. package/dist/core/memory/mutations.js +1 -1
  287. package/dist/core/memory/service.d.ts +5 -0
  288. package/dist/core/memory/service.js +2 -2
  289. package/dist/core/memory-resolver.d.ts +11 -7
  290. package/dist/core/memory-resolver.js +2 -2
  291. package/dist/core/model-auth/daemon-login.d.ts +13 -0
  292. package/dist/core/model-auth/daemon-login.js +1 -0
  293. package/dist/core/model-auth/flows.d.ts +45 -0
  294. package/dist/core/model-auth/flows.js +1 -0
  295. package/dist/core/model-auth/handoff-jti.d.ts +4 -0
  296. package/dist/core/model-auth/handoff-jti.js +1 -0
  297. package/dist/core/model-routes.js +1 -1
  298. package/dist/core/nested-stores.d.ts +2 -1
  299. package/dist/core/nested-stores.js +1 -2
  300. package/dist/core/preview-registry.js +2 -2
  301. package/dist/core/profiles/env-store.js +2 -2
  302. package/dist/core/profiles/manifest.d.ts +16 -5
  303. package/dist/core/profiles/manifest.js +1 -1
  304. package/dist/core/provider-management.js +1 -1
  305. package/dist/core/review/birth.js +1 -1
  306. package/dist/core/review/companion.d.ts +0 -2
  307. package/dist/core/review/companion.js +1 -1
  308. package/dist/core/review/fork.js +2 -2
  309. package/dist/core/review/realize.js +1 -1
  310. package/dist/core/review/stage.d.ts +1 -1
  311. package/dist/core/review/stage.js +1 -1
  312. package/dist/core/review/types.d.ts +1 -1
  313. package/dist/core/runs/events.d.ts +34 -0
  314. package/dist/core/runs/events.js +1 -0
  315. package/dist/core/runs/operations.d.ts +43 -0
  316. package/dist/core/runs/operations.js +12 -0
  317. package/dist/core/runtime/bearings-render.d.ts +2 -2
  318. package/dist/core/runtime/bearings-render.js +11 -11
  319. package/dist/core/runtime/bearings.js +2 -2
  320. package/dist/core/runtime/broker/cli-relay.d.ts +5 -0
  321. package/dist/core/runtime/broker/cli-relay.js +1 -0
  322. package/dist/core/runtime/broker/client-registry.d.ts +0 -5
  323. package/dist/core/runtime/broker/client-registry.js +1 -1
  324. package/dist/core/runtime/broker/daemon-ops.d.ts +28 -1
  325. package/dist/core/runtime/broker/daemon-ops.js +1 -1
  326. package/dist/core/runtime/broker/engine-drive.d.ts +0 -2
  327. package/dist/core/runtime/broker/engine-drive.js +1 -1
  328. package/dist/core/runtime/broker/fault-retry.d.ts +9 -0
  329. package/dist/core/runtime/broker/fault-retry.js +1 -1
  330. package/dist/core/runtime/broker/frame-dispatch.d.ts +5 -9
  331. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  332. package/dist/core/runtime/broker/frame-engine-control.d.ts +3 -2
  333. package/dist/core/runtime/broker/frame-engine-control.js +1 -1
  334. package/dist/core/runtime/broker/frame-memory-refs.d.ts +4 -3
  335. package/dist/core/runtime/broker/frame-memory-refs.js +1 -1
  336. package/dist/core/runtime/broker/frame-read.js +1 -1
  337. package/dist/core/runtime/broker/frame-session.js +1 -1
  338. package/dist/core/runtime/broker/held-deferred-inbox.d.ts +3 -1
  339. package/dist/core/runtime/broker/held-deferred-inbox.js +1 -1
  340. package/dist/core/runtime/broker/inbox.d.ts +1 -2
  341. package/dist/core/runtime/broker/inbox.js +7 -10
  342. package/dist/core/runtime/broker/model-adapter.d.ts +9 -0
  343. package/dist/core/runtime/broker/model-adapter.js +2 -0
  344. package/dist/core/runtime/broker/node-token.d.ts +3 -0
  345. package/dist/core/runtime/broker/node-token.js +1 -0
  346. package/dist/core/runtime/broker/read-ops.js +1 -1
  347. package/dist/core/runtime/broker/rebind.d.ts +2 -0
  348. package/dist/core/runtime/broker/rebind.js +1 -1
  349. package/dist/core/runtime/broker/tool-groups.js +1 -1
  350. package/dist/core/runtime/broker/turn-ignition.d.ts +3 -3
  351. package/dist/core/runtime/broker/turn-ignition.js +1 -1
  352. package/dist/core/runtime/broker-cli.js +3 -3
  353. package/dist/core/runtime/broker-extension-render.d.ts +2 -5
  354. package/dist/core/runtime/broker-extension-render.js +4 -4
  355. package/dist/core/runtime/broker-persona-guidance.js +3 -3
  356. package/dist/core/runtime/broker-protocol.d.ts +7 -8
  357. package/dist/core/runtime/broker.js +1 -1
  358. package/dist/core/runtime/canvas-extensions.d.ts +1 -0
  359. package/dist/core/runtime/canvas-extensions.js +1 -1
  360. package/dist/core/runtime/close.d.ts +9 -0
  361. package/dist/core/runtime/close.js +1 -1
  362. package/dist/core/runtime/deliver-live.js +1 -1
  363. package/dist/core/runtime/fleet.d.ts +1 -1
  364. package/dist/core/runtime/front-door-login.js +1 -1
  365. package/dist/core/runtime/front-door.js +2 -2
  366. package/dist/core/runtime/headless-pi.d.ts +1 -1
  367. package/dist/core/runtime/headless-pi.js +1 -1
  368. package/dist/core/runtime/host.d.ts +1 -1
  369. package/dist/core/runtime/host.js +3 -1
  370. package/dist/core/runtime/invocation.d.ts +3 -0
  371. package/dist/core/runtime/kickoff.d.ts +1 -0
  372. package/dist/core/runtime/kickoff.js +16 -16
  373. package/dist/core/runtime/launch-target.d.ts +1 -1
  374. package/dist/core/runtime/launch-target.js +1 -1
  375. package/dist/core/runtime/launch.d.ts +10 -35
  376. package/dist/core/runtime/launch.js +1 -1
  377. package/dist/core/runtime/lifecycle.js +2 -2
  378. package/dist/core/runtime/memory.d.ts +1 -1
  379. package/dist/core/runtime/memory.js +1 -1
  380. package/dist/core/runtime/model-registry.js +1 -1
  381. package/dist/core/runtime/model-swap.d.ts +17 -19
  382. package/dist/core/runtime/model-swap.js +1 -1
  383. package/dist/core/runtime/node-read.js +3 -2
  384. package/dist/core/runtime/nodes.d.ts +7 -0
  385. package/dist/core/runtime/nodes.js +1 -1
  386. package/dist/core/runtime/outcome-document.js +1 -1
  387. package/dist/core/runtime/package-health.js +2 -2
  388. package/dist/core/runtime/persona.js +2 -2
  389. package/dist/core/runtime/pi-vendored.js +1 -1
  390. package/dist/core/runtime/placement-tmux.d.ts +1 -1
  391. package/dist/core/runtime/placement-tmux.js +1 -1
  392. package/dist/core/runtime/placement.js +1 -1
  393. package/dist/core/runtime/promote.js +1 -1
  394. package/dist/core/runtime/provider-credential-gate.js +2 -2
  395. package/dist/core/runtime/recovery-hold.d.ts +2 -0
  396. package/dist/core/runtime/recovery-hold.js +1 -0
  397. package/dist/core/runtime/recycle.js +1 -1
  398. package/dist/core/runtime/reopen.js +1 -1
  399. package/dist/core/runtime/reset.js +1 -1
  400. package/dist/core/runtime/revive.d.ts +1 -1
  401. package/dist/core/runtime/revive.js +2 -3
  402. package/dist/core/runtime/roadmap.js +4 -4
  403. package/dist/core/runtime/run-command.d.ts +6 -0
  404. package/dist/core/runtime/run-command.js +1 -1
  405. package/dist/core/runtime/session-branch.d.ts +2 -8
  406. package/dist/core/runtime/session-branch.js +1 -1
  407. package/dist/core/runtime/session-list-cache.d.ts +6 -22
  408. package/dist/core/runtime/session-list-cache.js +1 -1
  409. package/dist/core/runtime/situational-context.js +2 -2
  410. package/dist/core/runtime/spawn-env.d.ts +6 -6
  411. package/dist/core/runtime/spawn-env.js +1 -1
  412. package/dist/core/runtime/spawn.d.ts +5 -0
  413. package/dist/core/runtime/spawn.js +2 -2
  414. package/dist/core/runtime/stop-guard.js +2 -2
  415. package/dist/core/runtime/stop-signals.d.ts +2 -2
  416. package/dist/core/runtime/stop-signals.js +1 -1
  417. package/dist/core/runtime/structured-output.d.ts +10 -4
  418. package/dist/core/runtime/structured-output.js +4 -4
  419. package/dist/core/runtime/tmux-bindings.js +3 -3
  420. package/dist/core/runtime/tmux-driver.d.ts +4 -0
  421. package/dist/core/runtime/tmux-driver.js +7 -7
  422. package/dist/core/runtime/view-socket.d.ts +9 -2
  423. package/dist/core/runtime/view-socket.js +1 -1
  424. package/dist/core/runtime/warm-pool.js +1 -1
  425. package/dist/core/scope.d.ts +3 -2
  426. package/dist/core/scope.js +1 -1
  427. package/dist/core/scoped-state/db.js +1 -1
  428. package/dist/core/scoped-state/migrate.js +3 -3
  429. package/dist/core/scoped-state/profiles.d.ts +2 -1
  430. package/dist/core/scoped-state/profiles.js +1 -1
  431. package/dist/core/scoped-state/schema.d.ts +2 -1
  432. package/dist/core/scoped-state/schema.js +4 -4
  433. package/dist/core/scopes.d.ts +2 -2
  434. package/dist/core/scopes.js +1 -1
  435. package/dist/core/secrets.d.ts +1 -0
  436. package/dist/core/secrets.js +2 -2
  437. package/dist/core/spaces/mounts.d.ts +32 -0
  438. package/dist/core/spaces/mounts.js +1 -0
  439. package/dist/core/spaces/open-beneath.d.ts +71 -0
  440. package/dist/core/spaces/open-beneath.js +1 -0
  441. package/dist/core/spaces/permissions.d.ts +46 -0
  442. package/dist/core/spaces/permissions.js +1 -0
  443. package/dist/core/spaces/process.d.ts +27 -0
  444. package/dist/core/spaces/process.js +1 -0
  445. package/dist/core/spaces/space.d.ts +8 -0
  446. package/dist/core/spaces/space.js +2 -0
  447. package/dist/core/spaces/stop.d.ts +8 -0
  448. package/dist/core/spaces/stop.js +2 -0
  449. package/dist/core/spaces/users.d.ts +19 -0
  450. package/dist/core/spaces/users.js +1 -0
  451. package/dist/core/subscription-state.d.ts +2 -0
  452. package/dist/core/subscription-state.js +3 -3
  453. package/dist/core/substrate/frontmatter-validation.js +1 -1
  454. package/dist/core/substrate/injected-store.d.ts +28 -3
  455. package/dist/core/substrate/injected-store.js +2 -1
  456. package/dist/core/substrate/listings.js +1 -1
  457. package/dist/core/substrate/memory-events.d.ts +6 -0
  458. package/dist/core/substrate/memory-events.js +1 -0
  459. package/dist/core/substrate/on-read-node.js +1 -1
  460. package/dist/core/substrate/on-read.d.ts +6 -6
  461. package/dist/core/substrate/on-read.js +5 -5
  462. package/dist/core/substrate/plan.js +1 -1
  463. package/dist/core/substrate/render-node.js +1 -1
  464. package/dist/core/substrate/render.d.ts +4 -3
  465. package/dist/core/substrate/render.js +38 -38
  466. package/dist/core/substrate/schema.d.ts +6 -0
  467. package/dist/core/substrate/schema.js +1 -1
  468. package/dist/core/tui/panel.js +1 -1
  469. package/dist/core/user-settings.d.ts +12 -0
  470. package/dist/core/user-settings.js +1 -1
  471. package/dist/core/worktree-mutation-async.js +5 -5
  472. package/dist/core/worktree-quarantine.js +1 -1
  473. package/dist/core/worktree-remove.d.ts +15 -0
  474. package/dist/core/worktree-remove.js +1 -0
  475. package/dist/core/worktree-sweep.js +6 -6
  476. package/dist/daemon/analytics/compute.d.ts +37 -0
  477. package/dist/daemon/analytics/compute.js +1 -0
  478. package/dist/daemon/analytics/scan-worker.d.ts +1 -0
  479. package/dist/daemon/analytics/scan-worker.js +2 -0
  480. package/dist/daemon/analytics/scan.d.ts +37 -0
  481. package/dist/daemon/analytics/scan.js +1 -0
  482. package/dist/daemon/api/app-listener.d.ts +11 -0
  483. package/dist/daemon/api/app-listener.js +21 -0
  484. package/dist/daemon/api/bridge.js +5 -5
  485. package/dist/daemon/api/handlers/analytics.d.ts +2 -0
  486. package/dist/daemon/api/handlers/analytics.js +1 -0
  487. package/dist/daemon/api/handlers/attach.js +1 -1
  488. package/dist/daemon/api/handlers/bash-jobs.js +2 -2
  489. package/dist/daemon/api/handlers/bash.js +1 -1
  490. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  491. package/dist/daemon/api/handlers/canvas.d.ts +1 -1
  492. package/dist/daemon/api/handlers/canvas.js +6 -6
  493. package/dist/daemon/api/handlers/crons.js +1 -1
  494. package/dist/daemon/api/handlers/files.d.ts +1 -1
  495. package/dist/daemon/api/handlers/files.js +1 -1
  496. package/dist/daemon/api/handlers/health.js +2 -2
  497. package/dist/daemon/api/handlers/hook-exec.d.ts +2 -0
  498. package/dist/daemon/api/handlers/hook-exec.js +1 -0
  499. package/dist/daemon/api/handlers/human-requests.js +1 -1
  500. package/dist/daemon/api/handlers/inbox.js +1 -1
  501. package/dist/daemon/api/handlers/llm.d.ts +2 -0
  502. package/dist/daemon/api/handlers/llm.js +3 -0
  503. package/dist/daemon/api/handlers/memory-reads.d.ts +4 -0
  504. package/dist/daemon/api/handlers/memory-reads.js +1 -0
  505. package/dist/daemon/api/handlers/memory.js +5 -1
  506. package/dist/daemon/api/handlers/messages.js +2 -2
  507. package/dist/daemon/api/handlers/modelauth.js +1 -1
  508. package/dist/daemon/api/handlers/node-outcomes.js +1 -1
  509. package/dist/daemon/api/handlers/node-records.d.ts +2 -0
  510. package/dist/daemon/api/handlers/node-records.js +3 -0
  511. package/dist/daemon/api/handlers/nodes.d.ts +1 -1
  512. package/dist/daemon/api/handlers/nodes.js +1 -1
  513. package/dist/daemon/api/handlers/profiles.d.ts +4 -1
  514. package/dist/daemon/api/handlers/profiles.js +1 -1
  515. package/dist/daemon/api/handlers/reports.js +5 -3
  516. package/dist/daemon/api/handlers/reviews.d.ts +1 -1
  517. package/dist/daemon/api/handlers/reviews.js +1 -1
  518. package/dist/daemon/api/handlers/run-routes.d.ts +2 -0
  519. package/dist/daemon/api/handlers/run-routes.js +1 -0
  520. package/dist/daemon/api/handlers/runs.d.ts +9 -0
  521. package/dist/daemon/api/handlers/runs.js +1 -0
  522. package/dist/daemon/api/handlers/subscriptions.js +1 -1
  523. package/dist/daemon/api/handlers/worktree.js +1 -1
  524. package/dist/daemon/api/map.d.ts +10 -4
  525. package/dist/daemon/api/map.js +2 -2
  526. package/dist/daemon/api/operations.d.ts +18 -0
  527. package/dist/daemon/api/operations.js +1 -0
  528. package/dist/daemon/api/principal.d.ts +42 -0
  529. package/dist/daemon/api/principal.js +1 -0
  530. package/dist/daemon/api/router.d.ts +27 -3
  531. package/dist/daemon/api/router.js +1 -1
  532. package/dist/daemon/api/server.d.ts +4 -0
  533. package/dist/daemon/api/server.js +1 -1
  534. package/dist/daemon/api/vendor-signin.d.ts +7 -0
  535. package/dist/daemon/api/vendor-signin.js +77 -0
  536. package/dist/daemon/api/viewer-presence.d.ts +3 -0
  537. package/dist/daemon/api/viewer-presence.js +1 -0
  538. package/dist/daemon/cron/armed-context.d.ts +4 -0
  539. package/dist/daemon/cron/armed-context.js +1 -1
  540. package/dist/daemon/cron/escalation.js +3 -3
  541. package/dist/daemon/cron/lease-recovery.js +1 -1
  542. package/dist/daemon/cron/sinks.js +2 -2
  543. package/dist/daemon/cron-run.d.ts +5 -5
  544. package/dist/daemon/cron-run.js +1 -1
  545. package/dist/daemon/crtrd-cli.js +1 -1
  546. package/dist/daemon/crtrd.js +8 -7
  547. package/dist/daemon/delivery/run-delivery.d.ts +4 -0
  548. package/dist/daemon/delivery/run-delivery.js +1 -1
  549. package/dist/daemon/fleet.d.ts +1 -1
  550. package/dist/daemon/fleet.js +6 -6
  551. package/dist/daemon/http-dispatcher.d.ts +1 -0
  552. package/dist/daemon/http-dispatcher.js +1 -0
  553. package/dist/daemon/human/finish.js +7 -7
  554. package/dist/daemon/joined-owner.d.ts +5 -0
  555. package/dist/daemon/joined-owner.js +1 -0
  556. package/dist/daemon/manage.js +2 -2
  557. package/dist/daemon/messaging/node-message.js +1 -1
  558. package/dist/daemon/park-activity.js +1 -1
  559. package/dist/daemon/reconcilers/bash-deadline.js +1 -1
  560. package/dist/daemon/reconcilers/broker-supervision.d.ts +1 -1
  561. package/dist/daemon/reconcilers/broker-supervision.js +4 -4
  562. package/dist/daemon/reconcilers/delivery-lane.js +1 -1
  563. package/dist/daemon/reconcilers/live-obligation.d.ts +7 -0
  564. package/dist/daemon/reconcilers/live-obligation.js +1 -1
  565. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  566. package/dist/daemon/reconcilers/storage-maintenance.d.ts +20 -1
  567. package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
  568. package/dist/daemon/runs/append-section.d.ts +6 -0
  569. package/dist/daemon/runs/append-section.js +2 -0
  570. package/dist/daemon/runs/observer.d.ts +5 -0
  571. package/dist/daemon/runs/observer.js +4 -0
  572. package/dist/launcher/bwrap.d.ts +4 -0
  573. package/dist/launcher/bwrap.js +2 -0
  574. package/dist/launcher/client.d.ts +2 -0
  575. package/dist/launcher/client.js +3 -0
  576. package/dist/launcher/main.d.ts +1 -0
  577. package/dist/launcher/main.js +3 -0
  578. package/dist/launcher/netrule.d.ts +1 -0
  579. package/dist/launcher/netrule.js +1 -0
  580. package/dist/launcher/seccomp.d.ts +1 -0
  581. package/dist/launcher/seccomp.js +1 -0
  582. package/dist/launcher/spec.d.ts +88 -0
  583. package/dist/launcher/spec.js +1 -0
  584. package/dist/launcher/users.d.ts +18 -0
  585. package/dist/launcher/users.js +7 -0
  586. package/dist/launcher/validate.d.ts +22 -0
  587. package/dist/launcher/validate.js +1 -0
  588. package/dist/migrations/corpus.js +3 -3
  589. package/dist/migrations/runner.js +1 -1
  590. package/dist/native/linux/addon.node +0 -0
  591. package/dist/native/linux.d.ts +29 -0
  592. package/dist/native/linux.js +1 -0
  593. package/dist/pi-extensions/broker-local.js +2 -2
  594. package/dist/pi-extensions/canvas-bash-valve.d.ts +1 -3
  595. package/dist/pi-extensions/canvas-bash-valve.js +4 -7
  596. package/dist/pi-extensions/canvas-context-intro.d.ts +1 -2
  597. package/dist/pi-extensions/canvas-context-intro.js +2 -2
  598. package/dist/pi-extensions/canvas-doc-substrate.js +6 -6
  599. package/dist/pi-extensions/canvas-inbox-watcher.d.ts +2 -1
  600. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -1
  601. package/dist/pi-extensions/canvas-passive-context.d.ts +1 -1
  602. package/dist/pi-extensions/canvas-passive-context.js +11 -11
  603. package/dist/pi-extensions/canvas-recap.js +6 -6
  604. package/dist/pi-extensions/canvas-stophook.js +1 -1
  605. package/dist/pi-extensions/canvas-structured-output.js +4 -4
  606. package/dist/pi-extensions/canvas-tool-guide.js +1 -1
  607. package/dist/pi-extensions/system-prompt-entry.d.ts +15 -0
  608. package/dist/pi-extensions/system-prompt-entry.js +1 -0
  609. package/dist/shared/env.d.ts +5 -1
  610. package/dist/shared/env.js +1 -1
  611. package/dist/shared/strip-cd-prefix.d.ts +1 -0
  612. package/dist/shared/strip-cd-prefix.js +1 -0
  613. package/dist/types.d.ts +31 -15
  614. package/docs/cli/memory-and-preferences.md +3 -1
  615. package/docs/sdk/client.md +34 -0
  616. package/docs/sdk/errors.md +2 -0
  617. package/docs/sdk/memory.md +2 -2
  618. package/docs/sdk/streaming.md +21 -0
  619. package/package.json +19 -4
  620. package/packages/crouter-identity/dist/index.d.ts +54 -0
  621. package/packages/crouter-identity/dist/index.js +166 -0
  622. package/packages/crouter-identity/package.json +33 -0
  623. package/runtime.lock.json +44 -8
  624. package/scripts/build-native-linux.mjs +16 -0
  625. package/scripts/install-runtime.mjs +9 -7
  626. package/scripts/lib/isolation-env.mjs +42 -0
  627. package/scripts/runtime-smoke.mjs +49 -0
  628. package/src/native/linux/addon.c +249 -0
  629. package/dist/core/profiles/state-block.d.ts +0 -4
  630. package/dist/core/profiles/state-block.js +0 -3
  631. package/dist/core/runtime/broker/auth-reload.d.ts +0 -41
  632. package/dist/core/runtime/broker/auth-reload.js +0 -1
  633. package/dist/core/substrate/cli-context-delivery.d.ts +0 -22
  634. package/dist/core/substrate/cli-context-delivery.js +0 -1
@@ -1,2 +1,2 @@
1
- var D=Object.defineProperty;var c=(e,r)=>D(e,"name",{value:r,configurable:!0});import{readText as P}from"../fs-utils.js";import{notFound as v,usage as d}from"../errors.js";import{interpolateNodePaths as L}from"../canvas/paths.js";import{loadMemoryStoreView as q,loadMemoryTargetView as w,memoryStoresInPrecedence as M}from"../memory-resolver.js";import{canonicalSegments as x,stripNamespace as k,validateExplicitLocalName as j}from"./identity.js";import{memoryExtensionEffectiveCatalog as F,projectEffectiveMemoryExtensions as E}from"./extensions.js";import{historyLogPathForDoc as I,readHistoryRecords as K,resolveDeletedHistoryLogPath as T,summarizeChange as A,unifiedDiff as B}from"./history.js";import{docsByName as b,isDirName as $}from"../substrate/listings.js";import{parseSubstrateDoc as _}from"../substrate/schema.js";import{createDoc as le,deleteDoc as de,moveDoc as he,updateDoc as ue}from"./mutations.js";function H(e,r){return{winner:e===r,scope:e.scope,store_root:e.root,physical_relative_path:e.physicalRelativePath,path:e.path}}c(H,"candidateLocation");function y(e){if(e.scope!=="project"||e.mountStatus==="ready")return e;const r=e.ownerDir??e.storeRoot;if(e.mountStatus==="absent")throw d(`no memory store at ${e.storeRoot}`,{next:`Initialize it with \`crtr memory write <namespace> --dir ${r}\`, which declares the repository namespace.`});const a=e.repositoryRoot??r;throw d(e.diagnostic??`project memory store at ${e.storeRoot} does not declare a namespace`,{next:`Run \`crtr sys migrate --dir ${a}\`.`})}c(y,"requireMountedStore");function N(e){const r=x(e.trim()).join("/");if(r==="")throw d("memory document name required");const a=j(r);if(!a.ok)throw d(`invalid memory document name \`${e}\`: ${a.reason}`,{received:e,next:"Pass the full canonical name (a project document is <namespace>/<local name>); run `crtr memory find <leaf>` to look one up."});return r}c(N,"requireCanonicalName");function V(e,r){y(e);const a=N(r);if(e.namespace==="")return a;const s=k(a,e.namespace);if(s===null)throw d(`\`${a}\` is not in the namespace of the store at ${e.storeRoot} (\`${e.namespace}\`)`,{memory:a,next:`Every document there answers at \`${e.namespace}/<local name>\`; the store's own document answers at \`${e.namespace}\`.`});return s}c(V,"requireLocalNameInStore");function z(e){return e==="node"?-1:e==="project"?0:e==="profile"?1:e==="user"?2:3}c(z,"memoryScopeRank");function g(e){return e.store!=null?q(y(e.store),!0):w(e.target,{...e.scope===void 0?{}:{scope:e.scope},includeDescendants:!0,quiet:!0,reportDiscovery:!1})}c(g,"selectedView");function R(e){return g(e).docs}c(R,"selectedDocs");function S(e){return`${String(z(e.scope)+10).padStart(2,"0")}:${e.kind}:${e.name}:${e.physicalRelativePath}`}c(S,"memoryListKey");function O(e,r){const[a,s,i,...o]=e.split(":"),[n,t,m,...h]=r.split(":"),l=Number(a)-Number(n);if(l!==0)return l;const f=s.localeCompare(t);if(f!==0)return f;const u=i.localeCompare(m);return u!==0?u:o.join(":").localeCompare(h.join(":"))}c(O,"compareMemoryListKeys");function re(e){const r=R(e),a=e.store==null,s=new Map;for(const n of r){const t=s.get(n.name);t!==void 0?t.push(n):s.set(n.name,[n])}const i=new Set,o=[];for(const n of r){const t=_(n);if(!(t===null||e.kind!==void 0&&t.kind!==e.kind)){if(a){if(i.has(t.name))continue;i.add(t.name)}o.push({name:t.name,kind:t.kind,scope:t.scope,path:t.path,storeRoot:n.root,physicalRelativePath:n.physicalRelativePath,shortForm:t.shortForm,slash:t.slash,extensions:E(n.frontmatter?.extensions,F(n)),candidates:s.get(n.name)??[n]})}}return o.sort((n,t)=>O(S(n),S(t))),o}c(re,"listDocs");function U(e){const r=R(e),a=e.store==null,s=new Map;for(const n of r){const t=s.get(n.name);t!==void 0?t.push(n):s.set(n.name,[n])}const i=new Set,o=[];for(const n of r){const t=_(n);if(!(t===null||e.kind!==void 0&&t.kind!==e.kind)){if(a){if(i.has(t.name))continue;i.add(t.name)}o.push({name:t.name,localName:n.localName,kind:t.kind,scope:t.scope,path:t.path,store_root:n.root,physical_relative_path:n.physicalRelativePath,routing:t.whenAndWhyToRead,shortForm:t.shortForm,candidates:s.get(n.name)??[n],body:t.body})}}return o}c(U,"searchUnits");function C(e){return{path:e.path,store_root:e.store_root,physical_relative_path:e.physical_relative_path,...e.candidates.length>1?{candidates:e.candidates.map(r=>H(r,e.candidates[0]))}:{}}}c(C,"searchPath");function ae(e){if(e.grep===!0&&e.body===!0)throw d("--grep and --body are mutually exclusive (--grep always scans bodies).");if(e.grep===!0&&e.minScore!==void 0)throw d("--min-score is only available in ranked mode.");if(e.minScore!==void 0&&e.minScore<1)throw d("--min-score must be at least 1.");const r=U(e);if(e.grep===!0){let o;try{o=new RegExp(e.query)}catch{throw d(`invalid regex pattern: ${e.query}`)}const n=[];for(const t of r)t.body.split(`
2
- `).forEach((m,h)=>{o.test(m)&&n.push({name:t.name,scope:t.scope,line:h+1,text:m,...C(t)})});return n.sort((t,m)=>{const h=t.name.localeCompare(m.name);if(h!==0)return h;const l=t.scope.localeCompare(m.scope);if(l!==0)return l;const f=t.physical_relative_path.localeCompare(m.physical_relative_path);return f!==0?f:t.line-m.line}),{mode:"grep",matches:n.length,hits:n}}const a=e.query.toLowerCase().split(/\s+/).filter(o=>o.length>0);if(a.length===0)throw d("query must contain at least one non-whitespace term");const s=[];for(const o of r){const n=o.name.toLowerCase(),t=o.localName.toLowerCase(),m=o.physical_relative_path.toLowerCase(),h=o.routing.toLowerCase(),l=o.shortForm.toLowerCase(),f=e.body===!0?o.body.toLowerCase():null;let u=0;for(const p of a)(n.includes(p)||t.includes(p)||m.includes(p))&&(u+=10),h.includes(p)&&(u+=5),l.includes(p)&&(u+=3),f!==null&&f.includes(p)&&(u+=1);u>0&&s.push({unit:o,score:u})}s.sort((o,n)=>{if(n.score!==o.score)return n.score-o.score;const t=o.unit.scope.localeCompare(n.unit.scope);if(t!==0)return t;const m=o.unit.name.localeCompare(n.unit.name);return m!==0?m:o.unit.physical_relative_path.localeCompare(n.unit.physical_relative_path)});const i=e.minScore??(s.length===0?1:Math.max(1,Math.ceil(s[0].score/2)));return{mode:"ranked",matches:s.length,hits:s.filter(o=>o.score>=i).map(({unit:o,score:n})=>({name:o.name,kind:o.kind,scope:o.scope,score:n,short_form:o.shortForm,...C(o)}))}}c(ae,"searchDocs");function se(e){const r=g(e),a=e.kind===void 0?{}:{kind:e.kind},s=r.candidates(e.name,a),i=b(r.docs);if(s===null){const l=x(e.name.trim()).join("/");if(l!==""&&$(i,l))return{kind:"directory",name:l,listingByName:i};r.resolve(e.name,a)}const o=s,n=e.store==null?i:b([...r.docs,...w(e.target,{includeDescendants:!0,quiet:!0,reportDiscovery:!1}).docs]),t=e.frontmatter===!0?P(o.winner.path):o.winner.body,m=e.interpolateNodePaths===!1||e.target.nodeId===null?t:L(t,e.target.nodeId),h=[...o.winner.body.matchAll(/\[\[([^\]]+)\]\]/g)].map(l=>l[1].trim()).filter(l=>n.has(l)||$(n,l));return{kind:"document",doc:o.winner,candidates:o.candidates,content:m,links:h,listingByName:i}}c(se,"readDoc");function W(e){const a=g(e).candidates(e.name);if(a!==null){const o=a.winner;if(o.plugin!==void 0)throw d(`${o.name} belongs to the installed plugin "${o.plugin}" \u2014 a read-only corpus with no revision history.`,{memory:o.name,plugin:o.plugin});if(o.scope==="builtin")throw d(`${o.name} is a builtin document shipped with the package \u2014 a read-only corpus with no revision history.`,{memory:o.name,scope:"builtin"});return{name:o.name,scope:o.scope,logPath:I(o)}}const s=N(e.name),i=e.store!=null?[y(e.store)]:M(e.target,e.scope,!0,!1).filter(o=>o.mountStatus==="ready"&&o.scope!=="builtin"&&o.plugin===void 0);for(const o of i){if(o.namespace!==""&&k(s,o.namespace)===null)continue;const n=V(o,s),t=T(o.storeRoot,n);if(t!==null)return{name:s,scope:o.scope,logPath:t.logPath,deleted:t}}throw v(`no memory document or revision history found: ${e.name}`,{memory:e.name,next:"Run `crtr memory find <query>` to locate the document. A document that exists but has no history predates this surface or has never been mutated through it."})}c(W,"historyLocation");function ie(e){const r=W(e),a=K(r.logPath);if(a.length===0)throw v(`no revision history recorded for ${r.name}`,{memory:r.name,next:"The document predates this surface or has never been mutated through `crtr memory write`/`edit`/`delete`. Its first edit records the pre-existing content in full."});if(e.revision!==void 0){if(e.revision<1||e.revision>a.length)throw d(`revision ${e.revision} is out of range for ${r.name} (1..${a.length})`,{memory:r.name,next:`Run \`crtr memory history ${r.name}\` to see which revisions exist.`});return{...r,total:a.length,record:{revision:e.revision,...a[e.revision-1]}}}const s=a.map((i,o)=>{const n=A(i.before,i.after);return{revision:o+1,op:i.op,at:i.at,...i.node===void 0?{}:{node:i.node},...i.rationale===void 0?{}:{rationale:i.rationale},...i.verbatim===!0?{verbatim:!0}:{},...n,...e.diff===!0?{diff:B(i.before,i.after)}:{}}}).reverse().slice(0,Math.max(0,e.limit));return{...r,total:a.length,revisions:s}}c(ie,"readHistory");export{H as candidateLocation,O as compareMemoryListKeys,le as createDoc,de as deleteDoc,re as listDocs,S as memoryListKey,z as memoryScopeRank,he as moveDoc,se as readDoc,ie as readHistory,N as requireCanonicalName,V as requireLocalNameInStore,y as requireMountedStore,ae as searchDocs,ue as updateDoc};
1
+ var P=Object.defineProperty;var l=(e,n)=>P(e,"name",{value:n,configurable:!0});import{readFileBeneath as v}from"../spaces/open-beneath.js";import{notFound as w,usage as d}from"../errors.js";import{interpolateNodePaths as L}from"../canvas/paths.js";import{loadMemoryStoreView as q,loadMemoryTargetView as x,memoryStoresInPrecedence as M}from"../memory-resolver.js";import{canonicalSegments as k,stripNamespace as b,validateExplicitLocalName as F}from"./identity.js";import{memoryExtensionEffectiveCatalog as j,projectEffectiveMemoryExtensions as E}from"./extensions.js";import{historyLogPathForDoc as I,readHistoryRecords as B,resolveDeletedHistoryLogPath as K,summarizeChange as z,unifiedDiff as A}from"./history.js";import{docsByName as $,isDirName as S}from"../substrate/listings.js";import{effectivePrivacy as H,parseSubstrateDoc as _}from"../substrate/schema.js";import{literalBodySegment as T,serializeMemoryDocLiteral as V}from"./mutation-domain.js";import{createDoc as ue,deleteDoc as pe,moveDoc as ye,updateDoc as ge}from"./mutations.js";function O(e,n){return{winner:e===n,scope:e.scope,store_root:e.root,physical_relative_path:e.physicalRelativePath,path:e.path}}l(O,"candidateLocation");function y(e){if(e.scope!=="project"||e.mountStatus==="ready")return e;const n=e.ownerDir??e.storeRoot;if(e.mountStatus==="absent")throw d(`no memory store at ${e.storeRoot}`,{next:`Initialize it with \`crtr memory write <namespace> --dir ${n}\`, which declares the repository namespace.`});const a=e.repositoryRoot??n;throw d(e.diagnostic??`project memory store at ${e.storeRoot} does not declare a namespace`,{next:`Run \`crtr sys migrate --dir ${a}\`.`})}l(y,"requireMountedStore");function R(e){const n=k(e.trim()).join("/");if(n==="")throw d("memory document name required");const a=F(n);if(!a.ok)throw d(`invalid memory document name \`${e}\`: ${a.reason}`,{received:e,next:"Pass the full canonical name (a project document is <namespace>/<local name>); run `crtr memory find <leaf>` to look one up."});return n}l(R,"requireCanonicalName");function U(e,n){y(e);const a=R(n);if(e.namespace==="")return a;const s=b(a,e.namespace);if(s===null)throw d(`\`${a}\` is not in the namespace of the store at ${e.storeRoot} (\`${e.namespace}\`)`,{memory:a,next:`Every document there answers at \`${e.namespace}/<local name>\`; the store's own document answers at \`${e.namespace}\`.`});return s}l(U,"requireLocalNameInStore");function W(e){return e==="node"?-1:e==="project"?0:e==="profile"?1:e==="user"?2:3}l(W,"memoryScopeRank");function g(e){return e.store!=null?q(y(e.store),!0,e.target):x(e.target,{...e.scope===void 0?{}:{scope:e.scope},includeDescendants:!0,quiet:!0,reportDiscovery:!1})}l(g,"selectedView");function N(e){return g(e).docs}l(N,"selectedDocs");function C(e){return`${String(W(e.scope)+10).padStart(2,"0")}:${e.kind}:${e.name}:${e.physicalRelativePath}`}l(C,"memoryListKey");function G(e,n){const[a,s,i,...o]=e.split(":"),[r,t,c,...h]=n.split(":"),f=Number(a)-Number(r);if(f!==0)return f;const m=s.localeCompare(t);if(m!==0)return m;const u=i.localeCompare(c);return u!==0?u:o.join(":").localeCompare(h.join(":"))}l(G,"compareMemoryListKeys");function ce(e){const n=N(e),a=e.store==null,s=new Map;for(const r of n){const t=s.get(r.name);t!==void 0?t.push(r):s.set(r.name,[r])}const i=new Set,o=[];for(const r of n){const t=_(r);if(!(t===null||e.kind!==void 0&&t.kind!==e.kind)){if(a){if(i.has(t.name))continue;i.add(t.name)}o.push({name:t.name,kind:t.kind,privacy:t.privacy,scope:t.scope,path:t.path,storeRoot:r.root,physicalRelativePath:r.physicalRelativePath,shortForm:t.shortForm,slash:t.slash,extensions:E(r.frontmatter?.extensions,j(r)),candidates:s.get(r.name)??[r]})}}return o.sort((r,t)=>G(C(r),C(t))),o}l(ce,"listDocs");function J(e){const n=N(e),a=e.store==null,s=new Map;for(const r of n){const t=s.get(r.name);t!==void 0?t.push(r):s.set(r.name,[r])}const i=new Set,o=[];for(const r of n){const t=_(r);if(!(t===null||e.kind!==void 0&&t.kind!==e.kind)){if(a){if(i.has(t.name))continue;i.add(t.name)}o.push({name:t.name,localName:r.localName,kind:t.kind,privacy:t.privacy,scope:t.scope,path:t.path,store_root:r.root,physical_relative_path:r.physicalRelativePath,routing:t.whenAndWhyToRead,shortForm:t.shortForm,candidates:s.get(r.name)??[r],body:t.body})}}return o}l(J,"searchUnits");function D(e){return{path:e.path,store_root:e.store_root,physical_relative_path:e.physical_relative_path,...e.candidates.length>1?{candidates:e.candidates.map(n=>O(n,e.candidates[0]))}:{}}}l(D,"searchPath");function me(e){if(e.grep===!0&&e.body===!0)throw d("--grep and --body are mutually exclusive (--grep always scans bodies).");if(e.grep===!0&&e.minScore!==void 0)throw d("--min-score is only available in ranked mode.");if(e.minScore!==void 0&&e.minScore<1)throw d("--min-score must be at least 1.");const n=J(e);if(e.grep===!0){let o;try{o=new RegExp(e.query)}catch{throw d(`invalid regex pattern: ${e.query}`)}const r=[];for(const t of n)t.body.split(`
2
+ `).forEach((c,h)=>{o.test(c)&&r.push({name:t.name,privacy:t.privacy,scope:t.scope,line:h+1,text:c,...D(t)})});return r.sort((t,c)=>{const h=t.name.localeCompare(c.name);if(h!==0)return h;const f=t.scope.localeCompare(c.scope);if(f!==0)return f;const m=t.physical_relative_path.localeCompare(c.physical_relative_path);return m!==0?m:t.line-c.line}),{mode:"grep",matches:r.length,hits:r}}const a=e.query.toLowerCase().split(/\s+/).filter(o=>o.length>0);if(a.length===0)throw d("query must contain at least one non-whitespace term");const s=[];for(const o of n){const r=o.name.toLowerCase(),t=o.localName.toLowerCase(),c=o.physical_relative_path.toLowerCase(),h=o.routing.toLowerCase(),f=o.shortForm.toLowerCase(),m=e.body===!0?o.body.toLowerCase():null;let u=0;for(const p of a)(r.includes(p)||t.includes(p)||c.includes(p))&&(u+=10),h.includes(p)&&(u+=5),f.includes(p)&&(u+=3),m!==null&&m.includes(p)&&(u+=1);u>0&&s.push({unit:o,score:u})}s.sort((o,r)=>{if(r.score!==o.score)return r.score-o.score;const t=o.unit.scope.localeCompare(r.unit.scope);if(t!==0)return t;const c=o.unit.name.localeCompare(r.unit.name);return c!==0?c:o.unit.physical_relative_path.localeCompare(r.unit.physical_relative_path)});const i=e.minScore??(s.length===0?1:Math.max(1,Math.ceil(s[0].score/2)));return{mode:"ranked",matches:s.length,hits:s.filter(o=>o.score>=i).map(({unit:o,score:r})=>({name:o.name,kind:o.kind,privacy:o.privacy,scope:o.scope,score:r,short_form:o.shortForm,...D(o)}))}}l(me,"searchDocs");function le(e){const n=g(e),a=e.kind===void 0?{}:{kind:e.kind},s=n.candidates(e.name,a),i=$(n.docs);if(s===null){const m=k(e.name.trim()).join("/");if(m!==""&&S(i,m))return{kind:"directory",name:m,listingByName:i};n.resolve(e.name,a)}const o=s,r=e.store==null?i:$([...n.docs,...x(e.target,{includeDescendants:!0,quiet:!0,reportDiscovery:!1}).docs]),t=o.winner,c=e.frontmatter===!0?t.frontmatter!==null&&!("privacy"in t.frontmatter)?V({...t.frontmatter,privacy:H(t.frontmatter)},T(v(t.root,t.path).toString("utf8"))):v(t.root,t.path).toString("utf8"):t.body,h=e.interpolateNodePaths===!1||e.target.nodeId===null?c:L(c,e.target.nodeId,e.grantee??e.target.grantee),f=[...o.winner.body.matchAll(/\[\[([^\]]+)\]\]/g)].map(m=>m[1].trim()).filter(m=>r.has(m)||S(r,m));return{kind:"document",doc:o.winner,candidates:o.candidates,content:h,links:f,listingByName:i}}l(le,"readDoc");function Q(e){const a=g(e).candidates(e.name);if(a!==null){const o=a.winner;if(o.plugin!==void 0)throw d(`${o.name} belongs to the installed plugin "${o.plugin}" \u2014 a read-only corpus with no revision history.`,{memory:o.name,plugin:o.plugin});if(o.scope==="builtin")throw d(`${o.name} is a builtin document shipped with the package \u2014 a read-only corpus with no revision history.`,{memory:o.name,scope:"builtin"});return{name:o.name,scope:o.scope,root:o.root,logPath:I(o)}}const s=R(e.name),i=e.store!=null?[y(e.store)]:M(e.target,e.scope,!0,!1).filter(o=>o.mountStatus==="ready"&&o.scope!=="builtin"&&o.plugin===void 0);for(const o of i){if(o.namespace!==""&&b(s,o.namespace)===null||e.target.allowsStore?.(o,s)===!1)continue;const r=U(o,s),t=K(o.storeRoot,r);if(t!==null)return{name:s,scope:o.scope,root:o.storeRoot,logPath:t.logPath,deleted:t}}throw w(`no memory document or revision history found: ${e.name}`,{memory:e.name,next:"Run `crtr memory find <query>` to locate the document. A document that exists but has no history predates this surface or has never been mutated through it."})}l(Q,"historyLocation");function de(e){const n=Q(e),a=B(n.root,n.logPath);if(a.length===0)throw w(`no revision history recorded for ${n.name}`,{memory:n.name,next:"The document predates this surface or has never been mutated through `crtr memory write`/`edit`/`delete`. Its first edit records the pre-existing content in full."});if(e.revision!==void 0){if(e.revision<1||e.revision>a.length)throw d(`revision ${e.revision} is out of range for ${n.name} (1..${a.length})`,{memory:n.name,next:`Run \`crtr memory history ${n.name}\` to see which revisions exist.`});return{...n,total:a.length,record:{revision:e.revision,...a[e.revision-1]}}}const s=a.map((i,o)=>{const r=z(i.before,i.after);return{revision:o+1,op:i.op,at:i.at,...i.node===void 0?{}:{node:i.node},...i.rationale===void 0?{}:{rationale:i.rationale},...i.verbatim===!0?{verbatim:!0}:{},...r,...e.diff===!0?{diff:A(i.before,i.after)}:{}}}).reverse().slice(0,Math.max(0,e.limit));return{...n,total:a.length,revisions:s}}l(de,"readHistory");export{O as candidateLocation,G as compareMemoryListKeys,ue as createDoc,pe as deleteDoc,ce as listDocs,C as memoryListKey,W as memoryScopeRank,ye as moveDoc,le as readDoc,de as readHistory,R as requireCanonicalName,U as requireLocalNameInStore,y as requireMountedStore,me as searchDocs,ge as updateDoc};
@@ -54,6 +54,9 @@ export type MemoryStoreMountStatus = 'ready' | 'absent' | 'undeclared' | 'invali
54
54
  * canonical names compose under, and whether it mounts. */
55
55
  export interface MemoryStoreDescriptor {
56
56
  scope: MemoryScope;
57
+ /** App holding a profile store; absent for legacy local profiles. */
58
+ ownerApp?: string;
59
+ profileId?: string;
57
60
  /** Absolute path of the physical `memory/` dir. Store identity (and the
58
61
  * dedup of one real store reached twice) uses its realpath. */
59
62
  storeRoot: string;
@@ -75,7 +78,7 @@ export interface MemoryStoreDescriptor {
75
78
  /** Canonical owner path relative to the repository root, empty at the root. */
76
79
  ownerRelativePath?: string;
77
80
  /** Structured cause for a project store that does not mount. */
78
- mountFailure?: 'association' | 'collision' | 'undeclared-root' | 'invalid-root';
81
+ mountFailure?: 'association' | 'collision' | 'undeclared-root' | 'invalid-root' | 'symlink';
79
82
  /** The owning plugin's name for a plugin-mounted store. Plugin docs surface
80
83
  * within a source scope but live under the plugins dir and are managed by
81
84
  * `crtr pkg`, so consumers that mutate the store gate on this. */
@@ -185,6 +188,12 @@ export interface MemoryTarget {
185
188
  /** The node whose `nodes/<id>/context/memory/` store is the nearest scope,
186
189
  * or null outside a node. */
187
190
  nodeId: string | null;
191
+ /** App assignment from the selected node's row when outside its broker. */
192
+ grantee?: string;
193
+ /** Daemon authorization applied before exposing any candidate or store. */
194
+ allowsStore?: (store: MemoryStoreDescriptor, name?: string) => boolean;
195
+ /** Project roots whose repository is readable in the run's mount set. */
196
+ allowsProject?: (repositoryRoot: string) => boolean;
188
197
  }
189
198
  /** The target the ambient process describes: cwd + the two env seams every
190
199
  * profile/node-aware memory path reads through (`CRTR_PROFILE_ID`,
@@ -224,7 +233,7 @@ export declare function loadMemoryTargetView(target: MemoryTarget, opts?: Memory
224
233
  /** Load ONE exact physical store. An undeclared/invalid project store loads
225
234
  * under the empty namespace so lint and migration can inspect what it holds;
226
235
  * no target view ever sees those documents. */
227
- export declare function loadMemoryStoreView(store: MemoryStoreDescriptor, quiet?: boolean): MemoryStoreView;
236
+ export declare function loadMemoryStoreView(store: MemoryStoreDescriptor, quiet?: boolean, target?: MemoryTarget): MemoryStoreView;
228
237
  /** All project-scoped docs visible from an explicit node workspace/profile — the
229
238
  * project-only slice of a `MemoryTarget` view, used where only workspace docs
230
239
  * are wanted (a workspace-open render). For a full-precedence target-addressed
@@ -248,11 +257,6 @@ export declare function createMemoryDocSnapshot(target?: MemoryTarget): MemoryDo
248
257
  /** Resolve several canonical names over one memory-source snapshot. Failed
249
258
  * names are omitted so callers can preserve their per-document error behavior. */
250
259
  export declare function resolveMemoryDocs(names: readonly string[]): Map<string, MemoryDoc>;
251
- /** Load the body at an already-resolved memory path with the same frontmatter
252
- * stripping and in-node path interpolation as `memory read`. Callers that
253
- * already have the resolved path (such as slash-command discovery) avoid
254
- * re-walking every memory store for each document. */
255
- export declare function readMemoryDocContent(path: string, includeFrontmatter?: boolean): string;
256
260
  /** The address winner for an exact canonical name in the ambient target. */
257
261
  export declare function resolveMemoryDoc(rawName: string, opts?: MemoryResolutionOpts): MemoryDoc;
258
262
  /** Resolve a memory document as ANOTHER node would see it — the same precedence
@@ -1,2 +1,2 @@
1
- var V=Object.defineProperty;var c=(e,o)=>V(e,"name",{value:o,configurable:!0});import{envNodeId as x,envProfileId as W}from"../shared/env.js";import{dirname as G,join as y,relative as H,sep as J}from"node:path";import{readdirSync as Q}from"node:fs";import{CRTR_DIR_NAME as F}from"../types.js";import{pathExists as v,readText as $,realpathOrSelf as N,walkFiles as U}from"./fs-utils.js";import{parseFrontmatterGeneric as j}from"./frontmatter.js";import{interpolateNodePaths as X}from"./canvas/paths.js";import{listInstalledPlugins as Y,listInstalledPluginsInRoot as B}from"./resolver.js";import{notFound as Z,usage as b}from"./errors.js";import{warn as M}from"./output.js";import{NEUTRAL_PROJECT_MEMORY as h,pluginMemoryDir as ee,projectScopeRoots as oe,projectScopeRootsWithMemory as ne,scopeMemoryDir as te}from"./scope.js";import{effectiveDocKind as k}from"./substrate/schema.js";import{INDEX_SEGMENT as w,canonicalSegments as C,composeCanonicalName as E,localNameFromPath as re,normalizeNameSegment as T,representationForPath as ie,resolveLocalName as ae,routingAnchorFor as se,validateNamespace as ce}from"./memory/identity.js";import{loadProfileManifest as ue,profileMemoryDir as le}from"./profiles/manifest.js";import{memoryDir as me}from"./runtime/memory.js";import{descendantStoreRoots as de}from"./nested-stores.js";import{associateRepository as fe}from"./memory/repository-association.js";function g(){return{cwd:process.cwd(),profileId:W()||null,nodeId:x()||null}}c(g,"ambientMemoryTarget");function pe(){return g().profileId??""}c(pe,"selectedProfileId");function ye(e,o){if(o)return[o];const n=[];return e.nodeId&&n.push("node"),oe(e.cwd,e.profileId).length>0&&n.push("project"),e.profileId&&n.push("profile"),n.push("user"),n.push("builtin"),n}c(ye,"scopesInPrecedence");function L(e,o,n){const t={scope:"project",storeRoot:o,ownerDir:e,projectMemory:n};if(!v(o))return{...t,namespace:"",mountStatus:"absent"};const r=fe(e);if(!r.ok){const p=`run \`crtr sys migrate --dir ${e}\``;return r.code==="no-project-root"?{...t,namespace:"",mountStatus:"undeclared",mountFailure:"association",diagnostic:`project memory store at ${o} has no repository root declaring \`namespace:\` \u2014 ${p}`}:{...t,namespace:"",mountStatus:"invalid",mountFailure:"association",diagnostic:`project memory store at ${o} cannot be associated: ${r.reason} \u2014 ${p}`}}const{association:i}=r,s={namespacePath:i.declarationPath,repositoryRoot:i.repositoryRoot,repositoryKey:i.repositoryKey,ownerRelativePath:i.ownerRelativePath},u=i.declarationPath,d=i.ownerRelativePath!=="",a=`run \`crtr sys migrate --dir ${i.repositoryRoot}\``,l=d?`nested project memory store at ${o} takes its identity from ${u}, which is missing root ${w}.md declaring \`namespace:\` \u2014 ${a}`:`project memory store has no root ${w}.md declaring \`namespace:\` \u2014 ${a}`;if(!v(u))return{...t,...s,namespace:"",mountStatus:"undeclared",mountFailure:"undeclared-root",diagnostic:l};let m;try{m=j($(u)).data?.namespace}catch(p){return{...t,...s,namespace:"",mountStatus:"invalid",mountFailure:"invalid-root",diagnostic:`project memory store's ${u} does not parse (${z(p)}) \u2014 ${a}`}}if(m==null||m===""){const p=d?`nested project memory store at ${o} takes its identity from ${u}, which declares no \`namespace:\` \u2014 ${a}`:`project memory store's ${u} declares no \`namespace:\` \u2014 ${a}`;return{...t,...s,namespace:"",mountStatus:"undeclared",mountFailure:"undeclared-root",diagnostic:p}}if(typeof m!="string")return{...t,...s,namespace:"",mountStatus:"invalid",mountFailure:"invalid-root",diagnostic:`project memory store declares a non-string \`namespace:\` (${JSON.stringify(m)}) \u2014 quote it in ${u}, or ${a}`};const f=ce(m);return f.ok?{...t,...s,repositoryNamespace:m,namespace:E(m,i.ownerRelativePath),mountStatus:"ready"}:{...t,...s,namespace:"",mountStatus:"invalid",mountFailure:"invalid-root",diagnostic:`project memory store declares an invalid namespace \`${m}\` (${f.reason}) \u2014 ${a}`}}c(L,"projectStoreDescriptor");function R(e,o){return o===null?{scope:e,storeRoot:"",namespace:"",mountStatus:"absent",projectMemory:h}:{scope:e,storeRoot:o,namespace:"",mountStatus:v(o)?"ready":"absent",projectMemory:h}}c(R,"plainStoreDescriptor");function I(e,o,n){const t=ee(e);return{scope:o,storeRoot:t,namespace:e.name,plugin:e.name,mountStatus:v(t)?"ready":"absent",projectMemory:n}}c(I,"pluginStoreDescriptor");function _e(e){const o=N(e);return L(o,y(o,F,"memory"),h)}c(_e,"openProjectMemoryStore");function q(e,o,n=!1,t=!0){const r=[],i=c((a,l)=>{r.push(L(G(a),y(a,"memory"),l));for(const m of B("project",a).filter(f=>f.enabled))r.push(I(m,"project",l))},"projectStores");for(const a of ye(e,o))if(a==="project"){const l=ne(e.cwd,e.profileId);for(const{root:m,memory:f}of l)i(m,f);if(n)for(const m of de(l.map(({root:f})=>f),t))i(m,h)}else if(a==="profile"){const l=e.profileId??"";if(l!=="")try{const{profileId:m}=ue(l);r.push(R("profile",le(m)))}catch{}}else if(a==="node"){const l=e.nodeId??"";l!==""&&r.push(R("node",me(l)))}else{r.push(R(a,te(a)));for(const l of Y(a).filter(m=>m.enabled))r.push(I(l,a,h))}const s=new Set,u=r.filter(a=>{if(a.storeRoot==="")return!1;const l=N(a.storeRoot);return s.has(l)?!1:(s.add(l),!0)}),d=new Map;for(const a of u){if(a.scope!=="project"||a.mountStatus!=="ready"||a.repositoryRoot===void 0||a.ownerRelativePath===void 0)continue;const l=`${a.repositoryRoot}\0${a.ownerRelativePath}`,m=d.get(l);m?m.push(a):d.set(l,[a])}return u.map(a=>{if(a.scope!=="project"||a.mountStatus!=="ready"||a.repositoryRoot===void 0||a.ownerRelativePath===void 0)return a;const l=d.get(`${a.repositoryRoot}\0${a.ownerRelativePath}`);if(l===void 0||l.length<2)return a;const m=l.map(f=>f.ownerDir??f.storeRoot).join(", ");return{...a,mountStatus:"invalid",mountFailure:"collision",diagnostic:`project memory stores at ${m} normalize to the same effective prefix \`${a.namespace}\` \u2014 rename one owner directory`}})}c(q,"memoryStoresInPrecedence");function Ke(e,o=!1){return q(g(),e,o).filter(n=>n.mountStatus==="ready"&&n.scope!=="builtin"&&n.plugin===void 0).map(n=>({scope:n.scope,memoryDir:n.storeRoot,store:n}))}c(Ke,"nativeMemoryStoresInPrecedence");function z(e){return(e instanceof Error?e.message:String(e)).split(`
2
- `)[0]??""}c(z,"firstLine");function he(e,o,n){const{data:t,body:r}=j($(o)),i=re(n),s=ie(n),u=i===""?"":ae(t,i),d=E(e.namespace,u);return d===""?null:{name:d,localName:u,scope:e.scope,path:o,root:e.storeRoot,physicalRelativePath:n,representation:s,routingAnchor:se(d,s),store:e,frontmatter:t,body:r,projectMemory:e.projectMemory,...e.plugin===void 0?{}:{plugin:e.plugin}}}c(he,"loadMemoryDoc");function ge(e,o){const n=e.name.localeCompare(o.name);return n!==0?n:e.representation!==o.representation?e.representation==="directory-index"?-1:1:e.physicalRelativePath.localeCompare(o.physicalRelativePath)}c(ge,"compareDocs");function D(e,o=!1){if(e.storeRoot===""||!v(e.storeRoot))return[];const n=[];for(const t of U(e.storeRoot,r=>r.endsWith(".md")&&r!=="SKILL.md",r=>r===F)){const r=H(e.storeRoot,t).split(J).join("/");try{const i=he(e,t,r);if(i===null){o||M(`${t}: a root ${w}.md has no canonical name in a store without a namespace`);continue}n.push(i)}catch(i){o||M(`invalid frontmatter in ${t}: ${z(i)}`)}}return n.sort(ge)}c(D,"loadStoreMemoryDocs");function Oe(e,o,n=!1,t=h){return D(I(e,o,t),n)}c(Oe,"listPluginMemoryDocs");function P(e){return C(e.trim()).join("/")}c(P,"normalizeQuery");function A(e,o,n){const t=C(o),r=t[t.length-1]===w;r&&t.pop();const i=t[t.length-1]??o,s=r?`A directory's own document answers at the directory name \u2014 drop the trailing /${w}. Run \`crtr memory find ${i}\` to find the canonical name.`:`Resolution takes the full canonical name (a project doc is <namespace>/<local name>). Run \`crtr memory find ${i}\` to find it.`;return Z(`memory document not found: ${e}`,{memory:o,...n?{scope:n}:{},next:s})}c(A,"notFoundError");function _(e,o,n){const t=c((r,i)=>{const s=P(r);if(s==="")return null;const u=i?.kind,d=o.filter(a=>a.name===s&&(u===void 0||k(a)===u));return d.length===0?null:{name:s,winner:d[0],candidates:d}},"candidatesFor");return{stores:e,docs:o,candidates:t,candidateSets(r){const i=r?.kind,s=new Map;for(const u of o){if(i!==void 0&&k(u)!==i)continue;const d=s.get(u.name);d?d.push(u):s.set(u.name,[u])}return[...s.entries()].sort(([u],[d])=>u.localeCompare(d)).map(([u,d])=>({name:u,winner:d[0],candidates:d}))},resolve(r,i){const s=P(r);if(s==="")throw b("memory document name required");const u=t(s,i);if(u===null)throw A(r,s,n);return u.winner}}}c(_,"makeView");function S(e,o={}){const n=o.quiet??!1,t=q(e,o.scope,o.includeDescendants??!1,o.reportDiscovery??!n),r=[];for(const i of t)if(i.mountStatus!=="absent"){if(i.mountStatus!=="ready"){!n&&i.diagnostic!==void 0&&M(`memory store not mounted: ${i.diagnostic}`);continue}r.push(...D(i,n))}return{target:e,..._(t,r,o.scope)}}c(S,"loadMemoryTargetView");function ve(e,o=!1){return{store:e,..._([e],D(e,o))}}c(ve,"loadMemoryStoreView");function Ve(e=process.cwd(),o=pe()||null,n=!1){return[...S({cwd:e,profileId:o,nodeId:null},{scope:"project",quiet:n}).docs]}c(Ve,"listProjectMemoryDocs");function We(e,o=!1,n=!1){return[...S(g(),{...e?{scope:e}:{},quiet:o,includeDescendants:n}).docs]}c(We,"listAllMemoryDocs");function we(e=g()){const o=S(e,{quiet:!0});return{docs:o.docs,resolve:c(n=>{const t=new Map;for(const r of n){const i=o.candidates(r);i!==null&&t.set(r,i.winner)}return t},"resolve")}}c(we,"createMemoryDocSnapshot");function Ge(e){return we().resolve(e)}c(Ge,"resolveMemoryDocs");function He(e,o=!1){const n=$(e),t=o?n:j(n).body,r=x();return r?X(t,r):t}c(He,"readMemoryDocContent");function Je(e,o={}){return Se(e,g(),o)}c(Je,"resolveMemoryDoc");function Se(e,o,n={}){return K(e,o,n).winner}c(Se,"resolveMemoryDocForTarget");function Qe(e,o={}){return K(e,g(),o)}c(Qe,"resolveMemoryCandidates");function K(e,o,n={}){const t=S(o,{...n,quiet:!0}),r=P(e);if(r==="")throw b("memory document name required");const i=t.candidates(r,n);if(i===null)throw A(e,r,n.scope);return i}c(K,"resolveMemoryCandidatesForTarget");function Ue(e,o,n={}){return ve(o,!0).resolve(e,n)}c(Ue,"resolveMemoryDocInStore");function O(e,o,n,t=".md"){let r;try{r=Q(e,{withFileTypes:!0})}catch{return null}let i=null;for(const s of r)if(n==="dir"){if(!s.isDirectory())continue;if(s.name===o)return y(e,s.name);i===null&&T(s.name)===o&&(i=y(e,s.name))}else{if(!(s.isFile()&&s.name.endsWith(t)))continue;const u=s.name.slice(0,-t.length);if(u===o)return y(e,s.name);i===null&&T(u)===o&&(i=y(e,s.name))}return i}c(O,"matchNormalizedChild");function $e(e,o,n){let t=e;for(let r=0;r<o.length-1;r++){const i=O(t,o[r],"dir",n);if(!i)return null;t=i}return O(t,o[o.length-1],"file",n)}c($e,"resolveNormalizedFile");function Xe(e,o){return o.length===0?null:$e(e,o,".jsonl")}c(Xe,"resolveHistoryLogPath");export{g as ambientMemoryTarget,we as createMemoryDocSnapshot,We as listAllMemoryDocs,Oe as listPluginMemoryDocs,Ve as listProjectMemoryDocs,ve as loadMemoryStoreView,S as loadMemoryTargetView,D as loadStoreMemoryDocs,q as memoryStoresInPrecedence,Ke as nativeMemoryStoresInPrecedence,_e as openProjectMemoryStore,He as readMemoryDocContent,Xe as resolveHistoryLogPath,Qe as resolveMemoryCandidates,K as resolveMemoryCandidatesForTarget,Je as resolveMemoryDoc,Se as resolveMemoryDocForTarget,Ue as resolveMemoryDocInStore,Ge as resolveMemoryDocs};
1
+ var W=Object.defineProperty;var c=(e,o)=>W(e,"name",{value:o,configurable:!0});import{envGrantee as G,envNodeId as V,envProfileId as H}from"../shared/env.js";import{dirname as x,join as y,relative as J,sep as Q}from"node:path";import{readdirSync as U}from"node:fs";import{CRTR_DIR_NAME as F}from"../types.js";import{realpathOrSelf as $}from"./fs-utils.js";import{existsBeneath as X,isBeneathRefusal as Y,readFileBeneath as Z,readTextBeneathIfExists as ee,walkFilesBeneath as oe}from"./spaces/open-beneath.js";import{parseFrontmatterGeneric as k}from"./frontmatter.js";import{listInstalledPlugins as ne,listInstalledPluginsInRoot as te}from"./resolver.js";import{notFound as re,usage as N}from"./errors.js";import{warn as j}from"./output.js";import{NEUTRAL_PROJECT_MEMORY as h,pluginMemoryDir as ie,projectScopeRoots as ae,projectScopeRootsWithMemory as se,scopeMemoryDir as ce}from"./scope.js";import{effectiveDocKind as b}from"./substrate/schema.js";import{INDEX_SEGMENT as w,canonicalSegments as E,composeCanonicalName as T,localNameFromPath as ue,normalizeNameSegment as C,representationForPath as le,resolveLocalName as me,routingAnchorFor as de,validateNamespace as fe}from"./memory/identity.js";import{loadProfileManifest as A,profileMemoryDir as pe}from"./profiles/manifest.js";import{memoryDir as ye}from"./runtime/memory.js";import{descendantStoreRoots as he}from"./nested-stores.js";import{associateRepository as ge}from"./memory/repository-association.js";import{appSpace as we}from"./layout.js";function g(){return{cwd:process.cwd(),profileId:H()||null,nodeId:V()||null,grantee:G()||void 0}}c(g,"ambientMemoryTarget");function ve(){return g().profileId??""}c(ve,"selectedProfileId");function Se(e,o){if(o)return[o];const n=[];return e.nodeId&&n.push("node"),ae(e.cwd,e.profileId).length>0&&n.push("project"),e.profileId&&n.push("profile"),n.push("user"),n.push("builtin"),n}c(Se,"scopesInPrecedence");function L(e,o,n){const t={scope:"project",storeRoot:o,ownerDir:e,projectMemory:n},r=R(o);if(r.mountStatus!=="ready")return{...t,namespace:"",...r};const i=ge(e);if(!i.ok){const p=`run \`crtr sys migrate --dir ${e}\``;return i.code==="no-project-root"?{...t,namespace:"",mountStatus:"undeclared",mountFailure:"association",diagnostic:`project memory store at ${o} has no repository root declaring \`namespace:\` \u2014 ${p}`}:{...t,namespace:"",mountStatus:"invalid",mountFailure:"association",diagnostic:`project memory store at ${o} cannot be associated: ${i.reason} \u2014 ${p}`}}const{association:s}=i,u={namespacePath:s.declarationPath,repositoryRoot:s.repositoryRoot,repositoryKey:s.repositoryKey,ownerRelativePath:s.ownerRelativePath},m=s.declarationPath,a=s.ownerRelativePath!=="",l=`run \`crtr sys migrate --dir ${s.repositoryRoot}\``,f=a?`nested project memory store at ${o} takes its identity from ${m}, which is missing root ${w}.md declaring \`namespace:\` \u2014 ${l}`:`project memory store has no root ${w}.md declaring \`namespace:\` \u2014 ${l}`;let d;try{const p=ee(x(m),m);if(p===null)return{...t,...u,namespace:"",mountStatus:"undeclared",mountFailure:"undeclared-root",diagnostic:f};d=k(p).data?.namespace}catch(p){return{...t,...u,namespace:"",mountStatus:"invalid",mountFailure:"invalid-root",diagnostic:`project memory store's ${m} does not parse (${z(p)}) \u2014 ${l}`}}if(d==null||d===""){const p=a?`nested project memory store at ${o} takes its identity from ${m}, which declares no \`namespace:\` \u2014 ${l}`:`project memory store's ${m} declares no \`namespace:\` \u2014 ${l}`;return{...t,...u,namespace:"",mountStatus:"undeclared",mountFailure:"undeclared-root",diagnostic:p}}if(typeof d!="string")return{...t,...u,namespace:"",mountStatus:"invalid",mountFailure:"invalid-root",diagnostic:`project memory store declares a non-string \`namespace:\` (${JSON.stringify(d)}) \u2014 quote it in ${m}, or ${l}`};const v=fe(d);return v.ok?{...t,...u,repositoryNamespace:d,namespace:T(d,s.ownerRelativePath),mountStatus:"ready"}:{...t,...u,namespace:"",mountStatus:"invalid",mountFailure:"invalid-root",diagnostic:`project memory store declares an invalid namespace \`${d}\` (${v.reason}) \u2014 ${l}`}}c(L,"projectStoreDescriptor");function R(e){try{return{mountStatus:X(e,e)?"ready":"absent"}}catch(o){if(!Y(o))throw o;return{mountStatus:"invalid",mountFailure:"symlink",diagnostic:`memory store at ${e} is reached through a symlink, which never mounts`}}}c(R,"storeRootMount");function M(e,o){return o===null?{scope:e,storeRoot:"",namespace:"",mountStatus:"absent",projectMemory:h}:{scope:e,storeRoot:o,namespace:"",...R(o),projectMemory:h}}c(M,"plainStoreDescriptor");function I(e,o,n){const t=$(ie(e));return{scope:o,storeRoot:t,namespace:e.name,plugin:e.name,...R(t),projectMemory:n}}c(I,"pluginStoreDescriptor");function Ve(e){const o=$(e);return L(o,y(o,F,"memory"),h)}c(Ve,"openProjectMemoryStore");function q(e,o,n=!1,t=!0){const r=[],i=c((a,l)=>{r.push(L(x(a),y(a,"memory"),l));for(const f of te("project",a).filter(d=>d.enabled))r.push(I(f,"project",l))},"projectStores");for(const a of Se(e,o))if(a==="project"){const l=se(e.cwd,e.profileId);for(const{root:f,memory:d}of l)i(f,d);if(n)for(const f of he(l.map(({root:d})=>d),t))i(f,h)}else if(a==="profile"){const l=e.profileId??"";if(l!=="")try{const{profileId:f}=A(l),{manifest:d}=A(f),v=d.grantee?.startsWith("app:")?y(we(d.grantee).memory,"profiles",f):pe(f);r.push({...M("profile",v),profileId:f,ownerApp:d.grantee})}catch{}}else if(a==="node"){const l=e.nodeId??"";l!==""&&r.push({...M("node",ye(l,e.grantee)),ownerApp:e.grantee})}else{r.push(M(a,ce(a)));for(const l of ne(a).filter(f=>f.enabled))r.push(I(l,a,h))}const s=new Set,u=r.filter(a=>{if(a.storeRoot==="")return!1;const l=$(a.storeRoot);return s.has(l)?!1:(s.add(l),!0)}),m=new Map;for(const a of u){if(a.scope!=="project"||a.mountStatus!=="ready"||a.repositoryRoot===void 0||a.ownerRelativePath===void 0)continue;const l=`${a.repositoryRoot}\0${a.ownerRelativePath}`,f=m.get(l);f?f.push(a):m.set(l,[a])}return u.filter(a=>(a.scope!=="project"||a.repositoryRoot===void 0||e.allowsProject?.(a.repositoryRoot)!==!1)&&e.allowsStore?.(a)!==!1).map(a=>{if(a.scope!=="project"||a.mountStatus!=="ready"||a.repositoryRoot===void 0||a.ownerRelativePath===void 0)return a;const l=m.get(`${a.repositoryRoot}\0${a.ownerRelativePath}`);if(l===void 0||l.length<2)return a;const f=l.map(d=>d.ownerDir??d.storeRoot).join(", ");return{...a,mountStatus:"invalid",mountFailure:"collision",diagnostic:`project memory stores at ${f} normalize to the same effective prefix \`${a.namespace}\` \u2014 rename one owner directory`}})}c(q,"memoryStoresInPrecedence");function He(e,o=!1){return q(g(),e,o).filter(n=>n.mountStatus==="ready"&&n.scope!=="builtin"&&n.plugin===void 0).map(n=>({scope:n.scope,memoryDir:n.storeRoot,store:n}))}c(He,"nativeMemoryStoresInPrecedence");function z(e){return(e instanceof Error?e.message:String(e)).split(`
2
+ `)[0]??""}c(z,"firstLine");function $e(e,o,n){const{data:t,body:r}=k(Z(e.storeRoot,o).toString("utf8")),i=ue(n),s=le(n),u=i===""?"":me(t,i),m=T(e.namespace,u);return m===""?null:{name:m,localName:u,scope:e.scope,path:o,root:e.storeRoot,physicalRelativePath:n,representation:s,routingAnchor:de(m,s),store:e,frontmatter:t,body:r,projectMemory:e.projectMemory,...e.plugin===void 0?{}:{plugin:e.plugin}}}c($e,"loadMemoryDoc");function je(e,o){const n=e.name.localeCompare(o.name);return n!==0?n:e.representation!==o.representation?e.representation==="directory-index"?-1:1:e.physicalRelativePath.localeCompare(o.physicalRelativePath)}c(je,"compareDocs");function P(e,o=!1){if(e.storeRoot===""||e.mountFailure==="symlink")return[];const n=[];for(const t of oe(e.storeRoot,e.storeRoot,r=>r.endsWith(".md")&&r!=="SKILL.md",r=>r===F)){const r=J(e.storeRoot,t).split(Q).join("/");try{const i=$e(e,t,r);if(i===null){o||j(`${t}: a root ${w}.md has no canonical name in a store without a namespace`);continue}n.push(i)}catch(i){o||j(`invalid frontmatter in ${t}: ${z(i)}`)}}return n.sort(je)}c(P,"loadStoreMemoryDocs");function Je(e,o,n=!1,t=h){return P(I(e,o,t),n)}c(Je,"listPluginMemoryDocs");function D(e){return E(e.trim()).join("/")}c(D,"normalizeQuery");function B(e,o,n){const t=E(o),r=t[t.length-1]===w;r&&t.pop();const i=t[t.length-1]??o,s=r?`A directory's own document answers at the directory name \u2014 drop the trailing /${w}. Run \`crtr memory find ${i}\` to find the canonical name.`:`Resolution takes the full canonical name (a project doc is <namespace>/<local name>). Run \`crtr memory find ${i}\` to find it.`;return re(`memory document not found: ${e}`,{memory:o,...n?{scope:n}:{},next:s})}c(B,"notFoundError");function _(e,o,n){const t=c((r,i)=>{const s=D(r);if(s==="")return null;const u=i?.kind,m=o.filter(a=>a.name===s&&(u===void 0||b(a)===u));return m.length===0?null:{name:s,winner:m[0],candidates:m}},"candidatesFor");return{stores:e,docs:o,candidates:t,candidateSets(r){const i=r?.kind,s=new Map;for(const u of o){if(i!==void 0&&b(u)!==i)continue;const m=s.get(u.name);m?m.push(u):s.set(u.name,[u])}return[...s.entries()].sort(([u],[m])=>u.localeCompare(m)).map(([u,m])=>({name:u,winner:m[0],candidates:m}))},resolve(r,i){const s=D(r);if(s==="")throw N("memory document name required");const u=t(s,i);if(u===null)throw B(r,s,n);return u.winner}}}c(_,"makeView");function S(e,o={}){const n=o.quiet??!1,t=q(e,o.scope,o.includeDescendants??!1,o.reportDiscovery??!n),r=[];for(const i of t)if(i.mountStatus!=="absent"){if(i.mountStatus!=="ready"){!n&&i.diagnostic!==void 0&&j(`memory store not mounted: ${i.diagnostic}`);continue}r.push(...P(i,n).filter(s=>e.allowsStore?.(i,s.name)!==!1))}return{target:e,..._(t,r,o.scope)}}c(S,"loadMemoryTargetView");function Re(e,o=!1,n){const t=P(e,o).filter(r=>n?.allowsStore?.(e,r.name)!==!1);return{store:e,..._([e],t)}}c(Re,"loadMemoryStoreView");function Qe(e=process.cwd(),o=ve()||null,n=!1){return[...S({cwd:e,profileId:o,nodeId:null},{scope:"project",quiet:n}).docs]}c(Qe,"listProjectMemoryDocs");function Ue(e,o=!1,n=!1){return[...S(g(),{...e?{scope:e}:{},quiet:o,includeDescendants:n}).docs]}c(Ue,"listAllMemoryDocs");function Me(e=g()){const o=S(e,{quiet:!0});return{docs:o.docs,resolve:c(n=>{const t=new Map;for(const r of n){const i=o.candidates(r);i!==null&&t.set(r,i.winner)}return t},"resolve")}}c(Me,"createMemoryDocSnapshot");function Xe(e){return Me().resolve(e)}c(Xe,"resolveMemoryDocs");function Ye(e,o={}){return Ie(e,g(),o)}c(Ye,"resolveMemoryDoc");function Ie(e,o,n={}){return K(e,o,n).winner}c(Ie,"resolveMemoryDocForTarget");function Ze(e,o={}){return K(e,g(),o)}c(Ze,"resolveMemoryCandidates");function K(e,o,n={}){const t=S(o,{...n,quiet:!0}),r=D(e);if(r==="")throw N("memory document name required");const i=t.candidates(r,n);if(i===null)throw B(e,r,n.scope);return i}c(K,"resolveMemoryCandidatesForTarget");function eo(e,o,n={}){return Re(o,!0).resolve(e,n)}c(eo,"resolveMemoryDocInStore");function O(e,o,n,t=".md"){let r;try{r=U(e,{withFileTypes:!0})}catch{return null}let i=null;for(const s of r)if(n==="dir"){if(!s.isDirectory())continue;if(s.name===o)return y(e,s.name);i===null&&C(s.name)===o&&(i=y(e,s.name))}else{if(!(s.isFile()&&s.name.endsWith(t)))continue;const u=s.name.slice(0,-t.length);if(u===o)return y(e,s.name);i===null&&C(u)===o&&(i=y(e,s.name))}return i}c(O,"matchNormalizedChild");function Pe(e,o,n){let t=e;for(let r=0;r<o.length-1;r++){const i=O(t,o[r],"dir",n);if(!i)return null;t=i}return O(t,o[o.length-1],"file",n)}c(Pe,"resolveNormalizedFile");function oo(e,o){return o.length===0?null:Pe(e,o,".jsonl")}c(oo,"resolveHistoryLogPath");export{g as ambientMemoryTarget,Me as createMemoryDocSnapshot,Ue as listAllMemoryDocs,Je as listPluginMemoryDocs,Qe as listProjectMemoryDocs,Re as loadMemoryStoreView,S as loadMemoryTargetView,P as loadStoreMemoryDocs,q as memoryStoresInPrecedence,He as nativeMemoryStoresInPrecedence,Ve as openProjectMemoryStore,oo as resolveHistoryLogPath,Ze as resolveMemoryCandidates,K as resolveMemoryCandidatesForTarget,Ye as resolveMemoryDoc,Ie as resolveMemoryDocForTarget,eo as resolveMemoryDocInStore,Xe as resolveMemoryDocs};
@@ -0,0 +1,13 @@
1
+ import type { ProviderAuthInteraction } from '@earendil-works/pi-ai';
2
+ import type { CrtrClient } from '../../api/client.js';
3
+ import type { ManagedProviderId } from '../subscription-state.js';
4
+ /** A self-host box with a browser on this machine: the vendor's redirect can
5
+ * reach the daemon's loopback listener (RT-LLM-41). Over SSH or on a headless
6
+ * host the code page / device flow is the only one that works. */
7
+ export declare function localBrowserAvailable(env?: NodeJS.ProcessEnv): boolean;
8
+ /** Sign in to a managed provider through the daemon. Resolves once the daemon
9
+ * has written the credential; rejects with `Login cancelled` on abort. */
10
+ export declare function daemonManagedLogin(client: CrtrClient, provider: ManagedProviderId, interaction: ProviderAuthInteraction, options?: {
11
+ label?: string;
12
+ loopback?: boolean;
13
+ }): Promise<void>;
@@ -0,0 +1 @@
1
+ var f=Object.defineProperty;var a=(e,r)=>f(e,"name",{value:r,configurable:!0});import{ApiError as c}from"../../api/errors.js";function w(e=process.env){return e.SSH_CONNECTION||e.SSH_TTY?!1:process.platform==="darwin"||process.platform==="win32"?!0:!!(e.DISPLAY||e.WAYLAND_DISPLAY)}a(w,"localBrowserAvailable");function d(e){return e.aborted}a(d,"cancelled");function p(e,r){return r.aborted?Promise.reject(new Error("Login cancelled")):new Promise((n,t)=>{const s=a(()=>t(new Error("Login cancelled")),"onAbort");r.addEventListener("abort",s,{once:!0}),e.then(n,t).finally(()=>r.removeEventListener("abort",s))})}a(p,"raceAbort");function m(e){if(!(!(e instanceof c)||e.status!==404||!/no route for/.test(e.message)))return new Error("The running crtr daemon predates daemon-run sign-in. Run `crtr sys daemon restart`, then sign in again.")}a(m,"olderDaemon");async function u(e,r){try{return await e.startModelAuth(r)}catch(n){throw m(n)??n}}a(u,"startFlow");async function g(e,r,n,t){const s={provider:r,...n?{label:n}:{}};if(!t)return{flow:await u(e,s),loopback:!1};try{return{flow:await u(e,{...s,redirect:"loopback"}),loopback:!0}}catch(o){if(o instanceof c&&o.status===409&&o.param==="redirect")return{flow:await u(e,s),loopback:!1};throw o}}a(g,"start");async function l(e,r,n){for(;!d(n);){const t=await p(e.getModelAuthFlow(r,25),n);if(t.status==="connected")return;if(t.status!=="pending")throw new Error(t.message??`sign-in ${t.status}`)}throw new Error("Login cancelled")}a(l,"awaitFlow");async function A(e,r,n,t={}){const{flow:s,loopback:o}=await g(e,r,t.label,t.loopback??w()),i=a(()=>{e.cancelModelAuth(s.flow_id).catch(()=>{})},"cancel");if(d(n.signal))throw i(),new Error("Login cancelled");n.signal.addEventListener("abort",i,{once:!0});try{await h(e,s,o,n)}finally{n.signal.removeEventListener("abort",i)}}a(A,"daemonManagedLogin");async function h(e,r,n,t){if(r.user_code!==void 0){t.notify({type:"device_code",userCode:r.user_code,verificationUri:r.url,expiresInSeconds:900}),await l(e,r.flow_id,t.signal);return}if(t.notify({type:"auth_url",url:r.url,instructions:r.instructions}),n){await l(e,r.flow_id,t.signal);return}for(;;){const s=await t.prompt({type:"manual_code",message:"Paste the code Claude shows"});try{await e.completeModelAuth(r.flow_id,{input:s});return}catch(o){if(o instanceof c&&o.status===400&&(o.param==="input"||o.param==="state")){t.notify({type:"info",message:`${o.message} \u2014 paste it again.`});continue}throw o}}}a(h,"drive");export{A as daemonManagedLogin,w as localBrowserAvailable};
@@ -0,0 +1,45 @@
1
+ import { type ManagedProviderId } from '../subscription-state.js';
2
+ export declare const MODEL_AUTH_FLOW_TTL_S = 900;
3
+ export type ModelAuthFlowStatus = 'pending' | 'connected' | 'failed' | 'expired';
4
+ export interface StartedFlow {
5
+ flow_id: string;
6
+ provider: ManagedProviderId;
7
+ url: string;
8
+ instructions: string;
9
+ user_code?: string;
10
+ expires_at: string;
11
+ }
12
+ /** Resolve a caller-supplied provider (the page's `vendor=openai` included). */
13
+ export declare function modelAuthProvider(provider: unknown): ManagedProviderId;
14
+ /** `model_auth.start` (RT-LLM-20). A second start for a provider replaces its
15
+ * in-flight flow (RT-LLM-42). */
16
+ export declare function startModelAuthFlow(input: {
17
+ provider: unknown;
18
+ redirect?: unknown;
19
+ label?: unknown;
20
+ jti?: string;
21
+ }): Promise<StartedFlow>;
22
+ /** `model_auth.cancel`: the person gave up at the CLI. Ends the flow so it stops
23
+ * polling, frees its loopback port, and never writes a credential. Unknown or
24
+ * finished flows are left alone. */
25
+ export declare function cancelModelAuthFlow(flowId: string): FlowView | undefined;
26
+ /** `model_auth.complete` (RT-LLM-22, 31, 43, 49). Returns once the credential is
27
+ * written; a vendor refusal ends the flow as failed and throws. */
28
+ export declare function completeModelAuthFlow(flowId: unknown, input: unknown): Promise<{
29
+ flow_id: string;
30
+ provider: ManagedProviderId;
31
+ status: 'connected';
32
+ }>;
33
+ export interface FlowView {
34
+ flow_id: string;
35
+ provider: ManagedProviderId;
36
+ status: ModelAuthFlowStatus;
37
+ message?: string;
38
+ jti?: string;
39
+ }
40
+ /** A flow's current state, or undefined when it is unknown or long finished. */
41
+ export declare function readModelAuthFlow(flowId: string): FlowView | undefined;
42
+ /** Wait up to `waitMs` for a flow to leave `pending`; answers its state either way. */
43
+ export declare function waitModelAuthFlow(flowId: string, waitMs: number, signal?: AbortSignal): Promise<FlowView | undefined>;
44
+ /** Test seam: forget every flow (a daemon restart does this by construction). */
45
+ export declare function resetModelAuthFlowsForTest(): void;
@@ -0,0 +1 @@
1
+ var U=Object.defineProperty;var a=(e,t)=>U(e,"name",{value:t,configurable:!0});import{createHash as j,randomBytes as I,randomUUID as $}from"node:crypto";import{createServer as F}from"node:http";import{RunError as p}from"../runs/operations.js";import{ANTHROPIC_PROVIDER_ID as m,OPENAI_CODEX_PROVIDER_ID as P,commitManagedLogin as H,readSubscriptionPool as q}from"../subscription-state.js";const O=900,x="9d1c250a-e61b-44d9-88ed-5944d1962f5e",z="https://claude.ai/oauth/authorize",B="https://console.anthropic.com/oauth/code/callback",S={port:53692,path:"/callback",redirect:"http://localhost:53692/callback"},J="org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload",A="app_EMoamEEZ73f0CkXaXp7hrann",V="https://auth.openai.com/codex/device",T="https://auth.openai.com/deviceauth/callback",C={port:1455,path:"/auth/callback",redirect:"http://localhost:1455/auth/callback"},G="openid profile email offline_access",K=900,X="https://api.openai.com/auth",W=a(()=>process.env.CRTR_MODEL_AUTH_ANTHROPIC_TOKEN_URL||"https://platform.claude.com/v1/oauth/token","anthropicTokenUrl"),y=a(()=>(process.env.CRTR_MODEL_AUTH_OPENAI_BASE||"https://auth.openai.com").replace(/\/$/,""),"openaiBase"),f=new Map,v=new Map;function k(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}a(k,"base64url");function Z(){const e=k(I(32));return{verifier:e,challenge:k(j("sha256").update(e).digest())}}a(Z,"pkce");function R(e){if(e==="openai")return P;if(e===m||e===P)return e;throw new p(400,"invalid_request","provider must be anthropic or openai-codex","provider")}a(R,"managedProvider");function de(e){return R(e)}a(de,"modelAuthProvider");function l(e,t,r){if(e.status==="pending"){e.status=t,r!==void 0&&(e.message=r),clearTimeout(e.timer),e.abort.abort(),e.server?.close(),e.server?.closeIdleConnections(),v.get(e.provider)===e.id&&v.delete(e.provider);for(const i of e.waiters)i();e.waiters.clear(),setTimeout(()=>{f.get(e.id)===e&&f.delete(e.id)},6e4).unref()}}a(l,"settle");async function L(e,t){if(e.status!=="pending")throw new Error("the sign-in ended before the credential was written");await H(e.provider,e.label,{access:t.access,refresh:t.refresh,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},lastRateLimitedAt:e.lastRateLimitedAt,autoLabel:e.label===void 0})}a(L,"writeCredential");async function N(e,t,r){const i=await fetch(W(),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:x,code:t,state:r,redirect_uri:e.redirectUri,code_verifier:e.verifier}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!i.ok)throw new Error(`Anthropic token exchange failed (${i.status})`);const n=await i.json();if(typeof n.access_token!="string"||typeof n.refresh_token!="string"||typeof n.expires_in!="number"||!Number.isFinite(n.expires_in))throw new Error("Anthropic token exchange returned no credential");await L(e,{access:n.access_token,refresh:n.refresh_token,expires:Date.now()+n.expires_in*1e3-300*1e3})}a(N,"exchangeAnthropic");function Y(e){const t=e.split(".")[1];let r;try{r=JSON.parse(Buffer.from(t??"","base64url").toString("utf8"))[X]?.chatgpt_account_id}catch{r=void 0}if(typeof r!="string"||r==="")throw new Error("OpenAI token carries no ChatGPT account id");return r}a(Y,"openaiAccountId");async function D(e,t,r,i){const n=await fetch(`${y()}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:A,code:t,code_verifier:r,redirect_uri:i}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!n.ok)throw new Error(`OpenAI token exchange failed (${n.status})`);const o=await n.json();if(typeof o.access_token!="string"||typeof o.refresh_token!="string"||typeof o.expires_in!="number")throw new Error("OpenAI token exchange returned no credential");await L(e,{access:o.access_token,refresh:o.refresh_token,expires:Date.now()+o.expires_in*1e3,accountId:Y(o.access_token)})}a(D,"exchangeOpenAI");function Q(e,t){return new Promise((r,i)=>{if(t.aborted){i(new Error("flow ended"));return}const n=a(()=>{clearTimeout(o),i(new Error("flow ended"))},"onAbort"),o=setTimeout(()=>{t.removeEventListener("abort",n),r()},e);t.addEventListener("abort",n,{once:!0})})}a(Q,"sleep");async function ee(e,t){const r=Math.min(e.expiresAt,Date.now()+K*1e3);let i=Math.max(1e3,Math.floor(t.intervalS*1e3));try{for(;Date.now()<r&&(await Q(Math.min(i,Math.max(0,r-Date.now())),e.abort.signal),!(Date.now()>=r));){const n=await fetch(`${y()}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_auth_id:t.deviceAuthId,user_code:t.userCode}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(n.ok){const h=await n.json();if(typeof h.authorization_code!="string"||typeof h.code_verifier!="string")throw new Error("OpenAI device approval returned no code");await D(e,h.authorization_code,h.code_verifier,T),l(e,"connected");return}if(n.status===403||n.status===404)continue;const o=await n.text().catch(()=>"");let c;try{const h=JSON.parse(o).error;c=typeof h=="object"&&h!==null?h.code:h}catch{c=void 0}if(c!=="deviceauth_authorization_pending"){if(c==="slow_down"){i+=5e3;continue}throw new Error(`OpenAI device sign-in failed (${n.status})`)}}l(e,"expired","the OpenAI code expired")}catch(n){e.status==="pending"&&l(e,"failed",n instanceof Error?n.message:String(n))}}a(ee,"pollDevice");function M(e,t){const r=F((i,n)=>{const o=new URL(i.url??"/","http://localhost"),c=a((_,w)=>{n.writeHead(_,{"Content-Type":"text/plain; charset=utf-8",Connection:"close"}),n.end(w)},"reply");if(o.pathname!==t.path){c(404,"Not found.");return}const h=o.searchParams.get("code");if(o.searchParams.get("state")!==e.state||!h){c(400,"Sign-in could not be completed: state mismatch or missing code.");return}if(e.status!=="pending"||e.exchanging){c(409,"This sign-in has already finished.");return}e.exchanging=!0,(e.provider===m?N(e,h,e.state):D(e,h,e.verifier,e.redirectUri)).then(()=>{c(200,"Signed in. You can close this window."),l(e,"connected")},_=>{c(502,"The vendor refused the sign-in."),l(e,"failed",_ instanceof Error?_.message:String(_))})});return e.server=r,new Promise((i,n)=>{r.once("error",o=>n(new p(409,"conflict",`cannot listen on localhost:${t.port} for the vendor redirect (${o.code??o.message})`,"redirect"))),r.listen(t.port,"127.0.0.1",()=>i())})}a(M,"listenLoopback");async function ue(e){const t=R(e.provider);if(e.redirect!==void 0&&e.redirect!=="loopback")throw new p(400,"invalid_request",'redirect must be "loopback" when present',"redirect");if(e.label!==void 0&&typeof e.label!="string")throw new p(400,"invalid_request","label must be a string when present","label");const r=typeof e.label=="string"&&e.label.trim()?e.label.trim():void 0,i=v.get(t);if(i!==void 0){const u=f.get(i);u&&l(u,"failed","replaced by a newer sign-in")}const{verifier:n,challenge:o}=Z(),c=e.redirect==="loopback",h=Date.now()+O*1e3,d={id:$(),provider:t,kind:c?"loopback":t===m?"code_page":"device",state:t===m?n:I(16).toString("hex"),verifier:n,redirectUri:t===m?c?S.redirect:B:c?C.redirect:T,expiresAt:h,status:"pending",...e.jti?{jti:e.jti}:{},...r?{label:r}:{},lastRateLimitedAt:Math.max(0,...q(t).map(u=>u.lastRateLimitedAt)),abort:new AbortController,timer:setTimeout(()=>l(d,"expired","the sign-in expired"),O*1e3),waiters:new Set,exchanging:!1};d.timer.unref(),te(d);const _=a(()=>new p(409,"conflict","a newer sign-in for this provider replaced this one","provider"),"replacedDuringStart"),w={flow_id:d.id,provider:t,expires_at:new Date(h).toISOString()};try{if(t===m){const s=new URLSearchParams;if(s.set("code","true"),s.set("client_id",x),s.set("response_type","code"),s.set("redirect_uri",d.redirectUri),s.set("scope",J),s.set("code_challenge",o),s.set("code_challenge_method","S256"),s.set("state",d.state),c&&await M(d,S),d.status!=="pending")throw _();return{...w,url:`${z}?${s.toString()}`,instructions:c?"Sign in to Claude in your browser; this finishes by itself.":"Sign in to Claude, then copy the code Claude shows and paste it here."}}if(c){const s=new URL("https://auth.openai.com/oauth/authorize");if(s.searchParams.set("response_type","code"),s.searchParams.set("client_id",A),s.searchParams.set("redirect_uri",d.redirectUri),s.searchParams.set("scope",G),s.searchParams.set("code_challenge",o),s.searchParams.set("code_challenge_method","S256"),s.searchParams.set("state",d.state),s.searchParams.set("id_token_add_organizations","true"),s.searchParams.set("codex_cli_simplified_flow","true"),s.searchParams.set("originator","pi"),await M(d,C),d.status!=="pending")throw _();return{...w,url:s.toString(),instructions:"Sign in to ChatGPT in your browser; this finishes by itself."}}const u=await fetch(`${y()}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:A}),signal:AbortSignal.timeout(3e4)});if(!u.ok)throw new p(502,"server_error",`OpenAI refused to issue a device code (${u.status})`);const g=await u.json(),b=typeof g.interval=="string"?Number(g.interval.trim()):g.interval;if(typeof g.device_auth_id!="string"||typeof g.user_code!="string"||typeof b!="number"||!Number.isFinite(b)||b<0)throw new p(502,"server_error","OpenAI returned an invalid device code");if(d.status!=="pending")throw _();return ee(d,{deviceAuthId:g.device_auth_id,userCode:g.user_code,intervalS:b}),{...w,url:V,user_code:g.user_code,instructions:"Open the link, sign in to ChatGPT, and enter the code. The code expires in 15 minutes."}}catch(u){throw l(d,"failed",u instanceof Error?u.message:String(u)),f.delete(d.id),u instanceof p?u:new p(502,"server_error",`vendor sign-in could not start: ${u instanceof Error?u.message:String(u)}`)}}a(ue,"startModelAuthFlow");function te(e){f.set(e.id,e),v.set(e.provider,e.id)}a(te,"register");function he(e){const t=f.get(e);if(t)return l(t,"failed","cancelled"),E(t)}a(he,"cancelModelAuthFlow");function re(e){const t=e.trim();if(!t)return{};try{const r=new URL(t);return{code:r.searchParams.get("code")??void 0,state:r.searchParams.get("state")??void 0}}catch{}if(t.includes("#")){const[r,i]=t.split("#",2);return{code:r,state:i}}if(t.includes("code=")){const r=new URLSearchParams(t);return{code:r.get("code")??void 0,state:r.get("state")??void 0}}return{code:t}}a(re,"parseCodeInput");function ne(e){const t=typeof e=="string"?f.get(e):void 0;if(!t||t.status!=="pending"||Date.now()>=t.expiresAt)throw new p(400,"invalid_request","no in-flight sign-in has this flow_id","flow_id");return t}a(ne,"pendingFlow");async function pe(e,t){const r=ne(e);if(r.kind!=="code_page")throw new p(400,"invalid_request","this sign-in completes without a pasted code","flow_id");if(r.exchanging)throw new p(400,"invalid_request","this sign-in is already being completed","flow_id");if(typeof t!="string")throw new p(400,"invalid_request","input must be the code Claude shows","input");const{code:i,state:n}=re(t);if(!i)throw new p(400,"invalid_request","input must be the code Claude shows","input");if(n!==void 0&&n!==r.state)throw new p(400,"invalid_request","the pasted code belongs to a different sign-in","state");r.exchanging=!0;try{await N(r,i,n??r.state)}catch(o){throw l(r,"failed",o instanceof Error?o.message:String(o)),new p(502,"server_error","Anthropic refused the code")}return l(r,"connected"),{flow_id:r.id,provider:r.provider,status:"connected"}}a(pe,"completeModelAuthFlow");function E(e){return{flow_id:e.id,provider:e.provider,status:e.status,...e.message?{message:e.message}:{},...e.jti?{jti:e.jti}:{}}}a(E,"view");function le(e){const t=f.get(e);return t?E(t):void 0}a(le,"readModelAuthFlow");async function fe(e,t,r){const i=f.get(e);if(i)return i.status==="pending"&&t>0&&!r?.aborted&&await new Promise(n=>{const o=a(()=>{clearTimeout(c),r?.removeEventListener("abort",o),i.waiters.delete(o),n()},"done"),c=setTimeout(o,t);r?.addEventListener("abort",o,{once:!0}),i.waiters.add(o)}),E(i)}a(fe,"waitModelAuthFlow");function _e(){for(const e of f.values())l(e,"failed","reset");f.clear(),v.clear()}a(_e,"resetModelAuthFlowsForTest");export{O as MODEL_AUTH_FLOW_TTL_S,he as cancelModelAuthFlow,pe as completeModelAuthFlow,de as modelAuthProvider,le as readModelAuthFlow,_e as resetModelAuthFlowsForTest,ue as startModelAuthFlow,fe as waitModelAuthFlow};
@@ -0,0 +1,4 @@
1
+ export declare function handoffJtiConsumed(jti: string): boolean;
2
+ /** Record `jti` as consumed until `exp`; false when it already was. Expired
3
+ * entries are pruned on every write. */
4
+ export declare function consumeHandoffJti(jti: string, exp: number): boolean;
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var e=(t,n)=>c(t,"name",{value:n,configurable:!0});import{join as u}from"node:path";import{atomicWriteJson as a,readJsonIfExists as m}from"../fs-utils.js";import{secretsDir as d}from"../layout.js";function i(){return u(d(),"vendor-handoff-jti.json")}e(i,"jtiPath");function f(t){const n=m(i())??{},o={};for(const[s,r]of Object.entries(n))typeof r=="number"&&r>t&&(o[s]=r);return o}e(f,"readLive");function b(t){return Object.hasOwn(f(Date.now()/1e3),t)}e(b,"handoffJtiConsumed");function v(t,n){const o=f(Date.now()/1e3);return Object.hasOwn(o,t)?!1:(o[t]=n,a(i(),o,{mode:384}),!0)}e(v,"consumeHandoffJti");export{v as consumeHandoffJti,b as handoffJtiConsumed};
@@ -1 +1 @@
1
- var N=Object.defineProperty;var u=(e,t)=>N(e,"name",{value:t,configurable:!0});import{readMergedLaunchConfig as U}from"./config.js";import{isManagedProvider as w,readRotationConfig as E,readSubscriptionPool as P,resolveProviderCandidates as D}from"./subscription-state.js";const b=["ultra","strong","medium","light"],L=new Set(["off","minimal","low","medium","high","xhigh","max"]);function x(e){const t=e.indexOf("/");if(t<=0||t===e.length-1)return;const o=e.slice(0,t),n=e.slice(t+1),s=n.lastIndexOf(":"),f=s>0?n.slice(s+1).toLowerCase():void 0;return{providerId:o,modelId:f!==void 0&&L.has(f)?n.slice(0,s):n,...f!==void 0&&L.has(f)&&f!=="off"?{thinkingLevel:f}:{}}}u(x,"parseModelSpec");function G(e){const t=u(o=>{const n=e[o].strong.slice(0,e[o].strong.indexOf("/"));return{family:o,credentialSource:"default",providerId:n,models:e[o]}},"route");return{anthropic:t("anthropic"),openai:t("openai")}}u(G,"synthesizeRoutes");function M(e,t){return[e,...t.filter(o=>o!==e)]}u(M,"ordered");function H(e,t){return M(e,t).filter((o,n,s)=>s.indexOf(o)===n)}u(H,"strengths");function $(e,t,o){const n=U(t,o??null),s={...n.modelRoutes??{},...n.legacyModelRoutes??{}},f=Object.keys(s).length>0?s:G(n.modelLadders),a=Object.entries(f),m=n.modelRouting?.strengthFallback??[E().defaultFallbackStrength??"strong"],S=a.map(([,r])=>r.family).filter((r,d,l)=>l.indexOf(r)===d),I=a.map(([,r])=>r.credentialSource).filter((r,d,l)=>l.indexOf(r)===d);if(e.kind==="exact"){const r=x(e.spec);return r?[{routeId:"exact",credentialSource:"exact",family:r.providerId,strength:"strong",...r,rank:0}]:[]}const c=e.kind==="concrete"?x(e.spec):void 0,v=e.kind==="logical"?e:void 0,i=u((r,d)=>{const l=x(r);return l!==void 0&&c!==void 0&&l.providerId===c.providerId&&l.modelId===c.modelId&&(!d||l.thinkingLevel===c.thinkingLevel)},"matchesConcrete"),p=c===void 0?void 0:a.find(([,r])=>Object.values(r.models).some(d=>i(d,!1))),y=v?.strength??(()=>{if(!c)return"strong";for(const r of[!0,!1])for(const d of r?b:[...b].reverse())if(a.some(([,l])=>{const h=l.models[d];return h!==void 0&&i(h,r)}))return d;return"strong"})(),O=v?.family??p?.[1].family??c?.providerId??"anthropic",A=c?I:n.modelRouting?.credentialSourceOrder??I,T=c?[O]:n.modelRouting?.familyOrder??S,R=[],C=new Set,F=u((r,d,l,h)=>{const g=x(h);if(!g||c&&g.modelId!==c.modelId)return;const k=JSON.stringify([r,g.providerId,g.modelId,g.thinkingLevel]);C.has(k)||(C.add(k),R.push({routeId:r,credentialSource:d.credentialSource,family:d.family,strength:l,...g,rank:R.length}))},"append");if(c){const[r,d]=p??["concrete",{family:O,credentialSource:"default"}];F(r,d,y,e.spec)}for(const r of A)for(const d of c?[y]:H(y,m))for(const l of M(O,T))for(const[h,g]of a){if(g.credentialSource!==r||g.family!==l)continue;const k=g.models[d];k&&F(h,g,d,k)}return R.map((r,d)=>({...r,rank:d}))}u($,"expandModelCandidates");function W(e,t,o={}){if(e===void 0||e.kind==="logical")return;const n=$(e,o.cwd,o.profileId)[0];if(!(n===void 0||t.find(n.providerId,n.modelId)!==void 0))return{request:e,candidate:n,reason:"unregistered"}}u(W,"unregisteredConcreteModel");function j(e,t,o=Date.now()){const n=t.find(e.providerId,e.modelId);if(n===void 0)return{registered:!1,authenticated:!1};if(!w(e.providerId))return{registered:!0,authenticated:t.hasConfiguredAuth(n)};const s=P(e.providerId).filter(a=>a.authFailure===void 0),f=s.length>0&&s.every(a=>(a.rateLimitedUntil||0)>o);return{registered:!0,authenticated:s.length>0||t.hasConfiguredAuth(n),...f?{coolingUntil:Math.min(...s.map(a=>a.rateLimitedUntil||0))}:{}}}u(j,"probeRouteAvailability");function X(e,t,o={}){const n=$(e,o.cwd,o.profileId),s=new Set(n.map(i=>`${i.providerId}/${i.modelId}`)),f=e.kind==="logical"?t.getAll().filter(i=>!s.has(`${i.provider}/${i.id}`)).map((i,p)=>({routeId:`registry:${i.provider}/${i.id}`,credentialSource:"registry",family:i.provider,strength:"strong",providerId:i.provider,modelId:i.id,rank:n.length+p})):[],a=[...n,...f],m=o.now??Date.now(),S=a.some(i=>{const p=j(i,t,m);return w(i.providerId)&&p.registered&&p.authenticated}),I=D(a.map(i=>({...i,...j(i,t,m),automaticFallback:i.routeId.startsWith("registry:")?w(i.providerId)||!S:!0})),m,{pinnedToFirst:e.kind==="exact"}),c=I.candidates[0],v=c===void 0?void 0:t.find(c.providerId,c.modelId);return{...c!==void 0&&v!==void 0?{selected:{model:v,candidate:c}}:{},rejected:I.rejected}}u(X,"selectInitialModelRoute");function _(e,t,o){if(e){if(o)return{kind:"exact",spec:e};if(t){const n=t.lastIndexOf("/"),s=n>0?t.slice(n+1):"";if(b.includes(s))return{kind:"logical",family:t.slice(0,n),strength:s,spec:e}}return{kind:"concrete",spec:e}}}u(_,"modelRequestFromConfig");export{$ as expandModelCandidates,_ as modelRequestFromConfig,x as parseModelSpec,j as probeRouteAvailability,X as selectInitialModelRoute,W as unregisteredConcreteModel};
1
+ var N=Object.defineProperty;var u=(e,t)=>N(e,"name",{value:t,configurable:!0});import{readMergedLaunchConfig as U}from"./config.js";import{isManagedProvider as w,readRotationConfig as E,readSubscriptionPool as P,resolveProviderCandidates as D}from"./subscription-state.js";const b=["ultra","strong","medium","light"],L=new Set(["off","minimal","low","medium","high","xhigh","max"]);function x(e){const t=e.indexOf("/");if(t<=0||t===e.length-1)return;const o=e.slice(0,t),n=e.slice(t+1),s=n.lastIndexOf(":"),f=s>0?n.slice(s+1).toLowerCase():void 0;return{providerId:o,modelId:f!==void 0&&L.has(f)?n.slice(0,s):n,...f!==void 0&&L.has(f)&&f!=="off"?{thinkingLevel:f}:{}}}u(x,"parseModelSpec");function G(e){const t=u(o=>{const n=e[o].strong.slice(0,e[o].strong.indexOf("/"));return{family:o,credentialSource:"default",providerId:n,models:e[o]}},"route");return{anthropic:t("anthropic"),openai:t("openai")}}u(G,"synthesizeRoutes");function M(e,t){return[e,...t.filter(o=>o!==e)]}u(M,"ordered");function H(e,t){return M(e,t).filter((o,n,s)=>s.indexOf(o)===n)}u(H,"strengths");function $(e,t,o){if(e.kind==="exact"){const r=x(e.spec);return r?[{routeId:"exact",credentialSource:"exact",family:r.providerId,strength:"strong",...r,rank:0}]:[]}const n=U(t,o??null),s={...n.modelRoutes??{},...n.legacyModelRoutes??{}},f=Object.keys(s).length>0?s:G(n.modelLadders),a=Object.entries(f),m=n.modelRouting?.strengthFallback??[E().defaultFallbackStrength??"strong"],S=a.map(([,r])=>r.family).filter((r,d,l)=>l.indexOf(r)===d),I=a.map(([,r])=>r.credentialSource).filter((r,d,l)=>l.indexOf(r)===d),c=e.kind==="concrete"?x(e.spec):void 0,v=e.kind==="logical"?e:void 0,i=u((r,d)=>{const l=x(r);return l!==void 0&&c!==void 0&&l.providerId===c.providerId&&l.modelId===c.modelId&&(!d||l.thinkingLevel===c.thinkingLevel)},"matchesConcrete"),p=c===void 0?void 0:a.find(([,r])=>Object.values(r.models).some(d=>i(d,!1))),y=v?.strength??(()=>{if(!c)return"strong";for(const r of[!0,!1])for(const d of r?b:[...b].reverse())if(a.some(([,l])=>{const h=l.models[d];return h!==void 0&&i(h,r)}))return d;return"strong"})(),O=v?.family??p?.[1].family??c?.providerId??"anthropic",A=c?I:n.modelRouting?.credentialSourceOrder??I,T=c?[O]:n.modelRouting?.familyOrder??S,R=[],C=new Set,F=u((r,d,l,h)=>{const g=x(h);if(!g||c&&g.modelId!==c.modelId)return;const k=JSON.stringify([r,g.providerId,g.modelId,g.thinkingLevel]);C.has(k)||(C.add(k),R.push({routeId:r,credentialSource:d.credentialSource,family:d.family,strength:l,...g,rank:R.length}))},"append");if(c){const[r,d]=p??["concrete",{family:O,credentialSource:"default"}];F(r,d,y,e.spec)}for(const r of A)for(const d of c?[y]:H(y,m))for(const l of M(O,T))for(const[h,g]of a){if(g.credentialSource!==r||g.family!==l)continue;const k=g.models[d];k&&F(h,g,d,k)}return R.map((r,d)=>({...r,rank:d}))}u($,"expandModelCandidates");function W(e,t,o={}){if(e===void 0||e.kind==="logical")return;const n=$(e,o.cwd,o.profileId)[0];if(!(n===void 0||t.find(n.providerId,n.modelId)!==void 0))return{request:e,candidate:n,reason:"unregistered"}}u(W,"unregisteredConcreteModel");function j(e,t,o=Date.now()){const n=t.find(e.providerId,e.modelId);if(n===void 0)return{registered:!1,authenticated:!1};if(!w(e.providerId))return{registered:!0,authenticated:t.hasConfiguredAuth(n)};const s=P(e.providerId).filter(a=>a.authFailure===void 0),f=s.length>0&&s.every(a=>(a.rateLimitedUntil||0)>o);return{registered:!0,authenticated:s.length>0||t.hasConfiguredAuth(n),...f?{coolingUntil:Math.min(...s.map(a=>a.rateLimitedUntil||0))}:{}}}u(j,"probeRouteAvailability");function X(e,t,o={}){const n=$(e,o.cwd,o.profileId),s=new Set(n.map(i=>`${i.providerId}/${i.modelId}`)),f=e.kind==="logical"?t.getAll().filter(i=>!s.has(`${i.provider}/${i.id}`)).map((i,p)=>({routeId:`registry:${i.provider}/${i.id}`,credentialSource:"registry",family:i.provider,strength:"strong",providerId:i.provider,modelId:i.id,rank:n.length+p})):[],a=[...n,...f],m=o.now??Date.now(),S=a.some(i=>{const p=j(i,t,m);return w(i.providerId)&&p.registered&&p.authenticated}),I=D(a.map(i=>({...i,...j(i,t,m),automaticFallback:i.routeId.startsWith("registry:")?w(i.providerId)||!S:!0})),m,{pinnedToFirst:e.kind==="exact"}),c=I.candidates[0],v=c===void 0?void 0:t.find(c.providerId,c.modelId);return{...c!==void 0&&v!==void 0?{selected:{model:v,candidate:c}}:{},rejected:I.rejected}}u(X,"selectInitialModelRoute");function _(e,t,o){if(e){if(o)return{kind:"exact",spec:e};if(t){const n=t.lastIndexOf("/"),s=n>0?t.slice(n+1):"";if(b.includes(s))return{kind:"logical",family:t.slice(0,n),strength:s,spec:e}}return{kind:"concrete",spec:e}}}u(_,"modelRequestFromConfig");export{$ as expandModelCandidates,_ as modelRequestFromConfig,x as parseModelSpec,j as probeRouteAvailability,X as selectInitialModelRoute,W as unregisteredConcreteModel};
@@ -1,3 +1,4 @@
1
+ export declare function descendantStoreDiscoveryWarnings(ancestorRoots: string[]): string[];
1
2
  /**
2
3
  * Every `.crouter` store root strictly BELOW the given ancestor roots' owning
3
4
  * dirs, in owner order then discovery order. Takes the `projectScopeRoots()`
@@ -9,7 +10,7 @@
9
10
  * excluding centrally gives the resolver and lint the identical call with no
10
11
  * duplicated dedupe logic.
11
12
  */
12
- export declare function descendantStoreRoots(ancestorRoots: string[], reportBudgetExceeded?: boolean): string[];
13
+ export declare function descendantStoreRoots(ancestorRoots: string[], reportBudgetExceeded?: boolean, warnings?: string[]): string[];
13
14
  /** Complete descendant-store discovery for state migrations. Unlike the
14
15
  * interactive addressing lane, this filesystem walk has no time or depth
15
16
  * budget, crosses embedded repositories, admits plugin-only `.crouter` roots,
@@ -1,2 +1 @@
1
- var _=Object.defineProperty;var a=(o,i)=>_(o,"name",{value:i,configurable:!0});import{readdirSync as k}from"node:fs";import{dirname as g,join as f,sep as O}from"node:path";import{CRTR_DIR_NAME as l}from"../types.js";import{pathExists as h,realpathOrSelf as m}from"./fs-utils.js";import{gitSync as R}from"./git.js";import{warn as T}from"./output.js";const b=new Set(["node_modules",".git","dist","build",".next",".cache",".yalc",".venv"]),v=6,w=500,D=new Map;function G(o,i=!0){const t=[...o].sort().join(`
2
- `),s=D.get(t);if(s!==void 0)return s;const c=new Set(o.map(r=>m(r))),d=[],e=new Set;for(const r of o){const u=g(r),x=m(u);e.has(x)||(e.add(x),d.push(u))}const n=a(r=>{i&&T(`memory: nested-store discovery under ${r} exceeded its ${w}ms budget \u2014 this result may omit nested stores. To read a document from a known nested store, pass its owner as \`--dir <owner>\`; that exact-store read bypasses discovery.`)},"tripBudget"),p=[],S=new Set,y=a(r=>{const u=m(r);S.has(u)||c.has(u)||(S.add(u),p.push(r))},"add");for(const r of d)h(f(r,".git"))?M(r,y,w,()=>n(r)):$(r,y,Date.now()+w,()=>n(r));return D.set(t,p),p}a(G,"descendantStoreRoots");function M(o,i,t,s){const c=`/${l}/memory/`,d=R(["-C",o,"ls-files","-z","-co","--exclude-standard","--",`*/${l}/memory/*`],void 0,void 0,{timeoutMs:t});if(d.timedOut===!0){s();return}if(d.status===0)for(const e of d.stdout.split("\0")){if(e==="")continue;const n=e.indexOf(c);n<=0||i(f(o,e.slice(0,n).split("/").join(O),l))}}a(M,"collectGitStores");function $(o,i,t,s){E(o,i,{deadline:t,maxDepth:v,trip:s})}a($,"collectWalkStores");function E(o,i,t={}){const s=[{dir:o,depth:0}];for(;s.length>0;){if(t.deadline!==void 0&&Date.now()>t.deadline){t.trip?.();return}const{dir:c,depth:d}=s.pop();if(c!==o){if(t.crossEmbeddedRepos!==!0&&h(f(c,".git")))continue;const n=f(c,l);h(t.includePluginOnly===!0?n:f(n,"memory"))&&i(n)}if(t.maxDepth!==void 0&&d>=t.maxDepth)continue;let e;try{e=k(c,{withFileTypes:!0})}catch{continue}for(const n of e)n.isDirectory()&&(b.has(n.name)||n.name===l||s.push({dir:f(c,n.name),depth:d+1}))}}a(E,"collectWalkStoresFromOwner");function N(o){const i=new Set(o.map(e=>m(e))),t=[],s=new Set,c=a(e=>{const n=m(e);s.has(n)||i.has(n)||(s.add(n),t.push(e))},"add"),d=new Set(o.map(e=>m(g(e))));for(const e of d)E(e,c,{includePluginOnly:!0,crossEmbeddedRepos:!0});return t}a(N,"descendantStoreRootsExhaustive");export{G as descendantStoreRoots,N as descendantStoreRootsExhaustive};
1
+ var D=Object.defineProperty;var a=(t,r)=>D(t,"name",{value:r,configurable:!0});import{readdirSync as E}from"node:fs";import{dirname as x,join as f,sep as R}from"node:path";import{CRTR_DIR_NAME as l}from"../types.js";import{pathExists as p,realpathOrSelf as m}from"./fs-utils.js";import{gitSync as _}from"./git.js";import{warn as v}from"./output.js";const O=new Set(["node_modules",".git","dist","build",".next",".cache",".yalc",".venv"]),T=6,h=500;function C(t){const r=[];return b(t,!1,r),r}a(C,"descendantStoreDiscoveryWarnings");function b(t,r=!0,o=[]){const i=new Set(t.map(s=>m(s))),c=[],d=new Set;for(const s of t){const u=x(s),y=m(u);d.has(y)||(d.add(y),c.push(u))}const e=a(s=>{const u=`memory: nested-store discovery under ${s} exceeded its ${h}ms budget \u2014 this result may omit nested stores. To read a document from a known nested store, pass its owner as \`--dir <owner>\`; that exact-store read bypasses discovery.`;o.push(u),r&&v(u)},"tripBudget"),n=[],w=new Set,S=a(s=>{const u=m(s);w.has(u)||i.has(u)||(w.add(u),n.push(s))},"add");for(const s of c)p(f(s,".git"))?k(s,S,h,()=>e(s)):M(s,S,Date.now()+h,()=>e(s));return n}a(b,"descendantStoreRoots");function k(t,r,o,i){const c=`/${l}/memory/`,d=_(["-C",t,"ls-files","-z","-co","--exclude-standard","--",`*/${l}/memory/*`],void 0,void 0,{timeoutMs:o});if(d.timedOut===!0){i();return}if(d.status===0)for(const e of d.stdout.split("\0")){if(e==="")continue;const n=e.indexOf(c);n<=0||r(f(t,e.slice(0,n).split("/").join(R),l))}}a(k,"collectGitStores");function M(t,r,o,i){g(t,r,{deadline:o,maxDepth:T,trip:i})}a(M,"collectWalkStores");function g(t,r,o={}){const i=[{dir:t,depth:0}];for(;i.length>0;){if(o.deadline!==void 0&&Date.now()>o.deadline){o.trip?.();return}const{dir:c,depth:d}=i.pop();if(c!==t){if(o.crossEmbeddedRepos!==!0&&p(f(c,".git")))continue;const n=f(c,l);p(o.includePluginOnly===!0?n:f(n,"memory"))&&r(n)}if(o.maxDepth!==void 0&&d>=o.maxDepth)continue;let e;try{e=E(c,{withFileTypes:!0})}catch{continue}for(const n of e)n.isDirectory()&&(O.has(n.name)||n.name===l||i.push({dir:f(c,n.name),depth:d+1}))}}a(g,"collectWalkStoresFromOwner");function F(t){const r=new Set(t.map(e=>m(e))),o=[],i=new Set,c=a(e=>{const n=m(e);i.has(n)||r.has(n)||(i.add(n),o.push(e))},"add"),d=new Set(t.map(e=>m(x(e))));for(const e of d)g(e,c,{includePluginOnly:!0,crossEmbeddedRepos:!0});return o}a(F,"descendantStoreRootsExhaustive");export{C as descendantStoreDiscoveryWarnings,b as descendantStoreRoots,F as descendantStoreRootsExhaustive};
@@ -1,2 +1,2 @@
1
- var v=Object.defineProperty;var u=(n,e)=>v(n,"name",{value:e,configurable:!0});const g=new Set(["canvas roster","canvas snapshot","node inspect snapshot","node inspect show","sys context sysprompt"]);function M(n){return g.has(n)}u(M,"suppressOutputForLeaf");function N(n){for(const e of g){const t=e.split(" ");if(t.length<=n.length&&t.every((r,s)=>n[s]===r))return!0}return!1}u(N,"suppressOutputForPath");const b=61529,R=String.fromCodePoint(b),T={bash:String.fromCodePoint(61728),read:String.fromCodePoint(61788),write:String.fromCodePoint(61639),edit:String.fromCodePoint(61508)},w={canvas:61672,capture:61501,device:61705,human:61447,memory:61485,node:61842,pkg:61874,profile:62141,push:61678,search:61442,surface:61704,sys:61459},k={"canvas dashboard":61668,"canvas snapshot":61488,"canvas browse":61774,"canvas attention count":62098,"canvas attention list":61498,"canvas attention map":62073,"canvas revive":61473,"node lifecycle revive":61473,"canvas history search":61442,"canvas history read":61485,"canvas history grep":61616,"node inspect artifacts":61914,"sys daemon start":61515,"sys daemon status":61713,"sys daemon stop":61517,"canvas chord":61441,"surface tmux-spread":61449,"canvas issue new":61832,"canvas prune":61636,"human send":61529,"human review":61508,"human show":61704,"human cancel":61453,"human list":61498,"human resolve":61452,"memory list":61498,"memory read":61485,"memory find":61442,"memory write":61504,"memory edit":61508,"memory history":61914,"memory origin":61883,"memory lint":61770,"node new":61543,"node message send":61664,"node message request":61664,"cron add":61463,"node wait deadline":61463,"node subscription add":61683,"node subscription remove":61942,"node promote":61698,"node yield":62093,"surface node focus":61531,"surface node cycle":61473,"node inspect list":61498,"node inspect show":61550,"node inspect snapshot":61488,"node inspect context":61564,"node lifecycle recycle":61880,"node lifecycle close":61453,"node lifecycle demote":61699,"node config":61459,"cron list":61463,"cron cancel":61534,"pkg plugin install":61465,"pkg plugin remove":61460,"pkg plugin enable":61452,"pkg plugin disable":61534,"pkg plugin update":61473,"pkg plugin list":61498,"pkg plugin show":61550,"pkg market add":61543,"pkg market remove":61460,"pkg market update":61473,"pkg market list":61498,"pkg market browse":61774,"push update":61587,"push final":61726,"search web":61612,"search answer":61557,"search contents":61686,"surface attach to":61926,"sys config get":61465,"sys config set":61504,"sys config path":61563,"sys settings":61459,"sys setup":61613,"sys doctor":61681,"sys context sysprompt":61788,"sys context prompt-review":61442,"sys feedback":61557,"sys update":61473,"sys version":61483,"sys sync":61561};function H(n){let e;for(const[r,s]of Object.entries(k)){const o=r.split(" ");o.length<=n.length&&o.every((i,f)=>n[f]===i)&&(e===void 0||o.length>e.words)&&(e={words:o.length,cp:s})}if(e!==void 0)return String.fromCodePoint(e.cp);const t=n.length>0?w[n[0]]:void 0;return t!==void 0?String.fromCodePoint(t):"\u25C6"}u(H,"iconForPath");function x(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}u(x,"plainObject");function U(n){const e=x(x(n)?.details);if(e===void 0)return[];const t=e.crtrPreviews;return(Array.isArray(t)?t:[e.crtrPreview]).flatMap(s=>{const o=x(s);if(o===void 0||typeof o.path!="string")return[];const i=o.jsonl;return[{path:o.path,result:x(o.result),jsonl:Array.isArray(i)?i.flatMap(f=>{const p=x(f);return p===void 0?[]:[p]}):void 0,error:x(o.error)}]})}u(U,"crtrPreviewRecords");const P=3;function c(n){return n.result}u(c,"record");function a(n,e){const t=n[e];return typeof t=="string"&&t!==""?t:void 0}u(a,"stringField");function m(n,e){return typeof n[e]=="boolean"?n[e]:void 0}u(m,"booleanField");function l(n,e){return typeof n[e]=="number"&&Number.isFinite(n[e])?n[e]:void 0}u(l,"numberField");function $(n,e){const t=n[e];return Array.isArray(t)&&t.every(r=>r!==null&&typeof r=="object"&&!Array.isArray(r))?t:void 0}u($,"arrayField");function D(n){const e=n.replace(/[\\/]+$/,""),t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}u(D,"basename");function A(n,e){return n.length>e?`${n.slice(0,e).trimEnd()}\u2026`:n}u(A,"truncateLine");function S(n,e,t=5){const r=n.map(i=>a(i,e));if(r.some(i=>i===void 0))return;const s=r.slice(0,t),o=r.length-s.length;return o>0?`${s.join(", ")}, \u2026 ${o} more`:s.join(", ")}u(S,"topNames");function C(n){const e=n.error;if(e===void 0)return null;const t=a(e,"error"),r=a(e,"message");return t===void 0||r===void 0?null:[{text:t,tone:"error"},{text:A(r,160),tone:"muted"}]}u(C,"summarizeError");function _(n){const e=c(n);if(e===void 0)return null;const t=a(e,"name"),r=a(e,"kind"),s=a(e,"scope"),o=a(e,"content");if(t===void 0||r===void 0||s===void 0)return null;const i=[{text:`${t} \xB7 ${r} \xB7 ${s}`}];if(o!==void 0){const f=o.trim().split(`
2
- `).slice(0,P);f.length>0&&f.some(p=>p!=="")&&i.push({text:""},...f.map(p=>({text:p})))}return i}u(_,"summarizeMemoryRead");function j(n,e=!1){return t=>{const r=c(t),s=r===void 0?void 0:l(r,"count")??l(r,"total");return s===void 0?null:s===0&&e?[{text:`PASS \xB7 no ${n}`,tone:"success"}]:[{text:`${s} ${n}`,tone:s===0?"muted":"plain"}]}}u(j,"summarizeCount");function d(n,e="items"){return t=>{const r=c(t);if(r===void 0)return null;const s=$(r,e),o=l(r,"total")??s?.length;if(s===void 0||o===void 0)return null;const i=[{text:`${o} ${n}`,tone:o===0?"muted":"plain"}],f=S(s,"name");return f!==void 0&&f!==""&&i.push({text:f,tone:"muted"}),i}}u(d,"summarizeArray");function O(n){const t=c(n)?.counts;if(t===null||typeof t!="object"||Array.isArray(t))return null;const r=Object.entries(t);if(r.some(([,i])=>typeof i!="number"))return null;const s=r.reduce((i,[,f])=>i+f,0);if(s===0)return[{text:"PASS \xB7 no pending asks",tone:"success"}];const o=r.filter(([,i])=>i>0).sort((i,f)=>f[1]-i[1])[0];return o===void 0?null:[{text:`${s} asks`,tone:"warning"},{text:`hottest: ${o[0]} (${o[1]})`,tone:"muted"}]}u(O,"summarizeAttentionMap");function h(n,e,t){return r=>{const s=c(r);if(s===void 0)return null;const o=m(s,n);if(o===void 0)return null;const i=l(s,"pid")??l(s,"existing_pid");return[{text:o?`${e}${i===void 0?"":` \xB7 pid ${i}`}`:t,tone:o?"success":"muted"}]}}u(h,"summarizeDaemon");function E(n){const e=c(n);if(e===void 0||a(e,"page_id")===void 0)return null;const t=m(e,"reply");return t===void 0?null:[{text:t?"page sent \u2192 waiting on human":"announcement sent",tone:t?"accent":"success"}]}u(E,"summarizeHumanSend");function z(n){const e=c(n);if(e===void 0)return null;const t=m(e,"resolved"),r=a(e,"job_id");return t===void 0||r===void 0?null:[{text:`${t?"resolved":"not resolved"} ${r}`,tone:t?"success":"warning"}]}u(z,"summarizeHumanResolve");function y(n){const e=c(n);if(e===void 0)return null;const t=a(e,"status");return t===void 0?null:[{text:t,tone:["done","success","submitted","filed"].includes(t)?"success":t==="failed"?"error":"plain"}]}u(y,"summarizeStatus");function F(n){const e=n.jsonl;if(e===void 0)return null;const t=e.filter(r=>a(r,"name")!==void 0&&l(r,"projects_count")!==void 0);return t.length===0&&e.length>0?null:[{text:`${t.length} profile${t.length===1?"":"s"}`},...t.slice(0,5).map(r=>({text:`${a(r,"name")} \xB7 ${l(r,"projects_count")} projects`,tone:"muted"}))]}u(F,"summarizeProfileList");const I=[{path:"memory read",run:_},{path:"memory list",run:d("docs")},{path:"memory find",run:d("hits","hits")},{path:"canvas attention count",run:j("pending asks",!0)},{path:"canvas attention list",run:d("pending asks")},{path:"canvas attention map",run:O},{path:"human send",run:E},{path:"human list",run:d("pending")},{path:"human resolve",run:z},{path:"pkg plugin list",run:d("plugins")},{path:"pkg market list",run:d("marketplaces")},{path:"pkg market browse",run:d("plugins")},{path:"canvas dashboard",run:d("nodes","rows")},{path:"node inspect list",run:d("nodes","nodes")},{path:"sys daemon start",run:h("started","started","already running")},{path:"sys daemon status",run:h("running","running","not running")},{path:"sys daemon stop",run:h("stopped","stopped","was not running")},{path:"sys update",run:y},{path:"sys feedback",run:y},{path:"profile list",run:F}];function Y(n,e=[]){const t=C(n);return t!==null?t:I.find(({path:s})=>s===n.path)?.run(n,e)??null}u(Y,"summarizePath");export{R as HELP_ICON,k as LEAF_ICON_CP,I as SUMMARIZERS,g as SUPPRESS_OUTPUT_LEAVES,T as TOOL_ICON,U as crtrPreviewRecords,H as iconForPath,Y as summarizePath,M as suppressOutputForLeaf,N as suppressOutputForPath};
1
+ var v=Object.defineProperty;var u=(n,e)=>v(n,"name",{value:e,configurable:!0});const g=new Set(["canvas roster","canvas snapshot","node inspect snapshot","node inspect show","sys context sysprompt"]);function M(n){return g.has(n)}u(M,"suppressOutputForLeaf");function N(n){for(const e of g){const t=e.split(" ");if(t.length<=n.length&&t.every((r,s)=>n[s]===r))return!0}return!1}u(N,"suppressOutputForPath");const b=61529,R=String.fromCodePoint(b),T={bash:String.fromCodePoint(61728),read:String.fromCodePoint(61788),write:String.fromCodePoint(61639),edit:String.fromCodePoint(61508)},w={canvas:61672,capture:61501,device:61705,human:61447,memory:61485,node:61842,pkg:61874,profile:62141,push:61678,"exa-search":61442,surface:61704,sys:61459},k={"canvas dashboard":61668,"canvas snapshot":61488,"canvas browse":61774,"canvas attention count":62098,"canvas attention list":61498,"canvas attention map":62073,"canvas revive":61473,"node lifecycle revive":61473,"canvas history search":61442,"canvas history read":61485,"canvas history grep":61616,"node inspect artifacts":61914,"sys daemon start":61515,"sys daemon status":61713,"sys daemon stop":61517,"canvas chord":61441,"surface tmux-spread":61449,"canvas issue new":61832,"canvas prune":61636,"human send":61529,"human review":61508,"human show":61704,"human cancel":61453,"human list":61498,"human resolve":61452,"memory list":61498,"memory read":61485,"memory find":61442,"memory write":61504,"memory edit":61508,"memory history":61914,"memory origin":61883,"memory lint":61770,"node new":61543,"node message send":61664,"node message request":61664,"cron add":61463,"node wait deadline":61463,"node subscription add":61683,"node subscription remove":61942,"node promote":61698,"node yield":62093,"surface node focus":61531,"surface node cycle":61473,"node inspect list":61498,"node inspect show":61550,"node inspect snapshot":61488,"node inspect context":61564,"node lifecycle recycle":61880,"node lifecycle close":61453,"node lifecycle demote":61699,"node config":61459,"cron list":61463,"cron cancel":61534,"pkg plugin install":61465,"pkg plugin remove":61460,"pkg plugin enable":61452,"pkg plugin disable":61534,"pkg plugin update":61473,"pkg plugin list":61498,"pkg plugin show":61550,"pkg market add":61543,"pkg market remove":61460,"pkg market update":61473,"pkg market list":61498,"pkg market browse":61774,"push update":61587,"push final":61726,"exa-search web":61612,"exa-search answer":61557,"exa-search contents":61686,"surface attach to":61926,"sys config get":61465,"sys config set":61504,"sys config path":61563,"sys settings":61459,"sys setup":61613,"sys doctor":61681,"sys context sysprompt":61788,"sys context prompt-review":61442,"sys feedback":61557,"sys update":61473,"sys version":61483,"sys sync":61561};function H(n){let e;for(const[r,s]of Object.entries(k)){const o=r.split(" ");o.length<=n.length&&o.every((i,a)=>n[a]===i)&&(e===void 0||o.length>e.words)&&(e={words:o.length,cp:s})}if(e!==void 0)return String.fromCodePoint(e.cp);const t=n.length>0?w[n[0]]:void 0;return t!==void 0?String.fromCodePoint(t):"\u25C6"}u(H,"iconForPath");function x(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}u(x,"plainObject");function U(n){const e=x(x(n)?.details);if(e===void 0)return[];const t=e.crtrPreviews;return(Array.isArray(t)?t:[e.crtrPreview]).flatMap(s=>{const o=x(s);if(o===void 0||typeof o.path!="string")return[];const i=o.jsonl;return[{path:o.path,result:x(o.result),jsonl:Array.isArray(i)?i.flatMap(a=>{const p=x(a);return p===void 0?[]:[p]}):void 0,error:x(o.error)}]})}u(U,"crtrPreviewRecords");const P=3;function c(n){return n.result}u(c,"record");function f(n,e){const t=n[e];return typeof t=="string"&&t!==""?t:void 0}u(f,"stringField");function m(n,e){return typeof n[e]=="boolean"?n[e]:void 0}u(m,"booleanField");function l(n,e){return typeof n[e]=="number"&&Number.isFinite(n[e])?n[e]:void 0}u(l,"numberField");function $(n,e){const t=n[e];return Array.isArray(t)&&t.every(r=>r!==null&&typeof r=="object"&&!Array.isArray(r))?t:void 0}u($,"arrayField");function D(n){const e=n.replace(/[\\/]+$/,""),t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}u(D,"basename");function A(n,e){return n.length>e?`${n.slice(0,e).trimEnd()}\u2026`:n}u(A,"truncateLine");function S(n,e,t=5){const r=n.map(i=>f(i,e));if(r.some(i=>i===void 0))return;const s=r.slice(0,t),o=r.length-s.length;return o>0?`${s.join(", ")}, \u2026 ${o} more`:s.join(", ")}u(S,"topNames");function C(n){const e=n.error;if(e===void 0)return null;const t=f(e,"error"),r=f(e,"message");return t===void 0||r===void 0?null:[{text:t,tone:"error"},{text:A(r,160),tone:"muted"}]}u(C,"summarizeError");function _(n){const e=c(n);if(e===void 0)return null;const t=f(e,"name"),r=f(e,"kind"),s=f(e,"scope"),o=f(e,"content");if(t===void 0||r===void 0||s===void 0)return null;const i=[{text:`${t} \xB7 ${r} \xB7 ${s}`}];if(o!==void 0){const a=o.trim().split(`
2
+ `).slice(0,P);a.length>0&&a.some(p=>p!=="")&&i.push({text:""},...a.map(p=>({text:p})))}return i}u(_,"summarizeMemoryRead");function j(n,e=!1){return t=>{const r=c(t),s=r===void 0?void 0:l(r,"count")??l(r,"total");return s===void 0?null:s===0&&e?[{text:`PASS \xB7 no ${n}`,tone:"success"}]:[{text:`${s} ${n}`,tone:s===0?"muted":"plain"}]}}u(j,"summarizeCount");function d(n,e="items"){return t=>{const r=c(t);if(r===void 0)return null;const s=$(r,e),o=l(r,"total")??s?.length;if(s===void 0||o===void 0)return null;const i=[{text:`${o} ${n}`,tone:o===0?"muted":"plain"}],a=S(s,"name");return a!==void 0&&a!==""&&i.push({text:a,tone:"muted"}),i}}u(d,"summarizeArray");function O(n){const t=c(n)?.counts;if(t===null||typeof t!="object"||Array.isArray(t))return null;const r=Object.entries(t);if(r.some(([,i])=>typeof i!="number"))return null;const s=r.reduce((i,[,a])=>i+a,0);if(s===0)return[{text:"PASS \xB7 no pending asks",tone:"success"}];const o=r.filter(([,i])=>i>0).sort((i,a)=>a[1]-i[1])[0];return o===void 0?null:[{text:`${s} asks`,tone:"warning"},{text:`hottest: ${o[0]} (${o[1]})`,tone:"muted"}]}u(O,"summarizeAttentionMap");function h(n,e,t){return r=>{const s=c(r);if(s===void 0)return null;const o=m(s,n);if(o===void 0)return null;const i=l(s,"pid")??l(s,"existing_pid");return[{text:o?`${e}${i===void 0?"":` \xB7 pid ${i}`}`:t,tone:o?"success":"muted"}]}}u(h,"summarizeDaemon");function E(n){const e=c(n);if(e===void 0||f(e,"page_id")===void 0)return null;const t=m(e,"reply");return t===void 0?null:[{text:t?"page sent \u2192 waiting on human":"announcement sent",tone:t?"accent":"success"}]}u(E,"summarizeHumanSend");function z(n){const e=c(n);if(e===void 0)return null;const t=m(e,"resolved"),r=f(e,"job_id");return t===void 0||r===void 0?null:[{text:`${t?"resolved":"not resolved"} ${r}`,tone:t?"success":"warning"}]}u(z,"summarizeHumanResolve");function y(n){const e=c(n);if(e===void 0)return null;const t=f(e,"status");return t===void 0?null:[{text:t,tone:["done","success","submitted","filed"].includes(t)?"success":t==="failed"?"error":"plain"}]}u(y,"summarizeStatus");function F(n){const e=n.jsonl;if(e===void 0)return null;const t=e.filter(r=>f(r,"name")!==void 0&&l(r,"projects_count")!==void 0);return t.length===0&&e.length>0?null:[{text:`${t.length} profile${t.length===1?"":"s"}`},...t.slice(0,5).map(r=>({text:`${f(r,"name")} \xB7 ${l(r,"projects_count")} projects`,tone:"muted"}))]}u(F,"summarizeProfileList");const I=[{path:"memory read",run:_},{path:"memory list",run:d("docs")},{path:"memory find",run:d("hits","hits")},{path:"canvas attention count",run:j("pending asks",!0)},{path:"canvas attention list",run:d("pending asks")},{path:"canvas attention map",run:O},{path:"human send",run:E},{path:"human list",run:d("pending")},{path:"human resolve",run:z},{path:"pkg plugin list",run:d("plugins")},{path:"pkg market list",run:d("marketplaces")},{path:"pkg market browse",run:d("plugins")},{path:"canvas dashboard",run:d("nodes","rows")},{path:"node inspect list",run:d("nodes","nodes")},{path:"sys daemon start",run:h("started","started","already running")},{path:"sys daemon status",run:h("running","running","not running")},{path:"sys daemon stop",run:h("stopped","stopped","was not running")},{path:"sys update",run:y},{path:"sys feedback",run:y},{path:"profile list",run:F}];function Y(n,e=[]){const t=C(n);return t!==null?t:I.find(({path:s})=>s===n.path)?.run(n,e)??null}u(Y,"summarizePath");export{R as HELP_ICON,k as LEAF_ICON_CP,I as SUMMARIZERS,g as SUPPRESS_OUTPUT_LEAVES,T as TOOL_ICON,U as crtrPreviewRecords,H as iconForPath,Y as summarizePath,M as suppressOutputForLeaf,N as suppressOutputForPath};
@@ -1,2 +1,2 @@
1
- var d=Object.defineProperty;var n=(e,t)=>d(e,"name",{value:t,configurable:!0});import{existsSync as y,readFileSync as p,renameSync as S,writeFileSync as O,chmodSync as R}from"node:fs";import{join as b}from"node:path";import{loadExactProfileManifest as w,profileRoot as a,withProfileManifestLock as u}from"./manifest.js";import{ensureDir as N}from"../fs-utils.js";import{notFound as x,usage as f}from"../errors.js";const P="env.json",V="CRTR_",_=new Set(["HOME"]);function v(e){return e.startsWith(V)||_.has(e)}n(v,"isReservedEnvName");function m(e){return e.includes("\0")}n(m,"hasNulByte");function l(e){return b(a(e),P)}n(l,"envPath");function i(e){const t=l(e),r=Object.create(null);if(!y(t))return{vars:r};try{const o=JSON.parse(p(t,"utf8"));for(const[s,c]of Object.entries(o.vars??{}))typeof c=="string"&&(m(c)||v(s)||(r[s]=c))}catch{}return{vars:r}}n(i,"readStoreUnlocked");function h(e,t){const r=l(e);N(a(e));const o=`${r}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;O(o,JSON.stringify(t,null,2)+`
2
- `,{mode:384}),R(o,384),S(o,r)}n(h,"writeStoreAtomic");function E(e){try{w(e)}catch(t){throw t instanceof Error&&t.message.startsWith("profile not found:")?x(`profile not found: ${e}`,{received:e}):t}}n(E,"requireProfileExists");function C(e){return Object.keys(i(e).vars).sort()}n(C,"listProfileEnvNames");function L(e,t,r){if(v(t))throw f(`env var name is reserved by crtr: ${t}`,{received:t,field:"name",next:"crtr identity/routing names (CRTR_* and HOME) cannot be stored in a profile env store \u2014 a stored value under one of these names could redirect a broker to a different canvas home. Choose a different name."});if(m(r))throw f("env var value contains a NUL byte, which no OS accepts in an environment variable",{field:"value",next:"Remove NUL bytes from the piped value and retry."});return u(e,()=>{E(e);const o=i(e),s=!Object.hasOwn(o.vars,t);return o.vars[t]=r,h(e,o),s})}n(L,"setProfileEnvVar");function A(e,t){return u(e,()=>{E(e);const r=i(e);return Object.hasOwn(r.vars,t)?(delete r.vars[t],h(e,r),!0):!1})}n(A,"removeProfileEnvVar");function D(e){if(e===null||e==="")return{};try{return{...i(e).vars}}catch{return{}}}n(D,"readProfileEnvVars");export{v as isReservedEnvName,C as listProfileEnvNames,D as readProfileEnvVars,A as removeProfileEnvVar,L as setProfileEnvVar};
1
+ var E=Object.defineProperty;var n=(e,t)=>E(e,"name",{value:t,configurable:!0});import{existsSync as p,readFileSync as y,renameSync as S,writeFileSync as O,chmodSync as b}from"node:fs";import{dirname as w}from"node:path";import{profileSpace as R}from"../layout.js";import{loadExactProfileManifest as c,withProfileManifestLock as u}from"./manifest.js";import{ensureDir as x}from"../fs-utils.js";import{notFound as N,usage as f}from"../errors.js";const P="CRTR_",g=new Set(["HOME"]);function v(e){return e.startsWith(P)||g.has(e)}n(v,"isReservedEnvName");function m(e){return e.includes("\0")}n(m,"hasNulByte");function l(e){const t=c(e);return R(t.manifest.grantee??"app:terminal",e).env}n(l,"envPath");function s(e){const t=l(e),r=Object.create(null);if(!p(t))return{vars:r};try{const o=JSON.parse(y(t,"utf8"));for(const[i,a]of Object.entries(o.vars??{}))typeof a=="string"&&(m(a)||v(i)||(r[i]=a))}catch{}return{vars:r}}n(s,"readStoreUnlocked");function d(e,t){const r=l(e);x(w(r));const o=`${r}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;O(o,JSON.stringify(t,null,2)+`
2
+ `,{mode:384}),b(o,384),S(o,r)}n(d,"writeStoreAtomic");function h(e){try{c(e)}catch(t){throw t instanceof Error&&t.message.startsWith("profile not found:")?N(`profile not found: ${e}`,{received:e}):t}}n(h,"requireProfileExists");function F(e){return Object.keys(s(e).vars).sort()}n(F,"listProfileEnvNames");function A(e,t,r){if(v(t))throw f(`env var name is reserved by crtr: ${t}`,{received:t,field:"name",next:"crtr identity/routing names (CRTR_* and HOME) cannot be stored in a profile env store \u2014 a stored value under one of these names could redirect a broker to a different canvas home. Choose a different name."});if(m(r))throw f("env var value contains a NUL byte, which no OS accepts in an environment variable",{field:"value",next:"Remove NUL bytes from the piped value and retry."});return u(e,()=>{h(e);const o=s(e),i=!Object.hasOwn(o.vars,t);return o.vars[t]=r,d(e,o),i})}n(A,"setProfileEnvVar");function D(e,t){return u(e,()=>{h(e);const r=s(e);return Object.hasOwn(r.vars,t)?(delete r.vars[t],d(e,r),!0):!1})}n(D,"removeProfileEnvVar");function L(e){if(e===null||e==="")return{};try{return{...s(e).vars}}catch{return{}}}n(L,"readProfileEnvVars");export{v as isReservedEnvName,F as listProfileEnvNames,L as readProfileEnvVars,D as removeProfileEnvVar,A as setProfileEnvVar};
@@ -1,12 +1,8 @@
1
1
  import type { ProfileManifest } from '../../types.js';
2
2
  import type { ProfileProject, ProfileProjectMemory } from '../../api/dto/profiles.js';
3
3
  export declare const ROOT_PROFILE_ID = "root-00000000";
4
- export declare function profilesRoot(): string;
5
- export declare function profileRoot(profileId: string): string;
6
- export declare function profileManifestPath(profileId: string): string;
7
4
  export declare function profileMemoryDir(profileId: string): string;
8
5
  export declare function assertProfileProjects(entries: unknown): asserts entries is ProfileProject[];
9
- export declare function profileHome(profileId: string | null): string | null;
10
6
  export interface ProfileEntry {
11
7
  profileId: string;
12
8
  manifest: ProfileManifest;
@@ -30,6 +26,16 @@ export declare function lookupProfile(profileIdOrName: string): ProfileLookup;
30
26
  /** Read one exact profile id without falling back to manifest-name matching.
31
27
  * Used at persistence gates that already hold a resolved durable identity. */
32
28
  export declare function loadExactProfileManifest(profileId: string): ProfileEntry;
29
+ /** Exact resolution only: the generated id, else a unique manifest `name`.
30
+ * Returns `null` when nothing matches exactly; still THROWS when a name is
31
+ * shared by several profiles, because that is a real collision the caller
32
+ * cannot resolve by guessing (and fuzzy matching would only guess harder). */
33
+ /** The two facts operand matching reads, from a stored entry or a daemon DTO. */
34
+ export interface ProfileCandidate {
35
+ profileId: string;
36
+ name: string;
37
+ }
38
+ type CandidateOf<T> = (entry: T) => ProfileCandidate;
33
39
  export declare function loadProfileManifest(profileIdOrName: string): ProfileEntry;
34
40
  /** Resolve a profile the USER TYPED — a `--profile` flag or a `<profile>`
35
41
  * operand. Exact id or name wins outright; only when nothing matches exactly
@@ -45,6 +51,9 @@ export declare function loadProfileManifest(profileIdOrName: string): ProfileEnt
45
51
  * those callers already handle, not the nearest surviving profile. Use
46
52
  * `loadProfileManifest` (or `loadExactProfileManifest`) for those. */
47
53
  export declare function resolveProfileOperand(operand: string): ProfileEntry;
54
+ /** `resolveProfileOperand` over any candidate list — the CLI passes the
55
+ * profiles the daemon lists for its caller. */
56
+ export declare function matchProfileOperand<T>(all: readonly T[], operand: string, key: CandidateOf<T>): T;
48
57
  /** Hold the per-profile manifest lock for the duration of `fn`. ALL manifest
49
58
  * mutations (create/rename/add-project/remove-project/delete/last-used)
50
59
  * below run inside this. */
@@ -66,7 +75,9 @@ export declare function sanitizeProfileMetadata(stored: unknown): Record<string,
66
75
  export declare function createProfile(name: string, projects?: ProfileProject[], opts?: {
67
76
  defaultKind?: string;
68
77
  metadata?: Record<string, string>;
78
+ grantee?: string;
69
79
  }): ProfileEntry;
80
+ export declare function ensureAppProfile(grantee: string): ProfileEntry;
70
81
  export declare function updateProfileLastUsed(profileId: string): ProfileEntry;
71
82
  /** Paused check for an ALREADY-RESOLVED durable id (a canvas row's `profile_id`,
72
83
  * `CRTR_PROFILE_ID`) — exact-id only, no name matching, so it costs one small
@@ -98,7 +109,7 @@ export declare function renameProfile(profileId: string, name: string): ProfileE
98
109
  * relationship never acquires one by default. */
99
110
  export declare function addProfileProject(profileId: string, dir: string, opts: {
100
111
  memory: ProfileProjectMemory;
101
- home?: boolean;
102
112
  }): ProfileEntry;
103
113
  export declare function removeProfileProject(profileId: string, dir: string): ProfileEntry;
104
114
  export declare function deleteProfile(profileId: string): void;
115
+ export {};
@@ -1 +1 @@
1
- var B=Object.defineProperty;var o=(e,t)=>B(e,"name",{value:t,configurable:!0});import{randomUUID as Q}from"node:crypto";import{existsSync as v,realpathSync as j,rmSync as X,statSync as A}from"node:fs";import{join as m,relative as I,resolve as P,sep as ee}from"node:path";import{SCHEMA_VERSION as M,PROFILE_DIR as te}from"../../types.js";import{PROFILE_PROJECT_MEMORY_VALUES as O}from"../../api/dto/profiles.js";import{userScopeRoot as u,resetScopeCache as h}from"../scope.js";import{ensureDir as g,nowIso as $}from"../fs-utils.js";import{deleteStoredProfile as re,getStoredProfile as S,insertStoredProfile as D,listStoredProfiles as ne,updateStoredProfile as oe}from"../scoped-state/profiles.js";import{usage as c,notFound as y,ambiguous as L,general as N}from"../errors.js";import{withExclusiveDirectoryLock as ie}from"../exclusive-lock.js";import{fuzzyMatchProfile as ae}from"./fuzzy-match.js";const z=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,f="root-00000000",se="root";function C(e,t){const r=p(e);g(r),g(m(r,"memory"))}o(C,"scaffoldProfile");function w(){return m(u(),te)}o(w,"profilesRoot");function _(e){if(!z.test(e))throw c(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}o(_,"assertSafeProfileId");function ce(e){const t=w(),r=P(t),n=v(t)?j(t):r,i=v(e)?j(e):P(n,I(r,P(e)));if(i!==n&&!i.startsWith(n+ee))throw c(`profile path escapes the profiles root: ${e}`)}o(ce,"assertInsideProfilesRoot");function p(e){_(e);const t=m(w(),e);return ce(t),t}o(p,"profileRoot");function ke(e){return m(p(e),"profile.json")}o(ke,"profileManifestPath");function fe(e){return m(p(e),"memory")}o(fe,"profileMemoryDir");function b(e,t){const r=typeof t.home=="string"&&t.home!==""?t.home:null;return{...t,home:e===f?r:r??t.projects[0]?.path??null,paused_at:typeof t.paused_at=="string"&&t.paused_at!==""?t.paused_at:null}}o(b,"normalizeHome");function F(e){const t=O.join(", ");if(!Array.isArray(e))throw c("projects must be an array of {path, memory} objects",{received:typeof e,field:"projects",next:`Pass entries like {"path": "/abs/dir", "memory": "content"} \u2014 memory is one of: ${t}.`});for(const r of e){if(typeof r!="object"||r===null||Array.isArray(r))throw c(`invalid project entry: ${JSON.stringify(r)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir", "memory": "content"}.'});const{path:n,memory:i}=r;if(typeof n!="string"||n.trim()==="")throw c(`project entry has no path: ${JSON.stringify(r)}`,{field:"projects",next:"Give every project entry a non-empty directory path."});if(typeof i!="string"||!O.includes(i))throw c(`invalid project memory value: ${JSON.stringify(i)}`,{received:String(i),field:"projects",next:`Set memory on ${n} to one of: ${t}.`})}}o(F,"assertProfileProjects");function Ee(e){if(e===null||e==="")return null;try{const t=H(e).manifest.home;return t!==null&&v(t)&&A(t).isDirectory()?t:null}catch{return null}}o(Ee,"profileHome");function le(){return{entries:ne(u()).map(({profileId:e,manifest:t})=>({profileId:e,manifest:b(e,t)})),unreadableIds:[]}}o(le,"enumerateProfiles");function k(){return le().entries}o(k,"listProfiles");function ue(e){const t=k(),r=T(t,e);return r?{kind:"resolved",entry:r}:{kind:"absent"}}o(ue,"lookupProfile");function J(e){_(e);const t=S(u(),e);if(t!==null)return{profileId:e,manifest:b(e,t.manifest)};throw y(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}o(J,"loadExactProfileManifest");function T(e,t){if(z.test(t)){const n=e.find(i=>i.profileId===t);if(n!==void 0)return n}const r=e.filter(n=>n.manifest.name===t);if(r.length===1)return r[0];if(r.length>1){const n=r.map(i=>i.profileId);throw L(`profile name "${t}" matches ${n.length} profiles: ${n.join(", ")}`,{received:t,candidates:n,next:`Re-run with one exact profile id: ${n.join(", ")}.`})}return null}o(T,"findExactProfile");function U(e,t){const r=e.map(n=>`${n.profileId} (${n.manifest.name})`);return y(`profile not found: ${t}`,{received:t,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}o(U,"profileNotFound");function H(e){const t=ue(e);if(t.kind==="resolved")return t.entry;throw U(k(),e)}o(H,"loadProfileManifest");function Ae(e){const t=k(),r=T(t,e);if(r!==null)return r;const{match:n,tied:i}=ae(e,t.map(a=>({profileId:a.profileId,name:a.manifest.name})));if(n!==null){const a=t.find(s=>s.profileId===n.profileId);return console.error(`crtr: no profile named "${e}" \u2014 using the closest match: ${a.manifest.name} (${a.profileId})`),a}if(i.length>1){const a=i.map(s=>`${s.profileId} (${s.name})`);throw L(`"${e}" is equally close to ${i.length} profiles: ${a.join(", ")}`,{received:e,candidates:i.map(s=>s.profileId),next:`Re-run with one exact profile id or name: ${a.join(", ")}.`})}throw U(t,e)}o(Ae,"resolveProfileOperand");function K(){return m(w(),".locks")}o(K,"locksDir");function R(e,t){return _(e),g(K()),ie(m(K(),`${e}.lock`),t,{timeoutError:o(()=>N(`timed out waiting for the profile lock: ${e}`,{next:"Retry \u2014 another `crtr profile` command may be running concurrently on this profile."}),"timeoutError")})}o(R,"withProfileManifestLock");function q(e){const t=P(e);if(!v(t)||!A(t).isDirectory())throw c(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return j(t)}catch{return t}}o(q,"resolveExistingProjectDir");function Z(e){const t=new Set,r=[];for(const n of e)t.has(n.path)||(t.add(n.path),r.push(n));return r}o(Z,"dedupeProjects");function me(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>40&&(t=t.slice(0,40).replace(/-+$/g,"")),t.length>0?t:"profile"}o(me,"slugify");function de(e){const t=me(e),r=w();for(let n=0;n<20;n++){const i=Q().replace(/-/g,"").slice(0,8),a=`${t}-${i}`;if(!v(m(r,a)))return a}throw N(`failed to generate a unique profile id for "${e}" after 20 attempts`)}o(de,"generateProfileId");function Me(){return R(f,()=>{const e=S(u(),f);if(e!==null)return g(p(f)),g(fe(f)),{profileId:f,manifest:b(f,e.manifest)};const t={schema_version:M,name:se,projects:[],home:null,paused_at:null,created_at:$(),last_used_at:$()};return C(f,t),D(u(),{profileId:f,manifest:t},p(f)),h(),{profileId:f,manifest:t}})}o(Me,"ensureRootProfile");const V=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function Y(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}o(Y,"metadataEnvName");function E(e){if(typeof e!="object"||e===null||Array.isArray(e))throw c("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const t=new Map;for(const[r,n]of Object.entries(e)){if(!V.test(r))throw c(`invalid metadata key: ${JSON.stringify(r)}`,{received:r,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof n!="string")throw c(`metadata value for ${r} must be a string`,{received:typeof n,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(n.includes("\0"))throw c(`metadata value for ${r} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const i=Y(r),a=t.get(i);if(a!==void 0)throw c(`metadata keys ${JSON.stringify(a)} and ${JSON.stringify(r)} both surface as ${i}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(i,r)}}o(E,"assertProfileMetadata");function G(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},r=new Set;for(const[n,i]of Object.entries(e)){if(typeof i!="string"||!V.test(n)||i.includes("\0"))continue;const a=Y(n);r.has(a)||(r.add(a),t[n]=i)}return t}o(G,"sanitizeProfileMetadata");function Oe(e,t=[],r={}){const n=e.trim();if(n==="")throw c("profile name must not be empty");r.metadata!==void 0&&E(r.metadata),F(t);const i=Z(t.map(s=>({path:q(s.path),memory:s.memory}))),a=de(n);return R(a,()=>{const s={schema_version:M,name:n,projects:i,home:i[0]?.path??null,paused_at:null,...r.defaultKind!==void 0?{default_kind:r.defaultKind}:{},...r.metadata!==void 0&&Object.keys(r.metadata).length>0?{metadata:{...r.metadata}}:{},created_at:$(),last_used_at:null};return C(a,s),D(u(),{profileId:a,manifest:s},p(a)),h(),{profileId:a,manifest:s}})}o(Oe,"createProfile");function W(e){if(_(e),S(u(),e)===null)throw y(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}o(W,"requireExistingProfile");function d(e,t){return W(e),R(e,()=>{const r=oe(u(),e,t);if(r===null)throw y(`profile not found: ${e}`,{received:e});return{profileId:e,manifest:b(e,r.manifest)}})}o(d,"mutateManifest");function De(e){return d(e,t=>({...t,last_used_at:$()}))}o(De,"updateProfileLastUsed");function pe(e){if(e==null||e==="")return null;try{return H(e)}catch{return null}}o(pe,"loadProfileManifestOrNull");function Le(e){if(e==null||e==="")return!1;try{return J(e).manifest.paused_at!==null}catch{return!1}}o(Le,"isProfilePaused");function he(e){if(e.manifest.paused_at!==null)throw c(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}o(he,"assertProfileEntryActive");function Ne(e){const t=pe(e);return t===null?null:(he(t),t)}o(Ne,"assertProfileActive");function ze(e){return d(e,t=>({...t,paused_at:t.paused_at??$()}))}o(ze,"pauseProfile");function Ce(e){let t=null;return{...d(e,n=>(t=n.paused_at,{...n,paused_at:null})),pausedAt:t}}o(Ce,"resumeProfile");function Fe(e,t){return d(e,r=>({...r,default_kind:t}))}o(Fe,"setProfileDefaultKind");function Je(e,t,r=[]){return E(t),d(e,n=>{const i={...G(n.metadata),...t};for(const x of r)delete i[x];E(i);const{metadata:a,...s}=n;return{...s,...Object.keys(i).length>0?{metadata:i}:{}}})}o(Je,"updateProfileMetadata");function Te(e){if(e===null||e==="")return{};try{return G(J(e).manifest.metadata)}catch{return{}}}o(Te,"readProfileMetadata");function Ue(e,t){const r=t.trim();if(r==="")throw c("profile name must not be empty");const n=d(e,i=>({...i,name:r}));return h(),n}o(Ue,"renameProfile");function He(e,t,r){F([{path:t,memory:r.memory}]);const n=q(t),i=d(e,a=>{const x=a.projects.some(l=>l.path===n)?a.projects.map(l=>l.path===n?{...l,memory:r.memory}:l):Z([...a.projects,{path:n,memory:r.memory}]);return{...a,projects:x,...r.home===!0?{home:n}:{}}});return h(),i}o(He,"addProfileProject");function Ke(e,t){const r=P(t);let n=r;try{n=j(r)}catch{}const i=d(e,a=>{const s=a.projects.filter(l=>l.path!==n&&l.path!==r),x=a.home===n||a.home===r?s[0]?.path??null:a.home;if(s.length===a.projects.length)throw y(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${a.projects.length>0?a.projects.map(l=>l.path).join(", "):"(none)"}.`});return{...a,projects:s,home:x}});return h(),i}o(Ke,"removeProfileProject");function qe(e){W(e),R(e,()=>{if(!re(u(),e))throw y(`profile not found: ${e}`,{received:e});X(p(e),{recursive:!0,force:!0})}),h()}o(qe,"deleteProfile");export{f as ROOT_PROFILE_ID,He as addProfileProject,Ne as assertProfileActive,he as assertProfileEntryActive,E as assertProfileMetadata,F as assertProfileProjects,Oe as createProfile,qe as deleteProfile,Me as ensureRootProfile,Le as isProfilePaused,k as listProfiles,J as loadExactProfileManifest,H as loadProfileManifest,ue as lookupProfile,Y as metadataEnvName,ze as pauseProfile,Ee as profileHome,ke as profileManifestPath,fe as profileMemoryDir,p as profileRoot,w as profilesRoot,Te as readProfileMetadata,Ke as removeProfileProject,Ue as renameProfile,Ae as resolveProfileOperand,Ce as resumeProfile,G as sanitizeProfileMetadata,Fe as setProfileDefaultKind,De as updateProfileLastUsed,Je as updateProfileMetadata,R as withProfileManifestLock};
1
+ var G=Object.defineProperty;var o=(e,t)=>G(e,"name",{value:t,configurable:!0});import{randomUUID as W}from"node:crypto";import{existsSync as B,realpathSync as E,rmSync as A,statSync as Q}from"node:fs";import{join as R,resolve as k}from"node:path";import{SCHEMA_VERSION as O}from"../../types.js";import{profileSpace as $}from"../layout.js";import{PROFILE_PROJECT_MEMORY_VALUES as M}from"../../api/dto/profiles.js";import{userScopeRoot as u,resetScopeCache as m}from"../scope.js";import{ensureDir as D,nowIso as y}from"../fs-utils.js";import{deleteStoredProfile as X,getStoredProfile as x,insertStoredProfile as L,listStoredProfiles as I,updateStoredProfile as ee}from"../scoped-state/profiles.js";import{usage as c,notFound as d,ambiguous as N,general as z}from"../errors.js";import{withExclusiveDirectoryLock as te}from"../exclusive-lock.js";import{fuzzyMatchProfile as re}from"./fuzzy-match.js";const C=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/,p="root-00000000",ne="root";function w(e){return e.grantee??"app:terminal"}o(w,"profileApp");function j(e,t){D($(w(t),e).memory)}o(j,"scaffoldProfile");function g(e){if(!C.test(e))throw c(`invalid profile id: ${e}`,{received:e,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}o(g,"assertSafeProfileId");function Se(e){g(e);const t=x(u(),e);if(t===null)throw d(`profile not found: ${e}`,{received:e});return $(w(t.manifest),e).memory}o(Se,"profileMemoryDir");function J(e){const t=M.join(", ");if(!Array.isArray(e))throw c("projects must be an array of {path, memory} objects",{received:typeof e,field:"projects",next:`Pass entries like {"path": "/abs/dir", "memory": "content"} \u2014 memory is one of: ${t}.`});for(const r of e){if(typeof r!="object"||r===null||Array.isArray(r))throw c(`invalid project entry: ${JSON.stringify(r)}`,{field:"projects",next:'Every project is an object like {"path": "/abs/dir", "memory": "content"}.'});const{path:n,memory:i}=r;if(typeof n!="string"||n.trim()==="")throw c(`project entry has no path: ${JSON.stringify(r)}`,{field:"projects",next:"Give every project entry a non-empty directory path."});if(typeof i!="string"||!M.includes(i))throw c(`invalid project memory value: ${JSON.stringify(i)}`,{received:String(i),field:"projects",next:`Set memory on ${n} to one of: ${t}.`})}}o(J,"assertProfileProjects");function oe(){return{entries:I(u()),unreadableIds:[]}}o(oe,"enumerateProfiles");function v(){return oe().entries}o(v,"listProfiles");function ie(e){const t=v(),r=T(t,e,b);return r?{kind:"resolved",entry:r}:{kind:"absent"}}o(ie,"lookupProfile");function _(e){g(e);const t=x(u(),e);if(t!==null)return t;throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}o(_,"loadExactProfileManifest");const b=o(e=>({profileId:e.profileId,name:e.manifest.name}),"entryCandidate");function T(e,t,r){if(C.test(t)){const i=e.find(a=>r(a).profileId===t);if(i!==void 0)return i}const n=e.filter(i=>r(i).name===t);if(n.length===1)return n[0];if(n.length>1){const i=n.map(a=>r(a).profileId);throw N(`profile name "${t}" matches ${i.length} profiles: ${i.join(", ")}`,{received:t,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}o(T,"findExactProfile");function U(e,t,r){const n=e.map(i=>`${r(i).profileId} (${r(i).name})`);return d(`profile not found: ${t}`,{received:t,available:n,next:n.length>0?`Re-run with one of the profiles on this host: ${n.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}o(U,"profileNotFound");function ae(e){const t=ie(e);if(t.kind==="resolved")return t.entry;throw U(v(),e,b)}o(ae,"loadProfileManifest");function Ee(e){return se(v(),e,b)}o(Ee,"resolveProfileOperand");function se(e,t,r){const n=T(e,t,r);if(n!==null)return n;const{match:i,tied:a}=re(t,e.map(r));if(i!==null){const s=e.find(f=>r(f).profileId===i.profileId);return console.error(`crtr: no profile named "${t}" \u2014 using the closest match: ${r(s).name} (${r(s).profileId})`),s}if(a.length>1){const s=a.map(f=>`${f.profileId} (${f.name})`);throw N(`"${t}" is equally close to ${a.length} profiles: ${s.join(", ")}`,{received:t,candidates:a.map(f=>f.profileId),next:`Re-run with one exact profile id or name: ${s.join(", ")}.`})}throw U(e,t,r)}o(se,"matchProfileOperand");function F(){return R(u(),"profile-locks")}o(F,"locksDir");function P(e,t){return g(e),D(F()),te(R(F(),`${e}.lock`),t,{timeoutError:o(()=>z(`timed out waiting for the profile lock: ${e}`,{next:"Retry \u2014 another `crtr profile` command may be running concurrently on this profile."}),"timeoutError")})}o(P,"withProfileManifestLock");function K(e){const t=k(e);if(!B(t)||!Q(t).isDirectory())throw c(`project directory does not exist or is not a directory: ${e}`,{received:e,next:"Pass an existing directory path."});try{return E(t)}catch{return t}}o(K,"resolveExistingProjectDir");function q(e){const t=new Set,r=[];for(const n of e)t.has(n.path)||(t.add(n.path),r.push(n));return r}o(q,"dedupeProjects");function fe(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");return t.length>40&&(t=t.slice(0,40).replace(/-+$/g,"")),t.length>0?t:"profile"}o(fe,"slugify");function ce(e){const t=fe(e);for(let r=0;r<20;r++){const n=W().replace(/-/g,"").slice(0,8),i=`${t}-${n}`;if(x(u(),i)===null)return i}throw z(`failed to generate a unique profile id for "${e}" after 20 attempts`)}o(ce,"generateProfileId");function Ae(){return P(p,()=>{const e=x(u(),p);if(e!==null)return j(p,e.manifest),e;const t={schema_version:O,name:ne,projects:[],grantee:"app:terminal",paused_at:null,created_at:y(),last_used_at:y()};return j(p,t),L(u(),{profileId:p,manifest:t}),m(),{profileId:p,manifest:t}})}o(Ae,"ensureRootProfile");const H=/^[A-Za-z0-9][A-Za-z0-9_-]*$/;function Z(e){return`CRTR_PROFILE_META_${e.toUpperCase().replace(/[^A-Z0-9]+/g,"_")}`}o(Z,"metadataEnvName");function S(e){if(typeof e!="object"||e===null||Array.isArray(e))throw c("metadata must be a map of string keys to string values",{field:"metadata",next:'Pass an object, e.g. {"role": "support"}.'});const t=new Map;for(const[r,n]of Object.entries(e)){if(!H.test(r))throw c(`invalid metadata key: ${JSON.stringify(r)}`,{received:r,field:"metadata",next:"Keys start with a letter or digit, followed by letters, digits, `_`, or `-`."});if(typeof n!="string")throw c(`metadata value for ${r} must be a string`,{received:typeof n,field:"metadata",next:"Every metadata value is an env-var value \u2014 pass strings only."});if(n.includes("\0"))throw c(`metadata value for ${r} contains a NUL byte, which no OS accepts in an environment variable`,{field:"metadata",next:"Remove NUL bytes from the value and retry."});const i=Z(r),a=t.get(i);if(a!==void 0)throw c(`metadata keys ${JSON.stringify(a)} and ${JSON.stringify(r)} both surface as ${i}`,{field:"metadata",next:"Rename or drop one \u2014 keys must stay distinct after uppercasing and `_`-folding."});t.set(i,r)}}o(S,"assertProfileMetadata");function V(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={},r=new Set;for(const[n,i]of Object.entries(e)){if(typeof i!="string"||!H.test(n)||i.includes("\0"))continue;const a=Z(n);r.has(a)||(r.add(a),t[n]=i)}return t}o(V,"sanitizeProfileMetadata");function ue(e,t=[],r={}){const n=e.trim();if(n==="")throw c("profile name must not be empty");r.metadata!==void 0&&S(r.metadata),J(t);const i=q(t.map(s=>({path:K(s.path),memory:s.memory}))),a=ce(n);return P(a,()=>{const s={schema_version:O,name:n,projects:i,paused_at:null,...r.grantee===void 0?{}:{grantee:r.grantee},...r.defaultKind!==void 0?{default_kind:r.defaultKind}:{},...r.metadata!==void 0&&Object.keys(r.metadata).length>0?{metadata:{...r.metadata}}:{},created_at:y(),last_used_at:null};return j(a,s),L(u(),{profileId:a,manifest:s}),m(),{profileId:a,manifest:s}})}o(ue,"createProfile");function Re(e){if(!e.startsWith("app:")||e.length<=4)throw c("an app grantee is required");const t=`app-${e.slice(4)}`,r=v().filter(n=>n.manifest.name===t&&n.manifest.grantee===e);if(r.length>1)throw new Error(`duplicate default profile for ${e}`);return r[0]?r[0]:ue(t,[],{grantee:e})}o(Re,"ensureAppProfile");function Y(e){if(g(e),x(u(),e)===null)throw d(`profile not found: ${e}`,{received:e,next:"Run `crtr profile list` to see available profiles."})}o(Y,"requireExistingProfile");function l(e,t){return Y(e),P(e,()=>{const r=ee(u(),e,t);if(r===null)throw d(`profile not found: ${e}`,{received:e});return r})}o(l,"mutateManifest");function ke(e){return l(e,t=>({...t,last_used_at:y()}))}o(ke,"updateProfileLastUsed");function le(e){if(e==null||e==="")return null;try{return ae(e)}catch{return null}}o(le,"loadProfileManifestOrNull");function Oe(e){if(e==null||e==="")return!1;try{return _(e).manifest.paused_at!==null}catch{return!1}}o(Oe,"isProfilePaused");function de(e){if(e.manifest.paused_at!==null)throw c(`profile "${e.manifest.name}" is paused and cannot start nodes`,{received:e.profileId,next:`Resume it with \`crtr profile resume ${e.profileId}\`.`})}o(de,"assertProfileEntryActive");function Me(e){const t=le(e);return t===null?null:(de(t),t)}o(Me,"assertProfileActive");function De(e){return l(e,t=>({...t,paused_at:t.paused_at??y()}))}o(De,"pauseProfile");function Le(e){let t=null;return{...l(e,n=>(t=n.paused_at,{...n,paused_at:null})),pausedAt:t}}o(Le,"resumeProfile");function Ne(e,t){return l(e,r=>({...r,default_kind:t}))}o(Ne,"setProfileDefaultKind");function ze(e,t,r=[]){return S(t),l(e,n=>{const i={...V(n.metadata),...t};for(const f of r)delete i[f];S(i);const{metadata:a,...s}=n;return{...s,...Object.keys(i).length>0?{metadata:i}:{}}})}o(ze,"updateProfileMetadata");function Ce(e){if(e===null||e==="")return{};try{return V(_(e).manifest.metadata)}catch{return{}}}o(Ce,"readProfileMetadata");function Je(e,t){const r=t.trim();if(r==="")throw c("profile name must not be empty");const n=l(e,i=>({...i,name:r}));return m(),n}o(Je,"renameProfile");function Te(e,t,r){J([{path:t,memory:r.memory}]);const n=K(t),i=l(e,a=>{const f=a.projects.some(h=>h.path===n)?a.projects.map(h=>h.path===n?{...h,memory:r.memory}:h):q([...a.projects,{path:n,memory:r.memory}]);return{...a,projects:f}});return m(),i}o(Te,"addProfileProject");function Ue(e,t){const r=k(t);let n=r;try{n=E(r)}catch{}const i=l(e,a=>{const s=a.projects.filter(f=>f.path!==n&&f.path!==r);if(s.length===a.projects.length)throw d(`project not found on profile: ${t}`,{received:t,next:`Current projects: ${a.projects.length>0?a.projects.map(f=>f.path).join(", "):"(none)"}.`});return{...a,projects:s}});return m(),i}o(Ue,"removeProfileProject");function Fe(e){Y(e),P(e,()=>{const t=$(w(_(e).manifest),e);if(!X(u(),e))throw d(`profile not found: ${e}`,{received:e});A(t.memory,{recursive:!0,force:!0}),A(t.env,{force:!0})}),m()}o(Fe,"deleteProfile");export{p as ROOT_PROFILE_ID,Te as addProfileProject,Me as assertProfileActive,de as assertProfileEntryActive,S as assertProfileMetadata,J as assertProfileProjects,ue as createProfile,Fe as deleteProfile,Re as ensureAppProfile,Ae as ensureRootProfile,Oe as isProfilePaused,v as listProfiles,_ as loadExactProfileManifest,ae as loadProfileManifest,ie as lookupProfile,se as matchProfileOperand,Z as metadataEnvName,De as pauseProfile,Se as profileMemoryDir,Ce as readProfileMetadata,Ue as removeProfileProject,Je as renameProfile,Ee as resolveProfileOperand,Le as resumeProfile,V as sanitizeProfileMetadata,Ne as setProfileDefaultKind,ke as updateProfileLastUsed,ze as updateProfileMetadata,P as withProfileManifestLock};
@@ -1 +1 @@
1
- var d=Object.defineProperty;var n=(a,e)=>d(a,"name",{value:e,configurable:!0});import{join as m}from"node:path";import{deleteAuthCredential as r}from"./auth-file.js";import{removeManagedProvider as i}from"./subscription-state.js";async function f(a,e){return e.managed?(await i(e.providerId,e.label),e.label===void 0?`Removed ${e.name}`:`Removed ${e.name} account`):(await r(e.providerId,m(a,"auth.json")),`Removed ${e.name}`)}n(f,"removeProviderRow");export{f as removeProviderRow};
1
+ var i=Object.defineProperty;var a=(r,e)=>i(r,"name",{value:e,configurable:!0});import{join as m}from"node:path";import{deleteAuthCredential as n}from"./auth-file.js";import{secretsDir as t}from"./layout.js";import{removeManagedProvider as o}from"./subscription-state.js";async function l(r,e){return e.managed?(await o(e.providerId,e.label),e.label===void 0?`Removed ${e.name}`:`Removed ${e.name} account`):(await n(e.providerId,m(t(),"auth.json")),`Removed ${e.name}`)}a(l,"removeProviderRow");export{l as removeProviderRow};
@@ -1 +1 @@
1
- var d=Object.defineProperty;var n=(o,e)=>d(o,"name",{value:e,configurable:!0});import{commitBindingRequest as w}from"../human/requests.js";import{getReview as _}from"./store.js";import{discardStaging as s,stageReview as c}from"./stage.js";import{realizeReview as a}from"./realize.js";async function m(o){const e=await c(o);if(e.existing!==void 0){await a(e.existing.request_id);const r=_(e.existing.request_id);if(r===null)throw new Error(`realized review disappeared: ${e.existing.request_id}`);return r}let i;try{i=w({request_id:e.row.review_id,idempotency_key:e.row.idempotency_key,requester_node_id:e.row.origin_node_id,companion_node_id:e.row.companion_node_id,request_dir:e.row.review_dir,file:e.row.file,specification:{origin_kind:e.row.origin_kind,origin_session_file:e.row.origin_session_file,origin_session_id:e.row.origin_session_id,origin_leaf_id:e.row.origin_leaf_id,model_spec:e.row.model_spec,branch_file:e.row.branch_file,baseline_sha256:e.row.baseline_sha256,baseline_bytes:e.row.baseline_bytes,captured_at:e.row.captured_at,output_path:e.row.output_path},anchor_base_sha256:e.row.anchor_base_sha256,anchor_base_bytes:e.row.anchor_base_bytes,created_at:e.row.created,subtitle:e.row.subtitle,inbox_listed:e.row.origin_kind==="ticket"})}catch(r){throw s(e.row.review_id),r}i.won||s(e.row.review_id),await a(i.request_id);const t=_(i.request_id);if(t===null)throw new Error(`realized review disappeared: ${i.request_id}`);return t}n(m,"createReview");export{m as createReview};
1
+ var d=Object.defineProperty;var n=(o,e)=>d(o,"name",{value:e,configurable:!0});import{commitBindingRequest as w}from"../human/requests.js";import{getReview as _}from"./store.js";import{discardStaging as s,stageReview as c}from"./stage.js";import{realizeReview as a}from"./realize.js";async function b(o){const e=await c(o);if(e.existing!==void 0){await a(e.existing.request_id);const r=_(e.existing.request_id);if(r===null)throw new Error(`realized review disappeared: ${e.existing.request_id}`);return r}let i;try{i=w({request_id:e.row.review_id,idempotency_key:e.row.idempotency_key,requester_node_id:e.row.origin_node_id,companion_node_id:e.row.companion_node_id,request_dir:e.row.review_dir,file:e.row.file,specification:{origin_kind:e.row.origin_kind,origin_session_file:e.row.origin_session_file,origin_session_id:e.row.origin_session_id,origin_leaf_id:e.row.origin_leaf_id,model_spec:e.row.model_spec,branch_file:e.row.branch_file,baseline_sha256:e.row.baseline_sha256,baseline_bytes:e.row.baseline_bytes,captured_at:e.row.captured_at,output_path:e.row.output_path},anchor_base_sha256:e.row.anchor_base_sha256,anchor_base_bytes:e.row.anchor_base_bytes,created_at:e.row.created,subtitle:e.row.subtitle,inbox_listed:e.row.origin_kind==="ticket"})}catch(r){throw s(e.row.review_id,e.row.branch_file),r}i.won||s(e.row.review_id,e.row.branch_file),await a(i.request_id);const t=_(i.request_id);if(t===null)throw new Error(`realized review disappeared: ${i.request_id}`);return t}n(b,"createReview");export{b as createReview};