@semiont/core 0.5.20 → 0.5.22

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
@@ -1865,6 +1865,20 @@ interface components {
1865
1865
  BeckonSparkleEvent: {
1866
1866
  annotationId: string;
1867
1867
  };
1868
+ /** @description One edit to a linking annotation's body list: add or remove a body item, or replace an existing one. */
1869
+ BindBodyOperation: {
1870
+ /**
1871
+ * @description The type of body operation
1872
+ * @enum {string}
1873
+ */
1874
+ op: "add" | "remove" | "replace";
1875
+ /** @description Body item for add operations */
1876
+ item?: components["schemas"]["AnnotationBody"];
1877
+ /** @description Previous body item for replace operations */
1878
+ oldItem?: components["schemas"]["AnnotationBody"];
1879
+ /** @description Replacement body item for replace operations */
1880
+ newItem?: components["schemas"]["AnnotationBody"];
1881
+ };
1868
1882
  /** @description Void success reply emitted on the bind:body-updated channel after bind:update-body has been applied, matched to the originating command by correlationId. */
1869
1883
  BindBodyUpdated: {
1870
1884
  /** @description Correlation id echoed from the originating bind:update-body command so busRequest can match the reply. */
@@ -1891,20 +1905,8 @@ interface components {
1891
1905
  annotationId: string;
1892
1906
  /** @description Branded ResourceId of the resource the annotation belongs to */
1893
1907
  resourceId: string;
1894
- /** @description List of body mutation operations to apply */
1895
- operations: {
1896
- /**
1897
- * @description The type of body operation
1898
- * @enum {string}
1899
- */
1900
- op: "add" | "remove" | "replace";
1901
- /** @description Body item for add operations */
1902
- item?: components["schemas"]["AnnotationBody"];
1903
- /** @description Previous body item for replace operations */
1904
- oldItem?: components["schemas"]["AnnotationBody"];
1905
- /** @description Replacement body item for replace operations */
1906
- newItem?: components["schemas"]["AnnotationBody"];
1907
- }[];
1908
+ /** @description Ordered body-list edits to apply. */
1909
+ operations: components["schemas"]["BindBodyOperation"][];
1908
1910
  };
1909
1911
  BodyOperationAdd: {
1910
1912
  /** @enum {string} */
@@ -2241,8 +2243,8 @@ interface components {
2241
2243
  placement: "local" | "codespace";
2242
2244
  /** @description owner/name GitHub slug — present for codespace placements, where the repo is the stack's identity */
2243
2245
  repo?: string;
2244
- /** @description The KB's did:web identifier as recorded from its committed .semiont/config — the permanent identity stamped into its event log. Prefer this as a merge key: ports are reallocated across restarts; the did follows the KB. */
2245
- did?: string;
2246
+ /** @description The KB's did:web identifier, from its committed .semiont/config — "did:web:" + the [site] domain, verbatim. REQUIRED: a KB that declares no domain has no identity to publish, and the launcher refuses to start it rather than inventing or defaulting one. NOT unique within a document: a did names the knowledge base, not a running copy of it, so a local clone and a codespace of the same repo legitimately share one and both are published. host:port is the unique field (at most one entry per address), so consumers look up by ADDRESS and use the did to VERIFY that the copy they reached is the KB they meant — an address alone cannot say which KB is which, and an identity alone cannot say which copy. */
2247
+ did: string;
2246
2248
  /** @description Human-readable site name from the KB's .semiont/config, for display */
2247
2249
  siteName?: string;
2248
2250
  /** @description The agent that owns this entry's lifecycle (the launcher writes "semiont-launcher"). Consumers treat managed entries as authoritative for themselves — upsert on appearance, remove on disappearance — and never touch entries they did not write. */
@@ -2356,6 +2358,15 @@ interface components {
2356
2358
  /** @description The gathered annotation context (unified GatheredContext, focus.kind:'annotation') */
2357
2359
  response: components["schemas"]["GatheredContext"];
2358
2360
  };
2361
+ /** @description Optional configuration for an annotation-focus gather, which windows text around a mark. Distinct from the resource-focus options (depth / maxResources / includeContent / includeSummary), which traverse the resource graph. */
2362
+ GatherAnnotationOptions: {
2363
+ /** @description Whether to include source context in the gathered result */
2364
+ includeSourceContext?: boolean;
2365
+ /** @description Whether to include target context in the gathered result */
2366
+ includeTargetContext?: boolean;
2367
+ /** @description Characters of surrounding text context to include */
2368
+ contextWindow?: number;
2369
+ };
2359
2370
  /** @description Request payload sent on the gather:requested bus channel to gather context for an annotation. */
2360
2371
  GatherAnnotationRequest: {
2361
2372
  /** @description Client-generated correlation ID to thread the response back to the originating request */
@@ -2364,15 +2375,7 @@ interface components {
2364
2375
  annotationId: string;
2365
2376
  /** @description Branded ResourceId of the resource the annotation belongs to */
2366
2377
  resourceId: string;
2367
- /** @description Optional gathering configuration */
2368
- options?: {
2369
- /** @description Whether to include source context in the gathered result */
2370
- includeSourceContext?: boolean;
2371
- /** @description Whether to include target context in the gathered result */
2372
- includeTargetContext?: boolean;
2373
- /** @description Characters of surrounding text context to include */
2374
- contextWindow?: number;
2375
- };
2378
+ options?: components["schemas"]["GatherAnnotationOptions"];
2376
2379
  };
2377
2380
  /** @description Progress payload emitted on the gather:annotation-progress SSE channel during LLM context gathering. */
2378
2381
  GatherProgress: {
@@ -2972,12 +2975,8 @@ interface components {
2972
2975
  MatchSearchResult: {
2973
2976
  correlationId: string;
2974
2977
  referenceId: string;
2975
- response: (components["schemas"]["ResourceDescriptor"] & {
2976
- /** @description Relevance score */
2977
- score?: number;
2978
- /** @description Human-readable reason for the match */
2979
- matchReason?: string;
2980
- })[];
2978
+ /** @description The scored candidates, best first. */
2979
+ response: components["schemas"]["ScoredResource"][];
2981
2980
  };
2982
2981
  MediaTokenRequest: {
2983
2982
  /** @description The resource ID to generate a media token for */
@@ -3179,6 +3178,13 @@ interface components {
3179
3178
  contentChecksum: string;
3180
3179
  contentByteSize?: number;
3181
3180
  };
3181
+ /** @description A resource returned by a search, carrying its relevance score and the reason it matched. */
3182
+ ScoredResource: components["schemas"]["ResourceDescriptor"] & {
3183
+ /** @description Relevance score assigned by the matcher; higher is a better candidate. */
3184
+ score?: number;
3185
+ /** @description Human-readable reason for the match. */
3186
+ matchReason?: string;
3187
+ };
3182
3188
  /** @description Selection data for user-initiated annotations. Captures the text range and optional selector information from a user's highlight in the UI. */
3183
3189
  SelectionData: {
3184
3190
  /** @description The exact selected text */
@@ -3245,6 +3251,8 @@ interface components {
3245
3251
  projectName?: string;
3246
3252
  /** @description Current git branch of the knowledge base repository */
3247
3253
  gitBranch?: string;
3254
+ /** @description The knowledge base's did:web identity — 'did:web:' + the committed [site] domain, byte-identical to the string the launcher publishes in its discovery document. REQUIRED: a KB that declares no domain does not run (the launcher refuses to start it, and the backend refuses to boot), so a response without this field means the caller reached something that bypassed both. Identifies WHICH knowledge base this is; it does NOT identify which running copy — one KB reachable at two addresses (a local clone and a codespace of one repo) reports the same did at both. Use it to verify what you connected to, not to select among discovered entries. */
3255
+ did: string;
3248
3256
  };
3249
3257
  /** @description A persisted domain event with metadata. Flat shape — event fields and metadata are peers. */
3250
3258
  StoredEventResponse: {
@@ -3787,6 +3795,23 @@ interface ResourceAnnotations {
3787
3795
  updatedAt: string;
3788
3796
  }
3789
3797
 
3798
+ /**
3799
+ * Viewport-space rectangle of a clicked annotation element — runtime-only
3800
+ * view geometry riding UI events (never wire vocabulary; deliberately not in
3801
+ * the OpenAPI schemas). Structurally satisfied by a DOM `DOMRect`, spelled
3802
+ * out here because this package compiles without the DOM lib.
3803
+ */
3804
+ interface AnchorRect {
3805
+ x: number;
3806
+ y: number;
3807
+ width: number;
3808
+ height: number;
3809
+ top: number;
3810
+ right: number;
3811
+ bottom: number;
3812
+ left: number;
3813
+ }
3814
+
3790
3815
  /**
3791
3816
  * Bus Protocol
3792
3817
  *
@@ -3830,22 +3855,6 @@ type BindUpdateBodyCommand = components['schemas']['BindUpdateBodyCommand'] & {
3830
3855
  * - Commands/reads/results/UI: OpenAPI schema refs — plain strings
3831
3856
  * - void: UI-only signals with no payload
3832
3857
  */
3833
- /**
3834
- * Viewport-space rectangle of a clicked annotation element — runtime-only
3835
- * view geometry riding UI events (never wire vocabulary; deliberately not in
3836
- * the OpenAPI schemas). Structurally satisfied by a DOM `DOMRect`, spelled
3837
- * out here because this package compiles without the DOM lib.
3838
- */
3839
- interface AnchorRect {
3840
- x: number;
3841
- y: number;
3842
- width: number;
3843
- height: number;
3844
- top: number;
3845
- right: number;
3846
- bottom: number;
3847
- left: number;
3848
- }
3849
3858
  type EventMap = {
3850
3859
  'yield:created': StoredEvent<EventOfType<'yield:created'>>;
3851
3860
  'yield:cloned': StoredEvent<EventOfType<'yield:cloned'>>;
@@ -4183,6 +4192,7 @@ type EventMap = {
4183
4192
  reason: string;
4184
4193
  };
4185
4194
  };
4195
+
4186
4196
  /**
4187
4197
  * Any valid channel name on the EventBus — `keyof EventMap`, the root channel
4188
4198
  * type. Two subsets matter, and confusing them is a silent-failure trap:
@@ -6495,8 +6505,12 @@ declare function isDefined<T>(value: T | null | undefined): value is T;
6495
6505
  *
6496
6506
  * DID:WEB shapes used in Semiont:
6497
6507
  *
6498
- * Person: did:web:<host>:users:<email%40host>
6499
- * Software: did:web:<host>:agents:<provider>:<model>
6508
+ * Knowledge base: did:web:<domain>
6509
+ * Person: did:web:<domain>:users:<email%40host>
6510
+ * Software: did:web:<domain>:agents:<provider>:<model>
6511
+ *
6512
+ * `<domain>` is the KB's committed `[site] domain` — one identity, with its
6513
+ * people and software peers named beneath it.
6500
6514
  *
6501
6515
  * `didToAgent` is the inverse: parse the DID, recognize whether the
6502
6516
  * subject is a person or a software peer, and return a typed Agent.
@@ -6508,6 +6522,23 @@ declare function isDefined<T>(value: T | null | undefined): value is T;
6508
6522
  */
6509
6523
 
6510
6524
  type Agent = components['schemas']['Agent'];
6525
+ /**
6526
+ * The knowledge base's own did:web identity, from its committed
6527
+ * `[site] domain` (`SemiontProject.siteDomain()`).
6528
+ *
6529
+ * Format: `did:web:<domain>` — the domain **verbatim, never encoded**. The
6530
+ * config already stores it in did:web colon-path form
6531
+ * (`the-ai-alliance.github.io:semiont-caselaw-kb`), so encoding those colons
6532
+ * would mint a string nothing else in the system produces. The launcher
6533
+ * mints the identical string in Go (`kbconfig.go` `didWeb()`), and the two
6534
+ * MUST agree byte-for-byte: the Browser joins discovered KBs to connected
6535
+ * ones on this value, and a mismatch fails silently — looking implemented
6536
+ * while never matching (.plans/KB-IDENTITY-VS-ADDRESS.md).
6537
+ *
6538
+ * A KB has no did when it declares no domain; identity is declared, never
6539
+ * defaulted or inferred from an address.
6540
+ */
6541
+ declare function kbDid(domain: string): string;
6511
6542
  /**
6512
6543
  * Convert a user object to a DID:WEB identifier.
6513
6544
  *
@@ -7170,18 +7201,19 @@ type TomlFileReader = {
7170
7201
  * Parse ~/.semiontconfig and .semiont/config and return EnvironmentConfig.
7171
7202
  *
7172
7203
  * @param projectRoot - Path to the project root (contains .semiont/config)
7173
- * @param environment - Environment name (e.g. 'local', 'production')
7204
+ * @param environment - Environment name (e.g. 'local', 'production'); when
7205
+ * undefined, resolved from SEMIONT_ENV, then `[defaults] environment`
7174
7206
  * @param globalConfigPath - Path to ~/.semiontconfig (caller resolves ~ expansion)
7175
7207
  * @param reader - File reader abstraction
7176
7208
  * @param env - Environment variables for ${VAR} resolution
7177
7209
  */
7178
- declare function loadTomlConfig(projectRoot: string | null, environment: string, globalConfigPath: string, reader: TomlFileReader, env: Record<string, string | undefined>): EnvironmentConfig;
7210
+ declare function loadTomlConfig(projectRoot: string | null, environment: string | undefined, globalConfigPath: string, reader: TomlFileReader, env: Record<string, string | undefined>): EnvironmentConfig;
7179
7211
  /**
7180
7212
  * Create a TOML config loader backed by a file reader.
7181
7213
  * Drop-in replacement for createConfigLoader that reads TOML instead of JSON.
7182
7214
  * The caller must resolve globalConfigPath (e.g. expand '~' using process.env.HOME).
7183
7215
  */
7184
- declare function createTomlConfigLoader(reader: TomlFileReader, globalConfigPath: string, env: Record<string, string | undefined>): (projectRoot: string | null, environment: string) => EnvironmentConfig;
7216
+ declare function createTomlConfigLoader(reader: TomlFileReader, globalConfigPath: string, env: Record<string, string | undefined>): (projectRoot: string | null, environment?: string) => EnvironmentConfig;
7185
7217
 
7186
7218
  /**
7187
7219
  * Environment validation utilities
@@ -7341,5 +7373,5 @@ declare function retryWithBackoff<T>(fn: () => Promise<T>, isRetryable: (error:
7341
7373
  */
7342
7374
  declare const DISCOVERY_URL_PATH = "/discovery/kbs.json";
7343
7375
 
7344
- export { AUTHORABLE_MEDIA_TYPES, BRIDGED_CHANNELS, BusRequestError, CHANNEL_SCHEMAS, CONTEXT_FULL_WEIGHT, CONTEXT_PARTIAL_WEIGHT, ConfigurationError, ConflictError, DISCOVERY_URL_PATH, EMBEDDABLE_MEDIA_TYPES, EventBus, 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, annotationId, annotationUri, applyBodyOperations, assembleAnnotation, authCode, baseMediaType, baseUrl, buildContentCache, burstBuffer, busLog, busLogEnabled, busRequest, capabilitiesOf, cloneToken, createCircleSvg, createFragmentSelector, createPolygonSvg, createRectangleSvg, createTomlConfigLoader, decodeRepresentation, decodeWithCharset, deriveViews, didToAgent, email, entityType, errField, extensionForMediaType, extractBoundingBox, extractCharset, extractContext, findBestTextMatch, findBodyItem, 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, getStorageUri, getSvgSelector, getTargetSelector, getTargetSource, getTextPositionSelector, getTextQuoteSelector, googleCredential, hasTargetSelector, isAnnotationId, isArchived, isArray, isAssessment, isBodyResolved, isBoolean, isComment, isDefined, isDraft, isEventRelatedToAnnotation, isFunction, isHighlight, isNull, isNullish, isNumber, isObject, isReference, isResolvedReference, isResourceId, isStoredEvent, isString, isStubReference, isSupportedMediaType, isTag, isTransientFetchError, isUndefined, isValidEmail, isValidPlatformType, jobId, loadTomlConfig, mcpToken, mediaTypeForExtension, normalizeCoordinates, normalizeText, parseEnvironment, parseFragmentSelector, parseSvgSelector, reconcileSelector, refreshToken, resourceAnnotationUri, resourceId, resourceUri, retryWithBackoff, scaleSvgToNative, searchQuery, serializePerKey, setBusLogTraceIdProvider, softwareToAgent, textExtractionOf, userDID, userId, userToAgent, userToDid, validateData, validateEnvironment, validateSvgMarkup, verifyPosition };
7376
+ export { AUTHORABLE_MEDIA_TYPES, BRIDGED_CHANNELS, BusRequestError, CHANNEL_SCHEMAS, CONTEXT_FULL_WEIGHT, CONTEXT_PARTIAL_WEIGHT, ConfigurationError, ConflictError, DISCOVERY_URL_PATH, EMBEDDABLE_MEDIA_TYPES, EventBus, 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, annotationId, annotationUri, applyBodyOperations, assembleAnnotation, authCode, baseMediaType, baseUrl, buildContentCache, burstBuffer, busLog, busLogEnabled, busRequest, capabilitiesOf, cloneToken, createCircleSvg, createFragmentSelector, createPolygonSvg, createRectangleSvg, createTomlConfigLoader, decodeRepresentation, decodeWithCharset, deriveViews, didToAgent, email, entityType, errField, extensionForMediaType, extractBoundingBox, extractCharset, extractContext, findBestTextMatch, findBodyItem, 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, getStorageUri, getSvgSelector, getTargetSelector, getTargetSource, getTextPositionSelector, getTextQuoteSelector, googleCredential, hasTargetSelector, isAnnotationId, isArchived, isArray, isAssessment, isBodyResolved, isBoolean, isComment, isDefined, isDraft, isEventRelatedToAnnotation, isFunction, isHighlight, isNull, isNullish, isNumber, isObject, isReference, isResolvedReference, isResourceId, isStoredEvent, isString, isStubReference, isSupportedMediaType, isTag, isTransientFetchError, isUndefined, isValidEmail, isValidPlatformType, jobId, kbDid, loadTomlConfig, mcpToken, mediaTypeForExtension, normalizeCoordinates, normalizeText, parseEnvironment, parseFragmentSelector, parseSvgSelector, reconcileSelector, refreshToken, resourceAnnotationUri, resourceId, resourceUri, retryWithBackoff, scaleSvgToNative, searchQuery, serializePerKey, setBusLogTraceIdProvider, softwareToAgent, textExtractionOf, userDID, userId, userToAgent, userToDid, validateData, validateEnvironment, validateSvgMarkup, verifyPosition };
7345
7377
  export type { AccessToken, AnchorConfidence, AnchorMethod, AnchorRect, AnchorSelectors, AnchorStrategy, AnchoringModel, Annotation, AnnotationCategory, AnnotationId, AnnotationUri, AnthropicProviderConfig, AppConfig, AssembledAnnotation, AuthCode, BackendDownload, BackendServiceConfig, BaseUrl, BodyItem, BodyItemIdentity, BodyOperation, BoundingBox, Brand, BridgedChannel, BurstBufferOptions, BusOp, BusRequestErrorCode, BusRequestPrimitive, CloneToken, CollaboratorEntry, ConnectionState, ContentCache, ContentFormat, CreateAnnotationInternal, DatabaseServiceConfig, DiscoveredKB, DiscoveryDocument, Email, EmbeddingServiceConfig, EmittableChannel, EntityType, EntityTypeStats, Environment, EnvironmentConfig, EventBase, EventInput, EventMap, EventMetadata, EventName, EventOfType, EventQuery, EventSignature, FragmentSelector, FrontendServiceConfig, GatheredContext, GoogleAuthRequest, GoogleCredential, GraphConnection, GraphDatabaseType, GraphPath, GraphServiceConfig, GraphViews, HealthCheckResponse, IBackendOperations, IContentTransport, ITransport, InferenceProvidersConfig, JobId, JobType, ListUsersResponse, LlmSelectorInput, LocaleInfo, Logger, MCPToken, MatchQuality, McpServiceConfig, MediaTypeCapabilities, Motivation, OllamaProviderConfig, PdfCoordinate, PersistedEvent, PersistedEventType, PlatformType, Point, ProgressCallback, ProgressEvent, 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, SupportedMediaType, SvgSelector, TagCategory, TagSchema, TextExtraction, TextPosition, TextPositionSelector, TextQuoteSelector, 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
@@ -2002,6 +2002,9 @@ function isDefined(value) {
2002
2002
  }
2003
2003
 
2004
2004
  // src/did-utils.ts
2005
+ function kbDid(domain) {
2006
+ return `did:web:${domain}`;
2007
+ }
2005
2008
  function userToDid(user) {
2006
2009
  return `did:web:${user.domain}:users:${encodeURIComponent(user.email)}`;
2007
2010
  }
@@ -2103,20 +2106,27 @@ function requirePlatform(value, serviceName) {
2103
2106
  }
2104
2107
  function loadTomlConfig(projectRoot, environment, globalConfigPath, reader, env) {
2105
2108
  const projectConfigContent = projectRoot ? reader.readIfExists(`${projectRoot}/.semiont/config`) : null;
2106
- let projectName = "semiont-project";
2107
- let projectVersion;
2108
- let projectSite;
2109
- let projectEnvSection = {};
2110
- if (projectConfigContent) {
2111
- const projectConfig = parse(projectConfigContent);
2112
- projectName = projectConfig.project?.name ?? projectName;
2113
- projectVersion = projectConfig.project?.version;
2114
- projectSite = projectConfig.site;
2115
- projectEnvSection = projectConfig.environments?.[environment] ?? {};
2116
- }
2109
+ const projectConfig = projectConfigContent ? parse(projectConfigContent) : void 0;
2110
+ const projectName = projectConfig?.project?.name ?? "semiont-project";
2111
+ const projectVersion = projectConfig?.project?.version;
2112
+ const projectSite = projectConfig?.site;
2117
2113
  const globalContent = reader.readIfExists(globalConfigPath);
2118
2114
  const raw = globalContent ? parse(globalContent) : {};
2119
- const userEnvSection = raw.environments?.[environment] ?? {};
2115
+ const resolvedEnvironment = environment ?? env.SEMIONT_ENV ?? raw.defaults?.environment;
2116
+ if (!resolvedEnvironment) {
2117
+ throw new Error(
2118
+ "No environment selected: pass one explicitly, set SEMIONT_ENV, or declare `[defaults] environment` in ~/.semiontconfig."
2119
+ );
2120
+ }
2121
+ const projectHasSection = projectConfig?.environments != null && resolvedEnvironment in projectConfig.environments;
2122
+ const globalHasSection = raw.environments != null && resolvedEnvironment in raw.environments;
2123
+ if (!projectHasSection && !globalHasSection) {
2124
+ throw new Error(
2125
+ `Environment "${resolvedEnvironment}" is selected but no [environments.${resolvedEnvironment}] section exists in the project (.semiont/config) or global (~/.semiontconfig) config. Declare the section, or select an environment that exists.`
2126
+ );
2127
+ }
2128
+ const projectEnvSection = projectConfig?.environments?.[resolvedEnvironment] ?? {};
2129
+ const userEnvSection = raw.environments?.[resolvedEnvironment] ?? {};
2120
2130
  const envSection = deepMerge(
2121
2131
  projectEnvSection,
2122
2132
  userEnvSection
@@ -2139,7 +2149,7 @@ function loadTomlConfig(projectRoot, environment, globalConfigPath, reader, env)
2139
2149
  } else {
2140
2150
  if (!flatInference.type) {
2141
2151
  throw new Error(
2142
- `[environments.${environment}.inference] is missing 'type'. Add type = "anthropic" or use [inference.anthropic] sub-section.`
2152
+ `[environments.${resolvedEnvironment}.inference] is missing 'type'. Add type = "anthropic" or use [inference.anthropic] sub-section.`
2143
2153
  );
2144
2154
  }
2145
2155
  providerDefaults.apiKey = flatInference.apiKey;
@@ -2152,7 +2162,7 @@ function loadTomlConfig(projectRoot, environment, globalConfigPath, reader, env)
2152
2162
  } else {
2153
2163
  if (!flatInference.type) {
2154
2164
  throw new Error(
2155
- `[environments.${environment}.inference] is missing 'type'. Add type = "ollama" or use [inference.ollama] sub-section.`
2165
+ `[environments.${resolvedEnvironment}.inference] is missing 'type'. Add type = "ollama" or use [inference.ollama] sub-section.`
2156
2166
  );
2157
2167
  }
2158
2168
  providerDefaults.baseURL = flatInference.baseURL;
@@ -2318,7 +2328,7 @@ function loadTomlConfig(projectRoot, environment, globalConfigPath, reader, env)
2318
2328
  } : void 0,
2319
2329
  logLevel: resolved.logLevel,
2320
2330
  _metadata: {
2321
- environment,
2331
+ environment: resolvedEnvironment,
2322
2332
  projectRoot,
2323
2333
  projectName,
2324
2334
  projectVersion,
@@ -2462,6 +2472,6 @@ async function retryWithBackoff(fn, isRetryable, policy, onRetry) {
2462
2472
  // src/discovery.ts
2463
2473
  var DISCOVERY_URL_PATH = "/discovery/kbs.json";
2464
2474
 
2465
- export { AUTHORABLE_MEDIA_TYPES, BRIDGED_CHANNELS, BusRequestError, CHANNEL_SCHEMAS, CONTEXT_FULL_WEIGHT, CONTEXT_PARTIAL_WEIGHT, ConfigurationError, ConflictError, DISCOVERY_URL_PATH, EMBEDDABLE_MEDIA_TYPES, EventBus, 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, annotationId, annotationUri, applyBodyOperations, assembleAnnotation, authCode, baseMediaType, baseUrl, buildContentCache, burstBuffer, busLog, busLogEnabled, busRequest, capabilitiesOf, cloneToken, createCircleSvg, createFragmentSelector, createPolygonSvg, createRectangleSvg, createTomlConfigLoader, decodeRepresentation, decodeWithCharset, deriveViews, didToAgent, email, entityType, errField, extensionForMediaType, extractBoundingBox, extractCharset, extractContext, findBestTextMatch, findBodyItem, 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, getStorageUri, getSvgSelector, getTargetSelector, getTargetSource, getTextPositionSelector, getTextQuoteSelector, googleCredential, hasTargetSelector, isAnnotationId, isArchived, isArray, isAssessment, isBodyResolved, isBoolean, isComment, isDefined, isDraft, isEventRelatedToAnnotation, isFunction, isHighlight, isNull, isNullish, isNumber, isObject, isReference, isResolvedReference, isResourceId, isStoredEvent, isString, isStubReference, isSupportedMediaType, isTag, isTransientFetchError, isUndefined, isValidEmail, isValidPlatformType, jobId, loadTomlConfig, mcpToken, mediaTypeForExtension, normalizeCoordinates, normalizeText, parseEnvironment, parseFragmentSelector, parseSvgSelector, reconcileSelector, refreshToken, resourceAnnotationUri, resourceId, resourceUri, retryWithBackoff, scaleSvgToNative, searchQuery, serializePerKey, setBusLogTraceIdProvider, softwareToAgent, textExtractionOf, userDID, userId, userToAgent, userToDid, validateData, validateEnvironment, validateSvgMarkup, verifyPosition };
2475
+ export { AUTHORABLE_MEDIA_TYPES, BRIDGED_CHANNELS, BusRequestError, CHANNEL_SCHEMAS, CONTEXT_FULL_WEIGHT, CONTEXT_PARTIAL_WEIGHT, ConfigurationError, ConflictError, DISCOVERY_URL_PATH, EMBEDDABLE_MEDIA_TYPES, EventBus, 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, annotationId, annotationUri, applyBodyOperations, assembleAnnotation, authCode, baseMediaType, baseUrl, buildContentCache, burstBuffer, busLog, busLogEnabled, busRequest, capabilitiesOf, cloneToken, createCircleSvg, createFragmentSelector, createPolygonSvg, createRectangleSvg, createTomlConfigLoader, decodeRepresentation, decodeWithCharset, deriveViews, didToAgent, email, entityType, errField, extensionForMediaType, extractBoundingBox, extractCharset, extractContext, findBestTextMatch, findBodyItem, 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, getStorageUri, getSvgSelector, getTargetSelector, getTargetSource, getTextPositionSelector, getTextQuoteSelector, googleCredential, hasTargetSelector, isAnnotationId, isArchived, isArray, isAssessment, isBodyResolved, isBoolean, isComment, isDefined, isDraft, isEventRelatedToAnnotation, isFunction, isHighlight, isNull, isNullish, isNumber, isObject, isReference, isResolvedReference, isResourceId, isStoredEvent, isString, isStubReference, isSupportedMediaType, isTag, isTransientFetchError, isUndefined, isValidEmail, isValidPlatformType, jobId, kbDid, loadTomlConfig, mcpToken, mediaTypeForExtension, normalizeCoordinates, normalizeText, parseEnvironment, parseFragmentSelector, parseSvgSelector, reconcileSelector, refreshToken, resourceAnnotationUri, resourceId, resourceUri, retryWithBackoff, scaleSvgToNative, searchQuery, serializePerKey, setBusLogTraceIdProvider, softwareToAgent, textExtractionOf, userDID, userId, userToAgent, userToDid, validateData, validateEnvironment, validateSvgMarkup, verifyPosition };
2466
2476
  //# sourceMappingURL=index.js.map
2467
2477
  //# sourceMappingURL=index.js.map