rh-pycordis-kernel 0.3.0__py3-none-any.whl

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 (46) hide show
  1. rh_pycordis_kernel/__init__.py +23 -0
  2. rh_pycordis_kernel/agent/__init__.py +28 -0
  3. rh_pycordis_kernel/agent/events.py +90 -0
  4. rh_pycordis_kernel/agent/inbox.py +96 -0
  5. rh_pycordis_kernel/agent/loop.py +249 -0
  6. rh_pycordis_kernel/agent/service.py +47 -0
  7. rh_pycordis_kernel/boot.py +98 -0
  8. rh_pycordis_kernel/cli.py +150 -0
  9. rh_pycordis_kernel/config.py +41 -0
  10. rh_pycordis_kernel/cordis.rows.yml +27 -0
  11. rh_pycordis_kernel/environment_pool.py +159 -0
  12. rh_pycordis_kernel/flush_policy.py +24 -0
  13. rh_pycordis_kernel/frozen.py +54 -0
  14. rh_pycordis_kernel/launcher.py +115 -0
  15. rh_pycordis_kernel/log.py +6 -0
  16. rh_pycordis_kernel/market/__init__.py +0 -0
  17. rh_pycordis_kernel/market/index.py +63 -0
  18. rh_pycordis_kernel/market/info.py +41 -0
  19. rh_pycordis_kernel/market/project.py +112 -0
  20. rh_pycordis_kernel/market/publish.py +120 -0
  21. rh_pycordis_kernel/market/rows.py +90 -0
  22. rh_pycordis_kernel/messages.py +69 -0
  23. rh_pycordis_kernel/model.py +42 -0
  24. rh_pycordis_kernel/model_host.py +69 -0
  25. rh_pycordis_kernel/registry.py +22 -0
  26. rh_pycordis_kernel/session/__init__.py +23 -0
  27. rh_pycordis_kernel/session/closers.py +43 -0
  28. rh_pycordis_kernel/session/events.py +41 -0
  29. rh_pycordis_kernel/session/projections.py +38 -0
  30. rh_pycordis_kernel/session/session.py +211 -0
  31. rh_pycordis_kernel/session/states.py +37 -0
  32. rh_pycordis_kernel/session/store.py +94 -0
  33. rh_pycordis_kernel/session_jsonl/__init__.py +21 -0
  34. rh_pycordis_kernel/session_jsonl/persistence.py +84 -0
  35. rh_pycordis_kernel/session_jsonl/writer.py +210 -0
  36. rh_pycordis_kernel/signal.py +78 -0
  37. rh_pycordis_kernel/system_prompt.py +38 -0
  38. rh_pycordis_kernel/templates.py +8 -0
  39. rh_pycordis_kernel/tools/__init__.py +19 -0
  40. rh_pycordis_kernel/tools/results.py +43 -0
  41. rh_pycordis_kernel/tools/schema.py +76 -0
  42. rh_pycordis_kernel/tools/service.py +244 -0
  43. rh_pycordis_kernel-0.3.0.dist-info/METADATA +11 -0
  44. rh_pycordis_kernel-0.3.0.dist-info/RECORD +46 -0
  45. rh_pycordis_kernel-0.3.0.dist-info/WHEEL +4 -0
  46. rh_pycordis_kernel-0.3.0.dist-info/entry_points.txt +4 -0
