@yaag/runtime 0.10.0 → 0.12.0

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 (59) hide show
  1. package/package.json +1 -1
  2. package/src/agent/agent-compaction.ts +80 -0
  3. package/src/agent/agent-usage.ts +11 -0
  4. package/src/agent/agent.ts +95 -3
  5. package/src/agent/define-agent.ts +7 -5
  6. package/src/agent/fork.ts +74 -0
  7. package/src/agent/index.ts +1 -0
  8. package/src/agent/spawn-open.ts +249 -0
  9. package/src/agent/spawn-request.ts +12 -1
  10. package/src/agent/spawn.ts +25 -197
  11. package/src/ask/ask-exchange.ts +2 -8
  12. package/src/cassette/cassette-replay.ts +33 -1
  13. package/src/cassette/cassette-schema.ts +20 -0
  14. package/src/cassette/cassette.ts +69 -6
  15. package/src/cassette/index.ts +1 -0
  16. package/src/cassette/recording-transport.ts +13 -0
  17. package/src/cassette/replay-divergence.ts +51 -2
  18. package/src/cassette/replay-transport.ts +22 -1
  19. package/src/cassette/resume-transport.ts +27 -2
  20. package/src/catalog/agent-describe-fixture.ts +121 -0
  21. package/src/catalog/agent-describe.ts +210 -0
  22. package/src/catalog/catalog-entry.ts +39 -0
  23. package/src/catalog/catalog-fixture.ts +87 -0
  24. package/src/catalog/catalog-match.ts +77 -0
  25. package/src/catalog/catalog-result.ts +69 -0
  26. package/src/catalog/index.ts +57 -0
  27. package/src/catalog/load-catalog.ts +74 -0
  28. package/src/catalog/program-scan.ts +64 -0
  29. package/src/catalog/registry-paths.ts +26 -0
  30. package/src/catalog/registry-reader.ts +115 -0
  31. package/src/catalog/registry-schema.ts +119 -0
  32. package/src/config/config-paths.ts +14 -7
  33. package/src/config/index.ts +1 -0
  34. package/src/contract/agent-report.ts +42 -0
  35. package/src/contract/error-codes.ts +65 -0
  36. package/src/contract/handle.ts +132 -0
  37. package/src/contract/index.ts +34 -0
  38. package/src/contract/model-spec.ts +81 -0
  39. package/src/contract/spawn-options.ts +127 -0
  40. package/src/error-factories.ts +70 -0
  41. package/src/errors.ts +22 -114
  42. package/src/events.ts +26 -1
  43. package/src/index.ts +49 -0
  44. package/src/model/model-resolution.ts +19 -71
  45. package/src/model/model-swap.ts +1 -1
  46. package/src/model/resolution-loop.ts +1 -1
  47. package/src/model/thinking-level.ts +5 -5
  48. package/src/public-api.ts +28 -0
  49. package/src/run/run-context.ts +4 -2
  50. package/src/summary/index.ts +1 -0
  51. package/src/summary/summary-agent.ts +38 -0
  52. package/src/summary/summary.ts +20 -0
  53. package/src/transport/fake-transport.ts +35 -1
  54. package/src/transport/index.ts +9 -1
  55. package/src/transport/live-transport.ts +9 -0
  56. package/src/transport/pi-state.ts +53 -10
  57. package/src/transport/transport.ts +54 -9
  58. package/src/transport/worktree-transport.ts +39 -6
  59. package/src/types.ts +16 -201
