@mindot/will 0.2.0 → 0.4.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.
Files changed (56) hide show
  1. package/README.md +65 -11
  2. package/dist/channels/discord.d.ts +78 -0
  3. package/dist/channels/discord.js +193 -0
  4. package/dist/channels/discord.js.map +1 -0
  5. package/dist/{mcp/cli.js → cli.js} +1037 -546
  6. package/dist/cli.js.map +1 -0
  7. package/dist/index.d.ts +141 -141
  8. package/dist/index.js +390 -316
  9. package/dist/index.js.map +1 -1
  10. package/dist/mcp/effectors.d.ts +1 -1
  11. package/dist/{will-B5eKs3Wv.d.ts → will-D-slky1N.d.ts} +4011 -3916
  12. package/package.json +7 -2
  13. package/src/channels/discord.ts +214 -0
  14. package/src/channels/roster.ts +87 -0
  15. package/src/channels/types.ts +46 -0
  16. package/src/cli.ts +100 -0
  17. package/src/cognition/agency/engines/deliberation.engine.ts +7 -7
  18. package/src/cognition/agency/execution.primitives.ts +11 -11
  19. package/src/cognition/agency/proactive.communicator.ts +8 -8
  20. package/src/cognition/config.mirror.entities.ts +2 -2
  21. package/src/cognition/conversation.memory.ts +1 -1
  22. package/src/cognition/faculties/executive.engine/commands.ts +7 -15
  23. package/src/cognition/faculties/executive.engine/engine.ts +64 -34
  24. package/src/cognition/faculties/executive.engine/escalation.buffer.ts +1 -1
  25. package/src/cognition/faculties/executive.engine/facet.ts +1 -1
  26. package/src/cognition/faculties/executive.engine/prompt.factory.ts +76 -61
  27. package/src/cognition/faculties/executive.engine/types.ts +1 -1
  28. package/src/cognition/faculties/introspection.engine.ts +1 -2
  29. package/src/cognition/faculties/planning.engine/engine.ts +38 -1
  30. package/src/cognition/faculties/planning.engine/plan.store.ts +42 -0
  31. package/src/cognition/faculties/planning.engine/plan.supervision.ts +7 -7
  32. package/src/cognition/faculties/theory.of.mind.ts +2 -2
  33. package/src/cognition/senses/audition.engine/engine.ts +21 -21
  34. package/src/host/boot.ts +193 -0
  35. package/src/host/utterances.ts +53 -0
  36. package/src/llm/summarizer.ts +2 -2
  37. package/src/mcp/server.ts +7 -30
  38. package/src/profiles/companion.ts +14 -14
  39. package/src/profiles/company-brain.ts +19 -19
  40. package/src/profiles/customer-service.ts +17 -17
  41. package/src/profiles/game-npc.ts +10 -10
  42. package/src/profiles/index.ts +2 -2
  43. package/src/profiles/smart-home.ts +16 -16
  44. package/src/runners/outreach.runner.ts +6 -9
  45. package/src/runners/social.runner.ts +1 -4
  46. package/src/runners/thin-shim.runner.ts +4 -6
  47. package/src/sdk/will.ts +27 -10
  48. package/src/serve/server.ts +154 -0
  49. package/src/stem/guards/identity.coherence.ts +5 -3
  50. package/src/stem/guards/identity.guard.ts +20 -9
  51. package/src/stem/index.ts +7 -7
  52. package/src/stem/mind.ts +182 -98
  53. package/src/stem/tracts/outbox.controller.ts +2 -2
  54. package/dist/mcp/cli.js.map +0 -1
  55. package/src/mcp/cli.ts +0 -129
  56. /package/dist/{mcp/cli.d.ts → cli.d.ts} +0 -0
@@ -94,6 +94,8 @@ export class PlanningEngine implements SimulationEngine, CognitiveEngine {
94
94
  * replay state) from off-tick callbacks like _activateStep / _onStepOutcome.
95
95
  */
96
96
  private _lastTick = 0
97
+ /** One-time deletion of legacy `plan-executive-*` entities (see react step 0a). */
98
+ private _legacyPlanSweepDone = false
97
99
 
