-
Notifications
You must be signed in to change notification settings - Fork 707
Expand file tree
/
Copy pathuser.ts
More file actions
1731 lines (1511 loc) · 68.6 KB
/
Copy pathuser.ts
File metadata and controls
1731 lines (1511 loc) · 68.6 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { RpcStub } from "capnweb";
import { GadgetMetadataWithTimestamps, AiChatAuthorInfo, AiModelConfig, SUGGESTED_MODELS, CollaboratorRole, ConnectedAccountsSubscriber, ConnectedAccountsFilter, GatekeeperVendorFilter, GadgetMetadata, BlueprintMetadata, BlueprintLibrarySummary, BlueprintSource, BlueprintUserSummary, BLUEPRINT_SCREENSHOT_R2_PREFIX, GatekeeperVendorInfo, BlueprintOutput, OutputSummary, WorkpieceId, ListOutputsResult, AUTH_ERROR_CODES, createAuthError } from '@gadgets/workshop-shared/api';
import { Gatekeeper, GatekeeperUser, GatekeeperUserVerifier, GatekeeperVendor, AccountDescription, VendorDescription, GatekeeperConnectCallback, SupportedResource, ResourceConfiguratorFrame, AppUiContext, GatekeeperUiFrame } from "@gadgets/workshop-shared/gatekeeper";
import { shouldAutoProvisionAccount, ambientGatekeeperMode } from "./provisioning-policy.js";
import { CloudflareGatekeeperUser } from "@gadgets/workshop-shared/cloudflare-gatekeeper";
import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
import { createTypedStorage, collection } from "@gadgets/typed-storage";
import { createWorkshopLogger } from "./observability";
import { getAiGatewayConfig } from "./ai-gateway.js";
import { utcDayKey, nextUtcMidnightIso, DailyQuotaResult } from "./ai-gateway-billing/limits/config.js";
import type { AdminSettings } from "./admin-settings.js";
import { isReservedBlueprintKey, readBlueprintKvRecord } from "./blueprint-archive.js";
import { filterEnabledResources, isResourceDisabled, readAdminConfig } from "./admin-config.js";
import { buildGatekeeperVendorMap } from "./auth/auth-vendors.js";
const logger = createWorkshopLogger("workshop.user");
// How many workspaces one Outputs catch-up pass examines, bounding the Durable Objects a single
// listOutputs() call wakes and how long it waits. The client calls again until catch-up is done.
const OUTPUTS_BACKFILL_PAGE = 16;
type ConnectedAccountRecord = {
id: number;
account: Fetcher<GatekeeperUser>;
description: AccountDescription;
vendorId: string; // Derived from the GATEKEEPER_ binding name (e.g. "google", "email").
credentialExpiresAt?: Date; // When credentials are expected to expire, if known.
credentialsExpired?: boolean; // Set true by async notification from gatekeeper.
// True if the Workshop created this account automatically via GatekeeperVendor.createAccount()
// (no OAuth flow), rather than the user connecting it. Such accounts are protected from manual
// disconnect, since deleting one permanently destroys the user's data in that gatekeeper.
autoProvisioned?: boolean;
};
// Metadata about an auto-provisioned account that provides an agent singleton and/or a management UI.
// Returned to the overseer (ambient capsules / catalog) and the management-UI listing.
export type ProvidedAccountInfo = {
accountId: number;
vendorId: string;
description: AccountDescription; // carries `singleton` / `providesUi` declarations
};
// The singleton/UI methods (createAccount on GatekeeperVendor; getSingletonGatekeeperClass /
// startAppUi on GatekeeperUser) are optional on their interfaces. We don't need to probe whether a
// method is present — we already know from the declaration flags (autoProvisionsAccount /
// description.singleton / .providesUi) that we gated on — but TypeScript still can't call an optional
// method on the mapped stub type directly, so we view the stub through a plain shape that marks the
// needed method required. These are derived from the source interfaces (Pick + Required) rather than
// re-declared, so they can't drift. They are intentionally NOT wrapped in Service/Fetcher: a plain
// shape keeps the methods' declared return types (e.g. createAccount's Fetcher<GatekeeperUser>)
// usable directly, the way the runtime stub actually behaves.
type AccountCreatorStub = Required<Pick<GatekeeperVendor, "createAccount">>;
type SingletonAccountStub = Required<Pick<GatekeeperUser, "getSingletonGatekeeperClass" | "startAppUi">>;
function areCredentialsValid(record: ConnectedAccountRecord): boolean {
if (record.credentialsExpired) return false;
if (record.credentialExpiresAt && record.credentialExpiresAt.valueOf() < Date.now()) return false;
return true;
}
// Vendor id of the Cloudflare gatekeeper (the suffix of GATEKEEPER_CLOUDFLARE, lowercased). The AI
// Gateway billing flow is Cloudflare-specific, so several places key off this literal.
export const CLOUDFLARE_VENDOR_ID = "cloudflare";
export type UserAiModelRecord = {
profile: AiChatAuthorInfo;
config: AiModelConfig;
}
export type UserChatContext = {
profile: AiChatAuthorInfo;
aiModel?: UserAiModelRecord;
quickModel?: AiModelConfig;
}
type LoginSessionRecord = {
tokenId: string, // sha256 hash of token, hex-formatted
created: Date,
}
// Blueprint record stored in the user's `blueprints` collection.
type BlueprintUserRecord = {
id: string;
metadata: BlueprintMetadata;
gadgetId?: string;
// Source of truth for whether the blueprint is featured deployment-wide.
featured?: boolean;
};
type LibraryBlueprintRecord = {
id: string;
metadata: BlueprintMetadata;
addedAt: Date;
uploaded: boolean;
};
type GadgetRecord = GadgetMetadata & {
created: Date;
lastActive?: Date; // if missing, gadget is provisional
// If we're not the gadget owner (it was shared with us), `owner` is set (inherited from
// GadgetMetadata).
};
function isFullyCreated(g: GadgetRecord): g is GadgetMetadataWithTimestamps {
return g.lastActive !== undefined;
}
// One output of a workspace, as pushed into a user's output index by the Overseer that owns it
// (see `syncWorkspaceOutputs()`). Carries only what the workspace itself knows: its title,
// activity time and ownership are joined in from the `gadgets` collection on read, so they can't
// go stale here.
export type WorkspaceOutputEntry = {
workpieceId: WorkpieceId;
title: string;
created: Date;
// The format the gadget was built as, if it was instantiated from a blueprint declaring one.
output?: BlueprintOutput;
};
type OutputRecord = WorkspaceOutputEntry & {
// The workspace containing this output (an Overseer DO id).
workspaceId: string;
};
// AI Gateway billing state for the optional top-up flow: which Cloudflare account to bill and a
// cached credit balance. The OAuth tokens themselves live in the connected Cloudflare *gatekeeper*
// account (vendorId "cloudflare"); billing reads a usable token from there via getUsableAccessToken.
type CloudflareBilling = {
// Selected account, once chosen (auto-selected when the grant sees exactly one).
accountId?: string;
accountName?: string;
// Cached credit balance (USD) and when it was last fetched (unix ms).
creditsRemaining?: number | null;
creditsUpdatedAt?: number;
};
function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
if (a.length != b.length) {
return false;
}
let result = 0;
for (let i = 0; i < a.length; i++) {
result |= a[i] ^ b[i];
}
return result === 0;
}
function makeUserStorage(storage: DurableObjectStorage) {
return createTypedStorage(storage, {
collections: {
aiModels: collection<UserAiModelRecord>()({
primaryKey: record => record.profile.id,
}),
gadgets: collection<GadgetRecord>()({
primaryKey: "id"
}),
connectedAccounts: collection<ConnectedAccountRecord>()({
primaryKey: "id"
}),
sessions: collection<LoginSessionRecord>()({
primaryKey: "tokenId",
}),
blueprints: collection<BlueprintUserRecord>()({
primaryKey: "id",
}),
libraryBlueprints: collection<LibraryBlueprintRecord>()({
primaryKey: "id",
}),
// Outputs of every workspace in `gadgets`, mirrored here by each workspace's Overseer so the
// Outputs page is one cheap read of the user's own DO. Entries are meaningful only while the
// corresponding `gadgets` record exists; `syncWorkspaceOutputs()` and the `gadgets` deletion
// paths keep the two in step.
outputs: collection<OutputRecord>()({
primaryKey: record => `${record.workspaceId}:${record.workpieceId}`,
nonUniqueIndexes: {
byWorkspace(record: OutputRecord) { return record.workspaceId; },
},
}),
},
singletons: {
// AI Gateway billing state (selected account + cached balance) for the optional top-up flow;
// null until a Cloudflare account is connected and resolved.
cloudflareBilling: <CloudflareBilling | null>null,
created: false,
profile: <AiChatAuthorInfo>{
type: "user",
name: "User",
id: "user@example.com",
},
quickModel: <string | null>null,
preferredModel: <string | null>null,
onboardingCompleted: false,
// Set once the user's pre-existing workspaces have been asked to populate the outputs index
// (see #backfillOutputs()). Workspaces created since push on their own.
outputsBackfilled: false,
// How far that catch-up has got: the last workspace id examined. The sweep runs a page at a
// time and resumes here on the next visit.
outputsBackfillCursor: "",
nextAccountId: 0,
pinnedBlueprints: <string[]>[],
// Per-user free-tier daily LLM-call counter (only used when ENABLE_CLOUDFLARE_LIMITS is on).
// Stores the current UTC day and the calls made that day; a stale `day` implicitly resets the
// count. Folds the former standalone RateLimitDO into the user object.
dailyLlmCount: <{ day: string; count: number } | null>null,
// `passwordHash` value as passed to `login()`, but with an extra round of SHA-256 applied.
//
// null = password disabled (e.g. because some other auth mechanism is used)
passwordHashHash: <Uint8Array | null>null,
}
});
}
type UserStorage = ReturnType<typeof makeUserStorage>;
function unavailableGatekeeperVendorInfo(id: string): GatekeeperVendorInfo {
return {
id,
unavailable: true,
description: {
displayName: id,
url: "",
tagline: "Temporarily unavailable",
description: "This gatekeeper could not be loaded.",
},
supportedResources: [],
};
}
async function checkGatekeeperVendorFilter(
vendor: Service<GatekeeperVendor> | Service<GatekeeperUser>,
vendorId: string,
filter: GatekeeperVendorFilter): Promise<boolean> {
try {
if (filter.resourceUrl) {
let resources = await vendor.getSupportedResources();
let matched = false;
for (let resource of resources) {
if (typeof resource.urlPattern !== "string") {
// Guard against gatekeepers returning a non-string urlPattern for now.
//
// TODO: Consider whether this is the API we want for getSupportedResources(). Is URLPattern
// even the right thing?
throw new Error("Gatekeeper returned non-string urlPattern from getSupportedResources()");
}
if (new URLPattern(resource.urlPattern).test(filter.resourceUrl)) {
matched = true;
break;
}
}
if (!matched) return false;
}
return true;
} catch (err) {
// This function is called when iterating over several gatekeepers to filter them. If one of
// them throws we don't want to block the whole list, so instead log the error and assume this
// gatekeeper should be filtered.
logger.warn("gatekeeper filter check failed", {
event: "gatekeeper.filter.check.failed", vendorId, error: err,
});
return false;
}
}
// Durable Object that stores information about a user.
export class UserDurableObject extends DurableObject<Cloudflare.Env> {
private storage: UserStorage;
private vendors: Map<string, Service<GatekeeperVendor>>;
private adminSettings: DurableObjectNamespace<AdminSettings>;
constructor(ctx: DurableObjectState, env: Cloudflare.Env) {
super(ctx, env);
// Migrate data created prior to the minions -> gadgets rename.
// TODO(cleanup): Eventually remove this, very few people ever used it as "minions".
for (let [key, value] of Array.from(ctx.storage.kv.list({prefix: "minions:"}))) {
let newKey = "gadgets:" + key.slice("minions:".length);
ctx.storage.kv.put(newKey, value);
ctx.storage.kv.delete(key);
}
this.storage = makeUserStorage(ctx.storage);
this.adminSettings = this.ctx.exports.AdminSettings;
this.vendors = buildGatekeeperVendorMap(env);
}
async authenticate(token: string): Promise<void> {
let tokenBytes: Uint8Array;
try {
tokenBytes = Uint8Array.fromBase64(token);
} catch {
// A corrupt (non-Base64) token must classify as an auth failure like any other bad token,
// not surface as the decoder's SyntaxError.
throw createAuthError(AUTH_ERROR_CODES.invalidSessionToken);
}
let hash = await crypto.subtle.digest('SHA-256', tokenBytes);
let tokenId = new Uint8Array(hash).toHex();
let session = this.storage.sessions.get(tokenId);
if (!session) {
throw createAuthError(AUTH_ERROR_CODES.invalidSessionToken);
}
}
// Returns true when this login created the account on first use. When the account doesn't yet
// exist and `allowCreate` is false (deployment signups are closed), refuses rather than creating —
// existing users can still sign in.
async authenticateFromCfAccess(email: string, allowCreate: boolean): Promise<boolean> {
if (!this.storage.created.get()) {
if (!allowCreate) {
throw new Error("New sign-ups are currently disabled on this deployment.");
}
// Create on first use.
this.storage.created.put(true);
this.storage.profile.put({
type: "user",
name: email.split("@")[0],
id: email,
});
return true;
}
return false;
}
async #newSessionToken(): Promise<string> {
let sessionToken = new Uint8Array(32);
crypto.getRandomValues(sessionToken);
let tokenId = new Uint8Array(await crypto.subtle.digest('SHA-256', sessionToken)).toHex();
this.storage.sessions.put({ tokenId, created: new Date() });
return sessionToken.toBase64();
}
async login(passwordHash: Uint8Array): Promise<string | null> {
let passwordHashHash = new Uint8Array(await crypto.subtle.digest('SHA-256', passwordHash));
let actualHashHash = this.storage.passwordHashHash.get();
if (!actualHashHash) {
return null;
}
if (!bytesEqual(passwordHashHash, actualHashHash)) {
return null;
}
return this.#newSessionToken();
}
async createAccount(username: string, displayName: string, passwordHash: Uint8Array)
: Promise<string | null> {
if (this.storage.created.get()) {
return null;
}
// Do a little migration here for old data.
// TODO(soon): Delete this.
for (let gadget of Array.from(this.storage.gadgets.list())) {
if (!gadget.created || !gadget.lastActive) {
if (!gadget.created) {
gadget.created = new Date("2026-01-01");
}
if (!gadget.lastActive) {
gadget.lastActive = new Date("2026-01-01");;
}
this.storage.gadgets.put(gadget);
}
}
this.storage.created.put(true);
this.storage.profile.put({
type: "user",
name: displayName,
id: username,
});
let passwordHashHash = new Uint8Array(await crypto.subtle.digest('SHA-256', passwordHash));
this.storage.passwordHashHash.put(passwordHashHash);
return this.#newSessionToken();
}
// Log in via an authentication gatekeeper, creating the account on first use. The user DO is keyed
// by the verified email (this DO's id derives from idFromName(email)), so `email` is also used as
// the profile id and the initial display name is the email's local-part — consistent with the
// Cloudflare Access flow. Password login is left disabled for these accounts. Returns the session
// secret to store client-side.
//
// The profile is written only on first sign-in. We intentionally do NOT refresh the display name
// on later logins: once set, the name is the user's to change (via setOwnDisplayName), so we don't
// clobber a customized name with the email local-part.
//
// When the account doesn't yet exist and `allowCreate` is false (deployment signups are closed),
// returns null instead of creating one — existing users can still sign in.
async loginOrCreateViaGatekeeper(email: string, allowCreate: boolean): Promise<string | null> {
if (!this.storage.created.get()) {
if (!allowCreate) return null;
this.storage.created.put(true);
this.storage.profile.put({
type: "user",
name: email.split("@")[0],
id: email,
});
}
return this.#newSessionToken();
}
// Whether this account has a password set (false for gatekeeper sign-in accounts).
async hasPasswordLogin(): Promise<boolean> {
return this.storage.passwordHashHash.get() !== null;
}
async changePassword(oldHash: Uint8Array, newHash: Uint8Array): Promise<void> {
let actualHashHash = this.storage.passwordHashHash.get();
if (!actualHashHash) {
throw new Error("This account does not use password login.");
}
let oldHashHash = new Uint8Array(await crypto.subtle.digest('SHA-256', oldHash));
if (!bytesEqual(oldHashHash, actualHashHash)) {
throw new Error("Incorrect password.");
}
let newHashHash = new Uint8Array(await crypto.subtle.digest('SHA-256', newHash));
this.storage.passwordHashHash.put(newHashHash);
}
async whoami(): Promise<AiChatAuthorInfo> {
return this.storage.profile.get();
}
// Like whoami(), but returns null if the account was never initialized.
async whoamiIfExists(): Promise<AiChatAuthorInfo | null> {
if (!this.storage.created.get()) {
return null;
}
return this.storage.profile.get();
}
// Called by the overseer every time a collaborator opens a shared gadget.
// Creates the record on first open; updates lastActive on subsequent opens.
//
// `role` is cached so listings built from this DO can offer the actions it permits without
// reopening the workspace to ask. Presentation only: every operation is still authorized by the
// Overseer when attempted.
async recordSharedGadgetOpen(
gadgetId: string, title: string, ownerProfile: AiChatAuthorInfo, role?: CollaboratorRole
): Promise<void> {
let record = this.storage.gadgets.get(gadgetId);
if (record && !record.owner) {
throw new Error("User owns this workspace; it's not shared with them.");
}
let now = new Date();
if (record) {
// Already tracked -- update lastActive and cached fields.
record.lastActive = now;
record.title = title;
record.owner = ownerProfile;
record.role = role;
this.storage.gadgets.put(record);
} else {
// First time opening this shared gadget.
this.storage.gadgets.put({
id: gadgetId,
title,
owner: ownerProfile,
role,
created: now,
lastActive: now,
});
}
}
// Updates the presentation-only role cached for a shared workspace listing. Authorization still
// comes from the Overseer's live sharing graph; this only keeps the listing's available actions
// accurate after a collaborator is downgraded.
async updateSharedGadgetRole(gadgetId: string, role: CollaboratorRole): Promise<void> {
let record = this.storage.gadgets.get(gadgetId);
if (!record?.owner) return;
record.role = role;
this.storage.gadgets.put(record);
}
// Forgets a gadget shared with this user: drops it from their workspace listing and its outputs
// from their Outputs index. Called both when the user dismisses it and when their access is
// revoked (Overseer.refreshAffectedCollaboratorListings()); it grants and revokes nothing.
async forgetSharedGadget(gadgetId: string): Promise<void> {
let record = this.storage.gadgets.get(gadgetId);
if (record && record.owner) {
this.storage.gadgets.delete(gadgetId);
this.storage.outputs.byWorkspace.delete(gadgetId);
}
}
async setOwnDisplayName(name: string): Promise<void> {
let profile = this.storage.profile.get();
profile.name = name;
this.storage.profile.put(profile);
}
async listModels(): Promise<AiChatAuthorInfo[]> {
let result: AiChatAuthorInfo[] = [];
// When AI Gateway mode is active, include all suggested models for enabled providers.
let gwConfig = getAiGatewayConfig(this.env);
let gwModelIds = new Set<string>();
if (gwConfig) {
for (let entry of gwConfig.getModelList()) {
result.push(entry);
gwModelIds.add(entry.id);
}
}
// Also include user-configured models, skipping any that duplicate a gateway model.
for (let model of this.storage.aiModels.list()) {
if (!gwModelIds.has(model.profile.id)) {
result.push(model.profile);
}
}
return result;
}
async addModel(profile: AiChatAuthorInfo, config: AiModelConfig): Promise<void> {
let gwConfig = getAiGatewayConfig(this.env);
if (gwConfig && !gwConfig.providers.has(config.provider)) {
throw new Error(`Provider "${config.provider}" is not available in AI Gateway mode.`);
}
profile.type = "agent";
this.storage.aiModels.put({profile, config});
}
async deleteModel(id: string): Promise<void> {
// In AI Gateway mode, don't allow deleting built-in suggested models.
let gwConfig = getAiGatewayConfig(this.env);
if (gwConfig) {
for (let [provider, models] of Object.entries(SUGGESTED_MODELS)) {
if (gwConfig.providers.has(provider) && id in models) {
throw new Error(`Cannot delete built-in model "${models[id].name}".`);
}
}
}
this.storage.aiModels.delete(id);
}
async setQuickModel(id: string | null): Promise<void> {
this.storage.quickModel.put(id);
}
async getQuickModel(): Promise<null | string> {
let result = this.storage.quickModel.get();
if (result && this.storage.aiModels.get(result)) {
return result;
} else {
return null;
}
}
async getPreferredModel(): Promise<string | null> {
return this.storage.preferredModel.get();
}
async setPreferredModel(id: string | null): Promise<void> {
if (id !== null) {
// Validate that the model exists in the user's configured models or as a gateway model.
let gwConfig = getAiGatewayConfig(this.env);
let exists = !!this.storage.aiModels.get(id) || !!gwConfig?.resolveModel(id);
if (!exists) {
throw new Error(`No such model: ${id}`);
}
}
this.storage.preferredModel.put(id);
}
async isOnboardingCompleted(): Promise<boolean> {
return this.storage.onboardingCompleted.get();
}
async completeOnboarding(): Promise<void> {
this.storage.onboardingCompleted.put(true);
}
// ---------------------------------------------------------------------------------------------
// Cloudflare account connection (optional top-up flow).
// ---------------------------------------------------------------------------------------------
// Return the connected Cloudflare *gatekeeper* account stub, if any. The AI Gateway billing flow
// narrows it to CloudflareGatekeeperUser to obtain a usable access token. Null if the user hasn't
// connected (or signed in with) Cloudflare.
async getCloudflareGatekeeperAccount(): Promise<Fetcher<CloudflareGatekeeperUser> | null> {
let nextAccountId = this.storage.nextAccountId.get();
for (let id = 0; id < nextAccountId; id++) {
let rec: ConnectedAccountRecord | undefined;
try { rec = this.storage.connectedAccounts.get(id); } catch { continue; }
if (rec && rec.vendorId === CLOUDFLARE_VENDOR_ID) {
return rec.account as unknown as Fetcher<CloudflareGatekeeperUser>;
}
}
return null;
}
// The AI Gateway billing state (selected account + cached balance), or null if unset.
async getCloudflareBilling(): Promise<CloudflareBilling | null> {
return this.storage.cloudflareBilling.get();
}
// Update the cached credit balance for the billed account.
async updateCloudflareCredits(creditsRemaining: number | null): Promise<void> {
let record = this.storage.cloudflareBilling.get() ?? {};
record.creditsRemaining = creditsRemaining;
record.creditsUpdatedAt = Date.now();
this.storage.cloudflareBilling.put(record);
}
// Persist which Cloudflare account to bill. Clears the cached credit balance (it belonged to the
// old account).
async setCloudflareAccountSelection(accountId: string, accountName?: string): Promise<void> {
let record = this.storage.cloudflareBilling.get() ?? {};
record.accountId = accountId;
record.accountName = accountName;
record.creditsRemaining = undefined;
record.creditsUpdatedAt = undefined;
this.storage.cloudflareBilling.put(record);
}
// ---------------------------------------------------------------------------------------------
// Free-tier daily LLM-call counter (folded in from the former standalone RateLimitDO). Only used
// when ENABLE_CLOUDFLARE_LIMITS is on. Single-threaded DO execution makes the read-modify-write
// race-free; the window resets at UTC midnight when the stored day no longer matches.
// ---------------------------------------------------------------------------------------------
#dailyUsed(day: string): number {
let record = this.storage.dailyLlmCount.get();
return record && record.day === day ? record.count : 0;
}
// Read the current daily quota state without counting a call.
async checkDailyLlmCount(limit: number): Promise<DailyQuotaResult> {
let day = utcDayKey();
let used = this.#dailyUsed(day);
return { withinLimits: used < limit, remaining: Math.max(0, limit - used), limit, used,
resetAt: nextUtcMidnightIso() };
}
// Atomically check the daily limit and, if within it, count one call. `withinLimits` is the
// pre-count decision; `used`/`remaining` reflect the state AFTER counting. No-ops once exhausted,
// so a blocked request never counts.
async consumeDailyLlmCall(limit: number): Promise<DailyQuotaResult> {
let day = utcDayKey();
let used = this.#dailyUsed(day);
if (used >= limit) {
return { withinLimits: false, remaining: 0, limit, used, resetAt: nextUtcMidnightIso() };
}
let newUsed = used + 1;
this.storage.dailyLlmCount.put({ day, count: newUsed });
return { withinLimits: true, remaining: Math.max(0, limit - newUsed), limit, used: newUsed,
resetAt: nextUtcMidnightIso() };
}
// DO NOT MAKE PUBLIC -- returns API keys.
async getChatContext(modelId: string | null): Promise<UserChatContext> {
let gwConfig = getAiGatewayConfig(this.env);
let result: UserChatContext = {
profile: this.storage.profile.get()
};
if (modelId) {
// In AI Gateway mode, resolve gateway models first.
if (gwConfig) {
result.aiModel = gwConfig.resolveModel(modelId);
}
if (!result.aiModel) {
result.aiModel = this.storage.aiModels.get(modelId);
}
if (!result.aiModel) throw new Error(`No such model: ${modelId}`);
}
// Resolve the quick model (used for lightweight tasks like title generation).
if (gwConfig) {
// In AI Gateway mode, always use the hardcoded quick model.
result.quickModel = gwConfig.getQuickModelConfig();
} else {
let quickModelId = this.storage.quickModel.get();
if (quickModelId) {
let quickModel = this.storage.aiModels.get(quickModelId);
if (quickModel) {
result.quickModel = quickModel.config;
}
}
}
return result;
}
async getExternalMessageChatContext(existingChatModelId: string | null): Promise<UserChatContext> {
let models = await this.listModels();
// Prefer the existing chat's model, then the user's preferred model, then the first available model.
let selectedModel = models.find(model => model.id === existingChatModelId)
?? models.find(model => model.id === this.storage.preferredModel.get())
?? models[0];
return this.getChatContext(selectedModel?.id ?? null);
}
async listGadgets(): Promise<GadgetMetadataWithTimestamps[]> {
let result: GadgetMetadataWithTimestamps[] = [];
for (let gadget of this.storage.gadgets.list()) {
if (isFullyCreated(gadget)) {
result.push(gadget);
}
}
return result;
}
async updateTitle(gadgetId: string, title: string) {
let record = this.storage.gadgets.get(gadgetId);
if (!record) {
throw new Error("No such workspace belonging to user.");
}
record.title = title;
this.storage.gadgets.put(record);
}
async updatePinned(gadgetId: string, pinned: boolean) {
let record = this.storage.gadgets.get(gadgetId);
if (!record) {
throw new Error("No such workspace belonging to user.");
}
record.pinned = pinned;
this.storage.gadgets.put(record);
}
async getGadget(id: string): Promise<GadgetMetadata | null> {
return this.storage.gadgets.get(id) || null;
}
async newGadget(id: string, title: string): Promise<void> {
let created = new Date();
this.storage.gadgets.put({id, title, created});
}
async ensureGadgetRegistered(id: string, title: string): Promise<void> {
if (this.storage.gadgets.get(id)) return;
await this.newGadget(id, title);
}
async setGadgetLastActive(id: string, time: Date, totalCost: number | undefined): Promise<void> {
let gadget = this.storage.gadgets.get(id);
if (gadget) {
gadget.lastActive = time;
if (totalCost) {
gadget.totalCost = totalCost;
}
this.storage.gadgets.put(gadget);
}
}
async deleteGadget(id: string): Promise<void> {
this.storage.gadgets.delete(id);
this.storage.outputs.byWorkspace.delete(id);
}
// Replace the set of outputs recorded for one workspace. Called by that workspace's Overseer
// whenever its gadget registry changes and whenever it is opened.
//
// A workspace the user no longer tracks (deleted, or a shared one they dismissed) has its
// entries dropped.
syncWorkspaceOutputs(workspaceId: string, entries: WorkspaceOutputEntry[]): void {
this.storage.outputs.byWorkspace.delete(workspaceId);
if (!this.storage.gadgets.get(workspaceId)) return;
for (let entry of entries) {
this.storage.outputs.put({...entry, workspaceId});
}
}
async listOutputs(): Promise<ListOutputsResult> {
let catchingUp = await this.#backfillOutputs();
return {outputs: this.#readOutputs(), catchingUp};
}
// Ask the user's pre-existing workspaces to populate the outputs index, once. Workspaces push as
// they change and when opened, so only those predating the index need this.
//
// Sweeps one bounded page and reports whether more remains, rather than sweeping everything: a
// first Outputs load must not wait on every workspace the user has ever created. The caller
// drains the rest, so the list fills in while the page is open.
async #backfillOutputs(): Promise<boolean> {
if (this.storage.outputsBackfilled.get()) return false;
let startAfter = this.storage.outputsBackfillCursor.get() || undefined;
let cursor = startAfter ?? "";
let targets: string[] = [];
let examined = 0;
for (let gadget of this.storage.gadgets.list({startAfter, limit: OUTPUTS_BACKFILL_PAGE})) {
++examined;
cursor = gadget.id;
// A shared workspace is mirrored on open, not swept; a half-created one has nothing yet.
if (!gadget.owner && isFullyCreated(gadget)) targets.push(gadget.id);
}
let done = examined < OUTPUTS_BACKFILL_PAGE;
let ownerId = this.ctx.id.toString();
let overseers = this.ctx.exports.OverseerDurableObject;
let results = await Promise.allSettled(targets.map(id =>
overseers.get(overseers.idFromString(id)).getOutputsForOwnerBackfill(ownerId)));
let failureCount = 0;
let firstError: unknown;
for (let [index, result] of results.entries()) {
if (result.status === "fulfilled") {
if (result.value) this.syncWorkspaceOutputs(targets[index], result.value);
} else {
if (failureCount === 0) firstError = result.reason;
++failureCount;
}
}
if (failureCount > 0) {
logger.warn("failed to backfill outputs for some workspaces", {
event: "outputs.backfill.partial",
failureCount,
error: firstError,
});
}
// Advance past workspaces that failed, rather than retrying them. The index is self-healing,
// so one missed here reappears the moment it is touched, whereas holding the cursor lets a
// single unwakeable workspace stall the sweep forever.
if (done) {
this.storage.outputsBackfilled.put(true);
} else {
this.storage.outputsBackfillCursor.put(cursor);
}
// A page where everything failed looks systemic, so stop draining and let the next visit pick
// up from the next page: draining on would be a burst of doomed calls during an outage.
if (failureCount > 0 && failureCount === targets.length) return false;
return !done;
}
#readOutputs(): OutputSummary[] {
let result: OutputSummary[] = [];
for (let output of this.storage.outputs.list()) {
let workspace = this.storage.gadgets.get(output.workspaceId);
if (!workspace || !isFullyCreated(workspace)) continue;
result.push({
workspaceId: output.workspaceId,
workpieceId: output.workpieceId,
...(output.output ? {output: output.output} : {}),
title: output.title,
workspaceTitle: workspace.title,
created: output.created,
lastActive: workspace.lastActive,
...(workspace.owner ? {owner: workspace.owner} : {}),
...(workspace.role ? {role: workspace.role} : {}),
});
}
result.sort((a, b) => b.lastActive.getTime() - a.lastActive.getTime());
return result;
}
// --- Blueprint methods (called by Overseer during propagation) ---
async updateBlueprint(id: string, metadata: BlueprintMetadata, gadgetId: string): Promise<boolean> {
let existing = this.storage.blueprints.get(id);
// Preserve the featured bit across metadata-only/code updates.
let featured = existing?.featured === true;
this.storage.blueprints.put({id, metadata, gadgetId, featured});
return featured;
}
async importBlueprint(id: string, metadata: BlueprintMetadata): Promise<void> {
this.storage.libraryBlueprints.put({
id,
metadata,
addedAt: new Date(),
uploaded: true,
});
}
async deleteBlueprint(id: string): Promise<void> {
this.storage.blueprints.delete(id);
this.storage.pinnedBlueprints.put(
this.storage.pinnedBlueprints.get().filter(existing => existing !== id));
}
isBlueprintPinned(id: string): boolean {
return this.storage.pinnedBlueprints.get().includes(id);
}
async setBlueprintPinned(id: string, pinned: boolean): Promise<void> {
let pinnedBlueprints = this.storage.pinnedBlueprints.get().filter(existing => existing !== id);
if (pinned) {
if (!this.storage.blueprints.get(id) && !this.storage.libraryBlueprints.get(id)) {
await this.addBlueprintToLibrary(id);
}
pinnedBlueprints.unshift(id);
}
this.storage.pinnedBlueprints.put(pinnedBlueprints);
}
async addBlueprintToLibrary(id: string): Promise<void> {
let kvRecord = await readBlueprintKvRecord(this.env, id);
if (!kvRecord) {
throw new Error("Blueprint not found.");
}
let existing = this.storage.libraryBlueprints.get(id);
if (existing) {
existing.metadata = kvRecord.metadata;
this.storage.libraryBlueprints.put(existing);
return;
}
this.storage.libraryBlueprints.put({
id,
metadata: kvRecord.metadata,
addedAt: new Date(),
uploaded: false,
});
}
async removeBlueprintFromLibrary(id: string): Promise<void> {
let record = this.storage.libraryBlueprints.get(id);
if (!record) {
return;
}
if (record.uploaded) {
await this.deleteOwnedBlueprint(id);
} else {
this.storage.libraryBlueprints.delete(id);
await this.setBlueprintPinned(id, false);
}
}
async isBlueprintInLibrary(id: string): Promise<{ uploaded: boolean } | null> {
const record = this.storage.libraryBlueprints.get(id);
if (!record) return null;
return { uploaded: record.uploaded };
}
async deleteOwnedBlueprint(id: string): Promise<void> {
if (isReservedBlueprintKey(id)) {
throw new Error("Blueprint not found.");
}
let publishedRecord = this.storage.blueprints.get(id);
let libraryRecord = this.storage.libraryBlueprints.get(id);
let uploadedRecord = libraryRecord?.uploaded ? libraryRecord : undefined;
let kvRecord = await readBlueprintKvRecord(this.env, id);
if (!publishedRecord && !uploadedRecord && !kvRecord) {
throw new Error("Blueprint not found.");
}
if (kvRecord) {
if (kvRecord.ownerId !== this.ctx.id.toString()) {
throw new Error("You don't own this blueprint.");
}
// Delete all R2 objects with the blueprint ID prefix.
for (let v = 1; v <= kvRecord.metadata.version; v++) {
await this.env.BLUEPRINT_CONTENT.delete(`${id}/${v}`);
}
await this.env.BLUEPRINT_CONTENT.delete(`${BLUEPRINT_SCREENSHOT_R2_PREFIX}${id}`);
// Delete from KV.
await this.env.BLUEPRINTS.delete(id);
}
if (publishedRecord?.featured === true) {
await this.adminSettings.getByName("").deleteFeaturedBlueprint(id);
}
if (publishedRecord) {
this.storage.blueprints.delete(id);
}
if (uploadedRecord) {
this.storage.libraryBlueprints.delete(id);
}
await this.setBlueprintPinned(id, false);
}
async isBlueprintFeatured(id: string): Promise<boolean | null> {
let record = this.storage.blueprints.get(id);
if (!record) {