deepspace 0.12.0 → 0.13.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
@@ -2882,31 +2882,82 @@ declare function applyAiToolDefaults(toolName: string, params: Record<string, un
2882
2882
  declare const BUILT_IN_TOOLS: ToolSchema[];
2883
2883
 
2884
2884
  /**
2885
- * App-files limits and failure reading, shared by every caller of the files
2886
- * API: the browser hook (`client/storage/useR2Files.ts`), the CLI
2887
- * (`cli/lib/app-files-api.ts`), and the docs that quote them.
2888
- *
2889
- * The ceiling is not a product decision made here — it is what the transport
2890
- * physically allows. An upload crosses Cloudflare's request-body limit before
2891
- * any worker code runs, and the platform worker then reads the whole body into
2892
- * a ~128 MiB isolate before writing it to R2. So an oversized upload does not
2893
- * fail as a friendly JSON error; it fails as a raw Cloudflare HTML page that
2894
- * every caller here used to feed straight into `JSON.parse` and report as
2895
- * "Unexpected token '<' … is not valid JSON". That is the bug this module
2896
- * exists to make impossible.
2885
+ * App-files limits, chunk planning, and failure reading — shared by every
2886
+ * caller of the files API: the browser hook (`client/storage/useR2Files.ts`),
2887
+ * the CLI (`cli/lib/app-files-api.ts`), the server handler
2888
+ * (`server/utils/scoped-r2-files.ts`), and the docs that quote them.
2889
+ *
2890
+ * There are three numbers here and they answer three different questions.
2891
+ * Conflating them is what produced the old 25 MiB per-file ceiling: that was
2892
+ * never a product decision, it was the size of one HTTP request leaking out as
2893
+ * a rule about files. A request is bounded by physics — Cloudflare rejects an
2894
+ * oversized body before any worker runs, and the worker's isolate is ~128 MiB.
2895
+ * A FILE is not, once it travels as a sequence of bounded requests.
2896
+ *
2897
+ * The other half of this module is failure reading. An upload refused at the
2898
+ * edge answers with a Cloudflare HTML page, which every caller used to feed
2899
+ * straight into `JSON.parse` and report as "Unexpected token '<' … is not
2900
+ * valid JSON". `describeFilesFailure` exists to make that impossible.
2897
2901
  */
2898
2902
  /**
2899
2903
  * The largest single file the app-files API accepts.
2900
2904
  *
2901
- * Enforced by the shared upload handler (`server/utils/scoped-r2-files.ts`),
2902
- * which is the only place it is a real limit — above it the platform worker
2903
- * risks exhausting its isolate while holding the decoded file and the
2904
- * multipart envelope together. Callers also check it locally, but only so the
2905
- * failure is named early; skipping the client check cannot widen what is
2906
- * accepted. Well above it (~100 MB) Cloudflare rejects the request before the
2907
- * worker runs at all, which is why callers must read failures as text first.
2905
+ * Reachable only through the multipart transport: a file above
2906
+ * {@link UPLOAD_PART_BYTES} is uploaded as a sequence of parts, so no request
2907
+ * and no isolate ever holds more than one part. Enforced by the shared handler
2908
+ * (`server/utils/scoped-r2-files.ts`) twice — once at init against the
2909
+ * declared total, so an impossible upload fails before a byte moves, and again
2910
+ * at complete against the assembled object, because the declared total is
2911
+ * client-supplied. Callers check it locally too, but only to fail early;
2912
+ * skipping the client check cannot widen what is accepted.
2908
2913
  */
2909
2914
  declare const MAX_APP_FILE_BYTES: number;
2915
+ /**
2916
+ * The most any ONE request body may carry — a whole small file on the
2917
+ * single-request path, or one part on the multipart path.
2918
+ *
2919
+ * This is the transport's real physical bound, and the only thing 25 MiB ever
2920
+ * meant. Above it the worker risks exhausting its isolate holding the body;
2921
+ * well above it (~100 MB) Cloudflare refuses the request before the worker
2922
+ * runs at all, which is why callers must read failures as text first.
2923
+ */
2924
+ declare const MAX_UPLOAD_REQUEST_BYTES: number;
2925
+ /**
2926
+ * The part size clients chunk at, and the threshold above which they must.
2927
+ *
2928
+ * Below the {@link MAX_UPLOAD_REQUEST_BYTES} bound with headroom for the
2929
+ * request envelope, and comfortably inside R2's own part rules: parts must be
2930
+ * at least 5 MiB and every non-final part must be exactly the same size
2931
+ * (R2 errors 10011 / 10048). The server advertises this at init — a client
2932
+ * chunks at the size it is told, not at this constant, so the number can move
2933
+ * without stranding older callers mid-upload.
2934
+ */
2935
+ declare const UPLOAD_PART_BYTES: number;
2936
+ /**
2937
+ * The highest part number the server accepts.
2938
+ *
2939
+ * The handler holds no per-session state, so this — not the declared total —
2940
+ * is what bounds an in-flight upload. It is computed against
2941
+ * {@link UPLOAD_PART_BYTES}, which is why the server refuses a part larger
2942
+ * than that even though a whole small file may be 25 MiB: admitting 25 MiB
2943
+ * parts would make the real in-flight bound 52 × 25 MiB = 1300 MiB while the
2944
+ * advertised ceiling stayed 1 GiB. With both numbers agreeing, a session's
2945
+ * worst case is 52 × 20 MiB = 1040 MiB — the ceiling plus one part.
2946
+ *
2947
+ * R2 allows 10,000 parts, so this is far inside what the API permits.
2948
+ */
2949
+ declare const MAX_UPLOAD_PARTS: number;
2950
+ /**
2951
+ * The largest single file a deploy may ship as a static asset.
2952
+ *
2953
+ * Cloudflare Static Assets refuses anything larger, so this is a hard edge of
2954
+ * the platform rather than a policy dial — which is why the CLI may check it
2955
+ * locally. It lives here so the deploy worker and the CLI cannot drift; the
2956
+ * per-DEPLOY total is deliberately NOT here, because it is env-configurable
2957
+ * per environment and only the server can know it.
2958
+ */
2959
+ declare const MAX_DEPLOY_ASSET_FILE_BYTES: number;
2960
+ declare function formatBytes(bytes: number): string;
2910
2961
 
2911
2962
  /**
2912
2963
  * Shared Scoped R2 Files Handler
@@ -2920,10 +2971,29 @@ declare const MAX_APP_FILE_BYTES: number;
2920
2971
  * The security invariants are enforced here once — not per-worker.
2921
2972
  *
2922
2973
  * Routes:
2923
- * POST /api/files/upload → upload (prefix + generated key)
2924
- * GET /api/files → list (prefix + optional user prefix)
2925
- * GET /api/files/:key → download (validated against prefix)
2926
- * DELETE /api/files/:key → delete (validated against prefix)
2974
+ * POST /api/files/upload → upload one file in one request
2975
+ * POST /api/files/multipart → begin a chunked upload
2976
+ * PUT /api/files/multipart/part → send one part
2977
+ * POST /api/files/multipart/complete → assemble the parts
2978
+ * DELETE /api/files/multipart → abandon a chunked upload
2979
+ * GET /api/files → list (prefix + optional user prefix)
2980
+ * GET /api/files/:key → download (validated against prefix)
2981
+ * DELETE /api/files/:key → delete (validated against prefix)
2982
+ *
2983
+ * ## One transport discipline
2984
+ *
2985
+ * Both upload paths obey the rule the deploy asset transport established
2986
+ * (`docs/projects/2026-08-05-deploy-asset-transport/README.md`): nothing here
2987
+ * ever holds more than one bounded request in memory. The single-request path
2988
+ * exists so a small file still costs one round trip; above
2989
+ * {@link UPLOAD_PART_BYTES} a file travels as parts, each streamed into R2
2990
+ * through a `FixedLengthStream` with a required `Content-Length`. That is why
2991
+ * a 1 GiB file is admissible in a ~128 MiB isolate.
2992
+ *
2993
+ * Validation is identical on both paths and on both mounts, because it lives
2994
+ * here: the prefix scoping, the traversal check, the MIME refusals, and both
2995
+ * size bounds. A hand-rolled request that skips every client guard reaches
2996
+ * exactly these checks.
2927
2997
  */
2928
2998
 
2929
2999
  interface ScopeContext {
@@ -2953,6 +3023,7 @@ interface ScopedR2Auth {
2953
3023
  userId: string | null;
2954
3024
  }
2955
3025
  type ScopedR2Handler = (request: Request, url: URL, bucket: R2Bucket, auth: ScopedR2Auth) => Promise<Response>;
3026
+ declare function isFilesVerbPath(method: string, subpath: string): boolean;
2956
3027
  /**
2957
3028
  * Create a scoped R2 files handler.
2958
3029
  *
@@ -5166,4 +5237,4 @@ interface AppLogsResponse {
5166
5237
  declare const APP_LOG_EVENT_KEYS: readonly ["id", "timestamp", "level", "eventType", "message", "source", "outcome", "request", "exception"];
5167
5238
  type AppLogEventKey = (typeof APP_LOG_EVENT_KEYS)[number];
5168
5239
 
5169
- 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, 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, 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, getChat, getDeepSpaceAIModel, getGlobalDOSchemas, getGlobalDOType, getMessageType, getRolePermissions, handleAwarenessMessage, handleClientErrorReport, handleSyncMessage, hasContent, isAutoProvision, 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 };
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 };