deepspace 0.3.10 → 0.4.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.
Files changed (120) hide show
  1. package/dist/cli.js +331 -115
  2. package/dist/cli.js.map +1 -1
  3. package/dist/index.d.ts +199 -16
  4. package/dist/index.js +354 -166
  5. package/dist/index.js.map +1 -1
  6. package/dist/server.d.ts +242 -73
  7. package/dist/server.js +985 -374
  8. package/dist/server.js.map +1 -1
  9. package/dist/worker.d.ts +322 -73
  10. package/dist/worker.js +961 -343
  11. package/dist/worker.js.map +1 -1
  12. package/features/admin-page/feature.json +29 -0
  13. package/features/admin-page/src/AdminPage.tsx +292 -0
  14. package/features/admin-page/src/admin-schema.ts +20 -0
  15. package/features/ai-chat/feature.json +41 -0
  16. package/features/ai-chat/src/AiChatPage.tsx +692 -0
  17. package/features/ai-chat/src/ChatPanel.tsx +1098 -0
  18. package/features/ai-chat/src/ai-chat-schema.ts +11 -0
  19. package/features/canvas/feature.json +45 -0
  20. package/features/canvas/src/CanvasEditorPage.tsx +87 -0
  21. package/features/canvas/src/CanvasListPage.tsx +202 -0
  22. package/features/canvas/src/canvas-schema.ts +33 -0
  23. package/features/canvas/src/components/CanvasToolbar.tsx +170 -0
  24. package/features/canvas/src/components/CanvasView.tsx +369 -0
  25. package/features/canvas/src/components/ShapeRenderer.tsx +114 -0
  26. package/features/cron/feature.json +33 -0
  27. package/features/cron/src/CronLogPage.tsx +100 -0
  28. package/features/cron/src/cron.ts +25 -0
  29. package/features/docs/feature.json +96 -0
  30. package/features/docs/src/DocsEditorPage.tsx +1012 -0
  31. package/features/docs/src/DocsListPage.tsx +951 -0
  32. package/features/docs/src/DocsOutlinePanel.tsx +68 -0
  33. package/features/docs/src/DocsPresence.tsx +138 -0
  34. package/features/docs/src/InviteDialog.tsx +336 -0
  35. package/features/docs/src/LibrarySidebar.tsx +464 -0
  36. package/features/docs/src/docs-favorites.ts +18 -0
  37. package/features/docs/src/docs-library-types.ts +15 -0
  38. package/features/docs/src/docs-schema.ts +80 -0
  39. package/features/docs/src/docs-ui.css +309 -0
  40. package/features/docs/src/editor/DocEditorSurface.tsx +257 -0
  41. package/features/docs/src/editor/DocsTiptapToolbar.tsx +560 -0
  42. package/features/docs/src/editor/useDocEditor.ts +206 -0
  43. package/features/docs/src/use-yjs-room-with-awareness.ts +285 -0
  44. package/features/file-attachments/feature.json +42 -0
  45. package/features/file-attachments/src/AttachmentsPage.tsx +864 -0
  46. package/features/file-attachments/src/attachments-constants.ts +9 -0
  47. package/features/file-attachments/src/attachments-schema.ts +45 -0
  48. package/features/file-attachments/src/useFilePreview.ts +471 -0
  49. package/features/file-attachments/src/useMimeTypeDetection.ts +138 -0
  50. package/features/file-manager/feature.json +24 -0
  51. package/features/file-manager/src/FileManagerPage.tsx +330 -0
  52. package/features/integration-test/feature.json +18 -0
  53. package/features/integration-test/src/IntegrationTestPage.tsx +423 -0
  54. package/features/integration-test/src/integration.spec.ts +42 -0
  55. package/features/items/feature.json +33 -0
  56. package/features/items/src/ItemsPage.tsx +325 -0
  57. package/features/items/src/items-constants.ts +10 -0
  58. package/features/items/src/items-schema.ts +27 -0
  59. package/features/kanban/feature.json +18 -0
  60. package/features/kanban/src/Kanban.tsx +283 -0
  61. package/features/landing/feature.json +62 -0
  62. package/features/landing/src/LandingPage.tsx +627 -0
  63. package/features/landing/src/primitives.tsx +389 -0
  64. package/features/landing/src/sections/FAQSection.tsx +110 -0
  65. package/features/landing/src/sections/FeaturesGridSection.tsx +311 -0
  66. package/features/landing/src/sections/HowItWorksSection.tsx +62 -0
  67. package/features/landing/src/sections/LogoCloudSection.tsx +58 -0
  68. package/features/landing/src/sections/ShowcaseSection.tsx +63 -0
  69. package/features/landing/src/sections/StatsSection.tsx +31 -0
  70. package/features/landing/src/sections/TeamSection.tsx +86 -0
  71. package/features/landing/src/sections/TestimonialsSection.tsx +68 -0
  72. package/features/landing/src/sections/VideoSection.tsx +71 -0
  73. package/features/leaderboard/feature.json +33 -0
  74. package/features/leaderboard/src/LeaderboardPage.tsx +372 -0
  75. package/features/leaderboard/src/leaderboard-constants.ts +21 -0
  76. package/features/leaderboard/src/leaderboard-schema.ts +36 -0
  77. package/features/messaging/feature.json +111 -0
  78. package/features/messaging/src/ChatMultiPage.tsx +300 -0
  79. package/features/messaging/src/ChatPage.tsx +75 -0
  80. package/features/messaging/src/components/chat/ChatHeader.tsx +76 -0
  81. package/features/messaging/src/components/chat/MessageActionSheet.tsx +168 -0
  82. package/features/messaging/src/components/chat/MessageInput.tsx +65 -0
  83. package/features/messaging/src/components/chat/MessageItem.tsx +352 -0
  84. package/features/messaging/src/components/chat/MessageList.tsx +248 -0
  85. package/features/messaging/src/components/chat/ReactionPicker.tsx +2 -0
  86. package/features/messaging/src/components/chat/ThreadPanel.tsx +107 -0
  87. package/features/messaging/src/components/chat/UserProfilePopover.tsx +158 -0
  88. package/features/messaging/src/components/chat-multi/AddMemberModal.tsx +188 -0
  89. package/features/messaging/src/components/chat-multi/BrowseGroupsModal.tsx +163 -0
  90. package/features/messaging/src/components/chat-multi/ChannelListItem.tsx +147 -0
  91. package/features/messaging/src/components/chat-multi/ChannelSettingsPanel.tsx +344 -0
  92. package/features/messaging/src/components/chat-multi/ChannelSidebar.tsx +460 -0
  93. package/features/messaging/src/components/chat-multi/CreateGroupModal.tsx +190 -0
  94. package/features/messaging/src/components/chat-multi/InvitationList.tsx +149 -0
  95. package/features/messaging/src/components/chat-multi/NewMessageModal.tsx +159 -0
  96. package/features/messaging/src/hooks/useChatChannel.ts +64 -0
  97. package/features/messaging/src/hooks/useLongPress.ts +74 -0
  98. package/features/messaging/src/hooks/useMultiChannel.ts +142 -0
  99. package/features/messaging/src/messaging-schema.ts +25 -0
  100. package/features/presence-test/feature.json +21 -0
  101. package/features/presence-test/src/PresenceTestPage.tsx +120 -0
  102. package/features/sidebar/feature.json +19 -0
  103. package/features/sidebar/src/AppSidebar.tsx +558 -0
  104. package/features/tasks/feature.json +33 -0
  105. package/features/tasks/src/TasksPage.tsx +598 -0
  106. package/features/tasks/src/tasks-constants.ts +43 -0
  107. package/features/tasks/src/tasks-schema.ts +56 -0
  108. package/features/testing/feature.json +49 -0
  109. package/features/testing/src/TestPage.tsx +145 -0
  110. package/features/testing/src/cpu-burn-action.ts +51 -0
  111. package/features/testing/src/subrequest-burn-action.ts +53 -0
  112. package/features/testing/src/test-schema.ts +23 -0
  113. package/features/topbar/feature.json +18 -0
  114. package/features/topbar/src/Topbar.tsx +353 -0
  115. package/features/tree/feature.json +26 -0
  116. package/features/tree/src/TreeSidebar.tsx +607 -0
  117. package/features/tree/src/tree-constants.ts +68 -0
  118. package/features/tree/src/tree-hooks.ts +258 -0
  119. package/package.json +4 -2
  120. package/scripts/add-feature.cjs +654 -0
