@mindot/will 0.4.0 → 0.6.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 (135) hide show
  1. package/README.md +32 -12
  2. package/dist/channels/discord.d.ts +2 -11
  3. package/dist/channels/discord.js.map +1 -1
  4. package/dist/channels/whatsapp.d.ts +72 -0
  5. package/dist/channels/whatsapp.js +252 -0
  6. package/dist/channels/whatsapp.js.map +1 -0
  7. package/dist/cli.js +837 -91
  8. package/dist/cli.js.map +1 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.js +620 -79
  11. package/dist/index.js.map +1 -1
  12. package/dist/mcp/effectors.d.ts +1 -1
  13. package/dist/mcp/effectors.js.map +1 -1
  14. package/dist/types-E9-HV-SW.d.ts +11 -0
  15. package/dist/{will-D-slky1N.d.ts → will-Bikuk4s2.d.ts} +56 -12
  16. package/package.json +12 -3
  17. package/src/channels/discord.ts +11 -11
  18. package/src/channels/roster.ts +1 -1
  19. package/src/channels/types.ts +1 -1
  20. package/src/channels/whatsapp.ts +318 -0
  21. package/src/cli.ts +46 -23
  22. package/src/cognition/acp.ts +28 -0
  23. package/src/cognition/agency/consequence.ts +174 -0
  24. package/src/cognition/agency/engines/action.selector.ts +301 -48
  25. package/src/cognition/agency/engines/affordance.synthesizer.ts +26 -16
  26. package/src/cognition/agency/engines/deliberation.engine.ts +28 -14
  27. package/src/cognition/agency/engines/motor.schema.executor.ts +86 -14
  28. package/src/cognition/agency/engines/reafference.engine.ts +122 -18
  29. package/src/cognition/agency/execution.primitives.ts +13 -13
  30. package/src/cognition/agency/proactive.communicator.ts +1 -1
  31. package/src/cognition/agency/reconcile.learning.ts +1 -1
  32. package/src/cognition/agency/revocation.ts +79 -0
  33. package/src/cognition/agency/schemas/repertoire.ts +2 -2
  34. package/src/cognition/agency/selection.scoring.ts +25 -9
  35. package/src/cognition/bus.ts +2 -2
  36. package/src/cognition/completion.inbox.ts +1 -1
  37. package/src/cognition/config.mirror.entities.ts +5 -5
  38. package/src/cognition/event.log.ts +2 -2
  39. package/src/cognition/event.schemas.ts +67 -67
  40. package/src/cognition/faculties/aesthetic.evaluator.ts +6 -6
  41. package/src/cognition/faculties/affective.blender.ts +36 -4
  42. package/src/cognition/faculties/attachment.evaluator.ts +6 -6
  43. package/src/cognition/faculties/attention.allocator.ts +63 -8
  44. package/src/cognition/faculties/autobiographical.narrator.ts +3 -3
  45. package/src/cognition/faculties/bias.detector.ts +7 -7
  46. package/src/cognition/faculties/circadian.oscillator.ts +3 -3
  47. package/src/cognition/faculties/confidence.calibrator.ts +7 -7
  48. package/src/cognition/faculties/dream.simulator.ts +5 -5
  49. package/src/cognition/faculties/empathy.simulator.ts +7 -7
  50. package/src/cognition/faculties/energy.regulator.ts +4 -4
  51. package/src/cognition/faculties/episodic.consolidator.ts +6 -6
  52. package/src/cognition/faculties/executive.engine/commands.ts +6 -6
  53. package/src/cognition/faculties/executive.engine/context.ts +42 -42
  54. package/src/cognition/faculties/executive.engine/deferred.effects.ts +2 -2
  55. package/src/cognition/faculties/executive.engine/engine.ts +27 -26
  56. package/src/cognition/faculties/executive.engine/facet.supervisor.ts +12 -12
  57. package/src/cognition/faculties/executive.engine/facet.ts +18 -18
  58. package/src/cognition/faculties/executive.engine/gating.ts +2 -2
  59. package/src/cognition/faculties/executive.engine/messages.ts +3 -3
  60. package/src/cognition/faculties/executive.engine/parser.ts +11 -11
  61. package/src/cognition/faculties/executive.engine/prompt.factory.ts +55 -55
  62. package/src/cognition/faculties/exteroception.ts +99 -5
  63. package/src/cognition/faculties/forgetting.curve.ts +3 -3
  64. package/src/cognition/faculties/frustration.evaluator.ts +6 -6
  65. package/src/cognition/faculties/goal.manager.ts +15 -15
  66. package/src/cognition/faculties/inhibition.controller.ts +3 -3
  67. package/src/cognition/faculties/interoception.ts +3 -3
  68. package/src/cognition/faculties/introspection.engine.ts +3 -3
  69. package/src/cognition/faculties/known.entity.tracker.ts +15 -15
  70. package/src/cognition/faculties/loss.evaluator.ts +2 -2
  71. package/src/cognition/faculties/moral.evaluator.ts +4 -4
  72. package/src/cognition/faculties/novelty.detector.ts +4 -4
  73. package/src/cognition/faculties/persona.consolidator.ts +12 -12
  74. package/src/cognition/faculties/planning.engine/engine.ts +47 -47
  75. package/src/cognition/faculties/planning.engine/plan.frontier.ts +5 -5
  76. package/src/cognition/faculties/planning.engine/plan.store.ts +1 -1
  77. package/src/cognition/faculties/planning.engine/plan.supervision.ts +20 -20
  78. package/src/cognition/faculties/reputation.tracker.ts +6 -6
  79. package/src/cognition/faculties/reward.evaluator.ts +4 -4
  80. package/src/cognition/faculties/self.model.updater.ts +8 -8
  81. package/src/cognition/faculties/semantic.engine/integrator.ts +15 -15
  82. package/src/cognition/faculties/sleep.pressure.regulator.ts +4 -4
  83. package/src/cognition/faculties/social.perception.ts +3 -3
  84. package/src/cognition/faculties/spaced.repetition.ts +2 -2
  85. package/src/cognition/faculties/stress.regulator.ts +27 -4
  86. package/src/cognition/faculties/task.switcher.ts +11 -6
  87. package/src/cognition/faculties/theory.of.mind.ts +6 -6
  88. package/src/cognition/faculties/threat.evaluator.ts +3 -3
  89. package/src/cognition/faculties/working.memory.ts +8 -8
  90. package/src/cognition/generative.model.ts +2 -2
  91. package/src/cognition/memory/vector.adapter.ts +5 -5
  92. package/src/cognition/memory/vector.content.ts +4 -4
  93. package/src/cognition/memory/vector.embedder.ts +9 -9
  94. package/src/cognition/persona.prior.ts +1 -1
  95. package/src/cognition/schema.registry.ts +2 -2
  96. package/src/cognition/senses/audition.engine/engine.ts +2 -2
  97. package/src/cognition/senses/base.sense.engine.ts +1 -1
  98. package/src/cognition/utilities/token.tracker.ts +11 -5
  99. package/src/core/abstracts.ts +1 -1
  100. package/src/core/completion.recorder.ts +2 -2
  101. package/src/core/serialization.ts +3 -3
  102. package/src/core/snapshot.manager.ts +1 -1
  103. package/src/core/state.manager.ts +1 -1
  104. package/src/core/utils.ts +1 -1
  105. package/src/host/boot.ts +59 -37
  106. package/src/host/utterances.ts +1 -1
  107. package/src/llm/index.ts +84 -34
  108. package/src/llm/summarizer.ts +4 -4
  109. package/src/llm/wire.contracts.ts +1 -1
  110. package/src/mcp/effectors.ts +10 -10
  111. package/src/mcp/server.ts +11 -11
  112. package/src/pma/eval.ts +1 -1
  113. package/src/pma/index.ts +21 -21
  114. package/src/runners/outreach.runner.ts +3 -3
  115. package/src/runners/social.runner.ts +1 -1
  116. package/src/runners/thin-shim.runner.ts +1 -1
  117. package/src/sdk/will.ts +20 -11
  118. package/src/serve/server.ts +12 -12
  119. package/src/stem/assembly.audit.ts +3 -3
  120. package/src/stem/guards/identity.coherence.ts +13 -12
  121. package/src/stem/guards/identity.guard.ts +22 -22
  122. package/src/stem/index.ts +11 -11
  123. package/src/stem/mind.ts +12 -12
  124. package/src/stem/tracts/biography.writer.ts +3 -3
  125. package/src/stem/tracts/effector.controller.ts +4 -4
  126. package/src/stem/tracts/health.reporter.ts +1 -1
  127. package/src/stem/tracts/outbox.controller.ts +4 -0
  128. package/src/stem/tracts/outbox.writer.ts +4 -4
  129. package/src/stem/tracts/pma.controller.ts +1 -1
  130. package/src/stem/tracts/replay.controller.ts +10 -10
  131. package/src/stem/tracts/sensory.controller.ts +2 -2
  132. package/src/stem/tracts/session.logger.ts +4 -4
  133. package/src/stem/tracts/transport/socketio.transport.ts +7 -7
  134. package/src/stem/tracts/transport/stream.transport.ts +2 -2
  135. package/src/stem/tracts/transport.controller.ts +15 -15
