@yaag/runtime 0.24.0 → 0.25.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yaag/runtime",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -14,3 +14,4 @@ export {
14
14
  } from "./define-agent.ts";
15
15
  export { type ForkSource, type ForkSpawner, forkRequest } from "./fork.ts";
16
16
  export { makeSpawn } from "./spawn.ts";
17
+ export { isSpawnableDefinition } from "./spawnable-definition.ts";
@@ -8,7 +8,7 @@ import type { RunContext } from "../run/index.ts";
8
8
  import type { TransportFactory } from "../transport/index.ts";
9
9
  import type { Handle, SpawnOptions, SpawnOverrides } from "../types.ts";
10
10
  import type { Agent } from "./agent.ts";
11
- import type { AgentDefinition } from "./define-agent.ts";
11
+ import { type AgentDefinition, isAgentDefinition } from "./define-agent.ts";
12
12
  import { type ForkSpawner, forkRequest } from "./fork.ts";
13
13
  import { resolveRequest } from "./spawn-definition-request.ts";
14
14
  import { type OpenAgentContext, openAgent } from "./spawn-open.ts";
@@ -70,12 +70,15 @@ export function makeSpawn(deps: SpawnDependencies): SpawnGate {
70
70
  overrides?: SpawnOverrides,
71
71
  ): Promise<Handle> => {
72
72
  if (closed) throw new YaagError("RUN_CLOSED", "run has already settled");
73
- return openAgent(
74
- context,
75
- isProfiledDefinition(definitionOrOptions)
76
- ? profiledRequest(deps.profile, definitionOrOptions, overrides)
77
- : resolveRequest(definitionOrOptions, overrides),
78
- );
73
+ // The Agent Definition branch is explicit, although `resolveRequest` takes
74
+ // a plain options object too: it states the three accepted shapes in order.
75
+ if (isAgentDefinition(definitionOrOptions)) {
76
+ return openAgent(context, resolveRequest(definitionOrOptions, overrides));
77
+ }
78
+ if (isProfiledDefinition(definitionOrOptions)) {
79
+ return openAgent(context, profiledRequest(deps.profile, definitionOrOptions, overrides));
80
+ }
81
+ return openAgent(context, resolveRequest(definitionOrOptions, overrides));
79
82
  };
