Skip to content

Commit 7df2665

Browse files
committed
feat(souls): render a soul's hard limits last, its traits and its name on agent()
Signed-off-by: jddunn <[email protected]>
1 parent 07ac59e commit 7df2665

6 files changed

Lines changed: 108 additions & 23 deletions

File tree

‎docs/SOUL_FILES.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,7 @@ The `hexaco:` block in SOUL.md frontmatter maps directly to AgentOS's existing
321321
- [`PersonalityMutationStore`](https://github.com/framerslab/agentos/blob/master/src/cognition/emergent/PersonalityMutationStore.ts): records those changes when a storage adapter is configured
322322
- [`PersonaOverlayManager`](https://github.com/framerslab/agentos/blob/master/src/cognition/substrate/persona_overlays/PersonaOverlayManager.ts): patches traits and mood when a workflow agency's persona evolution rules fire
323323

324-
`agent({ soul })` does not read the scores; pass `personality` for its trait paragraph. `PersonaDriftMechanism` works from the traits a cognitive memory manager is configured with.
324+
`agent({ soul })` renders the scores as its trait paragraph unless `personality` is set, which wins. `PersonaDriftMechanism` works from the traits a cognitive memory manager is configured with.
325325

326326
Loaded personas store Honesty-Humility as `personalityTraits.honesty`, the key
327327
that `agent({ personality })`, `AdaptPersonalityTool`, and the memory system read.

‎docs/getting-started/HIGH_LEVEL_API.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -889,7 +889,7 @@ agent({ provider: 'openai', soul: './personas/aria.soul.md' });
889889
agent({ provider: 'openai', soul: { content: SOUL_MARKDOWN_STRING } });
890890
```
891891

892-
`agent({ soul })` uses the prose only. The frontmatter's structured fields (HEXACO scores, voice, mood, hard limits) land on the `personaDefinition` that `loadSoul()` returns, which the full runtime takes as a persona; give an `agent()` a trait paragraph with `personality`. See [SOUL_FILES.md](../SOUL_FILES.md) for the workspace files.
892+
`agent({ soul })` applies the front matter it has a renderer for: the `hardLimits` close the system prompt as a "Hard limits" block, after `systemBlocks` too, the `hexaco` scores render as the trait paragraph when no `personality` is set, and the soul's `name` is the name line when no `name` is set. An option set in code wins over the file. Mood, voice, avatar and the reasoning-trace limits have no renderer on this path. See [SOUL_FILES.md](../SOUL_FILES.md) for the workspace files.
893893

894894
### `souledAgent()`: soul plus a `memory/` wiki
895895

‎src/api/__tests__/souledAgent.e2e.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,11 +149,11 @@ describe('text migrated from a legacy MEMORY.md', () => {
149149
fs.writeFileSync(path.join(dir, 'MEMORY.md'), `${sentence}\n`);
150150
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
151151

152-
// A plain agent that writes no page gets the prompt it always got.
152+
// A plain agent that writes no page gets the soul's prose, the migrated index and the soul's name.
153153
expect(buildSystemPrompt({ soul: dir } as AgentOptions)).toBe(
154154
'You are Aria.\n\n## Long-Term Memory (index)\n\n' +
155155
'You maintain a memory wiki. This is its index. Use the `read_memory_page` tool to open any page by id.\n\n' +
156-
`# Memory Index\n\n<!-- migrated from MEMORY.md -->\n\n${sentence}`,
156+
`# Memory Index\n\n<!-- migrated from MEMORY.md -->\n\n${sentence}\n\nAssistant name: Aria.`,
157157
);
158158

159159
const k = key();

‎src/api/agent.ts‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ import type { IModelRouter } from '../core/llm/routing/IModelRouter.js';
4040
import type { SkillEntry } from '../cognition/skills/types.js';
4141
import { loadSoulSync, parseSoul, SoulLoadError, type LoadedSoul } from '../cognition/substrate/personas/SoulLoader.js';
4242
import { renderPersonalitySection } from '../cognition/substrate/personas/personalityPrompt.js';
43+
import { hardLimitsBlock } from '../cognition/substrate/personas/hardLimits.js';
44+
import { withHardLimitsLast } from './runtime/hardLimitsSystem.js';
4345
import type { ForgetReport, ImportReport, LearnedStateDocument, LearningConfig, LedgerEntry, LoopManifest } from '../cognition/learning/types.js';
4446
import type { HexacoTraitValues } from '../cognition/substrate/personas/hexaco.js';
4547
import type { AgencyLaunchOptions } from './runtime/agencyLaunch/types.js';
@@ -683,13 +685,20 @@ async function loadRecordedAgentOSUsage(
683685

684686
/**
685687
* The system prompt `agent()` assembles from its options: the soul's prose, `instructions`, the name line, the
686-
* personality text and skills.
688+
* personality text and skills. An option set in code wins over the soul's file: the name line is `name`, else the
689+
* soul's `name`; the personality text renders `personality`, else the soul's `hexaco`. The soul's hard limits are not
690+
* part of it: `agent()` closes the prompt with them (`withHardLimitsLast`).
687691
*
688692
* @param opts - The agent's options.
689693
* @param soul - The soul the caller loaded from `opts.soul`; `null` for none. Not passed, `opts.soul` is loaded here.
694+
* @param parts - `personality: false` renders no personality text, for a GMI that renders its own.
690695
* @throws {SoulLoadError} When the soul is loaded here, fails to load and is not optional.
691696
*/
692-
export function buildSystemPrompt(opts: AgentOptions, soul?: LoadedSoul | null): string | undefined {
697+
export function buildSystemPrompt(
698+
opts: AgentOptions,
699+
soul?: LoadedSoul | null,
700+
parts?: { personality?: false },
701+
): string | undefined {
693702
const sections: string[] = [];
694703

695704
// SOUL.md content first — the agent's identity comes before everything else.
@@ -723,12 +732,15 @@ export function buildSystemPrompt(opts: AgentOptions, soul?: LoadedSoul | null):
723732
sections.push(opts.instructions.trim());
724733
}
725734

726-
if (opts.name?.trim()) {
727-
sections.push(`Assistant name: ${opts.name.trim()}.`);
735+
// An option set in code wins over the soul's file for the name and the traits.
736+
const name = opts.name?.trim() || loaded?.frontmatter.name?.trim();
737+
if (name) {
738+
sections.push(`Assistant name: ${name}.`);
728739
}
729740

730-
if (opts.personality) {
731-
const desc = renderPersonalitySection(opts.personality);
741+
const traits = parts?.personality === false ? undefined : (opts.personality ?? loaded?.frontmatter.hexaco);
742+
if (traits) {
743+
const desc = renderPersonalitySection(traits);
732744
if (desc) {
733745
sections.push(desc);
734746
}
@@ -966,6 +978,11 @@ export function agent(opts: AgentOptions): Agent {
966978
warnSoulBesideSystemBlocks(opts);
967979
// Loaded once, at build: a soul that fails to load throws here unless it is optional.
968980
const loadedSoul = opts.soul ? loadSoulFromOption(opts.soul) : null;
981+
const hardLimits = loadedSoul?.frontmatter.hardLimits;
982+
// The soul's hard limits close the system prompt, after systemBlocks too.
983+
const agentSystem = withHardLimitsLast(opts.systemBlocks ?? buildSystemPrompt(opts, loadedSoul), hardLimits);
984+
// A string prompt carries no mark, so the block's text goes beside it for generateText's split.
985+
const hardLimitsText = hardLimitsBlock(hardLimits) ?? undefined;
969986
const sessionBuffers = new Map<string, SessionHistoryBuffer | null>();
970987
// In-memory usage tally per session and per agent. Populated synchronously
971988
// after every generate/send/stream call so `agent.usage()` and
@@ -1011,7 +1028,8 @@ export function agent(opts: AgentOptions): Agent {
10111028
const baseOpts: Partial<GenerateTextOptions> = {
10121029
provider: opts.provider,
10131030
model: opts.model,
1014-
system: opts.systemBlocks ?? buildSystemPrompt(opts, loadedSoul),
1031+
system: agentSystem,
1032+
...(hardLimitsText ? { _hardLimitsText: hardLimitsText } : {}),
10151033
tools: opts.tools,
10161034
maxSteps: opts.maxSteps ?? 5,
10171035
// Per-call completion-token cap applied to every generate /
@@ -1085,7 +1103,8 @@ export function agent(opts: AgentOptions): Agent {
10851103
* own, and that provider's from the environment otherwise.
10861104
*/
10871105
const callOptions = (extra: Partial<GenerateTextOptions> | undefined): Partial<GenerateTextOptions> => {
1088-
let merged = { ...baseOpts, ...extra };
1106+
// A call's own system prompt replaces the agent's, and the hard limits close it too.
1107+
let merged = { ...baseOpts, ...extra, ...(extra?.system !== undefined ? { system: withHardLimitsLast(extra.system, hardLimits) } : {}) };
10891108
if (!extra || (extra.provider === undefined && extra.model === undefined)) return merged;
10901109
if (
10911110
extra.provider === undefined &&

‎src/api/generateText.ts‎

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import {
4646
} from '../core/llm/routing/UncensoredModelCatalog.js';
4747
import { checkContextFit } from './runtime/contextWindowFit.js';
4848
import { responseFormatCarriesSchema } from './runtime/responseFormatForProvider.js';
49+
import { splitHardLimits } from './runtime/hardLimitsSystem.js';
4950
import {
5051
asSpendBudget,
5152
costOfUsageUSD,
@@ -440,6 +441,8 @@ export interface SystemContentBlock {
440441
* `cacheBreakpoint: true`.
441442
*/
442443
cacheTtl?: '5m' | '1h';
444+
/** @internal Set by agent() on the hard-limits block it appends, so a schema instruction is sent before it. */
445+
_hardLimits?: boolean;
443446
}
444447

445448
export interface GenerateTextOptions {
@@ -987,6 +990,11 @@ export interface GenerateTextOptions {
987990
* own system prompt and leaves it unset.
988991
*/
989992
_schemaInstruction?: string;
993+
/**
994+
* @internal The exact text of the hard-limits block a string `system` ends with, set by agent() beside it: a call
995+
* that sends schema instructions sends them before that block, which stays the last system text.
996+
*/
997+
_hardLimitsText?: string;
990998
/**
991999
* INTERNAL (sessions): how many TRAILING entries of `messages` belong to
9921000
* THIS call's transcript delta rather than prior history. Sessions that
@@ -2630,19 +2638,30 @@ export async function generateText(opts: GenerateTextOptions): Promise<GenerateT
26302638
const cotInstruction = resolveChainOfThought(opts.chainOfThought);
26312639
const hasTools = tools.length > 0;
26322640

2633-
if (typeof opts.system === 'string' || !opts.system) {
2641+
// A structured call whose payload carries no schema sends the schema instructions as a system message. When the
2642+
// system prompt closes with a hard-limits block, the instructions go before that block, which is sent as the
2643+
// last system message, so the limits stay the last system text of the call.
2644+
const schemaInstruction =
2645+
opts._schemaInstruction && !responseFormatCarriesSchema(responseFormat as Record<string, unknown> | undefined)
2646+
? opts._schemaInstruction
2647+
: undefined;
2648+
const { head: systemHead, limits: closingLimits } = schemaInstruction
2649+
? splitHardLimits(opts.system, opts._hardLimitsText)
2650+
: { head: opts.system, limits: undefined };
2651+
2652+
if (typeof systemHead === 'string' || !systemHead) {
26342653
// Plain string system prompt (existing behavior)
26352654
if (cotInstruction && hasTools) {
2636-
const systemContent = opts.system
2637-
? `${cotInstruction}\n\n${opts.system}`
2655+
const systemContent = systemHead
2656+
? `${cotInstruction}\n\n${systemHead}`
26382657
: cotInstruction;
26392658
messages.push({ role: 'system', content: systemContent });
2640-
} else if (opts.system) {
2641-
messages.push({ role: 'system', content: opts.system });
2659+
} else if (systemHead) {
2660+
messages.push({ role: 'system', content: systemHead });
26422661
}
26432662
} else {
26442663
// Structured SystemContentBlock[]: convert to content parts with cache_control
2645-
const blocks = opts.system as SystemContentBlock[];
2664+
const blocks = systemHead;
26462665
const parts = blocks.map(block => ({
26472666
type: 'text' as const,
26482667
text: block.text,
@@ -2659,11 +2678,10 @@ export async function generateText(opts: GenerateTextOptions): Promise<GenerateT
26592678
messages.push({ role: 'system', content: parts });
26602679
}
26612680

2662-
// A structured call whose payload carries no schema sends it after the
2663-
// system prompt, so the model sees what it has to answer in.
2664-
if (opts._schemaInstruction && !responseFormatCarriesSchema(responseFormat as Record<string, unknown> | undefined)) {
2665-
messages.push({ role: 'system', content: opts._schemaInstruction });
2666-
}
2681+
// The schema instructions follow the system prompt, so the model sees what it has to answer in; a closing
2682+
// hard-limits block split off above follows them.
2683+
if (schemaInstruction) messages.push({ role: 'system', content: schemaInstruction });
2684+
if (closingLimits !== undefined) messages.push({ role: 'system', content: closingLimits });
26672685

26682686
// Everything above is built from opts (system prompt, chain-of-thought
26692687
// instruction, schema instructions); a failover continuation rebuilds
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* @file hardLimitsSystem.ts
3+
* A persona's hard-limits block as the last part of an agent's system prompt on the default runtime, and the split
4+
* `generateText` makes when it has to send something else before that block.
5+
*
6+
* @module api/runtime/hardLimitsSystem
7+
*/
8+
import type { SystemContentBlock } from '../generateText.js';
9+
import { hardLimitsBlock } from '../../cognition/substrate/personas/hardLimits.js';
10+
11+
type SystemPrompt = string | SystemContentBlock[] | undefined;
12+
13+
/**
14+
* The agent's system prompt with the persona's hard-limits block as its last part: appended to a string after a blank
15+
* line, or as one more block after the host's blocks, with no cache breakpoint of its own. Unchanged when there are no
16+
* limits.
17+
*
18+
* @param system - The agent's system prompt: a string, the host's blocks, or none.
19+
* @param hardLimits - The persona's hard limits; blank lines are dropped.
20+
*/
21+
export function withHardLimitsLast(system: SystemPrompt, hardLimits: readonly string[] | undefined): SystemPrompt {
22+
const block = hardLimitsBlock(hardLimits);
23+
if (!block) return system;
24+
if (Array.isArray(system)) return [...system, { text: block, _hardLimits: true }];
25+
return system ? `${system}\n\n${block}` : block;
26+
}
27+
28+
/**
29+
* A system prompt apart from the hard-limits block that closes it: blocks whose last one carries the mark
30+
* `withHardLimitsLast` sets, or a string that ends with `hardLimitsText`. `limits` is undefined, and `head` the prompt
31+
* as given, when it closes with no such block.
32+
*
33+
* @param system - The call's system prompt.
34+
* @param hardLimitsText - The block's exact text, for a string prompt (`GenerateTextOptions._hardLimitsText`).
35+
*/
36+
export function splitHardLimits(system: SystemPrompt, hardLimitsText: string | undefined): { head: SystemPrompt; limits: string | undefined } {
37+
if (Array.isArray(system)) {
38+
const last = system[system.length - 1];
39+
if (!last?._hardLimits) return { head: system, limits: undefined };
40+
const rest = system.slice(0, -1);
41+
return { head: rest.length > 0 ? rest : undefined, limits: last.text };
42+
}
43+
if (typeof system === 'string' && hardLimitsText && system.endsWith(hardLimitsText)) {
44+
const head = system.slice(0, system.length - hardLimitsText.length).trimEnd();
45+
return { head: head || undefined, limits: hardLimitsText };
46+
}
47+
return { head: system, limits: undefined };
48+
}

0 commit comments

Comments
 (0)