@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.
package/dist/runtime.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { i as AuthContext, e as ThreadEnv, v as Agent, x as ThreadMetadata, y as ToolResult, M as Message, n as ClientToolRequest, o as ClientToolResponse, p as ClientStreamRequest, q as ClientStreamResponse, G as FileRecord, F as FlowState, K as FileStats, J as GrepResult, H as AttachmentRef, Q as MessageContent, E as Env, w as ThreadInstance } from './index-Lfan8QMN.js';
2
- export { A as AuthUser, f as BuilderThreadEndpointHandler, C as CLIENT_STREAM_CHUNK_BYTES, t as ClientDuplex, u as ClientForwarding, B as Controller, a as ControllerContext, z as FlowResult, O as ImageContentPart, I as ImageMetadata, L as LLMResponse, P as MultimodalContent, R as RequestContext, S as StorageBackend, D as TelemetryEvent, N as TextContentPart, b as ThreadEndpointContext, T as ToolCall, 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';
1
+ import { j as AuthContext, e as ThreadEnv, w as Agent, y as ThreadMetadata, z as ToolResult, M as Message, o as ClientToolRequest, p as ClientToolResponse, q as ClientStreamRequest, t as ClientStreamResponse, H as FileRecord, F as FlowState, N as FileStats, K as GrepResult, J as AttachmentRef, U as MessageContent, G as Env, x as ThreadInstance } from './index-BBu-Osn5.js';
2
+ export { A as AuthUser, f as BuilderThreadEndpointHandler, C as CLIENT_STREAM_CHUNK_BYTES, u as ClientDuplex, v as ClientForwarding, B as Controller, a as ControllerContext, D as FlowResult, P as ImageContentPart, I as ImageMetadata, L as LLMResponse, Q as MultimodalContent, R as RequestContext, S as StorageBackend, E as TelemetryEvent, O as TextContentPart, b as ThreadEndpointContext, T as ToolCall, 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';
3
3
  import { CodeExecutionOptions, CodeExecutionResult, SubagentRegistryEntry, InjectMessageInput, QueueMessageInput, CredentialGrant, SkillMetadata, SkillFileInput, ModelDefinition as ModelDefinition$1, ToolArgs, PromptTextPart, PromptEnvPart, VariableDefinition, SubpromptConfig as SubpromptConfig$1, PromptToolConfig as PromptToolConfig$1, SubagentToolConfig as SubagentToolConfig$1, ReasoningConfig, SideConfig as SideConfig$1, LLMProviderInterface, ContentPart, TextPart, ImagePart, FilePart, ThreadState, NamespaceContext, DefinitionLoader } from '@standardagents/spec';
4
4
  export { AgentType, DefinitionLoader, GlobalNamespaceContext, HookSignatures, ImageContent, ModelCapabilities, ModelProvider, NamespaceContext, PackageSignature, PackedExports, PackedMeta, PackedMetadata, PackedNamespaceContext, PromptInput, PromptTextPart, ProviderAssistantMessage, ProviderError, ProviderErrorCode, ProviderFactory, ProviderFactoryConfig, ProviderFinishReason, ProviderGeneratedImage, ProviderMessage, ProviderMessageContent, ModelCapabilities as ProviderModelCapabilities, ProviderReasoningDetail, ProviderRequest, ProviderResponse, ProviderStreamChunk, ProviderSystemMessage, ProviderTool, ProviderToolCallPart, ProviderToolMessage, ProviderToolResultContent, ProviderUsage, ProviderUserMessage, ReasoningConfig, StructuredPrompt, TextContent, Tool, ToolArgs, ToolArgsNode, ToolArgsRawShape, ToolContent, belongsToPackage, defineAgent, defineHook, defineModel, definePrompt, defineTool, isPacked, isVisibleInNamespace, mapReasoningLevel } from '@standardagents/spec';
5
5
  import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
@@ -116,6 +116,7 @@ declare function canAccessThread(auth: AuthContext, thread: {
116
116
  user_id: string | null;
117
117
  }): boolean;
118
118
 
119
+ /** Central API exposure policy shared by the generated Worker router and tests. */
119
120
  declare function isHostedInstance(env: Record<string, unknown> | undefined): boolean;
120
121
  /**
121
122
  * Local-only conveniences are enabled by the request destination, not merely
package/dist/runtime.js CHANGED
@@ -9551,7 +9551,12 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9551
9551
  const threadState = ThreadStateImpl.fromFlowState(state);
9552
9552
  for (const executor of executors) {
9553
9553
  try {
9554
- result = await executor(threadState, result);
9554
+ const hooked = await executor(threadState, _FlowEngine.rowToHookMessage(result));
9555
+ result = {
9556
+ ...result,
9557
+ ...hooked,
9558
+ attachments: hooked.attachments === void 0 ? result.attachments : hooked.attachments === null ? null : typeof hooked.attachments === "string" ? hooked.attachments : JSON.stringify(hooked.attachments)
9559
+ };
9555
9560
  } catch (error) {
9556
9561
  console.error("[Hooks] \u2717 Error running before_create_message hook:", error);
9557
9562
  }
@@ -9571,12 +9576,31 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9571
9576
  const threadState = ThreadStateImpl.fromFlowState(state);
9572
9577
  for (const executor of executors) {
9573
9578
  try {
9574
- await executor(threadState, message);
9579
+ await executor(threadState, _FlowEngine.rowToHookMessage(message));
9575
9580
  } catch (error) {
9576
9581
  console.error("[Hooks] \u2717 Error running after_create_message hook:", error);
9577
9582
  }
9578
9583
  }
9579
9584
  }
9585
+ /**
9586
+ * Builder rows store `attachments` as a JSON string; the spec hook surface
9587
+ * carries parsed AttachmentRef[]. Convert at every hook boundary so hooks
9588
+ * see the spec shape and cannot corrupt the stored row shape.
9589
+ */
9590
+ static rowToHookMessage(row) {
9591
+ const { attachments, ...rest } = row;
9592
+ let parsed = void 0;
9593
+ if (attachments === null) parsed = null;
9594
+ else if (typeof attachments === "string" && attachments) {
9595
+ try {
9596
+ const p = JSON.parse(attachments);
9597
+ parsed = Array.isArray(p) ? p : void 0;
9598
+ } catch {
9599
+ parsed = void 0;
9600
+ }
9601
+ }
9602
+ return { ...rest, attachments: parsed };
9603
+ }
9580
9604
  /**
9581
9605
  * Run the before_update_message hook if it exists
9582
9606
  * This hook allows developers to modify a message before it's updated
@@ -9615,7 +9639,7 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
9615
9639
  const threadState = ThreadStateImpl.fromFlowState(state);
9616
9640
  for (const executor of executors) {
9617
9641
  try {
9618
- await executor(threadState, message);
9642
+ await executor(threadState, _FlowEngine.rowToHookMessage(message));
9619
9643
  } catch (error) {
9620
9644
  console.error("[Hooks] \u2717 Error running after_update_message hook:", error);
9621
9645
  }
@@ -10704,7 +10728,11 @@ ${msg.content}` : `${imageDescriptions}${nonImageList}`;
10704
10728
  const threadState = ThreadStateImpl.fromFlowState(state);
10705
10729
  for (const executor of executors) {
10706
10730
  try {
10707
- result = await executor(threadState, result);
10731
+ const byId = /* @__PURE__ */ new Map();
10732
+ for (const row of result) if (row.id) byId.set(row.id, row);
10733
+ const hookView = result.map((row) => _FlowEngine.rowToHookMessage(row));
10734
+ const kept = await executor(threadState, hookView);
10735
+ result = kept.map((m) => m.id && byId.get(m.id) || null).filter((row) => row !== null);
10708
10736
  } catch (error) {
10709
10737
  console.error("[Hooks] \u2717 Error running filter_messages hook:", error);
10710
10738
  }
@@ -14291,9 +14319,25 @@ var init_ThreadStateImpl = __esm({
14291
14319
  parent_id: msg.parent_id,
14292
14320
  depth: msg.depth,
14293
14321
  silent: msg.silent,
14294
- metadata: msg.metadata
14322
+ metadata: msg.metadata,
14323
+ status: msg.status,
14324
+ tool_status: msg.tool_status,
14325
+ attachments: this._parseAttachmentRefs(msg.attachments)
14295
14326
  };
14296
14327
  };
14328
+ /** Builder rows store attachments as a JSON string of AttachmentRef[];
14329
+ * spec messages carry the parsed refs. Dropping them here is what made
14330
+ * generated assets invisible to every session_state consumer. */
14331
+ _parseAttachmentRefs = (raw) => {
14332
+ if (!raw) return void 0;
14333
+ if (Array.isArray(raw)) return raw;
14334
+ try {
14335
+ const parsed = JSON.parse(raw);
14336
+ return Array.isArray(parsed) ? parsed : void 0;
14337
+ } catch {
14338
+ return void 0;
14339
+ }
14340
+ };
14297
14341
  _mapFileRecord = (record) => {
14298
14342
  return {
14299
14343
  path: record.path,
@@ -14659,54 +14703,6 @@ var init_image_processing = __esm({
14659
14703
 
14660
14704
  // src/router/index.ts
14661
14705
  init_ThreadStateImpl();
14662
- function defineController2(controller) {
14663
- return controller;
14664
- }
14665
- function createThreadEndpointHandler(handler) {
14666
- return (async ({ req, params, env }) => {
14667
- const threadId = params.threadId ?? params.id;
14668
- if (!threadId) {
14669
- return Response.json({ error: "Thread ID required" }, { status: 400 });
14670
- }
14671
- try {
14672
- const agentBuilderId = env.AGENT_BUILDER.idFromName("singleton");
14673
- const agentBuilder = env.AGENT_BUILDER.get(agentBuilderId);
14674
- const metadata = await agentBuilder.getThread(threadId);
14675
- if (!metadata) {
14676
- return Response.json(
14677
- { error: `Thread not found: ${threadId}` },
14678
- { status: 404 }
14679
- );
14680
- }
14681
- const meta = metadata;
14682
- if (!meta.agent_id && meta.agent_name) {
14683
- meta.agent_id = meta.agent_name;
14684
- }
14685
- const durableId = env.AGENT_BUILDER_THREAD.idFromName(threadId);
14686
- const stub = env.AGENT_BUILDER_THREAD.get(durableId);
14687
- const instance = stub;
14688
- const threadState = ThreadStateImpl.fromThreadInstance(instance, metadata, {
14689
- env
14690
- });
14691
- const endpointParams = {};
14692
- for (const [key, value] of Object.entries(params)) {
14693
- if (key === "threadId" || key === "id" && !params.threadId) {
14694
- continue;
14695
- }
14696
- endpointParams[key === "_" ? "*" : key] = value;
14697
- }
14698
- const response = await handler(req, threadState, endpointParams);
14699
- await threadState.flushPendingEventDeliveries();
14700
- return response;
14701
- } catch (error) {
14702
- console.error(`Error in thread endpoint for ${threadId}:`, error);
14703
- return Response.json(
14704
- { error: error.message || "Internal server error" },
14705
- { status: 500 }
14706
- );
14707
- }
14708
- });
14709
- }
14710
14706
 
14711
14707
  // src/utils/auth.ts
14712
14708
  async function hashToken(token) {
@@ -14797,6 +14793,19 @@ var CORS_HEADERS = {
14797
14793
  "Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With",
14798
14794
  "Access-Control-Max-Age": "86400"
14799
14795
  };
14796
+ function endpointCallerFromAuth(auth) {
14797
+ if (!auth) return null;
14798
+ const { id, username, role, permissions, email, display_name, avatar_url } = auth.user;
14799
+ return {
14800
+ id,
14801
+ username,
14802
+ role,
14803
+ permissions: permissions ?? null,
14804
+ email: email ?? null,
14805
+ display_name: display_name ?? null,
14806
+ avatar_url: avatar_url ?? null
14807
+ };
14808
+ }
14800
14809
  function parsePermissions(value) {
14801
14810
  if (Array.isArray(value)) return value.filter((p) => typeof p === "string");
14802
14811
  if (typeof value === "string" && value.trim()) {
@@ -14931,6 +14940,61 @@ async function requireAdmin(request, env) {
14931
14940
  }
14932
14941
  return result;
14933
14942
  }
14943
+ function defineController2(controller) {
14944
+ return controller;
14945
+ }
14946
+ function createThreadEndpointHandler(handler) {
14947
+ return (async (context) => {
14948
+ const { req, params, env } = context;
14949
+ const threadId = params.threadId ?? params.id;
14950
+ if (!threadId) {
14951
+ return Response.json({ error: "Thread ID required" }, { status: 400 });
14952
+ }
14953
+ const endpointAuth = {
14954
+ caller: endpointCallerFromAuth(context.auth),
14955
+ threadAccess: Boolean(
14956
+ context.threadAccess && context.threadAccess.threadId === threadId
14957
+ )
14958
+ };
14959
+ try {
14960
+ const agentBuilderId = env.AGENT_BUILDER.idFromName("singleton");
14961
+ const agentBuilder = env.AGENT_BUILDER.get(agentBuilderId);
14962
+ const metadata = await agentBuilder.getThread(threadId);
14963
+ if (!metadata) {
14964
+ return Response.json(
14965
+ { error: `Thread not found: ${threadId}` },
14966
+ { status: 404 }
14967
+ );
14968
+ }
14969
+ const meta = metadata;
14970
+ if (!meta.agent_id && meta.agent_name) {
14971
+ meta.agent_id = meta.agent_name;
14972
+ }
14973
+ const durableId = env.AGENT_BUILDER_THREAD.idFromName(threadId);
14974
+ const stub = env.AGENT_BUILDER_THREAD.get(durableId);
14975
+ const instance = stub;
14976
+ const threadState = ThreadStateImpl.fromThreadInstance(instance, metadata, {
14977
+ env
14978
+ });
14979
+ const endpointParams = {};
14980
+ for (const [key, value] of Object.entries(params)) {
14981
+ if (key === "threadId" || key === "id" && !params.threadId) {
14982
+ continue;
14983
+ }
14984
+ endpointParams[key === "_" ? "*" : key] = value;
14985
+ }
14986
+ const response = await handler(req, threadState, endpointParams, endpointAuth);
14987
+ await threadState.flushPendingEventDeliveries();
14988
+ return response;
14989
+ } catch (error) {
14990
+ console.error(`Error in thread endpoint for ${threadId}:`, error);
14991
+ return Response.json(
14992
+ { error: error.message || "Internal server error" },
14993
+ { status: 500 }
14994
+ );
14995
+ }
14996
+ });
14997
+ }
14934
14998
 
14935
14999
  // src/utils/permissions.ts
14936
15000
  function canAccessThread(auth, thread) {
@@ -14963,10 +15027,6 @@ var PUBLIC_ROUTES = /* @__PURE__ */ new Set([
14963
15027
  function isProviderIconRoute(routePath) {
14964
15028
  return /^\/api\/providers\/[^/]+\/icon$/.test(routePath);
14965
15029
  }
14966
- function isPublicThreadFileRoute(routePath, method) {
14967
- if (method !== "GET" && method !== "HEAD") return false;
14968
- return /^\/api\/threads\/[^/]+\/public\/.+/.test(routePath);
14969
- }
14970
15030
  function isHostedInstance(env) {
14971
15031
  const value = env?.STANDARD_AGENTS_HOSTED;
14972
15032
  if (typeof value === "string") {
@@ -14993,9 +15053,6 @@ function isPublicApiRoute(routePath, request, env) {
14993
15053
  if (isProviderIconRoute(routePath)) {
14994
15054
  return true;
14995
15055
  }
14996
- if (isPublicThreadFileRoute(routePath, request.method.toUpperCase())) {
14997
- return true;
14998
- }
14999
15056
  if (!isTrustedLocalDevelopmentRequest(request, env)) return false;
15000
15057
  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/");
15001
15058
  }
@@ -28990,6 +29047,6 @@ init_context();
28990
29047
  init_ProviderRegistry();
28991
29048
  init_types2();
28992
29049
 
28993
- export { CLIENT_STREAM_CHUNK_BYTES, CodeExecutionBridge, DurableAgentBuilder, DurableThread, DurableUserHub, FlowStateSdk, NamespaceResolutionError, ProviderRegistry, ThreadWatchdog, authenticate, buildImageDescription, callClient, callClientStream, canAccessThread, cat, createNamespaceContext, createThreadEndpointHandler, decodeStreamChunk, defineController2 as defineController, emitThreadEvent, encodeStreamChunk, 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, requireAdmin, requireAuth, resolveAgent, resolveHook, resolveModel, resolvePrompt, resolveTool, rmdir, stat, supportsClientForwarding, tail, unlink, updateThread, writeFile, writeImage };
29050
+ export { CLIENT_STREAM_CHUNK_BYTES, CodeExecutionBridge, DurableAgentBuilder, DurableThread, DurableUserHub, FlowStateSdk, NamespaceResolutionError, ProviderRegistry, ThreadWatchdog, authenticate, buildImageDescription, callClient, callClientStream, canAccessThread, cat, createNamespaceContext, createThreadEndpointHandler, decodeStreamChunk, defineController2 as defineController, emitThreadEvent, encodeStreamChunk, endpointCallerFromAuth, 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, requireAdmin, requireAuth, resolveAgent, resolveHook, resolveModel, resolvePrompt, resolveTool, rmdir, stat, supportsClientForwarding, tail, unlink, updateThread, writeFile, writeImage };
28994
29051
  //# sourceMappingURL=runtime.js.map
28995
29052
  //# sourceMappingURL=runtime.js.map