fae-plugin-py 0.1.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.
fae_plugin/_worker.py ADDED
@@ -0,0 +1,584 @@
1
+ """Persistent worker with independent protocol, business, and stream tasks."""
2
+ from __future__ import annotations
3
+ import asyncio
4
+ import contextvars
5
+ import itertools
6
+ import json
7
+ import sys
8
+ import traceback
9
+ from collections import deque
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any
14
+ from ._host import BoundHost, Host
15
+ from ._protocol import PROTOCOL_VERSION, Writer, read_frame, reader
16
+ from .chain import HookNext
17
+ from .context import Context
18
+ from .errors import HookCancelled, MissingChainHandler, PluginHostError
19
+ from .registration import register
20
+ from .types import ModelRequest, ModelResponse, NativeObject, ToolRequest, ToolResponse, SessionMessage, UserMemory, encode, json_value
21
+
22
+ CURRENT_MEMBER: contextvars.ContextVar[str] = contextvars.ContextVar("fae_plugin_member")
23
+
24
+
25
+ @dataclass
26
+ class Invocation:
27
+ id: str
28
+ params: dict[str, Any]
29
+ deadline: float
30
+ group: str
31
+ terminal: bool = False
32
+ released: bool = False
33
+ task: asyncio.Task[Any] | None = None
34
+ streams: set[str] = field(default_factory=set)
35
+ responses: list[ModelResponse] = field(default_factory=list)
36
+
37
+ def remaining(self) -> float:
38
+ return max(0.0, self.deadline - asyncio.get_running_loop().time())
39
+
40
+ def check(self) -> None:
41
+ if self.terminal or self.released:
42
+ raise HookCancelled("Plugin invocation is no longer active", call_id=self.id)
43
+ if self.remaining() <= 0:
44
+ raise PluginHostError("Plugin invocation timed out", call_id=self.id)
45
+
46
+
47
+ class HostStream:
48
+ def __init__(self, host: BoundHost, stream_id: str):
49
+ self.host, self.stream_id = host, stream_id
50
+ self.closed = False
51
+ self.busy = False
52
+
53
+ def __aiter__(self) -> "HostStream":
54
+ return self
55
+
56
+ async def __anext__(self) -> dict[str, Any]:
57
+ if self.closed:
58
+ raise StopAsyncIteration
59
+ if self.busy:
60
+ raise ValueError("A stream permits only one next in flight")
61
+ self.busy = True
62
+ try:
63
+ result = await self.host.call("stream.next", {"stream_id": self.stream_id})
64
+ if result["eof"]:
65
+ self.closed = True
66
+ raise StopAsyncIteration
67
+ return result["chunk"]
68
+ finally:
69
+ self.busy = False
70
+
71
+ async def aclose(self) -> None:
72
+ if not self.closed:
73
+ self.closed = True
74
+ await self.host.call("stream.close", {"stream_id": self.stream_id})
75
+
76
+
77
+ class OwnedIterator:
78
+ """Keep creator identity while lazy inner/outer generators are iterated."""
79
+ def __init__(self, iterator: Any, invocation: Invocation, record: Any, method: str):
80
+ self.iterator = iterator.__aiter__()
81
+ self.invocation, self.record, self.method = invocation, record, method
82
+
83
+ def __aiter__(self) -> "OwnedIterator":
84
+ return self
85
+
86
+ async def __anext__(self) -> Any:
87
+ token = CURRENT_MEMBER.set(self.record.key)
88
+ try:
89
+ self.invocation.check()
90
+ chunk = await self.iterator.__anext__()
91
+ self.invocation.check()
92
+ return chunk
93
+ except StopAsyncIteration:
94
+ raise
95
+ except BaseException as error:
96
+ if not getattr(error, "details", {}).get("plugin_id"):
97
+ setattr(error, "details", {**getattr(error, "details", {}),
98
+ "plugin_id": self.record.plugin_id,
99
+ "implementation": self.record.mount["implementation"],
100
+ "method": self.method, "call_id": self.invocation.id})
101
+ raise
102
+ finally:
103
+ CURRENT_MEMBER.reset(token)
104
+
105
+ async def aclose(self) -> None:
106
+ token = CURRENT_MEMBER.set(self.record.key)
107
+ try:
108
+ close = getattr(self.iterator, "aclose", None)
109
+ if close is not None:
110
+ await close()
111
+ finally:
112
+ CURRENT_MEMBER.reset(token)
113
+
114
+
115
+ @dataclass
116
+ class Stream:
117
+ invocation: Invocation
118
+ iterator: Any
119
+ member: str
120
+ busy: bool = False
121
+ choices: dict[int, bool] = field(default_factory=dict)
122
+ tools: dict[tuple[int, int], dict[str, str]] = field(default_factory=dict)
123
+ first: bool = True
124
+ task: asyncio.Task[Any] | None = None
125
+
126
+
127
+ def check_value(point: str, method: str, value: Any, *, output: bool) -> None:
128
+ expected: Any
129
+ if method in ("on_query", "on_prompt") or (point == "ToolsHook" and method == "desc" and not output):
130
+ expected = str
131
+ elif method in ("on_memory", "on_history", "on_save"):
132
+ expected = list
133
+ elif method == "on_model_resp" or (point == "ModelHook" and output):
134
+ expected = ModelResponse
135
+ elif method == "on_tools_resp" or (point == "ToolsHook" and method == "exec" and output):
136
+ expected = ToolResponse
137
+ elif point == "ToolsHook" and method == "desc":
138
+ expected = dict
139
+ else:
140
+ expected = (NativeObject, dict)
141
+ if not isinstance(value, expected):
142
+ raise TypeError(f"{point}.{method} {'output' if output else 'input'} has invalid type")
143
+ if isinstance(value, list) and not all(isinstance(item, (NativeObject, dict)) for item in value):
144
+ raise TypeError(f"{method} requires native objects")
145
+ if isinstance(value, ToolResponse) and value._reference is None and not isinstance(value.result, str):
146
+ raise TypeError("Tool response must contain a string or a host reference")
147
+ if not isinstance(value, (ModelResponse, ToolResponse)):
148
+ json_value(encode(value))
149
+
150
+
151
+ class Worker:
152
+ def __init__(self, writer: Writer, members: list[dict[str, Any]]):
153
+ self.writer, self.host = writer, Host(writer)
154
+ self.records = register(members)
155
+ self.calls: dict[str, Invocation] = {}
156
+ self.streams: dict[str, Stream] = {}
157
+ self.host_streams: dict[str, Invocation] = {}
158
+ self.stream_ids = itertools.count()
159
+ self.queue: dict[str, deque[Invocation]] = {}
160
+ self.round_robin: deque[str] = deque()
161
+ self.active: dict[str, int] = {}
162
+ self.wake = asyncio.Event()
163
+ self.executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="fae-plugin")
164
+ self.thread_slots = asyncio.Semaphore(4)
165
+ self.controls: set[asyncio.Task[Any]] = set()
166
+ self.admitted = 0
167
+
168
+ def spawn(self, coroutine: Any) -> None:
169
+ task = asyncio.create_task(coroutine)
170
+ self.controls.add(task)
171
+ task.add_done_callback(self.controls.discard)
172
+
173
+ async def result(self, id: str, *, result: Any = None, error: BaseException | None = None,
174
+ control: bool = False) -> None:
175
+ if error is None:
176
+ frame = {"id": id, "result": result}
177
+ else:
178
+ frame = {"id": id, "error": {"code": getattr(error, "code", "plugin_call_failed"),
179
+ "message": str(error), "call_id": id,
180
+ **getattr(error, "details", {})}}
181
+ await self.writer.send(frame, control=control)
182
+
183
+ async def enqueue(self, frame: dict[str, Any]) -> None:
184
+ params = frame["params"]
185
+ group = params["group"] # The host supplies a validated user/session or root-run group.
186
+ pending = sum(len(q) for q in self.queue.values())
187
+ if pending >= 64 or len(self.queue.get(group, ())) >= 16 or len(self.calls) >= 96:
188
+ error = PluginHostError("Plugin pending call queue is full", resource="calls")
189
+ error.code = "plugin_busy"
190
+ await self.result(frame["id"], error=error)
191
+ return
192
+ if frame["id"] in self.calls:
193
+ await self.result(frame["id"], error=ValueError("Duplicate call ID"))
194
+ return
195
+ invocation = Invocation(frame["id"], params,
196
+ asyncio.get_running_loop().time() + params["timeout_ms"] / 1000, group)
197
+ self.calls[invocation.id] = invocation
198
+ if group not in self.queue:
199
+ self.queue[group] = deque()
200
+ self.round_robin.append(group)
201
+ self.queue[group].append(invocation)
202
+ self.wake.set()
203
+
204
+ async def schedule(self) -> None:
205
+ while True:
206
+ await self.wake.wait()
207
+ self.wake.clear()
208
+ count = len(self.round_robin)
209
+ for _ in range(count):
210
+ group = self.round_robin.popleft()
211
+ queue = self.queue[group]
212
+ while queue and (queue[0].released or queue[0].remaining() <= 0):
213
+ invocation = queue.popleft()
214
+ if not invocation.released:
215
+ await self.result(invocation.id, error=PluginHostError("Queue deadline exceeded"))
216
+ await self.release(invocation)
217
+ if queue and self.admitted < 8 and self.active.get(group, 0) < 4:
218
+ invocation = queue.popleft()
219
+ self.admitted += 1
220
+ self.active[group] = self.active.get(group, 0) + 1
221
+ invocation.task = asyncio.create_task(self.execute(invocation))
222
+ self.wake.set()
223
+ if queue:
224
+ self.round_robin.append(group)
225
+ else:
226
+ del self.queue[group]
227
+ # Queue deadlines are observed even when every business slot is occupied.
228
+ if self.queue:
229
+ earliest = min(inv.remaining() for q in self.queue.values() for inv in q)
230
+ asyncio.get_running_loop().call_later(earliest, self.wake.set)
231
+
232
+ def decode(self, invocation: Invocation, host: BoundHost) -> Any:
233
+ point, method, value = (invocation.params[k] for k in ("point", "method", "argument"))
234
+ if method == "on_model_resp":
235
+ if value["kind"] == "completed":
236
+ return ModelResponse.completed(value["response"])
237
+ return ModelResponse.streaming(HostStream(host, value["stream_id"]))
238
+ if method == "on_tools_resp":
239
+ return ToolResponse(value.get("result"), _reference=value.get("reference"))
240
+ if method in ("on_tools_req",) or (point == "ToolsHook" and method == "exec"):
241
+ return ToolRequest(value)
242
+ if method in ("on_model_req", "on_compression") or point == "ModelHook":
243
+ return ModelRequest(value)
244
+ if isinstance(value, list):
245
+ cls = UserMemory if method == "on_memory" else SessionMessage
246
+ return [cls(v) for v in value]
247
+ return value
248
+
249
+ async def method(self, function: Any, ctx: Context, value: Any, **kwargs: Any) -> Any:
250
+ import inspect
251
+ if inspect.iscoroutinefunction(function):
252
+ return await function(ctx, value, **kwargs)
253
+ await self.thread_slots.acquire()
254
+ copied = contextvars.copy_context()
255
+ future = asyncio.get_running_loop().run_in_executor(
256
+ self.executor, lambda: copied.run(function, ctx, value, **kwargs))
257
+ # Cancelling the waiter cannot stop a Python thread. Keep its actual slot until it exits.
258
+ future.add_done_callback(lambda _: self.thread_slots.release())
259
+ return await asyncio.shield(future)
260
+
261
+ async def matching_models(self, invocation: Invocation, records: list[Any], model: str) -> list[Any]:
262
+ if not isinstance(model, str):
263
+ raise TypeError("match_model requires a model string")
264
+ matching = []
265
+ for record in records:
266
+ host = BoundHost(self.host, invocation, record.key)
267
+ ctx = Context(_host=host, _data=invocation.params["contexts"][record.key])
268
+ token = CURRENT_MEMBER.set(record.key)
269
+ try:
270
+ invocation.check()
271
+ result = await self.method(record.object.match_model, ctx, model)
272
+ invocation.check()
273
+ if type(result) is not bool:
274
+ raise TypeError("match_model must return bool")
275
+ if result:
276
+ matching.append(record)
277
+ except BaseException as error:
278
+ setattr(error, "details", {**getattr(error, "details", {}),
279
+ "plugin_id": record.plugin_id,
280
+ "implementation": record.mount["implementation"],
281
+ "method": "match_model", "call_id": invocation.id})
282
+ raise
283
+ finally:
284
+ CURRENT_MEMBER.reset(token)
285
+ if len(matching) > 1 and matching[0].mode == "direct":
286
+ conflict = PluginHostError(f"Multiple model implementations match {model}")
287
+ conflict.code = "plugin_model_conflict"
288
+ raise conflict
289
+ return matching
290
+
291
+ async def execute(self, invocation: Invocation) -> None:
292
+ try:
293
+ point, method = invocation.params["point"], invocation.params["method"]
294
+ matching = [r for r in self.records if r.matches(
295
+ point, invocation.params.get("location"))]
296
+ if point == "ModelHook":
297
+ if method == "match_model":
298
+ models = await asyncio.wait_for(
299
+ self.matching_models(invocation, matching, invocation.params["argument"]),
300
+ invocation.remaining())
301
+ await self.result(invocation.id, result=[r.key for r in models])
302
+ return
303
+ selected = invocation.params.get("model_members")
304
+ if selected is None:
305
+ matching = await asyncio.wait_for(
306
+ self.matching_models(invocation, matching, invocation.params["argument"]["model"]),
307
+ invocation.remaining())
308
+ else:
309
+ if (not isinstance(selected, list) or not all(isinstance(key, str) for key in selected)
310
+ or len(set(selected)) != len(selected)
311
+ or any(key not in {r.key for r in matching} for key in selected)):
312
+ raise ValueError("Invalid selected model members")
313
+ matching = [r for r in matching if r.key in selected]
314
+ if not matching:
315
+ raise MissingChainHandler("No matching plugin implementation")
316
+ contexts = invocation.params["contexts"]
317
+ first_host = BoundHost(self.host, invocation, matching[0].key)
318
+ value = self.decode(invocation, first_host)
319
+ if isinstance(value, ModelResponse) and value.is_streaming:
320
+ invocation.responses.append(value)
321
+
322
+ async def layer(index: int, value: Any) -> Any:
323
+ invocation.check()
324
+ check_value(point, method, value, output=False)
325
+ if index == len(matching):
326
+ if point != "SingleAgentHook":
327
+ raise MissingChainHandler(f"No terminal {point}.{method} handler")
328
+ return value
329
+ record = matching[index]
330
+ host = BoundHost(self.host, invocation, record.key)
331
+ ctx = Context(_host=host, _data=contexts[record.key])
332
+ token = CURRENT_MEMBER.set(record.key)
333
+ continuation: HookNext[Any, Any] | None = None
334
+ try:
335
+ if record.mode == "chain":
336
+ def validate_next(v: Any) -> None:
337
+ invocation.check()
338
+ check_value(point, method, v, output=False)
339
+ continuation = HookNext(lambda next_value: layer(index + 1, next_value),
340
+ validate_next)
341
+ result = await self.method(getattr(record.object, method), ctx, value, next=continuation)
342
+ else:
343
+ result = await self.method(getattr(record.object, method), ctx, value)
344
+ invocation.check()
345
+ check_value(point, method, result, output=True)
346
+ if isinstance(result, ModelResponse) and result.is_streaming:
347
+ if not hasattr(result, "_member"):
348
+ setattr(result, "_member", record.key)
349
+ if not isinstance(result.value, HostStream):
350
+ result.value = OwnedIterator(result.value, invocation, record, method)
351
+ if not any(r is result for r in invocation.responses):
352
+ if len(invocation.responses) >= 64:
353
+ close = getattr(result.value, "aclose", None)
354
+ if close is not None:
355
+ await close()
356
+ error = PluginHostError("Model stream reference limit exceeded",
357
+ resource="stream_references")
358
+ error.code = "plugin_busy"
359
+ raise error
360
+ invocation.responses.append(result)
361
+ if record.mode == "direct" and index + 1 < len(matching):
362
+ result = await layer(index + 1, result)
363
+ return result
364
+ except BaseException as error:
365
+ if not getattr(error, "details", {}).get("plugin_id"):
366
+ setattr(error, "details", {**getattr(error, "details", {}),
367
+ "plugin_id": record.plugin_id,
368
+ "implementation": record.mount["implementation"],
369
+ "method": method, "call_id": invocation.id})
370
+ raise
371
+ finally:
372
+ if continuation:
373
+ continuation._close()
374
+ CURRENT_MEMBER.reset(token)
375
+
376
+ output = await asyncio.wait_for(layer(0, value), invocation.remaining())
377
+ invocation.check()
378
+ result: Any
379
+ if isinstance(output, ModelResponse):
380
+ if output.is_streaming:
381
+ group_streams = sum(s.invocation.group == invocation.group for s in self.streams.values())
382
+ group_streams += sum(i.group == invocation.group for i in self.host_streams.values())
383
+ if len(self.streams) + len(self.host_streams) >= 16 or group_streams >= 4:
384
+ close = getattr(output.value, "aclose", None)
385
+ if close is not None:
386
+ await close()
387
+ error = PluginHostError("Active model stream limit exceeded", resource="streams")
388
+ error.code = "plugin_busy"
389
+ raise error
390
+ if output is value and isinstance(output.value, HostStream):
391
+ self.host_streams[invocation.id] = invocation
392
+ result = {"kind": "host_stream", "stream_id": output.value.stream_id}
393
+ else:
394
+ stream_id = f"stream-{next(self.stream_ids)}"
395
+ self.streams[stream_id] = Stream(invocation, output.__aiter__(),
396
+ getattr(output, "_member", matching[0].key))
397
+ invocation.streams.add(stream_id)
398
+ result = {"kind": "streaming", "stream_id": stream_id}
399
+ else:
400
+ result = {"kind": "completed", "response": output.value}
401
+ elif isinstance(output, ToolResponse):
402
+ result = {"reference": output._reference} if output._reference else {"result": output.result}
403
+ else:
404
+ result = encode(output)
405
+ await self.result(invocation.id, result=result)
406
+ except asyncio.CancelledError:
407
+ await self.result(invocation.id, error=HookCancelled("Plugin call cancelled"), control=True)
408
+ except BaseException as error:
409
+ print(traceback.format_exc(), file=sys.stderr)
410
+ await self.result(invocation.id, error=error)
411
+ await self.release(invocation)
412
+ finally:
413
+ self.admitted -= 1
414
+ self.active[invocation.group] -= 1
415
+ if self.active[invocation.group] == 0:
416
+ self.active.pop(invocation.group)
417
+ self.wake.set()
418
+ # Host sends release after it has decoded the result and acquired any stream references.
419
+
420
+ async def next_stream(self, frame: dict[str, Any]) -> None:
421
+ stream_id = frame["params"]["stream_id"]
422
+ stream = self.streams.get(stream_id)
423
+ if stream is None or stream.busy:
424
+ await self.result(frame["id"], error=ValueError("Invalid or busy stream"))
425
+ return
426
+ stream.busy = True
427
+ stream.task = asyncio.current_task()
428
+ token = CURRENT_MEMBER.set(stream.member)
429
+ try:
430
+ stream.invocation.check()
431
+ chunk = await asyncio.wait_for(stream.iterator.__anext__(),
432
+ min(30 if stream.first else 60, stream.invocation.remaining()))
433
+ stream.first = False
434
+ chunk = json_value(encode(chunk))
435
+ if len(json.dumps(chunk).encode()) > 64 * 1024:
436
+ raise ValueError("Model chunk exceeds 64 KiB")
437
+ if not isinstance(chunk, dict) or not isinstance(chunk.get("choices"), list):
438
+ raise ValueError("Invalid OpenAI stream chunk")
439
+ if (not isinstance(chunk.get("id"), str) or not isinstance(chunk.get("model"), str)
440
+ or type(chunk.get("created")) is not int
441
+ or chunk.get("object") != "chat.completion.chunk"):
442
+ raise ValueError("Invalid OpenAI stream metadata")
443
+ for choice in chunk["choices"]:
444
+ index = choice["index"]
445
+ if type(index) is not int or index < 0:
446
+ raise ValueError("Invalid model choice index")
447
+ if stream.choices.get(index):
448
+ raise ValueError("Delta after choice finish")
449
+ delta = choice.get("delta")
450
+ if not isinstance(delta, dict):
451
+ raise ValueError("Invalid model delta")
452
+ for tool in delta.get("tool_calls") or []:
453
+ tool_index = tool.get("index")
454
+ if type(tool_index) is not int or tool_index < 0:
455
+ raise ValueError("Invalid tool delta index")
456
+ fields = stream.tools.setdefault((index, tool_index),
457
+ {"id": "", "name": "", "arguments": ""})
458
+ function = tool.get("function") or {}
459
+ for key, fragment in (("id", tool.get("id")), ("name", function.get("name")),
460
+ ("arguments", function.get("arguments"))):
461
+ if fragment is not None:
462
+ if not isinstance(fragment, str):
463
+ raise ValueError("Invalid tool call fragment")
464
+ fields[key] += fragment
465
+ if sum(len(v.encode()) for v in fields.values()) > 1024 * 1024:
466
+ raise ValueError("Tool call arguments exceed 1 MiB")
467
+ if choice.get("finish_reason") is not None:
468
+ for (choice_index, _), fields in stream.tools.items():
469
+ if choice_index == index:
470
+ if not fields["id"] or not fields["name"]:
471
+ raise ValueError("Incomplete tool call")
472
+ json.loads(fields["arguments"])
473
+ stream.choices[index] = choice.get("finish_reason") is not None
474
+ await self.result(frame["id"], result={"eof": False, "chunk": chunk})
475
+ except StopAsyncIteration:
476
+ if not stream.choices or not all(stream.choices.values()):
477
+ await self.result(frame["id"], error=ValueError("Model stream ended before choices finished"))
478
+ else:
479
+ await self.result(frame["id"], result={"eof": True})
480
+ await self.close_stream(stream_id)
481
+ except BaseException as error:
482
+ await self.result(frame["id"], error=error)
483
+ await self.close_stream(stream_id)
484
+ finally:
485
+ stream.busy = False
486
+ stream.task = None
487
+ CURRENT_MEMBER.reset(token)
488
+
489
+ async def close_stream(self, stream_id: str) -> None:
490
+ stream = self.streams.pop(stream_id, None)
491
+ if stream:
492
+ stream.invocation.streams.discard(stream_id)
493
+ if stream.task and stream.task is not asyncio.current_task() and not stream.task.done():
494
+ stream.task.cancel()
495
+ await asyncio.gather(stream.task, return_exceptions=True)
496
+ try:
497
+ if hasattr(stream.iterator, "aclose"):
498
+ await stream.iterator.aclose()
499
+ except Exception:
500
+ pass
501
+
502
+ async def release(self, invocation: Invocation) -> None:
503
+ if invocation.released:
504
+ return
505
+ invocation.released = True
506
+ self.host_streams.pop(invocation.id, None)
507
+ queue = self.queue.get(invocation.group)
508
+ if queue is not None:
509
+ try:
510
+ queue.remove(invocation)
511
+ except ValueError:
512
+ pass
513
+ self.wake.set()
514
+ if invocation.task and invocation.task is not asyncio.current_task() and not invocation.task.done():
515
+ invocation.task.cancel()
516
+ for stream_id in list(invocation.streams):
517
+ await self.close_stream(stream_id)
518
+ for response in invocation.responses:
519
+ close = getattr(response.value, "aclose", None)
520
+ if close is not None:
521
+ try:
522
+ await close()
523
+ except Exception:
524
+ pass
525
+ invocation.responses.clear()
526
+ self.calls.pop(invocation.id, None)
527
+
528
+ async def run(self) -> None:
529
+ self.spawn(self.schedule())
530
+ await self.writer.send({"method": "ready", "params": {
531
+ "protocol_version": PROTOCOL_VERSION, "api_version": "0.1.0",
532
+ "instances": [r.key for r in self.records]}}, control=True)
533
+ stream = await reader()
534
+ try:
535
+ while True:
536
+ frame = await read_frame(stream)
537
+ method = frame.get("method")
538
+ if method is None:
539
+ self.host.response(frame)
540
+ elif method == "call":
541
+ await self.enqueue(frame)
542
+ elif method == "stream.next":
543
+ if len(self.controls) >= 64:
544
+ await self.result(frame["id"], error=PluginHostError("Control capacity exceeded"))
545
+ else:
546
+ self.spawn(self.next_stream(frame))
547
+ elif method in ("release", "cancel"):
548
+ invocation = self.calls.get(frame["params"]["call_id"])
549
+ if invocation:
550
+ invocation.terminal = method == "cancel"
551
+ self.spawn(self.release(invocation))
552
+ elif method == "stream.close":
553
+ self.spawn(self.close_stream(frame["params"]["stream_id"]))
554
+ else:
555
+ raise ValueError("Unknown host protocol method")
556
+ finally:
557
+ self.host.close()
558
+ for invocation in list(self.calls.values()):
559
+ await self.release(invocation)
560
+ for task in self.controls:
561
+ task.cancel()
562
+ self.executor.shutdown(wait=False, cancel_futures=True)
563
+
564
+
565
+ async def main() -> None:
566
+ output = sys.stdout.buffer
567
+ sys.stdout = sys.stderr
568
+ writer = Writer(output)
569
+ writer_task = asyncio.create_task(writer.run())
570
+ try:
571
+ worker = Worker(writer, json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))["members"])
572
+ await worker.run()
573
+ except BaseException as error:
574
+ await writer.send({"method": "startup_error", "params": {"message": str(error)}}, control=True)
575
+ # Drain the startup error before closing stdout.
576
+ while not writer.control.empty():
577
+ await asyncio.sleep(0)
578
+ raise
579
+ finally:
580
+ writer_task.cancel()
581
+
582
+
583
+ if __name__ == "__main__":
584
+ asyncio.run(main())
fae_plugin/chain.py ADDED
@@ -0,0 +1,91 @@
1
+ """Onion continuations live in a single invocation and may be awaited once."""
2
+ from __future__ import annotations
3
+ import asyncio
4
+ from typing import Any, Awaitable, Callable, Generic, TypeVar
5
+ from .context import Context
6
+ from .errors import InvalidHookNext
7
+ from .hooks import ToolsHook
8
+ from .types import ModelRequest, ModelResponse, ToolRequest, ToolResponse, SessionMessage, UserMemory
9
+
10
+ Input = TypeVar("Input")
11
+ Output = TypeVar("Output")
12
+
13
+
14
+ class HookNext(Generic[Input, Output]):
15
+ def __init__(self, callback: Callable[[Input], Awaitable[Output]],
16
+ check: Callable[[Any], None]) -> None:
17
+ self._callback = callback
18
+ self._check = check
19
+ self._owner = asyncio.current_task()
20
+ self._used = False
21
+ self._active = True
22
+
23
+ async def __call__(self, value: Input) -> Output:
24
+ if not self._active or self._used or asyncio.current_task() is not self._owner:
25
+ raise InvalidHookNext("next must be awaited once in its owning method")
26
+ self._used = True
27
+ self._check(value)
28
+ result = await self._callback(value)
29
+ return result
30
+
31
+ def _close(self) -> None:
32
+ self._active = False
33
+
34
+
35
+ class ChainSingleAgentHook:
36
+ async def on_query(self, ctx: Context, query: str, *, next: HookNext[str, str]) -> str:
37
+ return await next(query)
38
+
39
+ async def on_prompt(self, ctx: Context, prompt: str, *, next: HookNext[str, str]) -> str:
40
+ return await next(prompt)
41
+
42
+ async def on_memory(self, ctx: Context, memories: list[UserMemory],
43
+ *, next: HookNext[list[UserMemory], list[UserMemory]]) -> list[UserMemory]:
44
+ return await next(memories)
45
+
46
+ async def on_history(self, ctx: Context, history: list[SessionMessage],
47
+ *, next: HookNext[list[SessionMessage], list[SessionMessage]]) -> list[SessionMessage]:
48
+ return await next(history)
49
+
50
+ async def on_compression(self, ctx: Context, request: ModelRequest, *, next: HookNext[ModelRequest, ModelRequest]) -> ModelRequest:
51
+ return await next(request)
52
+
53
+ async def on_model_req(self, ctx: Context, request: ModelRequest, *, next: HookNext[ModelRequest, ModelRequest]) -> ModelRequest:
54
+ return await next(request)
55
+
56
+ async def on_model_resp(self, ctx: Context, response: ModelResponse,
57
+ *, next: HookNext[ModelResponse, ModelResponse]) -> ModelResponse:
58
+ return await next(response)
59
+
60
+ async def on_tools_req(self, ctx: Context, request: ToolRequest, *, next: HookNext[ToolRequest, ToolRequest]) -> ToolRequest:
61
+ return await next(request)
62
+
63
+ async def on_tools_resp(self, ctx: Context, response: ToolResponse,
64
+ *, next: HookNext[ToolResponse, ToolResponse]) -> ToolResponse:
65
+ return await next(response)
66
+
67
+ async def on_save(self, ctx: Context, messages: list[SessionMessage],
68
+ *, next: HookNext[list[SessionMessage], list[SessionMessage]]) -> list[SessionMessage]:
69
+ return await next(messages)
70
+
71
+
72
+ class ChainToolsHook:
73
+ _channel: str
74
+ channel = ToolsHook.channel
75
+
76
+ async def desc(self, ctx: Context, tool_name: str,
77
+ *, next: HookNext[str, dict[str, Any]]) -> dict[str, Any]:
78
+ return await next(tool_name)
79
+
80
+ async def exec(self, ctx: Context, request: ToolRequest,
81
+ *, next: HookNext[ToolRequest, ToolResponse]) -> ToolResponse:
82
+ return await next(request)
83
+
84
+
85
+ class ChainModelHook:
86
+ async def match_model(self, ctx: Context, model: str) -> bool:
87
+ raise NotImplementedError("ChainModelHook.match_model must be implemented")
88
+
89
+ async def exec(self, ctx: Context, request: ModelRequest,
90
+ *, next: HookNext[ModelRequest, ModelResponse]) -> ModelResponse:
91
+ return await next(request)