Coverage for app / services / attachments.py: 99%

133 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""A chat turn's attached documents: which it may use, and how they travel. 

2 

3svc-core used to paste a chat's documents into the person's message, as a 

4``<documents>`` block before what they typed, and store the message that 

5way: every step of svc-ai's run read a document as the person's words (the 

624 October 2026 refusal), and the conversation could say which file a 

7message carried only by parsing its text. 

8 

9Now a turn's documents are data of their own: 

10 

11* **this message's** (:func:`turn_attachments`): the library documents the 

12 person attached, from the chat's workspace only, every one read; 

13* **earlier messages'** (:func:`earlier_attachments`): what the 

14 conversation's stored messages attached (``meta.attachments``), so the 

15 agent can use any document of the conversation — one since deleted, or no 

16 longer readable, is named and never quoted; 

17* **one list** (:func:`for_turn`): each document once, within the wire's 

18 limits (``app/util/attachment_wire.py``, shared with svc-ai); 

19* **governed as before** (:func:`governed_text`): the Input rules evaluate 

20 this message's documents with the words, as they always have, and their 

21 redaction then reaches the words and every document (:func:`redacted`); 

22* **sent beside the words** (:func:`wire`, ``ExecuteRequest.attachments``) 

23 and **stored beside them** (:func:`message_meta`): the message keeps the 

24 person's words, and names its documents by id. 

25""" 

26 

27from __future__ import annotations 

28 

29import hashlib 

30from collections.abc import Iterable, Sequence 

31from dataclasses import dataclass, replace 

32from typing import Any 

33 

34from sqlalchemy.orm import Session 

35 

36from app.db.postgres.enums import UploadEnum 

37from app.services import uploads 

38from app.util.attachment_wire import ( 

39 MAX_ATTACHMENT_CHARS, 

40 MAX_ATTACHMENTS, 

41 MAX_ATTACHMENTS_CHARS, 

42 MAX_TURN_ATTACHMENTS, 

43 AttachedIn, 

44 Availability, 

45) 

46from app.util.document import build_document_context_xml 

47 

48#: Where a user message keeps the documents it attached. 

49META_KEY = "attachments" 

50 

51 

52class TooManyDocuments(Exception): 

53 """A message attached more documents than one may carry.""" 

54 

55 def __init__(self, count: int): 

56 self.message = ( 

57 f"A message can carry {MAX_TURN_ATTACHMENTS} documents at most; " 

58 f"this one has {count}. Send the rest in another message." 

59 ) 

60 super().__init__(self.message) 

61 

62 

63@dataclass(frozen=True) 

64class TurnDocument: 

65 """One document a turn carries.""" 

66 

67 id: str 

68 name: str 

69 mime_type: str | None = None 

70 text: str = "" 

71 attached_in: AttachedIn = AttachedIn.turn 

72 availability: Availability = Availability.available 

73 #: Cut to ``MAX_ATTACHMENT_CHARS``. 

74 truncated: bool = False 

75 #: What its text hashes to: the same document attached twice is one. 

76 sha256: str | None = None 

77 #: For a document that is an answer — a swarm's piece, an earlier 

78 #: request's answer — the sources its text cites ``[1]``, ``[2]``… 

79 #: (``attachment_wire.carried_sources``): svc-ai gives each an id of the 

80 #: run's, so a step that reads it cites the source itself. 

81 sources: tuple[dict[str, Any], ...] = () 

82 

83 @property 

84 def readable(self) -> bool: 

85 return self.availability is Availability.available and bool(self.text) 

86 

87 def ref(self) -> dict[str, Any]: 

88 """What a stored message keeps of it: never its text.""" 

89 out: dict[str, Any] = {"id": self.id, "name": self.name} 

90 if self.mime_type: 

91 out["mime_type"] = self.mime_type 

92 return out 

93 

94 def spec(self) -> dict[str, Any]: 

95 """As svc-ai takes it (``ExecuteRequest.attachments``).""" 

96 out: dict[str, Any] = { 

97 "id": self.id, 

98 "name": self.name, 

99 "text": self.text, 

100 "attached_in": self.attached_in.value, 

101 "availability": self.availability.value, 

102 } 

103 if self.mime_type: 

104 out["mime_type"] = self.mime_type 

105 if self.truncated: 

106 out["truncated"] = True 

107 if self.sources: 

108 out["sources"] = list(self.sources) 

109 return out 

110 

111 

112def _sha(text: str) -> str: 

113 return hashlib.sha256(text.encode()).hexdigest() 

114 

115 

116def _of(row: Any, attached_in: AttachedIn) -> TurnDocument: 

117 text = row.content or "" 

118 return TurnDocument( 

119 id=str(row.id), 

120 name=row.name, 

121 mime_type=row.mime_type, 

122 text=text, 

123 attached_in=attached_in, 

124 sha256=row.content_sha256 or (_sha(text) if text else None), 

125 ) 

126 

127 

128def turn_attachments( 

129 db: Session, file_ids: Iterable[Any], ws: Any 

130) -> list[TurnDocument]: 

131 """The documents a message attaches: those of ``file_ids`` the chat's 

