@standardagents/builder 0.41.7 → 0.41.8

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,4 +1,4 @@
1
- import { D as DiscoveredPackage } from './types-D1ABHvAH.js';
1
+ import { D as DiscoveredPackage } from './types-Dhd0M369.js';
2
2
  import { ParentHookRequirement, PackageSignature } from '@standardagents/spec';
3
3
 
4
4
  /**
@@ -1,6 +1,6 @@
1
1
  import * as _standardagents_spec from '@standardagents/spec';
2
2
  import { ThreadState, ErrorOrigin, ToolResult as ToolResult$1, VariableDefinition, HookName, HookSignatures, HookMessage, HookToolCall, HookToolResult, CodeExecutionOptions, CodeExecutionResult, InjectMessageInput, QueueMessageInput, SubagentRegistryEntry, SubagentRelationship, PackageSignature, ProviderUsagePricing, ThreadUser, AgentDefinition, SkillMetadata, SkillFileInput, ControllerContext, Controller, ThreadEndpointHandler } from '@standardagents/spec';
3
- import { N as NamespacedRegistry } from './types-D1ABHvAH.js';
3
+ import { N as NamespacedRegistry } from './types-Dhd0M369.js';
4
4
  import { DurableObjectStorage } from '@cloudflare/workers-types';
5
5
  import { ZodObject, ZodRawShape } from 'zod';
6
6
 
@@ -1979,4 +1979,4 @@ declare function defineController<Env extends ThreadEnv = ThreadEnv>(controller:
1979
1979
  */
1980
1980
  declare function createThreadEndpointHandler<Env extends ThreadEnv = ThreadEnv>(handler: ThreadEndpointHandler): BuilderController<Env>;
1981
1981
 
1982
- 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 ProxyStreamReceiver as V, type ProxyStreamFrame as W, type ProxyStreamTarget as X, type ProxyStreamOpenResult as Y, type SkillStorageScope as Z, 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 };
1982
+ 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 ThreadEndpointContext as T, type MessageContent as U, type ProxyStreamReceiver as V, type ProxyStreamFrame as W, type ProxyStreamTarget as X, type ProxyStreamOpenResult as Y, type SkillStorageScope as Z, type BuilderControllerContext as a, type ThreadEnv as b, createThreadEndpointHandler as c, defineController as d, type BuilderThreadEndpointHandler as e, authenticate as f, requireAdmin as g, endpointCallerFromAuth 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 ToolCall as y, type ToolResult as z };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { ModelDefinition, AgentDefinition } from './runtime.js';
2
- export { AgentBuilderEnv, AgentBuilderEvent, BroadcastOptions, CodeExecutionBridge, DurableAgentBuilder, DurableThread, DurableUserHub, FlowStateSdk, FlowStateWithSdk, HandlerSide, HubClientInfo, HumanSide, ImageContextConfig, InjectMessageOptions, LLMProviderInterface, NamespaceResolutionError, PromptContent, PromptDefinition, PromptIncludePart, PromptPart, PromptSide, PromptToolConfig, Provider, ProviderContentPart, ProviderFilePart, ProviderImagePart, ProviderRegistry, ProviderTextPart, SessionToolBinding, SessionToolConfig, SideConfig, SubagentRelationship, SubagentToolConfig, SubpromptConfig, ThreadEventPayload, ThreadRegistryEntry, ThreadWatchdog, ThreadWatchdogState, ToolConfig, UpdateThreadParams, User, WatchdogCheckin, WatchdogProbeResult, applyRuntimeCors, 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, isSameOriginBrowserRequest, isTrustedLocalDevelopmentRequest, linkFile, mkdir, move, optimizeImageContext, parseQualifiedName, qualifyName, queueTool, readFile, readdir, reloadHistory, rename, replaceImagesWithDescriptions, resolveAgent, resolveHook, resolveModel, resolvePrompt, resolveTool, rmdir, runtimeCorsHeaders, runtimePreflightResponse, stat, tail, unlink, updateThread, writeFile, writeImage } from './runtime.js';
1
+ import { M as ModelDefinition, A as AgentDefinition } from './resolver-BMZAzKD3.js';
2
+ export { m as AgentBuilderEnv, n as AgentBuilderEvent, ah as BroadcastOptions, C as CodeExecutionBridge, h as DurableAgentBuilder, D as DurableThread, l as DurableUserHub, af as FlowStateSdk, ai as FlowStateWithSdk, G as HandlerSide, H as HubClientInfo, E as HumanSide, aq as ImageContextConfig, ae as InjectMessageOptions, as as LLMProviderInterface, aL as NamespaceResolutionError, w as PromptContent, s as PromptDefinition, y as PromptIncludePart, x as PromptPart, F as PromptSide, t as PromptToolConfig, P as Provider, at as ProviderContentPart, aw as ProviderFilePart, av as ProviderImagePart, ar as ProviderRegistry, au as ProviderTextPart, B as SessionToolBinding, z as SessionToolConfig, I as SideConfig, J as SubagentRelationship, u as SubagentToolConfig, S as SubpromptConfig, o as ThreadEventPayload, p as ThreadRegistryEntry, T as ThreadWatchdog, j as ThreadWatchdogState, v as ToolConfig, U as UpdateThreadParams, q as User, k as WatchdogCheckin, W as WatchdogProbeResult, f as applyRuntimeCors, am as buildImageDescription, c as canAccessThread, a9 as cat, aJ as createNamespaceContext, Q as emitThreadEvent, ag as enhanceFlowState, a0 as exists, ad as find, R as forceTurn, ap as generateImageDescription, a7 as getFileStats, N as getMessages, al as getMessagesToSummarize, az as getShortName, a8 as getThumbnail, ak as getUnsummarizedImageAttachments, aG as getVisibleAgentNames, aI as getVisibleModelNames, aH as getVisiblePromptNames, aF as getVisibleToolNames, ac as grep, aj as hasImageAttachments, aa as head, L as injectMessage, d as isAdminOnlyApiRoute, i as isHostedInstance, b as isPublicApiRoute, aK as isQualifiedName, e as isSameOriginBrowserRequest, a as isTrustedLocalDevelopmentRequest, Z as linkFile, a2 as mkdir, a5 as move, ao as optimizeImageContext, ax as parseQualifiedName, ay as qualifyName, K as queueTool, _ as readFile, a3 as readdir, O as reloadHistory, a6 as rename, an as replaceImagesWithDescriptions, aD as resolveAgent, aE as resolveHook, aC as resolveModel, aB as resolvePrompt, aA as resolveTool, a4 as rmdir, r as runtimeCorsHeaders, g as runtimePreflightResponse, $ as stat, ab as tail, a1 as unlink, V as updateThread, X as writeFile, Y as writeImage } from './resolver-BMZAzKD3.js';
3
3
  export { AgentPluginOptions, agentbuilder, builder } from './plugin.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-PSu6cMEz.js';
