dsh-workflow-execute 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3647 @@
1
+ /* Generated from client/index.js by scripts/build-client.mjs — do not edit by hand.
2
+ * Regenerate with: npm run build:client
3
+ */
4
+ window.__ModuleLoader__.load({
5
+ id: "dsh-workflow-execute",
6
+ factory: (require) => {
7
+ var module = { exports: {} }
8
+ var exports = module.exports
9
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" })
10
+ var React = require("react")
11
+ var YamlLibSrc = "var YamlLib=(()=>{var gs=Object.defineProperty;var Di=Object.getOwnPropertyDescriptor;var Ki=Object.getOwnPropertyNames;var ji=Object.prototype.hasOwnProperty;var g=(s,e,t)=>()=>{if(t)throw t[0];try{return s&&(e=s(s=0)),e}catch(n){throw t=[n],n}};var qi=(s,e)=>()=>{try{return e||s((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ys=(s,e)=>{for(var t in e)gs(s,t,{get:e[t],enumerable:!0})},Ri=(s,e,t,n)=>{if(e&&typeof e==\"object\"||typeof e==\"function\")for(let i of Ki(e))!ji.call(s,i)&&i!==t&&gs(s,i,{get:()=>e[i],enumerable:!(n=Di(e,i))||n.enumerable});return s};var Fi=s=>Ri(gs({},\"__esModule\",{value:!0}),s);function v(s){if(s&&typeof s==\"object\")switch(s[R]){case H:case ae:return!0}return!1}function L(s){if(s&&typeof s==\"object\")switch(s[R]){case Nt:case H:case U:case ae:return!0}return!1}var Nt,Ot,H,bs,U,ae,R,V,J,Y,I,E,Q,At,C=g(()=>{Nt=Symbol.for(\"yaml.alias\"),Ot=Symbol.for(\"yaml.document\"),H=Symbol.for(\"yaml.map\"),bs=Symbol.for(\"yaml.pair\"),U=Symbol.for(\"yaml.scalar\"),ae=Symbol.for(\"yaml.seq\"),R=Symbol.for(\"yaml.node.type\"),V=s=>!!s&&typeof s==\"object\"&&s[R]===Nt,J=s=>!!s&&typeof s==\"object\"&&s[R]===Ot,Y=s=>!!s&&typeof s==\"object\"&&s[R]===H,I=s=>!!s&&typeof s==\"object\"&&s[R]===bs,E=s=>!!s&&typeof s==\"object\"&&s[R]===U,Q=s=>!!s&&typeof s==\"object\"&&s[R]===ae;At=s=>(E(s)||v(s))&&!!s.anchor});function G(s,e){let t=bn(e);J(s)?Pe(null,s.contents,t,Object.freeze([s]))===ne&&(s.contents=null):Pe(null,s,t,Object.freeze([]))}function Pe(s,e,t,n){let i=wn(s,e,t,n);if(L(i)||I(i))return Sn(s,n,i),Pe(s,i,t,n);if(typeof i!=\"symbol\"){if(v(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){let o=Pe(r,e.items[r],t,n);if(typeof o==\"number\")r=o-1;else{if(o===F)return F;o===ne&&(e.items.splice(r,1),r-=1)}}}else if(I(e)){n=Object.freeze(n.concat(e));let r=Pe(\"key\",e.key,t,n);if(r===F)return F;r===ne&&(e.key=null);let o=Pe(\"value\",e.value,t,n);if(o===F)return F;o===ne&&(e.value=null)}}return i}async function Be(s,e){let t=bn(e);J(s)?await Me(null,s.contents,t,Object.freeze([s]))===ne&&(s.contents=null):await Me(null,s,t,Object.freeze([]))}async function Me(s,e,t,n){let i=await wn(s,e,t,n);if(L(i)||I(i))return Sn(s,n,i),Me(s,i,t,n);if(typeof i!=\"symbol\"){if(v(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){let o=await Me(r,e.items[r],t,n);if(typeof o==\"number\")r=o-1;else{if(o===F)return F;o===ne&&(e.items.splice(r,1),r-=1)}}}else if(I(e)){n=Object.freeze(n.concat(e));let r=await Me(\"key\",e.key,t,n);if(r===F)return F;r===ne&&(e.key=null);let o=await Me(\"value\",e.value,t,n);if(o===F)return F;o===ne&&(e.value=null)}}return i}function bn(s){return typeof s==\"object\"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}function wn(s,e,t,n){if(typeof t==\"function\")return t(s,e,n);if(Y(e))return t.Map?.(s,e,n);if(Q(e))return t.Seq?.(s,e,n);if(I(e))return t.Pair?.(s,e,n);if(E(e))return t.Scalar?.(s,e,n);if(V(e))return t.Alias?.(s,e,n)}function Sn(s,e,t){let n=e[e.length-1];if(v(n))n.items[s]=t;else if(I(n))s===\"key\"?n.key=t:n.value=t;else if(J(n))n.contents=t;else{let i=V(n)?\"alias\":\"scalar\";throw new Error(`Cannot replace node with ${i} parent`)}}var F,yn,ne,He=g(()=>{C();F=Symbol(\"break visit\"),yn=Symbol(\"skip children\"),ne=Symbol(\"remove node\");G.BREAK=F;G.SKIP=yn;G.REMOVE=ne;Be.BREAK=F;Be.SKIP=yn;Be.REMOVE=ne});var xi,Ui,ie,ws=g(()=>{C();He();xi={\"!\":\"%21\",\",\":\"%2C\",\"[\":\"%5B\",\"]\":\"%5D\",\"{\":\"%7B\",\"}\":\"%7D\"},Ui=s=>s.replace(/[!,[\\]{}]/g,e=>xi[e]),ie=class s{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},s.defaultYaml,e),this.tags=Object.assign({},s.defaultTags,t)}clone(){let e=new s(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new s(this.yaml,this.tags);switch(this.yaml.version){case\"1.1\":this.atNextDocument=!0;break;case\"1.2\":this.atNextDocument=!1,this.yaml={explicit:s.defaultYaml.explicit,version:\"1.2\"},this.tags=Object.assign({},s.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:s.defaultYaml.explicit,version:\"1.1\"},this.tags=Object.assign({},s.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \\t]+/),i=n.shift();switch(i){case\"%TAG\":{if(n.length!==2&&(t(0,\"%TAG directive should contain exactly two parts\"),n.length<2))return!1;let[r,o]=n;return this.tags[r]=o,!0}case\"%YAML\":{if(this.yaml.explicit=!0,n.length!==1)return t(0,\"%YAML directive should contain exactly one part\"),!1;let[r]=n;if(r===\"1.1\"||r===\"1.2\")return this.yaml.version=r,!0;{let o=/^\\d+\\.\\d+$/.test(r);return t(6,`Unsupported YAML version ${r}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===\"!\")return\"!\";if(e[0]!==\"!\")return t(`Not a valid tag: ${e}`),null;if(e[1]===\"<\"){let o=e.slice(2,-1);return o===\"!\"||o===\"!!\"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==\">\"&&t(\"Verbatim tags must end with a >\"),o)}let[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);let r=this.tags[n];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n===\"!\"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Ui(e.substring(n.length));return e[0]===\"!\"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||\"1.2\"}`]:[],n=Object.entries(this.tags),i;if(e&&n.length>0&&L(e.contents)){let r={};G(e.contents,(o,l)=>{L(l)&&l.tag&&(r[l.tag]=!0)}),i=Object.keys(r)}else i=[];for(let[r,o]of n)r===\"!!\"&&o===\"tag:yaml.org,2002:\"||(!e||i.some(l=>l.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`\n`)}};ie.defaultYaml={explicit:!1,version:\"1.2\"};ie.defaultTags={\"!!\":\"tag:yaml.org,2002:\"}});function Et(s){if(/[\\x00-\\x19\\s,[\\]{}]/.test(s)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(s)}`;throw new Error(t)}return!0}function Ss(s){let e=new Set;return G(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function ks(s,e){for(let t=1;;++t){let n=`${s}${t}`;if(!e.has(n))return n}}function kn(s,e){let t=[],n=new Map,i=null;return{onAnchor:r=>{t.push(r),i??(i=Ss(s));let o=ks(e,i);return i.add(o),o},setAnchors:()=>{for(let r of t){let o=n.get(r);if(typeof o==\"object\"&&o.anchor&&(E(o.node)||v(o.node)))o.node.anchor=o.anchor;else{let l=new Error(\"Failed to resolve repeated object (this should not happen)\");throw l.source=r,l}}},sourceObjects:n}}var Tt=g(()=>{C();He()});function pe(s,e,t,n){if(n&&typeof n==\"object\")if(Array.isArray(n))for(let i=0,r=n.length;i<r;++i){let o=n[i],l=pe(s,n,String(i),o);l===void 0?delete n[i]:l!==o&&(n[i]=l)}else if(n instanceof Map)for(let i of Array.from(n.keys())){let r=n.get(i),o=pe(s,n,i,r);o===void 0?n.delete(i):o!==r&&n.set(i,o)}else if(n instanceof Set)for(let i of Array.from(n)){let r=pe(s,n,i,i);r===void 0?n.delete(i):r!==i&&(n.delete(i),n.add(r))}else for(let[i,r]of Object.entries(n)){let o=pe(s,n,i,r);o===void 0?delete n[i]:o!==r&&(n[i]=o)}return s.call(e,t,n)}var Ns=g(()=>{});function K(s,e,t){if(Array.isArray(s))return s.map((n,i)=>K(n,String(i),t));if(s&&typeof s.toJSON==\"function\"){if(!t||!At(s))return s.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=r=>{n.res=r,delete t.onCreate};let i=s.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof s==\"bigint\"&&!t?.keep?Number(s):s}var me=g(()=>{C()});var de,It=g(()=>{Ns();C();me();de=class{constructor(e){Object.defineProperty(this,R,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:i,reviver:r}={}){if(!J(e))throw new TypeError(\"A document argument is required\");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==\"number\"?n:100},l=K(this,\"\",o);if(typeof i==\"function\")for(let{count:a,res:c}of o.anchors.values())i(c,a);return typeof r==\"function\"?pe(r,{\"\":l},\"\",l):l}}});function Lt(s,e,t){if(V(e)){let n=e.resolve(s),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(v(e)){let n=0;for(let i of e.items){let r=Lt(s,i,t);r>n&&(n=r)}return n}else if(I(e)){let n=Lt(s,e.key,t),i=Lt(s,e.value,t);return Math.max(n,i)}return 1}var X,Xe=g(()=>{Tt();He();C();It();me();X=class extends de{constructor(e){super(Nt),this.source=e,Object.defineProperty(this,\"tag\",{set(){throw new Error(\"Alias nodes cannot have tags\")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError(\"Alias resolution is disabled\");let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],G(e,{Node:(r,o)=>{(V(o)||At(o))&&n.push(o)}}),t&&(t.aliasResolveCache=n));let i;for(let r of n){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:r}=t,o=this.resolve(i,t);if(!o){let a=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(a)}let l=n.get(o);if(l||(K(o,null,t),l=n.get(o)),l?.res===void 0){let a=\"This should not happen: Alias anchor was not resolved?\";throw new ReferenceError(a)}if(r>=0&&(l.count+=1,l.aliasCount===0&&(l.aliasCount=Lt(i,o,n)),l.count*l.aliasCount>r)){let a=\"Excessive alias count indicates a resource exhaustion attack\";throw new ReferenceError(a)}return l.res}toString(e,t,n){let i=`*${this.source}`;if(e){if(Et(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(r)}if(e.implicitKey)return`${i} `}return i}}});var Ct,b,M=g(()=>{C();It();me();Ct=s=>!s||typeof s!=\"function\"&&typeof s!=\"object\",b=class extends de{constructor(e){super(U),this.value=e}toJSON(e,t){return t?.keep?this.value:K(this.value,e,t)}toString(){return String(this.value)}};b.BLOCK_FOLDED=\"BLOCK_FOLDED\";b.BLOCK_LITERAL=\"BLOCK_LITERAL\";b.PLAIN=\"PLAIN\";b.QUOTE_DOUBLE=\"QUOTE_DOUBLE\";b.QUOTE_SINGLE=\"QUOTE_SINGLE\"});function Ji(s,e,t){if(e){let n=t.filter(r=>r.tag===e),i=n.find(r=>!r.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(s)&&!n.format)}function ce(s,e,t){if(J(s)&&(s=s.contents),L(s))return s;if(I(s)){let f=t.schema[H].createNode?.(t.schema,null,t);return f.items.push(s),f}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<\"u\"&&s instanceof BigInt)&&(s=s.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:r,schema:o,sourceObjects:l}=t,a;if(n&&s&&typeof s==\"object\"){if(a=l.get(s),a)return a.anchor??(a.anchor=i(s)),new X(a.anchor);a={anchor:null,node:null},l.set(s,a)}e?.startsWith(\"!!\")&&(e=Vi+e.slice(2));let c=Ji(s,e,o.tags);if(!c){if(s&&typeof s.toJSON==\"function\"&&(s=s.toJSON()),!s||typeof s!=\"object\"){let f=new b(s);return a&&(a.node=f),f}c=s instanceof Map?o[H]:Symbol.iterator in Object(s)?o[ae]:o[H]}r&&(r(c),delete t.onTagObj);let p=c?.createNode?c.createNode(t.schema,s,t):typeof c?.nodeClass?.from==\"function\"?c.nodeClass.from(t.schema,s,t):new b(s);return e?p.tag=e:c.default||(p.tag=c.tag),a&&(a.node=p),p}var Vi,ze=g(()=>{Xe();C();M();Vi=\"tag:yaml.org,2002:\"});function Ze(s,e,t){let n=t;for(let i=e.length-1;i>=0;--i){let r=e[i];if(typeof r==\"number\"&&Number.isInteger(r)&&r>=0){let o=[];o[r]=n,n=o}else n=new Map([[r,n]])}return ce(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error(\"This should not happen, please report a bug.\")},schema:s,sourceObjects:new Map})}var Ke,De,vt=g(()=>{ze();C();It();Ke=s=>s==null||typeof s==\"object\"&&!!s[Symbol.iterator]().next().done,De=class extends de{constructor(e,t){super(e),Object.defineProperty(this,\"schema\",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>L(n)||I(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Ke(e))this.add(t);else{let[n,...i]=e,r=this.get(n,!0);if(v(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(n,Ze(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let i=this.get(t,!0);if(v(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,r=this.get(n,!0);return i.length===0?!t&&E(r)?r.value:r:v(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!I(t))return!1;let n=t.value;return n==null||e&&E(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let i=this.get(t,!0);return v(i)?i.hasIn(n):!1}setIn(e,t){let[n,...i]=e;if(i.length===0)this.set(n,t);else{let r=this.get(n,!0);if(v(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(n,Ze(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}});function W(s,e){return/^\\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}var Nn,re,et=g(()=>{Nn=s=>s.replace(/^(?!$)(?: $)?/gm,\"#\");re=(s,e,t)=>s.endsWith(`\n`)?W(t,e):t.includes(`\n`)?`\n`+W(t,e):(s.endsWith(\" \")?\"\":\" \")+t});function st(s,e,t=\"flow\",{indentAtStart:n,lineWidth:i=80,minContentWidth:r=20,onFold:o,onOverflow:l}={}){if(!i||i<0)return s;i<r&&(r=0);let a=Math.max(1+r,1+i-e.length);if(s.length<=a)return s;let c=[],p={},f=i-e.length;typeof n==\"number\"&&(n>i-Math.max(2,r)?c.push(0):f=i-n);let u,d,y=!1,h=-1,m=-1,S=-1;t===$t&&(h=On(s,h,e.length),h!==-1&&(f=h+a));for(let N;N=s[h+=1];){if(t===tt&&N===\"\\\\\"){switch(m=h,s[h+1]){case\"x\":h+=3;break;case\"u\":h+=5;break;case\"U\":h+=9;break;default:h+=1}S=h}if(N===`\n`)t===$t&&(h=On(s,h,e.length)),f=h+e.length+a,u=void 0;else{if(N===\" \"&&d&&d!==\" \"&&d!==`\n`&&d!==\"\t\"){let O=s[h+1];O&&O!==\" \"&&O!==`\n`&&O!==\"\t\"&&(u=h)}if(h>=f)if(u)c.push(u),f=u+a,u=void 0;else if(t===tt){for(;d===\" \"||d===\"\t\";)d=N,N=s[h+=1],y=!0;let O=h>S+1?h-2:m-1;if(p[O])return s;c.push(O),p[O]=!0,f=O+a,u=void 0}else y=!0}d=N}if(y&&l&&l(),c.length===0)return s;o&&o();let k=s.slice(0,c[0]);for(let N=0;N<c.length;++N){let O=c[N],A=c[N+1]||s.length;O===0?k=`\n${e}${s.slice(0,A)}`:(t===tt&&p[O]&&(k+=`${s[O]}\\\\`),k+=`\n${e}${s.slice(O+1,A)}`)}return k}function On(s,e,t){let n=e,i=e+1,r=s[i];for(;r===\" \"||r===\"\t\";)if(e<i+t)r=s[++e];else{do r=s[++e];while(r&&r!==`\n`);n=e,i=e+1,r=s[i]}return n}var Os,$t,tt,An=g(()=>{Os=\"flow\",$t=\"block\",tt=\"quoted\"});function Yi(s,e,t){if(!e||e<0)return!1;let n=e-t,i=s.length;if(i<=n)return!1;for(let r=0,o=0;r<i;++r)if(s[r]===`\n`){if(r-o>n)return!0;if(o=r+1,i-o<=n)return!1}return!0}function nt(s,e){let t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,r=e.indent||(Mt(s)?\" \":\"\"),o=\"\",l=0;for(let a=0,c=t[a];c;c=t[++a])if(c===\" \"&&t[a+1]===\"\\\\\"&&t[a+2]===\"n\"&&(o+=t.slice(l,a)+\"\\\\ \",a+=1,l=a,c=\"\\\\\"),c===\"\\\\\")switch(t[a+1]){case\"u\":{o+=t.slice(l,a);let p=t.substr(a+2,4);switch(p){case\"0000\":o+=\"\\\\0\";break;case\"0007\":o+=\"\\\\a\";break;case\"000b\":o+=\"\\\\v\";break;case\"001b\":o+=\"\\\\e\";break;case\"0085\":o+=\"\\\\N\";break;case\"00a0\":o+=\"\\\\_\";break;case\"2028\":o+=\"\\\\L\";break;case\"2029\":o+=\"\\\\P\";break;default:p.substr(0,2)===\"00\"?o+=\"\\\\x\"+p.substr(2):o+=t.substr(a,6)}a+=5,l=a+1}break;case\"n\":if(n||t[a+2]==='\"'||t.length<i)a+=1;else{for(o+=t.slice(l,a)+`\n\n`;t[a+2]===\"\\\\\"&&t[a+3]===\"n\"&&t[a+4]!=='\"';)o+=`\n`,a+=2;o+=r,t[a+2]===\" \"&&(o+=\"\\\\\"),a+=1,l=a+1}break;default:a+=1}return o=l?o+t.slice(l):t,n?o:st(o,r,tt,Pt(e,!1))}function As(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`\n`)||/[ \\t]\\n|\\n[ \\t]/.test(s))return nt(s,e);let t=e.indent||(Mt(s)?\" \":\"\"),n=\"'\"+s.replace(/'/g,\"''\").replace(/\\n+/g,`$&\n${t}`)+\"'\";return e.implicitKey?n:st(n,t,Os,Pt(e,!1))}function je(s,e){let{singleQuote:t}=e.options,n;if(t===!1)n=nt;else{let i=s.includes('\"'),r=s.includes(\"'\");i&&!r?n=As:r&&!i?n=nt:n=t?As:nt}return n(s,e)}function _t({comment:s,type:e,value:t},n,i,r){let{blockQuote:o,commentString:l,lineWidth:a}=n.options;if(!o||/\\n[\\t ]+$/.test(t))return je(t,n);let c=n.indent||(n.forceBlockIndent||Mt(t)?\" \":\"\"),p=o===\"literal\"?!0:o===\"folded\"||e===b.BLOCK_FOLDED?!1:e===b.BLOCK_LITERAL?!0:!Yi(t,a,c.length);if(!t)return p?`|\n`:`>\n`;let f,u;for(u=t.length;u>0;--u){let A=t[u-1];if(A!==`\n`&&A!==\"\t\"&&A!==\" \")break}let d=t.substring(u),y=d.indexOf(`\n`);y===-1?f=\"-\":t===d||y!==d.length-1?(f=\"+\",r&&r()):f=\"\",d&&(t=t.slice(0,-d.length),d[d.length-1]===`\n`&&(d=d.slice(0,-1)),d=d.replace(Es,`$&${c}`));let h=!1,m,S=-1;for(m=0;m<t.length;++m){let A=t[m];if(A===\" \")h=!0;else if(A===`\n`)S=m;else break}let k=t.substring(0,S<m?S+1:m);k&&(t=t.substring(k.length),k=k.replace(/\\n+/g,`$&${c}`));let O=(h?c?\"2\":\"1\":\"\")+f;if(s&&(O+=\" \"+l(s.replace(/ ?[\\r\\n]+/g,\" \")),i&&i()),!p){let A=t.replace(/\\n+/g,`\n$&`).replace(/(?:^|\\n)([\\t ].*)(?:([\\n\\t ]*)\\n(?![\\n\\t ]))?/g,\"$1$2\").replace(/\\n+/g,`$&${c}`),T=!1,$=Pt(n,!0);o!==\"folded\"&&e!==b.BLOCK_FOLDED&&($.onOverflow=()=>{T=!0});let w=st(`${k}${A}${d}`,c,$t,$);if(!T)return`>${O}\n${c}${w}`}return t=t.replace(/\\n+/g,`$&${c}`),`|${O}\n${c}${k}${t}${d}`}function Qi(s,e,t,n){let{type:i,value:r}=s,{actualString:o,implicitKey:l,indent:a,indentStep:c,inFlow:p}=e;if(l&&r.includes(`\n`)||p&&/[[\\]{},]/.test(r))return je(r,e);if(/^[\\n\\t ,[\\]{}#&*!|>'\"%@`]|^[?-]$|^[?-][ \\t]|[\\n:][ \\t]|[ \\t]\\n|[\\n\\t ]#|[\\n\\t :]$/.test(r))return l||p||!r.includes(`\n`)?je(r,e):_t(s,e,t,n);if(!l&&!p&&i!==b.PLAIN&&r.includes(`\n`))return _t(s,e,t,n);if(Mt(r)){if(a===\"\")return e.forceBlockIndent=!0,_t(s,e,t,n);if(l&&a===c)return je(r,e)}let f=r.replace(/\\n+/g,`$&\n${a}`);if(o){let u=h=>h.default&&h.tag!==\"tag:yaml.org,2002:str\"&&h.test?.test(f),{compat:d,tags:y}=e.doc.schema;if(y.some(u)||d?.some(u))return je(r,e)}return l?f:st(f,a,Os,Pt(e,!1))}function fe(s,e,t,n){let{implicitKey:i,inFlow:r}=e,o=typeof s.value==\"string\"?s:Object.assign({},s,{value:String(s.value)}),{type:l}=s;l!==b.QUOTE_DOUBLE&&/[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f\\u{D800}-\\u{DFFF}]/u.test(o.value)&&(l=b.QUOTE_DOUBLE);let a=p=>{switch(p){case b.BLOCK_FOLDED:case b.BLOCK_LITERAL:return i||r?je(o.value,e):_t(o,e,t,n);case b.QUOTE_DOUBLE:return nt(o.value,e);case b.QUOTE_SINGLE:return As(o.value,e);case b.PLAIN:return Qi(o,e,t,n);default:return null}},c=a(l);if(c===null){let{defaultKeyType:p,defaultStringType:f}=e.options,u=i&&p||f;if(c=a(u),c===null)throw new Error(`Unsupported default string type ${u}`)}return c}var Pt,Mt,Es,it=g(()=>{M();An();Pt=(s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),Mt=s=>/^(%|---|\\.\\.\\.)/m.test(s);try{Es=new RegExp(`(^|(?<!\n))\n+(?!\n|$)`,\"g\")}catch{Es=/\\n+(?!\\n|$)/g}});function Bt(s,e){let t=Object.assign({blockQuote:!0,commentString:Nn,defaultKeyType:null,defaultStringType:\"PLAIN\",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:\"false\",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:\"null\",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:\"true\",verifyAliasOrder:!0},s.schema.toStringOptions,e),n;switch(t.collectionStyle){case\"block\":n=!1;break;case\"flow\":n=!0;break;default:n=null}return{anchors:new Set,doc:s,flowCollectionPadding:t.flowCollectionPadding?\" \":\"\",indent:\"\",indentStep:typeof t.indent==\"number\"?\" \".repeat(t.indent):\" \",inFlow:n,options:t}}function Gi(s,e){if(e.tag){let i=s.filter(r=>r.tag===e.tag);if(i.length>0)return i.find(r=>r.format===e.format)??i[0]}let t,n;if(E(e)){n=e.value;let i=s.filter(r=>r.identify?.(n));if(i.length>1){let r=i.filter(o=>o.test);r.length>0&&(i=r)}t=i.find(r=>r.format===e.format)??i.find(r=>!r.format)}else n=e,t=s.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){let i=n?.constructor?.name??(n===null?\"null\":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}function Wi(s,e,{anchors:t,doc:n}){if(!n.directives)return\"\";let i=[],r=(E(s)||v(s))&&s.anchor;r&&Et(r)&&(t.add(r),i.push(`&${r}`));let o=s.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(\" \")}function ue(s,e,t,n){if(I(s))return s.toString(e,t,n);if(V(s)){if(e.doc.directives)return s.toString(e);if(e.resolvedAliases?.has(s))throw new TypeError(\"Cannot stringify circular structure without alias nodes\");e.resolvedAliases?e.resolvedAliases.add(s):e.resolvedAliases=new Set([s]),s=s.resolve(e.doc)}let i,r=L(s)?s:e.doc.createNode(s,{onTagObj:a=>i=a});i??(i=Gi(e.doc.schema.tags,r));let o=Wi(r,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let l=typeof i.stringify==\"function\"?i.stringify(r,e,t,n):E(r)?fe(r,e,t,n):r.toString(e,t,n);return o?E(r)||l[0]===\"{\"||l[0]===\"[\"?`${o} ${l}`:`${o}\n${e.indent}${l}`:l}var rt=g(()=>{Tt();C();et();it()});function En({key:s,value:e},t,n,i){let{allNullValues:r,doc:o,indent:l,indentStep:a,options:{commentString:c,indentSeq:p,simpleKeys:f}}=t,u=L(s)&&s.comment||null;if(f){if(u)throw new Error(\"With simple keys, key nodes cannot have comments\");if(v(s)||!L(s)&&typeof s==\"object\"){let $=\"With simple keys, collection cannot be used as a key value\";throw new Error($)}}let d=!f&&(!s||u&&e==null&&!t.inFlow||v(s)||(E(s)?s.type===b.BLOCK_FOLDED||s.type===b.BLOCK_LITERAL:typeof s==\"object\"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!d&&(f||!r),indent:l+a});let y=!1,h=!1,m=ue(s,t,()=>y=!0,()=>h=!0);if(!d&&!t.inFlow&&m.length>1024){if(f)throw new Error(\"With simple keys, single line scalar must not span more than 1024 characters\");d=!0}if(t.inFlow){if(r||e==null)return y&&n&&n(),m===\"\"?\"?\":d?`? ${m}`:m}else if(r&&!f||e==null&&d)return m=`? ${m}`,u&&!y?m+=re(m,t.indent,c(u)):h&&i&&i(),m;y&&(u=null),d?(u&&(m+=re(m,t.indent,c(u))),m=`? ${m}\n${l}:`):(m=`${m}:`,u&&(m+=re(m,t.indent,c(u))));let S,k,N;L(e)?(S=!!e.spaceBefore,k=e.commentBefore,N=e.comment):(S=!1,k=null,N=null,e&&typeof e==\"object\"&&(e=o.createNode(e))),t.implicitKey=!1,!d&&!u&&E(e)&&(t.indentAtStart=m.length+1),h=!1,!p&&a.length>=2&&!t.inFlow&&!d&&Q(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let O=!1,A=ue(e,t,()=>O=!0,()=>h=!0),T=\" \";if(u||S||k){if(T=S?`\n`:\"\",k){let $=c(k);T+=`\n${W($,t.indent)}`}A===\"\"&&!t.inFlow?T===`\n`&&N&&(T=`\n\n`):T+=`\n${t.indent}`}else if(!d&&v(e)){let $=A[0],w=A.indexOf(`\n`),B=w!==-1,he=t.inFlow??e.flow??e.items.length===0;if(B||!he){let _e=!1;if(B&&($===\"&\"||$===\"!\")){let D=A.indexOf(\" \");$===\"&\"&&D!==-1&&D<w&&A[D+1]===\"!\"&&(D=A.indexOf(\" \",D+1)),(D===-1||w<D)&&(_e=!0)}_e||(T=`\n${t.indent}`)}}else(A===\"\"||A[0]===`\n`)&&(T=\"\");return m+=T+A,t.inFlow?O&&n&&n():N&&!O?m+=re(m,t.indent,c(N)):h&&i&&i(),m}var Tn=g(()=>{C();M();rt();et()});function Dt(s,e){(s===\"debug\"||s===\"warn\")&&console.warn(e)}var Ts=g(()=>{});function Ls(s,e,t){let n=Ln(s,t);if(Q(n))for(let i of n.items)Is(s,e,i);else if(Array.isArray(n))for(let i of n)Is(s,e,i);else Is(s,e,n)}function Is(s,e,t){let n=Ln(s,t);if(!Y(n))throw new Error(\"Merge sources must be maps or map aliases\");let i=n.toJSON(null,s,Map);for(let[r,o]of i)e instanceof Map?e.has(r)||e.set(r,o):e instanceof Set?e.add(r):Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Ln(s,e){return s&&V(e)?e.resolve(s.doc,s):e}var Kt,z,In,jt=g(()=>{C();M();Kt=\"<<\",z={identify:s=>s===Kt||typeof s==\"symbol\"&&s.description===Kt,default:\"key\",tag:\"tag:yaml.org,2002:merge\",test:/^<<$/,resolve:()=>Object.assign(new b(Symbol(Kt)),{addToJSMap:Ls}),stringify:()=>Kt},In=(s,e)=>(z.identify(e)||E(e)&&(!e.type||e.type===b.PLAIN)&&z.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===z.tag&&t.default)});function qt(s,e,{key:t,value:n}){if(L(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(In(s,t))Ls(s,e,n);else{let i=K(t,\"\",s);if(e instanceof Map)e.set(i,K(n,i,s));else if(e instanceof Set)e.add(i);else{let r=Hi(t,i,s),o=K(n,r,s);r in e?Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[r]=o}}return e}function Hi(s,e,t){if(e===null)return\"\";if(typeof e!=\"object\")return String(e);if(L(s)&&t?.doc){let n=Bt(t.doc,{});n.anchors=new Set;for(let r of t.anchors.keys())n.anchors.add(r.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=s.toString(n);if(!t.mapKeyWarned){let r=JSON.stringify(i);r.length>40&&(r=r.substring(0,36)+'...\"'),Dt(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${r}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}var Cs=g(()=>{Ts();jt();rt();C();me()});function qe(s,e,t){let n=ce(s,void 0,t),i=ce(e,void 0,t);return new _(n,i)}var _,ge=g(()=>{ze();Tn();Cs();C();_=class s{constructor(e,t=null){Object.defineProperty(this,R,{value:bs}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return L(t)&&(t=t.clone(e)),L(n)&&(n=n.clone(e)),new s(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return qt(t,n,this)}toString(e,t,n){return e?.doc?En(this,e,t,n):JSON.stringify(this)}}});function Ft(s,e,t){return(e.inFlow??s.flow?zi:Xi)(s,e,t)}function Xi({comment:s,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:r,onChompKeep:o,onComment:l}){let{indent:a,options:{commentString:c}}=t,p=Object.assign({},t,{indent:r,type:null}),f=!1,u=[];for(let y=0;y<e.length;++y){let h=e[y],m=null;if(L(h))!f&&h.spaceBefore&&u.push(\"\"),Rt(t,u,h.commentBefore,f),h.comment&&(m=h.comment);else if(I(h)){let k=L(h.key)?h.key:null;k&&(!f&&k.spaceBefore&&u.push(\"\"),Rt(t,u,k.commentBefore,f))}f=!1;let S=ue(h,p,()=>m=null,()=>f=!0);m&&(S+=re(S,r,c(m))),f&&m&&(f=!1),u.push(n+S)}let d;if(u.length===0)d=i.start+i.end;else{d=u[0];for(let y=1;y<u.length;++y){let h=u[y];d+=h?`\n${a}${h}`:`\n`}}return s?(d+=`\n`+W(c(s),a),l&&l()):f&&o&&o(),d}function zi({items:s},e,{flowChars:t,itemIndent:n}){let{indent:i,indentStep:r,flowCollectionPadding:o,options:{commentString:l}}=e;n+=r;let a=Object.assign({},e,{indent:n,inFlow:!0,type:null}),c=!1,p=0,f=[];for(let y=0;y<s.length;++y){let h=s[y],m=null;if(L(h))h.spaceBefore&&f.push(\"\"),Rt(e,f,h.commentBefore,!1),h.comment&&(m=h.comment);else if(I(h)){let k=L(h.key)?h.key:null;k&&(k.spaceBefore&&f.push(\"\"),Rt(e,f,k.commentBefore,!1),k.comment&&(c=!0));let N=L(h.value)?h.value:null;N?(N.comment&&(m=N.comment),N.commentBefore&&(c=!0)):h.value==null&&k?.comment&&(m=k.comment)}m&&(c=!0);let S=ue(h,a,()=>m=null);c||(c=f.length>p||S.includes(`\n`)),y<s.length-1?S+=\",\":e.options.trailingComma&&(e.options.lineWidth>0&&(c||(c=f.reduce((k,N)=>k+N.length+2,2)+(S.length+2)>e.options.lineWidth)),c&&(S+=\",\")),m&&(S+=re(S,n,l(m))),f.push(S),p=f.length}let{start:u,end:d}=t;if(f.length===0)return u+d;if(!c){let y=f.reduce((h,m)=>h+m.length+2,2);c=e.options.lineWidth>0&&y>e.options.lineWidth}if(c){let y=u;for(let h of f)y+=h?`\n${r}${i}${h}`:`\n`;return`${y}\n${i}${d}`}else return`${u}${o}${f.join(\" \")}${o}${d}`}function Rt({indent:s,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\\n+/,\"\")),n){let r=W(e(n),s);t.push(r.trimStart())}}var vs=g(()=>{C();rt();et()});function ye(s,e){let t=E(e)?e.value:e;for(let n of s)if(I(n)&&(n.key===e||n.key===t||E(n.key)&&n.key.value===t))return n}var P,be=g(()=>{vs();Cs();vt();C();ge();M();P=class extends De{static get tagName(){return\"tag:yaml.org,2002:map\"}constructor(e){super(H,e),this.items=[]}static from(e,t,n){let{keepUndefined:i,replacer:r}=n,o=new this(e),l=(a,c)=>{if(typeof r==\"function\")c=r.call(t,a,c);else if(Array.isArray(r)&&!r.includes(a))return;(c!==void 0||i)&&o.items.push(qe(a,c,n))};if(t instanceof Map)for(let[a,c]of t)l(a,c);else if(t&&typeof t==\"object\")for(let a of Object.keys(t))l(a,t[a]);return typeof e.sortMapEntries==\"function\"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;I(e)?n=e:!e||typeof e!=\"object\"||!(\"key\"in e)?n=new _(e,e?.value):n=new _(e.key,e.value);let i=ye(this.items,n.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);E(i.value)&&Ct(n.value)?i.value.value=n.value:i.value=n.value}else if(r){let o=this.items.findIndex(l=>r(n,l)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let t=ye(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let i=ye(this.items,e)?.value;return(!t&&E(i)?i.value:i)??void 0}has(e){return!!ye(this.items,e)}set(e,t){this.add(new _(e,t),!0)}toJSON(e,t,n){let i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let r of this.items)qt(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!I(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ft(this,e,{blockItemPrefix:\"\",flowChars:{start:\"{\",end:\"}\"},itemIndent:e.indent||\"\",onChompKeep:n,onComment:t})}}});var Z,Re=g(()=>{C();be();Z={collection:\"map\",default:!0,nodeClass:P,tag:\"tag:yaml.org,2002:map\",resolve(s,e){return Y(s)||e(\"Expected a mapping for this tag\"),s},createNode:(s,e,t)=>P.from(s,e,t)}});function xt(s){let e=E(s)?s.value:s;return e&&typeof e==\"string\"&&(e=Number(e)),typeof e==\"number\"&&Number.isInteger(e)&&e>=0?e:null}var j,we=g(()=>{ze();vs();vt();C();M();me();j=class extends De{static get tagName(){return\"tag:yaml.org,2002:seq\"}constructor(e){super(ae,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=xt(e);return typeof t!=\"number\"?!1:this.items.splice(t,1).length>0}get(e,t){let n=xt(e);if(typeof n!=\"number\")return;let i=this.items[n];return!t&&E(i)?i.value:i}has(e){let t=xt(e);return typeof t==\"number\"&&t<this.items.length}set(e,t){let n=xt(e);if(typeof n!=\"number\")throw new Error(`Expected a valid index, not ${e}.`);let i=this.items[n];E(i)&&Ct(t)?i.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let i=0;for(let r of this.items)n.push(K(r,String(i++),t));return n}toString(e,t,n){return e?Ft(this,e,{blockItemPrefix:\"- \",flowChars:{start:\"[\",end:\"]\"},itemIndent:(e.indent||\"\")+\" \",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let l of t){if(typeof i==\"function\"){let a=t instanceof Set?l:String(o++);l=i.call(t,a,l)}r.items.push(ce(l,void 0,n))}}return r}}});var ee,Fe=g(()=>{C();we();ee={collection:\"seq\",default:!0,nodeClass:j,tag:\"tag:yaml.org,2002:seq\",resolve(s,e){return Q(s)||e(\"Expected a sequence for this tag\"),s},createNode:(s,e,t)=>j.from(s,e,t)}});var Se,ot=g(()=>{it();Se={identify:s=>typeof s==\"string\",default:!0,tag:\"tag:yaml.org,2002:str\",resolve:s=>s,stringify(s,e,t,n){return e=Object.assign({actualString:!0},e),fe(s,e,t,n)}}});var Te,Ut=g(()=>{M();Te={identify:s=>s==null,createNode:()=>new b(null),default:!0,tag:\"tag:yaml.org,2002:null\",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new b(null),stringify:({source:s},e)=>typeof s==\"string\"&&Te.test.test(s)?s:e.options.nullStr}});var lt,$s=g(()=>{M();lt={identify:s=>typeof s==\"boolean\",default:!0,tag:\"tag:yaml.org,2002:bool\",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:s=>new b(s[0]===\"t\"||s[0]===\"T\"),stringify({source:s,value:e},t){if(s&&lt.test.test(s)){let n=s[0]===\"t\"||s[0]===\"T\";if(e===n)return s}return e?t.options.trueStr:t.options.falseStr}}});function q({format:s,minFractionDigits:e,tag:t,value:n}){if(typeof n==\"bigint\")return String(n);let i=typeof n==\"number\"?n:Number(n);if(!isFinite(i))return isNaN(i)?\".nan\":i<0?\"-.inf\":\".inf\";let r=Object.is(n,-0)?\"-0\":JSON.stringify(n);if(!s&&e&&(!t||t===\"tag:yaml.org,2002:float\")&&/^-?\\d/.test(r)&&!r.includes(\"e\")){let o=r.indexOf(\".\");o<0&&(o=r.length,r+=\".\");let l=e-(r.length-o-1);for(;l-- >0;)r+=\"0\"}return r}var xe=g(()=>{});var Vt,Jt,Yt,_s=g(()=>{M();xe();Vt={identify:s=>typeof s==\"number\",default:!0,tag:\"tag:yaml.org,2002:float\",test:/^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,resolve:s=>s.slice(-3).toLowerCase()===\"nan\"?NaN:s[0]===\"-\"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:q},Jt={identify:s=>typeof s==\"number\",default:!0,tag:\"tag:yaml.org,2002:float\",format:\"EXP\",test:/^[-+]?(?:\\.[0-9]+|[0-9]+(?:\\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:s=>parseFloat(s),stringify(s){let e=Number(s.value);return isFinite(e)?e.toExponential():q(s)}},Yt={identify:s=>typeof s==\"number\",default:!0,tag:\"tag:yaml.org,2002:float\",test:/^[-+]?(?:\\.[0-9]+|[0-9]+\\.[0-9]*)$/,resolve(s){let e=new b(parseFloat(s)),t=s.indexOf(\".\");return t!==-1&&s[s.length-1]===\"0\"&&(e.minFractionDigits=s.length-t-1),e},stringify:q}});function Cn(s,e,t){let{value:n}=s;return Qt(n)&&n>=0?t+n.toString(e):q(s)}var Qt,Ps,Gt,Wt,Ht,Ms=g(()=>{xe();Qt=s=>typeof s==\"bigint\"||Number.isInteger(s),Ps=(s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t);Gt={identify:s=>Qt(s)&&s>=0,default:!0,tag:\"tag:yaml.org,2002:int\",format:\"OCT\",test:/^0o[0-7]+$/,resolve:(s,e,t)=>Ps(s,2,8,t),stringify:s=>Cn(s,8,\"0o\")},Wt={identify:Qt,default:!0,tag:\"tag:yaml.org,2002:int\",test:/^[-+]?[0-9]+$/,resolve:(s,e,t)=>Ps(s,0,10,t),stringify:q},Ht={identify:s=>Qt(s)&&s>=0,default:!0,tag:\"tag:yaml.org,2002:int\",format:\"HEX\",test:/^0x[0-9a-fA-F]+$/,resolve:(s,e,t)=>Ps(s,2,16,t),stringify:s=>Cn(s,16,\"0x\")}});var vn,$n=g(()=>{Re();Ut();Fe();ot();$s();_s();Ms();vn=[Z,ee,Se,Te,lt,Gt,Wt,Ht,Vt,Jt,Yt]});function _n(s){return typeof s==\"bigint\"||Number.isInteger(s)}var Xt,Zi,er,Pn,Mn=g(()=>{M();Re();Fe();Xt=({value:s})=>JSON.stringify(s),Zi=[{identify:s=>typeof s==\"string\",default:!0,tag:\"tag:yaml.org,2002:str\",resolve:s=>s,stringify:Xt},{identify:s=>s==null,createNode:()=>new b(null),default:!0,tag:\"tag:yaml.org,2002:null\",test:/^null$/,resolve:()=>null,stringify:Xt},{identify:s=>typeof s==\"boolean\",default:!0,tag:\"tag:yaml.org,2002:bool\",test:/^true$|^false$/,resolve:s=>s===\"true\",stringify:Xt},{identify:_n,default:!0,tag:\"tag:yaml.org,2002:int\",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(s,e,{intAsBigInt:t})=>t?BigInt(s):parseInt(s,10),stringify:({value:s})=>_n(s)?s.toString():JSON.stringify(s)},{identify:s=>typeof s==\"number\",default:!0,tag:\"tag:yaml.org,2002:float\",test:/^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:s=>parseFloat(s),stringify:Xt}],er={default:!0,tag:\"\",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},Pn=[Z,ee].concat(Zi,er)});var at,Bs=g(()=>{M();it();at={identify:s=>s instanceof Uint8Array,default:!1,tag:\"tag:yaml.org,2002:binary\",resolve(s,e){if(typeof atob==\"function\"){let t=atob(s.replace(/[\\n\\r]/g,\"\")),n=new Uint8Array(t.length);for(let i=0;i<t.length;++i)n[i]=t.charCodeAt(i);return n}else return e(\"This environment does not support reading binary tags; either Buffer or atob is required\"),s},stringify({comment:s,type:e,value:t},n,i,r){if(!t)return\"\";let o=t,l;if(typeof btoa==\"function\"){let a=\"\";for(let c=0;c<o.length;++c)a+=String.fromCharCode(o[c]);l=btoa(a)}else throw new Error(\"This environment does not support writing binary tags; either Buffer or btoa is required\");if(e??(e=b.BLOCK_LITERAL),e!==b.QUOTE_DOUBLE){let a=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),c=Math.ceil(l.length/a),p=new Array(c);for(let f=0,u=0;f<c;++f,u+=a)p[f]=l.substr(u,a);l=p.join(e===b.BLOCK_LITERAL?`\n`:\" \")}return fe({comment:s,type:e,value:l},n,i,r)}}});function Ds(s,e){if(Q(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!I(n)){if(Y(n)){n.items.length>1&&e(\"Each pair must have its own sequence indicator\");let i=n.items[0]||new _(new b(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}\n${i.key.commentBefore}`:n.commentBefore),n.comment){let r=i.value??i.key;r.comment=r.comment?`${n.comment}\n${r.comment}`:n.comment}n=i}s.items[t]=I(n)?n:new _(n)}}else e(\"Expected a sequence for this tag\");return s}function Ks(s,e,t){let{replacer:n}=t,i=new j(s);i.tag=\"tag:yaml.org,2002:pairs\";let r=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n==\"function\"&&(o=n.call(e,String(r++),o));let l,a;if(Array.isArray(o))if(o.length===2)l=o[0],a=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let c=Object.keys(o);if(c.length===1)l=c[0],a=o[l];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else l=o;i.items.push(qe(l,a,t))}return i}var ct,zt=g(()=>{C();ge();M();we();ct={collection:\"seq\",default:!1,tag:\"tag:yaml.org,2002:pairs\",resolve:Ds,createNode:Ks}});var Ue,ft,js=g(()=>{C();me();be();we();zt();Ue=class s extends j{constructor(){super(),this.add=P.prototype.add.bind(this),this.delete=P.prototype.delete.bind(this),this.get=P.prototype.get.bind(this),this.has=P.prototype.has.bind(this),this.set=P.prototype.set.bind(this),this.tag=s.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let i of this.items){let r,o;if(I(i)?(r=K(i.key,\"\",t),o=K(i.value,r,t)):r=K(i,\"\",t),n.has(r))throw new Error(\"Ordered maps must not include duplicate keys\");n.set(r,o)}return n}static from(e,t,n){let i=Ks(e,t,n),r=new this;return r.items=i.items,r}};Ue.tag=\"tag:yaml.org,2002:omap\";ft={collection:\"seq\",identify:s=>s instanceof Map,nodeClass:Ue,default:!1,tag:\"tag:yaml.org,2002:omap\",resolve(s,e){let t=Ds(s,e),n=[];for(let{key:i}of t.items)E(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new Ue,t)},createNode:(s,e,t)=>Ue.from(s,e,t)}});function Bn({value:s,source:e},t){return e&&(s?qs:Rs).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}var qs,Rs,Dn=g(()=>{M();qs={identify:s=>s===!0,default:!0,tag:\"tag:yaml.org,2002:bool\",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new b(!0),stringify:Bn},Rs={identify:s=>s===!1,default:!0,tag:\"tag:yaml.org,2002:bool\",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new b(!1),stringify:Bn}});var Kn,jn,qn,Rn=g(()=>{M();xe();Kn={identify:s=>typeof s==\"number\",default:!0,tag:\"tag:yaml.org,2002:float\",test:/^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,resolve:s=>s.slice(-3).toLowerCase()===\"nan\"?NaN:s[0]===\"-\"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:q},jn={identify:s=>typeof s==\"number\",default:!0,tag:\"tag:yaml.org,2002:float\",format:\"EXP\",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:s=>parseFloat(s.replace(/_/g,\"\")),stringify(s){let e=Number(s.value);return isFinite(e)?e.toExponential():q(s)}},qn={identify:s=>typeof s==\"number\",default:!0,tag:\"tag:yaml.org,2002:float\",test:/^[-+]?(?:[0-9][0-9_]*)?\\.[0-9_]*$/,resolve(s){let e=new b(parseFloat(s.replace(/_/g,\"\"))),t=s.indexOf(\".\");if(t!==-1){let n=s.substring(t+1).replace(/_/g,\"\");n[n.length-1]===\"0\"&&(e.minFractionDigits=n.length)}return e},stringify:q}});function Zt(s,e,t,{intAsBigInt:n}){let i=s[0];if((i===\"-\"||i===\"+\")&&(e+=1),s=s.substring(e).replace(/_/g,\"\"),n){switch(t){case 2:s=`0b${s}`;break;case 8:s=`0o${s}`;break;case 16:s=`0x${s}`;break}let o=BigInt(s);return i===\"-\"?BigInt(-1)*o:o}let r=parseInt(s,t);return i===\"-\"?-1*r:r}function Fs(s,e,t){let{value:n}=s;if(ut(n)){let i=n.toString(e);return n<0?\"-\"+t+i.substr(1):t+i}return q(s)}var ut,Fn,xn,Un,Vn,Jn=g(()=>{xe();ut=s=>typeof s==\"bigint\"||Number.isInteger(s);Fn={identify:ut,default:!0,tag:\"tag:yaml.org,2002:int\",format:\"BIN\",test:/^[-+]?0b[0-1_]+$/,resolve:(s,e,t)=>Zt(s,2,2,t),stringify:s=>Fs(s,2,\"0b\")},xn={identify:ut,default:!0,tag:\"tag:yaml.org,2002:int\",format:\"OCT\",test:/^[-+]?0[0-7_]+$/,resolve:(s,e,t)=>Zt(s,1,8,t),stringify:s=>Fs(s,8,\"0\")},Un={identify:ut,default:!0,tag:\"tag:yaml.org,2002:int\",test:/^[-+]?[0-9][0-9_]*$/,resolve:(s,e,t)=>Zt(s,0,10,t),stringify:q},Vn={identify:ut,default:!0,tag:\"tag:yaml.org,2002:int\",format:\"HEX\",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(s,e,t)=>Zt(s,2,16,t),stringify:s=>Fs(s,16,\"0x\")}});var Ve,ht,xs=g(()=>{C();ge();be();Ve=class s extends P{constructor(e){super(e),this.tag=s.tag}add(e){let t;I(e)?t=e:e&&typeof e==\"object\"&&\"key\"in e&&\"value\"in e&&e.value===null?t=new _(e.key,null):t=new _(e,null),ye(this.items,t.key)||this.items.push(t)}get(e,t){let n=ye(this.items,e);return!t&&I(n)?E(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=\"boolean\")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=ye(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new _(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error(\"Set items must all have null values\")}static from(e,t,n){let{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i==\"function\"&&(o=i.call(t,o,o)),r.items.push(qe(o,null,n));return r}};Ve.tag=\"tag:yaml.org,2002:set\";ht={collection:\"map\",identify:s=>s instanceof Set,nodeClass:Ve,default:!1,tag:\"tag:yaml.org,2002:set\",createNode:(s,e,t)=>Ve.from(s,e,t),resolve(s,e){if(Y(s)){if(s.hasAllNullValues(!0))return Object.assign(new Ve,s);e(\"Set items must all have null values\")}else e(\"Expected a mapping for this tag\");return s}}});function Us(s,e){let t=s[0],n=t===\"-\"||t===\"+\"?s.substring(1):s,i=o=>e?BigInt(o):Number(o),r=n.replace(/_/g,\"\").split(\":\").reduce((o,l)=>o*i(60)+i(l),i(0));return t===\"-\"?i(-1)*r:r}function Yn(s){let{value:e}=s,t=o=>o;if(typeof e==\"bigint\")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return q(s);let n=\"\";e<0&&(n=\"-\",e*=t(-1));let i=t(60),r=[e%i];return e<60?r.unshift(0):(e=(e-r[0])/i,r.unshift(e%i),e>=60&&(e=(e-r[0])/i,r.unshift(e))),n+r.map(o=>String(o).padStart(2,\"0\")).join(\":\").replace(/000000\\d*$/,\"\")}var es,ts,Je,Vs=g(()=>{xe();es={identify:s=>typeof s==\"bigint\"||Number.isInteger(s),default:!0,tag:\"tag:yaml.org,2002:int\",format:\"TIME\",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(s,e,{intAsBigInt:t})=>Us(s,t),stringify:Yn},ts={identify:s=>typeof s==\"number\",default:!0,tag:\"tag:yaml.org,2002:float\",format:\"TIME\",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*$/,resolve:s=>Us(s,!1),stringify:Yn},Je={identify:s=>s instanceof Date,default:!0,tag:\"tag:yaml.org,2002:timestamp\",test:RegExp(\"^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\\\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\\\.[0-9]+)?)(?:[ \\\\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$\"),resolve(s){let e=s.match(Je.test);if(!e)throw new Error(\"!!timestamp expects a date, starting with yyyy-mm-dd\");let[,t,n,i,r,o,l]=e.map(Number),a=e[7]?Number((e[7]+\"00\").substr(1,3)):0,c=Date.UTC(t,n-1,i,r||0,o||0,l||0,a),p=e[8];if(p&&p!==\"Z\"){let f=Us(p,!1);Math.abs(f)<30&&(f*=60),c-=6e4*f}return new Date(c)},stringify:({value:s})=>s?.toISOString().replace(/(T00:00:00)?\\.000Z$/,\"\")??\"\"}});var Js,Qn=g(()=>{Re();Ut();Fe();ot();Bs();Dn();Rn();Jn();jt();js();zt();xs();Vs();Js=[Z,ee,Se,Te,qs,Rs,Fn,xn,Un,Vn,Kn,jn,qn,at,z,ft,ct,ht,es,ts,Je]});function ss(s,e,t){let n=Gn.get(e);if(n&&!s)return t&&!n.includes(z)?n.concat(z):n.slice();let i=n;if(!i)if(Array.isArray(s))i=[];else{let r=Array.from(Gn.keys()).filter(o=>o!==\"yaml11\").map(o=>JSON.stringify(o)).join(\", \");throw new Error(`Unknown schema \"${e}\"; use one of ${r} or define customTags array`)}if(Array.isArray(s))for(let r of s)i=i.concat(r);else typeof s==\"function\"&&(i=s(i.slice()));return t&&(i=i.concat(z)),i.reduce((r,o)=>{let l=typeof o==\"string\"?Wn[o]:o;if(!l){let a=JSON.stringify(o),c=Object.keys(Wn).map(p=>JSON.stringify(p)).join(\", \");throw new Error(`Unknown custom tag ${a}; use one of ${c}`)}return r.includes(l)||r.push(l),r},[])}var Gn,Wn,Hn,Xn=g(()=>{Re();Ut();Fe();ot();$s();_s();Ms();$n();Mn();Bs();jt();js();zt();Qn();xs();Vs();Gn=new Map([[\"core\",vn],[\"failsafe\",[Z,ee,Se]],[\"json\",Pn],[\"yaml11\",Js],[\"yaml-1.1\",Js]]),Wn={binary:at,bool:lt,float:Yt,floatExp:Jt,floatNaN:Vt,floatTime:ts,int:Wt,intHex:Ht,intOct:Gt,intTime:es,map:Z,merge:z,null:Te,omap:ft,pairs:ct,seq:ee,set:ht,timestamp:Je},Hn={\"tag:yaml.org,2002:binary\":at,\"tag:yaml.org,2002:merge\":z,\"tag:yaml.org,2002:omap\":ft,\"tag:yaml.org,2002:pairs\":ct,\"tag:yaml.org,2002:set\":ht,\"tag:yaml.org,2002:timestamp\":Je}});var tr,Ie,Ys=g(()=>{C();Re();Fe();ot();Xn();tr=(s,e)=>s.key<e.key?-1:s.key>e.key?1:0,Ie=class s{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:l}){this.compat=Array.isArray(e)?ss(e,\"compat\"):e?ss(null,e):null,this.name=typeof r==\"string\"&&r||\"core\",this.knownTags=i?Hn:{},this.tags=ss(t,this.name,n),this.toStringOptions=l??null,Object.defineProperty(this,H,{value:Z}),Object.defineProperty(this,U,{value:Se}),Object.defineProperty(this,ae,{value:ee}),this.sortMapEntries=typeof o==\"function\"?o:o===!0?tr:null}clone(){let e=Object.create(s.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}});function zn(s,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&s.directives){let a=s.directives.toString(s);a?(t.push(a),n=!0):s.directives.docStart&&(n=!0)}n&&t.push(\"---\");let i=Bt(s,e),{commentString:r}=i.options;if(s.commentBefore){t.length!==1&&t.unshift(\"\");let a=r(s.commentBefore);t.unshift(W(a,\"\"))}let o=!1,l=null;if(s.contents){if(L(s.contents)){if(s.contents.spaceBefore&&n&&t.push(\"\"),s.contents.commentBefore){let p=r(s.contents.commentBefore);t.push(W(p,\"\"))}i.forceBlockIndent=!!s.comment,l=s.contents.comment}let a=l?void 0:()=>o=!0,c=ue(s.contents,i,()=>l=null,a);l&&(c+=re(c,\"\",r(l))),(c[0]===\"|\"||c[0]===\">\")&&t[t.length-1]===\"---\"?t[t.length-1]=`--- ${c}`:t.push(c)}else t.push(ue(s.contents,i));if(s.directives?.docEnd)if(s.comment){let a=r(s.comment);a.includes(`\n`)?(t.push(\"...\"),t.push(W(a,\"\"))):t.push(`... ${a}`)}else t.push(\"...\");else{let a=s.comment;a&&o&&(a=a.replace(/^\\n+/,\"\")),a&&((!o||l)&&t[t.length-1]!==\"\"&&t.push(\"\"),t.push(W(r(a),\"\")))}return t.join(`\n`)+`\n`}var Zn=g(()=>{C();rt();et()});function Ye(s){if(v(s))return!0;throw new Error(\"Expected a YAML collection as document contents\")}var te,pt=g(()=>{Xe();vt();C();ge();me();Ys();Zn();Tt();Ns();ze();ws();te=class s{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,R,{value:Ot});let i=null;typeof t==\"function\"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let r=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:\"warn\",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:\"1.2\"},n);this.options=r;let{version:o}=r;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new ie({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(s.prototype,{[R]:{value:Ot}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=L(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ye(this.contents)&&this.contents.add(e)}addIn(e,t){Ye(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=Ss(this);e.anchor=!t||n.has(t)?ks(t||\"a\",n):t}return new X(e.anchor)}createNode(e,t,n){let i;if(typeof t==\"function\")e=t.call({\"\":e},\"\",e),i=t;else if(Array.isArray(t)){let m=k=>typeof k==\"number\"||k instanceof String||k instanceof Number,S=t.filter(m).map(String);S.length>0&&(t=t.concat(S)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:r,anchorPrefix:o,flow:l,keepUndefined:a,onTagObj:c,tag:p}=n??{},{onAnchor:f,setAnchors:u,sourceObjects:d}=kn(this,o||\"a\"),y={aliasDuplicateObjects:r??!0,keepUndefined:a??!1,onAnchor:f,onTagObj:c,replacer:i,schema:this.schema,sourceObjects:d},h=ce(e,p,y);return l&&v(h)&&(h.flow=!0),u(),h}createPair(e,t,n={}){let i=this.createNode(e,null,n),r=this.createNode(t,null,n);return new _(i,r)}delete(e){return Ye(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ke(e)?this.contents==null?!1:(this.contents=null,!0):Ye(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return v(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ke(e)?!t&&E(this.contents)?this.contents.value:this.contents:v(this.contents)?this.contents.getIn(e,t):void 0}has(e){return v(this.contents)?this.contents.has(e):!1}hasIn(e){return Ke(e)?this.contents!==void 0:v(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ze(this.schema,[e],t):Ye(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ke(e)?this.contents=t:this.contents==null?this.contents=Ze(this.schema,Array.from(e),t):Ye(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==\"number\"&&(e=String(e));let n;switch(e){case\"1.1\":this.directives?this.directives.yaml.version=\"1.1\":this.directives=new ie({version:\"1.1\"}),n={resolveKnownTags:!1,schema:\"yaml-1.1\"};break;case\"1.2\":case\"next\":this.directives?this.directives.yaml.version=e:this.directives=new ie({version:e}),n={resolveKnownTags:!0,schema:\"core\"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Ie(Object.assign(n,t));else throw new Error(\"With a null YAML version, the { schema: Schema } option is required\")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:o}={}){let l={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i==\"number\"?i:100},a=K(this.contents,t??\"\",l);if(typeof r==\"function\")for(let{count:c,res:p}of l.anchors.values())r(p,c);return typeof o==\"function\"?pe(o,{\"\":a},\"\",a):a}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error(\"Document with errors cannot be stringified\");if(\"indent\"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`\"indent\" option must be a positive integer, not ${t}`)}return zn(this,e)}}});var Le,x,Ce,mt,dt=g(()=>{Le=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},x=class extends Le{constructor(e,t,n){super(\"YAMLParseError\",e,t,n)}},Ce=class extends Le{constructor(e,t,n){super(\"YAMLWarning\",e,t,n)}},mt=(s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(l=>e.linePos(l));let{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let r=i-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\\n\\r]+$/,\"\");if(r>=60&&o.length>80){let l=Math.min(r-39,o.length-79);o=\"\\u2026\"+o.substring(l),r-=l-1}if(o.length>80&&(o=o.substring(0,79)+\"\\u2026\"),n>1&&/^ *$/.test(o.substring(0,r))){let l=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);l.length>80&&(l=l.substring(0,79)+`\\u2026\n`),o=l+o}if(/[^ ]/.test(o)){let l=1,a=t.linePos[1];a?.line===n&&a.col>i&&(l=Math.max(1,Math.min(a.col-i,80-r)));let c=\" \".repeat(r)+\"^\".repeat(l);t.message+=`:\n\n${o}\n${c}\n`}}});function oe(s,{flow:e,indicator:t,next:n,offset:i,onError:r,parentIndent:o,startOnNewline:l}){let a=!1,c=l,p=l,f=\"\",u=\"\",d=!1,y=!1,h=null,m=null,S=null,k=null,N=null,O=null,A=null;for(let w of s)switch(y&&(w.type!==\"space\"&&w.type!==\"newline\"&&w.type!==\"comma\"&&r(w.offset,\"MISSING_CHAR\",\"Tags and anchors must be separated from the next token by white space\"),y=!1),h&&(c&&w.type!==\"comment\"&&w.type!==\"newline\"&&r(h,\"TAB_AS_INDENT\",\"Tabs are not allowed as indentation\"),h=null),w.type){case\"space\":!e&&(t!==\"doc-start\"||n?.type!==\"flow-collection\")&&w.source.includes(\"\t\")&&(h=w),p=!0;break;case\"comment\":{p||r(w,\"MISSING_CHAR\",\"Comments must be separated from other tokens by white space characters\");let B=w.source.substring(1)||\" \";f?f+=u+B:f=B,u=\"\",c=!1;break}case\"newline\":c?f?f+=w.source:(!O||t!==\"seq-item-ind\")&&(a=!0):u+=w.source,c=!0,d=!0,(m||S)&&(k=w),p=!0;break;case\"anchor\":m&&r(w,\"MULTIPLE_ANCHORS\",\"A node can have at most one anchor\"),w.source.endsWith(\":\")&&r(w.offset+w.source.length-1,\"BAD_ALIAS\",\"Anchor ending in : is ambiguous\",!0),m=w,A??(A=w.offset),c=!1,p=!1,y=!0;break;case\"tag\":{S&&r(w,\"MULTIPLE_TAGS\",\"A node can have at most one tag\"),S=w,A??(A=w.offset),c=!1,p=!1,y=!0;break}case t:(m||S)&&r(w,\"BAD_PROP_ORDER\",`Anchors and tags must be after the ${w.source} indicator`),O&&r(w,\"UNEXPECTED_TOKEN\",`Unexpected ${w.source} in ${e??\"collection\"}`),O=w,c=t===\"seq-item-ind\"||t===\"explicit-key-ind\",p=!1;break;case\"comma\":if(e){N&&r(w,\"UNEXPECTED_TOKEN\",`Unexpected , in ${e}`),N=w,c=!1,p=!1;break}default:r(w,\"UNEXPECTED_TOKEN\",`Unexpected ${w.type} token`),c=!1,p=!1}let T=s[s.length-1],$=T?T.offset+T.source.length:i;return y&&n&&n.type!==\"space\"&&n.type!==\"newline\"&&n.type!==\"comma\"&&(n.type!==\"scalar\"||n.source!==\"\")&&r(n.offset,\"MISSING_CHAR\",\"Tags and anchors must be separated from the next token by white space\"),h&&(c&&h.indent<=o||n?.type===\"block-map\"||n?.type===\"block-seq\")&&r(h,\"TAB_AS_INDENT\",\"Tabs are not allowed as indentation\"),{comma:N,found:O,spaceBefore:a,comment:f,hasNewline:d,anchor:m,tag:S,newlineAfterProp:k,end:$,start:A??$}}var gt=g(()=>{});function ke(s){if(!s)return null;switch(s.type){case\"alias\":case\"scalar\":case\"double-quoted-scalar\":case\"single-quoted-scalar\":if(s.source.includes(`\n`))return!0;if(s.end){for(let e of s.end)if(e.type===\"newline\")return!0}return!1;case\"flow-collection\":for(let e of s.items){for(let t of e.start)if(t.type===\"newline\")return!0;if(e.sep){for(let t of e.sep)if(t.type===\"newline\")return!0}if(ke(e.key)||ke(e.value))return!0}return!1;default:return!0}}var ns=g(()=>{});function yt(s,e,t){if(e?.type===\"flow-collection\"){let n=e.end[0];n.indent===s&&(n.source===\"]\"||n.source===\"}\")&&ke(e)&&t(n,\"BAD_INDENT\",\"Flow end indicator should be more indented than parent\",!0)}}var Qs=g(()=>{ns()});function is(s,e,t){let{uniqueKeys:n}=s.options;if(n===!1)return!1;let i=typeof n==\"function\"?n:(r,o)=>r===o||E(r)&&E(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}var Gs=g(()=>{C()});function ti({composeNode:s,composeEmptyNode:e},t,n,i,r){let o=r?.nodeClass??P,l=new o(t.schema);t.atRoot&&(t.atRoot=!1);let a=n.offset,c=null;for(let p of n.items){let{start:f,key:u,sep:d,value:y}=p,h=oe(f,{indicator:\"explicit-key-ind\",next:u??d?.[0],offset:a,onError:i,parentIndent:n.indent,startOnNewline:!0}),m=!h.found;if(m){if(u&&(u.type===\"block-seq\"?i(a,\"BLOCK_AS_IMPLICIT_KEY\",\"A block sequence may not be used as an implicit map key\"):\"indent\"in u&&u.indent!==n.indent&&i(a,\"BAD_INDENT\",ei)),!h.anchor&&!h.tag&&!d){c=h.end,h.comment&&(l.comment?l.comment+=`\n`+h.comment:l.comment=h.comment);continue}(h.newlineAfterProp||ke(u))&&i(u??f[f.length-1],\"MULTILINE_IMPLICIT_KEY\",\"Implicit keys need to be on a single line\")}else h.found?.indent!==n.indent&&i(a,\"BAD_INDENT\",ei);t.atKey=!0;let S=h.end,k=u?s(t,u,h,i):e(t,S,f,null,h,i);t.schema.compat&&yt(n.indent,u,i),t.atKey=!1,is(t,l.items,k)&&i(S,\"DUPLICATE_KEY\",\"Map keys must be unique\");let N=oe(d??[],{indicator:\"map-value-ind\",next:y,offset:k.range[2],onError:i,parentIndent:n.indent,startOnNewline:!u||u.type===\"block-scalar\"});if(a=N.end,N.found){m&&(y?.type===\"block-map\"&&!N.hasNewline&&i(a,\"BLOCK_AS_IMPLICIT_KEY\",\"Nested mappings are not allowed in compact mappings\"),t.options.strict&&h.start<N.found.offset-1024&&i(k.range,\"KEY_OVER_1024_CHARS\",\"The : indicator must be at most 1024 chars after the start of an implicit block mapping key\"));let O=y?s(t,y,N,i):e(t,a,d,null,N,i);t.schema.compat&&yt(n.indent,y,i),a=O.range[2];let A=new _(k,O);t.options.keepSourceTokens&&(A.srcToken=p),l.items.push(A)}else{m&&i(k.range,\"MISSING_CHAR\",\"Implicit map keys need to be followed by map values\"),N.comment&&(k.comment?k.comment+=`\n`+N.comment:k.comment=N.comment);let O=new _(k);t.options.keepSourceTokens&&(O.srcToken=p),l.items.push(O)}}return c&&c<a&&i(c,\"IMPOSSIBLE\",\"Map comment with trailing content\"),l.range=[n.offset,a,c??a],l}var ei,si=g(()=>{ge();be();gt();ns();Qs();Gs();ei=\"All mapping items must start at the same column\"});function ni({composeNode:s,composeEmptyNode:e},t,n,i,r){let o=r?.nodeClass??j,l=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let a=n.offset,c=null;for(let{start:p,value:f}of n.items){let u=oe(p,{indicator:\"seq-item-ind\",next:f,offset:a,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!u.found)if(u.anchor||u.tag||f)f?.type===\"block-seq\"?i(u.end,\"BAD_INDENT\",\"All sequence items must start at the same column\"):i(a,\"MISSING_CHAR\",\"Sequence item without - indicator\");else{c=u.end,u.comment&&(l.comment=u.comment);continue}let d=f?s(t,f,u,i):e(t,u.end,p,null,u,i);t.schema.compat&&yt(n.indent,f,i),a=d.range[2],l.items.push(d)}return l.range=[n.offset,a,c??a],l}var ii=g(()=>{we();gt();Qs()});function le(s,e,t,n){let i=\"\";if(s){let r=!1,o=\"\";for(let l of s){let{source:a,type:c}=l;switch(c){case\"space\":r=!0;break;case\"comment\":{t&&!r&&n(l,\"MISSING_CHAR\",\"Comments must be separated from other tokens by white space characters\");let p=a.substring(1)||\" \";i?i+=o+p:i=p,o=\"\";break}case\"newline\":i&&(o+=a),r=!0;break;default:n(l,\"UNEXPECTED_TOKEN\",`Unexpected ${c} at node end`)}e+=a.length}}return{comment:i,offset:e}}var Qe=g(()=>{});function ri({composeNode:s,composeEmptyNode:e},t,n,i,r){let o=n.start.source===\"{\",l=o?\"flow map\":\"flow sequence\",a=r?.nodeClass??(o?P:j),c=new a(t.schema);c.flow=!0;let p=t.atRoot;p&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let f=n.offset+n.start.source.length;for(let m=0;m<n.items.length;++m){let S=n.items[m],{start:k,key:N,sep:O,value:A}=S,T=oe(k,{flow:l,indicator:\"explicit-key-ind\",next:N??O?.[0],offset:f,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!T.found){if(!T.anchor&&!T.tag&&!O&&!A){m===0&&T.comma?i(T.comma,\"UNEXPECTED_TOKEN\",`Unexpected , in ${l}`):m<n.items.length-1&&i(T.start,\"UNEXPECTED_TOKEN\",`Unexpected empty item in ${l}`),T.comment&&(c.comment?c.comment+=`\n`+T.comment:c.comment=T.comment),f=T.end;continue}!o&&t.options.strict&&ke(N)&&i(N,\"MULTILINE_IMPLICIT_KEY\",\"Implicit keys of flow sequence pairs need to be on a single line\")}if(m===0)T.comma&&i(T.comma,\"UNEXPECTED_TOKEN\",`Unexpected , in ${l}`);else if(T.comma||i(T.start,\"MISSING_CHAR\",`Missing , between ${l} items`),T.comment){let $=\"\";e:for(let w of k)switch(w.type){case\"comma\":case\"space\":break;case\"comment\":$=w.source.substring(1);break e;default:break e}if($){let w=c.items[c.items.length-1];I(w)&&(w=w.value??w.key),w.comment?w.comment+=`\n`+$:w.comment=$,T.comment=T.comment.substring($.length+1)}}if(!o&&!O&&!T.found){let $=A?s(t,A,T,i):e(t,T.end,O,null,T,i);c.items.push($),f=$.range[2],Hs(A)&&i($.range,\"BLOCK_IN_FLOW\",Ws)}else{t.atKey=!0;let $=T.end,w=N?s(t,N,T,i):e(t,$,k,null,T,i);Hs(N)&&i(w.range,\"BLOCK_IN_FLOW\",Ws),t.atKey=!1;let B=oe(O??[],{flow:l,indicator:\"map-value-ind\",next:A,offset:w.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(B.found){if(!o&&!T.found&&t.options.strict){if(O)for(let D of O){if(D===B.found)break;if(D.type===\"newline\"){i(D,\"MULTILINE_IMPLICIT_KEY\",\"Implicit keys of flow sequence pairs need to be on a single line\");break}}T.start<B.found.offset-1024&&i(B.found,\"KEY_OVER_1024_CHARS\",\"The : indicator must be at most 1024 chars after the start of an implicit flow sequence key\")}}else A&&(\"source\"in A&&A.source?.[0]===\":\"?i(A,\"MISSING_CHAR\",`Missing space after : in ${l}`):i(B.start,\"MISSING_CHAR\",`Missing , or : between ${l} items`));let he=A?s(t,A,B,i):B.found?e(t,B.end,O,null,B,i):null;he?Hs(A)&&i(he.range,\"BLOCK_IN_FLOW\",Ws):B.comment&&(w.comment?w.comment+=`\n`+B.comment:w.comment=B.comment);let _e=new _(w,he);if(t.options.keepSourceTokens&&(_e.srcToken=S),o){let D=c;is(t,D.items,w)&&i($,\"DUPLICATE_KEY\",\"Map keys must be unique\"),D.items.push(_e)}else{let D=new P(t.schema);D.flow=!0,D.items.push(_e);let gn=(he??w).range;D.range=[w.range[0],gn[1],gn[2]],c.items.push(D)}f=he?he.range[2]:B.end}}let u=o?\"}\":\"]\",[d,...y]=n.end,h=f;if(d?.source===u)h=d.offset+d.source.length;else{let m=l[0].toUpperCase()+l.substring(1),S=p?`${m} must end with a ${u}`:`${m} in block collection must be sufficiently indented and end with a ${u}`;i(f,p?\"MISSING_CHAR\":\"BAD_INDENT\",S),d&&d.source.length!==1&&y.unshift(d)}if(y.length>0){let m=le(y,h,t.options.strict,i);m.comment&&(c.comment?c.comment+=`\n`+m.comment:c.comment=m.comment),c.range=[n.offset,h,m.offset]}else c.range=[n.offset,h,h];return c}var Ws,Hs,oi=g(()=>{C();ge();be();we();Qe();gt();ns();Gs();Ws=\"Block collections are not allowed within flow collections\",Hs=s=>s&&(s.type===\"block-map\"||s.type===\"block-seq\")});function Xs(s,e,t,n,i,r){let o=t.type===\"block-map\"?ti(s,e,t,n,r):t.type===\"block-seq\"?ni(s,e,t,n,r):ri(s,e,t,n,r),l=o.constructor;return i===\"!\"||i===l.tagName?(o.tag=l.tagName,o):(i&&(o.tag=i),o)}function li(s,e,t,n,i){let r=n.tag,o=r?e.directives.tagName(r.source,u=>i(r,\"TAG_RESOLVE_FAILED\",u)):null;if(t.type===\"block-seq\"){let{anchor:u,newlineAfterProp:d}=n,y=u&&r?u.offset>r.offset?u:r:u??r;y&&(!d||d.offset<y.offset)&&i(y,\"MISSING_CHAR\",\"Missing newline after block sequence props\")}let l=t.type===\"block-map\"?\"map\":t.type===\"block-seq\"?\"seq\":t.start.source===\"{\"?\"map\":\"seq\";if(!r||!o||o===\"!\"||o===P.tagName&&l===\"map\"||o===j.tagName&&l===\"seq\")return Xs(s,e,t,i,o);let a=e.schema.tags.find(u=>u.tag===o&&u.collection===l);if(!a){let u=e.schema.knownTags[o];if(u?.collection===l)e.schema.tags.push(Object.assign({},u,{default:!1})),a=u;else return u?i(r,\"BAD_COLLECTION_TYPE\",`${u.tag} used for ${l} collection, but expects ${u.collection??\"scalar\"}`,!0):i(r,\"TAG_RESOLVE_FAILED\",`Unresolved tag: ${o}`,!0),Xs(s,e,t,i,o)}let c=Xs(s,e,t,i,o,a),p=a.resolve?.(c,u=>i(r,\"TAG_RESOLVE_FAILED\",u),e.options)??c,f=L(p)?p:new b(p);return f.range=c.range,f.tag=o,a?.format&&(f.format=a.format),f}var ai=g(()=>{C();M();be();we();si();ii();oi()});function rs(s,e,t){let n=e.offset,i=sr(e,s.options.strict,t);if(!i)return{value:\"\",type:null,comment:\"\",range:[n,n,n]};let r=i.mode===\">\"?b.BLOCK_FOLDED:b.BLOCK_LITERAL,o=e.source?nr(e.source):[],l=o.length;for(let h=o.length-1;h>=0;--h){let m=o[h][1];if(m===\"\"||m===\"\\r\")l=h;else break}if(l===0){let h=i.chomp===\"+\"&&o.length>0?`\n`.repeat(Math.max(1,o.length-1)):\"\",m=n+i.length;return e.source&&(m+=e.source.length),{value:h,type:r,comment:i.comment,range:[n,m,m]}}let a=e.indent+i.indent,c=e.offset+i.length,p=0;for(let h=0;h<l;++h){let[m,S]=o[h];if(S===\"\"||S===\"\\r\")i.indent===0&&m.length>a&&(a=m.length);else{m.length<a&&t(c+m.length,\"MISSING_CHAR\",\"Block scalars with more-indented leading empty lines must use an explicit indentation indicator\"),i.indent===0&&(a=m.length),p=h,a===0&&!s.atRoot&&t(c,\"BAD_INDENT\",\"Block scalar values in collections must be indented\");break}c+=m.length+S.length+1}for(let h=o.length-1;h>=l;--h)o[h][0].length>a&&(l=h+1);let f=\"\",u=\"\",d=!1;for(let h=0;h<p;++h)f+=o[h][0].slice(a)+`\n`;for(let h=p;h<l;++h){let[m,S]=o[h];c+=m.length+S.length+1;let k=S[S.length-1]===\"\\r\";if(k&&(S=S.slice(0,-1)),S&&m.length<a){let O=`Block scalar lines must not be less indented than their ${i.indent?\"explicit indentation indicator\":\"first line\"}`;t(c-S.length-(k?2:1),\"BAD_INDENT\",O),m=\"\"}r===b.BLOCK_LITERAL?(f+=u+m.slice(a)+S,u=`\n`):m.length>a||S[0]===\"\t\"?(u===\" \"?u=`\n`:!d&&u===`\n`&&(u=`\n\n`),f+=u+m.slice(a)+S,u=`\n`,d=!0):S===\"\"?u===`\n`?f+=`\n`:u=`\n`:(f+=u+S,u=\" \",d=!1)}switch(i.chomp){case\"-\":break;case\"+\":for(let h=l;h<o.length;++h)f+=`\n`+o[h][0].slice(a);f[f.length-1]!==`\n`&&(f+=`\n`);break;default:f+=`\n`}let y=n+i.length+e.source.length;return{value:f,type:r,comment:i.comment,range:[n,y,y]}}function sr({offset:s,props:e},t,n){if(e[0].type!==\"block-scalar-header\")return n(e[0],\"IMPOSSIBLE\",\"Block scalar header not found\"),null;let{source:i}=e[0],r=i[0],o=0,l=\"\",a=-1;for(let u=1;u<i.length;++u){let d=i[u];if(!l&&(d===\"-\"||d===\"+\"))l=d;else{let y=Number(d);!o&&y?o=y:a===-1&&(a=s+u)}}a!==-1&&n(a,\"UNEXPECTED_TOKEN\",`Block scalar header includes extra characters: ${i}`);let c=!1,p=\"\",f=i.length;for(let u=1;u<e.length;++u){let d=e[u];switch(d.type){case\"space\":c=!0;case\"newline\":f+=d.source.length;break;case\"comment\":t&&!c&&n(d,\"MISSING_CHAR\",\"Comments must be separated from other tokens by white space characters\"),f+=d.source.length,p=d.source.substring(1);break;case\"error\":n(d,\"UNEXPECTED_TOKEN\",d.message),f+=d.source.length;break;default:{let y=`Unexpected token in block scalar header: ${d.type}`;n(d,\"UNEXPECTED_TOKEN\",y);let h=d.source;h&&typeof h==\"string\"&&(f+=h.length)}}}return{mode:r,indent:o,chomp:l,comment:p,length:f}}function nr(s){let e=s.split(/\\n( *)/),t=e[0],n=t.match(/^( *)/),r=[n?.[1]?[n[1],t.slice(n[1].length)]:[\"\",t]];for(let o=1;o<e.length;o+=2)r.push([e[o],e[o+1]]);return r}var zs=g(()=>{M()});function os(s,e,t){let{offset:n,type:i,source:r,end:o}=s,l,a,c=(u,d,y)=>t(n+u,d,y);switch(i){case\"scalar\":l=b.PLAIN,a=ir(r,c);break;case\"single-quoted-scalar\":l=b.QUOTE_SINGLE,a=rr(r,c);break;case\"double-quoted-scalar\":l=b.QUOTE_DOUBLE,a=or(r,c);break;default:return t(s,\"UNEXPECTED_TOKEN\",`Expected a flow scalar value, but found: ${i}`),{value:\"\",type:null,comment:\"\",range:[n,n+r.length,n+r.length]}}let p=n+r.length,f=le(o,p,e,t);return{value:a,type:l,comment:f.comment,range:[n,p,f.offset]}}function ir(s,e){let t=\"\";switch(s[0]){case\"\t\":t=\"a tab character\";break;case\",\":t=\"flow indicator character ,\";break;case\"%\":t=\"directive indicator character %\";break;case\"|\":case\">\":{t=`block scalar indicator ${s[0]}`;break}case\"@\":case\"`\":{t=`reserved character ${s[0]}`;break}}return t&&e(0,\"BAD_SCALAR_START\",`Plain value cannot start with ${t}`),ci(s)}function rr(s,e){return(s[s.length-1]!==\"'\"||s.length===1)&&e(s.length,\"MISSING_CHAR\",\"Missing closing 'quote\"),ci(s.slice(1,-1)).replace(/''/g,\"'\")}function ci(s){let e,t;try{e=new RegExp(`(.*?)(?<![ \t])[ \t]*\\r?\n`,\"sy\"),t=new RegExp(`[ \t]*(.*?)(?:(?<![ \t])[ \t]*)?\\r?\n`,\"sy\")}catch{e=/(.*?)[ \\t]*\\r?\\n/sy,t=/[ \\t]*(.*?)[ \\t]*\\r?\\n/sy}let n=e.exec(s);if(!n)return s;let i=n[1],r=\" \",o=e.lastIndex;for(t.lastIndex=o;n=t.exec(s);)n[1]===\"\"?r===`\n`?i+=r:r=`\n`:(i+=r+n[1],r=\" \"),o=t.lastIndex;let l=/[ \\t]*(.*)/sy;return l.lastIndex=o,n=l.exec(s),i+r+(n?.[1]??\"\")}function or(s,e){let t=\"\";for(let n=1;n<s.length-1;++n){let i=s[n];if(!(i===\"\\r\"&&s[n+1]===`\n`))if(i===`\n`){let{fold:r,offset:o}=lr(s,n);t+=r,n=o}else if(i===\"\\\\\"){let r=s[++n],o=ar[r];if(o)t+=o;else if(r===`\n`)for(r=s[n+1];r===\" \"||r===\"\t\";)r=s[++n+1];else if(r===\"\\r\"&&s[n+1]===`\n`)for(r=s[++n+1];r===\" \"||r===\"\t\";)r=s[++n+1];else if(r===\"x\"||r===\"u\"||r===\"U\"){let l=r===\"x\"?2:r===\"u\"?4:8;t+=cr(s,n+1,l,e),n+=l}else{let l=s.substr(n-1,2);e(n-1,\"BAD_DQ_ESCAPE\",`Invalid escape sequence ${l}`),t+=l}}else if(i===\" \"||i===\"\t\"){let r=n,o=s[n+1];for(;o===\" \"||o===\"\t\";)o=s[++n+1];o!==`\n`&&!(o===\"\\r\"&&s[n+2]===`\n`)&&(t+=n>r?s.slice(r,n+1):i)}else t+=i}return(s[s.length-1]!=='\"'||s.length===1)&&e(s.length,\"MISSING_CHAR\",'Missing closing \"quote'),t}function lr(s,e){let t=\"\",n=s[e+1];for(;(n===\" \"||n===\"\t\"||n===`\n`||n===\"\\r\")&&!(n===\"\\r\"&&s[e+2]!==`\n`);)n===`\n`&&(t+=`\n`),e+=1,n=s[e+1];return t||(t=\" \"),{fold:t,offset:e}}function cr(s,e,t,n){let i=s.substr(e,t),o=i.length===t&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let l=s.substr(e-2,t+2);return n(e-2,\"BAD_DQ_ESCAPE\",`Invalid escape sequence ${l}`),l}}var ar,Zs=g(()=>{M();Qe();ar={0:\"\\0\",a:\"\\x07\",b:\"\\b\",e:\"\\x1B\",f:\"\\f\",n:`\n`,r:\"\\r\",t:\"\t\",v:\"\\v\",N:\"\\x85\",_:\"\\xA0\",L:\"\\u2028\",P:\"\\u2029\",\" \":\" \",'\"':'\"',\"/\":\"/\",\"\\\\\":\"\\\\\",\"\t\":\"\t\"}});function en(s,e,t,n){let{value:i,type:r,comment:o,range:l}=e.type===\"block-scalar\"?rs(s,e,n):os(e,s.options.strict,n),a=t?s.directives.tagName(t.source,f=>n(t,\"TAG_RESOLVE_FAILED\",f)):null,c;s.options.stringKeys&&s.atKey?c=s.schema[U]:a?c=fr(s.schema,i,a,t,n):e.type===\"scalar\"?c=ur(s,i,e,n):c=s.schema[U];let p;try{let f=c.resolve(i,u=>n(t??e,\"TAG_RESOLVE_FAILED\",u),s.options);p=E(f)?f:new b(f)}catch(f){let u=f instanceof Error?f.message:String(f);n(t??e,\"TAG_RESOLVE_FAILED\",u),p=new b(i)}return p.range=l,p.source=i,r&&(p.type=r),a&&(p.tag=a),c.format&&(p.format=c.format),o&&(p.comment=o),p}function fr(s,e,t,n,i){if(t===\"!\")return s[U];let r=[];for(let l of s.tags)if(!l.collection&&l.tag===t)if(l.default&&l.test)r.push(l);else return l;for(let l of r)if(l.test?.test(e))return l;let o=s.knownTags[t];return o&&!o.collection?(s.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,\"TAG_RESOLVE_FAILED\",`Unresolved tag: ${t}`,t!==\"tag:yaml.org,2002:str\"),s[U])}function ur({atKey:s,directives:e,schema:t},n,i,r){let o=t.tags.find(l=>(l.default===!0||s&&l.default===\"key\")&&l.test?.test(n))||t[U];if(t.compat){let l=t.compat.find(a=>a.default&&a.test?.test(n))??t[U];if(o.tag!==l.tag){let a=e.tagString(o.tag),c=e.tagString(l.tag),p=`Value may be parsed as either ${a} or ${c}`;r(i,\"TAG_RESOLVE_FAILED\",p,!0)}}return o}var fi=g(()=>{C();M();zs();Zs()});function ui(s,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let i=e[n];switch(i.type){case\"space\":case\"comment\":case\"newline\":s-=i.source.length;continue}for(i=e[++n];i?.type===\"space\";)s+=i.source.length,i=e[++n];break}}return s}var hi=g(()=>{});function tn(s,e,t,n){let i=s.atKey,{spaceBefore:r,comment:o,anchor:l,tag:a}=t,c,p=!0;switch(e.type){case\"alias\":c=pr(s,e,n),(l||a)&&n(e,\"ALIAS_PROPS\",\"An alias node must not specify any properties\");break;case\"scalar\":case\"single-quoted-scalar\":case\"double-quoted-scalar\":case\"block-scalar\":c=en(s,e,a,n),l&&(c.anchor=l.source.substring(1));break;case\"block-map\":case\"block-seq\":case\"flow-collection\":try{c=li(hr,s,e,t,n),l&&(c.anchor=l.source.substring(1))}catch(f){let u=f instanceof Error?f.message:String(f);n(e,\"RESOURCE_EXHAUSTION\",u)}break;default:{let f=e.type===\"error\"?e.message:`Unsupported token (type: ${e.type})`;n(e,\"UNEXPECTED_TOKEN\",f),p=!1}}return c??(c=ls(s,e.offset,void 0,null,t,n)),l&&c.anchor===\"\"&&n(l,\"BAD_ALIAS\",\"Anchor cannot be an empty string\"),i&&s.options.stringKeys&&(!E(c)||typeof c.value!=\"string\"||c.tag&&c.tag!==\"tag:yaml.org,2002:str\")&&n(a??e,\"NON_STRING_KEY\",\"With stringKeys, all keys must be strings\"),r&&(c.spaceBefore=!0),o&&(e.type===\"scalar\"&&e.source===\"\"?c.comment=o:c.commentBefore=o),s.options.keepSourceTokens&&p&&(c.srcToken=e),c}function ls(s,e,t,n,{spaceBefore:i,comment:r,anchor:o,tag:l,end:a},c){let p={type:\"scalar\",offset:ui(e,t,n),indent:-1,source:\"\"},f=en(s,p,l,c);return o&&(f.anchor=o.source.substring(1),f.anchor===\"\"&&c(o,\"BAD_ALIAS\",\"Anchor cannot be an empty string\")),i&&(f.spaceBefore=!0),r&&(f.comment=r,f.range[2]=a),f}function pr({options:s},{offset:e,source:t,end:n},i){let r=new X(t.substring(1));r.source===\"\"&&i(e,\"BAD_ALIAS\",\"Alias cannot be an empty string\"),r.source.endsWith(\":\")&&i(e+t.length-1,\"BAD_ALIAS\",\"Alias ending in : is ambiguous\",!0);let o=e+t.length,l=le(n,o,s.strict,i);return r.range=[e,o,l.offset],l.comment&&(r.comment=l.comment),r}var hr,pi=g(()=>{Xe();C();ai();fi();Qe();hi();hr={composeNode:tn,composeEmptyNode:ls}});function mi(s,e,{offset:t,start:n,value:i,end:r},o){let l=Object.assign({_directives:e},s),a=new te(void 0,l),c={atKey:!1,atRoot:!0,directives:a.directives,options:a.options,schema:a.schema},p=oe(n,{indicator:\"doc-start\",next:i??r?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});p.found&&(a.directives.docStart=!0,i&&(i.type===\"block-map\"||i.type===\"block-seq\")&&!p.hasNewline&&o(p.end,\"MISSING_CHAR\",\"Block collection cannot start on same line with directives-end marker\")),a.contents=i?tn(c,i,p,o):ls(c,p.end,n,null,p,o);let f=a.contents.range[2],u=le(r,f,!1,o);return u.comment&&(a.comment=u.comment),a.range=[t,f,u.offset],a}var di=g(()=>{pt();pi();Qe();gt()});function bt(s){if(typeof s==\"number\")return[s,s+1];if(Array.isArray(s))return s.length===2?s:[s[0],s[1]];let{offset:e,source:t}=s;return[e,e+(typeof t==\"string\"?t.length:1)]}function gi(s){let e=\"\",t=!1,n=!1;for(let i=0;i<s.length;++i){let r=s[i];switch(r[0]){case\"#\":e+=(e===\"\"?\"\":n?`\n\n`:`\n`)+(r.substring(1)||\" \"),t=!0,n=!1;break;case\"%\":s[i+1]?.[0]!==\"#\"&&(i+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var Ne,sn=g(()=>{ws();pt();dt();C();di();Qe();Ne=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,r)=>{let o=bt(t);r?this.warnings.push(new Ce(o,n,i)):this.errors.push(new x(o,n,i))},this.directives=new ie({version:e.version||\"1.2\"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=gi(this.prelude);if(n){let r=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(i||e.directives.docStart||!r)e.commentBefore=n;else if(v(r)&&!r.flow&&r.items.length>0){let o=r.items[0];I(o)&&(o=o.key);let l=o.commentBefore;o.commentBefore=l?`${n}\n${l}`:n}else{let o=r.commentBefore;r.commentBefore=o?`${n}\n${o}`:n}}if(t){for(let r=0;r<this.errors.length;++r)e.errors.push(this.errors[r]);for(let r=0;r<this.warnings.length;++r)e.warnings.push(this.warnings[r])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:gi(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let i of e)yield*this.next(i);yield*this.end(t,n)}*next(e){switch(e.type){case\"directive\":this.directives.add(e.source,(t,n,i)=>{let r=bt(e);r[0]+=t,this.onError(r,\"BAD_DIRECTIVE\",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case\"document\":{let t=mi(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,\"MISSING_CHAR\",\"Missing directives-end/doc-start indicator line\"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case\"byte-order-mark\":case\"space\":break;case\"comment\":case\"newline\":this.prelude.push(e.source);break;case\"error\":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new x(bt(e),\"UNEXPECTED_TOKEN\",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case\"doc-end\":{if(!this.doc){let n=\"Unexpected doc-end without preceding document\";this.errors.push(new x(bt(e),\"UNEXPECTED_TOKEN\",n));break}this.doc.directives.docEnd=!0;let t=le(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let n=this.doc.comment;this.doc.comment=n?`${n}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new x(bt(e),\"UNEXPECTED_TOKEN\",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),i=new te(void 0,n);this.atDirectives&&this.onError(t,\"MISSING_CHAR\",\"Missing directives-end indicator line\"),i.range=[0,t,t],this.decorate(i,!1),yield i}}}});function yi(s,e=!0,t){if(s){let n=(i,r,o)=>{let l=typeof i==\"number\"?i:Array.isArray(i)?i[0]:i.offset;if(t)t(l,r,o);else throw new x([l,l+1],r,o)};switch(s.type){case\"scalar\":case\"single-quoted-scalar\":case\"double-quoted-scalar\":return os(s,e,n);case\"block-scalar\":return rs({options:{strict:e}},s,n)}}return null}function bi(s,e){let{implicitKey:t=!1,indent:n,inFlow:i=!1,offset:r=-1,type:o=\"PLAIN\"}=e,l=fe({type:o,value:s},{implicitKey:t,indent:n>0?\" \".repeat(n):\"\",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),a=e.end??[{type:\"newline\",offset:-1,indent:n,source:`\n`}];switch(l[0]){case\"|\":case\">\":{let c=l.indexOf(`\n`),p=l.substring(0,c),f=l.substring(c+1)+`\n`,u=[{type:\"block-scalar-header\",offset:r,indent:n,source:p}];return Si(u,a)||u.push({type:\"newline\",offset:-1,indent:n,source:`\n`}),{type:\"block-scalar\",offset:r,indent:n,props:u,source:f}}case'\"':return{type:\"double-quoted-scalar\",offset:r,indent:n,source:l,end:a};case\"'\":return{type:\"single-quoted-scalar\",offset:r,indent:n,source:l,end:a};default:return{type:\"scalar\",offset:r,indent:n,source:l,end:a}}}function wi(s,e,t={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:r=!1,type:o}=t,l=\"indent\"in s?s.indent:null;if(n&&typeof l==\"number\"&&(l+=2),!o)switch(s.type){case\"single-quoted-scalar\":o=\"QUOTE_SINGLE\";break;case\"double-quoted-scalar\":o=\"QUOTE_DOUBLE\";break;case\"block-scalar\":{let c=s.props[0];if(c.type!==\"block-scalar-header\")throw new Error(\"Invalid block scalar header\");o=c.source[0]===\">\"?\"BLOCK_FOLDED\":\"BLOCK_LITERAL\";break}default:o=\"PLAIN\"}let a=fe({type:o,value:e},{implicitKey:i||l===null,indent:l!==null&&l>0?\" \".repeat(l):\"\",inFlow:r,options:{blockQuote:!0,lineWidth:-1}});switch(a[0]){case\"|\":case\">\":mr(s,a);break;case'\"':nn(s,a,\"double-quoted-scalar\");break;case\"'\":nn(s,a,\"single-quoted-scalar\");break;default:nn(s,a,\"scalar\")}}function mr(s,e){let t=e.indexOf(`\n`),n=e.substring(0,t),i=e.substring(t+1)+`\n`;if(s.type===\"block-scalar\"){let r=s.props[0];if(r.type!==\"block-scalar-header\")throw new Error(\"Invalid block scalar header\");r.source=n,s.source=i}else{let{offset:r}=s,o=\"indent\"in s?s.indent:-1,l=[{type:\"block-scalar-header\",offset:r,indent:o,source:n}];Si(l,\"end\"in s?s.end:void 0)||l.push({type:\"newline\",offset:-1,indent:o,source:`\n`});for(let a of Object.keys(s))a!==\"type\"&&a!==\"offset\"&&delete s[a];Object.assign(s,{type:\"block-scalar\",indent:o,props:l,source:i})}}function Si(s,e){if(e)for(let t of e)switch(t.type){case\"space\":case\"comment\":s.push(t);break;case\"newline\":return s.push(t),!0}return!1}function nn(s,e,t){switch(s.type){case\"scalar\":case\"double-quoted-scalar\":case\"single-quoted-scalar\":s.type=t,s.source=e;break;case\"block-scalar\":{let n=s.props.slice(1),i=e.length;s.props[0].type===\"block-scalar-header\"&&(i-=s.props[0].source.length);for(let r of n)r.offset+=i;delete s.props,Object.assign(s,{type:t,source:e,end:n});break}case\"block-map\":case\"block-seq\":{let i={type:\"newline\",offset:s.offset+e.length,indent:s.indent,source:`\n`};delete s.items,Object.assign(s,{type:t,source:e,end:[i]});break}default:{let n=\"indent\"in s?s.indent:-1,i=\"end\"in s&&Array.isArray(s.end)?s.end.filter(r=>r.type===\"space\"||r.type===\"comment\"||r.type===\"newline\"):[];for(let r of Object.keys(s))r!==\"type\"&&r!==\"offset\"&&delete s[r];Object.assign(s,{type:t,indent:n,source:e,end:i})}}}var ki=g(()=>{zs();Zs();dt();it()});function cs(s){switch(s.type){case\"block-scalar\":{let e=\"\";for(let t of s.props)e+=cs(t);return e+s.source}case\"block-map\":case\"block-seq\":{let e=\"\";for(let t of s.items)e+=as(t);return e}case\"flow-collection\":{let e=s.start.source;for(let t of s.items)e+=as(t);for(let t of s.end)e+=t.source;return e}case\"document\":{let e=as(s);if(s.end)for(let t of s.end)e+=t.source;return e}default:{let e=s.source;if(\"end\"in s&&s.end)for(let t of s.end)e+=t.source;return e}}}function as({start:s,key:e,sep:t,value:n}){let i=\"\";for(let r of s)i+=r.source;if(e&&(i+=cs(e)),t)for(let r of t)i+=r.source;return n&&(i+=cs(n)),i}var Ni,Oi=g(()=>{Ni=s=>\"type\"in s?cs(s):as(s)});function Oe(s,e){\"type\"in s&&s.type===\"document\"&&(s={start:s.start,value:s.value}),Ei(Object.freeze([]),s,e)}function Ei(s,e,t){let n=t(e,s);if(typeof n==\"symbol\")return n;for(let i of[\"key\",\"value\"]){let r=e[i];if(r&&\"items\"in r){for(let o=0;o<r.items.length;++o){let l=Ei(Object.freeze(s.concat([[i,o]])),r.items[o],t);if(typeof l==\"number\")o=l-1;else{if(l===rn)return rn;l===Ai&&(r.items.splice(o,1),o-=1)}}typeof n==\"function\"&&i===\"key\"&&(n=n(e,s))}}return typeof n==\"function\"?n(e,s):n}var rn,dr,Ai,Ti=g(()=>{rn=Symbol(\"break visit\"),dr=Symbol(\"skip children\"),Ai=Symbol(\"remove item\");Oe.BREAK=rn;Oe.SKIP=dr;Oe.REMOVE=Ai;Oe.itemAtPath=(s,e)=>{let t=s;for(let[n,i]of e){let r=t?.[n];if(r&&\"items\"in r)t=r.items[i];else return}return t};Oe.parentCollection=(s,e)=>{let t=Oe.itemAtPath(s,e.slice(0,-1)),n=e[e.length-1][0],i=t?.[n];if(i&&\"items\"in i)return i;throw new Error(\"Parent collection not found\")}});var fs={};ys(fs,{BOM:()=>wt,DOCUMENT:()=>St,FLOW_END:()=>kt,SCALAR:()=>Ge,createScalarToken:()=>bi,isCollection:()=>gr,isScalar:()=>yr,prettyToken:()=>br,resolveAsScalar:()=>yi,setScalarValue:()=>wi,stringify:()=>Ni,tokenType:()=>on,visit:()=>Oe});function br(s){switch(s){case wt:return\"<BOM>\";case St:return\"<DOC>\";case kt:return\"<FLOW_END>\";case Ge:return\"<SCALAR>\";default:return JSON.stringify(s)}}function on(s){switch(s){case wt:return\"byte-order-mark\";case St:return\"doc-mode\";case kt:return\"flow-error-end\";case Ge:return\"scalar\";case\"---\":return\"doc-start\";case\"...\":return\"doc-end\";case\"\":case`\n`:case`\\r\n`:return\"newline\";case\"-\":return\"seq-item-ind\";case\"?\":return\"explicit-key-ind\";case\":\":return\"map-value-ind\";case\"{\":return\"flow-map-start\";case\"}\":return\"flow-map-end\";case\"[\":return\"flow-seq-start\";case\"]\":return\"flow-seq-end\";case\",\":return\"comma\"}switch(s[0]){case\" \":case\"\t\":return\"space\";case\"#\":return\"comment\";case\"%\":return\"directive-line\";case\"*\":return\"alias\";case\"&\":return\"anchor\";case\"!\":return\"tag\";case\"'\":return\"single-quoted-scalar\";case'\"':return\"double-quoted-scalar\";case\"|\":case\">\":return\"block-scalar-header\"}return null}var wt,St,kt,Ge,gr,yr,us=g(()=>{ki();Oi();Ti();wt=\"\\uFEFF\",St=\"\u0002\",kt=\"\u0018\",Ge=\"\u001f\",gr=s=>!!s&&\"items\"in s,yr=s=>!!s&&(s.type===\"scalar\"||s.type===\"single-quoted-scalar\"||s.type===\"double-quoted-scalar\"||s.type===\"block-scalar\")});function se(s){switch(s){case void 0:case\" \":case`\n`:case\"\\r\":case\"\t\":return!0;default:return!1}}var Ii,wr,hs,Sr,ln,ve,an=g(()=>{us();Ii=new Set(\"0123456789ABCDEFabcdef\"),wr=new Set(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()\"),hs=new Set(\",[]{}\"),Sr=new Set(` ,[]{}\n\\r\t`),ln=s=>!s||Sr.has(s),ve=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=\"\",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=\"string\")throw TypeError(\"source is not a string\");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??\"stream\";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===\" \"||t===\"\t\";)t=this.buffer[++e];return!t||t===\"#\"||t===`\n`?!0:t===\"\\r\"?this.buffer[e+1]===`\n`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===\" \";)t=this.buffer[++n+e];if(t===\"\\r\"){let i=this.buffer[n+e+1];if(i===`\n`||!i&&!this.atEnd)return e+n+1}return t===`\n`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===\"-\"||t===\".\"){let n=this.buffer.substr(e,3);if((n===\"---\"||n===\"...\")&&se(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=\"number\"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`\n`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===\"\\r\"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case\"stream\":return yield*this.parseStream();case\"line-start\":return yield*this.parseLineStart();case\"block-start\":return yield*this.parseBlockStart();case\"doc\":return yield*this.parseDocument();case\"flow\":return yield*this.parseFlowCollection();case\"quoted-scalar\":return yield*this.parseQuotedScalar();case\"block-scalar\":return yield*this.parseBlockScalar();case\"plain-scalar\":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(\"stream\");if(e[0]===wt&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===\"%\"){let t=e.length,n=e.indexOf(\"#\");for(;n!==-1;){let r=e[n-1];if(r===\" \"||r===\"\t\"){t=n-1;break}else n=e.indexOf(\"#\",n+1)}for(;;){let r=e[t-1];if(r===\" \"||r===\"\t\")t-=1;else break}let i=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-i),this.pushNewline(),\"stream\"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),\"stream\"}return yield St,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(\"line-start\");if(e===\"-\"||e===\".\"){if(!this.atEnd&&!this.hasChars(4))return this.setNext(\"line-start\");let t=this.peek(3);if((t===\"---\"||t===\"...\")&&se(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t===\"---\"?\"doc\":\"stream\"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!se(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(\"block-start\");if((e===\"-\"||e===\"?\"||e===\":\")&&se(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,\"block-start\"}return\"doc\"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(\"doc\");let t=yield*this.pushIndicators();switch(e[t]){case\"#\":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case\"{\":case\"[\":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,\"flow\";case\"}\":case\"]\":return yield*this.pushCount(1),\"doc\";case\"*\":return yield*this.pushUntil(ln),\"doc\";case'\"':case\"'\":return yield*this.parseQuotedScalar();case\"|\":case\">\":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let i=this.getLine();if(i===null)return this.setNext(\"flow\");if((n!==-1&&n<this.indentNext&&i[0]!==\"#\"||n===0&&(i.startsWith(\"---\")||i.startsWith(\"...\"))&&se(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]===\"]\"||i[0]===\"}\")))return this.flowLevel=0,yield kt,yield*this.parseLineStart();let r=0;for(;i[r]===\",\";)r+=yield*this.pushCount(1),r+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(r+=yield*this.pushIndicators(),i[r]){case void 0:return\"flow\";case\"#\":return yield*this.pushCount(i.length-r),\"flow\";case\"{\":case\"[\":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,\"flow\";case\"}\":case\"]\":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?\"flow\":\"doc\";case\"*\":return yield*this.pushUntil(ln),\"flow\";case'\"':case\"'\":return this.flowKey=!0,yield*this.parseQuotedScalar();case\":\":{let o=this.charAt(1);if(this.flowKey||se(o)||o===\",\")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),\"flow\"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===\"'\")for(;t!==-1&&this.buffer[t+1]===\"'\";)t=this.buffer.indexOf(\"'\",t+2);else for(;t!==-1;){let r=0;for(;this.buffer[t-1-r]===\"\\\\\";)r+=1;if(r%2===0)break;t=this.buffer.indexOf('\"',t+1)}let n=this.buffer.substring(0,t),i=n.indexOf(`\n`,this.pos);if(i!==-1){for(;i!==-1;){let r=this.continueScalar(i+1);if(r===-1)break;i=n.indexOf(`\n`,r)}i!==-1&&(t=i-(n[i-1]===\"\\r\"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(\"quoted-scalar\");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?\"flow\":\"doc\"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===\"+\")this.blockScalarKeep=!0;else if(t>\"0\"&&t<=\"9\")this.blockScalarIndent=Number(t)-1;else if(t!==\"-\")break}return yield*this.pushUntil(t=>se(t)||t===\"#\")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case\" \":t+=1;break;case`\n`:e=r,t=0;break;case\"\\r\":{let o=this.buffer[r+1];if(!o&&!this.atEnd)return this.setNext(\"block-scalar\");if(o===`\n`)break}default:break e}if(!n&&!this.atEnd)return this.setNext(\"block-scalar\");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let r=this.continueScalar(e+1);if(r===-1)break;e=this.buffer.indexOf(`\n`,r)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext(\"block-scalar\");e=this.buffer.length}}let i=e+1;for(n=this.buffer[i];n===\" \";)n=this.buffer[++i];if(n===\"\t\"){for(;n===\"\t\"||n===\" \"||n===\"\\r\"||n===`\n`;)n=this.buffer[++i];e=i-1}else if(!this.blockScalarKeep)do{let r=e-1,o=this.buffer[r];o===\"\\r\"&&(o=this.buffer[--r]);let l=r;for(;o===\" \";)o=this.buffer[--r];if(o===`\n`&&r>=this.pos&&r+1+t>l)e=r;else break}while(!0);return yield Ge,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===\":\"){let r=this.buffer[n+1];if(se(r)||e&&hs.has(r))break;t=n}else if(se(i)){let r=this.buffer[n+1];if(i===\"\\r\"&&(r===`\n`?(n+=1,i=`\n`,r=this.buffer[n+1]):t=n),r===\"#\"||e&&hs.has(r))break;if(i===`\n`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&hs.has(i))break;t=n}return!i&&!this.atEnd?this.setNext(\"plain-scalar\"):(yield Ge,yield*this.pushToIndex(t+1,!0),e?\"flow\":\"doc\")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield\"\"),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case\"!\":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case\"&\":e+=yield*this.pushUntil(ln),e+=yield*this.pushSpaces(!0);continue e;case\"-\":case\"?\":case\":\":{let t=this.flowLevel>0,n=this.charAt(1);if(se(n)||t&&hs.has(n)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)===\"<\"){let e=this.pos+2,t=this.buffer[e];for(;!se(t)&&t!==\">\";)t=this.buffer[++e];return yield*this.pushToIndex(t===\">\"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(wr.has(t))t=this.buffer[++e];else if(t===\"%\"&&Ii.has(this.buffer[e+1])&&Ii.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`\n`?yield*this.pushCount(1):e===\"\\r\"&&this.charAt(1)===`\n`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===\" \"||e&&n===\"\t\");let i=t-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=t),i}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}});var $e,cn=g(()=>{$e=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let i=this.lineStarts[t-1];return{line:t,col:e-i+1}}}}});function Ae(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}function Li(s){for(let e=0;e<s.length;++e)switch(s[e].type){case\"space\":case\"comment\":case\"newline\":break;default:return e}return-1}function vi(s){switch(s?.type){case\"alias\":case\"scalar\":case\"single-quoted-scalar\":case\"double-quoted-scalar\":case\"flow-collection\":return!0;default:return!1}}function ps(s){switch(s.type){case\"document\":return s.start;case\"block-map\":{let e=s.items[s.items.length-1];return e.sep??e.start}case\"block-seq\":return s.items[s.items.length-1].start;default:return[]}}function We(s){if(s.length===0)return[];let e=s.length;e:for(;--e>=0;)switch(s[e].type){case\"doc-start\":case\"explicit-key-ind\":case\"map-value-ind\":case\"seq-item-ind\":case\"newline\":break e}for(;s[++e]?.type===\"space\";);return s.splice(e,s.length)}function ms(s,e){if(e.length<1e5)Array.prototype.push.apply(s,e);else for(let t=0;t<e.length;++t)s.push(e[t])}function Ci(s){if(s.start.type===\"flow-seq-start\")for(let e of s.items)e.sep&&!e.value&&!Ae(e.start,\"explicit-key-ind\")&&!Ae(e.sep,\"map-value-ind\")&&(e.key&&(e.value=e.key),delete e.key,vi(e.value)?e.value.end?ms(e.value.end,e.sep):e.value.end=e.sep:ms(e.start,e.sep),delete e.sep)}var Ee,fn=g(()=>{us();an();Ee=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=\"\",this.type=\"\",this.lexer=new ve,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=on(e);if(t)if(t===\"scalar\")this.atNewLine=!1,this.atScalar=!0,this.type=\"scalar\";else{switch(this.type=t,yield*this.step(),t){case\"newline\":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case\"space\":this.atNewLine&&e[0]===\" \"&&(this.indent+=e.length);break;case\"explicit-key-ind\":case\"map-value-ind\":case\"seq-item-ind\":this.atNewLine&&(this.indent+=e.length);break;case\"doc-mode\":case\"flow-error-end\":return;default:this.atNewLine=!1}this.offset+=e.length}else{let n=`Not a YAML token: ${e}`;yield*this.pop({type:\"error\",offset:this.offset,message:n,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===\"doc-end\"&&e?.type!==\"doc-end\"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:\"doc-end\",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case\"document\":return yield*this.document(e);case\"alias\":case\"scalar\":case\"single-quoted-scalar\":case\"double-quoted-scalar\":return yield*this.scalar(e);case\"block-scalar\":return yield*this.blockScalar(e);case\"block-map\":return yield*this.blockMap(e);case\"block-seq\":return yield*this.blockSequence(e);case\"flow-collection\":return yield*this.flowCollection(e);case\"doc-end\":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:\"error\",offset:this.offset,source:\"\",message:\"Tried to pop an empty stack\"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type===\"block-scalar\"?t.indent=\"indent\"in n?n.indent:0:t.type===\"flow-collection\"&&n.type===\"document\"&&(t.indent=0),t.type===\"flow-collection\"&&Ci(t),n.type){case\"document\":n.value=t;break;case\"block-scalar\":n.props.push(t);break;case\"block-map\":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=t;else{Object.assign(i,{key:t,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case\"block-seq\":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:t}):i.value=t;break}case\"flow-collection\":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:t,sep:[]}):i.sep?i.value=t:Object.assign(i,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type===\"document\"||n.type===\"block-map\"||n.type===\"block-seq\")&&(t.type===\"block-map\"||t.type===\"block-seq\")){let i=t.items[t.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&Li(i.start)===-1&&(t.indent===0||i.start.every(r=>r.type!==\"comment\"||r.indent<t.indent))&&(n.type===\"document\"?n.end=i.start:n.items.push({start:i.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case\"directive-line\":yield{type:\"directive\",offset:this.offset,source:this.source};return;case\"byte-order-mark\":case\"space\":case\"comment\":case\"newline\":yield this.sourceToken;return;case\"doc-mode\":case\"doc-start\":{let e={type:\"document\",offset:this.offset,start:[]};this.type===\"doc-start\"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:\"error\",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case\"doc-start\":{Li(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case\"anchor\":case\"tag\":case\"space\":case\"comment\":case\"newline\":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:\"error\",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===\"map-value-ind\"){let t=ps(this.peek(2)),n=We(t),i;e.end?(i=e.end,i.push(this.sourceToken),delete e.end):i=[this.sourceToken];let r={type:\"block-map\",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case\"space\":case\"comment\":case\"newline\":e.props.push(this.sourceToken);return;case\"scalar\":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`\n`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`\n`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case\"newline\":if(this.onKeyLine=!1,t.value){let n=\"end\"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===\"comment\"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case\"space\":case\"comment\":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){ms(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,i=n&&(t.sep||t.explicitKey)&&this.type!==\"seq-item-ind\",r=[];if(i&&t.sep&&!t.value){let o=[];for(let l=0;l<t.sep.length;++l){let a=t.sep[l];switch(a.type){case\"newline\":o.push(l);break;case\"space\":break;case\"comment\":a.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(r=t.sep.splice(o[1]))}switch(this.type){case\"anchor\":case\"tag\":i||t.value?(r.push(this.sourceToken),e.items.push({start:r}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case\"explicit-key-ind\":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(r.push(this.sourceToken),e.items.push({start:r,explicitKey:!0})):this.stack.push({type:\"block-map\",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case\"map-value-ind\":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ae(t.sep,\"map-value-ind\"))this.stack.push({type:\"block-map\",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]});else if(vi(t.key)&&!Ae(t.sep,\"newline\")){let o=We(t.start),l=t.key,a=t.sep;a.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:\"block-map\",offset:this.offset,indent:this.indent,items:[{start:o,key:l,sep:a}]})}else r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(Ae(t.start,\"newline\"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=We(t.start);this.stack.push({type:\"block-map\",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:r,key:null,sep:[this.sourceToken]}):Ae(t.sep,\"map-value-ind\")?this.stack.push({type:\"block-map\",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case\"alias\":case\"scalar\":case\"single-quoted-scalar\":case\"double-quoted-scalar\":{let o=this.flowScalar(this.type);i||t.value?(e.items.push({start:r,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type===\"block-seq\"){if(!t.explicitKey&&t.sep&&!Ae(t.sep,\"newline\")){yield*this.pop({type:\"error\",offset:this.offset,message:\"Unexpected block-seq-ind on same line with key\",source:this.source});return}}else n&&e.items.push({start:r});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case\"newline\":if(t.value){let n=\"end\"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===\"comment\"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case\"space\":case\"comment\":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){ms(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case\"anchor\":case\"tag\":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case\"seq-item-ind\":if(this.indent!==e.indent)break;t.value||Ae(t.start,\"seq-item-ind\")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===\"flow-error-end\"){let n;do yield*this.pop(),n=this.peek(1);while(n?.type===\"flow-collection\")}else if(e.end.length===0){switch(this.type){case\"comma\":case\"explicit-key-ind\":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case\"map-value-ind\":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case\"space\":case\"comment\":case\"newline\":case\"anchor\":case\"tag\":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case\"alias\":case\"scalar\":case\"single-quoted-scalar\":case\"double-quoted-scalar\":{let i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,sep:[]});return}case\"flow-map-end\":case\"flow-seq-end\":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type===\"block-map\"&&(this.type===\"map-value-ind\"&&n.indent===e.indent||this.type===\"newline\"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===\"map-value-ind\"&&n.type!==\"flow-collection\"){let i=ps(n),r=We(i);Ci(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let l={type:\"block-map\",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=l}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`\n`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`\n`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case\"alias\":case\"scalar\":case\"single-quoted-scalar\":case\"double-quoted-scalar\":return this.flowScalar(this.type);case\"block-scalar-header\":return{type:\"block-scalar\",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:\"\"};case\"flow-map-start\":case\"flow-seq-start\":return{type:\"flow-collection\",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case\"seq-item-ind\":return{type:\"block-seq\",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case\"explicit-key-ind\":{this.onKeyLine=!0;let t=ps(e),n=We(t);return n.push(this.sourceToken),{type:\"block-map\",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case\"map-value-ind\":{this.onKeyLine=!0;let t=ps(e),n=We(t);return{type:\"block-map\",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==\"comment\"||this.indent<=t?!1:e.every(n=>n.type===\"newline\"||n.type===\"space\")}*documentEnd(e){this.type!==\"doc-mode\"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===\"newline\"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case\"comma\":case\"doc-start\":case\"doc-end\":case\"flow-seq-end\":case\"flow-map-end\":case\"map-value-ind\":yield*this.pop(),yield*this.step();break;case\"newline\":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===\"newline\"&&(yield*this.pop())}}}});function $i(s){let e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new $e||null,prettyErrors:e}}function un(s,e={}){let{lineCounter:t,prettyErrors:n}=$i(e),i=new Ee(t?.addNewLine),r=new Ne(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(let l of o)l.errors.forEach(mt(s,t)),l.warnings.forEach(mt(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}function ds(s,e={}){let{lineCounter:t,prettyErrors:n}=$i(e),i=new Ee(t?.addNewLine),r=new Ne(e),o=null;for(let l of r.compose(i.parse(s),!0,s.length))if(!o)o=l;else if(o.options.logLevel!==\"silent\"){o.errors.push(new x(l.range.slice(0,2),\"MULTIPLE_DOCS\",\"Source contains multiple documents; please use YAML.parseAllDocuments()\"));break}return n&&t&&(o.errors.forEach(mt(s,t)),o.warnings.forEach(mt(s,t))),o}function hn(s,e,t){let n;typeof e==\"function\"?n=e:t===void 0&&e&&typeof e==\"object\"&&(t=e);let i=ds(s,t);if(!i)return null;if(i.warnings.forEach(r=>Dt(i.options.logLevel,r)),i.errors.length>0){if(i.options.logLevel!==\"silent\")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},t))}function pn(s,e,t){let n=null;if(typeof e==\"function\"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t==\"string\"&&(t=t.length),typeof t==\"number\"){let i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(s===void 0){let{keepUndefined:i}=t??e??{};if(!i)return}return J(s)&&!n?s.toString(t):new te(s,n,t).toString(t)}var _i=g(()=>{sn();pt();dt();Ts();C();cn();fn()});var mn={};ys(mn,{Alias:()=>X,CST:()=>fs,Composer:()=>Ne,Document:()=>te,Lexer:()=>ve,LineCounter:()=>$e,Pair:()=>_,Parser:()=>Ee,Scalar:()=>b,Schema:()=>Ie,YAMLError:()=>Le,YAMLMap:()=>P,YAMLParseError:()=>x,YAMLSeq:()=>j,YAMLWarning:()=>Ce,isAlias:()=>V,isCollection:()=>v,isDocument:()=>J,isMap:()=>Y,isNode:()=>L,isPair:()=>I,isScalar:()=>E,isSeq:()=>Q,parse:()=>hn,parseAllDocuments:()=>un,parseDocument:()=>ds,stringify:()=>pn,visit:()=>G,visitAsync:()=>Be});var dn=g(()=>{sn();pt();Ys();dt();Xe();C();ge();M();be();we();us();an();cn();fn();_i();He()});var Pi={};ys(Pi,{Alias:()=>X,CST:()=>fs,Composer:()=>Ne,Document:()=>te,Lexer:()=>ve,LineCounter:()=>$e,Pair:()=>_,Parser:()=>Ee,Scalar:()=>b,Schema:()=>Ie,YAMLError:()=>Le,YAMLMap:()=>P,YAMLParseError:()=>x,YAMLSeq:()=>j,YAMLWarning:()=>Ce,default:()=>kr,isAlias:()=>V,isCollection:()=>v,isDocument:()=>J,isMap:()=>Y,isNode:()=>L,isPair:()=>I,isScalar:()=>E,isSeq:()=>Q,parse:()=>hn,parseAllDocuments:()=>un,parseDocument:()=>ds,stringify:()=>pn,visit:()=>G,visitAsync:()=>Be});var kr,Mi=g(()=>{dn();dn();kr=mn});var Nr=qi((eu,Bi)=>{Bi.exports=(Mi(),Fi(Pi))});return Nr();})();\n";
12
+ var YamlLib = null;
13
+ function makeYamlLibIsolated() { return new Function(YamlLibSrc + "\n;return YamlLib")() }
14
+
15
+ /**
16
+ * @weibaohui/dsh-plugin-kit — client source(由消费者构建脚本内联进 bundle,
17
+ * 不经 loader 运行时加载)。对外暴露 PluginKit:
18
+ *
19
+ * PluginKit.substituteParams(template, params) — {{key}} 模板插值
20
+ * PluginKit.makeActionShareDialog(React, opts) — 返回 ActionShareDialog 组件
21
+ *
22
+ * ActionShareDialog props:
23
+ * title / hint / rows: [[label, value], ...] / initialPrompt
24
+ * params: [{ key, label?, placeholder?, multiline?, value? }] — 可选;模板参数
25
+ * 输入区(idle 态渲染在 prompt 上方),值实时替换进 prompt 的 {{key}} 占位符
26
+ * completedView: ({ job, output, close, retry }) => node — 可选;完成态插槽,
27
+ * 提供后 job done 不再渲染默认「输出原文」,改由插槽全权负责(如解析 AI 输出
28
+ * 成可编辑表单 + 创建按钮),Dialog footer 同时置空,操作按钮由插槽自承
29
+ * run: async (prompt) => { jobId } — 发起执行
30
+ * poll: async (jobId) => { status, output, code }
31
+ * labels: { copy, copied, run, running, done, failed, outputLabel, openSession, close }
32
+ * onOpenSession: (sessionId) => void — 可选;job 出现 sessionId 时渲染「打开会话」
33
+ * onClose
34
+ *
35
+ * 全部样式内联(主题 token + 回退值),消费者无需自带 CSS。
36
+ */
37
+ var PluginKit = (function () {
38
+ function substituteParams(template, params) {
39
+ var out = String(template || '')
40
+ for (var key in (params || {})) out = out.split('{{' + key + '}}').join(String(params[key]))
41
+ return out
42
+ }
43
+
44
+ function makeActionShareDialog(React, options) {
45
+ options = options || {}
46
+ var h = React.createElement
47
+ var useState = React.useState
48
+ var useEffect = React.useEffect
49
+ var useRef = React.useRef
50
+ var doFetch = options.fetch || (typeof fetch !== 'undefined' ? fetch : null)
51
+ var inputStyle = { width: '100%', minHeight: 190, resize: 'vertical', fontFamily: 'var(--dsw-font-family)', lineHeight: 1.6, fontSize: 12, background: 'var(--dsw-alias-bg-layer-2,transparent)', color: 'inherit', border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', borderRadius: '8px', padding: '10px', boxSizing: 'border-box' }
52
+ var paramStyle = { width: '100%', fontFamily: 'var(--dsw-font-family)', lineHeight: 1.5, fontSize: 13, background: 'var(--dsw-alias-bg-layer-2,transparent)', color: 'inherit', border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', borderRadius: '8px', padding: '6px 10px', boxSizing: 'border-box' }
53
+ var btnStyle = { background: 'transparent', color: 'inherit', border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', borderRadius: '8px', padding: '5px 12px', fontSize: 13, cursor: 'pointer', font: 'inherit' }
54
+ // 主按钮亮暗跟随:与 skills-management .sk-btn-primary 同款 token 组合
55
+ var primaryStyle = Object.assign({}, btnStyle, { background: 'var(--dsw-alias-state-business-primary,var(--dsw-alias-brand-primary,#4a7dff))', borderColor: 'transparent', color: 'var(--dsw-alias-label-primary-inverted,#fff)' })
56
+
57
+ return function ActionShareDialog(props) {
58
+ var title = props.title
59
+ var hint = props.hint
60
+ var labels = props.labels || {}
61
+ // 模板参数定义([{key,label,placeholder,multiline,value}])→ 值表
62
+ var paramDefs = Array.isArray(props.params) ? props.params : []
63
+ var initialParamValues = {}
64
+ for (var pi = 0; pi < paramDefs.length; pi++) {
65
+ var def = paramDefs[pi]
66
+ initialParamValues[def.key] = def.value !== undefined && def.value !== null ? String(def.value) : ''
67
+ }
68
+ var _pv = useState(initialParamValues)
69
+ var paramValues = _pv[0]; var setParamValues = _pv[1]
70
+ var _p = useState(props.initialPrompt || '')
71
+ var prompt = _p[0]; var setPrompt = _p[1]
72
+ // 「上次自动生成的 prompt」ref 镜像:effect 里比较当前 prompt 是否等于它,
73
+ // 判断用户是否手动编辑过——未手改则参数/模板变化可安全覆盖,手改过则保留
74
+ // 手动编辑(ntd ActionButton 的 lastGenerated 同款规则)。旧 dirty 单标记
75
+ // 无法表达「手改后又想让参数替换生效」的场景,且要同时服务 initialPrompt
76
+ // 异步到位的跟随行为,故统一收敛到这一处比较。
77
+ var lastGeneratedRef = useRef(null)
78
+ var _j = useState(null)
79
+ var job = _j[0]; var setJob = _j[1]
80
+ var _b = useState(false)
81
+ var busy = _b[0]; var setBusy = _b[1]
82
+ var _c = useState(false)
83
+ var copied = _c[0]; var setCopied = _c[1]
84
+ var _e = useState('')
85
+ var error = _e[0]; var setError = _e[1]
86
+
87
+ // 参数值/模板变化 → 重新生成 prompt;仅当用户未手改时覆盖
88
+ useEffect(function () {
89
+ var generated = substituteParams(props.initialPrompt || '', paramValues)
90
+ var userEdited = lastGeneratedRef.current !== null && prompt !== lastGeneratedRef.current
91
+ lastGeneratedRef.current = generated
92
+ if (!userEdited) setPrompt(generated)
93
+ }, [props.initialPrompt, paramValues])
94
+
95
+ useEffect(function () {
96
+ if (job === null || job.status !== 'running' || typeof props.poll !== 'function') return
97
+ var timer = setInterval(function () {
98
+ props.poll(job.jobId).then(function (d) {
99
+ setJob({ jobId: job.jobId, status: d.status, output: d.output || '', code: d.code !== undefined ? d.code : null, sessionId: d.sessionId })
100
+ }).catch(function () {})
101
+ }, 1500)
102
+ return function () { clearInterval(timer) }
103
+ }, [job !== null && job.jobId])
104
+
105
+ var setParam = function (key, value) {
106
+ setParamValues(function (prev) {
107
+ var next = {}
108
+ for (var k in prev) next[k] = prev[k]
109
+ next[key] = value
110
+ return next
111
+ })
112
+ }
113
+
114
+ var doRun = function () {
115
+ if (typeof props.run !== 'function') return
116
+ setBusy(true); setError('')
117
+ props.run(prompt).then(function (r) {
118
+ setJob({ jobId: r.jobId, status: 'running', output: '', code: null })
119
+ }).catch(function (e) { setError(String(e && e.message)) }).finally(function () { setBusy(false) })
120
+ }
121
+ var canOpenSession = typeof props.onOpenSession === 'function' && job !== null && job.sessionId
122
+ var openSession = function () { props.onOpenSession(job.sessionId) }
123
+ var copy = function () {
124
+ if (typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText) {
125
+ navigator.clipboard.writeText(prompt).then(function () { setCopied(true); setTimeout(function () { setCopied(false) }, 1500) }).catch(function () {})
126
+ }
127
+ }
128
+ var statusText = job === null ? '' : job.status === 'running' ? (labels.running || 'running') : job.status === 'done' ? (labels.done || 'done') : (labels.failed || 'failed') + (job.code != null ? ' (' + job.code + ')' : '')
129
+ // 完成态插槽:提供后 job done 由插槽全权渲染(footer 置空,操作按钮插槽自承)
130
+ var completedSlot = typeof props.completedView === 'function' && job !== null && job.status === 'done'
131
+
132
+ return h('div', { onClick: function (e) { if (e.target === e.currentTarget && props.onClose) props.onClose() }, style: { position: 'fixed', inset: 0, zIndex: 2147483000, background: 'rgba(0,0,0,.45)', display: 'flex', alignItems: 'center', justifyContent: 'center' } },
133
+ h('div', { style: { width: 'min(640px,92vw)', maxHeight: '86vh', overflow: 'auto', background: 'var(--dsw-alias-bg-layer-1,#fff)', border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', borderRadius: '16px', padding: '20px', display: 'flex', flexDirection: 'column', gap: 12, color: 'var(--dsw-alias-label-primary,inherit)', font: 'var(--dsw-font-family,inherit)' } },
134
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: 10 } },
135
+ h('div', { style: { fontSize: 17, fontWeight: 600 } }, title || ''),
136
+ h('button', { onClick: props.onClose, style: Object.assign({}, btnStyle, { marginLeft: 'auto', width: 28, height: 28, padding: 0, borderRadius: 28 }) }, '✕')),
137
+ hint ? h('div', { style: { fontSize: 12, opacity: .7 } }, hint) : null,
138
+ // 模板参数输入区(idle 态;值实时替换进 prompt,位于 prompt 上方与 ntd 同布局)
139
+ paramDefs.length > 0 ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10 } },
140
+ paramDefs.map(function (d) {
141
+ return h('label', { key: d.key, style: { display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12, opacity: .85 } },
142
+ h('span', null, d.label || d.key),
143
+ d.multiline
144
+ ? h('textarea', { value: paramValues[d.key] || '', placeholder: d.placeholder || '', onChange: function (e) { setParam(d.key, e.target.value) }, spellCheck: false, style: Object.assign({}, paramStyle, { minHeight: 64, resize: 'vertical' }) })
145
+ : h('input', { value: paramValues[d.key] || '', placeholder: d.placeholder || '', onChange: function (e) { setParam(d.key, e.target.value) }, style: paramStyle }))
146
+ })) : null,
147
+ (props.rows || []).length > 0 ? h('div', { style: { display: 'flex', flexDirection: 'column', gap: 4, fontSize: 13 } },
148
+ props.rows.map(function (r, i) {
149
+ return r[1] ? h('div', { key: i }, h('b', null, r[0] + ':'), h('span', null, r[1])) : null
150
+ })) : null,
151
+ h('textarea', { value: prompt, onChange: function (e) { setPrompt(e.target.value) }, spellCheck: false, style: inputStyle }),
152
+ error !== '' ? h('div', { style: { fontSize: 12, color: 'var(--dsw-alias-state-error,#c75050)' } }, error) : null,
153
+ completedSlot
154
+ ? props.completedView({ job: job, output: job.output || '', close: props.onClose, retry: doRun })
155
+ : (job !== null ? h('div', null,
156
+ h('div', { style: { fontSize: 12, opacity: .7, margin: '4px 0' } }, (labels.outputLabel || 'Output') + ' · ' + statusText),
157
+ h('pre', { style: { maxHeight: 220, margin: 0, overflow: 'auto', whiteSpace: 'pre-wrap', fontSize: 12, background: 'var(--dsw-alias-bg-layer-2,transparent)', border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.2))', borderRadius: '8px', padding: '8px' } }, job.output || '…')) : null),
158
+ completedSlot ? null : h('div', { style: { display: 'flex', gap: 8 } },
159
+ canOpenSession ? h('button', { onClick: openSession, style: btnStyle }, labels.openSession || 'Open chat') : null,
160
+ h('button', { onClick: copy, style: btnStyle }, copied ? (labels.copied || 'Copied') : (labels.copy || 'Copy')),
161
+ h('button', { onClick: doRun, disabled: busy || (job !== null && job.status === 'running'), style: primaryStyle }, job !== null && job.status === 'running' ? (labels.running || 'Running…') : (labels.run || 'Run')))))
162
+ }
163
+ }
164
+
165
+ // ── 共享事件推送枢纽 ─────────────────────────────────────────────────
166
+ // 解决:dsh web 网关是 HTTP/1.1,同源并发只有 ~6 条连接,每个插件自建
167
+ // 永久 SSE 会把预算占满、首页全部排队。全页面只开**一条**事件通道
168
+ // (WebSocket 优先,握手后豁免于连接预算;连续 3 次握手失败自动降级
169
+ // SSE 总线),按帧里的 plugin 字段分发。服务端由任意消费者经
170
+ // PluginKit.ensureHostHub(ctx, {webServer, connection}) 协调出唯一路由
171
+ // (本包 src/index.js)。
172
+ //
173
+ // 关键实现约束:**总线状态必须挂 window.__dshEventHub**,不能放本文件
174
+ // 模块作用域——每个消费者 bundle 都内联一份本源码,模块状态是每副本
175
+ // 独立的,只有 window 上的状态能跨副本共享(否则每插件各开一条 ws)。
176
+ var HUB_WS_PATH = '/dsh-event-hub/ws'
177
+ var HUB_SSE_PATH = '/dsh-event-hub/api/stream'
178
+
179
+ function hubState() {
180
+ if (!window.__dshEventHub) {
181
+ window.__dshEventHub = {
182
+ subscribers: new Map(), // plugin -> Set<fn(data, frame)>
183
+ started: false,
184
+ ws: null,
185
+ wsAttempts: 0,
186
+ sse: null,
187
+ }
188
+ }
189
+ window.__dshEventHub.subscribe = function (plugin, fn) {
190
+ return hubSubscribe(plugin, fn)
191
+ }
192
+ window.__dshEventHub.readyState = function () {
193
+ if (hubState().ws && hubState().ws.readyState === 1) return 1
194
+ if (hubState().sse) return 1
195
+ return 0
196
+ }
197
+ return window.__dshEventHub
198
+ }
199
+
200
+ function hubDispatch(data, frame) {
201
+ var st = hubState()
202
+ var set = st.subscribers.get(frame.plugin)
203
+ if (!set) return
204
+ set.forEach(function (fn) {
205
+ try { fn(data, frame) } catch (e) { /* 单个订阅者出错不影响其他 */ }
206
+ })
207
+ }
208
+
209
+ function hubSubscribe(plugin, fn) {
210
+ var st = hubState()
211
+ var set = st.subscribers.get(plugin)
212
+ if (!set) { set = new Set(); st.subscribers.set(plugin, set) }
213
+ set.add(fn)
214
+ return function () { st.subscribers.get(plugin).delete(fn) }
215
+ }
216
+
217
+ /** SSE 兜底总线(老宿主 ws 不可用/连续握手失败时)。 */
218
+ function startSseHub() {
219
+ var st = hubState()
220
+ if (st.mode === 'sse' && st.sse) return
221
+ st.mode = 'sse'
222
+ st.sse = new EventSource(HUB_SSE_PATH)
223
+ st.sse.onmessage = function (msg) {
224
+ var frame
225
+ try { frame = JSON.parse(msg.data) } catch (e) { return }
226
+ if (!frame || typeof frame.plugin !== 'string') return
227
+ hubDispatch(frame.data, frame)
228
+ }
229
+ }
230
+
231
+ /** ws 主通道:自动重连;连续 3 次未握手成功则永久降级 SSE。 */
232
+ function startWsHub() {
233
+ var st = hubState()
234
+ if (st.ws) return
235
+ try {
236
+ var proto = location.protocol === 'https:' ? 'wss://' : 'ws://'
237
+ st.wsAttempts++
238
+ st.ws = new WebSocket(proto + location.host + HUB_WS_PATH)
239
+ st.ws.onopen = function () { st.wsAttempts = 0 }
240
+ st.ws.onmessage = function (msg) {
241
+ var frame
242
+ try { frame = JSON.parse(msg.data) } catch (e) { return }
243
+ if (!frame || typeof frame.plugin !== 'string') return
244
+ hubDispatch(frame.data, frame)
245
+ }
246
+ st.ws.onclose = function () {
247
+ st.ws = null
248
+ if (st.wsAttempts < 3) setTimeout(function () { startTransport() }, 3000)
249
+ else startSseHub()
250
+ }
251
+ st.ws.onerror = function () { try { st.ws.close() } catch (e) { /* 已关 */ } }
252
+ } catch (e) {
253
+ startSseHub()
254
+ }
255
+ }
256
+
257
+ function startTransport() {
258
+ var st = hubState()
259
+ if (st.started && (st.ws || st.sse)) return
260
+ // WebSocket 优先(握手后豁免于 h1.1 连接预算);连续 3 次握手失败转 SSE
261
+ if (typeof WebSocket !== 'undefined' && typeof location !== 'undefined' && st.wsAttempts < 3) startWsHub()
262
+ else startSseHub()
263
+ }
264
+
265
+ /**
266
+ * 订阅某插件的事件流:枢纽就绪则共享连接(零额外连接);
267
+ * 浏览器不支持时返回 null,调用方自行回退(自有 SSE / 轮询)。
268
+ */
269
+ function connectEvents(plugin, onFrame, onState) {
270
+ if (typeof window === 'undefined' || typeof EventSource === 'undefined') return null
271
+ startTransport()
272
+ var off = hubSubscribe(plugin, function (data, frame) {
273
+ if (onState) { try { onState('live') } catch (e) {} }
274
+ onFrame(data, frame)
275
+ })
276
+ var st = hubState()
277
+ if (onState) { try { onState(st.ws || st.sse ? 'live' : 'connecting') } catch (e) {} }
278
+ return off
279
+ }
280
+
281
+ return { substituteParams: substituteParams, makeActionShareDialog: makeActionShareDialog, connectEvents: connectEvents }
282
+ })()
283
+
284
+ /**
285
+ * dsh-workflow-execute — Browser half(工作流管理)。
286
+ *
287
+ * 三个挂载面:
288
+ * - 侧栏入口行(DOM 注入「新会话」下方,与任务看板同一家族块;滚动数字 = 我的 | 内置)。
289
+ * - 主页面:中栏接管视图(taskboard 同款,容器挂会话列末尾、html[data-dswfe-active] 驱动开合,
290
+ * 盖会话列不盖侧栏;列表+详情/编辑器工作台;Esc / 点会话行 / 与其他面板互斥时关闭)。
291
+ * - 兜底:会话列缺席的退化壳层下,开面板 450ms 后容器强制挂 body 退回全屏浮层。
292
+ *
293
+ * 数据流:EventSource /dsh-workflow-execute/events 变更帧 → 全量 refetch + revision 追赶
294
+ * (taskboard S16 同款);编辑走 baseHash 乐观锁,409 给「重新加载 / 仍然覆盖」。
295
+ *
296
+ * React 是 loader 平台模块;plain Node(契约测试)下降级为最小 shim。
297
+ */
298
+
299
+ let __React = null
300
+ try { __React = require('react') } catch {}
301
+ if (!__React || typeof __React.createElement !== 'function') {
302
+ __React = {
303
+ createElement(type, props, ...kids) {
304
+ return { type, props: props || {}, kids: kids.flat(9).filter(k => k !== null && k !== undefined && k !== false && k !== true) }
305
+ },
306
+ useState(init) { const v = [typeof init === 'function' ? init() : init]; return [v[0], x => { v[0] = typeof x === 'function' ? x(v[0]) : x }] },
307
+ useEffect() {}, useMemo(fn) { return fn() }, useRef(v = null) { return { current: v } },
308
+ }
309
+ }
310
+ const { createElement: h, useState, useEffect, useMemo, useRef, useCallback } = __React
311
+ const useLayoutEffect = __React.useLayoutEffect || useEffect // React shim 兜底
312
+
313
+ const CLIENT_NAME = 'dsh-workflow-execute'
314
+ // API 基址随页面走:子路径反代(如 https://host/app/dsh/)下,绝对路径 /dsh-workflow-execute
315
+ // 会打到站点根而 404。与宿主官方客户端一致,用 document.baseURI 推导(dsh-sync#14 同款)。
316
+ const API = (() => {
317
+ try {
318
+ const base = (typeof document !== 'undefined' && document.baseURI) || (typeof location !== 'undefined' ? location.href : '/')
319
+ return new URL('dsh-workflow-execute', new URL('.', base)).pathname.replace(/\/+$/, '')
320
+ } catch { return '/dsh-workflow-execute' }
321
+ })()
322
+ const NS = 'dshProcess'
323
+ const PANEL_NAME = 'dsh-workflow-execute'
324
+ const ACTIVATE_EVENT = 'dsh-panel-activate'
325
+ const ENTRY_ATTR = 'data-dswfe-entry'
326
+ // 中栏接管(taskboard 同款)开合属性 + 兄弟面板属性表
327
+ const PRC_ACTIVE_ATTR = 'data-dswfe-active'
328
+ const PRC_OTHER_ACTIVE_ATTRS = ['data-dsh-atb-active', 'data-dsh-taskboard-active', 'data-dsh-ssh-active', 'data-dsh-git-active', 'data-dsh-kb-active']
329
+ const PRC_SIDEBAR_ROW_SELECTOR = '[class*="sessionRow"], [class*="projectRow"], [class*="searchResultRow"], [class*="newSession"]'
330
+ // 侧栏整列:点「文档管理/插件/记忆系统」这类导航项也要退出中栏接管,否则 html[data-dswfe-active]
331
+ // 会把壳层渲染在中栏的其他视图一起隐藏,看起来像切不回去。
332
+ const PRC_SIDEBAR_COLUMN_SELECTOR = '[data-pane="sidebar"], [class*="sidebarCol"], .dshDesktopUpstreamSidebar, .dshDesktopSidebarSurface'
333
+ const PREFS_KEY = 'dswfe:prefs'
334
+
335
+ // ── i18n ─────────────────────────────────────────────────────────────────
336
+
337
+ const ZH = {
338
+ title: '工作流',
339
+ entryAria: '打开工作流',
340
+ entryTitle: '工作流 — 我的 {user} · 内置 {bundled}',
341
+ count: '我的 {user} · 内置 {bundled}',
342
+ searchPlaceholder: '搜索名称 / 描述…',
343
+ filterAll: '全部来源', filterUser: '我的', filterBundled: '内置',
344
+ categoryAll: '全部分类', complexityAll: '全部复杂度',
345
+ sortDefault: '按名称', sortUpdated: '按更新时间', sortComplexity: '按复杂度', sortLinks: '按环节数',
346
+ newTask: '新建', newBlank: '空白工作流', newFromExisting: '复制现有…',
347
+ importBtn: '导入', exportBtn: '导出', exportAll: '全部(zip)', exportUser: '我的库(zip)', exportOne: '本工作流(yaml)',
348
+ settingsBtn: '设置', aiBtn: 'AI 生成',
349
+ close: '关闭', cancel: '取消', save: '保存', confirm: '确认', delete: '删除', edit: '编辑', copy: '复制', rename: '重命名',
350
+ copyToMine: '复制到我的库', reload: '重新加载', overwrite: '仍然覆盖', discard: '放弃修改', keepEditing: '继续编辑',
351
+ tabOverview: '概览', tabStructure: '结构', tabYaml: 'YAML',
352
+ loading: '加载中…', emptyList: '没有匹配的工作流', emptyListHint: '试试清空筛选,或「新建 / 导入」一个工作流',
353
+ emptyDetail: '从左侧选择一个工作流', selectFirst: '左侧选择工作流后在这里看概览、结构与 YAML',
354
+ errOne: '处错误', warnOne: '处警告',
355
+ readOnly: '内置 · 只读', mine: '我的', bundled: '内置',
356
+ limits: '限额', steps: '环节执行上限', tokens: 'token 上限', unlimited: '不限',
357
+ abnormal: '异常触发', phases: '阶段', links: '环节',
358
+ diagnostics: '诊断', noIssues: '结构正常 · 没有发现错误或警告',
359
+ name: '名称', displayName: '显示名', guid: 'GUID', version: '版本', category: '分类', complexity: '复杂度',
360
+ prompt: '指令 prompt', executor: '执行器', expert: '专家', skills: '技能', model: '模型',
361
+ artifacts: '期望产物', gates: '门禁', flow: '流转', rework: '返工上限', acceptance: '验收标准', reviewPrompt: '复核提示词', reviewType: '复核方式',
362
+ onSuccess: '成功后', onGateFail: '门禁不过', onRatingFail: '评级不过',
363
+ flowNext: '下一环节', flowEnd: '结束', flowBreak: '中止(询问用户)',
364
+ flowBreakStop: '中止(停下问我)', flowJumpTo: '跳到「环节{no} · {name}」',
365
+ editorTitle: '编辑', editorCreate: '新建工作流', editorCopy: '复制工作流',
366
+ unsaved: '未保存', saved: '已保存', validating: '校验中…',
367
+ saveConflict: '文件已被外部修改(可能是其他编辑器)。', forcedHint: '覆盖将丢弃外部改动。',
368
+ dirtyGuard: '有未保存的修改,确定放弃吗?',
369
+ deleteConfirm: '删除后移入回收站(.trash),确定删除',
370
+ createName: '工作流名(文件名,不含 .yaml)', createDir: '子目录(可选,如 software)', createDisplayName: '显示名(可选)',
371
+ copyName: '新工作流名', importTitle: '导入工作流', importHint: '选择或拖入 .yaml / .yml(可多选),导入到我的库',
372
+ importOverwrite: '覆盖同名文件', importPick: '选择文件', importResults: '导入结果',
373
+ importCreated: '已导入', importOverwritten: '已覆盖', importExists: '同名已存在(未导入)', importInvalid: '校验未通过',
374
+ settingsTitle: '工作流库设置', settingsUserRoot: '我的库根目录', settingsBundledRoot: '内置库根目录(只读)',
375
+ settingsMaxDepth: '扫描深度', settingsSaved: '设置已保存,正在重扫',
376
+ renameTitle: '重命名显示名', newName: '新显示名', renameHint: '只改界面显示的名称,文件名与标识不变',
377
+ aiTitle: 'AI 生成工作流', aiHint: '描述要解决的需求,AI 会产出一版工作流 YAML;生成后可校验并写入我的库',
378
+ aiRequirement: '要做什么(需求描述)', aiComplexity: '复杂度(低 / 中 / 高)', aiReference: '参考工作流(可选)',
379
+ aiPreviewTitle: '生成结果预览', aiSaveName: '写入名称', aiSave: '写入我的库', aiParseFail: '输出里没有找到 YAML 代码块',
380
+ copied: '已复制', copyYaml: '复制 YAML',
381
+ openSession: '打开会话', aiRunning: '生成中…', aiDone: '生成完成',
382
+ openLib: '打开工作流库', settingsSectionHint: '工作流 = 多阶段 agent 工作流模板;此处配置工作流库根目录。',
383
+ validate: '校验', linesCount: '{n} 行',
384
+ validateOk: '校验通过:0 错误 0 警告', validateResult: '校验完成:{e} 个错误 · {w} 个警告',
385
+ toastSaved: '已保存', toastForceSaved: '已覆盖保存', toastCopied: '已复制到我的库', toastRenamed: '已重命名',
386
+ toastTrashed: '已移入回收站(.trash)', toastImported: '{n} 个工作流已导入', toastAiSaved: '已写入我的库',
387
+ copyPrompt: '复制 Prompt', aiOutput: '输出', aiFailed: '失败', aiRequirementPh: '例如:把口头需求整理成 PRD 并拆解成开发任务',
388
+ kitMissing: 'dsh-plugin-kit 未内联(构建问题)', nameRule: '名称不能为空、不能含 / 或 \\、不能以点开头',
389
+ sessionUnavailable: '当前页面拿不到会话服务,无法跳转',
390
+ atAgent: '给 agent', atAgentTitle: '@ 进对话框,让 agent 帮你修改这个工作流(输入你的修改要求后发送)',
391
+ atAgentBundledTitle: '@ 进对话框(内置只读,agent 会改完存成你的新工作流)',
392
+ atAgentBundledHint: '(这是内置只读工作流——请改完用 workflow_save 存成我的库里的新工作流)',
393
+ atInserted: '已 @ 进对话框:输入你的修改要求后发送', atCopied: '没找到输入框,已复制引用到剪贴板',
394
+ viewLib: '工作流', viewExec: '执行记录',
395
+ runCreate: '▶ 按工作流执行', runWorkspace: '工作区(可选)', runStarted: '运行已发起',
396
+ workspaceDefault: '默认(不绑定)',
397
+ statusQueued: '排队中', statusRunning: '运行中', statusPaused: '已暂停', statusAwaiting: '等待裁决', statusAwaitingReview: '等待人工审核',
398
+ statusDone: '已完成', statusStopped: '已停止', statusFailed: '失败',
399
+ pause: '暂停', resume: '继续', stopRun: '停止运行', stopConfirm: '停止后当前环节结果作废,确定停止?',
400
+ noRuns: '还没有运行记录', noRunsHint: '到「工作流」打开一个工作流,点「▶ 按工作流执行」发起一次运行',
401
+ emptyRun: '左侧选择一次运行查看看板',
402
+ runLoadFailed: '运行详情加载失败',
403
+ retryLoad: '重试',
404
+ progress: '{done}/{total} 环节', attemptN: '第 {n} 次尝试', reworkN: '返工 ×{n}',
405
+ usageTitle: '输入 {input} · 输出 {output} · {calls} 次调用(含门禁评审)', usageTotal: 'Token',
406
+ artifactsTitle: '产物', artifactMissing: '未生成',
407
+ artifactsNone: '还没有观察到文件写入:执行中用 write / edit / str-replace-editor 改动的文件会出现在这里',
408
+ fileViewTitle: '产物预览', fileBinary: '二进制文件,暂不支持预览', fileTruncated: '文件较大,仅显示前 {size},完整内容请在工作区打开',
409
+ viewFiles: '查看输出物', linkFilesTitle: '环节产物', diffLabel: '变更', contentLabel: '内容', noFiles: '本环节没有声明产物,也没有观察到文件写入', pickFile: '选择左侧文件后在这里查看内容',
410
+ gateLabel: '门禁', gateScore: '{score} 分(线 {min})',
411
+ openSession: '打开会话', outputLabel: '实时输出', retryLink: '从本环节重新运行', skipLink: '跳过本环节',
412
+ breakTitle: '门禁未过,等待你的裁决', decisionRetry: '重试本环节', decisionSkip: '跳过本环节', decisionStop: '中止运行',
413
+ humanReviewTitle: '人工审核,等待你的验收', decisionApprove: '审核通过,继续下一步', decisionReject: '打回重做',
414
+ gateReasonLabel: '评审理由', linkAwaitingReviewHint: '该环节已执行完毕,请查看产物与执行报告后裁决',
415
+ linkPending: '待跑', linkDone: '完成', linkRunning: '进行中', linkGateFailed: '门禁未过', linkSkipped: '跳过', linkFailed: '失败', linkAbandoned: '中断', linkAwaitingReview: '待人工审核', linkApproved: '审核通过', linkRejected: '打回重做',
416
+ currentStep: '当前', runError: '运行异常',
417
+ runUserInput: '需求 / 要处理的问题(必填,只注入第一个环节)', runUserInputPh: '例如:把「XX」这条口头需求整理成 PRD 并拆解任务',
418
+ formMode: '画布', yamlMode: 'YAML', formUnparseable: '当前 YAML 有语法错误,请切到 YAML 模式修复后再用画布',
419
+ canvasHint: '点击节点在右侧编辑属性;点空白处看工作流属性', canvasEmpty: '还没有任何阶段,点「+ 添加阶段」开始',
420
+ propGlobal: '工作流属性', propPhase: '阶段属性', propLink: '环节属性',
421
+ canvasDelPhase: '删除阶段「{name}」及其下 {n} 个环节?', canvasDelLink: '删除环节「{name}」?',
422
+ formProvider: '供应商', modelDefault: '(默认)', modelProvDefault: '(供应商默认)',
423
+ skillsPick: '点选技能…', skillsNone: '无可用技能', skillsClear: '清空已选({n})',
424
+ formBasic: '基本信息', formLimits: '限额', formPhases: '阶段', formAddPhase: '+ 添加阶段', formAddLink: '+ 添加环节',
425
+ formDelPhase: '删除阶段', formDelLink: '删除环节', formAddGate: '+ 添加门禁', formGateName: '门禁名(如 证据齐全)', formGateMin: '分数线',
426
+ formName: '环节名', formGates: '门禁', formGateType: '门禁类型', formGateArtifact: '产物名',
427
+ formSkillsPh: '技能1, 技能2',
428
+ formDisplayName: '显示名', formVersion: '版本', formCategory: '分类', formComplexity: '复杂度', formDescription: '描述',
429
+ cxLow: '低', cxMid: '中', cxHigh: '高',
430
+ formMaxSteps: '环节执行上限(空=不限)', formMaxTokens: 'token 上限(空=不限)', formPrompt: '指令 prompt',
431
+ formAcceptance: '验收标准', formPhaseName: '阶段名', formPhaseSpec: '阶段说明', formExecutor: '执行器', formExpert: '专家',
432
+ formModel: '模型', formReviewType: '复核方式', formMaxRework: '返工上限', formOnSuccess: '成功后',
433
+ formOnGateFail: '门禁不过', formOnRatingFail: '评级不过', formNewLinkName: '新环节',
434
+ tabFlow: '流程图',
435
+ flowGate: '门禁 ≥{min}', flowRework: '返工≤{n}', flowNoGate: '无门禁',
436
+ flowLegendForward: '正常流转', flowLegendJump: '跳转', flowLegendFail: '门禁未过回跳', flowLegendBreak: '中止(不连线)',
437
+ flowRunCurrent: '当前环节', flowRunDone: '已完成', flowRunGateFailed: '门禁未过', flowRunSkipped: '跳过', flowRunFailed: '失败',
438
+ flowNoParsed: '工作流无法解析,无法绘制流程图',
439
+ flowReviewAi: 'AI评审', flowReviewHuman: '人工评审', flowReviewNone: '无需评审',
440
+ flowScore: '得分:{score}',
441
+ flowStartLabel: '开始', flowEndLabel: '结束',
442
+ linkNo: '环节{n}', phaseNo: '阶段{n}',
443
+ execAI: 'AI 评审', execHuman: '人工评审', execNone: '无需评审',
444
+ reviewAi: 'AI 评审', reviewHuman: '人工评审', reviewNone: '无需评审',
445
+ overviewTitle: '概述', overviewEmpty: '这个工作流还没有环节',
446
+ helpReviewType: '环节由谁判定是否通过:AI = 评审会话按门禁分数自动判定;人工 = 执行完停下等人审核;无需 = 直接进入下一环节。',
447
+ helpPrompt: '发给执行会话的指令正文。写清要做什么、产物写到哪个文件、执行报告要写什么。',
448
+ helpAcceptance: '本环节的验收标准,门禁评审时按它打分。',
449
+ helpGates: '门禁是一组评审规则:评审分数低于分数线即判不通过,按「门禁不过」流转。',
450
+ helpGateMin: '门禁分数线(0-100)。评审分数达到该值才算通过。',
451
+ helpCanvas: '点击节点在右侧编辑属性;点空白处看工作流属性。',
452
+ helpSessionMode: '多会话:每个环节开一个新会话,门禁单独开会话,上下文互不干扰。单会话:整条流程共用一个会话(门禁也在其中),省 token 但上下文会累积。',
453
+ sessionMode: '对话模式', sessionMulti: '多会话(每环节一个)', sessionSingle: '单会话(全流程一个)', requestLabel: '需求',
454
+ startedAt: '开始', endedAt: '结束', durationTotal: '总耗时', tokenLabel: 'TOKEN',
455
+ durationUnknown: '—',
456
+ viewArtifacts: '查看输出物', deleteRun: '删除', deleteRunConfirm: '删除这条运行记录?',
457
+ }
458
+
459
+ const EN = {
460
+ title: 'Workflows', entryAria: 'Open workflow library', entryTitle: 'Workflows — mine {user} · bundled {bundled}',
461
+ count: 'mine {user} · bundled {bundled}', searchPlaceholder: 'Search name / description…',
462
+ filterAll: 'All sources', filterUser: 'Mine', filterBundled: 'Bundled',
463
+ categoryAll: 'All categories', complexityAll: 'All complexities',
464
+ sortDefault: 'By name', sortUpdated: 'By updated', sortComplexity: 'By complexity', sortLinks: 'By links',
465
+ newTask: 'New', newBlank: 'Blank workflow', newFromExisting: 'Duplicate existing…',
466
+ importBtn: 'Import', exportBtn: 'Export', exportAll: 'All (zip)', exportUser: 'Mine (zip)', exportOne: 'This one (yaml)',
467
+ settingsBtn: 'Settings', aiBtn: 'AI generate',
468
+ close: 'Close', cancel: 'Cancel', save: 'Save', confirm: 'OK', delete: 'Delete', edit: 'Edit', copy: 'Duplicate', rename: 'Rename',
469
+ copyToMine: 'Copy to my library', reload: 'Reload', overwrite: 'Overwrite anyway', discard: 'Discard', keepEditing: 'Keep editing',
470
+ tabOverview: 'Overview', tabStructure: 'Structure', tabYaml: 'YAML',
471
+ loading: 'Loading…', emptyList: 'No matching workflows', emptyListHint: 'Try clearing filters, or create / import one',
472
+ emptyDetail: 'Pick a workflow on the left', selectFirst: 'Overview, structure and YAML show up here after you select one',
473
+ errOne: ' error(s)', warnOne: ' warning(s)',
474
+ readOnly: 'Bundled · read-only', mine: 'Mine', bundled: 'Bundled',
475
+ limits: 'Limits', steps: 'max step runs', tokens: 'max tokens', unlimited: 'unlimited',
476
+ abnormal: 'Abnormal trigger', phases: 'phases', links: 'links',
477
+ diagnostics: 'Diagnostics', noIssues: 'Structure looks fine · no errors or warnings',
478
+ name: 'Name', displayName: 'Display name', guid: 'GUID', version: 'Version', category: 'Category', complexity: 'Complexity',
479
+ prompt: 'Prompt', executor: 'Executor', expert: 'Expert', skills: 'Skills', model: 'Model',
480
+ artifacts: 'Expected artifacts', gates: 'Gates', flow: 'Flow', rework: 'Max rework', acceptance: 'Acceptance', reviewPrompt: 'Review prompt', reviewType: 'Review',
481
+ onSuccess: 'On success', onGateFail: 'On gate fail', onRatingFail: 'On rating fail',
482
+ flowNext: 'next link', flowEnd: 'end', flowBreak: 'break (ask user)',
483
+ flowBreakStop: 'break (stop and ask me)', flowJumpTo: 'Jump to link {no} · {name}',
484
+ editorTitle: 'Edit', editorCreate: 'New workflow', editorCopy: 'Duplicate workflow',
485
+ unsaved: 'Unsaved', saved: 'Saved', validating: 'Validating…',
486
+ saveConflict: 'The file was changed externally (another editor).', forcedHint: 'Overwriting discards those changes.',
487
+ dirtyGuard: 'Discard unsaved changes?',
488
+ deleteConfirm: 'Delete moves the file into .trash. Delete',
489
+ createName: 'Workflow name (file name, no .yaml)', createDir: 'Sub-directory (optional, e.g. software)', createDisplayName: 'Display name (optional)',
490
+ copyName: 'New workflow name', importTitle: 'Import workflows', importHint: 'Pick or drop .yaml / .yml files (multi-select) into MY library',
491
+ importOverwrite: 'Overwrite existing files', importPick: 'Choose files', importResults: 'Results',
492
+ importCreated: 'imported', importOverwritten: 'overwritten', importExists: 'skipped (exists)', importInvalid: 'invalid',
493
+ settingsTitle: 'Workflow library settings', settingsUserRoot: 'My library root', settingsBundledRoot: 'Bundled library root (read-only)',
494
+ settingsMaxDepth: 'Scan depth', settingsSaved: 'Settings saved; rescanning',
495
+ renameTitle: 'Rename display name', newName: 'New display name', renameHint: 'Only the shown name changes; file name and id stay.',
496
+ aiTitle: 'AI generate workflow', aiHint: 'Describe the need; AI drafts a workflow YAML you can validate and save into MY library',
497
+ aiRequirement: 'What should it do', aiComplexity: 'Complexity (low / medium / high)', aiReference: 'Reference workflow (optional)',
498
+ aiPreviewTitle: 'Generated preview', aiSaveName: 'Save as', aiSave: 'Save to my library', aiParseFail: 'No YAML code block found in the output',
499
+ copied: 'Copied', copyYaml: 'Copy YAML',
500
+ openSession: 'Open chat', aiRunning: 'Generating…', aiDone: 'Generated',
501
+ openLib: 'Open workflow library', settingsSectionHint: 'A workflow is a multi-phase agent workflow template; configure library roots here.',
502
+ validate: 'Validate', linesCount: '{n} lines',
503
+ validateOk: 'Validated: 0 errors, 0 warnings', validateResult: 'Validated: {e} errors · {w} warnings',
504
+ toastSaved: 'Saved', toastForceSaved: 'Overwritten and saved', toastCopied: 'Copied to my library', toastRenamed: 'Renamed',
505
+ toastTrashed: 'Moved to .trash', toastImported: '{n} workflow(es) imported', toastAiSaved: 'Saved to my library',
506
+ copyPrompt: 'Copy prompt', aiOutput: 'Output', aiFailed: 'Failed', aiRequirementPh: 'e.g. turn a verbal requirement into a PRD and split it into dev tasks',
507
+ kitMissing: 'dsh-plugin-kit not inlined (build issue)', nameRule: 'Name must be non-empty, without / or \\, and not start with a dot',
508
+ sessionUnavailable: 'Session service unavailable on this page',
509
+ atAgent: 'Ask agent', atAgentTitle: '@-reference into the composer and let an agent modify this workflow',
510
+ atAgentBundledTitle: '@-reference (bundled is read-only; the agent will save a new workflow into your library)',
511
+ atAgentBundledHint: '(this is a read-only bundled workflow — save your edited version as a new workflow in MY library via workflow_save)',
512
+ atInserted: '@-referenced in the composer: type your change request and send', atCopied: 'Composer not found — reference copied to clipboard',
513
+ viewLib: 'Library', viewExec: 'Runs',
514
+ runCreate: '▶ Run workflow', runWorkspace: 'Workspace (optional)', runStarted: 'Run started',
515
+ workspaceDefault: 'Default (unbound)',
516
+ statusQueued: 'Queued', statusRunning: 'Running', statusPaused: 'Paused', statusAwaiting: 'Awaiting decision', statusAwaitingReview: 'Awaiting manual review',
517
+ statusDone: 'Done', statusStopped: 'Stopped', statusFailed: 'Failed',
518
+ pause: 'Pause', resume: 'Resume', stopRun: 'Stop run', stopConfirm: 'The running link result will be discarded. Stop?',
519
+ noRuns: 'No runs yet', noRunsHint: 'Open a workflow in "Library" and click "▶ Run workflow"',
520
+ emptyRun: 'Pick a run on the left to see its board',
521
+ runLoadFailed: 'Failed to load this run',
522
+ retryLoad: 'Retry',
523
+ progress: '{done}/{total} links', attemptN: 'attempt {n}', reworkN: 'rework ×{n}',
524
+ usageTitle: 'in {input} · out {output} · {calls} calls (incl. gate review)', usageTotal: 'Tokens',
525
+ artifactsTitle: 'Artifacts', artifactMissing: 'missing',
526
+ artifactsNone: 'No file writes observed: files changed via write / edit / str-replace-editor during execution appear here',
527
+ fileViewTitle: 'Artifact preview', fileBinary: 'Binary file — preview not supported', fileTruncated: 'File is large; showing the first {size}. Open it in the workspace for the full content.',
528
+ viewFiles: 'Artifacts', linkFilesTitle: 'Link artifacts', diffLabel: 'Diff', contentLabel: 'Content', noFiles: 'No artifacts declared or observed for this link', pickFile: 'Pick a file on the left to see its content',
529
+ gateLabel: 'Gate', gateScore: '{score} (min {min})',
530
+ openSession: 'Open chat', outputLabel: 'Live output', retryLink: 'Rerun from this link', skipLink: 'Skip link',
531
+ breakTitle: 'Gate failed — awaiting your decision', decisionRetry: 'Retry this link', decisionSkip: 'Skip this link', decisionStop: 'Stop run',
532
+ humanReviewTitle: 'Manual review — awaiting your approval', decisionApprove: 'Approve and continue', decisionReject: 'Reject and redo',
533
+ gateReasonLabel: 'Reason', linkAwaitingReviewHint: 'This link finished; check the artifacts and report, then decide',
534
+ linkPending: 'pending', linkDone: 'done', linkRunning: 'running', linkGateFailed: 'gate failed', linkSkipped: 'skipped', linkFailed: 'failed', linkAbandoned: 'abandoned', linkAwaitingReview: 'awaiting review', linkApproved: 'approved', linkRejected: 'rejected',
535
+ currentStep: 'current', runError: 'run error',
536
+ runUserInput: 'Requirement / what to work on (required, injected into the first link only)', runUserInputPh: 'e.g. turn requirement XX into a PRD and split tasks',
537
+ formMode: 'Canvas', yamlMode: 'YAML', formUnparseable: 'YAML has syntax errors — fix them in YAML mode before using the canvas',
538
+ canvasHint: 'Click a node to edit its properties on the right; click empty space for workflow properties', canvasEmpty: 'No phases yet — click "+ Add phase" to start',
539
+ propGlobal: 'Workflow properties', propPhase: 'Phase properties', propLink: 'Link properties',
540
+ canvasDelPhase: 'Delete phase "{name}" and its {n} link(s)?', canvasDelLink: 'Delete link "{name}"?',
541
+ formProvider: 'Provider', modelDefault: '(default)', modelProvDefault: '(provider default)',
542
+ skillsPick: 'Pick skills…', skillsNone: 'No skills available', skillsClear: 'Clear selection ({n})',
543
+ formBasic: 'Basics', formLimits: 'Limits', formPhases: 'Phases', formAddPhase: '+ Add phase', formAddLink: '+ Add link',
544
+ formDelPhase: 'Delete phase', formDelLink: 'Delete link', formAddGate: '+ Add gate', formGateName: 'Gate name (e.g. evidence provided)', formGateMin: 'Min score',
545
+ formName: 'Link name', formGates: 'Gates', formGateType: 'Gate type', formGateArtifact: 'Artifact',
546
+ formSkillsPh: 'skill1, skill2',
547
+ formDisplayName: 'Display name', formVersion: 'Version', formCategory: 'Category', formComplexity: 'Complexity', formDescription: 'Description',
548
+ cxLow: 'Low', cxMid: 'Medium', cxHigh: 'High',
549
+ formMaxSteps: 'Max step runs (empty = unlimited)', formMaxTokens: 'Max tokens (empty = unlimited)', formPrompt: 'Prompt',
550
+ formAcceptance: 'Acceptance', formPhaseName: 'Phase name', formPhaseSpec: 'Phase spec', formExecutor: 'Executor', formExpert: 'Expert',
551
+ formModel: 'Model', formReviewType: 'Review', formMaxRework: 'Max rework', formOnSuccess: 'On success',
552
+ formOnGateFail: 'On gate fail', formOnRatingFail: 'On rating fail', formNewLinkName: 'New link',
553
+ tabFlow: 'Flow',
554
+ flowGate: 'gate ≥{min}', flowRework: 'rework≤{n}', flowNoGate: 'no gate',
555
+ flowLegendForward: 'forward', flowLegendJump: 'jump', flowLegendFail: 'gate-fail back', flowLegendBreak: 'break (no edge)',
556
+ flowRunCurrent: 'current', flowRunDone: 'done', flowRunGateFailed: 'gate failed', flowRunSkipped: 'skipped', flowRunFailed: 'failed',
557
+ flowNoParsed: 'Workflow cannot be parsed — cannot draw flow',
558
+ flowReviewAi: 'AI', flowReviewHuman: 'Human', flowReviewNone: 'No review',
559
+ flowScore: 'Score: {score}',
560
+ flowStartLabel: 'Start', flowEndLabel: 'End',
561
+ linkNo: 'Link {n}', phaseNo: 'Phase {n}',
562
+ execAI: 'AI review', execHuman: 'Human review', execNone: 'No review',
563
+ reviewAi: 'AI review', reviewHuman: 'Human review', reviewNone: 'No review',
564
+ overviewTitle: 'Overview', overviewEmpty: 'This workflow has no links yet',
565
+ helpReviewType: 'Who decides whether the link passed: AI = a review session scores against the gate; Human = execution pauses for your approval; None = continue directly.',
566
+ helpPrompt: 'The instruction sent to the execution session. State what to do, which file to write, and what the report must contain.',
567
+ helpAcceptance: 'Acceptance criteria for this link; the gate review scores against it.',
568
+ helpGates: 'A gate is a review rule: a score below the threshold means failed, and the flow follows "on gate fail".',
569
+ helpGateMin: 'Gate threshold (0-100). The review score must reach it to pass.',
570
+ helpCanvas: 'Click a node to edit its properties on the right; click empty space for workflow properties.',
571
+ helpSessionMode: 'Multi-session: one fresh session per link, gates get their own session, contexts stay isolated. Single-session: the whole run shares one session (gates included) — fewer tokens, but context accumulates.',
572
+ sessionMode: 'Conversation mode', sessionMulti: 'Multi-session (one per link)', sessionSingle: 'Single-session (one for the run)', requestLabel: 'Request',
573
+ startedAt: 'Start', endedAt: 'End', durationTotal: 'Total', tokenLabel: 'TOKEN',
574
+ durationUnknown: '—',
575
+ viewArtifacts: 'Artifacts', deleteRun: 'Delete', deleteRunConfirm: 'Delete this run record?',
576
+ }
577
+
578
+ function makeT(bound) {
579
+ return (key, vars) => {
580
+ let out = (bound && bound(key)) || EN[key] || ZH[key] || key
581
+ if (vars) for (const [k, v] of Object.entries(vars)) out = out.split('{' + k + '}').join(String(v))
582
+ return out
583
+ }
584
+ }
585
+
586
+ // ── 样式 ─────────────────────────────────────────────────────────────────
587
+
588
+ const STYLE = `
589
+ .dswfe-entry { display:flex; align-items:center; gap:8px; position:relative; width:calc(100% - 8px); margin:2px 4px; padding:6px 10px; border:none; border-radius:8px; background:transparent; color:var(--dsw-text-secondary, inherit); font:inherit; font-size:13px; cursor:pointer; text-align:left; }
590
+ .dswfe-entry:hover { background:var(--dsw-hover, rgba(128,128,128,.12)); color:var(--dsw-text-primary, inherit); }
591
+ .dswfe-entry[data-active="true"] { background:var(--dsw-active, rgba(128,128,128,.18)); color:var(--dsw-text-primary, inherit); font-weight:500; }
592
+ .dswfe-entry svg { flex:none; }
593
+ .dswfe-entry-stats { margin-left:auto; display:inline-flex; align-items:center; gap:3px; font-size:11px; line-height:1; color:var(--dsw-text-secondary, gray); font-variant-numeric:tabular-nums; white-space:nowrap; }
594
+ .dswfe-entry-sep { opacity:.5; }
595
+ .dswfe-roll { position:relative; display:inline-block; overflow:hidden; height:12px; min-width:1ch; text-align:center; vertical-align:middle; }
596
+ .dswfe-roll[data-stat="user"] { color:#3e63dd; }
597
+ .dswfe-roll[data-stat="bundled"] { color:#8e8e93; }
598
+ .dswfe-rn { display:block; height:12px; line-height:12px; text-align:center; }
599
+ .dswfe-rn-next { position:absolute; left:0; right:0; top:100%; }
600
+ .dswfe-roll[data-dir="down"] .dswfe-rn-next { top:auto; bottom:100%; }
601
+ .dswfe-roll .dswfe-rn { transition:transform .3s cubic-bezier(.25,.1,.25,1); }
602
+ .dswfe-roll[data-anim="1"][data-dir="up"] .dswfe-rn { transform:translateY(-100%); }
603
+ .dswfe-roll[data-anim="1"][data-dir="down"] .dswfe-rn { transform:translateY(100%); }
604
+ @media (prefers-reduced-motion: reduce) { .dswfe-roll .dswfe-rn { transition:none; } }
605
+ [data-sidebar-collapsed] [data-dswfe-entry], [class*="_collapsed"] [data-dswfe-entry] { width:36px; height:36px; min-width:36px; margin:0 0 12px; padding:0; justify-content:center; gap:0; text-align:center; }
606
+ [data-sidebar-collapsed] [data-dswfe-entry] .dswfe-entry-label, [data-sidebar-collapsed] [data-dswfe-entry] .dswfe-entry-stats,
607
+ [class*="_collapsed"] [data-dswfe-entry] .dswfe-entry-label, [class*="_collapsed"] [data-dswfe-entry] .dswfe-entry-stats { display:none; }
608
+
609
+ /* 中栏接管视图(taskboard 同款):容器挂进会话列末尾,html 属性驱动开合,只隐藏列内兄弟。
610
+ * 三代壳层选择器:dev shell data-pane / 官方 CSS-Module centerCol / Desktop 扩展框。 */
611
+ .dswfe-view { display:none; }
612
+ html[data-dswfe-active] [data-pane="conversation"] > *:not([data-dswfe-view]),
613
+ html[data-dswfe-active] [class*="centerCol"] > *:not([data-dswfe-view]),
614
+ html[data-dswfe-active] .dshDesktopConversationSurface > *:not([data-dswfe-view]) { display:none !important; }
615
+ html[data-dswfe-active] .dswfe-view { display:flex; flex-direction:column; height:100%; overflow:hidden; }
616
+ /* 壳层退化(会话列缺席):容器兜底挂 body 时退回全屏浮层,保证入口点击永远有响应 */
617
+ .dswfe-view[data-dswfe-fallback] { position:fixed; inset:0; z-index:2147483000; display:flex; }
618
+ .dswfe-panel { position:relative; flex:1; min-height:0; display:flex; flex-direction:column; overflow:hidden; pointer-events:auto; background:var(--dsw-alias-bg-base, var(--dsw-bg, #fff)); color:var(--dsw-alias-label-primary, var(--dsw-text-primary, inherit)); font:var(--dsw-font-family, inherit); font-size:13px; }
619
+ .dswfe-toolbar { display:flex; align-items:center; gap:8px; flex-wrap:wrap; padding:10px 14px; border-bottom:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.35)); background:var(--dsw-alias-bg-layer-1, transparent); }
620
+ .dswfe-title { font-size:15px; font-weight:600; margin:0; }
621
+ .dswfe-count { font-size:12px; color:var(--dsw-text-secondary, gray); }
622
+ .dswfe-spacer { flex:1; }
623
+ .dswfe-btn { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.35)); background:transparent; color:inherit; border-radius:8px; padding:5px 10px; font:inherit; font-size:13px; cursor:pointer; white-space:nowrap; }
624
+ .dswfe-btn:hover { background:var(--dsw-hover, rgba(128,128,128,.12)); }
625
+ .dswfe-btn[data-primary="true"] { background:var(--dsw-alias-button-primary-fill, var(--dsw-alias-brand-primary, #1f2328)); border-color:transparent; color:var(--dsw-alias-label-primary-inverted, #fff); }
626
+ .dswfe-btn[data-danger="true"] { color:var(--dsw-alias-state-error, #c75050); border-color:var(--dsw-alias-state-error, #c75050); }
627
+ .dswfe-btn:disabled { opacity:.5; cursor:default; }
628
+ .dswfe-input, .dswfe-select { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.35)) !important; background:var(--dsw-alias-bg-layer-2, transparent); color:inherit; border-radius:8px; padding:5px 8px; font:inherit; font-size:13px; }
629
+ .dswfe-input:focus, .dswfe-select:focus, .dswfe-textarea:focus { border-color:var(--dsw-alias-accent, rgba(77,107,254,.85)) !important; outline:2px solid rgba(77,107,254,.35); outline-offset:1px; }
630
+ .dswfe-search { width:170px; }
631
+ .dswfe-body { flex:1; display:flex; min-height:0; }
632
+ .dswfe-list { width:300px; min-width:240px; overflow-y:auto; border-right:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.35)); padding:6px; box-sizing:border-box; }
633
+ .dswfe-group { margin:8px 2px 4px; font-size:11px; color:var(--dsw-text-secondary, gray); display:flex; align-items:center; gap:6px; }
634
+ .dswfe-row { display:flex; flex-direction:column; gap:3px; width:100%; text-align:left; border:1px solid transparent; border-left-width:3px; border-radius:8px; background:transparent; color:inherit; padding:7px 9px; margin:2px 0; cursor:pointer; font:inherit; font-size:13px; position:relative; box-sizing:border-box; }
635
+ .dswfe-row:hover { background:var(--dsw-hover, rgba(128,128,128,.1)); }
636
+ .dswfe-row[data-selected="true"] { background:var(--dsw-active, rgba(128,128,128,.16)); border-color:var(--dsw-alias-border-l2, rgba(128,128,128,.3)); }
637
+ .dswfe-row[data-source="bundled"] { border-left-style:dashed; }
638
+ .dswfe-row[data-complexity="low"] { border-left-color:#3e63dd; }
639
+ .dswfe-row[data-complexity="medium"] { border-left-color:#8e8e93; }
640
+ .dswfe-row[data-complexity="high"] { border-left-color:#8e4ec6; }
641
+ .dswfe-row-name { font-weight:500; display:flex; align-items:center; gap:6px; min-width:0; }
642
+ .dswfe-row-name span.lbl { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
643
+ .dswfe-row-meta { display:flex; gap:6px; align-items:center; font-size:11px; color:var(--dsw-text-secondary, gray); flex-wrap:wrap; }
644
+ .dswfe-badge { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:6px; padding:0 5px; font-size:10px; line-height:16px; white-space:nowrap; }
645
+ .dswfe-badge[data-kind="err"] { color:var(--dsw-alias-state-error, #c75050); border-color:var(--dsw-alias-state-error, #c75050); }
646
+ .dswfe-badge[data-kind="warn"] { color:#b8860b; border-color:#b8860b; }
647
+ .dswfe-dot { width:6px; height:6px; border-radius:6px; display:inline-block; }
648
+ .dswfe-dot[data-kind="err"] { background:var(--dsw-alias-state-error, #c75050); }
649
+ .dswfe-dot[data-kind="warn"] { background:#d9a514; }
650
+ .dswfe-detail { flex:1; min-width:0; overflow-y:auto; padding:14px 18px; box-sizing:border-box; }
651
+ .dswfe-detail-head { display:flex; align-items:flex-start; gap:10px; flex-wrap:wrap; margin-bottom:10px; }
652
+ .dswfe-detail-title { font-size:17px; font-weight:700; margin:0; letter-spacing:-.01em; }
653
+ .dswfe-chips { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin:8px 0 14px; }
654
+ .dswfe-chip { display:inline-flex; align-items:center; gap:4px; border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:999px; padding:2px 10px; font-size:11px; line-height:18px; white-space:nowrap; color:var(--dsw-text-secondary, gray); font-variant-numeric:tabular-nums; background:var(--dsw-alias-bg-layer-2, transparent); }
655
+ .dswfe-actions { margin-left:auto; display:flex; gap:6px; flex-wrap:wrap; }
656
+ .dswfe-tabs { display:flex; gap:2px; border-bottom:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); margin-bottom:12px; }
657
+ .dswfe-tab { border:none; background:transparent; color:var(--dsw-text-secondary, inherit); padding:7px 12px; font:inherit; font-size:13px; cursor:pointer; border-bottom:2px solid transparent; }
658
+ .dswfe-tab[data-on="true"] { color:var(--dsw-text-primary, inherit); font-weight:600; border-bottom-color:var(--dsw-alias-brand-primary, currentColor); }
659
+ .dswfe-desc { white-space:pre-wrap; line-height:1.65; margin:0 0 12px; }
660
+ .dswfe-kv { display:flex; gap:8px; font-size:12px; margin:3px 0; flex-wrap:wrap; }
661
+ .dswfe-kv b { opacity:.7; font-weight:500; }
662
+ .dswfe-diag { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:8px; padding:8px 10px; margin:6px 0; display:flex; flex-direction:column; gap:4px; }
663
+ .dswfe-diag-item { display:flex; gap:8px; align-items:baseline; cursor:pointer; font-size:12px; border:none; background:transparent; color:inherit; padding:2px 4px; border-radius:6px; text-align:left; font:inherit; width:100%; box-sizing:border-box; }
664
+ .dswfe-diag-item:hover { background:var(--dsw-hover, rgba(128,128,128,.1)); }
665
+ .dswfe-diag-item[data-kind="err"] .dswfe-diag-code { color:var(--dsw-alias-state-error, #c75050); }
666
+ .dswfe-diag-item[data-kind="warn"] .dswfe-diag-code { color:#b8860b; }
667
+ .dswfe-diag-code { font-weight:600; flex:none; }
668
+ .dswfe-diag-line { opacity:.6; flex:none; min-width:34px; }
669
+ .dswfe-phase { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:11px; padding:12px 14px; margin:10px 0; }
670
+ .dswfe-phase-head { display:flex; align-items:baseline; gap:8px; font-weight:700; font-size:13px; }
671
+ .dswfe-phase-spec { white-space:pre-wrap; font-size:12px; opacity:.8; margin:6px 0; }
672
+ .dswfe-link { border-top:1px dashed var(--dsw-alias-border-l1, rgba(128,128,128,.2)); margin-top:6px; padding-top:6px; }
673
+ .dswfe-link-row { display:flex; align-items:baseline; gap:8px; width:100%; border:none; background:transparent; color:inherit; font:inherit; font-size:13px; cursor:pointer; padding:4px 2px; border-radius:6px; text-align:left; box-sizing:border-box; }
674
+ .dswfe-link-row:hover { background:var(--dsw-hover, rgba(128,128,128,.1)); }
675
+ .dswfe-link-id { font-family:ui-monospace, SFMono-Regular, Menlo, monospace; font-size:11px; opacity:.75; flex:none; }
676
+ .dswfe-link-meta { font-size:11px; color:var(--dsw-text-secondary, gray); margin-left:auto; display:flex; gap:6px; flex-wrap:wrap; }
677
+ .dswfe-link-body { padding:6px 8px 2px; display:flex; flex-direction:column; gap:6px; }
678
+ .dswfe-pre { white-space:pre-wrap; line-height:1.6; font-size:12px; background:var(--dsw-alias-bg-layer-2, rgba(128,128,128,.07)); border:1px solid var(--dsw-alias-border-l1, rgba(128,128,128,.2)); border-radius:8px; padding:8px 10px; margin:0; overflow-x:auto; }
679
+ .dswfe-code { font-family:ui-monospace, SFMono-Regular, Menlo, monospace; font-size:12px; line-height:1.55; border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:10px; overflow:auto; max-height:calc(100vh - 260px); background:var(--dsw-alias-bg-layer-2, rgba(128,128,128,.05)); }
680
+ .dswfe-code-line { display:flex; }
681
+ .dswfe-code-line[data-hl="true"] { background:rgba(217,130,43,.18); }
682
+ .dswfe-code-no { flex:none; width:44px; text-align:right; padding-right:10px; color:var(--dsw-text-secondary, gray); user-select:none; opacity:.7; }
683
+ .dswfe-code-tx { white-space:pre; padding-right:16px; }
684
+ .dswfe-cm { color:var(--dsw-text-secondary, gray); font-style:italic; }
685
+ .dswfe-key { color:#3e63dd; }
686
+ .dswfe-editor { display:flex; flex-direction:column; gap:8px; flex:1; min-height:0; }
687
+ .dswfe-editor-wrap { display:flex; flex:1; min-height:0; border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.35)); border-radius:10px; overflow:hidden; background:var(--dsw-alias-bg-layer-2, rgba(128,128,128,.05)); }
688
+ .dswfe-gutter { flex:none; width:46px; text-align:right; padding:8px 10px 8px 0; font-family:ui-monospace, SFMono-Regular, Menlo, monospace; font-size:12px; line-height:19px; color:var(--dsw-text-secondary, gray); overflow:hidden; user-select:none; opacity:.7; box-sizing:border-box; }
689
+ .dswfe-textarea { flex:1; border:none; outline:none; resize:none; background:transparent; color:inherit; font-family:ui-monospace, SFMono-Regular, Menlo, monospace; font-size:12px; line-height:19px; padding:8px 12px; white-space:pre; overflow:auto; tab-size:2; }
690
+ .dswfe-status { display:flex; gap:10px; align-items:center; font-size:12px; color:var(--dsw-text-secondary, gray); flex-wrap:wrap; }
691
+ .dswfe-conflict { border:1px solid var(--dsw-alias-state-error, #c75050); border-radius:8px; padding:8px 10px; display:flex; gap:8px; align-items:center; flex-wrap:wrap; font-size:12px; }
692
+ .dswfe-modal-backdrop { position:fixed; inset:0; z-index:2147482900; background:rgba(0,0,0,.45); display:flex; align-items:center; justify-content:center; }
693
+ html[data-windows-titlebar] .dswfe-modal-backdrop { top:var(--dsh-windows-titlebar-height, 38px); }
694
+ html[data-windows-titlebar][data-fullscreen] .dswfe-modal-backdrop { top:0; }
695
+ .dswfe-modal { width:min(560px, 92vw); max-height:86vh; overflow:auto; background:var(--dsw-alias-bg-layer-1, #fff); color:var(--dsw-alias-label-primary, inherit); border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:14px; padding:18px; display:flex; flex-direction:column; gap:12px; font:var(--dsw-font-family, inherit); }
696
+ .dswfe-modal h3 { margin:0; font-size:16px; }
697
+ .dswfe-field { display:flex; flex-direction:column; gap:6px; font-size:12px; }
698
+ .dswfe-field input, .dswfe-field select, .dswfe-field textarea { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); background:var(--dsw-alias-bg-layer-2, transparent); color:inherit; border-radius:8px; padding:6px 10px; font:inherit; font-size:13px; }
699
+ .dswfe-field textarea { resize:vertical; min-height:52px; width:100%; box-sizing:border-box; line-height:1.5; }
700
+ .dswfe-menuback { position:fixed; inset:0; z-index:2147482800; }
701
+ .dswfe-menu { position:fixed; z-index:2147482850; background:var(--dsw-alias-bg-overlay, var(--dsw-alias-bg-layer-1, #252830)); color:var(--dsw-alias-label-primary, inherit); border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:10px; padding:4px; display:flex; flex-direction:column; min-width:150px; box-shadow:0 8px 30px rgba(0,0,0,.25); }
702
+ .dswfe-menu button { border:none; background:transparent; color:inherit; text-align:left; padding:7px 10px; border-radius:7px; font:inherit; font-size:13px; cursor:pointer; white-space:nowrap; }
703
+ .dswfe-menu button:hover { background:var(--dsw-hover, rgba(128,128,128,.15)); }
704
+ .dswfe-toast { position:fixed; left:50%; bottom:26px; transform:translateX(-50%); z-index:2147483000; background:var(--dsw-alias-bg-overlay, #252830); color:var(--dsw-alias-label-primary, #fff); border-radius:10px; padding:8px 14px; font-size:13px; box-shadow:0 6px 24px rgba(0,0,0,.3); max-width:70vw; }
705
+ .dswfe-toast[data-kind="err"] { outline:1px solid var(--dsw-alias-state-error, #c75050); }
706
+ .dswfe-empty { flex:1; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:8px; color:var(--dsw-text-secondary, gray); text-align:center; padding:20px; }
707
+ .dswfe-error { margin:8px 14px 0; border:1px solid var(--dsw-alias-state-error, #c75050); color:var(--dsw-alias-state-error, #c75050); border-radius:8px; padding:6px 10px; font-size:12px; }
708
+ .dswfe-drop { border:2px dashed var(--dsw-alias-border-l2, rgba(128,128,128,.4)); border-radius:10px; padding:22px; text-align:center; font-size:12px; color:var(--dsw-text-secondary, gray); }
709
+ .dswfe-drop[data-over="true"] { border-color:var(--dsw-alias-brand-primary, #3e63dd); }
710
+ .dswfe-sec { margin:10px 0; }
711
+ .dswfe-sec h4 { margin:0 0 8px; font-size:12.5px; font-weight:700; letter-spacing:.04em; color:var(--dsw-alias-label-secondary, inherit); }
712
+
713
+ .dswfe-runlist { width:296px; min-width:230px; overflow-y:auto; border-right:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.35)); padding:8px; box-sizing:border-box; }
714
+ .dswfe-runrow { display:flex; flex-direction:column; gap:4px; width:100%; text-align:left; border:1px solid transparent; border-radius:9px; background:transparent; color:inherit; padding:9px 10px; margin:3px 0; cursor:pointer; font:inherit; font-size:12px; box-sizing:border-box; }
715
+ .dswfe-runrow:hover { background:var(--dsw-hover, rgba(128,128,128,.1)); }
716
+ .dswfe-runrow[data-selected="true"] { background:var(--dsw-active, rgba(128,128,128,.16)); border-color:var(--dsw-alias-border-l2, rgba(128,128,128,.3)); }
717
+ .dswfe-runrow-top { display:flex; align-items:center; gap:6px; min-width:0; }
718
+ .dswfe-runrow-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-weight:600; }
719
+ .dswfe-runrow-meta { display:flex; flex-wrap:wrap; gap:8px; color:var(--dsw-text-secondary, gray); font-size:11px; font-variant-numeric:tabular-nums; }
720
+ .dswfe-runrow-req { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; color:var(--dsw-text-secondary, gray); font-size:11px; line-height:1.5; opacity:.9; }
721
+ .dswfe-runrow[data-selected="true"] .dswfe-runrow-req { opacity:1; }
722
+ .dswfe-rundel { opacity:0; transition:opacity .12s; }
723
+ .dswfe-runrow:hover .dswfe-rundel, .dswfe-runrow:focus-within .dswfe-rundel { opacity:1; }
724
+ .dswfe-linkdur { flex:none; font-size:11px; opacity:.8; font-variant-numeric:tabular-nums; margin-left:6px; padding-left:8px; border-left:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.25)); }
725
+ .dswfe-help { position:relative; display:inline-flex; align-items:center; justify-content:center; width:14px; height:14px; margin-left:6px; border-radius:50%; border:1px solid currentColor; opacity:.45; font-size:9.5px; line-height:1; cursor:help; vertical-align:middle; user-select:none; flex:none; }
726
+ .dswfe-help:hover, .dswfe-help:focus-visible { opacity:.9; }
727
+ .dswfe-tip { position:fixed; z-index:2147483100; padding:8px 10px; border-radius:9px; background:#000 !important; background-color:#000 !important; color:#fff !important; border:1px solid rgba(255,255,255,.16); font-size:12px; line-height:18px; font-weight:400; text-align:left; white-space:normal; word-break:break-word; box-shadow:0 10px 28px rgba(0,0,0,.35); pointer-events:none; }
728
+ .dswfe-field-label { display:inline-flex; align-items:center; margin:10px 0 0; font-size:11px; opacity:.75; }
729
+ .dswfe-check { display:flex; flex-direction:row; align-items:center; gap:6px; font-size:12px; }
730
+ .dswfe-check input { margin:0; }
731
+ .dswfe-outline { display:flex; flex-direction:column; gap:2px; }
732
+ .dswfe-ovphase { display:flex; align-items:center; gap:6px; margin-top:8px; font-size:12px; font-weight:600; }
733
+ .dswfe-ovlink { display:flex; align-items:center; gap:8px; padding:2px 0 2px 10px; font-size:12.5px; }
734
+ .dswfe-ovno { flex:none; min-width:52px; color:var(--dsw-text-secondary, gray); font-variant-numeric:tabular-nums; }
735
+ .dswfe-ovname { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
736
+ .dswfe-ovkind { flex:none; margin-left:auto; font-size:11px; color:var(--dsw-text-secondary, gray); font-variant-numeric:tabular-nums; }
737
+ .dswfe-ovno { flex:none; min-width:56px; opacity:.6; font-size:11px; }
738
+ .dswfe-ovname { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
739
+ .dswfe-ovkind { flex:none; margin-left:auto; font-size:11px; color:var(--dsw-text-secondary, gray); font-variant-numeric:tabular-nums; }
740
+ .dswfe-artgroup { margin-bottom:4px; }
741
+ .dswfe-artrow { display:flex; gap:8px; align-items:center; width:100%; text-align:left; border:1px solid var(--dsw-alias-border-l1, rgba(128,128,128,.2)); border-radius:8px; background:transparent; color:inherit; padding:6px 10px; margin:3px 0; cursor:pointer; font:inherit; font-size:12px; box-sizing:border-box; }
742
+ .dswfe-artrow:hover { background:var(--dsw-hover, rgba(128,128,128,.1)); border-color:var(--dsw-alias-border-l2, rgba(128,128,128,.35)); }
743
+ .dswfe-artrow[data-selected="true"] { background:var(--dsw-active, rgba(128,128,128,.16)); border-color:var(--dsw-alias-border-l2, rgba(128,128,128,.35)); }
744
+ .dswfe-mini[data-active="true"] { background:var(--dsw-active, rgba(128,128,128,.16)); }
745
+ .dswfe-pill { border-radius:999px; padding:2px 9px; font-size:10.5px; line-height:15px; white-space:nowrap; border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); }
746
+ .dswfe-pill[data-status="running"] { color:#d9822b; border-color:#d9822b; }
747
+ .dswfe-pill[data-status="queued"] { color:#3e63dd; border-color:#3e63dd; }
748
+ .dswfe-pill[data-status="awaiting"] { color:#c75050; border-color:#c75050; }
749
+ .dswfe-pill[data-status="paused"] { color:#b8860b; border-color:#b8860b; }
750
+ .dswfe-pill[data-status="done"] { color:#2e9e5b; border-color:#2e9e5b; }
751
+ .dswfe-pill[data-status="stopped"] { color:var(--dsw-text-secondary, gray); }
752
+ .dswfe-pill[data-status="failed"] { color:var(--dsw-alias-state-error, #c75050); border-color:var(--dsw-alias-state-error, #c75050); }
753
+ .dswfe-board { flex:1; min-width:0; overflow-y:auto; padding:16px 20px; box-sizing:border-box; }
754
+ .dswfe-runhead { display:flex; align-items:center; gap:10px; flex-wrap:wrap; margin-bottom:10px; }
755
+ .dswfe-break { border:1px solid var(--dsw-alias-state-error, #c75050); border-radius:10px; padding:10px 12px; margin:8px 0; display:flex; gap:8px; align-items:center; flex-wrap:wrap; }
756
+ .dswfe-linkcard { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:9px; padding:9px 11px; margin:6px 0; display:flex; flex-direction:column; gap:6px; }
757
+ .dswfe-linkcard[data-state="running"] { border-color:#d9822b; }
758
+ .dswfe-linkcard[data-state="done"] { opacity:.82; }
759
+ .dswfe-linkcard[data-state="gate_failed"] { border-color:var(--dsw-alias-state-error, #c75050); }
760
+ .dswfe-linktop { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
761
+ .dswfe-linktop .grow { flex:1; }
762
+ .dswfe-mini { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); background:transparent; color:inherit; border-radius:6px; padding:2px 7px; font:inherit; font-size:11px; cursor:pointer; white-space:nowrap; }
763
+ .dswfe-mini:hover { background:var(--dsw-hover, rgba(128,128,128,.12)); }
764
+ .dswfe-tail { max-height:180px; overflow:auto; margin:0; }
765
+ .dswfe-flowwrap { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:10px; background:var(--dsw-alias-bg-layer-2, rgba(128,128,128,.05)); overflow:auto; max-height:min(64vh, 640px); }
766
+ .dswfe-flowlegend { display:flex; gap:14px; flex-wrap:wrap; font-size:11px; color:var(--dsw-text-secondary, gray); margin:6px 2px 10px; align-items:center; }
767
+ .dswfe-flowlegend .sw { display:inline-block; width:26px; height:0; border-top:2px solid; margin-right:5px; vertical-align:middle; }
768
+ .dswfe-flowlegend .sw.fwd { border-color:var(--dsw-text-secondary, #94a3b8); }
769
+ .dswfe-flowlegend .sw.jump { border-color:#22c55e; }
770
+ .dswfe-flowlegend .sw.fail { border-color:var(--dsw-alias-state-error, #ef4444); border-top-width:2px; border-top-style:dashed; }
771
+ .dswfe-form { flex:1; min-height:0; overflow-y:auto; padding:12px 16px; box-sizing:border-box; }
772
+ /* 画布编辑器:左画布(阶段泳道+环节节点)+ 右属性面板 */
773
+ .dswfe-canvas { flex:1; min-height:0; display:flex; overflow:hidden; }
774
+ .dswfe-canvas-left { flex:1; min-width:0; overflow:auto; padding:14px; box-sizing:border-box; }
775
+ .dswfe-canvas-bar { display:flex; align-items:center; gap:10px; margin-bottom:12px; position:sticky; top:0; z-index:2; background:var(--dsw-alias-bg-base, inherit); padding:4px 0; }
776
+ .dswfe-canvas-hint { font-size:11px; opacity:.55; }
777
+ .dswfe-canvas-empty { border:1px dashed var(--dsw-alias-border-l2, rgba(128,128,128,.35)); border-radius:12px; padding:32px; text-align:center; opacity:.6; }
778
+ .dswfe-lane { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:12px; margin:0 0 12px; background:var(--dsw-alias-bg-layer-1, transparent); overflow:hidden; }
779
+ .dswfe-lane[data-sel="true"] { border-color:var(--dsw-alias-brand-primary, #d9822b); box-shadow:0 0 0 1px var(--dsw-alias-brand-primary, #d9822b); }
780
+ .dswfe-lane-head { display:flex; align-items:center; gap:8px; padding:8px 12px; cursor:pointer; background:var(--dsw-alias-bg-layer-2, rgba(128,128,128,.06)); user-select:none; }
781
+ .dswfe-lane-no { color:#fff; font-size:10px; font-weight:700; border-radius:8px; padding:2px 7px; font-family:ui-monospace, monospace; }
782
+ .dswfe-lane-name { font-weight:600; font-size:13px; }
783
+ .dswfe-lane-id { font-family:ui-monospace, monospace; font-size:11px; opacity:.5; }
784
+ .dswfe-lane-count { margin-left:auto; font-size:11px; opacity:.55; }
785
+ .dswfe-lane-body { display:flex; flex-wrap:wrap; gap:10px; align-items:center; padding:12px; }
786
+ .dswfe-node { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.35)); border-radius:10px; padding:8px 12px; cursor:pointer; min-width:130px; max-width:210px; background:var(--dsw-alias-bg-base, transparent); user-select:none; }
787
+ .dswfe-node:hover { border-color:var(--dsw-alias-brand-primary, #d9822b); }
788
+ .dswfe-node[data-sel="true"] { border-color:var(--dsw-alias-brand-primary, #d9822b); box-shadow:0 0 0 1px var(--dsw-alias-brand-primary, #d9822b); }
789
+ .dswfe-node-name { font-weight:600; font-size:12.5px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
790
+ .dswfe-node-meta { display:flex; gap:6px; align-items:center; margin-top:3px; }
791
+ .dswfe-node-id { font-family:ui-monospace, monospace; font-size:10.5px; opacity:.5; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
792
+ .dswfe-node-badge { font-size:10.5px; color:#b8860b; white-space:nowrap; }
793
+ .dswfe-node-arrow { opacity:.45; font-size:14px; }
794
+ .dswfe-node-add { border:1px dashed var(--dsw-alias-border-l2, rgba(128,128,128,.4)); background:transparent; color:inherit; border-radius:10px; min-width:34px; height:38px; font-size:16px; cursor:pointer; opacity:.65; }
795
+ .dswfe-node-add:hover { opacity:1; border-color:var(--dsw-alias-brand-primary, #d9822b); }
796
+ .dswfe-props { width:400px; min-width:340px; flex:none; border-left:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); overflow-y:auto; padding:12px 16px; box-sizing:border-box; }
797
+ /* 模型两极下拉 + 技能多选下拉 */
798
+ .dswfe-modelrow { display:flex; gap:6px; }
799
+ .dswfe-native-sel { flex:1; min-width:0; border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); background:var(--dsw-alias-bg-layer-2, transparent); color:inherit; border-radius:8px; padding:6px 8px; font:inherit; font-size:12.5px; }
800
+ .dswfe-native-sel:disabled { opacity:.45; }
801
+ .dswfe-selbtn { width:100%; display:flex; align-items:center; gap:6px; text-align:left; border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); background:var(--dsw-alias-bg-layer-2, transparent); color:inherit; border-radius:8px; padding:6px 10px; font:inherit; font-size:12.5px; cursor:pointer; }
802
+ .dswfe-selbtn .dswfe-selph { opacity:.45; }
803
+ .dswfe-selbtn span:first-child { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
804
+ .dswfe-selcar { opacity:.5; }
805
+ .dswfe-skillpick { position:relative; }
806
+ .dswfe-skillpop { position:absolute; left:0; right:0; top:calc(100% + 4px); z-index:30; background:var(--dsw-alias-bg-overlay, var(--dsw-alias-bg-layer-1, #252830)); color:var(--dsw-alias-label-primary, inherit); border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:10px; box-shadow:0 8px 30px rgba(0,0,0,.25); max-height:260px; overflow-y:auto; padding:4px; }
807
+ .dswfe-skillrow { display:flex; align-items:center; gap:8px; padding:6px 8px; border-radius:6px; cursor:pointer; font-size:12.5px; }
808
+ .dswfe-skillrow:hover { background:var(--dsw-alias-bg-layer-2, rgba(128,128,128,.12)); }
809
+ .dswfe-skillrow input { flex:none; }
810
+ .dswfe-skillname { font-weight:600; white-space:nowrap; }
811
+ .dswfe-skilldesc { opacity:.55; font-size:11px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
812
+ .dswfe-skillnone { padding:10px; opacity:.55; font-size:12px; text-align:center; }
813
+ .dswfe-skillclear { width:100%; border:none; border-top:1px solid var(--dsw-alias-border-l1, rgba(128,128,128,.2)); background:transparent; color:inherit; padding:7px; font:inherit; font-size:12px; cursor:pointer; opacity:.7; }
814
+ .dswfe-skillclear:hover { opacity:1; }
815
+ .dswfe-fsec { margin:0 0 14px; }
816
+ .dswfe-fsec h4 { margin:0 0 8px; font-size:13px; }
817
+ .dswfe-fgrid { display:grid; grid-template-columns:repeat(auto-fit, minmax(180px, 1fr)); gap:8px 12px; }
818
+ .dswfe-fphase { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:10px; padding:10px 12px; margin:8px 0; background:var(--dsw-alias-bg-layer-1, transparent); }
819
+ .dswfe-flink { border:1px solid var(--dsw-alias-border-l1, rgba(128,128,128,.2)); border-radius:8px; padding:8px 10px; margin:8px 0; background:var(--dsw-alias-bg-layer-2, rgba(128,128,128,.04)); }
820
+ .dswfe-flink .dswfe-field { margin:6px 0; }
821
+ .dswfe-fgates { border-top:1px dashed var(--dsw-alias-border-l1, rgba(128,128,128,.2)); padding-top:6px; }
822
+ `
823
+
824
+ let stylesInjected = false
825
+ function ensureStyles() {
826
+ if (stylesInjected || typeof document === 'undefined') return
827
+ const el = document.createElement('style')
828
+ el.id = 'dswfe-styles'
829
+ el.textContent = STYLE
830
+ document.head.appendChild(el)
831
+ stylesInjected = true
832
+ }
833
+
834
+ // ── API 帮手 ─────────────────────────────────────────────────────────────
835
+
836
+ async function api(path, opts) {
837
+ const res = await fetch(API + path, {
838
+ method: (opts && opts.method) || 'GET',
839
+ headers: opts && opts.body ? { 'content-type': 'application/json' } : undefined,
840
+ body: opts && opts.body ? JSON.stringify(opts.body) : undefined,
841
+ signal: AbortSignal.timeout ? AbortSignal.timeout(30000) : undefined,
842
+ })
843
+ let data = {}
844
+ try { data = await res.json() } catch { /* 空响应 */ }
845
+ if (!res.ok) {
846
+ const e = new Error(data.error || (res.statusText + ' (' + res.status + ')'))
847
+ e.code = data.code
848
+ e.status = res.status
849
+ e.data = data
850
+ throw e
851
+ }
852
+ return data
853
+ }
854
+
855
+ // 旧包名时代的面板偏好存在 dsh-prc:prefs:新键缺失时读一次旧键并写回新键
856
+ function loadPrefs() {
857
+ let raw = null
858
+ try { raw = localStorage.getItem(PREFS_KEY) } catch { /* 隐身模式等 */ }
859
+ if (!raw) {
860
+ try {
861
+ const legacy = localStorage.getItem('dsh-prc:prefs')
862
+ if (legacy) { raw = legacy; localStorage.setItem(PREFS_KEY, legacy) }
863
+ } catch { /* 同上 */ }
864
+ }
865
+ try { return JSON.parse(raw) || {} } catch { return {} }
866
+ }
867
+ function savePrefs(prefs) {
868
+ try { localStorage.setItem(PREFS_KEY, JSON.stringify(prefs)) } catch { /* 隐身模式等 */ }
869
+ }
870
+
871
+ // ── Controller ───────────────────────────────────────────────────────────
872
+
873
+ function initialState() {
874
+ const prefs = loadPrefs()
875
+ return {
876
+ loaded: false, revision: 0, roots: { user: '', bundled: '' }, processes: [], lastError: undefined, error: undefined,
877
+ panelOpen: false,
878
+ selectedId: prefs.selectedId, tab: prefs.tab || 'overview',
879
+ item: undefined, itemLoading: false, highlightLine: undefined,
880
+ search: '', filters: Object.assign({ source: 'all', category: '', complexity: '' }, prefs.filters || {}),
881
+ sortBy: prefs.sortBy || 'default',
882
+ editor: null,
883
+ dialog: null,
884
+ toast: null,
885
+ settings: undefined,
886
+ view: prefs.view || 'lib',
887
+ runs: { revision: -1, list: [] },
888
+ runId: prefs.runId, run: undefined, runLoading: false, runError: null,
889
+ }
890
+ }
891
+
892
+ class Controller {
893
+ constructor() {
894
+ this.state = initialState()
895
+ this.subs = new Set()
896
+ this.es = null
897
+ this.seenRevision = undefined
898
+ this.seenRunsRevision = undefined
899
+ this.refreshInFlight = null
900
+ this.validateTimer = null
901
+ this.toastTimer = null
902
+ this.disposed = false
903
+ }
904
+ getSnapshot() { return this.state }
905
+ subscribe(fn) { this.subs.add(fn); return () => { this.subs.delete(fn) } }
906
+ setState(patch) { this.state = { ...this.state, ...patch }; this.emit() }
907
+ emit() { if (this.disposed) return; for (const fn of this.subs) { try { fn() } catch {} } }
908
+ persist() {
909
+ const s = this.state
910
+ savePrefs({ selectedId: s.selectedId, tab: s.tab, filters: s.filters, sortBy: s.sortBy, view: s.view, runId: s.runId })
911
+ }
912
+ toast(text, kind) {
913
+ this.setState({ toast: { text, kind: kind || 'ok' } })
914
+ if (this.toastTimer) clearTimeout(this.toastTimer)
915
+ this.toastTimer = setTimeout(() => { if (!this.disposed) this.setState({ toast: null }) }, 2600)
916
+ }
917
+
918
+ start() {
919
+ void this.refresh()
920
+ try { this.connectStream() } catch { /* 实时通道不可用:仅手动刷新 */ }
921
+ }
922
+ connectStream() {
923
+ const onEvent = (event, payload) => {
924
+ if (event !== 'hello' && event !== 'change') return
925
+ try { this.seenRevision = payload.revision; this.seenRunsRevision = payload.runsRevision } catch (e) {}
926
+ void this.refresh()
927
+ }
928
+ // 枢纽优先(dsh-plugin-kit ≥0.4 的共享单连接);帧形状 {event, data}
929
+ if (typeof PluginKit !== 'undefined' && typeof PluginKit.connectEvents === 'function') {
930
+ this.hubOff = PluginKit.connectEvents('dsh-workflow-execute', (data) => {
931
+ if (data && typeof data.event === 'string') onEvent(data.event, data.data)
932
+ }, () => {})
933
+ if (this.hubOff) return
934
+ }
935
+ const es = new EventSource(API + '/events')
936
+ this.es = es
937
+ es.addEventListener('hello', (e) => {
938
+ let d; try { d = JSON.parse(e.data) } catch (err) { return }
939
+ onEvent('hello', d)
940
+ })
941
+ es.addEventListener('change', (e) => {
942
+ let d; try { d = JSON.parse(e.data) } catch (err) { return }
943
+ onEvent('change', d)
944
+ })
945
+ es.onerror = () => { /* EventSource 自动重连;hello 里对齐 gap */ }
946
+ }
947
+ async refresh() {
948
+ if (this.refreshInFlight) return this.refreshInFlight
949
+ this.refreshInFlight = (async () => {
950
+ try {
951
+ let snap
952
+ // revision 追赶:变更帧落在请求飞行中时,旧响应可能落后(taskboard S16)
953
+ for (let round = 0; round < 3; round++) {
954
+ const [stateRsp, runsRsp] = await Promise.all([api('/state'), api('/runs')])
955
+ snap = stateRsp
956
+ const keep = this.state.selectedId && snap.processes.some((p) => p.id === this.state.selectedId)
957
+ ? this.state.selectedId : undefined
958
+ this.setState({
959
+ loaded: true, revision: snap.revision, roots: snap.roots, processes: snap.processes,
960
+ lastError: snap.lastError, error: undefined, selectedId: keep,
961
+ runs: { revision: runsRsp.revision, list: runsRsp.runs },
962
+ })
963
+ const libCaughtUp = this.seenRevision === undefined || snap.revision >= this.seenRevision
964
+ const runsCaughtUp = this.seenRunsRevision === undefined || runsRsp.revision >= this.seenRunsRevision
965
+ if (libCaughtUp && runsCaughtUp) break
966
+ }
967
+ // 选中的运行已不在台账里 → 清选中,避免看板停留在「加载中」
968
+ if (this.state.runId && !this.state.runs.list.some((r) => r.id === this.state.runId)) {
969
+ this.setState({ runId: null, run: undefined, runLoading: false, runError: null })
970
+ this.persist()
971
+ }
972
+ // 运行看板:活跃运行随帧刷新;静态运行只取一次
973
+ if (this.state.view === 'exec' && this.state.runId) {
974
+ const active = ['queued', 'running', 'awaiting'].includes((this.state.run && this.state.run.status) || '')
975
+ if (active || !this.state.run) void this.loadRun(this.state.runId)
976
+ }
977
+ // 选中项跟随外部改动:非编辑态自动刷新;编辑态不打断(保存时乐观锁兜底)
978
+ if (this.state.selectedId && !this.state.itemLoading) {
979
+ if (this.state.editor && this.state.editor.id === this.state.selectedId) { /* 编辑中:跳过 */ }
980
+ else if (this.state.item && this.state.item.meta.id === this.state.selectedId) {
981
+ const fresh = snap.processes.find((p) => p.id === this.state.selectedId)
982
+ if (fresh && this.state.item.meta.hash !== fresh.hash) void this.loadItem(this.state.selectedId)
983
+ } else void this.loadItem(this.state.selectedId)
984
+ }
985
+ } catch (error) {
986
+ this.setState({ error: String(error && error.message || error) })
987
+ } finally {
988
+ this.refreshInFlight = null
989
+ }
990
+ })()
991
+ return this.refreshInFlight
992
+ }
993
+ dispose() {
994
+ this.disposed = true
995
+ if (this.hubOff) { try { this.hubOff() } catch {} }
996
+ if (this.es) { try { this.es.close() } catch {} }
997
+ if (this.validateTimer) clearTimeout(this.validateTimer)
998
+ if (this.toastTimer) clearTimeout(this.toastTimer)
999
+ this.subs.clear()
1000
+ }
1001
+
1002
+ // ── 面板 ──
1003
+ openPanel() {
1004
+ this.setState({ panelOpen: true })
1005
+ try { document.dispatchEvent(new CustomEvent(ACTIVATE_EVENT, { detail: PANEL_NAME })) } catch {}
1006
+ if (!this.state.loaded) void this.refresh()
1007
+ // 兜底:视图容器未能在中栏放置(壳层退化)→ 450ms 后强制挂 body 全屏,
1008
+ // 保证侧栏入口点击永远有响应
1009
+ setTimeout(() => {
1010
+ if (this.disposed) return
1011
+ const s = this.getSnapshot()
1012
+ if (s.panelOpen && typeof document !== 'undefined' && !document.querySelector('[data-dswfe-panel]')) {
1013
+ if (prcView) prcView.ensure(true)
1014
+ }
1015
+ }, 450)
1016
+ }
1017
+ closePanel() { this.setState({ panelOpen: false, dialog: null }) }
1018
+ togglePanel() { if (this.state.panelOpen) this.closePanel(); else this.openPanel() }
1019
+
1020
+ // ── 选择 / 筛选 ──
1021
+ select(id) {
1022
+ if (!id) return
1023
+ const ed = this.state.editor
1024
+ if (ed && ed.id !== id) {
1025
+ // 编辑中切换:脏了先确认,干净直接关编辑器
1026
+ if (ed.dirty) {
1027
+ this.setState({ dialog: { type: 'confirm', message: this.tr('dirtyGuard'), danger: true, yes: 'discard', onYes: () => { this.setState({ editor: null, dialog: null }); this.select(id) } } })
1028
+ return
1029
+ }
1030
+ this.setState({ editor: null })
1031
+ }
1032
+ this.setState({ selectedId: id, item: undefined, itemLoading: true, highlightLine: undefined })
1033
+ this.persist()
1034
+ void this.loadItem(id)
1035
+ }
1036
+ async loadItem(id) {
1037
+ try {
1038
+ const item = await api('/item?id=' + encodeURIComponent(id))
1039
+ if (this.state.selectedId !== id) return
1040
+ this.setState({ item, itemLoading: false })
1041
+ } catch (error) {
1042
+ if (this.state.selectedId === id) this.setState({ itemLoading: false, error: String(error && error.message || error) })
1043
+ }
1044
+ }
1045
+ /** 跳到某个会话(AI 生成任务的会话):客户端 sessions 服务 open(id),逐次懒解析。 */
1046
+ openSession(sessionId) {
1047
+ const svc = this.sessionsSvc
1048
+ if (!svc || typeof svc.open !== 'function') { this.toast(this.tr('sessionUnavailable'), 'err'); return }
1049
+ try { svc.open(sessionId); this.closePanel() } catch (error) { this.toast(String(error && error.message || error), 'err') }
1050
+ }
1051
+ tr(key, vars) { return this.t ? this.t(key, vars) : (ZH[key] || key) }
1052
+ setTab(tab) { this.setState({ tab }); this.persist() }
1053
+ setSearch(search) { this.setState({ search }) }
1054
+ setFilter(key, value) {
1055
+ const filters = { ...this.state.filters, [key]: value }
1056
+ this.setState({ filters }); this.persist()
1057
+ }
1058
+ setSortBy(sortBy) { this.setState({ sortBy }); this.persist() }
1059
+
1060
+ // ── 编辑器 ──
1061
+ openEditor(payload) {
1062
+ this.setState({
1063
+ editor: {
1064
+ mode: payload.mode, id: payload.id || null, name: payload.name || '', dir: payload.dir || '',
1065
+ text: payload.text || '', baseHash: payload.baseHash || null, original: payload.text || '',
1066
+ dirty: false, diagnostics: payload.diagnostics || null, busy: false, conflict: null, error: null,
1067
+ },
1068
+ })
1069
+ this.scheduleValidate(50)
1070
+ }
1071
+ async editSelected() {
1072
+ const item = this.state.item
1073
+ if (!item) return
1074
+ const t0 = Date.now()
1075
+ this.openEditor({ mode: 'update', id: item.meta.id, text: item.yaml, baseHash: item.hash, diagnostics: item.diagnostics })
1076
+ }
1077
+ async createBlank(name, dir, displayName) {
1078
+ try {
1079
+ const q = '?name=' + encodeURIComponent(name) + (displayName ? '&displayName=' + encodeURIComponent(displayName) : '')
1080
+ const { yaml } = await api('/skeleton' + q)
1081
+ this.setState({ dialog: null })
1082
+ this.openEditor({ mode: 'create', name, dir, text: yaml })
1083
+ } catch (error) { this.toast(String(error && error.message || error), 'err') }
1084
+ }
1085
+ setEditorText(text) {
1086
+ const ed = this.state.editor
1087
+ if (!ed) return
1088
+ this.setState({ editor: { ...ed, text, dirty: text !== ed.original, conflict: null, validatedAt: null } })
1089
+ this.scheduleValidate()
1090
+ }
1091
+ scheduleValidate(delay) {
1092
+ if (this.validateTimer) clearTimeout(this.validateTimer)
1093
+ this.validateTimer = setTimeout(() => { this.validateTimer = null; void this.validateEditor(true) }, delay === undefined ? 400 : delay)
1094
+ }
1095
+ async validateEditor(silent) {
1096
+ const ed = this.state.editor
1097
+ if (!ed || ed.text.trim() === '') return
1098
+ try {
1099
+ const d = await api('/validate', { method: 'POST', body: { yaml: ed.text } })
1100
+ const cur = this.state.editor
1101
+ if (cur && cur.text === ed.text) {
1102
+ this.setState({ editor: { ...cur, diagnostics: { errors: d.errors, warnings: d.warnings }, validatedAt: Date.now() } })
1103
+ }
1104
+ // 自动校验(防抖后逐字触发)不弹提示,结果只体现在状态栏与诊断区;
1105
+ // 只有手动点「校验」才 toast,避免每输入一个字就冒一个气泡。
1106
+ if (!silent) {
1107
+ const errors = (d.errors || []).length
1108
+ const warnings = (d.warnings || []).length
1109
+ this.toast(errors === 0 && warnings === 0
1110
+ ? this.tr('validateOk')
1111
+ : this.tr('validateResult', { e: errors, w: warnings }), errors > 0 ? 'err' : undefined)
1112
+ }
1113
+ } catch (error) {
1114
+ if (!silent) this.toast(String((error && error.message) || error), 'err')
1115
+ }
1116
+ }
1117
+ async saveEditor(force) {
1118
+ const ed = this.state.editor
1119
+ if (!ed || ed.busy) return
1120
+ this.setState({ editor: { ...ed, busy: true, error: null } })
1121
+ try {
1122
+ let body
1123
+ if (ed.mode === 'create') body = { mode: 'create', name: ed.name, dir: ed.dir, yaml: ed.text }
1124
+ else body = { mode: 'update', id: ed.id, yaml: ed.text, baseHash: force && ed.conflict ? ed.conflict.currentHash : ed.baseHash }
1125
+ const result = await api('/save', { method: 'POST', body })
1126
+ // 保存后留在编辑器:用落盘内容刷新文本与基线,清脏标、保留画布选中与 form/yaml 子模式
1127
+ let item = null
1128
+ try { item = await api('/item?id=' + encodeURIComponent(result.id)) } catch {}
1129
+ const cur = this.state.editor || ed
1130
+ this.setState({
1131
+ dialog: null,
1132
+ selectedId: result.id,
1133
+ item: item || this.state.item,
1134
+ itemLoading: false,
1135
+ editor: Object.assign({}, cur, {
1136
+ mode: 'update', id: result.id, name: ed.name, dir: ed.dir,
1137
+ text: item ? item.yaml : cur.text,
1138
+ original: item ? item.yaml : cur.text,
1139
+ baseHash: item ? item.hash : cur.baseHash,
1140
+ dirty: false, busy: false, conflict: null, error: null,
1141
+ diagnostics: item ? item.diagnostics : cur.diagnostics,
1142
+ }),
1143
+ })
1144
+ void this.refresh()
1145
+ this.toast(force ? this.tr('toastForceSaved') : this.tr('toastSaved'))
1146
+ } catch (error) {
1147
+ const cur = this.state.editor
1148
+ if (!cur) return
1149
+ if (error.code === 'conflict') this.setState({ editor: { ...cur, busy: false, conflict: { currentHash: error.data && error.data.currentHash }, error: null } })
1150
+ else if (error.data && error.data.diagnostics) this.setState({ editor: { ...cur, busy: false, diagnostics: error.data.diagnostics, error: String(error.message) } })
1151
+ else this.setState({ editor: { ...cur, busy: false, error: String(error && error.message || error) } })
1152
+ }
1153
+ }
1154
+ async reloadEditor() {
1155
+ const ed = this.state.editor
1156
+ if (!ed || !ed.id) return
1157
+ try {
1158
+ const item = await api('/item?id=' + encodeURIComponent(ed.id))
1159
+ this.setState({ editor: { ...ed, text: item.yaml, original: item.yaml, baseHash: item.hash, dirty: false, conflict: null, diagnostics: item.diagnostics, error: null } })
1160
+ } catch (error) { this.toast(String(error && error.message || error), 'err') }
1161
+ }
1162
+ requestCloseEditor() {
1163
+ const ed = this.state.editor
1164
+ if (ed && ed.dirty) this.setState({ dialog: { type: 'confirm', message: this.tr('dirtyGuard'), danger: true, yes: 'discard', onYes: () => this.setState({ editor: null, dialog: null }) } })
1165
+ else this.setState({ editor: null })
1166
+ }
1167
+
1168
+ // ── 动作 ──
1169
+ async copyProcess(fromId, name, dir) {
1170
+ try {
1171
+ const result = await api('/save', { method: 'POST', body: { mode: 'copy', fromId, name, dir } })
1172
+ this.setState({ dialog: null })
1173
+ this.select(result.id)
1174
+ void this.refresh()
1175
+ this.toast(this.tr('toastCopied'))
1176
+ } catch (error) { this.toast(String(error && error.message || error), 'err') }
1177
+ }
1178
+ async renameProcess(id, newName) {
1179
+ try {
1180
+ const result = await api('/rename', { method: 'POST', body: { id, newName } })
1181
+ this.setState({ dialog: null })
1182
+ this.select(result.id || id)
1183
+ void this.refresh()
1184
+ this.toast(this.tr('toastRenamed'))
1185
+ } catch (error) { this.toast(String(error && error.message || error), 'err') }
1186
+ }
1187
+ async removeProcess(id) {
1188
+ try {
1189
+ await api('/delete', { method: 'POST', body: { id } })
1190
+ this.setState({ dialog: null, selectedId: undefined, item: undefined, editor: null })
1191
+ await this.refresh()
1192
+ this.toast(this.tr('toastTrashed'))
1193
+ } catch (error) { this.toast(String(error && error.message || error), 'err') }
1194
+ }
1195
+ async importFiles(files, overwrite) {
1196
+ const results = await api('/import', { method: 'POST', body: { files, overwrite } }).then((d) => d.results)
1197
+ await this.refresh()
1198
+ return results
1199
+ }
1200
+ async loadSettings() {
1201
+ const d = await api('/settings')
1202
+ this.setState({ settings: d.settings })
1203
+ return d.settings
1204
+ }
1205
+ async saveSettings(patch) {
1206
+ const d = await api('/settings', { method: 'POST', body: patch })
1207
+ this.setState({ settings: d.settings })
1208
+ await this.refresh()
1209
+ return d.settings
1210
+ }
1211
+ aiRun(prompt) { return api('/ai-generate', { method: 'POST', body: { prompt } }).then((d) => d.jobId) }
1212
+ aiPoll(jobId) { return api('/jobs?id=' + encodeURIComponent(jobId)) }
1213
+
1214
+ /**
1215
+ * @ 给 agent:把工作流文件以 @绝对路径 引用进当前会话的 composer(file-share 同款
1216
+ * 双形态写入 + 剪贴板兜底),用户接着输入修改要求发送即可——agent 会用
1217
+ * workflow_get/workflow_validate/workflow_save 工具完成修改。
1218
+ */
1219
+ atAgent(meta) {
1220
+ const root = meta.source === 'user' ? this.state.roots.user : this.state.roots.bundled
1221
+ const abs = (root || '').replace(/\/+$/, '') + '/' + meta.relPath
1222
+ const hint = meta.source === 'bundled' ? this.tr('atAgentBundledHint') : ''
1223
+ const text = '@' + abs + ' ' + hint
1224
+ const result = insertComposerText(text)
1225
+ this.closePanel()
1226
+ if (result === 'ok') this.toast(this.tr('atInserted'))
1227
+ else this.toast(this.tr('atCopied'), 'err')
1228
+ }
1229
+
1230
+ // ── 执行视图(v0.2)──
1231
+ setView(view) { this.setState({ view }); this.persist() }
1232
+ selectRun(id) {
1233
+ if (!id) return
1234
+ this.setState({ runId: id, run: undefined, runLoading: true })
1235
+ this.persist()
1236
+ void this.loadRun(id)
1237
+ }
1238
+ async loadRun(id) {
1239
+ try {
1240
+ const d = await api('/run?id=' + encodeURIComponent(id))
1241
+ if (this.state.runId !== id) return
1242
+ this.setState({ run: d.run, runLoading: false, runError: null })
1243
+ } catch (error) {
1244
+ if (this.state.runId !== id) return
1245
+ const msg = String(error && error.message || error)
1246
+ // 台账里已经没有这条运行(已删除/被清理):清掉选中,别让看板永远停在「加载中」
1247
+ if (error && error.code === 'not_found') {
1248
+ this.setState({ runId: null, run: undefined, runLoading: false, runError: null })
1249
+ this.persist()
1250
+ this.toast(msg, 'err')
1251
+ return
1252
+ }
1253
+ this.setState({ runLoading: false, runError: msg, error: msg })
1254
+ }
1255
+ }
1256
+ async loadLinkFiles(runId, linkId) {
1257
+ const d = await api('/run-link-files?run=' + encodeURIComponent(runId) + '&link=' + encodeURIComponent(linkId))
1258
+ return d.files || []
1259
+ }
1260
+ async loadArtifact(runId, path) {
1261
+ const d = await api('/run-file?run=' + encodeURIComponent(runId) + '&path=' + encodeURIComponent(path))
1262
+ return d.file
1263
+ }
1264
+ async runAction(action, body) {
1265
+ const d = await api('/run-action', { method: 'POST', body: { action, ...body } })
1266
+ if (this.state.runId === d.run.id) void this.loadRun(d.run.id)
1267
+ void this.refresh()
1268
+ return d.run
1269
+ }
1270
+ /** 删除一条已结束的运行台账(服务端只允许删除终态)。 */
1271
+ async deleteRun(id) {
1272
+ try {
1273
+ await api('/run-delete', { method: 'POST', body: { id } })
1274
+ if (this.state.runId === id) this.setState({ runId: null, run: undefined })
1275
+ this.persist()
1276
+ this.toast(this.tr('delete'))
1277
+ void this.refresh()
1278
+ } catch (error) {
1279
+ // 以前静默吞掉:接口报错时按钮看着像没生效,这里把原因显出来
1280
+ this.toast(String((error && error.message) || error), 'err')
1281
+ }
1282
+ }
1283
+ async createRun(body) {
1284
+ const d = await api('/run-create', { method: 'POST', body })
1285
+ this.setState({ dialog: null, view: 'exec', runId: d.run.id, run: undefined, runLoading: true })
1286
+ this.persist()
1287
+ void this.loadRun(d.run.id)
1288
+ this.toast(this.tr('runStarted'))
1289
+ return d.run
1290
+ }
1291
+ }
1292
+
1293
+ // ── 侧栏入口行(DOM 注入,taskboard 家族同款) ─────────────────────────────
1294
+
1295
+ /** 把文本写进当前会话的 composer(file-share 同款双形态 + 剪贴板兜底)。
1296
+ * 返回 'ok'(已写入输入框)或 'copied'(退化为剪贴板)。 */
1297
+ function insertComposerText(text) {
1298
+ try {
1299
+ const card = document.querySelector('[data-composer-card]')
1300
+ const ta = card && card.querySelector('textarea')
1301
+ const ce = card && (card.querySelector('[contenteditable="true"]') || card.querySelector('[contenteditable=""]'))
1302
+ if (typeof document.execCommand === 'function' && (ta || ce)) {
1303
+ if (ta) {
1304
+ ta.focus()
1305
+ const len = ta.value ? ta.value.length : 0
1306
+ try { ta.setSelectionRange(len, len) } catch {}
1307
+ } else if (ce) {
1308
+ ce.focus()
1309
+ const sel = window.getSelection()
1310
+ const range = document.createRange()
1311
+ range.selectNodeContents(ce)
1312
+ range.collapse(false)
1313
+ sel.removeAllRanges()
1314
+ sel.addRange(range)
1315
+ }
1316
+ if (document.execCommand('insertText', false, text)) return 'ok'
1317
+ }
1318
+ } catch {}
1319
+ try { navigator.clipboard.writeText(text) } catch {}
1320
+ return 'copied'
1321
+ }
1322
+
1323
+
1324
+ // ── 表单编辑:Document API 双向同步(v0.4)──────────────────────────────
1325
+
1326
+ /** yaml 库:bundle 内 YamlLibSrc 源经 new Function 隔离构造(懒加载,避开其他插件
1327
+ * 加载期的全局污染窗口);plain Node(单测)退回 require('yaml')。 */
1328
+ function getYamlLib() {
1329
+ try { if (typeof YamlLib !== 'undefined' && YamlLib) return YamlLib } catch {}
1330
+ try { if (typeof makeYamlLibIsolated === 'function') { YamlLib = makeYamlLibIsolated(); return YamlLib } } catch {}
1331
+ try { return require('yaml') } catch { return null }
1332
+ }
1333
+
1334
+ /** 解析编辑器文本为 Document;语法错误返回 null(表单不可用)。 */
1335
+ function fmDoc(text) {
1336
+ const lib = getYamlLib()
1337
+ if (!lib) return null
1338
+ try {
1339
+ const doc = lib.parseDocument(String(text || ''), { keepSourceTokens: true })
1340
+ return doc.errors.length === 0 ? doc : null
1341
+ } catch { return null }
1342
+ }
1343
+
1344
+ /** setIn:写标量/对象;中间节点缺失自动创建。返回新文本。 */
1345
+ function fmSet(text, path, value) {
1346
+ const doc = fmDoc(text)
1347
+ if (!doc) return text
1348
+ try { doc.setIn(path, value) } catch { return text }
1349
+ return doc.toString()
1350
+ }
1351
+
1352
+ /** deleteIn:删除键或序列项。返回新文本。 */
1353
+ function fmDel(text, path) {
1354
+ const doc = fmDoc(text)
1355
+ if (!doc) return text
1356
+ try { doc.deleteIn(path) } catch { return text }
1357
+ return doc.toString()
1358
+ }
1359
+
1360
+ /** 向序列(如 phases / links / gates)追加一个普通对象。 */
1361
+ function fmAppend(text, path, value) {
1362
+ const doc = fmDoc(text)
1363
+ if (!doc) return text
1364
+ try {
1365
+ const seq = doc.getIn(path, true)
1366
+ if (seq && typeof seq.add === 'function') seq.add(value)
1367
+ else doc.setIn(path, [value])
1368
+ } catch { return text }
1369
+ return doc.toString()
1370
+ }
1371
+
1372
+ /** 读路径上的 JS 值(缺失 → dflt)。 */
1373
+ function fmGet(text, path, dflt) {
1374
+ const doc = fmDoc(text)
1375
+ if (!doc) return dflt
1376
+ const v = doc.getIn(path)
1377
+ return v === undefined || v === null ? dflt : v
1378
+ }
1379
+
1380
+ const fmSeqLen = (doc, path) => { const s = doc.getIn(path, true); return s && s.items ? s.items.length : 0 }
1381
+
1382
+ /** 删除环节 + 级联:所有指向被删 id 的 on_success/on_gate_fail 重置(next/break)。 */
1383
+ function fmDeleteLink(text, phaseIndex, linkIndex) {
1384
+ const doc = fmDoc(text)
1385
+ if (!doc) return text
1386
+ const linksPath = ['phases', phaseIndex, 'links']
1387
+ const deletedId = String(doc.getIn([...linksPath, linkIndex, 'id']) ?? '')
1388
+ try { doc.getIn(linksPath, true).delete(linkIndex) } catch { return text }
1389
+ if (deletedId) {
1390
+ const pc = fmSeqLen(doc, ['phases'])
1391
+ for (let pi = 0; pi < pc; pi++) {
1392
+ const lc = fmSeqLen(doc, ['phases', pi, 'links'])
1393
+ for (let li = 0; li < lc; li++) {
1394
+ for (const field of ['on_success', 'on_gate_fail']) {
1395
+ const v = doc.getIn(['phases', pi, 'links', li, field])
1396
+ if (v === deletedId || v === 'goto:' + deletedId) {
1397
+ doc.setIn(['phases', pi, 'links', li, field], field === 'on_success' ? 'next' : 'break')
1398
+ }
1399
+ }
1400
+ }
1401
+ }
1402
+ }
1403
+ return doc.toString()
1404
+ }
1405
+
1406
+ /** 删除阶段 + 级联重置其下所有环节 id 的引用。 */
1407
+ function fmDeletePhase(text, phaseIndex) {
1408
+ const doc = fmDoc(text)
1409
+ if (!doc) return text
1410
+ const deletedIds = []
1411
+ const lc0 = fmSeqLen(doc, ['phases', phaseIndex, 'links'])
1412
+ for (let li = 0; li < lc0; li++) {
1413
+ const id = doc.getIn(['phases', phaseIndex, 'links', li, 'id'])
1414
+ if (id) deletedIds.push(String(id))
1415
+ }
1416
+ try { doc.getIn(['phases'], true).delete(phaseIndex) } catch { return text }
1417
+ const pc = fmSeqLen(doc, ['phases'])
1418
+ for (let pi = 0; pi < pc; pi++) {
1419
+ const lc = fmSeqLen(doc, ['phases', pi, 'links'])
1420
+ for (let li = 0; li < lc; li++) {
1421
+ for (const field of ['on_success', 'on_gate_fail']) {
1422
+ const v = doc.getIn(['phases', pi, 'links', li, field])
1423
+ if (v && (deletedIds.includes(v) || deletedIds.includes(String(v).replace(/^goto:/, '')))) {
1424
+ doc.setIn(['phases', pi, 'links', li, field], field === 'on_success' ? 'next' : 'break')
1425
+ }
1426
+ }
1427
+ }
1428
+ }
1429
+ return doc.toString()
1430
+ }
1431
+
1432
+ /** 环节改 id + 级联:所有引用旧 id 的流转值同步替换(含 goto: 前缀)。 */
1433
+ function fmSetLinkId(text, phaseIndex, linkIndex, newId) {
1434
+ const doc = fmDoc(text)
1435
+ if (!doc) return text
1436
+ const oldId = String(doc.getIn(['phases', phaseIndex, 'links', linkIndex, 'id']) ?? '')
1437
+ doc.setIn(['phases', phaseIndex, 'links', linkIndex, 'id'], newId)
1438
+ if (!oldId || oldId === newId) return doc.toString()
1439
+ const pc = fmSeqLen(doc, ['phases'])
1440
+ for (let pi = 0; pi < pc; pi++) {
1441
+ const lc = fmSeqLen(doc, ['phases', pi, 'links'])
1442
+ for (let li = 0; li < lc; li++) {
1443
+ for (const field of ['on_success', 'on_gate_fail']) {
1444
+ const v = doc.getIn(['phases', pi, 'links', li, field])
1445
+ if (v === oldId) doc.setIn(['phases', pi, 'links', li, field], newId)
1446
+ else if (v === 'goto:' + oldId) doc.setIn(['phases', pi, 'links', li, field], 'goto:' + newId)
1447
+ }
1448
+ }
1449
+ }
1450
+ return doc.toString()
1451
+ }
1452
+
1453
+ const ICON = '<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="1.5" y="1.5" width="5" height="4.5" rx="1"/><rect x="9.5" y="10" width="5" height="4.5" rx="1"/><path d="M4 6v3.5A1.5 1.5 0 0 0 5.5 11h4"/></svg>'
1454
+
1455
+ function sidebarRoot() {
1456
+ const column = document.querySelector(PRC_SIDEBAR_COLUMN_SELECTOR)
1457
+ if (column === null) return undefined
1458
+ const logoOwner = column.querySelector('[class*="logoRow"]') && column.querySelector('[class*="logoRow"]').parentElement
1459
+ return logoOwner || (column.firstElementChild || undefined)
1460
+ }
1461
+
1462
+ function newSessionButton(root) {
1463
+ const nested = root.querySelector('button[class*="newSession"]')
1464
+ if (nested) return nested
1465
+ for (const child of root.children) {
1466
+ if (child instanceof HTMLButtonElement && !child.matches('[' + ENTRY_ATTR + ']')) return child
1467
+ }
1468
+ const byAria = root.querySelector('button[aria-label="新建会话"], button[aria-label="New Session"], button[aria-label*="新会话"], button[aria-label*="new session" i]')
1469
+ if (byAria) return byAria
1470
+ const buttons = Array.from(root.querySelectorAll('button'))
1471
+ return buttons.find((b) => !b.matches('[' + ENTRY_ATTR + ']') && /新会话|新建会话|new session/i.test(b.textContent || ''))
1472
+ }
1473
+
1474
+ function createEntry(controller, t) {
1475
+ const entry = document.createElement('button')
1476
+ entry.type = 'button'
1477
+ entry.setAttribute(ENTRY_ATTR, '')
1478
+ entry.className = 'dswfe-entry'
1479
+ entry.setAttribute('aria-label', t('entryAria'))
1480
+ entry.innerHTML = '<span class="dswfe-entry-icon">' + ICON + '</span><span class="dswfe-entry-label"></span><span class="dswfe-entry-stats"></span>'
1481
+ entry.addEventListener('click', () => controller.togglePanel())
1482
+ return entry
1483
+ }
1484
+
1485
+ function setRollValue(slot, value) {
1486
+ const text = String(value)
1487
+ if (slot.dataset.value === text) return
1488
+ const previous = slot.dataset.value
1489
+ slot.dataset.value = text
1490
+ slot.style.minWidth = text.length + 'ch'
1491
+ if (previous === undefined) { slot.textContent = text; return }
1492
+ if (slot.dataset.busy === '1') { slot.dataset.busy = ''; slot.dataset.anim = '' }
1493
+ const oldEl = document.createElement('span'); oldEl.className = 'dswfe-rn'; oldEl.textContent = previous
1494
+ const newEl = document.createElement('span'); newEl.className = 'dswfe-rn dswfe-rn-next'; newEl.textContent = text
1495
+ slot.replaceChildren(oldEl, newEl)
1496
+ slot.dataset.dir = value > Number(previous) ? 'up' : 'down'
1497
+ slot.dataset.busy = '1'
1498
+ requestAnimationFrame(() => { slot.dataset.anim = '1' })
1499
+ const finish = () => {
1500
+ if (slot.dataset.busy !== '1') return
1501
+ slot.dataset.busy = ''; slot.dataset.anim = ''
1502
+ slot.textContent = slot.dataset.value || ''
1503
+ }
1504
+ slot.addEventListener('transitionend', finish, { once: true })
1505
+ setTimeout(finish, 400)
1506
+ }
1507
+
1508
+ function wireEntrySync(entry, controller, t) {
1509
+ const stats = entry.querySelector('.dswfe-entry-stats')
1510
+ const label = entry.querySelector('.dswfe-entry-label')
1511
+ const slots = []
1512
+ if (stats) {
1513
+ for (let i = 0; i < 2; i++) {
1514
+ if (i > 0) { const sep = document.createElement('span'); sep.className = 'dswfe-entry-sep'; sep.textContent = '|'; stats.append(sep) }
1515
+ const slot = document.createElement('span')
1516
+ slot.className = 'dswfe-roll'
1517
+ slot.dataset.stat = i === 0 ? 'user' : 'bundled'
1518
+ stats.append(slot); slots.push(slot)
1519
+ }
1520
+ }
1521
+ const sync = () => {
1522
+ const s = controller.getSnapshot()
1523
+ if (s.panelOpen) entry.dataset.active = 'true'; else delete entry.dataset.active
1524
+ const user = s.processes.filter((p) => p.source === 'user').length
1525
+ const bundled = s.processes.filter((p) => p.source === 'bundled').length
1526
+ if (slots[0]) setRollValue(slots[0], user)
1527
+ if (slots[1]) setRollValue(slots[1], bundled)
1528
+ if (label) label.textContent = t('title')
1529
+ entry.setAttribute('aria-label', t('entryAria'))
1530
+ entry.title = t('entryTitle', { user, bundled })
1531
+ }
1532
+ return sync
1533
+ }
1534
+
1535
+ function placeEntry(root, entry) {
1536
+ const button = newSessionButton(root)
1537
+ if (!button) return false
1538
+ if (entry.parentElement !== root) {
1539
+ const family = Array.from(root.children).filter((el) => el instanceof HTMLElement
1540
+ && el.matches('[' + ENTRY_ATTR + '], [data-dsh-atb-entry], [data-dsh-taskboard-entry], [data-dsh-ssh-entry]'))
1541
+ if (family.length > 0) {
1542
+ const last = family[family.length - 1]
1543
+ last.parentElement.insertBefore(entry, last.nextSibling)
1544
+ } else {
1545
+ const row = button.closest('[class*="logoRow"]')
1546
+ const base = (row && row.parentElement === root) ? row : button
1547
+ root.insertBefore(entry, base.nextSibling)
1548
+ }
1549
+ }
1550
+ return true
1551
+ }
1552
+
1553
+ function mountSidebarEntry(controller, t) {
1554
+ const entry = createEntry(controller, t)
1555
+ const debug = { attempts: 0, found: false, placed: false }
1556
+ try {
1557
+ const host = globalThis.location && globalThis.location.hostname
1558
+ if (host === 'localhost' || host === '127.0.0.1') window.__prcDebug = debug
1559
+ } catch {}
1560
+ let root
1561
+ let placed = false
1562
+ const tryPlace = () => {
1563
+ debug.attempts++
1564
+ if (root && !root.isConnected) { rootObserver.disconnect(); root = undefined; placed = false }
1565
+ if (placed) {
1566
+ if (document.body.contains(entry)) return
1567
+ rootObserver.disconnect(); root = undefined; placed = false
1568
+ }
1569
+ root = root || sidebarRoot()
1570
+ if (!root) return
1571
+ debug.found = !!newSessionButton(root)
1572
+ placed = placeEntry(root, entry)
1573
+ debug.placed = placed
1574
+ if (placed) rootObserver.observe(root, { childList: true, subtree: true })
1575
+ }
1576
+ const waitObserver = new MutationObserver(() => tryPlace())
1577
+ waitObserver.observe(document.body, { childList: true, subtree: true })
1578
+ const rootObserver = new MutationObserver(() => {
1579
+ if (!root || !root.isConnected) { placed = false; tryPlace(); return }
1580
+ if (!root.contains(entry)) placed = placeEntry(root, entry)
1581
+ })
1582
+ const retry = setInterval(() => tryPlace(), 2000)
1583
+ const sync = wireEntrySync(entry, controller, t)
1584
+ const unsubscribe = controller.subscribe(sync)
1585
+ sync()
1586
+ tryPlace()
1587
+ return () => {
1588
+ clearInterval(retry)
1589
+ waitObserver.disconnect()
1590
+ rootObserver.disconnect()
1591
+ unsubscribe()
1592
+ entry.remove()
1593
+ }
1594
+ }
1595
+
1596
+ // ── 工具函数 ─────────────────────────────────────────────────────────────
1597
+
1598
+ function complexityLabel(t, v) {
1599
+ const key = { low: 'cxLow', medium: 'cxMid', high: 'cxHigh' }[v]
1600
+ return key ? t(key) : String(v)
1601
+ }
1602
+
1603
+ function filterProcesses(state) {
1604
+ const q = state.search.trim().toLowerCase()
1605
+ const rows = state.processes.filter((p) =>
1606
+ (state.filters.source === 'all' || p.source === state.filters.source)
1607
+ && (state.filters.category === '' || p.category === state.filters.category)
1608
+ && (state.filters.complexity === '' || p.complexity === state.filters.complexity)
1609
+ && (q === '' || (p.name + ' ' + (p.display_name || '') + ' ' + (p.description || '')).toLowerCase().includes(q)))
1610
+ const rank = { low: 0, medium: 1, high: 2 }
1611
+ const sorted = [...rows]
1612
+ if (state.sortBy === 'updated') sorted.sort((a, b) => b.mtime - a.mtime)
1613
+ else if (state.sortBy === 'complexity') sorted.sort((a, b) => (rank[a.complexity] ?? 9) - (rank[b.complexity] ?? 9) || a.relPath.localeCompare(b.relPath))
1614
+ else if (state.sortBy === 'links') sorted.sort((a, b) => b.linkCount - a.linkCount)
1615
+ else sorted.sort((a, b) => a.relPath.localeCompare(b.relPath))
1616
+ return sorted
1617
+ }
1618
+
1619
+ function flowLabel(t, v) {
1620
+ if (v === 'next') return t('flowNext')
1621
+ if (v === 'end') return t('flowEnd')
1622
+ if (v === 'break') return t('flowBreak')
1623
+ return String(v)
1624
+ }
1625
+
1626
+ function linkExpert(ln) { return (ln && (ln.expert_name || ln.expert)) || undefined }
1627
+
1628
+ /** 极轻量 YAML 着色:注释灰、键蓝、其余默认。 */
1629
+ function colorizeLine(line) {
1630
+ const trimmed = line.trimStart()
1631
+ if (trimmed.startsWith('#')) return [h('span', { className: 'dswfe-cm' }, line)]
1632
+ const m = line.match(/^(\s*(?:-\s+)?)([A-Za-z_][\w.-]*)(:)(.*)$/)
1633
+ if (m) {
1634
+ return [m[1], h('span', { className: 'dswfe-key' }, m[2] + ':'), m[4] ? colorizeScalar(m[4]) : '']
1635
+ }
1636
+ return [line]
1637
+ }
1638
+ function colorizeScalar(rest) {
1639
+ const t = rest.trim()
1640
+ if (t === '' || t === '|' || t === '>' || t === '|-' || t === '>-') return rest
1641
+ if (t.startsWith('#')) return [h('span', { className: 'dswfe-cm' }, rest)]
1642
+ return rest
1643
+ }
1644
+
1645
+ // ── 组件 ─────────────────────────────────────────────────────────────────
1646
+
1647
+ function useControllerState(controller) {
1648
+ const getSnap = useCallback(() => controller.getSnapshot(), [controller])
1649
+ const subscribe = useCallback((cb) => controller.subscribe(cb), [controller])
1650
+ return useSyncExternalStore(subscribe, getSnap)
1651
+ }
1652
+ let useSyncExternalStore = __React.useSyncExternalStore
1653
+ || ((subscribe, getSnap) => {
1654
+ const [v, setV] = useState(getSnap)
1655
+ useEffect(() => subscribe(() => setV(getSnap())), [subscribe, getSnap])
1656
+ return v
1657
+ })
1658
+
1659
+ function Menu({ x, y, items, onClose }) {
1660
+ return h('div', null,
1661
+ h('div', { className: 'dswfe-menuback', onClick: onClose, onContextMenu: (e) => { e.preventDefault(); onClose() } }),
1662
+ h('div', { className: 'dswfe-menu', style: { left: Math.max(4, x) + 'px', top: Math.max(4, y) + 'px' } },
1663
+ items.map((it, i) => h('button', { key: i, onClick: () => { onClose(); it.onClick() } }, it.label))))
1664
+ }
1665
+
1666
+ function anchorMenu(btn, items, onClose) {
1667
+ let pos = { x: 100, y: 100 }
1668
+ try { const r = btn.getBoundingClientRect(); pos = { x: r.left, y: r.bottom + 4 } } catch {}
1669
+ return h(Menu, { x: pos.x, y: pos.y, items, onClose })
1670
+ }
1671
+
1672
+ function Toolbar({ state, controller, t }) {
1673
+ const [menu, setMenu] = useState(null) // {kind, btn}
1674
+ const categories = useMemo(() => [...new Set(state.processes.map((p) => p.category).filter(Boolean))].sort(), [state.processes])
1675
+ const user = state.processes.filter((p) => p.source === 'user').length
1676
+ const bundled = state.processes.filter((p) => p.source === 'bundled').length
1677
+ const sel = state.item && state.item.meta
1678
+ const openMenu = (kind) => (e) => setMenu(menu && menu.kind === kind ? null : { kind, btn: e.currentTarget })
1679
+ return h('div', { className: 'dswfe-toolbar' },
1680
+ h('h2', { className: 'dswfe-title' }, t('title')),
1681
+ h('span', { className: 'dswfe-count' }, t('count', { user, bundled })),
1682
+ h('div', { className: 'dswfe-tabs', style: { borderBottom: 'none', margin: '0 4px' } },
1683
+ h('button', { className: 'dswfe-tab', 'data-on': state.view === 'lib' ? 'true' : undefined, onClick: () => controller.setView('lib') }, t('viewLib')),
1684
+ h('button', { className: 'dswfe-tab', 'data-on': state.view === 'exec' ? 'true' : undefined, onClick: () => controller.setView('exec') }, t('viewExec'))),
1685
+ h('input', { className: 'dswfe-input dswfe-search', value: state.search, placeholder: t('searchPlaceholder'), spellCheck: false, onChange: (e) => controller.setSearch(e.target.value) }),
1686
+ h('select', { className: 'dswfe-select', value: state.filters.source, onChange: (e) => controller.setFilter('source', e.target.value) },
1687
+ h('option', { value: 'all' }, t('filterAll')), h('option', { value: 'user' }, t('filterUser')), h('option', { value: 'bundled' }, t('filterBundled'))),
1688
+ h('select', { className: 'dswfe-select', value: state.filters.category, onChange: (e) => controller.setFilter('category', e.target.value) },
1689
+ h('option', { value: '' }, t('categoryAll')), categories.map((c) => h('option', { key: c, value: c }, c))),
1690
+ h('select', { className: 'dswfe-select', value: state.filters.complexity, onChange: (e) => controller.setFilter('complexity', e.target.value) },
1691
+ h('option', { value: '' }, t('complexityAll')), [['low', t('cxLow')], ['medium', t('cxMid')], ['high', t('cxHigh')]].map(([v, label]) => h('option', { key: v, value: v }, label))),
1692
+ h('select', { className: 'dswfe-select', value: state.sortBy, title: t('sortDefault'), onChange: (e) => controller.setSortBy(e.target.value) },
1693
+ h('option', { value: 'default' }, t('sortDefault')), h('option', { value: 'updated' }, t('sortUpdated')),
1694
+ h('option', { value: 'complexity' }, t('sortComplexity')), h('option', { value: 'links' }, t('sortLinks'))),
1695
+ h('div', { className: 'dswfe-spacer' }),
1696
+ h('button', { className: 'dswfe-btn', title: t('aiBtn'), onClick: () => controller.setState({ dialog: { type: 'ai' } }) }, '⚡ ' + t('aiBtn')),
1697
+ h('button', { className: 'dswfe-btn', 'data-primary': 'true', onClick: openMenu('new') }, '+ ' + t('newTask')),
1698
+ h('button', { className: 'dswfe-btn', onClick: () => controller.setState({ dialog: { type: 'import' } }) }, t('importBtn')),
1699
+ h('button', { className: 'dswfe-btn', onClick: openMenu('export') }, t('exportBtn')),
1700
+ h('button', { className: 'dswfe-btn', onClick: () => controller.setState({ dialog: { type: 'settings' } }) }, t('settingsBtn')),
1701
+ h('button', { className: 'dswfe-btn', title: t('close'), onClick: () => controller.closePanel() }, '✕'),
1702
+ menu === null ? null
1703
+ : menu.kind === 'new'
1704
+ ? anchorMenu(menu.btn, [
1705
+ { label: t('newBlank'), onClick: () => controller.setState({ dialog: { type: 'create' } }) },
1706
+ { label: t('newFromExisting'), onClick: () => controller.setState({ dialog: { type: 'copy', fromId: sel ? sel.id : undefined } }) },
1707
+ ], () => setMenu(null))
1708
+ : anchorMenu(menu.btn, [
1709
+ { label: t('exportAll'), onClick: () => download(API + '/export?all=1') },
1710
+ { label: t('exportUser'), onClick: () => download(API + '/export?source=user') },
1711
+ { label: t('exportOne'), onClick: () => { if (sel) download(API + '/export?id=' + encodeURIComponent(sel.id)) } },
1712
+ ], () => setMenu(null)))
1713
+ }
1714
+
1715
+ function download(url) {
1716
+ const a = document.createElement('a')
1717
+ a.href = url
1718
+ a.rel = 'noopener'
1719
+ document.body.appendChild(a)
1720
+ a.click()
1721
+ a.remove()
1722
+ }
1723
+
1724
+ function ListPane({ state, controller, t }) {
1725
+ const rows = filterProcesses(state)
1726
+ const userRows = rows.filter((p) => p.source === 'user')
1727
+ const bundledRows = rows.filter((p) => p.source === 'bundled')
1728
+ const onKey = (e) => {
1729
+ if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return
1730
+ e.preventDefault()
1731
+ const ids = rows.map((p) => p.id)
1732
+ if (ids.length === 0) return
1733
+ const idx = ids.indexOf(state.selectedId)
1734
+ const next = e.key === 'ArrowDown' ? ids[Math.min(ids.length - 1, idx + 1)] || ids[0] : ids[Math.max(0, idx - 1)]
1735
+ controller.select(next)
1736
+ }
1737
+ const row = (p) => h('button', {
1738
+ key: p.id, className: 'dswfe-row', role: 'button', tabIndex: 0,
1739
+ 'data-selected': state.selectedId === p.id ? 'true' : undefined,
1740
+ 'data-source': p.source, 'data-complexity': p.complexity || 'medium',
1741
+ onClick: () => controller.select(p.id),
1742
+ onKeyDown: (e) => { if ((e.key === 'Enter' || e.key === ' ') && e.target === e.currentTarget) { e.preventDefault(); controller.select(p.id) } },
1743
+ },
1744
+ h('div', { className: 'dswfe-row-name' },
1745
+ h('span', { className: 'lbl' }, p.display_name || p.name),
1746
+ p.errors > 0 ? h('span', { className: 'dswfe-dot', 'data-kind': 'err', title: p.errors + t('errOne') }) : null,
1747
+ p.warnings > 0 ? h('span', { className: 'dswfe-dot', 'data-kind': 'warn', title: p.warnings + t('warnOne') }) : null),
1748
+ h('div', { className: 'dswfe-row-meta' },
1749
+ h('span', null, p.name),
1750
+ p.complexity ? h('span', { className: 'dswfe-badge' }, complexityLabel(t, p.complexity)) : null,
1751
+ p.version ? h('span', null, 'v' + p.version) : null,
1752
+ h('span', null, p.phaseCount + t('phases') + ' · ' + p.linkCount + t('links'))))
1753
+ const group = (label, items) => h('div', null,
1754
+ h('div', { className: 'dswfe-group' }, label, h('span', null, items.length)),
1755
+ items.map(row))
1756
+ return h('div', { className: 'dswfe-list', onKeyDown: onKey, tabIndex: 0 },
1757
+ rows.length === 0
1758
+ ? h('div', { style: { padding: '18px 8px', color: 'var(--dsw-text-secondary, gray)', fontSize: 12 } }, t('emptyList'), h('div', { style: { marginTop: 4, opacity: .8 } }, t('emptyListHint')))
1759
+ : [group(t('mine'), userRows), group(t('bundled'), bundledRows)])
1760
+ }
1761
+
1762
+ function DiagList({ diagnostics, t, onJump }) {
1763
+ const items = [...(diagnostics.errors || []).map((d) => ({ ...d, kind: 'err' })), ...(diagnostics.warnings || []).map((d) => ({ ...d, kind: 'warn' }))]
1764
+ if (items.length === 0) return h('div', { className: 'dswfe-diag', style: { opacity: .75 } }, t('noIssues'))
1765
+ return h('div', { className: 'dswfe-diag' }, items.map((d, i) => h('button', {
1766
+ key: i, className: 'dswfe-diag-item', 'data-kind': d.kind,
1767
+ onClick: () => onJump && d.line && onJump(d.line),
1768
+ },
1769
+ h('span', { className: 'dswfe-diag-line' }, d.line ? 'L' + d.line : ''),
1770
+ h('span', { className: 'dswfe-diag-code' }, d.kind === 'err' ? '✗' : '⚠'),
1771
+ h('span', null, d.message),
1772
+ h('span', { style: { opacity: .5, marginLeft: 'auto', flex: 'none' } }, d.code))))
1773
+ }
1774
+
1775
+ function StructureLinkCard({ t, ln, phaseId, index }) {
1776
+ const [open, setOpen] = useState(false)
1777
+ const meta = []
1778
+ // 环节级 model 运行时不被读取(execution.js 只用 run.model),不展示也不配置
1779
+ meta.push(execLabel(t, { reviewType: ln.review_type || 'ai' }))
1780
+ if (Array.isArray(ln.gates) && ln.gates.length) meta.push(t('flowGate', { min: ln.gates.map((g) => (g && g.min_score != null ? g.min_score : '?')).join('/') }))
1781
+ if (ln.max_rework !== undefined && ln.max_rework !== null) meta.push(t('flowRework', { n: ln.max_rework }))
1782
+ return h('div', { className: 'dswfe-link' },
1783
+ h('button', { className: 'dswfe-link-row', onClick: () => setOpen(!open), 'aria-expanded': open },
1784
+ h('span', { className: 'dswfe-link-id' }, t('linkNo', { n: index })),
1785
+ h('span', null, ln.name || ''),
1786
+ h('span', { className: 'dswfe-link-meta' }, meta.join(' · '))),
1787
+ !open ? null : h('div', { className: 'dswfe-link-body' },
1788
+ ln.prompt ? h('div', null, h('div', { style: { fontSize: 11, opacity: .65, marginBottom: 3 } }, t('prompt')), h('pre', { className: 'dswfe-pre' }, ln.prompt)) : null,
1789
+ h('div', { className: 'dswfe-kv' }, h('b', null, t('onSuccess') + ':'), flowLabel(t, ln.on_success || '—')),
1790
+ h('div', { className: 'dswfe-kv' }, h('b', null, t('onGateFail') + ':'), flowLabel(t, ln.on_gate_fail || '—')),
1791
+ ln.review_type ? h('div', { className: 'dswfe-kv' }, h('b', null, t('reviewType') + ':'), t(ln.review_type === 'human' ? 'reviewHuman' : ln.review_type === 'none' ? 'reviewNone' : 'reviewAi')) : null,
1792
+ ln.review_prompt ? h('div', { className: 'dswfe-kv' }, h('b', null, t('reviewPrompt') + ':'), h('span', { style: { whiteSpace: 'pre-wrap' } }, ln.review_prompt)) : null,
1793
+ ln.acceptance_criteria ? h('div', { className: 'dswfe-kv' }, h('b', null, t('acceptance') + ':'), h('span', { style: { whiteSpace: 'pre-wrap' } }, ln.acceptance_criteria)) : null,
1794
+ Array.isArray(ln.expected_artifacts) && ln.expected_artifacts.length > 0 ? h('div', { className: 'dswfe-kv' },
1795
+ h('b', null, t('artifacts') + ':'),
1796
+ h('span', null, ln.expected_artifacts.map((a) => (a && (a.path || a.name)) || '').filter(Boolean).join(' · '))) : null,
1797
+ Array.isArray(ln.gates) && ln.gates.length > 0 ? h('div', { className: 'dswfe-kv' },
1798
+ h('b', null, t('gates') + ':'),
1799
+ h('span', null, ln.gates.map((g) => (g ? (g.name || '?') + (g.min_score !== undefined && g.min_score !== null ? ' ≥' + g.min_score : '') : '')).join(' · '))) : null,
1800
+ h('div', { style: { fontSize: 11, opacity: .55 } }, phaseId)))
1801
+ }
1802
+
1803
+ function StructureTab({ t, parsed }) {
1804
+ const phases = parsed && Array.isArray(parsed.phases) ? parsed.phases : []
1805
+ if (phases.length === 0) return h('div', { className: 'dswfe-empty' }, '—')
1806
+ let seq = 0
1807
+ return h('div', null, phases.map((ph, i) => {
1808
+ const links = Array.isArray(ph.links) ? ph.links : []
1809
+ return h('div', { className: 'dswfe-phase', key: ph.id || i },
1810
+ h('div', { className: 'dswfe-phase-head' },
1811
+ h('span', { className: 'dswfe-badge' }, t('phaseNo', { n: i + 1 })),
1812
+ h('span', null, ph.name || ''),
1813
+ h('span', { className: 'dswfe-link-meta' }, links.length + ' ' + t('links'))),
1814
+ ph.spec ? h('div', { className: 'dswfe-phase-spec' }, ph.spec) : null,
1815
+ ph.acceptance_criteria ? h('div', { className: 'dswfe-kv' }, h('b', null, t('acceptance') + ':'), h('span', { style: { whiteSpace: 'pre-wrap' } }, ph.acceptance_criteria)) : null,
1816
+ links.map((ln, j) => { seq += 1; return h(StructureLinkCard, { key: ln.id || j, t, ln, phaseId: ph.id, index: seq }) }))
1817
+ }))
1818
+ }
1819
+
1820
+ function YamlView({ yaml, highlightLine }) {
1821
+ const boxRef = useRef(null)
1822
+ const lines = useMemo(() => String(yaml || '').split('\n'), [yaml])
1823
+ useEffect(() => {
1824
+ if (!highlightLine || !boxRef.current) return
1825
+ const el = boxRef.current.querySelector('[data-line="' + highlightLine + '"]')
1826
+ if (el) el.scrollIntoView({ block: 'center' })
1827
+ }, [highlightLine, yaml])
1828
+ return h('div', { className: 'dswfe-code', ref: boxRef },
1829
+ lines.map((line, i) => h('div', { key: i, className: 'dswfe-code-line', 'data-line': i + 1, 'data-hl': highlightLine === i + 1 ? 'true' : undefined },
1830
+ h('span', { className: 'dswfe-code-no' }, i + 1),
1831
+ h('span', { className: 'dswfe-code-tx' }, colorizeLine(line)))))
1832
+ }
1833
+
1834
+ function OverviewTab({ t, meta, parsed, diagnostics, onJump }) {
1835
+ const limits = parsed && parsed.limits
1836
+ const abnormal = parsed && parsed.abnormal_handler
1837
+ const phases = parsed && Array.isArray(parsed.phases) ? parsed.phases : []
1838
+ let seq = 0
1839
+ const outline = []
1840
+ phases.forEach((ph, pi) => {
1841
+ const links = Array.isArray(ph.links) ? ph.links : []
1842
+ outline.push(h('div', { className: 'dswfe-ovphase', key: 'ph' + pi },
1843
+ h('span', { className: 'dswfe-badge' }, t('phaseNo', { n: pi + 1 })),
1844
+ h('span', null, ph.name || '')))
1845
+ links.forEach((ln, li) => {
1846
+ seq += 1
1847
+ outline.push(h('div', { className: 'dswfe-ovlink', key: 'ln' + pi + '-' + li },
1848
+ h('span', { className: 'dswfe-ovno' }, t('linkNo', { n: seq })),
1849
+ h('span', { className: 'dswfe-ovname' }, ln.name || ln.id || ''),
1850
+ h('span', { className: 'dswfe-ovkind' }, [
1851
+ execLabel(t, { reviewType: ln.review_type || 'ai' }),
1852
+ (Array.isArray(ln.gates) && ln.gates.length > 0)
1853
+ ? t('flowGate', { min: Math.min(...ln.gates.map((g) => Number(g && g.min_score) || 0)) })
1854
+ : t('flowNoGate'),
1855
+ ln.max_rework === null || ln.max_rework === undefined ? null : t('flowRework', { n: ln.max_rework }),
1856
+ ].filter(Boolean).join(' · '))))
1857
+ })
1858
+ })
1859
+ return h('div', null,
1860
+ h('div', { className: 'dswfe-kv' }, h('b', null, t('name') + ':'), meta.name),
1861
+ limits ? h('div', { className: 'dswfe-kv' }, h('b', null, t('limits') + ':'),
1862
+ (limits.max_step_executions == null ? t('unlimited') : limits.max_step_executions + ' ' + t('steps')) + ' · '
1863
+ + (limits.max_total_tokens == null ? t('unlimited') : limits.max_total_tokens + ' ' + t('tokens'))) : null,
1864
+ abnormal && Array.isArray(abnormal.trigger_on) ? h('div', { className: 'dswfe-kv' }, h('b', null, t('abnormal') + ':'), abnormal.trigger_on.join(', ')) : null,
1865
+ h('div', { className: 'dswfe-sec' },
1866
+ h('h4', null, t('overviewTitle')),
1867
+ meta.description ? h('p', { className: 'dswfe-desc' }, meta.description) : null,
1868
+ outline.length === 0 ? h('div', { className: 'dswfe-diag', style: { opacity: .75 } }, t('overviewEmpty')) : h('div', { className: 'dswfe-outline' }, outline)),
1869
+ h('div', { className: 'dswfe-sec' }, h('h4', null, t('diagnostics')), h(DiagList, { t, diagnostics, onJump })))
1870
+ }
1871
+
1872
+ function DetailPane({ state, controller, t }) {
1873
+ const item = state.item
1874
+ const meta = item && item.meta
1875
+ const isUser = meta && meta.source === 'user'
1876
+ const [confirmDelete, setConfirmDelete] = useState(false)
1877
+ const jump = (line) => { controller.setState({ highlightLine: line }); controller.setTab('yaml') }
1878
+ const copyYaml = () => {
1879
+ if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(item.yaml).then(() => controller.toast(t('copied'))).catch(() => {})
1880
+ }
1881
+ const atAgent = () => controller.atAgent(meta)
1882
+ if (state.itemLoading) return h('div', { className: 'dswfe-detail' }, t('loading'))
1883
+ if (!item || !meta) return h('div', { className: 'dswfe-empty' }, h('div', null, t('emptyDetail')), h('div', { style: { fontSize: 12, opacity: .8 } }, t('selectFirst')))
1884
+ return h('div', { className: 'dswfe-detail' },
1885
+ h('div', { className: 'dswfe-detail-head' },
1886
+ h('h3', { className: 'dswfe-detail-title' }, meta.display_name || meta.name),
1887
+ h('div', { className: 'dswfe-actions' },
1888
+ isUser ? [
1889
+ h('button', { key: 'e', className: 'dswfe-btn', 'data-primary': 'true', onClick: () => controller.editSelected() }, '✎ ' + t('edit')),
1890
+ h('button', { key: 'r', className: 'dswfe-btn', onClick: () => controller.setState({ dialog: { type: 'rename', id: meta.id, name: meta.display_name || meta.name } }) }, t('rename')),
1891
+ !confirmDelete
1892
+ ? h('button', { key: 'd', className: 'dswfe-btn', onClick: () => setConfirmDelete(true) }, '🗑 ' + t('delete'))
1893
+ : h('span', { key: 'dc', style: { display: 'inline-flex', gap: 6, alignItems: 'center' } },
1894
+ h('span', { style: { fontSize: 12 } }, t('deleteConfirm') + '?'),
1895
+ h('button', { className: 'dswfe-btn', 'data-danger': 'true', onClick: () => { setConfirmDelete(false); controller.removeProcess(meta.id) } }, t('confirm')),
1896
+ h('button', { className: 'dswfe-btn', onClick: () => setConfirmDelete(false) }, t('cancel'))),
1897
+ ] : [
1898
+ h('button', { key: 'c', className: 'dswfe-btn', 'data-primary': 'true', onClick: () => controller.setState({ dialog: { type: 'copy', fromId: meta.id } }) }, '⧉ ' + t('copyToMine')),
1899
+ ],
1900
+ h('button', { key: 'run', className: 'dswfe-btn', 'data-primary': 'true', title: t('runCreate'), onClick: () => controller.setState({ dialog: { type: 'newrun', processId: meta.id } }) }, t('runCreate')),
1901
+ h('button', { key: 'x', className: 'dswfe-btn', onClick: copyYaml }, t('copyYaml')))),
1902
+ h('div', { className: 'dswfe-chips' },
1903
+ h('span', { className: 'dswfe-chip' }, isUser ? t('mine') : t('readOnly')),
1904
+ meta.category ? h('span', { className: 'dswfe-chip' }, t('category') + ': ' + meta.category) : null,
1905
+ meta.complexity ? h('span', { className: 'dswfe-chip' }, t('complexity') + ': ' + complexityLabel(t, meta.complexity)) : null,
1906
+ meta.version ? h('span', { className: 'dswfe-chip' }, 'v' + meta.version) : null,
1907
+ h('span', { className: 'dswfe-chip' }, meta.phaseCount + ' ' + t('phases') + ' · ' + meta.linkCount + ' ' + t('links')),
1908
+ item.diagnostics && item.diagnostics.errors.length > 0 ? h('span', { className: 'dswfe-badge', 'data-kind': 'err' }, item.diagnostics.errors.length + t('errOne')) : null,
1909
+ item.diagnostics && item.diagnostics.warnings.length > 0 ? h('span', { className: 'dswfe-badge', 'data-kind': 'warn' }, item.diagnostics.warnings.length + t('warnOne')) : null),
1910
+ h('div', { className: 'dswfe-tabs' },
1911
+ ['overview', 'flow', 'structure', 'yaml'].map((tab) => h('button', { key: tab, className: 'dswfe-tab', 'data-on': state.tab === tab ? 'true' : undefined, onClick: () => controller.setTab(tab) },
1912
+ t('tab' + tab[0].toUpperCase() + tab.slice(1))))),
1913
+ state.tab === 'overview' ? h(OverviewTab, { t, meta, parsed: item.parsed, diagnostics: item.diagnostics, onJump: jump })
1914
+ : state.tab === 'flow' ? h(FlowGraph, { t, parsed: item.parsed })
1915
+ : state.tab === 'structure' ? h(StructureTab, { t, parsed: item.parsed })
1916
+ : h(YamlView, { yaml: item.yaml, highlightLine: state.highlightLine }))
1917
+ }
1918
+
1919
+ // ── 编辑器 ───────────────────────────────────────────────────────────────
1920
+
1921
+ // ── 表单编辑器(v0.4):与 YAML 实时双向同步 ───────────────────────────
1922
+ // 单一数据源 = 编辑器文本(ed.text)。表单字段修改:解析当前文本 →
1923
+ // Document setIn/deleteIn/append → toString 写回 ed.text;YAML 子模式
1924
+ // 的每次输入同样写回 ed.text——两个视图天然互相同步。
1925
+
1926
+ function FormField({ label, children, help }) {
1927
+ return h('label', { className: 'dswfe-field' },
1928
+ h('span', { className: 'dswfe-field-label' }, label, help ? h(Help, { text: help }) : null),
1929
+ children)
1930
+ }
1931
+
1932
+ function FormText({ value, onChange, placeholder, multiline, rows, type }) {
1933
+ const style = { width: '100%', fontFamily: type === 'mono' ? 'ui-monospace, Menlo, monospace' : 'var(--dsw-font-family, inherit)', fontSize: 12.5, lineHeight: multiline ? 1.55 : 1.4, border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', borderRadius: 8, padding: multiline ? '7px 9px' : '5px 9px', background: 'var(--dsw-alias-bg-layer-2,transparent)', color: 'inherit', boxSizing: 'border-box', whiteSpace: multiline ? 'pre-wrap' : undefined }
1934
+ return multiline
1935
+ ? h('textarea', { value, placeholder: placeholder || '', spellCheck: false, rows: rows || 2, style: Object.assign({ resize: 'vertical' }, style), onChange: (e) => onChange(e.target.value) })
1936
+ : h('input', { value, type: type || 'text', placeholder: placeholder || '', spellCheck: false, style, onChange: (e) => onChange(e.target.value) })
1937
+ }
1938
+
1939
+ function FormSelect({ value, onChange, options }) {
1940
+ return h('select', { value, onChange: (e) => onChange(e.target.value), style: { width: '100%', border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', background: 'var(--dsw-alias-bg-layer-2,transparent)', color: 'inherit', borderRadius: 8, padding: '5px 8px', font: 'inherit', fontSize: 12.5 } },
1941
+ options.map((o) => h('option', { key: o[0], value: o[0] }, o[1])))
1942
+ }
1943
+
1944
+ // ── FormEditor(可视化表单,与 YAML 双向实时同步)─────────────────────────
1945
+ // 单一数据源 = ed.text:表单改动经 Document API(fmSet 等,注释/未知字段不丢)
1946
+ // 写回 ed.text;YAML 手改后表单随 useMemo 重新解析实时反映。
1947
+
1948
+ function FormField({ label, children, help }) {
1949
+ return h('label', { className: 'dswfe-field' },
1950
+ h('span', { className: 'dswfe-field-label' }, label, help ? h(Help, { text: help }) : null),
1951
+ children)
1952
+ }
1953
+
1954
+ function FormText({ value, onChange, placeholder, mono }) {
1955
+ return h('input', { value: String(value ?? ''), spellCheck: false, placeholder,
1956
+ style: mono ? { fontFamily: 'ui-monospace, monospace' } : undefined,
1957
+ onChange: (e) => onChange(e.target.value) })
1958
+ }
1959
+
1960
+ function FormNum({ value, onChange, placeholder, min }) {
1961
+ return h('input', { type: 'number', value: value === null || value === undefined || value === '' ? '' : String(value), min, placeholder, spellCheck: false,
1962
+ onChange: (e) => onChange(e.target.value === '' ? null : Number(e.target.value)) })
1963
+ }
1964
+
1965
+ function FormArea({ value, onChange, rows, placeholder }) {
1966
+ return h('textarea', { value: String(value ?? ''), rows: rows || 3, spellCheck: false, placeholder,
1967
+ onChange: (e) => onChange(e.target.value) })
1968
+ }
1969
+
1970
+ function FormSelect({ value, options, onChange }) {
1971
+ const cur = String(value ?? '')
1972
+ // 选项既可以是字符串,也可以是 [值, 显示文案]——后者用来把英文枚举显示成中文
1973
+ const pairs = options.map((o) => (Array.isArray(o) ? [String(o[0]), o[1]] : [String(o), o]))
1974
+ const list = pairs.some((p) => p[0] === cur) ? pairs : [[cur, cur]].concat(pairs)
1975
+ return h('select', { value: cur, onChange: (e) => onChange(e.target.value) },
1976
+ list.map((p) => h('option', { key: p[0], value: p[0] }, p[1])))
1977
+ }
1978
+
1979
+ // 模型目录 + 技能目录的模块级缓存(跨 form↔yaml 切换、跨编辑器开关复用,不设过期)
1980
+ const catalogCache = { loaded: false, models: { providers: [] }, skills: [] }
1981
+ // 画布选中态的模块级记忆:form↔yaml 切换重挂载后按 id 恢复(id 对不上自动回落 global)
1982
+ let canvasSelMemory = { kind: 'global' }
1983
+
1984
+ /** 模型两极下拉:供应商 → 模型(不让手填)。YAML 值 = 'provider/model';空 = 跟随运行模型。 */
1985
+ function ModelPicker({ value, catalog, onChange, t }) {
1986
+ const raw = String(value ?? '')
1987
+ const slash = raw.indexOf('/')
1988
+ const curProvider = slash >= 0 ? raw.slice(0, slash) : raw
1989
+ const curModel = slash >= 0 ? raw.slice(slash + 1) : ''
1990
+ const providers = (catalog.models && catalog.models.providers) || []
1991
+ const prov = providers.find((p) => p.id === curProvider)
1992
+ const models = prov ? prov.models : []
1993
+ const opts = [h('option', { key: '', value: '' }, t('modelDefault'))].concat(
1994
+ providers.map((p) => h('option', { key: p.id, value: p.id }, p.name)),
1995
+ (curProvider && !prov) ? [h('option', { key: curProvider, value: curProvider }, curProvider)] : [])
1996
+ const mopts = [h('option', { key: '', value: '' }, curProvider ? t('modelProvDefault') : t('modelDefault'))].concat(
1997
+ models.map((m) => h('option', { key: m.id, value: m.id }, m.name)),
1998
+ (curModel && (!prov || !models.some((m) => m.id === curModel))) ? [h('option', { key: curModel, value: curModel }, curModel)] : [])
1999
+ return h('div', { className: 'dswfe-modelrow' },
2000
+ h('select', {
2001
+ className: 'dswfe-native-sel', value: curProvider, title: t('formProvider'),
2002
+ onChange: (e) => { const p = e.target.value; onChange(p === '' ? null : (models.some((m) => m.id === curModel) ? p + '/' + curModel : p)) },
2003
+ }, opts),
2004
+ h('select', {
2005
+ className: 'dswfe-native-sel', value: curModel, title: '模型', disabled: curProvider === '',
2006
+ onChange: (e) => { const m = e.target.value; onChange(curProvider === '' ? null : (m === '' ? curProvider : curProvider + '/' + m)) },
2007
+ }, mopts))
2008
+ }
2009
+
2010
+ /** 技能多选下拉:dsh 技能目录(/skills),勾选写回 skills 数组。 */
2011
+ function SkillPicker({ value, skills, onChange, t }) {
2012
+ const [open, setOpen] = useState(false)
2013
+ const wrapRef = useRef(null)
2014
+ useEffect(() => {
2015
+ if (!open) return undefined
2016
+ const onDown = (e) => { if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false) }
2017
+ document.addEventListener('mousedown', onDown)
2018
+ return () => document.removeEventListener('mousedown', onDown)
2019
+ }, [open])
2020
+ const arr = Array.isArray(value) ? value.map(String)
2021
+ : (value && Array.isArray(value.items)) ? value.items.map((n) => String(n && n.value !== undefined ? n.value : n))
2022
+ : []
2023
+ const toggle = (name) => onChange(arr.includes(name) ? arr.filter((x) => x !== name) : arr.concat(name))
2024
+ return h('div', { className: 'dswfe-skillpick', ref: wrapRef },
2025
+ h('button', { type: 'button', className: 'dswfe-selbtn', onClick: () => setOpen(!open), 'data-open': open ? 'true' : undefined },
2026
+ h('span', { className: arr.length ? '' : 'dswfe-selph' }, arr.length ? arr.join(', ') : t('skillsPick')),
2027
+ h('span', { className: 'dswfe-selcar' }, open ? '▴' : '▾')),
2028
+ !open ? null : h('div', { className: 'dswfe-skillpop' },
2029
+ (!skills || skills.length === 0) ? h('div', { className: 'dswfe-skillnone' }, t('skillsNone')) :
2030
+ skills.map((s) => h('label', { key: s.name, className: 'dswfe-skillrow' },
2031
+ h('input', { type: 'checkbox', checked: arr.includes(s.name), onChange: () => toggle(s.name) }),
2032
+ h('span', { className: 'dswfe-skillname' }, s.name),
2033
+ s.description ? h('span', { className: 'dswfe-skilldesc', title: s.description }, s.description) : null)),
2034
+ arr.length ? h('button', { type: 'button', className: 'dswfe-skillclear', onClick: () => onChange([]) }, t('skillsClear', { n: arr.length })) : null))
2035
+ }
2036
+
2037
+ function FormEditor({ state, controller, t, ed }) {
2038
+ const doc = useMemo(() => fmDoc(ed.text), [ed.text])
2039
+ // 画布选中态:{kind:'global'} | {kind:'phase', id} | {kind:'link', id}。
2040
+ // 只存 id:编辑导致索引漂移时按 id 重扫,找不到(刚删掉)回落 global。
2041
+ const [sel, setSelState] = useState(() => canvasSelMemory)
2042
+ const setSel = (s) => { canvasSelMemory = s; setSelState(s) }
2043
+ // 模型目录 + dsh 技能目录(模块级缓存,编辑器每次挂载只拉一次)
2044
+ const [catalog, setCatalog] = useState(() => catalogCache)
2045
+ useEffect(() => {
2046
+ if (catalogCache.loaded) return
2047
+ let live = true
2048
+ Promise.all([api('/models').catch(() => null), api('/skills').catch(() => null)]).then(([m, s]) => {
2049
+ catalogCache.models = m || { providers: [] }
2050
+ catalogCache.skills = s && Array.isArray(s.skills) ? s.skills : []
2051
+ catalogCache.loaded = true
2052
+ if (live) setCatalog({ ...catalogCache })
2053
+ })
2054
+ return () => { live = false }
2055
+ }, [])
2056
+ if (!doc) {
2057
+ return h('div', { className: 'dswfe-form' },
2058
+ h('div', { className: 'dswfe-error' }, t('formUnparseable')))
2059
+ }
2060
+ const P = (path, dflt) => { const v = doc.getIn(path); return v === undefined || v === null ? dflt : v }
2061
+ const set = (path, value) => controller.setEditorText(fmSet(ed.text, path, value))
2062
+
2063
+ const phaseCount = fmSeqLen(doc, ['phases'])
2064
+ const allLinkIds = []
2065
+ for (let pi = 0; pi < phaseCount; pi++) {
2066
+ const lc = fmSeqLen(doc, ['phases', pi, 'links'])
2067
+ for (let li = 0; li < lc; li++) {
2068
+ const id = P(['phases', pi, 'links', li, 'id'], '')
2069
+ if (id) allLinkIds.push(String(id))
2070
+ }
2071
+ }
2072
+ // 流转下拉:关键字显示中文;目标只列 goto:<id> 一种写法——引擎里 parseFlow 会剥掉 goto: 前缀,
2073
+ // 裸 <id> 与 goto:<id> 完全等价,之前两种都列出来才让人看不懂。当前值若是裸 id,就地补一条
2074
+ // 本地化文案(不静默改用户数据)。
2075
+ const linkMeta = []
2076
+ for (let pi = 0; pi < phaseCount; pi++) {
2077
+ const lc = fmSeqLen(doc, ['phases', pi, 'links'])
2078
+ for (let li = 0; li < lc; li++) {
2079
+ const id = String(P(['phases', pi, 'links', li, 'id'], '') || '')
2080
+ if (!id) continue
2081
+ linkMeta.push({ id, no: linkMeta.length + 1, name: String(P(['phases', pi, 'links', li, 'name'], '') || '') })
2082
+ }
2083
+ }
2084
+ const jumpLabel = (id) => {
2085
+ const m = linkMeta.find((x) => x.id === id)
2086
+ return m ? t('flowJumpTo', { no: m.no, name: m.name || m.id }) : t('flowJumpTo', { no: linkMeta.length + 1, name: id })
2087
+ }
2088
+ const flowOptions = (fixed, cur) => {
2089
+ const head = fixed.map((v) => [v, v === 'next' ? t('flowNext') : v === 'end' ? t('flowEnd') : v === 'break' ? t('flowBreakStop') : v])
2090
+ const raw = String(cur == null ? '' : cur)
2091
+ // 同一条目标只出现一次:当前值本来就是裸 id 时,这条目标就用裸 id 作值(不静默改用户数据也不重复列)
2092
+ const jumps = linkMeta.map((m) => [raw === m.id ? m.id : 'goto:' + m.id, jumpLabel(m.id)])
2093
+ if (raw && !head.some((p) => p[0] === raw) && !jumps.some((p) => p[0] === raw)) jumps.push([raw, jumpLabel(raw.replace(/^goto:/, ''))])
2094
+ return head.concat(jumps)
2095
+ }
2096
+
2097
+ // ── 选中解析:按 id 重扫定位索引 ──
2098
+ const linkIdAt = (pi, li) => String(P(['phases', pi, 'links', li, 'id'], '') || '')
2099
+ const phaseIdAt = (pi) => String(P(['phases', pi, 'id'], '') || '')
2100
+ const R = (() => {
2101
+ if (sel.kind === 'global') return { kind: 'global' }
2102
+ for (let pi = 0; pi < phaseCount; pi++) {
2103
+ if (sel.kind === 'phase' && phaseIdAt(pi) === sel.id) return { kind: 'phase', pi }
2104
+ const lc = fmSeqLen(doc, ['phases', pi, 'links'])
2105
+ for (let li = 0; li < lc; li++) {
2106
+ if (sel.kind === 'link' && linkIdAt(pi, li) === sel.id) return { kind: 'link', pi, li }
2107
+ }
2108
+ }
2109
+ return { kind: 'global' }
2110
+ })()
2111
+
2112
+ const addPhase = () => {
2113
+ let n = phaseCount + 1
2114
+ let pid = 'phase-' + n
2115
+ while (allLinkIds.some((id) => id.startsWith(pid))) { n += 1; pid = 'phase-' + n }
2116
+ controller.setEditorText(fmAppend(ed.text, ['phases'], { id: pid, name: '', spec: '', links: [] }))
2117
+ setSel({ kind: 'phase', id: pid })
2118
+ }
2119
+ const addLink = (pi) => {
2120
+ let n = allLinkIds.length + 1
2121
+ let lid = 'link-' + n
2122
+ while (allLinkIds.includes(lid)) { n += 1; lid = 'link-' + n }
2123
+ controller.setEditorText(fmAppend(ed.text, ['phases', pi, 'links'], {
2124
+ id: lid, name: t('formNewLinkName'), prompt: '', executor: null, expert: null, skills: [],
2125
+ model: null, review_type: 'ai', gates: [], on_success: 'next', on_gate_fail: 'break',
2126
+ on_rating_fail: 'break', max_rework: null,
2127
+ }))
2128
+ setSel({ kind: 'link', id: lid })
2129
+ }
2130
+ const delPhase = (pi) => {
2131
+ const name = String(P(['phases', pi, 'name'], '') || phaseIdAt(pi) || '#' + (pi + 1))
2132
+ const n = fmSeqLen(doc, ['phases', pi, 'links'])
2133
+ if (!window.confirm(t('canvasDelPhase', { name, n }))) return
2134
+ controller.setEditorText(fmDeletePhase(ed.text, pi))
2135
+ setSel({ kind: 'global' })
2136
+ }
2137
+ const delLink = (pi, li) => {
2138
+ const name = String(P(['phases', pi, 'links', li, 'name'], '') || linkIdAt(pi, li))
2139
+ if (!window.confirm(t('canvasDelLink', { name }))) return
2140
+ controller.setEditorText(fmDeleteLink(ed.text, pi, li))
2141
+ setSel({ kind: 'global' })
2142
+ }
2143
+
2144
+ // ── 左:画布 ──
2145
+ const lane = (pi) => {
2146
+ const pid = phaseIdAt(pi)
2147
+ const pname = String(P(['phases', pi, 'name'], '') || pid)
2148
+ const lc = fmSeqLen(doc, ['phases', pi, 'links'])
2149
+ const phaseSel = R.kind === 'phase' && R.pi === pi
2150
+ const chipKids = []
2151
+ for (let li = 0; li < lc; li++) {
2152
+ const lid = linkIdAt(pi, li)
2153
+ const lname = String(P(['phases', pi, 'links', li, 'name'], '') || lid)
2154
+ const gateCount = fmSeqLen(doc, ['phases', pi, 'links', li, 'gates'])
2155
+ const isSel = R.kind === 'link' && R.pi === pi && R.li === li
2156
+ if (li > 0) chipKids.push(h('span', { className: 'dswfe-node-arrow', key: 'ar' + li }, '→'))
2157
+ chipKids.push(h('div', {
2158
+ key: 'nd' + li, className: 'dswfe-node', 'data-sel': isSel ? 'true' : undefined,
2159
+ onClick: (e) => { e.stopPropagation(); setSel({ kind: 'link', id: lid }) },
2160
+ },
2161
+ h('div', { className: 'dswfe-node-name' }, lname),
2162
+ h('div', { className: 'dswfe-node-meta' },
2163
+ h('span', { className: 'dswfe-node-id' }, lid),
2164
+ gateCount > 0 ? h('span', { className: 'dswfe-node-badge' }, '🔒' + gateCount) : null)),
2165
+ )
2166
+ }
2167
+ chipKids.push(h('button', {
2168
+ key: 'addlk', className: 'dswfe-node-add', title: t('formAddLink'),
2169
+ onClick: (e) => { e.stopPropagation(); addLink(pi) },
2170
+ }, '+'))
2171
+ return h('div', { className: 'dswfe-lane', key: 'ph' + pi, 'data-sel': phaseSel ? 'true' : undefined },
2172
+ h('div', { className: 'dswfe-lane-head', onClick: () => setSel({ kind: 'phase', id: pid }) },
2173
+ h('span', { className: 'dswfe-lane-no', style: { background: flowPhaseColor(pid) } }, '#' + (pi + 1)),
2174
+ h('span', { className: 'dswfe-lane-name' }, pname),
2175
+ h('span', { className: 'dswfe-lane-id' }, pid),
2176
+ h('span', { className: 'dswfe-lane-count' }, lc + t('links'))),
2177
+ h('div', { className: 'dswfe-lane-body' }, chipKids))
2178
+ }
2179
+
2180
+ const laneKids = []
2181
+ for (let pi = 0; pi < phaseCount; pi++) laneKids.push(lane(pi))
2182
+
2183
+ const canvas = h('div', {
2184
+ className: 'dswfe-canvas-left',
2185
+ onClick: (e) => { if (e.target === e.currentTarget) setSel({ kind: 'global' }) },
2186
+ },
2187
+ h('div', { className: 'dswfe-canvas-bar' },
2188
+ h('button', { className: 'dswfe-btn', 'data-primary': 'true', onClick: addPhase }, t('formAddPhase')),
2189
+ h('span', { className: 'dswfe-canvas-hint' }, h(Help, { text: t('helpCanvas') }))),
2190
+ phaseCount === 0 ? h('div', { className: 'dswfe-canvas-empty' }, t('canvasEmpty')) : null,
2191
+ h('div', null, laneKids))
2192
+
2193
+ // ── 右:属性面板 ──
2194
+ const sec = (title, extra) => h('div', { className: 'dswfe-fsec' },
2195
+ h('h4', null, title), extra || null)
2196
+
2197
+ const propsGlobal = [
2198
+ sec(t('propGlobal')),
2199
+ h('div', { className: 'dswfe-fsec', key: 'basic' },
2200
+ h('div', { className: 'dswfe-fgrid' },
2201
+ h(FormField, { label: t('formDisplayName') }, h(FormText, { value: P(['process', 'display_name'], ''), onChange: (v) => set(['process', 'display_name'], v) })),
2202
+ h(FormField, { label: t('formVersion') }, h(FormText, { value: P(['process', 'version'], ''), onChange: (v) => set(['process', 'version'], v) })),
2203
+ h(FormField, { label: t('formCategory') }, h(FormText, { value: P(['process', 'category'], ''), onChange: (v) => set(['process', 'category'], v) })),
2204
+ h(FormField, { label: t('formComplexity') }, h(FormSelect, { value: P(['process', 'complexity'], 'medium'), options: [['low', t('cxLow')], ['medium', t('cxMid')], ['high', t('cxHigh')]], onChange: (v) => set(['process', 'complexity'], v) }))),
2205
+ h('div', { style: { height: 8 } }),
2206
+ h(FormField, { label: t('formDescription') }, h(FormArea, { value: P(['process', 'description'], ''), rows: 5, onChange: (v) => set(['process', 'description'], v) }))),
2207
+ sec(t('formLimits')),
2208
+ h('div', { className: 'dswfe-fsec', key: 'limits' },
2209
+ h('div', { className: 'dswfe-fgrid' },
2210
+ h(FormField, { label: t('formMaxSteps') }, h(FormNum, { value: P(['limits', 'max_step_executions'], null), min: 1, onChange: (v) => set(['limits', 'max_step_executions'], v) })),
2211
+ h(FormField, { label: t('formMaxTokens') }, h(FormNum, { value: P(['limits', 'max_total_tokens'], null), min: 1, onChange: (v) => set(['limits', 'max_total_tokens'], v) }))))
2212
+ ]
2213
+
2214
+ const propsPhase = (pi) => [
2215
+ sec(t('propPhase') + ' · #' + (pi + 1),
2216
+ h('button', { className: 'dswfe-btn', 'data-danger': 'true', style: { marginLeft: 'auto' }, onClick: () => delPhase(pi) }, t('formDelPhase'))),
2217
+ h('div', { className: 'dswfe-fsec', key: 'meta' },
2218
+ h('div', { className: 'dswfe-fgrid' },
2219
+ h(FormField, { label: 'id' }, h(FormText, { value: phaseIdAt(pi), mono: true, onChange: (v) => { if (v.trim() !== '') { set(['phases', pi, 'id'], v.trim()); setSel({ kind: 'phase', id: v.trim() }) } } })),
2220
+ h(FormField, { label: t('formPhaseName') }, h(FormText, { value: P(['phases', pi, 'name'], ''), placeholder: t('formPhaseName'), onChange: (v) => set(['phases', pi, 'name'], v) }))),
2221
+ h(FormField, { label: t('formPhaseSpec'), style: { marginTop: 6 } }, h(FormArea, { value: P(['phases', pi, 'spec'], ''), rows: 4, onChange: (v) => set(['phases', pi, 'spec'], v) })))
2222
+ ]
2223
+
2224
+ const propsLink = (pi, li) => {
2225
+ const lp = ['phases', pi, 'links', li]
2226
+ const gatesPath = [...lp, 'gates']
2227
+ const gateCount = fmSeqLen(doc, gatesPath)
2228
+ // 执行器/专家:运行时都不读(只影响 prompt 措辞),面板已隐藏;YAML 里的旧字段仍能解析
2229
+ const metaFields = [
2230
+ ['id', 'id', true], [t('formName'), 'name', false],
2231
+ ]
2232
+ const gridKids = metaFields.map(([label, key, mono], i) => h(FormField, { label, key: 'm' + i },
2233
+ h(FormText, {
2234
+ value: key === 'id' ? linkIdAt(pi, li) : P([...lp, key], ''),
2235
+ mono,
2236
+ placeholder: key === 'id' ? 'req-01' : undefined,
2237
+ onChange: (v) => {
2238
+ if (key === 'id') {
2239
+ if (v.trim() !== '') { controller.setEditorText(fmSetLinkId(ed.text, pi, li, v.trim())); setSel({ kind: 'link', id: v.trim() }) }
2240
+ }
2241
+ else set([...lp, key], v === '' ? null : v)
2242
+ },
2243
+ })))
2244
+ gridKids.push(h(FormField, { label: t('formReviewType'), key: 'rt', help: t('helpReviewType') },
2245
+ h(FormSelect, { value: P([...lp, 'review_type'], 'ai'), options: [['ai', t('reviewAi')], ['human', t('reviewHuman')], ['none', t('reviewNone')]], onChange: (v) => set([...lp, 'review_type'], v) })))
2246
+ gridKids.push(h(FormField, { label: t('formMaxRework'), key: 'mr' },
2247
+ h(FormNum, { value: P([...lp, 'max_rework'], null), min: 0, onChange: (v) => set([...lp, 'max_rework'], v) })))
2248
+
2249
+ const gateKids = []
2250
+ gateKids.push(h('div', { style: { display: 'flex', alignItems: 'center', margin: '6px 0' }, key: 'ghd' },
2251
+ h('b', { style: { fontSize: 12, letterSpacing: '.02em' } }, t('formGates'), h(Help, { text: t('helpGates') })),
2252
+ h('button', { className: 'dswfe-btn', style: { marginLeft: 'auto' }, onClick: () => controller.setEditorText(fmAppend(ed.text, gatesPath, { name: '', type: 'ai_criteria_review', min_score: 80 })) }, t('formAddGate'))))
2253
+ for (let gi = 0; gi < gateCount; gi++) {
2254
+ const gp = [...gatesPath, gi]
2255
+ gateKids.push(h('div', { className: 'dswfe-fgrid', key: 'g' + gi, style: { alignItems: 'end' } },
2256
+ h(FormField, { label: t('formGateName') }, h(FormText, { value: P([...gp, 'name'], ''), onChange: (v) => set([...gp, 'name'], v) })),
2257
+ h(FormField, { label: t('formGateMin'), help: t('helpGateMin') }, h(FormNum, { value: P([...gp, 'min_score'], null), min: 0, onChange: (v) => set([...gp, 'min_score'], v) })),
2258
+ h('button', { className: 'dswfe-btn', 'data-danger': 'true', onClick: () => controller.setEditorText(fmDel(ed.text, gp)) }, '✕')))
2259
+ }
2260
+
2261
+ return [
2262
+ sec(t('propLink'),
2263
+ h('button', { className: 'dswfe-btn', 'data-danger': 'true', style: { marginLeft: 'auto' }, onClick: () => delLink(pi, li) }, t('formDelLink'))),
2264
+ h('div', { className: 'dswfe-fgrid', key: 'meta' }, gridKids),
2265
+ h(FormField, { label: t('formPrompt'), key: 'prompt', help: t('helpPrompt') },
2266
+ h(FormArea, { value: P([...lp, 'prompt'], ''), rows: 6, onChange: (v) => set([...lp, 'prompt'], v) })),
2267
+ h(FormField, { label: t('formAcceptance'), key: 'acc', help: t('helpAcceptance') },
2268
+ h(FormArea, { value: P([...lp, 'acceptance_criteria'], ''), rows: 2, onChange: (v) => set([...lp, 'acceptance_criteria'], v) })),
2269
+ h('div', { className: 'dswfe-fgrid', style: { marginTop: 6 }, key: 'flow' },
2270
+ h(FormField, { label: t('formOnSuccess') }, h(FormSelect, { value: P([...lp, 'on_success'], 'next'), options: flowOptions(['next', 'end'], P([...lp, 'on_success'], 'next')), onChange: (v) => set([...lp, 'on_success'], v) })),
2271
+ h(FormField, { label: t('formOnGateFail') }, h(FormSelect, { value: P([...lp, 'on_gate_fail'], 'break'), options: flowOptions(['break'], P([...lp, 'on_gate_fail'], 'break')), onChange: (v) => set([...lp, 'on_gate_fail'], v) }))),
2272
+ h('div', { className: 'dswfe-fgates', key: 'gates' }, gateKids),
2273
+ ]
2274
+ }
2275
+
2276
+ const propsKids = R.kind === 'phase' ? propsPhase(R.pi)
2277
+ : R.kind === 'link' ? propsLink(R.pi, R.li)
2278
+ : propsGlobal
2279
+
2280
+ return h('div', { className: 'dswfe-canvas' },
2281
+ canvas,
2282
+ h('div', { className: 'dswfe-props' }, propsKids))
2283
+ }
2284
+
2285
+
2286
+ function EditorPane({ state, controller, t }) {
2287
+ const ed = state.editor
2288
+ const taRef = useRef(null)
2289
+ const gutterRef = useRef(null)
2290
+ // 子模式:'form'(画布:左节点图+右属性面板)| 'yaml'(YAML 文本)——同一份 ed.text 双向实时同步
2291
+ const [subMode, setSubMode] = useState('form')
2292
+ const docOk = useMemo(() => !!fmDoc(ed ? ed.text : ''), [ed && ed.text])
2293
+ const mode = subMode === 'form' && !docOk ? 'yaml' : subMode
2294
+ if (!ed) return null
2295
+ const lines = ed.text.split('\n')
2296
+ const diag = ed.diagnostics || { errors: [], warnings: [] }
2297
+ const errCount = diag.errors.length
2298
+ const warnCount = diag.warnings.length
2299
+ const onScroll = () => { if (gutterRef.current && taRef.current) gutterRef.current.scrollTop = taRef.current.scrollTop }
2300
+ const jump = (line) => {
2301
+ const ta = taRef.current
2302
+ if (!ta) return
2303
+ const pos = lines.slice(0, line - 1).reduce((acc, l) => acc + l.length + 1, 0)
2304
+ ta.focus()
2305
+ ta.setSelectionRange(pos, pos)
2306
+ ta.scrollTop = Math.max(0, (line - 6) * 19)
2307
+ }
2308
+ const onKeyDown = (e) => {
2309
+ const ta = taRef.current
2310
+ if (!ta) return
2311
+ if (e.key === 'Tab') {
2312
+ e.preventDefault()
2313
+ const s = ta.selectionStart
2314
+ const next = ed.text.slice(0, s) + ' ' + ed.text.slice(ta.selectionEnd)
2315
+ controller.setEditorText(next)
2316
+ requestAnimationFrame(() => { ta.setSelectionRange(s + 2, s + 2) })
2317
+ } else if ((e.metaKey || e.ctrlKey) && (e.key === 's' || e.key === 'S')) {
2318
+ e.preventDefault()
2319
+ void controller.saveEditor(false)
2320
+ }
2321
+ }
2322
+ return h('div', { className: 'dswfe-detail dswfe-editor' },
2323
+ h('div', { className: 'dswfe-detail-head' },
2324
+ h('h3', { className: 'dswfe-detail-title' }, (ed.mode === 'create' ? t('editorCreate') : t('editorTitle')) + (ed.name ? ':' + ed.name : '')),
2325
+ h('div', { className: 'dswfe-tabs', style: { borderBottom: 'none', margin: '0 6px 0 0' } },
2326
+ h('button', { className: 'dswfe-tab', 'data-on': mode === 'form' ? 'true' : undefined, onClick: () => setSubMode('form'), disabled: !docOk, title: !docOk ? t('formUnparseable') : undefined }, t('formMode')),
2327
+ h('button', { className: 'dswfe-tab', 'data-on': mode === 'yaml' ? 'true' : undefined, onClick: () => setSubMode('yaml') }, t('yamlMode'))),
2328
+ h('div', { className: 'dswfe-actions' },
2329
+ ed.dirty ? h('span', { className: 'dswfe-badge', 'data-kind': 'warn' }, t('unsaved')) : null,
2330
+ h('button', { className: 'dswfe-btn', onClick: () => void controller.validateEditor(), disabled: ed.busy }, '✓ ' + t('validate')),
2331
+ h('button', { className: 'dswfe-btn', 'data-primary': 'true', onClick: () => void controller.saveEditor(false), disabled: ed.busy || errCount > 0 }, '💾 ' + t('save')),
2332
+ h('button', { className: 'dswfe-btn', onClick: () => controller.requestCloseEditor() }, t('cancel')))),
2333
+ ed.conflict ? h('div', { className: 'dswfe-conflict' },
2334
+ h('span', null, '⚠ ' + t('saveConflict') + ' ' + t('forcedHint')),
2335
+ h('button', { className: 'dswfe-btn', onClick: () => void controller.reloadEditor() }, t('reload')),
2336
+ h('button', { className: 'dswfe-btn', 'data-danger': 'true', onClick: () => void controller.saveEditor(true) }, t('overwrite'))) : null,
2337
+ ed.error ? h('div', { className: 'dswfe-error' }, ed.error) : null,
2338
+ mode === 'form'
2339
+ ? h(FormEditor, { state, controller, t, ed })
2340
+ : h('div', { className: 'dswfe-editor-wrap' },
2341
+ h('div', { className: 'dswfe-gutter', ref: gutterRef }, lines.map((_, i) => h('div', { key: i }, i + 1))),
2342
+ h('textarea', {
2343
+ className: 'dswfe-textarea', ref: taRef, value: ed.text, spellCheck: false,
2344
+ onChange: (e) => controller.setEditorText(e.target.value),
2345
+ onScroll, onKeyDown,
2346
+ })),
2347
+ h('div', { className: 'dswfe-status' },
2348
+ h('span', null, t('linesCount', { n: lines.length })),
2349
+ ed.dirty ? null : h('span', null, t('saved')),
2350
+ ed.validatedAt ? h('span', { style: { opacity: .6 } }, '✓ ' + new Date(ed.validatedAt).toLocaleTimeString()) : null,
2351
+ errCount > 0 ? h('span', { className: 'dswfe-badge', 'data-kind': 'err' }, errCount + t('errOne')) : null,
2352
+ warnCount > 0 ? h('span', { className: 'dswfe-badge', 'data-kind': 'warn' }, warnCount + t('warnOne')) : null,
2353
+ errCount === 0 && warnCount === 0 && !ed.dirty ? h('span', { style: { opacity: .7 } }, t('noIssues')) : null),
2354
+ (errCount > 0 || warnCount > 0) ? h(DiagList, { t, diagnostics: diag, onJump: jump }) : null)
2355
+ }
2356
+
2357
+ // ── 弹窗 ─────────────────────────────────────────────────────────────────
2358
+
2359
+ function Modal({ title, onClose, children, width }) {
2360
+ useEffect(() => {
2361
+ const onKey = (e) => { if (e.key === 'Escape') onClose() }
2362
+ document.addEventListener('keydown', onKey)
2363
+ return () => document.removeEventListener('keydown', onKey)
2364
+ }, [onClose])
2365
+ return h('div', { className: 'dswfe-modal-backdrop', onMouseDown: (e) => { if (e.target === e.currentTarget) onClose() } },
2366
+ h('div', { className: 'dswfe-modal', style: width ? { width: 'min(' + width + 'px, 94vw)' } : undefined, role: 'dialog', 'aria-modal': 'true' },
2367
+ h('div', { style: { display: 'flex', alignItems: 'center' } },
2368
+ h('h3', null, title),
2369
+ h('button', { className: 'dswfe-btn', style: { marginLeft: 'auto', width: 28, height: 28, padding: 0, borderRadius: 28 }, onClick: onClose }, '✕')),
2370
+ children))
2371
+ }
2372
+
2373
+ function FieldInput({ label, value, onChange, placeholder, type }) {
2374
+ return h('label', { className: 'dswfe-field' }, label,
2375
+ h('input', { value, type: type || 'text', placeholder, spellCheck: false, onChange: (e) => onChange(e.target.value) }))
2376
+ }
2377
+
2378
+ function CreateDialog({ state, controller, t }) {
2379
+ const [name, setName] = useState('')
2380
+ const [dir, setDir] = useState('')
2381
+ const [display, setDisplay] = useState('')
2382
+ const ok = /^[^\\/\0\r\n.][^\\/\0\r\n]{0,79}$/.test(name.trim())
2383
+ return h(Modal, { title: t('editorCreate'), onClose: () => controller.setState({ dialog: null }) },
2384
+ h(FieldInput, { label: t('createName'), value: name, onChange: setName, placeholder: 'my-process' }),
2385
+ h(FieldInput, { label: t('createDir'), value: dir, onChange: setDir, placeholder: 'software' }),
2386
+ h(FieldInput, { label: t('createDisplayName'), value: display, onChange: setDisplay }),
2387
+ h('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end' } },
2388
+ h('button', { className: 'dswfe-btn', onClick: () => controller.setState({ dialog: null }) }, t('cancel')),
2389
+ h('button', { className: 'dswfe-btn', 'data-primary': 'true', disabled: !ok || name.trim() === '', onClick: () => void controller.createBlank(name.trim(), dir.trim(), display.trim()) }, t('confirm'))),
2390
+ !ok && name.trim() !== '' ? h('div', { className: 'dswfe-error' }, t('nameRule')) : null)
2391
+ }
2392
+
2393
+ function CopyDialog({ state, controller, t }) {
2394
+ const dlg = state.dialog
2395
+ const from = dlg && dlg.fromId ? state.processes.find((p) => p.id === dlg.fromId) : undefined
2396
+ const [name, setName] = useState(from ? from.fileName + '-copy' : '')
2397
+ const [dir, setDir] = useState(from && from.source === 'user' ? (from.relPath.includes('/') ? from.relPath.split('/').slice(0, -1).join('/') : '') : '')
2398
+ return h(Modal, { title: t('editorCopy'), onClose: () => controller.setState({ dialog: null }) },
2399
+ h('div', { className: 'dswfe-kv' }, h('b', null, t('name') + ':'), from ? (from.display_name || from.name) + '(' + from.relPath + ')' : '—'),
2400
+ h(FieldInput, { label: t('copyName'), value: name, onChange: setName, placeholder: 'my-process' }),
2401
+ h(FieldInput, { label: t('createDir'), value: dir, onChange: setDir }),
2402
+ h('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end' } },
2403
+ h('button', { className: 'dswfe-btn', onClick: () => controller.setState({ dialog: null }) }, t('cancel')),
2404
+ h('button', { className: 'dswfe-btn', 'data-primary': 'true', disabled: !from || name.trim() === '', onClick: () => void controller.copyProcess(from.id, name.trim(), dir.trim()) }, t('copy'))))
2405
+ }
2406
+
2407
+ function RenameDialog({ state, controller, t }) {
2408
+ const dlg = state.dialog
2409
+ const [name, setName] = useState(dlg ? dlg.name : '')
2410
+ return h(Modal, { title: t('renameTitle'), onClose: () => controller.setState({ dialog: null }) },
2411
+ h(FieldInput, { label: t('newName'), value: name, onChange: setName }),
2412
+ h('div', { style: { fontSize: 12, opacity: .7 } }, t('renameHint')),
2413
+ h('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end' } },
2414
+ h('button', { className: 'dswfe-btn', onClick: () => controller.setState({ dialog: null }) }, t('cancel')),
2415
+ h('button', { className: 'dswfe-btn', 'data-primary': 'true', disabled: name.trim() === '', onClick: () => void controller.renameProcess(dlg.id, name.trim()) }, t('confirm'))))
2416
+ }
2417
+
2418
+ function ConfirmDialog({ state, controller, t }) {
2419
+ const dlg = state.dialog
2420
+ return h(Modal, { title: t('confirm'), onClose: () => controller.setState({ dialog: null }) },
2421
+ h('div', null, dlg.message),
2422
+ h('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end' } },
2423
+ h('button', { className: 'dswfe-btn', onClick: () => controller.setState({ dialog: null }) }, dlg.yes === 'discard' ? t('keepEditing') : t('cancel')),
2424
+ h('button', { className: 'dswfe-btn', 'data-danger': dlg.danger ? 'true' : undefined, onClick: () => dlg.onYes() }, dlg.yes === 'discard' ? t('discard') : t('confirm'))))
2425
+ }
2426
+
2427
+ function ImportDialog({ state, controller, t }) {
2428
+ const [over, setOver] = useState(false)
2429
+ const [dragOver, setDragOver] = useState(false)
2430
+ const [results, setResults] = useState(null)
2431
+ const [busy, setBusy] = useState(false)
2432
+ const doImport = async (fileList) => {
2433
+ const files = []
2434
+ for (const f of fileList) {
2435
+ if (f.size > 1024 * 1024) { files.push({ name: f.name, content: '' }); continue }
2436
+ // eslint-disable-next-line no-await-in-loop
2437
+ files.push({ name: f.name, content: await f.text() })
2438
+ }
2439
+ setBusy(true)
2440
+ try {
2441
+ const r = await controller.importFiles(files, over)
2442
+ setResults(r)
2443
+ controller.toast(t('toastImported', { n: r.filter((x) => x.status === 'created' || x.status === 'overwritten').length }))
2444
+ } catch (error) { controller.toast(String(error && error.message || error), 'err') } finally { setBusy(false) }
2445
+ }
2446
+ const statusLabel = { created: t('importCreated'), overwritten: t('importOverwritten'), exists: t('importExists'), invalid: t('importInvalid') }
2447
+ return h(Modal, { title: t('importTitle'), onClose: () => controller.setState({ dialog: null }), width: 620 },
2448
+ h('div', null, t('importHint')),
2449
+ h('label', { style: { display: 'flex', gap: 6, alignItems: 'center', fontSize: 12 } },
2450
+ h('input', { type: 'checkbox', checked: over, onChange: (e) => setOver(e.target.checked) }), t('importOverwrite')),
2451
+ h('div', {
2452
+ className: 'dswfe-drop', 'data-over': dragOver ? 'true' : undefined,
2453
+ onDragOver: (e) => { e.preventDefault(); setDragOver(true) },
2454
+ onDragLeave: () => setDragOver(false),
2455
+ onDrop: (e) => { e.preventDefault(); setDragOver(false); if (!busy) void doImport(Array.from(e.dataTransfer.files)) },
2456
+ },
2457
+ t('importHint'),
2458
+ h('div', { style: { marginTop: 10 } },
2459
+ h('input', { type: 'file', accept: '.yaml,.yml', multiple: true, disabled: busy, onChange: (e) => { const list = Array.from(e.target.files || []); e.target.value = ''; if (!busy) void doImport(list) } }))),
2460
+ busy ? h('div', null, t('loading')) : null,
2461
+ results ? h('div', { className: 'dswfe-diag' },
2462
+ h('div', { style: { fontWeight: 600 } }, t('importResults')),
2463
+ results.map((r, i) => h('div', { key: i, style: { display: 'flex', gap: 8, fontSize: 12 } },
2464
+ h('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, r.name),
2465
+ h('span', { style: { color: r.status === 'created' || r.status === 'overwritten' ? 'var(--dsw-alias-state-success, #2e9e5b)' : r.status === 'invalid' ? 'var(--dsw-alias-state-error, #c75050)' : 'inherit' } },
2466
+ statusLabel[r.status] || r.status),
2467
+ r.errors && r.errors.length ? h('span', { style: { opacity: .7 } }, r.errors[0].message) : null))) : null)
2468
+ }
2469
+
2470
+ function SettingsDialog({ state, controller, t }) {
2471
+ const [form, setForm] = useState(state.settings)
2472
+ const [busy, setBusy] = useState(false)
2473
+ useEffect(() => { if (!state.settings) void controller.loadSettings() }, [])
2474
+ useEffect(() => { if (state.settings && !form) setForm(state.settings) }, [state.settings])
2475
+ if (!form) return h(Modal, { title: t('settingsTitle'), onClose: () => controller.setState({ dialog: null }) }, t('loading'))
2476
+ const set = (k) => (v) => setForm({ ...form, [k]: v })
2477
+ return h(Modal, { title: t('settingsTitle'), onClose: () => controller.setState({ dialog: null }) },
2478
+ h(FieldInput, { label: t('settingsUserRoot'), value: form.userRoot, onChange: set('userRoot') }),
2479
+ h(FieldInput, { label: t('settingsBundledRoot'), value: form.bundledRoot, onChange: set('bundledRoot') }),
2480
+ h('label', { className: 'dswfe-field' }, t('settingsMaxDepth'),
2481
+ h('select', { value: String(form.maxDepth), onChange: (e) => set('maxDepth')(Number(e.target.value)) },
2482
+ [1, 2, 3, 4, 5, 6].map((n) => h('option', { key: n, value: n }, n)))),
2483
+ h('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end' } },
2484
+ h('button', { className: 'dswfe-btn', onClick: () => controller.setState({ dialog: null }) }, t('cancel')),
2485
+ h('button', { className: 'dswfe-btn', 'data-primary': 'true', disabled: busy, onClick: async () => {
2486
+ setBusy(true)
2487
+ try { await controller.saveSettings(form); controller.toast(t('settingsSaved')); controller.setState({ dialog: null }) }
2488
+ catch (error) { controller.toast(String(error && error.message || error), 'err') } finally { setBusy(false) }
2489
+ } }, t('save'))))
2490
+ }
2491
+
2492
+ // ── ⚡ AI 生成(kit ActionShareDialog + completedView 预览确认) ────────────
2493
+
2494
+ const AI_PROMPT = `请为下面的需求设计一个工作流(Process:多阶段 phase、多环节 link 的 agent 工作流模板),输出严格的 YAML。
2495
+
2496
+ 需求:{{requirement}}
2497
+ 复杂度:{{complexity}}
2498
+ {{reference}}
2499
+
2500
+ 硬性要求:
2501
+ 1. 只输出一个 \`\`\`yaml 代码块,不要任何其他解释文字。
2502
+ 2. 顶层结构:process(name / guid:生成一个 uuid v4 / display_name / description / category: software / complexity / version: 1.0.0)+ limits(max_step_executions / max_total_tokens,可为 null)+ abnormal_handler(可为 null)+ phases 列表。
2503
+ 3. 每个 phase:id、name、spec、acceptance_criteria、links 列表。每个 link:id(全工作流唯一,建议简短助记如 req-01)、name、prompt(明确可执行的指令,含产物落点)、executor、expert(专家库里的名字,不确定就 null)、skills(列表)、expected_artifacts([{name, type: file, path}])、gates([{name, type: ai_criteria_review, min_score}],可选)、on_success(next / end / <环节id>)、on_gate_fail(break / <环节id> / goto:<环节id>)、on_rating_fail: break、max_rework(0-3)。
2504
+ 4. on_success / on_gate_fail 引用的环节 id 必须真实存在;最后一步用 on_success: end。
2505
+ 5. 阶段数量与环节粒度贴合复杂度:轻需求 1-2 阶段 3-6 环节;复杂需求 3+ 阶段。`
2506
+
2507
+ function AiPreview({ controller, t, output, close }) {
2508
+ const parsedBlock = useMemo(() => {
2509
+ const blocks = [...String(output || '').matchAll(/```(?:yaml|yml)?\s*\n([\s\S]*?)```/g)]
2510
+ if (blocks.length > 0) return blocks[blocks.length - 1][1].trim()
2511
+ const s = String(output || '').trim()
2512
+ return s.startsWith('process:') || s.startsWith('#') ? s : ''
2513
+ }, [output])
2514
+ const [yaml, setYaml] = useState(parsedBlock)
2515
+ const [diag, setDiag] = useState(null)
2516
+ const [name, setName] = useState('')
2517
+ const [busy, setBusy] = useState(false)
2518
+ useEffect(() => {
2519
+ if (!yaml) { setDiag(null); return }
2520
+ let live = true
2521
+ api('/validate', { method: 'POST', body: { yaml } }).then((d) => { if (live) setDiag({ errors: d.errors, warnings: d.warnings, meta: d.meta }) }).catch(() => {})
2522
+ return () => { live = false }
2523
+ }, [yaml])
2524
+ useEffect(() => {
2525
+ if (diag && diag.meta && diag.meta.name && !name) setName(diag.meta.name)
2526
+ }, [diag])
2527
+ if (!parsedBlock) {
2528
+ return h('div', null, h('div', { className: 'dswfe-error' }, t('aiParseFail')), h('pre', { className: 'dswfe-pre', style: { maxHeight: 200 } }, String(output || '')))
2529
+ }
2530
+ const errCount = diag ? diag.errors.length : 0
2531
+ return h('div', { style: { display: 'flex', flexDirection: 'column', gap: 10, minWidth: 'min(680px, 80vw)' } },
2532
+ h('div', { style: { fontWeight: 600 } }, t('aiPreviewTitle')),
2533
+ h('textarea', { value: yaml, onChange: (e) => setYaml(e.target.value), spellCheck: false, style: { minHeight: 260, fontFamily: 'ui-monospace, Menlo, monospace', fontSize: 12, lineHeight: 1.5, border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', borderRadius: 8, padding: 8, background: 'var(--dsw-alias-bg-layer-2,transparent)', color: 'inherit', whiteSpace: 'pre' } }),
2534
+ diag ? h(DiagList, { t, diagnostics: diag, onJump: () => {} }) : h('div', { style: { fontSize: 12, opacity: .7 } }, t('validating')),
2535
+ h('div', { style: { display: 'flex', gap: 8, alignItems: 'center' } },
2536
+ h('input', { value: name, onChange: (e) => setName(e.target.value), placeholder: t('aiSaveName'), spellCheck: false, style: { flex: 1, border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', background: 'var(--dsw-alias-bg-layer-2,transparent)', color: 'inherit', borderRadius: 8, padding: '6px 10px', font: 'inherit' } }),
2537
+ h('button', {
2538
+ className: 'dswfe-btn', 'data-primary': 'true', disabled: busy || errCount > 0 || name.trim() === '',
2539
+ onClick: async () => {
2540
+ setBusy(true)
2541
+ try {
2542
+ const result = await api('/save', { method: 'POST', body: { mode: 'create', name: name.trim(), yaml } })
2543
+ await controller.refresh()
2544
+ controller.select(result.id)
2545
+ controller.toast(t('toastAiSaved'))
2546
+ close()
2547
+ } catch (error) { controller.toast(String(error && error.message || error), 'err') } finally { setBusy(false) }
2548
+ },
2549
+ }, t('aiSave'))))
2550
+ }
2551
+
2552
+ function AiDialog({ state, controller, t }) {
2553
+ const Dialog = useMemo(() => { const kit = getKit(); return kit ? kit.makeActionShareDialog(ReactGlobal || __React, {}) : null }, [])
2554
+ if (!Dialog) return h(Modal, { title: t('aiTitle'), onClose: () => controller.setState({ dialog: null }) }, h('div', { className: 'dswfe-error' }, t('kitMissing')))
2555
+ return h(Dialog, {
2556
+ title: '⚡ ' + t('aiTitle'),
2557
+ hint: t('aiHint'),
2558
+ params: [
2559
+ { key: 'requirement', label: t('aiRequirement'), multiline: true, placeholder: t('aiRequirementPh') },
2560
+ { key: 'complexity', label: t('aiComplexity'), placeholder: 'medium' },
2561
+ { key: 'reference', label: t('aiReference'), placeholder: '' },
2562
+ ],
2563
+ initialPrompt: AI_PROMPT,
2564
+ run: (prompt) => controller.aiRun(prompt).then((jobId) => ({ jobId })),
2565
+ poll: (jobId) => controller.aiPoll(jobId),
2566
+ labels: { run: t('aiBtn'), running: t('aiRunning'), done: t('aiDone'), failed: t('aiFailed'), copy: t('copyPrompt'), copied: t('copied'), outputLabel: t('aiOutput'), openSession: t('openSession') },
2567
+ onOpenSession: (sessionId) => controller.openSession(sessionId),
2568
+ completedView: ({ job, output, close }) => h(AiPreview, { controller, t, output, close }),
2569
+ onClose: () => controller.setState({ dialog: null }),
2570
+ })
2571
+ }
2572
+
2573
+ // ── 面板根 ───────────────────────────────────────────────────────────────
2574
+
2575
+ function ProcessPanel({ controller, t, slotProps }) {
2576
+ const state = useControllerState(controller)
2577
+ // 当前会话变化(点侧栏会话行/新会话)→ 关面板
2578
+ const useSess = slotProps && slotProps.useSessions
2579
+ const current = useSess ? useSess((s) => s.current) : undefined
2580
+ const prevCurrent = useRef(current)
2581
+ useEffect(() => {
2582
+ if (prevCurrent.current !== current && prevCurrent.current !== undefined && controller.getSnapshot().panelOpen) controller.closePanel()
2583
+ prevCurrent.current = current
2584
+ }, [current])
2585
+ // Esc 关面板(弹窗自己处理 Esc,开着弹窗时不抢)
2586
+ useEffect(() => {
2587
+ if (!state.panelOpen) return
2588
+ const onKey = (e) => {
2589
+ if (e.key !== 'Escape') return
2590
+ const s = controller.getSnapshot()
2591
+ if (s.dialog) return
2592
+ // 编辑器里按 Esc 先离开文本框(再按一次才关面板);其他地方直接关
2593
+ if (e.target && e.target.tagName === 'TEXTAREA') { e.target.blur(); return }
2594
+ controller.closePanel()
2595
+ }
2596
+ document.addEventListener('keydown', onKey)
2597
+ return () => document.removeEventListener('keydown', onKey)
2598
+ }, [state.panelOpen])
2599
+ // 中栏接管开合:panelOpen ↔ html[data-dswfe-active](useLayoutEffect:开/关都在绘制前生效)
2600
+ useLayoutEffect(() => {
2601
+ try {
2602
+ if (state.panelOpen) {
2603
+ for (const attr of PRC_OTHER_ACTIVE_ATTRS) document.documentElement.removeAttribute(attr)
2604
+ document.documentElement.setAttribute(PRC_ACTIVE_ATTR, '')
2605
+ document.dispatchEvent(new CustomEvent(ACTIVATE_EVENT, { detail: PANEL_NAME }))
2606
+ } else {
2607
+ document.documentElement.removeAttribute(PRC_ACTIVE_ATTR)
2608
+ }
2609
+ } catch {}
2610
+ }, [state.panelOpen])
2611
+ // 点侧栏会话行自动关面板(自家入口子树豁免)
2612
+ useEffect(() => {
2613
+ const onClickRow = (e) => {
2614
+ if (!controller.getSnapshot().panelOpen) return
2615
+ const target = e.target
2616
+ if (!(target instanceof Element)) return
2617
+ if (target.closest('[' + ENTRY_ATTR + ']')) return
2618
+ if (target.closest(PRC_SIDEBAR_ROW_SELECTOR) || target.closest(PRC_SIDEBAR_COLUMN_SELECTOR)) controller.closePanel()
2619
+ }
2620
+ document.addEventListener('click', onClickRow, true)
2621
+ return () => document.removeEventListener('click', onClickRow, true)
2622
+ }, [controller])
2623
+ if (!state.panelOpen) return null
2624
+ const detail = state.editor ? h(EditorPane, { state, controller, t }) : h(DetailPane, { state, controller, t })
2625
+ return h('div', { className: 'dswfe-panel', 'data-dswfe-panel': '' },
2626
+ h(Toolbar, { state, controller, t }),
2627
+ state.error ? h('div', { className: 'dswfe-error' }, state.error) : null,
2628
+ state.lastError ? h('div', { className: 'dswfe-error' }, 'store: ' + state.lastError) : null,
2629
+ h('div', { className: 'dswfe-body' },
2630
+ state.view === 'exec' ? h(ExecView, { state, controller, t }) : h('div', { style: { display: 'contents' } }, h(ListPane, { state, controller, t }), detail)),
2631
+ state.dialog && state.dialog.type === 'create' ? h(CreateDialog, { state, controller, t }) : null,
2632
+ state.dialog && state.dialog.type === 'copy' ? h(CopyDialog, { state, controller, t }) : null,
2633
+ state.dialog && state.dialog.type === 'rename' ? h(RenameDialog, { state, controller, t }) : null,
2634
+ state.dialog && state.dialog.type === 'confirm' ? h(ConfirmDialog, { state, controller, t }) : null,
2635
+ state.dialog && state.dialog.type === 'import' ? h(ImportDialog, { state, controller, t }) : null,
2636
+ state.dialog && state.dialog.type === 'settings' ? h(SettingsDialog, { state, controller, t }) : null,
2637
+ state.dialog && state.dialog.type === 'ai' ? h(AiDialog, { state, controller, t }) : null,
2638
+ state.dialog && state.dialog.type === 'newrun' ? h(NewRunDialog, { state, controller, t }) : null,
2639
+ state.dialog && state.dialog.type === 'fileview' ? h(FileViewDialog, { state, controller, t }) : null,
2640
+ state.dialog && state.dialog.type === 'linkfiles' ? h(LinkFilesDialog, { state, controller, t }) : null,
2641
+ state.toast ? h('div', { className: 'dswfe-toast', 'data-kind': state.toast.kind }, state.toast.text) : null)
2642
+ }
2643
+
2644
+ // ── 执行视图(v0.2)─────────────────────────────────────────────────────
2645
+
2646
+ const LINK_STATE_KEY = { running: 'linkRunning', done: 'linkDone', gate_failed: 'linkGateFailed', skipped: 'linkSkipped', failed: 'linkFailed', abandoned: 'linkAbandoned', awaiting_review: 'linkAwaitingReview', approved: 'linkApproved', rejected: 'linkRejected' }
2647
+
2648
+ const STATUS_KEY = { queued: 'statusQueued', running: 'statusRunning', paused: 'statusPaused', awaiting: 'statusAwaiting', awaiting_review: 'statusAwaitingReview', done: 'statusDone', stopped: 'statusStopped', failed: 'statusFailed' }
2649
+
2650
+ function StatusPill({ t, status }) {
2651
+ const key = STATUS_KEY[status] || 'status' + String(status || '')[0].toUpperCase() + String(status || '').slice(1)
2652
+ return h('span', { className: 'dswfe-pill', 'data-status': status }, t(key))
2653
+ }
2654
+
2655
+ /** 每个环节的最新一次执行记录。 */
2656
+ function latestAttempts(run) {
2657
+ const map = new Map()
2658
+ for (const t of run.trail || []) {
2659
+ const prev = map.get(t.linkId)
2660
+ if (!prev || t.startedAt >= prev.startedAt) {
2661
+ // 最新记录缺 sessionId(如 skip 记录)时继承上一次的,跳转会话不丢
2662
+ map.set(t.linkId, !t.sessionId && prev && prev.sessionId ? { ...t, sessionId: prev.sessionId } : t)
2663
+ }
2664
+ }
2665
+ return map
2666
+ }
2667
+
2668
+ function runProgress(run) {
2669
+ const latest = latestAttempts(run)
2670
+ const total = new Set([...indexLinksOf(run).keys()]).size
2671
+ let done = 0
2672
+ for (const [linkId] of indexLinksOf(run)) {
2673
+ const st = latest.get(linkId) && latest.get(linkId).status
2674
+ if (st === 'done' || st === 'skipped') done++
2675
+ }
2676
+ return { done, total }
2677
+ }
2678
+ function indexLinksOf(run) {
2679
+ const phases = run.snapshot && Array.isArray(run.snapshot.phases) ? run.snapshot.phases : []
2680
+ const map = new Map()
2681
+ for (const ph of phases) for (const ln of (Array.isArray(ph.links) ? ph.links : [])) if (ln.id) map.set(ln.id, { phase: ph, link: ln })
2682
+ return map
2683
+ }
2684
+
2685
+ // ── token 用量展示(v0.5.2)──────────────────────────────────────────────
2686
+
2687
+ /** 环节卡用量 = 环节执行 + 门禁评审两份合并(都缺返回 null)。 */
2688
+ function linkUsage(attempt) {
2689
+ if (!attempt || (!attempt.usage && !attempt.gateUsage)) return null
2690
+ const sum = (a, b) => (a || 0) + (b || 0)
2691
+ const u = attempt.usage, g = attempt.gateUsage
2692
+ return {
2693
+ inputTokens: sum(u && u.inputTokens, g && g.inputTokens),
2694
+ outputTokens: sum(u && u.outputTokens, g && g.outputTokens),
2695
+ totalTokens: sum(u && u.totalTokens, g && g.totalTokens),
2696
+ calls: sum(u && u.calls, g && g.calls),
2697
+ }
2698
+ }
2699
+
2700
+ /** 优先用宿主上报的 totalTokens,缺失时退回 input+output。 */
2701
+ function usageTotalOf(u) {
2702
+ if (!u) return 0
2703
+ return u.totalTokens > 0 ? u.totalTokens : (u.inputTokens || 0) + (u.outputTokens || 0)
2704
+ }
2705
+
2706
+ /** 1234 → 1.2k;670 → 670(去尾零)。 */
2707
+ function fmtTokens(n) {
2708
+ if (!Number.isFinite(n) || n <= 0) return '0'
2709
+ if (n >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, '') + 'M'
2710
+ if (n >= 1e3) return (n / 1e3).toFixed(1).replace(/\.0$/, '') + 'k'
2711
+ return String(Math.round(n))
2712
+ }
2713
+
2714
+ /** react-dom:只为把问号气泡挂到 body(祖先带 opacity,就地渲染必然是半透明浅灰底)。 */
2715
+ let __ReactDOM = null
2716
+ try { __ReactDOM = require('react-dom') } catch {}
2717
+ function portalHost() { return __ReactDOM && typeof __ReactDOM.createPortal === 'function' ? __ReactDOM : null }
2718
+
2719
+ /**
2720
+ * 字段说明问号:自绘气泡(原生 title 在这套壳里常被重渲染吞掉),
2721
+ * 提示用 position:fixed 的浮层按图标坐标定位:属性栏/画布栏都是滚动容器,::after 会被裁切或挤压。
2722
+ */
2723
+ function Help({ text }) {
2724
+ const ref = useRef(null)
2725
+ const [pos, setPos] = useState(null)
2726
+ if (!text) return null
2727
+ const W = 260
2728
+ const show = () => {
2729
+ const el = ref.current
2730
+ if (!el) return
2731
+ const r = el.getBoundingClientRect()
2732
+ const vw = window.innerWidth || 1280
2733
+ const vh = window.innerHeight || 800
2734
+ const estH = Math.max(1, Math.ceil([...String(text)].reduce((n, ch) => n + (/[\u2E80-\u9FFF\uF900-\uFAFF\uFF00-\uFFEF\u3000-\u303F]/.test(ch) ? 11.5 : 6.4), 0) / (W - 20))) * 17 + 16
2735
+ // 弹窗里的气泡必须留在弹窗内:弹窗遮罩的 z-index 是 2147482900,气泡落在外层会被压暗、被弹窗切掉上半截。
2736
+ const dlgEl = el.closest('[role="dialog"], dialog, [class*="modal"]')
2737
+ const dlg = dlgEl ? dlgEl.getBoundingClientRect() : null
2738
+ const minL = dlg ? dlg.left + 10 : 8
2739
+ const maxR = dlg ? dlg.right - 10 : vw - 8
2740
+ const minT = dlg ? dlg.top + 10 : 8
2741
+ const maxB = dlg ? dlg.bottom - 10 : vh - 8
2742
+ let left
2743
+ let top
2744
+ if (dlg && r.right + 14 + W <= maxR) {
2745
+ // 右侧有地方就放右侧,不去盖下方的按钮和诊断区
2746
+ left = r.right + 14
2747
+ top = Math.max(minT, Math.min(r.top + r.height / 2 - estH / 2, maxB - estH))
2748
+ } else {
2749
+ left = Math.max(minL, Math.min(r.left - 6, maxR - W))
2750
+ top = r.bottom + 8
2751
+ if (top + estH > maxB) top = Math.max(minT, r.top - estH - 8)
2752
+ }
2753
+ setPos({ left, top })
2754
+ }
2755
+ const hide = () => setPos(null)
2756
+ const tip = pos ? h('span', { className: 'dswfe-tip', style: { left: pos.left + 'px', top: pos.top + 'px', width: W + 'px' } }, text) : null
2757
+ const host = tip ? portalHost() : null
2758
+ return h('span', {
2759
+ className: 'dswfe-help', ref, tabIndex: 0, role: 'note', 'aria-label': text,
2760
+ onMouseEnter: show, onMouseLeave: hide, onFocus: show, onBlur: hide,
2761
+ }, '?', tip ? (host ? host.createPortal(tip, document.body) : tip) : null)
2762
+ }
2763
+
2764
+ /** 毫秒 → 「12 分 30 秒」;缺值/未知返回 unknown(默认 —)。 */
2765
+ function fmtDuration(ms, unknown) {
2766
+ if (!Number.isFinite(ms) || ms < 0) return unknown || '—'
2767
+ const total = Math.round(ms / 1000)
2768
+ const hrs = Math.floor(total / 3600)
2769
+ const min = Math.floor((total % 3600) / 60)
2770
+ const sec = total % 60
2771
+ if (hrs > 0) return hrs + ' 小时 ' + min + ' 分'
2772
+ if (min > 0) return min + ' 分 ' + sec + ' 秒'
2773
+ return sec + ' 秒'
2774
+ }
2775
+
2776
+ /** 环节耗时:结束时间 - 开始时间(老记录没有 finishedAt 时给 null)。 */
2777
+ function attemptDuration(attempt) {
2778
+ if (!attempt || !attempt.startedAt) return null
2779
+ const end = attempt.finishedAt || (attempt.status === 'running' ? Date.now() : null)
2780
+ return end ? Math.max(0, end - attempt.startedAt) : null
2781
+ }
2782
+
2783
+ /** 执行方式文案:AI 评审 / 人工评审 / 无需评审(结构页与概览共用)。 */
2784
+ function execLabel(t, node) {
2785
+ const rt = (node && node.reviewType) || 'ai'
2786
+ if (rt === 'human') return t('execHuman')
2787
+ if (rt === 'none') return t('execNone')
2788
+ return t('execAI')
2789
+ }
2790
+
2791
+ function UsageBadge({ t, usage }) {
2792
+ if (!usage || usage.calls <= 0) return null
2793
+ return h('span', {
2794
+ className: 'dswfe-badge',
2795
+ title: t('usageTitle', { input: fmtTokens(usage.inputTokens), output: fmtTokens(usage.outputTokens), calls: usage.calls }),
2796
+ }, '⚡ ' + fmtTokens(usageTotalOf(usage)))
2797
+ }
2798
+
2799
+ function RunList({ state, controller, t }) {
2800
+ const runs = state.runs.list
2801
+ const running = (r) => ['queued', 'running', 'paused', 'awaiting'].includes(r.status)
2802
+ const elapsed = (r) => fmtDuration((r.finishedAt || (running(r) ? Date.now() : r.updatedAt)) - r.createdAt, t('durationUnknown'))
2803
+ const tokens = (r) => (r.usage && r.usage.calls > 0 ? fmtTokens(usageTotalOf(r.usage)) : '—')
2804
+ return h('div', { className: 'dswfe-runlist' },
2805
+ runs.length === 0
2806
+ ? h('div', { style: { padding: '16px 8px', color: 'var(--dsw-text-secondary, gray)', fontSize: 12 } }, t('noRuns'), h('div', { style: { marginTop: 4, opacity: .8 } }, t('noRunsHint')))
2807
+ : runs.map((r) => h('div', {
2808
+ key: r.id, className: 'dswfe-runrow', role: 'button', tabIndex: 0,
2809
+ 'data-selected': state.runId === r.id ? 'true' : undefined,
2810
+ onClick: () => controller.selectRun(r.id),
2811
+ onKeyDown: (e) => { if (e.key === 'Enter') { e.preventDefault(); controller.selectRun(r.id) } },
2812
+ },
2813
+ h('div', { className: 'dswfe-runrow-top' },
2814
+ h('span', { className: 'dswfe-pill', 'data-status': r.status }, t('status' + r.status[0].toUpperCase() + r.status.slice(1))),
2815
+ h('span', { className: 'dswfe-runrow-name', title: r.displayName || r.processName }, r.displayName || r.processName || r.runName),
2816
+ h('button', {
2817
+ className: 'dswfe-mini dswfe-rundel', title: t('deleteRun'), 'aria-label': t('deleteRun'),
2818
+ onClick: (e) => {
2819
+ e.stopPropagation()
2820
+ // 壳层里 window.confirm 常被吞掉 → 用面板自己的确认框
2821
+ controller.setState({ dialog: { type: 'confirm', message: t('deleteRunConfirm'), danger: true, onYes: () => { controller.setState({ dialog: null }); void controller.deleteRun(r.id) } } })
2822
+ },
2823
+ }, '🗑')),
2824
+ r.request
2825
+ ? h('div', { className: 'dswfe-runrow-req', title: r.request }, '📝 ' + t('requestLabel') + ': ' + r.request)
2826
+ : null,
2827
+ h('div', { className: 'dswfe-runrow-meta' },
2828
+ h('span', null, t('progress', { done: r.doneLinks, total: r.totalLinks })),
2829
+ h('span', null, '⚡ ' + tokens(r)),
2830
+ h('span', null, t('durationTotal') + ':' + elapsed(r))))))
2831
+ }
2832
+
2833
+ function RunLinkCard({ t, run, phase, link, attempt, controller, index }) {
2834
+ const st = attempt ? attempt.status : 'pending'
2835
+ const isCurrent = run.current && run.current.linkId === link.id && ['running', 'queued', 'awaiting'].includes(run.status)
2836
+ const rework = (run.rework && run.rework[link.id]) || 0
2837
+ const active = ['queued', 'running', 'awaiting', 'paused'].includes(run.status)
2838
+ const dur = attemptDuration(attempt)
2839
+ return h('div', { className: 'dswfe-linkcard', 'data-state': st },
2840
+ h('div', { className: 'dswfe-linktop' },
2841
+ h('span', { className: 'dswfe-badge' }, t('linkNo', { n: index })),
2842
+ h('span', { style: { fontWeight: 600 } }, link.name || ''),
2843
+ isCurrent ? h('span', { className: 'dswfe-badge', 'data-kind': 'warn' }, t('currentStep')) : null,
2844
+ h('span', { className: 'grow' }),
2845
+ attempt && attempt.attempt > 1 ? h('span', { style: { fontSize: 11, opacity: .7 } }, t('attemptN', { n: attempt.attempt })) : null,
2846
+ rework > 0 ? h('span', { style: { fontSize: 11, color: '#b8860b' } }, t('reworkN', { n: rework })) : null,
2847
+ attempt && attempt.gate && attempt.gate.score !== null && attempt.gate.score !== undefined
2848
+ ? h('span', { className: 'dswfe-badge', 'data-kind': attempt.gate.score >= (attempt.gate.minScore || 0) ? 'ok' : 'err', title: attempt.gate.reason },
2849
+ t('gateLabel') + ' ' + attempt.gate.score + ' / ' + (attempt.gate.minScore || 0)) : null,
2850
+ attempt && attempt.gate && attempt.gate.reason
2851
+ ? h('span', { style: { fontSize: 11, opacity: .65, maxWidth: 420, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } },
2852
+ '↳ ' + attempt.gate.reason) : null,
2853
+ h(UsageBadge, { t, usage: linkUsage(attempt) }),
2854
+ h('span', { style: { fontSize: 11, opacity: .75 } }, t(LINK_STATE_KEY[st] || 'linkPending')),
2855
+ h('span', { className: 'dswfe-linkdur', title: t('durationTotal') }, fmtDuration(dur, t('durationUnknown')))),
2856
+ h('div', { style: { display: 'flex', gap: 6, flexWrap: 'wrap' } },
2857
+ attempt && attempt.sessionId ? h('button', { className: 'dswfe-mini', onClick: () => controller.openSession(attempt.sessionId) }, t('openSession')) : null,
2858
+ h('button', { className: 'dswfe-mini', onClick: () => controller.setState({ dialog: { type: 'linkfiles', runId: run.id, linkId: link.id, name: link.name || link.id } }) }, t('viewFiles')),
2859
+ !active && attempt ? h('button', { className: 'dswfe-mini', onClick: () => void controller.runAction('retry-link', { id: run.id, linkId: link.id }) }, t('retryLink')) : null,
2860
+ !active && st !== 'pending' ? h('button', { className: 'dswfe-mini', onClick: () => void controller.runAction('skip-link', { id: run.id, linkId: link.id }) }, t('skipLink')) : null))
2861
+ }
2862
+
2863
+ /** 字节数可读化(产物大小)。 */
2864
+ function fmtBytes(n) {
2865
+ if (!Number.isFinite(n) || n <= 0) return '0 B'
2866
+ if (n >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, '') + ' MB'
2867
+ if (n >= 1e3) return (n / 1e3).toFixed(1).replace(/\.0$/, '') + ' KB'
2868
+ return Math.round(n) + ' B'
2869
+ }
2870
+
2871
+ /** 文件修改时间 → HH:MM(产物列表用,区分是哪一轮写的)。 */
2872
+ function fmtClock(ms) {
2873
+ if (!Number.isFinite(ms) || ms <= 0) return ''
2874
+ const d = new Date(ms)
2875
+ const p = (n) => String(n).padStart(2, '0')
2876
+ return p(d.getHours()) + ':' + p(d.getMinutes())
2877
+ }
2878
+
2879
+ /** diffstat:+12 −3(git 风格带色)。 */
2880
+ function DiffStat({ additions, deletions }) {
2881
+ if (!additions && !deletions) return null
2882
+ return h('span', { style: { fontFamily: 'var(--dsw-font-family-mono, monospace)', fontSize: 11, whiteSpace: 'nowrap' } },
2883
+ additions > 0 ? h('span', { style: { color: '#4a9a4a' } }, '+' + additions) : null,
2884
+ additions > 0 && deletions > 0 ? ' ' : null,
2885
+ deletions > 0 ? h('span', { style: { color: '#c75050' } }, '−' + deletions) : null)
2886
+ }
2887
+
2888
+ /** diff 文本 → 按行着色(+/−/@@)。 */
2889
+ function DiffView({ text }) {
2890
+ if (!text) return h('div', { style: { fontSize: 12, opacity: .6, padding: 8 } }, '—')
2891
+ return h('pre', { className: 'dswfe-pre', style: { margin: 0, fontSize: 12, lineHeight: 1.55, overflow: 'auto' } },
2892
+ text.split('\n').map((l, i) => {
2893
+ const kind = l.startsWith('+') ? 'add' : l.startsWith('-') ? 'del' : l.startsWith('@@') ? 'hunk' : 'ctx'
2894
+ return h('span', { key: i, style: {
2895
+ display: 'block',
2896
+ whiteSpace: 'pre-wrap', wordBreak: 'break-all',
2897
+ color: kind === 'add' ? '#4a9a4a' : kind === 'del' ? '#c75050' : kind === 'hunk' ? '#8080c0' : undefined,
2898
+ background: kind === 'add' ? 'rgba(74,154,74,.08)' : kind === 'del' ? 'rgba(199,80,80,.08)' : undefined,
2899
+ } }, l === '' ? ' ' : l)
2900
+ }))
2901
+ }
2902
+
2903
+ /** 产物查看器:拉 /run-file(content 与 diff 一次拿全),变更/内容两个 tab。 */
2904
+ function ArtifactViewer({ t, controller, runId, path }) {
2905
+ const [file, setFile] = useState(null)
2906
+ const [error, setError] = useState(null)
2907
+ const [tab, setTab] = useState('diff')
2908
+ useEffect(() => {
2909
+ let alive = true
2910
+ setFile(null)
2911
+ setError(null)
2912
+ setTab('diff')
2913
+ controller.loadArtifact(runId, path)
2914
+ .then((f) => { if (alive) setFile(f) })
2915
+ .catch((e) => { if (alive) setError(String(e && e.message || e)) })
2916
+ return () => { alive = false }
2917
+ }, [runId, path])
2918
+ if (error) return h('div', { className: 'dswfe-empty' }, error)
2919
+ if (!file) return h('div', { className: 'dswfe-empty' }, t('loading'))
2920
+ const showTab = file.diff ? tab : 'content'
2921
+ return h('div', null,
2922
+ h('div', { style: { display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap', margin: '6px 0' } },
2923
+ h('span', { className: 'dswfe-chip' }, file.path),
2924
+ file.size != null ? h('span', { className: 'dswfe-chip' }, fmtBytes(file.size)) : null,
2925
+ h(DiffStat, { additions: file.additions, deletions: file.deletions }),
2926
+ file.truncated ? h('span', { className: 'dswfe-badge', 'data-kind': 'warn' }, t('fileTruncated', { size: fmtBytes(1048576) })) : null,
2927
+ h('span', { style: { flex: 1 } }),
2928
+ h('button', { className: 'dswfe-mini', 'data-active': showTab === 'diff' || undefined, onClick: () => setTab('diff') }, t('diffLabel')),
2929
+ h('button', { className: 'dswfe-mini', 'data-active': showTab === 'content' || undefined, onClick: () => setTab('content') }, t('contentLabel'))),
2930
+ file.binary ? h('div', { className: 'dswfe-empty' }, t('fileBinary'))
2931
+ : showTab === 'diff' ? h(DiffView, { text: file.diff })
2932
+ : h('pre', { className: 'dswfe-pre', style: { margin: 0, maxHeight: '58vh', overflow: 'auto' } }, file.content))
2933
+ }
2934
+
2935
+ /** 产物列表(看板):按环节分组,同一路径跨尝试取最新一条记录。 */
2936
+ function ArtifactList({ t, run, controller }) {
2937
+ const linkName = new Map()
2938
+ for (const ph of (run.snapshot && run.snapshot.phases) || []) {
2939
+ for (const ln of (ph && Array.isArray(ph.links) ? ph.links : [])) {
2940
+ if (ln && ln.id) linkName.set(ln.id, (ph.name ? ph.name + ' / ' : '') + (ln.name || ln.id))
2941
+ }
2942
+ }
2943
+ const latest = new Map() // path → { art, linkId }(trail 按时间序,后者覆盖)
2944
+ for (const a of run.trail || []) for (const art of a.artifacts || []) latest.set(art.path, { art, linkId: a.linkId })
2945
+ if (latest.size === 0) return h('div', { style: { fontSize: 12, opacity: .7, padding: '4px 2px' } }, t('artifactsNone'))
2946
+ const groups = new Map()
2947
+ for (const linkId of indexLinksOf(run).keys()) groups.set(linkId, [])
2948
+ for (const [path, v] of latest) {
2949
+ if (!groups.has(v.linkId)) groups.set(v.linkId, [])
2950
+ groups.get(v.linkId).push({ ...v.art, path })
2951
+ }
2952
+ const children = []
2953
+ for (const [linkId, arts] of groups) {
2954
+ if (!arts || arts.length === 0) continue
2955
+ children.push(h('div', { key: linkId, className: 'dswfe-artgroup' },
2956
+ h('div', { style: { fontSize: 11, opacity: .65, margin: '8px 0 2px' } }, linkName.get(linkId) || linkId),
2957
+ arts.map((a) => h('button', {
2958
+ key: a.path, className: 'dswfe-artrow', title: a.path,
2959
+ onClick: () => controller.setState({ dialog: { type: 'fileview', runId: run.id, path: a.path, name: a.name } }),
2960
+ },
2961
+ h('span', { style: { fontWeight: 500, whiteSpace: 'nowrap' } }, a.name),
2962
+ h('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', opacity: .7, fontSize: 12 } }, a.path),
2963
+ !a.exists ? h('span', { className: 'dswfe-badge', 'data-kind': 'err' }, t('artifactMissing')) : null,
2964
+ h(DiffStat, { additions: a.additions, deletions: a.deletions }),
2965
+ a.mtime ? h('span', { style: { fontSize: 11, opacity: .6, whiteSpace: 'nowrap' } }, fmtClock(a.mtime)) : null,
2966
+ a.exists && a.size != null ? h('span', { style: { fontSize: 11, opacity: .6, whiteSpace: 'nowrap' } }, fmtBytes(a.size)) : null))))
2967
+ }
2968
+ return h('div', { className: 'dswfe-artifacts' }, children)
2969
+ }
2970
+
2971
+ /** 产物预览弹窗(看板产物列表点开)。 */
2972
+ function FileViewDialog({ state, controller, t }) {
2973
+ const dlg = state.dialog
2974
+ return h(Modal, { title: t('fileViewTitle') + ':' + (dlg.name || dlg.path), onClose: () => controller.setState({ dialog: null }), width: 860 },
2975
+ h(ArtifactViewer, { t, controller, runId: dlg.runId, path: dlg.path }))
2976
+ }
2977
+
2978
+ /** 路径 → 树:{ dirs: Map, files: [] }。 */
2979
+ function buildFileTree(entries) {
2980
+ const root = { dirs: new Map(), files: [] }
2981
+ for (const e of entries) {
2982
+ const parts = String(e.path).split('/')
2983
+ let node = root
2984
+ for (let i = 0; i < parts.length - 1; i++) {
2985
+ const seg = parts[i]
2986
+ if (seg === '') continue
2987
+ if (!node.dirs.has(seg)) node.dirs.set(seg, { dirs: new Map(), files: [] })
2988
+ node = node.dirs.get(seg)
2989
+ }
2990
+ node.files.push(e)
2991
+ }
2992
+ return root
2993
+ }
2994
+
2995
+ /** 文件树渲染:目录恒展开,文件行带 diffstat,点击选中。 */
2996
+ function FileTree({ t, entries, sel, onSelect }) {
2997
+ const render = (node, depth) => {
2998
+ const out = []
2999
+ for (const [name, child] of [...node.dirs.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {
3000
+ out.push(h('div', { key: 'd:' + name, style: { padding: '3px 4px', fontSize: 12, opacity: .75, paddingLeft: 4 + depth * 14 } }, '📁 ' + name))
3001
+ out.push(...render(child, depth + 1))
3002
+ }
3003
+ for (const f of [...node.files].sort((a, b) => a.name.localeCompare(b.name))) {
3004
+ out.push(h('button', {
3005
+ key: f.path, className: 'dswfe-artrow', 'data-selected': sel === f.path || undefined,
3006
+ style: { paddingLeft: 4 + depth * 14, gap: 6 }, title: f.path, onClick: () => onSelect(f.path),
3007
+ },
3008
+ h('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, f.name),
3009
+ f.mtime ? h('span', { style: { fontSize: 11, opacity: .6, whiteSpace: 'nowrap' } }, fmtClock(f.mtime)) : null,
3010
+ h(DiffStat, { additions: f.additions, deletions: f.deletions }),
3011
+ !f.exists ? h('span', { className: 'dswfe-badge', 'data-kind': 'err' }, t('artifactMissing')) : null))
3012
+ }
3013
+ return out
3014
+ }
3015
+ return h('div', null, render(buildFileTree(entries), 0))
3016
+ }
3017
+
3018
+ /** 环节产物弹窗:左侧该环节的文件树(同路径取最新一次尝试),右侧查看器。 */
3019
+ function LinkFilesDialog({ state, controller, t }) {
3020
+ const dlg = state.dialog
3021
+ const [files, setFiles] = useState(null)
3022
+ const [sel, setSel] = useState(null)
3023
+ const [err, setErr] = useState(null)
3024
+ useEffect(() => {
3025
+ let alive = true
3026
+ setFiles(null)
3027
+ setSel(null)
3028
+ setErr(null)
3029
+ controller.loadLinkFiles(dlg.runId, dlg.linkId)
3030
+ .then((list) => {
3031
+ if (!alive) return
3032
+ setFiles(list)
3033
+ const first = list.filter((f) => f.exists !== false)[0] || list[0]
3034
+ setSel(first ? first.path : null)
3035
+ })
3036
+ .catch((e) => { if (alive) { setErr(String(e && e.message || e)); setFiles([]) } })
3037
+ return () => { alive = false }
3038
+ }, [dlg.runId, dlg.linkId])
3039
+ const entries = files || []
3040
+ return h(Modal, { title: t('linkFilesTitle') + ':' + (dlg.name || dlg.linkId), onClose: () => controller.setState({ dialog: null }), width: 960 },
3041
+ h('div', { style: { display: 'flex', gap: 12, minHeight: 320 } },
3042
+ h('div', { style: { width: 280, flexShrink: 0, overflowY: 'auto', maxHeight: '62vh', borderRight: '1px solid var(--dsw-alias-border-l1, rgba(128,128,128,.2))', paddingRight: 8 } },
3043
+ files === null && !err ? h('div', { style: { fontSize: 12, opacity: .7, padding: 4 } }, t('loading'))
3044
+ : entries.length === 0 ? h('div', { style: { fontSize: 12, opacity: .7, padding: 4 } }, err || t('noFiles'))
3045
+ : h(FileTree, { t, entries, sel, onSelect: setSel })),
3046
+ h('div', { style: { flex: 1, minWidth: 0, overflowY: 'auto', maxHeight: '62vh' } },
3047
+ sel ? h(ArtifactViewer, { t, controller, runId: dlg.runId, path: sel })
3048
+ : h('div', { className: 'dswfe-empty' }, err || t('pickFile')))))
3049
+ }
3050
+
3051
+ function RunBoard({ state, controller, t }) {
3052
+ const run = state.run
3053
+ if (state.runLoading) return h('div', { className: 'dswfe-board' }, t('loading'))
3054
+ if (!run) return h('div', { className: 'dswfe-empty' }, t('emptyRun'))
3055
+ const latest = latestAttempts(run)
3056
+ const phases = Array.isArray(run.snapshot && run.snapshot.phases) ? run.snapshot.phases : []
3057
+ const { done, total } = runProgress(run)
3058
+ const active = ['queued', 'running', 'awaiting', 'paused'].includes(run.status)
3059
+ const wfName = run.displayName || run.processName || run.processId
3060
+ const spanMs = (run.finishedAt || (active ? Date.now() : run.updatedAt)) - run.createdAt
3061
+ const children = [
3062
+ h('div', { className: 'dswfe-runhead' },
3063
+ h('h3', { className: 'dswfe-detail-title' }, wfName),
3064
+ h(StatusPill, { t, status: run.status }),
3065
+ h('span', { className: 'dswfe-count' }, t('progress', { done, total })),
3066
+ h('div', { className: 'dswfe-actions' },
3067
+ run.status === 'running' || run.status === 'queued' ? h('button', { className: 'dswfe-btn', onClick: () => void controller.runAction('pause', { id: run.id }) }, t('pause')) : null,
3068
+ run.status === 'paused' ? h('button', { className: 'dswfe-btn', 'data-primary': 'true', onClick: () => void controller.runAction('resume', { id: run.id }) }, t('resume')) : null,
3069
+ active ? h('button', { className: 'dswfe-btn', 'data-danger': 'true', onClick: () => void controller.runAction('stop', { id: run.id }) }, t('stopRun')) : null)),
3070
+ h('div', { className: 'dswfe-chips' },
3071
+ h('span', { className: 'dswfe-chip' }, '⚡ ' + (run.usage && run.usage.calls > 0 ? fmtTokens(usageTotalOf(run.usage)) : '—')),
3072
+ h('span', { className: 'dswfe-chip' }, '▶ ' + t('startedAt') + ' ' + (run.createdAt ? new Date(run.createdAt).toLocaleString() : '—')),
3073
+ h('span', { className: 'dswfe-chip' }, '⏹ ' + t('endedAt') + ' ' + (run.finishedAt ? new Date(run.finishedAt).toLocaleString() : active ? '…' : '—')),
3074
+ h('span', { className: 'dswfe-chip' }, '⏱ ' + t('durationTotal') + ' ' + fmtDuration(spanMs, t('durationUnknown'))),
3075
+ h('span', { className: 'dswfe-chip' }, '💬 ' + t('sessionMode') + ':' + t(run.sessionMode === 'single' ? 'sessionSingle' : 'sessionMulti')),
3076
+ run.error ? h('span', { className: 'dswfe-badge', 'data-kind': 'err' }, t('runError') + ': ' + run.error) : null),
3077
+ ]
3078
+ if (run.userInput) children.push(h('div', { className: 'dswfe-kv', style: { background: 'var(--dsw-alias-bg-layer-2, rgba(128,128,128,.06))', border: '1px solid var(--dsw-alias-border-l1, rgba(128,128,128,.2))', borderRadius: 8, padding: '6px 10px' } }, h('b', null, '📌 ' + t('runUserInput') + ':'), h('span', { style: { whiteSpace: 'pre-wrap' } }, run.userInput)))
3079
+ children.push(h('div', { className: 'dswfe-sec' }, h(FlowGraph, { t, parsed: run.snapshot, run })))
3080
+ if (run.pendingBreak) {
3081
+ const humanBreak = run.pendingBreak.kind === 'human'
3082
+ children.push(h('div', { className: 'dswfe-break' },
3083
+ h('span', { style: { fontWeight: 600 } }, '⚠ ' + t(humanBreak ? 'humanReviewTitle' : 'breakTitle')),
3084
+ h('span', { style: { fontSize: 12 } },
3085
+ run.pendingBreak.linkId
3086
+ + (run.pendingBreak.gate && run.pendingBreak.gate.score !== null && run.pendingBreak.gate.score !== undefined
3087
+ ? ' · ' + t('gateLabel') + ' ' + run.pendingBreak.gate.score + ' / ' + (run.pendingBreak.gate.minScore || 0) : '')
3088
+ + ' · ' + (run.pendingBreak.reason || '')),
3089
+ h('div', { className: 'dswfe-actions' },
3090
+ h('button', { className: 'dswfe-btn', 'data-primary': 'true', onClick: () => void controller.runAction('resolve-break', { id: run.id, decision: 'retry' }) }, t(humanBreak ? 'decisionReject' : 'decisionRetry')),
3091
+ h('button', { className: 'dswfe-btn', onClick: () => void controller.runAction('resolve-break', { id: run.id, decision: 'skip' }) }, t(humanBreak ? 'decisionApprove' : 'decisionSkip')),
3092
+ h('button', { className: 'dswfe-btn', 'data-danger': 'true', onClick: () => void controller.runAction('resolve-break', { id: run.id, decision: 'stop' }) }, t('decisionStop')))))
3093
+ }
3094
+ let seq = 0
3095
+ for (let i = 0; i < phases.length; i++) {
3096
+ const ph = phases[i]
3097
+ const links = Array.isArray(ph.links) ? ph.links : []
3098
+ children.push(h('div', { className: 'dswfe-phase', key: ph.id || i },
3099
+ h('div', { className: 'dswfe-phase-head' },
3100
+ h('span', { className: 'dswfe-badge' }, t('phaseNo', { n: i + 1 })),
3101
+ h('span', null, ph.name || ''),
3102
+ h('span', { className: 'dswfe-link-meta' }, links.length + ' ' + t('links'))),
3103
+ links.map((ln) => { seq += 1; return h(RunLinkCard, { key: ln.id, t, run, phase: ph, link: ln, attempt: latest.get(ln.id), controller, index: seq }) })))
3104
+ }
3105
+ return h('div', { className: 'dswfe-board' }, children)
3106
+ }
3107
+
3108
+ function ExecView({ state, controller, t }) {
3109
+ return h('div', { style: { display: 'contents' } },
3110
+ h(RunList, { state, controller, t }),
3111
+ state.runId && (state.runLoading || state.run) ? h(RunBoard, { state, controller, t })
3112
+ : state.runId && state.runError
3113
+ ? h('div', { className: 'dswfe-board' },
3114
+ h('div', { className: 'dswfe-error' }, t('runLoadFailed') + ':' + state.runError),
3115
+ h('div', { className: 'dswfe-actions', style: { marginTop: 10 } },
3116
+ h('button', { className: 'dswfe-btn', 'data-primary': 'true', onClick: () => void controller.loadRun(state.runId) }, t('retryLoad')),
3117
+ h('button', { className: 'dswfe-btn', onClick: () => controller.setState({ runId: null, run: undefined, runError: null }) }, t('cancel'))))
3118
+ : state.runId ? h('div', { className: 'dswfe-empty' }, t('loading')) : h('div', { className: 'dswfe-empty' }, t('emptyRun')))
3119
+ }
3120
+
3121
+ function NewRunDialog({ state, controller, t }) {
3122
+ const dlg = state.dialog
3123
+ const [workspaces, setWorkspaces] = useState(null)
3124
+ const [ws, setWs] = useState('')
3125
+ const [req, setReq] = useState('')
3126
+ const [mode, setMode] = useState('single')
3127
+ useEffect(() => {
3128
+ api('/workspaces').then((d) => setWorkspaces(d.workspaces || [])).catch(() => setWorkspaces([]))
3129
+ }, [])
3130
+ useEffect(() => { if (!state.settings) void controller.loadSettings() }, [])
3131
+ const proc = state.processes.find((p) => p.id === dlg.processId)
3132
+ const [busy, setBusy] = useState(false)
3133
+ const reqOk = req.trim() !== ''
3134
+ return h(Modal, { title: t('runCreate') + ':' + (proc ? (proc.display_name || proc.name) : ''), onClose: () => controller.setState({ dialog: null }) },
3135
+ h('div', { className: 'dswfe-kv' }, h('b', null, t('name') + ':'), proc ? proc.relPath : '—'),
3136
+ h('label', { className: 'dswfe-field' }, t('runUserInput'),
3137
+ h('textarea', {
3138
+ value: req, placeholder: t('runUserInputPh'), spellCheck: false, rows: 4,
3139
+ style: { width: '100%', resize: 'vertical', fontFamily: 'var(--dsw-font-family, inherit)', fontSize: 13, lineHeight: 1.6, border: '1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.3))', borderRadius: 8, padding: '8px 10px', background: 'var(--dsw-alias-bg-layer-2,transparent)', color: 'inherit', boxSizing: 'border-box' },
3140
+ onChange: (e) => setReq(e.target.value),
3141
+ })),
3142
+ h('label', { className: 'dswfe-field' }, t('runWorkspace'),
3143
+ h('select', { value: ws, onChange: (e) => setWs(e.target.value) },
3144
+ workspaces === null ? h('option', { value: '' }, t('loading')) : [
3145
+ h('option', { key: '_', value: '' }, t('workspaceDefault')),
3146
+ workspaces.map((w) => h('option', { key: w.id, value: w.id }, w.title)),
3147
+ ])),
3148
+ h('label', { className: 'dswfe-field' }, h('span', { className: 'dswfe-field-label' }, t('sessionMode'), h(Help, { text: t('helpSessionMode') })),
3149
+ h('select', { value: mode, onChange: (e) => setMode(e.target.value) },
3150
+ h('option', { key: 'multi', value: 'multi' }, t('sessionMulti')),
3151
+ h('option', { key: 'single', value: 'single' }, t('sessionSingle')))),
3152
+ h('div', { style: { fontSize: 12, opacity: .7 } }, mode === 'single'
3153
+ ? '整条流程共用一个会话(门禁也在其中):省 token,但上下文会持续累积。'
3154
+ : '每个环节开一个全新会话执行;用户需求只注入第一个环节,后续环节读上游产出文件;门禁由评审会话打分,不过按 on_gate_fail 流转,返工不超过 max_rework。'),
3155
+ h('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end' } },
3156
+ h('button', { className: 'dswfe-btn', onClick: () => controller.setState({ dialog: null }) }, t('cancel')),
3157
+ h('button', { className: 'dswfe-btn', 'data-primary': 'true', disabled: busy || !proc || !reqOk, onClick: async () => {
3158
+ setBusy(true)
3159
+ try { await controller.createRun({ processId: dlg.processId, workspaceId: ws || undefined, userInput: req.trim(), sessionMode: mode }) } catch (error) { controller.toast(String(error && error.message || error), 'err') } finally { setBusy(false) }
3160
+ } }, t('runCreate'))))
3161
+ }
3162
+
3163
+ /**
3164
+ * 流程图可视化(v0.3):工作流 YAML → 有向图 → 零依赖分层布局 → SVG 渲染。
3165
+ *
3166
+ * 建模对齐 ProcessFlowGraph 的视觉语言:
3167
+ * - START → 第一个环节 → … → END;on_success 实线(forward 灰 / goto 跳转绿),
3168
+ * on_gate_fail 红色虚线 + 「门禁未过 → <id>」标签,break 不连线只在节点上标注,
3169
+ * 回边(指向更早环节)从节点上沿绕行,自环画右侧小环。
3170
+ * - 节点卡:序号徽标、环节名、executor/expert、门禁徽标(最低分数线)、返工上限。
3171
+ * - 运行态叠加:attempt 状态映射节点描边/徽标(当前橙、完成绿+实际门禁得分、
3172
+ * 门禁未过红、跳过灰虚、中断深灰)。
3173
+ *
3174
+ * 布局是纯函数(rank 用 forward 边最长路径,层内按声明序),可在 plain Node 下单测。
3175
+ */
3176
+
3177
+
3178
+ const START_ID = '__start'
3179
+ const END_ID = '__end'
3180
+
3181
+ /** 解析流转值(host validate.flowTarget 的客户端镜像):'next'|'end'|'break'|{jump}。 */
3182
+ function clientFlowTarget(value) {
3183
+ if (value === undefined || value === null || value === '') return null
3184
+ const v = String(value).trim()
3185
+ if (v === 'next' || v === 'end' || v === 'break') return v
3186
+ if (v.startsWith('goto:')) return { jump: v.slice(5).trim() }
3187
+ return { jump: v }
3188
+ }
3189
+
3190
+ /**
3191
+ * 解析后的工作流对象 → 流程图模型。
3192
+ * @returns {{ nodes: Array, edges: Array, breaks: Array, warnings: string[] } | null}
3193
+ * nodes: { id, no, name, phaseId, phaseName, executor, expert, gateMin, gateCount, maxRework, skills }
3194
+ * edges: { from, to, kind: 'forward'|'jump'|'fail', label }
3195
+ * breaks: { linkId, field, value }(break 不连线,节点上标注)
3196
+ */
3197
+ function buildFlowModel(parsed) {
3198
+ if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.phases)) return null
3199
+ const nodes = []
3200
+ const byId = new Map()
3201
+ for (const ph of parsed.phases) {
3202
+ if (!ph || typeof ph !== 'object') continue
3203
+ const links = Array.isArray(ph.links) ? ph.links : []
3204
+ for (const ln of links) {
3205
+ if (!ln || typeof ln !== 'object' || !ln.id) continue
3206
+ const gates = Array.isArray(ln.gates) ? ln.gates.filter((g) => g && typeof g === 'object') : []
3207
+ const gateMin = gates.reduce((min, g) => (typeof g.min_score === 'number' ? Math.min(min, g.min_score) : min), Infinity)
3208
+ const node = {
3209
+ id: String(ln.id),
3210
+ no: nodes.length + 1,
3211
+ name: ln.name || ln.id,
3212
+ phaseId: ph.id || '',
3213
+ phaseName: ph.name || ph.id || '',
3214
+ executor: ln.executor || null,
3215
+ reviewType: ln.review_type || 'ai',
3216
+ expert: (ln.expert_name || ln.expert) || null,
3217
+ gateCount: gates.length,
3218
+ gateMin: Number.isFinite(gateMin) ? gateMin : null,
3219
+ maxRework: Number.isInteger(ln.max_rework) ? ln.max_rework : null,
3220
+ skills: Array.isArray(ln.skills) ? ln.skills : [],
3221
+ onSuccess: ln.on_success || 'next',
3222
+ onGateFail: ln.on_gate_fail == null ? null : String(ln.on_gate_fail),
3223
+ }
3224
+ nodes.push(node)
3225
+ byId.set(node.id, node)
3226
+ }
3227
+ }
3228
+ if (nodes.length === 0) return null
3229
+
3230
+ const edges = []
3231
+ const breaks = []
3232
+ const warnings = []
3233
+ if (nodes.length > 0) edges.push({ from: START_ID, to: nodes[0].id, kind: 'forward', label: '' })
3234
+ const resolve = (value, fromNode) => {
3235
+ const t = clientFlowTarget(value)
3236
+ if (t === null) return null
3237
+ if (t === 'next' || t === 'end' || t === 'break') return t
3238
+ return byId.has(t.jump) ? t.jump : null
3239
+ }
3240
+ nodes.forEach((node, i) => {
3241
+ // on_success
3242
+ const ok = resolve(node.onSuccess)
3243
+ if (ok === 'next') {
3244
+ const nextNode = nodes[i + 1]
3245
+ if (nextNode) edges.push({ from: node.id, to: nextNode.id, kind: 'forward', label: '' })
3246
+ else edges.push({ from: node.id, to: END_ID, kind: 'forward', label: '' })
3247
+ } else if (ok === 'end') {
3248
+ edges.push({ from: node.id, to: END_ID, kind: 'forward', label: '' })
3249
+ } else if (typeof ok === 'string') {
3250
+ edges.push({ from: node.id, to: ok, kind: 'jump', label: node.onSuccess })
3251
+ } else {
3252
+ warnings.push(`环节 "${node.id}" 的 on_success 无法解析`)
3253
+ }
3254
+ // on_gate_fail(与成功策略不同才画;显式 break 才记标注,缺省不标)
3255
+ const gf = node.onGateFail == null ? null : resolve(node.onGateFail)
3256
+ if (node.onGateFail === 'break') {
3257
+ breaks.push({ linkId: node.id, field: 'on_gate_fail', value: 'break' })
3258
+ } else if (typeof gf === 'string' && gf !== ok) {
3259
+ edges.push({ from: node.id, to: gf, kind: 'fail', label: `门禁未过 → ${gf}` })
3260
+ }
3261
+ })
3262
+ return { nodes, edges, breaks, warnings }
3263
+ }
3264
+
3265
+ // ── 布局(纯函数)────────────────────────────────────────────────────────
3266
+
3267
+ const FLOW_NODE_W = 196
3268
+ const FLOW_NODE_H = 74
3269
+ const FLOW_GAP_X = 80
3270
+ const FLOW_GAP_Y = 42
3271
+ const FLOW_PAD = 26
3272
+ const LOOP_BACK_PAD = 64
3273
+
3274
+ /**
3275
+ * 分层布局:START=rank0;沿 forward/jump 前向边做最长路径分层;回边(to.rank≤from.rank)
3276
+ * 不参与分层、渲染为顶部绕行弧线。层内按声明序排布。
3277
+ * @returns {{ positions: Map, width: number, height: number, backEdges: Set<string>, loops: Set<string> }}
3278
+ * positions: id → {x, y}(节点左上角;含 START/END 虚拟节点)
3279
+ */
3280
+ function layoutFlowGraph(model) {
3281
+ const { nodes, edges } = model
3282
+ const positions = new Map()
3283
+ const backEdges = new Set()
3284
+ const loops = new Set()
3285
+ const meta = new Map() // id → { row, col, dir }(蛇形排布信息,边路由用)
3286
+ const n = nodes.length
3287
+ if (n === 0) return { positions, width: 200, height: 120, backEdges, loops, meta }
3288
+
3289
+ // 蛇形排布:每行 K 个(3-5,按 n 取平方根级别),奇数行反向,图变紧凑可读
3290
+ const K = Math.max(3, Math.min(5, Math.ceil(Math.sqrt(n))))
3291
+ const rowH = FLOW_NODE_H + FLOW_GAP_Y * 2
3292
+ nodes.forEach((nd, i) => {
3293
+ const row = Math.floor(i / K)
3294
+ const colInRow = i % K
3295
+ const dir = row % 2 === 0 ? 1 : -1
3296
+ const col = dir === 1 ? colInRow : K - 1 - colInRow
3297
+ positions.set(nd.id, {
3298
+ x: FLOW_PAD + col * (FLOW_NODE_W + FLOW_GAP_X),
3299
+ y: FLOW_PAD + LOOP_BACK_PAD + row * rowH,
3300
+ })
3301
+ meta.set(nd.id, { row, col, dir })
3302
+ })
3303
+ const rows = Math.ceil(n / K)
3304
+ const first = nodes[0].id, last = nodes[n - 1].id
3305
+ const firstPos = positions.get(first), lastPos = positions.get(last)
3306
+ positions.set(START_ID, { x: firstPos.x, y: firstPos.y - 78 })
3307
+ positions.set(END_ID, { x: lastPos.x, y: lastPos.y + FLOW_NODE_H + 34 })
3308
+ for (const e of edges) {
3309
+ const key = e.from + '→' + e.to
3310
+ if (e.from === e.to) loops.add(key)
3311
+ }
3312
+ const width = FLOW_PAD * 2 + K * (FLOW_NODE_W + FLOW_GAP_X) - FLOW_GAP_X
3313
+ const height = FLOW_PAD * 2 + LOOP_BACK_PAD + rows * rowH + 60
3314
+ return { positions, width, height, backEdges, loops, meta }
3315
+ }
3316
+
3317
+
3318
+ // ── 流程图 SVG 组件(v0.3)──────────────────────────────────────────────
3319
+
3320
+ function flowPhaseColor(phaseId) {
3321
+ let h = 0
3322
+ for (let i = 0; i < String(phaseId || '').length; i++) h = (h * 31 + String(phaseId).charCodeAt(i)) >>> 0
3323
+ return 'hsl(' + (h % 360) + ' 45% 55%)'
3324
+ }
3325
+
3326
+ function escXml(text) {
3327
+ return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
3328
+ }
3329
+
3330
+ /**
3331
+ * SVG 文本按估算宽度截断,超出补「…」。卡片宽度固定、角标文案随语言变长时用。
3332
+ */
3333
+ function fitFlowText(text, maxPx, fontPx) {
3334
+ const src = String(text == null ? '' : text)
3335
+ const chWidth = (ch) => (ch.charCodeAt(0) > 0x2e80 ? fontPx : fontPx * 0.56)
3336
+ let total = 0
3337
+ for (const ch of src) total += chWidth(ch)
3338
+ if (total <= maxPx) return src
3339
+ let out = ''
3340
+ let acc = fontPx * 0.56
3341
+ for (const ch of src) {
3342
+ const w = chWidth(ch)
3343
+ if (acc + w > maxPx) break
3344
+ out += ch
3345
+ acc += w
3346
+ }
3347
+ return out + '…'
3348
+ }
3349
+
3350
+ /**
3351
+ * 流程图 SVG。model/layout 来自 flow-model;runState 可选(运行态高亮):
3352
+ * { latestByLink: Map<linkId, attempt>, currentLinkId, pendingLinkId }
3353
+ */
3354
+ function FlowGraph({ t, parsed, run }) {
3355
+ const [zoom, setZoom] = useState(1)
3356
+ const wrapRef = useRef(null)
3357
+ const fittedRef = useRef(false)
3358
+ const model = useMemo(() => buildFlowModel(parsed), [parsed])
3359
+ const layout = useMemo(() => (model ? layoutFlowGraph(model) : null), [model])
3360
+ // 首屏自适应:整图铺满容器宽度(最多放大到 100%),之后用户手动缩放不被覆盖
3361
+ useEffect(() => {
3362
+ if (!layout || fittedRef.current || !wrapRef.current) return
3363
+ fittedRef.current = true
3364
+ const avail = wrapRef.current.clientWidth - 4
3365
+ if (layout.width > avail && avail > 100) setZoom(Math.max(0.3, avail / layout.width))
3366
+ }, [layout])
3367
+ const latest = useMemo(() => (run ? latestAttempts(run) : null), [run])
3368
+ if (!model || !layout) return h('div', { className: 'dswfe-empty' }, t('flowNoParsed'))
3369
+
3370
+ const pos = layout.positions
3371
+ const nodeById = new Map([[START_ID, { id: START_ID, name: 'START', phaseName: '' }], [END_ID, { id: END_ID, name: 'END', phaseName: '' }], ...model.nodes.map((n) => [n.id, n])])
3372
+ const currentLinkId = run && run.current && run.current.linkId
3373
+ const stateOf = (linkId) => {
3374
+ if (!run) return null
3375
+ if (run.pendingBreak && run.pendingBreak.linkId === linkId) return 'awaiting'
3376
+ if (currentLinkId === linkId && ['running', 'queued', 'awaiting'].includes(run.status)) return 'current'
3377
+ const a = latest && latest.get(linkId)
3378
+ return a ? a.status : null
3379
+ }
3380
+ const STROKE = { forward: 'var(--dsw-text-secondary, #94a3b8)', jump: '#22c55e', fail: 'var(--dsw-alias-state-error, #ef4444)' }
3381
+ const edgePath = (e) => {
3382
+ const from = pos.get(e.from)
3383
+ const to = pos.get(e.to)
3384
+ if (!from || !to) return null
3385
+ const isLoop = layout.loops.has(e.from + '→' + e.to)
3386
+ if (e.from === START_ID) return { d: 'M' + (from.x + FLOW_NODE_W / 2) + ' ' + (from.y + 30) + ' L' + (to.x + FLOW_NODE_W / 2) + ' ' + to.y, label: null }
3387
+ if (e.to === END_ID) return { d: 'M' + (from.x + FLOW_NODE_W / 2) + ' ' + (from.y + FLOW_NODE_H) + ' L' + (to.x + FLOW_NODE_W / 2) + ' ' + to.y, label: null }
3388
+ if (isLoop) {
3389
+ const sx = from.x + FLOW_NODE_W, sy = from.y + 18
3390
+ return { d: 'M' + sx + ' ' + sy + ' C' + (sx + 46) + ' ' + sy + ' ' + (sx + 46) + ' ' + (sy + 30) + ' ' + sx + ' ' + (sy + 34), label: null }
3391
+ }
3392
+ const mf = layout.meta.get(e.from), mt = layout.meta.get(e.to)
3393
+ if (!mf || !mt) return null
3394
+ // 同行:顺向直线;逆向/跨列走节点上方弧线(含 fail 回边)
3395
+ if (mf.row === mt.row) {
3396
+ const toRight = mt.col > mf.col
3397
+ const inFlowDir = toRight === (mf.dir === 1)
3398
+ const sx = toRight ? from.x + FLOW_NODE_W : from.x
3399
+ const tx = toRight ? to.x : to.x + FLOW_NODE_W
3400
+ const y = from.y + FLOW_NODE_H / 2
3401
+ if (Math.abs(mt.col - mf.col) === 1 && inFlowDir) return { d: 'M' + sx + ' ' + y + ' L' + tx + ' ' + y, label: e.label || null }
3402
+ const ax = (sx + tx) / 2
3403
+ const asx = toRight ? sx - 12 : sx + 12
3404
+ const atx = toRight ? tx + 12 : tx - 12
3405
+ return { d: 'M' + asx + ' ' + (from.y) + ' C' + asx + ' ' + (from.y - 34) + ' ' + atx + ' ' + (to.y - 34) + ' ' + atx + ' ' + to.y, label: e.label || null, arcY: Math.min(from.y, to.y) - 24, ax }
3406
+ }
3407
+ // 相邻行的同列:垂直直落
3408
+ if (mt.row === mf.row + 1 && mt.col === mf.col) {
3409
+ return { d: 'M' + (from.x + FLOW_NODE_W / 2) + ' ' + (from.y + FLOW_NODE_H) + ' L' + (to.x + FLOW_NODE_W / 2) + ' ' + to.y, label: e.label || null }
3410
+ }
3411
+ // 跨行任意:走两行之间走廊的正交折线(出边 → 横移 → 进边),不斜穿、不压节点
3412
+ const sx = from.x + FLOW_NODE_W / 2
3413
+ const tx = to.x + FLOW_NODE_W / 2
3414
+ if (mt.row > mf.row) {
3415
+ const sy = from.y + FLOW_NODE_H
3416
+ const laneY = from.y + FLOW_NODE_H + FLOW_GAP_Y
3417
+ return { d: 'M' + sx + ' ' + sy + ' L' + sx + ' ' + laneY + ' L' + tx + ' ' + laneY + ' L' + tx + ' ' + to.y, label: e.label || null }
3418
+ }
3419
+ // 回边(回到更早的行):从源顶边偏左出线、走走廊横移、进目标底边偏右,避免与同列垂直前向边重叠
3420
+ const bx = from.x + 26
3421
+ const btx = to.x + 40
3422
+ const laneY = from.y - FLOW_GAP_Y
3423
+ return { d: 'M' + bx + ' ' + from.y + ' L' + bx + ' ' + laneY + ' L' + btx + ' ' + laneY + ' L' + btx + ' ' + (to.y + FLOW_NODE_H), label: e.label || null }
3424
+ }
3425
+
3426
+ const nodeSvg = (id) => {
3427
+ const p = pos.get(id)
3428
+ if (!p) return null
3429
+ if (id === START_ID || id === END_ID) {
3430
+ const isStart = id === START_ID
3431
+ return h('g', { key: id },
3432
+ h('rect', { x: p.x, y: p.y, width: FLOW_NODE_W, height: 30, rx: 15, fill: 'var(--dsw-alias-bg-layer-1, transparent)', stroke: 'var(--dsw-alias-border-l2, rgba(128,128,128,.4))' }),
3433
+ h('text', { x: p.x + FLOW_NODE_W / 2, y: p.y + 20, textAnchor: 'middle', fontSize: 12, fontWeight: 700, fill: 'var(--dsw-text-secondary, gray)', style: { fontFamily: 'monospace', letterSpacing: 2 } }, isStart ? '▶ ' + t('flowStartLabel') : '■ ' + t('flowEndLabel')))
3434
+ }
3435
+ const node = nodeById.get(id)
3436
+ const st = stateOf(id)
3437
+ const att = run && latest && latest.get(id)
3438
+ const border = st === 'current' ? '#d9822b'
3439
+ : st === 'done' || st === 'skipped' ? '#2e9e5b'
3440
+ : st === 'gate_failed' || st === 'awaiting' ? 'var(--dsw-alias-state-error, #ef4444)'
3441
+ : st === 'failed' ? 'var(--dsw-alias-state-error, #ef4444)' : 'var(--dsw-alias-border-l2, rgba(128,128,128,.35))'
3442
+ // 复核方式放在「门禁」左边(三选一:AI 评审 / 人工评审 / 无需评审)
3443
+ const reviewLabel = node.reviewType === 'human' ? t('flowReviewHuman')
3444
+ : node.reviewType === 'none' ? t('flowReviewNone') : t('flowReviewAi')
3445
+ const badge = [reviewLabel]
3446
+ if (node.gateCount > 0) badge.push(t('flowGate', { min: node.gateMin === null ? '?' : node.gateMin }))
3447
+ else badge.push(t('flowNoGate'))
3448
+ if (node.maxRework !== null) badge.push(t('flowRework', { n: node.maxRework }))
3449
+ let runBadge = null
3450
+ let runBadgeW = 0
3451
+ if (att && att.gate && att.gate.score !== null && att.gate.score !== undefined) {
3452
+ runBadge = t('flowScore', { score: String(att.gate.score) })
3453
+ // 角标占位宽度:中文/全角按字号 10px,西文数字按 5.6px(与 fitFlowText 的估算口径一致)
3454
+ for (const ch of runBadge) runBadgeW += ch.charCodeAt(0) > 0xff ? 10 : 5.6
3455
+ }
3456
+ // executor 恒为 agent,不再是可读信息(早前明确要求不在图上显示),只留专家名
3457
+ const meta = [node.expert].filter(Boolean).join(' · ')
3458
+ const w = FLOW_NODE_W, hgt = FLOW_NODE_H
3459
+ return h('g', { key: id },
3460
+ h('rect', { x: p.x + 3, y: p.y + 6, width: 6, height: hgt - 12, rx: 3, fill: flowPhaseColor(node.phaseId) }),
3461
+ h('rect', { x: p.x, y: p.y, width: w, height: hgt, rx: 10, fill: 'var(--dsw-alias-bg-layer-1, #fff)', stroke: border, strokeWidth: st === 'current' ? 2.5 : 1.2 }),
3462
+ h('rect', { x: p.x - 9, y: p.y - 9, width: 22, height: 18, rx: 9, fill: 'var(--dsw-alias-bg-layer-2, #f1f5f9)', stroke: 'var(--dsw-alias-border-l1, rgba(128,128,128,.2))' }),
3463
+ h('text', { x: p.x + 2, y: p.y + 4, textAnchor: 'middle', fontSize: 10, fontWeight: 700, fill: 'var(--dsw-text-secondary, gray)', style: { fontFamily: 'monospace' } }, String(node.no).padStart(2, '0')),
3464
+ h('text', { x: p.x + 14, y: p.y + 24, fontSize: 13, fontWeight: 600, fill: 'var(--dsw-alias-label-primary, currentColor)' }, escXml(node.name.slice(0, 16))),
3465
+ h('text', { x: p.x + 14, y: p.y + 41, fontSize: 10, fill: 'var(--dsw-text-secondary, gray)' }, escXml((meta || node.phaseName || '').slice(0, 26))),
3466
+ h('text', { x: p.x + 14, y: p.y + hgt - 10, fontSize: 10, fill: node.gateCount > 0 ? '#b8860b' : 'var(--dsw-text-secondary, gray)' }, escXml(fitFlowText(badge.join('·'), w - 14 - (runBadge ? runBadgeW + 22 : 12), 10))),
3467
+ runBadge ? h('text', { x: p.x + w - 12, y: p.y + hgt - 10, textAnchor: 'end', fontSize: 10, fontWeight: 700, fill: '#2e9e5b' }, runBadge) : null,
3468
+ st === 'current' ? h('circle', { cx: p.x + w - 12, cy: p.y + 12, r: 5, fill: '#d9822b' }) : null,
3469
+ st === 'done' ? h('circle', { cx: p.x + w - 12, cy: p.y + 12, r: 5, fill: '#2e9e5b' }) : null,
3470
+ (st === 'gate_failed' || st === 'awaiting' || st === 'failed') ? h('circle', { cx: p.x + w - 12, cy: p.y + 12, r: 5, fill: 'var(--dsw-alias-state-error, #ef4444)' }) : null)
3471
+ }
3472
+
3473
+ const edgeSvgs = []
3474
+ for (const e of model.edges) {
3475
+ const path = edgePath(e)
3476
+ if (!path) continue
3477
+ const color = e.kind === 'fail' ? STROKE.fail : e.kind === 'jump' ? STROKE.jump : STROKE.forward
3478
+ const dashed = e.kind === 'fail' ? '6,4' : undefined
3479
+ edgeSvgs.push(h('path', { key: e.from + '→' + e.to + e.kind, d: path.d, fill: 'none', stroke: color, strokeWidth: e.kind === 'fail' ? 1.8 : 1.4, strokeDasharray: dashed, markerEnd: 'url(#dswfe-arrow-' + (e.kind === 'fail' ? 'f' : e.kind === 'jump' ? 'j' : 'n') + ')' }))
3480
+ }
3481
+
3482
+ return h('div', null,
3483
+ h('div', { className: 'dswfe-flowlegend' },
3484
+ h('span', null, h('span', { className: 'sw fwd' }), t('flowLegendForward')),
3485
+ h('span', null, h('span', { className: 'sw jump' }), t('flowLegendJump')),
3486
+ h('span', null, h('span', { className: 'sw fail' }), t('flowLegendFail')),
3487
+ h('span', null, t('flowLegendBreak')),
3488
+ h('span', { style: { marginLeft: 'auto' } },
3489
+ h('button', { className: 'dswfe-mini', onClick: () => setZoom(Math.max(0.5, zoom - 0.2)) }, '−'),
3490
+ h('span', { style: { margin: '0 6px' } }, Math.round(zoom * 100) + '%'),
3491
+ h('button', { className: 'dswfe-mini', onClick: () => setZoom(Math.min(2, zoom + 0.2)) }, '+'))),
3492
+ h('div', { className: 'dswfe-flowwrap', ref: wrapRef },
3493
+ h('svg', { width: layout.width * zoom, height: layout.height * zoom, viewBox: '0 0 ' + layout.width + ' ' + layout.height },
3494
+ h('defs', null,
3495
+ h('marker', { id: 'dswfe-arrow-n', viewBox: '0 0 10 10', refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: 'auto-start-reverse' }, h('path', { d: 'M0 0L10 5L0 10z', fill: 'var(--dsw-text-secondary, #94a3b8)' })),
3496
+ h('marker', { id: 'dswfe-arrow-j', viewBox: '0 0 10 10', refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: 'auto-start-reverse' }, h('path', { d: 'M0 0L10 5L0 10z', fill: '#22c55e' })),
3497
+ h('marker', { id: 'dswfe-arrow-f', viewBox: '0 0 10 10', refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: 'auto-start-reverse' }, h('path', { d: 'M0 0L10 5L0 10z', fill: 'var(--dsw-alias-state-error, #ef4444)' }))),
3498
+ edgeSvgs,
3499
+ [START_ID, ...model.nodes.map((n) => n.id), END_ID].map((id) => nodeSvg(id)))))
3500
+ }
3501
+
3502
+ function FlowTab({ t, parsed }) {
3503
+ return h('div', null, h(FlowGraph, { t, parsed }))
3504
+ }
3505
+
3506
+ // ── 挂载 ─────────────────────────────────────────────────────────────────
3507
+
3508
+ const name = CLIENT_NAME
3509
+ const inject = ['slots', 'locale']
3510
+
3511
+ // (v0.4 起 shell.overlay slot 已移除:全屏 overlay 盖住侧栏观感差,改走 mountPrcView 中栏接管。)
3512
+
3513
+ let ReactGlobal = null
3514
+ try { ReactGlobal = require('react') } catch {}
3515
+
3516
+ /** 同页重复 apply 防护:上一次挂载的 teardown(apply 内赋值)。 */
3517
+ let activeApplyTeardown = null
3518
+
3519
+ /** 中栏接管视图(apply 内赋值;openPanel 的兜底 ensure 也会用到)。 */
3520
+ let prcView = null
3521
+
3522
+ /**
3523
+ * 中栏接管视图(taskboard board-mount 同款):容器 div 追加为会话列末尾子节点
3524
+ * (React shell 不管理它),ProcessPanel 常驻其中、关闭时渲染 null;开合由
3525
+ * html[data-dswfe-active] 属性驱动(CSS 隐藏列内兄弟,侧栏保持可见)。
3526
+ * ensure(force):force=true 时壳层退化兜底——容器挂 body 退回全屏浮层。
3527
+ */
3528
+ function mountPrcView(controller, t) {
3529
+ const COLUMN_SELECTOR = '[data-pane="conversation"], [class*="centerCol"], .dshDesktopConversationSurface'
3530
+ let container = null
3531
+ let root = null
3532
+ const unplace = () => {
3533
+ try { if (root) root.unmount() } catch {}
3534
+ try { if (container) container.remove() } catch {}
3535
+ root = null; container = null
3536
+ }
3537
+ const place = (host, fallback) => {
3538
+ container = document.createElement('div')
3539
+ container.className = 'dswfe-view'
3540
+ container.setAttribute('data-dswfe-view', '')
3541
+ if (fallback) container.setAttribute('data-dswfe-fallback', '')
3542
+ host.appendChild(container)
3543
+ root = require('react-dom/client').createRoot(container)
3544
+ root.render(h(ProcessPanel, { controller, t, slotProps: null }))
3545
+ }
3546
+ const ensure = (force) => {
3547
+ if (container && container.isConnected) return
3548
+ const column = document.querySelector(COLUMN_SELECTOR)
3549
+ if (column) { unplace(); place(column, false) }
3550
+ else if (force && document.body) { unplace(); place(document.body, true) }
3551
+ }
3552
+ const tryPlace = () => { ensure(false) }
3553
+ const waitObserver = new MutationObserver(tryPlace)
3554
+ waitObserver.observe(document.body, { childList: true, subtree: true })
3555
+ const retry = setInterval(tryPlace, 2000)
3556
+ tryPlace()
3557
+ return {
3558
+ ensure,
3559
+ dispose() {
3560
+ clearInterval(retry)
3561
+ waitObserver.disconnect()
3562
+ unplace()
3563
+ try { document.documentElement.removeAttribute(PRC_ACTIVE_ATTR) } catch {}
3564
+ },
3565
+ }
3566
+ }
3567
+
3568
+ const moduleExports = {
3569
+ name,
3570
+ inject,
3571
+ __internals: { Controller, filterProcesses, ZH, EN, AI_PROMPT, colorizeLine, buildFlowModel, layoutFlowGraph, clientFlowTarget },
3572
+ __boot(container, opts = {}) {
3573
+ ensureStyles()
3574
+ const t = makeT(null)
3575
+ const controller = new Controller()
3576
+ controller.t = t
3577
+ if (opts.autostart !== false) controller.start()
3578
+ if (opts.open !== false) controller.openPanel()
3579
+ const root = require('react-dom/client').createRoot(container)
3580
+ root.render(h(ProcessPanel, { controller, t, slotProps: null }))
3581
+ return { controller, root }
3582
+ },
3583
+ apply(ctx) {
3584
+ ensureStyles()
3585
+ let t = makeT(null)
3586
+ try {
3587
+ if (ctx.locale && typeof ctx.locale.register === 'function') {
3588
+ ctx.locale.register(NS, 'zh', ZH)
3589
+ ctx.locale.register(NS, 'en', EN)
3590
+ const bound = typeof ctx.locale.bind === 'function' ? ctx.locale.bind(NS) : null
3591
+ if (bound) t = makeT(bound)
3592
+ }
3593
+ } catch (e) { try { console.error('[dsh-workflow-execute] locale init:', e) } catch {} }
3594
+ const controller = new Controller()
3595
+ controller.t = t
3596
+ controller.start()
3597
+ try {
3598
+ const host = globalThis.location && globalThis.location.hostname
3599
+ if (host === 'localhost' || host === '127.0.0.1') window.__prc = controller
3600
+ } catch {}
3601
+ // 会话服务:动态 inject(客户端 ctx 支持;缺席时「打开会话」降级提示)
3602
+ try {
3603
+ if (typeof ctx.inject === 'function') {
3604
+ ctx.inject(['sessions'], (scope) => {
3605
+ const svc = scope && scope.sessions
3606
+ if (svc && typeof svc.open === 'function') controller.sessionsSvc = svc
3607
+ })
3608
+ // dsh 0.1.7+: sessions.open() 被移除,会话导航改走
3609
+ // uiWorkspace.openSession()。归一成 { open(id) } 面孔,调用点不变。
3610
+ ctx.inject(['uiWorkspace'], (scope) => {
3611
+ const svc = scope && scope.uiWorkspace
3612
+ const cur = controller.sessionsSvc
3613
+ if (svc && typeof svc.openSession === 'function' && !(cur && typeof cur.open === 'function')) {
3614
+ controller.sessionsSvc = { open: (id) => svc.openSession(id) }
3615
+ }
3616
+ })
3617
+ }
3618
+ } catch (e) { console.error('[dsh-workflow-execute] sessions inject:', e) }
3619
+ // 同页重复 apply(重建/热重载):先拆掉上一次挂载,避免残留失效的入口行
3620
+ if (typeof activeApplyTeardown === 'function') { try { activeApplyTeardown() } catch {} activeApplyTeardown = null }
3621
+ const disposers = []
3622
+ try { disposers.push(mountSidebarEntry(controller, t)) } catch (e) { console.error('[dsh-workflow-execute] sidebar mount:', e) }
3623
+ try { prcView = mountPrcView(controller, t); disposers.push(() => prcView && prcView.dispose()) } catch (e) { console.error('[dsh-workflow-execute] view mount:', e) }
3624
+ // 与其他面板互斥
3625
+ const onActivate = (event) => { if (event.detail !== PANEL_NAME && controller.getSnapshot().panelOpen) controller.closePanel() }
3626
+ document.addEventListener(ACTIVATE_EVENT, onActivate)
3627
+ const teardown = () => {
3628
+ document.removeEventListener(ACTIVATE_EVENT, onActivate)
3629
+ if (prcView) { try { prcView.dispose() } catch {} prcView = null }
3630
+ for (const d of disposers) { try { d() } catch {} }
3631
+ controller.dispose()
3632
+ }
3633
+ activeApplyTeardown = teardown
3634
+ ctx.effect(() => teardown, 'dsh-workflow-execute: client mount')
3635
+ },
3636
+ }
3637
+
3638
+ // kit 内联(构建期注入到同一 factory 作用域的 var PluginKit;plain Node 测试下缺失 → AI 对话框降级提示)
3639
+ function getKit() {
3640
+ try { return typeof PluginKit !== 'undefined' ? PluginKit : null } catch { return null }
3641
+ }
3642
+
3643
+ module.exports = moduleExports
3644
+
3645
+ return module.exports
3646
+ }
3647
+ })