@aiquants/enrichment-core 0.1.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +225 -5
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3343 -474
- package/dist/index.d.ts +3343 -474
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var u=class extends Error{statusCode;responseBody;parsedBody;constructor(t,n,a,i){super(t),this.name="EnrichmentClientError",this.statusCode=n,this.responseBody=a,this.parsedBody=i}},g=class{baseUrl;apiKey;fetchFn;timeoutMs;constructor(t){if(!t||typeof t.baseUrl!="string"||t.baseUrl.trim().length===0)throw new Error("baseUrl is required and must be a non-empty string for EnrichmentClient.");let n=t.baseUrl.trim().replace(/\/$/,"");if(t.apiKey&&n.startsWith("http://")&&!n.includes("localhost")&&!n.includes("127.0.0.1"))throw new Error("Security Violation: Transmitting Bearer tokens over unencrypted HTTP to non-localhost hosts is strictly prohibited.");this.baseUrl=n,this.apiKey=t.apiKey,this.fetchFn=t.fetchFn??fetch,this.timeoutMs=t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:3e4}async request(t,n,a,i){let c=`${this.baseUrl}${t}`;if(i){let o=new URLSearchParams;for(let[P,h]of Object.entries(i))h!=null&&h.trim().length>0&&o.append(P,h);let s=o.toString();s.length>0&&(c+=`?${s}`)}let _={Accept:"application/json"};this.apiKey&&(_.Authorization=`Bearer ${this.apiKey}`),a!==void 0&&(_["Content-Type"]="application/json");let b=new AbortController,O=setTimeout(()=>b.abort(),this.timeoutMs),p;try{p=await this.fetchFn(c,{method:n,headers:_,body:a!==void 0?JSON.stringify(a):void 0,signal:b.signal})}catch(o){let s=o instanceof Error?o.message:String(o);throw new u(`Network request failed for ${n} ${c}: ${s}`,0,"")}finally{clearTimeout(O)}if(!p.ok){let o=await p.text().catch(()=>""),s;try{s=JSON.parse(o)}catch{}throw new u(`API request failed with status ${p.status}: ${o}`,p.status,o,s)}let E=await p.text().catch(()=>"");if(E.trim().length!==0)try{return JSON.parse(E)}catch(o){let s=o instanceof Error?o.message:String(o);throw new u(`Failed to parse response JSON from ${c}: ${s}`,p.status,E)}}};import{z as e}from"zod";import{z as R}from"zod";var k=R.enum(["google_cloud","google_vision","yomitoku_local","faster_whisper_local","google_speech","ollama_local","openai","anthropic","azure_openai","bedrock","custom_openai_compatible"]),f=R.enum(["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"]),x="RESTRICTED";var Z={rrfK:{min:1,max:200,default:60},alpha:{min:0,max:1,default:.7},threshold:{min:0,max:1},limit:{min:1,max:50,default:10}},T=f.options.filter(r=>r!==x);if(T.length===0)throw new Error("The confidentiality vocabulary left nothing filterable after removing the quarantined level; a validator built from this list would reject every request.");var ee=T,v=["KEYWORD","SPARSE","DENSE","HYBRID","GRAPH_TRAVERSE"],S={KEYWORD:{dense:!1,sparse:!1,graph:!1,lexical:!0},SPARSE:{dense:!1,sparse:!0,graph:!1,lexical:!1},DENSE:{dense:!0,sparse:!1,graph:!1,lexical:!1},HYBRID:{dense:!0,sparse:!0,graph:!0,lexical:!0},GRAPH_TRAVERSE:{dense:!1,sparse:!1,graph:!0,lexical:!1}};function te(r){let t=S[r];return t.dense||t.sparse||t.graph}function ne(r){let t=S[r];return t.dense&&!t.sparse}function re(r,t){let n=S[r],a=(n.dense||n.sparse)&&t.vector,i=n.graph&&t.graph;return a||i?a?i?{mode:r,discardGraph:!1}:n.dense&&n.sparse?{mode:r,discardGraph:!0}:{mode:n.dense?"DENSE":"SPARSE",discardGraph:!1}:{mode:"GRAPH_TRAVERSE",discardGraph:!1}:null}function ae(r){let t=S[r];return[t.dense,t.sparse,t.graph,t.lexical].filter(Boolean).length>1}var y=e.string().trim().min(1,"tenant_id must be a non-empty string"),m=e.string().trim().min(1,"file_uri must be a non-empty string"),ce=e.enum(["PENDING","EXTRACTING","ENRICHING","PROJECTING","SYNCED","FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"]),A=e.object({page:e.number().int().positive().optional(),x:e.number().nonnegative().optional(),y:e.number().nonnegative().optional(),width:e.number().positive().optional(),height:e.number().positive().optional(),start_sec:e.number().nonnegative().optional(),end_sec:e.number().nonnegative().optional(),frame_index:e.number().int().nonnegative().optional(),timestamp_sec:e.number().nonnegative().optional(),scene_confidence:e.number().min(0).max(1).optional()}),U=e.object({title:e.string().trim().min(1),start_sec:e.number().nonnegative(),end_sec:e.number().nonnegative(),summary:e.string()}),z=e.object({start_sec:e.number().nonnegative(),end_sec:e.number().nonnegative(),speaker:e.string().trim().min(1),text:e.string()}),q=e.object({label:e.string(),value:e.number(),currency:e.string()}),pe=e.object({document_type:e.string().optional(),title:e.string().optional(),organization:e.string().optional(),key_entities:e.array(e.string()).optional(),dates:e.array(e.string()).optional(),amounts:e.array(q).optional(),media_type:e.enum(["video","audio"]).optional(),duration_sec:e.number().nonnegative().optional(),chapters:e.array(U).optional(),transcript_segments:e.array(z).optional()}),H=e.enum(["CLOSED","OPEN","HALF_OPEN"]),G=e.enum(["FULL_HYBRID","VECTOR_ONLY","GRAPH_ONLY","STANDARD_SEMANTIC","DEGRADED_KEYWORD_ONLY"]),K=e.enum(v),B=e.object({search_mode:K,quality_tier:G,is_degraded:e.boolean(),degradation_reason:e.string().nullable().optional(),circuit_breaker_status:e.record(H).optional(),latency_ms:e.number().nonnegative()}),I=e.enum(["CONTRACT_LEGAL","EMAIL_THREAD","DAILY_REPORT","FINANCIAL_REPORT","TECHNICAL_SPEC","MASTER_DATA","MEDIA_ASSET","GENERAL_DOCUMENT"]),V=e.enum(["hierarchical","conversation","section","fixed_size","table_aware","semantic","none","multimodal"]),C=e.object({id:e.number().int().positive(),tenant_id:y,parent_metadata_id:e.number().int().positive().nullable().optional(),file_uri:m,file_uri_hash:e.string(),revision:e.number().int().nonnegative(),is_current:e.boolean(),is_deleted:e.boolean(),is_derived:e.boolean(),file_name:e.string(),file_path:e.string(),folder_path:e.string().nullable().optional(),confidentiality_level:f,department_id:e.number().int().positive().nullable().optional(),file_size:e.number().int().nonnegative(),mime_type:e.string(),asset_type:e.string().nullable().optional(),asset_index:e.number().int().nonnegative().nullable().optional(),bounding_box:A.nullable().optional(),created_at:e.string(),updated_at:e.string()}),$=e.object({chunk_uid:e.string().min(1),file_uri:m,score:e.number(),content:e.string(),chunk_index:e.number().int().nonnegative(),clause_identifier:e.string().nullable().optional(),authority_tier:e.number().int().positive().nullable().optional(),breadcrumb_path:e.string().nullable().optional(),bounding_box:A.nullable().optional()}),N=e.object({query:e.string().trim().min(1,"query must not be empty"),tenant_id:y,domain_key:I.optional(),limit:e.number().int().positive().default(10),department_id:e.number().int().positive().optional(),user_roles:e.array(e.string()).default([])}),D=e.object({hits:e.array($),metadata:B}),L=e.object({file_uri:m,tenant_id:y,force:e.boolean().default(!1)}),M=e.object({file_uri:m,domain_key:I,strategy_name:e.string(),chunking_strategy:V.optional(),applied_rule_name:e.string().nullable().optional(),assigned_department_id:e.number().int().positive().nullable().optional()});var w=class extends g{async search(t){let n=N.parse(t),a=await this.request("/ai/search","POST",n);return D.parse(a)}async reclassify(t){let n=L.parse(t),a=await this.request("/ai/reclassify","POST",n);return M.parse(a)}async getFileMetadata(t,n){let a=m.parse(t),i=y.parse(n),c=await this.request("/ai/metadata","GET",void 0,{file_uri:a,tenant_id:i});return C.parse(c)}async getMetadata(t,n){return this.getFileMetadata(t,n)}};var F=[{key:"enable_summary_generation",featureFlagKey:null,label:"\u8981\u7D04\u751F\u6210"},{key:"enable_structured_extraction",featureFlagKey:null,label:"\u69CB\u9020\u5316\u62BD\u51FA"},{key:"enable_asset_extraction",featureFlagKey:"ENABLE_ASSET_EXTRACTION",label:"\u30A2\u30BB\u30C3\u30C8\u62BD\u51FA"},{key:"enable_vector_indexing",featureFlagKey:"ENABLE_VECTOR_INDEXING",label:"\u30D9\u30AF\u30C8\u30EB\u7D22\u5F15"},{key:"enable_graph_indexing",featureFlagKey:"ENABLE_GRAPH_INDEXING",label:"\u30B0\u30E9\u30D5\u6295\u5F71"}],j=new Set(F.map(r=>r.key));function he(r){return j.has(r)}function ge(r){let t=F.find(n=>n.key===r);if(t===void 0)throw new Error(`ENRICHMENT_STAGES does not carry ${r}; the canonical list and the key type have drifted apart.`);return t}var Se={pageSize:{min:1,max:200,default:50},topologyLabels:{min:1,max:24,default:24}};var d=-1,l=0;function Y(r){return/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r)}function Ee(){let r=typeof globalThis<"u"&&globalThis.crypto?globalThis.crypto:typeof crypto<"u"?crypto:void 0;if(!r||typeof r.getRandomValues!="function")throw new Error("Cryptographically secure random number generator (crypto.getRandomValues) is required but not available.");let t=new Uint8Array(16);r.getRandomValues(t);let n=Date.now();if(n===d){if(l++,l>4095){for(;Date.now()<=d;);n=Date.now(),d=n,l=(t[6]<<4|t[7]&15)&1023}}else n>d?(d=n,l=(t[6]<<4|t[7]&15)&1023):(n=d,l++,l>4095&&(l=0));t[0]=Math.floor(n/1099511627776)&255,t[1]=Math.floor(n/4294967296)&255,t[2]=n>>>24&255,t[3]=n>>>16&255,t[4]=n>>>8&255,t[5]=n&255,t[6]=112|l>>>8&15,t[7]=l&255,t[8]=128|t[8]&63;let a=Array.from(t,c=>c.toString(16).padStart(2,"0")).join("");return`${a.slice(0,8)}-${a.slice(8,12)}-${a.slice(12,16)}-${a.slice(16,20)}-${a.slice(20)}`}function xe(r){if(!Y(r))throw new Error(`Invalid RFC 9562 UUIDv7 string: "${r}"`);let t=r.slice(0,8)+r.slice(9,13),n=parseInt(t,16);if(Number.isNaN(n))throw new Error(`Invalid hex timestamp in UUIDv7: "${t}"`);return new Date(n)}export{q as AmountEntrySchema,g as BaseEnrichmentClient,A as BoundingBoxSchema,I as CanonicalDomainKeySchema,U as ChapterSegmentSchema,V as ChunkingStrategySchema,H as CircuitBreakerStatusSchema,f as ConfidentialityLevelSchema,pe as DocumentStructuredDataSchema,F as ENRICHMENT_STAGES,w as EnrichmentClient,u as EnrichmentClientError,ce as EnrichmentSyncStatusSchema,ee as FILTERABLE_CONFIDENTIALITY_LEVELS,C as FileMetadataResponseSchema,m as FileUriSchema,Se as GRAPH_INDEX_LIMITS,S as MODE_TIERS,k as ModelProviderSchema,x as QUARANTINED_CONFIDENTIALITY_LEVEL,G as QualityTierSchema,L as ReclassifyRequestSchema,M as ReclassifyResponseSchema,v as SEARCH_MODES,Z as SEARCH_PARAM_LIMITS,$ as SearchHitSchema,B as SearchMetadataSchema,K as SearchModeSchema,N as SearchRequestSchema,D as SearchResponseSchema,y as TenantIdSchema,z as TranscriptSegmentSchema,ge as enrichmentStage,Ee as generateUuidV7,he as isEnrichmentStageKey,Y as isValidUuidV7,ae as modeFusesRankings,te as modeNeedsRemoteTiers,ne as modeScoreIsSimilarity,re as narrowModeToAllowedTiers,xe as uuidv7ToDate};
|
|
1
|
+
var R=class extends Error{statusCode;responseBody;parsedBody;constructor(t,n,a,l){super(t),this.name="EnrichmentClientError",this.statusCode=n,this.responseBody=a,this.parsedBody=l}},N=class{baseUrl;apiKey;fetchFn;timeoutMs;constructor(t){if(!t||typeof t.baseUrl!="string"||t.baseUrl.trim().length===0)throw new Error("baseUrl is required and must be a non-empty string for EnrichmentClient.");let n=t.baseUrl.trim().replace(/\/$/,"");if(t.apiKey&&n.startsWith("http://")&&!n.includes("localhost")&&!n.includes("127.0.0.1"))throw new Error("Security Violation: Transmitting Bearer tokens over unencrypted HTTP to non-localhost hosts is strictly prohibited.");this.baseUrl=n,this.apiKey=t.apiKey,this.fetchFn=t.fetchFn??fetch,this.timeoutMs=t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:3e4}async request(t,n,a){let l=`${this.baseUrl}${t}`,c={Accept:"application/json","Content-Type":"application/json","X-Tenant-Id":n};this.apiKey&&(c.Authorization=`Bearer ${this.apiKey}`);let d=new AbortController,m=setTimeout(()=>d.abort(),this.timeoutMs),f;try{f=await this.fetchFn(l,{method:"POST",headers:c,body:JSON.stringify(a),signal:d.signal})}catch(y){let g=y instanceof Error?y.message:String(y);throw new R(`Network request failed for POST ${l}: ${g}`,0,"")}finally{clearTimeout(m)}if(!f.ok){let y=await f.text().catch(()=>""),g;try{g=JSON.parse(y)}catch{}throw new R(`API request failed with status ${f.status}: ${y}`,f.status,y,g)}let I=await f.text().catch(()=>"");if(I.trim().length!==0)try{return JSON.parse(I)}catch(y){let g=y instanceof Error?y.message:String(y);throw new R(`Failed to parse response JSON from ${l}: ${g}`,f.status,I)}}};import{z as r}from"zod";import{z as B}from"zod";var ge=B.enum(["google_cloud","google_vision","yomitoku_local","faster_whisper_local","google_speech","ollama_local","openai","anthropic","azure_openai","bedrock","custom_openai_compatible"]),F=B.enum(["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"]),L="RESTRICTED";var zt={rrfK:{min:1,max:200,default:60},alpha:{min:0,max:1,default:.7},threshold:{min:0,max:1},limit:{min:1,max:50,default:10}},j=F.options.filter(e=>e!==L);if(j.length===0)throw new Error("The confidentiality vocabulary left nothing filterable after removing the quarantined level; a validator built from this list would reject every request.");var Kt=j,Y=["KEYWORD","SPARSE","DENSE","HYBRID","GRAPH_TRAVERSE"],C={KEYWORD:{dense:!1,sparse:!1,graph:!1,lexical:!0},SPARSE:{dense:!1,sparse:!0,graph:!1,lexical:!1},DENSE:{dense:!0,sparse:!1,graph:!1,lexical:!1},HYBRID:{dense:!0,sparse:!0,graph:!0,lexical:!0},GRAPH_TRAVERSE:{dense:!1,sparse:!1,graph:!0,lexical:!1}};function Ht(e){let t=C[e];return t.dense||t.sparse||t.graph}function Bt(e){let t=C[e];return t.dense&&!t.sparse}function jt(e,t){let n=C[e],a=(n.dense||n.sparse)&&t.vector,l=n.graph&&t.graph;return a||l?a?l?{mode:e,discardGraph:!1}:n.dense&&n.sparse?{mode:e,discardGraph:!0}:{mode:n.dense?"DENSE":"SPARSE",discardGraph:!1}:{mode:"GRAPH_TRAVERSE",discardGraph:!1}:null}function Yt(e){let t=C[e];return[t.dense,t.sparse,t.graph,t.lexical].filter(Boolean).length>1}var Ie=["vector","graph"],Re=["empty_query","caller_token_unavailable","time_window_unsupported"],_e=["vector_tier_not_configured","graph_tier_not_configured","no_active_vector_collection","vector_collections_missing"],Ae=["remote_tiers_unavailable","remote_tiers_timed_out","remote_tiers_refused_caller","remote_tiers_rejected_request","remote_tiers_failed","remote_tiers_not_executed","vector_search_disabled","graph_search_disabled"],$t=[...Re,..._e,...Ae,...Ie.map(e=>`circuit_breaker_open:${e}`)];var Ne=r.string().trim().min(1,"tenant_id must be a non-empty string"),Jt=r.string().trim().min(1,"file_uri must be a non-empty string"),Qt=r.enum(["PENDING","EXTRACTING","ENRICHING","PROJECTING","SYNCED","FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"]),Wt=r.object({page:r.number().int().positive().optional(),x:r.number().nonnegative().optional(),y:r.number().nonnegative().optional(),width:r.number().positive().optional(),height:r.number().positive().optional(),start_sec:r.number().nonnegative().optional(),end_sec:r.number().nonnegative().optional(),frame_index:r.number().int().nonnegative().optional(),timestamp_sec:r.number().nonnegative().optional(),scene_confidence:r.number().min(0).max(1).optional()}),Ce=r.object({title:r.string().trim().min(1),start_sec:r.number().nonnegative(),end_sec:r.number().nonnegative(),summary:r.string()}),Te=r.object({start_sec:r.number().nonnegative(),end_sec:r.number().nonnegative(),speaker:r.string().trim().min(1),text:r.string()}),xe=r.object({label:r.string(),value:r.number(),currency:r.string()}),Zt=r.object({document_type:r.string().optional(),title:r.string().optional(),organization:r.string().optional(),key_entities:r.array(r.string()).optional(),dates:r.array(r.string()).optional(),amounts:r.array(xe).optional(),media_type:r.enum(["video","audio"]).optional(),duration_sec:r.number().nonnegative().optional(),chapters:r.array(Ce).optional(),transcript_segments:r.array(Te).optional()}),en=r.enum(["CLOSED","OPEN","HALF_OPEN"]),be=r.enum(Y),De=r.object({circuit_breaker_status:r.string(),quality_tier:r.string(),latency_ms:r.number().nonnegative(),total_hits:r.number().int().nonnegative(),fallback_applied:r.boolean(),degraded_reason:r.string().nullable()}),Oe=r.enum(["CONTRACT_LEGAL","EMAIL_THREAD","DAILY_REPORT","FINANCIAL_REPORT","TECHNICAL_SPEC","MASTER_DATA","MEDIA_ASSET","GENERAL_DOCUMENT"]),tn=r.enum(["hierarchical","conversation","section","fixed_size","table_aware","semantic","none","multimodal"]),Pe=r.object({metadata_id:r.number().int().positive(),chunk_index:r.number().int().nonnegative(),text:r.string(),score:r.number()}),Fe=r.object({metadata_id:r.number().int().positive(),relation:r.string(),target_name:r.string()}),$=r.object({query:r.string().trim().min(1,"query must not be empty"),tenant_id:Ne,domain_key:Oe.optional(),limit:r.number().int().positive().optional(),department_id:r.number().int().positive().optional(),search_mode:be.optional(),strategy_id:r.number().int().positive().optional()}).strict(),V=r.object({hits:r.array(Pe),graph_hits:r.array(Fe),tiers:r.record(r.string(),r.boolean()),metadata:De});var X=class extends N{async search(t){let n=$.parse(t),a=await this.request("/ai/search/hybrid",n.tenant_id,n);return V.parse(a)}};var Z=["email","pdf","office","image","media","text","google_native","other"],ln={email:"\u30E1\u30FC\u30EB",pdf:"PDF",office:"Office \u6587\u66F8",image:"\u753B\u50CF",media:"\u97F3\u58F0\u30FB\u52D5\u753B",text:"\u30C6\u30AD\u30B9\u30C8",google_native:"Google \u30CD\u30A4\u30C6\u30A3\u30D6",other:"\u305D\u306E\u4ED6"},Le=[["message/rfc822","email"],["application/pdf","pdf"],["application/vnd.openxmlformats-officedocument.*","office"],["application/msword","office"],["application/vnd.ms-excel","office"],["application/vnd.ms-powerpoint","office"],["application/vnd.google-apps.*","google_native"],["image/svg+xml","text"],["image/emf","other"],["image/x-emf","other"],["image/wmf","other"],["image/x-wmf","other"],["image/*","image"],["audio/*","media"],["video/*","media"],["text/*","text"],["application/json","text"],["application/xml","text"]];function cn(e){let t=(e.split(";")[0]??"").trim().toLowerCase();for(let[n,a]of Le)if(n.endsWith("*")?t.startsWith(n.slice(0,-1)):t===n)return a;return"other"}var ee=["delete_child_assets","extract_text","analyze_media","extract_assets","ocr_children","ocr_document","resolve_body","enrich_document","project_to_indexes"],pn=["EXTRACTING","ENRICHING","PROJECTING"],v=e=>({featureFlagKey:e,whenClosed:"skip",failureStatus:null}),q=(e,t)=>({featureFlagKey:e,whenClosed:"fail",failureStatus:t}),te={delete_child_assets:{key:"delete_child_assets",label:"\u65E7\u7248\u306E\u5B50\u30A2\u30BB\u30C3\u30C8\u524A\u9664",description:"\u3053\u306E\u7248\u3088\u308A\u524D\u306E\u7248\u304C\u751F\u3093\u3060\u5B50\u30A2\u30BB\u30C3\u30C8\u3092\u4FDD\u7BA1\u5C64\u3068\u7D22\u5F15\u304B\u3089\u5916\u3059\u3002",endpoint:"/ai/assets/delete",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:null,fanOut:null},extract_text:{key:"extract_text",label:"\u6587\u5B57\u5C64\u306E\u62BD\u51FA",description:"\u6587\u66F8\u304C\u6301\u3064\u6587\u5B57\u5C64 (PDF \u306E\u6587\u5B57\u30FBOffice \u306E\u672C\u6587\u30FB\u30E1\u30FC\u30EB\u306E\u672C\u6587\u3068\u898B\u51FA\u3057) \u3092\u8AAD\u307F\u3001\u4F4D\u7F6E\u60C5\u5831\u3068\u5171\u306B\u4FDD\u5B58\u3059\u308B\u3002",endpoint:"/ai/enrichment/extract",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:null,fanOut:null},analyze_media:{key:"analyze_media",label:"\u30E1\u30C7\u30A3\u30A2\u89E3\u6790",description:"\u97F3\u58F0\u30FB\u52D5\u753B\u3092\u8EE2\u5199\u3057\u3001\u767A\u8A71\u533A\u9593\u4ED8\u304D\u306E\u30C1\u30E3\u30F3\u30AF\u3068\u30AD\u30FC\u30D5\u30EC\u30FC\u30E0\u6570\u3092\u8A18\u9332\u3059\u308B\u3002",endpoint:"/ai/media/analyze",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[v("ENABLE_MEDIA_ANALYSIS")],capability:"transcription",fanOut:null},extract_assets:{key:"extract_assets",label:"\u5B50\u30A2\u30BB\u30C3\u30C8\u306E\u62BD\u51FA",description:"\u57CB\u3081\u8FBC\u307F\u753B\u50CF\u3084\u30E1\u30FC\u30EB\u306E\u6DFB\u4ED8\u3092\u5B50\u30A2\u30BB\u30C3\u30C8\u3068\u3057\u3066\u5207\u308A\u51FA\u3057\u3001\u6587\u66F8\u306E\u96A3\u306B\u4FDD\u7BA1\u3057\u3066\u767B\u9332\u3059\u308B\u3002",endpoint:"/ai/assets/extract",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[v("ENABLE_ASSET_EXTRACTION")],capability:"asset_extraction",fanOut:null},ocr_children:{key:"ocr_children",label:"\u5B50\u30A2\u30BB\u30C3\u30C8\u306E\u8AAD\u307F\u53D6\u308A",description:"\u5207\u308A\u51FA\u3057\u305F\u5B50\u30A2\u30BB\u30C3\u30C8\u3092\u62BD\u51FA\u9806\u306B 1 \u4EF6\u305A\u3064\u8AAD\u307F\u3001\u6587\u5B57\u5C64\u3092\u8AAD\u3081\u308B\u5B50 (\u30C6\u30AD\u30B9\u30C8\u30FB\u30E1\u30FC\u30EB\u30FBOffice\u30FBPDF) \u306F\u305D\u306E\u6587\u5B57\u5C64\u3092\u3001\u8AAD\u3081\u306A\u3044\u5B50\u306F\u7248\u9762\u3092\u5149\u5B66\u8A8D\u8B58\u3067\u8AAD\u3093\u3067\u3001\u5B50\u3054\u3068\u306B\u672C\u6587\u3068\u51FA\u6240\u3092\u4FDD\u5B58\u3059\u308B\u3002",endpoint:"/ai/ocr/run",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[],capability:"ocr",fanOut:"children"},ocr_document:{key:"ocr_document",label:"\u6587\u66F8\u306E OCR",description:"\u6587\u66F8\u81EA\u8EAB\u306E\u7248\u9762 (\u753B\u50CF\u30FBPDF \u306E\u5404\u30DA\u30FC\u30B8) \u3092\u5149\u5B66\u8A8D\u8B58\u306B\u304B\u3051\u308B\u3002",endpoint:"/ai/ocr/run",phase:"EXTRACTING",failureStatus:"FAILED_EXTRACT",gates:[v("ENABLE_OCR")],capability:"ocr",fanOut:null},resolve_body:{key:"resolve_body",label:"\u672C\u6587\u306E\u78BA\u5B9A",description:"\u6587\u5B57\u5C64\u30FBOCR\u30FB\u8EE2\u5199\u306E\u3069\u308C\u3092\u672C\u6587\u3068\u3059\u308B\u304B\u3092\u6C7A\u3081\u3001\u51FA\u6240\u3092\u8A18\u9332\u3059\u308B\u3002",endpoint:"/ai/enrichment/body",phase:"ENRICHING",failureStatus:"FAILED_ENRICH",gates:[],capability:null,fanOut:null},enrich_document:{key:"enrich_document",label:"\u8981\u7D04\u3068\u69CB\u9020\u5316\u62BD\u51FA",description:"\u672C\u6587\u3092\u30E2\u30C7\u30EB\u3078\u6E21\u3057\u3001\u8981\u7D04\u30FB\u30BF\u30B0\u30FB\u69CB\u9020\u5316\u30C7\u30FC\u30BF\u30FB\u30C9\u30E1\u30A4\u30F3\u5206\u985E\u3092\u5F97\u308B\u3002",endpoint:"/ai/enrichment/document",phase:"ENRICHING",failureStatus:"FAILED_ENRICH",gates:[],capability:"enrichment",fanOut:null},project_to_indexes:{key:"project_to_indexes",label:"\u30D9\u30AF\u30C8\u30EB\u3068\u30B0\u30E9\u30D5\u3078\u306E\u6295\u5F71",description:"\u672C\u6587\u3092\u30C1\u30E3\u30F3\u30AF\u306B\u3057\u3066\u57CB\u3081\u8FBC\u307F\u3001\u30D9\u30AF\u30C8\u30EB\u7D22\u5F15\u3068\u30CA\u30EC\u30C3\u30B8\u30B0\u30E9\u30D5\u3078\u66F8\u304F\u3002",endpoint:"/ai/enrichment/project",phase:"PROJECTING",failureStatus:"FAILED_VECTOR",gates:[q("ENABLE_VECTOR_INDEXING","FAILED_VECTOR"),q("ENABLE_GRAPH_INDEXING","FAILED_GRAPH")],capability:null,fanOut:null}},J={whenClosed:"fail",failureStatus:"FAILED_EXTRACT"},T=[{step:"delete_child_assets",dependsOn:[]},{step:"extract_text",dependsOn:["delete_child_assets"]},{step:"extract_assets",dependsOn:["extract_text"]},{step:"ocr_children",dependsOn:["extract_assets"]},{step:"ocr_document",dependsOn:["extract_text"]},{step:"resolve_body",dependsOn:["ocr_children","ocr_document"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],Q=[{step:"delete_child_assets",dependsOn:[]},{step:"extract_text",dependsOn:["delete_child_assets"]},{step:"resolve_body",dependsOn:["extract_text"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}],ve={email:{kind:"email",steps:T},pdf:{kind:"pdf",steps:T},office:{kind:"office",steps:T},google_native:{kind:"google_native",steps:T},image:{kind:"image",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"ocr_document",dependsOn:["delete_child_assets"],gatePolicy:J},{step:"resolve_body",dependsOn:["ocr_document"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"rebuild"}]},media:{kind:"media",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"analyze_media",dependsOn:["delete_child_assets"],gatePolicy:J},{step:"resolve_body",dependsOn:["analyze_media"]},{step:"enrich_document",dependsOn:["resolve_body"]},{step:"project_to_indexes",dependsOn:["enrich_document"],chunkSource:"existing"}]},text:{kind:"text",steps:Q},other:{kind:"other",steps:Q}};function dn(e){return ve[e]}function un(e){let{gates:t}=te[e.step],{gatePolicy:n}=e;return n===void 0?t:t.map(a=>({featureFlagKey:a.featureFlagKey,whenClosed:n.whenClosed,failureStatus:n.failureStatus}))}function mn(e){let t=new Map(e.steps.map(c=>[c.step,c]));for(let c of e.steps){if(c.gatePolicy!==void 0&&te[c.step].gates.length===0)throw new Error(`Flow ${e.kind}: step ${c.step} overrides its gate policy, but the step has no gate to close.`);for(let d of c.dependsOn)if(!t.has(d))throw new Error(`Flow ${e.kind}: step ${c.step} depends on ${d}, which the flow does not contain.`)}let n=[...e.steps],a=new Set,l=[];for(;n.length>0;){let c=n.findIndex(m=>m.dependsOn.every(f=>a.has(f)));if(c===-1)throw new Error(`Flow ${e.kind}: the steps ${n.map(m=>m.step).join(", ")} depend on each other in a cycle.`);let[d]=n.splice(c,1);a.add(d.step),l.push(d)}return l}var W={EXTRACTING:0,ENRICHING:1,PROJECTING:2};function yn(e,t){return W[e]-W[t]}import{z as o}from"zod";var ne=[{code:"DEPLOYMENT_DISABLED",status:503,errorCode:5035},{code:"RUN_ALREADY_ACTIVE",status:409,errorCode:4091},{code:"BASIS_INVALID",status:409,errorCode:4092},{code:"RUN_ALREADY_FINISHED",status:409,errorCode:4093},{code:"FORBIDDEN",status:403,errorCode:null}];import{z as k}from"zod";var A=k.string().uuid().transform(e=>e.toLowerCase()),u=k.string().datetime({offset:!0}),s=(e,t,n)=>{e.addIssue({code:k.ZodIssueCode.custom,path:[...t],message:n})},we=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:Z|([+-])(\d{2}):?(\d{2}))$/,re=e=>{let t=u.safeParse(e).success?we.exec(e):null;if(t===null)return null;let[,n,a,l,c,d,m,f,I,y,g]=t,P=new Date(0);P.setUTCFullYear(Number(n),Number(a)-1,Number(l)),P.setUTCHours(Number(c),Number(d),m===void 0?0:Number(m),0);let he=I===void 0?0:(I==="+"?1:-1)*(Number(y)*3600+Number(g)*60);return{epochSeconds:P.getTime()/1e3-he,fraction:f===void 0?"":f}},x=(e,t)=>{let n=re(e),a=re(t);if(n===null||a===null)return!1;if(n.epochSeconds!==a.epochSeconds)return n.epochSeconds<a.epochSeconds;let l=Math.max(n.fraction.length,a.fraction.length);return n.fraction.padEnd(l,"0")<a.fraction.padEnd(l,"0")};var oe={INTEGRITY_TOMBSTONE_RETENTION_DAYS:{min:1,max:3650},INTEGRITY_FINDING_SAMPLE_LIMIT:{min:1,max:5e3},INTEGRITY_RUN_HEARTBEAT_TIMEOUT_SECONDS:{min:30,max:3600},INTEGRITY_RUN_RETENTION_COUNT:{min:2,max:100},POLICY_CONFLICT_MAX_TIE_GROUP_SIZE:{min:2,max:60}};var Ue=e=>{for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)},b=Ue(oe),ie=e=>Object.hasOwn(b,e),ae=(e,t)=>{let{min:n,max:a}=b[e];if(!Number.isInteger(t)||t<n||t>a)throw new RangeError(`${e} \u306F ${n}\u301C${a} \u306E\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)},Rn=(e,t)=>{ie(e)&&ae(e,t)},_n=(e,t)=>{if(!ie(e))throw new TypeError(`The range table bounds no parameter named ${JSON.stringify(e)}.`);ae(e,t)};var ce=o.enum(["QDRANT","NEO4J"]),Ge=o.enum(["PRODUCTION","VARIANT","LABEL"]),pe=o.enum(["EXPECTED","LIVE","HISTORY","TOMBSTONE","AWAITING_SUCCESSOR","IN_FLIGHT","UNPLACED","UNRECORDED","UNREFERENCED","CHANGED_AFTER_START","PIPELINE_FAILED","PROJECTION_REFUSED","ORPHAN","TOMBSTONE_EXPIRED","UNPROPAGATED_DELETE","STALE_REVISION","MISPLACED","UNMARKED_SUPERSEDED","FLAG_DRIFT","DETACHED","UNKEYED","MISSING","COUNT_MISMATCH"]),ze=pe.exclude(["EXPECTED","LIVE","HISTORY"]),Ke=o.enum(["POINT","NODE","CHUNK","DOCUMENT"]),He=o.enum(["EXPECTED","HEALTHY","RETAINED","INFORMATIONAL","DISCREPANCY"]),Be=o.enum(["NONE","PURGE","FLAG","REPROJECT"]),p=(e,t)=>Object.freeze({disposition:e,repairAction:t}),je=Object.freeze({EXPECTED:p("EXPECTED","NONE"),LIVE:p("HEALTHY","NONE"),HISTORY:p("RETAINED","NONE"),TOMBSTONE:p("RETAINED","NONE"),AWAITING_SUCCESSOR:p("RETAINED","NONE"),IN_FLIGHT:p("INFORMATIONAL","NONE"),UNPLACED:p("INFORMATIONAL","NONE"),UNRECORDED:p("INFORMATIONAL","NONE"),UNREFERENCED:p("INFORMATIONAL","NONE"),CHANGED_AFTER_START:p("INFORMATIONAL","NONE"),PIPELINE_FAILED:p("INFORMATIONAL","NONE"),PROJECTION_REFUSED:p("INFORMATIONAL","NONE"),ORPHAN:p("DISCREPANCY","PURGE"),TOMBSTONE_EXPIRED:p("DISCREPANCY","PURGE"),UNPROPAGATED_DELETE:p("DISCREPANCY","FLAG"),STALE_REVISION:p("DISCREPANCY","PURGE"),MISPLACED:p("DISCREPANCY","PURGE"),UNMARKED_SUPERSEDED:p("DISCREPANCY","FLAG"),FLAG_DRIFT:p("DISCREPANCY","NONE"),DETACHED:p("DISCREPANCY","NONE"),UNKEYED:p("DISCREPANCY","NONE"),MISSING:p("DISCREPANCY","REPROJECT"),COUNT_MISMATCH:p("DISCREPANCY","REPROJECT")}),Ye=o.enum(["SCAN","REPAIR"]),$e=o.enum(["RUNNING","COMPLETED","FAILED","CANCELLED","ABANDONED"]),Ve=o.enum(["CONSISTENT","INCONSISTENT","UNDETERMINED"]),Xe=o.enum(["QDRANT","NEO4J","DOCUMENTS"]),qe=o.enum(["APPLIED","SKIPPED","FAILED"]),Je=o.enum(["RECLASSIFIED","IN_FLIGHT","DESTINATION_PENDING","BASIS_EXHAUSTED","PROJECTION_REFUSED"]),Qe=100,E=o.number().int().nonnegative(),D=o.number().int().min(300).max(599),w=["repairedCount","repairFailedCount","repairSkippedCount"],de=o.string().regex(/^[0-9a-f]{64}$/,"A store fingerprint is 64 lowercase hexadecimal digits."),se=b.INTEGRITY_TOMBSTONE_RETENTION_DAYS,We=o.object({runUid:A,mode:Ye,status:$e,requestedBy:o.string().min(1),executor:o.string().min(1),basisRunUid:A.nullable(),storeFingerprint:de,tombstoneRetentionDays:o.number().int().min(se.min).max(se.max),startedAt:u,finishedAt:u.nullable(),verdict:Ve.nullable(),errorClass:o.string().min(1).nullable(),reprojectDocuments:E.nullable(),reprojectRebuildDocuments:E.nullable()}).strict(),Ze=(e,t)=>{let n=e.status==="COMPLETED";e.mode==="REPAIR"!=(e.basisRunUid!==null)&&s(t,["basisRunUid"],"A REPAIR run names its basis SCAN run, and a SCAN run names none."),n!==(e.verdict!==null)&&s(t,["verdict"],"Only a COMPLETED run has a verdict."),n!==(e.reprojectDocuments!==null)&&s(t,["reprojectDocuments"],"Only a COMPLETED run has the count of documents to re-project.");let{reprojectDocuments:a,reprojectRebuildDocuments:l}=e;a===null||l===null?a!==l&&s(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are counted together with the documents it re-projects."):l>a&&s(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are no more than the documents it re-projects."),e.status==="RUNNING"!=(e.finishedAt===null)&&s(t,["finishedAt"],"Only a RUNNING run has not finished."),e.finishedAt!==null&&x(e.finishedAt,e.startedAt)&&s(t,["finishedAt"],"A run does not finish before it starts."),(e.status==="FAILED"||e.status==="ABANDONED")!=(e.errorClass!==null)&&s(t,["errorClass"],"Only a FAILED or ABANDONED run names an error class.")},U=We.superRefine(Ze),et=o.object({store:ce,scopeKey:o.string().min(1),scopeRole:Ge,itemClass:pe,unit:Ke,disposition:He,repairAction:Be,itemCount:E.nullable(),unmeasuredReason:o.string().min(1).nullable(),measuredAt:u.nullable(),repairedCount:E.nullable(),repairFailedCount:E.nullable(),repairSkippedCount:E.nullable()}).strict(),tt=(e,t)=>{let n=je[e.itemClass];e.disposition!==n.disposition&&s(t,["disposition"],`A ${e.itemClass} quantity is ${n.disposition}.`),e.repairAction!==n.repairAction&&s(t,["repairAction"],`A repair's action on ${e.itemClass} items is ${n.repairAction}.`);let a=e.itemCount===null;a!==(e.unmeasuredReason!==null)&&s(t,["unmeasuredReason"],"An unmeasured quantity (itemCount null) has a reason, and a measured one has none."),a!==(e.measuredAt===null)&&s(t,["measuredAt"],"Only a measured quantity has a measurement time.");let{repairedCount:l,repairFailedCount:c,repairSkippedCount:d}=e;if(l===null||c===null||d===null){if(w.some(m=>e[m]!==null))for(let m of w)e[m]===null&&s(t,[m],"The repaired, failed and skipped counts are recorded together or not at all.");return}e.repairAction==="NONE"&&s(t,["repairAction"],"Only a class with a repair action carries repair counts."),e.itemCount!==null&&l+c+d>e.itemCount&&s(t,["itemCount"],"The repaired, failed and skipped counts together do not exceed the measured count.")},nt=et.superRefine(tt),rt=o.object({run:U,phase:Xe.nullable(),phaseScope:o.string().min(1).nullable(),phaseDone:E.nullable(),phaseTotal:E.nullable(),heartbeatAt:u,isStale:o.boolean(),cancelRequestedAt:u.nullable()}).strict(),ot=(e,t)=>{if(e.run.status!=="RUNNING"&&s(t,["run","status"],"The active run is a RUNNING run."),x(e.heartbeatAt,e.run.startedAt)&&s(t,["heartbeatAt"],"A run's heartbeat is not earlier than its start."),e.phase===null)for(let n of["phaseScope","phaseDone","phaseTotal"])e[n]!==null&&s(t,[n],"A run with no phase has no phase progress.");e.phase==="DOCUMENTS"&&e.phaseScope!==null&&s(t,["phaseScope"],"The DOCUMENTS phase scans no scope.")},it=rt.superRefine(ot),at=o.object({run:U,quantities:o.array(nt),previousStoreFingerprint:de.nullable()}).strict(),st=(e,t)=>{e.run.status!=="COMPLETED"&&s(t,["run","status"],"The last completed run is a COMPLETED run.");let n=new Set;for(let[a,l]of e.quantities.entries()){let c=JSON.stringify([l.store,l.scopeKey,l.itemClass]);if(n.has(c)&&s(t,["quantities",a],"A run records each (store, scope, class) cell once."),n.add(c),e.run.mode==="SCAN")for(let d of w)l[d]!==null&&s(t,["quantities",a,d],"A SCAN run repairs nothing, so its quantities carry no repair counts.")}},lt=["FAILED","CANCELLED","ABANDONED"],ct=o.object({run:U,repairAppliedItems:E.nullable(),hasNewerRepair:o.boolean()}).strict(),pt=(e,t)=>{lt.includes(e.run.status)||s(t,["run","status"],"A newer unsuccessful run is FAILED, CANCELLED or ABANDONED."),e.run.mode==="SCAN"&&e.repairAppliedItems!==null&&s(t,["repairAppliedItems"],"A SCAN run applies nothing."),e.run.mode==="REPAIR"&&!e.hasNewerRepair&&s(t,["hasNewerRepair"],"An unsuccessful REPAIR run is itself a repair newer than the last completed run.")},bn=o.object({readAt:u,lastCompleted:at.superRefine(st).nullable(),active:it.nullable(),newerUnsuccessful:ct.superRefine(pt).nullable()}).strict(),dt=o.object({sequence:o.number().int().min(1),itemKey:o.string().min(1),metadataId:o.number().int().positive().nullable(),fileUri:o.string().nullable(),revision:o.number().int().nullable(),observed:o.record(o.string(),o.unknown()),repairOutcome:qe.nullable(),repairErrorClass:o.string().min(1).nullable(),repairSkipReason:Je.nullable()}).strict(),ut=(e,t)=>{e.repairOutcome==="FAILED"!=(e.repairErrorClass!==null)&&s(t,["repairErrorClass"],"Only a FAILED finding names an error class."),e.repairOutcome==="SKIPPED"!=(e.repairSkipReason!==null)&&s(t,["repairSkipReason"],"Only a SKIPPED finding names a skip reason.")},mt=dt.superRefine(ut),yt=o.object({rows:o.array(mt),nextAfter:o.number().int().min(1).nullable(),recordedCount:E,totalCount:E.nullable()}).strict(),ft=(e,t)=>{for(let[n,a]of e.rows.entries()){let l=e.rows[n-1];l!==void 0&&a.sequence<=l.sequence&&s(t,["rows",n,"sequence"],"A page lists its rows in ascending sequence.")}e.nextAfter!==null&&e.nextAfter!==e.rows.at(-1)?.sequence&&s(t,["nextAfter"],"The next page starts after the sequence of this page's last row.")},Dn=yt.superRefine(ft),On=o.object({runUid:A,store:ce,scopeKey:o.string().min(1),itemClass:ze,after:o.number().int().min(1).optional(),limit:o.number().int().min(1).max(Qe)}).strict(),G=o.enum(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),le=o.enum(["start","cancel"]),Et=G.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","FORBIDDEN","UPSTREAM_FAILED"]),St=G.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),M={start:Et,cancel:St},ht=o.object({code:G.exclude(["UPSTREAM_FAILED"]),status:D,errorCode:o.number().int().nullable()}).strict(),ue=Object.freeze(o.array(ht).parse(ne).map(e=>Object.freeze(e))),gt=(e,t)=>{e.code==="UPSTREAM_FAILED"||e.code==="FORBIDDEN"&&e.status===null||ue.some(n=>n.code===e.code&&n.status===e.status)||s(t,["status"],`A ${e.code} failure carries the status of its row in the code table.`)},Pn=o.discriminatedUnion("command",[o.object({command:le.extract(["start"]),code:M.start,status:D.nullable()}).strict(),o.object({command:le.extract(["cancel"]),code:M.cancel,status:D.nullable()}).strict()]).superRefine(gt),Fn=(e,t,n)=>{let a=M[e],l=ue.find(c=>c.status===t&&(c.errorCode===null||c.errorCode===n)&&a.safeParse(c.code).success);return l===void 0?"UPSTREAM_FAILED":l.code},Ln=o.discriminatedUnion("ok",[o.object({ok:o.literal(!0),runUid:A}).strict(),o.object({ok:o.literal(!1),status:D,errorCode:o.number().int().nullable()}).strict()]);import{z as i}from"zod";var me=i.enum(Z),O=i.enum(ee),It=i.enum(["RUNNING","SUCCEEDED","FAILED"]),Rt=i.enum(["RUNNING","SUCCEEDED","SKIPPED","FAILED"]),_t=i.enum(["ingest","retry","resync"]),At=i.enum(["text_layer","ocr","transcript"]),S=i.number().int().nonnegative().nullable(),Nt=i.object({provider:i.string().nullable(),model:i.string().nullable(),engine:i.string().nullable(),prompt_key:i.string().nullable(),prompt_version:i.number().int().nullable(),duration_ms:S,input_chars:S,output_chars:S,pages_read:S,pages_total:S,chunk_count:S,points_upserted:S,collection:i.string().nullable(),embedding_model:i.string().nullable(),strategy_id:i.number().int().positive().nullable(),graph_nodes:S,body_source:At.nullable(),detail:i.record(i.string(),i.unknown())}).strict(),Ct=["no_pages","no_pages_rendered"],Tt=i.enum(Ct),z="gate_closed:",K="source_skipped:",H="nothing_to_read:",ye="no_children",xt=/^[A-Z][A-Z0-9_]*$/;function bt(e){if(e===ye)return{kind:"no_children"};if(e.startsWith(z)){let t=e.slice(z.length);return xt.test(t)?{kind:"gate_closed",featureFlagKey:t}:null}if(e.startsWith(K)){let t=O.safeParse(e.slice(K.length));return t.success?{kind:"source_skipped",stepKey:t.data}:null}if(e.startsWith(H)){let t=Tt.safeParse(e.slice(H.length));return t.success?{kind:"nothing_to_read",token:t.data}:null}return null}function Gn(e){let t=Dt(e);if(bt(t)===null)throw new RangeError(`Skip reason ${JSON.stringify(e)} has no text form: ${JSON.stringify(t)} is outside the skip-reason grammar.`);return t}function Dt(e){switch(e.kind){case"gate_closed":return`${z}${e.featureFlagKey}`;case"no_children":return ye;case"source_skipped":return`${K}${e.stepKey}`;case"nothing_to_read":return`${H}${e.token}`;default:{let t=e;throw new RangeError(`Unknown skip reason kind: ${JSON.stringify(t)}`)}}}var Ot=i.object({id:i.number().int().positive(),runId:i.number().int().positive(),sequence:i.number().int().nonnegative(),stepKey:O,targetMetadataId:i.number().int().positive(),status:Rt,skipReason:i.string().nullable(),provenance:Nt.nullable(),strategyId:i.number().int().positive().nullable(),httpStatus:i.number().int().nullable(),errorCode:i.string().nullable(),errorMessage:i.string().nullable(),startedAt:u,finishedAt:u.nullable(),durationMs:S}).strict();function Pt(e,t){switch(e.status){case"SKIPPED":e.skipReason===null&&s(t,["skipReason"],"A SKIPPED step must record why it was skipped."),e.provenance!==null&&s(t,["provenance"],"A SKIPPED step read nothing, so it has no report.");return;case"SUCCEEDED":e.provenance===null&&s(t,["provenance"],"A SUCCEEDED step must carry its report."),e.skipReason!==null&&s(t,["skipReason"],"A SUCCEEDED step was not skipped.");return;case"RUNNING":e.finishedAt!==null&&s(t,["finishedAt"],"A RUNNING step has not finished.");return;case"FAILED":e.skipReason!==null&&s(t,["skipReason"],"A FAILED step was not skipped.");return}}var Ft=Ot.superRefine(Pt),fe=i.object({id:i.number().int().positive(),tenantId:i.string().min(1),metadataId:i.number().int().positive(),revision:i.number().int().positive(),runUid:i.string().uuid(),jobId:i.string().min(1),attempt:i.number().int().positive(),trigger:_t,documentKind:me,flowKey:i.string().min(1),status:It,retryScheduled:i.boolean(),failedStepKey:O.nullable(),errorMessage:i.string().nullable(),requestedBy:i.string().min(1),startedAt:u,finishedAt:u.nullable(),steps:i.array(Ft)}).strict();function Ee(e,t){e.retryScheduled&&e.status!=="FAILED"&&s(t,["retryScheduled"],"Only a FAILED run can have a retry scheduled.")}var zn=fe.superRefine(Ee),Kn=fe.omit({steps:!0}).superRefine(Ee);function Lt(e,t){e.sampleCount>0||(e.durationP50Ms!==null&&s(t,["durationP50Ms"],"A step with no sample has no median latency."),e.durationP95Ms!==null&&s(t,["durationP95Ms"],"A step with no sample has no 95th-percentile latency."))}var Hn=i.object({documentKind:me,stepKey:O,sampleCount:i.number().int().nonnegative(),succeeded:i.number().int().nonnegative(),failed:i.number().int().nonnegative(),skipped:i.number().int().nonnegative(),durationP50Ms:S,durationP95Ms:S,lastStartedAt:u.nullable()}).strict().superRefine(Lt);var Se=[{key:"enable_summary_generation",featureFlagKey:null,label:"\u8981\u7D04\u751F\u6210"},{key:"enable_structured_extraction",featureFlagKey:null,label:"\u69CB\u9020\u5316\u62BD\u51FA"},{key:"enable_asset_extraction",featureFlagKey:"ENABLE_ASSET_EXTRACTION",label:"\u30A2\u30BB\u30C3\u30C8\u62BD\u51FA"},{key:"enable_vector_indexing",featureFlagKey:"ENABLE_VECTOR_INDEXING",label:"\u30D9\u30AF\u30C8\u30EB\u7D22\u5F15"},{key:"enable_graph_indexing",featureFlagKey:"ENABLE_GRAPH_INDEXING",label:"\u30B0\u30E9\u30D5\u6295\u5F71"}],vt=new Set(Se.map(e=>e.key));function jn(e){return vt.has(e)}function Yn(e){let t=Se.find(n=>n.key===e);if(t===void 0)throw new Error(`ENRICHMENT_STAGES does not carry ${e}; the canonical list and the key type have drifted apart.`);return t}var $n={pageSize:{min:1,max:200,default:50},topologyLabels:{min:1,max:24,default:24}};var _=-1,h=0;function kt(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}function Xn(){let e=typeof globalThis<"u"&&globalThis.crypto?globalThis.crypto:typeof crypto<"u"?crypto:void 0;if(!e||typeof e.getRandomValues!="function")throw new Error("Cryptographically secure random number generator (crypto.getRandomValues) is required but not available.");let t=new Uint8Array(16);e.getRandomValues(t);let n=Date.now();if(n===_){if(h++,h>4095){for(;Date.now()<=_;);n=Date.now(),_=n,h=(t[6]<<4|t[7]&15)&1023}}else n>_?(_=n,h=(t[6]<<4|t[7]&15)&1023):(n=_,h++,h>4095&&(h=0));t[0]=Math.floor(n/1099511627776)&255,t[1]=Math.floor(n/4294967296)&255,t[2]=n>>>24&255,t[3]=n>>>16&255,t[4]=n>>>8&255,t[5]=n&255,t[6]=112|h>>>8&15,t[7]=h&255,t[8]=128|t[8]&63;let a=Array.from(t,c=>c.toString(16).padStart(2,"0")).join("");return`${a.slice(0,8)}-${a.slice(8,12)}-${a.slice(12,16)}-${a.slice(16,20)}-${a.slice(20)}`}function qn(e){if(!kt(e))throw new Error(`Invalid RFC 9562 UUIDv7 string: "${e}"`);let t=e.slice(0,8)+e.slice(9,13),n=parseInt(t,16);if(Number.isNaN(n))throw new Error(`Invalid hex timestamp in UUIDv7: "${t}"`);return new Date(n)}export{xe as AmountEntrySchema,N as BaseEnrichmentClient,At as BodySourceSchema,Wt as BoundingBoxSchema,Ie as CIRCUIT_BREAKER_SERVICES,Oe as CanonicalDomainKeySchema,Ce as ChapterSegmentSchema,tn as ChunkingStrategySchema,en as CircuitBreakerStatusSchema,F as ConfidentialityLevelSchema,Ae as DISPATCH_DEGRADATION_REASONS,Z as DOCUMENT_KINDS,ln as DOCUMENT_KIND_LABELS,me as DocumentKindSchema,Zt as DocumentStructuredDataSchema,Se as ENRICHMENT_STAGES,X as EnrichmentClient,R as EnrichmentClientError,Qt as EnrichmentSyncStatusSchema,Kt as FILTERABLE_CONFIDENTIALITY_LEVELS,Jt as FileUriSchema,$n as GRAPH_INDEX_LIMITS,Fe as GraphSearchHitSchema,je as INTEGRITY_CLASS_POLICY,ue as INTEGRITY_COMMAND_CODES,Qe as INTEGRITY_FINDINGS_PAGE_LIMIT_MAX,it as IntegrityActiveRunSchema,bn as IntegrityAuditOverviewSchema,St as IntegrityCancelFailureCodeSchema,G as IntegrityCommandFailureCodeSchema,Pn as IntegrityCommandFailureSchema,Ln as IntegrityCommandReplySchema,le as IntegrityCommandSchema,He as IntegrityDispositionSchema,ze as IntegrityFindingItemClassSchema,Dn as IntegrityFindingPageSchema,mt as IntegrityFindingSchema,On as IntegrityFindingsQuerySchema,pe as IntegrityItemClassSchema,Xe as IntegrityPhaseSchema,nt as IntegrityQuantitySchema,Be as IntegrityRepairActionSchema,qe as IntegrityRepairOutcomeSchema,Je as IntegrityRepairSkipReasonSchema,U as IntegrityRunHeaderSchema,Ye as IntegrityRunModeSchema,$e as IntegrityRunStatusSchema,Ge as IntegrityScopeRoleSchema,Et as IntegrityStartFailureCodeSchema,ce as IntegrityStoreSchema,Ke as IntegrityUnitSchema,Ve as IntegrityVerdictSchema,Re as LOCAL_DEGRADATION_REASONS,Le as MIME_KIND_RULES,C as MODE_TIERS,ge as ModelProviderSchema,Ct as NOTHING_TO_READ_TOKENS,Tt as NothingToReadTokenSchema,ve as PIPELINE_FLOWS,pn as PIPELINE_PHASES,te as PIPELINE_STEPS,ee as PIPELINE_STEP_KEYS,zn as PipelineRunRecordSchema,It as PipelineRunStatusSchema,Kn as PipelineRunSummarySchema,O as PipelineStepKeySchema,Hn as PipelineStepMetricSchema,Ft as PipelineStepRecordSchema,Rt as PipelineStepStatusSchema,_t as PipelineTriggerSchema,L as QUARANTINED_CONFIDENTIALITY_LEVEL,_e as REMOTE_DEGRADATION_REASONS,$t as SEARCH_DEGRADATION_REASONS,Y as SEARCH_MODES,zt as SEARCH_PARAM_LIMITS,b as SYSTEM_PARAMETER_RANGES,Pe as SearchHitSchema,De as SearchMetadataSchema,be as SearchModeSchema,$ as SearchRequestSchema,V as SearchResponseSchema,Nt as StageProvenanceSchema,Ne as TenantIdSchema,Te as TranscriptSegmentSchema,_n as assertBoundedSystemParameter,Rn as assertSystemParameterInRange,cn as classifyDocumentKind,yn as comparePhases,Yn as enrichmentStage,dn as flowFor,un as flowStepGates,Gn as formatSkipReason,Xn as generateUuidV7,Fn as integrityCommandFailureCodeOf,jn as isEnrichmentStageKey,x as isStrictlyEarlier,kt as isValidUuidV7,Yt as modeFusesRankings,Ht as modeNeedsRemoteTiers,Bt as modeScoreIsSimilarity,jt as narrowModeToAllowedTiers,mn as orderedSteps,bt as parseSkipReason,qn as uuidv7ToDate};
|