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/types.py ADDED
@@ -0,0 +1,464 @@
1
+ """Immutable snapshots and native request/response wrappers for API 0.1.0."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import math
6
+ from dataclasses import dataclass, fields, is_dataclass
7
+ from enum import Enum
8
+ from typing import Any, AsyncIterator, Literal, TYPE_CHECKING, TypeAlias
9
+
10
+ if TYPE_CHECKING:
11
+ from .session import Session
12
+
13
+ JsonValue: TypeAlias = None | bool | int | float | str | list["JsonValue"] | dict[str, "JsonValue"]
14
+ StackEntryId: TypeAlias = int
15
+ API_VERSION = "0.1.0"
16
+
17
+
18
+ def json_value(value: Any) -> JsonValue:
19
+ if value is None or isinstance(value, (bool, str)):
20
+ return value
21
+ if isinstance(value, int):
22
+ if not -(1 << 63) <= value < (1 << 64):
23
+ raise ValueError("JSON integer is outside the host range")
24
+ return value
25
+ if isinstance(value, float):
26
+ if not math.isfinite(value):
27
+ raise ValueError("Non-finite JSON number")
28
+ return value
29
+ if isinstance(value, list):
30
+ return [json_value(v) for v in value]
31
+ if isinstance(value, dict) and all(isinstance(k, str) for k in value):
32
+ return {k: json_value(v) for k, v in value.items()}
33
+ raise TypeError(f"Not a JSON value: {type(value).__name__}")
34
+
35
+
36
+ def u64(value: int | None) -> None:
37
+ if value is not None and (type(value) is not int or not 0 <= value < (1 << 64)):
38
+ raise ValueError("Expected an unsigned 64-bit integer")
39
+
40
+
41
+ class RegistrationMode(str, Enum):
42
+ CHAIN = "chain"
43
+ DIRECT = "direct"
44
+
45
+
46
+ class ContextStateKind(str, Enum):
47
+ CREATED = "created"
48
+ RUNNING = "running"
49
+ SUCCEEDED = "succeeded"
50
+ FAILED = "failed"
51
+ CANCELLED = "cancelled"
52
+
53
+
54
+ class ContextStateUpdate(str, Enum):
55
+ APPLIED = "applied"
56
+ UNCHANGED = "unchanged"
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class ContextFailure:
61
+ message: str
62
+
63
+ def __post_init__(self) -> None:
64
+ if not isinstance(self.message, str):
65
+ raise TypeError("failure message must be a string")
66
+
67
+
68
+ class ContextOutput:
69
+ __slots__ = ("_value", "_host", "_handle")
70
+
71
+ def __init__(self, value: JsonValue, *, _host: Any = None, _handle: str | None = None):
72
+ self._value = json_value(value)
73
+ self._host = _host
74
+ self._handle = _handle
75
+
76
+ @classmethod
77
+ def from_json(cls, value: JsonValue) -> ContextOutput:
78
+ return cls(value)
79
+
80
+ async def json_snapshot(self) -> JsonValue:
81
+ if self._handle is not None:
82
+ return await self._host.call("output.json_snapshot", {"handle": self._handle})
83
+ return json_value(self._value)
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class ContextState:
88
+ kind: ContextStateKind
89
+ output: ContextOutput | None = None
90
+ error: ContextFailure | None = None
91
+ reason: str | None = None
92
+
93
+ def __post_init__(self) -> None:
94
+ if not isinstance(self.kind, ContextStateKind):
95
+ raise TypeError("kind must be ContextStateKind")
96
+ actual = (self.output is not None, self.error is not None, self.reason is not None)
97
+ expected = {
98
+ ContextStateKind.SUCCEEDED: (True, False, False),
99
+ ContextStateKind.FAILED: (False, True, False),
100
+ ContextStateKind.CANCELLED: (False, False, True),
101
+ }.get(self.kind, (False, False, False))
102
+ if actual != expected:
103
+ raise ValueError("State fields do not match its kind")
104
+ if self.output is not None and not isinstance(self.output, ContextOutput):
105
+ raise TypeError("output must be ContextOutput")
106
+ if self.error is not None and not isinstance(self.error, ContextFailure):
107
+ raise TypeError("error must be ContextFailure")
108
+ if self.reason is not None and not isinstance(self.reason, str):
109
+ raise TypeError("reason must be str")
110
+
111
+ @classmethod
112
+ def created(cls) -> ContextState:
113
+ return cls(ContextStateKind.CREATED)
114
+
115
+ @classmethod
116
+ def running(cls) -> ContextState:
117
+ return cls(ContextStateKind.RUNNING)
118
+
119
+ @classmethod
120
+ def succeeded(cls, value: JsonValue) -> ContextState:
121
+ return cls(ContextStateKind.SUCCEEDED, output=ContextOutput.from_json(value))
122
+
123
+ @classmethod
124
+ def failed(cls, message: str) -> ContextState:
125
+ return cls(ContextStateKind.FAILED, error=ContextFailure(message))
126
+
127
+ @classmethod
128
+ def cancelled(cls, reason: str) -> ContextState:
129
+ return cls(ContextStateKind.CANCELLED, reason=reason)
130
+
131
+ def is_terminal(self) -> bool:
132
+ return self.kind in (ContextStateKind.SUCCEEDED, ContextStateKind.FAILED, ContextStateKind.CANCELLED)
133
+
134
+ def is_cancelled(self) -> bool:
135
+ return self.kind == ContextStateKind.CANCELLED
136
+
137
+
138
+ class ContextStackPhase(str, Enum):
139
+ DISPATCHED = "dispatched"
140
+ STARTED = "started"
141
+ SUCCEEDED = "succeeded"
142
+ FAILED = "failed"
143
+ CANCELLED = "cancelled"
144
+ CLEANUP_FINISHED = "cleanup_finished"
145
+
146
+
147
+ class TaskTypeKind(str, Enum):
148
+ TOOL = "tool"
149
+ SKILL = "skill"
150
+ MCP = "mcp"
151
+ PLAN = "plan"
152
+ WORKFLOW = "workflow"
153
+ MODEL = "model"
154
+ SESSION = "session"
155
+ MEMORY = "memory"
156
+ ANY = "any"
157
+
158
+
159
+ @dataclass(frozen=True)
160
+ class TaskType:
161
+ kind: TaskTypeKind = TaskTypeKind.TOOL
162
+ value: str | None = None
163
+
164
+ def __post_init__(self) -> None:
165
+ if not isinstance(self.kind, TaskTypeKind):
166
+ raise TypeError("kind must be TaskTypeKind")
167
+ if (self.kind == TaskTypeKind.ANY) != (isinstance(self.value, str) and bool(self.value)):
168
+ if self.kind == TaskTypeKind.ANY or self.value is not None:
169
+ raise ValueError("Only ANY task type requires a value")
170
+
171
+
172
+ @dataclass(frozen=True)
173
+ class TaskMeta:
174
+ id: str
175
+ plan_id: str
176
+ ty: TaskType
177
+ publisher: str
178
+ executor: str
179
+
180
+ def __post_init__(self) -> None:
181
+ if not isinstance(self.ty, TaskType) or not all(
182
+ isinstance(v, str) for v in (self.id, self.plan_id, self.publisher, self.executor)
183
+ ):
184
+ raise TypeError("Invalid TaskMeta fields")
185
+
186
+
187
+ @dataclass(frozen=True)
188
+ class ContextStackDraft:
189
+ task_meta: TaskMeta
190
+ phase: ContextStackPhase
191
+ parent_entry_id: StackEntryId | None = None
192
+ elapsed_ms: int | None = None
193
+ message: str | None = None
194
+
195
+ def __post_init__(self) -> None:
196
+ u64(self.parent_entry_id)
197
+ u64(self.elapsed_ms)
198
+ if not isinstance(self.phase, ContextStackPhase):
199
+ raise TypeError("phase must be ContextStackPhase")
200
+ if not isinstance(self.task_meta, TaskMeta) or (
201
+ self.message is not None and not isinstance(self.message, str)
202
+ ):
203
+ raise TypeError("Invalid stack draft fields")
204
+
205
+
206
+ @dataclass(frozen=True)
207
+ class ContextStack:
208
+ entry_id: StackEntryId
209
+ parent_entry_id: StackEntryId | None
210
+ sequence: int
211
+ scope_id: str
212
+ task_meta: TaskMeta
213
+ phase: ContextStackPhase
214
+ timestamp: str
215
+ elapsed_ms: int | None
216
+ message: str | None
217
+
218
+
219
+ @dataclass(frozen=True)
220
+ class ContextStackQuery:
221
+ tree: bool = False
222
+ task_id: str | None = None
223
+ plan_id: str | None = None
224
+ executor: str | None = None
225
+ phase: ContextStackPhase | None = None
226
+ after_sequence: int | None = None
227
+ limit: int | None = None
228
+
229
+ def __post_init__(self) -> None:
230
+ if type(self.tree) is not bool or (
231
+ self.phase is not None and not isinstance(self.phase, ContextStackPhase)
232
+ ):
233
+ raise TypeError("Invalid stack query flags")
234
+ if any(v is not None and not isinstance(v, str)
235
+ for v in (self.task_id, self.plan_id, self.executor)):
236
+ raise TypeError("Invalid stack query filters")
237
+ u64(self.after_sequence)
238
+ u64(self.limit)
239
+ if self.limit is not None and self.limit > 256:
240
+ raise ValueError("Stack query limit exceeds 256")
241
+
242
+
243
+ @dataclass(frozen=True)
244
+ class ContextUser:
245
+ user_id: str
246
+
247
+
248
+ @dataclass(frozen=True)
249
+ class ContextSession:
250
+ session_id: str
251
+ session: Session
252
+
253
+
254
+ @dataclass(frozen=True)
255
+ class TodoPlanScope:
256
+ plan_id: str
257
+ agent_id: str
258
+ user_id: str
259
+ user_input: str
260
+ _handle: str = ""
261
+
262
+
263
+ @dataclass(frozen=True)
264
+ class TodoContextBinding:
265
+ kind: Literal["auto", "inherit", "clear", "bind"] = "auto"
266
+ scope: TodoPlanScope | None = None
267
+
268
+ def __post_init__(self) -> None:
269
+ if self.kind not in ("auto", "inherit", "clear", "bind"):
270
+ raise ValueError("Invalid todo binding")
271
+ if (self.kind == "bind") != (self.scope is not None):
272
+ raise ValueError("bind requires a todo scope")
273
+ if self.scope is not None and not isinstance(self.scope, TodoPlanScope):
274
+ raise TypeError("scope must be TodoPlanScope")
275
+
276
+
277
+ @dataclass(frozen=True)
278
+ class SingleAgentSource:
279
+ kind: Literal["agent_id", "paths"]
280
+ agent_id: str | None = None
281
+ config: str | None = None
282
+ prompt: str | None = None
283
+
284
+ def __post_init__(self) -> None:
285
+ if self.kind == "agent_id":
286
+ if not self.agent_id or self.config is not None or self.prompt is not None:
287
+ raise ValueError("Invalid agent_id source")
288
+ elif self.kind == "paths":
289
+ if self.agent_id is not None or not self.config or not self.prompt:
290
+ raise ValueError("Invalid paths source")
291
+ else:
292
+ raise ValueError("Invalid source kind")
293
+
294
+
295
+ @dataclass(frozen=True)
296
+ class TimerOwner:
297
+ agent_id: str
298
+ user_id: str
299
+
300
+
301
+ @dataclass(frozen=True)
302
+ class TimerExecutionBinding:
303
+ owner: TimerOwner
304
+ source: SingleAgentSource
305
+ workspace: str
306
+
307
+
308
+ @dataclass(frozen=True)
309
+ class ContextScope:
310
+ scope_id: str
311
+ parent_scope_id: str | None
312
+ user: ContextUser
313
+ session: ContextSession | None = None
314
+ agent_id: str | None = None
315
+ workflow_id: str | None = None
316
+ node_id: str | None = None
317
+ turn_id: int | None = None
318
+ todo: TodoPlanScope | None = None
319
+ workspace: str | None = None
320
+ execution_origin: str | None = None
321
+ timer_execution: TimerExecutionBinding | None = None
322
+
323
+ def __post_init__(self) -> None:
324
+ u64(self.turn_id)
325
+ if not isinstance(self.scope_id, str) or not isinstance(self.user, ContextUser):
326
+ raise TypeError("Invalid scope identity")
327
+ if any(v is not None and not isinstance(v, str) for v in (
328
+ self.parent_scope_id, self.agent_id, self.workflow_id, self.node_id,
329
+ self.workspace, self.execution_origin,
330
+ )):
331
+ raise TypeError("Invalid scope fields")
332
+
333
+
334
+ @dataclass(frozen=True)
335
+ class ContextChildSpec:
336
+ timer_source: SingleAgentSource | None = None
337
+ timer_workspace: str | None = None
338
+ workspace: str | None = None
339
+ session: ContextSession | None = None
340
+ agent_id: str | None = None
341
+ workflow_id: str | None = None
342
+ node_id: str | None = None
343
+ turn_id: int | None = None
344
+ execution: bool = False
345
+ todo: TodoContextBinding = TodoContextBinding()
346
+
347
+ def __post_init__(self) -> None:
348
+ u64(self.turn_id)
349
+ if type(self.execution) is not bool or not isinstance(self.todo, TodoContextBinding):
350
+ raise TypeError("Invalid child execution or todo binding")
351
+ if self.session is not None and not isinstance(self.session, ContextSession):
352
+ raise TypeError("session must be ContextSession")
353
+ if self.timer_source is not None and not isinstance(self.timer_source, SingleAgentSource):
354
+ raise TypeError("timer_source must be SingleAgentSource")
355
+ if any(v is not None and not isinstance(v, str) for v in (
356
+ self.timer_workspace, self.workspace, self.agent_id, self.workflow_id, self.node_id,
357
+ )):
358
+ raise TypeError("Invalid child scope fields")
359
+
360
+
361
+ @dataclass(frozen=True)
362
+ class MessageReceipt:
363
+ message_id: str
364
+
365
+
366
+ class NativeObject:
367
+ """OpenAI/native JSON with attribute access; unknown fields remain lossless."""
368
+ def __init__(self, data: dict[str, Any]):
369
+ object.__setattr__(self, "_data", json_value(data))
370
+
371
+ def __getattr__(self, name: str) -> Any:
372
+ try:
373
+ value = self._data[name]
374
+ except KeyError:
375
+ if name == "stream":
376
+ return False
377
+ raise AttributeError(name) from None
378
+ if isinstance(value, dict):
379
+ return NativeObject(value)
380
+ if isinstance(value, list):
381
+ return [NativeObject(v) if isinstance(v, dict) else v for v in value]
382
+ return value
383
+
384
+ def __setattr__(self, name: str, value: Any) -> None:
385
+ self._data[name] = encode(value)
386
+
387
+ def to_dict(self) -> dict[str, Any]:
388
+ return json_value(self._data) # type: ignore[return-value]
389
+
390
+
391
+ class ModelRequest(NativeObject):
392
+ pass
393
+
394
+
395
+ class SessionMessage(NativeObject):
396
+ pass
397
+
398
+
399
+ class UserMemory(NativeObject):
400
+ pass
401
+
402
+
403
+ class ToolRequest(NativeObject):
404
+ def arguments_json(self) -> JsonValue:
405
+ return json_value(json.loads(self.arguments))
406
+
407
+
408
+ class ToolResponse:
409
+ def __init__(self, result: str | None = None, *, _reference: str | None = None):
410
+ self.result = result
411
+ self._reference = _reference
412
+
413
+ @classmethod
414
+ def completed(cls, result: str) -> ToolResponse:
415
+ if not isinstance(result, str):
416
+ raise TypeError("Tool result must be a string")
417
+ return cls(result)
418
+
419
+
420
+ class ModelResponse:
421
+ def __init__(self, value: dict[str, Any] | AsyncIterator[dict[str, Any]], *, streaming: bool):
422
+ self.value = value
423
+ self.is_streaming = streaming
424
+
425
+ @classmethod
426
+ def completed(cls, value: dict[str, Any]) -> ModelResponse:
427
+ if not isinstance(value, dict):
428
+ raise TypeError("Model completion must be an OpenAI response object")
429
+ return cls(json_value(value), streaming=False) # type: ignore[arg-type]
430
+
431
+ @classmethod
432
+ def streaming(cls, chunks: AsyncIterator[dict[str, Any]]) -> ModelResponse:
433
+ if not hasattr(chunks, "__aiter__"):
434
+ raise TypeError("Model stream must be an async iterator")
435
+ return cls(chunks, streaming=True)
436
+
437
+ def __aiter__(self) -> AsyncIterator[dict[str, Any]]:
438
+ if not self.is_streaming:
439
+ raise TypeError("Completed response is not a stream")
440
+ return self.value.__aiter__() # type: ignore[union-attr]
441
+
442
+
443
+ def encode(value: Any) -> Any:
444
+ if isinstance(value, NativeObject):
445
+ return value.to_dict()
446
+ if isinstance(value, Enum):
447
+ return value.value
448
+ if isinstance(value, ContextOutput):
449
+ if value._handle:
450
+ return {"handle": value._handle}
451
+ return {"json": json_value(value._value)}
452
+ if hasattr(value, "_wire_reference"):
453
+ return value._wire_reference()
454
+ if is_dataclass(value):
455
+ result = {f.name: encode(getattr(value, f.name)) for f in fields(value)
456
+ if getattr(value, f.name) is not None and not f.name.startswith("_")}
457
+ if isinstance(value, TodoPlanScope):
458
+ result["handle"] = value._handle
459
+ return result
460
+ if isinstance(value, (list, tuple)):
461
+ return [encode(v) for v in value]
462
+ if isinstance(value, dict):
463
+ return {k: encode(v) for k, v in value.items()}
464
+ return json_value(value)