deepspace 0.13.0 → 0.15.0

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.
package/dist/worker.d.ts CHANGED
@@ -2550,6 +2550,9 @@ declare function getMessageType(data: Uint8Array): number;
2550
2550
 
2551
2551
  /** First source migration required by the canonical app identity cutover. */
2552
2552
  declare const CANONICAL_APP_IDENTITY_MIGRATION_ID = "2026-08-canonical-app-identity-wire";
2553
+ /** Asset-layer misses became real 404s, and the worker owns the fallback. The
2554
+ * config and the worker's fallback path have to move together. */
2555
+ declare const WORKER_OWNED_NOT_FOUND_MIGRATION_ID = "2026-08-worker-owned-not-found";
2553
2556
  type AppMigrationIdsValidation = {
2554
2557
  valid: true;
2555
2558
  ids: string[];
@@ -2736,6 +2739,82 @@ interface ResolvedDeepSpaceAgentModel {
2736
2739
  }
2737
2740
  declare function resolveDeepSpaceAgentModel(modelId: unknown, profileId?: DeepSpaceAgentProfileId): ResolvedDeepSpaceAgentModel | null;
2738
2741
 
2742
+ /**
2743
+ * Routing decisions the deploy worker, the CLI, and the scaffold all depend
2744
+ * on. One home so they cannot drift — see docs/platform/app-platform-contract.md
2745
+ * for why this boundary needs one.
2746
+ */
2747
+ /** Where every release serves its own identity. The deploy worker injects this
2748
+ * asset; the CLI polls it to learn which release an edge is serving. */
2749
+ declare const RELEASE_STAMP_PATH = "/.well-known/deepspace/release.json";
2750
+ /**
2751
+ * What the asset layer does with a path it has no file for — Cloudflare's own
2752
+ * `not_found_handling`, restated here because both ends of a deploy have to
2753
+ * agree on the legal values.
2754
+ *
2755
+ * The app declares this and the platform honors it. It is the app's to declare
2756
+ * because it is half of a decision whose other half lives in the app's worker:
2757
+ * `none` sends misses to the worker, which is the only place that can tell a
2758
+ * client route from a missing file, and a worker written for one setting
2759
+ * misbehaves under the other. Overriding it from here would silently rewrite
2760
+ * the behavior of code the platform did not write — see
2761
+ * docs/platform/app-platform-contract.md.
2762
+ */
2763
+ declare const ASSET_NOT_FOUND_HANDLING_VALUES: readonly ["none", "single-page-application", "404-page"];
2764
+ type AssetNotFoundHandling = (typeof ASSET_NOT_FOUND_HANDLING_VALUES)[number];
2765
+ /**
2766
+ * Applied when a deploy declares nothing.
2767
+ *
2768
+ * This is NOT Cloudflare's default (`none`) and not the value new apps ship.
2769
+ * It is what the platform hardcoded for every app before it started honoring
2770
+ * the declaration, and a deploy carrying no declaration is a CLI too old to
2771
+ * send one — necessarily paired with an app written for the old behavior.
2772
+ * Anything else here breaks every app whose CLI has not been upgraded, which
2773
+ * is the failure Rule 1 exists to prevent.
2774
+ */
2775
+ declare const UNDECLARED_ASSET_NOT_FOUND_HANDLING: AssetNotFoundHandling;
2776
+ declare function isAssetNotFoundHandling(value: unknown): value is AssetNotFoundHandling;
2777
+ /** Stated, not inherited from the compatibility date: from 2025-04-01 the
2778
+ * default sends navigations to the asset layer, which under
2779
+ * `not_found_handling: "none"` would 404 every client route before the
2780
+ * worker sees it. Required for every app, whatever it declares above. */
2781
+ declare const REQUIRED_COMPATIBILITY_FLAGS: readonly ["nodejs_compat", "assets_navigation_has_no_effect"];
2782
+ /** Required flags plus whatever the app added that does not contradict them. */
2783
+ declare function resolveCompatibilityFlags(declared: readonly string[] | undefined): string[];
2784
+ /** Routes Cloudflare hands to the worker before the asset layer answers. The
2785
+ * agent paths are here so an app publishing nothing there 404s instead of
2786
+ * returning its homepage. */
2787
+ declare const SDK_RUN_WORKER_FIRST: readonly ["/api/*", "/ws/*", "/internal/*", "/v1/*", "/_deepspace/*", "/llms.txt", "/llms-full.txt", "/.well-known/mcp", "/.well-known/mcp.json", "/.well-known/mcp/*"];
2788
+ /** Deny-list for an app's own `run_worker_first`. Strictly wider than what the
2789
+ * platform routes worker-first; expressing it as a superset keeps the
2790
+ * difference deliberate. */
2791
+ declare const RESERVED_RUN_WORKER_FIRST: readonly string[];
2792
+ /**
2793
+ * Whether the platform owns this path — so an app's worker must answer 404
2794
+ * rather than its shell when nothing is published there. Exported as a
2795
+ * predicate, not a list, because the patterns carry globs and every caller
2796
+ * matching them by hand is another copy that can drift.
2797
+ */
2798
+ declare function isPlatformReservedPath(pathname: string): boolean;
2799
+
2800
+ /**
2801
+ * The platform endpoints this SDK's client hooks call through an app's proxy.
2802
+ *
2803
+ * The app's worker forwards these with its own identity, so the proxy is an
2804
+ * allow-list rather than a passthrough. That list has to match what the hooks
2805
+ * actually call — and only this package knows that, which is why it is stated
2806
+ * here instead of copied into each scaffold. A frozen copy in a customer's
2807
+ * repo would 404 the next hook we ship, in their browser, silently.
2808
+ *
2809
+ * The scaffold still registers the proxy itself, visibly and editably; it just
2810
+ * reads the routes from here.
2811
+ */
2812
+ interface ProxyRoute {
2813
+ method: string;
2814
+ path: string;
2815
+ }
2816
+ declare const BROWSER_PROXY_ROUTES: ReadonlyArray<ProxyRoute>;
2817
+
2739
2818
  /**
2740
2819
  * Wildcard-aware CORS origin matching for the platform workers.
2741
2820
  *
@@ -2947,6 +3026,33 @@ declare const UPLOAD_PART_BYTES: number;
2947
3026
  * R2 allows 10,000 parts, so this is far inside what the API permits.
2948
3027
  */
2949
3028
  declare const MAX_UPLOAD_PARTS: number;
3029
+ /**
3030
+ * Per-tier storage schedule, in bytes. Product semantics, not a deployment
3031
+ * dial — the one table both storage allocations admit against:
3032
+ *
3033
+ * - the repo store (Git packs + retained bundles + deploy assets), admitted
3034
+ * by the app's Repo DO (`platform/deploy-worker/src/vc/storage-quota.ts`)
3035
+ * - the app-files allocation, admitted by the shared files handler
3036
+ * (`server/utils/scoped-r2-files.ts`)
3037
+ *
3038
+ * Each allocation gets the full amount independently; they are different
3039
+ * buckets with different writers (docs/platform/r2-storage.md). The
3040
+ * customer-visible "storage" number is the app-files allocation — the repo
3041
+ * store is platform bookkeeping that degrades (drops rollback retention)
3042
+ * rather than surfacing here.
3043
+ */
3044
+ declare const APP_STORAGE_LIMIT_BYTES: {
3045
+ readonly test: 0;
3046
+ readonly free: number;
3047
+ readonly starter: number;
3048
+ readonly premium: number;
3049
+ readonly admin: number;
3050
+ };
3051
+ /** The storage limit for a billing tier; unknown or missing tiers get free. */
3052
+ declare function storageLimitForTier(tier: string | null | undefined): number;
3053
+ /** The one storage-quota refusal sentence. `usedBytes` is net of any object
3054
+ * the upload replaces, so an upsert is charged only for its growth. */
3055
+ declare function storageQuotaMessage(incomingBytes: number, usedBytes: number, limitBytes: number): string;
2950
3056
  /**
2951
3057
  * The largest single file a deploy may ship as a static asset.
2952
3058
  *
@@ -3019,8 +3125,26 @@ interface ScopedR2Config {
3019
3125
  */
3020
3126
  requireAuthForMutations?: boolean;
3021
3127
  }
