yaml-flow 8.6.3 → 8.7.0
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/browser/adapters/firebase-storage.js +3 -0
- package/browser/adapters/firestore-storage.js +3 -0
- package/browser/adapters/localstorage-storage.js +4 -0
- package/browser/asset-integrity.json +20 -4
- package/browser/server-runtime-controlface.js +8 -0
- package/examples/ARCHITECTURE.md +5 -32
- package/examples/board/demo-shell-with-server.html +2 -2
- package/examples/board/doc.html +2 -2
- package/examples/board/server/board-server.js +4 -2
- package/examples/board/server/chat-flow/flow-steps.json +10 -5
- package/examples/board/test/server-http-test.js +93 -0
- package/examples/board-firestore/README.md +81 -0
- package/examples/board-firestore/browser/board-runtime.js +263 -0
- package/examples/board-firestore/firestore.indexes.json +29 -0
- package/examples/board-firestore/package.json +14 -0
- package/examples/board-firestore/server/adapters/firestore-archive-factory.js +59 -0
- package/examples/board-firestore/server/adapters/firestore-blob-storage.js +82 -0
- package/examples/board-firestore/server/adapters/firestore-board-adapter.js +127 -0
- package/examples/board-firestore/server/adapters/firestore-journal-storage.js +54 -0
- package/examples/board-firestore/server/adapters/firestore-kv-storage.js +47 -0
- package/examples/board-firestore/server/adapters/firestore-lock.js +62 -0
- package/examples/board-firestore/server/adapters/firestore-queue-storage.js +186 -0
- package/examples/board-firestore/server/adapters/firestore-scratch-storage.js +50 -0
- package/examples/board-firestore/server/worker.js +146 -0
- package/lib/{artifacts-store-lib-BR-Samty.d.cts → artifacts-store-lib-D9nMkVcE.d.cts} +1 -1
- package/lib/{artifacts-store-lib-DT7XlWUL.d.ts → artifacts-store-lib-DSSMqVL2.d.ts} +1 -1
- package/lib/artifacts-store-public.d.cts +2 -2
- package/lib/artifacts-store-public.d.ts +2 -2
- package/lib/board-live-cards-mcp.cjs +1 -1
- package/lib/board-live-cards-mcp.d.cts +51 -3
- package/lib/board-live-cards-mcp.d.ts +51 -3
- package/lib/board-live-cards-mcp.js +1 -1
- package/lib/board-live-cards-node.cjs +8 -8
- package/lib/board-live-cards-node.d.cts +13 -9
- package/lib/board-live-cards-node.d.ts +13 -9
- package/lib/board-live-cards-node.js +8 -8
- package/lib/{board-live-cards-public-BMUIPOrc.d.ts → board-live-cards-public-D-DJek3X.d.ts} +1 -1
- package/lib/{board-live-cards-public-wkNmBIRC.d.cts → board-live-cards-public-DQzPe7A9.d.cts} +1 -1
- package/lib/board-live-cards-public-async-3hUuHxDx.d.ts +55 -0
- package/lib/board-live-cards-public-async-CgMCYYft.d.cts +55 -0
- package/lib/board-live-cards-public.d.cts +1 -1
- package/lib/board-live-cards-public.d.ts +1 -1
- package/lib/board-live-cards-server-runtime.cjs +1 -1
- package/lib/board-live-cards-server-runtime.d.cts +10 -6
- package/lib/board-live-cards-server-runtime.d.ts +10 -6
- package/lib/board-live-cards-server-runtime.js +1 -1
- package/lib/board-platform-adapter-async-DOfEq_HC.d.cts +129 -0
- package/lib/board-platform-adapter-async-JZPCzZnH.d.ts +129 -0
- package/lib/board-worker-adapter.cjs +3 -3
- package/lib/board-worker-adapter.js +3 -3
- package/lib/card-store-public.d.cts +1 -1
- package/lib/card-store-public.d.ts +1 -1
- package/lib/{chat-storage-lib-BIUbE-fM.d.cts → chat-storage-lib-B9Q34Dyv.d.cts} +1 -1
- package/lib/{chat-storage-lib-BlG-sobS.d.ts → chat-storage-lib-DB9iSai2.d.ts} +1 -1
- package/lib/chat-store-public.d.cts +2 -2
- package/lib/chat-store-public.d.ts +2 -2
- package/lib/chunk-272IYUKT.cjs +2 -0
- package/lib/chunk-5XHOHTLZ.cjs +2 -0
- package/lib/chunk-6APH25VI.js +2 -0
- package/lib/chunk-7FGPOGRV.cjs +2 -0
- package/lib/chunk-7ICPAABP.cjs +7 -0
- package/lib/chunk-CPAXTVBQ.cjs +2 -0
- package/lib/chunk-DDYSXP2A.cjs +3 -0
- package/lib/chunk-EGRHWZRV.js +2 -0
- package/lib/chunk-GL2OHR2E.cjs +2 -0
- package/lib/chunk-IPLSRN6P.cjs +4 -0
- package/lib/chunk-J5J6BG7B.js +2 -0
- package/lib/chunk-KAWQPLIE.cjs +2 -0
- package/lib/chunk-LPXVVMQT.cjs +2 -0
- package/lib/chunk-M3OU6IS5.cjs +2 -0
- package/lib/chunk-M6STQR5F.cjs +2 -0
- package/lib/chunk-NJJ7WEDT.cjs +2 -0
- package/lib/chunk-NKIQRCOM.cjs +2 -0
- package/lib/chunk-NM6O35RY.cjs +2 -0
- package/lib/chunk-NTICU4OK.js +2 -0
- package/lib/chunk-O7NOHKVR.js +2 -0
- package/lib/chunk-PRHQBGPT.js +2 -0
- package/lib/chunk-S44QZUDX.js +2 -0
- package/lib/chunk-SGV7PU4H.js +2 -0
- package/lib/chunk-TSN3RTXT.js +4 -0
- package/lib/chunk-VXJHBWK3.js +2 -0
- package/lib/chunk-WHDEBJLT.js +7 -0
- package/lib/chunk-XYN5D3GL.js +2 -0
- package/lib/chunk-YGALANRO.js +2 -0
- package/lib/chunk-ZJ5M5COT.js +2 -0
- package/lib/chunk-ZXQR7GHT.js +3 -0
- package/lib/cloud-storage.cjs +1 -1
- package/lib/cloud-storage.d.cts +5 -3
- package/lib/cloud-storage.d.ts +5 -3
- package/lib/cloud-storage.js +1 -1
- package/lib/firebase-storage/index.cjs +3 -0
- package/lib/firebase-storage/index.d.cts +57 -0
- package/lib/firebase-storage/index.d.ts +57 -0
- package/lib/firebase-storage/index.js +3 -0
- package/lib/firestore-storage/index.cjs +3 -0
- package/lib/firestore-storage/index.d.cts +98 -0
- package/lib/firestore-storage/index.d.ts +98 -0
- package/lib/firestore-storage/index.js +3 -0
- package/lib/localstorage-storage/index.cjs +2 -0
- package/lib/localstorage-storage/index.d.cts +39 -0
- package/lib/localstorage-storage/index.d.ts +39 -0
- package/lib/localstorage-storage/index.js +2 -0
- package/lib/mcp-tool-registries-BBObLYga.d.ts +41 -0
- package/lib/mcp-tool-registries-W3TRj6O5.d.cts +41 -0
- package/lib/queue-lane-registry-PaZuFpwp.d.cts +30 -0
- package/lib/queue-lane-registry-PaZuFpwp.d.ts +30 -0
- package/lib/server-jobs-queue-runner/index.cjs +2 -0
- package/lib/server-jobs-queue-runner/index.d.cts +22 -0
- package/lib/server-jobs-queue-runner/index.d.ts +22 -0
- package/lib/server-jobs-queue-runner/index.js +2 -0
- package/lib/server-runtime/index.cjs +1 -1
- package/lib/server-runtime/index.d.cts +11 -17
- package/lib/server-runtime/index.d.ts +11 -17
- package/lib/server-runtime/index.js +1 -1
- package/lib/server-runtime-agentface/index.cjs +2 -0
- package/lib/server-runtime-agentface/index.d.cts +53 -0
- package/lib/server-runtime-agentface/index.d.ts +53 -0
- package/lib/server-runtime-agentface/index.js +2 -0
- package/lib/server-runtime-controlface/index.cjs +2 -0
- package/lib/server-runtime-controlface/index.d.cts +80 -0
- package/lib/server-runtime-controlface/index.d.ts +80 -0
- package/lib/server-runtime-controlface/index.js +2 -0
- package/lib/server-runtime-core/index.cjs +2 -0
- package/lib/server-runtime-core/index.d.cts +376 -0
- package/lib/server-runtime-core/index.d.ts +376 -0
- package/lib/server-runtime-core/index.js +2 -0
- package/lib/server-runtime-watchers/index.cjs +2 -0
- package/lib/server-runtime-watchers/index.d.cts +127 -0
- package/lib/server-runtime-watchers/index.d.ts +127 -0
- package/lib/server-runtime-watchers/index.js +2 -0
- package/lib/server-runtime-webhooks/index.cjs +2 -0
- package/lib/server-runtime-webhooks/index.d.cts +34 -0
- package/lib/server-runtime-webhooks/index.d.ts +34 -0
- package/lib/server-runtime-webhooks/index.js +2 -0
- package/lib/storage-async-interface-BRR4eBjx.d.cts +81 -0
- package/lib/storage-async-interface-DhlOVPSp.d.ts +81 -0
- package/lib/{queue-lane-registry-BPKWWgd4.d.cts → types-BzQY45dH.d.cts} +8 -34
- package/lib/{queue-lane-registry-Be6c0ftj.d.ts → types-CF2xUcZW.d.ts} +8 -34
- package/package.json +46 -2
- package/examples/board-local/demo-shell-localstorage.html +0 -843
- package/lib/board-live-cards-public-async-DKZqbJVU.d.ts +0 -256
- package/lib/board-live-cards-public-async-dMWNbWq6.d.cts +0 -256
- package/lib/chunk-GJJMEAVN.cjs +0 -2
- package/lib/chunk-GLIX37VG.cjs +0 -8
- package/lib/chunk-LRVAVWAG.js +0 -8
- package/lib/chunk-MLVTJASJ.js +0 -2
- package/lib/chunk-SCWHDI3I.js +0 -2
- package/lib/chunk-WOALA3V5.cjs +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function p(e){return String(e).replace(/[^a-zA-Z0-9_-]/g,"_")}function m(e){let n=e.payload??{};return {id:e.id,role:typeof n.role=="string"?n.role:"system",text:typeof n.text=="string"?n.text:"",files:Array.isArray(n.files)?n.files:[],turn:typeof n.turn=="string"?n.turn:"",updated_at:typeof n.updated_at=="string"?n.updated_at:""}}function R(e,n){let a=t=>`chats/${p(t)}/processing`,r=t=>`chats/${p(t)}/config`;return {append(t,i,o,u=[],s=""){return e(t).append({role:i,text:o,files:u,turn:s,updated_at:new Date().toISOString()}).id},readAll(t){return e(t).readAll().map(m)},readAfter(t,i){let o=e(t).readAfter(i);return {records:o.entries.map(m),cursor:o.newCursor}},clear(t){e(t).clear?.();},setProcessing(t,i){i?n.write(a(t),true):n.delete(a(t));},isProcessing(t){return n.read(a(t))===true},getConfig(t){return n.read(r(t))??{}},setConfig(t,i){let o=n.read(r(t))??{};n.write(r(t),{...o,...i});}}}function S(){let e=globalThis.crypto;return typeof e?.randomUUID=="function"?String(e.randomUUID()):`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function $(){let e=new Map,n=new Map;function a(r){return e.has(r)||e.set(r,[]),e.get(r)}return {append(r,t,i,o=[],u=""){let s={id:S(),role:t,text:i,files:o,turn:u,updated_at:new Date().toISOString()};return a(r).push(s),s.id},readAll(r){return a(r).slice()},readAfter(r,t){let i=a(r);if(!t)return {records:i.slice(),cursor:i.length>0?i[i.length-1].id:null};let o=i.findIndex(s=>s.id===t),u=o===-1?i.slice():i.slice(o+1);return {records:u,cursor:u.length>0?u[u.length-1].id:t}},clear(r){e.set(r,[]);},setProcessing(r,t){t?n.set(`p:${r}`,true):n.delete(`p:${r}`);},isProcessing(r){return n.get(`p:${r}`)===true},getConfig(r){return n.get(`c:${r}`)??{}},setConfig(r,t){let i=n.get(`c:${r}`)??{};n.set(`c:${r}`,{...i,...t});}}}function y(){return new Date().toISOString()}function x(e){return new TextEncoder().encode(e).byteLength}function A(e){return e?{key:e.key,size:e.size,updatedAt:e.updatedAt,contentType:e.contentType}:null}function w(e){let n=String(e||"").match(/^(\d+)[-_]/);return n?parseInt(n[1],10):0}function I(e){let n=String(e||"").trim();if(!n)return "upload.bin";let a=Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"));return (a>=0?n.slice(a+1):n)||"upload.bin"}function k(e){return String(e||"").toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"")||"file"}function z(e){if(!e||e===".")return "";let n=String(e).replace(/^\./,"").toLowerCase().replace(/[^a-z0-9]/g,"");return n?`.${n}`:""}function F(e){let n=I(e),a=n.lastIndexOf(".");return a<=0||a===n.length-1?{stem:n,ext:""}:{stem:n.slice(0,a),ext:n.slice(a)}}function M(e){let n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e}function L(e){function n(a){let r=e.stat?A(e.stat(a)):null;if(r)return r;if(!e.exists(a))return null;let t=e.read(a);return t===null?{key:a}:{key:a,size:x(t)}}return {exists(a){return e.exists(a)},putText(a,r,t="text/plain; charset=utf-8"){e.write(a,r);let i=n(a)??{key:a};return i.contentType=t,i.updatedAt=i.updatedAt??y(),i.size=i.size??x(r),i},putBytes(a,r,t="application/octet-stream"){if(e.writeBytes)e.writeBytes(a,r);else {let o=JSON.stringify({__kind:"bytes-array",data:[...r]});e.write(a,o);}let i=n(a)??{key:a};return i.contentType=t,i.updatedAt=i.updatedAt??y(),i.size=i.size??r.byteLength,i},getText(a){let r=e.read(a);if(r===null){if(!e.readBytes)return null;let t=e.readBytes(a);return t===null?null:Buffer.from(t).toString("utf-8")}try{let t=JSON.parse(r);if(t&&t.__kind==="bytes-array"&&Array.isArray(t.data))return new TextDecoder("utf-8").decode(new Uint8Array(t.data))}catch{}return r},getBytes(a){if(e.readBytes){let t=e.readBytes(a);if(t!==null)return t}let r=e.read(a);if(r===null)return null;try{let t=JSON.parse(r);if(t&&t.__kind==="bytes-array"&&Array.isArray(t.data))return new Uint8Array(t.data)}catch{}return new TextEncoder().encode(r)},head:n,list(a=""){return e.listKeys(a).map(r=>n(r)??{key:r}).sort((r,t)=>r.key.localeCompare(t.key))},remove(a){e.remove(a);}}}function b(e){function n(t,i){let o=0,u=[];Array.isArray(i)&&u.push(...i);for(let s of e.list(`${t}/`))u.push(M(s.key));for(let s of u){let l=w(s);Number.isFinite(l)&&l>o&&(o=l);}return o+1}function a(t,i,o){let u=Number(o?.maxLen||32),{stem:s,ext:l}=F(t),h=z(l),C=k(s),d=`${String(i).padStart(3,"0")}-`,g=h,f=u-d.length-g.length;f<1&&(g="",f=u-d.length);let _=C.slice(0,Math.max(1,f)),c=`${d}${_}${g}`;return c.length>u&&(c=c.slice(0,u).replace(/\.$/,"")),c}function r(t,i,o){let u=n(t,o?.seedNames),s=a(i,u,{maxLen:o?.maxLen});for(;e.exists(`${t}/${s}`);)u+=1,s=a(i,u,{maxLen:o?.maxLen});return s}return {nextSerial:n,buildStoredName:a,allocateStoredName:r}}function N(){function e(t,i){if(!Array.isArray(t))return [];let o=[];for(let u of t){if(!u||typeof u!="object")continue;let s=u;typeof s.stored_name=="string"&&o.push({name:typeof s.name=="string"?s.name:s.stored_name,stored_name:s.stored_name,size:typeof s.size=="number"&&Number.isFinite(s.size)?s.size:null,mime_type:typeof s.mime_type=="string"?s.mime_type:null,uploaded_at:typeof s.uploaded_at=="string"?s.uploaded_at:i||null,chat:s.chat===true});}return o}function n(t){return !t||typeof t!="object"?[]:e(t.files,void 0)}function a(t,i){let o=n(t);if(i.length===0)return t.files=o,o;let u=new Set(o.map(s=>s.stored_name));for(let s of i)u.has(s.stored_name)||(o.push(s),u.add(s.stored_name));return t.files=o,o}function r(t,i,o){let u=n(t);if(!Number.isInteger(i)||i<0||i>=u.length)return {ok:false,reason:"index_out_of_range"};let s=u[i];return !s||!s.stored_name?{ok:false,reason:"missing_stored_name"}:o&&o!==s.stored_name?{ok:false,reason:"stale_reference"}:{ok:true,file:s}}return {read:n,normalizeIncoming:e,merge:a,resolve:r}}export{R as a,$ as b,L as c,b as d,N as e};//# sourceMappingURL=chunk-6APH25VI.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-6APH25VI.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkLPXVVMQT_cjs=require('./chunk-LPXVVMQT.cjs'),chunk272IYUKT_cjs=require('./chunk-272IYUKT.cjs');function G(q){let{apiBasePath:x,json:r,readJsonBody:k,bootstrapBoard:T,createMcpFacade:B,createMcpToolRegistry:I,resolveCardFileDownloadPayload:j,isLikelyTextMimeType:v,sliceTextByLines:C}=q;async function D(b,e,N){let A=b.method||"GET",M=N,L=M.pathname;try{if(A==="POST"&&L===`${x}/mcp`){await T();let t=await k(b),i=typeof t.tool=="string"?t.tool.trim():"",a=t.args&&typeof t.args=="object"&&!Array.isArray(t.args)?t.args:{};if(!i)return r(e,400,{error:"tool is required"}),!0;if(i==="inspect.file-contents")return r(e,400,{error:"inspect.file-contents is only available on /mcp-raw"}),!0;try{let n=await chunk272IYUKT_cjs.a(i,a,I(B()));if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;if(s.status==="fail")return r(e,400,{error:chunk272IYUKT_cjs.b(n,"Request failed")}),!0;if(s.status==="error")return r(e,500,{error:chunk272IYUKT_cjs.b(n,"Internal error")}),!0}r(e,200,n);}catch(n){let s=typeof n?.statusCode=="number"?Number(n.statusCode):500,d=n instanceof Error?n.message:String(n);r(e,s,{error:d});}return !0}if(A==="POST"&&L===`${x}/mcp-raw`){await T();let t=await k(b),i=typeof t.tool=="string"?t.tool.trim():"",a=t.args&&typeof t.args=="object"&&!Array.isArray(t.args)?t.args:{};if(!i)return r(e,400,{error:"tool is required"}),!0;if(i!=="inspect.file-contents")return r(e,400,{error:`Tool does not support raw response: ${i}`}),!0;let n=chunkLPXVVMQT_cjs.a(a,"card_id","cardId"),s=chunkLPXVVMQT_cjs.b(a,"file_idx","fileIdx"),d=chunkLPXVVMQT_cjs.b(a,"head-lines","headLines"),m=chunkLPXVVMQT_cjs.b(a,"tail-lines","tailLines"),f=chunkLPXVVMQT_cjs.b(a,"head-bytes","headBytes"),y=chunkLPXVVMQT_cjs.b(a,"tail-bytes","tailBytes");if(!n)return r(e,400,{error:"inspect.file-contents requires card_id"}),!0;if(s===void 0||!Number.isInteger(s)||s<0)return r(e,400,{error:"inspect.file-contents requires file_idx to be a non-negative integer"}),!0;if([d,m,f,y].filter(o=>o!==void 0).length>1)return r(e,400,{error:"inspect.file-contents accepts at most one of head-lines, tail-lines, head-bytes, tail-bytes"}),!0;for(let[o,u]of [["head-lines",d],["tail-lines",m],["head-bytes",f],["tail-bytes",y]])if(u!==void 0&&(!Number.isInteger(u)||u<0))return r(e,400,{error:`inspect.file-contents requires ${o} to be a non-negative integer`}),!0;let F=await B().inspectFileContents({cardId:n,fileIdx:s}),$=typeof F?.stored_name=="string"?F.stored_name:null,{fileRecord:R,bytes:p}=await j(n,s,$),P=String(R.name||R.stored_name||"download.bin"),w=String(R.mime_type||"application/octet-stream"),g=(M.searchParams.get("resp")||"").trim().toLowerCase();if(g&&g!=="json-b64")return r(e,400,{error:`unsupported resp mode: ${g}`}),!0;let U=g==="json-b64",c;if(d!==void 0||m!==void 0){if(!v(w))return r(e,400,{error:"head-lines/tail-lines are only supported for text-like files; use head-bytes/tail-bytes for binary content"}),!0;let o=new TextDecoder().decode(p),u=d!==void 0?C(o,"head",d):C(o,"tail",m);c=typeof Buffer<"u"?Buffer.from(u,"utf8"):new TextEncoder().encode(u);}else if(f!==void 0||y!==void 0){let o=f??y;c=f!==void 0?p.slice(0,o):p.slice(Math.max(0,p.length-o));}else c=p;if(U){let o=typeof Buffer<"u"?Buffer.from(c).toString("base64"):btoa(String.fromCharCode(...c));return r(e,200,{bodyBase64:o,mimeType:w,filename:P,byteLength:c.length}),!0}return e.writeHead(200,{"Content-Type":w,"Content-Disposition":`attachment; filename="${P}"`,"Content-Length":c.length}),e.end(c),!0}return !1}catch(t){let i=t?.statusCode||500;return r(e,i,{error:String(t?.message||t)}),true}}return {handleAgentfaceApi:D}}exports.a=G;//# sourceMappingURL=chunk-7FGPOGRV.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-7FGPOGRV.cjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
'use strict';var chunkKAWQPLIE_cjs=require('./chunk-KAWQPLIE.cjs');function A(h){let r=new Map,a=new Map,d=new Map,I=0,b=null;function g(e){let t=JSON.stringify(e);return I++,`id: ${I}
|
|
2
|
+
data: ${t}
|
|
3
|
+
|
|
4
|
+
`}function C(e){let t=e;try{t.flushHeaders?.();}catch{}try{t.flush?.();}catch{}try{t.socket?.setNoDelay?.(!0);}catch{}try{t.socket?.uncork?.();}catch{}}function y(e,t){let s=r.get(e);if(s&&!(t&&s.res!==t)){r.delete(e),w();try{h.onSseClientDisconnected?.(e);}catch{}try{s.res.end();}catch{}}}function v(e,t,s){let n=r.get(e);n&&y(e,n.res),r.set(e,{res:t,subscribedChatCardIds:s??new Set});}function f(e,t){let s=r.get(e);if(!s)return;let n=g(t);try{s.res.write(n),C(s.res);}catch{y(e,s.res);}}function c(){let e=new Set;for(let t of r.values())for(let s of t.subscribedChatCardIds)e.add(s);return Array.from(e)}function l(e){let t=a.has(e)?a.get(e):null,{cursor:s}=h.chatStorage.readAfter(e,t),n=h.chatStorage.isProcessing(e),o=n!==(d.get(e)??false),S=s!==t;return S&&a.set(e,s),d.set(e,n),S||o}function u(e,t){let s=h.readChatRecords(e),n=Date.now();return {kind:"card_chats",cardId:e,sentAt:new Date(n).toISOString(),sentAtMs:n,messages:s.map(o=>({role:String(o.role||"system"),text:String(o.text||""),files:Array.isArray(o.files)?o.files:[]})),receiving:t,processing:h.chatStorage.isProcessing(e)}}function i(e,t=true){let s={kind:"notification-batch",notifications:[u(e,t)]};for(let[n,o]of r.entries())o.subscribedChatCardIds.has(e)&&f(n,s);}function w(){c().length>0||(b&&(clearInterval(b),b=null),a.clear(),d.clear());}function p(){if(b)return;let e=()=>{let t=c();if(t.length===0){w();return}let s=new Set(t);for(let n of Array.from(a.keys()))s.has(n)||a.delete(n);for(let n of Array.from(d.keys()))s.has(n)||d.delete(n);for(let n of t)l(n)&&i(n,true);};e(),b=setInterval(e,1e3);}function k(e,t){let s=r.get(e);if(!s)return false;s.subscribedChatCardIds.add(t);let{cursor:n}=h.chatStorage.readAfter(t,null);return a.set(t,n),d.set(t,h.chatStorage.isProcessing(t)),p(),f(e,{kind:"notification-batch",notifications:[u(t,true)]}),true}function m(e,t){let s=r.get(e);return s?(s.subscribedChatCardIds.delete(t),c().includes(t)||(a.delete(t),d.delete(t)),w(),true):false}function R(e){if(!e||typeof e!="object")return false;let t=e.kind;return t==="card_chats"||t==="chat_messages"}function P(e){if(!e||e.length===0)return;let t=[],s=new Set;for(let n of e)R(n)&&typeof n.cardId=="string"?s.add(String(n.cardId)):t.push(n);if(t.length>0){let n={kind:"notification-batch",notifications:t};for(let o of r.keys())f(o,n);}for(let n of s)i(n,true);}return {size:()=>r.size,has:e=>r.has(e),get:e=>r.get(e),buildFrame:g,flushTransport:C,register:v,disconnect:y,writeFrame:f,subscribeChat:k,unsubscribeChat:m,broadcastNotificationBatch:P,broadcastCardChats:i}}function D(h){let{sseHub:r,corsHeaders:a,json:d,buildPublishedRuntimePayload:I,onSseClientConnected:b,onChannelSubscribed:g,onChannelUnsubscribed:C}=h;function y(f,c,l,u,i){if(!r.has(c)){d(f,404,{error:`SSE client not connected: ${c}`});return}i?g?.(c,l,u):C?.(c,l,u),d(f,200,{ok:true,clientId:c,channelName:l,...u.cardId?{cardId:u.cardId}:{},subscribed:i});}async function v(f,c,l){let u=r.get(l),i=u?new Set(u.subscribedChatCardIds):new Set;c.writeHead(200,{...a,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),r.flushTransport(c),r.register(l,c,i);let w=await I(),p=r.buildFrame(w);c.write(p);try{b?.(l,m=>{r.writeFrame(l,m);});}catch{}let k=setInterval(()=>{try{c.write(`: keepalive
|
|
5
|
+
|
|
6
|
+
`);}catch{}},15e3);f.on("close",()=>{clearInterval(k),r.disconnect(l,c);});}return {handleChannelSubscription:y,handleSse:v}}function T(h){let{apiBasePath:r,json:a,readJsonBody:d,initBoardAndSetup:I,bootstrapBoard:b,boardContexts:g,publishPersistedStateSnapshot:C,upsertCardsFromSource:y,sseHub:v}=h,{handleSse:f,handleChannelSubscription:c}=D(h);async function l(u,i,w){let p=u.method||"GET",k=w,m=k.pathname;try{if(p==="GET"&&m===`${r}/sse`){await I();let s=String(k.searchParams.get("clientId")||"").trim();if(!s)return a(i,400,{error:"clientId query param is required for SSE"}),!0;await f(u,i,s);for(let n=0;n<g.length;n++)await C(g[n]),await y(g[n],n),await C(g[n]);return !0}let R=m.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(r)}/cards/([^/]+)/chats/subscribe-sse$`));if(p==="POST"&&R){await b();let s=decodeURIComponent(R[1]),n=await d(u),o=typeof n?.clientId=="string"?n.clientId.trim():"";return o?v.subscribeChat(o,s)?(a(i,200,{ok:!0,clientId:o,cardId:s,subscribed:!0}),!0):(a(i,404,{error:`SSE client not connected: ${o}`}),!0):(a(i,400,{error:"clientId is required"}),!0)}let P=m.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(r)}/cards/([^/]+)/chats/unsubscribe-sse$`));if(p==="POST"&&P){await b();let s=decodeURIComponent(P[1]),n=await d(u),o=typeof n?.clientId=="string"?n.clientId.trim():"";return o?v.unsubscribeChat(o,s)?(a(i,200,{ok:!0,clientId:o,cardId:s,subscribed:!1}),!0):(a(i,404,{error:`SSE client not connected: ${o}`}),!0):(a(i,400,{error:"clientId is required"}),!0)}let e=m.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(r)}/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(p==="POST"&&e){await b();let s=decodeURIComponent(e[1]),n=e[2]==="subscribe",o=await d(u),S=typeof o?.clientId=="string"?o.clientId.trim():"";return S?(c(i,S,s,{},n),!0):(a(i,400,{error:"clientId is required"}),!0)}let t=m.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(r)}/cards/([^/]+)/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(p==="POST"&&t){await b();let s=decodeURIComponent(t[1]),n=decodeURIComponent(t[2]),o=t[3]==="subscribe",S=await d(u),H=typeof S?.clientId=="string"?S.clientId.trim():"";return H?(c(i,H,n,{cardId:s},o),!0):(a(i,400,{error:"clientId is required"}),!0)}return !1}catch(R){let P=R?.statusCode||500;return a(i,P,{error:String(R?.message||R)}),true}}return {handleWatchersRoutes:l,handleSse:f,handleChannelSubscription:c}}exports.a=A;exports.b=T;//# sourceMappingURL=chunk-7ICPAABP.cjs.map
|
|
7
|
+
//# sourceMappingURL=chunk-7ICPAABP.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkGL2OHR2E_cjs=require('./chunk-GL2OHR2E.cjs');function d(a,e){return e?{...a,...e.pollIntervalMs!=null?{pollIntervalMs:e.pollIntervalMs}:{},...e.visibilityMs!=null?{visibilityMs:e.visibilityMs}:{},...e.concurrency!=null?{concurrency:e.concurrency}:{},...e.maxAttempts!=null?{maxAttempts:e.maxAttempts}:{}}:a}function p(a,e,c,s){return {id:a,async lease(o){return (await Promise.resolve(e.leaseRequests(o))).map(r=>({id:r.messageId,attempt:r.attempt,message:r.request,ack:()=>Promise.resolve(e.ackRequest(r.messageId,r.leaseToken)),nack:t=>Promise.resolve(e.nackRequest(r.messageId,r.leaseToken,t))}))},async handle(o){await c(o.args,o);},onError:s?(o,u)=>s(o,u.attempt,u.message):void 0}}function l(a,e,c,s){return {id:a,async lease(o){return (await Promise.resolve(e.lease(o))).map(r=>({id:r.id,attempt:r.attempt,message:r.body,ack:()=>Promise.resolve(e.ack(r.id,r.leaseToken)),nack:t=>Promise.resolve(e.nack(r.id,r.leaseToken,t))}))},async handle(){await c();},onError:s?(o,u)=>s(o,u.attempt):void 0}}function y(a){let e=a.logger??{info(){},warn(){},error(){}},c=a.boardAdapter,s=a.runtime.queueLaneTuning??{},o=c.processAccumulatedStore(),u=c.chatAgentStore(),r=[];if(r.push(d(l("process-accumulated",o,async()=>{let t=await a.runtime.processAccumulatedLane();if(t.status!=="success")throw new Error(t.error||`processAccumulatedLane returned ${t.status}`)},(t,n)=>{e.error(`[board-server] queued process-accumulated failed for ${a.boardId} (attempt ${n}): ${String(t&&t.message||t)}`);}),s.processAccumulated)),r.push(d(p("chat-agent",u,async(t,n)=>{await a.runtime.handleChatAgentRequest(n);},(t,n,i)=>{let m=typeof i.args?.cardId=="string"?i.args.cardId:"";e.error(`[board-server] queued chat-agent failed for ${a.boardId}${m?`/${m}`:""} (attempt ${n}): ${String(t&&t.message||t)}`);}),s.chatAgent)),a.executeTaskExecutorRequest){let t=c.boardWorkerStore();r.push(d(p("task-executor",t,a.executeTaskExecutorRequest,(n,i)=>{e.error(`[board-server] queued board-worker failed for ${a.boardId} (attempt ${i}): ${String(n&&n.message||n)}`);}),s.taskExecutor));}return chunkGL2OHR2E_cjs.a(r)}exports.a=y;//# sourceMappingURL=chunk-CPAXTVBQ.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-CPAXTVBQ.cjs.map
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
'use strict';var chunkM3OU6IS5_cjs=require('./chunk-M3OU6IS5.cjs'),chunk7FGPOGRV_cjs=require('./chunk-7FGPOGRV.cjs'),chunk7ICPAABP_cjs=require('./chunk-7ICPAABP.cjs'),chunkKAWQPLIE_cjs=require('./chunk-KAWQPLIE.cjs'),chunkNM6O35RY_cjs=require('./chunk-NM6O35RY.cjs'),chunk272IYUKT_cjs=require('./chunk-272IYUKT.cjs'),chunkNJJ7WEDT_cjs=require('./chunk-NJJ7WEDT.cjs'),chunkH5HBXPOI_cjs=require('./chunk-H5HBXPOI.cjs'),chunkOEFTOO47_cjs=require('./chunk-OEFTOO47.cjs'),chunkYMEIPKLW_cjs=require('./chunk-YMEIPKLW.cjs'),chunkGYQXDNNI_cjs=require('./chunk-GYQXDNNI.cjs');function te(S){let{apiBasePath:v,json:h,readJsonBody:Z,readRawBody:V,initBoardAndSetup:N,bootstrapBoard:$,buildPublishedRuntimePayload:K,createMcpControlplaneToolRegistry:Q,readCardFromStore:tt,patchCard:nt,retriggerCard:U,applyCardAction:ot,resolveChatHandlerTarget:it,createMcpFacade:ct,chatStorePublic:dt,uploadCardFile:m,sendCardFileDownloadResponse:C}=S;async function I(d,u,q){let x=d.method||"GET",O=q,P=O.pathname;try{if(x==="GET"&&P===`${v}/init-board`)return await N(),h(u,200,await K()),!0;if(x==="GET"&&P===`${v}/board-status`)return h(u,200,await K()),!0;if(x==="POST"&&P===`${v}/mcp-controlplane`){await $();let f=await Z(d),c=typeof f.tool=="string"?f.tool.trim():"",j=f.args&&typeof f.args=="object"&&!Array.isArray(f.args)?f.args:{};if(!c)return h(u,400,{error:"tool is required"}),!0;try{let l=await chunk272IYUKT_cjs.a(c,j,Q());if(l&&typeof l=="object"&&!Array.isArray(l)){let k=l;if(k.status==="fail")return h(u,400,{error:chunk272IYUKT_cjs.b(l,"Request failed")}),!0;if(k.status==="error")return h(u,500,{error:chunk272IYUKT_cjs.b(l,"Internal error")}),!0}h(u,200,l);}catch(l){let k=typeof l?.statusCode=="number"?Number(l.statusCode):500,L=l instanceof Error?l.message:String(l);h(u,k,{error:L});}return !0}let D=P.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/cards/([^/]+)$`));if(x==="GET"&&D){await $();let f=decodeURIComponent(D[1]),c=await tt(f);return c?(h(u,200,c),!0):(h(u,404,{error:`card not found: ${f}`}),!0)}if(x==="PATCH"&&D){await $();let f=decodeURIComponent(D[1]),c=await Z(d);return await nt(f,c),h(u,200,{ok:!0}),!0}let et=P.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/cards/([^/]+)/retrigger$`));if(x==="POST"&&et){await $();let f=decodeURIComponent(et[1]);return await U(f),h(u,200,{ok:!0}),!0}let rt=P.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/cards/([^/]+)/actions$`));if(x==="POST"&&rt){await $();let f=decodeURIComponent(rt[1]),c=Date.now(),j=new Date(c).toISOString(),l=await Z(d),k=l?.actionType;if(k==="chat-send"&&!await it(f)){let T=Date.now();return h(u,409,{error:`chat handler is not configured for card: ${f}`,requestReceivedAt:j,requestReceivedAtMs:c,responseSentAt:new Date(T).toISOString(),responseSentAtMs:T,responseStatus:409}),!0}if(k==="chat-send"){let T=l?.payload??{},W=typeof T["turn-id"]=="string"?T["turn-id"]:typeof T.turnId=="string"?T.turnId:typeof T.turn=="string"?T.turn:"";if(!W||!String(W).trim()){let ut=Date.now();return h(u,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${f}`,requestReceivedAt:j,requestReceivedAtMs:c,responseSentAt:new Date(ut).toISOString(),responseSentAtMs:ut,responseStatus:400}),!0}}await ot(f,k,l?.payload);let L=Date.now();return h(u,200,{ok:!0,requestReceivedAt:j,requestReceivedAtMs:c,responseSentAt:new Date(L).toISOString(),responseSentAtMs:L,responseStatus:200}),!0}let M=P.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/cards/([^/]+)/chats$`));if(x==="GET"&&M){await $();let f=decodeURIComponent(M[1]),c=String(O.searchParams.get("turn-id")||""),j=String(O.searchParams.get("all-turns")||"").toLowerCase()==="true",l=String(O.searchParams.get("tail-turns-before-id")||""),k=O.searchParams.get("tail-turns"),L=k==null||k===""?j||c?void 0:1:Number.parseInt(k,10),T=dt.readAll({params:{cardId:f},body:{...L===void 0?{}:{tailTurns:L},...c?{turnId:c}:{},...j?{allTurns:!0}:{},...l?{tailTurnsBeforeId:l}:{}}});if(T.status!=="success")return h(u,400,{error:T.error||"Failed to read chats"}),!0;let W=T.data.records;return h(u,200,{ok:!0,messages:W}),!0}if(x==="POST"&&M){await $();let f=decodeURIComponent(M[1]),c=await Z(d),j=typeof c?.role=="string"?c.role:"assistant",l=typeof c?.text=="string"?c.text:"",k=Array.isArray(c?.files)?c.files:[],L=typeof c?.turn=="string"?c.turn:typeof c?.["turn-id"]=="string"?c["turn-id"]:typeof c?.turnId=="string"?c.turnId:"",T=c?.done===!0,W=ct(),G=(await W.manageAddChatEntryAndAnyAttachments({cardId:f,role:j,text:l,files:k,turn:L})).data.id;return T&&W.setChatProcessing({cardId:f,active:!1}),h(u,200,{ok:!0,id:G}),!0}let X=P.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/cards/([^/]+)/files$`));if(x==="POST"&&X){await $();let f=decodeURIComponent(X[1]),c=String(O.searchParams.get("inChat")||"").toLowerCase()==="true",j=String(O.searchParams.get("turn-id")||"").trim();if(c&&!j)return h(u,400,{error:`file upload with inChat=true requires a non-empty 'turn-id' query parameter for card: ${f}`}),!0;let l=d.headers["x-file-name"],k=String(d.headers["content-type"]||"application/octet-stream"),L=Array.isArray(l)?l[0]:l,T=L?decodeURIComponent(String(L)):"upload.bin",W=await V(d);return h(u,200,await m(f,T,k,W,{inChat:c,turnId:j})),!0}let z=P.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/cards/([^/]+)/files/(\\d+)$`));if(x==="GET"&&z){let f=decodeURIComponent(z[1]),c=parseInt(z[2],10),j=O.searchParams.get("sn");return await C(u,f,c,j),!0}return !1}catch(D){let et=D?.statusCode||500;return h(u,et,{error:String(D?.message||D)}),true}}return {handleRuntimeApi:I}}var re={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},ee="chat-handler-flow-queue";function or(S){let v=String(S.apiBasePath||"/api/board").replace(/\/$/,""),h={...re,...S.corsHeaders||{}},Z=S.queueLaneTuning??{},V=S.boardId||"",N=S.logger||{info:console.log,warn:console.warn,error:console.error},$=S.invocationAdapter,K=S.chatFlowRunner||null,Q=S.chatStorage??chunkNJJ7WEDT_cjs.b(),tt=chunkGYQXDNNI_cjs.a(Q),nt=S.notificationTransport||null,U=S.serverUrl||null,ot=S.executionExtra||{},it=S.onSseClientConnected,ct=S.onSseClientDisconnected,dt=S.onChannelSubscribed,m=S.onChannelUnsubscribed,C=chunk7ICPAABP_cjs.a({chatStorage:Q,readChatRecords:t=>bt(t),onSseClientDisconnected:ct});function I(t){function e(o){if(Array.isArray(o))return o;if(o&&typeof o=="object"){let i=o;return Array.isArray(i.files)?i.files:[o]}return null}function r(o){return {async get(i){return o.get(i)},async set(i){return o.set(i)},async del(i){return o.del(i)},async patch(i){return o.patch(i)},async appendFiles(i){return o.appendFiles(i)}}}function a(o){function i(b){return {status:"success",data:b}}function g(b){return {status:"fail",error:b}}function p(b){return {status:"error",error:b instanceof Error?b.message:String(b)}}return {async get(b){try{let R=b.params?.id;if(R){let E=await o.readCard(R);return E?i({cards:[E]}):g(`card "${R}" not found`)}return i({cards:await o.readAllCards()})}catch(R){return p(R)}},async set(b){try{let R=b.body;if(R==null)return g("set requires a body (card object or array of cards)");let E=Array.isArray(R)?R:[R];for(let _ of E){if(typeof _.id!="string")return g("each card must have a string `id` field");await o.writeCard(_.id,_);}return i({count:E.length})}catch(R){return p(R)}},async del(b){try{let R=b.body?.ids??[],E=b.params?.id,_=E?[...R,E]:R;if(_.length===0)return g("del requires body.ids (string[]) or params.id");for(let st of _)await o.removeCard(st);return i({count:_.length})}catch(R){return p(R)}},async patch(b){try{let R=b.params?.id,E=b.params?.path;if(!R)return g("patch requires params.id");if(!E)return g("patch requires params.path");let _=b.body,st=_&&Object.prototype.hasOwnProperty.call(_,"value")?_.value:b.body;return await o.patchCard(R,E,st),i({count:1})}catch(R){return p(R)}},async appendFiles(b){try{let R=b.params?.id;if(!R)return g("appendFiles requires params.id");let E=await o.readCard(R);if(!E)return g(`card "${R}" not found`);let _=e(b.body);if(!_||_.length===0)return g("appendFiles requires a file metadata object, array, or body.files array");let st=E.card_data&&typeof E.card_data=="object"&&!Array.isArray(E.card_data)?E.card_data:{},Bt=Array.isArray(st.files)?st.files:[],Fe=[...Bt,..._];return await o.patchCard(R,"card_data.files",Fe),i({files_added:_.map((Oe,Te)=>({idx:Bt.length+Te,entry:Oe}))})}catch(R){return p(R)}}}}let n=chunkKAWQPLIE_cjs.a(t.boardAdapter)?chunkH5HBXPOI_cjs.j(t.baseRef,t.boardAdapter):chunkOEFTOO47_cjs.y(t.baseRef,t.boardAdapter),s=t.nonCoreAdapter??(!chunkKAWQPLIE_cjs.a(t.boardAdapter)&&x(t.boardAdapter)?t.boardAdapter:null),y=s?chunkOEFTOO47_cjs.z(t.baseRef,s):null,B,w=chunkKAWQPLIE_cjs.a(t.boardAdapter)?(()=>{let o=chunkH5HBXPOI_cjs.d(chunkH5HBXPOI_cjs.c(chunkH5HBXPOI_cjs.b(t.boardAdapter.kvStorageForRef(t.cardStoreRef)),t.boardAdapter.hashFn),N.warn),i=a(o);return B={get(g){return i.get(g)},set(g){return i.set(g)}},i})():(()=>{let o=t.boardAdapter.kvStorageForRef(t.cardStoreRef),g=chunkYMEIPKLW_cjs.a(chunkOEFTOO47_cjs.l({readIndex:()=>o.read("_index"),writeIndex:p=>o.write("_index",p),readCard:p=>o.read(p),writeCard:(p,b)=>(o.write(p,b),p),removeCard:p=>{o.delete(p);},cardExists:p=>o.read(p)!==null,defaultCardKey:p=>p},N.warn));return B=g,r(g)})(),F=t.artifactsAdapter||t.boardAdapter,A=t.filesArtifactsStore??null,H=A?{putBytes(o,i,g){A.putBytes(o,i,g);},getBytes(o){return A.getBytes(o)},listKeys(o){return A.list(o).map(i=>i.key)}}:null;if(!H&&!chunkKAWQPLIE_cjs.a(F)){let o=t.artifactsAdapter?F.blobStorage(""):F.blobStorage("files"),i=chunkNJJ7WEDT_cjs.c(o);H={putBytes(g,p,b){i.putBytes(g,p,b);},getBytes(g){return i.getBytes(g)},listKeys(g){return i.list(g).map(p=>p.key)}};}else if(!H&&chunkKAWQPLIE_cjs.a(F)){let o=t.artifactsAdapter?F.blobStorage(""):F.blobStorage("files");H={async putBytes(i,g){if(o.writeBytes){await o.writeBytes(i,g);return}let p=JSON.stringify({__kind:"bytes-array",data:[...g]});await o.write(i,p);},async getBytes(i){if(o.readBytes){let p=await o.readBytes(i);if(p!==null)return p}let g=await o.read(i);if(g===null)return null;try{let p=JSON.parse(g);if(p&&p.__kind==="bytes-array"&&Array.isArray(p.data))return new Uint8Array(p.data)}catch{}return new TextEncoder().encode(g)},async listKeys(i){return await o.listKeys(i)}};}let J={async init(o){return n.init(o)},async status(o){return n.status(o)},async getConfig(o){return n.getConfig(o)},async getAllOutputsDataObjects(o){return n.getAllOutputsDataObjects(o)},async getAllOutputsComputedValues(o){return n.getAllOutputsComputedValues(o)},async getOutputsFetchedSources(o){return n.getOutputsFetchedSources(o)},async upsertCard(o){return n.upsertCard(o)},async removeCard(o){return n.removeCard(o)},async cardRefreshedNotify(o){return n.cardRefreshedNotify(o)},async sourceDataFetched(o){return n.sourceDataFetched(o)},async sourceDataFetchFailure(o){return n.sourceDataFetchFailure(o)}};return {label:t.label,board:n,nonCore:y,publicCardStore:B,boardOps:J,cardStoreOps:w,get filesArtifacts(){return H},boardAdapter:t.boardAdapter,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,artifactsStoreRef:t.artifactsStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef,archiveStoreRef:t.archiveStoreRef,notifyRef:t.notifyRef,taskExecutorRef:t.taskExecutorRef,chatHandlerRef:t.chatHandlerRef,chatHandlerFlow:t.chatHandlerFlow,inferenceAdapterRef:t.inferenceAdapterRef,notification:chunkM3OU6IS5_cjs.a(),notificationTeardown:null,initialized:false,cardsBootstrapped:false}}let d=S.boards.map(I),u=new Map;function q(t){return u.get(t)??0}function x(t){let e=t;return typeof e.invokeExecutor=="function"&&typeof e.validateSchema=="function"}function O(t){let e=d[q(t)];return {files:e?e.filesArtifacts:null}}function P(){return chunkNJJ7WEDT_cjs.e()}function D(t){return String(t||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}async function et(t){if(!t||t.notificationTeardown||!nt||!t.notifyRef)return;let e=await nt.subscribe(t.notifyRef,r=>{chunkM3OU6IS5_cjs.c(t.notification,r);let a=r.kind==="notification-batch"?r.notifications:[r];C.broadcastNotificationBatch(a);});t.notificationTeardown=e;}async function rt(t){if(!t||t.initialized)return;let e={cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef};t.artifactsStoreRef&&(e.artifactsStoreRef=t.artifactsStoreRef),t.chatStoreRef&&(e.chatStoreRef=t.chatStoreRef),t.scratchStoreRef&&(e.scratchStoreRef=t.scratchStoreRef),t.archiveStoreRef&&(e.archiveStoreRef=t.archiveStoreRef);let r={};t.taskExecutorRef&&(r["task-executor-ref"]=t.taskExecutorRef),t.chatHandlerFlow!==void 0&&(r["chat-handler-flow"]=t.chatHandlerFlow),t.inferenceAdapterRef&&(r["inference-adapter-ref"]=t.inferenceAdapterRef);let a=await t.boardOps.init({params:e,body:r});if(a.status!=="success")throw Object.assign(new Error(a.error||`init failed for ${t.label}`),{statusCode:500});if(await et(t),!t.chatHandlerFlow&&t.chatHandlerRef&&$.describe)try{let n=await $.describe(t.chatHandlerRef);n&&n.kind!=="chat-handler"?N.warn(`[init] chat-handler describe returned kind="${n.kind}", expected "chat-handler" for ${t.label}`):n&&N.info(`[init] chat-handler validated: ${n.name} (protocol ${n.protocolVersion}) for ${t.label}`);}catch(n){N.warn(`[init] chat-handler describe failed for ${t.label}: ${n?.message||String(n)}`);}t.initialized=true;}async function M(t){if(!t.boardAdapter.publishBoardChangeNotifications)return;let e=[],r=await t.boardOps.status({});r.status==="success"&&r.data!=null&&chunkM3OU6IS5_cjs.b(r.data)&&e.push({kind:"status",status:r.data});let a=await t.boardOps.getAllOutputsDataObjects({});if(a.status==="success"&&a.data!=null)for(let[s,y]of Object.entries(a.data))s&&e.push({kind:"data_object",key:s,payload:y});let n=await t.boardOps.getAllOutputsComputedValues({});if(n.status==="success"&&n.data!=null)for(let[s,y]of Object.entries(n.data))s&&e.push({kind:"computed_values",cardId:s,values:y});e.length>0&&t.boardAdapter.publishBoardChangeNotifications(e);}async function X(t,e){if(!t||t.cardsBootstrapped)return;let r=await t.cardStoreOps.get({}),a=r.status==="success"&&Array.isArray(r.data?.cards)?r.data.cards:[];for(let n of a)typeof n.id=="string"&&(u.set(n.id,e),await t.boardOps.upsertCard({params:{cardId:n.id}}));t.cardsBootstrapped=true;}async function z(){for(let t of d)await rt(t);}async function f(){await z();for(let t=0;t<d.length;t++)await M(d[t]),await X(d[t],t),await M(d[t]);}async function c(t=false){t||await z();for(let e of d){let r=await e.board.processAccumulatedEvents({});if(r.status!=="success")return r}return {status:"success"}}async function j(){return await z(),c(true)}function l(t){return d[q(t)]??null}async function k(t){let e=l(t);if(!e)return null;let r=await e.cardStoreOps.get({params:{id:t}});if(r.status!=="success")return null;let a=Array.isArray(r.data?.cards)?r.data.cards:[];return a.length>0?a[0]:null}async function L(){let t=async r=>{if(!r)return [];let a=await r.cardStoreOps.get({});return a.status!=="success"||!Array.isArray(a.data?.cards)?[]:a.data.cards},e=[];for(let r of d)e.push(...await t(r));return e}function T(){return d[0]??null}let W=chunkM3OU6IS5_cjs.n({boardContexts:d,cardOwnerIndex:u,cardContextForCard:t=>l(t),readStatusSnapshot:()=>ie(),readDataObjectsByToken:()=>de(),readCardRuntimeArtifacts:()=>ce(),readCardFromStore:t=>k(t),readCardDefinitions:()=>L(),processAccumulatedLaneInternal:t=>c(t),reportSourceFetched:(t,e)=>St(t,{ref:e}),reportSourceFetchFailure:(t,e)=>kt(t,{reason:e}),uploadCardFile:(t,e,r,a,n)=>Rt(t,e,r,a,n),chatStorePublic:tt,serverUrl:U,apiBasePath:v}),ut=W.mcpCardStoreFacade,G=W.createMcpFacade,ne=chunkM3OU6IS5_cjs.h({boardId:V,getMcpFacade:()=>G(),getMcpCardStoreFacade:()=>ut()});function ae(t){return chunkM3OU6IS5_cjs.k(t)}function oe(){return chunkM3OU6IS5_cjs.l(G())}function se(){return chunkM3OU6IS5_cjs.m({boardId:V,uploadCardFile:Rt,getMcpFacade:()=>G(),controlplane:ne})}let lt=chunkM3OU6IS5_cjs.i({boardId:V,boardContexts:d,readCardDefinitions:()=>L(),readChatRecords:t=>bt(t),getChatProcessing:t=>G().getChatProcessing({cardId:t}).active}),ie=lt.readStatusSnapshot,ce=lt.readCardRuntimeArtifacts,de=lt.readDataObjectsByToken,gt=lt.buildPublishedRuntimePayload;async function yt(t,e,r){let a=r?.syncBoard!==false,n=r?.restartOnlyIfChanged===true,s=l(t);if(!s)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let y=await k(t);if(!y)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let B=n?JSON.stringify(y):null,w=e(y)||y;if(n&&JSON.stringify(w)===B)return;let F=await s.cardStoreOps.set({body:w});if(F.status!=="success")throw Object.assign(new Error(F.error||`Failed to persist card: ${t}`),{statusCode:500});if(a){let A=await s.boardOps.upsertCard({params:{cardId:t,restart:true}});if(A.status!=="success")throw Object.assign(new Error(A.error||`Failed to upsert card: ${t}`),{statusCode:500})}}async function ue(t,e){await yt(t,e,{syncBoard:true});}async function ht(t,e){await yt(t,e,{syncBoard:false});}async function le(t){let e=l(t);if(!e)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});if(!await k(t))throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let a=await e.boardOps.upsertCard({params:{cardId:t,restart:true}});if(a.status!=="success")throw Object.assign(new Error(a.error||`Failed to retrigger card: ${t}`),{statusCode:500})}async function fe(t,e){await yt(t,r=>{if(!e||typeof e!="object"||Object.keys(e).length===0)return r;function a(n,s,y){let B=String(s||"").split(".").filter(Boolean);if(!B.length)return;let w=n;for(let F=0;F<B.length-1;F++){let A=B[F];(!w[A]||typeof w[A]!="object")&&(w[A]={}),w=w[A];}w[B[B.length-1]]=y;}if(e.fieldValues!==void 0&&e.fieldValues!==null){let n=null,s=r.view;if(s&&Array.isArray(s.elements)){for(let y of s.elements)if(y?.data&&y.data.writeTo){n=y.data.writeTo;break}}n?a(r,n,e.fieldValues):typeof e.fieldValues=="object"&&!Array.isArray(e.fieldValues)&&(r.card_data={...r.card_data||{},...e.fieldValues});}else {if(Array.isArray(e._stagedFiles)&&e._stagedFiles.length>0)return r;for(let[n,s]of Object.entries(e))n!=="_stagedFiles"&&(s!==null&&typeof s=="object"&&!Array.isArray(s)&&r[n]!==null&&typeof r[n]=="object"&&!Array.isArray(r[n])?r[n]={...r[n],...s}:r[n]=s);}return r},{syncBoard:true,restartOnlyIfChanged:true});}function pe(t){Q.clear(t);try{G().setChatProcessing({cardId:t,active:!1});}catch{}}function me(t,e,r,a,n=""){let s=typeof r=="string"?r.trim():"";return Q.append(t,e||"system",s,a,n)}function bt(t){return Q.readAll(t)}let Rt=chunkM3OU6IS5_cjs.j({safeCardId:t=>D(t),artifactsStores:t=>O(t),cardFileMetadataStore:()=>P(),readCardFromStore:t=>k(t),updateCardLocalOnly:(t,e)=>ht(t,e),writeChatRecord:(t,e,r,a,n)=>me(t,e,r,a,n)}).uploadCardFile;async function Ct(t){let e=l(t);if(!e)return null;let r=await e.boardOps.getConfig({params:{key:"chat-handler-flow"}}),a=r.status==="success"?r.data?.value:null,n=e.chatHandlerRef;return a==null&&(!n||typeof n!="object")?null:{ctx:e,handlerFlow:a,handlerRef:n}}async function ge(t,e,r=false,a=""){let n=await Ct(t);if(!n)return;let{ctx:s,handlerFlow:y,handlerRef:B}=n;if(!r)try{G().setChatProcessing({cardId:t,active:!0});}catch{}let w={boardId:V,cardId:String(t),lastChatEntryId:e,...a?{turnId:a}:{},...ot,...U?{serverUrl:U}:{}},F=y!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:ee}}:B;try{chunkKAWQPLIE_cjs.a(s.boardAdapter)?await s.boardAdapter.chatAgentStore().enqueueRequest({boardId:V,ref:F,args:y!=null?{...w,__chatHandlerFlow:y}:w}):s.boardAdapter.chatAgentStore().enqueueRequest({boardId:V,ref:F,args:y!=null?{...w,__chatHandlerFlow:y}:w}),await Promise.resolve(s.boardAdapter.requestProcessAccumulated?.());}catch(A){try{G().setChatProcessing({cardId:t,active:!1});}catch{}N.warn(`[chat-handler] queue failed for card "${t}": ${A instanceof Error?A.message:String(A)}`);}}async function ye(t,e,r){if(e.howToRun==="built-in"&&chunkKAWQPLIE_cjs.b(e)===ee){let a=K,n=r.__chatHandlerFlow,s={...r};return delete s.__chatHandlerFlow,a?a.run(n,s,{boardId:V,cardId:String(s.cardId||""),label:t.label,logger:N,serverUrl:U,executionExtra:ot}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return $.invoke(e,r)}async function Re(t,e=false){e||await z();let r=typeof t.args?.cardId=="string"?t.args.cardId:"",a=r?l(r):T();if(!a)throw new Error(r?`Board context is unavailable for chat-agent request: ${r}`:"Board context is unavailable for chat-agent request");let n=await ye(a,t.ref,t.args);if(!n.dispatched){if(r)try{Q.setProcessing(r,!1);}catch{}throw new Error(n.error||`chat-agent dispatch failed for card "${r||"unknown"}"`)}}async function we(t,e,r){let a=e==="chat-send"?ht:ue,n;await a(t,s=>{let y=new Date().toISOString(),B=s.card_data&&typeof s.card_data=="object"?s.card_data:{};if(s.card_data=B,e==="chat-send"){let w=r&&typeof r.text=="string"?r.text.trim():"",F=r&&typeof r["turn-id"]=="string"?r["turn-id"]:r&&typeof r.turnId=="string"?r.turnId:r&&typeof r.turn=="string"?r.turn:"",A=[];if(Array.isArray(r?.files)){for(let H of r.files)if(H){if(typeof H=="string"){A.push({name:H});continue}if(typeof H=="object"){let J=H;typeof J.name=="string"&&A.push({name:J.name,size:J.size,mime_type:J.mime_type,uploaded_at:J.uploaded_at,stored_name:J.stored_name,chat:J.chat===true});}}}if(w||A.length>0){let H=tt.runBatch({cardId:t,commands:[{command:"append",role:"user",text:w,files:A,turn:F},{command:"set-processing",active:true}]});if(H.status!=="success")throw new Error(H.error);let J=H.data.results[0]?.data?.id;if(typeof J!="string"||!J)throw new Error(`chat-send did not return an append id for card ${t}`);n={cardId:t,lastEntryId:J,processingAlreadySet:true,turnId:F};try{C.broadcastCardChats(t);}catch{}}return s}if(e==="file-upload"){let w=P().normalizeIncoming(r?.files,y);return w.length>0&&P().merge(B,w),s}if(e==="action"){let w=r&&typeof r.buttonId=="string"?r.buttonId:"";if(!w)return s;B.lastAction={buttonId:w,at:y},B.lastActionText=`${w} @ ${y}`;}return s}),n&&ge(n.cardId,n.lastEntryId,n.processingAlreadySet,n.turnId??"");}function ft(t,e,r){let a=JSON.stringify(r),n=typeof Buffer<"u"?Buffer.byteLength(a):new TextEncoder().encode(a).length;t.writeHead(e,{...h,"Content-Type":"application/json; charset=utf-8","Content-Length":n}),t.end(a);}async function At(t,e,r){let a=await k(t);if(!a)throw Object.assign(new Error("Card not found"),{statusCode:404});let n=P().resolve(a.card_data,e,r);if(!n.ok&&n.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!n.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let s=n.file,y=D(t),B=O(t),w=String(s.stored_name||""),F=`${y}/${w}`,A=B.files?await B.files.getBytes(F):null;if(!A)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:s,bytes:A}}async function he(t,e,r,a){let{fileRecord:n,bytes:s}=await At(e,r,a),y=String(n.name||n.stored_name||"download.bin"),B=String(n.mime_type||"application/octet-stream");t.writeHead(200,{"Content-Type":B,"Content-Disposition":`attachment; filename="${y}"`,"Content-Length":s.length}),t.end(s);}function be(t){let e=String(t||"").toLowerCase();return e.startsWith("text/")||e.includes("json")||e.includes("xml")||e.includes("javascript")||e.includes("typescript")||e.includes("yaml")||e.includes("csv")}function Ce(t,e,r){let a=t.split(/\r?\n/);return (e==="head"?a.slice(0,r):a.slice(-r)).join(`
|
|
2
|
+
`)}async function pt(t){let e=[];for await(let a of t)e.push(a);let r=typeof Buffer<"u"?Buffer.concat(e).toString("utf-8").trim():new TextDecoder().decode(chunkKAWQPLIE_cjs.d(e)).trim();return r?JSON.parse(r):{}}async function Ae(t){let e=[];for await(let r of t)e.push(r);return typeof Buffer<"u"?Buffer.concat(e):chunkKAWQPLIE_cjs.d(e)}async function St(t,e){let r=typeof e.ref=="string"?e.ref.trim():"";if(!r)return {status:"fail",error:"board-worker success callback requires body.ref"};let a=d[0];return a?a.boardOps.sourceDataFetched({params:{token:t,ref:r}}):{status:"fail",error:"no board context"}}async function kt(t,e){let r=typeof e.reason=="string"&&e.reason.trim()?e.reason:"unknown",a=d[0];return a?a.boardOps.sourceDataFetchFailure({params:{token:t,reason:r}}):{status:"fail",error:"no board context"}}let Se=chunk7ICPAABP_cjs.b({sseHub:C,corsHeaders:h,json:ft,buildPublishedRuntimePayload:()=>gt(),onSseClientConnected:it,onChannelSubscribed:dt,onChannelUnsubscribed:m,apiBasePath:v,readJsonBody:t=>pt(t),initBoardAndSetup:()=>z(),bootstrapBoard:()=>f(),boardContexts:d,publishPersistedStateSnapshot:t=>M(t),upsertCardsFromSource:(t,e)=>X(t,e)}).handleWatchersRoutes,ke=chunk7FGPOGRV_cjs.a({apiBasePath:v,json:ft,readJsonBody:t=>pt(t),bootstrapBoard:()=>f(),createMcpFacade:()=>G(),createMcpToolRegistry:t=>ae(t),resolveCardFileDownloadPayload:(t,e,r)=>At(t,e,r),isLikelyTextMimeType:t=>be(t),sliceTextByLines:(t,e,r)=>Ce(t,e,r)}).handleAgentfaceApi,Be=chunkNM6O35RY_cjs.a({apiBasePath:v,json:ft,readJsonBody:t=>pt(t),initBoardAndSetup:()=>z(),createMcpWebhookToolRegistry:()=>oe()}).handleWebhooksApi,ve=te({apiBasePath:v,json:ft,readJsonBody:t=>pt(t),readRawBody:t=>Ae(t),initBoardAndSetup:()=>z(),bootstrapBoard:()=>f(),buildPublishedRuntimePayload:()=>gt(),createMcpControlplaneToolRegistry:()=>se(),readCardFromStore:t=>k(t),patchCard:(t,e)=>fe(t,e),retriggerCard:t=>le(t),applyCardAction:(t,e,r)=>we(t,e,r),resolveChatHandlerTarget:t=>Ct(t),createMcpFacade:()=>G(),chatStorePublic:tt,uploadCardFile:(t,e,r,a,n)=>Rt(t,e,r,a,n),sendCardFileDownloadResponse:(t,e,r,a)=>he(t,e,r,a)}).handleRuntimeApi;async function Pe(t,e,r){return !!(await ke(t,e,r)||await Be(t,e,r)||await Se(t,e,r)||await ve(t,e,r))}return {get apiBasePath(){return v},get corsHeaders(){return h},get queueLaneTuning(){return Z},handleRuntimeApi:Pe,buildPublishedRuntimePayload:gt,processAccumulatedEvents:j,processAccumulatedLane:c,handleChatAgentRequest:Re,clearChatRecords:pe,reportSourceFetched(t,e){return St(t,{ref:e})},reportSourceFetchFailure(t,e){return kt(t,{reason:e})},get cardStore(){return d[0]?.publicCardStore??{get(){return Promise.resolve({status:"fail",error:"no board context"})},set(){return Promise.resolve({status:"fail",error:"no board context"})}}}}}function sr(S){let v=String(S.apiBasePath||"/api/boards").replace(/\/$/,""),h={...re,...S.corsHeaders||{}},Z=S.serverMetaStore,V=S.boardRuntimeFactory,N=new Map,$="boards-config.json";function K(){let m=Z.getText($);if(!m)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(m)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function Q(m){Z.putText($,JSON.stringify(m,null,2));}function tt(m){let C=String(m||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return C.length>0&&C.length<=64?C:null}function nt(m){if(N.has(m))return N.get(m);let I=K().boards.find(u=>u.id===m)||{},d=V(m,I);return N.set(m,d),d}function U(m,C,I){let d=JSON.stringify(I),u=typeof Buffer<"u"?Buffer.byteLength(d):new TextEncoder().encode(d).length;m.writeHead(C,{...h,"Content-Type":"application/json; charset=utf-8","Content-Length":u}),m.end(d);}async function ot(m,C,I){let d=m.method||"GET",u=I.pathname;if(d==="GET"&&u===v)return U(C,200,{ok:true,boards:K().boards}),true;if(d==="POST"&&u===v){let q=[];for await(let M of m)q.push(M);let x=typeof Buffer<"u"?Buffer.concat(q).toString("utf-8").trim():new TextDecoder().decode(chunkKAWQPLIE_cjs.d(q)).trim(),O={};try{O=x?JSON.parse(x):{};}catch{O={};}let P=tt(O.id);if(!P)return U(C,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let D=K();if(D.boards.some(M=>M.id===P))return U(C,409,{error:`Board "${P}" is already registered`}),true;let et=typeof O.label=="string"&&O.label.trim()?O.label.trim():P,rt={id:P,label:et};for(let[M,X]of Object.entries(O))M==="id"||M==="label"||X!=null&&(rt[M]=X);return D.boards.push(rt),Q(D),U(C,200,{ok:true,board:rt}),true}return false}async function it(m,C,I){let u=I.pathname.match(new RegExp(`^${chunkKAWQPLIE_cjs.c(v)}/([^/]+)(/|$)`));if(!u)return false;let q=tt(decodeURIComponent(u[1]));return q?K().boards.some(P=>P.id===q)?!!await nt(q).handleRuntimeApi(m,C,I):(U(C,404,{error:`Board "${q}" not registered. POST ${v} with {id} to register it first.`}),true):(U(C,400,{error:"Invalid board id"}),true)}async function ct(m,C,I){return !!(await ot(m,C,I)||await it(m,C,I))}function dt(m){if(!K().boards.some(I=>I.id===m))throw Object.assign(new Error(`Board "${m}" not registered`),{statusCode:404});return {service:nt(m)}}return {get apiBasePath(){return v},get corsHeaders(){return h},handleApi:ct,requireBoardService:dt}}exports.a=te;exports.b=or;exports.c=sr;//# sourceMappingURL=chunk-DDYSXP2A.cjs.map
|
|
3
|
+
//# sourceMappingURL=chunk-DDYSXP2A.cjs.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';function k(o){if(o==null||typeof o!="object")return JSON.stringify(o);if(Array.isArray(o))return `[${o.map(k).join(",")}]`;let r=o;return `{${Object.keys(r).sort().map(u=>`${JSON.stringify(u)}:${k(r[u])}`).join(",")}}`}function _(o,r){let S=r>>>0;for(let u=0;u<o.length;u++)S^=o.charCodeAt(u),S=Math.imul(S,16777619)>>>0;return S}function K(o){let r=k(o),S=_(r,2166136261),u=_(r,3735928559),h=_(r,19088743),s=_(r,4277009102);return [S,u,h,s].map(i=>i.toString(16).padStart(8,"0")).join("")}function J(o){function r(s){return `${o}:blob:${s}`}let S=new TextEncoder;function u(s){if(typeof btoa=="function"){let i="";for(let n=0;n<s.length;n++)i+=String.fromCharCode(s[n]);return btoa(i)}return ""}function h(s){if(typeof atob=="function"){let i=atob(s),n=new Uint8Array(i.length);for(let a=0;a<i.length;a++)n[a]=i.charCodeAt(a);return n}return new Uint8Array}return {read(s){return globalThis.localStorage.getItem(r(s))},write(s,i){globalThis.localStorage.setItem(r(s),i);},exists(s){return globalThis.localStorage.getItem(r(s))!==null},remove(s){globalThis.localStorage.removeItem(r(s));},readBytes(s){let i=globalThis.localStorage.getItem(r(s));if(i===null)return null;try{let n=JSON.parse(i);if(n&&n.__kind==="bytes-b64"&&typeof n.data=="string")return h(n.data)}catch{}return S.encode(i)},writeBytes(s,i){let n=JSON.stringify({__kind:"bytes-b64",data:u(i)});globalThis.localStorage.setItem(r(s),n);},listKeys(s){let i=r(s??""),n=[];for(let a=0;a<globalThis.localStorage.length;a++){let l=globalThis.localStorage.key(a);l&&l.startsWith(i)&&n.push(l.slice(r("").length));}return n.sort()},stat(s){let i=globalThis.localStorage.getItem(r(s));if(i===null)return null;let n=S.encode(i).byteLength;try{let a=JSON.parse(i);a&&a.__kind==="bytes-b64"&&typeof a.data=="string"&&(n=h(a.data).byteLength);}catch{}return {key:s,size:n}}}}var N=":scratch-marker",C=":scratch-config",A=":scratch:",L=1440*60*1e3,O=720*60*1e3,B=200;function $(o,r){if(!o)return r;let S=o.replace(/[^A-Za-z0-9._-]/g,"_");return S.length>0?S:r}function W(o){let r=`${o}${N}`,S=`${o}${C}`,u=t=>`${o}${A}${t}`,h=t=>`${o}${A}${t}:__ts`,s=globalThis.localStorage.getItem(r)===null;if(s)try{globalThis.localStorage.setItem(r,`scratch-store
|
|
2
|
+
${new Date().toISOString()}`);}catch{}function i(){let t=globalThis.localStorage.getItem(S);if(t===null)return {};try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return {}}}function n(t){try{globalThis.localStorage.setItem(S,JSON.stringify(t));}catch{}}if(s){let t=i();typeof t["retention.lastSweepAt"]!="number"&&(t["retention.lastSweepAt"]=Date.now(),n(t));}function a(){if(globalThis.localStorage.getItem(r)===null)return;let t=i(),e=typeof t["retention.maxAgeMs"]=="number"?t["retention.maxAgeMs"]:L,c=typeof t["retention.sweepIntervalMs"]=="number"?t["retention.sweepIntervalMs"]:O;if(e<=0||c<=0)return;let g=typeof t["retention.lastSweepAt"]=="number"?t["retention.lastSweepAt"]:0,y=Date.now();if(y-g<c)return;t["retention.lastSweepAt"]=y,n(t);let f=y,m=`${o}${A}`,b=[];for(let p=0;p<globalThis.localStorage.length;p++){let w=globalThis.localStorage.key(p);w&&w.startsWith(m)&&!w.endsWith(":__ts")&&b.push(w);}for(let p of b){if(Date.now()-f>B)break;let w=globalThis.localStorage.getItem(`${p}:__ts`),I=w===null?0:Number(w);if(Number.isFinite(I)&&I>0&&y-I>e){try{globalThis.localStorage.removeItem(p);}catch{}try{globalThis.localStorage.removeItem(`${p}:__ts`);}catch{}}}}function l(t,e){let c=$(t,"scratch"),g=$(e,".json"),y=g.startsWith(".")?g:`.${g}`,f=Math.random().toString(36).slice(2,10);return `${c}-${Date.now()}-${f}${y}`}function d(t,e){globalThis.localStorage.setItem(u(t),e),globalThis.localStorage.setItem(h(t),String(Date.now()));}return {read(t){return globalThis.localStorage.getItem(u(t))},write(t,e){d(t,e);try{a();}catch{}},exists(t){return globalThis.localStorage.getItem(u(t))!==null},remove(t){try{globalThis.localStorage.removeItem(u(t));}catch{}try{globalThis.localStorage.removeItem(h(t));}catch{}},readBytes(t){let e=globalThis.localStorage.getItem(u(t));return e===null?null:new TextEncoder().encode(e)},writeBytes(t,e){let c="";for(let g=0;g<e.length;g++)c+=String.fromCharCode(e[g]);d(t,c);try{a();}catch{}},stat(t){let e=globalThis.localStorage.getItem(u(t));if(e===null)return null;let c=globalThis.localStorage.getItem(h(t)),g=c===null?null:Number(c);return {key:t,size:new TextEncoder().encode(e).byteLength,updatedAt:g!==null&&Number.isFinite(g)?new Date(g).toISOString():void 0}},listKeys(t){let e=`${o}${A}`,c=[];for(let g=0;g<globalThis.localStorage.length;g++){let y=globalThis.localStorage.key(g);if(y&&y.startsWith(e)&&!y.endsWith(":__ts")){let f=y.slice(e.length);(!t||f.startsWith(t))&&c.push(f);}}return c.sort()},getUniqueKey(t,e){return l(t,e)},create(t,e,c){let g=l(e,c);d(g,t);try{a();}catch{}return g},keyRef(t){return {kind:"local-storage-scratch",value:t,extra:{prefix:o}}},config:{get(t){return i()[t]??null},set(t,e){let c=i();e==null?delete c[t]:c[t]=e,n(c);}}}}var M=":archive-marker",R=":archive-config",T=":archive:stream:",v=":archive:blob:";function E(o){let r=o.replace(/[^A-Za-z0-9._-]/g,"_");if(!r)throw new Error("Archive segment name cannot be empty after sanitization");return r}function D(o){let r=`${o}${M}`,S=`${o}${R}`,u=n=>`${o}${T}${n}`;if(globalThis.localStorage.getItem(r)===null)try{globalThis.localStorage.setItem(r,`archive-store
|
|
3
|
+
${new Date().toISOString()}`);}catch{}function h(){let n=globalThis.localStorage.getItem(S);if(n===null)return {};try{let a=JSON.parse(n);return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}catch{return {}}}function s(n){try{globalThis.localStorage.setItem(S,JSON.stringify(n));}catch{}}function i(){if(globalThis.localStorage.getItem(r)===null)return;let n=h(),a=typeof n["retention.maxAgeMs"]=="number"?n["retention.maxAgeMs"]:0,l=typeof n["retention.sweepIntervalMs"]=="number"?n["retention.sweepIntervalMs"]:0;if(a<=0||l<=0)return;let d=typeof n["retention.lastSweepAt"]=="number"?n["retention.lastSweepAt"]:0,t=Date.now();if(t-d<l)return;n["retention.lastSweepAt"]=t,s(n);let e=`${o}${T}`;for(let c=0;c<globalThis.localStorage.length;c++){let g=globalThis.localStorage.key(c);if(!g||!g.startsWith(e))continue;let y=globalThis.localStorage.getItem(g);if(y)try{let f=JSON.parse(y),m=f.filter(b=>typeof b.__ts!="number"||t-b.__ts<=a);m.length!==f.length&&globalThis.localStorage.setItem(g,JSON.stringify(m));}catch{}}}return {stream(n){let a=E(n),l=u(a);function d(){let e=globalThis.localStorage.getItem(l);if(!e)return [];try{return JSON.parse(e)}catch{return []}}function t(e){try{globalThis.localStorage.setItem(l,JSON.stringify(e));}catch{}}return {append(e){let c={id:globalThis.crypto.randomUUID(),payload:e,__ts:Date.now()},g=d();g.push(c),t(g);try{i();}catch{}return {id:c.id,payload:c.payload}},readAll(){return d().map(e=>({id:e.id,payload:e.payload}))},readAfter(e){let c=d();if(!e){let m=c.map(b=>({id:b.id,payload:b.payload}));return {entries:m,newCursor:m.length>0?m[m.length-1].id:null}}let g=c.findIndex(m=>m.id===e),f=(g===-1?c:c.slice(g+1)).map(m=>({id:m.id,payload:m.payload}));return {entries:f,newCursor:f.length>0?f[f.length-1].id:e}},clear(){try{globalThis.localStorage.removeItem(l);}catch{}}}},blob(n){let a=E(n),l=J(`${o}${v}${a}`);return {read:d=>l.read(d),write:(d,t)=>{l.write(d,t);try{i();}catch{}},exists:d=>l.exists(d),remove:d=>l.remove(d),readBytes:l.readBytes?d=>l.readBytes(d):void 0,writeBytes:l.writeBytes?(d,t)=>{l.writeBytes(d,t);try{i();}catch{}}:void 0,listKeys:d=>l.listKeys(d),stat:l.stat?d=>l.stat(d):void 0}},listStreams(n){let a=`${o}${T}`,l=[];for(let d=0;d<globalThis.localStorage.length;d++){let t=globalThis.localStorage.key(d);if(!t||!t.startsWith(a))continue;let e=t.slice(a.length);(!n||e.startsWith(n))&&l.push(e);}return l.sort()},listBlobs(n){let a=`${o}${v}`,l=new Set;for(let d=0;d<globalThis.localStorage.length;d++){let t=globalThis.localStorage.key(d);if(!t||!t.startsWith(a))continue;let e=t.slice(a.length),c=e.indexOf(":"),g=c===-1?e:e.slice(0,c);(!n||g.startsWith(n))&&l.add(g);}return Array.from(l).sort()},config:{get(n){return h()[n]??null},set(n,a){let l=h();a==null?delete l[n]:l[n]=a,s(l);}}}}function j(o){function r(S){return `${o}:kv:${S}`}return {read(S){let u=globalThis.localStorage.getItem(r(S));if(u===null)return null;try{return JSON.parse(u)}catch{return null}},write(S,u){globalThis.localStorage.setItem(r(S),JSON.stringify(u));},delete(S){globalThis.localStorage.removeItem(r(S));},listKeys(S){let u=r(S??""),h=[];for(let s=0;s<globalThis.localStorage.length;s++){let i=globalThis.localStorage.key(s);i!==null&&i.startsWith(u)&&h.push(i.slice(r("").length));}return h}}}function H(o){function r(){let u=globalThis.localStorage.getItem(o);if(!u)return [];try{return JSON.parse(u)}catch{return []}}function S(u){globalThis.localStorage.setItem(o,JSON.stringify(u));}return {readAllEntries(){return r()},appendEntry(u){let h=r();h.push(u),S(h);},generateId(){return globalThis.crypto.randomUUID()}}}exports.a=K;exports.b=J;exports.c=W;exports.d=D;exports.e=j;exports.f=H;//# sourceMappingURL=chunk-IPLSRN6P.cjs.map
|
|
4
|
+
//# sourceMappingURL=chunk-IPLSRN6P.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a,c,d,e,b,f}from'./chunk-O7NOHKVR.js';import {a as a$1}from'./chunk-SGV7PU4H.js';import {b as b$1}from'./chunk-BQS3EIEK.js';import {a as a$2}from'./chunk-PRHQBGPT.js';function K(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function V(n){if(!n||typeof n!="object")return false;let e=n.summary;return !e||typeof e!="object"?false:Number(e.card_count||0)>0}function z(n,e){if(!e||typeof e!="object")return;let a=e;if(a.kind==="notification-batch"&&Array.isArray(a.notifications)){for(let l of a.notifications)z(n,l);return}a.kind==="status"&&V(a.status)&&(n.status=a.status),a.kind==="computed_values"&&a.cardId&&(n.computedValues[a.cardId]=a.values),a.kind==="data_object"&&a.key&&(n.dataObjects[a.key]=a.payload),a.kind==="card_refreshed"&&a.cardId&&(n.cards[a.cardId]=a.card),a.kind==="card_removed"&&a.cardId&&(delete n.cards[a.cardId],delete n.computedValues[a.cardId]);}function B(n,e){if(n?.status==="success")return Object.prototype.hasOwnProperty.call(n,"data")?n.data:void 0;throw n?.status==="fail"||n?.status==="error"?Object.assign(new Error(n.error||`${e} failed`),{statusCode:400}):Object.assign(new Error(`${e} returned an unexpected response`),{statusCode:500})}async function j(n,e){return B(await n,e)}function D(n){let e=a(n,"key");if(!e)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let a$1=e.split(".");if(!(a$1.length>=2&&a$1[0]==="chat"&&a$1.every(w=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(w))))throw Object.assign(new Error("MCP tool only supports card meta keys under chat.*"),{statusCode:400});return e}function q(n,e){let a=n.meta;for(let l of e.split(".")){if(!a||typeof a!="object"||Array.isArray(a)||!Object.prototype.hasOwnProperty.call(a,l))return {exists:false,value:null};a=a[l];}return {exists:true,value:a}}function Q(n){let{boardId:e,getMcpFacade:a$1,getMcpCardStoreFacade:l}=n;function w(p){let o=a(p,"board_id"),c=a(p,"card_id");if(!o)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!c)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(o!==e)throw Object.assign(new Error(`Unknown board_id: ${o}`),{statusCode:400});return {cardId:c}}function _(p,o){let{cardId:c}=w(p);return a$1().setChatProcessing({cardId:c,active:o}),{status:"success",data:{boardId:e,cardId:c,active:o}}}function R(p){let{cardId:o}=w(p),c=a$1().getChatProcessing({cardId:o});return {status:"success",data:{boardId:e,cardId:o,active:c.active}}}async function t(p){let{cardId:o}=w(p),c=D(p);if(!Object.prototype.hasOwnProperty.call(p,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(c.split(".").includes("__visible_controlplane_only")){let i=await j(l().get({params:{id:o}}),"cardStore.get"),g=Array.isArray(i.cards)&&i.cards.length>0&&typeof i.cards[0]=="object"&&!Array.isArray(i.cards[0])?i.cards[0]:null,h=g?q(g,"__visible_controlplane_only").value:void 0;if(p.value!==h)throw Object.assign(new Error("MCP tool cannot change the reserved meta flag __visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:e,cardId:o,key:c}}}return B(await l().patch({params:{id:o,path:`meta.${c}`},body:{value:p.value}}),"cardStore.patch"),{status:"success",data:{boardId:e,cardId:o,key:c}}}async function C(p){let{cardId:o}=w(p),c=D(p),i=await j(l().get({params:{id:o}}),"cardStore.get"),g=Array.isArray(i.cards)&&i.cards.length>0&&i.cards[0]&&typeof i.cards[0]=="object"&&!Array.isArray(i.cards[0])?i.cards[0]:null;if(!g)throw Object.assign(new Error(`Card "${o}" not found`),{statusCode:404});let h=q(g,c);return {status:"success",data:{boardId:e,cardId:o,key:c,exists:h.exists,value:h.value}}}return {requireCardArgs:w,setChatProcessing:_,getChatProcessing:R,setCardMeta:t,getCardMeta:C}}function ee(n){let{boardId:e,boardContexts:a,readCardDefinitions:l,readChatRecords:w,getChatProcessing:_}=n;async function R(){let o=(await Promise.all(a.map(async y=>{try{let u=y.boardAdapter.kvStorageForRef(y.outputsStoreRef),m=await Promise.resolve(u.read("status"));if(m!=null)return m}catch{}return y.notification.status}))).filter(Boolean);if(o.length===0)return null;if(o.length===1)return o[0];let c=[],i=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],g={};for(let y of i)g[y]=0;for(let y of o){let u=y,m=Array.isArray(u.cards)?u.cards:[];c.push(...m);for(let k of i)g[k]+=Number(u?.summary?.[k]||0);}let h=o[0];return {...h,cards:c,summary:{...h.summary||{},card_count:c.length,...g}}}async function t(){let o={},c=async i=>{try{let g=await i.boardOps.getAllOutputsComputedValues({});if(g.status==="success"&&g.data&&typeof g.data=="object"){for(let[h,y]of Object.entries(g.data)){let u=i.notification.cards[h];o[h]={schema_version:"v1",card_id:h,card_data:u?.card_data??{},computed_values:y??{}};}return}}catch{}for(let[g,h]of Object.entries(i.notification.computedValues)){let y=i.notification.cards[g];o[g]={schema_version:"v1",card_id:g,card_data:y?.card_data??{},computed_values:h??{}};}};for(let i of a)await c(i);return o}async function C(){let o={};for(let c of a){try{let i=await c.boardOps.getAllOutputsDataObjects({});if(i.status==="success"&&i.data&&typeof i.data=="object"){Object.assign(o,i.data);continue}}catch{}Object.assign(o,c.notification.dataObjects||{});}return o}async function p(){let o=await l(),c=await t(),i=await C(),g={};for(let y of o){if(!y?.id)continue;let u=y.id,m=c[u]||{},k={...m.card_data&&typeof m.card_data=="object"?m.card_data:y.card_data&&typeof y.card_data=="object"?y.card_data:{}};g[u]={schema_version:m.schema_version||"v1",card_id:m.card_id||u,card_data:k,computed_values:m.computed_values&&typeof m.computed_values=="object"?m.computed_values:{}};}let h={};for(let y of o){if(!y?.id)continue;let u=y.id;try{let m=w(u),k=_(u);(m.length>0||k)&&(h[u]={messages:m.map(v=>({role:String(v.role||"system"),text:String(v.text||""),files:Array.isArray(v.files)?v.files:[]})),receiving:!1,processing:k});}catch{}}return {boardId:e,cardDefinitions:o,statusSnapshot:await R(),dataObjectsByToken:i,cardRuntimeById:g,cardChatsByCardId:h}}return {readStatusSnapshot:R,readCardRuntimeArtifacts:t,readDataObjectsByToken:C,buildPublishedRuntimePayload:p}}function H(n){let e=String(n||"").trim();if(!e)return "upload.bin";let a=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return (a>=0?e.slice(a+1):e)||"upload.bin"}function re(n){let{safeCardId:e,artifactsStores:a,cardFileMetadataStore:l,readCardFromStore:w,updateCardLocalOnly:_,writeChatRecord:R}=n;async function t(o){let c=[];try{let i=await w(o);if(!i)return c;let g=l().read(i.card_data&&typeof i.card_data=="object"?i.card_data:null);for(let h of g)c.push(String(h.stored_name??""));}catch{}return c}async function C(o,c,i,g){let h=e(o),y=a(o),u=H(c),m=await t(o),v=`${String(m.length+1).padStart(3,"0")}-${u}`.slice(-36);return y.files&&await y.files.putBytes(`${h}/${v}`,new Uint8Array(g),i||"application/octet-stream"),{name:u,stored_name:v,size:g.length,mime_type:i||"application/octet-stream",uploaded_at:new Date().toISOString()}}async function p(o,c,i,g,h){if(!g.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let y=h?.inChat===true,u=await C(o,c,i,g),m=null;if(await _(o,k=>{let v=new Date().toISOString(),A=k.card_data&&typeof k.card_data=="object"?k.card_data:{};k.card_data=A;let s=l().normalizeIncoming([{name:u.name,stored_name:u.stored_name,size:u.size,mime_type:u.mime_type,uploaded_at:u.uploaded_at||v,chat:y}],v);return m=l().merge(A,s).findIndex(d=>d.stored_name===u.stored_name),k}),y){let k=typeof m=="number"&&m>=0?` #${m}`:"";R(o,"system",`file uploaded: ${u.name} as ${u.stored_name}${k}`,[],h?.turnId??"");}return {ok:true,file:{...u,...typeof m=="number"&&m>=0?{file_idx:m}:{},chat:y},...typeof m=="number"&&m>=0?{file_idx:m}:{}}}return {uploadCardFile:p,readCardStoredFileNames:t}}function oe(n){return {"discover.source-kinds":()=>n.discoverSourceKinds(),"inspect.board-runtime-status":()=>n.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":e=>n.inspectCardDefinitionAndRuntime({cardId:a(e,"card_id")}),"inspect.chat-messages-on-cards":e=>{let a$1=b(e,"tail_turns"),l=b(e,"tail"),w=a(e,"turn_id"),_=e.all_turns===true,R=a(e,"tail_turns_before_id");return n.inspectChatMessagesOnCards({cardId:a(e,"card_id"),...a$1!==void 0?{lastUserTurns:a$1}:{},...l!==void 0?{tail:l}:{},...w?{turnId:w}:{},..._?{allTurns:true}:{},...R?{tailTurnsBeforeId:R}:{}})},"inspect.file-contents":e=>n.inspectFileContents({cardId:a(e,"card_id"),fileIdx:Number(b(e,"file_idx"))}),"preflight.validate-candidate-card-definition":e=>n.preflightValidateCandidateCardDefinition({candidateCardContent:d(e,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":e=>n.preflightMaterializeCandidateCard({candidateCardContent:d(e,"candidate_card_content","candidate_card_content"),mockRequires:d(e,"mock_requires","mock_requires"),mockFetchedSources:d(e,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":e$1=>n.preflightProbeSingleSourceInCandidateCard({candidateCardContent:d(e$1,"candidate_card_content","candidate_card_content"),mockProjections:c(e$1,"mock_projections"),sourceIdx:e(e$1,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":e$1=>n.preflightRunSingleSourceInCandidateCard({candidateCardContent:d(e$1,"candidate_card_content","candidate_card_content"),mockProjections:c(e$1,"mock_projections"),sourceIdx:e(e$1,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":e$1=>n.preflightRunSingleSourceInLiveCard({cardId:a(e$1,"card_id"),sourceIdx:e(e$1,"source_idx","source_idx"),mockRequires:d(e$1,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":e=>n.preflightRunOneCycleWithCandidateCard({candidateCardContent:d(e,"candidate_card_content","candidate_card_content"),mockRequires:c(e,"mock_requires")}),"manage.read-card":e=>n.manageReadCard({cardId:a(e,"card_id")}),"stage-ai-response-and-any-attachments":e=>{let a$1=a(e,"turn_id");if(!a$1)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return n.manageAddChatEntryAndAnyAttachments({cardId:a(e,"card_id"),role:"assistant",...typeof e.text=="string"?{text:e.text}:{},...a$1?{turn:a$1}:{},...Array.isArray(e.files)?{files:e.files}:{}})},"manage.upsert-card":e=>n.manageUpsertCard({cardId:a(e,"card_id"),candidateCardContent:c(e,"candidate_card_content")}),"manage.remove-card":e=>n.manageRemoveCard({cardId:a(e,"card_id")})}}function se(n){return {"webhook.process-accumulated":()=>n.webhookProcessAccumulated(),"webhook.source-fetch-done":e=>n.webhookSourceFetchDone({token:a(e,"token"),ref:a(e,"ref")}),"webhook.source-fetch-failed":e=>n.webhookSourceFetchFailed({token:a(e,"token"),reason:a(e,"reason")})}}function de(n){let{boardId:e,uploadCardFile:a$1,getMcpFacade:l,controlplane:w}=n;function _(t,C){let p=a(t,"board_id");if(!p)throw Object.assign(new Error(`${C} requires board_id`),{statusCode:400});if(p!==e)throw Object.assign(new Error(`Unknown board_id: ${p}`),{statusCode:400})}function R(t,C){let{cardId:p}=w.requireCardArgs(t),o=a(t,"turn_id");return _(t,C),l().manageAddChatAttachment({cardId:p,role:a(t,"role")||"user",...o?{turn:o}:{},files:[{file_name:a(t,"file_name"),content_type:a(t,"content_type")||"application/octet-stream",...typeof t.text=="string"?{text:t.text}:{},...typeof t.base64=="string"?{base64:t.base64}:{},...Array.isArray(t.bytes)?{bytes:t.bytes}:{}}]})}return {"list-runtime-cards":t=>(_(t,"list-runtime-cards"),l().listRuntimeCards()),"getstate.is-chat-processing":t=>w.getChatProcessing(t),"setstate.chat-processing-started":t=>w.setChatProcessing(t,true),"setstate.chat-processing-done":t=>w.setChatProcessing(t,false),"getstate.card-meta":t=>w.getCardMeta(t),"setstate.card-meta":t=>w.setCardMeta(t),"manage.upload-card-file":t=>{let C=a(t,"card_id"),p=a(t,"file_name"),o=a(t,"content_type")||"application/octet-stream",c=f(t);if(_(t,"manage.upload-card-file"),!C)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!p)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!c)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return a$1(C,p,o,c,{inChat:false})},"manage.add-chat-attachment":t=>R(t,"manage.add-chat-attachment"),"manage.add-chat-attachement":t=>R(t,"manage.add-chat-attachement"),"manage.add-chat-entry-and-any-attachments":t=>{let{cardId:C}=w.requireCardArgs(t),p=a(t,"role")||"user",o=a(t,"turn_id");return _(t,"manage.add-chat-entry-and-any-attachments"),l().manageAddChatEntryAndAnyAttachments({cardId:C,role:p,...typeof t.text=="string"?{text:t.text}:{},...o?{turn:o}:{},...Array.isArray(t.files)?{files:t.files}:{}})},"manage.patch-card":t=>{let{cardId:C}=w.requireCardArgs(t);return _(t,"manage.patch-card"),l().managePatchCard({cardId:C,patch:c(t,"patch")})},"manage.upsert-card":t=>{let{cardId:C}=w.requireCardArgs(t);return _(t,"manage.upsert-card"),l().manageUpsertCard({cardId:C,candidateCardContent:c(t,"candidate_card_content")})},"manage.remove-card":t=>{let{cardId:C}=w.requireCardArgs(t);return _(t,"manage.remove-card"),l().manageRemoveCard({cardId:C})},"manage.admin-read-card":async t=>{let{cardId:C}=w.requireCardArgs(t);return {status:"success",data:{cards:await l().adminReadCard({cardId:C})}}},"manage.admin-upsert-card":t=>{let C=a(t,"board_id"),p=a(t,"card_id");if(!C)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!p)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(C!==e)throw Object.assign(new Error(`Unknown board_id: ${C}`),{statusCode:400});return l().adminUpsertCard({cardId:p,candidateCardContent:c(t,"candidate_card_content")})}}}function pe(n){let{boardContexts:e,cardOwnerIndex:a,cardContextForCard:l,readStatusSnapshot:w,readDataObjectsByToken:_,readCardRuntimeArtifacts:R,readCardFromStore:t,readCardDefinitions:C,processAccumulatedLaneInternal:p,reportSourceFetched:o,reportSourceFetchFailure:c,uploadCardFile:i,chatStorePublic:g,serverUrl:h,apiBasePath:y}=n;function u(){return e[0]??null}function m(){return {async status(){let s=await w();return s==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:s}},async getOutputsDataObject(s){let r=s?.params?.key;return r?{status:"success",data:(await _())[r]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},async getOutputsComputedValues(s){let r=s?.params?.key;return r?{status:"success",data:(await R())[r]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},async getOutputsFetchedSources(s){let r=s?.params?.key;if(!r)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let d=l(r)??u();return d?d.boardOps.getOutputsFetchedSources({params:{key:r}}):{status:"fail",error:"Board context is unavailable"}},async removeCard(s){let r=s?.params?.id;if(!r)return {status:"fail",error:"removeCard requires params.id"};let d=l(r)??u();return d?d.boardOps.removeCard({params:{id:r}}):{status:"fail",error:"Board context is unavailable"}},async cardRefreshedNotify(s){let r=s?.params?.cardId;if(!r)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let d=l(r)??u();return d?d.boardOps.cardRefreshedNotify({params:{cardId:r}}):{status:"fail",error:"Board context is unavailable"}},async upsertCard(s){let r=s?.params?.cardId;if(!r)return {status:"fail",error:"upsertCard requires params.cardId"};let d=l(r)??u();if(!d)return {status:"fail",error:"Board context is unavailable"};let b=await d.boardOps.upsertCard({params:{cardId:r,restart:s.params.restart===true}});if(b.status!=="success")return b;if(a$1(d.boardAdapter)){let x=await p(true);if(x.status!=="success")return x}return b}}}function k(){let s=()=>{let r=u();if(!r?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return r.nonCore};return {describeTaskExecutorCapabilities(r){return s().describeTaskExecutorCapabilities(r)},validateCardPreflight(r){return s().validateCardPreflight(r)},evalCardCompute(r){return s().evalCardCompute(r)},probeSourcePreflight(r){return s().probeSourcePreflight(r)},runSourcePreflight(r){return s().runSourcePreflight(r)},simulateCardCycle(r){return s().simulateCardCycle(r)}}}function v(){return {async get(s){let r=typeof s.params?.id=="string"?s.params.id:void 0;if(r){let d=await t(r);return d?{status:"success",data:{cards:[d]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:await C()}}},async set(s){let r=s.body;if(r==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let d=Array.isArray(r)?r:[r];for(let b of d){let x=b,I=typeof x.id=="string"?x.id:"";if(!I)return {status:"fail",error:"each card must have a string `id` field"};let T=a.get(I)??0,L=e[T]??u();if(!L)return {status:"fail",error:"Board context is unavailable"};let N=await L.cardStoreOps.set({body:x});if(N.status!=="success")return N;a.set(I,T);}return {status:"success",data:{count:d.length}}},async del(s){let r=[s.params?.id,...s.body?.ids??[]].filter(d=>typeof d=="string"&&!!d);if(r.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let d of r){let b=l(d)??u();if(!b)return {status:"fail",error:"Board context is unavailable"};let x=await b.cardStoreOps.del({params:{id:d}});if(x.status!=="success")return x;a.delete(d);}return {status:"success",data:{count:r.length}}},async patch(s){let r=typeof s.params?.id=="string"?s.params.id:void 0,d=typeof s.params?.path=="string"?s.params.path:void 0;if(!r||!d)return {status:"fail",error:"patch requires params.id and params.path"};let b=l(r)??u();return b?b.cardStoreOps.patch(s):{status:"fail",error:"Board context is unavailable"}},async appendFiles(s){let r=typeof s.params?.id=="string"?s.params.id:void 0;if(!r)return {status:"fail",error:"appendFiles requires params.id"};let d=l(r)??u();return d?d.cardStoreOps.appendFiles(s):{status:"fail",error:"Board context is unavailable"}}}}function A(){return a$2({board:m(),nonCore:k(),cardStore:v(),chatStore:g,processAccumulated:()=>p(true),sourceFetchDone:({token:s,ref:r})=>o(s,r),sourceFetchFailed:({token:s,reason:r})=>c(s,r),uploadCardFile({cardId:s,fileName:r,contentType:d,bytes:b}){return i(s,r,d,b,{inChat:true})},buildFileDownloadUrl({cardId:s,fileIdx:r,storedName:d}){let b=`${h||""}${y}/cards/${encodeURIComponent(s)}/files/${r}`;return d?`${b}?sn=${encodeURIComponent(d)}`:b},readFetchedSourceJsonByRef({cardId:s,ref:r}){let d=l(s)??u();if(!d||a$1(d.boardAdapter))return null;let I=d.boardAdapter.resolveBlob(b$1(r)).trim();return I?JSON.parse(I):null}})}return {mcpBoardFacade:m,mcpNonCoreFacade:k,mcpCardStoreFacade:v,createMcpFacade:A}}export{K as a,V as b,z as c,B as d,j as e,D as f,q as g,Q as h,ee as i,re as j,oe as k,se as l,de as m,pe as n};//# sourceMappingURL=chunk-J5J6BG7B.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-J5J6BG7B.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkSFVO2LB2_cjs=require('./chunk-SFVO2LB2.cjs');function p(t){return typeof t.journalStorage=="function"}function s(t){return typeof t.whatToRun=="string"?t.whatToRun.startsWith("b64:")?chunkSFVO2LB2_cjs.b(t.whatToRun).value:t.whatToRun:t.whatToRun.value}function c(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f(t){let a=t.reduce((r,u)=>r+u.length,0),o=new Uint8Array(a),n=0;for(let r of t)o.set(r,n),n+=r.length;return o}exports.a=p;exports.b=s;exports.c=c;exports.d=f;//# sourceMappingURL=chunk-KAWQPLIE.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-KAWQPLIE.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';function u(n,...r){for(let e of r)if(typeof n[e]=="string")return String(n[e]);return ""}function s(n,...r){for(let e of r)if(n[e]!==void 0)return Number(n[e])}function c(n,...r){for(let e of r){let t=n[e];if(t&&typeof t=="object"&&!Array.isArray(t))return t}return {}}function f(n,r,...e){for(let t of e){let o=n[t];if(o&&typeof o=="object"&&!Array.isArray(o))return o}throw Object.assign(new Error(`MCP tool requires ${r}`),{statusCode:400})}function d(n,r,...e){for(let t of e){let o=n[t];if(o!==void 0){let i=Number(o);if(Number.isFinite(i))return i}}throw Object.assign(new Error(`MCP tool requires ${r}`),{statusCode:400})}function g(n){if(Array.isArray(n.bytes))return new Uint8Array(n.bytes.map(r=>Math.max(0,Math.min(255,Number(r)||0))));if(typeof n.text=="string")return new TextEncoder().encode(n.text);if(typeof n.base64=="string"){let r=String(n.base64).replace(/-/g,"+").replace(/_/g,"/"),e=r+"=".repeat((4-r.length%4)%4),t=atob(e);return Uint8Array.from(t,o=>o.charCodeAt(0))}return null}exports.a=u;exports.b=s;exports.c=c;exports.d=f;exports.e=d;exports.f=g;//# sourceMappingURL=chunk-LPXVVMQT.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-LPXVVMQT.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkLPXVVMQT_cjs=require('./chunk-LPXVVMQT.cjs'),chunkKAWQPLIE_cjs=require('./chunk-KAWQPLIE.cjs'),chunkSFVO2LB2_cjs=require('./chunk-SFVO2LB2.cjs'),chunkM6STQR5F_cjs=require('./chunk-M6STQR5F.cjs');function K(){return {status:null,computedValues:{},dataObjects:{},cards:{}}}function V(n){if(!n||typeof n!="object")return false;let e=n.summary;return !e||typeof e!="object"?false:Number(e.card_count||0)>0}function z(n,e){if(!e||typeof e!="object")return;let a=e;if(a.kind==="notification-batch"&&Array.isArray(a.notifications)){for(let l of a.notifications)z(n,l);return}a.kind==="status"&&V(a.status)&&(n.status=a.status),a.kind==="computed_values"&&a.cardId&&(n.computedValues[a.cardId]=a.values),a.kind==="data_object"&&a.key&&(n.dataObjects[a.key]=a.payload),a.kind==="card_refreshed"&&a.cardId&&(n.cards[a.cardId]=a.card),a.kind==="card_removed"&&a.cardId&&(delete n.cards[a.cardId],delete n.computedValues[a.cardId]);}function B(n,e){if(n?.status==="success")return Object.prototype.hasOwnProperty.call(n,"data")?n.data:void 0;throw n?.status==="fail"||n?.status==="error"?Object.assign(new Error(n.error||`${e} failed`),{statusCode:400}):Object.assign(new Error(`${e} returned an unexpected response`),{statusCode:500})}async function j(n,e){return B(await n,e)}function D(n){let e=chunkLPXVVMQT_cjs.a(n,"key");if(!e)throw Object.assign(new Error("MCP tool requires key"),{statusCode:400});let a=e.split(".");if(!(a.length>=2&&a[0]==="chat"&&a.every(w=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(w))))throw Object.assign(new Error("MCP tool only supports card meta keys under chat.*"),{statusCode:400});return e}function q(n,e){let a=n.meta;for(let l of e.split(".")){if(!a||typeof a!="object"||Array.isArray(a)||!Object.prototype.hasOwnProperty.call(a,l))return {exists:false,value:null};a=a[l];}return {exists:true,value:a}}function Q(n){let{boardId:e,getMcpFacade:a,getMcpCardStoreFacade:l}=n;function w(p){let o=chunkLPXVVMQT_cjs.a(p,"board_id"),c=chunkLPXVVMQT_cjs.a(p,"card_id");if(!o)throw Object.assign(new Error("MCP tool requires board_id"),{statusCode:400});if(!c)throw Object.assign(new Error("MCP tool requires card_id"),{statusCode:400});if(o!==e)throw Object.assign(new Error(`Unknown board_id: ${o}`),{statusCode:400});return {cardId:c}}function _(p,o){let{cardId:c}=w(p);return a().setChatProcessing({cardId:c,active:o}),{status:"success",data:{boardId:e,cardId:c,active:o}}}function R(p){let{cardId:o}=w(p),c=a().getChatProcessing({cardId:o});return {status:"success",data:{boardId:e,cardId:o,active:c.active}}}async function t(p){let{cardId:o}=w(p),c=D(p);if(!Object.prototype.hasOwnProperty.call(p,"value"))throw Object.assign(new Error("MCP tool requires value"),{statusCode:400});if(c.split(".").includes("__visible_controlplane_only")){let i=await j(l().get({params:{id:o}}),"cardStore.get"),g=Array.isArray(i.cards)&&i.cards.length>0&&typeof i.cards[0]=="object"&&!Array.isArray(i.cards[0])?i.cards[0]:null,h=g?q(g,"__visible_controlplane_only").value:void 0;if(p.value!==h)throw Object.assign(new Error("MCP tool cannot change the reserved meta flag __visible_controlplane_only"),{statusCode:403});return {status:"success",data:{boardId:e,cardId:o,key:c}}}return B(await l().patch({params:{id:o,path:`meta.${c}`},body:{value:p.value}}),"cardStore.patch"),{status:"success",data:{boardId:e,cardId:o,key:c}}}async function C(p){let{cardId:o}=w(p),c=D(p),i=await j(l().get({params:{id:o}}),"cardStore.get"),g=Array.isArray(i.cards)&&i.cards.length>0&&i.cards[0]&&typeof i.cards[0]=="object"&&!Array.isArray(i.cards[0])?i.cards[0]:null;if(!g)throw Object.assign(new Error(`Card "${o}" not found`),{statusCode:404});let h=q(g,c);return {status:"success",data:{boardId:e,cardId:o,key:c,exists:h.exists,value:h.value}}}return {requireCardArgs:w,setChatProcessing:_,getChatProcessing:R,setCardMeta:t,getCardMeta:C}}function ee(n){let{boardId:e,boardContexts:a,readCardDefinitions:l,readChatRecords:w,getChatProcessing:_}=n;async function R(){let o=(await Promise.all(a.map(async y=>{try{let u=y.boardAdapter.kvStorageForRef(y.outputsStoreRef),m=await Promise.resolve(u.read("status"));if(m!=null)return m}catch{}return y.notification.status}))).filter(Boolean);if(o.length===0)return null;if(o.length===1)return o[0];let c=[],i=["completed","eligible","pending","blocked","unresolved","failed","in_progress","orphan_cards"],g={};for(let y of i)g[y]=0;for(let y of o){let u=y,m=Array.isArray(u.cards)?u.cards:[];c.push(...m);for(let k of i)g[k]+=Number(u?.summary?.[k]||0);}let h=o[0];return {...h,cards:c,summary:{...h.summary||{},card_count:c.length,...g}}}async function t(){let o={},c=async i=>{try{let g=await i.boardOps.getAllOutputsComputedValues({});if(g.status==="success"&&g.data&&typeof g.data=="object"){for(let[h,y]of Object.entries(g.data)){let u=i.notification.cards[h];o[h]={schema_version:"v1",card_id:h,card_data:u?.card_data??{},computed_values:y??{}};}return}}catch{}for(let[g,h]of Object.entries(i.notification.computedValues)){let y=i.notification.cards[g];o[g]={schema_version:"v1",card_id:g,card_data:y?.card_data??{},computed_values:h??{}};}};for(let i of a)await c(i);return o}async function C(){let o={};for(let c of a){try{let i=await c.boardOps.getAllOutputsDataObjects({});if(i.status==="success"&&i.data&&typeof i.data=="object"){Object.assign(o,i.data);continue}}catch{}Object.assign(o,c.notification.dataObjects||{});}return o}async function p(){let o=await l(),c=await t(),i=await C(),g={};for(let y of o){if(!y?.id)continue;let u=y.id,m=c[u]||{},k={...m.card_data&&typeof m.card_data=="object"?m.card_data:y.card_data&&typeof y.card_data=="object"?y.card_data:{}};g[u]={schema_version:m.schema_version||"v1",card_id:m.card_id||u,card_data:k,computed_values:m.computed_values&&typeof m.computed_values=="object"?m.computed_values:{}};}let h={};for(let y of o){if(!y?.id)continue;let u=y.id;try{let m=w(u),k=_(u);(m.length>0||k)&&(h[u]={messages:m.map(v=>({role:String(v.role||"system"),text:String(v.text||""),files:Array.isArray(v.files)?v.files:[]})),receiving:!1,processing:k});}catch{}}return {boardId:e,cardDefinitions:o,statusSnapshot:await R(),dataObjectsByToken:i,cardRuntimeById:g,cardChatsByCardId:h}}return {readStatusSnapshot:R,readCardRuntimeArtifacts:t,readDataObjectsByToken:C,buildPublishedRuntimePayload:p}}function H(n){let e=String(n||"").trim();if(!e)return "upload.bin";let a=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return (a>=0?e.slice(a+1):e)||"upload.bin"}function re(n){let{safeCardId:e,artifactsStores:a,cardFileMetadataStore:l,readCardFromStore:w,updateCardLocalOnly:_,writeChatRecord:R}=n;async function t(o){let c=[];try{let i=await w(o);if(!i)return c;let g=l().read(i.card_data&&typeof i.card_data=="object"?i.card_data:null);for(let h of g)c.push(String(h.stored_name??""));}catch{}return c}async function C(o,c,i,g){let h=e(o),y=a(o),u=H(c),m=await t(o),v=`${String(m.length+1).padStart(3,"0")}-${u}`.slice(-36);return y.files&&await y.files.putBytes(`${h}/${v}`,new Uint8Array(g),i||"application/octet-stream"),{name:u,stored_name:v,size:g.length,mime_type:i||"application/octet-stream",uploaded_at:new Date().toISOString()}}async function p(o,c,i,g,h){if(!g.length)throw Object.assign(new Error("Empty upload body"),{statusCode:400});let y=h?.inChat===true,u=await C(o,c,i,g),m=null;if(await _(o,k=>{let v=new Date().toISOString(),A=k.card_data&&typeof k.card_data=="object"?k.card_data:{};k.card_data=A;let s=l().normalizeIncoming([{name:u.name,stored_name:u.stored_name,size:u.size,mime_type:u.mime_type,uploaded_at:u.uploaded_at||v,chat:y}],v);return m=l().merge(A,s).findIndex(d=>d.stored_name===u.stored_name),k}),y){let k=typeof m=="number"&&m>=0?` #${m}`:"";R(o,"system",`file uploaded: ${u.name} as ${u.stored_name}${k}`,[],h?.turnId??"");}return {ok:true,file:{...u,...typeof m=="number"&&m>=0?{file_idx:m}:{},chat:y},...typeof m=="number"&&m>=0?{file_idx:m}:{}}}return {uploadCardFile:p,readCardStoredFileNames:t}}function oe(n){return {"discover.source-kinds":()=>n.discoverSourceKinds(),"inspect.board-runtime-status":()=>n.inspectBoardRuntimeStatus(),"inspect.card-definition-and-runtime":e=>n.inspectCardDefinitionAndRuntime({cardId:chunkLPXVVMQT_cjs.a(e,"card_id")}),"inspect.chat-messages-on-cards":e=>{let a=chunkLPXVVMQT_cjs.b(e,"tail_turns"),l=chunkLPXVVMQT_cjs.b(e,"tail"),w=chunkLPXVVMQT_cjs.a(e,"turn_id"),_=e.all_turns===true,R=chunkLPXVVMQT_cjs.a(e,"tail_turns_before_id");return n.inspectChatMessagesOnCards({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),...a!==void 0?{lastUserTurns:a}:{},...l!==void 0?{tail:l}:{},...w?{turnId:w}:{},..._?{allTurns:true}:{},...R?{tailTurnsBeforeId:R}:{}})},"inspect.file-contents":e=>n.inspectFileContents({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),fileIdx:Number(chunkLPXVVMQT_cjs.b(e,"file_idx"))}),"preflight.validate-candidate-card-definition":e=>n.preflightValidateCandidateCardDefinition({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content")}),"preflight.materialize-candidate-card":e=>n.preflightMaterializeCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content"),mockRequires:chunkLPXVVMQT_cjs.d(e,"mock_requires","mock_requires"),mockFetchedSources:chunkLPXVVMQT_cjs.d(e,"mock_fetched_sources","mock_fetched_sources")}),"preflight.probe-single-source-in-candidate-card":e=>n.preflightProbeSingleSourceInCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content"),mockProjections:chunkLPXVVMQT_cjs.c(e,"mock_projections"),sourceIdx:chunkLPXVVMQT_cjs.e(e,"source_idx","source_idx")}),"preflight.run-single-source-in-candidate-card":e=>n.preflightRunSingleSourceInCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content"),mockProjections:chunkLPXVVMQT_cjs.c(e,"mock_projections"),sourceIdx:chunkLPXVVMQT_cjs.e(e,"source_idx","source_idx")}),"preflight.run-single-source-in-live-card":e=>n.preflightRunSingleSourceInLiveCard({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),sourceIdx:chunkLPXVVMQT_cjs.e(e,"source_idx","source_idx"),mockRequires:chunkLPXVVMQT_cjs.d(e,"mock_requires","mock_requires")}),"preflight.run-one-cycle-with-candidate-card":e=>n.preflightRunOneCycleWithCandidateCard({candidateCardContent:chunkLPXVVMQT_cjs.d(e,"candidate_card_content","candidate_card_content"),mockRequires:chunkLPXVVMQT_cjs.c(e,"mock_requires")}),"manage.read-card":e=>n.manageReadCard({cardId:chunkLPXVVMQT_cjs.a(e,"card_id")}),"stage-ai-response-and-any-attachments":e=>{let a=chunkLPXVVMQT_cjs.a(e,"turn_id");if(!a)throw Object.assign(new Error("stage-ai-response-and-any-attachments requires a non-empty turn_id"),{statusCode:400});return n.manageAddChatEntryAndAnyAttachments({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),role:"assistant",...typeof e.text=="string"?{text:e.text}:{},...a?{turn:a}:{},...Array.isArray(e.files)?{files:e.files}:{}})},"manage.upsert-card":e=>n.manageUpsertCard({cardId:chunkLPXVVMQT_cjs.a(e,"card_id"),candidateCardContent:chunkLPXVVMQT_cjs.c(e,"candidate_card_content")}),"manage.remove-card":e=>n.manageRemoveCard({cardId:chunkLPXVVMQT_cjs.a(e,"card_id")})}}function se(n){return {"webhook.process-accumulated":()=>n.webhookProcessAccumulated(),"webhook.source-fetch-done":e=>n.webhookSourceFetchDone({token:chunkLPXVVMQT_cjs.a(e,"token"),ref:chunkLPXVVMQT_cjs.a(e,"ref")}),"webhook.source-fetch-failed":e=>n.webhookSourceFetchFailed({token:chunkLPXVVMQT_cjs.a(e,"token"),reason:chunkLPXVVMQT_cjs.a(e,"reason")})}}function de(n){let{boardId:e,uploadCardFile:a,getMcpFacade:l,controlplane:w}=n;function _(t,C){let p=chunkLPXVVMQT_cjs.a(t,"board_id");if(!p)throw Object.assign(new Error(`${C} requires board_id`),{statusCode:400});if(p!==e)throw Object.assign(new Error(`Unknown board_id: ${p}`),{statusCode:400})}function R(t,C){let{cardId:p}=w.requireCardArgs(t),o=chunkLPXVVMQT_cjs.a(t,"turn_id");return _(t,C),l().manageAddChatAttachment({cardId:p,role:chunkLPXVVMQT_cjs.a(t,"role")||"user",...o?{turn:o}:{},files:[{file_name:chunkLPXVVMQT_cjs.a(t,"file_name"),content_type:chunkLPXVVMQT_cjs.a(t,"content_type")||"application/octet-stream",...typeof t.text=="string"?{text:t.text}:{},...typeof t.base64=="string"?{base64:t.base64}:{},...Array.isArray(t.bytes)?{bytes:t.bytes}:{}}]})}return {"list-runtime-cards":t=>(_(t,"list-runtime-cards"),l().listRuntimeCards()),"getstate.is-chat-processing":t=>w.getChatProcessing(t),"setstate.chat-processing-started":t=>w.setChatProcessing(t,true),"setstate.chat-processing-done":t=>w.setChatProcessing(t,false),"getstate.card-meta":t=>w.getCardMeta(t),"setstate.card-meta":t=>w.setCardMeta(t),"manage.upload-card-file":t=>{let C=chunkLPXVVMQT_cjs.a(t,"card_id"),p=chunkLPXVVMQT_cjs.a(t,"file_name"),o=chunkLPXVVMQT_cjs.a(t,"content_type")||"application/octet-stream",c=chunkLPXVVMQT_cjs.f(t);if(_(t,"manage.upload-card-file"),!C)throw Object.assign(new Error("manage.upload-card-file requires card_id"),{statusCode:400});if(!p)throw Object.assign(new Error("manage.upload-card-file requires file_name"),{statusCode:400});if(!c)throw Object.assign(new Error("manage.upload-card-file requires args.bytes, args.text, or args.base64"),{statusCode:400});return a(C,p,o,c,{inChat:false})},"manage.add-chat-attachment":t=>R(t,"manage.add-chat-attachment"),"manage.add-chat-attachement":t=>R(t,"manage.add-chat-attachement"),"manage.add-chat-entry-and-any-attachments":t=>{let{cardId:C}=w.requireCardArgs(t),p=chunkLPXVVMQT_cjs.a(t,"role")||"user",o=chunkLPXVVMQT_cjs.a(t,"turn_id");return _(t,"manage.add-chat-entry-and-any-attachments"),l().manageAddChatEntryAndAnyAttachments({cardId:C,role:p,...typeof t.text=="string"?{text:t.text}:{},...o?{turn:o}:{},...Array.isArray(t.files)?{files:t.files}:{}})},"manage.patch-card":t=>{let{cardId:C}=w.requireCardArgs(t);return _(t,"manage.patch-card"),l().managePatchCard({cardId:C,patch:chunkLPXVVMQT_cjs.c(t,"patch")})},"manage.upsert-card":t=>{let{cardId:C}=w.requireCardArgs(t);return _(t,"manage.upsert-card"),l().manageUpsertCard({cardId:C,candidateCardContent:chunkLPXVVMQT_cjs.c(t,"candidate_card_content")})},"manage.remove-card":t=>{let{cardId:C}=w.requireCardArgs(t);return _(t,"manage.remove-card"),l().manageRemoveCard({cardId:C})},"manage.admin-read-card":async t=>{let{cardId:C}=w.requireCardArgs(t);return {status:"success",data:{cards:await l().adminReadCard({cardId:C})}}},"manage.admin-upsert-card":t=>{let C=chunkLPXVVMQT_cjs.a(t,"board_id"),p=chunkLPXVVMQT_cjs.a(t,"card_id");if(!C)throw Object.assign(new Error("manage.admin-upsert-card requires board_id"),{statusCode:400});if(!p)throw Object.assign(new Error("manage.admin-upsert-card requires card_id"),{statusCode:400});if(C!==e)throw Object.assign(new Error(`Unknown board_id: ${C}`),{statusCode:400});return l().adminUpsertCard({cardId:p,candidateCardContent:chunkLPXVVMQT_cjs.c(t,"candidate_card_content")})}}}function pe(n){let{boardContexts:e,cardOwnerIndex:a,cardContextForCard:l,readStatusSnapshot:w,readDataObjectsByToken:_,readCardRuntimeArtifacts:R,readCardFromStore:t,readCardDefinitions:C,processAccumulatedLaneInternal:p,reportSourceFetched:o,reportSourceFetchFailure:c,uploadCardFile:i,chatStorePublic:g,serverUrl:h,apiBasePath:y}=n;function u(){return e[0]??null}function m(){return {async status(){let s=await w();return s==null?{status:"fail",error:"Board status is unavailable"}:{status:"success",data:s}},async getOutputsDataObject(s){let r=s?.params?.key;return r?{status:"success",data:(await _())[r]}:{status:"fail",error:"getOutputsDataObject requires params.key"}},async getOutputsComputedValues(s){let r=s?.params?.key;return r?{status:"success",data:(await R())[r]?.computed_values}:{status:"fail",error:"getOutputsComputedValues requires params.key"}},async getOutputsFetchedSources(s){let r=s?.params?.key;if(!r)return {status:"fail",error:"getOutputsFetchedSources requires params.key"};let d=l(r)??u();return d?d.boardOps.getOutputsFetchedSources({params:{key:r}}):{status:"fail",error:"Board context is unavailable"}},async removeCard(s){let r=s?.params?.id;if(!r)return {status:"fail",error:"removeCard requires params.id"};let d=l(r)??u();return d?d.boardOps.removeCard({params:{id:r}}):{status:"fail",error:"Board context is unavailable"}},async cardRefreshedNotify(s){let r=s?.params?.cardId;if(!r)return {status:"fail",error:"cardRefreshedNotify requires params.cardId"};let d=l(r)??u();return d?d.boardOps.cardRefreshedNotify({params:{cardId:r}}):{status:"fail",error:"Board context is unavailable"}},async upsertCard(s){let r=s?.params?.cardId;if(!r)return {status:"fail",error:"upsertCard requires params.cardId"};let d=l(r)??u();if(!d)return {status:"fail",error:"Board context is unavailable"};let b=await d.boardOps.upsertCard({params:{cardId:r,restart:s.params.restart===true}});if(b.status!=="success")return b;if(chunkKAWQPLIE_cjs.a(d.boardAdapter)){let x=await p(true);if(x.status!=="success")return x}return b}}}function k(){let s=()=>{let r=u();if(!r?.nonCore)throw new Error("Board non-core adapter is not configured for MCP preflight/discovery tools");return r.nonCore};return {describeTaskExecutorCapabilities(r){return s().describeTaskExecutorCapabilities(r)},validateCardPreflight(r){return s().validateCardPreflight(r)},evalCardCompute(r){return s().evalCardCompute(r)},probeSourcePreflight(r){return s().probeSourcePreflight(r)},runSourcePreflight(r){return s().runSourcePreflight(r)},simulateCardCycle(r){return s().simulateCardCycle(r)}}}function v(){return {async get(s){let r=typeof s.params?.id=="string"?s.params.id:void 0;if(r){let d=await t(r);return d?{status:"success",data:{cards:[d]}}:{status:"success",data:{cards:[]}}}return {status:"success",data:{cards:await C()}}},async set(s){let r=s.body;if(r==null)return {status:"fail",error:"set requires a body (card object or array of cards)"};let d=Array.isArray(r)?r:[r];for(let b of d){let x=b,I=typeof x.id=="string"?x.id:"";if(!I)return {status:"fail",error:"each card must have a string `id` field"};let T=a.get(I)??0,L=e[T]??u();if(!L)return {status:"fail",error:"Board context is unavailable"};let N=await L.cardStoreOps.set({body:x});if(N.status!=="success")return N;a.set(I,T);}return {status:"success",data:{count:d.length}}},async del(s){let r=[s.params?.id,...s.body?.ids??[]].filter(d=>typeof d=="string"&&!!d);if(r.length===0)return {status:"fail",error:"del requires body.ids (string[]) or params.id"};for(let d of r){let b=l(d)??u();if(!b)return {status:"fail",error:"Board context is unavailable"};let x=await b.cardStoreOps.del({params:{id:d}});if(x.status!=="success")return x;a.delete(d);}return {status:"success",data:{count:r.length}}},async patch(s){let r=typeof s.params?.id=="string"?s.params.id:void 0,d=typeof s.params?.path=="string"?s.params.path:void 0;if(!r||!d)return {status:"fail",error:"patch requires params.id and params.path"};let b=l(r)??u();return b?b.cardStoreOps.patch(s):{status:"fail",error:"Board context is unavailable"}},async appendFiles(s){let r=typeof s.params?.id=="string"?s.params.id:void 0;if(!r)return {status:"fail",error:"appendFiles requires params.id"};let d=l(r)??u();return d?d.cardStoreOps.appendFiles(s):{status:"fail",error:"Board context is unavailable"}}}}function A(){return chunkM6STQR5F_cjs.a({board:m(),nonCore:k(),cardStore:v(),chatStore:g,processAccumulated:()=>p(true),sourceFetchDone:({token:s,ref:r})=>o(s,r),sourceFetchFailed:({token:s,reason:r})=>c(s,r),uploadCardFile({cardId:s,fileName:r,contentType:d,bytes:b}){return i(s,r,d,b,{inChat:true})},buildFileDownloadUrl({cardId:s,fileIdx:r,storedName:d}){let b=`${h||""}${y}/cards/${encodeURIComponent(s)}/files/${r}`;return d?`${b}?sn=${encodeURIComponent(d)}`:b},readFetchedSourceJsonByRef({cardId:s,ref:r}){let d=l(s)??u();if(!d||chunkKAWQPLIE_cjs.a(d.boardAdapter))return null;let I=d.boardAdapter.resolveBlob(chunkSFVO2LB2_cjs.b(r)).trim();return I?JSON.parse(I):null}})}return {mcpBoardFacade:m,mcpNonCoreFacade:k,mcpCardStoreFacade:v,createMcpFacade:A}}exports.a=K;exports.b=V;exports.c=z;exports.d=B;exports.e=j;exports.f=D;exports.g=q;exports.h=Q;exports.i=ee;exports.j=re;exports.k=oe;exports.l=se;exports.m=de;exports.n=pe;//# sourceMappingURL=chunk-M3OU6IS5.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-M3OU6IS5.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkIXZG74EW_cjs=require('./chunk-IXZG74EW.cjs');function A(s,i){if(s?.status==="success")return Object.prototype.hasOwnProperty.call(s,"data")?s.data:void 0;throw s?.status==="fail"||s?.status==="error"?new Error(s.error||`${i} failed`):new Error(`${i} returned an unexpected response`)}function H(s,i){if(s?.status==="success"&&Object.prototype.hasOwnProperty.call(s,"data"))return s.data;throw s?.status==="success"?new Error(`${i} returned success without data`):s?.status==="fail"||s?.status==="error"?new Error(s.error||`${i} failed`):new Error(`${i} returned an unexpected response`)}function a(s){return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}function y(s){return Array.isArray(s)?s:[]}function N(s,i){if(typeof i!="string"||i.length===0)return;let c=s,u=i;u.startsWith("fetched_sources.")&&(c=a(s).fetched_sources,u=u.slice(16));for(let p of u.split(".")){if(c==null||typeof c!="object")return;c=c[p];}return c}function V(s,i){let c=a(s.view),u=y(c.elements);return {layout:c.layout,features:c.features,elements:u.map((p,k)=>{let R=a(p),b=a(R.data),h=typeof R.visible=="string"?!!N(i,R.visible):true,U=typeof b.bind=="string"?b.bind:void 0,S=typeof b.maxRows=="number"?b.maxRows:void 0,B=U?N(i,U):void 0,F={id:typeof R.id=="string"&&R.id?R.id:`element-${k}`,kind:R.kind,label:R.label,visible:h};return B!==void 0&&(F.resolved=Array.isArray(B)&&typeof S=="number"?B.slice(0,S):B),F})}}function G(s,i){let c=typeof s.id=="string"&&s.id?s.id:"card",u=y(s.provides),p=u.length>0?u:[{bindTo:c,ref:"card_data"}],k={};for(let R of p){let b=a(R),h=typeof b.bindTo=="string"?b.bindTo:"",U=typeof b.ref=="string"?b.ref:"";if(!h||!U)continue;let S=N(i,U);S!==void 0&&(k[h]=S);}return k}function be(s){if(typeof s!="string"||!s.trim())return null;let i=/^(file uploaded|AI generated|AI geneterated):\s*.*?#(\d+)\s*$/i.exec(s.trim());if(!i)return null;let c=Number.parseInt(i[2],10);return !Number.isInteger(c)||c<0?null:c}function he(s){return {"card-content":s}}function E(s){let{meta:i,...c}=s;return c}function ke(s,i){return Object.prototype.hasOwnProperty.call(s,i)}function Re(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}function ve(s,i){let c=Re(s);if(!i||Object.keys(i).length===0)return c;function u(p,k,R){let b=String(k||"").split(".").filter(Boolean);if(!b.length)return;let h=p;for(let U=0;U<b.length-1;U+=1){let S=b[U];(!h[S]||typeof h[S]!="object")&&(h[S]={}),h=h[S];}h[b[b.length-1]]=R;}if(i.fieldValues!==void 0&&i.fieldValues!==null){let p=null,k=a(c.view),R=y(k.elements);for(let b of R){let h=a(a(b).data);if(typeof h.writeTo=="string"&&h.writeTo){p=h.writeTo;break}}return p?u(c,p,i.fieldValues):typeof i.fieldValues=="object"&&!Array.isArray(i.fieldValues)&&(c.card_data={...a(c.card_data),...i.fieldValues}),c}if(Array.isArray(i._stagedFiles)&&i._stagedFiles.length>0)return c;for(let[p,k]of Object.entries(i))p!=="_stagedFiles"&&(k!==null&&typeof k=="object"&&!Array.isArray(k)&&c[p]!==null&&typeof c[p]=="object"&&!Array.isArray(c[p])?c[p]={...c[p],...k}:c[p]=k);return c}function Q(s){return a(s.meta).__visible_controlplane_only===true}async function T(s,i){let c=await M(s.get({params:{id:i}}),"cardStore.get"),u=Array.isArray(c?.cards)?c.cards:[];if(u.length===0)throw new Error(`Card "${i}" not found`);return u[0]}function Ae(s){let{board:i,nonCore:c,cardStore:u,chatStore:p,processAccumulated:k,sourceFetchDone:R,sourceFetchFailed:b,uploadCardFile:h,buildFileDownloadUrl:U,readFetchedSourceJsonByRef:S}=s;function B(e,r){if(typeof e=="function")return e;throw new Error(`${r} is not configured for this MCP facade`)}async function F(){let e=await M(u.get({}),"cardStore.get");return Array.isArray(e.cards)?e.cards.map(r=>a(r)):[]}function X(e){if(Array.isArray(e.bytes))return new Uint8Array(e.bytes.map(r=>Math.max(0,Math.min(255,Number(r)||0))));if(typeof e.text=="string")return new TextEncoder().encode(e.text);if(typeof e.base64=="string"){let r=String(e.base64).replace(/-/g,"+").replace(/_/g,"/"),t=r+"=".repeat((4-r.length%4)%4),n=atob(t);return Uint8Array.from(n,o=>o.charCodeAt(0))}throw new Error("file entry requires bytes, text, or base64")}async function Y(){let e=a(await M(c.describeTaskExecutorCapabilities({}),"describeTaskExecutorCapabilities"));return {version:e.version,commonSourceFields:a(e.commonSourceDefFields),sourceKinds:a(e.sourceKinds)}}async function Z(){let e=a(await M(i.status({}),"status")),r=a(e.summary),t=y(e.cards);return {meta:a(e.meta),summary:{card_count:typeof r.card_count=="number"?r.card_count:0,completed:typeof r.completed=="number"?r.completed:0,eligible:typeof r.eligible=="number"?r.eligible:0,pending:typeof r.pending=="number"?r.pending:0,blocked:typeof r.blocked=="number"?r.blocked:0,in_progress:typeof r.in_progress=="number"?r.in_progress:0,failed:typeof r.failed=="number"?r.failed:0,unresolved:typeof r.unresolved=="number"?r.unresolved:0},cards:t.map(n=>{let o=a(n);return {"card-id":typeof o.name=="string"?o.name:null,status:o.status??null,error:o.error??null,requires:y(o.requires),requires_satisfied:y(o.requires_satisfied),requires_missing:y(o.requires_missing),provides_declared:y(o.provides_declared),provides_runtime:y(o.provides_runtime)}})}}async function ee(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("inspectCardDefinitionAndRuntime requires cardId");let t=a(await M(i.status({}),"status")),o=y(t.cards).map(a).find(m=>m.name===r);if(!o)throw new Error(`card "${r}" not found in board status`);let d=a(await T(u,r));if(Q(d))throw Object.assign(new Error(`card "${r}" not found`),{statusCode:404});let f=E(d),g=y(o.requires_satisfied).filter(m=>typeof m=="string"&&!!m),_=y(o.provides_runtime).filter(m=>typeof m=="string"&&!!m),v=Object.fromEntries(await Promise.all(g.map(async m=>[m,await M(i.getOutputsDataObject({params:{key:m}}),`getOutputsDataObject(${m})`)]))),I=Object.fromEntries(await Promise.all(_.map(async m=>[m,await M(i.getOutputsDataObject({params:{key:m}}),`getOutputsDataObject(${m})`)]))),w=a(await M(i.getOutputsComputedValues({params:{key:r}}),"getOutputsComputedValues")),l=await M(i.getOutputsFetchedSources({params:{key:r}}),"getOutputsFetchedSources"),P=y(d.source_defs).map(a),C={};for(let m of P)typeof m.bindTo=="string"&&typeof m.outputFile=="string"&&(C[m.outputFile]=m.bindTo);let x={};for(let[m,O]of Object.entries(l)){let q=C[m]??m;if(!S||typeof O!="string"){x[q]=null;continue}try{x[q]=S({cardId:r,ref:O});}catch{x[q]=null;}}let L={card_data:a(d.card_data),requires:v,fetched_sources:x,computed_values:w};return {cardId:r,card_status_in_board:o,card_definition_and_static_data:f,refs_for_fetched_source_files:l,runtime_data:{requires:v,provides:I,computed_values:w,rendered_view:V(d,L)}}}async function re(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("inspectChatMessagesOnCards requires cardId");let t=typeof e.turnId=="string"?e.turnId:"",n=e.allTurns===true,o=typeof e.tailTurnsBeforeId=="string"?e.tailTurnsBeforeId:"",d=n?void 0:e.lastUserTurns??(t?void 0:1),f=e.tail,g={...d===void 0?{}:{tailTurns:d},...t?{turnId:t}:{},...n?{allTurns:true}:{},...o?{tailTurnsBeforeId:o}:{}},_=Object.keys(g).length>0?{params:{cardId:r},body:g}:{params:{cardId:r}},v=A(p.readAll(_),"chatStore.readAll"),I=a(await T(u,r)),w=y(a(I.card_data).files).map((C,x)=>({idx:x,stored_name:a(C).stored_name})).filter(C=>typeof C.stored_name=="string"&&C.stored_name.length>0),P=(Array.isArray(v.records)?v.records:[]).map(C=>{let L=a(C.payload),m={...C},O=typeof C?.role=="string"?C.role:typeof L.role=="string"?String(L.role):"",q=typeof C?.text=="string"?C.text:typeof L.text=="string"?String(L.text):"";if(O==="system"){let $=be(q);if($!==null&&w.some(j=>j.idx===$)){let j=`Retrieve using inspect-file-contents --card-id ${r} --file-idx ${$}`;m.retrieval_hint=j,Object.keys(L).length>0&&typeof C.role!="string"&&(m.payload={...L,retrieval_hint:j});}}return m});return {cardId:r,messages:typeof f=="number"&&f>=0?P.slice(-f):P}}async function te(e){let r=String(e.cardId||"").trim(),t=Number(e.fileIdx);if(!r)throw new Error("inspectFileContents requires cardId");if(!Number.isInteger(t)||t<0)throw new Error("inspectFileContents requires fileIdx to be a non-negative integer");let n=a(await T(u,r)),o=y(a(n.card_data).files).map(a);if(t>=o.length)throw new Error(`attachment index ${t} is out of range for card "${r}"`);let d=o[t],f=typeof d.stored_name=="string"?d.stored_name:null;return {cardId:r,fileIdx:t,downloadUrl:U({cardId:r,fileIdx:t,storedName:f}),...typeof d.name=="string"?{name:d.name}:{},...typeof d.stored_name=="string"?{stored_name:d.stored_name}:{},...typeof d.mime_type=="string"?{mime_type:d.mime_type}:{},...typeof d.size=="number"?{size:d.size}:{},...typeof d.uploaded_at=="string"?{uploaded_at:d.uploaded_at}:{}}}async function D(e){return await c.validateCardPreflight({body:he(e.candidateCardContent)})}function ne(e){if(!e.mockRequires||typeof e.mockRequires!="object"||Array.isArray(e.mockRequires))throw new Error("preflightMaterializeCandidateCard requires mockRequires");if(!e.mockFetchedSources||typeof e.mockFetchedSources!="object"||Array.isArray(e.mockFetchedSources))throw new Error("preflightMaterializeCandidateCard requires mockFetchedSources");let r=c.evalCardCompute({body:{"card-content":e.candidateCardContent,"mock-requires":e.mockRequires,"mock-fetched-sources":e.mockFetchedSources}});if(r.status!=="success")return r;let t=a(H(r,"evalCardCompute")),n=a(e.candidateCardContent),o={card_data:a(n.card_data),requires:a(e.mockRequires),fetched_sources:a(e.mockFetchedSources),computed_values:a(t.computed_values)};return {status:"success",data:{cardId:typeof t.cardId=="string"?t.cardId:typeof n.id=="string"?n.id:"(unknown)",ok:t.ok===true,computed_values:a(t.computed_values),errors:y(t.errors).map(d=>{let f=a(d);return {bindTo:typeof f.bindTo=="string"?f.bindTo:"",error:typeof f.error=="string"?f.error:""}}),provides_outputs:G(n,o),rendered_view:V(n,o)}}}async function ae(e){return await c.probeSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":e.candidateCardContent,"mock-projections":e.mockProjections}})}async function oe(e){return await c.runSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":e.candidateCardContent,"mock-projections":e.mockProjections}})}async function se(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("preflightRunSingleSourceInLiveCard requires cardId");if(!e.mockRequires||typeof e.mockRequires!="object"||Array.isArray(e.mockRequires))throw new Error("preflightRunSingleSourceInLiveCard requires mockRequires");let t=a(await T(u,r)),n=y(t.source_defs).filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)),o={};if(e.sourceIdx>=0&&e.sourceIdx<n.length){let d=n[e.sourceIdx],f=chunkIXZG74EW_cjs.a.enrichSourcesSync([d],{card_data:a(t.card_data),requires:e.mockRequires});Array.isArray(f)&&f.length>0&&(o=a(f[0]._projections));}return await c.runSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":t,"mock-requires":e.mockRequires,"mock-projections":o}})}async function ie(e){let r=a(await M(c.simulateCardCycle({body:{"card-content":e.candidateCardContent,"mock-requires":e.mockRequires}}),"simulateCardCycle")),t=a(e.candidateCardContent),n=a(r.validation),o=y(r.source_probes),d=y(r.projection_errors),f=a(r.fetched_sources),g=y(r.compute_errors),_=a(r.computed_values),v={card_data:a(t.card_data),requires:e.mockRequires,fetched_sources:f,computed_values:_},I=[];for(let w of y(n.issues))typeof w=="string"&&w&&I.push(w);for(let w of o){let l=a(w),P=typeof l.bindTo=="string"?l.bindTo:"source",C=typeof l.error=="string"?l.error:"";C&&I.push(`${P}: ${C}`);}for(let w of d){let l=a(w),P=typeof l.bindTo=="string"?l.bindTo:"source",C=typeof l.key=="string"?l.key:"projection",x=typeof l.error=="string"?l.error:"projection failed";I.push(`${P}.${C}: ${x}`);}for(let w of g){let l=a(w),P=typeof l.bindTo=="string"?l.bindTo:"compute",C=typeof l.error=="string"?l.error:"compute failed";I.push(`${P}: ${C}`);}return {status:"success",data:{cardId:typeof r.cardId=="string"?r.cardId:"(unknown)",ok:r.ok===true,issues:I,provides_outputs:G(t,v),rendered_view:V(t,v)}}}async function z(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("manageReadCard requires cardId");let t=await M(u.get({params:{id:r}}),"cardStore.get"),n=Array.isArray(t.cards)?t.cards.map(a):[];if(n.some(Q))throw Object.assign(new Error(`Card "${r}" not found`),{statusCode:404});return n.map(o=>E(o))}async function K(e){let r=await Promise.all(y(e.files).map(async t=>{let n=a(t),o=String(n.file_name??n.fileName??n.name??"").trim(),d=String(n.content_type??n.contentType??"application/octet-stream");if(!o)throw new Error("file entry requires file_name");return await h({cardId:e.cardId,fileName:o,contentType:d,bytes:X(n)})}));return r.forEach((t,n)=>{let o=a(t.file),d=typeof t.file_idx=="number"&&Number.isInteger(t.file_idx)&&t.file_idx>=0?t.file_idx:n,f=e.role==="assistant"?`AI generated: ${String(o.name||"")} as ${String(o.stored_name||"")} #${d}`:`file uploaded: ${String(o.name||"")} as ${String(o.stored_name||"")} #${d}`;A(p.append({params:{cardId:e.cardId},body:{role:"system",text:f,files:[],turn:e.turn}}),"chatStore.append(system attachment message)");}),r.map(t=>t.file)}async function de(e){let r=String(e.cardId||"").trim(),t=String(e.role||"user").trim()||"user",n=typeof e.turn=="string"?e.turn:"";if(!r)throw new Error("manageAddChatAttachment requires cardId");let o=await K({cardId:r,role:t,turn:n,files:e.files});return {status:"success",data:{cardId:r,turn:n,files:o}}}async function ce(e){let r=String(e.cardId||"").trim(),t=String(e.role||"").trim(),n=typeof e.text=="string"?e.text:"",o=typeof e.turn=="string"?e.turn:"";if(!r)throw new Error("manageAddChatEntryAndAnyAttachments requires cardId");if(!t)throw new Error("manageAddChatEntryAndAnyAttachments requires role");if(t==="assistant"&&o){let g=A(p.readAll({params:{cardId:r},body:{turnId:o}}),"chatStore.readAll(existing turn messages)"),_=Array.isArray(g.records)?g.records.find(v=>v.role==="assistant"&&String(v.turn||"")===o):void 0;if(_)return {status:"success",data:{cardId:r,id:String(_.id),role:t,turn:o,files:Array.isArray(_.files)?_.files:[]}}}let d=await K({cardId:r,role:t,turn:o,files:e.files}),f=A(p.append({params:{cardId:r},body:{role:t,text:n,files:d,turn:o}}),"chatStore.append");return {status:"success",data:{cardId:r,id:String(f.id),role:t,turn:o,files:d}}}async function ue(e){let r=String(e.cardId||"").trim(),t=a(e.patch);if(!r)throw new Error("managePatchCard requires cardId");let n=await z({cardId:r}),o=a(n[0]),d=ve(o,t);return J({cardId:r,candidateCardContent:d})}async function J(e){let r=String(e.cardId||"").trim(),t=a(e.candidateCardContent),n=E(t);if(!r)throw new Error("manageUpsertCard requires cardId");if(typeof n.id!="string"||!n.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(n.id!==r)throw new Error(`candidateCardContent.id must match cardId (${r})`);let o=await D({candidateCardContent:n}),d=a(o),f=a(d.data);if(d.status!=="success"||f.isValid!==true)return {status:"fail",step:"validate",validation:o};let g=null;try{g=await T(u,r);}catch{g=null;}let _=g&&ke(a(g),"meta")?{...n,meta:a(g).meta}:n,v=await u.set({body:_});A(v,"cardStore.set");let I;try{I=await i.upsertCard({params:{cardId:r,restart:!0}}),A(I,"upsertCard");}catch(l){try{g&&await u.set({body:g});}catch{}throw l}let w=null;try{w=await i.cardRefreshedNotify({params:{cardId:r}}),A(w,"cardRefreshedNotify");}catch{w=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:I,refresh_notify:w}}}async function le(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("manageRemoveCard requires cardId");let t=await i.removeCard({params:{id:r}});A(t,"removeCard");let n=await u.del({params:{id:r}});return A(n,"cardStore.del"),{status:"success",data:{board_result:t,store_result:n}}}async function me(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("adminReadCard requires cardId");let t=await M(u.get({params:{id:r}}),"cardStore.get");return Array.isArray(t.cards)?t.cards.map(n=>a(n)):[]}async function pe(e){let r=String(e.cardId||"").trim(),t=a(e.candidateCardContent),n=E(t);if(!r)throw new Error("adminUpsertCard requires cardId");if(typeof n.id!="string"||!n.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(n.id!==r)throw new Error(`candidateCardContent.id must match cardId (${r})`);let o=await D({candidateCardContent:n}),d=a(o),f=a(d.data);if(d.status!=="success"||f.isValid!==true)return {status:"fail",step:"validate",validation:o};let g=null;try{g=await T(u,r);}catch{g=null;}let _=g?a(a(g).meta):{},v={...n,meta:{..._,__visible_controlplane_only:true}},I=await u.set({body:v});A(I,"cardStore.set");let w;try{w=await i.upsertCard({params:{cardId:r,restart:!0}}),A(w,"upsertCard");}catch(P){try{g&&await u.set({body:g});}catch{}throw P}let l=null;try{l=await i.cardRefreshedNotify({params:{cardId:r}}),A(l,"cardRefreshedNotify");}catch{l=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:w,refresh_notify:l}}}function fe(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("getChatProcessing requires cardId");let t=H(p.isProcessing({params:{cardId:r}}),"chatStore.isProcessing");return {cardId:r,active:!!t.active}}function ge(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("setChatProcessing requires cardId");if(typeof e.active!="boolean")throw new Error("setChatProcessing requires boolean active");return A(p.setProcessing({params:{cardId:r},body:{active:e.active}}),"chatStore.setProcessing"),{cardId:r,active:e.active}}async function we(){let e=await B(k,"webhook.process-accumulated")();return e?.status==="fail"||e?.status==="error"?e:{status:"success",data:{runtime_result:Object.prototype.hasOwnProperty.call(e??{},"data")?e.data??null:null}}}async function Ce(e){let r=String(e.token||"").trim(),t=String(e.ref||"").trim();if(!r)throw new Error("webhookSourceFetchDone requires token");if(!t)throw new Error("webhookSourceFetchDone requires ref");let n=await B(R,"webhook.source-fetch-done")({token:r,ref:t});return n?.status==="fail"||n?.status==="error"?n:{status:"success",data:{token:r,ref:t,runtime_result:Object.prototype.hasOwnProperty.call(n??{},"data")?n.data??null:null}}}async function ye(e){let r=String(e.token||"").trim(),t=String(e.reason||"").trim();if(!r)throw new Error("webhookSourceFetchFailed requires token");if(!t)throw new Error("webhookSourceFetchFailed requires reason");let n=await B(b,"webhook.source-fetch-failed")({token:r,reason:t});return n?.status==="fail"||n?.status==="error"?n:{status:"success",data:{token:r,reason:t,runtime_result:Object.prototype.hasOwnProperty.call(n??{},"data")?n.data??null:null}}}return {listRuntimeCards:F,discoverSourceKinds:Y,inspectBoardRuntimeStatus:Z,inspectCardDefinitionAndRuntime:ee,inspectChatMessagesOnCards:re,inspectFileContents:te,preflightValidateCandidateCardDefinition:D,preflightMaterializeCandidateCard:ne,preflightProbeSingleSourceInCandidateCard:ae,preflightRunSingleSourceInCandidateCard:oe,preflightRunSingleSourceInLiveCard:se,preflightRunOneCycleWithCandidateCard:ie,manageReadCard:z,manageAddChatAttachment:de,manageAddChatEntryAndAnyAttachments:ce,managePatchCard:ue,manageUpsertCard:J,manageRemoveCard:le,adminReadCard:me,adminUpsertCard:pe,getChatProcessing:fe,setChatProcessing:ge,webhookProcessAccumulated:we,webhookSourceFetchDone:Ce,webhookSourceFetchFailed:ye}}async function M(s,i){return A(await s,i)}exports.a=Ae;//# sourceMappingURL=chunk-M6STQR5F.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-M6STQR5F.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';function p(e){return String(e).replace(/[^a-zA-Z0-9_-]/g,"_")}function m(e){let n=e.payload??{};return {id:e.id,role:typeof n.role=="string"?n.role:"system",text:typeof n.text=="string"?n.text:"",files:Array.isArray(n.files)?n.files:[],turn:typeof n.turn=="string"?n.turn:"",updated_at:typeof n.updated_at=="string"?n.updated_at:""}}function R(e,n){let a=t=>`chats/${p(t)}/processing`,r=t=>`chats/${p(t)}/config`;return {append(t,i,o,u=[],s=""){return e(t).append({role:i,text:o,files:u,turn:s,updated_at:new Date().toISOString()}).id},readAll(t){return e(t).readAll().map(m)},readAfter(t,i){let o=e(t).readAfter(i);return {records:o.entries.map(m),cursor:o.newCursor}},clear(t){e(t).clear?.();},setProcessing(t,i){i?n.write(a(t),true):n.delete(a(t));},isProcessing(t){return n.read(a(t))===true},getConfig(t){return n.read(r(t))??{}},setConfig(t,i){let o=n.read(r(t))??{};n.write(r(t),{...o,...i});}}}function S(){let e=globalThis.crypto;return typeof e?.randomUUID=="function"?String(e.randomUUID()):`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function $(){let e=new Map,n=new Map;function a(r){return e.has(r)||e.set(r,[]),e.get(r)}return {append(r,t,i,o=[],u=""){let s={id:S(),role:t,text:i,files:o,turn:u,updated_at:new Date().toISOString()};return a(r).push(s),s.id},readAll(r){return a(r).slice()},readAfter(r,t){let i=a(r);if(!t)return {records:i.slice(),cursor:i.length>0?i[i.length-1].id:null};let o=i.findIndex(s=>s.id===t),u=o===-1?i.slice():i.slice(o+1);return {records:u,cursor:u.length>0?u[u.length-1].id:t}},clear(r){e.set(r,[]);},setProcessing(r,t){t?n.set(`p:${r}`,true):n.delete(`p:${r}`);},isProcessing(r){return n.get(`p:${r}`)===true},getConfig(r){return n.get(`c:${r}`)??{}},setConfig(r,t){let i=n.get(`c:${r}`)??{};n.set(`c:${r}`,{...i,...t});}}}function y(){return new Date().toISOString()}function x(e){return new TextEncoder().encode(e).byteLength}function A(e){return e?{key:e.key,size:e.size,updatedAt:e.updatedAt,contentType:e.contentType}:null}function w(e){let n=String(e||"").match(/^(\d+)[-_]/);return n?parseInt(n[1],10):0}function I(e){let n=String(e||"").trim();if(!n)return "upload.bin";let a=Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"));return (a>=0?n.slice(a+1):n)||"upload.bin"}function k(e){return String(e||"").toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"")||"file"}function z(e){if(!e||e===".")return "";let n=String(e).replace(/^\./,"").toLowerCase().replace(/[^a-z0-9]/g,"");return n?`.${n}`:""}function F(e){let n=I(e),a=n.lastIndexOf(".");return a<=0||a===n.length-1?{stem:n,ext:""}:{stem:n.slice(0,a),ext:n.slice(a)}}function M(e){let n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e}function L(e){function n(a){let r=e.stat?A(e.stat(a)):null;if(r)return r;if(!e.exists(a))return null;let t=e.read(a);return t===null?{key:a}:{key:a,size:x(t)}}return {exists(a){return e.exists(a)},putText(a,r,t="text/plain; charset=utf-8"){e.write(a,r);let i=n(a)??{key:a};return i.contentType=t,i.updatedAt=i.updatedAt??y(),i.size=i.size??x(r),i},putBytes(a,r,t="application/octet-stream"){if(e.writeBytes)e.writeBytes(a,r);else {let o=JSON.stringify({__kind:"bytes-array",data:[...r]});e.write(a,o);}let i=n(a)??{key:a};return i.contentType=t,i.updatedAt=i.updatedAt??y(),i.size=i.size??r.byteLength,i},getText(a){let r=e.read(a);if(r===null){if(!e.readBytes)return null;let t=e.readBytes(a);return t===null?null:Buffer.from(t).toString("utf-8")}try{let t=JSON.parse(r);if(t&&t.__kind==="bytes-array"&&Array.isArray(t.data))return new TextDecoder("utf-8").decode(new Uint8Array(t.data))}catch{}return r},getBytes(a){if(e.readBytes){let t=e.readBytes(a);if(t!==null)return t}let r=e.read(a);if(r===null)return null;try{let t=JSON.parse(r);if(t&&t.__kind==="bytes-array"&&Array.isArray(t.data))return new Uint8Array(t.data)}catch{}return new TextEncoder().encode(r)},head:n,list(a=""){return e.listKeys(a).map(r=>n(r)??{key:r}).sort((r,t)=>r.key.localeCompare(t.key))},remove(a){e.remove(a);}}}function b(e){function n(t,i){let o=0,u=[];Array.isArray(i)&&u.push(...i);for(let s of e.list(`${t}/`))u.push(M(s.key));for(let s of u){let l=w(s);Number.isFinite(l)&&l>o&&(o=l);}return o+1}function a(t,i,o){let u=Number(o?.maxLen||32),{stem:s,ext:l}=F(t),h=z(l),C=k(s),d=`${String(i).padStart(3,"0")}-`,g=h,f=u-d.length-g.length;f<1&&(g="",f=u-d.length);let _=C.slice(0,Math.max(1,f)),c=`${d}${_}${g}`;return c.length>u&&(c=c.slice(0,u).replace(/\.$/,"")),c}function r(t,i,o){let u=n(t,o?.seedNames),s=a(i,u,{maxLen:o?.maxLen});for(;e.exists(`${t}/${s}`);)u+=1,s=a(i,u,{maxLen:o?.maxLen});return s}return {nextSerial:n,buildStoredName:a,allocateStoredName:r}}function N(){function e(t,i){if(!Array.isArray(t))return [];let o=[];for(let u of t){if(!u||typeof u!="object")continue;let s=u;typeof s.stored_name=="string"&&o.push({name:typeof s.name=="string"?s.name:s.stored_name,stored_name:s.stored_name,size:typeof s.size=="number"&&Number.isFinite(s.size)?s.size:null,mime_type:typeof s.mime_type=="string"?s.mime_type:null,uploaded_at:typeof s.uploaded_at=="string"?s.uploaded_at:i||null,chat:s.chat===true});}return o}function n(t){return !t||typeof t!="object"?[]:e(t.files,void 0)}function a(t,i){let o=n(t);if(i.length===0)return t.files=o,o;let u=new Set(o.map(s=>s.stored_name));for(let s of i)u.has(s.stored_name)||(o.push(s),u.add(s.stored_name));return t.files=o,o}function r(t,i,o){let u=n(t);if(!Number.isInteger(i)||i<0||i>=u.length)return {ok:false,reason:"index_out_of_range"};let s=u[i];return !s||!s.stored_name?{ok:false,reason:"missing_stored_name"}:o&&o!==s.stored_name?{ok:false,reason:"stale_reference"}:{ok:true,file:s}}return {read:n,normalizeIncoming:e,merge:a,resolve:r}}exports.a=R;exports.b=$;exports.c=L;exports.d=b;exports.e=N;//# sourceMappingURL=chunk-NJJ7WEDT.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-NJJ7WEDT.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunk272IYUKT_cjs=require('./chunk-272IYUKT.cjs');function w(c){let{apiBasePath:p,json:t,readJsonBody:m,initBoardAndSetup:d,createMcpWebhookToolRegistry:R}=c;async function l(i,r,y){let g=i.method||"GET",b=y.pathname;try{if(g==="POST"&&b===`${p}/mcp-webhooks`){await d();let o=await m(i),s=typeof o.tool=="string"?o.tool.trim():"",f=o.args&&typeof o.args=="object"&&!Array.isArray(o.args)?o.args:{};if(!s)return t(r,400,{error:"tool is required"}),!0;try{let e=await chunk272IYUKT_cjs.a(s,f,R());if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.status==="fail")return t(r,400,{error:chunk272IYUKT_cjs.b(e,"Request failed")}),!0;if(n.status==="error")return t(r,500,{error:chunk272IYUKT_cjs.b(e,"Internal error")}),!0}t(r,200,e);}catch(e){let n=typeof e?.statusCode=="number"?Number(e.statusCode):500,h=e instanceof Error?e.message:String(e);t(r,n,{error:h});}return !0}return !1}catch(o){let s=o?.statusCode||500;return t(r,s,{error:String(o?.message||o)}),true}}return {handleWebhooksApi:l}}exports.a=w;//# sourceMappingURL=chunk-NM6O35RY.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-NM6O35RY.cjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1,b as b$1}from'./chunk-O7NOHKVR.js';import {a,b}from'./chunk-ZJ5M5COT.js';function G(q){let{apiBasePath:x,json:r,readJsonBody:k,bootstrapBoard:T,createMcpFacade:B,createMcpToolRegistry:I,resolveCardFileDownloadPayload:j,isLikelyTextMimeType:v,sliceTextByLines:C}=q;async function D(b$2,e,N){let A=b$2.method||"GET",M=N,L=M.pathname;try{if(A==="POST"&&L===`${x}/mcp`){await T();let t=await k(b$2),i=typeof t.tool=="string"?t.tool.trim():"",a$1=t.args&&typeof t.args=="object"&&!Array.isArray(t.args)?t.args:{};if(!i)return r(e,400,{error:"tool is required"}),!0;if(i==="inspect.file-contents")return r(e,400,{error:"inspect.file-contents is only available on /mcp-raw"}),!0;try{let n=await a(i,a$1,I(B()));if(n&&typeof n=="object"&&!Array.isArray(n)){let s=n;if(s.status==="fail")return r(e,400,{error:b(n,"Request failed")}),!0;if(s.status==="error")return r(e,500,{error:b(n,"Internal error")}),!0}r(e,200,n);}catch(n){let s=typeof n?.statusCode=="number"?Number(n.statusCode):500,d=n instanceof Error?n.message:String(n);r(e,s,{error:d});}return !0}if(A==="POST"&&L===`${x}/mcp-raw`){await T();let t=await k(b$2),i=typeof t.tool=="string"?t.tool.trim():"",a=t.args&&typeof t.args=="object"&&!Array.isArray(t.args)?t.args:{};if(!i)return r(e,400,{error:"tool is required"}),!0;if(i!=="inspect.file-contents")return r(e,400,{error:`Tool does not support raw response: ${i}`}),!0;let n=a$1(a,"card_id","cardId"),s=b$1(a,"file_idx","fileIdx"),d=b$1(a,"head-lines","headLines"),m=b$1(a,"tail-lines","tailLines"),f=b$1(a,"head-bytes","headBytes"),y=b$1(a,"tail-bytes","tailBytes");if(!n)return r(e,400,{error:"inspect.file-contents requires card_id"}),!0;if(s===void 0||!Number.isInteger(s)||s<0)return r(e,400,{error:"inspect.file-contents requires file_idx to be a non-negative integer"}),!0;if([d,m,f,y].filter(o=>o!==void 0).length>1)return r(e,400,{error:"inspect.file-contents accepts at most one of head-lines, tail-lines, head-bytes, tail-bytes"}),!0;for(let[o,u]of [["head-lines",d],["tail-lines",m],["head-bytes",f],["tail-bytes",y]])if(u!==void 0&&(!Number.isInteger(u)||u<0))return r(e,400,{error:`inspect.file-contents requires ${o} to be a non-negative integer`}),!0;let F=await B().inspectFileContents({cardId:n,fileIdx:s}),$=typeof F?.stored_name=="string"?F.stored_name:null,{fileRecord:R,bytes:p}=await j(n,s,$),P=String(R.name||R.stored_name||"download.bin"),w=String(R.mime_type||"application/octet-stream"),g=(M.searchParams.get("resp")||"").trim().toLowerCase();if(g&&g!=="json-b64")return r(e,400,{error:`unsupported resp mode: ${g}`}),!0;let U=g==="json-b64",c;if(d!==void 0||m!==void 0){if(!v(w))return r(e,400,{error:"head-lines/tail-lines are only supported for text-like files; use head-bytes/tail-bytes for binary content"}),!0;let o=new TextDecoder().decode(p),u=d!==void 0?C(o,"head",d):C(o,"tail",m);c=typeof Buffer<"u"?Buffer.from(u,"utf8"):new TextEncoder().encode(u);}else if(f!==void 0||y!==void 0){let o=f??y;c=f!==void 0?p.slice(0,o):p.slice(Math.max(0,p.length-o));}else c=p;if(U){let o=typeof Buffer<"u"?Buffer.from(c).toString("base64"):btoa(String.fromCharCode(...c));return r(e,200,{bodyBase64:o,mimeType:w,filename:P,byteLength:c.length}),!0}return e.writeHead(200,{"Content-Type":w,"Content-Disposition":`attachment; filename="${P}"`,"Content-Length":c.length}),e.end(c),!0}return !1}catch(t){let i=t?.statusCode||500;return r(e,i,{error:String(t?.message||t)}),true}}return {handleAgentfaceApi:D}}export{G as a};//# sourceMappingURL=chunk-NTICU4OK.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-NTICU4OK.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function u(n,...r){for(let e of r)if(typeof n[e]=="string")return String(n[e]);return ""}function s(n,...r){for(let e of r)if(n[e]!==void 0)return Number(n[e])}function c(n,...r){for(let e of r){let t=n[e];if(t&&typeof t=="object"&&!Array.isArray(t))return t}return {}}function f(n,r,...e){for(let t of e){let o=n[t];if(o&&typeof o=="object"&&!Array.isArray(o))return o}throw Object.assign(new Error(`MCP tool requires ${r}`),{statusCode:400})}function d(n,r,...e){for(let t of e){let o=n[t];if(o!==void 0){let i=Number(o);if(Number.isFinite(i))return i}}throw Object.assign(new Error(`MCP tool requires ${r}`),{statusCode:400})}function g(n){if(Array.isArray(n.bytes))return new Uint8Array(n.bytes.map(r=>Math.max(0,Math.min(255,Number(r)||0))));if(typeof n.text=="string")return new TextEncoder().encode(n.text);if(typeof n.base64=="string"){let r=String(n.base64).replace(/-/g,"+").replace(/_/g,"/"),e=r+"=".repeat((4-r.length%4)%4),t=atob(e);return Uint8Array.from(t,o=>o.charCodeAt(0))}return null}export{u as a,s as b,c,f as d,d as e,g as f};//# sourceMappingURL=chunk-O7NOHKVR.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-O7NOHKVR.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a as a$1}from'./chunk-JMDHDY6M.js';function A(s,i){if(s?.status==="success")return Object.prototype.hasOwnProperty.call(s,"data")?s.data:void 0;throw s?.status==="fail"||s?.status==="error"?new Error(s.error||`${i} failed`):new Error(`${i} returned an unexpected response`)}function H(s,i){if(s?.status==="success"&&Object.prototype.hasOwnProperty.call(s,"data"))return s.data;throw s?.status==="success"?new Error(`${i} returned success without data`):s?.status==="fail"||s?.status==="error"?new Error(s.error||`${i} failed`):new Error(`${i} returned an unexpected response`)}function a(s){return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}function y(s){return Array.isArray(s)?s:[]}function N(s,i){if(typeof i!="string"||i.length===0)return;let c=s,u=i;u.startsWith("fetched_sources.")&&(c=a(s).fetched_sources,u=u.slice(16));for(let p of u.split(".")){if(c==null||typeof c!="object")return;c=c[p];}return c}function V(s,i){let c=a(s.view),u=y(c.elements);return {layout:c.layout,features:c.features,elements:u.map((p,k)=>{let R=a(p),b=a(R.data),h=typeof R.visible=="string"?!!N(i,R.visible):true,U=typeof b.bind=="string"?b.bind:void 0,S=typeof b.maxRows=="number"?b.maxRows:void 0,B=U?N(i,U):void 0,F={id:typeof R.id=="string"&&R.id?R.id:`element-${k}`,kind:R.kind,label:R.label,visible:h};return B!==void 0&&(F.resolved=Array.isArray(B)&&typeof S=="number"?B.slice(0,S):B),F})}}function G(s,i){let c=typeof s.id=="string"&&s.id?s.id:"card",u=y(s.provides),p=u.length>0?u:[{bindTo:c,ref:"card_data"}],k={};for(let R of p){let b=a(R),h=typeof b.bindTo=="string"?b.bindTo:"",U=typeof b.ref=="string"?b.ref:"";if(!h||!U)continue;let S=N(i,U);S!==void 0&&(k[h]=S);}return k}function be(s){if(typeof s!="string"||!s.trim())return null;let i=/^(file uploaded|AI generated|AI geneterated):\s*.*?#(\d+)\s*$/i.exec(s.trim());if(!i)return null;let c=Number.parseInt(i[2],10);return !Number.isInteger(c)||c<0?null:c}function he(s){return {"card-content":s}}function E(s){let{meta:i,...c}=s;return c}function ke(s,i){return Object.prototype.hasOwnProperty.call(s,i)}function Re(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}function ve(s,i){let c=Re(s);if(!i||Object.keys(i).length===0)return c;function u(p,k,R){let b=String(k||"").split(".").filter(Boolean);if(!b.length)return;let h=p;for(let U=0;U<b.length-1;U+=1){let S=b[U];(!h[S]||typeof h[S]!="object")&&(h[S]={}),h=h[S];}h[b[b.length-1]]=R;}if(i.fieldValues!==void 0&&i.fieldValues!==null){let p=null,k=a(c.view),R=y(k.elements);for(let b of R){let h=a(a(b).data);if(typeof h.writeTo=="string"&&h.writeTo){p=h.writeTo;break}}return p?u(c,p,i.fieldValues):typeof i.fieldValues=="object"&&!Array.isArray(i.fieldValues)&&(c.card_data={...a(c.card_data),...i.fieldValues}),c}if(Array.isArray(i._stagedFiles)&&i._stagedFiles.length>0)return c;for(let[p,k]of Object.entries(i))p!=="_stagedFiles"&&(k!==null&&typeof k=="object"&&!Array.isArray(k)&&c[p]!==null&&typeof c[p]=="object"&&!Array.isArray(c[p])?c[p]={...c[p],...k}:c[p]=k);return c}function Q(s){return a(s.meta).__visible_controlplane_only===true}async function T(s,i){let c=await M(s.get({params:{id:i}}),"cardStore.get"),u=Array.isArray(c?.cards)?c.cards:[];if(u.length===0)throw new Error(`Card "${i}" not found`);return u[0]}function Ae(s){let{board:i,nonCore:c,cardStore:u,chatStore:p,processAccumulated:k,sourceFetchDone:R,sourceFetchFailed:b,uploadCardFile:h,buildFileDownloadUrl:U,readFetchedSourceJsonByRef:S}=s;function B(e,r){if(typeof e=="function")return e;throw new Error(`${r} is not configured for this MCP facade`)}async function F(){let e=await M(u.get({}),"cardStore.get");return Array.isArray(e.cards)?e.cards.map(r=>a(r)):[]}function X(e){if(Array.isArray(e.bytes))return new Uint8Array(e.bytes.map(r=>Math.max(0,Math.min(255,Number(r)||0))));if(typeof e.text=="string")return new TextEncoder().encode(e.text);if(typeof e.base64=="string"){let r=String(e.base64).replace(/-/g,"+").replace(/_/g,"/"),t=r+"=".repeat((4-r.length%4)%4),n=atob(t);return Uint8Array.from(n,o=>o.charCodeAt(0))}throw new Error("file entry requires bytes, text, or base64")}async function Y(){let e=a(await M(c.describeTaskExecutorCapabilities({}),"describeTaskExecutorCapabilities"));return {version:e.version,commonSourceFields:a(e.commonSourceDefFields),sourceKinds:a(e.sourceKinds)}}async function Z(){let e=a(await M(i.status({}),"status")),r=a(e.summary),t=y(e.cards);return {meta:a(e.meta),summary:{card_count:typeof r.card_count=="number"?r.card_count:0,completed:typeof r.completed=="number"?r.completed:0,eligible:typeof r.eligible=="number"?r.eligible:0,pending:typeof r.pending=="number"?r.pending:0,blocked:typeof r.blocked=="number"?r.blocked:0,in_progress:typeof r.in_progress=="number"?r.in_progress:0,failed:typeof r.failed=="number"?r.failed:0,unresolved:typeof r.unresolved=="number"?r.unresolved:0},cards:t.map(n=>{let o=a(n);return {"card-id":typeof o.name=="string"?o.name:null,status:o.status??null,error:o.error??null,requires:y(o.requires),requires_satisfied:y(o.requires_satisfied),requires_missing:y(o.requires_missing),provides_declared:y(o.provides_declared),provides_runtime:y(o.provides_runtime)}})}}async function ee(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("inspectCardDefinitionAndRuntime requires cardId");let t=a(await M(i.status({}),"status")),o=y(t.cards).map(a).find(m=>m.name===r);if(!o)throw new Error(`card "${r}" not found in board status`);let d=a(await T(u,r));if(Q(d))throw Object.assign(new Error(`card "${r}" not found`),{statusCode:404});let f=E(d),g=y(o.requires_satisfied).filter(m=>typeof m=="string"&&!!m),_=y(o.provides_runtime).filter(m=>typeof m=="string"&&!!m),v=Object.fromEntries(await Promise.all(g.map(async m=>[m,await M(i.getOutputsDataObject({params:{key:m}}),`getOutputsDataObject(${m})`)]))),I=Object.fromEntries(await Promise.all(_.map(async m=>[m,await M(i.getOutputsDataObject({params:{key:m}}),`getOutputsDataObject(${m})`)]))),w=a(await M(i.getOutputsComputedValues({params:{key:r}}),"getOutputsComputedValues")),l=await M(i.getOutputsFetchedSources({params:{key:r}}),"getOutputsFetchedSources"),P=y(d.source_defs).map(a),C={};for(let m of P)typeof m.bindTo=="string"&&typeof m.outputFile=="string"&&(C[m.outputFile]=m.bindTo);let x={};for(let[m,O]of Object.entries(l)){let q=C[m]??m;if(!S||typeof O!="string"){x[q]=null;continue}try{x[q]=S({cardId:r,ref:O});}catch{x[q]=null;}}let L={card_data:a(d.card_data),requires:v,fetched_sources:x,computed_values:w};return {cardId:r,card_status_in_board:o,card_definition_and_static_data:f,refs_for_fetched_source_files:l,runtime_data:{requires:v,provides:I,computed_values:w,rendered_view:V(d,L)}}}async function re(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("inspectChatMessagesOnCards requires cardId");let t=typeof e.turnId=="string"?e.turnId:"",n=e.allTurns===true,o=typeof e.tailTurnsBeforeId=="string"?e.tailTurnsBeforeId:"",d=n?void 0:e.lastUserTurns??(t?void 0:1),f=e.tail,g={...d===void 0?{}:{tailTurns:d},...t?{turnId:t}:{},...n?{allTurns:true}:{},...o?{tailTurnsBeforeId:o}:{}},_=Object.keys(g).length>0?{params:{cardId:r},body:g}:{params:{cardId:r}},v=A(p.readAll(_),"chatStore.readAll"),I=a(await T(u,r)),w=y(a(I.card_data).files).map((C,x)=>({idx:x,stored_name:a(C).stored_name})).filter(C=>typeof C.stored_name=="string"&&C.stored_name.length>0),P=(Array.isArray(v.records)?v.records:[]).map(C=>{let L=a(C.payload),m={...C},O=typeof C?.role=="string"?C.role:typeof L.role=="string"?String(L.role):"",q=typeof C?.text=="string"?C.text:typeof L.text=="string"?String(L.text):"";if(O==="system"){let $=be(q);if($!==null&&w.some(j=>j.idx===$)){let j=`Retrieve using inspect-file-contents --card-id ${r} --file-idx ${$}`;m.retrieval_hint=j,Object.keys(L).length>0&&typeof C.role!="string"&&(m.payload={...L,retrieval_hint:j});}}return m});return {cardId:r,messages:typeof f=="number"&&f>=0?P.slice(-f):P}}async function te(e){let r=String(e.cardId||"").trim(),t=Number(e.fileIdx);if(!r)throw new Error("inspectFileContents requires cardId");if(!Number.isInteger(t)||t<0)throw new Error("inspectFileContents requires fileIdx to be a non-negative integer");let n=a(await T(u,r)),o=y(a(n.card_data).files).map(a);if(t>=o.length)throw new Error(`attachment index ${t} is out of range for card "${r}"`);let d=o[t],f=typeof d.stored_name=="string"?d.stored_name:null;return {cardId:r,fileIdx:t,downloadUrl:U({cardId:r,fileIdx:t,storedName:f}),...typeof d.name=="string"?{name:d.name}:{},...typeof d.stored_name=="string"?{stored_name:d.stored_name}:{},...typeof d.mime_type=="string"?{mime_type:d.mime_type}:{},...typeof d.size=="number"?{size:d.size}:{},...typeof d.uploaded_at=="string"?{uploaded_at:d.uploaded_at}:{}}}async function D(e){return await c.validateCardPreflight({body:he(e.candidateCardContent)})}function ne(e){if(!e.mockRequires||typeof e.mockRequires!="object"||Array.isArray(e.mockRequires))throw new Error("preflightMaterializeCandidateCard requires mockRequires");if(!e.mockFetchedSources||typeof e.mockFetchedSources!="object"||Array.isArray(e.mockFetchedSources))throw new Error("preflightMaterializeCandidateCard requires mockFetchedSources");let r=c.evalCardCompute({body:{"card-content":e.candidateCardContent,"mock-requires":e.mockRequires,"mock-fetched-sources":e.mockFetchedSources}});if(r.status!=="success")return r;let t=a(H(r,"evalCardCompute")),n=a(e.candidateCardContent),o={card_data:a(n.card_data),requires:a(e.mockRequires),fetched_sources:a(e.mockFetchedSources),computed_values:a(t.computed_values)};return {status:"success",data:{cardId:typeof t.cardId=="string"?t.cardId:typeof n.id=="string"?n.id:"(unknown)",ok:t.ok===true,computed_values:a(t.computed_values),errors:y(t.errors).map(d=>{let f=a(d);return {bindTo:typeof f.bindTo=="string"?f.bindTo:"",error:typeof f.error=="string"?f.error:""}}),provides_outputs:G(n,o),rendered_view:V(n,o)}}}async function ae(e){return await c.probeSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":e.candidateCardContent,"mock-projections":e.mockProjections}})}async function oe(e){return await c.runSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":e.candidateCardContent,"mock-projections":e.mockProjections}})}async function se(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("preflightRunSingleSourceInLiveCard requires cardId");if(!e.mockRequires||typeof e.mockRequires!="object"||Array.isArray(e.mockRequires))throw new Error("preflightRunSingleSourceInLiveCard requires mockRequires");let t=a(await T(u,r)),n=y(t.source_defs).filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)),o={};if(e.sourceIdx>=0&&e.sourceIdx<n.length){let d=n[e.sourceIdx],f=a$1.enrichSourcesSync([d],{card_data:a(t.card_data),requires:e.mockRequires});Array.isArray(f)&&f.length>0&&(o=a(f[0]._projections));}return await c.runSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":t,"mock-requires":e.mockRequires,"mock-projections":o}})}async function ie(e){let r=a(await M(c.simulateCardCycle({body:{"card-content":e.candidateCardContent,"mock-requires":e.mockRequires}}),"simulateCardCycle")),t=a(e.candidateCardContent),n=a(r.validation),o=y(r.source_probes),d=y(r.projection_errors),f=a(r.fetched_sources),g=y(r.compute_errors),_=a(r.computed_values),v={card_data:a(t.card_data),requires:e.mockRequires,fetched_sources:f,computed_values:_},I=[];for(let w of y(n.issues))typeof w=="string"&&w&&I.push(w);for(let w of o){let l=a(w),P=typeof l.bindTo=="string"?l.bindTo:"source",C=typeof l.error=="string"?l.error:"";C&&I.push(`${P}: ${C}`);}for(let w of d){let l=a(w),P=typeof l.bindTo=="string"?l.bindTo:"source",C=typeof l.key=="string"?l.key:"projection",x=typeof l.error=="string"?l.error:"projection failed";I.push(`${P}.${C}: ${x}`);}for(let w of g){let l=a(w),P=typeof l.bindTo=="string"?l.bindTo:"compute",C=typeof l.error=="string"?l.error:"compute failed";I.push(`${P}: ${C}`);}return {status:"success",data:{cardId:typeof r.cardId=="string"?r.cardId:"(unknown)",ok:r.ok===true,issues:I,provides_outputs:G(t,v),rendered_view:V(t,v)}}}async function z(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("manageReadCard requires cardId");let t=await M(u.get({params:{id:r}}),"cardStore.get"),n=Array.isArray(t.cards)?t.cards.map(a):[];if(n.some(Q))throw Object.assign(new Error(`Card "${r}" not found`),{statusCode:404});return n.map(o=>E(o))}async function K(e){let r=await Promise.all(y(e.files).map(async t=>{let n=a(t),o=String(n.file_name??n.fileName??n.name??"").trim(),d=String(n.content_type??n.contentType??"application/octet-stream");if(!o)throw new Error("file entry requires file_name");return await h({cardId:e.cardId,fileName:o,contentType:d,bytes:X(n)})}));return r.forEach((t,n)=>{let o=a(t.file),d=typeof t.file_idx=="number"&&Number.isInteger(t.file_idx)&&t.file_idx>=0?t.file_idx:n,f=e.role==="assistant"?`AI generated: ${String(o.name||"")} as ${String(o.stored_name||"")} #${d}`:`file uploaded: ${String(o.name||"")} as ${String(o.stored_name||"")} #${d}`;A(p.append({params:{cardId:e.cardId},body:{role:"system",text:f,files:[],turn:e.turn}}),"chatStore.append(system attachment message)");}),r.map(t=>t.file)}async function de(e){let r=String(e.cardId||"").trim(),t=String(e.role||"user").trim()||"user",n=typeof e.turn=="string"?e.turn:"";if(!r)throw new Error("manageAddChatAttachment requires cardId");let o=await K({cardId:r,role:t,turn:n,files:e.files});return {status:"success",data:{cardId:r,turn:n,files:o}}}async function ce(e){let r=String(e.cardId||"").trim(),t=String(e.role||"").trim(),n=typeof e.text=="string"?e.text:"",o=typeof e.turn=="string"?e.turn:"";if(!r)throw new Error("manageAddChatEntryAndAnyAttachments requires cardId");if(!t)throw new Error("manageAddChatEntryAndAnyAttachments requires role");if(t==="assistant"&&o){let g=A(p.readAll({params:{cardId:r},body:{turnId:o}}),"chatStore.readAll(existing turn messages)"),_=Array.isArray(g.records)?g.records.find(v=>v.role==="assistant"&&String(v.turn||"")===o):void 0;if(_)return {status:"success",data:{cardId:r,id:String(_.id),role:t,turn:o,files:Array.isArray(_.files)?_.files:[]}}}let d=await K({cardId:r,role:t,turn:o,files:e.files}),f=A(p.append({params:{cardId:r},body:{role:t,text:n,files:d,turn:o}}),"chatStore.append");return {status:"success",data:{cardId:r,id:String(f.id),role:t,turn:o,files:d}}}async function ue(e){let r=String(e.cardId||"").trim(),t=a(e.patch);if(!r)throw new Error("managePatchCard requires cardId");let n=await z({cardId:r}),o=a(n[0]),d=ve(o,t);return J({cardId:r,candidateCardContent:d})}async function J(e){let r=String(e.cardId||"").trim(),t=a(e.candidateCardContent),n=E(t);if(!r)throw new Error("manageUpsertCard requires cardId");if(typeof n.id!="string"||!n.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(n.id!==r)throw new Error(`candidateCardContent.id must match cardId (${r})`);let o=await D({candidateCardContent:n}),d=a(o),f=a(d.data);if(d.status!=="success"||f.isValid!==true)return {status:"fail",step:"validate",validation:o};let g=null;try{g=await T(u,r);}catch{g=null;}let _=g&&ke(a(g),"meta")?{...n,meta:a(g).meta}:n,v=await u.set({body:_});A(v,"cardStore.set");let I;try{I=await i.upsertCard({params:{cardId:r,restart:!0}}),A(I,"upsertCard");}catch(l){try{g&&await u.set({body:g});}catch{}throw l}let w=null;try{w=await i.cardRefreshedNotify({params:{cardId:r}}),A(w,"cardRefreshedNotify");}catch{w=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:I,refresh_notify:w}}}async function le(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("manageRemoveCard requires cardId");let t=await i.removeCard({params:{id:r}});A(t,"removeCard");let n=await u.del({params:{id:r}});return A(n,"cardStore.del"),{status:"success",data:{board_result:t,store_result:n}}}async function me(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("adminReadCard requires cardId");let t=await M(u.get({params:{id:r}}),"cardStore.get");return Array.isArray(t.cards)?t.cards.map(n=>a(n)):[]}async function pe(e){let r=String(e.cardId||"").trim(),t=a(e.candidateCardContent),n=E(t);if(!r)throw new Error("adminUpsertCard requires cardId");if(typeof n.id!="string"||!n.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(n.id!==r)throw new Error(`candidateCardContent.id must match cardId (${r})`);let o=await D({candidateCardContent:n}),d=a(o),f=a(d.data);if(d.status!=="success"||f.isValid!==true)return {status:"fail",step:"validate",validation:o};let g=null;try{g=await T(u,r);}catch{g=null;}let _=g?a(a(g).meta):{},v={...n,meta:{..._,__visible_controlplane_only:true}},I=await u.set({body:v});A(I,"cardStore.set");let w;try{w=await i.upsertCard({params:{cardId:r,restart:!0}}),A(w,"upsertCard");}catch(P){try{g&&await u.set({body:g});}catch{}throw P}let l=null;try{l=await i.cardRefreshedNotify({params:{cardId:r}}),A(l,"cardRefreshedNotify");}catch{l=null;}return {status:"success",data:{validation:o,card_saved:null,board_result:w,refresh_notify:l}}}function fe(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("getChatProcessing requires cardId");let t=H(p.isProcessing({params:{cardId:r}}),"chatStore.isProcessing");return {cardId:r,active:!!t.active}}function ge(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("setChatProcessing requires cardId");if(typeof e.active!="boolean")throw new Error("setChatProcessing requires boolean active");return A(p.setProcessing({params:{cardId:r},body:{active:e.active}}),"chatStore.setProcessing"),{cardId:r,active:e.active}}async function we(){let e=await B(k,"webhook.process-accumulated")();return e?.status==="fail"||e?.status==="error"?e:{status:"success",data:{runtime_result:Object.prototype.hasOwnProperty.call(e??{},"data")?e.data??null:null}}}async function Ce(e){let r=String(e.token||"").trim(),t=String(e.ref||"").trim();if(!r)throw new Error("webhookSourceFetchDone requires token");if(!t)throw new Error("webhookSourceFetchDone requires ref");let n=await B(R,"webhook.source-fetch-done")({token:r,ref:t});return n?.status==="fail"||n?.status==="error"?n:{status:"success",data:{token:r,ref:t,runtime_result:Object.prototype.hasOwnProperty.call(n??{},"data")?n.data??null:null}}}async function ye(e){let r=String(e.token||"").trim(),t=String(e.reason||"").trim();if(!r)throw new Error("webhookSourceFetchFailed requires token");if(!t)throw new Error("webhookSourceFetchFailed requires reason");let n=await B(b,"webhook.source-fetch-failed")({token:r,reason:t});return n?.status==="fail"||n?.status==="error"?n:{status:"success",data:{token:r,reason:t,runtime_result:Object.prototype.hasOwnProperty.call(n??{},"data")?n.data??null:null}}}return {listRuntimeCards:F,discoverSourceKinds:Y,inspectBoardRuntimeStatus:Z,inspectCardDefinitionAndRuntime:ee,inspectChatMessagesOnCards:re,inspectFileContents:te,preflightValidateCandidateCardDefinition:D,preflightMaterializeCandidateCard:ne,preflightProbeSingleSourceInCandidateCard:ae,preflightRunSingleSourceInCandidateCard:oe,preflightRunSingleSourceInLiveCard:se,preflightRunOneCycleWithCandidateCard:ie,manageReadCard:z,manageAddChatAttachment:de,manageAddChatEntryAndAnyAttachments:ce,managePatchCard:ue,manageUpsertCard:J,manageRemoveCard:le,adminReadCard:me,adminUpsertCard:pe,getChatProcessing:fe,setChatProcessing:ge,webhookProcessAccumulated:we,webhookSourceFetchDone:Ce,webhookSourceFetchFailed:ye}}async function M(s,i){return A(await s,i)}export{Ae as a};//# sourceMappingURL=chunk-PRHQBGPT.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-PRHQBGPT.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function T(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.code=="number")return t.code}function c(e,t){return T(e)===t}function l(e,t,r){return t?typeof t=="function"?t(e):t:r}function b(e){return (e?.()??new Date).toISOString()}function L(e,t){if(t)return t();let r=String((e?.()??new Date).getTime()).padStart(13,"0"),n=Math.random().toString(36).slice(2,10).padEnd(8,"0");return `${r}-${n}`}function p(e){return {id:e.id,payload:e.payload}}function B(e,t={}){return {async read(r){let n=l(r,t.partitionKey,"kv");try{return (await e.item(r,n).read()).resource?.value??null}catch(o){if(c(o,404))return null;throw o}},async write(r,n){let o=l(r,t.partitionKey,"kv");await e.items.upsert({id:r,pk:o,kind:"kv",value:n});},async delete(r){let n=l(r,t.partitionKey,"kv");try{await e.item(r,n).delete();}catch(o){if(!c(o,404))throw o}},async listKeys(r=""){let{resources:n}=await e.items.query({query:"SELECT c.id FROM c WHERE c.kind = @kind AND STARTSWITH(c.id, @prefix)",parameters:[{name:"@kind",value:"kv"},{name:"@prefix",value:r}]}).fetchAll();return n.map(o=>o.id).sort()}}}function x(e,t,r={}){let n=l(t,r.partitionKey,`journal:${t}`);return {async append(o){let s={id:L(r.now,r.idFactory),pk:n,kind:"journal",streamKey:t,createdAt:b(r.now),payload:o};return await e.items.create(s),p(s)},async readAll(){let{resources:o}=await e.items.query({query:"SELECT * FROM c WHERE c.kind = @kind AND c.pk = @pk AND c.streamKey = @streamKey ORDER BY c.id",parameters:[{name:"@kind",value:"journal"},{name:"@pk",value:n},{name:"@streamKey",value:t}]}).fetchAll();return o.sort((s,a)=>s.id.localeCompare(a.id)).map(p)},async readAfter(o){let{resources:s}=await e.items.query({query:o?"SELECT * FROM c WHERE c.kind = @kind AND c.pk = @pk AND c.streamKey = @streamKey AND c.id > @cursor ORDER BY c.id":"SELECT * FROM c WHERE c.kind = @kind AND c.pk = @pk AND c.streamKey = @streamKey ORDER BY c.id",parameters:[{name:"@kind",value:"journal"},{name:"@pk",value:n},{name:"@streamKey",value:t},...o?[{name:"@cursor",value:o}]:[]]}).fetchAll(),a=s.sort((m,g)=>m.id.localeCompare(g.id));return {entries:a.map(p),newCursor:a.length>0?a[a.length-1].id:o}},async clear(){let o=await this.readAll();await Promise.all(o.map(s=>e.item(s.id,n).delete()));}}}function D(e,t,r={}){let n=r.partitionKey??"lock",o=r.holderId??`holder-${Math.random().toString(36).slice(2,10)}`,s=r.now,a=r.ttlMs??3e4;function m(){let i=s?.()??new Date;return {id:t,pk:n,kind:"lock",held:true,holderId:o,expiresAt:new Date(i.getTime()+a).toISOString(),updatedAt:i.toISOString()}}function g(i){return {...i??{id:t,pk:n,kind:"lock"},kind:"lock",held:false,holderId:o,expiresAt:null,updatedAt:b(s)}}async function k(){try{return (await e.item(t,n).read()).resource??null}catch(i){if(c(i,404))return null;throw i}}function S(i){return i?.held?i.expiresAt?Date.parse(i.expiresAt)>(s?.()??new Date).getTime():true:false}return {async tryAcquire(){let i=await k(),A=m();if(i){if(S(i))return null;try{await e.item(t,n).replace(A,i._etag?{accessCondition:{type:"IfMatch",condition:i._etag}}:void 0);}catch(u){if(c(u,412)||c(u,409))return null;throw u}}else try{await e.items.create(A);}catch(u){if(c(u,409))return null;throw u}return async()=>{let u=await k();if(!u)return;let w=g(u);try{await e.item(t,n).replace(w,u._etag?{accessCondition:{type:"IfMatch",condition:u._etag}}:void 0);}catch{}}}}}function M(e){return new TextDecoder().decode(e)}function P(e,t={}){return {async read(r){if(!await e.getBlobClient(r).exists())return null;let n=await e.getBlobClient(r).downloadToBuffer();return M(n)},async write(r,n){await e.getBlockBlobClient(r).upload(n,new TextEncoder().encode(n).byteLength,{blobHTTPHeaders:{blobContentType:t.defaultContentType??"application/json; charset=utf-8"}});},exists(r){return e.getBlobClient(r).exists()},async remove(r){await e.getBlobClient(r).deleteIfExists();},async readBytes(r){return await e.getBlobClient(r).exists()?await e.getBlobClient(r).downloadToBuffer():null},async writeBytes(r,n){await e.getBlockBlobClient(r).upload(n,n.byteLength,{blobHTTPHeaders:{blobContentType:t.defaultContentType??"application/octet-stream"}});},async listKeys(r=""){let n=[];for await(let o of e.listBlobsFlat({prefix:r}))n.push(o.name);return n.sort()},async stat(r){if(!await e.getBlobClient(r).exists())return null;let n=await e.getBlobClient(r).getProperties();return {key:r,size:Number(n.contentLength??0),updatedAt:n.lastModified?.toISOString(),contentType:n.contentType}},keyRef(r){return t.keyRef?.(r)??{kind:"azure-blob-key",value:r}}}}function C(e){if(!e||typeof e!="object")return;let t=e;if(typeof t.statusCode=="number")return t.statusCode;if(typeof t.code=="number")return t.code}function y(e){let t=JSON.stringify(e),r=globalThis.Buffer;if(r)return r.from(t,"utf-8").toString("base64");if(typeof btoa=="function")return btoa(t);throw new Error("No base64 encoder available in this runtime")}function f(e){let t=e??"",r=globalThis.Buffer;if(r)return JSON.parse(r.from(t,"base64").toString("utf-8"));if(typeof atob=="function")return JSON.parse(atob(t));throw new Error("No base64 decoder available in this runtime")}function d(e,t){return (e??t()).toISOString()}function v(e,t){return {id:String(e.messageId??""),body:f(e.messageText),enqueuedAt:d(e.insertedOn??e.insertionTime,t),attempt:Number(e.dequeueCount??0)}}function h(e,t){return {id:String(e.messageId??""),body:f(e.messageText),enqueuedAt:d(e.insertedOn??e.insertionTime,t),attempt:Number(e.dequeueCount??0),leaseToken:String(e.popReceipt??""),leaseExpiresAt:d(e.nextVisibleOn,t)}}function R(e,t={}){let r=t.now??(()=>new Date);return {async enqueue(n){let o=await e.sendMessage(y(n));return {id:String(o.messageId??""),body:n,enqueuedAt:d(o.insertionTime,r),attempt:0}},async lease(n){return (await e.receiveMessages({numberOfMessages:n?.max,visibilityTimeout:n?.visibilityMs?Math.max(1,Math.ceil(n.visibilityMs/1e3)):void 0})).receivedMessageItems.map(s=>h(s,r))},async ack(n,o){try{return await e.deleteMessage(n,o),!0}catch(s){if(C(s)===404)return false;throw s}},async nack(n,o,s){try{if(s?.dead){if(!t.deadLetterQueueClient)return !1;let a={messageId:n,reason:s.reason??null};return await t.deadLetterQueueClient.sendMessage(y(a)),await e.deleteMessage(n,o),!0}return await e.updateMessage(n,o,y({requeued:!0}),0),!0}catch(a){if(C(a)===404)return false;throw a}},async peekActive(n=""){return (await e.peekMessages({numberOfMessages:32})).peekedMessageItems.map(s=>v(s,r)).filter(s=>!n||s.id.startsWith(n))},async peekDeadLetter(n=""){return t.deadLetterQueueClient?(await t.deadLetterQueueClient.peekMessages({numberOfMessages:32})).peekedMessageItems.map(s=>{let a=f(s.messageText);return {id:String(s.messageId??""),body:a,enqueuedAt:d(s.insertedOn??s.insertionTime,r),attempt:Number(s.dequeueCount??0),reason:typeof a.reason=="string"?a.reason:void 0}}).filter(s=>!n||s.id.startsWith(n)):[]}}}export{B as a,x as b,D as c,P as d,R as e};//# sourceMappingURL=chunk-S44QZUDX.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-S44QZUDX.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {b}from'./chunk-BQS3EIEK.js';function p(t){return typeof t.journalStorage=="function"}function s(t){return typeof t.whatToRun=="string"?t.whatToRun.startsWith("b64:")?b(t.whatToRun).value:t.whatToRun:t.whatToRun.value}function c(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function f(t){let a=t.reduce((r,u)=>r+u.length,0),o=new Uint8Array(a),n=0;for(let r of t)o.set(r,n),n+=r.length;return o}export{p as a,s as b,c,f as d};//# sourceMappingURL=chunk-SGV7PU4H.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-SGV7PU4H.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
function k(o){if(o==null||typeof o!="object")return JSON.stringify(o);if(Array.isArray(o))return `[${o.map(k).join(",")}]`;let r=o;return `{${Object.keys(r).sort().map(u=>`${JSON.stringify(u)}:${k(r[u])}`).join(",")}}`}function _(o,r){let S=r>>>0;for(let u=0;u<o.length;u++)S^=o.charCodeAt(u),S=Math.imul(S,16777619)>>>0;return S}function K(o){let r=k(o),S=_(r,2166136261),u=_(r,3735928559),h=_(r,19088743),s=_(r,4277009102);return [S,u,h,s].map(i=>i.toString(16).padStart(8,"0")).join("")}function J(o){function r(s){return `${o}:blob:${s}`}let S=new TextEncoder;function u(s){if(typeof btoa=="function"){let i="";for(let n=0;n<s.length;n++)i+=String.fromCharCode(s[n]);return btoa(i)}return ""}function h(s){if(typeof atob=="function"){let i=atob(s),n=new Uint8Array(i.length);for(let a=0;a<i.length;a++)n[a]=i.charCodeAt(a);return n}return new Uint8Array}return {read(s){return globalThis.localStorage.getItem(r(s))},write(s,i){globalThis.localStorage.setItem(r(s),i);},exists(s){return globalThis.localStorage.getItem(r(s))!==null},remove(s){globalThis.localStorage.removeItem(r(s));},readBytes(s){let i=globalThis.localStorage.getItem(r(s));if(i===null)return null;try{let n=JSON.parse(i);if(n&&n.__kind==="bytes-b64"&&typeof n.data=="string")return h(n.data)}catch{}return S.encode(i)},writeBytes(s,i){let n=JSON.stringify({__kind:"bytes-b64",data:u(i)});globalThis.localStorage.setItem(r(s),n);},listKeys(s){let i=r(s??""),n=[];for(let a=0;a<globalThis.localStorage.length;a++){let l=globalThis.localStorage.key(a);l&&l.startsWith(i)&&n.push(l.slice(r("").length));}return n.sort()},stat(s){let i=globalThis.localStorage.getItem(r(s));if(i===null)return null;let n=S.encode(i).byteLength;try{let a=JSON.parse(i);a&&a.__kind==="bytes-b64"&&typeof a.data=="string"&&(n=h(a.data).byteLength);}catch{}return {key:s,size:n}}}}var N=":scratch-marker",C=":scratch-config",A=":scratch:",L=1440*60*1e3,O=720*60*1e3,B=200;function $(o,r){if(!o)return r;let S=o.replace(/[^A-Za-z0-9._-]/g,"_");return S.length>0?S:r}function W(o){let r=`${o}${N}`,S=`${o}${C}`,u=t=>`${o}${A}${t}`,h=t=>`${o}${A}${t}:__ts`,s=globalThis.localStorage.getItem(r)===null;if(s)try{globalThis.localStorage.setItem(r,`scratch-store
|
|
2
|
+
${new Date().toISOString()}`);}catch{}function i(){let t=globalThis.localStorage.getItem(S);if(t===null)return {};try{let e=JSON.parse(t);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return {}}}function n(t){try{globalThis.localStorage.setItem(S,JSON.stringify(t));}catch{}}if(s){let t=i();typeof t["retention.lastSweepAt"]!="number"&&(t["retention.lastSweepAt"]=Date.now(),n(t));}function a(){if(globalThis.localStorage.getItem(r)===null)return;let t=i(),e=typeof t["retention.maxAgeMs"]=="number"?t["retention.maxAgeMs"]:L,c=typeof t["retention.sweepIntervalMs"]=="number"?t["retention.sweepIntervalMs"]:O;if(e<=0||c<=0)return;let g=typeof t["retention.lastSweepAt"]=="number"?t["retention.lastSweepAt"]:0,y=Date.now();if(y-g<c)return;t["retention.lastSweepAt"]=y,n(t);let f=y,m=`${o}${A}`,b=[];for(let p=0;p<globalThis.localStorage.length;p++){let w=globalThis.localStorage.key(p);w&&w.startsWith(m)&&!w.endsWith(":__ts")&&b.push(w);}for(let p of b){if(Date.now()-f>B)break;let w=globalThis.localStorage.getItem(`${p}:__ts`),I=w===null?0:Number(w);if(Number.isFinite(I)&&I>0&&y-I>e){try{globalThis.localStorage.removeItem(p);}catch{}try{globalThis.localStorage.removeItem(`${p}:__ts`);}catch{}}}}function l(t,e){let c=$(t,"scratch"),g=$(e,".json"),y=g.startsWith(".")?g:`.${g}`,f=Math.random().toString(36).slice(2,10);return `${c}-${Date.now()}-${f}${y}`}function d(t,e){globalThis.localStorage.setItem(u(t),e),globalThis.localStorage.setItem(h(t),String(Date.now()));}return {read(t){return globalThis.localStorage.getItem(u(t))},write(t,e){d(t,e);try{a();}catch{}},exists(t){return globalThis.localStorage.getItem(u(t))!==null},remove(t){try{globalThis.localStorage.removeItem(u(t));}catch{}try{globalThis.localStorage.removeItem(h(t));}catch{}},readBytes(t){let e=globalThis.localStorage.getItem(u(t));return e===null?null:new TextEncoder().encode(e)},writeBytes(t,e){let c="";for(let g=0;g<e.length;g++)c+=String.fromCharCode(e[g]);d(t,c);try{a();}catch{}},stat(t){let e=globalThis.localStorage.getItem(u(t));if(e===null)return null;let c=globalThis.localStorage.getItem(h(t)),g=c===null?null:Number(c);return {key:t,size:new TextEncoder().encode(e).byteLength,updatedAt:g!==null&&Number.isFinite(g)?new Date(g).toISOString():void 0}},listKeys(t){let e=`${o}${A}`,c=[];for(let g=0;g<globalThis.localStorage.length;g++){let y=globalThis.localStorage.key(g);if(y&&y.startsWith(e)&&!y.endsWith(":__ts")){let f=y.slice(e.length);(!t||f.startsWith(t))&&c.push(f);}}return c.sort()},getUniqueKey(t,e){return l(t,e)},create(t,e,c){let g=l(e,c);d(g,t);try{a();}catch{}return g},keyRef(t){return {kind:"local-storage-scratch",value:t,extra:{prefix:o}}},config:{get(t){return i()[t]??null},set(t,e){let c=i();e==null?delete c[t]:c[t]=e,n(c);}}}}var M=":archive-marker",R=":archive-config",T=":archive:stream:",v=":archive:blob:";function E(o){let r=o.replace(/[^A-Za-z0-9._-]/g,"_");if(!r)throw new Error("Archive segment name cannot be empty after sanitization");return r}function D(o){let r=`${o}${M}`,S=`${o}${R}`,u=n=>`${o}${T}${n}`;if(globalThis.localStorage.getItem(r)===null)try{globalThis.localStorage.setItem(r,`archive-store
|
|
3
|
+
${new Date().toISOString()}`);}catch{}function h(){let n=globalThis.localStorage.getItem(S);if(n===null)return {};try{let a=JSON.parse(n);return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}catch{return {}}}function s(n){try{globalThis.localStorage.setItem(S,JSON.stringify(n));}catch{}}function i(){if(globalThis.localStorage.getItem(r)===null)return;let n=h(),a=typeof n["retention.maxAgeMs"]=="number"?n["retention.maxAgeMs"]:0,l=typeof n["retention.sweepIntervalMs"]=="number"?n["retention.sweepIntervalMs"]:0;if(a<=0||l<=0)return;let d=typeof n["retention.lastSweepAt"]=="number"?n["retention.lastSweepAt"]:0,t=Date.now();if(t-d<l)return;n["retention.lastSweepAt"]=t,s(n);let e=`${o}${T}`;for(let c=0;c<globalThis.localStorage.length;c++){let g=globalThis.localStorage.key(c);if(!g||!g.startsWith(e))continue;let y=globalThis.localStorage.getItem(g);if(y)try{let f=JSON.parse(y),m=f.filter(b=>typeof b.__ts!="number"||t-b.__ts<=a);m.length!==f.length&&globalThis.localStorage.setItem(g,JSON.stringify(m));}catch{}}}return {stream(n){let a=E(n),l=u(a);function d(){let e=globalThis.localStorage.getItem(l);if(!e)return [];try{return JSON.parse(e)}catch{return []}}function t(e){try{globalThis.localStorage.setItem(l,JSON.stringify(e));}catch{}}return {append(e){let c={id:globalThis.crypto.randomUUID(),payload:e,__ts:Date.now()},g=d();g.push(c),t(g);try{i();}catch{}return {id:c.id,payload:c.payload}},readAll(){return d().map(e=>({id:e.id,payload:e.payload}))},readAfter(e){let c=d();if(!e){let m=c.map(b=>({id:b.id,payload:b.payload}));return {entries:m,newCursor:m.length>0?m[m.length-1].id:null}}let g=c.findIndex(m=>m.id===e),f=(g===-1?c:c.slice(g+1)).map(m=>({id:m.id,payload:m.payload}));return {entries:f,newCursor:f.length>0?f[f.length-1].id:e}},clear(){try{globalThis.localStorage.removeItem(l);}catch{}}}},blob(n){let a=E(n),l=J(`${o}${v}${a}`);return {read:d=>l.read(d),write:(d,t)=>{l.write(d,t);try{i();}catch{}},exists:d=>l.exists(d),remove:d=>l.remove(d),readBytes:l.readBytes?d=>l.readBytes(d):void 0,writeBytes:l.writeBytes?(d,t)=>{l.writeBytes(d,t);try{i();}catch{}}:void 0,listKeys:d=>l.listKeys(d),stat:l.stat?d=>l.stat(d):void 0}},listStreams(n){let a=`${o}${T}`,l=[];for(let d=0;d<globalThis.localStorage.length;d++){let t=globalThis.localStorage.key(d);if(!t||!t.startsWith(a))continue;let e=t.slice(a.length);(!n||e.startsWith(n))&&l.push(e);}return l.sort()},listBlobs(n){let a=`${o}${v}`,l=new Set;for(let d=0;d<globalThis.localStorage.length;d++){let t=globalThis.localStorage.key(d);if(!t||!t.startsWith(a))continue;let e=t.slice(a.length),c=e.indexOf(":"),g=c===-1?e:e.slice(0,c);(!n||g.startsWith(n))&&l.add(g);}return Array.from(l).sort()},config:{get(n){return h()[n]??null},set(n,a){let l=h();a==null?delete l[n]:l[n]=a,s(l);}}}}function j(o){function r(S){return `${o}:kv:${S}`}return {read(S){let u=globalThis.localStorage.getItem(r(S));if(u===null)return null;try{return JSON.parse(u)}catch{return null}},write(S,u){globalThis.localStorage.setItem(r(S),JSON.stringify(u));},delete(S){globalThis.localStorage.removeItem(r(S));},listKeys(S){let u=r(S??""),h=[];for(let s=0;s<globalThis.localStorage.length;s++){let i=globalThis.localStorage.key(s);i!==null&&i.startsWith(u)&&h.push(i.slice(r("").length));}return h}}}function H(o){function r(){let u=globalThis.localStorage.getItem(o);if(!u)return [];try{return JSON.parse(u)}catch{return []}}function S(u){globalThis.localStorage.setItem(o,JSON.stringify(u));}return {readAllEntries(){return r()},appendEntry(u){let h=r();h.push(u),S(h);},generateId(){return globalThis.crypto.randomUUID()}}}export{K as a,J as b,W as c,D as d,j as e,H as f};//# sourceMappingURL=chunk-TSN3RTXT.js.map
|
|
4
|
+
//# sourceMappingURL=chunk-TSN3RTXT.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import {c}from'./chunk-SGV7PU4H.js';function A(h){let r=new Map,a=new Map,d=new Map,I=0,b=null;function g(e){let t=JSON.stringify(e);return I++,`id: ${I}
|
|
2
|
+
data: ${t}
|
|
3
|
+
|
|
4
|
+
`}function C(e){let t=e;try{t.flushHeaders?.();}catch{}try{t.flush?.();}catch{}try{t.socket?.setNoDelay?.(!0);}catch{}try{t.socket?.uncork?.();}catch{}}function y(e,t){let s=r.get(e);if(s&&!(t&&s.res!==t)){r.delete(e),w();try{h.onSseClientDisconnected?.(e);}catch{}try{s.res.end();}catch{}}}function v(e,t,s){let n=r.get(e);n&&y(e,n.res),r.set(e,{res:t,subscribedChatCardIds:s??new Set});}function f(e,t){let s=r.get(e);if(!s)return;let n=g(t);try{s.res.write(n),C(s.res);}catch{y(e,s.res);}}function c(){let e=new Set;for(let t of r.values())for(let s of t.subscribedChatCardIds)e.add(s);return Array.from(e)}function l(e){let t=a.has(e)?a.get(e):null,{cursor:s}=h.chatStorage.readAfter(e,t),n=h.chatStorage.isProcessing(e),o=n!==(d.get(e)??false),S=s!==t;return S&&a.set(e,s),d.set(e,n),S||o}function u(e,t){let s=h.readChatRecords(e),n=Date.now();return {kind:"card_chats",cardId:e,sentAt:new Date(n).toISOString(),sentAtMs:n,messages:s.map(o=>({role:String(o.role||"system"),text:String(o.text||""),files:Array.isArray(o.files)?o.files:[]})),receiving:t,processing:h.chatStorage.isProcessing(e)}}function i(e,t=true){let s={kind:"notification-batch",notifications:[u(e,t)]};for(let[n,o]of r.entries())o.subscribedChatCardIds.has(e)&&f(n,s);}function w(){c().length>0||(b&&(clearInterval(b),b=null),a.clear(),d.clear());}function p(){if(b)return;let e=()=>{let t=c();if(t.length===0){w();return}let s=new Set(t);for(let n of Array.from(a.keys()))s.has(n)||a.delete(n);for(let n of Array.from(d.keys()))s.has(n)||d.delete(n);for(let n of t)l(n)&&i(n,true);};e(),b=setInterval(e,1e3);}function k(e,t){let s=r.get(e);if(!s)return false;s.subscribedChatCardIds.add(t);let{cursor:n}=h.chatStorage.readAfter(t,null);return a.set(t,n),d.set(t,h.chatStorage.isProcessing(t)),p(),f(e,{kind:"notification-batch",notifications:[u(t,true)]}),true}function m(e,t){let s=r.get(e);return s?(s.subscribedChatCardIds.delete(t),c().includes(t)||(a.delete(t),d.delete(t)),w(),true):false}function R(e){if(!e||typeof e!="object")return false;let t=e.kind;return t==="card_chats"||t==="chat_messages"}function P(e){if(!e||e.length===0)return;let t=[],s=new Set;for(let n of e)R(n)&&typeof n.cardId=="string"?s.add(String(n.cardId)):t.push(n);if(t.length>0){let n={kind:"notification-batch",notifications:t};for(let o of r.keys())f(o,n);}for(let n of s)i(n,true);}return {size:()=>r.size,has:e=>r.has(e),get:e=>r.get(e),buildFrame:g,flushTransport:C,register:v,disconnect:y,writeFrame:f,subscribeChat:k,unsubscribeChat:m,broadcastNotificationBatch:P,broadcastCardChats:i}}function D(h){let{sseHub:r,corsHeaders:a,json:d,buildPublishedRuntimePayload:I,onSseClientConnected:b,onChannelSubscribed:g,onChannelUnsubscribed:C}=h;function y(f,c,l,u,i){if(!r.has(c)){d(f,404,{error:`SSE client not connected: ${c}`});return}i?g?.(c,l,u):C?.(c,l,u),d(f,200,{ok:true,clientId:c,channelName:l,...u.cardId?{cardId:u.cardId}:{},subscribed:i});}async function v(f,c,l){let u=r.get(l),i=u?new Set(u.subscribedChatCardIds):new Set;c.writeHead(200,{...a,"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),r.flushTransport(c),r.register(l,c,i);let w=await I(),p=r.buildFrame(w);c.write(p);try{b?.(l,m=>{r.writeFrame(l,m);});}catch{}let k=setInterval(()=>{try{c.write(`: keepalive
|
|
5
|
+
|
|
6
|
+
`);}catch{}},15e3);f.on("close",()=>{clearInterval(k),r.disconnect(l,c);});}return {handleChannelSubscription:y,handleSse:v}}function T(h){let{apiBasePath:r,json:a,readJsonBody:d,initBoardAndSetup:I,bootstrapBoard:b,boardContexts:g,publishPersistedStateSnapshot:C,upsertCardsFromSource:y,sseHub:v}=h,{handleSse:f,handleChannelSubscription:c$1}=D(h);async function l(u,i,w){let p=u.method||"GET",k=w,m=k.pathname;try{if(p==="GET"&&m===`${r}/sse`){await I();let s=String(k.searchParams.get("clientId")||"").trim();if(!s)return a(i,400,{error:"clientId query param is required for SSE"}),!0;await f(u,i,s);for(let n=0;n<g.length;n++)await C(g[n]),await y(g[n],n),await C(g[n]);return !0}let R=m.match(new RegExp(`^${c(r)}/cards/([^/]+)/chats/subscribe-sse$`));if(p==="POST"&&R){await b();let s=decodeURIComponent(R[1]),n=await d(u),o=typeof n?.clientId=="string"?n.clientId.trim():"";return o?v.subscribeChat(o,s)?(a(i,200,{ok:!0,clientId:o,cardId:s,subscribed:!0}),!0):(a(i,404,{error:`SSE client not connected: ${o}`}),!0):(a(i,400,{error:"clientId is required"}),!0)}let P=m.match(new RegExp(`^${c(r)}/cards/([^/]+)/chats/unsubscribe-sse$`));if(p==="POST"&&P){await b();let s=decodeURIComponent(P[1]),n=await d(u),o=typeof n?.clientId=="string"?n.clientId.trim():"";return o?v.unsubscribeChat(o,s)?(a(i,200,{ok:!0,clientId:o,cardId:s,subscribed:!1}),!0):(a(i,404,{error:`SSE client not connected: ${o}`}),!0):(a(i,400,{error:"clientId is required"}),!0)}let e=m.match(new RegExp(`^${c(r)}/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(p==="POST"&&e){await b();let s=decodeURIComponent(e[1]),n=e[2]==="subscribe",o=await d(u),S=typeof o?.clientId=="string"?o.clientId.trim():"";return S?(c$1(i,S,s,{},n),!0):(a(i,400,{error:"clientId is required"}),!0)}let t=m.match(new RegExp(`^${c(r)}/cards/([^/]+)/watch-channel/([^/]+)/(subscribe|unsubscribe)-sse$`));if(p==="POST"&&t){await b();let s=decodeURIComponent(t[1]),n=decodeURIComponent(t[2]),o=t[3]==="subscribe",S=await d(u),H=typeof S?.clientId=="string"?S.clientId.trim():"";return H?(c$1(i,H,n,{cardId:s},o),!0):(a(i,400,{error:"clientId is required"}),!0)}return !1}catch(R){let P=R?.statusCode||500;return a(i,P,{error:String(R?.message||R)}),true}}return {handleWatchersRoutes:l,handleSse:f,handleChannelSubscription:c$1}}export{A as a,T as b};//# sourceMappingURL=chunk-WHDEBJLT.js.map
|
|
7
|
+
//# sourceMappingURL=chunk-WHDEBJLT.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a,b}from'./chunk-ZJ5M5COT.js';function w(c){let{apiBasePath:p,json:t,readJsonBody:m,initBoardAndSetup:d,createMcpWebhookToolRegistry:R}=c;async function l(i,r,y){let g=i.method||"GET",b$1=y.pathname;try{if(g==="POST"&&b$1===`${p}/mcp-webhooks`){await d();let o=await m(i),s=typeof o.tool=="string"?o.tool.trim():"",f=o.args&&typeof o.args=="object"&&!Array.isArray(o.args)?o.args:{};if(!s)return t(r,400,{error:"tool is required"}),!0;try{let e=await a(s,f,R());if(e&&typeof e=="object"&&!Array.isArray(e)){let n=e;if(n.status==="fail")return t(r,400,{error:b(e,"Request failed")}),!0;if(n.status==="error")return t(r,500,{error:b(e,"Internal error")}),!0}t(r,200,e);}catch(e){let n=typeof e?.statusCode=="number"?Number(e.statusCode):500,h=e instanceof Error?e.message:String(e);t(r,n,{error:h});}return !0}return !1}catch(o){let s=o?.statusCode||500;return t(r,s,{error:String(o?.message||o)}),true}}return {handleWebhooksApi:l}}export{w as a};//# sourceMappingURL=chunk-XYN5D3GL.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-XYN5D3GL.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-VXJHBWK3.js';function d(a,e){return e?{...a,...e.pollIntervalMs!=null?{pollIntervalMs:e.pollIntervalMs}:{},...e.visibilityMs!=null?{visibilityMs:e.visibilityMs}:{},...e.concurrency!=null?{concurrency:e.concurrency}:{},...e.maxAttempts!=null?{maxAttempts:e.maxAttempts}:{}}:a}function p(a,e,c,s){return {id:a,async lease(o){return (await Promise.resolve(e.leaseRequests(o))).map(r=>({id:r.messageId,attempt:r.attempt,message:r.request,ack:()=>Promise.resolve(e.ackRequest(r.messageId,r.leaseToken)),nack:t=>Promise.resolve(e.nackRequest(r.messageId,r.leaseToken,t))}))},async handle(o){await c(o.args,o);},onError:s?(o,u)=>s(o,u.attempt,u.message):void 0}}function l(a,e,c,s){return {id:a,async lease(o){return (await Promise.resolve(e.lease(o))).map(r=>({id:r.id,attempt:r.attempt,message:r.body,ack:()=>Promise.resolve(e.ack(r.id,r.leaseToken)),nack:t=>Promise.resolve(e.nack(r.id,r.leaseToken,t))}))},async handle(){await c();},onError:s?(o,u)=>s(o,u.attempt):void 0}}function y(a$1){let e=a$1.logger??{info(){},warn(){},error(){}},c=a$1.boardAdapter,s=a$1.runtime.queueLaneTuning??{},o=c.processAccumulatedStore(),u=c.chatAgentStore(),r=[];if(r.push(d(l("process-accumulated",o,async()=>{let t=await a$1.runtime.processAccumulatedLane();if(t.status!=="success")throw new Error(t.error||`processAccumulatedLane returned ${t.status}`)},(t,n)=>{e.error(`[board-server] queued process-accumulated failed for ${a$1.boardId} (attempt ${n}): ${String(t&&t.message||t)}`);}),s.processAccumulated)),r.push(d(p("chat-agent",u,async(t,n)=>{await a$1.runtime.handleChatAgentRequest(n);},(t,n,i)=>{let m=typeof i.args?.cardId=="string"?i.args.cardId:"";e.error(`[board-server] queued chat-agent failed for ${a$1.boardId}${m?`/${m}`:""} (attempt ${n}): ${String(t&&t.message||t)}`);}),s.chatAgent)),a$1.executeTaskExecutorRequest){let t=c.boardWorkerStore();r.push(d(p("task-executor",t,a$1.executeTaskExecutorRequest,(n,i)=>{e.error(`[board-server] queued board-worker failed for ${a$1.boardId} (attempt ${i}): ${String(n&&n.message||n)}`);}),s.taskExecutor));}return a(r)}export{y as a};//# sourceMappingURL=chunk-YGALANRO.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-YGALANRO.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
async function u(t,i,o){let s=o[t];if(!s)throw Object.assign(new Error(`Unknown MCP tool: ${t}`),{statusCode:400});let r=await s(i);if(r&&typeof r=="object"&&!Array.isArray(r)){let n=r,e=n.status;if(e==="success")return Object.prototype.hasOwnProperty.call(n,"data")?r:{status:"success",data:{}};if(e==="fail"||e==="error")return r}return {status:"success",data:r}}function f(t,i){if(!t||typeof t!="object"||Array.isArray(t))return i;let o=t;if(typeof o.error=="string"&&o.error.trim())return o.error;if(o.step==="validate"){let s=o.validation;if(s&&typeof s=="object"&&!Array.isArray(s)){let n=s.data;if(n&&typeof n=="object"&&!Array.isArray(n)){let e=n.issues;if(Array.isArray(e)){let c=e.find(d=>typeof d=="string"&&d.trim());if(typeof c=="string")return `Validation failed: ${c}`}let a=n.errors;if(Array.isArray(a)&&a.length>0)return "Validation failed"}}return "Validation failed"}return i}export{u as a,f as b};//# sourceMappingURL=chunk-ZJ5M5COT.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-ZJ5M5COT.js.map
|