@kindgi/api 0.1.3 → 0.1.4-rc.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 (222) hide show
  1. package/dist/agent-binding.d.ts +26 -4
  2. package/dist/agent-binding.d.ts.map +1 -1
  3. package/dist/agent-pins.d.ts +48 -0
  4. package/dist/agent-pins.d.ts.map +1 -0
  5. package/dist/agent-pins.js +102 -0
  6. package/dist/agent-pins.js.map +1 -0
  7. package/dist/app.d.ts +22 -0
  8. package/dist/app.d.ts.map +1 -1
  9. package/dist/app.js +27 -3
  10. package/dist/app.js.map +1 -1
  11. package/dist/block-binding.d.ts +132 -0
  12. package/dist/block-binding.d.ts.map +1 -0
  13. package/dist/block-binding.js +4 -0
  14. package/dist/block-binding.js.map +1 -0
  15. package/dist/block-pins.d.ts +22 -0
  16. package/dist/block-pins.d.ts.map +1 -0
  17. package/dist/block-pins.js +112 -0
  18. package/dist/block-pins.js.map +1 -0
  19. package/dist/cost-binding.d.ts +20 -1
  20. package/dist/cost-binding.d.ts.map +1 -1
  21. package/dist/cost-binding.js +4 -0
  22. package/dist/cost-binding.js.map +1 -1
  23. package/dist/deploy-versions.d.ts +60 -0
  24. package/dist/deploy-versions.d.ts.map +1 -0
  25. package/dist/deploy-versions.js +91 -0
  26. package/dist/deploy-versions.js.map +1 -0
  27. package/dist/deployment-binding.d.ts +24 -3
  28. package/dist/deployment-binding.d.ts.map +1 -1
  29. package/dist/derive-agent-version.d.ts +77 -0
  30. package/dist/derive-agent-version.d.ts.map +1 -0
  31. package/dist/derive-agent-version.js +149 -0
  32. package/dist/derive-agent-version.js.map +1 -0
  33. package/dist/errors.d.ts.map +1 -1
  34. package/dist/errors.js +18 -0
  35. package/dist/errors.js.map +1 -1
  36. package/dist/eval-case-binding.d.ts +65 -0
  37. package/dist/eval-case-binding.d.ts.map +1 -0
  38. package/dist/eval-case-binding.js +4 -0
  39. package/dist/eval-case-binding.js.map +1 -0
  40. package/dist/eval-run-binding.d.ts +37 -0
  41. package/dist/eval-run-binding.d.ts.map +1 -1
  42. package/dist/eval-run-binding.js.map +1 -1
  43. package/dist/eval-run-dispatcher.d.ts +41 -3
  44. package/dist/eval-run-dispatcher.d.ts.map +1 -1
  45. package/dist/eval-run-dispatcher.js +21 -15
  46. package/dist/eval-run-dispatcher.js.map +1 -1
  47. package/dist/eval-suite-binding.d.ts +1 -1
  48. package/dist/eval-suite-binding.d.ts.map +1 -1
  49. package/dist/eval-suite-binding.js +2 -0
  50. package/dist/eval-suite-binding.js.map +1 -1
  51. package/dist/flow-binding.d.ts +18 -4
  52. package/dist/flow-binding.d.ts.map +1 -1
  53. package/dist/flow-pins.d.ts +36 -0
  54. package/dist/flow-pins.d.ts.map +1 -0
  55. package/dist/flow-pins.js +81 -0
  56. package/dist/flow-pins.js.map +1 -0
  57. package/dist/guardrail-binding.d.ts +8 -0
  58. package/dist/guardrail-binding.d.ts.map +1 -1
  59. package/dist/handler-binding.d.ts +3 -0
  60. package/dist/handler-binding.d.ts.map +1 -1
  61. package/dist/index.d.ts +18 -6
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +8 -2
  64. package/dist/index.js.map +1 -1
  65. package/dist/judged-dispatcher.d.ts +138 -0
  66. package/dist/judged-dispatcher.d.ts.map +1 -0
  67. package/dist/judged-dispatcher.js +308 -0
  68. package/dist/judged-dispatcher.js.map +1 -0
  69. package/dist/judged-items.d.ts +86 -0
  70. package/dist/judged-items.d.ts.map +1 -0
  71. package/dist/judged-items.js +184 -0
  72. package/dist/judged-items.js.map +1 -0
  73. package/dist/judgment-binding.d.ts +316 -0
  74. package/dist/judgment-binding.d.ts.map +1 -0
  75. package/dist/judgment-binding.js +19 -0
  76. package/dist/judgment-binding.js.map +1 -0
  77. package/dist/openapi/generate.d.ts.map +1 -1
  78. package/dist/openapi/generate.js +4 -1
  79. package/dist/openapi/generate.js.map +1 -1
  80. package/dist/openapi/operations.d.ts.map +1 -1
  81. package/dist/openapi/operations.js +482 -13
  82. package/dist/openapi/operations.js.map +1 -1
  83. package/dist/openapi/schemas.d.ts +46 -0
  84. package/dist/openapi/schemas.d.ts.map +1 -1
  85. package/dist/openapi/schemas.js +1350 -175
  86. package/dist/openapi/schemas.js.map +1 -1
  87. package/dist/provider-binding.d.ts +12 -7
  88. package/dist/provider-binding.d.ts.map +1 -1
  89. package/dist/registry-read-only.d.ts +32 -0
  90. package/dist/registry-read-only.d.ts.map +1 -0
  91. package/dist/registry-read-only.js +22 -0
  92. package/dist/registry-read-only.js.map +1 -0
  93. package/dist/routes/agents.d.ts +9 -1
  94. package/dist/routes/agents.d.ts.map +1 -1
  95. package/dist/routes/agents.js +181 -11
  96. package/dist/routes/agents.js.map +1 -1
  97. package/dist/routes/blocks.d.ts +19 -0
  98. package/dist/routes/blocks.d.ts.map +1 -0
  99. package/dist/routes/blocks.js +306 -0
  100. package/dist/routes/blocks.js.map +1 -0
  101. package/dist/routes/cost.d.ts.map +1 -1
  102. package/dist/routes/cost.js +47 -2
  103. package/dist/routes/cost.js.map +1 -1
  104. package/dist/routes/deployments.d.ts +3 -0
  105. package/dist/routes/deployments.d.ts.map +1 -1
  106. package/dist/routes/deployments.js +224 -55
  107. package/dist/routes/deployments.js.map +1 -1
  108. package/dist/routes/eval-comparison.d.ts +15 -0
  109. package/dist/routes/eval-comparison.d.ts.map +1 -0
  110. package/dist/routes/eval-comparison.js +123 -0
  111. package/dist/routes/eval-comparison.js.map +1 -0
  112. package/dist/routes/eval-runs.d.ts +7 -1
  113. package/dist/routes/eval-runs.d.ts.map +1 -1
  114. package/dist/routes/eval-runs.js +42 -3
  115. package/dist/routes/eval-runs.js.map +1 -1
  116. package/dist/routes/eval-versions.d.ts +25 -0
  117. package/dist/routes/eval-versions.d.ts.map +1 -0
  118. package/dist/routes/eval-versions.js +66 -0
  119. package/dist/routes/eval-versions.js.map +1 -0
  120. package/dist/routes/flows.d.ts +13 -1
  121. package/dist/routes/flows.d.ts.map +1 -1
  122. package/dist/routes/flows.js +48 -3
  123. package/dist/routes/flows.js.map +1 -1
  124. package/dist/routes/guardrails.d.ts.map +1 -1
  125. package/dist/routes/guardrails.js +4 -0
  126. package/dist/routes/guardrails.js.map +1 -1
  127. package/dist/routes/hierarchy-errors.d.ts +45 -0
  128. package/dist/routes/hierarchy-errors.d.ts.map +1 -0
  129. package/dist/routes/hierarchy-errors.js +47 -0
  130. package/dist/routes/hierarchy-errors.js.map +1 -0
  131. package/dist/routes/judged-suites.d.ts +20 -0
  132. package/dist/routes/judged-suites.d.ts.map +1 -0
  133. package/dist/routes/judged-suites.js +272 -0
  134. package/dist/routes/judged-suites.js.map +1 -0
  135. package/dist/routes/judgment-context.d.ts +22 -0
  136. package/dist/routes/judgment-context.d.ts.map +1 -0
  137. package/dist/routes/judgment-context.js +88 -0
  138. package/dist/routes/judgment-context.js.map +1 -0
  139. package/dist/routes/judgment-flow-context.d.ts +32 -0
  140. package/dist/routes/judgment-flow-context.d.ts.map +1 -0
  141. package/dist/routes/judgment-flow-context.js +195 -0
  142. package/dist/routes/judgment-flow-context.js.map +1 -0
  143. package/dist/routes/judgments.d.ts +41 -0
  144. package/dist/routes/judgments.d.ts.map +1 -0
  145. package/dist/routes/judgments.js +566 -0
  146. package/dist/routes/judgments.js.map +1 -0
  147. package/dist/routes/orgs.d.ts +5 -2
  148. package/dist/routes/orgs.d.ts.map +1 -1
  149. package/dist/routes/orgs.js +38 -22
  150. package/dist/routes/orgs.js.map +1 -1
  151. package/dist/routes/policies.d.ts.map +1 -1
  152. package/dist/routes/policies.js +12 -1
  153. package/dist/routes/policies.js.map +1 -1
  154. package/dist/routes/projects.d.ts +10 -2
  155. package/dist/routes/projects.d.ts.map +1 -1
  156. package/dist/routes/projects.js +94 -80
  157. package/dist/routes/projects.js.map +1 -1
  158. package/dist/routes/providers.d.ts.map +1 -1
  159. package/dist/routes/providers.js +6 -1
  160. package/dist/routes/providers.js.map +1 -1
  161. package/dist/routes/runs.js +25 -3
  162. package/dist/routes/runs.js.map +1 -1
  163. package/dist/routes/teams.d.ts +6 -2
  164. package/dist/routes/teams.d.ts.map +1 -1
  165. package/dist/routes/teams.js +83 -73
  166. package/dist/routes/teams.js.map +1 -1
  167. package/dist/routes/tools.d.ts.map +1 -1
  168. package/dist/routes/tools.js +4 -0
  169. package/dist/routes/tools.js.map +1 -1
  170. package/dist/tool-binding.d.ts +8 -0
  171. package/dist/tool-binding.d.ts.map +1 -1
  172. package/openapi.json +14253 -10099
  173. package/package.json +21 -21
  174. package/src/agent-binding.ts +28 -4
  175. package/src/agent-pins.ts +147 -0
  176. package/src/app.ts +81 -3
  177. package/src/block-binding.ts +137 -0
  178. package/src/block-pins.ts +148 -0
  179. package/src/cost-binding.ts +21 -1
  180. package/src/deploy-versions.ts +157 -0
  181. package/src/deployment-binding.ts +27 -3
  182. package/src/derive-agent-version.ts +217 -0
  183. package/src/errors.ts +18 -0
  184. package/src/eval-case-binding.ts +71 -0
  185. package/src/eval-run-binding.ts +40 -0
  186. package/src/eval-run-dispatcher.ts +60 -16
  187. package/src/eval-suite-binding.ts +2 -0
  188. package/src/flow-binding.ts +20 -4
  189. package/src/flow-pins.ts +113 -0
  190. package/src/guardrail-binding.ts +9 -0
  191. package/src/handler-binding.ts +3 -0
  192. package/src/index.ts +86 -2
  193. package/src/judged-dispatcher.ts +530 -0
  194. package/src/judged-items.ts +263 -0
  195. package/src/judgment-binding.ts +349 -0
  196. package/src/openapi/generate.ts +7 -1
  197. package/src/openapi/operations.ts +579 -13
  198. package/src/openapi/schemas.ts +1408 -128
  199. package/src/provider-binding.ts +12 -7
  200. package/src/registry-read-only.ts +43 -0
  201. package/src/routes/agents.ts +252 -19
  202. package/src/routes/blocks.ts +387 -0
  203. package/src/routes/cost.ts +55 -1
  204. package/src/routes/deployments.ts +291 -56
  205. package/src/routes/eval-comparison.ts +135 -0
  206. package/src/routes/eval-runs.ts +57 -3
  207. package/src/routes/eval-versions.ts +110 -0
  208. package/src/routes/flows.ts +70 -5
  209. package/src/routes/guardrails.ts +7 -0
  210. package/src/routes/hierarchy-errors.ts +60 -0
  211. package/src/routes/judged-suites.ts +363 -0
  212. package/src/routes/judgment-context.ts +128 -0
  213. package/src/routes/judgment-flow-context.ts +245 -0
  214. package/src/routes/judgments.ts +743 -0
  215. package/src/routes/orgs.ts +44 -27
  216. package/src/routes/policies.ts +19 -0
  217. package/src/routes/projects.ts +118 -96
  218. package/src/routes/providers.ts +5 -0
  219. package/src/routes/runs.ts +29 -3
  220. package/src/routes/teams.ts +104 -90
  221. package/src/routes/tools.ts +7 -0
  222. package/src/tool-binding.ts +9 -0
