@squidcloud/jira-client 1.0.496 → 1.0.498

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.
Files changed (64) hide show
  1. package/dist/connectors/jira/common/src/jira-types.d.ts +1 -28
  2. package/dist/internal-common/src/ai/system-openai-compatible.d.ts +35 -0
  3. package/dist/internal-common/src/public-types/ai-agent-integrations.public-types.d.ts +71 -0
  4. package/dist/internal-common/src/public-types/ai-agent.public-types.d.ts +1594 -0
  5. package/dist/internal-common/src/public-types/ai-common.public-types.d.ts +303 -0
  6. package/dist/internal-common/src/public-types/ai-function.public-types.d.ts +114 -0
  7. package/dist/internal-common/src/public-types/ai-knowledge-base.public-types.d.ts +2378 -0
  8. package/dist/internal-common/src/public-types/ai-query.public-types.d.ts +266 -0
  9. package/dist/internal-common/src/public-types/api-client.public-types.d.ts +9 -0
  10. package/dist/internal-common/src/public-types/api.public-types.d.ts +99 -0
  11. package/dist/internal-common/src/public-types/backend.public-types.d.ts +61 -0
  12. package/dist/internal-common/src/public-types/connector.public-types.d.ts +12 -0
  13. package/dist/internal-common/src/public-types/context.public-types.d.ts +83 -0
  14. package/dist/internal-common/src/public-types/document.public-types.d.ts +71 -0
  15. package/dist/internal-common/src/public-types/event.public-types.d.ts +18 -0
  16. package/dist/internal-common/src/public-types/extraction.public-types.d.ts +405 -0
  17. package/dist/internal-common/src/public-types/http-status.public-types.d.ts +415 -0
  18. package/dist/internal-common/src/public-types/integration.public-types.d.ts +65 -0
  19. package/dist/internal-common/src/public-types/job.public-types.d.ts +101 -0
  20. package/dist/internal-common/src/public-types/langgraph.public-types.d.ts +50 -0
  21. package/dist/internal-common/src/public-types/metadata-filter.public-types.d.ts +106 -0
  22. package/dist/internal-common/src/public-types/query.public-types.d.ts +149 -0
  23. package/dist/internal-common/src/public-types/scheduler.public-types.d.ts +43 -0
  24. package/dist/internal-common/src/public-types/schema.public-types.d.ts +88 -0
  25. package/dist/internal-common/src/public-types/secret.public-types.d.ts +82 -0
  26. package/dist/internal-common/src/public-types/socket.public-types.d.ts +4 -0
  27. package/dist/internal-common/src/public-types/source-code.public-types.d.ts +208 -0
  28. package/dist/internal-common/src/public-types/typescript.public-types.d.ts +20 -0
  29. package/dist/internal-common/src/public-types-backend/ai-agent.public-context.d.ts +101 -0
  30. package/dist/internal-common/src/public-types-backend/api-call.public-context.d.ts +30 -0
  31. package/dist/internal-common/src/public-types-backend/application.public-types.d.ts +94 -0
  32. package/dist/internal-common/src/public-types-backend/bundle-api.public-types.d.ts +199 -0
  33. package/dist/internal-common/src/public-types-backend/bundle-data.public-types.d.ts +18 -0
  34. package/dist/internal-common/src/public-types-backend/distributed-lock.public-context.d.ts +4 -0
  35. package/dist/internal-common/src/public-types-backend/graphql.public-context.d.ts +7 -0
  36. package/dist/internal-common/src/public-types-backend/langgraph.public-context.d.ts +16 -0
  37. package/dist/internal-common/src/public-types-backend/mcp.public-types.d.ts +55 -0
  38. package/dist/internal-common/src/public-types-backend/metric.public-context.d.ts +12 -0
  39. package/dist/internal-common/src/public-types-backend/mutation.public-context.d.ts +161 -0
  40. package/dist/internal-common/src/public-types-backend/native-query.public-context.d.ts +75 -0
  41. package/dist/internal-common/src/public-types-backend/query.public-context.d.ts +193 -0
  42. package/dist/internal-common/src/public-types-backend/storage.public-types.d.ts +15 -0
  43. package/dist/internal-common/src/public-types-backend/topic.public-context.d.ts +17 -0
  44. package/dist/internal-common/src/types/application.types.d.ts +98 -0
  45. package/dist/internal-common/src/types/backend-run.types.d.ts +55 -0
  46. package/dist/internal-common/src/types/bundle-data.types.d.ts +18 -0
  47. package/dist/internal-common/src/types/connector.types.d.ts +77 -0
  48. package/dist/internal-common/src/types/integrations/ai.types.d.ts +1 -0
  49. package/dist/internal-common/src/types/integrations/api.types.d.ts +76 -0
  50. package/dist/internal-common/src/types/integrations/auth.types.d.ts +1 -0
  51. package/dist/internal-common/src/types/integrations/database.types.d.ts +44 -0
  52. package/dist/internal-common/src/types/integrations/observability.types.d.ts +1 -0
  53. package/dist/internal-common/src/types/integrations/queue-types.d.ts +1 -0
  54. package/dist/internal-common/src/types/integrations/schemas.d.ts +6 -0
  55. package/dist/internal-common/src/types/integrations/storage-types.d.ts +22 -0
  56. package/dist/internal-common/src/types/langgraph.types.d.ts +1 -0
  57. package/dist/internal-common/src/types/openapi.types.d.ts +1 -0
  58. package/dist/internal-common/src/types/query.types.d.ts +21 -0
  59. package/dist/internal-common/src/types/secret.types.d.ts +7 -0
  60. package/dist/internal-common/src/types/time-units.d.ts +1 -0
  61. package/dist/internal-common/src/utils/object.d.ts +88 -0
  62. package/dist/internal-common/src/utils/serialization.d.ts +30 -0
  63. package/dist/internal-common/src/utils/worker-manager-utils.d.ts +2 -0
  64. package/package.json +2 -2
