Skip to content

Commit c823259

Browse files
committed
feat(souls)!: a soul that fails to load throws at build
Pass soul: { path, optional: true } to run without it; one soul.load_failed line is then written. Signed-off-by: jddunn <[email protected]>
1 parent 9591cc9 commit c823259

8 files changed

Lines changed: 100 additions & 55 deletions

File tree

‎docs/SOUL_FILES.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ The cognitive-memory mechanisms layered on top (decay, retrieval-induced forgett
3535

3636
| File | What it holds | What AgentOS does with it |
3737
|---|---|---|
38-
| **SOUL.md** | Personality, values, tone, behavioral boundaries | The body opens the system prompt; the frontmatter becomes `personaDefinition`. Without it, `loadSoul()` throws and `agent({ soul })` boots without a soul. |
38+
| **SOUL.md** | Personality, values, tone, behavioral boundaries | The body opens the system prompt; the frontmatter becomes `personaDefinition`. Without it, `loadSoul()` throws, and so does building an agent on it: `agent()` and `gmi()` throw `SoulLoadError`, and `souledAgent()` rejects with it. A front matter field of the wrong type throws the same error, naming the field. `soul: { path, optional: true }` runs the agent without the soul and writes one `soul.load_failed` log line. |
3939
| **STYLE.md** | Voice patterns, vocabulary, register | Appended to the system prompt as a `## Style` section. |
4040
| **IDENTITY.md** | Display card: name, role, agent-ID, avatar | Returned as `identityContent`; nothing in the runtime reads it. |
4141
| **AGENTS.md** | Procedural rules, session-start checks, workflow steps | Returned as `agentsContent`; nothing in the runtime reads or runs it. |

‎docs/getting-started/HIGH_LEVEL_API.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -876,7 +876,7 @@ With `runtime: 'gmi'` (or [`gmi()`](https://github.com/framerslab/agentos/blob/m
876876

877877
### Per-agent identity via SOUL.md
878878

879-
Pass a `soul:` option to give an agent its identity from a SOUL.md workspace. `agent()` builds its system prompt from the SOUL.md body first, then a `## Style` section from STYLE.md, then the `memory/index.md` catalog, then `instructions`, `name`, `personality` and skills. A soul that fails to load logs a warning, and the agent starts without it.
879+
Pass a `soul:` option to give an agent its identity from a SOUL.md workspace. `agent()` builds its system prompt from the SOUL.md body first, then a `## Style` section from STYLE.md, then the `memory/index.md` catalog, then `instructions`, `name`, `personality` and skills. A soul that fails to load throws `SoulLoadError` when the agent is built; pass `soul: { path, optional: true }` to run without it.
880880

881881
```ts
882882
// Workspace path: SOUL.md, STYLE.md and memory/index.md shape the prompt

‎src/api/agent.ts‎

Lines changed: 44 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ import { maskStreamMembers } from './runtime/pool/maskedOutput.js';
3838
import type { HostLLMPolicy } from './runtime/hostPolicy.js';
3939
import type { IModelRouter } from '../core/llm/routing/IModelRouter.js';
4040
import type { SkillEntry } from '../cognition/skills/types.js';
41-
import { loadSoulSync, parseSoul } from '../cognition/substrate/personas/SoulLoader.js';
41+
import { loadSoulSync, parseSoul, SoulLoadError, type LoadedSoul } from '../cognition/substrate/personas/SoulLoader.js';
4242
import { renderPersonalitySection } from '../cognition/substrate/personas/personalityPrompt.js';
4343
import type { ForgetReport, ImportReport, LearnedStateDocument, LearningConfig, LedgerEntry, LoopManifest } from '../cognition/learning/types.js';
4444
import type { HexacoTraitValues } from '../cognition/substrate/personas/hexaco.js';
@@ -342,14 +342,16 @@ export interface AgentOptions extends BaseAgentConfig {
342342
* `instructions`, `name`, `personality` and `skills`. The front matter's
343343
* structured fields (HEXACO traits, voice, mood, hard limits) are not applied
344344
* here: they live on the persona (`personaDefinition`) that `loadSoul()`
345-
* returns, which the full runtime takes. A soul that fails to load logs a
346-
* warning, and the agent is built without it.
345+
* returns, which the full runtime takes. A soul that fails to load, or whose
346+
* front matter has a field of the wrong type, throws `SoulLoadError` when the
347+
* agent is built. `optional: true` on the object forms runs the agent without
348+
* it and writes one `soul.load_failed` log line.
347349
*
348350
* @see `loadSoul` in `@framers/agentos/cognition/substrate/personas/SoulLoader`
349351
* for the loader implementation and full SOUL.md format spec.
350352
* @see https://github.com/aaronjmars/soul.md for the cross-framework convention.
351353
*/
352-
soul?: string | { content: string } | { path: string };
354+
soul?: string | { content: string; optional?: boolean } | { path: string; optional?: boolean };
353355
/**
354356
* Which engine serves this agent. `'legacy'` (the default) calls the model through
355357
* generateText and streamText; `'gmi'` serves every session with a Generalized Mind
@@ -679,25 +681,34 @@ async function loadRecordedAgentOSUsage(
679681
return getRecordedAgentOSUsage(options);
680682
}
681683

682-
export function buildSystemPrompt(opts: AgentOptions): string | undefined {
684+
/**
685+
* The system prompt `agent()` assembles from its options: the soul's prose, `instructions`, the name line, the
686+
* personality text and skills.
687+
*
688+
* @param opts - The agent's options.
689+
* @param soul - The soul the caller loaded from `opts.soul`; `null` for none. Not passed, `opts.soul` is loaded here.
690+
* @throws {SoulLoadError} When the soul is loaded here, fails to load and is not optional.
691+
*/
692+
export function buildSystemPrompt(opts: AgentOptions, soul?: LoadedSoul | null): string | undefined {
683693
const sections: string[] = [];
684694

685695
// SOUL.md content first — the agent's identity comes before everything else.
686696
// See `loadSoul` in cognition/substrate/personas/SoulLoader.
687-
if (opts.soul) {
688-
const loaded = loadSoulFromOption(opts.soul);
689-
if (loaded?.soulContent) {
697+
// The soul the caller loaded; a caller that passes none has it loaded here.
698+
const loaded = soul === undefined ? (opts.soul ? loadSoulFromOption(opts.soul) : null) : soul;
699+
if (loaded) {
700+
if (loaded.soulContent) {
690701
sections.push(loaded.soulContent);
691702
}
692-
if (loaded?.styleContent) {
703+
if (loaded.styleContent) {
693704
sections.push(`## Style\n\n${loaded.styleContent}`);
694705
}
695706
// The memory wiki's index.md catalog. The agent reads it to know what it
696707
// remembers, then pulls full pages via the read_memory_page tool. Skip the
697708
// empty catalog (a bare "# Memory Index") so agents with no memory yet keep
698709
// a clean prompt.
699710
// The loader leaves out the end marker of text migrated from a legacy MEMORY.md, the wiki's own bookkeeping.
700-
const wikiIndex = loaded?.wikiIndex ?? '';
711+
const wikiIndex = loaded.wikiIndex ?? '';
701712
if (wikiIndex && wikiIndex !== '# Memory Index') {
702713
sections.push(
703714
'## Long-Term Memory (index)\n\n' +
@@ -778,30 +789,31 @@ function maskStreamResult(result: StreamTextResult, mask: (error: unknown) => un
778789
}
779790

780791
/**
781-
* Resolve an `AgentOptions.soul` value (string path | { content } | { path })
782-
* into a `LoadedSoul`. Returns null on failure so the agent can still boot
783-
* (the soul is additive, not load-blocking), and warns with `console.warn` in
784-
* every environment that the agent boots without it; the loads of one agent
785-
* build warn once (`withOneSoulWarning`).
792+
* Loads an `AgentOptions.soul` value (a path, `{ content }` or `{ path }`).
793+
*
794+
* @returns The loaded soul; `null` only for a soul given `optional: true` that failed to load, after one
795+
* `soul.load_failed` line (once per `withOneSoulWarning` scope).
796+
* @throws {SoulLoadError} When the soul fails to load and is not optional: a missing or unread SOUL.md, a front matter
797+
* field of the wrong type, or a value that is none of the three forms.
786798
*/
787799
export function loadSoulFromOption(
788800
soul: NonNullable<AgentOptions['soul']>,
789-
): import('../cognition/substrate/personas/SoulLoader.js').LoadedSoul | null {
801+
): LoadedSoul | null {
802+
const given = soul as unknown;
803+
const asObject = typeof given === 'object' && given !== null ? (given as { content?: unknown; path?: unknown; optional?: unknown }) : undefined;
804+
const source = typeof given === 'string' ? given : typeof asObject?.path === 'string' ? asObject.path : 'inline soul';
790805
try {
791-
if (typeof soul === 'string') {
792-
return loadSoulSync({ source: soul });
793-
}
794-
if ('content' in soul) {
795-
return parseSoul(soul.content);
796-
}
797-
if ('path' in soul) {
798-
return loadSoulSync({ source: soul.path });
799-
}
800-
return null;
806+
if (typeof given === 'string') return loadSoulSync({ source: given });
807+
if (typeof asObject?.content === 'string') return parseSoul(asObject.content);
808+
if (typeof asObject?.path === 'string') return loadSoulSync({ source: asObject.path });
809+
throw new SoulLoadError(source, 'the soul option must be a path, { content } or { path }');
801810
} catch (err) {
802-
// Non-fatal: the agent boots without the soul, and says so in every environment.
803-
warnSoulLoadFailed(typeof soul === 'string' ? soul : 'path' in soul ? String(soul.path) : 'inline soul', err);
804-
return null;
811+
if (asObject?.optional === true) {
812+
warnSoulLoadFailed(source, err);
813+
return null;
814+
}
815+
if (err instanceof SoulLoadError) throw err;
816+
throw new SoulLoadError(source, err instanceof Error ? err.message : String(err), { cause: err });
805817
}
806818
}
807819

@@ -952,6 +964,8 @@ export function agent(opts: AgentOptions): Agent {
952964
}
953965
// The GMI path warns in gmi(), so an agent on it warns once.
954966
warnSoulBesideSystemBlocks(opts);
967+
// Loaded once, at build: a soul that fails to load throws here unless it is optional.
968+
const loadedSoul = opts.soul ? loadSoulFromOption(opts.soul) : null;
955969
const sessionBuffers = new Map<string, SessionHistoryBuffer | null>();
956970
// In-memory usage tally per session and per agent. Populated synchronously
957971
// after every generate/send/stream call so `agent.usage()` and
@@ -997,7 +1011,7 @@ export function agent(opts: AgentOptions): Agent {
9971011
const baseOpts: Partial<GenerateTextOptions> = {
9981012
provider: opts.provider,
9991013
model: opts.model,
1000-
system: opts.systemBlocks ?? buildSystemPrompt(opts),
1014+
system: opts.systemBlocks ?? buildSystemPrompt(opts, loadedSoul),
10011015
tools: opts.tools,
10021016
maxSteps: opts.maxSteps ?? 5,
10031017
// Per-call completion-token cap applied to every generate /

‎src/api/gmi.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
*/
2121
import { randomUUID } from 'node:crypto';
2222
import type { Agent, AgentLearning, AgentOptions, AgentSession, AgentSessionOptions, SessionSendOptions } from './agent.js';
23+
// agent.ts imports this module back; each side calls the other only inside functions.
24+
import { loadSoulFromOption } from './agent.js';
2325
import { extractTextFromContent, resolveChainOfThought, type GenerateTextOptions, type GenerateTextResult, type Message, type MessageContent, type TokenUsage } from './generateText.js';
2426
import type { StreamTextResult } from './streamText.js';
2527
import { GMI } from '../cognition/substrate/GMI.js';
@@ -536,6 +538,8 @@ export function gmi(opts: GmiOptions): GmiHandle {
536538
console.warn(`[AgentOS] gmi() accepted config it does not enforce yet: ${deferred.join(', ')}.`);
537539
}
538540
warnSoulBesideSystemBlocks(opts);
541+
// Loaded once, at build: a soul that fails to load throws here unless it is optional.
542+
const soul = opts.soul ? loadSoulFromOption(opts.soul) : null;
539543
const cognition = resolveCognition(opts);
540544
// generate() and stream() run the light profile, under the agent's own learning option.
541545
const lightCognition = resolveCognition({ cognition: 'light', learning: opts.learning });
@@ -636,10 +640,10 @@ export function gmi(opts: GmiOptions): GmiHandle {
636640

637641
const shared = retryingOnce<Shared>(async () => {
638642
// Throws, as generateText throws, when no provider or model resolves.
639-
// Both personas load the soul: a soul that fails to load warns once for the pair.
643+
// Both personas take the soul loaded at build.
640644
const [persona, lightPersona] = withOneSoulWarning(() => [
641-
personaFromAgentOptions(opts, cognition, tools),
642-
personaFromAgentOptions(opts, lightCognition, tools),
645+
personaFromAgentOptions(opts, cognition, tools, soul),
646+
personaFromAgentOptions(opts, lightCognition, tools, soul),
643647
] as const);
644648
const promptEngine = new PromptEngine();
645649
await promptEngine.initialize(GMI_PROMPT_ENGINE_CONFIG);
@@ -962,7 +966,7 @@ export function gmi(opts: GmiOptions): GmiHandle {
962966
extra?.provider ??
963967
(extra?.model && opts.provider && modelNamesAnotherProvider(opts.provider, extra.model) ? undefined : opts.provider);
964968
const persona = extra && (extra.model || extra.provider)
965-
? personaFromAgentOptions({ ...opts, model: extra.model ?? opts.model, provider: callProvider }, lightCognition, tools)
969+
? personaFromAgentOptions({ ...opts, model: extra.model ?? opts.model, provider: callProvider }, lightCognition, tools, soul)
966970
: s.lightPersona;
967971
// A call has no user of its own, so no learner; with learning on its GMI sends the personality section.
968972
const learner = await learnerSessionFor(callId, persona.id, undefined);

‎src/api/runtime/gmiPersona.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,13 @@
1515
* persona's `metaPrompts`.
1616
*/
1717
import { randomUUID } from 'node:crypto';
18-
import { buildSystemPrompt, type AgentOptions } from '../agent.js';
18+
import { buildSystemPrompt, loadSoulFromOption, type AgentOptions } from '../agent.js';
1919
import { resolveModelOption } from '../model.js';
2020
import { normalizeHexacoTraits } from '../../cognition/substrate/personas/hexaco.js';
2121
import { stableIdOfName } from '../../cognition/substrate/personas/stableId.js';
2222
import { normalizePersonaDefinition } from '../../cognition/substrate/personas/personaNormalization.js';
2323
import type { IPersonaDefinition, SentimentTrackingConfig } from '../../cognition/substrate/personas/IPersonaDefinition.js';
24+
import type { LoadedSoul } from '../../cognition/substrate/personas/SoulLoader.js';
2425
import type { ITool } from '../../core/tools/ITool.js';
2526
import type { ModelCompletionOptions } from '../../core/llm/providers/IProvider.js';
2627
import type { ResolvedCognition } from './gmiCognition.js';
@@ -63,10 +64,12 @@ function completionOptionsOf(opts: AgentOptions): Partial<ModelCompletionOptions
6364
/**
6465
* The persona's base prompt. With learning on, the personality section stays out of it, so the section the GMI
6566
* sends each turn appears once; `systemBlocks` never carry one.
67+
*
68+
* @param soul - The soul loaded from `opts.soul`, or `null` for none.
6669
*/
67-
function basePrompt(opts: AgentOptions, learningOn: boolean): string {
70+
function basePrompt(opts: AgentOptions, learningOn: boolean, soul: LoadedSoul | null): string {
6871
if (opts.systemBlocks) return opts.systemBlocks.map((block) => block.text).filter(Boolean).join('\n\n');
69-
return buildSystemPrompt(learningOn ? { ...opts, personality: undefined } : opts) ?? '';
72+
return buildSystemPrompt(learningOn ? { ...opts, personality: undefined } : opts, soul) ?? '';
7073
}
7174

7275
/**
@@ -75,12 +78,20 @@ function basePrompt(opts: AgentOptions, learningOn: boolean): string {
7578
* @param opts - The agent's options.
7679
* @param cognition - The resolved profile ({@link resolveCognition}): sentiment tracking, metaprompts, and whether learning is on.
7780
* @param tools - The agent's tools, adapted: they decide the persona's capabilities.
81+
* @param soul - The soul the caller loaded from `opts.soul`, `null` for none; not passed, `opts.soul` is loaded here.
7882
* @returns The persona. With `cognition.learning` set its base prompt has no personality section: a GMI built from it
7983
* sends the section only when it is given a learner session (`GMIBaseConfig.learning`) or the persona's traits
8084
* (`GMIBaseConfig.personaTraits`), as `gmi()` gives it.
8185
* @throws {Error} When no provider or model can be resolved, as `generateText` throws.
86+
* @throws {SoulLoadError} When the soul is loaded here, fails to load and is not optional.
8287
*/
83-
export function personaFromAgentOptions(opts: AgentOptions, cognition: ResolvedCognition, tools: ITool[]): IPersonaDefinition {
88+
export function personaFromAgentOptions(
89+
opts: AgentOptions,
90+
cognition: ResolvedCognition,
91+
tools: ITool[],
92+
soul?: LoadedSoul | null,
93+
): IPersonaDefinition {
94+
const loaded = soul === undefined ? (opts.soul ? loadSoulFromOption(opts.soul) : null) : soul;
8495
const { providerId, modelId } = resolveModelOption({ provider: opts.provider, model: opts.model, baseUrl: opts.baseUrl }, 'text');
8596
const name = opts.name?.trim() || 'Agent';
8697
const firstLine = opts.instructions?.split('\n').map((line) => line.trim()).find(Boolean);
@@ -91,7 +102,7 @@ export function personaFromAgentOptions(opts: AgentOptions, cognition: ResolvedC
91102
name,
92103
description: firstLine ?? name,
93104
version: '1.0.0',
94-
baseSystemPrompt: basePrompt(opts, cognition.learning !== undefined),
105+
baseSystemPrompt: basePrompt(opts, cognition.learning !== undefined, loaded),
95106
...(opts.personality ? { personalityTraits: normalizeHexacoTraits(opts.personality) } : {}),
96107
defaultProviderId: providerId,
97108
defaultModelId: modelId,

‎src/api/runtime/soulLoadWarning.ts‎

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,23 @@
11
/**
22
* @file soulLoadWarning.ts
3-
* The warning for a soul that fails to load, written once per agent build.
3+
* The `soul.load_failed` line for a soul given `optional: true` that fails to load, written once per agent build.
44
*
5-
* One build can load the same soul more than once: a GMI agent builds two
6-
* personas from the agent's options on its first turn, and each builds the
7-
* system prompt, which loads the soul. A build runs those loads inside
8-
* {@link withOneSoulWarning}, and the same failure is warned about once there.
9-
* Outside such a scope every failure is warned about, so two builds each warn.
5+
* A soul that is not optional throws when it fails to load. One build can load an optional soul more than once; a
6+
* build runs those loads inside {@link withOneSoulWarning}, and the same failure is logged once there. Outside such a
7+
* scope every failure is logged, so two builds each log.
108
*
119
* @module api/runtime/soulLoadWarning
1210
*/
11+
import { soulLog } from '../../cognition/substrate/personas/soulLog.js';
12+
import { errorFields } from '../../core/logging/events.js';
1313

14-
/** The failures warned about in the running scope, as `source + NUL + message`; null outside a scope. */
14+
/** The failures logged in the running scope, as `source + NUL + message`; null outside a scope. */
1515
let warnedInScope: Set<string> | null = null;
1616

1717
/**
18-
* Run `build` with soul-load warnings deduplicated: a failure warned about
19-
* once inside it is not warned about again until it returns. `build` must be
20-
* synchronous; a scope already running is joined.
18+
* Run `build` with soul-load lines deduplicated: a failure logged once inside
19+
* it is not logged again until it returns. `build` must be synchronous; a
20+
* scope already running is joined.
2121
*
2222
* @param build - The synchronous work that may load the soul several times.
2323
* @returns What `build` returns.
@@ -33,10 +33,10 @@ export function withOneSoulWarning<T>(build: () => T): T {
3333
}
3434

3535
/**
36-
* Warn that a soul failed to load and the agent runs without it, in every
37-
* environment, once per {@link withOneSoulWarning} scope.
36+
* Logs that a soul given `optional: true` failed to load and the agent runs without it: one `soul.load_failed` line,
37+
* with the error's type and code and no path or message, once per {@link withOneSoulWarning} scope.
3838
*
39-
* @param source - What names the soul: its path, or `inline soul` for `{ content }`.
39+
* @param source - What names the soul: its path, or `inline soul` for `{ content }`. Used only to log a failure once.
4040
* @param error - Why it failed.
4141
*/
4242
export function warnSoulLoadFailed(source: string, error: unknown): void {
@@ -46,7 +46,7 @@ export function warnSoulLoadFailed(source: string, error: unknown): void {
4646
if (warnedInScope.has(key)) return;
4747
warnedInScope.add(key);
4848
}
49-
console.warn(`[@framers/agentos] Failed to load soul: ${message}. Agent will boot without SOUL.md identity.`);
49+
soulLog.warn('soul.load_failed', { optional: 'yes', ...errorFields(error) });
5050
}
5151

5252
/**
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
/**
2+
* @fileoverview The soul module's event handle. Each line is one of the `soul.*` events in `AGENTOS_EVENTS`: a field
3+
* name, a reason, an error's type and code; never a soul's path, its text or an error's message.
4+
*
5+
* @module agentos/cognition/substrate/personas/soulLog
6+
*/
7+
import { moduleLogger } from '../../../core/logging/loggerFactory.js';
8+
9+
/** Writes the `soul.*` events to the logger current when each is written. */
10+
export const soulLog = moduleLogger('souls', 'library');

0 commit comments

Comments
 (0)