80
83
  return {
81
84
  spawn,
@@ -0,0 +1,9 @@
1
+ /** The shared Spawnable Definition predicate (ADR-0053). */
2
+ import type { SpawnableDefinition } from "../contract/index.ts";
3
+ import { isProfiledDefinition } from "../profile/index.ts";
4
+ import { isAgentDefinition } from "./define-agent.ts";
5
+
6
+ /** True for an Agent Definition and for a Profiled Definition, and for nothing else. */
7
+ export function isSpawnableDefinition(value: unknown): value is SpawnableDefinition {
8
+ return isAgentDefinition(value) || isProfiledDefinition(value);
9
+ }
@@ -4,9 +4,10 @@
4
4
  * fixture Catalog consumer tests assert against, plus the on-demand describe
5
5
  * contract for a registered Agent Definition (ADR-0047) and its recorded
6
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.
7
+ * scanner, the layer merge, and the Catalog Resolve resolver. The contract
8
+ * half is pure; `load-catalog.ts`, `registry-reader.ts`, and `program-scan.ts`
9
+ * — the readers and the scanner — import no module; `resolve.ts` is the one
10
+ * file that imports a Definition module, on a program's request (ADR-0053).
10
11
  */
11
12
 
12
13
  export type {
@@ -56,3 +57,4 @@ export {
56
57
  parseRegistryFile,
57
58
  readRegistryDocument,
58
59
  } from "./registry-schema.ts";
60
+ export { createYaagGlobal } from "./resolve.ts";
@@ -0,0 +1,184 @@
1
+ /**
2
+ * The Catalog Resolve resolver (ADR-0053). It is the one file in `catalog/`
3
+ * that imports an Orchestration Program's Definition module, and only on a
4
+ * program's request.
5
+ *
6
+ * It calls `readFile` and `parseRegistryFile` directly and never
7
+ * `readRegistryLayer`: the reader turns every failure into a diagnostic, and
8
+ * this call must throw.
9
+ */
10
+ import { readFile, stat } from "node:fs/promises";
11
+ import { dirname, resolve } from "node:path";
12
+ import { isSpawnableDefinition } from "../agent/index.ts";
13
+ import type {
14
+ CatalogScope,
15
+ SpawnableDefinition,
16
+ YaagGlobal,
17
+ YaagGlobalOptions,
18
+ } from "../contract/index.ts";
19
+ import { YaagError } from "../errors.ts";
20
+ import type { AgentDefinitionEntry } from "./catalog-entry.ts";
21
+ import { parseRegistryFile } from "./registry-schema.ts";
22
+
23
+ /** Builds the `$yaag` global: two independent Catalog Scopes, never `undefined`. */
24
+ export function createYaagGlobal(options: YaagGlobalOptions): YaagGlobal {
25
+ return {
26
+ global: scope("global", options.globalRegistryPath),
27
+ project: scope("project", options.projectRegistryPath),
28
+ };
29
+ }
30
+
31
+ function scope(name: "global" | "project", registryPath: string | undefined): CatalogScope {
32
+ return { importAgent: (agent) => importAgent({ scope: name, registryPath, name: agent }) };
33
+ }
34
+
35
+ /** One resolve request: which scope asked, which Registry File, which name. */
36
+ interface ResolveRequest {
37
+ readonly scope: "global" | "project";
38
+ readonly registryPath: string | undefined;
39
+ readonly name: string;
40
+ }
41
+
42
+ /** Runs the fixed check order of the spec (decision 9). */
43
+ async function importAgent(request: ResolveRequest): Promise<SpawnableDefinition> {
44
+ if (request.registryPath === undefined) {
45
+ throw notFound(request, "this Run has no Program Directory");
46
+ }
47
+ const registry = resolve(request.registryPath);
48
+ const text = await readRegistry(request, registry);
49
+ const entries = parseEntries(request, registry, text);
50
+
51
+ const matches = entries.filter((entry) => entry.name === request.name);
52
+ if (matches.length > 1) {
53
+ const files = matches.map((entry) => JSON.stringify(entry.file)).join(", ");
54
+ throw new YaagError(
55
+ "CATALOG_ENTRY_AMBIGUOUS",
56
+ `${prefix(request)}: ${matches.length} agent entries have this name in ${registry}: ${files}`,
57
+ );
58
+ }
59
+ const [entry] = matches;
60
+ if (entry === undefined) {
61
+ throw notFound(request, `no agent entry has this name in ${registry}`);
62
+ }
63
+ const malformed =
64
+ entry.file === ""
65
+ ? "file is empty"
66
+ : entry.exportName === ""
67
+ ? "exportName is empty"
68
+ : undefined;
69
+ if (malformed !== undefined) {
70
+ throw unresolvable(request, `the entry in ${registry} is malformed: ${malformed}`, malformed);
71
+ }
72
+ return await loadEntry(request, resolve(dirname(registry), entry.file), entry.exportName);
73
+ }
74
+
75
+ /**
76
+ * Step 1, the read. ENOENT alone is `NOT_FOUND`; every other errno is
77
+ * `cannot be read`. This deviates from `readRegistryLayer`, which also
78
+ * swallows ENOTDIR: the spec names ENOENT only, thus a registry path under a
79
+ * file reads as `cannot be read`.
80
+ */
81
+ async function readRegistry(request: ResolveRequest, registry: string): Promise<string> {
82
+ try {
83
+ return await readFile(registry, "utf8");
84
+ } catch (cause) {
85
+ if ((cause as NodeJS.ErrnoException).code === "ENOENT") {
86
+ throw notFound(request, `no Registry File at ${registry}`);
87
+ }
88
+ throw unresolvable(request, `${registry} did not parse: cannot be read`, "cannot be read");
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Step 1, the parse. The file-scoped diagnostic prose comes from
94
+ * `registry-schema.ts`; this maps it to the spec's three remaining reasons. A
95
+ * `programs`-section diagnostic is ignored on purpose: a broken `programs`
96
+ * array never fails an agent resolve.
97
+ */
98
+ function parseEntries(
99
+ request: ResolveRequest,
100
+ registry: string,
101
+ text: string,
102
+ ): readonly AgentDefinitionEntry[] {
103
+ const parsed = parseRegistryFile(text, registry);
104
+ for (const diagnostic of parsed.diagnostics) {
105
+ if (diagnostic.scope !== "file") continue;
106
+ const reason = parseReason(diagnostic.message);
107
+ if (reason === undefined) continue;
108
+ throw unresolvable(request, `${registry} did not parse: ${reason}`, reason);
109
+ }
110
+ return parsed.entries;
111
+ }
112
+
113
+ function parseReason(message: string): string | undefined {
114
+ if (message.includes("is not valid JSON")) return "is not valid JSON";
115
+ if (message.includes("must contain a JSON object")) return "root is not an object";
116
+ if (message.includes('"agents" must be an array')) return "agents is not an array";
117
+ return undefined;
118
+ }
119
+
120
+ /** Steps 5 to 8: the target file, the import, the export, the predicate. */
121
+ async function loadEntry(
122
+ request: ResolveRequest,
123
+ target: string,
124
+ exportName: string,
125
+ ): Promise<SpawnableDefinition> {
126
+ if (!(await isFile(target))) {
127
+ throw unresolvable(request, targetTail(target, "file not found"), "file not found");
128
+ }
129
+ let namespace: unknown;
130
+ try {
131
+ namespace = await import(target);
132
+ } catch (cause) {
133
+ throw failed(request, targetTail(target, "module threw on import"), cause);
134
+ }
135
+ if (typeof namespace !== "object" || namespace === null || !(exportName in namespace)) {
136
+ const reason = `export "${exportName}" not found`;
137
+ throw unresolvable(request, targetTail(target, reason), reason);
138
+ }
139
+ const value = Reflect.get(namespace, exportName);
140
+ if (!isSpawnableDefinition(value)) {
141
+ const reason = `export "${exportName}" is not a Spawnable Definition`;
142
+ throw unresolvable(request, targetTail(target, reason), reason);
143
+ }
144
+ return value;
145
+ }
146
+
147
+ async function isFile(target: string): Promise<boolean> {
148
+ try {
149
+ return (await stat(target)).isFile();
150
+ } catch {
151
+ return false;
152
+ }
153
+ }
154
+
155
+ function prefix(request: ResolveRequest): string {
156
+ return `$yaag.${request.scope}.importAgent("${request.name}")`;
157
+ }
158
+
159
+ function notFound(request: ResolveRequest, tail: string): YaagError {
160
+ return new YaagError("CATALOG_ENTRY_NOT_FOUND", `${prefix(request)}: ${tail}`);
161
+ }
162
+
163
+ /**
164
+ * An UNRESOLVABLE whose cause is a plain `Error` with the reason fragment as
165
+ * its message, and nothing else (decision 10).
166
+ */
167
+ function unresolvable(request: ResolveRequest, tail: string, reason: string): YaagError {
168
+ return failed(request, tail, new Error(reason));
169
+ }
170
+
171
+ /** An UNRESOLVABLE whose cause is the failure it wraps, for step 6. */
172
+ function failed(request: ResolveRequest, tail: string, cause: unknown): YaagError {
173
+ return new YaagError(
174
+ "CATALOG_ENTRY_UNRESOLVABLE",
175
+ `${prefix(request)}: ${tail}`,
176
+ undefined,
177
+ undefined,
178
+ cause,
179
+ );
180
+ }
181
+
182
+ function targetTail(target: string, reason: string): string {
183
+ return `${target} did not resolve: ${reason}`;
184
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The Catalog Resolve author contract (ADR-0053): what `$yaag.<scope>.importAgent`
3
+ * returns, and the options `createYaagGlobal` takes.
4
+ *
5
+ * Type-only. It is the one file in this directory that names a type from
6
+ * outside it: `SpawnableDefinition` is the union of the two Definition shapes,
7
+ * and both already sit in the emitted author tree (ADR-0045).
8
+ */
9
+ import type { AgentDefinition } from "../agent/define-agent.ts";
10
+ import type { ProfiledDefinition } from "../profile/use-profile.ts";
11
+
12
+ /** An Agent Definition or a Profiled Definition: what a Catalog Resolve gives back. */
13
+ export type SpawnableDefinition = AgentDefinition | ProfiledDefinition;
14
+
15
+ /** One Catalog scope, global or project. */
16
+ export interface CatalogScope {
17
+ /** Resolves the Spawnable Definition registered under `name` in this scope. */
18
+ importAgent(name: string): Promise<SpawnableDefinition>;
19
+ }
20
+
21
+ /** The `$yaag` global an Orchestration Program reads. */
22
+ export interface YaagGlobal {
23
+ readonly global: CatalogScope;
24
+ readonly project: CatalogScope;
25
+ }
26
+
27
+ /** What `createYaagGlobal` needs to build the two scopes. */
28
+ export interface YaagGlobalOptions {
29
+ /** Absolute path of the global Registry File. The file may not exist. */
30
+ readonly globalRegistryPath: string;
31
+ /** Absolute path of the project Registry File. `undefined` when the Run has no Program Directory. */
32
+ readonly projectRegistryPath: string | undefined;
33
+ }
@@ -66,4 +66,7 @@ export type YaagErrorCode =
66
66
  | "RUN_STOPPED" // the Run's abort signal fired before the program completed
67
67
  | "WORKTREE_REFUSED" // base cwd is not a clean Git repository
68
68
  | "MODEL_RESOLUTION_FAILED" // the resolver gave up, or every candidate failed; carries the history
69
+ | "CATALOG_ENTRY_NOT_FOUND" // no Registry File, no Program Directory, or no entry with that name (ADR-0053)
70
+ | "CATALOG_ENTRY_AMBIGUOUS" // two or more registry entries carry that name
71
+ | "CATALOG_ENTRY_UNRESOLVABLE" // the entry exists but did not yield a Spawnable Definition
69
72
  | "SPAWN_FAILED"; // the spawn was refused, e.g. a guarded system prompt, a broken tool contract or a startup timeout
@@ -3,11 +3,19 @@
3
3
  * Program author reads (ADR-0045).
4
4
  *
5
5
  * Every file here is type-only and imports nothing outside this directory
6
- * except `typebox`. That keeps the declaration tree a workspace gets small.
7
- * Files inside this directory import each other directly.
6
+ * except `typebox`, with one exception: `catalog-resolve.ts` names
7
+ * `AgentDefinition` and `ProfiledDefinition`, type-only, because both already
8
+ * sit in the emitted author tree. That keeps the declaration tree a workspace
9
+ * gets small. Files inside this directory import each other directly.
8
10
  */
9
11
  export type { AgentPolicy } from "./agent-policy.ts";
10
12
  export type { AgentProgress, CompactionResult, TokenBreakdown } from "./agent-report.ts";
13
+ export type {
14
+ CatalogScope,
15
+ SpawnableDefinition,
16
+ YaagGlobal,
17
+ YaagGlobalOptions,
18
+ } from "./catalog-resolve.ts";
11
19
  export type {
12
20
  AskInvalidOutputOutcome,
13
21
  AskLimitKind,
package/src/errors.ts CHANGED
@@ -22,7 +22,12 @@ export type {
22
22
  YaagErrorCode,
23
23
  } from "./contract/index.ts";
24
24
 
25
- /** The single error class of the runtime (ADR-0003). */
25
+ /**
26
+ * The single error class of the runtime (ADR-0003).
27
+ *
28
+ * The fifth constructor parameter `cause` goes to `Error.prototype.cause`, so
29
+ * a wrapped failure keeps its origin.
30
+ */
26
31
  export class YaagError extends Error {
27
32
  readonly code: YaagErrorCode;
28
33
  /** Agent name, when the error concerns one. */
@@ -57,8 +62,9 @@ export class YaagError extends Error {
57
62
  | AskStalledOutcome
58
63
  | AskInvalidOutputOutcome
59
64
  | ModelResolutionOutcome,
65
+ cause?: unknown,
60
66
  ) {
61
- super(message);
67
+ super(message, { cause });
62
68
  this.name = "YaagError";
63
69
  this.code = code;
64
70
  if (agent !== undefined) this.agent = agent;
package/src/index.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  export type { AgentConfig, AgentDefinition } from "./agent/index.ts";
2
- export { agentDefinitionConfig, defineAgent, isAgentDefinition } from "./agent/index.ts";
2
+ export {
3
+ agentDefinitionConfig,
4
+ defineAgent,
5
+ isAgentDefinition,
6
+ isSpawnableDefinition,
7
+ } from "./agent/index.ts";
3
8
  export type {
4
9
  Cassette,
5
10
  CassetteAgent,
@@ -48,6 +53,7 @@ export {
48
53
  AGENT_DESCRIBE_TRANSCRIPT,
49
54
  agentDescribeArgv,
50
55
  CATALOG_FIXTURE,
56
+ createYaagGlobal,
51
57
  describedAgent,
52
58
  encodeAgentDescribe,
53
59
  filterCatalog,
package/src/public-api.ts CHANGED
@@ -12,6 +12,12 @@
12
12
 
13
13
  export type { AgentConfig, AgentDefinition } from "./agent/define-agent.ts";
14
14
  export { defineAgent } from "./agent/define-agent.ts";
15
+ export type {
16
+ CatalogScope,
17
+ SpawnableDefinition,
18
+ YaagGlobal,
19
+ YaagGlobalOptions,
20
+ } from "./contract/catalog-resolve.ts";
15
21
  export type {
16
22
  AgentPolicy,
17
23
  AskOptions,
@@ -1,7 +1,12 @@
1
1
  // `../agent/define-agent.ts` is a deep import on purpose: the author
2
2
  // declaration tree must not pull the `agent/` barrel (ADR-0045).
3
3
  import type { AgentDefinition } from "../agent/define-agent.ts";
4
- import type { Handle, SpawnOptions, SpawnOverrides } from "../contract/index.ts";
4
+ import type {
5
+ Handle,
6
+ SpawnableDefinition,
7
+ SpawnOptions,
8
+ SpawnOverrides,
9
+ } from "../contract/index.ts";
5
10
  import type { ProfiledDefinition } from "../profile/use-profile.ts";
6
11
 
7
12
  /** What an Orchestration Program is handed. */
@@ -20,6 +25,8 @@ export interface RunContext<Args = unknown> {
20
25
  spawn(options?: SpawnOptions): Promise<Handle>;
21
26
  spawn(definition: AgentDefinition, overrides?: SpawnOverrides): Promise<Handle>;
22
27
  spawn(profiled: ProfiledDefinition, overrides?: SpawnOverrides): Promise<Handle>;
28
+ /** Last on purpose: a union-typed value, e.g. what a Catalog Resolve gave back (ADR-0053). */
29
+ spawn(definition: SpawnableDefinition, overrides?: SpawnOverrides): Promise<Handle>;
23
30
  /**
24
31
  * The Profile this Run activated (ADR-0052). Defined when the program
25
32
  * declares Profiles, undefined otherwise.