deepspace 0.35.0 → 0.37.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
@@ -1572,7 +1572,7 @@ declare function armCronRoom(ctx: {
1572
1572
  * Persistent job queue with serial execution, progress, cancellation and retries.
1573
1573
  * Jobs run inside alarms unless listed in `backgroundJobTypes`.
1574
1574
  * Use `ctx.continue` to save a checkpoint for the next run.
1575
- * After a restart, running jobs older than 16 minutes are retried or failed.
1575
+ * After a restart, interrupted running jobs are retried or failed.
1576
1576
  */
1577
1577
 
1578
1578
  type JobStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'canceled';
@@ -1696,7 +1696,7 @@ declare abstract class JobRoom<E = Record<string, unknown>, P = unknown, R = unk
1696
1696
  private drainDueJobs;
1697
1697
  private executeJob;
1698
1698
  private makeContext;
1699
- private readStatus;
1699
+ private readRunState;
1700
1700
  /** Reauthorize every live event so role revocation does not leave a stale reader. */
1701
1701
  protected broadcast(message: ServerMessage, exclude?: WebSocket): void;
1702
1702
  private resolveAccess;
@@ -4479,10 +4479,28 @@ interface DeepSpaceAuthConfig {
4479
4479
  keyId: string;
4480
4480
  privateKey: string;
4481
4481
  };
4482
+ /**
4483
+ * Extra OAuth client ids whose ID tokens may sign in through Better Auth's
4484
+ * `POST /sign-in/social` `{ provider, idToken }`: a native app's own Google
4485
+ * iOS/web client ids, or its iOS bundle id for Sign in with Apple. Tokens
4486
+ * are still checked for Google's or Apple's signature, issuer and expiry.
4487
+ * A provider listed here without its web credentials above accepts ID
4488
+ * tokens only; it can't start a browser sign-in.
4489
+ */
4490
+ nativeIdTokenAudiences?: {
4491
+ google?: string[];
4492
+ apple?: string[];
4493
+ };
4482
4494
  /** Enable email/password authentication */
4483
4495
  emailAndPassword?: boolean;
4484
4496
  /** Trusted origins for CORS */
4485
4497
  trustedOrigins?: string[];
4498
+ /**
4499
+ * Where a failed OAuth callback lands when the flow can't be tied back to
4500
+ * its own error URL (for example its state expired). Without it Better Auth
4501
+ * shows its own developer-facing error page.
4502
+ */
4503
+ errorURL?: string;
4486
4504
  /**
4487
4505
  * Server-owned fields to add to Better Auth's user model. Use `input: false`
4488
4506
  * for values that may only be populated by a database hook, and
@@ -5523,8 +5541,11 @@ declare function createDeepSpaceAuth(config: DeepSpaceAuthConfig): better_auth.A
5523
5541
  };
5524
5542
  };
5525
5543
  } | undefined;
5526
- socialProviders: Parameters<typeof betterAuth>[0]["socialProviders"];
5527
5544
  trustedOrigins: string[];
5545
+ onAPIError?: {
5546
+ errorURL: string;
5547
+ } | undefined;
5548
+ socialProviders: Parameters<typeof betterAuth>[0]["socialProviders"];
5528
5549
  user?: {
5529
5550
  additionalFields: {
5530
5551
  [x: string]: better_auth.DBFieldAttribute;
@@ -5636,6 +5657,17 @@ interface ExpoAuthBridgeOptions {
5636
5657
  declare function nativeAuthStart(request: Request, env: ExpoAuthWorkerEnv, options?: ExpoAuthBridgeOptions): Response;
5637
5658
  declare function nativeAuthCallback(request: Request, _env: ExpoAuthWorkerEnv, options?: ExpoAuthBridgeOptions): Response;
5638
5659
  declare function nativeAuthExchange(request: Request, env: ExpoAuthWorkerEnv): Promise<Response>;
5660
+ /**
5661
+ * Native sign-in with the platform's own Google or Apple SDK. The app sends
5662
+ * the ID token it received; the auth worker checks the token's signature,
5663
+ * issuer, expiry and audience (one of the plane's configured native client
5664
+ * ids) and accepts each token only once. A nonce, when the app sends one, is
5665
+ * checked against the token too, but it isn't a replay defense: the app
5666
+ * chooses it. Returns the same `{ sessionToken, accessToken }` as
5667
+ * `nativeAuthExchange`. Apple only shares a person's name on their first
5668
+ * sign-in, so the app may pass it along as `user.name`.
5669
+ */
5670
+ declare function nativeAuthIdToken(request: Request, env: ExpoAuthWorkerEnv): Promise<Response>;
5639
5671
  declare function nativeAuthToken(request: Request, env: ExpoAuthWorkerEnv): Promise<Response>;
5640
5672
  declare function nativeAuthMe(request: Request, env: ExpoAuthWorkerEnv): Promise<Response>;
5641
5673
  declare function nativeAuthSignOut(request: Request, env: ExpoAuthWorkerEnv): Promise<Response>;
@@ -5796,4 +5828,4 @@ declare const MAX_LOG_TEXT_LENGTH: number;
5796
5828
  */
5797
5829
  declare function workerErrorHandler(prefix: string, respond?: (c: Context) => Response): ErrorHandler;
5798
5830
 
5799
- 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, AI_SDK_7_MIGRATION_ID, 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, BodyTooLargeError, 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 DeepSpaceUserCreateContext, type DoMigrationDirective, type DoMigrationPlan, type ExistingDOBinding, type ExpoAuthBridgeOptions, type ExpoAuthWorkerEnv, FILES_SESSION_COOKIE_READS_MIGRATION_ID, 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, PLANES, PRODUCTION_OFFICIAL_AGENT_ORIGINS, type PermissionContext, type PermissionLevel, type PlaneName, type PlaneUrls, 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, SANDBOX_SCOPES, SANDBOX_SCOPE_HEADER, 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, type SandboxFile, SandboxFileError, type SandboxFileList, type SandboxFilesClient, type SandboxFilesOptions, type SandboxScope, type SandboxUploadOptions, 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, callableFromSandbox, canCreate, canDelete, canRead, canUpdate, capToolResultSize, captureScreenshot, checkFieldPermissions, checkUnclaimedOwnerTransition, clientBuild, codeExecutionTool, 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, forwardSandboxContainer, getChat, getDeepSpaceAIModel, getMessageType, getRolePermissions, handleAwarenessMessage, handleSyncMessage, hasContent, isAnonymousUserId, isAssetNotFoundHandling, isAutoProvision, isFilesVerbPath, isOwner, isPlatformReservedPath, isRestrictedPlane, isTestAccountClaims, isTestAccountEmail, isTestAccountTier, knowledge, lintSchema, lintSchemaSet, lintSchemas, listDeepSpaceAgentModels, loadMessages, logEventText, loggableError, makeDefaultSummarizer, matchOrigin, meterAi, meterUsage, meterVectorize, mintAppId, mintUlid, nativeAuthCallback, nativeAuthExchange, nativeAuthMe, nativeAuthSignOut, nativeAuthStart, nativeAuthToken, noopPermissionContext, normalizeAgentTargetOrigin, normalizeApiError, normalizeKnowledgeFolder, parseQuotaLimit, platformCorsPatterns, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, readBoundedBodyText, readVarUint, readVarUint8Array, registerAgentToolRoutes, registerDeepSpaceDocumentation, registryErrorJson, registryStub, resolveAppMembership, resolveAppName, resolveAppRole, resolveColumn, resolveCompatibilityFlags, resolveDeepSpaceAgentModel, resolveSessionReadAuth, reuseSandbox, rowToData, runMigrations, sandboxFiles, sandboxOutputs, sandboxUpload, serverBuild, storageLimitForTier, storageQuotaMessage, streamDeepSpaceAgent, timingSafeEqualHex, timingSafeEqualStrings, toUint8Array, totalChars, truncateLogText, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppMigrationIds, validateAppName, validateBindingManifest, validateDoManifest, verifyAgentToken, verifyJwt, workerErrorHandler, writeVarUint, writeVarUint8Array };
5831
+ 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, AI_SDK_7_MIGRATION_ID, 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, BodyTooLargeError, 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 DeepSpaceUserCreateContext, type DoMigrationDirective, type DoMigrationPlan, type ExistingDOBinding, type ExpoAuthBridgeOptions, type ExpoAuthWorkerEnv, FILES_SESSION_COOKIE_READS_MIGRATION_ID, 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, PLANES, PRODUCTION_OFFICIAL_AGENT_ORIGINS, type PermissionContext, type PermissionLevel, type PlaneName, type PlaneUrls, 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, SANDBOX_SCOPES, SANDBOX_SCOPE_HEADER, 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, type SandboxFile, SandboxFileError, type SandboxFileList, type SandboxFilesClient, type SandboxFilesOptions, type SandboxScope, type SandboxUploadOptions, 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, callableFromSandbox, canCreate, canDelete, canRead, canUpdate, capToolResultSize, captureScreenshot, checkFieldPermissions, checkUnclaimedOwnerTransition, clientBuild, codeExecutionTool, 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, forwardSandboxContainer, getChat, getDeepSpaceAIModel, getMessageType, getRolePermissions, handleAwarenessMessage, handleSyncMessage, hasContent, isAnonymousUserId, isAssetNotFoundHandling, isAutoProvision, isFilesVerbPath, isOwner, isPlatformReservedPath, isRestrictedPlane, isTestAccountClaims, isTestAccountEmail, isTestAccountTier, knowledge, lintSchema, lintSchemaSet, lintSchemas, listDeepSpaceAgentModels, loadMessages, logEventText, loggableError, makeDefaultSummarizer, matchOrigin, meterAi, meterUsage, meterVectorize, mintAppId, mintUlid, nativeAuthCallback, nativeAuthExchange, nativeAuthIdToken, nativeAuthMe, nativeAuthSignOut, nativeAuthStart, nativeAuthToken, noopPermissionContext, normalizeAgentTargetOrigin, normalizeApiError, normalizeKnowledgeFolder, parseQuotaLimit, platformCorsPatterns, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, readBoundedBodyText, readVarUint, readVarUint8Array, registerAgentToolRoutes, registerDeepSpaceDocumentation, registryErrorJson, registryStub, resolveAppMembership, resolveAppName, resolveAppRole, resolveColumn, resolveCompatibilityFlags, resolveDeepSpaceAgentModel, resolveSessionReadAuth, reuseSandbox, rowToData, runMigrations, sandboxFiles, sandboxOutputs, sandboxUpload, 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
@@ -4660,7 +4660,7 @@ var JobRoom = class extends BaseRoom {
4660
4660
  `);
4661
4661
  this.sql.exec(`CREATE INDEX IF NOT EXISTS jobs_status_next_run ON jobs (status, next_run_at)`);
4662
4662
  this.sql.exec(`CREATE INDEX IF NOT EXISTS jobs_completed_at ON jobs (completed_at)`);
4663
- this.recoverStuckRunning();
4663
+ this.recoverStuckRunning(true);
4664
4664
  this.scheduleNextAlarm();
4665
4665
  }
4666
4666
  // ==========================================================================
@@ -4906,8 +4906,7 @@ var JobRoom = class extends BaseRoom {
4906
4906
  }
4907
4907
  async executeJob(row) {
4908
4908
  const startedAt = row.started_at ?? (/* @__PURE__ */ new Date()).toISOString();
4909
- const attemptsBefore = row.attempts;
4910
- const attempt = attemptsBefore + 1;
4909
+ const attempt = row.attempts + 1;
4911
4910
  this.sql.exec(
4912
4911
  `UPDATE jobs SET status = 'running', started_at = ?, attempts = ? WHERE id = ?`,
4913
4912
  startedAt,
@@ -4927,7 +4926,7 @@ var JobRoom = class extends BaseRoom {
4927
4926
  let result;
4928
4927
  let errorMessage;
4929
4928
  try {
4930
- const ctx = this.makeContext(row.id, controller.signal);
4929
+ const ctx = this.makeContext(row.id, attempt, controller.signal);
4931
4930
  result = await this.onJob(job, ctx);
4932
4931
  if (this.continueState) outcome = "continued";
4933
4932
  } catch (e) {
@@ -4937,8 +4936,8 @@ var JobRoom = class extends BaseRoom {
4937
4936
  } finally {
4938
4937
  this.inFlight.delete(row.id);
4939
4938
  }
4940
- const currentStatus = this.readStatus(row.id);
4941
- if (currentStatus !== "running") {
4939
+ const current = this.readRunState(row.id);
4940
+ if (current?.status !== "running" || current.attempts !== attempt) {
4942
4941
  this.continueState = null;
4943
4942
  return;
4944
4943
  }
@@ -5017,9 +5016,11 @@ var JobRoom = class extends BaseRoom {
5017
5016
  const updated = this.getJobById(row.id);
5018
5017
  if (updated) this.broadcast(serverBuild.jobFailed(updated));
5019
5018
  }
5020
- makeContext(jobId, signal) {
5019
+ makeContext(jobId, attempt, signal) {
5021
5020
  return {
5022
5021
  progress: (value, message) => {
5022
+ const current = this.readRunState(jobId);
5023
+ if (current?.status !== "running" || current.attempts !== attempt) return;
5023
5024
  const clamped = Math.max(0, Math.min(1, value));
5024
5025
  this.sql.exec(
5025
5026
  `UPDATE jobs SET progress = ?, progress_message = ? WHERE id = ?`,
@@ -5039,9 +5040,9 @@ var JobRoom = class extends BaseRoom {
5039
5040
  signal
5040
5041
  };
5041
5042
  }
5042
- readStatus(jobId) {
5043
- const row = this.sql.exec(`SELECT status FROM jobs WHERE id = ?`, jobId).toArray()[0];
5044
- return row?.status ?? null;
5043
+ readRunState(jobId) {
5044
+ const row = this.sql.exec(`SELECT status, attempts FROM jobs WHERE id = ?`, jobId).toArray()[0];
5045
+ return row ?? null;
5045
5046
  }
5046
5047
  /** Reauthorize every live event so role revocation does not leave a stale reader. */
5047
5048
  broadcast(message, exclude) {
@@ -5099,11 +5100,12 @@ var JobRoom = class extends BaseRoom {
5099
5100
  if (targets.length === 0) return;
5100
5101
  this.state.storage.setAlarm(Math.max(Math.min(...targets), now + 50));
5101
5102
  }
5102
- recoverStuckRunning() {
5103
+ recoverStuckRunning(onStartup = false) {
5103
5104
  const cutoff = new Date(Date.now() - RUNNING_STALE_MS).toISOString();
5104
5105
  const stuck = this.sql.exec(
5105
5106
  `SELECT id, attempts, max_attempts FROM jobs
5106
- WHERE status = 'running' AND (started_at IS NULL OR started_at <= ?)`,
5107
+ WHERE status = 'running' AND (? = 1 OR started_at IS NULL OR started_at <= ?)`,
5108
+ onStartup ? 1 : 0,
5107
5109
  cutoff
5108
5110
  ).toArray();
5109
5111
  for (const r of stuck) {
@@ -10484,8 +10486,12 @@ import { organization, twoFactor } from "better-auth/plugins";
10484
10486
  import { SignJWT, importPKCS8 } from "jose";
10485
10487
  function createDeepSpaceAuth(config) {
10486
10488
  const socialProviders = {};
10489
+ const googleAudiences = config.nativeIdTokenAudiences?.google ?? [];
10490
+ const appleAudiences = config.nativeIdTokenAudiences?.apple ?? [];
10487
10491
  if (config.google) {
10488
- socialProviders.google = config.google;
10492
+ socialProviders.google = googleAudiences.length ? { ...config.google, clientId: [config.google.clientId, ...googleAudiences] } : config.google;
10493
+ } else if (googleAudiences.length) {
10494
+ socialProviders.google = { clientId: googleAudiences, clientSecret: "" };
10489
10495
  }
10490
10496
  if (config.github) {
10491
10497
  socialProviders.github = config.github;
@@ -10495,16 +10501,27 @@ function createDeepSpaceAuth(config) {
10495
10501
  }
10496
10502
  if (config.apple) {
10497
10503
  const apple = config.apple;
10504
+ const audience = appleAudiences.length ? [apple.clientId, ...appleAudiences] : void 0;
10498
10505
  socialProviders.apple = async () => {
10499
10506
  try {
10500
- return { clientId: apple.clientId, clientSecret: await generateAppleClientSecret(apple) };
10507
+ return {
10508
+ clientId: apple.clientId,
10509
+ clientSecret: await generateAppleClientSecret(apple),
10510
+ ...audience ? { audience } : {}
10511
+ };
10501
10512
  } catch (err) {
10502
10513
  console.error(
10503
10514
  `[deepspace] failed to mint Apple client secret; Apple sign-in disabled: ${loggableError(err)}`
10504
10515
  );
10505
- return { clientId: apple.clientId, clientSecret: "" };
10516
+ return { clientId: apple.clientId, clientSecret: "", ...audience ? { audience } : {} };
10506
10517
  }
10507
10518
  };
10519
+ } else if (appleAudiences.length) {
10520
+ socialProviders.apple = {
10521
+ clientId: appleAudiences[0],
10522
+ clientSecret: "",
10523
+ audience: appleAudiences
10524
+ };
10508
10525
  }
10509
10526
  return betterAuth({
10510
10527
  database: config.database,
@@ -10525,6 +10542,7 @@ function createDeepSpaceAuth(config) {
10525
10542
  },
10526
10543
  ...config.userAdditionalFields ? { user: { additionalFields: config.userAdditionalFields } } : {},
10527
10544
  socialProviders,
10545
+ ...config.errorURL ? { onAPIError: { errorURL: config.errorURL } } : {},
10528
10546
  trustedOrigins: config.trustedOrigins ?? [
10529
10547
  "https://deep.space",
10530
10548
  "https://*.deep.space",
@@ -10976,13 +10994,62 @@ async function nativeAuthExchange(request2, env) {
10976
10994
  if (!exchanged || typeof exchanged.sessionToken !== "string") {
10977
10995
  return Response.json({ error: "The auth service did not issue a session." }, { status: 502 });
10978
10996
  }
10997
+ return nativeSession(env, exchanged.sessionToken);
10998
+ }
10999
+ var ID_TOKEN_PROVIDERS = /* @__PURE__ */ new Set(["google", "apple"]);
11000
+ async function nativeAuthIdToken(request2, env) {
11001
+ const body = await request2.json().catch(() => null);
11002
+ if (!body || typeof body.provider !== "string" || !ID_TOKEN_PROVIDERS.has(body.provider) || typeof body.idToken !== "string" || body.idToken.length < 16 || body.idToken.length > 8192 || body.nonce !== void 0 && (typeof body.nonce !== "string" || body.nonce.length < 16 || body.nonce.length > 256)) {
11003
+ return Response.json({ error: "A Google or Apple ID token is required." }, { status: 400 });
11004
+ }
11005
+ const name = body.user?.name;
11006
+ const text = (value) => typeof value === "string" ? value.trim().slice(0, 100) : void 0;
11007
+ const firstName = text(name?.firstName);
11008
+ const lastName = text(name?.lastName);
11009
+ let signIn;
11010
+ try {
11011
+ signIn = await authWorkerFetch(env, "/api/auth/sign-in/social", {
11012
+ method: "POST",
11013
+ headers: { "Content-Type": "application/json" },
11014
+ body: JSON.stringify({
11015
+ provider: body.provider,
11016
+ idToken: {
11017
+ token: body.idToken,
11018
+ ...typeof body.nonce === "string" ? { nonce: body.nonce } : {},
11019
+ ...firstName || lastName ? { user: { name: { firstName, lastName } } } : {}
11020
+ }
11021
+ })
11022
+ });
11023
+ } catch {
11024
+ return Response.json({ error: "The authentication service is unavailable." }, { status: 502 });
11025
+ }
11026
+ if (!signIn.ok) {
11027
+ if (signIn.status === 404) {
11028
+ return Response.json({ error: "Signing in this way is not set up for this app." }, { status: 503 });
11029
+ }
11030
+ if (signIn.status === 429) {
11031
+ return Response.json({ error: "Too many sign-in attempts. Try again shortly." }, { status: 429 });
11032
+ }
11033
+ const rejected = signIn.status >= 400 && signIn.status < 500;
11034
+ return Response.json(
11035
+ { error: rejected ? "That sign-in could not be verified. Please try again." : "The authentication service is unavailable." },
11036
+ { status: rejected ? 401 : 502 }
11037
+ );
11038
+ }
11039
+ const signedIn = await signIn.json().catch(() => null);
11040
+ if (!signedIn || typeof signedIn.token !== "string") {
11041
+ return Response.json({ error: "The auth service did not issue a session." }, { status: 502 });
11042
+ }
11043
+ return nativeSession(env, signedIn.token);
11044
+ }
11045
+ async function nativeSession(env, sessionToken) {
10979
11046
  let tokenResponse = null;
10980
11047
  let token = null;
10981
11048
  for (let attempt = 0; attempt < 2; attempt += 1) {
10982
11049
  try {
10983
11050
  tokenResponse = await authWorkerFetch(env, "/api/auth/token", {
10984
11051
  method: "POST",
10985
- headers: { Cookie: `${SESSION_COOKIE}=${encodeURIComponent(exchanged.sessionToken)}` }
11052
+ headers: { Cookie: `${SESSION_COOKIE}=${encodeURIComponent(sessionToken)}` }
10986
11053
  });
10987
11054
  } catch {
10988
11055
  tokenResponse = null;
@@ -11006,7 +11073,7 @@ async function nativeAuthExchange(request2, env) {
11006
11073
  return Response.json({ error: "The auth service did not issue an access token." }, { status: 502 });
11007
11074
  }
11008
11075
  return Response.json(
11009
- { sessionToken: exchanged.sessionToken, accessToken: token.token },
11076
+ { sessionToken, accessToken: token.token },
11010
11077
  { headers: { "Cache-Control": "no-store" } }
11011
11078
  );
11012
11079
  }
@@ -11310,6 +11377,7 @@ export {
11310
11377
  mintUlid,
11311
11378
  nativeAuthCallback,
11312
11379
  nativeAuthExchange,
11380
+ nativeAuthIdToken,
11313
11381
  nativeAuthMe,
11314
11382
  nativeAuthSignOut,
11315
11383
  nativeAuthStart,