132 workspace ``ws`` holds, in the order given. Another workspace's id is 

133 left out, as if it did not exist; one of its own not read yet, or never 

134 readable, raises ``uploads.DocumentsNotReady`` — left out, the agent 

135 would answer as if it had read it. More than a message may carry raises 

136 :class:`TooManyDocuments`.""" 

137 ids = uploads.as_ids(file_ids) 

138 if len(ids) > MAX_TURN_ATTACHMENTS: 

139 raise TooManyDocuments(len(ids)) 

140 return [_of(row, AttachedIn.turn) for row in uploads.ready_rows(db, ids, ws)] 

141 

142 

143def stored_refs(meta: Any) -> list[dict[str, Any]]: 

144 """The documents a stored user message attached (``meta.attachments``), 

145 each ``{id, name, mime_type?}``; none for a message that attached none 

146 or predates them.""" 

147 refs = meta.get(META_KEY) if isinstance(meta, dict) else None 

148 out = [] 

149 for ref in refs or []: 

150 if isinstance(ref, dict) and ref.get("id") and ref.get("name"): 

151 out.append(ref) 

152 return out 

153 

154 

155def _newest_first(conversation: Any) -> list[Any]: 

156 messages = list(getattr(conversation, "messages", None) or []) 

157 return sorted( 

158 messages, 

159 key=lambda m: getattr(m, "sent_at", None) or 0, 

160 reverse=True, 

161 ) 

162 

163 

164def earlier_attachments( 

165 db: Session, conversation: Any, ws: Any, exclude: Iterable[str] = () 

166) -> list[TurnDocument]: 

167 """The documents the conversation's earlier messages attached, newest 