@@ -0,0 +1,23 @@
1
+ """The harness core: session log, tools, agent loop, environment pool, launcher and market tooling.
2
+
3
+ The modules named in `cordis.rows.yml` are the kernel's Cordis plugins. What is exported here
4
+ is the vocabulary every plugin shares: the message format, reading the log, the model service,
5
+ the stop signal and prompt templates.
6
+ """
7
+
8
+ from .frozen import freeze, thaw
9
+ from .log import latest
10
+ from .messages import blocks, image, message, text, text_of, tool_call, tool_calls, tool_message, user_message
11
+ from .model import ModelService, model_of
12
+ from .signal import AbortController, AbortError, AbortSignal
13
+ from .templates import fill
14
+
15
+ __version__ = '0.3.0'
16
+
17
+ __all__ = [
18
+ 'freeze', 'thaw', 'latest',
19
+ 'blocks', 'image', 'message', 'text', 'text_of', 'tool_call', 'tool_calls', 'tool_message', 'user_message',
20
+ 'ModelService', 'model_of',
21
+ 'AbortController', 'AbortError', 'AbortSignal',
22
+ 'fill',
23
+ ]
@@ -0,0 +1,28 @@
1
+ """The agent loop plugin: `ReactLoopAgent`, its inbox, and `ctx.agents`.
2
+
3
+ Hooks, both waterfalls:
4
+
5
+ agent/pre-step ({agent, turn, step, messages}, next) -> {kind: 'enter', messages} | {kind: 'reject'}
6
+ agent/post-step ({agent, turn, step, config, message}, next) -> None
7
+
8
+ Notifications: `agent/inbox/inserted {agent, message}` and `agent/inbox/claimed {agent, message}`.
9
+ """
10
+
11
+ from pycordis import schema
12
+
13
+ from .service import Agents
14
+
15
+ name = 'agent'
16
+ inject = ['session_events', 'session_states', 'session_closers', 'system_prompt', 'tools']
17
+ Config = schema.object({
18
+ 'model': schema.dict_(schema.any_()).required().description(
19
+ 'The model config of every controller request: `model`, and whatever else the model service takes.'),
20
+ 'max_steps_per_turn': schema.natural().default(6).description(
21
+ 'Steps a turn may take. If the last one calls no action tool, the loop calls it itself.'),
22
+ 'max_turns': schema.natural().default(100).description(
23
+ 'Turns an episode may take before it ends with reason `max-turns`.'),
24
+ })
25
+
26
+
27
+ def apply(ctx, config):
28
+ Agents(ctx, config)
@@ -0,0 +1,90 @@
1
+ """The events the agent loop writes."""
2
+
3
+ from typing import NotRequired, TypedDict
4
+
5
+
6
+ class TurnStart(TypedDict):
7
+ turn: int
8
+
9
+
10
+ class TurnEnd(TypedDict):
11
+ turn: int
12
+ reason: str # 'completed' | 'aborted' | 'blocked' | 'error' | 'interrupted' (closed after a crash)
13
+
14
+
15
+ class StepStart(TypedDict):
16
+ turn: int
17
+ step: int
18
+
19
+
20
+ class StepEnd(TypedDict):
21
+ turn: int
22
+ step: int
23
+
24
+
25
+ class RetirePreviousTurn(TypedDict):
26
+ message: dict # empty: it stands in for every node the previous turn appended
27
+
28
+
29
+ class SystemMessage(TypedDict):
30
+ message: dict # {role: 'system', content: [{type: 'text', text}]}
31
+
32
+
33
+ class UserMessage(TypedDict):
34
+ turn: int
35
+ step: int
36
+ message: dict # the accepted UserMessage, unchanged: {id, role: 'user', content, source}
37
+
38
+
39
+ class RequestHeader(TypedDict):
40
+ header: dict # {config, tools}: everything the request needs besides its messages
41
+
42
+
43
+ class DeveloperMessage(TypedDict):
44
+ message: dict # tells the model what changed in the request header
45
+
46
+
47
+ class AssistantMessage(TypedDict):
48
+ turn: int
49
+ step: int
50
+ message: dict
51
+ forced: NotRequired[bool] # the loop called the action tool itself
52
+
53
+
54
+ class AssistantAttempt(TypedDict):
55
+ turn: int
56
+ step: int
57
+ error: NotRequired[str] # why the model call failed
58
+
59
+
60
+ class InboxSpliced(TypedDict):
61
+ target: str # 'next-turn' | 'next-step'
62
+ start: int # the index in the target queue where the change happens
63
+ inserted: list # the messages put in at `start`
64
+ removedCount: NotRequired[int]
65
+ outcome: NotRequired[str] # why messages were removed, e.g. 'rejected'
66
+
67
+
68
+ class EpisodeEnd(TypedDict):
69
+ reason: str # 'success' | 'max-turns'
70
+ turns: int
71
+
72
+
73
+ LOG_ONLY = {
74
+ 'turn/start': TurnStart,
75
+ 'turn/end': TurnEnd,
76
+ 'step/start': StepStart,
77
+ 'step/end': StepEnd,
78
+ 'request/header': RequestHeader,
79
+ 'assistant/attempt': AssistantAttempt,
80
+ 'agent/inbox/spliced': InboxSpliced,
81
+ 'episode/end': EpisodeEnd,
82
+ }
83
+
84
+ SURFACE = {
85
+ 'turn/retire-previous-turn': RetirePreviousTurn,
86
+ 'system/message': SystemMessage,
87
+ 'user/message': UserMessage,
88
+ 'developer/message': DeveloperMessage,
89
+ 'assistant/message': AssistantMessage,
90
+ }
@@ -0,0 +1,96 @@
1
+ """The inbox: messages queued for an agent's next step or next turn.
2
+
3
+ The log is the storage. Every change is one `agent/inbox/spliced` event, and the live queues
4
+ are the session state `inbox`, a fold of the log:
5
+
6
+ {'next-turn': [...], 'next-step': [...], 'admitted': [ids]}
7
+
8
+ A message appended as `user/message` is admitted: it stays in its queue, but `claim` skips it.
9
+ `turn/end` with reason `completed` is the commit that removes the admitted messages; any other
10
+ reason makes them pending again. So a turn that crashed delivers its messages again, and no
11
+ recovery code is needed.
12
+ """
13
+
14
+ import math
15
+ from itertools import groupby
16
+
17
+ TARGETS = ('next-turn', 'next-step')
18
+
19
+
20
+ def init():
21
+ return {'next-turn': [], 'next-step': [], 'admitted': []}
22
+
23
+
24
+ def apply(state, event):
25
+ type, data = event['type'], event['data']
26
+ if type == 'agent/inbox/spliced':
27
+ queue, start = state[data['target']], data['start']
28
+ after = start + data.get('removedCount', 0)
29
+ return {**state, data['target']: [*queue[:start], *data['inserted'], *queue[after:]]}
30
+ if type == 'user/message':
31
+ id = data['message']['id']
32
+ queued = any(message['id'] == id for target in TARGETS for message in state[target])
33
+ return {**state, 'admitted': [*state['admitted'], id]} if queued else state
34
+ if type == 'turn/end' and state['admitted']:
35
+ committed = state['admitted'] if data['reason'] == 'completed' else ()
36
+ return {target: [message for message in state[target] if message['id'] not in committed]
37
+ for target in TARGETS} | {'admitted': []}
38
+ return state
39
+
40
+
41
+ class Inbox:
42
+ """One agent's queues."""
43
+
44
+ def __init__(self, ctx, agent):
45
+ self.ctx = ctx
46
+ self.agent = agent
47
+
48
+ def pending(self, target):
49
+ """The messages in one queue that no step of the running turn has taken."""
50
+ state = self.agent.session.state('inbox')
51
+ return [message for message in state[target] if message['id'] not in state['admitted']]
52
+
53
+ def splice(self, target, start, delete_count=0, inserted=(), *, outcome=None):
54
+ """Remove `delete_count` messages at `start` of the `target` queue and insert `inserted` there.
55
+
56
+ A `start` of `math.inf` means the end of the queue. A message whose id is already queued
57
+ is refused.
58
+ """
59
+ state = self.agent.session.state('inbox')
60
+ queue = state[target]
61
+ start = len(queue) if start == math.inf else max(0, min(start, len(queue)))
62
+ queued = {message['id'] for name in TARGETS for message in state[name]}
63
+ for message in inserted:
64
+ if message['id'] in queued:
65
+ raise ValueError(f'inbox: message {message["id"]} is already queued')
66
+ queued.add(message['id'])
67
+
68
+ data = {'target': target, 'start': start, 'inserted': list(inserted)}
69
+ if removed := len(queue[start:start + delete_count]):
70
+ data['removedCount'] = removed
71
+ if outcome:
72
+ data['outcome'] = outcome
73
+ self.agent.session.append('agent/inbox/spliced', data)
74
+ for message in inserted:
75
+ self.ctx.emit('agent/inbox/inserted', {'agent': self.agent, 'message': message})
76
+
77
+ def claim(self, target):
78
+ """Every pending message a step may take: `next-step`, then `next-turn` on a turn's first step.
79
+
80
+ The claim is in memory only: nothing is removed and nothing is logged.
81
+ """
82
+ targets = ('next-step', 'next-turn') if target == 'next-turn' else ('next-step',)
83
+ claimed = [message for name in targets for message in self.pending(name)]
84
+ for message in claimed:
85
+ self.ctx.emit('agent/inbox/claimed', {'agent': self.agent, 'message': message})
86
+ return claimed
87
+
88
+ def reject(self, claimed):
89
+ """Remove the claimed messages of a rejected step: one splice per run of them in each queue."""
90
+ ids = {message['id'] for message in claimed}
91
+ for target in TARGETS:
92
+ queue = self.agent.session.state('inbox')[target]
93
+ runs = [list(group) for rejected, group in groupby(range(len(queue)), lambda i: queue[i]['id'] in ids)
94
+ if rejected]
95
+ for run in reversed(runs): # from the end, so earlier indexes stay valid
96
+ self.splice(target, run[0], len(run), outcome='rejected')
@@ -0,0 +1,249 @@
1
+ """The agent loop: the driver of one session."""
2
+
3
+ import itertools
4
+ import json
5
+ import math
6
+ import uuid
7
+
8
+ from ..log import latest
9
+ from ..messages import message, text_of, tool_call, tool_calls
10
+ from ..model import model_of
11
+ from ..signal import AbortController, AbortError
12
+ from .inbox import Inbox
13
+
14
+ RETRIES = 2 # how often a failed model call is asked again
15
+
16
+
17
+ class ReactLoopAgent:
18
+ """Controls a robot in turns: the model gathers information over steps, then acts once.
19
+
20
+ A turn is the steps from `turn/start` until the model calls an action tool, a tool whose
21
+ name starts with `action`; that call ends the turn. A step is one model call and the tool
22
+ call it makes. Each turn's messages are retired when the next turn starts.
23
+
24
+ The agent keeps no message list. Each phase writes facts with the synchronous
25
+ `session.append`, and the request is rebuilt from the log right before every model call.
26
+ """
27
+
28
+ def __init__(self, ctx, session, config):
29
+ self.ctx = ctx
30
+ self.session = session
31
+ self.config = config
32
+ self.inbox = Inbox(ctx, self)
33
+ self._cancelled = False
34
+ self._stop = AbortController() # the stop signal of the running turn
35
+
36
+ def send(self, message, target='next-turn'):
37
+ """Queue a UserMessage for the agent's next turn (a follow-up) or next step (a steer)."""
38
+ self.inbox.splice(target, math.inf, 0, [message])
39
+
40
+ def cancel(self):
41
+ """Cancel the running turn, and start no further one. A running tool sees it as `exec.signal`."""
42
+ self._cancelled = True
43
+ self._stop.abort(AbortError('tool call aborted'))
44
+
45
+ async def run(self):
46
+ """Run turns until the episode ends or the agent is cancelled. Returns the data of `episode/end`, if any.
47
+
48
+ A turn that fails ends with reason `error` and raises; the session can be resumed.
49
+ """
50
+ session, log = self.session, self.session.log
51
+ if latest(log, 'system/message') is None:
52
+ self._open()
53
+ while (end := latest(log, 'episode/end')) is None and not self._cancelled:
54
+ start = latest(log, 'turn/start')
55
+ turn = start['data']['turn'] + 1 if start else 1
56
+ if turn > self.config['max_turns']:
57
+ session.append('episode/end', {'reason': 'max-turns', 'turns': turn - 1})
58
+ elif await self._turn(turn):
59
+ session.append('episode/end', {'reason': 'success', 'turns': turn})
60
+ return end and end['data']
61
+
62
+ # ------------------------------------------------------------------ turns
63
+
64
+ def _open(self):
65
+ """Before turn 1: log the system message and the request header outside any turn, so they never retire."""
66
+ assembly = self.ctx.system_prompt.assemble()
67
+ self.session.append('system/message', {'message': message('system', assembly['system'])}, surface_op='append')
68
+ self.session.append('request/header', {'header': self._header(assembly)})
69
+
70
+ async def _turn(self, turn):
71
+ """One turn, from `turn/start` to `turn/end`. Returns the `success` of the action it ended with."""
72
+ self._retire_previous_turn()
73
+ self.session.append('turn/start', {'turn': turn})
74
+ self._stop = AbortController()
75
+ try:
76
+ reason, success = await self._steps(turn)
77
+ except AbortError:
78
+ reason, success = 'aborted', False
79
+ except Exception:
80
+ self._end_turn(turn, 'error')
81
+ raise
82
+ self._end_turn(turn, reason)
83
+ return success
84
+
85
+ def _end_turn(self, turn, reason):
86
+ self.session.append('turn/end', {'turn': turn, 'reason': reason})
87
+ self.ctx.logger('agent').info('%s: turn %d %s', self.session.id, turn, reason)
88
+
89
+ def _retire_previous_turn(self):
90
+ """Replace every node the previous turn created with one empty node, so each turn gathers afresh.
91
+
92
+ The run is taken by position in `nodes`. A node that replaced an older one, such as a
93
+ changed system message, was logged inside the turn but is not part of the run.
94
+ """
95
+ log = self.session.log
96
+ start, end = latest(log, 'turn/start'), latest(log, 'turn/end')
97
+ if start is None:
98
+ return
99
+ first, last = start['seq'], end['seq'] if end and end['seq'] > start['seq'] else math.inf
100
+ ops = {seq: log[seq]['surfaceOp'] for seq in self.session.nodes if first < seq < last}
101
+ run = [seq for seq, op in ops.items() if op == 'append' or op['startSeq'] > first]
102
+ if run:
103
+ self.session.append('turn/retire-previous-turn', {'message': message('user', [])},
104
+ surface_op={'op': 'replace', 'startSeq': run[0], 'endSeq': run[-1]})
105
+
106
+ async def _steps(self, turn):
107
+ """Run steps until one ends the turn. Returns the turn's end reason and the action's `success`."""
108
+ for step in itertools.count(1):
109
+ self._stop.signal.throw_if_aborted()
110
+ admitted = await self._admit(turn, step)
111
+ if admitted is None:
112
+ return 'blocked', False
113
+ action = await self._step(turn, step, *admitted)
114
+ if action is not None:
115
+ return 'completed', not action['isError'] and action['value'].get('success') is True
116
+
117
+ # ------------------------------------------------------------------ pre step
118
+
119
+ async def _admit(self, turn, step):
120
+ """Claim the inbox, assemble the prompt, and let plugins add messages or reject the step.
121
+
122
+ Returns the assembly and the accepted messages, or None for a rejected step. Nothing is
123
+ logged yet, except the removal of a rejected step's messages.
124
+ """
125
+ claimed = self.inbox.claim('next-turn' if step == 1 else 'next-step')
126
+ assembly = self.ctx.system_prompt.assemble()
127
+ payload = {'agent': self, 'turn': turn, 'step': step, 'messages': list(claimed)}
128
+
129
+ async def enter():
130
+ return {'kind': 'enter', 'messages': payload['messages']}
131
+
132
+ decision = await self.ctx.waterfall('agent/pre-step', payload, enter)
133
+ if decision['kind'] == 'reject':
134
+ self.inbox.reject(claimed)
135
+ return None
136
+ claimed_ids = {message['id'] for message in claimed}
137
+ if [message for message in decision['messages'] if message['id'] in claimed_ids] != claimed:
138
+ raise ValueError('agent/pre-step: an enter must keep every claimed message, unchanged and in order')
139
+ return assembly, decision['messages']
140
+
141
+ async def _step(self, turn, step, assembly, messages):
142
+ """One step, from `step/start` to `step/end`. Returns the action tool's result if one was called."""
143
+ session, at = self.session, {'turn': turn, 'step': step}
144
+ session.append('step/start', at)
145
+ try:
146
+ self._log_system(assembly['system'])
147
+ for accepted in messages:
148
+ session.append('user/message', {**at, 'message': accepted}, surface_op='append')
149
+ header = self._log_header(self._header(assembly))
150
+ reply = await self._ask(at, header)
151
+ action = await self._dispatch(at, header, reply)
152
+ post = {'agent': self, **at, 'config': header['config'], 'message': reply}
153
+ await self.ctx.waterfall('agent/post-step', post, _done)
154
+ return action
155
+ finally:
156
+ session.append('step/end', at)
157
+
158
+ def _header(self, assembly):
159
+ return {'config': self.config['model'], 'tools': assembly['tools']}
160
+
161
+ def _log_system(self, system):
162
+ """Append `system/message` when the text changed. It replaces the previous one at nodes[0], and only it."""
163
+ current = self.session.log[self.session.nodes[0]]
164
+ if text_of(current['data']['message']) != system:
165
+ seq = current['seq']
166
+ self.session.append('system/message', {'message': message('system', system)},
167
+ surface_op={'op': 'replace', 'startSeq': seq, 'endSeq': seq})
168
+
169
+ def _log_header(self, header):
170
+ """Append `request/header` when it changed, with a developer message that tells the model what did."""
171
+ previous = latest(self.session.log, 'request/header')['data']['header']
172
+ if header != previous:
173
+ self.session.append('request/header', {'header': header})
174
+ notice = message('developer', header_changes(previous, header))
175
+ self.session.append('developer/message', {'message': notice}, surface_op='append')
176
+ return header
177
+
178
+ # ------------------------------------------------------------------ execution
179
+
180
+ async def _ask(self, at, header):
181
+ """Await the model's reply to the request rebuilt from the log, and log it. A failed call is retried."""
182
+ request = {**header, 'messages': self.session.derive_messages()}
183
+ for attempt in itertools.count():
184
+ try:
185
+ reply = await model_of(self.ctx).complete(request, signal=self._stop.signal)
186
+ break
187
+ except AbortError:
188
+ raise
189
+ except Exception as error:
190
+ self.session.append('assistant/attempt', {**at, 'error': f'{type(error).__name__}: {error}'})
191
+ if attempt == RETRIES:
192
+ raise
193
+ logged = self.session.append('assistant/message', {**at, 'message': _with_one_call(reply)}, surface_op='append')
194
+ return logged['data']['message']
195
+
196
+ async def _dispatch(self, at, header, reply):
197
+ """Run the reply's tool call. On the turn's last step, call the action tool if the model didn't.
198
+
199
+ Returns the result of the action tool, or None if the step called none.
200
+ """
201
+ call = next(iter(tool_calls(reply)), None)
202
+ result = await self._call(at, header, call) if call else None
203
+ if not _is_action(call) and at['step'] >= self.config['max_steps_per_turn']:
204
+ call = tool_call(f'forced-{uuid.uuid4().hex[:12]}', _action_tool(header))
205
+ forced = {**at, 'message': message('assistant', [call]), 'forced': True}
206
+ self.session.append('assistant/message', forced, surface_op='append') # so the call pairs with its result
207
+ result = await self._call(at, header, call)
208
+ return result if _is_action(call) else None
209
+
210
+ async def _call(self, at, header, call):
211
+ result = await self.ctx.tools.execute(call, agent=self, **at, signal=self._stop.signal, offered=header['tools'])
212
+ self._stop.signal.throw_if_aborted()
213
+ return result
214
+
215
+
216
+ async def _done():
217
+ return None
218
+
219
+
220
+ def _is_action(call):
221
+ return call is not None and call['name'].startswith('action')
222
+
223
+
224
+ def _action_tool(header):
225
+ """The action tool the loop calls itself when a turn's last step called none."""
226
+ for tool in header['tools']:
227
+ if tool['name'].startswith('action'):
228
+ return tool['name']
229
+ raise RuntimeError('no action tool is registered, so the turn cannot end with an action')
230
+
231
+
232
+ def _with_one_call(reply):
233
+ """The reply with at most its first tool call: a step makes one call."""
234
+ first = next(iter(tool_calls(reply)), None)
235
+ return {**reply, 'content': [block for block in reply['content'] if block['type'] != 'tool-call' or block is first]}
236
+
237
+
238
+ def header_changes(old, new):
239
+ """What changed between two request headers, one sentence per change."""
240
+ before, after = ({tool['name']: tool for tool in header['tools']} for header in (old, new))
241
+ lines = [f'Tool "{name}" was added.' for name in sorted(after.keys() - before.keys())]
242
+ lines += [f'Tool "{name}" was deleted.' for name in sorted(before.keys() - after.keys())]
243
+ lines += [f'Tool "{name}" was changed.' for name in sorted(before.keys() & after.keys())
244
+ if before[name] != after[name]]
245
+ for key in sorted(old['config'].keys() | new['config'].keys()):
246
+ was, now = old['config'].get(key), new['config'].get(key)
247
+ if was != now:
248
+ lines.append(f'Model parameter "{key}" changed from {json.dumps(was)} to {json.dumps(now)}.')
249
+ return '\n'.join(lines)
@@ -0,0 +1,47 @@
1
+ """`ctx.agents`: the agent of each live session."""
2
+
3
+ import pycordis
4
+
5
+ from ..log import latest
6
+ from . import events, inbox
7
+ from .loop import ReactLoopAgent
8
+
9
+
10
+ def close_step(log):
11
+ """The closer of `step/start`: a step that a crash left open ends."""
12
+ last = latest(log, 'step/start', 'step/end')
13
+ return [{'type': 'step/end', 'data': last['data']}] if last and last['type'] == 'step/start' else []
14
+
15
+
16
+ def close_turn(log):
17
+ """The closer of `turn/start`: an open turn ends as `interrupted`, so its inbox messages are pending again."""
18
+ last = latest(log, 'turn/start', 'turn/end')
19
+ if last is None or last['type'] == 'turn/end':
20
+ return []
21
+ return [{'type': 'turn/end', 'data': {'turn': last['data']['turn'], 'reason': 'interrupted'}}]
22
+
23
+
24
+ class Agents(pycordis.Service):
25
+ """`ctx.agents`: session id -> the `ReactLoopAgent` that drives it."""
26
+
27
+ def __init__(self, ctx, config):
28
+ super().__init__(ctx, 'agents')
29
+ self._own_ctx = ctx
30
+ self._config = config
31
+ self._agents: dict[str, ReactLoopAgent] = {}
32
+ for name, data in events.LOG_ONLY.items():
33
+ ctx.session_events.register(name, data)
34
+ for name, data in events.SURFACE.items():
35
+ ctx.session_events.register(name, data, surface=True)
36
+ ctx.session_states.register('inbox', inbox.init, inbox.apply)
37
+ ctx.session_closers.register('step/end', close_step, before=['turn/end'])
38
+ ctx.session_closers.register('turn/end', close_turn)
39
+ ctx.on('session/disposed', lambda session: self._agents.pop(session.id, None))
40
+
41
+ def create(self, session) -> ReactLoopAgent:
42
+ """The agent that drives `session`."""
43
+ agent = self._agents[session.id] = ReactLoopAgent(self._own_ctx, session, self._config)
44
+ return agent
45
+
46
+ def get(self, session_id) -> ReactLoopAgent | None:
47
+ return self._agents.get(session_id)
@@ -0,0 +1,98 @@
1
+ """Booting a harness folder, and the dry boot that checks its rows."""
2
+
3
+ from contextlib import asynccontextmanager
4
+ from dataclasses import asdict, dataclass, field
5
+ from pathlib import Path
6
+
7
+ import pycordis
8
+ from dotenv import load_dotenv
9
+ from pycordis import schema
10
+
11
+ from .config import describe, unknown_keys
12
+
13
+ SESSIONS_ROW = 'rh-pycordis-kernel-session-jsonl' # the kernel row whose `root` says where sessions are stored
14
+
15
+
16
+ def load_env(start: Path):
17
+ """Load the nearest `.env` at or above `start` into the environment. A variable that is already set is kept."""
18
+ for directory in [start, *start.parents]:
19
+ if (directory / '.env').is_file():
20
+ load_dotenv(directory / '.env')
21
+ return
22
+
23
+
24
+ @asynccontextmanager
25
+ async def boot(harness, *, sessions=None, verbose=False):
26
+ """Start the harness in the folder `harness`: its `.env`, then every row of its `cordis.yml`.
27
+
28
+ `sessions` stores the sessions somewhere else than the row says, for this boot only.
29
+ `verbose` also prints debug log lines.
30
+ """
31
+ harness = Path(harness).resolve()
32
+ load_env(harness)
33
+ patches = [{'id': SESSIONS_ROW, 'config': {'root': str(Path(sessions).resolve())}}] if sessions else None
34
+ async with pycordis.App(logger={'levels': {'default': 3 if verbose else 2}}) as app:
35
+ await app.load_config(harness / 'cordis.yml', patches=patches)
36
+ yield app
37
+
38
+
39
+ @dataclass
40
+ class Row:
41
+ """One row of `cordis.yml`, as the dry boot found it."""
42
+
43
+ id: str
44
+ plugin: str # the row's `name`
45
+ state: str # 'active', 'pending', 'failed', 'disabled' or 'not loaded'
46
+ problems: list = field(default_factory=list) # why the row is not fine
47
+ config: list = field(default_factory=list) # its plugin's Config: key, type, default, description
48
+ run_config: list = field(default_factory=list) # its plugin's RunConfig, for an environment plugin
49
+
50
+ @property
51
+ def ok(self):
52
+ return self.state in ('active', 'disabled') and not self.problems
53
+
54
+
55
+ async def survey(app) -> list[Row]:
56
+ """The dry boot's report: the state of every row, and what is wrong with it.
57
+
58
+ A row is fine when its plugin is active and its `config` has no key the plugin's `Config`
59
+ does not declare, so a misspelled key cannot be silently ignored.
60
+ """
61
+ rows, loader = [], app.ctx.get('loader')
62
+ for entry in pycordis.js.iterate(loader.entries()):
63
+ options = pycordis.to_py(entry.options)
64
+ if options['name'].startswith('cordis:'): # an include or a group: structure, not a plugin
65
+ continue
66
+ fiber = getattr(entry, 'fiber', None)
67
+ if fiber is None:
68
+ disabled = bool(entry.disabled)
69
+ rows.append(Row(options['id'], options['name'], 'disabled' if disabled else 'not loaded',
70
+ [] if disabled else ['the plugin could not be imported; see the log above']))
71
+ continue
72
+
73
+ plugin = loader.unwrapExports(entry.moduleNamespace) # the plugin as the row's module exports it
74
+ declared = getattr(plugin, 'Config', None)
75
+ row = Row(options['id'], options['name'], fiber.state.name.lower(), config=describe(declared),
76
+ run_config=describe(getattr(plugin, 'RunConfig', None)))
77
+ if declared is None or isinstance(declared, schema.Schema):
78
+ row.problems += [f'unknown config key "{key}"' for key in unknown_keys(declared, options.get('config'))]
79
+ if row.state == 'pending':
80
+ missing = [name for name in pycordis.js.keys(fiber.inject) if fiber.ctx.get(name) is None]
81
+ row.problems.append(f'waiting for {", ".join(missing)}')
82
+ elif row.state == 'failed':
83
+ try:
84
+ await fiber
85
+ except Exception as error:
86
+ row.problems.append(str(error))
87
+ rows.append(row)
88
+ return rows
89
+
90
+
91
+ async def dry_boot(harness):
92
+ """Boot the harness, report on every row, and shut down. Nothing is launched."""
93
+ async with boot(harness) as app:
94
+ return await survey(app)
95
+
96
+
97
+ def as_json(rows):
98
+ return [asdict(row) | {'ok': row.ok} for row in rows]