@@ -0,0 +1,148 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+
4
+ import { type Agent, MODEL_SETTINGS_SCHEMA, settingsSchemaIssues } from '@kindgi/agents';
5
+ import { pickVersion } from '@kindgi/tools';
6
+ import type { Cursor, TenantId } from '@kindgi/types';
7
+
8
+ import type { UnpinnableRef } from './agent-pins.js';
9
+ import type { BlockRegistryBinding } from './block-binding.js';
10
+
11
+ /** The data-block versions an agent version pins, and the references that matched none. */
12
+ export interface BlockPins {
13
+ readonly prompts: Readonly<Record<string, string>>;
14
+ readonly settings: Readonly<Record<string, string>>;
15
+ readonly issues: readonly UnpinnableRef[];
16
+ }
17
+
18
+ interface Ref {
19
+ readonly path: string;
20
+ readonly id: string;
21
+ readonly range: string;
22
+ readonly role: 'prompt' | 'settings' | 'model-settings';
23
+ }
24
+
25
+ /** Page size for reading a block's versions. */
26
+ const VERSIONS_PAGE = 200;
27
+
28
+ /**
29
+ * Pin the data blocks an agent references (its prompt block, settings
30
+ * blocks and model-settings block) when a version of it is published:
31
+ * each range resolves by `pickVersion` over the block's active versions,
32
+ * as a turn of an unpinned agent would. A reference that matches no
33
+ * published version, names a block of the other kind, or names model
34
+ * settings that aren't (`MODEL_SETTINGS_SCHEMA`) is an issue: the
35
+ * caller refuses the publish. So is any reference on a runtime with no
36
+ * block registry.
37
+ */
38
+ export async function resolveBlockPins(
39
+ blocks: BlockRegistryBinding | undefined,
40
+ tenantId: TenantId,
41
+ agent: Agent,
42
+ ): Promise<BlockPins> {
43
+ const prompts: Record<string, string> = {};
44
+ const settings: Record<string, string> = {};
45
+ const issues: UnpinnableRef[] = [];
46
+ for (const ref of blockRefs(agent)) {
47
+ if (blocks === undefined) {
48
+ issues.push({
49
+ path: ref.path,
50
+ message: `${describe(ref)}: this runtime serves no data blocks`,
51
+ });
52
+ continue;
53
+ }
54
+ const available = await activeBlockVersions(blocks, tenantId, ref.id);
55
+ const pick = pickVersion(available, ref.range);
56
+ if (pick.kind !== 'ok') {
57
+ issues.push({
58
+ path: ref.path,
59
+ message:
60
+ available.length === 0
61
+ ? `${describe(ref)} has no published version; publish the block first`
62
+ : `${describe(ref)} has no published version in "${ref.range}" (published: ${available.join(', ')})`,
63
+ });
64
+ continue;
65
+ }
66
+ const block = await blocks.getVersion({ tenantId, blockId: ref.id, version: pick.version });
67
+ const problem =
68
+ block === null
69
+ ? `${describe(ref)} version ${pick.version} can't be read`
70
+ : misfit(ref, block);
71
+ if (problem !== undefined) {
72
+ issues.push({ path: ref.path, message: problem });
73
+ continue;
74
+ }
75
+ (ref.role === 'prompt' ? prompts : settings)[ref.id] = pick.version;
76
+ }
77
+ return { prompts, settings, issues };
78
+ }
79
+
80
+ function blockRefs(agent: Agent): Ref[] {
81
+ const refs: Ref[] = [];
82
+ if (typeof agent.instructions === 'object') {
83
+ refs.push({
84
+ path: '/instructions/version',
85
+ id: agent.instructions.prompt,
86
+ range: agent.instructions.version,
87
+ role: 'prompt',
88
+ });
89
+ }
90
+ for (const [i, s] of (agent.settings ?? []).entries()) {
91
+ refs.push({ path: `/settings/${i}/version`, id: s.id, range: s.version, role: 'settings' });
92
+ }
93
+ if (agent.modelSettings !== undefined) {
94
+ refs.push({
95
+ path: '/modelSettings/version',
96
+ id: agent.modelSettings.id,
97
+ range: agent.modelSettings.version,
98
+ role: 'model-settings',
99
+ });
100
+ }
101
+ return refs;
102
+ }
103
+
104
+ /** Why a block version can't serve its reference; undefined when it can. */
105
+ function misfit(
106
+ ref: Ref,
107
+ block: { readonly kind: string; readonly version: string; readonly content: unknown },
108
+ ): string | undefined {
109
+ const wanted = ref.role === 'prompt' ? 'prompt' : 'settings';
110
+ if (block.kind !== wanted) return `${describe(ref)} is a ${block.kind} block`;
111
+ if (ref.role !== 'model-settings') return undefined;
112
+ const values = (block.content as { readonly values?: unknown }).values;
113
+ const issues = settingsSchemaIssues(values, MODEL_SETTINGS_SCHEMA);
114
+ return issues.length === 0
115
+ ? undefined
116
+ : `${describe(ref)} version ${block.version} isn't model settings: ${issues.map((i) => `${i.path} ${i.message}`).join('; ')}`;
117
+ }
118
+
119
+ function describe(ref: Ref): string {
120
+ const what =
121
+ ref.role === 'prompt'
122
+ ? 'prompt'
123
+ : ref.role === 'model-settings'
124
+ ? 'model-settings'
125
+ : 'settings';
126
+ return `${what} block "${ref.id}"`;
127
+ }
128
+
129
+ /** Every active version of a block, newest published first. */
130
+ async function activeBlockVersions(
131
+ blocks: BlockRegistryBinding,
132
+ tenantId: TenantId,
133
+ blockId: string,
134
+ ): Promise<readonly string[]> {
135
+ const versions: string[] = [];
136
+ let cursor: Cursor | undefined;
137
+ do {
138
+ const page = await blocks.listVersions({
139
+ tenantId,
140
+ blockId,
141
+ limit: VERSIONS_PAGE,
142
+ ...(cursor !== undefined && { cursor }),
143
+ });
144
+ versions.push(...page.data.map((b) => b.version));
145
+ cursor = page.nextCursor;
146
+ } while (cursor !== undefined);
147
+ return versions;
148
+ }
@@ -44,7 +44,10 @@ export interface CostBinding {
44
44
  * Multi-dimensional aggregate rollup. `groupBy` may combine any
45
45
  * subset of `COST_GROUP_DIMENSIONS`; the binding returns one group per
46
46
  * distinct key tuple within the required `from`..`to` window, with its
47
- * cost and token sums.
47
+ * cost and token sums. With `limit`, a binding may return only the
48
+ * `limit` most expensive groups (`totalUsd` descending, ties by key)
49
+ * and the count before the cap in `totalGroups`; one that returns
50
+ * every group is capped by the route.
48
51
  */
49
52
  aggregate(input: CostAggregateInput): Promise<CostAggregateResult>;
50
53
  }