168 first, each once, less ``exclude`` (this message's). One the workspace 

169 still holds, read, comes with its text; one deleted since, moved out of 

170 reach or no longer readable is named only (``removed``).""" 

171 if conversation is None: 

172 return [] 

173 skip = {str(i) for i in exclude} 

174 named: dict[str, dict[str, Any]] = {} 

175 for message in _newest_first(conversation): 

176 if str(getattr(getattr(message, "role", None), "value", "")) != "user": 

177 continue 

178 for ref in stored_refs(getattr(message, "meta", None)): 

179 key = str(ref["id"]) 

180 if key not in skip and key not in named: 

181 named[key] = ref 

182 if not named: 

183 return [] 

184 rows = uploads.in_workspace(db, uploads.as_ids(named), ws) 

185 by_id = {str(row_id): row for row_id, row in rows.items()} 

186 out: list[TurnDocument] = [] 

187 for key, ref in named.items(): 

188 row = by_id.get(key) 

189 if row is not None and uploads.status_of(row)[0] is UploadEnum.Status.ready: 

190 out.append(_of(row, AttachedIn.earlier)) 

191 else: 

192 out.append( 

193 TurnDocument( 

194 id=key, 

195 name=str(ref["name"]), 

196 mime_type=ref.get("mime_type"), 

197 attached_in=AttachedIn.earlier, 

198 availability=Availability.removed, 

199 ) 

200 ) 

201 return out 

202 

203 

204def for_turn( 

205 this: Sequence[TurnDocument], earlier: Sequence[TurnDocument] = () 

206) -> list[TurnDocument]: 

207 """What the turn carries: this message's documents, then earlier ones, 

208 each once (by id, then by text), within the wire's limits. A document 

209 longer than one may carry is cut; this message's are never left out, and 

210 an earlier one past what a turn carries is named only (``omitted``).""" 

211 out: list[TurnDocument] = [] 

212 seen_ids: set[str] = set() 

213 seen_text: set[str] = set() 

214 total = 0 

215 for doc in [*this, *earlier]: 

216 if doc.id in seen_ids or (doc.readable and doc.sha256 in seen_text): 

217 continue 

218 if len(out) >= MAX_ATTACHMENTS: 

219 break 

220 seen_ids.add(doc.id) 

221 if doc.readable and doc.sha256: 

222 seen_text.add(doc.sha256) 

223 if doc.readable and len(doc.text) > MAX_ATTACHMENT_CHARS: 

224 doc = replace(doc, text=doc.text[:MAX_ATTACHMENT_CHARS], truncated=True) 

225 if doc.readable: 

226 if ( 

227 doc.attached_in is AttachedIn.earlier 

228 and total + len(doc.text) > MAX_ATTACHMENTS_CHARS 

229 ): 

230 doc = replace(doc, text="", availability=Availability.omitted) 

231 else: 

232 total += len(doc.text) 

233 out.append(doc) 

234 return out 

235 

236 

237def governed_text(words: str, this: Sequence[TurnDocument]) -> str: 

238 """What the Input rules evaluate: this message's documents as they were 

239 pasted, then the words — what the rules have always read, so a rule's 

240 conditions, a block and its one activity row keep their meaning. Never 

241 sent or stored.""" 

242 docs = build_document_context_xml( 

243 [{"name": d.name, "content": d.text} for d in this if d.readable] 

244 ) 

245 return f"{docs}\n\n{words}" if docs else words 

246 

247 

248def redacted(docs: Sequence[TurnDocument], rule_pass: Any) -> list[TurnDocument]: 

249 """``docs`` through the Input rules' redaction — their names and text, 

250 never their ids: the same placeholder for a value wherever it appears. 

251 Earlier documents meet it as the conversation's history does.""" 

252 redact = getattr(rule_pass, "redact", None) 

253 if redact is None: 

254 return list(docs) 

255 return [ 

256 replace(doc, name=redact(doc.name) or doc.name, text=redact(doc.text)) 

257 for doc in docs 

258 ] 

259 

260 

261def wire(docs: Sequence[TurnDocument]) -> list[dict[str, Any]]: 

262 """The turn's documents as svc-ai takes them.""" 

263 return [doc.spec() for doc in docs] 

264 

265 

266def message_meta( 

267 command_meta: dict[str, Any] | None, docs: Sequence[TurnDocument] 

268) -> dict[str, Any] | None: 

269 """What the user's message keeps beside its words: the chat command it 

270 ran (``command``) and the documents it attached (``attachments``) — 

271 this message's among ``docs``, by id.""" 

272 meta: dict[str, Any] = {} 

273 if command_meta: 

274 meta["command"] = command_meta 

275 refs = [d.ref() for d in docs if d.attached_in is AttachedIn.turn] 

276 if refs: 

277 meta[META_KEY] = refs 

278 return meta or None 

279 

280 

281def command_of(meta: Any) -> dict[str, Any] | None: 

282 """The chat command a stored user message ran: under ``command``, or — 

283 stored before 24 October 2026 — the message's whole meta.""" 

284 if not isinstance(meta, dict): 

285 return None 

286 if isinstance(meta.get("command"), dict): 

287 return meta["command"] 

288 if meta.get("line") and meta.get("action"): 

289 return meta 

290 return None