@cavelon/cli 0.1.3 → 0.1.5

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 (43) hide show
  1. package/README.md +43 -17
  2. package/dist/agent-env.js +24 -0
  3. package/dist/choose.js +8 -4
  4. package/dist/code-hints.js +74 -0
  5. package/dist/commands/api.js +174 -33
  6. package/dist/commands/async.js +26 -5
  7. package/dist/commands/docs.js +183 -37
  8. package/dist/commands/fmt.js +117 -0
  9. package/dist/commands/index.js +6 -1
  10. package/dist/commands/init.js +28 -6
  11. package/dist/commands/inventory.js +27 -5
  12. package/dist/commands/models.js +7 -1
  13. package/dist/commands/schema.js +193 -0
  14. package/dist/commands/session.js +69 -13
  15. package/dist/commands/solution.js +275 -36
  16. package/dist/commands/tenants.js +125 -15
  17. package/dist/commands/work.js +245 -24
  18. package/dist/contracts.js +3 -0
  19. package/dist/default-route.js +21 -0
  20. package/dist/errors.js +4 -0
  21. package/dist/git.js +14 -5
  22. package/dist/http.js +27 -4
  23. package/dist/invoke.js +8 -4
  24. package/dist/kit-codes.js +85 -0
  25. package/dist/limits.js +12 -1
  26. package/dist/local-state.js +9 -2
  27. package/dist/main.js +16 -3
  28. package/dist/mcp.js +19 -8
  29. package/dist/openapi.js +91 -21
  30. package/dist/operations.js +4 -3
  31. package/dist/package-check.js +193 -4
  32. package/dist/package-files.js +21 -10
  33. package/dist/package-format.js +149 -0
  34. package/dist/package-references.js +231 -0
  35. package/dist/paths.js +4 -3
  36. package/dist/preview-report.js +152 -0
  37. package/dist/results.js +65 -5
  38. package/dist/skills/cavelon-authoring/SKILL.md +67 -8
  39. package/dist/skills/cavelon-long-running/SKILL.md +3 -1
  40. package/dist/skills/cavelon-loop/SKILL.md +75 -13
  41. package/dist/skills/cavelon-testing/SKILL.md +85 -4
  42. package/dist/tenant-choice.js +12 -5
  43. package/package.json +3 -3
@@ -61,7 +61,8 @@ export async function getOperation(client, id, signal) {
61
61
  }
62
62
  }
