deepspace 0.28.0 → 0.28.1
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/CHANGELOG.md +6 -0
- package/README.md +8 -0
- package/dist/{chunk-652TIGI4.js → chunk-PVEUIQN4.js} +2 -2
- package/dist/{chunk-652TIGI4.js.map → chunk-PVEUIQN4.js.map} +1 -1
- package/dist/cli.js +467 -35
- package/dist/cli.js.map +1 -1
- package/dist/documentation-client-core.js +1 -1
- package/dist/documentation-default-renderer.cjs +1 -1
- package/dist/documentation-react.js +1 -1
- package/dist/documentation-runtime.js +1 -1
- package/dist/documentation-server-core.js +1 -1
- package/dist/documentation.js +1 -1
- package/dist/documentation.js.map +1 -1
- package/dist/server.d.ts +21 -1
- package/dist/server.js +46 -11
- package/dist/server.js.map +1 -1
- package/dist/worker.d.ts +99 -1
- package/dist/worker.js +305 -33
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
package/dist/worker.d.ts
CHANGED
|
@@ -3202,6 +3202,20 @@ interface AppRoleEnv {
|
|
|
3202
3202
|
DEEPSPACE_APP_ID: string;
|
|
3203
3203
|
OWNER_USER_ID: string;
|
|
3204
3204
|
}
|
|
3205
|
+
interface AppMembership {
|
|
3206
|
+
/** True when the caller's row exists in the app's canonical users collection. */
|
|
3207
|
+
member: boolean;
|
|
3208
|
+
role: Role;
|
|
3209
|
+
}
|
|
3210
|
+
/**
|
|
3211
|
+
* Resolve a user's membership and role from the app's canonical users
|
|
3212
|
+
* collection in one read. This is the single definition of "is this user in
|
|
3213
|
+
* the app" — gate new surfaces with it rather than re-deriving membership
|
|
3214
|
+
* from another tool call. Returns null when the read itself failed (room
|
|
3215
|
+
* unreachable, aborted): callers must treat that as "could not verify", never
|
|
3216
|
+
* as "not a member".
|
|
3217
|
+
*/
|
|
3218
|
+
declare function resolveAppMembership(env: AppRoleEnv, userId: string, signal?: AbortSignal): Promise<AppMembership | null>;
|
|
3205
3219
|
/** Resolve a user's current role from the app's canonical users collection. */
|
|
3206
3220
|
declare function resolveAppRole(env: AppRoleEnv, userId: string): Promise<Role>;
|
|
3207
3221
|
|
|
@@ -4021,6 +4035,12 @@ interface VerifyOutcome {
|
|
|
4021
4035
|
*/
|
|
4022
4036
|
declare function verifyJwt(config: JwtVerifierConfig, token: string | null | undefined): Promise<VerifyOutcome>;
|
|
4023
4037
|
|
|
4038
|
+
declare const AGENT_TOKEN_SCOPE = "agent";
|
|
4039
|
+
/** A separate issuer keeps agent credentials invalid at ordinary platform APIs. */
|
|
4040
|
+
declare function agentTokenIssuer(issuer: string): string;
|
|
4041
|
+
/** Verify an agent credential for the exact origin currently receiving it. */
|
|
4042
|
+
declare function verifyAgentToken(config: Omit<JwtVerifierConfig, 'audience'>, token: string | null | undefined, targetOrigin: string): Promise<VerifyOutcome>;
|
|
4043
|
+
|
|
4024
4044
|
/**
|
|
4025
4045
|
* HMAC primitives used by the per-app identity tokens (APP_IDENTITY_TOKEN)
|
|
4026
4046
|
* minted at deploy time and verified on every /internal/* call into the
|
|
@@ -5221,6 +5241,84 @@ interface ClientErrorReport {
|
|
|
5221
5241
|
col?: number;
|
|
5222
5242
|
}
|
|
5223
5243
|
|
|
5244
|
+
/** Wire-size limits shared by the app Worker and the stateless CLI bridge. */
|
|
5245
|
+
/** Maximum JSON body accepted by one tool invocation. */
|
|
5246
|
+
declare const AGENT_TOOL_REQUEST_BODY_CAP: number;
|
|
5247
|
+
/** Maximum JSON response accepted or emitted by the discovery bridge. */
|
|
5248
|
+
declare const AGENT_TOOL_RESPONSE_BODY_CAP: number;
|
|
5249
|
+
|
|
5250
|
+
/**
|
|
5251
|
+
* Authenticated local-assistant tool routes for generated DeepSpace apps.
|
|
5252
|
+
*
|
|
5253
|
+
* The generated worker owns authentication policy; this SDK registrar only
|
|
5254
|
+
* consumes its verified access decision and executes the app's existing AI SDK
|
|
5255
|
+
* tools as that verified user.
|
|
5256
|
+
*/
|
|
5257
|
+
|
|
5258
|
+
interface AgentToolRouteEnv {
|
|
5259
|
+
APP_NAME: string;
|
|
5260
|
+
DEEPSPACE_APP_ID: string;
|
|
5261
|
+
RECORD_ROOMS: DurableObjectNamespace;
|
|
5262
|
+
}
|
|
5263
|
+
/**
|
|
5264
|
+
* The generated worker distinguishes a missing identity (401), a denied
|
|
5265
|
+
* identity (403), and an access check it could not complete (503) — a
|
|
5266
|
+
* transient failure must not present as a permanent permission denial.
|
|
5267
|
+
*/
|
|
5268
|
+
type AgentToolAccessResult = {
|
|
5269
|
+
ok: true;
|
|
5270
|
+
auth: VerifyResult;
|
|
5271
|
+
} | {
|
|
5272
|
+
ok: false;
|
|
5273
|
+
status: 401 | 403 | 503;
|
|
5274
|
+
};
|
|
5275
|
+
interface AgentToolRouteOptions<Env extends AgentToolRouteEnv> {
|
|
5276
|
+
/** Preserve the generated app's existing tool definitions unchanged. */
|
|
5277
|
+
buildTools: (executor: (toolName: string, params: Record<string, unknown>) => Promise<unknown>) => ToolSet;
|
|
5278
|
+
/** Performs app-specific authentication and authorization before tool discovery or execution. */
|
|
5279
|
+
resolveAccess: (request: Request, env: Env) => Promise<AgentToolAccessResult>;
|
|
5280
|
+
}
|
|
5281
|
+
interface UserToolExecutorEnv {
|
|
5282
|
+
DEEPSPACE_APP_ID: string;
|
|
5283
|
+
RECORD_ROOMS: DurableObjectNamespace;
|
|
5284
|
+
}
|
|
5285
|
+
/**
|
|
5286
|
+
* Execute one app tool in the canonical app RecordRoom as the verified user.
|
|
5287
|
+
* Every assistant surface (website chat, local agent) must share this path so
|
|
5288
|
+
* a tool behaves identically regardless of which surface invoked it.
|
|
5289
|
+
*/
|
|
5290
|
+
declare function createUserToolExecutor(env: UserToolExecutorEnv, userId: string, signal: AbortSignal): (toolName: string, params: Record<string, unknown>) => Promise<unknown>;
|
|
5291
|
+
/**
|
|
5292
|
+
* Register the generated app's local assistant tool API.
|
|
5293
|
+
*
|
|
5294
|
+
* Mount before a broad `/_deepspace/*` proxy route so these SDK-owned paths
|
|
5295
|
+
* stay in the app Worker and retain the verified caller identity.
|
|
5296
|
+
*/
|
|
5297
|
+
declare function registerAgentToolRoutes<Env extends AgentToolRouteEnv>(app: Hono<{
|
|
5298
|
+
Bindings: Env;
|
|
5299
|
+
}>, options: AgentToolRouteOptions<Env>): void;
|
|
5300
|
+
|
|
5301
|
+
/**
|
|
5302
|
+
* First-party non-app origins allowed as agent targets on the production app
|
|
5303
|
+
* domain. The token minter and the CLI must agree on this policy, so both the
|
|
5304
|
+
* set AND the "is production" predicate (appDomain === PRODUCTION_APP_DOMAIN)
|
|
5305
|
+
* live here — callers never re-derive either.
|
|
5306
|
+
*/
|
|
5307
|
+
declare const PRODUCTION_OFFICIAL_AGENT_ORIGINS: readonly string[];
|
|
5308
|
+
interface AgentTargetPolicy {
|
|
5309
|
+
appDomain: string;
|
|
5310
|
+
allowLoopback?: boolean;
|
|
5311
|
+
}
|
|
5312
|
+
/** Normalize an agent target only when it is an exact trusted origin. */
|
|
5313
|
+
declare function normalizeAgentTargetOrigin(value: unknown, policy: AgentTargetPolicy): string | null;
|
|
5314
|
+
|
|
5315
|
+
/**
|
|
5316
|
+
* Better Auth session cookie name. The CLI presents it when exchanging a
|
|
5317
|
+
* stored session for JWTs, and the auth worker requires it when minting —
|
|
5318
|
+
* the two sides must agree on the exact name.
|
|
5319
|
+
*/
|
|
5320
|
+
declare const SESSION_COOKIE = "__Secure-better-auth.session_token";
|
|
5321
|
+
|
|
5224
5322
|
/**
|
|
5225
5323
|
* `deepspace logs` wire DTO — the single source of truth for the whitelisted
|
|
5226
5324
|
* shape the platform telemetry reader emits and every consumer reads.
|
|
@@ -5309,4 +5407,4 @@ interface AppLogsResponse {
|
|
|
5309
5407
|
declare const APP_LOG_EVENT_KEYS: readonly ["id", "timestamp", "level", "eventType", "message", "source", "outcome", "request", "exception"];
|
|
5310
5408
|
type AppLogEventKey = (typeof APP_LOG_EVENT_KEYS)[number];
|
|
5311
5409
|
|
|
5312
|
-
export { ACCOUNT_STORAGE_LIMIT_BYTES, ACTION_ROUTES_BEARER_GUARD_MIGRATION_ID, ACTION_TOOLS_DELETE_WHERE_MIGRATION_ID, 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 ApiWorkerEnv, type AppLogEvent, type AppLogEventKey, type AppLogsResponse, 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, CLIENT_LOG_MARKER, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientErrorKind, type ClientErrorReport, 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_DELETE_WHERE_LIMIT, MAX_DEPLOY_ASSET_FILE_BYTES, MAX_ENV_VAR_BYTES, MAX_UPLOAD_PARTS, MAX_UPLOAD_REQUEST_BYTES, MESSAGES_SCHEMA, MSG, MSG_AWARENESS, MSG_SYNC, MSG_SYNC_STEP1, MSG_SYNC_STEP2, MSG_SYNC_UPDATE, MSG_YJS_AWARENESS, MSG_YJS_SYNC, type MessageHandlers, type MsgType, type MutateActionData, type 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, SECURE_ROOM_BOUNDARIES_MIGRATION_ID, 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 ValidationError, type VerifiedAuth, type VerifyOutcome, type VerifyResult, type Viewport, WORKER_OWNED_NOT_FOUND_MIGRATION_ID, YjsRoom, 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, dataToColumnValues, decodeJwtPayload, deepSpaceAgentErrorSummary, deleteChatCascade, dispatch, encode, encodeAwarenessMessage, encodeSyncStep1, encodeSyncStep2, encodeUpdate, enqueueJob, epochSeconds, folderFilter, formatBytes, getChat, getDeepSpaceAIModel, getMessageType, getRolePermissions, handleAwarenessMessage, handleClientErrorReport, handleSyncMessage, hasContent, isAnonymousUserId, isAssetNotFoundHandling, isAutoProvision, isFilesVerbPath, isOwner, isPlatformReservedPath, isTestAccountClaims, isTestAccountEmail, isTestAccountTier, knowledge, lintSchema, lintSchemaSet, lintSchemas, listDeepSpaceAgentModels, loadMessages, makeDefaultSummarizer, matchOrigin, meterAi, meterUsage, meterVectorize, mintAppId, mintUlid, noopPermissionContext, normalizeKnowledgeFolder, parseQuotaLimit, platformCorsPatterns, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, readVarUint, readVarUint8Array, registerClientErrorRoute, registerDeepSpaceDocumentation, registryErrorJson, registryStub, resolveAppName, resolveAppRole, resolveColumn, resolveCompatibilityFlags, resolveDeepSpaceAgentModel, rowToData, runMigrations, serverBuild, storageLimitForTier, storageQuotaMessage, streamDeepSpaceAgent, timingSafeEqualHex, timingSafeEqualStrings, toUint8Array, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppMigrationIds, validateAppName, validateBindingManifest, validateDoManifest, verifyJwt, writeVarUint, writeVarUint8Array };
|
|
5410
|
+
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, CLIENT_LOG_MARKER, COST_RATES, CanvasRoom, type CanvasShape, type ChatContextConfig, type ChatMessageRow, type ChatRow, type ChatTurn, type ClientErrorKind, type ClientErrorReport, 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_DELETE_WHERE_LIMIT, MAX_DEPLOY_ASSET_FILE_BYTES, MAX_ENV_VAR_BYTES, MAX_UPLOAD_PARTS, MAX_UPLOAD_REQUEST_BYTES, MESSAGES_SCHEMA, MSG, MSG_AWARENESS, MSG_SYNC, MSG_SYNC_STEP1, MSG_SYNC_STEP2, MSG_SYNC_UPDATE, MSG_YJS_AWARENESS, MSG_YJS_SYNC, type MessageHandlers, type MsgType, type MutateActionData, 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, 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, handleClientErrorReport, handleSyncMessage, hasContent, isAnonymousUserId, isAssetNotFoundHandling, isAutoProvision, isFilesVerbPath, isOwner, isPlatformReservedPath, isTestAccountClaims, isTestAccountEmail, isTestAccountTier, knowledge, lintSchema, lintSchemaSet, lintSchemas, listDeepSpaceAgentModels, loadMessages, makeDefaultSummarizer, matchOrigin, meterAi, meterUsage, meterVectorize, mintAppId, mintUlid, noopPermissionContext, normalizeAgentTargetOrigin, normalizeKnowledgeFolder, parseQuotaLimit, platformCorsPatterns, platformWorkerFetch, prepareMessagesWithCompaction, priceBindingUsageEvent, readVarUint, readVarUint8Array, registerAgentToolRoutes, registerClientErrorRoute, registerDeepSpaceDocumentation, registryErrorJson, registryStub, resolveAppMembership, resolveAppName, resolveAppRole, resolveColumn, resolveCompatibilityFlags, resolveDeepSpaceAgentModel, rowToData, runMigrations, serverBuild, storageLimitForTier, storageQuotaMessage, streamDeepSpaceAgent, timingSafeEqualHex, timingSafeEqualStrings, toUint8Array, totalChars, truncateOldToolResults, turnsToCoreMessages, unwrapToolOutput, updateChat, validateAppMigrationIds, validateAppName, validateBindingManifest, validateDoManifest, verifyAgentToken, verifyJwt, writeVarUint, writeVarUint8Array };
|
package/dist/worker.js
CHANGED
|
@@ -7450,8 +7450,8 @@ function buildCronContext(env, ownerUserId, roomId = "default") {
|
|
|
7450
7450
|
}
|
|
7451
7451
|
|
|
7452
7452
|
// src/server/utils/app-role.ts
|
|
7453
|
-
async function
|
|
7454
|
-
if (userId === env.OWNER_USER_ID) return "admin";
|
|
7453
|
+
async function resolveAppMembership(env, userId, signal) {
|
|
7454
|
+
if (userId === env.OWNER_USER_ID) return { member: true, role: "admin" };
|
|
7455
7455
|
const stub = env.RECORD_ROOMS.get(env.RECORD_ROOMS.idFromName(`app:${env.DEEPSPACE_APP_ID}`));
|
|
7456
7456
|
try {
|
|
7457
7457
|
const res = await stub.fetch(
|
|
@@ -7465,16 +7465,21 @@ async function resolveAppRole(env, userId) {
|
|
|
7465
7465
|
body: JSON.stringify({
|
|
7466
7466
|
tool: "records.get",
|
|
7467
7467
|
params: { collection: "users", recordId: userId }
|
|
7468
|
-
})
|
|
7468
|
+
}),
|
|
7469
|
+
signal
|
|
7469
7470
|
})
|
|
7470
7471
|
);
|
|
7471
7472
|
const json = await res.json();
|
|
7472
|
-
|
|
7473
|
-
|
|
7473
|
+
if (!json.success || !json.data?.record) return { member: false, role: "viewer" };
|
|
7474
|
+
const role = json.data.record.data?.role;
|
|
7475
|
+
return { member: true, role: isWriterRole(role) ? role : "viewer" };
|
|
7474
7476
|
} catch {
|
|
7475
|
-
return
|
|
7477
|
+
return null;
|
|
7476
7478
|
}
|
|
7477
7479
|
}
|
|
7480
|
+
async function resolveAppRole(env, userId) {
|
|
7481
|
+
return (await resolveAppMembership(env, userId))?.role ?? "viewer";
|
|
7482
|
+
}
|
|
7478
7483
|
|
|
7479
7484
|
// src/server/utils/ai.ts
|
|
7480
7485
|
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
@@ -7909,6 +7914,9 @@ function locateTrimmableArray(result) {
|
|
|
7909
7914
|
}
|
|
7910
7915
|
return void 0;
|
|
7911
7916
|
}
|
|
7917
|
+
function utf8ByteLength(text) {
|
|
7918
|
+
return new TextEncoder().encode(text).byteLength;
|
|
7919
|
+
}
|
|
7912
7920
|
function capToolResultSize(result, byteCap) {
|
|
7913
7921
|
let serialized;
|
|
7914
7922
|
try {
|
|
@@ -7917,7 +7925,7 @@ function capToolResultSize(result, byteCap) {
|
|
|
7917
7925
|
return { success: false, error: "Tool result could not be serialized." };
|
|
7918
7926
|
}
|
|
7919
7927
|
if (typeof serialized !== "string") return result;
|
|
7920
|
-
if (serialized
|
|
7928
|
+
if (utf8ByteLength(serialized) <= byteCap) return result;
|
|
7921
7929
|
if (result && typeof result === "object") {
|
|
7922
7930
|
const located = locateTrimmableArray(result);
|
|
7923
7931
|
if (located) {
|
|
@@ -7926,7 +7934,7 @@ function capToolResultSize(result, byteCap) {
|
|
|
7926
7934
|
const build = (k) => setPath(result, path, items.slice(0, k), { truncated: true, returned: k, total });
|
|
7927
7935
|
const fits = (k) => {
|
|
7928
7936
|
try {
|
|
7929
|
-
return JSON.stringify(build(k))
|
|
7937
|
+
return utf8ByteLength(JSON.stringify(build(k))) <= byteCap;
|
|
7930
7938
|
} catch {
|
|
7931
7939
|
return false;
|
|
7932
7940
|
}
|
|
@@ -7946,7 +7954,7 @@ function capToolResultSize(result, byteCap) {
|
|
|
7946
7954
|
return {
|
|
7947
7955
|
success: false,
|
|
7948
7956
|
truncated: true,
|
|
7949
|
-
error: `Tool result exceeded ${byteCap} bytes (was ${serialized
|
|
7957
|
+
error: `Tool result exceeded ${byteCap} bytes (was ${utf8ByteLength(serialized)}). Retry with a narrower query (e.g. add a \`where\` filter, reduce \`limit\`, or call records.get for a single record).`,
|
|
7950
7958
|
preview: serialized.slice(0, 2e3)
|
|
7951
7959
|
};
|
|
7952
7960
|
}
|
|
@@ -8098,10 +8106,15 @@ async function prepareMessagesWithCompaction(messages, config, options) {
|
|
|
8098
8106
|
newSummary: { text, throughId }
|
|
8099
8107
|
};
|
|
8100
8108
|
} catch (err) {
|
|
8101
|
-
console.error(
|
|
8109
|
+
console.error(
|
|
8110
|
+
"prepareMessagesWithCompaction: summarizer failed, falling back to sliding window",
|
|
8111
|
+
err
|
|
8112
|
+
);
|
|
8102
8113
|
}
|
|
8103
8114
|
} else {
|
|
8104
|
-
console.warn(
|
|
8115
|
+
console.warn(
|
|
8116
|
+
"prepareMessagesWithCompaction: messages lack ids; cannot anchor a summary, falling back to sliding window"
|
|
8117
|
+
);
|
|
8105
8118
|
}
|
|
8106
8119
|
return {
|
|
8107
8120
|
messages: applySlidingWindow(working, config.contextBudget, config.minKept)
|
|
@@ -9100,38 +9113,43 @@ function documentationLimiterErrorSummary(error) {
|
|
|
9100
9113
|
});
|
|
9101
9114
|
}
|
|
9102
9115
|
|
|
9103
|
-
// src/
|
|
9104
|
-
var
|
|
9116
|
+
// src/shared/bounded-body.ts
|
|
9117
|
+
var BodyTooLargeError = class extends Error {
|
|
9105
9118
|
constructor(maxBytes) {
|
|
9106
|
-
super(`
|
|
9119
|
+
super(`Body exceeds ${maxBytes} bytes`);
|
|
9107
9120
|
this.maxBytes = maxBytes;
|
|
9108
|
-
this.name = "
|
|
9121
|
+
this.name = "BodyTooLargeError";
|
|
9109
9122
|
}
|
|
9110
9123
|
};
|
|
9111
|
-
async function
|
|
9124
|
+
async function readBoundedBodyText(source, maxBytes) {
|
|
9112
9125
|
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {
|
|
9113
9126
|
throw new TypeError("maxBytes must be a positive safe integer");
|
|
9114
9127
|
}
|
|
9115
|
-
const declared =
|
|
9128
|
+
const declared = source.headers.get("content-length");
|
|
9116
9129
|
if (declared && /^\d+$/.test(declared.trim()) && Number(declared) > maxBytes) {
|
|
9117
|
-
|
|
9130
|
+
await source.body?.cancel().catch(() => void 0);
|
|
9131
|
+
throw new BodyTooLargeError(maxBytes);
|
|
9118
9132
|
}
|
|
9119
|
-
if (!
|
|
9120
|
-
const reader =
|
|
9133
|
+
if (!source.body) return "";
|
|
9134
|
+
const reader = source.body.getReader();
|
|
9121
9135
|
const decoder = new TextDecoder();
|
|
9122
9136
|
let bytes = 0;
|
|
9123
9137
|
let text = "";
|
|
9124
|
-
|
|
9125
|
-
|
|
9126
|
-
|
|
9127
|
-
|
|
9128
|
-
|
|
9129
|
-
|
|
9130
|
-
|
|
9138
|
+
try {
|
|
9139
|
+
while (true) {
|
|
9140
|
+
const chunk = await reader.read();
|
|
9141
|
+
if (chunk.done) break;
|
|
9142
|
+
bytes += chunk.value.byteLength;
|
|
9143
|
+
if (bytes > maxBytes) {
|
|
9144
|
+
await reader.cancel().catch(() => void 0);
|
|
9145
|
+
throw new BodyTooLargeError(maxBytes);
|
|
9146
|
+
}
|
|
9147
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
9131
9148
|
}
|
|
9132
|
-
text
|
|
9149
|
+
return text + decoder.decode();
|
|
9150
|
+
} finally {
|
|
9151
|
+
reader.releaseLock();
|
|
9133
9152
|
}
|
|
9134
|
-
return text + decoder.decode();
|
|
9135
9153
|
}
|
|
9136
9154
|
|
|
9137
9155
|
// src/documentation/worker/assistant-routes.ts
|
|
@@ -9171,13 +9189,13 @@ function registerDocumentationAssistantRoutes(app, resolveAuth, publicBasePath =
|
|
|
9171
9189
|
}
|
|
9172
9190
|
let body = null;
|
|
9173
9191
|
try {
|
|
9174
|
-
const raw = await
|
|
9192
|
+
const raw = await readBoundedBodyText(c.req.raw, MAX_REQUEST_BYTES);
|
|
9175
9193
|
const parsed = JSON.parse(raw);
|
|
9176
9194
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
9177
9195
|
body = parsed;
|
|
9178
9196
|
}
|
|
9179
9197
|
} catch (error) {
|
|
9180
|
-
if (error instanceof
|
|
9198
|
+
if (error instanceof BodyTooLargeError) {
|
|
9181
9199
|
return c.json({ error: `request exceeds ${MAX_REQUEST_BYTES} bytes` }, 413);
|
|
9182
9200
|
}
|
|
9183
9201
|
return c.json({ error: "request body must be valid JSON" }, 400);
|
|
@@ -9597,9 +9615,9 @@ function registerDocumentationMcpRoutes(app, publicBasePath = DOCUMENTATION_BASE
|
|
|
9597
9615
|
}
|
|
9598
9616
|
let raw;
|
|
9599
9617
|
try {
|
|
9600
|
-
raw = await
|
|
9618
|
+
raw = await readBoundedBodyText(c.req.raw, MAX_REQUEST_BYTES2);
|
|
9601
9619
|
} catch (error) {
|
|
9602
|
-
if (error instanceof
|
|
9620
|
+
if (error instanceof BodyTooLargeError) {
|
|
9603
9621
|
return mcpError(null, -32600, `Request exceeds ${MAX_REQUEST_BYTES2} bytes`, 413);
|
|
9604
9622
|
}
|
|
9605
9623
|
return mcpError(null, -32700, "Unable to read request body", 400);
|
|
@@ -9928,6 +9946,24 @@ async function verifyJwt(config, token) {
|
|
|
9928
9946
|
}
|
|
9929
9947
|
}
|
|
9930
9948
|
|
|
9949
|
+
// src/server/auth/agentToken.ts
|
|
9950
|
+
var AGENT_TOKEN_SCOPE = "agent";
|
|
9951
|
+
function agentTokenIssuer(issuer) {
|
|
9952
|
+
return `${issuer.replace(/\/+$/, "")}/agent`;
|
|
9953
|
+
}
|
|
9954
|
+
async function verifyAgentToken(config, token, targetOrigin) {
|
|
9955
|
+
const outcome = await verifyJwt(
|
|
9956
|
+
{
|
|
9957
|
+
...config,
|
|
9958
|
+
issuer: agentTokenIssuer(config.issuer),
|
|
9959
|
+
audience: targetOrigin
|
|
9960
|
+
},
|
|
9961
|
+
token
|
|
9962
|
+
);
|
|
9963
|
+
if (!outcome.result || outcome.result.claims.scope === AGENT_TOKEN_SCOPE) return outcome;
|
|
9964
|
+
return { ...outcome, result: null, error: new Error("Invalid agent token scope") };
|
|
9965
|
+
}
|
|
9966
|
+
|
|
9931
9967
|
// src/server/auth/internalAuth.ts
|
|
9932
9968
|
var nodeCryptoPromise = null;
|
|
9933
9969
|
async function loadNodeCrypto() {
|
|
@@ -10206,6 +10242,231 @@ function registerClientErrorRoute(app) {
|
|
|
10206
10242
|
app.post(CLIENT_ERROR_PATH, (c) => handleClientErrorReport(c.req.raw));
|
|
10207
10243
|
}
|
|
10208
10244
|
|
|
10245
|
+
// src/server/agent-tools.ts
|
|
10246
|
+
import { asSchema } from "ai";
|
|
10247
|
+
|
|
10248
|
+
// src/shared/agent-tool-protocol.ts
|
|
10249
|
+
var AGENT_TOOL_REQUEST_BODY_CAP = 64 * 1024;
|
|
10250
|
+
var AGENT_TOOL_RESPONSE_BODY_CAP = 1024 * 1024;
|
|
10251
|
+
|
|
10252
|
+
// src/server/agent-tools.ts
|
|
10253
|
+
function jsonResponse3(body, status = 200) {
|
|
10254
|
+
return rawJsonResponse(JSON.stringify(body), status);
|
|
10255
|
+
}
|
|
10256
|
+
function rawJsonResponse(body, status = 200) {
|
|
10257
|
+
return new Response(body, {
|
|
10258
|
+
status,
|
|
10259
|
+
headers: {
|
|
10260
|
+
"Cache-Control": "no-store",
|
|
10261
|
+
"Content-Type": "application/json; charset=utf-8"
|
|
10262
|
+
}
|
|
10263
|
+
});
|
|
10264
|
+
}
|
|
10265
|
+
function errorResponse(status, code) {
|
|
10266
|
+
const errors = {
|
|
10267
|
+
unauthenticated: "Authentication is required.",
|
|
10268
|
+
forbidden: "You are not allowed to use assistant tools.",
|
|
10269
|
+
access_check_unavailable: "Access could not be verified. Try again.",
|
|
10270
|
+
tool_not_found: "The requested tool is not available.",
|
|
10271
|
+
invalid_json: "The request body must be valid JSON.",
|
|
10272
|
+
invalid_tool_input: "The tool input is invalid.",
|
|
10273
|
+
payload_too_large: "The request body is too large.",
|
|
10274
|
+
tool_configuration_error: "Assistant tools are not configured correctly.",
|
|
10275
|
+
tool_execution_failed: "The tool could not be executed.",
|
|
10276
|
+
invalid_tool_result: "The tool returned an invalid result.",
|
|
10277
|
+
tool_result_too_large: "The tool returned a result that is too large."
|
|
10278
|
+
};
|
|
10279
|
+
return jsonResponse3({ ok: false, code, error: errors[code] }, status);
|
|
10280
|
+
}
|
|
10281
|
+
function parseToolRequestBody(text) {
|
|
10282
|
+
let parsed;
|
|
10283
|
+
try {
|
|
10284
|
+
parsed = JSON.parse(text);
|
|
10285
|
+
} catch {
|
|
10286
|
+
return void 0;
|
|
10287
|
+
}
|
|
10288
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
10289
|
+
if (!Object.hasOwn(parsed, "input")) return null;
|
|
10290
|
+
return { input: parsed.input };
|
|
10291
|
+
}
|
|
10292
|
+
function isAsyncIterable(value) {
|
|
10293
|
+
return value !== null && (typeof value === "object" || typeof value === "function") && Symbol.asyncIterator in value;
|
|
10294
|
+
}
|
|
10295
|
+
function jsonText(value) {
|
|
10296
|
+
try {
|
|
10297
|
+
const serialized = JSON.stringify(value);
|
|
10298
|
+
return typeof serialized === "string" ? serialized : void 0;
|
|
10299
|
+
} catch {
|
|
10300
|
+
return void 0;
|
|
10301
|
+
}
|
|
10302
|
+
}
|
|
10303
|
+
function executableTool(tools, name) {
|
|
10304
|
+
if (!Object.hasOwn(tools, name)) return void 0;
|
|
10305
|
+
const tool3 = tools[name];
|
|
10306
|
+
return typeof tool3.execute === "function" ? { ...tool3, execute: tool3.execute } : void 0;
|
|
10307
|
+
}
|
|
10308
|
+
function toolMetadata(tools) {
|
|
10309
|
+
return Object.entries(tools).flatMap(([name, tool3]) => {
|
|
10310
|
+
if (typeof tool3.execute !== "function") return [];
|
|
10311
|
+
const inputSchema = asSchema(tool3.inputSchema);
|
|
10312
|
+
const entry = {
|
|
10313
|
+
name,
|
|
10314
|
+
description: typeof tool3.description === "string" ? tool3.description : "",
|
|
10315
|
+
inputSchema: inputSchema.jsonSchema
|
|
10316
|
+
};
|
|
10317
|
+
if (tool3.outputSchema) entry.outputSchema = asSchema(tool3.outputSchema).jsonSchema;
|
|
10318
|
+
return [entry];
|
|
10319
|
+
}).sort((left, right) => left.name.localeCompare(right.name));
|
|
10320
|
+
}
|
|
10321
|
+
function createUserToolExecutor(env, userId, signal) {
|
|
10322
|
+
const roomId = env.RECORD_ROOMS.idFromName(`app:${env.DEEPSPACE_APP_ID}`);
|
|
10323
|
+
const room = env.RECORD_ROOMS.get(roomId);
|
|
10324
|
+
return async (toolName, params) => {
|
|
10325
|
+
const response = await room.fetch(
|
|
10326
|
+
new Request("https://internal/api/tools/execute", {
|
|
10327
|
+
method: "POST",
|
|
10328
|
+
headers: {
|
|
10329
|
+
"Content-Type": "application/json",
|
|
10330
|
+
"X-User-Id": userId
|
|
10331
|
+
},
|
|
10332
|
+
body: JSON.stringify({ tool: toolName, params }),
|
|
10333
|
+
signal
|
|
10334
|
+
})
|
|
10335
|
+
);
|
|
10336
|
+
return capToolResultSize(await response.json(), DEFAULT_CONTEXT_CONFIG.toolResultCap);
|
|
10337
|
+
};
|
|
10338
|
+
}
|
|
10339
|
+
async function resolveCallerTools(options, request2, env) {
|
|
10340
|
+
let access;
|
|
10341
|
+
try {
|
|
10342
|
+
access = await options.resolveAccess(request2, env);
|
|
10343
|
+
} catch {
|
|
10344
|
+
return errorResponse(500, "tool_configuration_error");
|
|
10345
|
+
}
|
|
10346
|
+
if (!access.ok) {
|
|
10347
|
+
return errorResponse(
|
|
10348
|
+
access.status,
|
|
10349
|
+
access.status === 401 ? "unauthenticated" : access.status === 403 ? "forbidden" : "access_check_unavailable"
|
|
10350
|
+
);
|
|
10351
|
+
}
|
|
10352
|
+
try {
|
|
10353
|
+
return options.buildTools(createUserToolExecutor(env, access.auth.userId, request2.signal));
|
|
10354
|
+
} catch {
|
|
10355
|
+
return errorResponse(500, "tool_configuration_error");
|
|
10356
|
+
}
|
|
10357
|
+
}
|
|
10358
|
+
function registerAgentToolRoutes(app, options) {
|
|
10359
|
+
app.get("/_deepspace/agent/tools", async (c) => {
|
|
10360
|
+
const tools = await resolveCallerTools(options, c.req.raw, c.env);
|
|
10361
|
+
if (tools instanceof Response) return tools;
|
|
10362
|
+
try {
|
|
10363
|
+
const serialized = jsonText({
|
|
10364
|
+
ok: true,
|
|
10365
|
+
app: { id: c.env.DEEPSPACE_APP_ID, name: c.env.APP_NAME },
|
|
10366
|
+
tools: toolMetadata(tools)
|
|
10367
|
+
});
|
|
10368
|
+
if (!serialized || utf8ByteLength(serialized) > AGENT_TOOL_RESPONSE_BODY_CAP) {
|
|
10369
|
+
return errorResponse(500, "tool_configuration_error");
|
|
10370
|
+
}
|
|
10371
|
+
return rawJsonResponse(serialized);
|
|
10372
|
+
} catch {
|
|
10373
|
+
return errorResponse(500, "tool_configuration_error");
|
|
10374
|
+
}
|
|
10375
|
+
});
|
|
10376
|
+
app.post("/_deepspace/agent/tools/:name", async (c) => {
|
|
10377
|
+
const tools = await resolveCallerTools(options, c.req.raw, c.env);
|
|
10378
|
+
if (tools instanceof Response) return tools;
|
|
10379
|
+
let tool3;
|
|
10380
|
+
try {
|
|
10381
|
+
tool3 = executableTool(tools, c.req.param("name"));
|
|
10382
|
+
} catch {
|
|
10383
|
+
return errorResponse(500, "tool_configuration_error");
|
|
10384
|
+
}
|
|
10385
|
+
if (!tool3) return errorResponse(404, "tool_not_found");
|
|
10386
|
+
let text;
|
|
10387
|
+
try {
|
|
10388
|
+
text = await readBoundedBodyText(c.req.raw, AGENT_TOOL_REQUEST_BODY_CAP);
|
|
10389
|
+
} catch (error) {
|
|
10390
|
+
return error instanceof BodyTooLargeError ? errorResponse(413, "payload_too_large") : errorResponse(400, "invalid_json");
|
|
10391
|
+
}
|
|
10392
|
+
const body = parseToolRequestBody(text);
|
|
10393
|
+
if (body === void 0) return errorResponse(400, "invalid_json");
|
|
10394
|
+
if (body === null) return errorResponse(400, "invalid_tool_input");
|
|
10395
|
+
let input = body.input;
|
|
10396
|
+
try {
|
|
10397
|
+
const validation = asSchema(tool3.inputSchema).validate;
|
|
10398
|
+
if (validation) {
|
|
10399
|
+
const result = await validation(input);
|
|
10400
|
+
if (!result.success) return errorResponse(400, "invalid_tool_input");
|
|
10401
|
+
input = result.value;
|
|
10402
|
+
}
|
|
10403
|
+
} catch {
|
|
10404
|
+
return errorResponse(400, "invalid_tool_input");
|
|
10405
|
+
}
|
|
10406
|
+
let output;
|
|
10407
|
+
try {
|
|
10408
|
+
output = await tool3.execute(input, {
|
|
10409
|
+
toolCallId: crypto.randomUUID(),
|
|
10410
|
+
messages: [],
|
|
10411
|
+
abortSignal: c.req.raw.signal
|
|
10412
|
+
});
|
|
10413
|
+
} catch {
|
|
10414
|
+
return errorResponse(500, "tool_execution_failed");
|
|
10415
|
+
}
|
|
10416
|
+
if (isAsyncIterable(output)) return errorResponse(500, "invalid_tool_result");
|
|
10417
|
+
try {
|
|
10418
|
+
if (tool3.outputSchema) {
|
|
10419
|
+
const validation = asSchema(tool3.outputSchema).validate;
|
|
10420
|
+
if (validation) {
|
|
10421
|
+
const result = await validation(output);
|
|
10422
|
+
if (!result.success) return errorResponse(500, "invalid_tool_result");
|
|
10423
|
+
output = result.value;
|
|
10424
|
+
}
|
|
10425
|
+
}
|
|
10426
|
+
} catch {
|
|
10427
|
+
return errorResponse(500, "invalid_tool_result");
|
|
10428
|
+
}
|
|
10429
|
+
const serialized = jsonText(output === void 0 ? null : output);
|
|
10430
|
+
if (!serialized) return errorResponse(500, "invalid_tool_result");
|
|
10431
|
+
if (utf8ByteLength(serialized) > DEFAULT_CONTEXT_CONFIG.toolResultCap) {
|
|
10432
|
+
return errorResponse(500, "tool_result_too_large");
|
|
10433
|
+
}
|
|
10434
|
+
return rawJsonResponse(`{"ok":true,"result":${serialized}}`);
|
|
10435
|
+
});
|
|
10436
|
+
app.all("/_deepspace/agent", () => errorResponse(404, "tool_not_found"));
|
|
10437
|
+
app.all("/_deepspace/agent/*", () => errorResponse(404, "tool_not_found"));
|
|
10438
|
+
}
|
|
10439
|
+
|
|
10440
|
+
// src/server/agent-target.ts
|
|
10441
|
+
var PRODUCTION_OFFICIAL_AGENT_ORIGINS = ["https://admin.deep.space"];
|
|
10442
|
+
var PRODUCTION_APP_DOMAIN = "app.space";
|
|
10443
|
+
function normalizeAgentTargetOrigin(value, policy) {
|
|
10444
|
+
if (typeof value !== "string" || !value) return null;
|
|
10445
|
+
let url;
|
|
10446
|
+
try {
|
|
10447
|
+
url = new URL(value);
|
|
10448
|
+
} catch {
|
|
10449
|
+
return null;
|
|
10450
|
+
}
|
|
10451
|
+
if (url.username || url.password || url.search || url.hash || url.pathname !== "/") return null;
|
|
10452
|
+
const hostname = url.hostname.toLowerCase();
|
|
10453
|
+
const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(hostname);
|
|
10454
|
+
if (loopback) {
|
|
10455
|
+
return policy.allowLoopback && ["http:", "https:"].includes(url.protocol) ? url.origin : null;
|
|
10456
|
+
}
|
|
10457
|
+
if (url.protocol !== "https:" || url.port) return null;
|
|
10458
|
+
if (policy.appDomain.toLowerCase() === PRODUCTION_APP_DOMAIN && PRODUCTION_OFFICIAL_AGENT_ORIGINS.includes(url.origin)) {
|
|
10459
|
+
return url.origin;
|
|
10460
|
+
}
|
|
10461
|
+
const suffix = `.${policy.appDomain.toLowerCase()}`;
|
|
10462
|
+
if (!hostname.endsWith(suffix)) return null;
|
|
10463
|
+
const label = hostname.slice(0, -suffix.length);
|
|
10464
|
+
return !label.includes(".") && validateAppName(label).valid ? url.origin : null;
|
|
10465
|
+
}
|
|
10466
|
+
|
|
10467
|
+
// src/shared/auth-session.ts
|
|
10468
|
+
var SESSION_COOKIE = "__Secure-better-auth.session_token";
|
|
10469
|
+
|
|
10209
10470
|
// src/shared/log-events.ts
|
|
10210
10471
|
var LOG_LEVELS = ["debug", "log", "info", "warn", "error"];
|
|
10211
10472
|
var APP_LOG_EVENT_KEYS = [
|
|
@@ -10223,6 +10484,9 @@ export {
|
|
|
10223
10484
|
ACCOUNT_STORAGE_LIMIT_BYTES,
|
|
10224
10485
|
ACTION_ROUTES_BEARER_GUARD_MIGRATION_ID,
|
|
10225
10486
|
ACTION_TOOLS_DELETE_WHERE_MIGRATION_ID,
|
|
10487
|
+
AGENT_TOKEN_SCOPE,
|
|
10488
|
+
AGENT_TOOL_REQUEST_BODY_CAP,
|
|
10489
|
+
AGENT_TOOL_RESPONSE_BODY_CAP,
|
|
10226
10490
|
AI_CHATS_SCHEMA,
|
|
10227
10491
|
AI_MESSAGES_SCHEMA,
|
|
10228
10492
|
ALLOWED_BINDING_TYPES,
|
|
@@ -10274,6 +10538,7 @@ export {
|
|
|
10274
10538
|
MSG_SYNC_UPDATE,
|
|
10275
10539
|
MSG_YJS_AWARENESS,
|
|
10276
10540
|
MSG_YJS_SYNC,
|
|
10541
|
+
PRODUCTION_OFFICIAL_AGENT_ORIGINS,
|
|
10277
10542
|
PresenceRoom,
|
|
10278
10543
|
REACTIONS_SCHEMA,
|
|
10279
10544
|
READ_RECEIPTS_SCHEMA,
|
|
@@ -10292,6 +10557,7 @@ export {
|
|
|
10292
10557
|
RegistryClientError,
|
|
10293
10558
|
SDK_RUN_WORKER_FIRST,
|
|
10294
10559
|
SECURE_ROOM_BOUNDARIES_MIGRATION_ID,
|
|
10560
|
+
SESSION_COOKIE,
|
|
10295
10561
|
STRICT_APP_ID_RE,
|
|
10296
10562
|
SYSTEM_ASSIGNED_COLUMNS,
|
|
10297
10563
|
SYSTEM_COLLECTIONS,
|
|
@@ -10304,6 +10570,7 @@ export {
|
|
|
10304
10570
|
USERS_COLUMNS,
|
|
10305
10571
|
WORKER_OWNED_NOT_FOUND_MIGRATION_ID,
|
|
10306
10572
|
YjsRoom,
|
|
10573
|
+
agentTokenIssuer,
|
|
10307
10574
|
apiWorkerFetch,
|
|
10308
10575
|
appendMessage,
|
|
10309
10576
|
applyAiToolDefaults,
|
|
@@ -10337,6 +10604,7 @@ export {
|
|
|
10337
10604
|
createDeepSpaceAuth,
|
|
10338
10605
|
createEncoder,
|
|
10339
10606
|
createScopedR2Handler,
|
|
10607
|
+
createUserToolExecutor,
|
|
10340
10608
|
dataToColumnValues,
|
|
10341
10609
|
decodeJwtPayload,
|
|
10342
10610
|
deepSpaceAgentErrorSummary,
|
|
@@ -10382,6 +10650,7 @@ export {
|
|
|
10382
10650
|
mintAppId,
|
|
10383
10651
|
mintUlid,
|
|
10384
10652
|
noopPermissionContext,
|
|
10653
|
+
normalizeAgentTargetOrigin,
|
|
10385
10654
|
normalizeKnowledgeFolder,
|
|
10386
10655
|
parseQuotaLimit,
|
|
10387
10656
|
platformCorsPatterns,
|
|
@@ -10390,10 +10659,12 @@ export {
|
|
|
10390
10659
|
priceBindingUsageEvent,
|
|
10391
10660
|
readVarUint,
|
|
10392
10661
|
readVarUint8Array,
|
|
10662
|
+
registerAgentToolRoutes,
|
|
10393
10663
|
registerClientErrorRoute,
|
|
10394
10664
|
registerDeepSpaceDocumentation,
|
|
10395
10665
|
registryErrorJson,
|
|
10396
10666
|
registryStub,
|
|
10667
|
+
resolveAppMembership,
|
|
10397
10668
|
resolveAppName,
|
|
10398
10669
|
resolveAppRole,
|
|
10399
10670
|
resolveColumn,
|
|
@@ -10417,6 +10688,7 @@ export {
|
|
|
10417
10688
|
validateAppName,
|
|
10418
10689
|
validateBindingManifest,
|
|
10419
10690
|
validateDoManifest,
|
|
10691
|
+
verifyAgentToken,
|
|
10420
10692
|
verifyJwt,
|
|
10421
10693
|
writeVarUint,
|
|
10422
10694
|
writeVarUint8Array
|