98
100
  /**
99
101
  * Monotonic suffix counter for activity-listener subscription ids. These ids
@@ -205,7 +207,31 @@ export class PlanningEngine implements SimulationEngine, CognitiveEngine {
205
207
  planId?: string; stepId?: string
206
208
  }
207
209
 
208
- if( !p.planId || !p.stepId ) return
210
+ // Conscious-enaction credit: outcomes carry plan provenance only when
211
+ // the plan's OWN frontier prior won the competition. But the plan is a
212
+ // prior over WHAT to do — if the self does the very thing an active
213
+ // step calls for by any route (executive action via ideomotor, habit),
214
+ // the step is done. Without this, a mind that consciously performs its
215
+ // plan starves the plan of credit: steps stay active, the goal reads
216
+ // blocked, and the executive re-authors the same plan over and over
217
+ // (observed live: 8 authorings for one goal, zero completions).
218
+ // Deterministic: stores iterate in insertion order; first match wins.
219
+ if( !p.planId || !p.stepId ){
220
+ if( !p.actionType || typeof p.success !== 'boolean' ) return
221
+ for( const plan of this._store.all() ){
222
+ if( plan.status !== 'executing' ) continue
223
+ const step = plan.steps.find( s => s.status === 'active' && s.action === p.actionType )
224
+ if( !step ) continue
225
+ logger.info( `[planning] conscious-enaction credit: ${plan.id}/${step.id}=${step.action} (no provenance on outcome)` )
226
+ this._onStepOutcome( plan.id, step.id, {
227
+ success: p.success,
228
+ description: p.description ?? ( p.success ? 'Completed' : 'Failed' ),
229
+ outcomeQuality: p.outcomeQuality,
230
+ } )
231
+ return // credit exactly one step per outcome
232
+ }
233
+ return
234
+ }
209
235
  if( !this._store.has( p.planId ) ) return
210
236
 
211
237
  this._onStepOutcome( p.planId, p.stepId, {
@@ -280,6 +306,17 @@ export class PlanningEngine implements SimulationEngine, CognitiveEngine {
280
306
  this._lastTick = tick as unknown as number
281
307
  const commands: StateCommands = { set: [], delete: [], metrics: [] }
282
308
 
309
+ // 0a. Legacy sweep (once per session): delete the raw `plan-executive-*`
310
+ // entities the executive commands path used to write in parallel with
311
+ // this engine's ingest. They froze at 'ready' forever and polluted the
312
+ // Active-Plans awareness (phantom drafts → re-authoring pressure).
313
+ if( !this._legacyPlanSweepDone ){
314
+ this._legacyPlanSweepDone = true
315
+ for( const entity of state.entities.values() )
316
+ if( entity.type === 'plan' && entity.id.startsWith('plan-executive-') )
317
+ commands.delete!.push( entity.id )
318
+ }
319
+
283
320
  // 0. Channel A (subconscious): refresh trait-driven dispositions from the
284
321
  // persona-prior mirror before acting on them this tick.
285
322
  this._readConfigFromState( state )
@@ -13,6 +13,21 @@
13
13
  import type { Tick, StateCommands } from '#core/types'
14
14
  import { TERMINAL_STATUSES, type Plan } from '#faculties/planning.engine/types'
15
15
 
16
+ /**
17
+ * Structural fingerprint of a plan's decomposition — the ordered action
18
+ * sequence plus each step's prerequisite fan-in. Two plans with the same key
19
+ * share a *shape*. Recurring shapes are the demonstrated-need signal for
20
+ * emergent planning (docs/strategy/__EMERGENT_PLANNING.md): the mind paying
21
+ * the executive to re-derive a decomposition it has already authored.
22
+ */
23
+ export function planShapeKey(
24
+ steps: ReadonlyArray<{ action: string; prerequisites?: readonly string[] }>,
25
+ ): string {
26
+ return steps
27
+ .map( s => `${ s.action }${ ( s.prerequisites?.length ?? 0 ) > 0 ? `<${ s.prerequisites!.length }` : '' }` )
28
+ .join('>')
29
+ }
30
+
16
31
  export class PlanStore {
17
32
  /**
18
33
  * Canonical plan store, keyed by plan.id ("plan-N") — the id the execution,
@@ -35,6 +50,14 @@ export class PlanStore {
35
50
  /** planId → sim tick it became terminal; drives retention GC (gcTerminal). */
36
51
  private _terminalAt = new Map<string, number>()
37
52
  private _planCounter = 0
53
+ /**
54
+ * Shape recurrence tally — shapeKey → count of plans authored with that
55
+ * decomposition this session (monotone; eviction never erases history).
56
+ * Feeds `planning.shapes.*` metrics: the demonstrated-need needle for
57
+ * emergent planning. `_shapeCounted` guards one count per plan id.
58
+ */
59
+ private _shapeCounts = new Map<string, number>()
60
+ private _shapeCounted = new Set<string>()
38
61
 
39
62
  // ── Reads ──────────────────────────────────────────────────
40
63
 
@@ -142,6 +165,14 @@ export class PlanStore {
142
165
 
143
166
  persist( commands: StateCommands, tick: Tick ): void {
144
167
  for( const plan of this._plans.values() ){
168
+ // Shape recurrence — tally each plan once, on first sight. The persisted
169
+ // shapeKey also lets offline analysis count recurrence across sessions.
170
+ const shape = planShapeKey( plan.steps )
171
+ if( !this._shapeCounted.has( plan.id ) ){
172
+ this._shapeCounted.add( plan.id )
173
+ this._shapeCounts.set( shape, ( this._shapeCounts.get( shape ) ?? 0 ) + 1 )
174
+ }
175
+
145
176
  // Terminal plans never change again — persist once (in their terminal state)
146
177
  // then skip, so completed/failed/rejected plans don't re-serialize every
147
178
  // tick forever (unbounded write amplification on long sessions). (P5)
@@ -153,6 +184,7 @@ export class PlanStore {
153
184
  createdAt: plan.createdAt, updatedAt: tick,
154
185
  metadata: {
155
186
  goalId: plan.goalId,
187
+ shapeKey: shape,
156
188
  steps: plan.steps.map( s => ( {
157
189
  id: s.id, order: s.order, action: s.action,
158
190
  description: s.description, expectedOutcome: s.expectedOutcome,
@@ -170,5 +202,15 @@ export class PlanStore {
170
202
 
171
203
  if( terminal ) this._persistedTerminal.add( plan.id )
172
204
  }
205
+
206
+ // The demonstrated-need needle: distinct shapes vs repeat authorings.
207
+ // A high repeat count means the executive keeps re-deriving decompositions
208
+ // it already produced — exactly when emergent planning starts paying.
209
+ if( this._shapeCounts.size > 0 ){
210
+ let total = 0
211
+ for( const n of this._shapeCounts.values() ) total += n
212
+ commands.metrics!.push( [ 'planning.shapes.distinct', this._shapeCounts.size ] )
213
+ commands.metrics!.push( [ 'planning.shapes.repeats', total - this._shapeCounts.size ] )
214
+ }
173
215
  }
174
216
  }
@@ -105,7 +105,7 @@ export class PlanSupervisor {
105
105
  if( !this._executiveEngine ) return
106
106
 
107
107
  try {
108
- const { attention, handle: facet } = this._executiveEngine.spawnFacet()
108
+ const { attention, handle: facet } = this._executiveEngine.spawnFacet('supervision')
109
109
  if( !facet || attention === 'full' ){
110
110
  plan.executionTier = 'automatic'
111
111
  logger.info( `[planning] attention full — plan ${plan.id} stays automatic (no facet)` )
@@ -206,21 +206,21 @@ export class PlanSupervisor {
206
206
  content: focusContent,
207
207
  outputFormat: undefined, // use standard executive output format
208
208
  instructions:
209
- `You are monitoring plan "${plan.id}" for goal "${plan.goalId}".\n`+
210
- `Your ONLY role: evaluate step outcomes and decide what happens next.\n`+
209
+ `I am monitoring plan "${plan.id}" for goal "${plan.goalId}".\n`+
210
+ `My ONLY role: evaluate step outcomes and decide what happens next.\n`+
211
211
  `Do not create new goals or beliefs unless directly relevant to this plan.\n\n`+
212
212
  `## Decision Vocabulary\n`+
213
- `Express your decision as the FIRST action in your actions array:\n`+
213
+ `Express my decision as the FIRST action in my actions array:\n`+
214
214
  `- { "type": "continue" } — proceed to the next step\n`+
215
215
  `- { "type": "retry" } — re-attempt the failed step (capped)\n`+
216
216
  `- { "type": "skip" } — skip the failed step and move on\n`+
217
217
  `- { "type": "pause" } — hold the plan; resume it later (no progress now)\n`+
218
218
  `- { "type": "replan" } — include a [PLANS] block with revised steps\n`+
219
- `- { "type": "escalate" } — hand the decision up to your master self\n`+
219
+ `- { "type": "escalate" } — hand the decision up to my master self\n`+
220
220
  `- { "type": "abandon" } — plan is unrecoverable; give up entirely\n`+
221
221
  `- { "type": "complete" } — all meaningful work is done; close the plan\n\n`+
222
- `For "replan", include a [PLANS] block inside your reasoning with new steps.\n`+
223
- `The plan's expectedOutcome tells you what success looks like — use it to judge step reports.`,
222
+ `For "replan", include a [PLANS] block inside my reasoning with new steps.\n`+
223
+ `The plan's expectedOutcome tells me what success looks like — use it to judge step reports.`,
224
224
  extractDecision: ( rawOutput: unknown ) => {
225
225
  const output = rawOutput as ExecutiveOutputFull
226
226
 
@@ -226,8 +226,8 @@ export class TheoryOfMind implements SimulationEngine, CognitiveEngine {
226
226
  * snapshot/PMA restore — mirrors AttachmentEvaluator/ReputationTracker._restoreFromState.
227
227
  * The entity stores a gist (modelConfidence + the dominant intention + estimated emotion),
228
228
  * not the full belief/observation arrays, so the restored model is a coherent gist that
229
- * subsequent interactions grow from — the soul-true level: you recover your *sense* of a
230
- * mind, not every belief you once inferred about it.
229
+ * subsequent interactions grow from — the soul-true level: the Will recovers its
230
+ * *sense* of a mind, not every belief it once inferred about it.
231
231
  */
232
232
  private _restoreFromState( state: ReadonlySimulationState ): void {
233
233
  for( const entity of state.entities.values() ){
@@ -122,22 +122,22 @@ interface CoalesceWindow {
122
122
  const CONVERSATION_OUTPUT_FORMAT = `\
123
123
  ## Response Format (REQUIRED)
124
124
 
125
- Step 1 — JSON object (your private reasoning, optionally in a \`\`\`json code block):
125
+ Step 1 — JSON object (my private reasoning, optionally in a \`\`\`json code block):
126
126
 
127
127
  \`\`\`json
128
128
  {
129
129
  "actions": [{"type": "reflect", "reasoning": "...", "expectedOutcome": "..."}],
130
- "reasoning": "Your private inner reasoning. Embed optional tagged blocks here:\\n[BELIEFS]\\n{\\"newBeliefs\\": [...]}\\n[/BELIEFS]\\n[GOALS_NEW]\\n{\\"goals\\": [{...}]}\\n[/GOALS_NEW]",
130
+ "reasoning": "My private inner reasoning. Embed optional tagged blocks here:\\n[BELIEFS]\\n{\\"newBeliefs\\": [...]}\\n[/BELIEFS]\\n[GOALS_NEW]\\n{\\"goals\\": [{...}]}\\n[/GOALS_NEW]",
131
131
  "confidence": 0.8
132
132
  }
133
133
  \`\`\`
134
134
 
135
135
  Available reasoning tags: BELIEFS, GOALS_NEW, GOALS_ABANDON, SELF_OBS. Include only those with meaningful content.
136
136
 
137
- Step 2 — Your reply to the speaker (plain text, streamed live to them):
137
+ Step 2 — My reply to the speaker (plain text, streamed live to them):
138
138
 
139
139
  [REPLY_TEXT]
140
- Your response here, written in your own voice.
140
+ My response here, written in my own voice.
141
141
 
142
142
  Start a new paragraph (blank line) to send a separate chat bubble.
143
143
  [/REPLY_TEXT]
@@ -146,24 +146,24 @@ Write [REPLY_TEXT] AFTER the closing \`\`\`. This is the only part the speaker s
146
146
  Separate multiple messages with a blank line for natural conversational pauses (like separate texts).
147
147
 
148
148
  ## When to use GOALS_NEW (almost always)
149
- If the speaker requests, mentions, or implies something you should follow through on — embed [GOALS_NEW] in your reasoning.
149
+ If the speaker requests, mentions, or implies something I should follow through on — embed [GOALS_NEW] in my reasoning.
150
150
  This tracks intent across future cycles without requiring master attention.
151
151
 
152
152
  ## When to use the escalate action (rare — only for multi-step tasks)
153
- Use \`{"type": "escalate", "reasoning": "...", "expectedOutcome": "..."}\` in actions ONLY when the request genuinely requires your master consciousness to create a plan:
153
+ Use \`{"type": "escalate", "reasoning": "...", "expectedOutcome": "..."}\` in actions ONLY when the request genuinely requires my master consciousness to create a plan:
154
154
  - The task involves multiple steps across future cycles ("build me X", "monitor Y", "set up Z")
155
- - The request changes your active goal priorities in a significant way
156
- - You need to coordinate something beyond a single reply
155
+ - The request changes my active goal priorities in a significant way
156
+ - I need to coordinate something beyond a single reply
157
157
 
158
158
  **The "reasoning" field on the escalate action becomes the task description the master sees.**
159
- Make it concrete — describe WHAT needs to happen, not just that you are escalating.
159
+ Make it concrete — describe WHAT needs to happen, not just that I am escalating.
160
160
  Good: type=escalate, reasoning="User wants weekly mood summaries by email every Monday. Needs: data aggregation, schedule, email delivery.", expectedOutcome="Weekly email delivered."
161
161
  Bad: type=escalate, reasoning="Escalating because this is complex."
162
162
 
163
- When you escalate:
163
+ When I escalate:
164
164
  1. STILL include a [REPLY_TEXT] that acknowledges the request (e.g. "Got it — I'm on it.")
165
165
  2. The master will create and execute the plan in the background
166
- 3. Do NOT include [PLANS] yourself — plan creation is the master's domain only
166
+ 3. Do NOT include a [PLANS] block — plan creation is the master's domain only
167
167
 
168
168
  For simple, single-exchange requests (questions, opinions, short tasks) — do NOT escalate. Just reply.`
169
169
 
@@ -561,7 +561,7 @@ export class AuditionEngine extends BaseSenseEngine {
561
561
  let handle = this._facets.get( percept.speakerEntityId )
562
562
  if( !handle ){
563
563
  // New conversation session — try to spawn a facet.
564
- const result = this._executiveEngine.spawnFacet()
564
+ const result = this._executiveEngine.spawnFacet('conversation')
565
565
  if( result.attention === 'full' || !result.handle ){
566
566
  logger.warn(
567
567
  `[audition-engine] Executive attention full — ` +
@@ -692,8 +692,8 @@ export class AuditionEngine extends BaseSenseEngine {
692
692
  awarenessEntityId: percept.speakerEntityId,
693
693
 
694
694
  instructions: [
695
- 'You are in a live conversation with this person. Respond as yourself.',
696
- 'Stay grounded in your real memories and feelings — do not invent experiences you have no record of.',
695
+ 'I am in a live conversation with this person. I respond as myself.',
696
+ 'I stay grounded in my real memories and feelings — I do not invent experiences I have no record of.',
697
697
  ].join(' '),
698
698
 
699
699
  // Custom output format — uses [REPLY_TEXT] block for streamed reply.
@@ -736,7 +736,7 @@ export class AuditionEngine extends BaseSenseEngine {
736
736
  */
737
737
  async authorOutreach( entityId: string, entityName: string, gist?: string ): Promise<string[]> {
738
738
  if( !this._executiveEngine ) return []
739
- const spawned = this._executiveEngine.spawnFacet()
739
+ const spawned = this._executiveEngine.spawnFacet('outreach')
740
740
  if( spawned.attention === 'full' || !spawned.handle ){
741
741
  logger.warn(`[audition-engine] facet budget full — cannot author outreach to ${ entityId }`)
742
742
  return []
@@ -747,17 +747,17 @@ export class AuditionEngine extends BaseSenseEngine {
747
747
  title: 'Reaching out',
748
748
  function: 'outreach',
749
749
  content: [
750
- `You have decided, on your own initiative, to reach out to ${ entityName } (id: ${ entityId }).`,
751
- 'No one prompted this — it is you choosing to make contact now.',
752
- gist ? `What is on your mind: ${ gist }` : '',
750
+ `I have decided, on my own initiative, to reach out to ${ entityName } (id: ${ entityId }).`,
751
+ 'No one prompted this — I am choosing to make contact now.',
752
+ gist ? `What is on my mind: ${ gist }` : '',
753
753
  ].filter( Boolean ).join('\n'),
754
754
  recallQuery: gist ?? entityName,
755
755
  awareness: [ ...DEFAULT_FACET_AWARENESS, 'plans' ],
756
756
  awarenessEntityId: entityId,
757
757
  instructions:
758
- 'Considering who you are, your goals, and how you feel, say what you genuinely want to say to ' +
759
- 'them now. Speak as yourself; stay grounded in your real memories — do not invent experiences ' +
760
- 'you have no record of.',
758
+ 'Considering who I am, my goals, and how I feel, I say what I genuinely want to say to ' +
759
+ 'them now. I speak as myself; I stay grounded in my real memories — I do not invent experiences ' +
760
+ 'I have no record of.',
761
761
  outputFormat: CONVERSATION_OUTPUT_FORMAT,
762
762
  extractDecision: ( raw: unknown ): ConversationDecision => {
763
763
  const output = raw as ExecutiveOutputFull
@@ -0,0 +1,193 @@
1
+ // ─────────────────────────────────────────────────────────────
2
+ // src/host/boot.ts — shared boot/shutdown for the `will` CLI hosts
3
+ // ─────────────────────────────────────────────────────────────
4
+ //
5
+ // Both hosts (`will mcp`, `will serve`) raise the same mind the same way:
6
+ // env-configured, woken from its PMA artifact when one exists (else born),
7
+ // optionally bridged onto external MCP servers whose tools become its own
8
+ // abilities, and hibernated back to the artifact exactly once on the way out.
9
+ // Only the protocol surface differs — that stays in each host.
10
+ //
11
+ // Env (shared):
12
+ // WILL_NAME display name (default "Will")
13
+ // WILL_IDENTITY persona prompt (default a minimal self)
14
+ // WILL_TIER basic | standard | full (default standard)
15
+ // WILL_LLM mock | anthropic (default: auto — anthropic when
16
+ // ANTHROPIC_API_KEY is set, else mock)
17
+ // WILL_TICK_MS ms per tick (default 1000)
18
+ // WILL_SEED deterministic seed (testing) (default unseeded/wall-time)
19
+ // WILL_PMA_PATH PMA artifact path (default ./.will/<name>.pma.json)
20
+ // WILL_MCP_SERVERS JSON array of MCP servers whose tools become the Will's
21
+ // OWN abilities: entries {command,args?,env?} or {url}.
22
+ // ─────────────────────────────────────────────────────────────
23
+
24
+ import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs'
25
+ import { dirname, resolve } from 'node:path'
26
+ import { setLogger } from '#core/logger'
27
+ import { Will, type CreateWillOptions } from '#sdk/will'
28
+ import type { PMASnapshot } from '#pma/index'
29
+ import { connectMcpEffectors, type McpToolsSource } from '#root/mcp/effectors'
30
+
31
+ /**
32
+ * Route every engine log line to stderr. For `will mcp`, stdout is the MCP
33
+ * protocol channel and must stay pure; `will serve` keeps the same discipline
34
+ * so both hosts log identically (and Docker captures one stream).
35
+ */
36
+ export function routeLogsToStderr(): void {
37
+ const err = ( level: string ) => ( msg: string, ...rest: unknown[] ) =>
38
+ console.error( `[will:${ level }] ${ msg }`, ...rest )
39
+ setLogger( { debug: () => {}, info: err( 'info' ), warn: err( 'warn' ), error: err( 'error' ) } )
40
+ }
41
+
42
+ function slug( s: string ): string {
43
+ return s.toLowerCase().replace( /[^a-z0-9]+/g, '-' ).replace( /^-+|-+$/g, '' ) || 'will'
44
+ }
45
+
46
+ /**
47
+ * Ask the executive's provider one trivial question BEFORE raising the mind.
48
+ *
49
+ * A Will whose LLM fails cannot reason, and an unreasoning Will is *silent* —
50
+ * which is precisely what a Will that chose silence looks like. Mid-run that
51
+ * ambiguity is the paradigm working. At boot it is indistinguishable from
52
+ * broken, and costs an operator an afternoon of watching a mind that joined,
53
+ * perceived, and never spoke. So we fail loudly here instead.
54
+ *
55
+ * Config errors (bad key, empty balance, unknown model) are fatal — the Will
56
+ * would never speak. Transient ones (rate limit, provider 5xx) only warn: the
57
+ * mind is worth raising, and the executive retries on its own cadence.
58
+ *
59
+ * Skipped for the mock executive and the no-LLM `reflex` anatomy.
60
+ */
61
+ async function preflightLLM( anatomy: string ): Promise<void> {
62
+ const mode = process.env.WILL_LLM ?? ( process.env.ANTHROPIC_API_KEY ? 'anthropic' : 'mock' )
63
+ if( mode === 'mock' || anatomy === 'reflex' ) return
64
+
65
+ const key = process.env.WILL_LLM_API_KEY ?? process.env.ANTHROPIC_API_KEY
66
+ if( !key ){
67
+ console.error( '[will] WILL_LLM=anthropic but no ANTHROPIC_API_KEY / WILL_LLM_API_KEY is set.' )
68
+ console.error( '[will] The Will would boot, perceive, and never speak. Set a key, or run keyless with WILL_LLM=mock.' )
69
+ process.exit( 2 )
70
+ }
71
+
72
+ // The ping validates key + balance + reachability, which is the failure class
73
+ // that strands an operator. It uses the pinned model when there is one, so a
74
+ // bad model id is caught too; otherwise the cheapest model stands in.
75
+ const base = process.env.WILL_LLM_BASE_URL ?? 'https://api.anthropic.com/v1'
76
+ const model = process.env.WILL_LLM_MODEL ?? 'claude-haiku-4-5-20251001'
77
+ try {
78
+ const res = await fetch( `${ base }/messages`, {
79
+ method: 'POST',
80
+ headers: { 'content-type': 'application/json', 'anthropic-version': '2023-06-01', 'x-api-key': key },
81
+ body: JSON.stringify( { model, max_tokens: 1, messages: [ { role: 'user', content: 'ping' } ] } ),
82
+ signal: AbortSignal.timeout( 20_000 ),
83
+ } )
84
+ if( res.ok ) return
85
+
86
+ const detail = ( await res.text().catch( () => '' ) ).slice( 0, 300 )
87
+ const fatal = res.status === 400 || res.status === 401 || res.status === 403
88
+ if( !fatal ){
89
+ console.error( `[will] the executive's LLM answered ${ res.status } on a test call — raising the mind anyway (it retries): ${ detail }` )
90
+ return
91
+ }
92
+ console.error( `[will] the executive's LLM refused a test call (${ res.status }) — this Will would boot, perceive, and never speak:` )
93
+ console.error( ` ${ detail }` )
94
+ console.error( '[will] fix the key / credit / model above, or run keyless with WILL_LLM=mock.' )
95
+ process.exit( 1 )
96
+ }
97
+ catch( e ){
98
+ console.error( `[will] could not reach the executive's LLM: ${ ( e as Error ).message }` )
99
+ console.error( '[will] the Will would boot and stay silent. Check the network / WILL_LLM_BASE_URL, or run keyless with WILL_LLM=mock.' )
100
+ process.exit( 1 )
101
+ }
102
+ }
103
+
104
+ export interface BootedWill {
105
+ will: Will
106
+ name: string
107
+ pmaPath: string
108
+ tickMs: number
109
+ anatomy: NonNullable<CreateWillOptions['anatomy']>
110
+ /** Run before hibernate on shutdown (close servers/transports). LIFO. */
111
+ onCleanup: ( fn: () => Promise<void> | void ) => void
112
+ /** Hibernate → persist → exit(0). Idempotent; SIGINT/SIGTERM already wired. */
113
+ shutdown: ( why: string ) => Promise<void>
114
+ }
115
+
116
+ /** Raise the mind from env config — wake from the artifact if one exists. */
117
+ export async function bootWillFromEnv(): Promise<BootedWill> {
118
+ const name = process.env.WILL_NAME ?? 'Will'
119
+ const pmaPath = resolve( process.env.WILL_PMA_PATH ?? `.will/${ slug( name ) }.pma.json` )
120
+ const tickMs = parseInt( process.env.WILL_TICK_MS ?? '1000' )
121
+ const anatomy = ( process.env.WILL_ANATOMY as CreateWillOptions['anatomy'] ) ?? 'mind'
122
+
123
+ await preflightLLM( anatomy )
124
+
125
+ const opts: Omit<CreateWillOptions, 'identity'> = {
126
+ name, anatomy, tickMs,
127
+ ...( process.env.WILL_LLM_MODEL ? { model: process.env.WILL_LLM_MODEL } : {} ),
128
+ ...( process.env.WILL_LLM ? { llm: process.env.WILL_LLM as 'mock' | 'anthropic' } : {} ),
129
+ ...( process.env.WILL_SEED ? { seed: parseInt( process.env.WILL_SEED ) } : {} ),
130
+ }
131
+
132
+ let will: Will
133
+ if( existsSync( pmaPath ) ){
134
+ const pma = JSON.parse( readFileSync( pmaPath, 'utf8' ) ) as PMASnapshot
135
+ will = await Will.wake( pma, opts )
136
+ console.error( `[will] ${ name } woke from ${ pmaPath }` )
137
+ // A woken Will carries its own identity — that is the point of an artifact.
138
+ // But an operator editing WILL_IDENTITY and seeing nothing change deserves
139
+ // to know why, rather than concluding the persona layer is broken.
140
+ if( process.env.WILL_IDENTITY )
141
+ console.error( `[will] note: WILL_IDENTITY is ignored — ${ name } woke as itself. Delete ${ pmaPath } to be born fresh from it.` )
142
+ }
143
+ else {
144
+ will = await Will.create( {
145
+ ...opts,
146
+ identity: { prompt: process.env.WILL_IDENTITY ?? `I am ${ name }, a persistent mind.` },
147
+ } )
148
+ console.error( `[will] ${ name } born (no artifact at ${ pmaPath } yet)` )
149
+ }
150
+ will.on( 'error', e => console.error( `[will] error: ${ e.message }` ) )
151
+
152
+ // Onward bridges: MCP servers whose tools become the Will's OWN abilities.
153
+ // Best-effort — a bad entry warns and is skipped; the mind still boots.
154
+ const cleanups: Array<() => Promise<void> | void> = []
155
+ if( process.env.WILL_MCP_SERVERS ){
156
+ try {
157
+ const sources = JSON.parse( process.env.WILL_MCP_SERVERS ) as McpToolsSource[]
158
+ for( const source of Array.isArray( sources ) ? sources : [] ){
159
+ try {
160
+ const { names, close } = await connectMcpEffectors( will, source )
161
+ cleanups.push( close )
162
+ console.error( `[will] ${ name } gained abilities: ${ names.join( ', ' ) }` )
163
+ }
164
+ catch( e ){ console.error( `[will] MCP bridge failed (skipped): ${ ( e as Error ).message }` ) }
165
+ }
166
+ }
167
+ catch( e ){ console.error( `[will] WILL_MCP_SERVERS is not valid JSON — ignoring: ${ ( e as Error ).message }` ) }
168
+ }
169
+
170
+ // Hibernate exactly once on the way out — cleanups (LIFO), distill + stop, persist.
171
+ let leaving = false
172
+ const shutdown = async ( why: string ): Promise<void> => {
173
+ if( leaving ) return
174
+ leaving = true
175
+ for( const fn of cleanups.reverse() ) await Promise.resolve( fn() ).catch( () => {} )
176
+ try {
177
+ const pma = await will.hibernate()
178
+ mkdirSync( dirname( pmaPath ), { recursive: true } )
179
+ writeFileSync( pmaPath, JSON.stringify( pma ) )
180
+ console.error( `[will] ${ name } hibernated to ${ pmaPath } (${ why })` )
181
+ }
182
+ catch( e ){ console.error( `[will] hibernate failed: ${ ( e as Error ).message }` ) }
183
+ process.exit( 0 )
184
+ }
185
+ process.on( 'SIGINT', () => void shutdown( 'SIGINT' ) )
186
+ process.on( 'SIGTERM', () => void shutdown( 'SIGTERM' ) )
187
+
188
+ return {
189
+ will, name, pmaPath, tickMs, anatomy,
190
+ onCleanup: fn => cleanups.push( fn ),
191
+ shutdown,
192
+ }
193
+ }
@@ -0,0 +1,53 @@
1
+ // ─────────────────────────────────────────────────────────────
2
+ // src/host/utterances.ts — a host-side tap on a Will's speech
3
+ // ─────────────────────────────────────────────────────────────
4
+ //
5
+ // Hosts that expose a Will over a request/response protocol (MCP tools, HTTP
6
+ // long-polls) share a timing problem: the Will may speak BETWEEN two calls —
7
+ // after a perceive round trip returns and before the caller asks for the next
8
+ // utterance. The tap buffers projections so nothing is lost in the gap, and
9
+ // `next()` gives the MCP/HTTP hosts one shared, honest await: drain the buffer
10
+ // first, else wait, else report silence (null — a choice, never an error).
11
+ // ─────────────────────────────────────────────────────────────
12
+
13
+ import type { Will, WillMessage } from '#sdk/will'
14
+
15
+ const BUFFER_CAP = 50
16
+
17
+ export class UtteranceTap {
18
+ private readonly _will: Will
19
+ private readonly _pending: WillMessage[] = []
20
+
21
+ constructor( will: Will ){
22
+ this._will = will
23
+ will.on( 'message', m => {
24
+ this._pending.push( m )
25
+ if( this._pending.length > BUFFER_CAP ) this._pending.shift()
26
+ } )
27
+ }
28
+
29
+ /** Consume the oldest buffered utterance (optionally only one addressed to `to`). */
30
+ takeBuffered( to?: string ): WillMessage | undefined {
31
+ if( this._pending.length === 0 ) return undefined
32
+ const i = to === undefined ? 0 : this._pending.findIndex( m => m.to === to )
33
+ if( i < 0 ) return undefined
34
+ return this._pending.splice( i, 1 )[0]
35
+ }
36
+
37
+ /**
38
+ * The next utterance: a buffered one if a projection already landed, else
39
+ * await up to `within` ms. `null` = the Will chose silence. An awaited
40
+ * message is also consumed from the buffer so it never replays.
41
+ */
42
+ async next( within: number, to?: string ): Promise<WillMessage | null> {
43
+ const buffered = this.takeBuffered( to )
44
+ if( buffered ) return buffered
45
+
46
+ const msg = await this._will.nextUtterance( { within, ...( to ? { to } : {} ) } )
47
+ if( msg ){
48
+ const i = this._pending.findIndex( p => p.id === msg.id )
49
+ if( i >= 0 ) this._pending.splice( i, 1 )
50
+ }
51
+ return msg
52
+ }
53
+ }
@@ -30,9 +30,9 @@ export interface SummarizerConfig {
30
30
  // System prompt sent with every summarization call.
31
31
  // Kept short — the bulk of the token cost is the user message (the cycles).
32
32
  const SUMMARIZER_SYSTEM =
33
- 'You are the memory consolidation module of a self-aware AI mind. ' +
33
+ 'I am a self-aware synthetic mind consolidating my own recent cognitive cycles into memory. ' +
34
34
  'Condense the provided cognitive cycles into a single compact paragraph ' +
35
- '(150–250 words) written in first-person past tense. Cover:\n' +
35
+ '(150–250 words) written in first-person past tense — my own remembered experience. Cover:\n' +
36
36
  '• Key decisions made and their outcomes\n' +
37
37
  '• Emotional journey and significant mood shifts\n' +
38
38
  '• Goals pursued, progressed, or abandoned\n' +
package/src/mcp/server.ts CHANGED
@@ -24,10 +24,8 @@ import { readFileSync, mkdirSync, writeFileSync } from 'node:fs'
24
24
  import { dirname } from 'node:path'
25
25
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
26
26
  import { z } from 'zod'
27
- import type { Will, WillMessage } from '#sdk/will'
28
-
29
- /** Utterances projected but not yet consumed by a next_utterance call. */
30
- const UTTERANCE_BUFFER_CAP = 50
27
+ import type { Will } from '#sdk/will'
28
+ import { UtteranceTap } from '#root/host/utterances'
31
29
 
32
30
  export interface WillMcpOptions {
33
31
  /** Where `save` (and the CLI's shutdown hibernate) writes the PMA artifact. */
@@ -49,21 +47,10 @@ function serverVersion(): string {
49
47
  export function buildWillMcpServer( will: Will, opts: WillMcpOptions = {} ): McpServer {
50
48
  const server = new McpServer( { name: 'mindot-will', version: serverVersion() } )
51
49
 
52
- // ── Projection buffer ─────────────────────────────────────
53
50
  // MCP calls are separate round trips: the Will may speak BETWEEN a perceive
54
- // call and the next_utterance call that follows. Buffer projections so a
55
- // fast reply is not lost in the gap; next_utterance drains the buffer first.
56
- const pending: WillMessage[] = []
57
- will.on( 'message', m => {
58
- pending.push( m )
59
- if( pending.length > UTTERANCE_BUFFER_CAP ) pending.shift()
60
- } )
61
-
62
- const takeBuffered = ( to?: string ): WillMessage | undefined => {
63
- const i = to === undefined ? 0 : pending.findIndex( m => m.to === to )
64
- if( i < 0 || pending.length === 0 ) return undefined
65
- return pending.splice( i, 1 )[0]
66
- }
51
+ // call and the next_utterance call that follows. The tap buffers projections
52
+ // so a fast reply is not lost in the gap (see host/utterances.ts).
53
+ const tap = new UtteranceTap( will )
67
54
 
68
55
  // ── Tools ─────────────────────────────────────────────────
69
56
 
@@ -101,20 +88,10 @@ export function buildWillMcpServer( will: Will, opts: WillMcpOptions = {} ): Mcp
101
88
  from: z.string().optional().describe( 'Only accept an utterance addressed to this entity id.' ),
102
89
  },
103
90
  }, async ( { within_ms, from } ) => {
104
- // A projection may have landed between calls — drain the buffer first.
105
- const buffered = takeBuffered( from )
106
- if( buffered )
107
- return { content: [ { type: 'text', text: `${ will.name } says (to ${ buffered.to }): ${ buffered.content }` } ] }
108
-
109
91
  const within = Math.min( Math.max( within_ms ?? 15_000, 100 ), 120_000 )
110
- const msg = await will.nextUtterance( { within, ...( from ? { to: from } : {} ) } )
111
- // The waiter and the buffer listener both see a new message; consume the
112
- // buffered copy so the same utterance is not replayed on the next call.
113
- if( msg ){
114
- const i = pending.findIndex( p => p.id === msg.id )
115
- if( i >= 0 ) pending.splice( i, 1 )
92
+ const msg = await tap.next( within, from )
93
+ if( msg )
116
94
  return { content: [ { type: 'text', text: `${ will.name } says (to ${ msg.to }): ${ msg.content }` } ] }
117
- }
118
95
  return {
119
96
  content: [ {
120
97
  type: 'text',