File size: 6,450 Bytes
ff293b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee21104
 
 
 
 
 
 
ff293b1
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

"""Data models for GhostExec — all world and API types live here."""

from __future__ import annotations

from typing import Any, Literal

from pydantic import BaseModel, ConfigDict, Field, model_validator

try:
    from openenv.core.env_server.types import Action as _OpenEnvAction
    from openenv.core.env_server.types import Observation as _OpenEnvObservation
except Exception:
    _OpenEnvAction = BaseModel  # type: ignore[assignment]
    _OpenEnvObservation = BaseModel  # type: ignore[assignment]


def _is_pydantic_model_class(cls: object) -> bool:
    try:
        return isinstance(cls, type) and issubclass(cls, BaseModel)
    except TypeError:
        return False


# Some OpenEnv builds expose dataclass-style Action/Observation that do not accept
# additional keyword fields, which breaks GhostexecAction/GhostexecObservation
# construction in Colab. Fall back to BaseModel in that case.
ActionBase = _OpenEnvAction if _is_pydantic_model_class(_OpenEnvAction) else BaseModel
ObservationBase = (
    _OpenEnvObservation if _is_pydantic_model_class(_OpenEnvObservation) else BaseModel
)

# --- Aliases for scenario / world strings ---

EmailPriority = Literal["critical", "high", "normal", "low"]
SenderRelationship = Literal["VIP", "personal", "professional", "unknown"]
ContactRelationship = Literal[
    "board_member",
    "spouse",
    "investor",
    "direct_report",
    "client",
    "friend",
    "team_member",
]
CommPreference = Literal["email", "text", "call"]
Mood = Literal["happy", "neutral", "annoyed", "angry", "furious"]
TaskStatus = Literal["pending", "in-progress", "done", "overdue"]
Effort = Literal["low", "medium", "high"]
MeetingPriority = Literal["critical", "high", "normal", "low"]

GhostexecActionType = Literal[
    "reply_email",
    "archive_email",
    "reschedule_meeting",
    "cancel_meeting",
    "complete_task",
    "delegate_task",
    "send_message",
    "do_nothing",
]


class Email(BaseModel):
    """Single inbox message."""

    model_config = ConfigDict(extra="forbid")

    id: str
    sender: str
    subject: str
    body: str
    read: bool = False
    replied: bool = False
    priority: EmailPriority
    sender_relationship: SenderRelationship


class Meeting(BaseModel):
    """Calendar block."""

    model_config = ConfigDict(extra="forbid")

    id: str
    title: str
    start: str = Field(..., description="ISO 8601 start datetime")
    duration_minutes: int = Field(..., ge=1)
    attendees: list[str] = Field(default_factory=list)
    location: str = ""
    priority: MeetingPriority = "normal"
    cancelled: bool = False


class Contact(BaseModel):
    """Stakeholder in the exec's network."""

    model_config = ConfigDict(extra="forbid")

    name: str
    relationship_type: ContactRelationship
    communication_preference: CommPreference
    importance: int = Field(..., ge=1, le=5)
    mood: Mood = "neutral"


class Task(BaseModel):
    """To-do item."""

    model_config = ConfigDict(extra="forbid")

    id: str
    description: str
    deadline: str = Field(..., description="ISO 8601 deadline")
    owner: str
    status: TaskStatus = "pending"
    effort: Effort = "medium"
    delegated_to: str | None = None


class WorldState(BaseModel):
    """Full simulated world — JSON-serialisable."""

    model_config = ConfigDict(extra="forbid")

    simulation_time: str = Field(..., description="Current simulated instant, ISO 8601")
    stress: int = Field(default=0, ge=0, le=100)
    active_conflicts: list[str] = Field(default_factory=list)
    action_log: list[str] = Field(default_factory=list)
    episode_active: bool = True
    episode_end_reason: str | None = None
    max_episode_steps: int = Field(default=48, ge=1, le=10_000)
    emails: list[Email] = Field(default_factory=list)
    meetings: list[Meeting] = Field(default_factory=list)
    contacts: list[Contact] = Field(default_factory=list)
    tasks: list[Task] = Field(default_factory=list)


class GhostexecAction(ActionBase):
    """
    Legal agent actions (Phase 3). Unknown HTTP payloads default to do_nothing
    so older clients do not crash deserialization.
    """

    action_type: GhostexecActionType = Field(
        default="do_nothing",
        description="Which legal action to execute this step",
    )
    email_id: str = ""
    message_body: str = ""
    meeting_id: str = ""
    new_time: str = ""
    reason: str = ""
    task_id: str = ""
    contact_name: str = ""
    message: str = Field(default="", description="Optional note for action_log (legacy / debug)")

    @model_validator(mode="before")
    @classmethod
    def _default_action_type(cls, data: Any) -> Any:
        if isinstance(data, dict) and "action_type" not in data:
            data = {**data, "action_type": "do_nothing"}
        return data


class GhostexecObservation(ObservationBase):
    """
    Primary LLM-facing field is `echoed_message`: full plain-text briefing (Phase 3).
    """

    # Keep these fields explicit for compatibility with OpenEnv builds where
    # Observation is not a pydantic base carrying done/reward/metadata.
    done: bool = False
    reward: float | None = None
    metadata: dict[str, Any] = Field(default_factory=dict)

    echoed_message: str = Field(
        default="",
        description="Human-readable briefing text for the LLM (not JSON)",
    )
    message_length: int = Field(default=0, description="Byte length of echoed_message for quick checks")


class RewardBreakdown(BaseModel):
    """Phase 4 reward components (logged and exposed in observation metadata)."""

    model_config = ConfigDict(extra="forbid")

    conflict_raw: float = 0.0
    critical_queue_bonus: float = 0.0
    conflict: float = 0.0
    relationship: float = 0.0
    task: float = 0.0
    shaping_synergy: float = 0.0
    shaping_tradeoff: float = 0.0
    shaping_potential: float = 0.0
    shaping_scaffold: float = 0.0
    shaping_quality: float = 0.0
    shaping_total: float = 0.0
    shaping_to_base_ratio: float = 0.0
    weighted_base: float = 0.0
    output_scale: float = 1.0
    invalid_step_adjustment: float = 0.0
    episode_completion_bonus: float = 0.0
    catastrophic_penalty: float = 0.0
    do_nothing_floor: float = 0.0
    final: float = 0.0