@@ -0,0 +1,2378 @@
1
+ import { AiChatModelSelection, AiReasoningEffort, ContextImageFailure, UpsertContextErrorCode, UpsertContextStatusError } from './ai-agent.public-types';
2
+ import { AiEmbeddingsModelSelection, AiRerankProvider } from './ai-common.public-types';
3
+ import { AiContextId, AiKnowledgeBaseId, AppId } from './communication.public-types';
4
+ import { DocumentExtractionMethod } from './extraction.public-types';
5
+ import { MetadataAndFilter, MetadataFieldFilter, MetadataOrFilter, MetadataSimpleFilter, MetadataValue, MetadataValueArray } from './metadata-filter.public-types';
6
+ /**
7
+ * The set of supported vector store backends for a knowledge base. The authoritative backend for a
8
+ * given KB is persisted on its record; reads/writes route through the matching vector provider.
9
+ * @category AI
10
+ */
11
+ export declare const VECTOR_DB_TYPES: readonly ["postgres", "mongoAtlas"];
12
+ /**
13
+ * A vector store backend identifier. See {@link VECTOR_DB_TYPES}.
14
+ * @category AI
15
+ */
16
+ export type VectorDbType = (typeof VECTOR_DB_TYPES)[number];
17
+ /**
18
+ * Represents an AI knowledge base that can be attached to an AI agent.
19
+ * @category AI
20
+ */
21
+ export interface AiKnowledgeBase {
22
+ /** The unique identifier of the knowledge base.*/
23
+ id: AiKnowledgeBaseId;
24
+ /** The app id that the knowledge base belongs to. */
25
+ appId: AppId;
26
+ /** The user's description of the knowledge base */
27
+ description: string;
28
+ /** A set of predefined metadata fields for the knowledge base that can be used for filtering.*/
29
+ metadataFields: Array<AiKnowledgeBaseMetadataField>;
30
+ /** The embedding model that should be used for this knowledge base.*/
31
+ embeddingModel: AiEmbeddingsModelSelection;
32
+ /** The model name that should be used when asking questions of this knowledge base. */
33
+ chatModel: AiChatModelSelection;
34
+ /**
35
+ * The vector store backend this knowledge base reads/writes from. Set at creation (defaulting to
36
+ * the server's `SQUID_DEFAULT_VECTOR_DB_TYPE`, otherwise `'postgres'`) and immutable thereafter.
37
+ * Optional on the read type for backwards compatibility with older records.
38
+ */
39
+ vectorDbType?: VectorDbType;
40
+ /**
41
+ * Opt-in GraphRAG configuration. Only honored for `vectorDbType:'mongoAtlas'` KBs; enables
42
+ * per-chunk entity/relationship extraction at ingest and `searchMode:'graph'` at query time.
43
+ */
44
+ graphRag?: AiKnowledgeBaseGraphConfig;
45
+ /**
46
+ * Default RAG strategy for newly ingested contexts; a per-request `options.ragType` overrides it.
47
+ * Omitted ⇒ the server default (`'contextual'`). Changing it affects future ingests only — existing
48
+ * chunks are not re-processed.
49
+ */
50
+ ragType?: AiRagType;
51
+ /**
52
+ * Lifetime LLM usage of the contextual-RAG situating-blurb calls on this KB (server-managed; ignored
53
+ * on upsert). Persisted on the KB itself so the record survives Core restarts and covers any vector
54
+ * store. Under the combined-ingest strategy this stays ≈0 — growth is a visible fallback-rate signal.
55
+ */
56
+ contextualIngestUsage?: KnowledgeBaseGraphUsage;
57
+ /**
58
+ * Per-caller access control over retrieval. Omitted ⇒ `'none'`: stored scopes are ignored and every
59
+ * caller sees every chunk.
60
+ */
61
+ accessControl?: AiKnowledgeBaseAccessControl;
62
+ /** The timestamp the knowledge base was last updated */
63
+ updatedAt: Date;
64
+ }
65
+ /**
66
+ * The access-control modes a knowledge base can be in. See {@link AiKnowledgeBaseAccessControl}.
67
+ * @category AI
68
+ */
69
+ export declare const AI_KB_ACCESS_CONTROL_MODES: readonly ["none", "enforced"];
70
+ /**
71
+ * A knowledge base access-control mode. See {@link AI_KB_ACCESS_CONTROL_MODES}.
72
+ * @category AI
73
+ */
74
+ export type AiKnowledgeBaseAccessControlMode = (typeof AI_KB_ACCESS_CONTROL_MODES)[number];
75
+ /**
76
+ * Restricts what a search returns to the content its caller is entitled to.
77
+ *
78
+ * Under `'enforced'`, every chunk carries the access scopes of the context it came from, the caller is
79
+ * resolved to the scopes they hold, and the two are intersected inside the vector query — so a caller
80
+ * never retrieves a chunk they hold no scope for. A chunk stamped as public is visible to everyone; a
81
+ * chunk with no scopes at all (ingested before access control was enabled) is visible to no one.
82
+ *
83
+ * Enforcement covers retrieval channels that can apply the scope predicate. The raw-text scan (`grep`)
84
+ * and knowledge-graph (`queryGraph`, `searchMode: 'graph'`) channels read stores that carry no scopes,
85
+ * so an enforced knowledge base refuses them rather than answering unfiltered.
86
+ *
87
+ * Mutable, but enabling it on a populated knowledge base hides everything already ingested until those
88
+ * contexts are re-ingested with scopes.
89
+ *
90
+ * @category AI
91
+ */
92
+ export interface AiKnowledgeBaseAccessControl {
93
+ /** `'none'` (the default) ignores stored scopes entirely; `'enforced'` intersects them per caller. */
94
+ mode: AiKnowledgeBaseAccessControlMode;
95
+ /**
96
+ * The backend function that resolves a caller into the access scopes they hold, as
97
+ * `'ServiceName:functionName'`. It runs once per search, receives a `ResolveKbScopesContext` and
98
+ * returns the scopes as an array of strings. Required under `'enforced'`.
99
+ *
100
+ * An `'enforced'` knowledge base whose function is not deployed fails every search rather than
101
+ * falling back to an unfiltered one.
102
+ *
103
+ * @pattern ^[^:]+:[^:]+$
104
+ */
105
+ scopeResolver?: string;
106
+ }
107
+ /**
108
+ * Represents a field in an AI knowledge base metadata.
109
+ */
110
+ export interface AiKnowledgeBaseMetadataField {
111
+ /** The name of field.*/
112
+ name: string;
113
+ /**
114
+ * The field data type - used for validation and filtering. `date` values are normalized to integer
115
+ * epoch milliseconds at write time so range filters (`$gt`/`$lt`) work across vector store backends.
116
+ * `array` is not yet supported and is rejected at knowledge-base upsert time.
117
+ */
118
+ dataType: 'string' | 'number' | 'boolean' | 'date' | 'array';
119
+ /** Indicates if the field is required for knowledge base entries.*/
120
+ required: boolean;
121
+ /**
122
+ * In case that the field is required and not provided when uploaded to the knowledge base,
123
+ * this description will be used for extracting the value from the document.
124
+ * Also, it will be used for auto filtering when a prompt is sent to an AI agent.
125
+ */
126
+ description?: string;
127
+ /**
128
+ * True when {@link description} was AI-generated (via `generateMetadataFieldDescriptions`). Undefined or
129
+ * false means the description was authored by a human or has not been generated yet; it clears back to
130
+ * false once a human edits the description.
131
+ */
132
+ descriptionGeneratedByAi?: boolean;
133
+ /**
134
+ * Whether the LLM extraction pass may fill this field when it is missing. Defaults to `true` when
135
+ * undefined, so knowledge bases created before this flag existed keep their behavior. Set to `false`
136
+ * for fields whose value the caller supplies deterministically (e.g. folder-derived path metadata): a
137
+ * missing value then stays absent rather than being guessed from the document.
138
+ */
139
+ llmExtraction?: boolean;
140
+ }
141
+ /**
142
+ * A record of metadata key-value pairs for AI context, where values are primitive types or undefined.
143
+ * @category AI
144
+ */
145
+ export type AiContextMetadata = Record<string, AiContextMetadataValue>;
146
+ /**
147
+ * @category AI
148
+ * @deprecated Use {@link MetadataValue} from `metadata-filter.public-types` instead.
149
+ */
150
+ export type AiContextMetadataValue = MetadataValue;
151
+ /**
152
+ * @category AI
153
+ * @deprecated Use {@link MetadataValueArray} from `metadata-filter.public-types` instead.
154
+ */
155
+ export type AiContextMetadataValueArray = MetadataValueArray;
156
+ /**
157
+ * @category AI
158
+ * @deprecated Use {@link MetadataSimpleFilter} from `metadata-filter.public-types` instead.
159
+ */
160
+ export type AiContextMetadataSimpleFilter = MetadataSimpleFilter;
161
+ /**
162
+ * A filter for AI context metadata based on field-specific conditions or values.
163
+ * @category AI
164
+ * @deprecated Use {@link MetadataFieldFilter} from `metadata-filter.public-types` instead.
165
+ */
166
+ export type AiContextMetadataFieldFilter = MetadataFieldFilter;
167
+ /**
168
+ * A filter combining multiple AI context metadata filters with a logical AND operation.
169
+ * @category AI
170
+ * @deprecated Use {@link MetadataAndFilter} from `metadata-filter.public-types` instead.
171
+ */
172
+ export type AiContextMetadataAndFilter = MetadataAndFilter;
173
+ /**
174
+ * A filter combining multiple AI context metadata filters with a logical OR operation.
175
+ * @category AI
176
+ * @deprecated Use {@link MetadataOrFilter} from `metadata-filter.public-types` instead.
177
+ */
178
+ export type AiContextMetadataOrFilter = MetadataOrFilter;
179
+ /**
180
+ * Retrieval mode for a knowledge-base search.
181
+ * - `'vector'`: dense-only similarity.
182
+ * - `'hybrid'`: native fusion of dense + lexical (only distinct on backends with native fusion, e.g.
183
+ * Mongo Atlas; on pgvector it degrades to dense + a legacy app-side keyword fallback).
184
+ * - `'keyword'`: embedding-free lexical retrieval; the mechanism is backend-specific — native Lucene BM25
185
+ * on Mongo Atlas (ranked, term-optional: a partial-term query still matches), and a boolean substring
186
+ * filter on pgvector (every term must appear literally; unranked).
187
+ * - `'graph'`: GraphRAG retrieval — seeds entities via vector search, expands relationships via graph
188
+ * traversal, then maps entities back to their source chunks, RRF-fused with a standard hybrid search.
189
+ * Only available on `vectorDbType:'mongoAtlas'` KBs with `graphRag.enabled`; tuned via
190
+ * {@link AiKnowledgeBaseGraphSearchOptions}. This is the DEFAULT mode when a search omits `searchMode`
191
+ * on a `graphRag.enabled` KB (non-graph KBs default to `'hybrid'`).
192
+ * @category AI
193
+ */
194
+ export type AiKnowledgeBaseSearchMode = 'vector' | 'hybrid' | 'keyword' | 'graph';
195
+ /**
196
+ * Fine-grained options for `searchMode: 'graph'` retrieval (GraphRAG). The graph channel is always
197
+ * RRF-fused with a standard hybrid search; themes-level "global" answering has moved to the
198
+ * `globalSummary` op of the `queryKnowledgeGraph` surface.
199
+ * @category AI
200
+ */
201
+ export interface AiKnowledgeBaseGraphSearchOptions {
202
+ /** Entities seeded via vector search before graph expansion. Default 8, max 25. */
203
+ seedLimit?: number;
204
+ /** Number of hops to expand from each seed (traversal depth + 1). Default 2, max 3. */
205
+ maxHops?: number;
206
+ /** When true, attach the traversed {@link AiKnowledgeBaseGraphContext} to the response. Default false. */
207
+ includeGraphContext?: boolean;
208
+ }
209
+ /**
210
+ * Per-knowledge-base GraphRAG configuration. Opt-in and mutable (unlike `embeddingModel`/`vectorDbType`);
211
+ * only honored for `vectorDbType:'mongoAtlas'` KBs. Enabling it on a KB that already has content backfills
212
+ * the graph automatically (a debounced structural build runs once the KB goes quiet); the `rebuildGraph`
213
+ * endpoint remains available for an immediate or full rebuild.
214
+ * @category AI
215
+ */
216
+ export interface AiKnowledgeBaseGraphConfig {
217
+ /** When true, ingestion extracts an entity/relationship graph and `searchMode:'graph'` becomes available. */
218
+ enabled: boolean;
219
+ /** Chat model used for per-chunk entity/relationship extraction. Defaults to the server's graph model. */
220
+ extractionModel?: AiChatModelSelection;
221
+ /** Optional domain taxonomy hint (entity types) injected into the extraction prompt. */
222
+ entityTypes?: string[];
223
+ /**
224
+ * Quiet window (milliseconds) after the last graph activity before the sweep auto-builds the
225
+ * structure. Must be a positive integer, and is floored at 3 seconds — a shorter window is not
226
+ * servable. Defaults to the server's window (5 minutes); the sweep cadence (1 minute) bounds how
227
+ * promptly an elapsed window is picked up.
228
+ */
229
+ autoBuildDebounceMs?: number;
230
+ /**
231
+ * When true, the sweep starts no automatic build for this KB, entity resolution included: activity keeps
232
+ * arming the build, and the first quiet window after the flag is cleared runs it. `rebuildGraph` stays
233
+ * available. To hold only the structural build, use `structuralBuildSchedule`. Defaults to false.
234
+ */
235
+ autoBuildPaused?: boolean;
236
+ /**
237
+ * When the sweep may start an automatic structural build: `'debounced'` (one quiet window after activity),
238
+ * `'off'` (manual `rebuildGraph` only) or a 5-field cron expression. Entity resolution keeps running
239
+ * either way. Omitted ⇒ the server's default, `'debounced'` unless the deployment sets one.
240
+ */
241
+ structuralBuildSchedule?: string;
242
+ /** IANA time zone of a cron `structuralBuildSchedule`, e.g. `'America/Los_Angeles'`. Omitted ⇒ the server's default (UTC). */
243
+ structuralBuildTimeZone?: string;
244
+ /**
245
+ * How long after a cron slot its structural build may still start (milliseconds); past it, the build waits for
246
+ * the next slot. Must be a positive integer. Omitted ⇒ the server's default (3 hours).
247
+ */
248
+ structuralBuildCatchUpMs?: number;
249
+ /** Concept-layer (facet taxonomy) configuration. Omitted ⇒ `facets: 'auto'`. */
250
+ concepts?: AiKnowledgeBaseGraphConceptsConfig;
251
+ }
252
+ /**
253
+ * Configuration of the graph's concept layer (Layered KB Graph L3 facets — deterministic trees built
254
+ * from metadata values at rebuild).
255
+ * @category AI
256
+ */
257
+ export interface AiKnowledgeBaseGraphConceptsConfig {
258
+ /**
259
+ * Which metadata fields become value facets (flat sets of categorical values). `'auto'` (the default)
260
+ * profiles the KB's context metadata and selects the categorical fields; an explicit list overrides
261
+ * auto-selection (fields still subject to the hard cardinality cap); `[]` disables value facets.
262
+ */
263
+ facets?: string[] | 'auto';
264
+ /**
265
+ * Explicit path facets — deterministic trees split from a hierarchical path field (e.g. a folder path)
266
+ * rather than LLM-grouped. Independent of {@link facets}: a path facet always builds when its field has
267
+ * values, coexists with auto value-facet selection (reserved outside the facet cap), and is exempt from
268
+ * the categorical eligibility gates (a path field is near-unique by leaf). Omitted/`[]` ⇒ no path facets.
269
+ */
270
+ pathFacets?: AiKnowledgeBaseGraphPathFacetConfig[];
271
+ }
272
+ /**
273
+ * The canonical folder-path metadata field: a POSIX-separated path relative to the upload root, no
274
+ * leading/trailing slash, case-preserved. Stamped by folder-aware ingestion (console folder upload,
275
+ * SDK clients). Register it under `graphRag.concepts.pathFacets` (`[{ field: 'folderPath', type: 'path' }]`)
276
+ * to build a navigable folder tree in the graph — the field name is never treated specially on its own.
277
+ * @category AI
278
+ */
279
+ export declare const FOLDER_PATH_METADATA_FIELD_NAME = "folderPath";
280
+ /**
281
+ * The canonical file-name metadata field: the source file's name, stamped by file ingestion (console
282
+ * upload, document connectors). Metadata extraction reads it, beside {@link FOLDER_PATH_METADATA_FIELD_NAME},
283
+ * as evidence about the document.
284
+ * @category AI
285
+ */
286
+ export declare const FILE_NAME_METADATA_FIELD_NAME = "filename";
287
+ /**
288
+ * A path facet: a deterministic tree built by splitting a hierarchical path field on {@link separator}.
289
+ * Interior nodes are the path prefixes; scoping a search to one node matches that folder and everything
290
+ * beneath it. Exempt from the near-unique/cardinality eligibility gates (those judge flat value sets).
291
+ * Declared under {@link AiKnowledgeBaseGraphConceptsConfig.pathFacets}.
292
+ * @category AI
293
+ */
294
+ export interface AiKnowledgeBaseGraphPathFacetConfig {
295
+ /** The metadata field holding the path values (e.g. `'folderPath'`). */
296
+ field: string;
297
+ /** Marks this as a path facet. */
298
+ type: 'path';
299
+ /** Path segment separator. Defaults to `'/'`. */
300
+ separator?: string;
301
+ }
302
+ /**
303
+ * The canonical declaration of {@link FOLDER_PATH_METADATA_FIELD_NAME}, shared by every writer that
304
+ * declares it on a knowledge base. `llmExtraction` is off, so a missing folder path stays absent
305
+ * instead of being guessed from document content.
306
+ * @category AI
307
+ */
308
+ export declare const FOLDER_PATH_METADATA_FIELD: AiKnowledgeBaseMetadataField;
309
+ /** A single entity surfaced in a graph search's {@link AiKnowledgeBaseGraphContext}. @category AI */
310
+ export interface AiKnowledgeBaseGraphContextEntity {
311
+ /** Canonical display name of the entity. */
312
+ name: string;
313
+ /** Entity type (e.g. PERSON, ORGANIZATION). */
314
+ type: string;
315
+ /** Compacted description of the entity. */
316
+ description: string;
317
+ /** Traversal relevance score in [0,1]. */
318
+ score: number;
319
+ }
320
+ /** A single relationship surfaced in a graph search's {@link AiKnowledgeBaseGraphContext}. @category AI */
321
+ export interface AiKnowledgeBaseGraphContextRelationship {
322
+ /** Source entity display name. */
323
+ source: string;
324
+ /** Target entity display name. */
325
+ target: string;
326
+ /** Relationship label (short verb phrase). */
327
+ type: string;
328
+ /** Optional description of the relationship. */
329
+ description?: string;
330
+ }
331
+ /**
332
+ * The subgraph traversed to answer a `searchMode:'graph'` query. Additive/optional — returned only when
333
+ * `graphOptions.includeGraphContext` is set; clients that ignore it are unaffected.
334
+ * @category AI
335
+ */
336
+ export interface AiKnowledgeBaseGraphContext {
337
+ /** Entities reached by the traversal, sorted by score descending. */
338
+ entities: Array<AiKnowledgeBaseGraphContextEntity>;
339
+ /** Outgoing relationships between reached entities. */
340
+ relationships: Array<AiKnowledgeBaseGraphContextRelationship>;
341
+ }
342
+ /**
343
+ * The options for the AI knowledgebase search method.
344
+ * @category AI
345
+ */
346
+ export interface AiKnowledgeBaseChatOptions {
347
+ /** A set of filters that will limit the context the AI can access. */
348
+ contextMetadataFilter?: AiContextMetadataFilter;
349
+ /** Whether to include references from the source context in the response. Default to false. */
350
+ includeReference?: boolean;
351
+ /** Include metadata in the context */
352
+ includeMetadata?: boolean;
353
+ /** Which provider's reranker to use for reranking the context. Defaults to 'cohere'. */
354
+ rerankProvider?: AiRerankProvider;
355
+ /**
356
+ * Minimum reranker relevance score a chunk must reach to stay once at least 10 chunks are already kept.
357
+ * Defaults to 0.2. Lets an eval tune the drop threshold per reranker, whose score ranges differ.
358
+ */
359
+ rerankScoreThreshold?: number;
360
+ /** The maximum number of results to return. Defaults to 30 */
361
+ limit?: number;
362
+ /** How many chunks to look over. Defaults to 100 */
363
+ chunkLimit?: number;
364
+ /** Which chat model to use when asking the question */
365
+ chatModel?: AiChatModelSelection;
366
+ /**
367
+ * Selects how the underlying vector store generates candidates:
368
+ * - `'hybrid'` (default): fuses dense vector and keyword candidates when the backend supports it
369
+ * (Mongo Atlas uses `$rankFusion`; backends without native fusion fall back to dense-only with
370
+ * the legacy app-side keyword fallback).
371
+ * - `'vector'`: dense-only — skips native fusion even on backends that support it.
372
+ * - `'keyword'`: embedding-free lexical retrieval; the mechanism is backend-specific. On Mongo Atlas it
373
+ * is native Lucene BM25 (`$search`): results are ranked by relevance and term-optional — a partial-term
374
+ * query still returns its best matches. On Postgres it is a boolean substring filter (`ILIKE ALL`):
375
+ * every whitespace-separated term must appear in a chunk as a literal, case-insensitive substring,
376
+ * matched independently (order, adjacency and relevance are NOT considered), so results are unranked and
377
+ * for broad terms the returned top-k is arbitrary. Both skip embedding, dense, reranking and the
378
+ * app-side keyword fallback. Lets an agent (or an eval) target exact tokens — identifiers, names, codes
379
+ * — that dense retrieval tends to miss.
380
+ *
381
+ * Intended to let A/B evaluations compare dense-only, hybrid and boolean-keyword candidate generation
382
+ * on the same backend.
383
+ *
384
+ * When omitted, the default is `'graph'` (RRF-fused GraphRAG) on a `graphRag.enabled` KB and
385
+ * `'hybrid'` otherwise. See {@link AiKnowledgeBaseSearchMode}.
386
+ */
387
+ searchMode?: AiKnowledgeBaseSearchMode;
388
+ /**
389
+ * Per-pipeline weights for native hybrid fusion (Mongo `$rankFusion.combination.weights`). Only
390
+ * applies when `searchMode` is `'hybrid'` on a backend with native fusion; ignored otherwise.
391
+ * Each value must be a finite non-negative number; an omitted key defaults to `1` (the MongoDB
392
+ * default). Useful for A/B evaluating dense-vs-keyword weighting on the same backend.
393
+ */
394
+ hybridWeights?: AiHybridSearchWeights;
395
+ /** Tuning for `searchMode:'graph'` (GraphRAG). Ignored for other search modes. */
396
+ graphOptions?: AiKnowledgeBaseGraphSearchOptions;
397
+ /**
398
+ * Scopes the search to the documents under one concept of the KB's graph (Layered KB Graph).
399
+ * Composes with every `searchMode` and with `contextMetadataFilter`. Requires `graphRag.enabled`.
400
+ */
401
+ graphFilter?: AiKnowledgeBaseGraphFilter;
402
+ }
403
+ /**
404
+ * Graph scope for a knowledge-base search: restricts results to the documents under one concept.
405
+ * @category AI
406
+ */
407
+ export interface AiKnowledgeBaseGraphFilter {
408
+ /**
409
+ * The concept to scope to: a facet nodeId (`facet_…` — exact, the only persistable concept handles)
410
+ * or a concept name, resolved server-side (exact → alias → similarity). Facet scopes filter by exact
411
+ * metadata membership; topic scopes are thematic (recall-safe but fuzzy — docs outside the theme's
412
+ * current membership are excluded). An unresolvable ref fails with `CONCEPT_NOT_FOUND` and the
413
+ * nearest matching concept names.
414
+ */
415
+ underConcept: string;
416
+ }
417
+ /**
418
+ * Per-pipeline weights for native hybrid fusion. Sub-keys mirror the `$rankFusion` pipeline names.
419
+ * @category AI
420
+ */
421
+ export interface AiHybridSearchWeights {
422
+ /** Weight for the dense vector sub-pipeline. Defaults to `1`. */
423
+ vector?: number;
424
+ /** Weight for the BM25 keyword sub-pipeline. Defaults to `1`. */
425
+ keyword?: number;
426
+ }
427
+ /**
428
+ * Segment-safe subtree match on a hierarchical string field such as a folder path: matches when the
429
+ * field's value is exactly the operand, or begins with the operand followed by a `/` separator. Unlike
430
+ * a raw character prefix, `{ folderPath: { $underPath: 'reports/2023' } }` matches `reports/2023` and
431
+ * `reports/2023/q1/deck` but never the lexical sibling `reports/2023 drafts` — the separator supplies
432
+ * the segment boundary, so subtree scoping never leaks into a sibling that merely shares a prefix.
433
+ *
434
+ * The operand is normalized by stripping any leading and trailing `/` before matching, so a caller that
435
+ * writes `reports/2023/` addresses the same subtree as `reports/2023`. The empty operand matches every
436
+ * document that HAS the field. Matching is case-sensitive.
437
+ *
438
+ * ### Canonical `folderPath` contract
439
+ * The value this operator is designed for — a document's `folderPath` metadata — is written and matched
440
+ * under one canonical form so filters, subtree scoping and the knowledge-graph path facet never
441
+ * fragment by how a value was authored:
442
+ * - POSIX `/` separators; no leading or trailing slash.
443
+ * - The empty string denotes the upload root (a file directly under it), never `undefined`.
444
+ * - Case-preserved on write and matched case-sensitively (`Reports` and `reports` are distinct folders).
445
+ * - NFC-normalized on write, so canonically-equivalent Unicode spellings compare equal.
446
+ *
447
+ * `folderPath` is an ordinary metadata key (not reserved); this operator is the tool for scoping to it.
448
+ * `$underPath` is knowledge-base-only: it is deliberately absent from the shared {@link MetadataSimpleFilter}
449
+ * that metrics and matchmaking consume (they reject unknown operators at runtime).
450
+ * @category AI
451
+ */
452
+ export interface MetadataUnderPathFilter {
453
+ /** The subtree root the field's value must equal or sit under (leading/trailing `/` are ignored). */
454
+ $underPath: string;
455
+ }
456
+ /** A knowledge-base single-field operator: the shared {@link MetadataSimpleFilter} operators plus `$underPath`. */
457
+ export type AiKbMetadataSimpleFilter = MetadataSimpleFilter | MetadataUnderPathFilter;
458
+ /** A knowledge-base field filter: field names mapped to a {@link AiKbMetadataSimpleFilter} or a direct scalar. */
459
+ export interface AiKbMetadataFieldFilter {
460
+ /** A record where keys are field names and values are either operator objects or direct scalar values. */
461
+ [field: string]: AiKbMetadataSimpleFilter | MetadataValue;
462
+ }
463
+ /** Knowledge-base filters combined with logical AND; each branch may itself use `$underPath`. */
464
+ export interface AiKbMetadataAndFilter {
465
+ /** An array of filters that must all be true for the condition to pass. */
466
+ $and: AiContextMetadataFilter[];
467
+ }
468
+ /** Knowledge-base filters combined with logical OR; each branch may itself use `$underPath`. */
469
+ export interface AiKbMetadataOrFilter {
470
+ /** An array of filters where at least one must be true for the condition to pass. */
471
+ $or: AiContextMetadataFilter[];
472
+ }
473
+ /**
474
+ * The knowledge-base context metadata filter: the shared MongoDB-style filter syntax extended with the
475
+ * KB-only `$underPath` operator (see {@link MetadataUnderPathFilter}). Other subsystems (metrics,
476
+ * matchmaking) use the plain `MetadataFilter`, which omits `$underPath`.
477
+ * @category AI
478
+ */
479
+ export type AiContextMetadataFilter = AiKbMetadataFieldFilter | AiKbMetadataAndFilter | AiKbMetadataOrFilter;
480
+ /**
481
+ * Represents an AI knowledge base's context entry with metadata and content.
482
+ * @category AI
483
+ */
484
+ export interface AiKnowledgeBaseContext {
485
+ /** The unique identifier of the context entry. */
486
+ id: string;
487
+ /** The application id of the context entry */
488
+ appId: AppId;
489
+ /** The knowledge base id of the context entry */
490
+ knowledgeBaseId: AiKnowledgeBaseId;
491
+ /** The date and time the context was created. */
492
+ createdAt: Date;
493
+ /** The date and time the context was last updated. */
494
+ updatedAt: Date;
495
+ /** The type of context (e.g., 'text' or 'file'). */
496
+ type: AiKnowledgeBaseContextType;
497
+ /** A title describing the context content. */
498
+ title: string;
499
+ /** The text content of the context. */
500
+ text: string;
501
+ /** Indicates whether the context is a preview; defaults to false. */
502
+ preview: boolean;
503
+ /** The size of the context content in bytes. */
504
+ sizeBytes: number;
505
+ /** Metadata associated with the context. */
506
+ metadata: AiContextMetadata;
507
+ /**
508
+ * Names of metadata fields whose stored values were machine-extracted from the content
509
+ * (driven by the knowledge base's `metadataFields` schema, plus the reserved `lastModified` key
510
+ * every knowledge base derives from the document container) rather than user-supplied.
511
+ * On re-upsert/replay, extracted values count as not-supplied (re-extracted fresh) while
512
+ * user-supplied values are preserved; consumers can also use this to caveat extracted values.
513
+ */
514
+ autoExtractedMetadataFields?: string[];
515
+ /**
516
+ * SHA-256 (hex) of the source bytes (file) or UTF-8 text this context was ingested from. Powers
517
+ * content-level dedup on upsert. Absent on legacy contexts ingested before hashing was introduced.
518
+ */
519
+ contentHash?: string;
520
+ /**
521
+ * The options the context was ingested with, replayed when it is reupserted. Absent on contexts that
522
+ * carry none; their reupsert takes the defaults.
523
+ */
524
+ requestConfig?: AiKnowledgeBaseContextRequestConfig;
525
+ }
526
+ /**
527
+ * The ingestion request's options only. Everything else a reupsert needs lives on the context itself —
528
+ * its text or stored file, title, metadata and access scopes — where it can change after ingestion.
529
+ * @category AI
530
+ */
531
+ export type AiKnowledgeBaseContextRequestConfig = Omit<AiKnowledgeBaseTextContextRequest, 'text' | 'title' | 'metadata' | 'scopes'> | Omit<AiKnowledgeBaseFileContextRequest, 'metadata' | 'scopes'>;
532
+ /**
533
+ * @category AI
534
+ */
535
+ export type AiKnowledgeBaseContextType = 'text' | 'file';
536
+ /**
537
+ * @category AI
538
+ */
539
+ export type AiKnowledgeBaseContextRequest = AiKnowledgeBaseTextContextRequest | AiKnowledgeBaseFileContextRequest;
540
+ /**
541
+ * Base fields shared by all knowledge base context requests.
542
+ * @category AI
543
+ */
544
+ export interface BaseAiKnowledgeBaseContextRequest {
545
+ /** The unique identifier of the context item. */
546
+ contextId?: string;
547
+ /** The type of the context content. */
548
+ type: AiKnowledgeBaseContextType;
549
+ /** Optional metadata associated with the context item. */
550
+ metadata?: AiContextMetadata;
551
+ /**
552
+ * Access scopes granting read access to this context, stamped onto every chunk it produces. Only
553
+ * meaningful on a knowledge base with `accessControl.mode: 'enforced'`, where a caller retrieves the
554
+ * context only if they hold at least one of these scopes.
555
+ *
556
+ * Supplied here rather than through a follow-up call so a restricted context is never briefly
557
+ * readable by everyone between being indexed and being scoped. Omitted on a re-ingest keeps whatever
558
+ * scopes the context already had; an empty array makes it visible to every caller.
559
+ *
560
+ * Scopes are opaque strings the resolver and the ingest side agree on. The `__` prefix is reserved.
561
+ */
562
+ scopes?: Array<string>;
563
+ }
564
+ /**
565
+ * Base options for upserting text content into the AI agent's context.
566
+ * @category AI
567
+ */
568
+ export interface AiKnowledgeBaseContextTextOptions extends BaseAiKnowledgeBaseContextOptions {
569
+ }
570
+ /**
571
+ * Base options for upserting file content into the AI agent's context.
572
+ * @category AI
573
+ */
574
+ export interface AiKnowledgeBaseContextFileOptions extends BaseAiKnowledgeBaseContextOptions {
575
+ }
576
+ /**
577
+ * Hint about the format of a text context payload.
578
+ *
579
+ * - `auto`: detect the format from the content (default).
580
+ * - `markdown`: treat the text as Markdown — image references will be extracted if `extractImages` is true.
581
+ * - `html`: treat the text as HTML — `<img>` tags will be extracted if `extractImages` is true.
582
+ * - `plain`: treat the text as plain text — no image extraction is performed even if `extractImages` is true.
583
+ *
584
+ * @category AI
585
+ */
586
+ export type AiKnowledgeBaseTextFormat = 'auto' | 'markdown' | 'html' | 'plain';
587
+ /**
588
+ * Request structure for adding text-based context to an AI agent.
589
+ * @category AI
590
+ */
591
+ export interface AiKnowledgeBaseTextContextRequest extends BaseAiKnowledgeBaseContextRequest {
592
+ /**
593
+ * The id of the context. Optional: when omitted, the server generates one and rejects the upload if
594
+ * another context in the knowledge base already holds identical content (content-level dedup). Provide
595
+ * an explicit id to address a specific context — that overwrites it unconditionally and allows duplicate
596
+ * content across different ids.
597
+ */
598
+ contextId?: AiContextId;
599
+ /** Specifies the context type as 'text'. */
600
+ type: 'text';
601
+ /** A title for the text context. */
602
+ title: string;
603
+ /** The text content to add to the context. */
604
+ text: string;
605
+ /**
606
+ * Hint about the format of the text. If omitted (or `'auto'`), the format is sniffed from the content.
607
+ * Only `'markdown'` and `'html'` (or `'auto'` with content that looks like markdown/HTML) participate in
608
+ * image extraction when `extractImages` is true.
609
+ */
610
+ format?: AiKnowledgeBaseTextFormat;
611
+ /**
612
+ * Whether to extract images embedded in markdown/HTML text. Defaults to FALSE — deliberately the
613
+ * opposite of {@link AiKnowledgeBaseFileContextRequest.extractImages}. A pasted blob's inline images
614
+ * are usually layout chrome, whereas an uploaded document's images are part of its content. Uploading
615
+ * the same markdown as a `.md` file is therefore the file case, and defaults to images ON.
616
+ *
617
+ * When true and the text is detected as (or declared to be) markdown/HTML, image references inside the
618
+ * text (`![alt](url)` or `<img src="...">`) are fetched, stored, and have descriptions generated
619
+ * just like images extracted from a PDF.
620
+ *
621
+ * Has no effect for plain text.
622
+ */
623
+ extractImages?: boolean;
624
+ /** Minimum width/height (in pixels) for an image to be kept. Smaller images are skipped. */
625
+ imageMinSizePixels?: number;
626
+ /** The AI model to use for generating image descriptions, if specified. */
627
+ imageExtractionModel?: AiChatModelSelection;
628
+ /** General options for how to process the text. */
629
+ options?: AiKnowledgeBaseContextTextOptions;
630
+ }
631
+ /**
632
+ * Request structure for adding file-based context to an AI agent.
633
+ * @category AI
634
+ */
635
+ export interface AiKnowledgeBaseFileContextRequest extends BaseAiKnowledgeBaseContextRequest {
636
+ /**
637
+ * The id of the context. Optional: when omitted, the server generates one and rejects the upload if
638
+ * another context in the knowledge base already holds identical content (content-level dedup). Provide
639
+ * an explicit id to address a specific context — that overwrites it unconditionally and allows duplicate
640
+ * content across different ids.
641
+ */
642
+ contextId?: AiContextId;
643
+ /** Specifies the context type as 'file'. */
644
+ type: 'file';
645
+ /**
646
+ * Whether to extract images from the file, describe them with a vision model, and index those
647
+ * descriptions alongside the text. Defaults to TRUE — a document's charts, diagrams and scanned pages
648
+ * carry content the text layer does not, so a file context captures them unless asked not to.
649
+ *
650
+ * Note this is the opposite of {@link AiKnowledgeBaseTextContextRequest.extractImages}, which defaults
651
+ * to false: images referenced from a pasted markdown/HTML blob are usually layout chrome, and fetching
652
+ * them means following URLs the caller supplied.
653
+ */
654
+ extractImages?: boolean;
655
+ /** The minimum size for extracted images, if applicable. */
656
+ imageMinSizePixels?: number;
657
+ /** The AI model to use for extraction, if specified. */
658
+ imageExtractionModel?: AiChatModelSelection;
659
+ /** General options for how to process the file. */
660
+ options?: AiKnowledgeBaseContextFileOptions;
661
+ /** The preferred method for extracting data from the document. */
662
+ preferredExtractionMethod?: DocumentExtractionMethod;
663
+ /**
664
+ * Whether Squid discards the downloadable original once the file is extracted; the extracted text and
665
+ * images are stored either way. Defaults to false: the original is kept so the user can download it and
666
+ * Squid can reprocess it. Without it, `querySpreadsheetsWithAi` cannot open a workbook context and a
667
+ * reupsert of the context fails, on the sync and the bulk lane alike.
668
+ */
669
+ discardOriginalFile?: boolean;
670
+ }
671
+ /**
672
+ * Largest single file the bulk multipart staging endpoint accepts (`bulkUpsertContexts` with `files`).
673
+ *
674
+ * Public and shared deliberately: the upload parser rejects an oversized part with a 413 that carries no
675
+ * fallback token, so a client that does not know this bound has no way to route around it — every retry
676
+ * fails identically. Callers with larger files should use `createBulkUploadUrls` + `stagedObjectKey`, which
677
+ * uploads straight to storage and is not subject to it.
678
+ * @category AI
679
+ */
680
+ export declare const BULK_INGESTION_MAX_MULTIPART_FILE_BYTES: number;
681
+ /**
682
+ * Largest single file the platform's upload endpoints accept, per file: the multer limit core applies
683
+ * to every file-upload route (`COMMON_FILE_UPLOAD_OPTIONS`). By definition it also caps a bulk-ingestion
684
+ * source object, whichever way its bytes arrive: core re-enforces it on every staged object — rejecting
685
+ * the whole staging batch with the oversized object — so a staging caller pre-parks larger files.
686
+ * @category AI
687
+ */
688
+ export declare const MAX_UPLOAD_FILE_BYTES: number;
689
+ /**
690
+ * @category AI
691
+ */
692
+ export declare const RAG_TYPES: readonly ["contextual", "basic"];
693
+ /**
694
+ * @category AI
695
+ */
696
+ export type AiRagType = (typeof RAG_TYPES)[number];
697
+ /**
698
+ * Base options for how to deal with the content being upserted.
699
+ * @category AI
700
+ */
701
+ export type BaseAiKnowledgeBaseContextOptions = {
702
+ /** The type of RAG to use for the content. */
703
+ ragType?: AiRagType;
704
+ /** Amount of chunk overlap, in characters. */
705
+ chunkOverlap?: number;
706
+ };
707
+ /**
708
+ * Specific options for the AI knowledgebase search method.
709
+ * @category AI
710
+ */
711
+ export interface AiKnowledgeBaseSearchOptions {
712
+ /** The prompt to search for */
713
+ prompt: string;
714
+ /** The maximum number of results to return */
715
+ limit?: number;
716
+ /** Which provider's reranker to use for reranking the context. Defaults to 'cohere'. */
717
+ rerankProvider?: AiRerankProvider;
718
+ /**
719
+ * Minimum reranker relevance score a chunk must reach to stay once at least 10 chunks are already kept.
720
+ * Defaults to 0.2. Lets an eval tune the drop threshold per reranker, whose score ranges differ.
721
+ */
722
+ rerankScoreThreshold?: number;
723
+ /** How many chunks to look over. Defaults to 100 */
724
+ chunkLimit?: number;
725
+ /** Which chat model to use when asking the question */
726
+ chatModel?: AiChatModelSelection;
727
+ /**
728
+ * Selects how the underlying vector store generates candidates:
729
+ * - `'hybrid'` (default): fuses dense vector and keyword candidates when the backend supports it
730
+ * (Mongo Atlas uses `$rankFusion`; backends without native fusion fall back to dense-only with
731
+ * the legacy app-side keyword fallback).
732
+ * - `'vector'`: dense-only — skips native fusion even on backends that support it.
733
+ * - `'keyword'`: embedding-free lexical retrieval; the mechanism is backend-specific. On Mongo Atlas it
734
+ * is native Lucene BM25 (`$search`): results are ranked by relevance and term-optional — a partial-term
735
+ * query still returns its best matches. On Postgres it is a boolean substring filter (`ILIKE ALL`):
736
+ * every whitespace-separated term must appear in a chunk as a literal, case-insensitive substring,
737
+ * matched independently (order, adjacency and relevance are NOT considered), so results are unranked and
738
+ * for broad terms the returned top-k is arbitrary. Both skip embedding, dense, reranking and the
739
+ * app-side keyword fallback. Lets an agent (or an eval) target exact tokens — identifiers, names, codes
740
+ * — that dense retrieval tends to miss.
741
+ *
742
+ * Intended to let A/B evaluations compare dense-only, hybrid and boolean-keyword candidate generation
743
+ * on the same backend.
744
+ *
745
+ * When omitted, the default is `'graph'` (RRF-fused GraphRAG) on a `graphRag.enabled` KB and
746
+ * `'hybrid'` otherwise. See {@link AiKnowledgeBaseSearchMode}.
747
+ */
748
+ searchMode?: AiKnowledgeBaseSearchMode;
749
+ /**
750
+ * Per-pipeline weights for native hybrid fusion (Mongo `$rankFusion.combination.weights`). Only
751
+ * applies when `searchMode` is `'hybrid'` on a backend with native fusion; ignored otherwise.
752
+ * Each value must be a finite non-negative number; an omitted key defaults to `1` (the MongoDB
753
+ * default). Useful for A/B evaluating dense-vs-keyword weighting on the same backend.
754
+ */
755
+ hybridWeights?: AiHybridSearchWeights;
756
+ /** Tuning for `searchMode:'graph'` (GraphRAG). Ignored for other search modes. */
757
+ graphOptions?: AiKnowledgeBaseGraphSearchOptions;
758
+ /**
759
+ * Scopes the search to the documents under one concept of the KB's graph (Layered KB Graph).
760
+ * Composes with every `searchMode` and with `contextMetadataFilter`. Requires `graphRag.enabled`.
761
+ */
762
+ graphFilter?: AiKnowledgeBaseGraphFilter;
763
+ }
764
+ /**
765
+ * A single chunk of data returned from an AI search operation.
766
+ * @category AI
767
+ */
768
+ export interface AiKnowledgeBaseSearchResultChunk {
769
+ /** The unique identifier of the context. */
770
+ contextId: string;
771
+ /** The data content of the search result chunk. */
772
+ data: string;
773
+ /** Optional metadata associated with the chunk. */
774
+ metadata?: AiContextMetadata;
775
+ /** The relevance score of the chunk, indicating match quality. */
776
+ score: number;
777
+ }
778
+ /**
779
+ * Response structure for upserting context for an AiKnowledgeBase
780
+ * @category AI
781
+ */
782
+ export interface UpsertKnowledgeBaseContextResponse {
783
+ /** List of the upsert status of each item sent in the request. */
784
+ failure?: UpsertContextStatusError;
785
+ /**
786
+ * Set when the context was stored (and is fully searchable via vector/keyword) but NOT graph-indexed
787
+ * because the knowledge base is over its per-KB graph chunk cap. Only GraphRAG coverage is absent; the
788
+ * singular counterpart of {@link UpsertKnowledgeBaseContextsResponse.graphIndexingSkippedContextIds}.
789
+ */
790
+ graphIndexingSkipped?: boolean;
791
+ /**
792
+ * First images (capped) the context lacks a description for because describing them failed; the context
793
+ * is otherwise fully ingested. Absent when every image succeeded. `imageFailureCount` is the total.
794
+ */
795
+ imageFailures?: Array<ContextImageFailure>;
796
+ /** Total number of failed images, which exceeds `imageFailures.length` when the list was capped. */
797
+ imageFailureCount?: number;
798
+ }
799
+ /**
800
+ * The failed images of one context in a multi-context upsert.
801
+ * @category AI
802
+ */
803
+ export interface UpsertContextImageFailures {
804
+ /** The context the images belong to. */
805
+ contextId: AiContextId;
806
+ /** First failed images (capped); `imageFailureCount` is the total. */
807
+ imageFailures: Array<ContextImageFailure>;
808
+ /** Total number of failed images, which exceeds `imageFailures.length` when the list was capped. */
809
+ imageFailureCount: number;
810
+ }
811
+ /**
812
+ * Response structure for upserting contexts for an AiKnowledgeBase
813
+ * @category AI
814
+ */
815
+ export interface UpsertKnowledgeBaseContextsResponse {
816
+ /** List of the upsert status of each item sent in the request. */
817
+ failures: Array<UpsertContextStatusError>;
818
+ /**
819
+ * The context id of every request in the batch, positionally aligned with the `contextRequests` array
820
+ * that was sent — `contextIds[i]` is the id of the i-th request. Each entry is the caller-supplied id,
821
+ * or the id the server generated when the request omitted one, and is present regardless of whether that
822
+ * request succeeded or failed. Lets a caller that upserts without a contextId learn the assigned id.
823
+ *
824
+ * Optional because a newer client talking to an older core (which predates this field) receives it as
825
+ * `undefined` at runtime — callers must handle its absence rather than trust it is always populated.
826
+ */
827
+ contextIds?: Array<AiContextId>;
828
+ /**
829
+ * Contexts that were stored (and are fully searchable via vector/keyword) but NOT graph-indexed because
830
+ * the knowledge base is over its per-KB graph chunk cap. Only GraphRAG coverage is absent; surfaced so a
831
+ * caller can report the graph-coverage gap. Absent/empty when nothing was skipped or graph is disabled.
832
+ */
833
+ graphIndexingSkippedContextIds?: Array<AiContextId>;
834
+ /**
835
+ * Per stored context, the images that lack a description because describing them failed; each such
836
+ * context is otherwise fully ingested. A context that failed outright lists its images on its entry in
837
+ * `failures` instead. Absent when every image succeeded.
838
+ */
839
+ imageFailures?: Array<UpsertContextImageFailures>;
840
+ }
841
+ /**
842
+ * Request structure for searching an AiKnowledgeBase
843
+ * @category AI
844
+ */
845
+ export interface AiKnowledgeBaseSearchRequest {
846
+ /** The id of the AiKnowledgeBase */
847
+ knowledgeBaseId: string;
848
+ /** The user prompt to search on */
849
+ prompt: string;
850
+ /** The search options for this search */
851
+ options: AiKnowledgeBaseSearchOptions;
852
+ }
853
+ /** Default number of grep matches returned when the caller does not ask for a specific number. */
854
+ export declare const GREP_KNOWLEDGE_BASE_DEFAULT_MAX_MATCHES = 50;
855
+ /** Hard ceiling on grep matches: a larger `maxMatches` is clamped down to this value. */
856
+ export declare const GREP_KNOWLEDGE_BASE_MAX_MATCHES = 200;
857
+ /**
858
+ * Longest accepted grep pattern. A literal needle is short by nature; the cap exists so an
859
+ * adversarially long pattern cannot be used to inflate matching cost on a shared server.
860
+ */
861
+ export declare const GREP_KNOWLEDGE_BASE_MAX_PATTERN_CHARS = 500;
862
+ /** Longest `line` / `context` a single match returns; anything longer is clipped with an ellipsis. */
863
+ export declare const GREP_KNOWLEDGE_BASE_MAX_MATCH_LINE_CHARS = 500;
864
+ /**
865
+ * Options for a literal scan over a knowledge base's raw extracted text.
866
+ * @category AI
867
+ */
868
+ export interface GrepKnowledgeBaseOptions {
869
+ /**
870
+ * Scopes the scan to the contexts whose metadata matches this filter — the same grammar knowledge-base
871
+ * chunk search accepts, including `$and`/`$or` composition and the `$underPath` folder operator. The
872
+ * filter selects the contexts BEFORE any text is matched.
873
+ */
874
+ metadataFilter?: AiContextMetadataFilter;
875
+ /**
876
+ * The maximum number of matches to return. Defaults to {@link GREP_KNOWLEDGE_BASE_DEFAULT_MAX_MATCHES}
877
+ * and is clamped to {@link GREP_KNOWLEDGE_BASE_MAX_MATCHES}.
878
+ */
879
+ maxMatches?: number;
880
+ }
881
+ /**
882
+ * Request structure for a literal scan over a knowledge base's raw extracted text.
883
+ * @category AI
884
+ */
885
+ export interface GrepKnowledgeBaseRequest {
886
+ /** The id of the AiKnowledgeBase */
887
+ knowledgeBaseId: AiKnowledgeBaseId;
888
+ /**
889
+ * The literal substring to look for. Every regex metacharacter in it is escaped, so punctuation and
890
+ * symbols mean themselves, and it may span lines. Capped at
891
+ * {@link GREP_KNOWLEDGE_BASE_MAX_PATTERN_CHARS} characters.
892
+ *
893
+ * Matching is case-insensitive for ASCII letters only: `acme` finds `ACME`, but `café` does not find
894
+ * `CAFÉ`. The store and the server run two different regex engines, and their `i` flags disagree on
895
+ * non-ASCII folding — matching ASCII-only is what keeps them in step, so a hit is never reported as an
896
+ * absence. Search the exact casing for non-ASCII text.
897
+ */
898
+ pattern: string;
899
+ /** Scan options. */
900
+ options?: GrepKnowledgeBaseOptions;
901
+ }
902
+ /**
903
+ * One matching line found by {@link GrepKnowledgeBaseRequest}.
904
+ * @category AI
905
+ */
906
+ export interface AiKnowledgeBaseGrepMatch {
907
+ /** The id of the context the match was found in. */
908
+ contextId: AiContextId;
909
+ /** The source file name (or context title for text contexts). */
910
+ fileName: string;
911
+ /** The locator within the file: a sheet/section title when the extractor supplied one, else `page N`. */
912
+ part: string;
913
+ /** The 1-based line number the match starts on within its part. */
914
+ lineNumber: number;
915
+ /** The matching line, clipped to {@link GREP_KNOWLEDGE_BASE_MAX_MATCH_LINE_CHARS} with an ellipsis. */
916
+ line: string;
917
+ /**
918
+ * The matching line plus a small window of the lines around it, joined by newlines and clipped to
919
+ * {@link GREP_KNOWLEDGE_BASE_MAX_MATCH_LINE_CHARS}. Wide spreadsheet rows are the normal case here, so
920
+ * the clip is what keeps a full result set from overflowing an agent's context window.
921
+ */
922
+ context: string;
923
+ }
924
+ /**
925
+ * Why a grep result does not cover everything the caller asked for. Absent means the scan was complete
926
+ * over the requested scope, and only then may an empty `matches` be read as the pattern being absent.
927
+ * At most one applies; the server picks the most significant.
928
+ *
929
+ * - `timedOut` — the scan hit its server-side deadline. Routine on large knowledge bases, since the
930
+ * match is unindexed. Says nothing at all about whether the pattern occurs.
931
+ * - `noIndexedText` — nothing in scope has stored text, so nothing was searched. Contexts ingested
932
+ * before literal search existed sit here until they are re-ingested.
933
+ * - `filterMatchedNoContexts` — `metadataFilter`, composed with any visibility filter the application
934
+ * applies, admitted no contexts, so the scan had nothing to read.
935
+ * - `scopeTruncated` — `metadataFilter` admitted more contexts than one scan can cover, so only a prefix
936
+ * of them was searched. Narrow the filter.
937
+ * - `partsCapReached` — the scan filled its per-call budget of matching pages/sheets, so more matching
938
+ * places exist than it read.
939
+ * - `partialCoverage` — some contexts in scope have stored text and some do not; see
940
+ * {@link GrepKnowledgeBaseResponse.unscannedContextCount}.
941
+ * - `truncatedContent` — some in-scope text was cut at ingest, either because one page or sheet exceeded
942
+ * the per-part storage cap or because a document had more pages than the per-document cap, so that
943
+ * content was never searchable.
944
+ * - `coverageUnknown` — the scan itself succeeded, but how much of the scope holds stored text could not
945
+ * be determined, so completeness cannot be asserted either way.
946
+ * - `patternTooBroad` — the pattern may occur in too many places to check them all within the time limit,
947
+ * so only some were searched. Narrow with `metadataFilter` or use a longer, more distinctive pattern.
948
+ * @category AI
949
+ */
950
+ export type GrepScanLimitation = 'timedOut' | 'noIndexedText' | 'filterMatchedNoContexts' | 'scopeTruncated' | 'partsCapReached' | 'partialCoverage' | 'truncatedContent' | 'coverageUnknown' | 'patternTooBroad';
951
+ /**
952
+ * Response structure for a literal scan over a knowledge base's raw extracted text.
953
+ * @category AI
954
+ */
955
+ export interface GrepKnowledgeBaseResponse {
956
+ /** The matches found, in context/part/line order. */
957
+ matches: Array<AiKnowledgeBaseGrepMatch>;
958
+ /**
959
+ * True when the returned list stopped at `maxMatches` — more matches exist than were returned. This
960
+ * means ONLY that: every other way a scan can fall short of the request lives in {@link limitation},
961
+ * so a caller branching on this one field never mistakes an incomplete scan for "there are more hits".
962
+ */
963
+ truncated: boolean;
964
+ /**
965
+ * Why the scan did not cover the full requested scope, if it did not. Absent means it did — which is
966
+ * the only case where an empty `matches` is evidence that the pattern does not occur. The whole point
967
+ * of this API is to make absence claims trustworthy, so callers must branch on this before concluding
968
+ * anything from an empty result.
969
+ */
970
+ limitation?: GrepScanLimitation;
971
+ /**
972
+ * With `limitation: 'partialCoverage'`, how many contexts in scope have no stored text and were
973
+ * therefore never scanned. The result is silent about those contexts.
974
+ */
975
+ unscannedContextCount?: number;
976
+ /**
977
+ * Every in-scope document known to have lost content at ingest, by file name. Present whenever such a
978
+ * document is in scope, alongside whichever {@link limitation} the scan reported — a cut document is no
979
+ * less cut because the scan also stopped early. Absent when none is.
980
+ */
981
+ truncatedContentFileNames?: Array<string>;
982
+ }
983
+ /**
984
+ * Request structure for searching AI contexts in the AiKnowledgeBase.
985
+ * @category AI
986
+ */
987
+ export interface BaseAiKnowledgeBaseSearchContextsRequest {
988
+ /** The id of the AiKnowledgeBase */
989
+ knowledgeBaseId: AiKnowledgeBaseId;
990
+ /** The maximum number of results to return */
991
+ limit?: number;
992
+ /** A set of filters that will limit the context the AI can access. */
993
+ contextMetadataFilter?: AiContextMetadataFilter;
994
+ /** Whether to rerank the results with AI and provide reasoning - defaults to true */
995
+ rerank?: boolean;
996
+ /** Which chat model to use when doing reranking */
997
+ chatModel?: AiChatModelSelection;
998
+ /**
999
+ * Reasoning effort of the reranking model. A score needs little thought, so `'low'` is the usual
1000
+ * choice; when unset the model applies its own default.
1001
+ */
1002
+ rerankReasoningEffort?: AiReasoningEffort;
1003
+ }
1004
+ /**
1005
+ * Request structure for searching AI contexts in the AiKnowledgeBase with prompt.
1006
+ * @category AI
1007
+ */
1008
+ export interface AiKnowledgeBaseSearchContextsWithPromptRequest extends BaseAiKnowledgeBaseSearchContextsRequest {
1009
+ /** The user prompt to search on */
1010
+ prompt: string;
1011
+ }
1012
+ /**
1013
+ * Request structure for searching AI contexts in the AiKnowledgeBase with an existing context.
1014
+ * @category AI
1015
+ */
1016
+ export interface AiKnowledgeBaseSearchContextsWithContextIdRequest extends BaseAiKnowledgeBaseSearchContextsRequest {
1017
+ /** The contextId to search with */
1018
+ contextId: string;
1019
+ }
1020
+ /**
1021
+ * A context with reasoning and matching score.
1022
+ * @category AI
1023
+ */
1024
+ export interface AiKnowledgeBaseContextWithReasoning {
1025
+ /** The actual context */
1026
+ context: AiKnowledgeBaseContext;
1027
+ /** The reasoning behind why this context was matched - can be undefined if no reasoning was requested */
1028
+ reasoning?: string;
1029
+ /** The score of the match, ranging from 0 to 100, where 100 is the best match. */
1030
+ score: number;
1031
+ }
1032
+ /**
1033
+ * Response structure for searching contexts in an AiKnowledgeBase.
1034
+ * @category AI
1035
+ */
1036
+ export interface AiKnowledgeBaseSearchContextsResponse {
1037
+ /** The resulting contexts, with reasoning if it was requested */
1038
+ results: Array<AiKnowledgeBaseContextWithReasoning>;
1039
+ }
1040
+ /**
1041
+ * Request structure for requesting a download link to the context file that you previously provided.
1042
+ * @category AI
1043
+ */
1044
+ export interface AiKnowledgeBaseDownloadContextRequest {
1045
+ /** The id of the AiKnowledgeBase */
1046
+ knowledgeBaseId: string;
1047
+ /** The id of the particular AiKnowledgeBaseContext */
1048
+ contextId: string;
1049
+ }
1050
+ /**
1051
+ * Response structure with the URL to download the specified context.
1052
+ *
1053
+ * Can be undefined if the file is not available in Squid.
1054
+ * @category AI
1055
+ */
1056
+ export interface AiKnowledgeBaseDownloadContextResponse {
1057
+ /** The URL to download the file, if available. */
1058
+ url?: string;
1059
+ }
1060
+ /**
1061
+ * KnowledgeBase with optional fields, used during upsert
1062
+ * @category AI
1063
+ */
1064
+ export type AiEmbeddingsModelWithOptionalFields = Omit<AiKnowledgeBase, 'chatModel' | 'embeddingModel'> & {
1065
+ chatModel?: AiKnowledgeBase['chatModel'];
1066
+ name?: string;
1067
+ embeddingModel?: AiEmbeddingsModelSelection;
1068
+ };
1069
+ /**
1070
+ * API request for deleting an AiKnowledgeBase
1071
+ * @category AI
1072
+ */
1073
+ export interface DeleteAiKnowledgeBaseRequest {
1074
+ /** The id of the AiKnowledgeBase */
1075
+ id: string;
1076
+ }
1077
+ /**
1078
+ * API request for upserting an AiKnowledgeBase
1079
+ * @category AI
1080
+ */
1081
+ export interface UpsertAiKnowledgeBaseRequest {
1082
+ /** The AiKnowledgeBase to upsert */
1083
+ knowledgeBase: Omit<AiEmbeddingsModelWithOptionalFields, 'appId' | 'updatedAt'>;
1084
+ }
1085
+ /**
1086
+ * API request for deleting AiKnowledgeBaseContexts
1087
+ * @category AI
1088
+ */
1089
+ export interface DeleteAiKnowledgeBaseContextsRequest {
1090
+ /** The id of the AiKnowledgeBase */
1091
+ knowledgeBaseId: string;
1092
+ /** An array of AiKnowledgeBaseContext ids */
1093
+ contextIds: Array<string>;
1094
+ }
1095
+ /**
1096
+ * API response to list AiKnowledgeBaseContexts
1097
+ * @category AI
1098
+ */
1099
+ export interface ListAiKnowledgeBaseContextsResponse {
1100
+ /** The list of AiKnowledgeBaseContexts */
1101
+ contexts: Array<AiKnowledgeBaseContext>;
1102
+ }
1103
+ /**
1104
+ * Options for {@link AiKnowledgeBaseReference.listContextsPage}
1105
+ * @category AI
1106
+ */
1107
+ export interface ListKnowledgeBaseContextsOptions {
1108
+ /** The number of characters after which text is truncated. Optional */
1109
+ truncateTextAfter?: number;
1110
+ /** The number of contexts to skip, for pagination. Optional */
1111
+ offset?: number;
1112
+ /** The maximum number of contexts to return, for pagination. Optional */
1113
+ limit?: number;
1114
+ /** Case-insensitive substring search across id/title only. Optional */
1115
+ search?: string;
1116
+ }
1117
+ /**
1118
+ * API request for listing a page of AiKnowledgeBaseContexts
1119
+ * @category AI
1120
+ */
1121
+ export interface ListAiKnowledgeBaseContextsPageRequest {
1122
+ /** The id of the AiKnowledgeBase */
1123
+ id: string;
1124
+ /** The number of characters after which text is truncated. Optional */
1125
+ truncateTextAfter?: number;
1126
+ /** The number of contexts to skip, for pagination. Optional */
1127
+ offset?: number;
1128
+ /** The maximum number of contexts to return, for pagination. Optional */
1129
+ limit?: number;
1130
+ /** Case-insensitive substring search across id/title only. Optional */
1131
+ search?: string;
1132
+ }
1133
+ /**
1134
+ * API response to list a page of AiKnowledgeBaseContexts
1135
+ * @category AI
1136
+ */
1137
+ export interface ListAiKnowledgeBaseContextsPageResponse {
1138
+ /** The list of AiKnowledgeBaseContexts */
1139
+ contexts: Array<AiKnowledgeBaseContext>;
1140
+ /** The total number of contexts in the AiKnowledgeBase, ignoring offset/limit */
1141
+ totalCount: number;
1142
+ }
1143
+ /**
1144
+ * API response for searching an AiKnowledgeBase
1145
+ * @category AI
1146
+ */
1147
+ export interface AiKnowledgeBaseSearchResponse {
1148
+ /** Array of result chunks from the search */
1149
+ chunks: Array<AiKnowledgeBaseSearchResultChunk>;
1150
+ /**
1151
+ * The subgraph traversed for a `searchMode:'graph'` query. Present only when
1152
+ * `graphOptions.includeGraphContext` was set; absent for all other searches.
1153
+ */
1154
+ graphContext?: AiKnowledgeBaseGraphContext;
1155
+ }
1156
+ /**
1157
+ * Response containing the list of AI knowledge bases in an application.
1158
+ * @category AI
1159
+ */
1160
+ export interface ListAiKnowledgeBasesResponse {
1161
+ /** All AI knowledge bases defined for the application. */
1162
+ knowledgeBases: Array<AiKnowledgeBase>;
1163
+ }
1164
+ /** Request to AI-generate descriptions for a KB's metadata fields and return them (the caller persists). */
1165
+ export interface GenerateMetadataFieldDescriptionsRequest {
1166
+ /** The id of the AiKnowledgeBase. */
1167
+ knowledgeBaseId: AiKnowledgeBaseId;
1168
+ /** Limit generation to these fields; omitted ⇒ all declared fields. */
1169
+ fieldNames?: string[];
1170
+ /** When true, regenerate fields that already have a description; default false (fill empties only). */
1171
+ overwriteExisting?: boolean;
1172
+ }
1173
+ /** Response for the AI-generated metadata field descriptions. */
1174
+ export interface GenerateMetadataFieldDescriptionsResponse {
1175
+ /** The (re)generated fields with their new descriptions; not persisted — the caller saves them. */
1176
+ fields: Array<GeneratedMetadataFieldDescription>;
1177
+ }
1178
+ /** A generated description for a single metadata field. */
1179
+ export interface GeneratedMetadataFieldDescription {
1180
+ /** The name of the metadata field. */
1181
+ name: string;
1182
+ /** The AI-generated description for the field. */
1183
+ description: string;
1184
+ }
1185
+ /**
1186
+ * Request structure for reading a knowledge base's GraphRAG build/readiness status.
1187
+ * @category AI
1188
+ */
1189
+ export interface GetKnowledgeBaseGraphStatusRequest {
1190
+ /** The id of the AiKnowledgeBase. */
1191
+ knowledgeBaseId: AiKnowledgeBaseId;
1192
+ }
1193
+ /**
1194
+ * Response structure for a knowledge base's GraphRAG build/readiness status. Drives the ai-eval
1195
+ * readiness poll (index until `contextsIndexed === contextsTotal` and `buildJob` is not in-progress).
1196
+ * @category AI
1197
+ */
1198
+ export interface GetKnowledgeBaseGraphStatusResponse {
1199
+ /** Whether GraphRAG is enabled on the KB. */
1200
+ enabled: boolean;
1201
+ /** Number of live entities in the KB's graph partition (quarantined ones excluded). */
1202
+ entityCount: number;
1203
+ /** Entities hidden by a dead-weight quarantine run; absent when the KB's graph store cannot quarantine. */
1204
+ quarantinedEntityCount?: number;
1205
+ /** Number of outgoing relationships (mirrors excluded). */
1206
+ relationshipCount: number;
1207
+ /** Number of communities detected (Phase 3), 0 when none. */
1208
+ communityCount: number;
1209
+ /** Contexts stamped as graph-indexed. */
1210
+ contextsIndexed: number;
1211
+ /** Total contexts in the KB. */
1212
+ contextsTotal: number;
1213
+ /** Document nodes in the KB's graph (Layered KB Graph L1) — one per graph-indexed context. */
1214
+ docNodesTotal?: number;
1215
+ /** Document nodes carrying a non-empty LLM description (failed descriptions retry on rebuild). */
1216
+ docsDescribed?: number;
1217
+ /** The KB's facet trees (Layered KB Graph L3, deterministic) — empty until a rebuild builds them. */
1218
+ facets?: Array<KnowledgeBaseGraphFacetStatus>;
1219
+ /**
1220
+ * The KB's topic (theme) hierarchy — present once a graph build has clustered topics. Ids churn on
1221
+ * rebuild ({@link KnowledgeBaseGraphTopic.id}); resolve them per session, never persist them.
1222
+ */
1223
+ topics?: Array<KnowledgeBaseGraphTopic>;
1224
+ /**
1225
+ * Leaf-level inter-topic edges (relationship counts crossing topic boundaries), present once a graph
1226
+ * build has computed them. Roll up to coarser tiers by mapping each endpoint to its ancestor.
1227
+ */
1228
+ topicEdges?: Array<KnowledgeBaseGraphTopicEdge>;
1229
+ /**
1230
+ * True when documents were graph-indexed after the last topic build — themes may lag content until
1231
+ * the next `rebuildGraph`. Only meaningful once topics exist (absent before the first rebuild).
1232
+ */
1233
+ structureStale?: boolean;
1234
+ /** Documents added since the last topic build (the `structureStale` numerator). */
1235
+ staleDocCount?: number;
1236
+ /** Status of the most recent backfill/rebuild job, when one exists. */
1237
+ buildJob?: KnowledgeBaseGraphBuildJob;
1238
+ /** Lifetime LLM usage of incremental graph ingestion (per-upsert extraction), when any was recorded. */
1239
+ ingestUsage?: KnowledgeBaseGraphUsage;
1240
+ /**
1241
+ * LLM usage of the most recent COMPLETED `rebuildGraph` run (including its re-extraction), when one
1242
+ * ran. A build in flight leaves it on the previous build until it completes — read
1243
+ * {@link buildUsageHistory} for the in-flight run.
1244
+ */
1245
+ lastRebuildUsage?: KnowledgeBaseGraphUsage;
1246
+ /**
1247
+ * Per-build LLM usage of the KB's most recent `rebuildGraph` runs, newest first, bounded to the last
1248
+ * 50 builds. Unlike {@link lastRebuildUsage} no build erases another's record, so back-to-back builds
1249
+ * are all accounted for.
1250
+ */
1251
+ buildUsageHistory?: Array<KnowledgeBaseGraphBuildUsage>;
1252
+ /**
1253
+ * Lifetime LLM usage of the combined contextual-blurb + graph-extraction call (run automatically for
1254
+ * `ragType:'contextual'` graph-enabled KBs), when any was recorded. Covers BOTH the contextual blurb
1255
+ * and graph extraction in one call, so it is not directly comparable to the graph-only
1256
+ * {@link ingestUsage}.
1257
+ */
1258
+ combinedIngestUsage?: KnowledgeBaseGraphUsage;
1259
+ /** When a structural/full rebuild last completed successfully (epoch millis), when one ever has. */
1260
+ lastStructureBuildAt?: number;
1261
+ /**
1262
+ * When the debounced auto-build sweep will pick the KB up (epoch millis), present while an auto-build
1263
+ * is pending. Recomputed per poll — it moves forward while ingest activity continues.
1264
+ */
1265
+ nextAutoBuildAt?: number;
1266
+ /**
1267
+ * True when graph-scoped search (`graphFilter.underConcept`) runs on the index-native denormalized
1268
+ * `conceptIds` pre-filter: the backend's search indexes serve the field AND the chunk copies are in
1269
+ * sync with the doc nodes. False while either half is not ready (index still building, or a rebuild
1270
+ * is in flight — a rebuild drops the sync gate for its duration); scoped search then uses the
1271
+ * capped contextId-closure fallback. Absent when GraphRAG is disabled.
1272
+ */
1273
+ conceptScopeReady?: boolean;
1274
+ /** The incremental entity-resolution sweep's latest readings, present once a sweep has sampled the KB. */
1275
+ resolution?: KnowledgeBaseGraphResolutionStatus;
1276
+ /** Scheduled structural build slots skipped because the build could not start in time, newest last. */
1277
+ structuralBuildSkips?: Array<KnowledgeBaseGraphStructuralBuildSkip>;
1278
+ /** A manual `rebuildGraph` request waiting for the running entity-resolution build to finish. */
1279
+ queuedRebuild?: KnowledgeBaseGraphQueuedRebuild;
1280
+ }
1281
+ /**
1282
+ * A manual graph rebuild requested while an entity-resolution build ran. It starts once that build ends,
1283
+ * regardless of the structural build schedule.
1284
+ * @category AI
1285
+ */
1286
+ export interface KnowledgeBaseGraphQueuedRebuild {
1287
+ /** The requested rebuild mode; a `'full'` request absorbs a `'structural'` one queued with it. */
1288
+ mode: KnowledgeBaseGraphRebuildMode;
1289
+ /** When the latest request was queued (epoch millis). */
1290
+ requestedAt: number;
1291
+ }
1292
+ /**
1293
+ * Readings the incremental entity-resolution sweep persists on a knowledge base: the dirty backlog it
1294
+ * drains across sweeps and the duplicate-name fragmentation it exists to merge.
1295
+ * @category AI
1296
+ */
1297
+ export interface KnowledgeBaseGraphResolutionStatus {
1298
+ /** Entities rewritten since the sweep last examined them. */
1299
+ backlog: number;
1300
+ /** When `backlog` was sampled (epoch millis) — the start or end of a sweep. */
1301
+ backlogSampledAt: number;
1302
+ /** Entities sharing another entity's significant-name-token signature; absent until a sweep sampled it. */
1303
+ duplicateNames?: number;
1304
+ /** When `duplicateNames` was sampled (epoch millis). */
1305
+ duplicateNamesSampledAt?: number;
1306
+ /** The most recent sweep: the bounds it ran under and what it got through; absent until one has run. */
1307
+ lastSweep?: KnowledgeBaseGraphResolutionSweep;
1308
+ }
1309
+ /**
1310
+ * One incremental entity-resolution sweep's bounds and counters, as persisted at its start (counters
1311
+ * zero) and again at its end.
1312
+ * @category AI
1313
+ */
1314
+ export interface KnowledgeBaseGraphResolutionSweep {
1315
+ /** Dirty entities one pass of the sweep examined at most. */
1316
+ dirtyBatch: number;
1317
+ /** Drain rounds the sweep ran at most. */
1318
+ maxRounds: number;
1319
+ /** Candidate pairs one drain round of the sweep adjudicated at most. */
1320
+ maxPairsPerRound: number;
1321
+ /** Resolution passes one drain round of the sweep ran at most. */
1322
+ maxPasses: number;
1323
+ /** Adjudication calls the sweep kept in flight. */
1324
+ adjudicationConcurrency: number;
1325
+ /** Dirty entities one pass of the sweep searched candidates for at once. */
1326
+ proposalConcurrency: number;
1327
+ /** Drain rounds the sweep ran. */
1328
+ rounds: number;
1329
+ /** Dirty entities the sweep examined. */
1330
+ examined: number;
1331
+ /** Candidate pairs the sweep sent to adjudication. */
1332
+ pairsAdjudicated: number;
1333
+ /** Candidate pairs adjudication confirmed as the same entity. */
1334
+ pairsConfirmed: number;
1335
+ /** Adjudication calls the sweep made; absent on a reading from a sweep that did not record calls. */
1336
+ adjudicationCalls?: number;
1337
+ /** Of those, calls the provider served the instruction prefix from its prompt cache; absent with them. */
1338
+ adjudicationCachedCalls?: number;
1339
+ /**
1340
+ * Index-visibility wait tokens the sweep spent: a count of waits, not a duration. Absent on a reading
1341
+ * from a sweep that did not record waits.
1342
+ */
1343
+ visibilityWaits?: number;
1344
+ /** When this reading was written (epoch millis). */
1345
+ sampledAt: number;
1346
+ }
1347
+ /** The most recent graph backfill/rebuild job of a knowledge base. @category AI */
1348
+ export interface KnowledgeBaseGraphBuildJob {
1349
+ /** The job's lifecycle state. */
1350
+ status: 'in_progress' | 'completed' | 'failed';
1351
+ /** Failure message, present when `status` is `'failed'`. */
1352
+ error?: string;
1353
+ /** When the job was enqueued (epoch millis). */
1354
+ startedAt?: number;
1355
+ }
1356
+ /**
1357
+ * LLM usage of one graph build (`rebuildGraph` run), kept per build so a later build cannot erase it.
1358
+ * Accumulated across the run's execution attempts — a resumed rebuild adds to the same record.
1359
+ * @category AI
1360
+ */
1361
+ export interface KnowledgeBaseGraphBuildUsage {
1362
+ /** Identity of the build, stable across its execution attempts. */
1363
+ buildId: string;
1364
+ /** The plan the build executed; `'resolution'` is the internal resolution-only continuation. */
1365
+ mode: KnowledgeBaseGraphRebuildMode | 'resolution';
1366
+ /** The build's lifecycle state. */
1367
+ status: 'in_progress' | 'completed' | 'failed';
1368
+ /** When the build started (epoch millis). */
1369
+ startedAt: number;
1370
+ /** When the build reached a terminal state (epoch millis); absent while it runs. */
1371
+ completedAt?: number;
1372
+ /** Contexts whose chunks the build re-extracted; `0` when it re-extracted nothing. */
1373
+ contextsReextracted: number;
1374
+ /** The build's total LLM usage, with its per-model split. */
1375
+ usage: KnowledgeBaseGraphUsage;
1376
+ /** The split of {@link usage} across the stages the build ran. */
1377
+ stages: KnowledgeBaseGraphBuildStageUsage;
1378
+ /** What the build's incremental entity-resolution stage has got through; absent until its first pass reports. */
1379
+ resolutionProgress?: KnowledgeBaseGraphResolutionProgress;
1380
+ }
1381
+ /**
1382
+ * Running progress of a build's incremental entity-resolution stage, written as each pass proposes,
1383
+ * adjudicates and merges, and summed over the build's execution attempts. The build's `usage` is flushed
1384
+ * at the same points, so it reads as the cost so far while the build runs.
1385
+ * @category AI
1386
+ */
1387
+ export interface KnowledgeBaseGraphResolutionProgress {
1388
+ /** Drain rounds completed. */
1389
+ rounds: number;
1390
+ /** Resolution passes completed. */
1391
+ passes: number;
1392
+ /** Dirty entities examined. */
1393
+ examined: number;
1394
+ /** Candidate pairs sent to adjudication. */
1395
+ pairsProposed: number;
1396
+ /** Candidate pairs adjudication confirmed as the same entity. */
1397
+ pairsConfirmed: number;
1398
+ /** Entities merged into a canonical entity. */
1399
+ entitiesMerged: number;
1400
+ /** Time spent proposing candidate pairs (millis). */
1401
+ proposalMs: number;
1402
+ /** Time spent adjudicating candidate pairs (millis). */
1403
+ adjudicationMs: number;
1404
+ /** Time spent merging confirmed pairs and refreshing the survivors (millis). */
1405
+ mergeMs: number;
1406
+ /** When the progress was last written (epoch millis). */
1407
+ updatedAt: number;
1408
+ }
1409
+ /**
1410
+ * A scheduled structural build slot whose catch-up window closed (or the next slot superseded it) without a
1411
+ * structural build, because the automatic build could not start while the window was open.
1412
+ * @category AI
1413
+ */
1414
+ export interface KnowledgeBaseGraphStructuralBuildSkip {
1415
+ /** The cron slot that was skipped (epoch millis). */
1416
+ slotAt: number;
1417
+ /** When the slot's catch-up window closed (epoch millis). */
1418
+ windowEndsAt: number;
1419
+ /**
1420
+ * Why the build could not start: an entity-resolution build was still running, another graph build held the KB,
1421
+ * a manual rebuild was queued ahead of it, a bulk ingestion was writing to it, or `graphRag.autoBuildPaused` was set.
1422
+ * The last reason seen in the window.
1423
+ */
1424
+ reason: KnowledgeBaseGraphStructuralBuildSkipReason;
1425
+ /** When the skip was recorded (epoch millis). */
1426
+ recordedAt: number;
1427
+ }
1428
+ /** Why an automatic structural build could not start inside its scheduled window. @category AI */
1429
+ export type KnowledgeBaseGraphStructuralBuildSkipReason = 'resolution-running' | 'build-in-progress' | 'queued-rebuild' | 'bulk-ingest' | 'paused';
1430
+ /**
1431
+ * A graph build's LLM usage split by pipeline stage. A stage the build entered but spent nothing on
1432
+ * reads zero; a stage it never ran (skipped by its plan, or by a resume) is absent.
1433
+ * @category AI
1434
+ */
1435
+ export interface KnowledgeBaseGraphBuildStageUsage {
1436
+ /** Entity/relationship re-extraction from the KB's chunks. */
1437
+ reextraction?: KnowledgeBaseGraphUsage;
1438
+ /** Entity resolution (duplicate-name adjudication and merges). */
1439
+ resolution?: KnowledgeBaseGraphUsage;
1440
+ /** The lexical mention backstop, which is deterministic and normally spends nothing. */
1441
+ backstop?: KnowledgeBaseGraphUsage;
1442
+ /** Topic clustering and topic summaries. */
1443
+ topics?: KnowledgeBaseGraphUsage;
1444
+ /** Facet tree construction. */
1445
+ facets?: KnowledgeBaseGraphUsage;
1446
+ }
1447
+ /**
1448
+ * Aggregated LLM token usage (and best-effort cost) of graph work on a KB. Token counts are the
1449
+ * provider-reported ground truth; `estCostUsd` is estimated from model list prices at call time —
1450
+ * recompute from the tokens for exact accounting.
1451
+ * @category AI
1452
+ */
1453
+ export interface KnowledgeBaseGraphUsage {
1454
+ /** Number of LLM calls. */
1455
+ llmCalls: number;
1456
+ /** Prompt (input) tokens. */
1457
+ inputTokens: number;
1458
+ /** Completion (output) tokens. */
1459
+ outputTokens: number;
1460
+ /** Reasoning tokens, where the provider reports them separately. */
1461
+ reasoningTokens: number;
1462
+ /** Input tokens served from the provider's prompt cache. */
1463
+ cacheReadTokens: number;
1464
+ /** Input tokens written into the provider's prompt cache. */
1465
+ cacheWriteTokens: number;
1466
+ /** Best-effort USD estimated from list prices at call time. */
1467
+ estCostUsd: number;
1468
+ /**
1469
+ * Per-model split of the totals above (LLM calls only), present when any usage was recorded. The
1470
+ * per-model figures sum to the aggregate; embedding usage is excluded from both.
1471
+ */
1472
+ byModel?: Array<KnowledgeBaseGraphModelUsage>;
1473
+ }
1474
+ /**
1475
+ * One model's slice of a KB's graph LLM usage, keyed by the resolved model name. Token counts are the
1476
+ * provider-reported ground truth; `estCostUsd` is estimated from model list prices at call time.
1477
+ * @category AI
1478
+ */
1479
+ export interface KnowledgeBaseGraphModelUsage {
1480
+ /** The resolved model these totals are attributed to. */
1481
+ model: string;
1482
+ /** Number of LLM calls billed to this model. */
1483
+ llmCalls: number;
1484
+ /** Prompt (input) tokens. */
1485
+ inputTokens: number;
1486
+ /** Completion (output) tokens. */
1487
+ outputTokens: number;
1488
+ /** Reasoning tokens, where the provider reports them separately. */
1489
+ reasoningTokens: number;
1490
+ /** Input tokens served from the provider's prompt cache. */
1491
+ cacheReadTokens: number;
1492
+ /** Input tokens written into the provider's prompt cache. */
1493
+ cacheWriteTokens: number;
1494
+ /** Best-effort USD estimated from list prices at call time. */
1495
+ estCostUsd: number;
1496
+ }
1497
+ /**
1498
+ * One facet tree in a graph status response: the metadata field it is built from and its value leaves
1499
+ * (most-populated first, capped — compare `values.length` against `valueCount` for truncation).
1500
+ * @category AI
1501
+ */
1502
+ export interface KnowledgeBaseGraphFacetStatus {
1503
+ /** The metadata field the facet is built from. */
1504
+ facetKey: string;
1505
+ /** Display name of the facet root. */
1506
+ name: string;
1507
+ /** Total facet-value leaves (may exceed `values.length` — the list is capped). */
1508
+ valueCount: number;
1509
+ /** Documents carrying any value of this facet. */
1510
+ docCount: number;
1511
+ /** The facet's value leaves. */
1512
+ values: Array<KnowledgeBaseGraphFacetValueStatus>;
1513
+ }
1514
+ /** One value leaf of a facet in a graph status response. @category AI */
1515
+ export interface KnowledgeBaseGraphFacetValueStatus {
1516
+ /** Display name of the value (the most frequent raw variant). */
1517
+ name: string;
1518
+ /** Documents assigned to this value. */
1519
+ docCount: number;
1520
+ /** Raw variants consolidated into this value ("USA" under "United States"), when any. */
1521
+ aliases?: string[];
1522
+ }
1523
+ /**
1524
+ * How much of the knowledge base's graph a rebuild recomputes.
1525
+ *
1526
+ * - `'structural'` (default) — keeps the already-extracted entity graph (LLM extraction runs only for
1527
+ * contexts that were never graph-indexed, e.g. after an interrupted ingest) and recomputes the
1528
+ * derived structure on top of it: entity resolution, lexical mentions, topics and facets. Typically
1529
+ * a small fraction of a full rebuild's cost — the right choice for folding freshly ingested
1530
+ * documents into topics/facets.
1531
+ * - `'full'` — wipes the graph and re-extracts entities/relationships from every chunk with an LLM,
1532
+ * then rebuilds the concept layer. The expensive deep-clean: re-extraction dominates its cost.
1533
+ * Only needed when the extraction itself must be redone, e.g. after changing `entityTypes` or
1534
+ * `extractionModel`.
1535
+ * @category AI
1536
+ */
1537
+ export type KnowledgeBaseGraphRebuildMode = 'full' | 'structural';
1538
+ /**
1539
+ * Request structure for enqueuing a GraphRAG rebuild/backfill of a knowledge base.
1540
+ * @category AI
1541
+ */
1542
+ export interface RebuildKnowledgeBaseGraphRequest {
1543
+ /** The id of the AiKnowledgeBase. */
1544
+ knowledgeBaseId: AiKnowledgeBaseId;
1545
+ /** What to recompute (see {@link KnowledgeBaseGraphRebuildMode}). Default `'structural'`. */
1546
+ mode?: KnowledgeBaseGraphRebuildMode;
1547
+ /**
1548
+ * When true, starts the rebuild even while a bulk-ingestion job on the KB is still active. Off by
1549
+ * default: such a rebuild is refused (`GRAPH_REBUILD_BLOCKED_BY_BULK_JOB`) because it re-extracts the
1550
+ * contexts the job is still merging. Set it for a job that is wedged (its pod died and its deadline
1551
+ * has not passed) when cancelling the job is not an option.
1552
+ */
1553
+ ignoreActiveBulkJobs?: boolean;
1554
+ }
1555
+ /**
1556
+ * Request structure for exploring a bounded subgraph of a knowledge base's graph (Phase 3 visualization).
1557
+ * Returns the highest-degree entities and the relationships among them. Seed-based exploration
1558
+ * (prompt/entity-name seeding + traversal depth) is a planned extension; its fields will be added
1559
+ * here once implemented.
1560
+ * @category AI
1561
+ */
1562
+ export interface ExploreKnowledgeBaseGraphRequest {
1563
+ /** The id of the AiKnowledgeBase. */
1564
+ knowledgeBaseId: AiKnowledgeBaseId;
1565
+ /** Hard cap on returned nodes. Default 200, max 1000. */
1566
+ nodeLimit?: number;
1567
+ /**
1568
+ * Restricts the subgraph to entities under the given topic node id — any hierarchy level; an entity
1569
+ * matches when the topic appears anywhere in its `topicPath`. Unknown ids fail with
1570
+ * `TOPIC_NOT_FOUND`. Ids come from {@link KnowledgeBaseGraphTopic.id} and churn on rebuild.
1571
+ */
1572
+ topicId?: string;
1573
+ }
1574
+ /** A node in an {@link ExploreKnowledgeBaseGraphResponse}. @category AI */
1575
+ export interface KnowledgeBaseGraphNode {
1576
+ /** Stable node id (the entity's document id). */
1577
+ id: string;
1578
+ /** Canonical display name. */
1579
+ name: string;
1580
+ /** Entity type. */
1581
+ type: string;
1582
+ /** Compacted description. */
1583
+ description: string;
1584
+ /** Relationship degree (denormalized). */
1585
+ degree: number;
1586
+ /** Community id (Phase 3), when community detection has run. */
1587
+ communityId?: string;
1588
+ /** Level-0..k topic nodeIds (bottom-up, Layered KB Graph), when a topic rebuild has run. */
1589
+ topicPath?: string[];
1590
+ /** Norm-names this entity absorbed via resolution merges (present only when non-empty). */
1591
+ aliases?: string[];
1592
+ }
1593
+ /** An edge in an {@link ExploreKnowledgeBaseGraphResponse}. @category AI */
1594
+ export interface KnowledgeBaseGraphEdge {
1595
+ /** Source node id. */
1596
+ source: string;
1597
+ /** Target node id. */
1598
+ target: string;
1599
+ /** Relationship label. */
1600
+ type: string;
1601
+ /** Co-mention weight. */
1602
+ weight: number;
1603
+ }
1604
+ /**
1605
+ * Response structure for the bounded subgraph exploration (Phase 3 visualization).
1606
+ * @category AI
1607
+ */
1608
+ export interface ExploreKnowledgeBaseGraphResponse {
1609
+ /** The subgraph nodes. */
1610
+ nodes: Array<KnowledgeBaseGraphNode>;
1611
+ /** The subgraph edges (outgoing only, both endpoints present in `nodes`). */
1612
+ edges: Array<KnowledgeBaseGraphEdge>;
1613
+ /**
1614
+ * The KB's topic (theme) nodes — the id→name/hierarchy table for the nodes' `topicPath` ids, so a
1615
+ * visualization can label and group by theme without extra round trips. Present when the concept
1616
+ * layer has been built (a rebuild ran).
1617
+ */
1618
+ topics?: Array<KnowledgeBaseGraphTopic>;
1619
+ }
1620
+ /**
1621
+ * A topic (theme) node of the graph's concept layer, as referenced by
1622
+ * {@link KnowledgeBaseGraphNode.topicPath}.
1623
+ * @category AI
1624
+ */
1625
+ export interface KnowledgeBaseGraphTopic {
1626
+ /** Topic nodeId (matches `topicPath` entries). Churns on rebuild — not a persistable handle. */
1627
+ id: string;
1628
+ /** Topic display name. Re-resolves by name across rebuilds. */
1629
+ name: string;
1630
+ /** Hierarchy level: 0 = leaf tier, higher = coarser tiers. */
1631
+ level: number;
1632
+ /** Parent topic nodeId, when the topic sits under a coarser tier. */
1633
+ parentId?: string;
1634
+ /** Documents under the topic, when tracked. */
1635
+ docCount?: number;
1636
+ /** Members of the topic: entities at level 0, child topics at higher levels. */
1637
+ memberCount?: number;
1638
+ }
1639
+ /**
1640
+ * An aggregated relationship edge between two leaf topics: how many entity relationships cross
1641
+ * between their member entities. Undirected (one entry per pair) and pruned to each topic's
1642
+ * strongest neighbors, so weak long-tail links may be absent. Ids churn on rebuild, like
1643
+ * {@link KnowledgeBaseGraphTopic.id}.
1644
+ * @category AI
1645
+ */
1646
+ export interface KnowledgeBaseGraphTopicEdge {
1647
+ /** One endpoint's topic nodeId. */
1648
+ source: string;
1649
+ /** The other endpoint's topic nodeId. */
1650
+ target: string;
1651
+ /** Number of entity relationships crossing between the two topics. */
1652
+ weight: number;
1653
+ }
1654
+ /**
1655
+ * The closed operation set of the `queryKnowledgeGraph` surface (Layered KB Graph P4). Every op is one
1656
+ * round trip with a complete answer — no per-level walking.
1657
+ * @category AI
1658
+ */
1659
+ export type KnowledgeBaseGraphQueryOp = 'overview' | 'resolve' | 'describe' | 'subtree' | 'docsUnder' | 'conceptsOf' | 'neighborhood' | 'pathBetween' | 'globalSummary';
1660
+ /**
1661
+ * Request structure for querying a knowledge base's graph (documents, entities, topics, facets) through
1662
+ * the closed op set. `ref` accepts a facet nodeId (`facet_…` — exact; the only persistable concept
1663
+ * handles) or a name, resolved server-side (exact → alias → similarity). An unresolvable ref fails with
1664
+ * `CONCEPT_NOT_FOUND` plus the nearest matching names.
1665
+ * @category AI
1666
+ */
1667
+ export interface QueryKnowledgeBaseGraphRequest {
1668
+ /** The id of the AiKnowledgeBase. */
1669
+ knowledgeBaseId: AiKnowledgeBaseId;
1670
+ /** The operation to run. */
1671
+ op: KnowledgeBaseGraphQueryOp;
1672
+ /** Node ref (name or facet nodeId). Required by resolve/describe/subtree/docsUnder/neighborhood/pathBetween. */
1673
+ ref?: string;
1674
+ /** Second node ref for `pathBetween`. */
1675
+ refB?: string;
1676
+ /** The document's contextId for `conceptsOf`. */
1677
+ contextId?: string;
1678
+ /** The free-text question for `globalSummary` (ranks the KB's topic summaries against it). */
1679
+ query?: string;
1680
+ /** `subtree`: maximum depth below the resolved node. Default (and cap) 3. */
1681
+ depth?: number;
1682
+ /** `neighborhood`: expansion hops from the resolved entity. Default 1, max 2. */
1683
+ hops?: number;
1684
+ /** `docsUnder`: when true (default), include documents under the whole subtree, not just the node itself. */
1685
+ recursive?: boolean;
1686
+ /** `docsUnder`: maximum documents returned. Default 25, max 100 (`totalDocs` always reports the full count). */
1687
+ limit?: number;
1688
+ }
1689
+ /** One node matched by a graph query (`resolve`, and the anchors of other ops). @category AI */
1690
+ export interface KnowledgeBaseGraphQueryMatch {
1691
+ /** What kind of node matched. */
1692
+ kind: 'document' | 'entity' | 'topic' | 'facetRoot' | 'facetValue';
1693
+ /** Display name (document title, entity/topic/facet name). */
1694
+ name: string;
1695
+ /**
1696
+ * Persistable handle, present only where one exists: facet nodeIds (stable across rebuilds) and
1697
+ * document contextIds. Topic and entity refs re-resolve by name — their internal ids are omitted.
1698
+ */
1699
+ id?: string;
1700
+ /** The metadata field a facet node belongs to. */
1701
+ facetKey?: string;
1702
+ /** Node description (may be empty for facet leaves). */
1703
+ description?: string;
1704
+ /** Documents under the node, where tracked (topics and facet nodes). */
1705
+ docCount?: number;
1706
+ /** Topics: members of the node (entities at level 0, child topics at higher levels). */
1707
+ memberCount?: number;
1708
+ }
1709
+ /** A node in a `subtree` response: the resolved node with its children, recursively. @category AI */
1710
+ export interface KnowledgeBaseGraphQuerySubtreeNode {
1711
+ /** Display name. */
1712
+ name: string;
1713
+ /** Persistable facet nodeId (present on facet nodes; see {@link KnowledgeBaseGraphQueryMatch.id}). */
1714
+ id?: string;
1715
+ /** Documents under this node. */
1716
+ docCount?: number;
1717
+ /** Raw variants consolidated into a facet value ("United States of America" under "United States"). */
1718
+ aliases?: string[];
1719
+ /** Child nodes, depth-limited by the request. */
1720
+ children?: Array<KnowledgeBaseGraphQuerySubtreeNode>;
1721
+ }
1722
+ /** A document summary returned by `docsUnder`. @category AI */
1723
+ export interface KnowledgeBaseGraphQueryDoc {
1724
+ /** The document's contextId (usable with `conceptsOf` and the KB context APIs). */
1725
+ contextId: string;
1726
+ /** Document title, when one exists. */
1727
+ title?: string;
1728
+ /** The document node's LLM description ('' when generation failed). */
1729
+ description?: string;
1730
+ }
1731
+ /** A document's concept memberships (`conceptsOf`): facet paths + topics. @category AI */
1732
+ export interface KnowledgeBaseGraphQueryConcepts {
1733
+ /** The facet values the document carries, with their persistable leaf ids. */
1734
+ facets: Array<{
1735
+ facetKey: string;
1736
+ value: string;
1737
+ id: string;
1738
+ }>;
1739
+ /** Names of the topics (flat themes) the document belongs to. Thematic — refs re-resolve by name. */
1740
+ topics: Array<string>;
1741
+ }
1742
+ /**
1743
+ * One topic (community) summary returned by the `globalSummary` op — the themes-level "global" answer
1744
+ * content, ranked against the query. @category AI
1745
+ */
1746
+ export interface KnowledgeBaseGraphQueryGlobalSummary {
1747
+ /** Topic display name. Thematic — re-resolves by name across rebuilds. */
1748
+ topic: string;
1749
+ /** The topic's LLM-generated summary. */
1750
+ summary: string;
1751
+ }
1752
+ /**
1753
+ * A `pathBetween` answer. Two-tier: an entity path when one exists (explanatory — the chain of typed
1754
+ * relationships), else concept/topic co-membership labeled `thematic` (the refs share concepts but no
1755
+ * entity chain connects them).
1756
+ * @category AI
1757
+ */
1758
+ export interface KnowledgeBaseGraphQueryPath {
1759
+ /** Which tier answered: `'entity'` (relationship chain) or `'thematic'` (shared concepts only). */
1760
+ tier: 'entity' | 'thematic';
1761
+ /** Entity tier: the relationship chain, in order. */
1762
+ steps?: Array<{
1763
+ from: string;
1764
+ type: string;
1765
+ to: string;
1766
+ }>;
1767
+ /** Thematic tier: names of concepts both refs sit under. */
1768
+ sharedConcepts?: Array<string>;
1769
+ }
1770
+ /**
1771
+ * Response structure for a graph query. `op` echoes the request; exactly the fields that op produces
1772
+ * are set (e.g. `matches` for `resolve`, `tree` for `subtree`).
1773
+ * @category AI
1774
+ */
1775
+ export interface QueryKnowledgeBaseGraphResponse {
1776
+ /** The operation that ran. */
1777
+ op: KnowledgeBaseGraphQueryOp;
1778
+ /** `overview`: the rendered knowledge-graph map (names + counts). */
1779
+ overview?: string;
1780
+ /** `resolve`: matching nodes across all kinds, best first. */
1781
+ matches?: Array<KnowledgeBaseGraphQueryMatch>;
1782
+ /** `describe`: the resolved node. */
1783
+ node?: KnowledgeBaseGraphQueryMatch;
1784
+ /** `describe`: ancestor names root-first (facet path / topic hierarchy), when the node has one. */
1785
+ path?: Array<string>;
1786
+ /** `describe`: immediate related nodes — children with counts, a document's concepts, an entity's edges. */
1787
+ related?: Array<{
1788
+ relation: string;
1789
+ name: string;
1790
+ docCount?: number;
1791
+ }>;
1792
+ /** `subtree`: the resolved node's subtree with doc counts. */
1793
+ tree?: KnowledgeBaseGraphQuerySubtreeNode;
1794
+ /** `docsUnder`: documents in the resolved node's closure (capped by `limit`). */
1795
+ documents?: Array<KnowledgeBaseGraphQueryDoc>;
1796
+ /** `docsUnder`: the full closure size (compare with `documents.length` for truncation). */
1797
+ totalDocs?: number;
1798
+ /** `conceptsOf`: the document's concept memberships. */
1799
+ concepts?: KnowledgeBaseGraphQueryConcepts;
1800
+ /** `neighborhood`: the entity subgraph around the resolved entity. */
1801
+ graph?: ExploreKnowledgeBaseGraphResponse;
1802
+ /** `pathBetween`: the two-tier path answer; absent when the refs are entirely unconnected. */
1803
+ pathBetween?: KnowledgeBaseGraphQueryPath;
1804
+ /** `globalSummary`: the KB's topic summaries ranked against the query, most relevant first. */
1805
+ summaries?: Array<KnowledgeBaseGraphQueryGlobalSummary>;
1806
+ }
1807
+ /**
1808
+ * One context to stage through bulk ingestion. Unlike the sync request, `imageExtractionModel` is not
1809
+ * accepted: a job bills one fixed vision model for every image it describes.
1810
+ * @category AI
1811
+ */
1812
+ export interface BulkIngestionContext {
1813
+ /**
1814
+ * The id of the context. Optional: when omitted, the server generates one and rejects the upload if
1815
+ * another context in the knowledge base already holds identical content (content-level dedup). Provide
1816
+ * an explicit id to address a specific context — that overwrites it unconditionally and allows duplicate
1817
+ * content across different ids, exactly as the synchronous `upsertContexts` treats a supplied id. Must
1818
+ * be unique within one request (each staged context becomes one per-file row keyed by this id), at most
1819
+ * 512 UTF-8 bytes of letters, digits, `_`, `.`, `:`, `@` or `-` only, and the overwrite lands
1820
+ * asynchronously when the job finalizes the file.
1821
+ */
1822
+ contextId?: AiContextId;
1823
+ /** `'text'` (the default) stages a text context; `'file'` consumes the next uploaded file positionally. */
1824
+ type?: 'text' | 'file';
1825
+ /** Title for a text context (required); optional display title for a file context. */
1826
+ title?: string;
1827
+ /** The text content to stage; required for `type: 'text'`. */
1828
+ text?: string;
1829
+ /** Whether to extract images: inline markdown/HTML images for text contexts, embedded images for files. */
1830
+ extractImages?: boolean;
1831
+ /** Hint about a text context's format; only meaningful for `type: 'text'`. */
1832
+ format?: 'markdown' | 'html' | 'plain';
1833
+ /**
1834
+ * Key returned by bulk/createUploadUrls; the server ingests the staged object as this context's file.
1835
+ * Mutually exclusive with a positional multipart file.
1836
+ */
1837
+ stagedObjectKey?: string;
1838
+ /**
1839
+ * The preferred method for extracting data from a file context; mirrors the sync lane's field of the
1840
+ * same name, so a caller's choice survives whichever lane a deployment routes the upload through.
1841
+ */
1842
+ preferredExtractionMethod?: DocumentExtractionMethod;
1843
+ /**
1844
+ * The RAG type and chunk overlap this context is chunked and indexed with; mirrors the sync request's
1845
+ * `options`, with the same defaults (the knowledge base's `ragType`, and the overlap that type implies).
1846
+ * `chunkOverlap` must be a number below the 4,000-character chunk size.
1847
+ */
1848
+ options?: BaseAiKnowledgeBaseContextOptions;
1849
+ /**
1850
+ * Minimum width/height in pixels for an extracted image to be kept; mirrors the sync request's field of
1851
+ * the same name. Smaller images are skipped, and an inline markdown/HTML image below it keeps its raw
1852
+ * reference in the text.
1853
+ */
1854
+ imageMinSizePixels?: number;
1855
+ /**
1856
+ * Whether Squid discards a file context's downloadable original once it is extracted (the extracted
1857
+ * text and images are stored either way); mirrors {@link AiKnowledgeBaseFileContextRequest.discardOriginalFile},
1858
+ * with the same consequences. Ignored for a text context.
1859
+ */
1860
+ discardOriginalFile?: boolean;
1861
+ /**
1862
+ * Optional metadata associated with the context item; mirrors {@link BaseAiKnowledgeBaseContextRequest.metadata}.
1863
+ * Squid-reserved keys are stripped server-side, and values are validated/normalized against the target
1864
+ * knowledge base's `metadataFields` schema when one is declared.
1865
+ */
1866
+ metadata?: Record<string, unknown>;
1867
+ /**
1868
+ * Access scopes granting read access to this context, stamped onto every chunk it produces when the
1869
+ * job finalizes; mirrors {@link BaseAiKnowledgeBaseContextRequest.scopes}, with the same semantics:
1870
+ * omitted keeps whatever scopes the context already had, an empty array makes it visible to every
1871
+ * caller. On a knowledge base with `accessControl.mode: 'enforced'`, a context whose scopes resolve
1872
+ * to nothing at finalize is stamped unreadable rather than public.
1873
+ */
1874
+ scopes?: Array<string>;
1875
+ }
1876
+ /**
1877
+ * Request structure for staging contexts through bulk ingestion: a durable, asynchronous lane that
1878
+ * processes contexts through provider batch APIs rather than inline, for high-volume ingestion. Poll
1879
+ * {@link BulkIngestionJobStatusResponse} with the returned job id for progress.
1880
+ * @category AI
1881
+ */
1882
+ export interface BulkIngestionUpsertContextsRequest {
1883
+ /** The id of the AiKnowledgeBase to ingest into. */
1884
+ knowledgeBaseId: string;
1885
+ /** The contexts to stage; each becomes one bulk-ingestion file. */
1886
+ contexts: Array<BulkIngestionContext>;
1887
+ /**
1888
+ * How quickly this job must finish. A hint, not a command: Squid honours it where the job's models and
1889
+ * its share of the ingestion pool allow, and otherwise runs the job the way it can. Read
1890
+ * {@link BulkIngestionJobStatusResponse.transport} to see what it actually ran as.
1891
+ */
1892
+ speed?: BulkIngestionSpeed;
1893
+ }
1894
+ /**
1895
+ * The optional half of a bulk-ingestion staging call.
1896
+ * @category AI
1897
+ */
1898
+ export interface BulkIngestionUpsertContextsOptions {
1899
+ /** See {@link BulkIngestionUpsertContextsRequest.speed}. */
1900
+ speed?: BulkIngestionSpeed;
1901
+ }
1902
+ /**
1903
+ * How quickly a bulk-ingestion job must finish, and so which provider tier Squid buys for it. The model,
1904
+ * the prompts and the resulting chunks are identical at every speed — only the queue in front of them
1905
+ * differs.
1906
+ *
1907
+ * - `economy` — provider batch, cheapest, tails up to 24 hours.
1908
+ * - `auto` — Squid decides from the job's size. The default.
1909
+ * - `fast` — runs inline, minutes rather than hours, at full list price.
1910
+ * @category AI
1911
+ */
1912
+ export declare const BULK_INGESTION_SPEEDS: readonly ["economy", "auto", "fast"];
1913
+ /** See {@link BULK_INGESTION_SPEEDS}. */
1914
+ export type BulkIngestionSpeed = (typeof BULK_INGESTION_SPEEDS)[number];
1915
+ /**
1916
+ * Response for a staged bulk-ingestion request.
1917
+ * @category AI
1918
+ */
1919
+ export interface BulkIngestionUpsertContextsResponse {
1920
+ /** The id of the staged bulk-ingestion job. */
1921
+ jobId: string;
1922
+ /**
1923
+ * Context ids assigned to the staged contexts, in the same order as the request's `contexts` array. A
1924
+ * context rejected as a duplicate still occupies its slot here, so this stays index-aligned with the
1925
+ * request; cross-reference `duplicates` by `contextId` to tell which ids were actually staged.
1926
+ */
1927
+ contextIds: Array<string>;
1928
+ /**
1929
+ * Contexts rejected because the knowledge base already holds identical content — either stored under
1930
+ * an existing context or accepted earlier in this same call. Absent when nothing was rejected.
1931
+ *
1932
+ * Same shape and `errorCode: 'DUPLICATE_CONTENT'` the synchronous `upsertContexts` returns, so a caller
1933
+ * handles a duplicate identically on both lanes. These contexts are NOT part of the job: they are not
1934
+ * extracted, not staged, and never appear in its per-file statuses.
1935
+ *
1936
+ * Covers TEXT contexts and MULTIPART file contexts (their bytes are in hand at staging). A file staged
1937
+ * by `stagedObjectKey` is the one exception: its bytes are first read by the deferred extraction pass,
1938
+ * so its duplicate surfaces asynchronously as a failed file with `errorCode: 'DUPLICATE_CONTENT'` in
1939
+ * the job's per-file statuses instead.
1940
+ */
1941
+ duplicates?: Array<UpsertContextStatusError>;
1942
+ }
1943
+ /**
1944
+ * Request structure for reading a bulk-ingestion job's progress.
1945
+ * @category AI
1946
+ */
1947
+ export interface BulkIngestionJobStatusRequest {
1948
+ /** The id of the bulk-ingestion job to inspect. */
1949
+ jobId: string;
1950
+ }
1951
+ /**
1952
+ * Progress counters for a bulk-ingestion job, aggregated from its files and logical requests.
1953
+ * @category AI
1954
+ */
1955
+ export interface BulkIngestionJobStatusCounts {
1956
+ /** Total files staged for the job. */
1957
+ files: number;
1958
+ /** Files whose contexts have been finalized into the knowledge base. */
1959
+ finalized: number;
1960
+ /** Files that terminally failed. */
1961
+ failed: number;
1962
+ /** Logical requests still pending submission. */
1963
+ requestsPending: number;
1964
+ /** Logical requests submitted to the provider and awaiting results. */
1965
+ requestsSubmitted: number;
1966
+ }
1967
+ /**
1968
+ * Machine-readable class of a bulk-ingestion file failure, for outcomes to treat differently from real
1969
+ * failures. Terminal — reported with `retryable: false` — are `'CONTENT_TOO_LARGE'` (past the per-context
1970
+ * ceiling), `'ENCRYPTED_DOCUMENT'`, `'IMAGE_OVER_PROVIDER_LIMIT'` (the OCR provider refuses an image in the
1971
+ * document as too large, even with the pages that draw it redrawn smaller), `'NO_EMBEDDABLE_CONTENT'`,
1972
+ * `'SOURCE_OVER_PROVIDER_LIMIT'` (the bytes exceed what the extraction provider accepts),
1973
+ * `'UNREADABLE_DOCUMENT'` (a PDF or Office file whose bytes cannot be opened as one), `'UNREADABLE_WORKBOOK'`
1974
+ * (a spreadsheet whose content the parser cannot read) and `'UNSUPPORTED_FILE_TYPE'`.
1975
+ * `'DUPLICATE_CONTENT'` is a skip rather than a failure: the KB already holds this content.
1976
+ * `'EXTRACTION_TIMED_OUT'` stays retryable — the deadline is contended, so a borderline document can
1977
+ * cross it under load. So do `'SOURCE_UNREACHABLE'` (the provider could not fetch the source, which a
1978
+ * fresh link can fix) and `'PROVIDER_ACCESS_DENIED'` (the provider refused the credential or its quota is
1979
+ * spent, a fault of the environment). `'JOB_FULL'`: the job's request ceiling had no room left for this
1980
+ * file, so re-submit it in a fresh job; a file that alone exceeds the ceiling fails this way in every job.
1981
+ * @category AI
1982
+ */
1983
+ export type BulkIngestionFileErrorCode = 'CONTENT_TOO_LARGE' | 'DUPLICATE_CONTENT' | 'ENCRYPTED_DOCUMENT' | 'EXTRACTION_TIMED_OUT' | 'IMAGE_OVER_PROVIDER_LIMIT' | 'JOB_FULL' | 'NO_EMBEDDABLE_CONTENT' | 'PROVIDER_ACCESS_DENIED' | 'SOURCE_OVER_PROVIDER_LIMIT' | 'SOURCE_UNREACHABLE' | 'UNREADABLE_DOCUMENT' | 'UNREADABLE_WORKBOOK' | 'UNSUPPORTED_FILE_TYPE';
1984
+ /**
1985
+ * Per-file/per-context status within a bulk-ingestion job, so a caller can see which file finished,
1986
+ * which is still processing, and why a file failed.
1987
+ * @category AI
1988
+ */
1989
+ export interface BulkIngestionFileStatus {
1990
+ /** The context id assigned to this file at staging. */
1991
+ contextId: string;
1992
+ /** The file's title — the uploaded file name, or the caller-supplied title for text contexts. */
1993
+ title: string;
1994
+ /** User-facing per-file status. */
1995
+ status: 'processing' | 'completed' | 'failed';
1996
+ /** Present only when status is 'failed': the terminal failure reason. */
1997
+ errorMessage?: string;
1998
+ /**
1999
+ * Machine-readable class of a failed file, for outcomes to treat differently from real failures.
2000
+ * Additive; absent for ordinary failures. See {@link BulkIngestionFileErrorCode}.
2001
+ */
2002
+ errorCode?: BulkIngestionFileErrorCode;
2003
+ /**
2004
+ * Present only on a failed file an extraction provider answered: a stable fingerprint of that answer
2005
+ * (provider, HTTP status and provider code), so a caller can tell the same failure repeating from a new one.
2006
+ */
2007
+ errorSignature?: string;
2008
+ /**
2009
+ * Present only on a failed file: the same bytes fail the same way, so a caller must park the file
2010
+ * instead of re-submitting it. Absence means retryable.
2011
+ */
2012
+ retryable?: false;
2013
+ /**
2014
+ * First images (capped) the context lacks a description for because describing them failed; a
2015
+ * `completed` file is otherwise fully ingested. Absent when every image succeeded.
2016
+ */
2017
+ imageFailures?: Array<ContextImageFailure>;
2018
+ /** Total number of failed images, which exceeds `imageFailures.length` when the list was capped. */
2019
+ imageFailureCount?: number;
2020
+ /**
2021
+ * Set on a `completed` file that is stored and searchable but that the job withheld from graph indexing;
2022
+ * the bulk counterpart of {@link UpsertKnowledgeBaseContextsResponse.graphIndexingSkippedContextIds}, and
2023
+ * `graphIndexingSkipReason` says why. Records the job's own outcome: it is written when the job's graph
2024
+ * run admits its files, which can be after the job completes (a poll of the job status sees it, the
2025
+ * terminal push may not), and it stays set even if a later graph build indexes the file.
2026
+ */
2027
+ graphIndexingSkipped?: boolean;
2028
+ /** Why graph indexing was withheld; present exactly when `graphIndexingSkipped` is. */
2029
+ graphIndexingSkipReason?: BulkIngestionGraphSkipReason;
2030
+ }
2031
+ /**
2032
+ * Why a bulk-ingested file was withheld from graph indexing. `'cap'`: the knowledge base is over its
2033
+ * per-KB graph chunk cap (or the cap could not be checked and the job failed closed), so the file stays
2034
+ * out until the cap allows it. `'queue'`: the graph-indexing queue was full when the file finalized; the
2035
+ * file is left to the graph auto-build sweep, which indexes it under the same cap once the job goes quiet.
2036
+ * @category AI
2037
+ */
2038
+ export type BulkIngestionGraphSkipReason = 'cap' | 'queue';
2039
+ /**
2040
+ * The durable ingestion status of a single file/text context, tracked independently of any one
2041
+ * bulk-ingestion job so it survives job purge. `'no_record'` means the knowledge base has never seen
2042
+ * this path — never persisted, only synthesized when a status query finds nothing. `'in_progress'`
2043
+ * covers every non-terminal bulk-ingestion stage (staged through embedding); the ledger only records
2044
+ * terminal outcomes, so finer sub-stages are not distinguished. `'completed'` and `'failed'` are terminal.
2045
+ * @category AI
2046
+ */
2047
+ export type AiKnowledgeBaseFileStatus = 'no_record' | 'in_progress' | 'completed' | 'failed';
2048
+ /**
2049
+ * The durable ingestion status of one file/text context at a path, returned by
2050
+ * {@link AiKnowledgeBaseReference.getFileStatus} and as one entry of
2051
+ * {@link AiKnowledgeBaseFolderStatusResponse.files}.
2052
+ * @category AI
2053
+ */
2054
+ export interface AiKnowledgeBaseFileStatusInfo {
2055
+ /** The context id, absent only when `status` is `'no_record'`. */
2056
+ contextId?: AiContextId;
2057
+ /** The file's path: `folderPath/filename`, or just `filename` at the upload root. */
2058
+ path: string;
2059
+ /** The file's current durable status. */
2060
+ status: AiKnowledgeBaseFileStatus;
2061
+ /** Present only when `status` is `'failed'`: the terminal failure reason. */
2062
+ errorMessage?: string;
2063
+ /**
2064
+ * Present only when `status` is `'failed'`: the machine-readable failure class, when known. A bulk
2065
+ * lane failure reports {@link BulkIngestionFileErrorCode}; a synchronous `upsertContexts` failure
2066
+ * reports {@link UpsertContextErrorCode} — the two lanes use distinct, mostly-overlapping codes.
2067
+ */
2068
+ errorCode?: BulkIngestionFileErrorCode | UpsertContextErrorCode;
2069
+ /** When this status was last recorded; absent when `status` is `'no_record'`. */
2070
+ updatedAt?: Date;
2071
+ }
2072
+ /**
2073
+ * Request to look up the durable ingestion status of a single file/text context by path.
2074
+ * @category AI
2075
+ */
2076
+ export interface GetKnowledgeBaseFileStatusRequest {
2077
+ /** The knowledge base to query. */
2078
+ knowledgeBaseId: AiKnowledgeBaseId;
2079
+ /** The file's path: `folderPath/filename`, or just `filename` at the upload root. */
2080
+ path: string;
2081
+ }
2082
+ /**
2083
+ * Request to search and aggregate the durable ingestion status of every file/text context matching
2084
+ * `folderPath`, read three ways and unioned: a folder subtree, a bare filename anywhere in the
2085
+ * knowledge base, and — when it contains a `/` — an exact `folderPath/filename` path.
2086
+ * @category AI
2087
+ */
2088
+ export interface GetKnowledgeBaseFolderStatusRequest {
2089
+ /** The knowledge base to query. */
2090
+ knowledgeBaseId: AiKnowledgeBaseId;
2091
+ /**
2092
+ * The folder subtree, bare filename, or exact file path to search for. A subtree match uses the same
2093
+ * segment-safe matching as `$underPath` metadata filters; a value containing `/` also matches that
2094
+ * exact file, so pasting a path from an earlier result finds that one file, not a folder of the same name.
2095
+ */
2096
+ folderPath: string;
2097
+ /**
2098
+ * Maximum number of files to return in `files`, prioritizing failures (the ones needing attention)
2099
+ * before filling remaining room with other statuses. `counts`/`totalFiles` always cover every file
2100
+ * regardless of this cap. Defaults to 50.
2101
+ */
2102
+ fileLimit?: number;
2103
+ }
2104
+ /**
2105
+ * Aggregate ingestion status for every file/text context matching a searched folder subtree, bare
2106
+ * filename, or exact file path (see {@link GetKnowledgeBaseFolderStatusRequest.folderPath}), combining
2107
+ * a name/path search with per-status counts and the failures that need attention.
2108
+ * @category AI
2109
+ */
2110
+ export interface AiKnowledgeBaseFolderStatusResponse {
2111
+ /** The folder subtree, filename, or exact path that was searched. */
2112
+ folderPath: string;
2113
+ /** Count of matching files by terminal/in-progress status (excludes `no_record`), uncapped. */
2114
+ counts: Record<Exclude<AiKnowledgeBaseFileStatus, 'no_record'>, number>;
2115
+ /** Total files found, across all statuses in `counts`. */
2116
+ totalFiles: number;
2117
+ /** False when nothing matched — the folder-level `no_record` case. */
2118
+ hasAnyRecords: boolean;
2119
+ /** Files under the folder, capped at `fileLimit` and prioritizing failures. */
2120
+ files: Array<AiKnowledgeBaseFileStatusInfo>;
2121
+ /** True when `files` was capped and more files exist under the folder than are returned. */
2122
+ truncated: boolean;
2123
+ }
2124
+ /**
2125
+ * Why a whole bulk-ingestion staging call was refused, on the `details` of its 400 response. The
2126
+ * refusal names the one context that caused it, so a caller recording per-file outcomes charges only
2127
+ * that file.
2128
+ * @category AI
2129
+ */
2130
+ export interface BulkIngestionStagingRefusal {
2131
+ /** The staged object exceeds the per-file source ceiling. */
2132
+ errorCode: 'STAGED_OBJECT_TOO_LARGE';
2133
+ /** The same bytes are refused the same way, so the named file must be parked rather than re-staged. */
2134
+ retryable: false;
2135
+ /** The context whose file caused the refusal. */
2136
+ contextId: string;
2137
+ }
2138
+ /**
2139
+ * One provider batch created for a bulk-ingestion job, so a caller can tell a job waiting on a
2140
+ * submitted provider batch (healthy — the designed cost/latency tradeoff of the batch lane, with
2141
+ * turnaround up to 24 hours) from a job that is actually stuck, and see since when.
2142
+ * @category AI
2143
+ */
2144
+ export interface BulkIngestionProviderBatchStatus {
2145
+ /** The provider running the batch. Mirrors the core batch row's union, like {@link state}. */
2146
+ provider: 'openai' | 'anthropic' | 'mistral' | 'voyage';
2147
+ /** The provider API the batch rides. Mirrors the core batch row's union, like {@link state}. */
2148
+ endpoint: '/v1/embeddings' | '/v1/messages/batches' | '/v1/chat/completions' | '/v1/ocr';
2149
+ /**
2150
+ * The batch's lifecycle state: `intent` (created, not yet submitted), `submitted` (waiting on the
2151
+ * provider), `ended` (provider finished, results not yet absorbed), or terminal
2152
+ * (`reconciled`/`cancelled`/`failed`).
2153
+ */
2154
+ state: 'intent' | 'submitted' | 'ended' | 'reconciled' | 'cancelled' | 'failed';
2155
+ /** The provider's own batch id; absent until the batch is submitted. */
2156
+ providerBatchId?: string;
2157
+ /** When the batch was created — the "since when has this been waiting" clock for an in-flight batch. */
2158
+ createdAt: Date;
2159
+ /**
2160
+ * When the batch row was last written. NOT a state-transition time: the poller refreshes it on every
2161
+ * poll of an in-flight batch, so on a healthy job it is always recent — it freezing means polling
2162
+ * stopped, not that the batch is waiting. Read wait duration off {@link createdAt}.
2163
+ */
2164
+ updatedAt: Date;
2165
+ /** The lanes of the requests the batch carries; empty when a batch of an older core cannot tell. */
2166
+ lanes?: Array<BulkIngestionRequestLane>;
2167
+ /**
2168
+ * The provider's status at the newest poll, as the adapter reports it: provider-raw for OpenAI, normalized
2169
+ * (`in_progress`, `completed`, …) for Anthropic and Mistral.
2170
+ */
2171
+ providerStatus?: string;
2172
+ /** When a poll first saw {@link providerStatus}. */
2173
+ providerStatusChangedAt?: Date;
2174
+ /** Why the provider failed the batch as a whole, in its own words; absent on a batch it did not fail. */
2175
+ providerError?: string;
2176
+ /** When the provider started running the batch; absent while it has not. */
2177
+ providerInProgressAt?: Date;
2178
+ /** Per-request progress at the newest poll; absent for a provider that does not report it. */
2179
+ requestCounts?: BulkIngestionProviderBatchRequestCounts;
2180
+ /** When the poll that read {@link requestCounts} ran. */
2181
+ requestCountsAt?: Date;
2182
+ }
2183
+ /**
2184
+ * The lane a bulk-ingestion request belongs to; core's `BulkIngestionLane` is this type.
2185
+ * @category AI
2186
+ */
2187
+ export type BulkIngestionRequestLane = 'embeddings' | 'imageDescription' | 'spreadsheetSummary' | 'metadataExtraction' | 'chunkContext' | 'documentOcr';
2188
+ /**
2189
+ * A provider batch's per-request progress as the provider reports it.
2190
+ * @category AI
2191
+ */
2192
+ export interface BulkIngestionProviderBatchRequestCounts {
2193
+ /** Requests in the batch. */
2194
+ total: number;
2195
+ /**
2196
+ * Requests the provider ran to a result, succeeded or failed. Requests it reports as cancelled or expired unrun are
2197
+ * left out, so `total − completed` is not the count still in flight.
2198
+ */
2199
+ completed: number;
2200
+ /** Of {@link completed}, the ones that failed, when the provider reports that breakdown. */
2201
+ failed?: number;
2202
+ }
2203
+ /**
2204
+ * Provider-side progress of one job's batches on one provider route (provider, endpoint and model). A route
2205
+ * is the unit the provider queues, and one batch can carry several lanes, so progress is reported per route.
2206
+ * @category AI
2207
+ */
2208
+ export interface BulkIngestionProviderRouteThroughput {
2209
+ /** The provider running the route's batches. */
2210
+ provider: BulkIngestionProviderBatchStatus['provider'];
2211
+ /** The provider API the route's batches ride. */
2212
+ endpoint: BulkIngestionProviderBatchStatus['endpoint'];
2213
+ /** The model the route's batches run on. */
2214
+ model: string;
2215
+ /** The lanes the route's batches carry. */
2216
+ lanes: Array<BulkIngestionRequestLane>;
2217
+ /** The route's batches created or submitted and not yet ended at the provider. */
2218
+ batchesInFlight: number;
2219
+ /** Requests in those batches the provider has not settled yet. */
2220
+ requestsInFlight: number;
2221
+ /** Requests the provider ran to a result, succeeded or failed, across the route's batches. */
2222
+ requestsCompleted: number;
2223
+ /** Of {@link requestsCompleted}, the ones that failed; absent when no batch reports that breakdown. */
2224
+ requestsFailed?: number;
2225
+ /**
2226
+ * Requests the provider completed per minute over the last {@link BulkIngestionProviderThroughput.windowMinutes};
2227
+ * absent when no batch of the route reports counts.
2228
+ */
2229
+ completedPerMinute?: number;
2230
+ /**
2231
+ * The oldest view of an in-flight batch: when its counts were read, else when its status last was, else when it
2232
+ * was created. Older than a few minutes means polls lag or return no counts, not that the provider stalled:
2233
+ * {@link completedPerMinute} then misses what the provider did since.
2234
+ */
2235
+ countsObservedAt?: Date;
2236
+ }
2237
+ /**
2238
+ * One in-flight provider-batch budget of the app on the shared system credential.
2239
+ * @category AI
2240
+ */
2241
+ export interface BulkIngestionInFlightBatchBudget {
2242
+ /** The lanes whose batches the budget gates. */
2243
+ lanes: Array<BulkIngestionRequestLane>;
2244
+ /** Batches of the WHOLE app holding the budget: another job of the app holds slots too. */
2245
+ inFlight: number;
2246
+ /** How many batches the budget admits right now; a lane whose budget is full waits for a slot. */
2247
+ limit: number;
2248
+ }
2249
+ /**
2250
+ * Whether a running job's provider batches are draining: per-route progress and the app's in-flight budgets.
2251
+ * @category AI
2252
+ */
2253
+ export interface BulkIngestionProviderThroughput {
2254
+ /** The span, in minutes, the per-route completion rates cover. */
2255
+ windowMinutes: number;
2256
+ /** Progress per provider route the job has batches on. */
2257
+ routes: Array<BulkIngestionProviderRouteThroughput>;
2258
+ /** The app's in-flight budgets; absent when the job's batches run on the app's own provider key, which is not capped. */
2259
+ inFlightBatchBudgets?: Array<BulkIngestionInFlightBatchBudget>;
2260
+ }
2261
+ /**
2262
+ * Response describing a bulk-ingestion job's current state and progress counts.
2263
+ * @category AI
2264
+ */
2265
+ export interface BulkIngestionJobStatusResponse {
2266
+ /** The job's lifecycle state (e.g. running, completed, failed, cancelled). */
2267
+ state: string;
2268
+ /**
2269
+ * The job's execution transport: `'batch'` rides provider batches (half price, tails up to 24
2270
+ * hours), `'sync'` executes inline within minutes. Decided at staging from the job's size, with one
2271
+ * transition — a defer-eligible job whose OCR routing lands on the provider batch is promoted
2272
+ * `'sync'` to `'batch'` — and held from then on. Descriptive metadata ONLY: it says how the job
2273
+ * runs, never whether a batch is draining right now, so it must not gate any wait/timeout policy;
2274
+ * that is {@link activeProviderBatchCount}. Optional on the wire: consumers must tolerate its
2275
+ * absence.
2276
+ */
2277
+ transport?: 'batch' | 'sync';
2278
+ /**
2279
+ * The lanes a `'batch'` job ROUTES inline — at the synchronous price, within minutes — rather than onto a
2280
+ * provider batch: `embeddings`, whose batches are too small for the discount to beat the queue tail.
2281
+ * Absent when every lane batches, and on a `'sync'` job (every lane of which runs inline). The job's
2282
+ * routing policy, not a record of what ran: a lane handed to the inline transport by a cancelled
2283
+ * provider-batch tail executes inline without being named here. Descriptive metadata, like {@link transport}.
2284
+ */
2285
+ inlineLanes?: Array<'embeddings' | 'imageDescription' | 'spreadsheetSummary' | 'metadataExtraction'>;
2286
+ /** Progress counters aggregated from the job's files and logical requests. */
2287
+ counts: BulkIngestionJobStatusCounts;
2288
+ /** Provider batch ids created for this job, across every batch state — including already-drained ones. */
2289
+ providerBatchIds: Array<string>;
2290
+ /**
2291
+ * Number of provider batches still in flight (created, submitted, or awaiting result reconciliation).
2292
+ * THE deferral signal: work is draining through a provider batch right now exactly when this is
2293
+ * positive — unlike {@link providerBatchIds}, which keeps terminal batches, and unlike
2294
+ * {@link transport}, which is descriptive metadata. Optional on the wire: consumers must tolerate
2295
+ * its absence.
2296
+ */
2297
+ activeProviderBatchCount?: number;
2298
+ /**
2299
+ * Per-batch detail for every provider batch of the job, so a caller can tell a healthy wait on a
2300
+ * submitted provider batch from a stall — and see since when. A SUPERSET of
2301
+ * {@link providerBatchIds}, not index-aligned with it: an `intent` batch appears here with no
2302
+ * `providerBatchId` while that list omits it. Optional on the wire: consumers must tolerate its
2303
+ * absence.
2304
+ */
2305
+ providerBatches?: Array<BulkIngestionProviderBatchStatus>;
2306
+ /**
2307
+ * Coarse answer to "what is this job doing right now": `awaiting-provider-batch` while the
2308
+ * PROVIDER is working — an `intent` or `submitted` batch (deferred OCR included; it wins whatever stage the
2309
+ * files carry) or batch-route work still queued for submission — `extracting` while files still
2310
+ * await or undergo extraction with no submitted batch, and `indexing` otherwise (inline/flex
2311
+ * requests executing, `ended` batches' results being absorbed, contexts being written — our own
2312
+ * work, however long it takes). Present only while the job {@link state} is `running`; the other
2313
+ * non-terminal states (`finalizing`, `cancelling`) already name what the job is doing. Optional on
2314
+ * the wire: consumers must tolerate its absence.
2315
+ */
2316
+ phase?: 'extracting' | 'awaiting-provider-batch' | 'indexing';
2317
+ /**
2318
+ * Provider-side progress of the job's batches, so a saturated in-flight budget the provider is draining
2319
+ * reads differently from one it completes nothing in. Present only while a `'batch'` job is `running`.
2320
+ * Optional on the wire: consumers must tolerate its absence.
2321
+ */
2322
+ providerThroughput?: BulkIngestionProviderThroughput;
2323
+ /** Per-file status, one entry per staged context (bounded by the job's file cap). */
2324
+ files: Array<BulkIngestionFileStatus>;
2325
+ }
2326
+ /**
2327
+ * Request structure for cancelling a running bulk-ingestion job.
2328
+ * @category AI
2329
+ */
2330
+ export interface BulkIngestionCancelRequest {
2331
+ /** The id of the bulk-ingestion job to cancel. */
2332
+ jobId: string;
2333
+ }
2334
+ /**
2335
+ * Request structure for subscribing to push updates on a bulk-ingestion job. Once subscribed, the caller's
2336
+ * client id receives a `bulkIngestionStatus` socket event on each orchestrator tick that touches the job,
2337
+ * plus one final event on completion/failure/cancellation — in addition to (not instead of) polling
2338
+ * {@link BulkIngestionJobStatusResponse} through `bulk/getJob`.
2339
+ * @category AI
2340
+ */
2341
+ export interface BulkIngestionSubscribeRequest {
2342
+ /** The id of the bulk-ingestion job to subscribe to. */
2343
+ jobId: string;
2344
+ }
2345
+ /**
2346
+ * Request structure for minting presigned upload URLs for direct-to-storage bulk ingestion: the caller
2347
+ * PUTs each file's bytes straight to storage, then references it in {@link BulkIngestionContext} via
2348
+ * `stagedObjectKey`, bypassing multipart upload through core.
2349
+ * @category AI
2350
+ */
2351
+ export interface BulkIngestionCreateUploadUrlsRequest {
2352
+ /** The files to mint upload URLs for (at most 500 per call). */
2353
+ files: Array<{
2354
+ fileName: string;
2355
+ }>;
2356
+ }
2357
+ /**
2358
+ * Response listing a presigned upload URL and staged-object key for each requested file, positionally
2359
+ * aligned with the request's `files` array.
2360
+ * @category AI
2361
+ */
2362
+ export interface BulkIngestionCreateUploadUrlsResponse {
2363
+ /** One entry per requested file. */
2364
+ uploads: Array<{
2365
+ /** The original file name, echoed back from the request. */
2366
+ fileName: string;
2367
+ /** Presigned URL the caller PUTs the file's bytes to; expires shortly after minting. */
2368
+ uploadUrl: string;
2369
+ /**
2370
+ * Headers the PUT MUST carry in addition to the caller's own `Content-Type`. Empty on storage
2371
+ * backends that mandate none (S3); on Azure Blob Storage the PUT is rejected with 400
2372
+ * `MissingRequiredHeader` unless these are sent.
2373
+ */
2374
+ requiredHeaders: Record<string, string>;
2375
+ /** Key to pass as {@link BulkIngestionContext.stagedObjectKey} once the PUT completes. */
2376
+ stagedObjectKey: string;
2377
+ }>;
2378
+ }