yaml-flow 8.11.7 → 8.11.8

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.
Files changed (74) hide show
  1. package/browser/asset-integrity.json +5 -5
  2. package/browser/live-cards.schema.json +4 -0
  3. package/browser/server-runtime-controlface.js +4 -4
  4. package/examples/board/cards/card-rebalance-sim.json +4 -1
  5. package/lib/board-live-cards-mcp.cjs +1 -1
  6. package/lib/board-live-cards-mcp.js +1 -1
  7. package/lib/board-live-cards-node.cjs +6 -6
  8. package/lib/board-live-cards-node.js +6 -6
  9. package/lib/board-live-cards-public.cjs +1 -1
  10. package/lib/board-live-cards-public.js +1 -1
  11. package/lib/board-live-cards-server-runtime.cjs +1 -1
  12. package/lib/board-live-cards-server-runtime.js +1 -1
  13. package/lib/board-livegraph-runtime/index.cjs +1 -1
  14. package/lib/board-livegraph-runtime/index.js +1 -1
  15. package/lib/card-compute/index.cjs +1 -1
  16. package/lib/card-compute/index.d.cts +6 -0
  17. package/lib/card-compute/index.d.ts +6 -0
  18. package/lib/card-compute/index.js +1 -1
  19. package/lib/card-store-public.cjs +1 -1
  20. package/lib/card-store-public.js +1 -1
  21. package/lib/card-validation.cjs +1 -1
  22. package/lib/card-validation.js +1 -1
  23. package/lib/{chunk-NOAERAOE.cjs → chunk-36KKCQVE.cjs} +2 -2
  24. package/lib/chunk-3DWVFRQD.cjs +3 -0
  25. package/lib/chunk-3SLSRX6Q.js +3 -0
  26. package/lib/{chunk-EHREWADE.js → chunk-4NWVZ7AW.js} +2 -2
  27. package/lib/chunk-543ZEGP7.cjs +2 -0
  28. package/lib/{chunk-YAPTL2MP.cjs → chunk-6SPWFJRG.cjs} +2 -2
  29. package/lib/{chunk-HKPVF5UI.js → chunk-BA25VGJP.js} +3 -3
  30. package/lib/chunk-BRYV6CDD.js +3 -0
  31. package/lib/chunk-EGZPROOH.cjs +3 -0
  32. package/lib/{chunk-GHUW6P4G.cjs → chunk-ESTFYRHF.cjs} +2 -2
  33. package/lib/{chunk-52XPRCZC.cjs → chunk-HOS2ZUFZ.cjs} +2 -2
  34. package/lib/chunk-JOQWJ3VR.cjs +2 -0
  35. package/lib/chunk-MRESV3MD.js +2 -0
  36. package/lib/chunk-MRIFSG7L.cjs +3 -0
  37. package/lib/{chunk-6M3RIGUH.js → chunk-NN52BT3Q.js} +2 -2
  38. package/lib/{chunk-TUQ6JBER.cjs → chunk-OR6B2H2Y.cjs} +3 -3
  39. package/lib/{chunk-I3ZOFU3F.js → chunk-PIPXFUEA.js} +2 -2
  40. package/lib/chunk-REZO2QJD.js +3 -0
  41. package/lib/{chunk-23PEDGFN.js → chunk-ROIYEFSE.js} +2 -2
  42. package/lib/chunk-UJQ7IML5.js +2 -0
  43. package/lib/chunk-YOY2JM5N.js +2 -0
  44. package/lib/chunk-ZV35WD6K.cjs +2 -0
  45. package/lib/cloud-storage.cjs +1 -1
  46. package/lib/cloud-storage.js +1 -1
  47. package/lib/continuous-event-graph/index.cjs +1 -1
  48. package/lib/continuous-event-graph/index.js +1 -1
  49. package/lib/firestore-storage/index.cjs +1 -1
  50. package/lib/firestore-storage/index.js +1 -1
  51. package/lib/index.cjs +2 -2
  52. package/lib/index.js +1 -1
  53. package/lib/localstorage-storage/index.cjs +1 -1
  54. package/lib/localstorage-storage/index.js +1 -1
  55. package/lib/server-runtime/index.cjs +1 -1
  56. package/lib/server-runtime/index.js +1 -1
  57. package/lib/server-runtime-controlface/index.cjs +1 -1
  58. package/lib/server-runtime-controlface/index.js +1 -1
  59. package/lib/server-runtime-core/index.cjs +1 -1
  60. package/lib/server-runtime-core/index.js +1 -1
  61. package/package.json +1 -1
  62. package/schema/live-cards.schema.json +4 -0
  63. package/lib/chunk-2LGCYN35.js +0 -2
  64. package/lib/chunk-3XPY7CCM.cjs +0 -3
  65. package/lib/chunk-ATOQP3BD.js +0 -2
  66. package/lib/chunk-CPJXGK2T.cjs +0 -2
  67. package/lib/chunk-J7KE7SPA.cjs +0 -2
  68. package/lib/chunk-K5TEZRZK.cjs +0 -3
  69. package/lib/chunk-QBEQL4TL.cjs +0 -2
  70. package/lib/chunk-QEHKMLHA.cjs +0 -3
  71. package/lib/chunk-RKLEBQUG.js +0 -3
  72. package/lib/chunk-WGYS2L4V.js +0 -2
  73. package/lib/chunk-X32SJDLT.js +0 -3
  74. package/lib/chunk-YT76JNKE.js +0 -3