package/dist/index.js CHANGED
@@ -2814,6 +2814,11 @@ var MODEL_PRICING = {
2814
2814
  // Legacy aliases kept for backward compat
2815
2815
  "anthropic/claude-haiku-4": { input: 1, output: 5 },
2816
2816
  "anthropic/claude-opus-4": { input: 5, output: 25 },
2817
+ // Z.ai (GLM-5 family). `glm-5.2[1m]` is the same model asking for its 1M
2818
+ // context window — same rate, so it gets its own row rather than relying on
2819
+ // the normalizer (a future long-context tier would price differently).
2820
+ "glm/glm-5.2": { input: 1.4, output: 4.4 },
2821
+ "glm/glm-5.2[1m]": { input: 1.4, output: 4.4 },
2817
2822
  // Google
2818
2823
  "google/gemini-2.0-flash": { input: 0.1, output: 0.4 },
2819
2824
  "google/gemini-2.0-pro": { input: 1.25, output: 5 },
@@ -3602,6 +3607,9 @@ var SleepPressureRegulator = class {
3602
3607
  }
3603
3608
  };
3604
3609
 
3610
+ // src/cognition/acp.ts
3611
+ var ACP_SELF_PRECISION = 0.35;
3612
+
3605
3613
  // src/cognition/persona.prior.ts
3606
3614
  var PERSONA_PRIOR_ID = "persona-prior";
3607
3615
  var PERSONA_PRIOR_TYPE = "persona.prior";
@@ -3710,6 +3718,8 @@ function consolidatePrior(current, adjustments, tick, opts = {}) {
3710
3718
  }
3711
3719
 
3712
3720
  // src/cognition/faculties/attention.allocator.ts
3721
+ var ACP_USAGE_UPLIFT = 0.15;
3722
+ var ACP_CONFIDENCE = 0.4;
3713
3723
  var EFFORT_BASELINE2 = 0.7;
3714
3724
  var EFFORT_MIN = 0.4;
3715
3725
  var EFFORT_MAX = 1;