package/dist/server.d.ts CHANGED
@@ -357,52 +357,6 @@ interface ActionContext<TEnv = Record<string, unknown>> {
357
357
  }
358
358
  type ActionHandler<TEnv = Record<string, unknown>> = (ctx: ActionContext<TEnv>) => Promise<ActionResult>;
359
359
 
360
- /**
361
- * Cron System — Server-Side Scheduled Tasks
362
- *
363
- * Provides CronContext for miniapp cron handlers and buildCronContext
364
- * to construct it from worker environment bindings.
365
- *
366
- * CronContext gives handlers access to:
367
- * - records: Query/create/update/delete via RecordRoom tools API
368
- * - integrations: Call platform integration endpoints (billed to owner)
369
- * - ownerUserId: The app owner's user ID
370
- */
371
- /** Context passed to cron handler functions */
372
- interface CronContext {
373
- /** RecordRoom data access (queries the DO directly via tools API) */
374
- records: {
375
- query(collection: string, opts?: {
376
- where?: Record<string, unknown>;
377
- limit?: number;
378
- }): Promise<any[]>;
379
- create(collection: string, data: Record<string, unknown>): Promise<any>;
380
- update(collection: string, recordId: string, data: Record<string, unknown>): Promise<any>;
381
- delete(collection: string, recordId: string): Promise<any>;
382
- };
383
- /** Call platform integration endpoints, billed to owner */
384
- integrations: {
385
- call(endpoint: string, params: Record<string, unknown>): Promise<any>;
386
- };
387
- /** App owner's user ID */
388
- ownerUserId: string;
389
- }
390
- /** Environment bindings needed by buildCronContext */
391
- interface CronEnv {
392
- RECORD_ROOMS: DurableObjectNamespace;
393
- INTERNAL_STORAGE_HMAC_SECRET?: string;
394
- /** Override API base URL for local dev or custom platform deployments. */
395
- API_BASE_URL?: string;
396
- }
397
- /**
398
- * Build a CronContext from worker environment bindings.
399
- *
400
- * @param env - Worker environment with RECORD_ROOMS DO namespace and HMAC secret
401
- * @param ownerUserId - App owner's user ID (for RBAC and billing)
402
- * @param roomId - RecordRoom ID (defaults to 'default')
403
- */
404
- declare function buildCronContext(env: CronEnv, ownerUserId: string, roomId?: string): CronContext;
405
-
406
360
  /**
407
361
  * Upstream worker proxy helpers.
408
362
  *
@@ -490,6 +444,61 @@ declare function platformWorkerFetch(env: PlatformWorkerEnv, pathOrRequest: stri
490
444
  */
