@aiquants/enrichment-core 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AI Quants
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # @aiquants/enrichment-core
2
+
3
+ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types, RFC 9562 UUIDv7 utility, and API client SDK.
4
+
5
+ ストレージメタデータ・AI エンリッチメント基盤の正準 TypeScript 型定義、RFC 9562 準拠 UUIDv7 ユーティリティ、およびクライアント SDK を提供する共有コアライブラリ。
6
+
7
+ ## Features / 主な機能
8
+
9
+ - **RFC 9562 UUIDv7**: ゼロ依存のブラウザ・Node.js 共通ミリ秒タイムスタンプ付き時間順序 UUIDv7 生成・復元 (`generateUuidV7`, `uuidv7ToDate`, `isValidUuidV7`)。
10
+ - **Canonical Types & Schemas**: `EnrichmentSyncStatus`, `DocumentStructuredData`, `BoundingBox`, `SearchMetadata`, `CircuitBreakerStatus` 等の正準 TypeScript 型および Zod スキーマ。
11
+ - **EnrichmentClient**: セマンティック/ハイブリッド検索、メタデータ取得、動的再分類を扱う高信頼 HTTP クライアント SDK。
12
+ - **EnrichmentAdminClient**: Tri-Store 状態監視、同期ステータス集計、Qdrant 統計取得、失敗再エンキュー、整合性修復を扱う管理者用 SDK。
13
+
14
+ ## Installation / インストール
15
+
16
+ ```bash
17
+ pnpm add @aiquants/enrichment-core
18
+ ```
19
+
20
+ ## Usage / 利用例
21
+
22
+ ```typescript
23
+ import { generateUuidV7, uuidv7ToDate, EnrichmentClient } from "@aiquants/enrichment-core"
24
+
25
+ // UUIDv7 の生成とタイムスタンプ復元
26
+ const id = generateUuidV7()
27
+ const createdAt = uuidv7ToDate(id)
28
+
29
+ // クライアントの初期化と検索
30
+ const client = new EnrichmentClient({ baseUrl: "https://api.example.com" })
31
+ const result = await client.search({
32
+ query: "契約書の第3条",
33
+ tenant_id: "acme",
34
+ })
35
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var b=Object.defineProperty;var Q=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var J=Object.prototype.hasOwnProperty;var W=(r,t)=>{for(var n in t)b(r,n,{get:t[n],enumerable:!0})},Z=(r,t,n,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of X(t))!J.call(r,o)&&o!==n&&b(r,o,{get:()=>t[o],enumerable:!(a=Q(t,o))||a.enumerable});return r};var ee=r=>Z(b({},"__esModule",{value:!0}),r);var ye={};W(ye,{AmountEntrySchema:()=>z,BaseEnrichmentClient:()=>h,BoundingBoxSchema:()=>v,CanonicalDomainKeySchema:()=>A,ChapterSegmentSchema:()=>k,ChunkingStrategySchema:()=>B,CircuitBreakerStatusSchema:()=>q,ConfidentialityLevelSchema:()=>d,DocumentStructuredDataSchema:()=>le,ENRICHMENT_STAGES:()=>w,EnrichmentClient:()=>M,EnrichmentClientError:()=>u,EnrichmentSyncStatusSchema:()=>se,FILTERABLE_CONFIDENTIALITY_LEVELS:()=>ne,FileMetadataResponseSchema:()=>I,FileUriSchema:()=>m,GRAPH_INDEX_LIMITS:()=>me,MODE_TIERS:()=>g,ModelProviderSchema:()=>O,QUARANTINED_CONFIDENTIALITY_LEVEL:()=>_,QualityTierSchema:()=>H,ReclassifyRequestSchema:()=>D,ReclassifyResponseSchema:()=>L,SEARCH_MODES:()=>T,SEARCH_PARAM_LIMITS:()=>te,SearchHitSchema:()=>V,SearchMetadataSchema:()=>K,SearchModeSchema:()=>G,SearchRequestSchema:()=>C,SearchResponseSchema:()=>N,TenantIdSchema:()=>f,TranscriptSegmentSchema:()=>U,enrichmentStage:()=>ue,generateUuidV7:()=>de,isEnrichmentStageKey:()=>pe,isValidUuidV7:()=>$,modeFusesRankings:()=>ie,modeNeedsRemoteTiers:()=>re,modeScoreIsSimilarity:()=>ae,narrowModeToAllowedTiers:()=>oe,uuidv7ToDate:()=>fe});module.exports=ee(ye);var u=class extends Error{statusCode;responseBody;parsedBody;constructor(t,n,a,o){super(t),this.name="EnrichmentClientError",this.statusCode=n,this.responseBody=a,this.parsedBody=o}},h=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,o){let c=`${this.baseUrl}${t}`;if(o){let i=new URLSearchParams;for(let[Y,S]of Object.entries(o))S!=null&&S.trim().length>0&&i.append(Y,S);let s=i.toString();s.length>0&&(c+=`?${s}`)}let E={Accept:"application/json"};this.apiKey&&(E.Authorization=`Bearer ${this.apiKey}`),a!==void 0&&(E["Content-Type"]="application/json");let F=new AbortController,j=setTimeout(()=>F.abort(),this.timeoutMs),p;try{p=await this.fetchFn(c,{method:n,headers:E,body:a!==void 0?JSON.stringify(a):void 0,signal:F.signal})}catch(i){let s=i instanceof Error?i.message:String(i);throw new u(`Network request failed for ${n} ${c}: ${s}`,0,"")}finally{clearTimeout(j)}if(!p.ok){let i=await p.text().catch(()=>""),s;try{s=JSON.parse(i)}catch{}throw new u(`API request failed with status ${p.status}: ${i}`,p.status,i,s)}let x=await p.text().catch(()=>"");if(x.trim().length!==0)try{return JSON.parse(x)}catch(i){let s=i instanceof Error?i.message:String(i);throw new u(`Failed to parse response JSON from ${c}: ${s}`,p.status,x)}}};var e=require("zod");var R=require("zod"),O=R.z.enum(["google_cloud","google_vision","yomitoku_local","faster_whisper_local","google_speech","ollama_local","openai","anthropic","azure_openai","bedrock","custom_openai_compatible"]),d=R.z.enum(["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"]),_="RESTRICTED";var te={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}},P=d.options.filter(r=>r!==_);if(P.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 ne=P,T=["KEYWORD","SPARSE","DENSE","HYBRID","GRAPH_TRAVERSE"],g={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 re(r){let t=g[r];return t.dense||t.sparse||t.graph}function ae(r){let t=g[r];return t.dense&&!t.sparse}function oe(r,t){let n=g[r],a=(n.dense||n.sparse)&&t.vector,o=n.graph&&t.graph;return a||o?a?o?{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 ie(r){let t=g[r];return[t.dense,t.sparse,t.graph,t.lexical].filter(Boolean).length>1}var f=e.z.string().trim().min(1,"tenant_id must be a non-empty string"),m=e.z.string().trim().min(1,"file_uri must be a non-empty string"),se=e.z.enum(["PENDING","EXTRACTING","ENRICHING","PROJECTING","SYNCED","FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"]),v=e.z.object({page:e.z.number().int().positive().optional(),x:e.z.number().nonnegative().optional(),y:e.z.number().nonnegative().optional(),width:e.z.number().positive().optional(),height:e.z.number().positive().optional(),start_sec:e.z.number().nonnegative().optional(),end_sec:e.z.number().nonnegative().optional(),frame_index:e.z.number().int().nonnegative().optional(),timestamp_sec:e.z.number().nonnegative().optional(),scene_confidence:e.z.number().min(0).max(1).optional()}),k=e.z.object({title:e.z.string().trim().min(1),start_sec:e.z.number().nonnegative(),end_sec:e.z.number().nonnegative(),summary:e.z.string()}),U=e.z.object({start_sec:e.z.number().nonnegative(),end_sec:e.z.number().nonnegative(),speaker:e.z.string().trim().min(1),text:e.z.string()}),z=e.z.object({label:e.z.string(),value:e.z.number(),currency:e.z.string()}),le=e.z.object({document_type:e.z.string().optional(),title:e.z.string().optional(),organization:e.z.string().optional(),key_entities:e.z.array(e.z.string()).optional(),dates:e.z.array(e.z.string()).optional(),amounts:e.z.array(z).optional(),media_type:e.z.enum(["video","audio"]).optional(),duration_sec:e.z.number().nonnegative().optional(),chapters:e.z.array(k).optional(),transcript_segments:e.z.array(U).optional()}),q=e.z.enum(["CLOSED","OPEN","HALF_OPEN"]),H=e.z.enum(["FULL_HYBRID","VECTOR_ONLY","GRAPH_ONLY","STANDARD_SEMANTIC","DEGRADED_KEYWORD_ONLY"]),G=e.z.enum(T),K=e.z.object({search_mode:G,quality_tier:H,is_degraded:e.z.boolean(),degradation_reason:e.z.string().nullable().optional(),circuit_breaker_status:e.z.record(q).optional(),latency_ms:e.z.number().nonnegative()}),A=e.z.enum(["CONTRACT_LEGAL","EMAIL_THREAD","DAILY_REPORT","FINANCIAL_REPORT","TECHNICAL_SPEC","MASTER_DATA","MEDIA_ASSET","GENERAL_DOCUMENT"]),B=e.z.enum(["hierarchical","conversation","section","fixed_size","table_aware","semantic","none","multimodal"]),I=e.z.object({id:e.z.number().int().positive(),tenant_id:f,parent_metadata_id:e.z.number().int().positive().nullable().optional(),file_uri:m,file_uri_hash:e.z.string(),revision:e.z.number().int().nonnegative(),is_current:e.z.boolean(),is_deleted:e.z.boolean(),is_derived:e.z.boolean(),file_name:e.z.string(),file_path:e.z.string(),folder_path:e.z.string().nullable().optional(),confidentiality_level:d,department_id:e.z.number().int().positive().nullable().optional(),file_size:e.z.number().int().nonnegative(),mime_type:e.z.string(),asset_type:e.z.string().nullable().optional(),asset_index:e.z.number().int().nonnegative().nullable().optional(),bounding_box:v.nullable().optional(),created_at:e.z.string(),updated_at:e.z.string()}),V=e.z.object({chunk_uid:e.z.string().min(1),file_uri:m,score:e.z.number(),content:e.z.string(),chunk_index:e.z.number().int().nonnegative(),clause_identifier:e.z.string().nullable().optional(),authority_tier:e.z.number().int().positive().nullable().optional(),breadcrumb_path:e.z.string().nullable().optional(),bounding_box:v.nullable().optional()}),C=e.z.object({query:e.z.string().trim().min(1,"query must not be empty"),tenant_id:f,domain_key:A.optional(),limit:e.z.number().int().positive().default(10),department_id:e.z.number().int().positive().optional(),user_roles:e.z.array(e.z.string()).default([])}),N=e.z.object({hits:e.z.array(V),metadata:K}),D=e.z.object({file_uri:m,tenant_id:f,force:e.z.boolean().default(!1)}),L=e.z.object({file_uri:m,domain_key:A,strategy_name:e.z.string(),chunking_strategy:B.optional(),applied_rule_name:e.z.string().nullable().optional(),assigned_department_id:e.z.number().int().positive().nullable().optional()});var M=class extends h{async search(t){let n=C.parse(t),a=await this.request("/ai/search","POST",n);return N.parse(a)}async reclassify(t){let n=D.parse(t),a=await this.request("/ai/reclassify","POST",n);return L.parse(a)}async getFileMetadata(t,n){let a=m.parse(t),o=f.parse(n),c=await this.request("/ai/metadata","GET",void 0,{file_uri:a,tenant_id:o});return I.parse(c)}async getMetadata(t,n){return this.getFileMetadata(t,n)}};var w=[{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"}],ce=new Set(w.map(r=>r.key));function pe(r){return ce.has(r)}function ue(r){let t=w.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 me={pageSize:{min:1,max:200,default:50},topologyLabels:{min:1,max:24,default:24}};var y=-1,l=0;function $(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 de(){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===y){if(l++,l>4095){for(;Date.now()<=y;);n=Date.now(),y=n,l=(t[6]<<4|t[7]&15)&1023}}else n>y?(y=n,l=(t[6]<<4|t[7]&15)&1023):(n=y,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 fe(r){if(!$(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)}0&&(module.exports={AmountEntrySchema,BaseEnrichmentClient,BoundingBoxSchema,CanonicalDomainKeySchema,ChapterSegmentSchema,ChunkingStrategySchema,CircuitBreakerStatusSchema,ConfidentialityLevelSchema,DocumentStructuredDataSchema,ENRICHMENT_STAGES,EnrichmentClient,EnrichmentClientError,EnrichmentSyncStatusSchema,FILTERABLE_CONFIDENTIALITY_LEVELS,FileMetadataResponseSchema,FileUriSchema,GRAPH_INDEX_LIMITS,MODE_TIERS,ModelProviderSchema,QUARANTINED_CONFIDENTIALITY_LEVEL,QualityTierSchema,ReclassifyRequestSchema,ReclassifyResponseSchema,SEARCH_MODES,SEARCH_PARAM_LIMITS,SearchHitSchema,SearchMetadataSchema,SearchModeSchema,SearchRequestSchema,SearchResponseSchema,TenantIdSchema,TranscriptSegmentSchema,enrichmentStage,generateUuidV7,isEnrichmentStageKey,isValidUuidV7,modeFusesRankings,modeNeedsRemoteTiers,modeScoreIsSimilarity,narrowModeToAllowedTiers,uuidv7ToDate});