@flyle/ai-operator-mcp 1.0.0-develop.20261109153131.g4e258f6 → 1.1.0-develop.20261109160053.g0b5ef29
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/main.js +1 -1
- package/package.json +1 -1
package/main.js
CHANGED
|
@@ -26,7 +26,7 @@ function I(e){return M({kind:`schema`,type:`string`,reference:I,expects:`string`
|
|
|
26
26
|
function Pe(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__ */
|
|
27
27
|
function Fe(e,t){return M({kind:`schema`,type:`union`,reference:Fe,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];j(this,`type`,e,t,{issues:/* @__PURE__ */ Pe(r)}),e.typed=!0}else if(i?.length===1)return i[0];else j(this,`type`,e,t,{issues:/* @__PURE__ */ Pe(i)});return e}})}/* @__NO_SIDE_EFFECTS__ */
|
|
28
28
|
function L(...e){return M({...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__ */
|
|
29
|
-
function Ie(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 Le=e=>{let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)},Re=`1.
|
|
29
|
+
function Ie(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 Le=e=>{let t=e.length;for(;t>0&&e[t-1]===`/`;)--t;return e.slice(0,t)},Re=`1.1.0`,ze=/^flyle_ai_operator_ac_[0-9A-Za-z]{43}$/,Be=/^flyle_ai_operator_ut_[0-9A-Za-z]{43}$/,Ve=/^flyle_ai_operator_rt_[0-9A-Za-z]{43}$/,He=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/,Ue=/^[a-z0-9](-?[a-z0-9])*$/,We=6e5,Ge=536870912;var R=class extends Error{name=`ConfigError`},Ke=class extends Error{name=`GuideArticlesLoadError`};const qe="ログインが必要です。作業ディレクトリで `npx @flyle/ai-operator-mcp@latest login` を実行してください";var Je=class extends Error{name=`InvalidGrantError`},z=class extends Error{name=`CliError`};const Ye={allowInsecureHttp:`FLYLE_AI_OPERATOR_MCP_ALLOW_INSECURE_HTTP`},Xe=[`FLYLE_AI_CONTACT_CENTER_API_BASE_URL`,`FLYLE_AI_CONTACT_CENTER_TENANT_NAME`,`FLYLE_AI_CONTACT_CENTER_MCP_OUTPUT_DIR`,`FLYLE_AI_CONTACT_CENTER_MCP_FILE_ROOTS`,`FLYLE_AI_CONTACT_CENTER_MCP_STORAGE_HOSTS`,`FLYLE_AI_CONTACT_CENTER_MCP_ALLOW_INSECURE_HTTP`],Ze=[`.amazonaws.com`],Qe=/* @__PURE__ */ new Set([`localhost`,`127.0.0.1`,`[::1]`]),$e=e=>Qe.has(e),et=(e,t,n)=>{let r;try{r=new URL(e)}catch{throw new R(`${n} is not a valid URL`)}if(r.search!==``||r.hash!==``||r.username!==``||r.password!==``)throw new R(`${n} must not contain query, hash, or credentials`);let i=r.protocol===`http:`&&t&&$e(r.hostname);if(r.protocol!==`https:`&&!i)throw new R(`${n} must use https (http is allowed only for localhost with ${Ye.allowInsecureHttp}=1)`);let a=Le(r.pathname);return new URL(`${r.origin}${a}`)},tt=e=>e===`1`||e===`true`,nt=e=>e.length>=2&&e.length<=32&&Ue.test(e),rt=(e,t)=>{if(!nt(e))throw new R(`${t} is not a valid tenant name`);return e},it=e=>{if(e.FLYLE_AI_CONTACT_CENTER_API_KEY!=null)throw new R("API キー方式は廃止されました。`npx @flyle/ai-operator-mcp@latest login` でログインしてください");let t=Xe.filter(t=>e[t]!=null);if(t.length!==0)throw new R(`${t.join(`, `)} は廃止しました。MCP の設定から削除してください。接続先(環境とテナント)は作業ディレクトリで \`npx @flyle/ai-operator-mcp@latest login --tenant <テナント名>\` を実行すると決まり、保存先と読込元は作業ディレクトリです。`)},at=e=>tt(e[Ye.allowInsecureHttp]),B=e=>e.host,ot=(e,t,n)=>{let r=at(e);return{baseUrl:et(n.apiBaseUrl,r,`作業ディレクトリの接続先`),tenantName:rt(n.tenantName,`作業ディレクトリのテナント`),outputDir:_.resolve(t,`.flyle-ai-operator-mcp/downloads`),fileRoots:[t],storageHostSuffixes:r?[...Ze,`s3.flyle.local`]:Ze,allowInsecureHttp:r}},st=`flyle-ai-operator-mcp`,ct=`credentials`,lt=()=>a(8).toString(`hex`),ut=/* @__PURE__ */ Ne({version:/* @__PURE__ */ Oe(1),apiBaseUrl:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ we()),tenantName:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ be(nt)),loginConnectionId:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ P(He)),accessToken:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ P(Be)),accessTokenExpiresAt:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ N()),refreshToken:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ P(Ve)),refreshTokenExpiresAt:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ N())}),dt=({platform:e,env:t,homeDir:n})=>{let r=t.XDG_CONFIG_HOME;if(r!=null&&_.isAbsolute(r))return _.join(r,st,ct);let i=t.APPDATA;return e===`win32`&&i!=null&&_.isAbsolute(i)?_.join(i,st,ct):_.join(n,`.config`,st,ct)},ft=(e,t)=>_.join(e,`${t}.json`),pt=e=>e instanceof Error&&k(e,`code`)?e.code:null,mt=async e=>{let t;try{t=await d(e,`utf8`)}catch(e){if(pt(e)===`ENOENT`)return null;throw e}let n;try{n=JSON.parse(t)}catch{n=null}let r=/* @__PURE__ */ Ie(ut,n);if(!r.success)throw new x(`login_required`,`保存されたログイン情報(${e})を読めません。作業ディレクトリで \`npx @flyle/ai-operator-mcp@latest login\` を実行し直してください`);return r.output},ht=async e=>{await l(e,{recursive:!0,mode:448}),await s(e,448)},gt=async(e,t)=>{await ht(_.dirname(e));let n={version:1,...t},r=`${e}.${lt()}.tmp`;try{let t=await u(r,`wx`,384);try{await t.writeFile(`${JSON.stringify(n,null,2)}\n`)}finally{await t.close()}await p(r,e)}catch(e){throw await m(r,{force:!0}).catch(O),e}},_t=async e=>{await m(e,{force:!0})},vt=(e,t)=>({staleMs:6e4,acquireTimeoutMs:9e4,retryIntervalMs:100,now:e,sleep:t}),yt=async e=>{let t;try{t=await u(e,`r`)}catch(e){if(pt(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()}},bt=async(e,t)=>{let n=`${e}.${lt()}.aside`;try{await p(e,n)}catch(e){if(pt(e)===`ENOENT`)return!1;throw e}return await d(n,`utf8`)===t?(await m(n,{force:!0}),!0):(await c(n,e).catch(e=>{if(pt(e)!==`EEXIST`)throw e}),await m(n,{force:!0}),!1)},xt=async(e,t)=>{let n=await yt(e);return n==null?!0:t.now()-n.mtimeMs<t.staleMs?!1:bt(e,n.owner)},St=async(e,t)=>{let n=`${e}.${lt()}.tmp`,r=await u(n,`wx`,384);try{await r.writeFile(t)}finally{await r.close()}try{return await c(n,e),!0}catch(e){if(pt(e)===`EEXIST`)return!1;throw e}finally{await m(n,{force:!0})}},Ct=async(e,t,n)=>{await ht(_.dirname(e));let r=`${e}.lock`,i=lt(),a=t.now()+t.acquireTimeoutMs;for(;!await St(r,i);)if(!await xt(r,t)){if(t.now()>=a)throw Error(`ログイン情報のロック(${r})を取得できませんでした。別の MCP プロセスが更新中です。しばらくしてから再実行してください`);await t.sleep(t.retryIntervalMs)}try{return await n()}finally{await bt(r,i).catch(O)}},V=e=>{if(e?.aborted)throw new C(`aborted`,`the API request was cancelled`)},wt=(e,t,n)=>(V(t),t==null?n(e):new Promise((r,i)=>{let a=()=>{i(new C(`aborted`,`the API request was cancelled`))};t.addEventListener(`abort`,a,{once:!0}),n(e).then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})})),Tt=/\r\n|\n|\r/,Et=()=>{let e=``,t=!1,n=``,r=[],i=null,a=()=>{if(r.length===0)return n=``,null;let e={event:n===``?`message`:n,data:r.join(`
|
|
30
30
|
`),id:i};return n=``,r=[],e},o=e=>{if(e===``)return a();if(e.startsWith(`:`))return null;let t=e.indexOf(`:`),o=t===-1?e:e.slice(0,t),s=t===-1?``:e.slice(t+1);return s.startsWith(` `)&&(s=s.slice(1)),o===`event`?n=s:o===`data`?r.push(s):o===`id`&&!s.includes(`\0`)&&(i=s),null};return{push:n=>{e+=n,t&&(t=!1,e.startsWith(`
|
|
31
31
|
`)&&(e=e.slice(1)));let r=[],i=e.search(Tt);for(;i!==-1;){let n=e.slice(0,i);e[i]===`\r`&&i===e.length-1&&(t=!0);let a=e.startsWith(`\r
|
|
32
32
|
`,i)?2:1;e=e.slice(i+a);let s=o(n);s!=null&&r.push(s),i=e.search(Tt)}return r},hasPendingIncomplete:()=>e!==``||r.length>0,flush:()=>(e=``,t=!1,n=``,r=[],[])}},Dt=async(e,t)=>{if(t<=0)return`deadline`;let n=null,r=new Promise(e=>{n=setTimeout(e,t,`deadline`)});try{return await Promise.race([e.read(),r])}finally{n!=null&&clearTimeout(n)}},Ot=async(e,t)=>{let n=e.getReader(),r=new TextDecoder(`utf-8`),i=Et(),a=[],o=0,s=async e=>(await n.cancel().catch(O),{events:a,truncated:!0,reason:e,discardedIncomplete:!1});for(;;){let e=await Dt(n,t.deadlineAt-t.now());if(e===`deadline`)return await s(`deadline`);if(e.done){a.push(...i.push(r.decode()));let e=i.hasPendingIncomplete();return i.flush(),{events:a,truncated:!1,reason:`end`,discardedIncomplete:e}}if(o+=e.value.byteLength,o>t.maxBytes)return await s(`max_bytes`);if(a.push(...i.push(r.decode(e.value,{stream:!0}))),a.length>t.maxEvents)return a.length=t.maxEvents,await s(`max_events`)}},kt=e=>{try{return JSON.parse(e)}catch{return e}},At=`application/json`,jt=`text/event-stream`,Mt=`x-request-id`,Nt={headersTimeoutMs:6e4,maxJsonBytes:16777216,sseTotalMs:9e5,sseMaxEvents:1e4,sseMaxBytes:33554432,maxRetryAfterSeconds:30},Pt=(e,t)=>{if(e.origin!==t.origin)throw new C(`request_refused`,`refusing to send credentials outside the configured API origin`)},Ft=(e,t)=>{let n=`${Le(e.pathname)}${t.path}`,r=new URL(n,e);if(r.pathname!==n)throw new C(`request_refused`,`refusing to send a request whose path was normalized`);for(let[e,n]of t.query)r.searchParams.append(e,n);return Pt(r,e),r},It=e=>{switch(e){case`json`:case`empty`:return At;case`sse`:return jt;case`binary`:return`*/*`;default:throw Error(`unknown response kind ${String(e)}`)}},Lt=async(e,t)=>{let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw await e.body?.cancel().catch(O),new C(`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(O),new C(`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},Rt=e=>new TextDecoder(`utf-8`).decode(e),zt=(e,t)=>(e.headers.get(`content-type`)??``).toLowerCase().startsWith(t),Bt=e=>{if(e==null)return null;let t=Number(e);return Number.isInteger(t)&&t>=0?t:null},Vt=(e,t)=>{let n=e[t];return typeof n==`string`?n:null},Ht=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Ut=async(e,t)=>{let n=e.headers.get(Mt),r=Bt(e.headers.get(`retry-after`)),i;try{i=Rt(await Lt(e,t))}catch{i=``}if(zt(e,At))try{let t=JSON.parse(i),a=Ht(t)&&Ht(t.error)?t.error:null;if(a!=null)return new S({status:e.status,code:Vt(a,`code`),message:Vt(a,`message`)??e.statusText,detail:Vt(a,`detail`),requestId:Vt(a,`requestId`)??n,retryAfterSeconds:r})}catch{}return new S({status:e.status,code:null,message:i.slice(0,500)||e.statusText||`HTTP error`,detail:null,requestId:n,retryAfterSeconds:r})},Wt=e=>{if(e==null)return null;let t=/filename\*=UTF-8''([^;]+)/i.exec(e);if(t?.[1]!=null)try{return decodeURIComponent(t[1].trim())}catch{return null}return/filename="?([^";]+)"?/i.exec(e)?.[1]?.trim()??null},Gt=e=>e instanceof C?e:e instanceof Error&&e.name===`AbortError`?new C(`timeout`,`the API did not respond in time`):new C(`network`,e instanceof Error?e.message:`network failure`),Kt=(e,t=Nt)=>{let{config:n,auth:r,clientWorkspaceId:i,userAgent:a,fetch:o,now:s,sleep:c,logger:l}=e,u=async(e,r,{signal:c,canSend:l,metrics:u})=>{V(c);let d=Ft(n.baseUrl,e),f=new Headers({accept:It(e.responseKind)});a!=null&&f.set(`user-agent`,a),i!=null&&f.set(`x-flyle-client-workspace`,i),r!=null&&f.set(`authorization`,`Bearer ${r}`);let p;e.hasBody&&(p=JSON.stringify(e.body??{}),f.set(`content-type`,At));let m=new AbortController,h=setTimeout(()=>m.abort(),t.headersTimeoutMs),g;try{if(l?.()===!1)throw new C(`aborted`,`the API request was cancelled before sending`);u!=null&&(u.attempts+=1,u.requestBytes+=p==null?0:new TextEncoder().encode(p).byteLength),g=await o(d,{method:e.method,headers:f,...p==null?{}:{body:p},redirect:`manual`,signal:c==null?m.signal:AbortSignal.any([m.signal,c])})}catch(e){throw clearTimeout(h),V(c),Gt(e)}let _=g.body;if(u!=null&&_!=null){let e=g,t=_.getReader(),n=new ReadableStream({async pull(e){try{let{done:n,value:r}=await t.read();if(n){t.releaseLock(),e.close();return}u.responseBytes+=r.byteLength,e.enqueue(r)}catch(n){t.releaseLock(),e.error(n)}},async cancel(e){try{await t.cancel(e)}finally{t.releaseLock()}}},{highWaterMark:0});g=new Response(n,{status:e.status,statusText:e.statusText,headers:e.headers})}if(g.type===`opaqueredirect`||g.status>=300&&g.status<400)throw clearTimeout(h),await g.body?.cancel().catch(O),new C(`redirect_not_followed`,`redirect responses are not followed`,g.status);if(!g.ok)try{throw await Ut(g,t.maxJsonBytes)}finally{clearTimeout(h)}let v=g.headers.get(Mt);switch(e.responseKind){case`json`:try{if(!zt(g,At))throw await g.body?.cancel().catch(O),new C(`unexpected_content_type`,`expected an application/json response`,g.status);let e=Rt(await Lt(g,t.maxJsonBytes)),n;try{n=JSON.parse(e)}catch{throw new C(`invalid_json`,`the response body is not valid JSON`,g.status)}return{kind:`json`,status:g.status,requestId:v,body:n}}catch(e){throw V(c),Gt(e)}finally{clearTimeout(h)}case`empty`:return clearTimeout(h),await g.body?.cancel().catch(O),{kind:`empty`,status:g.status,requestId:v};case`sse`:{if(clearTimeout(h),!zt(g,jt))throw await g.body?.cancel().catch(O),new C(`unexpected_content_type`,`expected a text/event-stream response`,g.status);if(g.body==null)throw new C(`empty_body`,`the stream has no body`,g.status);let e=await Ot(g.body,{deadlineAt:s()+t.sseTotalMs,maxEvents:t.sseMaxEvents,maxBytes:t.sseMaxBytes,now:s});return V(c),{kind:`sse`,status:g.status,requestId:v,...e}}case`binary`:if(clearTimeout(h),g.body==null)throw new C(`empty_body`,`the download has no body`,g.status);return{kind:`binary`,status:g.status,requestId:v,contentType:g.headers.get(`content-type`),fileName:Wt(g.headers.get(`content-disposition`)),body:g.body};default:throw e.responseKind,Error(`unknown response kind ${String(e.responseKind)}`)}},d=async(e,n,r)=>{let{signal:i}=r,a=e.method===`GET`&&(e.responseKind===`json`||e.responseKind===`empty`);try{return await u(e,n,r)}catch(o){if(V(i),!a)throw o;if(o instanceof S&&o.info.status===429&&o.info.retryAfterSeconds!=null&&o.info.retryAfterSeconds<=t.maxRetryAfterSeconds)return l.warn(`rate limited; retrying once`,{path:e.path,retryAfterSeconds:o.info.retryAfterSeconds}),await wt(o.info.retryAfterSeconds*1e3,i,c),await u(e,n,r);if(o instanceof C&&o.kind===`network`)return l.warn(`network failure; retrying once`,{path:e.path}),await u(e,n,r);throw o}};return{request:async(e,t,n,i)=>{V(t);let a={signal:t,canSend:n,metrics:i};if(r==null)return d(e,null,a);let o=await r.getAccessToken();try{return await d(e,o,a)}catch(n){if(!(n instanceof S)||n.info.status!==401)throw n;V(t);let i=await r.refreshAfterRejection(o);if(V(t),i===o)throw n;return l.warn(`access token rejected; retrying once with a refreshed token`,{path:e.path}),await d(e,i,a)}}}},qt=`{tenantName}`,Jt={...Nt,headersTimeoutMs:2e4},Yt=/* @__PURE__ */ F({authorizationUrlTemplate:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ xe(qt))}),Xt=/* @__PURE__ */ F({accessToken:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ P(Be)),accessTokenExpiresAt:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ N()),refreshToken:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ P(Ve)),refreshTokenExpiresAt:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ N()),tenantName:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ be(nt)),loginConnectionId:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ P(He))}),Zt=(e,t,n)=>{let r=/* @__PURE__ */ Ie(e,t);if(!r.success)throw new C(`invalid_json`,`the login connection response does not match the contract`,n);return r.output},Qt=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 C(`unexpected_content_type`,`not JSON`);return Zt(Yt,t.body,t.status).authorizationUrlTemplate},$t=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 S&&e.info.code===`invalid_grant`?new Je(`the authorization code or refresh token is no longer valid`):e}if(n.kind!==`json`)throw new C(`unexpected_content_type`,`not JSON`);return Zt(Xt,n.body,n.status)},en=(e,t,n)=>{if(e.apiBaseUrl!==t.href||e.tenantName!==n)throw new x(`credentials_mismatch`,`保存されたログイン(環境 ${B(new URL(e.apiBaseUrl))} / テナント ${e.tenantName})が、この作業ディレクトリの接続先(環境 ${B(t)} / テナント ${n})と一致しません。この作業ディレクトリで \`npx @flyle/ai-operator-mcp@latest login\` を実行し直してください`)},tn=(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=(...e)=>{c.push(...e),c.splice(0,Math.max(0,c.length-8))},u=async()=>{let e=await mt(t);if(e==null||Date.parse(e.refreshTokenExpiresAt)<=a())throw new x(`login_required`,qe);return en(e,n,r),e},d=e=>e-a()>6e4,f=async e=>{try{await gt(t,e)}catch{try{await gt(t,e)}catch{await _t(t)}}},p=a=>Ct(t,e.lock,async()=>{let e=await u();l(e.accessToken,e.refreshToken);let s=Date.parse(e.accessTokenExpiresAt);if(e.accessToken!==a&&d(s))return o={token:e.accessToken,expiresAt:s},e.accessToken;let c;try{c=await $t(i,{grant_type:`refresh_token`,refresh_token:e.refreshToken})}catch(e){throw e instanceof Je?(await _t(t),new x(`login_required`,qe)):e}if(l(c.accessToken,c.refreshToken),c.tenantName!==r)throw await _t(t),new x(`login_required`,`ログインの更新で、設定と違うテナント(${c.tenantName})の応答を受け取ったため、保存したログイン情報を破棄しました。${qe}`);if(c.loginConnectionId!==e.loginConnectionId)throw await _t(t),new x(`login_required`,`ログインの更新で、保存したログインと違う接続の応答を受け取ったため、保存したログイン情報を破棄しました。${qe}`);return o={token:c.accessToken,expiresAt:Date.parse(c.accessTokenExpiresAt)},await f(tn(c,n)),c.accessToken}),m=e=>(s??=p(e).finally(()=>{s=null}),s);return{getAccessToken:()=>o!=null&&d(o.expiresAt)?Promise.resolve(o.token):m(o?.token??null),refreshAfterRejection:e=>o!=null&&o.token!==e?Promise.resolve(o.token):(o=null,m(e)),assertLoggedIn:async()=>{o??await u()},secrets:()=>c,whenIdle:async()=>{await Promise.allSettled(s==null?[]:[s])}}},rn=(e,t)=>e===`darwin`?[`open`,[t]]:e===`win32`?[`rundll32`,[`url.dll,FileProtocolHandler`,t]]:[`xdg-open`,[t]],an=(e,t=process.platform)=>{let[n,r]=rn(t,e),i=v(n,r,{stdio:`ignore`,detached:!0,shell:!1});i.on(`error`,O),i.unref()},on=`flyle-ai-operator-mcp/${Re}`,sn=(e,t=Nt)=>{let{workspaceId:n,...r}=e;return Kt({...r,clientWorkspaceId:n,userAgent:on},t)},cn=`.flyle-ai-operator-mcp`,ln=/* @__PURE__ */ F({tenantName:/* @__PURE__ */ I(),apiBaseUrl:/* @__PURE__ */ je(/* @__PURE__ */ ke(/* @__PURE__ */ I()),null)}),un=e=>_.join(e,cn,`workspace.json`),dn=e=>e instanceof Error&&k(e,`code`)&&e.code===`ENOENT`,fn=e=>e instanceof Error&&k(e,`code`)&&e.code===`EEXIST`,pn=async e=>{let t;try{t=await d(un(e),`utf8`)}catch(e){if(dn(e))return null;throw e}let n;try{n=JSON.parse(t)}catch{n=null}let r=/* @__PURE__ */ Ie(ln,n);if(!r.success)throw new D(`corrupted`,`${un(e)} is not a valid workspace binding. Inspect it manually; the MCP server never overwrites it.`);return r.output},mn=async e=>(await pn(e))?.tenantName??null,hn=e=>` If you have never logged in successfully in this directory (e.g. you mistyped the tenant), delete ${_.join(e,cn)} and run login again (saved results in the default downloads folder are deleted too).`,gn=(e,t,n)=>new D(`tenant_mismatch`,`${e} is dedicated to tenant "${t}", not "${n}". Use a separate directory (and a separate Claude Code session) for each tenant.`+hn(e)),_n=(e,t,n)=>new D(`environment_mismatch`,`${e} is dedicated to the API ${new URL(t).host}, not ${new URL(n).host}. Use a separate directory for each environment.`+hn(e)),vn=e=>{let t=[],n=_.dirname(e);for(;n!==_.dirname(n);)t.push(n),n=_.dirname(n);return t.push(n),t},yn=async(e,t)=>{let n=await Promise.all(vn(e).map(async e=>({dir:e,tenant:await mn(e)})));for(let{dir:e,tenant:r}of n)if(r!=null&&r!==t)throw gn(e,r,t)},bn=(e,t)=>i(`sha256`).update(`${e.hostname}\0${e.username}\0${t}`).digest(`base64url`).slice(0,32),xn=(e,t)=>{let n={version:2,tenantName:e.tenantName,apiBaseUrl:e.apiBaseUrl,boundAt:t.toISOString()};return`${JSON.stringify(n,null,2)}\n`},Sn=async(e,t,n)=>{let r=un(e),i=`${r}.${a(8).toString(`hex`)}.tmp`;try{await g(i,xn(t,n),{flag:`wx`}),await p(i,r)}finally{await m(i,{force:!0})}},Cn=async(e,t,n,r)=>{await l(_.join(e,cn),{recursive:!0,mode:448});try{await g(un(e),xn(t,n),{flag:`wx`});return}catch(e){if(!fn(e))throw e}let i=await pn(e);if(i?.tenantName!==t.tenantName)throw gn(e,i?.tenantName??`(unknown)`,t.tenantName);if(i.apiBaseUrl!==t.apiBaseUrl){if(i.apiBaseUrl==null&&r)await Sn(e,t,n);else throw _n(e,i.apiBaseUrl??`(unknown)`,t.apiBaseUrl)}},wn=async e=>{let t=await f(e.cwd);if(t===await f(e.homeDir).catch(()=>e.homeDir)||t===_.parse(t).root)throw new D(`shared_directory`,`${t} is shared by everything you do and cannot be dedicated to one tenant. Create a directory for this tenant (e.g. ~/flyle-cs/<tenant>) and start the session there.`);return t},Tn=async(e,t)=>{let n=await wn(e);return await yn(n,t.tenantName),await Cn(n,t,e.now(),!0),{...t,root:n,workspaceId:bn(e,n)}},En=async e=>{let t=await wn(e),n=await pn(t);return n?.apiBaseUrl==null?null:(await yn(t,n.tenantName),{tenantName:n.tenantName,apiBaseUrl:n.apiBaseUrl,root:t,workspaceId:bn(e,t)})},Dn=async(e,t)=>{await Cn(e.root,e,t,!1)},On=(e,t,n)=>new D(`outside_workspace`,`${n} (${t}) must be inside the tenant workspace ${e}; a shared location could mix files between tenants.`),kn=async(e,t)=>{if(!t.startsWith(`${e.root}${_.sep}`))throw On(e.root,t,`the file`);let n=[];for(let r=_.dirname(t);r!==e.root;r=_.dirname(r))n.push(r);let r=await Promise.all(n.map(async e=>({dir:e,tenant:await mn(e)})));for(let{dir:t,tenant:n}of r)if(n!=null&&n!==e.tenantName)throw gn(t,n,e.tenantName)},An=(e,t,n)=>sn({config:{baseUrl:t},auth:null,workspaceId:n,fetch:e.fetch,now:e.now,sleep:e.sleep,logger:e.logger},Jt),jn=async e=>{let t=await En(e.workspaceEnv);if(t==null)return null;let n=ft(e.credentialsDir,t.workspaceId),r=await mt(n);return r==null?null:{workspace:t,file:n,stored:r,baseUrl:et(r.apiBaseUrl,at(e.env),`${n} の apiBaseUrl`)}},Mn=(e,t)=>{let n=nn({credentialsFile:t.file,baseUrl:t.baseUrl,tenantName:t.stored.tenantName,tokenClient:An(e,t.baseUrl,t.workspace.workspaceId),now:e.now,lock:e.lock});return{auth:n,client:sn({config:{baseUrl:t.baseUrl},auth:n,workspaceId:t.workspace.workspaceId,fetch:e.fetch,now:e.now,sleep:e.sleep,logger:e.logger})}},Nn=(e,t)=>`/v0/tenants/${encodeURIComponent(e)}${t}`,Pn=e=>e instanceof z||e instanceof x||e instanceof R||e instanceof D?e.message:e instanceof S?`公開 API がエラーを返しました(${String(e.info.status)} ${e.info.code??`http_error`}): ${e.info.message}`:e instanceof C?`公開 API と通信できませんでした(${e.kind}): ${e.message}`:e instanceof Error?e.message:String(e),H=(e,t)=>{let n=e;for(let e of t)e.length!==0&&(n=n.split(e).join(`[redacted]`));return n},Fn=async(e,t)=>{let{client:n}=Mn(e,t);try{await n.request({method:`DELETE`,path:Nn(t.stored.tenantName,`/current-login-connection`),query:[],hasBody:!1,body:null,responseKind:`empty`})}catch(e){if(!(e instanceof x&&e.kind===`login_required`||e instanceof S&&e.info.status===401))throw e}},In=async e=>{let t=await jn(e);t==null?e.out(`この作業ディレクトリにはログイン情報がありません。`):(await Fn(e,t),await Ct(t.file,e.lock,()=>_t(t.file)),e.out(`ログアウトしました(環境 ${B(t.baseUrl)} / テナント ${t.stored.tenantName})。`))},Ln=`127.0.0.1`,Rn=`/callback`,zn=e=>{try{let{values:t}=te({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 z(`${e instanceof Error?e.message:String(e)}\n使い方: login [--tenant <テナント名>] [--api-base-url <URL>]`)}},Bn=(e,t,n)=>e==null?t?.apiBaseUrl==null?et(`https://api.flygate.flyle.io`,n,`既定の接続先`):et(t.apiBaseUrl,n,`作業ディレクトリの接続先`):et(e,n,`--api-base-url`),Vn=(e,t)=>{if(e!=null)return rt(e,`--tenant`);if(t!=null)return t.tenantName;throw new z("テナントを決められません。`login --tenant <テナント名>` で指定してください(作業ディレクトリをそのテナント専用にします)。")},Hn=()=>a(32).toString(`base64url`),Un=e=>i(`sha256`).update(e).digest(`base64url`),Wn=(e,t)=>{let n=Buffer.from(e),r=Buffer.from(t);return n.length===r.length&&o(n,r)},Gn=(e,t,n)=>{let r;try{r=new URL(e.replaceAll(qt,t))}catch{throw new z(`公開 API が返した同意画面の URL が不正です。`)}let i=r.protocol===`http:`&&n&&($e(r.hostname)||r.hostname.endsWith(`.localhost`));if(r.protocol!==`https:`&&!i)throw new z(`公開 API が返した同意画面の URL が https ではありません。`);return r},Kn=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Co}]/gu,qn=(e,t)=>{let n=``;for(let r of e){if(n.length+r.length>t)break;n+=r}return n},Jn=(e,t)=>{let n=e=>e.replaceAll(Kn,``);return qn(`${n(e)} / ${n(_.basename(t))}`,255)},Yn=/* @__PURE__ */ Fe([/* @__PURE__ */ F({error:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ P(/^[a-z_]{1,64}$/)),state:/* @__PURE__ */ I()}),/* @__PURE__ */ F({code:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ P(ze)),state:/* @__PURE__ */ I()})]),Xn={success:`ログインが完了しました。このタブは閉じてかまいません。`,denied:`ログインを中止しました。このタブは閉じてかまいません。`,failure:`ログインを完了できませんでした。このタブを閉じて、ターミナルの表示を確認してください。`,handled:`このログインは処理済みです。このタブは閉じてかまいません。`,unknown:`実行中のログインの応答として確認できませんでした。ログインを続ける場合は、ターミナルに表示された URL から同意画面を開き直してください。`,rejected:`この宛先への要求は受け付けていません。`},Zn=(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オペレーター</title><p>${Xn[n]}</p></html>`)},Qn=e=>new Promise((t,n)=>{e.once(`error`,n),e.listen(0,Ln,()=>{let r=e.address();r==null||typeof r==`string`?n(new z(`ログイン用の待受ポートを開けませんでした。`)):t(r.port)})}),$n=async(e,t,n)=>{let r=!1,i=0,a=null,o=Promise.withResolvers(),s=e=>{r=!0,o.reject(new z(e))},c=(e,t,r)=>{i+=1,Zn(e,400,t),n(r)},l=ee((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!==Rn){n.writeHead(404).end();return}if(r){Zn(n,410,`handled`);return}let l=i.searchParams.get(`state`);if(l==null||!Wn(l,e)){c(n,`unknown`,`このログインのものではない応答(state が一致しない、または無い)を受け取ったため無視しました。ブラウザで同意を続けてください。`);return}let u=/* @__PURE__ */ Ie(Yn,fe(i.searchParams));if(!u.success){Zn(n,400,`failure`),s(`同意画面からの応答の形式が正しくありません(認可コードがない、または形式が違います)。もう一度 login を実行してください。`);return}let d=u.output;if(k(d,`error`)){let e=d.error===`access_denied`;Zn(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,Zn(n,e===`success`?200:400,e))}})}),u=await Qn(l);a=`${Ln}:${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())})}},er=`その接続は最長 30 日間有効なまま残る可能性があります。管理画面の「設定 → 外部ツール接続」から切断してください。`,tr=async(e,t)=>{if(t!=null)try{await Fn(e,t)}catch(n){e.err(`以前のログイン(接続 ID ${t.stored.loginConnectionId})をサーバーで切断できませんでした(${Pn(n)})。${er}`)}},nr=async e=>{try{return await jn(e)}catch(t){if(!(t instanceof x&&t.kind===`login_required`)&&!(t instanceof R))throw t;return e.err(`以前のログイン情報を読めなかったため、新しいログインで上書きします(${Pn(t)})。以前の接続はサーバーで切断できていません。${er}`),null}},rr=async(e,t,n,r)=>{let i=ft(e.credentialsDir,t.workspaceId);await Ct(i,e.lock,()=>gt(i,tn(r,n)))},ir=e=>({getAccessToken:()=>Promise.resolve(e),refreshAfterRejection:()=>Promise.resolve(e),secrets:()=>[e]}),ar=async(e,t,n,r)=>{let i=sn({config:{baseUrl:t},auth:ir(r.accessToken),workspaceId:n.workspaceId,fetch:e.fetch,now:e.now,sleep:e.sleep,logger:e.logger});try{return await i.request({method:`DELETE`,path:Nn(r.tenantName,`/current-login-connection`),query:[],hasBody:!1,body:null,responseKind:`empty`}),!0}catch{return!1}},or=async e=>{let t=zn(e.argv),n=at(e.env),r=await pn(e.workspaceEnv.cwd),i=Bn(t.apiBaseUrl,r,n),a=Vn(t.tenant,r),o=await Tn(e.workspaceEnv,{tenantName:a,apiBaseUrl:i.href}),s=await nr(e),c=An(e,i,o.workspaceId),l=Gn(await Qt(c),a,n),u=Hn(),d=Hn(),f=[u,d],p=await $n(d,e.callbackTimeoutMs,e.err),m=null;try{let t=`http://${Ln}:${String(p.port)}${Rn}`;l.searchParams.set(`tenant_name`,a),l.searchParams.set(`code_challenge`,Un(u)),l.searchParams.set(`code_challenge_method`,`S256`),l.searchParams.set(`redirect_uri`,t),l.searchParams.set(`state`,d),l.searchParams.set(`connection_name`,Jn(e.workspaceEnv.hostname,o.root)),l.searchParams.set(`api_origin`,i.origin),e.err(`環境 ${B(i)} のテナント「${a}」にログインします。ブラウザで同意画面を開きます。\n開かない場合は、次の URL をブラウザで開いてください:\n${l.href}`),e.openBrowser(l.href),m=await p.received,f.push(m.code);let n;try{n=await $t(c,{grant_type:`authorization_code`,code:m.code,code_verifier:u,redirect_uri:t})}catch(e){throw e instanceof Je?new z(`認可コードを交換できませんでした。もう一度 login を実行してください。`):e}if(f.push(n.accessToken,n.refreshToken),n.tenantName!==a){let t=await ar(e,i,o,n);throw new z(`ブラウザで同意したテナント(${n.tenantName})が、ログインしようとしたテナント(${a})と違います。ログイン情報は保存していません。`+(t?`そのテナントに作られた接続は切断しました。`:`テナント ${n.tenantName} の管理画面の「設定 → 外部ツール接続」から、作られた接続を切断してください。`))}await Dn(o,new Date(e.now())),await tr(e,s),await rr(e,o,i,n),m.finish(`success`),e.out(`ログインしました(環境 ${B(i)} / テナント ${a} / 作業ディレクトリ ${o.root})。`)}catch(e){throw m?.finish(`failure`),new z(H(Pn(e),f))}finally{await p.close()}},sr=/* @__PURE__ */ F({currentUser:/* @__PURE__ */ F({name:/* @__PURE__ */ ke(/* @__PURE__ */ I()),email:/* @__PURE__ */ ke(/* @__PURE__ */ I()),roles:/* @__PURE__ */ De(/* @__PURE__ */ F({roleName:/* @__PURE__ */ I()})),currentLoginConnection:/* @__PURE__ */ F({name:/* @__PURE__ */ I(),expiresAt:/* @__PURE__ */ L(/* @__PURE__ */ I(),/* @__PURE__ */ N())})})}),cr="ログインしていません。作業ディレクトリで `npx @flyle/ai-operator-mcp@latest login` を実行してください",lr=async e=>{let t=await jn(e);if(t==null)throw new z(cr);e.out(`環境: ${B(t.baseUrl)}`),e.out(`テナント: ${t.stored.tenantName}`);let{client:n}=Mn(e,t),r;try{r=await n.request({method:`GET`,path:Nn(t.stored.tenantName,`/current-user`),query:[],hasBody:!1,body:null,responseKind:`json`})}catch(e){throw e instanceof x&&e.kind===`login_required`?new z(`ログインの有効期限が切れています。${cr}`):e}let i=/* @__PURE__ */ Ie(sr,r.kind===`json`?r.body:null);if(!i.success)throw new C(`invalid_json`,`the current user response does not match the contract`);let a=i.output.currentUser,o=a.email==null?``:` <${a.email}>`;e.out(`ユーザー: ${a.name??`(名前未設定)`}${o}`),e.out(`ロール: ${a.roles.map(e=>e.roleName).join(`, `)||`(なし)`}`),e.out(`接続名: ${a.currentLoginConnection.name}`),e.out(`ログインの有効期限: ${a.currentLoginConnection.expiresAt}(使うたびに延長。ログインから最長 90 日)`)},ur=async e=>{let t=await u(e,ne.O_RDONLY|ne.O_NONBLOCK|ne.O_NOFOLLOW);try{let e=await t.stat();if(!e.isFile())throw new T(`not_a_file`,`only regular files can be read`);return{handle:t,size:e.size}}catch(e){throw await t.close(),e}},dr=async(e,t)=>{let{handle:n,size:r}=await ur(e);try{if(r>t)throw new T(`too_large`,`the file exceeds ${String(t)} bytes`);let e=[],i=0;for(;;){let r=Buffer.allocUnsafe(Math.min(1048576,t-i+1)),{bytesRead:a}=await n.read(r,0,r.length,null);if(a===0)break;if(i+=a,i>t)throw new T(`too_large`,`the file exceeds ${String(t)} bytes`);e.push(r.subarray(0,a))}return Buffer.concat(e,i)}finally{await n.close()}},fr=(e,t)=>e===t||e.startsWith(`${t}${_.sep}`),pr=async(e,t,n,r)=>{let i=_.resolve(n,e),a;try{a=await f(i)}catch{throw new T(`not_found`,`file not found: ${e}`)}if(!(await Promise.all(t.map(e=>f(e).catch(()=>e)))).some(e=>fr(a,e)))throw new T(`outside_roots`,`the path is outside the configured file roots`);return await kn(r,a),a},mr=/* @__PURE__ */ new Map([[`.md`,`text/markdown`],[`.markdown`,`text/markdown`],[`.txt`,`text/plain`],[`.csv`,`text/csv`],[`.json`,`application/json`],[`.html`,`text/html`],[`.htm`,`text/html`],[`.pdf`,`application/pdf`],[`.docx`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`],[`.xlsx`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`],[`.pptx`,`application/vnd.openxmlformats-officedocument.presentationml.presentation`],[`.png`,`image/png`],[`.jpg`,`image/jpeg`],[`.jpeg`,`image/jpeg`],[`.zip`,`application/zip`]]),hr=e=>mr.get(_.extname(e).toLowerCase())??`application/octet-stream`,gr=e=>new Promise((t,n)=>{let r=i(`sha256`);e.on(`data`,e=>r.update(e)).on(`error`,n).on(`end`,()=>t(r.digest()))}),_r=async(e,t,n,r)=>{let i=await pr(e,t,n,r),{handle:a,size:o}=await ur(i),s;try{s=await gr(a.createReadStream())}finally{await a.close()}let c=_.basename(i);return{path:i,fileName:c,sizeBytes:o,sha256Hex:s.toString(`hex`),sha256Base64:s.toString(`base64`),mimeType:hr(c)}},vr=(e,t=9e5,n=1e3)=>{let r=/* @__PURE__ */ new Map,i=()=>{let t=e();for(let[e,n]of r)n.expiresAt<=t&&r.delete(e)};return{get size(){return r.size},register:(a,o,s)=>{for(i();r.size>=n;){let e=r.keys().next();if(e.done)break;r.delete(e.value)}r.delete(a),r.set(a,{kind:o,headers:s,expiresAt:e()+t})},take:(t,n)=>{let i=r.get(t);if(i?.kind!==n)throw new w(`unknown_url`,`the URL was not returned by a recent API call for this kind of transfer`);if(r.delete(t),i.expiresAt<=e())throw new w(`expired_url`,`the signed URL has expired; call the API again to get a new one`);return i}}},yr=(e,t)=>{let n;try{n=new URL(e)}catch{throw new w(`not_allowed_host`,`the transfer URL is not a valid URL`)}let r=t.allowInsecureHttp&&$e(n.hostname);if(n.protocol!==`https:`&&!(n.protocol===`http:`&&r))throw new w(`insecure_url`,`transfer URLs must use https`);if(n.username!==``||n.password!==``)throw new w(`not_allowed_host`,`transfer URLs must not contain credentials`);let i=n.hostname.toLowerCase();if(!(r||t.storageHostSuffixes.some(e=>e.startsWith(`.`)?i.endsWith(e):i===e)))throw new w(`not_allowed_host`,`the host ${i} is not an allowed storage host`);return n},br=4096,xr=async e=>{if(e.body==null)return``;let t=e.body.getReader(),n=[],r=0;try{for(;r<br;){let{done:e,value:i}=await t.read();if(e)break;n.push(i),r+=i.byteLength}}catch{}finally{await t.cancel().catch(O)}return new TextDecoder(`utf-8`).decode(Buffer.concat(n)).slice(0,br)},Sr=e=>e instanceof w?e:e instanceof Error&&(e.name===`AbortError`||e.name===`TimeoutError`)?new w(`timeout`,`the storage did not respond in time`):new w(`network`,e instanceof Error?e.message:`network failure`),Cr=async e=>{if(ue(e.headers).some(e=>e.toLowerCase()===`authorization`))throw new w(`invalid_headers`,`transfer headers must not include authorization`);let t;try{t=await dr(e.filePath,e.maxBytes)}catch(e){throw e instanceof T&&(e.kind===`not_a_file`||e.kind===`too_large`)?new w(e.kind,e.kind===`not_a_file`?`only regular files can be uploaded`:e.message):e}let n;try{n=await e.fetch(e.url,{method:`PUT`,headers:e.headers,body:t,redirect:`manual`,signal:AbortSignal.timeout(e.timeoutMs)})}catch(e){throw Sr(e)}if(n.status>=300&&n.status<400)throw await n.body?.cancel().catch(O),new w(`redirect_not_followed`,`redirect responses are not followed`,n.status);if(!n.ok)throw new w(`http_error`,`upload failed: ${(await xr(n)).slice(0,300)}`,n.status);return await n.body?.cancel().catch(O),{status:n.status,etag:n.headers.get(`etag`),bytes:t.byteLength}},wr=/[^A-Za-z0-9._-]/g,Tr=(e,t)=>{let n=_.basename(e??``).replace(wr,`_`).replace(/^_+/,``).slice(0,120);return n===``||/^\.+$/.test(n)?t:n},Er=e=>`${(/* @__PURE__ */ new Date()).toISOString().replaceAll(/[:.]/g,`-`)}-${a(3).toString(`hex`)}-${e}`,Dr=async(e,t)=>{if(t<=0)return`timeout`;let n=null,r=new Promise(e=>{n=setTimeout(e,t,`timeout`)});try{return await Promise.race([e.read(),r])}finally{n!=null&&clearTimeout(n)}},Or=async(e,t)=>{await l(t.outputDir,{recursive:!0,mode:448});let n=_.join(t.outputDir,Er(t.fileName)),r=await u(n,`wx`,384),a=i(`sha256`),o=e.getReader(),s=Date.now()+t.timeoutMs,c=0;try{for(;;){let e=await Dr(o,s-Date.now());if(e===`timeout`)throw await o.cancel().catch(O),new w(`timeout`,`the download did not finish within ${t.timeoutMs} ms`);let{done:n,value:i}=e;if(n)break;if(c+=i.byteLength,c>t.maxBytes)throw await o.cancel().catch(O),new w(`too_large`,`the download exceeds ${t.maxBytes} bytes`);a.update(i),await r.write(i)}}catch(e){throw await r.close(),await h(n).catch(O),Sr(e)}return await r.close(),{path:n,bytes:c,sha256Hex:a.digest(`hex`)}},kr=async e=>{let t;try{t=await e.fetch(e.url,{method:`GET`,redirect:`manual`,signal:AbortSignal.timeout(e.timeoutMs)})}catch(e){throw Sr(e)}if(t.status>=300&&t.status<400)throw await t.body?.cancel().catch(O),new w(`redirect_not_followed`,`redirect responses are not followed`,t.status);if(!t.ok)throw new w(`http_error`,`download failed: ${(await xr(t)).slice(0,300)}`,t.status);if(t.body==null)throw new w(`network`,`the download has no body`,t.status);return{...await Or(t.body,{outputDir:e.outputDir,fileName:e.fileName,maxBytes:e.maxBytes,timeoutMs:e.timeoutMs}),status:t.status,contentType:t.headers.get(`content-type`)}},Ar=(e,t,n,r)=>{let i={level:e,message:t,...n,time:(/* @__PURE__ */ new Date()).toISOString()};return H(JSON.stringify(i),r)},jr=(e,t=e=>console.error(e))=>({info:(n,r)=>t(Ar(`info`,n,r,e())),warn:(n,r)=>t(Ar(`warn`,n,r,e())),error:(n,r)=>t(Ar(`error`,n,r,e()))}),Mr=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],Nr=[`json`,`empty`,`sse`,`binary`],Pr=[`upload`,`download`],Fr=[`read`,`draft`],Ir=[`wav-pcm16`,`base64`],Lr=[`pcm16le`,`base64`],U=e=>{throw new oe(e)},W=e=>e===null,G=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),Rr=e=>{if(!Array.isArray(e)||e.length===0)return!1;let t=0;for(let n of e){if(typeof n!=`number`||!Number.isInteger(n)||n<200||n>=300||n<=t)return!1;t=n}return!0},zr=e=>typeof e==`string`&&Mr.some(t=>t===e),Br=e=>typeof e==`string`&&Nr.some(t=>t===e),Vr=e=>typeof e==`string`&&Pr.some(t=>t===e),Hr=e=>typeof e==`string`&&Fr.some(t=>t===e),Ur=(e,t)=>{if(W(e))return null;if(!A(e))return U(`${t}.transfer must be an object or null`);let{kind:n,urlPointer:r,headersPointer:i,namePointer:a}=e;return Vr(n)?typeof r==`string`?!W(i)&&typeof i!=`string`?U(`${t}.transfer.headersPointer is invalid`):!W(a)&&typeof a!=`string`?U(`${t}.transfer.namePointer is invalid`):{kind:n,urlPointer:r,headersPointer:i,namePointer:a}:U(`${t}.transfer.urlPointer is invalid`):U(`${t}.transfer.kind is invalid`)},Wr=e=>typeof e==`string`&&Ir.some(t=>t===e),Gr=e=>typeof e==`string`&&Lr.some(t=>t===e),Kr=e=>typeof e==`number`&&Number.isInteger(e)&&e>0,qr=(e,t)=>{if(W(e))return null;if(!A(e))return U(`${t} must be an object or null`);let{sampleRateHz:n,channels:r}=e;return Kr(n)?Kr(r)?{sampleRateHz:n,channels:r}:U(`${t}.channels is invalid`):U(`${t}.sampleRateHz is invalid`)},Jr=(e,t)=>{if(!A(e))return U(`${t} must be an object`);let{pointer:n,format:r,maxBytes:i,pcm:a}=e;if(typeof n!=`string`||!n.startsWith(`/`))return U(`${t}.pointer is invalid`);if(!Wr(r))return U(`${t}.format is invalid`);if(!Kr(i))return U(`${t}.maxBytes is invalid`);let o=qr(a,`${t}.pcm`);return r===`wav-pcm16`==(o!=null)?{pointer:n,format:r,maxBytes:i,pcm:o}:U(`${t}.pcm does not match the format`)},Yr=(e,t)=>{if(!A(e))return U(`${t} must be an object`);let{event:n,pointer:r,format:i,pcm:a,mediaType:o}=e;if(!W(n)&&typeof n!=`string`)return U(`${t}.event is invalid`);if(typeof r!=`string`||!r.startsWith(`/`))return U(`${t}.pointer is invalid`);if(!Gr(i))return U(`${t}.format is invalid`);if(!W(o)&&typeof o!=`string`)return U(`${t}.mediaType is invalid`);let s=qr(a,`${t}.pcm`);return i===`pcm16le`==(s!=null)?i===`base64`==(o!=null)?{event:n,pointer:r,format:i,pcm:s,mediaType:o}:U(`${t}.mediaType does not match the format`):U(`${t}.pcm does not match the format`)},Xr=(e,t)=>{if(W(e))return null;if(!A(e))return U(`${t}.inlineFiles must be an object or null`);let{input:n,output:r}=e;return!Array.isArray(n)||!Array.isArray(r)?U(`${t}.inlineFiles is invalid`):n.length===0&&r.length===0?U(`${t}.inlineFiles must declare input or output`):{input:n.map((e,n)=>Jr(e,`${t}.inlineFiles.input[${String(n)}]`)),output:r.map((e,n)=>Yr(e,`${t}.inlineFiles.output[${String(n)}]`))}},Zr=(e,t)=>{if(W(e))return null;if(!A(e))return U(`${t}.sseOutcome must be an object or null`);let{requiredEvents:n,terminalEvent:r,successPointer:i,successValue:a,failureEvents:o}=e;return G(n)?typeof r==`string`?W(i)&&W(a)?G(o)?{requiredEvents:n,terminalEvent:r,successPointer:i,successValue:a,failureEvents:o}:U(`${t}.sseOutcome.failureEvents is invalid`):typeof i!=`string`||!i.startsWith(`/`)?U(`${t}.sseOutcome.successPointer is invalid`):typeof a!=`string`&&typeof a!=`number`&&typeof a!=`boolean`?U(`${t}.sseOutcome.successValue is invalid`):G(o)?{requiredEvents:n,terminalEvent:r,successPointer:i,successValue:a,failureEvents:o}:U(`${t}.sseOutcome.failureEvents is invalid`):U(`${t}.sseOutcome.terminalEvent is invalid`):U(`${t}.sseOutcome.requiredEvents is invalid`)},Qr=(e,t)=>{let n=`operations[${t}]`;if(!A(e))return U(`${n} must be an object`);let{operationId:r,method:i,pathTemplate:a,summary:o,label:s,description:c,permission:l,effect:u,responseContainsSecret:d,responseKind:f,successStatuses:p,pathParams:m,queryParams:h,bodyFields:g,wholeBodyField:_,inputSchema:v,transfer:ee,inlineFiles:te,sseOutcome:ne}=e;return typeof r!=`string`||r===``?U(`${n}.operationId is invalid`):zr(i)?typeof a!=`string`||!a.startsWith(`/`)?U(`${n}.pathTemplate is invalid`):typeof o==`string`?!W(s)&&typeof s!=`string`?U(`${n}.label is invalid`):!W(c)&&typeof c!=`string`?U(`${n}.description is invalid`):!W(u)&&!Hr(u)?U(`${n}.effect is invalid`):typeof d==`boolean`?Br(f)?Rr(p)?G(m)?G(h)?!W(g)&&!G(g)?U(`${n}.bodyFields is invalid`):!W(_)&&typeof _!=`string`?U(`${n}.wholeBodyField is invalid`):g!=null&&_!=null?U(`${n} declares both bodyFields and wholeBodyField`):A(v)?{operationId:r,method:i,pathTemplate:a,summary:o,label:s,description:c,permission:l??null,effect:u,responseContainsSecret:d,responseKind:f,successStatuses:p,pathParams:m,queryParams:h,bodyFields:g,wholeBodyField:_,inputSchema:v,transfer:Ur(ee,n),inlineFiles:Xr(te,n),sseOutcome:Zr(ne,n)}:U(`${n}.inputSchema is invalid`):U(`${n}.queryParams is invalid`):U(`${n}.pathParams is invalid`):U(`${n}.successStatuses is invalid`):U(`${n}.responseKind is invalid`):U(`${n}.responseContainsSecret is invalid`):U(`${n}.summary is invalid`):U(`${n}.method is invalid`)},$r=e=>{if(!A(e))return U(`manifest must be an object`);let t=e.source;if(!A(t)||typeof t.title!=`string`||typeof t.version!=`string`)return U(`manifest.source is invalid`);let n=e.operations;if(!Array.isArray(n))return U(`manifest.operations must be an array`);let r=n.map((e,t)=>Qr(e,t));return new Set(r.map(e=>e.operationId)).size===r.length?{source:{title:t.title,version:t.version},operations:r}:U(`manifest.operations has duplicate operationId`)},ei=(e,t)=>{let n;try{n=re(e)}catch{throw t(`${e.pathname} cannot be read`)}try{return JSON.parse((e.pathname.endsWith(`.br`)?ie(n):n).toString(`utf8`))}catch{throw t(`${e.pathname} is not valid JSON or brotli`)}},ti=new URL(`./manifest.json.br`,import.meta.url),ni=(e=ti)=>$r(ei(e,e=>new oe(`manifest at ${e}`))),ri=e=>`${e.product}/${e.slug}`,ii=e=>({articles:e,articleByReference:new Map(e.map(e=>[ri(e),e])),searchEntries:e.map(e=>({article:e,normalizedTitle:e.title.toLowerCase(),normalizedDescription:e.description.toLowerCase(),normalizedGroup:e.group.toLowerCase(),normalizedBody:e.body.toLowerCase()}))}),ai=(e,t)=>e.articleByReference.get(t)??null,oi=(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},si=(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:ri(e.article),title:e.article.title,group:e.article.group,description:e.article.description,snippet:oi(e,r)}))},ci=(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(`
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@flyle/ai-operator-mcp","version":"1.
|
|
1
|
+
{"name":"@flyle/ai-operator-mcp","version":"1.1.0-develop.20261109160053.g0b5ef29","description":"MCP server for the Flyle AI Operator 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/flygate/mcp"},"type":"module","engines":{"node":">=22.0.0"},"publishConfig":{"access":"public","registry":"https://registry.npmjs.org/"},"bin":{"flyle-ai-operator-mcp":"./main.js"},"dependencies":{"@modelcontextprotocol/server":"2.3.1"}}
|