deepspace 0.30.0 → 0.30.2

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/server.d.ts CHANGED
@@ -531,6 +531,26 @@ interface YjsLeavePayload {
531
531
  fieldName: string;
532
532
  }
533
533
 
534
+ /**
535
+ * Platform API error normalization — the one chokepoint that turns the
536
+ * api-worker's error envelope into a render-safe + branch-safe shape.
537
+ *
538
+ * The platform emits errors as `{ error: <machine slug>, message?: <human>,
539
+ * ...details }` (e.g. 402 `{ error: 'insufficient_credits', message:
540
+ * 'Insufficient credits.', availableCredits, requiredCredits }`; some routes
541
+ * send the bare slug with no `message` at all, e.g. 409
542
+ * `{ error: 'owner_connect_not_ready' }`). Consumers must never show the slug
543
+ * to a person or make an agent parse the sentence — this module separates the
544
+ * two once, for the integration client, server actions, billing hooks, and the
545
+ * CLI.
546
+ */
547
+ /** One structured validation issue (Zod shape) from a `validation_failed` response. */
548
+ interface ApiErrorIssue {
549
+ path?: string[];
550
+ message: string;
551
+ code?: string;
552
+ }
553
+
534
554
  /**
535
555
  * Server Action Types
536
556
  *
@@ -555,7 +575,16 @@ type ActionResult<TData = unknown> = {
555
575
  } | {
556
576
  success: false;
557
577
  data?: never;
578
+ /** Human-readable error, safe to render directly. */
558
579
  error: string;
580
+ /** Machine slug for branching, when the failing tool supplied one. */
581
+ code?: string;
582
+ /** HTTP status from an upstream platform request, when applicable. */
583
+ status?: number;
584
+ /** Structured fields supplied with the error response. */
585
+ details?: Record<string, unknown>;
586
+ /** Validation issues supplied with a `validation_failed` response. */
587
+ issues?: ApiErrorIssue[];
559
588
  };
560
589
  /** Shape of the data field for `tools.query`. */
