@flyle/ai-cx-mcp 0.2.1-develop.20261109142004.gc21216e → 0.2.1-develop.20261109153131.g4e258f6
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 +3 -2
- package/guide-articles.json.br +0 -0
- package/main.js +41 -37
- package/manifest.json.br +0 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @flyle/ai-cx-mcp
|
|
2
2
|
|
|
3
|
-
Flyle AI CX を Claude Code などの MCP クライアントから操作するための MCP サーバーです。ブラウザでご自身のアカウントにログインし、**ご自身のロールの権限の範囲で**テーブル・レコード・ロール・レポート・ダッシュボード・AI
|
|
3
|
+
Flyle AI CX を Claude Code などの MCP クライアントから操作するための MCP サーバーです。ブラウザでご自身のアカウントにログインし、**ご自身のロールの権限の範囲で**テーブル・レコード・ロール・レポート・ダッシュボード・AI グルーピングを操作し、ワークフローを参照・下書きとして作成・更新し、フォームを参照・編集できます。
|
|
4
4
|
|
|
5
5
|
> [!NOTE]
|
|
6
6
|
> 試験的な提供です。現在は Flyle 社内メンバー(flyle.io ドメインのアカウント)と、Flyle が提供を始めたテナントに限定しています。公開 API のベータ版(`v0`)に対応しており、仕様が変わる場合があります。
|
|
@@ -74,7 +74,8 @@ Claude Code を起動したままログインした場合は、`/mcp` から MCP
|
|
|
74
74
|
- ユーザーの一覧・取得・招待・名前の変更・削除、ユーザーグループの一覧・取得・作成・更新・メンバーの追加と削除・削除
|
|
75
75
|
- レポート・ダッシュボードの参照・作成・更新と、保存前のプレビュー画像の作成
|
|
76
76
|
- AI グルーピングの参照・作成・更新・削除、グループの追加・移動・並べ替え・統合・削除、分類の実行・状況の確認・中止(AI で分類する実行は AI クレジットを消費します)
|
|
77
|
-
-
|
|
77
|
+
- ワークフローの一覧・定義と公開版の起動方法の参照、下書きの作成・更新・指定した版への戻し(公開はされません)、削除、実行状況の確認
|
|
78
|
+
- フォームの取得、内容(セクション・設問・分岐・計算ステップ)の更新、指定した版への戻し(公開の状態は変えません)
|
|
78
79
|
- テーブルの作成、フィールドの削除・種類の変更、データのエクスポート、ワークフローの公開は行えません。
|
|
79
80
|
- ワークフローの実行は API キー専用の操作です(再送で二重に実行しないよう Idempotency-Key が必須なため)。ログイン接続で動く MCP サーバーのツールにはありません。
|
|
80
81
|
- Owner ロールや全操作(`*`)を許可・拒否するロールの付与、それらを持つユーザー・ユーザーグループの削除は、画面で行います。
|
package/guide-articles.json.br
CHANGED
|
Binary file
|
package/main.js
CHANGED
|
@@ -1,35 +1,36 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{homedir as e,hostname as t,userInfo as n}from"node:os";import{createInterface as r}from"node:readline/promises";import{serveStdio as i}from"@modelcontextprotocol/server/stdio";import{createHash as a,randomBytes as o,timingSafeEqual as s}from"node:crypto";import{chmod as c,link as l,lstat as u,mkdir as d,open as f,readFile as p,readdir as m,realpath as h,rename as
|
|
3
|
-
function
|
|
4
|
-
function
|
|
5
|
-
function
|
|
6
|
-
function
|
|
7
|
-
function
|
|
8
|
-
function
|
|
9
|
-
function
|
|
10
|
-
function
|
|
11
|
-
function Ce(e){return{kind:`validation`,type:`non_empty`,reference:Ce,async:!1,expects:`!0`,message:e,"~run"(e,t){return e.typed&&e.value.length===0&&
|
|
12
|
-
function O(e,t){return{kind:`validation`,type:`regex`,reference:O,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!this.requirement.test(e.value)&&
|
|
2
|
+
import{homedir as e,hostname as t,userInfo as n}from"node:os";import{createInterface as r}from"node:readline/promises";import{serveStdio as i}from"@modelcontextprotocol/server/stdio";import{createHash as a,randomBytes as o,timingSafeEqual as s}from"node:crypto";import{chmod as c,link as l,lstat as u,mkdir as d,open as f,readFile as p,readdir as m,realpath as h,rename as g,rm as _,writeFile as ee}from"node:fs/promises";import*as v from"node:path";import{spawn as te}from"node:child_process";import{createServer as ne}from"node:http";import{parseArgs as re}from"node:util";import{readFileSync as ie}from"node:fs";import{brotliDecompressSync as ae}from"node:zlib";import{McpServer as oe,fromJsonSchema as y}from"@modelcontextprotocol/server";import{AjvJsonSchemaValidator as se}from"@modelcontextprotocol/server/validators/ajv";var ce=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);function b(e,t){return Object.hasOwn(e,t)}const le=(e,t)=>b(e,t),x=e=>{let t=[];for(let n in e)le(e,n)&&t.push(n);return t},S=e=>{let t=[];for(let n in e)if(le(e,n)){let r=Reflect.get(e,n);t.push([n,r])}return t},ue=e=>{let t=[];for(let n in e)if(le(e,n)){let r=Reflect.get(e,n);t.push(r)}return t},C=e=>{let t={};for(let[n,r]of e)Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:r,writable:!0});return t},w=e=>typeof e==`object`&&!!e&&!Array.isArray(e),de=(e,t)=>e===t?0:e<t?-1:1,fe=(e,t)=>{let n=e.length,r=t.length,i=Array.from({length:n+1},()=>Array.from({length:r+1}).fill(0));for(let e=0;e<=n;e++){let t=i[e];t!=null&&(t[0]=e)}for(let e=0;e<=r;e++){let t=i[0];t!=null&&(t[e]=e)}for(let a=1;a<=n;a++)for(let n=1;n<=r;n++){let r=i[a-1],o=i[a];if(o==null||r==null)continue;let s=e[a-1]===t[n-1]?0:1;o[n]=Math.min((r[n]??0)+1,(o[n-1]??0)+1,(r[n-1]??0)+s)}return i[n]?.[r]??0},T=()=>{},pe={lang:void 0,message:void 0,abortEarly:void 0,abortPipeEarly:void 0};/* @__NO_SIDE_EFFECTS__ */
|
|
3
|
+
function me(e){return e?{lang:e?.lang??void 0,message:e?.message,abortEarly:e?.abortEarly??void 0,abortPipeEarly:e?.abortPipeEarly??void 0}:pe}/* @__NO_SIDE_EFFECTS__ */
|
|
4
|
+
function he(e){let t=typeof e;return t===`string`?`"${e}"`:t===`number`||t===`bigint`||t===`boolean`?`${e}`:t===`object`||t===`function`?(e&&Object.getPrototypeOf(e)?.constructor?.name)??`null`:t}function E(e,t,n,r,i){let a=i&&`input`in i?i.input:n.value,o=i?.expected??e.expects??null,s=i?.received??/* @__PURE__ */ he(a),c={kind:e.kind,type:e.type,input:a,expected:o,received:s,message:`Invalid ${t}: ${o?`Expected ${o} but r`:`R`}eceived ${s}`,requirement:e.requirement,path:i?.path,issues:i?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},l=e.kind===`schema`,u=i?.message??e.message??(e.reference,c.lang,void 0)??(l?(c.lang,void 0):null)??r.message??(c.lang,void 0);u!==void 0&&(c.message=typeof u==`function`?u(c):u),l&&(n.typed=!1),n.issues?n.issues.push(c):n.issues=[c]}/* @__NO_SIDE_EFFECTS__ */
|
|
5
|
+
function ge(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}/* @__NO_SIDE_EFFECTS__ */
|
|
6
|
+
function _e(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&t!==`__proto__`&&t!==`prototype`&&t!==`constructor`}/* @__NO_SIDE_EFFECTS__ */
|
|
7
|
+
function ve(e,t){let n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??`never`}function D(e){return e[`~standard`]={version:1,vendor:`valibot`,validate:t=>e[`~run`]({value:t},/* @__PURE__ */ me())},e}const ye=/^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z| ?[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;/* @__NO_SIDE_EFFECTS__ */
|
|
8
|
+
function be(e,t){return{kind:`validation`,type:`check`,reference:be,async:!1,expects:null,requirement:e,message:t,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&E(this,`input`,e,t),e}}}/* @__NO_SIDE_EFFECTS__ */
|
|
9
|
+
function xe(e,t){let n=/* @__PURE__ */ he(e);return{kind:`validation`,type:`includes`,reference:xe,async:!1,expects:n,requirement:e,message:t,"~run"(e,t){return e.typed&&!e.value.includes(this.requirement)&&E(this,`content`,e,t,{received:`!${n}`}),e}}}/* @__NO_SIDE_EFFECTS__ */
|
|
10
|
+
function Se(e){return{kind:`validation`,type:`iso_timestamp`,reference:Se,async:!1,expects:null,requirement:ye,message:e,"~run"(e,t){return e.typed&&!this.requirement.test(e.value)&&E(this,`timestamp`,e,t),e}}}/* @__NO_SIDE_EFFECTS__ */
|
|
11
|
+
function Ce(e){return{kind:`validation`,type:`non_empty`,reference:Ce,async:!1,expects:`!0`,message:e,"~run"(e,t){return e.typed&&e.value.length===0&&E(this,`length`,e,t,{received:`0`}),e}}}/* @__NO_SIDE_EFFECTS__ */
|
|
12
|
+
function O(e,t){return{kind:`validation`,type:`regex`,reference:O,async:!1,expects:`${e}`,requirement:e,message:t,"~run"(e,t){return e.typed&&!this.requirement.test(e.value)&&E(this,`format`,e,t),e}}}/* @__NO_SIDE_EFFECTS__ */
|
|
13
13
|
function we(e){return{kind:`transformation`,type:`transform`,reference:we,async:!1,operation:e,"~run"(e){return e.value=this.operation(e.value),e}}}/* @__NO_SIDE_EFFECTS__ */
|
|
14
|
-
function Te(e){return{kind:`validation`,type:`url`,reference:Te,async:!1,expects:null,requirement(e){try{return URL.canParse?URL.canParse(e):(new URL(e),!0)}catch{return!1}},message:e,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&
|
|
14
|
+
function Te(e){return{kind:`validation`,type:`url`,reference:Te,async:!1,expects:null,requirement(e){try{return URL.canParse?URL.canParse(e):(new URL(e),!0)}catch{return!1}},message:e,"~run"(e,t){return e.typed&&!this.requirement(e.value)&&E(this,`URL`,e,t),e}}}/* @__NO_SIDE_EFFECTS__ */
|
|
15
15
|
function Ee(e,t,n){return typeof e.fallback==`function`?e.fallback(t,n):e.fallback}/* @__NO_SIDE_EFFECTS__ */
|
|
16
16
|
function De(e,t,n){return typeof e.default==`function`?e.default(t,n):e.default}/* @__NO_SIDE_EFFECTS__ */
|
|
17
|
-
function Oe(e,t){return
|
|
18
|
-
function ke(e,t){return
|
|
19
|
-
function Ae(e){return
|
|
20
|
-
function k(e,t){return
|
|
21
|
-
function je(e,t,n){return
|
|
22
|
-
function Me(e,t){return
|
|
23
|
-
function A(e){return
|
|
17
|
+
function Oe(e,t){return D({kind:`schema`,type:`array`,reference:Oe,expects:`Array`,async:!1,item:e,message:t,"~run"(e,t){let n=e.value;if(Array.isArray(n)){e.typed=!0,e.value=[];for(let r=0;r<n.length;r++){let i=n[r],a=this.item[`~run`]({value:i},t);if(a.issues){let o={type:`array`,origin:`value`,input:n,key:r,value:i};for(let t of a.issues)t.path?t.path.unshift(o):t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}a.typed||(e.typed=!1),e.value.push(a.value)}}else E(this,`type`,e,t);return e}})}/* @__NO_SIDE_EFFECTS__ */
|
|
18
|
+
function ke(e,t){return D({kind:`schema`,type:`literal`,reference:ke,expects:/* @__PURE__ */ he(e),async:!1,literal:e,message:t,"~run"(e,t){return/* @__PURE__ */ ge(e.value,this.literal)?e.typed=!0:E(this,`type`,e,t),e}})}/* @__NO_SIDE_EFFECTS__ */
|
|
19
|
+
function Ae(e){return D({kind:`schema`,type:`number`,reference:Ae,expects:`number`,async:!1,message:e,"~run"(e,t){return typeof e.value==`number`&&!isNaN(e.value)?e.typed=!0:E(this,`type`,e,t),e}})}/* @__NO_SIDE_EFFECTS__ */
|
|
20
|
+
function k(e,t){return D({kind:`schema`,type:`object`,reference:k,expects:`Object`,async:!1,entries:e,message:t,"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in this.entries){let i=this.entries[r];if(r in n||(i.type===`exact_optional`||i.type===`optional`||i.type===`nullish`)&&i.default!==void 0){let a=r in n?n[r]:/* @__PURE__ */ De(i),o=i[`~run`]({value:a},t);if(o.issues){let i={type:`object`,origin:`value`,input:n,key:r,value:a};for(let t of o.issues)t.path?t.path.unshift(i):t.path=[i],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value[r]=o.value}else if(i.fallback!==void 0)e.value[r]=/* @__PURE__ */ Ee(i);else if(i.type!==`exact_optional`&&i.type!==`optional`&&i.type!==`nullish`&&(E(this,`key`,e,t,{input:void 0,expected:`"${r}"`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]}),t.abortEarly))break}}else E(this,`type`,e,t);return e}})}/* @__NO_SIDE_EFFECTS__ */
|
|
21
|
+
function je(e,t,n){return D({kind:`schema`,type:`record`,reference:je,expects:`Object`,async:!1,key:e,value:t,message:n,"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in n)if(/* @__PURE__ */ _e(n,r)){let i=n[r],a=this.key[`~run`]({value:r},t);if(a.issues){let o={type:`object`,origin:`key`,input:n,key:r,value:i};for(let t of a.issues)t.path=[o],e.issues?.push(t);if(e.issues||=a.issues,t.abortEarly){e.typed=!1;break}}let o=this.value[`~run`]({value:i},t);if(o.issues){let a={type:`object`,origin:`value`,input:n,key:r,value:i};for(let t of o.issues)t.path?t.path.unshift(a):t.path=[a],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}(!a.typed||!o.typed)&&(e.typed=!1),a.typed&&(e.value[a.value]=o.value)}}else E(this,`type`,e,t);return e}})}/* @__NO_SIDE_EFFECTS__ */
|
|
22
|
+
function Me(e,t){return D({kind:`schema`,type:`strict_object`,reference:Me,expects:`Object`,async:!1,entries:e,message:t,"~run"(e,t){let n=e.value;if(n&&typeof n==`object`){e.typed=!0,e.value={};for(let r in this.entries){let i=this.entries[r];if(r in n||(i.type===`exact_optional`||i.type===`optional`||i.type===`nullish`)&&i.default!==void 0){let a=r in n?n[r]:/* @__PURE__ */ De(i),o=i[`~run`]({value:a},t);if(o.issues){let i={type:`object`,origin:`value`,input:n,key:r,value:a};for(let t of o.issues)t.path?t.path.unshift(i):t.path=[i],e.issues?.push(t);if(e.issues||=o.issues,t.abortEarly){e.typed=!1;break}}o.typed||(e.typed=!1),e.value[r]=o.value}else if(i.fallback!==void 0)e.value[r]=/* @__PURE__ */ Ee(i);else if(i.type!==`exact_optional`&&i.type!==`optional`&&i.type!==`nullish`&&(E(this,`key`,e,t,{input:void 0,expected:`"${r}"`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]}),t.abortEarly))break}if(!e.issues||!t.abortEarly){for(let r in n)if(!Object.prototype.hasOwnProperty.call(this.entries,r)){E(this,`key`,e,t,{input:r,expected:`never`,path:[{type:`object`,origin:`key`,input:n,key:r,value:n[r]}]});break}}}else E(this,`type`,e,t);return e}})}/* @__NO_SIDE_EFFECTS__ */
|
|
23
|
+
function A(e){return D({kind:`schema`,type:`string`,reference:A,expects:`string`,async:!1,message:e,"~run"(e,t){return typeof e.value==`string`?e.typed=!0:E(this,`type`,e,t),e}})}/* @__NO_SIDE_EFFECTS__ */
|
|
24
24
|
function Ne(e){let t;if(e)for(let n of e)if(t)for(let e of n.issues)t.push(e);else t=n.issues;return t}/* @__NO_SIDE_EFFECTS__ */
|
|
25
|
-
function Pe(e,t){return
|
|
26
|
-
function j(...e){return
|
|
27
|
-
function
|
|
25
|
+
function Pe(e,t){return D({kind:`schema`,type:`union`,reference:Pe,expects:/* @__PURE__ */ ve(e.map(e=>e.expects),`|`),async:!1,options:e,message:t,"~run"(e,t){let n,r,i;for(let a of this.options){let o=a[`~run`]({value:e.value},t);if(o.typed){if(o.issues)r?r.push(o):r=[o];else{n=o;break}}else i?i.push(o):i=[o]}if(n)return n;if(r){if(r.length===1)return r[0];E(this,`type`,e,t,{issues:/* @__PURE__ */ Ne(r)}),e.typed=!0}else if(i?.length===1)return i[0];else E(this,`type`,e,t,{issues:/* @__PURE__ */ Ne(i)});return e}})}/* @__NO_SIDE_EFFECTS__ */
|
|
26
|
+
function j(...e){return D({...e[0],pipe:e,"~run"(t,n){for(let r of e)if(r.kind!==`metadata`){if(t.issues&&(r.kind===`schema`||r.kind===`transformation`)){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=r[`~run`](t,n))}return t}})}/* @__NO_SIDE_EFFECTS__ */
|
|
27
|
+
function M(e,t,n){let r=e[`~run`]({value:t},/* @__PURE__ */ me(n));return{typed:r.typed,success:!r.issues,output:r.value,issues:r.issues}}const Fe=`0.2.1`,Ie=`https://public-api.nexus.flyle.io`,Le=/^flyle_ac_[0-9A-Za-z]{43}$/,Re=/^flyle_ut_[0-9A-Za-z]{43}$/,ze=/^flyle_rt_[0-9A-Za-z]{43}$/,Be=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,Ve=/^[a-z0-9](-?[a-z0-9])*$/,N=`get_input_schema`;var He=class extends Error{name=`InvalidArgumentsError`},P=class extends Error{name=`AuthError`;kind;constructor(e,t){super(t),this.kind=e}},Ue=class extends Error{name=`ManifestLoadError`},We=class extends Error{name=`ManifestBuildError`},F=class extends Error{name=`ApiError`;info;constructor(e){super(`${e.status} ${e.code??`http_error`}: ${e.message}`),this.info=e}},I=class extends Error{name=`TransportError`;kind;status;constructor(e,t,n=null){super(t),this.kind=e,this.status=n}},L=class extends Error{name=`ConfigError`},Ge=class extends Error{name=`GuideArticlesLoadError`},R=class extends Error{name=`ResultFileError`;kind;constructor(e,t){super(t),this.kind=e}},z=class extends Error{name=`WorkspaceBindingError`;kind;constructor(e,t){super(t),this.kind=e}};const Ke=e=>{let t=`npx @flyle/ai-cx-mcp@latest login --tenant ${e.tenantName}`;return e.baseUrl.href===new URL(`https://public-api.nexus.flyle.io`).href||!e.baseUrlVerified?t:`${t} --api-base-url ${e.baseUrl.href}`},qe=e=>`ログインが必要です(ログインの期限切れや切断のほか、テナント設定で外部ツールの接続が許可されなくなった場合もこの状態になります)。作業ディレクトリで \`${Ke(e)}\` を実行してください。ログインできない場合は、テナントの管理者に外部ツールの接続が許可されているか確認してください`;var Je=class extends Error{name=`InvalidGrantError`},B=class extends Error{name=`CliError`};const Ye=`.flyle-ai-cx-mcp`,Xe=/* @__PURE__ */ new Set([`node_modules`,`.git`,Ye]),Ze=/* @__PURE__ */ k({tenantName:/* @__PURE__ */ A(),apiBaseUrl:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ Te())}),Qe=e=>v.join(e,Ye),$e=e=>v.join(Qe(e),`workspace.json`),V=e=>e instanceof Error&&b(e,`code`)?e.code:null,et=async e=>{let t;try{t=await p($e(e),`utf8`)}catch(e){if(V(e)===`ENOENT`)return null;throw e}let n;try{n=JSON.parse(t)}catch{n=null}let r=/* @__PURE__ */ M(Ze,n);if(!r.success)throw new z(`corrupted`,`${$e(e)} の内容が正しくありません。MCP サーバーはこのファイルを上書きしません。中身を確かめ、心当たりが無ければ ${Ye} ごと削除してから login し直してください。`);return r.output},tt=async e=>{try{return await et(e)}catch(t){if(t instanceof z)throw t;let n=V(t);throw new z(`unreadable`,`${Qe(e)} を確認できません(${typeof n==`string`?n:`unknown`})。他のテナントの作業ディレクトリと入れ子になっていないかを確かめるため、このディレクトリを読めない間は起動しません。${Qe(e)} の権限を見直すか、心当たりが無ければ削除してください。`)}},nt=e=>`このディレクトリでまだ一度もログインに成功していない(打ち間違えた)場合は、${Qe(e)} を削除してから login し直してください(保存した結果の downloads も消えます)。`,rt=(e,t,n)=>new z(`tenant_mismatch`,`${e} はテナント「${t}」専用の作業ディレクトリなので、テナント「${n}」には使えません。テナントごとに別のディレクトリを作り、そこで Claude Code のセッションを始めてください。`+nt(e)),it=(e,t,n)=>new z(`environment_mismatch`,`${e} は環境 ${new URL(t).host} 専用の作業ディレクトリなので、環境 ${new URL(n).host} には使えません。環境ごとに別のディレクトリを作ってください。`+nt(e)),at=(e,t,n)=>{if(t.tenantName!==n.tenantName)throw rt(e,t.tenantName,n.tenantName);if(t.apiBaseUrl!==n.apiBaseUrl)throw it(e,t.apiBaseUrl,n.apiBaseUrl)},ot=(e,t,n)=>new z(`nested_workspace`,`${e} の中に、別の接続先(テナント「${n}」)の作業ディレクトリ ${t} があります。別のテナントの作業ディレクトリを含む場所は作業ディレクトリにできません。重ならない別のディレクトリを作り、そこでセッションを始めてください。`),st=e=>{let t=[],n=v.dirname(e);for(;n!==v.dirname(n);)t.push(n),n=v.dirname(n);return t.push(n),t},ct=(e,t)=>a(`sha256`).update(`flyle-ai-cx-mcp/workspace-id/v2\0${e.username}\0${t}`).digest(`base64url`).slice(0,32),lt=(e,t)=>a(`sha256`).update(`${e.hostname}\0${e.username}\0${t}`).digest(`base64url`).slice(0,32),ut=(e,t)=>({root:t,workspaceId:ct(e,t),legacyWorkspaceId:lt(e,t)}),dt=(e,t)=>{let n={version:1,tenantName:e.tenantName,apiBaseUrl:e.apiBaseUrl,boundAt:t.toISOString()};return`${JSON.stringify(n,null,2)}\n`},ft=e=>new z(`corrupted`,`${e} がシンボリックリンク、またはディレクトリではありません。作業ディレクトリの外へテナントのデータを書き出さないよう、MCP サーバーはこれを使いません。心当たりが無ければ ${e} を削除してから login し直してください。`),pt=async e=>{let t=Qe(e);await d(t,{mode:448}).catch(e=>{if(V(e)!==`EEXIST`)throw e});let n=await u(t);if(n.isSymbolicLink()||!n.isDirectory())throw ft(t);return t},mt=async e=>{let t=v.join(e,`.gitignore`);if((await u(t).catch(e=>{if(V(e)===`ENOENT`)return null;throw e}))?.isFile()===!0&&await p(t,`utf8`)===`*
|
|
28
28
|
`)return;let n=`${t}.${o(8).toString(`hex`)}.tmp`;try{let e=await f(n,`wx`);try{await e.writeFile(`*
|
|
29
|
-
`)}finally{await e.close()}await ee(n,t)}catch(e){throw await g(n,{force:!0}).catch(w),e}},ht=async(e,t,n)=>{let r=await pt(e);await mt(r);try{await te($e(e),dt(t,n),{flag:`wx`});return}catch(e){if(V(e)!==`EEXIST`)throw e}let i=await et(e);if(i==null)throw rt(e,`(unknown)`,t.tenantName);at(e,i,t)},gt=e=>new z(`shared_directory`,`${e} はさまざまな作業で共有される場所なので、1 つのテナント専用にできません。このテナント用のディレクトリ(例: ~/flyle-ai-cx/<テナント名>)を作り、そこでセッションを始めてください。`),_t=async e=>{let t=await h(e.cwd),n=await h(e.homeDir).catch(()=>e.homeDir),r=[t,...st(t)];return{cwd:t,home:n,bindings:await Promise.all(r.map(async e=>({dir:e,binding:e===t?await et(e):await tt(e)})))}},vt=(e,t)=>e===t||e===_.parse(e).root,yt=e=>{let t=e.bindings.find(e=>e.binding!=null),n=t?.dir??e.cwd;if(vt(n,e.home))throw gt(n);return{root:n,binding:t?.binding??null}},bt=(e,t,n)=>{let r=e.bindings.findIndex(e=>e.dir===t);for(let{dir:t,binding:i}of e.bindings.slice(r+1))i!=null&&at(t,i,n)},xt=e=>new z(`nested_workspace`,`${e} の中のディレクトリが多すぎて、別のテナントの作業ディレクトリが入っていないかを確かめきれません。このテナント専用の空のディレクトリ(例: ~/flyle-ai-cx/<テナント名>)を作り、そこでセッションを始めてください。`),St=async e=>{try{return await m(e,{withFileTypes:!0})}catch(e){let t=V(e);if(t===`EACCES`||t===`EPERM`||t===`ENOENT`)return[];throw e}},Ct=async(e,t)=>{let n=[e],r=0,i=0;for(;n.length>0;){let a=await Promise.all(n.map(async e=>({dir:e,entries:await St(e)}))),o=await Promise.all(a.filter(({dir:t,entries:n})=>t!==e&&n.some(e=>e.name===`.flyle-ai-cx-mcp`)).map(async({dir:e})=>({dir:e,binding:await tt(e)})));for(let{dir:n,binding:r}of o)if(r!=null&&(r.tenantName!==t.tenantName||r.apiBaseUrl!==t.apiBaseUrl))throw ot(e,n,r.tenantName);if(i>=6)return;if(n=a.flatMap(({dir:e,entries:t})=>t.filter(e=>e.isDirectory()&&!Xe.has(e.name)).map(t=>_.join(e,t.name))),r+=n.length,r>5e3)throw xt(e);i+=1}},wt=async(e,t)=>{let n=await _t(e),{root:r}=yt(n);return bt(n,r,t),await Ct(r,t),await ht(r,t,e.now()),{...t,...ut(e,r)}},Tt=async e=>yt(await _t(e)).binding,Et=async e=>ut(e,yt(await _t(e)).root),Dt=async e=>{let t=await _t(e),{root:n,binding:r}=yt(t);return r==null?null:(bt(t,n,r),{...r,...ut(e,n)})},Ot=async(e,t)=>{await ht(e.root,e,t)},kt={allowInsecureHttp:`FLYLE_AI_CX_MCP_ALLOW_INSECURE_HTTP`,noBrowser:`FLYLE_AI_CX_MCP_NO_BROWSER`},At=/* @__PURE__ */ new Set([`localhost`,`127.0.0.1`,`[::1]`]),jt=e=>{let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)},Mt=e=>At.has(e),Nt=(e,t,n)=>{let r;try{r=new URL(e)}catch{throw new L(`${n} が URL として正しくありません。`)}if(r.search!==``||r.hash!==``||r.username!==``||r.password!==``)throw new L(`${n} にクエリ(?)・フラグメント(#)・認証情報を含めないでください。`);let i=r.protocol===`http:`&&t&&Mt(r.hostname);if(r.protocol!==`https:`&&!i)throw new L(`${n} は https の URL を指定してください(http はローカル開発で ${kt.allowInsecureHttp}=1 を付けたときの localhost だけ使えます)。`);let a=jt(r.pathname);return new URL(`${r.origin}${a}`)},Pt=e=>e===`1`||e===`true`,Ft=e=>e.length>=2&&e.length<=32&&He.test(e),It=(e,t)=>{if(!Ft(e))throw new L(`${t} がテナント名として正しくありません。英小文字・数字・ハイフンで 2〜32 文字のテナント名を指定してください。`);return e},Lt=e=>Pt(e[kt.allowInsecureHttp]),Rt=e=>Pt(e[kt.noBrowser]),H=e=>e.host,zt=(e,t,n)=>{let r=Lt(e);return{baseUrl:Nt(n.apiBaseUrl,r,`作業ディレクトリの接続先`),tenantName:It(n.tenantName,`作業ディレクトリのテナント`),outputDir:_.resolve(t,Ye,`downloads`),allowInsecureHttp:r}},Bt=`flyle-ai-cx-mcp`,Vt=`credentials`,Ht=()=>o(8).toString(`hex`),Ut=/* @__PURE__ */ Me({version:/* @__PURE__ */ ke(1),apiBaseUrl:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ Te()),tenantName:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ xe(Ft)),loginConnectionId:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(Ve)),accessToken:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(ze)),accessTokenExpiresAt:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ D()),refreshToken:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(Be)),refreshTokenExpiresAt:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ D())}),Wt=({platform:e,env:t,homeDir:n})=>{let r=t.XDG_CONFIG_HOME;if(r!=null&&_.isAbsolute(r))return _.join(r,Bt,Vt);let i=t.APPDATA;return e===`win32`&&i!=null&&_.isAbsolute(i)?_.join(i,Bt,Vt):_.join(n,`.config`,Bt,Vt)},Gt=(e,t)=>_.join(e,`${t}.json`),U=e=>e instanceof Error&&y(e,`code`)?e.code:null,Kt=async(e,t)=>{let n=Gt(e,t.workspaceId),r=Gt(e,t.legacyWorkspaceId);try{await l(r,n)}catch(e){let t=U(e);if(t===`ENOENT`||t===`EEXIST`)return n;throw e}return await g(r,{force:!0}),n},qt=async e=>{let t;try{t=await p(e,`utf8`)}catch(e){if(U(e)===`ENOENT`)return null;throw e}let n;try{n=JSON.parse(t)}catch{n=null}let r=/* @__PURE__ */ Fe(Ut,n);if(!r.success)throw new P(`login_required`,`保存されたログイン情報(${e})を読めません。`);return r.output},Jt=async e=>{await d(e,{recursive:!0,mode:448}),await c(e,448)},Yt=async(e,t)=>{await Jt(_.dirname(e));let n={version:1,...t},r=`${e}.${Ht()}.tmp`;try{let t=await f(r,`wx`,384);try{await t.writeFile(`${JSON.stringify(n,null,2)}\n`)}finally{await t.close()}await ee(r,e)}catch(e){throw await g(r,{force:!0}).catch(w),e}},Xt=async e=>{await g(e,{force:!0})},Zt=(e,t)=>({staleMs:6e4,acquireTimeoutMs:9e4,retryIntervalMs:100,now:e,sleep:t}),Qt=async e=>{let t;try{t=await f(e,`r`)}catch(e){if(U(e)===`ENOENT`)return null;throw e}try{let[e,n]=await Promise.all([t.readFile(`utf8`),t.stat()]);return{owner:e,mtimeMs:n.mtimeMs}}finally{await t.close()}},$t=async(e,t)=>{let n=`${e}.${Ht()}.tmp`,r=await f(n,`wx`,384);try{await r.writeFile(t)}finally{await r.close()}try{return await l(n,e),!0}catch(e){if(U(e)===`EEXIST`)return!1;throw e}finally{await g(n,{force:!0})}},en=async(e,t)=>{let n=`${e}.${Ht()}.aside`;try{await ee(e,n)}catch(e){if(U(e)===`ENOENT`)return!1;throw e}return await p(n,`utf8`)===t?(await g(n,{force:!0}),!0):(await l(n,e).catch(e=>{if(U(e)!==`EEXIST`)throw e}),await g(n,{force:!0}),!1)},tn=async(e,t,n)=>{let r=`${e}.guard`,i=Ht(),a=t.now()+t.acquireTimeoutMs;for(;!await $t(r,i);){let n=await Qt(r);if(n!=null){if(t.now()-n.mtimeMs>=t.staleMs)await en(r,n.owner);else{if(t.now()>=a)throw Error(`ログイン情報のロック(${e})を取得できませんでした。別の MCP プロセスが更新中です。しばらくしてから再実行してください`);await t.sleep(t.retryIntervalMs)}}}try{return await n()}finally{await en(r,i)}},nn=(e,t,n)=>tn(e,n,async()=>(await Qt(e))?.owner===t&&(await g(e,{force:!0}),!0)),rn=(e,t)=>tn(e,t,async()=>{let n=await Qt(e);return n==null?!0:t.now()-n.mtimeMs<t.staleMs?!1:(await g(e,{force:!0}),!0)}),an=async(e,t,n)=>{await Jt(_.dirname(e));let r=`${e}.lock`,i=Ht(),a=t.now()+t.acquireTimeoutMs;for(;!await $t(r,i);)if(!await rn(r,t)){if(t.now()>=a)throw Error(`ログイン情報のロック(${r})を取得できませんでした。別の MCP プロセスが更新中です。しばらくしてから再実行してください`);await t.sleep(t.retryIntervalMs)}try{return await n()}finally{await nn(r,i,t).catch(w)}},on=`application/json`,sn=`x-request-id`,cn=(e,t)=>{if(e.origin!==t.origin)throw new I(`request_refused`,`refusing to send credentials outside the configured API origin`)},ln=e=>{let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)},un=(e,t)=>{let n=`${ln(e.pathname)}${t.path}`,r=new URL(n,e);if(r.pathname!==n)throw new I(`request_refused`,`refusing to send a request whose path was normalized`);for(let[e,n]of t.query)r.searchParams.append(e,n);return cn(r,e),r},dn=async(e,t)=>{let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw await e.body?.cancel().catch(w),new I(`response_too_large`,`response exceeds ${t} bytes`,e.status);if(e.body==null)return/* @__PURE__ */ new Uint8Array;let r=e.body.getReader(),i=[],a=0;for(;;){let{done:n,value:o}=await r.read();if(n)break;if(a+=o.byteLength,a>t)throw await r.cancel().catch(w),new I(`response_too_large`,`response exceeds ${t} bytes`,e.status);i.push(o)}let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return o},fn=e=>new TextDecoder(`utf-8`).decode(e),pn=(e,t)=>(e.headers.get(`content-type`)??``).toLowerCase().startsWith(t),mn=e=>{if(e==null)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null},hn=(e,t)=>{let n=e[t];return typeof n==`string`?n:null},gn=e=>typeof e==`object`&&!!e&&!Array.isArray(e),_n=e=>{let t=e.issues;return Array.isArray(t)?t.filter(e=>gn(e)):null},vn=async(e,t)=>{let n=e.headers.get(sn),r=mn(e.headers.get(`retry-after`)),i;try{i=fn(await dn(e,t))}catch{i=``}if(pn(e,on))try{let t=JSON.parse(i),a=gn(t)&&gn(t.error)?t.error:null;if(a!=null)return new F({status:e.status,code:hn(a,`code`),message:hn(a,`message`)??e.statusText,detail:hn(a,`detail`),issues:_n(a),requestId:hn(a,`requestId`)??n,retryAfterSeconds:r})}catch{}return new F({status:e.status,code:null,message:i.slice(0,500)||e.statusText||`HTTP error`,detail:null,issues:null,requestId:n,retryAfterSeconds:r})},yn=e=>e instanceof I?e:e instanceof Error&&e.name===`AbortError`?new I(`timeout`,`the API did not respond in time`):new I(`network`,e instanceof Error?e.message:`network failure`),bn=(e,t,n)=>{let r=e.getReader(),i=!1,a=async()=>{i||(i=!0,await r.cancel().catch(w))};return{chunks:async function*(){let e=setTimeout(()=>t.abort(),n);try{for(;;){let{done:a,value:o}=await r.read();if(a){i=!0;return}clearTimeout(e),e=setTimeout(()=>t.abort(),n),yield o}}catch(e){throw i=!0,yn(e)}finally{clearTimeout(e),await a()}}(),cancel:a}},xn=(e,t)=>{let{baseUrl:n,auth:r,fetch:i,sleep:a,logger:o}=e,s=async(r,a)=>{let o=un(n,r),s=new Headers({...e.headers,accept:on});a!=null&&s.set(`authorization`,`Bearer ${a}`);let c;r.hasBody&&(c=JSON.stringify(r.body??{}),s.set(`content-type`,on));let l=new AbortController,u=setTimeout(()=>l.abort(),t.headersTimeoutMs),d;try{d=await i(o,{method:r.method,headers:s,...c==null?{}:{body:c},redirect:`manual`,signal:l.signal})}catch(e){throw clearTimeout(u),yn(e)}if(d.status>=300&&d.status<400)throw clearTimeout(u),await d.body?.cancel().catch(w),new I(`redirect_not_followed`,`redirect responses are not followed`,d.status);if(!d.ok)try{throw await vn(d,t.maxJsonBytes)}finally{clearTimeout(u)}let f=d.headers.get(sn);switch(r.responseKind){case`json`:try{if(!pn(d,on))throw await d.body?.cancel().catch(w),new I(`unexpected_content_type`,`expected an application/json response`,d.status);let e=fn(await dn(d,t.maxJsonBytes)),n;try{n=JSON.parse(e)}catch{throw new I(`invalid_json`,`the response body is not valid JSON`,d.status)}return{kind:`json`,status:d.status,requestId:f,body:n}}catch(e){throw yn(e)}finally{clearTimeout(u)}case`empty`:return clearTimeout(u),await d.body?.cancel().catch(w),{kind:`empty`,status:d.status,requestId:f};case`file`:if(clearTimeout(u),!pn(d,on)||d.body==null)throw await d.body?.cancel().catch(w),new I(`unexpected_content_type`,`expected an application/json file response`,d.status);return{kind:`file`,status:d.status,requestId:f,...bn(d.body,l,t.downloadIdleTimeoutMs)};default:throw r.responseKind,Error(`unknown response kind ${String(r.responseKind)}`)}},c=async(e,n)=>{let r=e.method===`GET`;try{return await s(e,n)}catch(i){if(!r)throw i;if(i instanceof F&&i.info.status===429&&i.info.retryAfterSeconds!=null&&i.info.retryAfterSeconds<=t.maxRetryAfterSeconds)return o.warn(`rate limited; retrying once`,{path:e.path,retryAfterSeconds:i.info.retryAfterSeconds}),await a(i.info.retryAfterSeconds*1e3),await s(e,n);if(i instanceof I&&i.kind===`network`)return o.warn(`network failure; retrying once`,{path:e.path}),await s(e,n);throw i}};return{request:async e=>{if(r==null)return c(e,null);let t=await r.getAccessToken();try{return await c(e,t)}catch(n){if(!(n instanceof F)||n.info.status!==401)throw n;let i=await r.refreshAfterRejection(t);if(i===t)throw n;return o.warn(`access token rejected; retrying once with a refreshed token`,{path:e.path}),await c(e,i)}}}},Sn={headersTimeoutMs:6e4,maxJsonBytes:16777216,maxRetryAfterSeconds:30,downloadIdleTimeoutMs:6e4},Cn=(e,t=Sn)=>xn({baseUrl:e.config.baseUrl,auth:e.auth,headers:{"user-agent":`flyle-ai-cx-mcp/${Ie}`,"x-flyle-client-workspace":e.workspaceId},fetch:e.fetch,sleep:e.sleep,logger:e.logger},t),wn=`{tenantName}`,Tn={...Sn,headersTimeoutMs:2e4},En=/* @__PURE__ */ k({authorizationUrlTemplate:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ Se(wn))}),Dn=/* @__PURE__ */ k({accessToken:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(ze)),accessTokenExpiresAt:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ D()),refreshToken:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(Be)),refreshTokenExpiresAt:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ D()),tenantName:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ xe(Ft)),loginConnectionId:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(Ve))}),On=(e,t,n)=>{let r=/* @__PURE__ */ Fe(e,t);if(!r.success)throw new I(`invalid_json`,`the login connection response does not match the contract`,n);return r.output},kn=async e=>{let t=await e.request({method:`GET`,path:`/v0/login-connections/metadata`,query:[],hasBody:!1,body:null,responseKind:`json`});if(t.kind!==`json`)throw new I(`unexpected_content_type`,`not JSON`);return On(En,t.body,t.status).authorizationUrlTemplate},An=async(e,t)=>{let n;try{n=await e.request({method:`POST`,path:`/v0/login-connections/token`,query:[],hasBody:!0,body:t,responseKind:`json`})}catch(e){throw e instanceof F&&e.info.code===`invalid_grant`?new Je(`the authorization code or refresh token is no longer valid`):e}if(n.kind!==`json`)throw new I(`unexpected_content_type`,`not JSON`);return On(Dn,n.body,n.status)},jn=(e,t,n)=>{if(e.apiBaseUrl===t.href&&e.tenantName===n)return;let r=Ke({tenantName:n,baseUrl:t,baseUrlVerified:e.apiBaseUrl===t.href});throw new P(`credentials_mismatch`,`保存されたログイン(環境 ${H(new URL(e.apiBaseUrl))} / テナント ${e.tenantName})が、この作業ディレクトリの接続先(環境 ${H(t)} / テナント ${n})と一致しません。この作業ディレクトリで \`${r}\` を実行し直してください`)},Mn=(e,t)=>({apiBaseUrl:t.href,tenantName:e.tenantName,loginConnectionId:e.loginConnectionId,accessToken:e.accessToken,accessTokenExpiresAt:e.accessTokenExpiresAt,refreshToken:e.refreshToken,refreshTokenExpiresAt:e.refreshTokenExpiresAt}),Nn=e=>{let{credentialsFile:t,baseUrl:n,tenantName:r,tokenClient:i,now:a}=e,o=null,s=null,c=[],l=!1,u=(...e)=>{c.push(...e),c.splice(0,Math.max(0,c.length-8))},d=()=>qe({tenantName:r,baseUrl:n,baseUrlVerified:l}),f=()=>new P(`login_required`,d()),p=async()=>{let e;try{e=await qt(t)}catch(e){throw e instanceof P?new P(`login_required`,`${e.message}${d()}`):e}if(e?.apiBaseUrl===n.href&&(l=!0),e==null||Date.parse(e.refreshTokenExpiresAt)<=a())throw f();return jn(e,n,r),e},m=e=>e-a()>6e4,h=async e=>{try{await Yt(t,e)}catch{try{await Yt(t,e)}catch{await Xt(t)}}},ee=a=>an(t,e.lock,async()=>{let e=await p();u(e.accessToken,e.refreshToken);let s=Date.parse(e.accessTokenExpiresAt);if(e.accessToken!==a&&m(s))return o={token:e.accessToken,expiresAt:s},e.accessToken;let c;try{c=await An(i,{grant_type:`refresh_token`,refresh_token:e.refreshToken})}catch(e){throw e instanceof Je?(await Xt(t),f()):e}if(u(c.accessToken,c.refreshToken),c.tenantName!==r)throw await Xt(t),new P(`login_required`,`ログインの更新で、設定と違うテナント(${c.tenantName})の応答を受け取ったため、保存したログイン情報を破棄しました。${d()}`);if(c.loginConnectionId!==e.loginConnectionId)throw await Xt(t),new P(`login_required`,`ログインの更新で、保存したログインと違う接続の応答を受け取ったため、保存したログイン情報を破棄しました。${d()}`);return o={token:c.accessToken,expiresAt:Date.parse(c.accessTokenExpiresAt)},await h(Mn(c,n)),c.accessToken}),g=e=>(s??=ee(e).finally(()=>{s=null}),s);return{getAccessToken:()=>o!=null&&m(o.expiresAt)?Promise.resolve(o.token):g(o?.token??null),refreshAfterRejection:e=>o!=null&&o.token!==e?Promise.resolve(o.token):(o=null,g(e)),assertLoggedIn:async()=>{o??await p()},secrets:()=>c,whenIdle:async()=>{await Promise.allSettled(s==null?[]:[s])}}},Pn=(e,t)=>e===`darwin`?[`open`,[t]]:e===`win32`?[`rundll32`,[`url.dll,FileProtocolHandler`,t]]:[`xdg-open`,[t]],Fn=(e,t=process.platform)=>{let[n,r]=Pn(t,e),i=ne(n,r,{stdio:`ignore`,detached:!0,shell:!1});i.on(`error`,w),i.unref()},In=(e,t,n)=>Cn({config:{baseUrl:t},auth:null,workspaceId:n,fetch:e.fetch,sleep:e.sleep,logger:e.logger},Tn),Ln=e=>e==null?"作業ディレクトリで `npx @flyle/ai-cx-mcp@latest login --tenant <テナント名>` を実行し直してください":qe({tenantName:e.tenantName,baseUrl:new URL(e.apiBaseUrl),baseUrlVerified:!1}),Rn=async(e,t,n)=>{let r=await Kt(e.credentialsDir,t),i;try{i=await qt(r)}catch(e){throw e instanceof P?new P(`login_required`,`${e.message}${Ln(n)}`):e}if(i==null)return null;let a=Nt(i.apiBaseUrl,Lt(e.env),`${r} の apiBaseUrl`);return{workspace:{...t,...n??{tenantName:i.tenantName,apiBaseUrl:a.href}},file:r,stored:i,baseUrl:a}},zn=async e=>{let t=await Dt(e.workspaceEnv);return t==null?null:Rn(e,t,t)},Bn=async e=>Rn(e,await Et(e.workspaceEnv),null),Vn=(e,t)=>{let n=Nn({credentialsFile:t.file,baseUrl:t.baseUrl,tenantName:t.stored.tenantName,tokenClient:In(e,t.baseUrl,t.workspace.workspaceId),now:e.now,lock:e.lock});return{auth:n,client:Cn({config:{baseUrl:t.baseUrl},auth:n,workspaceId:t.workspace.workspaceId,fetch:e.fetch,sleep:e.sleep,logger:e.logger})}},Hn=(e,t)=>`/v0/tenants/${encodeURIComponent(e)}${t}`,W=e=>e instanceof B||e instanceof P||e instanceof L||e instanceof z?e.message:e instanceof F?`公開 API がエラーを返しました(${String(e.info.status)} ${e.info.code??`http_error`}): ${e.info.message}`:e instanceof I?`公開 API と通信できませんでした(${e.kind}): ${e.message}`:e instanceof Error?e.message:String(e),Un=`tenantName`,G=(e,t)=>{let n=e;for(let e of t)e.length!==0&&(n=n.split(e).join(`[redacted]`));return n},Wn=async(e,t)=>{let{client:n}=Vn(e,t);try{return await n.request({method:`DELETE`,path:Hn(t.stored.tenantName,`/current-login-connection`),query:[],hasBody:!1,body:null,responseKind:`empty`}),`revoked`}catch(e){if(!(e instanceof P&&e.kind===`login_required`||e instanceof F&&e.info.status===401))throw e;return`unconfirmed`}},Gn=async e=>{let t=await Bn(e);if(t==null){e.out(`この作業ディレクトリにはログイン情報がありません。`);return}let n=await Wn(e,t);await an(t.file,e.lock,()=>Xt(t.file)),e.out(`ログアウトしました(環境 ${H(t.baseUrl)} / テナント ${t.stored.tenantName})。`),n===`unconfirmed`&&e.err(`サーバー側で接続を切断できたか確認できませんでした。接続が残っている場合は、Flyle AI CX の「設定」>「外部ツール接続」から切断してください。`)},Kn=`127.0.0.1`,qn=`/callback`,Jn=e=>{try{let{values:t}=ie({args:[...e],options:{tenant:{type:`string`},"api-base-url":{type:`string`}},strict:!0,allowPositionals:!1});return{tenant:t.tenant??null,apiBaseUrl:t[`api-base-url`]??null}}catch(e){throw new B(`${e instanceof Error?e.message:String(e)}\n使い方: login [--tenant <テナント名>] [--api-base-url <URL>]`)}},Yn=async e=>{try{return await Bn(e)}catch{return null}},Xn=async(e,t,n,r)=>{if(t!=null)return Nt(t,r,`--api-base-url`);let i=Nt(Le,r,`既定の接続先`);if(n==null)return i;let a=Nt(n.apiBaseUrl,r,`作業ディレクトリの接続先`);if(a.href===i.href||(await Yn(e))?.baseUrl.href===a.href)return a;throw new B(`この作業ディレクトリは既定以外の接続先(${a.host})に束縛されています。その接続先が正しいことを確かめたうえで \`login --api-base-url <URL>\` で明示してください。心当たりが無ければ、このディレクトリの ${Ye} は他人が置いたものかもしれません。`)},Zn=async(e,t,n)=>{let r=new URL(Le);if(t.href!==r.href&&!(n&&t.protocol===`http:`&&Mt(t.hostname))&&(await Yn(e))?.baseUrl.href!==t.href&&!await e.confirm(`接続先 ${t.host} は Flyle AI CX の本番の接続先(${r.host})ではありません。ログインすると、この接続先へ認可コードを送ります。Flyle から案内された接続先で間違いなければ y を入力してください [y/N]: `))throw new B(`接続先 ${t.host} へのログインを中止しました。本番以外の接続先へは、対話できる端末で login を実行し、接続先を確かめて y を入力したときだけログインします。`)},Qn=(e,t)=>{if(e!=null)return It(e,`--tenant`);if(t!=null)return t.tenantName;throw new B("テナントを決められません。`login --tenant <テナント名>` で指定してください(作業ディレクトリをそのテナント専用にします)。")},$n=()=>o(32).toString(`base64url`),er=e=>a(`sha256`).update(e).digest(`base64url`),tr=(e,t)=>{let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&s(n,r)},nr=(e,t,n)=>{let r;try{r=new URL(e.replaceAll(wn,t))}catch{throw new B(`公開 API が返した同意画面の URL が不正です。`)}let i=r.protocol===`http:`&&n&&(Mt(r.hostname)||r.hostname.endsWith(`.localhost`));if(r.protocol!==`https:`&&!i)throw new B(`公開 API が返した同意画面の URL が https ではありません。`);return r},rr=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Co}]/gu,ir=(e,t)=>{let n=``;for(let r of e){if(n.length+r.length>t)break;n+=r}return n},ar=(e,t)=>{let n=e=>e.replaceAll(rr,``);return ir(`${n(e)} / ${n(_.basename(t))}`,255)},or=/* @__PURE__ */ Pe([/* @__PURE__ */ k({error:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(/^[a-z_]{1,64}$/)),state:/* @__PURE__ */ A()}),/* @__PURE__ */ k({code:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(Re)),state:/* @__PURE__ */ A()})]),sr={success:`ログインが完了しました。このタブは閉じてかまいません。`,denied:`ログインを中止しました。このタブは閉じてかまいません。`,failure:`ログインを完了できませんでした。このタブを閉じて、ターミナルの表示を確認してください。`,handled:`このログインは処理済みです。このタブは閉じてかまいません。`,unknown:`実行中のログインの応答として確認できませんでした。ログインを続ける場合は、ターミナルに表示された URL から同意画面を開き直してください。`,rejected:`この宛先への要求は受け付けていません。`},cr=(e,t,n)=>{e.writeHead(t,{"content-type":`text/html; charset=utf-8`,"cache-control":`no-store`,"content-security-policy":`default-src 'none'`,"referrer-policy":`no-referrer`}),e.end(`<!doctype html><html lang="ja"><meta charset="utf-8"><title>Flyle AI CX</title><p>${sr[n]}</p></html>`)},lr=e=>new Promise((t,n)=>{e.once(`error`,n),e.listen(0,Kn,()=>{let r=e.address();r==null||typeof r==`string`?n(new B(`ログイン用の待受ポートを開けませんでした。`)):t(r.port)})}),ur=async(e,t,n)=>{let r=!1,i=0,a=null,o=Promise.withResolvers(),s=e=>{r=!0,o.reject(new B(e))},c=(e,t,r)=>{i+=1,cr(e,400,t),n(r)},l=re((t,n)=>{if(a==null||t.headers.host!==a){c(n,`rejected`,`ログイン用の待受に、想定外の宛先(Host ヘッダ)の要求が届いたため拒否しました。ログインは待ち続けています。`);return}let i=new URL(t.url??`/`,`http://${a}`);if(t.method!==`GET`||i.pathname!==qn){n.writeHead(404).end();return}if(r){cr(n,410,`handled`);return}let l=i.searchParams.get(`state`);if(l==null||!tr(l,e)){c(n,`unknown`,`このログインのものではない応答(state が一致しない、または無い)を受け取ったため無視しました。ブラウザで同意を続けてください。`);return}let u=/* @__PURE__ */ Fe(or,S(i.searchParams));if(!u.success){cr(n,400,`failure`),s(`同意画面からの応答の形式が正しくありません(認可コードがない、または形式が違います)。もう一度 login を実行してください。`);return}let d=u.output;if(y(d,`error`)){let e=d.error===`access_denied`;cr(n,200,e?`denied`:`failure`),s(e?`ブラウザでログインが拒否されました。`:`同意画面がエラーを返しました(${d.error})。`);return}r=!0;let f=!1;o.resolve({code:d.code,finish:e=>{f||(f=!0,cr(n,e===`success`?200:400,e))}})}),u=await lr(l);a=`${Kn}:${String(u)}`;let d=setTimeout(()=>{if(r)return;let e=i===0?``:`(このログインのものではない要求を ${String(i)} 件受け取り、無視しました)`;s(`${String(Math.round(t/1e3/60))} 分以内にブラウザでの同意が完了しませんでした${e}。もう一度 login を実行してください。`)},t);return{port:u,received:o.promise,close:()=>new Promise(e=>{clearTimeout(d),l.closeAllConnections(),l.close(()=>e())})}},dr=`その接続は最長 30 日間有効なまま残る可能性があります。管理画面の「設定」>「外部ツール接続」から切断してください。`,fr=async(e,t)=>{if(t!=null)try{await Wn(e,t)}catch(n){e.err(`以前のログイン(接続 ID ${t.stored.loginConnectionId})をサーバーで切断できませんでした(${W(n)})。${dr}`)}},pr=async e=>{try{return await zn(e)}catch(t){if(!(t instanceof P&&t.kind===`login_required`)&&!(t instanceof L))throw t;return e.err(`以前のログイン情報を読めなかったため、新しいログインで上書きします(${W(t)})。以前の接続はサーバーで切断できていません。${dr}`),null}},mr=async(e,t,n,r)=>{let i=Gt(e.credentialsDir,t.workspaceId);await an(i,e.lock,()=>Yt(i,Mn(r,n)))},hr=e=>({getAccessToken:()=>Promise.resolve(e),refreshAfterRejection:()=>Promise.resolve(e),assertLoggedIn:()=>Promise.resolve(),secrets:()=>[e]}),gr=async(e,t,n,r)=>{let i=Cn({config:{baseUrl:t},auth:hr(r.accessToken),workspaceId:n.workspaceId,fetch:e.fetch,sleep:e.sleep,logger:e.logger});try{return await i.request({method:`DELETE`,path:Hn(r.tenantName,`/current-login-connection`),query:[],hasBody:!1,body:null,responseKind:`empty`}),!0}catch{return!1}},_r=async e=>{let t=Jn(e.argv),n=Lt(e.env),r=await Tt(e.workspaceEnv),i=await Xn(e,t.apiBaseUrl,r,n),a=Qn(t.tenant,r);await Zn(e,i,n);let o=await wt(e.workspaceEnv,{tenantName:a,apiBaseUrl:i.href}),s=await pr(e),c=In(e,i,o.workspaceId),l=nr(await kn(c),a,n),u=$n(),d=$n(),f=[u,d],p=await ur(d,e.callbackTimeoutMs,e.err),m=null;try{let t=`http://${Kn}:${String(p.port)}${qn}`;l.searchParams.set(`tenant_name`,a),l.searchParams.set(`code_challenge`,er(u)),l.searchParams.set(`code_challenge_method`,`S256`),l.searchParams.set(`redirect_uri`,t),l.searchParams.set(`state`,d),l.searchParams.set(`connection_name`,ar(e.workspaceEnv.hostname,o.root)),e.err(`環境 ${H(i)} のテナント「${a}」にログインします。ブラウザで同意画面を開きます。\n開かない場合は、次の URL をブラウザで開いてください:\n${l.href}`),e.openBrowser(l.href),m=await p.received,f.push(m.code);let n;try{n=await An(c,{grant_type:`authorization_code`,code:m.code,code_verifier:u,redirect_uri:t})}catch(e){throw e instanceof Je?new B(`認可コードを交換できませんでした。もう一度 login を実行してください。`):e}if(f.push(n.accessToken,n.refreshToken),n.tenantName!==a){let t=await gr(e,i,o,n);throw new B(`ブラウザで同意したテナント(${n.tenantName})が、ログインしようとしたテナント(${a})と違います。ログイン情報は保存していません。`+(t?`そのテナントに作られた接続は切断しました。`:`テナント ${n.tenantName} の管理画面の「設定」>「外部ツール接続」から、作られた接続を切断してください。`))}try{await Ot(o,new Date(e.now())),await fr(e,s),await mr(e,o,i,n)}catch(t){let r=await gr(e,i,o,n);throw new B(`ログイン情報を保存できませんでした(${W(t)})。`+(r?`作った接続は切断しました。原因を取り除いてから、もう一度 login を実行してください。`:`作った接続を切断できませんでした。${dr}`))}m.finish(`success`),e.out(`ログインしました(環境 ${H(i)} / テナント ${a} / 作業ディレクトリ ${o.root})。`)}catch(e){throw m?.finish(`failure`),new B(G(W(e),f))}finally{await p.close()}},vr=/* @__PURE__ */ k({currentUser:/* @__PURE__ */ k({name:/* @__PURE__ */ A(),email:/* @__PURE__ */ A(),roles:/* @__PURE__ */ Oe(/* @__PURE__ */ k({roleName:/* @__PURE__ */ A()})),tenantName:/* @__PURE__ */ A(),currentLoginConnection:/* @__PURE__ */ k({name:/* @__PURE__ */ A(),expiresAt:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ D())})})}),yr=async e=>{let t=await Dt(e.workspaceEnv);return t==null?"ログインしていません。作業ディレクトリで `npx @flyle/ai-cx-mcp@latest login --tenant <テナント名>` を実行してください":`ログインしていません。作業ディレクトリで \`${Ke({tenantName:t.tenantName,baseUrl:new URL(t.apiBaseUrl),baseUrlVerified:!1})}\` を実行してください`},br=async e=>{let t=await zn(e);if(t==null)throw new B(await yr(e));e.out(`環境: ${H(t.baseUrl)}`),e.out(`テナント: ${t.stored.tenantName}`);let{client:n}=Vn(e,t),r;try{r=await n.request({method:`GET`,path:Hn(t.stored.tenantName,`/current-user`),query:[],hasBody:!1,body:null,responseKind:`json`})}catch(e){throw e instanceof P&&e.kind===`login_required`?new B(e.message):e}let i=/* @__PURE__ */ Fe(vr,r.kind===`json`?r.body:null);if(!i.success)throw new I(`invalid_json`,`the current user response does not match the contract`);let a=i.output.currentUser;if(a.tenantName!==t.stored.tenantName){let e=Ke({tenantName:t.workspace.tenantName,baseUrl:new URL(t.workspace.apiBaseUrl),baseUrlVerified:t.baseUrl.href===t.workspace.apiBaseUrl});throw new P(`credentials_mismatch`,`ログイン中のテナント(${a.tenantName})が、この作業ディレクトリのテナント(${t.stored.tenantName})と一致しません。この作業ディレクトリで \`${e}\` を実行し直してください`)}e.out(`ユーザー: ${a.name} <${a.email}>`),e.out(`ロール: ${a.roles.map(e=>e.roleName).join(`, `)||`(なし)`}`),e.out(`接続名: ${a.currentLoginConnection.name}`),e.out(`ログインの有効期限: ${a.currentLoginConnection.expiresAt}(使うたびに延長。ログインから最長 90 日)`)},xr=(e,t,n,r)=>{let i={level:e,message:t,...n,time:(/* @__PURE__ */ new Date()).toISOString()};return G(JSON.stringify(i),r)},Sr=(e,t=e=>console.error(e))=>({info:(n,r)=>t(xr(`info`,n,r,e())),warn:(n,r)=>t(xr(`warn`,n,r,e())),error:(n,r)=>t(xr(`error`,n,r,e()))}),Cr=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],wr=[`json`,`empty`,`file`],Tr=[`read`,`write`],Er=[`image/svg+xml`],K=(e,t)=>{throw new We(`${e}: ${t}`)},Dr=(e,t)=>C(e)?e:K(t,`expected an object`),Or=(e,t)=>typeof e==`string`?e:K(t,`expected a string`),kr=/^[a-z0-9]{1,8}$/,Ar=/^\w+$/,jr=e=>{let[t,...n]=e.split(`/`);return t===``&&n.length>=1&&n.length<=8&&n.every(e=>Ar.test(e))},Mr=(e,t)=>e==null?[]:Array.isArray(e)?e.map((e,n)=>{let r=Dr(e,`${t}[${n}]`),i=Or(r.pointer,`${t}[${n}].pointer`),a=Or(r.extension,`${t}[${n}].extension`),o=Er.find(e=>e===r.mediaType);return o==null?K(`${t}[${n}]`,`unsupported mediaType`):jr(i)?kr.test(a)?{pointer:i,mediaType:o,extension:a}:K(`${t}[${n}]`,`invalid extension`):K(`${t}[${n}]`,`invalid pointer`)}):K(t,`x-inline-artifacts must be an array`),q=e=>{throw new Ue(e)},J=e=>e===null,Nr=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),Pr=e=>typeof e==`string`&&Cr.some(t=>t===e),Fr=e=>typeof e==`string`&&wr.some(t=>t===e),Ir=e=>typeof e==`string`&&Tr.some(t=>t===e),Lr=(e,t)=>{if(!C(e))return q(`${t} must be an object`);let{value:n,summary:r,schema:i}=e;return typeof n!=`string`||typeof r!=`string`||!C(i)?q(`${t} is invalid`):{value:n,summary:r,schema:i}},Rr=(e,t)=>{if(!C(e))return q(`${t} must be an object`);let{path:n,discriminator:r,description:i,variants:a}=e;return typeof n!=`string`||typeof r!=`string`?q(`${t} is invalid`):!J(i)&&typeof i!=`string`?q(`${t}.description is invalid`):Array.isArray(a)?{path:n,discriminator:r,description:i,variants:a.map((e,n)=>Lr(e,`${t}.variants[${n}]`))}:q(`${t}.variants is invalid`)},zr=(e,t)=>{if(!C(e)||!y(e,`value`))return q(`${t} is invalid`);let{path:n}=e;return!J(n)&&typeof n!=`string`?q(`${t}.path is invalid`):{path:n,value:e.value}},Br=(e,t)=>{if(J(e))return null;if(!C(e))return q(`${t} is invalid`);let{groups:n,definitions:r,examples:i}=e;return!Array.isArray(n)||n.length===0?q(`${t}.groups is invalid`):C(r)?Array.isArray(i)?{groups:n.map((e,n)=>Rr(e,`${t}.groups[${n}]`)),definitions:r,examples:i.map((e,n)=>zr(e,`${t}.examples[${n}]`))}:q(`${t}.examples is invalid`):q(`${t}.definitions is invalid`)},Vr=(e,t)=>{let n=`operations[${t}]`;if(!C(e))return q(`${n} must be an object`);let{operationId:r,method:i,pathTemplate:a,summary:o,description:s,effect:c,responseKind:l,queryParams:u,bodyFields:d,wholeBodyField:f,inputSchema:p,fullInputSchema:m,inputDetails:h,inlineArtifacts:ee}=e;return typeof r!=`string`||r===``?q(`${n}.operationId is invalid`):Pr(i)?typeof a!=`string`||!a.startsWith(`/`)?q(`${n}.pathTemplate is invalid`):typeof o==`string`?!J(s)&&typeof s!=`string`?q(`${n}.description is invalid`):Ir(c)?Fr(l)?Nr(u)?!J(d)&&!Nr(d)?q(`${n}.bodyFields is invalid`):!J(f)&&typeof f!=`string`?q(`${n}.wholeBodyField is invalid`):d!=null&&f!=null?q(`${n} declares both bodyFields and wholeBodyField`):C(p)?C(m)?{operationId:r,method:i,pathTemplate:a,summary:o,description:s,effect:c,responseKind:l,queryParams:u,bodyFields:d,wholeBodyField:f,inputSchema:p,fullInputSchema:m,inputDetails:Br(h,`${n}.inputDetails`),inlineArtifacts:Mr(ee,`${n}.inlineArtifacts`)}:q(`${n}.fullInputSchema is invalid`):q(`${n}.inputSchema is invalid`):q(`${n}.queryParams is invalid`):q(`${n}.responseKind is invalid`):q(`${n}.effect is invalid`):q(`${n}.summary is invalid`):q(`${n}.method is invalid`)},Hr=e=>{if(!C(e))return q(`manifest must be an object`);let t=e.source;if(!C(t)||typeof t.title!=`string`||typeof t.version!=`string`)return q(`manifest.source is invalid`);let n=e.operations;if(!Array.isArray(n))return q(`manifest.operations must be an array`);let r=n.map((e,t)=>Vr(e,t));return new Set(r.map(e=>e.operationId)).size===r.length?{source:{title:t.title,version:t.version},operations:r}:q(`manifest.operations has duplicate operationId`)},Ur=(e,t)=>{let n;try{n=ae(e)}catch{throw t(`${e.pathname} cannot be read`)}try{return JSON.parse((e.pathname.endsWith(`.br`)?oe(n):n).toString(`utf8`))}catch{throw t(`${e.pathname} is not valid JSON or brotli`)}},Wr=new URL(`./manifest.json.br`,import.meta.url),Gr=(e=Wr)=>Hr(Ur(e,e=>new Ue(`manifest at ${e}`))),Kr=e=>`${e.product}/${e.slug}`,qr=e=>({articles:e,articleByReference:new Map(e.map(e=>[Kr(e),e])),searchEntries:e.map(e=>({article:e,normalizedTitle:e.title.toLowerCase(),normalizedDescription:e.description.toLowerCase(),normalizedGroup:e.group.toLowerCase(),normalizedBody:e.body.toLowerCase()}))}),Jr=(e,t)=>e.articleByReference.get(t)??null,Yr=(e,t)=>{for(let n of t){let t=e.normalizedBody.indexOf(n);if(t===-1)continue;let{body:r}=e.article,i=Math.max(0,t-80),a=Math.min(r.length,t+n.length+80),o=i>0?`…`:``,s=a<r.length?`…`:``;return`${o}${r.slice(i,a).replaceAll(/\s+/g,` `).trim()}${s}`}return e.article.description},Xr=(e,t,n)=>{let r=[...new Set(t.toLowerCase().split(/\s+/).filter(e=>e.length>0))];if(r.length===0)return[];let i=[];for(let t of e.searchEntries){let e=0,n=0;for(let i of r){let r=0;t.normalizedTitle.includes(i)&&(r+=10),t.normalizedDescription.includes(i)&&(r+=5),t.normalizedGroup.includes(i)&&(r+=3),t.normalizedBody.includes(i)&&(r+=1),r>0&&(e+=1,n+=r)}e>0&&i.push({entry:t,matchedKeywordCount:e,score:n})}return i.sort((e,t)=>t.matchedKeywordCount===e.matchedKeywordCount?t.score-e.score:t.matchedKeywordCount-e.matchedKeywordCount),i.slice(0,n).map(({entry:e})=>({article:Kr(e.article),title:e.article.title,group:e.article.group,description:e.article.description,snippet:Yr(e,r)}))},Zr=(e,t)=>{let n=e.replaceAll(/!\[[^\]]*\]\([^)]*\)/g,``),r=[];for(let e of n.split(/\r?\n/))(e.trim()!==``||r.at(-1)?.trim()!==``)&&r.push(e);return r.join(`
|
|
30
|
-
`).replaceAll(/\]\(([^)\s]+)\)/g,(e,n)=>{try{return`](${new URL(n,t).toString()})`}catch{return e}})},
|
|
31
|
-
`))
|
|
32
|
-
`)},
|
|
29
|
+
`)}finally{await e.close()}await g(n,t)}catch(e){throw await _(n,{force:!0}).catch(T),e}},ht=async(e,t,n)=>{let r=await pt(e);await mt(r);try{await ee($e(e),dt(t,n),{flag:`wx`});return}catch(e){if(V(e)!==`EEXIST`)throw e}let i=await et(e);if(i==null)throw rt(e,`(unknown)`,t.tenantName);at(e,i,t)},gt=e=>new z(`shared_directory`,`${e} はさまざまな作業で共有される場所なので、1 つのテナント専用にできません。このテナント用のディレクトリ(例: ~/flyle-ai-cx/<テナント名>)を作り、そこでセッションを始めてください。`),_t=async e=>{let t=await h(e.cwd),n=await h(e.homeDir).catch(()=>e.homeDir),r=[t,...st(t)];return{cwd:t,home:n,bindings:await Promise.all(r.map(async e=>({dir:e,binding:e===t?await et(e):await tt(e)})))}},vt=(e,t)=>e===t||e===v.parse(e).root,yt=e=>{let t=e.bindings.find(e=>e.binding!=null),n=t?.dir??e.cwd;if(vt(n,e.home))throw gt(n);return{root:n,binding:t?.binding??null}},bt=(e,t,n)=>{let r=e.bindings.findIndex(e=>e.dir===t);for(let{dir:t,binding:i}of e.bindings.slice(r+1))i!=null&&at(t,i,n)},xt=e=>new z(`nested_workspace`,`${e} の中のディレクトリが多すぎて、別のテナントの作業ディレクトリが入っていないかを確かめきれません。このテナント専用の空のディレクトリ(例: ~/flyle-ai-cx/<テナント名>)を作り、そこでセッションを始めてください。`),St=async e=>{try{return await m(e,{withFileTypes:!0})}catch(e){let t=V(e);if(t===`EACCES`||t===`EPERM`||t===`ENOENT`)return[];throw e}},Ct=async(e,t)=>{let n=[e],r=0,i=0;for(;n.length>0;){let a=await Promise.all(n.map(async e=>({dir:e,entries:await St(e)}))),o=await Promise.all(a.filter(({dir:t,entries:n})=>t!==e&&n.some(e=>e.name===`.flyle-ai-cx-mcp`)).map(async({dir:e})=>({dir:e,binding:await tt(e)})));for(let{dir:n,binding:r}of o)if(r!=null&&(r.tenantName!==t.tenantName||r.apiBaseUrl!==t.apiBaseUrl))throw ot(e,n,r.tenantName);if(i>=6)return;if(n=a.flatMap(({dir:e,entries:t})=>t.filter(e=>e.isDirectory()&&!Xe.has(e.name)).map(t=>v.join(e,t.name))),r+=n.length,r>5e3)throw xt(e);i+=1}},wt=async(e,t)=>{let n=await _t(e),{root:r}=yt(n);return bt(n,r,t),await Ct(r,t),await ht(r,t,e.now()),{...t,...ut(e,r)}},Tt=async e=>yt(await _t(e)).binding,Et=async e=>ut(e,yt(await _t(e)).root),Dt=async e=>{let t=await _t(e),{root:n,binding:r}=yt(t);return r==null?null:(bt(t,n,r),{...r,...ut(e,n)})},Ot=async(e,t)=>{await ht(e.root,e,t)},kt={allowInsecureHttp:`FLYLE_AI_CX_MCP_ALLOW_INSECURE_HTTP`,noBrowser:`FLYLE_AI_CX_MCP_NO_BROWSER`},At=/* @__PURE__ */ new Set([`localhost`,`127.0.0.1`,`[::1]`]),jt=e=>{let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)},Mt=e=>At.has(e),Nt=(e,t,n)=>{let r;try{r=new URL(e)}catch{throw new L(`${n} が URL として正しくありません。`)}if(r.search!==``||r.hash!==``||r.username!==``||r.password!==``)throw new L(`${n} にクエリ(?)・フラグメント(#)・認証情報を含めないでください。`);let i=r.protocol===`http:`&&t&&Mt(r.hostname);if(r.protocol!==`https:`&&!i)throw new L(`${n} は https の URL を指定してください(http はローカル開発で ${kt.allowInsecureHttp}=1 を付けたときの localhost だけ使えます)。`);let a=jt(r.pathname);return new URL(`${r.origin}${a}`)},Pt=e=>e===`1`||e===`true`,Ft=e=>e.length>=2&&e.length<=32&&Ve.test(e),It=(e,t)=>{if(!Ft(e))throw new L(`${t} がテナント名として正しくありません。英小文字・数字・ハイフンで 2〜32 文字のテナント名を指定してください。`);return e},Lt=e=>Pt(e[kt.allowInsecureHttp]),Rt=e=>Pt(e[kt.noBrowser]),H=e=>e.host,zt=(e,t,n)=>{let r=Lt(e);return{baseUrl:Nt(n.apiBaseUrl,r,`作業ディレクトリの接続先`),tenantName:It(n.tenantName,`作業ディレクトリのテナント`),outputDir:v.resolve(t,Ye,`downloads`),allowInsecureHttp:r}},Bt=`flyle-ai-cx-mcp`,Vt=`credentials`,Ht=()=>o(8).toString(`hex`),Ut=/* @__PURE__ */ Me({version:/* @__PURE__ */ ke(1),apiBaseUrl:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ Te()),tenantName:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ be(Ft)),loginConnectionId:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(Be)),accessToken:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(Re)),accessTokenExpiresAt:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ Se()),refreshToken:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(ze)),refreshTokenExpiresAt:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ Se())}),Wt=({platform:e,env:t,homeDir:n})=>{let r=t.XDG_CONFIG_HOME;if(r!=null&&v.isAbsolute(r))return v.join(r,Bt,Vt);let i=t.APPDATA;return e===`win32`&&i!=null&&v.isAbsolute(i)?v.join(i,Bt,Vt):v.join(n,`.config`,Bt,Vt)},Gt=(e,t)=>v.join(e,`${t}.json`),U=e=>e instanceof Error&&b(e,`code`)?e.code:null,Kt=async(e,t)=>{let n=Gt(e,t.workspaceId),r=Gt(e,t.legacyWorkspaceId);try{await l(r,n)}catch(e){let t=U(e);if(t===`ENOENT`||t===`EEXIST`)return n;throw e}return await _(r,{force:!0}),n},qt=async e=>{let t;try{t=await p(e,`utf8`)}catch(e){if(U(e)===`ENOENT`)return null;throw e}let n;try{n=JSON.parse(t)}catch{n=null}let r=/* @__PURE__ */ M(Ut,n);if(!r.success)throw new P(`login_required`,`保存されたログイン情報(${e})を読めません。`);return r.output},Jt=async e=>{await d(e,{recursive:!0,mode:448}),await c(e,448)},Yt=async(e,t)=>{await Jt(v.dirname(e));let n={version:1,...t},r=`${e}.${Ht()}.tmp`;try{let t=await f(r,`wx`,384);try{await t.writeFile(`${JSON.stringify(n,null,2)}\n`)}finally{await t.close()}await g(r,e)}catch(e){throw await _(r,{force:!0}).catch(T),e}},Xt=async e=>{await _(e,{force:!0})},Zt=(e,t)=>({staleMs:6e4,acquireTimeoutMs:9e4,retryIntervalMs:100,now:e,sleep:t}),Qt=async e=>{let t;try{t=await f(e,`r`)}catch(e){if(U(e)===`ENOENT`)return null;throw e}try{let[e,n]=await Promise.all([t.readFile(`utf8`),t.stat()]);return{owner:e,mtimeMs:n.mtimeMs}}finally{await t.close()}},$t=async(e,t)=>{let n=`${e}.${Ht()}.tmp`,r=await f(n,`wx`,384);try{await r.writeFile(t)}finally{await r.close()}try{return await l(n,e),!0}catch(e){if(U(e)===`EEXIST`)return!1;throw e}finally{await _(n,{force:!0})}},en=async(e,t)=>{let n=`${e}.${Ht()}.aside`;try{await g(e,n)}catch(e){if(U(e)===`ENOENT`)return!1;throw e}return await p(n,`utf8`)===t?(await _(n,{force:!0}),!0):(await l(n,e).catch(e=>{if(U(e)!==`EEXIST`)throw e}),await _(n,{force:!0}),!1)},tn=async(e,t,n)=>{let r=`${e}.guard`,i=Ht(),a=t.now()+t.acquireTimeoutMs;for(;!await $t(r,i);){let n=await Qt(r);if(n!=null){if(t.now()-n.mtimeMs>=t.staleMs)await en(r,n.owner);else{if(t.now()>=a)throw Error(`ログイン情報のロック(${e})を取得できませんでした。別の MCP プロセスが更新中です。しばらくしてから再実行してください`);await t.sleep(t.retryIntervalMs)}}}try{return await n()}finally{await en(r,i)}},nn=(e,t,n)=>tn(e,n,async()=>(await Qt(e))?.owner===t&&(await _(e,{force:!0}),!0)),rn=(e,t)=>tn(e,t,async()=>{let n=await Qt(e);return n==null?!0:t.now()-n.mtimeMs<t.staleMs?!1:(await _(e,{force:!0}),!0)}),an=async(e,t,n)=>{await Jt(v.dirname(e));let r=`${e}.lock`,i=Ht(),a=t.now()+t.acquireTimeoutMs;for(;!await $t(r,i);)if(!await rn(r,t)){if(t.now()>=a)throw Error(`ログイン情報のロック(${r})を取得できませんでした。別の MCP プロセスが更新中です。しばらくしてから再実行してください`);await t.sleep(t.retryIntervalMs)}try{return await n()}finally{await nn(r,i,t).catch(T)}},on=`application/json`,sn=`x-request-id`,cn=(e,t)=>{if(e.origin!==t.origin)throw new I(`request_refused`,`refusing to send credentials outside the configured API origin`)},ln=e=>{let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)},un=(e,t)=>{let n=`${ln(e.pathname)}${t.path}`,r=new URL(n,e);if(r.pathname!==n)throw new I(`request_refused`,`refusing to send a request whose path was normalized`);for(let[e,n]of t.query)r.searchParams.append(e,n);return cn(r,e),r},dn=async(e,t)=>{let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw await e.body?.cancel().catch(T),new I(`response_too_large`,`response exceeds ${t} bytes`,e.status);if(e.body==null)return/* @__PURE__ */ new Uint8Array;let r=e.body.getReader(),i=[],a=0;for(;;){let{done:n,value:o}=await r.read();if(n)break;if(a+=o.byteLength,a>t)throw await r.cancel().catch(T),new I(`response_too_large`,`response exceeds ${t} bytes`,e.status);i.push(o)}let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return o},fn=e=>new TextDecoder(`utf-8`).decode(e),pn=(e,t)=>(e.headers.get(`content-type`)??``).toLowerCase().startsWith(t),mn=e=>{if(e==null)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null},hn=(e,t)=>{let n=e[t];return typeof n==`string`?n:null},gn=e=>typeof e==`object`&&!!e&&!Array.isArray(e),_n=e=>{let t=e.issues;return Array.isArray(t)?t.filter(e=>gn(e)):null},vn=async(e,t)=>{let n=e.headers.get(sn),r=mn(e.headers.get(`retry-after`)),i;try{i=fn(await dn(e,t))}catch{i=``}if(pn(e,on))try{let t=JSON.parse(i),a=gn(t)&&gn(t.error)?t.error:null;if(a!=null)return new F({status:e.status,code:hn(a,`code`),message:hn(a,`message`)??e.statusText,detail:hn(a,`detail`),issues:_n(a),requestId:hn(a,`requestId`)??n,retryAfterSeconds:r})}catch{}return new F({status:e.status,code:null,message:i.slice(0,500)||e.statusText||`HTTP error`,detail:null,issues:null,requestId:n,retryAfterSeconds:r})},yn=e=>e instanceof I?e:e instanceof Error&&e.name===`AbortError`?new I(`timeout`,`the API did not respond in time`):new I(`network`,e instanceof Error?e.message:`network failure`),bn=(e,t,n)=>{let r=e.getReader(),i=!1,a=async()=>{i||(i=!0,await r.cancel().catch(T))};return{chunks:async function*(){let e=setTimeout(()=>t.abort(),n);try{for(;;){let{done:a,value:o}=await r.read();if(a){i=!0;return}clearTimeout(e),e=setTimeout(()=>t.abort(),n),yield o}}catch(e){throw i=!0,yn(e)}finally{clearTimeout(e),await a()}}(),cancel:a}},xn=(e,t)=>{let{baseUrl:n,auth:r,fetch:i,sleep:a,logger:o}=e,s=async(r,a)=>{let o=un(n,r),s=new Headers({...e.headers,accept:on});a!=null&&s.set(`authorization`,`Bearer ${a}`);let c;r.hasBody&&(c=JSON.stringify(r.body??{}),s.set(`content-type`,on));let l=new AbortController,u=setTimeout(()=>l.abort(),t.headersTimeoutMs),d;try{d=await i(o,{method:r.method,headers:s,...c==null?{}:{body:c},redirect:`manual`,signal:l.signal})}catch(e){throw clearTimeout(u),yn(e)}if(d.status>=300&&d.status<400)throw clearTimeout(u),await d.body?.cancel().catch(T),new I(`redirect_not_followed`,`redirect responses are not followed`,d.status);if(!d.ok)try{throw await vn(d,t.maxJsonBytes)}finally{clearTimeout(u)}let f=d.headers.get(sn);switch(r.responseKind){case`json`:try{if(!pn(d,on))throw await d.body?.cancel().catch(T),new I(`unexpected_content_type`,`expected an application/json response`,d.status);let e=fn(await dn(d,t.maxJsonBytes)),n;try{n=JSON.parse(e)}catch{throw new I(`invalid_json`,`the response body is not valid JSON`,d.status)}return{kind:`json`,status:d.status,requestId:f,body:n}}catch(e){throw yn(e)}finally{clearTimeout(u)}case`empty`:return clearTimeout(u),await d.body?.cancel().catch(T),{kind:`empty`,status:d.status,requestId:f};case`file`:if(clearTimeout(u),!pn(d,on)||d.body==null)throw await d.body?.cancel().catch(T),new I(`unexpected_content_type`,`expected an application/json file response`,d.status);return{kind:`file`,status:d.status,requestId:f,...bn(d.body,l,t.downloadIdleTimeoutMs)};default:throw r.responseKind,Error(`unknown response kind ${String(r.responseKind)}`)}},c=async(e,n)=>{let r=e.method===`GET`;try{return await s(e,n)}catch(i){if(!r)throw i;if(i instanceof F&&i.info.status===429&&i.info.retryAfterSeconds!=null&&i.info.retryAfterSeconds<=t.maxRetryAfterSeconds)return o.warn(`rate limited; retrying once`,{path:e.path,retryAfterSeconds:i.info.retryAfterSeconds}),await a(i.info.retryAfterSeconds*1e3),await s(e,n);if(i instanceof I&&i.kind===`network`)return o.warn(`network failure; retrying once`,{path:e.path}),await s(e,n);throw i}};return{request:async e=>{if(r==null)return c(e,null);let t=await r.getAccessToken();try{return await c(e,t)}catch(n){if(!(n instanceof F)||n.info.status!==401)throw n;let i=await r.refreshAfterRejection(t);if(i===t)throw n;return o.warn(`access token rejected; retrying once with a refreshed token`,{path:e.path}),await c(e,i)}}}},Sn={headersTimeoutMs:6e4,maxJsonBytes:16777216,maxRetryAfterSeconds:30,downloadIdleTimeoutMs:6e4},Cn=(e,t=Sn)=>xn({baseUrl:e.config.baseUrl,auth:e.auth,headers:{"user-agent":`flyle-ai-cx-mcp/${Fe}`,"x-flyle-client-workspace":e.workspaceId},fetch:e.fetch,sleep:e.sleep,logger:e.logger},t),wn=`{tenantName}`,Tn={...Sn,headersTimeoutMs:2e4},En=/* @__PURE__ */ k({authorizationUrlTemplate:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ xe(wn))}),Dn=/* @__PURE__ */ k({accessToken:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(Re)),accessTokenExpiresAt:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ Se()),refreshToken:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(ze)),refreshTokenExpiresAt:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ Se()),tenantName:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ be(Ft)),loginConnectionId:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(Be))}),On=(e,t,n)=>{let r=/* @__PURE__ */ M(e,t);if(!r.success)throw new I(`invalid_json`,`the login connection response does not match the contract`,n);return r.output},kn=async e=>{let t=await e.request({method:`GET`,path:`/v0/login-connections/metadata`,query:[],hasBody:!1,body:null,responseKind:`json`});if(t.kind!==`json`)throw new I(`unexpected_content_type`,`not JSON`);return On(En,t.body,t.status).authorizationUrlTemplate},An=async(e,t)=>{let n;try{n=await e.request({method:`POST`,path:`/v0/login-connections/token`,query:[],hasBody:!0,body:t,responseKind:`json`})}catch(e){throw e instanceof F&&e.info.code===`invalid_grant`?new Je(`the authorization code or refresh token is no longer valid`):e}if(n.kind!==`json`)throw new I(`unexpected_content_type`,`not JSON`);return On(Dn,n.body,n.status)},jn=(e,t,n)=>{if(e.apiBaseUrl===t.href&&e.tenantName===n)return;let r=Ke({tenantName:n,baseUrl:t,baseUrlVerified:e.apiBaseUrl===t.href});throw new P(`credentials_mismatch`,`保存されたログイン(環境 ${H(new URL(e.apiBaseUrl))} / テナント ${e.tenantName})が、この作業ディレクトリの接続先(環境 ${H(t)} / テナント ${n})と一致しません。この作業ディレクトリで \`${r}\` を実行し直してください`)},Mn=(e,t)=>({apiBaseUrl:t.href,tenantName:e.tenantName,loginConnectionId:e.loginConnectionId,accessToken:e.accessToken,accessTokenExpiresAt:e.accessTokenExpiresAt,refreshToken:e.refreshToken,refreshTokenExpiresAt:e.refreshTokenExpiresAt}),Nn=e=>{let{credentialsFile:t,baseUrl:n,tenantName:r,tokenClient:i,now:a}=e,o=null,s=null,c=[],l=!1,u=(...e)=>{c.push(...e),c.splice(0,Math.max(0,c.length-8))},d=()=>qe({tenantName:r,baseUrl:n,baseUrlVerified:l}),f=()=>new P(`login_required`,d()),p=async()=>{let e;try{e=await qt(t)}catch(e){throw e instanceof P?new P(`login_required`,`${e.message}${d()}`):e}if(e?.apiBaseUrl===n.href&&(l=!0),e==null||Date.parse(e.refreshTokenExpiresAt)<=a())throw f();return jn(e,n,r),e},m=e=>e-a()>6e4,h=async e=>{try{await Yt(t,e)}catch{try{await Yt(t,e)}catch{await Xt(t)}}},g=a=>an(t,e.lock,async()=>{let e=await p();u(e.accessToken,e.refreshToken);let s=Date.parse(e.accessTokenExpiresAt);if(e.accessToken!==a&&m(s))return o={token:e.accessToken,expiresAt:s},e.accessToken;let c;try{c=await An(i,{grant_type:`refresh_token`,refresh_token:e.refreshToken})}catch(e){throw e instanceof Je?(await Xt(t),f()):e}if(u(c.accessToken,c.refreshToken),c.tenantName!==r)throw await Xt(t),new P(`login_required`,`ログインの更新で、設定と違うテナント(${c.tenantName})の応答を受け取ったため、保存したログイン情報を破棄しました。${d()}`);if(c.loginConnectionId!==e.loginConnectionId)throw await Xt(t),new P(`login_required`,`ログインの更新で、保存したログインと違う接続の応答を受け取ったため、保存したログイン情報を破棄しました。${d()}`);return o={token:c.accessToken,expiresAt:Date.parse(c.accessTokenExpiresAt)},await h(Mn(c,n)),c.accessToken}),_=e=>(s??=g(e).finally(()=>{s=null}),s);return{getAccessToken:()=>o!=null&&m(o.expiresAt)?Promise.resolve(o.token):_(o?.token??null),refreshAfterRejection:e=>o!=null&&o.token!==e?Promise.resolve(o.token):(o=null,_(e)),assertLoggedIn:async()=>{o??await p()},secrets:()=>c,whenIdle:async()=>{await Promise.allSettled(s==null?[]:[s])}}},Pn=(e,t)=>e===`darwin`?[`open`,[t]]:e===`win32`?[`rundll32`,[`url.dll,FileProtocolHandler`,t]]:[`xdg-open`,[t]],Fn=(e,t=process.platform)=>{let[n,r]=Pn(t,e),i=te(n,r,{stdio:`ignore`,detached:!0,shell:!1});i.on(`error`,T),i.unref()},In=(e,t,n)=>Cn({config:{baseUrl:t},auth:null,workspaceId:n,fetch:e.fetch,sleep:e.sleep,logger:e.logger},Tn),Ln=e=>e==null?"作業ディレクトリで `npx @flyle/ai-cx-mcp@latest login --tenant <テナント名>` を実行し直してください":qe({tenantName:e.tenantName,baseUrl:new URL(e.apiBaseUrl),baseUrlVerified:!1}),Rn=async(e,t,n)=>{let r=await Kt(e.credentialsDir,t),i;try{i=await qt(r)}catch(e){throw e instanceof P?new P(`login_required`,`${e.message}${Ln(n)}`):e}if(i==null)return null;let a=Nt(i.apiBaseUrl,Lt(e.env),`${r} の apiBaseUrl`);return{workspace:{...t,...n??{tenantName:i.tenantName,apiBaseUrl:a.href}},file:r,stored:i,baseUrl:a}},zn=async e=>{let t=await Dt(e.workspaceEnv);return t==null?null:Rn(e,t,t)},Bn=async e=>Rn(e,await Et(e.workspaceEnv),null),Vn=(e,t)=>{let n=Nn({credentialsFile:t.file,baseUrl:t.baseUrl,tenantName:t.stored.tenantName,tokenClient:In(e,t.baseUrl,t.workspace.workspaceId),now:e.now,lock:e.lock});return{auth:n,client:Cn({config:{baseUrl:t.baseUrl},auth:n,workspaceId:t.workspace.workspaceId,fetch:e.fetch,sleep:e.sleep,logger:e.logger})}},Hn=(e,t)=>`/v0/tenants/${encodeURIComponent(e)}${t}`,W=e=>e instanceof B||e instanceof P||e instanceof L||e instanceof z?e.message:e instanceof F?`公開 API がエラーを返しました(${String(e.info.status)} ${e.info.code??`http_error`}): ${e.info.message}`:e instanceof I?`公開 API と通信できませんでした(${e.kind}): ${e.message}`:e instanceof Error?e.message:String(e),Un=`tenantName`,G=(e,t)=>{let n=e;for(let e of t)e.length!==0&&(n=n.split(e).join(`[redacted]`));return n},Wn=async(e,t)=>{let{client:n}=Vn(e,t);try{return await n.request({method:`DELETE`,path:Hn(t.stored.tenantName,`/current-login-connection`),query:[],hasBody:!1,body:null,responseKind:`empty`}),`revoked`}catch(e){if(!(e instanceof P&&e.kind===`login_required`||e instanceof F&&e.info.status===401))throw e;return`unconfirmed`}},Gn=async e=>{let t=await Bn(e);if(t==null){e.out(`この作業ディレクトリにはログイン情報がありません。`);return}let n=await Wn(e,t);await an(t.file,e.lock,()=>Xt(t.file)),e.out(`ログアウトしました(環境 ${H(t.baseUrl)} / テナント ${t.stored.tenantName})。`),n===`unconfirmed`&&e.err(`サーバー側で接続を切断できたか確認できませんでした。接続が残っている場合は、Flyle AI CX の「設定」>「外部ツール接続」から切断してください。`)},Kn=`127.0.0.1`,qn=`/callback`,Jn=e=>{try{let{values:t}=re({args:[...e],options:{tenant:{type:`string`},"api-base-url":{type:`string`}},strict:!0,allowPositionals:!1});return{tenant:t.tenant??null,apiBaseUrl:t[`api-base-url`]??null}}catch(e){throw new B(`${e instanceof Error?e.message:String(e)}\n使い方: login [--tenant <テナント名>] [--api-base-url <URL>]`)}},Yn=async e=>{try{return await Bn(e)}catch{return null}},Xn=async(e,t,n,r)=>{if(t!=null)return Nt(t,r,`--api-base-url`);let i=Nt(Ie,r,`既定の接続先`);if(n==null)return i;let a=Nt(n.apiBaseUrl,r,`作業ディレクトリの接続先`);if(a.href===i.href||(await Yn(e))?.baseUrl.href===a.href)return a;throw new B(`この作業ディレクトリは既定以外の接続先(${a.host})に束縛されています。その接続先が正しいことを確かめたうえで \`login --api-base-url <URL>\` で明示してください。心当たりが無ければ、このディレクトリの ${Ye} は他人が置いたものかもしれません。`)},Zn=async(e,t,n)=>{let r=new URL(Ie);if(t.href!==r.href&&!(n&&t.protocol===`http:`&&Mt(t.hostname))&&(await Yn(e))?.baseUrl.href!==t.href&&!await e.confirm(`接続先 ${t.host} は Flyle AI CX の本番の接続先(${r.host})ではありません。ログインすると、この接続先へ認可コードを送ります。Flyle から案内された接続先で間違いなければ y を入力してください [y/N]: `))throw new B(`接続先 ${t.host} へのログインを中止しました。本番以外の接続先へは、対話できる端末で login を実行し、接続先を確かめて y を入力したときだけログインします。`)},Qn=(e,t)=>{if(e!=null)return It(e,`--tenant`);if(t!=null)return t.tenantName;throw new B("テナントを決められません。`login --tenant <テナント名>` で指定してください(作業ディレクトリをそのテナント専用にします)。")},$n=()=>o(32).toString(`base64url`),er=e=>a(`sha256`).update(e).digest(`base64url`),tr=(e,t)=>{let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&s(n,r)},nr=(e,t,n)=>{let r;try{r=new URL(e.replaceAll(wn,t))}catch{throw new B(`公開 API が返した同意画面の URL が不正です。`)}let i=r.protocol===`http:`&&n&&(Mt(r.hostname)||r.hostname.endsWith(`.localhost`));if(r.protocol!==`https:`&&!i)throw new B(`公開 API が返した同意画面の URL が https ではありません。`);return r},rr=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Co}]/gu,ir=(e,t)=>{let n=``;for(let r of e){if(n.length+r.length>t)break;n+=r}return n},ar=(e,t)=>{let n=e=>e.replaceAll(rr,``);return ir(`${n(e)} / ${n(v.basename(t))}`,255)},or=/* @__PURE__ */ Pe([/* @__PURE__ */ k({error:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(/^[a-z_]{1,64}$/)),state:/* @__PURE__ */ A()}),/* @__PURE__ */ k({code:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ O(Le)),state:/* @__PURE__ */ A()})]),sr={success:`ログインが完了しました。このタブは閉じてかまいません。`,denied:`ログインを中止しました。このタブは閉じてかまいません。`,failure:`ログインを完了できませんでした。このタブを閉じて、ターミナルの表示を確認してください。`,handled:`このログインは処理済みです。このタブは閉じてかまいません。`,unknown:`実行中のログインの応答として確認できませんでした。ログインを続ける場合は、ターミナルに表示された URL から同意画面を開き直してください。`,rejected:`この宛先への要求は受け付けていません。`},cr=(e,t,n)=>{e.writeHead(t,{"content-type":`text/html; charset=utf-8`,"cache-control":`no-store`,"content-security-policy":`default-src 'none'`,"referrer-policy":`no-referrer`}),e.end(`<!doctype html><html lang="ja"><meta charset="utf-8"><title>Flyle AI CX</title><p>${sr[n]}</p></html>`)},lr=e=>new Promise((t,n)=>{e.once(`error`,n),e.listen(0,Kn,()=>{let r=e.address();r==null||typeof r==`string`?n(new B(`ログイン用の待受ポートを開けませんでした。`)):t(r.port)})}),ur=async(e,t,n)=>{let r=!1,i=0,a=null,o=Promise.withResolvers(),s=e=>{r=!0,o.reject(new B(e))},c=(e,t,r)=>{i+=1,cr(e,400,t),n(r)},l=ne((t,n)=>{if(a==null||t.headers.host!==a){c(n,`rejected`,`ログイン用の待受に、想定外の宛先(Host ヘッダ)の要求が届いたため拒否しました。ログインは待ち続けています。`);return}let i=new URL(t.url??`/`,`http://${a}`);if(t.method!==`GET`||i.pathname!==qn){n.writeHead(404).end();return}if(r){cr(n,410,`handled`);return}let l=i.searchParams.get(`state`);if(l==null||!tr(l,e)){c(n,`unknown`,`このログインのものではない応答(state が一致しない、または無い)を受け取ったため無視しました。ブラウザで同意を続けてください。`);return}let u=/* @__PURE__ */ M(or,C(i.searchParams));if(!u.success){cr(n,400,`failure`),s(`同意画面からの応答の形式が正しくありません(認可コードがない、または形式が違います)。もう一度 login を実行してください。`);return}let d=u.output;if(b(d,`error`)){let e=d.error===`access_denied`;cr(n,200,e?`denied`:`failure`),s(e?`ブラウザでログインが拒否されました。`:`同意画面がエラーを返しました(${d.error})。`);return}r=!0;let f=!1;o.resolve({code:d.code,finish:e=>{f||(f=!0,cr(n,e===`success`?200:400,e))}})}),u=await lr(l);a=`${Kn}:${String(u)}`;let d=setTimeout(()=>{if(r)return;let e=i===0?``:`(このログインのものではない要求を ${String(i)} 件受け取り、無視しました)`;s(`${String(Math.round(t/1e3/60))} 分以内にブラウザでの同意が完了しませんでした${e}。もう一度 login を実行してください。`)},t);return{port:u,received:o.promise,close:()=>new Promise(e=>{clearTimeout(d),l.closeAllConnections(),l.close(()=>e())})}},dr=`その接続は最長 30 日間有効なまま残る可能性があります。管理画面の「設定」>「外部ツール接続」から切断してください。`,fr=async(e,t)=>{if(t!=null)try{await Wn(e,t)}catch(n){e.err(`以前のログイン(接続 ID ${t.stored.loginConnectionId})をサーバーで切断できませんでした(${W(n)})。${dr}`)}},pr=async e=>{try{return await zn(e)}catch(t){if(!(t instanceof P&&t.kind===`login_required`)&&!(t instanceof L))throw t;return e.err(`以前のログイン情報を読めなかったため、新しいログインで上書きします(${W(t)})。以前の接続はサーバーで切断できていません。${dr}`),null}},mr=async(e,t,n,r)=>{let i=Gt(e.credentialsDir,t.workspaceId);await an(i,e.lock,()=>Yt(i,Mn(r,n)))},hr=e=>({getAccessToken:()=>Promise.resolve(e),refreshAfterRejection:()=>Promise.resolve(e),assertLoggedIn:()=>Promise.resolve(),secrets:()=>[e]}),gr=async(e,t,n,r)=>{let i=Cn({config:{baseUrl:t},auth:hr(r.accessToken),workspaceId:n.workspaceId,fetch:e.fetch,sleep:e.sleep,logger:e.logger});try{return await i.request({method:`DELETE`,path:Hn(r.tenantName,`/current-login-connection`),query:[],hasBody:!1,body:null,responseKind:`empty`}),!0}catch{return!1}},_r=async e=>{let t=Jn(e.argv),n=Lt(e.env),r=await Tt(e.workspaceEnv),i=await Xn(e,t.apiBaseUrl,r,n),a=Qn(t.tenant,r);await Zn(e,i,n);let o=await wt(e.workspaceEnv,{tenantName:a,apiBaseUrl:i.href}),s=await pr(e),c=In(e,i,o.workspaceId),l=nr(await kn(c),a,n),u=$n(),d=$n(),f=[u,d],p=await ur(d,e.callbackTimeoutMs,e.err),m=null;try{let t=`http://${Kn}:${String(p.port)}${qn}`;l.searchParams.set(`tenant_name`,a),l.searchParams.set(`code_challenge`,er(u)),l.searchParams.set(`code_challenge_method`,`S256`),l.searchParams.set(`redirect_uri`,t),l.searchParams.set(`state`,d),l.searchParams.set(`connection_name`,ar(e.workspaceEnv.hostname,o.root)),e.err(`環境 ${H(i)} のテナント「${a}」にログインします。ブラウザで同意画面を開きます。\n開かない場合は、次の URL をブラウザで開いてください:\n${l.href}`),e.openBrowser(l.href),m=await p.received,f.push(m.code);let n;try{n=await An(c,{grant_type:`authorization_code`,code:m.code,code_verifier:u,redirect_uri:t})}catch(e){throw e instanceof Je?new B(`認可コードを交換できませんでした。もう一度 login を実行してください。`):e}if(f.push(n.accessToken,n.refreshToken),n.tenantName!==a){let t=await gr(e,i,o,n);throw new B(`ブラウザで同意したテナント(${n.tenantName})が、ログインしようとしたテナント(${a})と違います。ログイン情報は保存していません。`+(t?`そのテナントに作られた接続は切断しました。`:`テナント ${n.tenantName} の管理画面の「設定」>「外部ツール接続」から、作られた接続を切断してください。`))}try{await Ot(o,new Date(e.now())),await fr(e,s),await mr(e,o,i,n)}catch(t){let r=await gr(e,i,o,n);throw new B(`ログイン情報を保存できませんでした(${W(t)})。`+(r?`作った接続は切断しました。原因を取り除いてから、もう一度 login を実行してください。`:`作った接続を切断できませんでした。${dr}`))}m.finish(`success`),e.out(`ログインしました(環境 ${H(i)} / テナント ${a} / 作業ディレクトリ ${o.root})。`)}catch(e){throw m?.finish(`failure`),new B(G(W(e),f))}finally{await p.close()}},vr=/* @__PURE__ */ k({currentUser:/* @__PURE__ */ k({name:/* @__PURE__ */ A(),email:/* @__PURE__ */ A(),roles:/* @__PURE__ */ Oe(/* @__PURE__ */ k({roleName:/* @__PURE__ */ A()})),tenantName:/* @__PURE__ */ A(),currentLoginConnection:/* @__PURE__ */ k({name:/* @__PURE__ */ A(),expiresAt:/* @__PURE__ */ j(/* @__PURE__ */ A(),/* @__PURE__ */ Se())})})}),yr=async e=>{let t=await Dt(e.workspaceEnv);return t==null?"ログインしていません。作業ディレクトリで `npx @flyle/ai-cx-mcp@latest login --tenant <テナント名>` を実行してください":`ログインしていません。作業ディレクトリで \`${Ke({tenantName:t.tenantName,baseUrl:new URL(t.apiBaseUrl),baseUrlVerified:!1})}\` を実行してください`},br=async e=>{let t=await zn(e);if(t==null)throw new B(await yr(e));e.out(`環境: ${H(t.baseUrl)}`),e.out(`テナント: ${t.stored.tenantName}`);let{client:n}=Vn(e,t),r;try{r=await n.request({method:`GET`,path:Hn(t.stored.tenantName,`/current-user`),query:[],hasBody:!1,body:null,responseKind:`json`})}catch(e){throw e instanceof P&&e.kind===`login_required`?new B(e.message):e}let i=/* @__PURE__ */ M(vr,r.kind===`json`?r.body:null);if(!i.success)throw new I(`invalid_json`,`the current user response does not match the contract`);let a=i.output.currentUser;if(a.tenantName!==t.stored.tenantName){let e=Ke({tenantName:t.workspace.tenantName,baseUrl:new URL(t.workspace.apiBaseUrl),baseUrlVerified:t.baseUrl.href===t.workspace.apiBaseUrl});throw new P(`credentials_mismatch`,`ログイン中のテナント(${a.tenantName})が、この作業ディレクトリのテナント(${t.stored.tenantName})と一致しません。この作業ディレクトリで \`${e}\` を実行し直してください`)}e.out(`ユーザー: ${a.name} <${a.email}>`),e.out(`ロール: ${a.roles.map(e=>e.roleName).join(`, `)||`(なし)`}`),e.out(`接続名: ${a.currentLoginConnection.name}`),e.out(`ログインの有効期限: ${a.currentLoginConnection.expiresAt}(使うたびに延長。ログインから最長 90 日)`)},xr=(e,t,n,r)=>{let i={level:e,message:t,...n,time:(/* @__PURE__ */ new Date()).toISOString()};return G(JSON.stringify(i),r)},Sr=(e,t=e=>console.error(e))=>({info:(n,r)=>t(xr(`info`,n,r,e())),warn:(n,r)=>t(xr(`warn`,n,r,e())),error:(n,r)=>t(xr(`error`,n,r,e()))}),Cr=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],wr=[`json`,`empty`,`file`],Tr=[`read`,`write`],Er=[`table`,`workflow`,`form`,`report`,`dashboard`,`folder`,`role`,`user`,`user_group`],Dr=[`image/svg+xml`],K=(e,t)=>{throw new We(`${e}: ${t}`)},Or=(e,t)=>w(e)?e:K(t,`expected an object`),kr=(e,t)=>typeof e==`string`?e:K(t,`expected a string`),Ar=/^[a-z0-9]{1,8}$/,jr=/^\w+$/,Mr=e=>{let[t,...n]=e.split(`/`);return t===``&&n.length>=1&&n.length<=8&&n.every(e=>jr.test(e))},Nr=(e,t)=>e==null?[]:Array.isArray(e)?e.map((e,n)=>{let r=Or(e,`${t}[${n}]`),i=kr(r.pointer,`${t}[${n}].pointer`),a=kr(r.extension,`${t}[${n}].extension`),o=Dr.find(e=>e===r.mediaType);return o==null?K(`${t}[${n}]`,`unsupported mediaType`):Mr(i)?Ar.test(a)?{pointer:i,mediaType:o,extension:a}:K(`${t}[${n}]`,`invalid extension`):K(`${t}[${n}]`,`invalid pointer`)}):K(t,`x-inline-artifacts must be an array`),Pr=/^[A-Za-z]\w*$/,Fr=(e,t)=>{if(e==null)return null;let n=Or(e,t);if(n.in===`path`){let e=kr(n.name,`${t}.name`);return Pr.test(e)?{in:`path`,name:e}:K(t,`invalid path parameter`)}if(n.in===`response`){let e=kr(n.pointer,`${t}.pointer`);return Mr(e)?{in:`response`,pointer:e}:K(t,`invalid pointer`)}return K(t,`id.in must be path or response`)},Ir=(e,t)=>{if(e==null)return null;let n=Or(e,t),r=Er.find(e=>e===n.type);return r==null?K(`${t}.type`,`unknown type`):{type:r,id:Fr(n.id,`${t}.id`)}},q=e=>{throw new Ue(e)},J=e=>e===null,Lr=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),Rr=e=>typeof e==`string`&&Cr.some(t=>t===e),zr=e=>typeof e==`string`&&wr.some(t=>t===e),Br=e=>typeof e==`string`&&Tr.some(t=>t===e),Vr=(e,t)=>{if(!w(e))return q(`${t} must be an object`);let{value:n,summary:r,schema:i}=e;return typeof n!=`string`||typeof r!=`string`||!w(i)?q(`${t} is invalid`):{value:n,summary:r,schema:i}},Hr=(e,t)=>{if(!w(e))return q(`${t} must be an object`);let{path:n,discriminator:r,description:i,variants:a}=e;return typeof n!=`string`||typeof r!=`string`?q(`${t} is invalid`):!J(i)&&typeof i!=`string`?q(`${t}.description is invalid`):Array.isArray(a)?{path:n,discriminator:r,description:i,variants:a.map((e,n)=>Vr(e,`${t}.variants[${n}]`))}:q(`${t}.variants is invalid`)},Ur=(e,t)=>{if(!w(e)||!b(e,`value`))return q(`${t} is invalid`);let{path:n}=e;return!J(n)&&typeof n!=`string`?q(`${t}.path is invalid`):{path:n,value:e.value}},Wr=(e,t)=>{if(J(e))return null;if(!w(e))return q(`${t} is invalid`);let{groups:n,definitions:r,examples:i}=e;return!Array.isArray(n)||n.length===0?q(`${t}.groups is invalid`):w(r)?Array.isArray(i)?{groups:n.map((e,n)=>Hr(e,`${t}.groups[${n}]`)),definitions:r,examples:i.map((e,n)=>Ur(e,`${t}.examples[${n}]`))}:q(`${t}.examples is invalid`):q(`${t}.definitions is invalid`)},Gr=(e,t)=>{let n=`operations[${t}]`;if(!w(e))return q(`${n} must be an object`);let{operationId:r,method:i,pathTemplate:a,summary:o,description:s,effect:c,responseKind:l,queryParams:u,bodyFields:d,wholeBodyField:f,inputSchema:p,fullInputSchema:m,inputDetails:h,inlineArtifacts:g}=e;return typeof r!=`string`||r===``?q(`${n}.operationId is invalid`):Rr(i)?typeof a!=`string`||!a.startsWith(`/`)?q(`${n}.pathTemplate is invalid`):typeof o==`string`?!J(s)&&typeof s!=`string`?q(`${n}.description is invalid`):Br(c)?zr(l)?Lr(u)?!J(d)&&!Lr(d)?q(`${n}.bodyFields is invalid`):!J(f)&&typeof f!=`string`?q(`${n}.wholeBodyField is invalid`):d!=null&&f!=null?q(`${n} declares both bodyFields and wholeBodyField`):w(p)?w(m)?b(e,`changedResource`)?{operationId:r,method:i,pathTemplate:a,summary:o,description:s,effect:c,responseKind:l,queryParams:u,bodyFields:d,wholeBodyField:f,inputSchema:p,fullInputSchema:m,inputDetails:Wr(h,`${n}.inputDetails`),inlineArtifacts:Nr(g,`${n}.inlineArtifacts`),changedResource:Ir(e.changedResource,`${n}.changedResource`)}:q(`${n}.changedResource is missing`):q(`${n}.fullInputSchema is invalid`):q(`${n}.inputSchema is invalid`):q(`${n}.queryParams is invalid`):q(`${n}.responseKind is invalid`):q(`${n}.effect is invalid`):q(`${n}.summary is invalid`):q(`${n}.method is invalid`)},Kr=e=>{if(!w(e))return q(`manifest must be an object`);let t=e.source;if(!w(t)||typeof t.title!=`string`||typeof t.version!=`string`)return q(`manifest.source is invalid`);let n=e.operations;if(!Array.isArray(n))return q(`manifest.operations must be an array`);let r=n.map((e,t)=>Gr(e,t));return new Set(r.map(e=>e.operationId)).size===r.length?{source:{title:t.title,version:t.version},operations:r}:q(`manifest.operations has duplicate operationId`)},qr=(e,t)=>{let n;try{n=ie(e)}catch{throw t(`${e.pathname} cannot be read`)}try{return JSON.parse((e.pathname.endsWith(`.br`)?ae(n):n).toString(`utf8`))}catch{throw t(`${e.pathname} is not valid JSON or brotli`)}},Jr=new URL(`./manifest.json.br`,import.meta.url),Yr=(e=Jr)=>Kr(qr(e,e=>new Ue(`manifest at ${e}`))),Xr=e=>`${e.product}/${e.slug}`,Zr=e=>({articles:e,articleByReference:new Map(e.map(e=>[Xr(e),e])),searchEntries:e.map(e=>({article:e,normalizedTitle:e.title.toLowerCase(),normalizedDescription:e.description.toLowerCase(),normalizedGroup:e.group.toLowerCase(),normalizedBody:e.body.toLowerCase()}))}),Qr=(e,t)=>e.articleByReference.get(t)??null,$r=(e,t)=>{for(let n of t){let t=e.normalizedBody.indexOf(n);if(t===-1)continue;let{body:r}=e.article,i=Math.max(0,t-80),a=Math.min(r.length,t+n.length+80),o=i>0?`…`:``,s=a<r.length?`…`:``;return`${o}${r.slice(i,a).replaceAll(/\s+/g,` `).trim()}${s}`}return e.article.description},ei=(e,t,n)=>{let r=[...new Set(t.toLowerCase().split(/\s+/).filter(e=>e.length>0))];if(r.length===0)return[];let i=[];for(let t of e.searchEntries){let e=0,n=0;for(let i of r){let r=0;t.normalizedTitle.includes(i)&&(r+=10),t.normalizedDescription.includes(i)&&(r+=5),t.normalizedGroup.includes(i)&&(r+=3),t.normalizedBody.includes(i)&&(r+=1),r>0&&(e+=1,n+=r)}e>0&&i.push({entry:t,matchedKeywordCount:e,score:n})}return i.sort((e,t)=>t.matchedKeywordCount===e.matchedKeywordCount?t.score-e.score:t.matchedKeywordCount-e.matchedKeywordCount),i.slice(0,n).map(({entry:e})=>({article:Xr(e.article),title:e.article.title,group:e.article.group,description:e.article.description,snippet:$r(e,r)}))},ti=(e,t)=>{let n=e.replaceAll(/!\[[^\]]*\]\([^)]*\)/g,``),r=[];for(let e of n.split(/\r?\n/))(e.trim()!==``||r.at(-1)?.trim()!==``)&&r.push(e);return r.join(`
|
|
30
|
+
`).replaceAll(/\]\(([^)\s]+)\)/g,(e,n)=>{try{return`](${new URL(n,t).toString()})`}catch{return e}})},Y=`get_product_guide`,X=`search_product_guide`,Z=`read_product_guide_article`,ni=e=>{let t=null,n=()=>(t??=e.loadArticles(),t),r=null,i=()=>(r??=Zr(n().articles),r),a=e.withOverview?`${Y} の一覧か ${X}`:X;return{articlesFile:n,knowledge:i,searchOutcome:(e,t)=>({isError:!1,payload:{results:ei(i(),e,t)}}),readArticleOutcome:t=>{let n=Qr(i(),t);return n==null?{isError:!0,payload:{error:{kind:`guide_article_not_found`,message:`記事 "${t}" はありません。${a} で記事を探し、"${e.exampleArticle}" の形式で指定してください。`}}}:{isError:!1,payload:{article:Xr(n),title:n.title,group:n.group,url:n.url,body:ti(n.body,n.url)}}}}},ri=()=>({isError:!0,payload:{error:{kind:`product_guide_required`,message:`製品の考え方を確認する前の操作は実行しません。先に ${Y} を呼び、依頼に関係する記事を ${Z} で読んでから、この操作をやり直してください。`}}}),ii=e=>{if(!w(e))return null;let{slug:t,title:n,description:r}=e;return typeof t!=`string`||typeof n!=`string`||typeof r!=`string`?null:`- ${t}: ${n}。${r}`},ai=e=>{if(!w(e))return null;let{guides:t}=e;if(!Array.isArray(t)||t.length===0)return null;let n=t.map(e=>ii(e));return n.includes(null)?null:`定義を書くための記事の一覧です。全文は read_advanced_guide に slug を渡して読みます。\n\n${n.join(`
|
|
31
|
+
`)}`},oi=new URL(`./guide-articles.json.br`,import.meta.url),si=/* @__PURE__ */ Me({productLabels:/* @__PURE__ */ je(/* @__PURE__ */ A(),/* @__PURE__ */ A()),articles:/* @__PURE__ */ j(/* @__PURE__ */ Oe(/* @__PURE__ */ Me({product:/* @__PURE__ */ A(),slug:/* @__PURE__ */ A(),title:/* @__PURE__ */ A(),description:/* @__PURE__ */ A(),group:/* @__PURE__ */ A(),order:/* @__PURE__ */ Ae(),body:/* @__PURE__ */ j(/* @__PURE__ */ Oe(/* @__PURE__ */ A()),/* @__PURE__ */ we(e=>e.join(`
|
|
32
|
+
`))),url:/* @__PURE__ */ A()})),/* @__PURE__ */ Ce())}),ci=(e=oi)=>{let t=/* @__PURE__ */ M(si,qr(e,e=>new Ge(`guide articles at ${e}`)));if(!t.success)throw new Ge(`guide articles at ${e.pathname} has an unexpected shape`);return t.output},li=(e,t)=>{let n=[],r=null,i=null;for(let a of e)a.product!==r&&(r=a.product,i=null,n.push(`## ${t[a.product]??a.product}`,``)),a.group!==i&&(i=a.group,n.push(`### ${a.group}`)),n.push(`- ${Xr(a)}: ${a.title}`);return n.join(`
|
|
33
|
+
`)},ui=`# Flyle AI CX の全体像
|
|
33
34
|
|
|
34
35
|
Flyle AI CX は、メール・チャット・アンケート・通話などに散らばった顧客の声(VoC)を 1 か所に集め、AI で分類・要約・可視化し、ワークフローで対応を自動化する製品です。利用者は CS・マーケティング・品質管理などの業務担当者で、エンジニアではありません。
|
|
35
36
|
|
|
@@ -66,13 +67,15 @@ Flyle AI CX は、メール・チャット・アンケート・通話などに
|
|
|
66
67
|
3. 書き込む前に、何をどう変えるか(対象・変更前 → 変更後)を利用者に示して同意を得ます(合意の範囲と確認を省ける場合は、サーバーの指示に従ってください)。レポート・ダッシュボードはプレビュー画像で見た目の同意を得ます。
|
|
67
68
|
4. 書き込んだ後は取得系のツールで結果を確かめ、利用者に報告します。
|
|
68
69
|
|
|
70
|
+
ワークフローを書くときは、先に read_advanced_guide で組み立て方・変数式・使うノードの記事を読み、書いたら validate_workflow で確かめて、error が無くなるまで直してから保存します。
|
|
71
|
+
|
|
69
72
|
## よくある依頼と使う記事
|
|
70
73
|
|
|
71
74
|
- 問い合わせの傾向を調べたい: filter-and-views(絞り込みの考え方)→ search_records で抽出し、集計はレポートのプレビューで示す
|
|
72
75
|
- 問い合わせを自動で分類したい: ai-grouping → create_ai_grouping → start_ai_grouping_job(またはスケジュール)→ get_ai_grouping_job で完了を待つ → list_ai_grouping_groups でグループを確かめ、統合・移動・削除で整える
|
|
73
76
|
- 集計をグラフにしたい・ダッシュボードにまとめたい: report-create と各グラフの記事、dashboard-create / dashboard-layout → preview_report / preview_dashboard → create_*
|
|
74
77
|
- 権限を設計したい: role-management / role-data-filter / user-groups → list_roles / get_role → 変更案の同意 → update_role / update_role_assignments
|
|
75
|
-
- レコードを直したい: table-edit / link-tables(値の形式)→ get_table → search_records / get_record → update_record`,ri={get_current_user:[`role-management`,`public-api`],list_tables:[`table-create-import`,`table-edit`],create_table:[`table-create-import`,`table-edit`],get_table:[`table-edit`,`link-tables`],list_select_options:[`table-edit`,`public-api`],update_table:[`table-edit`],move_table:[`resource-management`],delete_table:[`table-edit`,`trash`],list_table_views:[`filter-and-views`,`split-view`,`dashboard-create`],get_table_view:[`filter-and-views`,`split-view`,`timeline-view`],create_table_view:[`filter-and-views`,`split-view`,`timeline-view`],update_table_view:[`filter-and-views`,`split-view`,`timeline-view`],delete_table_view:[`filter-and-views`],create_field:[`table-edit`,`link-tables`],create_fields:[`table-edit`,`link-tables`],update_field:[`table-edit`],update_fields:[`table-edit`],delete_field:[`table-edit`,`role-data-filter`],create_select_options:[`table-edit`],update_select_options:[`table-edit`],delete_select_options:[`table-edit`,`ai-grouping`],search_records:[`filter-and-views`,`public-api`],get_record:[`table-record-detail`,`public-api`],create_record:[`table-edit`,`link-tables`,`public-api`],update_record:[`table-edit`,`link-tables`,`bulk-update-fields`],delete_record:[`record-trash-delete`,`public-api`],create_records:[`table-edit`,`link-tables`,`public-api`],update_records:[`table-edit`,`link-tables`,`bulk-update-fields`],delete_records:[`record-trash-delete`,`public-api`],create_record_audio_upload_url:[`table-create-import`,`public-api`],attach_record_audio:[`table-create-import`,`public-api`],get_record_audio:[`table-record-detail`,`public-api`],create_record_import:[`table-create-import`,`data-overwrite-update`,`public-api`],start_record_import:[`table-create-import`,`data-overwrite-update`,`public-api`],get_record_import:[`import-export-history`,`public-api`],cancel_record_import:[`import-export-history`,`public-api`],start_record_export:[`data-export`,`public-api`],get_record_export:[`import-export-history`,`public-api`],cancel_record_export:[`import-export-history`,`public-api`],list_reports:[`report-create`],get_report:[`report-create`],preview_report:[`report-create`,`chart-bar`,`pivot-table-layout`],create_report:[`report-create`,`chart-bar`,`pivot-table-layout`],update_report:[`report-create`,`chart-bar`,`pivot-table-layout`],move_report:[`resource-management`],list_dashboards:[`dashboard-create`],get_dashboard:[`dashboard-create`],preview_dashboard:[`dashboard-create`,`dashboard-layout`,`dashboard-filter-view`],create_dashboard:[`dashboard-create`,`dashboard-layout`,`dashboard-filter-view`],update_dashboard:[`dashboard-create`,`dashboard-layout`,`dashboard-filter-view`],move_dashboard:[`resource-management`],list_ai_groupings:[`ai-grouping`],get_ai_grouping:[`ai-grouping`],create_ai_grouping:[`ai-grouping`,`ai-usage`],update_ai_grouping:[`ai-grouping`],delete_ai_grouping:[`ai-grouping`],list_ai_grouping_groups:[`ai-grouping`],create_ai_grouping_group:[`ai-grouping`],reorder_ai_grouping_group:[`ai-grouping`],move_ai_grouping_groups:[`ai-grouping`],merge_ai_grouping_groups:[`ai-grouping`],delete_ai_grouping_group:[`ai-grouping`],start_ai_grouping_job:[`ai-grouping`,`ai-usage`],get_ai_grouping_job:[`ai-grouping`],get_latest_ai_grouping_job:[`ai-grouping`],cancel_ai_grouping_job:[`ai-grouping`],list_roles:[`role-management`,`user-groups`],get_role:[`role-management`,`role-data-filter`],create_role:[`role-management`,`role-data-filter`],update_role:[`role-management`,`role-data-filter`],update_role_assignments:[`role-management`,`user-groups`],delete_role:[`role-management`],list_users:[`invite-users`,`role-management`],get_user:[`invite-users`,`role-management`],invite_user:[`invite-users`,`role-management`,`user-groups`],invite_users:[`invite-users`,`role-management`,`user-groups`],update_user:[`invite-users`],delete_user:[`invite-users`,`user-bulk-import`],list_user_groups:[`user-groups`,`role-management`],get_user_group:[`user-groups`],create_user_group:[`user-groups`,`role-management`],update_user_group:[`user-groups`],update_user_group_members:[`user-groups`],delete_user_group:[`user-groups`],list_folders:[`folder-create-organize`,`public-api`],get_folder:[`folder-create-organize`,`public-api`],create_folder:[`folder-create-organize`,`resource-management`],update_folder:[`folder-create-organize`,`resource-management`],delete_folder:[`resource-management`,`trash`],list_workflows:[`workflow-basics`,`workflow-overview`],get_workflow:[`workflow-basics`,`workflow-advanced-nodes`],create_workflow:[`workflow-basics`,`workflow-advanced-nodes`,`workflow-overview`],update_workflow:[`workflow-basics`,`workflow-advanced-nodes`,`workflow-overview`],move_workflow:[`resource-management`],delete_workflow:[`resource-management`,`trash`],get_workflow_execution:[`workflow-run-history`,`public-api`],list_workflow_runs:[`workflow-run-history`,`public-api`],get_workflow_run:[`workflow-run-history`,`public-api`],download_workflow_run_log:[`workflow-run-history`,`public-api`]},ii={list_tables:{createTool:null,articles:[`table-create-import`,`import-export-history`]},list_workflows:{createTool:`create_workflow`,articles:[`workflow-basics`,`workflow-export-import`]},list_folders:{createTool:null,articles:[`folder-create-organize`]}},ai=e=>e.map(e=>`nexus/${e}`).join(`, `),oi=e=>{let t=ii[e];if(t==null)return null;let n=ai(t.articles);return t.createTool==null?`一覧が空なら、ツールでは作成できないので、画面での作成・インポートを案内してください(記事: ${n})。`:`一覧が空なら ${t.createTool} で作成できます。インポートや画面での作成は記事(${n})を案内してください。`},si=e=>{let t=ri[e];return t==null?null:`先に読む記事: ${ai(t)}`};let ci=null;const li=()=>(ci??=ei(),ci);let ui=null;const di=()=>(ui??=qr(li().articles),ui),fi=()=>{let{articles:e,productLabels:t}=li();return{isError:!1,payload:{guide:`${ni}\n\n# ご利用ガイドの記事一覧\n\n記事の説明は ${X} の結果に、全文は ${Z} にあります。\n\n${ti(e,t)}`}}},pi=(e,t)=>({isError:!1,payload:{results:Xr(di(),e,t)}}),mi=e=>{let t=Jr(di(),e);return t==null?{isError:!0,payload:{error:{kind:`guide_article_not_found`,message:`記事 "${e}" はありません。${Y} の一覧か ${X} で記事を探し、"nexus/table-edit" の形式で指定してください。`}}}:{isError:!1,payload:{article:Kr(t),title:t.title,group:t.group,url:t.url,body:Zr(t.body,t.url)}}},hi=()=>({isError:!0,payload:{error:{kind:`product_guide_required`,message:`製品の考え方を確認する前の操作は実行しません。先に ${Y} を呼び、依頼に関係する記事を ${Z} で読んでから、この操作をやり直してください。`}}}),gi=new ce,_i={},vi={getValidator:e=>gi.getValidator(_i)},yi=`^[0-7][0-9A-HJKMNP-TV-Z]{25}$`,bi=/, (?=data[/ ])/u,xi=/^must have required property '(.+)'$/u,Si=`must match pattern "${yi}"`,Ci=`must be equal to one of the allowed values`,wi=`must be equal to constant`,Ti=/* @__PURE__ */ new Set([`must match a schema in anyOf`,`must match exactly one schema in oneOf`]),Ei=`must be null`,Di=/^\d+$/u,Oi=[`anyOf`,`oneOf`,`allOf`],ki=e=>e.split(`/`).slice(1).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`)),Ai=e=>{let t=e.slice(4),n=t.indexOf(` `),r=ki(n===-1?t:t.slice(0,n)),i=n===-1?e:t.slice(n+1),a=xi.exec(i)?.[1];return a==null?{code:i===`must NOT have additional properties`?`unknown_argument`:`invalid_value`,path:r.join(`.`),message:i}:{code:`required`,path:[...r,a].join(`.`),message:i}},ji=(e,t)=>{let n=/* @__PURE__ */ new Set,r=C(e.$defs)?e.$defs:{},i=(e,t,a)=>{if(!C(e)||a>64)return;let o=e.$ref;typeof o==`string`&&o.startsWith(`#/$defs/`)&&i(r[o.slice(8)],t,a+1);for(let n of Oi){let r=e[n];if(Array.isArray(r))for(let e of r)i(e,t,a+1)}let[s,...c]=t;if(s==null){let t=e.enum;if(Array.isArray(t))for(let e of t)n.add(e);y(e,`const`)&&n.add(e.const);return}let l=e.properties;C(l)&&y(l,s)?i(l[s],c,a+1):C(e.additionalProperties)&&i(e.additionalProperties,c,a+1),Di.test(s)&&i(e.items,c,a+1)};return i(e,t,0),[...n]},Mi=(e,t)=>{let n=e;for(let e of t)if(Array.isArray(n)&&Di.test(e))n=n[Number(e)];else if(C(n)&&y(n,e))n=n[e];else return;return n},Ni=(e,t)=>{if(typeof t!=`string`||t.length>64)return`must be one of ${e.map(e=>JSON.stringify(e)).join(`, `)}`;let n=e.map(e=>({value:e,distance:typeof e==`string`?pe(t,e):1/0})).toSorted((e,t)=>e.distance-t.distance),[r]=n,i=r!=null&&r.distance<=3?` (did you mean ${JSON.stringify(r.value)}?)`:``;return`must be one of ${n.map(e=>JSON.stringify(e.value)).join(`, `)}${i}`},Pi=(e,t,n)=>{if(n.message!==Ci&&n.message!==wi)return n;let r=n.path===``?[]:n.path.split(`.`),i=ji(e,r);return i.length===0?n:{...n,message:Ni(i,Mi(t,r))}},Fi=e=>{let t=/* @__PURE__ */ new Set,n=e.filter(e=>{let n=`${e.code}\u0000${e.path}\u0000${e.message}`;return!t.has(n)&&(t.add(n),!0)}),r=n.filter(e=>!Ti.has(e.message)&&e.message!==Ei).map(e=>e.path),i=new Set(r),a=new Set(r.flatMap(e=>{let t=e.split(`.`);return t.map((e,n)=>t.slice(0,n+1).join(`.`))}));return n.filter(e=>Ti.has(e.message)?!(e.path===``?r.length>0:a.has(e.path)):e.message!==Ei||!i.has(e.path))},Ii=e=>e.slice(0,Math.max(e.lastIndexOf(`.`),0)),Li=e=>{let t=/* @__PURE__ */ new Map;for(let n of e)(n.message===Ci||n.message===wi)&&t.set(n.path,(t.get(n.path)??0)+1);let n=new Set([...t].filter(([e,t])=>t>1&&e.includes(`.`)).map(([e])=>e));if(n.size===0)return[...e];let r=new Set(Array.from(n,e=>Ii(e)));return e.filter(e=>{if(n.has(e.path))return!0;let t=e.path.split(`.`);return!t.some((e,n)=>r.has(t.slice(0,n+1).join(`.`)))})},Ri=(e,t)=>{let n=C(e.properties)?e.properties:{};return b(t).filter(e=>!y(n,e)).map(e=>({code:`unknown_argument`,path:e,message:`is not an argument of this tool`}))},zi=(e,t)=>{let n=C(e.properties)?e.properties[t]:null;return C(n)&&n.pattern===yi},Bi=(e,t)=>[...t.some(e=>e.message===Si)||t.some(t=>t.code===`required`&&zi(e,t.path))?[`IDs are 26-character codes such as 01J9Z3K8Q2M4N6P8R0T2V4X6Y8, not names. Get table IDs with list_tables, field IDs with get_table, and other IDs from the list_* or get_* tool of that resource.`]:[],...t.some(e=>e.code===`unknown_argument`)?[`Remove the arguments that the input schema of this tool does not list.`]:[]],Vi=(e,t)=>{let n=gi.getValidator(t);return r=>{let i=n(r);if(i.valid)return null;let a=i.errorMessage.split(bi).map(e=>Ai(e)),o=Fi([...Li(a.filter(e=>e.code!==`unknown_argument`||e.path!==``)).map(e=>Pi(t,r,e)),...a.some(e=>e.code===`unknown_argument`&&e.path===``)?Ri(t,r):[]]);return{isError:!0,payload:{error:{kind:`invalid_arguments`,code:`invalid_request`,message:`The arguments do not match the input schema of ${e}; nothing was sent to the API.`,issues:o.slice(0,20),hints:Bi(t,o)}}}}};var Hi=class extends Error{constructor(e,t){super(e,t),this.name=`UnsafeSvgError`}},Ui=class extends Hi{bytes;maxBytes;constructor(e,t){super(`svg is ${e.bytes} bytes, exceeding the ${e.maxBytes} byte limit`,t),this.name=`SvgTooLargeError`,this.bytes=e.bytes,this.maxBytes=e.maxBytes}},Wi=/* @__PURE__ */ le((e=>{
|
|
78
|
+
- レコードを直したい: table-edit / link-tables(値の形式)→ get_table → search_records / get_record → update_record`,di={get_current_user:[`role-management`,`public-api`],list_tables:[`table-create-import`,`table-edit`],create_table:[`table-create-import`,`table-edit`],get_table:[`table-edit`,`link-tables`],list_select_options:[`table-edit`,`public-api`],update_table:[`table-edit`],move_table:[`resource-management`],delete_table:[`table-edit`,`trash`],list_table_views:[`filter-and-views`,`split-view`,`dashboard-create`],get_table_view:[`filter-and-views`,`split-view`,`timeline-view`],create_table_view:[`filter-and-views`,`split-view`,`timeline-view`],update_table_view:[`filter-and-views`,`split-view`,`timeline-view`],delete_table_view:[`filter-and-views`],create_field:[`table-edit`,`link-tables`],create_fields:[`table-edit`,`link-tables`],update_field:[`table-edit`],update_fields:[`table-edit`],delete_field:[`table-edit`,`role-data-filter`],create_select_options:[`table-edit`],update_select_options:[`table-edit`],delete_select_options:[`table-edit`,`ai-grouping`],search_records:[`filter-and-views`,`public-api`],get_record:[`table-record-detail`,`public-api`],create_record:[`table-edit`,`link-tables`,`public-api`],update_record:[`table-edit`,`link-tables`,`bulk-update-fields`],delete_record:[`record-trash-delete`,`public-api`],create_records:[`table-edit`,`link-tables`,`public-api`],update_records:[`table-edit`,`link-tables`,`bulk-update-fields`],delete_records:[`record-trash-delete`,`public-api`],create_record_audio_upload_url:[`table-create-import`,`public-api`],attach_record_audio:[`table-create-import`,`public-api`],get_record_audio:[`table-record-detail`,`public-api`],create_record_import:[`table-create-import`,`data-overwrite-update`,`public-api`],start_record_import:[`table-create-import`,`data-overwrite-update`,`public-api`],get_record_import:[`import-export-history`,`public-api`],cancel_record_import:[`import-export-history`,`public-api`],start_record_export:[`data-export`,`public-api`],get_record_export:[`import-export-history`,`public-api`],cancel_record_export:[`import-export-history`,`public-api`],list_reports:[`report-create`],get_report:[`report-create`],preview_report:[`report-create`,`chart-bar`,`pivot-table-layout`],create_report:[`report-create`,`chart-bar`,`pivot-table-layout`],update_report:[`report-create`,`chart-bar`,`pivot-table-layout`],move_report:[`resource-management`],list_dashboards:[`dashboard-create`],get_dashboard:[`dashboard-create`],preview_dashboard:[`dashboard-create`,`dashboard-layout`,`dashboard-filter-view`],create_dashboard:[`dashboard-create`,`dashboard-layout`,`dashboard-filter-view`],update_dashboard:[`dashboard-create`,`dashboard-layout`,`dashboard-filter-view`],move_dashboard:[`resource-management`],list_ai_groupings:[`ai-grouping`],get_ai_grouping:[`ai-grouping`],create_ai_grouping:[`ai-grouping`,`ai-usage`],update_ai_grouping:[`ai-grouping`],delete_ai_grouping:[`ai-grouping`],list_ai_grouping_groups:[`ai-grouping`],create_ai_grouping_group:[`ai-grouping`],reorder_ai_grouping_group:[`ai-grouping`],move_ai_grouping_groups:[`ai-grouping`],merge_ai_grouping_groups:[`ai-grouping`],delete_ai_grouping_group:[`ai-grouping`],start_ai_grouping_job:[`ai-grouping`,`ai-usage`],get_ai_grouping_job:[`ai-grouping`],get_latest_ai_grouping_job:[`ai-grouping`],cancel_ai_grouping_job:[`ai-grouping`],list_roles:[`role-management`,`user-groups`],get_role:[`role-management`,`role-data-filter`],create_role:[`role-management`,`role-data-filter`],update_role:[`role-management`,`role-data-filter`],update_role_assignments:[`role-management`,`user-groups`],delete_role:[`role-management`],list_users:[`invite-users`,`role-management`],get_user:[`invite-users`,`role-management`],invite_user:[`invite-users`,`role-management`,`user-groups`],invite_users:[`invite-users`,`role-management`,`user-groups`],update_user:[`invite-users`],delete_user:[`invite-users`,`user-bulk-import`],list_user_groups:[`user-groups`,`role-management`],get_user_group:[`user-groups`],create_user_group:[`user-groups`,`role-management`],update_user_group:[`user-groups`],update_user_group_members:[`user-groups`],delete_user_group:[`user-groups`],list_folders:[`folder-create-organize`,`public-api`],get_folder:[`folder-create-organize`,`public-api`],create_folder:[`folder-create-organize`,`resource-management`],update_folder:[`folder-create-organize`,`resource-management`],delete_folder:[`resource-management`,`trash`],list_workflows:[`workflow-basics`,`workflow-overview`],get_workflow:[`workflow-basics`,`workflow-advanced-nodes`],create_workflow:[`workflow-basics`,`workflow-advanced-nodes`,`workflow-overview`],update_workflow:[`workflow-basics`,`workflow-advanced-nodes`,`workflow-overview`],validate_workflow:[`public-api`],list_advanced_guides:[`public-api`],read_advanced_guide:[`public-api`],restore_workflow_version:[`workflow-basics`,`public-api`],move_workflow:[`resource-management`],delete_workflow:[`resource-management`,`trash`],get_workflow_execution:[`workflow-run-history`,`public-api`],list_workflow_runs:[`workflow-run-history`,`public-api`],get_workflow_run:[`workflow-run-history`,`public-api`],download_workflow_run_log:[`workflow-run-history`,`public-api`],get_form:[`form-sections`,`form-answer`],update_form:[`form-sections`,`form-answer`],restore_form_version:[`form-sections`,`public-api`]},fi=`nexus`,pi={list_tables:{createTool:null,articles:[`table-create-import`,`import-export-history`]},list_workflows:{createTool:`create_workflow`,articles:[`workflow-basics`,`workflow-export-import`]},list_folders:{createTool:null,articles:[`folder-create-organize`]}},mi=e=>e.map(e=>`${fi}/${e}`).join(`, `),hi=e=>{let t=pi[e];if(t==null)return null;let n=mi(t.articles);return t.createTool==null?`一覧が空なら、ツールでは作成できないので、画面での作成・インポートを案内してください(記事: ${n})。`:`一覧が空なら ${t.createTool} で作成できます。インポートや画面での作成は記事(${n})を案内してください。`},gi=e=>{let t=di[e];return t==null?null:`先に読む記事: ${mi(t)}`},_i=ni({loadArticles:()=>ci(),withOverview:!0,exampleArticle:`${fi}/table-edit`}),{knowledge:vi,searchOutcome:yi,readArticleOutcome:bi}=_i,xi=e=>{let{articles:t,productLabels:n}=_i.articlesFile(),r=e==null?``:`\n\n# 定義の書き方の記事\n\n${e}`;return{isError:!1,payload:{guide:`${ui}\n\n# ご利用ガイドの記事一覧\n\n記事の説明は ${X} の結果に、全文は ${Z} にあります。\n\n${li(t,n)}${r}`}}},Si=new se,Ci={},wi={getValidator:e=>Si.getValidator(Ci)},Ti=`^[0-7][0-9A-HJKMNP-TV-Z]{25}$`,Ei=/, (?=data[/ ])/u,Di=/^must have required property '(.+)'$/u,Oi=`must match pattern "${Ti}"`,ki=`must be equal to one of the allowed values`,Ai=`must be equal to constant`,ji=/* @__PURE__ */ new Set([`must match a schema in anyOf`,`must match exactly one schema in oneOf`]),Mi=`must be null`,Ni=/^\d+$/u,Pi=[`anyOf`,`oneOf`,`allOf`],Fi=e=>e.split(`/`).slice(1).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`)),Ii=e=>{let t=e.slice(4),n=t.indexOf(` `),r=Fi(n===-1?t:t.slice(0,n)),i=n===-1?e:t.slice(n+1),a=Di.exec(i)?.[1];return a==null?{code:i===`must NOT have additional properties`?`unknown_argument`:`invalid_value`,path:r.join(`.`),message:i}:{code:`required`,path:[...r,a].join(`.`),message:i}},Li=(e,t)=>{let n=/* @__PURE__ */ new Set,r=w(e.$defs)?e.$defs:{},i=(e,t,a)=>{if(!w(e)||a>64)return;let o=e.$ref;typeof o==`string`&&o.startsWith(`#/$defs/`)&&i(r[o.slice(8)],t,a+1);for(let n of Pi){let r=e[n];if(Array.isArray(r))for(let e of r)i(e,t,a+1)}let[s,...c]=t;if(s==null){let t=e.enum;if(Array.isArray(t))for(let e of t)n.add(e);b(e,`const`)&&n.add(e.const);return}let l=e.properties;w(l)&&b(l,s)?i(l[s],c,a+1):w(e.additionalProperties)&&i(e.additionalProperties,c,a+1),Ni.test(s)&&i(e.items,c,a+1)};return i(e,t,0),[...n]},Ri=(e,t)=>{let n=e;for(let e of t)if(Array.isArray(n)&&Ni.test(e))n=n[Number(e)];else if(w(n)&&b(n,e))n=n[e];else return;return n},zi=(e,t)=>{if(typeof t!=`string`||t.length>64)return`must be one of ${e.map(e=>JSON.stringify(e)).join(`, `)}`;let n=e.map(e=>({value:e,distance:typeof e==`string`?fe(t,e):1/0})).toSorted((e,t)=>e.distance-t.distance),[r]=n,i=r!=null&&r.distance<=3?` (did you mean ${JSON.stringify(r.value)}?)`:``;return`must be one of ${n.map(e=>JSON.stringify(e.value)).join(`, `)}${i}`},Bi=(e,t,n)=>{if(n.message!==ki&&n.message!==Ai)return n;let r=n.path===``?[]:n.path.split(`.`),i=Li(e,r);return i.length===0?n:{...n,message:zi(i,Ri(t,r))}},Vi=e=>{let t=/* @__PURE__ */ new Set,n=e.filter(e=>{let n=`${e.code}\u0000${e.path}\u0000${e.message}`;return!t.has(n)&&(t.add(n),!0)}),r=n.filter(e=>!ji.has(e.message)&&e.message!==Mi).map(e=>e.path),i=new Set(r),a=new Set(r.flatMap(e=>{let t=e.split(`.`);return t.map((e,n)=>t.slice(0,n+1).join(`.`))}));return n.filter(e=>ji.has(e.message)?!(e.path===``?r.length>0:a.has(e.path)):e.message!==Mi||!i.has(e.path))},Hi=e=>e.slice(0,Math.max(e.lastIndexOf(`.`),0)),Ui=e=>{let t=/* @__PURE__ */ new Map;for(let n of e)(n.message===ki||n.message===Ai)&&t.set(n.path,(t.get(n.path)??0)+1);let n=new Set([...t].filter(([e,t])=>t>1&&e.includes(`.`)).map(([e])=>e));if(n.size===0)return[...e];let r=new Set(Array.from(n,e=>Hi(e)));return e.filter(e=>{if(n.has(e.path))return!0;let t=e.path.split(`.`);return!t.some((e,n)=>r.has(t.slice(0,n+1).join(`.`)))})},Wi=(e,t)=>{let n=w(e.properties)?e.properties:{};return x(t).filter(e=>!b(n,e)).map(e=>({code:`unknown_argument`,path:e,message:`is not an argument of this tool`}))},Gi=(e,t)=>{let n=w(e.properties)?e.properties[t]:null;return w(n)&&n.pattern===Ti},Ki=(e,t)=>[...t.some(e=>e.message===Oi)||t.some(t=>t.code===`required`&&Gi(e,t.path))?[`IDs are 26-character codes such as 01J9Z3K8Q2M4N6P8R0T2V4X6Y8, not names. Get table IDs with list_tables, field IDs with get_table, and other IDs from the list_* or get_* tool of that resource.`]:[],...t.some(e=>e.code===`unknown_argument`)?[`Remove the arguments that the input schema of this tool does not list.`]:[]],qi=(e,t)=>{let n=Si.getValidator(t);return r=>{let i=n(r);if(i.valid)return null;let a=i.errorMessage.split(Ei).map(e=>Ii(e)),o=Vi([...Ui(a.filter(e=>e.code!==`unknown_argument`||e.path!==``)).map(e=>Bi(t,r,e)),...a.some(e=>e.code===`unknown_argument`&&e.path===``)?Wi(t,r):[]]);return{isError:!0,payload:{error:{kind:`invalid_arguments`,code:`invalid_request`,message:`The arguments do not match the input schema of ${e}; nothing was sent to the API.`,issues:o.slice(0,20),hints:Ki(t,o)}}}}};var Ji=class extends Error{constructor(e,t){super(e,t),this.name=`UnsafeSvgError`}},Yi=class extends Ji{bytes;maxBytes;constructor(e,t){super(`svg is ${e.bytes} bytes, exceeding the ${e.maxBytes} byte limit`,t),this.name=`SvgTooLargeError`,this.bytes=e.bytes,this.maxBytes=e.maxBytes}},Xi=/* @__PURE__ */ ce((e=>{
|
|
76
79
|
/**
|
|
77
80
|
* Character classes and associated utilities for the 5th edition of XML 1.0.
|
|
78
81
|
*
|
|
@@ -82,7 +85,7 @@ Flyle AI CX は、メール・チャット・アンケート・通話などに
|
|
|
82
85
|
*/
|
|
83
86
|
Object.defineProperty(e,"__esModule",{value:!0}),e.CHAR=`
|
|
84
87
|
\r --�𐀀-`,e.S=` \r
|
|
85
|
-
`,e.NAME_START_CHAR=`:A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-⁰-Ⰰ-、-豈-﷏ﷰ-�𐀀-`,e.NAME_CHAR=`-`+e.NAME_START_CHAR+`.0-9·̀-ͯ‿-⁀`,e.CHAR_RE=RegExp(`^[`+e.CHAR+`]$`,`u`),e.S_RE=RegExp(`^[`+e.S+`]+$`,`u`),e.NAME_START_CHAR_RE=RegExp(`^[`+e.NAME_START_CHAR+`]$`,`u`),e.NAME_CHAR_RE=RegExp(`^[`+e.NAME_CHAR+`]$`,`u`),e.NAME_RE=RegExp(`^[`+e.NAME_START_CHAR+`][`+e.NAME_CHAR+`]*$`,`u`),e.NMTOKEN_RE=RegExp(`^[`+e.NAME_CHAR+`]+$`,`u`);var t=9,n=10,r=13,i=32;e.S_LIST=[i,n,r,t];function a(e){return e>=i&&e<=55295||e===n||e===r||e===t||e>=57344&&e<=65533||e>=65536&&e<=1114111}e.isChar=a;function o(e){return e===i||e===n||e===r||e===t}e.isS=o;function s(e){return e>=65&&e<=90||e>=97&&e<=122||e===58||e===95||e===8204||e===8205||e>=192&&e<=214||e>=216&&e<=246||e>=248&&e<=767||e>=880&&e<=893||e>=895&&e<=8191||e>=8304&&e<=8591||e>=11264&&e<=12271||e>=12289&&e<=55295||e>=63744&&e<=64975||e>=65008&&e<=65533||e>=65536&&e<=983039}e.isNameStartChar=s;function c(e){return s(e)||e>=48&&e<=57||e===45||e===46||e===183||e>=768&&e<=879||e>=8255&&e<=8256}e.isNameChar=c})),
|
|
88
|
+
`,e.NAME_START_CHAR=`:A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-⁰-Ⰰ-、-豈-﷏ﷰ-�𐀀-`,e.NAME_CHAR=`-`+e.NAME_START_CHAR+`.0-9·̀-ͯ‿-⁀`,e.CHAR_RE=RegExp(`^[`+e.CHAR+`]$`,`u`),e.S_RE=RegExp(`^[`+e.S+`]+$`,`u`),e.NAME_START_CHAR_RE=RegExp(`^[`+e.NAME_START_CHAR+`]$`,`u`),e.NAME_CHAR_RE=RegExp(`^[`+e.NAME_CHAR+`]$`,`u`),e.NAME_RE=RegExp(`^[`+e.NAME_START_CHAR+`][`+e.NAME_CHAR+`]*$`,`u`),e.NMTOKEN_RE=RegExp(`^[`+e.NAME_CHAR+`]+$`,`u`);var t=9,n=10,r=13,i=32;e.S_LIST=[i,n,r,t];function a(e){return e>=i&&e<=55295||e===n||e===r||e===t||e>=57344&&e<=65533||e>=65536&&e<=1114111}e.isChar=a;function o(e){return e===i||e===n||e===r||e===t}e.isS=o;function s(e){return e>=65&&e<=90||e>=97&&e<=122||e===58||e===95||e===8204||e===8205||e>=192&&e<=214||e>=216&&e<=246||e>=248&&e<=767||e>=880&&e<=893||e>=895&&e<=8191||e>=8304&&e<=8591||e>=11264&&e<=12271||e>=12289&&e<=55295||e>=63744&&e<=64975||e>=65008&&e<=65533||e>=65536&&e<=983039}e.isNameStartChar=s;function c(e){return s(e)||e>=48&&e<=57||e===45||e===46||e===183||e>=768&&e<=879||e>=8255&&e<=8256}e.isNameChar=c})),Zi=/* @__PURE__ */ ce((e=>{
|
|
86
89
|
/**
|
|
87
90
|
* Character classes and associated utilities for the 2nd edition of XML 1.1.
|
|
88
91
|
*
|
|
@@ -91,7 +94,7 @@ Object.defineProperty(e,"__esModule",{value:!0}),e.CHAR=`
|
|
|
91
94
|
* @copyright Louis-Dominique Dubeau
|
|
92
95
|
*/
|
|
93
96
|
Object.defineProperty(e,"__esModule",{value:!0}),e.CHAR=`--�𐀀-`,e.RESTRICTED_CHAR=`-\b\v\f---`,e.S=` \r
|
|
94
|
-
`,e.NAME_START_CHAR=`:A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-⁰-Ⰰ-、-豈-﷏ﷰ-�𐀀-`,e.NAME_CHAR=`-`+e.NAME_START_CHAR+`.0-9·̀-ͯ‿-⁀`,e.CHAR_RE=RegExp(`^[`+e.CHAR+`]$`,`u`),e.RESTRICTED_CHAR_RE=RegExp(`^[`+e.RESTRICTED_CHAR+`]$`,`u`),e.S_RE=RegExp(`^[`+e.S+`]+$`,`u`),e.NAME_START_CHAR_RE=RegExp(`^[`+e.NAME_START_CHAR+`]$`,`u`),e.NAME_CHAR_RE=RegExp(`^[`+e.NAME_CHAR+`]$`,`u`),e.NAME_RE=RegExp(`^[`+e.NAME_START_CHAR+`][`+e.NAME_CHAR+`]*$`,`u`),e.NMTOKEN_RE=RegExp(`^[`+e.NAME_CHAR+`]+$`,`u`);var t=9,n=10,r=13,i=32;e.S_LIST=[i,n,r,t];function a(e){return e>=1&&e<=55295||e>=57344&&e<=65533||e>=65536&&e<=1114111}e.isChar=a;function o(e){return e>=1&&e<=8||e===11||e===12||e>=14&&e<=31||e>=127&&e<=132||e>=134&&e<=159}e.isRestrictedChar=o;function s(e){return e===9||e===10||e===13||e>31&&e<127||e===133||e>159&&e<=55295||e>=57344&&e<=65533||e>=65536&&e<=1114111}e.isCharAndNotRestricted=s;function c(e){return e===i||e===n||e===r||e===t}e.isS=c;function l(e){return e>=65&&e<=90||e>=97&&e<=122||e===58||e===95||e===8204||e===8205||e>=192&&e<=214||e>=216&&e<=246||e>=248&&e<=767||e>=880&&e<=893||e>=895&&e<=8191||e>=8304&&e<=8591||e>=11264&&e<=12271||e>=12289&&e<=55295||e>=63744&&e<=64975||e>=65008&&e<=65533||e>=65536&&e<=983039}e.isNameStartChar=l;function u(e){return l(e)||e>=48&&e<=57||e===45||e===46||e===183||e>=768&&e<=879||e>=8255&&e<=8256}e.isNameChar=u})),
|
|
97
|
+
`,e.NAME_START_CHAR=`:A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-⁰-Ⰰ-、-豈-﷏ﷰ-�𐀀-`,e.NAME_CHAR=`-`+e.NAME_START_CHAR+`.0-9·̀-ͯ‿-⁀`,e.CHAR_RE=RegExp(`^[`+e.CHAR+`]$`,`u`),e.RESTRICTED_CHAR_RE=RegExp(`^[`+e.RESTRICTED_CHAR+`]$`,`u`),e.S_RE=RegExp(`^[`+e.S+`]+$`,`u`),e.NAME_START_CHAR_RE=RegExp(`^[`+e.NAME_START_CHAR+`]$`,`u`),e.NAME_CHAR_RE=RegExp(`^[`+e.NAME_CHAR+`]$`,`u`),e.NAME_RE=RegExp(`^[`+e.NAME_START_CHAR+`][`+e.NAME_CHAR+`]*$`,`u`),e.NMTOKEN_RE=RegExp(`^[`+e.NAME_CHAR+`]+$`,`u`);var t=9,n=10,r=13,i=32;e.S_LIST=[i,n,r,t];function a(e){return e>=1&&e<=55295||e>=57344&&e<=65533||e>=65536&&e<=1114111}e.isChar=a;function o(e){return e>=1&&e<=8||e===11||e===12||e>=14&&e<=31||e>=127&&e<=132||e>=134&&e<=159}e.isRestrictedChar=o;function s(e){return e===9||e===10||e===13||e>31&&e<127||e===133||e>159&&e<=55295||e>=57344&&e<=65533||e>=65536&&e<=1114111}e.isCharAndNotRestricted=s;function c(e){return e===i||e===n||e===r||e===t}e.isS=c;function l(e){return e>=65&&e<=90||e>=97&&e<=122||e===58||e===95||e===8204||e===8205||e>=192&&e<=214||e>=216&&e<=246||e>=248&&e<=767||e>=880&&e<=893||e>=895&&e<=8191||e>=8304&&e<=8591||e>=11264&&e<=12271||e>=12289&&e<=55295||e>=63744&&e<=64975||e>=65008&&e<=65533||e>=65536&&e<=983039}e.isNameStartChar=l;function u(e){return l(e)||e>=48&&e<=57||e===45||e===46||e===183||e>=768&&e<=879||e>=8255&&e<=8256}e.isNameChar=u})),Qi=/* @__PURE__ */ ce((e=>{
|
|
95
98
|
/**
|
|
96
99
|
* Character class utilities for XML NS 1.0 edition 3.
|
|
97
100
|
*
|
|
@@ -99,24 +102,25 @@ Object.defineProperty(e,"__esModule",{value:!0}),e.CHAR=`--�𐀀-`,
|
|
|
99
102
|
* @license MIT
|
|
100
103
|
* @copyright Louis-Dominique Dubeau
|
|
101
104
|
*/
|
|
102
|
-
Object.defineProperty(e,"__esModule",{value:!0}),e.NC_NAME_START_CHAR=`A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ--⁰-Ⰰ-、-豈-﷏ﷰ-�𐀀-`,e.NC_NAME_CHAR=`-`+e.NC_NAME_START_CHAR+`.0-9·̀-ͯ‿-⁀`,e.NC_NAME_START_CHAR_RE=RegExp(`^[`+e.NC_NAME_START_CHAR+`]$`,`u`),e.NC_NAME_CHAR_RE=RegExp(`^[`+e.NC_NAME_CHAR+`]$`,`u`),e.NC_NAME_RE=RegExp(`^[`+e.NC_NAME_START_CHAR+`][`+e.NC_NAME_CHAR+`]*$`,`u`);function t(e){return e>=65&&e<=90||e===95||e>=97&&e<=122||e>=192&&e<=214||e>=216&&e<=246||e>=248&&e<=767||e>=880&&e<=893||e>=895&&e<=8191||e>=8204&&e<=8205||e>=8304&&e<=8591||e>=11264&&e<=12271||e>=12289&&e<=55295||e>=63744&&e<=64975||e>=65008&&e<=65533||e>=65536&&e<=983039}e.isNCNameStartChar=t;function n(e){return t(e)||e===45||e===46||e>=48&&e<=57||e===183||e>=768&&e<=879||e>=8255&&e<=8256}e.isNCNameChar=n}))
|
|
103
|
-
${h}.`);break;case m:switch(t){case`xml`:break;case``:e.fail(`the default namespace may not be set to ${n}.`);break;default:e.fail(`may not assign the xml namespace to another prefix.`)}}}function v(e,t){for(let n of Object.keys(t))se(e,n,t[n])}let ce=e=>p.test(e),le=e=>l.test(e);e.EVENTS=[`xmldecl`,`text`,`processinginstruction`,`doctype`,`comment`,`opentagstart`,`attribute`,`opentag`,`closetag`,`cdata`,`error`,`end`,`ready`];let y={xmldecl:`xmldeclHandler`,text:`textHandler`,processinginstruction:`piHandler`,doctype:`doctypeHandler`,comment:`commentHandler`,opentagstart:`openTagStartHandler`,attribute:`attributeHandler`,opentag:`openTagHandler`,closetag:`closeTagHandler`,cdata:`cdataHandler`,error:`errorHandler`,end:`endHandler`,ready:`readyHandler`};e.SaxesParser=class{constructor(e){this.opt=e??{},this.fragmentOpt=!!this.opt.fragment;let t=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,t){this.nameStartCheck=d,this.nameCheck=f,this.isName=ce,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},ee);let e=this.opt.additionalNamespaces;e!=null&&(v(this,e),Object.assign(this.ns,e))}else this.nameStartCheck=o,this.nameCheck=s,this.isName=le,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}get closed(){return this._closed}_init(){var e;this.openWakaBang=``,this.text=``,this.name=``,this.piTarget=``,this.entity=``,this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk=``,this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=0,this.attribList=[];let{fragmentOpt:t}=this;this.state=t?13:0,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=t,this.xmlDeclPossible=!t,this.xmlDeclExpects=[`version`],this.entityReturnState=void 0;let{defaultXMLVersion:n}=this.opt;if(n===void 0){if(this.opt.forceXMLVersion===!0)throw Error(`forceXMLVersion set but defaultXMLVersion is not set`);n=`1.0`}this.setXMLVersion(n),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(g),(e=this.readyHandler)==null||e.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(e,t){this[y[e]]=t}off(e){this[y[e]]=void 0}makeError(e){let t=this.fileName??``;return this.trackPosition&&(t.length>0&&(t+=`:`),t+=`${this.line}:${this.column}`),t.length>0&&(t+=`: `),Error(t+e)}fail(e){let t=this.makeError(e),n=this.errorHandler;if(n===void 0)throw t;return n(t),this}write(e){if(this.closed)return this.fail(`cannot write after close; assign an onready handler.`);let t=!1;e===null?(t=!0,e=``):typeof e==`object`&&(e=e.toString()),this.carriedFromPrevious!==void 0&&(e=`${this.carriedFromPrevious}${e}`,this.carriedFromPrevious=void 0);let n=e.length,r=e.charCodeAt(n-1);!t&&(r===13||r>=55296&&r<=56319)&&(this.carriedFromPrevious=e[n-1],n--,e=e.slice(0,n));let{stateTable:i}=this;for(this.chunk=e,this.i=0;this.i<n;)i[this.state].call(this);return this.chunkPosition+=n,t?this.end():this}close(){return this.write(null)}getCode10(){let{chunk:e,i:t}=this;if(this.prevI=t,this.i=t+1,t>=e.length)return-1;let n=e.charCodeAt(t);if(this.column++,n<55296){if(n>=32||n===9)return n;switch(n){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:return e.charCodeAt(t+1)===10&&(this.i=t+2),this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail(`disallowed character.`),n}}if(n>56319)return n>=57344&&n<=65533||this.fail(`disallowed character.`),n;let r=65536+(n-55296)*1024+(e.charCodeAt(t+1)-56320);return this.i=t+2,r>1114111&&this.fail(`disallowed character.`),r}getCode11(){let{chunk:e,i:t}=this;if(this.prevI=t,this.i=t+1,t>=e.length)return-1;let n=e.charCodeAt(t);if(this.column++,n<55296){if(n>31&&n<127||n>159&&n!==te||n===9)return n;switch(n){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:{let n=e.charCodeAt(t+1);(n===10||n===133)&&(this.i=t+2)}case 133:case te:return this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail(`disallowed character.`),n}}if(n>56319)return n>=57344&&n<=65533||this.fail(`disallowed character.`),n;let r=65536+(n-55296)*1024+(e.charCodeAt(t+1)-56320);return this.i=t+2,r>1114111&&this.fail(`disallowed character.`),r}getCodeNorm(){let e=this.getCode();return e===-2?10:e}unget(){this.i=this.prevI,this.column--}captureTo(e){let{i:t}=this,{chunk:n}=this;for(;;){let r=this.getCode(),i=r===-2,a=i?10:r;if(a===-1||e.includes(a))return this.text+=n.slice(t,this.prevI),a;i&&(this.text+=`${n.slice(t,this.prevI)}\n`,t=this.i)}}captureToChar(e){let{i:t}=this,{chunk:n}=this;for(;;){let r=this.getCode();switch(r){case-2:this.text+=`${n.slice(t,this.prevI)}\n`,t=this.i,r=10;break;case-1:return this.text+=n.slice(t),!1}if(r===e)return this.text+=n.slice(t,this.prevI),!0}}captureNameChars(){let{chunk:e,i:t}=this;for(;;){let n=this.getCode();if(n===-1)return this.name+=e.slice(t),-1;if(!s(n))return this.name+=e.slice(t,this.prevI),n===-2?10:n}}skipSpaces(){for(;;){let e=this.getCodeNorm();if(e===-1||!i(e))return e}}setXMLVersion(e){this.currentXMLVersion=e,e===`1.0`?(this.isChar=a,this.getCode=this.getCode10):(this.isChar=u,this.getCode=this.getCode11)}sBegin(){this.chunk.charCodeAt(0)===65279&&(this.i++,this.column++),this.state=1}sBeginWhitespace(){let e=this.i,t=this.skipSpaces();switch(this.prevI!==e&&(this.xmlDeclPossible=!1),t){case 60:if(this.state=15,this.text.length!==0)throw Error(`no-empty text at start`);break;case-1:break;default:this.unget(),this.state=13,this.xmlDeclPossible=!1}}sDoctype(){var e;let t=this.captureTo(re);switch(t){case 62:(e=this.doctypeHandler)==null||e.call(this,this.text),this.text=``,this.state=13,this.doctype=!0;break;case-1:break;default:this.text+=String.fromCodePoint(t),t===91?this.state=4:_(t)&&(this.state=3,this.q=t)}}sDoctypeQuote(){let e=this.q;this.captureToChar(e)&&(this.text+=String.fromCodePoint(e),this.q=null,this.state=2)}sDTD(){let e=this.captureTo(ie);e!==-1&&(this.text+=String.fromCodePoint(e),e===93?this.state=2:e===60?this.state=6:_(e)&&(this.state=5,this.q=e))}sDTDQuoted(){let e=this.q;this.captureToChar(e)&&(this.text+=String.fromCodePoint(e),this.state=4,this.q=null)}sDTDOpenWaka(){let e=this.getCodeNorm();switch(this.text+=String.fromCodePoint(e),e){case 33:this.state=7,this.openWakaBang=``;break;case 63:this.state=11;break;default:this.state=4}}sDTDOpenWakaBang(){let e=String.fromCodePoint(this.getCodeNorm()),t=this.openWakaBang+=e;this.text+=e,t!==`-`&&(this.state=t===`--`?8:4,this.openWakaBang=``)}sDTDComment(){this.captureToChar(45)&&(this.text+=`-`,this.state=9)}sDTDCommentEnding(){let e=this.getCodeNorm();this.text+=String.fromCodePoint(e),this.state=e===45?10:8}sDTDCommentEnded(){let e=this.getCodeNorm();this.text+=String.fromCodePoint(e),e===62?this.state=4:(this.fail(`malformed comment.`),this.state=8)}sDTDPI(){this.captureToChar(63)&&(this.text+=`?`,this.state=12)}sDTDPIEnding(){let e=this.getCodeNorm();this.text+=String.fromCodePoint(e),e===62&&(this.state=4)}sText(){this.tags.length===0?this.handleTextOutsideRoot():this.handleTextInRoot()}sEntity(){let{i:e}=this,{chunk:t}=this;loop:for(;;)switch(this.getCode()){case-2:this.entity+=`${t.slice(e,this.prevI)}\n`,e=this.i;break;case 59:{let{entityReturnState:n}=this,r=this.entity+t.slice(e,this.prevI);this.state=n;let i;r===``?(this.fail(`empty entity name.`),i=`&;`):(i=this.parseEntity(r),this.entity=``),(n!==13||this.textHandler!==void 0)&&(this.text+=i);break loop}case-1:this.entity+=t.slice(e);break loop}}sOpenWaka(){let e=this.getCode();if(o(e))this.state=34,this.unget(),this.xmlDeclPossible=!1;else switch(e){case 47:this.state=43,this.xmlDeclPossible=!1;break;case 33:this.state=16,this.openWakaBang=``,this.xmlDeclPossible=!1;break;case 63:this.state=23;break;default:this.fail(`disallowed character in tag name`),this.state=13,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case`[CDATA[`:!this.sawRoot&&!this.reportedTextBeforeRoot&&(this.fail(`text data outside of root node.`),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail(`text data outside of root node.`),this.reportedTextAfterRoot=!0),this.state=20,this.openWakaBang=``;break;case`--`:this.state=17,this.openWakaBang=``;break;case`DOCTYPE`:this.state=2,(this.doctype||this.sawRoot)&&this.fail(`inappropriately located doctype declaration.`),this.openWakaBang=``;break;default:this.openWakaBang.length>=7&&this.fail(`incorrect syntax.`)}}sComment(){this.captureToChar(45)&&(this.state=18)}sCommentEnding(){var e;let t=this.getCodeNorm();t===45?(this.state=19,(e=this.commentHandler)==null||e.call(this,this.text),this.text=``):(this.text+=`-${String.fromCodePoint(t)}`,this.state=17)}sCommentEnded(){let e=this.getCodeNorm();e===62?this.state=13:(this.fail(`malformed comment.`),this.text+=`--${String.fromCodePoint(e)}`,this.state=17)}sCData(){this.captureToChar(93)&&(this.state=21)}sCDataEnding(){let e=this.getCodeNorm();e===93?this.state=22:(this.text+=`]${String.fromCodePoint(e)}`,this.state=20)}sCDataEnding2(){var e;let t=this.getCodeNorm();switch(t){case 62:(e=this.cdataHandler)==null||e.call(this,this.text),this.text=``,this.state=13;break;case 93:this.text+=`]`;break;default:this.text+=`]]${String.fromCodePoint(t)}`,this.state=20}}sPIFirstChar(){let e=this.getCodeNorm();this.nameStartCheck(e)?(this.piTarget+=String.fromCodePoint(e),this.state=24):e===63||i(e)?(this.fail(`processing instruction without a target.`),this.state=e===63?26:25):(this.fail(`disallowed character in processing instruction name.`),this.piTarget+=String.fromCodePoint(e),this.state=24)}sPIRest(){let{chunk:e,i:t}=this;for(;;){let n=this.getCodeNorm();if(n===-1){this.piTarget+=e.slice(t);return}if(!this.nameCheck(n)){this.piTarget+=e.slice(t,this.prevI);let r=n===63;r||i(n)?this.piTarget===`xml`?(this.xmlDeclPossible||this.fail(`an XML declaration must be at the start of the document.`),this.state=r?33:27):this.state=r?26:25:(this.fail(`disallowed character in processing instruction name.`),this.piTarget+=String.fromCodePoint(n));break}}}sPIBody(){if(this.text.length===0){let e=this.getCodeNorm();e===63?this.state=26:i(e)||(this.text=String.fromCodePoint(e))}else this.captureToChar(63)&&(this.state=26)}sPIEnding(){var e;let t=this.getCodeNorm();if(t===62){let{piTarget:t}=this;t.toLowerCase()===`xml`&&this.fail(`the XML declaration must appear at the start of the document.`),(e=this.piHandler)==null||e.call(this,{target:t,body:this.text}),this.piTarget=this.text=``,this.state=13}else t===63?this.text+=`?`:(this.text+=`?${String.fromCodePoint(t)}`,this.state=25);this.xmlDeclPossible=!1}sXMLDeclNameStart(){let e=this.skipSpaces();e===63?this.state=33:e!==-1&&(this.state=28,this.name=String.fromCodePoint(e))}sXMLDeclName(){let e=this.captureTo(ae);if(e===63)this.state=33,this.name+=this.text,this.text=``,this.fail(`XML declaration is incomplete.`);else if(i(e)||e===61){if(this.name+=this.text,this.text=``,!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail(`did not expect any more name/value pairs.`);break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(`, `)}`)}this.state=e===61?30:29}}sXMLDeclEq(){let e=this.getCodeNorm();e===63?(this.state=33,this.fail(`XML declaration is incomplete.`)):i(e)||(e!==61&&this.fail(`value required.`),this.state=30)}sXMLDeclValueStart(){let e=this.getCodeNorm();e===63?(this.state=33,this.fail(`XML declaration is incomplete.`)):i(e)||(_(e)?this.q=e:(this.fail(`value must be quoted.`),this.q=32),this.state=31)}sXMLDeclValue(){let e=this.captureTo([this.q,63]);if(e===63){this.state=33,this.text=``,this.fail(`XML declaration is incomplete.`);return}if(e===-1)return;let t=this.text;switch(this.text=``,this.name){case`version`:{this.xmlDeclExpects=[`encoding`,`standalone`];let e=t;this.xmlDecl.version=e,/^1\.[0-9]+$/.test(e)?this.opt.forceXMLVersion||this.setXMLVersion(e):this.fail(`version number must match /^1\\.[0-9]+$/.`);break}case`encoding`:/^[A-Za-z][A-Za-z0-9._-]*$/.test(t)||this.fail(`encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/.`),this.xmlDeclExpects=[`standalone`],this.xmlDecl.encoding=t;break;case`standalone`:t!==`yes`&&t!==`no`&&this.fail(`standalone value must match "yes" or "no".`),this.xmlDeclExpects=[],this.xmlDecl.standalone=t}this.name=``,this.state=32}sXMLDeclSeparator(){let e=this.getCodeNorm();e===63?this.state=33:(i(e)||(this.fail(`whitespace required.`),this.unget()),this.state=27)}sXMLDeclEnding(){var e;this.getCodeNorm()===62?(this.piTarget===`xml`?this.name!==`version`&&this.xmlDeclExpects.includes(`version`)&&this.fail(`XML declaration must contain a version.`):this.fail(`processing instructions are not allowed before root.`),(e=this.xmldeclHandler)==null||e.call(this,this.xmlDecl),this.name=``,this.piTarget=this.text=``,this.state=13):this.fail(`The character ? is disallowed anywhere in XML declarations.`),this.xmlDeclPossible=!1}sOpenTag(){var e;let t=this.captureNameChars();if(t===-1)return;let n=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name=``,this.xmlnsOpt&&(this.topNS=n.ns=Object.create(null)),(e=this.openTagStartHandler)==null||e.call(this,n),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail(`documents may contain only one root.`),t){case 62:this.openTag();break;case 47:this.state=35;break;default:i(t)||this.fail(`disallowed character in tag name.`),this.state=36}}sOpenTagSlash(){this.getCode()===62?this.openSelfClosingTag():(this.fail(`forward-slash in opening tag not followed by >.`),this.state=36)}sAttrib(){let e=this.skipSpaces();e!==-1&&(o(e)?(this.unget(),this.state=37):e===62?this.openTag():e===47?this.state=35:this.fail(`disallowed character in attribute name.`))}sAttribName(){let e=this.captureNameChars();e===61?this.state=39:i(e)?this.state=38:e===62?(this.fail(`attribute without value.`),this.pushAttrib(this.name,this.name),this.name=this.text=``,this.openTag()):e!==-1&&this.fail(`disallowed character in attribute name.`)}sAttribNameSawWhite(){let e=this.skipSpaces();switch(e){case-1:return;case 61:this.state=39;break;default:this.fail(`attribute without value.`),this.text=``,this.name=``,e===62?this.openTag():o(e)?(this.unget(),this.state=37):(this.fail(`disallowed character in attribute name.`),this.state=36)}}sAttribValue(){let e=this.getCodeNorm();_(e)?(this.q=e,this.state=40):i(e)||(this.fail(`unquoted attribute value.`),this.state=42,this.unget())}sAttribValueQuoted(){let{q:e,chunk:t}=this,{i:n}=this;for(;;)switch(this.getCode()){case e:this.pushAttrib(this.name,this.text+t.slice(n,this.prevI)),this.name=this.text=``,this.q=null,this.state=41;return;case 38:this.text+=t.slice(n,this.prevI),this.state=14,this.entityReturnState=40;return;case 10:case-2:case 9:this.text+=`${t.slice(n,this.prevI)} `,n=this.i;break;case 60:this.text+=t.slice(n,this.prevI),this.fail(`disallowed character.`);return;case-1:this.text+=t.slice(n);return}}sAttribValueClosed(){let e=this.getCodeNorm();i(e)?this.state=36:e===62?this.openTag():e===47?this.state=35:o(e)?(this.fail(`no whitespace between attributes.`),this.unget(),this.state=37):this.fail(`disallowed character in attribute name.`)}sAttribValueUnquoted(){let e=this.captureTo(oe);switch(e){case 38:this.state=14,this.entityReturnState=42;break;case 60:this.fail(`disallowed character.`);break;case-1:break;default:this.text.includes(`]]>`)&&this.fail(`the string "]]>" is disallowed in char data.`),this.pushAttrib(this.name,this.text),this.name=this.text=``,e===62?this.openTag():this.state=36}}sCloseTag(){let e=this.captureNameChars();e===62?this.closeTag():i(e)?this.state=44:e!==-1&&this.fail(`disallowed character in closing tag.`)}sCloseTagSawWhite(){switch(this.skipSpaces()){case 62:this.closeTag();break;case-1:break;default:this.fail(`disallowed character in closing tag.`)}}handleTextInRoot(){let{i:e,forbiddenState:t}=this,{chunk:n,textHandler:r}=this;scanLoop:for(;;)switch(this.getCode()){case 60:if(this.state=15,r!==void 0){let{text:t}=this,i=n.slice(e,this.prevI);t.length===0?i.length!==0&&r(i):(r(t+i),this.text=``)}t=0;break scanLoop;case 38:this.state=14,this.entityReturnState=13,r!==void 0&&(this.text+=n.slice(e,this.prevI)),t=0;break scanLoop;case 93:switch(t){case 0:t=1;break;case 1:t=2;break;case 2:break;default:throw Error(`impossible state`)}break;case 62:t===2&&this.fail(`the string "]]>" is disallowed in char data.`),t=0;break;case-2:r!==void 0&&(this.text+=`${n.slice(e,this.prevI)}\n`),e=this.i,t=0;break;case-1:r!==void 0&&(this.text+=n.slice(e));break scanLoop;default:t=0}this.forbiddenState=t}handleTextOutsideRoot(){let{i:e}=this,{chunk:t,textHandler:n}=this,r=!1;outRootLoop:for(;;){let a=this.getCode();switch(a){case 60:if(this.state=15,n!==void 0){let{text:r}=this,i=t.slice(e,this.prevI);r.length===0?i.length!==0&&n(i):(n(r+i),this.text=``)}break outRootLoop;case 38:this.state=14,this.entityReturnState=13,n!==void 0&&(this.text+=t.slice(e,this.prevI)),r=!0;break outRootLoop;case-2:n!==void 0&&(this.text+=`${t.slice(e,this.prevI)}\n`),e=this.i;break;case-1:n!==void 0&&(this.text+=t.slice(e));break outRootLoop;default:i(a)||(r=!0)}}r&&(!this.sawRoot&&!this.reportedTextBeforeRoot&&(this.fail(`text data outside of root node.`),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail(`text data outside of root node.`),this.reportedTextAfterRoot=!0))}pushAttribNS(e,t){var n;let{prefix:r,local:i}=this.qname(e),a={name:e,prefix:r,local:i,value:t};if(this.attribList.push(a),(n=this.attributeHandler)==null||n.call(this,a),r===`xmlns`){let e=t.trim();this.currentXMLVersion===`1.0`&&e===``&&this.fail(`invalid attempt to undefine prefix in XML 1.0`),this.topNS[i]=e,se(this,i,e)}else if(e===`xmlns`){let e=t.trim();this.topNS[``]=e,se(this,``,e)}}pushAttribPlain(e,t){var n;let r={name:e,value:t};this.attribList.push(r),(n=this.attributeHandler)==null||n.call(this,r)}end(){var e,t;this.sawRoot||this.fail(`document must contain a root element.`);let{tags:n}=this;for(;n.length>0;){let e=n.pop();this.fail(`unclosed tag: ${e.name}`)}this.state!==0&&this.state!==13&&this.fail(`unexpected end.`);let{text:r}=this;return r.length!==0&&((e=this.textHandler)==null||e.call(this,r),this.text=``),this._closed=!0,(t=this.endHandler)==null||t.call(this),this._init(),this}resolve(e){var t;let n=this.topNS[e];if(n!==void 0)return n;let{tags:r}=this;for(let t=r.length-1;t>=0;t--)if(n=r[t].ns[e],n!==void 0)return n;return n=this.ns[e],n===void 0?(t=this.opt).resolvePrefix?.call(t,e):n}qname(e){let t=e.indexOf(`:`);if(t===-1)return{prefix:``,local:e};let n=e.slice(t+1),r=e.slice(0,t);return(r===``||n===``||n.includes(`:`))&&this.fail(`malformed name: ${e}.`),{prefix:r,local:n}}processAttribsNS(){let{attribList:e}=this,t=this.tag;{let{prefix:e,local:n}=this.qname(t.name);t.prefix=e,t.local=n;let r=t.uri=this.resolve(e)??``;e!==``&&(e===`xmlns`&&this.fail(`tags may not have "xmlns" as prefix.`),r===``&&(this.fail(`unbound namespace prefix: ${JSON.stringify(e)}.`),t.uri=e))}if(e.length===0)return;let{attributes:n}=t,r=/* @__PURE__ */ new Set;for(let t of e){let{name:e,prefix:i,local:a}=t,o,s;i===``?(o=e===`xmlns`?h:``,s=e):(o=this.resolve(i),o===void 0&&(this.fail(`unbound namespace prefix: ${JSON.stringify(i)}.`),o=i),s=`{${o}}${a}`),r.has(s)&&this.fail(`duplicate attribute: ${s}.`),r.add(s),t.uri=o,n[e]=t}this.attribList=[]}processAttribsPlain(){let{attribList:e}=this,t=this.tag.attributes;for(let{name:n,value:r}of e)t[n]!==void 0&&this.fail(`duplicate attribute: ${n}.`),t[n]=r;this.attribList=[]}openTag(){var e;this.processAttribs();let{tags:t}=this,n=this.tag;n.isSelfClosing=!1,(e=this.openTagHandler)==null||e.call(this,n),t.push(n),this.state=13,this.name=``}openSelfClosingTag(){var e,t;this.processAttribs();let{tags:n}=this,r=this.tag;r.isSelfClosing=!0,(e=this.openTagHandler)==null||e.call(this,r),(t=this.closeTagHandler)==null||t.call(this,r),(this.tag=n[n.length-1]??null)===null&&(this.closedRoot=!0),this.state=13,this.name=``}closeTag(){let{tags:e,name:t}=this;if(this.state=13,this.name=``,t===``){this.fail(`weird empty close tag.`),this.text+=`</>`;return}let n=this.closeTagHandler,r=e.length;for(;r-->0;){let r=this.tag=e.pop();if(this.topNS=r.ns,n?.(r),r.name===t)break;this.fail(`unexpected close tag.`)}r===0?this.closedRoot=!0:r<0&&(this.fail(`unmatched closing tag: ${t}.`),this.text+=`</${t}>`)}parseEntity(e){if(e[0]!==`#`){let t=this.ENTITIES[e];return t===void 0?(this.fail(this.isName(e)?`undefined entity.`:`disallowed character in entity name.`),`&${e};`):t}let t=NaN;return e[1]===`x`&&/^#x[0-9a-f]+$/i.test(e)?t=parseInt(e.slice(2),16):/^#[0-9]+$/.test(e)&&(t=parseInt(e.slice(1),10)),this.isChar(t)?String.fromCodePoint(t):(this.fail(`malformed character entity.`),`&${e};`)}}})))();const Ji=e=>{let t=0;for(let n of e){let e=n.codePointAt(0)??0;t+=e<128?1:e<2048?2:e<65536?3:4}return t},Yi=/* @__PURE__ */ new Set([`svg`,`g`,`path`,`rect`,`circle`,`ellipse`,`line`,`polyline`,`polygon`,`text`,`tspan`,`defs`,`clipPath`,`linearGradient`,`radialGradient`,`stop`,`title`,`desc`]),Xi=/* @__PURE__ */ new Set(/* @__PURE__ */ `xmlns.xmlns:xlink.version.baseProfile.id.class.x.y.x1.y1.x2.y2.cx.cy.r.rx.ry.fx.fy.dx.dy.width.height.viewBox.preserveAspectRatio.transform.d.points.offset.gradientUnits.gradientTransform.clipPathUnits.fill.fill-opacity.fill-rule.clip-path.clip-rule.stroke.stroke-width.stroke-opacity.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-dasharray.stroke-dashoffset.stop-color.stop-opacity.opacity.paint-order.pointer-events.font-family.font-size.font-weight.font-style.text-anchor.dominant-baseline.xml:space.style.ecmeta_ssr_type.ecmeta_series_index.ecmeta_data_index.ecmeta_ssr_component.ecmeta_ssr_component_index`.split(`.`)),Zi=/* @__PURE__ */ new Set([`font-size`,`font-family`,`font-weight`,`font-style`,`fill`,`fill-opacity`,`stroke`,`stroke-width`,`stroke-opacity`,`opacity`,`paint-order`,`white-space`]),Qi=/url\s*\(([^)]*)\)/gi,$i=/^\s*(['"]?)#[\w.:-]+\1\s*$/,ea=/javascript:|vbscript:|data:|expression\s*\(|@import|https?:|\/\//i,ta=/[\\<>]|\/\*/,Q=e=>{throw new Hi(e)},na=(e,t)=>{ta.test(t)&&Q(`forbidden character in attribute ${e}`),ea.test(t)&&Q(`forbidden value in attribute ${e}`);for(let n of t.matchAll(Qi))$i.test(n[1]??``)||Q(`non-local url() in attribute ${e}`)},ra=e=>{for(let t of e.split(`;`)){if(t.trim()===``)continue;let e=t.indexOf(`:`),n=(e===-1?t:t.slice(0,e)).trim().toLowerCase();Zi.has(n)||Q(`style property ${n} is not allowed`)}},ia=(e,t,n)=>{Xi.has(t)||Q(`attribute ${t} on <${e}> is not allowed`),t===`xmlns`?n!==`http://www.w3.org/2000/svg`&&Q(`unexpected namespace`):t===`xmlns:xlink`?n!==`http://www.w3.org/1999/xlink`&&Q(`unexpected namespace`):(na(t,n),t===`style`&&ra(n))},aa=(e,t)=>{let n=Ji(e);if(n>t)throw new Ui({bytes:n,maxBytes:t});let r=new qi.SaxesParser({xmlns:!1}),i=0,a=!1;r.on(`error`,e=>Q(`malformed svg: ${e.message}`)),r.on(`doctype`,()=>Q(`doctype is not allowed`)),r.on(`xmldecl`,()=>Q(`xml declaration is not allowed`)),r.on(`processinginstruction`,()=>Q(`processing instructions are not allowed`)),r.on(`comment`,()=>Q(`comments are not allowed`)),r.on(`cdata`,()=>Q(`cdata sections are not allowed`)),r.on(`opentag`,e=>{i===0&&((a||e.name!==`svg`)&&Q(`root element must be a single <svg>`),a=!0),i+=1,i>64&&Q(`elements are nested too deeply`),Yi.has(e.name)||Q(`element <${e.name}> is not allowed`);for(let[t,n]of x(e.attributes))ia(e.name,t,n)}),r.on(`closetag`,()=>{--i}),r.write(e).close(),a||Q(`root element must be a single <svg>`)},oa=(e,t)=>`${t.toISOString().replaceAll(/[:.]/g,`-`)}-${o(3).toString(`hex`)}-${e}`,sa=e=>new R(`write_failed`,e instanceof Error?e.message:`the result could not be written`),ca=(e,t)=>e instanceof Error&&y(e,`code`)&&e.code===t,la=async e=>{for(let t of[_.dirname(e),e]){await d(t,{mode:448}).catch(e=>{if(!ca(e,`EEXIST`))throw e});let e=await u(t);if(e.isSymbolicLink()||!e.isDirectory())throw new R(`unsafe_location`,`${t} is not a real directory (symbolic links are not followed)`)}},ua=async e=>{for(let t of[_.dirname(e),e]){let e=await u(t).catch(e=>{if(ca(e,`ENOENT`))return null;throw e});if(e==null||e.isSymbolicLink()||!e.isDirectory())return!1}return!0},da=async e=>{try{await e()}catch(e){throw sa(e)}},fa=async(e,t)=>{let n=_.join(e.outputDir,oa(e.fileName,e.now)),r;try{await la(e.outputDir),r=await f(n,`wx`,384)}catch(e){throw e instanceof R?e:sa(e)}try{let e=await t(r);return await da(()=>r.close()),{path:n,...e}}catch(e){throw await r.close().catch(w),await g(n,{force:!0}).catch(w),e}},pa=async(e,t)=>{if(e.byteLength>t.maxBytes)throw new R(`too_large`,`the result exceeds ${t.maxBytes} bytes`);return fa(t,async t=>(await da(()=>t.writeFile(e)),{bytes:e.byteLength,sha256Hex:a(`sha256`).update(e).digest(`hex`)}))},ma=(e,t)=>fa(t,async n=>{let r=a(`sha256`),i=0;for await(let a of e){if(i+=a.byteLength,i>t.maxBytes)throw new R(`too_large`,`the result exceeds ${t.maxBytes} bytes`);r.update(a),await da(async()=>{await n.write(a)})}return{bytes:i,sha256Hex:r.digest(`hex`)}}),ha=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-[0-9a-f]{6}-/,ga=async(e,t)=>{if(!await ua(e))return 0;let n;try{n=await m(e,{withFileTypes:!0})}catch(e){if(ca(e,`ENOENT`))return 0;throw e}let r=t.now.getTime()-t.maxAgeMs;return(await Promise.all(n.filter(e=>e.isFile()&&ha.test(e.name)).map(async t=>{let n=_.join(e,t.name),i=await u(n);return!i.isFile()||i.mtimeMs>=r?!1:(await g(n,{force:!0}),!0)}))).filter(Boolean).length},_a=e=>e.split(`/`).slice(1),va=(e,t,n)=>{if(e===`image/svg+xml`)aa(t,n);else throw new Hi(`unknown artifact media type`)},ya=e=>e instanceof R?e.kind:e instanceof Ui?`too_large`:e instanceof Hi?`unsafe_content`:`unexpected`,ba=async(e,t,n)=>{if(e.isError||t.length===0||!C(e.payload))return e;let r=e.payload.body;if(!C(r))return e;let i=structuredClone(r);for(let e of t){let t=_a(e.pointer),r=t.pop(),a=i;for(let e of t)a=C(a)&&y(a,e)?a[e]:null;if(r==null||!C(a)||typeof a[r]!=`string`)continue;let o=a;try{let t=G(String(o[r]),n.secrets);va(e.mediaType,t,n.maxBytes);let i=Buffer.from(t,`utf8`);o[r]={file:{...await pa(i,{outputDir:n.outputDir,fileName:`${n.operationId}.${e.extension}`,maxBytes:n.maxBytes,now:n.now}),mediaType:e.mediaType}}}catch(e){o[r]={error:{kind:`artifact_not_saved`,failure:ya(e)}}}}return{isError:!1,payload:{...e.payload,body:i}}},xa=e=>Array.isArray(e),Sa=`#/$defs/`,Ca=/* @__PURE__ */ new Set([`oneOf`,`anyOf`,`allOf`,`prefixItems`]),wa=/* @__PURE__ */ new Set([`items`,`additionalProperties`,`propertyNames`,`not`]),Ta=e=>Array.isArray(e)?e.map(e=>Ta(e)):C(e)?S(x(e).flatMap(([e,t])=>{if(e!==`$comment`||typeof t!=`string`)return[[e,Ta(t)]];if(!t.startsWith(`Additional constraints are validated by the server`))return[[e,t]];let n=t.slice(50);return n.startsWith(`: `)?[[e,n.slice(2)]]:[]})):e,Ea=(e,t)=>C(e)&&b(e).length===1&&Array.isArray(e[t]),Da=e=>Array.isArray(e)?e.map(e=>Da(e)):C(e)?S(x(e).map(([e,t])=>{let n=Da(t);return e!==`anyOf`&&e!==`oneOf`||!Array.isArray(n)?[e,n]:[e,n.flatMap(t=>{let n=Ea(t,e)?t[e]:null;return xa(n)?n:[t]})]})):e,Oa=(e,t)=>{let n=e.properties;if(!C(n))return null;let r=n[t];return C(r)&&b(r).length===1&&y(r,`const`)?r:null},ka=(e,t)=>Oa(e,t)?.const,Aa=e=>{let t=e.properties;return C(t)?b(t).filter(t=>Oa(e,t)!=null):[]},ja=(e,t)=>{let n=C(e.properties)?e.properties:{};return`${t}${JSON.stringify({...e,properties:{...n,[t]:`\0`}})}`},Ma=e=>{let t=/* @__PURE__ */ new Map;for(let[n,r]of e.entries())if(C(r))for(let e of Aa(r)){let i=ja(r,e),a=t.get(i);a==null?t.set(i,[n]):a.push(n)}let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set,i=[...t].toSorted(([,e],[,t])=>t.length-e.length);for(let[t,a]of i){let i=a.filter(e=>!r.has(e)),[o]=i;if(o==null||i.length<2)continue;let s=t.slice(0,t.indexOf(`\0`)),c=e[o];if(!C(c)||!C(c.properties))continue;let l=i.map(t=>{let n=e[t];return C(n)?ka(n,s):void 0});for(let e of i)r.add(e);n.set(o,{...c,properties:{...c.properties,[s]:{enum:l}}})}return e.flatMap((e,t)=>n.has(t)?[n.get(t)]:r.has(t)?[]:[e])},Na=e=>Array.isArray(e)?e.map(e=>Na(e)):C(e)?S(x(e).map(([e,t])=>{let n=Na(t);return(e===`anyOf`||e===`oneOf`)&&Array.isArray(n)?[e,Ma(n)]:[e,n]})):e,Pa=(e,t)=>S(x(e).map(([e,n])=>(e===`properties`||e===`$defs`)&&C(n)?[e,S(x(n).map(([e,n])=>[e,C(n)?t(n):n]))]:Ca.has(e)&&Array.isArray(n)?[e,n.map(e=>C(e)?t(e):e)]:wa.has(e)&&C(n)?[e,t(n)]:[e,n])),Fa=(e,t,n)=>{let r=/* @__PURE__ */ new Map,i=e=>{let t=JSON.stringify(e);return t.length>=n&&r.set(t,(r.get(t)??0)+1),Pa(e,i)};Pa(e,i);for(let e of de(t))C(e)&&Pa(e,i);return r},Ia=(e,t,n)=>{let r=null,i=0;for(let[a,o]of e){let e=o*(a.length-t)-a.length-n;o>1&&e>i&&(r=a,i=e)}return r},La=(e,t)=>{let n=e;for(let e=1;;e+=1){let r=C(n.$defs)?n.$defs:{},i=`shared${String(e)}`;for(;y(r,i);)i=`_${i}`;let a=`${Sa}${i}`,{$defs:o,...s}=n,c=Ia(Fa(s,r,t),JSON.stringify({$ref:a}).length,JSON.stringify({[i]:null}).length);if(c==null)return n;let l=e=>JSON.stringify(e)===c?{$ref:a}:Pa(e,l),u=Pa(s,l),d=S(x(r).map(([e,t])=>[e,C(t)?Pa(t,l):t])),f=JSON.parse(c);n={...u,$defs:S([...x(d),[i,f]].toSorted(([e],[t])=>fe(e,t)))}}},Ra=e=>{let t=e.lastIndexOf(`__`);return t===-1?``:e.slice(0,t+2)},za=e=>{let t=e.$defs;if(!C(t))return e;let n=b(t),[r]=n;if(r==null)return e;let i=Ra(r);for(;i!==``&&!n.every(e=>e.startsWith(i)&&e!==i);)i=Ra(i.slice(0,-2));if(i===``)return e;let a=`${Sa}${i}`,o=e=>Array.isArray(e)?e.map(e=>o(e)):C(e)?S(x(e).map(([e,t])=>e===`$ref`&&typeof t==`string`&&t.startsWith(a)?[e,`${Sa}${t.slice(a.length)}`]:e===`$defs`&&C(t)?[e,S(x(t).map(([e,t])=>[e.startsWith(i)?e.slice(i.length):e,o(t)]))]:[e,o(t)])):e,s=o(e);return C(s)?s:e},Ba=(e,t)=>{let n=Na(Da(Ta(e)));return La(za(C(n)?n:e),t)},Va=e=>typeof e==`string`&&e.startsWith(`#/$defs/`)?e.slice(8).replaceAll(`~1`,`/`).replaceAll(`~0`,`~`):null,Ha=(e,t)=>{let n=/* @__PURE__ */ new Map,r=e=>{if(Array.isArray(e))for(let t of e)r(t);else if(C(e))for(let[i,a]of x(e)){let e=i===`$ref`?Va(a):null;e==null?r(a):n.has(e)||(n.set(e,t[e]),r(t[e]))}};return r(e),S([...n].toSorted(([e],[t])=>fe(e,t)))},Ua=[`anyOf`,`oneOf`,`allOf`],Wa=`The server also validates constraints that JSON Schema cannot express; $comment states them where known.`,Ga=(e,t)=>{let n=e;for(let e=0;e<16;e+=1){let e=n.$ref;if(typeof e!=`string`||!e.startsWith(`#/$defs/`))return n;let r=t[e.slice(8)];if(!C(r))return n;n=r}return n},Ka=(e,t,n)=>{let r=Ga(e,n),i=r.properties;if(C(i)&&C(i[t]))return i[t];let a=r.items;if(C(a))return Ka(a,t,n);let o=Ua.flatMap(e=>{let i=r[e];return Array.isArray(i)?i.flatMap(e=>{let r=C(e)?Ka(e,t,n):null;return r==null?[]:[r]}):[]}),[s]=o;return s==null?null:o.length===1?s:{anyOf:o}},qa=(e,t)=>{let n=Ga(e,t),r=n.properties;if(C(r))return b(r);let i=Ua.flatMap(e=>{let r=n[e];return Array.isArray(r)?r.flatMap(e=>C(e)?qa(e,t):[]):[]});return[...new Set(i)]},Ja=(e,t,n)=>{let r=e;for(let e of t.split(`.`)){if(r==null)return null;r=Ka(r,e,n)}return r},Ya=(e,t)=>{let n=Ha(e,t);return b(n).length===0?e:{...e,$defs:n}},Xa=(e,t,n)=>{let r=[],i=e=>{if(!(r.length>=2)){if(Array.isArray(e))for(let t of e)i(t);else if(C(e)){if(e[t]===n)r.push(e);else for(let t of de(e))i(t)}}};for(let t of e)i(t.value);return r},Za=e=>({isError:!0,payload:{error:e}}),Qa=(e,t)=>Za({kind:`unknown_path`,message:e,keys:t}),$a=(e,t)=>{let{operationId:n}=e,{$defs:r,...i}=e.fullInputSchema,a=C(r)?r:{},o=t==null?i:Ja(i,t,a);if(o==null)return Qa(`The input of ${n} has no key path "${t??``}". Use a key below, or join nested keys with "." (array items are entered implicitly).`,qa(i,a));let s=e.inputDetails;return{isError:!1,payload:{operationId:n,...t==null?{description:e.description,hint:`To get only part of the schema, call ${M} again with path set to a key (nested keys joined with ".").`}:{selectedPath:t},...s==null||t!=null?{}:{groups:s.groups.map(e=>({path:e.path,discriminator:e.discriminator,description:e.description,types:e.variants.map(t=>({[e.discriminator]:t.value,summary:t.summary}))})),typeHint:`The keys at each group path depend on ${s.groups[0]?.discriminator??`type`}. Call ${M} with type to get the full shape of one type before sending it.`},note:Wa,schema:Ba(Ya(o,a),80),...s==null||t!=null?{}:{examples:s.examples}}}},eo=(e,t,n,r)=>{let i=e.get(t);if(i==null)return Za({kind:`unknown_operation`,message:`${t} is not a tool of this server.`,operationIds:[...e.keys()]});if(n==null)return $a(i,r);let a=i.inputDetails,o=(a?.groups??[]).flatMap(e=>e.variants.filter(e=>e.value===n).map(t=>({group:e,variant:t})));if(a==null||o.length===0)return Za({kind:`unknown_type`,message:a==null?`The input of ${t} does not depend on a type. Call ${M} without type.`:`${t} has no input type "${n}". Call ${M} without type to list the types.`,types:(a?.groups??[]).flatMap(e=>e.variants.map(e=>e.value))});let s=[];for(let{group:e,variant:i}of o){let o=qa(i.schema,a.definitions),c=r==null?i.schema:Ja(i.schema,r,a.definitions);if(c==null)return Qa(`The ${n} input of ${t} has no key path "${r??``}". Use a key below, or join nested keys with "." (array items are entered implicitly, e.g. "aggregates.query").`,o);s.push({path:r==null?e.path:`${e.path}.${r}`,discriminator:e.discriminator,...r==null?{keys:o,examples:Xa(a.examples,e.discriminator,n)}:{},schema:Ba(Ya(c,a.definitions),80)})}return{isError:!1,payload:{operationId:t,type:n,...r==null?{hint:`To get only part of the schema, call ${M} again with path set to one of keys (nested keys joined with ".").`}:{selectedPath:r},note:Wa,schemas:s}}},to=(e,t)=>{let n=``,r=0,i=e.indexOf(`{`);for(;i!==-1;){let a=e.indexOf(`}`,i+1);if(a===-1)break;n+=a===i+1?e.slice(r,a+1):e.slice(r,i)+t(e.slice(i+1,a)),r=a+1,i=e.indexOf(`{`,r)}return n+e.slice(r)},no=(e,t)=>{if(typeof t==`string`)return t;if(typeof t==`number`||typeof t==`boolean`)return String(t);throw new N(`argument "${e}" must be a string, number, or boolean`)},ro=/* @__PURE__ */ new Set([`.`,`..`,`%2e`,`.%2e`,`%2e.`,`%2e%2e`]),io=(e,t)=>{if(t===``||ro.has(t.toLowerCase()))throw new N(`path parameter "${e}" must not be empty, "." or ".."`);return encodeURIComponent(t)},ao=(e,t,n)=>{if(y(n,`tenantName`))throw new N(`"${Un}" is fixed by the server configuration`);let r=to(t.pathTemplate,t=>{if(t===`tenantName`)return encodeURIComponent(e.tenantName);let r=n[t];if(r==null)throw new N(`path parameter "${t}" is required`);return io(t,no(t,r))}),i=[];for(let e of t.queryParams){let t=n[e];if(t!=null){if(Array.isArray(t))for(let n of t)i.push([e,no(e,n)]);else i.push([e,no(e,t)])}}let a=null,o=!1;if(t.wholeBodyField!=null){if(!y(n,t.wholeBodyField))throw new N(`argument "${t.wholeBodyField}" is required`);a=n[t.wholeBodyField],o=!0}else if(t.bodyFields!=null){let e={};for(let r of t.bodyFields)y(n,r)&&(e[r]=n[r]);a=e,o=!0}return{method:t.method,path:r,query:i,hasBody:o,body:a,responseKind:t.responseKind}},oo=async(e,t)=>{try{return await e.preflight(),{isError:!1,payload:await t()}}catch(t){let n=e.secrets(),r=JSON.parse(G(JSON.stringify(e.errorPayload(t,n)),n));return e.onFailure(t,r),{isError:!0,payload:r}}},so=(e,t)=>{if(e instanceof F){let{retryAfterSeconds:t,status:n}=e.info;return{error:{kind:`api`,...e.info,...t==null?{}:{hint:`${n===429?`Rate limited; the request was not processed. `:``}Wait ${String(t)} seconds, then call the tool again.`}}}}return e instanceof I?{error:{kind:`transport`,failure:e.kind,status:e.status,message:e.message,...t===`write`?{note:`The write may have completed on the server even though no valid response was received. Check the current state with list_* / get_* / search_records before running it again.`}:{}}}:null},co=(e,t,n)=>{let r=so(e,n);if(r!=null)return{isError:!0,payload:r};if(e instanceof R)return{isError:!0,payload:{error:{kind:`result_not_saved`,failure:e.kind,message:`The file could not be saved to the output directory.`}}};if(e instanceof N)return{isError:!0,payload:{error:{kind:`invalid_arguments`,message:e.message}}};if(e instanceof z)return{isError:!0,payload:{error:{kind:`workspace`,failure:e.kind,message:e.message}}};if(e instanceof P)return{isError:!0,payload:{error:{kind:`auth`,failure:e.kind,message:e.message}}};if(e instanceof Error)return{isError:!0,payload:{error:{kind:`unexpected`,message:G(e.message,t)}}};throw e},lo=(e,t,n)=>oo({preflight:async()=>{await Ot(e.workspace,new Date(e.now())),await e.auth.assertLoggedIn()},secrets:()=>e.auth.secrets(),errorPayload:(e,n)=>co(e,n,t.effect).payload,onFailure:(n,r)=>{e.logger.warn(`tool call failed`,{operationId:t.operationId,payload:r})}},n),uo=async(e,t,n)=>lo(e,t,async()=>{let r=await e.client.request(ao(e.config,t,n));switch(r.kind){case`json`:return{status:r.status,requestId:r.requestId,body:r.body};case`empty`:return{status:r.status,requestId:r.requestId};case`file`:try{let n=await ma(r.chunks,{outputDir:e.config.outputDir,fileName:`${t.operationId}.json`,maxBytes:2147483648,now:new Date(e.now())});return{status:r.status,requestId:r.requestId,file:{...n,format:`json`}}}finally{await r.cancel()}default:throw Error(`unknown response kind`)}}),fo=(e,t)=>`Flyle AI CX の公開 API を呼ぶツール群です。テーブルとレコードの参照・検索・作成・更新・削除、ロールの設定・割り当て、レポート・ダッシュボードの作成・編集、AI グルーピングの作成・編集・削除、ワークフローの参照と下書きの作成・更新を、ログインしたユーザーの権限で行います。
|
|
105
|
+
Object.defineProperty(e,"__esModule",{value:!0}),e.NC_NAME_START_CHAR=`A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ--⁰-Ⰰ-、-豈-﷏ﷰ-�𐀀-`,e.NC_NAME_CHAR=`-`+e.NC_NAME_START_CHAR+`.0-9·̀-ͯ‿-⁀`,e.NC_NAME_START_CHAR_RE=RegExp(`^[`+e.NC_NAME_START_CHAR+`]$`,`u`),e.NC_NAME_CHAR_RE=RegExp(`^[`+e.NC_NAME_CHAR+`]$`,`u`),e.NC_NAME_RE=RegExp(`^[`+e.NC_NAME_START_CHAR+`][`+e.NC_NAME_CHAR+`]*$`,`u`);function t(e){return e>=65&&e<=90||e===95||e>=97&&e<=122||e>=192&&e<=214||e>=216&&e<=246||e>=248&&e<=767||e>=880&&e<=893||e>=895&&e<=8191||e>=8204&&e<=8205||e>=8304&&e<=8591||e>=11264&&e<=12271||e>=12289&&e<=55295||e>=63744&&e<=64975||e>=65008&&e<=65533||e>=65536&&e<=983039}e.isNCNameStartChar=t;function n(e){return t(e)||e===45||e===46||e>=48&&e<=57||e===183||e>=768&&e<=879||e>=8255&&e<=8256}e.isNCNameChar=n})),$i=(/* @__PURE__ */ ce((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SaxesParser=e.EVENTS=void 0;let t=Xi(),n=Zi(),r=Qi();var i=t.isS,a=t.isChar,o=t.isNameStartChar,s=t.isNameChar,c=t.S_LIST,l=t.NAME_RE,u=n.isChar,d=r.isNCNameStartChar,f=r.isNCNameChar,p=r.NC_NAME_RE;let m=`http://www.w3.org/XML/1998/namespace`,h=`http://www.w3.org/2000/xmlns/`,g={__proto__:null,xml:m,xmlns:h},_={__proto__:null,amp:`&`,gt:`>`,lt:`<`,quot:`"`,apos:`'`},ee=8232,v=e=>e===34||e===39,te=[34,39],ne=[...te,91,62],re=[...te,60,93],ie=[61,63,...c],ae=[...c,62,38,60];function oe(e,t,n){switch(t){case`xml`:n!==m&&e.fail(`xml prefix must be bound to ${m}.`);break;case`xmlns`:n!==h&&e.fail(`xmlns prefix must be bound to ${h}.`)}switch(n){case h:e.fail(t===``?`the default namespace may not be set to ${n}.`:`may not assign a prefix (even "xmlns") to the URI \
|
|
106
|
+
${h}.`);break;case m:switch(t){case`xml`:break;case``:e.fail(`the default namespace may not be set to ${n}.`);break;default:e.fail(`may not assign the xml namespace to another prefix.`)}}}function y(e,t){for(let n of Object.keys(t))oe(e,n,t[n])}let se=e=>p.test(e),ce=e=>l.test(e);e.EVENTS=[`xmldecl`,`text`,`processinginstruction`,`doctype`,`comment`,`opentagstart`,`attribute`,`opentag`,`closetag`,`cdata`,`error`,`end`,`ready`];let b={xmldecl:`xmldeclHandler`,text:`textHandler`,processinginstruction:`piHandler`,doctype:`doctypeHandler`,comment:`commentHandler`,opentagstart:`openTagStartHandler`,attribute:`attributeHandler`,opentag:`openTagHandler`,closetag:`closeTagHandler`,cdata:`cdataHandler`,error:`errorHandler`,end:`endHandler`,ready:`readyHandler`};e.SaxesParser=class{constructor(e){this.opt=e??{},this.fragmentOpt=!!this.opt.fragment;let t=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,t){this.nameStartCheck=d,this.nameCheck=f,this.isName=se,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},g);let e=this.opt.additionalNamespaces;e!=null&&(y(this,e),Object.assign(this.ns,e))}else this.nameStartCheck=o,this.nameCheck=s,this.isName=ce,this.processAttribs=this.processAttribsPlain,this.pushAttrib=this.pushAttribPlain;this.stateTable=[this.sBegin,this.sBeginWhitespace,this.sDoctype,this.sDoctypeQuote,this.sDTD,this.sDTDQuoted,this.sDTDOpenWaka,this.sDTDOpenWakaBang,this.sDTDComment,this.sDTDCommentEnding,this.sDTDCommentEnded,this.sDTDPI,this.sDTDPIEnding,this.sText,this.sEntity,this.sOpenWaka,this.sOpenWakaBang,this.sComment,this.sCommentEnding,this.sCommentEnded,this.sCData,this.sCDataEnding,this.sCDataEnding2,this.sPIFirstChar,this.sPIRest,this.sPIBody,this.sPIEnding,this.sXMLDeclNameStart,this.sXMLDeclName,this.sXMLDeclEq,this.sXMLDeclValueStart,this.sXMLDeclValue,this.sXMLDeclSeparator,this.sXMLDeclEnding,this.sOpenTag,this.sOpenTagSlash,this.sAttrib,this.sAttribName,this.sAttribNameSawWhite,this.sAttribValue,this.sAttribValueQuoted,this.sAttribValueClosed,this.sAttribValueUnquoted,this.sCloseTag,this.sCloseTagSawWhite],this._init()}get closed(){return this._closed}_init(){var e;this.openWakaBang=``,this.text=``,this.name=``,this.piTarget=``,this.entity=``,this.q=null,this.tags=[],this.tag=null,this.topNS=null,this.chunk=``,this.chunkPosition=0,this.i=0,this.prevI=0,this.carriedFromPrevious=void 0,this.forbiddenState=0,this.attribList=[];let{fragmentOpt:t}=this;this.state=t?13:0,this.reportedTextBeforeRoot=this.reportedTextAfterRoot=this.closedRoot=this.sawRoot=t,this.xmlDeclPossible=!t,this.xmlDeclExpects=[`version`],this.entityReturnState=void 0;let{defaultXMLVersion:n}=this.opt;if(n===void 0){if(this.opt.forceXMLVersion===!0)throw Error(`forceXMLVersion set but defaultXMLVersion is not set`);n=`1.0`}this.setXMLVersion(n),this.positionAtNewLine=0,this.doctype=!1,this._closed=!1,this.xmlDecl={version:void 0,encoding:void 0,standalone:void 0},this.line=1,this.column=0,this.ENTITIES=Object.create(_),(e=this.readyHandler)==null||e.call(this)}get position(){return this.chunkPosition+this.i}get columnIndex(){return this.position-this.positionAtNewLine}on(e,t){this[b[e]]=t}off(e){this[b[e]]=void 0}makeError(e){let t=this.fileName??``;return this.trackPosition&&(t.length>0&&(t+=`:`),t+=`${this.line}:${this.column}`),t.length>0&&(t+=`: `),Error(t+e)}fail(e){let t=this.makeError(e),n=this.errorHandler;if(n===void 0)throw t;return n(t),this}write(e){if(this.closed)return this.fail(`cannot write after close; assign an onready handler.`);let t=!1;e===null?(t=!0,e=``):typeof e==`object`&&(e=e.toString()),this.carriedFromPrevious!==void 0&&(e=`${this.carriedFromPrevious}${e}`,this.carriedFromPrevious=void 0);let n=e.length,r=e.charCodeAt(n-1);!t&&(r===13||r>=55296&&r<=56319)&&(this.carriedFromPrevious=e[n-1],n--,e=e.slice(0,n));let{stateTable:i}=this;for(this.chunk=e,this.i=0;this.i<n;)i[this.state].call(this);return this.chunkPosition+=n,t?this.end():this}close(){return this.write(null)}getCode10(){let{chunk:e,i:t}=this;if(this.prevI=t,this.i=t+1,t>=e.length)return-1;let n=e.charCodeAt(t);if(this.column++,n<55296){if(n>=32||n===9)return n;switch(n){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:return e.charCodeAt(t+1)===10&&(this.i=t+2),this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail(`disallowed character.`),n}}if(n>56319)return n>=57344&&n<=65533||this.fail(`disallowed character.`),n;let r=65536+(n-55296)*1024+(e.charCodeAt(t+1)-56320);return this.i=t+2,r>1114111&&this.fail(`disallowed character.`),r}getCode11(){let{chunk:e,i:t}=this;if(this.prevI=t,this.i=t+1,t>=e.length)return-1;let n=e.charCodeAt(t);if(this.column++,n<55296){if(n>31&&n<127||n>159&&n!==ee||n===9)return n;switch(n){case 10:return this.line++,this.column=0,this.positionAtNewLine=this.position,10;case 13:{let n=e.charCodeAt(t+1);(n===10||n===133)&&(this.i=t+2)}case 133:case ee:return this.line++,this.column=0,this.positionAtNewLine=this.position,-2;default:return this.fail(`disallowed character.`),n}}if(n>56319)return n>=57344&&n<=65533||this.fail(`disallowed character.`),n;let r=65536+(n-55296)*1024+(e.charCodeAt(t+1)-56320);return this.i=t+2,r>1114111&&this.fail(`disallowed character.`),r}getCodeNorm(){let e=this.getCode();return e===-2?10:e}unget(){this.i=this.prevI,this.column--}captureTo(e){let{i:t}=this,{chunk:n}=this;for(;;){let r=this.getCode(),i=r===-2,a=i?10:r;if(a===-1||e.includes(a))return this.text+=n.slice(t,this.prevI),a;i&&(this.text+=`${n.slice(t,this.prevI)}\n`,t=this.i)}}captureToChar(e){let{i:t}=this,{chunk:n}=this;for(;;){let r=this.getCode();switch(r){case-2:this.text+=`${n.slice(t,this.prevI)}\n`,t=this.i,r=10;break;case-1:return this.text+=n.slice(t),!1}if(r===e)return this.text+=n.slice(t,this.prevI),!0}}captureNameChars(){let{chunk:e,i:t}=this;for(;;){let n=this.getCode();if(n===-1)return this.name+=e.slice(t),-1;if(!s(n))return this.name+=e.slice(t,this.prevI),n===-2?10:n}}skipSpaces(){for(;;){let e=this.getCodeNorm();if(e===-1||!i(e))return e}}setXMLVersion(e){this.currentXMLVersion=e,e===`1.0`?(this.isChar=a,this.getCode=this.getCode10):(this.isChar=u,this.getCode=this.getCode11)}sBegin(){this.chunk.charCodeAt(0)===65279&&(this.i++,this.column++),this.state=1}sBeginWhitespace(){let e=this.i,t=this.skipSpaces();switch(this.prevI!==e&&(this.xmlDeclPossible=!1),t){case 60:if(this.state=15,this.text.length!==0)throw Error(`no-empty text at start`);break;case-1:break;default:this.unget(),this.state=13,this.xmlDeclPossible=!1}}sDoctype(){var e;let t=this.captureTo(ne);switch(t){case 62:(e=this.doctypeHandler)==null||e.call(this,this.text),this.text=``,this.state=13,this.doctype=!0;break;case-1:break;default:this.text+=String.fromCodePoint(t),t===91?this.state=4:v(t)&&(this.state=3,this.q=t)}}sDoctypeQuote(){let e=this.q;this.captureToChar(e)&&(this.text+=String.fromCodePoint(e),this.q=null,this.state=2)}sDTD(){let e=this.captureTo(re);e!==-1&&(this.text+=String.fromCodePoint(e),e===93?this.state=2:e===60?this.state=6:v(e)&&(this.state=5,this.q=e))}sDTDQuoted(){let e=this.q;this.captureToChar(e)&&(this.text+=String.fromCodePoint(e),this.state=4,this.q=null)}sDTDOpenWaka(){let e=this.getCodeNorm();switch(this.text+=String.fromCodePoint(e),e){case 33:this.state=7,this.openWakaBang=``;break;case 63:this.state=11;break;default:this.state=4}}sDTDOpenWakaBang(){let e=String.fromCodePoint(this.getCodeNorm()),t=this.openWakaBang+=e;this.text+=e,t!==`-`&&(this.state=t===`--`?8:4,this.openWakaBang=``)}sDTDComment(){this.captureToChar(45)&&(this.text+=`-`,this.state=9)}sDTDCommentEnding(){let e=this.getCodeNorm();this.text+=String.fromCodePoint(e),this.state=e===45?10:8}sDTDCommentEnded(){let e=this.getCodeNorm();this.text+=String.fromCodePoint(e),e===62?this.state=4:(this.fail(`malformed comment.`),this.state=8)}sDTDPI(){this.captureToChar(63)&&(this.text+=`?`,this.state=12)}sDTDPIEnding(){let e=this.getCodeNorm();this.text+=String.fromCodePoint(e),e===62&&(this.state=4)}sText(){this.tags.length===0?this.handleTextOutsideRoot():this.handleTextInRoot()}sEntity(){let{i:e}=this,{chunk:t}=this;loop:for(;;)switch(this.getCode()){case-2:this.entity+=`${t.slice(e,this.prevI)}\n`,e=this.i;break;case 59:{let{entityReturnState:n}=this,r=this.entity+t.slice(e,this.prevI);this.state=n;let i;r===``?(this.fail(`empty entity name.`),i=`&;`):(i=this.parseEntity(r),this.entity=``),(n!==13||this.textHandler!==void 0)&&(this.text+=i);break loop}case-1:this.entity+=t.slice(e);break loop}}sOpenWaka(){let e=this.getCode();if(o(e))this.state=34,this.unget(),this.xmlDeclPossible=!1;else switch(e){case 47:this.state=43,this.xmlDeclPossible=!1;break;case 33:this.state=16,this.openWakaBang=``,this.xmlDeclPossible=!1;break;case 63:this.state=23;break;default:this.fail(`disallowed character in tag name`),this.state=13,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case`[CDATA[`:!this.sawRoot&&!this.reportedTextBeforeRoot&&(this.fail(`text data outside of root node.`),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail(`text data outside of root node.`),this.reportedTextAfterRoot=!0),this.state=20,this.openWakaBang=``;break;case`--`:this.state=17,this.openWakaBang=``;break;case`DOCTYPE`:this.state=2,(this.doctype||this.sawRoot)&&this.fail(`inappropriately located doctype declaration.`),this.openWakaBang=``;break;default:this.openWakaBang.length>=7&&this.fail(`incorrect syntax.`)}}sComment(){this.captureToChar(45)&&(this.state=18)}sCommentEnding(){var e;let t=this.getCodeNorm();t===45?(this.state=19,(e=this.commentHandler)==null||e.call(this,this.text),this.text=``):(this.text+=`-${String.fromCodePoint(t)}`,this.state=17)}sCommentEnded(){let e=this.getCodeNorm();e===62?this.state=13:(this.fail(`malformed comment.`),this.text+=`--${String.fromCodePoint(e)}`,this.state=17)}sCData(){this.captureToChar(93)&&(this.state=21)}sCDataEnding(){let e=this.getCodeNorm();e===93?this.state=22:(this.text+=`]${String.fromCodePoint(e)}`,this.state=20)}sCDataEnding2(){var e;let t=this.getCodeNorm();switch(t){case 62:(e=this.cdataHandler)==null||e.call(this,this.text),this.text=``,this.state=13;break;case 93:this.text+=`]`;break;default:this.text+=`]]${String.fromCodePoint(t)}`,this.state=20}}sPIFirstChar(){let e=this.getCodeNorm();this.nameStartCheck(e)?(this.piTarget+=String.fromCodePoint(e),this.state=24):e===63||i(e)?(this.fail(`processing instruction without a target.`),this.state=e===63?26:25):(this.fail(`disallowed character in processing instruction name.`),this.piTarget+=String.fromCodePoint(e),this.state=24)}sPIRest(){let{chunk:e,i:t}=this;for(;;){let n=this.getCodeNorm();if(n===-1){this.piTarget+=e.slice(t);return}if(!this.nameCheck(n)){this.piTarget+=e.slice(t,this.prevI);let r=n===63;r||i(n)?this.piTarget===`xml`?(this.xmlDeclPossible||this.fail(`an XML declaration must be at the start of the document.`),this.state=r?33:27):this.state=r?26:25:(this.fail(`disallowed character in processing instruction name.`),this.piTarget+=String.fromCodePoint(n));break}}}sPIBody(){if(this.text.length===0){let e=this.getCodeNorm();e===63?this.state=26:i(e)||(this.text=String.fromCodePoint(e))}else this.captureToChar(63)&&(this.state=26)}sPIEnding(){var e;let t=this.getCodeNorm();if(t===62){let{piTarget:t}=this;t.toLowerCase()===`xml`&&this.fail(`the XML declaration must appear at the start of the document.`),(e=this.piHandler)==null||e.call(this,{target:t,body:this.text}),this.piTarget=this.text=``,this.state=13}else t===63?this.text+=`?`:(this.text+=`?${String.fromCodePoint(t)}`,this.state=25);this.xmlDeclPossible=!1}sXMLDeclNameStart(){let e=this.skipSpaces();e===63?this.state=33:e!==-1&&(this.state=28,this.name=String.fromCodePoint(e))}sXMLDeclName(){let e=this.captureTo(ie);if(e===63)this.state=33,this.name+=this.text,this.text=``,this.fail(`XML declaration is incomplete.`);else if(i(e)||e===61){if(this.name+=this.text,this.text=``,!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail(`did not expect any more name/value pairs.`);break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(`, `)}`)}this.state=e===61?30:29}}sXMLDeclEq(){let e=this.getCodeNorm();e===63?(this.state=33,this.fail(`XML declaration is incomplete.`)):i(e)||(e!==61&&this.fail(`value required.`),this.state=30)}sXMLDeclValueStart(){let e=this.getCodeNorm();e===63?(this.state=33,this.fail(`XML declaration is incomplete.`)):i(e)||(v(e)?this.q=e:(this.fail(`value must be quoted.`),this.q=32),this.state=31)}sXMLDeclValue(){let e=this.captureTo([this.q,63]);if(e===63){this.state=33,this.text=``,this.fail(`XML declaration is incomplete.`);return}if(e===-1)return;let t=this.text;switch(this.text=``,this.name){case`version`:{this.xmlDeclExpects=[`encoding`,`standalone`];let e=t;this.xmlDecl.version=e,/^1\.[0-9]+$/.test(e)?this.opt.forceXMLVersion||this.setXMLVersion(e):this.fail(`version number must match /^1\\.[0-9]+$/.`);break}case`encoding`:/^[A-Za-z][A-Za-z0-9._-]*$/.test(t)||this.fail(`encoding value must match /^[A-Za-z0-9][A-Za-z0-9._-]*$/.`),this.xmlDeclExpects=[`standalone`],this.xmlDecl.encoding=t;break;case`standalone`:t!==`yes`&&t!==`no`&&this.fail(`standalone value must match "yes" or "no".`),this.xmlDeclExpects=[],this.xmlDecl.standalone=t}this.name=``,this.state=32}sXMLDeclSeparator(){let e=this.getCodeNorm();e===63?this.state=33:(i(e)||(this.fail(`whitespace required.`),this.unget()),this.state=27)}sXMLDeclEnding(){var e;this.getCodeNorm()===62?(this.piTarget===`xml`?this.name!==`version`&&this.xmlDeclExpects.includes(`version`)&&this.fail(`XML declaration must contain a version.`):this.fail(`processing instructions are not allowed before root.`),(e=this.xmldeclHandler)==null||e.call(this,this.xmlDecl),this.name=``,this.piTarget=this.text=``,this.state=13):this.fail(`The character ? is disallowed anywhere in XML declarations.`),this.xmlDeclPossible=!1}sOpenTag(){var e;let t=this.captureNameChars();if(t===-1)return;let n=this.tag={name:this.name,attributes:Object.create(null)};switch(this.name=``,this.xmlnsOpt&&(this.topNS=n.ns=Object.create(null)),(e=this.openTagStartHandler)==null||e.call(this,n),this.sawRoot=!0,!this.fragmentOpt&&this.closedRoot&&this.fail(`documents may contain only one root.`),t){case 62:this.openTag();break;case 47:this.state=35;break;default:i(t)||this.fail(`disallowed character in tag name.`),this.state=36}}sOpenTagSlash(){this.getCode()===62?this.openSelfClosingTag():(this.fail(`forward-slash in opening tag not followed by >.`),this.state=36)}sAttrib(){let e=this.skipSpaces();e!==-1&&(o(e)?(this.unget(),this.state=37):e===62?this.openTag():e===47?this.state=35:this.fail(`disallowed character in attribute name.`))}sAttribName(){let e=this.captureNameChars();e===61?this.state=39:i(e)?this.state=38:e===62?(this.fail(`attribute without value.`),this.pushAttrib(this.name,this.name),this.name=this.text=``,this.openTag()):e!==-1&&this.fail(`disallowed character in attribute name.`)}sAttribNameSawWhite(){let e=this.skipSpaces();switch(e){case-1:return;case 61:this.state=39;break;default:this.fail(`attribute without value.`),this.text=``,this.name=``,e===62?this.openTag():o(e)?(this.unget(),this.state=37):(this.fail(`disallowed character in attribute name.`),this.state=36)}}sAttribValue(){let e=this.getCodeNorm();v(e)?(this.q=e,this.state=40):i(e)||(this.fail(`unquoted attribute value.`),this.state=42,this.unget())}sAttribValueQuoted(){let{q:e,chunk:t}=this,{i:n}=this;for(;;)switch(this.getCode()){case e:this.pushAttrib(this.name,this.text+t.slice(n,this.prevI)),this.name=this.text=``,this.q=null,this.state=41;return;case 38:this.text+=t.slice(n,this.prevI),this.state=14,this.entityReturnState=40;return;case 10:case-2:case 9:this.text+=`${t.slice(n,this.prevI)} `,n=this.i;break;case 60:this.text+=t.slice(n,this.prevI),this.fail(`disallowed character.`);return;case-1:this.text+=t.slice(n);return}}sAttribValueClosed(){let e=this.getCodeNorm();i(e)?this.state=36:e===62?this.openTag():e===47?this.state=35:o(e)?(this.fail(`no whitespace between attributes.`),this.unget(),this.state=37):this.fail(`disallowed character in attribute name.`)}sAttribValueUnquoted(){let e=this.captureTo(ae);switch(e){case 38:this.state=14,this.entityReturnState=42;break;case 60:this.fail(`disallowed character.`);break;case-1:break;default:this.text.includes(`]]>`)&&this.fail(`the string "]]>" is disallowed in char data.`),this.pushAttrib(this.name,this.text),this.name=this.text=``,e===62?this.openTag():this.state=36}}sCloseTag(){let e=this.captureNameChars();e===62?this.closeTag():i(e)?this.state=44:e!==-1&&this.fail(`disallowed character in closing tag.`)}sCloseTagSawWhite(){switch(this.skipSpaces()){case 62:this.closeTag();break;case-1:break;default:this.fail(`disallowed character in closing tag.`)}}handleTextInRoot(){let{i:e,forbiddenState:t}=this,{chunk:n,textHandler:r}=this;scanLoop:for(;;)switch(this.getCode()){case 60:if(this.state=15,r!==void 0){let{text:t}=this,i=n.slice(e,this.prevI);t.length===0?i.length!==0&&r(i):(r(t+i),this.text=``)}t=0;break scanLoop;case 38:this.state=14,this.entityReturnState=13,r!==void 0&&(this.text+=n.slice(e,this.prevI)),t=0;break scanLoop;case 93:switch(t){case 0:t=1;break;case 1:t=2;break;case 2:break;default:throw Error(`impossible state`)}break;case 62:t===2&&this.fail(`the string "]]>" is disallowed in char data.`),t=0;break;case-2:r!==void 0&&(this.text+=`${n.slice(e,this.prevI)}\n`),e=this.i,t=0;break;case-1:r!==void 0&&(this.text+=n.slice(e));break scanLoop;default:t=0}this.forbiddenState=t}handleTextOutsideRoot(){let{i:e}=this,{chunk:t,textHandler:n}=this,r=!1;outRootLoop:for(;;){let a=this.getCode();switch(a){case 60:if(this.state=15,n!==void 0){let{text:r}=this,i=t.slice(e,this.prevI);r.length===0?i.length!==0&&n(i):(n(r+i),this.text=``)}break outRootLoop;case 38:this.state=14,this.entityReturnState=13,n!==void 0&&(this.text+=t.slice(e,this.prevI)),r=!0;break outRootLoop;case-2:n!==void 0&&(this.text+=`${t.slice(e,this.prevI)}\n`),e=this.i;break;case-1:n!==void 0&&(this.text+=t.slice(e));break outRootLoop;default:i(a)||(r=!0)}}r&&(!this.sawRoot&&!this.reportedTextBeforeRoot&&(this.fail(`text data outside of root node.`),this.reportedTextBeforeRoot=!0),this.closedRoot&&!this.reportedTextAfterRoot&&(this.fail(`text data outside of root node.`),this.reportedTextAfterRoot=!0))}pushAttribNS(e,t){var n;let{prefix:r,local:i}=this.qname(e),a={name:e,prefix:r,local:i,value:t};if(this.attribList.push(a),(n=this.attributeHandler)==null||n.call(this,a),r===`xmlns`){let e=t.trim();this.currentXMLVersion===`1.0`&&e===``&&this.fail(`invalid attempt to undefine prefix in XML 1.0`),this.topNS[i]=e,oe(this,i,e)}else if(e===`xmlns`){let e=t.trim();this.topNS[``]=e,oe(this,``,e)}}pushAttribPlain(e,t){var n;let r={name:e,value:t};this.attribList.push(r),(n=this.attributeHandler)==null||n.call(this,r)}end(){var e,t;this.sawRoot||this.fail(`document must contain a root element.`);let{tags:n}=this;for(;n.length>0;){let e=n.pop();this.fail(`unclosed tag: ${e.name}`)}this.state!==0&&this.state!==13&&this.fail(`unexpected end.`);let{text:r}=this;return r.length!==0&&((e=this.textHandler)==null||e.call(this,r),this.text=``),this._closed=!0,(t=this.endHandler)==null||t.call(this),this._init(),this}resolve(e){var t;let n=this.topNS[e];if(n!==void 0)return n;let{tags:r}=this;for(let t=r.length-1;t>=0;t--)if(n=r[t].ns[e],n!==void 0)return n;return n=this.ns[e],n===void 0?(t=this.opt).resolvePrefix?.call(t,e):n}qname(e){let t=e.indexOf(`:`);if(t===-1)return{prefix:``,local:e};let n=e.slice(t+1),r=e.slice(0,t);return(r===``||n===``||n.includes(`:`))&&this.fail(`malformed name: ${e}.`),{prefix:r,local:n}}processAttribsNS(){let{attribList:e}=this,t=this.tag;{let{prefix:e,local:n}=this.qname(t.name);t.prefix=e,t.local=n;let r=t.uri=this.resolve(e)??``;e!==``&&(e===`xmlns`&&this.fail(`tags may not have "xmlns" as prefix.`),r===``&&(this.fail(`unbound namespace prefix: ${JSON.stringify(e)}.`),t.uri=e))}if(e.length===0)return;let{attributes:n}=t,r=/* @__PURE__ */ new Set;for(let t of e){let{name:e,prefix:i,local:a}=t,o,s;i===``?(o=e===`xmlns`?h:``,s=e):(o=this.resolve(i),o===void 0&&(this.fail(`unbound namespace prefix: ${JSON.stringify(i)}.`),o=i),s=`{${o}}${a}`),r.has(s)&&this.fail(`duplicate attribute: ${s}.`),r.add(s),t.uri=o,n[e]=t}this.attribList=[]}processAttribsPlain(){let{attribList:e}=this,t=this.tag.attributes;for(let{name:n,value:r}of e)t[n]!==void 0&&this.fail(`duplicate attribute: ${n}.`),t[n]=r;this.attribList=[]}openTag(){var e;this.processAttribs();let{tags:t}=this,n=this.tag;n.isSelfClosing=!1,(e=this.openTagHandler)==null||e.call(this,n),t.push(n),this.state=13,this.name=``}openSelfClosingTag(){var e,t;this.processAttribs();let{tags:n}=this,r=this.tag;r.isSelfClosing=!0,(e=this.openTagHandler)==null||e.call(this,r),(t=this.closeTagHandler)==null||t.call(this,r),(this.tag=n[n.length-1]??null)===null&&(this.closedRoot=!0),this.state=13,this.name=``}closeTag(){let{tags:e,name:t}=this;if(this.state=13,this.name=``,t===``){this.fail(`weird empty close tag.`),this.text+=`</>`;return}let n=this.closeTagHandler,r=e.length;for(;r-->0;){let r=this.tag=e.pop();if(this.topNS=r.ns,n?.(r),r.name===t)break;this.fail(`unexpected close tag.`)}r===0?this.closedRoot=!0:r<0&&(this.fail(`unmatched closing tag: ${t}.`),this.text+=`</${t}>`)}parseEntity(e){if(e[0]!==`#`){let t=this.ENTITIES[e];return t===void 0?(this.fail(this.isName(e)?`undefined entity.`:`disallowed character in entity name.`),`&${e};`):t}let t=NaN;return e[1]===`x`&&/^#x[0-9a-f]+$/i.test(e)?t=parseInt(e.slice(2),16):/^#[0-9]+$/.test(e)&&(t=parseInt(e.slice(1),10)),this.isChar(t)?String.fromCodePoint(t):(this.fail(`malformed character entity.`),`&${e};`)}}})))();const ea=e=>{let t=0;for(let n of e){let e=n.codePointAt(0)??0;t+=e<128?1:e<2048?2:e<65536?3:4}return t},ta=/* @__PURE__ */ new Set([`svg`,`g`,`path`,`rect`,`circle`,`ellipse`,`line`,`polyline`,`polygon`,`text`,`tspan`,`defs`,`clipPath`,`linearGradient`,`radialGradient`,`stop`,`title`,`desc`]),na=/* @__PURE__ */ new Set(/* @__PURE__ */ `xmlns.xmlns:xlink.version.baseProfile.id.class.x.y.x1.y1.x2.y2.cx.cy.r.rx.ry.fx.fy.dx.dy.width.height.viewBox.preserveAspectRatio.transform.d.points.offset.gradientUnits.gradientTransform.clipPathUnits.fill.fill-opacity.fill-rule.clip-path.clip-rule.stroke.stroke-width.stroke-opacity.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-dasharray.stroke-dashoffset.stop-color.stop-opacity.opacity.paint-order.pointer-events.font-family.font-size.font-weight.font-style.text-anchor.dominant-baseline.xml:space.style.ecmeta_ssr_type.ecmeta_series_index.ecmeta_data_index.ecmeta_ssr_component.ecmeta_ssr_component_index`.split(`.`)),ra=/* @__PURE__ */ new Set([`font-size`,`font-family`,`font-weight`,`font-style`,`fill`,`fill-opacity`,`stroke`,`stroke-width`,`stroke-opacity`,`opacity`,`paint-order`,`white-space`]),ia=/url\s*\(([^)]*)\)/gi,aa=/^\s*(['"]?)#[\w.:-]+\1\s*$/,oa=/javascript:|vbscript:|data:|expression\s*\(|@import|https?:|\/\//i,sa=/[\\<>]|\/\*/,Q=e=>{throw new Ji(e)},ca=(e,t)=>{sa.test(t)&&Q(`forbidden character in attribute ${e}`),oa.test(t)&&Q(`forbidden value in attribute ${e}`);for(let n of t.matchAll(ia))aa.test(n[1]??``)||Q(`non-local url() in attribute ${e}`)},la=e=>{for(let t of e.split(`;`)){if(t.trim()===``)continue;let e=t.indexOf(`:`),n=(e===-1?t:t.slice(0,e)).trim().toLowerCase();ra.has(n)||Q(`style property ${n} is not allowed`)}},ua=(e,t,n)=>{na.has(t)||Q(`attribute ${t} on <${e}> is not allowed`),t===`xmlns`?n!==`http://www.w3.org/2000/svg`&&Q(`unexpected namespace`):t===`xmlns:xlink`?n!==`http://www.w3.org/1999/xlink`&&Q(`unexpected namespace`):(ca(t,n),t===`style`&&la(n))},da=(e,t)=>{let n=ea(e);if(n>t)throw new Yi({bytes:n,maxBytes:t});let r=new $i.SaxesParser({xmlns:!1}),i=0,a=!1;r.on(`error`,e=>Q(`malformed svg: ${e.message}`)),r.on(`doctype`,()=>Q(`doctype is not allowed`)),r.on(`xmldecl`,()=>Q(`xml declaration is not allowed`)),r.on(`processinginstruction`,()=>Q(`processing instructions are not allowed`)),r.on(`comment`,()=>Q(`comments are not allowed`)),r.on(`cdata`,()=>Q(`cdata sections are not allowed`)),r.on(`opentag`,e=>{i===0&&((a||e.name!==`svg`)&&Q(`root element must be a single <svg>`),a=!0),i+=1,i>64&&Q(`elements are nested too deeply`),ta.has(e.name)||Q(`element <${e.name}> is not allowed`);for(let[t,n]of S(e.attributes))ua(e.name,t,n)}),r.on(`closetag`,()=>{--i}),r.write(e).close(),a||Q(`root element must be a single <svg>`)},fa=(e,t)=>`${t.toISOString().replaceAll(/[:.]/g,`-`)}-${o(3).toString(`hex`)}-${e}`,pa=e=>new R(`write_failed`,e instanceof Error?e.message:`the result could not be written`),ma=(e,t)=>e instanceof Error&&b(e,`code`)&&e.code===t,ha=async e=>{for(let t of[v.dirname(e),e]){await d(t,{mode:448}).catch(e=>{if(!ma(e,`EEXIST`))throw e});let e=await u(t);if(e.isSymbolicLink()||!e.isDirectory())throw new R(`unsafe_location`,`${t} is not a real directory (symbolic links are not followed)`)}},ga=async e=>{for(let t of[v.dirname(e),e]){let e=await u(t).catch(e=>{if(ma(e,`ENOENT`))return null;throw e});if(e==null||e.isSymbolicLink()||!e.isDirectory())return!1}return!0},_a=async e=>{try{await e()}catch(e){throw pa(e)}},va=async(e,t)=>{let n=v.join(e.outputDir,fa(e.fileName,e.now)),r;try{await ha(e.outputDir),r=await f(n,`wx`,384)}catch(e){throw e instanceof R?e:pa(e)}try{let e=await t(r);return await _a(()=>r.close()),{path:n,...e}}catch(e){throw await r.close().catch(T),await _(n,{force:!0}).catch(T),e}},ya=async(e,t)=>{if(e.byteLength>t.maxBytes)throw new R(`too_large`,`the result exceeds ${t.maxBytes} bytes`);return va(t,async t=>(await _a(()=>t.writeFile(e)),{bytes:e.byteLength,sha256Hex:a(`sha256`).update(e).digest(`hex`)}))},ba=(e,t)=>va(t,async n=>{let r=a(`sha256`),i=0;for await(let a of e){if(i+=a.byteLength,i>t.maxBytes)throw new R(`too_large`,`the result exceeds ${t.maxBytes} bytes`);r.update(a),await _a(async()=>{await n.write(a)})}return{bytes:i,sha256Hex:r.digest(`hex`)}}),xa=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z-[0-9a-f]{6}-/,Sa=async(e,t)=>{if(!await ga(e))return 0;let n;try{n=await m(e,{withFileTypes:!0})}catch(e){if(ma(e,`ENOENT`))return 0;throw e}let r=t.now.getTime()-t.maxAgeMs;return(await Promise.all(n.filter(e=>e.isFile()&&xa.test(e.name)).map(async t=>{let n=v.join(e,t.name),i=await u(n);return!i.isFile()||i.mtimeMs>=r?!1:(await _(n,{force:!0}),!0)}))).filter(Boolean).length},Ca=e=>e.split(`/`).slice(1),wa=(e,t,n)=>{if(e===`image/svg+xml`)da(t,n);else throw new Ji(`unknown artifact media type`)},Ta=e=>e instanceof R?e.kind:e instanceof Yi?`too_large`:e instanceof Ji?`unsafe_content`:`unexpected`,Ea=async(e,t,n)=>{if(e.isError||t.length===0||!w(e.payload))return e;let r=e.payload.body;if(!w(r))return e;let i=structuredClone(r);for(let e of t){let t=Ca(e.pointer),r=t.pop(),a=i;for(let e of t)a=w(a)&&b(a,e)?a[e]:null;if(r==null||!w(a)||typeof a[r]!=`string`)continue;let o=a;try{let t=G(String(o[r]),n.secrets);wa(e.mediaType,t,n.maxBytes);let i=Buffer.from(t,`utf8`);o[r]={file:{...await ya(i,{outputDir:n.outputDir,fileName:`${n.operationId}.${e.extension}`,maxBytes:n.maxBytes,now:n.now}),mediaType:e.mediaType}}}catch(e){o[r]={error:{kind:`artifact_not_saved`,failure:Ta(e)}}}}return{isError:!1,payload:{...e.payload,body:i}}},Da=e=>Array.isArray(e),Oa=`#/$defs/`,ka=/* @__PURE__ */ new Set([`oneOf`,`anyOf`,`allOf`,`prefixItems`]),Aa=/* @__PURE__ */ new Set([`items`,`additionalProperties`,`propertyNames`,`not`]),ja=e=>Array.isArray(e)?e.map(e=>ja(e)):w(e)?C(S(e).flatMap(([e,t])=>{if(e!==`$comment`||typeof t!=`string`)return[[e,ja(t)]];if(!t.startsWith(`Additional constraints are validated by the server`))return[[e,t]];let n=t.slice(50);return n.startsWith(`: `)?[[e,n.slice(2)]]:[]})):e,Ma=(e,t)=>w(e)&&x(e).length===1&&Array.isArray(e[t]),Na=e=>Array.isArray(e)?e.map(e=>Na(e)):w(e)?C(S(e).map(([e,t])=>{let n=Na(t);return e!==`anyOf`&&e!==`oneOf`||!Array.isArray(n)?[e,n]:[e,n.flatMap(t=>{let n=Ma(t,e)?t[e]:null;return Da(n)?n:[t]})]})):e,Pa=(e,t)=>{let n=e.properties;if(!w(n))return null;let r=n[t];return w(r)&&x(r).length===1&&b(r,`const`)?r:null},Fa=(e,t)=>Pa(e,t)?.const,Ia=e=>{let t=e.properties;return w(t)?x(t).filter(t=>Pa(e,t)!=null):[]},La=(e,t)=>{let n=w(e.properties)?e.properties:{};return`${t}${JSON.stringify({...e,properties:{...n,[t]:`\0`}})}`},Ra=e=>{let t=/* @__PURE__ */ new Map;for(let[n,r]of e.entries())if(w(r))for(let e of Ia(r)){let i=La(r,e),a=t.get(i);a==null?t.set(i,[n]):a.push(n)}let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set,i=[...t].toSorted(([,e],[,t])=>t.length-e.length);for(let[t,a]of i){let i=a.filter(e=>!r.has(e)),[o]=i;if(o==null||i.length<2)continue;let s=t.slice(0,t.indexOf(`\0`)),c=e[o];if(!w(c)||!w(c.properties))continue;let l=i.map(t=>{let n=e[t];return w(n)?Fa(n,s):void 0});for(let e of i)r.add(e);n.set(o,{...c,properties:{...c.properties,[s]:{enum:l}}})}return e.flatMap((e,t)=>n.has(t)?[n.get(t)]:r.has(t)?[]:[e])},za=e=>Array.isArray(e)?e.map(e=>za(e)):w(e)?C(S(e).map(([e,t])=>{let n=za(t);return(e===`anyOf`||e===`oneOf`)&&Array.isArray(n)?[e,Ra(n)]:[e,n]})):e,Ba=(e,t)=>C(S(e).map(([e,n])=>(e===`properties`||e===`$defs`)&&w(n)?[e,C(S(n).map(([e,n])=>[e,w(n)?t(n):n]))]:ka.has(e)&&Array.isArray(n)?[e,n.map(e=>w(e)?t(e):e)]:Aa.has(e)&&w(n)?[e,t(n)]:[e,n])),Va=(e,t,n)=>{let r=/* @__PURE__ */ new Map,i=e=>{let t=JSON.stringify(e);return t.length>=n&&r.set(t,(r.get(t)??0)+1),Ba(e,i)};Ba(e,i);for(let e of ue(t))w(e)&&Ba(e,i);return r},Ha=(e,t,n)=>{let r=null,i=0;for(let[a,o]of e){let e=o*(a.length-t)-a.length-n;o>1&&e>i&&(r=a,i=e)}return r},Ua=(e,t)=>{let n=e;for(let e=1;;e+=1){let r=w(n.$defs)?n.$defs:{},i=`shared${String(e)}`;for(;b(r,i);)i=`_${i}`;let a=`${Oa}${i}`,{$defs:o,...s}=n,c=Ha(Va(s,r,t),JSON.stringify({$ref:a}).length,JSON.stringify({[i]:null}).length);if(c==null)return n;let l=e=>JSON.stringify(e)===c?{$ref:a}:Ba(e,l),u=Ba(s,l),d=C(S(r).map(([e,t])=>[e,w(t)?Ba(t,l):t])),f=JSON.parse(c);n={...u,$defs:C([...S(d),[i,f]].toSorted(([e],[t])=>de(e,t)))}}},Wa=e=>{let t=e.lastIndexOf(`__`);return t===-1?``:e.slice(0,t+2)},Ga=e=>{let t=e.$defs;if(!w(t))return e;let n=x(t),[r]=n;if(r==null)return e;let i=Wa(r);for(;i!==``&&!n.every(e=>e.startsWith(i)&&e!==i);)i=Wa(i.slice(0,-2));if(i===``)return e;let a=`${Oa}${i}`,o=e=>Array.isArray(e)?e.map(e=>o(e)):w(e)?C(S(e).map(([e,t])=>e===`$ref`&&typeof t==`string`&&t.startsWith(a)?[e,`${Oa}${t.slice(a.length)}`]:e===`$defs`&&w(t)?[e,C(S(t).map(([e,t])=>[e.startsWith(i)?e.slice(i.length):e,o(t)]))]:[e,o(t)])):e,s=o(e);return w(s)?s:e},Ka=(e,t)=>{let n=za(Na(ja(e)));return Ua(Ga(w(n)?n:e),t)},qa=e=>typeof e==`string`&&e.startsWith(`#/$defs/`)?e.slice(8).replaceAll(`~1`,`/`).replaceAll(`~0`,`~`):null,Ja=(e,t)=>{let n=/* @__PURE__ */ new Map,r=e=>{if(Array.isArray(e))for(let t of e)r(t);else if(w(e))for(let[i,a]of S(e)){let e=i===`$ref`?qa(a):null;e==null?r(a):n.has(e)||(n.set(e,t[e]),r(t[e]))}};return r(e),C([...n].toSorted(([e],[t])=>de(e,t)))},Ya=[`anyOf`,`oneOf`,`allOf`],Xa=`The server also validates constraints that JSON Schema cannot express; $comment states them where known.`,Za=(e,t)=>{let n=e;for(let e=0;e<16;e+=1){let e=n.$ref;if(typeof e!=`string`||!e.startsWith(`#/$defs/`))return n;let r=t[e.slice(8)];if(!w(r))return n;n=r}return n},Qa=(e,t,n)=>{let r=Za(e,n),i=r.properties;if(w(i)&&w(i[t]))return i[t];let a=r.items;if(w(a))return Qa(a,t,n);let o=Ya.flatMap(e=>{let i=r[e];return Array.isArray(i)?i.flatMap(e=>{let r=w(e)?Qa(e,t,n):null;return r==null?[]:[r]}):[]}),[s]=o;return s==null?null:o.length===1?s:{anyOf:o}},$a=(e,t)=>{let n=Za(e,t),r=n.properties;if(w(r))return x(r);let i=Ya.flatMap(e=>{let r=n[e];return Array.isArray(r)?r.flatMap(e=>w(e)?$a(e,t):[]):[]});return[...new Set(i)]},eo=(e,t,n)=>{let r=e;for(let e of t.split(`.`)){if(r==null)return null;r=Qa(r,e,n)}return r},to=(e,t)=>{let n=Ja(e,t);return x(n).length===0?e:{...e,$defs:n}},no=(e,t,n)=>{let r=[],i=e=>{if(!(r.length>=2)){if(Array.isArray(e))for(let t of e)i(t);else if(w(e)){if(e[t]===n)r.push(e);else for(let t of ue(e))i(t)}}};for(let t of e)i(t.value);return r},ro=e=>({isError:!0,payload:{error:e}}),io=(e,t)=>ro({kind:`unknown_path`,message:e,keys:t}),ao=(e,t)=>{let{operationId:n}=e,{$defs:r,...i}=e.fullInputSchema,a=w(r)?r:{},o=t==null?i:eo(i,t,a);if(o==null)return io(`The input of ${n} has no key path "${t??``}". Use a key below, or join nested keys with "." (array items are entered implicitly).`,$a(i,a));let s=e.inputDetails;return{isError:!1,payload:{operationId:n,...t==null?{description:e.description,hint:`To get only part of the schema, call ${N} again with path set to a key (nested keys joined with ".").`}:{selectedPath:t},...s==null||t!=null?{}:{groups:s.groups.map(e=>({path:e.path,discriminator:e.discriminator,description:e.description,types:e.variants.map(t=>({[e.discriminator]:t.value,summary:t.summary}))})),typeHint:`The keys at each group path depend on ${s.groups[0]?.discriminator??`type`}. Call ${N} with type to get the full shape of one type before sending it.`},note:Xa,schema:Ka(to(o,a),80),...s==null||t!=null?{}:{examples:s.examples}}}},oo=(e,t,n,r)=>{let i=e.get(t);if(i==null)return ro({kind:`unknown_operation`,message:`${t} is not a tool of this server.`,operationIds:[...e.keys()]});if(n==null)return ao(i,r);let a=i.inputDetails,o=(a?.groups??[]).flatMap(e=>e.variants.filter(e=>e.value===n).map(t=>({group:e,variant:t})));if(a==null||o.length===0)return ro({kind:`unknown_type`,message:a==null?`The input of ${t} does not depend on a type. Call ${N} without type.`:`${t} has no input type "${n}". Call ${N} without type to list the types.`,types:(a?.groups??[]).flatMap(e=>e.variants.map(e=>e.value))});let s=[];for(let{group:e,variant:i}of o){let o=$a(i.schema,a.definitions),c=r==null?i.schema:eo(i.schema,r,a.definitions);if(c==null)return io(`The ${n} input of ${t} has no key path "${r??``}". Use a key below, or join nested keys with "." (array items are entered implicitly, e.g. "aggregates.query").`,o);s.push({path:r==null?e.path:`${e.path}.${r}`,discriminator:e.discriminator,...r==null?{keys:o,examples:no(a.examples,e.discriminator,n)}:{},schema:Ka(to(c,a.definitions),80)})}return{isError:!1,payload:{operationId:t,type:n,...r==null?{hint:`To get only part of the schema, call ${N} again with path set to one of keys (nested keys joined with ".").`}:{selectedPath:r},note:Xa,schemas:s}}},so=(e,t)=>{let n=``,r=0,i=e.indexOf(`{`);for(;i!==-1;){let a=e.indexOf(`}`,i+1);if(a===-1)break;n+=a===i+1?e.slice(r,a+1):e.slice(r,i)+t(e.slice(i+1,a)),r=a+1,i=e.indexOf(`{`,r)}return n+e.slice(r)},co=(e,t)=>{if(typeof t==`string`)return t;if(typeof t==`number`||typeof t==`boolean`)return String(t);throw new He(`argument "${e}" must be a string, number, or boolean`)},lo=/* @__PURE__ */ new Set([`.`,`..`,`%2e`,`.%2e`,`%2e.`,`%2e%2e`]),uo=(e,t)=>{if(t===``||lo.has(t.toLowerCase()))throw new He(`path parameter "${e}" must not be empty, "." or ".."`);return encodeURIComponent(t)},fo=(e,t,n)=>{if(b(n,`tenantName`))throw new He(`"${Un}" is fixed by the server configuration`);let r=so(t.pathTemplate,t=>{if(t===`tenantName`)return encodeURIComponent(e.tenantName);let r=n[t];if(r==null)throw new He(`path parameter "${t}" is required`);return uo(t,co(t,r))}),i=[];for(let e of t.queryParams){let t=n[e];if(t!=null){if(Array.isArray(t))for(let n of t)i.push([e,co(e,n)]);else i.push([e,co(e,t)])}}let a=null,o=!1;if(t.wholeBodyField!=null){if(!b(n,t.wholeBodyField))throw new He(`argument "${t.wholeBodyField}" is required`);a=n[t.wholeBodyField],o=!0}else if(t.bodyFields!=null){let e={};for(let r of t.bodyFields)b(n,r)&&(e[r]=n[r]);a=e,o=!0}return{method:t.method,path:r,query:i,hasBody:o,body:a,responseKind:t.responseKind}},po=async(e,t)=>{try{return await e.preflight(),{isError:!1,payload:await t()}}catch(t){let n=e.secrets(),r=JSON.parse(G(JSON.stringify(e.errorPayload(t,n)),n));return e.onFailure(t,r),{isError:!0,payload:r}}},mo=(e,t)=>{if(e instanceof F){let{retryAfterSeconds:t,status:n}=e.info;return{error:{kind:`api`,...e.info,...t==null?{}:{hint:`${n===429?`Rate limited; the request was not processed. `:``}Wait ${String(t)} seconds, then call the tool again.`}}}}return e instanceof I?{error:{kind:`transport`,failure:e.kind,status:e.status,message:e.message,...t===`write`?{note:`The write may have completed on the server even though no valid response was received. Check the current state with list_* / get_* / search_records before running it again.`}:{}}}:null},ho=(e,t,n)=>{let r=mo(e,n);if(r!=null)return{isError:!0,payload:r};if(e instanceof R)return{isError:!0,payload:{error:{kind:`result_not_saved`,failure:e.kind,message:`The file could not be saved to the output directory.`}}};if(e instanceof He)return{isError:!0,payload:{error:{kind:`invalid_arguments`,message:e.message}}};if(e instanceof z)return{isError:!0,payload:{error:{kind:`workspace`,failure:e.kind,message:e.message}}};if(e instanceof P)return{isError:!0,payload:{error:{kind:`auth`,failure:e.kind,message:e.message}}};if(e instanceof Error)return{isError:!0,payload:{error:{kind:`unexpected`,message:G(e.message,t)}}};throw e},go=(e,t,n)=>po({preflight:async()=>{await Ot(e.workspace,new Date(e.now())),await e.auth.assertLoggedIn()},secrets:()=>e.auth.secrets(),errorPayload:(e,n)=>ho(e,n,t.effect).payload,onFailure:(n,r)=>{e.logger.warn(`tool call failed`,{operationId:t.operationId,payload:r})}},n),_o=async(e,t,n)=>go(e,t,async()=>{let r=await e.client.request(fo(e.config,t,n));switch(r.kind){case`json`:return{status:r.status,requestId:r.requestId,body:r.body};case`empty`:return{status:r.status,requestId:r.requestId};case`file`:try{let n=await ba(r.chunks,{outputDir:e.config.outputDir,fileName:`${t.operationId}.json`,maxBytes:2147483648,now:new Date(e.now())});return{status:r.status,requestId:r.requestId,file:{...n,format:`json`}}}finally{await r.cancel()}default:throw Error(`unknown response kind`)}}),vo=(e,t)=>`Flyle AI CX の公開 API を呼ぶツール群です。テーブルとレコードの参照・検索・作成・更新・削除、ロールの設定・割り当て、レポート・ダッシュボードの作成・編集、AI グルーピングの作成・編集・削除、ワークフローの参照と下書きの作成・更新、フォームの参照と編集を、ログインしたユーザーの権限で行います。
|
|
104
107
|
- 作業を始める前に必ず ${Y} で製品の考え方とご利用ガイドの記事一覧を確認し、依頼に関係する記事を ${Z} で読んでください。公開 API の操作は ${Y} を呼ぶまで実行されません。ツールに無い操作は代わりの手順を組み立てず、該当する記事を示して画面での操作を案内してください。
|
|
105
108
|
- 顧客の環境を利用者の合意なしに変えないでください。まず読み取り系ツール(readOnlyHint)で調べ、どの設定・データをどう変えるか(対象、変更前 → 変更後、影響)と理由を示して、利用者の明示的な合意を得てから書き込み系ツールを呼びます。合意した範囲を超える変更が必要になったら、その都度改めて合意を得てください。preview_* や search_* など、設定やデータを変えない確認は合意なしで進めて構いません。利用者が合意を省いてよいと明示した場合は、その範囲に限って確認を省けます。
|
|
106
109
|
- ロールの変更(create_role / update_role / update_role_assignments / delete_role)はテナントの全員の権限に直ちに影響します。実行前に list_roles / get_role で対象と現在の設定を確かめ、変更内容(対象・変更前 → 変更後)を利用者に示して明示的な同意を得てから実行してください。
|
|
107
110
|
- AI グルーピング(create_ai_grouping / update_ai_grouping / delete_ai_grouping)は対象テーブルに出力用の選択肢フィールドを作り、スケジュールに従って LLM で全レコードを分類します(AI の利用量に計上されます)。実行前に get_table で入力フィールド(PLAIN_TEXT)とフィールド名の重複を確かめ、作成・変更する内容(出力フィールド名・階層・スケジュール)を利用者に示して同意を得てください。作成しただけでは分類は走りません。今すぐ分類するには start_ai_grouping_job を使い、FULL・ONLY_ASSIGN は AI の利用量に計上されるので実行前に利用者の同意を得てください。分類もグループの移動・統合・削除(move_ai_grouping_groups / merge_ai_grouping_groups / delete_ai_grouping_group)も非同期になりうるので、応答が status queued やジョブを返したら get_ai_grouping_job で SUCCEEDED などの終わった状態になるまで確かめてから結果を報告します。統合・移動・削除はレコードの値を書き換えるので、対象のグループ(list_ai_grouping_groups)と影響を利用者に示して同意を得てください。スケジュールは 1 時間に 1 回まで(cron 式の分は 1 つの値)で、FULL は実行のたびにテーブルの全レコードを分類し直すので、頻度は利用者と決めてください。作成の応答を受け取れずに再送して出力フィールド名の重複で 400 になったら、list_ai_groupings で作成済みかを確かめてください。削除しても出力フィールドと分類済みの値はテーブルに残ります。
|
|
108
|
-
- ワークフロー(create_workflow / update_workflow)は下書きとして保存するだけで、保存しても公開はされません(動き出しません)。公開は利用者が画面で中身を確かめて行うよう案内してください。応答の issues に直すべき箇所が、publishable に公開できる状態かが返ります。update_workflow の nodes / edges は配列ごとの置き換えなので、get_workflow の結果を編集して送ってください。保存先の folderId は list_folders で探します。ノードの config の書き方(type ごとの設定項目)と入力例は ${
|
|
109
|
-
-
|
|
111
|
+
- ワークフロー(create_workflow / update_workflow)は下書きとして保存するだけで、保存しても公開はされません(動き出しません)。公開は利用者が画面で中身を確かめて行うよう案内してください。応答の issues に直すべき箇所が、publishable に公開できる状態かが返ります。update_workflow の nodes / edges は配列ごとの置き換えなので、get_workflow の結果を編集して送ってください。保存先の folderId は list_folders で探します。ノードの config の書き方(type ごとの設定項目)と入力例は ${N} で取得します。変更を取り消すときは、変更前の get_workflow の version を restore_workflow_version に渡します(戻した変更も、戻す前の version を渡せばやり直せます)。
|
|
112
|
+
- フォーム(update_form / restore_form_version)には下書きが無く、公開中のフォームは保存した内容がすぐに回答者に見えます。設問を消したり回答の型を変えたりすると、回答を保存しているフィールドも消えます。実行前に get_form で今の内容を確かめ、変更内容を利用者に示して同意を得てください。sections は配列ごとの置き換えなので、get_form の結果を編集して送ってください。公開の状態(status・isPublic・受付期間)は変えられないので、画面で変えるよう案内してください。変更を取り消すときは、変更前の get_form の version を restore_form_version に渡します。
|
|
113
|
+
- ツールの説明は要約で、大きい入力 schema は最上位のキーと型だけを載せています。説明の全文(制約・エラー・値の形式)と入力 schema の全体・入力例は ${N}(operationId)で取得します。create_* / update_* / preview_* は、呼ぶ前に必ず ${N} で入力の形を確かめてください。型ごとに形が違う入力(レポートの reportOption、ワークフローのノードの config、フィールドの作成など)は、type を指定してその型の形を取得します。大きい結果はファイルに保存されるので、必要な部分だけを path(例: "filter"、"aggregates")で取得できます。
|
|
110
114
|
- 接続先テナントは「${e}」、環境(公開 API のホスト)は「${t}」です。テナント・環境・ログインはサーバー起動時に固定されており、ツール引数でテナントを指定することはできません。
|
|
111
115
|
- この作業ディレクトリは「${e}」専用です。別の顧客(テナント)の情報・ファイル・記憶をこのテナントへの書き込みに使わないでください。別テナントの作業は別ディレクトリの別セッションで行います。
|
|
112
116
|
- 各ツール結果の先頭の environment と tenantName は、その操作を実行した環境とテナントです。
|
|
113
117
|
- ツール説明の「HTTP:」は呼び出す公開 API の操作で、パスは /v0/tenants/{tenantName} からの相対です。「先に読む記事:」の記事は ${Z} で読みます。
|
|
114
118
|
- ツールが「ログインが必要です」と返したら、ツール結果に示されたコマンドを利用者に作業ディレクトリで実行してもらってください。--api-base-url などの引数を書き足したり変えたりしないでください(接続先は利用者自身が確かめて指定します)。
|
|
115
|
-
- レコードを検索・書き込む前に list_tables でテーブルを探し、get_table でフィールド ID・型・選択肢を確認してください。値の形式は型で決まり、${
|
|
119
|
+
- レコードを検索・書き込む前に list_tables でテーブルを探し、get_table でフィールド ID・型・選択肢を確認してください。値の形式は型で決まり、${N}(operationId: "create_record")の values の説明にあります。values のキーはフィールド名ではなくフィールド ID です。選択肢が多く optionsTruncated が true のフィールドは、list_select_options で選択肢 ID を探してください。
|
|
116
120
|
- search_records の結果は検索インデックス由来で、書き込み直後は数秒遅れることがあります。1 件の最新状態は get_record で確認してください。
|
|
117
121
|
- 書き込み系ツール(readOnlyHint: false)はテナントのデータを直ちに書き換えます(create_workflow / update_workflow は下書きを保存するだけで、公開も実行もしません)。書き込み系ツールは自動再送しません。Idempotency-Key はログイン接続では使えないため、タイムアウトや transport エラーの後は書き込みが完了している可能性があります。list_* / get_* / search_records で状態を確認してから再実行してください。
|
|
118
122
|
- 結果に error.kind = "result_not_saved" と operationCompleted: true があれば、操作は完了しており全文の保存だけに失敗しています。同じ操作を再実行しないでください。
|
|
119
123
|
- 大きな JSON 結果は出力ディレクトリに全文を保存し、保存先と先頭部分を返します。全文は保存ファイルを参照してください。
|
|
120
|
-
- レポート・ダッシュボードを作成・更新する前に preview_report / preview_dashboard で下書きを画像(SVG)にし、保存先のファイルを利用者に開いてもらって見た目(グラフの種類・軸・配色・配置)の同意を得てから create_* / update_* を実行してください。プレビューは何も保存しません。プレビューの応答に values(集計した数値)があれば、件数や集計値は画像ではなく values から読んでください。保存先の folderId は get_table の folderId(テーブルと同じフォルダ)か、既存のレポート・ダッシュボードの folderPath の末尾の ID です。update_dashboard の items は全カードの置き換えなので、読めないカード(他の人のレポートなど)も get_dashboard の結果のまま含めて送ってください。外すとダッシュボードから消えます。`,
|
|
121
|
-
`)},
|
|
122
|
-
引数なしで起動すると MCP サーバー(stdio)として動きます。`,2);await
|
|
124
|
+
- レポート・ダッシュボードを作成・更新する前に preview_report / preview_dashboard で下書きを画像(SVG)にし、保存先のファイルを利用者に開いてもらって見た目(グラフの種類・軸・配色・配置)の同意を得てから create_* / update_* を実行してください。プレビューは何も保存しません。プレビューの応答に values(集計した数値)があれば、件数や集計値は画像ではなく values から読んでください。保存先の folderId は get_table の folderId(テーブルと同じフォルダ)か、既存のレポート・ダッシュボードの folderPath の末尾の ID です。update_dashboard の items は全カードの置き換えなので、読めないカード(他の人のレポートなど)も get_dashboard の結果のまま含めて送ってください。外すとダッシュボードから消えます。`,yo=e=>w(e)&&e.type===`object`&&w(e.properties),bo=(e,t)=>{if(!yo(e))throw Error(`${t}: input schema must be an object schema`);return e},xo=`/v0/tenants/{${Un}}`,So={create_workflow:`下書きを保存するだけで、公開も実行もしません。`,update_workflow:`下書きを保存するだけで、公開も実行もしません。`,restore_workflow_version:`下書きを保存するだけで、公開も実行もしません。`},Co=e=>e.startsWith(xo)?e.slice(xo.length):e,wo=/(?<=\.)\s+/u,To=e=>{let t=[],n=0;for(let r of e.split(wo)){if(t.length>0&&n+r.length>280)break;t.push(r),n+=r.length+1}return t.join(` `)},Eo=e=>{let t=[e.summary];e.description!=null&&t.push(``,To(e.description)),t.push(``,`HTTP: ${e.method} ${Co(e.pathTemplate)}`);let n=gi(e.operationId);n!=null&&t.push(``,n);let r=hi(e.operationId);r!=null&&t.push(``,r);let i=So[e.operationId];return i!=null&&t.push(``,i),e.wholeBodyField!=null&&t.push(``,`リクエストボディは "${e.wholeBodyField}" 引数にそのまま渡します(判別共用体)。`),t.join(`
|
|
125
|
+
`)},Do=/* @__PURE__ */ new Set([`update_role_assignments`]),Oo=/* @__PURE__ */ new Set([`PUT`,`PATCH`,`DELETE`]),ko=e=>({readOnlyHint:e.effect===`read`,destructiveHint:e.effect!==`read`,idempotentHint:e.effect===`read`||Oo.has(e.method)||Do.has(e.operationId),openWorldHint:!1}),Ao=e=>{let t=e.slice(0,4096),n=t.codePointAt(t.length-1)??0;return n>=55296&&n<=56319?t.slice(0,-1):t},jo=(e,t,n)=>({content:[{type:`text`,text:JSON.stringify({environment:e.environment,tenantName:e.tenantName})},{type:`text`,text:t}],isError:n}),$=async(e,t)=>{let{secrets:n}=t,r=G(JSON.stringify(e.payload,null,t.indent?2:void 0)??`null`,n);if(r.length<=t.maxTextChars)return jo(t,r,e.isError);let i=Buffer.from(G(JSON.stringify(e.payload)??`null`,n),`utf8`),a={totalChars:r.length,preview:Ao(r)};try{let n=await ya(i,{outputDir:t.outputDir,fileName:t.fileName,maxBytes:t.maxFileBytes,now:t.now});return jo(t,JSON.stringify({file:{...n,format:`json`},...a},null,2),e.isError)}catch(n){let r=n instanceof R?n.kind:`unexpected`;t.logger.warn(`tool result could not be saved`,{fileName:t.fileName,failure:r,bytes:i.byteLength});let o=!e.isError,s=t.effect===`write`?`The operation completed. Only saving the full result failed; do not run the operation again. The preview below is the beginning of the result.`:`The operation completed. Only saving the full result failed; the preview below is the beginning of the result.`;return jo(t,JSON.stringify({error:{kind:`result_not_saved`,failure:r,operationCompleted:o,message:o?s:`The operation failed and its full error was not saved; only the preview below is available.`},...a},null,2),e.isError)}},Mo=(e,t,n)=>({environment:H(e.config.baseUrl),tenantName:e.config.tenantName,effect:n,outputDir:e.config.outputDir,fileName:`${t}.result.json`,logger:e.logger,secrets:e.auth.secrets(),maxFileBytes:67108864,maxTextChars:1048576,indent:!0,now:new Date(e.now())}),No=e=>w(e)?e:{},Po={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},Fo=async(e,t)=>{let n=t.operations.find(e=>e.operationId===`list_advanced_guides`);if(n==null)return null;let r=await _o(e,n,{});return r.isError||!w(r.payload)?null:ai(r.payload.body)},Io=(e,t,n,r)=>{e.registerTool(Y,{title:`Read the Flyle AI CX product overview and guide index`,description:`作業の最初に呼びます。Flyle AI CX の考え方(テーブル・レポート・ワークフロー・ロールなどの概念)、この MCP サーバーでできること・できないこと、よくある依頼の進め方と、ご利用ガイドの全記事の一覧を返します。これを呼ぶまで公開 API の操作は実行されません。`,inputSchema:y({type:`object`,properties:{}}),annotations:Po},async()=>(r(),$(xi(await Fo(t,n)),Mo(t,Y,`read`)))),e.registerTool(X,{title:`Search the Flyle AI CX user guide`,description:`ご利用ガイドの記事をキーワードで探します。空白区切りの複数キーワードは、より多く一致した記事を先に返します。記事の全文は ${Z} で読みます。`,inputSchema:y({type:`object`,properties:{query:{type:`string`,minLength:1,description:`検索キーワード(例: "AIグルーピング 階層")`},maxResults:{type:`integer`,minimum:1,maximum:20,description:`返す記事の最大数(既定 10)`}},required:[`query`],additionalProperties:!1}),annotations:Po},e=>{let n=No(e),r=typeof n.query==`string`?n.query:``,i=typeof n.maxResults==`number`?n.maxResults:10;return $(yi(r,i),Mo(t,X,`read`))}),e.registerTool(Z,{title:`Read a Flyle AI CX user guide article`,description:`ご利用ガイドの記事を全文読みます。記事は ${Y} の一覧や ${X} の結果にある "nexus/table-edit" 形式で指定します。画面での操作手順・制約・用語の正はこの記事です。`,inputSchema:y({type:`object`,properties:{article:{type:`string`,minLength:1,description:`記事(例: "nexus/ai-grouping")`}},required:[`article`],additionalProperties:!1}),annotations:Po},e=>{let n=No(e).article;return $(bi(typeof n==`string`?n:``),Mo(t,Z,`read`))})},Lo=(e,t,n)=>{let r=new Map(n.operations.map(e=>[e.operationId,e])),i={type:`object`,properties:{operationId:{enum:[...r.keys()],description:`詳しく知りたいツールの名前`},type:{type:`string`,minLength:1,description:`型(例: "PIVOT_TABLE"、"SELECT_TABLE_RECORDS")。省くと説明の全文・入力 schema・型の一覧を返す`},path:{type:`string`,minLength:1,description:`一部だけを返すときのキー(例: "filter"、"aggregates.query")。type と一緒なら、その型の中のキー`}},required:[`operationId`],additionalProperties:!1},a=qi(N,i);e.registerTool(N,{title:`Get the detailed input schema of a tool`,description:`ツールの説明の全文(制約・エラー・値の形式)と入力 schema の全体・入力例を返します。type を指定すると、レポートの reportOption やワークフローのノードの config のように型ごとに形が違う入力の、その型の schema を返します。path で一部だけを返し、大きい結果はファイルに保存します。`,inputSchema:y(i,wi),annotations:Po},e=>{let n=No(e),i=typeof n.operationId==`string`?n.operationId:``,o=typeof n.type==`string`?n.type:null,s=typeof n.path==`string`?n.path:null;return $(a(n)??oo(r,i,o,s),{...Mo(t,N,`read`),maxTextChars:16e3,indent:!1})})},Ro=(e,t)=>{let n=new oe({name:`flyle-ai-cx`,version:Fe},{capabilities:{tools:{}},instructions:vo(e.config.tenantName,H(e.config.baseUrl))}),r=!1;Io(n,e,t,()=>{r=!0}),Lo(n,e,t);for(let i of t.operations){let t=qi(i.operationId,bo(i.fullInputSchema,i.operationId));n.registerTool(i.operationId,{title:i.summary,description:Eo(i),inputSchema:y(bo(i.inputSchema,i.operationId),wi),annotations:ko(i)},async n=>{let a=Mo(e,i.operationId,i.effect),o=No(n),s=t(o);if(s!=null)return $(s,a);if(!r)return $(ri(),a);let c=await Ea(await _o(e,i,o),i.inlineArtifacts,{operationId:i.operationId,outputDir:a.outputDir,maxBytes:8388608,now:a.now,secrets:a.secrets});return $(c,a)})}return n},zo=e=>new Promise(t=>setTimeout(t,e)),Bo=()=>Date.now(),Vo=()=>{try{return n().username}catch{throw new B(`OS のユーザー情報を取得できませんでした(実行中のユーザーがシステムに登録されていない可能性があります)。登録済みのユーザーで実行してください。`)}},Ho=()=>({cwd:process.cwd(),homeDir:e(),hostname:t(),username:Vo(),now:()=>/* @__PURE__ */ new Date}),Uo=()=>Wt({platform:process.platform,env:process.env,homeDir:e()}),Wo=(e,t)=>{console.error(e),process.exit(t)},Go=async e=>{try{return await qt(e)}catch(e){if(e instanceof P&&e.kind===`login_required`)return null;throw e}},Ko=async()=>{let e=await Dt(Ho());if(e==null)throw new B("この作業ディレクトリはまだログインしていません。このディレクトリで `npx @flyle/ai-cx-mcp@latest login --tenant <テナント名>` を実行してから、MCP サーバーを起動し直してください。");let t=zt(process.env,e.root,e),n=await Kt(Uo(),e),r=await Go(n);return r!=null&&jn(r,t.baseUrl,t.tenantName),{config:t,workspace:e,credentialsFile:n,loggedIn:r!=null}},qo=async()=>{let e=await Ko().catch(e=>Wo(W(e),1)),{config:t,workspace:n,credentialsFile:r}=e,a=()=>[],o=Sr(()=>a()),s=Nn({credentialsFile:r,baseUrl:t.baseUrl,tenantName:t.tenantName,tokenClient:Cn({config:t,auth:null,workspaceId:n.workspaceId,fetch:globalThis.fetch,sleep:zo,logger:o},Tn),now:Bo,lock:Zt(Bo,zo)});a=s.secrets;let c=Yr(),l={config:t,auth:s,client:Cn({config:t,auth:s,workspaceId:n.workspaceId,fetch:globalThis.fetch,sleep:zo,logger:o}),logger:o,now:Bo,workspace:n},u=i(()=>Ro(l,c));o.info(`ai-cx mcp server started`,{environment:H(t.baseUrl),tenantName:t.tenantName,workspace:n.root,loggedIn:e.loggedIn,operations:c.operations.length});let d=!1,f=()=>{d||(d=!0,Promise.race([s.whenIdle(),zo(25e3)]).then(()=>u.close()).catch(T).finally(()=>process.exit(0)))};Sa(t.outputDir,{now:new Date(Bo()),maxAgeMs:6048e5}).then(e=>{e>0&&o.info(`old result files removed`,{removed:e})}).catch(()=>o.warn(`old result files could not be removed`)),process.on(`SIGINT`,f),process.on(`SIGTERM`,f),process.stdin.once(`end`,f)},Jo=()=>({env:process.env,workspaceEnv:Ho(),credentialsDir:Uo(),fetch:globalThis.fetch,now:Bo,sleep:zo,lock:Zt(Bo,zo),logger:Sr(()=>[]),out:e=>console.log(e),err:e=>console.error(e)}),Yo=async e=>{if(!process.stdin.isTTY)return!1;let t=r({input:process.stdin,output:process.stderr});try{return(await t.question(e)).trim().toLowerCase()===`y`}finally{t.close()}},Xo=async e=>{try{await e()}catch(e){Wo(W(e),1)}};await(async()=>{let[e,...t]=process.argv.slice(2);if(e==null){await qo();return}let n={login:()=>_r({...Jo(),argv:t,openBrowser:Rt(process.env)?()=>null:e=>Fn(e),callbackTimeoutMs:6e5,confirm:Yo}),logout:()=>Gn(Jo()),status:()=>br(Jo())},r=b(n,e)?n[e]:null;if(r==null)return Wo(`使い方: flyle-ai-cx-mcp [login [--tenant <テナント名>] [--api-base-url <URL>] | logout | status]
|
|
126
|
+
引数なしで起動すると MCP サーバー(stdio)として動きます。`,2);await Xo(r)})().catch(e=>Wo(W(e),1));export{};
|
package/manifest.json.br
CHANGED
|
Binary file
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@flyle/ai-cx-mcp","version":"0.2.1-develop.
|
|
1
|
+
{"name":"@flyle/ai-cx-mcp","version":"0.2.1-develop.20261109153131.g4e258f6","description":"MCP server for the Flyle AI CX public API","keywords":["flyle","mcp","modelcontextprotocol"],"license":"SEE LICENSE IN LICENSE","author":"Flyle.inc","repository":{"type":"git","url":"git+https://github.com/flyle-io/flyle-nexus.git","directory":"apps/nexus/mcp"},"type":"module","engines":{"node":">=22.0.0"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"bin":{"flyle-ai-cx-mcp":"./main.js"},"dependencies":{"@modelcontextprotocol/server":"2.3.1"}}
|