@standardagents/builder 0.37.7 → 0.38.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.
@@ -1,7 +1,7 @@
1
1
  import { DurableObjectStorage } from '@cloudflare/workers-types';
2
2
  import { ZodObject, ZodRawShape } from 'zod';
3
3
  import { N as NamespacedRegistry } from './types-Bpe7IANZ.js';
4
- import { ThreadState, ToolResult as ToolResult$1, VariableDefinition, HookName, HookSignatures, HookMessage, HookToolCall, HookToolResult, CodeExecutionOptions, CodeExecutionResult, InjectMessageInput, QueueMessageInput, SubagentRegistryEntry, ProviderUsagePricing, AgentDefinition, SkillMetadata, SkillFileInput, ControllerContext, Controller, ThreadEndpointHandler } from '@standardagents/spec';
4
+ import { ThreadState, ToolResult as ToolResult$1, VariableDefinition, HookName, HookSignatures, HookMessage, HookToolCall, HookToolResult, CodeExecutionOptions, CodeExecutionResult, InjectMessageInput, QueueMessageInput, SubagentRegistryEntry, ProviderUsagePricing, ThreadUser, AgentDefinition, SkillMetadata, SkillFileInput, ControllerContext, Controller, ThreadEndpointHandler } from '@standardagents/spec';
5
5
 
6
6
  /**
7
7
  * Callback function to execute before stream closes
@@ -1120,6 +1120,7 @@ interface FileStats {
1120
1120
  * - User session token (validated against DurableAgentBuilder)
1121
1121
  * - API key (validated against DurableAgentBuilder)
1122
1122
  */
