@aiquants/enrichment-core 0.2.0 → 0.3.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/README.md +16 -14
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +9 -5
- package/dist/index.d.ts +9 -5
- package/dist/index.js +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
|
|
|
11
11
|
- **EnrichmentClient**: ハイブリッド検索 (`POST /ai/search/hybrid`) を呼ぶ HTTP クライアント SDK。要求・応答のスキーマ (`SearchRequestSchema` / `SearchResponseSchema`) は Python 側 `HybridSearchRequest` / `HybridSearchResponse` と項目ごとに一致する。詳細は下の「Search client contract」。
|
|
12
12
|
- **Pipeline flow as data** (`flow.ts`): 文書種 (`DOCUMENT_KINDS` / `classifyDocumentKind`)、段 (`PIPELINE_STEPS`)、種類ごとの段の DAG (`PIPELINE_FLOWS` / `flowFor` / `orderedSteps`)。ワーカーの実行順とコンソールの図はこの 1 つの表から導く。段は自分を閉じるテナントのフラグ (`gates`) と、閉じたときの意味 (`skip` / `fail`) を宣言し、流れは段ごとにその意味を上書きできる (`FlowStep.gatePolicy`)。流れの中の門は `flowStepGates` で読む。詳細は下の「Pipeline flow contract」。
|
|
13
13
|
- **Pipeline records** (`pipelineRecord.ts`): 1 回の実行 (`PipelineRunRecordSchema`) と段ごとの記録 (`PipelineStepRecordSchema`)、段を除いた実行の要約 (`PipelineRunSummarySchema`、一覧向け)、段が自身について報告する値 (`StageProvenanceSchema`、Python 側の `StageProvenance` と項目ごとに一致)、段の集計 (`PipelineStepMetricSchema`)、飛ばした理由の文法 (`SkipReason` / `formatSkipReason` / `parseSkipReason`、読む対象が無かったときの値 `NOTHING_TO_READ_TOKENS` / `NothingToReadTokenSchema`)。測っていない値は `null` で、欠落させない。詳細は下の「Pipeline record contract」。
|
|
14
|
-
- **Integrity audit contract** (`integrity.ts`): Tri-Store 整合性監査の記録の語彙 (`IntegrityStoreSchema` を含む 12 の列挙と、所見を記録する区分 `IntegrityFindingItemClassSchema`)、区分の扱いと処置の表 (`INTEGRITY_CLASS_POLICY`)、概況 (`IntegrityAuditOverviewSchema`)、所見の頁と要求 (`IntegrityFindingPageSchema` / `IntegrityFindingsQuerySchema`)、開始・中止の命令と命令ごとの失敗の語彙 (`IntegrityCommandSchema` / `IntegrityCommandFailureSchema`) と (状態, 業務コード) の表 (`integrityCommandCodes.json` / `INTEGRITY_COMMAND_CODES` / `integrityCommandFailureCodeOf`)、ホストのストアの応答 (`IntegrityCommandReplySchema`)。詳細は下の「Integrity audit contract」。
|
|
14
|
+
- **Integrity audit contract** (`integrity.ts`): Tri-Store 整合性監査の記録の語彙 (`IntegrityStoreSchema` を含む 12 の列挙と、所見を記録する区分 `IntegrityFindingItemClassSchema`)、区分の扱いと処置の表 (`INTEGRITY_CLASS_POLICY`)、概況 (`IntegrityAuditOverviewSchema`)、所見の頁と要求 (`IntegrityFindingPageSchema` / `IntegrityFindingsQuerySchema`)、開始・中止の命令と命令ごとの失敗の語彙 (`IntegrityCommandSchema` / `IntegrityCommandFailureSchema`) と (状態, 業務コード) の表 (`integrityCommandCodes.json` / `INTEGRITY_COMMAND_CODES` / `integrityCommandFailureCodeOf`)、ホストのストアの応答 (`IntegrityCommandReplySchema`)、契約の時刻の前後の比較 (`isStrictlyEarlier`)。詳細は下の「Integrity audit contract」。
|
|
15
15
|
- **System parameter ranges** (`systemParameterRanges.ts`): 値域を持つシステムパラメータの唯一の表 (`systemParameterRanges.json` / `SYSTEM_PARAMETER_RANGES`) と、書き手が当てる検査 (`assertSystemParameterInRange`) と読み手が当てる検査 (`assertBoundedSystemParameter`)。詳細は下の「System parameter ranges」。
|
|
16
16
|
|
|
17
17
|
## Search client contract / 検索クライアントの契約
|
|
@@ -22,7 +22,7 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
|
|
|
22
22
|
| `SearchResponseSchema` | `HybridSearchResponse` | `hits` (`SearchHitSchema`: `metadata_id` / `chunk_index` / `text` / `score`)、`graph_hits` (`GraphSearchHitSchema`)、`tiers` (層の名前ごとの真偽値)、`metadata` |
|
|
23
23
|
| `SearchMetadataSchema` | `SearchMetadata` | `circuit_breaker_status` と `quality_tier` は文字列 (検索サービスは走らせたモード、層を飛ばしたときは `DEGRADED` を報告)、`latency_ms`、`total_hits`、`fallback_applied`、`degraded_reason` (飛ばした層の理由、無ければ `null`) |
|
|
24
24
|
|
|
25
|
-
- `EnrichmentClient` が持つのは `search` だけである。送信先は `<baseUrl>/ai/search/hybrid` であり、`baseUrl` はエンリッチメントのルーターが載る API ルート (
|
|
25
|
+
- `EnrichmentClient` が持つのは `search` だけである。送信先は `<baseUrl>/ai/search/hybrid` であり、`baseUrl` はエンリッチメントのルーターが載る API ルート (エンリッチメントのルーターを載せる API サーバーのホストと API 接頭辞、例 `https://api.example.com/api/v1`)。
|
|
26
26
|
- ルートは `Authorization: Bearer <apiKey>` の利用者を認可し、テナントを `X-Tenant-Id` から取る。クライアントは `X-Tenant-Id` に本文の `tenant_id` を入れる (両者が食い違えばルートが 403 で拒む)。`apiKey` には利用者のアクセストークンを渡す (無ければルートが拒む)。
|
|
27
27
|
- 2xx 以外の応答と通信失敗は `EnrichmentClientError` (`statusCode`・`responseBody`・JSON なら `parsedBody`、通信失敗は `statusCode` 0)、JSON でない 2xx は `EnrichmentClientError`、スキーマに反する要求・応答 (空本文を含む) は `ZodError` を投げる。
|
|
28
28
|
- 縮退理由の語彙 (`search.ts`) は閉じた集合であり、発生源ごとに `LOCAL_DEGRADATION_REASONS` (web が遠隔層を呼ばなかった理由) / `REMOTE_DEGRADATION_REASONS` (検索サービスが層を飛ばした理由) / `DISPATCH_DEGRADATION_REASONS` (遠隔の呼び出しと管理者の無効化) と、遮断器の `circuit_breaker_open:<service>` に分かれる (4 つは重ならない)。
|
|
@@ -44,7 +44,7 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
|
|
|
44
44
|
| `FlowStep.gatePolicy` (`FlowGatePolicy`) | 1 つの流れに限り、その段の全ての門の意味を上書きする。宣言できるのは `{ whenClosed: "fail", failureStatus }` だけ。門を持たない段に書くと `orderedSteps` が throw する |
|
|
45
45
|
| `flowStepGates(flowStep)` | 流れの中で段が持つ門 (上書きを適用した結果、宣言順)。ワーカーが評価し、コンソールが描くのはこの値であり、`PIPELINE_STEPS[key].gates` を直に読まない |
|
|
46
46
|
|
|
47
|
-
- 子の読み取りの段 (`ocr_children`) は門を宣言しない。子の文字層 (テキスト・メール・Office・PDF) は `ENABLE_OCR` に関係なく読まなければならず、段ごと飛ばすと添付のテキストが本文から消えるためである。認識の要る子だけが
|
|
47
|
+
- 子の読み取りの段 (`ocr_children`) は門を宣言しない。子の文字層 (テキスト・メール・Office・PDF) は `ENABLE_OCR` に関係なく読まなければならず、段ごと飛ばすと添付のテキストが本文から消えるためである。認識の要る子だけが API サーバー の中で `ENABLE_OCR` に従い、閉じていればワーカーはその子の行を `gate_closed:ENABLE_OCR` で `SKIPPED` と記録する (段のキーに OCR の名が残るのは、共有 DB の段の記録と集計がこのキーで引かれるためであり、運用者に見せる名前は「子アセットの読み取り」)。
|
|
48
48
|
- 出荷する上書きは 2 つだけ: 画像の流れの `ocr_document` とメディアの流れの `analyze_media`。どちらも流れの唯一の本文の出所であり、フラグ (`ENABLE_OCR` / `ENABLE_MEDIA_ANALYSIS`) が閉じていれば、その門で実行を `FAILED_EXTRACT` として止める。文字層を持つ流れ (pdf / email / office / google_native) の `ocr_document` は宣言どおり飛ばす。
|
|
49
49
|
- 実行側の契約 (`orderedSteps` の docstring): ワーカーは `orderedSteps(flow)` の順に段を走らせ、各段の前に `flowStepGates(step)` を評価する。最初に閉じていた門が決める — `skip` は段を `gate_closed:<flag>` で `SKIPPED` と記録して次へ進み、`fail` は段を `FAILED` と記録してその門の `failureStatus` で実行を終える。段は全ての門が開いているときだけ走る。
|
|
50
50
|
- どの流れも、門で飛ばされうる段だけに本文を頼らない (本文を作りうる段 `extract_text` / `ocr_document` / `analyze_media` のうち少なくとも 1 つは、閉じれば実行を止めるか門を持たない)。テストが出荷する全ての流れでこれを検査する。
|
|
@@ -92,7 +92,7 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
|
|
|
92
92
|
|
|
93
93
|
## Integrity audit contract / 整合性監査の契約
|
|
94
94
|
|
|
95
|
-
監査は
|
|
95
|
+
監査は API サーバー の中で走り、`td_integrity_audit_run` / `td_integrity_audit_quantity` / `td_integrity_audit_finding` へ記録する。ホストはその行を読み、次の形でコンソールへ渡す。記録の語彙 (下の表の `IntegrityStoreSchema` から `IntegrityRepairSkipReasonSchema` までの 12 の列挙と `IntegrityFindingItemClassSchema`) と区分の方針 (`INTEGRITY_CLASS_POLICY`) は各表の CHECK 制約の写しであり、実行の行の制約が持つ削除印の保持日数の範囲は、実行の見出しを検める `SYSTEM_PARAMETER_RANGES.INTEGRITY_TOMBSTONE_RETENTION_DAYS` の写しである。写しの一致はホストの試験が DDL を読んで確かめる (本パッケージはホストの DDL の置き場所を知らない)。
|
|
96
96
|
|
|
97
97
|
命令の語彙 (`IntegrityCommandSchema` / `IntegrityCommandFailureCodeSchema` と命令ごとのその部分集合) はコンソールの契約の持ち物で、DDL に写しを持たない。全てのスキーマは `.strict()` で、未知の鍵と鍵の欠落を拒む (最初の頁で省く `IntegrityFindingsQuerySchema.after` を除く)。`null` は宣言した項目 (測っていない・まだ無い) だけが持てる。
|
|
98
98
|
|
|
@@ -100,11 +100,13 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
|
|
|
100
100
|
|
|
101
101
|
- 契約が運ぶ項目についての CHECK 制約の規則。契約が運ばない列の規則 (完了した実行の段、中止した実行の中止の要求) は DB に任せる。
|
|
102
102
|
- ホストが読むときの一意の鍵 (組ごとに量 1 つ、所見は記録順)。
|
|
103
|
-
- 制約は持たないが、書き手 (
|
|
103
|
+
- 制約は持たないが、書き手 (API サーバー) と読み手 (ホスト) が保証する規則: 概況の各区画の実行は読み手が選んだ状態を持つ (`active` は `RUNNING`、`lastCompleted` は `COMPLETED`、`newerUnsuccessful` は `FAILED` / `CANCELLED` / `ABANDONED`)、`SCAN` の量は修復の件数を持たない、`DOCUMENTS` の段は範囲を持たない、`nextAfter` は頁の最後の行の `sequence`、不成功の `REPAIR` の `hasNewerRepair` は真。
|
|
104
104
|
|
|
105
105
|
これらを破る値は書き手か読み手の欠陥であり、契約は描かずに拒む。
|
|
106
106
|
|
|
107
|
-
実行の UID (`runUid` / `basisRunUid`、所見の要求と応答の `runUid` を含む) は 16 進の桁を大小文字を問わず受け入れ、小文字へ直して返す (RFC 9562 は桁を大小文字を問わず読み、小文字で書く)。
|
|
107
|
+
実行の UID (`runUid` / `basisRunUid`、所見の要求と応答の `runUid` を含む) は 16 進の桁を大小文字を問わず受け入れ、小文字へ直して返す (RFC 9562 は桁を大小文字を問わず読み、小文字で書く)。API サーバー は小文字で発行し、SQL Server の `uniqueidentifier` は tedious から大文字で届くが、契約を通した後は 1 つの実行が 1 つの綴りを持つ (コンソールは実行を文字列の等しさで比べる)。ホストの読み手が綴りを直す必要は無い。
|
|
108
|
+
|
|
109
|
+
契約の時刻 (`readAt`・`startedAt`・`heartbeatAt` など) の前後は、`Date.parse` でなく公開する `isStrictlyEarlier(earlier, later)` で比べる (`Date.parse` はミリ秒までしか保たず、100 ns 違う 2 つの時刻を等しいと見る)。両方が契約の受ける時刻で `earlier` が `later` より厳密に前のときだけ `true` を返し、時差 (`Z`・`±HH:mm`・`±HHmm`)・秒の省略・1 秒未満の全ての桁を読んで比べる。どちらかが契約の受ける時刻でなければどちらの向きにも `false` なので、`!isStrictlyEarlier(a, b)` は「`a` が `b` の後か同時」ではない。比べる前に値を契約 (`IntegrityAuditOverviewSchema` など) で検める。契約自身も同じ関数で、`finishedAt` と `heartbeatAt` が `startedAt` より前でないことを検める。
|
|
108
110
|
|
|
109
111
|
| Vocabulary / 語彙 | Values / 値 |
|
|
110
112
|
| --- | --- |
|
|
@@ -135,7 +137,7 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
|
|
|
135
137
|
| `FLAG_DRIFT`・`DETACHED`・`UNKEYED` | `DISCREPANCY` | `NONE` |
|
|
136
138
|
| `MISSING`・`COUNT_MISMATCH` | `DISCREPANCY` | `REPROJECT` |
|
|
137
139
|
|
|
138
|
-
判定 (`IntegrityVerdictSchema`) は `DISCREPANCY` の量を数え、`CONSISTENT` になれるのは扱いに依らず全ての量が測れたときだけ (測れた不整合が 1 つでも正なら、他の量の未測定に依らず `INCONSISTENT`)。判定の規則は
|
|
140
|
+
判定 (`IntegrityVerdictSchema`) は `DISCREPANCY` の量を数え、`CONSISTENT` になれるのは扱いに依らず全ての量が測れたときだけ (測れた不整合が 1 つでも正なら、他の量の未測定に依らず `INCONSISTENT`)。判定の規則は API サーバー が持ち、この契約は判定と量の突き合わせをしない。判定とタイルは単位 (`IntegrityUnitSchema`) の違う量を足さない。単位を混ぜた唯一の和は、不成功の修復の `repairAppliedItems` (適用した点とノードの数) である。
|
|
139
141
|
|
|
140
142
|
| Schema | Rules checked across fields / 項目の間で検める規則 |
|
|
141
143
|
| --- | --- |
|
|
@@ -148,17 +150,17 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
|
|
|
148
150
|
| `IntegrityFindingsQuerySchema` | `itemClass` は所見を記録する区分 (`IntegrityFindingItemClassSchema`) だけ。`limit` は必須で 1〜`INTEGRITY_FINDINGS_PAGE_LIMIT_MAX` (100) の整数 (0・負・`NaN`・文字列を拒む)。`after` は 1 以上の整数で、最初の頁では省く |
|
|
149
151
|
|
|
150
152
|
- コンソールが監査の実行について送る命令は `IntegrityCommandSchema` (`start` / `cancel`)。命令と失敗の語彙はコンソールの契約の持ち物で、DDL に写しを持たない。
|
|
151
|
-
- 開始・中止の失敗は `IntegrityCommandFailure` (`{command, code, status: 300〜599 の整数 | null}`、`command` で分かれる和の型) で運ぶ。`code` はコンソールが示す文ごとに 1 つ (`IntegrityCommandFailureCodeSchema`) で、各命令はその部分集合だけを持つ (
|
|
153
|
+
- 開始・中止の失敗は `IntegrityCommandFailure` (`{command, code, status: 300〜599 の整数 | null}`、`command` で分かれる和の型) で運ぶ。`code` はコンソールが示す文ごとに 1 つ (`IntegrityCommandFailureCodeSchema`) で、各命令はその部分集合だけを持つ (もう一方の命令だけの語彙は `code` の問題として拒み、型でも持てない):
|
|
152
154
|
- 開始 (`IntegrityStartFailureCodeSchema`): `DEPLOYMENT_DISABLED` / `RUN_ALREADY_ACTIVE` / `BASIS_INVALID` / `FORBIDDEN` / `UPSTREAM_FAILED`
|
|
153
|
-
- 中止 (`IntegrityCancelFailureCodeSchema`): `RUN_ALREADY_FINISHED` / `FORBIDDEN` / `UPSTREAM_FAILED` (
|
|
155
|
+
- 中止 (`IntegrityCancelFailureCodeSchema`): `DEPLOYMENT_DISABLED` / `RUN_ALREADY_FINISHED` / `FORBIDDEN` / `UPSTREAM_FAILED` (中止も共有の DB の実行の行を書くので、実行の切替を課される (修復の切替は課さない)。実行を始めることも根拠を名指すことも無い)
|
|
154
156
|
- 命令の語彙の型は `IntegrityCommandFailureCodeFor<Command>` で引ける。画面の文の表は命令ごとにこの型で漏れなく書ける。
|
|
155
157
|
- 表が名指す `code` は、その行の状態を持つ (`DEPLOYMENT_DISABLED` は 503、`RUN_ALREADY_ACTIVE` / `BASIS_INVALID` / `RUN_ALREADY_FINISHED` は 409、`FORBIDDEN` は 403)。例外は状態の無い `FORBIDDEN` だけ (ホストはトークンを持たない命令を送らずに拒むので、応答が無い)。`UPSTREAM_FAILED` は表に無い全ての失敗で、来た状態を持つか、応答が無ければ `status: null`。違反は `status` の問題として拒む。
|
|
156
|
-
- (状態, 業務コード) → `code` の表は `integrityCommandCodes.json` だけが持つ (このリポジトリの中では
|
|
157
|
-
- `integrityCommandFailureCodeOf(command, status, errorCode)` は、状態が等しく、業務コードが `null` か等しく、`code` がその命令の語彙である最初の行の `code` を、その命令の語彙の型で返す。業務コードが `null` の行 (`403` → `FORBIDDEN`) はその状態の全ての業務コードに一致する。その命令について一致する行の無い組 (
|
|
158
|
+
- (状態, 業務コード) → `code` の表は `integrityCommandCodes.json` だけが持つ (このリポジトリの中では API サーバー の試験も同じファイルを読む。公開する成果物は表を埋め込み、表と各行を凍結する。各行はモジュールの読み込みの時に検め、`UPSTREAM_FAILED` へ写す行・他の鍵を持つ行・300〜599 の外の状態の行があれば読み込みが投げる)。行の `code` がどの命令のものかは表でなく命令ごとの語彙が決める。
|
|
159
|
+
- `integrityCommandFailureCodeOf(command, status, errorCode)` は、状態が等しく、業務コードが `null` か等しく、`code` がその命令の語彙である最初の行の `code` を、その命令の語彙の型で返す。業務コードが `null` の行 (`403` → `FORBIDDEN`) はその状態の全ての業務コードに一致する。その命令について一致する行の無い組 (もう一方の命令だけの語彙へ写す組、`503` / `5030` と `503` / `5032` を含む) は `UPSTREAM_FAILED`。返した `code` は、命令と応答の状態とともに `IntegrityCommandFailureSchema` が受け入れる失敗になる。
|
|
158
160
|
|
|
159
161
|
| `status` | `errorCode` | `code` | 開始 | 中止 |
|
|
160
162
|
| --- | --- | --- | --- | --- |
|
|
161
|
-
| 503 | 5035 | `DEPLOYMENT_DISABLED` | ○ |
|
|
163
|
+
| 503 | 5035 | `DEPLOYMENT_DISABLED` | ○ | ○ |
|
|
162
164
|
| 409 | 4091 | `RUN_ALREADY_ACTIVE` | ○ | `UPSTREAM_FAILED` |
|
|
163
165
|
| 409 | 4092 | `BASIS_INVALID` | ○ | `UPSTREAM_FAILED` |
|
|
164
166
|
| 409 | 4093 | `RUN_ALREADY_FINISHED` | `UPSTREAM_FAILED` | ○ |
|
|
@@ -176,7 +178,7 @@ Transport- and DB-agnostic storage metadata AI enrichment core: canonical types,
|
|
|
176
178
|
| `INTEGRITY_RUN_RETENTION_COUNT` | 2〜100 |
|
|
177
179
|
| `POLICY_CONFLICT_MAX_TIE_GROUP_SIZE` | 2〜60 |
|
|
178
180
|
|
|
179
|
-
- 表の正本は `src/systemParameterRanges.json` の 1 つ。他の言語のホストは自分の写しを持ち、このリポジトリの中ではその試験がこのファイルを読んで一致を確かめる (
|
|
181
|
+
- 表の正本は `src/systemParameterRanges.json` の 1 つ。他の言語のホストは自分の写しを持ち、このリポジトリの中ではその試験がこのファイルを読んで一致を確かめる (API サーバー の `PARAMETER_RANGES`)。公開する成果物は表を埋め込む。
|
|
180
182
|
- `SYSTEM_PARAMETER_RANGES` は表と各値域を凍結してあり、型も値域まで読み取り専用である (プロセスの中の読み手の 1 つが値域を広げ、他の書き手と読み手の拒否を外すことができない)。
|
|
181
183
|
- `INTEGRITY_TOMBSTONE_RETENTION_DAYS` の値域は、実行の行の制約 (保持日数の範囲) と実行の見出しの契約 (`IntegrityRunHeaderSchema.tombstoneRetentionDays`) の範囲でもある。制約はこの表の写しなので、値域を変えるときは制約も同じ変更で改める (ホストの試験が一致を検める)。
|
|
182
184
|
- 表が抑えるパラメータは全て整数である。整数でないパラメータは、項目が型を宣言するまで表に加えられない。
|
|
@@ -244,7 +246,7 @@ import { assertBoundedSystemParameter, assertSystemParameterInRange, type Integr
|
|
|
244
246
|
// 監査の概況はホストの読み手が組んだ値を契約で検める (未測定は null のまま)
|
|
245
247
|
const overview = IntegrityAuditOverviewSchema.parse(body.overview)
|
|
246
248
|
|
|
247
|
-
// 中止のストアの失敗の応答を、画面が中止の文を選ぶ語彙へ写す (
|
|
249
|
+
// 中止のストアの失敗の応答を、画面が中止の文を選ぶ語彙へ写す (開始だけの語彙は型でも持てない)
|
|
248
250
|
const toCancelFailure = (reply: Extract<IntegrityCommandReply, { ok: false }>): IntegrityCommandFailure => ({ command: "cancel", code: integrityCommandFailureCodeOf("cancel", reply.status, reply.errorCode), status: reply.status })
|
|
249
251
|
|
|
250
252
|
// パラメータの書き手と読み手は同じ表で値域の外を拒む (RangeError の文面をそのまま示せる)
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var w=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var mt=(e,t)=>{for(var n in t)w(e,n,{get:t[n],enumerable:!0})},yt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dt(t))!ut.call(e,s)&&s!==n&&w(e,s,{get:()=>t[s],enumerable:!(i=pt(t,s))||i.enumerable});return e};var ft=e=>yt(w({},"__esModule",{value:!0}),e);var bn={};mt(bn,{AmountEntrySchema:()=>me,BaseEnrichmentClient:()=>A,BodySourceSchema:()=>Ze,BoundingBoxSchema:()=>Ct,CIRCUIT_BREAKER_SERVICES:()=>ae,CanonicalDomainKeySchema:()=>Ee,ChapterSegmentSchema:()=>de,ChunkingStrategySchema:()=>xt,CircuitBreakerStatusSchema:()=>bt,ConfidentialityLevelSchema:()=>x,DISPATCH_DEGRADATION_REASONS:()=>ce,DOCUMENT_KINDS:()=>B,DOCUMENT_KIND_LABELS:()=>Dt,DocumentKindSchema:()=>ne,DocumentStructuredDataSchema:()=>Tt,ENRICHMENT_STAGES:()=>re,EnrichmentClient:()=>K,EnrichmentClientError:()=>I,EnrichmentSyncStatusSchema:()=>Nt,FILTERABLE_CONFIDENTIALITY_LEVELS:()=>St,FileUriSchema:()=>At,GRAPH_INDEX_LIMITS:()=>Nn,GraphSearchHitSchema:()=>he,INTEGRITY_CLASS_POLICY:()=>we,INTEGRITY_COMMAND_CODES:()=>W,INTEGRITY_FINDINGS_PAGE_LIMIT_MAX:()=>Be,IntegrityActiveRunSchema:()=>$e,IntegrityAuditOverviewSchema:()=>Zt,IntegrityCancelFailureCodeSchema:()=>qe,IntegrityCommandFailureCodeSchema:()=>v,IntegrityCommandFailureSchema:()=>cn,IntegrityCommandReplySchema:()=>dn,IntegrityCommandSchema:()=>X,IntegrityDispositionSchema:()=>ve,IntegrityFindingItemClassSchema:()=>Fe,IntegrityFindingPageSchema:()=>on,IntegrityFindingSchema:()=>Ve,IntegrityFindingsQuerySchema:()=>an,IntegrityItemClassSchema:()=>Q,IntegrityPhaseSchema:()=>ze,IntegrityQuantitySchema:()=>Ye,IntegrityRepairActionSchema:()=>ke,IntegrityRepairOutcomeSchema:()=>Ke,IntegrityRepairSkipReasonSchema:()=>He,IntegrityRunHeaderSchema:()=>L,IntegrityRunModeSchema:()=>Me,IntegrityRunStatusSchema:()=>Ue,IntegrityScopeRoleSchema:()=>Pe,IntegrityStartFailureCodeSchema:()=>Xe,IntegrityStoreSchema:()=>J,IntegrityUnitSchema:()=>Le,IntegrityVerdictSchema:()=>Ge,LOCAL_DEGRADATION_REASONS:()=>se,MIME_KIND_RULES:()=>Ae,MODE_TIERS:()=>N,ModelProviderSchema:()=>oe,NOTHING_TO_READ_TOKENS:()=>tt,NothingToReadTokenSchema:()=>nt,PIPELINE_FLOWS:()=>Ne,PIPELINE_PHASES:()=>Pt,PIPELINE_STEPS:()=>Y,PIPELINE_STEP_KEYS:()=>j,PipelineRunRecordSchema:()=>Sn,PipelineRunStatusSchema:()=>Je,PipelineRunSummarySchema:()=>hn,PipelineStepKeySchema:()=>b,PipelineStepMetricSchema:()=>In,PipelineStepRecordSchema:()=>it,PipelineStepStatusSchema:()=>Qe,PipelineTriggerSchema:()=>We,QUARANTINED_CONFIDENTIALITY_LEVEL:()=>D,REMOTE_DEGRADATION_REASONS:()=>le,SEARCH_DEGRADATION_REASONS:()=>_t,SEARCH_MODES:()=>U,SEARCH_PARAM_LIMITS:()=>Et,SYSTEM_PARAMETER_RANGES:()=>T,SearchHitSchema:()=>Se,SearchMetadataSchema:()=>fe,SearchModeSchema:()=>ye,SearchRequestSchema:()=>G,SearchResponseSchema:()=>z,StageProvenanceSchema:()=>et,TenantIdSchema:()=>pe,TranscriptSegmentSchema:()=>ue,assertBoundedSystemParameter:()=>Kt,assertSystemParameterInRange:()=>zt,classifyDocumentKind:()=>Ot,comparePhases:()=>kt,enrichmentStage:()=>An,flowFor:()=>Ft,flowStepGates:()=>Lt,formatSkipReason:()=>mn,generateUuidV7:()=>Cn,integrityCommandFailureCodeOf:()=>pn,isEnrichmentStageKey:()=>_n,isValidUuidV7:()=>lt,modeFusesRankings:()=>Rt,modeNeedsRemoteTiers:()=>ht,modeScoreIsSimilarity:()=>gt,narrowModeToAllowedTiers:()=>It,orderedSteps:()=>vt,parseSkipReason:()=>ot,uuidv7ToDate:()=>Tn});module.exports=ft(bn);var I=class extends Error{statusCode;responseBody;parsedBody;constructor(t,n,i,s){super(t),this.name="EnrichmentClientError",this.statusCode=n,this.responseBody=i,this.parsedBody=s}},A=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 s=`${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(s,{method:"POST",headers:c,body:JSON.stringify(i),signal:d.signal})}catch(y){let g=y instanceof Error?y.message:String(y);throw new I(`Network request failed for POST ${s}: ${g}`,0,"")}finally{clearTimeout(m)}if(!f.ok){let y=await f.text().catch(()=>""),g;try{g=JSON.parse(y)}catch{}throw new I(`API request failed with status ${f.status}: ${y}`,f.status,y,g)}let R=await f.text().catch(()=>"");if(R.trim().length!==0)try{return JSON.parse(R)}catch(y){let g=y instanceof Error?y.message:String(y);throw new I(`Failed to parse response JSON from ${s}: ${g}`,f.status,R)}}};var r=require("zod");var M=require("zod"),oe=M.z.enum(["google_cloud","google_vision","yomitoku_local","faster_whisper_local","google_speech","ollama_local","openai","anthropic","azure_openai","bedrock","custom_openai_compatible"]),x=M.z.enum(["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"]),D="RESTRICTED";var Et={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}},ie=x.options.filter(e=>e!==D);if(ie.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 St=ie,U=["KEYWORD","SPARSE","DENSE","HYBRID","GRAPH_TRAVERSE"],N={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=N[e];return t.dense||t.sparse||t.graph}function gt(e){let t=N[e];return t.dense&&!t.sparse}function It(e,t){let n=N[e],i=(n.dense||n.sparse)&&t.vector,s=n.graph&&t.graph;return i||s?i?s?{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 Rt(e){let t=N[e];return[t.dense,t.sparse,t.graph,t.lexical].filter(Boolean).length>1}var ae=["vector","graph"],se=["empty_query","caller_token_unavailable","time_window_unsupported"],le=["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"],_t=[...se,...le,...ce,...ae.map(e=>`circuit_breaker_open:${e}`)];var pe=r.z.string().trim().min(1,"tenant_id must be a non-empty string"),At=r.z.string().trim().min(1,"file_uri must be a non-empty string"),Nt=r.z.enum(["PENDING","EXTRACTING","ENRICHING","PROJECTING","SYNCED","FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"]),Ct=r.z.object({page:r.z.number().int().positive().optional(),x:r.z.number().nonnegative().optional(),y:r.z.number().nonnegative().optional(),width:r.z.number().positive().optional(),height:r.z.number().positive().optional(),start_sec:r.z.number().nonnegative().optional(),end_sec:r.z.number().nonnegative().optional(),frame_index:r.z.number().int().nonnegative().optional(),timestamp_sec:r.z.number().nonnegative().optional(),scene_confidence:r.z.number().min(0).max(1).optional()}),de=r.z.object({title:r.z.string().trim().min(1),start_sec:r.z.number().nonnegative(),end_sec:r.z.number().nonnegative(),summary:r.z.string()}),ue=r.z.object({start_sec:r.z.number().nonnegative(),end_sec:r.z.number().nonnegative(),speaker:r.z.string().trim().min(1),text:r.z.string()}),me=r.z.object({label:r.z.string(),value:r.z.number(),currency:r.z.string()}),Tt=r.z.object({document_type:r.z.string().optional(),title:r.z.string().optional(),organization:r.z.string().optional(),key_entities:r.z.array(r.z.string()).optional(),dates:r.z.array(r.z.string()).optional(),amounts:r.z.array(me).optional(),media_type:r.z.enum(["video","audio"]).optional(),duration_sec:r.z.number().nonnegative().optional(),chapters:r.z.array(de).optional(),transcript_segments:r.z.array(ue).optional()}),bt=r.z.enum(["CLOSED","OPEN","HALF_OPEN"]),ye=r.z.enum(U),fe=r.z.object({circuit_breaker_status:r.z.string(),quality_tier:r.z.string(),latency_ms:r.z.number().nonnegative(),total_hits:r.z.number().int().nonnegative(),fallback_applied:r.z.boolean(),degraded_reason:r.z.string().nullable()}),Ee=r.z.enum(["CONTRACT_LEGAL","EMAIL_THREAD","DAILY_REPORT","FINANCIAL_REPORT","TECHNICAL_SPEC","MASTER_DATA","MEDIA_ASSET","GENERAL_DOCUMENT"]),xt=r.z.enum(["hierarchical","conversation","section","fixed_size","table_aware","semantic","none","multimodal"]),Se=r.z.object({metadata_id:r.z.number().int().positive(),chunk_index:r.z.number().int().nonnegative(),text:r.z.string(),score:r.z.number()}),he=r.z.object({metadata_id:r.z.number().int().positive(),relation:r.z.string(),target_name:r.z.string()}),G=r.z.object({query:r.z.string().trim().min(1,"query must not be empty"),tenant_id:pe,domain_key:Ee.optional(),limit:r.z.number().int().positive().optional(),department_id:r.z.number().int().positive().optional(),search_mode:ye.optional(),strategy_id:r.z.number().int().positive().optional()}).strict(),z=r.z.object({hits:r.z.array(Se),graph_hits:r.z.array(he),tiers:r.z.record(r.z.string(),r.z.boolean()),metadata:fe});var K=class extends A{async search(t){let n=G.parse(t),i=await this.request("/ai/search/hybrid",n.tenant_id,n);return z.parse(i)}};var B=["email","pdf","office","image","media","text","google_native","other"],Dt={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"},Ae=[["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 Ot(e){let t=(e.split(";")[0]??"").trim().toLowerCase();for(let[n,i]of Ae)if(n.endsWith("*")?t.startsWith(n.slice(0,-1)):t===n)return i;return"other"}var j=["delete_child_assets","extract_text","analyze_media","extract_assets","ocr_children","ocr_document","resolve_body","enrich_document","project_to_indexes"],Pt=["EXTRACTING","ENRICHING","PROJECTING"],H=e=>({featureFlagKey:e,whenClosed:"skip",failureStatus:null}),ge=(e,t)=>({featureFlagKey:e,whenClosed:"fail",failureStatus:t}),Y={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:[H("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:[H("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:[H("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:[ge("ENABLE_VECTOR_INDEXING","FAILED_VECTOR"),ge("ENABLE_GRAPH_INDEXING","FAILED_GRAPH")],capability:null,fanOut:null}},Ie={whenClosed:"fail",failureStatus:"FAILED_EXTRACT"},O=[{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"}],Re=[{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"}],Ne={email:{kind:"email",steps:O},pdf:{kind:"pdf",steps:O},office:{kind:"office",steps:O},google_native:{kind:"google_native",steps:O},image:{kind:"image",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"ocr_document",dependsOn:["delete_child_assets"],gatePolicy:Ie},{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:Ie},{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:Re},other:{kind:"other",steps:Re}};function Ft(e){return Ne[e]}function Lt(e){let{gates:t}=Y[e.step],{gatePolicy:n}=e;return n===void 0?t:t.map(i=>({featureFlagKey:i.featureFlagKey,whenClosed:n.whenClosed,failureStatus:n.failureStatus}))}function vt(e){let t=new Map(e.steps.map(c=>[c.step,c]));for(let c of e.steps){if(c.gatePolicy!==void 0&&Y[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,s=[];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),s.push(d)}return s}var _e={EXTRACTING:0,ENRICHING:1,PROJECTING:2};function kt(e,t){return _e[e]-_e[t]}var o=require("zod");var Ce=[{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}];var P=require("zod"),C=P.z.string().uuid().transform(e=>e.toLowerCase()),u=P.z.string().datetime({offset:!0}),l=(e,t,n)=>{e.addIssue({code:P.z.ZodIssueCode.custom,path:[...t],message:n})},Mt=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:Z|([+-])(\d{2}):?(\d{2}))$/,Te=e=>{let t=u.safeParse(e).success?Mt.exec(e):null;if(t===null)return null;let[,n,i,s,c,d,m,f,R,y,g]=t,k=new Date(0);k.setUTCFullYear(Number(n),Number(i)-1,Number(s)),k.setUTCHours(Number(c),Number(d),m===void 0?0:Number(m),0);let ct=R===void 0?0:(R==="+"?1:-1)*(Number(y)*3600+Number(g)*60);return{epochSeconds:k.getTime()/1e3-ct,fraction:f===void 0?"":f}},$=(e,t)=>{let n=Te(e),i=Te(t);if(n===null||i===null)return!1;if(n.epochSeconds!==i.epochSeconds)return n.epochSeconds<i.epochSeconds;let s=Math.max(n.fraction.length,i.fraction.length);return n.fraction.padEnd(s,"0")<i.fraction.padEnd(s,"0")};var be={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 Gt=e=>{for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)},T=Gt(be),xe=e=>Object.hasOwn(T,e),De=(e,t)=>{let{min:n,max:i}=T[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`)},zt=(e,t)=>{xe(e)&&De(e,t)},Kt=(e,t)=>{if(!xe(e))throw new TypeError(`The range table bounds no parameter named ${JSON.stringify(e)}.`);De(e,t)};var J=o.z.enum(["QDRANT","NEO4J"]),Pe=o.z.enum(["PRODUCTION","VARIANT","LABEL"]),Q=o.z.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"]),Fe=Q.exclude(["EXPECTED","LIVE","HISTORY"]),Le=o.z.enum(["POINT","NODE","CHUNK","DOCUMENT"]),ve=o.z.enum(["EXPECTED","HEALTHY","RETAINED","INFORMATIONAL","DISCREPANCY"]),ke=o.z.enum(["NONE","PURGE","FLAG","REPROJECT"]),p=(e,t)=>Object.freeze({disposition:e,repairAction:t}),we=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")}),Me=o.z.enum(["SCAN","REPAIR"]),Ue=o.z.enum(["RUNNING","COMPLETED","FAILED","CANCELLED","ABANDONED"]),Ge=o.z.enum(["CONSISTENT","INCONSISTENT","UNDETERMINED"]),ze=o.z.enum(["QDRANT","NEO4J","DOCUMENTS"]),Ke=o.z.enum(["APPLIED","SKIPPED","FAILED"]),He=o.z.enum(["RECLASSIFIED","IN_FLIGHT","DESTINATION_PENDING","BASIS_EXHAUSTED","PROJECTION_REFUSED"]),Be=100,E=o.z.number().int().nonnegative(),F=o.z.number().int().min(300).max(599),V=["repairedCount","repairFailedCount","repairSkippedCount"],je=o.z.string().regex(/^[0-9a-f]{64}$/,"A store fingerprint is 64 lowercase hexadecimal digits."),Oe=T.INTEGRITY_TOMBSTONE_RETENTION_DAYS,Ht=o.z.object({runUid:C,mode:Me,status:Ue,requestedBy:o.z.string().min(1),executor:o.z.string().min(1),basisRunUid:C.nullable(),storeFingerprint:je,tombstoneRetentionDays:o.z.number().int().min(Oe.min).max(Oe.max),startedAt:u,finishedAt:u.nullable(),verdict:Ge.nullable(),errorClass:o.z.string().min(1).nullable(),reprojectDocuments:E.nullable(),reprojectRebuildDocuments:E.nullable()}).strict(),Bt=(e,t)=>{let n=e.status==="COMPLETED";e.mode==="REPAIR"!=(e.basisRunUid!==null)&&l(t,["basisRunUid"],"A REPAIR run names its basis SCAN run, and a SCAN run names none."),n!==(e.verdict!==null)&&l(t,["verdict"],"Only a COMPLETED run has a verdict."),n!==(e.reprojectDocuments!==null)&&l(t,["reprojectDocuments"],"Only a COMPLETED run has the count of documents to re-project.");let{reprojectDocuments:i,reprojectRebuildDocuments:s}=e;i===null||s===null?i!==s&&l(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are counted together with the documents it re-projects."):s>i&&l(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are no more than the documents it re-projects."),e.status==="RUNNING"!=(e.finishedAt===null)&&l(t,["finishedAt"],"Only a RUNNING run has not finished."),e.finishedAt!==null&&$(e.finishedAt,e.startedAt)&&l(t,["finishedAt"],"A run does not finish before it starts."),(e.status==="FAILED"||e.status==="ABANDONED")!=(e.errorClass!==null)&&l(t,["errorClass"],"Only a FAILED or ABANDONED run names an error class.")},L=Ht.superRefine(Bt),jt=o.z.object({store:J,scopeKey:o.z.string().min(1),scopeRole:Pe,itemClass:Q,unit:Le,disposition:ve,repairAction:ke,itemCount:E.nullable(),unmeasuredReason:o.z.string().min(1).nullable(),measuredAt:u.nullable(),repairedCount:E.nullable(),repairFailedCount:E.nullable(),repairSkippedCount:E.nullable()}).strict(),Yt=(e,t)=>{let n=we[e.itemClass];e.disposition!==n.disposition&&l(t,["disposition"],`A ${e.itemClass} quantity is ${n.disposition}.`),e.repairAction!==n.repairAction&&l(t,["repairAction"],`A repair's action on ${e.itemClass} items is ${n.repairAction}.`);let i=e.itemCount===null;i!==(e.unmeasuredReason!==null)&&l(t,["unmeasuredReason"],"An unmeasured quantity (itemCount null) has a reason, and a measured one has none."),i!==(e.measuredAt===null)&&l(t,["measuredAt"],"Only a measured quantity has a measurement time.");let{repairedCount:s,repairFailedCount:c,repairSkippedCount:d}=e;if(s===null||c===null||d===null){if(V.some(m=>e[m]!==null))for(let m of V)e[m]===null&&l(t,[m],"The repaired, failed and skipped counts are recorded together or not at all.");return}e.repairAction==="NONE"&&l(t,["repairAction"],"Only a class with a repair action carries repair counts."),e.itemCount!==null&&s+c+d>e.itemCount&&l(t,["itemCount"],"The repaired, failed and skipped counts together do not exceed the measured count.")},Ye=jt.superRefine(Yt),$t=o.z.object({run:L,phase:ze.nullable(),phaseScope:o.z.string().min(1).nullable(),phaseDone:E.nullable(),phaseTotal:E.nullable(),heartbeatAt:u,isStale:o.z.boolean(),cancelRequestedAt:u.nullable()}).strict(),Vt=(e,t)=>{if(e.run.status!=="RUNNING"&&l(t,["run","status"],"The active run is a RUNNING run."),$(e.heartbeatAt,e.run.startedAt)&&l(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&&l(t,[n],"A run with no phase has no phase progress.");e.phase==="DOCUMENTS"&&e.phaseScope!==null&&l(t,["phaseScope"],"The DOCUMENTS phase scans no scope.")},$e=$t.superRefine(Vt),Xt=o.z.object({run:L,quantities:o.z.array(Ye),previousStoreFingerprint:je.nullable()}).strict(),qt=(e,t)=>{e.run.status!=="COMPLETED"&&l(t,["run","status"],"The last completed run is a COMPLETED run.");let n=new Set;for(let[i,s]of e.quantities.entries()){let c=JSON.stringify([s.store,s.scopeKey,s.itemClass]);if(n.has(c)&&l(t,["quantities",i],"A run records each (store, scope, class) cell once."),n.add(c),e.run.mode==="SCAN")for(let d of V)s[d]!==null&&l(t,["quantities",i,d],"A SCAN run repairs nothing, so its quantities carry no repair counts.")}},Jt=["FAILED","CANCELLED","ABANDONED"],Qt=o.z.object({run:L,repairAppliedItems:E.nullable(),hasNewerRepair:o.z.boolean()}).strict(),Wt=(e,t)=>{Jt.includes(e.run.status)||l(t,["run","status"],"A newer unsuccessful run is FAILED, CANCELLED or ABANDONED."),e.run.mode==="SCAN"&&e.repairAppliedItems!==null&&l(t,["repairAppliedItems"],"A SCAN run applies nothing."),e.run.mode==="REPAIR"&&!e.hasNewerRepair&&l(t,["hasNewerRepair"],"An unsuccessful REPAIR run is itself a repair newer than the last completed run.")},Zt=o.z.object({readAt:u,lastCompleted:Xt.superRefine(qt).nullable(),active:$e.nullable(),newerUnsuccessful:Qt.superRefine(Wt).nullable()}).strict(),en=o.z.object({sequence:o.z.number().int().min(1),itemKey:o.z.string().min(1),metadataId:o.z.number().int().positive().nullable(),fileUri:o.z.string().nullable(),revision:o.z.number().int().nullable(),observed:o.z.record(o.z.string(),o.z.unknown()),repairOutcome:Ke.nullable(),repairErrorClass:o.z.string().min(1).nullable(),repairSkipReason:He.nullable()}).strict(),tn=(e,t)=>{e.repairOutcome==="FAILED"!=(e.repairErrorClass!==null)&&l(t,["repairErrorClass"],"Only a FAILED finding names an error class."),e.repairOutcome==="SKIPPED"!=(e.repairSkipReason!==null)&&l(t,["repairSkipReason"],"Only a SKIPPED finding names a skip reason.")},Ve=en.superRefine(tn),nn=o.z.object({rows:o.z.array(Ve),nextAfter:o.z.number().int().min(1).nullable(),recordedCount:E,totalCount:E.nullable()}).strict(),rn=(e,t)=>{for(let[n,i]of e.rows.entries()){let s=e.rows[n-1];s!==void 0&&i.sequence<=s.sequence&&l(t,["rows",n,"sequence"],"A page lists its rows in ascending sequence.")}e.nextAfter!==null&&e.nextAfter!==e.rows.at(-1)?.sequence&&l(t,["nextAfter"],"The next page starts after the sequence of this page's last row.")},on=nn.superRefine(rn),an=o.z.object({runUid:C,store:J,scopeKey:o.z.string().min(1),itemClass:Fe,after:o.z.number().int().min(1).optional(),limit:o.z.number().int().min(1).max(Be)}).strict(),v=o.z.enum(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),X=o.z.enum(["start","cancel"]),Xe=v.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","FORBIDDEN","UPSTREAM_FAILED"]),qe=v.extract(["RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),q={start:Xe,cancel:qe},sn=o.z.object({code:v.exclude(["UPSTREAM_FAILED"]),status:F,errorCode:o.z.number().int().nullable()}).strict(),W=Object.freeze(o.z.array(sn).parse(Ce).map(e=>Object.freeze(e))),ln=(e,t)=>{e.code==="UPSTREAM_FAILED"||e.code==="FORBIDDEN"&&e.status===null||W.some(n=>n.code===e.code&&n.status===e.status)||l(t,["status"],`A ${e.code} failure carries the status of its row in the code table.`)},cn=o.z.discriminatedUnion("command",[o.z.object({command:X.extract(["start"]),code:q.start,status:F.nullable()}).strict(),o.z.object({command:X.extract(["cancel"]),code:q.cancel,status:F.nullable()}).strict()]).superRefine(ln),pn=(e,t,n)=>{let i=q[e],s=W.find(c=>c.status===t&&(c.errorCode===null||c.errorCode===n)&&i.safeParse(c.code).success);return s===void 0?"UPSTREAM_FAILED":s.code},dn=o.z.discriminatedUnion("ok",[o.z.object({ok:o.z.literal(!0),runUid:C}).strict(),o.z.object({ok:o.z.literal(!1),status:F,errorCode:o.z.number().int().nullable()}).strict()]);var a=require("zod");var ne=a.z.enum(B),b=a.z.enum(j),Je=a.z.enum(["RUNNING","SUCCEEDED","FAILED"]),Qe=a.z.enum(["RUNNING","SUCCEEDED","SKIPPED","FAILED"]),We=a.z.enum(["ingest","retry","resync"]),Ze=a.z.enum(["text_layer","ocr","transcript"]),S=a.z.number().int().nonnegative().nullable(),et=a.z.object({provider:a.z.string().nullable(),model:a.z.string().nullable(),engine:a.z.string().nullable(),prompt_key:a.z.string().nullable(),prompt_version:a.z.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.z.string().nullable(),embedding_model:a.z.string().nullable(),strategy_id:a.z.number().int().positive().nullable(),graph_nodes:S,body_source:Ze.nullable(),detail:a.z.record(a.z.string(),a.z.unknown())}).strict(),tt=["no_pages","no_pages_rendered"],nt=a.z.enum(tt),Z="gate_closed:",ee="source_skipped:",te="nothing_to_read:",rt="no_children",un=/^[A-Z][A-Z0-9_]*$/;function ot(e){if(e===rt)return{kind:"no_children"};if(e.startsWith(Z)){let t=e.slice(Z.length);return un.test(t)?{kind:"gate_closed",featureFlagKey:t}:null}if(e.startsWith(ee)){let t=b.safeParse(e.slice(ee.length));return t.success?{kind:"source_skipped",stepKey:t.data}:null}if(e.startsWith(te)){let t=nt.safeParse(e.slice(te.length));return t.success?{kind:"nothing_to_read",token:t.data}:null}return null}function mn(e){let t=yn(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 yn(e){switch(e.kind){case"gate_closed":return`${Z}${e.featureFlagKey}`;case"no_children":return rt;case"source_skipped":return`${ee}${e.stepKey}`;case"nothing_to_read":return`${te}${e.token}`;default:{let t=e;throw new RangeError(`Unknown skip reason kind: ${JSON.stringify(t)}`)}}}var fn=a.z.object({id:a.z.number().int().positive(),runId:a.z.number().int().positive(),sequence:a.z.number().int().nonnegative(),stepKey:b,targetMetadataId:a.z.number().int().positive(),status:Qe,skipReason:a.z.string().nullable(),provenance:et.nullable(),strategyId:a.z.number().int().positive().nullable(),httpStatus:a.z.number().int().nullable(),errorCode:a.z.string().nullable(),errorMessage:a.z.string().nullable(),startedAt:u,finishedAt:u.nullable(),durationMs:S}).strict();function En(e,t){switch(e.status){case"SKIPPED":e.skipReason===null&&l(t,["skipReason"],"A SKIPPED step must record why it was skipped."),e.provenance!==null&&l(t,["provenance"],"A SKIPPED step read nothing, so it has no report.");return;case"SUCCEEDED":e.provenance===null&&l(t,["provenance"],"A SUCCEEDED step must carry its report."),e.skipReason!==null&&l(t,["skipReason"],"A SUCCEEDED step was not skipped.");return;case"RUNNING":e.finishedAt!==null&&l(t,["finishedAt"],"A RUNNING step has not finished.");return;case"FAILED":e.skipReason!==null&&l(t,["skipReason"],"A FAILED step was not skipped.");return}}var it=fn.superRefine(En),at=a.z.object({id:a.z.number().int().positive(),tenantId:a.z.string().min(1),metadataId:a.z.number().int().positive(),revision:a.z.number().int().positive(),runUid:a.z.string().uuid(),jobId:a.z.string().min(1),attempt:a.z.number().int().positive(),trigger:We,documentKind:ne,flowKey:a.z.string().min(1),status:Je,retryScheduled:a.z.boolean(),failedStepKey:b.nullable(),errorMessage:a.z.string().nullable(),requestedBy:a.z.string().min(1),startedAt:u,finishedAt:u.nullable(),steps:a.z.array(it)}).strict();function st(e,t){e.retryScheduled&&e.status!=="FAILED"&&l(t,["retryScheduled"],"Only a FAILED run can have a retry scheduled.")}var Sn=at.superRefine(st),hn=at.omit({steps:!0}).superRefine(st);function gn(e,t){e.sampleCount>0||(e.durationP50Ms!==null&&l(t,["durationP50Ms"],"A step with no sample has no median latency."),e.durationP95Ms!==null&&l(t,["durationP95Ms"],"A step with no sample has no 95th-percentile latency."))}var In=a.z.object({documentKind:ne,stepKey:b,sampleCount:a.z.number().int().nonnegative(),succeeded:a.z.number().int().nonnegative(),failed:a.z.number().int().nonnegative(),skipped:a.z.number().int().nonnegative(),durationP50Ms:S,durationP95Ms:S,lastStartedAt:u.nullable()}).strict().superRefine(gn);var re=[{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"}],Rn=new Set(re.map(e=>e.key));function _n(e){return Rn.has(e)}function An(e){let t=re.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 Nn={pageSize:{min:1,max:200,default:50},topologyLabels:{min:1,max:24,default:24}};var _=-1,h=0;function lt(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 Cn(){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 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 Tn(e){if(!lt(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)}0&&(module.exports={AmountEntrySchema,BaseEnrichmentClient,BodySourceSchema,BoundingBoxSchema,CIRCUIT_BREAKER_SERVICES,CanonicalDomainKeySchema,ChapterSegmentSchema,ChunkingStrategySchema,CircuitBreakerStatusSchema,ConfidentialityLevelSchema,DISPATCH_DEGRADATION_REASONS,DOCUMENT_KINDS,DOCUMENT_KIND_LABELS,DocumentKindSchema,DocumentStructuredDataSchema,ENRICHMENT_STAGES,EnrichmentClient,EnrichmentClientError,EnrichmentSyncStatusSchema,FILTERABLE_CONFIDENTIALITY_LEVELS,FileUriSchema,GRAPH_INDEX_LIMITS,GraphSearchHitSchema,INTEGRITY_CLASS_POLICY,INTEGRITY_COMMAND_CODES,INTEGRITY_FINDINGS_PAGE_LIMIT_MAX,IntegrityActiveRunSchema,IntegrityAuditOverviewSchema,IntegrityCancelFailureCodeSchema,IntegrityCommandFailureCodeSchema,IntegrityCommandFailureSchema,IntegrityCommandReplySchema,IntegrityCommandSchema,IntegrityDispositionSchema,IntegrityFindingItemClassSchema,IntegrityFindingPageSchema,IntegrityFindingSchema,IntegrityFindingsQuerySchema,IntegrityItemClassSchema,IntegrityPhaseSchema,IntegrityQuantitySchema,IntegrityRepairActionSchema,IntegrityRepairOutcomeSchema,IntegrityRepairSkipReasonSchema,IntegrityRunHeaderSchema,IntegrityRunModeSchema,IntegrityRunStatusSchema,IntegrityScopeRoleSchema,IntegrityStartFailureCodeSchema,IntegrityStoreSchema,IntegrityUnitSchema,IntegrityVerdictSchema,LOCAL_DEGRADATION_REASONS,MIME_KIND_RULES,MODE_TIERS,ModelProviderSchema,NOTHING_TO_READ_TOKENS,NothingToReadTokenSchema,PIPELINE_FLOWS,PIPELINE_PHASES,PIPELINE_STEPS,PIPELINE_STEP_KEYS,PipelineRunRecordSchema,PipelineRunStatusSchema,PipelineRunSummarySchema,PipelineStepKeySchema,PipelineStepMetricSchema,PipelineStepRecordSchema,PipelineStepStatusSchema,PipelineTriggerSchema,QUARANTINED_CONFIDENTIALITY_LEVEL,REMOTE_DEGRADATION_REASONS,SEARCH_DEGRADATION_REASONS,SEARCH_MODES,SEARCH_PARAM_LIMITS,SYSTEM_PARAMETER_RANGES,SearchHitSchema,SearchMetadataSchema,SearchModeSchema,SearchRequestSchema,SearchResponseSchema,StageProvenanceSchema,TenantIdSchema,TranscriptSegmentSchema,assertBoundedSystemParameter,assertSystemParameterInRange,classifyDocumentKind,comparePhases,enrichmentStage,flowFor,flowStepGates,formatSkipReason,generateUuidV7,integrityCommandFailureCodeOf,isEnrichmentStageKey,isValidUuidV7,modeFusesRankings,modeNeedsRemoteTiers,modeScoreIsSimilarity,narrowModeToAllowedTiers,orderedSteps,parseSkipReason,uuidv7ToDate});
|
|
1
|
+
"use strict";var M=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var mt=(e,t)=>{for(var n in t)M(e,n,{get:t[n],enumerable:!0})},yt=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dt(t))!ut.call(e,s)&&s!==n&&M(e,s,{get:()=>t[s],enumerable:!(i=pt(t,s))||i.enumerable});return e};var ft=e=>yt(M({},"__esModule",{value:!0}),e);var xn={};mt(xn,{AmountEntrySchema:()=>me,BaseEnrichmentClient:()=>A,BodySourceSchema:()=>Ze,BoundingBoxSchema:()=>Ct,CIRCUIT_BREAKER_SERVICES:()=>ae,CanonicalDomainKeySchema:()=>Ee,ChapterSegmentSchema:()=>de,ChunkingStrategySchema:()=>bt,CircuitBreakerStatusSchema:()=>xt,ConfidentialityLevelSchema:()=>D,DISPATCH_DEGRADATION_REASONS:()=>ce,DOCUMENT_KINDS:()=>j,DOCUMENT_KIND_LABELS:()=>Dt,DocumentKindSchema:()=>ne,DocumentStructuredDataSchema:()=>Tt,ENRICHMENT_STAGES:()=>re,EnrichmentClient:()=>H,EnrichmentClientError:()=>I,EnrichmentSyncStatusSchema:()=>Nt,FILTERABLE_CONFIDENTIALITY_LEVELS:()=>St,FileUriSchema:()=>At,GRAPH_INDEX_LIMITS:()=>Nn,GraphSearchHitSchema:()=>he,INTEGRITY_CLASS_POLICY:()=>we,INTEGRITY_COMMAND_CODES:()=>W,INTEGRITY_FINDINGS_PAGE_LIMIT_MAX:()=>Be,IntegrityActiveRunSchema:()=>$e,IntegrityAuditOverviewSchema:()=>Zt,IntegrityCancelFailureCodeSchema:()=>qe,IntegrityCommandFailureCodeSchema:()=>k,IntegrityCommandFailureSchema:()=>cn,IntegrityCommandReplySchema:()=>dn,IntegrityCommandSchema:()=>X,IntegrityDispositionSchema:()=>ve,IntegrityFindingItemClassSchema:()=>Fe,IntegrityFindingPageSchema:()=>on,IntegrityFindingSchema:()=>Ve,IntegrityFindingsQuerySchema:()=>an,IntegrityItemClassSchema:()=>Q,IntegrityPhaseSchema:()=>ze,IntegrityQuantitySchema:()=>Ye,IntegrityRepairActionSchema:()=>ke,IntegrityRepairOutcomeSchema:()=>Ke,IntegrityRepairSkipReasonSchema:()=>He,IntegrityRunHeaderSchema:()=>v,IntegrityRunModeSchema:()=>Me,IntegrityRunStatusSchema:()=>Ue,IntegrityScopeRoleSchema:()=>Pe,IntegrityStartFailureCodeSchema:()=>Xe,IntegrityStoreSchema:()=>J,IntegrityUnitSchema:()=>Le,IntegrityVerdictSchema:()=>Ge,LOCAL_DEGRADATION_REASONS:()=>se,MIME_KIND_RULES:()=>Ae,MODE_TIERS:()=>N,ModelProviderSchema:()=>oe,NOTHING_TO_READ_TOKENS:()=>tt,NothingToReadTokenSchema:()=>nt,PIPELINE_FLOWS:()=>Ne,PIPELINE_PHASES:()=>Pt,PIPELINE_STEPS:()=>$,PIPELINE_STEP_KEYS:()=>Y,PipelineRunRecordSchema:()=>Sn,PipelineRunStatusSchema:()=>Je,PipelineRunSummarySchema:()=>hn,PipelineStepKeySchema:()=>b,PipelineStepMetricSchema:()=>In,PipelineStepRecordSchema:()=>it,PipelineStepStatusSchema:()=>Qe,PipelineTriggerSchema:()=>We,QUARANTINED_CONFIDENTIALITY_LEVEL:()=>O,REMOTE_DEGRADATION_REASONS:()=>le,SEARCH_DEGRADATION_REASONS:()=>_t,SEARCH_MODES:()=>G,SEARCH_PARAM_LIMITS:()=>Et,SYSTEM_PARAMETER_RANGES:()=>x,SearchHitSchema:()=>Se,SearchMetadataSchema:()=>fe,SearchModeSchema:()=>ye,SearchRequestSchema:()=>z,SearchResponseSchema:()=>K,StageProvenanceSchema:()=>et,TenantIdSchema:()=>pe,TranscriptSegmentSchema:()=>ue,assertBoundedSystemParameter:()=>Kt,assertSystemParameterInRange:()=>zt,classifyDocumentKind:()=>Ot,comparePhases:()=>kt,enrichmentStage:()=>An,flowFor:()=>Ft,flowStepGates:()=>Lt,formatSkipReason:()=>mn,generateUuidV7:()=>Cn,integrityCommandFailureCodeOf:()=>pn,isEnrichmentStageKey:()=>_n,isStrictlyEarlier:()=>T,isValidUuidV7:()=>lt,modeFusesRankings:()=>Rt,modeNeedsRemoteTiers:()=>ht,modeScoreIsSimilarity:()=>gt,narrowModeToAllowedTiers:()=>It,orderedSteps:()=>vt,parseSkipReason:()=>ot,uuidv7ToDate:()=>Tn});module.exports=ft(xn);var I=class extends Error{statusCode;responseBody;parsedBody;constructor(t,n,i,s){super(t),this.name="EnrichmentClientError",this.statusCode=n,this.responseBody=i,this.parsedBody=s}},A=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 s=`${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(s,{method:"POST",headers:c,body:JSON.stringify(i),signal:d.signal})}catch(y){let g=y instanceof Error?y.message:String(y);throw new I(`Network request failed for POST ${s}: ${g}`,0,"")}finally{clearTimeout(m)}if(!f.ok){let y=await f.text().catch(()=>""),g;try{g=JSON.parse(y)}catch{}throw new I(`API request failed with status ${f.status}: ${y}`,f.status,y,g)}let R=await f.text().catch(()=>"");if(R.trim().length!==0)try{return JSON.parse(R)}catch(y){let g=y instanceof Error?y.message:String(y);throw new I(`Failed to parse response JSON from ${s}: ${g}`,f.status,R)}}};var r=require("zod");var U=require("zod"),oe=U.z.enum(["google_cloud","google_vision","yomitoku_local","faster_whisper_local","google_speech","ollama_local","openai","anthropic","azure_openai","bedrock","custom_openai_compatible"]),D=U.z.enum(["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"]),O="RESTRICTED";var Et={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}},ie=D.options.filter(e=>e!==O);if(ie.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 St=ie,G=["KEYWORD","SPARSE","DENSE","HYBRID","GRAPH_TRAVERSE"],N={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=N[e];return t.dense||t.sparse||t.graph}function gt(e){let t=N[e];return t.dense&&!t.sparse}function It(e,t){let n=N[e],i=(n.dense||n.sparse)&&t.vector,s=n.graph&&t.graph;return i||s?i?s?{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 Rt(e){let t=N[e];return[t.dense,t.sparse,t.graph,t.lexical].filter(Boolean).length>1}var ae=["vector","graph"],se=["empty_query","caller_token_unavailable","time_window_unsupported"],le=["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"],_t=[...se,...le,...ce,...ae.map(e=>`circuit_breaker_open:${e}`)];var pe=r.z.string().trim().min(1,"tenant_id must be a non-empty string"),At=r.z.string().trim().min(1,"file_uri must be a non-empty string"),Nt=r.z.enum(["PENDING","EXTRACTING","ENRICHING","PROJECTING","SYNCED","FAILED_EXTRACT","FAILED_ENRICH","FAILED_VECTOR","FAILED_GRAPH"]),Ct=r.z.object({page:r.z.number().int().positive().optional(),x:r.z.number().nonnegative().optional(),y:r.z.number().nonnegative().optional(),width:r.z.number().positive().optional(),height:r.z.number().positive().optional(),start_sec:r.z.number().nonnegative().optional(),end_sec:r.z.number().nonnegative().optional(),frame_index:r.z.number().int().nonnegative().optional(),timestamp_sec:r.z.number().nonnegative().optional(),scene_confidence:r.z.number().min(0).max(1).optional()}),de=r.z.object({title:r.z.string().trim().min(1),start_sec:r.z.number().nonnegative(),end_sec:r.z.number().nonnegative(),summary:r.z.string()}),ue=r.z.object({start_sec:r.z.number().nonnegative(),end_sec:r.z.number().nonnegative(),speaker:r.z.string().trim().min(1),text:r.z.string()}),me=r.z.object({label:r.z.string(),value:r.z.number(),currency:r.z.string()}),Tt=r.z.object({document_type:r.z.string().optional(),title:r.z.string().optional(),organization:r.z.string().optional(),key_entities:r.z.array(r.z.string()).optional(),dates:r.z.array(r.z.string()).optional(),amounts:r.z.array(me).optional(),media_type:r.z.enum(["video","audio"]).optional(),duration_sec:r.z.number().nonnegative().optional(),chapters:r.z.array(de).optional(),transcript_segments:r.z.array(ue).optional()}),xt=r.z.enum(["CLOSED","OPEN","HALF_OPEN"]),ye=r.z.enum(G),fe=r.z.object({circuit_breaker_status:r.z.string(),quality_tier:r.z.string(),latency_ms:r.z.number().nonnegative(),total_hits:r.z.number().int().nonnegative(),fallback_applied:r.z.boolean(),degraded_reason:r.z.string().nullable()}),Ee=r.z.enum(["CONTRACT_LEGAL","EMAIL_THREAD","DAILY_REPORT","FINANCIAL_REPORT","TECHNICAL_SPEC","MASTER_DATA","MEDIA_ASSET","GENERAL_DOCUMENT"]),bt=r.z.enum(["hierarchical","conversation","section","fixed_size","table_aware","semantic","none","multimodal"]),Se=r.z.object({metadata_id:r.z.number().int().positive(),chunk_index:r.z.number().int().nonnegative(),text:r.z.string(),score:r.z.number()}),he=r.z.object({metadata_id:r.z.number().int().positive(),relation:r.z.string(),target_name:r.z.string()}),z=r.z.object({query:r.z.string().trim().min(1,"query must not be empty"),tenant_id:pe,domain_key:Ee.optional(),limit:r.z.number().int().positive().optional(),department_id:r.z.number().int().positive().optional(),search_mode:ye.optional(),strategy_id:r.z.number().int().positive().optional()}).strict(),K=r.z.object({hits:r.z.array(Se),graph_hits:r.z.array(he),tiers:r.z.record(r.z.string(),r.z.boolean()),metadata:fe});var H=class extends A{async search(t){let n=z.parse(t),i=await this.request("/ai/search/hybrid",n.tenant_id,n);return K.parse(i)}};var j=["email","pdf","office","image","media","text","google_native","other"],Dt={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"},Ae=[["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 Ot(e){let t=(e.split(";")[0]??"").trim().toLowerCase();for(let[n,i]of Ae)if(n.endsWith("*")?t.startsWith(n.slice(0,-1)):t===n)return i;return"other"}var Y=["delete_child_assets","extract_text","analyze_media","extract_assets","ocr_children","ocr_document","resolve_body","enrich_document","project_to_indexes"],Pt=["EXTRACTING","ENRICHING","PROJECTING"],B=e=>({featureFlagKey:e,whenClosed:"skip",failureStatus:null}),ge=(e,t)=>({featureFlagKey:e,whenClosed:"fail",failureStatus:t}),$={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:[B("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:[B("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:[B("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:[ge("ENABLE_VECTOR_INDEXING","FAILED_VECTOR"),ge("ENABLE_GRAPH_INDEXING","FAILED_GRAPH")],capability:null,fanOut:null}},Ie={whenClosed:"fail",failureStatus:"FAILED_EXTRACT"},P=[{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"}],Re=[{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"}],Ne={email:{kind:"email",steps:P},pdf:{kind:"pdf",steps:P},office:{kind:"office",steps:P},google_native:{kind:"google_native",steps:P},image:{kind:"image",steps:[{step:"delete_child_assets",dependsOn:[]},{step:"ocr_document",dependsOn:["delete_child_assets"],gatePolicy:Ie},{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:Ie},{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:Re},other:{kind:"other",steps:Re}};function Ft(e){return Ne[e]}function Lt(e){let{gates:t}=$[e.step],{gatePolicy:n}=e;return n===void 0?t:t.map(i=>({featureFlagKey:i.featureFlagKey,whenClosed:n.whenClosed,failureStatus:n.failureStatus}))}function vt(e){let t=new Map(e.steps.map(c=>[c.step,c]));for(let c of e.steps){if(c.gatePolicy!==void 0&&$[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,s=[];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),s.push(d)}return s}var _e={EXTRACTING:0,ENRICHING:1,PROJECTING:2};function kt(e,t){return _e[e]-_e[t]}var o=require("zod");var Ce=[{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}];var F=require("zod"),C=F.z.string().uuid().transform(e=>e.toLowerCase()),u=F.z.string().datetime({offset:!0}),l=(e,t,n)=>{e.addIssue({code:F.z.ZodIssueCode.custom,path:[...t],message:n})},Mt=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(?:Z|([+-])(\d{2}):?(\d{2}))$/,Te=e=>{let t=u.safeParse(e).success?Mt.exec(e):null;if(t===null)return null;let[,n,i,s,c,d,m,f,R,y,g]=t,w=new Date(0);w.setUTCFullYear(Number(n),Number(i)-1,Number(s)),w.setUTCHours(Number(c),Number(d),m===void 0?0:Number(m),0);let ct=R===void 0?0:(R==="+"?1:-1)*(Number(y)*3600+Number(g)*60);return{epochSeconds:w.getTime()/1e3-ct,fraction:f===void 0?"":f}},T=(e,t)=>{let n=Te(e),i=Te(t);if(n===null||i===null)return!1;if(n.epochSeconds!==i.epochSeconds)return n.epochSeconds<i.epochSeconds;let s=Math.max(n.fraction.length,i.fraction.length);return n.fraction.padEnd(s,"0")<i.fraction.padEnd(s,"0")};var xe={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 Gt=e=>{for(let t of Object.values(e))Object.freeze(t);return Object.freeze(e)},x=Gt(xe),be=e=>Object.hasOwn(x,e),De=(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`)},zt=(e,t)=>{be(e)&&De(e,t)},Kt=(e,t)=>{if(!be(e))throw new TypeError(`The range table bounds no parameter named ${JSON.stringify(e)}.`);De(e,t)};var J=o.z.enum(["QDRANT","NEO4J"]),Pe=o.z.enum(["PRODUCTION","VARIANT","LABEL"]),Q=o.z.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"]),Fe=Q.exclude(["EXPECTED","LIVE","HISTORY"]),Le=o.z.enum(["POINT","NODE","CHUNK","DOCUMENT"]),ve=o.z.enum(["EXPECTED","HEALTHY","RETAINED","INFORMATIONAL","DISCREPANCY"]),ke=o.z.enum(["NONE","PURGE","FLAG","REPROJECT"]),p=(e,t)=>Object.freeze({disposition:e,repairAction:t}),we=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")}),Me=o.z.enum(["SCAN","REPAIR"]),Ue=o.z.enum(["RUNNING","COMPLETED","FAILED","CANCELLED","ABANDONED"]),Ge=o.z.enum(["CONSISTENT","INCONSISTENT","UNDETERMINED"]),ze=o.z.enum(["QDRANT","NEO4J","DOCUMENTS"]),Ke=o.z.enum(["APPLIED","SKIPPED","FAILED"]),He=o.z.enum(["RECLASSIFIED","IN_FLIGHT","DESTINATION_PENDING","BASIS_EXHAUSTED","PROJECTION_REFUSED"]),Be=100,E=o.z.number().int().nonnegative(),L=o.z.number().int().min(300).max(599),V=["repairedCount","repairFailedCount","repairSkippedCount"],je=o.z.string().regex(/^[0-9a-f]{64}$/,"A store fingerprint is 64 lowercase hexadecimal digits."),Oe=x.INTEGRITY_TOMBSTONE_RETENTION_DAYS,Ht=o.z.object({runUid:C,mode:Me,status:Ue,requestedBy:o.z.string().min(1),executor:o.z.string().min(1),basisRunUid:C.nullable(),storeFingerprint:je,tombstoneRetentionDays:o.z.number().int().min(Oe.min).max(Oe.max),startedAt:u,finishedAt:u.nullable(),verdict:Ge.nullable(),errorClass:o.z.string().min(1).nullable(),reprojectDocuments:E.nullable(),reprojectRebuildDocuments:E.nullable()}).strict(),Bt=(e,t)=>{let n=e.status==="COMPLETED";e.mode==="REPAIR"!=(e.basisRunUid!==null)&&l(t,["basisRunUid"],"A REPAIR run names its basis SCAN run, and a SCAN run names none."),n!==(e.verdict!==null)&&l(t,["verdict"],"Only a COMPLETED run has a verdict."),n!==(e.reprojectDocuments!==null)&&l(t,["reprojectDocuments"],"Only a COMPLETED run has the count of documents to re-project.");let{reprojectDocuments:i,reprojectRebuildDocuments:s}=e;i===null||s===null?i!==s&&l(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are counted together with the documents it re-projects."):s>i&&l(t,["reprojectRebuildDocuments"],"The documents a re-projection embeds are no more than the documents it re-projects."),e.status==="RUNNING"!=(e.finishedAt===null)&&l(t,["finishedAt"],"Only a RUNNING run has not finished."),e.finishedAt!==null&&T(e.finishedAt,e.startedAt)&&l(t,["finishedAt"],"A run does not finish before it starts."),(e.status==="FAILED"||e.status==="ABANDONED")!=(e.errorClass!==null)&&l(t,["errorClass"],"Only a FAILED or ABANDONED run names an error class.")},v=Ht.superRefine(Bt),jt=o.z.object({store:J,scopeKey:o.z.string().min(1),scopeRole:Pe,itemClass:Q,unit:Le,disposition:ve,repairAction:ke,itemCount:E.nullable(),unmeasuredReason:o.z.string().min(1).nullable(),measuredAt:u.nullable(),repairedCount:E.nullable(),repairFailedCount:E.nullable(),repairSkippedCount:E.nullable()}).strict(),Yt=(e,t)=>{let n=we[e.itemClass];e.disposition!==n.disposition&&l(t,["disposition"],`A ${e.itemClass} quantity is ${n.disposition}.`),e.repairAction!==n.repairAction&&l(t,["repairAction"],`A repair's action on ${e.itemClass} items is ${n.repairAction}.`);let i=e.itemCount===null;i!==(e.unmeasuredReason!==null)&&l(t,["unmeasuredReason"],"An unmeasured quantity (itemCount null) has a reason, and a measured one has none."),i!==(e.measuredAt===null)&&l(t,["measuredAt"],"Only a measured quantity has a measurement time.");let{repairedCount:s,repairFailedCount:c,repairSkippedCount:d}=e;if(s===null||c===null||d===null){if(V.some(m=>e[m]!==null))for(let m of V)e[m]===null&&l(t,[m],"The repaired, failed and skipped counts are recorded together or not at all.");return}e.repairAction==="NONE"&&l(t,["repairAction"],"Only a class with a repair action carries repair counts."),e.itemCount!==null&&s+c+d>e.itemCount&&l(t,["itemCount"],"The repaired, failed and skipped counts together do not exceed the measured count.")},Ye=jt.superRefine(Yt),$t=o.z.object({run:v,phase:ze.nullable(),phaseScope:o.z.string().min(1).nullable(),phaseDone:E.nullable(),phaseTotal:E.nullable(),heartbeatAt:u,isStale:o.z.boolean(),cancelRequestedAt:u.nullable()}).strict(),Vt=(e,t)=>{if(e.run.status!=="RUNNING"&&l(t,["run","status"],"The active run is a RUNNING run."),T(e.heartbeatAt,e.run.startedAt)&&l(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&&l(t,[n],"A run with no phase has no phase progress.");e.phase==="DOCUMENTS"&&e.phaseScope!==null&&l(t,["phaseScope"],"The DOCUMENTS phase scans no scope.")},$e=$t.superRefine(Vt),Xt=o.z.object({run:v,quantities:o.z.array(Ye),previousStoreFingerprint:je.nullable()}).strict(),qt=(e,t)=>{e.run.status!=="COMPLETED"&&l(t,["run","status"],"The last completed run is a COMPLETED run.");let n=new Set;for(let[i,s]of e.quantities.entries()){let c=JSON.stringify([s.store,s.scopeKey,s.itemClass]);if(n.has(c)&&l(t,["quantities",i],"A run records each (store, scope, class) cell once."),n.add(c),e.run.mode==="SCAN")for(let d of V)s[d]!==null&&l(t,["quantities",i,d],"A SCAN run repairs nothing, so its quantities carry no repair counts.")}},Jt=["FAILED","CANCELLED","ABANDONED"],Qt=o.z.object({run:v,repairAppliedItems:E.nullable(),hasNewerRepair:o.z.boolean()}).strict(),Wt=(e,t)=>{Jt.includes(e.run.status)||l(t,["run","status"],"A newer unsuccessful run is FAILED, CANCELLED or ABANDONED."),e.run.mode==="SCAN"&&e.repairAppliedItems!==null&&l(t,["repairAppliedItems"],"A SCAN run applies nothing."),e.run.mode==="REPAIR"&&!e.hasNewerRepair&&l(t,["hasNewerRepair"],"An unsuccessful REPAIR run is itself a repair newer than the last completed run.")},Zt=o.z.object({readAt:u,lastCompleted:Xt.superRefine(qt).nullable(),active:$e.nullable(),newerUnsuccessful:Qt.superRefine(Wt).nullable()}).strict(),en=o.z.object({sequence:o.z.number().int().min(1),itemKey:o.z.string().min(1),metadataId:o.z.number().int().positive().nullable(),fileUri:o.z.string().nullable(),revision:o.z.number().int().nullable(),observed:o.z.record(o.z.string(),o.z.unknown()),repairOutcome:Ke.nullable(),repairErrorClass:o.z.string().min(1).nullable(),repairSkipReason:He.nullable()}).strict(),tn=(e,t)=>{e.repairOutcome==="FAILED"!=(e.repairErrorClass!==null)&&l(t,["repairErrorClass"],"Only a FAILED finding names an error class."),e.repairOutcome==="SKIPPED"!=(e.repairSkipReason!==null)&&l(t,["repairSkipReason"],"Only a SKIPPED finding names a skip reason.")},Ve=en.superRefine(tn),nn=o.z.object({rows:o.z.array(Ve),nextAfter:o.z.number().int().min(1).nullable(),recordedCount:E,totalCount:E.nullable()}).strict(),rn=(e,t)=>{for(let[n,i]of e.rows.entries()){let s=e.rows[n-1];s!==void 0&&i.sequence<=s.sequence&&l(t,["rows",n,"sequence"],"A page lists its rows in ascending sequence.")}e.nextAfter!==null&&e.nextAfter!==e.rows.at(-1)?.sequence&&l(t,["nextAfter"],"The next page starts after the sequence of this page's last row.")},on=nn.superRefine(rn),an=o.z.object({runUid:C,store:J,scopeKey:o.z.string().min(1),itemClass:Fe,after:o.z.number().int().min(1).optional(),limit:o.z.number().int().min(1).max(Be)}).strict(),k=o.z.enum(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),X=o.z.enum(["start","cancel"]),Xe=k.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_ACTIVE","BASIS_INVALID","FORBIDDEN","UPSTREAM_FAILED"]),qe=k.extract(["DEPLOYMENT_DISABLED","RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),q={start:Xe,cancel:qe},sn=o.z.object({code:k.exclude(["UPSTREAM_FAILED"]),status:L,errorCode:o.z.number().int().nullable()}).strict(),W=Object.freeze(o.z.array(sn).parse(Ce).map(e=>Object.freeze(e))),ln=(e,t)=>{e.code==="UPSTREAM_FAILED"||e.code==="FORBIDDEN"&&e.status===null||W.some(n=>n.code===e.code&&n.status===e.status)||l(t,["status"],`A ${e.code} failure carries the status of its row in the code table.`)},cn=o.z.discriminatedUnion("command",[o.z.object({command:X.extract(["start"]),code:q.start,status:L.nullable()}).strict(),o.z.object({command:X.extract(["cancel"]),code:q.cancel,status:L.nullable()}).strict()]).superRefine(ln),pn=(e,t,n)=>{let i=q[e],s=W.find(c=>c.status===t&&(c.errorCode===null||c.errorCode===n)&&i.safeParse(c.code).success);return s===void 0?"UPSTREAM_FAILED":s.code},dn=o.z.discriminatedUnion("ok",[o.z.object({ok:o.z.literal(!0),runUid:C}).strict(),o.z.object({ok:o.z.literal(!1),status:L,errorCode:o.z.number().int().nullable()}).strict()]);var a=require("zod");var ne=a.z.enum(j),b=a.z.enum(Y),Je=a.z.enum(["RUNNING","SUCCEEDED","FAILED"]),Qe=a.z.enum(["RUNNING","SUCCEEDED","SKIPPED","FAILED"]),We=a.z.enum(["ingest","retry","resync"]),Ze=a.z.enum(["text_layer","ocr","transcript"]),S=a.z.number().int().nonnegative().nullable(),et=a.z.object({provider:a.z.string().nullable(),model:a.z.string().nullable(),engine:a.z.string().nullable(),prompt_key:a.z.string().nullable(),prompt_version:a.z.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.z.string().nullable(),embedding_model:a.z.string().nullable(),strategy_id:a.z.number().int().positive().nullable(),graph_nodes:S,body_source:Ze.nullable(),detail:a.z.record(a.z.string(),a.z.unknown())}).strict(),tt=["no_pages","no_pages_rendered"],nt=a.z.enum(tt),Z="gate_closed:",ee="source_skipped:",te="nothing_to_read:",rt="no_children",un=/^[A-Z][A-Z0-9_]*$/;function ot(e){if(e===rt)return{kind:"no_children"};if(e.startsWith(Z)){let t=e.slice(Z.length);return un.test(t)?{kind:"gate_closed",featureFlagKey:t}:null}if(e.startsWith(ee)){let t=b.safeParse(e.slice(ee.length));return t.success?{kind:"source_skipped",stepKey:t.data}:null}if(e.startsWith(te)){let t=nt.safeParse(e.slice(te.length));return t.success?{kind:"nothing_to_read",token:t.data}:null}return null}function mn(e){let t=yn(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 yn(e){switch(e.kind){case"gate_closed":return`${Z}${e.featureFlagKey}`;case"no_children":return rt;case"source_skipped":return`${ee}${e.stepKey}`;case"nothing_to_read":return`${te}${e.token}`;default:{let t=e;throw new RangeError(`Unknown skip reason kind: ${JSON.stringify(t)}`)}}}var fn=a.z.object({id:a.z.number().int().positive(),runId:a.z.number().int().positive(),sequence:a.z.number().int().nonnegative(),stepKey:b,targetMetadataId:a.z.number().int().positive(),status:Qe,skipReason:a.z.string().nullable(),provenance:et.nullable(),strategyId:a.z.number().int().positive().nullable(),httpStatus:a.z.number().int().nullable(),errorCode:a.z.string().nullable(),errorMessage:a.z.string().nullable(),startedAt:u,finishedAt:u.nullable(),durationMs:S}).strict();function En(e,t){switch(e.status){case"SKIPPED":e.skipReason===null&&l(t,["skipReason"],"A SKIPPED step must record why it was skipped."),e.provenance!==null&&l(t,["provenance"],"A SKIPPED step read nothing, so it has no report.");return;case"SUCCEEDED":e.provenance===null&&l(t,["provenance"],"A SUCCEEDED step must carry its report."),e.skipReason!==null&&l(t,["skipReason"],"A SUCCEEDED step was not skipped.");return;case"RUNNING":e.finishedAt!==null&&l(t,["finishedAt"],"A RUNNING step has not finished.");return;case"FAILED":e.skipReason!==null&&l(t,["skipReason"],"A FAILED step was not skipped.");return}}var it=fn.superRefine(En),at=a.z.object({id:a.z.number().int().positive(),tenantId:a.z.string().min(1),metadataId:a.z.number().int().positive(),revision:a.z.number().int().positive(),runUid:a.z.string().uuid(),jobId:a.z.string().min(1),attempt:a.z.number().int().positive(),trigger:We,documentKind:ne,flowKey:a.z.string().min(1),status:Je,retryScheduled:a.z.boolean(),failedStepKey:b.nullable(),errorMessage:a.z.string().nullable(),requestedBy:a.z.string().min(1),startedAt:u,finishedAt:u.nullable(),steps:a.z.array(it)}).strict();function st(e,t){e.retryScheduled&&e.status!=="FAILED"&&l(t,["retryScheduled"],"Only a FAILED run can have a retry scheduled.")}var Sn=at.superRefine(st),hn=at.omit({steps:!0}).superRefine(st);function gn(e,t){e.sampleCount>0||(e.durationP50Ms!==null&&l(t,["durationP50Ms"],"A step with no sample has no median latency."),e.durationP95Ms!==null&&l(t,["durationP95Ms"],"A step with no sample has no 95th-percentile latency."))}var In=a.z.object({documentKind:ne,stepKey:b,sampleCount:a.z.number().int().nonnegative(),succeeded:a.z.number().int().nonnegative(),failed:a.z.number().int().nonnegative(),skipped:a.z.number().int().nonnegative(),durationP50Ms:S,durationP95Ms:S,lastStartedAt:u.nullable()}).strict().superRefine(gn);var re=[{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"}],Rn=new Set(re.map(e=>e.key));function _n(e){return Rn.has(e)}function An(e){let t=re.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 Nn={pageSize:{min:1,max:200,default:50},topologyLabels:{min:1,max:24,default:24}};var _=-1,h=0;function lt(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 Cn(){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 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 Tn(e){if(!lt(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)}0&&(module.exports={AmountEntrySchema,BaseEnrichmentClient,BodySourceSchema,BoundingBoxSchema,CIRCUIT_BREAKER_SERVICES,CanonicalDomainKeySchema,ChapterSegmentSchema,ChunkingStrategySchema,CircuitBreakerStatusSchema,ConfidentialityLevelSchema,DISPATCH_DEGRADATION_REASONS,DOCUMENT_KINDS,DOCUMENT_KIND_LABELS,DocumentKindSchema,DocumentStructuredDataSchema,ENRICHMENT_STAGES,EnrichmentClient,EnrichmentClientError,EnrichmentSyncStatusSchema,FILTERABLE_CONFIDENTIALITY_LEVELS,FileUriSchema,GRAPH_INDEX_LIMITS,GraphSearchHitSchema,INTEGRITY_CLASS_POLICY,INTEGRITY_COMMAND_CODES,INTEGRITY_FINDINGS_PAGE_LIMIT_MAX,IntegrityActiveRunSchema,IntegrityAuditOverviewSchema,IntegrityCancelFailureCodeSchema,IntegrityCommandFailureCodeSchema,IntegrityCommandFailureSchema,IntegrityCommandReplySchema,IntegrityCommandSchema,IntegrityDispositionSchema,IntegrityFindingItemClassSchema,IntegrityFindingPageSchema,IntegrityFindingSchema,IntegrityFindingsQuerySchema,IntegrityItemClassSchema,IntegrityPhaseSchema,IntegrityQuantitySchema,IntegrityRepairActionSchema,IntegrityRepairOutcomeSchema,IntegrityRepairSkipReasonSchema,IntegrityRunHeaderSchema,IntegrityRunModeSchema,IntegrityRunStatusSchema,IntegrityScopeRoleSchema,IntegrityStartFailureCodeSchema,IntegrityStoreSchema,IntegrityUnitSchema,IntegrityVerdictSchema,LOCAL_DEGRADATION_REASONS,MIME_KIND_RULES,MODE_TIERS,ModelProviderSchema,NOTHING_TO_READ_TOKENS,NothingToReadTokenSchema,PIPELINE_FLOWS,PIPELINE_PHASES,PIPELINE_STEPS,PIPELINE_STEP_KEYS,PipelineRunRecordSchema,PipelineRunStatusSchema,PipelineRunSummarySchema,PipelineStepKeySchema,PipelineStepMetricSchema,PipelineStepRecordSchema,PipelineStepStatusSchema,PipelineTriggerSchema,QUARANTINED_CONFIDENTIALITY_LEVEL,REMOTE_DEGRADATION_REASONS,SEARCH_DEGRADATION_REASONS,SEARCH_MODES,SEARCH_PARAM_LIMITS,SYSTEM_PARAMETER_RANGES,SearchHitSchema,SearchMetadataSchema,SearchModeSchema,SearchRequestSchema,SearchResponseSchema,StageProvenanceSchema,TenantIdSchema,TranscriptSegmentSchema,assertBoundedSystemParameter,assertSystemParameterInRange,classifyDocumentKind,comparePhases,enrichmentStage,flowFor,flowStepGates,formatSkipReason,generateUuidV7,integrityCommandFailureCodeOf,isEnrichmentStageKey,isStrictlyEarlier,isValidUuidV7,modeFusesRankings,modeNeedsRemoteTiers,modeScoreIsSimilarity,narrowModeToAllowedTiers,orderedSteps,parseSkipReason,uuidv7ToDate});
|
package/dist/index.d.cts
CHANGED
|
@@ -553,6 +553,7 @@ declare function flowFor(kind: DocumentKind): PipelineFlow;
|
|
|
553
553
|
declare function flowStepGates(flowStep: FlowStep): readonly StepGate[];
|
|
554
554
|
declare function orderedSteps(flow: PipelineFlow): readonly FlowStep[];
|
|
555
555
|
declare function comparePhases(a: PipelinePhase, b: PipelinePhase): number;
|
|
556
|
+
declare const isStrictlyEarlier: (earlier: string, later: string) => boolean;
|
|
556
557
|
declare const IntegrityStoreSchema: z.ZodEnum<[
|
|
557
558
|
"QDRANT",
|
|
558
559
|
"NEO4J"
|
|
@@ -2222,6 +2223,7 @@ declare const IntegrityStartFailureCodeSchema: z.ZodEnum<[
|
|
|
2222
2223
|
]>;
|
|
2223
2224
|
type IntegrityStartFailureCode = z.infer<typeof IntegrityStartFailureCodeSchema>;
|
|
2224
2225
|
declare const IntegrityCancelFailureCodeSchema: z.ZodEnum<[
|
|
2226
|
+
"DEPLOYMENT_DISABLED",
|
|
2225
2227
|
"RUN_ALREADY_FINISHED",
|
|
2226
2228
|
"FORBIDDEN",
|
|
2227
2229
|
"UPSTREAM_FAILED"
|
|
@@ -2236,6 +2238,7 @@ declare const FAILURE_CODES_OF_COMMAND: {
|
|
|
2236
2238
|
"UPSTREAM_FAILED"
|
|
2237
2239
|
]>;
|
|
2238
2240
|
readonly cancel: z.ZodEnum<[
|
|
2241
|
+
"DEPLOYMENT_DISABLED",
|
|
2239
2242
|
"RUN_ALREADY_FINISHED",
|
|
2240
2243
|
"FORBIDDEN",
|
|
2241
2244
|
"UPSTREAM_FAILED"
|
|
@@ -2290,17 +2293,18 @@ declare const IntegrityCommandFailureSchema: z.ZodEffects<z.ZodDiscriminatedUnio
|
|
|
2290
2293
|
"cancel"
|
|
2291
2294
|
]>;
|
|
2292
2295
|
code: z.ZodEnum<[
|
|
2296
|
+
"DEPLOYMENT_DISABLED",
|
|
2293
2297
|
"RUN_ALREADY_FINISHED",
|
|
2294
2298
|
"FORBIDDEN",
|
|
2295
2299
|
"UPSTREAM_FAILED"
|
|
2296
2300
|
]>;
|
|
2297
2301
|
status: z.ZodNullable<z.ZodNumber>;
|
|
2298
2302
|
}, "strict", z.ZodTypeAny, {
|
|
2299
|
-
code: "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2303
|
+
code: "DEPLOYMENT_DISABLED" | "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2300
2304
|
status: number | null;
|
|
2301
2305
|
command: "cancel";
|
|
2302
2306
|
}, {
|
|
2303
|
-
code: "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2307
|
+
code: "DEPLOYMENT_DISABLED" | "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2304
2308
|
status: number | null;
|
|
2305
2309
|
command: "cancel";
|
|
2306
2310
|
}>
|
|
@@ -2309,7 +2313,7 @@ declare const IntegrityCommandFailureSchema: z.ZodEffects<z.ZodDiscriminatedUnio
|
|
|
2309
2313
|
status: number | null;
|
|
2310
2314
|
command: "start";
|
|
2311
2315
|
} | {
|
|
2312
|
-
code: "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2316
|
+
code: "DEPLOYMENT_DISABLED" | "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2313
2317
|
status: number | null;
|
|
2314
2318
|
command: "cancel";
|
|
2315
2319
|
}, {
|
|
@@ -2317,7 +2321,7 @@ declare const IntegrityCommandFailureSchema: z.ZodEffects<z.ZodDiscriminatedUnio
|
|
|
2317
2321
|
status: number | null;
|
|
2318
2322
|
command: "start";
|
|
2319
2323
|
} | {
|
|
2320
|
-
code: "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2324
|
+
code: "DEPLOYMENT_DISABLED" | "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2321
2325
|
status: number | null;
|
|
2322
2326
|
command: "cancel";
|
|
2323
2327
|
}>;
|
|
@@ -3773,4 +3777,4 @@ type UuidV7 = string & {
|
|
|
3773
3777
|
declare function isValidUuidV7(uuid: string): uuid is UuidV7;
|
|
3774
3778
|
declare function generateUuidV7(): UuidV7;
|
|
3775
3779
|
declare function uuidv7ToDate(uuid: string): Date;
|
|
3776
|
-
export { type AmountEntry, AmountEntrySchema, BaseEnrichmentClient, type BodySource, BodySourceSchema, type BoundingBox, BoundingBoxSchema, CIRCUIT_BREAKER_SERVICES, type CanonicalDomainKey, CanonicalDomainKeySchema, type ChapterSegment, ChapterSegmentSchema, type ChunkSource, type ChunkingStrategy, ChunkingStrategySchema, type CircuitBreakerOpenReason, type CircuitBreakerService, type CircuitBreakerStatus, CircuitBreakerStatusSchema, type ConfidentialityLevel, ConfidentialityLevelSchema, DISPATCH_DEGRADATION_REASONS, DOCUMENT_KINDS, DOCUMENT_KIND_LABELS, type DispatchDegradationReason, type DocumentKind, DocumentKindSchema, type DocumentStructuredData, DocumentStructuredDataSchema, ENRICHMENT_STAGES, EnrichmentClient, EnrichmentClientError, type EnrichmentClientOptions, type EnrichmentStage, type EnrichmentStageKey, type EnrichmentSyncStatus, EnrichmentSyncStatusSchema, FILTERABLE_CONFIDENTIALITY_LEVELS, type FileUri, FileUriSchema, type FilterableConfidentialityLevel, type FlowGatePolicy, type FlowStep, GRAPH_INDEX_LIMITS, type GraphSearchHit, GraphSearchHitSchema, INTEGRITY_CLASS_POLICY, INTEGRITY_COMMAND_CODES, INTEGRITY_FINDINGS_PAGE_LIMIT_MAX, type IntegrityActiveRun, IntegrityActiveRunSchema, type IntegrityAuditOverview, IntegrityAuditOverviewSchema, type IntegrityCancelFailureCode, IntegrityCancelFailureCodeSchema, type IntegrityClassPolicy, type IntegrityCommand, type IntegrityCommandFailure, type IntegrityCommandFailureCode, type IntegrityCommandFailureCodeFor, IntegrityCommandFailureCodeSchema, IntegrityCommandFailureSchema, type IntegrityCommandReply, IntegrityCommandReplySchema, IntegrityCommandSchema, type IntegrityDisposition, IntegrityDispositionSchema, type IntegrityFinding, type IntegrityFindingItemClass, IntegrityFindingItemClassSchema, type IntegrityFindingPage, IntegrityFindingPageSchema, IntegrityFindingSchema, type IntegrityFindingsQuery, IntegrityFindingsQuerySchema, type IntegrityItemClass, IntegrityItemClassSchema, type IntegrityPhase, IntegrityPhaseSchema, type IntegrityQuantity, IntegrityQuantitySchema, type IntegrityRepairAction, IntegrityRepairActionSchema, type IntegrityRepairOutcome, IntegrityRepairOutcomeSchema, type IntegrityRepairSkipReason, IntegrityRepairSkipReasonSchema, type IntegrityRunHeader, IntegrityRunHeaderSchema, type IntegrityRunMode, IntegrityRunModeSchema, type IntegrityRunStatus, IntegrityRunStatusSchema, type IntegrityScopeRole, IntegrityScopeRoleSchema, type IntegrityStartFailureCode, IntegrityStartFailureCodeSchema, type IntegrityStore, IntegrityStoreSchema, type IntegrityUnit, IntegrityUnitSchema, type IntegrityVerdict, IntegrityVerdictSchema, LOCAL_DEGRADATION_REASONS, type LocalDegradationReason, MIME_KIND_RULES, MODE_TIERS, type ModelProvider, ModelProviderSchema, NOTHING_TO_READ_TOKENS, type NothingToReadToken, NothingToReadTokenSchema, PIPELINE_FLOWS, PIPELINE_PHASES, PIPELINE_STEPS, PIPELINE_STEP_KEYS, type PipelineFailureStatus, type PipelineFlow, type PipelinePhase, type PipelineRunRecord, PipelineRunRecordSchema, type PipelineRunStatus, PipelineRunStatusSchema, type PipelineRunSummary, PipelineRunSummarySchema, type PipelineStepDefinition, type PipelineStepKey, PipelineStepKeySchema, type PipelineStepMetric, PipelineStepMetricSchema, type PipelineStepRecord, PipelineStepRecordSchema, type PipelineStepStatus, PipelineStepStatusSchema, type PipelineTrigger, PipelineTriggerSchema, QUARANTINED_CONFIDENTIALITY_LEVEL, REMOTE_DEGRADATION_REASONS, type RemoteDegradationReason, type RemoteSearchFailureReason, SEARCH_DEGRADATION_REASONS, SEARCH_MODES, SEARCH_PARAM_LIMITS, SYSTEM_PARAMETER_RANGES, type SearchDegradationReason, type SearchHit, SearchHitSchema, type SearchMetadata, SearchMetadataSchema, type SearchMode, SearchModeSchema, type SearchRequest, type SearchRequestInput, SearchRequestSchema, type SearchResponse, SearchResponseSchema, type SkipReason, type StageProvenance, StageProvenanceSchema, type StepGate, type SystemParameterRange, type SystemParameterRangeKey, type TenantId, TenantIdSchema, type TranscriptSegment, TranscriptSegmentSchema, type UuidV7, assertBoundedSystemParameter, assertSystemParameterInRange, classifyDocumentKind, comparePhases, enrichmentStage, flowFor, flowStepGates, formatSkipReason, generateUuidV7, integrityCommandFailureCodeOf, isEnrichmentStageKey, isValidUuidV7, modeFusesRankings, modeNeedsRemoteTiers, modeScoreIsSimilarity, narrowModeToAllowedTiers, orderedSteps, parseSkipReason, uuidv7ToDate };
|
|
3780
|
+
export { type AmountEntry, AmountEntrySchema, BaseEnrichmentClient, type BodySource, BodySourceSchema, type BoundingBox, BoundingBoxSchema, CIRCUIT_BREAKER_SERVICES, type CanonicalDomainKey, CanonicalDomainKeySchema, type ChapterSegment, ChapterSegmentSchema, type ChunkSource, type ChunkingStrategy, ChunkingStrategySchema, type CircuitBreakerOpenReason, type CircuitBreakerService, type CircuitBreakerStatus, CircuitBreakerStatusSchema, type ConfidentialityLevel, ConfidentialityLevelSchema, DISPATCH_DEGRADATION_REASONS, DOCUMENT_KINDS, DOCUMENT_KIND_LABELS, type DispatchDegradationReason, type DocumentKind, DocumentKindSchema, type DocumentStructuredData, DocumentStructuredDataSchema, ENRICHMENT_STAGES, EnrichmentClient, EnrichmentClientError, type EnrichmentClientOptions, type EnrichmentStage, type EnrichmentStageKey, type EnrichmentSyncStatus, EnrichmentSyncStatusSchema, FILTERABLE_CONFIDENTIALITY_LEVELS, type FileUri, FileUriSchema, type FilterableConfidentialityLevel, type FlowGatePolicy, type FlowStep, GRAPH_INDEX_LIMITS, type GraphSearchHit, GraphSearchHitSchema, INTEGRITY_CLASS_POLICY, INTEGRITY_COMMAND_CODES, INTEGRITY_FINDINGS_PAGE_LIMIT_MAX, type IntegrityActiveRun, IntegrityActiveRunSchema, type IntegrityAuditOverview, IntegrityAuditOverviewSchema, type IntegrityCancelFailureCode, IntegrityCancelFailureCodeSchema, type IntegrityClassPolicy, type IntegrityCommand, type IntegrityCommandFailure, type IntegrityCommandFailureCode, type IntegrityCommandFailureCodeFor, IntegrityCommandFailureCodeSchema, IntegrityCommandFailureSchema, type IntegrityCommandReply, IntegrityCommandReplySchema, IntegrityCommandSchema, type IntegrityDisposition, IntegrityDispositionSchema, type IntegrityFinding, type IntegrityFindingItemClass, IntegrityFindingItemClassSchema, type IntegrityFindingPage, IntegrityFindingPageSchema, IntegrityFindingSchema, type IntegrityFindingsQuery, IntegrityFindingsQuerySchema, type IntegrityItemClass, IntegrityItemClassSchema, type IntegrityPhase, IntegrityPhaseSchema, type IntegrityQuantity, IntegrityQuantitySchema, type IntegrityRepairAction, IntegrityRepairActionSchema, type IntegrityRepairOutcome, IntegrityRepairOutcomeSchema, type IntegrityRepairSkipReason, IntegrityRepairSkipReasonSchema, type IntegrityRunHeader, IntegrityRunHeaderSchema, type IntegrityRunMode, IntegrityRunModeSchema, type IntegrityRunStatus, IntegrityRunStatusSchema, type IntegrityScopeRole, IntegrityScopeRoleSchema, type IntegrityStartFailureCode, IntegrityStartFailureCodeSchema, type IntegrityStore, IntegrityStoreSchema, type IntegrityUnit, IntegrityUnitSchema, type IntegrityVerdict, IntegrityVerdictSchema, LOCAL_DEGRADATION_REASONS, type LocalDegradationReason, MIME_KIND_RULES, MODE_TIERS, type ModelProvider, ModelProviderSchema, NOTHING_TO_READ_TOKENS, type NothingToReadToken, NothingToReadTokenSchema, PIPELINE_FLOWS, PIPELINE_PHASES, PIPELINE_STEPS, PIPELINE_STEP_KEYS, type PipelineFailureStatus, type PipelineFlow, type PipelinePhase, type PipelineRunRecord, PipelineRunRecordSchema, type PipelineRunStatus, PipelineRunStatusSchema, type PipelineRunSummary, PipelineRunSummarySchema, type PipelineStepDefinition, type PipelineStepKey, PipelineStepKeySchema, type PipelineStepMetric, PipelineStepMetricSchema, type PipelineStepRecord, PipelineStepRecordSchema, type PipelineStepStatus, PipelineStepStatusSchema, type PipelineTrigger, PipelineTriggerSchema, QUARANTINED_CONFIDENTIALITY_LEVEL, REMOTE_DEGRADATION_REASONS, type RemoteDegradationReason, type RemoteSearchFailureReason, SEARCH_DEGRADATION_REASONS, SEARCH_MODES, SEARCH_PARAM_LIMITS, SYSTEM_PARAMETER_RANGES, type SearchDegradationReason, type SearchHit, SearchHitSchema, type SearchMetadata, SearchMetadataSchema, type SearchMode, SearchModeSchema, type SearchRequest, type SearchRequestInput, SearchRequestSchema, type SearchResponse, SearchResponseSchema, type SkipReason, type StageProvenance, StageProvenanceSchema, type StepGate, type SystemParameterRange, type SystemParameterRangeKey, type TenantId, TenantIdSchema, type TranscriptSegment, TranscriptSegmentSchema, type UuidV7, assertBoundedSystemParameter, assertSystemParameterInRange, classifyDocumentKind, comparePhases, enrichmentStage, flowFor, flowStepGates, formatSkipReason, generateUuidV7, integrityCommandFailureCodeOf, isEnrichmentStageKey, isStrictlyEarlier, isValidUuidV7, modeFusesRankings, modeNeedsRemoteTiers, modeScoreIsSimilarity, narrowModeToAllowedTiers, orderedSteps, parseSkipReason, uuidv7ToDate };
|
package/dist/index.d.ts
CHANGED
|
@@ -553,6 +553,7 @@ declare function flowFor(kind: DocumentKind): PipelineFlow;
|
|
|
553
553
|
declare function flowStepGates(flowStep: FlowStep): readonly StepGate[];
|
|
554
554
|
declare function orderedSteps(flow: PipelineFlow): readonly FlowStep[];
|
|
555
555
|
declare function comparePhases(a: PipelinePhase, b: PipelinePhase): number;
|
|
556
|
+
declare const isStrictlyEarlier: (earlier: string, later: string) => boolean;
|
|
556
557
|
declare const IntegrityStoreSchema: z.ZodEnum<[
|
|
557
558
|
"QDRANT",
|
|
558
559
|
"NEO4J"
|
|
@@ -2222,6 +2223,7 @@ declare const IntegrityStartFailureCodeSchema: z.ZodEnum<[
|
|
|
2222
2223
|
]>;
|
|
2223
2224
|
type IntegrityStartFailureCode = z.infer<typeof IntegrityStartFailureCodeSchema>;
|
|
2224
2225
|
declare const IntegrityCancelFailureCodeSchema: z.ZodEnum<[
|
|
2226
|
+
"DEPLOYMENT_DISABLED",
|
|
2225
2227
|
"RUN_ALREADY_FINISHED",
|
|
2226
2228
|
"FORBIDDEN",
|
|
2227
2229
|
"UPSTREAM_FAILED"
|
|
@@ -2236,6 +2238,7 @@ declare const FAILURE_CODES_OF_COMMAND: {
|
|
|
2236
2238
|
"UPSTREAM_FAILED"
|
|
2237
2239
|
]>;
|
|
2238
2240
|
readonly cancel: z.ZodEnum<[
|
|
2241
|
+
"DEPLOYMENT_DISABLED",
|
|
2239
2242
|
"RUN_ALREADY_FINISHED",
|
|
2240
2243
|
"FORBIDDEN",
|
|
2241
2244
|
"UPSTREAM_FAILED"
|
|
@@ -2290,17 +2293,18 @@ declare const IntegrityCommandFailureSchema: z.ZodEffects<z.ZodDiscriminatedUnio
|
|
|
2290
2293
|
"cancel"
|
|
2291
2294
|
]>;
|
|
2292
2295
|
code: z.ZodEnum<[
|
|
2296
|
+
"DEPLOYMENT_DISABLED",
|
|
2293
2297
|
"RUN_ALREADY_FINISHED",
|
|
2294
2298
|
"FORBIDDEN",
|
|
2295
2299
|
"UPSTREAM_FAILED"
|
|
2296
2300
|
]>;
|
|
2297
2301
|
status: z.ZodNullable<z.ZodNumber>;
|
|
2298
2302
|
}, "strict", z.ZodTypeAny, {
|
|
2299
|
-
code: "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2303
|
+
code: "DEPLOYMENT_DISABLED" | "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2300
2304
|
status: number | null;
|
|
2301
2305
|
command: "cancel";
|
|
2302
2306
|
}, {
|
|
2303
|
-
code: "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2307
|
+
code: "DEPLOYMENT_DISABLED" | "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2304
2308
|
status: number | null;
|
|
2305
2309
|
command: "cancel";
|
|
2306
2310
|
}>
|
|
@@ -2309,7 +2313,7 @@ declare const IntegrityCommandFailureSchema: z.ZodEffects<z.ZodDiscriminatedUnio
|
|
|
2309
2313
|
status: number | null;
|
|
2310
2314
|
command: "start";
|
|
2311
2315
|
} | {
|
|
2312
|
-
code: "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2316
|
+
code: "DEPLOYMENT_DISABLED" | "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2313
2317
|
status: number | null;
|
|
2314
2318
|
command: "cancel";
|
|
2315
2319
|
}, {
|
|
@@ -2317,7 +2321,7 @@ declare const IntegrityCommandFailureSchema: z.ZodEffects<z.ZodDiscriminatedUnio
|
|
|
2317
2321
|
status: number | null;
|
|
2318
2322
|
command: "start";
|
|
2319
2323
|
} | {
|
|
2320
|
-
code: "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2324
|
+
code: "DEPLOYMENT_DISABLED" | "RUN_ALREADY_FINISHED" | "FORBIDDEN" | "UPSTREAM_FAILED";
|
|
2321
2325
|
status: number | null;
|
|
2322
2326
|
command: "cancel";
|
|
2323
2327
|
}>;
|
|
@@ -3773,4 +3777,4 @@ type UuidV7 = string & {
|
|
|
3773
3777
|
declare function isValidUuidV7(uuid: string): uuid is UuidV7;
|
|
3774
3778
|
declare function generateUuidV7(): UuidV7;
|
|
3775
3779
|
declare function uuidv7ToDate(uuid: string): Date;
|
|
3776
|
-
export { type AmountEntry, AmountEntrySchema, BaseEnrichmentClient, type BodySource, BodySourceSchema, type BoundingBox, BoundingBoxSchema, CIRCUIT_BREAKER_SERVICES, type CanonicalDomainKey, CanonicalDomainKeySchema, type ChapterSegment, ChapterSegmentSchema, type ChunkSource, type ChunkingStrategy, ChunkingStrategySchema, type CircuitBreakerOpenReason, type CircuitBreakerService, type CircuitBreakerStatus, CircuitBreakerStatusSchema, type ConfidentialityLevel, ConfidentialityLevelSchema, DISPATCH_DEGRADATION_REASONS, DOCUMENT_KINDS, DOCUMENT_KIND_LABELS, type DispatchDegradationReason, type DocumentKind, DocumentKindSchema, type DocumentStructuredData, DocumentStructuredDataSchema, ENRICHMENT_STAGES, EnrichmentClient, EnrichmentClientError, type EnrichmentClientOptions, type EnrichmentStage, type EnrichmentStageKey, type EnrichmentSyncStatus, EnrichmentSyncStatusSchema, FILTERABLE_CONFIDENTIALITY_LEVELS, type FileUri, FileUriSchema, type FilterableConfidentialityLevel, type FlowGatePolicy, type FlowStep, GRAPH_INDEX_LIMITS, type GraphSearchHit, GraphSearchHitSchema, INTEGRITY_CLASS_POLICY, INTEGRITY_COMMAND_CODES, INTEGRITY_FINDINGS_PAGE_LIMIT_MAX, type IntegrityActiveRun, IntegrityActiveRunSchema, type IntegrityAuditOverview, IntegrityAuditOverviewSchema, type IntegrityCancelFailureCode, IntegrityCancelFailureCodeSchema, type IntegrityClassPolicy, type IntegrityCommand, type IntegrityCommandFailure, type IntegrityCommandFailureCode, type IntegrityCommandFailureCodeFor, IntegrityCommandFailureCodeSchema, IntegrityCommandFailureSchema, type IntegrityCommandReply, IntegrityCommandReplySchema, IntegrityCommandSchema, type IntegrityDisposition, IntegrityDispositionSchema, type IntegrityFinding, type IntegrityFindingItemClass, IntegrityFindingItemClassSchema, type IntegrityFindingPage, IntegrityFindingPageSchema, IntegrityFindingSchema, type IntegrityFindingsQuery, IntegrityFindingsQuerySchema, type IntegrityItemClass, IntegrityItemClassSchema, type IntegrityPhase, IntegrityPhaseSchema, type IntegrityQuantity, IntegrityQuantitySchema, type IntegrityRepairAction, IntegrityRepairActionSchema, type IntegrityRepairOutcome, IntegrityRepairOutcomeSchema, type IntegrityRepairSkipReason, IntegrityRepairSkipReasonSchema, type IntegrityRunHeader, IntegrityRunHeaderSchema, type IntegrityRunMode, IntegrityRunModeSchema, type IntegrityRunStatus, IntegrityRunStatusSchema, type IntegrityScopeRole, IntegrityScopeRoleSchema, type IntegrityStartFailureCode, IntegrityStartFailureCodeSchema, type IntegrityStore, IntegrityStoreSchema, type IntegrityUnit, IntegrityUnitSchema, type IntegrityVerdict, IntegrityVerdictSchema, LOCAL_DEGRADATION_REASONS, type LocalDegradationReason, MIME_KIND_RULES, MODE_TIERS, type ModelProvider, ModelProviderSchema, NOTHING_TO_READ_TOKENS, type NothingToReadToken, NothingToReadTokenSchema, PIPELINE_FLOWS, PIPELINE_PHASES, PIPELINE_STEPS, PIPELINE_STEP_KEYS, type PipelineFailureStatus, type PipelineFlow, type PipelinePhase, type PipelineRunRecord, PipelineRunRecordSchema, type PipelineRunStatus, PipelineRunStatusSchema, type PipelineRunSummary, PipelineRunSummarySchema, type PipelineStepDefinition, type PipelineStepKey, PipelineStepKeySchema, type PipelineStepMetric, PipelineStepMetricSchema, type PipelineStepRecord, PipelineStepRecordSchema, type PipelineStepStatus, PipelineStepStatusSchema, type PipelineTrigger, PipelineTriggerSchema, QUARANTINED_CONFIDENTIALITY_LEVEL, REMOTE_DEGRADATION_REASONS, type RemoteDegradationReason, type RemoteSearchFailureReason, SEARCH_DEGRADATION_REASONS, SEARCH_MODES, SEARCH_PARAM_LIMITS, SYSTEM_PARAMETER_RANGES, type SearchDegradationReason, type SearchHit, SearchHitSchema, type SearchMetadata, SearchMetadataSchema, type SearchMode, SearchModeSchema, type SearchRequest, type SearchRequestInput, SearchRequestSchema, type SearchResponse, SearchResponseSchema, type SkipReason, type StageProvenance, StageProvenanceSchema, type StepGate, type SystemParameterRange, type SystemParameterRangeKey, type TenantId, TenantIdSchema, type TranscriptSegment, TranscriptSegmentSchema, type UuidV7, assertBoundedSystemParameter, assertSystemParameterInRange, classifyDocumentKind, comparePhases, enrichmentStage, flowFor, flowStepGates, formatSkipReason, generateUuidV7, integrityCommandFailureCodeOf, isEnrichmentStageKey, isValidUuidV7, modeFusesRankings, modeNeedsRemoteTiers, modeScoreIsSimilarity, narrowModeToAllowedTiers, orderedSteps, parseSkipReason, uuidv7ToDate };
|
|
3780
|
+
export { type AmountEntry, AmountEntrySchema, BaseEnrichmentClient, type BodySource, BodySourceSchema, type BoundingBox, BoundingBoxSchema, CIRCUIT_BREAKER_SERVICES, type CanonicalDomainKey, CanonicalDomainKeySchema, type ChapterSegment, ChapterSegmentSchema, type ChunkSource, type ChunkingStrategy, ChunkingStrategySchema, type CircuitBreakerOpenReason, type CircuitBreakerService, type CircuitBreakerStatus, CircuitBreakerStatusSchema, type ConfidentialityLevel, ConfidentialityLevelSchema, DISPATCH_DEGRADATION_REASONS, DOCUMENT_KINDS, DOCUMENT_KIND_LABELS, type DispatchDegradationReason, type DocumentKind, DocumentKindSchema, type DocumentStructuredData, DocumentStructuredDataSchema, ENRICHMENT_STAGES, EnrichmentClient, EnrichmentClientError, type EnrichmentClientOptions, type EnrichmentStage, type EnrichmentStageKey, type EnrichmentSyncStatus, EnrichmentSyncStatusSchema, FILTERABLE_CONFIDENTIALITY_LEVELS, type FileUri, FileUriSchema, type FilterableConfidentialityLevel, type FlowGatePolicy, type FlowStep, GRAPH_INDEX_LIMITS, type GraphSearchHit, GraphSearchHitSchema, INTEGRITY_CLASS_POLICY, INTEGRITY_COMMAND_CODES, INTEGRITY_FINDINGS_PAGE_LIMIT_MAX, type IntegrityActiveRun, IntegrityActiveRunSchema, type IntegrityAuditOverview, IntegrityAuditOverviewSchema, type IntegrityCancelFailureCode, IntegrityCancelFailureCodeSchema, type IntegrityClassPolicy, type IntegrityCommand, type IntegrityCommandFailure, type IntegrityCommandFailureCode, type IntegrityCommandFailureCodeFor, IntegrityCommandFailureCodeSchema, IntegrityCommandFailureSchema, type IntegrityCommandReply, IntegrityCommandReplySchema, IntegrityCommandSchema, type IntegrityDisposition, IntegrityDispositionSchema, type IntegrityFinding, type IntegrityFindingItemClass, IntegrityFindingItemClassSchema, type IntegrityFindingPage, IntegrityFindingPageSchema, IntegrityFindingSchema, type IntegrityFindingsQuery, IntegrityFindingsQuerySchema, type IntegrityItemClass, IntegrityItemClassSchema, type IntegrityPhase, IntegrityPhaseSchema, type IntegrityQuantity, IntegrityQuantitySchema, type IntegrityRepairAction, IntegrityRepairActionSchema, type IntegrityRepairOutcome, IntegrityRepairOutcomeSchema, type IntegrityRepairSkipReason, IntegrityRepairSkipReasonSchema, type IntegrityRunHeader, IntegrityRunHeaderSchema, type IntegrityRunMode, IntegrityRunModeSchema, type IntegrityRunStatus, IntegrityRunStatusSchema, type IntegrityScopeRole, IntegrityScopeRoleSchema, type IntegrityStartFailureCode, IntegrityStartFailureCodeSchema, type IntegrityStore, IntegrityStoreSchema, type IntegrityUnit, IntegrityUnitSchema, type IntegrityVerdict, IntegrityVerdictSchema, LOCAL_DEGRADATION_REASONS, type LocalDegradationReason, MIME_KIND_RULES, MODE_TIERS, type ModelProvider, ModelProviderSchema, NOTHING_TO_READ_TOKENS, type NothingToReadToken, NothingToReadTokenSchema, PIPELINE_FLOWS, PIPELINE_PHASES, PIPELINE_STEPS, PIPELINE_STEP_KEYS, type PipelineFailureStatus, type PipelineFlow, type PipelinePhase, type PipelineRunRecord, PipelineRunRecordSchema, type PipelineRunStatus, PipelineRunStatusSchema, type PipelineRunSummary, PipelineRunSummarySchema, type PipelineStepDefinition, type PipelineStepKey, PipelineStepKeySchema, type PipelineStepMetric, PipelineStepMetricSchema, type PipelineStepRecord, PipelineStepRecordSchema, type PipelineStepStatus, PipelineStepStatusSchema, type PipelineTrigger, PipelineTriggerSchema, QUARANTINED_CONFIDENTIALITY_LEVEL, REMOTE_DEGRADATION_REASONS, type RemoteDegradationReason, type RemoteSearchFailureReason, SEARCH_DEGRADATION_REASONS, SEARCH_MODES, SEARCH_PARAM_LIMITS, SYSTEM_PARAMETER_RANGES, type SearchDegradationReason, type SearchHit, SearchHitSchema, type SearchMetadata, SearchMetadataSchema, type SearchMode, SearchModeSchema, type SearchRequest, type SearchRequestInput, SearchRequestSchema, type SearchResponse, SearchResponseSchema, type SkipReason, type StageProvenance, StageProvenanceSchema, type StepGate, type SystemParameterRange, type SystemParameterRangeKey, type TenantId, TenantIdSchema, type TranscriptSegment, TranscriptSegmentSchema, type UuidV7, assertBoundedSystemParameter, assertSystemParameterInRange, classifyDocumentKind, comparePhases, enrichmentStage, flowFor, flowStepGates, formatSkipReason, generateUuidV7, integrityCommandFailureCodeOf, isEnrichmentStageKey, isStrictlyEarlier, isValidUuidV7, modeFusesRankings, modeNeedsRemoteTiers, modeScoreIsSimilarity, narrowModeToAllowedTiers, orderedSteps, parseSkipReason, uuidv7ToDate };
|
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"]),P=B.enum(["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"]),F="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=P.options.filter(e=>e!==F);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()}),be=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(be).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"]),xe=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:xe.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"],L=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:[L("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:[L("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:[L("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 v}from"zod";var A=v.string().uuid().transform(e=>e.toLowerCase()),u=v.string().datetime({offset:!0}),s=(e,t,n)=>{e.addIssue({code:v.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,O=new Date(0);O.setUTCFullYear(Number(n),Number(a)-1,Number(l)),O.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:O.getTime()/1e3-he,fraction:f===void 0?"":f}},k=(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(),x=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&&k(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."),k(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.")},xn=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(["RUN_ALREADY_FINISHED","FORBIDDEN","UPSTREAM_FAILED"]),M={start:Et,cancel:St},ht=o.object({code:G.exclude(["UPSTREAM_FAILED"]),status:x,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:x.nullable()}).strict(),o.object({command:le.extract(["cancel"]),code:M.cancel,status:x.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:x,errorCode:o.number().int().nullable()}).strict()]);import{z as i}from"zod";var me=i.enum(Z),D=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",bt=/^[A-Z][A-Z0-9_]*$/;function xt(e){if(e===ye)return{kind:"no_children"};if(e.startsWith(z)){let t=e.slice(z.length);return bt.test(t)?{kind:"gate_closed",featureFlagKey:t}:null}if(e.startsWith(K)){let t=D.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 Un(e){let t=Dt(e);if(xt(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:D,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:D.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 Gn=fe.superRefine(Ee),zn=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 Kn=i.object({documentKind:me,stepKey:D,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 Bn(e){return vt.has(e)}function jn(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 Yn={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 Vn(){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 Xn(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{be 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,P 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,Yn 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,xn 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,Gn as PipelineRunRecordSchema,It as PipelineRunStatusSchema,zn as PipelineRunSummarySchema,D as PipelineStepKeySchema,Kn as PipelineStepMetricSchema,Ft as PipelineStepRecordSchema,Rt as PipelineStepStatusSchema,_t as PipelineTriggerSchema,F 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,xe 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,jn as enrichmentStage,dn as flowFor,un as flowStepGates,Un as formatSkipReason,Vn as generateUuidV7,Fn as integrityCommandFailureCodeOf,Bn as isEnrichmentStageKey,kt as isValidUuidV7,Yt as modeFusesRankings,Ht as modeNeedsRemoteTiers,Bt as modeScoreIsSimilarity,jt as narrowModeToAllowedTiers,mn as orderedSteps,xt as parseSkipReason,Xn 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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aiquants/enrichment-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Storage metadata AI enrichment core: canonical schemas, RFC 9562 UUIDv7, and API client SDK.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"enrichment",
|
|
@@ -62,9 +62,9 @@
|
|
|
62
62
|
"build": "tsup && node ../../.config/scripts/strip-dts-comments.mjs dist",
|
|
63
63
|
"build:watch": "tsup --watch",
|
|
64
64
|
"dev": "tsup --watch",
|
|
65
|
-
"publish:patch": "pnpm run typecheck && pnpm run --if-present test && pnpm version patch --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
|
|
66
|
-
"publish:minor": "pnpm run typecheck && pnpm run --if-present test && pnpm version minor --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
|
|
67
|
-
"publish:major": "pnpm run typecheck && pnpm run --if-present test && pnpm version major --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
|
|
65
|
+
"publish:patch": "pnpm run typecheck && pnpm run --if-present test && pnpm run build && node ../../.config/scripts/check-publish-leaks.mjs && pnpm version patch --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
|
|
66
|
+
"publish:minor": "pnpm run typecheck && pnpm run --if-present test && pnpm run build && node ../../.config/scripts/check-publish-leaks.mjs && pnpm version minor --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
|
|
67
|
+
"publish:major": "pnpm run typecheck && pnpm run --if-present test && pnpm run build && node ../../.config/scripts/check-publish-leaks.mjs && pnpm version major --no-git-tag-version --no-git-checks && pnpm publish --no-git-checks",
|
|
68
68
|
"typecheck": "tsc --noEmit",
|
|
69
69
|
"clean": "rimraf dist",
|
|
70
70
|
"lint": "biome lint src/",
|