Skip to content

Commit 542be39

Browse files
committed
feat(souls): build the gmi() persona from the soul's front matter
Signed-off-by: jddunn <[email protected]>
1 parent 0ec580c commit 542be39

3 files changed

Lines changed: 77 additions & 30 deletions

File tree

‎docs/GMI.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,15 +106,16 @@ Every profile keeps the reasoning trace. Sentiment tracking scores each user tur
106106

107107
| Persona field | From |
108108
|---|---|
109-
| `id`, `name`, `description` | A slug of `name` (an id of its own for an agent with no name); `name`, or `Agent`; the first line of `instructions`, or the name |
110-
| `baseSystemPrompt` | The system prompt `agent()` sends ([`buildSystemPrompt()`](https://github.com/framerslab/agentos/blob/master/src/api/agent.ts): the soul file's body and style, `instructions`, the name line, the personality description, `skills`), or the joined `systemBlocks`; with `learning` on, without the personality description, which a GMI given a learner session (`GMIBaseConfig.learning`) sends as a system prompt of its own on each turn the session prepares, and renders itself from the persona's traits (`GMIBaseConfig.personaTraits`) on a turn it does not, as `gmi()` gives its GMIs both; a host that builds a GMI from this persona gives it both for the section on every turn, and a GMI with neither sends none ([Learning](#learning)) |
111-
| `personalityTraits` | `personality`, as HEXACO traits |
109+
| `id`, `name`, `description` | With a soul: the soul's `agentId`, else the slug of its `name`, else a slug of the agent's `name` (an id derived from the soul's text when it has none of these); `name`, else the soul's `name`, else `Agent`; the soul's `role`, else the first line of `instructions`, else the name. With no soul: a slug of `name` (an id of its own for an agent with no name); `name`, or `Agent`; the first line of `instructions`, or the name |
110+
| `baseSystemPrompt` | The system prompt `agent()` sends ([`buildSystemPrompt()`](https://github.com/framerslab/agentos/blob/master/src/api/agent.ts): the soul file's body and style, `instructions`, the name line, the personality description, `skills`), or the joined `systemBlocks`; with `learning` on or a persona that has traits, without the personality description, which a GMI given a learner session (`GMIBaseConfig.learning`) sends as a system prompt of its own on each turn the session prepares, and renders itself from the persona's traits (`GMIBaseConfig.personaTraits`) on a turn it does not, as `gmi()` gives its GMIs both; a host that builds a GMI from this persona gives it both for the section on every turn, and a GMI with neither sends none ([Learning](#learning)) |
111+
| `personalityTraits` | `personality`, else the soul's `hexaco`, as HEXACO traits |
112+
| `hardLimits`, `moodAdaptation`, `reasoningTraceConfig`, `metadata` | The soul's `hardLimits`, `defaultMood` and `allowedMoods`, `reasoningTrace` and `metadata`; a front matter `voice` or `avatar` is left out with one `soul.field_ignored` log line |
112113
| `defaultProviderId`, `defaultModelId` | `provider` and `model`, resolved as `generateText()` resolves them |
113114
| `defaultModelCompletionOptions` | `maxTokens` (or `controls.maxTotalTokens`), `controls.maxDurationMs` as `requestTimeout`, `thinking`, `effort`, `customModelParams`, `cache`; nothing else, so the provider's default temperature applies ([Completion options](#completion-options)) |
114115
| `allowedCapabilities` | The `requiredCapabilities` of the agent's tools |
115116
| `sentimentTracking`, `metaPrompts` | The profile |
116117

117-
A soul file's front matter is not applied, and the persona carries no `hardLimits`, so the "Hard limits" block ([Guardrails](./safety/GUARDRAILS_USAGE.md#hard-limits-in-the-persona)) is not in this path's prompt. What a soul gives each path (the prompt, the memory index, the front matter, recall, the `read_memory_page` tool and the wiki compile) is tabled in [Soul Files](./SOUL_FILES.md#what-applies-on-each-path). The chain-of-thought instruction (`chainOfThought`, on by default) goes first in the system prompt of each model call that offers tools, as `generateText()` puts it; a structured send's calls offer no tools and carry no such instruction, nor do the calls of a seat's turn whose tool names leave none. `onBeforeGeneration` receives the tool definitions the call offers: none on a structured send's calls, and on a seat's turn only the tools its tool names allow.
118+
A soul file's front matter is applied through the loader's one mapping, so the "Hard limits" block ([Guardrails](./safety/GUARDRAILS_USAGE.md#hard-limits-in-the-persona)) closes this path's prompt, after `systemBlocks` text too. Guardrails, RAG and approval settings are accepted and not applied on this path, with one warning line at construction. What a soul gives each path (the prompt, the memory index, the front matter, recall, the `read_memory_page` tool and the wiki compile) is tabled in [Soul Files](./SOUL_FILES.md#what-applies-on-each-path). The chain-of-thought instruction (`chainOfThought`, on by default) goes first in the system prompt of each model call that offers tools, as `generateText()` puts it; a structured send's calls offer no tools and carry no such instruction, nor do the calls of a seat's turn whose tool names leave none. `onBeforeGeneration` receives the tool definitions the call offers: none on a structured send's calls, and on a seat's turn only the tools its tool names allow.
118119

119120
**Tools and model calls.** The agent's `tools` run through a tool orchestrator of the agent's own, with capability checks off; the built-in `getCurrentDateTime` tool is left out, so an agent without tools offers the model none. `maxSteps` (5 by default) is each turn's tool-loop limit. Each GMI calls the model through a [completion gateway](#model-calls-through-a-completion-gateway) built from `apiKey`, `baseUrl`, `fallbackProviders`, `policyTier`, `router`, `routerParams` and `hostPolicy`, and the agent's `onFallback(error, provider)` is called on each fallback. The fallback guarantee is the gateway's: a hop that cannot start, or an attempt that fails with a retryable error before any output, moves to the next hop, and a step that has streamed output ends the turn when it fails. The metaprompts call the persona's model and find a provider only when the persona's provider served the turn; they have no fallback of their own.
120121

‎src/api/gmi.ts‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ import { createGmiLaunchTool } from './runtime/agencyLaunch/gmiLaunchTool.js';
6363
import { resolveCognition, type ResolvedCognition } from './runtime/gmiCognition.js';
6464
import { personaFromAgentOptions, stablePersonaIdOf } from './runtime/gmiPersona.js';
6565
import { warnSoulBesideSystemBlocks, withOneSoulWarning } from './runtime/soulLoadWarning.js';
66+
import { soulLog } from '../cognition/substrate/personas/soulLog.js';
6667
import { modelNamesAnotherProvider } from './runtime/credentialOwner.js';
6768
import {
6869
assertEmbeddingConfig,
@@ -540,6 +541,10 @@ export function gmi(opts: GmiOptions): GmiHandle {
540541
warnSoulBesideSystemBlocks(opts);
541542
// Loaded once, at build: a soul that fails to load throws here unless it is optional.
542543
const soul = opts.soul ? loadSoulFromOption(opts.soul) : null;
544+
// gmi() refuses the voice and avatar options, so a front matter that sets them is named and left out.
545+
for (const field of ['voice', 'avatar'] as const) {
546+
if (soul?.frontmatter[field]) soulLog.warn('soul.field_ignored', { field });
547+
}
543548
const cognition = resolveCognition(opts);
544549
// generate() and stream() run the light profile, under the agent's own learning option.
545550
const lightCognition = resolveCognition({ cognition: 'light', learning: opts.learning });
@@ -587,8 +592,9 @@ export function gmi(opts: GmiOptions): GmiHandle {
587592
: {}),
588593
})
589594
: undefined;
590-
/** The traits the agent was given, as the layer and a GMI's own render read them. */
591-
const authoredTraits = normalizeHexacoTraits(opts.personality);
595+
/** The traits the agent was given, by option or by its soul, as the layer and a GMI's own render read them. */
596+
const authoredTraits = normalizeHexacoTraits(opts.personality ?? soul?.frontmatter.hexaco);
597+
const hasTraits = Object.keys(authoredTraits).length > 0;
592598
if (cognition.memory) assertEmbeddingConfig(cognition.memory);
593599
if (cognition.memory && opts.memoryProvider?.getContext) {
594600
console.warn('[agentos] gmi(): cognitive memory supplies the memory context; memoryProvider.getContext is skipped (observe still runs).');
@@ -773,9 +779,13 @@ export function gmi(opts: GmiOptions): GmiHandle {
773779
// another's memories. `GMI.shutdown()` shuts down the memory it was given;
774780
// on the view that does nothing, and `agent.close()` closes the manager.
775781
...(mem ? { cognitiveMemory: mem.manager.forSession() } : {}),
776-
// With learning on: the learner session, which prepares the personality section each turn, and the agent's
777-
// traits, which the GMI renders itself when that session does not answer.
778-
...(layer ? { ...(learner ? { learning: learner } : {}), personaTraits: { authored: authoredTraits } } : {}),
782+
// The agent's traits, which the GMI renders itself: with learning on, on a turn its learner session does not
783+
// prepare; with learning off, on every turn, since the base prompt then holds no personality section.
784+
...(layer
785+
? { ...(learner ? { learning: learner } : {}), personaTraits: { authored: authoredTraits } }
786+
: hasTraits
787+
? { personaTraits: { authored: authoredTraits } }
788+
: {}),
779789
// The usage a provider reports for a call after the call was stopped goes
780790
// to the turn that made the call, which meters and counts it.
781791
completionGateway: {

‎src/api/runtime/gmiPersona.ts‎

Lines changed: 57 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,30 @@
33
* The persona of a GMI built from agent options (`agent({ runtime: 'gmi' })`).
44
*
55
* The base system prompt is the text the legacy path sends: `buildSystemPrompt(opts)`
6-
* (or the joined `systemBlocks`). With the agent's `learning` option on, the
7-
* personality section is left out of it: a GMI given a learner session or the
8-
* persona's traits (`GMIBaseConfig.learning`, `GMIBaseConfig.personaTraits`), as
9-
* `gmi()` gives its GMIs both, sends that section as a system prompt of its own on
10-
* every turn. The chain-of-thought instruction is not part of
6+
* (or the joined `systemBlocks`). Whenever the GMI renders the personality section
7+
* itself, the section is left out of it: with the agent's `learning` option on, or
8+
* for a persona that has traits, `gmi()` gives its GMIs the persona's traits
9+
* (`GMIBaseConfig.personaTraits`, and with learning a learner session,
10+
* `GMIBaseConfig.learning`), and the GMI sends that section as a system prompt of
11+
* its own on every turn. With a soul, the persona carries the soul's fields through
12+
* the loader's one mapping (`personaFieldsOf`): its id, role, traits, mood,
13+
* reasoning-trace limits, hard limits and metadata; an option set in code wins for
14+
* the name and the traits. The chain-of-thought instruction is not part of
1115
* it: `gmi()` puts it first in the system prompt of each model call that offers
1216
* tools, as `generateText` does. The completion options are the
1317
* ones `agent()` forwards on every call. Sentiment presets are expanded into
1418
* metaprompts, as the persona loaders expand them, because the GMI runs only the
1519
* persona's `metaPrompts`.
1620
*/
17-
import { randomUUID } from 'node:crypto';
21+
import { createHash, randomUUID } from 'node:crypto';
1822
import { buildSystemPrompt, loadSoulFromOption, type AgentOptions } from '../agent.js';
1923
import { resolveModelOption } from '../model.js';
2024
import { normalizeHexacoTraits } from '../../cognition/substrate/personas/hexaco.js';
2125
import { stableIdOfName } from '../../cognition/substrate/personas/stableId.js';
2226
import { normalizePersonaDefinition } from '../../cognition/substrate/personas/personaNormalization.js';
2327
import type { IPersonaDefinition, SentimentTrackingConfig } from '../../cognition/substrate/personas/IPersonaDefinition.js';
24-
import type { LoadedSoul } from '../../cognition/substrate/personas/SoulLoader.js';
28+
import { personaFieldsOf, soulAgentIdOf, type LoadedSoul } from '../../cognition/substrate/personas/SoulLoader.js';
29+
import { canonicalJson } from '../../cognition/learning/ledger/canonical.js';
2530
import type { ITool } from '../../core/tools/ITool.js';
2631
import type { ModelCompletionOptions } from '../../core/llm/providers/IProvider.js';
2732
import type { ResolvedCognition } from './gmiCognition.js';
@@ -62,14 +67,31 @@ function completionOptionsOf(opts: AgentOptions): Partial<ModelCompletionOptions
6267
}
6368

6469
/**
65-
* The persona's base prompt. With learning on, the personality section stays out of it, so the section the GMI
66-
* sends each turn appears once; `systemBlocks` never carry one.
70+
* The persona id of a soul that gives no id (no `agentId`, no `name`, on an agent with no name): `soul-` and the first
71+
* 16 hex characters of SHA-256 over the canonical JSON of its front matter and body. The same at every build of the
72+
* same soul; it changes with the soul's text, so it names the persona alone and is never a memory, learner or brain key.
73+
*/
74+
export function derivedSoulPersonaId(soul: Pick<LoadedSoul, 'frontmatter' | 'soulContent'>): string {
75+
return `soul-${createHash('sha256').update(canonicalJson([soul.frontmatter, soul.soulContent])).digest('hex').slice(0, 16)}`;
76+
}
77+
78+
/**
79+
* The agent's stable id: with a soul, the soul's id rule (`soulAgentIdOf`); with none, a named agent's id. Undefined
80+
* for an agent that has neither.
81+
*/
82+
export function agentStableIdOf(opts: Pick<AgentOptions, 'name'>, soul: LoadedSoul | null | undefined): string | undefined {
83+
return soul ? soulAgentIdOf(soul.frontmatter, opts.name) : stablePersonaIdOf(opts);
84+
}
85+
86+
/**
87+
* The persona's base prompt. The personality section stays out of it whenever the GMI renders one itself (learning
88+
* on, or a persona with traits), so the section appears once; `systemBlocks` never carry one.
6789
*
6890
* @param soul - The soul loaded from `opts.soul`, or `null` for none.
6991
*/
70-
function basePrompt(opts: AgentOptions, learningOn: boolean, soul: LoadedSoul | null): string {
92+
function basePrompt(opts: AgentOptions, leaveOutPersonality: boolean, soul: LoadedSoul | null): string {
7193
if (opts.systemBlocks) return opts.systemBlocks.map((block) => block.text).filter(Boolean).join('\n\n');
72-
return buildSystemPrompt(learningOn ? { ...opts, personality: undefined } : opts, soul) ?? '';
94+
return buildSystemPrompt(opts, soul, leaveOutPersonality ? { personality: false } : undefined) ?? '';
7395
}
7496

7597
/**
@@ -79,9 +101,11 @@ function basePrompt(opts: AgentOptions, learningOn: boolean, soul: LoadedSoul |
79101
* @param cognition - The resolved profile ({@link resolveCognition}): sentiment tracking, metaprompts, and whether learning is on.
80102
* @param tools - The agent's tools, adapted: they decide the persona's capabilities.
81103
* @param soul - The soul the caller loaded from `opts.soul`, `null` for none; not passed, `opts.soul` is loaded here.
82-
* @returns The persona. With `cognition.learning` set its base prompt has no personality section: a GMI built from it
83-
* sends the section only when it is given a learner session (`GMIBaseConfig.learning`) or the persona's traits
84-
* (`GMIBaseConfig.personaTraits`), as `gmi()` gives it.
104+
* @returns The persona. With `cognition.learning` set, or when the persona has traits, its base prompt has no
105+
* personality section: a GMI built from it sends the section only when it is given a learner session
106+
* (`GMIBaseConfig.learning`) or the persona's traits (`GMIBaseConfig.personaTraits`), as `gmi()` gives it. With a
107+
* soul the persona carries the soul's id, role, traits, mood, reasoning-trace limits, hard limits and metadata, and
108+
* never its voice or avatar.
85109
* @throws {Error} When no provider or model can be resolved, as `generateText` throws.
86110
* @throws {SoulLoadError} When the soul is loaded here, fails to load and is not optional.
87111
*/
@@ -92,25 +116,37 @@ export function personaFromAgentOptions(
92116
soul?: LoadedSoul | null,
93117
): IPersonaDefinition {
94118
const loaded = soul === undefined ? (opts.soul ? loadSoulFromOption(opts.soul) : null) : soul;
119+
const fields = loaded ? personaFieldsOf(loaded.frontmatter) : undefined;
95120
const { providerId, modelId } = resolveModelOption({ provider: opts.provider, model: opts.model, baseUrl: opts.baseUrl }, 'text');
96-
const name = opts.name?.trim() || 'Agent';
121+
// An option set in code wins over the soul's file; the id is the soul's.
122+
const name = opts.name?.trim() || loaded?.frontmatter.name?.trim() || 'Agent';
97123
const firstLine = opts.instructions?.split('\n').map((line) => line.trim()).find(Boolean);
124+
const traitSource = opts.personality ?? loaded?.frontmatter.hexaco;
125+
const traits = normalizeHexacoTraits(traitSource);
126+
const hasTraits = Object.keys(traits).length > 0;
98127
const completion = completionOptionsOf(opts);
99128
const presets: SentimentTrackingConfig['presets'] = cognition.metaprompts === 'all' ? ['all'] : cognition.metaprompts || [];
100-
const persona: IPersonaDefinition = {
101-
id: stablePersonaIdOf(opts) ?? `agent-${randomUUID()}`,
129+
const persona = {
130+
id: loaded
131+
? (soulAgentIdOf(loaded.frontmatter, opts.name) ?? derivedSoulPersonaId(loaded))
132+
: (stablePersonaIdOf(opts) ?? `agent-${randomUUID()}`),
102133
name,
103-
description: firstLine ?? name,
134+
description: loaded?.frontmatter.role?.trim() || firstLine || name,
104135
version: '1.0.0',
105-
baseSystemPrompt: basePrompt(opts, cognition.learning !== undefined, loaded),
106-
...(opts.personality ? { personalityTraits: normalizeHexacoTraits(opts.personality) } : {}),
136+
baseSystemPrompt: basePrompt(opts, cognition.learning !== undefined || hasTraits, loaded),
137+
...(traitSource ? { personalityTraits: traits } : {}),
138+
...(fields?.hardLimits ? { hardLimits: fields.hardLimits } : {}),
139+
...(fields?.moodAdaptation ? { moodAdaptation: fields.moodAdaptation } : {}),
140+
...(fields?.reasoningTraceConfig ? { reasoningTraceConfig: fields.reasoningTraceConfig } : {}),
141+
// The persona type has no top-level metadata member; the loader carries it the same way.
142+
...(fields?.metadata ? { metadata: fields.metadata } : {}),
107143
defaultProviderId: providerId,
108144
defaultModelId: modelId,
109145
...(Object.keys(completion).length > 0 ? { defaultModelCompletionOptions: completion } : {}),
110146
allowedCapabilities: [...new Set(tools.flatMap((tool) => tool.requiredCapabilities ?? []))],
111147
conversationContextConfig: { maxMessages: GMI_SESSION_MAX_HISTORY_MESSAGES },
112148
sentimentTracking: cognition.sentiment ? { enabled: true, presets } : { enabled: false },
113149
...(cognition.metaprompts === false ? { metaPrompts: [] } : {}),
114-
};
150+
} as IPersonaDefinition;
115151
return normalizePersonaDefinition(persona);
116152
}

0 commit comments

Comments
 (0)