@jini-ai/core 0.7.2 → 0.7.3-next.1

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 (340) hide show
  1. package/CHANGELOG.md +0 -2
  2. package/README.md +40 -12
  3. package/dist/admin-runtime/admin-api-error.d.ts +68 -0
  4. package/dist/admin-runtime/admin-api-error.js +72 -0
  5. package/dist/admin-runtime/admin-config-error.d.ts +8 -0
  6. package/dist/admin-runtime/admin-config-error.js +11 -0
  7. package/dist/admin-runtime/controller-store.d.ts +20 -0
  8. package/dist/admin-runtime/controller-store.js +32 -0
  9. package/dist/admin-runtime/index.d.ts +13 -0
  10. package/dist/admin-runtime/index.js +12 -0
  11. package/dist/admin-runtime/panel-access.d.ts +88 -0
  12. package/dist/admin-runtime/panel-access.js +76 -0
  13. package/dist/admin-runtime/query-suffix.d.ts +5 -0
  14. package/dist/admin-runtime/query-suffix.js +5 -0
  15. package/dist/agent-handles/element-handles.d.ts +134 -0
  16. package/dist/agent-handles/element-handles.js +45 -0
  17. package/dist/agent-handles/field-descriptor.d.ts +28 -0
  18. package/dist/agent-handles/field-descriptor.js +3 -0
  19. package/dist/agent-handles/handle.d.ts +109 -0
  20. package/dist/agent-handles/handle.js +109 -0
  21. package/dist/agent-handles/index.d.ts +9 -0
  22. package/dist/agent-handles/index.js +6 -0
  23. package/dist/agent-handles/list-handles.d.ts +46 -0
  24. package/dist/agent-handles/list-handles.js +67 -0
  25. package/dist/agent-handles/secret-attrs.d.ts +14 -0
  26. package/dist/agent-handles/secret-attrs.js +13 -0
  27. package/dist/approval-batch-chain.d.ts +45 -0
  28. package/dist/approval-batch-chain.js +75 -0
  29. package/dist/approval.d.ts +33 -14
  30. package/dist/approval.js +57 -43
  31. package/dist/batch-tool-inputs.js +24 -20
  32. package/dist/contracts/admin-module.d.ts +166 -0
  33. package/dist/contracts/admin-module.js +14 -0
  34. package/dist/contracts/agents/definition.d.ts +459 -0
  35. package/dist/contracts/agents/definition.js +2 -0
  36. package/dist/contracts/agents/index.d.ts +7 -0
  37. package/dist/contracts/agents/index.js +2 -0
  38. package/dist/contracts/agents/launch.d.ts +64 -0
  39. package/dist/contracts/agents/launch.js +2 -0
  40. package/dist/contracts/agents/model-catalog.d.ts +213 -0
  41. package/dist/contracts/agents/model-catalog.js +4 -0
  42. package/dist/contracts/agents/native-tool-policy.d.ts +42 -0
  43. package/dist/contracts/agents/native-tool-policy.js +2 -0
  44. package/dist/contracts/ai-trace/capture.d.ts +17 -0
  45. package/dist/contracts/ai-trace/capture.js +43 -0
  46. package/dist/contracts/ai-trace/classify.d.ts +12 -0
  47. package/dist/contracts/ai-trace/classify.js +16 -0
  48. package/dist/contracts/ai-trace/index.d.ts +13 -0
  49. package/dist/contracts/ai-trace/index.js +6 -0
  50. package/dist/contracts/ai-trace/recorder.d.ts +64 -0
  51. package/dist/contracts/ai-trace/recorder.js +283 -0
  52. package/dist/contracts/ai-trace/sinks.d.ts +51 -0
  53. package/dist/contracts/ai-trace/sinks.js +153 -0
  54. package/dist/contracts/ai-trace/types.d.ts +123 -0
  55. package/dist/contracts/ai-trace/types.js +17 -0
  56. package/dist/contracts/ai-trace/usage.d.ts +16 -0
  57. package/dist/contracts/ai-trace/usage.js +45 -0
  58. package/dist/contracts/blob.d.ts +31 -0
  59. package/dist/contracts/blob.js +10 -0
  60. package/dist/contracts/capabilities.d.ts +95 -0
  61. package/dist/contracts/capabilities.js +111 -0
  62. package/dist/contracts/charts.d.ts +75 -0
  63. package/dist/contracts/charts.js +4 -0
  64. package/dist/contracts/env.d.ts +96 -0
  65. package/dist/contracts/env.js +6 -0
  66. package/dist/contracts/events/change-set.d.ts +106 -0
  67. package/dist/contracts/events/change-set.js +2 -0
  68. package/dist/contracts/events/command.d.ts +118 -0
  69. package/dist/contracts/events/command.js +2 -0
  70. package/dist/contracts/events/ports.d.ts +172 -0
  71. package/dist/contracts/events/ports.js +2 -0
  72. package/dist/contracts/events.d.ts +5 -0
  73. package/dist/contracts/events.js +2 -0
  74. package/dist/contracts/forms.d.ts +110 -0
  75. package/dist/contracts/forms.js +4 -0
  76. package/dist/contracts/hosted-mcp/config.d.ts +19 -0
  77. package/dist/contracts/hosted-mcp/record.d.ts +61 -4
  78. package/dist/contracts/mail/email-sender.d.ts +118 -0
  79. package/dist/contracts/mail/email-sender.js +20 -0
  80. package/dist/contracts/mail/smtp-payload.d.ts +32 -0
  81. package/dist/contracts/mail/smtp-payload.js +2 -0
  82. package/dist/contracts/mail.d.ts +2 -0
  83. package/dist/contracts/mail.js +1 -1
  84. package/dist/contracts/observability.d.ts +232 -0
  85. package/dist/contracts/observability.js +27 -0
  86. package/dist/contracts/plugin-sdk.d.ts +186 -0
  87. package/dist/contracts/plugin-sdk.js +39 -0
  88. package/dist/contracts/runtime/command.d.ts +41 -0
  89. package/dist/contracts/runtime/command.js +60 -0
  90. package/dist/contracts/runtime/environment.d.ts +18 -0
  91. package/dist/contracts/runtime/environment.js +26 -0
  92. package/dist/contracts/runtime/file-lock.d.ts +94 -0
  93. package/dist/contracts/runtime/file-lock.js +25 -0
  94. package/dist/contracts/runtime/fs.d.ts +33 -0
  95. package/dist/contracts/runtime/fs.js +2 -0
  96. package/dist/contracts/runtime/http.d.ts +89 -0
  97. package/dist/contracts/runtime/http.js +2 -0
  98. package/dist/contracts/runtime/platform.d.ts +3 -0
  99. package/dist/contracts/runtime/platform.js +2 -0
  100. package/dist/contracts/runtime/process.d.ts +40 -0
  101. package/dist/contracts/runtime/process.js +31 -0
  102. package/dist/contracts/runtime/reader.d.ts +11 -0
  103. package/dist/contracts/runtime/reader.js +2 -0
  104. package/dist/contracts/runtime/terminal.d.ts +99 -0
  105. package/dist/contracts/runtime/terminal.js +2 -0
  106. package/dist/contracts/runtime/testing.d.ts +84 -0
  107. package/dist/contracts/runtime/testing.js +116 -0
  108. package/dist/contracts/runtime.d.ts +10 -0
  109. package/dist/contracts/runtime.js +10 -0
  110. package/dist/contracts/server/api-error.d.ts +43 -0
  111. package/dist/contracts/server/api-error.js +49 -0
  112. package/dist/contracts/server/auth.d.ts +20 -0
  113. package/dist/contracts/server/auth.js +21 -0
  114. package/dist/contracts/server/conformance.d.ts +25 -0
  115. package/dist/contracts/server/conformance.js +50 -0
  116. package/dist/contracts/server/json-route.d.ts +176 -0
  117. package/dist/contracts/server/json-route.js +155 -0
  118. package/dist/contracts/server/middleware.d.ts +35 -0
  119. package/dist/contracts/server/middleware.js +56 -0
  120. package/dist/contracts/server/origin.d.ts +44 -0
  121. package/dist/contracts/server/origin.js +32 -0
  122. package/dist/contracts/server/query.d.ts +16 -0
  123. package/dist/contracts/server/query.js +69 -0
  124. package/dist/contracts/server/rate-limit.d.ts +20 -0
  125. package/dist/contracts/server/rate-limit.js +8 -0
  126. package/dist/contracts/server/request-body.d.ts +26 -0
  127. package/dist/contracts/server/request-body.js +82 -0
  128. package/dist/contracts/server/result.d.ts +17 -0
  129. package/dist/contracts/server/result.js +5 -0
  130. package/dist/contracts/server/route-table.d.ts +54 -0
  131. package/dist/contracts/server/route-table.js +119 -0
  132. package/dist/contracts/server/same-origin-write.d.ts +18 -0
  133. package/dist/contracts/server/same-origin-write.js +31 -0
  134. package/dist/contracts/server/security-headers.d.ts +30 -0
  135. package/dist/contracts/server/security-headers.js +35 -0
  136. package/dist/contracts/server/sse.d.ts +82 -0
  137. package/dist/contracts/server/sse.js +103 -0
  138. package/dist/contracts/server/testing.d.ts +59 -0
  139. package/dist/contracts/server/testing.js +68 -0
  140. package/dist/contracts/server/verified-origin/configured-origin.d.ts +37 -0
  141. package/dist/contracts/server/verified-origin/configured-origin.js +103 -0
  142. package/dist/contracts/server/verified-origin/index.d.ts +7 -0
  143. package/dist/contracts/server/verified-origin/index.js +6 -0
  144. package/dist/contracts/server/verified-origin/loopback-host.d.ts +9 -0
  145. package/dist/contracts/server/verified-origin/loopback-host.js +17 -0
  146. package/dist/contracts/server/verified-origin/origin.d.ts +64 -0
  147. package/dist/contracts/server/verified-origin/origin.js +162 -0
  148. package/dist/contracts/server/verified-origin/ports.d.ts +38 -0
  149. package/dist/contracts/server/verified-origin/ports.js +2 -0
  150. package/dist/contracts/server/verified-origin/repo.memory.d.ts +32 -0
  151. package/dist/contracts/server/verified-origin/repo.memory.js +34 -0
  152. package/dist/contracts/server/verified-origin/site-path.d.ts +113 -0
  153. package/dist/contracts/server/verified-origin/site-path.js +188 -0
  154. package/dist/contracts/server/verified-origin/types.d.ts +33 -0
  155. package/dist/contracts/server/verified-origin/types.js +30 -0
  156. package/dist/contracts/server.d.ts +46 -2
  157. package/dist/contracts/server.js +17 -3
  158. package/dist/contracts/storage/kernel.d.ts +86 -0
  159. package/dist/contracts/storage/kernel.js +38 -0
  160. package/dist/contracts/storage/migration.d.ts +32 -0
  161. package/dist/contracts/storage/migration.js +2 -0
  162. package/dist/contracts/storage/rows.d.ts +33 -0
  163. package/dist/contracts/storage/rows.js +42 -0
  164. package/dist/contracts/storage/sqlite.d.ts +113 -0
  165. package/dist/contracts/storage/sqlite.js +8 -0
  166. package/dist/contracts/storage/values.d.ts +25 -0
  167. package/dist/contracts/storage/values.js +25 -0
  168. package/dist/contracts/storage.d.ts +8 -0
  169. package/dist/contracts/storage.js +6 -0
  170. package/dist/contracts/vault/invariants.d.ts +26 -0
  171. package/dist/contracts/vault/invariants.js +49 -0
  172. package/dist/contracts/vault.d.ts +1 -0
  173. package/dist/contracts/vault.js +1 -1
  174. package/dist/env/coercers.d.ts +21 -0
  175. package/dist/env/coercers.js +68 -0
  176. package/dist/env/describe-env-for-diagnostics.d.ts +16 -0
  177. package/dist/env/describe-env-for-diagnostics.js +23 -0
  178. package/dist/env/format-env-issue.d.ts +13 -0
  179. package/dist/env/format-env-issue.js +22 -0
  180. package/dist/env/parse-env.d.ts +24 -0
  181. package/dist/env/parse-env.js +102 -0
  182. package/dist/env/value-echo.d.ts +17 -0
  183. package/dist/env/value-echo.js +42 -0
  184. package/dist/errors/approved-cause.d.ts +36 -0
  185. package/dist/errors/approved-cause.js +17 -0
  186. package/dist/errors/bindings.d.ts +61 -0
  187. package/dist/errors/bindings.js +57 -0
  188. package/dist/errors/catalog.d.ts +84 -0
  189. package/dist/errors/catalog.js +151 -0
  190. package/dist/errors/disclosure.d.ts +48 -0
  191. package/dist/errors/disclosure.js +27 -0
  192. package/dist/errors/error-id.d.ts +26 -0
  193. package/dist/errors/error-id.js +23 -0
  194. package/dist/errors/idioms.d.ts +73 -0
  195. package/dist/errors/idioms.js +85 -0
  196. package/dist/errors/incident-text.d.ts +16 -0
  197. package/dist/errors/incident-text.js +77 -0
  198. package/dist/errors/reporter.d.ts +94 -0
  199. package/dist/errors/reporter.js +152 -0
  200. package/dist/errors/sentences.d.ts +68 -0
  201. package/dist/errors/sentences.js +93 -0
  202. package/dist/errors/testing.d.ts +50 -0
  203. package/dist/errors/testing.js +44 -0
  204. package/dist/fetch/cache.d.ts +12 -5
  205. package/dist/fetch/cache.js +46 -47
  206. package/dist/fetch/index.d.ts +1 -1
  207. package/dist/fetch/loader-read.d.ts +6 -2
  208. package/dist/fetch/loader-read.js +4 -4
  209. package/dist/format-error-for-log.d.ts +15 -0
  210. package/dist/format-error-for-log.js +55 -0
  211. package/dist/host-read-vocabulary.d.ts +47 -0
  212. package/dist/host-read-vocabulary.js +44 -0
  213. package/dist/index.d.ts +5 -1
  214. package/dist/index.js +4 -0
  215. package/dist/list-page.d.ts +93 -0
  216. package/dist/list-page.js +154 -0
  217. package/dist/model-facing-tool-errors.d.ts +67 -5
  218. package/dist/model-facing-tool-errors.js +155 -19
  219. package/dist/net/endpoint-policy.d.ts +39 -0
  220. package/dist/net/endpoint-policy.js +218 -0
  221. package/dist/net/fetch-timeouts.d.ts +38 -0
  222. package/dist/net/fetch-timeouts.js +31 -0
  223. package/dist/net/index.d.ts +4 -0
  224. package/dist/net/index.js +4 -0
  225. package/dist/net/loopback.d.ts +13 -0
  226. package/dist/net/loopback.js +39 -0
  227. package/dist/optimistic-concurrency.d.ts +183 -0
  228. package/dist/optimistic-concurrency.js +222 -0
  229. package/dist/primitives/errors.d.ts +9 -0
  230. package/dist/primitives/errors.js +12 -0
  231. package/dist/primitives/ids.d.ts +0 -2
  232. package/dist/primitives/ids.js +1 -4
  233. package/dist/primitives/index.d.ts +3 -0
  234. package/dist/primitives/index.js +2 -0
  235. package/dist/primitives/logger.d.ts +36 -1
  236. package/dist/primitives/logger.js +125 -9
  237. package/dist/primitives/node-shape.d.ts +24 -0
  238. package/dist/primitives/node-shape.js +21 -0
  239. package/dist/primitives/time.d.ts +9 -2
  240. package/dist/primitives/time.js +4 -3
  241. package/dist/provider-registry.js +26 -20
  242. package/dist/records.d.ts +40 -7
  243. package/dist/records.js +37 -3
  244. package/dist/redact.d.ts +1 -84
  245. package/dist/redact.js +2 -826
  246. package/dist/redaction-collectors.d.ts +7 -0
  247. package/dist/redaction-collectors.js +152 -0
  248. package/dist/redaction-exact-secrets.d.ts +14 -0
  249. package/dist/redaction-exact-secrets.js +115 -0
  250. package/dist/redaction-labels.d.ts +14 -0
  251. package/dist/redaction-labels.js +156 -0
  252. package/dist/redaction-patterns.d.ts +54 -0
  253. package/dist/redaction-patterns.js +178 -0
  254. package/dist/redaction-spans.d.ts +31 -0
  255. package/dist/redaction-spans.js +83 -0
  256. package/dist/registration-kit.d.ts +1 -1
  257. package/dist/revision-conflict-error.d.ts +18 -0
  258. package/dist/revision-conflict-error.js +20 -0
  259. package/dist/secret-shapes.d.ts +50 -0
  260. package/dist/secret-shapes.js +105 -0
  261. package/dist/settings/agent-tools.js +22 -8
  262. package/dist/settings/agent-value-write-tools.d.ts +4 -1
  263. package/dist/settings/agent-value-write-tools.js +7 -6
  264. package/dist/settings/agent-writable-preferences.d.ts +3 -1
  265. package/dist/settings/agent-writable-preferences.js +1 -1
  266. package/dist/settings/agent-write-denylist.d.ts +7 -4
  267. package/dist/settings/agent-write-denylist.js +1 -1
  268. package/dist/settings/{express/cms-adapter.d.ts → cms-adapter.d.ts} +3 -2
  269. package/dist/settings/{express/cms-adapter.js → cms-adapter.js} +21 -11
  270. package/dist/settings/definitions-dispatch.js +3 -1
  271. package/dist/settings/ensure-definitions.js +3 -1
  272. package/dist/settings/errors.d.ts +1 -13
  273. package/dist/settings/errors.js +2 -15
  274. package/dist/settings/index.d.ts +11 -2
  275. package/dist/settings/index.js +10 -2
  276. package/dist/settings/purge-service.js +63 -86
  277. package/dist/settings/{express/contracts.d.ts → route-policy.d.ts} +53 -47
  278. package/dist/settings/{express/shared.js → route-policy.js} +1 -16
  279. package/dist/settings/settings.d.ts +19 -11
  280. package/dist/settings/settings.js +9 -11
  281. package/dist/settings/tool-registrations.d.ts +3 -3
  282. package/dist/settings/tool-registrations.js +130 -125
  283. package/dist/settings/types.d.ts +1 -1
  284. package/dist/settings/write-definition-rename.d.ts +37 -0
  285. package/dist/settings/write-definition-rename.js +119 -0
  286. package/dist/settings/write-definition-retype.d.ts +61 -0
  287. package/dist/settings/write-definition-retype.js +109 -0
  288. package/dist/settings/write-definition-status.d.ts +81 -0
  289. package/dist/settings/write-definition-status.js +121 -0
  290. package/dist/settings/write-reset.d.ts +34 -0
  291. package/dist/settings/write-reset.js +73 -0
  292. package/dist/settings/write-service.d.ts +16 -287
  293. package/dist/settings/write-service.js +49 -681
  294. package/dist/settings/write-value-revisions.d.ts +68 -0
  295. package/dist/settings/write-value-revisions.js +124 -0
  296. package/dist/settings/write-values.d.ts +96 -0
  297. package/dist/settings/write-values.js +83 -0
  298. package/dist/surface-exchanges.d.ts +2 -2
  299. package/dist/text/dictionary-translator.d.ts +19 -0
  300. package/dist/text/dictionary-translator.js +14 -0
  301. package/dist/text/format-byte-size.d.ts +25 -0
  302. package/dist/text/format-byte-size.js +25 -0
  303. package/dist/text/format-timestamp.d.ts +22 -0
  304. package/dist/text/format-timestamp.js +57 -0
  305. package/dist/text/index.d.ts +12 -0
  306. package/dist/text/index.js +9 -0
  307. package/dist/text/is-abort-error.d.ts +5 -0
  308. package/dist/text/is-abort-error.js +5 -0
  309. package/dist/text/mime.d.ts +5 -0
  310. package/dist/text/mime.js +21 -0
  311. package/dist/text/redact-urls.d.ts +7 -0
  312. package/dist/text/redact-urls.js +5 -0
  313. package/dist/text/resolve-active-tab-id.d.ts +13 -0
  314. package/dist/text/resolve-active-tab-id.js +15 -0
  315. package/dist/text/sanitize-untrusted-text.d.ts +1 -1
  316. package/dist/text/sanitize-untrusted-text.js +2 -1
  317. package/dist/text/tagged-text-suppression.d.ts +103 -0
  318. package/dist/text/tagged-text-suppression.js +143 -0
  319. package/dist/text/template-i18n.d.ts +37 -0
  320. package/dist/text/template-i18n.js +48 -0
  321. package/dist/tool-call-text.d.ts +59 -0
  322. package/dist/tool-call-text.js +62 -0
  323. package/dist/tool-input-envelope.js +8 -4
  324. package/dist/tool-input-normalization.js +8 -1
  325. package/dist/tool-input-repairs.d.ts +58 -0
  326. package/dist/tool-input-repairs.js +154 -0
  327. package/dist/tool-tokens.js +1 -1
  328. package/dist/user-facing-error.d.ts +1 -1
  329. package/dist/user-facing-error.js +3 -1
  330. package/package.json +234 -13
  331. package/dist/settings/express/contracts.js +0 -2
  332. package/dist/settings/express/http-request.d.ts +0 -33
  333. package/dist/settings/express/http-request.js +0 -50
  334. package/dist/settings/express/http.d.ts +0 -10
  335. package/dist/settings/express/http.js +0 -196
  336. package/dist/settings/express/index.d.ts +0 -5
  337. package/dist/settings/express/index.js +0 -4
  338. package/dist/settings/express/shared.d.ts +0 -68
  339. package/dist/settings/express/stream.d.ts +0 -24
  340. package/dist/settings/express/stream.js +0 -171
