deepspace 0.2.5 → 0.2.7

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
@@ -1,7 +1,5 @@
1
1
  import * as Y from 'yjs';
2
- import { AnthropicProvider } from '@ai-sdk/anthropic';
3
- import { OpenAIProvider } from '@ai-sdk/openai';
4
- import { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';
2
+ import { LanguageModel, ModelMessage } from 'ai';
5
3
  import * as better_auth from 'better-auth';
6
4
  import * as better_auth_plugins from 'better-auth/plugins';
7
5
 
@@ -1653,6 +1651,16 @@ type DOBindings<T extends readonly DOManifestEntry[]> = {
1653
1651
  /** Default manifest for apps that don't declare one */
1654
1652
  declare const DEFAULT_DO_MANIFEST: DOManifest;
1655
1653
 
1654
+ /**
1655
+ * AI Chat Schemas
1656
+ *
1657
+ * Pre-built collection schemas for DO-backed AI chat history.
1658
+ * The worker is the only writer; the client reads via `useQuery`.
1659
+ */
1660
+
1661
+ declare const AI_CHATS_SCHEMA: CollectionSchema;
1662
+ declare const AI_MESSAGES_SCHEMA: CollectionSchema;
1663
+
1656
1664
  /**
1657
1665
  * Messaging Schemas
1658
1666
  *
@@ -2221,12 +2229,13 @@ declare function authWorkerFetch(env: AuthWorkerEnv, path: string, init?: Reques
2221
2229
  * const anthropic = createDeepSpaceAI(c.env, 'anthropic', { authToken: jwt })
2222
2230
  */
2223
2231
 
2232
+ /**
2233
+ * Model factory: `(modelId) => LanguageModel`. The explicit return type
2234
+ * keeps tsup's DTS build from leaking unportable `.pnpm/@ai-sdk+provider/...`
2235
+ * paths into the published `dist/index.d.ts`.
2236
+ */
2237
+ type DeepSpaceModelFactory = (modelId: string) => LanguageModel;
2224
2238
  type Provider = 'anthropic' | 'openai' | 'cerebras';
2225
- type ProviderReturn = {
2226
- anthropic: AnthropicProvider;
2227
- openai: OpenAIProvider;
2228
- cerebras: OpenAICompatibleProvider;
2229
- };
2230
2239
  interface DeepSpaceAIEnv extends ApiWorkerEnv {
2231
2240
  /**
2232
2241
  * Long-lived owner-scoped JWT minted at deploy time (or by `deepspace dev`).
@@ -2254,7 +2263,176 @@ interface DeepSpaceAIOptions {
2254
2263
  * (explicit or `env.APP_OWNER_JWT`) automatically. Throws a clear error if
2255
2264
  * either is unconfigured.
2256
2265
  */
2257
- declare function createDeepSpaceAI<P extends Provider>(env: DeepSpaceAIEnv, provider: P, options?: DeepSpaceAIOptions): ProviderReturn[P];
2266
+ declare function createDeepSpaceAI(env: DeepSpaceAIEnv, provider: Provider, options?: DeepSpaceAIOptions): DeepSpaceModelFactory;
2267
+
2268
+ /**
2269
+ * Chat context pipeline — keeps the per-request payload to the LLM bounded.
2270
+ *
2271
+ * `prepareMessagesWithCompaction` runs before `streamText`: truncate old tool
2272
+ * results, apply a cached summary if available, otherwise summarize the older
2273
+ * half of history when over budget. Falls back to a sliding window if
2274
+ * summarization fails. `capToolResultSize` caps individual tool calls.
2275
+ */
2276
+
2277
+ interface ChatTurn {
2278
+ id?: string;
2279
+ role: 'user' | 'assistant' | 'system';
2280
+ content: string;
2281
+ parts?: unknown[];
2282
+ }
2283
+ type Summarizer = (messages: ChatTurn[]) => Promise<string>;
2284
+ interface ChatContextConfig {
2285
+ contextBudget: number;
2286
+ toolResultCap: number;
2287
+ keepRecentToolResults: number;
2288
+ minKept: number;
2289
+ }
2290
+ declare const DEFAULT_CONTEXT_CONFIG: ChatContextConfig;
2291
+ declare function totalChars(messages: ChatTurn[]): number;
2292
+ /**
2293
+ * Replace older tool-result payloads with a small marker. Keeps the last
2294
+ * `keepRecent` tool results intact. Errors (`success: false`) are preserved —
2295
+ * they're small and the agent needs them for reasoning.
2296
+ */
2297
+ declare function truncateOldToolResults(messages: ChatTurn[], keepRecent: number): ChatTurn[];
2298
+ /**
2299
+ * Drop oldest messages until total character count is under `charCap`,
2300
+ * never going below `minKept` messages. System messages (e.g. compaction
2301
+ * summaries) are pinned — dropping them would discard the most condensed
2302
+ * context first.
2303
+ */
2304
+ declare function applySlidingWindow(messages: ChatTurn[], charCap: number, minKept: number): ChatTurn[];
2305
+ /**
2306
+ * Replace oversized tool results with an error telling the agent to narrow
2307
+ * its query. Keeps a small preview so the agent can see what it got.
2308
+ */
2309
+ declare function capToolResultSize(result: unknown, byteCap: number): unknown;
2310
+ /**
2311
+ * Convert persisted ChatTurns into AI SDK ModelMessages.
2312
+ *
2313
+ * Persisted assistant rows store `parts` in UI shape (text + tool-invocation,
2314
+ * each invocation carrying its own `result`). When fed back to the LLM, the
2315
+ * shape MUST match the original multi-step flow: an assistant message
2316
+ * containing a `tool_use` block must end with that block, the IMMEDIATELY
2317
+ * NEXT message must be a tool/user message containing the matching
2318
+ * `tool_result`, and any text the model produced AFTER seeing the tool
2319
+ * result belongs in a SEPARATE assistant message after the tool message.
2320
+ *
2321
+ * Anthropic specifically rejects an assistant message of the form
2322
+ * `[text, tool_use, text]` — the trailing text breaks its `tool_use` →
2323
+ * `tool_result` pairing check. So we walk the parts in order and split at
2324
+ * each tool-invocation boundary, emitting a fresh assistant + tool pair per
2325
+ * tool call, and a final trailing assistant message for any post-tool text.
2326
+ *
2327
+ * Tool-invocation entries with `state: 'call'` (no result — typically an
2328
+ * interrupted stream) are dropped on both sides.
2329
+ */
2330
+ declare function turnsToCoreMessages(turns: ChatTurn[]): ModelMessage[];
2331
+ /**
2332
+ * Convert AI SDK response messages into our persisted UI shape (text +
2333
+ * tool-invocation parts), pairing each assistant tool-call with its tool-
2334
+ * result from the following tool message. Order is chronological.
2335
+ *
2336
+ * Inverse of `turnsToCoreMessages`: takes the v5 `ModelMessage[]` returned
2337
+ * from `streamText`'s `onFinish` and produces the flat `parts` array we
2338
+ * persist on `ai-messages` rows. Reads `c.input` / `c.output` (v5 wire
2339
+ * names) and unwraps `output`'s tagged-union via `unwrapToolOutput`.
2340
+ */
2341
+ declare function buildUiParts(responseMessages: ModelMessage[]): unknown[];
2342
+ /**
2343
+ * Unwrap v5's tagged tool-result `output` to the flat shape we persist.
2344
+ * Errors get remapped to `{ success: false, error }` because
2345
+ * `truncateOldToolResults` preserves entries with that shape across turns —
2346
+ * without the remap, error context would get truncated like a normal result.
2347
+ */
2348
+ declare function unwrapToolOutput(output: unknown): unknown;
2349
+ /**
2350
+ * Pre-stream pipeline with compaction.
2351
+ *
2352
+ * 1. Truncate old tool results.
2353
+ * 2. If a cached summary covers a known message id, replace prior turns with it.
2354
+ * 3. If still over budget, summarize the older half of `working` and return a
2355
+ * `newSummary` for persistence — runs even after cached-summary application
2356
+ * so a long-running chat can re-summarize on subsequent turns.
2357
+ * 4. On summarizer error or missing ids, fall back to a sliding window
2358
+ * (which preserves system messages — see `applySlidingWindow`).
2359
+ */
2360
+ declare function prepareMessagesWithCompaction(messages: ChatTurn[], config: ChatContextConfig, options: {
2361
+ summarizer: Summarizer;
2362
+ cachedSummary?: {
2363
+ text: string;
2364
+ throughId: string;
2365
+ };
2366
+ }): Promise<{
2367
+ messages: ChatTurn[];
2368
+ newSummary?: {
2369
+ text: string;
2370
+ throughId: string;
2371
+ };
2372
+ }>;
2373
+ /**
2374
+ * Build a default summarizer backed by Claude Haiku.
2375
+ *
2376
+ * Billing: defaults to the app owner via `APP_OWNER_JWT` — summarization is
2377
+ * usually infrastructure, not user work. Pass `{ authToken }` to bill a
2378
+ * specific user (e.g. the caller's JWT) instead.
2379
+ */
2380
+ declare function makeDefaultSummarizer(env: DeepSpaceAIEnv, options?: {
2381
+ authToken?: string;
2382
+ }): Summarizer;
2383
+
2384
+ /**
2385
+ * Chat history helpers — wrap RecordRoom's tools API for ai-chats / ai-messages.
2386
+ *
2387
+ * Trust model: every helper sends `X-App-Action: 'true'`, which bypasses
2388
+ * RecordRoom's per-record RBAC. The worker is the trust boundary, not
2389
+ * RecordRoom. Callers MUST verify ownership before invoking write helpers
2390
+ * (`updateChat`, `appendMessage`, `deleteChatCascade`); the worker's
2391
+ * `/api/ai/chat`, `PATCH /api/ai/chats/:id`, and `DELETE /api/ai/chats/:id`
2392
+ * routes do this via a `getChat()` precheck that 404s when the row is
2393
+ * missing or owned by another user. Read helpers (`getChat`, `loadMessages`)
2394
+ * filter by `chatId` against userBound rows, so cross-user reads return
2395
+ * empty — but new consumers should still consider an explicit ownership
2396
+ * check before exposing data.
2397
+ *
2398
+ * The tools API returns records as `{ recordId, data, createdAt, updatedAt }`
2399
+ * envelopes; helpers below flatten them into ChatRow / ChatMessageRow.
2400
+ */
2401
+ type ChatRow = {
2402
+ id: string;
2403
+ userId: string;
2404
+ title: string;
2405
+ model?: string;
2406
+ compactedSummary?: string;
2407
+ compactedThroughId?: string;
2408
+ createdAt: string;
2409
+ updatedAt: string;
2410
+ };
2411
+ type ChatMessageRow = {
2412
+ id: string;
2413
+ chatId: string;
2414
+ userId: string;
2415
+ role: 'user' | 'assistant' | 'system';
2416
+ content: string;
2417
+ parts?: unknown[];
2418
+ createdAt: string;
2419
+ };
2420
+ declare function getChat(stub: DurableObjectStub, chatId: string, userId: string): Promise<ChatRow | null>;
2421
+ declare function createChat(stub: DurableObjectStub, userId: string, opts?: {
2422
+ title?: string;
2423
+ model?: string;
2424
+ }): Promise<ChatRow>;
2425
+ declare function updateChat(stub: DurableObjectStub, chatId: string, userId: string, patch: Partial<Pick<ChatRow, 'title' | 'model' | 'compactedSummary' | 'compactedThroughId'>>): Promise<void>;
2426
+ declare function deleteChatCascade(stub: DurableObjectStub, chatId: string, userId: string): Promise<void>;
2427
+ declare function loadMessages(stub: DurableObjectStub, chatId: string, userId: string): Promise<ChatMessageRow[]>;
2428
+ declare function appendMessage(stub: DurableObjectStub, msg: {
2429
+ id: string;
2430
+ chatId: string;
2431
+ userId: string;
2432
+ role: 'user' | 'assistant' | 'system';
2433
+ content: string;
2434
+ parts?: unknown[];
2435
+ }): Promise<void>;
2258
2436
 
2259
2437
  /**
2260
2438
  * Auth types for the DeepSpace SDK.
@@ -3209,4 +3387,4 @@ type DeepSpaceAuth = ReturnType<typeof createDeepSpaceAuth>;
3209
3387
  /** Collections that bypass schema checks (permissive access) */
3210
3388
  declare const SYSTEM_COLLECTIONS: Set<string>;
3211
3389
 
3212
- export { type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type ApiWorkerEnv, type AuthWorkerEnv, Awareness, type AwarenessState, type AwarenessStates, BASE_USERS_SCHEMA, BUILT_IN_TOOLS, type BaseMessage, BaseRoom, CHANNELS_SCHEMA, CHANNEL_INVITATIONS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, CONVERSATION_SCHEMAS, CanvasRoom, type CanvasShape, type ClientMessage, type CollectionPermissionSummary, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ConnectionAttachment, type ConvMemberData, type ConvMessageData, type ConvReactionData, type ConvReadCursorData, type ConvVoteData, type ConversationStateData, type CronContext, type CronExecution, CronRoom, type CronRoomConfig, type CronTask, DEFAULT_DO_MANIFEST, DEFAULT_MAX_SKEW_MS, DIRECTORY_SCHEMAS, type DOBindings, type DOManifest, type DOManifestEntry, type DeepSpaceAIEnv, type DeepSpaceAIOptions, type DeepSpaceAuth, type DeepSpaceAuthConfig, type DirectoryCommunityData, type DirectoryConversationData, type DirectoryMembershipData, type DirectoryPostData, GLOBAL_DO_TYPES, GLOBAL_DO_TYPE_NAMES, type GameInput, GameRoom, type GameRoomConfig, type GlobalDOType, type HandlerContext, type InternalSignature, type JwtClaims, type JwtVerifierConfig, 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 PermissionAnalysis, type PermissionContext, type PermissionLevel, type PermissionSource, type PlatformWorkerEnv, type Player, type PrefixResult, type PresencePeer, PresenceRoom, type ProtocolMessage, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, RESERVED_COLLECTION_NAMES, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, type ResolvedColumn, type ResolvedPermission, type RolePermissions, SYSTEM_COLLECTIONS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ServerMessage, type SharedConnection, type SignInternalPayloadInput, type StoredRecord, type SyncResult, type TokenDebugInfo, type ToolResult, type ToolSchema, USERS_COLUMNS, type User, type UserAttachment, VOTING_SCHEMAS, type VerifiedAuth, type VerifyInternalSignatureInput, type VerifyOutcome, type VerifyResult, type Viewport, WORKSPACE_SCHEMAS, YjsRoom, analyzePermissions, apiWorkerFetch, authWorkerFetch, buildCronContext, buildInternalPayload, buildTableSelect, canCreate, canDelete, canRead, canUpdate, checkFieldPermissions, clientBuild, coerceValue, collectionTableName, columnId, computeHmacHex, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, dataToColumnValues, decodeJwtPayload, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, getGlobalDOSchemas, getGlobalDOType, getMessageType, getRolePermissions, handleAwarenessMessage, handleSyncMessage, hasContent, isOwner, noopPermissionContext, platformWorkerFetch, readVarUint, readVarUint8Array, resolveColumn, rowToData, serverBuild, signInternalPayload, timingSafeEqualHex, toUint8Array, verifyInternalSignature, verifyJwt, workspaceAccountsSchema, workspaceContentSharesSchema, workspaceEmailHandlesSchema, workspaceFormResponsesSchema, workspacePeopleSchema, workspaceProjectsSchema, workspaceTagsSchema, workspaceTasksSchema, workspaceTeamMembersSchema, workspaceTeamsSchema, workspaceTransactionsSchema, writeVarUint, writeVarUint8Array };
3390
+ export { AI_CHATS_SCHEMA, AI_MESSAGES_SCHEMA, type ActionContext, type ActionHandler, type ActionResult, type ActionTools, type ApiWorkerEnv, type AuthWorkerEnv, Awareness, type AwarenessState, type AwarenessStates, BASE_USERS_SCHEMA, BUILT_IN_TOOLS, type BaseMessage, BaseRoom, CHANNELS_SCHEMA, CHANNEL_INVITATIONS_SCHEMA, CHANNEL_MEMBERS_SCHEMA, CONVERSATION_SCHEMAS, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientMessage, type CollectionPermissionSummary, type CollectionSchema, type ColumnDefinition, type ColumnInterpretation, type ConnectionAttachment, type ConvMemberData, type ConvMessageData, type ConvReactionData, type ConvReadCursorData, type ConvVoteData, type ConversationStateData, type CronContext, type CronExecution, CronRoom, type CronRoomConfig, type CronTask, DEFAULT_CONTEXT_CONFIG, DEFAULT_DO_MANIFEST, DEFAULT_MAX_SKEW_MS, DIRECTORY_SCHEMAS, type DOBindings, type DOManifest, type DOManifestEntry, type DeepSpaceAIEnv, type DeepSpaceAIOptions, type DeepSpaceAuth, type DeepSpaceAuthConfig, type DirectoryCommunityData, type DirectoryConversationData, type DirectoryMembershipData, type DirectoryPostData, GLOBAL_DO_TYPES, GLOBAL_DO_TYPE_NAMES, type GameInput, GameRoom, type GameRoomConfig, type GlobalDOType, type HandlerContext, type InternalSignature, type JwtClaims, type JwtVerifierConfig, 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 PermissionAnalysis, type PermissionContext, type PermissionLevel, type PermissionSource, type PlatformWorkerEnv, type Player, type PrefixResult, type PresencePeer, PresenceRoom, type ProtocolMessage, REACTIONS_SCHEMA, READ_RECEIPTS_SCHEMA, RESERVED_COLLECTION_NAMES, ROLE_ADMIN, ROLE_ANONYMOUS, ROLE_DEFAULT, RecordRoom, type RecordRoomConfig, type ResolvedColumn, type ResolvedPermission, type RolePermissions, SYSTEM_COLLECTIONS, SYSTEM_MANAGED_COLUMNS, SchemaRegistry, type ScopeContext, type ScopedR2Auth, type ScopedR2Config, type ScopedR2Handler, type ServerMessage, type SharedConnection, type SignInternalPayloadInput, type StoredRecord, type Summarizer, type SyncResult, type TokenDebugInfo, type ToolResult, type ToolSchema, USERS_COLUMNS, type User, type UserAttachment, VOTING_SCHEMAS, type VerifiedAuth, type VerifyInternalSignatureInput, type VerifyOutcome, type VerifyResult, type Viewport, WORKSPACE_SCHEMAS, YjsRoom, analyzePermissions, apiWorkerFetch, appendMessage, applySlidingWindow, authWorkerFetch, buildCronContext, buildInternalPayload, buildTableSelect, buildUiParts, canCreate, canDelete, canRead, canUpdate, capToolResultSize, checkFieldPermissions, clientBuild, coerceValue, collectionTableName, columnId, computeHmacHex, createChat, createDecoder, createDeepSpaceAI, createDeepSpaceAuth, createEncoder, createScopedR2Handler, dataToColumnValues, decodeJwtPayload, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, getChat, getGlobalDOSchemas, getGlobalDOType, getMessageType, getRolePermissions, handleAwarenessMessage, handleSyncMessage, hasContent, isOwner, loadMessages, makeDefaultSummarizer, noopPermissionContext, platformWorkerFetch, prepareMessagesWithCompaction, readVarUint, readVarUint8Array, resolveColumn, rowToData, serverBuild, signInternalPayload, timingSafeEqualHex, toUint8Array, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, verifyInternalSignature, verifyJwt, workspaceAccountsSchema, workspaceContentSharesSchema, workspaceEmailHandlesSchema, workspaceFormResponsesSchema, workspacePeopleSchema, workspaceProjectsSchema, workspaceTagsSchema, workspaceTasksSchema, workspaceTeamMembersSchema, workspaceTeamsSchema, workspaceTransactionsSchema, writeVarUint, writeVarUint8Array };