@aiquants/enrichment-core 0.3.1 → 0.3.3
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 +26 -15
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +146 -41
- package/dist/index.d.ts +146 -41
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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};
|
|
1
|
+
var g=class extends Error{statusCode;responseBody;parsedBody;constructor(t,n,i,l){super(t),this.name="EnrichmentClientError",this.statusCode=n,this.responseBody=i,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,i){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(i),signal:d.signal})}catch(y){let I=y instanceof Error?y.message:String(y);throw new g(`Network request failed for POST ${l}: ${I}`,0,"")}finally{clearTimeout(m)}if(!f.ok){let y=await f.text().catch(()=>""),I;try{I=JSON.parse(y)}catch{}throw new g(`API request failed with status ${f.status}: ${y}`,f.status,y,I)}let R=await f.text().catch(()=>"");if(R.trim().length!==0)try{return JSON.parse(R)}catch(y){let I=y instanceof Error?y.message:String(y);throw new g(`Failed to parse response JSON from ${l}: ${I}`,f.status,R)}}};import{z as o}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"]),L=B.enum(["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"]),v="RESTRICTED";var Ht={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}},$=L.options.filter(e=>e!==v);if($.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 Yt=$,V=["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 jt(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 $t(e,t){let n=C[e],i=(n.dense||n.sparse)&&t.vector,l=n.graph&&t.graph;return i||l?i?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 Vt(e){let t=C[e];return[t.dense,t.sparse,t.graph,t.lexical].filter(Boolean).length>1}var _e=["vector","graph"],Ae=["empty_query","caller_token_unavailable","time_window_unsupported"],Ne=["vector_tier_not_configured","graph_tier_not_configured","no_active_vector_collection","vector_collections_missing"],Ce=["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"],Xt=[...Ae,...Ne,...Ce,..._e.map(e=>`circuit_breaker_open:${e}`)];var Te=o.string().trim().min(1,"tenant_id must be a non-empty string"),Wt=o.string().trim().min(1,"file_uri must be a non-empty string"),Zt=o.enum(["PENDING","EXTRACTING","ENRICHING","PROJECTING","SYNCED","FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"]),en=o.object({page:o.number().int().positive().optional(),x:o.number().nonnegative().optional(),y:o.number().nonnegative().optional(),width:o.number().positive().optional(),height:o.number().positive().optional(),start_sec:o.number().nonnegative().optional(),end_sec:o.number().nonnegative().optional(),frame_index:o.number().int().nonnegative().optional(),timestamp_sec:o.number().nonnegative().optional(),scene_confidence:o.number().min(0).max(1).optional()}),be=o.object({title:o.string().trim().min(1),start_sec:o.number().nonnegative(),end_sec:o.number().nonnegative(),summary:o.string()}),xe=o.object({start_sec:o.number().nonnegative(),end_sec:o.number().nonnegative(),speaker:o.string().trim().min(1),text:o.string()}),De=o.object({label:o.string(),value:o.number(),currency:o.string()}),tn=o.object({document_type:o.string().optional(),title:o.string().optional(),organization:o.string().optional(),key_entities:o.array(o.string()).optional(),dates:o.array(o.string()).optional(),amounts:o.array(De).optional(),media_type:o.enum(["video","audio"]).optional(),duration_sec:o.number().nonnegative().optional(),chapters:o.array(be).optional(),transcript_segments:o.array(xe).optional()}),nn=o.enum(["CLOSED","OPEN","HALF_OPEN"]),Oe=o.enum(V),Pe=o.object({circuit_breaker_status:o.string(),quality_tier:o.string(),latency_ms:o.number().nonnegative(),total_hits:o.number().int().nonnegative(),fallback_applied:o.boolean(),degraded_reason:o.string().nullable()}),Fe=o.enum(["CONTRACT_LEGAL","EMAIL_THREAD","DAILY_REPORT","FINANCIAL_REPORT","TECHNICAL_SPEC","MASTER_DATA","MEDIA_ASSET","GENERAL_DOCUMENT"]),rn=o.enum(["hierarchical","conversation","section","fixed_size","table_aware","semantic","none","multimodal"]),Le=o.object({metadata_id:o.number().int().positive(),chunk_index:o.number().int().nonnegative(),text:o.string(),score:o.number()}),ve=o.object({metadata_id:o.number().int().positive(),relation:o.string(),target_name:o.string()}),X=o.object({query:o.string().trim().min(1,"query must not be empty"),tenant_id:Te,domain_key:Fe.optional(),limit:o.number().int().positive().optional(),department_id:o.number().int().positive().optional(),search_mode:Oe.optional(),strategy_id:o.number().int().positive().optional()}).strict(),q=o.object({hits:o.array(Le),graph_hits:o.array(ve),tiers:o.record(o.string(),o.boolean()),metadata:Pe});var J=class extends N{async search(t){let n=X.parse(t),i=await this.request("/ai/search/hybrid",n.tenant_id,n);return q.parse(i)}};var te=["email","pdf","office","image","media","text","google_native","other"],pn={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"},ke=[["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 dn(e){let t=(e.split(";")[0]??"").trim().toLowerCase();for(let[n,i]of ke)if(n.endsWith("*")?t.startsWith(n.slice(0,-1)):t===n)return i;return"other"}var ne=["delete_child_assets","extract_text","analyze_media","extract_assets","ocr_children","ocr_document","resolve_body","enrich_document","project_to_indexes"],un=["EXTRACTING","ENRICHING","PROJECTING"],k=e=>({featureFlagKey:e,whenClosed:"skip",failureStatus:null}),Q=(e,t)=>({featureFlagKey:e,whenClosed:"fail",failureStatus:t}),re={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:[k("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:[k("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:[k("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}},W={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"}],Z=[{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"}],Ue={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:W},{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:W},{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:Z},other:{kind:"other",steps:Z}};function mn(e){return Ue[e]}function yn(e){let{gates:t}=re[e.step],{gatePolicy:n}=e;return n===void 0?t:t.map(i=>({featureFlagKey:i.featureFlagKey,whenClosed:n.whenClosed,failureStatus:n.failureStatus}))}function fn(e){let t=new Map(e.steps.map(c=>[c.step,c]));for(let c of e.steps){if(c.gatePolicy!==void 0&&re[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],i=new Set,l=[];for(;n.length>0;){let c=n.findIndex(m=>m.dependsOn.every(f=>i.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);i.add(d.step),l.push(d)}return l}var ee={EXTRACTING:0,ENRICHING:1,PROJECTING:2};function En(e,t){return ee[e]-ee[t]}import{z as r}from"zod";var oe=[{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 U}from"zod";var _=U.string().uuid().transform(e=>e.toLowerCase()),u=U.string().datetime({offset:!0}),s=(e,t,n)=>{e.addIssue({code:U.ZodIssueCode.custom,path:[...t],message:n})},Me=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:Z|([+-])(\d{2}):?(\d{2}))$/,ie=e=>{let t=u.safeParse(e).success?Me.exec(e):null;if(t===null)return null;let[,n,i,l,c,d,m,f,R,y,I]=t,F=new Date(0);F.setUTCFullYear(Number(n),Number(i)-1,Number(l)),F.setUTCHours(Number(c),Number(d),m===void 0?0:Number(m),0);let Re=R===void 0?0:(R==="+"?1:-1)*(Number(y)*3600+Number(I)*60);return{epochSeconds:F.getTime()/1e3-Re,fraction:f===void 0?"":f}},b=(e,t)=>{let n=ie(e),i=ie(t);if(n===null||i===null)return!1;if(n.epochSeconds!==i.epochSeconds)return n.epochSeconds<i.epochSeconds;let l=Math.max(n.fraction.length,i.fraction.length);return n.fraction.padEnd(l,"0")<i.fraction.padEnd(l,"0")};var ae={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 ze=e=>{for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)},x=ze(ae),se=e=>Object.hasOwn(x,e),le=(e,t)=>{let{min:n,max:i}=x[e];if(!Number.isInteger(t)||t<n||t>i)throw new RangeError(`${e} \u306F ${n}\u301C${i} \u306E\u6574\u6570\u3067\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044\u3002`)},An=(e,t)=>{se(e)&&le(e,t)},Nn=(e,t)=>{if(!se(e))throw new TypeError(`The range table bounds no parameter named ${JSON.stringify(e)}.`);le(e,t)};var G=r.enum(["QDRANT","NEO4J"]),Ke=r.enum(["PRODUCTION","VARIANT","LABEL"]),de=r.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","OUT_OF_TIER","UNMARKED_SUPERSEDED","FLAG_DRIFT","VARIANT_FLAG_DRIFT","DETACHED","UNKEYED","MISSING","COUNT_MISMATCH","UNPROJECTED","UNKEYED_ENTITY"]),ue=de.exclude(["EXPECTED","LIVE","HISTORY"]),He=r.enum(["POINT","NODE","CHUNK","DOCUMENT"]),Ye=r.enum(["EXPECTED","HEALTHY","RETAINED","INFORMATIONAL","DISCREPANCY"]),je=r.enum(["NONE","PURGE","FLAG","REPROJECT"]),p=(e,t)=>Object.freeze({disposition:e,repairAction:t}),Be=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"),OUT_OF_TIER:p("DISCREPANCY","PURGE"),UNMARKED_SUPERSEDED:p("DISCREPANCY","FLAG"),FLAG_DRIFT:p("DISCREPANCY","REPROJECT"),VARIANT_FLAG_DRIFT:p("DISCREPANCY","NONE"),DETACHED:p("DISCREPANCY","PURGE"),UNKEYED:p("DISCREPANCY","PURGE"),MISSING:p("DISCREPANCY","REPROJECT"),COUNT_MISMATCH:p("DISCREPANCY","REPROJECT"),UNPROJECTED:p("DISCREPANCY","REPROJECT"),UNKEYED_ENTITY:p("DISCREPANCY","NONE")}),$e=r.enum(["SCAN","REPAIR"]),Ve=r.enum(["RUNNING","COMPLETED","FAILED","CANCELLED","ABANDONED"]),Xe=r.enum(["CONSISTENT","INCONSISTENT","UNDETERMINED"]),qe=r.enum(["QDRANT","NEO4J","DOCUMENTS"]),Je=r.enum(["APPLIED","SKIPPED","FAILED"]),Qe=r.enum(["RECLASSIFIED","IN_FLIGHT","DESTINATION_PENDING","BASIS_EXHAUSTED","PROJECTION_REFUSED","PIPELINE_FAILED","UNRECORDED","OUTSIDE"]),D=100,E=r.number().int().nonnegative(),O=r.number().int().min(300).max(599),w=["repairedCount","repairFailedCount","repairSkippedCount"],me=r.string().regex(/^[0-9a-f]{64}$/,"A store fingerprint is 64 lowercase hexadecimal digits."),ce=x.INTEGRITY_TOMBSTONE_RETENTION_DAYS,We=r.object({runUid:_,mode:$e,status:Ve,requestedBy:r.string().min(1),executor:r.string().min(1),basisRunUid:_.nullable(),storeFingerprint:me,tombstoneRetentionDays:r.number().int().min(ce.min).max(ce.max),startedAt:u,finishedAt:u.nullable(),verdict:Xe.nullable(),errorClass:r.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:i,reprojectRebuildDocuments:l}=e;i===null||l===null?i!==l&&s(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are counted together with the documents it re-projects."):l>i&&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&&b(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.")},z=We.superRefine(Ze),et=r.object({store:G,scopeKey:r.string().min(1),scopeRole:Ke,itemClass:de,unit:He,disposition:Ye,repairAction:je,itemCount:E.nullable(),unmeasuredReason:r.string().min(1).nullable(),measuredAt:u.nullable(),repairedCount:E.nullable(),repairFailedCount:E.nullable(),repairSkippedCount:E.nullable()}).strict(),tt=(e,t)=>{let n=Be[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 i=e.itemCount===null;i!==(e.unmeasuredReason!==null)&&s(t,["unmeasuredReason"],"An unmeasured quantity (itemCount null) has a reason, and a measured one has none."),i!==(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=r.object({run:z,phase:qe.nullable(),phaseScope:r.string().min(1).nullable(),phaseDone:E.nullable(),phaseTotal:E.nullable(),heartbeatAt:u,isStale:r.boolean(),cancelRequestedAt:u.nullable()}).strict(),ot=(e,t)=>{if(e.run.status!=="RUNNING"&&s(t,["run","status"],"The active run is a RUNNING run."),b(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=r.object({run:z,quantities:r.array(nt),previousStoreFingerprint:me.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[i,l]of e.quantities.entries()){let c=JSON.stringify([l.store,l.scopeKey,l.itemClass]);if(n.has(c)&&s(t,["quantities",i],"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",i,d],"A SCAN run repairs nothing, so its quantities carry no repair counts.")}},lt=["FAILED","CANCELLED","ABANDONED"],ct=r.object({run:z,repairAppliedItems:E.nullable(),hasNewerRepair:r.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.")},On=r.object({readAt:u,lastCompleted:at.superRefine(st).nullable(),active:it.nullable(),newerUnsuccessful:ct.superRefine(pt).nullable()}).strict(),dt=r.object({sequence:r.number().int().min(1),itemKey:r.string().min(1),metadataId:r.number().int().positive().nullable(),fileUri:r.string().nullable(),revision:r.number().int().nullable(),observed:r.record(r.string(),r.unknown()),repairOutcome:Je.nullable(),repairErrorClass:r.string().min(1).nullable(),repairSkipReason:Qe.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),Pn=r.object({sotDomain:r.string().nullable()}).passthrough(),yt=r.object({rows:r.array(mt),nextAfter:r.number().int().min(1).nullable(),recordedCount:E,totalCount:E.nullable()}).strict(),ft=(e,t)=>{for(let[n,i]of e.rows.entries()){let l=e.rows[n-1];l!==void 0&&i.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.")},Fn=yt.superRefine(ft),Ln=r.object({runUid:_,store:G,scopeKey:r.string().min(1),itemClass:ue,after:r.number().int().min(1).optional(),limit:r.number().int().min(1).max(D)}).strict(),vn=r.object({runUid:_,store:G,scopeKey:r.string().min(1),itemClass:ue.extract(["UNRECORDED"]),after:r.number().int().min(1).optional()}).strict(),Et=r.object({requeued:E,skipped:r.array(r.object({metadataId:r.number().int().min(1),reason:r.string().min(1)}).strict()),nextAfter:r.number().int().min(1).nullable()}).strict(),St=(e,t)=>{let n=e.requeued+e.skipped.length;n>D&&s(t,["requeued"],`One chunk settles at most ${D} documents.`),e.nextAfter!==null!=(n===D)&&s(t,["nextAfter"],"A chunk continues exactly when it read the limit.");let i=new Set;for(let[l,c]of e.skipped.entries())i.has(c.metadataId)&&s(t,["skipped",l,"metadataId"],"A chunk keeps a document back once."),i.add(c.metadataId)},kn=Et.superRefine(St),K=r.enum(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),pe=r.enum(["start","cancel"]),ht=K.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","FORBIDDEN","UPSTREAM_FAILED"]),It=K.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),M={start:ht,cancel:It},Rt=r.object({code:K.exclude(["UPSTREAM_FAILED"]),status:O,errorCode:r.number().int().nullable()}).strict(),ye=Object.freeze(r.array(Rt).parse(oe).map(e=>Object.freeze(e))),gt=(e,t)=>{e.code==="UPSTREAM_FAILED"||e.code==="FORBIDDEN"&&e.status===null||ye.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.`)},Un=r.discriminatedUnion("command",[r.object({command:pe.extract(["start"]),code:M.start,status:O.nullable()}).strict(),r.object({command:pe.extract(["cancel"]),code:M.cancel,status:O.nullable()}).strict()]).superRefine(gt),wn=(e,t,n)=>{let i=M[e],l=ye.find(c=>c.status===t&&(c.errorCode===null||c.errorCode===n)&&i.safeParse(c.code).success);return l===void 0?"UPSTREAM_FAILED":l.code},Mn=r.discriminatedUnion("ok",[r.object({ok:r.literal(!0),runUid:_}).strict(),r.object({ok:r.literal(!1),status:O,errorCode:r.number().int().nullable()}).strict()]);import{z as a}from"zod";var fe=a.enum(te),P=a.enum(ne),_t=a.enum(["RUNNING","SUCCEEDED","FAILED"]),At=a.enum(["RUNNING","SUCCEEDED","SKIPPED","FAILED"]),Nt=a.enum(["ingest","retry","resync"]),Ct=a.enum(["text_layer","ocr","transcript"]),S=a.number().int().nonnegative().nullable(),Tt=a.object({provider:a.string().nullable(),model:a.string().nullable(),engine:a.string().nullable(),prompt_key:a.string().nullable(),prompt_version:a.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:a.string().nullable(),embedding_model:a.string().nullable(),strategy_id:a.number().int().positive().nullable(),graph_nodes:S,body_source:Ct.nullable(),detail:a.record(a.string(),a.unknown())}).strict(),bt=["no_pages","no_pages_rendered"],xt=a.enum(bt),H="gate_closed:",Y="source_skipped:",j="nothing_to_read:",Ee="no_children",Dt=/^[A-Z][A-Z0-9_]*$/;function Ot(e){if(e===Ee)return{kind:"no_children"};if(e.startsWith(H)){let t=e.slice(H.length);return Dt.test(t)?{kind:"gate_closed",featureFlagKey:t}:null}if(e.startsWith(Y)){let t=P.safeParse(e.slice(Y.length));return t.success?{kind:"source_skipped",stepKey:t.data}:null}if(e.startsWith(j)){let t=xt.safeParse(e.slice(j.length));return t.success?{kind:"nothing_to_read",token:t.data}:null}return null}function jn(e){let t=Pt(e);if(Ot(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 Pt(e){switch(e.kind){case"gate_closed":return`${H}${e.featureFlagKey}`;case"no_children":return Ee;case"source_skipped":return`${Y}${e.stepKey}`;case"nothing_to_read":return`${j}${e.token}`;default:{let t=e;throw new RangeError(`Unknown skip reason kind: ${JSON.stringify(t)}`)}}}var Ft=a.object({id:a.number().int().positive(),runId:a.number().int().positive(),sequence:a.number().int().nonnegative(),stepKey:P,targetMetadataId:a.number().int().positive(),status:At,skipReason:a.string().nullable(),provenance:Tt.nullable(),strategyId:a.number().int().positive().nullable(),httpStatus:a.number().int().nullable(),errorCode:a.string().nullable(),errorMessage:a.string().nullable(),startedAt:u,finishedAt:u.nullable(),durationMs:S}).strict();function Lt(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 vt=Ft.superRefine(Lt),Se=a.object({id:a.number().int().positive(),tenantId:a.string().min(1),metadataId:a.number().int().positive(),revision:a.number().int().positive(),runUid:a.string().uuid(),jobId:a.string().min(1),attempt:a.number().int().positive(),trigger:Nt,documentKind:fe,flowKey:a.string().min(1),status:_t,retryScheduled:a.boolean(),failedStepKey:P.nullable(),errorMessage:a.string().nullable(),requestedBy:a.string().min(1),startedAt:u,finishedAt:u.nullable(),steps:a.array(vt)}).strict();function he(e,t){e.retryScheduled&&e.status!=="FAILED"&&s(t,["retryScheduled"],"Only a FAILED run can have a retry scheduled.")}var Bn=Se.superRefine(he),$n=Se.omit({steps:!0}).superRefine(he);function kt(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 Vn=a.object({documentKind:fe,stepKey:P,sampleCount:a.number().int().nonnegative(),succeeded:a.number().int().nonnegative(),failed:a.number().int().nonnegative(),skipped:a.number().int().nonnegative(),durationP50Ms:S,durationP95Ms:S,lastStartedAt:u.nullable()}).strict().superRefine(kt);var Ie=[{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"}],Ut=new Set(Ie.map(e=>e.key));function qn(e){return Ut.has(e)}function Jn(e){let t=Ie.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 Qn={pageSize:{min:1,max:200,default:50},topologyLabels:{min:1,max:24,default:24}};var A=-1,h=0;function wt(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 Zn(){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===A){if(h++,h>4095){for(;Date.now()<=A;);n=Date.now(),A=n,h=(t[6]<<4|t[7]&15)&1023}}else n>A?(A=n,h=(t[6]<<4|t[7]&15)&1023):(n=A,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 i=Array.from(t,c=>c.toString(16).padStart(2,"0")).join("");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function er(e){if(!wt(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{De as AmountEntrySchema,N as BaseEnrichmentClient,Ct as BodySourceSchema,en as BoundingBoxSchema,_e as CIRCUIT_BREAKER_SERVICES,Fe as CanonicalDomainKeySchema,be as ChapterSegmentSchema,rn as ChunkingStrategySchema,nn as CircuitBreakerStatusSchema,L as ConfidentialityLevelSchema,Ce as DISPATCH_DEGRADATION_REASONS,te as DOCUMENT_KINDS,pn as DOCUMENT_KIND_LABELS,fe as DocumentKindSchema,tn as DocumentStructuredDataSchema,Ie as ENRICHMENT_STAGES,J as EnrichmentClient,g as EnrichmentClientError,Zt as EnrichmentSyncStatusSchema,Yt as FILTERABLE_CONFIDENTIALITY_LEVELS,Wt as FileUriSchema,Qn as GRAPH_INDEX_LIMITS,ve as GraphSearchHitSchema,Be as INTEGRITY_CLASS_POLICY,ye as INTEGRITY_COMMAND_CODES,D as INTEGRITY_FINDINGS_PAGE_LIMIT_MAX,it as IntegrityActiveRunSchema,On as IntegrityAuditOverviewSchema,It as IntegrityCancelFailureCodeSchema,vn as IntegrityCellResyncRequestSchema,kn as IntegrityCellResyncResultSchema,K as IntegrityCommandFailureCodeSchema,Un as IntegrityCommandFailureSchema,Mn as IntegrityCommandReplySchema,pe as IntegrityCommandSchema,Ye as IntegrityDispositionSchema,ue as IntegrityFindingItemClassSchema,Fn as IntegrityFindingPageSchema,mt as IntegrityFindingSchema,Ln as IntegrityFindingsQuerySchema,de as IntegrityItemClassSchema,qe as IntegrityPhaseSchema,Pn as IntegrityPlacementObservedSchema,nt as IntegrityQuantitySchema,je as IntegrityRepairActionSchema,Je as IntegrityRepairOutcomeSchema,Qe as IntegrityRepairSkipReasonSchema,z as IntegrityRunHeaderSchema,$e as IntegrityRunModeSchema,Ve as IntegrityRunStatusSchema,Ke as IntegrityScopeRoleSchema,ht as IntegrityStartFailureCodeSchema,G as IntegrityStoreSchema,He as IntegrityUnitSchema,Xe as IntegrityVerdictSchema,Ae as LOCAL_DEGRADATION_REASONS,ke as MIME_KIND_RULES,C as MODE_TIERS,ge as ModelProviderSchema,bt as NOTHING_TO_READ_TOKENS,xt as NothingToReadTokenSchema,Ue as PIPELINE_FLOWS,un as PIPELINE_PHASES,re as PIPELINE_STEPS,ne as PIPELINE_STEP_KEYS,Bn as PipelineRunRecordSchema,_t as PipelineRunStatusSchema,$n as PipelineRunSummarySchema,P as PipelineStepKeySchema,Vn as PipelineStepMetricSchema,vt as PipelineStepRecordSchema,At as PipelineStepStatusSchema,Nt as PipelineTriggerSchema,v as QUARANTINED_CONFIDENTIALITY_LEVEL,Ne as REMOTE_DEGRADATION_REASONS,Xt as SEARCH_DEGRADATION_REASONS,V as SEARCH_MODES,Ht as SEARCH_PARAM_LIMITS,x as SYSTEM_PARAMETER_RANGES,Le as SearchHitSchema,Pe as SearchMetadataSchema,Oe as SearchModeSchema,X as SearchRequestSchema,q as SearchResponseSchema,Tt as StageProvenanceSchema,Te as TenantIdSchema,xe as TranscriptSegmentSchema,Nn as assertBoundedSystemParameter,An as assertSystemParameterInRange,dn as classifyDocumentKind,En as comparePhases,Jn as enrichmentStage,mn as flowFor,yn as flowStepGates,jn as formatSkipReason,Zn as generateUuidV7,wn as integrityCommandFailureCodeOf,qn as isEnrichmentStageKey,b as isStrictlyEarlier,wt as isValidUuidV7,Vt as modeFusesRankings,jt as modeNeedsRemoteTiers,Bt as modeScoreIsSimilarity,$t as narrowModeToAllowedTiers,fn as orderedSteps,Ot as parseSkipReason,er as uuidv7ToDate};
|