4
+ export { v as Agent, J as AttachmentRef, i as AuthContext, A as AuthUser, e 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, 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, T as ThreadEndpointContext, b as ThreadEnv, w as ThreadInstance, x as ThreadMetadata, y as ToolCall, z as ToolResult, f as authenticate, j as callClient, k as callClientStream, c as createThreadEndpointHandler, m as decodeStreamChunk, d as defineController, l as encodeStreamChunk, h as endpointCallerFromAuth, g as requireAdmin, r as requireAuth, s as supportsClientForwarding } from './index-ChHAVogf.js';
5
5
  export { AgentType, DefineHandlerOptions, DefinitionLoader, GlobalNamespaceContext, HANDLER_SYMBOL, HandlerDefinition, HookExecutionContext, HookExecutionSource, HookSignatures, ImageContent, ModelCapabilities, ModelProvider, NamespaceContext, PackageSignature, PackedExports, PackedMeta, PackedMetadata, PackedNamespaceContext, ParentHookRequirement, ParentHookStage, 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, ThreadHookName, Tool, ToolArgs, ToolArgsNode, ToolArgsRawShape, ToolContent, belongsToPackage, defineAgent, defineHandler, defineHook, defineModel, definePrompt, defineProvider, defineTool, isHandler, isPacked, isVisibleInNamespace, mapReasoningLevel, providerConst, providerEnv, providerValue } from '@standardagents/spec';
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-D1ABHvAH.js';
7
- export { D as DiscoveryConfig, P as PackageDiscoveryService, d as discoverPackages } from './discovery-CIGNVJfG.js';
6
+ export { C as ConstituentItem, D as DiscoveredPackage, N as NamespacedRegistry, P as PackingAnalysis, a as PackingOptions, b as PackingResult, U as UnpackOptions, c as UnpackResult } from './types-Dhd0M369.js';
7
+ export { D as DiscoveryConfig, P as PackageDiscoveryService, d as discoverPackages } from './discovery-D5pmuazY.js';
8
8
  import 'cloudflare:workers';
9
9
  import 'vite';
10
10
  import '@cloudflare/workers-types';
package/dist/index.js CHANGED
@@ -37709,6 +37709,8 @@ import {
37709
37709
  applyRuntimeCors,
37710
37710
  runtimeCorsHeaders,
37711
37711
  runtimePreflightResponse,
37712
+ formatUpstreamTiming,
37713
+ withUpstreamTiming,
37712
37714
  } from "@standardagents/builder/runtime";