561
590
  interface QueryActionData<T = Record<string, unknown>> {
@@ -610,7 +639,9 @@ interface ActionTools {
610
639
  * api-worker. On success, `result.data` is the integration's response
611
640
  * body directly — there is no `.response` wrapper. So an OpenAI call
612
641
  * yields `result.data.choices`, a Freepik image call yields
613
- * `result.data.images`, etc.
642
+ * `result.data.images`, etc. On failure, `result.error` is human-readable;
643
+ * branch on `result.code` and inspect `status`, `details`, or `issues` when
644
+ * present.
614
645
  */
615
646
  integration<T = unknown>(endpoint: string, data?: unknown): Promise<ActionResult<T>>;
616
647
  /**
package/dist/worker.d.ts CHANGED
@@ -2915,6 +2915,48 @@ declare function isFilesVerbPath(method: string, subpath: string): boolean;
2915
2915
  */
2916
2916
  declare function createScopedR2Handler(config: ScopedR2Config): ScopedR2Handler;
2917
2917
 
2918
+ /**
2919
+ * Platform API error normalization — the one chokepoint that turns the
2920
+ * api-worker's error envelope into a render-safe + branch-safe shape.
2921
+ *
2922
+ * The platform emits errors as `{ error: <machine slug>, message?: <human>,
2923
+ * ...details }` (e.g. 402 `{ error: 'insufficient_credits', message:
2924
+ * 'Insufficient credits.', availableCredits, requiredCredits }`; some routes
2925
+ * send the bare slug with no `message` at all, e.g. 409
2926
+ * `{ error: 'owner_connect_not_ready' }`). Consumers must never show the slug
2927
+ * to a person or make an agent parse the sentence — this module separates the
2928
+ * two once, for the integration client, server actions, billing hooks, and the
2929
+ * CLI.
2930
+ */
2931
+ /** One structured validation issue (Zod shape) from a `validation_failed` response. */
2932
+ interface ApiErrorIssue {
2933
+ path?: string[];
2934
+ message: string;
2935
+ code?: string;
2936
+ }
2937
+ /** A platform error response, normalized. */
2938
+ interface NormalizedApiError {
2939
+ /**
2940
+ * Human-readable text, safe to render:
2941
+ * `message ?? non-slug error ?? humanized(slug) ?? slug`.
2942
+ */
2943
+ error: string;
2944
+ /** The machine slug (e.g. 'insufficient_credits') for branching — never render it. */
2945
+ code?: string;
2946
+ /** HTTP status of the response; 0 when no HTTP response arrived (transport failure). */
2947
+ status: number;
2948
+ /** Structured fields the server sent alongside the error (e.g. `availableCredits`). */
2949
+ details?: Record<string, unknown>;
2950
+ /** Zod issues accompanying a `validation_failed` response. */
2951
+ issues?: ApiErrorIssue[];
2952
+ }
2953
+ /**
2954
+ * Normalize a platform error body (parsed JSON, or anything else) plus its
2955
+ * HTTP status into a {@link NormalizedApiError}. Pass status 0 for failures
2956
+ * that never produced an HTTP response.
2957
+ */
2958
+ declare function normalizeApiError(status: number, body: unknown): NormalizedApiError;
2959
+
2918
2960
  /**
2919
2961
  * Server Action Types
2920
2962
  *
@@ -2939,7 +2981,16 @@ type ActionResult<TData = unknown> = {
2939
2981
  } | {
2940
2982
  success: false;
2941
2983
  data?: never;
2984
+ /** Human-readable error, safe to render directly. */
2942
2985
  error: string;
2986
+ /** Machine slug for branching, when the failing tool supplied one. */
2987
+ code?: string;
2988
+ /** HTTP status from an upstream platform request, when applicable. */
2989
+ status?: number;
2990
+ /** Structured fields supplied with the error response. */
2991
+ details?: Record<string, unknown>;
2992
+ /** Validation issues supplied with a `validation_failed` response. */
2993
+ issues?: ApiErrorIssue[];
2943
2994
  };
2944
2995
  /** Shape of the data field for `tools.query`. */
2945
2996
  interface QueryActionData<T = Record<string, unknown>> {
@@ -2994,7 +3045,9 @@ interface ActionTools {
2994
3045
  * api-worker. On success, `result.data` is the integration's response
2995
3046
  * body directly — there is no `.response` wrapper. So an OpenAI call
2996
3047
  * yields `result.data.choices`, a Freepik image call yields
2997
- * `result.data.images`, etc.
3048
+ * `result.data.images`, etc. On failure, `result.error` is human-readable;
3049
+ * branch on `result.code` and inspect `status`, `details`, or `issues` when
3050
+ * present.
2998
3051
  */
2999
3052
  integration<T = unknown>(endpoint: string, data?: unknown): Promise<ActionResult<T>>;
3000
3053
  /**
@@ -5237,15 +5290,11 @@ declare function registerAgentToolRoutes<Env extends AgentToolRouteEnv>(app: Hon
5237
5290
  Bindings: Env;
5238
5291
  }>, options: AgentToolRouteOptions<Env>): void;
5239
5292
 
5240
- /**
5241
- * First-party non-app origins allowed as agent targets on the production app
5242
- * domain. The token minter and the CLI must agree on this policy, so both the
5243
- * set AND the "is production" predicate (appDomain === PRODUCTION_APP_DOMAIN)
5244
- * live here — callers never re-derive either.
5245
- */
5293
+ /** First-party non-app origins retained for callers using the legacy policy shape. */
5246
5294
  declare const PRODUCTION_OFFICIAL_AGENT_ORIGINS: readonly string[];
5247
5295
  interface AgentTargetPolicy {
5248
5296
  appDomain: string;
5297
+ platformDomain?: string;
5249
5298
  allowLoopback?: boolean;
5250
5299
  }
5251
5300
  /** Normalize an agent target only when it is an exact trusted origin. */
@@ -5400,4 +5449,4 @@ declare const MAX_LOG_TEXT_LENGTH: number;
5400
5449
  */
5401
5450
  declare function workerErrorHandler(prefix: string, respond?: (c: Context) => Response): ErrorHandler;
5402
5451
 
5403
- export { ACCOUNT_STORAGE_LIMIT_BYTES, ACTION_ROUTES_BEARER_GUARD_MIGRATION_ID, ACTION_TOOLS_DELETE_WHERE_MIGRATION_ID, AGENT_TOKEN_SCOPE, AGENT_TOOL_REQUEST_BODY_CAP, AGENT_TOOL_RESPONSE_BODY_CAP, AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, ANONYMOUS_USER_ID_PREFIX, APP_ID_RE, APP_LOG_EVENT_KEYS, APP_NAME_RULES, ASSET_NOT_FOUND_HANDLING_VALUES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type AgentTargetPolicy, type AgentToolAccessResult, type AgentToolRouteEnv, type AgentToolRouteOptions, type ApiWorkerEnv, type AppLogEvent, type AppLogEventKey, type AppLogsResponse, type AppMembership, type AppMigrationIdsValidation, type AppNameResolution, type AppNameValidation, type AssetNotFoundHandling, type AuthWorkerEnv, Awareness, type AwarenessState, type AwarenessStates, BASE_USERS_SCHEMA, BROWSER_PROXY_ROUTES, BUILD_INJECTED_APP_ID_MIGRATION_ID, BUILT_IN_TOOLS, type BaseMessage, BaseRoom, type BindingJsonValue, CHANNELS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientMessage, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ComposioToolsOptions, type ConnectionAttachment, 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_DELETE_WHERE_LIMIT, DEFAULT_DO_MANIFEST, DEFAULT_QUERY_LIMIT, DEPLOYED_APPS_DEFAULTS, 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 DoMigrationDirective, type DoMigrationPlan, type ExistingDOBinding, type GetActionData, type HandlerContext, type Job, type JobContext, JobRoom, type JobRoomConfig, type JobStatus, type JwtClaims, type JwtVerifierConfig, type KnowledgeAddOptions, type KnowledgeAddResult, type KnowledgeClient, type KnowledgeEnv, KnowledgeError, type KnowledgeItem, type KnowledgeListOptions, type KnowledgeListResult, type KnowledgeSearchChunk, type KnowledgeSearchOptions, type KnowledgeSearchResult, type KnowledgeStatus, LOG_LEVELS, type LogLevel, MAX_APP_FILE_BYTES, MAX_BINDING_NAME_LENGTH, MAX_DELETE_WHERE_LIMIT, MAX_DEPLOY_ASSET_FILE_BYTES, MAX_ENV_VAR_BYTES, MAX_LOG_TEXT_LENGTH, 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, PRODUCTION_OFFICIAL_AGENT_ORIGINS, type PermissionContext, type PermissionLevel, type PlatformWorkerEnv, type PrefixResult, type PresencePeer, PresenceRoom, type ProtocolMessage, type ProxyRoute, type QueryActionData, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, RECORD_NOT_FOUND, REGISTRY_INSTANCE, RELEASE_STAMP_PATH, REPO_STORE_LIMIT_BYTES, REQUIRED_COMPATIBILITY_FLAGS, RESERVED_BINDING_NAMES, RESERVED_RUN_WORKER_FIRST, RESOURCE_ID_RE, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, RegistryClientError, type ResolvedColumn, type ResolvedDeepSpaceAgentModel, type RolePermissions, type RunMigrationsResult, SDK_RUN_WORKER_FIRST, SECRET_NAME_RE, SECURE_ROOM_BOUNDARIES_MIGRATION_ID, SESSION_COOKIE, STRICT_APP_ID_RE, SYSTEM_ASSIGNED_COLUMNS, SYSTEM_COLLECTIONS, SYSTEM_MAINTAINED_COLUMNS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedKnowledgeClient, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ScreenshotEnv, type ScreenshotResult, type ServerMessage, 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, type UserToolExecutorEnv, type ValidationError, type VerifiedAuth, type VerifyOutcome, type VerifyResult, type Viewport, WORKER_OWNED_NOT_FOUND_MIGRATION_ID, YjsRoom, agentTokenIssuer, apiWorkerFetch, appendMessage, applyAiToolDefaults, applySlidingWindow, armCronRoom, authWorkerFetch, authenticatedRoomRequest, bindingManifestFromOutputConfig, buildCronContext, buildTableSelect, buildUiParts, callRegistry, canCreate, canDelete, canRead, canUpdate, capToolResultSize, captureScreenshot, checkFieldPermissions, checkUnclaimedOwnerTransition, clientBuild, coerceValue, collectionTableName, columnId, composioTools, computeDoMigration, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, createUserToolExecutor, dataToColumnValues, decodeJwtPayload, deepSpaceAgentErrorSummary, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, enqueueJob, epochSeconds, folderFilter, formatBytes, getChat, getDeepSpaceAIModel, getMessageType, getRolePermissions, handleAwarenessMessage, handleSyncMessage, hasContent, isAnonymousUserId, isAssetNotFoundHandling, isAutoProvision, isFilesVerbPath, isOwner, isPlatformReservedPath, isTestAccountClaims, isTestAccountEmail, isTestAccountTier, knowledge, lintSchema, lintSchemaSet, lintSchemas, listDeepSpaceAgentModels, loadMessages, logEventText, loggableError, makeDefaultSummarizer, matchOrigin, meterAi, meterUsage, meterVectorize, mintAppId, mintUlid, noopPermissionContext, normalizeAgentTargetOrigin, normalizeKnowledgeFolder, parseQuotaLimit, platformCorsPatterns, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, readVarUint, readVarUint8Array, registerAgentToolRoutes, registerDeepSpaceDocumentation, registryErrorJson, registryStub, resolveAppMembership, resolveAppName, resolveAppRole, resolveColumn, resolveCompatibilityFlags, resolveDeepSpaceAgentModel, rowToData, runMigrations, serverBuild, storageLimitForTier, storageQuotaMessage, streamDeepSpaceAgent, timingSafeEqualHex, timingSafeEqualStrings, toUint8Array, totalChars, truncateLogText, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppMigrationIds, validateAppName, validateBindingManifest, validateDoManifest, verifyAgentToken, verifyJwt, workerErrorHandler, writeVarUint, writeVarUint8Array };
5452
+ export { ACCOUNT_STORAGE_LIMIT_BYTES, ACTION_ROUTES_BEARER_GUARD_MIGRATION_ID, ACTION_TOOLS_DELETE_WHERE_MIGRATION_ID, AGENT_TOKEN_SCOPE, AGENT_TOOL_REQUEST_BODY_CAP, AGENT_TOOL_RESPONSE_BODY_CAP, AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, ANONYMOUS_USER_ID_PREFIX, APP_ID_RE, APP_LOG_EVENT_KEYS, APP_NAME_RULES, ASSET_NOT_FOUND_HANDLING_VALUES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type AgentTargetPolicy, type AgentToolAccessResult, type AgentToolRouteEnv, type AgentToolRouteOptions, type ApiErrorIssue, type ApiWorkerEnv, type AppLogEvent, type AppLogEventKey, type AppLogsResponse, type AppMembership, type AppMigrationIdsValidation, type AppNameResolution, type AppNameValidation, type AssetNotFoundHandling, type AuthWorkerEnv, Awareness, type AwarenessState, type AwarenessStates, BASE_USERS_SCHEMA, BROWSER_PROXY_ROUTES, BUILD_INJECTED_APP_ID_MIGRATION_ID, BUILT_IN_TOOLS, type BaseMessage, BaseRoom, type BindingJsonValue, CHANNELS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientMessage, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ComposioToolsOptions, type ConnectionAttachment, 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_DELETE_WHERE_LIMIT, DEFAULT_DO_MANIFEST, DEFAULT_QUERY_LIMIT, DEPLOYED_APPS_DEFAULTS, 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 DoMigrationDirective, type DoMigrationPlan, type ExistingDOBinding, type GetActionData, type HandlerContext, type Job, type JobContext, JobRoom, type JobRoomConfig, type JobStatus, type JwtClaims, type JwtVerifierConfig, type KnowledgeAddOptions, type KnowledgeAddResult, type KnowledgeClient, type KnowledgeEnv, KnowledgeError, type KnowledgeItem, type KnowledgeListOptions, type KnowledgeListResult, type KnowledgeSearchChunk, type KnowledgeSearchOptions, type KnowledgeSearchResult, type KnowledgeStatus, LOG_LEVELS, type LogLevel, MAX_APP_FILE_BYTES, MAX_BINDING_NAME_LENGTH, MAX_DELETE_WHERE_LIMIT, MAX_DEPLOY_ASSET_FILE_BYTES, MAX_ENV_VAR_BYTES, MAX_LOG_TEXT_LENGTH, 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 NormalizedApiError, PRODUCTION_OFFICIAL_AGENT_ORIGINS, type PermissionContext, type PermissionLevel, type PlatformWorkerEnv, type PrefixResult, type PresencePeer, PresenceRoom, type ProtocolMessage, type ProxyRoute, type QueryActionData, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, RECORD_NOT_FOUND, REGISTRY_INSTANCE, RELEASE_STAMP_PATH, REPO_STORE_LIMIT_BYTES, REQUIRED_COMPATIBILITY_FLAGS, RESERVED_BINDING_NAMES, RESERVED_RUN_WORKER_FIRST, RESOURCE_ID_RE, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, RegistryClientError, type ResolvedColumn, type ResolvedDeepSpaceAgentModel, type RolePermissions, type RunMigrationsResult, SDK_RUN_WORKER_FIRST, SECRET_NAME_RE, SECURE_ROOM_BOUNDARIES_MIGRATION_ID, SESSION_COOKIE, STRICT_APP_ID_RE, SYSTEM_ASSIGNED_COLUMNS, SYSTEM_COLLECTIONS, SYSTEM_MAINTAINED_COLUMNS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedKnowledgeClient, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ScreenshotEnv, type ScreenshotResult, type ServerMessage, 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, type UserToolExecutorEnv, type ValidationError, type VerifiedAuth, type VerifyOutcome, type VerifyResult, type Viewport, WORKER_OWNED_NOT_FOUND_MIGRATION_ID, YjsRoom, agentTokenIssuer, apiWorkerFetch, appendMessage, applyAiToolDefaults, applySlidingWindow, armCronRoom, authWorkerFetch, authenticatedRoomRequest, bindingManifestFromOutputConfig, buildCronContext, buildTableSelect, buildUiParts, callRegistry, canCreate, canDelete, canRead, canUpdate, capToolResultSize, captureScreenshot, checkFieldPermissions, checkUnclaimedOwnerTransition, clientBuild, coerceValue, collectionTableName, columnId, composioTools, computeDoMigration, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, createUserToolExecutor, dataToColumnValues, decodeJwtPayload, deepSpaceAgentErrorSummary, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, enqueueJob, epochSeconds, folderFilter, formatBytes, getChat, getDeepSpaceAIModel, getMessageType, getRolePermissions, handleAwarenessMessage, handleSyncMessage, hasContent, isAnonymousUserId, isAssetNotFoundHandling, isAutoProvision, isFilesVerbPath, isOwner, isPlatformReservedPath, isTestAccountClaims, isTestAccountEmail, isTestAccountTier, knowledge, lintSchema, lintSchemaSet, lintSchemas, listDeepSpaceAgentModels, loadMessages, logEventText, loggableError, makeDefaultSummarizer, matchOrigin, meterAi, meterUsage, meterVectorize, mintAppId, mintUlid, noopPermissionContext, normalizeAgentTargetOrigin, normalizeApiError, normalizeKnowledgeFolder, parseQuotaLimit, platformCorsPatterns, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, readVarUint, readVarUint8Array, registerAgentToolRoutes, registerDeepSpaceDocumentation, registryErrorJson, registryStub, resolveAppMembership, resolveAppName, resolveAppRole, resolveColumn, resolveCompatibilityFlags, resolveDeepSpaceAgentModel, rowToData, runMigrations, serverBuild, storageLimitForTier, storageQuotaMessage, streamDeepSpaceAgent, timingSafeEqualHex, timingSafeEqualStrings, toUint8Array, totalChars, truncateLogText, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppMigrationIds, validateAppName, validateBindingManifest, validateDoManifest, verifyAgentToken, verifyJwt, workerErrorHandler, writeVarUint, writeVarUint8Array };
package/dist/worker.js CHANGED
@@ -10537,10 +10537,13 @@ function normalizeAgentTargetOrigin(value, policy) {
10537
10537
  return policy.allowLoopback && ["http:", "https:"].includes(url.protocol) ? url.origin : null;
10538
10538
  }
10539
10539
  if (url.protocol !== "https:" || url.port) return null;
10540
- if (policy.appDomain.toLowerCase() === PRODUCTION_APP_DOMAIN && PRODUCTION_OFFICIAL_AGENT_ORIGINS.includes(url.origin)) {
10540
+ const appDomain = policy.appDomain.toLowerCase();
10541
+ const platformDomain = policy.platformDomain?.toLowerCase();
10542
+ const officialAdminOrigin = platformDomain ? `https://admin.${platformDomain}` : appDomain === PRODUCTION_APP_DOMAIN ? PRODUCTION_OFFICIAL_AGENT_ORIGINS[0] : null;
10543
+ if (url.origin === officialAdminOrigin) {
10541
10544
  return url.origin;
10542
10545
  }
10543
- const suffix = `.${policy.appDomain.toLowerCase()}`;
10546
+ const suffix = `.${appDomain}`;
10544
10547
  if (!hostname.endsWith(suffix)) return null;
10545
10548
  const label = hostname.slice(0, -suffix.length);
10546
10549
  return !label.includes(".") && validateAppName(label).valid ? url.origin : null;
@@ -10549,6 +10552,49 @@ function normalizeAgentTargetOrigin(value, policy) {
10549
10552
  // src/shared/auth-session.ts
10550
10553
  var SESSION_COOKIE = "__Secure-better-auth.session_token";
10551
10554
 
10555
+ // src/shared/api-error.ts
10556
+ var SLUG_RE = /^[a-z0-9]+(?:[_.-][a-z0-9]+)*$/;
10557
+ var HUMAN_MESSAGES = {
10558
+ owner_connect_not_ready: "This app isn't ready to accept payments yet \u2014 the app owner needs to finish payment setup.",
10559
+ invalid_json: "The request body was not valid JSON.",
10560
+ invalid_body: "The request body is invalid.",
10561
+ invalid_product_id: "Invalid product id.",
10562
+ duplicate_product_id: "Duplicate product id.",
10563
+ unknown_product: "Unknown product.",
10564
+ too_many_products: "Too many products declared.",
10565
+ invalid_amount: "Invalid amount.",
10566
+ invalid_name: "Invalid product name.",
10567
+ invalid_description: "Invalid product description.",
10568
+ unsupported_currency: "Unsupported currency.",
10569
+ unknown_app: "Unknown app.",
10570
+ not_app_owner: "Only the app owner (or a collaborator) can do this.",
10571
+ invalid_return_url: "Invalid return URL.",
10572
+ invalid_cancel_url: "Invalid cancel URL.",
10573
+ unknown_plan: "Unknown subscription plan.",
10574
+ unknown_price: "No price is configured for that billing interval.",
10575
+ no_subscription: "No subscription found for this account."
10576
+ };
10577
+ function normalizeApiError(status, body) {
10578
+ const payload = body !== null && typeof body === "object" ? body : {};
10579
+ const rawError = typeof payload.error === "string" ? payload.error : void 0;
10580
+ const message = typeof payload.message === "string" ? payload.message : void 0;
10581
+ const humanError = rawError !== void 0 && !SLUG_RE.test(rawError) ? rawError : void 0;
10582
+ const code = rawError !== void 0 && SLUG_RE.test(rawError) ? rawError : typeof payload.code === "string" && SLUG_RE.test(payload.code) ? payload.code : void 0;
10583
+ const details = {};
10584
+ for (const [key, value] of Object.entries(payload)) {
10585
+ if (key === "success" || key === "error" || key === "message" || key === "issues" || key === "code")
10586
+ continue;
10587
+ details[key] = value;
10588
+ }
10589
+ return {
10590
+ error: message ?? humanError ?? (code !== void 0 ? HUMAN_MESSAGES[code] : void 0) ?? rawError ?? `Request failed (${status})`,
10591
+ ...code !== void 0 ? { code } : {},
10592
+ status,
10593
+ ...Object.keys(details).length > 0 ? { details } : {},
10594
+ ...Array.isArray(payload.issues) ? { issues: payload.issues } : {}
10595
+ };
10596
+ }
10597
+
10552
10598
  // src/server/worker-error.ts
10553
10599
  function workerErrorHandler(prefix, respond = (c) => c.text("Internal Server Error", 500)) {
10554
10600
  return (err, c) => {
@@ -10736,6 +10782,7 @@ export {
10736
10782
  mintUlid,
10737
10783
  noopPermissionContext,
10738
10784
  normalizeAgentTargetOrigin,
10785
+ normalizeApiError,
10739
10786
  normalizeKnowledgeFolder,
10740
10787
  parseQuotaLimit,
10741
10788
  platformCorsPatterns,