@@ -61,7 +61,7 @@ export function validateDefinitionInput(input) {
61
61
  }
62
62
  return { valid: true };
63
63
  }
64
- export function validateValueAgainstSchema(schema, value) {
64
+ export function validateValueAgainstSchema({ schema, value }, _optional = {}) {
65
65
  if (value === null)
66
66
  return schema.nullable === true;
67
67
  switch (schema.type) {
@@ -83,11 +83,8 @@ export function validateValueAgainstSchema(schema, value) {
83
83
  return false;
84
84
  }
85
85
  }
86
- /** Identity-registry of total coercers keyed by `coercionTag`. `"identity"` is always registered. See docs/decisions/DR-003-settings-ledger-invariants.md. */
87
- const coercers = new Map([["identity", ({ value }) => value]]);
88
- export function registerCoercer({ tag, fn }, _optional = {}) {
89
- coercers.set(tag, fn);
90
- }
86
+ /** Built-in total coercers keyed by `coercionTag`; never written after load. `"identity"` is always present. A host supplies its own tags per call through `getEffective`'s `coercers` option. See docs/decisions/DR-003-settings-ledger-invariants.md. */
87
+ const BUILTIN_COERCERS = new Map([["identity", ({ value }) => value]]);
91
88
  const cacheByRepo = new WeakMap();
92
89
  function getCacheStore(repo) {
93
90
  let store = cacheByRepo.get(repo);
@@ -114,7 +111,7 @@ function definitionCacheKey(workspaceId, namespace, key, epoch) {
114
111
  * definition's identity/shape/status in this namespace: register, rename
115
112
  * (both the old and new namespace), retype, deprecate, tombstone.
116
113
  */
117
- export function invalidateDefinitionNamespaceCache(repo, namespace) {
114
+ export function invalidateDefinitionNamespaceCache({ repo, namespace }, _optional = {}) {
118
115
  const store = getCacheStore(repo);
119
116
  store.epoch.set(namespace, namespaceEpoch(store, namespace) + 1);
120
117
  }
@@ -212,7 +209,7 @@ export async function resolveDefinition(deps, input) {
212
209
  * @overallScore 100
213
210
  * See docs/decisions/DR-003-settings-ledger-invariants.md.
214
211
  */
215
- export async function getEffective(deps, input) {
212
+ export async function getEffective({ deps, ...input }, { coercers } = {}) {
216
213
  const definition = await resolveDefinition(deps, {
217
214
  namespace: input.namespace,
218
215
  key: input.key,
@@ -222,14 +219,15 @@ export async function getEffective(deps, input) {
222
219
  return null;
223
220
  const hit = await firstSetLayer(deps.repo, definition.settingId, input.scopeContext);
224
221
  if (hit)
225
- return { value: coerceToVersion(definition, hit.record), sourceLayer: hit.sourceLayer, defVersion: definition.version };
222
+ return { value: coerceToVersion(definition, hit.record, coercers), sourceLayer: hit.sourceLayer, defVersion: definition.version };
226
223
  return { value: definition.defaultValue, sourceLayer: "default", defVersion: definition.version };
227
224
  }
228
225
  /** A value stored under an older definition version is coerced in memory (no write-back). O(1). */
229
- function coerceToVersion(definition, record) {
226
+ function coerceToVersion(definition, record, coercers) {
230
227
  if (record.defVersion === definition.version)
231
228
  return record.valueJson;
232
- const coercer = coercers.get(definition.coercionTag ?? "identity") ?? coercers.get("identity");
229
+ const tag = definition.coercionTag ?? "identity";
230
+ const coercer = coercers?.get(tag) ?? BUILTIN_COERCERS.get(tag) ?? BUILTIN_COERCERS.get("identity");
233
231
  return coercer({ value: record.valueJson });
234
232
  }
235
233
  /**
@@ -10,11 +10,11 @@ import type { Clock, IdGenerator } from "../primitives/index.js";
10
10
  import type { LegacyToolAuthorizeFn as AuthorizeFn } from "../tool-permissions.js";
11
11
  import { type SettingsWriteConfirmation } from "./agent-value-write-tools.js";
12
12
  import { type AgentSettingWriteRule } from "./agent-write-denylist.js";
13
- import { type DerivedRiskByToolId } from "../registration-kit.js";
13
+ import type { AgentToolSideEffect } from "../agent-tools.js";
14
14
  import { type ToolExecutionOptions, type ToolRegistration } from "../tool-registry.js";
15
15
  import type { SettingsPrincipalLookupPort } from "./principal-lookup.js";
16
16
  import type { SettingsRepoPort } from "./ports.js";
17
- import { set as setSettingValue } from "./write-service.js";
17
+ import { set as setSettingValue } from "./write-values.js";
18
18
  /**
19
19
  * The exact slice of a host's route-deps bag Settings' tool handlers read. Declared structurally
20
20
  * (rather than importing any host's own route-deps type) so this module carries no back-edge into
@@ -48,6 +48,6 @@ export interface SettingsToolDeps {
48
48
  * `sideEffects` declaration — and note that the two excluded bulk/schema writes appear NOWHERE here, which is
49
49
  * itself the strongest of the guards: an unclassified id cannot be wired at all.
50
50
  */
51
- export declare const settingsDerivedRisk: DerivedRiskByToolId;
51
+ export declare const settingsDerivedRisk: ReadonlyMap<string, AgentToolSideEffect>;
52
52
  export declare function buildSettingsRegistrations(routeDeps: SettingsToolDeps): ToolRegistration[];
53
53
  //# sourceMappingURL=tool-registrations.d.ts.map
@@ -9,7 +9,7 @@ import { AGENT_PREFERENCE_WRITE_SCOPE, AGENT_WRITABLE_PREFERENCE_IDS, resolveAge
9
9
  import { DefinitionNotFoundError, DefinitionTombstonedError, ScopeNotAllowedError, ValueValidationFailedError, } from "./errors.js";
10
10
  import { getEffective, resolveDefinition, resolveDefinitionRaw } from "./settings.js";
11
11
  import { SCOPE_BIT } from "./types.js";
12
- import { set as setSettingValue } from "./write-service.js";
12
+ import { set as setSettingValue } from "./write-values.js";
13
13
  const CATALOG_BY_ID = indexCatalogById({ catalog: getSettingsAgentToolCatalog() });
14
14
  /** Permission gating a read that names a DIFFERENT principal than the caller — mirrors a host's
15
15
  * own HTTP admin layer's equivalent constant (kept as a literal here per this file's header; the
@@ -110,7 +110,7 @@ async function describeDefinitionForAgent(routeDeps, rules, def) {
110
110
  ? await resolveDefinitionRaw({ repo: routeDeps.settingsRepo }, { namespace: def.namespace, key: def.key, workspaceId: routeDeps.workspaceId })
111
111
  : def;
112
112
  const coordinates = resolved ? [def, resolved] : [def];
113
- const matchesAny = (list) => coordinates.some((coordinate) => !!findAgentWriteRule(list, coordinate));
113
+ const matchesAny = (list) => coordinates.some((coordinate) => !!findAgentWriteRule({ rules: list, target: coordinate }));
114
114
  const denied = matchesAny(rules.denied);
115
115
  const confirmationRequired = matchesAny(rules.confirmation);
116
116
  const scopes = resolved?.scopes ?? def.scopes;
@@ -143,131 +143,136 @@ async function findDottedKeySplits(routeDeps, dottedKey) {
143
143
  }
144
144
  return matches;
145
145
  }
146
+ async function listDefinitionsHandler(routeDeps, ctx) {
147
+ const input = requireInputRecord({ input: ctx.input === undefined ? {} : ctx.input });
148
+ const search = optionalString({ input, key: "search" })?.toLowerCase();
149
+ const namespace = optionalString({ input, key: "namespace" });
150
+ await routeDeps.settingsReady;
151
+ await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: "settings.read.definitions" }, { entityType: "setting-definition" });
152
+ const [platformDefs, siteDefs] = await Promise.all([
153
+ routeDeps.settingsRepo.listActiveDefinitions({ workspaceId: null }),
154
+ routeDeps.settingsRepo.listActiveDefinitions({ workspaceId: routeDeps.workspaceId }),
155
+ ]);
156
+ // Filter only authorized workspace rows, before alias lookups; never search stored values.
157
+ const definitions = [...platformDefs, ...siteDefs]
158
+ .filter((def) => namespace === undefined || def.namespace === namespace)
159
+ .filter((def) => !search || `${def.namespace}.${def.key}`.toLowerCase().includes(search));
160
+ const rules = agentWriteRules(routeDeps);
161
+ const data = (await Promise.all(definitions.map((def) => describeDefinitionForAgent(routeDeps, rules, def))))
162
+ .sort((a, b) => a.namespace.localeCompare(b.namespace) || a.key.localeCompare(b.key));
163
+ return { data };
164
+ }
165
+ async function getEffectiveHandler(routeDeps, ctx) {
166
+ const input = requireInputRecord({ input: ctx.input });
167
+ const namespace = requireString({ input: input, key: "namespace" });
168
+ await routeDeps.settingsReady;
169
+ await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: "settings.read" }, { entityType: "setting-value" });
170
+ const workspaceId = routeDeps.workspaceId;
171
+ const principalId = await resolveOwnOrOtherPrincipalRead(routeDeps, {
172
+ requestedPrincipalId: optionalString({ input: input, key: "principalId" }),
173
+ callerPrincipalId: ctx.principal.id,
174
+ });
175
+ const [platformDefs, siteDefs] = await Promise.all([
176
+ routeDeps.settingsRepo.listActiveDefinitions({ workspaceId: null }),
177
+ routeDeps.settingsRepo.listActiveDefinitions({ workspaceId }),
178
+ ]);
179
+ const keys = new Set([...platformDefs, ...siteDefs].filter((d) => d.namespace === namespace).map((d) => d.key));
180
+ const data = [];
181
+ for (const key of keys) {
182
+ const resolved = await getEffective({ deps: { repo: routeDeps.settingsRepo }, namespace, key, scopeContext: { workspaceId, principalId } });
183
+ if (resolved)
184
+ data.push({ key, value: resolved.value, sourceLayer: resolved.sourceLayer, defVersion: resolved.defVersion });
185
+ }
186
+ return { data };
187
+ }
188
+ async function getRawHandler(routeDeps, ctx) {
189
+ const input = requireInputRecord({ input: ctx.input });
190
+ const namespace = requireString({ input: input, key: "namespace" });
191
+ const key = requireString({ input: input, key: "key" });
192
+ await routeDeps.settingsReady;
193
+ await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: "settings.read.raw" }, { entityType: "setting-value" });
194
+ const workspaceId = routeDeps.workspaceId;
195
+ const principalId = await resolveOwnOrOtherPrincipalRead(routeDeps, {
196
+ requestedPrincipalId: optionalString({ input: input, key: "principalId" }),
197
+ callerPrincipalId: ctx.principal.id,
198
+ });
199
+ const definition = await resolveDefinition({ repo: routeDeps.settingsRepo }, { namespace, key, workspaceId });
200
+ if (!definition)
201
+ throw new Error(`definition '${namespace}.${key}' was not found`);
202
+ const [globalValue, workspaceValue, userValue] = await Promise.all([
203
+ routeDeps.settingsRepo.getGlobalValue(definition.settingId),
204
+ routeDeps.settingsRepo.getWorkspaceValue({ workspaceId, settingId: definition.settingId }),
205
+ principalId ? routeDeps.settingsRepo.getUserValue({ workspaceId, principalId, settingId: definition.settingId }) : Promise.resolve(null),
206
+ ]);
207
+ return {
208
+ key: `${namespace}.${key}`,
209
+ global: layerValueOf(globalValue),
210
+ workspace: layerValueOf(workspaceValue),
211
+ user: layerValueOf(userValue),
212
+ default: definition.defaultValue,
213
+ };
214
+ }
215
+ async function setUiPreferenceHandler(routeDeps, ctx) {
216
+ const input = requireInputRecord({ input: ctx.input });
217
+ const settingId = requireString({ input: input, key: "setting" });
218
+ // Re-checked here even though the published schema carries the same enum. See
219
+ // `agent-writable-preferences.ts` on why: the enum is enforced by a caller's descriptor
220
+ // validation, and this is the check that still holds if a stale or bypassed descriptor lets
221
+ // an unlisted id through. Rejected BEFORE `settingsUiTabsReady` is awaited so an unlisted id
222
+ // cannot even be used to probe which definitions exist.
223
+ const preference = resolveAgentWritablePreference({ settingId });
224
+ if (!preference) {
225
+ throw new Error(`'${settingId}' is not an agent-writable preference. Allowed: ${AGENT_WRITABLE_PREFERENCE_IDS.join(", ")}.`);
226
+ }
227
+ // `in` rather than a truthiness check: `false` and `0` are legitimate values here
228
+ // (`soundEnabled`, `desktopEnabled`), and rejecting them would make the two boolean
229
+ // preferences settable in one direction only.
230
+ if (!("value" in input)) {
231
+ throw new Error(`a 'value' is required to set '${settingId}'`);
232
+ }
233
+ const value = input.value;
234
+ // This tool's definitions are registered by `ensureSettingsUiTabDefinitions()` at boot, not
235
+ // by any legacy-migration promise a host might also cover — awaiting the wrong promise would
236
+ // make an early call fail with a spurious "definition was not found".
237
+ await routeDeps.settingsUiTabsReady;
238
+ // No `requireToolPermission` call here, unlike every read above. That is deliberate and is
239
+ // the opposite of the reads' situation: the read paths carry no `authorize()` of their own,
240
+ // so this layer must supply it, whereas `write-service.set()` IS the authorization
241
+ // chokepoint and derives the permission itself from the scope and target. Adding a. See docs/decisions/DR-003-settings-ledger-invariants.md.
242
+ // pre-check would mean this file naming a permission string that the chokepoint might later
243
+ // derive differently — the exact fail-open drift `deriveRequiredPermission`'s own header
244
+ // (Red-Team ) says must not be duplicated. Omitting `principalId` is what makes the. See docs/decisions/DR-003-settings-ledger-invariants.md.
245
+ // derived permission `settings.user.self.write`.
246
+ ctx.signal.throwIfAborted();
247
+ const { value: stored, revisionSeq } = await withSchemaOnRejection({
248
+ toolId: "settings_set_ui_preference",
249
+ catalog: CATALOG_BY_ID,
250
+ isShapeRejection: ({ error }) => isPreferenceShapeRejection(error), fn: () => setSettingValue({
251
+ deps: toWriteDeps(routeDeps),
252
+ input: {
253
+ namespace: preference.namespace,
254
+ key: preference.key,
255
+ scope: AGENT_PREFERENCE_WRITE_SCOPE,
256
+ value,
257
+ workspaceId: routeDeps.workspaceId,
258
+ // `principalId` is deliberately NOT passed. `write-service.set()` falls back to
259
+ // `callerPrincipalId` for a user-scoped write, so the caller's own layer is the only
260
+ // reachable target — and the self-vs-other permission derivation sees a self-write.
261
+ callerPrincipalId: ctx.principal.id,
262
+ authWorkspaceId: routeDeps.workspaceId,
263
+ },
264
+ })
265
+ });
266
+ return { setting: settingId, value: stored, scope: AGENT_PREFERENCE_WRITE_SCOPE, revisionSeq };
267
+ }
146
268
  export function buildSettingsRegistrations(routeDeps) {
147
269
  const handlers = {
148
- settings_set_value: buildSettingsValueWriteHandler(routeDeps, "settings_set_value"),
149
- settings_clear_value: buildSettingsValueWriteHandler(routeDeps, "settings_clear_value"),
150
- settings_list_definitions: async (ctx) => {
151
- const input = requireInputRecord({ input: ctx.input === undefined ? {} : ctx.input });
152
- const search = optionalString({ input, key: "search" })?.toLowerCase();
153
- const namespace = optionalString({ input, key: "namespace" });
154
- await routeDeps.settingsReady;
155
- await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: "settings.read.definitions" }, { entityType: "setting-definition" });
156
- const [platformDefs, siteDefs] = await Promise.all([
157
- routeDeps.settingsRepo.listActiveDefinitions({ workspaceId: null }),
158
- routeDeps.settingsRepo.listActiveDefinitions({ workspaceId: routeDeps.workspaceId }),
159
- ]);
160
- // Filter only authorized workspace rows, before alias lookups; never search stored values.
161
- const definitions = [...platformDefs, ...siteDefs]
162
- .filter((def) => namespace === undefined || def.namespace === namespace)
163
- .filter((def) => !search || `${def.namespace}.${def.key}`.toLowerCase().includes(search));
164
- const rules = agentWriteRules(routeDeps);
165
- const data = (await Promise.all(definitions.map((def) => describeDefinitionForAgent(routeDeps, rules, def))))
166
- .sort((a, b) => a.namespace.localeCompare(b.namespace) || a.key.localeCompare(b.key));
167
- return { data };
168
- },
169
- settings_get_effective: async (ctx) => {
170
- const input = requireInputRecord({ input: ctx.input });
171
- const namespace = requireString({ input: input, key: "namespace" });
172
- await routeDeps.settingsReady;
173
- await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: "settings.read" }, { entityType: "setting-value" });
174
- const workspaceId = routeDeps.workspaceId;
175
- const principalId = await resolveOwnOrOtherPrincipalRead(routeDeps, {
176
- requestedPrincipalId: optionalString({ input: input, key: "principalId" }),
177
- callerPrincipalId: ctx.principal.id,
178
- });
179
- const [platformDefs, siteDefs] = await Promise.all([
180
- routeDeps.settingsRepo.listActiveDefinitions({ workspaceId: null }),
181
- routeDeps.settingsRepo.listActiveDefinitions({ workspaceId }),
182
- ]);
183
- const keys = new Set([...platformDefs, ...siteDefs].filter((d) => d.namespace === namespace).map((d) => d.key));
184
- const data = [];
185
- for (const key of keys) {
186
- const resolved = await getEffective({ repo: routeDeps.settingsRepo }, { namespace, key, scopeContext: { workspaceId, principalId } });
187
- if (resolved)
188
- data.push({ key, value: resolved.value, sourceLayer: resolved.sourceLayer, defVersion: resolved.defVersion });
189
- }
190
- return { data };
191
- },
192
- settings_get_raw: async (ctx) => {
193
- const input = requireInputRecord({ input: ctx.input });
194
- const namespace = requireString({ input: input, key: "namespace" });
195
- const key = requireString({ input: input, key: "key" });
196
- await routeDeps.settingsReady;
197
- await requireToolPermission({ authorize: adaptLegacyAuthorize({ authorize: routeDeps.authorize }), workspaceId: routeDeps.workspaceId, principalId: ctx.principal.id, permission: "settings.read.raw" }, { entityType: "setting-value" });
198
- const workspaceId = routeDeps.workspaceId;
199
- const principalId = await resolveOwnOrOtherPrincipalRead(routeDeps, {
200
- requestedPrincipalId: optionalString({ input: input, key: "principalId" }),
201
- callerPrincipalId: ctx.principal.id,
202
- });
203
- const definition = await resolveDefinition({ repo: routeDeps.settingsRepo }, { namespace, key, workspaceId });
204
- if (!definition)
205
- throw new Error(`definition '${namespace}.${key}' was not found`);
206
- const [globalValue, workspaceValue, userValue] = await Promise.all([
207
- routeDeps.settingsRepo.getGlobalValue(definition.settingId),
208
- routeDeps.settingsRepo.getWorkspaceValue({ workspaceId, settingId: definition.settingId }),
209
- principalId ? routeDeps.settingsRepo.getUserValue({ workspaceId, principalId, settingId: definition.settingId }) : Promise.resolve(null),
210
- ]);
211
- return {
212
- key: `${namespace}.${key}`,
213
- global: layerValueOf(globalValue),
214
- workspace: layerValueOf(workspaceValue),
215
- user: layerValueOf(userValue),
216
- default: definition.defaultValue,
217
- };
218
- },
219
- settings_set_ui_preference: async (ctx) => {
220
- const input = requireInputRecord({ input: ctx.input });
221
- const settingId = requireString({ input: input, key: "setting" });
222
- // Re-checked here even though the published schema carries the same enum. See
223
- // `agent-writable-preferences.ts` on why: the enum is enforced by a caller's descriptor
224
- // validation, and this is the check that still holds if a stale or bypassed descriptor lets
225
- // an unlisted id through. Rejected BEFORE `settingsUiTabsReady` is awaited so an unlisted id
226
- // cannot even be used to probe which definitions exist.
227
- const preference = resolveAgentWritablePreference(settingId);
228
- if (!preference) {
229
- throw new Error(`'${settingId}' is not an agent-writable preference. Allowed: ${AGENT_WRITABLE_PREFERENCE_IDS.join(", ")}.`);
230
- }
231
- // `in` rather than a truthiness check: `false` and `0` are legitimate values here
232
- // (`soundEnabled`, `desktopEnabled`), and rejecting them would make the two boolean
233
- // preferences settable in one direction only.
234
- if (!("value" in input)) {
235
- throw new Error(`a 'value' is required to set '${settingId}'`);
236
- }
237
- const value = input.value;
238
- // This tool's definitions are registered by `ensureSettingsUiTabDefinitions()` at boot, not
239
- // by any legacy-migration promise a host might also cover — awaiting the wrong promise would
240
- // make an early call fail with a spurious "definition was not found".
241
- await routeDeps.settingsUiTabsReady;
242
- // No `requireToolPermission` call here, unlike every read above. That is deliberate and is
243
- // the opposite of the reads' situation: the read paths carry no `authorize()` of their own,
244
- // so this layer must supply it, whereas `write-service.set()` IS the authorization
245
- // chokepoint and derives the permission itself from the scope and target. Adding a. See docs/decisions/DR-003-settings-ledger-invariants.md.
246
- // pre-check would mean this file naming a permission string that the chokepoint might later
247
- // derive differently — the exact fail-open drift `deriveRequiredPermission`'s own header
248
- // (Red-Team ) says must not be duplicated. Omitting `principalId` is what makes the. See docs/decisions/DR-003-settings-ledger-invariants.md.
249
- // derived permission `settings.user.self.write`.
250
- const { value: stored, revisionSeq } = await withSchemaOnRejection({
251
- toolId: "settings_set_ui_preference",
252
- catalog: CATALOG_BY_ID,
253
- isShapeRejection: ({ error }) => isPreferenceShapeRejection(error), fn: () => setSettingValue({
254
- deps: toWriteDeps(routeDeps),
255
- input: {
256
- namespace: preference.namespace,
257
- key: preference.key,
258
- scope: AGENT_PREFERENCE_WRITE_SCOPE,
259
- value,
260
- workspaceId: routeDeps.workspaceId,
261
- // `principalId` is deliberately NOT passed. `write-service.set()` falls back to
262
- // `callerPrincipalId` for a user-scoped write, so the caller's own layer is the only
263
- // reachable target — and the self-vs-other permission derivation sees a self-write.
264
- callerPrincipalId: ctx.principal.id,
265
- authWorkspaceId: routeDeps.workspaceId,
266
- },
267
- })
268
- });
269
- return { setting: settingId, value: stored, scope: AGENT_PREFERENCE_WRITE_SCOPE, revisionSeq };
270
- },
270
+ settings_set_value: buildSettingsValueWriteHandler({ deps: routeDeps, toolId: "settings_set_value" }),
271
+ settings_clear_value: buildSettingsValueWriteHandler({ deps: routeDeps, toolId: "settings_clear_value" }),
272
+ settings_list_definitions: (ctx) => listDefinitionsHandler(routeDeps, ctx),
273
+ settings_get_effective: (ctx) => getEffectiveHandler(routeDeps, ctx),
274
+ settings_get_raw: (ctx) => getRawHandler(routeDeps, ctx),
275
+ settings_set_ui_preference: (ctx) => setUiPreferenceHandler(routeDeps, ctx),
271
276
  };
272
277
  return buildDomainRegistrations({ domain: "settings", catalogModule: "settings/agent-tools.ts", catalog: CATALOG_BY_ID, handlers, derivedRisk: settingsDerivedRisk,
273
278
  inputNormalizers: { settings_set_value: async ({ input }) => {
@@ -5,7 +5,7 @@ import type { ISODateTime, JsonValue, UUID } from "../primitives/index.js";
5
5
  * Purpose:
6
6
  * Record shapes + the schema-validation vocabulary shared by `settings.ts`,
7
7
  * `write-service.ts`, `purge-service.ts`, and both repo adapters. Interfaces
8
- * and types only — no feature logic (mirrors `identity/types.ts`).
8
+ * and types only — no feature logic (mirrors `packages/user-management/src/core/types.ts`).
9
9
  */
10
10
  export type SettingScope = "global" | "workspace" | "user";
11
11
  export type SettingOwnerKind = "core" | "site" | "theme";
@@ -0,0 +1,37 @@
1
+ import type { UUID } from "../primitives/index.js";
2
+ import { type SettingsWriteServiceDeps } from './write-service.js';
3
+ export interface RenameDefinitionRequired {
4
+ deps: SettingsWriteServiceDeps;
5
+ input: {
6
+ namespace: string;
7
+ key: string;
8
+ workspaceId: UUID | null;
9
+ newNamespace: string;
10
+ newKey: string;
11
+ callerPrincipalId: UUID;
12
+ /** The workspace the caller is authorizing in (see `registerDefinitions`' identical field). */
13
+ authWorkspaceId: UUID;
14
+ };
15
+ }
16
+ /**
17
+ * The rename mechanism : a same-tx pair —
18
+ * (1) UPDATE the active definition row's `(namespace,key)` to the new name,
19
+ * same `setting_id`/`version` (ledgered `op='alias'`); (2) INSERT a fresh v1
20
+ * alias marker at the OLD name pointing at the new name. Because identity
21
+ * never moves, value rows (keyed on `setting_id` only) stay attached.
22
+ *
23
+ * Sequential rename (A->B then B->C) retargets every prior marker pointing
24
+ * at the OLD name to the NEW name in the same tx. A rename target that
25
+ * itself resolves to an existing alias is rejected `ALIAS_DEPTH_EXCEEDED`
26
+ * (behavior.spec.md §7: "the rename target resolves to an alias").
27
+ *
28
+ * Never touches `schema`/`defaultValue`/`scopes` -- a pure rename can never
29
+ * trigger `RENAME_RETYPE_CONFLICT` by construction; that guard lives in
30
+ * `retypeDefinition` ("no rename+retype in one op").
31
+ * See docs/decisions/DR-003-settings-ledger-invariants.md.
32
+ */
33
+ export declare function renameDefinition(required: RenameDefinitionRequired): Promise<{
34
+ settingId: string;
35
+ markerSettingId: string;
36
+ }>;
37
+ //# sourceMappingURL=write-definition-rename.d.ts.map
@@ -0,0 +1,119 @@
1
+ import { nowIso as kernelNowIso } from "../primitives/index.js";
2
+ import { AliasDepthExceededError, DefinitionInvalidError } from "./errors.js";
3
+ import { invalidateDefinitionNamespaceCache } from "./settings.js";
4
+ import {} from "./types.js";
5
+ import { authorizeDefinitionsManage, resolveActiveDefinitionOrThrow } from './write-service.js';
6
+ async function assertRenameTargetFree(deps, input) {
7
+ // A dispatched `rename` item that omits its target arrives here as `""` (see definitions-dispatch);
8
+ // without this guard the definition was silently moved to the empty name `.`.
9
+ if (!input.newNamespace || !input.newKey) {
10
+ throw new DefinitionInvalidError("rename requires a non-empty newNamespace and newKey");
11
+ }
12
+ if (input.namespace === input.newNamespace && input.key === input.newKey) {
13
+ throw new DefinitionInvalidError("rename requires newNamespace/newKey to differ from the current name");
14
+ }
15
+ const destination = await deps.repo.findActiveDefinition({
16
+ namespace: input.newNamespace,
17
+ key: input.newKey,
18
+ workspaceId: input.workspaceId,
19
+ });
20
+ if (destination) {
21
+ if (destination.status === "alias") {
22
+ throw new AliasDepthExceededError(`rename target '${input.newNamespace}.${input.newKey}' resolves to an existing alias marker; a marker's alias_of must point to an active definition (depth <=1)`);
23
+ }
24
+ throw new DefinitionInvalidError(`rename target '${input.newNamespace}.${input.newKey}' is already in use`);
25
+ }
26
+ }
27
+ /** Sequential rename: retarget every prior marker pointing at the OLD name to the NEW name. */
28
+ async function retargetPriorAliasMarkers({ deps, input, now }) {
29
+ const siblings = await deps.repo.listActiveDefinitions({ workspaceId: input.workspaceId });
30
+ for (const sibling of siblings) {
31
+ if (sibling.status === "alias" &&
32
+ sibling.aliasOfNamespace === input.namespace &&
33
+ sibling.aliasOfKey === input.key) {
34
+ await deps.repo.saveDefinition({
35
+ ...sibling,
36
+ aliasOfNamespace: input.newNamespace,
37
+ aliasOfKey: input.newKey,
38
+ updatedAt: now,
39
+ });
40
+ }
41
+ }
42
+ }
43
+ /** Step 2: insert a fresh v1 alias marker at the OLD name pointing at the NEW name. */
44
+ async function insertRenameAliasMarker({ deps, input, current, now }) {
45
+ const markerSettingId = deps.ids.newId();
46
+ await deps.repo.saveDefinition({
47
+ settingId: markerSettingId,
48
+ version: 1,
49
+ workspaceId: input.workspaceId,
50
+ namespace: input.namespace,
51
+ key: input.key,
52
+ ownerKind: current.ownerKind,
53
+ ownerId: current.ownerId,
54
+ schema: current.schema,
55
+ defaultValue: current.defaultValue,
56
+ scopes: current.scopes,
57
+ secret: current.secret,
58
+ status: "alias",
59
+ aliasOfNamespace: input.newNamespace,
60
+ aliasOfKey: input.newKey,
61
+ coercionTag: null,
62
+ createdAt: now,
63
+ updatedAt: now,
64
+ });
65
+ return markerSettingId;
66
+ }
67
+ async function applyRenameInTransaction({ deps, input, current }) {
68
+ const now = kernelNowIso({ clock: deps.clock });
69
+ // Step 1: move the active row to the new name -- same setting_id, same version.
70
+ await deps.repo.saveDefinition({ ...current, namespace: input.newNamespace, key: input.newKey, updatedAt: now });
71
+ await retargetPriorAliasMarkers({ deps, input, now });
72
+ const markerSettingId = await insertRenameAliasMarker({ deps, input, current, now });
73
+ await deps.repo.appendRevision({
74
+ entityKind: "definition",
75
+ settingId: current.settingId,
76
+ scope: null,
77
+ workspaceId: input.workspaceId,
78
+ principalId: null,
79
+ op: "alias",
80
+ beforeJson: null,
81
+ afterJson: null,
82
+ defVersion: current.version,
83
+ actor: input.callerPrincipalId,
84
+ originPluginId: null,
85
+ changeSetId: null,
86
+ createdAt: now,
87
+ });
88
+ return { settingId: current.settingId, markerSettingId };
89
+ }
90
+ /**
91
+ * The rename mechanism : a same-tx pair —
92
+ * (1) UPDATE the active definition row's `(namespace,key)` to the new name,
93
+ * same `setting_id`/`version` (ledgered `op='alias'`); (2) INSERT a fresh v1
94
+ * alias marker at the OLD name pointing at the new name. Because identity
95
+ * never moves, value rows (keyed on `setting_id` only) stay attached.
96
+ *
97
+ * Sequential rename (A->B then B->C) retargets every prior marker pointing
98
+ * at the OLD name to the NEW name in the same tx. A rename target that
99
+ * itself resolves to an existing alias is rejected `ALIAS_DEPTH_EXCEEDED`
100
+ * (behavior.spec.md §7: "the rename target resolves to an alias").
101
+ *
102
+ * Never touches `schema`/`defaultValue`/`scopes` -- a pure rename can never
103
+ * trigger `RENAME_RETYPE_CONFLICT` by construction; that guard lives in
104
+ * `retypeDefinition` ("no rename+retype in one op").
105
+ * See docs/decisions/DR-003-settings-ledger-invariants.md.
106
+ */
107
+ export async function renameDefinition(required) {
108
+ const { deps, input } = required;
109
+ await authorizeDefinitionsManage(deps, input.callerPrincipalId, input.authWorkspaceId);
110
+ const current = await resolveActiveDefinitionOrThrow(deps, input, "rename");
111
+ await assertRenameTargetFree(deps, input);
112
+ const result = await deps.repo.transaction(() => applyRenameInTransaction({ deps, input, current }));
113
+ // Both the old (alias-marker) namespace and the new (active-row) namespace
114
+ // need a fresh definition-cache read after a rename.
115
+ invalidateDefinitionNamespaceCache({ repo: deps.repo, namespace: input.namespace });
116
+ invalidateDefinitionNamespaceCache({ repo: deps.repo, namespace: input.newNamespace });
117
+ return result;
118
+ }
119
+ //# sourceMappingURL=write-definition-rename.js.map
@@ -0,0 +1,61 @@
1
+ import type { JsonValue, UUID } from "../primitives/index.js";
2
+ import { type SettingValueSchema } from "./types.js";
3
+ import { type SettingsWriteServiceDeps } from './write-service.js';
4
+ export interface RetypeDefinitionRequired {
5
+ deps: SettingsWriteServiceDeps;
6
+ input: {
7
+ namespace: string;
8
+ key: string;
9
+ workspaceId: UUID | null;
10
+ schema: SettingValueSchema;
11
+ defaultValue: JsonValue | null;
12
+ /** A total coercer id/tag ( registry in `settings.ts`) for reading values recorded under any prior version. See docs/decisions/DR-003-settings-ledger-invariants.md. */
13
+ coercionTag: string;
14
+ /**
15
+ * Present only to detect a combined rename+retype request;
16
+ * retype never actually moves `(namespace,key)` -- if provided and it
17
+ * differs from the current name while `schema` also differs, the whole
18
+ * op is rejected `RENAME_RETYPE_CONFLICT` rather than silently doing
19
+ * only the schema half.
20
+ */
21
+ newNamespace?: string | undefined;
22
+ newKey?: string | undefined;
23
+ callerPrincipalId: UUID;
24
+ authWorkspaceId: UUID;
25
+ };
26
+ }
27
+ /**
28
+ * The retype mechanism : a same-tx pair --
29
+ * (1) UPDATE the prior active version's `status` to `deprecated` FIRST (else
30
+ * the insert in step 2 collides with the one-active-row-per-slot
31
+ * invariant); (2) INSERT the new `version+1` row as `active`, same
32
+ * `setting_id`/`namespace`/`key`. Rejected unless every prior version
33
+ * (2..N) already carries a total coercer -- `coercionTag` is `null` only for
34
+ * version 1 by construction (`types.ts`), so this walks 2..N and requires
35
+ * each to be non-null.
36
+ * See docs/decisions/DR-003-settings-ledger-invariants.md.
37
+ */
38
+ export declare function retypeDefinition(required: RetypeDefinitionRequired): Promise<{
39
+ settingId: string;
40
+ version: number;
41
+ }>;
42
+ /** Add source-declared scopes to a core definition without moving or rewriting existing values.
43
+ * Boot uses this when a workspace preference gains a personal override. Scope removal is a
44
+ * separate migration decision: this operation only adds bits and preserves definition identity.
45
+ * @throws DefinitionInvalidError for operator-owned definitions or invalid scope bits.
46
+ * @complexity O(1), one definition transaction and cache invalidation.
47
+ * @example await extendDefinitionScopes({ deps, input: { namespace, key, workspaceId: null,
48
+ * scopes: SCOPE_BIT.user, callerPrincipalId, authWorkspaceId } });
49
+ */
50
+ export declare function extendDefinitionScopes({ deps, input }: {
51
+ deps: SettingsWriteServiceDeps;
52
+ input: {
53
+ namespace: string;
54
+ key: string;
55
+ workspaceId: UUID | null;
56
+ scopes: number;
57
+ callerPrincipalId: UUID;
58
+ authWorkspaceId: UUID;
59
+ };
60
+ }, _options?: {}): Promise<void>;
61
+ //# sourceMappingURL=write-definition-retype.d.ts.map