63
63
  export async function waitFor(ctx, client, ids, options) {
64
- const deadline = Date.now() + options.timeoutMs;
64
+ const started = Date.now();
65
+ const deadline = started + options.timeoutMs;
65
66
  const latest = new Map();
66
67
  let interval = options.intervalMs;
67
68
  for (;;) {
@@ -77,10 +78,10 @@ export async function waitFor(ctx, client, ids, options) {
77
78
  }
78
79
  const ops = ids.map((id) => latest.get(id));
79
80
  if (ops.every(isSettled))
80
- return { operations: ops, timedOut: false };
81
+ return { operations: ops, timedOut: false, waitedMs: Date.now() - started };
81
82
  const left = deadline - Date.now();
82
83
  if (left <= 0)
83
- return { operations: ops, timedOut: true };
84
+ return { operations: ops, timedOut: options.timeoutMs > 0, waitedMs: Date.now() - started };
84
85
  await ctx.io.sleep(Math.min(interval, left));
85
86
  interval = Math.min(Math.round(interval * 1.5), 5000);
86
87
  }
@@ -1,6 +1,9 @@
1
1
  import { Ajv2020 } from "ajv/dist/2020.js";
2
2
  import { BRANCH_WIDTH_KEY, branchConcurrency, offText } from "./branches.js";
3
3
  import { locate, schemaSections } from "./package-files.js";
4
+ import { PERSONA_SECTION, sectionFields } from "./package-format.js";
5
+ import { kitErrorEntry } from "./kit-codes.js";
6
+ import { checkModels, checkReferences, checkUnknownFields, DUPLICATE_CODE, FIELD_UNKNOWN_CODE, MODEL_UNKNOWN_CODE, REFERENCE_MISSING_CODE, REFERENCE_UNKNOWN_CODE, SEARCH_TOOL_KEYS, } from "./package-references.js";
4
7
  export const SCHEMA_CODE = "package_schema_invalid";
5
8
  const ENDPOINT_LIMIT_CODE = "model_endpoint_limit_without_base_url";
6
9
  const ENDPOINT_LIMIT_NOT_CARRIED = "model_endpoint_limit_not_in_package_schema";
@@ -13,7 +16,14 @@ const BRANCH_DOCS = "/docs/concepts/capacity-and-concurrency#branch-concurrency"
13
16
  const KB_WITHOUT_SEARCH_CODE = "knowledge_base_without_search_tool";
14
17
  const SEARCH_DOCS = "/docs/reference/builtin-tools#binding-knowledge-bases-to-search_documents";
15
18
  const SEARCH_TOOL = "search_documents";
16
- const SEARCH_TOOL_KEYS = new Set([SEARCH_TOOL, "search_knowledge_base", "search_kb"]);
19
+ const PERSONA_MESSAGE_CODE = "persona_message_empty";
20
+ const PERSONA_DOCS = "/docs/concepts/personas";
21
+ const PERSONA_MESSAGES = [
22
+ { switch: "greeting_enabled", text: "greeting_message", what: "greeting", when: "when a conversation starts" },
23
+ { switch: "fallback_message_enabled", text: "fallback_message", what: "fallback message", when: "when the assistant has no answer" },
24
+ ];
25
+ const ASSERTION_UNCHECKED_CODE = "test_assertion_unchecked";
26
+ const TESTING_DOCS = "/docs/concepts/regression-testing";
17
27
  export const KIT_CODES = [
18
28
  {
19
29
  code: SCHEMA_CODE,
@@ -71,6 +81,57 @@ export const KIT_CODES = [
71
81
  hint: `A knowledge base reaches an agent only through a search tool: add \`- tool_slug: ${SEARCH_TOOL}\` to the tool_assignments of the skill that names the knowledge base, or of the agent. \`cavelon docs get reference/builtin-tools\` shows the binding.`,
72
82
  docs: SEARCH_DOCS,
73
83
  },
84
+ {
85
+ code: ASSERTION_UNCHECKED_CODE,
86
+ area: "package",
87
+ message: "A test step has assertions (criteria with a type), and this instance's package schema does not describe a step's criteria, so validate cannot check them.",
88
+ hint: "An instance that knows the type checks the assertion in code; one that does not grades it as a judge criterion. " +
89
+ "`cavelon docs get concepts/regression-testing` says which types this instance knows; a newer instance publishes them in its package schema.",
90
+ docs: TESTING_DOCS,
91
+ },
92
+ {
93
+ code: PERSONA_MESSAGE_CODE,
94
+ area: "package",
95
+ message: "The persona turns a greeting or a fallback message on, but its text is empty.",
96
+ hint: "Write the text in persona.yaml (greeting_message, fallback_message) in the language the assistant answers in, or set " +
97
+ "greeting_enabled / fallback_message_enabled to false. The persona says who the assistant is for every agent of the solution.",
98
+ docs: PERSONA_DOCS,
99
+ },
100
+ {
101
+ code: DUPLICATE_CODE,
102
+ area: "package",
103
+ message: "Two entries of one section have the same key (slug, or name for a knowledge base).",
104
+ hint: "Rename or remove one of them: the import keeps only one entry per key.",
105
+ docs: PACKAGE_DOCS,
106
+ },
107
+ {
108
+ code: REFERENCE_MISSING_CODE,
109
+ area: "package",
110
+ message: "An agent hands off to an agent that is not in the package.",
111
+ hint: "Fix the to_agent_slug (the finding suggests the closest slug), or add the agent to package/agents.yaml.",
112
+ docs: PACKAGE_DOCS,
113
+ },
114
+ {
115
+ code: REFERENCE_UNKNOWN_CODE,
116
+ area: "package",
117
+ message: "A skill, tool, knowledge base or solution is named that is neither in the package nor among what the tenant held at the last pull.",
118
+ hint: "Fix the name (the finding suggests the closest one), or add the entry to the package. If it was created on the instance since, `cavelon pull` refreshes the list in .cavelon/inventory.json.",
119
+ docs: PACKAGE_DOCS,
120
+ },
121
+ {
122
+ code: FIELD_UNKNOWN_CODE,
123
+ area: "package",
124
+ message: "A package file sets a field this instance's package schema does not have; the import ignores it.",
125
+ hint: "Check the field name for a typo (the finding suggests the closest field); a field from a newer instance is ignored by this one.",
126
+ docs: PACKAGE_DOCS,
127
+ },
128
+ {
129
+ code: MODEL_UNKNOWN_CODE,
130
+ area: "package",
131
+ message: "An agent's llm_model is not in the tenant's model list as the kit last read it.",
132
+ hint: "Fix the model id (the finding suggests the closest one), or register the model. `cavelon models list` shows the tenant's models and refreshes the list validate checks against.",
133
+ docs: PACKAGE_DOCS,
134
+ },
74
135
  {
75
136
  code: "package_file_duplicate",
76
137
  area: "package",
@@ -87,7 +148,10 @@ export function catalogEntry(catalog, code) {
87
148
  if (api)
88
149
  return { ...api, kind: "api" };
89
150
  const kit = KIT_CODES.find((e) => e.code === code);
90
- return kit ? { ...kit, kind: "kit" } : undefined;
151
+ if (kit)
152
+ return { ...kit, kind: "kit" };
153
+ const cli = kitErrorEntry(code);
154
+ return cli ? { ...cli, kind: "cli" } : undefined;
91
155
  }
92
156
  export function packageVersionOf(pkg) {
93
157
  const manifest = pkg.manifest;
@@ -98,11 +162,57 @@ export function packageVersionOf(pkg) {
98
162
  }
99
163
  function compile(schema) {
100
164
  const { $id: _id, $schema: _schema, ...body } = schema;
101
- const ajv = new Ajv2020({ strict: false, allErrors: true, validateSchema: false, validateFormats: false });
165
+ const ajv = new Ajv2020({ strict: false, allErrors: true, verbose: true, validateSchema: false, validateFormats: false });
102
166
  return ajv.compile(body);
103
167
  }
168
+ function closestBranchErrors(errors) {
169
+ const dropped = new Set();
170
+ const countedAt = new Map();
171
+ const pathOf = (e) => countedAt.get(e) ?? e.schemaPath;
172
+ const isChoice = (e) => e.keyword === "anyOf" || e.keyword === "oneOf";
173
+ errors.forEach((choice, index) => {
174
+ if (!isChoice(choice))
175
+ return;
176
+ const list = choice.schema;
177
+ if (!Array.isArray(list))
178
+ return;
179
+ const prefixes = list.map((branch, i) => {
180
+ const ref = branch && typeof branch === "object" ? branch.$ref : undefined;
181
+ return [`${choice.schemaPath}/${i}/`, ...(typeof ref === "string" && ref.startsWith("#/") ? [`${ref}/`] : [])];
182
+ });
183
+ const here = choice.instancePath;
184
+ const byBranch = new Map();
185
+ for (const error of errors.slice(0, index)) {
186
+ if (dropped.has(error) || isChoice(error))
187
+ continue;
188
+ if (error.instancePath !== here && !error.instancePath.startsWith(`${here}/`))
189
+ continue;
190
+ const branch = prefixes.findIndex((list) => list.some((prefix) => pathOf(error).startsWith(prefix)));
191
+ if (branch >= 0)
192
+ byBranch.set(branch, [...(byBranch.get(branch) ?? []), error]);
193
+ }
194
+ const distance = (list) => list.reduce((sum, e) => {
195
+ if (e.keyword === "type" && e.instancePath === here)
196
+ return sum + 1000;
197
+ const field = e.instancePath.startsWith(`${here}/`) && !e.instancePath.slice(here.length + 1).includes("/");
198
+ return sum + ((e.keyword === "const" || e.keyword === "enum") && field ? 100 : 1);
199
+ }, 0);
200
+ const ranked = [...byBranch.values()].map((list) => ({ list, distance: distance(list) })).sort((a, b) => a.distance - b.distance);
201
+ if (ranked.length < 2 || ranked[0].distance === ranked[1].distance)
202
+ return;
203
+ for (const other of ranked.slice(1))
204
+ for (const error of other.list)
205
+ dropped.add(error);
206
+ for (const error of ranked[0].list)
207
+ countedAt.set(error, pathOf(choice));
208
+ });
209
+ return errors.filter((e) => !dropped.has(e));
210
+ }
104
211
  function describe(error) {
105
212
  const params = error.params;
213
+ if (error.keyword === "additionalProperties") {
214
+ return { pointer: error.instancePath, message: `field "${String(params.additionalProperty)}" is not allowed here` };
215
+ }
106
216
  if (error.keyword === "required") {
107
217
  return { pointer: error.instancePath, message: `missing required field "${String(params.missingProperty)}"` };
108
218
  }
@@ -142,7 +252,7 @@ export function checkPackage(disk, options) {
142
252
  const validate = compile(options.schema);
143
253
  if (!validate(disk.package)) {
144
254
  const seen = new Set();
145
- for (const error of validate.errors ?? []) {
255
+ for (const error of closestBranchErrors(validate.errors ?? [])) {
146
256
  if (error.keyword === "anyOf" || error.keyword === "oneOf")
147
257
  continue;
148
258
  const { pointer, message } = describe(error);
@@ -156,6 +266,11 @@ export function checkPackage(disk, options) {
156
266
  findings.push(...checkEndpointLimits(disk, options.schema));
157
267
  findings.push(...checkBranchConcurrency(disk, options.limits));
158
268
  findings.push(...checkKnowledgeSearch(disk));
269
+ findings.push(...checkUnknownFields(disk, options.schema, findings));
270
+ findings.push(...checkReferences(disk, options.inventory));
271
+ findings.push(...checkModels(disk, options.inventory));
272
+ findings.push(...checkPersonaMessages(disk, options.schema));
273
+ findings.push(...checkUncheckedAssertions(disk, options.schema));
159
274
  for (const finding of findings) {
160
275
  const entry = catalogEntry(options.catalog, finding.code);
161
276
  if (!entry)
@@ -340,3 +455,77 @@ function checkKnowledgeSearch(disk) {
340
455
  });
341
456
  return findings;
342
457
  }
458
+ function schemaNode(schema, node) {
459
+ let at = asObject(node);
460
+ for (let hops = 0; at && typeof at.$ref === "string" && hops < 10; hops++) {
461
+ const ref = at.$ref;
462
+ at = ref.startsWith("#/$defs/") ? asObject(schema.$defs?.[ref.slice("#/$defs/".length)]) : undefined;
463
+ }
464
+ return at;
465
+ }
466
+ function listItems(schema, node) {
467
+ const at = schemaNode(schema, node);
468
+ if (!at)
469
+ return undefined;
470
+ const branches = Array.isArray(at.anyOf) ? at.anyOf.map((b) => schemaNode(schema, b)) : [at];
471
+ const arrays = branches.filter((b) => b?.type === "array");
472
+ return arrays.length === 1 && "items" in arrays[0] ? (asObject(arrays[0].items) ?? {}) : undefined;
473
+ }
474
+ function checkUncheckedAssertions(disk, schema) {
475
+ const field = (node, name) => (asObject(schemaNode(schema, node)?.properties) ?? {})[name];
476
+ const step = schemaNode(schema, listItems(schema, field(listItems(schema, field(listItems(schema, schema.properties?.test_suites), "test_cases")), "steps")));
477
+ const criteria = listItems(schema, field(step, "evaluation_criteria"));
478
+ const described = !criteria || Object.keys(criteria).some((k) => k !== "title" && k !== "description");
479
+ if (described)
480
+ return [];
481
+ const suites = Array.isArray(disk.package.test_suites) ? disk.package.test_suites : [];
482
+ const byFile = new Map();
483
+ suites.forEach((suite, s) => {
484
+ (Array.isArray(asObject(suite)?.test_cases) ? asObject(suite).test_cases : []).forEach((testCase, c) => {
485
+ (Array.isArray(asObject(testCase)?.steps) ? asObject(testCase).steps : []).forEach((step, t) => {
486
+ const list = asObject(step)?.evaluation_criteria;
487
+ (Array.isArray(list) ? list : []).forEach((criterion, i) => {
488
+ const type = asObject(criterion)?.type;
489
+ if (typeof type !== "string")
490
+ return;
491
+ const at = locate(disk, `/test_suites/${s}/test_cases/${c}/steps/${t}/evaluation_criteria/${i}`);
492
+ const key = at.file ?? "";
493
+ if (!byFile.has(key))
494
+ byFile.set(key, { at, types: new Set() });
495
+ byFile.get(key).types.add(type);
496
+ });
497
+ });
498
+ });
499
+ });
500
+ return [...byFile.values()].map(({ at, types }) => ({
501
+ code: ASSERTION_UNCHECKED_CODE,
502
+ severity: "warning",
503
+ ...at,
504
+ message: `This instance's package schema does not describe a step's criteria, so the assertions here (${[...types].join(", ")}) are not checked. ` +
505
+ "An instance that does not know a type grades it as a judge criterion instead of checking it in code.",
506
+ }));
507
+ }
508
+ function checkPersonaMessages(disk, schema) {
509
+ const persona = asObject(disk.package[PERSONA_SECTION]);
510
+ const fields = sectionFields(schema, PERSONA_SECTION);
511
+ if (!persona || !fields)
512
+ return [];
513
+ const findings = [];
514
+ for (const pair of PERSONA_MESSAGES) {
515
+ if (!fields[pair.switch] || !fields[pair.text])
516
+ continue;
517
+ const on = persona[pair.switch] ?? fields[pair.switch].default;
518
+ const text = persona[pair.text];
519
+ if (on !== true || (typeof text === "string" && text.trim()))
520
+ continue;
521
+ const at = locate(disk, `/${PERSONA_SECTION}/${pair.switch in persona ? pair.switch : pair.text}`);
522
+ findings.push({
523
+ code: PERSONA_MESSAGE_CODE,
524
+ severity: "warning",
525
+ ...at,
526
+ message: `${pair.switch} is ${pair.switch in persona ? "true" : "true by default"}, but ${pair.text} is empty: ` +
527
+ `the solution shows no ${pair.what} of its own ${pair.when}. Write ${pair.text}, or set ${pair.switch} to false.`,
528
+ });
529
+ }
530
+ return findings;
531
+ }
@@ -1,8 +1,10 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
- import { LineCounter, parseDocument, stringify } from "yaml";
3
+ import { LineCounter, parseDocument } from "yaml";
4
4
  import { CavelonError, ExitCode } from "./errors.js";
5
5
  import { readTextFile, withoutBom, writeFileAtomic } from "./fsutil.js";
6
+ import { PERSONA_SECTION, sameSectionValue, sectionContent, sectionFields, toYaml, withoutNulls } from "./package-format.js";
7
+ export { toYaml };
6
8
  export const DEFAULT_LAYOUT = { package: "package", items: {} };
7
9
  const PACKAGE_FILE = /\.(ya?ml|json)$/i;
8
10
  export function layoutFrom(raw) {
@@ -127,7 +129,6 @@ export async function readPackage(root, layout) {
127
129
  const dir = path.join(root, layout.package);
128
130
  let empty = true;
129
131
  for (const name of await listFiles(dir)) {
130
- empty = false;
131
132
  const section = name.replace(PACKAGE_FILE, "");
132
133
  const file = path.join(dir, name);
133
134
  if (section in sources) {
@@ -143,10 +144,14 @@ export async function readPackage(root, layout) {
143
144
  if ("finding" in read) {
144
145
  sources[section] = { file: rel(root, file) };
145
146
  findings.push(read.finding);
147
+ empty = false;
146
148
  continue;
147
149
  }
148
150
  const parsed = parseFile(root, file, read.text);
149
151
  sources[section] = parsed.source;
152
+ if (!parsed.finding && section === PERSONA_SECTION && (parsed.value === null || parsed.value === undefined))
153
+ continue;
154
+ empty = false;
150
155
  if (parsed.finding)
151
156
  findings.push(parsed.finding);
152
157
  else
@@ -242,9 +247,6 @@ export function canonical(value) {
242
247
  return v;
243
248
  });
244
249
  }
245
- export function toYaml(value) {
246
- return stringify(value, { lineWidth: 0, aliasDuplicateObjects: false });
247
- }
248
250
  async function readValue(root, file) {
249
251
  const target = await contentPath(root, file);
250
252
  const text = target === undefined ? undefined : await readTextFile(target);
@@ -259,6 +261,12 @@ async function readValue(root, file) {
259
261
  return { ok: false };
260
262
  }
261
263
  }
264
+ export async function placeholdersOnly(root, relative) {
265
+ if (path.posix.basename(relative).replace(PACKAGE_FILE, "") !== PERSONA_SECTION)
266
+ return false;
267
+ const old = await readValue(root, path.join(root, relative));
268
+ return old.ok && (old.value === null || old.value === undefined);
269
+ }
262
270
  function itemFileName(item, index, taken) {
263
271
  const record = item && typeof item === "object" && !Array.isArray(item) ? item : {};
264
272
  const label = [record.slug, record.name, record.key].find((v) => typeof v === "string" && v.trim() !== "");
@@ -285,7 +293,10 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
285
293
  const plans = [];
286
294
  const same = [];
287
295
  const removals = [];
288
- for (const [section, value] of Object.entries(pkg)) {
296
+ const sections = Object.entries(pkg);
297
+ if (!(PERSONA_SECTION in pkg) && sectionFields(schema, PERSONA_SECTION))
298
+ sections.push([PERSONA_SECTION, null]);
299
+ for (const [section, value] of sections) {
289
300
  if (section in layout.items && Array.isArray(value))
290
301
  continue;
291
302
  if (!safeSectionName(section)) {
@@ -295,10 +306,10 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
295
306
  const current = existing.get(section);
296
307
  const file = path.join(dir, current ?? `${section}.yaml`);
297
308
  const old = await readValue(root, file);
298
- if (old.ok && canonical(old.value) === canonical(value))
309
+ if (old.ok && sameSectionValue(section, old.value, value, canonical))
299
310
  same.push({ file, section });
300
311
  else
301
- plans.push({ file, section, content: /\.json$/i.test(file) ? JSON.stringify(value, null, 2) + "\n" : toYaml(value) });
312
+ plans.push({ file, section, content: sectionContent(section, value, schema, /\.json$/i.test(file)) });
302
313
  }
303
314
  for (const [section, folder] of Object.entries(layout.items)) {
304
315
  const value = pkg[section];
@@ -315,7 +326,7 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
315
326
  const unclaimed = new Map(before);
316
327
  const placed = value.map((item) => {
317
328
  for (const [name, old] of unclaimed) {
318
- if (canonical(old) === canonical(item)) {
329
+ if (canonical(withoutNulls(old)) === canonical(withoutNulls(item))) {
319
330
  unclaimed.delete(name);
320
331
  taken.add(name);
321
332
  return name;
@@ -338,7 +349,7 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
338
349
  await fs.mkdir(itemDir, { recursive: true });
339
350
  }
340
351
  for (const [section, name] of existing) {
341
- if (section in pkg)
352
+ if (section in pkg || section === PERSONA_SECTION)
342
353
  continue;
343
354
  const file = path.join(dir, name);
344
355
  if (known.has(section))
@@ -0,0 +1,149 @@
1
+ import { stringify } from "yaml";
2
+ export const PERSONA_SECTION = "persona";
3
+ export function toYaml(value) {
4
+ return stringify(value, { lineWidth: 0, aliasDuplicateObjects: false });
5
+ }
6
+ const isObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
7
+ function resolve(schema, node) {
8
+ let current = isObject(node) ? node : undefined;
9
+ for (let hops = 0; current && typeof current.$ref === "string" && hops < 10; hops++) {
10
+ const ref = current.$ref;
11
+ if (!ref.startsWith("#/$defs/"))
12
+ return undefined;
13
+ current = schema.$defs?.[ref.slice("#/$defs/".length)];
14
+ }
15
+ return current;
16
+ }
17
+ function branches(schema, node, depth = 0) {
18
+ const list = (Array.isArray(node.anyOf) ? node.anyOf : Array.isArray(node.oneOf) ? node.oneOf : undefined);
19
+ if (!list || depth > 10)
20
+ return [node];
21
+ return list.map((b) => resolve(schema, b)).flatMap((b) => (b ? branches(schema, b, depth + 1) : []));
22
+ }
23
+ const propertiesOf = (node) => (isObject(node?.properties) ? node.properties : undefined);
24
+ function allowed(schema, node, value) {
25
+ const field = resolve(schema, node);
26
+ if (!field)
27
+ return true;
28
+ if ("const" in field)
29
+ return field.const === value;
30
+ return Array.isArray(field.enum) ? field.enum.includes(value) : true;
31
+ }
32
+ function fits(schema, shape, value) {
33
+ const props = propertiesOf(shape);
34
+ const required = Array.isArray(shape.required) ? shape.required : [];
35
+ return Object.entries(value).every(([k, v]) => k in props && allowed(schema, props[k], v)) && required.every((k) => k in value);
36
+ }
37
+ function objectBranch(schema, node, value) {
38
+ const objects = branches(schema, node).filter((b) => propertiesOf(b));
39
+ if (objects.length === 1) {
40
+ const only = objects[0];
41
+ return only.additionalProperties === false && Object.keys(value).some((k) => !(k in propertiesOf(only))) ? undefined : only;
42
+ }
43
+ const fitting = objects.filter((b) => fits(schema, b, value));
44
+ return fitting.length === 1 ? fitting[0] : undefined;
45
+ }
46
+ function arrayBranch(schema, node) {
47
+ const arrays = branches(schema, node).filter((b) => b.type === "array");
48
+ return arrays.length === 1 ? arrays[0] : undefined;
49
+ }
50
+ export function sectionFields(schema, section) {
51
+ if (!schema)
52
+ return undefined;
53
+ const node = resolve(schema, schema.properties?.[section]);
54
+ if (!node)
55
+ return undefined;
56
+ const object = branches(schema, node).find((b) => propertiesOf(b));
57
+ const props = propertiesOf(object);
58
+ if (!props)
59
+ return undefined;
60
+ return Object.fromEntries(Object.entries(props).map(([k, v]) => [k, resolve(schema, v) ?? {}]));
61
+ }
62
+ export function exportForm(schema, node, value, depth = 0) {
63
+ const resolved = resolve(schema, node);
64
+ if (!resolved || depth > 40)
65
+ return value;
66
+ if (Array.isArray(value)) {
67
+ const array = arrayBranch(schema, resolved);
68
+ return array?.items ? value.map((item) => exportForm(schema, array.items, item, depth + 1)) : value;
69
+ }
70
+ if (!isObject(value))
71
+ return value;
72
+ const object = objectBranch(schema, resolved, value);
73
+ const props = propertiesOf(object);
74
+ if (!props)
75
+ return value;
76
+ const out = {};
77
+ for (const [key, sub] of Object.entries(props)) {
78
+ if (key in value)
79
+ out[key] = exportForm(schema, sub, value[key], depth + 1);
80
+ else {
81
+ const fallback = resolve(schema, sub)?.default;
82
+ if (fallback !== undefined && fallback !== null)
83
+ out[key] = structuredClone(fallback);
84
+ }
85
+ }
86
+ for (const [key, inner] of Object.entries(value))
87
+ if (!(key in out) && !(key in props))
88
+ out[key] = inner;
89
+ return out;
90
+ }
91
+ export function packageExportForm(schema, pkg) {
92
+ const out = {};
93
+ for (const [section, value] of Object.entries(pkg)) {
94
+ const node = schema.properties?.[section];
95
+ out[section] = node ? exportForm(schema, node, value) : value;
96
+ }
97
+ return out;
98
+ }
99
+ export function withoutNulls(value) {
100
+ if (Array.isArray(value))
101
+ return value.map(withoutNulls);
102
+ if (!isObject(value))
103
+ return value;
104
+ const out = {};
105
+ for (const [key, inner] of Object.entries(value))
106
+ if (inner !== null)
107
+ out[key] = withoutNulls(inner);
108
+ return out;
109
+ }
110
+ function isEmpty(value) {
111
+ return value === null || value === undefined || (isObject(value) && Object.keys(value).length === 0);
112
+ }
113
+ export function sameSectionValue(section, a, b, key) {
114
+ const left = withoutNulls(a);
115
+ const right = withoutNulls(b);
116
+ if (section === PERSONA_SECTION && isEmpty(left) && isEmpty(right))
117
+ return true;
118
+ return key(left) === key(right);
119
+ }
120
+ function placeholder(key, field) {
121
+ const fallback = field.default !== undefined ? field.default : field.type === "array" ? [] : null;
122
+ return `# ${toYaml({ [key]: fallback }).trimEnd().split("\n").join("\n# ")}`;
123
+ }
124
+ const PERSONA_HEADER = [
125
+ "# The persona: who the assistant is, shared by every agent of this solution (an agent's",
126
+ "# system_prompt says what that agent does). A commented field is not set; remove its #",
127
+ "# to set it. Write the greeting and fallback texts in the language the assistant answers in.",
128
+ ];
129
+ export function personaYaml(value, fields) {
130
+ const set = isObject(value) ? value : {};
131
+ const lines = [...PERSONA_HEADER];
132
+ for (const [key, field] of Object.entries(fields)) {
133
+ if (set[key] === undefined || set[key] === null)
134
+ lines.push(placeholder(key, field));
135
+ else
136
+ lines.push(toYaml({ [key]: set[key] }).trimEnd());
137
+ }
138
+ for (const [key, inner] of Object.entries(set)) {
139
+ if (!(key in fields) && inner !== undefined)
140
+ lines.push(toYaml({ [key]: inner }).trimEnd());
141
+ }
142
+ return lines.join("\n") + "\n";
143
+ }
144
+ export function sectionContent(section, value, schema, json) {
145
+ if (json)
146
+ return JSON.stringify(value, null, 2) + "\n";
147
+ const fields = section === PERSONA_SECTION ? sectionFields(schema, section) : undefined;
148
+ return fields ? personaYaml(value, fields) : toYaml(value);
149
+ }