Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
216 commits
Select commit Hold shift + click to select a range
0ef1ef8
Asynchronous engine: entities may join and leave a running simulation
concordia-claw Oct 26, 2026
a5ad6b0
Entity agents can add and remove context components while they live
concordia-claw Oct 26, 2026
f9cfd15
Bounded logs for long asynchronous runs
concordia-claw Oct 26, 2026
7a095a4
Merge async-dynamic-population (integration of the core PRs)
concordia-claw Oct 26, 2026
28d47f4
Merge entity-dynamic-components (integration of the core PRs)
concordia-claw Oct 26, 2026
dcf05d9
Merge bounded-async-logs (integration of the core PRs)
concordia-claw Oct 26, 2026
969e598
Measurements can keep only the most recent data of each channel
concordia-claw Oct 26, 2026
f7698dc
Merge bounded-async-logs (integration of the core PRs)
concordia-claw Oct 26, 2026
491621a
examples: Lifeways, a sandbox where culture evolves (the skeleton)
concordia-claw Oct 26, 2026
6abd6d1
examples: Lifeways passes customs on by what people do
concordia-claw Oct 26, 2026
25003d7
examples: Lifeways keeps its memory flat over indefinite runs
concordia-claw Oct 26, 2026
4c01506
examples: Lifeways shares, shames and makes norms its own
concordia-claw Oct 26, 2026
79f3cb0
examples: Lifeways welcomes strangers and feeds 20-60 people
concordia-claw Oct 26, 2026
46bf8f5
examples: Lifeways founders differ in how they hold the sharing norm
concordia-claw Oct 26, 2026
08b47a0
examples: Lifeways writes customs down in libraries that outlive them
concordia-claw Oct 26, 2026
3643af0
examples: Lifeways schools teach other people's children
concordia-claw Oct 26, 2026
ad70f3e
examples: Lifeways holds rites at shrines
concordia-claw Oct 26, 2026
599cde5
examples: Lifeways fixes what audit #8 found
concordia-claw Oct 26, 2026
c22b681
examples: Lifeways tells stories and preaches
concordia-claw Oct 26, 2026
de5ffe0
examples: Lifeways lets the Experimenter release customs it designs
concordia-claw Oct 26, 2026
b73a4f6
examples: Lifeways speaks in dialects that drift apart
concordia-claw Oct 26, 2026
7bd0611
examples: Lifeways courts by name under marriage rules; peoples emerge
concordia-claw Oct 26, 2026
138c995
examples: Lifeways presets, and a land that regulates its people
concordia-claw Oct 26, 2026
cc77130
examples: Lifeways page, played by a person as the Experimenter
concordia-claw Oct 26, 2026
611f54f
examples: Lifeways feeds 20-60 for a thousand years; the page knows w…
concordia-claw Oct 26, 2026
bd4c5ff
examples: Lifeways plays with live minds from Ollama
concordia-claw Oct 26, 2026
03c9f26
examples: Lifeways lets the Experimenter interview people
concordia-claw Oct 26, 2026
0a47219
examples: Lifeways runs with any contrib model; counts calls and tokens
concordia-claw Oct 26, 2026
7988b80
examples: Lifeways free mode for live play
concordia-claw Oct 26, 2026
63271be
examples: Lifeways fixes what audit #9 found
concordia-claw Oct 26, 2026
fb5f124
examples: a Lifeways page world outlives its server
concordia-claw Oct 26, 2026
1340c8d
examples: Lifeways forks a twin of the page's world
concordia-claw Oct 26, 2026
06ba83e
examples: Lifeways draws kinship and the lineages of customs
concordia-claw Oct 26, 2026
226bc76
examples: Lifeways keeps the Experimenter's lab notebook
concordia-claw Oct 26, 2026
41eb58b
examples: Lifeways follows a person's releases until they die out
concordia-claw Oct 26, 2026
e570d70
examples: Lifeways sends disasters and brings migrants
concordia-claw Oct 26, 2026
6ad4021
examples: Lifeways names the map's ring for what it marks
concordia-claw Oct 26, 2026
bf2ab27
examples: Lifeways lets the Experimenter found and close institutions
concordia-claw Oct 26, 2026
bb4b3a4
examples: Lifeways says how a release fares in the twin
concordia-claw Oct 26, 2026
e4116dd
examples: Lifeways outlines recent disasters on the map
concordia-claw Oct 26, 2026
99164f0
examples: Lifeways says the chance a song at the ring is taken up
concordia-claw Oct 26, 2026
3721467
examples: Lifeways fixes what audit #10 found
concordia-claw Oct 26, 2026
eb67dd0
examples: Lifeways plays live minds on the page
concordia-claw Oct 26, 2026
030fd73
examples: Lifeways runs experiments over seeds
concordia-claw Oct 26, 2026
b219151
examples: Lifeways serves its page behind a proxy that strips the prefix
concordia-claw Oct 26, 2026
27d10a3
examples: Lifeways may part valleys altogether, and children may spea…
concordia-claw Oct 26, 2026
5c006ee
Lifeways: Bridged Valleys preset, peoples on the chart, new worlds by…
concordia-claw Oct 27, 2026
b06d414
Lifeways: what the owner's first play showed (releases that reach peo…
concordia-claw Oct 27, 2026
d6b97dc
PlayerRoster: players join and leave a game through its game master
concordia-claw Oct 27, 2026
7f7f344
Revert Simulation.remove_entity (#425): players leave through a Playe…
concordia-claw Oct 27, 2026
7e1c67c
Merge player-roster (integration of the core PRs)
concordia-claw Oct 27, 2026
5c92e94
PlayerRoster: players join and leave a game through its game master
concordia-claw Oct 27, 2026
5a6691a
examples: Lifeways' born and dead join and leave through a PlayerRoster
concordia-claw Oct 27, 2026
c035dc3
Merge async-dynamic-population (#425 with PlayerRoster; integration o…
concordia-claw Oct 27, 2026
f9ff54c
examples: Lifeways saves are of form 2 (the born in the roster's stat…
concordia-claw Oct 27, 2026
760db0d
PlayerRoster is ActionSpecIgnored: other components may condition on …
concordia-claw Oct 27, 2026
081bdea
Asynchronous engine: unchanged checkpoints, and threads freed as play…
concordia-claw Oct 27, 2026
4b55f1d
Merge async-dynamic-population (#425 after review and audit #11; inte…
concordia-claw Oct 27, 2026
7aec3d7
examples: Lifeways fixes what audit #11 found
concordia-claw Oct 27, 2026
a4fc604
examples: Lifeways farms (DESIGN §2: fields once farming customs exist)
concordia-claw Oct 27, 2026
e25a30e
examples: Lifeways' mock minds follow a norm of tending fields
concordia-claw Oct 27, 2026
80efd88
examples: Lifeways' page server library defines no flags
concordia-claw Oct 27, 2026
cfdf784
Merge branch 'lifeways-example' into lifeways-next
concordia-claw Oct 27, 2026
11a49a5
examples: Lifeways' fields are their tenders', and may be spared
concordia-claw Oct 27, 2026
a154d5c
examples: Lifeways' seen deeds are a World setting (witnessed; WITNES…
concordia-claw Oct 27, 2026
ef9c6eb
examples: Lifeways fixes what audit #12 found
concordia-claw Oct 27, 2026
ac88e57
Lifeways: live in the valley as a founder
concordia-claw Oct 27, 2026
b75b83a
Lifeways: the played person's memory, readable
concordia-claw Oct 27, 2026
da295f2
Lifeways: a played person lives on after death
concordia-claw Oct 27, 2026
8c68755
Lifeways: no example answer in the yearly question
concordia-claw Oct 27, 2026
b003237
Lifeways: the played person follows the know-how its move needs
concordia-claw Oct 27, 2026
739c0bd
Lifeways: README, the know-how a played move follows
concordia-claw Oct 27, 2026
8d1fd91
Lifeways: the played person sees how far its ways reach
concordia-claw Oct 27, 2026
31b09aa
Lifeways: the notebook notes the player's deaths and rebirths
concordia-claw Oct 27, 2026
c26f9c8
Lifeways: ask for the move exactly as written
concordia-claw Oct 27, 2026
72614eb
Lifeways: a custom's text drifts about its line's first, never away
concordia-claw Oct 27, 2026
32a1224
Lifeways: a custom's lineage the page explains
concordia-claw Oct 27, 2026
288802e
Lifeways: every part of the page in words a newcomer reads
concordia-claw Oct 27, 2026
25b2234
Lifeways: no custom ids on the played person's panel
concordia-claw Oct 27, 2026
f04668e
Lifeways: a key to the map's land
concordia-claw Oct 27, 2026
6737e3c
Lifeways: the twin's lever and the save note in words
concordia-claw Oct 27, 2026
9bbb8c6
Lifeways: README, how customs change and how the page shows it
concordia-claw Oct 27, 2026
1a777a3
Lifeways: say what living as a founder is, where a new world begins
concordia-claw Oct 27, 2026
04995cc
Lifeways: a test that the notebook names no custom by its id
concordia-claw Oct 27, 2026
42bab2d
Lifeways: if-blocks for optional params, no design references in code
concordia-claw Oct 27, 2026
ba35d69
Lifeways: audit #13 fixes
concordia-claw Oct 27, 2026
a2b0bf0
Lifeways: what the page hides stays hidden
concordia-claw Oct 27, 2026
28ac7e4
Lifeways: audit #13b fixes
concordia-claw Oct 27, 2026
65753bf
Lifeways: audit #13c fixes
concordia-claw Oct 27, 2026
e8a66b3
Lifeways: audit #13d fixes
concordia-claw Oct 27, 2026
2f56a4e
Lifeways: places in words where they are written (audit #13e)
concordia-claw Oct 27, 2026
aba9292
Lifeways: the played person's memory as observed (audit #13f)
concordia-claw Oct 27, 2026
1c8b01c
Lifeways: the played person's status from the World (audit #13g)
concordia-claw Oct 27, 2026
316f952
Lifeways: old release places read only in the World's own report (aud…
concordia-claw Oct 27, 2026
68e85ba
Lifeways: the oldest notebooks in words too (audit #13i)
concordia-claw Oct 27, 2026
c07f2c3
Lifeways: old died-out notes keep a release's whole text (audit #13j)
concordia-claw Oct 27, 2026
fb46f91
Lifeways: release know-how with how good it is
concordia-claw Oct 27, 2026
ee4a3a5
Lifeways: what tends to spread, on the release form
concordia-claw Oct 27, 2026
918698b
Lifeways: the World reads a move said in another form
concordia-claw Oct 27, 2026
8c90788
Lifeways: audit #14 fixes
concordia-claw Oct 27, 2026
3fc0965
Lifeways: a move said in another form is the answerer's own (audit #14b)
concordia-claw Oct 27, 2026
d411443
Lifeways: README, how the release table was made (audit #14b)
concordia-claw Oct 27, 2026
9bd1e2a
Lifeways: no move read from a clause that only sets the scene (audit …
concordia-claw Oct 27, 2026
a6f0e27
Lifeways: "now" leads a clause; scene-setting phrases are not moves (…
concordia-claw Oct 27, 2026
8b9f612
Lifeways: scene-setting is now or an opening -ing; readings pinned (a…
concordia-claw Oct 27, 2026
c460710
Lifeways: ", so she" is the answerer's clause; ", she says" is not (a…
concordia-claw Oct 27, 2026
d462d56
Lifeways: an aside is not the answerer's clause, a report is (audit #…
concordia-claw Oct 27, 2026
8032cf7
Lifeways: "so she will spend the year" is the answerer's clause (audi…
concordia-claw Oct 27, 2026
ba8ed53
Lifeways: a local model is told nothing before each prompt
concordia-claw Oct 27, 2026
17550a5
Lifeways: keep the contrib model's own framing (revert ba8ed532)
concordia-claw Oct 28, 2026
f0eb8b8
Lifeways: a person's answer begins with their name, as stock prefabs do
concordia-claw Oct 28, 2026
838bca6
Lifeways: the README says how a mind is asked
concordia-claw Oct 28, 2026
df365be
Lifeways: the page tells a narrated answer by the World's own rule
concordia-claw Oct 28, 2026
113bdb6
Lifeways: read a mind's answer as it begins, with its name (audit 15)
concordia-claw Oct 28, 2026
52118a1
Lifeways: the census keeps the answers it could not read
concordia-claw Oct 28, 2026
0bfdcbb
Lifeways: a lineage says each thing once (UI review 36: U3, U4, U14, …
concordia-claw Oct 28, 2026
0ae91f4
Lifeways: open panels keep to the year; peoples are named (U1, U2)
concordia-claw Oct 28, 2026
fcd6d6a
Lifeways: the page says the pace it keeps; "End this world" (U5, U26)
concordia-claw Oct 28, 2026
5804817
Lifeways: the notebook notes the valley's own great changes (U6, U16)
concordia-claw Oct 28, 2026
552597b
Lifeways: the map's colours, and small words, explained (UI review 36)
concordia-claw Oct 28, 2026
8557777
Lifeways: an ask is acknowledged, and answered to the point (U7, U8)
concordia-claw Oct 28, 2026
b56cd37
Lifeways: the palette, graphs and units say what they mean (UI review…
concordia-claw Oct 28, 2026
bcc71eb
Lifeways: the last of UI review 36 (U17, U29, U30)
concordia-claw Oct 28, 2026
6c90cc9
Lifeways: know-how versions say their level; the people key, styled
concordia-claw Oct 28, 2026
95c9da2
Lifeways: an interview asks what the person says
concordia-claw Oct 28, 2026
0a8e1b6
Lifeways: a mind's new sentence after its name is what it says
concordia-claw Oct 28, 2026
0ffe57b
Merge async-dynamic-population (PR1 at 081bdea1, PlayerRoster as the …
concordia-claw Oct 28, 2026
272aa66
Merge lifeways-integration (main + PR1 + PR2 + PR3 at their tips)
concordia-claw Oct 28, 2026
e106d05
Lifeways: the census counts sowings that grew nothing
concordia-claw Oct 28, 2026
5032ce2
Lifeways: the README reports the property norm in two kinds of mind
concordia-claw Oct 28, 2026
176e4ca
Lifeways: the README says the property norm's harm is in the naming
concordia-claw Oct 28, 2026
fddf7ee
Lifeways: courts, where the valley judges those seen hoarding
concordia-claw Oct 28, 2026
4e4f7e1
Lifeways: an interview's report is one line, its spaces collapsed
concordia-claw Oct 28, 2026
b09ac44
Lifeways: the grown see where better land lies
concordia-claw Oct 28, 2026
82e63b0
Lifeways: the census says whether barren sowers still knew how
concordia-claw Oct 28, 2026
ae009ad
Lifeways: the README corrects the property norm's cause: lost know-how
concordia-claw Oct 28, 2026
d9c11d9
Lifeways: a person's panel shows what they let go to make room
concordia-claw Oct 28, 2026
fdd8d8c
Lifeways: a custom let go for one of its kind says so plainly
concordia-claw Oct 28, 2026
466b980
Lifeways: the page is legible on a phone, in both themes
concordia-claw Oct 28, 2026
5bb7d52
Lifeways: the page's long paragraphs become short lines and lists
concordia-claw Oct 28, 2026
7e8643e
Lifeways: a played person's situation is a line a fact
concordia-claw Oct 28, 2026
069a813
Merge origin/main 71046c61 (Adventure example) into the integration o…
concordia-claw Oct 28, 2026
ba9da9b
Merge lifeways-integration (main 71046c61 + PR1 + PR2 + PR3)
concordia-claw Oct 28, 2026
f3e7832
Lifeways: the page shows how Concordia builds it (owner's 40: 41, 42,…
concordia-claw Oct 29, 2026
ccb3172
Lifeways: colour the map's people by descent, people, tongue, food or…
concordia-claw Oct 29, 2026
df70ba5
Lifeways: tap a place to see who keeps it and what it holds
concordia-claw Oct 29, 2026
0edcf5e
Lifeways: a header that stays, and sections that fold (owner's 40: 33…
concordia-claw Oct 29, 2026
5f8a9bf
Lifeways: the map in words, and by keyboard (owner's 40: 35, 36)
concordia-claw Oct 29, 2026
10bb0f1
Lifeways: a first-visit tour, and what happened while you were away
concordia-claw Oct 29, 2026
d1506cb
Lifeways: find a person or a custom (owner's 40: 32)
concordia-claw Oct 29, 2026
64f898c
Lifeways: a custom's versions and a person's family, drawn (owner's 4…
concordia-claw Oct 29, 2026
c81f8d3
Lifeways: the release form says what a song would meet (owner's 40: 31)
concordia-claw Oct 29, 2026
e82e02c
Lifeways: how fair the valley is, year by year (owner's 40: 3)
concordia-claw Oct 29, 2026
3bcb534
Lifeways: what most hold, and each people, over the years (owner's 40…
concordia-claw Oct 29, 2026
effd83c
Lifeways: norms kept, seen and unseen (owner's 40: 6)
concordia-claw Oct 29, 2026
38c1dc6
Lifeways: surveys (owner's 40: 2)
concordia-claw Oct 29, 2026
f0d05c4
Lifeways: the twin, side by side (owner's 40: 8)
concordia-claw Oct 29, 2026
4cc8eac
Lifeways: the data, to keep as CSV (owner's 40: 7)
concordia-claw Oct 29, 2026
5dcdad4
Lifeways: hypotheses that check themselves (owner's 40: 10)
concordia-claw Oct 29, 2026
bdf71db
Lifeways: the lab, experiments over seeds on the page (owner's 40: 1, 9)
concordia-claw Oct 29, 2026
ca7d737
Lifeways: minds compared, a tool (owner's 40: 11, part 1)
concordia-claw Oct 29, 2026
5f8633d
Lifeways: good years and lean, fields inherited, replays, the world o…
concordia-claw Oct 29, 2026
02d90bd
Lifeways: markets, know-how for food (owner's 40: 13)
concordia-claw Oct 29, 2026
dd9aef5
Lifeways: authority, judges' standing and deference (owner's 40: 15)
concordia-claw Oct 29, 2026
35e5d1d
Lifeways: decision logic as customs, question customs (owner's 40: 16)
concordia-claw Oct 29, 2026
3ae16a0
Lifeways: stories of the old days (owner's 40: 17)
concordia-claw Oct 29, 2026
0d7c5b2
Lifeways: scripts that drift, texts that grow unreadable (owner's 40:…
concordia-claw Oct 29, 2026
37f2dff
Lifeways: over the pass, migration between valleys (owner's 40: 19)
concordia-claw Oct 29, 2026
8bfa7a0
Lifeways: a person reads its situation first (owner's 40: 20, part 1)
concordia-claw Oct 29, 2026
ad4d269
Lifeways: README tidied for the example PR (owner's 40: 44)
concordia-claw Oct 29, 2026
868d673
Lifeways: the lineage panel says how know-how and scripts change
concordia-claw Oct 29, 2026
8046bc3
Lifeways: audit #16's findings fixed; offer lines say less twice
concordia-claw Oct 29, 2026
f1927e0
Lifeways: the inspector names the stock part a question custom wraps
concordia-claw Oct 29, 2026
5e06ee2
Lifeways: minds.py starts at any seed (--first_seed)
concordia-claw Oct 29, 2026
55f6e0f
Lifeways: README, minds compared and a 10,000-year run
concordia-claw Oct 29, 2026
53cc180
Lifeways: the notebook notes ruins that held something
concordia-claw Oct 29, 2026
b2de739
Lifeways: README, small live minds had no children
concordia-claw Oct 29, 2026
c454a99
Lifeways: README, four minds compared (owner's 40: 11)
concordia-claw Oct 29, 2026
8f9a4e4
Lifeways: README, qwen3:1.7b joins the minds compared
concordia-claw Oct 29, 2026
627b8dd
Lifeways: situation first is off by default, measured on two seeds
concordia-claw Oct 30, 2026
9ac228e
Entity agents can add and remove context components while they live
concordia-claw Oct 26, 2026
2c4e0ef
Bounded logs for long asynchronous runs
concordia-claw Oct 26, 2026
ec913cf
Measurements can keep only the most recent data of each channel
concordia-claw Oct 26, 2026
f5774c6
Merge entity-dynamic-components (PR2 rebased onto 7ec68dbe) into the …
concordia-claw Oct 30, 2026
f56e78f
Merge bounded-async-logs (PR3 rebased onto 7ec68dbe) into the integra…
concordia-claw Oct 30, 2026
e1742a4
Merge lifeways-integration rebuilt on main 7ec68dbe (PR1 as Google me…
concordia-claw Oct 30, 2026
febe1ca
Lifeways: wait for engine loops by what their threads run
concordia-claw Oct 30, 2026
fd70061
Bounded logs for long asynchronous runs
concordia-claw Oct 26, 2026
8e6cbea
Measurements can keep only the most recent data of each channel
concordia-claw Oct 26, 2026
00de634
Merge entity-dynamic-components (PR2) into the integration of the cor…
concordia-claw Nov 5, 2026
87b2806
Merge bounded-async-logs (PR3 rebased onto 4e4aec94) into the integra…
concordia-claw Nov 5, 2026
4a8bcb9
Merge lifeways-integration rebuilt on main 4e4aec94 (PR3 rebased past…
concordia-claw Nov 5, 2026
75264cd
Lifeways: the server logs every thread's stack when a world stops clo…
concordia-claw Nov 5, 2026
ab862ae
Contrib: social ties, a game master's network of who is close to whom
concordia-claw Nov 5, 2026
83da508
Lifeways: social ties, from the contrib SocialTies (mechanic 1)
concordia-claw Nov 5, 2026
af4b3d0
Contrib: rumours, news that spreads along contacts and changes as it …
concordia-claw Nov 5, 2026
3de00a7
Contrib: reputation, what each participant thinks of the others
concordia-claw Nov 5, 2026
f7db0e6
Lifeways: rumours, from the contrib Rumors (mechanic 2)
concordia-claw Nov 5, 2026
7434b06
Contrib: gifts and debts, a ledger of who owes whom a return
concordia-claw Nov 5, 2026
d0cbd16
Lifeways: reputation for generosity, from the contrib Reputation (mec…
concordia-claw Nov 5, 2026
82f040d
Contrib: contagion, a sickness that passes between those who meet
concordia-claw Nov 5, 2026
d5b01d8
Lifeways: gifts and debts, from the contrib Reciprocity (mechanic 4)
concordia-claw Nov 5, 2026
427b0eb
Contrib: gatherings, recurring occasions where participants come toge…
concordia-claw Nov 5, 2026
2934156
Lifeways: sickness, from the contrib Contagion (mechanic 5)
concordia-claw Nov 5, 2026
1a469c5
Contrib: an assembly, motions proposed, voted on and passed into law
concordia-claw Nov 5, 2026
9f33289
Contrib: offices, named positions, their holders, terms and history
concordia-claw Nov 5, 2026
8c6c5bc
Lifeways: gatherings and the assembly, from the contrib Gatherings and
concordia-claw Nov 5, 2026
828da85
Contrib: pacts, agreements offered, accepted, kept, broken and ended
concordia-claw Nov 5, 2026
85e0b93
Lifeways: the valley's chief, from the contrib Offices (mechanic 8)
concordia-claw Nov 5, 2026
a1b5945
Contrib: feuds, grievances between groups, raids and peace
concordia-claw Nov 5, 2026
0bbd732
Lifeways: pacts of aid, from the contrib Pacts (mechanic 9)
concordia-claw Nov 5, 2026
d1db748
Lifeways: feuds between peoples, from the contrib Feuds (mechanic 10)
concordia-claw Nov 5, 2026
c706069
Lifeways: the page names a chief's gathering, and the news hint names…
concordia-claw Nov 5, 2026
94a1baa
Lifeways: the README shows how another game builds on a contrib mechanic
concordia-claw Nov 5, 2026
09ed322
Contrib mechanics: atomic restores, a case begins the step after it i…
concordia-claw Nov 5, 2026
d47c631
Lifeways: the World finds its mechanics by key, and audit fixes
concordia-claw Nov 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
218 changes: 211 additions & 7 deletions concordia/agents/entity_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,25 @@

"""A modular entity agent using the new component system."""

from collections.abc import Mapping
from collections.abc import Callable, Mapping, Sequence
from concurrent import futures
import functools
import threading
import traceback
import types
from typing import cast, override
from typing import Any, cast, override

from absl import logging
from concordia.typing import entity
from concordia.typing import entity_component
from concordia.utils import concurrency

# Builds a context component from the name and the JSON-serializable spec it
# was added with (see `EntityAgent.add_component`).
ComponentFactory = Callable[
[str, entity_component.ComponentState], entity_component.ContextComponent
]


class EntityAgent(entity_component.EntityWithComponents):
"""An agent that has its functionality defined by components.
Expand All @@ -36,6 +42,12 @@ class EntityAgent(entity_component.EntityWithComponents):
call the ActComponent's `act` method when it needs to act, and the
ObservationComponent's `observe` method when they need to process an
observation.

Context components may be added and removed while the agent lives
(`add_component`, `remove_component`), including by its own components
during `act` or `observe`: a change requested during a call takes effect
when that call ends, so the components never change in the middle of a
phase.
"""

def __init__(
Expand All @@ -45,6 +57,7 @@ def __init__(
context_components: Mapping[str, entity_component.ContextComponent] = (
types.MappingProxyType({})
),
component_factory: ComponentFactory | None = None,
):
"""Initializes the agent.

Expand All @@ -55,6 +68,8 @@ def __init__(
agent_name: The name of the agent.
act_component: The component that will be used to act.
context_components: The ContextComponents that will be used by the agent.
component_factory: Optional. Rebuilds components added with a spec
(`add_component`) when `set_state` restores a state that has them.
"""
super().__init__()
self._agent_name = agent_name
Expand All @@ -71,6 +86,21 @@ def __init__(
for component in self._context_components.values():
component.set_entity(self)

# The components given at construction (restorable if removed), the specs
# of components added since (None: not restorable), and changes waiting
# for the current act or observe call to end.
self._component_factory = component_factory
self._built_in_components = dict(self._context_components)
self._added_specs: dict[str, entity_component.ComponentState | None] = {}
self._changes_lock = threading.Lock()
self._pending_changes: list[
tuple[
str,
entity_component.ContextComponent | None,
entity_component.ComponentState | None,
]
] = []

@override
@functools.cached_property
def name(self) -> str:
Expand Down Expand Up @@ -104,6 +134,110 @@ def get_all_context_components(
) -> Mapping[str, entity_component.ContextComponent]:
return types.MappingProxyType(self._context_components)

def add_component(
self,
name: str,
component: entity_component.ContextComponent,
spec: entity_component.ComponentState | None = None,
) -> None:
"""Adds a context component to the agent.

The component is owned by this agent from then on. Requested while the
agent is neither acting nor observing, it is added at once; requested
during `act` or `observe` (e.g. by one of the agent's components), it is
added when that call ends.

Args:
name: The component's name (its key in the agent's contexts).
component: The component, not owned by any other entity.
spec: Optional JSON-serializable description of the component. With a
`component_factory`, `set_state` rebuilds the component from it;
without a spec, a restored state does not include the component.

Raises:
ValueError: If the agent has, or is about to have, a component of that
name, or the component is owned by another entity.
"""
try:
owner = component.get_entity()
except RuntimeError:
owner = None
if owner is not None and owner is not self:
raise ValueError(f'Component {name} belongs to another entity.')
with self._changes_lock:
if self._will_have_component(name):
raise ValueError(f'{self.name} already has a component named {name}.')
self._pending_changes.append((name, component, spec))
self._apply_changes_if_idle()

def remove_component(self, name: str) -> None:
"""Removes a context component from the agent.

Requested while the agent is neither acting nor observing, the component
is removed at once; requested during `act` or `observe`, it is removed
when that call ends. A removed component is not reused by other agents.

Args:
name: The component's name.

Raises:
KeyError: If the agent has, or is about to have, no such component.
ValueError: If the acting component's explicit context order names it.
"""
get_order = getattr(self._act_component, 'get_context_concat_order', None)
order = cast(Sequence[str] | None, get_order() if get_order else None)
if order is not None and name in order:
raise ValueError(
f'The acting component of {self.name} orders component {name}; it'
' cannot be removed.'
)
with self._changes_lock:
if not self._will_have_component(name):
raise KeyError(f'{self.name} has no component named {name}.')
self._pending_changes.append((name, None, None))
self._apply_changes_if_idle()

def _will_have_component(self, name: str) -> bool:
"""Whether the agent has the component once pending changes apply."""
present = name in self._context_components
for changed, component, _ in self._pending_changes:
if changed == name:
present = component is not None
return present

def _apply_changes_if_idle(self) -> None:
"""Applies pending changes now unless a call is under way."""
if self._control_lock.acquire(blocking=False):
try:
self._apply_pending_changes()
finally:
self._control_lock.release()

def _apply_pending_changes(self) -> None:
"""Applies added and removed components. Requires the control lock."""
with self._changes_lock:
changes, self._pending_changes = self._pending_changes, []
if not changes:
return
# Replaced, not changed in place: readers may hold the old mapping.
components = dict(self._context_components)
for name, component, spec in changes:
if component is None:
del components[name]
self._added_specs.pop(name, None)
else:
component.set_entity(self)
self._component_added(name, component)
components[name] = component
self._added_specs[name] = spec
self._context_components = components

def _component_added(
self, name: str, component: entity_component.ContextComponent
) -> None:
"""Called when a component joins the agent after construction."""
del name, component

def _parallel_call_(
self,
method_name: str,
Expand Down Expand Up @@ -174,15 +308,17 @@ def act(
self._parallel_call_('update')

self._set_phase(entity_component.Phase.READY)

return action_attempt
except Exception:
# Ensure correct error handling in the case of multiple threads
# using the same entity by setting the phase to ready before raising.
self.set_phase(entity_component.Phase.READY)
raise
finally:
self._active_capture_key = self._agent_name
self._apply_pending_changes()
# Changes requested as the call ended, after the line above.
self._apply_changes_if_idle()
return action_attempt

@override
def observe(self, observation: str) -> None:
Expand Down Expand Up @@ -211,11 +347,37 @@ def observe(self, observation: str) -> None:
raise
finally:
self._active_capture_key = self._agent_name
self._apply_pending_changes()
# Changes requested as the call ended, after the line above.
self._apply_changes_if_idle()

def set_state(
self, entity_components_state: entity_component.EntityState
) -> None:
"""Sets the state of the agent."""
"""Sets the state of the agent.

Components added and removed after construction are added and removed
again as the state records them (rebuilding added components through the
`component_factory`), before every component's state is restored.

Args:
entity_components_state: A state from `get_state`.

Raises:
ValueError: If the state has added components but the agent has no
`component_factory`.
"""
# A state without changes records the components given at construction.
dynamic = cast(
Mapping[str, Any],
entity_components_state.get('dynamic_components') or {},
)
changed = self._added_specs or set(self._context_components) != set(
self._built_in_components
)
if dynamic or changed:
with self._control_lock:
self._restore_component_set(dynamic)

# Restore context components
context_components_state = entity_components_state.get(
Expand All @@ -241,15 +403,57 @@ def set_state(
'Error setting state for act component: %s', traceback.format_exc()
)

def _restore_component_set(self, dynamic: Mapping[str, Any]) -> None:
"""Makes the components those a state records. Requires the lock."""
added: dict[str, entity_component.ComponentState] = dict(
dynamic.get('added', {})
)
removed = set(dynamic.get('removed', ()))
factory = self._component_factory
if added and factory is None:
raise ValueError(
f'{self.name} needs a component_factory to restore added components.'
)
with self._changes_lock:
self._pending_changes = []
components = {
name: component
for name, component in self._built_in_components.items()
if name not in removed
}
specs = {}
for name, spec in added.items():
current = self._context_components.get(name)
if current is not None and self._added_specs.get(name) == spec:
components[name] = current # Already this component.
elif factory is not None:
component = factory(name, spec)
component.set_entity(self)
self._component_added(name, component)
components[name] = component
specs[name] = spec
self._added_specs = specs
self._context_components = components

def get_state(self) -> entity_component.EntityState:
"""Returns the state of the agent as a dictionary."""
return {
components = self._context_components
state: dict[str, entity_component.ComponentState] = {
'act_component': self._act_component.get_state(),
'context_components': {
component_name: component.get_state()
for component_name, component in self._context_components.items()
for component_name, component in components.items()
},
}
removed = sorted(set(self._built_in_components) - set(components))
added = {
name: spec
for name, spec in self._added_specs.items()
if spec is not None and name in components
}
if added or removed:
state['dynamic_components'] = {'added': added, 'removed': removed}
return state

def set_phase(self, phase: entity_component.Phase) -> None:
with self._phase_lock:
Expand Down
Loading
Loading