Skip to content

Commit 63ed54c

Browse files
square-tombclaude
andcommitted
fix: read agent cards permissively and share the image fetch limits
Treat the card id as opaque and require only id, name and an https avatarUrl. Drop the version, same-host avatar and effort-needs-model checks. Fetch agent.json through a helper shared with MediaImageProvider: abort after 20 s without a byte or 5 min overall, and cap cards at 2 MB. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Tom Brow <[email protected]>
1 parent 2c08643 commit 63ed54c

7 files changed

Lines changed: 223 additions & 179 deletions

File tree

‎mobile/README.md‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,14 @@ any length while the QR stays small.
5151
}
5252
```
5353

54-
- `v` (1 or 2), `id` (the link's card id), `name` and `avatarUrl` are required.
55-
`instructions`, `model` and `reasoningEffort` are optional and left for the
56-
user when absent; `reasoningEffort` needs `model`. A missing required field,
57-
a known field of the wrong type, or an avatar that isn't an `https` URL on the
58-
same CDN makes the card invalid, and no form opens. Other keys are ignored.
54+
- `id` (the link's card id), `name` and `avatarUrl` (an `https` URL) are
55+
required. `instructions`, `model` and `reasoningEffort` are optional and left
56+
for the user when absent. A missing required field or a known field of the
57+
wrong type makes the card invalid, and no form opens. Other keys, including
58+
`v`, are ignored. The card id is opaque to the app.
59+
- The fetch shares the image loader's limits (`lib/shared/utils/bounded_fetch.dart`):
60+
it is aborted after 20 seconds without a byte or 5 minutes overall, and a card
61+
over 2 MB is rejected.
5962
- `model` and `reasoningEffort` are pre-selected only if the live model catalog
6063
offers them (the effort only for that model).
6164
- The link waits for sign-in and community load. It needs Builderlab login and a
Lines changed: 33 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
import 'dart:async';
21
import 'dart:convert';
3-
import 'dart:typed_data';
42

53
import 'package:hooks_riverpod/hooks_riverpod.dart';
64
import 'package:http/http.dart' as http;
75

86
import '../../shared/deeplink/deep_link.dart';
97
import '../../shared/hosted/hosted_environment.dart';
8+
import '../../shared/utils/bounded_fetch.dart';
109
import 'agent_avatar_picker.dart';
1110

1211
/// Creates the HTTP client that fetches a card's `agent.json`; overridden in
@@ -16,9 +15,7 @@ final agentCardClientProvider = Provider<http.Client Function()>(
1615
);
1716

1817
/// Largest `agent.json` accepted, far above any real card.
19-
const maxAgentCardBytes = 256 * 1024;
20-
21-
const _fetchTimeout = Duration(seconds: 15);
18+
const maxAgentCardBytes = 2 * 1024 * 1024;
2219

2320
/// Why a card's draft could not be loaded, worded for the user.
2421
class AgentCardException implements Exception {
@@ -61,76 +58,64 @@ class AgentCreationDraft {
6158
http.Client client,
6259
) async {
6360
final cdn = HostedEnvironment.avatarsCdnOrigin;
64-
final url = cdn.replace(path: '/${link.cardId}/agent.json');
65-
final http.StreamedResponse response;
66-
final List<int> body;
61+
// The id is opaque; pathSegments percent-encodes anything path-unsafe.
62+
final url = cdn.replace(pathSegments: [link.cardId, 'agent.json']);
63+
final BoundedResponse response;
6764
try {
68-
response = await client
69-
.send(
70-
http.Request('GET', url)
71-
..headers['accept'] = 'application/json'
72-
// A redirect could lead off the CDN; treat it as unavailable.
73-
..followRedirects = false,
74-
)
75-
.timeout(_fetchTimeout);
76-
if (response.statusCode == 403 || response.statusCode == 404) {
77-
throw const AgentCardException('This agent card isn’t available.');
78-
}
79-
if (response.statusCode != 200) {
80-
throw AgentCardException(
81-
'Couldn’t load this agent card (HTTP ${response.statusCode}).',
82-
);
83-
}
84-
if ((response.contentLength ?? 0) > maxAgentCardBytes) {
85-
throw const AgentCardException('This agent card is too large.');
86-
}
87-
body = await _readBounded(response.stream).timeout(_fetchTimeout);
88-
} on AgentCardException {
89-
rethrow;
65+
response = await boundedGet(
66+
client,
67+
url,
68+
maxBytes: maxAgentCardBytes,
69+
headers: const {'accept': 'application/json'},
70+
// A redirect could lead off the CDN; treat it as unavailable.
71+
followRedirects: false,
72+
);
73+
} on ResponseTooLargeException {
74+
throw const AgentCardException('This agent card is too large.');
9075
} on Exception {
9176
throw const AgentCardException(
9277
'Couldn’t load this agent card. Check your connection and reopen the '
9378
'link.',
9479
);
9580
}
81+
if (response.statusCode == 403 || response.statusCode == 404) {
82+
throw const AgentCardException('This agent card isn’t available.');
83+
}
84+
if (response.statusCode != 200) {
85+
throw AgentCardException(
86+
'Couldn’t load this agent card (HTTP ${response.statusCode}).',
87+
);
88+
}
9689
final Object? json;
9790
try {
98-
json = jsonDecode(utf8.decode(body));
91+
json = jsonDecode(utf8.decode(response.bytes));
9992
} on FormatException {
10093
throw const AgentCardException('This agent card is invalid.');
10194
}
10295
if (json is! Map<String, dynamic>) {
10396
throw const AgentCardException('This agent card is invalid.');
10497
}
105-
return parseAgentCard(json, link.cardId, cdn);
98+
return parseAgentCard(json, link.cardId);
10699
}
107100

108-
/// Reads a card's draft from its `agent.json`, validated against the card
109-
/// schema (v1 or v2). `v`, `id` (matching [cardId]), `name` and `avatarUrl`
110-
/// are required; `instructions`, `model` and `reasoningEffort` are optional
111-
/// and left for the user when absent. A required field that is missing, or
112-
/// any known field of the wrong type, makes the card invalid. Other keys are
113-
/// ignored. The avatar must be an https URL on [cdn], the card's own host.
101+
/// Reads a card's draft from its `agent.json`. `id` (matching [cardId]),
102+
/// `name` and `avatarUrl` (an https URL) are required; `instructions`,
103+
/// `model` and `reasoningEffort` are optional and left for the user when
104+
/// absent or blank. A missing required field, or a known field of the wrong
105+
/// type, makes the card invalid. Other keys, including `v`, are ignored.
114106
static AgentCreationDraft parseAgentCard(
115107
Map<String, dynamic> json,
116108
String cardId,
117-
Uri cdn,
118109
) {
119110
const invalid = AgentCardException('This agent card is invalid.');
120-
final version = json['v'];
121-
if (version is! int || (version != 1 && version != 2)) throw invalid;
122111
if (json['id'] != cardId) throw invalid;
123112
final name = json['name'];
124113
final avatarUrl = json['avatarUrl'];
125114
if (name is! String || name.trim().isEmpty || avatarUrl is! String) {
126115
throw invalid;
127116
}
128117
final avatar = Uri.tryParse(avatarUrl);
129-
if (avatar == null ||
130-
avatar.scheme != 'https' ||
131-
avatar.host != cdn.host ||
132-
avatar.hasPort ||
133-
avatar.userInfo.isNotEmpty) {
118+
if (avatar == null || avatar.scheme != 'https' || avatar.host.isEmpty) {
134119
throw invalid;
135120
}
136121
String? optional(String key) {
@@ -140,26 +125,12 @@ class AgentCreationDraft {
140125
return text == null || text.isEmpty ? null : text;
141126
}
142127

143-
final modelId = optional('model');
144-
final reasoningEffort = optional('reasoningEffort');
145-
if (reasoningEffort != null && modelId == null) throw invalid;
146128
return AgentCreationDraft(
147129
name: name.trim(),
148130
instructions: optional('instructions') ?? '',
149131
avatar: AgentAvatarSelection.url(avatarUrl),
150-
modelId: modelId,
151-
reasoningEffort: reasoningEffort,
132+
modelId: optional('model'),
133+
reasoningEffort: optional('reasoningEffort'),
152134
);
153135
}
154-
155-
static Future<List<int>> _readBounded(Stream<List<int>> stream) async {
156-
final bytes = BytesBuilder(copy: false);
157-
await for (final chunk in stream) {
158-
if (bytes.length + chunk.length > maxAgentCardBytes) {
159-
throw const AgentCardException('This agent card is too large.');
160-
}
161-
bytes.add(chunk);
162-
}
163-
return bytes.takeBytes();
164-
}
165136
}

‎mobile/lib/shared/deeplink/agent_creation_link.dart‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ class AgentCreationDeepLink extends BuzzDeepLink {
1111
/// Creates a link for the published card [cardId].
1212
const AgentCreationDeepLink(this.cardId);
1313

14-
/// Published card id, a plain URL-safe token such as `av_…`.
14+
/// Published card id, opaque to the app (today `av_…`).
1515
final String cardId;
1616

1717
@override
@@ -25,8 +25,6 @@ class AgentCreationDeepLink extends BuzzDeepLink {
2525
String toString() => 'AgentCreationDeepLink($cardId)';
2626
}
2727

28-
final _cardId = RegExp(r'^[A-Za-z0-9_-]{1,64}$');
29-
3028
/// Parses `buzz://agent/new?card=<id>`; anything else is not this link.
3129
AgentCreationDeepLink? parseAgentCreationDeepLink(Uri uri) {
3230
if (uri.scheme != 'buzz' ||
@@ -40,6 +38,7 @@ AgentCreationDeepLink? parseAgentCreationDeepLink(Uri uri) {
4038
final params = uri.queryParametersAll;
4139
final card = params['card'];
4240
if (params.length != 1 || card == null || card.length != 1) return null;
43-
if (!_cardId.hasMatch(card.single)) return null;
41+
// The id is opaque, but it becomes one path segment of the card's URL.
42+
if (const {'', '.', '..'}.contains(card.single)) return null;
4443
return AgentCreationDeepLink(card.single);
4544
}

‎mobile/lib/shared/relay/media_image.dart‎

Lines changed: 16 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import 'dart:async';
2-
import 'dart:typed_data';
32
import 'dart:ui' as ui;
43

54
import 'package:flutter/foundation.dart';
@@ -9,6 +8,7 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
98
import 'package:http/http.dart' as http;
109

1110
import '../hosted/hosted_relay_auth.dart';
11+
import '../utils/bounded_fetch.dart';
1212
import 'media_auth.dart';
1313

1414
/// Shared, keep-alive HTTP client for media fetches. One client per container
@@ -71,8 +71,8 @@ class MediaImageProvider extends ImageProvider<MediaImageProvider> {
7171
this.onBytesLoaded,
7272
this.isThumbnailFallback = false,
7373
this.scale = 1.0,
74-
this.stallTimeout = const Duration(seconds: 20),
75-
this.maxFetchDuration = const Duration(minutes: 5),
74+
this.stallTimeout = defaultStallTimeout,
75+
this.maxFetchDuration = defaultMaxFetchDuration,
7676
});
7777

7878
/// Maximum encoded image body retained before decoding (20 MiB).
@@ -185,63 +185,19 @@ class MediaImageProvider extends ImageProvider<MediaImageProvider> {
185185
}
186186

187187
final uri = Uri.parse(url);
188-
final http.Response response;
189-
var wasAbandoned = false;
188+
final BoundedResponse response;
190189
try {
191-
final stop = Completer<void>();
192-
Timer? stall;
193-
void restartStallTimer() {
194-
stall?.cancel();
195-
stall = Timer(stallTimeout, () {
196-
if (!stop.isCompleted) stop.complete();
197-
});
198-
}
199-
200-
restartStallTimer();
201-
final deadline = Timer(maxFetchDuration, () {
202-
if (!stop.isCompleted) stop.complete();
203-
});
204-
unawaited(
205-
abort.then((_) {
206-
if (stop.isCompleted) return;
207-
wasAbandoned = true;
208-
stop.complete();
209-
}),
190+
response = await boundedGet(
191+
client,
192+
uri,
193+
maxBytes: maxResponseBytes,
194+
headers: auth.headersFor(url),
195+
stallTimeout: stallTimeout,
196+
maxFetchDuration: maxFetchDuration,
197+
cancel: abort,
210198
);
211-
StreamIterator<List<int>>? body;
212-
try {
213-
final request = http.AbortableRequest(
214-
'GET',
215-
uri,
216-
abortTrigger: stop.future,
217-
)..headers.addAll(auth.headersFor(url));
218-
final streamed = await client.send(request);
219-
restartStallTimer();
220-
final iterator = body = StreamIterator(streamed.stream);
221-
final bytes = BytesBuilder(copy: false);
222-
// An error body is never shown, and reading a slow one could hold
223-
// this load for the whole fetch cap before the fallback or
224-
// Retry-After applies. Leave it unread; finally cancels the stream.
225-
while (streamed.statusCode == 200 && await iterator.moveNext()) {
226-
restartStallTimer();
227-
final chunk = iterator.current;
228-
if (chunk.length > maxResponseBytes - bytes.length) {
229-
throw const FormatException('Image response too large');
230-
}
231-
bytes.add(chunk);
232-
}
233-
response = http.Response.bytes(
234-
bytes.takeBytes(),
235-
streamed.statusCode,
236-
headers: streamed.headers,
237-
);
238-
} finally {
239-
stall?.cancel();
240-
deadline.cancel();
241-
if (!stop.isCompleted) stop.complete();
242-
unawaited(body?.cancel());
243-
}
244-
} catch (_) {
199+
} catch (error) {
200+
final wasAbandoned = error is FetchCancelledException;
245201
// Nobody wanted the image any more; the URL itself did not fail.
246202
if (!wasAbandoned) {
247203
_cooldownUntil[url] = debugNow().add(_defaultCooldown);
@@ -263,15 +219,15 @@ class MediaImageProvider extends ImageProvider<MediaImageProvider> {
263219
uri: uri,
264220
);
265221
}
266-
final bytes = response.bodyBytes;
222+
final bytes = response.bytes;
267223
if (bytes.isEmpty) {
268224
_cooldownUntil[url] = debugNow().add(_defaultCooldown);
269225
throw NetworkImageLoadException(statusCode: 200, uri: uri);
270226
}
271227
return bytes;
272228
}
273229

274-
Duration _cooldownFor(http.Response response) {
230+
Duration _cooldownFor(BoundedResponse response) {
275231
final retryAfter = int.tryParse(response.headers['retry-after'] ?? '');
276232
if (retryAfter != null && retryAfter > 0) {
277233
final requested = Duration(seconds: retryAfter);

0 commit comments

Comments
 (0)