@@ -3731,6 +3741,8 @@ var AttentionAllocator = class {
3731
3741
  _effort = EFFORT_BASELINE2;
3732
3742
  /** A one-shot focus/rest request from the executive, applied next react(). */
3733
3743
  _effortRequest = null;
3744
+ /** ACP-P2: a self-caused precision attenuation is armed; react() restores after one observe. */
3745
+ _acpOneShot = false;
3734
3746
  _bus = null;
3735
3747
  _model = new GenerativeModel();
3736
3748
  constructor(config = {}) {
@@ -3751,8 +3763,12 @@ var AttentionAllocator = class {
3751
3763
  "executive.prediction.formed",
3752
3764
  "attention.regulate",
3753
3765
  // voluntary focus/rest from the executive (Option C)
3754
- "senses.*"
3766
+ "senses.*",
3755
3767
  // all sense percepts — salience feeds attention allocation
3768
+ // ACP-P2: our own enactions — anticipate the attention swing they cause
3769
+ "agency.enacted",
3770
+ "agency.communicate",
3771
+ "agency.invocation"
3756
3772
  ];
3757
3773
  }
3758
3774
  publishes() {
@@ -3779,6 +3795,18 @@ var AttentionAllocator = class {
3779
3795
  this._model.setPrecision("attention.usage", 1 + p.confidence * 0.5);
3780
3796
  break;
3781
3797
  }
3798
+ case "agency.enacted":
3799
+ case "agency.communicate":
3800
+ case "agency.invocation": {
3801
+ const usage = this._model.predict("attention.usage");
3802
+ const free = this._model.predict("attention.free_fraction");
3803
+ this._model.anticipate("attention.usage", Math.min(1, usage + ACP_USAGE_UPLIFT), ACP_CONFIDENCE);
3804
+ this._model.anticipate("attention.free_fraction", Math.max(0, free - ACP_USAGE_UPLIFT), ACP_CONFIDENCE);
3805
+ this._model.setPrecision("attention.usage", ACP_SELF_PRECISION);
3806
+ this._model.setPrecision("attention.free_fraction", ACP_SELF_PRECISION);
3807
+ this._acpOneShot = true;
3808
+ break;
3809
+ }
3782
3810
  default:
3783
3811
  if (e.type.startsWith("senses.")) {
3784
3812
  const percept = e.payload;
@@ -3862,6 +3890,11 @@ var AttentionAllocator = class {
3862
3890
  if (_bus) {
3863
3891
  const usageErr = this._model.observe("attention.usage", attentionUsage);
3864
3892
  const freeErr = this._model.observe("attention.free_fraction", freeFraction);
3893
+ if (this._acpOneShot) {
3894
+ this._model.setPrecision("attention.usage", 1);
3895
+ this._model.setPrecision("attention.free_fraction", 1);
3896
+ this._acpOneShot = false;
3897
+ }
3865
3898
  if (!usageErr.gated || !freeErr.gated)
3866
3899
  _bus.publish({ type: "attention.state.changed", version: 1, sourceEngine: this.name, salience: Math.max(usageErr.salience, freeErr.salience), payload: { usage: attentionUsage, focusCount, capacity: effectiveCapacity, freeFraction } });
3867
3900
  }
@@ -3981,7 +4014,18 @@ var StressRegulator = class {
3981
4014
  }
3982
4015
  // ── Engine interface ─────────────────────────────────────
3983
4016
  subscribes() {
3984
- return ["energy.state.changed", "sleep.state.changed", "novelty.state.changed", "goal.state.changed", "metacognition.state.changed", "executive.prediction.formed"];
4017
+ return [
4018
+ "energy.state.changed",
4019
+ "sleep.state.changed",
4020
+ "novelty.state.changed",
4021
+ "goal.state.changed",
4022
+ "metacognition.state.changed",
4023
+ "executive.prediction.formed",
4024
+ // ACP-P2: our own enactions — the stress swing they cause is expected
4025
+ "agency.enacted",
4026
+ "agency.communicate",
4027
+ "agency.invocation"
4028
+ ];
3985
4029
  }
3986
4030
  publishes() {
3987
4031
  return [];
@@ -4010,8 +4054,17 @@ var StressRegulator = class {
4010
4054
  this._model.setPrecision("stress.load", 1 + p.confidence * 0.5);
4011
4055
  break;
4012
4056
  }
4057
+ case "agency.enacted":
4058
+ case "agency.communicate":
4059
+ case "agency.invocation": {
4060
+ this._model.setPrecision("stress.load", ACP_SELF_PRECISION);
4061
+ this._acpOneShot = true;
4062
+ break;
4063
+ }
4013
4064
  }
4014
4065
  }
4066
+ /** ACP-P2: self-caused stress attenuation armed; react() restores after one observe. */
4067
+ _acpOneShot = false;
4015
4068
  snapshot() {
4016
4069
  return {
4017
4070
  energyLevel: this._energyLevel,
@@ -4104,6 +4157,10 @@ var StressRegulator = class {
4104
4157
  if (_bus) {
4105
4158
  const zoneCode = zone === "low" ? 0 : zone === "optimal" ? 1 : zone === "distress" ? 2 : 3;
4106
4159
  const predErr = this._model.observe("stress.load", newLoad);
4160
+ if (this._acpOneShot) {
4161
+ this._model.setPrecision("stress.load", 1);
4162
+ this._acpOneShot = false;
4163
+ }
4107
4164
  if (!predErr.gated || zone !== previousZone) {
4108
4165
  _bus.publish({ type: "stress.state.changed", version: 1, sourceEngine: this.name, salience: predErr.salience, payload: { load: newLoad, zoneCode, deadlineUrgency: state.metrics.get("deadline.urgency") ?? 0, cognitiveLoad: state.metrics.get("cognitive.load") ?? state.metrics.get("attention.usage") ?? 0 } });
4109
4166
  }
@@ -4326,6 +4383,116 @@ var CircadianOscillator = class {
4326
4383
  }
4327
4384
  };
4328
4385
 
4386
+ // src/cognition/agency/consequence.ts
4387
+ var CONSEQUENCE_TYPE = "agency.consequence";
4388
+ var ATTENUATION = 0.25;
4389
+ var MIN_TEXT_MATCH_LEN = 12;
4390
+ var CONSEQUENCE_TTL_TICKS = 30;
4391
+ function fnv1a(text) {
4392
+ let h = 2166136261;
4393
+ for (let i = 0; i < text.length; i++) {
4394
+ h ^= text.charCodeAt(i);
4395
+ h = Math.imul(h, 16777619) >>> 0;
4396
+ }
4397
+ return h >>> 0;
4398
+ }
4399
+ function paramsKey(value) {
4400
+ if (value === null || typeof value !== "object")
4401
+ return typeof value === "string" ? JSON.stringify(value) : String(value);
4402
+ if (Array.isArray(value))
4403
+ return `[${value.map(paramsKey).join(",")}]`;
4404
+ const obj = value;
4405
+ const keys = Object.keys(obj).sort();
4406
+ return `{${keys.map((k) => `${k}:${paramsKey(obj[k])}`).join(",")}}`;
4407
+ }
4408
+ function consequenceEntity(d) {
4409
+ return {
4410
+ id: `agency-consequence-${d.intentId}`,
4411
+ type: CONSEQUENCE_TYPE,
4412
+ metadata: { ...d }
4413
+ };
4414
+ }
4415
+ function readConsequence(m) {
4416
+ const meta = m ?? {};
4417
+ const intentId = typeof meta["intentId"] === "string" ? meta["intentId"] : void 0;
4418
+ const schema = typeof meta["schema"] === "string" ? meta["schema"] : void 0;
4419
+ const mode = meta["mode"] === "communicate" || meta["mode"] === "external" ? meta["mode"] : void 0;
4420
+ if (!intentId || !schema || !mode) return null;
4421
+ return {
4422
+ intentId,
4423
+ schema,
4424
+ mode,
4425
+ effector: typeof meta["effector"] === "string" ? meta["effector"] : void 0,
4426
+ targetEntityId: typeof meta["targetEntityId"] === "string" ? meta["targetEntityId"] : void 0,
4427
+ textHash: typeof meta["textHash"] === "number" ? meta["textHash"] : void 0,
4428
+ text: typeof meta["text"] === "string" ? meta["text"] : void 0,
4429
+ paramsHash: typeof meta["paramsHash"] === "number" ? meta["paramsHash"] : void 0,
4430
+ expiresAt: typeof meta["expiresAt"] === "number" ? meta["expiresAt"] : 0,
4431
+ tick: typeof meta["tick"] === "number" ? meta["tick"] : 0
4432
+ };
4433
+ }
4434
+ function liveConsequences(entities, tick) {
4435
+ const out = [];
4436
+ for (const [, e] of entities) {
4437
+ if (e.type !== CONSEQUENCE_TYPE) continue;
4438
+ const d = readConsequence(e.metadata);
4439
+ if (d && tick < d.expiresAt) out.push(d);
4440
+ }
4441
+ return out.sort((a, b) => a.intentId < b.intentId ? -1 : a.intentId > b.intentId ? 1 : 0);
4442
+ }
4443
+ function matchConsequenceText(descriptors, candidate) {
4444
+ if (candidate.length === 0) return null;
4445
+ const candidateHash = fnv1a(candidate);
4446
+ for (const d of descriptors) {
4447
+ if (d.textHash !== void 0 && d.textHash === candidateHash) return d;
4448
+ if (d.text !== void 0 && d.text.length >= MIN_TEXT_MATCH_LEN && candidate.includes(d.text)) return d;
4449
+ }
4450
+ return null;
4451
+ }
4452
+ var CORRESPONDENCE_ATTENUATION = 0.5;
4453
+ function matchConsequenceEntity(descriptors, entityId, changeType) {
4454
+ if (changeType !== "modified" || entityId.length === 0) return null;
4455
+ for (const d of descriptors)
4456
+ if (d.mode === "external" && d.targetEntityId === entityId) return d;
4457
+ return null;
4458
+ }
4459
+
4460
+ // src/cognition/agency/revocation.ts
4461
+ var REVOCATION_TYPE = "agency.revocation";
4462
+ var RUPTURE_REVOKE_GATE = 0.7;
4463
+ var REVOCATION_TTL_TICKS = 5;
4464
+ function revocationId(intentId) {
4465
+ return `agency-revocation-${intentId}`;
4466
+ }
4467
+ function revocationEntity(intentId, schema, rupture, tick) {
4468
+ return {
4469
+ id: revocationId(intentId),
4470
+ type: REVOCATION_TYPE,
4471
+ metadata: { intentId, schema, rupture, tick, expiresAt: tick + REVOCATION_TTL_TICKS }
4472
+ };
4473
+ }
4474
+ function revokedIntentIds(entities, tick) {
4475
+ const out = /* @__PURE__ */ new Set();
4476
+ for (const [, e] of entities) {
4477
+ if (e.type !== REVOCATION_TYPE) continue;
4478
+ const m = e.metadata ?? {};
4479
+ const intentId = typeof m["intentId"] === "string" ? m["intentId"] : void 0;
4480
+ const expiresAt = typeof m["expiresAt"] === "number" ? m["expiresAt"] : 0;
4481
+ if (intentId && tick < expiresAt) out.add(intentId);
4482
+ }
4483
+ return out;
4484
+ }
4485
+ function staleRevocationIds(entities, tick) {
4486
+ const stale = [];
4487
+ for (const [id, e] of entities) {
4488
+ if (e.type !== REVOCATION_TYPE) continue;
4489
+ const m = e.metadata ?? {};
4490
+ const expiresAt = typeof m["expiresAt"] === "number" ? m["expiresAt"] : 0;
4491
+ if (tick >= expiresAt) stale.push(id);
4492
+ }
4493
+ return stale;
4494
+ }
4495
+
4329
4496
  // src/cognition/faculties/exteroception.ts
4330
4497
  var internalTypes = /* @__PURE__ */ new Set([
4331
4498
  "percept",
@@ -4351,7 +4518,12 @@ var internalTypes = /* @__PURE__ */ new Set([
4351
4518
  "episodic_memory",
4352
4519
  // Internal state entities written by our own engines — not external events
4353
4520
  "affect.blends",
4354
- "executive.summary"
4521
+ "executive.summary",
4522
+ // The agency's own forward-model records (EXAFFERENCE P1/P2): perceiving our
4523
+ // expected-consequence descriptors would be a self-noise loop.
4524
+ CONSEQUENCE_TYPE,
4525
+ // The agency's own revocation tombstones (EXAFFERENCE P4) — internal bookkeeping.
4526
+ REVOCATION_TYPE
4355
4527
  ]);
4356
4528
  var Exteroception = class {
4357
4529
  name = "exteroception";
@@ -4401,17 +4573,26 @@ var Exteroception = class {
4401
4573
  const events = [], commands = { set: [], delete: [], metrics: [] };
4402
4574
  const rawPercepts = this._scanWorld(state);
4403
4575
  const capped = rawPercepts.slice(0, this._maxPerceptsPerTick);
4576
+ const consequences = liveConsequences(state.entities, tick);
4404
4577
  for (let i = 0; i < capped.length; i++) {
4405
4578
  const rp = capped[i];
4579
+ const textHit = consequences.length > 0 && rp.matchText ? matchConsequenceText(consequences, rp.matchText) : null;
4580
+ const entityHit = !textHit && consequences.length > 0 ? matchConsequenceEntity(consequences, rp.entityId, rp.changeType) : null;
4581
+ const hit = textHit ?? entityHit;
4582
+ const salience = textHit ? rp.salience * ATTENUATION : entityHit ? rp.salience * CORRESPONDENCE_ATTENUATION : rp.salience;
4406
4583
  const perceptEntity = {
4407
4584
  id: `percept-${tick}-${i}`,
4408
4585
  type: "percept",
4409
4586
  metadata: {
4410
4587
  entityId: rp.entityId,
4411
4588
  changeType: rp.changeType,
4412
- salience: rp.salience,
4589
+ salience,
4413
4590
  category: rp.category,
4414
4591
  summary: rp.summary,
4592
+ provenance: hit ? "reafferent" : "exafferent",
4593
+ ...hit ? { sourceIntentId: hit.intentId } : {},
4594
+ // affect→percept seam (registry #5): what this percept FEELS like
4595
+ ...rp.valence !== void 0 ? { valence: rp.valence, valenceSource: rp.valenceSource } : {},
4415
4596
  tick
4416
4597
  }
4417
4598
  };
@@ -4422,7 +4603,7 @@ var Exteroception = class {
4422
4603
  source: this.name,
4423
4604
  payload: {
4424
4605
  entityId: rp.entityId,
4425
- salience: rp.salience,
4606
+ salience,
4426
4607
  category: rp.category,
4427
4608
  summary: rp.summary
4428
4609
  }
@@ -4470,7 +4651,9 @@ var Exteroception = class {
4470
4651
  changeType: "appeared",
4471
4652
  salience: this._computeSalience(entity, "appeared", state.time),
4472
4653
  category: entity.type,
4473
- summary: this._summarizeEntity(entity, "appeared")
4654
+ summary: this._summarizeEntity(entity, "appeared"),
4655
+ matchText: this._matchText(entity),
4656
+ ...this._valenceOf(id, state)
4474
4657
  });
4475
4658
  } else if (entity.updatedAt > previousVersion) {
4476
4659
  percepts.push({
@@ -4478,7 +4661,9 @@ var Exteroception = class {
4478
4661
  changeType: "modified",
4479
4662
  salience: this._computeSalience(entity, "modified", state.time),
4480
4663
  category: entity.type,
4481
- summary: this._summarizeEntity(entity, "modified")
4664
+ summary: this._summarizeEntity(entity, "modified"),
4665
+ matchText: this._matchText(entity),
4666
+ ...this._valenceOf(id, state)
4482
4667
  });
4483
4668
  }
4484
4669
  this._previousEntityVersions.set(id, entity.updatedAt);
@@ -4504,6 +4689,46 @@ var Exteroception = class {
4504
4689
  * Generate a meaningful summary for an entity.
4505
4690
  * Instead of "New percept: percept-54-0", produce something useful.
4506
4691
  */
4692
+ /**
4693
+ * The text the corollary-discharge matcher inspects for this entity — its
4694
+ * content (a message body) over its description over its summary. Where our
4695
+ * own delivered words would surface if the world echoes them back.
4696
+ */
4697
+ /**
4698
+ * The affect→percept valence seam (registry #5). A percept carries how the
4699
+ * mind *feels* about what it is a percept OF, resolved most-specific-first:
4700
+ *
4701
+ * 1. the KnownEntityTracker's dossier for this entity (`ke-<id>.valence`) —
4702
+ * a real per-entity felt valence, the honest signal;
4703
+ * 2. otherwise the ambient `affect.valence` — the felt tone at perception
4704
+ * time. Weaker evidence, so it is tagged `'ambient'` and consumers
4705
+ * weight it down (mood is context, not appraisal of this thing).
4706
+ *
4707
+ * Absent both, no valence is stamped and every consumer keeps its
4708
+ * pre-seam behaviour.
4709
+ */
4710
+ /** Spread-friendly form of `_valenceFor` for percept construction. */
4711
+ _valenceOf(entityId, state) {
4712
+ const v = this._valenceFor(entityId, state);
4713
+ return v ? { valence: v.valence, valenceSource: v.source } : {};
4714
+ }
4715
+ _valenceFor(entityId, state) {
4716
+ const dossier = state.entities.get(`ke-${entityId}`);
4717
+ const felt = dossier?.metadata?.["valence"];
4718
+ if (typeof felt === "number" && Number.isFinite(felt))
4719
+ return { valence: felt, source: "entity" };
4720
+ const ambient = state.metrics.get("affect.valence");
4721
+ if (typeof ambient === "number" && Number.isFinite(ambient))
4722
+ return { valence: ambient, source: "ambient" };
4723
+ return void 0;
4724
+ }
4725
+ _matchText(entity) {
4726
+ const m = entity.metadata;
4727
+ const content = typeof m?.["content"] === "string" ? m["content"] : void 0;
4728
+ const description = typeof m?.["description"] === "string" ? m["description"] : void 0;
4729
+ const summary = typeof m?.["summary"] === "string" ? m["summary"] : void 0;
4730
+ return content ?? description ?? summary;
4731
+ }
4507
4732
  _summarizeEntity(entity, changeType) {
4508
4733
  const name = entity.metadata?.name;
4509
4734
  const description = entity.metadata?.description;
@@ -6488,6 +6713,8 @@ var MoralEvaluator = class {
6488
6713
  };
6489
6714
 
6490
6715
  // src/cognition/faculties/affective.blender.ts
6716
+ var ACP_AROUSAL_UPLIFT = 0.1;
6717
+ var ACP_CONFIDENCE2 = 0.4;
6491
6718
  var DOMINANT_EMOTION_CODES = {
6492
6719
  "neutral": 0,
6493
6720
  "fear": 1,
@@ -6588,6 +6815,8 @@ var AffectiveBlender = class {
6588
6815
  _previousPAD = { valence: 0, arousal: 0.3, dominance: 0.5 };
6589
6816
  _emotionHistory = /* @__PURE__ */ new Map();
6590
6817
  _moodBaseline = 0.5;
6818
+ /** ACP-P2: self-caused arousal attenuation armed; react() restores after one observe. */
6819
+ _acpOneShot = false;
6591
6820
  _energyLevel = 100;
6592
6821
  _comfort = 0.5;
6593
6822
  _sleepPressure = 0;
@@ -6621,8 +6850,12 @@ var AffectiveBlender = class {
6621
6850
  "sleep.state.changed",
6622
6851
  "stress.state.changed",
6623
6852
  "executive.prediction.formed",
6624
- "interaction.occurred"
6853
+ "interaction.occurred",
6625
6854
  // 2.1: social stimuli drive immediate arousal/valence shifts
6855
+ // ACP-P2: our own enactions — the arousal they cause is expected, not surprising
6856
+ "agency.enacted",
6857
+ "agency.communicate",
6858
+ "agency.invocation"
6626
6859
  ];
6627
6860
  }
6628
6861
  publishes() {
@@ -6631,6 +6864,15 @@ var AffectiveBlender = class {
6631
6864
  onCognitiveEvent(e) {
6632
6865
  this._model.observe(e.type, e.salience);
6633
6866
  switch (e.type) {
6867
+ case "agency.enacted":
6868
+ case "agency.communicate":
6869
+ case "agency.invocation": {
6870
+ const arousal = this._model.predict("affect.arousal");
6871
+ this._model.anticipate("affect.arousal", Math.min(1, arousal + ACP_AROUSAL_UPLIFT), ACP_CONFIDENCE2);
6872
+ this._model.setPrecision("affect.arousal", ACP_SELF_PRECISION);
6873
+ this._acpOneShot = true;
6874
+ break;
6875
+ }
6634
6876
  case "circadian.state.changed":
6635
6877
  this._moodBaseline = e.payload["moodBaseline"] ?? this._moodBaseline;
6636
6878
  break;
@@ -6734,8 +6976,14 @@ var AffectiveBlender = class {
6734
6976
  const _bus = this._bus;
6735
6977
  if (_bus)
6736
6978
  _bus.publish({ type: "affect.state.shifted", version: 1, sourceEngine: this.name, salience: Math.min(1, Math.abs(modulatedPAD.valence) + modulatedPAD.arousal * 0.5), payload: { valence: modulatedPAD.valence, arousal: modulatedPAD.arousal, dominantEmotion: dominant } });
6737
- if (_bus)
6738
- _bus.publish({ type: "affect.state.changed", version: 1, sourceEngine: this.name, salience: this._model.observe("affect.arousal", modulatedPAD.arousal).salience, payload: { valence: modulatedPAD.valence, arousal: modulatedPAD.arousal, dominance: modulatedPAD.dominance } });
6979
+ if (_bus) {
6980
+ const arousalErr = this._model.observe("affect.arousal", modulatedPAD.arousal);
6981
+ if (this._acpOneShot) {
6982
+ this._model.setPrecision("affect.arousal", 1);
6983
+ this._acpOneShot = false;
6984
+ }
6985
+ _bus.publish({ type: "affect.state.changed", version: 1, sourceEngine: this.name, salience: arousalErr.salience, payload: { valence: modulatedPAD.valence, arousal: modulatedPAD.arousal, dominance: modulatedPAD.dominance } });
6986
+ }
6739
6987
  return { events: events.length > 0 ? events : void 0, commands };
6740
6988
  }
6741
6989
  // ── PAD computation ──────────────────────────────────────
@@ -11699,6 +11947,38 @@ async function withGate(fn, label, gate = llmGate) {
11699
11947
  }
11700
11948
 
11701
11949
  // src/llm/index.ts
11950
+ var ANTHROPIC_WIRE = /* @__PURE__ */ new Set(["anthropic", "glm"]);
11951
+ function speaksAnthropicWire(provider) {
11952
+ return ANTHROPIC_WIRE.has(provider);
11953
+ }
11954
+ function defaultBaseFor(provider) {
11955
+ switch (provider) {
11956
+ case "anthropic":
11957
+ return "https://api.anthropic.com/v1";
11958
+ // Z.ai documents the base as `…/api/anthropic` because the Anthropic SDK
11959
+ // appends `/v1/messages`; this client appends `/messages`, so the version
11960
+ // segment belongs here — verified against the live endpoint.
11961
+ case "glm":
11962
+ return "https://api.z.ai/api/anthropic/v1";
11963
+ case "openai":
11964
+ return "https://api.openai.com/v1";
11965
+ case "deepseek":
11966
+ return "https://api.deepseek.com/v1";
11967
+ case "google":
11968
+ return "https://generativelanguage.googleapis.com/v1beta";
11969
+ }
11970
+ }
11971
+ function defaultModelFor(provider) {
11972
+ return provider === "glm" ? "glm-5.2" : "claude-sonnet-4-5-20250929";
11973
+ }
11974
+ function anthropicWireHeaders(provider, apiKey) {
11975
+ return {
11976
+ "Content-Type": "application/json",
11977
+ "anthropic-version": "2023-06-01",
11978
+ "x-api-key": apiKey,
11979
+ ...provider === "glm" ? { Authorization: `Bearer ${apiKey}` } : {}
11980
+ };
11981
+ }
11702
11982
  var DEFAULT_CALL_META = { category: "executive", attribute: "master", function: "decision" };
11703
11983
  var LLMDirector = class {
11704
11984
  _willId;
@@ -11801,7 +12081,7 @@ var LLMDirector = class {
11801
12081
  this._recordCompletion(systemPrompt, userMessage, tick, result2, Date.now() - start, true);
11802
12082
  return result2;
11803
12083
  }
11804
- const result = this._provider === "anthropic" ? await this._callAnthropicStream(systemPrompt, userMessage, onChunk, temperature) : await (async () => {
12084
+ const result = speaksAnthropicWire(this._provider) ? await this._callAnthropicStream(systemPrompt, userMessage, onChunk, temperature) : await (async () => {
11805
12085
  const r = await this._callProvider(systemPrompt, userMessage, temperature);
11806
12086
  onChunk(r.text);
11807
12087
  return r;
@@ -11881,11 +12161,7 @@ var LLMDirector = class {
11881
12161
  try {
11882
12162
  res = await fetch(`${this._resolvedBase()}/messages`, {
11883
12163
  method: "POST",
11884
- headers: {
11885
- "Content-Type": "application/json",
11886
- "anthropic-version": "2023-06-01",
11887
- "x-api-key": this._apiKey
11888
- },
12164
+ headers: anthropicWireHeaders(this._provider, this._apiKey),
11889
12165
  body: JSON.stringify({
11890
12166
  model: this._model,
11891
12167
  max_tokens: this._maxOutputTokens,
@@ -11960,7 +12236,7 @@ var LLMDirector = class {
11960
12236
  return result2;
11961
12237
  }
11962
12238
  const result = await withGate(
11963
- () => this._provider === "anthropic" ? this._callAnthropicStream(systemPrompt, userMessage, () => {
12239
+ () => speaksAnthropicWire(this._provider) ? this._callAnthropicStream(systemPrompt, userMessage, () => {
11964
12240
  }, temperature) : this._callProvider(systemPrompt, userMessage, temperature),
11965
12241
  "executive/direct"
11966
12242
  );
@@ -11972,6 +12248,8 @@ var LLMDirector = class {
11972
12248
  switch (this._provider) {
11973
12249
  case "anthropic":
11974
12250
  return this._callAnthropic(systemPrompt, userMessage, temperature);
12251
+ case "glm":
12252
+ return this._callAnthropic(systemPrompt, userMessage, temperature);
11975
12253
  case "deepseek":
11976
12254
  return this._callOpenAI(systemPrompt, userMessage, temperature);
11977
12255
  case "openai":
@@ -11984,16 +12262,7 @@ var LLMDirector = class {
11984
12262
  }
11985
12263
  /** Default API base URL (including version segment) for a provider. */
11986
12264
  _baseFor(provider) {
11987
- switch (provider) {
11988
- case "anthropic":
11989
- return "https://api.anthropic.com/v1";
11990
- case "openai":
11991
- return "https://api.openai.com/v1";
11992
- case "deepseek":
11993
- return "https://api.deepseek.com/v1";
11994
- case "google":
11995
- return "https://generativelanguage.googleapis.com/v1beta";
11996
- }
12265
+ return defaultBaseFor(provider);
11997
12266
  }
11998
12267
  /** Resolved API base: explicit override wins, else the provider default. */
11999
12268
  _resolvedBase() {
@@ -12033,15 +12302,11 @@ var LLMDirector = class {
12033
12302
  };
12034
12303
  const res = await this._fetchWithTimeout(`${this._resolvedBase()}/messages`, {
12035
12304
  method: "POST",
12036
- headers: {
12037
- "Content-Type": "application/json",
12038
- "anthropic-version": "2023-06-01",
12039
- "x-api-key": this._apiKey
12040
- },
12305
+ headers: anthropicWireHeaders(this._provider, this._apiKey),
12041
12306
  body: JSON.stringify(body)
12042
12307
  });
12043
12308
  if (!res.ok)
12044
- throw new Error(`Anthropic API ${res.status}: ${(await res.text()).slice(0, 300)}`);
12309
+ throw new Error(`${this._provider} API ${res.status}: ${(await res.text()).slice(0, 300)}`);
12045
12310
  const data = await res.json(), text = data.content.find((b) => b.type === "text")?.text ?? "";
12046
12311
  return {
12047
12312
  text,
@@ -12821,7 +13086,7 @@ var ExecutiveEngine = class extends AsyncEngine {
12821
13086
  this._gatingState.executiveInterval = rtConfig.executiveInterval;
12822
13087
  this._gatingState.cooldownTicks = rtConfig.cooldownTicks;
12823
13088
  if (!this._llmDirector && this._willId) {
12824
- const execModel = this._models.executive ?? process.env.WILL_LLM_MODEL ?? "claude-sonnet-4-5-20250929";
13089
+ const execModel = this._models.executive ?? process.env.WILL_LLM_MODEL ?? defaultModelFor(this._llm?.provider ?? process.env.WILL_LLM_PROVIDER ?? "anthropic");
12825
13090
  this._llmDirector = this._directorFor(execModel);
12826
13091
  this._summarizer?.attachLLMDirector(this._directorFor(this._models.summarizer ?? execModel));
12827
13092
  }
@@ -14730,7 +14995,8 @@ var TaskSwitcher = class {
14730
14995
  const currentGoal = activeGoals.find((g) => g.id === this._currentFocus.goalId);
14731
14996
  const currentPriority = currentGoal?.priority ?? 0;
14732
14997
  const switchAdvantage = topGoal.priority - currentPriority;
14733
- const switchCost = this._baseSwitchCost * (1 + this._currentFocus.focusTicks * 0.01);
14998
+ const stability = state.metrics.get("situation.stability") ?? 1;
14999
+ const switchCost = this._baseSwitchCost * (1 + this._currentFocus.focusTicks * 0.01 * stability);
14734
15000
  const netBenefit = switchAdvantage - switchCost;
14735
15001
  if (netBenefit > this._switchThreshold && this._currentFocus.focusTicks >= this._minFocusTicks) {
14736
15002
  this._currentFocus = {
@@ -18547,9 +18813,7 @@ var AffordanceSynthesizer = class {
18547
18813
  if (e.type === "affordance") del.push(id);
18548
18814
  const floor = schemas.filter((s) => s.binds === "none");
18549
18815
  for (const schema of floor)
18550
- set.push(this._toEntity(
18551
- this._build(schema, tick, state, valence, energyLow, skills, {})
18552
- ));
18816
+ set.push(this._toEntity(this._build(schema, tick, state, valence, energyLow, skills, {})));
18553
18817
  const candidates = [];
18554
18818
  const goalTargets = collectGoalTargets(state);
18555
18819
  const perceptSchema = schemas.find((s) => s.binds === "percept");
@@ -18763,11 +19027,24 @@ var BASE_SWITCH_COST = 0.15;
18763
19027
  var FOCUS_GAIN = 0.01;
18764
19028
  var AWAIT_STALE_TICKS = 15;
18765
19029
  var STALE_DECAY = 0.5;
19030
+ var RUPTURE_SALIENCE_GATE = 0.4;
19031
+ var RUPTURE_WINDOW_TICKS = 2;
19032
+ var STABILITY_RECOVERY = 0.05;
19033
+ var STABILITY_EPSILON = 1e-4;
19034
+ var REVOKE_HINT_WINDOW = 8;
18766
19035
  var ActionSelector = class {
18767
19036
  name = "action-selector";
18768
19037
  _bus = null;
18769
19038
  _lastEntropy = 0;
18770
19039
  _lastDeliberate = false;
19040
+ // EXAFFERENCE P4 follow-up (Channel B): the schema we most recently revoked
19041
+ // under rupture, so the *next* deliberation formed in its wake can own the
19042
+ // interruption in-character ("something changed — I dropped what I was
19043
+ // weighing"). Telemetry-grade instance state, mirroring _lastEntropy.
19044
+ _lastRevoked = null;
19045
+ // ACP §2b: sense-channel percepts buffered off the bus for the next react's
19046
+ // rupture computation (they never become entities). Cross-tick ⇒ FN9.
19047
+ _senseBuffer = [];
18771
19048
  attachBus(bus) {
18772
19049
  this._bus = bus;
18773
19050
  }
@@ -18775,16 +19052,60 @@ var ActionSelector = class {
18775
19052
  return [
18776
19053
  { type: "agency.selection.made", version: 1, validate: () => null },
18777
19054
  { type: "agency.selection.ambiguous", version: 1, validate: () => null },
18778
- { type: "agency.action.preempted", version: 1, validate: () => null }
19055
+ { type: "agency.action.preempted", version: 1, validate: () => null },
19056
+ { type: "agency.situation.rupture", version: 1, validate: () => null },
19057
+ { type: "agency.commitment.revoked", version: 1, validate: () => null }
18779
19058
  ];
18780
19059
  }
18781
19060
  subscribes() {
18782
- return [];
19061
+ return [
19062
+ "senses.*",
19063
+ // Registry #6 (ACP-P3): the model-error term — each carries its
19064
+ // engine's prediction-error salience, ALREADY precision-attenuated for
19065
+ // self-caused swings by the ACP-P2 consumers, so the echo guard
19066
+ // composes by construction: our own action's interoceptive wake
19067
+ // arrives below the rupture gate.
19068
+ "attention.state.changed",
19069
+ "affect.state.changed",
19070
+ "stress.state.changed"
19071
+ ];
18783
19072
  }
18784
- onCognitiveEvent() {
19073
+ /**
19074
+ * Mostly pull-model — but two afferent classes never become entities and
19075
+ * would leave rupture blind: sense-channel percepts
19076
+ * (ACTION_CONDITIONED_PREDICTION §2b) and the model-error state-change
19077
+ * events (registry #6). Buffer both (cross-tick: bus flush at T, consumed
19078
+ * by react at T+1 — FN9-snapshotted); the echo guard is applied at read
19079
+ * time for texts, and at the SOURCE for model errors (ACP-P2 precision).
19080
+ */
19081
+ onCognitiveEvent(e) {
19082
+ const isSense = e.type.startsWith("senses.") && e.type.endsWith(".percept");
19083
+ const isModelError = e.type === "attention.state.changed" || e.type === "affect.state.changed" || e.type === "stress.state.changed";
19084
+ if (!isSense && !isModelError) return;
19085
+ const p = e.payload;
19086
+ this._senseBuffer.push({
19087
+ salience: e.salience,
19088
+ ...isSense && typeof p?.content === "string" ? { text: p.content } : {}
19089
+ });
18785
19090
  }
18786
19091
  snapshot() {
18787
- return { lastEntropy: this._lastEntropy, lastDeliberate: this._lastDeliberate };
19092
+ return {
19093
+ lastEntropy: this._lastEntropy,
19094
+ lastDeliberate: this._lastDeliberate,
19095
+ lastRevoked: this._lastRevoked,
19096
+ senseBuffer: this._senseBuffer
19097
+ };
19098
+ }
19099
+ /** FN9: `_lastRevoked` has behavioral effect (the Channel-B `revokedBy` stamp),
19100
+ * so a restored mind must carry it — a rupture-driven letting-go survives a
19101
+ * snapshot boundary instead of silently losing its narrative thread. */
19102
+ restore(s) {
19103
+ if (typeof s["lastEntropy"] === "number") this._lastEntropy = s["lastEntropy"];
19104
+ if (typeof s["lastDeliberate"] === "boolean") this._lastDeliberate = s["lastDeliberate"];
19105
+ const lr = s["lastRevoked"];
19106
+ this._lastRevoked = lr && typeof lr === "object" && typeof lr.schema === "string" && typeof lr.tick === "number" ? { schema: lr.schema, tick: lr.tick } : null;
19107
+ const sb = s["senseBuffer"];
19108
+ this._senseBuffer = Array.isArray(sb) ? sb.filter((it) => it && typeof it.salience === "number").map((it) => ({ salience: it.salience, ...typeof it.text === "string" ? { text: it.text } : {} })) : [];
18788
19109
  }
18789
19110
  async react(_delta, tick, state, _context) {
18790
19111
  const eligible = [];
@@ -18813,54 +19134,121 @@ var ActionSelector = class {
18813
19134
  let blocking = false;
18814
19135
  let awaiting = null;
18815
19136
  let composite = null;
19137
+ let deliberating = null;
18816
19138
  for (const it of intents) {
18817
- if (it.st === "deliberating") blocking = true;
18818
- else if (it.st === "expanding") composite = { id: it.id, activation: it.activation, schema: it.schema };
19139
+ if (it.st === "deliberating") {
19140
+ blocking = true;
19141
+ deliberating = { id: it.id, schema: it.schema };
19142
+ } else if (it.st === "expanding") composite = { id: it.id, activation: it.activation, schema: it.schema };
18819
19143
  else if (it.st === "awaiting") awaiting = { id: it.id, activation: it.activation, schema: it.schema, target: it.target, dispatchedAt: it.dispatchedAt };
18820
19144
  else if (it.st === "selected") {
18821
19145
  const activeMacroSub = it.parentIntentId !== void 0 && expandingParents.has(it.parentIntentId);
18822
19146
  if (!activeMacroSub) blocking = true;
18823
19147
  }
18824
19148
  }
18825
- const busy = (n) => ({ commands: { metrics: [
18826
- ["agency.field.eligible", n],
18827
- ["agency.selection.busy", 1]
18828
- ] } });
19149
+ const senseEvents = this._senseBuffer;
19150
+ this._senseBuffer = [];
19151
+ const rupture = computeRupture(state, tick, senseEvents);
19152
+ const prevStab = metric2(state, "situation.stability", 1);
19153
+ const nextStabRaw = clamp017(prevStab + STABILITY_RECOVERY * (1 - prevStab) - rupture);
19154
+ const nextStab = 1 - nextStabRaw < STABILITY_EPSILON ? 1 : nextStabRaw;
19155
+ const stabMetrics = rupture > 0 || prevStab < 1 ? [["situation.stability", nextStab]] : [];
19156
+ if (rupture > 0 && this._bus) {
19157
+ try {
19158
+ this._bus.publish({
19159
+ type: "agency.situation.rupture",
19160
+ version: 1,
19161
+ sourceEngine: this.name,
19162
+ salience: rupture,
19163
+ payload: { rupture, stability: nextStab, tick }
19164
+ });
19165
+ } catch (err) {
19166
+ logger.warn(`[selector] rupture publish failed: ${err instanceof Error ? err.message : String(err)}`);
19167
+ }
19168
+ }
19169
+ const busy = (n) => ({
19170
+ commands: {
19171
+ metrics: [
19172
+ ["agency.field.eligible", n],
19173
+ ["agency.selection.busy", 1],
19174
+ ...stabMetrics
19175
+ ]
19176
+ }
19177
+ });
19178
+ if (deliberating && rupture >= RUPTURE_REVOKE_GATE) {
19179
+ if (this._bus) {
19180
+ try {
19181
+ this._bus.publish({
19182
+ type: "agency.commitment.revoked",
19183
+ version: 1,
19184
+ sourceEngine: this.name,
19185
+ salience: 0.85,
19186
+ payload: { from: deliberating.schema, reason: "exafferent-rupture", rupture, tick }
19187
+ });
19188
+ } catch (err) {
19189
+ logger.warn(`[selector] revoked publish failed: ${err instanceof Error ? err.message : String(err)}`);
19190
+ }
19191
+ }
19192
+ this._lastRevoked = { schema: deliberating.schema, tick };
19193
+ return {
19194
+ commands: {
19195
+ set: [revocationEntity(deliberating.id, deliberating.schema, rupture, tick)],
19196
+ metrics: [
19197
+ ["agency.field.eligible", eligible.length],
19198
+ ["agency.selection.busy", 1],
19199
+ ["agency.commitment.revoked", 1],
19200
+ ...stabMetrics
19201
+ ]
19202
+ }
19203
+ };
19204
+ }
18829
19205
  if (blocking) return busy(eligible.length);
18830
19206
  if (eligible.length === 0)
18831
- return { commands: { metrics: [["agency.field.eligible", 0], ["agency.selection.busy", awaiting || composite ? 1 : 0]] } };
19207
+ return {
19208
+ commands: {
19209
+ metrics: [
19210
+ ["agency.field.eligible", 0],
19211
+ ["agency.selection.busy", awaiting || composite ? 1 : 0],
19212
+ ...stabMetrics
19213
+ ]
19214
+ }
19215
+ };
18832
19216
  const bias = buildBias(state);
18833
- const effSwitchCost = effectiveSwitchCost(state);
19217
+ const effSwitchCost = effectiveSwitchCost(state) * (1 - rupture);
18834
19218
  const weights = effectiveWeights(state);
18835
19219
  const scored = eligible.map((a) => ({ affordance: a, activation: scoreAffordance(a, bias, weights) })).sort((x, y) => y.activation - x.activation);
18836
19220
  const winner = scored[0];
18837
19221
  if (!winner) return busy(eligible.length);
19222
+ let compositeTombstone;
19223
+ let compositeFrom;
18838
19224
  if (composite) {
18839
19225
  const different = winner.affordance.schema !== composite.schema;
18840
19226
  const switchCost = effSwitchCost * (1 - stakes(winner.affordance, bias));
18841
- if (different && winner.activation > composite.activation + switchCost) {
18842
- if (this._bus) try {
19227
+ if (!different || winner.activation <= composite.activation + switchCost)
19228
+ return busy(eligible.length);
19229
+ if (this._bus)
19230
+ try {
18843
19231
  this._bus.publish({
18844
19232
  type: "agency.action.preempted",
18845
19233
  version: 1,
18846
19234
  sourceEngine: this.name,
18847
19235
  salience: 0.8,
18848
- payload: { from: composite.schema, to: winner.affordance.schema, activation: winner.activation, tick }
19236
+ payload: {
19237
+ from: composite.schema,
19238
+ to: winner.affordance.schema,
19239
+ activation: winner.activation,
19240
+ tick
19241
+ }
18849
19242
  });
18850
19243
  } catch (err) {
18851
19244
  logger.warn(`[selector] preempt publish failed: ${err instanceof Error ? err.message : String(err)}`);
18852
19245
  }
18853
- return { commands: { delete: [composite.id], metrics: [
18854
- ["agency.field.eligible", eligible.length],
18855
- ["agency.selection.busy", 1],
18856
- ["agency.selection.preempted", 1]
18857
- ] } };
18858
- }
18859
- return busy(eligible.length);
19246
+ compositeTombstone = composite.id;
19247
+ compositeFrom = composite.schema;
18860
19248
  }
18861
19249
  let preemptDelete;
18862
- let preemptedFrom;
18863
- if (awaiting) {
19250
+ let preemptedFrom = compositeFrom;
19251
+ if (awaiting && !compositeTombstone) {
18864
19252
  const sameAction = winner.affordance.schema === awaiting.schema && (winner.affordance.targetEntityId ?? "") === awaiting.target;
18865
19253
  if (sameAction) return busy(eligible.length);
18866
19254
  const staleness = Math.min(1, (tick - awaiting.dispatchedAt) / AWAIT_STALE_TICKS);
@@ -18883,6 +19271,13 @@ var ActionSelector = class {
18883
19271
  const deliberate = margin < marginGate || stk > stakesGate;
18884
19272
  this._lastEntropy = entropy;
18885
19273
  this._lastDeliberate = deliberate;
19274
+ let revokedBy;
19275
+ if (this._lastRevoked) {
19276
+ if (deliberate && tick - this._lastRevoked.tick <= REVOKE_HINT_WINDOW)
19277
+ revokedBy = this._lastRevoked.schema;
19278
+ if (revokedBy || tick - this._lastRevoked.tick > REVOKE_HINT_WINDOW)
19279
+ this._lastRevoked = null;
19280
+ }
18886
19281
  const intent = {
18887
19282
  id: `agency-intent-${tick}`,
18888
19283
  type: "agency.intent",
@@ -18925,6 +19320,9 @@ var ActionSelector = class {
18925
19320
  // interrupted, so the deliberation facet can own the interruption in-character
18926
19321
  // ("I was about to X, but this pulled me away"). Only meaningful while deliberating.
18927
19322
  ...preemptedFrom ? { preemptedFrom } : {},
19323
+ // Channel B: this deliberation forms in the wake of a rupture-driven
19324
+ // revocation — the facet can own "something changed, I let go of X".
19325
+ ...revokedBy ? { revokedBy } : {},
18928
19326
  tick
18929
19327
  }
18930
19328
  };
@@ -18963,7 +19361,9 @@ var ActionSelector = class {
18963
19361
  }
18964
19362
  }
18965
19363
  const commands = {
18966
- set: [intent],
19364
+ // A composite preemption rides along as a tombstone (never a delete — the
19365
+ // executor's in-tick macro-advance would resurrect the parent).
19366
+ set: compositeTombstone ? [intent, revocationEntity(compositeTombstone, compositeFrom ?? "", rupture, tick)] : [intent],
18967
19367
  ...preemptDelete ? { delete: [preemptDelete] } : {},
18968
19368
  metrics: [
18969
19369
  ["agency.field.eligible", eligible.length],
@@ -18972,7 +19372,8 @@ var ActionSelector = class {
18972
19372
  ["agency.selection.margin", margin],
18973
19373
  ["agency.selection.deliberate", deliberate ? 1 : 0],
18974
19374
  ["agency.selection.preempted", preemptedFrom ? 1 : 0],
18975
- ["agency.selection.activation", winner.activation]
19375
+ ["agency.selection.activation", winner.activation],
19376
+ ...stabMetrics
18976
19377
  ]
18977
19378
  };
18978
19379
  return { commands };
@@ -18982,7 +19383,29 @@ function effectiveSwitchCost(state) {
18982
19383
  const params = readEffectiveParams(state, "engine-config-action-selector");
18983
19384
  const base = num2(params["switchCost"], BASE_SWITCH_COST);
18984
19385
  const focusTicks = metric2(state, "task_switch.current_focus_ticks", 0);
18985
- return base * (1 + focusTicks * FOCUS_GAIN);
19386
+ const stability = metric2(state, "situation.stability", 1);
19387
+ return base * (1 + focusTicks * FOCUS_GAIN * stability);
19388
+ }
19389
+ function computeRupture(state, tick, senseEvents = []) {
19390
+ let maxSalience = 0;
19391
+ for (const e of state.entities.values()) {
19392
+ if (e.type !== "percept") continue;
19393
+ const m = e.metadata;
19394
+ if (str2(m?.["provenance"]) !== "exafferent") continue;
19395
+ const pTick = num2(m?.["tick"], -1);
19396
+ if (pTick < 0 || tick - pTick > RUPTURE_WINDOW_TICKS) continue;
19397
+ const s = num2(m?.["salience"], 0);
19398
+ if (s > maxSalience) maxSalience = s;
19399
+ }
19400
+ if (senseEvents.length > 0) {
19401
+ const live = liveConsequences(state.entities, tick);
19402
+ for (const ev of senseEvents) {
19403
+ if (ev.text !== void 0 && live.length > 0 && matchConsequenceText(live, ev.text)) continue;
19404
+ if (ev.salience > maxSalience) maxSalience = ev.salience;
19405
+ }
19406
+ }
19407
+ if (maxSalience <= RUPTURE_SALIENCE_GATE) return 0;
19408
+ return clamp017((maxSalience - RUPTURE_SALIENCE_GATE) / (1 - RUPTURE_SALIENCE_GATE));
18986
19409
  }
18987
19410
  function effectiveWeights(state) {
18988
19411
  const p = readEffectiveParams(state, "engine-config-action-selector");
@@ -19083,19 +19506,28 @@ var DeliberationEngine = class {
19083
19506
  return { deliberations: this._deliberations };
19084
19507
  }
19085
19508
  async react(_delta, tick, state, _context) {
19509
+ const revoked = revokedIntentIds(state.entities, tick);
19510
+ const del = [];
19086
19511
  let target = null;
19087
19512
  for (const [id2, e] of state.entities) {
19088
19513
  if (e.type !== "agency.intent") continue;
19089
19514
  if (str3(e.metadata?.["status"]) !== "deliberating") continue;
19515
+ if (revoked.has(id2)) {
19516
+ del.push(id2, revocationId(id2));
19517
+ continue;
19518
+ }
19090
19519
  const meta2 = e.metadata ?? {};
19091
19520
  if (!target || id2 < target.id) target = { id: id2, meta: meta2 };
19092
19521
  }
19093
- if (!target) return { commands: {} };
19522
+ if (!target) return del.length > 0 ? { commands: { delete: del } } : { commands: {} };
19094
19523
  const { id, meta } = target;
19095
19524
  const provisional = str3(meta["schema"]) ?? "wait";
19096
19525
  const candidates = Array.isArray(meta["candidates"]) ? meta["candidates"] : [];
19097
19526
  if (!this._provider)
19098
- return { commands: { set: [this._commit(id, meta, provisional, candidates, "no-executive")] } };
19527
+ return { commands: {
19528
+ set: [this._commit(id, meta, provisional, candidates, "no-executive")],
19529
+ ...del.length > 0 ? { delete: del } : {}
19530
+ } };
19099
19531
  const chosen = await this._deliberate(state, candidates, provisional, meta);
19100
19532
  this._deliberations++;
19101
19533
  if (this._bus) {
@@ -19113,6 +19545,7 @@ var DeliberationEngine = class {
19113
19545
  return {
19114
19546
  commands: {
19115
19547
  set: [this._commit(id, meta, chosen, candidates, "facet")],
19548
+ ...del.length > 0 ? { delete: del } : {},
19116
19549
  metrics: [["agency.deliberation.count", 1]]
19117
19550
  }
19118
19551
  };
@@ -19170,7 +19603,10 @@ var DeliberationEngine = class {
19170
19603
  _buildFocusContent(state, candidates, meta) {
19171
19604
  const lines = [];
19172
19605
  const preemptedFrom = str3(meta["preemptedFrom"]);
19173
- if (preemptedFrom)
19606
+ const revokedBy = str3(meta["revokedBy"]);
19607
+ if (revokedBy)
19608
+ lines.push(`Something in my situation just shifted and I let go of what I was weighing ("${revokedBy}"). Decide afresh what to do now:`);
19609
+ else if (preemptedFrom)
19174
19610
  lines.push(`I just broke off a pending action ("${preemptedFrom}") because something more pressing pulled at me. Decide what to do now:`);
19175
19611
  else
19176
19612
  lines.push("My automatic action-selection was uncertain. Candidate actions:");
@@ -19343,6 +19779,19 @@ var MotorSchemaExecutor = class {
19343
19779
  const metrics = [];
19344
19780
  const energy = state.metrics.get("energy.level") ?? 100;
19345
19781
  const stress = state.metrics.get("stress.load") ?? 0;
19782
+ for (const [id, e] of state.entities) {
19783
+ if (e.type !== CONSEQUENCE_TYPE) continue;
19784
+ if (tick >= num3(e.metadata?.["expiresAt"], 0)) del.push(id);
19785
+ }
19786
+ del.push(...staleRevocationIds(state.entities, tick));
19787
+ const revoked = revokedIntentIds(state.entities, tick);
19788
+ if (revoked.size > 0)
19789
+ for (const [id, e] of state.entities) {
19790
+ if (e.type !== "agency.intent") continue;
19791
+ const parentId = str5(e.metadata?.["parentIntentId"]);
19792
+ if (revoked.has(id)) del.push(id, revocationId(id));
19793
+ else if (parentId && revoked.has(parentId)) del.push(id);
19794
+ }
19346
19795
  for (const [id, e] of state.entities) {
19347
19796
  if (e.type !== "agency.intent" || str5(e.metadata?.["status"]) !== "awaiting") continue;
19348
19797
  const dispatchedAt = num3(e.metadata?.["dispatchedAt"], tick);
@@ -19369,6 +19818,9 @@ var MotorSchemaExecutor = class {
19369
19818
  const selected = [...state.entities.entries()].filter(([, e]) => e.type === "agency.intent" && str5(e.metadata?.["status"]) === "selected").sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);
19370
19819
  let enactedCount = 0;
19371
19820
  for (const [id, e] of selected) {
19821
+ if (revoked.has(id)) continue;
19822
+ const parentOf = str5(e.metadata?.["parentIntentId"]);
19823
+ if (parentOf && revoked.has(parentOf)) continue;
19372
19824
  const intent = readIntent(id, e.metadata);
19373
19825
  const schema = this._resolve(intent.schema);
19374
19826
  if (schema?.kind === "composite" && schema.composedOf && schema.composedOf.length > 0) {
@@ -19417,6 +19869,18 @@ var MotorSchemaExecutor = class {
19417
19869
  predictedValence: predicted.expectedValence
19418
19870
  }
19419
19871
  });
19872
+ const awaitingText = enaction.mode === "communicate" ? str5(intent.parameters["content"]) ?? firstMessage(intent.parameters["messages"]) : void 0;
19873
+ set.push(consequenceEntity({
19874
+ intentId: id,
19875
+ schema: intent.schema,
19876
+ mode: enaction.mode === "communicate" ? "communicate" : "external",
19877
+ ...enaction.mode === "communicate" ? { effector: COMM_SCHEMA_TO_EFFECTOR[intent.schema] ?? intent.schema } : {},
19878
+ ...intent.targetEntityId ? { targetEntityId: intent.targetEntityId } : {},
19879
+ ...awaitingText ? { text: awaitingText, textHash: fnv1a(awaitingText) } : {},
19880
+ paramsHash: fnv1a(paramsKey(intent.parameters)),
19881
+ expiresAt: tick + CONSEQUENCE_TTL_TICKS,
19882
+ tick
19883
+ }));
19420
19884
  this._emitDispatch(intent, enaction.mode, tick);
19421
19885
  metrics.push([enaction.mode === "communicate" ? "agency.communicate.dispatched" : "agency.invocation.dispatched", 1]);
19422
19886
  }
@@ -19583,6 +20047,18 @@ var MotorSchemaExecutor = class {
19583
20047
  };
19584
20048
  set.push(outcomeEntity(tick, intent, out, predicted));
19585
20049
  del.push(id);
20050
+ if (result.success)
20051
+ set.push(consequenceEntity({
20052
+ intentId: id,
20053
+ schema: intent.schema,
20054
+ mode: "communicate",
20055
+ effector,
20056
+ ...intent.targetEntityId ? { targetEntityId: intent.targetEntityId } : {},
20057
+ textHash: fnv1a(bubbles.join("\n")),
20058
+ text: bubbles.join("\n"),
20059
+ expiresAt: tick + CONSEQUENCE_TTL_TICKS,
20060
+ tick
20061
+ }));
19586
20062
  this._emitEnacted(intent, out, predicted, tick);
19587
20063
  this._emitActionOutcome(
19588
20064
  intent,
@@ -19919,6 +20395,10 @@ function readSchema(m) {
19919
20395
 
19920
20396
  // src/cognition/agency/engines/reafference.engine.ts
19921
20397
  var PROC_THRESHOLD2 = 0.6;
20398
+ var SENSORY_SOFT_QUALITY = 0.6;
20399
+ var SENSORY_VALENCE_SPAN_ENTITY = 0.25;
20400
+ var SENSORY_VALENCE_SPAN_AMBIENT = 0.1;
20401
+ var SENSORY_SUCCESS_FLOOR = 0.5;
19922
20402
  var ReafferenceEngine = class {
19923
20403
  name = "reafference";
19924
20404
  _repertoire;
@@ -19968,14 +20448,64 @@ var ReafferenceEngine = class {
19968
20448
  const set = [];
19969
20449
  const del = [];
19970
20450
  const metrics = [];
19971
- let updates = 0;
19972
- let discovered = 0;
20451
+ const outcomes = [];
20452
+ const gradedIntentIds = /* @__PURE__ */ new Set();
19973
20453
  for (const [id, e] of state.entities) {
19974
20454
  if (e.type !== "agency.outcome") continue;
19975
20455
  const m = e.metadata ?? {};
20456
+ outcomes.push({ id, meta: m, fromState: true });
20457
+ const iid = str6(m["intentId"]);
20458
+ if (iid) gradedIntentIds.add(iid);
20459
+ }
20460
+ const awaiting = /* @__PURE__ */ new Map();
20461
+ for (const [id, e] of state.entities) {
20462
+ if (e.type !== "agency.intent" || str6(e.metadata?.["status"]) !== "awaiting") continue;
20463
+ const m = e.metadata ?? {};
20464
+ if (tick - num4(m["dispatchedAt"], tick) >= AWAIT_TIMEOUT) continue;
20465
+ awaiting.set(id, {
20466
+ schema: str6(m["schema"]) ?? "",
20467
+ predictedReward: num4(m["predictedReward"], 0.5),
20468
+ predictedValence: num4(m["predictedValence"], 0)
20469
+ });
20470
+ }
20471
+ let sensory = 0;
20472
+ const sensedIntentIds = /* @__PURE__ */ new Set();
20473
+ for (const [, e] of state.entities) {
20474
+ if (e.type !== "percept") continue;
20475
+ const m = e.metadata ?? {};
20476
+ if (str6(m["provenance"]) !== "reafferent") continue;
20477
+ const iid = str6(m["sourceIntentId"]);
20478
+ if (!iid || gradedIntentIds.has(iid) || sensedIntentIds.has(iid)) continue;
20479
+ const aw = awaiting.get(iid);
20480
+ if (!aw || !aw.schema) continue;
20481
+ sensedIntentIds.add(iid);
20482
+ sensory++;
20483
+ const feltRaw = m["valence"];
20484
+ const felt = typeof feltRaw === "number" && Number.isFinite(feltRaw) ? feltRaw : void 0;
20485
+ const span = str6(m["valenceSource"]) === "entity" ? SENSORY_VALENCE_SPAN_ENTITY : SENSORY_VALENCE_SPAN_AMBIENT;
20486
+ const quality = felt === void 0 ? SENSORY_SOFT_QUALITY : clamp0111(SENSORY_SOFT_QUALITY + Math.max(-1, Math.min(1, felt)) * span);
20487
+ outcomes.push({ id: `agency-outcome-${tick}-${iid}-sensory`, fromState: false, meta: {
20488
+ schema: aw.schema,
20489
+ intentId: iid,
20490
+ success: quality >= SENSORY_SUCCESS_FLOOR,
20491
+ outcomeQuality: quality,
20492
+ valence: felt ?? aw.predictedValence,
20493
+ predictedReward: aw.predictedReward,
20494
+ predictedValence: aw.predictedValence,
20495
+ surprise: clamp0111(Math.abs(aw.predictedReward - quality)),
20496
+ mode: "external",
20497
+ reconciled: true,
20498
+ sensory: true,
20499
+ ...felt !== void 0 ? { sensoryValence: felt, valenceSource: str6(m["valenceSource"]) } : {},
20500
+ tick
20501
+ } });
20502
+ }
20503
+ let updates = 0;
20504
+ let discovered = 0;
20505
+ for (const { id, meta: m, fromState } of outcomes) {
19976
20506
  const schema = str6(m["schema"]);
19977
20507
  if (!schema) {
19978
- del.push(id);
20508
+ if (fromState) del.push(id);
19979
20509
  continue;
19980
20510
  }
19981
20511
  const { skill, proceduralized } = this._repertoire.recordOutcome({
@@ -19987,7 +20517,7 @@ var ReafferenceEngine = class {
19987
20517
  tick
19988
20518
  });
19989
20519
  set.push(skillEntity(skill));
19990
- del.push(id);
20520
+ if (fromState) del.push(id);
19991
20521
  const intentId = str6(m["intentId"]);
19992
20522
  if (intentId) del.push(intentId);
19993
20523
  updates++;
@@ -20015,7 +20545,8 @@ var ReafferenceEngine = class {
20015
20545
  ["agency.learning.updates", updates],
20016
20546
  ["agency.discovered.count", discovered],
20017
20547
  ["agency.skill.count", skills.size],
20018
- ["agency.habitual.count", habitual]
20548
+ ["agency.habitual.count", habitual],
20549
+ ["agency.sensory.confirmed", sensory]
20019
20550
  );
20020
20551
  return { commands: { set, delete: del, metrics } };
20021
20552
  }
@@ -20099,6 +20630,9 @@ function str6(v) {
20099
20630
  function num4(v, fallback) {
20100
20631
  return typeof v === "number" && Number.isFinite(v) ? v : fallback;
20101
20632
  }
20633
+ function clamp0111(n) {
20634
+ return n < 0 ? 0 : n > 1 ? 1 : n;
20635
+ }
20102
20636
 
20103
20637
  // src/stem/assembly.audit.ts
20104
20638
  function fieldForAttach(method) {
@@ -23151,12 +23685,13 @@ async function checkIdentityCoherence(input, reviewer) {
23151
23685
  return { ok: !issues.some((i) => i.severity === "error"), ran: true, issues, raw: text };
23152
23686
  }
23153
23687
  async function reviewIdentityCoherence(input, opts = {}) {
23688
+ const provider = process.env.WILL_LLM_PROVIDER ?? "anthropic";
23154
23689
  const director = new LLMDirector({
23155
23690
  willId: opts.willId ?? "identity-coherence",
23156
- model: process.env.WILL_LLM_MODEL ?? "claude-sonnet-4-5-20250929",
23691
+ model: process.env.WILL_LLM_MODEL ?? defaultModelFor(provider),
23157
23692
  maxOutputTokens: 512,
23158
23693
  apiKey: process.env.WILL_LLM_API_KEY ?? process.env.ANTHROPIC_API_KEY ?? "",
23159
- provider: process.env.WILL_LLM_PROVIDER ?? "anthropic",
23694
+ provider,
23160
23695
  sessionLogger: null,
23161
23696
  baseUrl: process.env.WILL_LLM_BASE_URL ?? process.env.OPENAI_BASE_URL,
23162
23697
  // When a per-Will tracker is supplied, the creation-time review records under
@@ -24481,6 +25016,10 @@ var OutboxController = class {
24481
25016
  summary: delivered ? `My message was delivered successfully.` : `My message failed to reach the recipient.`,
24482
25017
  salience: delivered ? 0.35 : 0.6,
24483
25018
  changeType: delivered ? "delivered" : "failed",
25019
+ // Reafference by construction — this percept describes our own action's
25020
+ // outcome ("ear hears the word"). Tagged, not attenuated: it is the ack
25021
+ // surface, not a content echo (EXAFFERENCE P2).
25022
+ provenance: "reafferent",
24484
25023
  messageId
24485
25024
  }
24486
25025
  });
@@ -24882,7 +25421,7 @@ var InboundQueue = class {
24882
25421
  function reconcileInvocation(intentId, schema, result, tick, predicted = { reward: 0.5, valence: 0 }, provenance = {}) {
24883
25422
  const outcomeQuality = result.outcomeQuality ?? (result.success ? 0.8 : 0.1);
24884
25423
  const valence = result.valence ?? (result.success ? 0.2 : -0.2);
24885
- const surprise = clamp0111(Math.abs(predicted.reward - outcomeQuality));
25424
+ const surprise = clamp0112(Math.abs(predicted.reward - outcomeQuality));
24886
25425
  return {
24887
25426
  id: `agency-outcome-${tick}-${intentId}`,
24888
25427
  type: "agency.outcome",
@@ -24904,7 +25443,7 @@ function reconcileInvocation(intentId, schema, result, tick, predicted = { rewar
24904
25443
  }
24905
25444
  };
24906
25445
  }
24907
- function clamp0111(n) {
25446
+ function clamp0112(n) {
24908
25447
  return n < 0 ? 0 : n > 1 ? 1 : n;
24909
25448
  }
24910
25449
 
@@ -26469,7 +27008,9 @@ var Will = class _Will {
26469
27008
  }
26470
27009
  // ── Internals ──────────────────────────────────────────────
26471
27010
  _buildConfig(id, opts) {
26472
- const useMock = (opts.llm ?? (process.env.ANTHROPIC_API_KEY ? "anthropic" : "mock")) === "mock";
27011
+ const mode = opts.llm ?? (process.env.ANTHROPIC_API_KEY ? "anthropic" : process.env.ZAI_API_KEY ? "glm" : "mock");
27012
+ const useMock = mode === "mock";
27013
+ const llmConfig = mode === "glm" ? { provider: "glm", ...opts.llmConfig } : opts.llmConfig;
26473
27014
  return {
26474
27015
  id,
26475
27016
  name: opts.name,
@@ -26481,7 +27022,7 @@ var Will = class _Will {
26481
27022
  },
26482
27023
  anatomy: opts.anatomy ?? "mind",
26483
27024
  model: opts.model,
26484
- llm: opts.llmConfig,
27025
+ llm: llmConfig,
26485
27026
  testMode: useMock,
26486
27027
  persistentMemory: opts.persist ?? false,
26487
27028
  snapshotInterval: 100,