37713
37715
  import { isThreadEndpoint, getEndpointAccess } from "@standardagents/spec";
37714
37716
 
@@ -37833,13 +37835,19 @@ ${packedThreadRouteCode}
37833
37835
  // thread id, for same-request reuse by controllers (AB-05). Never cached
37834
37836
  // across requests.
37835
37837
  let threadAccess = null;
37838
+ // The request handed to the controller. A protected API request carries
37839
+ // x-standard-upstream-timing with the authentication cost; the header is
37840
+ // overwritten, never merged, so a caller cannot forge upstream time.
37841
+ let controllerRequest = request;
37836
37842
 
37837
37843
  // Require authentication for all API routes except public ones.
37838
37844
  // WebSocket tickets are single-use and are consumed here. Controllers
37839
37845
  // must reuse context.auth (resolveRequestAuth) rather than calling
37840
37846
  // requireAuth again, or a ticket-only upgrade will 401.
37841
37847
  if (isApiRoute && !publicRoute) {
37848
+ const authStartedAt = Date.now();
37842
37849
  const authResult = await requireAuth(request, env);
37850
+ controllerRequest = withUpstreamTiming(request, formatUpstreamTiming('auth', Date.now() - authStartedAt));
37843
37851
 
37844
37852
  // If requireAuth returns a Response, it's an error (401)
37845
37853
  if (authResult instanceof Response) {
@@ -37896,7 +37904,7 @@ ${packedThreadRouteCode}
37896
37904
  }
37897
37905
 
37898
37906
  const context = {
37899
- req: request,
37907
+ req: controllerRequest,
37900
37908
  params: routeMatch.params || {},
37901
37909
  env: env,
37902
37910
  url: url,
@@ -39380,6 +39388,9 @@ var UserStateImpl = class {
39380
39388
  host;
39381
39389
  /** Caller descriptor for grant `allow` policy checks. */
39382
39390
  caller;
39391
+ /** One identity lookup per execution: the singleton RPC runs at most once. */
39392
+ identityLookup = null;
39393
+ identityLookupMs = null;
39383
39394
  constructor(userId, host, caller) {
39384
39395
  this.userId = userId;
39385
39396
  this.host = host;
@@ -39391,6 +39402,22 @@ var UserStateImpl = class {
39391
39402
  return ns.get(ns.idFromName("singleton"));
39392
39403
  }
39393
39404
  async identity() {
39405
+ if (!this.identityLookup) {
39406
+ const started = Date.now();
39407
+ this.identityLookup = this.lookupIdentity().finally(() => {
39408
+ this.identityLookupMs = Date.now() - started;
39409
+ });
39410
+ this.identityLookup.catch(() => {
39411
+ this.identityLookup = null;
39412
+ });
39413
+ }
39414
+ return this.identityLookup;
39415
+ }
39416
+ /** Milliseconds the execution spent resolving identity, once it has. */
39417
+ timing() {
39418
+ return { identity_ms: this.identityLookupMs };
39419
+ }
39420
+ async lookupIdentity() {
39394
39421
  const user = await this.singleton().getUserById(this.userId);
39395
39422
  if (!user) throw new Error(`Unknown user: ${this.userId}`);
39396
39423
  return {
@@ -39489,6 +39516,44 @@ function createExecutionChain() {
39489
39516
  };
39490
39517
  }
39491
39518
 
39519
+ // src/users/upstream-timing.ts
39520
+ var UPSTREAM_TIMING_HEADER = "x-standard-upstream-timing";
39521
+ var MAX_HEADER_CHARS = 512;
39522
+ function formatUpstreamTiming(name, durationMs) {
39523
+ const safe = Number.isFinite(durationMs) && durationMs > 0 ? durationMs : 0;
39524
+ return `${name};dur=${Math.round(safe * 10) / 10}`;
39525
+ }
39526
+ function appendUpstreamTiming(current, name, durationMs) {
39527
+ const entry = formatUpstreamTiming(name, durationMs);
39528
+ if (!current) return entry;
39529
+ const combined = `${current}, ${entry}`;
39530
+ return combined.length > MAX_HEADER_CHARS ? current : combined;
39531
+ }
39532
+ function withUpstreamTiming(request, value) {
39533
+ const headers = new Headers(request.headers);
39534
+ headers.set(UPSTREAM_TIMING_HEADER, value);
39535
+ return new Request(request, { headers });
39536
+ }
39537
+ function responseWithUpstreamTiming(response, name, durationMs) {
39538
+ if (response.status === 101) return response;
39539
+ const value = appendUpstreamTiming(response.headers.get(UPSTREAM_TIMING_HEADER), name, durationMs);
39540
+ try {
39541
+ response.headers.set(UPSTREAM_TIMING_HEADER, value);
39542
+ return response;
39543
+ } catch {
39544
+ const headers = new Headers(response.headers);
39545
+ headers.set(UPSTREAM_TIMING_HEADER, value);
39546
+ return new Response(response.body, {
39547
+ status: response.status,
39548
+ statusText: response.statusText,
39549
+ headers
39550
+ });
39551
+ }
39552
+ }
39553
+
39554
+ // src/durable-objects/DurableUserHub.ts
39555
+ init_bridge_owner();
39556
+
39492
39557
  // src/users/grants.ts
39493
39558
  var INSTANCE_GRANTS_MAX_BYTES = 64 * 1024;
39494
39559
  var INSTANCE_GRANTS_MAX_COUNT = 64;
@@ -39729,11 +39794,7 @@ var DurableUserHub = class extends DurableObject {
39729
39794
  if (request.headers.get("Upgrade") === "websocket") {
39730
39795
  const pair = new WebSocketPair();
39731
39796
  const [client, server] = [pair[0], pair[1]];
39732
- const info = {
39733
- clientId: url.searchParams.get("client_id"),
39734
- clientName: url.searchParams.get("client_name"),
39735
- clientKind: url.searchParams.get("client_kind")
39736
- };
39797
+ const info = parseBridgeClientParams(url).info;
39737
39798
  this.ensureHeartbeatAutoResponse();
39738
39799
  this.ctx.acceptWebSocket(server);
39739
39800
  server.serializeAttachment({ type: "hub_client", ...info });
@@ -39832,13 +39893,21 @@ var DurableUserHub = class extends DurableObject {
39832
39893
  { status: 500 }
39833
39894
  );
39834
39895
  }
39896
+ const queuedAt = Date.now();
39835
39897
  return this.executionChain.run(async () => {
39898
+ const queueMs = Date.now() - queuedAt;
39899
+ const timed = withUpstreamTiming(
39900
+ request,
39901
+ appendUpstreamTiming(request.headers.get(UPSTREAM_TIMING_HEADER), "queue", queueMs)
39902
+ );
39836
39903
  const user = new UserStateImpl(userId, this.scopeHost(), {
39837
39904
  kind: "userEndpoint",
39838
39905
  name: match.key
39839
39906
  });
39840
39907
  try {
39841
- return await handler.__handler(request, user, match.params);
39908
+ const response = await handler.__handler(timed, user, match.params);
39909
+ const identityMs = user.timing().identity_ms;
39910
+ return identityMs === null ? response : responseWithUpstreamTiming(response, "identity", identityMs);
39842
39911
  } catch (error) {
39843
39912
  return Response.json(
39844
39913
  { error: error instanceof Error ? error.message : "User endpoint failed" },
@@ -39885,6 +39954,8 @@ var DurableUserHub = class extends DurableObject {
39885
39954
  this.ctx.waitUntil(run());
39886
39955
  }
39887
39956
  async webSocketClose(ws) {
39957
+ this.clientSockets.delete(ws);
39958
+ this.clientInfo.delete(ws);
39888
39959
  const attachment = ws.deserializeAttachment();
39889
39960
  if (attachment?.type === "user_stream") {
39890
39961
  this.dispatchUserHooks(String(attachment.userId), "user_client_detached", [
@@ -39893,10 +39964,7 @@ var DurableUserHub = class extends DurableObject {
39893
39964
  kind: typeof attachment.clientKind === "string" ? attachment.clientKind : void 0
39894
39965
  }
39895
39966
  ]);
39896
- return;
39897
39967
  }
39898
- this.clientSockets.delete(ws);
39899
- this.clientInfo.delete(ws);
39900
39968
  }
39901
39969
  // ─── User scope: credential grants (spec: Users §6) ───────────────────────
39902
39970
  /**
@@ -40017,7 +40085,16 @@ var DurableUserHub = class extends DurableObject {
40017
40085
  });
40018
40086
  }
40019
40087
  async webSocketMessage(ws, _message) {
40020
- if (!this.clientSockets.has(ws)) this.clientSockets.add(ws);
40088
+ const attachment = ws.deserializeAttachment();
40089
+ if (attachment?.type !== "hub_client") return;
40090
+ if (!this.clientSockets.has(ws)) {
40091
+ this.clientSockets.add(ws);
40092
+ this.clientInfo.set(ws, {
40093
+ clientId: typeof attachment.clientId === "string" ? attachment.clientId : null,
40094
+ clientName: typeof attachment.clientName === "string" ? attachment.clientName : null,
40095
+ clientKind: typeof attachment.clientKind === "string" ? attachment.clientKind : null
40096
+ });
40097
+ }
40021
40098
  }
40022
40099
  async webSocketError(ws) {
40023
40100
  await this.webSocketClose(ws);