@@ -195,8 +198,20 @@ export interface CostAggregateInput {
195
198
  * shape uniformity.
196
199
  */
197
200
  readonly inherit?: boolean;
201
+ /**
202
+ * The most groups the caller wants (`?limit=`, 1..`COST_AGGREGATE_MAX_LIMIT`,
203
+ * default `COST_AGGREGATE_DEFAULT_LIMIT`): the most expensive ones. A
204
+ * binding may cap in its query; the window's totals stay over every
205
+ * record either way.
206
+ */
207
+ readonly limit?: number;
198
208
  }
199
209
 
210
+ /** `GET /v1/cost/aggregate`'s `?limit=` when absent. */
211
+ export const COST_AGGREGATE_DEFAULT_LIMIT = 1000;
212
+ /** The largest `?limit=` the aggregate takes. */
213
+ export const COST_AGGREGATE_MAX_LIMIT = 10_000;
214
+
200
215
  /**
201
216
  * One row of the aggregate result. `key` maps every requested `groupBy`
202
217
  * dimension to its value for this group — `null` when the underlying
@@ -226,6 +241,11 @@ export interface CostTokenTotals {
226
241
 
227
242
  export interface CostAggregateResult {
228
243
  readonly groups: readonly CostAggregateGroup[];
244
+ /**
245
+ * How many groups there were before a cap: set by a binding that caps
246
+ * (`CostAggregateInput.limit`). Absent: `groups` is every group.
247
+ */
248
+ readonly totalGroups?: number;
229
249
  readonly totalUsd: number;
