@semiont/core 0.5.33 → 0.5.34

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/index.d.ts CHANGED
@@ -1975,6 +1975,11 @@ interface components {
1975
1975
  CommandError: {
1976
1976
  /** @description Optional correlation id echoed from the originating command. When present, the failure event can be matched back to the specific command that failed. */
1977
1977
  correlationId?: string;
1978
+ /**
1979
+ * @description Machine-readable failure class, for consumers that must BRANCH on why a command failed rather than log it. Optional and deliberately sparse: absent means 'no class declared', and every existing failure stays that way. An enum rather than a free string so the vocabulary has an owner — an unconstrained code is a mirror with no gate, and adding one should be a deliberate spec change. `message` remains the human-readable text and is unaffected. Members: `peer-unavailable` — the channel this command was sent on has no subscriber, i.e. the service that answers it has not connected yet. Transient by nature (a peer still starting), which is what distinguishes it from a refusal: retrying is the correct response.
1980
+ * @enum {string}
1981
+ */
1982
+ code?: "peer-unavailable";
1978
1983
  /** @description Human-readable error message */
1979
1984
  message: string;
1980
1985
  /** @description Optional additional context (stack trace, field name, etc.) */
@@ -6266,7 +6271,20 @@ type BridgedChannel = RegistryReply | (typeof BRIDGED_BROADCASTS)[number];
6266
6271
  type BusReply<Op extends BusOperationKey> = EventMap[(typeof BUS_OPERATIONS)[Op]['result'] & EventName] extends {
6267
6272
  response: infer R;
6268
6273
  } ? R : void;
6269
- type BusRequestErrorCode = 'bus.timeout' | 'bus.rejected' | 'bus.closed' | 'bus.bad-payload' | 'bus.unauthorized' | 'bus.forbidden' | 'bus.not-found' | 'bus.unsubscribed';
6274
+ type BusRequestErrorCode = 'bus.timeout' | 'bus.rejected' | 'bus.closed' | 'bus.bad-payload' | 'bus.unauthorized' | 'bus.forbidden' | 'bus.not-found'
6275
+ /**
6276
+ * THIS transport is not subscribed to the reply channel — a local
6277
+ * misconfiguration, caught before emitting. Not to be confused with
6278
+ * `bus.peer-unavailable`, which is the opposite end: the channel HAS no
6279
+ * subscriber because the service that answers it has not connected yet.
6280
+ */
6281
+ | 'bus.unsubscribed'
6282
+ /**
6283
+ * The service that answers this channel is not connected. Transient by
6284
+ * nature — a peer still starting — and therefore the one failure class on
6285
+ * this list worth retrying.
6286
+ */
6287
+ | 'bus.peer-unavailable';
6270
6288
  declare class BusRequestError extends SemiontError {
6271
6289
  code: BusRequestErrorCode;
6272
6290
  constructor(message: string, code: BusRequestErrorCode, details?: Record<string, unknown>);
@@ -7384,6 +7402,24 @@ declare function softwareToAgent(software: {
7384
7402
  *
7385
7403
  * Anything else falls back to a Person with the trailing segment as
7386
7404
  * `name`. This is the read-side inverse of `userToDid`/`agentToDid`.
7405
+ *
7406
+ * **`@id` is emitted only when the input is URI-shaped**, because every Agent
7407
+ * branch declares it `format: "uri"` and `@id` is required by none of them. A
7408
+ * non-URI value fails all three branches of the `oneOf`, and wire validation is
7409
+ * per-PAYLOAD — so one bad Agent rejects an entire `browse:resources-result`,
7410
+ * denying a reply about every resource in it. Measured 2026-09-09: one resource
7411
+ * carrying a raw CUID from pre-DID events (2026-03-26) made an unfiltered listing
7412
+ * of nine permanently unreturnable.
7413
+ *
7414
+ * This is a deliberate TOLERANCE, not a compatibility shim — it carries no
7415
+ * version check, no legacy branch, no second code path. It is one function
7416
+ * declining to assert an identifier it cannot vouch for. It is also a waypoint:
7417
+ * `userId` is declared `{"type":"string"}` with "DID of the user" in a
7418
+ * DESCRIPTION that nothing enforces, and the sequence out of here is (1) clean the
7419
+ * legacy values, (2) constrain `userId` in `StoredEventResponse.json`, (3) delete
7420
+ * this tolerance as unreachable. Do not delete it before step 2: the log is
7421
+ * append-only and the offending records cannot be edited away, so a strict reader
7422
+ * today would convert a partial failure into a total one.
7387
7423
  */
7388
7424
  declare function didToAgent(did: string | undefined | null): Agent;
7389
7425
 
@@ -8080,15 +8116,42 @@ interface GraphViews {
8080
8116
  declare function deriveViews(graph: KnowledgeGraph, mainResourceId: string, focalAnnotationId?: string): GraphViews;
8081
8117
 
8082
8118
  /**
8083
- * Bounded retry with exponential backoff.
8084
- *
8085
- * Exists for startup-critical network calls in long-running peers (worker,
8086
- * smelter, weaver): each authenticates against the KS the moment its
8087
- * container starts, and the gateway may not be reachable for a few seconds
8088
- * (gateway restart, container-network warm-up). Orchestration runs these
8089
- * processes with `--rm` and no restart policy, so a process that dies on
8090
- * the first `TypeError: fetch failed` is dead for good — the retry window
8091
- * here is the only recovery it gets.
8119
+ * Retry: the mechanism, and the classifications core itself owns.
8120
+ *
8121
+ * Originally just `retryWithBackoff`, for startup-critical calls in long-running
8122
+ * peers each authenticates the moment its container starts, the gateway may not
8123
+ * be reachable for a few seconds, and orchestration runs them with `--rm` and no
8124
+ * restart policy, so a process that dies on the first `TypeError: fetch failed` is
8125
+ * dead for good. That is still the shape; the module has grown a family around it.
8126
+ *
8127
+ * **What lives HERE — the mechanism, because it is one fact each:**
8128
+ * - `RetryPolicy` / `retryWithBackoff` — the loop, deadline-aware
8129
+ * - `equalJitter` — the backoff curve, shared with the SSE reconnect
8130
+ * - `retryBudgetMs` — how long a policy can take, derived rather than restated
8131
+ * - the predicates that narrow an error type CORE owns (`isTransientFetchError`
8132
+ * over `fetch`'s `TypeError`, `isRetryableRequestError` over `HttpStatusError`,
8133
+ * `isPeerUnavailable` over `BusRequestError`)
8134
+ *
8135
+ * **What deliberately does NOT — the judgment, because each is local knowledge:**
8136
+ * - **policies.** `EMIT_RETRY` (http-transport), `EMBEDDING_PROVIDER_RETRY`
8137
+ * (vectors). A policy answers *how long does THIS wait*, and centralizing that
8138
+ * is what caused a bug: the embedding path borrowed `STARTUP_FETCH_RETRY` —
8139
+ * sized for "until a peer starts listening" — to wait out a model download,
8140
+ * and its ceiling expired just before the thing it was waiting for arrived.
8141
+ * Two facts that happen to be measured in seconds are still two facts.
8142
+ * - **deadlines.** `EMIT_TIMEOUT_MS`, `EMBED_TIMEOUT_MS`,
8143
+ * `STARTUP_CONNECT_TIMEOUT_MS`, each with the call it bounds.
8144
+ * - **predicates over another package's errors.** `isColdModelError` is
8145
+ * `@semiont/vectors`'; core has no business knowing an Ollama 404 means
8146
+ * "not pulled yet".
8147
+ *
8148
+ * `STARTUP_FETCH_RETRY` is the one policy here, and only because five boot paths
8149
+ * genuinely share the one question it answers.
8150
+ *
8151
+ * **Deadlines beat budgets.** `retryWithBackoff` takes an optional `AbortSignal`
8152
+ * so a caller racing its own timeout can stop the retry, instead of the two
8153
+ * numbers having to be kept compatible by hand across packages. That is the
8154
+ * `context.Context` / gRPC-deadline move, with the platform's own primitive.
8092
8155
  */
8093
8156
  interface RetryPolicy {
8094
8157
  /** Total attempts, including the first one. */
@@ -8098,6 +8161,27 @@ interface RetryPolicy {
8098
8161
  /** Ceiling for the doubled delay. */
8099
8162
  maxDelayMs: number;
8100
8163
  }
8164
+ /**
8165
+ * Equal jitter: half the computed ceiling, plus a random share of the other
8166
+ * half — delay ∈ [cap/2, cap).
8167
+ *
8168
+ * **One home, because it is one fact.** `retryWithBackoff` and the SSE reconnect
8169
+ * loop (`actor-state-unit.ts`) both need it and carried byte-identical copies —
8170
+ * two implementations agreeing by coincidence, free to drift the first time
8171
+ * either is tuned. The reconnect computes its own ceiling (`reconnectMs · 2ⁿ`,
8172
+ * capped); only the jitter is shared, which is the part that must not diverge.
8173
+ *
8174
+ * Unconditional in `retryWithBackoff`, not an option. Every caller of
8175
+ * `retryWithBackoff` is a container in a fleet that boots together and retries
8176
+ * against ONE gateway, which is precisely the lockstep this exists to break: N
8177
+ * peers backing off by an identical schedule re-converge on the same instant and
8178
+ * re-deliver the burst that caused the failure. A flag would leave that hazard
8179
+ * reachable by default-choosing, and nobody would ever pass `false`.
8180
+ *
8181
+ * The worst case is unchanged — `delay <= cap` still holds, so the patience
8182
+ * budget a policy advertises stays true; only the expected wait drops, to ~75%.
8183
+ */
8184
+ declare function equalJitter(cap: number): number;
8101
8185
  interface RetryAttemptInfo {
8102
8186
  /** 1-based number of the attempt that just failed. */
8103
8187
  attempt: number;
@@ -8107,11 +8191,29 @@ interface RetryAttemptInfo {
8107
8191
  delayMs: number;
8108
8192
  error: unknown;
8109
8193
  }
8194
+ /**
8195
+ * The worst-case wall clock a policy can spend.
8196
+ *
8197
+ * Derived, because it was being restated by hand in three places — a docstring
8198
+ * saying "~39s", a test recomputing the sum, and a reader doing arithmetic to
8199
+ * decide whether some other deadline could cut it short. Any of those can drift
8200
+ * from the policy the moment someone edits it, and the drift is silent.
8201
+ *
8202
+ * `perAttemptMs` is the caller's per-attempt deadline. **Pass it, or the answer
8203
+ * is a lower bound rather than a ceiling**: delays are bounded by the policy, but
8204
+ * an unbounded attempt makes the total unbounded too, which is how a budget of
8205
+ * "12 attempts" ends up meaning nothing under packet loss. `0` (the default)
8206
+ * answers the delay sum alone, for a caller whose attempts cannot hang.
8207
+ *
8208
+ * Worst case, not expected: equal jitter puts each wait in [cap/2, cap), so the
8209
+ * true wait averages ~75% of this. A ceiling is what a deadline needs to clear.
8210
+ */
8211
+ declare function retryBudgetMs(policy: RetryPolicy, perAttemptMs?: number): number;
8110
8212
  /**
8111
8213
  * Default policy for startup connections to the gateway: 8 attempts with delay
8112
- * ceilings 1s, 2s, 4s, then capped at 8s up to ~39s of patience before giving
8113
- * up. "Up to", because the backoff is equal-jittered: each wait lands in
8114
- * [cap/2, cap), so the worst case is that sum and the expected case is ~75% of it.
8214
+ * ceilings 1s, 2s, 4s, then capped at 8s. `retryBudgetMs` is the authority on
8215
+ * how long that is; the equal-jittered backoff means the expected wait is ~75%
8216
+ * of the ceiling it reports.
8115
8217
  */
8116
8218
  declare const STARTUP_FETCH_RETRY: RetryPolicy;
8117
8219
  /**
@@ -8153,6 +8255,27 @@ interface HttpStatusError extends Error {
8153
8255
  * will not change its mind. A 429 differs — the gateway is up and *asking* us to
8154
8256
  * wait, so the same "it answered" fact points the other way.
8155
8257
  */
8258
+ /**
8259
+ * True when the service that answers a bus channel has not connected yet.
8260
+ *
8261
+ * A startup race, not a refusal: the gateway synthesizes this when a request's
8262
+ * channel has no subscriber, and the peer it is waiting for is usually seconds
8263
+ * away. The weaver's boot passes used to treat it as a data condition and give up
8264
+ * for the life of the process — an empty graph projection behind a healthy
8265
+ * `/health`, with live traffic then advancing the applied mark past events that
8266
+ * were never projected (2026-09-09).
8267
+ *
8268
+ * Narrow on purpose, and note what it EXCLUDES: `bus.unsubscribed` means *this*
8269
+ * transport is not subscribed to the reply channel — a local misconfiguration
8270
+ * caught before emitting, which retrying cannot fix and would only delay. The two
8271
+ * codes sound alike and mean opposite ends of the same wire; the predicate is
8272
+ * where that distinction has to hold.
8273
+ *
8274
+ * Takes a `BusRequestError` rather than any `{ code }` object: the code is a wire
8275
+ * value, and `busRequest` is the one place it is mapped into this vocabulary. An
8276
+ * object that did not come through there has not been classified.
8277
+ */
8278
+ declare function isPeerUnavailable(error: unknown): boolean;
8156
8279
  declare function isRetryableRequestError(error: unknown): boolean;
8157
8280
  /**
8158
8281
  * Run `fn`, retrying on errors `isRetryable` accepts, with equal-jitter
@@ -8161,7 +8284,23 @@ declare function isRetryableRequestError(error: unknown): boolean;
8161
8284
  * delay. The final error (retryable budget exhausted, or the first
8162
8285
  * non-retryable one) is rethrown verbatim.
8163
8286
  */
8164
- declare function retryWithBackoff<T>(fn: () => Promise<T>, isRetryable: (error: unknown) => boolean, policy: RetryPolicy, onRetry?: (info: RetryAttemptInfo) => void): Promise<T>;
8287
+ /**
8288
+ * Race `work` against a deadline, handing it the deadline as a signal.
8289
+ *
8290
+ * The other half of what this module owns: `retryWithBackoff` consumes an
8291
+ * `AbortSignal`, this produces one. A race alone can only ABANDON slow work —
8292
+ * work that retries never learns the deadline exists, and the two end up kept
8293
+ * compatible by hand.
8294
+ *
8295
+ * ONE timer drives both the abort and the rejection. `AbortSignal.timeout()`
8296
+ * schedules its own, so the signal and the race could fire at different moments,
8297
+ * which is the problem this exists to remove.
8298
+ *
8299
+ * `hint` is the caller's operational context, appended to the message — core
8300
+ * cannot know whether a restart policy is watching.
8301
+ */
8302
+ declare function withDeadline<T>(what: string, timeoutMs: number, work: (signal: AbortSignal) => Promise<T>, hint?: string): Promise<T>;
8303
+ declare function retryWithBackoff<T>(fn: () => Promise<T>, isRetryable: (error: unknown) => boolean, policy: RetryPolicy, onRetry?: (info: RetryAttemptInfo) => void, signal?: AbortSignal): Promise<T>;
8165
8304
 
8166
8305
  /**
8167
8306
  * Sharding Utilities
@@ -8229,5 +8368,5 @@ declare function getShardPath(key: string, numBuckets?: number): [string, string
8229
8368
  */
8230
8369
  declare const DISCOVERY_URL_PATH = "/discovery/kbs.json";
8231
8370
 
8232
- export { AUTHORABLE_MEDIA_TYPES, BRIDGED_CHANNELS, BUS_OPERATIONS, BusRequestError, CHANNEL_SCHEMAS, CONTEXT_FULL_WEIGHT, CONTEXT_PARTIAL_WEIGHT, ConfigurationError, ConflictError, DEFAULT_CHUNKING_CONFIG, DISCOVERY_URL_PATH, EMBEDDABLE_MEDIA_TYPES, EventBus, GENERATABLE_MEDIA_TYPES, JWTTokenSchema, LOCALES, MEDIA_TYPES, NotFoundError, PERSISTED_EVENT_TYPES, POSITION_WEIGHT_MAX, POSITION_WINDOW, RESOURCE_BROADCAST_TYPES, STARTUP_FETCH_RETRY, ScopedEventBus, ScriptError, SemiontError, UnauthorizedError, ValidationError, accessToken, agentToDid, anchorAnnotation, anchorRuns, annotationId, annotationUri, applyBodyOperations, assembleAnnotation, authCode, baseMediaType, baseUrl, buildContentCache, burstBuffer, busLog, busLogEnabled, busRequest, capabilitiesOf, chunkText, cloneFormat, cloneToken, createCircleSvg, createFragmentSelector, createPolygonSvg, createRectangleSvg, createTomlConfigLoader, decodeRepresentation, decodeWithCharset, deriveStorageUri, deriveViews, didToAgent, email, entityType, errField, estimateTokens, extensionForMediaType, extractBoundingBox, extractCharset, extractContext, findBestTextMatch, findBodyItem, findClaimSpan, folderOf, formatLocaleDisplay, generateUuid, getAllLocaleCodes, getAllPlatformTypes, getAnnotationExactText, getAnnotationUriFromEvent, getBodySource, getBodyType, getChecksum, getCommentText, getCreator, getDerivedFrom, getExactText, getFragmentSelector, getLanguage, getLocaleEnglishName, getLocaleInfo, getLocaleNativeName, getNodeEncoding, getPageFromFragment, getPrimaryMediaType, getPrimaryRepresentation, getPrimarySelector, getResourceEntityTypes, getResourceId, getShardPath, getStorageUri, getSvgSelector, getTargetSelector, getTargetSource, getTextPositionSelector, getTextQuoteSelector, googleCredential, hasTargetSelector, isAnnotatable, isAnnotationId, isArchived, isArray, isAssessment, isBodyResolved, isBoolean, isComment, isDefined, isDraft, isEventRelatedToAnnotation, isFunction, isGatheredContext, isGenerationJobParams, isHighlight, isNull, isNullish, isNumber, isObject, isReference, isResolvedReference, isResourceId, isRetryableRequestError, isStoredEvent, isString, isStubReference, isSupportedMediaType, isTag, isTextRun, isTransientFetchError, isUndefined, isValidEmail, isValidPlatformType, jobId, jumpConsistentHash, kbDid, loadTomlConfig, locate, mcpToken, mediaTypeForExtension, normalizeCoordinates, normalizeText, parseEnvironment, parseFragmentSelector, parseSvgSelector, proposeStoragePath, reconcileSelector, refreshToken, replyChannelsFor, resourceAnnotationUri, resourceId, resourceUri, retryWithBackoff, scaleSvgToNative, searchQuery, serializePerKey, setBusLogTraceIdProvider, softwareToAgent, storageFileName, textSourceOf, textUnder, userDID, userId, userToAgent, userToDid, uuidV4, validateData, validateEnvironment, validateSvgMarkup, verifyPosition, yieldsGeometryOf };
8371
+ export { AUTHORABLE_MEDIA_TYPES, BRIDGED_CHANNELS, BUS_OPERATIONS, BusRequestError, CHANNEL_SCHEMAS, CONTEXT_FULL_WEIGHT, CONTEXT_PARTIAL_WEIGHT, ConfigurationError, ConflictError, DEFAULT_CHUNKING_CONFIG, DISCOVERY_URL_PATH, EMBEDDABLE_MEDIA_TYPES, EventBus, GENERATABLE_MEDIA_TYPES, JWTTokenSchema, LOCALES, MEDIA_TYPES, NotFoundError, PERSISTED_EVENT_TYPES, POSITION_WEIGHT_MAX, POSITION_WINDOW, RESOURCE_BROADCAST_TYPES, STARTUP_FETCH_RETRY, ScopedEventBus, ScriptError, SemiontError, UnauthorizedError, ValidationError, accessToken, agentToDid, anchorAnnotation, anchorRuns, annotationId, annotationUri, applyBodyOperations, assembleAnnotation, authCode, baseMediaType, baseUrl, buildContentCache, burstBuffer, busLog, busLogEnabled, busRequest, capabilitiesOf, chunkText, cloneFormat, cloneToken, createCircleSvg, createFragmentSelector, createPolygonSvg, createRectangleSvg, createTomlConfigLoader, decodeRepresentation, decodeWithCharset, deriveStorageUri, deriveViews, didToAgent, email, entityType, equalJitter, errField, estimateTokens, extensionForMediaType, extractBoundingBox, extractCharset, extractContext, findBestTextMatch, findBodyItem, findClaimSpan, folderOf, formatLocaleDisplay, generateUuid, getAllLocaleCodes, getAllPlatformTypes, getAnnotationExactText, getAnnotationUriFromEvent, getBodySource, getBodyType, getChecksum, getCommentText, getCreator, getDerivedFrom, getExactText, getFragmentSelector, getLanguage, getLocaleEnglishName, getLocaleInfo, getLocaleNativeName, getNodeEncoding, getPageFromFragment, getPrimaryMediaType, getPrimaryRepresentation, getPrimarySelector, getResourceEntityTypes, getResourceId, getShardPath, getStorageUri, getSvgSelector, getTargetSelector, getTargetSource, getTextPositionSelector, getTextQuoteSelector, googleCredential, hasTargetSelector, isAnnotatable, isAnnotationId, isArchived, isArray, isAssessment, isBodyResolved, isBoolean, isComment, isDefined, isDraft, isEventRelatedToAnnotation, isFunction, isGatheredContext, isGenerationJobParams, isHighlight, isNull, isNullish, isNumber, isObject, isPeerUnavailable, isReference, isResolvedReference, isResourceId, isRetryableRequestError, isStoredEvent, isString, isStubReference, isSupportedMediaType, isTag, isTextRun, isTransientFetchError, isUndefined, isValidEmail, isValidPlatformType, jobId, jumpConsistentHash, kbDid, loadTomlConfig, locate, mcpToken, mediaTypeForExtension, normalizeCoordinates, normalizeText, parseEnvironment, parseFragmentSelector, parseSvgSelector, proposeStoragePath, reconcileSelector, refreshToken, replyChannelsFor, resourceAnnotationUri, resourceId, resourceUri, retryBudgetMs, retryWithBackoff, scaleSvgToNative, searchQuery, serializePerKey, setBusLogTraceIdProvider, softwareToAgent, storageFileName, textSourceOf, textUnder, userDID, userId, userToAgent, userToDid, uuidV4, validateData, validateEnvironment, validateSvgMarkup, verifyPosition, withDeadline, yieldsGeometryOf };
8233
8372
  export type { AccessToken, AnchorConfidence, AnchorMethod, AnchorRect, AnchorSelectors, AnchorStrategy, AnchoredText, AnchoredTextAnswer, AnchoringModel, Annotation, AnnotationCategory, AnnotationId, AnnotationUri, AnthropicProviderConfig, AppConfig, ArchivistServiceConfig, AssembledAnnotation, AuthCode, BaseUrl, BodyItem, BodyItemIdentity, BodyOperation, BoundingBox, Brand, BridgedChannel, BurstBufferOptions, BusOp, BusOperationKey, BusOperationSpec, BusRequestErrorCode, BusRequestPrimitive, ChunkingConfig, CloneToken, CollaboratorEntry, ConnectionState, ContentCache, ContentFormat, CreateAnnotationInternal, DatabaseServiceConfig, DiscoveredKB, DiscoveryDocument, Email, EmbeddingServiceConfig, EmittableChannel, EntityType, EntityTypeStats, Environment, EnvironmentConfig, EventBase, EventInput, EventMap, EventMetadata, EventName, EventOfType, EventQuery, EventSignature, ExtractionOutcome, FragmentSelector, GatewayServiceConfig, GatheredContext, GenerationJobParams, GoogleAuthRequest, GoogleCredential, GraphConnection, GraphDatabaseType, GraphPath, GraphServiceConfig, GraphViews, HealthCheckResponse, HttpStatusError, IContentTransport, IGatewayOperations, ITransport, InferenceProvidersConfig, JobAssessmentAnnotationResult, JobCommentAnnotationResult, JobHighlightAnnotationResult, JobId, JobReferenceAnnotationResult, JobTagAnnotationResult, JobType, ListUsersResponse, LlmSelectorInput, LocaleInfo, Logger, MCPToken, MatchQuality, McpServiceConfig, MediaTypeCapabilities, Motivation, OllamaProviderConfig, PdfCoordinate, PdfTextItem, PdfTextRun, PersistedEvent, PersistedEventType, PlatformType, Point, PutBinaryOptions, PutBinaryProgress, PutBinaryRequest, ReconciledSelector, RefreshToken, RenderMode, RenderedAnchor, ResourceAnnotationUri, ResourceAnnotations, ResourceBroadcastType, ResourceDescriptor, ResourceFilter, ResourceId, ResourceUri, RetryAttemptInfo, RetryPolicy, SearchQuery, SelectionData, Selector, SemiontConfig, ServicePlatformConfig, ServicesConfig, SiteConfig, StateUnit, StatusResponse, StoredEvent, StoredEventLike, StoredResource, SupportedMediaType, SvgSelector, TagCategory, TagSchema, TextPosition, TextPositionSelector, TextQuoteSelector, TextSource, ActorInferenceConfig as TomlActorInferenceConfig, TomlFileReader, InferenceConfig as TomlInferenceConfig, WorkerInferenceConfig as TomlWorkerInferenceConfig, TransportErrorCode, UpdateResourceInput, UpdateUserRequest, UpdateUserResponse, UserDID, UserId, UserResponse, ValidationFailure, ValidationResult, ValidationSuccess, VectorsServiceConfig, components, operations, paths };
package/dist/index.js CHANGED
@@ -1003,6 +1003,9 @@ var ConflictError = class extends SemiontError {
1003
1003
  };
1004
1004
 
1005
1005
  // src/bus-request.ts
1006
+ function classifyFailureCode(code) {
1007
+ return code === "peer-unavailable" ? "bus.peer-unavailable" : "bus.rejected";
1008
+ }
1006
1009
  var BusRequestError = class extends SemiontError {
1007
1010
  constructor(message, code, details) {
1008
1011
  super(message, code, details);
@@ -1044,7 +1047,7 @@ async function busRequest(bus, operation, payload, timeoutMs = 3e4) {
1044
1047
  filter((e) => e.correlationId === correlationId),
1045
1048
  map((e) => ({
1046
1049
  ok: false,
1047
- error: new BusRequestError(e.message ?? "Bus request rejected", "bus.rejected", {
1050
+ error: new BusRequestError(e.message ?? "Bus request rejected", classifyFailureCode(e.code), {
1048
1051
  channel: failureChannel,
1049
1052
  correlationId,
1050
1053
  payload: e
@@ -2036,17 +2039,19 @@ function softwareToAgent(software) {
2036
2039
  }
2037
2040
  function didToAgent(did) {
2038
2041
  if (!did) {
2039
- return { "@type": "Person", "@id": "unknown", name: "unknown" };
2042
+ return { "@type": "Person", name: "unknown" };
2040
2043
  }
2041
2044
  const parts = did.split(":");
2042
2045
  const agentsIdx = parts.lastIndexOf("agents");
2043
2046
  const usersIdx = parts.lastIndexOf("users");
2047
+ const uriShaped = (value) => /^[A-Za-z][A-Za-z0-9+.-]*:\S/.test(value);
2048
+ const identity = uriShaped(did) ? { "@id": did } : {};
2044
2049
  if (agentsIdx >= 0 && agentsIdx === parts.length - 3) {
2045
2050
  const provider = decodeURIComponent(parts[agentsIdx + 1] ?? "");
2046
2051
  const model = decodeURIComponent(parts[agentsIdx + 2] ?? "");
2047
2052
  return {
2048
2053
  "@type": "Software",
2049
- "@id": did,
2054
+ ...identity,
2050
2055
  name: `${provider} ${model}`,
2051
2056
  provider,
2052
2057
  model
@@ -2056,14 +2061,14 @@ function didToAgent(did) {
2056
2061
  const name = decodeURIComponent(parts[usersIdx + 1] ?? "");
2057
2062
  return {
2058
2063
  "@type": "Person",
2059
- "@id": did,
2064
+ ...identity,
2060
2065
  name
2061
2066
  };
2062
2067
  }
2063
2068
  const encoded = parts[parts.length - 1] || "unknown";
2064
2069
  return {
2065
2070
  "@type": "Person",
2066
- "@id": did,
2071
+ ...identity,
2067
2072
  name: decodeURIComponent(encoded)
2068
2073
  };
2069
2074
  }
@@ -2174,6 +2179,15 @@ function deriveViews(graph, mainResourceId, focalAnnotationId) {
2174
2179
  function equalJitter(cap) {
2175
2180
  return cap / 2 + Math.random() * (cap / 2);
2176
2181
  }
2182
+ function retryBudgetMs(policy, perAttemptMs = 0) {
2183
+ let cap = policy.initialDelayMs;
2184
+ let total = perAttemptMs;
2185
+ for (let i = 1; i < policy.attempts; i++) {
2186
+ total += cap + perAttemptMs;
2187
+ cap = Math.min(cap * 2, policy.maxDelayMs);
2188
+ }
2189
+ return total;
2190
+ }
2177
2191
  var STARTUP_FETCH_RETRY = {
2178
2192
  attempts: 8,
2179
2193
  initialDelayMs: 1e3,
@@ -2186,6 +2200,9 @@ function isTransientFetchError(error) {
2186
2200
  return typeof code === "string" && code.length > 0;
2187
2201
  }
2188
2202
  var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 503, 504]);
2203
+ function isPeerUnavailable(error) {
2204
+ return error instanceof BusRequestError && error.code === "bus.peer-unavailable";
2205
+ }
2189
2206
  function isRetryableRequestError(error) {
2190
2207
  if (isTransientFetchError(error)) return true;
2191
2208
  if (typeof error !== "object" || error === null) return false;
@@ -2193,12 +2210,33 @@ function isRetryableRequestError(error) {
2193
2210
  const status = error.status;
2194
2211
  return typeof status === "number" && RETRYABLE_STATUSES.has(status);
2195
2212
  }
2196
- async function retryWithBackoff(fn, isRetryable, policy, onRetry) {
2213
+ async function withDeadline(what, timeoutMs, work, hint) {
2214
+ const controller = new AbortController();
2215
+ let timer;
2216
+ try {
2217
+ return await Promise.race([
2218
+ work(controller.signal),
2219
+ new Promise((_resolve, reject) => {
2220
+ timer = setTimeout(() => {
2221
+ const expired = new Error(
2222
+ `${what} did not become available within ${timeoutMs / 1e3}s.${hint ? ` ${hint}` : ""}`
2223
+ );
2224
+ controller.abort(expired);
2225
+ reject(expired);
2226
+ }, timeoutMs);
2227
+ })
2228
+ ]);
2229
+ } finally {
2230
+ if (timer !== void 0) clearTimeout(timer);
2231
+ }
2232
+ }
2233
+ async function retryWithBackoff(fn, isRetryable, policy, onRetry, signal) {
2197
2234
  let cap = policy.initialDelayMs;
2198
2235
  for (let attempt = 1; ; attempt++) {
2199
2236
  try {
2200
2237
  return await fn();
2201
2238
  } catch (error) {
2239
+ if (signal?.aborted) throw error;
2202
2240
  if (attempt >= policy.attempts || !isRetryable(error)) throw error;
2203
2241
  const delayMs = equalJitter(cap);
2204
2242
  onRetry?.({ attempt, attempts: policy.attempts, delayMs, error });
@@ -2238,6 +2276,6 @@ function getShardPath(key, numBuckets = 65536) {
2238
2276
  // src/discovery.ts
2239
2277
  var DISCOVERY_URL_PATH = "/discovery/kbs.json";
2240
2278
 
2241
- export { AUTHORABLE_MEDIA_TYPES, BusRequestError, CHANNEL_SCHEMAS, CONTEXT_FULL_WEIGHT, CONTEXT_PARTIAL_WEIGHT, ConfigurationError, ConflictError, DEFAULT_CHUNKING_CONFIG, DISCOVERY_URL_PATH, EMBEDDABLE_MEDIA_TYPES, GENERATABLE_MEDIA_TYPES, JWTTokenSchema, LOCALES, MEDIA_TYPES, NotFoundError, PERSISTED_EVENT_TYPES, POSITION_WEIGHT_MAX, POSITION_WINDOW, RESOURCE_BROADCAST_TYPES, STARTUP_FETCH_RETRY, ScriptError, SemiontError, UnauthorizedError, ValidationError, agentToDid, anchorAnnotation, anchorRuns, annotationId, applyBodyOperations, assembleAnnotation, baseMediaType, buildContentCache, burstBuffer, busRequest, capabilitiesOf, chunkText, cloneFormat, createCircleSvg, createFragmentSelector, createPolygonSvg, createRectangleSvg, decodeRepresentation, decodeWithCharset, deriveStorageUri, deriveViews, didToAgent, errField, estimateTokens, extensionForMediaType, extractBoundingBox, extractCharset, extractContext, findBestTextMatch, findBodyItem, findClaimSpan, folderOf, formatLocaleDisplay, generateUuid, getAllLocaleCodes, getAllPlatformTypes, getAnnotationExactText, getAnnotationUriFromEvent, getBodySource, getBodyType, getChecksum, getCommentText, getCreator, getDerivedFrom, getExactText, getFragmentSelector, getLanguage, getLocaleEnglishName, getLocaleInfo, getLocaleNativeName, getNodeEncoding, getPageFromFragment, getPrimaryMediaType, getPrimaryRepresentation, getPrimarySelector, getResourceEntityTypes, getResourceId, getShardPath, getStorageUri, getSvgSelector, getTargetSelector, getTargetSource, getTextPositionSelector, getTextQuoteSelector, hasTargetSelector, isAnnotatable, isAnnotationId, isArchived, isArray, isAssessment, isBodyResolved, isBoolean, isComment, isDefined, isDraft, isEventRelatedToAnnotation, isFunction, isGatheredContext, isGenerationJobParams, isHighlight, isNull, isNullish, isNumber, isObject, isReference, isResolvedReference, isResourceId, isRetryableRequestError, isStoredEvent, isString, isStubReference, isSupportedMediaType, isTag, isTextRun, isTransientFetchError, isUndefined, isValidEmail, isValidPlatformType, jumpConsistentHash, kbDid, locate, mediaTypeForExtension, normalizeCoordinates, normalizeText, parseEnvironment, parseFragmentSelector, parseSvgSelector, proposeStoragePath, reconcileSelector, replyChannelsFor, resourceId, retryWithBackoff, scaleSvgToNative, serializePerKey, softwareToAgent, storageFileName, textSourceOf, textUnder, userId, userToAgent, userToDid, uuidV4, validateData, validateEnvironment, validateSvgMarkup, verifyPosition, yieldsGeometryOf };
2279
+ export { AUTHORABLE_MEDIA_TYPES, BusRequestError, CHANNEL_SCHEMAS, CONTEXT_FULL_WEIGHT, CONTEXT_PARTIAL_WEIGHT, ConfigurationError, ConflictError, DEFAULT_CHUNKING_CONFIG, DISCOVERY_URL_PATH, EMBEDDABLE_MEDIA_TYPES, GENERATABLE_MEDIA_TYPES, JWTTokenSchema, LOCALES, MEDIA_TYPES, NotFoundError, PERSISTED_EVENT_TYPES, POSITION_WEIGHT_MAX, POSITION_WINDOW, RESOURCE_BROADCAST_TYPES, STARTUP_FETCH_RETRY, ScriptError, SemiontError, UnauthorizedError, ValidationError, agentToDid, anchorAnnotation, anchorRuns, annotationId, applyBodyOperations, assembleAnnotation, baseMediaType, buildContentCache, burstBuffer, busRequest, capabilitiesOf, chunkText, cloneFormat, createCircleSvg, createFragmentSelector, createPolygonSvg, createRectangleSvg, decodeRepresentation, decodeWithCharset, deriveStorageUri, deriveViews, didToAgent, equalJitter, errField, estimateTokens, extensionForMediaType, extractBoundingBox, extractCharset, extractContext, findBestTextMatch, findBodyItem, findClaimSpan, folderOf, formatLocaleDisplay, generateUuid, getAllLocaleCodes, getAllPlatformTypes, getAnnotationExactText, getAnnotationUriFromEvent, getBodySource, getBodyType, getChecksum, getCommentText, getCreator, getDerivedFrom, getExactText, getFragmentSelector, getLanguage, getLocaleEnglishName, getLocaleInfo, getLocaleNativeName, getNodeEncoding, getPageFromFragment, getPrimaryMediaType, getPrimaryRepresentation, getPrimarySelector, getResourceEntityTypes, getResourceId, getShardPath, getStorageUri, getSvgSelector, getTargetSelector, getTargetSource, getTextPositionSelector, getTextQuoteSelector, hasTargetSelector, isAnnotatable, isAnnotationId, isArchived, isArray, isAssessment, isBodyResolved, isBoolean, isComment, isDefined, isDraft, isEventRelatedToAnnotation, isFunction, isGatheredContext, isGenerationJobParams, isHighlight, isNull, isNullish, isNumber, isObject, isPeerUnavailable, isReference, isResolvedReference, isResourceId, isRetryableRequestError, isStoredEvent, isString, isStubReference, isSupportedMediaType, isTag, isTextRun, isTransientFetchError, isUndefined, isValidEmail, isValidPlatformType, jumpConsistentHash, kbDid, locate, mediaTypeForExtension, normalizeCoordinates, normalizeText, parseEnvironment, parseFragmentSelector, parseSvgSelector, proposeStoragePath, reconcileSelector, replyChannelsFor, resourceId, retryBudgetMs, retryWithBackoff, scaleSvgToNative, serializePerKey, softwareToAgent, storageFileName, textSourceOf, textUnder, userId, userToAgent, userToDid, uuidV4, validateData, validateEnvironment, validateSvgMarkup, verifyPosition, withDeadline, yieldsGeometryOf };
2242
2280
  //# sourceMappingURL=index.js.map
2243
2281
  //# sourceMappingURL=index.js.map