491
445
  declare function authWorkerFetch(env: AuthWorkerEnv, path: string, init?: RequestInit): Promise<Response>;
492
446
 
447
+ /**
448
+ * Cron System — Server-Side Scheduled Tasks
449
+ *
450
+ * Provides CronContext for miniapp cron handlers and buildCronContext
451
+ * to construct it from worker environment bindings.
452
+ *
453
+ * CronContext gives handlers access to:
454
+ * - records: Query/create/update/delete via RecordRoom tools API
455
+ * - integrations: Call platform integration endpoints, billed to the app owner
456
+ * - ownerUserId: The app owner's user ID
457
+ */
458
+
459
+ /** Context passed to cron handler functions */
460
+ interface CronContext {
461
+ /** RecordRoom data access (queries the DO directly via tools API) */
462
+ records: {
463
+ query(collection: string, opts?: {
464
+ where?: Record<string, unknown>;
465
+ limit?: number;
466
+ }): Promise<any[]>;
467
+ create(collection: string, data: Record<string, unknown>): Promise<any>;
468
+ update(collection: string, recordId: string, data: Record<string, unknown>): Promise<any>;
469
+ delete(collection: string, recordId: string): Promise<any>;
470
+ };
471
+ /**
472
+ * Call a platform integration endpoint (e.g. "openai/chat-completion",
473
+ * "freepik/text-to-image-classic"). Billed to the app owner — the same
474
+ * APP_OWNER_JWT the rest of the SDK uses for server-side billed calls.
475
+ */
476
+ integrations: {
477
+ call(endpoint: string, params?: Record<string, unknown>): Promise<any>;
478
+ };
479
+ /** App owner's user ID */
480
+ ownerUserId: string;
481
+ }
482
+ /** Environment bindings needed by buildCronContext */
483
+ interface CronEnv extends ApiWorkerEnv {
484
+ RECORD_ROOMS: DurableObjectNamespace;
485
+ /**
486
+ * Long-lived app-owner JWT minted at deploy time. Required for
487
+ * `integrations.call()` so the call is billed to the app owner.
488
+ * Optional here so apps that don't use integrations from cron can omit
489
+ * it without a type error; missing-at-call-time throws a clear message.
490
+ */
491
+ APP_OWNER_JWT?: string;
492
+ }
493
+ /**
494
+ * Build a CronContext from worker environment bindings.
495
+ *
496
+ * @param env - Worker environment with RECORD_ROOMS DO namespace, APP_OWNER_JWT, and an api-worker transport (API_WORKER binding or API_WORKER_URL)
497
+ * @param ownerUserId - App owner's user ID (for RBAC and billing)
498
+ * @param roomId - RecordRoom ID (defaults to 'default')
499
+ */
500
+ declare function buildCronContext(env: CronEnv, ownerUserId: string, roomId?: string): CronContext;
501
+
493
502
  /**
494
503
  * AI provider helpers — create Vercel AI SDK providers that route through
495
504
  * the DeepSpace API worker proxy for per-user billing.
@@ -1034,6 +1043,7 @@ declare const MSG: {
1034
1043
  readonly USER_LIST: "user.list";
1035
1044
  readonly SET_ROLE: "user.set_role";
1036
1045
  readonly USER_UPDATE: "user.update";
1046
+ readonly AUTH: "auth";
1037
1047
  readonly YJS_JOIN: "yjs.join";
1038
1048
  readonly YJS_LEAVE: "yjs.leave";
1039
1049
  readonly ACK: "records.ack";
@@ -1062,6 +1072,10 @@ declare const MSG: {
1062
1072
  readonly CRON_PAUSE: "cron.pause";
1063
1073
  readonly CRON_RESUME: "cron.resume";
1064
1074
  readonly CRON_STATUS: "cron.status";
1075
+ readonly JOB_ENQUEUE: "job.enqueue";
1076
+ readonly JOB_CANCEL: "job.cancel";
1077
+ readonly JOB_RETRY: "job.retry";
1078
+ readonly JOB_UPDATE: "job.update";
1065
1079
  readonly PRESENCE_SYNC: "presence.sync";
1066
1080
  readonly PRESENCE_JOIN: "presence.join";
1067
1081
  readonly PRESENCE_LEAVE: "presence.leave";
@@ -1184,6 +1198,8 @@ type ServerMessage = BaseMessage<typeof MSG.QUERY_RESULT, {
1184
1198
  error: string;
1185
1199
  }> | BaseMessage<typeof MSG.RESUBSCRIBE, EmptyPayload> | BaseMessage<typeof MSG.LIST_SCHEMAS, {
1186
1200
  schemas: unknown;
1201
+ }> | BaseMessage<typeof MSG.AUTH, {
1202
+ canWrite: boolean;
1187
1203
  }> | BaseMessage<typeof MSG.USER_INFO, unknown> | BaseMessage<typeof MSG.USER_LIST, {
1188
1204
  users: unknown[];
1189
1205
  }> | BaseMessage<typeof MSG.YJS_JOIN, {
@@ -1243,6 +1259,12 @@ type ServerMessage = BaseMessage<typeof MSG.QUERY_RESULT, {
1243
1259
  }> | BaseMessage<typeof MSG.CRON_STATUS, {
1244
1260
  tasks: unknown;
1245
1261
  recentHistory: unknown;
1262
+ }> | BaseMessage<typeof MSG.JOB_UPDATE, {
1263
+ kind: 'snapshot' | 'enqueued' | 'progress' | 'succeeded' | 'failed' | 'canceled' | 'retried';
1264
+ job?: unknown;
1265
+ jobs?: unknown[];
1266
+ /** Echoes the enqueue requestId when the update is the enqueue ack. */
1267
+ requestId?: string;
1246
1268
  }> | BaseMessage<typeof MSG.PRESENCE_SYNC, {
1247
1269
  peers: unknown[];
1248
1270
  }> | BaseMessage<typeof MSG.PRESENCE_JOIN, {
@@ -1756,6 +1778,8 @@ interface GameInput {
1756
1778
  }
1757
1779
  interface GameAttachment extends UserAttachment {
1758
1780
  joinedAt: string;
1781
+ /** True for member/admin roles; false for viewers, unauthenticated anon, spectators. */
1782
+ canWrite: boolean;
1759
1783
  }
1760
1784
  declare abstract class GameRoom<E = Record<string, unknown>> extends BaseRoom<E> {
1761
1785
  private config;
@@ -1853,6 +1877,8 @@ interface Viewport {
1853
1877
  }
1854
1878
  interface CanvasAttachment extends UserAttachment {
1855
1879
  viewport: Viewport | null;
1880
+ /** True for member/admin roles; false for viewers and unauthenticated anon. */
1881
+ canWrite: boolean;
1856
1882
  }
1857
1883
  declare class CanvasRoom<E = Record<string, unknown>> extends BaseRoom<E> {
1858
1884
  private doc;
@@ -1965,13 +1991,17 @@ interface CronExecution {
1965
1991
  durationMs: number;
1966
1992
  error?: string;
1967
1993
  }
1994
+ interface CronAttachment extends UserAttachment {
1995
+ /** True for member/admin roles; false for viewers and unauthenticated anon. */
1996
+ canWrite: boolean;
1997
+ }
1968
1998
  declare abstract class CronRoom<E = Record<string, unknown>> extends BaseRoom<E> {
1969
1999
  private tasks;
1970
2000
  private initialized;
1971
2001
  constructor(state: DurableObjectState, env: unknown, config: CronRoomConfig);
1972
2002
  private ensureInitialized;
1973
2003
  fetch(request: Request): Promise<Response>;
1974
- protected onConnect(ws: WebSocket, user: UserAttachment): UserAttachment;
2004
+ protected onConnect(ws: WebSocket, user: UserAttachment): CronAttachment;
1975
2005
  protected onMessage(ws: WebSocket, user: UserAttachment, message: {
1976
2006
  type: string;
1977
2007
  [key: string]: unknown;
@@ -1989,6 +2019,166 @@ declare abstract class CronRoom<E = Record<string, unknown>> extends BaseRoom<E>
1989
2019
  protected abstract onTask(taskName: string): void | Promise<void>;
1990
2020
  }
1991
2021
 
2022
+ /**
2023
+ * JobRoom — Per-app durable background-job execution Durable Object.
2024
+ *
2025
+ * Solves the "long job dies when the response goes out" problem on
2026
+ * Cloudflare Workers. `ctx.waitUntil` only gets 30s after a response;
2027
+ * jobs that need minutes-to-hours live here instead: rows in SQLite,
2028
+ * picked up by DO alarms (15-min wall budget per tick), resumable
2029
+ * across ticks via `ctx.continue` for the rare longer cases.
2030
+ *
2031
+ * Lifecycle: queued → running → succeeded | failed | canceled
2032
+ *
2033
+ * Crash recovery: if an isolate is recycled mid-run, the row stays at
2034
+ * `running`. On next init, rows older than ~16 min are either retried
2035
+ * (if attempts left) or marked failed.
2036
+ *
2037
+ * See the abstract `onJob` method below for the subclass contract.
2038
+ * Message types: job.*
2039
+ */
2040
+
2041
+ type JobStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'canceled';
2042
+ /**
2043
+ * Job record exposed to `onJob` handlers and clients. Payloads are typed
2044
+ * as `unknown` at the SDK layer; subclasses narrow via a generic param.
2045
+ */
2046
+ interface Job<P = unknown> {
2047
+ id: string;
2048
+ type: string;
2049
+ status: JobStatus;
2050
+ payload: P;
2051
+ result?: unknown;
2052
+ error?: string;
2053
+ progress?: number;
2054
+ progressMessage?: string;
2055
+ attempts: number;
2056
+ maxAttempts: number;
2057
+ enqueuedAt: string;
2058
+ startedAt?: string | null;
2059
+ completedAt?: string | null;
2060
+ enqueuedBy?: string | null;
2061
+ /** Set when a previous run called `ctx.continue(state)`. */
2062
+ resumeFrom?: unknown;
2063
+ }
2064
+ interface JobContext {
2065
+ /** Set progress (0..1) with an optional message. Broadcasts. */
2066
+ progress(value: number, message?: string): void;
2067
+ /**
2068
+ * Save a resumable checkpoint and re-run `onJob` on the next alarm
2069
+ * with `job.resumeFrom = state`. The return value of `onJob` is
2070
+ * ignored once `continue` has been called.
2071
+ */
2072
+ continue(state: unknown, options?: {
2073
+ afterMs?: number;
2074
+ }): void;
2075
+ /**
2076
+ * Fires when a JOB_CANCEL arrives while this job is running in this
2077
+ * isolate. Cross-isolate cancels still mark the row `canceled` but
2078
+ * can't fire this signal.
2079
+ */
2080
+ signal: AbortSignal;
2081
+ }
2082
+ interface JobRoomConfig {
2083
+ /** Default for jobs enqueued without explicit `maxAttempts`. Default 1 (no auto-retry). */
2084
+ defaultMaxAttempts?: number;
2085
+ /** TTL for terminal rows (succeeded/failed/canceled) in ms. Default 24h. */
2086
+ retentionMs?: number;
2087
+ /** Job count in the initial snapshot to a new subscriber. Default 100. */
2088
+ snapshotLimit?: number;
2089
+ /** Delay before a failed attempt is retried, in ms. Default 1000. */
2090
+ retryBackoffMs?: number;
2091
+ }
2092
+ declare abstract class JobRoom<E = Record<string, unknown>, P = unknown, R = unknown> extends BaseRoom<E> {
2093
+ private initialized;
2094
+ private readonly defaultMaxAttempts;
2095
+ private readonly retentionMs;
2096
+ private readonly snapshotLimit;
2097
+ private readonly retryBackoffMs;
2098
+ /** In-flight jobs in this isolate; lets same-isolate JOB_CANCEL fire the signal. */
2099
+ private readonly inFlight;
2100
+ /** Set by `ctx.continue` inside `executeJob`; reset before every run. */
2101
+ private continueState;
2102
+ constructor(state: DurableObjectState, env: unknown, config?: JobRoomConfig);
2103
+ private ensureInitialized;
2104
+ fetch(request: Request): Promise<Response>;
2105
+ protected onConnect(ws: WebSocket, user: UserAttachment): UserAttachment;
2106
+ protected onMessage(ws: WebSocket, user: UserAttachment, message: {
2107
+ type: string;
2108
+ [key: string]: unknown;
2109
+ }): Promise<void>;
2110
+ protected onAlarm(): Promise<void>;
2111
+ /**
2112
+ * One internal endpoint, `POST /enqueue`, used by the `enqueueJob`
2113
+ * helper at the bottom of this file. The room is not meant to be
2114
+ * reachable from the public internet; callers route through the app
2115
+ * worker (or call `this.enqueue(...)` directly from a subclass).
2116
+ *
2117
+ * Subclasses overriding `onRequest` should call `super.onRequest(req)`
2118
+ * for paths they don't handle.
2119
+ */
2120
+ protected onRequest(request: Request): Promise<Response>;
2121
+ /**
2122
+ * Synchronously persist a new job and arm the alarm. Returns the new
2123
+ * job. This is the in-isolate path — useful for a subclass `onJob`
2124
+ * that wants to chain follow-up work without paying a fetch hop:
2125
+ *
2126
+ * protected async onJob(job: Job, ctx: JobContext) {
2127
+ * // ... do work ...
2128
+ * if (needsFollowup) this.enqueue('followup', { parent: job.id })
2129
+ * }
2130
+ *
2131
+ * Workers code that lives outside the DO isolate (HTTP routes, cron
2132
+ * tasks, server actions) cannot call this directly — they must go
2133
+ * through the `enqueueJob` helper at the bottom of this file, which
2134
+ * routes via the DO's `/enqueue` HTTP endpoint.
2135
+ */
2136
+ enqueue(type: string, payload?: unknown, options?: {
2137
+ maxAttempts?: number;
2138
+ enqueuedBy?: string;
2139
+ }): Job;
2140
+ private insertJob;
2141
+ private cancelJob;
2142
+ private retryJob;
2143
+ /**
2144
+ * Drain due jobs in FIFO order. All due jobs share the alarm's
2145
+ * 15-min wall budget (a CF property, not a per-job allocation).
2146
+ */
2147
+ private drainDueJobs;
2148
+ private executeJob;
2149
+ private makeContext;
2150
+ private readStatus;
2151
+ private scheduleNextAlarm;
2152
+ private recoverStuckRunning;
2153
+ private pruneExpired;
2154
+ private getRecentJobs;
2155
+ private getJobById;
2156
+ /**
2157
+ * Run a single job. Return a value for success; throw for failure
2158
+ * (retried until attempts >= maxAttempts). Use `ctx.progress` for
2159
+ * progress, `ctx.continue(state)` to span multiple alarms, and
2160
+ * `ctx.signal` to honor client cancellations.
2161
+ */
2162
+ protected abstract onJob(job: Job<P>, ctx: JobContext): Promise<R | void> | R | void;
2163
+ }
2164
+ /**
2165
+ * Enqueue a job from worker code that has the DO namespace. Routed by
2166
+ * `roomId` (typically `app:<APP_NAME>`; pass different ids for sharded
2167
+ * queues). Returns the new jobId; throws on failure.
2168
+ *
2169
+ * const jobId = await enqueueJob(
2170
+ * env.JOB_ROOMS,
2171
+ * `app:${env.APP_NAME}`,
2172
+ * 'ai-summarize',
2173
+ * { text },
2174
+ * { maxAttempts: 3 },
2175
+ * )
2176
+ */
2177
+ declare function enqueueJob(namespace: DurableObjectNamespace, roomId: string, type: string, payload?: unknown, options?: {
2178
+ maxAttempts?: number;
2179
+ enqueuedBy?: string;
2180
+ }): Promise<string>;
2181
+
1992
2182
  /**
1993
2183
  * DO Manifest — Dynamic Durable Object binding declarations.
1994
2184
  *
@@ -2130,7 +2320,7 @@ declare const ALLOWED_BINDING_TYPES: Set<string>;
2130
2320
  *
2131
2321
  * Includes:
2132
2322
  * - Static-asset + service bindings the platform sets up automatically.
2133
- * - SDK-managed env (auth, identity, owner JWT, HMAC secret).
2323
+ * - SDK-managed env (auth, identity, owner JWT).
2134
2324
  * - The auto-attached cost-tracking AE dataset (`USAGE_EVENTS`).
2135
2325
  *
2136
2326
  * DO binding names (RECORD_ROOMS, YJS_ROOMS, etc.) are NOT in this set
@@ -2752,22 +2942,6 @@ interface VerifyOutcome {
2752
2942
  debug?: TokenDebugInfo;
2753
2943
  error?: unknown;
2754
2944
  }
2755
- interface InternalSignature {
2756
- timestamp: string;
2757
- signature: string;
2758
- }
2759
- interface VerifyInternalSignatureInput {
2760
- secret: string | undefined;
2761
- timestamp: string | null | undefined;
2762
- signature: string | null | undefined;
2763
- payload: string;
2764
- maxSkewMs?: number;
2765
- }
2766
- interface SignInternalPayloadInput {
2767
- secret: string;
2768
- payload: string;
2769
- timestamp?: string;
2770
- }
2771
2945
 
2772
2946
  /**
2773
2947
  * JWT verification for DeepSpace workers.
@@ -2788,17 +2962,12 @@ interface SignInternalPayloadInput {
2788
2962
  declare function verifyJwt(config: JwtVerifierConfig, token: string | null | undefined): Promise<VerifyOutcome>;
2789
2963
 
2790
2964
  /**
2791
- * HMAC-based internal authentication for service-to-service calls.
2792
- *
2793
- * Ported as-is from Miyagi3 — this is auth-provider-agnostic.
2965
+ * HMAC primitives used by the per-app identity tokens (APP_IDENTITY_TOKEN)
2966
+ * minted at deploy time and verified on every /internal/* call into the
2967
+ * platform worker. Auth-provider-agnostic.
2794
2968
  */
2795
-
2796
- declare const DEFAULT_MAX_SKEW_MS: number;
2797
2969
  declare function computeHmacHex(secret: string, payload: string): Promise<string>;
2798
2970
  declare function timingSafeEqualHex(a: string, b: string): Promise<boolean>;
2799
- declare function signInternalPayload({ secret, payload, timestamp, }: SignInternalPayloadInput): Promise<InternalSignature>;
2800
- declare function verifyInternalSignature({ secret, timestamp, signature, payload, maxSkewMs, }: VerifyInternalSignatureInput): Promise<boolean>;
2801
- declare function buildInternalPayload(body: unknown): string;
2802
2971
 
2803
2972
  declare function decodeJwtPayload(token: string | null | undefined): TokenDebugInfo | undefined;
2804
2973
 
@@ -3802,4 +3971,4 @@ declare class RefundError extends Error {
3802
3971
  constructor(message: string, status: number);
3803
3972
  }
3804
3973
 
3805
- export { AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, APP_NAME_RULES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type ApiWorkerEnv, type AppNameResolution, type AppNameValidation, type AuthWorkerEnv, BASE_USERS_SCHEMA, BUILT_IN_TOOLS, BaseRoom, CHANNELS_SCHEMA, CHANNEL_INVITATIONS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, CONVERSATION_SCHEMAS, COST_RATES, CancelSubscriptionError, type CancelSubscriptionOpts, type CancelSubscriptionResult, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type CollectionPermissionSummary, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, 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, DEFAULT_CONTEXT_CONFIG, DEFAULT_DO_MANIFEST, DEFAULT_MAX_SKEW_MS, DIRECTORY_SCHEMAS, type DOBindings, type DOManifest, type DOManifestEntry, type DebugApiContext, type DeepSpaceAIEnv, type DeepSpaceAIOptions, type DeepSpaceAuth, type DeepSpaceAuthConfig, 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 InternalSignature, type JwtClaims, type JwtVerifierConfig, MESSAGES_SCHEMA, type MutateActionData, type PermissionAnalysis, type PermissionContext, type PermissionLevel, type PermissionSource, type PlanInfo, type PlatformWorkerEnv, type Player, type PrefixResult, type PresencePeer, PresenceRoom, type QueryActionData, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, RESERVED_BINDING_NAMES, RESERVED_COLLECTION_NAMES, type RecordContext, RecordRoom, type RecordRoomConfig, RefundError, type RefundOpts, type RefundResult, type ResolvedColumn, type ResolvedPermission, type RolePermissions, type RunMigrationsResult, SYSTEM_COLLECTION_SCHEMAS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ScreenshotEnv, type ScreenshotOptions, type ScreenshotResult, type SharedConnection, type SignInternalPayloadInput, type StoredRecord, SubscriptionAuthError, type SubscriptionContext, type SubscriptionRead, SubscriptionRequiredError, type SubscriptionStatus, type Summarizer, type TokenDebugInfo, type ToolResult, type ToolSchema, type ToolsApiContext, USERS_COLUMNS, type User, type UserAttachment, type UserContext, VOTING_SCHEMAS, type ValidationError, type VerifiedAuth, type VerifyInternalSignatureInput, type VerifyOutcome, type VerifyResult, type Viewport, WORKSPACE_SCHEMAS, type YjsContext, YjsRoom, analyzePermissions, apiWorkerFetch, appendMessage, applySlidingWindow, authWorkerFetch, bindingManifestFromOutputConfig, broadcastChange, broadcastYjsUpdate, buildCronContext, buildInternalPayload, buildTableSelect, buildUiParts, canCreate, canDelete, canRead, canUpdate, cancelSubscription, capToolResultSize, captureScreenshot, checkFieldPermissions, coerceValue, collectionTableName, columnId, computeDoMigration, computeHmacHex, createChat, createDeepSpaceAI, createDeepSpaceAuth, createScopedR2Handler, dataToColumnValues, decodeJwtPayload, deleteChatCascade, deleteRecord, executeQuery, getAllUsers, getChat, getGlobalDOSchemas, getGlobalDOType, getOrCreateYjsDoc, getRecord, getRolePermissions, getSubscription, getUser, getYjsDocKey, handleApiRequest, handleDelete, handlePut, handleSetRole, handleSubscribe, handleToolsRequest, handleUnsubscribe, handleUserList, handleUserUpdate, handleYjsBinaryMessage, handleYjsJoin, handleYjsLeave, isAutoProvision, isOwner, lintSchema, loadMessages, makeDefaultSummarizer, meterAi, meterUsage, meterVectorize, noopPermissionContext, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, putRecord, readRecord, recordMatchesSubscription, refundInvoice, registerUser, requireSubscription, resolveAppName, resolveColumn, rowToData, runMigrations, saveYjsDoc, signInternalPayload, timingSafeEqualHex, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppName, validateBindingManifest, validateDoManifest, verifyInternalSignature, verifyJwt, workspaceAccountsSchema, workspaceContentSharesSchema, workspaceEmailHandlesSchema, workspaceFormResponsesSchema, workspacePeopleSchema, workspaceProjectsSchema, workspaceTagsSchema, workspaceTasksSchema, workspaceTeamMembersSchema, workspaceTeamsSchema, workspaceTransactionsSchema };
3974
+ export { AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, ALLOWED_BINDING_TYPES, APP_NAME_RULES, AUTO_PROVISIONABLE_TYPES, AUTO_PROVISION_SENTINEL, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type ApiWorkerEnv, type AppNameResolution, type AppNameValidation, type AuthWorkerEnv, BASE_USERS_SCHEMA, BUILT_IN_TOOLS, BaseRoom, CHANNELS_SCHEMA, CHANNEL_INVITATIONS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, CONVERSATION_SCHEMAS, COST_RATES, CancelSubscriptionError, type CancelSubscriptionOpts, type CancelSubscriptionResult, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type CollectionPermissionSummary, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, 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, DEFAULT_CONTEXT_CONFIG, DEFAULT_DO_MANIFEST, DIRECTORY_SCHEMAS, type DOBindings, type DOManifest, type DOManifestEntry, type DebugApiContext, type DeepSpaceAIEnv, type DeepSpaceAIOptions, type DeepSpaceAuth, type DeepSpaceAuthConfig, 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 Job, type JobContext, JobRoom, type JobRoomConfig, type JobStatus, type JwtClaims, type JwtVerifierConfig, MESSAGES_SCHEMA, type MutateActionData, type PermissionAnalysis, type PermissionContext, type PermissionLevel, type PermissionSource, type PlanInfo, type PlatformWorkerEnv, type Player, type PrefixResult, type PresencePeer, PresenceRoom, type QueryActionData, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, RESERVED_BINDING_NAMES, RESERVED_COLLECTION_NAMES, type RecordContext, RecordRoom, type RecordRoomConfig, RefundError, type RefundOpts, type RefundResult, type ResolvedColumn, type ResolvedPermission, type RolePermissions, type RunMigrationsResult, SYSTEM_COLLECTION_SCHEMAS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ScreenshotEnv, type ScreenshotOptions, type ScreenshotResult, type SharedConnection, type StoredRecord, SubscriptionAuthError, type SubscriptionContext, type SubscriptionRead, SubscriptionRequiredError, type SubscriptionStatus, type Summarizer, type TokenDebugInfo, type ToolResult, type ToolSchema, type ToolsApiContext, USERS_COLUMNS, type User, type UserAttachment, type UserContext, VOTING_SCHEMAS, type ValidationError, type VerifiedAuth, type VerifyOutcome, type VerifyResult, type Viewport, WORKSPACE_SCHEMAS, type YjsContext, YjsRoom, analyzePermissions, apiWorkerFetch, appendMessage, applySlidingWindow, authWorkerFetch, bindingManifestFromOutputConfig, broadcastChange, broadcastYjsUpdate, buildCronContext, buildTableSelect, buildUiParts, canCreate, canDelete, canRead, canUpdate, cancelSubscription, capToolResultSize, captureScreenshot, checkFieldPermissions, coerceValue, collectionTableName, columnId, computeDoMigration, computeHmacHex, createChat, createDeepSpaceAI, createDeepSpaceAuth, createScopedR2Handler, dataToColumnValues, decodeJwtPayload, deleteChatCascade, deleteRecord, enqueueJob, executeQuery, getAllUsers, getChat, getGlobalDOSchemas, getGlobalDOType, getOrCreateYjsDoc, getRecord, getRolePermissions, getSubscription, getUser, getYjsDocKey, handleApiRequest, handleDelete, handlePut, handleSetRole, handleSubscribe, handleToolsRequest, handleUnsubscribe, handleUserList, handleUserUpdate, handleYjsBinaryMessage, handleYjsJoin, handleYjsLeave, isAutoProvision, isOwner, lintSchema, loadMessages, makeDefaultSummarizer, meterAi, meterUsage, meterVectorize, noopPermissionContext, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, putRecord, readRecord, recordMatchesSubscription, refundInvoice, registerUser, requireSubscription, resolveAppName, resolveColumn, rowToData, runMigrations, saveYjsDoc, timingSafeEqualHex, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppName, validateBindingManifest, validateDoManifest, verifyJwt, workspaceAccountsSchema, workspaceContentSharesSchema, workspaceEmailHandlesSchema, workspaceFormResponsesSchema, workspacePeopleSchema, workspaceProjectsSchema, workspaceTagsSchema, workspaceTasksSchema, workspaceTeamMembersSchema, workspaceTeamsSchema, workspaceTransactionsSchema };