@@ -0,0 +1,69 @@
1
+ import type { CatalogSource } from "./catalog-entry.ts";
2
+
3
+ /** What a Catalog row describes: a scanned program, or a registered Definition. */
4
+ export type CatalogKind = "program" | "agent";
5
+
6
+ /**
7
+ * One problem found while building the Catalog. A diagnostic never fails a
8
+ * call: the Catalog flags, it does not fail.
9
+ */
10
+ export interface CatalogDiagnostic {
11
+ /** `file` = the whole registry file is unusable; `entry` = one entry, still listed. */
12
+ readonly scope: "file" | "entry";
13
+ /** Index within the file's `agents` array, when the diagnostic is entry-scoped. */
14
+ readonly index?: number;
15
+ /**
16
+ * The registry file the problem came from. A file-scoped diagnostic produces
17
+ * no row, so this field is the only thing that names its file; absent means
18
+ * the caller parsed text it did not name.
19
+ */
20
+ readonly path?: string;
21
+ /** Names the problem. It never holds the file path: read `path` for that. */
22
+ readonly message: string;
23
+ }
24
+
25
+ /**
26
+ * One listed program or Agent Definition.
27
+ *
28
+ * A broken entry still gets a row: its `name` is the raw string when the value
29
+ * was a string, and `""` otherwise, plus an entry-scoped diagnostic. Rows are
30
+ * never dropped and duplicate names are never collapsed or shadowed —
31
+ * `source` and `path` disambiguate them.
32
+ */
33
+ export interface CatalogRow {
34
+ readonly kind: CatalogKind;
35
+ readonly name: string;
36
+ readonly description?: string;
37
+ readonly tags?: readonly string[];
38
+ /** The program file path, or the Definition's resolved `file`. */
39
+ readonly path: string;
40
+ /** Agents only: the module export the Definition is read from. */
41
+ readonly exportName?: string;
42
+ readonly source: CatalogSource;
43
+ /** Stat-only check filled by the reader; absent means "not checked". */
44
+ readonly fileMissing?: boolean;
45
+ readonly diagnostics?: readonly CatalogDiagnostic[];
46
+ }
47
+
48
+ /**
49
+ * A Catalog query. `pattern` is substring or glob, never a regex; `dir`
50
+ * narrows to one Program Directory.
51
+ */
52
+ export interface CatalogQuery {
53
+ readonly kind?: CatalogKind;
54
+ readonly pattern?: string;
55
+ readonly dir?: string;
56
+ }
57
+
58
+ /**
59
+ * The answer to one Catalog call. Row order is the global layer first, then
60
+ * Program Directories in sorted order, then file order inside each.
61
+ *
62
+ * A result is a fresh read per call. It layers sources but it does not merge
63
+ * them and it is not frozen for the life of a Run.
64
+ */
65
+ export interface CatalogResult {
66
+ readonly rows: readonly CatalogRow[];
67
+ /** File-scoped problems that produced no row, such as an unreadable file. */
68
+ readonly diagnostics: readonly CatalogDiagnostic[];
69
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Public surface of the `catalog/` module: the Catalog contract (ADR-0046) —
3
+ * registry file shapes, result rows, the matcher, the path ladder, and the
4
+ * fixture Catalog consumer tests assert against, plus the on-demand describe
5
+ * contract for a registered Agent Definition (ADR-0047) and its recorded
6
+ * CLI-child transcript, plus the reader, the program
7
+ * scanner, and the layer merge. The contract half is pure; `load-catalog.ts`,
8
+ * `registry-reader.ts`, and `program-scan.ts` read files and file names only,
9
+ * and import no Orchestration Program module.
10
+ */
11
+
12
+ export type {
13
+ AgentDeclaredMetadata,
14
+ AgentDescribeFinding,
15
+ AgentDescribeFindingCode,
16
+ AgentDescribeFindingResult,
17
+ AgentDescribeRequest,
18
+ AgentDescribeResult,
19
+ DescribedAgent,
20
+ NameDeviation,
21
+ } from "./agent-describe.ts";
22
+ export {
23
+ AGENT_DESCRIBE_FINDING_CODES,
24
+ agentDescribeArgv,
25
+ describedAgent,
26
+ encodeAgentDescribe,
27
+ parseAgentDescribe,
28
+ } from "./agent-describe.ts";
29
+ export {
30
+ AGENT_DESCRIBE_TRANSCRIPT,
31
+ type AgentDescribeTranscriptEntry,
32
+ transcriptFor,
33
+ } from "./agent-describe-fixture.ts";
34
+ export type {
35
+ AgentDefinitionEntry,
36
+ CatalogLayer,
37
+ CatalogSource,
38
+ RegistryDocument,
39
+ } from "./catalog-entry.ts";
40
+ export { CATALOG_FIXTURE } from "./catalog-fixture.ts";
41
+ export { filterCatalog, matchesPattern } from "./catalog-match.ts";
42
+ export type {
43
+ CatalogDiagnostic,
44
+ CatalogKind,
45
+ CatalogQuery,
46
+ CatalogResult,
47
+ CatalogRow,
48
+ } from "./catalog-result.ts";
49
+ export { type CatalogRequest, loadCatalog } from "./load-catalog.ts";
50
+ export { scanPrograms } from "./program-scan.ts";
51
+ export { globalRegistryPath, projectRegistryPath, REGISTRY_FILE_NAME } from "./registry-paths.ts";
52
+ export { type RegistryLayerRequest, readRegistryLayer } from "./registry-reader.ts";
53
+ export {
54
+ type ParsedRegistryFile,
55
+ parseRegistryFile,
56
+ readRegistryDocument,
57
+ } from "./registry-schema.ts";
@@ -0,0 +1,74 @@
1
+ import { resolve } from "node:path";
2
+ import type { ConfigEnvironment } from "../config/index.ts";
3
+ import { filterCatalog } from "./catalog-match.ts";
4
+ import type { CatalogQuery, CatalogResult, CatalogRow } from "./catalog-result.ts";
5
+ import { scanPrograms } from "./program-scan.ts";
6
+ import { globalRegistryPath, projectRegistryPath } from "./registry-paths.ts";
7
+ import { readRegistryLayer } from "./registry-reader.ts";
8
+
9
+ /** What one Catalog call reads. */
10
+ export interface CatalogRequest {
11
+ /** Program Directories to scan; the caller discovers them (ADR-0040). */
12
+ readonly programDirectories?: readonly string[];
13
+ /** Environment for the global registry ladder; defaults to `process.env`. */
14
+ readonly env?: ConfigEnvironment;
15
+ /**
16
+ * Skips the global layer. No shipped front-end sets it: both read the
17
+ * global layer always, because `filterCatalog` drops the global rows of a
18
+ * `dir` query while a file diagnostic must still surface. The tests of this
19
+ * module set it, so a Catalog assertion never depends on the global
20
+ * registry file of the developer.
21
+ */
22
+ readonly noGlobal?: boolean;
23
+ /** Applied to the merged rows; absent lists everything. */
24
+ readonly query?: CatalogQuery;
25
+ }
26
+
27
+ /**
28
+ * Reads the Catalog fresh: the global registry file first, then each Program
29
+ * Directory in sorted order, and inside one directory the scanned programs
30
+ * first, then its registry entries in file order.
31
+ *
32
+ * Layers are concatenated, never merged: two rows with the same name both
33
+ * survive, and `source` plus `path` tell them apart. Reads run concurrently,
34
+ * but assembly is deterministic — concurrency never leaks into row order.
35
+ *
36
+ * `query` filters rows only. Diagnostics are never filtered: a registry file
37
+ * yaag cannot read still needs reporting when its rows would not match.
38
+ *
39
+ * The result is a fresh read per call: nothing is cached and nothing is
40
+ * frozen. It is not an Effective Config.
41
+ */
42
+ export async function loadCatalog(request: CatalogRequest = {}): Promise<CatalogResult> {
43
+ const directories = normalise(request.programDirectories ?? []);
44
+ const global = request.noGlobal
45
+ ? undefined
46
+ : readRegistryLayer({ path: globalRegistryPath(request.env), layer: "global" });
47
+ const projects = directories.map(async (directory) => {
48
+ const [programs, agents] = await Promise.all([
49
+ scanPrograms(directory),
50
+ readRegistryLayer({ path: projectRegistryPath(directory), layer: "project" }),
51
+ ]);
52
+ return concat([programs, agents]);
53
+ });
54
+
55
+ const layers = await Promise.all([...(global === undefined ? [] : [global]), ...projects]);
56
+ const merged = concat(layers);
57
+ const rows: readonly CatalogRow[] =
58
+ request.query === undefined ? merged.rows : filterCatalog(merged.rows, request.query);
59
+ return { rows, diagnostics: merged.diagnostics };
60
+ }
61
+
62
+ function concat(results: readonly CatalogResult[]): CatalogResult {
63
+ return {
64
+ rows: results.flatMap((result) => result.rows),
65
+ diagnostics: results.flatMap((result) => result.diagnostics),
66
+ };
67
+ }
68
+
69
+ /** Resolves, de-duplicates, and sorts the caller's Program Directories. */
70
+ function normalise(directories: readonly string[]): readonly string[] {
71
+ return [...new Set(directories.map((directory) => resolve(directory)))].sort((left, right) =>
72
+ left.localeCompare(right),
73
+ );
74
+ }
@@ -0,0 +1,64 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import { basename, join, resolve } from "node:path";
3
+ import type { CatalogResult, CatalogRow } from "./catalog-result.ts";
4
+
5
+ /**
6
+ * Lists the Orchestration Programs of one Program Directory: the top-level
7
+ * `.ts` files there (ADR-0028). The scan is non-recursive, so `.yaag/` and
8
+ * every other sub-directory is skipped, and it never imports a module — a row
9
+ * is built from the directory entry alone.
10
+ *
11
+ * A scanned row carries no `description`: a program's description lives inside
12
+ * `defineRun(...)`, and reading it needs an import, which ADR-0046 forbids at
13
+ * list time. `yaag_describe` owns that path.
14
+ *
15
+ * Never throws: an unreadable or absent directory becomes one file-scoped
16
+ * diagnostic and zero rows.
17
+ */
18
+ export async function scanPrograms(programDirectory: string): Promise<CatalogResult> {
19
+ const directory = resolve(programDirectory);
20
+ try {
21
+ const found = await readdir(directory, { withFileTypes: true });
22
+ const rows: CatalogRow[] = found
23
+ .filter((entry) => entry.isFile() && isProgramFile(entry.name))
24
+ .map((entry) => ({
25
+ kind: "program" as const,
26
+ name: basename(entry.name, ".ts"),
27
+ path: join(directory, entry.name),
28
+ source: { layer: "project" as const, origin: directory },
29
+ }));
30
+ rows.sort((left, right) => left.path.localeCompare(right.path));
31
+ return { rows, diagnostics: [] };
32
+ } catch (error) {
33
+ return {
34
+ rows: [],
35
+ diagnostics: [
36
+ {
37
+ scope: "file",
38
+ path: directory,
39
+ message: `program directory cannot be read: ${describe(error)}`,
40
+ },
41
+ ],
42
+ };
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Names a read failure by its errno alone. A Node fs error states the path in
48
+ * its own message, and a diagnostic message never holds the file path: `path`
49
+ * names the directory (`catalog-result.ts`).
50
+ */
51
+ function describe(error: unknown): string {
52
+ if (typeof error === "object" && error !== null && "code" in error) {
53
+ const { code } = error;
54
+ if (typeof code === "string") return code;
55
+ }
56
+ return "unknown error";
57
+ }
58
+
59
+ /** A program file is a top-level `.ts` file that is not a test, a declaration, or a dotfile. */
60
+ function isProgramFile(name: string): boolean {
61
+ if (name.startsWith(".")) return false;
62
+ if (!name.endsWith(".ts")) return false;
63
+ return !name.endsWith(".d.ts") && !name.endsWith(".test.ts");
64
+ }
@@ -0,0 +1,26 @@
1
+ import { join } from "node:path";
2
+ import {
3
+ type ConfigEnvironment,
4
+ PROJECT_CONFIG_DIR,
5
+ resolveGlobalConfigDirectory,
6
+ } from "../config/index.ts";
7
+
8
+ /** Every Catalog registry file has this name, in both layers. */
9
+ export const REGISTRY_FILE_NAME = "registry.json";
10
+
11
+ /**
12
+ * The registry file of one Program Directory: `<dir>/.yaag/registry.json`.
13
+ * The Program Directory is an input: this module never walks upward.
14
+ */
15
+ export function projectRegistryPath(programDirectory: string): string {
16
+ return join(programDirectory, PROJECT_CONFIG_DIR, REGISTRY_FILE_NAME);
17
+ }
18
+
19
+ /**
20
+ * The global registry file: `registry.json` inside the Global Config
21
+ * directory, beside `config.json` but deliberately a separate file, so a
22
+ * catalog typo can never fail the strict config schema (ADR-0046).
23
+ */
24
+ export function globalRegistryPath(env?: ConfigEnvironment): string {
25
+ return join(resolveGlobalConfigDirectory(env), REGISTRY_FILE_NAME);
26
+ }
@@ -0,0 +1,115 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import type { AgentDefinitionEntry, CatalogLayer } from "./catalog-entry.ts";
4
+ import type { CatalogDiagnostic, CatalogResult, CatalogRow } from "./catalog-result.ts";
5
+ import { parseRegistryFile } from "./registry-schema.ts";
6
+
7
+ /** One registry file to read, and the layer its rows belong to. */
8
+ export interface RegistryLayerRequest {
9
+ readonly path: string;
10
+ readonly layer: CatalogLayer;
11
+ }
12
+
13
+ const EMPTY: CatalogResult = { rows: [], diagnostics: [] };
14
+
15
+ /**
16
+ * Reads one registry file into rows plus file-scoped diagnostics. Never
17
+ * throws: an absent file is a normal, silent state, and any other read error
18
+ * becomes a diagnostic. This deviates from `readConfigLayer`, which throws on
19
+ * `EACCES`, on purpose: the Catalog flags, it never fails (ADR-0046).
20
+ *
21
+ * The `fileMissing` flag is a `stat` only. This function imports no
22
+ * Orchestration Program module and reads no target file.
23
+ */
24
+ export async function readRegistryLayer(request: RegistryLayerRequest): Promise<CatalogResult> {
25
+ let text: string;
26
+ try {
27
+ text = await readFile(request.path, "utf8");
28
+ } catch (error) {
29
+ if (isMissing(error)) return EMPTY;
30
+ return {
31
+ rows: [],
32
+ diagnostics: [
33
+ {
34
+ scope: "file",
35
+ path: request.path,
36
+ message: `registry file cannot be read: ${describe(error)}`,
37
+ },
38
+ ],
39
+ };
40
+ }
41
+
42
+ const parsed = parseRegistryFile(text, request.path);
43
+ const fileScoped: CatalogDiagnostic[] = [];
44
+ const entryScoped = new Map<number, CatalogDiagnostic[]>();
45
+ for (const diagnostic of parsed.diagnostics) {
46
+ if (diagnostic.scope === "file" || diagnostic.index === undefined) {
47
+ fileScoped.push(diagnostic);
48
+ continue;
49
+ }
50
+ const bucket = entryScoped.get(diagnostic.index) ?? [];
51
+ bucket.push(diagnostic);
52
+ entryScoped.set(diagnostic.index, bucket);
53
+ }
54
+
55
+ const base = dirname(resolve(request.path));
56
+ const rows = parsed.entries.map((entry, index) =>
57
+ toRow(entry, base, request, entryScoped.get(index)),
58
+ );
59
+ return { rows: await Promise.all(rows.map(withFileMissing)), diagnostics: fileScoped };
60
+ }
61
+
62
+ /**
63
+ * Builds one row. A relative `file` resolves against the declaring registry
64
+ * file's directory, never the current working directory; an entry that lost
65
+ * its `file` keeps an empty path and is never checked on disk.
66
+ */
67
+ function toRow(
68
+ entry: AgentDefinitionEntry,
69
+ base: string,
70
+ request: RegistryLayerRequest,
71
+ diagnostics: readonly CatalogDiagnostic[] | undefined,
72
+ ): CatalogRow {
73
+ return {
74
+ kind: "agent",
75
+ name: entry.name,
76
+ exportName: entry.exportName,
77
+ path: entry.file === "" ? "" : resolve(base, entry.file),
78
+ ...(entry.description === undefined ? {} : { description: entry.description }),
79
+ ...(entry.tags === undefined ? {} : { tags: entry.tags }),
80
+ source: { layer: request.layer, origin: request.path },
81
+ ...(diagnostics === undefined ? {} : { diagnostics }),
82
+ };
83
+ }
84
+
85
+ async function withFileMissing(row: CatalogRow): Promise<CatalogRow> {
86
+ if (row.path === "") return row;
87
+ return { ...row, fileMissing: !(await isFile(row.path)) };
88
+ }
89
+
90
+ async function isFile(path: string): Promise<boolean> {
91
+ try {
92
+ return (await stat(path)).isFile();
93
+ } catch {
94
+ return false;
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Names a read failure by its errno alone. A Node fs error states the path in
100
+ * its own message, and a diagnostic message never holds the file path: `path`
101
+ * names the file (`catalog-result.ts`).
102
+ */
103
+ function describe(error: unknown): string {
104
+ if (typeof error === "object" && error !== null && "code" in error) {
105
+ const { code } = error;
106
+ if (typeof code === "string") return code;
107
+ }
108
+ return "unknown error";
109
+ }
110
+
111
+ function isMissing(error: unknown): boolean {
112
+ if (typeof error !== "object" || error === null || !("code" in error)) return false;
113
+ const { code } = error;
114
+ return code === "ENOENT" || code === "ENOTDIR";
115
+ }
@@ -0,0 +1,119 @@
1
+ import { Type } from "typebox";
2
+ import { Value } from "typebox/value";
3
+ import { formatValidationErrors } from "../validation-errors.ts";
4
+ import type { AgentDefinitionEntry, RegistryDocument } from "./catalog-entry.ts";
5
+ import type { CatalogDiagnostic } from "./catalog-result.ts";
6
+
7
+ /**
8
+ * The registry file schema. No node sets `additionalProperties: false` — like
9
+ * `cassette-schema.ts` and the opposite of `config-schema.ts`. A registry file
10
+ * is machine-written and read by many yaag versions, so an unknown key is
11
+ * forward compatibility, not a typo the author wants named. For the same
12
+ * reason this file wraps `formatValidationErrors` and never calls
13
+ * `describeConfigIssues`, which exists to name unknown keys in a strict schema.
14
+ */
15
+
16
+ const AGENT_ENTRY_SCHEMA = Type.Object({
17
+ file: Type.String(),
18
+ exportName: Type.String(),
19
+ name: Type.String(),
20
+ description: Type.Optional(Type.String()),
21
+ tags: Type.Optional(Type.Array(Type.String())),
22
+ });
23
+
24
+ /** The outcome of parsing one registry file: entries plus every problem found. */
25
+ export interface ParsedRegistryFile {
26
+ readonly entries: readonly AgentDefinitionEntry[];
27
+ readonly diagnostics: readonly CatalogDiagnostic[];
28
+ }
29
+
30
+ const EMPTY: ParsedRegistryFile = { entries: [], diagnostics: [] };
31
+
32
+ /**
33
+ * Parses one registry file's JSON text. Never throws: invalid JSON becomes one
34
+ * file-scoped diagnostic and zero entries. `path` names the file the text came
35
+ * from, and every file-scoped diagnostic carries it, so a caller can report
36
+ * which registry file failed.
37
+ */
38
+ export function parseRegistryFile(text: string, path?: string): ParsedRegistryFile {
39
+ let value: unknown;
40
+ try {
41
+ value = JSON.parse(text);
42
+ } catch (cause) {
43
+ const message = cause instanceof Error ? cause.message : String(cause);
44
+ return { entries: [], diagnostics: [fileIssue(`is not valid JSON: ${message}`, path)] };
45
+ }
46
+ return readRegistryDocument(value, path);
47
+ }
48
+
49
+ /**
50
+ * Reads an already-parsed registry document. Never throws: a wrong root shape
51
+ * is a file-scoped diagnostic naming `path`, and a malformed entry is kept
52
+ * with an entry-scoped diagnostic carrying its index.
53
+ */
54
+ export function readRegistryDocument(value: unknown, path?: string): ParsedRegistryFile {
55
+ const document = asRegistryDocument(value);
56
+ if (document === undefined) {
57
+ return { entries: [], diagnostics: [fileIssue("must contain a JSON object", path)] };
58
+ }
59
+ const agents = document.agents;
60
+ if (agents === undefined) return EMPTY;
61
+ if (!Array.isArray(agents)) {
62
+ return { entries: [], diagnostics: [fileIssue('"agents" must be an array', path)] };
63
+ }
64
+
65
+ const entries: AgentDefinitionEntry[] = [];
66
+ const diagnostics: CatalogDiagnostic[] = [];
67
+ agents.forEach((element, index) => {
68
+ const errors = formatValidationErrors(element, Value.Errors(AGENT_ENTRY_SCHEMA, element));
69
+ if (errors.length > 0) {
70
+ diagnostics.push({ scope: "entry", index, message: errors.join("; ") });
71
+ }
72
+ entries.push(toEntry(element));
73
+ });
74
+ return { entries, diagnostics };
75
+ }
76
+
77
+ /**
78
+ * Narrows a parsed JSON root to a registry document. An array, a scalar, and
79
+ * `null` are all rejected: only a JSON object can hold `agents`. The `agents`
80
+ * field itself stays unchecked here, because the caller reports a wrong one as
81
+ * its own diagnostic.
82
+ */
83
+ function asRegistryDocument(value: unknown): RegistryDocument | undefined {
84
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
85
+ return value as RegistryDocument;
86
+ }
87
+
88
+ /**
89
+ * Builds an entry from a possibly malformed element. A missing or non-string
90
+ * field becomes `""` so the entry still produces a row: the Catalog flags a
91
+ * problem, it never drops the entry.
92
+ */
93
+ function toEntry(element: unknown): AgentDefinitionEntry {
94
+ const record = (typeof element === "object" && element !== null ? element : {}) as Record<
95
+ string,
96
+ unknown
97
+ >;
98
+ const description = record["description"];
99
+ const tags = record["tags"];
100
+ return {
101
+ file: text(record["file"]),
102
+ exportName: text(record["exportName"]),
103
+ name: text(record["name"]),
104
+ ...(typeof description === "string" ? { description } : {}),
105
+ ...(Array.isArray(tags) ? { tags: tags.filter((tag) => typeof tag === "string") } : {}),
106
+ };
107
+ }
108
+
109
+ function text(value: unknown): string {
110
+ return typeof value === "string" ? value : "";
111
+ }
112
+
113
+ function fileIssue(message: string, path: string | undefined): CatalogDiagnostic {
114
+ return {
115
+ scope: "file",
116
+ ...(path === undefined ? {} : { path }),
117
+ message: `registry file ${message}`,
118
+ };
119
+ }
@@ -16,17 +16,24 @@ export const CONFIG_FILE_NAME = "config.json";
16
16
  export const PROJECT_CONFIG_DIR = ".yaag";
17
17
 
18
18
  /**
19
- * Resolves the Global Config path: `YAAG_CONFIG_DIR`, then an absolute
20
- * `XDG_CONFIG_HOME`, then `$HOME/.config`. A relative `XDG_CONFIG_HOME` is
21
- * ignored (XDG spec), exactly as in `resolveCheckpointDirectory`.
19
+ * Resolves the directory that holds the global yaag files: `YAAG_CONFIG_DIR`,
20
+ * then an absolute `XDG_CONFIG_HOME`, then `$HOME/.config`. A relative
21
+ * `XDG_CONFIG_HOME` is ignored (XDG spec), exactly as in
22
+ * `resolveCheckpointDirectory`. Never throws: an unset `HOME` falls back to
23
+ * `os.homedir()`.
22
24
  */
23
- export function resolveGlobalConfigPath(env: ConfigEnvironment = process.env): string {
25
+ export function resolveGlobalConfigDirectory(env: ConfigEnvironment = process.env): string {
24
26
  const override = env["YAAG_CONFIG_DIR"];
25
- if (override !== undefined && override !== "") return join(override, CONFIG_FILE_NAME);
27
+ if (override !== undefined && override !== "") return override;
26
28
  const xdg = env["XDG_CONFIG_HOME"];
27
- if (xdg !== undefined && isAbsolute(xdg)) return join(xdg, "yaag", CONFIG_FILE_NAME);
29
+ if (xdg !== undefined && isAbsolute(xdg)) return join(xdg, "yaag");
28
30
  const home = env["HOME"] !== undefined && env["HOME"] !== "" ? env["HOME"] : homedir();
29
- return join(home, ".config", "yaag", CONFIG_FILE_NAME);
31
+ return join(home, ".config", "yaag");
32
+ }
33
+
34
+ /** Resolves the Global Config file inside {@link resolveGlobalConfigDirectory}. */
35
+ export function resolveGlobalConfigPath(env: ConfigEnvironment = process.env): string {
36
+ return join(resolveGlobalConfigDirectory(env), CONFIG_FILE_NAME);
30
37
  }
31
38
 
32
39
  /**
@@ -9,6 +9,7 @@ export {
9
9
  type ConfigEnvironment,
10
10
  PROJECT_CONFIG_DIR,
11
11
  projectConfigPath,
12
+ resolveGlobalConfigDirectory,
12
13
  resolveGlobalConfigPath,
13
14
  } from "./config-paths.ts";
14
15
  export type { YaagConfigDocument } from "./config-schema.ts";
@@ -0,0 +1,42 @@
1
+ /**
2
+ * What an Agent reports about itself, as far as an author can read it.
3
+ *
4
+ * Types only, and no import outside this directory (ADR-0045). The transport
5
+ * modules that produce these shapes re-export them.
6
+ */
7
+
8
+ /** pi's full token usage for one Agent, as reported by `get_session_stats`. */
9
+ export interface TokenBreakdown {
10
+ readonly input: number;
11
+ readonly output: number;
12
+ readonly cacheRead: number;
13
+ readonly cacheWrite: number;
14
+ readonly total: number;
15
+ }
16
+
17
+ /**
18
+ * What one compaction of an Agent's context reported (ADR-0043).
19
+ *
20
+ * Every field is null when pi reported nothing for it: a custom compaction
21
+ * handler may answer without usage, and "unknown" must stay distinct from 0.
22
+ */
23
+ export interface CompactionResult {
24
+ /** Context tokens before the summary replaced the transcript. */
25
+ readonly tokensBefore: number | null;
26
+ /** Estimated context tokens after the summary replaced the transcript. */
27
+ readonly tokensAfter: number | null;
28
+ /** Token breakdown of the summary call itself. */
29
+ readonly tokens: TokenBreakdown | null;
30
+ /** Cost of the summary call itself. */
31
+ readonly cost: number | null;
32
+ }
33
+
34
+ /** What the Agent reported about its own work, read from a `get_state` probe. */
35
+ export interface AgentProgress {
36
+ /** True while pi streams a completion, compacts its context, or holds a queued prompt. */
37
+ readonly working: boolean;
38
+ readonly streaming: boolean;
39
+ readonly compacting: boolean;
40
+ /** Prompts pi has queued but not started. */
41
+ readonly pendingMessages: number;
42
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The failure vocabulary of the author contract (ADR-0003).
3
+ *
4
+ * Types only, and no import outside this directory (ADR-0045). `YaagError`
5
+ * itself stays in `errors.ts`, because it is a value.
6
+ */
7
+ import type { AgentProgress } from "./agent-report.ts";
8
+ import type { ModelError } from "./model-spec.ts";
9
+
10
+ /** Which soft Ask budget was exhausted. */
11
+ export type AskLimitKind = "turns" | "toolCalls" | "durationMs";
12
+
13
+ /** The recorded result when yaag aborts an Ask after a soft budget is exhausted. */
14
+ export interface AskLimitOutcome {
15
+ readonly kind: AskLimitKind;
16
+ readonly count: number;
17
+ }
18
+
19
+ /** The recorded result when yaag rejects an Ask because no frame arrived within `idleMs`. */
20
+ export interface AskStalledOutcome {
21
+ /** The configured silence threshold that tripped. */
22
+ readonly idleMs: number;
23
+ /** True when escalation failed to settle the Agent and yaag killed the process. */
24
+ readonly destructive: boolean;
25
+ /** State the Stall Watchdog probe observed; absent when the probe stayed silent. */
26
+ readonly state?: AgentProgress;
27
+ }
28
+
29
+ /** Recoverable result when all structured-output correction efforts are exhausted. */
30
+ export interface AskInvalidOutputOutcome {
31
+ /** Corrective steers sent before aborting this Ask. */
32
+ readonly steeringEfforts: number;
33
+ /** Final extraction or TypeBox diagnostics, localized to JSON paths. */
34
+ readonly errors: readonly string[];
35
+ }
36
+
37
+ /** The recorded history when every model candidate of one Model Resolution loop failed. */
38
+ export interface ModelResolutionOutcome {
39
+ readonly modelErrors: readonly ModelError[];
40
+ }
41
+
42
+ /** Why an Ask, spawn, or Run failed. Programs may branch on this; most won't. */
43
+ export type YaagErrorCode =
44
+ | "AGENT_FAILED" // turn settled with stopReason error/aborted, or empty text
45
+ | "AGENT_DIED" // process exited with an Ask pending
46
+ | "AGENT_BUSY" // concurrent ask() on one Handle
47
+ | "ASK_TIMEOUT" // timeoutMs elapsed
48
+ | "ASK_LIMIT" // soft Ask budget exceeded after grace
49
+ | "ASK_STALLED" // no frame arrived within the silence budget; escalated, then kill
50
+ | "COMPACT_DURING_ASK" // compact() was called while an Ask was in flight
51
+ | "COMPACT_FAILED" // pi refused or could not summarize the context
52
+ | "FORK_DURING_ASK" // fork() was called while the source Ask was in flight
53
+ | "FORK_REFUSED" // the fork source died mid-Ask, or holds no session file
54
+ | "ASK_INVALID_OUTPUT" // settled text could not be extracted or satisfy outputSchema
55
+ | "ARGS_INVALID" // arguments failed schema validation before the Run started
56
+ | "CONFIG_INVALID" // a config layer is missing, unparsable, or violates the schema
57
+ | "OPTIONS_CONFLICT" // incompatible Run options were supplied
58
+ | "RECORD_PATH_UNUSABLE" // the --record directory could not be created at Run start
59
+ | "REPLAY_DIVERGED" // replayed program differed from its Cassette
60
+ | "RESUME_REFUSED" // resume metadata is absent or the recorded tree moved
61
+ | "RUN_CLOSED" // spawn was requested after the Run began settling
62
+ | "RUN_STOPPED" // the Run's abort signal fired before the program completed
63
+ | "WORKTREE_REFUSED" // base cwd is not a clean Git repository
64
+ | "MODEL_RESOLUTION_FAILED" // the resolver gave up, or every candidate failed; carries the history
65
+ | "SPAWN_FAILED"; // pi failed to start, e.g. a broken tool contract or a startup timeout