agent-office-cli 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.
- agent_office/__init__.py +73 -0
- agent_office/adapters/__init__.py +11 -0
- agent_office/adapters/base.py +76 -0
- agent_office/adapters/discord.py +254 -0
- agent_office/adapters/memory.py +253 -0
- agent_office/cli.py +352 -0
- agent_office/errors.py +66 -0
- agent_office/formatter.py +204 -0
- agent_office/models.py +303 -0
- agent_office/service.py +551 -0
- agent_office/store.py +624 -0
- agent_office_cli-0.1.0.dist-info/METADATA +93 -0
- agent_office_cli-0.1.0.dist-info/RECORD +16 -0
- agent_office_cli-0.1.0.dist-info/WHEEL +5 -0
- agent_office_cli-0.1.0.dist-info/entry_points.txt +2 -0
- agent_office_cli-0.1.0.dist-info/top_level.txt +1 -0
agent_office/store.py
ADDED
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
"""SQLite persistence store for Agent Office."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import sqlite3
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from .errors import ConflictError, InvalidArgumentsError, NotFoundError, StorageError
|
|
13
|
+
from .models import (
|
|
14
|
+
CLOSED_REQUEST_STATUSES,
|
|
15
|
+
VALID_ACTOR_ROLES,
|
|
16
|
+
VALID_REQUEST_STATUSES,
|
|
17
|
+
Actor,
|
|
18
|
+
ActorRole,
|
|
19
|
+
Desk,
|
|
20
|
+
EventType,
|
|
21
|
+
Request,
|
|
22
|
+
RequestEvent,
|
|
23
|
+
RequestStatus,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
DEFAULT_DB_ENV = "AGENT_OFFICE_DB"
|
|
27
|
+
_UNSET: Any = object()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _utc_now_iso() -> str:
|
|
31
|
+
return datetime.now(timezone.utc).isoformat()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def default_db_path() -> Path:
|
|
35
|
+
env_path = os.environ.get(DEFAULT_DB_ENV, "").strip()
|
|
36
|
+
if env_path:
|
|
37
|
+
return Path(env_path)
|
|
38
|
+
appdata = os.environ.get("APPDATA")
|
|
39
|
+
if appdata:
|
|
40
|
+
return Path(appdata) / "agent-office" / "agent_office.db"
|
|
41
|
+
return Path.home() / ".config" / "agent-office" / "agent_office.db"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_SCHEMA_SQL = """
|
|
45
|
+
CREATE TABLE IF NOT EXISTS counters (
|
|
46
|
+
name TEXT PRIMARY KEY,
|
|
47
|
+
value INTEGER NOT NULL
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
CREATE TABLE IF NOT EXISTS desks (
|
|
51
|
+
desk_id TEXT PRIMARY KEY,
|
|
52
|
+
name TEXT NOT NULL,
|
|
53
|
+
adapter_type TEXT NOT NULL DEFAULT 'discord',
|
|
54
|
+
channel_id TEXT NOT NULL,
|
|
55
|
+
inbox_cursor TEXT,
|
|
56
|
+
default_assignee_id TEXT,
|
|
57
|
+
created_at TEXT NOT NULL
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
CREATE TABLE IF NOT EXISTS actors (
|
|
61
|
+
actor_id TEXT PRIMARY KEY,
|
|
62
|
+
display_name TEXT NOT NULL,
|
|
63
|
+
role TEXT NOT NULL,
|
|
64
|
+
desk_id TEXT,
|
|
65
|
+
external_user_id TEXT,
|
|
66
|
+
is_bot INTEGER NOT NULL DEFAULT 0,
|
|
67
|
+
created_at TEXT NOT NULL,
|
|
68
|
+
FOREIGN KEY (desk_id) REFERENCES desks(desk_id)
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
CREATE TABLE IF NOT EXISTS requests (
|
|
72
|
+
req_id TEXT PRIMARY KEY,
|
|
73
|
+
parent_req_id TEXT,
|
|
74
|
+
desk_id TEXT NOT NULL,
|
|
75
|
+
title TEXT NOT NULL,
|
|
76
|
+
body TEXT NOT NULL,
|
|
77
|
+
status TEXT NOT NULL,
|
|
78
|
+
requester_actor_id TEXT,
|
|
79
|
+
requester_external_id TEXT,
|
|
80
|
+
assignee_actor_id TEXT,
|
|
81
|
+
channel_id TEXT NOT NULL,
|
|
82
|
+
source_message_id TEXT,
|
|
83
|
+
thread_id TEXT,
|
|
84
|
+
thread_cursor TEXT,
|
|
85
|
+
created_at TEXT NOT NULL,
|
|
86
|
+
updated_at TEXT NOT NULL,
|
|
87
|
+
closed_at TEXT,
|
|
88
|
+
FOREIGN KEY (parent_req_id) REFERENCES requests(req_id),
|
|
89
|
+
FOREIGN KEY (desk_id) REFERENCES desks(desk_id),
|
|
90
|
+
FOREIGN KEY (requester_actor_id) REFERENCES actors(actor_id),
|
|
91
|
+
FOREIGN KEY (assignee_actor_id) REFERENCES actors(actor_id)
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_requests_channel_source
|
|
95
|
+
ON requests(channel_id, source_message_id)
|
|
96
|
+
WHERE source_message_id IS NOT NULL;
|
|
97
|
+
|
|
98
|
+
CREATE INDEX IF NOT EXISTS idx_requests_desk_status
|
|
99
|
+
ON requests(desk_id, status);
|
|
100
|
+
|
|
101
|
+
CREATE INDEX IF NOT EXISTS idx_requests_parent
|
|
102
|
+
ON requests(parent_req_id);
|
|
103
|
+
|
|
104
|
+
CREATE TABLE IF NOT EXISTS request_events (
|
|
105
|
+
event_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
106
|
+
req_id TEXT NOT NULL,
|
|
107
|
+
event_type TEXT NOT NULL,
|
|
108
|
+
actor_id TEXT,
|
|
109
|
+
external_user_id TEXT,
|
|
110
|
+
external_message_id TEXT,
|
|
111
|
+
content TEXT NOT NULL DEFAULT '',
|
|
112
|
+
metadata_json TEXT NOT NULL DEFAULT '{}',
|
|
113
|
+
created_at TEXT NOT NULL,
|
|
114
|
+
FOREIGN KEY (req_id) REFERENCES requests(req_id)
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
CREATE INDEX IF NOT EXISTS idx_events_req_id
|
|
118
|
+
ON request_events(req_id, event_id);
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _row_to_desk(row: sqlite3.Row) -> Desk:
|
|
123
|
+
return Desk(
|
|
124
|
+
desk_id=row["desk_id"],
|
|
125
|
+
name=row["name"],
|
|
126
|
+
adapter_type=row["adapter_type"],
|
|
127
|
+
channel_id=row["channel_id"],
|
|
128
|
+
inbox_cursor=row["inbox_cursor"],
|
|
129
|
+
default_assignee_id=row["default_assignee_id"],
|
|
130
|
+
created_at=row["created_at"],
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _row_to_actor(row: sqlite3.Row) -> Actor:
|
|
135
|
+
return Actor(
|
|
136
|
+
actor_id=row["actor_id"],
|
|
137
|
+
display_name=row["display_name"],
|
|
138
|
+
role=row["role"],
|
|
139
|
+
desk_id=row["desk_id"],
|
|
140
|
+
external_user_id=row["external_user_id"],
|
|
141
|
+
is_bot=bool(row["is_bot"]),
|
|
142
|
+
created_at=row["created_at"],
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _row_to_request(row: sqlite3.Row) -> Request:
|
|
147
|
+
return Request(
|
|
148
|
+
req_id=row["req_id"],
|
|
149
|
+
parent_req_id=row["parent_req_id"],
|
|
150
|
+
desk_id=row["desk_id"],
|
|
151
|
+
title=row["title"],
|
|
152
|
+
body=row["body"],
|
|
153
|
+
status=row["status"],
|
|
154
|
+
requester_actor_id=row["requester_actor_id"],
|
|
155
|
+
requester_external_id=row["requester_external_id"],
|
|
156
|
+
assignee_actor_id=row["assignee_actor_id"],
|
|
157
|
+
channel_id=row["channel_id"],
|
|
158
|
+
source_message_id=row["source_message_id"],
|
|
159
|
+
thread_id=row["thread_id"],
|
|
160
|
+
thread_cursor=row["thread_cursor"],
|
|
161
|
+
created_at=row["created_at"],
|
|
162
|
+
updated_at=row["updated_at"],
|
|
163
|
+
closed_at=row["closed_at"],
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _row_to_event(row: sqlite3.Row) -> RequestEvent:
|
|
168
|
+
try:
|
|
169
|
+
meta = json.loads(row["metadata_json"]) if row["metadata_json"] else {}
|
|
170
|
+
except json.JSONDecodeError:
|
|
171
|
+
meta = {}
|
|
172
|
+
return RequestEvent(
|
|
173
|
+
event_id=int(row["event_id"]),
|
|
174
|
+
req_id=row["req_id"],
|
|
175
|
+
event_type=row["event_type"],
|
|
176
|
+
actor_id=row["actor_id"],
|
|
177
|
+
external_user_id=row["external_user_id"],
|
|
178
|
+
external_message_id=row["external_message_id"],
|
|
179
|
+
content=row["content"],
|
|
180
|
+
metadata=meta if isinstance(meta, dict) else {},
|
|
181
|
+
created_at=row["created_at"],
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
class SQLiteStore:
|
|
186
|
+
"""SQLite-backed state store for desks, actors, requests, cursors, and events."""
|
|
187
|
+
|
|
188
|
+
def __init__(self, db_path: str | Path | None = None) -> None:
|
|
189
|
+
if db_path is None:
|
|
190
|
+
resolved = default_db_path()
|
|
191
|
+
self._db_target = str(resolved)
|
|
192
|
+
resolved.parent.mkdir(parents=True, exist_ok=True)
|
|
193
|
+
elif str(db_path) == ":memory:":
|
|
194
|
+
self._db_target = ":memory:"
|
|
195
|
+
else:
|
|
196
|
+
resolved = Path(db_path)
|
|
197
|
+
resolved.parent.mkdir(parents=True, exist_ok=True)
|
|
198
|
+
self._db_target = str(resolved)
|
|
199
|
+
|
|
200
|
+
try:
|
|
201
|
+
self._conn = sqlite3.connect(self._db_target)
|
|
202
|
+
self._conn.row_factory = sqlite3.Row
|
|
203
|
+
self._conn.execute("PRAGMA foreign_keys = ON;")
|
|
204
|
+
if self._db_target != ":memory:":
|
|
205
|
+
self._conn.execute("PRAGMA journal_mode = WAL;")
|
|
206
|
+
self._conn.executescript(_SCHEMA_SQL)
|
|
207
|
+
self._conn.commit()
|
|
208
|
+
except sqlite3.Error as exc:
|
|
209
|
+
raise StorageError(f"Failed to initialize database '{self._db_target}': {exc}") from exc
|
|
210
|
+
|
|
211
|
+
@property
|
|
212
|
+
def db_path(self) -> str:
|
|
213
|
+
return self._db_target
|
|
214
|
+
|
|
215
|
+
def close(self) -> None:
|
|
216
|
+
self._conn.close()
|
|
217
|
+
|
|
218
|
+
def __enter__(self) -> SQLiteStore:
|
|
219
|
+
return self
|
|
220
|
+
|
|
221
|
+
def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
222
|
+
self.close()
|
|
223
|
+
|
|
224
|
+
# --- Desks ---
|
|
225
|
+
|
|
226
|
+
def create_desk(
|
|
227
|
+
self,
|
|
228
|
+
desk_id: str,
|
|
229
|
+
channel_id: str,
|
|
230
|
+
*,
|
|
231
|
+
name: str | None = None,
|
|
232
|
+
adapter_type: str = "discord",
|
|
233
|
+
default_assignee_id: str | None = None,
|
|
234
|
+
) -> Desk:
|
|
235
|
+
cleaned_id = desk_id.strip()
|
|
236
|
+
cleaned_ch = channel_id.strip()
|
|
237
|
+
if not cleaned_id:
|
|
238
|
+
raise InvalidArgumentsError("desk_id must not be empty.")
|
|
239
|
+
if not cleaned_ch:
|
|
240
|
+
raise InvalidArgumentsError("channel_id must not be empty.")
|
|
241
|
+
|
|
242
|
+
now = _utc_now_iso()
|
|
243
|
+
display_name = (name or cleaned_id).strip() or cleaned_id
|
|
244
|
+
try:
|
|
245
|
+
with self._conn:
|
|
246
|
+
self._conn.execute(
|
|
247
|
+
"""
|
|
248
|
+
INSERT INTO desks (desk_id, name, adapter_type, channel_id, default_assignee_id, created_at)
|
|
249
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
250
|
+
""",
|
|
251
|
+
(cleaned_id, display_name, adapter_type.strip() or "discord", cleaned_ch, default_assignee_id, now),
|
|
252
|
+
)
|
|
253
|
+
except sqlite3.IntegrityError as exc:
|
|
254
|
+
raise ConflictError(f"Desk '{cleaned_id}' already exists.") from exc
|
|
255
|
+
except sqlite3.Error as exc:
|
|
256
|
+
raise StorageError(f"Failed to create desk '{cleaned_id}': {exc}") from exc
|
|
257
|
+
return self.get_desk(cleaned_id)
|
|
258
|
+
|
|
259
|
+
def get_desk(self, desk_id: str) -> Desk:
|
|
260
|
+
row = self._conn.execute(
|
|
261
|
+
"SELECT * FROM desks WHERE desk_id = ?", (desk_id.strip(),)
|
|
262
|
+
).fetchone()
|
|
263
|
+
if row is None:
|
|
264
|
+
raise NotFoundError(f"Desk '{desk_id}' was not found.")
|
|
265
|
+
return _row_to_desk(row)
|
|
266
|
+
|
|
267
|
+
def list_desks(self) -> list[Desk]:
|
|
268
|
+
rows = self._conn.execute("SELECT * FROM desks ORDER BY created_at ASC, desk_id ASC").fetchall()
|
|
269
|
+
return [_row_to_desk(r) for r in rows]
|
|
270
|
+
|
|
271
|
+
def update_desk_inbox_cursor(self, desk_id: str, cursor: str | None) -> Desk:
|
|
272
|
+
self.get_desk(desk_id)
|
|
273
|
+
try:
|
|
274
|
+
with self._conn:
|
|
275
|
+
self._conn.execute(
|
|
276
|
+
"UPDATE desks SET inbox_cursor = ? WHERE desk_id = ?",
|
|
277
|
+
(cursor, desk_id.strip()),
|
|
278
|
+
)
|
|
279
|
+
except sqlite3.Error as exc:
|
|
280
|
+
raise StorageError(f"Failed to update inbox cursor for desk '{desk_id}': {exc}") from exc
|
|
281
|
+
return self.get_desk(desk_id)
|
|
282
|
+
|
|
283
|
+
# --- Actors ---
|
|
284
|
+
|
|
285
|
+
def create_actor(
|
|
286
|
+
self,
|
|
287
|
+
actor_id: str,
|
|
288
|
+
role: ActorRole,
|
|
289
|
+
*,
|
|
290
|
+
display_name: str | None = None,
|
|
291
|
+
desk_id: str | None = None,
|
|
292
|
+
external_user_id: str | None = None,
|
|
293
|
+
is_bot: bool | None = None,
|
|
294
|
+
) -> Actor:
|
|
295
|
+
cleaned_id = actor_id.strip()
|
|
296
|
+
if not cleaned_id:
|
|
297
|
+
raise InvalidArgumentsError("actor_id must not be empty.")
|
|
298
|
+
if role not in VALID_ACTOR_ROLES:
|
|
299
|
+
raise InvalidArgumentsError(
|
|
300
|
+
f"Invalid actor role '{role}'. Expected one of: {', '.join(VALID_ACTOR_ROLES)}."
|
|
301
|
+
)
|
|
302
|
+
if desk_id is not None:
|
|
303
|
+
self.get_desk(desk_id)
|
|
304
|
+
|
|
305
|
+
resolved_bot = (role != "human") if is_bot is None else bool(is_bot)
|
|
306
|
+
now = _utc_now_iso()
|
|
307
|
+
label = (display_name or cleaned_id).strip() or cleaned_id
|
|
308
|
+
ext_id = external_user_id.strip() if external_user_id else None
|
|
309
|
+
try:
|
|
310
|
+
with self._conn:
|
|
311
|
+
self._conn.execute(
|
|
312
|
+
"""
|
|
313
|
+
INSERT INTO actors (actor_id, display_name, role, desk_id, external_user_id, is_bot, created_at)
|
|
314
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
315
|
+
""",
|
|
316
|
+
(cleaned_id, label, role, desk_id, ext_id, int(resolved_bot), now),
|
|
317
|
+
)
|
|
318
|
+
except sqlite3.IntegrityError as exc:
|
|
319
|
+
raise ConflictError(f"Actor '{cleaned_id}' already exists.") from exc
|
|
320
|
+
except sqlite3.Error as exc:
|
|
321
|
+
raise StorageError(f"Failed to create actor '{cleaned_id}': {exc}") from exc
|
|
322
|
+
return self.get_actor(cleaned_id)
|
|
323
|
+
|
|
324
|
+
def get_actor(self, actor_id: str) -> Actor:
|
|
325
|
+
row = self._conn.execute(
|
|
326
|
+
"SELECT * FROM actors WHERE actor_id = ?", (actor_id.strip(),)
|
|
327
|
+
).fetchone()
|
|
328
|
+
if row is None:
|
|
329
|
+
raise NotFoundError(f"Actor '{actor_id}' was not found.")
|
|
330
|
+
return _row_to_actor(row)
|
|
331
|
+
|
|
332
|
+
def find_actor_by_external_id(self, external_user_id: str) -> Actor | None:
|
|
333
|
+
cleaned = external_user_id.strip()
|
|
334
|
+
if not cleaned:
|
|
335
|
+
return None
|
|
336
|
+
row = self._conn.execute(
|
|
337
|
+
"SELECT * FROM actors WHERE external_user_id = ? LIMIT 1", (cleaned,)
|
|
338
|
+
).fetchone()
|
|
339
|
+
return _row_to_actor(row) if row is not None else None
|
|
340
|
+
|
|
341
|
+
def list_actors(
|
|
342
|
+
self,
|
|
343
|
+
*,
|
|
344
|
+
desk_id: str | None = None,
|
|
345
|
+
role: str | None = None,
|
|
346
|
+
) -> list[Actor]:
|
|
347
|
+
clauses: list[str] = []
|
|
348
|
+
params: list[Any] = []
|
|
349
|
+
if desk_id is not None:
|
|
350
|
+
clauses.append("desk_id = ?")
|
|
351
|
+
params.append(desk_id.strip())
|
|
352
|
+
if role is not None:
|
|
353
|
+
clauses.append("role = ?")
|
|
354
|
+
params.append(role.strip())
|
|
355
|
+
where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
|
|
356
|
+
rows = self._conn.execute(
|
|
357
|
+
f"SELECT * FROM actors {where} ORDER BY created_at ASC, actor_id ASC",
|
|
358
|
+
params,
|
|
359
|
+
).fetchall()
|
|
360
|
+
return [_row_to_actor(r) for r in rows]
|
|
361
|
+
|
|
362
|
+
# --- Requests ---
|
|
363
|
+
|
|
364
|
+
def next_req_id(self) -> str:
|
|
365
|
+
try:
|
|
366
|
+
with self._conn:
|
|
367
|
+
self._conn.execute(
|
|
368
|
+
"""
|
|
369
|
+
INSERT INTO counters (name, value) VALUES ('req_seq', 1)
|
|
370
|
+
ON CONFLICT(name) DO UPDATE SET value = value + 1
|
|
371
|
+
"""
|
|
372
|
+
)
|
|
373
|
+
row = self._conn.execute(
|
|
374
|
+
"SELECT value FROM counters WHERE name = 'req_seq'"
|
|
375
|
+
).fetchone()
|
|
376
|
+
seq = int(row["value"]) if row is not None else 1
|
|
377
|
+
except sqlite3.Error as exc:
|
|
378
|
+
raise StorageError(f"Failed to allocate next REQ-ID: {exc}") from exc
|
|
379
|
+
return f"REQ-{seq:04d}"
|
|
380
|
+
|
|
381
|
+
def create_request(
|
|
382
|
+
self,
|
|
383
|
+
*,
|
|
384
|
+
desk_id: str,
|
|
385
|
+
title: str,
|
|
386
|
+
body: str,
|
|
387
|
+
channel_id: str,
|
|
388
|
+
req_id: str | None = None,
|
|
389
|
+
parent_req_id: str | None = None,
|
|
390
|
+
status: RequestStatus = "OPEN",
|
|
391
|
+
requester_actor_id: str | None = None,
|
|
392
|
+
requester_external_id: str | None = None,
|
|
393
|
+
assignee_actor_id: str | None = None,
|
|
394
|
+
source_message_id: str | None = None,
|
|
395
|
+
thread_id: str | None = None,
|
|
396
|
+
thread_cursor: str | None = None,
|
|
397
|
+
) -> Request:
|
|
398
|
+
if status not in VALID_REQUEST_STATUSES:
|
|
399
|
+
raise InvalidArgumentsError(f"Invalid request status '{status}'.")
|
|
400
|
+
if parent_req_id is not None:
|
|
401
|
+
self.get_request(parent_req_id)
|
|
402
|
+
if requester_actor_id is not None:
|
|
403
|
+
self.get_actor(requester_actor_id)
|
|
404
|
+
if assignee_actor_id is not None:
|
|
405
|
+
self.get_actor(assignee_actor_id)
|
|
406
|
+
|
|
407
|
+
allocated_id = req_id.strip() if req_id else self.next_req_id()
|
|
408
|
+
now = _utc_now_iso()
|
|
409
|
+
closed_at = now if status in CLOSED_REQUEST_STATUSES else None
|
|
410
|
+
try:
|
|
411
|
+
with self._conn:
|
|
412
|
+
self._conn.execute(
|
|
413
|
+
"""
|
|
414
|
+
INSERT INTO requests (
|
|
415
|
+
req_id, parent_req_id, desk_id, title, body, status,
|
|
416
|
+
requester_actor_id, requester_external_id, assignee_actor_id,
|
|
417
|
+
channel_id, source_message_id, thread_id, thread_cursor,
|
|
418
|
+
created_at, updated_at, closed_at
|
|
419
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
420
|
+
""",
|
|
421
|
+
(
|
|
422
|
+
allocated_id,
|
|
423
|
+
parent_req_id,
|
|
424
|
+
desk_id,
|
|
425
|
+
title,
|
|
426
|
+
body,
|
|
427
|
+
status,
|
|
428
|
+
requester_actor_id,
|
|
429
|
+
requester_external_id,
|
|
430
|
+
assignee_actor_id,
|
|
431
|
+
channel_id,
|
|
432
|
+
source_message_id,
|
|
433
|
+
thread_id,
|
|
434
|
+
thread_cursor,
|
|
435
|
+
now,
|
|
436
|
+
now,
|
|
437
|
+
closed_at,
|
|
438
|
+
),
|
|
439
|
+
)
|
|
440
|
+
except sqlite3.IntegrityError as exc:
|
|
441
|
+
raise ConflictError(f"Request '{allocated_id}' conflicts with an existing record: {exc}") from exc
|
|
442
|
+
except sqlite3.Error as exc:
|
|
443
|
+
raise StorageError(f"Failed to create request '{allocated_id}': {exc}") from exc
|
|
444
|
+
return self.get_request(allocated_id)
|
|
445
|
+
|
|
446
|
+
def get_request(self, req_id: str) -> Request:
|
|
447
|
+
row = self._conn.execute(
|
|
448
|
+
"SELECT * FROM requests WHERE req_id = ?", (req_id.strip(),)
|
|
449
|
+
).fetchone()
|
|
450
|
+
if row is None:
|
|
451
|
+
raise NotFoundError(f"Request '{req_id}' was not found.")
|
|
452
|
+
return _row_to_request(row)
|
|
453
|
+
|
|
454
|
+
def find_request_by_source_message(
|
|
455
|
+
self,
|
|
456
|
+
channel_id: str,
|
|
457
|
+
source_message_id: str,
|
|
458
|
+
) -> Request | None:
|
|
459
|
+
row = self._conn.execute(
|
|
460
|
+
"SELECT * FROM requests WHERE channel_id = ? AND source_message_id = ? LIMIT 1",
|
|
461
|
+
(channel_id.strip(), source_message_id.strip()),
|
|
462
|
+
).fetchone()
|
|
463
|
+
return _row_to_request(row) if row is not None else None
|
|
464
|
+
|
|
465
|
+
def list_requests(
|
|
466
|
+
self,
|
|
467
|
+
*,
|
|
468
|
+
desk_id: str | None = None,
|
|
469
|
+
status: str | None = None,
|
|
470
|
+
parent_req_id: str | None = None,
|
|
471
|
+
assignee_actor_id: str | None = None,
|
|
472
|
+
limit: int = 50,
|
|
473
|
+
) -> list[Request]:
|
|
474
|
+
clauses: list[str] = []
|
|
475
|
+
params: list[Any] = []
|
|
476
|
+
if desk_id is not None:
|
|
477
|
+
clauses.append("desk_id = ?")
|
|
478
|
+
params.append(desk_id.strip())
|
|
479
|
+
if status is not None:
|
|
480
|
+
clauses.append("status = ?")
|
|
481
|
+
params.append(status.strip().upper())
|
|
482
|
+
if parent_req_id is not None:
|
|
483
|
+
clauses.append("parent_req_id = ?")
|
|
484
|
+
params.append(parent_req_id.strip())
|
|
485
|
+
if assignee_actor_id is not None:
|
|
486
|
+
clauses.append("assignee_actor_id = ?")
|
|
487
|
+
params.append(assignee_actor_id.strip())
|
|
488
|
+
where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
|
|
489
|
+
params.append(max(1, int(limit)))
|
|
490
|
+
rows = self._conn.execute(
|
|
491
|
+
f"SELECT * FROM requests {where} ORDER BY created_at DESC, req_id DESC LIMIT ?",
|
|
492
|
+
params,
|
|
493
|
+
).fetchall()
|
|
494
|
+
return [_row_to_request(r) for r in rows]
|
|
495
|
+
|
|
496
|
+
def update_request(
|
|
497
|
+
self,
|
|
498
|
+
req_id: str,
|
|
499
|
+
*,
|
|
500
|
+
status: Any = _UNSET,
|
|
501
|
+
assignee_actor_id: Any = _UNSET,
|
|
502
|
+
source_message_id: Any = _UNSET,
|
|
503
|
+
thread_id: Any = _UNSET,
|
|
504
|
+
thread_cursor: Any = _UNSET,
|
|
505
|
+
) -> Request:
|
|
506
|
+
existing = self.get_request(req_id)
|
|
507
|
+
updates: list[str] = []
|
|
508
|
+
params: list[Any] = []
|
|
509
|
+
now = _utc_now_iso()
|
|
510
|
+
|
|
511
|
+
if status is not _UNSET:
|
|
512
|
+
if status not in VALID_REQUEST_STATUSES:
|
|
513
|
+
raise InvalidArgumentsError(f"Invalid request status '{status}'.")
|
|
514
|
+
updates.append("status = ?")
|
|
515
|
+
params.append(status)
|
|
516
|
+
if status in CLOSED_REQUEST_STATUSES:
|
|
517
|
+
updates.append("closed_at = ?")
|
|
518
|
+
params.append(existing.closed_at or now)
|
|
519
|
+
else:
|
|
520
|
+
updates.append("closed_at = NULL")
|
|
521
|
+
|
|
522
|
+
if assignee_actor_id is not _UNSET:
|
|
523
|
+
if assignee_actor_id is not None:
|
|
524
|
+
self.get_actor(assignee_actor_id)
|
|
525
|
+
updates.append("assignee_actor_id = ?")
|
|
526
|
+
params.append(assignee_actor_id)
|
|
527
|
+
|
|
528
|
+
if source_message_id is not _UNSET:
|
|
529
|
+
updates.append("source_message_id = ?")
|
|
530
|
+
params.append(source_message_id)
|
|
531
|
+
|
|
532
|
+
if thread_id is not _UNSET:
|
|
533
|
+
updates.append("thread_id = ?")
|
|
534
|
+
params.append(thread_id)
|
|
535
|
+
|
|
536
|
+
if thread_cursor is not _UNSET:
|
|
537
|
+
updates.append("thread_cursor = ?")
|
|
538
|
+
params.append(thread_cursor)
|
|
539
|
+
|
|
540
|
+
if not updates:
|
|
541
|
+
return existing
|
|
542
|
+
|
|
543
|
+
updates.append("updated_at = ?")
|
|
544
|
+
params.append(now)
|
|
545
|
+
params.append(existing.req_id)
|
|
546
|
+
|
|
547
|
+
try:
|
|
548
|
+
with self._conn:
|
|
549
|
+
self._conn.execute(
|
|
550
|
+
f"UPDATE requests SET {', '.join(updates)} WHERE req_id = ?",
|
|
551
|
+
params,
|
|
552
|
+
)
|
|
553
|
+
except sqlite3.Error as exc:
|
|
554
|
+
raise StorageError(f"Failed to update request '{req_id}': {exc}") from exc
|
|
555
|
+
return self.get_request(existing.req_id)
|
|
556
|
+
|
|
557
|
+
# --- Events ---
|
|
558
|
+
|
|
559
|
+
def add_event(
|
|
560
|
+
self,
|
|
561
|
+
req_id: str,
|
|
562
|
+
event_type: EventType,
|
|
563
|
+
*,
|
|
564
|
+
content: str = "",
|
|
565
|
+
actor_id: str | None = None,
|
|
566
|
+
external_user_id: str | None = None,
|
|
567
|
+
external_message_id: str | None = None,
|
|
568
|
+
metadata: dict[str, Any] | None = None,
|
|
569
|
+
) -> RequestEvent:
|
|
570
|
+
now = _utc_now_iso()
|
|
571
|
+
meta_json = json.dumps(metadata or {}, ensure_ascii=False)
|
|
572
|
+
try:
|
|
573
|
+
with self._conn:
|
|
574
|
+
cur = self._conn.execute(
|
|
575
|
+
"""
|
|
576
|
+
INSERT INTO request_events (
|
|
577
|
+
req_id, event_type, actor_id, external_user_id,
|
|
578
|
+
external_message_id, content, metadata_json, created_at
|
|
579
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
580
|
+
""",
|
|
581
|
+
(
|
|
582
|
+
req_id,
|
|
583
|
+
event_type,
|
|
584
|
+
actor_id,
|
|
585
|
+
external_user_id,
|
|
586
|
+
external_message_id,
|
|
587
|
+
content,
|
|
588
|
+
meta_json,
|
|
589
|
+
now,
|
|
590
|
+
),
|
|
591
|
+
)
|
|
592
|
+
event_id = int(cur.lastrowid or 0)
|
|
593
|
+
except sqlite3.Error as exc:
|
|
594
|
+
raise StorageError(f"Failed to log event for request '{req_id}': {exc}") from exc
|
|
595
|
+
row = self._conn.execute(
|
|
596
|
+
"SELECT * FROM request_events WHERE event_id = ?", (event_id,)
|
|
597
|
+
).fetchone()
|
|
598
|
+
assert row is not None
|
|
599
|
+
return _row_to_event(row)
|
|
600
|
+
|
|
601
|
+
def list_events(self, req_id: str, *, limit: int = 50) -> list[RequestEvent]:
|
|
602
|
+
self.get_request(req_id)
|
|
603
|
+
rows = self._conn.execute(
|
|
604
|
+
"""
|
|
605
|
+
SELECT * FROM request_events
|
|
606
|
+
WHERE req_id = ?
|
|
607
|
+
ORDER BY event_id ASC
|
|
608
|
+
LIMIT ?
|
|
609
|
+
""",
|
|
610
|
+
(req_id.strip(), max(1, int(limit))),
|
|
611
|
+
).fetchall()
|
|
612
|
+
return [_row_to_event(r) for r in rows]
|
|
613
|
+
|
|
614
|
+
# --- Allowlist helpers ---
|
|
615
|
+
|
|
616
|
+
def list_allowed_channels(self) -> list[str]:
|
|
617
|
+
rows = self._conn.execute("SELECT DISTINCT channel_id FROM desks").fetchall()
|
|
618
|
+
return [str(r["channel_id"]) for r in rows if r["channel_id"]]
|
|
619
|
+
|
|
620
|
+
def list_allowed_threads(self) -> list[str]:
|
|
621
|
+
rows = self._conn.execute(
|
|
622
|
+
"SELECT DISTINCT thread_id FROM requests WHERE thread_id IS NOT NULL"
|
|
623
|
+
).fetchall()
|
|
624
|
+
return [str(r["thread_id"]) for r in rows if r["thread_id"]]
|