230
250
  readonly totalRecords: number;
231
251
  readonly tokens: CostTokenTotals;
@@ -0,0 +1,157 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+
4
+ import { type PinChange, type PinSet, pinChanges } from '@kindgi/agents';
5
+ import { canonicalize } from '@kindgi/schema';
6
+ import { nextVersion } from '@kindgi/tools';
7
+ import type { VersionDerivation, VersionDerivationReason } from '@kindgi/types';
8
+
9
+ /** A version a deploy registers with pins: an agent's or a flow's. */
10
+ export interface PinnedDefinition {
11
+ readonly version: string;
12
+ readonly pins?: PinSet;
13
+ readonly pinsDigest?: string;
14
+ readonly derivedFrom?: VersionDerivation;
15
+ }
16
+
17
+ /**
18
+ * How a deploy registered one of its agents or flows, given its pins.
19
+ * A deploy never keeps a version's old pins and never refuses a
20
+ * routine deploy:
21
+ *
22
+ * - `registered`: the definition's version was free, and is now
23
+ * registered with these pins;
24
+ * - `unchanged`: it's registered with the same definition and pins (or
25
+ * its project is gone, which a deploy has always left as it is);
26
+ * - `reused`: an earlier deploy already registered this definition and
27
+ * these pins under another number (`version`), so a redeploy changes
28
+ * nothing;
29
+ * - `renumbered`: the definition's version is registered with other
30
+ * pins or other content, and versions never change, so this deploy
31
+ * registered the next free version in its line (`nextVersion`).
32
+ */
33
+ export type DeployedVersionOutcome =
34
+ | { readonly kind: 'registered' | 'unchanged'; readonly version: string }
35
+ | {
36
+ readonly kind: 'reused' | 'renumbered';
37
+ readonly version: string;
38
+ readonly reason: VersionDerivationReason;
39
+ readonly pinChanges?: readonly PinChange[];
40
+ };
41
+
42
+ /** What registering one version did: stored it, found the number taken, or left it (no project). */
43
+ export type PublishOutcome = 'ok' | 'taken' | 'skipped';
44
+
45
+ export interface DeployVersionInput<T extends PinnedDefinition> {
46
+ /** Names the definition in an error, e.g. `agent "acme.matcher"`. */
47
+ readonly label: string;
48
+ /** The definition as the pack has it, with no pins. */
49
+ readonly definition: T;
50
+ readonly pins: PinSet;
51
+ readonly pinsDigest: string;
52
+ /** Every active version registered under the definition's id. */
53
+ readonly existing: readonly T[];
54
+ /** Register one version. */
55
+ readonly publish: (version: T) => Promise<PublishOutcome>;
56
+ }
57
+
58
+ /** How many versions after the definition's a deploy tries before it gives up. */
59
+ const MAX_RENUMBER = 100;
60
+
61
+ /**
62
+ * Register a deployed agent or flow with its pins (see
63
+ * `DeployedVersionOutcome`): one rule for both, so they can't drift
64
+ * apart. Each definition is registered at most once per deploy, and a
65
+ * new version derives from the definition's version only, never from a
66
+ * version the same deploy created, so a change cascading from a tool
67
+ * through an agent into a flow ends within the one deploy.
68
+ */
69
+ export async function deployVersion<T extends PinnedDefinition>(
70
+ input: DeployVersionInput<T>,
71
+ ): Promise<DeployedVersionOutcome> {
72
+ const { definition, pins, pinsDigest, existing } = input;
73
+ const authored = definition.version;
74
+ const key = definitionKey(definition);
75
+ const same = (v: T) => definitionKey(v) === key && v.pinsDigest === pinsDigest;
76
+
77
+ const atAuthored = existing.find((v) => v.version === authored);
78
+ if (atAuthored !== undefined && same(atAuthored)) return { kind: 'unchanged', version: authored };
79
+ if (atAuthored === undefined) {
80
+ const outcome = await input.publish({ ...definition, pins, pinsDigest });
81
+ if (outcome !== 'taken') {
82
+ return { kind: outcome === 'ok' ? 'registered' : 'unchanged', version: authored };
83
+ }
84
+ // Taken with no active version: an unregistered version holds the
85
+ // number. Register the next one.
86
+ }
87
+
88
+ const reason = derivationReason(atAuthored, key);
89
+ const changes =
90
+ reason === 'pins-changed' ? { pinChanges: pinChanges(atAuthored?.pins, pins) } : {};
91
+ const earlier = existing.find(same);
92
+ if (earlier !== undefined) {
93
+ return {
94
+ kind: 'reused',
95
+ version: earlier.version,
96
+ // An expert's edit reused by a deploy reports the deploy's own reason.
97
+ reason:
98
+ earlier.derivedFrom !== undefined && earlier.derivedFrom.reason !== 'edited'
99
+ ? earlier.derivedFrom.reason
100
+ : reason,
101
+ ...changes,
102
+ };
103
+ }
104
+ const taken = new Set(existing.map((v) => v.version));
105
+ const version = await registerNextFree(input, reason, taken);
106
+ return version === undefined
107
+ ? { kind: 'unchanged', version: authored }
108
+ : { kind: 'renumbered', version, reason, ...changes };
109
+ }
110
+
111
+ /** Why the definition's version can't be registered as it is. */
112
+ function derivationReason(
113
+ atAuthored: PinnedDefinition | undefined,
114
+ key: string,
115
+ ): VersionDerivationReason {
116
+ if (atAuthored === undefined || definitionKey(atAuthored) !== key) return 'version-taken';
117
+ return atAuthored.pins === undefined ? 'unpinned' : 'pins-changed';
118
+ }
119
+
120
+ /**
121
+ * Register the definition with its pins under the first free version
122
+ * after its own (`nextVersion`), recording where it came from.
123
+ * `undefined` when it was left as it is (its project is gone).
124
+ */
125
+ async function registerNextFree<T extends PinnedDefinition>(
126
+ input: DeployVersionInput<T>,
127
+ reason: VersionDerivationReason,
128
+ taken: ReadonlySet<string>,
129
+ ): Promise<string | undefined> {
130
+ const { definition, pins, pinsDigest } = input;
131
+ const authored = definition.version;
132
+ let candidate = nextVersion(authored);
133
+ for (let tries = 0; candidate !== undefined && tries < MAX_RENUMBER; tries++) {
134
+ if (!taken.has(candidate)) {
135
+ const outcome = await input.publish({
136
+ ...definition,
137
+ version: candidate,
138
+ pins,
139
+ pinsDigest,
140
+ derivedFrom: { version: authored, reason },
141
+ });
142
+ if (outcome === 'ok') return candidate;
143
+ if (outcome === 'skipped') return undefined;
144
+ // Taken: an unregistered version holds this one too.
145
+ }
146
+ candidate = nextVersion(candidate);
147
+ }
148
+ throw new Error(
149
+ `${input.label}: no free version after ${authored} to register its new pins under`,
150
+ );
151
+ }
152
+
153
+ /** A definition: everything but its version and what the runtime sets. */
154
+ export function definitionKey(definition: PinnedDefinition): string {
155
+ const { version: _v, pins: _p, pinsDigest: _d, derivedFrom: _f, ...rest } = definition;
156
+ return canonicalize(rest);
157
+ }
@@ -1,7 +1,8 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // Copyright (C) 2026 Kindgi Inc.
3
3
 
