on-munseo-local 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MANIFEST.json +505 -33
- package/README.md +75 -37
- package/local/build.json +3 -3
- package/local/config.js +1 -1
- package/local/main.js +1 -1
- package/local/setup.js +2 -0
- package/package.json +2 -2
- package/server/onform.js +1 -1
- package/server/onsvc/worker.js +1 -1
- package/server/onwrite.js +1 -1
- package/server/onwrite_auto.js +1 -1
- package/server/onwrite_chart.js +2 -0
- package/server/onwrite_docx.js +1 -1
- package/server/onwrite_gov.js +1 -1
- package/server/onwrite_gov_orgs.js +2 -0
- package/server/onwrite_numcheck.js +2 -0
- package/server/onwrite_review.js +1 -1
- package/trial/server/mcp_more.js +1 -1
- package/trial/server/webrules.js +2 -0
- package/trial/web/app/gallery/g01.hwpx +0 -0
- package/trial/web/app/gallery/g02.hwpx +0 -0
- package/trial/web/app/gallery/g03.hwpx +0 -0
- package/trial/web/app/gallery/g04.hwpx +0 -0
- package/trial/web/app/gallery/g05.hwpx +0 -0
- package/trial/web/app/gallery/g06.hwpx +0 -0
- package/trial/web/app/gallery/g07.hwpx +0 -0
- package/trial/web/app/gallery/g08.hwpx +0 -0
- package/trial/web/app/gallery/g09.hwpx +0 -0
- package/trial/web/app/gallery/g10.hwpx +0 -0
- package/trial/web/app/gallery/g11.hwpx +0 -0
- package/trial/web/app/gallery/g12.hwpx +0 -0
- package/trial/web/app/gallery/g13.hwpx +0 -0
- package/trial/web/app/gallery/g14.hwpx +0 -0
- package/trial/web/app/gallery/g15.hwpx +0 -0
- package/trial/web/app/gallery/g16.hwpx +0 -0
- package/trial/web/app/gallery/g17.hwpx +0 -0
- package/trial/web/app/gallery/g18.hwpx +0 -0
- package/trial/web/app/gallery/g19.hwpx +0 -0
- package/trial/web/app/gallery/g20.hwpx +0 -0
- package/trial/web/app/gallery/g21.hwpx +0 -0
- package/trial/web/app/gallery/g22.hwpx +0 -0
- package/trial/web/app/gallery/g23.hwpx +0 -0
- package/trial/web/app/gallery/g24.hwpx +0 -0
- package/trial/web/app/gallery/g25.hwpx +0 -0
- package/trial/web/app/gallery/g26.hwpx +0 -0
- package/trial/web/app/gallery/g27.hwpx +0 -0
- package/trial/web/app/gallery/g28.hwpx +0 -0
- package/trial/web/app/gallery/g29.hwpx +0 -0
- package/trial/web/app/gallery/g30.hwpx +0 -0
- package/trial/web/app/gallery/g31.hwpx +0 -0
- package/trial/web/app/gallery/g32.hwpx +0 -0
- package/trial/web/app/gallery/g33.hwpx +0 -0
- package/trial/web/app/gallery/g34.hwpx +0 -0
- package/trial/web/app/gallery/g35.hwpx +0 -0
- package/trial/web/app/gallery/g36.hwpx +0 -0
- package/trial/web/app/gallery/g37.hwpx +0 -0
- package/trial/web/app/gallery/g38.hwpx +0 -0
- package/trial/web/app/gallery/g39.hwpx +0 -0
- package/trial/web/app/gallery/g40.hwpx +0 -0
- package/trial/web/app/gallery/g41.hwpx +0 -0
- package/trial/web/app/gallery/g42.hwpx +0 -0
- package/trial/web/app/gallery/g43.hwpx +0 -0
- package/trial/web/app/gallery/g44.hwpx +0 -0
- package/trial/web/app/gallery/g45.hwpx +0 -0
- package/trial/web/app/gallery/g46.hwpx +0 -0
- package/trial/web/app/gallery/g47.hwpx +0 -0
- package/trial/web/app/gallery/g48.hwpx +0 -0
- package/trial/web/app/gallery/g49.hwpx +0 -0
- package/trial/web/app/gallery/g50.hwpx +0 -0
- package/trial/web/app/gallery/g51.hwpx +0 -0
- package/trial/web/app/gallery/g52.hwpx +0 -0
- package/trial/web/app/gallery/g53.hwpx +0 -0
- package/trial/web/app/gallery/g54.hwpx +0 -0
- package/trial/web/app/gallery/g55.hwpx +0 -0
- package/trial/web/app/gallery/g56.hwpx +0 -0
- package/trial/web/app/gallery/g57.hwpx +0 -0
- package/trial/web/app/gallery/g58.hwpx +0 -0
- package/trial/web/app/gallery/g59.hwpx +0 -0
- package/trial/web/app/gallery/g60.hwpx +0 -0
- package/trial/web/app/gallery/g61.hwpx +0 -0
- package/trial/web/app/gallery/g62.hwpx +0 -0
- package/trial/web/app/gallery/g63.hwpx +0 -0
- package/trial/web/app/gallery/g64.hwpx +0 -0
- package/trial/web/app/gallery/g65.hwpx +0 -0
- package/trial/web/app/gallery/g66.hwpx +0 -0
- package/trial/web/app/gallery/gallery.json +2404 -0
- package/trial/web/app/js/chart.js +2 -0
- package/trial/web/app/js/diagram.js +2 -0
- package/trial/web/app/js/fill_match.js +2 -0
- package/trial/web/app/js/gaejo.js +2 -0
- package/trial/web/app/js/refdoc.js +2 -0
package/trial/server/mcp_more.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/*! On 문서 내 PC 판 · on-munseo — 엔진·코드의 무단 복제·배포·재사용·역공학 금지(이용약관 제5조). 오픈소스 부품은 각 라이선스를 따름 */
|
|
2
|
-
export const LIM=Object.freeze({text:2e4,lines:2e3,tableText:2e4,diagramText:4e3,md:2e5,chapters:40,items:400,rows:200,cols:20,cell:2e3,material:3e5,files:4,blocks:400,renderPages:6,outPng:10485760,outText:4e5,chartH:2400,ms:9e4,rules:2e4});export function trialMoreTools(){}
|
|
2
|
+
import t from"fs";import e from"path";import{createRequire as s}from"module";import{fileURLToPath as n}from"url";import{z as r}from"zod";import{call as a,exec as i,withBudget as o,outsideBudget as l,isBudget as c}from"./webrules.js";import{scanText as p}from"./pii_fold.js";import{mdRunsProblem as h}from"./docguard.js";import{write as u,pages as m,read as f,fill as g}from"./engine.js";import{run as d}from"../../server/onsvc/pool.js";import{chartOrient as b}from"../../server/onwrite_chart.js";import{govPrep as w}from"../../server/onwrite_auto.js";import{reviewWritten as x}from"../../server/onwrite_review.js";const k=e.resolve(e.dirname(n(import.meta.url)),"..","..");export const LIM=Object.freeze({text:2e4,lines:2e3,tableText:2e4,diagramText:4e3,md:2e5,chapters:40,items:400,rows:200,cols:20,cell:2e3,material:3e5,files:4,blocks:400,renderPages:6,outPng:10485760,outText:4e5,chartH:2400,ms:9e4,rules:2e4});const y=(t,e,s)=>({lines_done:t,lines_total:e,note:`시간 한도로 앞 ${t.toLocaleString()}줄만 ${s}(${e.toLocaleString()}줄 가운데) — 나머지 줄은 원문 그대로예요. 남은 글을 나눠 다시 보내 주세요.`}),_=(t,e=400)=>Object.assign(new Error(t),{status:e}),S="보안 등급 표시(대외비·비밀 등급 등)가 있는 글이라 처리하지 않아요. 공개 문서·본인 문서만 써 주세요.",$=t=>{try{return!!p(String(t||""),{name:"doc.md"}).marks}catch{return!1}},j=(t,e=LIM.ms)=>{let s;return Promise.race([t,new Promise(((t,n)=>{s=setTimeout((()=>n(_("시간이 너무 오래 걸려 멈췄어요. 글을 줄여 다시 해 주세요.",408))),e),s.unref&&s.unref()}))]).finally((()=>clearTimeout(s)))};export const josa=(t,e,s)=>{const n=String(t||"").trim().slice(-1).charCodeAt(0)-44032;return n>=0&&n<11172?n%28?e:s:e};const I=(t,e,s)=>{const n=String(t??"");if(n.length>e)throw _(`${s}${josa(s,"이","가")} 너무 길어요(${e.toLocaleString()}자까지) — 나눠서 보내 주세요.`,413);return n},M=(t,e)=>(t=String(t||"").replace(/\s+/g," ").trim()).length>e?t.slice(0,e-1)+"…":t,E=(t,e)=>String(t||"").replace(/[\\/:*?"<>|\u0000-\u001f]+/g," ").replace(/\s+/g," ").trim().slice(0,60)||e,v=s(import.meta.url);let L=null;function A(){if(L)return L;L=v("@napi-rs/canvas");const t=e.join(k,"vendor","rhwp-studio","fonts");for(const s of["Pretendard-Regular.woff2","Pretendard-Medium.woff2","Pretendard-SemiBold.woff2","Pretendard-Bold.woff2"])try{L.GlobalFonts.registerFromPath(e.join(t,s),"OnUI")}catch{}return L}const C='px OnUI, Pretendard, "Malgun Gothic", sans-serif';function P(){const t=A().createCanvas(8,8).getContext("2d");let e="";return(s,n)=>{const r="700 "+n+C;return r!==e&&(t.font=r,e=r),t.measureText(String(s)).width}}async function T(t,e,s,n){if(!(s&&s.w>0&&s.h>0))throw _("그림을 짜지 못했어요.");if(s.h>LIM.chartH)throw _("항목이 너무 많아 그림이 너무 길어요 — 나눠서 그려 주세요.",413);const r=A().createCanvas(Math.round(2*s.w),Math.round(2*s.h));return i(t,e+".draw",[r.getContext("2d"),s,2,a(t,e+".palOf",[n])]),Buffer.from(await r.encode("png"))}const O=[e.join(k,"trial","web","app","gallery"),e.join(k,"public","gallery")];let B=null;function N(){if(B)return B;for(const s of O)try{const n=JSON.parse(t.readFileSync(e.join(s,"gallery.json"),"utf8"));if(Array.isArray(n.items))return B={dir:s,items:n.items}}catch{}throw _("예시 양식 목록을 찾지 못했어요.",503)}const F=t=>String(t.frame||"").split("\n").filter((t=>/^##\s/.test(t))).map((t=>t.replace(/^##\s+/,"").trim())).slice(0,20),D=t=>String(t||"").replace(/[\s·()]/g,"").toLowerCase(),V=t=>String(null==t?"":t).replace(/[&<>"]/g,(t=>({"&":"&","<":"<",">":">",'"':"""}[t])));function q(t){let e=V(t).replace(/<br\s*\/?>/gi,"<br>").replace(/<(\/?)(sup|sub)>/gi,"<$1$2>");return e=e.replace(/!\[[^\]]*\]\([^)]*\)/g,"").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\*\*([^*]+)\*\*/g,"<b>$1</b>").replace(/(^|[^*])\*([^*\s][^*]*)\*/g,"$1<i>$2</i>"),e}const G=t=>String(t||"").replace(/<br\s*\/?>/gi," ").replace(/<[^>]+>/g,"").replace(/!\[[^\]]*\]\([^)]*\)/g,"").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/\*\*|__/g,"").replace(/\s+/g," ").trim(),H=/^[\s(]*[-+−]?[\d,.]+\s*(%|배|원|명|개|건|곳|천|만|억|조|백만|천원|만원|억원|km|㎢|분|일|년|월)?[)\s]*$/,X=(t,e,s,n)=>'<p style="text-align:'+e+';margin:0"><span style="font-size:'+n+"pt"+(s?";font-weight:bold":"")+'">'+(s?"<b>"+t+"</b>":t)+"</span></p>";const U=/^\s*(<.*>|〈.*〉|\[.*\])\s*$/,z=/^\s*[((]?\s*(단위|자료|출처)\s*[::]/;function R(t){const e={};return t.forEach(((s,n)=>{if("t"!==s.k)return;const r=[],a=[];let i,o;for(i=n-1;i>=0&&n-i<=2;i--){const s=t[i];if("p"!==s.k||e[i]||!(s.cap||(U.test(s.plain)||z.test(s.plain))&&s.plain.length<=60))break;r.unshift(s),e[i]=1}for(o=n+1;o<t.length&&o-n<=2;o++){const s=t[o];if("p"!==s.k||e[o]||!(s.note||(z.test(s.plain)||/^\s*※/.test(s.plain))&&s.plain.length<=80))break;a.push(s),e[o]=1}s.with=r.concat(a),s.cap=r.map((t=>t.plain)).join(" ")})),t.filter(((t,s)=>!e[s]))}const J=t=>"t"===t.k?t.rows&&t.rows.length>=2:"p"===t.k&&String(t.plain||"").replace(/\s/g,"").length>=8,K=t=>{const e=new Map;for(const s of a("draw","EbChart.numsOf",[String(t||"")]))e.set(s,(e.get(s)||0)+1);return e};export function materialHeads(t){let e=!1;return String(t||"").split("\n").map((t=>{if(/^\s*(```|~~~)/.test(t))return e=!e,t;if(e||/^\s*\|/.test(t))return t;const s=/^\s*(?:[□■]|[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]\s*[.).]?|(?:X|IX|VIII|VII|VI|V|IV|III|II|I)\s*[.).])\s*(\S.{0,38})$/.exec(t);if(!s)return t;const n=s[1].trim();return/[::]/.test(n)||/(다|함|음|임|됨)\s*[.。?!]?$/.test(n)||/[.。?!]$/.test(n)||/\*\*/.test(n)?t:"## "+n})).join("\n")}const W=(t,e)=>!/뚜렷하지 않음|헷갈림/.test(t)||e&&e.sec?/장 제목을 찾지 못함/.test(t)?t+" — 이 양식은 칸 채우기만 돼요(「항목: 값」 줄, on_fields·on_fill)":t:t+" — 자료에 장 제목(「## 제목」·「□ 제목」 줄)을 두고 그 아래에 글을 두면 같은 이름 장에 맞춰요";let Z=new Map;const Y=t=>t.paras.map((t=>String(t.c||"").replace(/▯/g," "))).concat(t.tables.flatMap((t=>t.cells.flatMap((t=>t.lines.map((t=>String(t.c||"")))))))).join("\n"),Q=["□","○","-","·","*","※"],tt=["부제","날짜","기관","수신","경유","보도시점","배포","담당부서","담당자","연락처","공고번호","발신명의","시행","접수","전화","메일","홈페이지"],et=t=>I(t,LIM.cell,"칸 글").replace(/\|/g,"/").replace(/\s*\n\s*/g," ");export function qualityTips(t){const e=[],s=Array.isArray(t&&t.chapters)?t.chapters:[];if(!s.length)return e;const n=t=>String(t||"").replace(/\*\*/g,"");let r=0,a=0,i=0,o=0,l=new Set,c="",p=0,h=[];const u=[],m=new Set(s.flatMap((t=>(Array.isArray(t.items)?t.items:[]).filter((t=>t.table&&t.table.chart)).flatMap((t=>(t.table.rows||[]).flat().map((t=>String(t).replace(/[,\s]/g,""))))))));s.forEach(((t,s)=>{const f=Array.isArray(t.items)?t.items:[],g=f.filter((t=>t.mark||t.table||t.diagram)).length;if(g>=10&&!f.some((t=>"절"===t.head))&&e.push(`장 「${M(t.title||s+1,20)}」는 항목이 ${g}개인데 절이 없어요 — head 「절」·「소제목」으로 나누면 기본계획처럼 짜임이 보여요.`),0===s){const t=f.find((t=>!t.mark&&/^[◆◈◇]/.test(n(t.text))));t?n(t.text).length<100&&e.push(`첫 장 요약 「◆ …」이 ${n(t.text).length}자예요 — 중요한 내용이니 3~4줄(120~160자)로 쓰면 더 좋아요.`):e.push("첫 장 첫머리에 핵심 요약 「◆ …」(3~4줄, 120~160자)이 없어요.")}f.forEach(((t,e)=>{if(t.table&&t.table.chart){const t=f[e-1],s=f[e+1];t&&t.table&&t.table.chart||s&&s.table&&s.table.chart||p++}if(t.table&&(t.table.chart?r++:(t.table.rows||[]).length>=3&&(t.table.rows||[]).some((t=>(t||[]).slice(1).some((t=>/^[\d.,]+$/.test(String(t).trim())))))&&a++),t.table&&!t.table.chart&&(t.table.rows||[]).flat().filter((t=>/^[\d.,%]+$/.test(String(t).trim())&&!m.has(String(t).replace(/[,\s]/g,"")))).length>=3?u.push(M(t.table.title||(t.table.head||[]).join(" · "),30)):!t.table&&!t.diagram&&(t=>{const e={};for(const s of String(t||"").matchAll(/(\d[\d,]*(?:\.\d+)?)\s*(%|명|개소|개|건|곳|원|천원|만원|억원|조원|천명|만명|회|시간|분|대|톤)(?![가-힣])/g)){const t=s[1].replace(/,/g,"");m.has(t)||(e[s[2]]=(e[s[2]]||0)+1)}return Math.max(0,...Object.values(e))})(n(t.text))>=3&&u.push(M(n(t.text).replace(/^[□○\-·*※]\s*/,""),30)),"○"!==t.mark&&"-"!==t.mark||h.push(n(t.text).replace(/\s/g,"").length),"○"===t.mark){i++;const t=f[e+1];t&&"-"===t.mark||o++}for(const e of n(t.text).matchAll(/\b[A-Z]{2,}(?:-[A-Z]+)?\b/g))l.add(e[0]);"*"!==t.mark&&"※"!==t.mark||(c+=" "+n(t.text))}))}));{const t=h.length?h.reduce(((t,e)=>t+e),0)/h.length:99;h.length>=6&&t<30&&e.push(`○·- 문장이 짧아요(평균 ${Math.round(t)}자, 빈칸 뺌) — 한 줄은 약 38자예요. 문장마다 자료의 근거 숫자·주체·기간·대상을 담아 한 줄을 채우거나, 넘기면 둘째 줄까지 거의 채워 주세요(지어내지 않음).`)}p&&u.length&&e.push(`그래프 ${p}개가 짝 없이 따로 있어 한 줄을 다 차지해요 — 원고에 그래프로 쓰지 않은 숫자 묶음(「${u.slice(0,2).join("」「")}」)이 있으니 같은 절에서 함께 볼 것이면 그 숫자로 짝 그래프를 하나 더 만들어 잇달아 두세요(한 줄에 반 폭씩 나란히). 함께 볼 것이 아니면 그대로 둬도 돼요.`),!r&&a&&e.push(`숫자 표가 ${a}개인데 그래프가 없어요 — 비교·추이·구성비를 보여 줄 표 1~2개에 table.chart 를(그래프 두 개를 잇달아 두면 한 줄에 나란히).`),i>=4&&o/i>.6&&e.push(`○ ${i}줄 가운데 ${o}줄은 아래 - 줄이 없어요 — 자료에 있는 근거(숫자·주체·기간·대상·비율·견줌)로 ○ 마다 - 를 1~3줄 더해 촘촘하게(○ 를 되풀이하거나 말만 바꾼 줄은 쓰지 않음).`);const f=[...l].filter((t=>!c.includes(t))).slice(0,5);return f.length&&e.push(`풀이 없는 약어·용어: ${f.join(", ")} — 본문 낱말 뒤에 * 를 붙이고(예: KTAS*) 그 아래 mark 「*」 줄로 「KTAS: 한국형 응급환자 분류도구」처럼 풀이를(자료에 있는 풀이만).`),e.slice(0,6)}export function structureToText(t){const e=[],s=t.meta||{},n=Object.entries(s).filter((([t,e])=>tt.includes(t)&&null!=e&&String(e).trim()));if(n.length){e.push("---");for(const[t,s]of n)e.push(t+": "+M(s,200));e.push("---")}t.title&&e.push("제목: "+M(t.title,200),"");const r=Array.isArray(t.chapters)?t.chapters:[];if(r.length>LIM.chapters)throw _(`장은 ${LIM.chapters}개까지예요.`,413);return r.forEach(((t,s)=>{const n=String(t.title||"").replace(/^\s*(?:제\s*\d{1,2}\s*[장절]\.?|[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ]+\s*[.).]?|(?:XII|XI|X|IX|VIII|VII|VI|V|IV|III|II|I)\s*[.).]|\d{1,2}\s*[.).])\s*/,"").trim();t.title&&e.push(("ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ"[s]||String(s+1))+". "+M(n||t.title,120),"");const r=Array.isArray(t.items)?t.items:[];if(r.length>LIM.items)throw _(`한 장에 항목은 ${LIM.items}개까지예요.`,413);let a=0,i=0,o=null;for(let t=0;t<r.length;t++){const s=r[t];if("절"===s.head||"소제목"===s.head){const t=M(I(s.text,300,"제목").replace(/\s*\n\s*/g," ").replace(/^\s*(?:\d{1,2}(?:-\d{1,2})?[.)]?|[①-⑳]|\(\d{1,2}\))\s*/,"").trim(),200);if(!t)continue;"절"===s.head?(a++,i=0,e.push("### "+a+". "+t,"")):(i++,e.push("#### "+String.fromCharCode(9312+Math.min(i,20)-1)+" "+t,""));continue}if(s.table){const n=s.table,a=(n.head||[]).map(et),i=(n.rows||[]).map((t=>(t||[]).map(et)));if(n.title=String(n.title||"").trim().replace(/^[<〈《\s]+|[>〉》\s]+$/g,""),n.source&&(n.source=String(n.source).trim().replace(/^[*※\s]*(?:자료|출처)\s*[::]\s*/,"")),i.length>LIM.rows||a.length>LIM.cols||i.some((t=>t.length>LIM.cols)))throw _(`표는 ${LIM.rows}줄·${LIM.cols}칸까지예요.`,413);if(!a.length||!i.length)continue;if(n.compare){e.push("```비교표 "+M(n.title||"",100).replace(/`/g,""),a.join(" | "),...i.map((t=>t.join(" | "))),"```",""),n.source&&e.push("* 자료: "+M(n.source,200),"");continue}const l=n.chart?"그래프 "+("line"===n.chart?"꺾은선":"pie"===n.chart?"원":"막대"):"표";e.push(`[${l}] ${M(n.title||"",100)}${n.unit?` (단위: ${M(n.unit,30)})`:""}`,a.join(" | "),...i.map((t=>t.join(" | "))),"");const c=r[t+1],p=n.source?M(n.source,200):"";if(n.chart&&!o&&c&&c.table&&c.table.chart&&(c.table.head||[]).length&&(c.table.rows||[]).length){o={s:p};continue}if(o){const t=o.s;o=null;const s=t&&p&&t!==p?t+" / "+p:t||p;s&&e.push("* 자료: "+s,"");continue}p&&e.push("* 자료: "+p,"");continue}if(s.diagram){const t=s.diagram,n=String(t.text||"").replace(/`/g,"").split("\n").slice(0,60).map((t=>t.slice(0,120))).filter((t=>t.trim()));if("비전"===t.kind){e.push("```비전체계 "+M(t.title||"",100).replace(/`/g,""),...n,"```","");continue}n.some((t=>/^\s*[□■○●◦\-–·]\s/.test(t)||/\s(?:→|->|⇒)\s/.test(t)))?e.push("```체계도 "+(M(t.title||"",100).replace(/`/g,"")||"체계도"),...n,"```",""):e.push("[체계도] "+M(t.title||"",100),...n,"");continue}const n=I(s.text,4e3,"항목 글").replace(/\s*\n\s*/g," ").trim();if(!n)continue;const l=Q.includes(s.mark)?s.mark:"";if(l){const t=new RegExp("^\\s*"+l.replace(/[-*]/g,"\\$&")+"\\s+");if(t.test(n)){const s=n.replace(t,"").trim();if(s){e.push(l+" "+s,"");continue}}}l||!/^[◆◈◇]/.test(n)?e.push(l?l+" "+n:n,""):e.push("> "+n,"")}})),e.join("\n")}const st=t=>(String(t).match(/\d/g)||[]).join(""),nt=t=>{const e=String(t).replace(/\r\n?/g,"\n").split("\n");if(e.length>LIM.lines)throw _(`줄이 너무 많아요(${LIM.lines.toLocaleString()}줄까지).`,413);return e},rt=/^\s*(?:[□■◆◇○●◦ㆍ·•\-–—※*▶▷►▸]|\d{1,2}[.)]|[가-하][.)]\s|\(\d{1,2}\)|\([가-하]\)|[①-⑳]|#{1,6}\s|\||[ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ]\.?\s|<)/,at=/[가-힣][.!?。]["'」』”’)\]]*$|[.!?。]["'」』”’]$/,it=/^(?:적|성|화|률|율|별|용|형|들|상|씩|째|님|간)(?=\s|$|[,.)])/,ot=/^(?:등|및|수|것|때|중|후|전|간|내|외|약|각|총|또는|그리고|이후|또한|모두|대한|위한|통해|따라|관한|위해)(?=[을를은는이가의에로도과와만]|\s|$|[,.)])/,lt=/(?:는|은|을|를|이|가|의|에|도|로|와|과|만|서|고|며|면|해|한|할|된|될|던|인|게|지|듯|나|든|라|요|다|음|함|임|됨|까|데|께|뿐|여|며)$/;export function unwrapLines(t){const e=String(t).replace(/\r\n?/g,"\n").split("\n"),s=e.map((t=>t.trim().length)).filter((t=>t>0)).sort(((t,e)=>e-t)),n=s.length>=2?s[1]:s[0]||0,r=[];if(n<20)return{text:e.join("\n"),joins:r};const a=[];for(let t=0;t<e.length;t++){let s=e[t];for(;t+1<e.length;){const a=s.replace(/\s+$/,""),i=e[t+1].trim(),o=a.split("\n").pop()||"";if(!a.trim()||!i||o.trim().length<.7*n||rt.test(i)||at.test(a))break;const l=a.slice(-1),c=i[0],p=(/(\S+)$/.exec(a)||["",""])[1],h=/[가-힣]/.test(l),u=/[가-힣]/.test(c);let m;m=h&&u?!it.test(i)&&(!!ot.test(i)||(1!==(p.match(/[가-힣]/g)||[]).length||!/^[가-힣]$/.test(p))&<.test(p)):!(/\d/.test(l)&&/\d/.test(c)),r.push({at:(p+(m?" ":"")+(/^\S+/.exec(i)||[""])[0]).slice(0,40),space:m}),s=a+(m?" ":"")+i,t++}a.push(s)}return{text:a.join("\n"),joins:r}}const ct=(t,e)=>a("gaejo","EbGaejo.guard",[t,e]),pt=(t,e)=>l((()=>ct(t,e)));export function trialMoreTools(s,n,i,l){const p=(t,e,s,n,r)=>l.reg(t,{title:e,description:s,inputSchema:n},(async t=>{try{if(l.paused())throw l.userErr(new Error("잠시 멈춘 열쇠입니다."));l.rate();const e=await j(o(Math.max(1,Math.min(LIM.rules,+process.env.TRIAL_RULE_BUDGET_MS||LIM.rules)),(()=>r(t||{}))));if(e&&Array.isArray(e.content))return e;const s="string"==typeof e?e:JSON.stringify(e,null,1);if(s.length>LIM.outText)throw _("결과가 너무 커요 — 글을 나눠 다시 해 주세요.",413);return l.T(s)}catch(t){return l.fail(t)}})),k=(t,e,s="글")=>{const n=I(t.text,e,s);if(!n.trim())throw _(`${s}${josa(s,"을","를")} text 로 주세요.`);if($(n))throw _(S,403);return n},v=(t,e,s)=>({content:[{type:"text",text:JSON.stringify({...e,file:s},null,1)},{type:"image",data:t.toString("base64"),mimeType:"image/png"}]}),L=r.object({head:r.enum(["절","소제목"]).optional().describe("장 안의 절(「1 │ 제목」 번호 상자)·소제목(「① 제목」) — text 가 제목, 번호는 자동"),mark:r.enum(["□","○","-","·","*","※",""]).optional().describe("개조식 기호(□ 큰 항목 ○ 그 아래 - 더 아래 · 참고 줄 * 주석 ※)"),text:r.string().optional().describe("항목 글 — ~함·~임 끝맺음, **굵게** 가능, 한 줄 한 생각"),table:r.object({title:r.string().optional(),unit:r.string().optional(),head:r.array(r.string()),rows:r.array(r.array(r.string())),source:r.string().optional(),chart:r.enum(["bar","line","pie"]).optional().describe("주면 표 대신 그 숫자로 그래프 그림"),compare:r.boolean().optional().describe("현행 → 개선(안) 비교표로(head 예: 구분 | 현행 | 개선(안), 칸 안 「 / 」는 줄바꿈)")}).optional(),diagram:r.object({title:r.string().optional(),kind:r.enum(["비전"]).optional().describe("비전 체계도 한 장 — text 를 「비전: …」「목표: 가 | 나 | 다」「전략: 이름 > 과제 · 과제」(전략 줄 여럿, 과제 사이는 띄어 쓴 「 · 」나 쉼표) 줄로"),text:r.string().describe("□ ○ - 글머리 줄 또는 「가 → 나 → 다」(kind 비전이면 위 꼴)")}).optional()});p("on_write_gov","On 공문서 쓰기 — 보고서·계획서·결과보고서·보도자료 한글 문서","보고서·계획서·결과보고서·보도자료·기안문·공고문처럼 공문서 꼴 한글 문서를 만드는 도구 — 마크다운이나 짜임(structure)을 정부 공문서 꼴 한글 파일(HWPX)로 만든다(꾸밈 없는 일반 문서는 on_write). 글 없는 글머리 줄(「- 」만 있는 줄)은 넣지 않고, markdown 원고에서 장 제목 아래 갈래가 마크다운 글머리(-)만 쓰면 깊이대로 ○ → - → · 단계로 옮긴다(□○ 기호를 쓴 갈래는 그대로). On 문서 화면 「AI 새 문서」와 같은 엔진(AI 없음). 휴먼명조·HY헤드라인M, 장 제목 막대, 표 캡션·단위, 계획서·결과보고서는 표지·목차. 원고에 없는 사실·숫자는 넣지 않는다. 원고는 markdown 이나 structure 로 받는다 — structure 는 장(chapters 의 title)마다 items(head 절·소제목, mark □ ○ - · * ※, text, table, diagram)를 칸으로 주는 꼴이라 장·절·그래프 자리가 칸 그대로 들어가고, markdown 은 아래 【markdown】 표기로 같은 꼴이 된다. 【꼴】 보고서·계획서·결과보고서는 응급의료 기본계획(보건복지부) 꼴: 장(chapters 의 title — 번호 없이, Ⅰ. Ⅱ. 는 자동) → 절(items 의 head 「절」 — 번호 상자 「1 │ 제목」) → 소제목(head 「소제목」 — 「① 제목」) → □ → ○ → - → ·(참고·근거 숫자 줄). 줄 글은 「~함」「~임」 같은 끝맺음으로 끝나며, 명사로 끝난 줄(「…지원」)은 결재 전 점검(on_check_text)에서 「공문 형식」으로 잡힌다. 이 꼴은 ○ 마다 그 아래 - 가 1~3줄(자료의 숫자·주체·기간·대상·비율·견줌)로 촘촘하고, ○ 되풀이·말만 바꾼 줄·자료끼리 이어 붙인 해석(「~에 대응함」「~가 기준임」)이 없다. 한 줄은 빈칸 포함 약 40자 — 줄 끝에 1~2글자만 넘어가면 엔진이 그 문단만 낱말 사이 빈칸을 먼저, 모자라면 자간을 조금 줄여 한 줄에 넣고, 3글자 넘게 넘어가 둘째 줄이 짧게 남으면 결과의 short_last_lines 에 잡힌다. 그러면 원고·자료에 이미 있는 숫자·주체·기간·대상을 그 문장에 보태 둘째 줄까지 거의 채우거나(80자 안팎), 보탤 사실이 없으면 줄여 한 줄로 고쳐 다시 만든다(자료에 없는 말·숫자는 지어내지 않음). 장 첫머리 핵심 요약은 mark 없이 text 를 「◆ …」로 쓴 3~4줄(120~160자). 낱말 뒤 *(예: KTAS*)와 그 ○ 묶음 아래 mark 「*」 줄은 주석이 된다. table.compare 는 현행 → 개선(안) 비교표, diagram.kind 「비전」은 비전·목표·전략 한 장 체계도. chapters 하나에 title 없이 items 만 주면 장 막대 없이 □○ 로 시작하는 1쪽 보고자료(style 보고서). meta 의 기관·날짜·부제는 표지·머리에 들어가고, 기관이 없는 계획서·결과보고서 표지에는 기관 줄이 없다. 【그래프·체계도】 table.chart(비교 bar·추이 line·구성비 pie)는 그 표 숫자로 그래프 그림을, items 의 diagram 은 추진체계·절차·단계·역할 나눔 체계도를 넣는다. items 에 잇달아(사이에 다른 항목 없이) 둔 그래프 둘은 한 줄에 반 폭씩 나란히 들어간다 — 기본계획 꼴 문서는 비교·추이·구성비 숫자가 셋 이상인 자료를 같은 절의 그래프 두 개로 보이고 자세한 숫자는 표로 둔다. 그림은 준 숫자·낱말로만 그린다. 【markdown】 첫 줄 「# 제목」, 「## Ⅰ. 장 제목」, 「### 1. 절 제목」(번호 상자 — 번호 없는 ### 는 밑줄 제목), 「#### ① 소제목」, 장 첫머리 요약 「> ◆ …」. 「---」로 감싼 「기관: ○○시」 「날짜: 2026. 11.」 「부제: …」 머리말은 글 맨 위(「# 제목」보다 앞)에 둘 때 머리말로 읽힌다 — 「# 제목」 다음에 두면 장 제목으로 찍힌다. 표는 마크다운 표(위에 「< 표 제목 >」 줄·「(단위: 명)」 줄), 그래프는 「```그래프 막대 제목」(꺾은선·원) 울타리 안에 마크다운 표 — 연도가 머리 칸인 가로 표도 됨(「[그래프 막대] 제목」 묶음도 같음). 숫자·이름은 원문 그대로 남는다(천 단위 쉼표는 넣어도 됨). 【결과】 check.same 은 만든 파일을 다시 읽어 견준 결과(false 면 잃은 글이 있음 — check.examples), quality 는 고칠 곳 목록, short_last_lines 는 둘째 줄이 짧게 남은 문장(고쳐 다시 만든다 — 위 「한 줄은 약 40자」 참고), preview 1~2 는 앞 쪽 그림. tell_user 는 사용자에게 그대로 옮겨 전할 쉬운 말(만든 꼴·쪽 수·저절로 맞춘 것·채울 자리·확인할 곳), number_check 는 표 합계·글 속 비율·증감 셈이 맞지 않아 보이는 곳, spell_check 는 맞춤법·날짜·금액에서 볼 곳 — 문서는 고치지 않았으니 결과를 건넬 때 tell_user 와 함께 그대로 알린다. Make a Korean government-style HWPX (report/plan/press release/draft/notice) from markdown or a structure. 마크다운 20만 자·장 40·장마다 항목 400·표 200줄×20칸까지.",{style:r.enum(["보고서","계획서","결과보고서","보도자료","기안문","공고문"]).describe("공문서 꼴"),title:r.string().optional().describe("문서 제목"),markdown:r.string().optional().describe("공문서 꼴 원고 마크다운 — 「## Ⅰ. 장 제목」·「### 1. 절 제목」·「#### ① 소제목」·□ ○ - 줄·마크다운 표·그래프는 「```그래프 막대 제목」 울타리 안에 마크다운 표(「[그래프 막대] 제목」 묶음도 같음)·체계도는 「```체계도 제목」"),structure:r.object({title:r.string().optional().describe("문서 제목(표지·머리 제목)"),meta:r.record(r.string(),r.string()).optional().describe("쓸 수 있는 이름: 부제·날짜·기관·수신·경유·보도시점·배포·담당부서·담당자·연락처·공고번호·발신명의·시행·접수·전화·메일·홈페이지 (그 밖의 이름은 무시하고 알려 줌). 기관 예: 「○○시 보건정책과」"),chapters:r.array(r.object({title:r.string().optional().describe("장 제목 — 번호 없이(Ⅰ. 은 자동). 없으면 장 막대 없이 items 만"),items:r.array(L).optional()})).optional()}).optional().describe("markdown 대신 짜임으로 — { title, meta: { 기관, 날짜, 부제 … }, chapters: [{ title, items: [{ head?, mark?, text?, table?, diagram? }] }] }"),preview:r.number().int().min(0).max(2).optional().describe("쪽 몇 장을 그림으로 함께(0~2, 기본 0) — 표지·목차는 건너뛰고 본문 첫 쪽부터, 2장이면 그래프가 든 쪽을 먼저"),preview_pages:r.string().max(20).optional().describe("그림으로 볼 쪽을 직접(「3-4」·「2,5」 꼴, 2쪽까지) — preview 보다 먼저")},(async t=>{const e=t.structure?structureToText(t.structure):((t,e)=>["보고서","계획서","결과보고서","보도자료"].includes(t)?w(e):e)(t.style,I(t.markdown,LIM.md,"마크다운"));if(!e.trim())throw _("만들 글(markdown 또는 structure)을 주세요.");if(e.length>LIM.md)throw _("글이 너무 길어요(20만 자까지).",413);{const t=h(e);if(t)throw _(t,413)}if($(e))throw _(S,403);const s=t.structure&&t.structure.title,n=((e.match(/^#\s+(.+)$/m)||[])[1]||"").trim(),r=await u(e,{title:M(s||t.title||"",120),style:t.style});l.charge("write_gov");const a=E(t.title||s||r.title||n,"공문서"),i={style:t.style,pages:r.pages,check:r.check,file:l.keep(Buffer.from(r.buf),a+".hwpx","application/octet-stream")},o=[];if((t.structure?!(!t.structure.meta||!String(t.structure.meta["기관"]||"").trim()):/^기관\s*:\s*\S/m.test(e.slice(0,1200)))||"계획서"!==t.style&&"결과보고서"!==t.style||o.push("기관을 주지 않아 표지에 기관 줄을 넣지 않았어요 — structure.meta.기관(또는 markdown 머리말 「기관: ○○시」)에 기관 이름을 넣어 다시 만들면 표지 아래에 들어갑니다."),"공고문"===t.style||"기안문"===t.style){const s=s=>t.structure?String((t.structure.meta||{})[s]||"").trim():((new RegExp("^"+s+"\\s*:\\s*(\\S.*)$","m").exec(e.slice(0,1500))||[])[1]||"").trim(),n=[];"공고문"===t.style?(s("공고번호")||n.push("공고번호(머리 줄 「제○○○○-○○호」)"),s("기관")||s("발신명의")||n.push("기관·발신명의(「○○부 공고」·「○○부장관」)"),s("날짜")||n.push("날짜(끝 「2026. . .」)")):s("발신명의")||s("기관")||/^\s*내부\s*결재\s*$/.test(s("수신"))||n.push("발신명의(「○○기관장」)"),n.length&&(i.placeholders=n,o.push(`주지 않아 「○○」·빈칸으로 둔 자리: ${n.join(", ")} — structure.meta(또는 markdown 머리말)에 넣어 다시 만들거나, 게시·발송 전에 채워 주세요.`))}if(t.structure&&t.structure.meta){const e=Object.keys(t.structure.meta).filter((t=>!tt.includes(t)));e.length&&o.push("meta 이름을 몰라 무시한 것: "+e.join(", ")+" (쓸 수 있는 이름: "+tt.join("·")+")")}r.check&&!1===r.check.same&&o.push("원고의 글·숫자 일부가 결과에서 빠졌어요 — check.examples 를 보고 고쳐 다시 만들어 주세요.");{const t=(r.stats&&Array.isArray(r.stats.chartNotes)?r.stats.chartNotes:[]).slice(0,10);t.length&&(i.charts_as_table=t,o.push(`그래프 ${t.length}개는 그대로 그릴 수 없어 표로 넣었어요(charts_as_table — ${t.map((t=>(t.title?"「"+M(t.title,24)+"」 ":"")+t.why)).join(" / ")}). 그래프로 넣으려면 표를 고쳐 다시 만들고, 아니면 그대로 두면 돼요.`))}if(t.structure&&["계획서","보고서","결과보고서"].includes(t.style)){const e=qualityTips(t.structure);e.length&&(i.quality=e,o.push("기본계획 수준으로 더 알차게 하려면(quality): "+e.length+"가지 — 고쳐 다시 만들어 주세요."))}if(Array.isArray(r.gaps)&&r.gaps.length){i.page_gaps=r.gaps.slice(0,8);const t=r.gaps.slice(0,3).map((t=>`${t.page}쪽 아래 ${t.empty_pct}%`)).join("·"),e=r.gaps[0].next_kind,s=(e.charCodeAt(e.length-1)-44032)%28?"이":"가";(i.quality||(i.quality=[])).push(`쪽 아래가 비었어요(${t}) — 다음 쪽 맨 위 ${e}(「${M(r.gaps[0].next_top,20)}」)${s} 남은 자리에 안 들어가 통째로 넘어갔어요. 그 앞 글을 자료의 근거로 보태 쪽을 채우거나, 그래프면 같은 절의 다른 그래프와 짝지어(반 폭) 두세요(page_gaps).`),o.some((t=>/quality/.test(t)))||o.push("쪽 채움(quality·page_gaps)을 보고 고쳐 다시 만들어 주세요.")}r.tails&&r.tails.length&&(i.short_last_lines=r.tails.slice(0,15),o.push(`두 줄로 꺾였는데 마지막 줄이 짧게 끝난 문장이 ${r.tails.length}곳 있어요(short_last_lines) — 고쳐 다시 만들어 주세요. 마지막 줄이 3글자 이상(prefer add)이면 add(빈칸 빼고 더 쓸 글자 수)만큼 원고·자료에 이미 있는 숫자·주체·기간·대상을 그 문장에 보태 두 줄을 거의 채우고(자료에 없는 말·숫자는 지어내지 않음), 보탤 사실이 없으면 cut 글자만큼 줄여 한 줄로. 1~2글자(prefer cut)는 엔진이 빈칸·자간을 한도까지 줄여도 한컴에서 안전하게 안 들어간 것이라 cut 글자만큼 줄여(낱말을 짧은 말로) 한 줄로. line_chars 는 한 줄에 드는 글자 수(빈칸 뺀), last_pct 는 마지막 줄이 앞 줄의 몇 %를 채웠는지예요(text 끝 「…」은 결과 목록에서만 줄인 것 — 문서 글은 온전함).`));let c=[];if(t.preview_pages)for(const e of String(t.preview_pages).split(",")){const t=/^\s*(\d{1,3})\s*(?:-\s*(\d{1,3}))?\s*$/.exec(e);if(!t)throw _("preview_pages 는 「3-4」·「2,5」 꼴로 주세요.");for(let e=+t[1];e<=(t[2]?+t[2]:+t[1])&&c.length<2;e++)e>=1&&(!r.pages||e<=r.pages)&&c.push(e)}else{const e=Math.max(0,Math.min(2,0|t.preview));if(e){const t=Math.min(Math.max(1,(r.front||0)+1),r.pages||1);if(c.push(t),e>1){const e=(r.chartPages||[]).find((e=>e!==t))||t+1;(!r.pages||e<=r.pages)&&c.push(e)}c.sort(((t,e)=>t-e))}}c.length&&(i.preview_pages=c,(r.front||0)>0&&!t.preview_pages&&o.push(`미리보기는 표지·목차(${r.front}쪽)를 건너뛰고 ${c.join("·")}쪽을 보여요 — 다른 쪽은 preview_pages(「3-4」 꼴)로.`));try{const s=await x(e,r,t.style,{placeholders:i.placeholders});Object.assign(i,s),(s.number_check||s.spell_check)&&o.push("셈·맞춤법에서 확인할 곳이 있어요(number_check·spell_check) — 문서는 고치지 않았으니 자료와 맞대 보고, 틀렸으면 고쳐 다시 만들거나 사용자에게 알려 주세요.")}catch{}if(o.length&&(i.notes=o),!c.length)return i;let p=[];try{p=(await m(Buffer.from(r.buf),c,1,c.length)).images||[]}catch{p=[]}return{content:[{type:"text",text:JSON.stringify(i,null,1)},...p.map((t=>({type:"image",data:Buffer.from(t.png).toString("base64"),mimeType:"image/png"})))]}})),p("on_list_templates","예시 양식 목록","On 문서 화면 「양식으로 쓰기」의 예시 양식 66종(계획·보고·행사·공고·보도자료 등) 목록 — 번호(g01 꼴)·갈래·이름·꼴·쪽 수·장 제목. on_fill_template 에 넣을 양식을 고를 때 쓴다. List the 66 example government templates for on_fill_template. query 로 거름.",{query:r.string().max(60).optional().describe("찾을 말(이름·갈래·설명)")},(async t=>{const e=D(t.query||""),s=N(),n=s.items.filter((t=>!e||[t.name,t.group,t.kind,t.desc,t.style,t.variant].some((t=>D(t).includes(e))))).map((t=>({id:t.id,group:t.group,name:t.name,style:t.style,kind:t.kind,pages:t.pages,desc:t.desc,chapters:F(t)})));return{total:s.items.length,shown:n.length,items:n}}));const A=r.object({file_base64:r.string(),file_name:r.string().max(200).optional()});p("on_fill_template","AI 없이 양식 채우기","예시 양식(on_list_templates 의 번호) 하나를 열어, 주어진 자료(글·파일)의 문단·표를 낱말로 맞는 장 끝에 넣고 「일시: …」 같은 항목은 같은 이름 칸에 넣은 HWPX 를 만든다 — On 문서 화면 「AI 없이 채우기」와 같은 규칙. 자료의 장 제목은 「## 제목」·「□ 제목」·「Ⅰ. 제목」 줄로 준다. 자리가 분명하지 않은 덩이는 넣지 않고 목록(unplaced)으로 돌려준다(틀린 자리보다 안 넣는 것이 낫다). 자료를 넣은 장의 예시 글·표·그래프는 빼고(examples: keep 이면 그대로), 남은 예시 글은 examples_left 로 알린다. 제목·날짜·기관은 title·date·org 로 바꾼다. 채운 뒤 넣은 숫자가 문서에 그대로 있는지 다시 읽어 대조한다. Fill an example template with given material, rule-based (no AI). 자료 글 30만 자·파일 4개(하나 25MB)·덩이 400개까지.",{template:r.string().max(60).describe("양식 번호(g01 꼴) 또는 이름"),material_text:r.string().optional().describe("넣을 자료 글(마크다운·개조식·마크다운 표) — 장 제목은 「## 제목」이나 「□ 제목」 줄, 칸에 넣을 값은 「성명: 홍길동」 줄"),material_name:r.string().max(60).optional().describe("자료 이름(출처 표시에 씀, 기본 「자료」)"),files:r.array(A).max(LIM.files).optional().describe("자료 파일(한글·PDF·워드·엑셀·파워포인트) base64 — 글자 인식은 하지 않음"),source:r.enum(["note","line","none"]).optional().describe("출처 표시 — note 각주(기본, 자료마다 한 번) · line 아래 줄 · none"),unplaced:r.enum(["list","end"]).optional().describe("자리를 못 정한 덩이 — list 목록으로만(기본) · end 문서 끝에 넣기"),fields:r.boolean().optional().describe("「항목: 값」 칸 채우기(기본 켬)"),examples:r.enum(["drop","keep"]).optional().describe("자료를 넣은 장의 예시 글·표·그래프 — drop 빼기(기본, 칸을 채운 표는 남기고 그 표에서 못 채운 예시 값은 비움) · keep 그대로"),title:r.string().max(120).optional().describe("문서 제목 — 양식의 예시 제목을 바꿈"),date:r.string().max(40).optional().describe("날짜(예: 2026. 2. 13.) — 양식 머리의 예시 날짜를 바꿈"),org:r.string().max(60).optional().describe("기관·부서(예: ○○시 ○○과) — 양식 머리의 예시 기관을 바꿈")},(async s=>{const{g:n,buf:r}=function(s){const n=N(),r=String(s||"").trim(),a=/^g\d{2,3}$/.test(r)?n.items.find((t=>t.id===r)):n.items.find((t=>D(t.name)===D(r)));if(!a||!/^g\d{2,3}\.hwpx$/.test(a.file))throw _("그런 양식이 없어요 — on_list_templates 로 양식 번호(g01 꼴)를 보세요.",404);return{g:a,buf:t.readFileSync(e.join(n.dir,a.file))}}(s.template),i=[];if(null!=s.material_text&&String(s.material_text).trim()){const t=I(s.material_text,LIM.material,"자료 글");if($(t))throw _(S,403);{const e=h(t);if(e)throw _(e,413)}i.push({name:M(s.material_name||"자료",60),text:materialHeads(t)})}const o=[];let c=i.reduce(((t,e)=>t+e.text.length),0);for(const t of s.files||[]){const e=String(t.file_base64||"").replace(/^data:[^,]*,/,"").replace(/\s+/g,""),s=M(t.file_name||"자료",60);if(e&&(/[^A-Za-z0-9+/=_-]/.test(e)||/=[^=]/.test(e))){o.push({name:s,why:"base64 로 풀지 못함(파일 내용을 base64 로 바꿔 넣어 주세요)"});continue}const n=Buffer.from(e,/[-_]/.test(e)?"base64url":"base64");if(!n.length){o.push({name:s,why:"비어 있음"});continue}if(n.length>26214400){o.push({name:s,why:"25MB 넘음"});continue}const r=await l.read(n,t.file_name||"",{ocr:!1}),a=String(r.markdown||"");if(c+=a.length,c>LIM.material)throw _("자료 글이 너무 길어요(합쳐 30만 자까지).",413);if(a.trim()){{const t=h(a);if(t)throw _(t,413)}i.push({name:s,text:materialHeads(a)})}else o.push({name:s,why:"글을 찾지 못함"})}if(!i.length)throw _("넣을 자료(material_text 또는 files)를 주세요.");const p=[],u=[];for(const t of i)for(const e of R(a("refdoc","EbRefDoc.parse",[t.text]))){const s={...e,from:t.name};u.length<5*LIM.blocks&&u.push(s),J(e)&&p.push(s)}if(p.length>LIM.blocks)throw _(`자료 덩이가 너무 많아요(${LIM.blocks}개까지) — 자료를 줄여 주세요.`,413);const m=new Map(p.map(((t,e)=>[t,e]))),f=await d("tplItems",{buf:r}),b=function(t){const e=new Map;for(const s of t.tables){const t=s.s+":"+s.p;e.has(t)||e.set(t,s)}return t.paras.map((t=>{const s=e.get(t.s+":"+t.p),n=s?s.cells.map((t=>t.lines.map((t=>String(t.c||"").replace(/▯/g,""))).join(" ").trim())):null;return{s:t.s,p:t.p,t:String(t.c||"").replace(/▯/g,""),cells:n}}))}(f),w=a("fill","EbFillMatch.heads",[b]),x=a("fill","EbFillMatch.suggest",[p.map((t=>({k:t.k,sec:t.sec,plain:(t.cap?t.cap+" ":"")+t.plain}))),w]),k=!1!==s.fields?a("fill","EbFillMatch.fieldPairs",[u]):[],y=!1!==s.fields?a("fill","EbFillMatch.fieldSlots",[f.paras,f.tables]):[],j=!1!==s.fields?a("fill","EbFillMatch.matchFields",[k,y]):[],v=new Set(j.filter((t=>null!=t.pair.b&&u[t.pair.b]&&"p"===u[t.pair.b].k)).map((t=>m.get(u[t.pair.b]))).filter((t=>null!=t))),L=x.filter((t=>!v.has(t.b))),A=[],C=s.source||"note";j.forEach(((t,e)=>{const s=t.slot.at;A.push(s.cel?{k:"cell",id:"f"+e,s:s.s,p:s.p,tk:s.cel.tk,cell:s.cel.cell,cp:s.cel.cp,off:s.off,len:s.len,from:s.from,to:t.pair.value,nums:s.from}:{k:"text",id:"f"+e,s:s.s,p:s.p,off:s.off,len:s.len,from:s.from,to:t.pair.value,nums:s.from})}));const P=new Map;for(const t of L)t.h>=0&&(P.get(t.h)||P.set(t.h,[]).get(t.h)).push(t.b);const T=L.filter((t=>t.h<0)),O=new Map;for(const t of f.tables){const e=t.s+":"+t.p;(O.get(e)||O.set(e,[]).get(e)).push(t)}const B=t=>{const e=f.paras[t];return[String(e.c||"").replace(/▯/g," "),...(O.get(e.s+":"+e.p)||[]).flatMap((t=>t.cells.flatMap((t=>t.lines.map((t=>String(t.c||"")))))))].join("\n")},F=new Set(j.map((t=>t.slot.at.s+":"+t.slot.at.p))),U=t=>!!t&&(/^\s*[<〈].*[>〉]\s*$/.test(t.c)||/^\s*[((]\s*단위/.test(t.c)),z=new Set,Q="keep"!==s.examples;if(Q)for(const t of P.keys()){const e=w[t];for(let s=e.at+1;s<=e.end&&s<f.paras.length;s++){const e=f.paras[s];if(!e||0===e.p||z.has(s))continue;if(F.has(e.s+":"+e.p)||w.some(((e,n)=>n!==t&&e.at===s&&P.has(n))))continue;const n=f.paras[s+1],r=f.paras[s+2];U(e)&&(n&&F.has(n.s+":"+n.p)||U(n)&&r&&F.has(r.s+":"+r.p))||(z.add(s),A.push({k:"drop",id:"d"+s,s:e.s,p:e.p,from:e.c,nums:B(s)}))}}const tt=[];if(Q){const t=new Set(j.map((t=>JSON.stringify(t.slot.at)))),e=new Set(j.filter((t=>t.slot.at.cel)).map((t=>t.slot.at.s+":"+t.slot.at.p+":"+t.slot.at.cel.tk)));y.forEach(((s,n)=>{const r=s.at;r.cel&&!t.has(JSON.stringify(r))&&e.has(r.s+":"+r.p+":"+r.cel.tk)&&(a("fill","EbFillMatch.holeVal",[s.cur])||(A.push({k:"cell",id:"c"+n,s:r.s,p:r.p,tk:r.cel.tk,cell:r.cel.cell,cp:r.cel.cp,off:0,len:r.len,from:r.from,to:"",nums:r.from}),tt.push({label:s.label,was:M(s.cur,40)})))}))}const et=w.length?w[0].at:b.length,st=[],nt=/(?:19|20)\d{2}\s*\.\s*\d{1,2}\s*\.(?:\s*\d{1,2}\s*\.)?/,rt=[];for(let t=0;t<Math.min(et,f.paras.length);t++){const e=f.paras[t],s=String(e.c||"");s.replace(/▯/g,"").trim()&&!s.includes("▯")&&rt.push({k:t,kind:"p",text:s,at:{s:e.s,p:e.p}});for(const s of O.get(e.s+":"+e.p)||[])if(1===s.cells.length){const n=(s.cells[0].lines||[]).filter((t=>String(t.c||"").trim()));1===n.length&&rt.push({k:t,kind:"cell",text:String(n[0].c),at:{s:e.s,p:e.p,cel:n[0].cel}})}}const at=(t,e,s,n,r)=>"cell"===t.kind?{k:"cell",id:r,s:t.at.s,p:t.at.p,tk:t.at.cel.tk,cell:t.at.cel.cell,cp:t.at.cel.cp,off:e,len:s,from:t.text.substr(e,s),to:n,nums:t.text.substr(e,s)}:{k:"text",id:r,s:t.at.s,p:t.at.p,off:e,len:s,from:t.text.substr(e,s),to:n,nums:t.text.substr(e,s)},it=rt.find((t=>!nt.test(t.text)&&t.text.replace(/\s/g,"").length>=4)),ot=rt.find((t=>nt.test(t.text))),lt=[];if(it)if(s.title&&String(s.title).trim()){const t=M(s.title,120);A.push(at(it,0,it.text.length,t,"ht")),lt.push(t)}else st.push({chapter:"머리(제목)",text:M(it.text,60),hint:"title 을 주면 바꿔요"});if(ot){const t=nt.exec(ot.text),e=ot.text.slice(t.index+t[0].length),n=t.index+t[0].length+(e.length-e.replace(/^\s+/,"").length),r=e.trim();if(r&&s.org&&String(s.org).trim()){const t=M(s.org,60);A.push(at(ot,n,r.length,t,"ho")),lt.push(t)}else r&&st.push({chapter:"머리(기관)",text:M(r,40),hint:"org 를 주면 바꿔요"});if(s.date&&String(s.date).trim()){const e=M(s.date,40);A.push(at(ot,t.index,t[0].length,e,"hd")),lt.push(e)}else st.push({chapter:"머리(날짜)",text:t[0],hint:"date 를 주면 바꿔요"})}const ct=[...P].sort(((t,e)=>w[t[0]].at-w[e[0]].at)).flatMap((([,t])=>[...t].sort(((t,e)=>t-e)))).concat("end"===s.unplaced?T.map((t=>t.b)):[]),pt=new Map;for(const t of ct)pt.has(p[t].from)||pt.set(p[t].from,t);const ht=t=>{const e=p[t],s=[e].concat(e.with||[]).sort(((t,e)=>t.i-e.i));let n=s.map((t=>function(t,e){if("t"===t.k)return function(t,e){const s="border:0.5pt solid #000000;padding:1pt 3pt;vertical-align:middle;",n=s+"background-color:#E8E8E8;";let r='<table border="1" cellspacing="0" cellpadding="2" style="border-collapse:collapse;width:100%">';return t.rows.forEach(((a,i)=>{const o=i<(t.head||0);r+="<tr>"+a.map((t=>{const r=String(t.t||"").split(/<br\s*\/?>/i),a=G(t.t),i=o?"center":H.test(a)&&a?"right":a.length<=8?"center":"left",l=(r.length?r:[""]).map((s=>X(q(G(s)),i,o||t.th,e))).join("");return"<td"+(t.rs>1?' rowspan="'+t.rs+'"':"")+(t.cs>1?' colspan="'+t.cs+'"':"")+' style="'+(o?n:s)+'">'+l+"</td>"})).join("")+"</tr>"})),r+"</table>"}(t,e);if("h"===t.k)return"<p><b>"+q(t.text)+"</b></p>";if(t.cap){const e=G(t.text);return'<p style="text-align:center"><b>'+V(/^</.test(e)?e:"< "+e+" >")+"</b></p>"}return t.note?'<p style="text-align:'+(/^\(?\s*단위/.test(G(t.text))?"right":"left")+'"><span style="font-size:'+Math.max(8,e-1)+'pt">'+q(t.text)+"</span></p>":"<p>"+q(t.text)+"</p>"}(t,11))).join("");const r=s.some((t=>"t"!==t.k)),a=s.some((t=>"t"===t.k||t.cap||t.note)),i="note"!==C||r?C:"line";"line"===i&&(n+='<p><span style="font-size:'+Math.max(8,10)+'pt">자료: '+V(e.from)+"</span></p>");const o="p"===e.k?(/^\s*([□○\-·※*])\s/.exec(G(e.text))||[])[1]:null;return{id:"b"+t,html:n,own:a||"line"===i,note:"note"===i&&pt.get(e.from)===t?"자료: "+e.from:null,...o?{mark:o}:{}}};for(const[t,e]of P){const s=b[w[t].end+1];A.push({k:"paste",id:"h"+t,at:s?{s:s.s,p:s.p}:null,blocks:e.sort(((t,e)=>t-e)).map(ht)})}"end"===s.unplaced&&T.length&&A.push({k:"paste",id:"end",at:null,blocks:T.map((t=>ht(t.b)))});const ut=t=>"paste"!==t.k||t.at?["paste"===t.k?t.at.s:t.s,"paste"===t.k?t.at.p:t.p,"paste"===t.k?1:0,t.off||0]:[-1,-1,1,0];A.sort(((t,e)=>{const s=ut(t),n=ut(e);return n[0]-s[0]||n[1]-s[1]||s[2]-n[2]||n[3]-s[3]}));const mt=[...P.values()].flat().concat("end"===s.unplaced?T.map((t=>t.b)):[]),ft=new Set(j.map((t=>t.pair.key))),gt=new Set(mt),dt=k.filter(((t,e,s)=>!ft.has(t.key)&&s.findIndex((e=>e.key===t.key))===e&&!gt.has(m.get(u[t.b])))),bt=A.map((({nums:t,...e})=>e));if(!bt.length&&!dt.length)return{template:n.id,file:null,filled:{chapters:[],fields:[]},unplaced:T.map((t=>({from:p[t.b].from,text:M(p[t.b].plain,80),why:W(t.why,p[t.b])}))),note:"맞는 장·칸을 찾은 자료가 없어 넣지 않았어요."};const wt=bt.length?await d("tplEdit",{buf:r,ops:bt}):{buf:r,done:{},skipped:[],pages:1};let xt=Buffer.from(wt.buf);const kt=[],yt=[];if(dt.length){let t=null;try{t=await g(xt,Object.fromEntries(dt.map((t=>[t.label,t.value]))),{})}catch{t=null}const e=new Set((t&&t.filled||[]).map((t=>String(t.key))));for(const t of dt)e.has(t.label)?kt.push(t):yt.push(t);t&&t.buf&&kt.length&&(xt=Buffer.from(t.buf))}const _t=await d("tplItems",{buf:xt}),St=K(Y(_t)),$t=await async function(t,e){if(Z.has(t))return Z.get(t);const s=K(Y(await d("tplItems",{buf:e})));return Z.size>80&&(Z=new Map),Z.set(t,s),s}(n.id,r),jt=new Set(wt.skipped||[]),It=new Map($t);for(const t of A)if(null!=t.nums&&!jt.has(t.id))for(const[e,s]of K(t.nums))It.set(e,(It.get(e)||0)-s);for(const[t,e]of It)St.set(t,(St.get(t)||0)-e);const Mt=[],Et=t=>{for(const[e,s]of K(t)){const t=St.get(e)||0;t<s&&Mt.push(e),St.set(e,t-s)}};for(const t of mt.filter((t=>!jt.has("b"+t)))){const e=p[t];for(const t of[e].concat(e.with||[]))Et("t"===t.k?t.rows.map((t=>t.map((t=>G(t.t))).join(" "))).join(" "):G(t.text))}for(const t of j.filter(((t,e)=>!jt.has("f"+e))))Et(t.pair.value);for(const t of lt)Et(t);for(const t of kt)Et(t.value);if(Mt.length&&process.env.MCPX_DEBUG&&console.warn("[mcpx 대조]",JSON.stringify({lost:Mt,fm:j.map((t=>[t.slot.at.from,t.pair.value])),placed:mt.map((t=>p[t].plain.slice(0,60))),skip:[...jt]})),Mt.length)throw _(`채운 문서에서 숫자 ${[...new Set(Mt)].slice(0,10).join(", ")}를 다시 찾지 못해 결과를 내지 않았어요 — 자료를 나눠 다시 해 주세요.`,422);if(!(wt.pages>0))throw _("채운 문서를 다시 열지 못했어요.",422);l.charge("fill_template");const vt=w.map((t=>t.top>=0?w[t.top]:t)),Lt=t=>(vt[t].no?vt[t].no+". ":"")+vt[t].key,At=new Set(w.map((t=>t.at))),Ct=new Set(f.paras.map(((t,e)=>F.has(t.s+":"+t.p)?e:-1)).filter((t=>t>=0))),Pt=[];w.forEach(((t,e)=>{if(t.top>=0&&t.top!==e)return;const s=t.end;for(let n=t.at+1;n<=s&&n<f.paras.length;n++){if(z.has(n)||At.has(n)||Ct.has(n)||U(f.paras[n]))continue;const t=B(n).replace(/\s+/g," ").trim();t.replace(/[\s▯]/g,"").length<4||Pt.push({chapter:Lt(e),text:M(t,60),numbers:/\d/.test(t)})}})),Pt.sort(((t,e)=>(e.numbers?1:0)-(t.numbers?1:0)));const Tt=st.concat(Pt.slice(0,20).map((({numbers:t,...e})=>e))),Ot=[];if(Pt.length&&Ot.push(`예시 글 ${Pt.length}줄이 남아 있어요(examples_left — 자료를 넣지 않은 장${"keep"===s.examples?"·examples: keep":""}) — 결재 전에 지우거나 자료로 바꿔 주세요.`),st.length){const t=st.map((t=>t.chapter.replace(/^머리\(|\)$/g,""))).join("·"),e=(t.charCodeAt(t.length-1)-44032)%28?"이":"가";Ot.push(`머리의 예시 ${t}${e} 그대로예요 — title·date·org 를 주면 바꿔요.`)}tt.length&&Ot.push(`채운 표에서 자료에 없는 칸 ${tt.length}개(${tt.map((t=>t.label)).slice(0,6).join("·")})는 예시 값을 지우고 빈칸으로 뒀어요(cleared).`),z.size&&Ot.push(`자료를 넣은 장의 예시 문단·표 ${z.size}개를 뺐어요(그대로 두려면 examples: keep).`);const Bt=new Set(kt.map((t=>m.get(u[t.b]))).filter((t=>null!=t))),Nt="end"===s.unplaced?[]:T.filter((t=>!Bt.has(t.b))).slice(0,60).map((t=>({from:p[t.b].from,text:M(p[t.b].plain,80),why:W(t.why,p[t.b])})));for(const t of yt){const e=M(t.label+": "+t.value,80);Nt.some((t=>t.text===e))||Nt.push({from:t.from||"자료",text:e,why:"양식에서 같은 이름 칸을 찾지 못함 — on_fields 로 칸 이름을 보고 on_fill 로 넣을 수 있어요"})}return{template:n.id,name:n.name,pages:wt.pages,file:l.keep(xt,E(s.title||n.name,"양식")+"_채움.hwpx","application/octet-stream"),filled:{chapters:[...P].sort(((t,e)=>w[t[0]].at-w[e[0]].at)).map((([t,e])=>({chapter:Lt(t)+(vt[t]!==w[t]?" › "+w[t].key:""),blocks:e.length}))),fields:j.map((t=>({label:t.slot.label,value:M(t.pair.value,40),how:t.how}))).concat(kt.map((t=>({label:t.label,value:M(t.value,40),how:"서식 칸 찾기(on_fill 규칙)"}))))},unplaced:Nt,appended_at_end:"end"===s.unplaced?T.length:0,...tt.length?{cleared:tt}:{},examples_left:Tt,skipped_files:o,done:wt.done,check:{numbers:"넣은 숫자가 모두 문서에 있음"},...Ot.length?{notes:Ot}:{},note:"결재 전에 자료와 견줘 주세요"+(Tt.length?" — examples_left 의 예시 글은 실제 내용이 아니에요.":".")}})),p("on_table","글을 공문서 표로","「항목: 값」 줄·탭(엑셀 복사)·쉼표·「|」 줄·개조식·한 줄 나열(2022 120 / 2023 135)을 공문서 표로 나눈다 — On 문서 화면 「표로」와 같은 규칙. 같은 단위는 「(단위: …)」로 모으고 칸에는 원문 그대로. 표로 옮긴 뒤 원문 숫자를 하나도 잃지 않았는지 대조하고, 잃었으면 결과 대신 까닭을 낸다. 합계 줄이 맞지 않으면 알린다. 결과는 마크다운 표와 표 하나짜리 한글 파일(HWPX). Turn text into a government-style table. 글 2만 자·200줄·20칸까지.",{text:r.string().describe("표로 만들 글"),title:r.string().optional(),unit:r.string().optional(),source:r.string().optional().describe("자료(출처) 줄"),gather_units:r.boolean().optional().describe("같은 단위를 (단위: …)로 모으기(기본 켬)"),hwpx:r.boolean().optional().describe("한글 파일도(기본 켬)")},(async t=>{const e=k(t,LIM.tableText,"표로 만들 글"),{r:s,T:n}=((t,e={})=>{const s=a("draw","EbChart.toTable",[t]);if(s.error)throw _(s.error);const n=!1===e.gather?s:a("draw","EbChart.tidyUnits",[s]);return e.title&&(n.title=M(e.title,120)),null!=e.unit&&""!==e.unit&&(n.unit=M(e.unit,30)),e.source&&(n.src=M(e.source,200)),{r:s,T:n}})(e,{title:t.title,unit:t.unit,source:t.source,gather:t.gather_units}),r=[a("draw","EbChart.tableText",[n]),n.capNo||"",n.title,n.unit,n.src,...n.notes||[]].join("\n"),i=a("draw","EbChart.lost",[e,r,{commaSplit:"comma2"===s.how}]);if(i.length)throw _(`숫자 ${i.slice(0,12).join(", ")}가 표에 없어 만들지 않았어요 — 원문을 고쳐 주세요.`,422);const o=a("draw","EbChart.checkTotals",[n]),c=o.filter((t=>!t.ok)),p=t=>"| "+t.map((t=>String(t??"").replace(/\|/g,"/"))).join(" | ")+" |",m=[p(n.head),"|"+n.head.map((()=>"---")).join("|")+"|",...n.rows.map(p)].join("\n"),g=[n.title?`< ${n.title} >`:"",n.unit?`(단위: ${n.unit})`:"","",m,"",n.src?"* 자료: "+n.src:"",...(n.notes||[]).map((t=>String(t)))].filter(((t,e,s)=>""!==t||""!==s[e-1]&&e>0)).join("\n"),d={how:s.howName,rows:n.rows.length,cols:n.head.length,title:n.title||"",unit:n.unit||"",source:n.src||"",notes:n.notes||[],markdown:m,check:{numbers:a("draw","EbChart.numsOf",[e]).length,missing:[],totals:o.length?c.length?c.map((t=>`「${t.head}」 적힌 값 ${t.given} · 더한 값 ${t.sum}`)):"합계 검산 맞음":null},...s.synth?{note:"머리 칸 이름은 짐작한 것 — 확인해 주세요"}:{},...s.fail?{failed_lines:s.fail}:{}};if(!1!==t.hwpx){{const t=h(g);if(t)throw _(t,413)}const t=await u(g,{title:n.title||"표",style:"보고서"}),r=await f(Buffer.from(t.buf),"t.hwpx",{ocr:!1}),i=a("draw","EbChart.lost",[e,r.markdown||"",{commaSplit:"comma2"===s.how}]);if(i.length)throw _(`한글 파일에서 숫자 ${i.slice(0,12).join(", ")}를 다시 찾지 못해 결과를 내지 않았어요.`,422);d.file=l.keep(Buffer.from(t.buf),E(n.title,"표")+".hwpx","application/octet-stream")}return l.charge("table"),d}));const C=["teal","navy","gray","plum","brown"];p("on_chart","표 자료를 그래프 그림으로","표 자료(「항목 | 값」 줄·탭·한 줄 나열)를 공문서용 그래프 그림(PNG — 막대·꺾은선·원·가로막대, 색 5가지)으로 그린다 — On 문서 화면 「그래프로」와 같은 규칙·같은 그림. 종류를 주지 않으면 자료에 맞게 고른다. 그린 뒤 자료의 숫자가 모두 그림 글(값·항목·범례·※ 줄)과 제목·단위·자료 줄에 있는지, 막대 길이·점 높이·값 글 자리가 값과 맞는지 대조하고, 어긋나면 그림 대신 까닭을 낸다. Draw a chart PNG from table data with number/geometry checks. 자료 2만 자·그림 높이 제한.",{text:r.string().describe("그래프 자료 — 첫 줄 머리 칸(항목 | 계열)"),kind:r.enum(["bar","line","pie","hbar"]).optional(),color:r.enum(C).optional().describe("청록(기본)·남색·회색·자주·갈색"),title:r.string().optional(),unit:r.string().optional(),source:r.string().optional(),show_values:r.boolean().optional().describe("값 표시(기본 켬)"),up_means:r.enum(["plus","minus"]).optional().describe("▲ 를 늘어남(plus)·줄어듦(minus) 가운데 어느 쪽으로 읽을지 — 적자·감소 같은 말이 있어 물을 때만")},(async t=>{let e=k(t,LIM.tableText,"그래프 자료");"minus"===t.up_means&&(e=e.replace(/▲/g,"−"));const s=a("draw","EbChart.toTable",[e]);if(s.error)throw _("그래프로 그릴 숫자를 찾지 못했어요 — 「항목 숫자」 줄이나 「항목: 값」 줄로 적어 주세요.");{const t=b([s.head||[],...s.rows||[]]);t.turned&&(s.head=t.rows[0],s.rows=t.rows.slice(1),s.turned=!0)}const n=a("draw","EbChart.chartData",[s]);if(!n)throw _("숫자 세로줄이 없어 그래프로 그릴 수 없어요.");if(n.upAsk&&!t.up_means)throw _("제목·머리에 「적자·손실·감소」 같은 말이 있어 ▲가 줄어듦(−)일 수 있어요 — up_means(plus 또는 minus)를 정해 다시 불러 주세요.",409);const r=a("draw","EbChart.recommend",[n]),i=t.kind||r.kind,o=a("draw","EbChart.kindCheck",[n,i]);if(o.block)throw _(o.text,422);const c=null!=t.unit?M(t.unit,30):n.unit||s.unit||"",p=M(t.title||s.title||"",120),h=M(t.source||s.src||"",200),u=!1!==t.show_values,m=P(),f=a("draw","EbChart.layout",[n,i,m,{showValues:u,unit:c}]);let g=e;s.capNo&&(g=g.replace(/^\s*(?:<\s*표\s*[\d-]*\s*>|\[\s*표\s*[\d-]*\s*\]).*$/m,(t=>t.replace(/표\s*[\d-]+/,"표"))));const d=[p,c,h].concat(s.notes||[]),w={commaSplit:"comma2"===s.how};let x=a("draw","EbChart.drawnCheck",[g,f,d,w]),y=x.miss,S=[];if(!u&&y.length){S=y;const t=a("draw","EbChart.layout",[n,i,m,{showValues:!0,unit:c}]);y=a("draw","EbChart.drawnCheck",[g,t,d,w]).miss}if(y.length)throw _(`그림에 없는 수 ${y.length}개(${y.slice(0,12).join(", ")}) — 그리지 않았어요${x.roles&&x.roles.length?"("+x.roles[0].why+")":n.unread&&n.unread.length?"(「"+n.unread.join("」「")+"」 열은 숫자로 읽지 못함)":"(항목 이름이 잘렸으면 줄여 주세요)"}.`,422);const $=C.includes(t.color)?t.color:"teal",j=a("draw","EbChart.descOf",[{kind:i,color:$,title:p,unit:c,src:h,showValues:u,text:e}]);if(S.length&&a("draw","EbChart.lost",[e,j]).length)throw _("자료가 길어 값 표시를 끄면 수가 어디에도 남지 않아요 — show_values 를 켜 주세요.",422);const I=await T("draw","EbChart",f,$);return l.charge("chart"),v(I,{kind:i,kind_name:a("draw","EbChart.kindName",[i])||i,recommended:r.kind,why:o.text||r.why||"",title:p,unit:c,source:h,notes:(s.notes||[]).concat(s.turned?["줄이 계열인 가로 표라 돌려서 그렸어요(머리 칸 → 가로축 항목, 줄 → 계열)."]:[]),width:I.readUInt32BE(16),height:I.readUInt32BE(20),check:{numbers:x.shown,missing:[],hidden_values:S.length,geometry:"막대·점·값 글 자리 맞음"},description:j},l.keep(I,E(p,"그래프")+".png","image/png"))})),p("on_diagram","글머리를 체계도 그림으로","글머리(□ 큰 단계 ○ 그 아래 - 더 아래, 「가 → 나 → 다」, 「제목: 」, [구역], ⇨ 맺음)를 공문서용 체계도 그림(PNG — 단계 흐름·추진체계·구성도·개념 모식도, 색 5가지)으로 그린다 — On 문서 화면 체계도 만들기와 같은 규칙. 상자 글은 원문 낱말 그대로이며, 원문 숫자를 잃거나 항목이 그림에서 빠지면 그림 대신 까닭을 낸다. Draw an org/flow diagram PNG from bullet text. 글 4천 자·큰 항목 8개·그 아래 8개까지.",{text:r.string().describe("글머리 글"),kind:r.enum(["flow","tree","group","concept"]).optional(),color:r.enum(C).optional()},(async t=>{const e=k(t,LIM.diagramText,"체계도 글"),s=a("draw","EbDiagram.parse",[e]);if(!s.items||!s.items.length)throw _("항목을 찾지 못했어요 — □ ○ - 글머리나 「가 → 나 → 다」로 적어 주세요.");const n=a("draw","EbDiagram.verify",[s,e]);if(n.length)throw _("원문에 없는 상자 글이 생겨 그리지 않았어요: "+n.slice(0,3).join(" · "),422);const r=(s.items||[]).reduce(((t,e)=>t+1+(e.kids||[]).reduce(((t,e)=>t+1+(e.kids||[]).length),0)),0)+(s.chain?s.chain.length:0),i=e.split("\n").filter((t=>/^\s*(?:[□■◆◇▣○●◦◯\-–—·•*※]|\d{1,2}[.)]|[①-⑳]|[가-힣][.)]\s)/.test(t))).length;if(i>r)throw _(`그림에 다 담지 못했어요(글머리 ${i}줄 중 ${r}개) — 큰 항목 8개·그 아래 8개까지 그려요. 나눠서 그려 주세요.`,422);const o=t.kind||a("draw","EbDiagram.guess",[s]),c=C.includes(t.color)?t.color:"teal",p=a("draw","EbDiagram.layout",[s,o,P()]),h=p.shapes.map((t=>[t.text||"",...t.lines||[]].join(" "))).join("\n"),u=a("draw","EbChart.lost",[a("draw","EbDiagram.toText",[s]),h]),m=a("draw","EbChart.lost",[e,h]);if(u.length||m.length)throw _(`그림에서 숫자 ${[...new Set([...u,...m])].slice(0,10).join(", ")}를 찾지 못해 그리지 않았어요(상자 글이 너무 길면 잘림 — 줄여 주세요).`,422);const f=await T("draw","EbDiagram",p,c);return l.charge("diagram"),v(f,{kind:o,title:s.title||"",items:r,width:f.readUInt32BE(16),height:f.readUInt32BE(20),check:{words:"상자 글은 모두 원문 낱말",numbers:"원문 숫자 모두 그림에 있음"}},l.keep(f,E(s.title,"체계도")+".png","image/png"))})),p("on_gaejo","개조식으로","서술형 문단을 공문서 개조식(□ ○ - 기호, 「~함」「~임」 끝맺음, 한 줄 한 생각)으로 바꾼다 — On 문서 화면 「개조식으로」와 같은 규칙(AI 없음). 바꾸는 것은 문장 나누기·끝 서술어·문장 머리 접속어·긴 문장 이음뿐이고, 바꾼 뒤 숫자·날짜·로마자·따옴표·괄호 안 말이 원문과 같은지 문장마다 다시 센다(어긋나면 그 문장은 원문 그대로). 끝맺음을 확실히 못 정한 문장도 그대로 두고 알린다. Convert prose to Korean bullet style (gaejo). 글 2만 자·2천 줄까지.",{text:r.string().describe("바꿀 글(문단은 줄로 나눔 — PDF 에서 복사해 문장 가운데서 끊긴 줄은 이어 붙여 봄)"),start:r.enum(["o","box","dash"]).optional().describe("첫 단계 기호 — o ○(기본) · box □ 아래 ○ · dash -"),join_lines:r.boolean().optional().describe("문장 가운데서 끊긴 줄(PDF 복사) 잇기 — 기본 켬, false 면 줄을 그대로")},(async t=>{const e=k(t,LIM.text),s=["o","box","dash"].includes(t.start)?t.start:"o";nt(e);const n=!1===t.join_lines?{text:e,joins:[]}:unwrapLines(e),r=n.text;if(r.replace(/\s/g,"")!==e.replace(/\s/g,""))throw _("글을 이어 붙이다 글자가 달라져 멈췄어요 — join_lines 를 false 로 다시 해 주세요.",422);const i=[],o=[],p=[],h=nt(r);let u=0,m=0,f=-1;for(let t=0;t<h.length;t++){const e=h[t];if(!e.trim()){i.push("");continue}let n;try{n=a("gaejo","EbGaejo.convert",[e,{start:s}])}catch(e){if(!c(e))throw e;f=t,i.push(...h.slice(t));break}o.push(...(n.kept||[]).map((t=>({sentence:M(t.s,80),why:t.why})))),!n.done&&n.out.length<=1?(m++,i.push(e)):(u+=n.done,p.push(...(n.fixes||[]).slice(0,20).map((t=>({from:M(t.from,80),to:M(t.to,80),why:t.why})))),i.push(...n.out))}const g=i.join("\n"),d=pt(r,g);if(d.length)throw _(`바꾼 글에서 빠진 것이 있어 결과를 내지 않았어요(${d.slice(0,8).join(", ")}).`,422);return l.charge("gaejo"),{text:g,changed_sentences:u,unchanged_paragraphs:m,kept:o.slice(0,60),fixes:p.slice(0,100),check:{lost:[],note:"숫자·이름·따옴표·괄호 말 잃음 0"},...f>=0?{partial:y(f,h.length,"바꿨어요")}:{},...n.joins.length?{joined_lines:n.joins.length,joins:n.joins.slice(0,30),joins_note:`문장 가운데서 끊긴 줄 ${n.joins.length}곳을 이어 붙였어요(PDF 등에서 복사한 줄바꿈) — 낱말 가운데서 끊긴 곳은 붙이고 그 밖은 띄웠어요. joins 의 띄어쓰기를 한 번 확인해 주세요(줄을 그대로 두려면 join_lines: false).`}:{}}}));const O=(t,e,s,n,a)=>p(t,e,s,{text:r.string().describe("고칠 글(문단은 줄로 나눔)")},(async t=>{const e=k(t,LIM.text),s=nt(e),r=[],i=[],o=[],p=n(s),h=p.hits;let u=p.upto;s.forEach(((t,e)=>{if(e>=u)return void r.push(t);const{out:s,used:n}=function(t,e){const s=e.filter((e=>!(e.nofix||null==e.to||e.to===e.from||t.substr(e.off,e.len)!==e.from||st(e.from)!==st(e.to)||/[\u0000-\u001f]/.test(e.from)))).sort(((t,e)=>t.off-e.off)).filter(((t,e,s)=>!s.slice(0,e).some((e=>t.off<e.off+e.len))));let n=t;for(const t of[...s].reverse())n=n.slice(0,t.off)+t.to+n.slice(t.off+t.len);return{out:n,used:s}}(t,h.filter((t=>t.i===e)));if(s!==t){let n;try{n=ct(t,s)}catch(s){if(!c(s))throw s;return u=e,void r.push(t)}if(n.length)return o.push({line:e+1,why:"바꾸면 빠지는 것이 있어 그대로 둠("+n.slice(0,3).join(", ")+")"}),void r.push(t)}r.push(s),i.push(...n.map((t=>({line:e+1,from:t.from,to:t.to,kind:t.kind||"",why:String(t.why||"").slice(0,160)}))))}));const m=r.join("\n"),f=pt(e,m);if(f.length)throw _(`고친 글에서 빠진 것이 있어 결과를 내지 않았어요(${f.slice(0,8).join(", ")}).`,422);return l.charge(a),{text:m,fixed:i.length,fixes:i.slice(0,300),kept:o,check:{lost:[],note:"숫자가 바뀌는 고침은 하지 않음 · 숫자·이름 잃음 0"},...u<s.length?{partial:y(u,s.length,"점검했어요")}:{}}}));O("on_spell","맞춤법·띄어쓰기","틀린 것이 거의 확실한 맞춤법·띄어쓰기(몇일→며칠, 할수있다→할 수 있다, 율/률, 의존 명사 띄어 쓰기 등)만 고친 글과 고친 곳(무엇을→무엇으로·까닭)을 돌려준다 — On 문서 편집기 자동 점검과 같은 규칙(AI 없음, 한글 맞춤법 근거). 애매한 말은 건드리지 않는다. Fix near-certain Korean spelling/spacing errors. 글 2만 자까지.",(t=>{const e=[];let s=t.length;for(let n=0;n<t.length;n++)if(!(t[n].length<2))try{for(const s of a("words","EbSpell.scan",[t[n]]))e.push({...s,i:n})}catch(t){if(!c(t))throw t;s=n;break}return{hits:e,upto:s}}),"spell"),O("on_plain","쉬운 말로","번역투(~에 있어서·~을 통해)·이중 피동(되어지다)·겹말(가장 최적)·어려운 한자어(제고하다·사료된다)를 쉬운 말로 바꾼 글과 바꾼 곳·까닭을 돌려준다 — On 문서 화면 「쉬운 말」과 같은 규칙(AI 없음). 뜻이 다른 말은 건드리지 않는다. Rewrite translationese and hard words into plain Korean. 글 2만 자까지.",(t=>({hits:a("words","EbPlain.scan",[t]),upto:t.length})),"plain"),l.reg("on_render_pages",{title:"쪽 그림(범위)",description:`한글 문서(.hwp·.hwpx)의 쪽을 On 한글엔진으로 그린 그림(PNG)으로 돌려준다 — 한글과 같은 쪽 나눔·줄바꿈. pages 에 「1-3,5」 꼴로 쪽 번호(한 번에 ${LIM.renderPages}쪽까지), scale 0.5~1.5. Render HWP/HWPX pages to PNG. 그림 합 10MB 까지(넘으면 앞 쪽까지만).`,inputSchema:{...l.FILE,pages:r.string().max(60).optional().describe("쪽 번호(1부터) — 「1-3,5」 꼴, 없으면 1쪽"),scale:r.number().min(.5).max(1.5).optional().describe("배율(기본 1)")}},(async t=>{try{if(l.paused())throw l.userErr(new Error("잠시 멈춘 열쇠입니다."));l.rate();const e=await l.fileArg(t),s=[];for(const e of String(t.pages||"1").split(",")){const t=/^\s*(\d{1,4})\s*(?:-\s*(\d{1,4}))?\s*$/.exec(e);if(!t)throw _("pages 는 「1-3,5」 꼴로 주세요.");const n=+t[1],r=t[2]?+t[2]:n;if(n<1||r<n)throw _("쪽 번호가 맞지 않아요.");for(let t=n;t<=r&&s.length<=LIM.renderPages;t++)s.push(t)}if(s.length>LIM.renderPages)throw _(`한 번에 ${LIM.renderPages}쪽까지예요.`,413);await l.gate(e,t.file_name);const n=await j(m(e,[...new Set(s)],Math.max(.5,Math.min(1.5,+t.scale||1)),LIM.renderPages)),r=[];let a=0,i=0;for(const t of n.images||[]){const e=Buffer.from(t.png);a+e.length>LIM.outPng?i++:(a+=e.length,r.push({page:t.page,b:e}))}return l.charge("render_pages",r.length),{content:[{type:"text",text:`전체 ${n.pages}쪽 중 ${r.map((t=>t.page)).join(", ")||"없음"}쪽${i?` (그림이 커서 ${i}쪽은 뺌 — 범위를 줄이거나 scale 을 낮춰 주세요)`:""}`},...r.map((t=>({type:"image",data:t.b.toString("base64"),mimeType:"image/png"})))]}}catch(t){return l.fail(t)}}))}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! On 문서 내 PC 판 · on-munseo — 엔진·코드의 무단 복제·배포·재사용·역공학 금지(이용약관 제5조). 오픈소스 부품은 각 라이선스를 따름 */
|
|
2
|
+
import t from"fs";import e from"path";import o from"vm";import{AsyncLocalStorage as r}from"async_hooks";import{fileURLToPath as n}from"url";import"../../public/js/spellcheck.js";import"../../public/js/plain_rules.js";const l=e.resolve(e.dirname(n(import.meta.url)),"..",".."),a=e.join(l,"trial","web","app","js"),s=e.join(l,"public","js"),c={gaejo:[e.join(a,"gaejo.js")],draw:[e.join(a,"diagram.js"),e.join(a,"chart.js")],fill:[e.join(a,"fill_match.js")],refdoc:[e.join(a,"refdoc.js")],words:[e.join(s,"spellcheck.js"),e.join(s,"plain_rules.js")]},i={gaejo:"EbGaejo",draw:"EbChart",fill:"EbFillMatch",refdoc:"EbRefDoc",words:"EbSpell"};function u(){}u.prototype.parseFromString=function(t){const e=function(t){const e=String(t||""),o=/<table[\s>]/i.exec(e);if(!o)return null;const r=/<(\/?)(table|tr|td|th)\b([^>]*)>/gi,n=[];let l,a=0,s=null,c=null;for(r.lastIndex=o.index;l=r.exec(e);){const t=!!l[1],o=l[2].toLowerCase(),r=l[3]||"";if("table"!==o){if(1===a)if("tr"!==o)if(t)c&&(s.cells.push({innerHTML:e.slice(c.start,l.index),rowSpan:c.rowSpan,colSpan:c.colSpan,tagName:c.tagName}),c=null);else{s||(s={cells:[]},n.push(s));const t=t=>{const e=new RegExp(t+"\\s*=\\s*[\"']?(\\d+)","i").exec(r);return e?Math.max(1,Math.min(1e3,+e[1])):1};c={start:l.index+l[0].length,rowSpan:t("rowspan"),colSpan:t("colspan"),tagName:o.toUpperCase()}}else t?s=null:(s={cells:[]},n.push(s))}else if(a+=t?-1:1,0===a)break}const i={rows:n.map((t=>({cells:t.cells,closest:()=>i})))};return i}(t);return{querySelector:t=>"table"===t?e:null}};const p=new Map;function f(r){if(p.has(r))return p.get(r);const n=c[r];if(!n)throw new Error("모르는 규칙");const l={log(){},warn(){},debug(){},error(){}},a=o.createContext({window:{},console:l,..."refdoc"===r?{navigator:{platform:"",userAgent:""},document:{body:{},querySelector:()=>null,querySelectorAll:()=>[],addEventListener(){}},DOMParser:u}:{}});for(const r of n)o.runInContext(t.readFileSync(r,"utf8"),a,{filename:e.basename(r),timeout:5e3});return p.set(r,a),a}const d=new r;export const withBudget=(t,e)=>d.run({end:Date.now()+Math.max(1,+t||0),ms:Math.max(1,+t||0)},e);export const outsideBudget=t=>d.exit(t);export const budgetLeft=()=>{const t=d.getStore();return t?t.end-Date.now():1/0};export const isBudget=t=>!(!t||!t.budget);const m=()=>{const t=d.getStore();return Object.assign(new Error(`요청 하나에 쓸 수 있는 규칙 처리 시간(${Math.round((t?t.ms:0)/1e3)}초)을 넘었어요. 글을 나눠 다시 해 주세요.`),{status:408,budget:!0})},w=new o.Script("__o = JSON.stringify(__f.apply(__t, __a))",{filename:"onrule-call"}),_=/^(EbGaejo|EbChart|EbDiagram|EbFillMatch|EbRefDoc|EbSpell|EbPlain)\.([A-Za-z]\w{0,40})$/;export const _calls={n:0};export function call(t,e,o=[],r=3e3){_calls.n++;const n=_.exec(String(e));if(!n)throw new Error("모르는 규칙");const l=budgetLeft();if(l<=0)throw m();const a=Math.max(1,Math.ceil(Math.min(r,l))),s=a<r,c=f(t),i=c.window[n[1]],u=i&&Object.prototype.hasOwnProperty.call(i,n[2])?i[n[2]]:null;if("function"!=typeof u)throw new Error("모르는 규칙");Object.assign(c,{__f:u,__t:i,__a:Array.isArray(o)?o:[o],__o:void 0});try{return w.runInContext(c,{timeout:a}),void 0===c.__o?null:JSON.parse(c.__o)}catch(t){if(t&&"ERR_SCRIPT_EXECUTION_TIMEOUT"===t.code)throw s?m():Object.assign(new Error("규칙 처리가 너무 오래 걸려 멈췄어요. 글을 나눠 다시 해 주세요."),{status:408});throw t}finally{Object.assign(c,{__f:null,__t:null,__a:null,__o:void 0})}}export const exec=(t,e,o)=>{call(t,e,o,5e3)};export const has=t=>{try{return!!f(t).window[i[t]]}catch{return!1}};
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|