3128
+ /**
3129
+ * The storage-quota contract for one allocation, supplied per request by the
3130
+ * mount. The handler is the enforcer; the mount only knows whose limit
3131
+ * applies.
3132
+ */
3133
+ interface StorageAdmission {
3134
+ /** The WHOLE allocation the quota governs — the app prefix, not the
3135
+ * (possibly deeper) scope prefix a request resolved to. */
3136
+ prefix: string;
3137
+ /**
3138
+ * Resolve the owner's limit in bytes. `null` means the lookup failed;
3139
+ * writes then fail closed (503) rather than admitting unmetered storage,
3140
+ * mirroring the repo store's `StorageBillingUnavailableError`.
3141
+ */
3142
+ limitBytes: () => Promise<number | null>;
3143
+ }
3022
3144
  interface ScopedR2Auth {
3023
3145
  userId: string | null;
3146
+ /** Absent = no quota on this mount (e.g. an app's own bucket). */
3147
+ storage?: StorageAdmission;
3024
3148
  }
3025
3149
  type ScopedR2Handler = (request: Request, url: URL, bucket: R2Bucket, auth: ScopedR2Auth) => Promise<Response>;
3026
3150
  declare function isFilesVerbPath(method: string, subpath: string): boolean;
@@ -5237,4 +5361,4 @@ interface AppLogsResponse {
5237
5361
  declare const APP_LOG_EVENT_KEYS: readonly ["id", "timestamp", "level", "eventType", "message", "source", "outcome", "request", "exception"];
5238
5362
  type AppLogEventKey = (typeof APP_LOG_EVENT_KEYS)[number];
5239
5363
 
5240
- export { AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, APP_ID_RE, APP_LOG_EVENT_KEYS, APP_NAME_RULES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type ApiWorkerEnv, type AppLogEvent, type AppLogEventKey, type AppLogsResponse, type AppMigrationIdsValidation, type AppNameResolution, type AppNameValidation, type AuthWorkerEnv, Awareness, type AwarenessState, type AwarenessStates, BASE_USERS_SCHEMA, BUILT_IN_TOOLS, type BaseMessage, BaseRoom, CANONICAL_APP_IDENTITY_MIGRATION_ID, CHANNELS_SCHEMA, CHANNEL_INVITATIONS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, CLIENT_LOG_MARKER, CONVERSATION_SCHEMAS, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientErrorKind, type ClientErrorReport, type ClientMessage, type CollectionPermissionSummary, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ComposioToolsOptions, type ConnectionAttachment, type ConvMemberData, type ConvMessageData, type ConvReactionData, type ConvReadCursorData, type ConvVoteData, type ConversationStateData, type CronContext, type CronExecution, CronRoom, type CronRoomConfig, type CronTask, type CustomBinding, type CustomBindingManifest, DEEPSPACE_AGENT_PROFILES, DEEPSPACE_AI_DEFAULTS, DEEPSPACE_AI_MODELS, DEEPSPACE_MODEL_CATALOG_PROVENANCE, DEFAULT_CONTEXT_CONFIG, DEFAULT_DO_MANIFEST, DEFAULT_QUERY_LIMIT, DEPLOYED_APPS_DEFAULTS, DIRECTORY_SCHEMAS, type DOBindings, type DOManifest, type DOManifestEntry, type DeepSpaceAIEnv, type DeepSpaceAIModel, type DeepSpaceAIModelId, type DeepSpaceAIOptions, type DeepSpaceAIProvider, type DeepSpaceAgentDiagnosticContext, DeepSpaceAgentModelError, type DeepSpaceAgentProfile, DeepSpaceAgentProfileError, type DeepSpaceAgentProfileId, type DeepSpaceAgentStream, type DeepSpaceAgentStreamOptions, type DeepSpaceAgentSupport, type DeepSpaceAuth, type DeepSpaceAuthConfig, type DeepSpaceDocumentationRouteEnv, type DeepSpaceDocumentationRouteOptions, type DirectoryCommunityData, type DirectoryConversationData, type DirectoryMembershipData, type DirectoryPostData, type DoMigrationDirective, type DoMigrationPlan, type ExistingDOBinding, GLOBAL_DO_TYPES, GLOBAL_DO_TYPE_NAMES, type GameInput, GameRoom, type GameRoomConfig, type GetActionData, type GlobalDOType, type HandlerContext, type Job, type JobContext, JobRoom, type JobRoomConfig, type JobStatus, type JwtClaims, type JwtVerifierConfig, LOG_LEVELS, type LogLevel, MAX_APP_FILE_BYTES, MAX_DEPLOY_ASSET_FILE_BYTES, MAX_UPLOAD_PARTS, MAX_UPLOAD_REQUEST_BYTES, MESSAGES_SCHEMA, MSG, MSG_AWARENESS, MSG_SYNC, MSG_SYNC_STEP1, MSG_SYNC_STEP2, MSG_SYNC_UPDATE, MSG_YJS_AWARENESS, MSG_YJS_SYNC, type MessageHandlers, type MsgType, type MutateActionData, type PermissionAnalysis, type PermissionContext, type PermissionLevel, type PermissionSource, type PlatformWorkerEnv, type Player, type PrefixResult, type PresencePeer, PresenceRoom, type ProtocolMessage, type QueryActionData, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, REGISTRY_INSTANCE, RESERVED_BINDING_NAMES, RESERVED_COLLECTION_NAMES, RESOURCE_ID_RE, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, RegistryClientError, type ResolvedColumn, type ResolvedDeepSpaceAgentModel, type ResolvedPermission, type RolePermissions, type RunMigrationsResult, STRICT_APP_ID_RE, SYSTEM_COLLECTIONS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ScreenshotEnv, type ScreenshotResult, type ServerMessage, type SharedConnection, type StoredRecord, type Summarizer, type SyncResult, TEST_ACCOUNT_EMAIL_SUFFIX, type TokenDebugInfo, type ToolResult, type ToolSchema, UPLOAD_PART_BYTES, USERS_COLUMNS, type User, type UserAttachment, VOTING_SCHEMAS, type ValidationError, type VerifiedAuth, type VerifyOutcome, type VerifyResult, type Viewport, WORKSPACE_SCHEMAS, YjsRoom, analyzePermissions, apiWorkerFetch, appendMessage, applyAiToolDefaults, applySlidingWindow, authWorkerFetch, bindingManifestFromOutputConfig, buildCronContext, buildTableSelect, buildUiParts, callRegistry, canCreate, canDelete, canRead, canUpdate, capToolResultSize, captureScreenshot, checkFieldPermissions, clientBuild, coerceValue, collectionTableName, columnId, composioTools, computeDoMigration, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, dataToColumnValues, decodeJwtPayload, deepSpaceAgentErrorSummary, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, enqueueJob, formatBytes, getChat, getDeepSpaceAIModel, getGlobalDOSchemas, getGlobalDOType, getMessageType, getRolePermissions, handleAwarenessMessage, handleClientErrorReport, handleSyncMessage, hasContent, isAutoProvision, isFilesVerbPath, isOwner, isTestAccountClaims, isTestAccountEmail, isTestAccountTier, lintSchema, listDeepSpaceAgentModels, loadMessages, makeDefaultSummarizer, matchOrigin, meterAi, meterUsage, meterVectorize, noopPermissionContext, parseQuotaLimit, platformCorsPatterns, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, readVarUint, readVarUint8Array, registerClientErrorRoute, registerDeepSpaceDocumentation, registryErrorJson, registryStub, resolveAppName, resolveColumn, resolveDeepSpaceAgentModel, rowToData, runMigrations, serverBuild, streamDeepSpaceAgent, timingSafeEqualHex, timingSafeEqualStrings, toUint8Array, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppMigrationIds, validateAppName, validateBindingManifest, validateDoManifest, verifyJwt, workspaceAccountsSchema, workspaceContentSharesSchema, workspaceEmailHandlesSchema, workspaceFormResponsesSchema, workspacePeopleSchema, workspaceProjectsSchema, workspaceTagsSchema, workspaceTasksSchema, workspaceTeamMembersSchema, workspaceTeamsSchema, workspaceTransactionsSchema, writeVarUint, writeVarUint8Array };
5364
+ export { AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, APP_ID_RE, APP_LOG_EVENT_KEYS, APP_NAME_RULES, APP_STORAGE_LIMIT_BYTES, ASSET_NOT_FOUND_HANDLING_VALUES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type ApiWorkerEnv, type AppLogEvent, type AppLogEventKey, type AppLogsResponse, type AppMigrationIdsValidation, type AppNameResolution, type AppNameValidation, type AssetNotFoundHandling, type AuthWorkerEnv, Awareness, type AwarenessState, type AwarenessStates, BASE_USERS_SCHEMA, BROWSER_PROXY_ROUTES, BUILT_IN_TOOLS, type BaseMessage, BaseRoom, CANONICAL_APP_IDENTITY_MIGRATION_ID, CHANNELS_SCHEMA, CHANNEL_INVITATIONS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, CLIENT_LOG_MARKER, CONVERSATION_SCHEMAS, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientErrorKind, type ClientErrorReport, type ClientMessage, type CollectionPermissionSummary, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ComposioToolsOptions, type ConnectionAttachment, type ConvMemberData, type ConvMessageData, type ConvReactionData, type ConvReadCursorData, type ConvVoteData, type ConversationStateData, type CronContext, type CronExecution, CronRoom, type CronRoomConfig, type CronTask, type CustomBinding, type CustomBindingManifest, DEEPSPACE_AGENT_PROFILES, DEEPSPACE_AI_DEFAULTS, DEEPSPACE_AI_MODELS, DEEPSPACE_MODEL_CATALOG_PROVENANCE, DEFAULT_CONTEXT_CONFIG, DEFAULT_DO_MANIFEST, DEFAULT_QUERY_LIMIT, DEPLOYED_APPS_DEFAULTS, DIRECTORY_SCHEMAS, type DOBindings, type DOManifest, type DOManifestEntry, type DeepSpaceAIEnv, type DeepSpaceAIModel, type DeepSpaceAIModelId, type DeepSpaceAIOptions, type DeepSpaceAIProvider, type DeepSpaceAgentDiagnosticContext, DeepSpaceAgentModelError, type DeepSpaceAgentProfile, DeepSpaceAgentProfileError, type DeepSpaceAgentProfileId, type DeepSpaceAgentStream, type DeepSpaceAgentStreamOptions, type DeepSpaceAgentSupport, type DeepSpaceAuth, type DeepSpaceAuthConfig, type DeepSpaceDocumentationRouteEnv, type DeepSpaceDocumentationRouteOptions, type DirectoryCommunityData, type DirectoryConversationData, type DirectoryMembershipData, type DirectoryPostData, type DoMigrationDirective, type DoMigrationPlan, type ExistingDOBinding, GLOBAL_DO_TYPES, GLOBAL_DO_TYPE_NAMES, type GameInput, GameRoom, type GameRoomConfig, type GetActionData, type GlobalDOType, type HandlerContext, type Job, type JobContext, JobRoom, type JobRoomConfig, type JobStatus, type JwtClaims, type JwtVerifierConfig, LOG_LEVELS, type LogLevel, MAX_APP_FILE_BYTES, MAX_DEPLOY_ASSET_FILE_BYTES, MAX_UPLOAD_PARTS, MAX_UPLOAD_REQUEST_BYTES, MESSAGES_SCHEMA, MSG, MSG_AWARENESS, MSG_SYNC, MSG_SYNC_STEP1, MSG_SYNC_STEP2, MSG_SYNC_UPDATE, MSG_YJS_AWARENESS, MSG_YJS_SYNC, type MessageHandlers, type MsgType, type MutateActionData, type PermissionAnalysis, type PermissionContext, type PermissionLevel, type PermissionSource, type PlatformWorkerEnv, type Player, type PrefixResult, type PresencePeer, PresenceRoom, type ProtocolMessage, type ProxyRoute, type QueryActionData, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, REGISTRY_INSTANCE, RELEASE_STAMP_PATH, REQUIRED_COMPATIBILITY_FLAGS, RESERVED_BINDING_NAMES, RESERVED_COLLECTION_NAMES, RESERVED_RUN_WORKER_FIRST, RESOURCE_ID_RE, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, RegistryClientError, type ResolvedColumn, type ResolvedDeepSpaceAgentModel, type ResolvedPermission, type RolePermissions, type RunMigrationsResult, SDK_RUN_WORKER_FIRST, STRICT_APP_ID_RE, SYSTEM_COLLECTIONS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ScreenshotEnv, type ScreenshotResult, type ServerMessage, type SharedConnection, type StorageAdmission, type StoredRecord, type Summarizer, type SyncResult, TEST_ACCOUNT_EMAIL_SUFFIX, type TokenDebugInfo, type ToolResult, type ToolSchema, UNDECLARED_ASSET_NOT_FOUND_HANDLING, UPLOAD_PART_BYTES, USERS_COLUMNS, type User, type UserAttachment, VOTING_SCHEMAS, type ValidationError, type VerifiedAuth, type VerifyOutcome, type VerifyResult, type Viewport, WORKER_OWNED_NOT_FOUND_MIGRATION_ID, WORKSPACE_SCHEMAS, YjsRoom, analyzePermissions, apiWorkerFetch, appendMessage, applyAiToolDefaults, applySlidingWindow, authWorkerFetch, bindingManifestFromOutputConfig, buildCronContext, buildTableSelect, buildUiParts, callRegistry, canCreate, canDelete, canRead, canUpdate, capToolResultSize, captureScreenshot, checkFieldPermissions, clientBuild, coerceValue, collectionTableName, columnId, composioTools, computeDoMigration, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, dataToColumnValues, decodeJwtPayload, deepSpaceAgentErrorSummary, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, enqueueJob, formatBytes, getChat, getDeepSpaceAIModel, getGlobalDOSchemas, getGlobalDOType, getMessageType, getRolePermissions, handleAwarenessMessage, handleClientErrorReport, handleSyncMessage, hasContent, isAssetNotFoundHandling, isAutoProvision, isFilesVerbPath, isOwner, isPlatformReservedPath, isTestAccountClaims, isTestAccountEmail, isTestAccountTier, lintSchema, listDeepSpaceAgentModels, loadMessages, makeDefaultSummarizer, matchOrigin, meterAi, meterUsage, meterVectorize, noopPermissionContext, parseQuotaLimit, platformCorsPatterns, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, readVarUint, readVarUint8Array, registerClientErrorRoute, registerDeepSpaceDocumentation, registryErrorJson, registryStub, resolveAppName, resolveColumn, resolveCompatibilityFlags, resolveDeepSpaceAgentModel, rowToData, runMigrations, serverBuild, storageLimitForTier, storageQuotaMessage, streamDeepSpaceAgent, timingSafeEqualHex, timingSafeEqualStrings, toUint8Array, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppMigrationIds, validateAppName, validateBindingManifest, validateDoManifest, verifyJwt, workspaceAccountsSchema, workspaceContentSharesSchema, workspaceEmailHandlesSchema, workspaceFormResponsesSchema, workspacePeopleSchema, workspaceProjectsSchema, workspaceTagsSchema, workspaceTasksSchema, workspaceTeamMembersSchema, workspaceTeamsSchema, workspaceTransactionsSchema, writeVarUint, writeVarUint8Array };
package/dist/worker.js CHANGED
@@ -6019,6 +6019,7 @@ var RESERVED_COLLECTION_NAMES = new Set(
6019
6019
  var APP_MIGRATION_ID_RE = /^[a-z0-9][a-z0-9._-]{0,127}$/;
6020
6020
  var MAX_APP_MIGRATION_IDS = 256;
6021
6021
  var CANONICAL_APP_IDENTITY_MIGRATION_ID = "2026-08-canonical-app-identity-wire";
6022
+ var WORKER_OWNED_NOT_FOUND_MIGRATION_ID = "2026-08-worker-owned-not-found";
6022
6023
  function validateAppMigrationIds(value) {
6023
6024
  if (!Array.isArray(value)) {
6024
6025
  return { valid: false, reason: "app migrations must be a JSON string array" };
@@ -6170,6 +6171,76 @@ function resolveDeepSpaceAgentModel(modelId, profileId = "application") {
6170
6171
  return { modelId: model.id, provider: model.provider, model, profile };
6171
6172
  }
6172
6173
 
6174
+ // src/shared/app-routing.ts
6175
+ var RELEASE_STAMP_PATH = "/.well-known/deepspace/release.json";
6176
+ var ASSET_NOT_FOUND_HANDLING_VALUES = [
6177
+ "none",
6178
+ "single-page-application",
6179
+ "404-page"
6180
+ ];
6181
+ var UNDECLARED_ASSET_NOT_FOUND_HANDLING = "single-page-application";
6182
+ function isAssetNotFoundHandling(value) {
6183
+ return ASSET_NOT_FOUND_HANDLING_VALUES.includes(value);
6184
+ }
6185
+ var REQUIRED_COMPATIBILITY_FLAGS = [
6186
+ "nodejs_compat",
6187
+ "assets_navigation_has_no_effect"
6188
+ ];
6189
+ var CONTRADICTORY_COMPATIBILITY_FLAGS = /* @__PURE__ */ new Set([
6190
+ "no_nodejs_compat",
6191
+ "assets_navigation_prefers_asset_serving"
6192
+ ]);
6193
+ function resolveCompatibilityFlags(declared) {
6194
+ const flags = new Set(REQUIRED_COMPATIBILITY_FLAGS);
6195
+ for (const flag of declared ?? []) {
6196
+ if (typeof flag !== "string") continue;
6197
+ const trimmed = flag.trim();
6198
+ if (!trimmed || CONTRADICTORY_COMPATIBILITY_FLAGS.has(trimmed)) continue;
6199
+ flags.add(trimmed);
6200
+ }
6201
+ return [...flags];
6202
+ }
6203
+ var SDK_RUN_WORKER_FIRST = [
6204
+ "/api/*",
6205
+ "/ws/*",
6206
+ "/internal/*",
6207
+ "/v1/*",
6208
+ "/_deepspace/*",
6209
+ "/llms.txt",
6210
+ "/llms-full.txt",
6211
+ "/.well-known/mcp",
6212
+ "/.well-known/mcp.json",
6213
+ "/.well-known/mcp/*"
6214
+ ];
6215
+ var DOCUMENTATION_PATHS = [
6216
+ "/_documentation",
6217
+ "/_documentation/*",
6218
+ "/_documentation-root",
6219
+ "/_documentation-root/*"
6220
+ ];
6221
+ var RESERVED_RUN_WORKER_FIRST = [
6222
+ ...SDK_RUN_WORKER_FIRST,
6223
+ ...DOCUMENTATION_PATHS
6224
+ ];
6225
+ function isPlatformReservedPath(pathname) {
6226
+ return RESERVED_RUN_WORKER_FIRST.some((pattern) => {
6227
+ if (!pattern.endsWith("/*")) return pathname === pattern;
6228
+ const base = pattern.slice(0, -2);
6229
+ return pathname === base || pathname.startsWith(`${base}/`);
6230
+ });
6231
+ }
6232
+
6233
+ // src/shared/platform-proxy.ts
6234
+ var BROWSER_PROXY_ROUTES = [
6235
+ // useSubscription — read state, subscribe, manage billing.
6236
+ { method: "GET", path: "/_deepspace/subscriptions/me" },
6237
+ { method: "POST", path: "/_deepspace/subscriptions/checkout" },
6238
+ { method: "POST", path: "/_deepspace/subscriptions/portal" },
6239
+ // useCheckout (one-time charges).
6240
+ { method: "POST", path: "/_deepspace/charges/create" },
6241
+ { method: "GET", path: "/_deepspace/charges/me" }
6242
+ ];
6243
+
6173
6244
  // src/server/utils/cors.ts
6174
6245
  function matchOrigin(origin, patterns) {
6175
6246
  if (!origin) return null;
@@ -6246,6 +6317,23 @@ var MAX_UPLOAD_REQUEST_BYTES = 25 * 1024 * 1024;
6246
6317
  var UPLOAD_PART_BYTES = 20 * 1024 * 1024;
6247
6318
  var MAX_UPLOAD_PARTS = Math.ceil(MAX_APP_FILE_BYTES / UPLOAD_PART_BYTES);
6248
6319
  var MAX_BASE64_UPLOAD_BYTES = Math.floor(MAX_UPLOAD_REQUEST_BYTES * 3 / 4);
6320
+ var APP_STORAGE_LIMIT_BYTES = {
6321
+ test: 0,
6322
+ free: 128 * 1024 * 1024,
6323
+ starter: 512 * 1024 * 1024,
6324
+ premium: 2 * 1024 * 1024 * 1024,
6325
+ admin: 10 * 1024 * 1024 * 1024
6326
+ };
6327
+ function storageLimitForTier(tier) {
6328
+ if (tier && Object.hasOwn(APP_STORAGE_LIMIT_BYTES, tier)) {
6329
+ return APP_STORAGE_LIMIT_BYTES[tier];
6330
+ }
6331
+ return APP_STORAGE_LIMIT_BYTES.free;
6332
+ }
6333
+ function storageQuotaMessage(incomingBytes, usedBytes, limitBytes) {
6334
+ const free = Math.max(0, limitBytes - usedBytes);
6335
+ return `This upload needs ${formatBytes(incomingBytes)} but the app's file storage has ${formatBytes(free)} free (${formatBytes(usedBytes)} of ${formatBytes(limitBytes)} used). Delete files with \`deepspace app files rm <key>\`, or upgrade the owner's plan.`;
6336
+ }
6249
6337
  var MAX_DEPLOY_ASSET_FILE_BYTES = 25 * 1024 * 1024;
6250
6338
  var DANGEROUS_MIME_TYPES = /* @__PURE__ */ new Set([
6251
6339
  "text/html",
@@ -6332,6 +6420,52 @@ function declaredLength(request, what) {
6332
6420
  function isKeyWithinPrefix(key, prefix) {
6333
6421
  return key.startsWith(prefix);
6334
6422
  }
6423
+ async function allocationUsage(bucket, prefix) {
6424
+ let total = 0;
6425
+ let cursor;
6426
+ do {
6427
+ const page = await bucket.list({ prefix, cursor, limit: 1e3 });
6428
+ for (const object of page.objects) total += object.size;
6429
+ cursor = page.truncated ? page.cursor : void 0;
6430
+ } while (cursor !== void 0);
6431
+ return total;
6432
+ }
6433
+ async function admitStorage(bucket, storage, incomingBytes, replacesKey) {
6434
+ if (!storage) return null;
6435
+ const limit = await storage.limitBytes();
6436
+ if (limit === null) {
6437
+ return fail(
6438
+ 503,
6439
+ "The storage limit for this app could not be verified; nothing was uploaded. Retry shortly.",
6440
+ "storage_limit_unavailable"
6441
+ );
6442
+ }
6443
+ const stored = await allocationUsage(bucket, storage.prefix);
6444
+ const replaced = replacesKey === null ? 0 : (await bucket.head(replacesKey))?.size ?? 0;
6445
+ const used = stored - replaced;
6446
+ if (used + incomingBytes <= limit) return null;
6447
+ return fail(409, storageQuotaMessage(incomingBytes, used, limit), "storage_quota_exceeded", {
6448
+ usedBytes: used,
6449
+ limitBytes: limit
6450
+ });
6451
+ }
6452
+ async function admitAssembledObject(bucket, storage, key, objectBytes) {
6453
+ if (!storage) return null;
6454
+ const limit = await storage.limitBytes();
6455
+ if (limit === null) {
6456
+ console.error("[files:quota] limit unavailable at complete; keeping", key);
6457
+ return null;
6458
+ }
6459
+ const stored = await allocationUsage(bucket, storage.prefix);
6460
+ if (stored <= limit) return null;
6461
+ await bucket.delete(key).catch(() => void 0);
6462
+ return fail(
6463
+ 409,
6464
+ `${storageQuotaMessage(objectBytes, stored - objectBytes, limit)} The assembled upload was not kept.`,
6465
+ "storage_quota_exceeded",
6466
+ { usedBytes: stored - objectBytes, limitBytes: limit }
6467
+ );
6468
+ }
6335
6469
  function anchorKey(raw, prefix) {
6336
6470
  const safe = sanitizeSubpath(raw);
6337
6471
  if (safe === null) return fail(400, "Invalid key: traversal not allowed", "invalid_key");
@@ -6421,10 +6555,10 @@ function createScopedR2Handler(config) {
6421
6555
  await request.body?.cancel().catch(() => void 0);
6422
6556
  return fail(401, "Authentication required", "unauthorized");
6423
6557
  }
6424
- return subpath === "upload" ? handleUpload(request, url, bucket, prefix, auth.userId, scope) : handleMultipart(request, url, bucket, prefix, auth.userId, scope, subpath);
6558
+ return subpath === "upload" ? handleUpload(request, url, bucket, prefix, auth, scope) : handleMultipart(request, url, bucket, prefix, auth, scope, subpath);
6425
6559
  }
6426
6560
  if (!subpath && request.method === "GET") {
6427
- return handleList(bucket, prefix, url, scope);
6561
+ return handleList(bucket, prefix, url, scope, auth);
6428
6562
  }
6429
6563
  if (subpath && request.method === "GET") {
6430
6564
  if (!isKeyWithinPrefix(subpath, prefix)) {
@@ -6458,7 +6592,7 @@ function createScopedR2Handler(config) {
6458
6592
  return Response.json({ error: "Method not allowed" }, { status: 405, headers: CORS_HEADERS3 });
6459
6593
  };
6460
6594
  }
6461
- async function handleUpload(request, url, bucket, prefix, userId, scope) {
6595
+ async function handleUpload(request, url, bucket, prefix, auth, scope) {
6462
6596
  try {
6463
6597
  const declared = overRequestBound(Number(request.headers.get("content-length")), 8 * 1024);
6464
6598
  if (declared) return declared;
@@ -6489,9 +6623,12 @@ async function handleUpload(request, url, bucket, prefix, userId, scope) {
6489
6623
  if (mime instanceof Response) return mime;
6490
6624
  const located = locateUpload(url, prefix, fileName);
6491
6625
  if (located instanceof Response) return located;
6626
+ const replacesKey = url.searchParams.get("key") === null ? null : located.key;
6627
+ const overQuota = await admitStorage(bucket, auth.storage, fileData.byteLength, replacesKey);
6628
+ if (overQuota) return overQuota;
6492
6629
  await bucket.put(located.key, fileData, {
6493
6630
  httpMetadata: { contentType: mime.mimeType },
6494
- customMetadata: fileMetadata(fileName, userId)
6631
+ customMetadata: fileMetadata(fileName, auth.userId)
6495
6632
  });
6496
6633
  return storedFileJson(located.key, fileName, url, scope);
6497
6634
  } catch (err) {
@@ -6566,17 +6703,17 @@ async function streamPart(upload, partNumber, body, expectedBytes) {
6566
6703
  }
6567
6704
  return { ok: true, part: uploaded.value };
6568
6705
  }
6569
- async function handleMultipart(request, url, bucket, prefix, userId, scope, subpath) {
6706
+ async function handleMultipart(request, url, bucket, prefix, auth, scope, subpath) {
6570
6707
  if (subpath === "multipart" && request.method === "POST") {
6571
- return multipartInit(request, url, bucket, prefix, userId);
6708
+ return multipartInit(request, url, bucket, prefix, auth);
6572
6709
  }
6573
6710
  if (subpath === "multipart/part") return multipartPart(request, url, bucket, prefix);
6574
6711
  if (subpath === "multipart/complete") {
6575
- return multipartComplete(request, url, bucket, prefix, scope);
6712
+ return multipartComplete(request, url, bucket, prefix, auth, scope);
6576
6713
  }
6577
6714
  return multipartAbort(url, bucket, prefix);
6578
6715
  }
6579
- async function multipartInit(request, url, bucket, prefix, userId) {
6716
+ async function multipartInit(request, url, bucket, prefix, auth) {
6580
6717
  const body = await readControlJson(request);
6581
6718
  if (body instanceof Response) return body;
6582
6719
  const size = body.size;
@@ -6591,11 +6728,14 @@ async function multipartInit(request, url, bucket, prefix, userId) {
6591
6728
  if (mime instanceof Response) return mime;
6592
6729
  const located = locateUpload(url, prefix, name);
6593
6730
  if (located instanceof Response) return located;
6731
+ const replacesKey = url.searchParams.get("key") === null ? null : located.key;
6732
+ const overQuota = await admitStorage(bucket, auth.storage, size, replacesKey);
6733
+ if (overQuota) return overQuota;
6594
6734
  let upload;
6595
6735
  try {
6596
6736
  upload = await bucket.createMultipartUpload(located.key, {
6597
6737
  httpMetadata: { contentType: mime.mimeType },
6598
- customMetadata: fileMetadata(name, userId)
6738
+ customMetadata: fileMetadata(name, auth.userId)
6599
6739
  });
6600
6740
  } catch (error) {
6601
6741
  return multipartFailure(error);
@@ -6645,7 +6785,7 @@ async function multipartPart(request, url, bucket, prefix) {
6645
6785
  { headers: CORS_HEADERS3 }
6646
6786
  );
6647
6787
  }
6648
- async function multipartComplete(request, url, bucket, prefix, scope) {
6788
+ async function multipartComplete(request, url, bucket, prefix, auth, scope) {
6649
6789
  const body = await readControlJson(request);
6650
6790
  if (body instanceof Response) return body;
6651
6791
  const session = resolveSession(url, prefix);
@@ -6679,6 +6819,8 @@ async function multipartComplete(request, url, bucket, prefix, scope) {
6679
6819
  await bucket.delete(session.key).catch(() => void 0);
6680
6820
  return tooBig;
6681
6821
  }
6822
+ const overQuota = await admitAssembledObject(bucket, auth.storage, session.key, object.size);
6823
+ if (overQuota) return overQuota;
6682
6824
  const name = object.customMetadata?.originalName ?? session.key.split("/").pop() ?? "file";
6683
6825
  return storedFileJson(session.key, name, url, scope);
6684
6826
  }
@@ -6693,7 +6835,7 @@ async function multipartAbort(url, bucket, prefix) {
6693
6835
  }
6694
6836
  return Response.json({ success: true, aborted: true }, { headers: CORS_HEADERS3 });
6695
6837
  }
6696
- async function handleList(bucket, prefix, url, scope) {
6838
+ async function handleList(bucket, prefix, url, scope, auth) {
6697
6839
  const userPrefix = url.searchParams.get("prefix") || "";
6698
6840
  const listPrefix = `${prefix}${userPrefix}`;
6699
6841
  const limit = parseInt(url.searchParams.get("limit") || "100", 10);
@@ -6709,7 +6851,16 @@ async function handleList(bucket, prefix, url, scope) {
6709
6851
  ...obj.customMetadata
6710
6852
  };
6711
6853
  });
6712
- return Response.json({ files, truncated: listed.truncated }, { headers: CORS_HEADERS3 });
6854
+ let storage;
6855
+ if (auth.storage) {
6856
+ storage = { usedBytes: await allocationUsage(bucket, auth.storage.prefix) };
6857
+ const limitBytes = await auth.storage.limitBytes();
6858
+ if (limitBytes !== null) storage.limitBytes = limitBytes;
6859
+ }
6860
+ return Response.json(
6861
+ { files, truncated: listed.truncated, ...storage ? { storage } : {} },
6862
+ { headers: CORS_HEADERS3 }
6863
+ );
6713
6864
  }
6714
6865
  async function handleDownload(bucket, key, scope) {
6715
6866
  const object = await bucket.get(key);
@@ -9317,10 +9468,13 @@ export {
9317
9468
  APP_ID_RE,
9318
9469
  APP_LOG_EVENT_KEYS,
9319
9470
  APP_NAME_RULES,
9471
+ APP_STORAGE_LIMIT_BYTES,
9472
+ ASSET_NOT_FOUND_HANDLING_VALUES,
9320
9473
  AUTO_PROVISIONABLE_TYPES,
9321
9474
  AUTO_PROVISION_SENTINEL,
9322
9475
  Awareness,
9323
9476
  BASE_USERS_SCHEMA,
9477
+ BROWSER_PROXY_ROUTES,
9324
9478
  BUILT_IN_TOOLS,
9325
9479
  BaseRoom,
9326
9480
  CANONICAL_APP_IDENTITY_MIGRATION_ID,
@@ -9365,22 +9519,28 @@ export {
9365
9519
  REACTIONS_SCHEMA,
9366
9520
  READ_RECEIPTS_SCHEMA,
9367
9521
  REGISTRY_INSTANCE,
9522
+ RELEASE_STAMP_PATH,
9523
+ REQUIRED_COMPATIBILITY_FLAGS,
9368
9524
  RESERVED_BINDING_NAMES,
9369
9525
  RESERVED_COLLECTION_NAMES,
9526
+ RESERVED_RUN_WORKER_FIRST,
9370
9527
  RESOURCE_ID_RE,
9371
9528
  ROLE_ADMIN,
9372
9529
  ROLE_ANONYMOUS,
9373
9530
  ROLE_DEFAULT,
9374
9531
  RecordRoom,
9375
9532
  RegistryClientError,
9533
+ SDK_RUN_WORKER_FIRST,
9376
9534
  STRICT_APP_ID_RE,
9377
9535
  SYSTEM_COLLECTIONS,
9378
9536
  SYSTEM_MANAGED_COLUMNS,
9379
9537
  SchemaRegistry,
9380
9538
  TEST_ACCOUNT_EMAIL_SUFFIX,
9539
+ UNDECLARED_ASSET_NOT_FOUND_HANDLING,
9381
9540
  UPLOAD_PART_BYTES,
9382
9541
  USERS_COLUMNS,
9383
9542
  VOTING_SCHEMAS,
9543
+ WORKER_OWNED_NOT_FOUND_MIGRATION_ID,
9384
9544
  WORKSPACE_SCHEMAS,
9385
9545
  YjsRoom,
9386
9546
  analyzePermissions,
@@ -9436,9 +9596,11 @@ export {
9436
9596
  handleClientErrorReport,
9437
9597
  handleSyncMessage,
9438
9598
  hasContent,
9599
+ isAssetNotFoundHandling,
9439
9600
  isAutoProvision,
9440
9601
  isFilesVerbPath,
9441
9602
  isOwner,
9603
+ isPlatformReservedPath,
9442
9604
  isTestAccountClaims,
9443
9605
  isTestAccountEmail,
9444
9606
  isTestAccountTier,
@@ -9464,10 +9626,13 @@ export {
9464
9626
  registryStub,
9465
9627
  resolveAppName,
9466
9628
  resolveColumn,
9629
+ resolveCompatibilityFlags,
9467
9630
  resolveDeepSpaceAgentModel,
9468
9631
  rowToData,
9469
9632
  runMigrations,
9470
9633
  serverBuild,
9634
+ storageLimitForTier,
9635
+ storageQuotaMessage,
9471
9636
  streamDeepSpaceAgent,
9472
9637
  timingSafeEqualHex,
9473
9638
  timingSafeEqualStrings,