4
- import type { Cursor, SigningKeyId, TenantId } from '@kindgi/types';
4
+ import type { PinChange } from '@kindgi/agents';
5
+ import type { Cursor, SigningKeyId, TenantId, VersionDerivationReason } from '@kindgi/types';
5
6
 
6
7
  /**
7
8
  * Caller-plugged surface for the deployment ledger — the audit anchor
@@ -127,11 +128,34 @@ export interface DeployedPrimitive {
127
128
  readonly version?: string;
128
129
  }
129
130
 
131
+ /**
132
+ * An agent or flow a deployment shipped, under the version it's
133
+ * registered as. A deploy registers one under another version than its
134
+ * definition's when that version is registered already with other pins
135
+ * or content (versions never change); then `authoredVersion` is the
136
+ * definition's and `reason` says why.
137
+ */
138
+ export interface DeployedVersion extends DeployedPrimitive {
139
+ /** The version the agent's definition names, when it differs from `version`. */
140
+ readonly authoredVersion?: string;
141
+ readonly reason?: VersionDerivationReason;
142
+ /** `true`: this deploy registered `version`; `false`: an earlier deploy did. */
143
+ readonly newVersion?: boolean;
144
+ /** For `pins-changed`: the pins that differ from `authoredVersion`'s. */
145
+ readonly pinChanges?: readonly PinChange[];
146
+ }
147
+
148
+ /** An agent a deployment shipped (`DeployedVersion`). */
149
+ export type DeployedAgent = DeployedVersion;
150
+
151
+ /** A flow a deployment shipped (`DeployedVersion`). */
152
+ export type DeployedFlow = DeployedVersion;
153
+
130
154
  export interface DeploymentContents {
131
155
  readonly tools: readonly DeployedPrimitive[];
132
156
  readonly guardrails: readonly DeployedPrimitive[];
133
- readonly agents: readonly DeployedPrimitive[];
134
- readonly flows: readonly DeployedPrimitive[];
157
+ readonly agents: readonly DeployedAgent[];
158
+ readonly flows: readonly DeployedFlow[];
135
159
  }