@@ -0,0 +1,3 @@
1
+ import {q}from'./chunk-MNEOJWPS.js';import {b as b$1}from'./chunk-FW4363Y4.js';import $ from'ajv-formats';import {createRequire}from'module';var b={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://nsreehari.github.io/boards/live-cards.schema.json",definitions:{bind_ref:{description:"A card data path reference, e.g. 'card_data.raw_quotes' or 'requires.upstream'",type:"string",pattern:"^(card_data|requires|fetched_sources|computed_values)(\\.|$)"},bind_or_literal:{description:"A literal value or a bind reference object",oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"array"},{type:"object",properties:{bind:{$ref:"#/definitions/bind_ref"}},required:["bind"]}]},compute_expr:{description:"A declarative JSON compute expression",type:"object",required:["fn"],properties:{fn:{type:"string",description:"Function name from the built-in vocabulary",enum:["sum","avg","min","max","count","first","last","add","sub","mul","div","round","abs","mod","gt","gte","lt","lte","eq","neq","if","and","or","not","concat","upper","lower","template","filter","pluck","map","sort","slice","flat","unique","group","get","default","now","diff_days","format_date"]},input:{description:"card_data.path, literal, array of inputs, or nested compute_expr",oneOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"array"},{$ref:"#/definitions/compute_expr"}]},field:{type:"string",description:"For pluck/sum/group \u2014 the object key to extract"},where:{$ref:"#/definitions/compute_expr",description:"For filter \u2014 predicate expression ($ = current item)"},cond:{$ref:"#/definitions/compute_expr",description:"For if \u2014 condition expression"},then:{description:"For if \u2014 value when cond is truthy"},else:{description:"For if \u2014 value when cond is falsy"},format:{type:"string",description:"For format_date \u2014 date format string"}}},meta:{type:"object",properties:{title:{type:"string"},presentation:{type:"object",description:"Semantic presentation hints authored on the card, expressed from the user's perception of the card on the Main Canvas. Content shape is inferred from view.elements[].kind; runtime placement and live drag/resize coordinates are frontend-managed and must not be authored into card JSON.",properties:{prominence:{type:"string",default:"standard",description:"How much the user should care about this card / how much attention it earns. Default: standard; omit unless a non-standard value is needed.",enum:["glance","standard","feature","spotlight"]},footprint:{type:"string",default:"standard",description:"How much room the card wants to render well, independent of attention. Default: standard; omit unless a non-standard value is needed.",enum:["compact","standard","wide","large"]},resizable:{type:"boolean",default:true,description:"Whether the user may resize this card at runtime. Default: true; omit unless it must be false."}},additionalProperties:true},tags:{type:"array",items:{type:"string"}}},additionalProperties:true},__private:{description:"Control-plane-owned private state. Stripped entirely from all regular /mcp read responses. Writable only via 'setstate.card-private' and 'manage.admin-upsert-card'. Agents must never author this field. Keys inside use plain names (no leading underscores).",type:"object",additionalProperties:true},requires:{type:"array",items:{type:"string"},description:"IDs of upstream nodes this node depends on"},provides:{type:"array",items:{type:"object",required:["bindTo","ref"],properties:{bindTo:{type:"string",description:"Token name published downstream"},ref:{type:"string",description:"Path to read value from (card_data.*, requires.*, fetched_sources.*, computed_values.*)"}}},description:"Explicit bindings exposing computed or card_data values downstream as named tokens"},compute_step:{description:"A single ordered compute step: reads card_data.*/requires.*/computed_values.*, writes to computed_values[bindTo]",type:"object",required:["bindTo","expr"],properties:{bindTo:{type:"string",description:"Key in computed_values to write result"},expr:{type:"string",description:"JSONata expression evaluated against { card_data, requires, fetched_sources, computed_values }"}}},source_def:{description:"One source entry. The engine requires 'bindTo' (compute namespace key) and 'outputFile' (delivery signal path). bindTo and outputFile must be unique across all source_defs in a card. Every other property is yours \u2014 add whatever your task-executor needs: kind, url, headers, mailbox, channel, model, query, etc. The full object is passed verbatim as the --in JSON to the executor.",type:"object",required:["bindTo","outputFile"],additionalProperties:true,properties:{bindTo:{type:"string",description:"Key under fetched_sources.* available in compute expressions"},outputFile:{type:"string",description:"Board-relative path the executor writes its JSON result to. Presence of this file signals delivery."},projections:{type:"object",description:"Named data projections from card_data or requires, evaluated before the executor is called. Each key is a ref name; each value is a JSONata expression rooted at card_data or requires. The resolved values are passed to the executor as _projections. fetched_sources, computed_values, and source_defs are not accessible here \u2014 sources run before those exist.",additionalProperties:{type:"string"}},skip_when:{type:"string",description:"JSONata over card_data/requires. Truthy skips this source."},timeout:{type:"integer",minimum:0,default:12e4,description:"Executor/script timeout in ms. Default: 120 000 (2 min)."},script:{type:"string",description:"Legacy direct-run: shell command executed when no .task-executor is registered. stdout is captured as the result."}}},render_element:{type:"object",required:["kind"],properties:{id:{type:"string",description:"Optional element ID for targeted updates"},kind:{enum:["metric","table","editable-table","chart","form","filter","list","notes","todo","alert","narrative","badge","text","markdown","ref","custom","actions"]},label:{type:"string",description:"Heading above this element"},className:{type:"string",description:"Bootstrap grid class, e.g. 'col-12 col-md-6'"},visible:{type:"string",description:"card_data/requires/fetched_sources/computed_values path \u2014 element shown only if truthy"},data:{type:"object",properties:{bind:{$ref:"#/definitions/bind_ref",description:"card_data/requires/fetched_sources/computed_values path to read data from"},writeTo:{$ref:"#/definitions/bind_ref",description:"card_data path for user input (form, filter, todo, notes)"},columns:{type:"array",items:{type:"string"},description:"table: visible columns"},maxRows:{type:"integer",description:"table/list: max rows to display"},sortable:{type:"boolean",default:true,description:"table: enable click-to-sort"},placeholder:{type:"string",description:"Empty-state message"},chartType:{enum:["bar","line","pie","doughnut"]},chartOptions:{type:"object",description:"Chart.js options passthrough"},fields:{type:"object",description:"JSON Schema for form/filter fields"},thresholds:{type:"object",properties:{green:{type:"string"},amber:{type:"string"}}},colorMap:{type:"object",description:"badge: value \u2192 Bootstrap color"},style:{enum:["heading","muted","default"],description:"text: display style"},upload:{type:"boolean",default:true,description:"file-upload: show drop zone (false = read-only file list)"},accept:{type:"array",items:{type:"string"},description:"file-upload: allowed extensions"},multiple:{type:"boolean",default:true,description:"file-upload: allow multiple files"},fileAttach:{type:"boolean",default:false,description:"chat: enable inline file attachments"},fileAccept:{type:"array",items:{type:"string"},description:"chat: allowed attachment extensions"},buttons:{type:"array",description:"actions: button definitions",items:{type:"object",required:["id","label"],properties:{id:{type:"string"},label:{type:"string"},style:{type:"string",description:"Bootstrap button variant, e.g. 'success', 'outline-danger'"},size:{type:"string",default:"sm"},disabled:{oneOf:[{type:"boolean"},{type:"string",description:"card_data/requires/fetched_sources/computed_values path \u2014 truthy = disabled"}]}}}}}}}},view:{type:"object",required:["elements"],properties:{elements:{type:"array",minItems:1,items:{$ref:"#/definitions/render_element"}}}}},title:"LiveCard",description:"A unified card node. Behavior depends on which sections are present (source_defs, compute, view, etc.)",type:"object",required:["id"],additionalProperties:false,properties:{id:{type:"string"},requires:{$ref:"#/definitions/requires"},provides:{$ref:"#/definitions/provides"},meta:{$ref:"#/definitions/meta"},__private:{$ref:"#/definitions/__private"},view:{$ref:"#/definitions/view"},card_data:{type:"object",description:"User editable data on card. Includes uploaded-file metadata maintained by host handlers. Not to be used for card static content.",properties:{files:{type:"array",description:"Optional uploaded-file metadata maintained by host handlers. Stored name is normalized and serial-prefixed (for example 001-my_file.pdf).",items:{type:"object",required:["name","stored_name"],properties:{name:{type:"string",minLength:1},stored_name:{type:"string",minLength:5,maxLength:32,pattern:"^[0-9]{3,}-[a-z0-9._-]+$"},size:{oneOf:[{type:"integer",minimum:0},{type:"null"}]},mime_type:{type:"string"},path:{type:"string",pattern:"^[^\\s]+/files/[0-9]{3,}-[a-z0-9._-]+$"},uploaded_at:{type:"string",format:"date-time"},chat:{type:"boolean",description:"Whether this file entry is associated with a chat interaction"}},additionalProperties:false}}},additionalProperties:true},source_defs:{type:"array",description:"Source entries. Each entry is passed verbatim to the board's .task-executor (registered via init --task-executor) as the --in JSON file. The executor fetches/generates the data and writes JSON to --out. If no executor is registered, the built-in executor runs the entry's 'cli' command directly. Sources gate completion.",items:{$ref:"#/definitions/source_def"}},compute:{type:"array",description:"Ordered array of compute steps. Each reads card_data.*/requires.*/fetched_sources.*/computed_values.* and writes to ephemeral computed_values[bindTo].",items:{$ref:"#/definitions/compute_step"}}}};var v=b$1(q(),1);var N=createRequire(import.meta.url),S=N("./jsonata-sync.cjs"),m=null;var _=/\b(card_data|requires|fetched_sources|computed_values|source_defs)\b/g,E=/^\s*(card_data|requires|fetched_sources|computed_values|source_defs)(\.|$)/;function O(e){let t=new Set,s;for(_.lastIndex=0;(s=_.exec(e))!==null;)t.add(s[1]);return t}function w(e){let t=E.exec(e);return t?t[1]:null}function h(e,t,s,o){try{S(e);}catch(n){let d=n instanceof Error?n.message:String(n);o.push(`${t}: invalid JSONata expression (${d})`);return}let i=O(e);for(let n of i)s.has(n)||o.push(`${t}: disallowed namespace "${n}" in expression`);}function g(e,t,s){if(Array.isArray(e)){e.forEach((i,n)=>{g(i,`${t}/${n}`,s);});return}if(typeof e=="string"){let i=w(e);if(!i)return;new Set(["card_data","requires","computed_values"]).has(i)||s.push(`${t}: disallowed namespace "${i}" in view reference`);return}if(!e||typeof e!="object")return;let o=e;for(let[i,n]of Object.entries(o))g(n,`${t}/${i}`,s);}function T(){if(m)return m;let e=new v.default({allErrors:true});return $(e),m=e.compile(b),m}function R(e){let t=T(),s=t(e),o=(t.errors??[]).map(i=>`${i.instancePath||"/"}: ${i.message??"unknown error"}`);if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e.source_defs;if(Array.isArray(i)){let n=new Set,d=new Set;i.forEach((c,l)=>{if(!c||typeof c!="object"||Array.isArray(c))return;let r=c;typeof r.bindTo=="string"&&r.bindTo&&(n.has(r.bindTo)&&o.push(`/source_defs/${l}/bindTo: bindTo "${r.bindTo}" must be unique across all source_defs`),n.add(r.bindTo)),typeof r.outputFile=="string"&&r.outputFile&&(d.has(r.outputFile)&&o.push(`/source_defs/${l}/outputFile: outputFile "${r.outputFile}" must be unique across all source_defs`),d.add(r.outputFile));});}}return !s||o.length>0?{ok:false,errors:o}:{ok:true,errors:[]}}function F(e){let t=[];if(!e||typeof e!="object"||Array.isArray(e))return {ok:true,errors:[]};let s=e,o=s.compute;Array.isArray(o)&&o.forEach((r,p)=>{if(!r||typeof r!="object"||Array.isArray(r))return;let a=r.expr;typeof a!="string"||a.trim().length===0||h(a,`/compute/${p}/expr`,new Set(["card_data","requires","fetched_sources","computed_values"]),t);});let i=new Set(["card_data","requires","fetched_sources","computed_values"]),n=s.provides;Array.isArray(n)&&n.forEach((r,p)=>{if(!r||typeof r!="object"||Array.isArray(r))return;let a=r.ref;if(typeof a!="string"||a.trim().length===0)return;let u=w(a);u===null?t.push(`/provides/${p}/ref: path "${a}" must start with a valid namespace (${[...i].join(", ")})`):i.has(u)||t.push(`/provides/${p}/ref: disallowed namespace "${u}" in path "${a}" (valid: ${[...i].join(", ")})`);});let d=s.view;d&&typeof d=="object"&&!Array.isArray(d)&&g(d,"/view",t);let c=new Set(["card_data","requires"]),l=s.source_defs;return Array.isArray(l)&&l.forEach((r,p)=>{if(!r||typeof r!="object"||Array.isArray(r))return;let a=r,u=a.skip_when;typeof u=="string"&&u.trim().length>0&&h(u,`/source_defs/${p}/skip_when`,c,t);let f=a.projections;if(!(!f||typeof f!="object"||Array.isArray(f)))for(let[x,y]of Object.entries(f))typeof y!="string"||y.trim().length===0||h(y,`/source_defs/${p}/projections/${x}`,c,t);}),{ok:t.length===0,errors:t}}function L(e){return P(e)}function P(e){let t=R(e);if(!t.ok)return t;let s=F(e);return s.ok?{ok:true,errors:[]}:{ok:false,errors:s.errors}}
2
+ export{R as a,F as b,L as c,P as d};//# sourceMappingURL=chunk-3SLSRX6Q.js.map
3
+ //# sourceMappingURL=chunk-3SLSRX6Q.js.map
@@ -1,2 +1,2 @@
1
- import {t}from'./chunk-FULAMLUU.js';import {a}from'./chunk-ATOQP3BD.js';function b(e){return JSON.parse(JSON.stringify(e))}function E(e){let r=e.provides&&e.provides.length>0?e.provides.map(n=>n.bindTo):[e.id];return {requires:e.requires&&e.requires.length>0?[...e.requires]:void 0,provides:r,taskHandlers:[e.id],description:e.meta?.title??e.id}}function I(e){let r=new Map;for(let[n,u]of e.entries()){let o=u.provides&&u.provides.length>0?u.provides:[{bindTo:n,ref:"card_data"}];for(let h of o)r.set(h.bindTo,n);}return r}function O(e,r){let n=I(e),u=e.get(r);if(u){for(let o of u.requires??[])if(!n.has(o))throw new Error(`Card "${r}" requires token "${o}" but no card provides it`)}}var F={CARD_PREFIX:"yf:cards:",RUNTIME_OUT_PREFIX:"yf:runtime-out:cards:",STATUS_KEY:"yf:runtime-out:status",writeCard(e,r){try{localStorage.setItem(this.CARD_PREFIX+e,JSON.stringify(r));}catch(n){console.warn(`Failed to write card ${e} to localStorage:`,n);}},readCard(e){try{let r=localStorage.getItem(this.CARD_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read card ${e} from localStorage:`,r),null}},readAllCards(e){let r={};for(let n of e){let u=this.readCard(n);u&&(r[n]=u);}return r},writeComputedArtifact(e){if(!(!e||!e.card_id))try{localStorage.setItem(this.RUNTIME_OUT_PREFIX+String(e.card_id),JSON.stringify(e));}catch(r){console.warn(`Failed to write computed artifact ${e.card_id}:`,r);}},readComputedArtifact(e){try{let r=localStorage.getItem(this.RUNTIME_OUT_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read computed artifact ${e}:`,r),null}},readAllComputedArtifacts(e){let r={};for(let n of e){let u=this.readComputedArtifact(n);u&&(r[n]=u);}return r},writeStatusSnapshot(e){try{localStorage.setItem(this.STATUS_KEY,JSON.stringify(e));}catch(r){console.warn("Failed to write status snapshot to localStorage:",r);}},readStatusSnapshot(){try{let e=localStorage.getItem(this.STATUS_KEY);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to read status snapshot from localStorage:",e),null}},clear(){let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n&&(n.startsWith(this.CARD_PREFIX)||n.startsWith(this.RUNTIME_OUT_PREFIX)||n===this.STATUS_KEY)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}};function H(e,r={}){let n=Array.isArray(e)?{}:{id:e.id,title:e.title,mode:e.mode,positions:e.positions,settings:e.settings},u=Array.isArray(e)?e:e.nodes,o=new Map;for(let t of u){if(o.has(t.id))throw new Error(`Duplicate card ID: "${t.id}"`);o.set(t.id,b(t));}let h=new Set,S=r.taskExecutor,L=r.sourceAdapters??{},d=r.defaultSourceAdapter,m=null,A=(t,g)=>{let a={events:t,graph:g,nodes:v()};for(let w of h)w(a);},_=t=>async g=>{let a$1=o.get(t);if(!a$1)return "task-initiate-failure";let w={};for(let R of a$1.requires??[]){let y=g.state[R];if(!y||typeof y!="object")continue;let k=y.provides_data;!k||typeof k!="object"||Object.prototype.hasOwnProperty.call(k,R)&&(w[R]=k[R]);}let p={};if(a$1.source_defs&&a$1.source_defs.length>0){let R=L[t]??d,y=S?await S({card:a$1,input:g}):R?await R({card:a$1,input:g}):void 0;if(y&&typeof y=="object")for(let k of a$1.source_defs)Object.prototype.hasOwnProperty.call(y,k.bindTo)?p[k.bindTo]=y[k.bindTo]:a$1.source_defs.length===1&&(p[k.bindTo]=y);}let c={id:a$1.id,card_data:b(a$1.card_data??{}),requires:w,source_defs:a$1.source_defs,compute:a$1.compute};c._sourcesData=p,c.compute&&c.compute.length>0&&await a.run(c,{sourcesData:p});let T={};if(a$1.provides&&a$1.provides.length>0)for(let{bindTo:R,ref:y}of a$1.provides)T[R]=a.resolve(c,y);else T[a$1.id]={...c.card_data??{},...c.computed_values??{},...c._sourcesData??{}};let B={provides_data:T,card_data:c.card_data??{},computed_values:c.computed_values??{},fetched_sources:p,requires:w};return m?.resolveCallback(g.callbackToken,B),"task-initiated"},s={},f={};for(let[t,g]of o.entries())O(o,t),s[t]=E(g),f[t]=_(t);let l={id:n.id??`browser-board-${Date.now()}`,settings:{completion:"manual",execution_mode:"eligibility-mode",...n.settings??{},...r.graphSettings??{}},tasks:s},C=r.reactiveOptions?.onDrain,i=t(l,{...r.reactiveOptions??{},handlers:f,onDrain:(t,g,a)=>{C?.(t,g,a),A(t,g);}},r.executionId);m=i;function v(){let t=i.getState(),g=[];for(let[a,w]of o.entries()){let p=t.state.tasks[a]?.data,c=t.state.tasks[a],T={...w.card_data??{},...p&&typeof p.card_data=="object"?p.card_data:{}},B=c?.status==="running"?"loading":c?.status,R={...T,...B?{status:B}:{},...c?.lastUpdated?{lastRun:c.lastUpdated}:{},...c?.status==="failed"&&c.error?{error:c.error}:{}};g.push({id:a,card:b(w),card_data:R,requires:p&&typeof p.requires=="object"?b(p.requires):{},computed_values:p&&typeof p.computed_values=="object"?b(p.computed_values):{},runtime_state:c?b(c):{}});}return g}return {getGraph:()=>i,getState:()=>i.getState(),getSchedule:()=>i.getSchedule(),getNodes:()=>v(),getBoard:()=>({...n,nodes:v()}),subscribe(t){return h.add(t),t({events:[],graph:i.getState(),nodes:v()}),()=>h.delete(t)},addCard(t){if(o.has(t.id))throw new Error(`Card "${t.id}" already exists`);o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},upsertCard(t){o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},removeCard(t){o.delete(t),i.unregisterHandler(t),i.removeNode(t);},patchCardState(t,g){let a=o.get(t);if(!a)throw new Error(`Card "${t}" not found`);a.card_data={...a.card_data??{},...g},i.retrigger(t);},retrigger(t){i.retrigger(t);},retriggerAll(){i.retriggerAll(Array.from(o.keys()));},push(t){i.push(t);},pushAll(t){i.pushAll(t);},dispose(){h.clear(),i.dispose();}}}function G(e){return e==="running"||e==="in-progress"?"loading":e==="failed"?"error":"fresh"}function D(e){return e==="loading"?"in-progress":e==="error"?"failed":e==="stale"?"pending":e==="fresh"?"completed":"pending"}function M(e,r){let n=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return {schema_version:n.schema_version||"v1",card_id:typeof n.card_id=="string"?n.card_id:e,card_data:n.card_data&&typeof n.card_data=="object"&&!Array.isArray(n.card_data)?structuredClone(n.card_data):{},computed_values:n.computed_values&&typeof n.computed_values=="object"&&!Array.isArray(n.computed_values)?structuredClone(n.computed_values):{}}}function P(e,r){if(!e||typeof e!="object")throw new Error("payload must be an object");if(!r)throw new Error("cardId is required");let u=(Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).find(t=>t.id===r);if(!u)throw new Error(`cardDefinitions has no entry with id ${r}`);let o=e.statusSnapshot&&typeof e.statusSnapshot=="object"?e.statusSnapshot:{},h=e.cardRuntimeById&&typeof e.cardRuntimeById=="object"?e.cardRuntimeById:{},S=e.dataObjectsByToken&&typeof e.dataObjectsByToken=="object"?e.dataObjectsByToken:{},d=(Array.isArray(o.cards)?o.cards:[]).find(t=>t.name===r),m=structuredClone(u),A=M(r,h[r]),s={...m.card_data&&typeof m.card_data=="object"&&!Array.isArray(m.card_data)?m.card_data:{},...A.card_data||{},status:G(d?.status),lastRun:d?.runtime?.last_transition_at??null};d?.error?.message&&(s.error=d.error.message);let f=d?{task_status:d.status??null,card_status:G(d.status),runtime:structuredClone(d.runtime??{}),error:d.error?structuredClone(d.error):null,blocked_by:Array.isArray(d.blocked_by)?structuredClone(d.blocked_by):[],requires_missing:Array.isArray(d.requires_missing)?structuredClone(d.requires_missing):[]}:{task_status:null,card_status:s.status??"fresh",runtime:{last_transition_at:s.lastRun??null},error:s.error?{message:s.error}:null,blocked_by:[],requires_missing:[]},l=Array.isArray(m.requires)?m.requires:[],C={};for(let[t,g]of Object.entries(S))C[t]=structuredClone(g);for(let t of l)Object.prototype.hasOwnProperty.call(C,t)||(C[t]=null);let v=(e.cardChatsByCardId&&typeof e.cardChatsByCardId=="object"?e.cardChatsByCardId:{})[r],q=v?{messages:Array.isArray(v.messages)?v.messages:[],receiving:!!v.receiving,processing:!!v.processing}:null;return {id:r,card:m,card_data:s,requires:C,computed_values:A.computed_values,runtime_state:f,card_chats:q}}function $(e){if(!e||typeof e!="object")throw new Error("payload must be an object");return (Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).map(n=>P(e,n.id))}function J({boardPath:e,cardDefinitions:r,runtimeModels:n,graphState:u}){let o=Array.isArray(r)?r:[],h=Array.isArray(n)?n:[],S=new Map(h.map(s=>[s.id,s])),d=u.state?.tasks??{},m={};for(let s of h)s?.id&&(m[s.id]={schema_version:"v1",card_id:s.id,card_data:structuredClone(s.card_data??{}),computed_values:structuredClone(s.computed_values??{})});let A={};for(let s of Object.keys(d)){let f=d[s]?.data?.provides_data;if(f&&typeof f=="object")for(let l of Object.keys(f))A[l]=structuredClone(f[l]);}let _=o.map(s=>{let f=S.get(s.id)??{},l=d[s.id],C=typeof l?.status=="string"?l.status:D(f.card_data?.status),i=typeof l?.error=="string"?l.error:typeof f.card_data?.error=="string"?f.card_data.error:null;return {name:s.id,status:C,...i?{error:{message:i,code:"TASK_FAILED",at:l?.failedAt??null,source:"browser-runtime"}}:{},requires:Array.isArray(s.requires)?s.requires:[],requires_satisfied:[],requires_missing:[],provides_declared:Array.isArray(s.provides)?s.provides.map(v=>v.bindTo):[s.id],provides_runtime:Object.keys(l?.data?.provides_data??{}).sort(),blocked_by:[],unblocks:[],runtime:{attempt_count:l?.executionCount??0,restart_count:l?.retryCount??0,in_progress_since:C==="in-progress"?l?.startedAt??null:null,last_transition_at:l?.lastUpdated??f.card_data?.lastRun??null,last_completed_at:l?.completedAt??null,last_restarted_at:l?.startedAt??null,status_age_ms:null}}});return {cardDefinitions:structuredClone(o),cardRuntimeById:m,dataObjectsByToken:A,statusSnapshot:{schema_version:"v1",meta:{board:{path:e??"browser-runtime"}},summary:{card_count:_.length,completed:_.filter(s=>s.status==="completed").length,eligible:0,pending:_.filter(s=>s.status==="pending").length,blocked:0,unresolved:0,failed:_.filter(s=>s.status==="failed").length,in_progress:_.filter(s=>s.status==="in-progress").length,orphan_cards:0,topology:{edge_count:0,max_fan_out_card:null,max_fan_out:0}},cards:_}}}export{F as a,H as b,P as c,$ as d,J as e};//# sourceMappingURL=chunk-EHREWADE.js.map
2
- //# sourceMappingURL=chunk-EHREWADE.js.map
1
+ import {t}from'./chunk-FULAMLUU.js';import {a}from'./chunk-YOY2JM5N.js';function b(e){return JSON.parse(JSON.stringify(e))}function E(e){let r=e.provides&&e.provides.length>0?e.provides.map(n=>n.bindTo):[e.id];return {requires:e.requires&&e.requires.length>0?[...e.requires]:void 0,provides:r,taskHandlers:[e.id],description:e.meta?.title??e.id}}function I(e){let r=new Map;for(let[n,u]of e.entries()){let o=u.provides&&u.provides.length>0?u.provides:[{bindTo:n,ref:"card_data"}];for(let h of o)r.set(h.bindTo,n);}return r}function O(e,r){let n=I(e),u=e.get(r);if(u){for(let o of u.requires??[])if(!n.has(o))throw new Error(`Card "${r}" requires token "${o}" but no card provides it`)}}var F={CARD_PREFIX:"yf:cards:",RUNTIME_OUT_PREFIX:"yf:runtime-out:cards:",STATUS_KEY:"yf:runtime-out:status",writeCard(e,r){try{localStorage.setItem(this.CARD_PREFIX+e,JSON.stringify(r));}catch(n){console.warn(`Failed to write card ${e} to localStorage:`,n);}},readCard(e){try{let r=localStorage.getItem(this.CARD_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read card ${e} from localStorage:`,r),null}},readAllCards(e){let r={};for(let n of e){let u=this.readCard(n);u&&(r[n]=u);}return r},writeComputedArtifact(e){if(!(!e||!e.card_id))try{localStorage.setItem(this.RUNTIME_OUT_PREFIX+String(e.card_id),JSON.stringify(e));}catch(r){console.warn(`Failed to write computed artifact ${e.card_id}:`,r);}},readComputedArtifact(e){try{let r=localStorage.getItem(this.RUNTIME_OUT_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read computed artifact ${e}:`,r),null}},readAllComputedArtifacts(e){let r={};for(let n of e){let u=this.readComputedArtifact(n);u&&(r[n]=u);}return r},writeStatusSnapshot(e){try{localStorage.setItem(this.STATUS_KEY,JSON.stringify(e));}catch(r){console.warn("Failed to write status snapshot to localStorage:",r);}},readStatusSnapshot(){try{let e=localStorage.getItem(this.STATUS_KEY);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to read status snapshot from localStorage:",e),null}},clear(){let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n&&(n.startsWith(this.CARD_PREFIX)||n.startsWith(this.RUNTIME_OUT_PREFIX)||n===this.STATUS_KEY)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}};function H(e,r={}){let n=Array.isArray(e)?{}:{id:e.id,title:e.title,mode:e.mode,positions:e.positions,settings:e.settings},u=Array.isArray(e)?e:e.nodes,o=new Map;for(let t of u){if(o.has(t.id))throw new Error(`Duplicate card ID: "${t.id}"`);o.set(t.id,b(t));}let h=new Set,S=r.taskExecutor,L=r.sourceAdapters??{},d=r.defaultSourceAdapter,m=null,A=(t,g)=>{let a={events:t,graph:g,nodes:v()};for(let w of h)w(a);},_=t=>async g=>{let a$1=o.get(t);if(!a$1)return "task-initiate-failure";let w={};for(let R of a$1.requires??[]){let y=g.state[R];if(!y||typeof y!="object")continue;let k=y.provides_data;!k||typeof k!="object"||Object.prototype.hasOwnProperty.call(k,R)&&(w[R]=k[R]);}let p={};if(a$1.source_defs&&a$1.source_defs.length>0){let R=L[t]??d,y=S?await S({card:a$1,input:g}):R?await R({card:a$1,input:g}):void 0;if(y&&typeof y=="object")for(let k of a$1.source_defs)Object.prototype.hasOwnProperty.call(y,k.bindTo)?p[k.bindTo]=y[k.bindTo]:a$1.source_defs.length===1&&(p[k.bindTo]=y);}let c={id:a$1.id,card_data:b(a$1.card_data??{}),requires:w,source_defs:a$1.source_defs,compute:a$1.compute};c._sourcesData=p,c.compute&&c.compute.length>0&&await a.run(c,{sourcesData:p});let T={};if(a$1.provides&&a$1.provides.length>0)for(let{bindTo:R,ref:y}of a$1.provides)T[R]=a.resolve(c,y);else T[a$1.id]={...c.card_data??{},...c.computed_values??{},...c._sourcesData??{}};let B={provides_data:T,card_data:c.card_data??{},computed_values:c.computed_values??{},fetched_sources:p,requires:w};return m?.resolveCallback(g.callbackToken,B),"task-initiated"},s={},f={};for(let[t,g]of o.entries())O(o,t),s[t]=E(g),f[t]=_(t);let l={id:n.id??`browser-board-${Date.now()}`,settings:{completion:"manual",execution_mode:"eligibility-mode",...n.settings??{},...r.graphSettings??{}},tasks:s},C=r.reactiveOptions?.onDrain,i=t(l,{...r.reactiveOptions??{},handlers:f,onDrain:(t,g,a)=>{C?.(t,g,a),A(t,g);}},r.executionId);m=i;function v(){let t=i.getState(),g=[];for(let[a,w]of o.entries()){let p=t.state.tasks[a]?.data,c=t.state.tasks[a],T={...w.card_data??{},...p&&typeof p.card_data=="object"?p.card_data:{}},B=c?.status==="running"?"loading":c?.status,R={...T,...B?{status:B}:{},...c?.lastUpdated?{lastRun:c.lastUpdated}:{},...c?.status==="failed"&&c.error?{error:c.error}:{}};g.push({id:a,card:b(w),card_data:R,requires:p&&typeof p.requires=="object"?b(p.requires):{},computed_values:p&&typeof p.computed_values=="object"?b(p.computed_values):{},runtime_state:c?b(c):{}});}return g}return {getGraph:()=>i,getState:()=>i.getState(),getSchedule:()=>i.getSchedule(),getNodes:()=>v(),getBoard:()=>({...n,nodes:v()}),subscribe(t){return h.add(t),t({events:[],graph:i.getState(),nodes:v()}),()=>h.delete(t)},addCard(t){if(o.has(t.id))throw new Error(`Card "${t.id}" already exists`);o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},upsertCard(t){o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},removeCard(t){o.delete(t),i.unregisterHandler(t),i.removeNode(t);},patchCardState(t,g){let a=o.get(t);if(!a)throw new Error(`Card "${t}" not found`);a.card_data={...a.card_data??{},...g},i.retrigger(t);},retrigger(t){i.retrigger(t);},retriggerAll(){i.retriggerAll(Array.from(o.keys()));},push(t){i.push(t);},pushAll(t){i.pushAll(t);},dispose(){h.clear(),i.dispose();}}}function G(e){return e==="running"||e==="in-progress"?"loading":e==="failed"?"error":"fresh"}function D(e){return e==="loading"?"in-progress":e==="error"?"failed":e==="stale"?"pending":e==="fresh"?"completed":"pending"}function M(e,r){let n=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return {schema_version:n.schema_version||"v1",card_id:typeof n.card_id=="string"?n.card_id:e,card_data:n.card_data&&typeof n.card_data=="object"&&!Array.isArray(n.card_data)?structuredClone(n.card_data):{},computed_values:n.computed_values&&typeof n.computed_values=="object"&&!Array.isArray(n.computed_values)?structuredClone(n.computed_values):{}}}function P(e,r){if(!e||typeof e!="object")throw new Error("payload must be an object");if(!r)throw new Error("cardId is required");let u=(Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).find(t=>t.id===r);if(!u)throw new Error(`cardDefinitions has no entry with id ${r}`);let o=e.statusSnapshot&&typeof e.statusSnapshot=="object"?e.statusSnapshot:{},h=e.cardRuntimeById&&typeof e.cardRuntimeById=="object"?e.cardRuntimeById:{},S=e.dataObjectsByToken&&typeof e.dataObjectsByToken=="object"?e.dataObjectsByToken:{},d=(Array.isArray(o.cards)?o.cards:[]).find(t=>t.name===r),m=structuredClone(u),A=M(r,h[r]),s={...m.card_data&&typeof m.card_data=="object"&&!Array.isArray(m.card_data)?m.card_data:{},...A.card_data||{},status:G(d?.status),lastRun:d?.runtime?.last_transition_at??null};d?.error?.message&&(s.error=d.error.message);let f=d?{task_status:d.status??null,card_status:G(d.status),runtime:structuredClone(d.runtime??{}),error:d.error?structuredClone(d.error):null,blocked_by:Array.isArray(d.blocked_by)?structuredClone(d.blocked_by):[],requires_missing:Array.isArray(d.requires_missing)?structuredClone(d.requires_missing):[]}:{task_status:null,card_status:s.status??"fresh",runtime:{last_transition_at:s.lastRun??null},error:s.error?{message:s.error}:null,blocked_by:[],requires_missing:[]},l=Array.isArray(m.requires)?m.requires:[],C={};for(let[t,g]of Object.entries(S))C[t]=structuredClone(g);for(let t of l)Object.prototype.hasOwnProperty.call(C,t)||(C[t]=null);let v=(e.cardChatsByCardId&&typeof e.cardChatsByCardId=="object"?e.cardChatsByCardId:{})[r],q=v?{messages:Array.isArray(v.messages)?v.messages:[],receiving:!!v.receiving,processing:!!v.processing}:null;return {id:r,card:m,card_data:s,requires:C,computed_values:A.computed_values,runtime_state:f,card_chats:q}}function $(e){if(!e||typeof e!="object")throw new Error("payload must be an object");return (Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).map(n=>P(e,n.id))}function J({boardPath:e,cardDefinitions:r,runtimeModels:n,graphState:u}){let o=Array.isArray(r)?r:[],h=Array.isArray(n)?n:[],S=new Map(h.map(s=>[s.id,s])),d=u.state?.tasks??{},m={};for(let s of h)s?.id&&(m[s.id]={schema_version:"v1",card_id:s.id,card_data:structuredClone(s.card_data??{}),computed_values:structuredClone(s.computed_values??{})});let A={};for(let s of Object.keys(d)){let f=d[s]?.data?.provides_data;if(f&&typeof f=="object")for(let l of Object.keys(f))A[l]=structuredClone(f[l]);}let _=o.map(s=>{let f=S.get(s.id)??{},l=d[s.id],C=typeof l?.status=="string"?l.status:D(f.card_data?.status),i=typeof l?.error=="string"?l.error:typeof f.card_data?.error=="string"?f.card_data.error:null;return {name:s.id,status:C,...i?{error:{message:i,code:"TASK_FAILED",at:l?.failedAt??null,source:"browser-runtime"}}:{},requires:Array.isArray(s.requires)?s.requires:[],requires_satisfied:[],requires_missing:[],provides_declared:Array.isArray(s.provides)?s.provides.map(v=>v.bindTo):[s.id],provides_runtime:Object.keys(l?.data?.provides_data??{}).sort(),blocked_by:[],unblocks:[],runtime:{attempt_count:l?.executionCount??0,restart_count:l?.retryCount??0,in_progress_since:C==="in-progress"?l?.startedAt??null:null,last_transition_at:l?.lastUpdated??f.card_data?.lastRun??null,last_completed_at:l?.completedAt??null,last_restarted_at:l?.startedAt??null,status_age_ms:null}}});return {cardDefinitions:structuredClone(o),cardRuntimeById:m,dataObjectsByToken:A,statusSnapshot:{schema_version:"v1",meta:{board:{path:e??"browser-runtime"}},summary:{card_count:_.length,completed:_.filter(s=>s.status==="completed").length,eligible:0,pending:_.filter(s=>s.status==="pending").length,blocked:0,unresolved:0,failed:_.filter(s=>s.status==="failed").length,in_progress:_.filter(s=>s.status==="in-progress").length,orphan_cards:0,topology:{edge_count:0,max_fan_out_card:null,max_fan_out:0}},cards:_}}}export{F as a,H as b,P as c,$ as d,J as e};//# sourceMappingURL=chunk-4NWVZ7AW.js.map
2
+ //# sourceMappingURL=chunk-4NWVZ7AW.js.map
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunk3DWVFRQD_cjs=require('./chunk-3DWVFRQD.cjs');function s(r){let e=chunk3DWVFRQD_cjs.d(r);return {isValid:e.ok,issues:e.errors}}exports.a=s;//# sourceMappingURL=chunk-543ZEGP7.cjs.map
2
+ //# sourceMappingURL=chunk-543ZEGP7.cjs.map
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkAW3COGCI_cjs=require('./chunk-AW3COGCI.cjs'),chunkQBEQL4TL_cjs=require('./chunk-QBEQL4TL.cjs');function b(e){return JSON.parse(JSON.stringify(e))}function E(e){let r=e.provides&&e.provides.length>0?e.provides.map(n=>n.bindTo):[e.id];return {requires:e.requires&&e.requires.length>0?[...e.requires]:void 0,provides:r,taskHandlers:[e.id],description:e.meta?.title??e.id}}function I(e){let r=new Map;for(let[n,u]of e.entries()){let o=u.provides&&u.provides.length>0?u.provides:[{bindTo:n,ref:"card_data"}];for(let h of o)r.set(h.bindTo,n);}return r}function O(e,r){let n=I(e),u=e.get(r);if(u){for(let o of u.requires??[])if(!n.has(o))throw new Error(`Card "${r}" requires token "${o}" but no card provides it`)}}var F={CARD_PREFIX:"yf:cards:",RUNTIME_OUT_PREFIX:"yf:runtime-out:cards:",STATUS_KEY:"yf:runtime-out:status",writeCard(e,r){try{localStorage.setItem(this.CARD_PREFIX+e,JSON.stringify(r));}catch(n){console.warn(`Failed to write card ${e} to localStorage:`,n);}},readCard(e){try{let r=localStorage.getItem(this.CARD_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read card ${e} from localStorage:`,r),null}},readAllCards(e){let r={};for(let n of e){let u=this.readCard(n);u&&(r[n]=u);}return r},writeComputedArtifact(e){if(!(!e||!e.card_id))try{localStorage.setItem(this.RUNTIME_OUT_PREFIX+String(e.card_id),JSON.stringify(e));}catch(r){console.warn(`Failed to write computed artifact ${e.card_id}:`,r);}},readComputedArtifact(e){try{let r=localStorage.getItem(this.RUNTIME_OUT_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read computed artifact ${e}:`,r),null}},readAllComputedArtifacts(e){let r={};for(let n of e){let u=this.readComputedArtifact(n);u&&(r[n]=u);}return r},writeStatusSnapshot(e){try{localStorage.setItem(this.STATUS_KEY,JSON.stringify(e));}catch(r){console.warn("Failed to write status snapshot to localStorage:",r);}},readStatusSnapshot(){try{let e=localStorage.getItem(this.STATUS_KEY);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to read status snapshot from localStorage:",e),null}},clear(){let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n&&(n.startsWith(this.CARD_PREFIX)||n.startsWith(this.RUNTIME_OUT_PREFIX)||n===this.STATUS_KEY)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}};function H(e,r={}){let n=Array.isArray(e)?{}:{id:e.id,title:e.title,mode:e.mode,positions:e.positions,settings:e.settings},u=Array.isArray(e)?e:e.nodes,o=new Map;for(let t of u){if(o.has(t.id))throw new Error(`Duplicate card ID: "${t.id}"`);o.set(t.id,b(t));}let h=new Set,S=r.taskExecutor,L=r.sourceAdapters??{},d=r.defaultSourceAdapter,m=null,A=(t,g)=>{let a={events:t,graph:g,nodes:v()};for(let w of h)w(a);},_=t=>async g=>{let a=o.get(t);if(!a)return "task-initiate-failure";let w={};for(let R of a.requires??[]){let y=g.state[R];if(!y||typeof y!="object")continue;let k=y.provides_data;!k||typeof k!="object"||Object.prototype.hasOwnProperty.call(k,R)&&(w[R]=k[R]);}let p={};if(a.source_defs&&a.source_defs.length>0){let R=L[t]??d,y=S?await S({card:a,input:g}):R?await R({card:a,input:g}):void 0;if(y&&typeof y=="object")for(let k of a.source_defs)Object.prototype.hasOwnProperty.call(y,k.bindTo)?p[k.bindTo]=y[k.bindTo]:a.source_defs.length===1&&(p[k.bindTo]=y);}let c={id:a.id,card_data:b(a.card_data??{}),requires:w,source_defs:a.source_defs,compute:a.compute};c._sourcesData=p,c.compute&&c.compute.length>0&&await chunkQBEQL4TL_cjs.a.run(c,{sourcesData:p});let T={};if(a.provides&&a.provides.length>0)for(let{bindTo:R,ref:y}of a.provides)T[R]=chunkQBEQL4TL_cjs.a.resolve(c,y);else T[a.id]={...c.card_data??{},...c.computed_values??{},...c._sourcesData??{}};let B={provides_data:T,card_data:c.card_data??{},computed_values:c.computed_values??{},fetched_sources:p,requires:w};return m?.resolveCallback(g.callbackToken,B),"task-initiated"},s={},f={};for(let[t,g]of o.entries())O(o,t),s[t]=E(g),f[t]=_(t);let l={id:n.id??`browser-board-${Date.now()}`,settings:{completion:"manual",execution_mode:"eligibility-mode",...n.settings??{},...r.graphSettings??{}},tasks:s},C=r.reactiveOptions?.onDrain,i=chunkAW3COGCI_cjs.t(l,{...r.reactiveOptions??{},handlers:f,onDrain:(t,g,a)=>{C?.(t,g,a),A(t,g);}},r.executionId);m=i;function v(){let t=i.getState(),g=[];for(let[a,w]of o.entries()){let p=t.state.tasks[a]?.data,c=t.state.tasks[a],T={...w.card_data??{},...p&&typeof p.card_data=="object"?p.card_data:{}},B=c?.status==="running"?"loading":c?.status,R={...T,...B?{status:B}:{},...c?.lastUpdated?{lastRun:c.lastUpdated}:{},...c?.status==="failed"&&c.error?{error:c.error}:{}};g.push({id:a,card:b(w),card_data:R,requires:p&&typeof p.requires=="object"?b(p.requires):{},computed_values:p&&typeof p.computed_values=="object"?b(p.computed_values):{},runtime_state:c?b(c):{}});}return g}return {getGraph:()=>i,getState:()=>i.getState(),getSchedule:()=>i.getSchedule(),getNodes:()=>v(),getBoard:()=>({...n,nodes:v()}),subscribe(t){return h.add(t),t({events:[],graph:i.getState(),nodes:v()}),()=>h.delete(t)},addCard(t){if(o.has(t.id))throw new Error(`Card "${t.id}" already exists`);o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},upsertCard(t){o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},removeCard(t){o.delete(t),i.unregisterHandler(t),i.removeNode(t);},patchCardState(t,g){let a=o.get(t);if(!a)throw new Error(`Card "${t}" not found`);a.card_data={...a.card_data??{},...g},i.retrigger(t);},retrigger(t){i.retrigger(t);},retriggerAll(){i.retriggerAll(Array.from(o.keys()));},push(t){i.push(t);},pushAll(t){i.pushAll(t);},dispose(){h.clear(),i.dispose();}}}function G(e){return e==="running"||e==="in-progress"?"loading":e==="failed"?"error":"fresh"}function D(e){return e==="loading"?"in-progress":e==="error"?"failed":e==="stale"?"pending":e==="fresh"?"completed":"pending"}function M(e,r){let n=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return {schema_version:n.schema_version||"v1",card_id:typeof n.card_id=="string"?n.card_id:e,card_data:n.card_data&&typeof n.card_data=="object"&&!Array.isArray(n.card_data)?structuredClone(n.card_data):{},computed_values:n.computed_values&&typeof n.computed_values=="object"&&!Array.isArray(n.computed_values)?structuredClone(n.computed_values):{}}}function P(e,r){if(!e||typeof e!="object")throw new Error("payload must be an object");if(!r)throw new Error("cardId is required");let u=(Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).find(t=>t.id===r);if(!u)throw new Error(`cardDefinitions has no entry with id ${r}`);let o=e.statusSnapshot&&typeof e.statusSnapshot=="object"?e.statusSnapshot:{},h=e.cardRuntimeById&&typeof e.cardRuntimeById=="object"?e.cardRuntimeById:{},S=e.dataObjectsByToken&&typeof e.dataObjectsByToken=="object"?e.dataObjectsByToken:{},d=(Array.isArray(o.cards)?o.cards:[]).find(t=>t.name===r),m=structuredClone(u),A=M(r,h[r]),s={...m.card_data&&typeof m.card_data=="object"&&!Array.isArray(m.card_data)?m.card_data:{},...A.card_data||{},status:G(d?.status),lastRun:d?.runtime?.last_transition_at??null};d?.error?.message&&(s.error=d.error.message);let f=d?{task_status:d.status??null,card_status:G(d.status),runtime:structuredClone(d.runtime??{}),error:d.error?structuredClone(d.error):null,blocked_by:Array.isArray(d.blocked_by)?structuredClone(d.blocked_by):[],requires_missing:Array.isArray(d.requires_missing)?structuredClone(d.requires_missing):[]}:{task_status:null,card_status:s.status??"fresh",runtime:{last_transition_at:s.lastRun??null},error:s.error?{message:s.error}:null,blocked_by:[],requires_missing:[]},l=Array.isArray(m.requires)?m.requires:[],C={};for(let[t,g]of Object.entries(S))C[t]=structuredClone(g);for(let t of l)Object.prototype.hasOwnProperty.call(C,t)||(C[t]=null);let v=(e.cardChatsByCardId&&typeof e.cardChatsByCardId=="object"?e.cardChatsByCardId:{})[r],q=v?{messages:Array.isArray(v.messages)?v.messages:[],receiving:!!v.receiving,processing:!!v.processing}:null;return {id:r,card:m,card_data:s,requires:C,computed_values:A.computed_values,runtime_state:f,card_chats:q}}function $(e){if(!e||typeof e!="object")throw new Error("payload must be an object");return (Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).map(n=>P(e,n.id))}function J({boardPath:e,cardDefinitions:r,runtimeModels:n,graphState:u}){let o=Array.isArray(r)?r:[],h=Array.isArray(n)?n:[],S=new Map(h.map(s=>[s.id,s])),d=u.state?.tasks??{},m={};for(let s of h)s?.id&&(m[s.id]={schema_version:"v1",card_id:s.id,card_data:structuredClone(s.card_data??{}),computed_values:structuredClone(s.computed_values??{})});let A={};for(let s of Object.keys(d)){let f=d[s]?.data?.provides_data;if(f&&typeof f=="object")for(let l of Object.keys(f))A[l]=structuredClone(f[l]);}let _=o.map(s=>{let f=S.get(s.id)??{},l=d[s.id],C=typeof l?.status=="string"?l.status:D(f.card_data?.status),i=typeof l?.error=="string"?l.error:typeof f.card_data?.error=="string"?f.card_data.error:null;return {name:s.id,status:C,...i?{error:{message:i,code:"TASK_FAILED",at:l?.failedAt??null,source:"browser-runtime"}}:{},requires:Array.isArray(s.requires)?s.requires:[],requires_satisfied:[],requires_missing:[],provides_declared:Array.isArray(s.provides)?s.provides.map(v=>v.bindTo):[s.id],provides_runtime:Object.keys(l?.data?.provides_data??{}).sort(),blocked_by:[],unblocks:[],runtime:{attempt_count:l?.executionCount??0,restart_count:l?.retryCount??0,in_progress_since:C==="in-progress"?l?.startedAt??null:null,last_transition_at:l?.lastUpdated??f.card_data?.lastRun??null,last_completed_at:l?.completedAt??null,last_restarted_at:l?.startedAt??null,status_age_ms:null}}});return {cardDefinitions:structuredClone(o),cardRuntimeById:m,dataObjectsByToken:A,statusSnapshot:{schema_version:"v1",meta:{board:{path:e??"browser-runtime"}},summary:{card_count:_.length,completed:_.filter(s=>s.status==="completed").length,eligible:0,pending:_.filter(s=>s.status==="pending").length,blocked:0,unresolved:0,failed:_.filter(s=>s.status==="failed").length,in_progress:_.filter(s=>s.status==="in-progress").length,orphan_cards:0,topology:{edge_count:0,max_fan_out_card:null,max_fan_out:0}},cards:_}}}exports.a=F;exports.b=H;exports.c=P;exports.d=$;exports.e=J;//# sourceMappingURL=chunk-YAPTL2MP.cjs.map
2
- //# sourceMappingURL=chunk-YAPTL2MP.cjs.map
1
+ 'use strict';var chunkAW3COGCI_cjs=require('./chunk-AW3COGCI.cjs'),chunkZV35WD6K_cjs=require('./chunk-ZV35WD6K.cjs');function b(e){return JSON.parse(JSON.stringify(e))}function E(e){let r=e.provides&&e.provides.length>0?e.provides.map(n=>n.bindTo):[e.id];return {requires:e.requires&&e.requires.length>0?[...e.requires]:void 0,provides:r,taskHandlers:[e.id],description:e.meta?.title??e.id}}function I(e){let r=new Map;for(let[n,u]of e.entries()){let o=u.provides&&u.provides.length>0?u.provides:[{bindTo:n,ref:"card_data"}];for(let h of o)r.set(h.bindTo,n);}return r}function O(e,r){let n=I(e),u=e.get(r);if(u){for(let o of u.requires??[])if(!n.has(o))throw new Error(`Card "${r}" requires token "${o}" but no card provides it`)}}var F={CARD_PREFIX:"yf:cards:",RUNTIME_OUT_PREFIX:"yf:runtime-out:cards:",STATUS_KEY:"yf:runtime-out:status",writeCard(e,r){try{localStorage.setItem(this.CARD_PREFIX+e,JSON.stringify(r));}catch(n){console.warn(`Failed to write card ${e} to localStorage:`,n);}},readCard(e){try{let r=localStorage.getItem(this.CARD_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read card ${e} from localStorage:`,r),null}},readAllCards(e){let r={};for(let n of e){let u=this.readCard(n);u&&(r[n]=u);}return r},writeComputedArtifact(e){if(!(!e||!e.card_id))try{localStorage.setItem(this.RUNTIME_OUT_PREFIX+String(e.card_id),JSON.stringify(e));}catch(r){console.warn(`Failed to write computed artifact ${e.card_id}:`,r);}},readComputedArtifact(e){try{let r=localStorage.getItem(this.RUNTIME_OUT_PREFIX+e);return r?JSON.parse(r):null}catch(r){return console.warn(`Failed to read computed artifact ${e}:`,r),null}},readAllComputedArtifacts(e){let r={};for(let n of e){let u=this.readComputedArtifact(n);u&&(r[n]=u);}return r},writeStatusSnapshot(e){try{localStorage.setItem(this.STATUS_KEY,JSON.stringify(e));}catch(r){console.warn("Failed to write status snapshot to localStorage:",r);}},readStatusSnapshot(){try{let e=localStorage.getItem(this.STATUS_KEY);return e?JSON.parse(e):null}catch(e){return console.warn("Failed to read status snapshot from localStorage:",e),null}},clear(){let e=[];for(let r=0;r<localStorage.length;r++){let n=localStorage.key(r);n&&(n.startsWith(this.CARD_PREFIX)||n.startsWith(this.RUNTIME_OUT_PREFIX)||n===this.STATUS_KEY)&&e.push(n);}for(let r of e)localStorage.removeItem(r);}};function H(e,r={}){let n=Array.isArray(e)?{}:{id:e.id,title:e.title,mode:e.mode,positions:e.positions,settings:e.settings},u=Array.isArray(e)?e:e.nodes,o=new Map;for(let t of u){if(o.has(t.id))throw new Error(`Duplicate card ID: "${t.id}"`);o.set(t.id,b(t));}let h=new Set,S=r.taskExecutor,L=r.sourceAdapters??{},d=r.defaultSourceAdapter,m=null,A=(t,g)=>{let a={events:t,graph:g,nodes:v()};for(let w of h)w(a);},_=t=>async g=>{let a=o.get(t);if(!a)return "task-initiate-failure";let w={};for(let R of a.requires??[]){let y=g.state[R];if(!y||typeof y!="object")continue;let k=y.provides_data;!k||typeof k!="object"||Object.prototype.hasOwnProperty.call(k,R)&&(w[R]=k[R]);}let p={};if(a.source_defs&&a.source_defs.length>0){let R=L[t]??d,y=S?await S({card:a,input:g}):R?await R({card:a,input:g}):void 0;if(y&&typeof y=="object")for(let k of a.source_defs)Object.prototype.hasOwnProperty.call(y,k.bindTo)?p[k.bindTo]=y[k.bindTo]:a.source_defs.length===1&&(p[k.bindTo]=y);}let c={id:a.id,card_data:b(a.card_data??{}),requires:w,source_defs:a.source_defs,compute:a.compute};c._sourcesData=p,c.compute&&c.compute.length>0&&await chunkZV35WD6K_cjs.a.run(c,{sourcesData:p});let T={};if(a.provides&&a.provides.length>0)for(let{bindTo:R,ref:y}of a.provides)T[R]=chunkZV35WD6K_cjs.a.resolve(c,y);else T[a.id]={...c.card_data??{},...c.computed_values??{},...c._sourcesData??{}};let B={provides_data:T,card_data:c.card_data??{},computed_values:c.computed_values??{},fetched_sources:p,requires:w};return m?.resolveCallback(g.callbackToken,B),"task-initiated"},s={},f={};for(let[t,g]of o.entries())O(o,t),s[t]=E(g),f[t]=_(t);let l={id:n.id??`browser-board-${Date.now()}`,settings:{completion:"manual",execution_mode:"eligibility-mode",...n.settings??{},...r.graphSettings??{}},tasks:s},C=r.reactiveOptions?.onDrain,i=chunkAW3COGCI_cjs.t(l,{...r.reactiveOptions??{},handlers:f,onDrain:(t,g,a)=>{C?.(t,g,a),A(t,g);}},r.executionId);m=i;function v(){let t=i.getState(),g=[];for(let[a,w]of o.entries()){let p=t.state.tasks[a]?.data,c=t.state.tasks[a],T={...w.card_data??{},...p&&typeof p.card_data=="object"?p.card_data:{}},B=c?.status==="running"?"loading":c?.status,R={...T,...B?{status:B}:{},...c?.lastUpdated?{lastRun:c.lastUpdated}:{},...c?.status==="failed"&&c.error?{error:c.error}:{}};g.push({id:a,card:b(w),card_data:R,requires:p&&typeof p.requires=="object"?b(p.requires):{},computed_values:p&&typeof p.computed_values=="object"?b(p.computed_values):{},runtime_state:c?b(c):{}});}return g}return {getGraph:()=>i,getState:()=>i.getState(),getSchedule:()=>i.getSchedule(),getNodes:()=>v(),getBoard:()=>({...n,nodes:v()}),subscribe(t){return h.add(t),t({events:[],graph:i.getState(),nodes:v()}),()=>h.delete(t)},addCard(t){if(o.has(t.id))throw new Error(`Card "${t.id}" already exists`);o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},upsertCard(t){o.set(t.id,b(t)),O(o,t.id),i.registerHandler(t.id,_(t.id)),i.addNode(t.id,E(t));},removeCard(t){o.delete(t),i.unregisterHandler(t),i.removeNode(t);},patchCardState(t,g){let a=o.get(t);if(!a)throw new Error(`Card "${t}" not found`);a.card_data={...a.card_data??{},...g},i.retrigger(t);},retrigger(t){i.retrigger(t);},retriggerAll(){i.retriggerAll(Array.from(o.keys()));},push(t){i.push(t);},pushAll(t){i.pushAll(t);},dispose(){h.clear(),i.dispose();}}}function G(e){return e==="running"||e==="in-progress"?"loading":e==="failed"?"error":"fresh"}function D(e){return e==="loading"?"in-progress":e==="error"?"failed":e==="stale"?"pending":e==="fresh"?"completed":"pending"}function M(e,r){let n=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return {schema_version:n.schema_version||"v1",card_id:typeof n.card_id=="string"?n.card_id:e,card_data:n.card_data&&typeof n.card_data=="object"&&!Array.isArray(n.card_data)?structuredClone(n.card_data):{},computed_values:n.computed_values&&typeof n.computed_values=="object"&&!Array.isArray(n.computed_values)?structuredClone(n.computed_values):{}}}function P(e,r){if(!e||typeof e!="object")throw new Error("payload must be an object");if(!r)throw new Error("cardId is required");let u=(Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).find(t=>t.id===r);if(!u)throw new Error(`cardDefinitions has no entry with id ${r}`);let o=e.statusSnapshot&&typeof e.statusSnapshot=="object"?e.statusSnapshot:{},h=e.cardRuntimeById&&typeof e.cardRuntimeById=="object"?e.cardRuntimeById:{},S=e.dataObjectsByToken&&typeof e.dataObjectsByToken=="object"?e.dataObjectsByToken:{},d=(Array.isArray(o.cards)?o.cards:[]).find(t=>t.name===r),m=structuredClone(u),A=M(r,h[r]),s={...m.card_data&&typeof m.card_data=="object"&&!Array.isArray(m.card_data)?m.card_data:{},...A.card_data||{},status:G(d?.status),lastRun:d?.runtime?.last_transition_at??null};d?.error?.message&&(s.error=d.error.message);let f=d?{task_status:d.status??null,card_status:G(d.status),runtime:structuredClone(d.runtime??{}),error:d.error?structuredClone(d.error):null,blocked_by:Array.isArray(d.blocked_by)?structuredClone(d.blocked_by):[],requires_missing:Array.isArray(d.requires_missing)?structuredClone(d.requires_missing):[]}:{task_status:null,card_status:s.status??"fresh",runtime:{last_transition_at:s.lastRun??null},error:s.error?{message:s.error}:null,blocked_by:[],requires_missing:[]},l=Array.isArray(m.requires)?m.requires:[],C={};for(let[t,g]of Object.entries(S))C[t]=structuredClone(g);for(let t of l)Object.prototype.hasOwnProperty.call(C,t)||(C[t]=null);let v=(e.cardChatsByCardId&&typeof e.cardChatsByCardId=="object"?e.cardChatsByCardId:{})[r],q=v?{messages:Array.isArray(v.messages)?v.messages:[],receiving:!!v.receiving,processing:!!v.processing}:null;return {id:r,card:m,card_data:s,requires:C,computed_values:A.computed_values,runtime_state:f,card_chats:q}}function $(e){if(!e||typeof e!="object")throw new Error("payload must be an object");return (Array.isArray(e.cardDefinitions)?e.cardDefinitions:[]).map(n=>P(e,n.id))}function J({boardPath:e,cardDefinitions:r,runtimeModels:n,graphState:u}){let o=Array.isArray(r)?r:[],h=Array.isArray(n)?n:[],S=new Map(h.map(s=>[s.id,s])),d=u.state?.tasks??{},m={};for(let s of h)s?.id&&(m[s.id]={schema_version:"v1",card_id:s.id,card_data:structuredClone(s.card_data??{}),computed_values:structuredClone(s.computed_values??{})});let A={};for(let s of Object.keys(d)){let f=d[s]?.data?.provides_data;if(f&&typeof f=="object")for(let l of Object.keys(f))A[l]=structuredClone(f[l]);}let _=o.map(s=>{let f=S.get(s.id)??{},l=d[s.id],C=typeof l?.status=="string"?l.status:D(f.card_data?.status),i=typeof l?.error=="string"?l.error:typeof f.card_data?.error=="string"?f.card_data.error:null;return {name:s.id,status:C,...i?{error:{message:i,code:"TASK_FAILED",at:l?.failedAt??null,source:"browser-runtime"}}:{},requires:Array.isArray(s.requires)?s.requires:[],requires_satisfied:[],requires_missing:[],provides_declared:Array.isArray(s.provides)?s.provides.map(v=>v.bindTo):[s.id],provides_runtime:Object.keys(l?.data?.provides_data??{}).sort(),blocked_by:[],unblocks:[],runtime:{attempt_count:l?.executionCount??0,restart_count:l?.retryCount??0,in_progress_since:C==="in-progress"?l?.startedAt??null:null,last_transition_at:l?.lastUpdated??f.card_data?.lastRun??null,last_completed_at:l?.completedAt??null,last_restarted_at:l?.startedAt??null,status_age_ms:null}}});return {cardDefinitions:structuredClone(o),cardRuntimeById:m,dataObjectsByToken:A,statusSnapshot:{schema_version:"v1",meta:{board:{path:e??"browser-runtime"}},summary:{card_count:_.length,completed:_.filter(s=>s.status==="completed").length,eligible:0,pending:_.filter(s=>s.status==="pending").length,blocked:0,unresolved:0,failed:_.filter(s=>s.status==="failed").length,in_progress:_.filter(s=>s.status==="in-progress").length,orphan_cards:0,topology:{edge_count:0,max_fan_out_card:null,max_fan_out:0}},cards:_}}}exports.a=F;exports.b=H;exports.c=P;exports.d=$;exports.e=J;//# sourceMappingURL=chunk-6SPWFJRG.cjs.map
2
+ //# sourceMappingURL=chunk-6SPWFJRG.cjs.map
@@ -1,3 +1,3 @@
1
- import {a,b}from'./chunk-JB4Q2W7I.js';import {a as a$3}from'./chunk-XYN5D3GL.js';import {a as a$5,c as c$2}from'./chunk-O5UYCGIN.js';import {p,j,k,l,c as c$1,d as d$1,m as m$1,n,e as e$2,a as a$7,b as b$3,o}from'./chunk-I3ZOFU3F.js';import {a as a$4,d as d$2,b as b$2,c as c$3}from'./chunk-FOFGEABN.js';import {a as a$b}from'./chunk-RKKSVOP2.js';import {a as a$2}from'./chunk-NTICU4OK.js';import {a as a$8,c as c$4}from'./chunk-O7NOHKVR.js';import {a as a$9,b as b$4}from'./chunk-ZJ5M5COT.js';import {i,d,c,b as b$1,g,h}from'./chunk-RKLEBQUG.js';import {a as a$a}from'./chunk-PEJRTZU3.js';import {e,f}from'./chunk-X32SJDLT.js';import {H,m}from'./chunk-WGYS2L4V.js';import {a as a$6}from'./chunk-BJGK5FNL.js';import {a as a$1}from'./chunk-NIBLKYXN.js';import {e as e$1}from'./chunk-UGB7PC4P.js';function ce(g){let{apiBasePath:w,json:b,readJsonBody:I,bootstrapBoard:B,createMcpControlplaneToolRegistry:$,retriggerCard:N,applyCardAction:x,resolveChatHandlerTarget:_,sendCardFileDownloadResponse:H}=g;async function E(T,S,z){let q=T.method||"GET",K=z,l=K.pathname;try{if(q==="POST"&&l===`${w}/mcp-actions`){await B();let f=Date.now(),y=new Date(f).toISOString(),k=await I(T),u=typeof k.tool=="string"?k.tool.trim():"",P=k.args&&typeof k.args=="object"&&!Array.isArray(k.args)?k.args:{};if(!u)return b(S,400,{error:"tool is required"}),!0;let v=a$8(P,"card_id");if(!v)return b(S,400,{error:"MCP action requires card_id"}),!0;if(u==="retrigger-card"||u==="retrigger"){await N(v);let O=Date.now();return b(S,200,{status:"success",data:{ok:!0,cardId:v,actionType:u,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:200}}),!0}let A=c$4(P,"payload");if(u==="chat-send"&&!await _(v)){let O=Date.now();return b(S,409,{error:`chat handler is not configured for card: ${v}`,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:409}),!0}if(u==="chat-send"){let O=typeof A["turn-id"]=="string"?A["turn-id"]:typeof A.turnId=="string"?A.turnId:typeof A.turn=="string"?A.turn:"";if(!O||!String(O).trim()){let U=Date.now();return b(S,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${v}`,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(U).toISOString(),responseSentAtMs:U,responseStatus:400}),!0}}await x(v,u,A);let D=Date.now();return b(S,200,{status:"success",data:{ok:!0,cardId:v,actionType:u,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(D).toISOString(),responseSentAtMs:D,responseStatus:200}}),!0}if(q==="POST"&&l===`${w}/mcp-controlplane`){await B();let f=await I(T),y=typeof f.tool=="string"?f.tool.trim():"",k=f.args&&typeof f.args=="object"&&!Array.isArray(f.args)?f.args:{};if(!y)return b(S,400,{error:"tool is required"}),!0;try{let u=await a$9(y,k,$());if(u&&typeof u=="object"&&!Array.isArray(u)){let P=u;if(P.status==="fail")return b(S,400,{error:b$4(u,"Request failed")}),!0;if(P.status==="error")return b(S,500,{error:b$4(u,"Internal error")}),!0}b(S,200,u);}catch(u){let P=typeof u?.statusCode=="number"?Number(u.statusCode):500,v=u instanceof Error?u.message:String(u);b(S,P,{error:v});}return !0}let R=l.match(new RegExp(`^${c$3(w)}/cards/([^/]+)/retrigger$`));if(q==="POST"&&R){await B();let f=decodeURIComponent(R[1]);return await N(f),b(S,200,{ok:!0}),!0}let F=l.match(new RegExp(`^${c$3(w)}/cards/([^/]+)/actions$`));if(q==="POST"&&F){await B();let f=decodeURIComponent(F[1]),y=Date.now(),k=new Date(y).toISOString(),u=await I(T),P=u?.actionType;if(P==="chat-send"&&!await _(f)){let A=Date.now();return b(S,409,{error:`chat handler is not configured for card: ${f}`,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(A).toISOString(),responseSentAtMs:A,responseStatus:409}),!0}if(P==="chat-send"){let A=u?.payload??{},D=typeof A["turn-id"]=="string"?A["turn-id"]:typeof A.turnId=="string"?A.turnId:typeof A.turn=="string"?A.turn:"";if(!D||!String(D).trim()){let O=Date.now();return b(S,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${f}`,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:400}),!0}}await x(f,P,u?.payload);let v=Date.now();return b(S,200,{ok:!0,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(v).toISOString(),responseSentAtMs:v,responseStatus:200}),!0}let p=l.match(new RegExp(`^${c$3(w)}/cards/([^/]+)/files/(\\d+)$`));if(q==="GET"&&p){let f=decodeURIComponent(p[1]),y=parseInt(p[2],10),k=K.searchParams.get("sn");return await H(S,f,y,k),!0}return !1}catch(R){let F=R?.statusCode||500;return b(S,F,{error:String(R?.message||R)}),true}}return {handleRuntimeApi:E}}var Ke=3e4;function Ve(g){let w=g.socket?.remoteAddress??"";return w==="127.0.0.1"||w==="::1"||w==="::ffff:127.0.0.1"}function ue(g){let{apiBasePath:w,emitNotifications:b,readJsonBody:I,json:B}=g,$=`${w}/notify-q`;async function N(x,_,H){if(H.pathname!==$)return false;if((x.method??"").toUpperCase()!=="POST")return B(_,405,{status:"error",error:"Method not allowed"}),true;if(!Ve(x))return B(_,403,{status:"error",error:"Forbidden"}),true;let E;try{E=await I(x);}catch{return B(_,400,{status:"error",error:"Invalid JSON body"}),true}if(!E||typeof E!="object"||!Array.isArray(E.notifications))return B(_,400,{status:"error",error:"body.notifications must be an array"}),true;let T=E.notifications,{accepted:S,rejected:z}=b$3(T,Date.now(),Ke);return S.length>0&&b(S),B(_,200,{status:"success",data:{accepted:S.length,rejected:z}}),true}return {handleNotifyRoute:N}}var le={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},de="chat-handler-flow-queue",ot="__probe__echo__probe__";function Mr(g$1){let w=String(g$1.apiBasePath||"/api/board").replace(/\/$/,""),b$3={...le,...g$1.corsHeaders||{}},I=g$1.queueLaneTuning??{},B=g$1.boardId||"",$=Number.isInteger(g$1.chatBootstrapTailTurns)&&g$1.chatBootstrapTailTurns>0?g$1.chatBootstrapTailTurns:1,N=g$1.logger||{info:console.log,warn:console.warn,error:console.error},x=g$1.invocationAdapter,_=g$1.chatFlowRunner||null,H$1=g$1.notificationTransport||null,E=g$1.serverUrl||null,T=g$1.executionExtra||{},S=g$1.onSseClientConnected,z=g$1.onSseClientDisconnected,q=g$1.onChannelSubscribed,K=g$1.onChannelUnsubscribed,l$1=a({buildChatOneShotBatch:async(t,e)=>await Q.buildSseOneShotBatch({params:{cardId:t},body:{receiving:e}}),onSseClientDisconnected:z}),R=a({buildChatOneShotBatch:async()=>({status:"success",data:{kind:"notification-batch",category:"batch",notifications:[]}})});function F(t){function e$1(a){return {...a,queueStorageForRef(d,C){return a$6(a.queueStorageForRef(d,C),{lane:C,emitNotification:i$1})}}}function r(a){return {...a,queueStorageForRef(d,C){return h(a.queueStorageForRef(d,C),{lane:C,emitNotification:i$1})}}}function n(a){return {async get(d){return a.get(d)},async set(d){return a.set(d)},async del(d){return a.del(d)},async patch(d){return a.patch(d)},async appendFiles(d){return a.appendFiles(d)}}}function o(a){return {async get(d){return await a.get(d)},async set(d){return await a.set(d)},async del(d){return await a.del(d)},async patch(d){return await a.patch(d)},async appendFiles(d){return await a.appendFiles(d)}}}let s=null;function i$1(a){if(a.kind==="notification-batch"){V(a.notifications,s??void 0);return}V([a],s??void 0);}let c$2=a$4(t.boardAdapter)?r(t.boardAdapter):e$1(t.boardAdapter),j=t.nonCoreAdapter??(!a$4(c$2)&&P(c$2)?c$2:null),h$1=a$4(c$2)?i(t.baseRef,c$2,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,scratchStoreRef:t.scratchStoreRef,taskExecutorRef:t.taskExecutorRef,chatHandlerFlow:t.chatHandlerFlow,emitNotification:i$1}):e(t.baseRef,c$2,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,scratchStoreRef:t.scratchStoreRef,taskExecutorRef:t.taskExecutorRef,chatHandlerFlow:t.chatHandlerFlow,emitNotification:i$1}),M=t.nonCore??(j?f(t.baseRef,j,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,taskExecutorRef:t.taskExecutorRef}):null),We=c$2.chatStorageForRef(t.chatStoreRef),lt,Je=a$4(c$2)?(()=>{let a=d(c(b$1(c$2.kvStorageForRef(t.cardStoreRef)),c$2.hashFn),N.warn),d$1=g(a,{emitNotification:i$1}),C=o(d$1);return lt={get(m){return C.get(m)},set(m){return C.set(m)}},C})():(()=>{let a=c$2.kvStorageForRef(t.cardStoreRef),C=H(m({readIndex:()=>a.read("_index"),writeIndex:m=>a.write("_index",m),readCard:m=>a.read(m),writeCard:(m,pt)=>(a.write(m,pt),m),removeCard:m=>{a.delete(m);},cardExists:m=>a.read(m)!==null,defaultCardKey:m=>m},N.warn),{emitNotification:i$1});return lt=C,n(C)})(),ft;if(a$4(c$2)){let a=c$2.blobStorageForRef(t.artifactsStoreRef);ft={async putBytes(d,C){if(a.writeBytes){await a.writeBytes(d,C);return}let m=JSON.stringify({__kind:"bytes-array",data:[...C]});await a.write(d,m);},async getBytes(d){if(a.readBytes){let m=await a.readBytes(d);if(m!==null)return m}let C=await a.read(d);if(C===null)return null;try{let m=JSON.parse(C);if(m&&m.__kind==="bytes-array"&&Array.isArray(m.data))return new Uint8Array(m.data)}catch{}return new TextEncoder().encode(C)},async listKeys(d){return await a.listKeys(d)}};}else {let a=c$2.blobStorageForRef(t.artifactsStoreRef),d=a$5(a);ft={putBytes(C,m,pt){d.putBytes(C,m,pt);},getBytes(C){return d.getBytes(C)},listKeys(C){return d.list(C).map(m=>m.key)}};}let ze={async init(a){return h$1.init(a)},async status(a){return h$1.status(a)},async getConfig(a){return h$1.getConfig(a)},async getAllOutputsDataObjects(a){return h$1.getAllOutputsDataObjects(a)},async getAllOutputsComputedValues(a){return h$1.getAllOutputsComputedValues(a)},async getOutputsFetchedSources(a){return h$1.getOutputsFetchedSources(a)},async buildSseOneShotPayload(a){return h$1.buildSseOneShotPayload(a)},async upsertCard(a){return h$1.upsertCard(a)},async removeCard(a){return h$1.removeCard(a)},async sourceDataFetched(a){return h$1.sourceDataFetched(a)},async sourceDataFetchFailure(a){return h$1.sourceDataFetchFailure(a)}};return s={label:t.label,board:h$1,nonCore:M,publicCardStore:lt,boardOps:ze,cardStoreOps:Je,get filesArtifacts(){return ft},get chatStorage(){return We},boardAdapter:c$2,boardRuntimeStoreRef:t.boardRuntimeStoreRef,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,artifactsStoreRef:t.artifactsStoreRef,fetchedSourcesStoreRef:t.fetchedSourcesStoreRef,queueStoreRef:t.queueStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef,notifyRef:t.notifyRef,taskExecutorRef:t.taskExecutorRef,chatHandlerRef:t.chatHandlerRef,chatHandlerFlow:t.chatHandlerFlow,inferenceAdapterRef:t.inferenceAdapterRef,notification:c$1(),notificationTeardown:null,initialized:false,cardsBootstrapped:false},s}let p$1=g$1.boards.map(F),f$1=new Map;function y(t){return f$1.get(t)??0}function k$1(t){return t.queueStoreRef}function u(t,e){if(a$4(t.boardAdapter)){let n=t.boardAdapter.queueStorageForRef(k$1(t),e);return a$a(n)}let r=t.boardAdapter.queueStorageForRef(k$1(t),e);return a$b(r)}function P(t){let e=t;return typeof e.invokeExecutor=="function"&&typeof e.validateSchema=="function"}function v(t){let e=p$1[y(t)];return {files:e?e.filesArtifacts:null}}function A(){return c$2()}function D(t){return String(t||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}function O(t){return "cardId"in t&&typeof t.cardId=="string"?W(t.cardId)??void 0:p$1[0]??void 0}function U(t){for(let e of t){let r=O(e);if(r)return r}return p$1[0]??void 0}function ct(t,e={}){if(!t||t.length===0)return;let r=e$1(t),n={kind:"notification-batch",category:"batch",notifications:r},o=e.ctx??U(r);if(e.appendState!==false&&o&&e$2(o.notification,n),e.broadcastSse!==false){let s=r.filter(c=>c.kind==="message_enqueued"),i=r.filter(c=>c.kind!=="message_enqueued");i.length>0&&l$1.broadcastNotificationBatch(i),s.length>0&&R.broadcastNotificationBatch(s);}if(!(e.mirrorExternal===false||!o?.boardAdapter.publishBoardChangeNotifications))try{let s=r.filter(i=>i.category==="board-output"||i.category==="card-store"||i.category==="chat-store"||i.category==="hosted-runtime");s.length>0&&o.boardAdapter.publishBoardChangeNotifications(s);}catch{}}function V(t,e){ct(t,{ctx:e,appendState:true,broadcastSse:true,mirrorExternal:true});}async function fe(t){if(!t||t.notificationTeardown||!H$1||!t.notifyRef)return;let e=await H$1.subscribe(t.notifyRef,r=>{let n=a$7(r);ct(n,{ctx:t,appendState:true,broadcastSse:true,mirrorExternal:false});});t.notificationTeardown=e;}async function pe(t){if(!t||t.initialized)return;let e={boardRuntimeStoreRef:t.boardRuntimeStoreRef,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,fetchedSourcesStoreRef:t.fetchedSourcesStoreRef,artifactsStoreRef:t.artifactsStoreRef,queueStoreRef:t.queueStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef},r={};t.taskExecutorRef&&(r["task-executor-ref"]=t.taskExecutorRef),t.chatHandlerFlow!==void 0&&(r["chat-handler-flow"]=t.chatHandlerFlow);let n=await t.boardOps.init({params:e,body:r});if(n.status!=="success")throw Object.assign(new Error(n.error||`init failed for ${t.label}`),{statusCode:500});if(await fe(t),!t.chatHandlerFlow&&t.chatHandlerRef&&x.describe)try{let o=await x.describe(t.chatHandlerRef);o&&o.kind!=="chat-handler"?N.warn(`[init] chat-handler describe returned kind="${o.kind}", expected "chat-handler" for ${t.label}`):o&&N.info(`[init] chat-handler validated: ${o.name} (protocol ${o.protocolVersion}) for ${t.label}`);}catch(o){N.warn(`[init] chat-handler describe failed for ${t.label}: ${o?.message||String(o)}`);}t.initialized=true;}async function ut(t){let e=[],r=await t.boardOps.status({});r.status==="success"&&r.data!=null&&d$1(r.data)&&e.push({kind:"status",status:r.data});let n=await t.boardOps.getAllOutputsDataObjects({});if(n.status==="success"&&n.data!=null)for(let[s,i]of Object.entries(n.data))s&&e.push({kind:"data_object",key:s,payload:i});let o=await t.boardOps.getAllOutputsComputedValues({});if(o.status==="success"&&o.data!=null)for(let[s,i]of Object.entries(o.data))s&&i&&typeof i=="object"&&!Array.isArray(i)&&e.push({kind:"computed_values",cardId:s,values:i});e.length>0&&ct(e,{ctx:t,appendState:true,broadcastSse:true,mirrorExternal:false});}async function Rt(t,e){if(!t||t.cardsBootstrapped)return;let r=await t.cardStoreOps.get({}),n=r.status==="success"&&Array.isArray(r.data?.cards)?r.data.cards:[];for(let o of n)typeof o.id=="string"&&(f$1.set(o.id,e),await t.boardOps.upsertCard({params:{cardId:o.id}}));t.cardsBootstrapped=true;}async function G(){for(let t of p$1)await pe(t);}async function at(){await G();for(let t=0;t<p$1.length;t++)await ut(p$1[t]),await Rt(p$1[t],t),await ut(p$1[t]);}async function yt(t=false){t||await G();for(let e of p$1){let r=await e.board.processAccumulatedEvents({});if(r.status!=="success")return r}return {status:"success"}}function W(t){return p$1[y(t)]??null}async function Y(t){let e=W(t);if(!e)return null;let r=await e.cardStoreOps.get({params:{id:t}});if(r.status!=="success")return null;let n=Array.isArray(r.data?.cards)?r.data.cards:[];return n.length>0?n[0]:null}async function me(){let t=async r=>{if(!r)return [];let n=await r.cardStoreOps.get({});return n.status!=="success"||!Array.isArray(n.data?.cards)?[]:n.data.cards},e=[];for(let r of p$1)e.push(...await t(r));return e}function ht(){return p$1[0]??null}function ge(t){return W(t)??ht()}function L(t){let e=ge(t);if(!e)throw Object.assign(new Error(`Board context is unavailable for chat operations: ${t}`),{statusCode:404});return e.chatStorage}async function Re(t){return await L(t).isProcessing(t)}async function tt(t,e){let r=await Q.setProcessing({params:{cardId:t},body:{active:e}});if(r.status!=="success")throw Object.assign(new Error(r.error||`Failed to set chat processing for card: ${t}`),{statusCode:500})}let Q=a$1({append(t,e,r,n,o){return L(t).append(t,e,r,n,o)},readAll(t){return L(t).readAll(t)},readAfter(t,e){return L(t).readAfter(t,e)},clear(t){return L(t).clear(t)},setProcessing(t,e){return L(t).setProcessing(t,e)},isProcessing(t){return L(t).isProcessing(t)},getConfig(t){return L(t).getConfig(t)},setConfig(t,e){return L(t).setConfig(t,e)}},{emitNotification(t){if(t.kind==="notification-batch"){V(t.notifications);return}V([t]);}}),wt=p({boardContexts:p$1,cardOwnerIndex:f$1,cardContextForCard:t=>W(t),readStatusSnapshot:()=>Se(),readDataObjectsByToken:()=>Ae(),readCardRuntimeArtifacts:()=>Ce(),readCardFromStore:t=>Y(t),readCardDefinitions:()=>me(),processAccumulatedLaneInternal:t=>yt(t),reportSourceFetched:(t,e)=>kt(t,{ref:e}),reportSourceFetchFailure:(t,e)=>Pt(t,{reason:e}),uploadCardFile:(t,e,r,n,o)=>Ct(t,e,r,n,o),chatStorePublic:Q,serverUrl:E,apiBasePath:w}),ye=wt.mcpCardStoreFacade,st=wt.createMcpFacade,he=j({boardId:B,bootstrapBoard:()=>at(),sseHub:l$1,onChannelSubscribed:q,onChannelUnsubscribed:K,getMcpFacade:()=>st(),getMcpCardStoreFacade:()=>ye()});function we(t){return m$1(t)}function be(){return n(st())}function bt(){return o({boardId:B,uploadCardFile:Ct,getMcpFacade:()=>st(),controlplane:he})}let it=k({boardId:B,boardContexts:p$1,readChatRecords:(t,e)=>ve(t,e),getChatProcessing:t=>Re(t),chatBootstrapTailTurns:$}),Se=it.readStatusSnapshot,Ce=it.readCardRuntimeArtifacts,Ae=it.readDataObjectsByToken,dt=it.buildPublishedRuntimePayload;async function St(t,e,r){let n=r?.syncBoard!==false,o=r?.restartOnlyIfChanged===true,s=W(t);if(!s)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let i=await Y(t);if(!i)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let c=o?JSON.stringify(i):null,j=e(i)||i;if(o&&JSON.stringify(j)===c)return;let h=await s.cardStoreOps.set({body:j});if(h.status!=="success")throw Object.assign(new Error(h.error||`Failed to persist card: ${t}`),{statusCode:500});if(n){let M=await s.boardOps.upsertCard({params:{cardId:t,restart:true}});if(M.status!=="success")throw Object.assign(new Error(M.error||`Failed to upsert card: ${t}`),{statusCode:500})}}async function Be(t,e){await St(t,e,{syncBoard:true});}async function ke(t,e){await St(t,e,{syncBoard:false});}async function Pe(t){let e=W(t);if(!e)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});if(!await Y(t))throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let n=await e.boardOps.upsertCard({params:{cardId:t,restart:true}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to retrigger card: ${t}`),{statusCode:500})}async function Oe(t){let e=await Q.clear({params:{cardId:t}});if(e.status!=="success")throw Object.assign(new Error(e.error||`Failed to clear chat records for card: ${t}`),{statusCode:500});try{await tt(t,!1);}catch{}}async function Fe(t,e,r,n,o=""){let s=typeof r=="string"?r.trim():"",i=await Q.append({params:{cardId:t},body:{role:e||"system",text:s,files:n,turn:o}});if(i.status!=="success")throw Object.assign(new Error(i.error||`Failed to append chat record for card: ${t}`),{statusCode:500});return String(i.data?.id||"")}async function ve(t,e){let r=Number.isInteger(e?.tailTurns)&&e?.tailTurns>0?e?.tailTurns:void 0,n=await Q.readAll({params:{cardId:t},...r===void 0?{}:{body:{tailTurns:r}}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to read chat records for card: ${t}`),{statusCode:500});return Array.isArray(n.data?.records)?n.data.records:[]}let Ct=l({safeCardId:t=>D(t),artifactsStores:t=>v(t),cardFileMetadataStore:()=>A(),readCardFromStore:t=>Y(t),updateCardLocalOnly:(t,e)=>ke(t,e),writeChatRecord:(t,e,r,n,o)=>Fe(t,e,r,n,o)}).uploadCardFile;async function At(t){let e=W(t);if(!e)return null;let r=await e.boardOps.getConfig({params:{key:"chat-handler-flow"}}),o=(r.status==="success"?r.data?.value:null)??e.chatHandlerFlow??null,s=e.chatHandlerRef;return o==null&&(!s||typeof s!="object")?null:{ctx:e,handlerFlow:o,handlerRef:s}}function xe(t){let e=typeof t=="string"?t.trim():"";if(e.length<ot.length*2||!e.startsWith(ot)||!e.endsWith(ot))return null;let r=e.slice(ot.length,e.length-ot.length).trim(),n=/^([A-Za-z0-9_-]+)__(.*)$/s.exec(r);return n?{assistant:n[1].trim().toLowerCase(),text:n[2].trim()}:{assistant:"echo",text:r}}async function Te(t,e,r=false,n="",o=""){try{let s=await At(t);if(!s){try{await tt(t,!1);}catch{}return}let{ctx:i,handlerFlow:c,handlerRef:j}=s;if(!r)try{await tt(t,!0);}catch{}let h={boardId:B,cardId:String(t),lastChatEntryId:e,...n?{turnId:n}:{},...typeof o=="string"&&o.trim()?{probe:o.trim()}:{},...T,...E?{serverUrl:E}:{}},M=c!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:de}}:j;a$4(i.boardAdapter)?await u(i,"chat-agent").enqueueRequest({boardId:B,ref:M,args:c!=null?{...h,__chatHandlerFlow:c}:h}):u(i,"chat-agent").enqueueRequest({boardId:B,ref:M,args:c!=null?{...h,__chatHandlerFlow:c}:h}),await Promise.resolve(i.boardAdapter.requestProcessAccumulated?.());}catch(s){try{await tt(t,!1);}catch{}N.warn(`[chat-handler] queue failed for card "${t}": ${s instanceof Error?s.message:String(s)}`);}}async function Ne(t,e,r){if(e.howToRun==="built-in"&&b$2(e)===de){let n=_,o=r.__chatHandlerFlow,s={...r};return delete s.__chatHandlerFlow,n?n.run(o,s,{boardId:B,cardId:String(s.cardId||""),label:t.label,logger:N,serverUrl:E,executionExtra:T}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return x.invoke(e,r)}async function Ee(t,e=false){e||await G();let r=typeof t.args?.cardId=="string"?t.args.cardId:"",n=r?W(r):ht();if(!n)throw new Error(r?`Board context is unavailable for chat-agent request: ${r}`:"Board context is unavailable for chat-agent request");let o=await Ne(n,t.ref,t.args);if(!o.dispatched){if(r)try{await tt(r,!1);}catch{}throw new Error(o.error||`chat-agent dispatch failed for card "${r||"unknown"}"`)}}async function je(t,e,r){if(e==="chat-send"){let o=r&&typeof r["turn-id"]=="string"?r["turn-id"]:r&&typeof r.turnId=="string"?r.turnId:r&&typeof r.turn=="string"?r.turn:"";if(r&&"files"in r&&r.files!==void 0&&r.files!==null)throw Object.assign(new Error('chat-send does not accept a "files" parameter; upload attachments via manage.add-chat-attachment first'),{statusCode:400});let s=bt(),i=xe(r?.text),c=i?i.text:r?.text,j=await a$9("manage.add-chat-entry-and-any-attachments",{board_id:B,card_id:t,role:"user",text:c,turn_id:o,files:[]},s);if(j?.status!=="success")throw new Error(b$4(j,`chat-send append failed for card ${t}`));let h=j?.data?.id;if(typeof h!="string"||!h)throw new Error(`chat-send did not return an append id for card ${t}`);let M=await a$9("setstate.chat-processing-started",{board_id:B,card_id:t},s);if(M?.status!=="success")throw new Error(b$4(M,`chat-send processing update failed for card ${t}`));Te(t,h,true,o,i?.assistant||"");return}await Be(t,o=>{let s=new Date().toISOString(),i=o.card_data&&typeof o.card_data=="object"?o.card_data:{};if(o.card_data=i,e==="file-upload"){let c=A().normalizeIncoming(r?.files,s);return c.length>0&&A().merge(i,c),o}if(e==="action"){let c=r&&typeof r.buttonId=="string"?r.buttonId:"";if(!c)return o;i.lastAction={buttonId:c,at:s},i.lastActionText=`${c} @ ${s}`;}return o});}function et(t,e,r){let n=JSON.stringify(r),o=typeof Buffer<"u"?Buffer.byteLength(n):new TextEncoder().encode(n).length;t.writeHead(e,{...b$3,"Content-Type":"application/json; charset=utf-8","Content-Length":o}),t.end(n);}async function Bt(t,e,r){let n=await Y(t);if(!n)throw Object.assign(new Error("Card not found"),{statusCode:404});let o=A().resolve(n.card_data,e,r);if(!o.ok&&o.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!o.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let s=o.file,i=D(t),c=v(t),j=String(s.stored_name||""),h=`${i}/${j}`,M=c.files?await c.files.getBytes(h):null;if(!M)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:s,bytes:M}}async function Me(t,e,r,n){let{fileRecord:o,bytes:s}=await Bt(e,r,n),i=String(o.name||o.stored_name||"download.bin"),c=String(o.mime_type||"application/octet-stream");t.writeHead(200,{"Content-Type":c,"Content-Disposition":`attachment; filename="${i}"`,"Content-Length":s.length}),t.end(s);}function _e(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 De(t,e,r){let n=t.split(/\r?\n/);return (e==="head"?n.slice(0,r):n.slice(-r)).join(`
2
- `)}async function rt(t){let e=[];for await(let n of t)e.push(n);let r=typeof Buffer<"u"?Buffer.concat(e).toString("utf-8").trim():new TextDecoder().decode(d$2(e)).trim();return r?JSON.parse(r):{}}async function kt(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 n=p$1[0];return n?n.boardOps.sourceDataFetched({params:{token:t,ref:r}}):{status:"fail",error:"no board context"}}async function Pt(t,e){let r=typeof e.reason=="string"&&e.reason.trim()?e.reason:"unknown",n=p$1[0];return n?n.boardOps.sourceDataFetchFailure({params:{token:t,reason:r}}):{status:"fail",error:"no board context"}}let Ie=b({sseHub:l$1,queueSseHub:R,corsHeaders:b$3,json:et,buildPublishedRuntimePayload:()=>dt(),onSseClientConnected:S,onChannelSubscribed:q,onChannelUnsubscribed:K,apiBasePath:w,readJsonBody:t=>rt(t),initBoardAndSetup:()=>G(),bootstrapBoard:()=>at(),boardContexts:p$1,publishPersistedStateSnapshot:t=>ut(t),upsertCardsFromSource:(t,e)=>Rt(t,e)}).handleWatchersRoutes,qe=a$2({apiBasePath:w,json:et,readJsonBody:t=>rt(t),bootstrapBoard:()=>at(),createMcpFacade:()=>st(),createMcpToolRegistry:t=>we(t),resolveCardFileDownloadPayload:(t,e,r)=>Bt(t,e,r),isLikelyTextMimeType:t=>_e(t),sliceTextByLines:(t,e,r)=>De(t,e,r)}).handleAgentfaceApi,$e=a$3({apiBasePath:w,json:et,readJsonBody:t=>rt(t),initBoardAndSetup:()=>G(),createMcpWebhookToolRegistry:()=>be()}).handleWebhooksApi,He=ce({apiBasePath:w,json:et,readJsonBody:t=>rt(t),bootstrapBoard:()=>at(),createMcpControlplaneToolRegistry:()=>bt(),retriggerCard:t=>Pe(t),applyCardAction:(t,e,r)=>je(t,e,r),resolveChatHandlerTarget:t=>At(t),sendCardFileDownloadResponse:(t,e,r,n)=>Me(t,e,r,n)}).handleRuntimeApi,Le=ue({apiBasePath:w,emitNotifications:t=>V(t),readJsonBody:t=>rt(t),json:(t,e,r)=>et(t,e,r)}).handleNotifyRoute;async function Ue(t,e,r){return !!(await qe(t,e,r)||await $e(t,e,r)||await Ie(t,e,r)||await Le(t,e,r)||await He(t,e,r))}return {get apiBasePath(){return w},get corsHeaders(){return b$3},get queueLaneTuning(){return I},handleRuntimeApi:Ue,emitNotification(t){if(t.kind==="notification-batch"){V(t.notifications);return}V([t]);},buildPublishedRuntimePayload:dt,__drainProcessAccumulatedLane:yt,handleChatAgentRequest:Ee,clearChatRecords:Oe,reportSourceFetched(t,e){return kt(t,{ref:e})},reportSourceFetchFailure(t,e){return Pt(t,{reason:e})},get cardStore(){return p$1[0]?.publicCardStore??{get(){return Promise.resolve({status:"fail",error:"no board context"})},set(){return Promise.resolve({status:"fail",error:"no board context"})}}}}}function _r(g){let w=String(g.apiBasePath||"/api/boards").replace(/\/$/,""),b={...le,...g.corsHeaders||{}},I=g.serverMetaStore,B=g.boardRuntimeFactory,$=new Map,N="boards-config.json";function x(){let l=I.getText(N);if(!l)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(l)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function _(l){I.putText(N,JSON.stringify(l,null,2));}function H(l){let R=String(l||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return R.length>0&&R.length<=64?R:null}function E(l){if($.has(l))return $.get(l);let F=x().boards.find(f=>f.id===l)||{},p=B(l,F);return $.set(l,p),p}function T(l,R,F){let p=JSON.stringify(F),f=typeof Buffer<"u"?Buffer.byteLength(p):new TextEncoder().encode(p).length;l.writeHead(R,{...b,"Content-Type":"application/json; charset=utf-8","Content-Length":f}),l.end(p);}async function S(l,R,F){let p=l.method||"GET",f=F.pathname;if(p==="GET"&&f===w)return T(R,200,{ok:true,boards:x().boards}),true;if(p==="POST"&&f===w){let y=[];for await(let O of l)y.push(O);let k=typeof Buffer<"u"?Buffer.concat(y).toString("utf-8").trim():new TextDecoder().decode(d$2(y)).trim(),u={};try{u=k?JSON.parse(k):{};}catch{u={};}let P=H(u.id);if(!P)return T(R,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let v=x();if(v.boards.some(O=>O.id===P))return T(R,409,{error:`Board "${P}" is already registered`}),true;let A=typeof u.label=="string"&&u.label.trim()?u.label.trim():P,D={id:P,label:A};for(let[O,U]of Object.entries(u))O==="id"||O==="label"||U!=null&&(D[O]=U);return v.boards.push(D),_(v),T(R,200,{ok:true,board:D}),true}return false}async function z(l,R,F){let f=F.pathname.match(new RegExp(`^${c$3(w)}/([^/]+)(/|$)`));if(!f)return false;let y=H(decodeURIComponent(f[1]));return y?x().boards.some(P=>P.id===y)?!!await E(y).handleRuntimeApi(l,R,F):(T(R,404,{error:`Board "${y}" not registered. POST ${w} with {id} to register it first.`}),true):(T(R,400,{error:"Invalid board id"}),true)}async function q(l,R,F){return !!(await S(l,R,F)||await z(l,R,F))}function K(l){if(!x().boards.some(F=>F.id===l))throw Object.assign(new Error(`Board "${l}" not registered`),{statusCode:404});return {service:E(l)}}return {get apiBasePath(){return w},get corsHeaders(){return b},handleApi:q,requireBoardService:K}}export{Mr as a,_r as b};//# sourceMappingURL=chunk-HKPVF5UI.js.map
3
- //# sourceMappingURL=chunk-HKPVF5UI.js.map
1
+ import {a,b}from'./chunk-JB4Q2W7I.js';import {a as a$3}from'./chunk-XYN5D3GL.js';import {a as a$5,c as c$2}from'./chunk-O5UYCGIN.js';import {p,j,k,l,c as c$1,d as d$1,m as m$1,n,e as e$2,a as a$7,b as b$3,o}from'./chunk-PIPXFUEA.js';import {a as a$4,d as d$2,b as b$2,c as c$3}from'./chunk-FOFGEABN.js';import {a as a$b}from'./chunk-RKKSVOP2.js';import {a as a$2}from'./chunk-NTICU4OK.js';import {a as a$8,c as c$4}from'./chunk-O7NOHKVR.js';import {a as a$9,b as b$4}from'./chunk-ZJ5M5COT.js';import {i,d,c,b as b$1,g,h}from'./chunk-REZO2QJD.js';import {a as a$a}from'./chunk-PEJRTZU3.js';import {e,f}from'./chunk-BRYV6CDD.js';import {H,m}from'./chunk-MRESV3MD.js';import {a as a$6}from'./chunk-BJGK5FNL.js';import {a as a$1}from'./chunk-NIBLKYXN.js';import {e as e$1}from'./chunk-UGB7PC4P.js';function ce(g){let{apiBasePath:w,json:b,readJsonBody:I,bootstrapBoard:B,createMcpControlplaneToolRegistry:$,retriggerCard:N,applyCardAction:x,resolveChatHandlerTarget:_,sendCardFileDownloadResponse:H}=g;async function E(T,S,z){let q=T.method||"GET",K=z,l=K.pathname;try{if(q==="POST"&&l===`${w}/mcp-actions`){await B();let f=Date.now(),y=new Date(f).toISOString(),k=await I(T),u=typeof k.tool=="string"?k.tool.trim():"",P=k.args&&typeof k.args=="object"&&!Array.isArray(k.args)?k.args:{};if(!u)return b(S,400,{error:"tool is required"}),!0;let v=a$8(P,"card_id");if(!v)return b(S,400,{error:"MCP action requires card_id"}),!0;if(u==="retrigger-card"||u==="retrigger"){await N(v);let O=Date.now();return b(S,200,{status:"success",data:{ok:!0,cardId:v,actionType:u,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:200}}),!0}let A=c$4(P,"payload");if(u==="chat-send"&&!await _(v)){let O=Date.now();return b(S,409,{error:`chat handler is not configured for card: ${v}`,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:409}),!0}if(u==="chat-send"){let O=typeof A["turn-id"]=="string"?A["turn-id"]:typeof A.turnId=="string"?A.turnId:typeof A.turn=="string"?A.turn:"";if(!O||!String(O).trim()){let U=Date.now();return b(S,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${v}`,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(U).toISOString(),responseSentAtMs:U,responseStatus:400}),!0}}await x(v,u,A);let D=Date.now();return b(S,200,{status:"success",data:{ok:!0,cardId:v,actionType:u,requestReceivedAt:y,requestReceivedAtMs:f,responseSentAt:new Date(D).toISOString(),responseSentAtMs:D,responseStatus:200}}),!0}if(q==="POST"&&l===`${w}/mcp-controlplane`){await B();let f=await I(T),y=typeof f.tool=="string"?f.tool.trim():"",k=f.args&&typeof f.args=="object"&&!Array.isArray(f.args)?f.args:{};if(!y)return b(S,400,{error:"tool is required"}),!0;try{let u=await a$9(y,k,$());if(u&&typeof u=="object"&&!Array.isArray(u)){let P=u;if(P.status==="fail")return b(S,400,{error:b$4(u,"Request failed")}),!0;if(P.status==="error")return b(S,500,{error:b$4(u,"Internal error")}),!0}b(S,200,u);}catch(u){let P=typeof u?.statusCode=="number"?Number(u.statusCode):500,v=u instanceof Error?u.message:String(u);b(S,P,{error:v});}return !0}let R=l.match(new RegExp(`^${c$3(w)}/cards/([^/]+)/retrigger$`));if(q==="POST"&&R){await B();let f=decodeURIComponent(R[1]);return await N(f),b(S,200,{ok:!0}),!0}let F=l.match(new RegExp(`^${c$3(w)}/cards/([^/]+)/actions$`));if(q==="POST"&&F){await B();let f=decodeURIComponent(F[1]),y=Date.now(),k=new Date(y).toISOString(),u=await I(T),P=u?.actionType;if(P==="chat-send"&&!await _(f)){let A=Date.now();return b(S,409,{error:`chat handler is not configured for card: ${f}`,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(A).toISOString(),responseSentAtMs:A,responseStatus:409}),!0}if(P==="chat-send"){let A=u?.payload??{},D=typeof A["turn-id"]=="string"?A["turn-id"]:typeof A.turnId=="string"?A.turnId:typeof A.turn=="string"?A.turn:"";if(!D||!String(D).trim()){let O=Date.now();return b(S,400,{error:`chat-send requires a non-empty 'turn-id' (or 'turnId'/'turn') in payload for card: ${f}`,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(O).toISOString(),responseSentAtMs:O,responseStatus:400}),!0}}await x(f,P,u?.payload);let v=Date.now();return b(S,200,{ok:!0,requestReceivedAt:k,requestReceivedAtMs:y,responseSentAt:new Date(v).toISOString(),responseSentAtMs:v,responseStatus:200}),!0}let p=l.match(new RegExp(`^${c$3(w)}/cards/([^/]+)/files/(\\d+)$`));if(q==="GET"&&p){let f=decodeURIComponent(p[1]),y=parseInt(p[2],10),k=K.searchParams.get("sn");return await H(S,f,y,k),!0}return !1}catch(R){let F=R?.statusCode||500;return b(S,F,{error:String(R?.message||R)}),true}}return {handleRuntimeApi:E}}var Ke=3e4;function Ve(g){let w=g.socket?.remoteAddress??"";return w==="127.0.0.1"||w==="::1"||w==="::ffff:127.0.0.1"}function ue(g){let{apiBasePath:w,emitNotifications:b,readJsonBody:I,json:B}=g,$=`${w}/notify-q`;async function N(x,_,H){if(H.pathname!==$)return false;if((x.method??"").toUpperCase()!=="POST")return B(_,405,{status:"error",error:"Method not allowed"}),true;if(!Ve(x))return B(_,403,{status:"error",error:"Forbidden"}),true;let E;try{E=await I(x);}catch{return B(_,400,{status:"error",error:"Invalid JSON body"}),true}if(!E||typeof E!="object"||!Array.isArray(E.notifications))return B(_,400,{status:"error",error:"body.notifications must be an array"}),true;let T=E.notifications,{accepted:S,rejected:z}=b$3(T,Date.now(),Ke);return S.length>0&&b(S),B(_,200,{status:"success",data:{accepted:S.length,rejected:z}}),true}return {handleNotifyRoute:N}}var le={"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"content-type,x-file-name","Access-Control-Allow-Methods":"GET,POST,PATCH,OPTIONS"},de="chat-handler-flow-queue",ot="__probe__echo__probe__";function Mr(g$1){let w=String(g$1.apiBasePath||"/api/board").replace(/\/$/,""),b$3={...le,...g$1.corsHeaders||{}},I=g$1.queueLaneTuning??{},B=g$1.boardId||"",$=Number.isInteger(g$1.chatBootstrapTailTurns)&&g$1.chatBootstrapTailTurns>0?g$1.chatBootstrapTailTurns:1,N=g$1.logger||{info:console.log,warn:console.warn,error:console.error},x=g$1.invocationAdapter,_=g$1.chatFlowRunner||null,H$1=g$1.notificationTransport||null,E=g$1.serverUrl||null,T=g$1.executionExtra||{},S=g$1.onSseClientConnected,z=g$1.onSseClientDisconnected,q=g$1.onChannelSubscribed,K=g$1.onChannelUnsubscribed,l$1=a({buildChatOneShotBatch:async(t,e)=>await Q.buildSseOneShotBatch({params:{cardId:t},body:{receiving:e}}),onSseClientDisconnected:z}),R=a({buildChatOneShotBatch:async()=>({status:"success",data:{kind:"notification-batch",category:"batch",notifications:[]}})});function F(t){function e$1(a){return {...a,queueStorageForRef(d,C){return a$6(a.queueStorageForRef(d,C),{lane:C,emitNotification:i$1})}}}function r(a){return {...a,queueStorageForRef(d,C){return h(a.queueStorageForRef(d,C),{lane:C,emitNotification:i$1})}}}function n(a){return {async get(d){return a.get(d)},async set(d){return a.set(d)},async del(d){return a.del(d)},async patch(d){return a.patch(d)},async appendFiles(d){return a.appendFiles(d)}}}function o(a){return {async get(d){return await a.get(d)},async set(d){return await a.set(d)},async del(d){return await a.del(d)},async patch(d){return await a.patch(d)},async appendFiles(d){return await a.appendFiles(d)}}}let s=null;function i$1(a){if(a.kind==="notification-batch"){V(a.notifications,s??void 0);return}V([a],s??void 0);}let c$2=a$4(t.boardAdapter)?r(t.boardAdapter):e$1(t.boardAdapter),j=t.nonCoreAdapter??(!a$4(c$2)&&P(c$2)?c$2:null),h$1=a$4(c$2)?i(t.baseRef,c$2,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,scratchStoreRef:t.scratchStoreRef,taskExecutorRef:t.taskExecutorRef,chatHandlerFlow:t.chatHandlerFlow,emitNotification:i$1}):e(t.baseRef,c$2,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,scratchStoreRef:t.scratchStoreRef,taskExecutorRef:t.taskExecutorRef,chatHandlerFlow:t.chatHandlerFlow,emitNotification:i$1}),M=t.nonCore??(j?f(t.baseRef,j,{boardRuntimeStoreRef:t.boardRuntimeStoreRef,taskExecutorRef:t.taskExecutorRef}):null),We=c$2.chatStorageForRef(t.chatStoreRef),lt,Je=a$4(c$2)?(()=>{let a=d(c(b$1(c$2.kvStorageForRef(t.cardStoreRef)),c$2.hashFn),N.warn),d$1=g(a,{emitNotification:i$1}),C=o(d$1);return lt={get(m){return C.get(m)},set(m){return C.set(m)}},C})():(()=>{let a=c$2.kvStorageForRef(t.cardStoreRef),C=H(m({readIndex:()=>a.read("_index"),writeIndex:m=>a.write("_index",m),readCard:m=>a.read(m),writeCard:(m,pt)=>(a.write(m,pt),m),removeCard:m=>{a.delete(m);},cardExists:m=>a.read(m)!==null,defaultCardKey:m=>m},N.warn),{emitNotification:i$1});return lt=C,n(C)})(),ft;if(a$4(c$2)){let a=c$2.blobStorageForRef(t.artifactsStoreRef);ft={async putBytes(d,C){if(a.writeBytes){await a.writeBytes(d,C);return}let m=JSON.stringify({__kind:"bytes-array",data:[...C]});await a.write(d,m);},async getBytes(d){if(a.readBytes){let m=await a.readBytes(d);if(m!==null)return m}let C=await a.read(d);if(C===null)return null;try{let m=JSON.parse(C);if(m&&m.__kind==="bytes-array"&&Array.isArray(m.data))return new Uint8Array(m.data)}catch{}return new TextEncoder().encode(C)},async listKeys(d){return await a.listKeys(d)}};}else {let a=c$2.blobStorageForRef(t.artifactsStoreRef),d=a$5(a);ft={putBytes(C,m,pt){d.putBytes(C,m,pt);},getBytes(C){return d.getBytes(C)},listKeys(C){return d.list(C).map(m=>m.key)}};}let ze={async init(a){return h$1.init(a)},async status(a){return h$1.status(a)},async getConfig(a){return h$1.getConfig(a)},async getAllOutputsDataObjects(a){return h$1.getAllOutputsDataObjects(a)},async getAllOutputsComputedValues(a){return h$1.getAllOutputsComputedValues(a)},async getOutputsFetchedSources(a){return h$1.getOutputsFetchedSources(a)},async buildSseOneShotPayload(a){return h$1.buildSseOneShotPayload(a)},async upsertCard(a){return h$1.upsertCard(a)},async removeCard(a){return h$1.removeCard(a)},async sourceDataFetched(a){return h$1.sourceDataFetched(a)},async sourceDataFetchFailure(a){return h$1.sourceDataFetchFailure(a)}};return s={label:t.label,board:h$1,nonCore:M,publicCardStore:lt,boardOps:ze,cardStoreOps:Je,get filesArtifacts(){return ft},get chatStorage(){return We},boardAdapter:c$2,boardRuntimeStoreRef:t.boardRuntimeStoreRef,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,artifactsStoreRef:t.artifactsStoreRef,fetchedSourcesStoreRef:t.fetchedSourcesStoreRef,queueStoreRef:t.queueStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef,notifyRef:t.notifyRef,taskExecutorRef:t.taskExecutorRef,chatHandlerRef:t.chatHandlerRef,chatHandlerFlow:t.chatHandlerFlow,inferenceAdapterRef:t.inferenceAdapterRef,notification:c$1(),notificationTeardown:null,initialized:false,cardsBootstrapped:false},s}let p$1=g$1.boards.map(F),f$1=new Map;function y(t){return f$1.get(t)??0}function k$1(t){return t.queueStoreRef}function u(t,e){if(a$4(t.boardAdapter)){let n=t.boardAdapter.queueStorageForRef(k$1(t),e);return a$a(n)}let r=t.boardAdapter.queueStorageForRef(k$1(t),e);return a$b(r)}function P(t){let e=t;return typeof e.invokeExecutor=="function"&&typeof e.validateSchema=="function"}function v(t){let e=p$1[y(t)];return {files:e?e.filesArtifacts:null}}function A(){return c$2()}function D(t){return String(t||"").replace(/[^a-zA-Z0-9_-]/g,"_")||"unknown-card"}function O(t){return "cardId"in t&&typeof t.cardId=="string"?W(t.cardId)??void 0:p$1[0]??void 0}function U(t){for(let e of t){let r=O(e);if(r)return r}return p$1[0]??void 0}function ct(t,e={}){if(!t||t.length===0)return;let r=e$1(t),n={kind:"notification-batch",category:"batch",notifications:r},o=e.ctx??U(r);if(e.appendState!==false&&o&&e$2(o.notification,n),e.broadcastSse!==false){let s=r.filter(c=>c.kind==="message_enqueued"),i=r.filter(c=>c.kind!=="message_enqueued");i.length>0&&l$1.broadcastNotificationBatch(i),s.length>0&&R.broadcastNotificationBatch(s);}if(!(e.mirrorExternal===false||!o?.boardAdapter.publishBoardChangeNotifications))try{let s=r.filter(i=>i.category==="board-output"||i.category==="card-store"||i.category==="chat-store"||i.category==="hosted-runtime");s.length>0&&o.boardAdapter.publishBoardChangeNotifications(s);}catch{}}function V(t,e){ct(t,{ctx:e,appendState:true,broadcastSse:true,mirrorExternal:true});}async function fe(t){if(!t||t.notificationTeardown||!H$1||!t.notifyRef)return;let e=await H$1.subscribe(t.notifyRef,r=>{let n=a$7(r);ct(n,{ctx:t,appendState:true,broadcastSse:true,mirrorExternal:false});});t.notificationTeardown=e;}async function pe(t){if(!t||t.initialized)return;let e={boardRuntimeStoreRef:t.boardRuntimeStoreRef,cardStoreRef:t.cardStoreRef,outputsStoreRef:t.outputsStoreRef,fetchedSourcesStoreRef:t.fetchedSourcesStoreRef,artifactsStoreRef:t.artifactsStoreRef,queueStoreRef:t.queueStoreRef,chatStoreRef:t.chatStoreRef,scratchStoreRef:t.scratchStoreRef},r={};t.taskExecutorRef&&(r["task-executor-ref"]=t.taskExecutorRef),t.chatHandlerFlow!==void 0&&(r["chat-handler-flow"]=t.chatHandlerFlow);let n=await t.boardOps.init({params:e,body:r});if(n.status!=="success")throw Object.assign(new Error(n.error||`init failed for ${t.label}`),{statusCode:500});if(await fe(t),!t.chatHandlerFlow&&t.chatHandlerRef&&x.describe)try{let o=await x.describe(t.chatHandlerRef);o&&o.kind!=="chat-handler"?N.warn(`[init] chat-handler describe returned kind="${o.kind}", expected "chat-handler" for ${t.label}`):o&&N.info(`[init] chat-handler validated: ${o.name} (protocol ${o.protocolVersion}) for ${t.label}`);}catch(o){N.warn(`[init] chat-handler describe failed for ${t.label}: ${o?.message||String(o)}`);}t.initialized=true;}async function ut(t){let e=[],r=await t.boardOps.status({});r.status==="success"&&r.data!=null&&d$1(r.data)&&e.push({kind:"status",status:r.data});let n=await t.boardOps.getAllOutputsDataObjects({});if(n.status==="success"&&n.data!=null)for(let[s,i]of Object.entries(n.data))s&&e.push({kind:"data_object",key:s,payload:i});let o=await t.boardOps.getAllOutputsComputedValues({});if(o.status==="success"&&o.data!=null)for(let[s,i]of Object.entries(o.data))s&&i&&typeof i=="object"&&!Array.isArray(i)&&e.push({kind:"computed_values",cardId:s,values:i});e.length>0&&ct(e,{ctx:t,appendState:true,broadcastSse:true,mirrorExternal:false});}async function Rt(t,e){if(!t||t.cardsBootstrapped)return;let r=await t.cardStoreOps.get({}),n=r.status==="success"&&Array.isArray(r.data?.cards)?r.data.cards:[];for(let o of n)typeof o.id=="string"&&(f$1.set(o.id,e),await t.boardOps.upsertCard({params:{cardId:o.id}}));t.cardsBootstrapped=true;}async function G(){for(let t of p$1)await pe(t);}async function at(){await G();for(let t=0;t<p$1.length;t++)await ut(p$1[t]),await Rt(p$1[t],t),await ut(p$1[t]);}async function yt(t=false){t||await G();for(let e of p$1){let r=await e.board.processAccumulatedEvents({});if(r.status!=="success")return r}return {status:"success"}}function W(t){return p$1[y(t)]??null}async function Y(t){let e=W(t);if(!e)return null;let r=await e.cardStoreOps.get({params:{id:t}});if(r.status!=="success")return null;let n=Array.isArray(r.data?.cards)?r.data.cards:[];return n.length>0?n[0]:null}async function me(){let t=async r=>{if(!r)return [];let n=await r.cardStoreOps.get({});return n.status!=="success"||!Array.isArray(n.data?.cards)?[]:n.data.cards},e=[];for(let r of p$1)e.push(...await t(r));return e}function ht(){return p$1[0]??null}function ge(t){return W(t)??ht()}function L(t){let e=ge(t);if(!e)throw Object.assign(new Error(`Board context is unavailable for chat operations: ${t}`),{statusCode:404});return e.chatStorage}async function Re(t){return await L(t).isProcessing(t)}async function tt(t,e){let r=await Q.setProcessing({params:{cardId:t},body:{active:e}});if(r.status!=="success")throw Object.assign(new Error(r.error||`Failed to set chat processing for card: ${t}`),{statusCode:500})}let Q=a$1({append(t,e,r,n,o){return L(t).append(t,e,r,n,o)},readAll(t){return L(t).readAll(t)},readAfter(t,e){return L(t).readAfter(t,e)},clear(t){return L(t).clear(t)},setProcessing(t,e){return L(t).setProcessing(t,e)},isProcessing(t){return L(t).isProcessing(t)},getConfig(t){return L(t).getConfig(t)},setConfig(t,e){return L(t).setConfig(t,e)}},{emitNotification(t){if(t.kind==="notification-batch"){V(t.notifications);return}V([t]);}}),wt=p({boardContexts:p$1,cardOwnerIndex:f$1,cardContextForCard:t=>W(t),readStatusSnapshot:()=>Se(),readDataObjectsByToken:()=>Ae(),readCardRuntimeArtifacts:()=>Ce(),readCardFromStore:t=>Y(t),readCardDefinitions:()=>me(),processAccumulatedLaneInternal:t=>yt(t),reportSourceFetched:(t,e)=>kt(t,{ref:e}),reportSourceFetchFailure:(t,e)=>Pt(t,{reason:e}),uploadCardFile:(t,e,r,n,o)=>Ct(t,e,r,n,o),chatStorePublic:Q,serverUrl:E,apiBasePath:w}),ye=wt.mcpCardStoreFacade,st=wt.createMcpFacade,he=j({boardId:B,bootstrapBoard:()=>at(),sseHub:l$1,onChannelSubscribed:q,onChannelUnsubscribed:K,getMcpFacade:()=>st(),getMcpCardStoreFacade:()=>ye()});function we(t){return m$1(t)}function be(){return n(st())}function bt(){return o({boardId:B,uploadCardFile:Ct,getMcpFacade:()=>st(),controlplane:he})}let it=k({boardId:B,boardContexts:p$1,readChatRecords:(t,e)=>ve(t,e),getChatProcessing:t=>Re(t),chatBootstrapTailTurns:$}),Se=it.readStatusSnapshot,Ce=it.readCardRuntimeArtifacts,Ae=it.readDataObjectsByToken,dt=it.buildPublishedRuntimePayload;async function St(t,e,r){let n=r?.syncBoard!==false,o=r?.restartOnlyIfChanged===true,s=W(t);if(!s)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let i=await Y(t);if(!i)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let c=o?JSON.stringify(i):null,j=e(i)||i;if(o&&JSON.stringify(j)===c)return;let h=await s.cardStoreOps.set({body:j});if(h.status!=="success")throw Object.assign(new Error(h.error||`Failed to persist card: ${t}`),{statusCode:500});if(n){let M=await s.boardOps.upsertCard({params:{cardId:t,restart:true}});if(M.status!=="success")throw Object.assign(new Error(M.error||`Failed to upsert card: ${t}`),{statusCode:500})}}async function Be(t,e){await St(t,e,{syncBoard:true});}async function ke(t,e){await St(t,e,{syncBoard:false});}async function Pe(t){let e=W(t);if(!e)throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});if(!await Y(t))throw Object.assign(new Error(`Card not found: ${t}`),{statusCode:404});let n=await e.boardOps.upsertCard({params:{cardId:t,restart:true}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to retrigger card: ${t}`),{statusCode:500})}async function Oe(t){let e=await Q.clear({params:{cardId:t}});if(e.status!=="success")throw Object.assign(new Error(e.error||`Failed to clear chat records for card: ${t}`),{statusCode:500});try{await tt(t,!1);}catch{}}async function Fe(t,e,r,n,o=""){let s=typeof r=="string"?r.trim():"",i=await Q.append({params:{cardId:t},body:{role:e||"system",text:s,files:n,turn:o}});if(i.status!=="success")throw Object.assign(new Error(i.error||`Failed to append chat record for card: ${t}`),{statusCode:500});return String(i.data?.id||"")}async function ve(t,e){let r=Number.isInteger(e?.tailTurns)&&e?.tailTurns>0?e?.tailTurns:void 0,n=await Q.readAll({params:{cardId:t},...r===void 0?{}:{body:{tailTurns:r}}});if(n.status!=="success")throw Object.assign(new Error(n.error||`Failed to read chat records for card: ${t}`),{statusCode:500});return Array.isArray(n.data?.records)?n.data.records:[]}let Ct=l({safeCardId:t=>D(t),artifactsStores:t=>v(t),cardFileMetadataStore:()=>A(),readCardFromStore:t=>Y(t),updateCardLocalOnly:(t,e)=>ke(t,e),writeChatRecord:(t,e,r,n,o)=>Fe(t,e,r,n,o)}).uploadCardFile;async function At(t){let e=W(t);if(!e)return null;let r=await e.boardOps.getConfig({params:{key:"chat-handler-flow"}}),o=(r.status==="success"?r.data?.value:null)??e.chatHandlerFlow??null,s=e.chatHandlerRef;return o==null&&(!s||typeof s!="object")?null:{ctx:e,handlerFlow:o,handlerRef:s}}function xe(t){let e=typeof t=="string"?t.trim():"";if(e.length<ot.length*2||!e.startsWith(ot)||!e.endsWith(ot))return null;let r=e.slice(ot.length,e.length-ot.length).trim(),n=/^([A-Za-z0-9_-]+)__(.*)$/s.exec(r);return n?{assistant:n[1].trim().toLowerCase(),text:n[2].trim()}:{assistant:"echo",text:r}}async function Te(t,e,r=false,n="",o=""){try{let s=await At(t);if(!s){try{await tt(t,!1);}catch{}return}let{ctx:i,handlerFlow:c,handlerRef:j}=s;if(!r)try{await tt(t,!0);}catch{}let h={boardId:B,cardId:String(t),lastChatEntryId:e,...n?{turnId:n}:{},...typeof o=="string"&&o.trim()?{probe:o.trim()}:{},...T,...E?{serverUrl:E}:{}},M=c!=null?{meta:"chat-handler-flow",howToRun:"built-in",whatToRun:{kind:"built-in",value:de}}:j;a$4(i.boardAdapter)?await u(i,"chat-agent").enqueueRequest({boardId:B,ref:M,args:c!=null?{...h,__chatHandlerFlow:c}:h}):u(i,"chat-agent").enqueueRequest({boardId:B,ref:M,args:c!=null?{...h,__chatHandlerFlow:c}:h}),await Promise.resolve(i.boardAdapter.requestProcessAccumulated?.());}catch(s){try{await tt(t,!1);}catch{}N.warn(`[chat-handler] queue failed for card "${t}": ${s instanceof Error?s.message:String(s)}`);}}async function Ne(t,e,r){if(e.howToRun==="built-in"&&b$2(e)===de){let n=_,o=r.__chatHandlerFlow,s={...r};return delete s.__chatHandlerFlow,n?n.run(o,s,{boardId:B,cardId:String(s.cardId||""),label:t.label,logger:N,serverUrl:E,executionExtra:T}):{dispatched:false,error:"chat-handler-flow configured but no chatFlowRunner was provided"}}return x.invoke(e,r)}async function Ee(t,e=false){e||await G();let r=typeof t.args?.cardId=="string"?t.args.cardId:"",n=r?W(r):ht();if(!n)throw new Error(r?`Board context is unavailable for chat-agent request: ${r}`:"Board context is unavailable for chat-agent request");let o=await Ne(n,t.ref,t.args);if(!o.dispatched){if(r)try{await tt(r,!1);}catch{}throw new Error(o.error||`chat-agent dispatch failed for card "${r||"unknown"}"`)}}async function je(t,e,r){if(e==="chat-send"){let o=r&&typeof r["turn-id"]=="string"?r["turn-id"]:r&&typeof r.turnId=="string"?r.turnId:r&&typeof r.turn=="string"?r.turn:"";if(r&&"files"in r&&r.files!==void 0&&r.files!==null)throw Object.assign(new Error('chat-send does not accept a "files" parameter; upload attachments via manage.add-chat-attachment first'),{statusCode:400});let s=bt(),i=xe(r?.text),c=i?i.text:r?.text,j=await a$9("manage.add-chat-entry-and-any-attachments",{board_id:B,card_id:t,role:"user",text:c,turn_id:o,files:[]},s);if(j?.status!=="success")throw new Error(b$4(j,`chat-send append failed for card ${t}`));let h=j?.data?.id;if(typeof h!="string"||!h)throw new Error(`chat-send did not return an append id for card ${t}`);let M=await a$9("setstate.chat-processing-started",{board_id:B,card_id:t},s);if(M?.status!=="success")throw new Error(b$4(M,`chat-send processing update failed for card ${t}`));Te(t,h,true,o,i?.assistant||"");return}await Be(t,o=>{let s=new Date().toISOString(),i=o.card_data&&typeof o.card_data=="object"?o.card_data:{};if(o.card_data=i,e==="file-upload"){let c=A().normalizeIncoming(r?.files,s);return c.length>0&&A().merge(i,c),o}if(e==="action"){let c=r&&typeof r.buttonId=="string"?r.buttonId:"";if(!c)return o;i.lastAction={buttonId:c,at:s},i.lastActionText=`${c} @ ${s}`;}return o});}function et(t,e,r){let n=JSON.stringify(r),o=typeof Buffer<"u"?Buffer.byteLength(n):new TextEncoder().encode(n).length;t.writeHead(e,{...b$3,"Content-Type":"application/json; charset=utf-8","Content-Length":o}),t.end(n);}async function Bt(t,e,r){let n=await Y(t);if(!n)throw Object.assign(new Error("Card not found"),{statusCode:404});let o=A().resolve(n.card_data,e,r);if(!o.ok&&o.reason==="stale_reference")throw Object.assign(new Error("File reference is stale. Refresh and try again."),{statusCode:409});if(!o.ok)throw Object.assign(new Error("File not found"),{statusCode:404});let s=o.file,i=D(t),c=v(t),j=String(s.stored_name||""),h=`${i}/${j}`,M=c.files?await c.files.getBytes(h):null;if(!M)throw Object.assign(new Error("File not found"),{statusCode:404});return {fileRecord:s,bytes:M}}async function Me(t,e,r,n){let{fileRecord:o,bytes:s}=await Bt(e,r,n),i=String(o.name||o.stored_name||"download.bin"),c=String(o.mime_type||"application/octet-stream");t.writeHead(200,{"Content-Type":c,"Content-Disposition":`attachment; filename="${i}"`,"Content-Length":s.length}),t.end(s);}function _e(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 De(t,e,r){let n=t.split(/\r?\n/);return (e==="head"?n.slice(0,r):n.slice(-r)).join(`
2
+ `)}async function rt(t){let e=[];for await(let n of t)e.push(n);let r=typeof Buffer<"u"?Buffer.concat(e).toString("utf-8").trim():new TextDecoder().decode(d$2(e)).trim();return r?JSON.parse(r):{}}async function kt(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 n=p$1[0];return n?n.boardOps.sourceDataFetched({params:{token:t,ref:r}}):{status:"fail",error:"no board context"}}async function Pt(t,e){let r=typeof e.reason=="string"&&e.reason.trim()?e.reason:"unknown",n=p$1[0];return n?n.boardOps.sourceDataFetchFailure({params:{token:t,reason:r}}):{status:"fail",error:"no board context"}}let Ie=b({sseHub:l$1,queueSseHub:R,corsHeaders:b$3,json:et,buildPublishedRuntimePayload:()=>dt(),onSseClientConnected:S,onChannelSubscribed:q,onChannelUnsubscribed:K,apiBasePath:w,readJsonBody:t=>rt(t),initBoardAndSetup:()=>G(),bootstrapBoard:()=>at(),boardContexts:p$1,publishPersistedStateSnapshot:t=>ut(t),upsertCardsFromSource:(t,e)=>Rt(t,e)}).handleWatchersRoutes,qe=a$2({apiBasePath:w,json:et,readJsonBody:t=>rt(t),bootstrapBoard:()=>at(),createMcpFacade:()=>st(),createMcpToolRegistry:t=>we(t),resolveCardFileDownloadPayload:(t,e,r)=>Bt(t,e,r),isLikelyTextMimeType:t=>_e(t),sliceTextByLines:(t,e,r)=>De(t,e,r)}).handleAgentfaceApi,$e=a$3({apiBasePath:w,json:et,readJsonBody:t=>rt(t),initBoardAndSetup:()=>G(),createMcpWebhookToolRegistry:()=>be()}).handleWebhooksApi,He=ce({apiBasePath:w,json:et,readJsonBody:t=>rt(t),bootstrapBoard:()=>at(),createMcpControlplaneToolRegistry:()=>bt(),retriggerCard:t=>Pe(t),applyCardAction:(t,e,r)=>je(t,e,r),resolveChatHandlerTarget:t=>At(t),sendCardFileDownloadResponse:(t,e,r,n)=>Me(t,e,r,n)}).handleRuntimeApi,Le=ue({apiBasePath:w,emitNotifications:t=>V(t),readJsonBody:t=>rt(t),json:(t,e,r)=>et(t,e,r)}).handleNotifyRoute;async function Ue(t,e,r){return !!(await qe(t,e,r)||await $e(t,e,r)||await Ie(t,e,r)||await Le(t,e,r)||await He(t,e,r))}return {get apiBasePath(){return w},get corsHeaders(){return b$3},get queueLaneTuning(){return I},handleRuntimeApi:Ue,emitNotification(t){if(t.kind==="notification-batch"){V(t.notifications);return}V([t]);},buildPublishedRuntimePayload:dt,__drainProcessAccumulatedLane:yt,handleChatAgentRequest:Ee,clearChatRecords:Oe,reportSourceFetched(t,e){return kt(t,{ref:e})},reportSourceFetchFailure(t,e){return Pt(t,{reason:e})},get cardStore(){return p$1[0]?.publicCardStore??{get(){return Promise.resolve({status:"fail",error:"no board context"})},set(){return Promise.resolve({status:"fail",error:"no board context"})}}}}}function _r(g){let w=String(g.apiBasePath||"/api/boards").replace(/\/$/,""),b={...le,...g.corsHeaders||{}},I=g.serverMetaStore,B=g.boardRuntimeFactory,$=new Map,N="boards-config.json";function x(){let l=I.getText(N);if(!l)return {boards:[{id:"default",label:"Default Board"}]};try{return JSON.parse(l)}catch{return {boards:[{id:"default",label:"Default Board"}]}}}function _(l){I.putText(N,JSON.stringify(l,null,2));}function H(l){let R=String(l||"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/^_+|_+$/g,"");return R.length>0&&R.length<=64?R:null}function E(l){if($.has(l))return $.get(l);let F=x().boards.find(f=>f.id===l)||{},p=B(l,F);return $.set(l,p),p}function T(l,R,F){let p=JSON.stringify(F),f=typeof Buffer<"u"?Buffer.byteLength(p):new TextEncoder().encode(p).length;l.writeHead(R,{...b,"Content-Type":"application/json; charset=utf-8","Content-Length":f}),l.end(p);}async function S(l,R,F){let p=l.method||"GET",f=F.pathname;if(p==="GET"&&f===w)return T(R,200,{ok:true,boards:x().boards}),true;if(p==="POST"&&f===w){let y=[];for await(let O of l)y.push(O);let k=typeof Buffer<"u"?Buffer.concat(y).toString("utf-8").trim():new TextDecoder().decode(d$2(y)).trim(),u={};try{u=k?JSON.parse(k):{};}catch{u={};}let P=H(u.id);if(!P)return T(R,400,{error:"board id must be 1-64 alphanumeric/dash/underscore characters"}),true;let v=x();if(v.boards.some(O=>O.id===P))return T(R,409,{error:`Board "${P}" is already registered`}),true;let A=typeof u.label=="string"&&u.label.trim()?u.label.trim():P,D={id:P,label:A};for(let[O,U]of Object.entries(u))O==="id"||O==="label"||U!=null&&(D[O]=U);return v.boards.push(D),_(v),T(R,200,{ok:true,board:D}),true}return false}async function z(l,R,F){let f=F.pathname.match(new RegExp(`^${c$3(w)}/([^/]+)(/|$)`));if(!f)return false;let y=H(decodeURIComponent(f[1]));return y?x().boards.some(P=>P.id===y)?!!await E(y).handleRuntimeApi(l,R,F):(T(R,404,{error:`Board "${y}" not registered. POST ${w} with {id} to register it first.`}),true):(T(R,400,{error:"Invalid board id"}),true)}async function q(l,R,F){return !!(await S(l,R,F)||await z(l,R,F))}function K(l){if(!x().boards.some(F=>F.id===l))throw Object.assign(new Error(`Board "${l}" not registered`),{statusCode:404});return {service:E(l)}}return {get apiBasePath(){return w},get corsHeaders(){return b},handleApi:q,requireBoardService:K}}export{Mr as a,_r as b};//# sourceMappingURL=chunk-BA25VGJP.js.map
3
+ //# sourceMappingURL=chunk-BA25VGJP.js.map
@@ -0,0 +1,3 @@
1
+ import {a as a$1,p,q,t as t$1}from'./chunk-FULAMLUU.js';import {D,l,z,B,i,H,G,n,h,A,q as q$1,p as p$1,E,t,m as m$1,u,F,s,o,C}from'./chunk-MRESV3MD.js';import {a,b,c}from'./chunk-44L64VQ2.js';import {a as a$2}from'./chunk-YOY2JM5N.js';import {e,f}from'./chunk-UGB7PC4P.js';function Ct(o){return typeof o=="string"&&o.trim().length>0}function ht(o,r){if(!o||typeof o!="object")throw new Error(`${r}: adapter.selfRef is required`);if(!Ct(o.howToRun))throw new Error(`${r}: adapter.selfRef.howToRun is required`);if(!Ct(o.whatToRun))throw new Error(`${r}: adapter.selfRef.whatToRun is required`)}function St(o,r){if(!o||typeof o!="object")throw new Error(`${r}: adapter.callbackTransport is required`);if(typeof o.createCallback!="function")throw new Error(`${r}: adapter.callbackTransport.createCallback is required`)}function $t(o,r="callbackTransport"){return {createCallback(S){let _=o();return ht(_,r),{token:S,via:_}}}}function Ye(o){return $t(()=>o,"createStaticExecutionRefCallbackTransport")}function Yt(o){return Ye({meta:"board-live-cards",howToRun:"http:post",whatToRun:a({kind:"http-url",value:String(o||"").trim()})})}function Ut(o){return Ye({meta:"board-live-cards",howToRun:"in-process-loop",whatToRun:a({kind:"in-process-loop",value:String(o||"").trim()})})}function Xt(o){let r=typeof o=="string"?{notifyChannel:o}:o??{},S={};return r.notifyChannel&&(S.notifyChannel=r.notifyChannel),r.boardRuntimeStoreRef&&(S.boardRuntimeStoreRef=r.boardRuntimeStoreRef),r.queueStoreRef&&(S.queueStoreRef=r.queueStoreRef),Ye({meta:"board-live-cards",howToRun:"built-in",whatToRun:a({kind:"built-in",value:"board-live-cards"}),...Object.keys(S).length>0?{extra:S}:{}})}function m(o){return o!==void 0?{status:"success",data:o}:{status:"success"}}function d(o){return {status:"fail",error:o}}function g(o){return {status:"error",error:o instanceof Error?o.message:String(o)}}function Dt(o){let r=new TextEncoder().encode(o),S=Array.from(r,_=>String.fromCharCode(_)).join("");return btoa(S).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function vt(o){let r=o.replace(/-/g,"+").replace(/_/g,"/"),S=r+"=".repeat((4-r.length%4)%4),_=atob(S),E=Uint8Array.from(_,K=>K.charCodeAt(0));return new TextDecoder().decode(E)}function Pe(o){try{let r=JSON.parse(vt(o));return typeof r?.t=="string"?{taskName:r.t}:null}catch{return null}}function bt(o){return Dt(JSON.stringify(o))}function yt(o){try{let r=JSON.parse(vt(o));return typeof r?.cbk=="string"&&typeof r?.cid=="string"&&typeof r?.b=="string"&&typeof r?.d=="string"?r:null}catch{return null}}function N(){return new Date().toISOString()}function Vt(o){let r=new Map;return {appendEntries(S,_){if(!S||_.length===0)return;let E=r.get(S)??[];r.set(S,[...E,..._]);},dispatchEntriesForJournalId(S,_){if(!S)return;let E=r.get(S);if(!(!E||E.length===0)){for(let K of E)try{_(K);}catch(j){try{o(K,j instanceof Error?j.message:String(j));}catch{}}r.delete(S);}}}}function sr(o$1,r,S={}){St(r.callbackTransport,"createBoardLiveCardsPublic");let _=r.callbackTransport,E$1=r.onWarn??(()=>{}),K=a(o$1),j=S.boardRuntimeStoreRef,G$1=S.scratchStoreRef,ce=S.taskExecutorRef,ke=S.chatHandlerFlow,Ce=S.emitNotification??(t=>{if(!r.publishBoardChangeNotifications)return;let e=t.kind==="notification-batch"?t.notifications:[t];return r.publishBoardChangeNotifications(e)});function ne(){if(!j)throw new Error(`Board at ${o$1.value} has no board runtime store configured. Pass boardRuntimeStoreRef at construction or init.`);return j}function Ne(t){if(t.length!==0)try{let e$1=e(t),s=f({kind:"notification-batch",notifications:e$1}),i=Ce(s);i&&typeof i.catch=="function"&&i.catch(f=>E$1(`[board-live-cards-public] emitNotification failed: ${f instanceof Error?f.message:String(f)}`));}catch(e){E$1(`[board-live-cards-public] emitNotification failed: ${e instanceof Error?e.message:String(e)}`);}}function qe(){let t=q$2().readCardStoreRef();if(!t)throw new Error(`Board at ${o$1.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let e=r.kvStorageForRef(t);return {readIndex(){return e.read("_index")},writeIndex(s){e.write("_index",s);},readCard(s){return e.read(s)},writeCard(s,i){return e.write(s,i),r.hashFn(i)},removeCard(s){e.delete(s);},cardExists(s){return e.read(s)!==null},defaultCardKey(s){return s}}}let je={readValues(t){let e=r.kvStorageForRef(ne()),s=e.listKeys().sort();if(s.length===0)return {version:null,values:{}};let i={};for(let f of s)i[f]=e.read(f);return {version:r.hashFn(i),values:i}},writeValues(t,e,s){let i=r.kvStorageForRef(ne());for(let f of s)i.delete(f);for(let[f,v]of Object.entries(e))i.write(f,v);return r.hashFn(e)}},q$2=()=>t(r.kvStorageForRef(ne())),oe=()=>s(je),de=()=>o(r.journalAdapterForRef(ne())),l$1=()=>m$1(qe(),E$1),n$1=()=>{let t=q$2().readOutputsStoreRef();if(!t)throw new Error(`Board at ${o$1.value} has no outputs store configured. Run: init --outputs-store-ref <b64-ref>`);return u(r.kvStorageForRef(t))};function u$1(){return ce??q$2().readTaskExecutorRef()}function R(){return !!oe().readSnapshot(o$1.value).values[q$1]}function y(){let t=oe().readSnapshot(o$1.value);if(!t.values[q$1])throw new Error(`Board not initialized at ${o$1.value}`);return F(t.values)}function C$1(t,e){let s=oe().commitSnapshot(o$1.value,{schemaVersion:p$1,expectedVersion:e,commitId:r.genId(),committedAt:N(),deleteKeys:[],shallowMerge:E(t)});if(!s.ok)throw new Error(`Snapshot commit failed (version mismatch): expected=${e??"null"} current=${s.currentVersion??"null"}`)}function p$2(t){de().appendEvent(t);}async function A$1(){let e=Vt((a,c)=>{let h=a.payload,w=(h?.enrichedCard??{}).id??h?.cardId??"unknown";p$2({type:"task-failed",taskName:w,error:c,timestamp:N()});}),s=y(),i$1=q(s.graph),{events:f,newCursor:v}=de().readEntriesAfterCursor(s.lastDrainedJournalId),k=Y(),b=n(k,a=>r.resolveBlob(a)),x={...s.runtimeByCardId},P=new Map,Z={readRuntime(a){return P.get(a)??x[a]??{_sources:{}}},writeRuntime(a,c){P.set(a,c),x[a]=c;}},ee=[],V=new Map,ae={readSourceData(a,c){let h=`${a}/${c}`;return V.has(h)?V.get(h):b.readSourceData(a,c)},ingestSourceDataStaged(a,c,h,H){b.ingestSourceDataStaged(a,c,h,H);},commitSourceData(a,c,h){let H=`${a}/.staged/${h}/${c}`,w=k.read(H);if(w==null){let B=k.keyRef?.(H);B&&(w=r.resolveBlob(B));}if(w==null)return false;let M=`${a}/${c}`,Q=w.trim();try{V.set(M,JSON.parse(Q));}catch{V.set(M,Q);}return ee.push({cardId:a,outputFile:c,deliveryToken:h}),true},hasSource(a,c){let h=`${a}/${c}`;return V.has(h)?true:b.hasSource(a,c)},listSources(a){let c=b.listSources(a),h=new Set;for(let w of V.keys())w.startsWith(`${a}/`)&&h.add(w.slice(`${a}/`.length));let H=new Set([...c,...h]);return Array.from(H)}},pe=()=>i$1.config.tasks,te={cardStore:l$1(),cardRuntimeStore:Z,fetchedSourcesStore:ae,outputStore:n$1(),executionRequestStore:e,activeTaskConfigs:()=>pe()},ge=[],$e=[],De=[],Ve=new Map,We=new Set,Nt=(a,c)=>{ge.push({type:"task-completed",taskName:a,data:c,timestamp:N()});},Je=(a,c)=>{p$2({type:"task-failed",taskName:a,error:c,timestamp:N()});},Re=t$1(i$1,{handlers:{"card-handler":C(o$1,v,te,Nt,Je,(a,c)=>{$e.push({cardId:a,values:c});},a=>{De.push(a);})},onNodeRemoved:a=>{Ve.delete(a),P.delete(a),delete x[a],We.add(a);}});for(pe=()=>Re.getState().config.tasks,ge=f;ge.length>0;){let a=ge;ge=[];for(let c of a)if(c.type==="task-restart"){let h=te.cardStore.readCard(c.taskName);h&&Ve.set(c.taskName,h);}Re.pushAll(a),await Re.waitForHandlers();}let Ze=Re.getState();await Re.dispose({wait:true});let qt=oe().readSnapshot(o$1.value).version;C$1({lastDrainedJournalId:v,graph:p(Ze),runtimeByCardId:x},qt);for(let{cardId:a,values:c}of $e)te.outputStore.writeComputedValues(a,c);for(let a of De)te.outputStore.writeDataObjects(a);for(let{cardId:a,outputFile:c,deliveryToken:h}of ee)b.commitSourceData(a,c,h);let ve;try{ve=z(B(K,Ze)),te.outputStore.writeStatusSnapshot(ve);}catch(a){E$1(`[board-live-cards-public] status publish failed: ${a instanceof Error?a.message:String(a)}`);}let ie=[];for(let{cardId:a,values:c}of $e)ie.push({kind:"computed_values",cardId:a,values:c});for(let a of De)for(let[c,h]of Object.entries(a))c&&ie.push({kind:"data_object",key:c,payload:h});for(let[a,c]of Ve)a!==i&&ie.push({kind:"card_refreshed",cardId:a,card:c});for(let a of We)ie.push({kind:"card_removed",cardId:a});ve!==void 0&&ie.push({kind:"status",status:ve}),Ne(ie);let ue=u$1()??{howToRun:"built-in",whatToRun:a({kind:"built-in",value:"source-cli-task-executor"})},et=r.supportsDirectSourceOutput?.(ue)===true;e.dispatchEntriesForJournalId(v,a$1=>{if(a$1.taskKind!=="source-fetch"){E$1(`[process-accumulated-events] unknown taskKind "${a$1.taskKind}" \u2014 skipping`);return}let c=a$1.payload,h=c.enrichedCard?.id??"unknown",H=c.enrichedCard?.source_defs??[];if(ue.howToRun==="queue-storage"&&et){try{let w=r.queueStorageForRef(T(),"task-executor"),M=typeof ue.extra?.boardId=="string"?ue.extra.boardId:void 0,Q=[];for(let B of H){if(!B.outputFile){E$1(`[dispatch] source "${B.bindTo}" has no outputFile \u2014 skipping`);continue}let we=r.genId(),Te=`${h}/.staged/${we}/${B.outputFile}`,tt=k.keyRef?.(Te);if(!tt)continue;let rt={ref:a(tt),deliveryToken:we,outputFile:B.outputFile,cardId:h},jt=bt({cbk:c.callbackToken,rg:o$1.value,br:a(o$1),cid:h,b:B.bindTo,d:B.outputFile,cs:void 0,rqt:c.rqt,dt:rt.deliveryToken});Q.push({...M?{boardId:M}:{},ref:ue,args:{source_def:B,base_ref:a(o$1),callback:_.createCallback(jt),output:rt}});}Q.length>0&&w.enqueueMany(Q);}catch(w){Je(h,w instanceof Error?w.message:String(w));}return}for(let w of H){if(!w.outputFile){E$1(`[dispatch] source "${w.bindTo}" has no outputFile \u2014 skipping`);continue}let M;if(et){let B=r.genId(),we=`${h}/.staged/${B}/${w.outputFile}`,Te=k.keyRef?.(we);Te&&(M={ref:a(Te),deliveryToken:B,outputFile:w.outputFile,cardId:h});}let Q=bt({cbk:c.callbackToken,rg:o$1.value,br:a(o$1),cid:h,b:w.bindTo,d:w.outputFile,cs:void 0,rqt:c.rqt,...M?{dt:M.deliveryToken}:{}});r.dispatchExecution(ue,{source_def:w,base_ref:a(o$1),callback:_.createCallback(Q),...M?{output:M}:{}}).catch(B=>Je(h,B instanceof Error?B.message:String(B)));}});}function T(){let t=q$2().readQueueStoreRef();if(!t)throw new Error(`Board at ${o$1.value} has no queue store configured. Run: init --queue-store-ref <b64-ref>`);return t}function $(){r.queueStorageForRef(T(),"process-accumulated").enqueue({boardRef:a(o$1)}),r.requestProcessAccumulated?.();}function F$1(){let t=r.queueStorageForRef(T(),"process-accumulated");for(;;){let e=t.lease({max:64,visibilityMs:1e3});if(e.length<=0)return;for(let s of e)t.ack(s.id,s.leaseToken);if(e.length<64)return}}async function X(){try{let t=()=>{let s=y(),{events:i}=de().readEntriesAfterCursor(s.lastDrainedJournalId);i.length<=0||$();},e=await c(r.lock,A$1,t);return m({ran:e!==!1})}catch(t){return g(t)}}function J(){$();}function z$1(t){try{let e=t.params?.cardStoreRef;if(!e)return d("init requires params.cardStoreRef \u2014 create a card store with card-store-cli and pass its ref here");if(j=t.params?.boardRuntimeStoreRef,!j)return d("init requires params.boardRuntimeStoreRef \u2014 pass the board runtime store ref here");if(!R()){let P=a$1(D);C$1({lastDrainedJournalId:"",graph:p(P),runtimeByCardId:{}},null);}let s=t.params?.outputsStoreRef;if(!s)return d("init requires params.outputsStoreRef \u2014 pass the outputs store ref here");let i=t.params?.queueStoreRef;if(!i)return d("init requires params.queueStoreRef \u2014 pass the queue store ref here");let f=t.params?.fetchedSourcesStoreRef;if(!f)return d("init requires params.fetchedSourcesStoreRef \u2014 pass the fetched sources store ref here");G$1=t.params?.scratchStoreRef;let v=t.params?.chatStoreRef;if(!v)return d("init requires params.chatStoreRef \u2014 pass the chat store ref here");let k=t.params?.artifactsStoreRef;if(!k)return d("init requires params.artifactsStoreRef \u2014 pass the artifacts store ref here");let b=q$2();b.writeBoardRuntimeStoreRef(j),b.writeCardStoreRef(e),b.writeOutputsStoreRef(s),b.writeQueueStoreRef(i),b.writeFetchedSourcesStoreRef(f),b.writeChatStoreRef(v),b.writeArtifactsStoreRef(k),l$1().writeCard(l().id,l());let x=ye({params:{cardId:l().id,restart:!0}});if(x.status!=="success")return x;try{n$1().writeStatusSnapshot(z(B(K,q(y().graph))));}catch{}return m()}catch(e){return g(e)}}function he(t){try{let e=n$1().readStatusSnapshot();if(!e){e=z(B(K,q(y().graph)));try{n$1().writeStatusSnapshot(e);}catch{}}return m(e)}catch(e){return g(e)}}function le(t){try{let e=t.params?.id;if(!e)return d("removeCard requires params.id");try{r.kvStorage("card-upsert").delete(e);}catch{}return p$2({type:"task-removal",taskName:e,timestamp:N()}),e!==i&&p$2({type:"task-restart",taskName:i,timestamp:N()}),J(),m()}catch(e){return g(e)}}function fe(t){try{let e=t.params?.cardId;if(!e)return d("addCardFiles requires params.cardId");let s=H(l$1(),{emitNotification:Ce}).appendFiles({params:{id:e},body:t.body});return s.status!=="success"?s:m({cardId:e,files_added:s.data.files_added,notified:!0})}catch(e){return g(e)}}function Se(t){try{let e=t.params?.id;return e?(p$2({type:"task-restart",taskName:e,timestamp:N()}),J(),m()):d("retrigger requires params.id")}catch(e){return g(e)}}async function se(t){return F$1(),X()}function be(){let t=q$2().readFetchedSourcesStoreRef();if(!t)throw new Error(`Board at ${o$1.value} has no fetched sources store configured. Run: init --fetched-sources-store-ref <b64-ref>`);return t}function Y(){return r.blobStorageForRef(be())}function ye(t){try{let e=t.params?.cardId,s=t.params?.all,i$1=!!t.params?.restart;if(!e&&!s)return d("upsertCard requires --card-id <id> or --all");let f=s?l$1().readAllCards().map(k=>k.id):[e];for(let k of f)if(!l$1().readCard(k))return d(`Card "${k}" not found in board at ${o$1.value}`);let v=!1;for(let k of f){let b=l$1().readCard(k),x=G(b),P=r.hashFn(x),Z=r.kvStorage("card-upsert"),ee=Z.read(k),V=ee?.taskConfigHash!==P;if(!(!V&&!i$1)){if(V){let ae=ee?.blobRef??l$1().readCardKey(k)??k;p$2({type:"task-upsert",taskName:k,taskConfig:x,timestamp:N()}),Z.write(k,{blobRef:ae,taskConfigHash:P,updatedAt:N()}),v=v||k!==i;}i$1&&p$2({type:"task-restart",taskName:k,timestamp:N()});}}return v&&p$2({type:"task-restart",taskName:i,timestamp:N()}),J(),m()}catch(e){return g(e)}}function I(t){try{let e=t.params?.token;if(!e)return d("taskFailed requires params.token");let s=t.params?.error??"unknown error",i=Pe(e);return i?(p$2({type:"task-failed",taskName:i.taskName,error:s,timestamp:N()}),J(),m()):d("Invalid callback token")}catch(e){return g(e)}}function D$1(t){try{let e=t.params?.token;if(!e)return d("taskProgress requires params.token");let i=(t.body??{}).update??{},f=Pe(e);return f?(p$2({type:"task-progress",taskName:f.taskName,update:i,timestamp:N()}),J(),m()):d("Invalid callback token")}catch(e){return g(e)}}function L(t){try{let e=t.params?.token,s=t.params?.ref;if(!e)return d("sourceDataFetched requires params.token");if(!s)return d("sourceDataFetched requires params.ref");let i=yt(e);if(!i)return d("Invalid source token");let{cbk:f,cid:v,b:k,d:b$1,cs:x,rqt:P,dt:Z}=i,ee=n(Y(),te=>r.resolveBlob(te)),V=Z||r.genId();Z||ee.ingestSourceDataStaged(v,b$1,b(s),V);let ae=Pe(f);if(!ae)return d("Invalid callback token embedded in source token");let pe=N();return p$2({type:"task-progress",taskName:ae.taskName,update:{bindTo:k,outputFile:b$1,fetchedAt:pe,deliveryToken:V,sourceChecksum:x,rqt:P},timestamp:pe}),J(),m()}catch(e){return g(e)}}function W(t){try{let e=t.params?.token,s=t.params?.reason??"unknown";if(!e)return d("sourceDataFetchFailure requires params.token");let i=yt(e);if(!i)return d("Invalid source token");let{cbk:f,b:v,d:k,cs:b,rqt:x}=i,P=Pe(f);return P?(p$2({type:"task-progress",taskName:P.taskName,update:{bindTo:v,outputFile:k,failure:!0,reason:s,sourceChecksum:b,rqt:x},timestamp:N()}),J(),m()):d("Invalid callback token embedded in source token")}catch(e){return g(e)}}function me(t){try{let e=q$2().readCardStoreRef();return e?m({storeRef:e}):d(`Board at ${o$1.value} has no card store configured`)}catch(e){return g(e)}}function U(t){try{return m({storeRef:j??null})}catch(e){return g(e)}}function wt(t){try{let e=q$2().readOutputsStoreRef();return e?m({storeRef:e}):d(`Board at ${o$1.value} has no outputs store configured`)}catch(e){return g(e)}}function Tt(t){try{return m({storeRef:G$1??null})}catch(e){return g(e)}}function It(t){try{let e=q$2().readChatStoreRef();return m({storeRef:e})}catch(e){return g(e)}}function xt(t){try{let e=q$2().readArtifactsStoreRef();return m({storeRef:e})}catch(e){return g(e)}}function Et(t){try{let e=q$2().readFetchedSourcesStoreRef();return m({storeRef:e})}catch(e){return g(e)}}function At(t){try{let e=t.params?.key;if(!e)return d("getConfig requires params.key");let s=q$2(),i;switch(e){case "task-executor":i=ce??null;break;case "chat-handler-flow":i=ke??null;break;case "board-runtime-store-ref":i=s.readBoardRuntimeStoreRef();break;case "card-store-ref":i=s.readCardStoreRef();break;case "outputs-store-ref":i=s.readOutputsStoreRef();break;case "scratch-store-ref":i=G$1??null;break;case "chat-store-ref":i=s.readChatStoreRef();break;case "artifacts-store-ref":i=s.readArtifactsStoreRef();break;case "fetched-sources-store-ref":i=s.readFetchedSourcesStoreRef();break;default:return d(`getConfig: unknown key "${e}"`)}return m({value:i})}catch(e){return g(e)}}function Bt(t){try{let e=t.params?.key;if(!e)return d("getOutputsDataObject requires params.key");if(e===h)return m(null);let s=n$1().readDataObject(e);return m(s)}catch(e){return g(e)}}function Ue(t){try{return m(A(n$1().readAllDataObjects()))}catch(e){return g(e)}}function _t(t){try{let e=t.params?.key;if(!e)return d("getOutputsComputedValues requires params.key");let s=n$1().readComputedValues(e);return m(s)}catch(e){return g(e)}}function Xe(t){try{return m(n$1().readAllComputedValues())}catch(e){return g(e)}}function ze(){return n(Y(),t=>r.resolveBlob(t))}function Qe(t){let e=Y().keyRef?.(t);if(!e)throw new Error("configured fetched-sources store does not support keyRef");return a(e)}function Ft(t){try{let e=t.params?.key;if(!e)return d("getOutputsFetchedSources requires params.key");let s=ze().listSources(e),i={};for(let f of s)i[f]=Qe(`${e}/${f}`);return m(i)}catch(e){return g(e)}}function Ot(t){try{let e=ze(),s=new Set;for(let f of Y().listKeys()){let v=f.indexOf("/");v>0&&!f.includes("/.staged/")&&s.add(f.slice(0,v));}let i={};for(let f of s){let v=e.listSources(f);if(v.length>0){i[f]={};for(let k of v)i[f][k]=Qe(`${f}/${k}`);}}return m(i)}catch(e){return g(e)}}function Pt(t){try{let e=l$1().readAllCards().filter(b=>b.id!==i),s=he({});if(s.status!=="success")return s;let i$1=Ue({});if(i$1.status!=="success")return i$1;let f=Xe({});if(f.status!=="success")return f;let v=f.data,k={};for(let b of e){let x=typeof b?.id=="string"?b.id:null;if(!x)continue;let P=b.card_data&&typeof b.card_data=="object"&&!Array.isArray(b.card_data)?b.card_data:{};k[x]={schema_version:"v1",card_id:x,card_data:{...P},computed_values:v[x]&&typeof v[x]=="object"?v[x]:{}};}return m({cardDefinitions:e,statusSnapshot:s.data,dataObjectsByToken:i$1.data,cardRuntimeById:k})}catch(e){return g(e)}}return {init:z$1,status:he,getBoardRuntimeStoreRef:U,getCardStoreRef:me,getOutputsStoreRef:wt,getScratchStoreRef:Tt,getChatStoreRef:It,getArtifactsStoreRef:xt,getFetchedSourcesStoreRef:Et,getConfig:At,getOutputsDataObject:Bt,getAllOutputsDataObjects:Ue,getOutputsComputedValues:_t,getAllOutputsComputedValues:Xe,getOutputsFetchedSources:Ft,getAllOutputsFetchedSources:Ot,buildSseOneShotPayload:Pt,removeCard:le,addCardFiles:fe,retrigger:Se,processAccumulatedEvents:se,upsertCard:ye,taskFailed:I,taskProgress:D$1,sourceDataFetched:L,sourceDataFetchFailure:W}}function ar(o,r,S){let _=S?.taskExecutorRef,E=()=>{if(S){if(!S.boardRuntimeStoreRef)throw new Error(`Board at ${o.value} requires boardRuntimeStoreRef for non-core runtime operations.`);return t(r.kvStorageForRef(S.boardRuntimeStoreRef))}return t(r.kvStorage("config"))};function K(){let l=E().readCardStoreRef();if(!l)throw new Error(`Board at ${o.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let n=r.kvStorageForRef(l);return {readIndex(){return n.read("_index")},writeIndex(u){n.write("_index",u);},readCard(u){return n.read(u)},writeCard(u,R){return n.write(u,R),r.hashFn(R)},removeCard(u){n.delete(u);},cardExists(u){return n.read(u)!==null},defaultCardKey(u){return u}}}let j=()=>m$1(K(),r.onWarn??(()=>{}));function G(){return _??E().readTaskExecutorRef()}async function ce(l,n){let u=r.validateSchema(n),R=[],y=G();if(y&&Array.isArray(n.source_defs))for(let p of n.source_defs){let A=typeof p.bindTo=="string"?p.bindTo:"(unknown)";try{let T;try{T=await r.invokeExecutor(y,"validate-source-def",{timeout:r.executorTimeouts?.validationMs??1e4,input:JSON.stringify(p)});}catch(F){let X=F;if(T=typeof X?.stdout=="string"?X.stdout:"",!T.trim()){R.push(`source "${A}": executor validate-source-def failed \u2014 ${F instanceof Error?F.message:String(F)}`);continue}}let $=JSON.parse(T.trim());if(!$.ok&&Array.isArray($.errors))for(let F of $.errors)R.push(`source "${A}": ${F}`);}catch(T){R.push(`source "${A}": executor validate-source-def failed \u2014 ${T instanceof Error?T.message:String(T)}`);}}let C=[...u.errors,...R];return m({cardId:l,isValid:C.length===0,issues:C})}function ke(l,n){let u=l.params?.sourceIdx,R=l.params?.outRef;if(u===void 0)return d(`${n} requires params.sourceIdx`);if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d(`${n} requires card JSON object in body`);let y=l.body,C=y["card-content"]??y,p=y["mock-projections"]??{},A=C.source_defs??[];if(u<0||u>=A.length)return d(`sourceIdx ${u} out of range (card has ${A.length} source(s))`);let T=A[u],$=typeof T.bindTo=="string"?T.bindTo:"source";return {src:T,bindTo:$,outRef:R,mockProjections:p}}async function Ce(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d("validateCardPreflight requires card JSON object in body");let n=l.body,u=n["card-content"]??n,R=typeof u.id=="string"?u.id:"(unknown)";return await ce(R,u)}catch(n){return g(n)}}async function ne(l){try{let n=ke(l,"probeSourcePreflight");if("status"in n)return n;let u=G();if(!u)return d("No task-executor registered for this board");try{let R={...n.src,_projections:n.mockProjections},y=await r.invokeExecutor(u,"probe-source-preflight",{timeout:n.src.timeout??r.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(R)}),C=JSON.parse(y.trim());return C.ok?m({bindTo:n.bindTo,reachable:C.reachable,latencyMs:C.latencyMs,note:C.note}):d(C.error??"Preflight probe failed")}catch{return d("Executor does not support probe-source-preflight")}}catch(n){return g(n)}}async function Ne(l){try{let n=ke(l,"runSourcePreflight");if("status"in n)return n;let u=G();if(!u)return d("No task-executor registered for this board");try{let R={...n.src,_projections:n.mockProjections},y=await r.invokeExecutor(u,"run-source-preflight",{timeout:n.src.timeout??r.executorTimeouts?.probeMs??6e4,input:JSON.stringify(R)}),C=JSON.parse(y.trim());if(!C.ok)return m({bindTo:n.bindTo,ok:!1,result:null,issues:[C.error??"Preflight run failed"]});if(n.outRef){let p=b(n.outRef);r.absoluteBlob.write(p.value,JSON.stringify(C.resultValue,null,2));}return m({bindTo:typeof C.bindTo=="string"?C.bindTo:n.bindTo,ok:!0,result:C.resultValue??null,issues:[]})}catch(R){let y=R instanceof Error?R.message:String(R);return m({bindTo:n.bindTo,ok:!1,result:null,issues:[y]})}}catch(n){return g(n)}}async function qe(l){try{let n=G();if(!n)return d("No task-executor registered for this board");let u=await r.invokeExecutor(n,"describe-capabilities",{timeout:r.executorTimeouts?.describeMs??1e4});return m(JSON.parse(u.trim()))}catch(n){return g(n)}}function je(l){try{let n=l.body;if(!n||!Array.isArray(n.ops))return d("updatesInCardStore requires body.ops array");let u=n.ops,R=j();for(let y of u){let C=y.op,p=y.id;if(!p)return d('op is missing "id"');if(C==="update"){let A=y["card-content"];if(!A)return d(`update op for "${p}" is missing "card-content"`);R.writeCard(p,A);}else return d(`Unknown op type: "${C??"(none)"}"`)}return m()}catch(n){return g(n)}}function q(l){try{let n=l.body;if(!n||!Array.isArray(n.ids))return d("readFromCardStore requires body.ids array");let u=n.ids,R=j(),y=u.map(C=>({id:C,"card-content":R.readCard(C)}));return m({cards:y})}catch(n){return g(n)}}function oe(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d("evalCardCompute requires a JSON object in body");let n=l.body,u=n["card-content"]??n,R=typeof u.id=="string"?u.id:"(unknown)",y=n["mock-fetched-sources"]??{},C=n["mock-requires"]??{},p=u.compute;if(!p||!Array.isArray(p)||p.length===0)return m({cardId:R,ok:!0,computed_values:{},errors:[]});let A={id:R,card_data:u.card_data??{},requires:C,source_defs:u.source_defs,compute:p},T=a$2.runSync(A,{sourcesData:y}),$=T.node.computed_values??{},F=T.errors??[];return m({cardId:R,ok:F.length===0,computed_values:$,errors:F})}catch(n){return g(n)}}async function de(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d("simulateCardCycle requires a JSON object in body");let n=l.body,u=n["card-content"]??n,R=typeof u.id=="string"?u.id:"(unknown)",y=n["mock-fetched-sources"]??{},C=n["mock-requires"]??{},p=await ce(R,u),A=p.status==="success"?{isValid:p.data.isValid,issues:p.data.issues}:{isValid:!1,issues:[p.status==="fail"?p.error:"internal error"]},T=u.source_defs??[],$=u.card_data??{},F=[],X=[],J=[];if(T.length>0){F=a$2.enrichSourcesSync(T,{card_data:$,requires:C}),X=F.filter(I=>I._skip!==!0);for(let I of X){let D=I.projections,L=I._projections;if(D&&L){for(let W of Object.keys(D))if(L[W]===void 0){let me=typeof I.bindTo=="string"?I.bindTo:"(unknown)";J.push({bindTo:me,key:W,error:`Projection "${W}" resolved to undefined`});}}}}let z=[],he=new Set(X.map(I=>typeof I.bindTo=="string"?I.bindTo:"")),le=Object.fromEntries(Object.entries(y).filter(([I])=>he.has(I))),fe=n["task-executor-ref"],Se=(fe?.howToRun&&fe?.whatToRun?fe:void 0)??G();for(let I=0;I<F.length;I++){let D=F[I],L=typeof D.bindTo=="string"?D.bindTo:`source_${I}`;if(D._skip===!0){z.push({bindTo:L,skipped:!0});continue}if(!Se){z.push({bindTo:L,skipped:!0,error:"No task executor configured"});continue}try{let W={...D},me=await r.invokeExecutor(Se,"run-source-preflight",{timeout:D.timeout??r.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(W)}),U=JSON.parse(me.trim());U.ok&&!Object.prototype.hasOwnProperty.call(y,L)&&Object.prototype.hasOwnProperty.call(U,"resultValue")&&(le[L]=U.resultValue),z.push({bindTo:L,reachable:U.reachable,latencyMs:U.latencyMs,error:U.ok?void 0:U.error});}catch{z.push({bindTo:L,skipped:!0,error:"Executor does not support run-source-preflight"});}}let se=u.compute,be={},Y=[];if(se&&Array.isArray(se)&&se.length>0){let I={id:R,card_data:$,requires:C,source_defs:u.source_defs,compute:se},D=a$2.runSync(I,{sourcesData:le});be=D.node.computed_values??{},Y=D.errors??[];}let ye=A.isValid&&J.length===0&&Y.length===0&&z.every(I=>I.reachable!==!1);return m({cardId:R,ok:ye,validation:A,source_probes:z,projection_errors:J,fetched_sources:le,computed_values:be,compute_errors:Y})}catch(n){return g(n)}}return {validateCardPreflight:Ce,probeSourcePreflight:ne,runSourcePreflight:Ne,evalCardCompute:oe,simulateCardCycle:de,describeTaskExecutorCapabilities:qe,updatesInCardStore:je,readFromCardStore:q}}
2
+ export{St as a,Yt as b,Ut as c,Xt as d,sr as e,ar as f};//# sourceMappingURL=chunk-BRYV6CDD.js.map
3
+ //# sourceMappingURL=chunk-BRYV6CDD.js.map
@@ -0,0 +1,3 @@
1
+ 'use strict';var chunkAW3COGCI_cjs=require('./chunk-AW3COGCI.cjs'),chunkJOQWJ3VR_cjs=require('./chunk-JOQWJ3VR.cjs'),chunkVQCIOKJV_cjs=require('./chunk-VQCIOKJV.cjs'),chunkZV35WD6K_cjs=require('./chunk-ZV35WD6K.cjs'),chunk2RIHC5TZ_cjs=require('./chunk-2RIHC5TZ.cjs');function Ct(o){return typeof o=="string"&&o.trim().length>0}function ht(o,r){if(!o||typeof o!="object")throw new Error(`${r}: adapter.selfRef is required`);if(!Ct(o.howToRun))throw new Error(`${r}: adapter.selfRef.howToRun is required`);if(!Ct(o.whatToRun))throw new Error(`${r}: adapter.selfRef.whatToRun is required`)}function St(o,r){if(!o||typeof o!="object")throw new Error(`${r}: adapter.callbackTransport is required`);if(typeof o.createCallback!="function")throw new Error(`${r}: adapter.callbackTransport.createCallback is required`)}function $t(o,r="callbackTransport"){return {createCallback(S){let _=o();return ht(_,r),{token:S,via:_}}}}function Ye(o){return $t(()=>o,"createStaticExecutionRefCallbackTransport")}function Yt(o){return Ye({meta:"board-live-cards",howToRun:"http:post",whatToRun:chunkVQCIOKJV_cjs.a({kind:"http-url",value:String(o||"").trim()})})}function Ut(o){return Ye({meta:"board-live-cards",howToRun:"in-process-loop",whatToRun:chunkVQCIOKJV_cjs.a({kind:"in-process-loop",value:String(o||"").trim()})})}function Xt(o){let r=typeof o=="string"?{notifyChannel:o}:o??{},S={};return r.notifyChannel&&(S.notifyChannel=r.notifyChannel),r.boardRuntimeStoreRef&&(S.boardRuntimeStoreRef=r.boardRuntimeStoreRef),r.queueStoreRef&&(S.queueStoreRef=r.queueStoreRef),Ye({meta:"board-live-cards",howToRun:"built-in",whatToRun:chunkVQCIOKJV_cjs.a({kind:"built-in",value:"board-live-cards"}),...Object.keys(S).length>0?{extra:S}:{}})}function m(o){return o!==void 0?{status:"success",data:o}:{status:"success"}}function d(o){return {status:"fail",error:o}}function g(o){return {status:"error",error:o instanceof Error?o.message:String(o)}}function Dt(o){let r=new TextEncoder().encode(o),S=Array.from(r,_=>String.fromCharCode(_)).join("");return btoa(S).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function vt(o){let r=o.replace(/-/g,"+").replace(/_/g,"/"),S=r+"=".repeat((4-r.length%4)%4),_=atob(S),E=Uint8Array.from(_,K=>K.charCodeAt(0));return new TextDecoder().decode(E)}function Pe(o){try{let r=JSON.parse(vt(o));return typeof r?.t=="string"?{taskName:r.t}:null}catch{return null}}function bt(o){return Dt(JSON.stringify(o))}function yt(o){try{let r=JSON.parse(vt(o));return typeof r?.cbk=="string"&&typeof r?.cid=="string"&&typeof r?.b=="string"&&typeof r?.d=="string"?r:null}catch{return null}}function N(){return new Date().toISOString()}function Vt(o){let r=new Map;return {appendEntries(S,_){if(!S||_.length===0)return;let E=r.get(S)??[];r.set(S,[...E,..._]);},dispatchEntriesForJournalId(S,_){if(!S)return;let E=r.get(S);if(!(!E||E.length===0)){for(let K of E)try{_(K);}catch(j){try{o(K,j instanceof Error?j.message:String(j));}catch{}}r.delete(S);}}}}function sr(o,r,S={}){St(r.callbackTransport,"createBoardLiveCardsPublic");let _=r.callbackTransport,E=r.onWarn??(()=>{}),K=chunkVQCIOKJV_cjs.a(o),j=S.boardRuntimeStoreRef,G=S.scratchStoreRef,ce=S.taskExecutorRef,ke=S.chatHandlerFlow,Ce=S.emitNotification??(t=>{if(!r.publishBoardChangeNotifications)return;let e=t.kind==="notification-batch"?t.notifications:[t];return r.publishBoardChangeNotifications(e)});function ne(){if(!j)throw new Error(`Board at ${o.value} has no board runtime store configured. Pass boardRuntimeStoreRef at construction or init.`);return j}function Ne(t){if(t.length!==0)try{let e=chunk2RIHC5TZ_cjs.e(t),s=chunk2RIHC5TZ_cjs.f({kind:"notification-batch",notifications:e}),i=Ce(s);i&&typeof i.catch=="function"&&i.catch(f=>E(`[board-live-cards-public] emitNotification failed: ${f instanceof Error?f.message:String(f)}`));}catch(e){E(`[board-live-cards-public] emitNotification failed: ${e instanceof Error?e.message:String(e)}`);}}function qe(){let t=q().readCardStoreRef();if(!t)throw new Error(`Board at ${o.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let e=r.kvStorageForRef(t);return {readIndex(){return e.read("_index")},writeIndex(s){e.write("_index",s);},readCard(s){return e.read(s)},writeCard(s,i){return e.write(s,i),r.hashFn(i)},removeCard(s){e.delete(s);},cardExists(s){return e.read(s)!==null},defaultCardKey(s){return s}}}let je={readValues(t){let e=r.kvStorageForRef(ne()),s=e.listKeys().sort();if(s.length===0)return {version:null,values:{}};let i={};for(let f of s)i[f]=e.read(f);return {version:r.hashFn(i),values:i}},writeValues(t,e,s){let i=r.kvStorageForRef(ne());for(let f of s)i.delete(f);for(let[f,v]of Object.entries(e))i.write(f,v);return r.hashFn(e)}},q=()=>chunkJOQWJ3VR_cjs.t(r.kvStorageForRef(ne())),oe=()=>chunkJOQWJ3VR_cjs.s(je),de=()=>chunkJOQWJ3VR_cjs.o(r.journalAdapterForRef(ne())),l=()=>chunkJOQWJ3VR_cjs.m(qe(),E),n=()=>{let t=q().readOutputsStoreRef();if(!t)throw new Error(`Board at ${o.value} has no outputs store configured. Run: init --outputs-store-ref <b64-ref>`);return chunkJOQWJ3VR_cjs.u(r.kvStorageForRef(t))};function u(){return ce??q().readTaskExecutorRef()}function R(){return !!oe().readSnapshot(o.value).values[chunkJOQWJ3VR_cjs.q]}function y(){let t=oe().readSnapshot(o.value);if(!t.values[chunkJOQWJ3VR_cjs.q])throw new Error(`Board not initialized at ${o.value}`);return chunkJOQWJ3VR_cjs.F(t.values)}function C(t,e){let s=oe().commitSnapshot(o.value,{schemaVersion:chunkJOQWJ3VR_cjs.p,expectedVersion:e,commitId:r.genId(),committedAt:N(),deleteKeys:[],shallowMerge:chunkJOQWJ3VR_cjs.E(t)});if(!s.ok)throw new Error(`Snapshot commit failed (version mismatch): expected=${e??"null"} current=${s.currentVersion??"null"}`)}function p(t){de().appendEvent(t);}async function A(){let e=Vt((a,c)=>{let h=a.payload,w=(h?.enrichedCard??{}).id??h?.cardId??"unknown";p({type:"task-failed",taskName:w,error:c,timestamp:N()});}),s=y(),i=chunkAW3COGCI_cjs.q(s.graph),{events:f,newCursor:v}=de().readEntriesAfterCursor(s.lastDrainedJournalId),k=Y(),b=chunkJOQWJ3VR_cjs.n(k,a=>r.resolveBlob(a)),x={...s.runtimeByCardId},P=new Map,Z={readRuntime(a){return P.get(a)??x[a]??{_sources:{}}},writeRuntime(a,c){P.set(a,c),x[a]=c;}},ee=[],V=new Map,ae={readSourceData(a,c){let h=`${a}/${c}`;return V.has(h)?V.get(h):b.readSourceData(a,c)},ingestSourceDataStaged(a,c,h,H){b.ingestSourceDataStaged(a,c,h,H);},commitSourceData(a,c,h){let H=`${a}/.staged/${h}/${c}`,w=k.read(H);if(w==null){let B=k.keyRef?.(H);B&&(w=r.resolveBlob(B));}if(w==null)return false;let M=`${a}/${c}`,Q=w.trim();try{V.set(M,JSON.parse(Q));}catch{V.set(M,Q);}return ee.push({cardId:a,outputFile:c,deliveryToken:h}),true},hasSource(a,c){let h=`${a}/${c}`;return V.has(h)?true:b.hasSource(a,c)},listSources(a){let c=b.listSources(a),h=new Set;for(let w of V.keys())w.startsWith(`${a}/`)&&h.add(w.slice(`${a}/`.length));let H=new Set([...c,...h]);return Array.from(H)}},pe=()=>i.config.tasks,te={cardStore:l(),cardRuntimeStore:Z,fetchedSourcesStore:ae,outputStore:n(),executionRequestStore:e,activeTaskConfigs:()=>pe()},ge=[],$e=[],De=[],Ve=new Map,We=new Set,Nt=(a,c)=>{ge.push({type:"task-completed",taskName:a,data:c,timestamp:N()});},Je=(a,c)=>{p({type:"task-failed",taskName:a,error:c,timestamp:N()});},Re=chunkAW3COGCI_cjs.t(i,{handlers:{"card-handler":chunkJOQWJ3VR_cjs.C(o,v,te,Nt,Je,(a,c)=>{$e.push({cardId:a,values:c});},a=>{De.push(a);})},onNodeRemoved:a=>{Ve.delete(a),P.delete(a),delete x[a],We.add(a);}});for(pe=()=>Re.getState().config.tasks,ge=f;ge.length>0;){let a=ge;ge=[];for(let c of a)if(c.type==="task-restart"){let h=te.cardStore.readCard(c.taskName);h&&Ve.set(c.taskName,h);}Re.pushAll(a),await Re.waitForHandlers();}let Ze=Re.getState();await Re.dispose({wait:true});let qt=oe().readSnapshot(o.value).version;C({lastDrainedJournalId:v,graph:chunkAW3COGCI_cjs.p(Ze),runtimeByCardId:x},qt);for(let{cardId:a,values:c}of $e)te.outputStore.writeComputedValues(a,c);for(let a of De)te.outputStore.writeDataObjects(a);for(let{cardId:a,outputFile:c,deliveryToken:h}of ee)b.commitSourceData(a,c,h);let ve;try{ve=chunkJOQWJ3VR_cjs.z(chunkJOQWJ3VR_cjs.B(K,Ze)),te.outputStore.writeStatusSnapshot(ve);}catch(a){E(`[board-live-cards-public] status publish failed: ${a instanceof Error?a.message:String(a)}`);}let ie=[];for(let{cardId:a,values:c}of $e)ie.push({kind:"computed_values",cardId:a,values:c});for(let a of De)for(let[c,h]of Object.entries(a))c&&ie.push({kind:"data_object",key:c,payload:h});for(let[a,c]of Ve)a!==chunkJOQWJ3VR_cjs.i&&ie.push({kind:"card_refreshed",cardId:a,card:c});for(let a of We)ie.push({kind:"card_removed",cardId:a});ve!==void 0&&ie.push({kind:"status",status:ve}),Ne(ie);let ue=u()??{howToRun:"built-in",whatToRun:chunkVQCIOKJV_cjs.a({kind:"built-in",value:"source-cli-task-executor"})},et=r.supportsDirectSourceOutput?.(ue)===true;e.dispatchEntriesForJournalId(v,a=>{if(a.taskKind!=="source-fetch"){E(`[process-accumulated-events] unknown taskKind "${a.taskKind}" \u2014 skipping`);return}let c=a.payload,h=c.enrichedCard?.id??"unknown",H=c.enrichedCard?.source_defs??[];if(ue.howToRun==="queue-storage"&&et){try{let w=r.queueStorageForRef(T(),"task-executor"),M=typeof ue.extra?.boardId=="string"?ue.extra.boardId:void 0,Q=[];for(let B of H){if(!B.outputFile){E(`[dispatch] source "${B.bindTo}" has no outputFile \u2014 skipping`);continue}let we=r.genId(),Te=`${h}/.staged/${we}/${B.outputFile}`,tt=k.keyRef?.(Te);if(!tt)continue;let rt={ref:chunkVQCIOKJV_cjs.a(tt),deliveryToken:we,outputFile:B.outputFile,cardId:h},jt=bt({cbk:c.callbackToken,rg:o.value,br:chunkVQCIOKJV_cjs.a(o),cid:h,b:B.bindTo,d:B.outputFile,cs:void 0,rqt:c.rqt,dt:rt.deliveryToken});Q.push({...M?{boardId:M}:{},ref:ue,args:{source_def:B,base_ref:chunkVQCIOKJV_cjs.a(o),callback:_.createCallback(jt),output:rt}});}Q.length>0&&w.enqueueMany(Q);}catch(w){Je(h,w instanceof Error?w.message:String(w));}return}for(let w of H){if(!w.outputFile){E(`[dispatch] source "${w.bindTo}" has no outputFile \u2014 skipping`);continue}let M;if(et){let B=r.genId(),we=`${h}/.staged/${B}/${w.outputFile}`,Te=k.keyRef?.(we);Te&&(M={ref:chunkVQCIOKJV_cjs.a(Te),deliveryToken:B,outputFile:w.outputFile,cardId:h});}let Q=bt({cbk:c.callbackToken,rg:o.value,br:chunkVQCIOKJV_cjs.a(o),cid:h,b:w.bindTo,d:w.outputFile,cs:void 0,rqt:c.rqt,...M?{dt:M.deliveryToken}:{}});r.dispatchExecution(ue,{source_def:w,base_ref:chunkVQCIOKJV_cjs.a(o),callback:_.createCallback(Q),...M?{output:M}:{}}).catch(B=>Je(h,B instanceof Error?B.message:String(B)));}});}function T(){let t=q().readQueueStoreRef();if(!t)throw new Error(`Board at ${o.value} has no queue store configured. Run: init --queue-store-ref <b64-ref>`);return t}function $(){r.queueStorageForRef(T(),"process-accumulated").enqueue({boardRef:chunkVQCIOKJV_cjs.a(o)}),r.requestProcessAccumulated?.();}function F(){let t=r.queueStorageForRef(T(),"process-accumulated");for(;;){let e=t.lease({max:64,visibilityMs:1e3});if(e.length<=0)return;for(let s of e)t.ack(s.id,s.leaseToken);if(e.length<64)return}}async function X(){try{let t=()=>{let s=y(),{events:i}=de().readEntriesAfterCursor(s.lastDrainedJournalId);i.length<=0||$();},e=await chunkVQCIOKJV_cjs.c(r.lock,A,t);return m({ran:e!==!1})}catch(t){return g(t)}}function J(){$();}function z(t){try{let e=t.params?.cardStoreRef;if(!e)return d("init requires params.cardStoreRef \u2014 create a card store with card-store-cli and pass its ref here");if(j=t.params?.boardRuntimeStoreRef,!j)return d("init requires params.boardRuntimeStoreRef \u2014 pass the board runtime store ref here");if(!R()){let P=chunkAW3COGCI_cjs.a(chunkJOQWJ3VR_cjs.D);C({lastDrainedJournalId:"",graph:chunkAW3COGCI_cjs.p(P),runtimeByCardId:{}},null);}let s=t.params?.outputsStoreRef;if(!s)return d("init requires params.outputsStoreRef \u2014 pass the outputs store ref here");let i=t.params?.queueStoreRef;if(!i)return d("init requires params.queueStoreRef \u2014 pass the queue store ref here");let f=t.params?.fetchedSourcesStoreRef;if(!f)return d("init requires params.fetchedSourcesStoreRef \u2014 pass the fetched sources store ref here");G=t.params?.scratchStoreRef;let v=t.params?.chatStoreRef;if(!v)return d("init requires params.chatStoreRef \u2014 pass the chat store ref here");let k=t.params?.artifactsStoreRef;if(!k)return d("init requires params.artifactsStoreRef \u2014 pass the artifacts store ref here");let b=q();b.writeBoardRuntimeStoreRef(j),b.writeCardStoreRef(e),b.writeOutputsStoreRef(s),b.writeQueueStoreRef(i),b.writeFetchedSourcesStoreRef(f),b.writeChatStoreRef(v),b.writeArtifactsStoreRef(k),l().writeCard(chunkJOQWJ3VR_cjs.l().id,chunkJOQWJ3VR_cjs.l());let x=ye({params:{cardId:chunkJOQWJ3VR_cjs.l().id,restart:!0}});if(x.status!=="success")return x;try{n().writeStatusSnapshot(chunkJOQWJ3VR_cjs.z(chunkJOQWJ3VR_cjs.B(K,chunkAW3COGCI_cjs.q(y().graph))));}catch{}return m()}catch(e){return g(e)}}function he(t){try{let e=n().readStatusSnapshot();if(!e){e=chunkJOQWJ3VR_cjs.z(chunkJOQWJ3VR_cjs.B(K,chunkAW3COGCI_cjs.q(y().graph)));try{n().writeStatusSnapshot(e);}catch{}}return m(e)}catch(e){return g(e)}}function le(t){try{let e=t.params?.id;if(!e)return d("removeCard requires params.id");try{r.kvStorage("card-upsert").delete(e);}catch{}return p({type:"task-removal",taskName:e,timestamp:N()}),e!==chunkJOQWJ3VR_cjs.i&&p({type:"task-restart",taskName:chunkJOQWJ3VR_cjs.i,timestamp:N()}),J(),m()}catch(e){return g(e)}}function fe(t){try{let e=t.params?.cardId;if(!e)return d("addCardFiles requires params.cardId");let s=chunkJOQWJ3VR_cjs.H(l(),{emitNotification:Ce}).appendFiles({params:{id:e},body:t.body});return s.status!=="success"?s:m({cardId:e,files_added:s.data.files_added,notified:!0})}catch(e){return g(e)}}function Se(t){try{let e=t.params?.id;return e?(p({type:"task-restart",taskName:e,timestamp:N()}),J(),m()):d("retrigger requires params.id")}catch(e){return g(e)}}async function se(t){return F(),X()}function be(){let t=q().readFetchedSourcesStoreRef();if(!t)throw new Error(`Board at ${o.value} has no fetched sources store configured. Run: init --fetched-sources-store-ref <b64-ref>`);return t}function Y(){return r.blobStorageForRef(be())}function ye(t){try{let e=t.params?.cardId,s=t.params?.all,i=!!t.params?.restart;if(!e&&!s)return d("upsertCard requires --card-id <id> or --all");let f=s?l().readAllCards().map(k=>k.id):[e];for(let k of f)if(!l().readCard(k))return d(`Card "${k}" not found in board at ${o.value}`);let v=!1;for(let k of f){let b=l().readCard(k),x=chunkJOQWJ3VR_cjs.G(b),P=r.hashFn(x),Z=r.kvStorage("card-upsert"),ee=Z.read(k),V=ee?.taskConfigHash!==P;if(!(!V&&!i)){if(V){let ae=ee?.blobRef??l().readCardKey(k)??k;p({type:"task-upsert",taskName:k,taskConfig:x,timestamp:N()}),Z.write(k,{blobRef:ae,taskConfigHash:P,updatedAt:N()}),v=v||k!==chunkJOQWJ3VR_cjs.i;}i&&p({type:"task-restart",taskName:k,timestamp:N()});}}return v&&p({type:"task-restart",taskName:chunkJOQWJ3VR_cjs.i,timestamp:N()}),J(),m()}catch(e){return g(e)}}function I(t){try{let e=t.params?.token;if(!e)return d("taskFailed requires params.token");let s=t.params?.error??"unknown error",i=Pe(e);return i?(p({type:"task-failed",taskName:i.taskName,error:s,timestamp:N()}),J(),m()):d("Invalid callback token")}catch(e){return g(e)}}function D(t){try{let e=t.params?.token;if(!e)return d("taskProgress requires params.token");let i=(t.body??{}).update??{},f=Pe(e);return f?(p({type:"task-progress",taskName:f.taskName,update:i,timestamp:N()}),J(),m()):d("Invalid callback token")}catch(e){return g(e)}}function L(t){try{let e=t.params?.token,s=t.params?.ref;if(!e)return d("sourceDataFetched requires params.token");if(!s)return d("sourceDataFetched requires params.ref");let i=yt(e);if(!i)return d("Invalid source token");let{cbk:f,cid:v,b:k,d:b,cs:x,rqt:P,dt:Z}=i,ee=chunkJOQWJ3VR_cjs.n(Y(),te=>r.resolveBlob(te)),V=Z||r.genId();Z||ee.ingestSourceDataStaged(v,b,chunkVQCIOKJV_cjs.b(s),V);let ae=Pe(f);if(!ae)return d("Invalid callback token embedded in source token");let pe=N();return p({type:"task-progress",taskName:ae.taskName,update:{bindTo:k,outputFile:b,fetchedAt:pe,deliveryToken:V,sourceChecksum:x,rqt:P},timestamp:pe}),J(),m()}catch(e){return g(e)}}function W(t){try{let e=t.params?.token,s=t.params?.reason??"unknown";if(!e)return d("sourceDataFetchFailure requires params.token");let i=yt(e);if(!i)return d("Invalid source token");let{cbk:f,b:v,d:k,cs:b,rqt:x}=i,P=Pe(f);return P?(p({type:"task-progress",taskName:P.taskName,update:{bindTo:v,outputFile:k,failure:!0,reason:s,sourceChecksum:b,rqt:x},timestamp:N()}),J(),m()):d("Invalid callback token embedded in source token")}catch(e){return g(e)}}function me(t){try{let e=q().readCardStoreRef();return e?m({storeRef:e}):d(`Board at ${o.value} has no card store configured`)}catch(e){return g(e)}}function U(t){try{return m({storeRef:j??null})}catch(e){return g(e)}}function wt(t){try{let e=q().readOutputsStoreRef();return e?m({storeRef:e}):d(`Board at ${o.value} has no outputs store configured`)}catch(e){return g(e)}}function Tt(t){try{return m({storeRef:G??null})}catch(e){return g(e)}}function It(t){try{let e=q().readChatStoreRef();return m({storeRef:e})}catch(e){return g(e)}}function xt(t){try{let e=q().readArtifactsStoreRef();return m({storeRef:e})}catch(e){return g(e)}}function Et(t){try{let e=q().readFetchedSourcesStoreRef();return m({storeRef:e})}catch(e){return g(e)}}function At(t){try{let e=t.params?.key;if(!e)return d("getConfig requires params.key");let s=q(),i;switch(e){case "task-executor":i=ce??null;break;case "chat-handler-flow":i=ke??null;break;case "board-runtime-store-ref":i=s.readBoardRuntimeStoreRef();break;case "card-store-ref":i=s.readCardStoreRef();break;case "outputs-store-ref":i=s.readOutputsStoreRef();break;case "scratch-store-ref":i=G??null;break;case "chat-store-ref":i=s.readChatStoreRef();break;case "artifacts-store-ref":i=s.readArtifactsStoreRef();break;case "fetched-sources-store-ref":i=s.readFetchedSourcesStoreRef();break;default:return d(`getConfig: unknown key "${e}"`)}return m({value:i})}catch(e){return g(e)}}function Bt(t){try{let e=t.params?.key;if(!e)return d("getOutputsDataObject requires params.key");if(e===chunkJOQWJ3VR_cjs.h)return m(null);let s=n().readDataObject(e);return m(s)}catch(e){return g(e)}}function Ue(t){try{return m(chunkJOQWJ3VR_cjs.A(n().readAllDataObjects()))}catch(e){return g(e)}}function _t(t){try{let e=t.params?.key;if(!e)return d("getOutputsComputedValues requires params.key");let s=n().readComputedValues(e);return m(s)}catch(e){return g(e)}}function Xe(t){try{return m(n().readAllComputedValues())}catch(e){return g(e)}}function ze(){return chunkJOQWJ3VR_cjs.n(Y(),t=>r.resolveBlob(t))}function Qe(t){let e=Y().keyRef?.(t);if(!e)throw new Error("configured fetched-sources store does not support keyRef");return chunkVQCIOKJV_cjs.a(e)}function Ft(t){try{let e=t.params?.key;if(!e)return d("getOutputsFetchedSources requires params.key");let s=ze().listSources(e),i={};for(let f of s)i[f]=Qe(`${e}/${f}`);return m(i)}catch(e){return g(e)}}function Ot(t){try{let e=ze(),s=new Set;for(let f of Y().listKeys()){let v=f.indexOf("/");v>0&&!f.includes("/.staged/")&&s.add(f.slice(0,v));}let i={};for(let f of s){let v=e.listSources(f);if(v.length>0){i[f]={};for(let k of v)i[f][k]=Qe(`${f}/${k}`);}}return m(i)}catch(e){return g(e)}}function Pt(t){try{let e=l().readAllCards().filter(b=>b.id!==chunkJOQWJ3VR_cjs.i),s=he({});if(s.status!=="success")return s;let i=Ue({});if(i.status!=="success")return i;let f=Xe({});if(f.status!=="success")return f;let v=f.data,k={};for(let b of e){let x=typeof b?.id=="string"?b.id:null;if(!x)continue;let P=b.card_data&&typeof b.card_data=="object"&&!Array.isArray(b.card_data)?b.card_data:{};k[x]={schema_version:"v1",card_id:x,card_data:{...P},computed_values:v[x]&&typeof v[x]=="object"?v[x]:{}};}return m({cardDefinitions:e,statusSnapshot:s.data,dataObjectsByToken:i.data,cardRuntimeById:k})}catch(e){return g(e)}}return {init:z,status:he,getBoardRuntimeStoreRef:U,getCardStoreRef:me,getOutputsStoreRef:wt,getScratchStoreRef:Tt,getChatStoreRef:It,getArtifactsStoreRef:xt,getFetchedSourcesStoreRef:Et,getConfig:At,getOutputsDataObject:Bt,getAllOutputsDataObjects:Ue,getOutputsComputedValues:_t,getAllOutputsComputedValues:Xe,getOutputsFetchedSources:Ft,getAllOutputsFetchedSources:Ot,buildSseOneShotPayload:Pt,removeCard:le,addCardFiles:fe,retrigger:Se,processAccumulatedEvents:se,upsertCard:ye,taskFailed:I,taskProgress:D,sourceDataFetched:L,sourceDataFetchFailure:W}}function ar(o,r,S){let _=S?.taskExecutorRef,E=()=>{if(S){if(!S.boardRuntimeStoreRef)throw new Error(`Board at ${o.value} requires boardRuntimeStoreRef for non-core runtime operations.`);return chunkJOQWJ3VR_cjs.t(r.kvStorageForRef(S.boardRuntimeStoreRef))}return chunkJOQWJ3VR_cjs.t(r.kvStorage("config"))};function K(){let l=E().readCardStoreRef();if(!l)throw new Error(`Board at ${o.value} has no card store configured. Run: init --base-ref <ref> --store-ref <b64-ref>`);let n=r.kvStorageForRef(l);return {readIndex(){return n.read("_index")},writeIndex(u){n.write("_index",u);},readCard(u){return n.read(u)},writeCard(u,R){return n.write(u,R),r.hashFn(R)},removeCard(u){n.delete(u);},cardExists(u){return n.read(u)!==null},defaultCardKey(u){return u}}}let j=()=>chunkJOQWJ3VR_cjs.m(K(),r.onWarn??(()=>{}));function G(){return _??E().readTaskExecutorRef()}async function ce(l,n){let u=r.validateSchema(n),R=[],y=G();if(y&&Array.isArray(n.source_defs))for(let p of n.source_defs){let A=typeof p.bindTo=="string"?p.bindTo:"(unknown)";try{let T;try{T=await r.invokeExecutor(y,"validate-source-def",{timeout:r.executorTimeouts?.validationMs??1e4,input:JSON.stringify(p)});}catch(F){let X=F;if(T=typeof X?.stdout=="string"?X.stdout:"",!T.trim()){R.push(`source "${A}": executor validate-source-def failed \u2014 ${F instanceof Error?F.message:String(F)}`);continue}}let $=JSON.parse(T.trim());if(!$.ok&&Array.isArray($.errors))for(let F of $.errors)R.push(`source "${A}": ${F}`);}catch(T){R.push(`source "${A}": executor validate-source-def failed \u2014 ${T instanceof Error?T.message:String(T)}`);}}let C=[...u.errors,...R];return m({cardId:l,isValid:C.length===0,issues:C})}function ke(l,n){let u=l.params?.sourceIdx,R=l.params?.outRef;if(u===void 0)return d(`${n} requires params.sourceIdx`);if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d(`${n} requires card JSON object in body`);let y=l.body,C=y["card-content"]??y,p=y["mock-projections"]??{},A=C.source_defs??[];if(u<0||u>=A.length)return d(`sourceIdx ${u} out of range (card has ${A.length} source(s))`);let T=A[u],$=typeof T.bindTo=="string"?T.bindTo:"source";return {src:T,bindTo:$,outRef:R,mockProjections:p}}async function Ce(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d("validateCardPreflight requires card JSON object in body");let n=l.body,u=n["card-content"]??n,R=typeof u.id=="string"?u.id:"(unknown)";return await ce(R,u)}catch(n){return g(n)}}async function ne(l){try{let n=ke(l,"probeSourcePreflight");if("status"in n)return n;let u=G();if(!u)return d("No task-executor registered for this board");try{let R={...n.src,_projections:n.mockProjections},y=await r.invokeExecutor(u,"probe-source-preflight",{timeout:n.src.timeout??r.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(R)}),C=JSON.parse(y.trim());return C.ok?m({bindTo:n.bindTo,reachable:C.reachable,latencyMs:C.latencyMs,note:C.note}):d(C.error??"Preflight probe failed")}catch{return d("Executor does not support probe-source-preflight")}}catch(n){return g(n)}}async function Ne(l){try{let n=ke(l,"runSourcePreflight");if("status"in n)return n;let u=G();if(!u)return d("No task-executor registered for this board");try{let R={...n.src,_projections:n.mockProjections},y=await r.invokeExecutor(u,"run-source-preflight",{timeout:n.src.timeout??r.executorTimeouts?.probeMs??6e4,input:JSON.stringify(R)}),C=JSON.parse(y.trim());if(!C.ok)return m({bindTo:n.bindTo,ok:!1,result:null,issues:[C.error??"Preflight run failed"]});if(n.outRef){let p=chunkVQCIOKJV_cjs.b(n.outRef);r.absoluteBlob.write(p.value,JSON.stringify(C.resultValue,null,2));}return m({bindTo:typeof C.bindTo=="string"?C.bindTo:n.bindTo,ok:!0,result:C.resultValue??null,issues:[]})}catch(R){let y=R instanceof Error?R.message:String(R);return m({bindTo:n.bindTo,ok:!1,result:null,issues:[y]})}}catch(n){return g(n)}}async function qe(l){try{let n=G();if(!n)return d("No task-executor registered for this board");let u=await r.invokeExecutor(n,"describe-capabilities",{timeout:r.executorTimeouts?.describeMs??1e4});return m(JSON.parse(u.trim()))}catch(n){return g(n)}}function je(l){try{let n=l.body;if(!n||!Array.isArray(n.ops))return d("updatesInCardStore requires body.ops array");let u=n.ops,R=j();for(let y of u){let C=y.op,p=y.id;if(!p)return d('op is missing "id"');if(C==="update"){let A=y["card-content"];if(!A)return d(`update op for "${p}" is missing "card-content"`);R.writeCard(p,A);}else return d(`Unknown op type: "${C??"(none)"}"`)}return m()}catch(n){return g(n)}}function q(l){try{let n=l.body;if(!n||!Array.isArray(n.ids))return d("readFromCardStore requires body.ids array");let u=n.ids,R=j(),y=u.map(C=>({id:C,"card-content":R.readCard(C)}));return m({cards:y})}catch(n){return g(n)}}function oe(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d("evalCardCompute requires a JSON object in body");let n=l.body,u=n["card-content"]??n,R=typeof u.id=="string"?u.id:"(unknown)",y=n["mock-fetched-sources"]??{},C=n["mock-requires"]??{},p=u.compute;if(!p||!Array.isArray(p)||p.length===0)return m({cardId:R,ok:!0,computed_values:{},errors:[]});let A={id:R,card_data:u.card_data??{},requires:C,source_defs:u.source_defs,compute:p},T=chunkZV35WD6K_cjs.a.runSync(A,{sourcesData:y}),$=T.node.computed_values??{},F=T.errors??[];return m({cardId:R,ok:F.length===0,computed_values:$,errors:F})}catch(n){return g(n)}}async function de(l){try{if(!l.body||typeof l.body!="object"||Array.isArray(l.body))return d("simulateCardCycle requires a JSON object in body");let n=l.body,u=n["card-content"]??n,R=typeof u.id=="string"?u.id:"(unknown)",y=n["mock-fetched-sources"]??{},C=n["mock-requires"]??{},p=await ce(R,u),A=p.status==="success"?{isValid:p.data.isValid,issues:p.data.issues}:{isValid:!1,issues:[p.status==="fail"?p.error:"internal error"]},T=u.source_defs??[],$=u.card_data??{},F=[],X=[],J=[];if(T.length>0){F=chunkZV35WD6K_cjs.a.enrichSourcesSync(T,{card_data:$,requires:C}),X=F.filter(I=>I._skip!==!0);for(let I of X){let D=I.projections,L=I._projections;if(D&&L){for(let W of Object.keys(D))if(L[W]===void 0){let me=typeof I.bindTo=="string"?I.bindTo:"(unknown)";J.push({bindTo:me,key:W,error:`Projection "${W}" resolved to undefined`});}}}}let z=[],he=new Set(X.map(I=>typeof I.bindTo=="string"?I.bindTo:"")),le=Object.fromEntries(Object.entries(y).filter(([I])=>he.has(I))),fe=n["task-executor-ref"],Se=(fe?.howToRun&&fe?.whatToRun?fe:void 0)??G();for(let I=0;I<F.length;I++){let D=F[I],L=typeof D.bindTo=="string"?D.bindTo:`source_${I}`;if(D._skip===!0){z.push({bindTo:L,skipped:!0});continue}if(!Se){z.push({bindTo:L,skipped:!0,error:"No task executor configured"});continue}try{let W={...D},me=await r.invokeExecutor(Se,"run-source-preflight",{timeout:D.timeout??r.executorTimeouts?.preflightMs??6e4,input:JSON.stringify(W)}),U=JSON.parse(me.trim());U.ok&&!Object.prototype.hasOwnProperty.call(y,L)&&Object.prototype.hasOwnProperty.call(U,"resultValue")&&(le[L]=U.resultValue),z.push({bindTo:L,reachable:U.reachable,latencyMs:U.latencyMs,error:U.ok?void 0:U.error});}catch{z.push({bindTo:L,skipped:!0,error:"Executor does not support run-source-preflight"});}}let se=u.compute,be={},Y=[];if(se&&Array.isArray(se)&&se.length>0){let I={id:R,card_data:$,requires:C,source_defs:u.source_defs,compute:se},D=chunkZV35WD6K_cjs.a.runSync(I,{sourcesData:le});be=D.node.computed_values??{},Y=D.errors??[];}let ye=A.isValid&&J.length===0&&Y.length===0&&z.every(I=>I.reachable!==!1);return m({cardId:R,ok:ye,validation:A,source_probes:z,projection_errors:J,fetched_sources:le,computed_values:be,compute_errors:Y})}catch(n){return g(n)}}return {validateCardPreflight:Ce,probeSourcePreflight:ne,runSourcePreflight:Ne,evalCardCompute:oe,simulateCardCycle:de,describeTaskExecutorCapabilities:qe,updatesInCardStore:je,readFromCardStore:q}}
2
+ exports.a=St;exports.b=Yt;exports.c=Ut;exports.d=Xt;exports.e=sr;exports.f=ar;//# sourceMappingURL=chunk-EGZPROOH.cjs.map
3
+ //# sourceMappingURL=chunk-EGZPROOH.cjs.map
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkQBEQL4TL_cjs=require('./chunk-QBEQL4TL.cjs');function P(s,d){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||`${d} failed`):new Error(`${d} returned an unexpected response`)}function G(s,d){if(s?.status==="success"&&Object.prototype.hasOwnProperty.call(s,"data"))return s.data;throw s?.status==="success"?new Error(`${d} returned success without data`):s?.status==="fail"||s?.status==="error"?new Error(s.error||`${d} failed`):new Error(`${d} returned an unexpected response`)}function n(s){return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}function y(s){return Array.isArray(s)?s:[]}function N(s,d){if(typeof d!="string"||d.length===0)return;let u=s,p=d;p.startsWith("fetched_sources.")&&(u=n(s).fetched_sources,p=p.slice(16));for(let g of p.split(".")){if(u==null||typeof u!="object")return;u=u[g];}return u}function z(s,d){let u=n(s.view);return {elements:y(u.elements).map((g,h)=>{let R=n(g),b=n(R.data),k=typeof R.visible=="string"?!!N(d,R.visible):true,x=typeof b.bind=="string"?b.bind:void 0,S=typeof b.maxRows=="number"?b.maxRows:void 0,B=x?N(d,x):void 0,q={id:typeof R.id=="string"&&R.id?R.id:`element-${h}`,kind:R.kind,label:R.label,visible:k};return B!==void 0&&(q.resolved=Array.isArray(B)&&typeof S=="number"?B.slice(0,S):B),q})}}function Q(s,d){let u=typeof s.id=="string"&&s.id?s.id:"card",p=y(s.provides),g=p.length>0?p:[{bindTo:u,ref:"card_data"}],h={};for(let R of g){let b=n(R),k=typeof b.bindTo=="string"?b.bindTo:"",x=typeof b.ref=="string"?b.ref:"";if(!k||!x)continue;let S=N(d,x);S!==void 0&&(h[k]=S);}return h}function be(s){if(typeof s!="string"||!s.trim())return null;let d=/^(file uploaded|AI generated|AI geneterated):\s*.*?#(\d+)\s*$/i.exec(s.trim());if(!d)return null;let u=Number.parseInt(d[2],10);return !Number.isInteger(u)||u<0?null:u}function ke(s){return {"card-content":s}}function j(s){let d={...s};return delete d.__private,d}function he(s,d){return Object.prototype.hasOwnProperty.call(s,d)}function Re(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}function ve(s,d){let u=Re(s);if(!d||Object.keys(d).length===0)return u;function p(g,h,R){let b=String(h||"").split(".").filter(Boolean);if(!b.length)return;let k=g;for(let x=0;x<b.length-1;x+=1){let S=b[x];(!k[S]||typeof k[S]!="object")&&(k[S]={}),k=k[S];}k[b[b.length-1]]=R;}if(d.fieldValues!==void 0&&d.fieldValues!==null){let g=null,h=n(u.view),R=y(h.elements);for(let b of R){let k=n(n(b).data);if(typeof k.writeTo=="string"&&k.writeTo){g=k.writeTo;break}}return g?p(u,g,d.fieldValues):typeof d.fieldValues=="object"&&!Array.isArray(d.fieldValues)&&(u.card_data={...n(u.card_data),...d.fieldValues}),u}if(Array.isArray(d._stagedFiles)&&d._stagedFiles.length>0)return u;for(let[g,h]of Object.entries(d))g!=="_stagedFiles"&&(h!==null&&typeof h=="object"&&!Array.isArray(h)&&u[g]!==null&&typeof u[g]=="object"&&!Array.isArray(u[g])?u[g]={...u[g],...h}:u[g]=h);return u}function D(s){return n(s.__private).visible_controlplane_only===true}async function T(s,d){let u=await A(s.get({params:{id:d}}),"cardStore.get"),p=Array.isArray(u?.cards)?u.cards:[];if(p.length===0)throw new Error(`Card "${d}" not found`);return p[0]}function Ae(s){let{board:d,nonCore:u,cardStore:p,chatStore:g,processAccumulated:h,sourceFetchDone:R,sourceFetchFailed:b,uploadCardFile:k,buildFileDownloadUrl:x,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 q(){let e=await A(p.get({}),"cardStore.get");return Array.isArray(e.cards)?e.cards.map(r=>n(r)).filter(r=>!D(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),a=atob(t);return Uint8Array.from(a,o=>o.charCodeAt(0))}throw new Error("file entry requires bytes, text, or base64")}async function Y(){let e=n(await A(u.describeTaskExecutorCapabilities({}),"describeTaskExecutorCapabilities"));return {version:e.version,commonSourceFields:n(e.commonSourceDefFields),sourceKinds:n(e.sourceKinds)}}async function Z(){let e=n(await A(d.status({}),"status")),r=n(e.summary),t=y(e.cards),a=await A(p.get({}),"cardStore.get"),o=new Set((Array.isArray(a.cards)?a.cards.map(n):[]).filter(D).map(c=>typeof c.id=="string"?c.id:"").filter(Boolean)),i=t.filter(c=>!o.has(String(n(c).name??"")));return {meta:n(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:i.map(c=>{let l=n(c);return {"card-id":typeof l.name=="string"?l.name:null,status:l.status??null,error:l.error??null,requires:y(l.requires),requires_satisfied:y(l.requires_satisfied),requires_missing:y(l.requires_missing),provides_declared:y(l.provides_declared),provides_runtime:y(l.provides_runtime)}})}}async function ee(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("inspectCardDefinitionAndRuntime requires cardId");let t=n(await A(d.status({}),"status")),o=y(t.cards).map(n).find(f=>f.name===r);if(!o)throw new Error(`card "${r}" not found in board status`);let i=n(await T(p,r)),c=j(i),l=y(o.requires_satisfied).filter(f=>typeof f=="string"&&!!f),I=y(o.provides_runtime).filter(f=>typeof f=="string"&&!!f),v=Object.fromEntries(await Promise.all(l.map(async f=>[f,await A(d.getOutputsDataObject({params:{key:f}}),`getOutputsDataObject(${f})`)]))),_=Object.fromEntries(await Promise.all(I.map(async f=>[f,await A(d.getOutputsDataObject({params:{key:f}}),`getOutputsDataObject(${f})`)]))),m=n(await A(d.getOutputsComputedValues({params:{key:r}}),"getOutputsComputedValues")),C=await A(d.getOutputsFetchedSources({params:{key:r}}),"getOutputsFetchedSources"),M=y(i.source_defs).map(n),w={};for(let f of M)typeof f.bindTo=="string"&&typeof f.outputFile=="string"&&(w[f.outputFile]=f.bindTo);let U={};for(let[f,F]of Object.entries(C)){let O=w[f]??f;if(!S||typeof F!="string"){U[O]=null;continue}try{U[O]=S({cardId:r,ref:F});}catch{U[O]=null;}}let L={card_data:n(i.card_data),requires:v,fetched_sources:U,computed_values:m};return {cardId:r,card_status_in_board:o,card_definition_and_static_data:c,refs_for_fetched_source_files:C,runtime_data:{requires:v,provides:_,computed_values:m,rendered_view:z(i,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:"",a=e.allTurns===true,o=typeof e.tailTurnsBeforeId=="string"?e.tailTurnsBeforeId:"",i=a?void 0:e.lastUserTurns??(t?void 0:1),c=e.tail,l={...i===void 0?{}:{tailTurns:i},...t?{turnId:t}:{},...a?{allTurns:true}:{},...o?{tailTurnsBeforeId:o}:{}},I=Object.keys(l).length>0?{params:{cardId:r},body:l}:{params:{cardId:r}},v=P(await g.readAll(I),"chatStore.readAll"),_=n(await T(p,r)),m=y(n(_.card_data).files).map((w,U)=>({idx:U,stored_name:n(w).stored_name})).filter(w=>typeof w.stored_name=="string"&&w.stored_name.length>0),M=(Array.isArray(v.records)?v.records:[]).map(w=>{let L=n(w.payload),f={...w},F=typeof w?.role=="string"?w.role:typeof L.role=="string"?String(L.role):"",O=typeof w?.text=="string"?w.text:typeof L.text=="string"?String(L.text):"";if(F==="system"){let V=be(O);if(V!==null&&m.some(E=>E.idx===V)){let E=`Retrieve using inspect-file-contents --card-id ${r} --file-idx ${V}`;f.retrieval_hint=E,Object.keys(L).length>0&&typeof w.role!="string"&&(f.payload={...L,retrieval_hint:E});}}return f});return {cardId:r,messages:typeof c=="number"&&c>=0?M.slice(-c):M}}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 a=n(await T(p,r)),o=y(n(a.card_data).files).map(n);if(t>=o.length)throw new Error(`attachment index ${t} is out of range for card "${r}"`);let i=o[t],c=typeof i.stored_name=="string"?i.stored_name:null;return {cardId:r,fileIdx:t,downloadUrl:x({cardId:r,fileIdx:t,storedName:c}),...typeof i.name=="string"?{name:i.name}:{},...typeof i.stored_name=="string"?{stored_name:i.stored_name}:{},...typeof i.mime_type=="string"?{mime_type:i.mime_type}:{},...typeof i.size=="number"?{size:i.size}:{},...typeof i.uploaded_at=="string"?{uploaded_at:i.uploaded_at}:{}}}async function $(e){return await u.validateCardPreflight({body:ke(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=u.evalCardCompute({body:{"card-content":e.candidateCardContent,"mock-requires":e.mockRequires,"mock-fetched-sources":e.mockFetchedSources}});if(r.status!=="success")return r;let t=n(G(r,"evalCardCompute")),a=n(e.candidateCardContent),o={card_data:n(a.card_data),requires:n(e.mockRequires),fetched_sources:n(e.mockFetchedSources),computed_values:n(t.computed_values)};return {status:"success",data:{cardId:typeof t.cardId=="string"?t.cardId:typeof a.id=="string"?a.id:"(unknown)",ok:t.ok===true,computed_values:n(t.computed_values),errors:y(t.errors).map(i=>{let c=n(i);return {bindTo:typeof c.bindTo=="string"?c.bindTo:"",error:typeof c.error=="string"?c.error:""}}),provides_outputs:Q(a,o),rendered_view:z(a,o)}}}async function ae(e){return await u.probeSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":e.candidateCardContent,"mock-projections":e.mockProjections}})}async function oe(e){return await u.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=n(await T(p,r)),a=y(t.source_defs).filter(i=>!!i&&typeof i=="object"&&!Array.isArray(i)),o={};if(e.sourceIdx>=0&&e.sourceIdx<a.length){let i=a[e.sourceIdx],c=chunkQBEQL4TL_cjs.a.enrichSourcesSync([i],{card_data:n(t.card_data),requires:e.mockRequires});Array.isArray(c)&&c.length>0&&(o=n(c[0]._projections));}return await u.runSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":t,"mock-requires":e.mockRequires,"mock-projections":o}})}async function ie(e){let r=n(await A(u.simulateCardCycle({body:{"card-content":e.candidateCardContent,"mock-requires":e.mockRequires}}),"simulateCardCycle")),t=n(e.candidateCardContent),a=n(r.validation),o=y(r.source_probes),i=y(r.projection_errors),c=n(r.fetched_sources),l=y(r.compute_errors),I=n(r.computed_values),v={card_data:n(t.card_data),requires:e.mockRequires,fetched_sources:c,computed_values:I},_=[];for(let m of y(a.issues))typeof m=="string"&&m&&_.push(m);for(let m of o){let C=n(m),M=typeof C.bindTo=="string"?C.bindTo:"source",w=typeof C.error=="string"?C.error:"";w&&_.push(`${M}: ${w}`);}for(let m of i){let C=n(m),M=typeof C.bindTo=="string"?C.bindTo:"source",w=typeof C.key=="string"?C.key:"projection",U=typeof C.error=="string"?C.error:"projection failed";_.push(`${M}.${w}: ${U}`);}for(let m of l){let C=n(m),M=typeof C.bindTo=="string"?C.bindTo:"compute",w=typeof C.error=="string"?C.error:"compute failed";_.push(`${M}: ${w}`);}return {status:"success",data:{cardId:typeof r.cardId=="string"?r.cardId:"(unknown)",ok:r.ok===true,issues:_,provides_outputs:Q(t,v),rendered_view:z(t,v)}}}async function K(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("manageReadCard requires cardId");let t=await A(p.get({params:{id:r}}),"cardStore.get");return (Array.isArray(t.cards)?t.cards.map(n):[]).map(o=>j(o))}async function W(e){let r=await Promise.all(y(e.files).map(async t=>{let a=n(t),o=String(a.file_name??a.fileName??a.name??"").trim(),i=String(a.content_type??a.contentType??"application/octet-stream");if(!o)throw new Error("file entry requires file_name");return await k({cardId:e.cardId,fileName:o,contentType:i,bytes:X(a),suppressChatRecordWrite:true})}));for(let[t,a]of r.entries()){let o=n(a.file),i=typeof a.file_idx=="number"&&Number.isInteger(a.file_idx)&&a.file_idx>=0?a.file_idx:t,c=e.role==="assistant"?`AI generated: ${String(o.name||"")} as ${String(o.stored_name||"")} #${i}`:`file uploaded: ${String(o.name||"")} as ${String(o.stored_name||"")} #${i}`;P(await g.append({params:{cardId:e.cardId},body:{role:"system",text:c,files:[],turn:e.turn}}),"chatStore.append(system attachment message)");}return r.map(t=>t.file)}async function de(e){let r=String(e.cardId||"").trim(),t=String(e.role||"user").trim()||"user",a=typeof e.turn=="string"?e.turn:"";if(!r)throw new Error("manageAddChatAttachment requires cardId");let o=await W({cardId:r,role:t,turn:a,files:e.files});return {status:"success",data:{cardId:r,turn:a,files:o}}}async function ce(e){let r=String(e.cardId||"").trim(),t=String(e.role||"").trim(),a=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 l=P(await g.readAll({params:{cardId:r},body:{turnId:o}}),"chatStore.readAll(existing turn messages)"),I=Array.isArray(l.records)?l.records.find(v=>v.role==="assistant"&&String(v.turn||"")===o):void 0;if(I)return {status:"success",data:{cardId:r,id:String(I.id),role:t,turn:o,files:Array.isArray(I.files)?I.files:[]}}}let i=await W({cardId:r,role:t,turn:o,files:e.files}),c=P(await g.append({params:{cardId:r},body:{role:t,text:a,files:i,turn:o}}),"chatStore.append");return {status:"success",data:{cardId:r,id:String(c.id),role:t,turn:o,files:i}}}async function ue(e,r={}){let t=String(e.cardId||"").trim(),a=n(e.patch);if(!t)throw new Error("managePatchCard requires cardId");let o=await K({cardId:t}),i=n(o[0]),c=ve(i,a);return J({cardId:t,candidateCardContent:c},r)}async function J(e,r={}){let t=String(e.cardId||"").trim(),a=n(e.candidateCardContent),o=j(a);if(!t)throw new Error("manageUpsertCard requires cardId");if(typeof o.id!="string"||!o.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(o.id!==t)throw new Error(`candidateCardContent.id must match cardId (${t})`);let i=null;try{i=await $({candidateCardContent:o});}catch(m){let C=m instanceof Error?m.message:String(m);if(!/non-core adapter is not configured/i.test(C))throw m;i=null;}if(i!==null){let m=n(i),C=n(m.data);if(m.status!=="success"||C.isValid!==true)return {status:"fail",step:"validate",validation:i}}let c=null;try{c=await T(p,t);}catch{c=null;}let l=c?n(c):null;if(l&&D(l)&&!r.allowControlplaneOnlyCards)throw Object.assign(new Error(`Card "${t}" not found`),{statusCode:404});let I={...o,...l&&he(l,"__private")?{__private:l.__private}:{}},v=await p.set({body:I});P(v,"cardStore.set");let _;try{_=await d.upsertCard({params:{cardId:t,restart:!0}}),P(_,"upsertCard");}catch(m){try{c&&await p.set({body:c});}catch{}throw m}return {status:"success",data:{validation:i,card_saved:null,board_result:_}}}async function le(e,r={}){let t=String(e.cardId||"").trim();if(!t)throw new Error("manageRemoveCard requires cardId");if(!r.allowControlplaneOnlyCards){let i=await A(p.get({params:{id:t}}),"cardStore.get");if((Array.isArray(i.cards)?i.cards.map(n):[]).some(D))throw Object.assign(new Error(`Card "${t}" not found`),{statusCode:404})}let a=await d.removeCard({params:{id:t}});P(a,"removeCard");let o=await p.del({params:{id:t}});return P(o,"cardStore.del"),{status:"success",data:{board_result:a,store_result:o}}}async function pe(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("adminReadCard requires cardId");let t=await A(p.get({params:{id:r}}),"cardStore.get");return Array.isArray(t.cards)?t.cards.map(a=>n(a)):[]}async function me(e){let r=String(e.cardId||"").trim(),t=n(e.candidateCardContent),a=j(t);if(!r)throw new Error("adminUpsertCard requires cardId");if(typeof a.id!="string"||!a.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(a.id!==r)throw new Error(`candidateCardContent.id must match cardId (${r})`);let o=await $({candidateCardContent:a}),i=n(o),c=n(i.data);if(i.status!=="success"||c.isValid!==true)return {status:"fail",step:"validate",validation:o};let l=null;try{l=await T(p,r);}catch{l=null;}let I=l?n(n(l).__private):{},v={...a,__private:{...I,visible_controlplane_only:true}},_=await p.set({body:v});P(_,"cardStore.set");let m;try{m=await d.upsertCard({params:{cardId:r,restart:!0}}),P(m,"upsertCard");}catch(C){try{l&&await p.set({body:l});}catch{}throw C}return {status:"success",data:{validation:o,card_saved:null,board_result:m}}}async function fe(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("getChatProcessing requires cardId");let t=G(await g.isProcessing({params:{cardId:r}}),"chatStore.isProcessing");return {cardId:r,active:!!t.active}}async 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 P(await g.setProcessing({params:{cardId:r},body:{active:e.active}}),"chatStore.setProcessing"),{cardId:r,active:e.active}}async function Ce(){let e=await B(h,"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 we(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 a=await B(R,"webhook.source-fetch-done")({token:r,ref:t});return a?.status==="fail"||a?.status==="error"?a:{status:"success",data:{token:r,ref:t,runtime_result:Object.prototype.hasOwnProperty.call(a??{},"data")?a.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 a=await B(b,"webhook.source-fetch-failed")({token:r,reason:t});return a?.status==="fail"||a?.status==="error"?a:{status:"success",data:{token:r,reason:t,runtime_result:Object.prototype.hasOwnProperty.call(a??{},"data")?a.data??null:null}}}return {listRuntimeCards:q,discoverSourceKinds:Y,inspectBoardRuntimeStatus:Z,inspectCardDefinitionAndRuntime:ee,inspectChatMessagesOnCards:re,inspectFileContents:te,preflightValidateCandidateCardDefinition:$,preflightMaterializeCandidateCard:ne,preflightProbeSingleSourceInCandidateCard:ae,preflightRunSingleSourceInCandidateCard:oe,preflightRunSingleSourceInLiveCard:se,preflightRunOneCycleWithCandidateCard:ie,manageReadCard:K,manageAddChatAttachment:de,manageAddChatEntryAndAnyAttachments:ce,managePatchCard:ue,manageUpsertCard:J,manageRemoveCard:le,adminReadCard:pe,adminUpsertCard:me,getChatProcessing:fe,setChatProcessing:ge,webhookProcessAccumulated:Ce,webhookSourceFetchDone:we,webhookSourceFetchFailed:ye}}async function A(s,d){return P(await s,d)}exports.a=Ae;//# sourceMappingURL=chunk-GHUW6P4G.cjs.map
2
- //# sourceMappingURL=chunk-GHUW6P4G.cjs.map
1
+ 'use strict';var chunkZV35WD6K_cjs=require('./chunk-ZV35WD6K.cjs');function P(s,d){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||`${d} failed`):new Error(`${d} returned an unexpected response`)}function G(s,d){if(s?.status==="success"&&Object.prototype.hasOwnProperty.call(s,"data"))return s.data;throw s?.status==="success"?new Error(`${d} returned success without data`):s?.status==="fail"||s?.status==="error"?new Error(s.error||`${d} failed`):new Error(`${d} returned an unexpected response`)}function n(s){return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}function y(s){return Array.isArray(s)?s:[]}function N(s,d){if(typeof d!="string"||d.length===0)return;let u=s,p=d;p.startsWith("fetched_sources.")&&(u=n(s).fetched_sources,p=p.slice(16));for(let g of p.split(".")){if(u==null||typeof u!="object")return;u=u[g];}return u}function z(s,d){let u=n(s.view);return {elements:y(u.elements).map((g,h)=>{let R=n(g),b=n(R.data),k=typeof R.visible=="string"?!!N(d,R.visible):true,x=typeof b.bind=="string"?b.bind:void 0,S=typeof b.maxRows=="number"?b.maxRows:void 0,B=x?N(d,x):void 0,q={id:typeof R.id=="string"&&R.id?R.id:`element-${h}`,kind:R.kind,label:R.label,visible:k};return B!==void 0&&(q.resolved=Array.isArray(B)&&typeof S=="number"?B.slice(0,S):B),q})}}function Q(s,d){let u=typeof s.id=="string"&&s.id?s.id:"card",p=y(s.provides),g=p.length>0?p:[{bindTo:u,ref:"card_data"}],h={};for(let R of g){let b=n(R),k=typeof b.bindTo=="string"?b.bindTo:"",x=typeof b.ref=="string"?b.ref:"";if(!k||!x)continue;let S=N(d,x);S!==void 0&&(h[k]=S);}return h}function be(s){if(typeof s!="string"||!s.trim())return null;let d=/^(file uploaded|AI generated|AI geneterated):\s*.*?#(\d+)\s*$/i.exec(s.trim());if(!d)return null;let u=Number.parseInt(d[2],10);return !Number.isInteger(u)||u<0?null:u}function ke(s){return {"card-content":s}}function j(s){let d={...s};return delete d.__private,d}function he(s,d){return Object.prototype.hasOwnProperty.call(s,d)}function Re(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}function ve(s,d){let u=Re(s);if(!d||Object.keys(d).length===0)return u;function p(g,h,R){let b=String(h||"").split(".").filter(Boolean);if(!b.length)return;let k=g;for(let x=0;x<b.length-1;x+=1){let S=b[x];(!k[S]||typeof k[S]!="object")&&(k[S]={}),k=k[S];}k[b[b.length-1]]=R;}if(d.fieldValues!==void 0&&d.fieldValues!==null){let g=null,h=n(u.view),R=y(h.elements);for(let b of R){let k=n(n(b).data);if(typeof k.writeTo=="string"&&k.writeTo){g=k.writeTo;break}}return g?p(u,g,d.fieldValues):typeof d.fieldValues=="object"&&!Array.isArray(d.fieldValues)&&(u.card_data={...n(u.card_data),...d.fieldValues}),u}if(Array.isArray(d._stagedFiles)&&d._stagedFiles.length>0)return u;for(let[g,h]of Object.entries(d))g!=="_stagedFiles"&&(h!==null&&typeof h=="object"&&!Array.isArray(h)&&u[g]!==null&&typeof u[g]=="object"&&!Array.isArray(u[g])?u[g]={...u[g],...h}:u[g]=h);return u}function D(s){return n(s.__private).visible_controlplane_only===true}async function T(s,d){let u=await A(s.get({params:{id:d}}),"cardStore.get"),p=Array.isArray(u?.cards)?u.cards:[];if(p.length===0)throw new Error(`Card "${d}" not found`);return p[0]}function Ae(s){let{board:d,nonCore:u,cardStore:p,chatStore:g,processAccumulated:h,sourceFetchDone:R,sourceFetchFailed:b,uploadCardFile:k,buildFileDownloadUrl:x,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 q(){let e=await A(p.get({}),"cardStore.get");return Array.isArray(e.cards)?e.cards.map(r=>n(r)).filter(r=>!D(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),a=atob(t);return Uint8Array.from(a,o=>o.charCodeAt(0))}throw new Error("file entry requires bytes, text, or base64")}async function Y(){let e=n(await A(u.describeTaskExecutorCapabilities({}),"describeTaskExecutorCapabilities"));return {version:e.version,commonSourceFields:n(e.commonSourceDefFields),sourceKinds:n(e.sourceKinds)}}async function Z(){let e=n(await A(d.status({}),"status")),r=n(e.summary),t=y(e.cards),a=await A(p.get({}),"cardStore.get"),o=new Set((Array.isArray(a.cards)?a.cards.map(n):[]).filter(D).map(c=>typeof c.id=="string"?c.id:"").filter(Boolean)),i=t.filter(c=>!o.has(String(n(c).name??"")));return {meta:n(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:i.map(c=>{let l=n(c);return {"card-id":typeof l.name=="string"?l.name:null,status:l.status??null,error:l.error??null,requires:y(l.requires),requires_satisfied:y(l.requires_satisfied),requires_missing:y(l.requires_missing),provides_declared:y(l.provides_declared),provides_runtime:y(l.provides_runtime)}})}}async function ee(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("inspectCardDefinitionAndRuntime requires cardId");let t=n(await A(d.status({}),"status")),o=y(t.cards).map(n).find(f=>f.name===r);if(!o)throw new Error(`card "${r}" not found in board status`);let i=n(await T(p,r)),c=j(i),l=y(o.requires_satisfied).filter(f=>typeof f=="string"&&!!f),I=y(o.provides_runtime).filter(f=>typeof f=="string"&&!!f),v=Object.fromEntries(await Promise.all(l.map(async f=>[f,await A(d.getOutputsDataObject({params:{key:f}}),`getOutputsDataObject(${f})`)]))),_=Object.fromEntries(await Promise.all(I.map(async f=>[f,await A(d.getOutputsDataObject({params:{key:f}}),`getOutputsDataObject(${f})`)]))),m=n(await A(d.getOutputsComputedValues({params:{key:r}}),"getOutputsComputedValues")),C=await A(d.getOutputsFetchedSources({params:{key:r}}),"getOutputsFetchedSources"),M=y(i.source_defs).map(n),w={};for(let f of M)typeof f.bindTo=="string"&&typeof f.outputFile=="string"&&(w[f.outputFile]=f.bindTo);let U={};for(let[f,F]of Object.entries(C)){let O=w[f]??f;if(!S||typeof F!="string"){U[O]=null;continue}try{U[O]=S({cardId:r,ref:F});}catch{U[O]=null;}}let L={card_data:n(i.card_data),requires:v,fetched_sources:U,computed_values:m};return {cardId:r,card_status_in_board:o,card_definition_and_static_data:c,refs_for_fetched_source_files:C,runtime_data:{requires:v,provides:_,computed_values:m,rendered_view:z(i,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:"",a=e.allTurns===true,o=typeof e.tailTurnsBeforeId=="string"?e.tailTurnsBeforeId:"",i=a?void 0:e.lastUserTurns??(t?void 0:1),c=e.tail,l={...i===void 0?{}:{tailTurns:i},...t?{turnId:t}:{},...a?{allTurns:true}:{},...o?{tailTurnsBeforeId:o}:{}},I=Object.keys(l).length>0?{params:{cardId:r},body:l}:{params:{cardId:r}},v=P(await g.readAll(I),"chatStore.readAll"),_=n(await T(p,r)),m=y(n(_.card_data).files).map((w,U)=>({idx:U,stored_name:n(w).stored_name})).filter(w=>typeof w.stored_name=="string"&&w.stored_name.length>0),M=(Array.isArray(v.records)?v.records:[]).map(w=>{let L=n(w.payload),f={...w},F=typeof w?.role=="string"?w.role:typeof L.role=="string"?String(L.role):"",O=typeof w?.text=="string"?w.text:typeof L.text=="string"?String(L.text):"";if(F==="system"){let V=be(O);if(V!==null&&m.some(E=>E.idx===V)){let E=`Retrieve using inspect-file-contents --card-id ${r} --file-idx ${V}`;f.retrieval_hint=E,Object.keys(L).length>0&&typeof w.role!="string"&&(f.payload={...L,retrieval_hint:E});}}return f});return {cardId:r,messages:typeof c=="number"&&c>=0?M.slice(-c):M}}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 a=n(await T(p,r)),o=y(n(a.card_data).files).map(n);if(t>=o.length)throw new Error(`attachment index ${t} is out of range for card "${r}"`);let i=o[t],c=typeof i.stored_name=="string"?i.stored_name:null;return {cardId:r,fileIdx:t,downloadUrl:x({cardId:r,fileIdx:t,storedName:c}),...typeof i.name=="string"?{name:i.name}:{},...typeof i.stored_name=="string"?{stored_name:i.stored_name}:{},...typeof i.mime_type=="string"?{mime_type:i.mime_type}:{},...typeof i.size=="number"?{size:i.size}:{},...typeof i.uploaded_at=="string"?{uploaded_at:i.uploaded_at}:{}}}async function $(e){return await u.validateCardPreflight({body:ke(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=u.evalCardCompute({body:{"card-content":e.candidateCardContent,"mock-requires":e.mockRequires,"mock-fetched-sources":e.mockFetchedSources}});if(r.status!=="success")return r;let t=n(G(r,"evalCardCompute")),a=n(e.candidateCardContent),o={card_data:n(a.card_data),requires:n(e.mockRequires),fetched_sources:n(e.mockFetchedSources),computed_values:n(t.computed_values)};return {status:"success",data:{cardId:typeof t.cardId=="string"?t.cardId:typeof a.id=="string"?a.id:"(unknown)",ok:t.ok===true,computed_values:n(t.computed_values),errors:y(t.errors).map(i=>{let c=n(i);return {bindTo:typeof c.bindTo=="string"?c.bindTo:"",error:typeof c.error=="string"?c.error:""}}),provides_outputs:Q(a,o),rendered_view:z(a,o)}}}async function ae(e){return await u.probeSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":e.candidateCardContent,"mock-projections":e.mockProjections}})}async function oe(e){return await u.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=n(await T(p,r)),a=y(t.source_defs).filter(i=>!!i&&typeof i=="object"&&!Array.isArray(i)),o={};if(e.sourceIdx>=0&&e.sourceIdx<a.length){let i=a[e.sourceIdx],c=chunkZV35WD6K_cjs.a.enrichSourcesSync([i],{card_data:n(t.card_data),requires:e.mockRequires});Array.isArray(c)&&c.length>0&&(o=n(c[0]._projections));}return await u.runSourcePreflight({params:{sourceIdx:e.sourceIdx},body:{"card-content":t,"mock-requires":e.mockRequires,"mock-projections":o}})}async function ie(e){let r=n(await A(u.simulateCardCycle({body:{"card-content":e.candidateCardContent,"mock-requires":e.mockRequires}}),"simulateCardCycle")),t=n(e.candidateCardContent),a=n(r.validation),o=y(r.source_probes),i=y(r.projection_errors),c=n(r.fetched_sources),l=y(r.compute_errors),I=n(r.computed_values),v={card_data:n(t.card_data),requires:e.mockRequires,fetched_sources:c,computed_values:I},_=[];for(let m of y(a.issues))typeof m=="string"&&m&&_.push(m);for(let m of o){let C=n(m),M=typeof C.bindTo=="string"?C.bindTo:"source",w=typeof C.error=="string"?C.error:"";w&&_.push(`${M}: ${w}`);}for(let m of i){let C=n(m),M=typeof C.bindTo=="string"?C.bindTo:"source",w=typeof C.key=="string"?C.key:"projection",U=typeof C.error=="string"?C.error:"projection failed";_.push(`${M}.${w}: ${U}`);}for(let m of l){let C=n(m),M=typeof C.bindTo=="string"?C.bindTo:"compute",w=typeof C.error=="string"?C.error:"compute failed";_.push(`${M}: ${w}`);}return {status:"success",data:{cardId:typeof r.cardId=="string"?r.cardId:"(unknown)",ok:r.ok===true,issues:_,provides_outputs:Q(t,v),rendered_view:z(t,v)}}}async function K(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("manageReadCard requires cardId");let t=await A(p.get({params:{id:r}}),"cardStore.get");return (Array.isArray(t.cards)?t.cards.map(n):[]).map(o=>j(o))}async function W(e){let r=await Promise.all(y(e.files).map(async t=>{let a=n(t),o=String(a.file_name??a.fileName??a.name??"").trim(),i=String(a.content_type??a.contentType??"application/octet-stream");if(!o)throw new Error("file entry requires file_name");return await k({cardId:e.cardId,fileName:o,contentType:i,bytes:X(a),suppressChatRecordWrite:true})}));for(let[t,a]of r.entries()){let o=n(a.file),i=typeof a.file_idx=="number"&&Number.isInteger(a.file_idx)&&a.file_idx>=0?a.file_idx:t,c=e.role==="assistant"?`AI generated: ${String(o.name||"")} as ${String(o.stored_name||"")} #${i}`:`file uploaded: ${String(o.name||"")} as ${String(o.stored_name||"")} #${i}`;P(await g.append({params:{cardId:e.cardId},body:{role:"system",text:c,files:[],turn:e.turn}}),"chatStore.append(system attachment message)");}return r.map(t=>t.file)}async function de(e){let r=String(e.cardId||"").trim(),t=String(e.role||"user").trim()||"user",a=typeof e.turn=="string"?e.turn:"";if(!r)throw new Error("manageAddChatAttachment requires cardId");let o=await W({cardId:r,role:t,turn:a,files:e.files});return {status:"success",data:{cardId:r,turn:a,files:o}}}async function ce(e){let r=String(e.cardId||"").trim(),t=String(e.role||"").trim(),a=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 l=P(await g.readAll({params:{cardId:r},body:{turnId:o}}),"chatStore.readAll(existing turn messages)"),I=Array.isArray(l.records)?l.records.find(v=>v.role==="assistant"&&String(v.turn||"")===o):void 0;if(I)return {status:"success",data:{cardId:r,id:String(I.id),role:t,turn:o,files:Array.isArray(I.files)?I.files:[]}}}let i=await W({cardId:r,role:t,turn:o,files:e.files}),c=P(await g.append({params:{cardId:r},body:{role:t,text:a,files:i,turn:o}}),"chatStore.append");return {status:"success",data:{cardId:r,id:String(c.id),role:t,turn:o,files:i}}}async function ue(e,r={}){let t=String(e.cardId||"").trim(),a=n(e.patch);if(!t)throw new Error("managePatchCard requires cardId");let o=await K({cardId:t}),i=n(o[0]),c=ve(i,a);return J({cardId:t,candidateCardContent:c},r)}async function J(e,r={}){let t=String(e.cardId||"").trim(),a=n(e.candidateCardContent),o=j(a);if(!t)throw new Error("manageUpsertCard requires cardId");if(typeof o.id!="string"||!o.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(o.id!==t)throw new Error(`candidateCardContent.id must match cardId (${t})`);let i=null;try{i=await $({candidateCardContent:o});}catch(m){let C=m instanceof Error?m.message:String(m);if(!/non-core adapter is not configured/i.test(C))throw m;i=null;}if(i!==null){let m=n(i),C=n(m.data);if(m.status!=="success"||C.isValid!==true)return {status:"fail",step:"validate",validation:i}}let c=null;try{c=await T(p,t);}catch{c=null;}let l=c?n(c):null;if(l&&D(l)&&!r.allowControlplaneOnlyCards)throw Object.assign(new Error(`Card "${t}" not found`),{statusCode:404});let I={...o,...l&&he(l,"__private")?{__private:l.__private}:{}},v=await p.set({body:I});P(v,"cardStore.set");let _;try{_=await d.upsertCard({params:{cardId:t,restart:!0}}),P(_,"upsertCard");}catch(m){try{c&&await p.set({body:c});}catch{}throw m}return {status:"success",data:{validation:i,card_saved:null,board_result:_}}}async function le(e,r={}){let t=String(e.cardId||"").trim();if(!t)throw new Error("manageRemoveCard requires cardId");if(!r.allowControlplaneOnlyCards){let i=await A(p.get({params:{id:t}}),"cardStore.get");if((Array.isArray(i.cards)?i.cards.map(n):[]).some(D))throw Object.assign(new Error(`Card "${t}" not found`),{statusCode:404})}let a=await d.removeCard({params:{id:t}});P(a,"removeCard");let o=await p.del({params:{id:t}});return P(o,"cardStore.del"),{status:"success",data:{board_result:a,store_result:o}}}async function pe(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("adminReadCard requires cardId");let t=await A(p.get({params:{id:r}}),"cardStore.get");return Array.isArray(t.cards)?t.cards.map(a=>n(a)):[]}async function me(e){let r=String(e.cardId||"").trim(),t=n(e.candidateCardContent),a=j(t);if(!r)throw new Error("adminUpsertCard requires cardId");if(typeof a.id!="string"||!a.id.trim())throw new Error("candidateCardContent.id must be a non-empty string");if(a.id!==r)throw new Error(`candidateCardContent.id must match cardId (${r})`);let o=await $({candidateCardContent:a}),i=n(o),c=n(i.data);if(i.status!=="success"||c.isValid!==true)return {status:"fail",step:"validate",validation:o};let l=null;try{l=await T(p,r);}catch{l=null;}let I=l?n(n(l).__private):{},v={...a,__private:{...I,visible_controlplane_only:true}},_=await p.set({body:v});P(_,"cardStore.set");let m;try{m=await d.upsertCard({params:{cardId:r,restart:!0}}),P(m,"upsertCard");}catch(C){try{l&&await p.set({body:l});}catch{}throw C}return {status:"success",data:{validation:o,card_saved:null,board_result:m}}}async function fe(e){let r=String(e.cardId||"").trim();if(!r)throw new Error("getChatProcessing requires cardId");let t=G(await g.isProcessing({params:{cardId:r}}),"chatStore.isProcessing");return {cardId:r,active:!!t.active}}async 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 P(await g.setProcessing({params:{cardId:r},body:{active:e.active}}),"chatStore.setProcessing"),{cardId:r,active:e.active}}async function Ce(){let e=await B(h,"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 we(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 a=await B(R,"webhook.source-fetch-done")({token:r,ref:t});return a?.status==="fail"||a?.status==="error"?a:{status:"success",data:{token:r,ref:t,runtime_result:Object.prototype.hasOwnProperty.call(a??{},"data")?a.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 a=await B(b,"webhook.source-fetch-failed")({token:r,reason:t});return a?.status==="fail"||a?.status==="error"?a:{status:"success",data:{token:r,reason:t,runtime_result:Object.prototype.hasOwnProperty.call(a??{},"data")?a.data??null:null}}}return {listRuntimeCards:q,discoverSourceKinds:Y,inspectBoardRuntimeStatus:Z,inspectCardDefinitionAndRuntime:ee,inspectChatMessagesOnCards:re,inspectFileContents:te,preflightValidateCandidateCardDefinition:$,preflightMaterializeCandidateCard:ne,preflightProbeSingleSourceInCandidateCard:ae,preflightRunSingleSourceInCandidateCard:oe,preflightRunSingleSourceInLiveCard:se,preflightRunOneCycleWithCandidateCard:ie,manageReadCard:K,manageAddChatAttachment:de,manageAddChatEntryAndAnyAttachments:ce,managePatchCard:ue,manageUpsertCard:J,manageRemoveCard:le,adminReadCard:pe,adminUpsertCard:me,getChatProcessing:fe,setChatProcessing:ge,webhookProcessAccumulated:Ce,webhookSourceFetchDone:we,webhookSourceFetchFailed:ye}}async function A(s,d){return P(await s,d)}exports.a=Ae;//# sourceMappingURL=chunk-ESTFYRHF.cjs.map
2
+ //# sourceMappingURL=chunk-ESTFYRHF.cjs.map