@yaag/runtime 0.21.0 → 0.22.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.21.0",
3
+ "version": "0.22.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -45,7 +45,7 @@ export function profiledRequest(
45
45
  let thrown: unknown;
46
46
  let threw = false;
47
47
  try {
48
- result = factory(recorder.view);
48
+ result = factory({ profile: recorder.view });
49
49
  } catch (error) {
50
50
  threw = true;
51
51
  thrown = error;
@@ -23,11 +23,11 @@ export interface CheckpointEnvironment {
23
23
  * `$HOME/.local/state`. A relative `XDG_STATE_HOME` is ignored (XDG spec).
24
24
  */
25
25
  export function resolveCheckpointDirectory(env: CheckpointEnvironment = process.env): string {
26
- const override = env["YAAG_CHECKPOINT_DIR"];
26
+ const override = env.YAAG_CHECKPOINT_DIR;
27
27
  if (override !== undefined && override !== "") return override;
28
- const xdg = env["XDG_STATE_HOME"];
28
+ const xdg = env.XDG_STATE_HOME;
29
29
  if (xdg !== undefined && isAbsolute(xdg)) return join(xdg, CHECKPOINT_SUFFIX);
30
- const home = env["HOME"] !== undefined && env["HOME"] !== "" ? env["HOME"] : homedir();
30
+ const home = env.HOME !== undefined && env.HOME !== "" ? env.HOME : homedir();
31
31
  return join(home, ".local", "state", CHECKPOINT_SUFFIX);
32
32
  }
33
33
 
@@ -156,9 +156,9 @@ function asRegistryDocument(value: unknown): RegistryDocument | undefined {
156
156
  function toAgentEntry(element: unknown): AgentDefinitionEntry {
157
157
  const record = asRecord(element);
158
158
  return {
159
- file: text(record["file"]),
160
- exportName: text(record["exportName"]),
161
- name: text(record["name"]),
159
+ file: text(record.file),
160
+ exportName: text(record.exportName),
161
+ name: text(record.name),
162
162
  ...metadata(record),
163
163
  };
164
164
  }
@@ -166,7 +166,7 @@ function toAgentEntry(element: unknown): AgentDefinitionEntry {
166
166
  /** Builds a program entry from a possibly malformed element, repaired the same way. */
167
167
  function toProgramEntry(element: unknown): ProgramEntry {
168
168
  const record = asRecord(element);
169
- return { file: text(record["file"]), name: text(record["name"]), ...metadata(record) };
169
+ return { file: text(record.file), name: text(record.name), ...metadata(record) };
170
170
  }
171
171
 
172
172
  /** Keeps `description` when it is a string and keeps the string tags only. */
@@ -174,8 +174,8 @@ function metadata(record: Record<string, unknown>): {
174
174
  description?: string;
175
175
  tags?: string[];
176
176
  } {
177
- const description = record["description"];
178
- const tags = record["tags"];
177
+ const description = record.description;
178
+ const tags = record.tags;
179
179
  return {
180
180
  ...(typeof description === "string" ? { description } : {}),
181
181
  ...(Array.isArray(tags) ? { tags: tags.filter((tag) => typeof tag === "string") } : {}),
@@ -23,11 +23,11 @@ export const PROJECT_CONFIG_DIR = ".yaag";
23
23
  * `os.homedir()`.
24
24
  */
25
25
  export function resolveGlobalConfigDirectory(env: ConfigEnvironment = process.env): string {
26
- const override = env["YAAG_CONFIG_DIR"];
26
+ const override = env.YAAG_CONFIG_DIR;
27
27
  if (override !== undefined && override !== "") return override;
28
- const xdg = env["XDG_CONFIG_HOME"];
28
+ const xdg = env.XDG_CONFIG_HOME;
29
29
  if (xdg !== undefined && isAbsolute(xdg)) return join(xdg, "yaag");
30
- const home = env["HOME"] !== undefined && env["HOME"] !== "" ? env["HOME"] : homedir();
30
+ const home = env.HOME !== undefined && env.HOME !== "" ? env.HOME : homedir();
31
31
  return join(home, ".config", "yaag");
32
32
  }
33
33
 
package/src/index.ts CHANGED
@@ -120,11 +120,16 @@ export type {
120
120
  ModelCandidate,
121
121
  ProfileBuilder,
122
122
  ProfiledDefinition,
123
+ ProfileFactory,
124
+ ProfileInput,
123
125
  Profiles,
126
+ ProfilesConfig,
124
127
  ProfilesSnapshot,
125
128
  ProfileView,
126
129
  Role,
127
- RoleBinding,
130
+ RoleLookup,
131
+ RoleMap,
132
+ RoleNamesOf,
128
133
  } from "./profile/index.ts";
129
134
  // `selectProfile`, `profileViewRecorder` and `profiledDefinitionFactory` stay
130
135
  // on `profile/index.ts`: the Run and the spawn gate use them, and no consumer
@@ -1,15 +1,25 @@
1
1
  import { lowerCandidate, type ModelCandidate } from "./lowering.ts";
2
+ import {
3
+ ROLE_LOOKUP_KEY,
4
+ type Role,
5
+ type RoleLookup,
6
+ type RoleMap,
7
+ roleMap,
8
+ roleOf,
9
+ } from "./role.ts";
2
10
 
3
11
  export type { ModelCandidate } from "./lowering.ts";
12
+ export type { Role, RoleLookup, RoleMap } from "./role.ts";
4
13
 
5
- /** Not exported, so a Role is opaque and traceable to the Profiles value that made it. */
6
- const roleSymbol = Symbol("yaag.role");
7
14
  /** Not exported, so only this directory reaches the declaration state. */
8
15
  const stateSymbol = Symbol("yaag.profiles");
9
16
 
10
- /** A declared Role. Opaque: only `bind()` reads it. */
11
- export interface Role {
12
- readonly [roleSymbol]: { readonly owner: ProfilesState; readonly name: string };
17
+ /** Which Profiles value made a Role. A Role from another value may not be bound. */
18
+ const roleOwners = new WeakMap<Role, ProfilesState>();
19
+
20
+ /** What `defineProfiles` takes: the Role names, in declaration order. */
21
+ export interface ProfilesConfig<Name extends string> {
22
+ readonly roles: readonly Name[];
13
23
  }
14
24
 
15
25
  /** Declares one Profile: its default provider and its Role Bindings. */
@@ -30,15 +40,36 @@ export interface BindingBuilder extends ProfileBuilder {
30
40
  fallback(spec: ModelCandidate): BindingBuilder;
31
41
  }
32
42
 
33
- /** The value `defineProfiles()` returns and `defineRun({ profiles })` seals. */
43
+ /**
44
+ * The value `defineProfiles()` returns and `defineRun({ profiles })` seals.
45
+ * Not generic: a consumer takes any Profiles value. `defineProfiles` returns
46
+ * the `TypedProfiles` refinement, whose `role` keys are the declared names.
47
+ */
34
48
  export interface Profiles {
35
- /** Declares a Role. A duplicate name throws a TypeError. */
36
- role(name: string): Role;
49
+ /**
50
+ * The declared Roles, by name. An undeclared name throws a TypeError.
51
+ * The bound fields of a Role read the default Profile: the sealed default,
52
+ * else the first registered Profile.
53
+ */
54
+ readonly role: RoleLookup;
37
55
  /** Declares a Profile. A duplicate id throws a TypeError. */
38
56
  register(profile: { readonly id: string }): ProfileBuilder;
39
57
  readonly [stateSymbol]: ProfilesState;
40
58
  }
41
59
 
60
+ /** A Profiles value whose `role` map is typed after the declared names. */
61
+ export type TypedProfiles<Name extends string> = Profiles & { readonly role: RoleMap<Name> };
62
+
63
+ /**
64
+ * The Role names a Profiles type declares: the keys of its `role` map minus
65
+ * the lookup method. `string` for the plain, untyped `Profiles`.
66
+ */
67
+ export type RoleNamesOf<P extends Profiles> = [
68
+ Exclude<keyof P["role"], typeof ROLE_LOOKUP_KEY>,
69
+ ] extends [never]
70
+ ? string
71
+ : Exclude<keyof P["role"], typeof ROLE_LOOKUP_KEY> & string;
72
+
42
73
  /** The sealed, frozen picture of a Profiles value: what describe prints. */
43
74
  export interface ProfilesSnapshot {
44
75
  /** The resolved default: `defaultProfile` when given, else the first registered id. */
@@ -62,7 +93,7 @@ export interface ProfileRecord {
62
93
  }
63
94
 
64
95
  export interface ProfilesState {
65
- readonly roles: string[];
96
+ readonly roles: readonly string[];
66
97
  readonly profiles: Map<string, ProfileRecord>;
67
98
  sealed: boolean;
68
99
  snapshot?: ProfilesSnapshot;
@@ -81,14 +112,14 @@ function assertUnsealed(state: ProfilesState, call: string): void {
81
112
  }
82
113
 
83
114
  function roleName(state: ProfilesState, role: Role): string {
84
- const identity = typeof role === "object" && role !== null ? role[roleSymbol] : undefined;
85
- if (identity === undefined) {
86
- throw new TypeError("bind: expected a Role from profiles.role(name)");
115
+ const owner = typeof role === "object" && role !== null ? roleOwners.get(role) : undefined;
116
+ if (owner === undefined) {
117
+ throw new TypeError("bind: expected a Role from profiles.role.<name>");
87
118
  }
88
- if (identity.owner !== state) {
89
- throw new TypeError(`bind: Role "${identity.name}" belongs to another Profiles value`);
119
+ if (owner !== state) {
120
+ throw new TypeError(`bind: Role "${role.roleName}" belongs to another Profiles value`);
90
121
  }
91
- return identity.name;
122
+ return role.roleName;
92
123
  }
93
124
 
94
125
  function bindingBuilder(
@@ -145,23 +176,87 @@ function profileBuilder(state: ProfilesState, profile: ProfileRecord): ProfileBu
145
176
  return Object.freeze(builder);
146
177
  }
147
178
 
179
+ /** The Profile a declared Role reads: the sealed default, else the first registered. */
180
+ function defaultProfile(state: ProfilesState): ProfileRecord {
181
+ const id = state.snapshot?.default ?? state.profiles.keys().next().value;
182
+ const profile = id === undefined ? undefined : state.profiles.get(id);
183
+ if (profile === undefined) {
184
+ throw new TypeError("role: no Profile is registered — call register({ id }) first");
185
+ }
186
+ return profile;
187
+ }
188
+
189
+ /** The lowered candidates a declared Role reads from the default Profile. */
190
+ function defaultCandidates(state: ProfilesState, name: string): readonly string[] {
191
+ const profile = defaultProfile(state);
192
+ const binding = profile.bindings.get(name);
193
+ if (binding === undefined || !binding.hasModel) {
194
+ throw new TypeError(`role: Role "${name}" has no model() on Profile "${profile.id}"`);
195
+ }
196
+ return binding.candidates;
197
+ }
198
+
199
+ function declaredRoles(state: ProfilesState): RoleMap<string> {
200
+ const cache = new Map<string, Role>();
201
+ return roleMap({
202
+ names: state.roles,
203
+ roleOf(name) {
204
+ let role = cache.get(name);
205
+ if (role === undefined) {
206
+ role = roleOf(name, () => defaultCandidates(state, name));
207
+ roleOwners.set(role, state);
208
+ cache.set(name, role);
209
+ }
210
+ return role;
211
+ },
212
+ missing(name) {
213
+ throw new TypeError(
214
+ `role: Role "${name}" is not declared — declared: ${state.roles.join(", ")}`,
215
+ );
216
+ },
217
+ });
218
+ }
219
+
220
+ function checkRoleNames(roles: readonly string[]): void {
221
+ if (!Array.isArray(roles)) {
222
+ throw new TypeError("defineProfiles: roles must be an array of Role names");
223
+ }
224
+ const seen = new Set<string>();
225
+ for (const name of roles) {
226
+ if (typeof name !== "string" || name.trim() === "") {
227
+ throw new TypeError("defineProfiles: a Role name must be a non-empty string");
228
+ }
229
+ if (name === ROLE_LOOKUP_KEY) {
230
+ throw new TypeError(
231
+ `defineProfiles: "${ROLE_LOOKUP_KEY}" is reserved and cannot name a Role`,
232
+ );
233
+ }
234
+ if (seen.has(name)) throw new TypeError(`defineProfiles: Role "${name}" is declared twice`);
235
+ seen.add(name);
236
+ }
237
+ }
238
+
148
239
  /**
149
240
  * Declares the Profiles of an Orchestration Program (ADR-0052).
150
241
  *
242
+ * The Role names come from `config.roles`, so `profiles.role.<Name>` is typed.
151
243
  * Every builder method throws a TypeError at the call that breaks a
152
244
  * declaration rule, and every method throws once `defineRun` sealed the value.
153
245
  */
154
- export function defineProfiles(): Profiles {
155
- const state: ProfilesState = { roles: [], profiles: new Map(), sealed: false };
156
- const profiles: Profiles = {
157
- role(name: string): Role {
158
- assertUnsealed(state, "role");
159
- if (state.roles.includes(name)) {
160
- throw new TypeError(`role: Role "${name}" is already declared`);
161
- }
162
- state.roles.push(name);
163
- return Object.freeze({ [roleSymbol]: { owner: state, name } });
164
- },
246
+ export function defineProfiles<const Name extends string>(
247
+ config: ProfilesConfig<Name>,
248
+ ): TypedProfiles<Name> {
249
+ if (typeof config !== "object" || config === null) {
250
+ throw new TypeError("defineProfiles: expected a config object { roles }");
251
+ }
252
+ checkRoleNames(config.roles);
253
+ const state: ProfilesState = {
254
+ roles: Object.freeze([...config.roles]),
255
+ profiles: new Map(),
256
+ sealed: false,
257
+ };
258
+ const profiles: TypedProfiles<Name> = {
259
+ role: declaredRoles(state) as RoleMap<Name>,
165
260
  register(profile: { readonly id: string }): ProfileBuilder {
166
261
  assertUnsealed(state, "register");
167
262
  const { id } = profile;
@@ -7,15 +7,24 @@ export type {
7
7
  ModelCandidate,
8
8
  ProfileBuilder,
9
9
  Profiles,
10
+ ProfilesConfig,
10
11
  ProfilesSnapshot,
11
12
  Role,
13
+ RoleLookup,
14
+ RoleMap,
15
+ RoleNamesOf,
12
16
  } from "./define-profiles.ts";
13
17
  export { defineProfiles } from "./define-profiles.ts";
14
18
  export type { ActiveProfile, ProfileViewRecorder } from "./profile-view.ts";
15
19
  export { profileViewRecorder, roleNotFoundMessage } from "./profile-view.ts";
16
20
  export { profilesSnapshot, sealProfiles } from "./seal.ts";
17
21
  export { selectProfile } from "./select-profile.ts";
18
- export type { ProfiledDefinition, ProfileView, RoleBinding } from "./use-profile.ts";
22
+ export type {
23
+ ProfiledDefinition,
24
+ ProfileFactory,
25
+ ProfileInput,
26
+ ProfileView,
27
+ } from "./use-profile.ts";
19
28
  export {
20
29
  isProfiledDefinition,
21
30
  profiledDefinitionFactory,
@@ -1,10 +1,23 @@
1
1
  import type { ThinkingLevel } from "../contract/index.ts";
2
+ // Deep import on purpose: this file is reachable from `public-api.ts`, and the
3
+ // `model/` index would pull the whole resolution tree into the vendored
4
+ // declarations (ADR-0045).
5
+ import { isThinkingLevel } from "../model/thinking-level.ts";
2
6
 
3
7
  /** One model candidate of a Role Binding, before lowering (ADR-0052). */
4
8
  export type ModelCandidate =
5
9
  | string
6
10
  | { readonly provider?: string; readonly name: string; readonly thinking?: ThinkingLevel };
7
11
 
12
+ /** The parts of one lowered candidate, as a Role reads them back. */
13
+ export interface CandidateParts {
14
+ /** The lowered pattern string, as `AgentConfig.model` takes it. */
15
+ readonly pattern: string;
16
+ readonly provider: string | undefined;
17
+ readonly modelName: string;
18
+ readonly thinking: ThinkingLevel | undefined;
19
+ }
20
+
8
21
  function isCandidateObject(
9
22
  spec: ModelCandidate,
10
23
  ): spec is { provider?: string; name: string; thinking?: ThinkingLevel } {
@@ -35,3 +48,20 @@ export function lowerCandidate(spec: ModelCandidate, defaultProvider: string | u
35
48
  const model = prefix === undefined ? name : `${prefix}/${name}`;
36
49
  return thinking === undefined ? model : `${model}:${thinking}`;
37
50
  }
51
+
52
+ /**
53
+ * Splits one lowered pattern into its parts. The inverse of `lowerCandidate`.
54
+ *
55
+ * The thinking suffix is the tail after the last `:` when that tail is a
56
+ * thinking level. The provider is the head before the first `/`. A pattern
57
+ * with no `/` has no provider.
58
+ */
59
+ export function parseCandidate(pattern: string): CandidateParts {
60
+ const separator = pattern.lastIndexOf(":");
61
+ const tail = separator > 0 ? pattern.slice(separator + 1) : undefined;
62
+ const thinking = isThinkingLevel(tail) ? tail : undefined;
63
+ const model = thinking === undefined ? pattern : pattern.slice(0, separator);
64
+ const slash = model.indexOf("/");
65
+ if (slash <= 0) return { pattern, provider: undefined, modelName: model, thinking };
66
+ return { pattern, provider: model.slice(0, slash), modelName: model.slice(slash + 1), thinking };
67
+ }
@@ -4,7 +4,8 @@
4
4
  */
5
5
  import { YaagError } from "../errors.ts";
6
6
  import type { ProfilesSnapshot } from "./define-profiles.ts";
7
- import type { ProfileView, RoleBinding } from "./use-profile.ts";
7
+ import { type Role, roleMap, roleOf } from "./role.ts";
8
+ import type { ProfileView } from "./use-profile.ts";
8
9
 
9
10
  /** The Profile a Run activated, plus the sealed bindings it reads. */
10
11
  export interface ActiveProfile {
@@ -36,21 +37,31 @@ export function roleNotFoundMessage(name: string): string {
36
37
  return `spawn: Role "${name}" is not declared by this program`;
37
38
  }
38
39
 
39
- /** Builds a recording view of one active Profile. Each view serves one spawn. */
40
+ /**
41
+ * Builds a recording view of one active Profile. Each view serves one spawn.
42
+ * A read is one access of `view.role.<name>` or `view.role.ofName(name)`.
43
+ */
40
44
  export function profileViewRecorder(active: ActiveProfile): ProfileViewRecorder {
41
45
  const reads: string[] = [];
42
46
  const failures: string[] = [];
43
- const view: ProfileView = {
44
- id: active.id,
45
- role(name: string): RoleBinding {
46
- const candidates = active.bindings[name];
47
- if (candidates === undefined) {
48
- failures.push(name);
49
- throw new YaagError("ROLE_NOT_FOUND", roleNotFoundMessage(name));
50
- }
47
+ const roles = new Map<string, Role>();
48
+ const names = Object.keys(active.bindings);
49
+ const role = roleMap({
50
+ names,
51
+ roleOf(name) {
51
52
  reads.push(name);
52
- return Object.freeze({ model: Object.freeze([...candidates]) });
53
+ let known = roles.get(name);
54
+ if (known === undefined) {
55
+ known = roleOf(name, () => active.bindings[name] ?? []);
56
+ roles.set(name, known);
57
+ }
58
+ return known;
59
+ },
60
+ missing(name) {
61
+ failures.push(name);
62
+ throw new YaagError("ROLE_NOT_FOUND", roleNotFoundMessage(name));
53
63
  },
54
- };
55
- return { view: Object.freeze(view), reads, failures };
64
+ });
65
+ const view: ProfileView = Object.freeze({ id: active.id, role });
66
+ return { view, reads, failures };
56
67
  }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * A Role as an author reads it: its name, and the model the active Profile
3
+ * binds to it (ADR-0052). One shape serves `profiles.role.<Name>` and the
4
+ * `profile.role.<Name>` a `useProfile` factory sees.
5
+ */
6
+ import type { ThinkingLevel } from "../contract/index.ts";
7
+ import { parseCandidate } from "./lowering.ts";
8
+
9
+ /**
10
+ * A declared Role. `roleName` is always readable. The other fields read the
11
+ * Role Binding of the active Profile, and throw a TypeError when no Profile
12
+ * is active.
13
+ */
14
+ export interface Role<Name extends string = string> {
15
+ readonly roleName: Name;
16
+ /** Every lowered model candidate of the binding, in order. Fits `AgentConfig.model`. */
17
+ readonly model: readonly string[];
18
+ /** Provider of the first candidate; undefined when the candidate names none. */
19
+ readonly provider: string | undefined;
20
+ /** Model name of the first candidate, without provider and thinking suffix. */
21
+ readonly modelName: string;
22
+ /** Thinking level of the first candidate; undefined when the candidate names none. */
23
+ readonly thinking: ThinkingLevel | undefined;
24
+ }
25
+
26
+ /** Looks a Role up by a name known only at run time. */
27
+ export interface RoleLookup {
28
+ /** The Role of that name. An undeclared name throws. */
29
+ ofName(name: string): Role;
30
+ }
31
+
32
+ /**
33
+ * The Roles of a Profiles value, keyed by name. With literal names every key
34
+ * is typed. With `string` only `ofName()` is typed, so a dynamic name reads
35
+ * through it.
36
+ */
37
+ export type RoleMap<Name extends string = string> = (string extends Name
38
+ ? unknown
39
+ : { readonly [K in Name]: Role<K> }) &
40
+ RoleLookup;
41
+
42
+ /** The one key of a RoleMap that is not a Role, so a Role may not take it. */
43
+ export const ROLE_LOOKUP_KEY = "ofName";
44
+
45
+ /** How `roleOf` reaches the binding: it returns the lowered candidates, or throws. */
46
+ export type CandidatesOf = () => readonly string[];
47
+
48
+ /** Builds one Role whose bound fields read `candidates()` on every access. */
49
+ export function roleOf<Name extends string>(roleName: Name, candidates: CandidatesOf): Role<Name> {
50
+ const first = (): string => {
51
+ const [head] = candidates();
52
+ if (head === undefined) {
53
+ throw new TypeError(`Role "${roleName}": the binding has no model candidate`);
54
+ }
55
+ return head;
56
+ };
57
+ const role: Role<Name> = {
58
+ roleName,
59
+ get model(): readonly string[] {
60
+ return Object.freeze([...candidates()]);
61
+ },
62
+ get provider(): string | undefined {
63
+ return parseCandidate(first()).provider;
64
+ },
65
+ get modelName(): string {
66
+ return parseCandidate(first()).modelName;
67
+ },
68
+ get thinking(): ThinkingLevel | undefined {
69
+ return parseCandidate(first()).thinking;
70
+ },
71
+ };
72
+ return Object.freeze(role);
73
+ }
74
+
75
+ /** What `roleMap` needs: the declared names, and how to make or refuse a Role. */
76
+ export interface RoleMapOptions {
77
+ readonly names: readonly string[];
78
+ /** Called for a declared name. May cache: the map itself does not. */
79
+ readonly roleOf: (name: string) => Role;
80
+ /** Called for an undeclared name. It must throw. */
81
+ readonly missing: (name: string) => never;
82
+ }
83
+
84
+ /**
85
+ * Builds a RoleMap over a Proxy, so `map.Unknown` throws instead of yielding
86
+ * undefined. Symbol keys and `ofName` bypass the lookup.
87
+ */
88
+ export function roleMap(options: RoleMapOptions): RoleMap<string> {
89
+ const { names, roleOf: make, missing } = options;
90
+ const lookup = (name: string): Role => (names.includes(name) ? make(name) : missing(name));
91
+ // Not frozen: a Proxy over a non-extensible target may not report extra keys.
92
+ const target: RoleLookup = { ofName: lookup };
93
+ return new Proxy(target, {
94
+ get(base, key) {
95
+ if (typeof key !== "string") return undefined;
96
+ if (key === ROLE_LOOKUP_KEY) return base.ofName;
97
+ return lookup(key);
98
+ },
99
+ has(_base, key) {
100
+ return key === ROLE_LOOKUP_KEY || (typeof key === "string" && names.includes(key));
101
+ },
102
+ ownKeys() {
103
+ return [ROLE_LOOKUP_KEY, ...names];
104
+ },
105
+ getOwnPropertyDescriptor(base, key) {
106
+ if (key === ROLE_LOOKUP_KEY) return Object.getOwnPropertyDescriptor(base, key);
107
+ if (typeof key !== "string" || !names.includes(key)) return undefined;
108
+ return { value: make(key), enumerable: true, configurable: true, writable: false };
109
+ },
110
+ set() {
111
+ return false;
112
+ },
113
+ deleteProperty() {
114
+ return false;
115
+ },
116
+ });
117
+ }
@@ -7,23 +7,35 @@
7
7
  */
8
8
  // `../agent/define-agent.ts` is a deep import on purpose, as `run-context.ts` does.
9
9
  import type { AgentConfig } from "../agent/define-agent.ts";
10
+ import type { Profiles, RoleNamesOf } from "./define-profiles.ts";
11
+ import type { RoleMap } from "./role.ts";
10
12
 
11
- /** What one Profile gives one Role. Today only `model`; later more Agent policy. */
12
- export type RoleBinding = Partial<AgentConfig>;
13
-
14
- /** The active Profile as a factory sees it. Every `role()` read is recorded. */
15
- export interface ProfileView {
13
+ /** The active Profile as a factory sees it. Every Role read is recorded. */
14
+ export interface ProfileView<Name extends string = string> {
16
15
  readonly id: string;
17
- /** The Role Binding of this Profile. An undeclared name throws ROLE_NOT_FOUND. */
18
- role(name: string): RoleBinding;
16
+ /**
17
+ * The Roles of this Profile, by name. `role.<Name>` and `role.ofName(name)`
18
+ * throw ROLE_NOT_FOUND for an undeclared name.
19
+ */
20
+ readonly role: RoleMap<Name>;
21
+ }
22
+
23
+ /** What a `useProfile` factory receives. */
24
+ export interface ProfileInput<Name extends string = string> {
25
+ readonly profile: ProfileView<Name>;
19
26
  }
20
27
 
28
+ /** The factory of a Profiled Definition: it builds an AgentConfig from the active Profile. */
29
+ export type ProfileFactory<Name extends string = string> = (
30
+ input: ProfileInput<Name>,
31
+ ) => AgentConfig;
32
+
21
33
  /** Not exported, so the factory is unreachable outside this directory. */
22
34
  const profiled = Symbol("yaag.profiled");
23
35
 
24
36
  /** Opaque, frozen result of `useProfile`. It is not an Agent Definition. */
25
37
  export interface ProfiledDefinition {
26
- readonly [profiled]: (profile: ProfileView) => AgentConfig;
38
+ readonly [profiled]: ProfileFactory;
27
39
  }
28
40
 
29
41
  /**
@@ -32,12 +44,20 @@ export interface ProfiledDefinition {
32
44
  * The factory runs once per spawn, with a view of the Profile the Run
33
45
  * activated. Its result passes through `defineAgent`, so the ordinary
34
46
  * definition rules still hold.
47
+ *
48
+ * `useProfile<typeof profiles>(...)` types `profile.role.<Name>` after the
49
+ * declared names. Without the type argument, read a dynamic name through
50
+ * `profile.role.ofName(name)`.
35
51
  */
36
- export function useProfile(factory: (profile: ProfileView) => AgentConfig): ProfiledDefinition {
52
+ export function useProfile<P extends Profiles = Profiles>(
53
+ factory: ProfileFactory<RoleNamesOf<P>>,
54
+ ): ProfiledDefinition {
37
55
  if (typeof factory !== "function") {
38
- throw new TypeError("useProfile: expected a factory function (profile) => AgentConfig");
56
+ throw new TypeError("useProfile: expected a factory function ({ profile }) => AgentConfig");
39
57
  }
40
- return Object.freeze({ [profiled]: factory });
58
+ // The view is a Proxy that serves every declared name, so the typed factory
59
+ // and the untyped one see the same runtime value.
60
+ return Object.freeze({ [profiled]: factory as unknown as ProfileFactory });
41
61
  }
42
62
 
43
63
  /** True only for values produced by `useProfile`. */
@@ -49,7 +69,7 @@ export function isProfiledDefinition(value: unknown): value is ProfiledDefinitio
49
69
  * Recovers the factory behind a Profiled Definition.
50
70
  * Throws a TypeError when the value did not come from `useProfile`.
51
71
  */
52
- export function profiledDefinitionFactory(value: unknown): (profile: ProfileView) => AgentConfig {
72
+ export function profiledDefinitionFactory(value: unknown): ProfileFactory {
53
73
  if (!isProfiledDefinition(value)) {
54
74
  throw new TypeError("not a Profiled Definition — build it with useProfile(factory)");
55
75
  }
package/src/public-api.ts CHANGED
@@ -28,13 +28,18 @@ export type {
28
28
  ModelCandidate,
29
29
  ProfileBuilder,
30
30
  Profiles,
31
+ ProfilesConfig,
31
32
  Role,
33
+ RoleLookup,
34
+ RoleMap,
35
+ RoleNamesOf,
32
36
  } from "./profile/define-profiles.ts";
33
37
  export { defineProfiles } from "./profile/define-profiles.ts";
34
38
  export type {
35
39
  ProfiledDefinition,
40
+ ProfileFactory,
41
+ ProfileInput,
36
42
  ProfileView,
37
- RoleBinding,
38
43
  } from "./profile/use-profile.ts";
39
44
  export { isProfiledDefinition, useProfile } from "./profile/use-profile.ts";
40
45
  export { prompt } from "./prompt/prompt.ts";