136
160
 
137
161
  export interface DeploymentPrimitiveCounts {
@@ -0,0 +1,217 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Copyright (C) 2026 Kindgi Inc.
3
+
4
+ import {
5
+ type Agent,
6
+ type AgentId,
7
+ type AgentPins,
8
+ MODEL_SETTINGS_SCHEMA,
9
+ pinsDigest,
10
+ settingsSchemaIssues,
11
+ } from '@kindgi/agents';
12
+ import type { TupleEnqueueHook } from '@kindgi/authz';
13
+ import { latestVersion, nextVersion } from '@kindgi/tools';
14
+ import type { ProjectId, Semver, TenantId } from '@kindgi/types';
15
+
16
+ import type { AgentRegistryBinding, AgentVersionRecord } from './agent-binding.js';
17
+ import { activeAgentVersions } from './agent-pins.js';
18
+ import type { BlockRegistryBinding } from './block-binding.js';
19
+ import { definitionKey } from './deploy-versions.js';
20
+
21
+ /** Which data-block pins to swap, by kind then block id → exact version. */
22
+ export interface PinSwaps {
23
+ readonly prompts?: Readonly<Record<string, string>>;
24
+ readonly settings?: Readonly<Record<string, string>>;
25
+ }
26
+
27
+ export interface DeriveAgentVersionInput {
28
+ readonly agents: AgentRegistryBinding;
29
+ readonly blocks: BlockRegistryBinding | undefined;
30
+ readonly tenantId: TenantId;
31
+ readonly agentId: AgentId;
32
+ /** The version to derive from: it must be pinned. */
33
+ readonly from: string;
34
+ readonly swaps: PinSwaps;
35
+ /** A short label for the new version. */
36
+ readonly label?: string;
37
+ /** Who derived it (`user:<id>`). */
38
+ readonly by?: string;
39
+ /** The project, when the store doesn't record one on the version. */
40
+ readonly projectId?: ProjectId;
41
+ /** The authorization tuples for the new version, in the project it lands in. */
42
+ readonly tuplesFor: (projectId: ProjectId) => TupleEnqueueHook;
43
+ }
44
+
45
+ export interface SwapIssue {
46
+ readonly path: string;
47
+ readonly message: string;
48
+ }
49
+
50
+ export type DeriveAgentVersionOutcome =
51
+ | { readonly kind: 'ok'; readonly agent: Agent }
52
+ /** An active version already has this definition and these pins: that one, unchanged. */
53
+ | { readonly kind: 'reused'; readonly agent: Agent }
54
+ | { readonly kind: 'not-found' }
55
+ | { readonly kind: 'unpinned' }
56
+ | { readonly kind: 'invalid'; readonly issues: readonly SwapIssue[] }
57
+ | { readonly kind: 'no-project' }
58
+ | { readonly kind: 'project-not-found'; readonly projectId: ProjectId };
59
+
60
+ /** How many numbers after the highest a derive tries before it gives up. */
61
+ const MAX_TRIES = 100;
62
+
63
+ /**
64
+ * Derive a new agent version from a pinned one with some data-block
65
+ * pins swapped: an expert's edit (a new prompt or settings version)
66
+ * reaching an agent without a code change. The new version is the old
67
+ * one's bag with those pins swapped (`derivedFrom: { version, reason:
68
+ * 'edited', label, by }`), numbered the next free patch after the
69
+ * agent's highest version (versions never change). If an active version
70
+ * already holds that definition and those pins (the same swap derived
71
+ * before, or a deploy that registered it), that version is returned
72
+ * unchanged (`reused`) rather than a duplicate.
73
+ *
74
+ * Only data-block pins swap: a swap must name a block the version
75
+ * already references (adding one is a code change), at a published,
76
+ * active version of the right kind (and, for the model-settings block,
77
+ * model settings). Tool pins come from code.
78
+ */
79
+ export async function deriveAgentVersion(
80
+ input: DeriveAgentVersionInput,
81
+ ): Promise<DeriveAgentVersionOutcome> {
82
+ const { agents, tenantId, agentId } = input;
83
+ const from = await agents.getVersion({ tenantId, agentId, version: input.from as Semver });
84
+ if (from === null) return { kind: 'not-found' };
85
+ if (from.pins === undefined) return { kind: 'unpinned' };
86
+
87
+ const issues = await swapIssues(input, from, from.pins);
88
+ if (issues.length > 0) return { kind: 'invalid', issues };
89
+ const pins: AgentPins = {
90
+ tools: from.pins.tools,
91
+ prompts: { ...from.pins.prompts, ...(input.swaps.prompts ?? {}) },
92
+ settings: { ...from.pins.settings, ...(input.swaps.settings ?? {}) },
93
+ };
94
+ const digest = pinsDigest(pins);
95
+ if (digest === from.pinsDigest) {
96
+ return { kind: 'invalid', issues: [{ path: '/pins', message: 'no pin changes' }] };
97
+ }
98
+
99
+ const projectId = from.projectId ?? input.projectId;
100
+ if (projectId === undefined) return { kind: 'no-project' };
101
+ const { unregisteredAt: _u, projectId: _p, derivedFrom: _d, ...definition } = from;
102
+ return publishNextFree(input, projectId, {
103
+ ...definition,
104
+ pins,
105
+ pinsDigest: digest,
106
+ derivedFrom: {
107
+ version: from.version,
108
+ reason: 'edited',
109
+ ...(input.label !== undefined && { label: input.label }),
110
+ ...(input.by !== undefined && { by: input.by }),
111
+ },
112
+ });
113
+ }
114
+
115
+ /** Publish the derived version under the first free patch after the agent's highest. */
116
+ async function publishNextFree(
117
+ input: DeriveAgentVersionInput,
118
+ projectId: ProjectId,
119
+ derived: Agent,
120
+ ): Promise<DeriveAgentVersionOutcome> {
121
+ const { agents, tenantId, agentId } = input;
122
+ const active = await activeAgentVersions(agents, tenantId, agentId);
123
+ // The same swap again (or a deploy that registered it) finds the
124
+ // version that already holds it: versions are never duplicated.
125
+ const key = definitionKey(derived);
126
+ const same = active.find((a) => a.pinsDigest === derived.pinsDigest && definitionKey(a) === key);
127
+ if (same !== undefined) return { kind: 'reused', agent: same };
128
+ const highest =
129
+ latestVersion(active.map((a) => a.version as unknown as string)) ??
130
+ (derived.version as unknown as string);
131
+ let candidate = nextVersion(highest);
132
+ for (let tries = 0; candidate !== undefined && tries < MAX_TRIES; tries++) {
133
+ const agent: Agent = { ...derived, version: candidate as Semver };
134
+ const outcome = await agents.publish({
135
+ tenantId,
136
+ projectId,
137
+ agent,
138
+ enqueueTuples: input.tuplesFor(projectId),
139
+ });
140
+ if (outcome.kind === 'ok') return { kind: 'ok', agent };
141
+ if (outcome.kind === 'project-not-found') return { kind: 'project-not-found', projectId };
142
+ candidate = nextVersion(candidate);
143
+ }
144
+ throw new Error(`agent "${agentId as unknown as string}": no free version after ${highest}`);
145
+ }
146
+
147
+ /** What's wrong with the swaps, against the version's references and the block store. */
148
+ async function swapIssues(
149
+ input: DeriveAgentVersionInput,
150
+ from: AgentVersionRecord,
151
+ pins: AgentPins,
152
+ ): Promise<SwapIssue[]> {
153
+ const issues: SwapIssue[] = [];
154
+ const swaps = [
155
+ ...Object.entries(input.swaps.prompts ?? {}).map(([id, v]) => ['prompts', id, v] as const),
156
+ ...Object.entries(input.swaps.settings ?? {}).map(([id, v]) => ['settings', id, v] as const),
157
+ ];
158
+ if (swaps.length === 0)
159
+ return [{ path: '/pins', message: 'name at least one prompt or settings pin to swap' }];
160
+ for (const [kind, id, version] of swaps) {
161
+ const path = `/pins/${kind}/${id}`;
162
+ if (pins[kind][id] === undefined) {
163
+ issues.push({
164
+ path,
165
+ message: `agent version ${from.version} doesn't reference ${kind === 'prompts' ? 'prompt' : 'settings'} block "${id}"; adding a block is a code change`,
166
+ });
167
+ continue;
168
+ }
169
+ const problem = await blockProblem(input, from, kind, id, version);
170
+ if (problem !== undefined) issues.push({ path, message: problem });
171
+ }
172
+ return issues;
173
+ }
174
+
175
+ async function blockProblem(
176
+ input: DeriveAgentVersionInput,
177
+ from: AgentVersionRecord,
178
+ kind: 'prompts' | 'settings',
179
+ id: string,
180
+ version: string,
181
+ ): Promise<string | undefined> {
182
+ if (input.blocks === undefined) return 'this runtime serves no data blocks';
183
+ const block = await input.blocks.getVersion({ tenantId: input.tenantId, blockId: id, version });
184
+ const what = `block "${id}" version ${version}`;
185
+ if (block === null) return `${what} isn't published`;
186
+ if (block.unregisteredAt !== undefined) return `${what} is unregistered`;
187
+ const wanted = kind === 'prompts' ? 'prompt' : 'settings';
188
+ if (block.kind !== wanted) return `${what} is a ${block.kind} block, not ${wanted}`;
189
+ if (block.kind === 'settings' && from.modelSettings?.id === id) {
190
+ const issues = settingsSchemaIssues(block.content.values, MODEL_SETTINGS_SCHEMA);
191
+ if (issues.length > 0) {
192
+ return `${what} isn't model settings: ${issues.map((i) => `${i.path} ${i.message}`).join('; ')}`;
193
+ }
194
+ }
195
+ return undefined;
196
+ }
197
+
198
+ /**
199
+ * The first version after `after` that no version of the agent holds,
200
+ * active or unregistered (versions never change): what a refused
201
+ * publish of a taken number suggests, by the deploy rule's numbering.
202
+ * `undefined` when none is free within the tries.
203
+ */
204
+ export async function nextFreeAgentVersion(
205
+ agents: AgentRegistryBinding,
206
+ tenantId: TenantId,
207
+ agentId: AgentId,
208
+ after: string,
209
+ ): Promise<string | undefined> {
210
+ let candidate = nextVersion(after);
211
+ for (let tries = 0; candidate !== undefined && tries < MAX_TRIES; tries++) {
212
+ const held = await agents.getVersion({ tenantId, agentId, version: candidate as Semver });
213
+ if (held === null) return candidate;
214
+ candidate = nextVersion(candidate);
215
+ }
216
+ return undefined;
217
+ }
package/src/errors.ts CHANGED
@@ -31,6 +31,7 @@ export interface WireError {
31
31
  export const ERROR_CODE_TO_STATUS: Readonly<Record<string, number>> = {
32
32
  // 400 — bad request
33
33
  'validation-failed': 400,
34
+ 'kind-not-applied': 400,
34
35
  'unknown-field': 400,
35
36
  'bad-input': 400,
36
37
  'unresolved-tool': 400,
@@ -66,6 +67,7 @@ export const ERROR_CODE_TO_STATUS: Readonly<Record<string, number>> = {
66
67
  'duplicate-edge-id': 409,
67
68
  'agent-version-mismatch': 409,
68
69
  'agent-already-registered': 409,
70
+ 'registry-read-only': 409,
69
71
  'agent-gone': 410,
70
72
  'flow-gone': 410,
71
73
  'policy-gone': 410,
@@ -160,10 +162,22 @@ export const ERROR_CODE_TO_STATUS: Readonly<Record<string, number>> = {
160
162
  'policy-not-found': 404,
161
163
  'policy-already-registered': 409,
162
164
  // Admin plane — eval suites.
165
+ 'block-not-found': 404,
166
+ 'block-already-registered': 409,
167
+ 'block-project-mismatch': 409,
163
168
  'eval-suite-not-found': 404,
164
169
  'eval-suite-already-registered': 409,
165
170
  // Admin plane — eval-run dispatch.
166
171
  'eval-run-not-found': 404,
172
+ // Judgments (yes/no on a run's output items) and judge classes.
173
+ 'judgment-not-found': 404,
174
+ 'judge-class-not-found': 404,
175
+ 'judge-class-name-taken': 409,
176
+ 'judge-class-not-applicable': 400,
177
+ 'run-not-finished': 409,
178
+ 'item-not-found': 400,
179
+ // The judgment binding can't list judged runs, so no test sets from judgments.
180
+ 'test-sets-not-supported': 501,
167
181
  'eval-run-already-terminal': 409,
168
182
  'dispatcher-not-registered': 422,
169
183
  'dispatcher-input-invalid': 400,
@@ -215,6 +229,10 @@ export const ERROR_CODE_TO_STATUS: Readonly<Record<string, number>> = {
215
229
  'project-not-found': 404,
216
230
  'team-membership-not-found': 404,
217
231
  'project-membership-not-found': 404,
232
+ // A slug another org, team or project in the tenant already has; a
233
+ // second Default project.
234
+ 'slug-conflict': 409,
235
+ 'project-default-already-exists': 409,
218
236
  'tenant-not-found': 404,
219
237
  'tenant-config-not-found': 404,
220
238
  'tenant-config-revision-conflict': 409,