1123
+
1123
1124
  interface AuthUser {
1124
1125
  id: string;
1125
1126
  username: string;
@@ -1139,6 +1140,13 @@ interface AuthContext {
1139
1140
  user: AuthUser;
1140
1141
  authType: 'super_admin' | 'session' | 'api_key';
1141
1142
  }
1143
+ /**
1144
+ * Project an authenticated request onto the spec's endpoint caller identity
1145
+ * (`ThreadEndpointAuth.caller` / `ControllerContext.caller`). Returns exactly
1146
+ * the spec `ThreadUser` fields — internal extras like `platform_user_id`
1147
+ * never reach endpoint code.
1148
+ */
1149
+ declare function endpointCallerFromAuth(auth: AuthContext | null | undefined): ThreadUser | null;
1142
1150
  /**
1143
1151
  * Authenticate a request using various token types
1144
1152
  */
@@ -1851,4 +1859,4 @@ declare function defineController<Env extends ThreadEnv = ThreadEnv>(controller:
1851
1859
  */
1852
1860
  declare function createThreadEndpointHandler<Env extends ThreadEnv = ThreadEnv>(handler: ThreadEndpointHandler): BuilderController<Env>;
1853
1861
 
1854
- export { type AuthUser as A, type BuilderController as B, CLIENT_STREAM_CHUNK_BYTES as C, type TelemetryEvent as D, type Env as E, type FlowState as F, type FileRecord as G, type AttachmentRef as H, type ImageMetadata as I, type GrepResult as J, type FileStats as K, type LLMResponse as L, type Message as M, type TextContentPart as N, type ImageContentPart as O, type MultimodalContent as P, type MessageContent as Q, type RequestContext as R, type StorageBackend as S, type ToolCall as T, type BuilderControllerContext as a, type ThreadEndpointContext as b, createThreadEndpointHandler as c, defineController as d, type ThreadEnv as e, type BuilderThreadEndpointHandler as f, authenticate as g, requireAdmin as h, type AuthContext as i, callClient as j, callClientStream as k, encodeStreamChunk as l, decodeStreamChunk as m, type ClientToolRequest as n, type ClientToolResponse as o, type ClientStreamRequest as p, type ClientStreamResponse as q, requireAuth as r, supportsClientForwarding as s, type ClientDuplex as t, type ClientForwarding as u, type Agent as v, type ThreadInstance as w, type ThreadMetadata as x, type ToolResult as y, type FlowResult as z };
1862
+ export { type AuthUser as A, type BuilderController as B, CLIENT_STREAM_CHUNK_BYTES as C, type FlowResult as D, type TelemetryEvent as E, type FlowState as F, type Env as G, type FileRecord as H, type ImageMetadata as I, type AttachmentRef as J, type GrepResult as K, type LLMResponse as L, type Message as M, type FileStats as N, type TextContentPart as O, type ImageContentPart as P, type MultimodalContent as Q, type RequestContext as R, type StorageBackend as S, type ToolCall as T, type MessageContent as U, type BuilderControllerContext as a, type ThreadEndpointContext as b, createThreadEndpointHandler as c, defineController as d, type ThreadEnv as e, type BuilderThreadEndpointHandler as f, authenticate as g, requireAdmin as h, endpointCallerFromAuth as i, type AuthContext as j, callClient as k, callClientStream as l, encodeStreamChunk as m, decodeStreamChunk as n, type ClientToolRequest as o, type ClientToolResponse as p, type ClientStreamRequest as q, requireAuth as r, supportsClientForwarding as s, type ClientStreamResponse as t, type ClientDuplex as u, type ClientForwarding as v, type Agent as w, type ThreadInstance as x, type ThreadMetadata as y, type ToolResult as z };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ModelDefinition, AgentDefinition } from './runtime.js';
2
2
  export { AgentBuilderEnv, AgentBuilderEvent, BroadcastOptions, CodeExecutionBridge, DurableAgentBuilder, DurableThread, DurableUserHub, FlowStateSdk, FlowStateWithSdk, HubClientInfo, ImageContextConfig, InjectMessageOptions, LLMProviderInterface, NamespaceResolutionError, PromptContent, PromptDefinition, PromptIncludePart, PromptPart, PromptToolConfig, Provider, ProviderContentPart, ProviderFilePart, ProviderImagePart, ProviderRegistry, ProviderTextPart, SessionToolBinding, SessionToolConfig, SideConfig, SubagentToolConfig, SubpromptConfig, ThreadEventPayload, ThreadRegistryEntry, ThreadWatchdog, ThreadWatchdogState, ToolConfig, UpdateThreadParams, User, WatchdogCheckin, WatchdogProbeResult, buildImageDescription, canAccessThread, cat, createNamespaceContext, emitThreadEvent, enhanceFlowState, exists, find, forceTurn, generateImageDescription, getFileStats, getMessages, getMessagesToSummarize, getShortName, getThumbnail, getUnsummarizedImageAttachments, getVisibleAgentNames, getVisibleModelNames, getVisiblePromptNames, getVisibleToolNames, grep, hasImageAttachments, head, injectMessage, isAdminOnlyApiRoute, isHostedInstance, isPublicApiRoute, isQualifiedName, isTrustedLocalDevelopmentRequest, linkFile, mkdir, move, optimizeImageContext, parseQualifiedName, qualifyName, queueTool, readFile, readdir, reloadHistory, rename, replaceImagesWithDescriptions, resolveAgent, resolveHook, resolveModel, resolvePrompt, resolveTool, rmdir, stat, tail, unlink, updateThread, writeFile, writeImage } from './runtime.js';
3
3
  export { AgentPluginOptions, agentbuilder, builder } from './plugin.js';
4
- export { v as Agent, H as AttachmentRef, i as AuthContext, A as AuthUser, f as BuilderThreadEndpointHandler, C as CLIENT_STREAM_CHUNK_BYTES, t as ClientDuplex, u as ClientForwarding, p as ClientStreamRequest, q as ClientStreamResponse, n as ClientToolRequest, o as ClientToolResponse, B as Controller, a as ControllerContext, E as Env, G as FileRecord, K as FileStats, z as FlowResult, F as FlowState, J as GrepResult, O as ImageContentPart, I as ImageMetadata, L as LLMResponse, M as Message, Q as MessageContent, P as MultimodalContent, R as RequestContext, S as StorageBackend, D as TelemetryEvent, N as TextContentPart, b as ThreadEndpointContext, e as ThreadEnv, w as ThreadInstance, x as ThreadMetadata, T as ToolCall, y as ToolResult, g as authenticate, j as callClient, k as callClientStream, c as createThreadEndpointHandler, m as decodeStreamChunk, d as defineController, l as encodeStreamChunk, h as requireAdmin, r as requireAuth, s as supportsClientForwarding } from './index-Lfan8QMN.js';
4
+ export { w as Agent, J as AttachmentRef, j as AuthContext, A as AuthUser, f as BuilderThreadEndpointHandler, C as CLIENT_STREAM_CHUNK_BYTES, u as ClientDuplex, v as ClientForwarding, q as ClientStreamRequest, t as ClientStreamResponse, o as ClientToolRequest, p as ClientToolResponse, B as Controller, a as ControllerContext, G as Env, H as FileRecord, N as FileStats, D as FlowResult, F as FlowState, K as GrepResult, P as ImageContentPart, I as ImageMetadata, L as LLMResponse, M as Message, U as MessageContent, Q as MultimodalContent, R as RequestContext, S as StorageBackend, E as TelemetryEvent, O as TextContentPart, b as ThreadEndpointContext, e as ThreadEnv, x as ThreadInstance, y as ThreadMetadata, T as ToolCall, z as ToolResult, g as authenticate, k as callClient, l as callClientStream, c as createThreadEndpointHandler, n as decodeStreamChunk, d as defineController, m as encodeStreamChunk, i as endpointCallerFromAuth, h as requireAdmin, r as requireAuth, s as supportsClientForwarding } from './index-BBu-Osn5.js';
5
5
  export { AgentType, DefinitionLoader, GlobalNamespaceContext, HookSignatures, ImageContent, ModelCapabilities, ModelProvider, NamespaceContext, PackageSignature, PackedExports, PackedMeta, PackedMetadata, PackedNamespaceContext, PromptInput, PromptTextPart, ProviderAssistantMessage, ProviderConfigSlot, ProviderConfigSlots, ProviderConfigValueSource, ProviderDefinition, ProviderError, ProviderErrorCode, ProviderFactory, ProviderFactoryConfig, ProviderFinishReason, ProviderGeneratedImage, ProviderMessage, ProviderMessageContent, ProviderMethodOverrides, ModelCapabilities as ProviderModelCapabilities, ProviderOverride, ProviderOverrideContext, ProviderReasoningDetail, ProviderRequest, ProviderResponse, ProviderStreamChunk, ProviderSyncOverride, ProviderSystemMessage, ProviderTool, ProviderToolCallPart, ProviderToolMessage, ProviderToolResultContent, ProviderUsage, ProviderUserMessage, ReasoningConfig, StructuredPrompt, TextContent, Tool, ToolArgs, ToolArgsNode, ToolArgsRawShape, ToolContent, belongsToPackage, defineAgent, defineHook, defineModel, definePrompt, defineProvider, defineTool, isPacked, isVisibleInNamespace, mapReasoningLevel, providerConst, providerEnv, providerValue } from '@standardagents/spec';
6
6
  export { C as ConstituentItem, D as DiscoveredPackage, N as NamespacedRegistry, P as PackingAnalysis, a as PackingOptions, b as PackingResult, c as UnpackOptions, d as UnpackResult } from './types-Bpe7IANZ.js';
7
7
  export { D as DiscoveryConfig, P as PackageDiscoveryService, d as discoverPackages } from './discovery-DiMJWisl.js';
package/dist/index.js CHANGED
@@ -9560,7 +9560,12 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9560
9560
  const threadState = ThreadStateImpl.fromFlowState(state);
9561
9561
  for (const executor of executors) {
9562
9562
  try {
9563
- result = await executor(threadState, result);
9563
+ const hooked = await executor(threadState, _FlowEngine.rowToHookMessage(result));
9564
+ result = {
9565
+ ...result,
9566
+ ...hooked,
9567
+ attachments: hooked.attachments === void 0 ? result.attachments : hooked.attachments === null ? null : typeof hooked.attachments === "string" ? hooked.attachments : JSON.stringify(hooked.attachments)
9568
+ };
9564
9569
  } catch (error) {
9565
9570
  console.error("[Hooks] \u2717 Error running before_create_message hook:", error);
9566
9571
  }
@@ -9580,12 +9585,31 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9580
9585
  const threadState = ThreadStateImpl.fromFlowState(state);
9581
9586
  for (const executor of executors) {
9582
9587
  try {
9583
- await executor(threadState, message);
9588
+ await executor(threadState, _FlowEngine.rowToHookMessage(message));
9584
9589
  } catch (error) {
9585
9590
  console.error("[Hooks] \u2717 Error running after_create_message hook:", error);
9586
9591
  }
9587
9592
  }
9588
9593
  }
9594
+ /**
9595
+ * Builder rows store `attachments` as a JSON string; the spec hook surface
9596
+ * carries parsed AttachmentRef[]. Convert at every hook boundary so hooks
9597
+ * see the spec shape and cannot corrupt the stored row shape.
9598
+ */
9599
+ static rowToHookMessage(row) {
9600
+ const { attachments, ...rest } = row;
9601
+ let parsed = void 0;
9602
+ if (attachments === null) parsed = null;
9603
+ else if (typeof attachments === "string" && attachments) {
9604
+ try {
9605
+ const p = JSON.parse(attachments);
9606
+ parsed = Array.isArray(p) ? p : void 0;
9607
+ } catch {
9608
+ parsed = void 0;
9609
+ }
9610
+ }
9611
+ return { ...rest, attachments: parsed };
9612
+ }
9589
9613
  /**
9590
9614
  * Run the before_update_message hook if it exists
9591
9615
  * This hook allows developers to modify a message before it's updated
@@ -9624,7 +9648,7 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9624
9648
  const threadState = ThreadStateImpl.fromFlowState(state);
9625
9649
  for (const executor of executors) {
9626
9650
  try {
9627
- await executor(threadState, message);
9651
+ await executor(threadState, _FlowEngine.rowToHookMessage(message));
9628
9652
  } catch (error) {
9629
9653
  console.error("[Hooks] \u2717 Error running after_update_message hook:", error);
9630
9654
  }
@@ -10713,7 +10737,11 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
10713
10737
  const threadState = ThreadStateImpl.fromFlowState(state);
10714
10738
  for (const executor of executors) {
10715
10739
  try {
10716
- result = await executor(threadState, result);
10740
+ const byId = /* @__PURE__ */ new Map();
10741
+ for (const row of result) if (row.id) byId.set(row.id, row);
10742
+ const hookView = result.map((row) => _FlowEngine.rowToHookMessage(row));
10743
+ const kept = await executor(threadState, hookView);
10744
+ result = kept.map((m) => m.id && byId.get(m.id) || null).filter((row) => row !== null);
10717
10745
  } catch (error) {
10718
10746
  console.error("[Hooks] \u2717 Error running filter_messages hook:", error);
10719
10747
  }
@@ -14300,9 +14328,25 @@ var init_ThreadStateImpl = __esm({
14300
14328
  parent_id: msg.parent_id,
14301
14329
  depth: msg.depth,
14302
14330
  silent: msg.silent,
14303
- metadata: msg.metadata
14331
+ metadata: msg.metadata,
14332
+ status: msg.status,
14333
+ tool_status: msg.tool_status,
14334
+ attachments: this._parseAttachmentRefs(msg.attachments)
14304
14335
  };
14305
14336
  };
14337
+ /** Builder rows store attachments as a JSON string of AttachmentRef[];
14338
+ * spec messages carry the parsed refs. Dropping them here is what made
14339
+ * generated assets invisible to every session_state consumer. */
14340
+ _parseAttachmentRefs = (raw) => {
14341
+ if (!raw) return void 0;
14342
+ if (Array.isArray(raw)) return raw;
14343
+ try {
14344
+ const parsed = JSON.parse(raw);
14345
+ return Array.isArray(parsed) ? parsed : void 0;
14346
+ } catch {
14347
+ return void 0;
14348
+ }
14349
+ };
14306
14350
  _mapFileRecord = (record) => {
14307
14351
  return {
14308
14352
  path: record.path,
@@ -21370,10 +21414,6 @@ var PUBLIC_ROUTES = /* @__PURE__ */ new Set([
21370
21414
  function isProviderIconRoute(routePath) {
21371
21415
  return /^\/api\/providers\/[^/]+\/icon$/.test(routePath);
21372
21416
  }
21373
- function isPublicThreadFileRoute(routePath, method) {
21374
- if (method !== "GET" && method !== "HEAD") return false;
21375
- return /^\/api\/threads\/[^/]+\/public\/.+/.test(routePath);
21376
- }
21377
21417
  function isHostedInstance(env) {
21378
21418
  const value = env?.STANDARD_AGENTS_HOSTED;
21379
21419
  if (typeof value === "string") {
@@ -21400,9 +21440,6 @@ function isPublicApiRoute(routePath, request, env) {
21400
21440
  if (isProviderIconRoute(routePath)) {
21401
21441
  return true;
21402
21442
  }
21403
- if (isPublicThreadFileRoute(routePath, request.method.toUpperCase())) {
21404
- return true;
21405
- }
21406
21443
  if (!isTrustedLocalDevelopmentRequest(request, env)) return false;
21407
21444
  return routePath === "/api/threads" || routePath.startsWith("/api/threads/") || routePath === "/api/platform" || routePath.startsWith("/api/platform/") || routePath === "/api/platform-session" || routePath.startsWith("/api/platform-session/") || routePath === "/api/platform-auth" || routePath.startsWith("/api/platform-auth/");
21408
21445
  }
@@ -22156,14 +22193,16 @@ import { prompts, promptNames } from "virtual:@standardagents-prompts";
22156
22193
  import { agents, agentNames } from "virtual:@standardagents-agents";
22157
22194
  import { registry } from "virtual:@standardagents-registry";
22158
22195
  import {
22196
+ authenticate,
22159
22197
  requireAuth,
22160
22198
  createThreadEndpointHandler,
22161
22199
  canAccessThread,
22200
+ endpointCallerFromAuth,
22162
22201
  isHostedInstance,
22163
22202
  isPublicApiRoute,
22164
22203
  isAdminOnlyApiRoute,
22165
22204
  } from "@standardagents/builder/runtime";
22166
- import { isThreadEndpoint } from "@standardagents/spec";
22205
+ import { isThreadEndpoint, getEndpointAccess } from "@standardagents/spec";
22167
22206
 
22168
22207
  function platformEndpoint(env) {
22169
22208
  const configured =
@@ -22306,8 +22345,16 @@ ${packedThreadRouteCode}
22306
22345
  );
22307
22346
 
22308
22347
  if (routeMatch) {
22348
+ let controller = await routeMatch.data();
22349
+
22350
+ // Endpoint-declared access (spec: EndpointAccess). A 'public' declaration
22351
+ // opts that one endpoint out of the router's authentication gate; the
22352
+ // handler still receives the resolved caller identity when the request
22353
+ // presents verifiable credentials.
22354
+ const declaredPublic = getEndpointAccess(controller) === 'public';
22355
+
22309
22356
  // Check if authentication is required for this route
22310
- const publicRoute = isPublicApiRoute(routePath, request, env);
22357
+ const publicRoute = declaredPublic || isPublicApiRoute(routePath, request, env);
22311
22358
  const isApiRoute = routePath.startsWith('/api/');
22312
22359
 
22313
22360
  let authContext = null;
@@ -22350,10 +22397,24 @@ ${packedThreadRouteCode}
22350
22397
  threadAccess = { threadId, thread };
22351
22398
  }
22352
22399
  }
22400
+ } else if (isApiRoute && declaredPublic) {
22401
+ // Optional caller resolution for endpoint-declared public routes:
22402
+ // verifiable credentials attribute the request, anything else stays
22403
+ // anonymous instead of being rejected (spec ThreadEndpointAuth).
22404
+ authContext = await authenticate(request, env);
22405
+ if (authContext && routePath.startsWith('/api/threads/')) {
22406
+ const threadId = routeMatch.params?.threadId || routeMatch.params?.id;
22407
+ if (threadId) {
22408
+ const agentBuilderId = env.AGENT_BUILDER.idFromName('singleton');
22409
+ const agentBuilder = env.AGENT_BUILDER.get(agentBuilderId);
22410
+ const thread = await agentBuilder.getThread(threadId);
22411
+ if (thread && canAccessThread(authContext, thread)) {
22412
+ threadAccess = { threadId, thread };
22413
+ }
22414
+ }
22415
+ }
22353
22416
  }
22354
22417
 
22355
- let controller = await routeMatch.data();
22356
-
22357
22418
  // Check if this is a thread endpoint (marked by defineThreadEndpoint)
22358
22419
  // If so, wrap it with createThreadEndpointHandler to provide ThreadState
22359
22420
  if (isThreadEndpoint(controller)) {
@@ -22368,6 +22429,7 @@ ${packedThreadRouteCode}
22368
22429
  config,
22369
22430
  tools,
22370
22431
  auth: authContext, // Add auth context to controller context
22432
+ caller: endpointCallerFromAuth(authContext), // Spec ControllerContext.caller
22371
22433
  threadAccess, // Router's thread authorization, bound to the exact id
22372
22434
  };
22373
22435
  const result = await controller(context);
@@ -23148,54 +23210,6 @@ var builder = agentbuilder;
23148
23210
 
23149
23211
  // src/router/index.ts
23150
23212
  init_ThreadStateImpl();
23151
- function defineController2(controller) {
23152
- return controller;
23153
- }
23154
- function createThreadEndpointHandler(handler) {
23155
- return (async ({ req, params, env }) => {
23156
- const threadId = params.threadId ?? params.id;
23157
- if (!threadId) {
23158
- return Response.json({ error: "Thread ID required" }, { status: 400 });
23159
- }
23160
- try {
23161
- const agentBuilderId = env.AGENT_BUILDER.idFromName("singleton");
23162
- const agentBuilder = env.AGENT_BUILDER.get(agentBuilderId);
23163
- const metadata = await agentBuilder.getThread(threadId);
23164
- if (!metadata) {
23165
- return Response.json(
23166
- { error: `Thread not found: ${threadId}` },
23167
- { status: 404 }
23168
- );
23169
- }
23170
- const meta = metadata;
23171
- if (!meta.agent_id && meta.agent_name) {
23172
- meta.agent_id = meta.agent_name;
23173
- }
23174
- const durableId = env.AGENT_BUILDER_THREAD.idFromName(threadId);
23175
- const stub = env.AGENT_BUILDER_THREAD.get(durableId);
23176
- const instance = stub;
23177
- const threadState = ThreadStateImpl.fromThreadInstance(instance, metadata, {
23178
- env
23179
- });
23180
- const endpointParams = {};
23181
- for (const [key, value] of Object.entries(params)) {
23182
- if (key === "threadId" || key === "id" && !params.threadId) {
23183
- continue;
23184
- }
23185
- endpointParams[key === "_" ? "*" : key] = value;
23186
- }
23187
- const response = await handler(req, threadState, endpointParams);
23188
- await threadState.flushPendingEventDeliveries();
23189
- return response;
23190
- } catch (error) {
23191
- console.error(`Error in thread endpoint for ${threadId}:`, error);
23192
- return Response.json(
23193
- { error: error.message || "Internal server error" },
23194
- { status: 500 }
23195
- );
23196
- }
23197
- });
23198
- }
23199
23213
 
23200
23214
  // src/utils/auth.ts
23201
23215
  async function hashToken(token) {
@@ -23286,6 +23300,19 @@ var CORS_HEADERS = {
23286
23300
  "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With",
23287
23301
  "Access-Control-Max-Age": "86400"
23288
23302
  };
23303
+ function endpointCallerFromAuth(auth) {
23304
+ if (!auth) return null;
23305
+ const { id, username, role, permissions, email, display_name, avatar_url } = auth.user;
23306
+ return {
23307
+ id,
23308
+ username,
23309
+ role,
23310
+ permissions: permissions ?? null,
23311
+ email: email ?? null,
23312
+ display_name: display_name ?? null,
23313
+ avatar_url: avatar_url ?? null
23314
+ };
23315
+ }
23289
23316
  function parsePermissions(value) {
23290
23317
  if (Array.isArray(value)) return value.filter((p) => typeof p === "string");
23291
23318
  if (typeof value === "string" && value.trim()) {
@@ -23420,6 +23447,61 @@ async function requireAdmin(request, env) {
23420
23447
  }
23421
23448
  return result;
23422
23449
  }
23450
+ function defineController2(controller) {
23451
+ return controller;
23452
+ }
23453
+ function createThreadEndpointHandler(handler) {
23454
+ return (async (context) => {
23455
+ const { req, params, env } = context;
23456
+ const threadId = params.threadId ?? params.id;
23457
+ if (!threadId) {
23458
+ return Response.json({ error: "Thread ID required" }, { status: 400 });
23459
+ }
23460
+ const endpointAuth = {
23461
+ caller: endpointCallerFromAuth(context.auth),
23462
+ threadAccess: Boolean(
23463
+ context.threadAccess && context.threadAccess.threadId === threadId
23464
+ )
23465
+ };
23466
+ try {
23467
+ const agentBuilderId = env.AGENT_BUILDER.idFromName("singleton");
23468
+ const agentBuilder = env.AGENT_BUILDER.get(agentBuilderId);
23469
+ const metadata = await agentBuilder.getThread(threadId);
23470
+ if (!metadata) {
23471
+ return Response.json(
23472
+ { error: `Thread not found: ${threadId}` },
23473
+ { status: 404 }
23474
+ );
23475
+ }
23476
+ const meta = metadata;
23477
+ if (!meta.agent_id && meta.agent_name) {
23478
+ meta.agent_id = meta.agent_name;
23479
+ }
23480
+ const durableId = env.AGENT_BUILDER_THREAD.idFromName(threadId);
23481
+ const stub = env.AGENT_BUILDER_THREAD.get(durableId);
23482
+ const instance = stub;
23483
+ const threadState = ThreadStateImpl.fromThreadInstance(instance, metadata, {
23484
+ env
23485
+ });
23486
+ const endpointParams = {};
23487
+ for (const [key, value] of Object.entries(params)) {
23488
+ if (key === "threadId" || key === "id" && !params.threadId) {
23489
+ continue;
23490
+ }
23491
+ endpointParams[key === "_" ? "*" : key] = value;
23492
+ }
23493
+ const response = await handler(req, threadState, endpointParams, endpointAuth);
23494
+ await threadState.flushPendingEventDeliveries();
23495
+ return response;
23496
+ } catch (error) {
23497
+ console.error(`Error in thread endpoint for ${threadId}:`, error);
23498
+ return Response.json(
23499
+ { error: error.message || "Internal server error" },
23500
+ { status: 500 }
23501
+ );
23502
+ }
23503
+ });
23504
+ }
23423
23505
 
23424
23506
  // src/utils/permissions.ts
23425
23507
  function canAccessThread(auth, thread) {
@@ -37405,6 +37487,6 @@ init_context();
37405
37487
  init_ProviderRegistry();
37406
37488
  init_types2();
37407
37489
 
37408
- export { CLIENT_STREAM_CHUNK_BYTES, CodeExecutionBridge, DurableAgentBuilder, DurableThread, DurableUserHub, FlowStateSdk, NamespaceResolutionError, PackageDiscoveryService, ProviderRegistry, ThreadWatchdog, agentbuilder, assistantMessageText, authenticate, buildImageDescription, builder, callClient, callClientStream, canAccessThread, cat, createNamespaceContext, createThreadEndpointHandler, decodeStreamChunk, defineController2 as defineController, discoverPackages, emitThreadEvent, encodeStreamChunk, enhanceFlowState, exists, find, forceTurn, generateAgentFile, generateImageDescription, generateModelFile, generatePromptFile, getFileStats, getMessages, getMessagesToSummarize, getShortName, getThumbnail, getUnsummarizedImageAttachments, getVisibleAgentNames, getVisibleModelNames, getVisiblePromptNames, getVisibleToolNames, grep, hasImageAttachments, hasJsonArrayEntries, head, injectMessage, isAdminOnlyApiRoute, isHostedInstance, isPublicApiRoute, isQualifiedName, isTrustedLocalDevelopmentRequest, isVisibleTerminalAssistantMessage, linkFile, messageTimestampSeconds, mkdir, move, optimizeImageContext, parseQualifiedName, qualifyName, queueTool, readFile, readdir, reloadHistory, rename, replaceImagesWithDescriptions, requireAdmin, requireAuth, resolveAgent, resolveHook, resolveModel, resolvePrompt, resolveTool, rmdir, stat, supportsClientForwarding, tail, unlink, updateThread, writeFile, writeImage };
37490
+ export { CLIENT_STREAM_CHUNK_BYTES, CodeExecutionBridge, DurableAgentBuilder, DurableThread, DurableUserHub, FlowStateSdk, NamespaceResolutionError, PackageDiscoveryService, ProviderRegistry, ThreadWatchdog, agentbuilder, assistantMessageText, authenticate, buildImageDescription, builder, callClient, callClientStream, canAccessThread, cat, createNamespaceContext, createThreadEndpointHandler, decodeStreamChunk, defineController2 as defineController, discoverPackages, emitThreadEvent, encodeStreamChunk, endpointCallerFromAuth, enhanceFlowState, exists, find, forceTurn, generateAgentFile, generateImageDescription, generateModelFile, generatePromptFile, getFileStats, getMessages, getMessagesToSummarize, getShortName, getThumbnail, getUnsummarizedImageAttachments, getVisibleAgentNames, getVisibleModelNames, getVisiblePromptNames, getVisibleToolNames, grep, hasImageAttachments, hasJsonArrayEntries, head, injectMessage, isAdminOnlyApiRoute, isHostedInstance, isPublicApiRoute, isQualifiedName, isTrustedLocalDevelopmentRequest, isVisibleTerminalAssistantMessage, linkFile, messageTimestampSeconds, mkdir, move, optimizeImageContext, parseQualifiedName, qualifyName, queueTool, readFile, readdir, reloadHistory, rename, replaceImagesWithDescriptions, requireAdmin, requireAuth, resolveAgent, resolveHook, resolveModel, resolvePrompt, resolveTool, rmdir, stat, supportsClientForwarding, tail, unlink, updateThread, writeFile, writeImage };
37409
37491
  //# sourceMappingURL=index.js.map
37410
37492
  //# sourceMappingURL=index.js.map