@lingjingai/scriptctl 0.65.4 → 0.65.7

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.
@@ -1,5 +1,5 @@
1
- import{Command as fO,CommanderError as mO}from"commander";import*as xc from"node:crypto";import*as Mi from"node:fs";import*as Er from"node:path";import*as Ue from"node:fs";import*as Mt from"node:path";var Ms=class{workspace;constructor(t){this.workspace=t}get sourceText(){return Mt.join(this.workspace,"source.txt")}get directDir(){return Mt.join(this.workspace,"draft","scriptctl","direct")}get directScript(){return Mt.join(this.directDir,"script.initial.json")}get validation(){return Mt.join(this.directDir,"validation.json")}get runState(){return Mt.join(this.directDir,"run_state.json")}get episodeResultsDir(){return Mt.join(this.directDir,"episode_results")}get batchResultsDir(){return Mt.join(this.directDir,"batch_results")}outputScript(t){return Mt.join(t,"script.json")}};function Ow(e){let t="";for(let n of e)n==="*"?t+="[^/]*":n==="?"?t+="[^/]":".+^$()[]{}|\\".includes(n)?t+="\\"+n:t+=n;return new RegExp("^"+t+"$")}var Ec=class{exists(t){return Ue.existsSync(t)}readText(t){return Ue.readFileSync(t,"utf-8")}writeText(t,n){Ue.mkdirSync(Mt.dirname(t),{recursive:!0}),Ue.writeFileSync(t,n,"utf-8")}readJson(t){return JSON.parse(Ue.readFileSync(t,"utf-8"))}writeJson(t,n){this.writeText(t,JSON.stringify(n,null,2)+`
2
- `)}list(t,n="*"){if(!Ue.existsSync(t))return[];let o=Ow(n),i=Ue.readdirSync(t),r=[];for(let s of i)o.test(s)&&r.push(Mt.join(t,s));return r.sort(),r}delete(t){Ue.existsSync(t)&&Ue.unlinkSync(t)}deleteTree(t){Ue.existsSync(t)&&Ue.rmSync(t,{recursive:!0,force:!0})}copyToPath(t,n){Ue.mkdirSync(Mt.dirname(n),{recursive:!0}),Ue.copyFileSync(t,n)}},Ns=new Ec;var B=0,J=64,k=66,ee=70,co=78,eu=30;var SO=Er.join("draft","scriptctl","direct"),vw=Er.join("workspace","script.json");var tu=["\u4E0A\u53E4\u65F6\u4EE3","\u53E4\u4EE3\u5386\u53F2","\u53E4\u98CE\u67B6\u7A7A","\u8FD1\u4EE3\u6C11\u56FD","\u73B0\u4EE3","\u6B27\u6D32\u4E2D\u4E16\u7EAA","\u8D5B\u535A\u670B\u514B","\u661F\u9645\u65F6\u4EE3","\u897F\u5E7B\u67B6\u7A7A"],nu=new Set(["actor","location","prop"]);var IO=`scriptctl parse \u8F93\u5165 = \u4E00\u4E2A md \u5DE5\u4F5C\u533A\u76EE\u5F55\u3002\u6587\u4EF6\u6309\u804C\u8D23\u5206\u5F00\uFF0C\u4E92\u4E0D\u6DF7\u5199\uFF1A
1
+ import{Command as mO,CommanderError as gO}from"commander";import*as Ic from"node:crypto";import*as Ni from"node:fs";import*as Sr from"node:path";import*as Ue from"node:fs";import*as Mt from"node:path";var Ns=class{workspace;constructor(t){this.workspace=t}get sourceText(){return Mt.join(this.workspace,"source.txt")}get directDir(){return Mt.join(this.workspace,"draft","scriptctl","direct")}get directScript(){return Mt.join(this.directDir,"script.initial.json")}get validation(){return Mt.join(this.directDir,"validation.json")}get runState(){return Mt.join(this.directDir,"run_state.json")}get episodeResultsDir(){return Mt.join(this.directDir,"episode_results")}get batchResultsDir(){return Mt.join(this.directDir,"batch_results")}outputScript(t){return Mt.join(t,"script.json")}};function Mw(e){let t="";for(let n of e)n==="*"?t+="[^/]*":n==="?"?t+="[^/]":".+^$()[]{}|\\".includes(n)?t+="\\"+n:t+=n;return new RegExp("^"+t+"$")}var Sc=class{exists(t){return Ue.existsSync(t)}readText(t){return Ue.readFileSync(t,"utf-8")}writeText(t,n){Ue.mkdirSync(Mt.dirname(t),{recursive:!0}),Ue.writeFileSync(t,n,"utf-8")}readJson(t){return JSON.parse(Ue.readFileSync(t,"utf-8"))}writeJson(t,n){this.writeText(t,JSON.stringify(n,null,2)+`
2
+ `)}list(t,n="*"){if(!Ue.existsSync(t))return[];let o=Mw(n),i=Ue.readdirSync(t),r=[];for(let s of i)o.test(s)&&r.push(Mt.join(t,s));return r.sort(),r}delete(t){Ue.existsSync(t)&&Ue.unlinkSync(t)}deleteTree(t){Ue.existsSync(t)&&Ue.rmSync(t,{recursive:!0,force:!0})}copyToPath(t,n){Ue.mkdirSync(Mt.dirname(n),{recursive:!0}),Ue.copyFileSync(t,n)}},Ls=new Sc;var G=0,B=64,k=66,X=70,po=78,nu=30;var IO=Sr.join("draft","scriptctl","direct"),Nw=Sr.join("workspace","script.json");var ou=["\u4E0A\u53E4\u65F6\u4EE3","\u53E4\u4EE3\u5386\u53F2","\u53E4\u98CE\u67B6\u7A7A","\u8FD1\u4EE3\u6C11\u56FD","\u73B0\u4EE3","\u6B27\u6D32\u4E2D\u4E16\u7EAA","\u8D5B\u535A\u670B\u514B","\u661F\u9645\u65F6\u4EE3","\u897F\u5E7B\u67B6\u7A7A"],iu=new Set(["actor","location","prop"]);var AO=`scriptctl parse \u8F93\u5165 = \u4E00\u4E2A md \u5DE5\u4F5C\u533A\u76EE\u5F55\u3002\u6587\u4EF6\u6309\u804C\u8D23\u5206\u5F00\uFF0C\u4E92\u4E0D\u6DF7\u5199\uFF1A
3
3
 
4
4
  ep_001.md, ep_002.md, ... \u6B63\u6587\uFF08\u6BCF\u96C6\u4E00\u4E2A\uFF0C\u53EA\u653E\u5267\u672C\u672C\u8EAB\uFF09
5
5
  \u4EBA\u7269.md \u5168\u5267\u552F\u4E00\u4E00\u4EFD\u89D2\u8272\u767B\u8BB0\uFF08\u6240\u6709 worker \u5171\u540C\u5F80\u91CC\u52A0\uFF09
@@ -79,7 +79,7 @@ import{Command as fO,CommanderError as mO}from"commander";import*as xc from"node
79
79
  <\u6574\u90E8\u5168\u6587\u6897\u6982\uFF0C\u7EAF\u6587\u672C\uFF0C\u53EF\u591A\u884C>
80
80
 
81
81
  ==================== 7. \u5143\u4FE1\u606F.md\uFF08\u53EF\u9009\uFF0C\u6574\u90E8\u5143\u4FE1\u606F\uFF1B\u4E00\u822C\u7531 merger \u6536\u53E3\u65F6\u5199\uFF09 ====================
82
- worldview: <\u4E16\u754C\u89C2\uFF0C\u53D6\u8FD9\u4E9B\u679A\u4E3E\u4E4B\u4E00\uFF1A`+tu.join(" / ")+`>
82
+ worldview: <\u4E16\u754C\u89C2\uFF0C\u53D6\u8FD9\u4E9B\u679A\u4E3E\u4E4B\u4E00\uFF1A`+ou.join(" / ")+`>
83
83
  style: <\u98CE\u683C\uFF0C\u81EA\u7531\u6587\u672C\uFF0C\u5982 \u90FD\u5E02\u751C\u5BA0 / \u60AC\u7591\u590D\u4EC7>
84
84
  title: <\u5267\u540D>
85
85
  \u4E3B\u89D2: <\u4E3B\u89D2\u540D1>, <\u4E3B\u89D2\u540D2> \u2190 \u5217\u5728\u8FD9\u91CC\u7684\u8BBE\u4E3A role_type=\u4E3B\u89D2\uFF0C\u5176\u4F59\u89D2\u8272=\u914D\u89D2
@@ -119,30 +119,30 @@ Rules:
119
119
  - \u7FA4\u4F53\u8BCD\uFF08\u4F17\u4EBA / \u7FA4\u4F17 / \u56F4\u89C2\u8005 / \u8DEF\u4EBA\u4EEC\uFF09\u4E0D\u8FDB \u4EBA\u7269.md\uFF0C\u767B\u5230 \u53D1\u58F0\u6E90.md \u7528 group \u6216\u5199\u52A8\u4F5C\u65C1\u767D\u3002
120
120
  - \u52A8\u4F5C / \u5BF9\u767D\u6B63\u6587\u9010\u5B57\u4FDD\u7559\uFF0C\u4E0D\u8981\u8F6C\u8FF0 / \u7FFB\u8BD1 / \u6982\u62EC / \u52A0\u6CE8\u91CA\uFF1B\u52A8\u4F5C\u79CD\u7C7B\u53EA\u6709 act/dlg/think\u3002
121
121
  - \u6BCF\u4E2A\u51FA\u73B0\u5728\u6B63\u6587\u91CC\u7684\u89D2\u8272\uFF0C\u90FD\u8981\u5728 \u4EBA\u7269.md \u7ED9\u51FA\u975E\u7A7A\u63CF\u8FF0\uFF08\u5426\u5219\u6821\u9A8C\u62A5\u9519\uFF09\u3002
122
- `,S=class extends Error{exitCode;errorCode;hint;data;constructor(t,n){super(t),this.name="CliError",this.exitCode=n.exitCode,this.errorCode=n.errorCode,this.hint=n.hint,this.data=n.data??{}}};function Rw(e){return new Ms(e)}function ou(e){return Rw(e).directDir}function ge(e){let t=e.script_path??e.scriptPath;return Er.resolve(typeof t=="string"&&t.length>0?t:vw)}function xr(e){return Ns.readJson(e)}function Sc(e,t){Ns.writeJson(e,t)}function zo(e){return Ns.exists(e)}function Ee(e){return xc.createHash("sha256").update(e,"utf-8").digest("hex")}function Ic(e){let t=xc.createHash("sha256"),n=Mi.openSync(e,"r");try{let o=Buffer.alloc(1048576);for(;;){let i=Mi.readSync(n,o,0,o.length,null);if(i<=0)break;t.update(o.subarray(0,i))}}finally{Mi.closeSync(n)}return t.digest("hex")}var Nt={policy:["content_blocked"],network:["dns_failed","connection_refused","connection_reset","network_unreachable","tls_failed","network_failed"],timeout:["connect_timeout","request_timeout","media_processing_timeout"],rate_limit:["rate_limited"],authentication:["authentication_failed"],authorization:["permission_denied"],provider:["resource_not_found","provider_unavailable","request_rejected","attempts_exhausted"],media:["media_upload_failed","media_processing_failed","media_too_large","unsupported_media"],response:["output_truncated","empty_response","malformed_response"],pipeline:["serial_parse_failed","source_mismatch","pipeline_mismatch"],validation:["script_validation_failed"],cancelled:["cancelled"],unknown:["unknown","legacy_unclassified"]};function Lt(e,t){return typeof e=="string"&&t.some(n=>n===e)}function iu(e,t){switch(e){case"policy":return Lt(t,Nt.policy)?{failure_type:e,failure_code:t}:null;case"network":return Lt(t,Nt.network)?{failure_type:e,failure_code:t}:null;case"timeout":return Lt(t,Nt.timeout)?{failure_type:e,failure_code:t}:null;case"rate_limit":return Lt(t,Nt.rate_limit)?{failure_type:e,failure_code:t}:null;case"authentication":return Lt(t,Nt.authentication)?{failure_type:e,failure_code:t}:null;case"authorization":return Lt(t,Nt.authorization)?{failure_type:e,failure_code:t}:null;case"provider":return Lt(t,Nt.provider)?{failure_type:e,failure_code:t}:null;case"media":return Lt(t,Nt.media)?{failure_type:e,failure_code:t}:null;case"response":return Lt(t,Nt.response)?{failure_type:e,failure_code:t}:null;case"pipeline":return Lt(t,Nt.pipeline)?{failure_type:e,failure_code:t}:null;case"validation":return Lt(t,Nt.validation)?{failure_type:e,failure_code:t}:null;case"cancelled":return Lt(t,Nt.cancelled)?{failure_type:e,failure_code:t}:null;case"unknown":return Lt(t,Nt.unknown)?{failure_type:e,failure_code:t}:null;default:return null}}function Ut(e,t){return{...e,...t}}function Ni(e){switch(e.failure_type){case"policy":return{failure_type:e.failure_type,failure_code:e.failure_code};case"network":return{failure_type:e.failure_type,failure_code:e.failure_code};case"timeout":return{failure_type:e.failure_type,failure_code:e.failure_code};case"rate_limit":return{failure_type:e.failure_type,failure_code:e.failure_code};case"authentication":return{failure_type:e.failure_type,failure_code:e.failure_code};case"authorization":return{failure_type:e.failure_type,failure_code:e.failure_code};case"provider":return{failure_type:e.failure_type,failure_code:e.failure_code};case"media":return{failure_type:e.failure_type,failure_code:e.failure_code};case"response":return{failure_type:e.failure_type,failure_code:e.failure_code};case"pipeline":return{failure_type:e.failure_type,failure_code:e.failure_code};case"validation":return{failure_type:e.failure_type,failure_code:e.failure_code};case"cancelled":return{failure_type:e.failure_type,failure_code:e.failure_code};case"unknown":return{failure_type:e.failure_type,failure_code:e.failure_code}}}function Sr(e){return{...e.provider!==void 0?{provider:e.provider}:{},...e.model!==void 0?{model:e.model}:{},...e.operation!==void 0?{operation:e.operation}:{},...e.http_status!==void 0?{http_status:e.http_status}:{},...e.system_code!==void 0?{system_code:e.system_code}:{},...e.provider_source!==void 0?{provider_source:e.provider_source}:{},...e.provider_reason!==void 0?{provider_reason:e.provider_reason}:{},...e.provider_reason_raw!==void 0?{provider_reason_raw:e.provider_reason_raw}:{},...e.finish_message!==void 0?{finish_message:e.finish_message}:{},...e.safety_ratings!==void 0?{safety_ratings:e.safety_ratings}:{},...e.details!==void 0?{details:e.details}:{}}}function ru(e,t){if(e.length===0)return Ut({failure_type:"unknown",failure_code:"unknown"},{retryable:!1,message:t});let n=e[0],i=e.every(r=>r.failure_type===n.failure_type&&r.failure_code===n.failure_code)?Ni(n):{failure_type:"provider",failure_code:"attempts_exhausted"};return Ut(i,{retryable:e.some(r=>r.retryable),message:t})}function hn(e){let t=e.provider||e.model?`${e.provider??"provider"}/${e.model??"model"} `:"",n=e.provider_reason?` provider_reason=${e.provider_reason}`:"",o=e.system_code?` system_code=${e.system_code}`:"",i=e.http_status!==void 0?` http_status=${e.http_status}`:"",r=e.details?.length?` | ${e.details.join(" | ")}`:"";return`${t}${e.failure_type}/${e.failure_code}${n}${o}${i}: ${e.message}${r}`}import*as Eu from"node:crypto";import*as xu from"node:fs";import*as Su from"node:path";import*as fu from"node:crypto";var Tn=["action","dialogue","inner_thought","transition"],qt=new Set(Tn),Vn=["system","broadcast","offscreen","group"],Ho=new Set(Vn),$n=["featured","background"],Pt=new Set($n),Li=["\u4E3B\u89D2","\u914D\u89D2"],po=new Set(Li),Ls=["day","night","dawn","dusk"],Ac=new Set(Ls);function Ir(e){return typeof e=="string"&&Ac.has(e)}var kc=["interior","exterior"],su=new Set(kc);function dt(e){return e.normalize("NFKC").toLowerCase()}function au(e){return JSON.stringify([e.code,e.path,e.message])}function bc(e){let t=new Map;for(let n of e){let o=au(n);t.set(o,(t.get(o)??0)+1)}return t}function Oc(e,t){if(e.ok||t.errors.length>=e.errors.length)return!1;let n=bc(e.errors),o=bc(t.errors);for(let[i,r]of o)if(r>(n.get(i)??0))return!1;return!0}function vc(e,t){let n=bc(e),o=[];for(let i of t){let r=au(i),s=n.get(r)??0;s>0?n.set(r,s-1):o.push(i)}return o}import{customAlphabet as Mw}from"nanoid";var Ui="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Rc=6,Pi={episode:"ep",scene:"scn",action:"ac",actor:"act",location:"loc",prop:"prp",state:"st"},Nw=Mw(Ui,Rc),Lw=`[${Ui}]`,cu=Object.fromEntries(Object.entries(Pi).map(([e,t])=>[e,new RegExp(`^${t}${Lw}{${Rc}}$`)]));function $(e,t){return typeof t=="string"&&cu[e].test(t)}var Mc="ID_SPACE_EXHAUSTED";function Ar(e,t=new Set,n=Nw){let o=Pi[e];for(let i=0;i<128;i++){let r=`${o}${n()}`;if(!t.has(r))return r}throw Object.assign(new Error(`Could not generate an unused ${e} ID after 128 attempts.`),{code:Mc})}var et=class extends Error{input;constructor(t,n){super(n),this.input=t,this.name="TimestampParseError"}},Uw=/^(\d+):(\d{2})(?:\.(\d{1,3}))?$/,Pw=/^(\d+):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/;function du(e){return e?Number(e.padEnd(3,"0")):0}function pu(e,t){if(!Number.isSafeInteger(t))throw new et(e,"Timestamp exceeds the supported numeric range.");return t}function lu(e,t){let n=Math.floor(e/1e3),o=Math.floor(n/3600),i=Math.floor(n%3600/60),r=n%60,s=t?`.${t}`:"";return o>0?`${o}:${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}${s}`:`${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}${s}`}function lo(e){let t=e.trim();if(!t)throw new et(e,"Timestamp must not be empty.");let n=t.match(Pw);if(n){let a=Number(n[1]),d=Number(n[2]),p=Number(n[3]),l=n[4];if(d>59)throw new et(e,"Hour-form timestamps require minutes between 00 and 59.");if(p>59)throw new et(e,"Timestamp seconds must be between 00 and 59.");let f=pu(e,((a*60+d)*60+p)*1e3+du(l));return{canonical:lu(f,l),milliseconds:f,fractionDigits:l?.length??0}}let o=t.match(Uw);if(!o)throw new et(e,"Use M:SS, MM:SS, or H:MM:SS with an optional 1-3 digit fraction.");let i=Number(o[1]),r=Number(o[2]),s=o[3];if(r>59)throw new et(e,"Timestamp seconds must be between 00 and 59.");let c=pu(e,(i*60+r)*1e3+du(s));return{canonical:lu(c,s),milliseconds:c,fractionDigits:s?.length??0}}function Cw(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.extend;if(!(typeof t!="object"||t===null||Array.isArray(t)))return t.timestamp}function Us(e,t,n){let o=null;e.forEach((i,r)=>{let s=Cw(i);if(s===void 0)return;let c=`${t}[${r}].extend.timestamp`;if(typeof s!="string"){n("timestamp_invalid",c,"timestamp must be a string in M:SS, MM:SS, or H:MM:SS form");return}let a;try{a=lo(s)}catch(d){if(!(d instanceof et))throw d;n("timestamp_invalid",c,d.message);return}o!==null&&a.milliseconds<o.timestamp.milliseconds&&n("timestamp_out_of_order",c,`timestamp ${a.canonical} is earlier than Action ${o.actionIndex+1} timestamp ${o.timestamp.canonical}; equal timestamps are allowed`),o={actionIndex:r,timestamp:a}})}var yt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Dn=e=>Array.isArray(e),Ie=e=>typeof e=="string",Tw=["state_changes","actor_id","speakers","lines"];function wt(e){let t=[],n=[],o=(u,g,h,m)=>t.push({code:u,path:g,message:h,...m?{repair_hint:m}:{}}),i=(u,g,h)=>n.push({code:u,path:g,message:h});if(!yt(e))return{ok:!1,errors:[{code:"not_object",path:"$",message:"script must be an object"}],warnings:n};e.version!==3&&o("version","$.version","version must be 3");for(let u of["title","worldview","style"])Ie(e[u])||o("field",`$.${u}`,`${u} must be a string`);let r=new Map,s=new Map,c=new Map,a=(u,g,h,m,w)=>{if(!Dn(u)){o("field",w,`${w} must be an array`);return}u.forEach((y,_)=>{let x=`${w}[${_}]`;if(!yt(y)){o("asset",x,"asset must be an object");return}let E=y[h];if(!Ie(E)){o("asset_id",`${x}.${h}`,`${h} required`);return}if(s.has(E)&&o("dup_id",`${x}.${h}`,`duplicate id ${E}`),s.set(E,g),!Ie(y[m]))o("asset_name",`${x}.${m}`,`${m} required`);else if(g==="actor"){let R=dt(y[m]),I=c.get(R);I!==void 0?o("dup_actor_name",`${x}.${m}`,`actor name ${y[m]} already belongs to ${I}`):c.set(R,E)}(!Ie(y.importance)||!$n.includes(y.importance))&&o("importance",`${x}.importance`,`importance must be one of ${$n.join("|")}`),Ie(y.description)||o("asset_desc",`${x}.description`,"description must be a string");let A=new Set,b=new Set,C=0;!Dn(y.states)||y.states.length===0?o("states",`${x}.states`,"states must be a non-empty array"):y.states.forEach((R,I)=>{let O=`${x}.states[${I}]`;if(!yt(R)||!Ie(R.state_id)){o("state_id",O,"state_id required");return}A.has(R.state_id)&&o("dup_state",O,`duplicate state_id ${R.state_id}`),A.add(R.state_id),R.state_id==="default"&&C++,Ie(R.state_name)?(b.has(R.state_name)&&o("dup_state_name",`${O}.state_name`,`duplicate state_name ${R.state_name}`),b.add(R.state_name)):o("state_name",`${O}.state_name`,"state_name required")}),Dn(y.states)&&C!==1&&o("default_state",`${x}.states`,`exactly one 'default' state required, found ${C}`),r.set(E,A)})};a(e.actors,"actor","actor_id","actor_name","$.actors"),a(e.locations,"location","location_id","location_name","$.locations"),a(e.props,"prop","prop_id","prop_name","$.props");let d=(u,g,h,m)=>{if(s.get(u)!==h){o("ref",m,`${h} ${u} not found`);return}g!==void 0&&(!Ie(g)||!r.get(u)?.has(g))&&o("state_ref",m,`state ${String(g)} not materialized on ${u}`)},p=(u,g,h,m)=>{if(u===void 0){o("field",m,`${m} required (may be empty array)`);return}if(!Dn(u)){o("field",m,`${m} must be an array`);return}u.forEach((w,y)=>{if(!yt(w)||!Ie(w[h])){o("ref",`${m}[${y}]`,`${h} required`);return}d(w[h],w.state_id,g,`${m}[${y}]`)})},l=(u,g,h,m)=>{if(!yt(u)){o("action",g,"action must be an object");return}for(let y of Tw)y in u&&o("legacy_field",`${g}.${y}`,`v3 forbids action.${y}`);let w=u.type;if((!Ie(w)||!Tn.includes(w))&&o("action_type",`${g}.type`,`invalid action type ${String(w)}`),Ie(u.content)||o("content",`${g}.content`,"content must be a plain-text string"),w==="dialogue"||w==="inner_thought"){let y=u.speaker;if(!yt(y))o("speaker",`${g}.speaker`,"dialogue/inner_thought needs a speaker");else if("kind"in y)(!Ie(y.kind)||!Vn.includes(y.kind))&&o("speaker_kind",`${g}.speaker.kind`,"invalid non-actor speaker kind");else if(Ie(y.actor_id)){if(d(y.actor_id,y.state_id,"actor",`${g}.speaker`),!h.has(y.actor_id)){let _=r.get(y.actor_id),x=Ie(y.state_id)&&_?.has(y.state_id)?y.state_id:_?.has("default")?"default":_?.values().next().value,E=m&&x?`scriptctl scene-ref ${m} actor:${y.actor_id} --state ${x} -p "$SCRIPT"`:void 0;o("actor_not_in_scene",`${g}.speaker.actor_id`,`actor ${y.actor_id} is not referenced by this scene`,E)}}else o("speaker",`${g}.speaker`,"speaker needs actor_id or kind")}},f=e.episodes;return Dn(f)?f.forEach((u,g)=>{let h=`$.episodes[${g}]`;if(!yt(u)||!Ie(u.episode_id)){o("episode_id",h,"episode_id required");return}if(!Dn(u.scenes)){o("scenes",`${h}.scenes`,"scenes must be an array");return}u.scenes.forEach((m,w)=>{let y=`${h}.scenes[${w}]`;if(!yt(m)){o("scene",y,"scene must be an object");return}"context"in m&&o("legacy_field",`${y}.context`,"v3 forbids scene.context"),Ie(m.scene_id)||o("scene_id",y,"scene_id required");let _=m.environment;_===void 0||yt(_)&&(!Ie(_.time)||_.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!yt(_)||_.space!==void 0&&!Ie(_.space)||!Ie(_.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):Ir(_.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk"),(m.environment===void 0||yt(m.environment)&&(!Ie(m.environment.space)||m.environment.space.trim()===""))&&i("scene_space_missing",`${y}.environment.space`,"scene interior/exterior is required for production review"),m.location===null&&i("scene_location_missing",`${y}.location`,"scene location is required for production review");let x=m.location;if(x!==null&&(!yt(x)||!Ie(x.location_id)?o("location",`${y}.location`,"location must be null or {location_id}"):d(x.location_id,x.state_id,"location",`${y}.location`)),p(m.actors,"actor","actor_id",`${y}.actors`),p(m.props,"prop","prop_id",`${y}.props`),Dn(m.props)){let A=new Set;m.props.forEach((b,C)=>{!yt(b)||!Ie(b.prop_id)||(A.has(b.prop_id)&&o("dup_prop_ref",`${y}.props[${C}]`,`duplicate prop ref ${b.prop_id}`),A.add(b.prop_id))})}let E=new Set(Dn(m.actors)?m.actors.filter(A=>yt(A)).map(A=>A.actor_id).filter(A=>Ie(A)):[]);if(!Dn(m.actions))o("actions",`${y}.actions`,"actions must be an array");else{let A=Ie(m.scene_id)?`${u.episode_id}/${m.scene_id}`:void 0;m.actions.forEach((b,C)=>l(b,`${y}.actions[${C}]`,E,A)),Us(m.actions,`${y}.actions`,o)}})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}var tt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pe=e=>typeof e=="string",yn=e=>Array.isArray(e);function Nc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Nc):tt(e)&&Object.values(e).every(Nc)}function Ci(e,t,n){e!==void 0&&(!tt(e)||!Object.values(e).every(Nc))&&n("extend",t,"extend must be an object containing JSON values")}function Vw(e){for(let t=1;t<e.length;t++)if(e[t-1]>e[t])return!1;return!0}function Pe(e){let t=[],n=[],o=(u,g,h,m)=>t.push({code:u,path:g,message:h,...m?{repair_hint:m}:{}}),i=(u,g,h,m)=>n.push({code:u,path:g,message:h,...m?{repair_hint:m}:{}});if(!tt(e))return{ok:!1,errors:[{code:"not_object",path:"$",message:"script must be an object"}],warnings:n};e.version!==4&&o("version","$.version","version must be 4");for(let u of["title","worldview","style"])pe(e[u])||o("field",`$.${u}`,`${u} must be a string`);for(let u of["worldview_raw","synopsis","logline","theme"])e[u]!==void 0&&!pe(e[u])&&o("field",`$.${u}`,`${u} must be a string`);e.main_characters!==void 0&&(!yn(e.main_characters)||!e.main_characters.every(u=>tt(u)&&pe(u.name)&&pe(u.role)))&&o("main_characters","$.main_characters","main_characters must contain {name, role} string records"),Ci(e.extend,"$.extend",o);let r=new Map,s=new Map,c=new Set,a=(u,g,h,m,w)=>{if(!yn(u)){o("field",w,`${w} must be an array`);return}let y=new Set;u.forEach((_,x)=>{let E=`${w}[${x}]`;if(!tt(_)){o("asset",E,"asset must be an object");return}let A=_[h];if(!$(g,A)){o("asset_id",`${E}.${h}`,`${h} must be ${g} ID`);return}if(y.has(A)&&o("dup_id",`${E}.${h}`,`duplicate ${h} ${A}`),y.add(A),r.set(A,g),!pe(_[m])||_[m].trim()==="")o("asset_name",`${E}.${m}`,`${m} must be a non-empty string`);else if(g==="actor"){let I=_[m].trim().toLocaleLowerCase();c.has(I)&&o("dup_actor_name",`${E}.${m}`,`duplicate actor name ${_[m]}`),c.add(I)}if((!pe(_.importance)||!$n.includes(_.importance))&&o("importance",`${E}.importance`,`importance must be ${$n.join("|")}`),g==="actor"&&_.role_type!==void 0&&(!pe(_.role_type)||!Li.includes(_.role_type))&&o("role_type",`${E}.role_type`,`role_type must be ${Li.join("|")}`),pe(_.description)||o("asset_desc",`${E}.description`,"description must be a string"),_.aliases!==void 0&&(!yn(_.aliases)||!_.aliases.every(pe)))o("aliases",`${E}.aliases`,"aliases must be an array of strings");else if(yn(_.aliases)&&_.aliases.every(pe)){let I=new Set,O=pe(_[m])?_[m]:"";_.aliases.forEach((N,U)=>{N===""&&o("alias_empty",`${E}.aliases[${U}]`,"alias must not be empty"),N===O&&o("alias_equals_name",`${E}.aliases[${U}]`,"alias must differ from the asset name"),I.has(N)&&o("dup_alias",`${E}.aliases[${U}]`,`duplicate alias ${N}`),I.add(N)})}Ci(_.extend,`${E}.extend`,o);let b=new Set,C=new Set,R=0;!yn(_.states)||_.states.length===0?o("states",`${E}.states`,"states must be a non-empty array"):_.states.forEach((I,O)=>{let N=`${E}.states[${O}]`;if(!tt(I)){o("state",N,"state must be an object");return}let U=I.state_id;if(U!=="default"&&!$("state",U)){o("state_id",`${N}.state_id`,"state_id must be default or st plus six Base58 characters");return}b.has(U)&&o("dup_state",`${N}.state_id`,`duplicate state_id ${U}`),b.add(U),U==="default"&&R++,!pe(I.state_name)||I.state_name.trim()===""?o("state_name",`${N}.state_name`,"state_name must be a non-empty string"):(C.has(I.state_name)&&o("dup_state_name",`${N}.state_name`,`duplicate state_name ${I.state_name}`),C.add(I.state_name)),pe(I.description)||o("state_description",`${N}.description`,"description must be a string"),Ci(I.extend,`${N}.extend`,o)}),R!==1&&o("default_state",`${E}.states`,`exactly one default state required, found ${R}`),s.set(A,b)})};a(e.actors,"actor","actor_id","actor_name","$.actors"),a(e.locations,"location","location_id","location_name","$.locations"),a(e.props,"prop","prop_id","prop_name","$.props");let d=(u,g,h)=>{if(!yn(g)||g.length===0||!g.every(pe))return o("state_ids",h,"state_ids must be a non-empty array of strings"),[];let m=g,w=new Set;return m.forEach((y,_)=>{w.has(y)&&o("dup_state_ref",`${h}[${_}]`,`duplicate state_id ${y}`),w.add(y),s.get(u)?.has(y)||o("state_ref",`${h}[${_}]`,`state ${y} not found on ${u}`)}),Vw(m)||o("state_ids_order",h,"state_ids must be sorted lexically"),m},p=new Set,l=new Set,f=new Set;return yn(e.episodes)?e.episodes.forEach((u,g)=>{let h=`$.episodes[${g}]`;if(!tt(u)){o("episode",h,"episode must be an object");return}$("episode",u.episode_id)?(p.has(u.episode_id)&&o("dup_episode_id",`${h}.episode_id`,`duplicate episode_id ${u.episode_id}`),p.add(u.episode_id)):o("episode_id",`${h}.episode_id`,"episode_id must be ep plus six Base58 characters");for(let m of["title","synopsis"])u[m]!==void 0&&!pe(u[m])&&o("field",`${h}.${m}`,`${m} must be a string`);if(Ci(u.extend,`${h}.extend`,o),!yn(u.scenes)){o("scenes",`${h}.scenes`,"scenes must be an array");return}u.scenes.forEach((m,w)=>{let y=`${h}.scenes[${w}]`;if(!tt(m)){o("scene",y,"scene must be an object");return}$("scene",m.scene_id)?(l.has(m.scene_id)&&o("dup_scene_id",`${y}.scene_id`,`duplicate scene_id ${m.scene_id}`),l.add(m.scene_id)):o("scene_id",`${y}.scene_id`,"scene_id must be scn plus six Base58 characters"),Ci(m.extend,`${y}.extend`,o),m.environment===void 0||tt(m.environment)&&(!pe(m.environment.time)||m.environment.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!tt(m.environment)||m.environment.space!==void 0&&!pe(m.environment.space)||!pe(m.environment.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):Ir(m.environment.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk"),(m.environment===void 0||tt(m.environment)&&(!pe(m.environment.space)||m.environment.space.trim()===""))&&i("scene_space_missing",`${y}.environment.space`,"scene interior/exterior is required for production review"),m.location===null&&i("scene_location_missing",`${y}.location`,"scene location is required for production review"),m.location!==null&&(!tt(m.location)||!$("location",m.location.location_id)?o("location",`${y}.location`,"location must be null or a typed v4 location reference"):("state_id"in m.location&&o("v3_field",`${y}.location.state_id`,"Script v4 scene references use state_ids"),r.get(m.location.location_id)!=="location"&&o("location_ref",`${y}.location.location_id`,`location ${m.location.location_id} not found`),d(m.location.location_id,m.location.state_ids,`${y}.location.state_ids`)));let _=new Map,x=(E,A,b,C)=>{if(!yn(E)){o("field",C,`${C} must be an array`);return}let R=new Set;E.forEach((I,O)=>{let N=`${C}[${O}]`;if(!tt(I)||!$(A,I[b])){o("ref",N,`${b} must be a typed v4 ID`);return}let U=I[b];"state_id"in I&&o("v3_field",`${N}.state_id`,"Script v4 scene references use state_ids"),R.has(U)&&o("dup_asset_ref",`${N}.${b}`,`duplicate ${A} ref ${U}`),R.add(U),r.get(U)!==A&&o("asset_ref",`${N}.${b}`,`${A} ${U} not found`);let M=d(U,I.state_ids,`${N}.state_ids`);A==="actor"&&_.set(U,new Set(M))})};if(x(m.actors,"actor","actor_id",`${y}.actors`),x(m.props,"prop","prop_id",`${y}.props`),!yn(m.actions)){o("actions",`${y}.actions`,"actions must be an array");return}m.actions.forEach((E,A)=>{let b=`${y}.actions[${A}]`;if(!tt(E)){o("action",b,"action must be an object");return}if($("action",E.action_id)?(f.has(E.action_id)&&o("dup_action_id",`${b}.action_id`,`duplicate action_id ${E.action_id}`),f.add(E.action_id)):o("action_id",`${b}.action_id`,"action_id must be ac plus six Base58 characters"),(!pe(E.type)||!Tn.includes(E.type))&&o("action_type",`${b}.type`,`invalid action type ${String(E.type)}`),pe(E.content)||o("content",`${b}.content`,"content must be a string"),"emotion"in E&&o("v3_field",`${b}.emotion`,"Script v4 does not allow emotion"),Ci(E.extend,`${b}.extend`,o),E.type==="dialogue"||E.type==="inner_thought")if(E.parenthetical!==void 0&&!pe(E.parenthetical)&&o("parenthetical",`${b}.parenthetical`,"parenthetical must be a string"),!tt(E.speaker))o("speaker",`${b}.speaker`,"dialogue/inner_thought requires a speaker");else if(pe(E.speaker.actor_id)){("kind"in E.speaker||"label"in E.speaker)&&o("speaker_shape",`${b}.speaker`,"actor speaker cannot contain non-actor speaker fields");let R=E.speaker.actor_id;(!$("actor",R)||r.get(R)!=="actor")&&o("speaker_actor",`${b}.speaker.actor_id`,`actor ${R} not found`);let I=_.get(R),O=s.get(R),N=pe(E.speaker.state_id)&&O?.has(E.speaker.state_id)?E.speaker.state_id:void 0,U=O?.has("default")?"default":O?.values().next().value,M=N?[N]:U?[U]:[],V=$("scene",m.scene_id)&&$("actor",R)&&M.length>0?`scriptctl scene-ref ${m.scene_id} ${R} ${M.map(F=>`--state ${F}`).join(" ")} -p "$SCRIPT"`:void 0;if(I||o("actor_not_in_scene",`${b}.speaker.actor_id`,`actor ${R} is not referenced by this scene`,V),E.speaker.state_id!==void 0&&(!pe(E.speaker.state_id)||!I?.has(E.speaker.state_id))){let F=N?[...new Set([...I??[],N])].sort():[],Re=$("scene",m.scene_id)&&$("actor",R)&&F.length>0?`scriptctl scene-ref ${m.scene_id} ${R} ${F.map(X=>`--state ${X}`).join(" ")} -p "$SCRIPT"`:V;o("speaker_state",`${b}.speaker.state_id`,`speaker state ${String(E.speaker.state_id)} is not in this scene's actor state_ids`,Re)}}else pe(E.speaker.kind)?(("actor_id"in E.speaker||"state_id"in E.speaker)&&o("speaker_shape",`${b}.speaker`,"non-actor speaker cannot contain actor speaker fields"),Vn.includes(E.speaker.kind)||o("speaker_kind",`${b}.speaker.kind`,"invalid non-actor speaker kind"),E.speaker.label!==void 0&&!pe(E.speaker.label)&&o("speaker_label",`${b}.speaker.label`,"speaker label must be a string")):o("speaker",`${b}.speaker`,"speaker needs actor_id or kind");else"parenthetical"in E&&o("parenthetical_type",`${b}.parenthetical`,"parenthetical only belongs to speaking actions"),"speaker"in E&&o("speaker_type",`${b}.speaker`,"speaker only belongs to speaking actions");if(E.transition_prompt!==void 0){let R=E.transition_prompt;!tt(R)||!pe(R.target)||!pe(R.process)||R.process===""||!pe(R.contrast)||R.contrast===""?o("transition_prompt",`${b}.transition_prompt`,"transition_prompt requires non-empty target/process/contrast"):r.has(R.target)||o("transition_target",`${b}.transition_prompt.target`,`asset ${R.target} not found`)}}),Us(m.actions,`${y}.actions`,o)})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}function Fo(e,t=new Set,n){try{return n?Ar(e,t,n):Ar(e,t)}catch(o){throw o?.code!==Mc?o:new S(`Could not generate an unused ${e} ID.`,{exitCode:k,errorCode:"ID_SPACE_RETRY_EXHAUSTED",hint:"Retry the command. If this persists, inspect the configured ID generator."})}}function Ae(e,t=[]){throw new S(e,{exitCode:k,errorCode:"CREATIVE_DRAFT_INVALID",hint:"Use the readable creative draft schema; do not include Script IDs or .scriptctl syntax.",data:{actual:t.map(String)}})}function Gn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Z(e,t=""){return String(e??"").replace(/\s+/gu," ").trim()||t}function $w(e,t){let n=Number(e);return(!Number.isSafeInteger(n)||n<1)&&Ae(`${t} must be a positive integer.`,[e]),n}function Dw(e){return e===void 0?{}:(Gn(e)||Ae("Action extensions must be an object."),structuredClone(e))}function Gw(e){let t=new Set;for(let n of e.actors){t.add(n.actor_id);for(let o of n.states)t.add(o.state_id)}for(let n of e.locations){t.add(n.location_id);for(let o of n.states)t.add(o.state_id)}for(let n of e.props){t.add(n.prop_id);for(let o of n.states)t.add(o.state_id)}for(let n of e.episodes){t.add(n.episode_id);for(let o of n.scenes){t.add(o.scene_id);for(let i of o.actions)t.add(i.action_id)}}return t}function uo(e,t,n){for(let o=0;o<128;o+=1){let i=fu.createHash("sha256").update(`${e}:${t}:${o}`).digest(),r="";for(let c=0;c<6;c+=1)r+=Ui[i[c]%Ui.length];let s=`${Pi[e]}${r}`;if(!n.has(s))return n.add(s),s}Ae(`Could not allocate a stable ${e} ID.`)}function Bw(e){let t=Z(e).match(/^(\d+):([0-5]\d)(?:\.(\d{1,3}))?$/u);return t?(Number(t[1])*60+Number(t[2]))*1e3+Number((t[3]??"").padEnd(3,"0")):null}function Jw(e){return`${Math.floor(e/6e4)}:${String(Math.floor(e%6e4/1e3)).padStart(2,"0")}.${String(e%1e3).padStart(3,"0")}`}function jw(e){let t=Number(e.extend?.duration_ms??e.extend?.rewrite_duration_ms);return Number.isFinite(t)&&t>0?Math.round(t):1200}function Kw(e){let t=0;for(let n of e.scenes.flatMap(o=>o.actions))t=(Bw(n.extend?.timestamp)??t)+jw(n);return t}function mu(e){return e===void 0?[]:((!Array.isArray(e)||!e.every(Gn))&&Ae("Asset variants must be an array of readable objects."),e)}function zw(e,t){let n=e.assets;if(n===void 0)return[];Gn(n)||Ae("assets must be an object.");let o=n[t];return o===void 0?[]:((!Array.isArray(o)||!o.every(Gn))&&Ae(`assets.${t} must be an array.`),o)}function Hw(e,t){return e==="actors"?t.actor_name:e==="locations"?t.location_name:t.prop_name}function Fw(e,t){return e[t]}function Qw(e,t){return[Hw(e,t),...t.aliases??[]].map(dt)}function gu(e,t,n){let o=dt(n);return zw(e,t).find(i=>[i.name,...Array.isArray(i.aliases)?i.aliases:[]].map(r=>dt(Z(r))).includes(o))??null}function hu(e,t){if(!e)return null;let n=dt(t);return mu(e.variants).find(o=>{let i=dt(Z(o.name));return i===n||["default","\u9ED8\u8BA4"].includes(n)&&["default","\u9ED8\u8BA4"].includes(i)})??null}function yu(e,t,n){let o=hu(e,n),i=Z(o?.description);return(!o||!i)&&Ae(`${t}/${n} is a new variant and requires a readable assets declaration with a self-contained description.`),o}function Yw(e,t){let n=Z(t?.name);return n&&!["default","\u9ED8\u8BA4"].includes(dt(n))?n:e==="actors"?"\u57FA\u7840\u9020\u578B":e==="locations"?"\u5E38\u89C4\u5E03\u7F6E":"\u57FA\u7840\u5916\u89C2"}function qw(e,t,n,o,i,r){let s=gu(t,n,o);s||Ae(`${o} is not an existing ${n} asset and has no readable declaration.`);let c=Z(s.name,o),a=mu(s.variants),d=hu(s,"\u9ED8\u8BA4")??a[0]??null;n==="actors"&&!Z(s.description)&&Ae(`${c} requires an identity description separate from its appearance variants.`),n==="actors"&&!Z(d?.description)&&Ae(`${c} requires its first variant to provide a self-contained base appearance description.`);let p=[{state_id:"default",state_name:Yw(n,d),description:Z(d?.description,Z(s.description,`${c}\u7684\u57FA\u7840\u53C2\u8003\u5916\u89C2\u3002`))}];for(let u of a){let g=Z(u.name);if(u===d||!g||["default","\u9ED8\u8BA4"].includes(dt(g)))continue;let h=uo("state",`${n}:${c}:${g}`,i);p.push({state_id:h,state_name:g,description:Z(yu(s,c,g).description)}),r.states.push(`${c}/${g}`)}let l={aliases:Array.isArray(s.aliases)?[...new Set(s.aliases.map(u=>Z(u)).filter(u=>u&&u!==c))]:[],importance:s.importance==="background"?"background":"featured",description:Z(s.description,`${c}\u7684\u57FA\u7840\u8BBE\u5B9A\u3002`),states:p};if(n==="actors"){let u={...l,actor_id:uo("actor",c,i),actor_name:c,...s.roleType==="\u4E3B\u89D2"||s.roleType==="\u914D\u89D2"?{role_type:s.roleType}:{}};return e.actors.push(u),r.actors.push(c),u}if(n==="locations"){let u={...l,location_id:uo("location",c,i),location_name:c};return e.locations.push(u),r.locations.push(c),u}let f={...l,prop_id:uo("prop",c,i),prop_name:c};return e.props.push(f),r.props.push(c),f}function Cs(e,t,n,o,i,r){let s=Z(o);s||Ae(`${n} reference requires a readable name.`);let c=dt(s);return Fw(e,n).find(d=>Qw(n,d).includes(c))??qw(e,t,n,s,i,r)}function kr(e,t,n,o,i,r){let s=Z(t,"\u9ED8\u8BA4"),c=dt(s),a=e.states.find(u=>dt(u.state_name)===c||u.state_id==="default"&&["default","\u9ED8\u8BA4"].includes(c));if(a)return a.state_id;let d="actor_name"in e?e.actor_name:"location_name"in e?e.location_name:e.prop_name,p=gu(n,o,d),l=yu(p,d,s),f={state_id:uo("state",`${d}:${s}`,i),state_name:s,description:Z(l.description)};return e.states.push(f),r.states.push(`${d}/${s}`),f.state_id}function uu(e,t){return e===void 0?[]:((!Array.isArray(e)||!e.every(Gn))&&Ae(`${t} must be an array of readable references.`),e)}function Ps(e,t,n){let o=structuredClone(e);for(let i of t){let r=o.find(s=>n(s)===n(i));r?r.state_ids=[...new Set([...r.state_ids,...i.state_ids])].sort():o.push(structuredClone(i))}return o}function Zw(e,t){return!!(e&&e.location?.location_id&&t.location?.location_id&&e.location.location_id===t.location.location_id&&Z(e.environment?.space)===Z(t.environment?.space)&&Z(e.environment?.time)===Z(t.environment?.time))}function Ww(e,t,n,o,i,r,s,c){(!Array.isArray(e)||e.length===0||!e.every(Gn))&&Ae("scene.actions must contain at least one readable Action.");let a=structuredClone(o),d=r;return{actions:e.map((l,f)=>{let u=Z(l.type,"action");["action","transition","dialogue","inner_thought"].includes(u)||Ae(`Action ${f+1} has an unsupported type.`,[u]);let g=Z(l.content);g||Ae(`Action ${f+1} has empty content.`);let h=Math.max(400,Math.min(8e3,Math.round(Number(l.durationMs)||Number(l.weight||1)*1200))),m=Dw(l.extensions);m.timestamp=Jw(d),m.duration_ms=h,m.rewrite_duration_ms!==void 0&&(m.rewrite_duration_ms=h);let w={action_id:uo("action",`${i}:${f+1}:${g}`,s),type:u,content:g,extend:m};if(d+=h,u==="action"||u==="transition")return w;let y=Z(l.speaker);y||Ae(`Action ${f+1} requires a speaker.`);let _=y.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");new RegExp(`^${_}\\s*[:\uFF1A]`,"iu").test(g)&&Ae(`Action ${f+1} repeats the speaker name in dialogue content.`),/^(?:“[^”]+”|「[^」]+」|『[^』]+』|"[^"]+")$/u.test(g)&&Ae(`Action ${f+1} wraps dialogue content in quotation marks.`);let x=dt(y);if(["\u65C1\u767D","narrator"].includes(x))return{...w,speaker:{kind:"broadcast",label:"\u65C1\u767D"},...Z(l.parenthetical)?{parenthetical:Z(l.parenthetical)}:{}};if(["\u753B\u5916\u97F3","offscreen"].includes(x))return{...w,speaker:{kind:"offscreen",label:"\u753B\u5916\u97F3"},...Z(l.parenthetical)?{parenthetical:Z(l.parenthetical)}:{}};let E=Cs(t,n,"actors",y,s,c),A=Z(l.speakerVariant),b=a.find(R=>R.actor_id===E.actor_id),C;if(A)C=kr(E,A,n,"actors",s,c),b?b.state_ids=[...new Set([...b.state_ids,C])].sort():a.push({actor_id:E.actor_id,state_ids:[C]});else if(!b){let R=kr(E,"\u9ED8\u8BA4",n,"actors",s,c);a.push({actor_id:E.actor_id,state_ids:[R]})}return{...w,speaker:{actor_id:E.actor_id,...C?{state_id:C}:{}},...Z(l.parenthetical)?{parenthetical:Z(l.parenthetical)}:{}}}),actorRefs:a}}function wu(e,t){(!Gn(t)||t.version!==1)&&Ae("Creative draft version must be 1."),(!Gn(t.episode)||!Gn(t.scene))&&Ae("Creative draft requires episode and scene objects.");let n=structuredClone(t),o=n.episode,i=n.scene,r=structuredClone(e),s=Gw(r),c={actors:[],locations:[],props:[],states:[]},a=$w(o.number,"episode.number");a>r.episodes.length+1&&Ae("Episodes must be composed in order.",[a]);let d=r.episodes[a-1];d?(Z(d.title)||(d.title=Z(o.title,`\u7B2C ${a} \u96C6`)),Z(d.synopsis)||(d.synopsis=Z(o.synopsis,`\u7B2C ${a} \u96C6\u5267\u60C5\u3002`))):(d={episode_id:uo("episode",`episode:${a}`,s),title:Z(o.title,`\u7B2C ${a} \u96C6`),synopsis:Z(o.synopsis,`\u7B2C ${a} \u96C6\u5267\u60C5\u3002`),scenes:[]},r.episodes.push(d));let p=Cs(r,n,"locations",i.location,s,c),l=kr(p,i.locationVariant,n,"locations",s,c),f=uu(i.actors,"scene.actors").map(I=>{let O=Cs(r,n,"actors",I.name,s,c);return{actor_id:O.actor_id,state_ids:[kr(O,I.variant,n,"actors",s,c)]}}),u=Ps([],f,I=>I.actor_id),g=uu(i.props,"scene.props").map(I=>{let O=Cs(r,n,"props",I.name,s,c);return{prop_id:O.prop_id,state_ids:[kr(O,I.variant,n,"props",s,c)]}}),h=Ps([],g,I=>I.prop_id),m=d.scenes.at(-1),w={scene_id:uo("scene",`episode:${a}:scene:${d.scenes.length+1}:${Z(i.title)}`,s),environment:{space:Z(i.space,"interior"),time:Z(i.time,"day")},location:{location_id:p.location_id,state_ids:[l]},actors:u,props:h,actions:[],extend:{scene_title:Z(i.title,`\u7B2C ${d.scenes.length+1} \u573A`)}},y=Z(i.boundary,"auto");["auto","new","continue"].includes(y)||Ae("scene.boundary must be auto, new, or continue.");let _=Zw(m,w);y==="continue"&&!_&&Ae("scene.boundary=continue requires the same location, space, and time as the previous scene.");let x=y!=="new"&&_,E=x&&m?m:w,A=x?d.scenes.length:d.scenes.length+1,b=Ps(E.actors,w.actors,I=>I.actor_id),C=Ww(i.actions,r,n,b,E.scene_id,Kw(d),s,c);E.actors=C.actorRefs,E.props=Ps(E.props,w.props,I=>I.prop_id),E.location&&w.location&&(E.location.state_ids=[...new Set([...E.location.state_ids,...w.location.state_ids])].sort()),E.actions.push(...C.actions),x||d.scenes.push(E);let R=Pe(r);return R.ok||Ae("Composed screenplay does not pass Script v4 validation.",R.errors.slice(0,12).map(I=>`${I.path}: ${I.message}`)),{script:r,validation:R,episodeNumber:a,sceneNumber:A,sceneId:E.scene_id,actionIds:C.actions.map(I=>I.action_id),joinedPreviousScene:x,created:c}}function He(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function wn(e,t){return e[t]===void 0||typeof e[t]=="string"}function Lc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Lc):He(e)&&Object.values(e).every(Lc)}function Ti(e){return e.extend===void 0||He(e.extend)&&Object.values(e.extend).every(Lc)}function Uc(e){return e==="default"||$("state",e)}function Xw(e){return He(e)&&Uc(e.state_id)&&typeof e.state_name=="string"&&typeof e.description=="string"&&Ti(e)}function Pc(e){return typeof e.importance=="string"&&Pt.has(e.importance)&&typeof e.description=="string"&&(e.aliases===void 0||Array.isArray(e.aliases)&&e.aliases.every(t=>typeof t=="string"))&&Array.isArray(e.states)&&e.states.every(Xw)&&Ti(e)}function e_(e){return He(e)&&$("actor",e.actor_id)&&typeof e.actor_name=="string"&&(e.role_type===void 0||typeof e.role_type=="string"&&po.has(e.role_type))&&Pc(e)}function t_(e){return He(e)&&$("location",e.location_id)&&typeof e.location_name=="string"&&Pc(e)}function n_(e){return He(e)&&$("prop",e.prop_id)&&typeof e.prop_name=="string"&&Pc(e)}function Cc(e){return Array.isArray(e)&&e.every(Uc)}function o_(e){return He(e)&&$("actor",e.actor_id)&&Cc(e.state_ids)}function i_(e){return He(e)&&$("location",e.location_id)&&Cc(e.state_ids)}function r_(e){return He(e)&&$("prop",e.prop_id)&&Cc(e.state_ids)}function s_(e){return $("actor",e.actor_id)&&(e.state_id===void 0||Uc(e.state_id))}function a_(e){return typeof e.kind=="string"&&Ho.has(e.kind)&&wn(e,"label")}function c_(e){return!(!He(e)||!$("action",e.action_id)||typeof e.type!="string"||!qt.has(e.type)||typeof e.content!="string"||!wn(e,"parenthetical")||!Ti(e)||(e.type==="dialogue"||e.type==="inner_thought")&&(!He(e.speaker)||!s_(e.speaker)&&!a_(e.speaker))||e.transition_prompt!==void 0&&(!He(e.transition_prompt)||!$("actor",e.transition_prompt.target)&&!$("location",e.transition_prompt.target)&&!$("prop",e.transition_prompt.target)||typeof e.transition_prompt.process!="string"||typeof e.transition_prompt.contrast!="string"))}function d_(e){return!(!He(e)||!$("scene",e.scene_id)||!Array.isArray(e.actors)||!e.actors.every(o_)||!Array.isArray(e.props)||!e.props.every(r_)||!Array.isArray(e.actions)||!e.actions.every(c_)||!Ti(e)||e.location!==null&&!i_(e.location)||e.environment!==void 0&&(!He(e.environment)||!wn(e.environment,"space")||!wn(e.environment,"time")))}function p_(e){return He(e)&&$("episode",e.episode_id)&&wn(e,"title")&&wn(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(d_)&&Ti(e)}function l_(e){return He(e)&&e.version===4&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&wn(e,"worldview_raw")&&wn(e,"synopsis")&&wn(e,"logline")&&wn(e,"theme")&&(e.main_characters===void 0||Array.isArray(e.main_characters)&&e.main_characters.every(t=>He(t)&&typeof t.name=="string"&&typeof t.role=="string"))&&Array.isArray(e.actors)&&e.actors.every(e_)&&Array.isArray(e.locations)&&e.locations.every(t_)&&Array.isArray(e.props)&&e.props.every(n_)&&Array.isArray(e.episodes)&&e.episodes.every(p_)&&Ti(e)}function Vi(e){let t=Pe(e);if(t.ok)return e;throw new S("The local file is not a valid Script v4 document.",{exitCode:k,errorCode:"SCRIPT_V4_INVALID",hint:"Run `scriptctl validate --script-path <path>` and repair the reported v4 fields.",data:{expected:["A valid Script v4 document"],actual:t.errors.slice(0,20).map(n=>`${n.path}: ${n.message}`)}})}function _n(e){if(l_(e))return e;throw new S("The local file is not a structurally readable Script v4 document.",{exitCode:k,errorCode:"SCRIPT_V4_SHAPE_INVALID",hint:"Repair the local Script v4 structure, then rerun the command.",data:{expected:["Script v4 with typed assets, episodes, scenes, references, and actions"],actual:[Array.isArray(e)?"array":typeof e]}})}import*as br from"node:crypto";import*as $e from"node:fs";import*as Ct from"node:path";import u_ from"proper-lockfile";function Vc(e){if(Array.isArray(e))return e.map(Vc);if(e!==null&&typeof e=="object"){let t=e,n={};for(let o of Object.keys(t).sort())n[o]=Vc(t[o]);return n}return e}function Be(e){let t=JSON.stringify(Vc(e));return`sha256:${br.createHash("sha256").update(t).digest("hex")}`}function Or(e){return $e.existsSync(e)?`sha256:${br.createHash("sha256").update($e.readFileSync(e)).digest("hex")}`:null}function vr(e,t){let n=Or(e);if(n!==t)throw new S("The local script changed while the command was running.",{exitCode:k,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and retry the command.",data:{actual:[`loadedFingerprint=${t??"<missing>"}`,`currentFingerprint=${n??"<missing>"}`,e]}})}function Rr(e){let t=Ct.resolve(e),n=Ct.join(Ct.dirname(t),".scriptctl"),o=Ct.basename(t);return{scriptPath:t,stateDir:n,metadataPath:Ct.join(n,`${o}.working-copy.json`),lockPath:Ct.join(n,o)}}async function Ts(e,t){let n=Rr(e);$e.mkdirSync(n.stateDir,{recursive:!0});let o=null;try{o=await u_.lock(n.lockPath,{realpath:!1,stale:12e4,update:1e4,retries:{retries:60,factor:1,minTimeout:500,maxTimeout:500}})}catch(i){throw new S("Timed out waiting for the script file lock.",{exitCode:ee,errorCode:"WORKING_COPY_LOCK_TIMEOUT",hint:"Wait for the other scriptctl command to finish, then retry.",data:{actual:[n.scriptPath,i instanceof Error?i.message:String(i)]}})}try{return await t()}finally{await o()}}function Fe(e,t){Vs(e,`${JSON.stringify(t,null,2)}
123
- `)}function Vs(e,t){let n=Ct.dirname(e);$e.mkdirSync(n,{recursive:!0});let o=Ct.join(n,`.${Ct.basename(e)}.${process.pid}.${br.randomUUID()}.tmp`),i=$e.openSync(o,"wx");try{$e.writeFileSync(i,t,"utf-8"),$e.fsyncSync(i)}finally{$e.closeSync(i)}$e.renameSync(o,e)}function $s(e){let t=Rr(e).metadataPath;if(!$e.existsSync(t))return null;let n;try{n=JSON.parse($e.readFileSync(t,"utf-8"))}catch(i){throw Tc(t,i instanceof Error?i.message:String(i))}if(n===null||typeof n!="object"||Array.isArray(n))throw Tc(t,"metadata root must be an object");let o=n;if(o.schemaVersion!==1||typeof o.projectGroupNo!="string"||o.projectGroupNo.length===0||typeof o.apiBaseUrl!="string"||o.apiBaseUrl.length===0||!Number.isInteger(o.baseRevision)||Number(o.baseRevision)<0||typeof o.baseContentHash!="string"||!o.baseContentHash.startsWith("sha256:"))throw Tc(t,"required fields are missing or invalid");return{schemaVersion:1,projectGroupNo:o.projectGroupNo,apiBaseUrl:o.apiBaseUrl,baseRevision:Number(o.baseRevision),baseContentHash:o.baseContentHash}}function Ds(e,t){Fe(Rr(e).metadataPath,t)}function Tc(e,t){return new S("Working copy metadata is invalid.",{exitCode:k,errorCode:"WORKING_COPY_METADATA_INVALID",hint:"Run `scriptctl checkout --discard-local` to recreate the working copy metadata.",data:{expected:["valid scriptctl working-copy metadata"],actual:[e,t]}})}function Gt(e,t){let n;try{n=JSON.parse($e.readFileSync(e,"utf-8"))}catch(i){throw new S("The local script changed while the command was running.",{exitCode:k,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and re-apply the operation.",data:{actual:[e,i instanceof Error?i.message:String(i)]}})}let o=Be(n);if(o!==t)throw new S("The local script changed while the command was running.",{exitCode:k,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and re-apply the operation.",data:{actual:[`loadedHash=${t}`,`currentHash=${o}`,e]}})}function v(e){return e==null?"":String(e)}function ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bn(e){return Array.isArray(e)}function re(e){return Array.isArray(e)?e:[]}function $c(e,t=[]){throw new S(e,{exitCode:J,errorCode:"CREATIVE_DRAFT_USAGE_INVALID",hint:"Run `scriptctl authoring compose <draft.json> --script-path <script.json>` and apply the returned plan digest.",data:{actual:t}})}function _u(e,t){let n=Su.resolve(e),o;try{o=xu.readFileSync(n)}catch{throw new S(`${t} does not exist.`,{exitCode:k,errorCode:"CREATIVE_DRAFT_SOURCE_UNAVAILABLE",data:{actual:[n]}})}try{return{path:n,bytes:o,value:JSON.parse(o.toString("utf-8"))}}catch(i){throw new S(`${t} is not valid JSON.`,{exitCode:k,errorCode:"CREATIVE_DRAFT_JSON_INVALID",data:{actual:[n,i instanceof Error?i.message:String(i)]}})}}function Iu(e){let t=Array.isArray(e._args)?e._args:[],n=typeof t[0]=="string"?t[0]:"";(!n||n==="-")&&$c("Creative draft input must be a named JSON file.",[n||"<missing>"]);let o=_u(n,"The creative draft"),i=ge(e),r=_u(i,"The target Script v4 file"),s=_n(r.value),c=Be(s),a=wu(s,o.value),d=`sha256:${Eu.createHash("sha256").update(o.bytes).digest("hex")}`,p={version:1,op:"compose",sourceDigest:d,baseline:c,proposed:Be(a.script),episodeNumber:a.episodeNumber,sceneNumber:a.sceneNumber,sceneId:a.sceneId,actionIds:a.actionIds,joinedPreviousScene:a.joinedPreviousScene,created:a.created},l=`sha256:${Ee(JSON.stringify(p))}`,f=e.apply===!0,u=v(e.plan).trim();if(f&&!u&&$c("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!f&&u&&$c("--plan is only valid together with --apply.",[`plan=${u}`]),f&&u!==l)throw new S("The supplied plan does not match the current draft or script baseline.",{exitCode:k,errorCode:"CREATIVE_DRAFT_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[l],actual:[u]}});return f&&(Gt(i,c),Fe(i,a.script)),[{text:[`${f?"Applied":"Planned"} readable scene draft as episode ${a.episodeNumber}, scene ${a.sceneNumber}${a.joinedPreviousScene?" (joined previous scene)":""}`,`plan: ${l}`].join(`
124
- `),data:{op:"compose",applied:f,source_path:o.path,source_digest:d,script_path:i,baseline:c,plan_digest:l,episode_number:a.episodeNumber,scene_number:a.sceneNumber,scene_id:a.sceneId,action_ids:a.actionIds,joined_previous_scene:a.joinedPreviousScene,created:a.created,validation:a.validation}},B]}import*as Uu from"node:fs";import*as Pu from"node:path";var Zt={line:1,column:1};function f_(e){let t=[];for(let n of e.actors){let o=structuredClone(n);o.states=[],t.push({declarationKind:"actor",value:o,source:Zt});for(let i of n.states)t.push(Dc("actor",n.actor_id,i))}for(let n of e.locations){let o=structuredClone(n);o.states=[],t.push({declarationKind:"location",value:o,source:Zt});for(let i of n.states)t.push(Dc("location",n.location_id,i))}for(let n of e.props){let o=structuredClone(n);o.states=[],t.push({declarationKind:"prop",value:o,source:Zt});for(let i of n.states)t.push(Dc("prop",n.prop_id,i))}return t}function Dc(e,t,n){return{declarationKind:"state",ownerKind:e,ownerId:t,value:structuredClone(n),source:Zt}}function Au(e){let t={kind:"script",title:e.title,worldview:e.worldview,style:e.style,episodes:structuredClone(e.episodes),source:Zt};return e.worldview_raw!==void 0&&(t.worldviewRaw=e.worldview_raw),e.synopsis!==void 0&&(t.synopsis=e.synopsis),e.logline!==void 0&&(t.logline=e.logline),e.theme!==void 0&&(t.theme=e.theme),e.main_characters!==void 0&&(t.mainCharacters=structuredClone(e.main_characters)),e.extend!==void 0&&(t.extend=structuredClone(e.extend)),{version:1,declarations:f_(e),targets:[t],targetKind:"script"}}function $i(e,t){return{version:1,declarations:[],targets:t,targetKind:e}}function m_(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function g_(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function fe(e,t,n){let o=[e,...t].map(m_).join("|"),i=g_(n);return`[${o}]${i.length>0?` ${i}`:""}`}function Bc(e){if(Array.isArray(e))return e.map(Bc);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=Bc(e[n]);return t}return e}function Jn(e){return e===void 0?[]:[fe("extensions",[],""),...Object.keys(e).sort().map(t=>fe("extend",[t],JSON.stringify(Bc(e[t]))))]}function h_(e){return"actor_id"in e?e.state_id===void 0?e.actor_id:`${e.actor_id}/${e.state_id}`:e.label===void 0?e.kind:`${e.kind}:${e.label}`}function ku(e){let t=Jn(e.extend);if(e.transition_prompt!==void 0&&t.push(fe("prompt",[e.transition_prompt.target,e.transition_prompt.process,e.transition_prompt.contrast],"")),e.type==="dialogue"||e.type==="inner_thought"){let o=e.type==="dialogue"?"dlg":"think",i=[h_(e.speaker)];return e.emotion!==void 0&&i.push(e.emotion),t.push(fe(o,i,e.content)),t}let n=e.type==="action"?"act":"trans";return t.push(fe(n,e.emotion===void 0?[]:[e.emotion],e.content)),t}function Jc(e,t){let n=[...Jn(e.extend),`<scene ${t}>`];if(e.environment!==void 0&&(e.environment.time!==void 0?n.push(fe("environment",[e.environment.space??"",e.environment.time],"")):e.environment.space!==void 0?n.push(fe("environment",[e.environment.space],"")):n.push(fe("environment",[],""))),e.location===null)n.push(fe("location",[],""));else{let o=[e.location.location_id];e.location.state_id!==void 0&&o.push(e.location.state_id),n.push(fe("location",o,""))}for(let o of e.actors){let i=[o.actor_id];o.state_id!==void 0&&i.push(o.state_id),n.push(fe("cast",i,""))}for(let o of e.props){let i=[o.prop_id];o.state_id!==void 0&&i.push(o.state_id),n.push(fe("prop",i,""))}n.push("","<body>");for(let o of e.actions)n.push(...ku(o));return n.push("</body>","","</scene>"),n}function Gc(e){let t=[...Jn(e.extend),`<episode id=${e.episode_id}>`];return e.title!==void 0&&t.push(fe("title",[],e.title)),e.synopsis!==void 0&&t.push(fe("synopsis",[],e.synopsis)),(e.title!==void 0||e.synopsis!==void 0)&&e.scenes.length>0&&t.push(""),e.scenes.forEach((n,o)=>{t.push(...Jc(n,`id=${n.scene_id}`)),o<e.scenes.length-1&&t.push("")}),t.push("</episode>"),t}function y_(e){if(e.declarationKind==="state")return w_(e.ownerKind,e.ownerId,e.value);let t=e.value,n=Jn(t.extend);t.aliases!==void 0&&n.push(fe("aliases",[],""));for(let o of t.aliases??[])n.push(fe("alias",[],o));if(e.declarationKind==="actor"){let o=e.value,i=[o.actor_id,o.actor_name,o.importance];o.role_type!==void 0&&i.push(o.role_type),n.push(fe("actor",i,o.description))}else if(e.declarationKind==="location"){let o=e.value;n.push(fe("location",[o.location_id,o.location_name,o.importance],o.description))}else{let o=e.value;n.push(fe("prop",[o.prop_id,o.prop_name,o.importance],o.description))}return n}function w_(e,t,n){return[...Jn(n.extend),fe("state",[`${e}:${t}`,n.state_id,n.state_name],n.description)]}function __(e){switch(e.kind){case"script":{let t=[...Jn(e.extend),"<script>"];if(t.push(fe("title",[],e.title)),t.push(fe("worldview",[],e.worldview)),e.worldviewRaw!==void 0&&t.push(fe("worldview-raw",[],e.worldviewRaw)),t.push(fe("style",[],e.style)),e.synopsis!==void 0&&t.push(fe("synopsis",[],e.synopsis)),e.logline!==void 0&&t.push(fe("logline",[],e.logline)),e.theme!==void 0&&t.push(fe("theme",[],e.theme)),e.mainCharacters!==void 0){t.push(fe("main-characters",[],""));for(let n of e.mainCharacters)t.push(fe("main-character",[n.name,n.role],""))}return e.episodes.length>0&&t.push(""),e.episodes.forEach((n,o)=>{t.push(...Gc(n)),o<e.episodes.length-1&&t.push("")}),t.push("</script>"),t}case"episode":return Gc(e.value);case"episode-span":{let t=[...Jn(e.extend),`<episode-span from=${e.from} through=${e.through}>`];return e.episodes.forEach((n,o)=>{t.push(...Gc(n)),o<e.episodes.length-1&&t.push("")}),t.push("</episode-span>"),t}case"scene":return Jc(e.value,`id=${e.value.scene_id} parent=${e.parent}`);case"scene-span":{let t=[...Jn(e.extend),`<scene-span parent=${e.parent} from=${e.from} through=${e.through}>`];return e.scenes.forEach((n,o)=>{t.push(...Jc(n,`id=${n.scene_id}`)),o<e.scenes.length-1&&t.push("")}),t.push("</scene-span>"),t}case"action-span":{let t=[...Jn(e.extend),`<action-span parent=${e.parent} from=${e.from} through=${e.through}>`,"<body>"];for(let n of e.actions)t.push(...ku(n));return t.push("</body>","</action-span>"),t}}}function bu(e){let t=["<authoring version=1>",""];if(e.declarations.length>0){t.push("<create>");for(let n of e.declarations)t.push(...y_(n));t.push("</create>","")}return e.targets.forEach((n,o)=>{t.push(...__(n)),o<e.targets.length-1&&t.push("")}),t.push("","</authoring>"),`${t.join(`
122
+ `,x=class extends Error{exitCode;errorCode;hint;data;constructor(t,n){super(t),this.name="CliError",this.exitCode=n.exitCode,this.errorCode=n.errorCode,this.hint=n.hint,this.data=n.data??{}}};function Lw(e){return new Ns(e)}function ru(e){return Lw(e).directDir}function me(e){let t=e.script_path??e.scriptPath;return Sr.resolve(typeof t=="string"&&t.length>0?t:Nw)}function Ir(e){return Ls.readJson(e)}function Ac(e,t){Ls.writeJson(e,t)}function zo(e){return Ls.exists(e)}function _e(e){return Ic.createHash("sha256").update(e,"utf-8").digest("hex")}function kc(e){let t=Ic.createHash("sha256"),n=Ni.openSync(e,"r");try{let o=Buffer.alloc(1048576);for(;;){let i=Ni.readSync(n,o,0,o.length,null);if(i<=0)break;t.update(o.subarray(0,i))}}finally{Ni.closeSync(n)}return t.digest("hex")}var Nt={policy:["content_blocked"],network:["dns_failed","connection_refused","connection_reset","network_unreachable","tls_failed","network_failed"],timeout:["connect_timeout","request_timeout","media_processing_timeout"],rate_limit:["rate_limited"],authentication:["authentication_failed"],authorization:["permission_denied"],provider:["resource_not_found","provider_unavailable","request_rejected","attempts_exhausted"],media:["media_upload_failed","media_processing_failed","media_too_large","unsupported_media"],response:["output_truncated","empty_response","malformed_response"],pipeline:["serial_parse_failed","source_mismatch","pipeline_mismatch"],validation:["script_validation_failed"],cancelled:["cancelled"],unknown:["unknown","legacy_unclassified"]};function Lt(e,t){return typeof e=="string"&&t.some(n=>n===e)}function su(e,t){switch(e){case"policy":return Lt(t,Nt.policy)?{failure_type:e,failure_code:t}:null;case"network":return Lt(t,Nt.network)?{failure_type:e,failure_code:t}:null;case"timeout":return Lt(t,Nt.timeout)?{failure_type:e,failure_code:t}:null;case"rate_limit":return Lt(t,Nt.rate_limit)?{failure_type:e,failure_code:t}:null;case"authentication":return Lt(t,Nt.authentication)?{failure_type:e,failure_code:t}:null;case"authorization":return Lt(t,Nt.authorization)?{failure_type:e,failure_code:t}:null;case"provider":return Lt(t,Nt.provider)?{failure_type:e,failure_code:t}:null;case"media":return Lt(t,Nt.media)?{failure_type:e,failure_code:t}:null;case"response":return Lt(t,Nt.response)?{failure_type:e,failure_code:t}:null;case"pipeline":return Lt(t,Nt.pipeline)?{failure_type:e,failure_code:t}:null;case"validation":return Lt(t,Nt.validation)?{failure_type:e,failure_code:t}:null;case"cancelled":return Lt(t,Nt.cancelled)?{failure_type:e,failure_code:t}:null;case"unknown":return Lt(t,Nt.unknown)?{failure_type:e,failure_code:t}:null;default:return null}}function Ut(e,t){return{...e,...t}}function Li(e){switch(e.failure_type){case"policy":return{failure_type:e.failure_type,failure_code:e.failure_code};case"network":return{failure_type:e.failure_type,failure_code:e.failure_code};case"timeout":return{failure_type:e.failure_type,failure_code:e.failure_code};case"rate_limit":return{failure_type:e.failure_type,failure_code:e.failure_code};case"authentication":return{failure_type:e.failure_type,failure_code:e.failure_code};case"authorization":return{failure_type:e.failure_type,failure_code:e.failure_code};case"provider":return{failure_type:e.failure_type,failure_code:e.failure_code};case"media":return{failure_type:e.failure_type,failure_code:e.failure_code};case"response":return{failure_type:e.failure_type,failure_code:e.failure_code};case"pipeline":return{failure_type:e.failure_type,failure_code:e.failure_code};case"validation":return{failure_type:e.failure_type,failure_code:e.failure_code};case"cancelled":return{failure_type:e.failure_type,failure_code:e.failure_code};case"unknown":return{failure_type:e.failure_type,failure_code:e.failure_code}}}function Ar(e){return{...e.provider!==void 0?{provider:e.provider}:{},...e.model!==void 0?{model:e.model}:{},...e.operation!==void 0?{operation:e.operation}:{},...e.http_status!==void 0?{http_status:e.http_status}:{},...e.system_code!==void 0?{system_code:e.system_code}:{},...e.provider_source!==void 0?{provider_source:e.provider_source}:{},...e.provider_reason!==void 0?{provider_reason:e.provider_reason}:{},...e.provider_reason_raw!==void 0?{provider_reason_raw:e.provider_reason_raw}:{},...e.finish_message!==void 0?{finish_message:e.finish_message}:{},...e.safety_ratings!==void 0?{safety_ratings:e.safety_ratings}:{},...e.details!==void 0?{details:e.details}:{}}}function au(e,t){if(e.length===0)return Ut({failure_type:"unknown",failure_code:"unknown"},{retryable:!1,message:t});let n=e[0],i=e.every(r=>r.failure_type===n.failure_type&&r.failure_code===n.failure_code)?Li(n):{failure_type:"provider",failure_code:"attempts_exhausted"};return Ut(i,{retryable:e.some(r=>r.retryable),message:t})}function hn(e){let t=e.provider||e.model?`${e.provider??"provider"}/${e.model??"model"} `:"",n=e.provider_reason?` provider_reason=${e.provider_reason}`:"",o=e.system_code?` system_code=${e.system_code}`:"",i=e.http_status!==void 0?` http_status=${e.http_status}`:"",r=e.details?.length?` | ${e.details.join(" | ")}`:"";return`${t}${e.failure_type}/${e.failure_code}${n}${o}${i}: ${e.message}${r}`}import*as Su from"node:crypto";import*as Iu from"node:fs";import*as Au from"node:path";import*as gu from"node:crypto";var Tn=["action","dialogue","inner_thought","transition"],qt=new Set(Tn),Vn=["system","broadcast","offscreen","group"],Ho=new Set(Vn),$n=["featured","background"],Pt=new Set($n),Ui=["\u4E3B\u89D2","\u914D\u89D2"],lo=new Set(Ui),Us=["day","night","dawn","dusk"],bc=new Set(Us);function kr(e){return typeof e=="string"&&bc.has(e)}var Oc=["interior","exterior"],cu=new Set(Oc);function dt(e){return e.normalize("NFKC").toLowerCase()}function du(e){return JSON.stringify([e.code,e.path,e.message])}function vc(e){let t=new Map;for(let n of e){let o=du(n);t.set(o,(t.get(o)??0)+1)}return t}function Rc(e,t){if(e.ok||t.errors.length>=e.errors.length)return!1;let n=vc(e.errors),o=vc(t.errors);for(let[i,r]of o)if(r>(n.get(i)??0))return!1;return!0}function Mc(e,t){let n=vc(e),o=[];for(let i of t){let r=du(i),s=n.get(r)??0;s>0?n.set(r,s-1):o.push(i)}return o}import{customAlphabet as Uw}from"nanoid";var Pi="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Nc=6,Ci={episode:"ep",scene:"scn",action:"ac",actor:"act",location:"loc",prop:"prp",state:"st"},Pw=Uw(Pi,Nc),Cw=`[${Pi}]`,pu=Object.fromEntries(Object.entries(Ci).map(([e,t])=>[e,new RegExp(`^${t}${Cw}{${Nc}}$`)]));function V(e,t){return typeof t=="string"&&pu[e].test(t)}var Lc="ID_SPACE_EXHAUSTED";function br(e,t=new Set,n=Pw){let o=Ci[e];for(let i=0;i<128;i++){let r=`${o}${n()}`;if(!t.has(r))return r}throw Object.assign(new Error(`Could not generate an unused ${e} ID after 128 attempts.`),{code:Lc})}var et=class extends Error{input;constructor(t,n){super(n),this.input=t,this.name="TimestampParseError"}},Tw=/^(\d+):(\d{2})(?:\.(\d{1,3}))?$/,Vw=/^(\d+):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/;function lu(e){return e?Number(e.padEnd(3,"0")):0}function uu(e,t){if(!Number.isSafeInteger(t))throw new et(e,"Timestamp exceeds the supported numeric range.");return t}function fu(e,t){let n=Math.floor(e/1e3),o=Math.floor(n/3600),i=Math.floor(n%3600/60),r=n%60,s=t?`.${t}`:"";return o>0?`${o}:${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}${s}`:`${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}${s}`}function uo(e){let t=e.trim();if(!t)throw new et(e,"Timestamp must not be empty.");let n=t.match(Vw);if(n){let a=Number(n[1]),d=Number(n[2]),p=Number(n[3]),l=n[4];if(d>59)throw new et(e,"Hour-form timestamps require minutes between 00 and 59.");if(p>59)throw new et(e,"Timestamp seconds must be between 00 and 59.");let f=uu(e,((a*60+d)*60+p)*1e3+lu(l));return{canonical:fu(f,l),milliseconds:f,fractionDigits:l?.length??0}}let o=t.match(Tw);if(!o)throw new et(e,"Use M:SS, MM:SS, or H:MM:SS with an optional 1-3 digit fraction.");let i=Number(o[1]),r=Number(o[2]),s=o[3];if(r>59)throw new et(e,"Timestamp seconds must be between 00 and 59.");let c=uu(e,(i*60+r)*1e3+lu(s));return{canonical:fu(c,s),milliseconds:c,fractionDigits:s?.length??0}}function $w(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e.extend;if(!(typeof t!="object"||t===null||Array.isArray(t)))return t.timestamp}function Ps(e,t,n){let o=null;e.forEach((i,r)=>{let s=$w(i);if(s===void 0)return;let c=`${t}[${r}].extend.timestamp`;if(typeof s!="string"){n("timestamp_invalid",c,"timestamp must be a string in M:SS, MM:SS, or H:MM:SS form");return}let a;try{a=uo(s)}catch(d){if(!(d instanceof et))throw d;n("timestamp_invalid",c,d.message);return}o!==null&&a.milliseconds<o.timestamp.milliseconds&&n("timestamp_out_of_order",c,`timestamp ${a.canonical} is earlier than Action ${o.actionIndex+1} timestamp ${o.timestamp.canonical}; equal timestamps are allowed`),o={actionIndex:r,timestamp:a}})}var yt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Dn=e=>Array.isArray(e),Ie=e=>typeof e=="string",Dw=["state_changes","actor_id","speakers","lines"];function wt(e){let t=[],n=[],o=(u,m,h,g)=>t.push({code:u,path:m,message:h,...g?{repair_hint:g}:{}}),i=(u,m,h)=>n.push({code:u,path:m,message:h});if(!yt(e))return{ok:!1,errors:[{code:"not_object",path:"$",message:"script must be an object"}],warnings:n};e.version!==3&&o("version","$.version","version must be 3");for(let u of["title","worldview","style"])Ie(e[u])||o("field",`$.${u}`,`${u} must be a string`);let r=new Map,s=new Map,c=new Map,a=(u,m,h,g,w)=>{if(!Dn(u)){o("field",w,`${w} must be an array`);return}u.forEach((y,_)=>{let S=`${w}[${_}]`;if(!yt(y)){o("asset",S,"asset must be an object");return}let E=y[h];if(!Ie(E)){o("asset_id",`${S}.${h}`,`${h} required`);return}if(s.has(E)&&o("dup_id",`${S}.${h}`,`duplicate id ${E}`),s.set(E,m),!Ie(y[g]))o("asset_name",`${S}.${g}`,`${g} required`);else if(m==="actor"){let M=dt(y[g]),I=c.get(M);I!==void 0?o("dup_actor_name",`${S}.${g}`,`actor name ${y[g]} already belongs to ${I}`):c.set(M,E)}(!Ie(y.importance)||!$n.includes(y.importance))&&o("importance",`${S}.importance`,`importance must be one of ${$n.join("|")}`),Ie(y.description)||o("asset_desc",`${S}.description`,"description must be a string");let A=new Set,b=new Set,U=0;!Dn(y.states)||y.states.length===0?o("states",`${S}.states`,"states must be a non-empty array"):y.states.forEach((M,I)=>{let v=`${S}.states[${I}]`;if(!yt(M)||!Ie(M.state_id)){o("state_id",v,"state_id required");return}A.has(M.state_id)&&o("dup_state",v,`duplicate state_id ${M.state_id}`),A.add(M.state_id),M.state_id==="default"&&U++,Ie(M.state_name)?(b.has(M.state_name)&&o("dup_state_name",`${v}.state_name`,`duplicate state_name ${M.state_name}`),b.add(M.state_name)):o("state_name",`${v}.state_name`,"state_name required")}),Dn(y.states)&&U!==1&&o("default_state",`${S}.states`,`exactly one 'default' state required, found ${U}`),r.set(E,A)})};a(e.actors,"actor","actor_id","actor_name","$.actors"),a(e.locations,"location","location_id","location_name","$.locations"),a(e.props,"prop","prop_id","prop_name","$.props");let d=(u,m,h,g)=>{if(s.get(u)!==h){o("ref",g,`${h} ${u} not found`);return}m!==void 0&&(!Ie(m)||!r.get(u)?.has(m))&&o("state_ref",g,`state ${String(m)} not materialized on ${u}`)},p=(u,m,h,g)=>{if(u===void 0){o("field",g,`${g} required (may be empty array)`);return}if(!Dn(u)){o("field",g,`${g} must be an array`);return}u.forEach((w,y)=>{if(!yt(w)||!Ie(w[h])){o("ref",`${g}[${y}]`,`${h} required`);return}d(w[h],w.state_id,m,`${g}[${y}]`)})},l=(u,m,h,g)=>{if(!yt(u)){o("action",m,"action must be an object");return}for(let y of Dw)y in u&&o("legacy_field",`${m}.${y}`,`v3 forbids action.${y}`);let w=u.type;if((!Ie(w)||!Tn.includes(w))&&o("action_type",`${m}.type`,`invalid action type ${String(w)}`),Ie(u.content)||o("content",`${m}.content`,"content must be a plain-text string"),w==="dialogue"||w==="inner_thought"){let y=u.speaker;if(!yt(y))o("speaker",`${m}.speaker`,"dialogue/inner_thought needs a speaker");else if("kind"in y)(!Ie(y.kind)||!Vn.includes(y.kind))&&o("speaker_kind",`${m}.speaker.kind`,"invalid non-actor speaker kind");else if(Ie(y.actor_id)){if(d(y.actor_id,y.state_id,"actor",`${m}.speaker`),!h.has(y.actor_id)){let _=r.get(y.actor_id),S=Ie(y.state_id)&&_?.has(y.state_id)?y.state_id:_?.has("default")?"default":_?.values().next().value,E=g&&S?`scriptctl scene-ref ${g} actor:${y.actor_id} --state ${S} -p "$SCRIPT"`:void 0;o("actor_not_in_scene",`${m}.speaker.actor_id`,`actor ${y.actor_id} is not referenced by this scene`,E)}}else o("speaker",`${m}.speaker`,"speaker needs actor_id or kind")}},f=e.episodes;return Dn(f)?f.forEach((u,m)=>{let h=`$.episodes[${m}]`;if(!yt(u)||!Ie(u.episode_id)){o("episode_id",h,"episode_id required");return}if(!Dn(u.scenes)){o("scenes",`${h}.scenes`,"scenes must be an array");return}u.scenes.forEach((g,w)=>{let y=`${h}.scenes[${w}]`;if(!yt(g)){o("scene",y,"scene must be an object");return}"context"in g&&o("legacy_field",`${y}.context`,"v3 forbids scene.context"),Ie(g.scene_id)||o("scene_id",y,"scene_id required");let _=g.environment;_===void 0||yt(_)&&(!Ie(_.time)||_.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!yt(_)||_.space!==void 0&&!Ie(_.space)||!Ie(_.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):kr(_.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk"),(g.environment===void 0||yt(g.environment)&&(!Ie(g.environment.space)||g.environment.space.trim()===""))&&i("scene_space_missing",`${y}.environment.space`,"scene interior/exterior is required for production review"),g.location===null&&i("scene_location_missing",`${y}.location`,"scene location is required for production review");let S=g.location;if(S!==null&&(!yt(S)||!Ie(S.location_id)?o("location",`${y}.location`,"location must be null or {location_id}"):d(S.location_id,S.state_id,"location",`${y}.location`)),p(g.actors,"actor","actor_id",`${y}.actors`),p(g.props,"prop","prop_id",`${y}.props`),Dn(g.props)){let A=new Set;g.props.forEach((b,U)=>{!yt(b)||!Ie(b.prop_id)||(A.has(b.prop_id)&&o("dup_prop_ref",`${y}.props[${U}]`,`duplicate prop ref ${b.prop_id}`),A.add(b.prop_id))})}let E=new Set(Dn(g.actors)?g.actors.filter(A=>yt(A)).map(A=>A.actor_id).filter(A=>Ie(A)):[]);if(!Dn(g.actions))o("actions",`${y}.actions`,"actions must be an array");else{let A=Ie(g.scene_id)?`${u.episode_id}/${g.scene_id}`:void 0;g.actions.forEach((b,U)=>l(b,`${y}.actions[${U}]`,E,A)),Ps(g.actions,`${y}.actions`,o)}})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}var tt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),de=e=>typeof e=="string",yn=e=>Array.isArray(e);function Uc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Uc):tt(e)&&Object.values(e).every(Uc)}function Ti(e,t,n){e!==void 0&&(!tt(e)||!Object.values(e).every(Uc))&&n("extend",t,"extend must be an object containing JSON values")}function Gw(e){for(let t=1;t<e.length;t++)if(e[t-1]>e[t])return!1;return!0}function Pe(e){let t=[],n=[],o=(u,m,h,g)=>t.push({code:u,path:m,message:h,...g?{repair_hint:g}:{}}),i=(u,m,h,g)=>n.push({code:u,path:m,message:h,...g?{repair_hint:g}:{}});if(!tt(e))return{ok:!1,errors:[{code:"not_object",path:"$",message:"script must be an object"}],warnings:n};e.version!==4&&o("version","$.version","version must be 4");for(let u of["title","worldview","style"])de(e[u])||o("field",`$.${u}`,`${u} must be a string`);for(let u of["worldview_raw","synopsis","logline","theme"])e[u]!==void 0&&!de(e[u])&&o("field",`$.${u}`,`${u} must be a string`);e.main_characters!==void 0&&(!yn(e.main_characters)||!e.main_characters.every(u=>tt(u)&&de(u.name)&&de(u.role)))&&o("main_characters","$.main_characters","main_characters must contain {name, role} string records"),Ti(e.extend,"$.extend",o);let r=new Map,s=new Map,c=new Set,a=(u,m,h,g,w)=>{if(!yn(u)){o("field",w,`${w} must be an array`);return}let y=new Set;u.forEach((_,S)=>{let E=`${w}[${S}]`;if(!tt(_)){o("asset",E,"asset must be an object");return}let A=_[h];if(!V(m,A)){o("asset_id",`${E}.${h}`,`${h} must be ${m} ID`);return}if(y.has(A)&&o("dup_id",`${E}.${h}`,`duplicate ${h} ${A}`),y.add(A),r.set(A,m),!de(_[g])||_[g].trim()==="")o("asset_name",`${E}.${g}`,`${g} must be a non-empty string`);else if(m==="actor"){let I=_[g].trim().toLocaleLowerCase();c.has(I)&&o("dup_actor_name",`${E}.${g}`,`duplicate actor name ${_[g]}`),c.add(I)}if((!de(_.importance)||!$n.includes(_.importance))&&o("importance",`${E}.importance`,`importance must be ${$n.join("|")}`),m==="actor"&&_.role_type!==void 0&&(!de(_.role_type)||!Ui.includes(_.role_type))&&o("role_type",`${E}.role_type`,`role_type must be ${Ui.join("|")}`),de(_.description)||o("asset_desc",`${E}.description`,"description must be a string"),_.aliases!==void 0&&(!yn(_.aliases)||!_.aliases.every(de)))o("aliases",`${E}.aliases`,"aliases must be an array of strings");else if(yn(_.aliases)&&_.aliases.every(de)){let I=new Set,v=de(_[g])?_[g]:"";_.aliases.forEach((L,C)=>{L===""&&o("alias_empty",`${E}.aliases[${C}]`,"alias must not be empty"),L===v&&o("alias_equals_name",`${E}.aliases[${C}]`,"alias must differ from the asset name"),I.has(L)&&o("dup_alias",`${E}.aliases[${C}]`,`duplicate alias ${L}`),I.add(L)})}Ti(_.extend,`${E}.extend`,o);let b=new Set,U=new Set,M=0;!yn(_.states)||_.states.length===0?o("states",`${E}.states`,"states must be a non-empty array"):_.states.forEach((I,v)=>{let L=`${E}.states[${v}]`;if(!tt(I)){o("state",L,"state must be an object");return}let C=I.state_id;if(C!=="default"&&!V("state",C)){o("state_id",`${L}.state_id`,"state_id must be default or st plus six Base58 characters");return}b.has(C)&&o("dup_state",`${L}.state_id`,`duplicate state_id ${C}`),b.add(C),C==="default"&&M++,!de(I.state_name)||I.state_name.trim()===""?o("state_name",`${L}.state_name`,"state_name must be a non-empty string"):(U.has(I.state_name)&&o("dup_state_name",`${L}.state_name`,`duplicate state_name ${I.state_name}`),U.add(I.state_name)),de(I.description)||o("state_description",`${L}.description`,"description must be a string"),Ti(I.extend,`${L}.extend`,o)}),M!==1&&o("default_state",`${E}.states`,`exactly one default state required, found ${M}`),s.set(A,b)})};a(e.actors,"actor","actor_id","actor_name","$.actors"),a(e.locations,"location","location_id","location_name","$.locations"),a(e.props,"prop","prop_id","prop_name","$.props");let d=(u,m,h)=>{if(!yn(m)||m.length===0||!m.every(de))return o("state_ids",h,"state_ids must be a non-empty array of strings"),[];let g=m,w=new Set;return g.forEach((y,_)=>{w.has(y)&&o("dup_state_ref",`${h}[${_}]`,`duplicate state_id ${y}`),w.add(y),s.get(u)?.has(y)||o("state_ref",`${h}[${_}]`,`state ${y} not found on ${u}`)}),Gw(g)||o("state_ids_order",h,"state_ids must be sorted lexically"),g},p=new Set,l=new Set,f=new Set;return yn(e.episodes)?e.episodes.forEach((u,m)=>{let h=`$.episodes[${m}]`;if(!tt(u)){o("episode",h,"episode must be an object");return}V("episode",u.episode_id)?(p.has(u.episode_id)&&o("dup_episode_id",`${h}.episode_id`,`duplicate episode_id ${u.episode_id}`),p.add(u.episode_id)):o("episode_id",`${h}.episode_id`,"episode_id must be ep plus six Base58 characters");for(let g of["title","synopsis"])u[g]!==void 0&&!de(u[g])&&o("field",`${h}.${g}`,`${g} must be a string`);if(Ti(u.extend,`${h}.extend`,o),!yn(u.scenes)){o("scenes",`${h}.scenes`,"scenes must be an array");return}u.scenes.forEach((g,w)=>{let y=`${h}.scenes[${w}]`;if(!tt(g)){o("scene",y,"scene must be an object");return}V("scene",g.scene_id)?(l.has(g.scene_id)&&o("dup_scene_id",`${y}.scene_id`,`duplicate scene_id ${g.scene_id}`),l.add(g.scene_id)):o("scene_id",`${y}.scene_id`,"scene_id must be scn plus six Base58 characters"),Ti(g.extend,`${y}.extend`,o),g.environment===void 0||tt(g.environment)&&(!de(g.environment.time)||g.environment.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!tt(g.environment)||g.environment.space!==void 0&&!de(g.environment.space)||!de(g.environment.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):kr(g.environment.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk"),(g.environment===void 0||tt(g.environment)&&(!de(g.environment.space)||g.environment.space.trim()===""))&&i("scene_space_missing",`${y}.environment.space`,"scene interior/exterior is required for production review"),g.location===null&&i("scene_location_missing",`${y}.location`,"scene location is required for production review"),g.location!==null&&(!tt(g.location)||!V("location",g.location.location_id)?o("location",`${y}.location`,"location must be null or a typed v4 location reference"):("state_id"in g.location&&o("v3_field",`${y}.location.state_id`,"Script v4 scene references use state_ids"),r.get(g.location.location_id)!=="location"&&o("location_ref",`${y}.location.location_id`,`location ${g.location.location_id} not found`),d(g.location.location_id,g.location.state_ids,`${y}.location.state_ids`)));let _=new Map,S=(E,A,b,U)=>{if(!yn(E)){o("field",U,`${U} must be an array`);return}let M=new Set;E.forEach((I,v)=>{let L=`${U}[${v}]`;if(!tt(I)||!V(A,I[b])){o("ref",L,`${b} must be a typed v4 ID`);return}let C=I[b];"state_id"in I&&o("v3_field",`${L}.state_id`,"Script v4 scene references use state_ids"),M.has(C)&&o("dup_asset_ref",`${L}.${b}`,`duplicate ${A} ref ${C}`),M.add(C),r.get(C)!==A&&o("asset_ref",`${L}.${b}`,`${A} ${C} not found`);let R=d(C,I.state_ids,`${L}.state_ids`);A==="actor"&&_.set(C,new Set(R))})};if(S(g.actors,"actor","actor_id",`${y}.actors`),S(g.props,"prop","prop_id",`${y}.props`),!yn(g.actions)){o("actions",`${y}.actions`,"actions must be an array");return}g.actions.forEach((E,A)=>{let b=`${y}.actions[${A}]`;if(!tt(E)){o("action",b,"action must be an object");return}if(V("action",E.action_id)?(f.has(E.action_id)&&o("dup_action_id",`${b}.action_id`,`duplicate action_id ${E.action_id}`),f.add(E.action_id)):o("action_id",`${b}.action_id`,"action_id must be ac plus six Base58 characters"),(!de(E.type)||!Tn.includes(E.type))&&o("action_type",`${b}.type`,`invalid action type ${String(E.type)}`),de(E.content)||o("content",`${b}.content`,"content must be a string"),"emotion"in E&&o("v3_field",`${b}.emotion`,"Script v4 does not allow emotion"),Ti(E.extend,`${b}.extend`,o),E.type==="dialogue"||E.type==="inner_thought")if(E.parenthetical!==void 0&&!de(E.parenthetical)&&o("parenthetical",`${b}.parenthetical`,"parenthetical must be a string"),!tt(E.speaker))o("speaker",`${b}.speaker`,"dialogue/inner_thought requires a speaker");else if(de(E.speaker.actor_id)){("kind"in E.speaker||"label"in E.speaker)&&o("speaker_shape",`${b}.speaker`,"actor speaker cannot contain non-actor speaker fields");let M=E.speaker.actor_id;(!V("actor",M)||r.get(M)!=="actor")&&o("speaker_actor",`${b}.speaker.actor_id`,`actor ${M} not found`);let I=_.get(M),v=s.get(M),L=de(E.speaker.state_id)&&v?.has(E.speaker.state_id)?E.speaker.state_id:void 0,C=v?.has("default")?"default":v?.values().next().value,R=L?[L]:C?[C]:[],J=V("scene",g.scene_id)&&V("actor",M)&&R.length>0?`scriptctl scene-ref ${g.scene_id} ${M} ${R.map(W=>`--state ${W}`).join(" ")} -p "$SCRIPT"`:void 0;if(I||o("actor_not_in_scene",`${b}.speaker.actor_id`,`actor ${M} is not referenced by this scene`,J),E.speaker.state_id!==void 0&&(!de(E.speaker.state_id)||!I?.has(E.speaker.state_id))){let W=L?[...new Set([...I??[],L])].sort():[],Re=V("scene",g.scene_id)&&V("actor",M)&&W.length>0?`scriptctl scene-ref ${g.scene_id} ${M} ${W.map(ie=>`--state ${ie}`).join(" ")} -p "$SCRIPT"`:J;o("speaker_state",`${b}.speaker.state_id`,`speaker state ${String(E.speaker.state_id)} is not in this scene's actor state_ids`,Re)}}else de(E.speaker.kind)?(("actor_id"in E.speaker||"state_id"in E.speaker)&&o("speaker_shape",`${b}.speaker`,"non-actor speaker cannot contain actor speaker fields"),Vn.includes(E.speaker.kind)||o("speaker_kind",`${b}.speaker.kind`,"invalid non-actor speaker kind"),E.speaker.label!==void 0&&!de(E.speaker.label)&&o("speaker_label",`${b}.speaker.label`,"speaker label must be a string")):o("speaker",`${b}.speaker`,"speaker needs actor_id or kind");else"parenthetical"in E&&o("parenthetical_type",`${b}.parenthetical`,"parenthetical only belongs to speaking actions"),"speaker"in E&&o("speaker_type",`${b}.speaker`,"speaker only belongs to speaking actions");if(E.transition_prompt!==void 0){let M=E.transition_prompt;!tt(M)||!de(M.target)||!de(M.process)||M.process===""||!de(M.contrast)||M.contrast===""?o("transition_prompt",`${b}.transition_prompt`,"transition_prompt requires non-empty target/process/contrast"):r.has(M.target)||o("transition_target",`${b}.transition_prompt.target`,`asset ${M.target} not found`)}}),Ps(g.actions,`${y}.actions`,o)})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}function Fo(e,t=new Set,n){try{return n?br(e,t,n):br(e,t)}catch(o){throw o?.code!==Lc?o:new x(`Could not generate an unused ${e} ID.`,{exitCode:k,errorCode:"ID_SPACE_RETRY_EXHAUSTED",hint:"Retry the command. If this persists, inspect the configured ID generator."})}}function Ae(e,t=[]){throw new x(e,{exitCode:k,errorCode:"CREATIVE_DRAFT_INVALID",hint:"Use the readable creative draft schema; do not include Script IDs or .scriptctl syntax.",data:{actual:t.map(String)}})}function Gn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function q(e,t=""){return String(e??"").replace(/\s+/gu," ").trim()||t}function Bw(e,t){let n=Number(e);return(!Number.isSafeInteger(n)||n<1)&&Ae(`${t} must be a positive integer.`,[e]),n}function Jw(e){return e===void 0?{}:(Gn(e)||Ae("Action extensions must be an object."),structuredClone(e))}function Kw(e){let t=new Set;for(let n of e.actors){t.add(n.actor_id);for(let o of n.states)t.add(o.state_id)}for(let n of e.locations){t.add(n.location_id);for(let o of n.states)t.add(o.state_id)}for(let n of e.props){t.add(n.prop_id);for(let o of n.states)t.add(o.state_id)}for(let n of e.episodes){t.add(n.episode_id);for(let o of n.scenes){t.add(o.scene_id);for(let i of o.actions)t.add(i.action_id)}}return t}function fo(e,t,n){for(let o=0;o<128;o+=1){let i=gu.createHash("sha256").update(`${e}:${t}:${o}`).digest(),r="";for(let c=0;c<6;c+=1)r+=Pi[i[c]%Pi.length];let s=`${Ci[e]}${r}`;if(!n.has(s))return n.add(s),s}Ae(`Could not allocate a stable ${e} ID.`)}function jw(e){let t=q(e).match(/^(\d+):([0-5]\d)(?:\.(\d{1,3}))?$/u);return t?(Number(t[1])*60+Number(t[2]))*1e3+Number((t[3]??"").padEnd(3,"0")):null}function zw(e){return`${Math.floor(e/6e4)}:${String(Math.floor(e%6e4/1e3)).padStart(2,"0")}.${String(e%1e3).padStart(3,"0")}`}function Hw(e){let t=Number(e.extend?.duration_ms??e.extend?.rewrite_duration_ms);return Number.isFinite(t)&&t>0?Math.round(t):1200}function Fw(e){let t=0;for(let n of e.scenes.flatMap(o=>o.actions))t=(jw(n.extend?.timestamp)??t)+Hw(n);return t}function hu(e){return e===void 0?[]:((!Array.isArray(e)||!e.every(Gn))&&Ae("Asset variants must be an array of readable objects."),e)}function Qw(e,t){let n=e.assets;if(n===void 0)return[];Gn(n)||Ae("assets must be an object.");let o=n[t];return o===void 0?[]:((!Array.isArray(o)||!o.every(Gn))&&Ae(`assets.${t} must be an array.`),o)}function Yw(e,t){return e==="actors"?t.actor_name:e==="locations"?t.location_name:t.prop_name}function qw(e,t){return e[t]}function Zw(e,t){return[Yw(e,t),...t.aliases??[]].map(dt)}function yu(e,t,n){let o=dt(n);return Qw(e,t).find(i=>[i.name,...Array.isArray(i.aliases)?i.aliases:[]].map(r=>dt(q(r))).includes(o))??null}function wu(e,t){if(!e)return null;let n=dt(t);return hu(e.variants).find(o=>{let i=dt(q(o.name));return i===n||["default","\u9ED8\u8BA4"].includes(n)&&["default","\u9ED8\u8BA4"].includes(i)})??null}function _u(e,t,n){let o=wu(e,n),i=q(o?.description);return(!o||!i)&&Ae(`${t}/${n} is a new variant and requires a readable assets declaration with a self-contained description.`),o}function Ww(e,t){let n=q(t?.name);return n&&!["default","\u9ED8\u8BA4"].includes(dt(n))?n:e==="actors"?"\u57FA\u7840\u9020\u578B":e==="locations"?"\u5E38\u89C4\u5E03\u7F6E":"\u57FA\u7840\u5916\u89C2"}function Xw(e,t,n,o,i,r){let s=yu(t,n,o);s||Ae(`${o} is not an existing ${n} asset and has no readable declaration.`);let c=q(s.name,o),a=hu(s.variants),d=wu(s,"\u9ED8\u8BA4")??a[0]??null;n==="actors"&&!q(s.description)&&Ae(`${c} requires an identity description separate from its appearance variants.`),n==="actors"&&!q(d?.description)&&Ae(`${c} requires its first variant to provide a self-contained base appearance description.`);let p=[{state_id:"default",state_name:Ww(n,d),description:q(d?.description,q(s.description,`${c}\u7684\u57FA\u7840\u53C2\u8003\u5916\u89C2\u3002`))}];for(let u of a){let m=q(u.name);if(u===d||!m||["default","\u9ED8\u8BA4"].includes(dt(m)))continue;let h=fo("state",`${n}:${c}:${m}`,i);p.push({state_id:h,state_name:m,description:q(_u(s,c,m).description)}),r.states.push(`${c}/${m}`)}let l={aliases:Array.isArray(s.aliases)?[...new Set(s.aliases.map(u=>q(u)).filter(u=>u&&u!==c))]:[],importance:s.importance==="background"?"background":"featured",description:q(s.description,`${c}\u7684\u57FA\u7840\u8BBE\u5B9A\u3002`),states:p};if(n==="actors"){let u={...l,actor_id:fo("actor",c,i),actor_name:c,...s.roleType==="\u4E3B\u89D2"||s.roleType==="\u914D\u89D2"?{role_type:s.roleType}:{}};return e.actors.push(u),r.actors.push(c),u}if(n==="locations"){let u={...l,location_id:fo("location",c,i),location_name:c};return e.locations.push(u),r.locations.push(c),u}let f={...l,prop_id:fo("prop",c,i),prop_name:c};return e.props.push(f),r.props.push(c),f}function Ts(e,t,n,o,i,r){let s=q(o);s||Ae(`${n} reference requires a readable name.`);let c=dt(s);return qw(e,n).find(d=>Zw(n,d).includes(c))??Xw(e,t,n,s,i,r)}function Or(e,t,n,o,i,r){let s=q(t,"\u9ED8\u8BA4"),c=dt(s),a=e.states.find(u=>dt(u.state_name)===c||u.state_id==="default"&&["default","\u9ED8\u8BA4"].includes(c));if(a)return a.state_id;let d="actor_name"in e?e.actor_name:"location_name"in e?e.location_name:e.prop_name,p=yu(n,o,d),l=_u(p,d,s),f={state_id:fo("state",`${d}:${s}`,i),state_name:s,description:q(l.description)};return e.states.push(f),r.states.push(`${d}/${s}`),f.state_id}function mu(e,t){return e===void 0?[]:((!Array.isArray(e)||!e.every(Gn))&&Ae(`${t} must be an array of readable references.`),e)}function Cs(e,t,n){let o=structuredClone(e);for(let i of t){let r=o.find(s=>n(s)===n(i));r?r.state_ids=[...new Set([...r.state_ids,...i.state_ids])].sort():o.push(structuredClone(i))}return o}function e_(e,t){return!!(e&&e.location?.location_id&&t.location?.location_id&&e.location.location_id===t.location.location_id&&q(e.environment?.space)===q(t.environment?.space)&&q(e.environment?.time)===q(t.environment?.time))}function t_(e,t,n,o,i,r,s,c){(!Array.isArray(e)||e.length===0||!e.every(Gn))&&Ae("scene.actions must contain at least one readable Action.");let a=structuredClone(o),d=r;return{actions:e.map((l,f)=>{let u=q(l.type,"action");["action","transition","dialogue","inner_thought"].includes(u)||Ae(`Action ${f+1} has an unsupported type.`,[u]);let m=q(l.content);m||Ae(`Action ${f+1} has empty content.`);let h=Math.max(400,Math.min(8e3,Math.round(Number(l.durationMs)||Number(l.weight||1)*1200))),g=Jw(l.extensions);g.timestamp=zw(d),g.duration_ms=h,g.rewrite_duration_ms!==void 0&&(g.rewrite_duration_ms=h);let w={action_id:fo("action",`${i}:${f+1}:${m}`,s),type:u,content:m,extend:g};if(d+=h,u==="action"||u==="transition")return w;let y=q(l.speaker);y||Ae(`Action ${f+1} requires a speaker.`);let _=y.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");new RegExp(`^${_}\\s*[:\uFF1A]`,"iu").test(m)&&Ae(`Action ${f+1} repeats the speaker name in dialogue content.`),/^(?:“[^”]+”|「[^」]+」|『[^』]+』|"[^"]+")$/u.test(m)&&Ae(`Action ${f+1} wraps dialogue content in quotation marks.`);let S=dt(y);if(["\u65C1\u767D","narrator"].includes(S))return{...w,speaker:{kind:"broadcast",label:"\u65C1\u767D"},...q(l.parenthetical)?{parenthetical:q(l.parenthetical)}:{}};if(["\u753B\u5916\u97F3","offscreen"].includes(S))return{...w,speaker:{kind:"offscreen",label:"\u753B\u5916\u97F3"},...q(l.parenthetical)?{parenthetical:q(l.parenthetical)}:{}};let E=Ts(t,n,"actors",y,s,c),A=q(l.speakerVariant),b=a.find(M=>M.actor_id===E.actor_id),U;if(A)U=Or(E,A,n,"actors",s,c),b?b.state_ids=[...new Set([...b.state_ids,U])].sort():a.push({actor_id:E.actor_id,state_ids:[U]});else if(!b){let M=Or(E,"\u9ED8\u8BA4",n,"actors",s,c);a.push({actor_id:E.actor_id,state_ids:[M]})}return{...w,speaker:{actor_id:E.actor_id,...U?{state_id:U}:{}},...q(l.parenthetical)?{parenthetical:q(l.parenthetical)}:{}}}),actorRefs:a}}function Eu(e,t){(!Gn(t)||t.version!==1)&&Ae("Creative draft version must be 1."),(!Gn(t.episode)||!Gn(t.scene))&&Ae("Creative draft requires episode and scene objects.");let n=structuredClone(t),o=n.episode,i=n.scene,r=structuredClone(e),s=Kw(r),c={actors:[],locations:[],props:[],states:[]},a=Bw(o.number,"episode.number");a>r.episodes.length+1&&Ae("Episodes must be composed in order.",[a]);let d=r.episodes[a-1];d?(q(d.title)||(d.title=q(o.title,`\u7B2C ${a} \u96C6`)),q(d.synopsis)||(d.synopsis=q(o.synopsis,`\u7B2C ${a} \u96C6\u5267\u60C5\u3002`))):(d={episode_id:fo("episode",`episode:${a}`,s),title:q(o.title,`\u7B2C ${a} \u96C6`),synopsis:q(o.synopsis,`\u7B2C ${a} \u96C6\u5267\u60C5\u3002`),scenes:[]},r.episodes.push(d));let p=Ts(r,n,"locations",i.location,s,c),l=Or(p,i.locationVariant,n,"locations",s,c),f=mu(i.actors,"scene.actors").map(I=>{let v=Ts(r,n,"actors",I.name,s,c);return{actor_id:v.actor_id,state_ids:[Or(v,I.variant,n,"actors",s,c)]}}),u=Cs([],f,I=>I.actor_id),m=mu(i.props,"scene.props").map(I=>{let v=Ts(r,n,"props",I.name,s,c);return{prop_id:v.prop_id,state_ids:[Or(v,I.variant,n,"props",s,c)]}}),h=Cs([],m,I=>I.prop_id),g=d.scenes.at(-1),w={scene_id:fo("scene",`episode:${a}:scene:${d.scenes.length+1}:${q(i.title)}`,s),environment:{space:q(i.space,"interior"),time:q(i.time,"day")},location:{location_id:p.location_id,state_ids:[l]},actors:u,props:h,actions:[],extend:{scene_title:q(i.title,`\u7B2C ${d.scenes.length+1} \u573A`)}},y=q(i.boundary,"auto");["auto","new","continue"].includes(y)||Ae("scene.boundary must be auto, new, or continue.");let _=e_(g,w);y==="continue"&&!_&&Ae("scene.boundary=continue requires the same location, space, and time as the previous scene.");let S=y!=="new"&&_,E=S&&g?g:w,A=S?d.scenes.length:d.scenes.length+1,b=Cs(E.actors,w.actors,I=>I.actor_id),U=t_(i.actions,r,n,b,E.scene_id,Fw(d),s,c);E.actors=U.actorRefs,E.props=Cs(E.props,w.props,I=>I.prop_id),E.location&&w.location&&(E.location.state_ids=[...new Set([...E.location.state_ids,...w.location.state_ids])].sort()),E.actions.push(...U.actions),S||d.scenes.push(E);let M=Pe(r);return M.ok||Ae("Composed screenplay does not pass Script v4 validation.",M.errors.slice(0,12).map(I=>`${I.path}: ${I.message}`)),{script:r,validation:M,episodeNumber:a,sceneNumber:A,sceneId:E.scene_id,actionIds:U.actions.map(I=>I.action_id),joinedPreviousScene:S,created:c}}function He(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function wn(e,t){return e[t]===void 0||typeof e[t]=="string"}function Pc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Pc):He(e)&&Object.values(e).every(Pc)}function Vi(e){return e.extend===void 0||He(e.extend)&&Object.values(e.extend).every(Pc)}function Cc(e){return e==="default"||V("state",e)}function n_(e){return He(e)&&Cc(e.state_id)&&typeof e.state_name=="string"&&typeof e.description=="string"&&Vi(e)}function Tc(e){return typeof e.importance=="string"&&Pt.has(e.importance)&&typeof e.description=="string"&&(e.aliases===void 0||Array.isArray(e.aliases)&&e.aliases.every(t=>typeof t=="string"))&&Array.isArray(e.states)&&e.states.every(n_)&&Vi(e)}function o_(e){return He(e)&&V("actor",e.actor_id)&&typeof e.actor_name=="string"&&(e.role_type===void 0||typeof e.role_type=="string"&&lo.has(e.role_type))&&Tc(e)}function i_(e){return He(e)&&V("location",e.location_id)&&typeof e.location_name=="string"&&Tc(e)}function r_(e){return He(e)&&V("prop",e.prop_id)&&typeof e.prop_name=="string"&&Tc(e)}function Vc(e){return Array.isArray(e)&&e.every(Cc)}function s_(e){return He(e)&&V("actor",e.actor_id)&&Vc(e.state_ids)}function a_(e){return He(e)&&V("location",e.location_id)&&Vc(e.state_ids)}function c_(e){return He(e)&&V("prop",e.prop_id)&&Vc(e.state_ids)}function d_(e){return V("actor",e.actor_id)&&(e.state_id===void 0||Cc(e.state_id))}function p_(e){return typeof e.kind=="string"&&Ho.has(e.kind)&&wn(e,"label")}function l_(e){return!(!He(e)||!V("action",e.action_id)||typeof e.type!="string"||!qt.has(e.type)||typeof e.content!="string"||!wn(e,"parenthetical")||!Vi(e)||(e.type==="dialogue"||e.type==="inner_thought")&&(!He(e.speaker)||!d_(e.speaker)&&!p_(e.speaker))||e.transition_prompt!==void 0&&(!He(e.transition_prompt)||!V("actor",e.transition_prompt.target)&&!V("location",e.transition_prompt.target)&&!V("prop",e.transition_prompt.target)||typeof e.transition_prompt.process!="string"||typeof e.transition_prompt.contrast!="string"))}function u_(e){return!(!He(e)||!V("scene",e.scene_id)||!Array.isArray(e.actors)||!e.actors.every(s_)||!Array.isArray(e.props)||!e.props.every(c_)||!Array.isArray(e.actions)||!e.actions.every(l_)||!Vi(e)||e.location!==null&&!a_(e.location)||e.environment!==void 0&&(!He(e.environment)||!wn(e.environment,"space")||!wn(e.environment,"time")))}function f_(e){return He(e)&&V("episode",e.episode_id)&&wn(e,"title")&&wn(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(u_)&&Vi(e)}function m_(e){return He(e)&&e.version===4&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&wn(e,"worldview_raw")&&wn(e,"synopsis")&&wn(e,"logline")&&wn(e,"theme")&&(e.main_characters===void 0||Array.isArray(e.main_characters)&&e.main_characters.every(t=>He(t)&&typeof t.name=="string"&&typeof t.role=="string"))&&Array.isArray(e.actors)&&e.actors.every(o_)&&Array.isArray(e.locations)&&e.locations.every(i_)&&Array.isArray(e.props)&&e.props.every(r_)&&Array.isArray(e.episodes)&&e.episodes.every(f_)&&Vi(e)}function $i(e){let t=Pe(e);if(t.ok)return e;throw new x("The local file is not a valid Script v4 document.",{exitCode:k,errorCode:"SCRIPT_V4_INVALID",hint:"Run `scriptctl validate --script-path <path>` and repair the reported v4 fields.",data:{expected:["A valid Script v4 document"],actual:t.errors.slice(0,20).map(n=>`${n.path}: ${n.message}`)}})}function _n(e){if(m_(e))return e;throw new x("The local file is not a structurally readable Script v4 document.",{exitCode:k,errorCode:"SCRIPT_V4_SHAPE_INVALID",hint:"Repair the local Script v4 structure, then rerun the command.",data:{expected:["Script v4 with typed assets, episodes, scenes, references, and actions"],actual:[Array.isArray(e)?"array":typeof e]}})}import*as vr from"node:crypto";import*as $e from"node:fs";import*as Ct from"node:path";import g_ from"proper-lockfile";function Dc(e){if(Array.isArray(e))return e.map(Dc);if(e!==null&&typeof e=="object"){let t=e,n={};for(let o of Object.keys(t).sort())n[o]=Dc(t[o]);return n}return e}function Je(e){let t=JSON.stringify(Dc(e));return`sha256:${vr.createHash("sha256").update(t).digest("hex")}`}function Rr(e){return $e.existsSync(e)?`sha256:${vr.createHash("sha256").update($e.readFileSync(e)).digest("hex")}`:null}function Mr(e,t){let n=Rr(e);if(n!==t)throw new x("The local script changed while the command was running.",{exitCode:k,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and retry the command.",data:{actual:[`loadedFingerprint=${t??"<missing>"}`,`currentFingerprint=${n??"<missing>"}`,e]}})}function Nr(e){let t=Ct.resolve(e),n=Ct.join(Ct.dirname(t),".scriptctl"),o=Ct.basename(t);return{scriptPath:t,stateDir:n,metadataPath:Ct.join(n,`${o}.working-copy.json`),lockPath:Ct.join(n,o)}}async function Vs(e,t){let n=Nr(e);$e.mkdirSync(n.stateDir,{recursive:!0});let o=null;try{o=await g_.lock(n.lockPath,{realpath:!1,stale:12e4,update:1e4,retries:{retries:60,factor:1,minTimeout:500,maxTimeout:500}})}catch(i){throw new x("Timed out waiting for the script file lock.",{exitCode:X,errorCode:"WORKING_COPY_LOCK_TIMEOUT",hint:"Wait for the other scriptctl command to finish, then retry.",data:{actual:[n.scriptPath,i instanceof Error?i.message:String(i)]}})}try{return await t()}finally{await o()}}function Fe(e,t){$s(e,`${JSON.stringify(t,null,2)}
123
+ `)}function $s(e,t){let n=Ct.dirname(e);$e.mkdirSync(n,{recursive:!0});let o=Ct.join(n,`.${Ct.basename(e)}.${process.pid}.${vr.randomUUID()}.tmp`),i=$e.openSync(o,"wx");try{$e.writeFileSync(i,t,"utf-8"),$e.fsyncSync(i)}finally{$e.closeSync(i)}$e.renameSync(o,e)}function Ds(e){let t=Nr(e).metadataPath;if(!$e.existsSync(t))return null;let n;try{n=JSON.parse($e.readFileSync(t,"utf-8"))}catch(i){throw $c(t,i instanceof Error?i.message:String(i))}if(n===null||typeof n!="object"||Array.isArray(n))throw $c(t,"metadata root must be an object");let o=n;if(o.schemaVersion!==1||typeof o.projectGroupNo!="string"||o.projectGroupNo.length===0||typeof o.apiBaseUrl!="string"||o.apiBaseUrl.length===0||!Number.isInteger(o.baseRevision)||Number(o.baseRevision)<0||typeof o.baseContentHash!="string"||!o.baseContentHash.startsWith("sha256:"))throw $c(t,"required fields are missing or invalid");return{schemaVersion:1,projectGroupNo:o.projectGroupNo,apiBaseUrl:o.apiBaseUrl,baseRevision:Number(o.baseRevision),baseContentHash:o.baseContentHash}}function Gs(e,t){Fe(Nr(e).metadataPath,t)}function $c(e,t){return new x("Working copy metadata is invalid.",{exitCode:k,errorCode:"WORKING_COPY_METADATA_INVALID",hint:"Run `scriptctl checkout --discard-local` to recreate the working copy metadata.",data:{expected:["valid scriptctl working-copy metadata"],actual:[e,t]}})}function Gt(e,t){let n;try{n=JSON.parse($e.readFileSync(e,"utf-8"))}catch(i){throw new x("The local script changed while the command was running.",{exitCode:k,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and re-apply the operation.",data:{actual:[e,i instanceof Error?i.message:String(i)]}})}let o=Je(n);if(o!==t)throw new x("The local script changed while the command was running.",{exitCode:k,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and re-apply the operation.",data:{actual:[`loadedHash=${t}`,`currentHash=${o}`,e]}})}function O(e){return e==null?"":String(e)}function oe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bn(e){return Array.isArray(e)}function re(e){return Array.isArray(e)?e:[]}function Gc(e,t=[]){throw new x(e,{exitCode:B,errorCode:"CREATIVE_DRAFT_USAGE_INVALID",hint:"Run `scriptctl authoring compose <draft.json> --script-path <script.json>` and apply the returned plan digest.",data:{actual:t}})}function xu(e,t){let n=Au.resolve(e),o;try{o=Iu.readFileSync(n)}catch{throw new x(`${t} does not exist.`,{exitCode:k,errorCode:"CREATIVE_DRAFT_SOURCE_UNAVAILABLE",data:{actual:[n]}})}try{return{path:n,bytes:o,value:JSON.parse(o.toString("utf-8"))}}catch(i){throw new x(`${t} is not valid JSON.`,{exitCode:k,errorCode:"CREATIVE_DRAFT_JSON_INVALID",data:{actual:[n,i instanceof Error?i.message:String(i)]}})}}function ku(e){let t=Array.isArray(e._args)?e._args:[],n=typeof t[0]=="string"?t[0]:"";(!n||n==="-")&&Gc("Creative draft input must be a named JSON file.",[n||"<missing>"]);let o=xu(n,"The creative draft"),i=me(e),r=xu(i,"The target Script v4 file"),s=_n(r.value),c=Je(s),a=Eu(s,o.value),d=`sha256:${Su.createHash("sha256").update(o.bytes).digest("hex")}`,p={version:1,op:"compose",sourceDigest:d,baseline:c,proposed:Je(a.script),episodeNumber:a.episodeNumber,sceneNumber:a.sceneNumber,sceneId:a.sceneId,actionIds:a.actionIds,joinedPreviousScene:a.joinedPreviousScene,created:a.created},l=`sha256:${_e(JSON.stringify(p))}`,f=e.apply===!0,u=O(e.plan).trim();if(f&&!u&&Gc("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!f&&u&&Gc("--plan is only valid together with --apply.",[`plan=${u}`]),f&&u!==l)throw new x("The supplied plan does not match the current draft or script baseline.",{exitCode:k,errorCode:"CREATIVE_DRAFT_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[l],actual:[u]}});return f&&(Gt(i,c),Fe(i,a.script)),[{text:[`${f?"Applied":"Planned"} readable scene draft as episode ${a.episodeNumber}, scene ${a.sceneNumber}${a.joinedPreviousScene?" (joined previous scene)":""}`,`plan: ${l}`].join(`
124
+ `),data:{op:"compose",applied:f,source_path:o.path,source_digest:d,script_path:i,baseline:c,plan_digest:l,episode_number:a.episodeNumber,scene_number:a.sceneNumber,scene_id:a.sceneId,action_ids:a.actionIds,joined_previous_scene:a.joinedPreviousScene,created:a.created,validation:a.validation}},G]}import*as Cu from"node:fs";import*as Tu from"node:path";var Zt={line:1,column:1};function h_(e){let t=[];for(let n of e.actors){let o=structuredClone(n);o.states=[],t.push({declarationKind:"actor",value:o,source:Zt});for(let i of n.states)t.push(Bc("actor",n.actor_id,i))}for(let n of e.locations){let o=structuredClone(n);o.states=[],t.push({declarationKind:"location",value:o,source:Zt});for(let i of n.states)t.push(Bc("location",n.location_id,i))}for(let n of e.props){let o=structuredClone(n);o.states=[],t.push({declarationKind:"prop",value:o,source:Zt});for(let i of n.states)t.push(Bc("prop",n.prop_id,i))}return t}function Bc(e,t,n){return{declarationKind:"state",ownerKind:e,ownerId:t,value:structuredClone(n),source:Zt}}function bu(e){let t={kind:"script",title:e.title,worldview:e.worldview,style:e.style,episodes:structuredClone(e.episodes),source:Zt};return e.worldview_raw!==void 0&&(t.worldviewRaw=e.worldview_raw),e.synopsis!==void 0&&(t.synopsis=e.synopsis),e.logline!==void 0&&(t.logline=e.logline),e.theme!==void 0&&(t.theme=e.theme),e.main_characters!==void 0&&(t.mainCharacters=structuredClone(e.main_characters)),e.extend!==void 0&&(t.extend=structuredClone(e.extend)),{version:1,declarations:h_(e),targets:[t],targetKind:"script"}}function Di(e,t){return{version:1,declarations:[],targets:t,targetKind:e}}function y_(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function w_(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function ue(e,t,n){let o=[e,...t].map(y_).join("|"),i=w_(n);return`[${o}]${i.length>0?` ${i}`:""}`}function Kc(e){if(Array.isArray(e))return e.map(Kc);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=Kc(e[n]);return t}return e}function Jn(e){return e===void 0?[]:[ue("extensions",[],""),...Object.keys(e).sort().map(t=>ue("extend",[t],JSON.stringify(Kc(e[t]))))]}function __(e){return"actor_id"in e?e.state_id===void 0?e.actor_id:`${e.actor_id}/${e.state_id}`:e.label===void 0?e.kind:`${e.kind}:${e.label}`}function Ou(e){let t=Jn(e.extend);if(e.transition_prompt!==void 0&&t.push(ue("prompt",[e.transition_prompt.target,e.transition_prompt.process,e.transition_prompt.contrast],"")),e.type==="dialogue"||e.type==="inner_thought"){let o=e.type==="dialogue"?"dlg":"think",i=[__(e.speaker)];return e.emotion!==void 0&&i.push(e.emotion),t.push(ue(o,i,e.content)),t}let n=e.type==="action"?"act":"trans";return t.push(ue(n,e.emotion===void 0?[]:[e.emotion],e.content)),t}function jc(e,t){let n=[...Jn(e.extend),`<scene ${t}>`];if(e.environment!==void 0&&(e.environment.time!==void 0?n.push(ue("environment",[e.environment.space??"",e.environment.time],"")):e.environment.space!==void 0?n.push(ue("environment",[e.environment.space],"")):n.push(ue("environment",[],""))),e.location===null)n.push(ue("location",[],""));else{let o=[e.location.location_id];e.location.state_id!==void 0&&o.push(e.location.state_id),n.push(ue("location",o,""))}for(let o of e.actors){let i=[o.actor_id];o.state_id!==void 0&&i.push(o.state_id),n.push(ue("cast",i,""))}for(let o of e.props){let i=[o.prop_id];o.state_id!==void 0&&i.push(o.state_id),n.push(ue("prop",i,""))}n.push("","<body>");for(let o of e.actions)n.push(...Ou(o));return n.push("</body>","","</scene>"),n}function Jc(e){let t=[...Jn(e.extend),`<episode id=${e.episode_id}>`];return e.title!==void 0&&t.push(ue("title",[],e.title)),e.synopsis!==void 0&&t.push(ue("synopsis",[],e.synopsis)),(e.title!==void 0||e.synopsis!==void 0)&&e.scenes.length>0&&t.push(""),e.scenes.forEach((n,o)=>{t.push(...jc(n,`id=${n.scene_id}`)),o<e.scenes.length-1&&t.push("")}),t.push("</episode>"),t}function E_(e){if(e.declarationKind==="state")return x_(e.ownerKind,e.ownerId,e.value);let t=e.value,n=Jn(t.extend);t.aliases!==void 0&&n.push(ue("aliases",[],""));for(let o of t.aliases??[])n.push(ue("alias",[],o));if(e.declarationKind==="actor"){let o=e.value,i=[o.actor_id,o.actor_name,o.importance];o.role_type!==void 0&&i.push(o.role_type),n.push(ue("actor",i,o.description))}else if(e.declarationKind==="location"){let o=e.value;n.push(ue("location",[o.location_id,o.location_name,o.importance],o.description))}else{let o=e.value;n.push(ue("prop",[o.prop_id,o.prop_name,o.importance],o.description))}return n}function x_(e,t,n){return[...Jn(n.extend),ue("state",[`${e}:${t}`,n.state_id,n.state_name],n.description)]}function S_(e){switch(e.kind){case"script":{let t=[...Jn(e.extend),"<script>"];if(t.push(ue("title",[],e.title)),t.push(ue("worldview",[],e.worldview)),e.worldviewRaw!==void 0&&t.push(ue("worldview-raw",[],e.worldviewRaw)),t.push(ue("style",[],e.style)),e.synopsis!==void 0&&t.push(ue("synopsis",[],e.synopsis)),e.logline!==void 0&&t.push(ue("logline",[],e.logline)),e.theme!==void 0&&t.push(ue("theme",[],e.theme)),e.mainCharacters!==void 0){t.push(ue("main-characters",[],""));for(let n of e.mainCharacters)t.push(ue("main-character",[n.name,n.role],""))}return e.episodes.length>0&&t.push(""),e.episodes.forEach((n,o)=>{t.push(...Jc(n)),o<e.episodes.length-1&&t.push("")}),t.push("</script>"),t}case"episode":return Jc(e.value);case"episode-span":{let t=[...Jn(e.extend),`<episode-span from=${e.from} through=${e.through}>`];return e.episodes.forEach((n,o)=>{t.push(...Jc(n)),o<e.episodes.length-1&&t.push("")}),t.push("</episode-span>"),t}case"scene":return jc(e.value,`id=${e.value.scene_id} parent=${e.parent}`);case"scene-span":{let t=[...Jn(e.extend),`<scene-span parent=${e.parent} from=${e.from} through=${e.through}>`];return e.scenes.forEach((n,o)=>{t.push(...jc(n,`id=${n.scene_id}`)),o<e.scenes.length-1&&t.push("")}),t.push("</scene-span>"),t}case"action-span":{let t=[...Jn(e.extend),`<action-span parent=${e.parent} from=${e.from} through=${e.through}>`,"<body>"];for(let n of e.actions)t.push(...Ou(n));return t.push("</body>","</action-span>"),t}}}function vu(e){let t=["<authoring version=1>",""];if(e.declarations.length>0){t.push("<create>");for(let n of e.declarations)t.push(...E_(n));t.push("</create>","")}return e.targets.forEach((n,o)=>{t.push(...S_(n)),o<e.targets.length-1&&t.push("")}),t.push("","</authoring>"),`${t.join(`
125
125
  `)}
126
- `}function Qe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _t(e,t){return e[t]===void 0||typeof e[t]=="string"}function jc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(jc):Qe(e)&&Object.values(e).every(jc)}function fo(e){return e.extend===void 0||Qe(e.extend)&&Object.values(e.extend).every(jc)}function Kc(e){return Qe(e)&&typeof e.state_id=="string"&&typeof e.state_name=="string"&&typeof e.description=="string"&&fo(e)}function E_(e){return Qe(e)&&typeof e.actor_id=="string"&&typeof e.actor_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&Pt.has(e.importance)&&(e.aliases===void 0||Array.isArray(e.aliases)&&e.aliases.every(t=>typeof t=="string"))&&(e.role_type===void 0||e.role_type==="\u4E3B\u89D2"||e.role_type==="\u914D\u89D2")&&Array.isArray(e.states)&&e.states.every(Kc)&&fo(e)}function x_(e){return Qe(e)&&typeof e.location_id=="string"&&typeof e.location_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&Pt.has(e.importance)&&(e.aliases===void 0||Array.isArray(e.aliases)&&e.aliases.every(t=>typeof t=="string"))&&Array.isArray(e.states)&&e.states.every(Kc)&&fo(e)}function S_(e){return Qe(e)&&typeof e.prop_id=="string"&&typeof e.prop_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&Pt.has(e.importance)&&(e.aliases===void 0||Array.isArray(e.aliases)&&e.aliases.every(t=>typeof t=="string"))&&Array.isArray(e.states)&&e.states.every(Kc)&&fo(e)}function I_(e){if(!Qe(e)||typeof e.type!="string"||!qt.has(e.type)||typeof e.content!="string"||!_t(e,"emotion"))return!1;if(e.speaker!==void 0){if(!Qe(e.speaker))return!1;if(typeof e.speaker.actor_id=="string"){if(!_t(e.speaker,"state_id"))return!1}else if(typeof e.speaker.kind=="string"){if(!Ho.has(e.speaker.kind)||!_t(e.speaker,"label"))return!1}else return!1}return e.transition_prompt!==void 0&&(!Qe(e.transition_prompt)||typeof e.transition_prompt.target!="string"||typeof e.transition_prompt.process!="string"||typeof e.transition_prompt.contrast!="string")?!1:fo(e)}function A_(e){return!Qe(e)||typeof e.scene_id!="string"||!Array.isArray(e.actors)||!Array.isArray(e.props)||!Array.isArray(e.actions)||!e.actions.every(I_)||!e.actors.every(t=>Qe(t)&&typeof t.actor_id=="string"&&_t(t,"state_id"))||!e.props.every(t=>Qe(t)&&typeof t.prop_id=="string"&&_t(t,"state_id"))||e.location!==null&&(!Qe(e.location)||typeof e.location.location_id!="string"||!_t(e.location,"state_id"))||e.environment!==void 0&&(!Qe(e.environment)||!_t(e.environment,"space")||!_t(e.environment,"time"))?!1:fo(e)}function k_(e){return Qe(e)&&typeof e.episode_id=="string"&&_t(e,"title")&&_t(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(A_)&&fo(e)}function b_(e){return Qe(e)&&e.version===3&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&_t(e,"worldview_raw")&&_t(e,"synopsis")&&_t(e,"logline")&&_t(e,"theme")&&(e.main_characters===void 0||Array.isArray(e.main_characters)&&e.main_characters.every(t=>Qe(t)&&typeof t.name=="string"&&typeof t.role=="string"))&&Array.isArray(e.actors)&&e.actors.every(E_)&&Array.isArray(e.locations)&&e.locations.every(x_)&&Array.isArray(e.props)&&e.props.every(S_)&&Array.isArray(e.episodes)&&e.episodes.every(k_)&&fo(e)}function Tt(e){if(b_(e))return e;throw new S("The local file is not a structurally readable Script v3 document.",{exitCode:k,errorCode:"SCRIPT_V3_SHAPE_INVALID",hint:"Repair the local Script v3 structure, then rerun authoring.",data:{expected:["Script v3 with typed assets, episodes, scenes, and actions"],actual:[Array.isArray(e)?"array":typeof e]}})}var zc=[3,4],O_={3:{version:3,require:Tt,requireStructurallyReadable:Tt,validate:wt},4:{version:4,require:Vi,requireStructurallyReadable:_n,validate:Pe}};function mo(e){return typeof e=="number"&&zc.some(t=>t===e)}function Qo(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new S("script.json must be an object with an explicit version.",{exitCode:k,errorCode:"SCRIPT_VERSION_MISSING",data:{expected:["version: 3 or version: 4"],actual:[Array.isArray(e)?"array":typeof e]}});let t=e.version;if(mo(t))return t;throw new S("script.json must declare version 3 or version 4.",{exitCode:k,errorCode:t===void 0?"SCRIPT_VERSION_MISSING":"SCRIPT_VERSION_UNSUPPORTED",hint:"Use an explicit supported script version; scriptctl does not infer a version from document shape.",data:{expected:["version: 3 or version: 4"],actual:[String(t)]}})}function Hc(e){return O_[Qo(e)]}function Gs(e){return Hc(e).require(e)}function Bs(e){return Hc(e).requireStructurallyReadable(e)}function Mr(e){return Hc(e).validate(e)}function Js(e){throw new S("Use a bare typed v4 ID or asset/state address.",{exitCode:J,errorCode:"V4_ADDRESS_INVALID",data:{expected:["ep\u2026 | scn\u2026 | ac\u2026 | act\u2026 | loc\u2026 | prp\u2026 | asset_id/state_id"],actual:[e||"<empty>"]}})}function Nr(e){let t=typeof e=="string"?e.trim():"",n=t.indexOf("/");if(n>=0){n!==t.lastIndexOf("/")&&Js(t);let o=t.slice(0,n),i=t.slice(n+1);return i!=="default"&&!$("state",i)&&Js(t),$("actor",o)?{kind:"state",assetKind:"actor",assetId:o,stateId:i}:$("location",o)?{kind:"state",assetKind:"location",assetId:o,stateId:i}:$("prop",o)?{kind:"state",assetKind:"prop",assetId:o,stateId:i}:Js(t)}return $("episode",t)?{kind:"episode",id:t}:$("scene",t)?{kind:"scene",id:t}:$("action",t)?{kind:"action",id:t}:$("actor",t)?{kind:"asset",assetKind:"actor",id:t}:$("location",t)?{kind:"asset",assetKind:"location",id:t}:$("prop",t)?{kind:"asset",assetKind:"prop",id:t}:Js(t)}function Yo(e){return e.episodes.map((t,n)=>({episode:t,episodeIndex:n}))}function jn(e){let t=[],n=0;return e.episodes.forEach((o,i)=>{o.scenes.forEach((r,s)=>{t.push({episode:o,episodeIndex:i,scene:r,sceneIndex:s,globalSceneIndex:n}),n++})}),t}function qo(e){let t=[],n=0,o=0;return e.episodes.forEach((i,r)=>{i.scenes.forEach((s,c)=>{s.actions.forEach((a,d)=>{t.push({episode:i,episodeIndex:r,scene:s,sceneIndex:c,globalSceneIndex:n,action:a,actionIndex:d,globalActionIndex:o}),o++}),n++})}),t}function En(e,t){return Yo(e).find(n=>n.episode.episode_id===t)??null}function Kn(e,t){return jn(e).find(n=>n.scene.scene_id===t)??null}function go(e,t){throw new S(t,{exitCode:J,errorCode:"ORDINAL_ANCHOR_INVALID",data:{expected:["@ep:N | @ep:N/scn:N | @ep:N/scn:N/ac:N | @scn:N | @scn:N/ac:N | @ac:N"],actual:[e]}})}function xn(e,t){return/^[1-9]\d*$/.test(e)||go(t,"Ordinal positions are 1-based positive integers."),Number(e)}function js(e,t){let n=/^@ep:(\d+)$/.exec(t);if(n){let o=Yo(e)[xn(n[1],t)-1];return o||go(t,"Episode ordinal is outside the current script."),{kind:"episode",id:o.episode.episode_id}}if(n=/^@ep:(\d+)\/scn:(\d+)$/.exec(t),n){let o=Yo(e)[xn(n[1],t)-1],i=o?.episode.scenes[xn(n[2],t)-1];return(!o||!i)&&go(t,"Episode-local scene ordinal is outside the current script."),{kind:"scene",id:i.scene_id}}if(n=/^@ep:(\d+)\/scn:(\d+)\/ac:(\d+)$/.exec(t),n){let o=Yo(e)[xn(n[1],t)-1],i=o?.episode.scenes[xn(n[2],t)-1],r=i?.actions[xn(n[3],t)-1];return(!o||!i||!r)&&go(t,"Episode-local action ordinal is outside the current script."),{kind:"action",id:r.action_id}}if(n=/^@scn:(\d+)$/.exec(t),n){let o=jn(e)[xn(n[1],t)-1];return o||go(t,"Global scene ordinal is outside the current script."),{kind:"scene",id:o.scene.scene_id}}if(n=/^@scn:(\d+)\/ac:(\d+)$/.exec(t),n){let o=jn(e)[xn(n[1],t)-1],i=o?.scene.actions[xn(n[2],t)-1];return(!o||!i)&&go(t,"Scene-local action ordinal is outside the current script."),{kind:"action",id:i.action_id}}if(n=/^@ac:(\d+)$/.exec(t),n){let o=qo(e)[xn(n[1],t)-1];return o||go(t,"Global action ordinal is outside the current script."),{kind:"action",id:o.action.action_id}}return go(t,"Ordinal anchor syntax is not supported.")}function Di(e,t){throw new S(e,{exitCode:J,errorCode:"V4_SELECTOR_INVALID",data:{expected:["typed v4 ID or same-kind inclusive range; comma joins regions"],actual:[t]}})}function Ou(e,t){return e.kind==="episode"||e.kind==="scene"||e.kind==="action"?e.kind:Di("Asset and state addresses are not narrative range anchors.",t)}function vu(e){return e.kind==="state"?`${e.assetId}/${e.stateId}`:e.id}function Ru(e,t,n){return t.startsWith("@")?(n||Di("Ordinal anchors are query-only.",t),js(e,t)):Nr(t)}function v_(e,t,n,o){let i=e.indexOf(t),r=e.indexOf(n);(i<0||r<0)&&Di("Range endpoint does not exist in the current script.",o);let s=Math.min(i,r),c=Math.max(i,r);return e.slice(s,c+1)}function Ks(e,t,n){let o=typeof t=="string"?t.trim():"";if(!o)return{isEmpty:!0,isWholeScript:!1,matchesEpisode:()=>!0,matchesScene:()=>!0,matchesAction:()=>!0};if(o==="*")return{isEmpty:!1,isWholeScript:!0,matchesEpisode:()=>!0,matchesScene:()=>!0,matchesAction:()=>!0};let i=Yo(e),r=jn(e),s=qo(e),c=i.map(m=>m.episode.episode_id),a=r.map(m=>m.scene.scene_id),d=s.map(m=>m.action.action_id),p=new Set,l=new Set,f=new Set,u=m=>{p.add(m);let w=i.find(y=>y.episode.episode_id===m)?.episode;w&&w.scenes.forEach(y=>{l.add(y.scene_id),y.actions.forEach(_=>f.add(_.action_id))})},g=m=>{l.add(m);let w=r.find(y=>y.scene.scene_id===m);w&&(p.add(w.episode.episode_id),w.scene.actions.forEach(y=>f.add(y.action_id)))},h=m=>{f.add(m);let w=s.find(y=>y.action.action_id===m);w&&(p.add(w.episode.episode_id),l.add(w.scene.scene_id))};for(let m of o.split(",")){let w=m.trim();w||Di("Selector contains an empty region.",o);let y=w.split("..");y.length>2&&Di("Selector region has too many range delimiters.",w);let _=Ru(e,y[0].trim(),n.allowOrdinals),x=Ru(e,(y[1]??y[0]).trim(),n.allowOrdinals),E=Ou(_,w);Ou(x,w)!==E&&Di("Range endpoints must have the same kind.",w);let A=vu(_),b=vu(x),R=v_(E==="episode"?c:E==="scene"?a:d,A,b,w);E==="episode"?R.forEach(u):E==="scene"?R.forEach(g):R.forEach(h)}return{isEmpty:!1,isWholeScript:!1,matchesEpisode:m=>p.has(m),matchesScene:m=>l.has(m),matchesAction:m=>f.has(m)}}function ho(e,t){throw new S(e,{exitCode:J,errorCode:"AUTHORING_SELECTOR_INVALID",data:{actual:t}})}function R_(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function M_(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function se(e,t,n=""){let o=[e,...t].map(R_).join("|"),i=M_(n);return`[${o}]${i?` ${i}`:""}`}function Yc(e){if(Array.isArray(e))return e.map(Yc);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=Yc(e[n]);return t}return e}function yo(e){return e===void 0?[]:[se("extensions",[]),...Object.keys(e).sort().map(t=>se("extend",[t],JSON.stringify(Yc(e[t]))))]}function N_(e){return"actor_id"in e?e.state_id===void 0?e.actor_id:`${e.actor_id}/${e.state_id}`:e.label===void 0?e.kind:`${e.kind}:${e.label}`}function Mu(e){let t=yo(e.extend);if(e.transition_prompt!==void 0&&t.push(se("prompt",[e.transition_prompt.target,e.transition_prompt.process,e.transition_prompt.contrast])),e.type==="dialogue"||e.type==="inner_thought"){let n=[e.action_id,N_(e.speaker)];"parenthetical"in e&&n.push(e.parenthetical??""),t.push(se(e.type==="dialogue"?"dlg":"think",n,e.content))}else t.push(se(e.type==="action"?"act":"trans",[e.action_id],e.content));return t}function qc(e,t){let n=[...yo(e.extend),`<scene ${t}>`];if(e.environment!==void 0){let o=e.environment.time===void 0?e.environment.space===void 0?[]:[e.environment.space]:[e.environment.space??"",e.environment.time];n.push(se("environment",o))}n.push(e.location===null?se("location",[]):se("location",[e.location.location_id,...e.location.state_ids]));for(let o of e.actors)n.push(se("cast",[o.actor_id,...o.state_ids]));for(let o of e.props)n.push(se("prop",[o.prop_id,...o.state_ids]));return n.push("","<body>"),e.actions.forEach(o=>n.push(...Mu(o))),n.push("</body>","","</scene>"),n}function Zc(e){let t=[...yo(e.extend),`<episode id=${e.episode_id}>`];return e.title!==void 0&&t.push(se("title",[],e.title)),e.synopsis!==void 0&&t.push(se("synopsis",[],e.synopsis)),e.scenes.forEach((n,o)=>{(o>0||e.title!==void 0||e.synopsis!==void 0)&&t.push(""),t.push(...qc(n,`id=${n.scene_id}`))}),t.push("</episode>"),t}function Fc(e,t){return[...yo(t.extend),se("state",[e,t.state_id,t.state_name],t.description)]}function L_(e){let t=["<create>"];for(let n of e.actors){t.push(...yo(n.extend)),n.aliases!==void 0&&(t.push(se("aliases",[])),n.aliases.forEach(i=>t.push(se("alias",[],i))));let o=[n.actor_id,n.actor_name,n.importance];n.role_type!==void 0&&o.push(n.role_type),t.push(se("actor",o,n.description)),n.states.forEach(i=>t.push(...Fc(n.actor_id,i)))}for(let n of e.locations)t.push(...yo(n.extend)),n.aliases!==void 0&&(t.push(se("aliases",[])),n.aliases.forEach(o=>t.push(se("alias",[],o)))),t.push(se("location",[n.location_id,n.location_name,n.importance],n.description)),n.states.forEach(o=>t.push(...Fc(n.location_id,o)));for(let n of e.props)t.push(...yo(n.extend)),n.aliases!==void 0&&(t.push(se("aliases",[])),n.aliases.forEach(o=>t.push(se("alias",[],o)))),t.push(se("prop",[n.prop_id,n.prop_name,n.importance],n.description)),n.states.forEach(o=>t.push(...Fc(n.prop_id,o)));return t.push("</create>"),t}function U_(e){let t=[...yo(e.extend),"<script>"];return t.push(se("title",[],e.title),se("worldview",[],e.worldview)),e.worldview_raw!==void 0&&t.push(se("worldview-raw",[],e.worldview_raw)),t.push(se("style",[],e.style)),e.synopsis!==void 0&&t.push(se("synopsis",[],e.synopsis)),e.logline!==void 0&&t.push(se("logline",[],e.logline)),e.theme!==void 0&&t.push(se("theme",[],e.theme)),e.main_characters!==void 0&&(t.push(se("main-characters",[])),e.main_characters.forEach(n=>t.push(se("main-character",[n.name,n.role])))),e.episodes.forEach(n=>t.push("",...Zc(n))),t.push("</script>"),t}function P_(e){return e.trim()||ho("This export kind requires --in.",["<missing>"]),e.split(",").map(t=>{let n=t.trim().split("..");return n.length>2||!n[0]||n.length===2&&!n[1]?ho("Selector region is invalid.",[t]):{left:n[0],right:n[1]??n[0]}})}function Qc(e,t,n,o,i){let r=-1;return P_(i).map(s=>{let c=f=>{if(!f.startsWith("@"))return f;let u=js(e,f);return u.kind!==t?ho("Selector endpoint kind does not match the export kind.",[f,t]):u.id},a=o.indexOf(c(s.left)),d=o.indexOf(c(s.right));(a<0||d<0)&&ho("Selector endpoint was not found.",[s.left,s.right]);let p=Math.min(a,d),l=Math.max(a,d);return p<=r&&ho("Selector regions must follow current document order without overlap.",[`${s.left}..${s.right}`]),r=l,n.slice(p,l+1)})}function Nu(e,t,n){let o=["<authoring version=1>",""],i=0;if(t==="script")o.push(...L_(e),"",...U_(e)),i=1;else if(t==="episodes"){let r=Ks(e,n,{allowOrdinals:!0}),s=e.episodes.filter(c=>r.matchesEpisode(c.episode_id));s.forEach((c,a)=>{a>0&&o.push(""),o.push(...Zc(c))}),i=s.length}else if(t==="episode-spans"){let r=Qc(e,"episode",e.episodes,e.episodes.map(s=>s.episode_id),n);for(let[s,c]of r.entries())s>0&&o.push(""),o.push(`<episode-span range=${c[0].episode_id}..${c.at(-1).episode_id}>`),c.forEach(a=>o.push(...Zc(a))),o.push("</episode-span>"),i++}else if(t==="scenes"){let r=Ks(e,n,{allowOrdinals:!0}),s=jn(e).filter(c=>r.matchesScene(c.scene.scene_id));s.forEach((c,a)=>{a>0&&o.push(""),o.push(...qc(c.scene,`id=${c.scene.scene_id} parent=${c.episode.episode_id}`))}),i=s.length}else if(t==="scene-spans"){let r=jn(e),s=Qc(e,"scene",r,r.map(c=>c.scene.scene_id),n);for(let[c,a]of s.entries()){let d=a[0].episode.episode_id;a.every(p=>p.episode.episode_id===d)||ho("A scene span must remain inside one episode.",[a[0].scene.scene_id,a.at(-1).scene.scene_id]),c>0&&o.push(""),o.push(`<scene-span parent=${d} range=${a[0].scene.scene_id}..${a.at(-1).scene.scene_id}>`),a.forEach(p=>o.push(...qc(p.scene,`id=${p.scene.scene_id}`))),o.push("</scene-span>"),i++}}else{let r=qo(e),s=Qc(e,"action",r,r.map(c=>c.action.action_id),n);for(let[c,a]of s.entries()){let d=a[0].scene.scene_id;a.every(p=>p.scene.scene_id===d)||ho("An action span must remain inside one scene.",[a[0].action.action_id,a.at(-1).action.action_id]),c>0&&o.push(""),o.push(`<action-span parent=${d} range=${a[0].action.action_id}..${a.at(-1).action.action_id}>`,"<body>"),a.forEach(p=>o.push(...Mu(p.action))),o.push("</body>","</action-span>"),i++}}return i===0&&ho("Selector did not match any authoring targets.",[n||"<empty>"]),o.push("","</authoring>"),{content:`${o.join(`
126
+ `}function Qe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function _t(e,t){return e[t]===void 0||typeof e[t]=="string"}function zc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(zc):Qe(e)&&Object.values(e).every(zc)}function mo(e){return e.extend===void 0||Qe(e.extend)&&Object.values(e.extend).every(zc)}function Hc(e){return Qe(e)&&typeof e.state_id=="string"&&typeof e.state_name=="string"&&typeof e.description=="string"&&mo(e)}function I_(e){return Qe(e)&&typeof e.actor_id=="string"&&typeof e.actor_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&Pt.has(e.importance)&&(e.aliases===void 0||Array.isArray(e.aliases)&&e.aliases.every(t=>typeof t=="string"))&&(e.role_type===void 0||e.role_type==="\u4E3B\u89D2"||e.role_type==="\u914D\u89D2")&&Array.isArray(e.states)&&e.states.every(Hc)&&mo(e)}function A_(e){return Qe(e)&&typeof e.location_id=="string"&&typeof e.location_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&Pt.has(e.importance)&&(e.aliases===void 0||Array.isArray(e.aliases)&&e.aliases.every(t=>typeof t=="string"))&&Array.isArray(e.states)&&e.states.every(Hc)&&mo(e)}function k_(e){return Qe(e)&&typeof e.prop_id=="string"&&typeof e.prop_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&Pt.has(e.importance)&&(e.aliases===void 0||Array.isArray(e.aliases)&&e.aliases.every(t=>typeof t=="string"))&&Array.isArray(e.states)&&e.states.every(Hc)&&mo(e)}function b_(e){if(!Qe(e)||typeof e.type!="string"||!qt.has(e.type)||typeof e.content!="string"||!_t(e,"emotion"))return!1;if(e.speaker!==void 0){if(!Qe(e.speaker))return!1;if(typeof e.speaker.actor_id=="string"){if(!_t(e.speaker,"state_id"))return!1}else if(typeof e.speaker.kind=="string"){if(!Ho.has(e.speaker.kind)||!_t(e.speaker,"label"))return!1}else return!1}return e.transition_prompt!==void 0&&(!Qe(e.transition_prompt)||typeof e.transition_prompt.target!="string"||typeof e.transition_prompt.process!="string"||typeof e.transition_prompt.contrast!="string")?!1:mo(e)}function O_(e){return!Qe(e)||typeof e.scene_id!="string"||!Array.isArray(e.actors)||!Array.isArray(e.props)||!Array.isArray(e.actions)||!e.actions.every(b_)||!e.actors.every(t=>Qe(t)&&typeof t.actor_id=="string"&&_t(t,"state_id"))||!e.props.every(t=>Qe(t)&&typeof t.prop_id=="string"&&_t(t,"state_id"))||e.location!==null&&(!Qe(e.location)||typeof e.location.location_id!="string"||!_t(e.location,"state_id"))||e.environment!==void 0&&(!Qe(e.environment)||!_t(e.environment,"space")||!_t(e.environment,"time"))?!1:mo(e)}function v_(e){return Qe(e)&&typeof e.episode_id=="string"&&_t(e,"title")&&_t(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(O_)&&mo(e)}function R_(e){return Qe(e)&&e.version===3&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&_t(e,"worldview_raw")&&_t(e,"synopsis")&&_t(e,"logline")&&_t(e,"theme")&&(e.main_characters===void 0||Array.isArray(e.main_characters)&&e.main_characters.every(t=>Qe(t)&&typeof t.name=="string"&&typeof t.role=="string"))&&Array.isArray(e.actors)&&e.actors.every(I_)&&Array.isArray(e.locations)&&e.locations.every(A_)&&Array.isArray(e.props)&&e.props.every(k_)&&Array.isArray(e.episodes)&&e.episodes.every(v_)&&mo(e)}function Tt(e){if(R_(e))return e;throw new x("The local file is not a structurally readable Script v3 document.",{exitCode:k,errorCode:"SCRIPT_V3_SHAPE_INVALID",hint:"Repair the local Script v3 structure, then rerun authoring.",data:{expected:["Script v3 with typed assets, episodes, scenes, and actions"],actual:[Array.isArray(e)?"array":typeof e]}})}var Fc=[3,4],M_={3:{version:3,require:Tt,requireStructurallyReadable:Tt,validate:wt},4:{version:4,require:$i,requireStructurallyReadable:_n,validate:Pe}};function go(e){return typeof e=="number"&&Fc.some(t=>t===e)}function Qo(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new x("script.json must be an object with an explicit version.",{exitCode:k,errorCode:"SCRIPT_VERSION_MISSING",data:{expected:["version: 3 or version: 4"],actual:[Array.isArray(e)?"array":typeof e]}});let t=e.version;if(go(t))return t;throw new x("script.json must declare version 3 or version 4.",{exitCode:k,errorCode:t===void 0?"SCRIPT_VERSION_MISSING":"SCRIPT_VERSION_UNSUPPORTED",hint:"Use an explicit supported script version; scriptctl does not infer a version from document shape.",data:{expected:["version: 3 or version: 4"],actual:[String(t)]}})}function Qc(e){return M_[Qo(e)]}function Bs(e){return Qc(e).require(e)}function Js(e){return Qc(e).requireStructurallyReadable(e)}function Lr(e){return Qc(e).validate(e)}function Ks(e){throw new x("Use a bare typed v4 ID or asset/state address.",{exitCode:B,errorCode:"V4_ADDRESS_INVALID",data:{expected:["ep\u2026 | scn\u2026 | ac\u2026 | act\u2026 | loc\u2026 | prp\u2026 | asset_id/state_id"],actual:[e||"<empty>"]}})}function Ur(e){let t=typeof e=="string"?e.trim():"",n=t.indexOf("/");if(n>=0){n!==t.lastIndexOf("/")&&Ks(t);let o=t.slice(0,n),i=t.slice(n+1);return i!=="default"&&!V("state",i)&&Ks(t),V("actor",o)?{kind:"state",assetKind:"actor",assetId:o,stateId:i}:V("location",o)?{kind:"state",assetKind:"location",assetId:o,stateId:i}:V("prop",o)?{kind:"state",assetKind:"prop",assetId:o,stateId:i}:Ks(t)}return V("episode",t)?{kind:"episode",id:t}:V("scene",t)?{kind:"scene",id:t}:V("action",t)?{kind:"action",id:t}:V("actor",t)?{kind:"asset",assetKind:"actor",id:t}:V("location",t)?{kind:"asset",assetKind:"location",id:t}:V("prop",t)?{kind:"asset",assetKind:"prop",id:t}:Ks(t)}function Yo(e){return e.episodes.map((t,n)=>({episode:t,episodeIndex:n}))}function Kn(e){let t=[],n=0;return e.episodes.forEach((o,i)=>{o.scenes.forEach((r,s)=>{t.push({episode:o,episodeIndex:i,scene:r,sceneIndex:s,globalSceneIndex:n}),n++})}),t}function qo(e){let t=[],n=0,o=0;return e.episodes.forEach((i,r)=>{i.scenes.forEach((s,c)=>{s.actions.forEach((a,d)=>{t.push({episode:i,episodeIndex:r,scene:s,sceneIndex:c,globalSceneIndex:n,action:a,actionIndex:d,globalActionIndex:o}),o++}),n++})}),t}function En(e,t){return Yo(e).find(n=>n.episode.episode_id===t)??null}function jn(e,t){return Kn(e).find(n=>n.scene.scene_id===t)??null}function ho(e,t){throw new x(t,{exitCode:B,errorCode:"ORDINAL_ANCHOR_INVALID",data:{expected:["@ep:N | @ep:N/scn:N | @ep:N/scn:N/ac:N | @scn:N | @scn:N/ac:N | @ac:N"],actual:[e]}})}function xn(e,t){return/^[1-9]\d*$/.test(e)||ho(t,"Ordinal positions are 1-based positive integers."),Number(e)}function js(e,t){let n=/^@ep:(\d+)$/.exec(t);if(n){let o=Yo(e)[xn(n[1],t)-1];return o||ho(t,"Episode ordinal is outside the current script."),{kind:"episode",id:o.episode.episode_id}}if(n=/^@ep:(\d+)\/scn:(\d+)$/.exec(t),n){let o=Yo(e)[xn(n[1],t)-1],i=o?.episode.scenes[xn(n[2],t)-1];return(!o||!i)&&ho(t,"Episode-local scene ordinal is outside the current script."),{kind:"scene",id:i.scene_id}}if(n=/^@ep:(\d+)\/scn:(\d+)\/ac:(\d+)$/.exec(t),n){let o=Yo(e)[xn(n[1],t)-1],i=o?.episode.scenes[xn(n[2],t)-1],r=i?.actions[xn(n[3],t)-1];return(!o||!i||!r)&&ho(t,"Episode-local action ordinal is outside the current script."),{kind:"action",id:r.action_id}}if(n=/^@scn:(\d+)$/.exec(t),n){let o=Kn(e)[xn(n[1],t)-1];return o||ho(t,"Global scene ordinal is outside the current script."),{kind:"scene",id:o.scene.scene_id}}if(n=/^@scn:(\d+)\/ac:(\d+)$/.exec(t),n){let o=Kn(e)[xn(n[1],t)-1],i=o?.scene.actions[xn(n[2],t)-1];return(!o||!i)&&ho(t,"Scene-local action ordinal is outside the current script."),{kind:"action",id:i.action_id}}if(n=/^@ac:(\d+)$/.exec(t),n){let o=qo(e)[xn(n[1],t)-1];return o||ho(t,"Global action ordinal is outside the current script."),{kind:"action",id:o.action.action_id}}return ho(t,"Ordinal anchor syntax is not supported.")}function Gi(e,t){throw new x(e,{exitCode:B,errorCode:"V4_SELECTOR_INVALID",data:{expected:["typed v4 ID or same-kind inclusive range; comma joins regions"],actual:[t]}})}function Ru(e,t){return e.kind==="episode"||e.kind==="scene"||e.kind==="action"?e.kind:Gi("Asset and state addresses are not narrative range anchors.",t)}function Mu(e){return e.kind==="state"?`${e.assetId}/${e.stateId}`:e.id}function Nu(e,t,n){return t.startsWith("@")?(n||Gi("Ordinal anchors are query-only.",t),js(e,t)):Ur(t)}function N_(e,t,n,o){let i=e.indexOf(t),r=e.indexOf(n);(i<0||r<0)&&Gi("Range endpoint does not exist in the current script.",o);let s=Math.min(i,r),c=Math.max(i,r);return e.slice(s,c+1)}function zs(e,t,n){let o=typeof t=="string"?t.trim():"";if(!o)return{isEmpty:!0,isWholeScript:!1,matchesEpisode:()=>!0,matchesScene:()=>!0,matchesAction:()=>!0};if(o==="*")return{isEmpty:!1,isWholeScript:!0,matchesEpisode:()=>!0,matchesScene:()=>!0,matchesAction:()=>!0};let i=Yo(e),r=Kn(e),s=qo(e),c=i.map(g=>g.episode.episode_id),a=r.map(g=>g.scene.scene_id),d=s.map(g=>g.action.action_id),p=new Set,l=new Set,f=new Set,u=g=>{p.add(g);let w=i.find(y=>y.episode.episode_id===g)?.episode;w&&w.scenes.forEach(y=>{l.add(y.scene_id),y.actions.forEach(_=>f.add(_.action_id))})},m=g=>{l.add(g);let w=r.find(y=>y.scene.scene_id===g);w&&(p.add(w.episode.episode_id),w.scene.actions.forEach(y=>f.add(y.action_id)))},h=g=>{f.add(g);let w=s.find(y=>y.action.action_id===g);w&&(p.add(w.episode.episode_id),l.add(w.scene.scene_id))};for(let g of o.split(",")){let w=g.trim();w||Gi("Selector contains an empty region.",o);let y=w.split("..");y.length>2&&Gi("Selector region has too many range delimiters.",w);let _=Nu(e,y[0].trim(),n.allowOrdinals),S=Nu(e,(y[1]??y[0]).trim(),n.allowOrdinals),E=Ru(_,w);Ru(S,w)!==E&&Gi("Range endpoints must have the same kind.",w);let A=Mu(_),b=Mu(S),M=N_(E==="episode"?c:E==="scene"?a:d,A,b,w);E==="episode"?M.forEach(u):E==="scene"?M.forEach(m):M.forEach(h)}return{isEmpty:!1,isWholeScript:!1,matchesEpisode:g=>p.has(g),matchesScene:g=>l.has(g),matchesAction:g=>f.has(g)}}function yo(e,t){throw new x(e,{exitCode:B,errorCode:"AUTHORING_SELECTOR_INVALID",data:{actual:t}})}function L_(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function U_(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function se(e,t,n=""){let o=[e,...t].map(L_).join("|"),i=U_(n);return`[${o}]${i?` ${i}`:""}`}function Zc(e){if(Array.isArray(e))return e.map(Zc);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=Zc(e[n]);return t}return e}function wo(e){return e===void 0?[]:[se("extensions",[]),...Object.keys(e).sort().map(t=>se("extend",[t],JSON.stringify(Zc(e[t]))))]}function P_(e){return"actor_id"in e?e.state_id===void 0?e.actor_id:`${e.actor_id}/${e.state_id}`:e.label===void 0?e.kind:`${e.kind}:${e.label}`}function Lu(e){let t=wo(e.extend);if(e.transition_prompt!==void 0&&t.push(se("prompt",[e.transition_prompt.target,e.transition_prompt.process,e.transition_prompt.contrast])),e.type==="dialogue"||e.type==="inner_thought"){let n=[e.action_id,P_(e.speaker)];"parenthetical"in e&&n.push(e.parenthetical??""),t.push(se(e.type==="dialogue"?"dlg":"think",n,e.content))}else t.push(se(e.type==="action"?"act":"trans",[e.action_id],e.content));return t}function Wc(e,t){let n=[...wo(e.extend),`<scene ${t}>`];if(e.environment!==void 0){let o=e.environment.time===void 0?e.environment.space===void 0?[]:[e.environment.space]:[e.environment.space??"",e.environment.time];n.push(se("environment",o))}n.push(e.location===null?se("location",[]):se("location",[e.location.location_id,...e.location.state_ids]));for(let o of e.actors)n.push(se("cast",[o.actor_id,...o.state_ids]));for(let o of e.props)n.push(se("prop",[o.prop_id,...o.state_ids]));return n.push("","<body>"),e.actions.forEach(o=>n.push(...Lu(o))),n.push("</body>","","</scene>"),n}function Xc(e){let t=[...wo(e.extend),`<episode id=${e.episode_id}>`];return e.title!==void 0&&t.push(se("title",[],e.title)),e.synopsis!==void 0&&t.push(se("synopsis",[],e.synopsis)),e.scenes.forEach((n,o)=>{(o>0||e.title!==void 0||e.synopsis!==void 0)&&t.push(""),t.push(...Wc(n,`id=${n.scene_id}`))}),t.push("</episode>"),t}function Yc(e,t){return[...wo(t.extend),se("state",[e,t.state_id,t.state_name],t.description)]}function C_(e){let t=["<create>"];for(let n of e.actors){t.push(...wo(n.extend)),n.aliases!==void 0&&(t.push(se("aliases",[])),n.aliases.forEach(i=>t.push(se("alias",[],i))));let o=[n.actor_id,n.actor_name,n.importance];n.role_type!==void 0&&o.push(n.role_type),t.push(se("actor",o,n.description)),n.states.forEach(i=>t.push(...Yc(n.actor_id,i)))}for(let n of e.locations)t.push(...wo(n.extend)),n.aliases!==void 0&&(t.push(se("aliases",[])),n.aliases.forEach(o=>t.push(se("alias",[],o)))),t.push(se("location",[n.location_id,n.location_name,n.importance],n.description)),n.states.forEach(o=>t.push(...Yc(n.location_id,o)));for(let n of e.props)t.push(...wo(n.extend)),n.aliases!==void 0&&(t.push(se("aliases",[])),n.aliases.forEach(o=>t.push(se("alias",[],o)))),t.push(se("prop",[n.prop_id,n.prop_name,n.importance],n.description)),n.states.forEach(o=>t.push(...Yc(n.prop_id,o)));return t.push("</create>"),t}function T_(e){let t=[...wo(e.extend),"<script>"];return t.push(se("title",[],e.title),se("worldview",[],e.worldview)),e.worldview_raw!==void 0&&t.push(se("worldview-raw",[],e.worldview_raw)),t.push(se("style",[],e.style)),e.synopsis!==void 0&&t.push(se("synopsis",[],e.synopsis)),e.logline!==void 0&&t.push(se("logline",[],e.logline)),e.theme!==void 0&&t.push(se("theme",[],e.theme)),e.main_characters!==void 0&&(t.push(se("main-characters",[])),e.main_characters.forEach(n=>t.push(se("main-character",[n.name,n.role])))),e.episodes.forEach(n=>t.push("",...Xc(n))),t.push("</script>"),t}function V_(e){return e.trim()||yo("This export kind requires --in.",["<missing>"]),e.split(",").map(t=>{let n=t.trim().split("..");return n.length>2||!n[0]||n.length===2&&!n[1]?yo("Selector region is invalid.",[t]):{left:n[0],right:n[1]??n[0]}})}function qc(e,t,n,o,i){let r=-1;return V_(i).map(s=>{let c=f=>{if(!f.startsWith("@"))return f;let u=js(e,f);return u.kind!==t?yo("Selector endpoint kind does not match the export kind.",[f,t]):u.id},a=o.indexOf(c(s.left)),d=o.indexOf(c(s.right));(a<0||d<0)&&yo("Selector endpoint was not found.",[s.left,s.right]);let p=Math.min(a,d),l=Math.max(a,d);return p<=r&&yo("Selector regions must follow current document order without overlap.",[`${s.left}..${s.right}`]),r=l,n.slice(p,l+1)})}function Uu(e,t,n){let o=["<authoring version=1>",""],i=0;if(t==="script")o.push(...C_(e),"",...T_(e)),i=1;else if(t==="episodes"){let r=zs(e,n,{allowOrdinals:!0}),s=e.episodes.filter(c=>r.matchesEpisode(c.episode_id));s.forEach((c,a)=>{a>0&&o.push(""),o.push(...Xc(c))}),i=s.length}else if(t==="episode-spans"){let r=qc(e,"episode",e.episodes,e.episodes.map(s=>s.episode_id),n);for(let[s,c]of r.entries())s>0&&o.push(""),o.push(`<episode-span range=${c[0].episode_id}..${c.at(-1).episode_id}>`),c.forEach(a=>o.push(...Xc(a))),o.push("</episode-span>"),i++}else if(t==="scenes"){let r=zs(e,n,{allowOrdinals:!0}),s=Kn(e).filter(c=>r.matchesScene(c.scene.scene_id));s.forEach((c,a)=>{a>0&&o.push(""),o.push(...Wc(c.scene,`id=${c.scene.scene_id} parent=${c.episode.episode_id}`))}),i=s.length}else if(t==="scene-spans"){let r=Kn(e),s=qc(e,"scene",r,r.map(c=>c.scene.scene_id),n);for(let[c,a]of s.entries()){let d=a[0].episode.episode_id;a.every(p=>p.episode.episode_id===d)||yo("A scene span must remain inside one episode.",[a[0].scene.scene_id,a.at(-1).scene.scene_id]),c>0&&o.push(""),o.push(`<scene-span parent=${d} range=${a[0].scene.scene_id}..${a.at(-1).scene.scene_id}>`),a.forEach(p=>o.push(...Wc(p.scene,`id=${p.scene.scene_id}`))),o.push("</scene-span>"),i++}}else{let r=qo(e),s=qc(e,"action",r,r.map(c=>c.action.action_id),n);for(let[c,a]of s.entries()){let d=a[0].scene.scene_id;a.every(p=>p.scene.scene_id===d)||yo("An action span must remain inside one scene.",[a[0].action.action_id,a.at(-1).action.action_id]),c>0&&o.push(""),o.push(`<action-span parent=${d} range=${a[0].action.action_id}..${a.at(-1).action.action_id}>`,"<body>"),a.forEach(p=>o.push(...Lu(p.action))),o.push("</body>","</action-span>"),i++}}return i===0&&yo("Selector did not match any authoring targets.",[n||"<empty>"]),o.push("","</authoring>"),{content:`${o.join(`
127
127
  `)}
128
- `,targetCount:i}}function le(e,t,n,o,i=k){throw new S(t,{exitCode:i,errorCode:e,hint:o,data:{actual:n}})}function C_(e){let t=ge(e),n;try{n=JSON.parse(Uu.readFileSync(t,"utf-8"))}catch(o){le("SCRIPT_JSON_UNAVAILABLE","The local script cannot be read as JSON.",[t,o instanceof Error?o.message:String(o)],"Provide a readable local Script v3 file.")}return Bs(n)}function Lr(e){return e||le("AUTHORING_SELECTOR_REQUIRED","This export kind requires --in.",["<missing>"],"Pass one or more comma-separated point or from..through regions.",J),e.split(",").map(t=>{let n=t.trim();n||le("AUTHORING_SELECTOR_INVALID","Selector contains an empty region.",[e],"Remove empty comma-separated regions.",J);let o=n.indexOf("..");if(o<0)return{from:n,through:n};n.indexOf("..",o+2)>=0&&le("AUTHORING_SELECTOR_INVALID","Selector region has more than one range delimiter.",[n],"Use point or from..through.",J);let i=n.slice(0,o),r=n.slice(o+2);return(!i||!r)&&le("AUTHORING_SELECTOR_INVALID","Selector range endpoint is empty.",[n],"Provide both endpoints.",J),{from:i,through:r}})}function zs(e,t,n){if(t.from==="*"&&t.through==="*")return e.length===0&&le("AUTHORING_SELECTOR_EMPTY",`The script contains no ${n}.`,["*"],"Choose a non-empty target kind."),[0,e.length-1];(e.filter(r=>r===t.from).length>1||e.filter(r=>r===t.through).length>1)&&le("AUTHORING_SELECTOR_AMBIGUOUS",`${n} selector endpoint is not unique.`,[t.from,t.through],"Repair duplicate stable IDs before exporting this target.");let o=e.indexOf(t.from),i=e.indexOf(t.through);return(o<0||i<0)&&le("AUTHORING_SELECTOR_NOT_FOUND",`${n} selector endpoint was not found.`,[t.from,t.through],"Use IDs from the current local script."),o>i&&le("AUTHORING_SELECTOR_REVERSED",`${n} selector is reversed in current document order.`,[t.from,t.through],"Put the earlier document endpoint first."),[o,i]}function Cu(e,t){let n=new Set;for(let o of e){let i=t(o);n.has(i)&&le("AUTHORING_SELECTOR_OVERLAP","Selector regions overlap or repeat a target.",[i],"Use non-overlapping regions."),n.add(i)}return e}function Ur(e,t){for(let n=1;n<e.length;n+=1){let o=e[n-1],i=e[n],r=Math.max(o.length,i.length),s=0;for(let c=0;c<r&&(s=(i[c]??0)-(o[c]??0),s===0);c+=1);s<=0&&le("AUTHORING_SELECTOR_ORDER",`${t} selector regions are not in current document order.`,[`region=${n+1}`],"List disjoint selector regions from earlier to later document positions.")}}function T_(e,t){let n=[],o=e.episodes.map(r=>r.episode_id);for(let r of Lr(t)){let[s,c]=zs(o,r,"episode");n.push(...e.episodes.slice(s,c+1))}Cu(n,r=>r.episode_id),Ur(n.map(r=>[o.indexOf(r.episode_id)]),"Episode");let i=n.map(r=>({kind:"episode",value:structuredClone(r),source:Zt}));return $i("episode",i)}function V_(e,t){let n=e.episodes.map(s=>s.episode_id),o=[],i=new Set,r=[];for(let s of Lr(t)){let[c,a]=zs(n,s,"episode");for(let d=c;d<=a;d+=1)i.has(d)&&le("AUTHORING_SELECTOR_OVERLAP","Episode span regions overlap.",[`${s.from}..${s.through}`],"Use non-overlapping regions."),i.add(d);o.push({kind:"episode-span",from:n[c],through:n[a],episodes:structuredClone(e.episodes.slice(c,a+1)),source:Zt}),r.push([c])}return Ur(r,"Episode span"),$i("episode-span",o)}function $_(e){return e.episodes.flatMap(t=>t.scenes.map(n=>({episodeId:t.episode_id,scene:n})))}function Wc(e){return`${e.episodeId}/${e.scene.scene_id}`}function D_(e,t){let n=$_(e),o=n.map(Wc),i=[];for(let s of Lr(t)){let[c,a]=zs(o,s,"scene");i.push(...n.slice(c,a+1))}Cu(i,Wc),Ur(i.map(s=>[o.indexOf(Wc(s))]),"Scene");let r=i.map(s=>({kind:"scene",parent:s.episodeId,value:structuredClone(s.scene),source:Zt}));return $i("scene",r)}function Xc(e){let t=/^([^/#]+)\/([^/#]+)$/.exec(e);return t||le("AUTHORING_SELECTOR_INVALID","Scene selector endpoint must be ep/scn.",[e],"Use ep_ID/scn_ID."),{episodeId:t[1],sceneId:t[2]}}function G_(e,t){let n=[],o=new Set,i=[];for(let r of Lr(t)){(r.from==="*"||r.through==="*")&&le("AUTHORING_SELECTOR_INVALID","A scene span wildcard has no single parent.",["*"],"Use one explicit region per episode.");let s=Xc(r.from),c=Xc(r.through);s.episodeId!==c.episodeId&&le("AUTHORING_SELECTOR_CROSS_PARENT","A scene span must remain inside one episode.",[r.from,r.through],"Split it into one region per episode.");let a=e.episodes.filter(u=>u.episode_id===s.episodeId);a.length===0&&le("AUTHORING_SELECTOR_NOT_FOUND","Scene span parent episode was not found.",[s.episodeId],"Use an existing episode ID."),a.length>1&&le("AUTHORING_SELECTOR_AMBIGUOUS","Scene span parent episode is not unique.",[s.episodeId],"Repair duplicate stable IDs before exporting.");let d=a[0],p=d.scenes.map(u=>u.scene_id),[l,f]=zs(p,{from:s.sceneId,through:c.sceneId},"scene");for(let u=l;u<=f;u+=1){let g=`${d.episode_id}/${p[u]}`;o.has(g)&&le("AUTHORING_SELECTOR_OVERLAP","Scene span regions overlap.",[g],"Use non-overlapping regions."),o.add(g)}n.push({kind:"scene-span",parent:d.episode_id,from:p[l],through:p[f],scenes:structuredClone(d.scenes.slice(l,f+1)),source:Zt}),i.push([e.episodes.indexOf(d),l])}return Ur(i,"Scene span"),$i("scene-span",n)}function Lu(e){let t=/^([^/#]+\/[^/#]+)#(\d+)$/.exec(e);t||le("AUTHORING_SELECTOR_INVALID","Action selector endpoint must be ep/scn#index.",[e],"Use a zero-based ep_ID/scn_ID#index address.");let n=Number(t[2]);return Number.isSafeInteger(n)||le("AUTHORING_SELECTOR_INVALID","Action index is outside the safe integer range.",[e],"Use a zero-based safe integer index."),{parent:t[1],index:n}}function B_(e,t){let n=[],o=new Set,i=[];for(let r of Lr(t)){(r.from==="*"||r.through==="*")&&le("AUTHORING_SELECTOR_INVALID","An action span wildcard has no single parent.",["*"],"Use one explicit region per scene.");let s=Lu(r.from),c=Lu(r.through);s.parent!==c.parent&&le("AUTHORING_SELECTOR_CROSS_PARENT","An action span must remain inside one scene.",[r.from,r.through],"Split it into one region per scene.");let a=Xc(s.parent),d=e.episodes.filter(u=>u.episode_id===a.episodeId);d.length===0&&le("AUTHORING_SELECTOR_NOT_FOUND","Action span parent episode was not found.",[a.episodeId],"Use an existing episode ID."),d.length>1&&le("AUTHORING_SELECTOR_AMBIGUOUS","Action span parent episode is not unique.",[a.episodeId],"Repair duplicate stable IDs before exporting.");let p=d[0],l=p.scenes.filter(u=>u.scene_id===a.sceneId);l.length===0&&le("AUTHORING_SELECTOR_NOT_FOUND","Action span parent scene was not found.",[s.parent],"Use an existing scene address."),l.length>1&&le("AUTHORING_SELECTOR_AMBIGUOUS","Action span parent scene is not unique.",[s.parent],"Repair duplicate stable IDs before exporting.");let f=l[0];s.index>c.index&&le("AUTHORING_SELECTOR_REVERSED","Action span is reversed.",[r.from,r.through],"Put the lower current action index first."),c.index>=f.actions.length&&le("AUTHORING_SELECTOR_NOT_FOUND","Action span endpoint is outside the current body.",[r.through,`actions=${f.actions.length}`],"Use current zero-based action indices.");for(let u=s.index;u<=c.index;u+=1){let g=`${s.parent}#${u}`;o.has(g)&&le("AUTHORING_SELECTOR_OVERLAP","Action span regions overlap.",[g],"Use non-overlapping regions."),o.add(g)}n.push({kind:"action-span",parent:s.parent,from:s.index,through:c.index,actions:structuredClone(f.actions.slice(s.index,c.index+1)),source:Zt}),i.push([e.episodes.indexOf(p),p.scenes.indexOf(f),s.index])}return Ur(i,"Action span"),$i("action-span",n)}function Tu(e,t){let n=v(t.output).trim();n||le("AUTHORING_OUTPUT_REQUIRED","Export requires --output.",["<missing>"],"Pass a destination .scriptctl file.",J);let o=C_(t),i=v(t.in).trim(),r=Pu.resolve(n);if(o.version===4){let p=Nu(_n(o),e,i);return Vs(r,p.content),[{text:`Exported ${p.targetCount} ${e} target(s) to ${r}`,data:{op:`export.${e}`,output:r,target_kind:e==="episodes"?"episode":e==="episode-spans"?"episode-span":e==="scenes"?"scene":e==="scene-spans"?"scene-span":e==="action-spans"?"action-span":"script",target_count:p.targetCount,bytes:Buffer.byteLength(p.content),script_version:4}},B]}let s=Tt(o),c;e==="script"?c=Au(s):e==="episodes"?c=T_(s,i):e==="episode-spans"?c=V_(s,i):e==="scenes"?c=D_(s,i):e==="scene-spans"?c=G_(s,i):c=B_(s,i);let a=bu(c);return Vs(r,a),[{text:`Exported ${c.targets.length} ${e} target(s) to ${r}`,data:{op:`export.${e}`,output:r,target_kind:c.targetKind,target_count:c.targets.length,bytes:Buffer.byteLength(a),script_version:3}},B]}import*as wd from"node:crypto";import*as Vr from"node:fs";import*as pf from"node:path";function Y(e,t,n,o,i=k){throw new S(t,{exitCode:i,errorCode:e,hint:o[0],data:{actual:n}})}function ue(e){return`line ${e.line}, column ${e.column}`}function Hs(e){if(Array.isArray(e))return e.map(Hs);if(e!==null&&typeof e=="object"){let t={};for(let[n,o]of Object.entries(e).sort(([i],[r])=>i.localeCompare(r)))t[n]=Hs(o);return t}return e}function wo(e,t){return JSON.stringify(Hs(e))===JSON.stringify(Hs(t))}function Pr(e,t){return"actor_id"in t?t.actor_id:"location_id"in t?t.location_id:t.prop_id}function J_(e,t){return"actor_name"in t?t.actor_name:"location_name"in t?t.location_name:t.prop_name}function j_(e,t){return t==="actor"?e.actors:t==="location"?e.locations:e.props}function K_(e,t){"actor_id"in t.value?e.actors.push(t.value):"location_id"in t.value?e.locations.push(t.value):e.props.push(t.value)}function ju(e,t,n){return j_(e,t).find(o=>Pr(t,o)===n)}function z_(e,t){for(let n of["actor","location","prop"]){let o=ju(e,n,t);if(o!==void 0)return{kind:n,value:o}}}function H_(e){let t=[],n=[],o={actor:0,location:1,prop:2},i=-1,r,s=!1,c=new Set;for(let a of e){if(a.declarationKind!=="state"){s&&Y("AUTHORING_DECLARATION_ORDER","Asset declarations must precede standalone state declarations.",[ue(a.source)],["Move standalone states to the end of <create>."]);let p=a.declarationKind;o[p]<i&&Y("AUTHORING_DECLARATION_ORDER","Asset declaration groups are out of canonical order.",[ue(a.source),p],["Order asset declarations as actor, location, then prop."]),i=o[p];let l=structuredClone(a.value);l.states=[];let f={kind:p,value:l,source:a.source},u=`${p}:${Pr(p,l)}`;c.has(u)&&Y("AUTHORING_DECLARATION_DUPLICATE","Asset declaration is duplicated.",[ue(a.source),u],["Keep one declaration per asset."]),c.add(u),t.push(f),r=f;continue}let d=`${a.ownerKind}:${a.ownerId}`;if(r!==void 0&&r.kind===a.ownerKind&&Pr(r.kind,r.value)===a.ownerId){r.value.states.push(structuredClone(a.value));continue}s=!0,r=void 0,n.push({kind:a.ownerKind,ownerId:a.ownerId,value:structuredClone(a.value),source:a.source})}for(let a of t){let d=Pr(a.kind,a.value);(a.value.states.length===0||a.value.states[0].state_id!=="default")&&Y("AUTHORING_DEFAULT_STATE_REQUIRED","Every declared asset must be immediately followed by its states, beginning with default.",[ue(a.source),`${a.kind}:${d}`],[`Add [state|${a.kind}:${d}|default|...] directly after the asset declaration.`]),a.value.states.filter(l=>l.state_id==="default").length!==1&&Y("AUTHORING_DEFAULT_STATE_DUPLICATE","Every declared asset must contain exactly one default state.",[ue(a.source),`${a.kind}:${d}`],["Keep exactly one default state."]);let p=a.value.aliases??[];(new Set(p).size!==p.length||p.includes(J_(a.kind,a.value)))&&Y("AUTHORING_ALIAS_INVALID","Asset aliases must be unique and must differ from the canonical name.",[ue(a.source),`${a.kind}:${d}`],["Remove duplicate aliases and the canonical name from aliases."])}return{assets:t,states:n}}function F_(){return{createdAssets:[],existingAssets:[],createdStates:[],existingStates:[]}}function Ku(e,t){let n=H_(t),o=F_();for(let i of n.assets){let r=Pr(i.kind,i.value),s=`${i.kind}:${r}`,c=z_(e,r);if(c!==void 0){if(c.kind===i.kind&&wo(c.value,i.value)){o.existingAssets.push(s),o.existingStates.push(...i.value.states.map(a=>`${s}/${a.state_id}`));continue}Y("AUTHORING_ASSET_CONFLICT","Create-only asset declaration conflicts with an existing asset.",[ue(i.source),`${i.kind}:${r}`],["Use the existing identical definition or change it with an explicit mutation verb."])}K_(e,i),o.createdAssets.push(s),o.createdStates.push(...i.value.states.map(a=>`${s}/${a.state_id}`))}for(let i of n.states){let r=ju(e,i.kind,i.ownerId);r===void 0&&Y("AUTHORING_STATE_OWNER_NOT_FOUND","Standalone state owner does not exist.",[ue(i.source),`${i.kind}:${i.ownerId}`],["Declare the asset before its states or use an existing asset ID."]);let s=r.states.find(a=>a.state_id===i.value.state_id);s!==void 0&&!wo(s,i.value)&&Y("AUTHORING_STATE_CONFLICT","Create-only state declaration conflicts with an existing state on the same asset.",[ue(i.source),`${i.kind}:${i.ownerId}/${i.value.state_id}`],["Use an unused state ID for this asset, or reuse the identical existing state."]);let c=`${i.kind}:${i.ownerId}/${i.value.state_id}`;s===void 0?(r.states.push(i.value),o.createdStates.push(c)):o.existingStates.push(c)}return o}function Vu(e){return{episodes:0,scenes:e===void 0?0:1,actions:e?.actions.length??0}}function $u(e){return{episodes:e===void 0?0:1,scenes:e?.scenes.length??0,actions:e?.scenes.reduce((t,n)=>t+n.actions.length,0)??0}}function Fs(e){return e.reduce((t,n)=>({episodes:t.episodes+1,scenes:t.scenes+n.scenes.length,actions:t.actions+n.scenes.reduce((o,i)=>o+i.actions.length,0)}),{episodes:0,scenes:0,actions:0})}function Du(e){return{episodes:0,scenes:e.length,actions:e.reduce((t,n)=>t+n.actions.length,0)}}function Cr(e,t){let n=new Set(e),o=new Set(t);return{retainedIds:t.filter(i=>n.has(i)),createdIds:t.filter(i=>!n.has(i)),removedIds:e.filter(i=>!o.has(i))}}function ed(e,t){let n=[];e.location!==null&&!e.location.state_id&&n.push(`location:${e.location.location_id}`);for(let o of e.actors)o.state_id||n.push(`actor:${o.actor_id}`);for(let o of e.props)o.state_id||n.push(`prop:${o.prop_id}`);n.length>0&&Y("AUTHORING_SCENE_REF_UNMATERIALIZED","Every scene asset reference in an authored block must bind a state.",[ue(t),...n],["Add the concrete state ID to every location, cast, and prop record."])}function td(e,t){for(let n of e.scenes)ed(n,t)}function Zo(e,t){return e.episodes.findIndex(n=>n.episode_id===t)}function Qs(e,t){return e.scenes.findIndex(n=>n.scene_id===t)}function zu(e,t,n){let o=Zo(e,t);o<0&&Y("AUTHORING_EPISODE_NOT_FOUND","Episode target does not exist.",[t],["Inspect episodes and use an existing parent."]);let i=Qs(e.episodes[o],n);return i<0&&Y("AUTHORING_SCENE_NOT_FOUND","Scene target does not exist.",[`${t}/${n}`],["Inspect scenes and use an existing target."]),[o,i]}function Q_(e,t){let n=Math.max(e.length,t.length);for(let o=0;o<n;o+=1){let i=(e[o]??0)-(t[o]??0);if(i!==0)return i}return 0}function Tr(e,t){for(let n=1;n<e.length;n+=1)Q_(e[n-1].coord,e[n].coord)>=0&&Y("AUTHORING_TARGET_ORDER",t,[ue(e[n].source)],["List replace targets in current document order without duplicates."],J)}function Y_(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>{let c=Zo(e,s.value.episode_id);return c<0&&Y("AUTHORING_EPISODE_NOT_FOUND","Episode replace target does not exist.",[ue(s.source),s.value.episode_id],["Use --create for a new episode or choose an existing ID."]),{coord:[c],source:s.source}});Tr(r,"Episode replace targets are not in document order.")}for(let r of n){td(r.value,r.source);let s=Zo(e,r.value.episode_id),c=s<0?void 0:e.episodes[s];o==="create"?c!==void 0?wo(c,r.value)||Y("AUTHORING_CREATE_CONFLICT","Episode create target already exists with different content.",[ue(r.source),r.value.episode_id],["Use --replace to replace it, or make the create block identical for a no-op retry."]):t.episodes.push(structuredClone(r.value)):t.episodes[s]=structuredClone(r.value),i.push({kind:"episode",address:r.value.episode_id,before:$u(c),after:$u(r.value),...Cr(c?.scenes.map(a=>a.scene_id)??[],r.value.scenes.map(a=>a.scene_id)),untouchedSiblings:Math.max(0,e.episodes.length-(c===void 0?0:1))})}return i}function q_(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>({coord:zu(e,s.parent,s.value.scene_id),source:s.source}));Tr(r,"Scene replace targets are not in document order.")}for(let r of n){ed(r.value,r.source);let s=Zo(e,r.parent);s<0&&Y("AUTHORING_EPISODE_NOT_FOUND","Scene parent episode does not exist.",[ue(r.source),r.parent],["Use an existing episode parent."]);let c=e.episodes[s],a=t.episodes[s],d=Qs(c,r.value.scene_id),p=d<0?void 0:c.scenes[d];o==="create"?p!==void 0?wo(p,r.value)||Y("AUTHORING_CREATE_CONFLICT","Scene create target already exists with different content.",[ue(r.source),`${r.parent}/${r.value.scene_id}`],["Use --replace or make the create block identical for a no-op retry."]):a.scenes.push(structuredClone(r.value)):(d<0&&Y("AUTHORING_SCENE_NOT_FOUND","Scene replace target does not exist.",[ue(r.source),`${r.parent}/${r.value.scene_id}`],["Use --create for a new scene or choose an existing scene."]),a.scenes[d]=structuredClone(r.value)),i.push({kind:"scene",address:`${r.parent}/${r.value.scene_id}`,before:Vu(p),after:Vu(r.value),...Cr(p===void 0?[]:[p.scene_id],[r.value.scene_id]),untouchedSiblings:Math.max(0,c.scenes.length-(p===void 0?0:1))})}return i}function Z_(e,t,n){let o=n.map(r=>{let s=Zo(e,r.from),c=Zo(e,r.through);(s<0||c<0)&&Y("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Episode-span endpoint does not exist.",[ue(r.source),`${r.from}..${r.through}`],["Use existing episode IDs as span endpoints."]),s>c&&Y("AUTHORING_SPAN_REVERSED","Episode-span endpoints are reversed in current document order.",[ue(r.source),`${r.from}..${r.through}`],["Swap from and through."]),r.episodes.length===0&&Y("AUTHORING_EMPTY_SPAN","Episode-span replacement cannot be empty.",[ue(r.source)],["Include at least one complete episode."]);for(let a of r.episodes)td(a,r.source);return{target:r,from:s,through:c}});Tr(o.map(r=>({coord:[r.from],source:r.target.source})),"Episode spans are not in document order.");for(let r=1;r<o.length;r+=1)o[r].from<=o[r-1].through&&Y("AUTHORING_SPAN_OVERLAP","Episode spans overlap.",[ue(o[r].target.source)],["Use disjoint episode spans."]);let i=o.map(({target:r,from:s,through:c})=>{let a=e.episodes.slice(s,c+1);return{kind:"episode-span",address:`${r.from}..${r.through}`,before:Fs(a),after:Fs(r.episodes),...Cr(a.map(d=>d.episode_id),r.episodes.map(d=>d.episode_id)),untouchedSiblings:e.episodes.length-a.length}});for(let{target:r,from:s,through:c}of[...o].reverse())t.episodes.splice(s,c-s+1,...structuredClone(r.episodes));return i}function W_(e,t,n){let o=n.map(s=>{let c=Zo(e,s.parent);c<0&&Y("AUTHORING_EPISODE_NOT_FOUND","Scene-span parent does not exist.",[ue(s.source),s.parent],["Use an existing parent episode."]);let a=e.episodes[c],d=Qs(a,s.from),p=Qs(a,s.through);(d<0||p<0)&&Y("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Scene-span endpoint does not exist in its parent.",[ue(s.source),`${s.parent}:${s.from}..${s.through}`],["Use scene IDs from the same existing episode."]),d>p&&Y("AUTHORING_SPAN_REVERSED","Scene-span endpoints are reversed in current document order.",[ue(s.source),`${s.from}..${s.through}`],["Swap from and through."]),s.scenes.length===0&&Y("AUTHORING_EMPTY_SPAN","Scene-span replacement cannot be empty.",[ue(s.source)],["Include at least one complete scene."]);for(let l of s.scenes)ed(l,s.source);return{target:s,epIndex:c,from:d,through:p}});Tr(o.map(s=>({coord:[s.epIndex,s.from],source:s.target.source})),"Scene spans are not in document order.");for(let s=1;s<o.length;s+=1){let c=o[s-1],a=o[s];a.epIndex===c.epIndex&&a.from<=c.through&&Y("AUTHORING_SPAN_OVERLAP","Scene spans overlap.",[ue(a.target.source)],["Use disjoint scene spans."])}let i=o.map(({target:s,epIndex:c,from:a,through:d})=>{let p=e.episodes[c].scenes.slice(a,d+1);return{kind:"scene-span",address:`${s.parent}/${s.from}..${s.parent}/${s.through}`,before:Du(p),after:Du(s.scenes),...Cr(p.map(l=>l.scene_id),s.scenes.map(l=>l.scene_id)),untouchedSiblings:e.episodes[c].scenes.length-p.length}}),r=new Map;for(let s of o)r.set(s.epIndex,[...r.get(s.epIndex)??[],s]);for(let[s,c]of r)for(let{target:a,from:d,through:p}of[...c].reverse())t.episodes[s].scenes.splice(d,p-d+1,...structuredClone(a.scenes));return i}function X_(e,t,n){let o=n.map(s=>{let c=s.parent.indexOf("/");(c<1||c===s.parent.length-1)&&Y("AUTHORING_SCENE_ADDRESS_INVALID","Action-span parent is not a complete scene address.",[ue(s.source),s.parent],["Use parent=ep_ID/scn_ID."]);let a=s.parent.slice(0,c),d=s.parent.slice(c+1),[p,l]=zu(e,a,d),f=e.episodes[p].scenes[l];return s.from>s.through&&Y("AUTHORING_SPAN_REVERSED","Action-span endpoints are reversed.",[ue(s.source),`${s.from}..${s.through}`],["Swap from and through."]),s.through>=f.actions.length&&Y("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Action-span endpoint is outside the current scene body.",[ue(s.source),`${s.from}..${s.through}`,`actions=${f.actions.length}`],["Use zero-based endpoints within the current body."]),s.actions.length===0&&Y("AUTHORING_EMPTY_SPAN","Action-span replacement cannot be empty.",[ue(s.source)],["Include at least one action."]),{target:s,epIndex:p,scIndex:l,scene:f,from:s.from,through:s.through}});Tr(o.map(s=>({coord:[s.epIndex,s.scIndex,s.from],source:s.target.source})),"Action spans are not in document order.");for(let s=1;s<o.length;s+=1){let c=o[s-1],a=o[s];a.epIndex===c.epIndex&&a.scIndex===c.scIndex&&a.from<=c.through&&Y("AUTHORING_SPAN_OVERLAP","Action spans overlap.",[ue(a.target.source)],["Use disjoint action spans."])}let i=o.map(({target:s,scene:c,from:a,through:d})=>({kind:"action-span",address:`${s.parent}#${a}..${s.parent}#${d}`,before:{episodes:0,scenes:0,actions:d-a+1},after:{episodes:0,scenes:0,actions:s.actions.length},retainedIds:[],createdIds:[],removedIds:[],untouchedSiblings:c.actions.length-(d-a+1)})),r=new Map;for(let s of o){let c=`${s.epIndex}/${s.scIndex}`;r.set(c,[...r.get(c)??[],s])}for(let s of r.values())for(let{target:c,epIndex:a,scIndex:d,from:p,through:l}of[...s].reverse())t.episodes[a].scenes[d].actions.splice(p,l-p+1,...structuredClone(c.actions));return i}function Hu(e){let t=new Set,n=new Set;for(let o of e.episodes){t.has(o.episode_id)&&Y("AUTHORING_EPISODE_ID_CONFLICT","Episode ID occurs more than once.",[o.episode_id],["Use globally unique episode IDs."]),t.add(o.episode_id);for(let i of o.scenes)n.has(i.scene_id)&&Y("AUTHORING_SCENE_ID_CONFLICT","Scene ID occurs more than once.",[i.scene_id],["Use globally unique stable scene IDs."]),n.add(i.scene_id)}}function eE(e,t){let n=/^\$\.episodes\[(\d+)]/.exec(e);if(n===null)return e;let o=t.episodes[Number(n[1])];if(o===void 0)return e;let i=e.replace(n[0],`$.episodes[${o.episode_id}]`),r=/^(\$\.episodes\[\d+]\.scenes)\[(\d+)]/.exec(e);if(r!==null){let s=o.scenes[Number(r[2])];if(s!==void 0){let c=`${n[0]}.scenes[${r[2]}]`;i=e.replace(c,`$.episodes[${o.episode_id}].scenes[${s.scene_id}]`)}}return i}function Gu(e,t){return`${e.code}\0${eE(e.path,t)}\0${e.message}`}function tE(e){let t={episodeIds:new Set,sceneIds:new Set,fullEpisodeIds:new Set,fullSceneIds:new Set,actionSpans:[]},n=i=>{t.sceneIds.add(i.scene_id),t.fullSceneIds.add(i.scene_id)},o=i=>{t.episodeIds.add(i.episode_id),t.fullEpisodeIds.add(i.episode_id);for(let r of i.scenes)n(r)};for(let i of e)if(i.kind==="script")for(let r of i.episodes)o(r);else if(i.kind==="episode")o(i.value);else if(i.kind==="episode-span")for(let r of i.episodes)o(r);else if(i.kind==="scene")n(i.value);else if(i.kind==="scene-span")for(let r of i.scenes)n(r);else t.sceneIds.add(i.parent.split("/")[1]??""),t.actionSpans.push(i);return t}function nE(e,t,n){let o=[],i=new Map(e?.episodes.map(a=>[a.episode_id,a])??[]),r=new Map;for(let a of e?.episodes??[])for(let d of a.scenes)r.set(d.scene_id,d);let s=new Map(t.episodes.map(a=>[a.episode_id,a])),c=new Map;for(let a of t.episodes)for(let d of a.scenes)c.set(d.scene_id,{episodeId:a.episode_id,scene:d});for(let a of n.fullEpisodeIds){let d=s.get(a);if(d===void 0||d.scenes.length>0)continue;let p=(i.get(a)?.scenes.length??0)>0;o.push({code:p?"authoring_episode_cleared":"authoring_empty_episode",path:`$.episodes[${a}]`,message:p?`authoring replaced episode ${a} with an empty scene list`:`authored episode ${a} has no scenes`})}for(let a of n.fullSceneIds){let d=c.get(a);if(d===void 0)continue;let p=`$.episodes[${d.episodeId}].scenes[${a}]`;if(d.scene.actions.length===0){let l=(r.get(a)?.actions.length??0)>0;o.push({code:l?"authoring_scene_cleared":"authoring_empty_scene",path:p,message:l?`authoring replaced scene ${a} with an empty body`:`authored scene ${a} has an empty body`})}d.scene.actions.forEach((l,f)=>{l.content.trim()===""&&o.push({code:"authoring_empty_action_content",path:`${p}.actions[${f}]`,message:"authored action content is empty"})})}for(let a of n.actionSpans)a.actions.forEach((d,p)=>{d.content.trim()===""&&o.push({code:"authoring_empty_action_content",path:`${a.parent}#replacement[${p}]`,message:"authored action-span replacement contains an action with empty content"})});return o}function Bu(e,t,n){let o=wt(t),i=tE(n),r=()=>({...o,warnings:[...o.warnings,...nE(e,t,i)]});if(o.ok||e!==null&&wo(e,t))return r();let s=new Set(e===null?[]:wt(e).errors.map(a=>Gu(a,e))),c=o.errors.filter(a=>{if(!s.has(Gu(a,t)))return!0;let d=/^\$\.episodes\[(\d+)]/.exec(a.path);if(!d)return!1;let p=t.episodes[Number(d[1])];if(p===void 0||i.episodeIds.has(p.episode_id))return!0;let l=/^\$\.episodes\[\d+]\.scenes\[(\d+)]/.exec(a.path),f=l===null?void 0:p.scenes[Number(l[1])];return f!==void 0&&i.sceneIds.has(f.scene_id)});return c.length>0&&Y("AUTHORING_VALIDATION_FAILED","The proposed script has blocking validation errors.",c.map(a=>`${a.path}: ${a.code} ${a.message}`),["Repair the authoring source and rerun the plan."]),r()}function Ju(e){let t=new Set;for(let n of e.episodes)for(let o of n.scenes){o.location!==null&&t.add(o.location.location_id);for(let i of o.actors)t.add(i.actor_id);for(let i of o.props)t.add(i.prop_id)}return[...e.actors.map(n=>n.actor_id),...e.locations.map(n=>n.location_id),...e.props.map(n=>n.prop_id)].filter(n=>!t.has(n))}function oE(e){let t=e.targets[0];t?.kind!=="script"&&Y("AUTHORING_TARGET_MODE","Script create requires exactly one script target.",[],["Use a single <script> block."],J);for(let i of t.episodes)td(i,t.source);let n={version:3,title:t.title,worldview:t.worldview,style:t.style,actors:[],locations:[],props:[],episodes:structuredClone(t.episodes)};t.worldviewRaw!==void 0&&(n.worldview_raw=t.worldviewRaw),t.synopsis!==void 0&&(n.synopsis=t.synopsis),t.logline!==void 0&&(n.logline=t.logline),t.theme!==void 0&&(n.theme=t.theme),t.mainCharacters!==void 0&&(n.main_characters=structuredClone(t.mainCharacters)),t.extend!==void 0&&(n.extend=structuredClone(t.extend));let o=Ku(n,e.declarations);return Hu(n),{script:n,declarations:o}}function Fu(e,t,n){if(t.targetKind==="script"){n!=="create"&&Y("AUTHORING_TARGET_MODE","Script targets support create only.",[n],["Use --create."],J);let a=oE(t),d=a.script;e!==null&&!wo(e,d)&&Y("AUTHORING_CREATE_CONFLICT","The script target already exists with different content.",["script"],["Use episode replacement for an existing script, or write an identical script for a no-op retry."]);let p=e===null?a.declarations:{createdAssets:[],existingAssets:[...a.declarations.existingAssets,...a.declarations.createdAssets],createdStates:[],existingStates:[...a.declarations.existingStates,...a.declarations.createdStates]},l=Bu(e,d,t.targets);return{script:d,changed:e===null||!wo(e,d),declarations:p,targets:[{kind:"script",address:"global",before:e===null?{episodes:0,scenes:0,actions:0}:Fs(e.episodes),after:Fs(d.episodes),...Cr(e?.episodes.map(f=>f.episode_id)??[],d.episodes.map(f=>f.episode_id)),untouchedSiblings:0}],retainedOrphanAssets:Ju(d),validation:l}}e===null&&Y("AUTHORING_SCRIPT_NOT_FOUND","A local Script v3 file is required for this target kind.",["<missing>"],["Create a script first or select an existing --script-path."]),(t.targetKind==="episode-span"||t.targetKind==="scene-span"||t.targetKind==="action-span")&&n!=="replace"&&Y("AUTHORING_TARGET_MODE",`${t.targetKind} supports replace only.`,[n],["Use --replace."],J);let o=structuredClone(e),i=structuredClone(e),r=Ku(i,t.declarations),s;switch(t.targetKind){case"episode":{let a=t.targets.flatMap(d=>d.kind==="episode"?[d]:[]);a.length!==t.targets.length&&Y("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],J),s=Y_(o,i,a,n);break}case"scene":{let a=t.targets.flatMap(d=>d.kind==="scene"?[d]:[]);a.length!==t.targets.length&&Y("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],J),s=q_(o,i,a,n);break}case"episode-span":{let a=t.targets.flatMap(d=>d.kind==="episode-span"?[d]:[]);a.length!==t.targets.length&&Y("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],J),s=Z_(o,i,a);break}case"scene-span":{let a=t.targets.flatMap(d=>d.kind==="scene-span"?[d]:[]);a.length!==t.targets.length&&Y("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],J),s=W_(o,i,a);break}case"action-span":{let a=t.targets.flatMap(d=>d.kind==="action-span"?[d]:[]);a.length!==t.targets.length&&Y("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],J),s=X_(o,i,a);break}default:Y("AUTHORING_TARGET_MODE","Unsupported authoring target.",[t.targetKind],["Use a supported homogeneous target kind."])}Hu(i);let c=Bu(e,i,t.targets);return{script:i,changed:!wo(e,i),declarations:r,targets:s,retainedOrphanAssets:Ju(i),validation:c}}function D(e,t,n,o){return new S(e,{exitCode:k,errorCode:"AUTHORING_SOURCE_INVALID",hint:o,data:{actual:[`line ${t.line}, column ${t.column}: ${n}`]}})}function nd(e,t,n){let o="";for(let i=0;i<e.length;i+=1){let r=e[i];if(r!=="\\"){o+=r;continue}let s=e[i+1];if(s===void 0)throw D("Trailing escape is invalid.",{line:t.line,column:t.column+i},e,"Escape a supported character or remove the trailing backslash.");if(s==="\\"||s==="n"||n&&(s==="|"||s==="]")){o+=s==="n"?`
129
- `:s,i+=1;continue}throw D("Unknown escape sequence.",{line:t.line,column:t.column+i},`\\${s}`,n?"Use only \\|, \\], \\\\, or \\n in a header.":"Use only \\\\ or \\n in record content.")}return o}function Gi(e,t){let n={line:t,column:Math.max(1,e.indexOf("[")+1)},o=e.trimStart();if(!o.startsWith("["))throw D("Expected a bracket record.",n,e,"Start the semantic line with a known [type] record.");let i=-1,r=!1;for(let g=1;g<o.length;g+=1){let h=o[g];if(r){r=!1;continue}if(h==="\\"){r=!0;continue}if(h==="]"){i=g;break}}if(i<0)throw D("Bracket record is not closed.",n,e,"Add the closing ].");let s=o.slice(1,i),c=[],a="";r=!1;for(let g=0;g<s.length;g+=1){let h=s[g];r?(a+=`\\${h}`,r=!1):h==="\\"?r=!0:h==="|"?(c.push(a),a=""):a+=h}r&&(a+="\\"),c.push(a);let[d,...p]=c,l=nd(d??"",n,!0);if(!l)throw D("Record type is empty.",n,e,"Use a known record type.");let f=o.slice(i+1),u=f.startsWith(" ")?f.slice(1):f;return{type:l,slots:p.map(g=>nd(g,n,!0)),content:nd(u,{line:t,column:i+2},!1),source:n}}function Et(){return{extend:{},extendPresent:!1,aliases:[],aliasesPresent:!1,phase:"extend"}}function zn(e){return e.extendPresent||e.aliasesPresent||e.prompt!==void 0}function xt(e){return e.extendPresent?e.extend:void 0}function od(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(od):typeof e!="object"?!1:Object.values(e).every(od)}function id(e){if(Array.isArray(e))return e.map(id);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=id(e[n]);return t}return e}function Qu(e){return e==="featured"||e==="background"}function iE(e){return e==="\u4E3B\u89D2"||e==="\u914D\u89D2"}function rE(e){return e==="system"||e==="broadcast"||e==="offscreen"||e==="group"}function sE(e){return e==="actor"||e==="location"||e==="prop"}function Yu(e,t,n,o){if(!/^\d+$/.test(e))throw D(`${n} must be an integer.`,t,e||"<empty>",`Use ${o?"a non-negative":"a positive"} integer.`);let i=Number(e);if(!Number.isSafeInteger(i)||(o?i<0:i<1))throw D(`${n} is out of range.`,t,e,`Use ${o?"a non-negative":"a positive"} safe integer.`);return i}function aE(e,t){let n=e.trim();if(!n.startsWith("<"))return null;let o={line:t,column:e.indexOf("<")+1},i=/^<\/([a-z-]+)>$/.exec(n);if(i)return{name:i[1],closing:!0,attrs:new Map,source:o};let r=/^<([a-z-]+)(?: ([^>]+))?>$/.exec(n);if(!r)throw D("Block tag syntax is invalid.",o,e,"Use <name key=value> or </name> on its own line.");let s=new Map,c=r[2]??"";if(c)for(let a of c.split(" ")){if(!a)throw D("Block attributes must use one space separators.",o,e,"Use canonical key=value attributes separated by one space.");let d=/^([a-z]+)=([A-Za-z0-9_./#:-]+)$/.exec(a);if(!d)throw D("Block attribute syntax is invalid.",o,a,"Use unquoted canonical key=value attributes.");if(s.has(d[1]))throw D("Block attribute is duplicated.",o,d[1],"Keep exactly one value for each attribute.");s.set(d[1],d[2])}return{name:r[1],closing:!1,attrs:s,source:o}}function Sn(e,t,n=[]){let o=new Set([...t,...n]),i=[...e.attrs.keys()].filter(s=>!o.has(s)),r=t.filter(s=>!e.attrs.has(s));if(i.length>0||r.length>0)throw D(`Attributes for <${e.name}> are invalid.`,e.source,`missing=${r.join(",")||"-"} unknown=${i.join(",")||"-"}`,`Use ${[...t,...n].map(s=>`${s}=...`).join(" ")}.`)}function cE(e,t){if(!e)throw D("Speaker is required.",t,"<empty>","Use act_ID[/state_ID] or system|broadcast|offscreen|group[:label].");let n=e.indexOf("/"),o=n>=0?e.slice(0,n):e;if(/^act_[A-Za-z0-9_-]+$/.test(o)){if(n<0)return{actor_id:o};let s=e.slice(n+1);if(!s||s.includes("/"))throw D("Actor speaker state is invalid.",t,e,"Use act_ID/state_ID.");return{actor_id:o,state_id:s}}let i=e.indexOf(":"),r=i>=0?e.slice(0,i):e;if(!Ho.has(r)||!rE(r))throw D("Speaker kind is invalid.",t,e,"Use an actor ID or system, broadcast, offscreen, or group.");return i<0?{kind:r}:{kind:r,label:e.slice(i+1)}}function dE(e,t){let o={act:"action",dlg:"dialogue",think:"inner_thought",trans:"transition"}[e.type];if(o===void 0||!qt.has(o))throw D("Body record type is invalid.",e.source,e.type,"Use [act], [dlg], [think], or [trans].");let i={type:o,content:e.content};if(o==="dialogue"||o==="inner_thought"){if(e.slots.length<1||e.slots.length>2)throw D("Speaker record slots are invalid.",e.source,e.slots.join("|"),`Use [${e.type}|speaker|emotion?].`);i.speaker=cE(e.slots[0],e.source),e.slots.length===2&&(i.emotion=e.slots[1])}else{if(e.slots.length>1)throw D("Body record slots are invalid.",e.source,e.slots.join("|"),`Use [${e.type}|emotion?].`);e.slots.length===1&&(i.emotion=e.slots[0])}let r=xt(t);if(r!==void 0&&(i.extend=r),t.aliasesPresent)throw D("Alias cannot modify an action.",t.source??e.source,t.aliases.join(","),"Use [alias] only before an asset declaration.");return t.prompt!==void 0&&(i.transition_prompt=t.prompt),i}var rd=class{lines;index=0;constructor(t){this.lines=t.replace(/\r\n?/g,`
128
+ `,targetCount:i}}function pe(e,t,n,o,i=k){throw new x(t,{exitCode:i,errorCode:e,hint:o,data:{actual:n}})}function $_(e){let t=me(e),n;try{n=JSON.parse(Cu.readFileSync(t,"utf-8"))}catch(o){pe("SCRIPT_JSON_UNAVAILABLE","The local script cannot be read as JSON.",[t,o instanceof Error?o.message:String(o)],"Provide a readable local Script v3 file.")}return Js(n)}function Pr(e){return e||pe("AUTHORING_SELECTOR_REQUIRED","This export kind requires --in.",["<missing>"],"Pass one or more comma-separated point or from..through regions.",B),e.split(",").map(t=>{let n=t.trim();n||pe("AUTHORING_SELECTOR_INVALID","Selector contains an empty region.",[e],"Remove empty comma-separated regions.",B);let o=n.indexOf("..");if(o<0)return{from:n,through:n};n.indexOf("..",o+2)>=0&&pe("AUTHORING_SELECTOR_INVALID","Selector region has more than one range delimiter.",[n],"Use point or from..through.",B);let i=n.slice(0,o),r=n.slice(o+2);return(!i||!r)&&pe("AUTHORING_SELECTOR_INVALID","Selector range endpoint is empty.",[n],"Provide both endpoints.",B),{from:i,through:r}})}function Hs(e,t,n){if(t.from==="*"&&t.through==="*")return e.length===0&&pe("AUTHORING_SELECTOR_EMPTY",`The script contains no ${n}.`,["*"],"Choose a non-empty target kind."),[0,e.length-1];(e.filter(r=>r===t.from).length>1||e.filter(r=>r===t.through).length>1)&&pe("AUTHORING_SELECTOR_AMBIGUOUS",`${n} selector endpoint is not unique.`,[t.from,t.through],"Repair duplicate stable IDs before exporting this target.");let o=e.indexOf(t.from),i=e.indexOf(t.through);return(o<0||i<0)&&pe("AUTHORING_SELECTOR_NOT_FOUND",`${n} selector endpoint was not found.`,[t.from,t.through],"Use IDs from the current local script."),o>i&&pe("AUTHORING_SELECTOR_REVERSED",`${n} selector is reversed in current document order.`,[t.from,t.through],"Put the earlier document endpoint first."),[o,i]}function Vu(e,t){let n=new Set;for(let o of e){let i=t(o);n.has(i)&&pe("AUTHORING_SELECTOR_OVERLAP","Selector regions overlap or repeat a target.",[i],"Use non-overlapping regions."),n.add(i)}return e}function Cr(e,t){for(let n=1;n<e.length;n+=1){let o=e[n-1],i=e[n],r=Math.max(o.length,i.length),s=0;for(let c=0;c<r&&(s=(i[c]??0)-(o[c]??0),s===0);c+=1);s<=0&&pe("AUTHORING_SELECTOR_ORDER",`${t} selector regions are not in current document order.`,[`region=${n+1}`],"List disjoint selector regions from earlier to later document positions.")}}function D_(e,t){let n=[],o=e.episodes.map(r=>r.episode_id);for(let r of Pr(t)){let[s,c]=Hs(o,r,"episode");n.push(...e.episodes.slice(s,c+1))}Vu(n,r=>r.episode_id),Cr(n.map(r=>[o.indexOf(r.episode_id)]),"Episode");let i=n.map(r=>({kind:"episode",value:structuredClone(r),source:Zt}));return Di("episode",i)}function G_(e,t){let n=e.episodes.map(s=>s.episode_id),o=[],i=new Set,r=[];for(let s of Pr(t)){let[c,a]=Hs(n,s,"episode");for(let d=c;d<=a;d+=1)i.has(d)&&pe("AUTHORING_SELECTOR_OVERLAP","Episode span regions overlap.",[`${s.from}..${s.through}`],"Use non-overlapping regions."),i.add(d);o.push({kind:"episode-span",from:n[c],through:n[a],episodes:structuredClone(e.episodes.slice(c,a+1)),source:Zt}),r.push([c])}return Cr(r,"Episode span"),Di("episode-span",o)}function B_(e){return e.episodes.flatMap(t=>t.scenes.map(n=>({episodeId:t.episode_id,scene:n})))}function ed(e){return`${e.episodeId}/${e.scene.scene_id}`}function J_(e,t){let n=B_(e),o=n.map(ed),i=[];for(let s of Pr(t)){let[c,a]=Hs(o,s,"scene");i.push(...n.slice(c,a+1))}Vu(i,ed),Cr(i.map(s=>[o.indexOf(ed(s))]),"Scene");let r=i.map(s=>({kind:"scene",parent:s.episodeId,value:structuredClone(s.scene),source:Zt}));return Di("scene",r)}function td(e){let t=/^([^/#]+)\/([^/#]+)$/.exec(e);return t||pe("AUTHORING_SELECTOR_INVALID","Scene selector endpoint must be ep/scn.",[e],"Use ep_ID/scn_ID."),{episodeId:t[1],sceneId:t[2]}}function K_(e,t){let n=[],o=new Set,i=[];for(let r of Pr(t)){(r.from==="*"||r.through==="*")&&pe("AUTHORING_SELECTOR_INVALID","A scene span wildcard has no single parent.",["*"],"Use one explicit region per episode.");let s=td(r.from),c=td(r.through);s.episodeId!==c.episodeId&&pe("AUTHORING_SELECTOR_CROSS_PARENT","A scene span must remain inside one episode.",[r.from,r.through],"Split it into one region per episode.");let a=e.episodes.filter(u=>u.episode_id===s.episodeId);a.length===0&&pe("AUTHORING_SELECTOR_NOT_FOUND","Scene span parent episode was not found.",[s.episodeId],"Use an existing episode ID."),a.length>1&&pe("AUTHORING_SELECTOR_AMBIGUOUS","Scene span parent episode is not unique.",[s.episodeId],"Repair duplicate stable IDs before exporting.");let d=a[0],p=d.scenes.map(u=>u.scene_id),[l,f]=Hs(p,{from:s.sceneId,through:c.sceneId},"scene");for(let u=l;u<=f;u+=1){let m=`${d.episode_id}/${p[u]}`;o.has(m)&&pe("AUTHORING_SELECTOR_OVERLAP","Scene span regions overlap.",[m],"Use non-overlapping regions."),o.add(m)}n.push({kind:"scene-span",parent:d.episode_id,from:p[l],through:p[f],scenes:structuredClone(d.scenes.slice(l,f+1)),source:Zt}),i.push([e.episodes.indexOf(d),l])}return Cr(i,"Scene span"),Di("scene-span",n)}function Pu(e){let t=/^([^/#]+\/[^/#]+)#(\d+)$/.exec(e);t||pe("AUTHORING_SELECTOR_INVALID","Action selector endpoint must be ep/scn#index.",[e],"Use a zero-based ep_ID/scn_ID#index address.");let n=Number(t[2]);return Number.isSafeInteger(n)||pe("AUTHORING_SELECTOR_INVALID","Action index is outside the safe integer range.",[e],"Use a zero-based safe integer index."),{parent:t[1],index:n}}function j_(e,t){let n=[],o=new Set,i=[];for(let r of Pr(t)){(r.from==="*"||r.through==="*")&&pe("AUTHORING_SELECTOR_INVALID","An action span wildcard has no single parent.",["*"],"Use one explicit region per scene.");let s=Pu(r.from),c=Pu(r.through);s.parent!==c.parent&&pe("AUTHORING_SELECTOR_CROSS_PARENT","An action span must remain inside one scene.",[r.from,r.through],"Split it into one region per scene.");let a=td(s.parent),d=e.episodes.filter(u=>u.episode_id===a.episodeId);d.length===0&&pe("AUTHORING_SELECTOR_NOT_FOUND","Action span parent episode was not found.",[a.episodeId],"Use an existing episode ID."),d.length>1&&pe("AUTHORING_SELECTOR_AMBIGUOUS","Action span parent episode is not unique.",[a.episodeId],"Repair duplicate stable IDs before exporting.");let p=d[0],l=p.scenes.filter(u=>u.scene_id===a.sceneId);l.length===0&&pe("AUTHORING_SELECTOR_NOT_FOUND","Action span parent scene was not found.",[s.parent],"Use an existing scene address."),l.length>1&&pe("AUTHORING_SELECTOR_AMBIGUOUS","Action span parent scene is not unique.",[s.parent],"Repair duplicate stable IDs before exporting.");let f=l[0];s.index>c.index&&pe("AUTHORING_SELECTOR_REVERSED","Action span is reversed.",[r.from,r.through],"Put the lower current action index first."),c.index>=f.actions.length&&pe("AUTHORING_SELECTOR_NOT_FOUND","Action span endpoint is outside the current body.",[r.through,`actions=${f.actions.length}`],"Use current zero-based action indices.");for(let u=s.index;u<=c.index;u+=1){let m=`${s.parent}#${u}`;o.has(m)&&pe("AUTHORING_SELECTOR_OVERLAP","Action span regions overlap.",[m],"Use non-overlapping regions."),o.add(m)}n.push({kind:"action-span",parent:s.parent,from:s.index,through:c.index,actions:structuredClone(f.actions.slice(s.index,c.index+1)),source:Zt}),i.push([e.episodes.indexOf(p),p.scenes.indexOf(f),s.index])}return Cr(i,"Action span"),Di("action-span",n)}function $u(e,t){let n=O(t.output).trim();n||pe("AUTHORING_OUTPUT_REQUIRED","Export requires --output.",["<missing>"],"Pass a destination .scriptctl file.",B);let o=$_(t),i=O(t.in).trim(),r=Tu.resolve(n);if(o.version===4){let p=Uu(_n(o),e,i);return $s(r,p.content),[{text:`Exported ${p.targetCount} ${e} target(s) to ${r}`,data:{op:`export.${e}`,output:r,target_kind:e==="episodes"?"episode":e==="episode-spans"?"episode-span":e==="scenes"?"scene":e==="scene-spans"?"scene-span":e==="action-spans"?"action-span":"script",target_count:p.targetCount,bytes:Buffer.byteLength(p.content),script_version:4}},G]}let s=Tt(o),c;e==="script"?c=bu(s):e==="episodes"?c=D_(s,i):e==="episode-spans"?c=G_(s,i):e==="scenes"?c=J_(s,i):e==="scene-spans"?c=K_(s,i):c=j_(s,i);let a=vu(c);return $s(r,a),[{text:`Exported ${c.targets.length} ${e} target(s) to ${r}`,data:{op:`export.${e}`,output:r,target_kind:c.targetKind,target_count:c.targets.length,bytes:Buffer.byteLength(a),script_version:3}},G]}import*as Ed from"node:crypto";import*as Dr from"node:fs";import*as uf from"node:path";function Q(e,t,n,o,i=k){throw new x(t,{exitCode:i,errorCode:e,hint:o[0],data:{actual:n}})}function le(e){return`line ${e.line}, column ${e.column}`}function Fs(e){if(Array.isArray(e))return e.map(Fs);if(e!==null&&typeof e=="object"){let t={};for(let[n,o]of Object.entries(e).sort(([i],[r])=>i.localeCompare(r)))t[n]=Fs(o);return t}return e}function _o(e,t){return JSON.stringify(Fs(e))===JSON.stringify(Fs(t))}function Tr(e,t){return"actor_id"in t?t.actor_id:"location_id"in t?t.location_id:t.prop_id}function z_(e,t){return"actor_name"in t?t.actor_name:"location_name"in t?t.location_name:t.prop_name}function H_(e,t){return t==="actor"?e.actors:t==="location"?e.locations:e.props}function F_(e,t){"actor_id"in t.value?e.actors.push(t.value):"location_id"in t.value?e.locations.push(t.value):e.props.push(t.value)}function zu(e,t,n){return H_(e,t).find(o=>Tr(t,o)===n)}function Q_(e,t){for(let n of["actor","location","prop"]){let o=zu(e,n,t);if(o!==void 0)return{kind:n,value:o}}}function Y_(e){let t=[],n=[],o={actor:0,location:1,prop:2},i=-1,r,s=!1,c=new Set;for(let a of e){if(a.declarationKind!=="state"){s&&Q("AUTHORING_DECLARATION_ORDER","Asset declarations must precede standalone state declarations.",[le(a.source)],["Move standalone states to the end of <create>."]);let p=a.declarationKind;o[p]<i&&Q("AUTHORING_DECLARATION_ORDER","Asset declaration groups are out of canonical order.",[le(a.source),p],["Order asset declarations as actor, location, then prop."]),i=o[p];let l=structuredClone(a.value);l.states=[];let f={kind:p,value:l,source:a.source},u=`${p}:${Tr(p,l)}`;c.has(u)&&Q("AUTHORING_DECLARATION_DUPLICATE","Asset declaration is duplicated.",[le(a.source),u],["Keep one declaration per asset."]),c.add(u),t.push(f),r=f;continue}let d=`${a.ownerKind}:${a.ownerId}`;if(r!==void 0&&r.kind===a.ownerKind&&Tr(r.kind,r.value)===a.ownerId){r.value.states.push(structuredClone(a.value));continue}s=!0,r=void 0,n.push({kind:a.ownerKind,ownerId:a.ownerId,value:structuredClone(a.value),source:a.source})}for(let a of t){let d=Tr(a.kind,a.value);(a.value.states.length===0||a.value.states[0].state_id!=="default")&&Q("AUTHORING_DEFAULT_STATE_REQUIRED","Every declared asset must be immediately followed by its states, beginning with default.",[le(a.source),`${a.kind}:${d}`],[`Add [state|${a.kind}:${d}|default|...] directly after the asset declaration.`]),a.value.states.filter(l=>l.state_id==="default").length!==1&&Q("AUTHORING_DEFAULT_STATE_DUPLICATE","Every declared asset must contain exactly one default state.",[le(a.source),`${a.kind}:${d}`],["Keep exactly one default state."]);let p=a.value.aliases??[];(new Set(p).size!==p.length||p.includes(z_(a.kind,a.value)))&&Q("AUTHORING_ALIAS_INVALID","Asset aliases must be unique and must differ from the canonical name.",[le(a.source),`${a.kind}:${d}`],["Remove duplicate aliases and the canonical name from aliases."])}return{assets:t,states:n}}function q_(){return{createdAssets:[],existingAssets:[],createdStates:[],existingStates:[]}}function Hu(e,t){let n=Y_(t),o=q_();for(let i of n.assets){let r=Tr(i.kind,i.value),s=`${i.kind}:${r}`,c=Q_(e,r);if(c!==void 0){if(c.kind===i.kind&&_o(c.value,i.value)){o.existingAssets.push(s),o.existingStates.push(...i.value.states.map(a=>`${s}/${a.state_id}`));continue}Q("AUTHORING_ASSET_CONFLICT","Create-only asset declaration conflicts with an existing asset.",[le(i.source),`${i.kind}:${r}`],["Use the existing identical definition or change it with an explicit mutation verb."])}F_(e,i),o.createdAssets.push(s),o.createdStates.push(...i.value.states.map(a=>`${s}/${a.state_id}`))}for(let i of n.states){let r=zu(e,i.kind,i.ownerId);r===void 0&&Q("AUTHORING_STATE_OWNER_NOT_FOUND","Standalone state owner does not exist.",[le(i.source),`${i.kind}:${i.ownerId}`],["Declare the asset before its states or use an existing asset ID."]);let s=r.states.find(a=>a.state_id===i.value.state_id);s!==void 0&&!_o(s,i.value)&&Q("AUTHORING_STATE_CONFLICT","Create-only state declaration conflicts with an existing state on the same asset.",[le(i.source),`${i.kind}:${i.ownerId}/${i.value.state_id}`],["Use an unused state ID for this asset, or reuse the identical existing state."]);let c=`${i.kind}:${i.ownerId}/${i.value.state_id}`;s===void 0?(r.states.push(i.value),o.createdStates.push(c)):o.existingStates.push(c)}return o}function Du(e){return{episodes:0,scenes:e===void 0?0:1,actions:e?.actions.length??0}}function Gu(e){return{episodes:e===void 0?0:1,scenes:e?.scenes.length??0,actions:e?.scenes.reduce((t,n)=>t+n.actions.length,0)??0}}function Qs(e){return e.reduce((t,n)=>({episodes:t.episodes+1,scenes:t.scenes+n.scenes.length,actions:t.actions+n.scenes.reduce((o,i)=>o+i.actions.length,0)}),{episodes:0,scenes:0,actions:0})}function Bu(e){return{episodes:0,scenes:e.length,actions:e.reduce((t,n)=>t+n.actions.length,0)}}function Vr(e,t){let n=new Set(e),o=new Set(t);return{retainedIds:t.filter(i=>n.has(i)),createdIds:t.filter(i=>!n.has(i)),removedIds:e.filter(i=>!o.has(i))}}function nd(e,t){let n=[];e.location!==null&&!e.location.state_id&&n.push(`location:${e.location.location_id}`);for(let o of e.actors)o.state_id||n.push(`actor:${o.actor_id}`);for(let o of e.props)o.state_id||n.push(`prop:${o.prop_id}`);n.length>0&&Q("AUTHORING_SCENE_REF_UNMATERIALIZED","Every scene asset reference in an authored block must bind a state.",[le(t),...n],["Add the concrete state ID to every location, cast, and prop record."])}function od(e,t){for(let n of e.scenes)nd(n,t)}function Zo(e,t){return e.episodes.findIndex(n=>n.episode_id===t)}function Ys(e,t){return e.scenes.findIndex(n=>n.scene_id===t)}function Fu(e,t,n){let o=Zo(e,t);o<0&&Q("AUTHORING_EPISODE_NOT_FOUND","Episode target does not exist.",[t],["Inspect episodes and use an existing parent."]);let i=Ys(e.episodes[o],n);return i<0&&Q("AUTHORING_SCENE_NOT_FOUND","Scene target does not exist.",[`${t}/${n}`],["Inspect scenes and use an existing target."]),[o,i]}function Z_(e,t){let n=Math.max(e.length,t.length);for(let o=0;o<n;o+=1){let i=(e[o]??0)-(t[o]??0);if(i!==0)return i}return 0}function $r(e,t){for(let n=1;n<e.length;n+=1)Z_(e[n-1].coord,e[n].coord)>=0&&Q("AUTHORING_TARGET_ORDER",t,[le(e[n].source)],["List replace targets in current document order without duplicates."],B)}function W_(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>{let c=Zo(e,s.value.episode_id);return c<0&&Q("AUTHORING_EPISODE_NOT_FOUND","Episode replace target does not exist.",[le(s.source),s.value.episode_id],["Use --create for a new episode or choose an existing ID."]),{coord:[c],source:s.source}});$r(r,"Episode replace targets are not in document order.")}for(let r of n){od(r.value,r.source);let s=Zo(e,r.value.episode_id),c=s<0?void 0:e.episodes[s];o==="create"?c!==void 0?_o(c,r.value)||Q("AUTHORING_CREATE_CONFLICT","Episode create target already exists with different content.",[le(r.source),r.value.episode_id],["Use --replace to replace it, or make the create block identical for a no-op retry."]):t.episodes.push(structuredClone(r.value)):t.episodes[s]=structuredClone(r.value),i.push({kind:"episode",address:r.value.episode_id,before:Gu(c),after:Gu(r.value),...Vr(c?.scenes.map(a=>a.scene_id)??[],r.value.scenes.map(a=>a.scene_id)),untouchedSiblings:Math.max(0,e.episodes.length-(c===void 0?0:1))})}return i}function X_(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>({coord:Fu(e,s.parent,s.value.scene_id),source:s.source}));$r(r,"Scene replace targets are not in document order.")}for(let r of n){nd(r.value,r.source);let s=Zo(e,r.parent);s<0&&Q("AUTHORING_EPISODE_NOT_FOUND","Scene parent episode does not exist.",[le(r.source),r.parent],["Use an existing episode parent."]);let c=e.episodes[s],a=t.episodes[s],d=Ys(c,r.value.scene_id),p=d<0?void 0:c.scenes[d];o==="create"?p!==void 0?_o(p,r.value)||Q("AUTHORING_CREATE_CONFLICT","Scene create target already exists with different content.",[le(r.source),`${r.parent}/${r.value.scene_id}`],["Use --replace or make the create block identical for a no-op retry."]):a.scenes.push(structuredClone(r.value)):(d<0&&Q("AUTHORING_SCENE_NOT_FOUND","Scene replace target does not exist.",[le(r.source),`${r.parent}/${r.value.scene_id}`],["Use --create for a new scene or choose an existing scene."]),a.scenes[d]=structuredClone(r.value)),i.push({kind:"scene",address:`${r.parent}/${r.value.scene_id}`,before:Du(p),after:Du(r.value),...Vr(p===void 0?[]:[p.scene_id],[r.value.scene_id]),untouchedSiblings:Math.max(0,c.scenes.length-(p===void 0?0:1))})}return i}function eE(e,t,n){let o=n.map(r=>{let s=Zo(e,r.from),c=Zo(e,r.through);(s<0||c<0)&&Q("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Episode-span endpoint does not exist.",[le(r.source),`${r.from}..${r.through}`],["Use existing episode IDs as span endpoints."]),s>c&&Q("AUTHORING_SPAN_REVERSED","Episode-span endpoints are reversed in current document order.",[le(r.source),`${r.from}..${r.through}`],["Swap from and through."]),r.episodes.length===0&&Q("AUTHORING_EMPTY_SPAN","Episode-span replacement cannot be empty.",[le(r.source)],["Include at least one complete episode."]);for(let a of r.episodes)od(a,r.source);return{target:r,from:s,through:c}});$r(o.map(r=>({coord:[r.from],source:r.target.source})),"Episode spans are not in document order.");for(let r=1;r<o.length;r+=1)o[r].from<=o[r-1].through&&Q("AUTHORING_SPAN_OVERLAP","Episode spans overlap.",[le(o[r].target.source)],["Use disjoint episode spans."]);let i=o.map(({target:r,from:s,through:c})=>{let a=e.episodes.slice(s,c+1);return{kind:"episode-span",address:`${r.from}..${r.through}`,before:Qs(a),after:Qs(r.episodes),...Vr(a.map(d=>d.episode_id),r.episodes.map(d=>d.episode_id)),untouchedSiblings:e.episodes.length-a.length}});for(let{target:r,from:s,through:c}of[...o].reverse())t.episodes.splice(s,c-s+1,...structuredClone(r.episodes));return i}function tE(e,t,n){let o=n.map(s=>{let c=Zo(e,s.parent);c<0&&Q("AUTHORING_EPISODE_NOT_FOUND","Scene-span parent does not exist.",[le(s.source),s.parent],["Use an existing parent episode."]);let a=e.episodes[c],d=Ys(a,s.from),p=Ys(a,s.through);(d<0||p<0)&&Q("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Scene-span endpoint does not exist in its parent.",[le(s.source),`${s.parent}:${s.from}..${s.through}`],["Use scene IDs from the same existing episode."]),d>p&&Q("AUTHORING_SPAN_REVERSED","Scene-span endpoints are reversed in current document order.",[le(s.source),`${s.from}..${s.through}`],["Swap from and through."]),s.scenes.length===0&&Q("AUTHORING_EMPTY_SPAN","Scene-span replacement cannot be empty.",[le(s.source)],["Include at least one complete scene."]);for(let l of s.scenes)nd(l,s.source);return{target:s,epIndex:c,from:d,through:p}});$r(o.map(s=>({coord:[s.epIndex,s.from],source:s.target.source})),"Scene spans are not in document order.");for(let s=1;s<o.length;s+=1){let c=o[s-1],a=o[s];a.epIndex===c.epIndex&&a.from<=c.through&&Q("AUTHORING_SPAN_OVERLAP","Scene spans overlap.",[le(a.target.source)],["Use disjoint scene spans."])}let i=o.map(({target:s,epIndex:c,from:a,through:d})=>{let p=e.episodes[c].scenes.slice(a,d+1);return{kind:"scene-span",address:`${s.parent}/${s.from}..${s.parent}/${s.through}`,before:Bu(p),after:Bu(s.scenes),...Vr(p.map(l=>l.scene_id),s.scenes.map(l=>l.scene_id)),untouchedSiblings:e.episodes[c].scenes.length-p.length}}),r=new Map;for(let s of o)r.set(s.epIndex,[...r.get(s.epIndex)??[],s]);for(let[s,c]of r)for(let{target:a,from:d,through:p}of[...c].reverse())t.episodes[s].scenes.splice(d,p-d+1,...structuredClone(a.scenes));return i}function nE(e,t,n){let o=n.map(s=>{let c=s.parent.indexOf("/");(c<1||c===s.parent.length-1)&&Q("AUTHORING_SCENE_ADDRESS_INVALID","Action-span parent is not a complete scene address.",[le(s.source),s.parent],["Use parent=ep_ID/scn_ID."]);let a=s.parent.slice(0,c),d=s.parent.slice(c+1),[p,l]=Fu(e,a,d),f=e.episodes[p].scenes[l];return s.from>s.through&&Q("AUTHORING_SPAN_REVERSED","Action-span endpoints are reversed.",[le(s.source),`${s.from}..${s.through}`],["Swap from and through."]),s.through>=f.actions.length&&Q("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Action-span endpoint is outside the current scene body.",[le(s.source),`${s.from}..${s.through}`,`actions=${f.actions.length}`],["Use zero-based endpoints within the current body."]),s.actions.length===0&&Q("AUTHORING_EMPTY_SPAN","Action-span replacement cannot be empty.",[le(s.source)],["Include at least one action."]),{target:s,epIndex:p,scIndex:l,scene:f,from:s.from,through:s.through}});$r(o.map(s=>({coord:[s.epIndex,s.scIndex,s.from],source:s.target.source})),"Action spans are not in document order.");for(let s=1;s<o.length;s+=1){let c=o[s-1],a=o[s];a.epIndex===c.epIndex&&a.scIndex===c.scIndex&&a.from<=c.through&&Q("AUTHORING_SPAN_OVERLAP","Action spans overlap.",[le(a.target.source)],["Use disjoint action spans."])}let i=o.map(({target:s,scene:c,from:a,through:d})=>({kind:"action-span",address:`${s.parent}#${a}..${s.parent}#${d}`,before:{episodes:0,scenes:0,actions:d-a+1},after:{episodes:0,scenes:0,actions:s.actions.length},retainedIds:[],createdIds:[],removedIds:[],untouchedSiblings:c.actions.length-(d-a+1)})),r=new Map;for(let s of o){let c=`${s.epIndex}/${s.scIndex}`;r.set(c,[...r.get(c)??[],s])}for(let s of r.values())for(let{target:c,epIndex:a,scIndex:d,from:p,through:l}of[...s].reverse())t.episodes[a].scenes[d].actions.splice(p,l-p+1,...structuredClone(c.actions));return i}function Qu(e){let t=new Set,n=new Set;for(let o of e.episodes){t.has(o.episode_id)&&Q("AUTHORING_EPISODE_ID_CONFLICT","Episode ID occurs more than once.",[o.episode_id],["Use globally unique episode IDs."]),t.add(o.episode_id);for(let i of o.scenes)n.has(i.scene_id)&&Q("AUTHORING_SCENE_ID_CONFLICT","Scene ID occurs more than once.",[i.scene_id],["Use globally unique stable scene IDs."]),n.add(i.scene_id)}}function oE(e,t){let n=/^\$\.episodes\[(\d+)]/.exec(e);if(n===null)return e;let o=t.episodes[Number(n[1])];if(o===void 0)return e;let i=e.replace(n[0],`$.episodes[${o.episode_id}]`),r=/^(\$\.episodes\[\d+]\.scenes)\[(\d+)]/.exec(e);if(r!==null){let s=o.scenes[Number(r[2])];if(s!==void 0){let c=`${n[0]}.scenes[${r[2]}]`;i=e.replace(c,`$.episodes[${o.episode_id}].scenes[${s.scene_id}]`)}}return i}function Ju(e,t){return`${e.code}\0${oE(e.path,t)}\0${e.message}`}function iE(e){let t={episodeIds:new Set,sceneIds:new Set,fullEpisodeIds:new Set,fullSceneIds:new Set,actionSpans:[]},n=i=>{t.sceneIds.add(i.scene_id),t.fullSceneIds.add(i.scene_id)},o=i=>{t.episodeIds.add(i.episode_id),t.fullEpisodeIds.add(i.episode_id);for(let r of i.scenes)n(r)};for(let i of e)if(i.kind==="script")for(let r of i.episodes)o(r);else if(i.kind==="episode")o(i.value);else if(i.kind==="episode-span")for(let r of i.episodes)o(r);else if(i.kind==="scene")n(i.value);else if(i.kind==="scene-span")for(let r of i.scenes)n(r);else t.sceneIds.add(i.parent.split("/")[1]??""),t.actionSpans.push(i);return t}function rE(e,t,n){let o=[],i=new Map(e?.episodes.map(a=>[a.episode_id,a])??[]),r=new Map;for(let a of e?.episodes??[])for(let d of a.scenes)r.set(d.scene_id,d);let s=new Map(t.episodes.map(a=>[a.episode_id,a])),c=new Map;for(let a of t.episodes)for(let d of a.scenes)c.set(d.scene_id,{episodeId:a.episode_id,scene:d});for(let a of n.fullEpisodeIds){let d=s.get(a);if(d===void 0||d.scenes.length>0)continue;let p=(i.get(a)?.scenes.length??0)>0;o.push({code:p?"authoring_episode_cleared":"authoring_empty_episode",path:`$.episodes[${a}]`,message:p?`authoring replaced episode ${a} with an empty scene list`:`authored episode ${a} has no scenes`})}for(let a of n.fullSceneIds){let d=c.get(a);if(d===void 0)continue;let p=`$.episodes[${d.episodeId}].scenes[${a}]`;if(d.scene.actions.length===0){let l=(r.get(a)?.actions.length??0)>0;o.push({code:l?"authoring_scene_cleared":"authoring_empty_scene",path:p,message:l?`authoring replaced scene ${a} with an empty body`:`authored scene ${a} has an empty body`})}d.scene.actions.forEach((l,f)=>{l.content.trim()===""&&o.push({code:"authoring_empty_action_content",path:`${p}.actions[${f}]`,message:"authored action content is empty"})})}for(let a of n.actionSpans)a.actions.forEach((d,p)=>{d.content.trim()===""&&o.push({code:"authoring_empty_action_content",path:`${a.parent}#replacement[${p}]`,message:"authored action-span replacement contains an action with empty content"})});return o}function Ku(e,t,n){let o=wt(t),i=iE(n),r=()=>({...o,warnings:[...o.warnings,...rE(e,t,i)]});if(o.ok||e!==null&&_o(e,t))return r();let s=new Set(e===null?[]:wt(e).errors.map(a=>Ju(a,e))),c=o.errors.filter(a=>{if(!s.has(Ju(a,t)))return!0;let d=/^\$\.episodes\[(\d+)]/.exec(a.path);if(!d)return!1;let p=t.episodes[Number(d[1])];if(p===void 0||i.episodeIds.has(p.episode_id))return!0;let l=/^\$\.episodes\[\d+]\.scenes\[(\d+)]/.exec(a.path),f=l===null?void 0:p.scenes[Number(l[1])];return f!==void 0&&i.sceneIds.has(f.scene_id)});return c.length>0&&Q("AUTHORING_VALIDATION_FAILED","The proposed script has blocking validation errors.",c.map(a=>`${a.path}: ${a.code} ${a.message}`),["Repair the authoring source and rerun the plan."]),r()}function ju(e){let t=new Set;for(let n of e.episodes)for(let o of n.scenes){o.location!==null&&t.add(o.location.location_id);for(let i of o.actors)t.add(i.actor_id);for(let i of o.props)t.add(i.prop_id)}return[...e.actors.map(n=>n.actor_id),...e.locations.map(n=>n.location_id),...e.props.map(n=>n.prop_id)].filter(n=>!t.has(n))}function sE(e){let t=e.targets[0];t?.kind!=="script"&&Q("AUTHORING_TARGET_MODE","Script create requires exactly one script target.",[],["Use a single <script> block."],B);for(let i of t.episodes)od(i,t.source);let n={version:3,title:t.title,worldview:t.worldview,style:t.style,actors:[],locations:[],props:[],episodes:structuredClone(t.episodes)};t.worldviewRaw!==void 0&&(n.worldview_raw=t.worldviewRaw),t.synopsis!==void 0&&(n.synopsis=t.synopsis),t.logline!==void 0&&(n.logline=t.logline),t.theme!==void 0&&(n.theme=t.theme),t.mainCharacters!==void 0&&(n.main_characters=structuredClone(t.mainCharacters)),t.extend!==void 0&&(n.extend=structuredClone(t.extend));let o=Hu(n,e.declarations);return Qu(n),{script:n,declarations:o}}function Yu(e,t,n){if(t.targetKind==="script"){n!=="create"&&Q("AUTHORING_TARGET_MODE","Script targets support create only.",[n],["Use --create."],B);let a=sE(t),d=a.script;e!==null&&!_o(e,d)&&Q("AUTHORING_CREATE_CONFLICT","The script target already exists with different content.",["script"],["Use episode replacement for an existing script, or write an identical script for a no-op retry."]);let p=e===null?a.declarations:{createdAssets:[],existingAssets:[...a.declarations.existingAssets,...a.declarations.createdAssets],createdStates:[],existingStates:[...a.declarations.existingStates,...a.declarations.createdStates]},l=Ku(e,d,t.targets);return{script:d,changed:e===null||!_o(e,d),declarations:p,targets:[{kind:"script",address:"global",before:e===null?{episodes:0,scenes:0,actions:0}:Qs(e.episodes),after:Qs(d.episodes),...Vr(e?.episodes.map(f=>f.episode_id)??[],d.episodes.map(f=>f.episode_id)),untouchedSiblings:0}],retainedOrphanAssets:ju(d),validation:l}}e===null&&Q("AUTHORING_SCRIPT_NOT_FOUND","A local Script v3 file is required for this target kind.",["<missing>"],["Create a script first or select an existing --script-path."]),(t.targetKind==="episode-span"||t.targetKind==="scene-span"||t.targetKind==="action-span")&&n!=="replace"&&Q("AUTHORING_TARGET_MODE",`${t.targetKind} supports replace only.`,[n],["Use --replace."],B);let o=structuredClone(e),i=structuredClone(e),r=Hu(i,t.declarations),s;switch(t.targetKind){case"episode":{let a=t.targets.flatMap(d=>d.kind==="episode"?[d]:[]);a.length!==t.targets.length&&Q("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=W_(o,i,a,n);break}case"scene":{let a=t.targets.flatMap(d=>d.kind==="scene"?[d]:[]);a.length!==t.targets.length&&Q("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=X_(o,i,a,n);break}case"episode-span":{let a=t.targets.flatMap(d=>d.kind==="episode-span"?[d]:[]);a.length!==t.targets.length&&Q("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=eE(o,i,a);break}case"scene-span":{let a=t.targets.flatMap(d=>d.kind==="scene-span"?[d]:[]);a.length!==t.targets.length&&Q("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=tE(o,i,a);break}case"action-span":{let a=t.targets.flatMap(d=>d.kind==="action-span"?[d]:[]);a.length!==t.targets.length&&Q("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=nE(o,i,a);break}default:Q("AUTHORING_TARGET_MODE","Unsupported authoring target.",[t.targetKind],["Use a supported homogeneous target kind."])}Qu(i);let c=Ku(e,i,t.targets);return{script:i,changed:!_o(e,i),declarations:r,targets:s,retainedOrphanAssets:ju(i),validation:c}}function $(e,t,n,o){return new x(e,{exitCode:k,errorCode:"AUTHORING_SOURCE_INVALID",hint:o,data:{actual:[`line ${t.line}, column ${t.column}: ${n}`]}})}function id(e,t,n){let o="";for(let i=0;i<e.length;i+=1){let r=e[i];if(r!=="\\"){o+=r;continue}let s=e[i+1];if(s===void 0)throw $("Trailing escape is invalid.",{line:t.line,column:t.column+i},e,"Escape a supported character or remove the trailing backslash.");if(s==="\\"||s==="n"||n&&(s==="|"||s==="]")){o+=s==="n"?`
129
+ `:s,i+=1;continue}throw $("Unknown escape sequence.",{line:t.line,column:t.column+i},`\\${s}`,n?"Use only \\|, \\], \\\\, or \\n in a header.":"Use only \\\\ or \\n in record content.")}return o}function Bi(e,t){let n={line:t,column:Math.max(1,e.indexOf("[")+1)},o=e.trimStart();if(!o.startsWith("["))throw $("Expected a bracket record.",n,e,"Start the semantic line with a known [type] record.");let i=-1,r=!1;for(let m=1;m<o.length;m+=1){let h=o[m];if(r){r=!1;continue}if(h==="\\"){r=!0;continue}if(h==="]"){i=m;break}}if(i<0)throw $("Bracket record is not closed.",n,e,"Add the closing ].");let s=o.slice(1,i),c=[],a="";r=!1;for(let m=0;m<s.length;m+=1){let h=s[m];r?(a+=`\\${h}`,r=!1):h==="\\"?r=!0:h==="|"?(c.push(a),a=""):a+=h}r&&(a+="\\"),c.push(a);let[d,...p]=c,l=id(d??"",n,!0);if(!l)throw $("Record type is empty.",n,e,"Use a known record type.");let f=o.slice(i+1),u=f.startsWith(" ")?f.slice(1):f;return{type:l,slots:p.map(m=>id(m,n,!0)),content:id(u,{line:t,column:i+2},!1),source:n}}function Et(){return{extend:{},extendPresent:!1,aliases:[],aliasesPresent:!1,phase:"extend"}}function zn(e){return e.extendPresent||e.aliasesPresent||e.prompt!==void 0}function xt(e){return e.extendPresent?e.extend:void 0}function rd(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(rd):typeof e!="object"?!1:Object.values(e).every(rd)}function sd(e){if(Array.isArray(e))return e.map(sd);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=sd(e[n]);return t}return e}function qu(e){return e==="featured"||e==="background"}function aE(e){return e==="\u4E3B\u89D2"||e==="\u914D\u89D2"}function cE(e){return e==="system"||e==="broadcast"||e==="offscreen"||e==="group"}function dE(e){return e==="actor"||e==="location"||e==="prop"}function Zu(e,t,n,o){if(!/^\d+$/.test(e))throw $(`${n} must be an integer.`,t,e||"<empty>",`Use ${o?"a non-negative":"a positive"} integer.`);let i=Number(e);if(!Number.isSafeInteger(i)||(o?i<0:i<1))throw $(`${n} is out of range.`,t,e,`Use ${o?"a non-negative":"a positive"} safe integer.`);return i}function pE(e,t){let n=e.trim();if(!n.startsWith("<"))return null;let o={line:t,column:e.indexOf("<")+1},i=/^<\/([a-z-]+)>$/.exec(n);if(i)return{name:i[1],closing:!0,attrs:new Map,source:o};let r=/^<([a-z-]+)(?: ([^>]+))?>$/.exec(n);if(!r)throw $("Block tag syntax is invalid.",o,e,"Use <name key=value> or </name> on its own line.");let s=new Map,c=r[2]??"";if(c)for(let a of c.split(" ")){if(!a)throw $("Block attributes must use one space separators.",o,e,"Use canonical key=value attributes separated by one space.");let d=/^([a-z]+)=([A-Za-z0-9_./#:-]+)$/.exec(a);if(!d)throw $("Block attribute syntax is invalid.",o,a,"Use unquoted canonical key=value attributes.");if(s.has(d[1]))throw $("Block attribute is duplicated.",o,d[1],"Keep exactly one value for each attribute.");s.set(d[1],d[2])}return{name:r[1],closing:!1,attrs:s,source:o}}function Sn(e,t,n=[]){let o=new Set([...t,...n]),i=[...e.attrs.keys()].filter(s=>!o.has(s)),r=t.filter(s=>!e.attrs.has(s));if(i.length>0||r.length>0)throw $(`Attributes for <${e.name}> are invalid.`,e.source,`missing=${r.join(",")||"-"} unknown=${i.join(",")||"-"}`,`Use ${[...t,...n].map(s=>`${s}=...`).join(" ")}.`)}function lE(e,t){if(!e)throw $("Speaker is required.",t,"<empty>","Use act_ID[/state_ID] or system|broadcast|offscreen|group[:label].");let n=e.indexOf("/"),o=n>=0?e.slice(0,n):e;if(/^act_[A-Za-z0-9_-]+$/.test(o)){if(n<0)return{actor_id:o};let s=e.slice(n+1);if(!s||s.includes("/"))throw $("Actor speaker state is invalid.",t,e,"Use act_ID/state_ID.");return{actor_id:o,state_id:s}}let i=e.indexOf(":"),r=i>=0?e.slice(0,i):e;if(!Ho.has(r)||!cE(r))throw $("Speaker kind is invalid.",t,e,"Use an actor ID or system, broadcast, offscreen, or group.");return i<0?{kind:r}:{kind:r,label:e.slice(i+1)}}function uE(e,t){let o={act:"action",dlg:"dialogue",think:"inner_thought",trans:"transition"}[e.type];if(o===void 0||!qt.has(o))throw $("Body record type is invalid.",e.source,e.type,"Use [act], [dlg], [think], or [trans].");let i={type:o,content:e.content};if(o==="dialogue"||o==="inner_thought"){if(e.slots.length<1||e.slots.length>2)throw $("Speaker record slots are invalid.",e.source,e.slots.join("|"),`Use [${e.type}|speaker|emotion?].`);i.speaker=lE(e.slots[0],e.source),e.slots.length===2&&(i.emotion=e.slots[1])}else{if(e.slots.length>1)throw $("Body record slots are invalid.",e.source,e.slots.join("|"),`Use [${e.type}|emotion?].`);e.slots.length===1&&(i.emotion=e.slots[0])}let r=xt(t);if(r!==void 0&&(i.extend=r),t.aliasesPresent)throw $("Alias cannot modify an action.",t.source??e.source,t.aliases.join(","),"Use [alias] only before an asset declaration.");return t.prompt!==void 0&&(i.transition_prompt=t.prompt),i}var ad=class{lines;index=0;constructor(t){this.lines=t.replace(/\r\n?/g,`
130
130
  `).split(`
131
- `)}parse(){this.skipBlank();let t=this.takeOpen("authoring");if(Sn(t,["version"]),t.attrs.get("version")!=="1")throw D("Authoring version is unsupported.",t.source,t.attrs.get("version")??"<missing>","Use <authoring version=1>.");let n=[],o=[],i=!1,r=Et();for(;;){if(this.skipBlank(),this.peekClose("authoring")){zn(r)&&this.throwDangling(r),this.takeClose("authoring");break}let a=this.peekSemantic();if(a===null)throw this.eofError("authoring");if(a.record?.type==="extensions"||a.record?.type==="extend"){r=this.addModifier(r,this.takeRecord());continue}if(a.tag?.name==="create"&&!a.tag.closing){if(i)throw D("<create> must precede every target.",a.tag.source,"<create>","Move the single <create> block before the targets.");zn(r)&&this.throwUnsupportedModifiers(r,"create"),n.push(...this.parseCreate()),i=!0;continue}i=!0,o.push(this.parseTarget(r)),r=Et()}if(this.skipBlank(),this.index<this.lines.length){let a={line:this.index+1,column:1};throw D("Content exists after </authoring>.",a,this.lines[this.index],"Remove content outside the root block.")}if(o.length===0)throw D("Authoring file has no target.",t.source,"<authoring>","Add one or more homogeneous target blocks.");let s=o[0].kind,c=o.find(a=>a.kind!==s);if(c!==void 0)throw D("Authoring targets are not homogeneous.",c.source,c.kind,`Keep only ${s} targets in this file.`);if(s==="script"&&o.length!==1)throw D("A script authoring file has exactly one target.",o[1].source,"second <script>","Keep one <script> target.");return{version:1,declarations:n,targets:o,targetKind:s}}parseCreate(){let t=this.takeOpen("create");Sn(t,[]);let n=[],o=Et();for(;;){if(this.skipBlank(),this.peekClose("create"))return zn(o)&&this.throwDangling(o),this.takeClose("create"),n;let i=this.takeRecord();if(i.type==="extensions"||i.type==="extend"||i.type==="aliases"||i.type==="alias"||i.type==="prompt"){o=this.addModifier(o,i);continue}if(i.type==="actor"){if(i.slots.length<3||i.slots.length>4)throw D("Actor declaration slots are invalid.",i.source,i.slots.join("|"),"Use [actor|id|name|importance|role?] description.");let[r,s,c,a]=i.slots;if(!r||!s||!c||!Pt.has(c)||!Qu(c))throw D("Actor declaration is invalid.",i.source,i.slots.join("|"),"Provide id, name, and featured|background importance.");if(a!==void 0&&(!po.has(a)||!iE(a)))throw D("Actor role is invalid.",i.source,a,"Use \u4E3B\u89D2 or \u914D\u89D2, or omit the slot.");let d={actor_id:r,actor_name:s,importance:c,description:i.content,states:[]};a!==void 0&&(d.role_type=a),o.aliasesPresent&&(d.aliases=[...o.aliases]);let p=xt(o);p!==void 0&&(d.extend=p),o.prompt!==void 0&&this.throwUnsupportedModifiers(o,"actor"),n.push({declarationKind:"actor",value:d,source:i.source}),o=Et();continue}if(i.type==="location"||i.type==="prop"){if(i.slots.length!==3)throw D(`${i.type} declaration slots are invalid.`,i.source,i.slots.join("|"),`Use [${i.type}|id|name|importance] description.`);let[r,s,c]=i.slots;if(!r||!s||!c||!Pt.has(c)||!Qu(c))throw D(`${i.type} declaration is invalid.`,i.source,i.slots.join("|"),"Provide id, name, and featured|background importance.");o.prompt!==void 0&&this.throwUnsupportedModifiers(o,i.type);let a=xt(o);if(i.type==="location"){let d={location_id:r,location_name:s,importance:c,description:i.content,states:[]};o.aliasesPresent&&(d.aliases=[...o.aliases]),a!==void 0&&(d.extend=a),n.push({declarationKind:"location",value:d,source:i.source})}else{let d={prop_id:r,prop_name:s,importance:c,description:i.content,states:[]};o.aliasesPresent&&(d.aliases=[...o.aliases]),a!==void 0&&(d.extend=a),n.push({declarationKind:"prop",value:d,source:i.source})}o=Et();continue}if(i.type==="state"){if(i.slots.length!==3)throw D("State declaration slots are invalid.",i.source,i.slots.join("|"),"Use [state|kind:asset_id|state_id|state_name] description.");(o.aliasesPresent||o.prompt!==void 0)&&this.throwUnsupportedModifiers(o,"state");let[r,s,c]=i.slots,a=/^(actor|location|prop):(.+)$/.exec(r??""),d=a?.[1]??"";if(!a||!sE(d)||!s||!c)throw D("State declaration is invalid.",i.source,i.slots.join("|"),"Use a typed owner and non-empty state ID/name.");let p={state_id:s,state_name:c,description:i.content},l=xt(o);l!==void 0&&(p.extend=l),n.push({declarationKind:"state",ownerKind:d,ownerId:a[2],value:p,source:i.source}),o=Et();continue}throw D("Record is not allowed in <create>.",i.source,i.type,"Use actor, location, prop, state, or a supported prefix modifier.")}}parseTarget(t){let n=this.peekTag();if(n===null||n.closing){let o=n?.source??{line:this.index+1,column:1};throw D("Expected a target block.",o,this.lines[this.index]??"<eof>","Add a supported target block.")}switch((t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,n.name),n.name){case"script":return this.parseScript(t);case"episode":return{kind:"episode",value:this.parseEpisode(t),source:n.source,...xt(t)?{extend:xt(t)}:{}};case"episode-span":return this.parseEpisodeSpan(t);case"scene":return Sn(n,["id","parent"]),{kind:"scene",parent:n.attrs.get("parent"),value:this.parseScene(t,!0),source:n.source,...xt(t)?{extend:xt(t)}:{}};case"scene-span":return this.parseSceneSpan(t);case"action-span":return this.parseActionSpan(t);default:throw D("Unknown target block.",n.source,n.name,"Use script, episode, episode-span, scene, scene-span, or action-span.")}}parseScript(t){let n=this.takeOpen("script");Sn(n,[]);let o=["title","worldview","worldview-raw","style","synopsis","logline","theme","main-characters","main-character"],i=new Map,r=[],s=[],c=-1,a=!1,d=Et();for(;;){if(this.skipBlank(),this.peekClose("script")){zn(d)&&this.throwDangling(d),this.takeClose("script");break}let g=this.peekSemantic();if(g?.record!==void 0){let h=this.takeRecord();if(h.type==="extensions"||h.type==="extend"||h.type==="aliases"||h.type==="alias"||h.type==="prompt"){d=this.addModifier(d,h);continue}zn(d)&&this.throwUnsupportedModifiers(d,h.type);let m=o.indexOf(h.type),w=h.type==="main-character";if(a||m<0||m<c||!w&&i.has(h.type))throw D("Metadata record in <script> is invalid or out of order.",h.source,h.type,`Use ${o.join(", ")} in canonical order before episode blocks.`);if(c=m,h.type==="main-characters"){if(h.slots.length!==0||h.content!=="")throw D("Main characters marker is invalid.",h.source,h.content,"Use [main-characters] with no slots or content.");i.set(h.type,"")}else if(w){if(h.slots.length!==2||!h.slots[0]||!h.slots[1]||h.content!=="")throw D("Main character record is invalid.",h.source,h.slots.join("|"),"Use [main-character|name|role] with no content.");r.push({name:h.slots[0],role:h.slots[1]})}else{if(h.slots.length!==0)throw D("Script metadata record has unexpected slots.",h.source,h.slots.join("|"),`Use [${h.type}] content.`);i.set(h.type,h.content)}continue}if(g?.tag===void 0||g.tag.closing||g.tag.name!=="episode"){let h=g?.tag?.source??{line:this.index+1,column:1};throw D("Unexpected member in <script>.",h,this.lines[this.index]??"<eof>","Use metadata records followed by <episode> blocks.")}a=!0,s.push(this.parseEpisode(d)),d=Et()}let p=this.requiredMetadata(i,"title",n.source),l=this.requiredMetadata(i,"worldview",n.source),f=this.requiredMetadata(i,"style",n.source),u=xt(t);return{kind:"script",title:p,worldview:l,style:f,...i.get("worldview-raw")!==void 0?{worldviewRaw:i.get("worldview-raw")}:{},...i.get("synopsis")!==void 0?{synopsis:i.get("synopsis")}:{},...i.get("logline")!==void 0?{logline:i.get("logline")}:{},...i.get("theme")!==void 0?{theme:i.get("theme")}:{},...i.has("main-characters")||r.length>0?{mainCharacters:r}:{},episodes:s,source:n.source,...u!==void 0?{extend:u}:{}}}parseEpisode(t){let n=this.takeOpen("episode");Sn(n,["id"]),(t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,"episode");let o=this.parseMetadataAndChildren("episode",["title","synopsis"],"scene",s=>this.parseScene(s,!1)),i={episode_id:n.attrs.get("id"),scenes:o.children};o.values.has("title")&&(i.title=o.values.get("title")),o.values.has("synopsis")&&(i.synopsis=o.values.get("synopsis"));let r=xt(t);return r!==void 0&&(i.extend=r),i}parseScene(t,n){let o=this.takeOpen("scene");Sn(o,n?["id","parent"]:["id"]),(t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,"scene");let i,r,s=[],c=[],a="environment",d;for(;;){if(this.skipBlank(),this.peekClose("scene")){this.takeClose("scene");break}let f=this.peekSemantic();if(f?.tag?.name==="body"&&!f.tag.closing){if(a==="body")throw D("Scene has more than one body.",f.tag.source,"<body>","Keep exactly one <body>.");a="body",d=this.parseBody();continue}if(f?.record===void 0){let g=f?.tag?.source??{line:this.index+1,column:1};throw D("Only scene records and <body> are allowed here.",g,this.lines[this.index]??"<eof>","Use environment, location, cast, prop, then body.")}let u=this.takeRecord();if(u.type==="extensions"||u.type==="extend"||u.type==="aliases"||u.type==="alias"||u.type==="prompt")throw D("Scene prefix modifier must directly precede <scene>.",u.source,u.type,"Move the modifier before the <scene> opening tag.");if(u.type==="environment"){if(a!=="environment"||i!==void 0||u.slots.length>2)throw D("Environment record is out of order or invalid.",u.source,u.slots.join("|"),"Place at most one [environment|space?|time?] first.");i={},u.slots.length>=1&&u.slots[0]!==""&&(i.space=u.slots[0]),u.slots.length>=2&&u.slots[1]!==""&&(i.time=u.slots[1]);continue}if(u.type==="location"){if(a==="cast"||a==="prop"||a==="body"||r!==void 0||u.slots.length>2)throw D("Location record is out of order or invalid.",u.source,u.slots.join("|"),"Place exactly one [location|id?|state?] before cast.");a="location";let g=u.slots[0];g===void 0||g===""?r=null:r=u.slots.length===2?{location_id:g,state_id:u.slots[1]}:{location_id:g};continue}if(u.type==="cast"){if(r===void 0||a==="prop"||a==="body"||u.slots.length<1||u.slots.length>2||!u.slots[0])throw D("Cast record is out of order or invalid.",u.source,u.slots.join("|"),"Place [cast|actor_id|state_id?] after location and before props.");a="cast",s.push(u.slots.length===2?{actor_id:u.slots[0],state_id:u.slots[1]}:{actor_id:u.slots[0]});continue}if(u.type==="prop"){if(r===void 0||a==="body"||u.slots.length<1||u.slots.length>2||!u.slots[0])throw D("Prop record is out of order or invalid.",u.source,u.slots.join("|"),"Place [prop|prop_id|state_id?] after cast and before body.");a="prop",c.push(u.slots.length===2?{prop_id:u.slots[0],state_id:u.slots[1]}:{prop_id:u.slots[0]});continue}throw D("Record is not allowed in a scene header.",u.source,u.type,"Use environment, location, cast, prop, or body records.")}if(r===void 0)throw D("Scene location record is missing.",o.source,`<scene id=${o.attrs.get("id")}>`,"Add [location] or [location|loc_ID|state_ID].");if(d===void 0)throw D("Scene body is missing.",o.source,`<scene id=${o.attrs.get("id")}>`,"Add one <body> block.");let p={scene_id:o.attrs.get("id"),location:r,actors:s,props:c,actions:d};i!==void 0&&(p.environment=i);let l=xt(t);return l!==void 0&&(p.extend=l),p}parseBody(){let t=this.takeOpen("body");Sn(t,[]);let n=[],o=Et();for(;;){if(this.skipBlank(),this.peekClose("body"))return zn(o)&&this.throwDangling(o),this.takeClose("body"),n;let i=this.takeRecord();if(i.type==="extensions"||i.type==="extend"||i.type==="aliases"||i.type==="prompt"||i.type==="alias"){o=this.addModifier(o,i);continue}n.push(dE(i,o)),o=Et()}}parseEpisodeSpan(t){let n=this.takeOpen("episode-span");Sn(n,["from","through"]);let o=this.parseOnlyChildren("episode-span","episode",r=>this.parseEpisode(r)),i=xt(t);return{kind:"episode-span",from:n.attrs.get("from"),through:n.attrs.get("through"),episodes:o,source:n.source,...i!==void 0?{extend:i}:{}}}parseSceneSpan(t){let n=this.takeOpen("scene-span");Sn(n,["parent","from","through"]);let o=this.parseOnlyChildren("scene-span","scene",r=>this.parseScene(r,!1)),i=xt(t);return{kind:"scene-span",parent:n.attrs.get("parent"),from:n.attrs.get("from"),through:n.attrs.get("through"),scenes:o,source:n.source,...i!==void 0?{extend:i}:{}}}parseActionSpan(t){let n=this.takeOpen("action-span");Sn(n,["parent","from","through"]),this.skipBlank();let o=this.parseBody();this.skipBlank(),this.takeClose("action-span");let i=xt(t);return{kind:"action-span",parent:n.attrs.get("parent"),from:Yu(n.attrs.get("from"),n.source,"action-span from",!0),through:Yu(n.attrs.get("through"),n.source,"action-span through",!0),actions:o,source:n.source,...i!==void 0?{extend:i}:{}}}parseMetadataAndChildren(t,n,o,i){let r=new Map,s=[],c=-1,a=!1,d=Et();for(;;){if(this.skipBlank(),this.peekClose(t))return zn(d)&&this.throwDangling(d),this.takeClose(t),{values:r,children:s};let p=this.peekSemantic();if(p?.record!==void 0){let f=this.takeRecord();if(f.type==="extensions"||f.type==="extend"||f.type==="aliases"||f.type==="alias"||f.type==="prompt"){d=this.addModifier(d,f);continue}zn(d)&&this.throwUnsupportedModifiers(d,f.type);let u=n.indexOf(f.type);if(a||u<0||u<c||r.has(f.type)||f.slots.length!==0)throw D(`Metadata record in <${t}> is invalid or out of order.`,f.source,f.type,`Use each of ${n.join(", ")} at most once in canonical order before child blocks.`);c=u,r.set(f.type,f.content);continue}let l=p?.tag;if(l===void 0||l.closing||l.name!==o){let f=l?.source??{line:this.index+1,column:1};throw D(`Unexpected member in <${t}>.`,f,this.lines[this.index]??"<eof>",`Use metadata records followed by <${o}> blocks.`)}a=!0,s.push(i(d)),d=Et()}}parseOnlyChildren(t,n,o){let i=[],r=Et();for(;;){if(this.skipBlank(),this.peekClose(t))return zn(r)&&this.throwDangling(r),this.takeClose(t),i;let s=this.peekSemantic();if(s?.record?.type==="extensions"||s?.record?.type==="extend"){r=this.addModifier(r,this.takeRecord());continue}if(s?.tag===void 0||s.tag.closing||s.tag.name!==n){let c=s?.tag?.source??s?.record?.source??{line:this.index+1,column:1};throw D(`Only <${n}> children are allowed in <${t}>.`,c,this.lines[this.index]??"<eof>",`Add complete <${n}> blocks.`)}i.push(o(r)),r=Et()}}addModifier(t,n){let o={extend:{...t.extend},extendPresent:t.extendPresent,aliases:[...t.aliases],aliasesPresent:t.aliasesPresent,phase:t.phase,...t.prompt!==void 0?{prompt:t.prompt}:{},source:t.source??n.source};if(n.type==="extensions"){if(o.phase!=="extend"||o.extendPresent||n.slots.length!==0||n.content!=="")throw D("Extensions marker is invalid or out of order.",n.source,n.content||"<empty>","Use one [extensions] marker before extension records.");return o.extendPresent=!0,o}if(n.type==="extend"){if(o.phase!=="extend"||n.slots.length!==1||!n.slots[0])throw D("Extend modifier is invalid or out of order.",n.source,n.slots.join("|"),"Place unique [extend|key] records first.");let i=n.slots[0];if(Object.hasOwn(o.extend,i))throw D("Extend key is duplicated.",n.source,i,"Keep one value for each extension key.");let r;try{r=JSON.parse(n.content)}catch{throw D("Extension value is not valid JSON.",n.source,n.content,"Use one canonical JSON value.")}if(!od(r))throw D("Extension value is not JSON-compatible.",n.source,n.content,"Use string, number, boolean, null, array, or object.");return o.extendPresent=!0,o.extend[i]=id(r),o}if(n.type==="aliases"){if(o.phase!=="extend"||o.aliasesPresent||n.slots.length!==0||n.content!=="")throw D("Aliases marker is invalid or out of order.",n.source,n.content||"<empty>","Use one [aliases] marker after extensions and before alias records.");return o.phase="alias",o.aliasesPresent=!0,o}if(n.type==="alias"){if(o.phase==="prompt"||n.slots.length!==0||!n.content)throw D("Alias modifier is invalid or out of order.",n.source,n.content||"<empty>","Place non-empty [alias] records after extensions and before prompt.");if(o.phase="alias",o.aliasesPresent=!0,o.aliases.includes(n.content))throw D("Alias is duplicated.",n.source,n.content,"Keep each alias once.");return o.aliases.push(n.content),o}if(n.type==="prompt"){if(o.prompt!==void 0||n.slots.length!==3||n.slots.some(i=>!i))throw D("Prompt modifier is invalid.",n.source,n.slots.join("|"),"Use one [prompt|target|process|contrast] after extensions and aliases.");if(!/^(?:actor:act_|location:loc_|prop:prp_)[A-Za-z0-9_-]+$/.test(n.slots[0]))throw D("Prompt target is invalid.",n.source,n.slots[0],"Use actor:act_ID, location:loc_ID, or prop:prp_ID.");return o.phase="prompt",o.prompt={target:n.slots[0],process:n.slots[1],contrast:n.slots[2]},o}throw D("Unknown prefix modifier.",n.source,n.type,"Use extend, alias, or prompt.")}requiredMetadata(t,n,o){let i=t.get(n);if(i===void 0)throw D(`Script ${n} record is missing.`,o,"<script>",`Add [${n}] in canonical metadata order.`);return i}peekSemantic(){if(this.skipBlank(),this.index>=this.lines.length)return null;let t=this.lines[this.index],n=aE(t,this.index+1);if(n!==null)return{tag:n};if(t.trimStart().startsWith("["))return{record:Gi(t,this.index+1)};let o={line:this.index+1,column:Math.max(1,t.search(/\S/)+1)};throw D("Semantic line is neither a tag nor a bracket record.",o,t,"Use only known tags, bracket records, or blank lines.")}peekTag(){return this.peekSemantic()?.tag??null}takeRecord(){let t=this.peekSemantic();if(t?.record===void 0){let n=t?.tag?.source??{line:this.index+1,column:1};throw D("Expected a bracket record.",n,this.lines[this.index]??"<eof>","Use the record required at this position.")}return this.index+=1,t.record}takeOpen(t){let n=this.peekTag();if(n===null||n.closing||n.name!==t){let o=n?.source??{line:this.index+1,column:1};throw D(`Expected <${t}>.`,o,this.lines[this.index]??"<eof>",`Open <${t}> here.`)}return this.index+=1,n}takeClose(t){let n=this.peekTag();if(n===null||!n.closing||n.name!==t){let o=n?.source??{line:this.index+1,column:1};throw D(`Expected </${t}>.`,o,this.lines[this.index]??"<eof>",`Close the current <${t}> block.`)}return this.index+=1,n}peekClose(t){let n=this.peekTag();return n!==null&&n.closing&&n.name===t}skipBlank(){for(;this.index<this.lines.length&&this.lines[this.index].trim()==="";)this.index+=1}eofError(t){return D(`Unexpected end of file inside <${t}>.`,{line:this.lines.length,column:1},"<eof>",`Add </${t}>.`)}throwDangling(t){throw D("Prefix modifier has no following node.",t.source??{line:this.index+1,column:1},"dangling modifier","Move it directly before a supported node.")}throwUnsupportedModifiers(t,n){throw D("Prefix modifier does not apply to this node.",t.source??{line:this.index+1,column:1},n,"Remove the unsupported modifier or move it before a supported node.")}};function qu(e){return new rd(e).parse()}function L(e,t,n){throw new S(e,{exitCode:k,errorCode:"AUTHORING_SOURCE_INVALID",data:{actual:[`line ${t}: ${n}`]}})}function dd(e,t){let n=e.trim(),o=/^<\/([a-z-]+)>$/.exec(n);if(o)return{name:o[1],closing:!0,attrs:new Map,line:t};let i=/^<([a-z-]+)(?: ([^>]+))?>$/.exec(n);if(!i)return null;let r=new Map,s=i[2]??"",c=s===""?[]:s.split(" ");c.some(a=>a==="")&&L("Tag attributes need one-space separators.",t,n);for(let a of c){let d=/^([a-z]+)=([A-Za-z0-9_./#:-]+)$/.exec(a);(!d||r.has(d[1]))&&L("Tag attributes are invalid.",t,a),r.set(d[1],d[2])}return{name:i[1],closing:!1,attrs:r,line:t}}function De(e,t,n=[]){let o=new Set([...t,...n]),i=[...e.attrs.keys()].filter(s=>!o.has(s)),r=t.filter(s=>!e.attrs.has(s));(i.length>0||r.length>0)&&L("Tag attributes do not match the canonical grammar.",e.line,[...r.map(s=>`missing:${s}`),...i.map(s=>`unknown:${s}`)].join(","))}var pd=class{lines;index=0;constructor(t){this.lines=t.split(/\r?\n/).map((n,o)=>({raw:n.replace(/^\s+/,""),line:o+1})).filter(n=>n.raw.trim()!=="")}peek(){let t=this.lines[this.index];return t||L("Unexpected end of authoring file.",this.lines.at(-1)?.line??1,"<eof>"),t}take(){let t=this.peek();return this.index++,t}tag(t,n){let o=this.take(),i=dd(o.raw,o.line);return(!i||i.name!==t||i.closing!==n)&&L(`Expected ${n?"</":"<"}${t}>.`,o.line,o.raw),i}record(){let t=this.take();return Gi(t.raw,t.line)}nextTag(){let t=this.peek();return dd(t.raw,t.line)}nextRecord(){let t=this.peek();return t.raw.startsWith("[")?Gi(t.raw,t.line):null}};function ld(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(ld):typeof e=="object"&&Object.values(e).every(ld)}function Wo(e){let t={},n=e.nextRecord();if(n?.type==="extensions"){e.record();let o={},i=null;for(;(n=e.nextRecord())?.type==="extend";){let r=e.record();(r.slots.length!==1||Object.hasOwn(o,r.slots[0]))&&L("extend record is invalid or duplicated.",r.source.line,r.type);let s=r.slots[0];i!==null&&i>=s&&L("extend keys must use ascending canonical order.",r.source.line,s);let c;try{c=JSON.parse(r.content)}catch{L("extend content must be JSON.",r.source.line,r.content)}ld(c)||L("extend value must be JSON-compatible.",r.source.line,r.content),o[s]=c,i=s}t.extend=o}if(n=e.nextRecord(),n?.type==="aliases"){e.record();let o=[];for(;(n=e.nextRecord())?.type==="alias";){let i=e.record();i.slots.length!==0&&L("alias takes no slots.",i.source.line,i.type),i.content===""&&L("alias must not be empty.",i.source.line,i.type),o.includes(i.content)&&L("alias must not be duplicated.",i.source.line,i.content),o.push(i.content)}t.aliases=o}if(n=e.nextRecord(),n?.type==="prompt"){let o=e.record();(o.slots.length!==3||o.slots.some(r=>r===""))&&L("prompt requires non-empty target, process, and contrast.",o.source.line,o.type);let i=o.slots[0];!$("actor",i)&&!$("location",i)&&!$("prop",i)&&L("prompt target must be an asset ID.",o.source.line,i),t.prompt={target:i,process:o.slots[1],contrast:o.slots[2]}}return t}function sd(e,t){return e!=="featured"&&e!=="background"&&L("Importance is invalid.",t,e),e}function pE(e,t){if(e!==void 0)return e!=="\u4E3B\u89D2"&&e!=="\u914D\u89D2"&&L("Role type is invalid.",t,e),e}function md(e,t){return e==="default"||$("state",e)?e:L("State ID is invalid.",t,e)}function lE(e){let t=e.tag("create",!1);De(t,[]);let n=[],o=new Map,i=null,r=0,s=a=>{if(i===null)return;let d=o.get(i);(!d||d.states.length===0||d.states[0].state_id!=="default")&&L("A new asset must be followed immediately by its default state.",a,i),i=null};for(;e.nextTag()?.name!=="create"||e.nextTag()?.closing!==!0;){let a=Wo(e),d=e.record();if(d.type==="actor"){r>0&&L("Create declarations are not in canonical order.",d.source.line,d.type),s(d.source.line),a.prompt!==void 0&&L("prompt cannot modify an asset.",d.source.line,d.type),(d.slots.length<3||d.slots.length>4||!$("actor",d.slots[0]))&&L("actor declaration is invalid.",d.source.line,d.type);let p=pE(d.slots[3],d.source.line),l={actor_id:d.slots[0],actor_name:d.slots[1],importance:sd(d.slots[2],d.source.line),description:d.content,states:[],...p===void 0?{}:{role_type:p},...a.aliases===void 0?{}:{aliases:a.aliases},...a.extend===void 0?{}:{extend:a.extend}};l.aliases?.includes(l.actor_name)&&L("An alias must differ from the asset name.",d.source.line,l.actor_name),n.push({kind:"actor",value:l}),o.set(l.actor_id,l),i=l.actor_id}else if(d.type==="location"||d.type==="prop"){let p=d.type==="location"?1:2;p<r&&L("Create declarations are not in canonical order.",d.source.line,d.type),r=p,s(d.source.line),a.prompt!==void 0&&L("prompt cannot modify an asset.",d.source.line,d.type);let l=d.type;if((d.slots.length!==3||(l==="location"?!$("location",d.slots[0]):!$("prop",d.slots[0])))&&L(`${l} declaration is invalid.`,d.source.line,d.type),l==="location"){let f=d.slots[0];$("location",f)||L("location ID is invalid.",d.source.line,f);let u={location_id:f,location_name:d.slots[1],importance:sd(d.slots[2],d.source.line),description:d.content,states:[],...a.aliases===void 0?{}:{aliases:a.aliases},...a.extend===void 0?{}:{extend:a.extend}};u.aliases?.includes(u.location_name)&&L("An alias must differ from the asset name.",d.source.line,u.location_name),n.push({kind:l,value:u}),o.set(u.location_id,u),i=u.location_id}else{let f=d.slots[0];$("prop",f)||L("prop ID is invalid.",d.source.line,f);let u={prop_id:f,prop_name:d.slots[1],importance:sd(d.slots[2],d.source.line),description:d.content,states:[],...a.aliases===void 0?{}:{aliases:a.aliases},...a.extend===void 0?{}:{extend:a.extend}};u.aliases?.includes(u.prop_name)&&L("An alias must differ from the asset name.",d.source.line,u.prop_name),n.push({kind:l,value:u}),o.set(u.prop_id,u),i=u.prop_id}}else if(d.type==="state"){(d.slots.length!==3||a.aliases!==void 0||a.prompt!==void 0)&&L("state declaration is invalid.",d.source.line,d.type);let p=d.slots[0],l=o.get(p);l&&i!==p&&L("States for a new asset must immediately follow that asset.",d.source.line,p),l||(s(d.source.line),r=3);let f={state_id:md(d.slots[1],d.source.line),state_name:d.slots[2],description:d.content,...a.extend===void 0?{}:{extend:a.extend}};l?(l.states.length===0&&f.state_id!=="default"&&L("The first state of a new asset must be default.",d.source.line,f.state_id),l.states.push(f)):n.push({kind:"state",ownerId:p,value:f})}else s(d.source.line),L("Unknown create declaration.",d.source.line,d.type)}s(e.peek().line);let c=e.tag("create",!0);return De(c,[]),n}function uE(e,t){let n=e.indexOf("/"),o=n<0?e:e.slice(0,n);if($("actor",o))return n<0?{actor_id:o}:{actor_id:o,state_id:md(e.slice(n+1),t)};let i=e.indexOf(":"),r=i<0?e:e.slice(0,i);return["system","broadcast","offscreen","group"].includes(r)?i<0?{kind:r}:{kind:r,label:e.slice(i+1)}:L("Speaker is invalid.",t,e)}function Zu(e){let t=Wo(e);t.aliases!==void 0&&L("aliases cannot modify an Action.",e.peek().line,"aliases");let n=e.record();return n.type==="act"||n.type==="trans"?((n.slots.length!==1||!$("action",n.slots[0]))&&L("Narrative Action record is invalid.",n.source.line,n.type),{action_id:n.slots[0],type:n.type==="act"?"action":"transition",content:n.content,...t.extend===void 0?{}:{extend:t.extend},...t.prompt===void 0?{}:{transition_prompt:t.prompt}}):n.type!=="dlg"&&n.type!=="think"?L("Unknown Action record.",n.source.line,n.type):((n.slots.length!==2&&n.slots.length!==3||!$("action",n.slots[0]))&&L("Speaking Action record is invalid.",n.source.line,n.type),{action_id:n.slots[0],type:n.type==="dlg"?"dialogue":"inner_thought",speaker:uE(n.slots[1],n.source.line),content:n.content,...n.slots.length===3?{parenthetical:n.slots[2]}:{},...t.extend===void 0?{}:{extend:t.extend},...t.prompt===void 0?{}:{transition_prompt:t.prompt}})}function ad(e,t){e.length===0&&L("Scene reference needs at least one state.",t,"<empty>");let n=e.map(o=>md(o,t));return new Set(n).size!==n.length&&L("Scene reference repeats a state.",t,n.join(",")),n.sort()}function ud(e,t,n,o){De(t,n===void 0?["id","parent"]:["id"]);let i=t.attrs.get("id")??"";$("scene",i)||L("Scene ID is invalid.",t.line,i);let r=t.attrs.get("parent")??n;r!==void 0&&!$("episode",r)&&L("Scene parent must be an Episode ID.",t.line,r);let s,c,a=[],d=[],p=new Set,l=new Set,f=0;for(;e.nextTag()?.name!=="body";){let h=e.record(),m=h.type==="environment"?0:h.type==="location"?1:h.type==="cast"?2:h.type==="prop"?3:-1;m<f&&L("Scene records are not in canonical order.",h.source.line,h.type),f=m,h.type==="environment"?(s!==void 0&&L("Scene environment is duplicated.",h.source.line,h.type),h.slots.length>2&&L("environment has too many slots.",h.source.line,h.type),s={...h.slots[0]===void 0?{}:{space:h.slots[0]},...h.slots[1]===void 0?{}:{time:h.slots[1]}}):h.type==="location"?(c!==void 0&&L("Scene location is duplicated.",h.source.line,h.type),h.slots.length===0?c=null:($("location",h.slots[0])||L("Location ref ID is invalid.",h.source.line,h.slots[0]),c={location_id:h.slots[0],state_ids:ad(h.slots.slice(1),h.source.line)})):h.type==="cast"?($("actor",h.slots[0])||L("Cast ref ID is invalid.",h.source.line,h.slots[0]??""),p.has(h.slots[0])&&L("Scene repeats an actor reference.",h.source.line,h.slots[0]),p.add(h.slots[0]),a.push({actor_id:h.slots[0],state_ids:ad(h.slots.slice(1),h.source.line)})):h.type==="prop"?($("prop",h.slots[0])||L("Prop ref ID is invalid.",h.source.line,h.slots[0]??""),l.has(h.slots[0])&&L("Scene repeats a prop reference.",h.source.line,h.slots[0]),l.add(h.slots[0]),d.push({prop_id:h.slots[0],state_ids:ad(h.slots.slice(1),h.source.line)})):L("Unknown scene header record.",h.source.line,h.type)}c===void 0&&L("Scene must declare location or [location].",e.peek().line,i);let u=e.tag("body",!1);De(u,[]);let g=[];for(;e.nextTag()?.name!=="body"||e.nextTag()?.closing!==!0;)g.push(Zu(e));return De(e.tag("body",!0),[]),De(e.tag("scene",!0),[]),{...r===void 0?{}:{parent:r},value:{scene_id:i,...s===void 0?{}:{environment:s},location:c,actors:a,props:d,actions:g,...o===void 0?{}:{extend:o}}}}function fd(e,t,n){De(t,["id"]);let o=t.attrs.get("id")??"";$("episode",o)||L("Episode ID is invalid.",t.line,o);let i,r,s=[],c=0;for(;e.nextTag()?.name!=="episode"||e.nextTag()?.closing!==!0;){let a=Wo(e);(a.aliases!==void 0||a.prompt!==void 0)&&L("Invalid episode child modifier.",e.peek().line,"modifier");let d=e.nextTag();if(d?.name==="scene"&&!d.closing){c=2,e.take(),s.push(ud(e,d,o,a.extend).value);continue}a.extend!==void 0&&L("extend must precede a scene here.",e.peek().line,"extend");let p=e.record(),l=p.type==="title"?0:p.type==="synopsis"?1:-1;l<c&&L("Episode records are not in canonical order.",p.source.line,p.type),c=l,p.type==="title"?(i!==void 0&&L("Episode title is duplicated.",p.source.line,p.type),p.slots.length!==0&&L("Episode title takes no slots.",p.source.line,p.type),i=p.content):p.type==="synopsis"?(r!==void 0&&L("Episode synopsis is duplicated.",p.source.line,p.type),p.slots.length!==0&&L("Episode synopsis takes no slots.",p.source.line,p.type),r=p.content):L("Unknown episode record.",p.source.line,p.type)}return De(e.tag("episode",!0),[]),{episode_id:o,...i===void 0?{}:{title:i},...r===void 0?{}:{synopsis:r},scenes:s,...n===void 0?{}:{extend:n}}}function cd(e,t){let n=e.attrs.get("range")??"",o=n.split("..");return(o.length!==2||!o[0]||!o[1]||!$(t,o[0])||!$(t,o[1]))&&L(`Span range must contain two ${t} IDs.`,e.line,n),[o[0],o[1]]}function fE(e,t,n){De(t,[]);let o,i,r,s,c,a,d,p,l=[],f=0;for(;e.nextTag()?.name!=="script"||e.nextTag()?.closing!==!0;){let u=Wo(e);(u.aliases!==void 0||u.prompt!==void 0)&&L("Invalid script child modifier.",e.peek().line,"modifier");let g=e.nextTag();if(g?.name==="episode"&&!g.closing){f=8,e.take(),l.push(fd(e,g,u.extend));continue}u.extend!==void 0&&L("extend must precede an episode here.",e.peek().line,"extend");let h=e.record(),m=h.type==="title"?0:h.type==="worldview"?1:h.type==="worldview-raw"?2:h.type==="style"?3:h.type==="synopsis"?4:h.type==="logline"?5:h.type==="theme"?6:h.type==="main-characters"||h.type==="main-character"?7:-1;m<f&&L("Script records are not in canonical order.",h.source.line,h.type),f=m,h.type!=="main-character"&&h.slots.length!==0&&L("Script metadata record takes no slots.",h.source.line,h.type),h.type==="title"?(o!==void 0&&L("Script title is duplicated.",h.source.line,h.type),o=h.content):h.type==="worldview"?(i!==void 0&&L("Script worldview is duplicated.",h.source.line,h.type),i=h.content):h.type==="worldview-raw"?(r!==void 0&&L("Script worldview-raw is duplicated.",h.source.line,h.type),r=h.content):h.type==="style"?(s!==void 0&&L("Script style is duplicated.",h.source.line,h.type),s=h.content):h.type==="synopsis"?(c!==void 0&&L("Script synopsis is duplicated.",h.source.line,h.type),c=h.content):h.type==="logline"?(a!==void 0&&L("Script logline is duplicated.",h.source.line,h.type),a=h.content):h.type==="theme"?(d!==void 0&&L("Script theme is duplicated.",h.source.line,h.type),d=h.content):h.type==="main-characters"?(p!==void 0&&L("Script main-characters is duplicated.",h.source.line,h.type),p=[]):h.type==="main-character"&&p!==void 0&&h.slots.length===2&&h.content===""?p.push({name:h.slots[0],role:h.slots[1]}):L("Unknown script record.",h.source.line,h.type)}return De(e.tag("script",!0),[]),(o===void 0||i===void 0||s===void 0)&&L("Script target needs title, worldview, and style.",e.peek().line,"script"),{kind:"script",value:{title:o,worldview:i,style:s,episodes:l,...r===void 0?{}:{worldview_raw:r},...c===void 0?{}:{synopsis:c},...a===void 0?{}:{logline:a},...d===void 0?{}:{theme:d},...p===void 0?{}:{main_characters:p},...n===void 0?{}:{extend:n}}}}function Wu(e){let t=new pd(e),n=t.tag("authoring",!1);De(n,["version"]),n.attrs.get("version")!=="1"&&L("authoring version must be 1.",1,n.attrs.get("version")??"<missing>");let o=t.nextTag()?.name==="create"?lE(t):[],i=[];for(;t.nextTag()?.name!=="authoring"||t.nextTag()?.closing!==!0;){let s=Wo(t);(s.aliases!==void 0||s.prompt!==void 0)&&L("Invalid target modifier.",t.peek().line,"modifier");let c=t.take(),a=dd(c.raw,c.line);if((!a||a.closing)&&L("Expected an authoring target.",c.line,c.raw),a.name==="script")i.push(fE(t,a,s.extend));else if(a.name==="episode")i.push({kind:"episode",value:fd(t,a,s.extend)});else if(a.name==="scene"){let d=ud(t,a,void 0,s.extend);d.parent||L("Top-level scene needs parent.",c.line,c.raw),i.push({kind:"scene",parent:d.parent,value:d.value})}else if(a.name==="episode-span"){s.extend!==void 0&&L("A span cannot carry node extensions.",c.line,c.raw),De(a,["range"]);let[d,p]=cd(a,"episode"),l=[];for(;t.nextTag()?.name!=="episode-span"||t.nextTag()?.closing!==!0;){let f=Wo(t);(f.aliases!==void 0||f.prompt!==void 0)&&L("Invalid episode child modifier.",t.peek().line,"modifier");let u=t.tag("episode",!1);l.push(fd(t,u,f.extend))}De(t.tag("episode-span",!0),[]),i.push({kind:"episode-span",from:d,through:p,values:l})}else if(a.name==="scene-span"){s.extend!==void 0&&L("A span cannot carry node extensions.",c.line,c.raw),De(a,["parent","range"]);let[d,p]=cd(a,"scene"),l=a.attrs.get("parent")??L("scene-span needs parent.",c.line,c.raw);$("episode",l)||L("scene-span parent must be an Episode ID.",c.line,l);let f=[];for(;t.nextTag()?.name!=="scene-span"||t.nextTag()?.closing!==!0;){let u=Wo(t);(u.aliases!==void 0||u.prompt!==void 0)&&L("Invalid scene child modifier.",t.peek().line,"modifier");let g=t.tag("scene",!1);f.push(ud(t,g,l,u.extend).value)}De(t.tag("scene-span",!0),[]),i.push({kind:"scene-span",parent:l,from:d,through:p,values:f})}else if(a.name==="action-span"){s.extend!==void 0&&L("A span cannot carry node extensions.",c.line,c.raw),De(a,["parent","range"]);let[d,p]=cd(a,"action"),l=a.attrs.get("parent")??L("action-span needs parent.",c.line,c.raw);$("scene",l)||L("action-span parent must be a Scene ID.",c.line,l),De(t.tag("body",!1),[]);let f=[];for(;t.nextTag()?.name!=="body"||t.nextTag()?.closing!==!0;)f.push(Zu(t));De(t.tag("body",!0),[]),De(t.tag("action-span",!0),[]),i.push({kind:"action-span",parent:l,from:d,through:p,values:f})}else L("Unknown authoring target.",c.line,a.name)}De(t.tag("authoring",!0),[]),(t.index!==t.lines.length||i.length===0)&&L("Authoring file has trailing content or no targets.",t.peek().line,"<root>");let r=i[0].kind;return i.every(s=>s.kind===r)||L("All targets must have the same kind.",1,r),{declarations:o,targets:i,targetKind:r}}function In(e){if(Array.isArray(e))return e.map(t=>In(t));if(ie(e)){let t={};for(let n of Object.keys(e).sort())t[n]=In(e[n]);return t}return e}function gd(e){if(e.length===0)return[];let t={};for(let i of e){let r=v(i.severity);t[r]=(t[r]??0)+1}let n=Object.entries(t).sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>`${i}: ${r}`),o=e[0];return[n.join("; "),`first: ${o.code} - ${o.summary}`,...o.repair_hint?[`repair: ${o.repair_hint}`]:[]]}function Xu(e,t){if(!(t.ok||e!==null&&Oc(Pe(e),t)))throw new S("The proposed document is not a valid or strictly improved Script v4.",{exitCode:k,errorCode:"AUTHORING_VALIDATION_FAILED",data:{actual:t.errors.slice(0,20).map(n=>`${n.path}: ${n.message}`)}})}function Ce(e,t){throw new S(e,{exitCode:k,errorCode:"AUTHORING_APPLY_INVALID",data:{actual:t}})}function yd(e){return{ids:e.map(t=>t.action_id),counts:{episodes:0,scenes:0,actions:e.length}}}function Bi(e){return{ids:e.flatMap(t=>[t.scene_id,...t.actions.map(n=>n.action_id)]),counts:{episodes:0,scenes:e.length,actions:e.reduce((t,n)=>t+n.actions.length,0)}}}function _o(e){return{ids:e.flatMap(t=>[t.episode_id,...t.scenes.flatMap(n=>[n.scene_id,...n.actions.map(o=>o.action_id)])]),counts:{episodes:e.length,scenes:e.reduce((t,n)=>t+n.scenes.length,0),actions:e.reduce((t,n)=>t+n.scenes.reduce((o,i)=>o+i.actions.length,0),0)}}}function mE(e){return e.kind==="script"?_o(e.value.episodes):e.kind==="episode"?_o([e.value]):e.kind==="episode-span"?_o(e.values):e.kind==="scene"?Bi([e.value]):e.kind==="scene-span"?Bi(e.values):yd(e.values)}function gE(e){return{actors:e.filter(t=>t.kind==="actor").map(t=>structuredClone(t.value)),locations:e.filter(t=>t.kind==="location").map(t=>structuredClone(t.value)),props:e.filter(t=>t.kind==="prop").map(t=>structuredClone(t.value))}}function hd(e,t){return JSON.stringify(In(e))===JSON.stringify(In(t))}function ef(e,t){let n=new Set(e===null?[]:[...e.actors.map(d=>d.actor_id),...e.locations.map(d=>d.location_id),...e.props.map(d=>d.prop_id)]),o=new Set(e===null?[]:[...e.actors.flatMap(d=>d.states.map(p=>`${d.actor_id}/${p.state_id}`)),...e.locations.flatMap(d=>d.states.map(p=>`${d.location_id}/${p.state_id}`)),...e.props.flatMap(d=>d.states.map(p=>`${d.prop_id}/${p.state_id}`))]),i=[],r=[],s=[],c=[],a=d=>{(o.has(d)?c:s).push(d)};for(let d of t){if(d.kind==="state"){n.has(d.ownerId)&&r.push(d.ownerId),a(`${d.ownerId}/${d.value.state_id}`);continue}let p=d.kind==="actor"?d.value.actor_id:d.kind==="location"?d.value.location_id:d.value.prop_id;(n.has(p)?r:i).push(p),d.value.states.forEach(l=>{a(`${p}/${l.state_id}`)})}return{createdAssets:i,existingAssets:[...new Set(r)],createdStates:s,existingStates:c}}function tf(e){let t=new Set;for(let n of e.episodes)for(let o of n.scenes)o.location&&t.add(o.location.location_id),o.actors.forEach(i=>t.add(i.actor_id)),o.props.forEach(i=>t.add(i.prop_id)),o.actions.forEach(i=>{i.transition_prompt&&t.add(i.transition_prompt.target)});return[...e.actors.map(n=>n.actor_id),...e.locations.map(n=>n.location_id),...e.props.map(n=>n.prop_id)].filter(n=>!t.has(n))}function nf(e){return[...e.actors.flatMap(t=>[t.actor_id,...t.states.map(n=>`${t.actor_id}/${n.state_id}`)]),...e.locations.flatMap(t=>[t.location_id,...t.states.map(n=>`${t.location_id}/${n.state_id}`)]),...e.props.flatMap(t=>[t.prop_id,...t.states.map(n=>`${t.prop_id}/${n.state_id}`)]),...e.episodes.flatMap(t=>[t.episode_id,...t.scenes.flatMap(n=>[n.scene_id,...n.actions.map(o=>o.action_id)])])]}function of(e,t){let n=e===null?[]:nf(e),o=nf(t),i=new Set(n),r=new Set(o);return{createdIds:o.filter(s=>!i.has(s)),removedIds:n.filter(s=>!r.has(s)),retainedIds:n.filter(s=>r.has(s))}}function hE(e,t){for(let n of t)if(n.kind==="actor")e.actors.some(o=>o.actor_id===n.value.actor_id)&&Ce("Declaration cannot redefine an existing actor.",[n.value.actor_id]),e.actors.push(structuredClone(n.value));else if(n.kind==="location")e.locations.some(o=>o.location_id===n.value.location_id)&&Ce("Declaration cannot redefine an existing location.",[n.value.location_id]),e.locations.push(structuredClone(n.value));else if(n.kind==="prop")e.props.some(o=>o.prop_id===n.value.prop_id)&&Ce("Declaration cannot redefine an existing prop.",[n.value.prop_id]),e.props.push(structuredClone(n.value));else{let o=e.actors.find(i=>i.actor_id===n.ownerId)??e.locations.find(i=>i.location_id===n.ownerId)??e.props.find(i=>i.prop_id===n.ownerId);o||Ce("State declaration owner was not found.",[n.ownerId]),o.states.some(i=>i.state_id===n.value.state_id)&&Ce("State declaration cannot redefine an existing state.",[`${n.ownerId}/${n.value.state_id}`]),o.states.push(structuredClone(n.value))}}function Wt(e,t,n){let o=e.indexOf(t),i=e.indexOf(n);return(o<0||i<0)&&Ce("Span endpoint was not found.",[t,n]),[Math.min(o,i),Math.max(o,i)]}function yE(e,t){if(t.kind==="script")return[0,0];if(t.kind==="episode"||t.kind==="episode-span"){let o=e.episodes.map(i=>i.episode_id);return t.kind==="episode"?Wt(o,t.value.episode_id,t.value.episode_id):Wt(o,t.from,t.through)}if(t.kind==="scene"||t.kind==="scene-span"){let o=e.episodes.flatMap(i=>i.scenes.map(r=>r.scene_id));return t.kind==="scene"?Wt(o,t.value.scene_id,t.value.scene_id):Wt(o,t.from,t.through)}let n=e.episodes.flatMap(o=>o.scenes.flatMap(i=>i.actions.map(r=>r.action_id)));return Wt(n,t.from,t.through)}function wE(e,t){let n=-1;for(let o of t){let[i,r]=yE(e,o);i<=n&&Ce("Replace targets must follow current document order without overlap.",[cf(o)]),n=r}}function cf(e){return e.kind==="script"?"script":e.kind==="episode"?e.value.episode_id:e.kind==="scene"?e.value.scene_id:`${e.from}..${e.through}`}function rf(e,t){if(t.kind==="script")return{..._o(e.episodes),siblings:0};if(t.kind==="episode"){let r=En(e,t.value.episode_id);return{..._o(r?[r.episode]:[]),siblings:Math.max(0,e.episodes.length-(r?1:0))}}if(t.kind==="episode-span"){let[r,s]=Wt(e.episodes.map(c=>c.episode_id),t.from,t.through);return{..._o(e.episodes.slice(r,s+1)),siblings:e.episodes.length-(s-r+1)}}if(t.kind==="scene"){let r=Kn(e,t.value.scene_id),s=En(e,t.parent)?.episode;return{...Bi(r?[r.scene]:[]),siblings:r?Math.max(0,r.episode.scenes.length-1):s?.scenes.length??0}}if(t.kind==="scene-span"){let r=En(e,t.parent)?.episode;if(!r)return{...Bi([]),siblings:0};let[s,c]=Wt(r.scenes.map(a=>a.scene_id),t.from,t.through);return{...Bi(r.scenes.slice(s,c+1)),siblings:r.scenes.length-(c-s+1)}}let n=Kn(e,t.parent)?.scene;if(!n)return{...yd([]),siblings:0};let[o,i]=Wt(n.actions.map(r=>r.action_id),t.from,t.through);return{...yd(n.actions.slice(o,i+1)),siblings:n.actions.length-(i-o+1)}}function sf(e,t){let n=mE(e),o=new Set(t.ids),i=new Set(n.ids);return{kind:e.kind,address:cf(e),before:t.counts,after:n.counts,retainedIds:t.ids.filter(r=>i.has(r)),createdIds:n.ids.filter(r=>!o.has(r)),removedIds:t.ids.filter(r=>!i.has(r)),untouchedSiblings:t.siblings}}function _E(e,t){if(t.kind==="script"&&Ce("An existing Script v4 is not replaced through a script root.",["script"]),t.kind==="episode"){let n=En(e,t.value.episode_id);n||Ce("Episode replacement target was not found.",[t.value.episode_id]),e.episodes[n.episodeIndex]=structuredClone(t.value)}else if(t.kind==="episode-span"){let[n,o]=Wt(e.episodes.map(i=>i.episode_id),t.from,t.through);t.values.length===0&&Ce("Episode span replacement cannot be empty.",[t.from,t.through]),e.episodes.splice(n,o-n+1,...structuredClone(t.values))}else if(t.kind==="scene"){let n=Kn(e,t.value.scene_id);(!n||n.episode.episode_id!==t.parent)&&Ce("Scene replacement target was not found under its parent.",[t.parent,t.value.scene_id]),n.episode.scenes[n.sceneIndex]=structuredClone(t.value)}else if(t.kind==="scene-span"){let n=En(e,t.parent)?.episode;n||Ce("Scene span parent was not found.",[t.parent]);let[o,i]=Wt(n.scenes.map(r=>r.scene_id),t.from,t.through);t.values.length===0&&Ce("Scene span replacement cannot be empty.",[t.from,t.through]),n.scenes.splice(o,i-o+1,...structuredClone(t.values))}else{let n=Kn(e,t.parent)?.scene;n||Ce("Action span parent was not found.",[t.parent]);let[o,i]=Wt(n.actions.map(r=>r.action_id),t.from,t.through);t.values.length===0&&Ce("Action span replacement cannot be empty.",[t.from,t.through]),n.actions.splice(o,i-o+1,...structuredClone(t.values))}}function EE(e,t){if(t.kind==="episode")e.episodes.push(structuredClone(t.value));else if(t.kind==="scene"){let n=En(e,t.parent)?.episode;n||Ce("Scene create parent was not found.",[t.parent]),n.scenes.push(structuredClone(t.value))}else Ce("This target kind does not support create against an existing script.",[t.kind])}function af(e){if(e.targets.length!==1||e.targets[0].kind!=="script")return Ce("Script create requires exactly one script target.",[e.targetKind]);if(e.declarations.some(n=>n.kind==="state"))return Ce("Standalone state declarations need an existing owner.",["state"]);let t=e.targets[0];return{version:4,...structuredClone(t.value),...gE(e.declarations)}}function df(e,t,n){let o;if(e===null)n!=="create"&&Ce("A missing target requires one script create target.",[n,t.targetKind]),o=af(t);else if(n==="create"&&t.targetKind==="script")o=af(t),hd(o,e)||Ce("Script create retry differs from the existing script.",["script"]);else{o=structuredClone(e),n==="replace"&&wE(e,t.targets),hE(o,t.declarations);let r=t.targets.map(a=>rf(e,a));if(n==="replace")for(let a of[...t.targets].reverse())_E(o,a);else for(let a of t.targets)EE(o,a);let s=t.targets.map((a,d)=>sf(a,r[d])),c=Pe(o);return Xu(e,c),{script:o,changed:!hd(e,o),validation:c,targets:s,declarations:ef(e,t.declarations),retainedOrphanAssets:tf(o),identity:of(e,o)}}let i=Pe(o);return Xu(e,i),{script:o,changed:e===null||!hd(e,o),validation:i,declarations:ef(e,t.declarations),retainedOrphanAssets:tf(o),identity:of(e,o),targets:t.targets.map(r=>{let s=e===null?{..._o([]),siblings:0}:rf(e,r);return sf(r,s)})}}function Xo(e,t){throw new S(e,{exitCode:J,errorCode:"AUTHORING_USAGE_INVALID",hint:"Choose exactly one mode and pass a regular authoring source file.",data:{expected:["scriptctl authoring write <file> (--create|--replace) [--apply --plan <digest>]"],actual:t}})}function xE(e){(!e||e==="-")&&Xo("Authoring input must be a named file.",[e||"<missing>"]);let t=pf.resolve(e),n;try{n=Vr.statSync(t)}catch{throw new S("The authoring source file does not exist.",{exitCode:k,errorCode:"AUTHORING_SOURCE_UNAVAILABLE",hint:"Write the complete authoring draft to a file, then rerun the command.",data:{actual:[t]}})}n.isFile()||Xo("Authoring input must be a regular file.",[t]);let o=Vr.readFileSync(t);return{absolutePath:t,bytes:o,text:o.toString("utf-8")}}function SE(e){let t=Or(e);if(t===null)return{script:null,baseline:"missing",fingerprint:t};let n;try{n=JSON.parse(Vr.readFileSync(e,"utf-8"))}catch(i){throw new S("The local script is not valid JSON.",{exitCode:k,errorCode:"SCRIPT_JSON_INVALID",hint:"Repair the local JSON file, then rerun authoring.",data:{actual:[e,i instanceof Error?i.message:String(i)]}})}let o=Bs(n);return{script:o,baseline:Be(o),fingerprint:t}}function IE(e){let t=e.create===!0,n=e.replace===!0;return t===n&&Xo("Choose exactly one authoring mode.",[`create=${t}`,`replace=${n}`]),t?"create":"replace"}function lf(e){return`sha256:${Ee(JSON.stringify(e))}`}function AE(e){return e.targets.reduce((t,n)=>({before:{episodes:t.before.episodes+n.before.episodes,scenes:t.before.scenes+n.before.scenes,actions:t.before.actions+n.before.actions},after:{episodes:t.after.episodes+n.after.episodes,scenes:t.after.scenes+n.after.scenes,actions:t.after.actions+n.after.actions}}),{before:{episodes:0,scenes:0,actions:0},after:{episodes:0,scenes:0,actions:0}})}function kE(e){let t=e.targets.map((n,o)=>[`target[${o}]=${n.address}`,`kind=${n.kind}`,`before=${JSON.stringify(n.before)}`,`after=${JSON.stringify(n.after)}`,`retained=${JSON.stringify(n.retainedIds)}`,`created=${JSON.stringify(n.createdIds)}`,`removed=${JSON.stringify(n.removedIds)}`,`untouched_siblings=${n.untouchedSiblings}`].join(" "));t.push(`created_assets=${JSON.stringify(e.declarations.createdAssets)}`,`existing_assets=${JSON.stringify(e.declarations.existingAssets)}`,`created_states=${JSON.stringify(e.declarations.createdStates)}`,`existing_states=${JSON.stringify(e.declarations.existingStates)}`,`retained_orphan_assets=${JSON.stringify(e.retainedOrphanAssets)}`,`validation_ok=${e.validation.ok} errors=${e.validation.errors.length} warnings=${e.validation.warnings.length}`);for(let n of e.validation.errors)t.push(`validation_error=${n.path} ${n.code} ${n.message}`);for(let n of e.validation.warnings)t.push(`validation_warning=${n.path} ${n.code} ${n.message}`);return t}function bE(e,t,n,o,i){let r=Wu(t.text),s=i.script===null?null:_n(i.script),c=df(s,r,n),a=`sha256:${wd.createHash("sha256").update(t.bytes).digest("hex")}`,d={version:1,sourceDigest:a,mode:n,targetKind:r.targetKind,targets:c.targets.map(m=>m.address),baseline:i.baseline,plan:{targets:c.targets,declarations:c.declarations,retainedOrphanAssets:c.retainedOrphanAssets,identity:c.identity,validation:c.validation}},p=lf(d),l=e.apply===!0,f=v(e.plan).trim();if(l&&!f&&Xo("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!l&&f&&Xo("--plan is only valid together with --apply.",[`plan=${f}`]),l&&f!==p)throw new S("The supplied plan does not match the current source, mode, targets, or script baseline.",{exitCode:k,errorCode:"AUTHORING_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[p],actual:[f]}});l&&c.changed&&(i.script===null?vr(o,i.fingerprint):Gt(o,i.baseline),Fe(o,c.script));let u=c.targets.map((m,w)=>`target[${w}]=${m.address} kind=${m.kind} before=${JSON.stringify(m.before)} after=${JSON.stringify(m.after)} retained=${JSON.stringify(m.retainedIds)} created=${JSON.stringify(m.createdIds)} removed=${JSON.stringify(m.removedIds)} untouched_siblings=${m.untouchedSiblings}`);return u.push(`created_assets=${JSON.stringify(c.declarations.createdAssets)}`,`existing_assets=${JSON.stringify(c.declarations.existingAssets)}`,`created_states=${JSON.stringify(c.declarations.createdStates)}`,`existing_states=${JSON.stringify(c.declarations.existingStates)}`,`retained_orphan_assets=${JSON.stringify(c.retainedOrphanAssets)}`,`created_ids=${JSON.stringify(c.identity.createdIds)}`,`removed_ids=${JSON.stringify(c.identity.removedIds)}`,`retained_ids=${JSON.stringify(c.identity.retainedIds)}`),[{text:[`${l?"Applied":"Planned"} ${c.targets.length} ${r.targetKind} target(s); validation ${c.validation.ok?"passed":"needs repair"}`,`plan: ${p}`,...u].join(`
132
- `),data:{op:"write",changed:c.changed,source_path:t.absolutePath,source_digest:a,script_path:o,baseline:i.baseline,script_hash:i.baseline==="missing"?null:i.baseline,plan_digest:p,plan:d.plan,mode:n,target_kind:r.targetKind,targets:c.targets,declarations:c.declarations,retained_orphan_assets:c.retainedOrphanAssets,identity:c.identity,validation:c.validation,applied:l,script_version:4}},B]}function uf(e){let t=Array.isArray(e._args)?e._args:[],n=typeof t[0]=="string"?t[0]:"",o=xE(n),i=IE(e),r=ge(e),s=SE(r);if(s.script===null||s.script.version===4)return bE(e,o,i,r,s);let c=qu(o.text),a=Fu(Tt(s.script),c,i),d=`sha256:${wd.createHash("sha256").update(o.bytes).digest("hex")}`,p={version:1,sourceDigest:d,mode:i,targetKind:c.targetKind,targets:a.targets.map(w=>w.address),baseline:s.baseline,plan:{targets:a.targets,declarations:a.declarations,retainedOrphanAssets:a.retainedOrphanAssets,validation:a.validation}},l=lf(p),f=e.apply===!0,u=v(e.plan).trim();if(f&&!u&&Xo("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!f&&u&&Xo("--plan is only valid together with --apply.",[`plan=${u}`]),f&&u!==l)throw new S("The supplied plan does not match the current source, mode, targets, or script baseline.",{exitCode:k,errorCode:"AUTHORING_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[l],actual:[u]}});f&&a.changed&&(s.script===null?vr(r,s.fingerprint):Gt(r,s.baseline),Fe(r,a.script));let g=AE(a);return[{text:[`${f?"Applied":"Planned"} ${a.targets.length} ${c.targetKind} target(s); episodes ${g.before.episodes}\u2192${g.after.episodes}, scenes ${g.before.scenes}\u2192${g.after.scenes}, actions ${g.before.actions}\u2192${g.after.actions}`,`plan: ${l}`,...kE(a)].join(`
133
- `),data:{op:"write",changed:a.changed,source_path:o.absolutePath,source_digest:d,script_path:r,baseline:s.baseline,script_hash:s.baseline==="missing"?null:s.baseline,plan_digest:l,plan:p.plan,mode:i,target_kind:c.targetKind,targets:a.targets,declarations:a.declarations,counts:g,validation:a.validation,retained_orphan_assets:a.retainedOrphanAssets,applied:f,script_version:3}},B]}function mf(e){return Array.isArray(e.rows)}function OE(e){return e.endsWith(`
131
+ `)}parse(){this.skipBlank();let t=this.takeOpen("authoring");if(Sn(t,["version"]),t.attrs.get("version")!=="1")throw $("Authoring version is unsupported.",t.source,t.attrs.get("version")??"<missing>","Use <authoring version=1>.");let n=[],o=[],i=!1,r=Et();for(;;){if(this.skipBlank(),this.peekClose("authoring")){zn(r)&&this.throwDangling(r),this.takeClose("authoring");break}let a=this.peekSemantic();if(a===null)throw this.eofError("authoring");if(a.record?.type==="extensions"||a.record?.type==="extend"){r=this.addModifier(r,this.takeRecord());continue}if(a.tag?.name==="create"&&!a.tag.closing){if(i)throw $("<create> must precede every target.",a.tag.source,"<create>","Move the single <create> block before the targets.");zn(r)&&this.throwUnsupportedModifiers(r,"create"),n.push(...this.parseCreate()),i=!0;continue}i=!0,o.push(this.parseTarget(r)),r=Et()}if(this.skipBlank(),this.index<this.lines.length){let a={line:this.index+1,column:1};throw $("Content exists after </authoring>.",a,this.lines[this.index],"Remove content outside the root block.")}if(o.length===0)throw $("Authoring file has no target.",t.source,"<authoring>","Add one or more homogeneous target blocks.");let s=o[0].kind,c=o.find(a=>a.kind!==s);if(c!==void 0)throw $("Authoring targets are not homogeneous.",c.source,c.kind,`Keep only ${s} targets in this file.`);if(s==="script"&&o.length!==1)throw $("A script authoring file has exactly one target.",o[1].source,"second <script>","Keep one <script> target.");return{version:1,declarations:n,targets:o,targetKind:s}}parseCreate(){let t=this.takeOpen("create");Sn(t,[]);let n=[],o=Et();for(;;){if(this.skipBlank(),this.peekClose("create"))return zn(o)&&this.throwDangling(o),this.takeClose("create"),n;let i=this.takeRecord();if(i.type==="extensions"||i.type==="extend"||i.type==="aliases"||i.type==="alias"||i.type==="prompt"){o=this.addModifier(o,i);continue}if(i.type==="actor"){if(i.slots.length<3||i.slots.length>4)throw $("Actor declaration slots are invalid.",i.source,i.slots.join("|"),"Use [actor|id|name|importance|role?] description.");let[r,s,c,a]=i.slots;if(!r||!s||!c||!Pt.has(c)||!qu(c))throw $("Actor declaration is invalid.",i.source,i.slots.join("|"),"Provide id, name, and featured|background importance.");if(a!==void 0&&(!lo.has(a)||!aE(a)))throw $("Actor role is invalid.",i.source,a,"Use \u4E3B\u89D2 or \u914D\u89D2, or omit the slot.");let d={actor_id:r,actor_name:s,importance:c,description:i.content,states:[]};a!==void 0&&(d.role_type=a),o.aliasesPresent&&(d.aliases=[...o.aliases]);let p=xt(o);p!==void 0&&(d.extend=p),o.prompt!==void 0&&this.throwUnsupportedModifiers(o,"actor"),n.push({declarationKind:"actor",value:d,source:i.source}),o=Et();continue}if(i.type==="location"||i.type==="prop"){if(i.slots.length!==3)throw $(`${i.type} declaration slots are invalid.`,i.source,i.slots.join("|"),`Use [${i.type}|id|name|importance] description.`);let[r,s,c]=i.slots;if(!r||!s||!c||!Pt.has(c)||!qu(c))throw $(`${i.type} declaration is invalid.`,i.source,i.slots.join("|"),"Provide id, name, and featured|background importance.");o.prompt!==void 0&&this.throwUnsupportedModifiers(o,i.type);let a=xt(o);if(i.type==="location"){let d={location_id:r,location_name:s,importance:c,description:i.content,states:[]};o.aliasesPresent&&(d.aliases=[...o.aliases]),a!==void 0&&(d.extend=a),n.push({declarationKind:"location",value:d,source:i.source})}else{let d={prop_id:r,prop_name:s,importance:c,description:i.content,states:[]};o.aliasesPresent&&(d.aliases=[...o.aliases]),a!==void 0&&(d.extend=a),n.push({declarationKind:"prop",value:d,source:i.source})}o=Et();continue}if(i.type==="state"){if(i.slots.length!==3)throw $("State declaration slots are invalid.",i.source,i.slots.join("|"),"Use [state|kind:asset_id|state_id|state_name] description.");(o.aliasesPresent||o.prompt!==void 0)&&this.throwUnsupportedModifiers(o,"state");let[r,s,c]=i.slots,a=/^(actor|location|prop):(.+)$/.exec(r??""),d=a?.[1]??"";if(!a||!dE(d)||!s||!c)throw $("State declaration is invalid.",i.source,i.slots.join("|"),"Use a typed owner and non-empty state ID/name.");let p={state_id:s,state_name:c,description:i.content},l=xt(o);l!==void 0&&(p.extend=l),n.push({declarationKind:"state",ownerKind:d,ownerId:a[2],value:p,source:i.source}),o=Et();continue}throw $("Record is not allowed in <create>.",i.source,i.type,"Use actor, location, prop, state, or a supported prefix modifier.")}}parseTarget(t){let n=this.peekTag();if(n===null||n.closing){let o=n?.source??{line:this.index+1,column:1};throw $("Expected a target block.",o,this.lines[this.index]??"<eof>","Add a supported target block.")}switch((t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,n.name),n.name){case"script":return this.parseScript(t);case"episode":return{kind:"episode",value:this.parseEpisode(t),source:n.source,...xt(t)?{extend:xt(t)}:{}};case"episode-span":return this.parseEpisodeSpan(t);case"scene":return Sn(n,["id","parent"]),{kind:"scene",parent:n.attrs.get("parent"),value:this.parseScene(t,!0),source:n.source,...xt(t)?{extend:xt(t)}:{}};case"scene-span":return this.parseSceneSpan(t);case"action-span":return this.parseActionSpan(t);default:throw $("Unknown target block.",n.source,n.name,"Use script, episode, episode-span, scene, scene-span, or action-span.")}}parseScript(t){let n=this.takeOpen("script");Sn(n,[]);let o=["title","worldview","worldview-raw","style","synopsis","logline","theme","main-characters","main-character"],i=new Map,r=[],s=[],c=-1,a=!1,d=Et();for(;;){if(this.skipBlank(),this.peekClose("script")){zn(d)&&this.throwDangling(d),this.takeClose("script");break}let m=this.peekSemantic();if(m?.record!==void 0){let h=this.takeRecord();if(h.type==="extensions"||h.type==="extend"||h.type==="aliases"||h.type==="alias"||h.type==="prompt"){d=this.addModifier(d,h);continue}zn(d)&&this.throwUnsupportedModifiers(d,h.type);let g=o.indexOf(h.type),w=h.type==="main-character";if(a||g<0||g<c||!w&&i.has(h.type))throw $("Metadata record in <script> is invalid or out of order.",h.source,h.type,`Use ${o.join(", ")} in canonical order before episode blocks.`);if(c=g,h.type==="main-characters"){if(h.slots.length!==0||h.content!=="")throw $("Main characters marker is invalid.",h.source,h.content,"Use [main-characters] with no slots or content.");i.set(h.type,"")}else if(w){if(h.slots.length!==2||!h.slots[0]||!h.slots[1]||h.content!=="")throw $("Main character record is invalid.",h.source,h.slots.join("|"),"Use [main-character|name|role] with no content.");r.push({name:h.slots[0],role:h.slots[1]})}else{if(h.slots.length!==0)throw $("Script metadata record has unexpected slots.",h.source,h.slots.join("|"),`Use [${h.type}] content.`);i.set(h.type,h.content)}continue}if(m?.tag===void 0||m.tag.closing||m.tag.name!=="episode"){let h=m?.tag?.source??{line:this.index+1,column:1};throw $("Unexpected member in <script>.",h,this.lines[this.index]??"<eof>","Use metadata records followed by <episode> blocks.")}a=!0,s.push(this.parseEpisode(d)),d=Et()}let p=this.requiredMetadata(i,"title",n.source),l=this.requiredMetadata(i,"worldview",n.source),f=this.requiredMetadata(i,"style",n.source),u=xt(t);return{kind:"script",title:p,worldview:l,style:f,...i.get("worldview-raw")!==void 0?{worldviewRaw:i.get("worldview-raw")}:{},...i.get("synopsis")!==void 0?{synopsis:i.get("synopsis")}:{},...i.get("logline")!==void 0?{logline:i.get("logline")}:{},...i.get("theme")!==void 0?{theme:i.get("theme")}:{},...i.has("main-characters")||r.length>0?{mainCharacters:r}:{},episodes:s,source:n.source,...u!==void 0?{extend:u}:{}}}parseEpisode(t){let n=this.takeOpen("episode");Sn(n,["id"]),(t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,"episode");let o=this.parseMetadataAndChildren("episode",["title","synopsis"],"scene",s=>this.parseScene(s,!1)),i={episode_id:n.attrs.get("id"),scenes:o.children};o.values.has("title")&&(i.title=o.values.get("title")),o.values.has("synopsis")&&(i.synopsis=o.values.get("synopsis"));let r=xt(t);return r!==void 0&&(i.extend=r),i}parseScene(t,n){let o=this.takeOpen("scene");Sn(o,n?["id","parent"]:["id"]),(t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,"scene");let i,r,s=[],c=[],a="environment",d;for(;;){if(this.skipBlank(),this.peekClose("scene")){this.takeClose("scene");break}let f=this.peekSemantic();if(f?.tag?.name==="body"&&!f.tag.closing){if(a==="body")throw $("Scene has more than one body.",f.tag.source,"<body>","Keep exactly one <body>.");a="body",d=this.parseBody();continue}if(f?.record===void 0){let m=f?.tag?.source??{line:this.index+1,column:1};throw $("Only scene records and <body> are allowed here.",m,this.lines[this.index]??"<eof>","Use environment, location, cast, prop, then body.")}let u=this.takeRecord();if(u.type==="extensions"||u.type==="extend"||u.type==="aliases"||u.type==="alias"||u.type==="prompt")throw $("Scene prefix modifier must directly precede <scene>.",u.source,u.type,"Move the modifier before the <scene> opening tag.");if(u.type==="environment"){if(a!=="environment"||i!==void 0||u.slots.length>2)throw $("Environment record is out of order or invalid.",u.source,u.slots.join("|"),"Place at most one [environment|space?|time?] first.");i={},u.slots.length>=1&&u.slots[0]!==""&&(i.space=u.slots[0]),u.slots.length>=2&&u.slots[1]!==""&&(i.time=u.slots[1]);continue}if(u.type==="location"){if(a==="cast"||a==="prop"||a==="body"||r!==void 0||u.slots.length>2)throw $("Location record is out of order or invalid.",u.source,u.slots.join("|"),"Place exactly one [location|id?|state?] before cast.");a="location";let m=u.slots[0];m===void 0||m===""?r=null:r=u.slots.length===2?{location_id:m,state_id:u.slots[1]}:{location_id:m};continue}if(u.type==="cast"){if(r===void 0||a==="prop"||a==="body"||u.slots.length<1||u.slots.length>2||!u.slots[0])throw $("Cast record is out of order or invalid.",u.source,u.slots.join("|"),"Place [cast|actor_id|state_id?] after location and before props.");a="cast",s.push(u.slots.length===2?{actor_id:u.slots[0],state_id:u.slots[1]}:{actor_id:u.slots[0]});continue}if(u.type==="prop"){if(r===void 0||a==="body"||u.slots.length<1||u.slots.length>2||!u.slots[0])throw $("Prop record is out of order or invalid.",u.source,u.slots.join("|"),"Place [prop|prop_id|state_id?] after cast and before body.");a="prop",c.push(u.slots.length===2?{prop_id:u.slots[0],state_id:u.slots[1]}:{prop_id:u.slots[0]});continue}throw $("Record is not allowed in a scene header.",u.source,u.type,"Use environment, location, cast, prop, or body records.")}if(r===void 0)throw $("Scene location record is missing.",o.source,`<scene id=${o.attrs.get("id")}>`,"Add [location] or [location|loc_ID|state_ID].");if(d===void 0)throw $("Scene body is missing.",o.source,`<scene id=${o.attrs.get("id")}>`,"Add one <body> block.");let p={scene_id:o.attrs.get("id"),location:r,actors:s,props:c,actions:d};i!==void 0&&(p.environment=i);let l=xt(t);return l!==void 0&&(p.extend=l),p}parseBody(){let t=this.takeOpen("body");Sn(t,[]);let n=[],o=Et();for(;;){if(this.skipBlank(),this.peekClose("body"))return zn(o)&&this.throwDangling(o),this.takeClose("body"),n;let i=this.takeRecord();if(i.type==="extensions"||i.type==="extend"||i.type==="aliases"||i.type==="prompt"||i.type==="alias"){o=this.addModifier(o,i);continue}n.push(uE(i,o)),o=Et()}}parseEpisodeSpan(t){let n=this.takeOpen("episode-span");Sn(n,["from","through"]);let o=this.parseOnlyChildren("episode-span","episode",r=>this.parseEpisode(r)),i=xt(t);return{kind:"episode-span",from:n.attrs.get("from"),through:n.attrs.get("through"),episodes:o,source:n.source,...i!==void 0?{extend:i}:{}}}parseSceneSpan(t){let n=this.takeOpen("scene-span");Sn(n,["parent","from","through"]);let o=this.parseOnlyChildren("scene-span","scene",r=>this.parseScene(r,!1)),i=xt(t);return{kind:"scene-span",parent:n.attrs.get("parent"),from:n.attrs.get("from"),through:n.attrs.get("through"),scenes:o,source:n.source,...i!==void 0?{extend:i}:{}}}parseActionSpan(t){let n=this.takeOpen("action-span");Sn(n,["parent","from","through"]),this.skipBlank();let o=this.parseBody();this.skipBlank(),this.takeClose("action-span");let i=xt(t);return{kind:"action-span",parent:n.attrs.get("parent"),from:Zu(n.attrs.get("from"),n.source,"action-span from",!0),through:Zu(n.attrs.get("through"),n.source,"action-span through",!0),actions:o,source:n.source,...i!==void 0?{extend:i}:{}}}parseMetadataAndChildren(t,n,o,i){let r=new Map,s=[],c=-1,a=!1,d=Et();for(;;){if(this.skipBlank(),this.peekClose(t))return zn(d)&&this.throwDangling(d),this.takeClose(t),{values:r,children:s};let p=this.peekSemantic();if(p?.record!==void 0){let f=this.takeRecord();if(f.type==="extensions"||f.type==="extend"||f.type==="aliases"||f.type==="alias"||f.type==="prompt"){d=this.addModifier(d,f);continue}zn(d)&&this.throwUnsupportedModifiers(d,f.type);let u=n.indexOf(f.type);if(a||u<0||u<c||r.has(f.type)||f.slots.length!==0)throw $(`Metadata record in <${t}> is invalid or out of order.`,f.source,f.type,`Use each of ${n.join(", ")} at most once in canonical order before child blocks.`);c=u,r.set(f.type,f.content);continue}let l=p?.tag;if(l===void 0||l.closing||l.name!==o){let f=l?.source??{line:this.index+1,column:1};throw $(`Unexpected member in <${t}>.`,f,this.lines[this.index]??"<eof>",`Use metadata records followed by <${o}> blocks.`)}a=!0,s.push(i(d)),d=Et()}}parseOnlyChildren(t,n,o){let i=[],r=Et();for(;;){if(this.skipBlank(),this.peekClose(t))return zn(r)&&this.throwDangling(r),this.takeClose(t),i;let s=this.peekSemantic();if(s?.record?.type==="extensions"||s?.record?.type==="extend"){r=this.addModifier(r,this.takeRecord());continue}if(s?.tag===void 0||s.tag.closing||s.tag.name!==n){let c=s?.tag?.source??s?.record?.source??{line:this.index+1,column:1};throw $(`Only <${n}> children are allowed in <${t}>.`,c,this.lines[this.index]??"<eof>",`Add complete <${n}> blocks.`)}i.push(o(r)),r=Et()}}addModifier(t,n){let o={extend:{...t.extend},extendPresent:t.extendPresent,aliases:[...t.aliases],aliasesPresent:t.aliasesPresent,phase:t.phase,...t.prompt!==void 0?{prompt:t.prompt}:{},source:t.source??n.source};if(n.type==="extensions"){if(o.phase!=="extend"||o.extendPresent||n.slots.length!==0||n.content!=="")throw $("Extensions marker is invalid or out of order.",n.source,n.content||"<empty>","Use one [extensions] marker before extension records.");return o.extendPresent=!0,o}if(n.type==="extend"){if(o.phase!=="extend"||n.slots.length!==1||!n.slots[0])throw $("Extend modifier is invalid or out of order.",n.source,n.slots.join("|"),"Place unique [extend|key] records first.");let i=n.slots[0];if(Object.hasOwn(o.extend,i))throw $("Extend key is duplicated.",n.source,i,"Keep one value for each extension key.");let r;try{r=JSON.parse(n.content)}catch{throw $("Extension value is not valid JSON.",n.source,n.content,"Use one canonical JSON value.")}if(!rd(r))throw $("Extension value is not JSON-compatible.",n.source,n.content,"Use string, number, boolean, null, array, or object.");return o.extendPresent=!0,o.extend[i]=sd(r),o}if(n.type==="aliases"){if(o.phase!=="extend"||o.aliasesPresent||n.slots.length!==0||n.content!=="")throw $("Aliases marker is invalid or out of order.",n.source,n.content||"<empty>","Use one [aliases] marker after extensions and before alias records.");return o.phase="alias",o.aliasesPresent=!0,o}if(n.type==="alias"){if(o.phase==="prompt"||n.slots.length!==0||!n.content)throw $("Alias modifier is invalid or out of order.",n.source,n.content||"<empty>","Place non-empty [alias] records after extensions and before prompt.");if(o.phase="alias",o.aliasesPresent=!0,o.aliases.includes(n.content))throw $("Alias is duplicated.",n.source,n.content,"Keep each alias once.");return o.aliases.push(n.content),o}if(n.type==="prompt"){if(o.prompt!==void 0||n.slots.length!==3||n.slots.some(i=>!i))throw $("Prompt modifier is invalid.",n.source,n.slots.join("|"),"Use one [prompt|target|process|contrast] after extensions and aliases.");if(!/^(?:actor:act_|location:loc_|prop:prp_)[A-Za-z0-9_-]+$/.test(n.slots[0]))throw $("Prompt target is invalid.",n.source,n.slots[0],"Use actor:act_ID, location:loc_ID, or prop:prp_ID.");return o.phase="prompt",o.prompt={target:n.slots[0],process:n.slots[1],contrast:n.slots[2]},o}throw $("Unknown prefix modifier.",n.source,n.type,"Use extend, alias, or prompt.")}requiredMetadata(t,n,o){let i=t.get(n);if(i===void 0)throw $(`Script ${n} record is missing.`,o,"<script>",`Add [${n}] in canonical metadata order.`);return i}peekSemantic(){if(this.skipBlank(),this.index>=this.lines.length)return null;let t=this.lines[this.index],n=pE(t,this.index+1);if(n!==null)return{tag:n};if(t.trimStart().startsWith("["))return{record:Bi(t,this.index+1)};let o={line:this.index+1,column:Math.max(1,t.search(/\S/)+1)};throw $("Semantic line is neither a tag nor a bracket record.",o,t,"Use only known tags, bracket records, or blank lines.")}peekTag(){return this.peekSemantic()?.tag??null}takeRecord(){let t=this.peekSemantic();if(t?.record===void 0){let n=t?.tag?.source??{line:this.index+1,column:1};throw $("Expected a bracket record.",n,this.lines[this.index]??"<eof>","Use the record required at this position.")}return this.index+=1,t.record}takeOpen(t){let n=this.peekTag();if(n===null||n.closing||n.name!==t){let o=n?.source??{line:this.index+1,column:1};throw $(`Expected <${t}>.`,o,this.lines[this.index]??"<eof>",`Open <${t}> here.`)}return this.index+=1,n}takeClose(t){let n=this.peekTag();if(n===null||!n.closing||n.name!==t){let o=n?.source??{line:this.index+1,column:1};throw $(`Expected </${t}>.`,o,this.lines[this.index]??"<eof>",`Close the current <${t}> block.`)}return this.index+=1,n}peekClose(t){let n=this.peekTag();return n!==null&&n.closing&&n.name===t}skipBlank(){for(;this.index<this.lines.length&&this.lines[this.index].trim()==="";)this.index+=1}eofError(t){return $(`Unexpected end of file inside <${t}>.`,{line:this.lines.length,column:1},"<eof>",`Add </${t}>.`)}throwDangling(t){throw $("Prefix modifier has no following node.",t.source??{line:this.index+1,column:1},"dangling modifier","Move it directly before a supported node.")}throwUnsupportedModifiers(t,n){throw $("Prefix modifier does not apply to this node.",t.source??{line:this.index+1,column:1},n,"Remove the unsupported modifier or move it before a supported node.")}};function Wu(e){return new ad(e).parse()}function N(e,t,n){throw new x(e,{exitCode:k,errorCode:"AUTHORING_SOURCE_INVALID",data:{actual:[`line ${t}: ${n}`]}})}function ld(e,t){let n=e.trim(),o=/^<\/([a-z-]+)>$/.exec(n);if(o)return{name:o[1],closing:!0,attrs:new Map,line:t};let i=/^<([a-z-]+)(?: ([^>]+))?>$/.exec(n);if(!i)return null;let r=new Map,s=i[2]??"",c=s===""?[]:s.split(" ");c.some(a=>a==="")&&N("Tag attributes need one-space separators.",t,n);for(let a of c){let d=/^([a-z]+)=([A-Za-z0-9_./#:-]+)$/.exec(a);(!d||r.has(d[1]))&&N("Tag attributes are invalid.",t,a),r.set(d[1],d[2])}return{name:i[1],closing:!1,attrs:r,line:t}}function De(e,t,n=[]){let o=new Set([...t,...n]),i=[...e.attrs.keys()].filter(s=>!o.has(s)),r=t.filter(s=>!e.attrs.has(s));(i.length>0||r.length>0)&&N("Tag attributes do not match the canonical grammar.",e.line,[...r.map(s=>`missing:${s}`),...i.map(s=>`unknown:${s}`)].join(","))}var ud=class{lines;index=0;constructor(t){this.lines=t.split(/\r?\n/).map((n,o)=>({raw:n.replace(/^\s+/,""),line:o+1})).filter(n=>n.raw.trim()!=="")}peek(){let t=this.lines[this.index];return t||N("Unexpected end of authoring file.",this.lines.at(-1)?.line??1,"<eof>"),t}take(){let t=this.peek();return this.index++,t}tag(t,n){let o=this.take(),i=ld(o.raw,o.line);return(!i||i.name!==t||i.closing!==n)&&N(`Expected ${n?"</":"<"}${t}>.`,o.line,o.raw),i}record(){let t=this.take();return Bi(t.raw,t.line)}nextTag(){let t=this.peek();return ld(t.raw,t.line)}nextRecord(){let t=this.peek();return t.raw.startsWith("[")?Bi(t.raw,t.line):null}};function fd(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(fd):typeof e=="object"&&Object.values(e).every(fd)}function Wo(e){let t={},n=e.nextRecord();if(n?.type==="extensions"){e.record();let o={},i=null;for(;(n=e.nextRecord())?.type==="extend";){let r=e.record();(r.slots.length!==1||Object.hasOwn(o,r.slots[0]))&&N("extend record is invalid or duplicated.",r.source.line,r.type);let s=r.slots[0];i!==null&&i>=s&&N("extend keys must use ascending canonical order.",r.source.line,s);let c;try{c=JSON.parse(r.content)}catch{N("extend content must be JSON.",r.source.line,r.content)}fd(c)||N("extend value must be JSON-compatible.",r.source.line,r.content),o[s]=c,i=s}t.extend=o}if(n=e.nextRecord(),n?.type==="aliases"){e.record();let o=[];for(;(n=e.nextRecord())?.type==="alias";){let i=e.record();i.slots.length!==0&&N("alias takes no slots.",i.source.line,i.type),i.content===""&&N("alias must not be empty.",i.source.line,i.type),o.includes(i.content)&&N("alias must not be duplicated.",i.source.line,i.content),o.push(i.content)}t.aliases=o}if(n=e.nextRecord(),n?.type==="prompt"){let o=e.record();(o.slots.length!==3||o.slots.some(r=>r===""))&&N("prompt requires non-empty target, process, and contrast.",o.source.line,o.type);let i=o.slots[0];!V("actor",i)&&!V("location",i)&&!V("prop",i)&&N("prompt target must be an asset ID.",o.source.line,i),t.prompt={target:i,process:o.slots[1],contrast:o.slots[2]}}return t}function cd(e,t){return e!=="featured"&&e!=="background"&&N("Importance is invalid.",t,e),e}function fE(e,t){if(e!==void 0)return e!=="\u4E3B\u89D2"&&e!=="\u914D\u89D2"&&N("Role type is invalid.",t,e),e}function hd(e,t){return e==="default"||V("state",e)?e:N("State ID is invalid.",t,e)}function mE(e){let t=e.tag("create",!1);De(t,[]);let n=[],o=new Map,i=null,r=0,s=a=>{if(i===null)return;let d=o.get(i);(!d||d.states.length===0||d.states[0].state_id!=="default")&&N("A new asset must be followed immediately by its default state.",a,i),i=null};for(;e.nextTag()?.name!=="create"||e.nextTag()?.closing!==!0;){let a=Wo(e),d=e.record();if(d.type==="actor"){r>0&&N("Create declarations are not in canonical order.",d.source.line,d.type),s(d.source.line),a.prompt!==void 0&&N("prompt cannot modify an asset.",d.source.line,d.type),(d.slots.length<3||d.slots.length>4||!V("actor",d.slots[0]))&&N("actor declaration is invalid.",d.source.line,d.type);let p=fE(d.slots[3],d.source.line),l={actor_id:d.slots[0],actor_name:d.slots[1],importance:cd(d.slots[2],d.source.line),description:d.content,states:[],...p===void 0?{}:{role_type:p},...a.aliases===void 0?{}:{aliases:a.aliases},...a.extend===void 0?{}:{extend:a.extend}};l.aliases?.includes(l.actor_name)&&N("An alias must differ from the asset name.",d.source.line,l.actor_name),n.push({kind:"actor",value:l}),o.set(l.actor_id,l),i=l.actor_id}else if(d.type==="location"||d.type==="prop"){let p=d.type==="location"?1:2;p<r&&N("Create declarations are not in canonical order.",d.source.line,d.type),r=p,s(d.source.line),a.prompt!==void 0&&N("prompt cannot modify an asset.",d.source.line,d.type);let l=d.type;if((d.slots.length!==3||(l==="location"?!V("location",d.slots[0]):!V("prop",d.slots[0])))&&N(`${l} declaration is invalid.`,d.source.line,d.type),l==="location"){let f=d.slots[0];V("location",f)||N("location ID is invalid.",d.source.line,f);let u={location_id:f,location_name:d.slots[1],importance:cd(d.slots[2],d.source.line),description:d.content,states:[],...a.aliases===void 0?{}:{aliases:a.aliases},...a.extend===void 0?{}:{extend:a.extend}};u.aliases?.includes(u.location_name)&&N("An alias must differ from the asset name.",d.source.line,u.location_name),n.push({kind:l,value:u}),o.set(u.location_id,u),i=u.location_id}else{let f=d.slots[0];V("prop",f)||N("prop ID is invalid.",d.source.line,f);let u={prop_id:f,prop_name:d.slots[1],importance:cd(d.slots[2],d.source.line),description:d.content,states:[],...a.aliases===void 0?{}:{aliases:a.aliases},...a.extend===void 0?{}:{extend:a.extend}};u.aliases?.includes(u.prop_name)&&N("An alias must differ from the asset name.",d.source.line,u.prop_name),n.push({kind:l,value:u}),o.set(u.prop_id,u),i=u.prop_id}}else if(d.type==="state"){(d.slots.length!==3||a.aliases!==void 0||a.prompt!==void 0)&&N("state declaration is invalid.",d.source.line,d.type);let p=d.slots[0],l=o.get(p);l&&i!==p&&N("States for a new asset must immediately follow that asset.",d.source.line,p),l||(s(d.source.line),r=3);let f={state_id:hd(d.slots[1],d.source.line),state_name:d.slots[2],description:d.content,...a.extend===void 0?{}:{extend:a.extend}};l?(l.states.length===0&&f.state_id!=="default"&&N("The first state of a new asset must be default.",d.source.line,f.state_id),l.states.push(f)):n.push({kind:"state",ownerId:p,value:f})}else s(d.source.line),N("Unknown create declaration.",d.source.line,d.type)}s(e.peek().line);let c=e.tag("create",!0);return De(c,[]),n}function gE(e,t){let n=e.indexOf("/"),o=n<0?e:e.slice(0,n);if(V("actor",o))return n<0?{actor_id:o}:{actor_id:o,state_id:hd(e.slice(n+1),t)};let i=e.indexOf(":"),r=i<0?e:e.slice(0,i);return["system","broadcast","offscreen","group"].includes(r)?i<0?{kind:r}:{kind:r,label:e.slice(i+1)}:N("Speaker is invalid.",t,e)}function Xu(e){let t=Wo(e);t.aliases!==void 0&&N("aliases cannot modify an Action.",e.peek().line,"aliases");let n=e.record();return n.type==="act"||n.type==="trans"?((n.slots.length!==1||!V("action",n.slots[0]))&&N("Narrative Action record is invalid.",n.source.line,n.type),{action_id:n.slots[0],type:n.type==="act"?"action":"transition",content:n.content,...t.extend===void 0?{}:{extend:t.extend},...t.prompt===void 0?{}:{transition_prompt:t.prompt}}):n.type!=="dlg"&&n.type!=="think"?N("Unknown Action record.",n.source.line,n.type):((n.slots.length!==2&&n.slots.length!==3||!V("action",n.slots[0]))&&N("Speaking Action record is invalid.",n.source.line,n.type),{action_id:n.slots[0],type:n.type==="dlg"?"dialogue":"inner_thought",speaker:gE(n.slots[1],n.source.line),content:n.content,...n.slots.length===3?{parenthetical:n.slots[2]}:{},...t.extend===void 0?{}:{extend:t.extend},...t.prompt===void 0?{}:{transition_prompt:t.prompt}})}function dd(e,t){e.length===0&&N("Scene reference needs at least one state.",t,"<empty>");let n=e.map(o=>hd(o,t));return new Set(n).size!==n.length&&N("Scene reference repeats a state.",t,n.join(",")),n.sort()}function md(e,t,n,o){De(t,n===void 0?["id","parent"]:["id"]);let i=t.attrs.get("id")??"";V("scene",i)||N("Scene ID is invalid.",t.line,i);let r=t.attrs.get("parent")??n;r!==void 0&&!V("episode",r)&&N("Scene parent must be an Episode ID.",t.line,r);let s,c,a=[],d=[],p=new Set,l=new Set,f=0;for(;e.nextTag()?.name!=="body";){let h=e.record(),g=h.type==="environment"?0:h.type==="location"?1:h.type==="cast"?2:h.type==="prop"?3:-1;g<f&&N("Scene records are not in canonical order.",h.source.line,h.type),f=g,h.type==="environment"?(s!==void 0&&N("Scene environment is duplicated.",h.source.line,h.type),h.slots.length>2&&N("environment has too many slots.",h.source.line,h.type),s={...h.slots[0]===void 0?{}:{space:h.slots[0]},...h.slots[1]===void 0?{}:{time:h.slots[1]}}):h.type==="location"?(c!==void 0&&N("Scene location is duplicated.",h.source.line,h.type),h.slots.length===0?c=null:(V("location",h.slots[0])||N("Location ref ID is invalid.",h.source.line,h.slots[0]),c={location_id:h.slots[0],state_ids:dd(h.slots.slice(1),h.source.line)})):h.type==="cast"?(V("actor",h.slots[0])||N("Cast ref ID is invalid.",h.source.line,h.slots[0]??""),p.has(h.slots[0])&&N("Scene repeats an actor reference.",h.source.line,h.slots[0]),p.add(h.slots[0]),a.push({actor_id:h.slots[0],state_ids:dd(h.slots.slice(1),h.source.line)})):h.type==="prop"?(V("prop",h.slots[0])||N("Prop ref ID is invalid.",h.source.line,h.slots[0]??""),l.has(h.slots[0])&&N("Scene repeats a prop reference.",h.source.line,h.slots[0]),l.add(h.slots[0]),d.push({prop_id:h.slots[0],state_ids:dd(h.slots.slice(1),h.source.line)})):N("Unknown scene header record.",h.source.line,h.type)}c===void 0&&N("Scene must declare location or [location].",e.peek().line,i);let u=e.tag("body",!1);De(u,[]);let m=[];for(;e.nextTag()?.name!=="body"||e.nextTag()?.closing!==!0;)m.push(Xu(e));return De(e.tag("body",!0),[]),De(e.tag("scene",!0),[]),{...r===void 0?{}:{parent:r},value:{scene_id:i,...s===void 0?{}:{environment:s},location:c,actors:a,props:d,actions:m,...o===void 0?{}:{extend:o}}}}function gd(e,t,n){De(t,["id"]);let o=t.attrs.get("id")??"";V("episode",o)||N("Episode ID is invalid.",t.line,o);let i,r,s=[],c=0;for(;e.nextTag()?.name!=="episode"||e.nextTag()?.closing!==!0;){let a=Wo(e);(a.aliases!==void 0||a.prompt!==void 0)&&N("Invalid episode child modifier.",e.peek().line,"modifier");let d=e.nextTag();if(d?.name==="scene"&&!d.closing){c=2,e.take(),s.push(md(e,d,o,a.extend).value);continue}a.extend!==void 0&&N("extend must precede a scene here.",e.peek().line,"extend");let p=e.record(),l=p.type==="title"?0:p.type==="synopsis"?1:-1;l<c&&N("Episode records are not in canonical order.",p.source.line,p.type),c=l,p.type==="title"?(i!==void 0&&N("Episode title is duplicated.",p.source.line,p.type),p.slots.length!==0&&N("Episode title takes no slots.",p.source.line,p.type),i=p.content):p.type==="synopsis"?(r!==void 0&&N("Episode synopsis is duplicated.",p.source.line,p.type),p.slots.length!==0&&N("Episode synopsis takes no slots.",p.source.line,p.type),r=p.content):N("Unknown episode record.",p.source.line,p.type)}return De(e.tag("episode",!0),[]),{episode_id:o,...i===void 0?{}:{title:i},...r===void 0?{}:{synopsis:r},scenes:s,...n===void 0?{}:{extend:n}}}function pd(e,t){let n=e.attrs.get("range")??"",o=n.split("..");return(o.length!==2||!o[0]||!o[1]||!V(t,o[0])||!V(t,o[1]))&&N(`Span range must contain two ${t} IDs.`,e.line,n),[o[0],o[1]]}function hE(e,t,n){De(t,[]);let o,i,r,s,c,a,d,p,l=[],f=0;for(;e.nextTag()?.name!=="script"||e.nextTag()?.closing!==!0;){let u=Wo(e);(u.aliases!==void 0||u.prompt!==void 0)&&N("Invalid script child modifier.",e.peek().line,"modifier");let m=e.nextTag();if(m?.name==="episode"&&!m.closing){f=8,e.take(),l.push(gd(e,m,u.extend));continue}u.extend!==void 0&&N("extend must precede an episode here.",e.peek().line,"extend");let h=e.record(),g=h.type==="title"?0:h.type==="worldview"?1:h.type==="worldview-raw"?2:h.type==="style"?3:h.type==="synopsis"?4:h.type==="logline"?5:h.type==="theme"?6:h.type==="main-characters"||h.type==="main-character"?7:-1;g<f&&N("Script records are not in canonical order.",h.source.line,h.type),f=g,h.type!=="main-character"&&h.slots.length!==0&&N("Script metadata record takes no slots.",h.source.line,h.type),h.type==="title"?(o!==void 0&&N("Script title is duplicated.",h.source.line,h.type),o=h.content):h.type==="worldview"?(i!==void 0&&N("Script worldview is duplicated.",h.source.line,h.type),i=h.content):h.type==="worldview-raw"?(r!==void 0&&N("Script worldview-raw is duplicated.",h.source.line,h.type),r=h.content):h.type==="style"?(s!==void 0&&N("Script style is duplicated.",h.source.line,h.type),s=h.content):h.type==="synopsis"?(c!==void 0&&N("Script synopsis is duplicated.",h.source.line,h.type),c=h.content):h.type==="logline"?(a!==void 0&&N("Script logline is duplicated.",h.source.line,h.type),a=h.content):h.type==="theme"?(d!==void 0&&N("Script theme is duplicated.",h.source.line,h.type),d=h.content):h.type==="main-characters"?(p!==void 0&&N("Script main-characters is duplicated.",h.source.line,h.type),p=[]):h.type==="main-character"&&p!==void 0&&h.slots.length===2&&h.content===""?p.push({name:h.slots[0],role:h.slots[1]}):N("Unknown script record.",h.source.line,h.type)}return De(e.tag("script",!0),[]),(o===void 0||i===void 0||s===void 0)&&N("Script target needs title, worldview, and style.",e.peek().line,"script"),{kind:"script",value:{title:o,worldview:i,style:s,episodes:l,...r===void 0?{}:{worldview_raw:r},...c===void 0?{}:{synopsis:c},...a===void 0?{}:{logline:a},...d===void 0?{}:{theme:d},...p===void 0?{}:{main_characters:p},...n===void 0?{}:{extend:n}}}}function ef(e){let t=new ud(e),n=t.tag("authoring",!1);De(n,["version"]),n.attrs.get("version")!=="1"&&N("authoring version must be 1.",1,n.attrs.get("version")??"<missing>");let o=t.nextTag()?.name==="create"?mE(t):[],i=[];for(;t.nextTag()?.name!=="authoring"||t.nextTag()?.closing!==!0;){let s=Wo(t);(s.aliases!==void 0||s.prompt!==void 0)&&N("Invalid target modifier.",t.peek().line,"modifier");let c=t.take(),a=ld(c.raw,c.line);if((!a||a.closing)&&N("Expected an authoring target.",c.line,c.raw),a.name==="script")i.push(hE(t,a,s.extend));else if(a.name==="episode")i.push({kind:"episode",value:gd(t,a,s.extend)});else if(a.name==="scene"){let d=md(t,a,void 0,s.extend);d.parent||N("Top-level scene needs parent.",c.line,c.raw),i.push({kind:"scene",parent:d.parent,value:d.value})}else if(a.name==="episode-span"){s.extend!==void 0&&N("A span cannot carry node extensions.",c.line,c.raw),De(a,["range"]);let[d,p]=pd(a,"episode"),l=[];for(;t.nextTag()?.name!=="episode-span"||t.nextTag()?.closing!==!0;){let f=Wo(t);(f.aliases!==void 0||f.prompt!==void 0)&&N("Invalid episode child modifier.",t.peek().line,"modifier");let u=t.tag("episode",!1);l.push(gd(t,u,f.extend))}De(t.tag("episode-span",!0),[]),i.push({kind:"episode-span",from:d,through:p,values:l})}else if(a.name==="scene-span"){s.extend!==void 0&&N("A span cannot carry node extensions.",c.line,c.raw),De(a,["parent","range"]);let[d,p]=pd(a,"scene"),l=a.attrs.get("parent")??N("scene-span needs parent.",c.line,c.raw);V("episode",l)||N("scene-span parent must be an Episode ID.",c.line,l);let f=[];for(;t.nextTag()?.name!=="scene-span"||t.nextTag()?.closing!==!0;){let u=Wo(t);(u.aliases!==void 0||u.prompt!==void 0)&&N("Invalid scene child modifier.",t.peek().line,"modifier");let m=t.tag("scene",!1);f.push(md(t,m,l,u.extend).value)}De(t.tag("scene-span",!0),[]),i.push({kind:"scene-span",parent:l,from:d,through:p,values:f})}else if(a.name==="action-span"){s.extend!==void 0&&N("A span cannot carry node extensions.",c.line,c.raw),De(a,["parent","range"]);let[d,p]=pd(a,"action"),l=a.attrs.get("parent")??N("action-span needs parent.",c.line,c.raw);V("scene",l)||N("action-span parent must be a Scene ID.",c.line,l),De(t.tag("body",!1),[]);let f=[];for(;t.nextTag()?.name!=="body"||t.nextTag()?.closing!==!0;)f.push(Xu(t));De(t.tag("body",!0),[]),De(t.tag("action-span",!0),[]),i.push({kind:"action-span",parent:l,from:d,through:p,values:f})}else N("Unknown authoring target.",c.line,a.name)}De(t.tag("authoring",!0),[]),(t.index!==t.lines.length||i.length===0)&&N("Authoring file has trailing content or no targets.",t.peek().line,"<root>");let r=i[0].kind;return i.every(s=>s.kind===r)||N("All targets must have the same kind.",1,r),{declarations:o,targets:i,targetKind:r}}function In(e){if(Array.isArray(e))return e.map(t=>In(t));if(oe(e)){let t={};for(let n of Object.keys(e).sort())t[n]=In(e[n]);return t}return e}function yd(e){if(e.length===0)return[];let t={};for(let i of e){let r=O(i.severity);t[r]=(t[r]??0)+1}let n=Object.entries(t).sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>`${i}: ${r}`),o=e[0];return[n.join("; "),`first: ${o.code} - ${o.summary}`,...o.repair_hint?[`repair: ${o.repair_hint}`]:[]]}function tf(e,t){if(!(t.ok||e!==null&&Rc(Pe(e),t)))throw new x("The proposed document is not a valid or strictly improved Script v4.",{exitCode:k,errorCode:"AUTHORING_VALIDATION_FAILED",data:{actual:t.errors.slice(0,20).map(n=>`${n.path}: ${n.message}`)}})}function Ce(e,t){throw new x(e,{exitCode:k,errorCode:"AUTHORING_APPLY_INVALID",data:{actual:t}})}function _d(e){return{ids:e.map(t=>t.action_id),counts:{episodes:0,scenes:0,actions:e.length}}}function Ji(e){return{ids:e.flatMap(t=>[t.scene_id,...t.actions.map(n=>n.action_id)]),counts:{episodes:0,scenes:e.length,actions:e.reduce((t,n)=>t+n.actions.length,0)}}}function Eo(e){return{ids:e.flatMap(t=>[t.episode_id,...t.scenes.flatMap(n=>[n.scene_id,...n.actions.map(o=>o.action_id)])]),counts:{episodes:e.length,scenes:e.reduce((t,n)=>t+n.scenes.length,0),actions:e.reduce((t,n)=>t+n.scenes.reduce((o,i)=>o+i.actions.length,0),0)}}}function yE(e){return e.kind==="script"?Eo(e.value.episodes):e.kind==="episode"?Eo([e.value]):e.kind==="episode-span"?Eo(e.values):e.kind==="scene"?Ji([e.value]):e.kind==="scene-span"?Ji(e.values):_d(e.values)}function wE(e){return{actors:e.filter(t=>t.kind==="actor").map(t=>structuredClone(t.value)),locations:e.filter(t=>t.kind==="location").map(t=>structuredClone(t.value)),props:e.filter(t=>t.kind==="prop").map(t=>structuredClone(t.value))}}function wd(e,t){return JSON.stringify(In(e))===JSON.stringify(In(t))}function nf(e,t){let n=new Set(e===null?[]:[...e.actors.map(d=>d.actor_id),...e.locations.map(d=>d.location_id),...e.props.map(d=>d.prop_id)]),o=new Set(e===null?[]:[...e.actors.flatMap(d=>d.states.map(p=>`${d.actor_id}/${p.state_id}`)),...e.locations.flatMap(d=>d.states.map(p=>`${d.location_id}/${p.state_id}`)),...e.props.flatMap(d=>d.states.map(p=>`${d.prop_id}/${p.state_id}`))]),i=[],r=[],s=[],c=[],a=d=>{(o.has(d)?c:s).push(d)};for(let d of t){if(d.kind==="state"){n.has(d.ownerId)&&r.push(d.ownerId),a(`${d.ownerId}/${d.value.state_id}`);continue}let p=d.kind==="actor"?d.value.actor_id:d.kind==="location"?d.value.location_id:d.value.prop_id;(n.has(p)?r:i).push(p),d.value.states.forEach(l=>{a(`${p}/${l.state_id}`)})}return{createdAssets:i,existingAssets:[...new Set(r)],createdStates:s,existingStates:c}}function of(e){let t=new Set;for(let n of e.episodes)for(let o of n.scenes)o.location&&t.add(o.location.location_id),o.actors.forEach(i=>t.add(i.actor_id)),o.props.forEach(i=>t.add(i.prop_id)),o.actions.forEach(i=>{i.transition_prompt&&t.add(i.transition_prompt.target)});return[...e.actors.map(n=>n.actor_id),...e.locations.map(n=>n.location_id),...e.props.map(n=>n.prop_id)].filter(n=>!t.has(n))}function rf(e){return[...e.actors.flatMap(t=>[t.actor_id,...t.states.map(n=>`${t.actor_id}/${n.state_id}`)]),...e.locations.flatMap(t=>[t.location_id,...t.states.map(n=>`${t.location_id}/${n.state_id}`)]),...e.props.flatMap(t=>[t.prop_id,...t.states.map(n=>`${t.prop_id}/${n.state_id}`)]),...e.episodes.flatMap(t=>[t.episode_id,...t.scenes.flatMap(n=>[n.scene_id,...n.actions.map(o=>o.action_id)])])]}function sf(e,t){let n=e===null?[]:rf(e),o=rf(t),i=new Set(n),r=new Set(o);return{createdIds:o.filter(s=>!i.has(s)),removedIds:n.filter(s=>!r.has(s)),retainedIds:n.filter(s=>r.has(s))}}function _E(e,t){for(let n of t)if(n.kind==="actor")e.actors.some(o=>o.actor_id===n.value.actor_id)&&Ce("Declaration cannot redefine an existing actor.",[n.value.actor_id]),e.actors.push(structuredClone(n.value));else if(n.kind==="location")e.locations.some(o=>o.location_id===n.value.location_id)&&Ce("Declaration cannot redefine an existing location.",[n.value.location_id]),e.locations.push(structuredClone(n.value));else if(n.kind==="prop")e.props.some(o=>o.prop_id===n.value.prop_id)&&Ce("Declaration cannot redefine an existing prop.",[n.value.prop_id]),e.props.push(structuredClone(n.value));else{let o=e.actors.find(i=>i.actor_id===n.ownerId)??e.locations.find(i=>i.location_id===n.ownerId)??e.props.find(i=>i.prop_id===n.ownerId);o||Ce("State declaration owner was not found.",[n.ownerId]),o.states.some(i=>i.state_id===n.value.state_id)&&Ce("State declaration cannot redefine an existing state.",[`${n.ownerId}/${n.value.state_id}`]),o.states.push(structuredClone(n.value))}}function Wt(e,t,n){let o=e.indexOf(t),i=e.indexOf(n);return(o<0||i<0)&&Ce("Span endpoint was not found.",[t,n]),[Math.min(o,i),Math.max(o,i)]}function EE(e,t){if(t.kind==="script")return[0,0];if(t.kind==="episode"||t.kind==="episode-span"){let o=e.episodes.map(i=>i.episode_id);return t.kind==="episode"?Wt(o,t.value.episode_id,t.value.episode_id):Wt(o,t.from,t.through)}if(t.kind==="scene"||t.kind==="scene-span"){let o=e.episodes.flatMap(i=>i.scenes.map(r=>r.scene_id));return t.kind==="scene"?Wt(o,t.value.scene_id,t.value.scene_id):Wt(o,t.from,t.through)}let n=e.episodes.flatMap(o=>o.scenes.flatMap(i=>i.actions.map(r=>r.action_id)));return Wt(n,t.from,t.through)}function xE(e,t){let n=-1;for(let o of t){let[i,r]=EE(e,o);i<=n&&Ce("Replace targets must follow current document order without overlap.",[pf(o)]),n=r}}function pf(e){return e.kind==="script"?"script":e.kind==="episode"?e.value.episode_id:e.kind==="scene"?e.value.scene_id:`${e.from}..${e.through}`}function af(e,t){if(t.kind==="script")return{...Eo(e.episodes),siblings:0};if(t.kind==="episode"){let r=En(e,t.value.episode_id);return{...Eo(r?[r.episode]:[]),siblings:Math.max(0,e.episodes.length-(r?1:0))}}if(t.kind==="episode-span"){let[r,s]=Wt(e.episodes.map(c=>c.episode_id),t.from,t.through);return{...Eo(e.episodes.slice(r,s+1)),siblings:e.episodes.length-(s-r+1)}}if(t.kind==="scene"){let r=jn(e,t.value.scene_id),s=En(e,t.parent)?.episode;return{...Ji(r?[r.scene]:[]),siblings:r?Math.max(0,r.episode.scenes.length-1):s?.scenes.length??0}}if(t.kind==="scene-span"){let r=En(e,t.parent)?.episode;if(!r)return{...Ji([]),siblings:0};let[s,c]=Wt(r.scenes.map(a=>a.scene_id),t.from,t.through);return{...Ji(r.scenes.slice(s,c+1)),siblings:r.scenes.length-(c-s+1)}}let n=jn(e,t.parent)?.scene;if(!n)return{..._d([]),siblings:0};let[o,i]=Wt(n.actions.map(r=>r.action_id),t.from,t.through);return{..._d(n.actions.slice(o,i+1)),siblings:n.actions.length-(i-o+1)}}function cf(e,t){let n=yE(e),o=new Set(t.ids),i=new Set(n.ids);return{kind:e.kind,address:pf(e),before:t.counts,after:n.counts,retainedIds:t.ids.filter(r=>i.has(r)),createdIds:n.ids.filter(r=>!o.has(r)),removedIds:t.ids.filter(r=>!i.has(r)),untouchedSiblings:t.siblings}}function SE(e,t){if(t.kind==="script"&&Ce("An existing Script v4 is not replaced through a script root.",["script"]),t.kind==="episode"){let n=En(e,t.value.episode_id);n||Ce("Episode replacement target was not found.",[t.value.episode_id]),e.episodes[n.episodeIndex]=structuredClone(t.value)}else if(t.kind==="episode-span"){let[n,o]=Wt(e.episodes.map(i=>i.episode_id),t.from,t.through);t.values.length===0&&Ce("Episode span replacement cannot be empty.",[t.from,t.through]),e.episodes.splice(n,o-n+1,...structuredClone(t.values))}else if(t.kind==="scene"){let n=jn(e,t.value.scene_id);(!n||n.episode.episode_id!==t.parent)&&Ce("Scene replacement target was not found under its parent.",[t.parent,t.value.scene_id]),n.episode.scenes[n.sceneIndex]=structuredClone(t.value)}else if(t.kind==="scene-span"){let n=En(e,t.parent)?.episode;n||Ce("Scene span parent was not found.",[t.parent]);let[o,i]=Wt(n.scenes.map(r=>r.scene_id),t.from,t.through);t.values.length===0&&Ce("Scene span replacement cannot be empty.",[t.from,t.through]),n.scenes.splice(o,i-o+1,...structuredClone(t.values))}else{let n=jn(e,t.parent)?.scene;n||Ce("Action span parent was not found.",[t.parent]);let[o,i]=Wt(n.actions.map(r=>r.action_id),t.from,t.through);t.values.length===0&&Ce("Action span replacement cannot be empty.",[t.from,t.through]),n.actions.splice(o,i-o+1,...structuredClone(t.values))}}function IE(e,t){if(t.kind==="episode")e.episodes.push(structuredClone(t.value));else if(t.kind==="scene"){let n=En(e,t.parent)?.episode;n||Ce("Scene create parent was not found.",[t.parent]),n.scenes.push(structuredClone(t.value))}else Ce("This target kind does not support create against an existing script.",[t.kind])}function df(e){if(e.targets.length!==1||e.targets[0].kind!=="script")return Ce("Script create requires exactly one script target.",[e.targetKind]);if(e.declarations.some(n=>n.kind==="state"))return Ce("Standalone state declarations need an existing owner.",["state"]);let t=e.targets[0];return{version:4,...structuredClone(t.value),...wE(e.declarations)}}function lf(e,t,n){let o;if(e===null)n!=="create"&&Ce("A missing target requires one script create target.",[n,t.targetKind]),o=df(t);else if(n==="create"&&t.targetKind==="script")o=df(t),wd(o,e)||Ce("Script create retry differs from the existing script.",["script"]);else{o=structuredClone(e),n==="replace"&&xE(e,t.targets),_E(o,t.declarations);let r=t.targets.map(a=>af(e,a));if(n==="replace")for(let a of[...t.targets].reverse())SE(o,a);else for(let a of t.targets)IE(o,a);let s=t.targets.map((a,d)=>cf(a,r[d])),c=Pe(o);return tf(e,c),{script:o,changed:!wd(e,o),validation:c,targets:s,declarations:nf(e,t.declarations),retainedOrphanAssets:of(o),identity:sf(e,o)}}let i=Pe(o);return tf(e,i),{script:o,changed:e===null||!wd(e,o),validation:i,declarations:nf(e,t.declarations),retainedOrphanAssets:of(o),identity:sf(e,o),targets:t.targets.map(r=>{let s=e===null?{...Eo([]),siblings:0}:af(e,r);return cf(r,s)})}}function Xo(e,t){throw new x(e,{exitCode:B,errorCode:"AUTHORING_USAGE_INVALID",hint:"Choose exactly one mode and pass a regular authoring source file.",data:{expected:["scriptctl authoring write <file> (--create|--replace) [--apply --plan <digest>]"],actual:t}})}function AE(e){(!e||e==="-")&&Xo("Authoring input must be a named file.",[e||"<missing>"]);let t=uf.resolve(e),n;try{n=Dr.statSync(t)}catch{throw new x("The authoring source file does not exist.",{exitCode:k,errorCode:"AUTHORING_SOURCE_UNAVAILABLE",hint:"Write the complete authoring draft to a file, then rerun the command.",data:{actual:[t]}})}n.isFile()||Xo("Authoring input must be a regular file.",[t]);let o=Dr.readFileSync(t);return{absolutePath:t,bytes:o,text:o.toString("utf-8")}}function kE(e){let t=Rr(e);if(t===null)return{script:null,baseline:"missing",fingerprint:t};let n;try{n=JSON.parse(Dr.readFileSync(e,"utf-8"))}catch(i){throw new x("The local script is not valid JSON.",{exitCode:k,errorCode:"SCRIPT_JSON_INVALID",hint:"Repair the local JSON file, then rerun authoring.",data:{actual:[e,i instanceof Error?i.message:String(i)]}})}let o=Js(n);return{script:o,baseline:Je(o),fingerprint:t}}function bE(e){let t=e.create===!0,n=e.replace===!0;return t===n&&Xo("Choose exactly one authoring mode.",[`create=${t}`,`replace=${n}`]),t?"create":"replace"}function ff(e){return`sha256:${_e(JSON.stringify(e))}`}function OE(e){return e.targets.reduce((t,n)=>({before:{episodes:t.before.episodes+n.before.episodes,scenes:t.before.scenes+n.before.scenes,actions:t.before.actions+n.before.actions},after:{episodes:t.after.episodes+n.after.episodes,scenes:t.after.scenes+n.after.scenes,actions:t.after.actions+n.after.actions}}),{before:{episodes:0,scenes:0,actions:0},after:{episodes:0,scenes:0,actions:0}})}function vE(e){let t=e.targets.map((n,o)=>[`target[${o}]=${n.address}`,`kind=${n.kind}`,`before=${JSON.stringify(n.before)}`,`after=${JSON.stringify(n.after)}`,`retained=${JSON.stringify(n.retainedIds)}`,`created=${JSON.stringify(n.createdIds)}`,`removed=${JSON.stringify(n.removedIds)}`,`untouched_siblings=${n.untouchedSiblings}`].join(" "));t.push(`created_assets=${JSON.stringify(e.declarations.createdAssets)}`,`existing_assets=${JSON.stringify(e.declarations.existingAssets)}`,`created_states=${JSON.stringify(e.declarations.createdStates)}`,`existing_states=${JSON.stringify(e.declarations.existingStates)}`,`retained_orphan_assets=${JSON.stringify(e.retainedOrphanAssets)}`,`validation_ok=${e.validation.ok} errors=${e.validation.errors.length} warnings=${e.validation.warnings.length}`);for(let n of e.validation.errors)t.push(`validation_error=${n.path} ${n.code} ${n.message}`);for(let n of e.validation.warnings)t.push(`validation_warning=${n.path} ${n.code} ${n.message}`);return t}function RE(e,t,n,o,i){let r=ef(t.text),s=i.script===null?null:_n(i.script),c=lf(s,r,n),a=`sha256:${Ed.createHash("sha256").update(t.bytes).digest("hex")}`,d={version:1,sourceDigest:a,mode:n,targetKind:r.targetKind,targets:c.targets.map(g=>g.address),baseline:i.baseline,plan:{targets:c.targets,declarations:c.declarations,retainedOrphanAssets:c.retainedOrphanAssets,identity:c.identity,validation:c.validation}},p=ff(d),l=e.apply===!0,f=O(e.plan).trim();if(l&&!f&&Xo("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!l&&f&&Xo("--plan is only valid together with --apply.",[`plan=${f}`]),l&&f!==p)throw new x("The supplied plan does not match the current source, mode, targets, or script baseline.",{exitCode:k,errorCode:"AUTHORING_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[p],actual:[f]}});l&&c.changed&&(i.script===null?Mr(o,i.fingerprint):Gt(o,i.baseline),Fe(o,c.script));let u=c.targets.map((g,w)=>`target[${w}]=${g.address} kind=${g.kind} before=${JSON.stringify(g.before)} after=${JSON.stringify(g.after)} retained=${JSON.stringify(g.retainedIds)} created=${JSON.stringify(g.createdIds)} removed=${JSON.stringify(g.removedIds)} untouched_siblings=${g.untouchedSiblings}`);return u.push(`created_assets=${JSON.stringify(c.declarations.createdAssets)}`,`existing_assets=${JSON.stringify(c.declarations.existingAssets)}`,`created_states=${JSON.stringify(c.declarations.createdStates)}`,`existing_states=${JSON.stringify(c.declarations.existingStates)}`,`retained_orphan_assets=${JSON.stringify(c.retainedOrphanAssets)}`,`created_ids=${JSON.stringify(c.identity.createdIds)}`,`removed_ids=${JSON.stringify(c.identity.removedIds)}`,`retained_ids=${JSON.stringify(c.identity.retainedIds)}`),[{text:[`${l?"Applied":"Planned"} ${c.targets.length} ${r.targetKind} target(s); validation ${c.validation.ok?"passed":"needs repair"}`,`plan: ${p}`,...u].join(`
132
+ `),data:{op:"write",changed:c.changed,source_path:t.absolutePath,source_digest:a,script_path:o,baseline:i.baseline,script_hash:i.baseline==="missing"?null:i.baseline,plan_digest:p,plan:d.plan,mode:n,target_kind:r.targetKind,targets:c.targets,declarations:c.declarations,retained_orphan_assets:c.retainedOrphanAssets,identity:c.identity,validation:c.validation,applied:l,script_version:4}},G]}function mf(e){let t=Array.isArray(e._args)?e._args:[],n=typeof t[0]=="string"?t[0]:"",o=AE(n),i=bE(e),r=me(e),s=kE(r);if(s.script===null||s.script.version===4)return RE(e,o,i,r,s);let c=Wu(o.text),a=Yu(Tt(s.script),c,i),d=`sha256:${Ed.createHash("sha256").update(o.bytes).digest("hex")}`,p={version:1,sourceDigest:d,mode:i,targetKind:c.targetKind,targets:a.targets.map(w=>w.address),baseline:s.baseline,plan:{targets:a.targets,declarations:a.declarations,retainedOrphanAssets:a.retainedOrphanAssets,validation:a.validation}},l=ff(p),f=e.apply===!0,u=O(e.plan).trim();if(f&&!u&&Xo("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!f&&u&&Xo("--plan is only valid together with --apply.",[`plan=${u}`]),f&&u!==l)throw new x("The supplied plan does not match the current source, mode, targets, or script baseline.",{exitCode:k,errorCode:"AUTHORING_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[l],actual:[u]}});f&&a.changed&&(s.script===null?Mr(r,s.fingerprint):Gt(r,s.baseline),Fe(r,a.script));let m=OE(a);return[{text:[`${f?"Applied":"Planned"} ${a.targets.length} ${c.targetKind} target(s); episodes ${m.before.episodes}\u2192${m.after.episodes}, scenes ${m.before.scenes}\u2192${m.after.scenes}, actions ${m.before.actions}\u2192${m.after.actions}`,`plan: ${l}`,...vE(a)].join(`
133
+ `),data:{op:"write",changed:a.changed,source_path:o.absolutePath,source_digest:d,script_path:r,baseline:s.baseline,script_hash:s.baseline==="missing"?null:s.baseline,plan_digest:l,plan:p.plan,mode:i,target_kind:c.targetKind,targets:a.targets,declarations:a.declarations,counts:m,validation:a.validation,retained_orphan_assets:a.retainedOrphanAssets,applied:f,script_version:3}},G]}function hf(e){return Array.isArray(e.rows)}function ME(e){return e.endsWith(`
134
134
  `)?e:`${e}
135
- `}function ff(e){return Array.isArray(e)?e.map(t=>String(t).replace(/[\r\n]+/g," ")):[]}function vE(e){return e==null?"":(typeof e=="string"?e:JSON.stringify(e)).replace(/\t/g," ").replace(/\r?\n/g," ")}function RE(e){if(!mf(e)||e.rows.length===0||!Array.isArray(e.row_columns))return null;let t=e.row_columns.filter(n=>typeof n=="string");return t.length===0?null:[t.join(" "),...e.rows.map(n=>t.map(o=>vE(n[o])).join(" "))].join(`
136
- `)}function gf(e,t,n,o){if(!(e.text===""&&Object.keys(e.data).length===0)){if(o==="addr"&&mf(e.data)){if(e.data.rows.length===0){process.stdout.write("");return}let i=e.data.rows.map(r=>String(r.addr??""));if(i.every(r=>r.length>0)){process.stdout.write(i.join(`
135
+ `}function gf(e){return Array.isArray(e)?e.map(t=>String(t).replace(/[\r\n]+/g," ")):[]}function NE(e){return e==null?"":(typeof e=="string"?e:JSON.stringify(e)).replace(/\t/g," ").replace(/\r?\n/g," ")}function LE(e){if(!hf(e)||e.rows.length===0||!Array.isArray(e.row_columns))return null;let t=e.row_columns.filter(n=>typeof n=="string");return t.length===0?null:[t.join(" "),...e.rows.map(n=>t.map(o=>NE(n[o])).join(" "))].join(`
136
+ `)}function yf(e,t,n,o){if(!(e.text===""&&Object.keys(e.data).length===0)){if(o==="addr"&&hf(e.data)){if(e.data.rows.length===0){process.stdout.write("");return}let i=e.data.rows.map(r=>String(r.addr??""));if(i.every(r=>r.length>0)){process.stdout.write(i.join(`
137
137
  `)+`
138
- `);return}}if(n){let i={ok:t===B,exit_code:t,...e.data};i.ok=t===B,i.exit_code=t,process.stdout.write(JSON.stringify(i,null,2)+`
139
- `)}else process.stdout.write(OE(RE(e.data)??e.text))}}function $r(e,t){if(t){let n={ok:!1,exit_code:e.exitCode,error_code:e.errorCode,message:e.message,...e.hint?{hint:e.hint}:{},...e.data};n.ok=!1,n.exit_code=e.exitCode,n.error_code=e.errorCode,n.message=e.message,e.hint&&(n.hint=e.hint),process.stdout.write(JSON.stringify(n,null,2)+`
140
- `)}else{let n=ff(e.data.actual),o=ff(e.data.expected),r=[`error: ${n.length>0?`${e.message.replace(/\.$/,"")}: ${n[0]}`:e.message}`];n.length>1&&r.push(`actual: ${n.slice(1).join("; ")}`),o.length>0&&r.push(`expected: ${o.join("; ")}`),e.hint&&r.push(e.hint),process.stderr.write(`${r.join(`
138
+ `);return}}if(n){let i={ok:t===G,exit_code:t,...e.data};i.ok=t===G,i.exit_code=t,process.stdout.write(JSON.stringify(i,null,2)+`
139
+ `)}else process.stdout.write(ME(LE(e.data)??e.text))}}function Gr(e,t){if(t){let n={ok:!1,exit_code:e.exitCode,error_code:e.errorCode,message:e.message,...e.hint?{hint:e.hint}:{},...e.data};n.ok=!1,n.exit_code=e.exitCode,n.error_code=e.errorCode,n.message=e.message,e.hint&&(n.hint=e.hint),process.stdout.write(JSON.stringify(n,null,2)+`
140
+ `)}else{let n=gf(e.data.actual),o=gf(e.data.expected),r=[`error: ${n.length>0?`${e.message.replace(/\.$/,"")}: ${n[0]}`:e.message}`];n.length>1&&r.push(`actual: ${n.slice(1).join("; ")}`),o.length>0&&r.push(`expected: ${o.join("; ")}`),e.hint&&r.push(e.hint),process.stderr.write(`${r.join(`
141
141
  `)}
142
- `)}return e.exitCode}var _d=new WeakMap;function ME(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function NE(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[ME(t),n]))}function LE(e){let t=[],n=e;for(;n;)t.unshift(n),n=n.parent;return Object.assign({},...t.map(o=>o.opts()))}function H(e,t){return async(...n)=>{let o=n[n.length-1],i=n.slice(0,-2).filter(d=>d!==void 0),r=NE(LE(o));i.length>0&&(r._args=i),t.jsonMode=!!r.json,t.format=typeof r.format=="string"?r.format:void 0;let s=async()=>e(r),[c,a]=_d.get(o)==="write"?await Ts(ge(r),s):await s();gf(c,a,t.jsonMode,t.format),t.exitCode=a}}function Me(e,t){return e.registeredArguments.forEach((n,o)=>{n.description=t[o]??""}),e}function te(e,t="write"){return _d.set(e,t),e.option("-p, --script-path <path>","Script JSON file (default: ./workspace/script.json)")}function Ed(e){return _d.set(e,"write"),e.option("-p, --script-path <path>","Local script JSON file (default: ./workspace/script.json)").option("--project-group-no <no>","Remote project group number")}function hf(e,t){let n=e.command("authoring").description("Structured screenplay compilation and atomic application transactions"),o=te(n.command("write <file>")).description("Plan or apply a complete structured authoring document").option("--create","Create the selected target").option("--replace","Replace the selected target").option("--apply","Apply the exact plan").option("--plan <digest>","Exact plan digest to apply").action(H(uf,t));Me(o,["Structured .scriptctl file"]);let i=te(n.command("compose <file>")).description("Compile a readable scene JSON draft with generated identities and timing").option("--apply","Apply the exact plan").option("--plan <digest>","Exact plan digest to apply").action(H(Iu,t));Me(i,["Readable scene JSON file"]);let r=n.command("export").description("Export complete structured content, including identities and extensions"),s=["script","episodes","episode-spans","scenes","scene-spans","action-spans"];for(let c of s){let a=te(r.command(c),"read").description(`Export structured ${c}`).requiredOption("-o, --output <file>","Destination .scriptctl file");c!=="script"&&a.requiredOption("-i, --in <selector>","Formal ID or @ep:N selector / inclusive range"),a.action(H(d=>Tu(c,d),t))}}import*as qs from"node:fs";import*as Od from"node:path";import*as Id from"node:fs";import*as Ji from"node:path";import{fileURLToPath as UE}from"node:url";var Sd="@lingjingai/scriptctl",xd="";function Ad(){if(xd)return xd;let e=Ji.dirname(UE(import.meta.url));for(;;){try{let n=Id.readFileSync(Ji.join(e,"package.json"),"utf-8");if(JSON.parse(n).name===Sd)return xd=e,e}catch{}let t=Ji.dirname(e);if(t===e)throw new Error(`${Sd} package root not found`);e=t}}function ji(){let e=Id.readFileSync(Ji.join(Ad(),"package.json"),"utf-8"),t=JSON.parse(e).version;if(typeof t!="string")throw new Error(`${Sd} package.json has no string version`);return t}var yf=/^\d+\.\d+\.\d+$/,PE="unreleased";function wf(){return Od.join(Ad(),"changes")}function CE(){return ji()}function Dr(e){if(!yf.test(e))throw new S("Version must use x.y.z.",{exitCode:J,errorCode:"CHANGELOG_VERSION_INVALID",hint:"Pass a released version such as `scriptctl changelog 0.25.10`.",data:{expected:["x.y.z"],actual:[e||"<empty>"]}});let[t,n,o]=e.split(".").map(i=>Number(i));return[t,n,o]}function bd(e,t){let n=Dr(e),o=Dr(t);for(let i=0;i<3;i++)if(n[i]!==o[i])return n[i]-o[i];return 0}function TE(){let e=wf();return qs.readdirSync(e).filter(t=>t.endsWith(".md")).map(t=>t.slice(0,-3)).filter(t=>yf.test(t)).sort(bd)}function Ys(e){return qs.readFileSync(Od.join(wf(),`${e}.md`),"utf-8").trimEnd()}function kd(e,t){return new S(`No changelog entry exists for ${e}.`,{exitCode:k,errorCode:"CHANGELOG_VERSION_NOT_FOUND",hint:t.length>0?`Available versions: ${t.join(", ")}`:"Add changes/<version>.md first.",data:{expected:["existing changelog version"],actual:[e]}})}function VE(e,t){return new S(`No released changelog entries found after ${e} through ${t}.`,{exitCode:k,errorCode:"CHANGELOG_RANGE_EMPTY",hint:"Choose a wider range or run `scriptctl changelog <version>` for a known release.",data:{expected:["a version range containing released changelog entries"],actual:[`--from ${e}`,`--to ${t}`]}})}function $E(e){return e.map(Ys).join(`
142
+ `)}return e.exitCode}var xd=new WeakMap;function UE(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function PE(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[UE(t),n]))}function CE(e){let t=[],n=e;for(;n;)t.unshift(n),n=n.parent;return Object.assign({},...t.map(o=>o.opts()))}function H(e,t){return async(...n)=>{let o=n[n.length-1],i=n.slice(0,-2).filter(d=>d!==void 0),r=PE(CE(o));i.length>0&&(r._args=i),t.jsonMode=!!r.json,t.format=typeof r.format=="string"?r.format:void 0;let s=async()=>e(r),[c,a]=xd.get(o)==="write"?await Vs(me(r),s):await s();yf(c,a,t.jsonMode,t.format),t.exitCode=a}}function Me(e,t){return e.registeredArguments.forEach((n,o)=>{n.description=t[o]??""}),e}function ee(e,t="write"){return xd.set(e,t),e.option("-p, --script-path <path>","Script JSON file (default: ./workspace/script.json)")}function Sd(e){return xd.set(e,"write"),e.option("-p, --script-path <path>","Local script JSON file (default: ./workspace/script.json)").option("--project-group-no <no>","Remote project group number")}function wf(e,t){let n=e.command("authoring").description("Structured screenplay compilation and atomic application transactions"),o=ee(n.command("write <file>")).description("Plan or apply a complete structured authoring document").option("--create","Create the selected target").option("--replace","Replace the selected target").option("--apply","Apply the exact plan").option("--plan <digest>","Exact plan digest to apply").action(H(mf,t));Me(o,["Structured .scriptctl file"]);let i=ee(n.command("compose <file>")).description("Compile a readable scene JSON draft with generated identities and timing").option("--apply","Apply the exact plan").option("--plan <digest>","Exact plan digest to apply").action(H(ku,t));Me(i,["Readable scene JSON file"]);let r=n.command("export").description("Export complete structured content, including identities and extensions"),s=["script","episodes","episode-spans","scenes","scene-spans","action-spans"];for(let c of s){let a=ee(r.command(c),"read").description(`Export structured ${c}`).requiredOption("-o, --output <file>","Destination .scriptctl file");c!=="script"&&a.requiredOption("-i, --in <selector>","Formal ID or @ep:N selector / inclusive range"),a.action(H(d=>$u(c,d),t))}}import*as Zs from"node:fs";import*as Rd from"node:path";import*as kd from"node:fs";import*as Ki from"node:path";import{fileURLToPath as TE}from"node:url";var Ad="@lingjingai/scriptctl",Id="";function bd(){if(Id)return Id;let e=Ki.dirname(TE(import.meta.url));for(;;){try{let n=kd.readFileSync(Ki.join(e,"package.json"),"utf-8");if(JSON.parse(n).name===Ad)return Id=e,e}catch{}let t=Ki.dirname(e);if(t===e)throw new Error(`${Ad} package root not found`);e=t}}function ji(){let e=kd.readFileSync(Ki.join(bd(),"package.json"),"utf-8"),t=JSON.parse(e).version;if(typeof t!="string")throw new Error(`${Ad} package.json has no string version`);return t}var _f=/^\d+\.\d+\.\d+$/,VE="unreleased";function Ef(){return Rd.join(bd(),"changes")}function $E(){return ji()}function Br(e){if(!_f.test(e))throw new x("Version must use x.y.z.",{exitCode:B,errorCode:"CHANGELOG_VERSION_INVALID",hint:"Pass a released version such as `scriptctl changelog 0.25.10`.",data:{expected:["x.y.z"],actual:[e||"<empty>"]}});let[t,n,o]=e.split(".").map(i=>Number(i));return[t,n,o]}function vd(e,t){let n=Br(e),o=Br(t);for(let i=0;i<3;i++)if(n[i]!==o[i])return n[i]-o[i];return 0}function DE(){let e=Ef();return Zs.readdirSync(e).filter(t=>t.endsWith(".md")).map(t=>t.slice(0,-3)).filter(t=>_f.test(t)).sort(vd)}function qs(e){return Zs.readFileSync(Rd.join(Ef(),`${e}.md`),"utf-8").trimEnd()}function Od(e,t){return new x(`No changelog entry exists for ${e}.`,{exitCode:k,errorCode:"CHANGELOG_VERSION_NOT_FOUND",hint:t.length>0?`Available versions: ${t.join(", ")}`:"Add changes/<version>.md first.",data:{expected:["existing changelog version"],actual:[e]}})}function GE(e,t){return new x(`No released changelog entries found after ${e} through ${t}.`,{exitCode:k,errorCode:"CHANGELOG_RANGE_EMPTY",hint:"Choose a wider range or run `scriptctl changelog <version>` for a known release.",data:{expected:["a version range containing released changelog entries"],actual:[`--from ${e}`,`--to ${t}`]}})}function BE(e){return e.map(qs).join(`
143
143
 
144
- `)}function _f(e){let t=e._args??[],n=t[0]?.trim()??"",o=String(e.from??"").trim(),i=String(e.to??"").trim(),r=!!e.unreleased;if(t.length>1)throw new S("changelog accepts at most one version argument.",{exitCode:J,errorCode:"CHANGELOG_TOO_MANY_ARGS",hint:"Pass a single version, or use --from/--to for a range.",data:{expected:["scriptctl changelog [version] [--from X] [--to Y] [--unreleased]"],actual:[t.join(" ")]}});if(r&&(n||o||i))throw new S("--unreleased cannot combine with version, --from, or --to.",{exitCode:J,errorCode:"CHANGELOG_SELECTOR_CONFLICT",hint:"Run `scriptctl changelog --unreleased` by itself.",data:{expected:["either --unreleased, a version, or a --from/--to range"],actual:["--unreleased with another selector"]}});if(n&&(o||i))throw new S("A version argument cannot combine with --from or --to.",{exitCode:J,errorCode:"CHANGELOG_SELECTOR_CONFLICT",hint:"Run `scriptctl changelog 0.25.10` or `scriptctl changelog --from 0.25.8 --to 0.25.10`.",data:{expected:["either a version argument, or --from/--to"],actual:[n,o?`--from ${o}`:"",i?`--to ${i}`:""].filter(Boolean)}});if(r){let d=Ys(PE);return[{text:d,data:{content:d,versions:[],unreleased:!0}},B]}let s=TE(),c=CE();if(n){if(Dr(n),!s.includes(n))throw kd(n,s);let d=Ys(n);return[{text:d,data:{content:d,versions:[n],unreleased:!1}},B]}if(o||i){if(!o)throw new S("--from is required for range queries.",{exitCode:J,errorCode:"CHANGELOG_FROM_MISSING",hint:"Run `scriptctl changelog --from 0.25.8 --to 0.25.10`.",data:{expected:["--from <x.y.z>"],actual:[i?`--to ${i}`:"<missing>"]}});Dr(o);let d=i||c;if(Dr(d),!s.includes(d))throw kd(d,s);let p=s.filter(f=>bd(f,o)>0&&bd(f,d)<=0);if(p.length===0)throw VE(o,d);let l=$E(p);return[{text:l,data:{content:l,versions:p,from:o,to:d,unreleased:!1}},B]}if(!s.includes(c))throw kd(c,s);let a=Ys(c);return[{text:a,data:{content:a,versions:[c],unreleased:!1}},B]}import*as Bt from"node:fs";import*as ii from"node:path";import{createRequire as Bx}from"node:module";import*as Hn from"node:fs";import*as Eo from"node:path";import*as xf from"node:os";import{fileURLToPath as DE}from"node:url";function Ef(e){return e.startsWith("~")?Eo.join(xf.homedir(),e.slice(1)):e}function GE(e){let t=Hn.readFileSync(e,"utf-8");for(let n of t.split(/\r?\n/)){let o=n.trim();if(!o||o.startsWith("#"))continue;o.startsWith("export ")&&(o=o.slice(7).trim());let i=o.indexOf("=");if(i<0)continue;let r=o.slice(0,i).trim(),s=o.slice(i+1).trim();s.length>=2&&s[0]===s[s.length-1]&&(s[0]==="'"||s[0]==='"')&&(s=s.slice(1,-1)),r&&s&&!process.env[r]&&(process.env[r]=s)}}function vd(){let e=[],t=(process.env.SCRIPTCTL_ENV_FILE??"").trim();t&&e.push(Ef(t));let n=(process.env.SCRIPTCTL_SKILL_DIR??"").trim();n&&e.push(Eo.join(Ef(n),".env"));let o;try{o=DE(import.meta.url)}catch{o=process.cwd()}let i=Eo.resolve(o),r=new Set;for(;;){let s=Eo.dirname(i);if(s===i||r.has(s))break;r.add(s),e.push(Eo.join(s,".env")),i=s}return e}function Sf(){let e=process.env.SCRIPTCTL_NO_DOTENV;if(e==="1"||e==="true"||e==="True")return;let t=new Set;for(let n of vd()){let o;try{o=Hn.existsSync(n)?Hn.realpathSync(n):n}catch{o=n}t.has(o)||!Hn.existsSync(n)||!Hn.statSync(n).isFile()||(t.add(o),GE(n))}}var me=class extends Error{status;code;payload;configMissing;constructor(t,n={}){super(t),this.name="ScriptOutputApiError",this.status=n.status??null,this.code=n.code??null,this.payload=n.payload,this.configMissing=n.configMissing??null}};async function Rd(e,t){if(e.updateEpisodeCount)try{await e.updateEpisodeCount(t)}catch{}}function If(e){let t=!!e?.remote,n=!!e?.local;if(t&&n)return{mode:null,conflict:!0};if(t)return{mode:"remote",conflict:!1};if(n)return{mode:"local",conflict:!1};let o=(process.env.SCRIPTCTL_OUTPUT_MODE??"").trim().toLowerCase();if(o==="local"||o==="remote")return{mode:o,conflict:!1};if(o!=="")return{mode:null,conflict:!1};let i=typeof e?.projectGroupNo=="string"?e.projectGroupNo.trim():"",r=(process.env.SANDBOX_PROJECT_GROUP_NO??"").trim();return i!==""||r!==""?{mode:"remote",conflict:!1}:{mode:null,conflict:!1}}import*as Jr from"node:fs";import*as kf from"node:os";import*as Gr from"node:path";import{parseDocument as BE}from"yaml";function ae(e,t,n){return{id:e,mode:t,version:"1",maxOutputTokens:n,defaultProfile:"default"}}var An={"direct.episode-titles":ae("direct.episode-titles","tool",4096),"direct.batch-extract":ae("direct.batch-extract","text",16e3),"direct.episode-synopsis":ae("direct.episode-synopsis","tool",2048),"direct.synopsis-reduction":ae("direct.synopsis-reduction","tool",4096),"direct.script-synopsis":ae("direct.script-synopsis","tool",2048),"direct.asset-grouping":ae("direct.asset-grouping","text",8e3),"direct.asset-curation":ae("direct.asset-curation","text",2e4),"direct.asset-curation-audit":ae("direct.asset-curation-audit","text",2e4),"direct.location-canonicalization":ae("direct.location-canonicalization","text",2e4),"direct.state-curation":ae("direct.state-curation","text",2e4),"direct.state-binding":ae("direct.state-binding","tool",16e3),"metadata.global":ae("metadata.global","text",16e3),"metadata.descriptions":ae("metadata.descriptions","text",16e3),"synopsis.chunk":ae("synopsis.chunk","text",4096),"synopsis.episode":ae("synopsis.episode","text",4096),"synopsis.arc":ae("synopsis.arc","text",16e3),"synopsis.script-overview":ae("synopsis.script-overview","text",16e3),"ingest.body-start":ae("ingest.body-start","text",16e3),"ingest.arc-summary":ae("ingest.arc-summary","text",4096),"ingest.text-normalize":ae("ingest.text-normalize","text",32e3),"ingest.episode-assets":ae("ingest.episode-assets","tool",32e3),"ingest.name-fix":ae("ingest.name-fix","tool",16e3),"ingest.mention-resolve":ae("ingest.mention-resolve","text",8e3),"ingest.asset-extract":ae("ingest.asset-extract","text",8e3),"ingest.asset-curate":ae("ingest.asset-curate","text",32e3),"ingest.asset-recall":ae("ingest.asset-recall","text",65536),"ingest.asset-refine":ae("ingest.asset-refine","text",32e3),"ingest.state-reconcile":ae("ingest.state-reconcile","text",32e3),"ingest.asset-audit":ae("ingest.asset-audit","tool",32e3),"ingest.speaker-audit":ae("ingest.speaker-audit","tool",16e3),"ingest.comic-serial":{id:"ingest.comic-serial",mode:"document",version:"1",defaultProfile:"default"},"ingest.video-serial":ae("ingest.video-serial","video",65536)},Af=Object.keys(An).filter(Md);function Md(e){return Object.hasOwn(An,e)}var JE=new Set(["protocol","baseUrl","apiKey","timeoutMs","maxAttempts","videoResponseSchemaField","videoUploadMode","documentResponseSchemaField","documentUploadMode"]),jE=new Set(["provider","model","thinking","reasoning","temperature","fallbacks"]),KE=new Set(["env"]),zE=new Set(["budgetTokens"]);function Oe(e,t=[]){return new S(e,{exitCode:k,errorCode:"LLM_CONFIG_INVALID",hint:"Fix the selected LLM configuration or environment and rerun `scriptctl doctor`.",data:{expected:["valid scriptctl LLM YAML configuration"],actual:t}})}function Ud(e,t){let n;try{n=new URL(e)}catch{throw Oe(`${t} must be an absolute URL.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Oe(`${t} must use http or https.`);return n.toString().replace(/\/$/,"")}function Pd(e,t="provider base URL"){return Ud(e,t)}function HE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xo(e,t){if(!HE(e))throw Oe(`${t} must be a mapping.`,[`${t}: ${typeof e}`]);return e}function So(e,t){if(typeof e!="string"||!e.trim())throw Oe(`${t} must be a non-empty string.`);return e.trim()}function Ld(e,t,n,o){if(!Number.isInteger(e)||typeof e!="number"||e<n||o!==void 0&&e>o)throw Oe(`${t} must be an integer in ${o===void 0?`[${n}, +\u221E)`:`[${n}, ${o}]`}.`);return e}function Br(e,t,n){let o=Object.keys(e).filter(i=>!t.has(i));if(o.length>0)throw Oe(`${n} contains unknown fields.`,o)}function FE(e,t){let n=xo(t,`providers.${e}`);Br(n,JE,`providers.${e}`);let o=So(n.protocol,`providers.${e}.protocol`);if(o!=="anthropic"&&o!=="openai-compatible"&&o!=="google-gemini"&&o!=="google-vertex")throw Oe(`providers.${e}.protocol is unsupported.`,[o]);let i=n.baseUrl===void 0&&o!=="openai-compatible"?null:Ud(So(n.baseUrl,`providers.${e}.baseUrl`),`providers.${e}.baseUrl`),r="";if(o!=="google-vertex"){let c=xo(n.apiKey,`providers.${e}.apiKey`);if(Br(c,KE,`providers.${e}.apiKey`),r=So(c.env,`providers.${e}.apiKey.env`),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw Oe(`providers.${e}.apiKey.env must be an environment variable name.`)}let s={protocol:o,baseUrl:i,apiKeyEnv:r,timeoutMs:Ld(n.timeoutMs,`providers.${e}.timeoutMs`,1),maxAttempts:Ld(n.maxAttempts,`providers.${e}.maxAttempts`,1,6)};for(let c of["videoResponseSchemaField","documentResponseSchemaField"]){let a=n[c];if(a!==void 0){if(o!=="google-gemini"&&o!=="google-vertex")throw Oe(`providers.${e}.${c} requires a Gemini ${c.startsWith("video")?"video":"document"} provider.`);if(a!=="responseJsonSchema"&&a!=="responseSchema")throw Oe(`providers.${e}.${c} must be responseJsonSchema or responseSchema.`);s[c]=a}}for(let c of["videoUploadMode","documentUploadMode"]){let a=n[c];if(a!==void 0){if(o!=="google-gemini"&&o!=="google-vertex")throw Oe(`providers.${e}.${c} requires a Gemini ${c.startsWith("video")?"video":"document"} provider.`);if(a!=="file-api"&&a!=="base64")throw Oe(`providers.${e}.${c} must be file-api or base64.`);s[c]=a}}return s}function QE(e,t,n){let o=xo(t,`models.${e}`);Br(o,jE,`models.${e}`);let i=So(o.provider,`models.${e}.provider`),r=n[i];if(!r)throw Oe(`models.${e} references an unknown provider.`,[i]);let s={provider:i,model:So(o.model,`models.${e}.model`)};if(o.reasoning!==void 0&&(s.reasoning=So(o.reasoning,`models.${e}.reasoning`)),o.fallbacks!==void 0){let c=o.fallbacks;if(!Array.isArray(c))throw Oe(`models.${e}.fallbacks must be a list of model profiles.`);s.fallbacks=c.map((a,d)=>So(a,`models.${e}.fallbacks[${d}]`))}if(o.temperature!==void 0){let c=o.temperature;if(typeof c!="number"||!Number.isFinite(c)||c<0)throw Oe(`models.${e}.temperature must be a number \u2265 0.`);s.temperature=c}if(o.thinking!==void 0){if(r.protocol!=="anthropic")throw Oe(`models.${e}.thinking is only valid for anthropic providers.`);let c=xo(o.thinking,`models.${e}.thinking`);Br(c,zE,`models.${e}.thinking`),s.thinkingBudgetTokens=Ld(c.budgetTokens,`models.${e}.thinking.budgetTokens`,1024)}return s}function YE(e,t){let n=xo(e,"config");if(Br(n,new Set(["version","providers","models","tasks"]),"config"),n.version!==1)throw Oe("config.version must be 1.");let o=xo(n.providers,"providers"),i={};for(let[a,d]of Object.entries(o))i[a]=FE(a,d);let r=xo(n.models,"models"),s={};for(let[a,d]of Object.entries(r))s[a]=QE(a,d,i);if(!s.default)throw Oe("models.default is required.");for(let[a,d]of Object.entries(s))for(let p of d.fallbacks??[])if(!s[p]||p===a)throw Oe(`models.${a}.fallbacks references an unknown or the same profile.`,[p]);let c={};if(n.tasks!==void 0){let a=xo(n.tasks,"tasks");for(let[d,p]of Object.entries(a)){if(!Md(d))throw Oe("tasks contains an unknown task id.",[d]);let l=So(p,`tasks.${d}`);if(!s[l])throw Oe(`tasks.${d} references an unknown model profile.`,[l]);c[d]=l}}return{version:1,providers:i,models:s,tasks:c,source:"file",sourcePath:t}}var ei={version:1,providers:{gw:{protocol:"openai-compatible",baseUrl:null,apiKeyEnv:"PROJECT_LITELLM_GATEWAY_API_KEY",timeoutMs:3e5,maxAttempts:3},"gw-anthropic":{protocol:"anthropic",baseUrl:null,apiKeyEnv:"PROJECT_LITELLM_GATEWAY_API_KEY",timeoutMs:3e5,maxAttempts:3},"google-gemini":{protocol:"google-vertex",baseUrl:null,apiKeyEnv:"",timeoutMs:6e5,maxAttempts:3},nnyyai:{protocol:"google-gemini",baseUrl:"https://api.nnyyai.com",apiKeyEnv:"NNYYAI_API_KEY",timeoutMs:6e5,maxAttempts:3,videoResponseSchemaField:"responseSchema",videoUploadMode:"base64",documentResponseSchemaField:"responseSchema",documentUploadMode:"base64"}},models:{default:{provider:"gw",model:"deepseek-v4-flash-packy",temperature:0},synopsis:{provider:"gw",model:"deepseek-v4.1-flash-huoshan",temperature:0},"ingest-low":{provider:"gw",model:"deepseek-v4-flash-packy",temperature:0},"ingest-normalize":{provider:"gw",model:"claude-sonnet-4-6-aihubmix",temperature:0},"ingest-video":{provider:"nnyyai",model:"gemini-3.8-flash"},"ingest-comic":{provider:"nnyyai",model:"gemini-3.8-flash"},"review-text":{provider:"google-gemini",model:"gemini-3.8-flash",temperature:0},"review-comic":{provider:"nnyyai",model:"gemini-3.8-flash",temperature:0},"review-agent":{provider:"google-gemini",model:"gemini-3.8-flash",temperature:0},reskin:{provider:"google-gemini",model:"gemini-3.8-flash"},"reskin-claude":{provider:"gw-anthropic",model:"claude-opus-5-5-nnyy-offical"}},tasks:{"synopsis.chunk":"synopsis","synopsis.episode":"synopsis","synopsis.arc":"synopsis","synopsis.script-overview":"synopsis","ingest.body-start":"ingest-low","ingest.arc-summary":"ingest-low","ingest.text-normalize":"ingest-low","ingest.mention-resolve":"ingest-low","ingest.asset-recall":"ingest-low","ingest.asset-audit":"ingest-normalize","ingest.episode-assets":"ingest-normalize","ingest.name-fix":"ingest-normalize","ingest.video-serial":"ingest-video","ingest.comic-serial":"ingest-comic"},source:"builtin",sourcePath:null};function qE(){let e=(process.env.PROJECT_LITELLM_GATEWAY_BASE_URL??"").trim(),t=e?Ud(e,"PROJECT_LITELLM_GATEWAY_BASE_URL"):null;return{...ei,providers:{gw:{...ei.providers.gw,baseUrl:t},"gw-anthropic":{...ei.providers["gw-anthropic"],baseUrl:t?t.replace(/\/v1\/?$/,""):null},"google-gemini":{...ei.providers["google-gemini"]},nnyyai:{...ei.providers.nnyyai}},models:{...ei.models},tasks:{...ei.tasks}}}function ZE(){let e=(process.env.XDG_CONFIG_HOME??"").trim();return e?Gr.join(e,"scriptctl","llm.yaml"):Gr.join(kf.homedir(),".config","scriptctl","llm.yaml")}function Nd(e){if(!Jr.existsSync(e))throw Oe("LLM configuration file does not exist.",[e]);let t=BE(Jr.readFileSync(e,"utf-8"),{uniqueKeys:!0});if(t.errors.length>0)throw Oe("LLM configuration YAML is invalid.",t.errors.map(o=>o.message));let n=t.toJS();return YE(n,Gr.resolve(e))}function Io(e){let t=(e??"").trim();if(t)return Nd(t);let n=(process.env.SCRIPTCTL_LLM_CONFIG??"").trim();if(n)return Nd(n);let o=ZE();return Jr.existsSync(o)?Nd(o):qE()}import*as Df from"node:crypto";import*as Gf from"node:fs";import ex,{APIConnectionError as tx,APIConnectionTimeoutError as nx,APIError as ox,APIUserAbortError as ix}from"@anthropic-ai/sdk";var Cd=1e8;function WE(e){switch(e){case"auth":return{failure_type:"authentication",failure_code:"authentication_failed"};case"permission_denied":return{failure_type:"authorization",failure_code:"permission_denied"};case"endpoint":return{failure_type:"provider",failure_code:"resource_not_found"};case"network":return{failure_type:"network",failure_code:"network_failed"};case"timeout":return{failure_type:"timeout",failure_code:"request_timeout"};case"rate_limited":return{failure_type:"rate_limit",failure_code:"rate_limited"};case"request_failed":return{failure_type:"provider",failure_code:"request_rejected"};case"truncated":return{failure_type:"response",failure_code:"output_truncated"};case"content_filtered":return{failure_type:"policy",failure_code:"content_blocked"};case"empty_response":return{failure_type:"response",failure_code:"empty_response"};case"invalid_response":return{failure_type:"response",failure_code:"malformed_response"};case"cancelled":return{failure_type:"cancelled",failure_code:"cancelled"}}}var T=class extends Error{code;retryable;details;failure;modelFailures;attempts;usage;constructor(t,n,o={}){super(n),this.name="LlmTransportError",this.code=t,this.retryable=o.retryable??!1,this.details=o.details??[],this.attempts=o.attempts??1,this.usage=o.usage??{},this.failure=Ut(o.classification??WE(t),{retryable:this.retryable,message:n,...o.context,...this.details.length>0?{details:this.details}:{}}),this.modelFailures=o.modelFailures??[]}};function XE(e){return new Promise(t=>setTimeout(t,e))}function Xt(e={},t={}){let n=c=>e[c]===void 0&&t[c]===void 0?void 0:(e[c]??0)+(t[c]??0),o=n("inputTokens"),i=n("outputTokens"),r=n("cachedInputTokens"),s=n("cacheCreationTokens");return{...o!==void 0?{inputTokens:o}:{},...i!==void 0?{outputTokens:i}:{},...r!==void 0?{cachedInputTokens:r}:{},...s!==void 0?{cacheCreationTokens:s}:{}}}async function en(e,t){let n={};for(let o=1;o<=e;o+=1)try{return{value:await t(),attempts:o,failedUsage:n}}catch(i){if(i instanceof T&&(n=Xt(n,i.usage),i.attempts=o,i.usage=n),!(i instanceof T)||!i.retryable||o===e)throw i;await XE(Math.min(3e4,1e3*2**(o-1)))}throw new Error("unreachable retry state")}function bf(e){let t=e.usage;if(!t)return{};let n=t.cache_read_input_tokens??0,o=t.cache_creation_input_tokens??0;return{inputTokens:(t.input_tokens??0)+n+o,outputTokens:t.output_tokens??0,cachedInputTokens:n,cacheCreationTokens:o}}function Of(e){if(e instanceof T)return e;if(e instanceof ix)return new T("request_failed","Anthropic request was aborted.");if(e instanceof nx)return new T("timeout","Anthropic request timed out.",{retryable:!0});if(e instanceof tx)return new T("request_failed","Anthropic connection failed.",{retryable:!0,details:[e.message.slice(0,500)]});if(e instanceof ox){let n=e.status??0,o=n===408||n===429||n>=500,i=n===401||n===403?"auth":n===429?"rate_limited":"request_failed";return new T(i,"Anthropic request failed.",{retryable:o,details:[`status: ${n}`,e.message.slice(0,500)]})}let t=e instanceof Error?e.message:String(e);return new T("request_failed","Anthropic request failed.",{details:[t.slice(0,500)]})}var Zs=class{constructor(t,n,o){this.provider=t;this.model=n;let i={apiKey:o};t.baseUrl&&(i.baseURL=t.baseUrl),this.client=new ex({...i,maxRetries:0})}provider;model;client;params(t){let n={model:this.model.model,max_tokens:t.maxOutputTokens,stream:!1,messages:[{role:"user",content:t.user}]};return t.system.trim()&&(n.system=t.system),this.model.thinkingBudgetTokens!==void 0&&(n.thinking={type:"enabled",budget_tokens:this.model.thinkingBudgetTokens}),n}async generateText(t){let n=await en(this.provider.maxAttempts,async()=>{try{let o=await this.client.messages.create(this.params(t),{timeout:this.provider.timeoutMs,signal:t.signal}),i=bf(o);if(o.stop_reason==="max_tokens")throw new T("truncated","Provider output was truncated.",{usage:i});if(o.stop_reason==="refusal")throw new T("content_filtered","Provider filtered the response.",{usage:i});let r=o.content.filter(s=>s.type==="text").map(s=>s.text).join(`
145
- `).trim();if(!r)throw new T("empty_response","Provider returned an empty text response.",{usage:i});return{text:r,finishReason:o.stop_reason??"",usage:i,raw:o}}catch(o){throw Of(o)}});return{...n.value,attempts:n.attempts,usage:Xt(n.failedUsage,n.value.usage)}}async generateTool(t){let n=await en(this.provider.maxAttempts,async()=>{try{let o={name:t.tool.name,description:t.tool.description,input_schema:{type:"object",...t.tool.inputSchema}},i=await this.client.messages.create({...this.params(t),tools:[o],tool_choice:{type:"tool",name:t.tool.name,disable_parallel_tool_use:!0}},{timeout:this.provider.timeoutMs,signal:t.signal}),r=bf(i);if(i.stop_reason==="max_tokens")throw new T("truncated","Provider tool output was truncated.",{usage:r});if(i.stop_reason==="refusal")throw new T("content_filtered","Provider filtered the response.",{usage:r});let s=i.content.find(c=>c.type==="tool_use"&&c.name===t.tool.name);if(!s||s.type!=="tool_use")throw new T("invalid_response","Provider did not return the required tool call.",{usage:r});return{input:s.input,finishReason:i.stop_reason??"",usage:r,raw:i}}catch(o){throw Of(o)}});return{...n.value,attempts:n.attempts,usage:Xt(n.failedUsage,n.value.usage)}}};import*as Dd from"node:fs";import*as Gd from"node:path";import{File as px}from"node:buffer";import{Agent as lx,fetch as Xs,FormData as ux}from"undici";function rx(e){return typeof e=="object"&&e!==null}function Td(e){let t=[],n=new Set,o=e;for(;rx(o)&&!n.has(o);)n.add(o),t.push(o),o=o.cause;return t}function Ws(e){for(let t of Td(e)){if(typeof t.status=="number")return t.status;if(typeof t.statusCode=="number")return t.statusCode}return null}function sx(e){for(let t of Td(e))if(typeof t.code=="string")return t.code}function ax(e){for(let t of Td(e))if(typeof t.name=="string")return t.name}function cx(e){let t=ax(e);return t==="AbortError"||t==="TimeoutError"||t==="RequestTimeoutError"||t==="APIConnectionTimeoutError"}function dx(e){return e?["ENOTFOUND","EAI_AGAIN"].includes(e)?{failure_type:"network",failure_code:"dns_failed"}:e==="ECONNREFUSED"?{failure_type:"network",failure_code:"connection_refused"}:["ECONNRESET","EPIPE","UND_ERR_SOCKET"].includes(e)?{failure_type:"network",failure_code:"connection_reset"}:["ENETUNREACH","EHOSTUNREACH"].includes(e)?{failure_type:"network",failure_code:"network_unreachable"}:e.startsWith("ERR_TLS_")||e.startsWith("ERR_SSL_")||e.startsWith("CERT_")||["DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"].includes(e)?{failure_type:"network",failure_code:"tls_failed"}:["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT"].includes(e)?{failure_type:"timeout",failure_code:"connect_timeout"}:{failure_type:"network",failure_code:"network_failed"}:{failure_type:"network",failure_code:"network_failed"}}function ti(e,t,n,o,i={}){if(t?.aborted)return new T("cancelled",n,{details:[o],classification:{failure_type:"cancelled",failure_code:"cancelled"},context:i});let r=sx(e),s=cx(e)?{failure_type:"timeout",failure_code:"request_timeout"}:dx(r),c=s.failure_type==="timeout"?"timeout":"network";return new T(c,n,{retryable:!0,details:[o],classification:s,context:{...i,...r?{system_code:r}:{}}})}function ni(e,t,n,o={}){let i,r,s=!1;return e===401?(i="auth",r={failure_type:"authentication",failure_code:"authentication_failed"}):e===403?(i="permission_denied",r={failure_type:"authorization",failure_code:"permission_denied"}):e===404?(i="endpoint",r={failure_type:"provider",failure_code:"resource_not_found"}):e===408?(i="timeout",r={failure_type:"timeout",failure_code:"request_timeout"},s=!0):e===413&&o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"media_too_large"}):e===415&&o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"unsupported_media"}):e===429?(i="rate_limited",r={failure_type:"rate_limit",failure_code:"rate_limited"},s=!0):e>=500?(i="request_failed",r={failure_type:"provider",failure_code:"provider_unavailable"},s=!0):o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"media_upload_failed"}):(i="request_failed",r={failure_type:"provider",failure_code:"request_rejected"}),new T(i,t,{retryable:s,details:[`status: ${e}`,n],classification:r,context:{...o,http_status:e}})}var fx=2e3;function mx(e){return new Promise(t=>setTimeout(t,e))}function Vd(e,t,n,o){if(e instanceof T)return e;let i=e instanceof Error?e.message:String(e),r=Ws(e),s={provider:"doubao",model:o,operation:n};return r!==null?ni(r,`Doubao ${n} failed.`,i.slice(0,500),s):ti(e,t,`Doubao ${n} failed.`,i.slice(0,500),s)}function gx(e){if(!e)return{};let t=n=>typeof n=="number"?n:void 0;return{inputTokens:t(e.input_tokens),outputTokens:t(e.output_tokens)}}function hx(e){let t=[];for(let n of e.output??[])if(n.type==="message")for(let o of n.content??[])o.type==="output_text"&&typeof o.text=="string"&&t.push(o.text);return t.join("").trim()}var ea=class{constructor(t,n,o,i,r,s){this.model=t;this.timeoutMs=n;this.maxAttempts=o;this.client=s??yx(i,r,n)}model;timeoutMs;maxAttempts;client;async run(t){let{value:n}=await en(this.maxAttempts,async()=>{try{return await this.client.uploadFile({filePath:t.localPath,mimeType:t.localMime,fps:t.fps})}catch(i){throw Vd(i,t.signal,"upload",this.model)}});if(!n.id)throw new T("invalid_response","Doubao upload returned no file id.");let o=await this.pollActive(n.id,t.signal);try{return await this.generateOnce(o,t)}finally{await this.client.deleteFile({id:o}).catch(()=>{})}}async pollActive(t,n){let o=Date.now()+this.timeoutMs,i="processing";for(;i==="processing"||i==="";){if(n?.aborted)throw new T("cancelled","Doubao upload aborted.",{context:{provider:"doubao",model:this.model,operation:"file_poll"}});if(Date.now()>=o)throw new T("timeout","Doubao file processing timed out.",{retryable:!0,classification:{failure_type:"timeout",failure_code:"media_processing_timeout"},context:{provider:"doubao",model:this.model,operation:"file_poll"}});await mx(fx);let r;try{r=await this.client.getFile({id:t})}catch(s){throw Vd(s,n,"file_poll",this.model)}i=(r.status??"").toLowerCase()}if(i==="failed"||i==="error")throw new T("invalid_response","Doubao file processing failed.",{classification:{failure_type:"media",failure_code:"media_processing_failed"},context:{provider:"doubao",model:this.model,operation:"file_poll"}});return t}async generateOnce(t,n){let o={model:this.model,input:[{role:"user",content:[{type:"input_video",file_id:t},{type:"input_text",text:n.user}]}]};return n.system?.trim()&&(o.instructions=n.system),n.responseJsonSchema&&(o.text={format:{type:"json_schema",name:"video_serial",schema:n.responseJsonSchema}}),this.generateResponse(o,n.signal,!!n.responseJsonSchema,n.acceptsText)}async generateText(t){let n=this.textParams(t);return t.responseFormat&&(n.text={format:{type:t.responseFormat}}),this.generateResponse(n,t.signal,!!t.responseFormat)}async generateDocument(t,n){let o=t.media.kind==="base64"?t.media.data:n?Dd.readFileSync(n).toString("base64"):void 0;if(!o)throw new T("invalid_response","Doubao PDF recovery requires the original document bytes.");let i={model:this.model,input:[{role:"user",content:[{type:"input_file",filename:n?Gd.basename(n):"document.pdf",file_data:`data:application/pdf;base64,${o}`},{type:"input_text",text:t.user}]}]};return t.system?.trim()&&(i.instructions=t.system),t.responseJsonSchema&&(i.text={format:{type:"json_schema",name:"document",schema:t.responseJsonSchema}}),this.generateResponse(i,t.signal,!!t.responseJsonSchema)}async generateTool(t){let n=this.textParams(t);n.text={format:{type:"json_schema",name:t.tool.name,description:t.tool.description,schema:t.tool.inputSchema}};let o=await this.generateResponse(n,t.signal,!0);return{input:JSON.parse(o.text),finishReason:o.finishReason,attempts:o.attempts,usage:o.usage,raw:o.raw}}textParams(t){return{model:this.model,instructions:t.system,input:[{role:"user",content:[{type:"input_text",text:t.user}]}]}}async generateResponse(t,n,o,i){let{value:r,attempts:s,failedUsage:c}=await en(this.maxAttempts,async()=>{let a;try{a=await this.client.createResponse(t,n)}catch(f){throw Vd(f,n,"generate",this.model)}let d=(a.status??"").toLowerCase(),p=gx(a.usage);if(d==="incomplete"){let f=a.incomplete_details?.reason??"unknown";throw f==="max_output_tokens"||f==="length"?new T("truncated","Doubao output was truncated.",{usage:p}):new T("content_filtered",`Doubao response incomplete (reason=${f}).`,{usage:p})}let l=hx(a);if(!l)throw new T("empty_response","Doubao returned an empty response.",{retryable:!0,usage:p});if(i&&!i(l))throw new T("invalid_response","Doubao response does not match the requested output format.",{retryable:!0,usage:p,context:{provider:"doubao",model:this.model,operation:"generate"}});if(o)try{JSON.parse(l)}catch{throw new T("invalid_response","Doubao returned malformed JSON for a structured response.",{retryable:!0,usage:p,context:{provider:"doubao",model:this.model,operation:"generate"}})}return{text:l,usage:p,raw:a}});return{text:r.text,finishReason:"STOP",attempts:s,usage:Xt(c,r.usage),raw:r.raw}}},$d=class extends Error{constructor(n,o){super(o);this.status=n;this.name="HttpError"}status};function yx(e,t,n){let o=t.replace(/\/$/,""),i={Authorization:`Bearer ${e}`},r=new lx({headersTimeout:n,bodyTimeout:n});function s(a){let d=AbortSignal.timeout(n);return a?AbortSignal.any([a,d]):d}async function c(a){let d=await a.text().catch(()=>"");throw new $d(a.status,d.slice(0,500))}return{async uploadFile({filePath:a,mimeType:d,fps:p}){let l=new ux,f=Dd.readFileSync(a);l.append("file",new px([f],Gd.basename(a),{type:d})),l.append("purpose","user_data"),l.append("preprocess_configs[video][fps]",String(p));let u=await Xs(`${o}/files`,{method:"POST",headers:i,body:l,signal:s(),dispatcher:r});return u.ok||await c(u),await u.json()},async getFile({id:a}){let d=await Xs(`${o}/files/${a}`,{headers:i,signal:s(),dispatcher:r});return d.ok||await c(d),await d.json()},async createResponse(a,d){let p=await Xs(`${o}/responses`,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify(a),signal:s(d),dispatcher:r});return p.ok||await c(p),await p.json()},async deleteFile({id:a}){let d=await Xs(`${o}/files/${a}`,{method:"DELETE",headers:i,signal:s(),dispatcher:r});d.ok||await c(d)}}}import{GoogleAuth as wx}from"google-auth-library";function ta(){let e=process.env.GOOGLE_CLOUD_PROJECT?.trim();if(!e)throw new Error("GOOGLE_CLOUD_PROJECT is required for official Vertex AI");return e}var vf=new wx({scopes:["https://www.googleapis.com/auth/cloud-platform"]});import*as Uf from"node:fs";import{createRequire as bx}from"node:module";import*as na from"node:fs";import*as _x from"node:http";import*as Ex from"node:https";import{HttpsProxyAgent as xx}from"https-proxy-agent";var Mf="https://generativelanguage.googleapis.com";function Sx(e,t){let n=new URL(e??Mf);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/upload/v1beta/files`,n.searchParams.set("key",t),n}function Ix(e,t){let n=new URL(t??Mf),o=new URL(e,n);if(!t)return o;o.protocol=n.protocol,o.host=n.host;let i=n.pathname.replace(/\/+$/,"");return i&&o.pathname!==i&&!o.pathname.startsWith(`${i}/`)&&(o.pathname=`${i}/${o.pathname.replace(/^\/+/,"")}`),o}function Ki(e,t){if(!t)return e;let n=e.split(t).join("[REDACTED]"),o=encodeURIComponent(t);return o!==t&&(n=n.split(o).join("[REDACTED]")),n}function Ax(e){return e?new xx(e):void 0}function Rf(e,t,n,o){return new Promise((i,r)=>{let c=(e.protocol==="http:"?_x:Ex).request({...t,agent:e.protocol==="https:"?t.agent:void 0,protocol:e.protocol,hostname:e.hostname,port:e.port||void 0,path:`${e.pathname}${e.search}`},a=>{let d="";a.on("data",p=>d+=p),a.on("end",()=>i({status:a.statusCode??0,headers:a.headers,body:d}))});if(c.on("error",r),o){if(o.aborted){c.destroy(new Error("aborted"));return}o.addEventListener("abort",()=>c.destroy(new Error("aborted")),{once:!0})}n&&typeof n.pipe=="function"?n.pipe(c):(n&&c.write(n),c.end())})}function kx(e,t){let n=e[t];return Array.isArray(n)?n[0]??"":n??""}async function Nf(e){let t=na.statSync(e.filePath).size,o={agent:Ax(e.proxyUrl??""),timeout:e.timeoutMs},i=Sx(e.baseUrl,e.apiKey),r=l=>Ki(l,e.apiKey),s;try{s=await Rf(i,{...o,method:"POST",headers:{"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(t),"X-Goog-Upload-Header-Content-Type":e.mimeType,"Content-Type":"application/json"}},JSON.stringify({file:{}}),e.signal)}catch(l){let f=r(l instanceof Error?l.message:String(l));throw ti(l,e.signal,"Gemini upload start failed.",f,{operation:"upload"})}let c=kx(s.headers,"x-goog-upload-url");if(s.status<200||s.status>=300)throw ni(s.status,"Gemini upload start failed.",r(s.body).slice(0,300),{operation:"upload"});if(!c)throw new T("invalid_response","Gemini upload start returned no upload URL.",{details:[r(s.body).slice(0,300)],context:{operation:"upload",http_status:s.status}});let a=Ix(c,e.baseUrl),d;try{d=await Rf(a,{...o,method:"POST",headers:{"Content-Length":String(t),"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"}},na.createReadStream(e.filePath),e.signal)}catch(l){let f=r(l instanceof Error?l.message:String(l));throw ti(l,e.signal,"Gemini upload transfer failed.",f,{operation:"upload"})}if(d.status<200||d.status>=300)throw ni(d.status,"Gemini upload transfer failed.",r(d.body).slice(0,300),{operation:"upload"});let p;try{p=JSON.parse(d.body)}catch{throw new T("invalid_response","Gemini upload returned invalid JSON.",{details:[r(d.body).slice(0,300)]})}if(!p.file)throw new T("invalid_response","Gemini upload returned no file.",{details:[r(d.body).slice(0,300)]});return p.file}var Ox=new Set(["SAFETY","PROHIBITED_CONTENT","RECITATION","BLOCKLIST","SPII","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION"]),vx=new Set(["LANGUAGE","OTHER","MALFORMED_FUNCTION_CALL","IMAGE_OTHER","NO_IMAGE","UNEXPECTED_TOOL_CALL","TOO_MANY_TOOL_CALLS","MISSING_THOUGHT_SIGNATURE","MALFORMED_RESPONSE"]);function Bd(e){switch(e){case"SAFETY":case"PROHIBITED_CONTENT":case"BLOCKLIST":case"SPII":case"RECITATION":case"IMAGE_SAFETY":case"IMAGE_PROHIBITED_CONTENT":case"IMAGE_RECITATION":case"ESCALATION":case"OTHER":return e;case"":case"BLOCK_REASON_UNSPECIFIED":case"FINISH_REASON_UNSPECIFIED":return"UNSPECIFIED";default:return"UNKNOWN"}}function Lf(e){if(e?.length)return e.map(t=>({category:t.category??"UNSPECIFIED",probability:t.probability??"UNSPECIFIED",blocked:t.blocked??!1}))}function Rx(e){if(typeof e!="object"||e===null)return{};let t=e,n=o=>typeof o=="number"?o:void 0;return{inputTokens:n(t.promptTokenCount),outputTokens:n(t.candidatesTokenCount)}}function Mx(e){return/-c\d+$/.test(e)}function Nx(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t<0||n<t)throw new SyntaxError("JSON object not found");return e.slice(t,n+1)}var Lx=2e3;function Ux(e){return new Promise(t=>setTimeout(t,e))}function Jd(e,t,n,o,i,r){if(e instanceof T)return new T(e.code,Ki(e.message,o),{retryable:e.retryable,details:e.details.map(d=>Ki(d,o)),attempts:e.attempts,usage:e.usage,classification:Ni(e.failure),context:{...Sr(e.failure),provider:i,model:r,operation:n},modelFailures:e.modelFailures});let s=Ki(e instanceof Error?e.message:String(e),o),c=Ws(e),a={provider:i,model:r,operation:n};return c!==null?ni(c,`Gemini ${n} failed.`,s.slice(0,500),a):ti(e,t,`Gemini ${n} failed.`,s.slice(0,500),a)}var zi=class{constructor(t,n,o,i){this.provider=t;this.model=n;this.apiKey=o;this.client=i??Cx(o,t.timeoutMs,t.baseUrl,t.protocol==="google-vertex")}provider;model;apiKey;client;async prepare(t,n,o,i){return o==="base64"||this.provider.protocol==="google-vertex"?{kind:"base64",data:Uf.readFileSync(t,"base64"),mimeType:n}:{kind:"file-api",file:await this.uploadFile(t,n,i)}}async uploadFile(t,n,o){let{value:i}=await en(this.provider.maxAttempts,async()=>{try{return await this.client.files.upload({file:t,config:{mimeType:n}})}catch(s){throw Jd(s,o,"upload",this.apiKey,this.model.provider,this.model.model)}}),r=await this.pollActive(i,o);if(!r.name||!r.uri)throw new T("invalid_response","Gemini upload returned no file reference.",{context:{provider:this.model.provider,model:this.model.model,operation:"upload"}});return{name:r.name,uri:r.uri,mimeType:r.mimeType??n}}async pollActive(t,n){let o=t,i=Date.now()+this.provider.timeoutMs;for(;(o.state??"").toUpperCase()==="PROCESSING";){if(n?.aborted)throw new T("cancelled","Gemini upload aborted.",{context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});if(Date.now()>=i)throw new T("timeout","Gemini file processing timed out.",{retryable:!0,classification:{failure_type:"timeout",failure_code:"media_processing_timeout"},context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});if(await Ux(Lx),!o.name)throw new T("invalid_response","Gemini upload returned no file name to poll.",{context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});try{o=await this.client.files.get({name:o.name})}catch(r){throw Jd(r,n,"file_poll",this.apiKey,this.model.provider,this.model.model)}}if((o.state??"").toUpperCase()==="FAILED")throw new T("invalid_response","Gemini file processing failed.",{details:[Ki(o.error?.message??"unknown media error",this.apiKey)],classification:{failure_type:"media",failure_code:"media_processing_failed"},context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});return o}async generateMedia(t,n){let o=!!t.responseJsonSchema&&Mx(this.model.model),i={mediaResolution:"MEDIA_RESOLUTION_HIGH"},r=[t.system?.trim(),o?`\u8F93\u51FA\u5FC5\u987B\u662F\u4E00\u4E2A\u53EF\u89E3\u6790\u7684 JSON \u5BF9\u8C61\u3002\u53EA\u8FD4\u56DE JSON\uFF0C\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u989D\u5916\u6587\u5B57\u6216 Markdown \u4EE3\u7801\u5757\u3002
144
+ `)}function xf(e){let t=e._args??[],n=t[0]?.trim()??"",o=String(e.from??"").trim(),i=String(e.to??"").trim(),r=!!e.unreleased;if(t.length>1)throw new x("changelog accepts at most one version argument.",{exitCode:B,errorCode:"CHANGELOG_TOO_MANY_ARGS",hint:"Pass a single version, or use --from/--to for a range.",data:{expected:["scriptctl changelog [version] [--from X] [--to Y] [--unreleased]"],actual:[t.join(" ")]}});if(r&&(n||o||i))throw new x("--unreleased cannot combine with version, --from, or --to.",{exitCode:B,errorCode:"CHANGELOG_SELECTOR_CONFLICT",hint:"Run `scriptctl changelog --unreleased` by itself.",data:{expected:["either --unreleased, a version, or a --from/--to range"],actual:["--unreleased with another selector"]}});if(n&&(o||i))throw new x("A version argument cannot combine with --from or --to.",{exitCode:B,errorCode:"CHANGELOG_SELECTOR_CONFLICT",hint:"Run `scriptctl changelog 0.25.10` or `scriptctl changelog --from 0.25.8 --to 0.25.10`.",data:{expected:["either a version argument, or --from/--to"],actual:[n,o?`--from ${o}`:"",i?`--to ${i}`:""].filter(Boolean)}});if(r){let d=qs(VE);return[{text:d,data:{content:d,versions:[],unreleased:!0}},G]}let s=DE(),c=$E();if(n){if(Br(n),!s.includes(n))throw Od(n,s);let d=qs(n);return[{text:d,data:{content:d,versions:[n],unreleased:!1}},G]}if(o||i){if(!o)throw new x("--from is required for range queries.",{exitCode:B,errorCode:"CHANGELOG_FROM_MISSING",hint:"Run `scriptctl changelog --from 0.25.8 --to 0.25.10`.",data:{expected:["--from <x.y.z>"],actual:[i?`--to ${i}`:"<missing>"]}});Br(o);let d=i||c;if(Br(d),!s.includes(d))throw Od(d,s);let p=s.filter(f=>vd(f,o)>0&&vd(f,d)<=0);if(p.length===0)throw GE(o,d);let l=BE(p);return[{text:l,data:{content:l,versions:p,from:o,to:d,unreleased:!1}},G]}if(!s.includes(c))throw Od(c,s);let a=qs(c);return[{text:a,data:{content:a,versions:[c],unreleased:!1}},G]}import*as Bt from"node:fs";import*as ii from"node:path";import{createRequire as Jx}from"node:module";import*as Hn from"node:fs";import*as xo from"node:path";import*as If from"node:os";import{fileURLToPath as JE}from"node:url";function Sf(e){return e.startsWith("~")?xo.join(If.homedir(),e.slice(1)):e}function KE(e){let t=Hn.readFileSync(e,"utf-8");for(let n of t.split(/\r?\n/)){let o=n.trim();if(!o||o.startsWith("#"))continue;o.startsWith("export ")&&(o=o.slice(7).trim());let i=o.indexOf("=");if(i<0)continue;let r=o.slice(0,i).trim(),s=o.slice(i+1).trim();s.length>=2&&s[0]===s[s.length-1]&&(s[0]==="'"||s[0]==='"')&&(s=s.slice(1,-1)),r&&s&&!process.env[r]&&(process.env[r]=s)}}function Md(){let e=[],t=(process.env.SCRIPTCTL_ENV_FILE??"").trim();t&&e.push(Sf(t));let n=(process.env.SCRIPTCTL_SKILL_DIR??"").trim();n&&e.push(xo.join(Sf(n),".env"));let o;try{o=JE(import.meta.url)}catch{o=process.cwd()}let i=xo.resolve(o),r=new Set;for(;;){let s=xo.dirname(i);if(s===i||r.has(s))break;r.add(s),e.push(xo.join(s,".env")),i=s}return e}function Af(){let e=process.env.SCRIPTCTL_NO_DOTENV;if(e==="1"||e==="true"||e==="True")return;let t=new Set;for(let n of Md()){let o;try{o=Hn.existsSync(n)?Hn.realpathSync(n):n}catch{o=n}t.has(o)||!Hn.existsSync(n)||!Hn.statSync(n).isFile()||(t.add(o),KE(n))}}var fe=class extends Error{status;code;payload;configMissing;constructor(t,n={}){super(t),this.name="ScriptOutputApiError",this.status=n.status??null,this.code=n.code??null,this.payload=n.payload,this.configMissing=n.configMissing??null}};async function Nd(e,t){if(e.updateEpisodeCount)try{await e.updateEpisodeCount(t)}catch{}}function kf(e){let t=!!e?.remote,n=!!e?.local;if(t&&n)return{mode:null,conflict:!0};if(t)return{mode:"remote",conflict:!1};if(n)return{mode:"local",conflict:!1};let o=(process.env.SCRIPTCTL_OUTPUT_MODE??"").trim().toLowerCase();if(o==="local"||o==="remote")return{mode:o,conflict:!1};if(o!=="")return{mode:null,conflict:!1};let i=typeof e?.projectGroupNo=="string"?e.projectGroupNo.trim():"",r=(process.env.SANDBOX_PROJECT_GROUP_NO??"").trim();return i!==""||r!==""?{mode:"remote",conflict:!1}:{mode:null,conflict:!1}}import*as jr from"node:fs";import*as Of from"node:os";import*as Jr from"node:path";import{parseDocument as jE}from"yaml";function ae(e,t,n){return{id:e,mode:t,version:"1",maxOutputTokens:n,defaultProfile:"default"}}var An={"direct.episode-titles":ae("direct.episode-titles","tool",4096),"direct.batch-extract":ae("direct.batch-extract","text",16e3),"direct.episode-synopsis":ae("direct.episode-synopsis","tool",2048),"direct.synopsis-reduction":ae("direct.synopsis-reduction","tool",4096),"direct.script-synopsis":ae("direct.script-synopsis","tool",2048),"direct.asset-grouping":ae("direct.asset-grouping","text",8e3),"direct.asset-curation":ae("direct.asset-curation","text",2e4),"direct.asset-curation-audit":ae("direct.asset-curation-audit","text",2e4),"direct.location-canonicalization":ae("direct.location-canonicalization","text",2e4),"direct.state-curation":ae("direct.state-curation","text",2e4),"direct.state-binding":ae("direct.state-binding","tool",16e3),"metadata.global":ae("metadata.global","text",16e3),"metadata.descriptions":ae("metadata.descriptions","text",16e3),"synopsis.chunk":ae("synopsis.chunk","text",4096),"synopsis.episode":ae("synopsis.episode","text",4096),"synopsis.arc":ae("synopsis.arc","text",16e3),"synopsis.script-overview":ae("synopsis.script-overview","text",16e3),"ingest.body-start":ae("ingest.body-start","text",16e3),"ingest.arc-summary":ae("ingest.arc-summary","text",4096),"ingest.text-normalize":ae("ingest.text-normalize","text",32e3),"ingest.episode-assets":ae("ingest.episode-assets","tool",32e3),"ingest.name-fix":ae("ingest.name-fix","tool",16e3),"ingest.mention-resolve":ae("ingest.mention-resolve","text",8e3),"ingest.asset-extract":ae("ingest.asset-extract","text",8e3),"ingest.asset-curate":ae("ingest.asset-curate","text",32e3),"ingest.asset-recall":ae("ingest.asset-recall","text",65536),"ingest.asset-refine":ae("ingest.asset-refine","text",32e3),"ingest.state-reconcile":ae("ingest.state-reconcile","text",32e3),"ingest.asset-audit":ae("ingest.asset-audit","tool",32e3),"ingest.speaker-audit":ae("ingest.speaker-audit","tool",16e3),"ingest.comic-serial":{id:"ingest.comic-serial",mode:"document",version:"1",defaultProfile:"default"},"ingest.video-serial":ae("ingest.video-serial","video",65536)},bf=Object.keys(An).filter(Ld);function Ld(e){return Object.hasOwn(An,e)}var zE=new Set(["protocol","baseUrl","apiKey","timeoutMs","maxAttempts","videoResponseSchemaField","videoUploadMode","documentResponseSchemaField","documentUploadMode"]),HE=new Set(["provider","model","thinking","reasoning","temperature","fallbacks"]),FE=new Set(["env"]),QE=new Set(["budgetTokens"]);function Oe(e,t=[]){return new x(e,{exitCode:k,errorCode:"LLM_CONFIG_INVALID",hint:"Fix the selected LLM configuration or environment and rerun `scriptctl doctor`.",data:{expected:["valid scriptctl LLM YAML configuration"],actual:t}})}function Cd(e,t){let n;try{n=new URL(e)}catch{throw Oe(`${t} must be an absolute URL.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Oe(`${t} must use http or https.`);return n.toString().replace(/\/$/,"")}function Td(e,t="provider base URL"){return Cd(e,t)}function YE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function So(e,t){if(!YE(e))throw Oe(`${t} must be a mapping.`,[`${t}: ${typeof e}`]);return e}function Io(e,t){if(typeof e!="string"||!e.trim())throw Oe(`${t} must be a non-empty string.`);return e.trim()}function Pd(e,t,n,o){if(!Number.isInteger(e)||typeof e!="number"||e<n||o!==void 0&&e>o)throw Oe(`${t} must be an integer in ${o===void 0?`[${n}, +\u221E)`:`[${n}, ${o}]`}.`);return e}function Kr(e,t,n){let o=Object.keys(e).filter(i=>!t.has(i));if(o.length>0)throw Oe(`${n} contains unknown fields.`,o)}function qE(e,t){let n=So(t,`providers.${e}`);Kr(n,zE,`providers.${e}`);let o=Io(n.protocol,`providers.${e}.protocol`);if(o!=="anthropic"&&o!=="openai-compatible"&&o!=="google-gemini"&&o!=="google-vertex")throw Oe(`providers.${e}.protocol is unsupported.`,[o]);let i=n.baseUrl===void 0&&o!=="openai-compatible"?null:Cd(Io(n.baseUrl,`providers.${e}.baseUrl`),`providers.${e}.baseUrl`),r="";if(o!=="google-vertex"){let c=So(n.apiKey,`providers.${e}.apiKey`);if(Kr(c,FE,`providers.${e}.apiKey`),r=Io(c.env,`providers.${e}.apiKey.env`),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw Oe(`providers.${e}.apiKey.env must be an environment variable name.`)}let s={protocol:o,baseUrl:i,apiKeyEnv:r,timeoutMs:Pd(n.timeoutMs,`providers.${e}.timeoutMs`,1),maxAttempts:Pd(n.maxAttempts,`providers.${e}.maxAttempts`,1,6)};for(let c of["videoResponseSchemaField","documentResponseSchemaField"]){let a=n[c];if(a!==void 0){if(o!=="google-gemini"&&o!=="google-vertex")throw Oe(`providers.${e}.${c} requires a Gemini ${c.startsWith("video")?"video":"document"} provider.`);if(a!=="responseJsonSchema"&&a!=="responseSchema")throw Oe(`providers.${e}.${c} must be responseJsonSchema or responseSchema.`);s[c]=a}}for(let c of["videoUploadMode","documentUploadMode"]){let a=n[c];if(a!==void 0){if(o!=="google-gemini"&&o!=="google-vertex")throw Oe(`providers.${e}.${c} requires a Gemini ${c.startsWith("video")?"video":"document"} provider.`);if(a!=="file-api"&&a!=="base64")throw Oe(`providers.${e}.${c} must be file-api or base64.`);s[c]=a}}return s}function ZE(e,t,n){let o=So(t,`models.${e}`);Kr(o,HE,`models.${e}`);let i=Io(o.provider,`models.${e}.provider`),r=n[i];if(!r)throw Oe(`models.${e} references an unknown provider.`,[i]);let s={provider:i,model:Io(o.model,`models.${e}.model`)};if(o.reasoning!==void 0&&(s.reasoning=Io(o.reasoning,`models.${e}.reasoning`)),o.fallbacks!==void 0){let c=o.fallbacks;if(!Array.isArray(c))throw Oe(`models.${e}.fallbacks must be a list of model profiles.`);s.fallbacks=c.map((a,d)=>Io(a,`models.${e}.fallbacks[${d}]`))}if(o.temperature!==void 0){let c=o.temperature;if(typeof c!="number"||!Number.isFinite(c)||c<0)throw Oe(`models.${e}.temperature must be a number \u2265 0.`);s.temperature=c}if(o.thinking!==void 0){if(r.protocol!=="anthropic")throw Oe(`models.${e}.thinking is only valid for anthropic providers.`);let c=So(o.thinking,`models.${e}.thinking`);Kr(c,QE,`models.${e}.thinking`),s.thinkingBudgetTokens=Pd(c.budgetTokens,`models.${e}.thinking.budgetTokens`,1024)}return s}function WE(e,t){let n=So(e,"config");if(Kr(n,new Set(["version","providers","models","tasks"]),"config"),n.version!==1)throw Oe("config.version must be 1.");let o=So(n.providers,"providers"),i={};for(let[a,d]of Object.entries(o))i[a]=qE(a,d);let r=So(n.models,"models"),s={};for(let[a,d]of Object.entries(r))s[a]=ZE(a,d,i);if(!s.default)throw Oe("models.default is required.");for(let[a,d]of Object.entries(s))for(let p of d.fallbacks??[])if(!s[p]||p===a)throw Oe(`models.${a}.fallbacks references an unknown or the same profile.`,[p]);let c={};if(n.tasks!==void 0){let a=So(n.tasks,"tasks");for(let[d,p]of Object.entries(a)){if(!Ld(d))throw Oe("tasks contains an unknown task id.",[d]);let l=Io(p,`tasks.${d}`);if(!s[l])throw Oe(`tasks.${d} references an unknown model profile.`,[l]);c[d]=l}}return{version:1,providers:i,models:s,tasks:c,source:"file",sourcePath:t}}var ei={version:1,providers:{gw:{protocol:"openai-compatible",baseUrl:null,apiKeyEnv:"PROJECT_LITELLM_GATEWAY_API_KEY",timeoutMs:3e5,maxAttempts:3},"gw-anthropic":{protocol:"anthropic",baseUrl:null,apiKeyEnv:"PROJECT_LITELLM_GATEWAY_API_KEY",timeoutMs:3e5,maxAttempts:3},"google-gemini":{protocol:"google-vertex",baseUrl:null,apiKeyEnv:"",timeoutMs:6e5,maxAttempts:3},nnyyai:{protocol:"google-gemini",baseUrl:"https://api.nnyyai.com",apiKeyEnv:"NNYYAI_API_KEY",timeoutMs:6e5,maxAttempts:3,videoResponseSchemaField:"responseSchema",videoUploadMode:"base64",documentResponseSchemaField:"responseSchema",documentUploadMode:"base64"}},models:{default:{provider:"gw",model:"deepseek-v4-flash-packy",temperature:0},synopsis:{provider:"gw",model:"deepseek-v4.1-flash-huoshan",temperature:0},"ingest-low":{provider:"gw",model:"deepseek-v4-flash-packy",temperature:0},"ingest-normalize":{provider:"gw",model:"claude-sonnet-4-6-aihubmix",temperature:0},"ingest-video":{provider:"nnyyai",model:"gemini-3.8-flash"},"ingest-comic":{provider:"nnyyai",model:"gemini-3.8-flash"},"review-text":{provider:"google-gemini",model:"gemini-3.8-flash",temperature:0},"review-comic":{provider:"nnyyai",model:"gemini-3.8-flash",temperature:0},"review-agent":{provider:"google-gemini",model:"gemini-3.8-flash",temperature:0},reskin:{provider:"google-gemini",model:"gemini-3.8-flash"},"reskin-claude":{provider:"gw-anthropic",model:"claude-opus-5-5-nnyy-offical"}},tasks:{"synopsis.chunk":"synopsis","synopsis.episode":"synopsis","synopsis.arc":"synopsis","synopsis.script-overview":"synopsis","ingest.body-start":"ingest-low","ingest.arc-summary":"ingest-low","ingest.text-normalize":"ingest-low","ingest.mention-resolve":"ingest-low","ingest.asset-recall":"ingest-low","ingest.asset-audit":"ingest-normalize","ingest.episode-assets":"ingest-normalize","ingest.name-fix":"ingest-normalize","ingest.video-serial":"ingest-video","ingest.comic-serial":"ingest-comic"},source:"builtin",sourcePath:null};function XE(){let e=(process.env.PROJECT_LITELLM_GATEWAY_BASE_URL??"").trim(),t=e?Cd(e,"PROJECT_LITELLM_GATEWAY_BASE_URL"):null;return{...ei,providers:{gw:{...ei.providers.gw,baseUrl:t},"gw-anthropic":{...ei.providers["gw-anthropic"],baseUrl:t?t.replace(/\/v1\/?$/,""):null},"google-gemini":{...ei.providers["google-gemini"]},nnyyai:{...ei.providers.nnyyai}},models:{...ei.models},tasks:{...ei.tasks}}}function ex(){let e=(process.env.XDG_CONFIG_HOME??"").trim();return e?Jr.join(e,"scriptctl","llm.yaml"):Jr.join(Of.homedir(),".config","scriptctl","llm.yaml")}function Ud(e){if(!jr.existsSync(e))throw Oe("LLM configuration file does not exist.",[e]);let t=jE(jr.readFileSync(e,"utf-8"),{uniqueKeys:!0});if(t.errors.length>0)throw Oe("LLM configuration YAML is invalid.",t.errors.map(o=>o.message));let n=t.toJS();return WE(n,Jr.resolve(e))}function Ao(e){let t=(e??"").trim();if(t)return Ud(t);let n=(process.env.SCRIPTCTL_LLM_CONFIG??"").trim();if(n)return Ud(n);let o=ex();return jr.existsSync(o)?Ud(o):XE()}import*as Bf from"node:crypto";import*as Hd from"node:fs";import ox,{APIConnectionError as ix,APIConnectionTimeoutError as rx,APIError as sx,APIUserAbortError as ax}from"@anthropic-ai/sdk";var Vd=1e8;function tx(e){switch(e){case"auth":return{failure_type:"authentication",failure_code:"authentication_failed"};case"permission_denied":return{failure_type:"authorization",failure_code:"permission_denied"};case"endpoint":return{failure_type:"provider",failure_code:"resource_not_found"};case"network":return{failure_type:"network",failure_code:"network_failed"};case"timeout":return{failure_type:"timeout",failure_code:"request_timeout"};case"rate_limited":return{failure_type:"rate_limit",failure_code:"rate_limited"};case"request_failed":return{failure_type:"provider",failure_code:"request_rejected"};case"truncated":return{failure_type:"response",failure_code:"output_truncated"};case"content_filtered":return{failure_type:"policy",failure_code:"content_blocked"};case"empty_response":return{failure_type:"response",failure_code:"empty_response"};case"invalid_response":return{failure_type:"response",failure_code:"malformed_response"};case"cancelled":return{failure_type:"cancelled",failure_code:"cancelled"}}}var T=class extends Error{code;retryable;details;failure;modelFailures;attempts;usage;constructor(t,n,o={}){super(n),this.name="LlmTransportError",this.code=t,this.retryable=o.retryable??!1,this.details=o.details??[],this.attempts=o.attempts??1,this.usage=o.usage??{},this.failure=Ut(o.classification??tx(t),{retryable:this.retryable,message:n,...o.context,...this.details.length>0?{details:this.details}:{}}),this.modelFailures=o.modelFailures??[]}};function nx(e){return new Promise(t=>setTimeout(t,e))}function Xt(e={},t={}){let n=c=>e[c]===void 0&&t[c]===void 0?void 0:(e[c]??0)+(t[c]??0),o=n("inputTokens"),i=n("outputTokens"),r=n("cachedInputTokens"),s=n("cacheCreationTokens");return{...o!==void 0?{inputTokens:o}:{},...i!==void 0?{outputTokens:i}:{},...r!==void 0?{cachedInputTokens:r}:{},...s!==void 0?{cacheCreationTokens:s}:{}}}async function en(e,t){let n={};for(let o=1;o<=e;o+=1)try{return{value:await t(),attempts:o,failedUsage:n}}catch(i){if(i instanceof T&&(n=Xt(n,i.usage),i.attempts=o,i.usage=n),!(i instanceof T)||!i.retryable||o===e)throw i;await nx(Math.min(3e4,1e3*2**(o-1)))}throw new Error("unreachable retry state")}function vf(e){let t=e.usage;if(!t)return{};let n=t.cache_read_input_tokens??0,o=t.cache_creation_input_tokens??0;return{inputTokens:(t.input_tokens??0)+n+o,outputTokens:t.output_tokens??0,cachedInputTokens:n,cacheCreationTokens:o}}function Rf(e){if(e instanceof T)return e;if(e instanceof ax)return new T("request_failed","Anthropic request was aborted.");if(e instanceof rx)return new T("timeout","Anthropic request timed out.",{retryable:!0});if(e instanceof ix)return new T("request_failed","Anthropic connection failed.",{retryable:!0,details:[e.message.slice(0,500)]});if(e instanceof sx){let n=e.status??0,o=n===408||n===429||n>=500,i=n===401||n===403?"auth":n===429?"rate_limited":"request_failed";return new T(i,"Anthropic request failed.",{retryable:o,details:[`status: ${n}`,e.message.slice(0,500)]})}let t=e instanceof Error?e.message:String(e);return new T("request_failed","Anthropic request failed.",{details:[t.slice(0,500)]})}var Ws=class{constructor(t,n,o){this.provider=t;this.model=n;let i={apiKey:o};t.baseUrl&&(i.baseURL=t.baseUrl),this.client=new ox({...i,maxRetries:0})}provider;model;client;params(t){let n={model:this.model.model,max_tokens:t.maxOutputTokens,stream:!1,messages:[{role:"user",content:t.user}]};return t.system.trim()&&(n.system=t.system),this.model.thinkingBudgetTokens!==void 0&&(n.thinking={type:"enabled",budget_tokens:this.model.thinkingBudgetTokens}),n}async generateText(t){let n=await en(this.provider.maxAttempts,async()=>{try{let o=await this.client.messages.create(this.params(t),{timeout:this.provider.timeoutMs,signal:t.signal}),i=vf(o);if(o.stop_reason==="max_tokens")throw new T("truncated","Provider output was truncated.",{usage:i});if(o.stop_reason==="refusal")throw new T("content_filtered","Provider filtered the response.",{usage:i});let r=o.content.filter(s=>s.type==="text").map(s=>s.text).join(`
145
+ `).trim();if(!r)throw new T("empty_response","Provider returned an empty text response.",{usage:i});return{text:r,finishReason:o.stop_reason??"",usage:i,raw:o}}catch(o){throw Rf(o)}});return{...n.value,attempts:n.attempts,usage:Xt(n.failedUsage,n.value.usage)}}async generateTool(t){let n=await en(this.provider.maxAttempts,async()=>{try{let o={name:t.tool.name,description:t.tool.description,input_schema:{type:"object",...t.tool.inputSchema}},i=await this.client.messages.create({...this.params(t),tools:[o],tool_choice:{type:"tool",name:t.tool.name,disable_parallel_tool_use:!0}},{timeout:this.provider.timeoutMs,signal:t.signal}),r=vf(i);if(i.stop_reason==="max_tokens")throw new T("truncated","Provider tool output was truncated.",{usage:r});if(i.stop_reason==="refusal")throw new T("content_filtered","Provider filtered the response.",{usage:r});let s=i.content.find(c=>c.type==="tool_use"&&c.name===t.tool.name);if(!s||s.type!=="tool_use")throw new T("invalid_response","Provider did not return the required tool call.",{usage:r});return{input:s.input,finishReason:i.stop_reason??"",usage:r,raw:i}}catch(o){throw Rf(o)}});return{...n.value,attempts:n.attempts,usage:Xt(n.failedUsage,n.value.usage)}}};import*as Bd from"node:fs";import*as Jd from"node:path";import{File as fx}from"node:buffer";import{Agent as mx,fetch as ea,FormData as gx}from"undici";function cx(e){return typeof e=="object"&&e!==null}function $d(e){let t=[],n=new Set,o=e;for(;cx(o)&&!n.has(o);)n.add(o),t.push(o),o=o.cause;return t}function Xs(e){for(let t of $d(e)){if(typeof t.status=="number")return t.status;if(typeof t.statusCode=="number")return t.statusCode}return null}function dx(e){for(let t of $d(e))if(typeof t.code=="string")return t.code}function px(e){for(let t of $d(e))if(typeof t.name=="string")return t.name}function lx(e){let t=px(e);return t==="AbortError"||t==="TimeoutError"||t==="RequestTimeoutError"||t==="APIConnectionTimeoutError"}function ux(e){return e?["ENOTFOUND","EAI_AGAIN"].includes(e)?{failure_type:"network",failure_code:"dns_failed"}:e==="ECONNREFUSED"?{failure_type:"network",failure_code:"connection_refused"}:["ECONNRESET","EPIPE","UND_ERR_SOCKET"].includes(e)?{failure_type:"network",failure_code:"connection_reset"}:["ENETUNREACH","EHOSTUNREACH"].includes(e)?{failure_type:"network",failure_code:"network_unreachable"}:e.startsWith("ERR_TLS_")||e.startsWith("ERR_SSL_")||e.startsWith("CERT_")||["DEPTH_ZERO_SELF_SIGNED_CERT","SELF_SIGNED_CERT_IN_CHAIN","UNABLE_TO_VERIFY_LEAF_SIGNATURE"].includes(e)?{failure_type:"network",failure_code:"tls_failed"}:["ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT"].includes(e)?{failure_type:"timeout",failure_code:"connect_timeout"}:{failure_type:"network",failure_code:"network_failed"}:{failure_type:"network",failure_code:"network_failed"}}function ti(e,t,n,o,i={}){if(t?.aborted)return new T("cancelled",n,{details:[o],classification:{failure_type:"cancelled",failure_code:"cancelled"},context:i});let r=dx(e),s=lx(e)?{failure_type:"timeout",failure_code:"request_timeout"}:ux(r),c=s.failure_type==="timeout"?"timeout":"network";return new T(c,n,{retryable:!0,details:[o],classification:s,context:{...i,...r?{system_code:r}:{}}})}function ni(e,t,n,o={}){let i,r,s=!1;return e===401?(i="auth",r={failure_type:"authentication",failure_code:"authentication_failed"}):e===403?(i="permission_denied",r={failure_type:"authorization",failure_code:"permission_denied"}):e===404?(i="endpoint",r={failure_type:"provider",failure_code:"resource_not_found"}):e===408?(i="timeout",r={failure_type:"timeout",failure_code:"request_timeout"},s=!0):e===413&&o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"media_too_large"}):e===415&&o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"unsupported_media"}):e===429?(i="rate_limited",r={failure_type:"rate_limit",failure_code:"rate_limited"},s=!0):e>=500?(i="request_failed",r={failure_type:"provider",failure_code:"provider_unavailable"},s=!0):o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"media_upload_failed"}):(i="request_failed",r={failure_type:"provider",failure_code:"request_rejected"}),new T(i,t,{retryable:s,details:[`status: ${e}`,n],classification:r,context:{...o,http_status:e}})}var hx=2e3;function yx(e){return new Promise(t=>setTimeout(t,e))}function Dd(e,t,n,o){if(e instanceof T)return e;let i=e instanceof Error?e.message:String(e),r=Xs(e),s={provider:"doubao",model:o,operation:n};return r!==null?ni(r,`Doubao ${n} failed.`,i.slice(0,500),s):ti(e,t,`Doubao ${n} failed.`,i.slice(0,500),s)}function wx(e){if(!e)return{};let t=n=>typeof n=="number"?n:void 0;return{inputTokens:t(e.input_tokens),outputTokens:t(e.output_tokens)}}function _x(e){let t=[];for(let n of e.output??[])if(n.type==="message")for(let o of n.content??[])o.type==="output_text"&&typeof o.text=="string"&&t.push(o.text);return t.join("").trim()}var ta=class{constructor(t,n,o,i,r,s){this.model=t;this.timeoutMs=n;this.maxAttempts=o;this.client=s??Ex(i,r,n)}model;timeoutMs;maxAttempts;client;async run(t){let{value:n}=await en(this.maxAttempts,async()=>{try{return await this.client.uploadFile({filePath:t.localPath,mimeType:t.localMime,fps:t.fps})}catch(i){throw Dd(i,t.signal,"upload",this.model)}});if(!n.id)throw new T("invalid_response","Doubao upload returned no file id.");let o=await this.pollActive(n.id,t.signal);try{return await this.generateOnce(o,t)}finally{await this.client.deleteFile({id:o}).catch(()=>{})}}async pollActive(t,n){let o=Date.now()+this.timeoutMs,i="processing";for(;i==="processing"||i==="";){if(n?.aborted)throw new T("cancelled","Doubao upload aborted.",{context:{provider:"doubao",model:this.model,operation:"file_poll"}});if(Date.now()>=o)throw new T("timeout","Doubao file processing timed out.",{retryable:!0,classification:{failure_type:"timeout",failure_code:"media_processing_timeout"},context:{provider:"doubao",model:this.model,operation:"file_poll"}});await yx(hx);let r;try{r=await this.client.getFile({id:t})}catch(s){throw Dd(s,n,"file_poll",this.model)}i=(r.status??"").toLowerCase()}if(i==="failed"||i==="error")throw new T("invalid_response","Doubao file processing failed.",{classification:{failure_type:"media",failure_code:"media_processing_failed"},context:{provider:"doubao",model:this.model,operation:"file_poll"}});return t}async generateOnce(t,n){let o={model:this.model,input:[{role:"user",content:[{type:"input_video",file_id:t},{type:"input_text",text:n.user}]}]};return n.system?.trim()&&(o.instructions=n.system),n.responseJsonSchema&&(o.text={format:{type:"json_schema",name:"video_serial",schema:n.responseJsonSchema}}),this.generateResponse(o,n.signal,!!n.responseJsonSchema,n.acceptsText)}async generateText(t){let n=this.textParams(t);return t.responseFormat&&(n.text={format:{type:t.responseFormat}}),this.generateResponse(n,t.signal,!!t.responseFormat)}async generateDocument(t,n){let o=t.media.kind==="base64"?t.media.data:n?Bd.readFileSync(n).toString("base64"):void 0;if(!o)throw new T("invalid_response","Doubao PDF recovery requires the original document bytes.");let i={model:this.model,input:[{role:"user",content:[{type:"input_file",filename:n?Jd.basename(n):"document.pdf",file_data:`data:application/pdf;base64,${o}`},{type:"input_text",text:t.user}]}]};return t.system?.trim()&&(i.instructions=t.system),t.responseJsonSchema&&(i.text={format:{type:"json_schema",name:"document",schema:t.responseJsonSchema}}),this.generateResponse(i,t.signal,!!t.responseJsonSchema)}async generateTool(t){let n=this.textParams(t);n.text={format:{type:"json_schema",name:t.tool.name,description:t.tool.description,schema:t.tool.inputSchema}};let o=await this.generateResponse(n,t.signal,!0);return{input:JSON.parse(o.text),finishReason:o.finishReason,attempts:o.attempts,usage:o.usage,raw:o.raw}}textParams(t){return{model:this.model,instructions:t.system,input:[{role:"user",content:[{type:"input_text",text:t.user}]}]}}async generateResponse(t,n,o,i){let{value:r,attempts:s,failedUsage:c}=await en(this.maxAttempts,async()=>{let a;try{a=await this.client.createResponse(t,n)}catch(f){throw Dd(f,n,"generate",this.model)}let d=(a.status??"").toLowerCase(),p=wx(a.usage);if(d==="incomplete"){let f=a.incomplete_details?.reason??"unknown";throw f==="max_output_tokens"||f==="length"?new T("truncated","Doubao output was truncated.",{usage:p}):new T("content_filtered",`Doubao response incomplete (reason=${f}).`,{usage:p})}let l=_x(a);if(!l)throw new T("empty_response","Doubao returned an empty response.",{retryable:!0,usage:p});if(i&&!i(l))throw new T("invalid_response","Doubao response does not match the requested output format.",{retryable:!0,usage:p,context:{provider:"doubao",model:this.model,operation:"generate"}});if(o)try{JSON.parse(l)}catch{throw new T("invalid_response","Doubao returned malformed JSON for a structured response.",{retryable:!0,usage:p,context:{provider:"doubao",model:this.model,operation:"generate"}})}return{text:l,usage:p,raw:a}});return{text:r.text,finishReason:"STOP",attempts:s,usage:Xt(c,r.usage),raw:r.raw}}},Gd=class extends Error{constructor(n,o){super(o);this.status=n;this.name="HttpError"}status};function Ex(e,t,n){let o=t.replace(/\/$/,""),i={Authorization:`Bearer ${e}`},r=new mx({headersTimeout:n,bodyTimeout:n});function s(a){let d=AbortSignal.timeout(n);return a?AbortSignal.any([a,d]):d}async function c(a){let d=await a.text().catch(()=>"");throw new Gd(a.status,d.slice(0,500))}return{async uploadFile({filePath:a,mimeType:d,fps:p}){let l=new gx,f=Bd.readFileSync(a);l.append("file",new fx([f],Jd.basename(a),{type:d})),l.append("purpose","user_data"),l.append("preprocess_configs[video][fps]",String(p));let u=await ea(`${o}/files`,{method:"POST",headers:i,body:l,signal:s(),dispatcher:r});return u.ok||await c(u),await u.json()},async getFile({id:a}){let d=await ea(`${o}/files/${a}`,{headers:i,signal:s(),dispatcher:r});return d.ok||await c(d),await d.json()},async createResponse(a,d){let p=await ea(`${o}/responses`,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify(a),signal:s(d),dispatcher:r});return p.ok||await c(p),await p.json()},async deleteFile({id:a}){let d=await ea(`${o}/files/${a}`,{method:"DELETE",headers:i,signal:s(),dispatcher:r});d.ok||await c(d)}}}import{GoogleAuth as xx}from"google-auth-library";function na(){let e=process.env.GOOGLE_CLOUD_PROJECT?.trim();if(!e)throw new Error("GOOGLE_CLOUD_PROJECT is required for official Vertex AI");return e}var Mf=new xx({scopes:["https://www.googleapis.com/auth/cloud-platform"]});import*as Cf from"node:fs";import{createRequire as Rx}from"node:module";import*as oa from"node:fs";import*as Sx from"node:http";import*as Ix from"node:https";import{HttpsProxyAgent as Ax}from"https-proxy-agent";var Lf="https://generativelanguage.googleapis.com";function kx(e,t){let n=new URL(e??Lf);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/upload/v1beta/files`,n.searchParams.set("key",t),n}function bx(e,t){let n=new URL(t??Lf),o=new URL(e,n);if(!t)return o;o.protocol=n.protocol,o.host=n.host;let i=n.pathname.replace(/\/+$/,"");return i&&o.pathname!==i&&!o.pathname.startsWith(`${i}/`)&&(o.pathname=`${i}/${o.pathname.replace(/^\/+/,"")}`),o}function zi(e,t){if(!t)return e;let n=e.split(t).join("[REDACTED]"),o=encodeURIComponent(t);return o!==t&&(n=n.split(o).join("[REDACTED]")),n}function Ox(e){return e?new Ax(e):void 0}function Nf(e,t,n,o){return new Promise((i,r)=>{let c=(e.protocol==="http:"?Sx:Ix).request({...t,agent:e.protocol==="https:"?t.agent:void 0,protocol:e.protocol,hostname:e.hostname,port:e.port||void 0,path:`${e.pathname}${e.search}`},a=>{let d="";a.on("data",p=>d+=p),a.on("end",()=>i({status:a.statusCode??0,headers:a.headers,body:d}))});if(c.on("error",r),o){if(o.aborted){c.destroy(new Error("aborted"));return}o.addEventListener("abort",()=>c.destroy(new Error("aborted")),{once:!0})}n&&typeof n.pipe=="function"?n.pipe(c):(n&&c.write(n),c.end())})}function vx(e,t){let n=e[t];return Array.isArray(n)?n[0]??"":n??""}async function Uf(e){let t=oa.statSync(e.filePath).size,o={agent:Ox(e.proxyUrl??""),timeout:e.timeoutMs},i=kx(e.baseUrl,e.apiKey),r=l=>zi(l,e.apiKey),s;try{s=await Nf(i,{...o,method:"POST",headers:{"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":String(t),"X-Goog-Upload-Header-Content-Type":e.mimeType,"Content-Type":"application/json"}},JSON.stringify({file:{}}),e.signal)}catch(l){let f=r(l instanceof Error?l.message:String(l));throw ti(l,e.signal,"Gemini upload start failed.",f,{operation:"upload"})}let c=vx(s.headers,"x-goog-upload-url");if(s.status<200||s.status>=300)throw ni(s.status,"Gemini upload start failed.",r(s.body).slice(0,300),{operation:"upload"});if(!c)throw new T("invalid_response","Gemini upload start returned no upload URL.",{details:[r(s.body).slice(0,300)],context:{operation:"upload",http_status:s.status}});let a=bx(c,e.baseUrl),d;try{d=await Nf(a,{...o,method:"POST",headers:{"Content-Length":String(t),"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"}},oa.createReadStream(e.filePath),e.signal)}catch(l){let f=r(l instanceof Error?l.message:String(l));throw ti(l,e.signal,"Gemini upload transfer failed.",f,{operation:"upload"})}if(d.status<200||d.status>=300)throw ni(d.status,"Gemini upload transfer failed.",r(d.body).slice(0,300),{operation:"upload"});let p;try{p=JSON.parse(d.body)}catch{throw new T("invalid_response","Gemini upload returned invalid JSON.",{details:[r(d.body).slice(0,300)]})}if(!p.file)throw new T("invalid_response","Gemini upload returned no file.",{details:[r(d.body).slice(0,300)]});return p.file}var Mx=new Set(["SAFETY","PROHIBITED_CONTENT","RECITATION","BLOCKLIST","SPII","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION"]),Nx=new Set(["LANGUAGE","OTHER","MALFORMED_FUNCTION_CALL","IMAGE_OTHER","NO_IMAGE","UNEXPECTED_TOOL_CALL","TOO_MANY_TOOL_CALLS","MISSING_THOUGHT_SIGNATURE","MALFORMED_RESPONSE"]);function Kd(e){switch(e){case"SAFETY":case"PROHIBITED_CONTENT":case"BLOCKLIST":case"SPII":case"RECITATION":case"IMAGE_SAFETY":case"IMAGE_PROHIBITED_CONTENT":case"IMAGE_RECITATION":case"ESCALATION":case"OTHER":return e;case"":case"BLOCK_REASON_UNSPECIFIED":case"FINISH_REASON_UNSPECIFIED":return"UNSPECIFIED";default:return"UNKNOWN"}}function Pf(e){if(e?.length)return e.map(t=>({category:t.category??"UNSPECIFIED",probability:t.probability??"UNSPECIFIED",blocked:t.blocked??!1}))}function Lx(e){if(typeof e!="object"||e===null)return{};let t=e,n=o=>typeof o=="number"?o:void 0;return{inputTokens:n(t.promptTokenCount),outputTokens:n(t.candidatesTokenCount)}}function Ux(e){return/-c\d+$/.test(e)}function Px(e){let t=e.indexOf("{"),n=e.lastIndexOf("}");if(t<0||n<t)throw new SyntaxError("JSON object not found");return e.slice(t,n+1)}var Cx=2e3;function Tx(e){return new Promise(t=>setTimeout(t,e))}function jd(e,t,n,o,i,r){if(e instanceof T)return new T(e.code,zi(e.message,o),{retryable:e.retryable,details:e.details.map(d=>zi(d,o)),attempts:e.attempts,usage:e.usage,classification:Li(e.failure),context:{...Ar(e.failure),provider:i,model:r,operation:n},modelFailures:e.modelFailures});let s=zi(e instanceof Error?e.message:String(e),o),c=Xs(e),a={provider:i,model:r,operation:n};return c!==null?ni(c,`Gemini ${n} failed.`,s.slice(0,500),a):ti(e,t,`Gemini ${n} failed.`,s.slice(0,500),a)}var Hi=class{constructor(t,n,o,i){this.provider=t;this.model=n;this.apiKey=o;this.client=i??$x(o,t.timeoutMs,t.baseUrl,t.protocol==="google-vertex")}provider;model;apiKey;client;async prepare(t,n,o,i){return o==="base64"||this.provider.protocol==="google-vertex"?{kind:"base64",data:Cf.readFileSync(t,"base64"),mimeType:n}:{kind:"file-api",file:await this.uploadFile(t,n,i)}}async uploadFile(t,n,o){let{value:i}=await en(this.provider.maxAttempts,async()=>{try{return await this.client.files.upload({file:t,config:{mimeType:n}})}catch(s){throw jd(s,o,"upload",this.apiKey,this.model.provider,this.model.model)}}),r=await this.pollActive(i,o);if(!r.name||!r.uri)throw new T("invalid_response","Gemini upload returned no file reference.",{context:{provider:this.model.provider,model:this.model.model,operation:"upload"}});return{name:r.name,uri:r.uri,mimeType:r.mimeType??n}}async pollActive(t,n){let o=t,i=Date.now()+this.provider.timeoutMs;for(;(o.state??"").toUpperCase()==="PROCESSING";){if(n?.aborted)throw new T("cancelled","Gemini upload aborted.",{context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});if(Date.now()>=i)throw new T("timeout","Gemini file processing timed out.",{retryable:!0,classification:{failure_type:"timeout",failure_code:"media_processing_timeout"},context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});if(await Tx(Cx),!o.name)throw new T("invalid_response","Gemini upload returned no file name to poll.",{context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});try{o=await this.client.files.get({name:o.name})}catch(r){throw jd(r,n,"file_poll",this.apiKey,this.model.provider,this.model.model)}}if((o.state??"").toUpperCase()==="FAILED")throw new T("invalid_response","Gemini file processing failed.",{details:[zi(o.error?.message??"unknown media error",this.apiKey)],classification:{failure_type:"media",failure_code:"media_processing_failed"},context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});return o}async generateMedia(t,n){let o=!!t.responseJsonSchema&&Ux(this.model.model),i={mediaResolution:"MEDIA_RESOLUTION_HIGH"},r=[t.system?.trim(),o?`\u8F93\u51FA\u5FC5\u987B\u662F\u4E00\u4E2A\u53EF\u89E3\u6790\u7684 JSON \u5BF9\u8C61\u3002\u53EA\u8FD4\u56DE JSON\uFF0C\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u989D\u5916\u6587\u5B57\u6216 Markdown \u4EE3\u7801\u5757\u3002
146
146
  \u4EE5\u4E0B\u662F\u5B8C\u6574\u8F93\u51FA JSON Schema\u3002\u4E25\u683C\u9075\u5B88\u6240\u6709\u5C42\u7EA7\u7684\u5B57\u6BB5\u540D\u3001\u7C7B\u578B\u3001required\u3001\u679A\u4E3E\u3001\u683C\u5F0F\u7EA6\u675F\u548C description\uFF1B\u4E0D\u5F97\u81EA\u884C\u6539\u540D\u6216\u7701\u7565\u5FC5\u586B\u5B57\u6BB5\u3002\u8FD4\u56DE\u7B26\u5408\u8BE5\u5B9A\u4E49\u7684\u6570\u636E\u5BF9\u8C61\uFF0C\u4E0D\u8981\u8FD4\u56DE schema \u672C\u8EAB\u3002
147
147
  <output_json_schema>
148
148
  ${JSON.stringify(t.responseJsonSchema,null,2)}
@@ -150,127 +150,128 @@ ${JSON.stringify(t.responseJsonSchema,null,2)}
150
150
 
151
151
  `);if(r&&(i.systemInstruction=r),t.responseJsonSchema&&!o){i.responseMimeType="application/json";let p=n?this.provider.videoResponseSchemaField:this.provider.documentResponseSchemaField;i[p??"responseJsonSchema"]=t.responseJsonSchema}let s={model:this.model.model,contents:[{role:"user",parts:[t.media.kind==="file-api"?{fileData:{fileUri:t.media.file.uri,mimeType:t.media.file.mimeType},...n?{videoMetadata:n}:{}}:{inlineData:{data:t.media.data,mimeType:t.media.mimeType},...n?{videoMetadata:n}:{}},{text:o?`${t.user}
152
152
 
153
- \u53EA\u8FD4\u56DE JSON \u5BF9\u8C61\u672C\u8EAB\uFF0C\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u89E3\u91CA\u3001\u524D\u8A00\u3001Markdown \u4EE3\u7801\u5757\u6216\u5176\u4ED6\u6587\u5B57\u3002`:t.user}]}],config:i},{value:c,attempts:a,failedUsage:d}=await en(this.provider.maxAttempts,async()=>{let p;try{if(this.client.models.generateContentStream){let w="",y={},_=await this.client.models.generateContentStream(s);for await(let x of _)x.text&&(w+=x.text),y={...y,...x,usageMetadata:x.usageMetadata??y.usageMetadata,promptFeedback:x.promptFeedback??y.promptFeedback,candidates:x.candidates??y.candidates};p={...y,text:w}}else p=await this.client.models.generateContent(s)}catch(w){throw Jd(w,t.signal,"generate",this.apiKey,this.model.provider,this.model.model)}let l=p.candidates?.[0],f=l?.finishReason??"",u=p.promptFeedback?.blockReason??"",g=Rx(p.usageMetadata),h={provider:this.model.provider,model:this.model.model,operation:"generate"};if(f==="MAX_TOKENS")throw new T("truncated","Gemini output was truncated.",{usage:g,context:h});if(u)throw new T("content_filtered",`Gemini blocked the prompt (blockReason=${u}).`,{usage:g,classification:{failure_type:"policy",failure_code:"content_blocked"},context:{...h,provider_source:"prompt",provider_reason:Bd(u),...Bd(u)==="UNKNOWN"?{provider_reason_raw:u}:{},safety_ratings:Lf(p.promptFeedback?.safetyRatings)}});if(Ox.has(f))throw new T("content_filtered",`Gemini filtered the response (finishReason=${f}).`,{usage:g,classification:{failure_type:"policy",failure_code:"content_blocked"},context:{...h,provider_source:"candidate",provider_reason:Bd(f),finish_message:l?.finishMessage,safety_ratings:Lf(l?.safetyRatings)}});let m=(p.text??"").trim();if(!m)throw vx.has(f)?new T("invalid_response",`Gemini returned no usable response (finishReason=${f}).`,{usage:g,context:{...h,provider_reason_raw:f,finish_message:l?.finishMessage}}):new T("empty_response",`Gemini returned an empty response (finishReason=${f||"none"}).`,{retryable:!0,usage:g,context:h});if(t.acceptsText&&!t.acceptsText(m))throw new T("invalid_response","Gemini response does not match the requested output format.",{retryable:!0,usage:g,context:{...h,provider_reason_raw:m.slice(0,200)}});if(!f)throw new T("invalid_response","Gemini stream ended before the response finished.",{retryable:!0,usage:g,context:{...h,provider_reason_raw:"missing_finish_reason"}});if(t.responseJsonSchema)try{let w=o?Nx(m):m;return JSON.parse(w),{text:w,finishReason:f,usage:g,raw:p}}catch{throw new T("invalid_response","Gemini returned malformed JSON for a structured media response.",{retryable:!0,usage:g,context:h})}return{text:m,finishReason:f,usage:g,raw:p}});return{text:c.text,finishReason:c.finishReason,attempts:a,usage:Xt(d,c.usage),raw:c.raw}}async release(t,n){if(!(t.kind==="base64"||t.kind==="local-fallback"||t.kind==="local"))try{await this.client.files.delete({name:t.file.name})}catch(o){}}},Px=bx(import.meta.url);function Cx(e,t,n,o){let{GoogleGenAI:i}=Px("@google/genai"),r=new i({...o?{vertexai:!0,project:ta(),location:"global"}:{apiKey:e},httpOptions:{timeout:t,...n?{baseUrl:n}:{}}}),s=(process.env.https_proxy??process.env.HTTPS_PROXY??process.env.http_proxy??process.env.HTTP_PROXY??"").trim();return s&&!(process.env.NODE_USE_ENV_PROXY??"").trim()&&process.stderr.write(`\u26A0\uFE0F \u68C0\u6D4B\u5230\u4EE3\u7406 ${s}\uFF0C\u4F46\u672A\u8BBE NODE_USE_ENV_PROXY=1\u3002
153
+ \u53EA\u8FD4\u56DE JSON \u5BF9\u8C61\u672C\u8EAB\uFF0C\u4E0D\u8981\u8F93\u51FA\u4EFB\u4F55\u89E3\u91CA\u3001\u524D\u8A00\u3001Markdown \u4EE3\u7801\u5757\u6216\u5176\u4ED6\u6587\u5B57\u3002`:t.user}]}],config:i},{value:c,attempts:a,failedUsage:d}=await en(this.provider.maxAttempts,async()=>{let p;try{if(this.client.models.generateContentStream){let w="",y={},_=await this.client.models.generateContentStream(s);for await(let S of _)S.text&&(w+=S.text),y={...y,...S,usageMetadata:S.usageMetadata??y.usageMetadata,promptFeedback:S.promptFeedback??y.promptFeedback,candidates:S.candidates??y.candidates};p={...y,text:w}}else p=await this.client.models.generateContent(s)}catch(w){throw jd(w,t.signal,"generate",this.apiKey,this.model.provider,this.model.model)}let l=p.candidates?.[0],f=l?.finishReason??"",u=p.promptFeedback?.blockReason??"",m=Lx(p.usageMetadata),h={provider:this.model.provider,model:this.model.model,operation:"generate"};if(f==="MAX_TOKENS")throw new T("truncated","Gemini output was truncated.",{usage:m,context:h});if(u)throw new T("content_filtered",`Gemini blocked the prompt (blockReason=${u}).`,{usage:m,classification:{failure_type:"policy",failure_code:"content_blocked"},context:{...h,provider_source:"prompt",provider_reason:Kd(u),...Kd(u)==="UNKNOWN"?{provider_reason_raw:u}:{},safety_ratings:Pf(p.promptFeedback?.safetyRatings)}});if(Mx.has(f))throw new T("content_filtered",`Gemini filtered the response (finishReason=${f}).`,{usage:m,classification:{failure_type:"policy",failure_code:"content_blocked"},context:{...h,provider_source:"candidate",provider_reason:Kd(f),finish_message:l?.finishMessage,safety_ratings:Pf(l?.safetyRatings)}});let g=(p.text??"").trim();if(!g)throw Nx.has(f)?new T("invalid_response",`Gemini returned no usable response (finishReason=${f}).`,{usage:m,context:{...h,provider_reason_raw:f,finish_message:l?.finishMessage}}):new T("empty_response",`Gemini returned an empty response (finishReason=${f||"none"}).`,{retryable:!0,usage:m,context:h});if(t.acceptsText&&!t.acceptsText(g))throw new T("invalid_response","Gemini response does not match the requested output format.",{retryable:!0,usage:m,context:{...h,provider_reason_raw:g.slice(0,200)}});if(!f)throw new T("invalid_response","Gemini stream ended before the response finished.",{retryable:!0,usage:m,context:{...h,provider_reason_raw:"missing_finish_reason"}});if(t.responseJsonSchema)try{let w=o?Px(g):g;return JSON.parse(w),{text:w,finishReason:f,usage:m,raw:p}}catch{throw new T("invalid_response","Gemini returned malformed JSON for a structured media response.",{retryable:!0,usage:m,context:h})}return{text:g,finishReason:f,usage:m,raw:p}});return{text:c.text,finishReason:c.finishReason,attempts:a,usage:Xt(d,c.usage),raw:c.raw}}async release(t,n){if(!(t.kind==="base64"||t.kind==="local-fallback"||t.kind==="local"))try{await this.client.files.delete({name:t.file.name})}catch(o){}}},Vx=Rx(import.meta.url);function $x(e,t,n,o){let{GoogleGenAI:i}=Vx("@google/genai"),r=new i({...o?{vertexai:!0,project:na(),location:"global"}:{apiKey:e},httpOptions:{timeout:t,...n?{baseUrl:n}:{}}}),s=(process.env.https_proxy??process.env.HTTPS_PROXY??process.env.http_proxy??process.env.HTTP_PROXY??"").trim();return s&&!(process.env.NODE_USE_ENV_PROXY??"").trim()&&process.stderr.write(`\u26A0\uFE0F \u68C0\u6D4B\u5230\u4EE3\u7406 ${s}\uFF0C\u4F46\u672A\u8BBE NODE_USE_ENV_PROXY=1\u3002
154
154
  Gemini \u4E0A\u4F20\u4F1A\u6210\u529F\u3001\u968F\u540E\u7684\u6587\u4EF6\u8F6E\u8BE2/\u751F\u6210\u4F1A\u6302\uFF08Node \u5185\u7F6E fetch \u9ED8\u8BA4\u4E0D\u8D70\u4EE3\u7406\uFF09\u3002
155
155
  \u8BF7\u5728\u547D\u4EE4\u524D\u52A0 NODE_USE_ENV_PROXY=1 \u91CD\u8DD1\u3002
156
- `),{files:{upload:c=>Nf({apiKey:e,filePath:c.file,mimeType:c.config?.mimeType??"video/mp4",timeoutMs:t,proxyUrl:s,baseUrl:n}),get:c=>r.files.get(c),delete:c=>r.files.delete(c)},models:{generateContent:c=>r.models.generateContent(c),generateContentStream:c=>r.models.generateContentStream(c)}}}var jr=class{constructor(t,n,o,i){this.provider=t;this.transport=new zi(t,n,o,i)}provider;transport;prepare(t,n){return this.transport.prepare(t,"application/pdf",this.provider.documentUploadMode??"file-api",n)}generate(t){return this.transport.generateMedia(t)}release(t,n){return this.transport.release(t,n)}};var oa=class extends zi{generate(t){let n=t.media;if(n.kind==="local-fallback"||n.kind==="local")throw new T("invalid_response","A local fallback video cannot be sent to Gemini.");return this.generateMedia({...t,media:n},{fps:t.fps})}};function Pf(e,t){if(!Fn(e)||!Fn(e.usage))return{};let n=e.usage,o=a=>{let d=typeof a=="number"?a:0;return Number.isFinite(d)?d:0},i=Fn(n.prompt_tokens_details)?n.prompt_tokens_details:{},r=o(n.prompt_tokens),s=o(i.cached_tokens)||o(n.cache_read_input_tokens),c=o(i.cache_creation_tokens)||o(n.cache_creation_input_tokens);return{inputTokens:t?r:r+s+c,outputTokens:o(n.completion_tokens),cachedInputTokens:s,cacheCreationTokens:c}}function Fn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tx(e){let t=e.trim().replace(/\/+$/,"");return t.endsWith("/chat/completions")?t:t.endsWith("/v1")?`${t}/chat/completions`:`${t}/v1/chat/completions`}function Cf(e){return!Fn(e)||!Array.isArray(e.choices)?null:e.choices.find(Fn)??null}function Tf(e){return e&&typeof e.finish_reason=="string"?e.finish_reason:""}function $f(e){return e&&Fn(e.message)?e.message:null}function Vx(e){let t=$f(e)?.content;return typeof t=="string"?t.trim():Array.isArray(t)?t.flatMap(n=>Fn(n)&&typeof n.text=="string"?[n.text]:[]).join(`
157
- `).trim():""}function Vf(e){try{return JSON.parse(e)}catch{throw new T("invalid_response","Provider returned invalid JSON.",{details:[e.slice(0,500)]})}}var ia=class{constructor(t,n,o){this.provider=t;this.model=n;this.apiKey=o;if(!t.baseUrl&&t.protocol!=="google-vertex")throw new T("endpoint","OpenAI-compatible provider endpoint (baseUrl) is not set \u2014 the built-in gateway reads PROJECT_LITELLM_GATEWAY_BASE_URL.");this.url=t.protocol==="google-vertex"?`https://aiplatform.googleapis.com/v1/projects/${ta()}/locations/global/endpoints/openapi/chat/completions`:Tx(t.baseUrl);try{this.host=new URL(this.url).host}catch{this.host=this.url}}provider;model;apiKey;url;host;async post(t,n){let o=await en(this.provider.maxAttempts,async()=>{let i=AbortSignal.timeout(this.provider.timeoutMs),r=n?AbortSignal.any([n,i]):i,s;try{s=await fetch(this.url,{method:"POST",headers:{authorization:`Bearer ${this.provider.protocol==="google-vertex"?await vf.getAccessToken():this.apiKey}`,"content-type":"application/json"},body:JSON.stringify(t),signal:r})}catch(a){let d=a instanceof Error?a.message:String(a),p=r.aborted&&!n?.aborted;throw new T(p?"timeout":"request_failed",p?`OpenAI-compatible request timed out reaching ${this.host}.`:`OpenAI-compatible request could not reach ${this.host}: ${d}`,{retryable:!n?.aborted,details:[d.slice(0,500)]})}let c=await s.text();if(!s.ok){let a=s.status===408||s.status===429||s.status>=500,d=s.status===401||s.status===403?"auth":s.status===429?"rate_limited":"request_failed";throw new T(d,`OpenAI-compatible request to ${this.host} failed (status ${s.status}).`,{retryable:a,details:[`status: ${s.status}`,c.slice(0,500)]})}return Vf(c)});return{payload:o.value,attempts:o.attempts,failedUsage:o.failedUsage}}baseBody(t){let n=[];return t.system.trim()&&n.push({role:"system",content:t.system}),n.push({role:"user",content:t.user}),{model:this.provider.protocol==="google-vertex"?`google/${this.model.model.replace(/^google\//,"")}`:this.model.model,messages:n,...t.responseFormat==="json_object"?{response_format:{type:"json_object"}}:{},...this.model.reasoning?{reasoning_effort:this.model.reasoning}:{},...this.model.temperature!==void 0?{temperature:this.model.temperature}:{}}}async generateText(t){let{payload:n,attempts:o,failedUsage:i}=await this.post(this.baseBody(t),t.signal),r=Xt(i,Pf(n,this.provider.protocol==="google-vertex"));try{let s=Cf(n),c=Tf(s);if(c==="length")throw new T("truncated","Provider output was truncated.");if(c==="content_filter"||c.startsWith("content_filter:"))throw new T("content_filtered",`Provider filtered the response (${c}).`);let a=Vx(s);if(!a)throw new T("empty_response","Provider returned an empty text response.");return{text:a,finishReason:c,attempts:o,usage:r,raw:n}}catch(s){throw s instanceof T&&(s.attempts=o,s.usage=r),s}}async generateTool(t){let{payload:n,attempts:o,failedUsage:i}=await this.post({...this.baseBody(t),tools:[{type:"function",function:{name:t.tool.name,description:t.tool.description,parameters:t.tool.inputSchema}}],tool_choice:{type:"function",function:{name:t.tool.name}},parallel_tool_calls:!1},t.signal),r=Xt(i,Pf(n,this.provider.protocol==="google-vertex"));try{let s=Cf(n),c=Tf(s);if(c==="length")throw new T("truncated","Provider tool output was truncated.");if(c==="content_filter"||c.startsWith("content_filter:"))throw new T("content_filtered",`Provider filtered the response (${c}).`);let a=$f(s)?.tool_calls;if(!Array.isArray(a))throw new T("invalid_response","Provider did not return a tool call.");for(let d of a){if(!Fn(d)||!Fn(d.function))continue;let p=d.function;if(!(p.name!==t.tool.name||typeof p.arguments!="string"))return{input:Vf(p.arguments),finishReason:c,attempts:o,usage:r,raw:n}}throw new T("invalid_response","Provider did not return the required tool call.")}catch(s){throw s instanceof T&&(s.attempts=o,s.usage=r),s}}};var kn={model:"ep-20260721150136-98dj9",modelEnv:"ARK_MODEL",baseUrl:"https://ark.cn-beijing.volces.com/api/v3",apiKeyEnv:"ARK_API_KEY",timeoutMs:6e5,maxAttempts:3},$x=["gemini-3.8-flash","gemini-3.7-flash","gemini-3.6-flash"];function Dx(e){return e?.trim().replace(/\/+$/,"")??"anthropic-sdk-default"}function Kd(e,t,n){let o=An[e],i=JSON.stringify({task:e,taskVersion:o.version,protocol:t.protocol,baseUrl:Dx(t.baseUrl),model:n.model,thinkingBudgetTokens:n.thinkingBudgetTokens??null,...o.mode==="video"&&t.videoResponseSchemaField==="responseSchema"?{videoResponseSchemaField:t.videoResponseSchemaField}:{},...o.mode==="document"&&t.documentResponseSchemaField==="responseSchema"?{documentResponseSchemaField:t.documentResponseSchemaField}:{}});return Df.createHash("sha256").update(i).digest("hex")}function Je(e,t,n){return new S(e,{exitCode:k,errorCode:"LLM_CONFIG_INVALID",hint:"Fix the selected LLM configuration and run `scriptctl doctor`.",data:{expected:t,actual:n}})}function Hi(e){return new S("The selected LLM provider credential is not configured.",{exitCode:ee,errorCode:"LLM_CREDENTIAL_MISSING",hint:"Configure the credential and rerun `scriptctl doctor`.",data:{expected:["credential environment variable referenced by the selected provider"],actual:[`provider: ${e}`,"credential: missing"]}})}function oi(e,t){return Ut(Ni(e.failure),{...Sr(e.failure),provider:t.provider,model:t.model,retryable:e.failure.retryable,message:e.message})}function Fi(e,t){if(t.length===1)return e;let n=ru(t,"All configured model routes failed.");return new T(e.code,n.message,{retryable:n.retryable,classification:Ni(n),context:Sr(n),modelFailures:t,details:t.map(hn)})}function Gx(e){return["google-gemini","google-vertex"].includes(e.protocol)||/(^|\/)gemini-/i.test(e.model)}function jd(e){let t=e.info.model.slice(0,e.info.model.lastIndexOf("/")+1);return[...new Set([e.info.model,...$x.map(o=>t+o)])].map(o=>{if(o===e.info.model)return e;let i={...e.modelConfig,model:o};return{...e,modelConfig:i,info:{...e.info,model:o,fingerprint:Kd(e.info.task,e.providerConfig,i)}}})}function Ao(e,t){return!t?.aborted&&e instanceof T&&e.code!=="cancelled"}var Kr=class{constructor(t,n={}){this.config=t;this.options=n}config;options;adapters=new Map;videoAdapters=new Map;doubaoAdapters=new Map;resolvedRoutes=new Map;usageLog=[];get configSource(){return this.config.source}resolve(t){let n=this.resolvedRoutes.get(t);if(n)return n;let o=An[t];if(o.mode==="video"&&this.options.videoProvider?.provider==="doubao"){let l=this.resolveDoubao(t,!0);return this.resolvedRoutes.set(t,l),l}let i=this.config.tasks[t]??o.defaultProfile,r=this.config.models[i];if(!r)throw Je("The task route references a missing model profile.",[i],[`task: ${t}`]);let s=this.config.providers[r.provider];if(!s)throw Je("The model profile references a missing provider.",[r.provider],[`profile: ${i}`]);if(s.protocol==="openai-compatible"&&!s.baseUrl)throw Je("OpenAI-compatible providers require an explicit endpoint \u2014 set the provider's baseUrl, or PROJECT_LITELLM_GATEWAY_BASE_URL for the built-in gateway.",["provider.baseUrl"],[`provider: ${r.provider}`]);if(r.thinkingBudgetTokens!==void 0&&o.mode==="tool")throw Je("Anthropic thinking cannot be combined with a forced tool call.",["a text task or a profile without thinking"],[`task: ${t}`,`profile: ${i}`]);if(o.mode!=="document"&&r.thinkingBudgetTokens!==void 0&&r.thinkingBudgetTokens>=o.maxOutputTokens)throw Je("The thinking token budget must be smaller than the task output budget.",[`thinking budget < ${o.maxOutputTokens}`],[`task: ${t}`,`thinking budget: ${r.thinkingBudgetTokens}`]);let c=o.mode==="video"?this.options.videoProvider:void 0,a=c?.baseUrl?{...s,protocol:"google-gemini",baseUrl:Pd(c.baseUrl,"--provider-base-url")}:s,d=c?.model?{...r,model:c.model.trim()}:r;if(c?.model!==void 0&&!d.model)throw Je("The video provider model cannot be empty.",["non-empty --provider-model"],["model: empty"]);let p={info:{task:t,profile:i,provider:r.provider,protocol:a.protocol,baseUrl:a.baseUrl,model:d.model,fingerprint:Kd(t,a,d),...o.mode==="video"&&a.videoUploadMode?{videoUploadMode:a.videoUploadMode}:{}},providerConfig:a,modelConfig:d};return this.resolvedRoutes.set(t,p),p}route(t){return this.resolve(t).info}routes(){return Af.map(t=>this.route(t))}emptyUsage(){return{calls:0,succeeded:0,failed:0,reused:0,attempts:0,durationMs:0,inputTokens:0,outputTokens:0,cachedInputTokens:0,cacheCreationTokens:0}}recordReuse(t){let n=new Date().toISOString();this.recordEvent(this.route(t),"reused",n,n,0,{})}usage(){let t=new Map;for(let n of this.usageLog){let o=`${n.task}\0${n.provider}\0${n.protocol}\0${n.model}\0${n.fingerprint}`,i=t.get(o)??{task:n.task,profile:n.profile,provider:n.provider,protocol:n.protocol,baseUrl:n.baseUrl,model:n.model,fingerprint:n.fingerprint,...this.emptyUsage()};n.status==="reused"?i.reused+=1:(i.calls+=1,i[n.status]+=1,i.attempts+=n.attempts,i.durationMs+=n.durationMs,i.inputTokens+=n.inputTokens,i.outputTokens+=n.outputTokens,i.cachedInputTokens+=n.cachedInputTokens,i.cacheCreationTokens+=n.cacheCreationTokens),t.set(o,i)}return[...t.values()]}usageEvents(){return this.usageLog.map(t=>({...t}))}recordEvent(t,n,o,i,r,s,c=0,a){this.usageLog.push({...t,sequence:this.usageLog.length+1,status:n,attempts:c,startedAt:o,endedAt:i,durationMs:r,inputTokens:s.inputTokens??0,outputTokens:s.outputTokens??0,cachedInputTokens:s.cachedInputTokens??0,cacheCreationTokens:s.cacheCreationTokens??0,...a?{errorCode:a}:{}})}async tracked(t,n){let o=Date.now(),i=new Date(o).toISOString();try{let r=await n(),s=Date.now();return this.recordEvent(t,"succeeded",i,new Date(s).toISOString(),s-o,r.usage??{},r.attempts),r}catch(r){let s=Date.now(),c=r instanceof T?r:null;throw this.recordEvent(t,"failed",i,new Date(s).toISOString(),s-o,c?.usage??{},c?.attempts??1,c?.code),r}}resolveDoubao(t,n){let o=n?this.options.videoProvider:void 0,i=n?(o?.model??process.env.ARK_MODEL??"").trim():this.doubaoModel();if(!i)throw Je("Doubao requires --provider-model or ARK_MODEL.",["--provider-model <id> or ARK_MODEL"],["model: empty"]);let r={protocol:"openai-compatible",baseUrl:o?.baseUrl?Pd(o.baseUrl,"--provider-base-url"):kn.baseUrl,apiKeyEnv:kn.apiKeyEnv,timeoutMs:kn.timeoutMs,maxAttempts:kn.maxAttempts},s={provider:"doubao",model:i};return{info:{task:t,profile:n?"doubao":"doubao-fallback",provider:"doubao",protocol:r.protocol,baseUrl:r.baseUrl,model:i,fingerprint:Kd(t,r,s)},providerConfig:r,modelConfig:s}}doubaoRoute(t){return this.resolveDoubao(t,!1).info}adapter(t){let n=`${t.info.provider}\0${t.info.model}\0${t.modelConfig.thinkingBudgetTokens??""}`,o=this.adapters.get(n);if(o)return o;let i=(process.env[t.providerConfig.apiKeyEnv]??"").trim();if(!i&&t.providerConfig.protocol!=="google-vertex")throw Hi(t.info.provider);let r=t.providerConfig.protocol==="anthropic"?new Zs(t.providerConfig,t.modelConfig,i):new ia(t.providerConfig,t.modelConfig,i);return this.adapters.set(n,r),r}videoAdapter(t){if(!["google-gemini","google-vertex"].includes(t.providerConfig.protocol))throw Je("Video tasks require a google-gemini provider.",["provider.protocol: google-gemini"],[`provider: ${t.info.provider}`,`protocol: ${t.providerConfig.protocol}`]);let n=t.info.model,o=`${t.info.provider} ${t.providerConfig.baseUrl??"official"} ${n}`,i=this.videoAdapters.get(o);if(i)return i;let r=this.videoCredential(t);if(!r&&t.providerConfig.protocol!=="google-vertex")throw Hi(t.info.provider);let s=new oa(t.providerConfig,t.modelConfig,r);return this.videoAdapters.set(o,s),s}videoCredential(t){let n=this.options.videoProvider?.apiKey,o=n?.kind==="literal"?n.value.trim():n?.kind==="env"?(process.env[n.name]??"").trim():(process.env[t.providerConfig.apiKeyEnv]??"").trim();if(!o&&(n||t.providerConfig.protocol!=="google-vertex"))throw Hi(t.info.provider);return o}documentPort(t){if(An[t].mode!=="document")throw Je("The task does not support document generation.",["document task"],[t]);let n=this.resolve(t);if(n.providerConfig.protocol!=="google-gemini"&&n.providerConfig.protocol!=="google-vertex")throw Je("PDF tasks require a Gemini provider.",["google-gemini or google-vertex"],[n.providerConfig.protocol]);let o=(process.env[n.providerConfig.apiKeyEnv]??"").trim();if(!o&&n.providerConfig.protocol!=="google-vertex")throw Hi(n.info.provider);let i=new jr(n.providerConfig,n.modelConfig,o),r=new WeakMap;return{prepare:async(s,c)=>{let a;try{a=await i.prepare(s,c)}catch(d){if(!Ao(d,c))throw d;process.stderr.write(`\u21AA\uFE0F PDF \u4E0A\u4F20\u5931\u8D25\uFF0C\u4F7F\u7528\u539F\u6587\u6863\u5B57\u8282\u7EE7\u7EED\u6A21\u578B\u8BF7\u6C42 (${hn(d.failure)})
158
- `),a={kind:"base64",data:Gf.readFileSync(s).toString("base64"),mimeType:"application/pdf"}}return r.set(a,s),a},generate:async s=>{let c=jd(n),a=[];for(let[d,p]of c.entries()){s.signal?.throwIfAborted();let l=d===0?i:new jr(p.providerConfig,p.modelConfig,o);try{return await this.tracked(p.info,()=>l.generate(s))}catch(f){if(!Ao(f,s.signal))throw f;let u=oi(f,p.info);a.push(u);let g=c[d+1];if(g){process.stderr.write(`\u21AA\uFE0F ${p.info.model} \u6587\u6863\u8BF7\u6C42\u5931\u8D25\uFF0C\u5207\u6362\u5230 ${g.info.model} (${hn(u)})
159
- `);continue}let h=this.arkAdapter();if(!h)throw Fi(f,a);let m=this.doubaoRoute(t);process.stderr.write(`\u21AA\uFE0F \u6587\u6863\u6A21\u578B\u8DEF\u7531\u5DF2\u8017\u5C3D\uFF0C\u56DE\u9000\u5230\u8C46\u5305 ${m.model}
160
- `);try{return await this.tracked(m,()=>h.generateDocument(s,r.get(s.media)))}catch(w){throw Ao(w,s.signal)?Fi(w,[...a,oi(w,m)]):w}}}throw new Error("Document model routes cannot be empty.")},release:async(s,c)=>{r.delete(s),await i.release(s,c)}}}videoPort(t){let n=An[t];if(n.mode!=="video")throw Je("The task does not support video generation.",["video task"],[`task: ${t}`]);let o=this.resolve(t);if(this.options.videoProvider?.provider==="doubao"){let r=this.doubaoAdapter(o);if(!r)throw Hi("doubao");return{prepare:async(s,c,a,d)=>{if(a!=="file-api")throw Je("Doubao requires file-api upload mode.",["file-api"],[a]);return d?.throwIfAborted(),{kind:"local",path:s,mimeType:c}},generate:s=>{if(s.media.kind!=="local")throw Je("Doubao requires locally prepared video.",["local media"],[s.media.kind]);s.signal?.throwIfAborted();let{path:c,mimeType:a}=s.media;return this.tracked(o.info,()=>r.run({localPath:c,localMime:a,user:s.user,fps:s.fps,maxOutputTokens:n.maxOutputTokens,...s.system?{system:s.system}:{},...s.responseJsonSchema?{responseJsonSchema:s.responseJsonSchema}:{},...s.acceptsText?{acceptsText:s.acceptsText}:{},...s.signal?{signal:s.signal}:{}}))},release:async()=>{}}}if(!["google-gemini","google-vertex"].includes(o.providerConfig.protocol))throw Je("Video tasks require a google-gemini provider.",["provider.protocol: google-gemini"],[`provider: ${o.info.provider}`,`protocol: ${o.providerConfig.protocol}`]);let i=this.videoAdapter(o);return{prepare:async(r,s,c,a)=>{let d=Date.now();try{return await i.prepare(r,s,c,a)}catch(p){if(!Ao(p,a)||!this.doubaoAdapter())throw p;return this.recordEvent(o.info,"failed",new Date(d).toISOString(),new Date().toISOString(),Date.now()-d,p.usage,p.attempts,p.code),{kind:"local-fallback",path:r,mimeType:s,primaryFailure:oi(p,o.info)}}},release:(r,s)=>r.kind==="local-fallback"?Promise.resolve():i.release(r,s),generate:async r=>{if(r.signal?.throwIfAborted(),r.media.kind==="local-fallback")return this.generateDoubaoVideo(t,r,[r.media.primaryFailure]);let s=jd(o),c=[];for(let[a,d]of s.entries()){r.signal?.throwIfAborted();try{return await this.tracked(d.info,()=>this.videoAdapter(d).generate({...r,maxOutputTokens:n.maxOutputTokens}))}catch(p){if(!Ao(p,r.signal))throw p;let l=oi(p,d.info);c.push(l);let f=s[a+1];if(f){process.stderr.write(`\u21AA\uFE0F ${d.info.model} \u8BF7\u6C42\u5931\u8D25\uFF0C\u5207\u6362\u5230 ${f.info.model} (${hn(l)})
161
- `);continue}if(!this.doubaoAdapter()||!r.localPath)throw Fi(p,c);return this.generateDoubaoVideo(t,r,c)}}throw new Error("Gemini model routes cannot be empty.")}}}async generateDoubaoVideo(t,n,o){let i=this.doubaoAdapter();if(!i)throw Hi("doubao");let r=n.media.kind==="local-fallback"?n.media.path:n.localPath;if(!r)throw Je("Doubao video fallback requires the local video.",["localPath"],["localPath: missing"]);let s=n.localMime??(n.media.kind==="file-api"?n.media.file.mimeType:n.media.mimeType),c=An[t];if(c.mode!=="video")throw Je("Expected a video task.",["video task"],[t]);let a=this.doubaoRoute(t);process.stderr.write(`\u21AA\uFE0F Gemini \u8DEF\u7531\u5DF2\u8017\u5C3D\uFF0C\u56DE\u9000\u5230\u8C46\u5305 ${a.model}
162
- `);try{return await this.tracked(a,()=>i.run({localPath:r,localMime:s,user:n.user,fps:n.fps,maxOutputTokens:c.maxOutputTokens,...n.system?{system:n.system}:{},...n.responseJsonSchema?{responseJsonSchema:n.responseJsonSchema}:{},...n.acceptsText?{acceptsText:n.acceptsText}:{},...n.signal?{signal:n.signal}:{}}))}catch(d){throw Ao(d,n.signal)?Fi(d,[...o,oi(d,a)]):d}}doubaoAdapter(t){return this.arkAdapter(t)}doubaoTextAdapter(){return this.arkAdapter()}arkAdapter(t){let n=t?this.videoCredential(t):(process.env[kn.apiKeyEnv]??"").trim();if(!n)return null;let o=t?.info.model??this.doubaoModel(),i=t?.providerConfig.baseUrl??kn.baseUrl,r=`doubao ${i} ${o}`,s=this.doubaoAdapters.get(r);if(s)return s;let c=new ea(o,kn.timeoutMs,kn.maxAttempts,n,i);return this.doubaoAdapters.set(r,c),c}doubaoModel(){return(process.env[kn.modelEnv]??"").trim()||kn.model}async withTextFallback(t,n,o){let i=this.resolve(t),r=Gx(i.info),s=r?jd(i):[i],c=[];for(let[a,d]of s.entries()){n?.throwIfAborted();let p=this.adapter(d);try{return await this.tracked(d.info,()=>o(p))}catch(l){if(!Ao(l,n)||!r&&l.code!=="content_filtered")throw l;let f=oi(l,d.info);c.push(f);let u=s[a+1];if(u){process.stderr.write(`\u21AA\uFE0F ${d.info.model} \u8BF7\u6C42\u5931\u8D25\uFF0C\u5207\u6362\u5230 ${u.info.model} (${hn(f)})
163
- `);continue}let g=this.doubaoTextAdapter();if(!g)throw Fi(l,c);let h=this.doubaoRoute(t);process.stderr.write(`\u21AA\uFE0F \u4E3B\u6A21\u578B\u8DEF\u7531\u5DF2\u8017\u5C3D\uFF0C\u56DE\u9000\u5230\u8C46\u5305 ${h.model}
164
- `);try{return await this.tracked(h,()=>o(g))}catch(m){throw Ao(m,n)?Fi(m,[...c,oi(m,h)]):m}}}throw new Error("Text model routes cannot be empty.")}async generateText(t,n){let o=An[t];if(o.mode!=="text")throw Je("The task does not support text generation.",["text task"],[`task: ${t}`]);return this.withTextFallback(t,n.signal,i=>i.generateText({...n,maxOutputTokens:o.maxOutputTokens}))}async generateTool(t,n){let o=An[t];if(o.mode!=="tool")throw Je("The task does not support tool generation.",["tool task"],[`task: ${t}`]);return this.withTextFallback(t,n.signal,i=>i.generateTool({...n,maxOutputTokens:o.maxOutputTokens}))}};function Bf(e,t){return new Kr(Io(e),t)}var Jx=Bx(import.meta.url);function ra(e){try{return Jx.resolve(e),!0}catch{return!1}}function jx(e){let t=!1;try{Bt.statSync(e).isDirectory()&&(Bt.accessSync(e,Bt.constants.W_OK),t=!0)}catch{t=!1}let n=!1;try{n=Bt.statSync(ii.join(e,"script.json")).isFile()}catch{n=!1}return{writable:t,hasScript:n}}function Kx(){return ii.join(ii.dirname(ii.resolve("workspace")),"output")}function Jf(e={}){let t=vd(),n=[],o=new Set;for(let M of t)try{if(!Bt.existsSync(M)||!Bt.statSync(M).isFile())continue;let V=Bt.realpathSync(M);if(o.has(V))continue;o.add(V),n.push(M)}catch{}let i=typeof e.llm_config=="string"?e.llm_config.trim():"",r=Io(i||void 0),c=new Kr(r).routes(),a=Object.entries(r.providers).map(([M,V])=>({alias:M,configured:!!(process.env[V.apiKeyEnv]??"").trim(),env:V.apiKeyEnv})),d=Object.entries(r.providers).filter(([,M])=>M.protocol==="openai-compatible").map(([M,V])=>{let F="not set";if(V.baseUrl)try{F=new URL(V.baseUrl).host}catch{F=V.baseUrl}return{alias:M,host:F}}),{mode:p}=If(),l=(process.env.SCRIPTCTL_OUTPUT_DIR??"").trim()||Kx(),f=p==="local"?jx(l):null,u=!!process.env.AWB_BASE_URL,g=!!process.env.LINGJING_AWB_ACCESS_KEY,h=!!process.env.SANDBOX_PROJECT_GROUP_NO,m={"@anthropic-ai/sdk":ra("@anthropic-ai/sdk"),"@google/genai":ra("@google/genai"),jszip:ra("jszip"),"fast-xml-parser":ra("fast-xml-parser")},w=Object.entries(m).filter(([,M])=>!M).map(([M])=>M),y=process.versions.node,_=`env_file: ${n[0]??"missing"}`,x=M=>M?"configured":"not configured",A=[`node: ${y}`,"storage: local-filesystem",_,`llm config: ${r.source}`,`llm routes: ${c.length}`,...a.map(M=>`llm provider ${M.alias}: ${x(M.configured)}`),...d.map(M=>`llm provider ${M.alias} endpoint: ${M.host}`)];p===null?A.push("output target: not configured"):p==="local"&&f?(A.push(`output writable: ${x(f.writable)}`),A.push(`output snapshot: ${f.hasScript?"present":"absent"}`)):(A.push(`gateway endpoint: ${x(u)}`),A.push(`gateway access credential: ${x(g)}`),A.push(`gateway project identifier: ${x(h)}`));for(let[M,V]of Object.entries(m))A.push(`dependency ${M}: ${V?"ok":"missing"}`);let b=[];w.length>0&&b.push("Install missing CLI dependencies (see above)."),a.some(M=>!M.configured)&&b.push("Configure every credential referenced by the selected LLM configuration."),d.some(M=>M.host==="not set")&&b.push("An openai-compatible provider has no endpoint \u2014 set PROJECT_LITELLM_GATEWAY_BASE_URL (built-in gateway) or the provider's baseUrl."),p===null?b.push("Configure an output target before running `publish` / script CRUD."):p==="local"?f&&!f.writable&&b.push("Output target is not writable; check directory permissions."):(!u||!g||!h)&&b.push("Configure gateway credentials before running `publish` / script CRUD against the remote project."),b.length===0&&b.push("Environment looks ready.");let[C,R]=y.split(".").map(M=>parseInt(M,10)),I=(C??0)>20||(C??0)===20&&(R??0)>=0,O=p===null?{configured:!1}:p==="local"?{dir:{ok:!!f?.writable,writable:!!f?.writable,hasScript:!!f?.hasScript}}:{endpoint:{ok:u},access:{ok:g},project:{ok:h}},N={node:{version:y,ok:I},storage:{backend:"local-filesystem",ok:!0},env:{ok:n.length>0,paths:n},llm:{config_source:r.source,...r.sourcePath?{config_path:r.sourcePath}:{},providers:a.map(M=>({alias:M.alias,ok:M.configured,credential_env:M.env,...d.find(V=>V.alias===M.alias)?{endpoint:d.find(V=>V.alias===M.alias).host}:{}})),profiles:Object.keys(r.models),routes:c.map(M=>({task:M.task,profile:M.profile,provider:M.provider,protocol:M.protocol,model:M.model}))},output:O,dependencies:m};return[{text:[...A,...b].join(`
165
- `),data:{checks:N}},B]}import{spawn as zx}from"node:child_process";var sa="@lingjingai/scriptctl",Hx=`${sa}@latest`,zd="npm";function Fx(){return ji()}function Qx(e){let t=/^(\d+)\.(\d+)\.\d+/.exec(e);return t?`${sa}@~${t[1]}.${t[2]}.0`:null}function Yx(e){return["install","-g",e]}function qx(e,t){return[e,...t].join(" ")}function Zx(e,t){return e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0).slice(-t)}function Wx(e,t){return new Promise(n=>{let o=zx(e,[...t],{stdio:["ignore","pipe","pipe"]}),i=[],r=[];o.stdout.setEncoding("utf-8"),o.stderr.setEncoding("utf-8"),o.stdout.on("data",s=>i.push(s)),o.stderr.on("data",s=>r.push(s)),o.once("error",s=>{n({exitCode:null,signal:null,stdout:i.join(""),stderr:r.join(""),error:s})}),o.once("close",(s,c)=>{n({exitCode:s,signal:c,stdout:i.join(""),stderr:r.join("")})})})}async function jf(e,t=Wx,n=Fx){let o=!!e.patch,i=n(),r=o?Qx(i):Hx;if(!r)throw new S(`Cannot compute a patch update range from version ${i}.`,{exitCode:ee,errorCode:"UPDATE_VERSION_INVALID",hint:"Run `scriptctl update` without --patch to install the latest version.",data:{version:i}});let s=[...Yx(r)],c=qx(zd,s),a={package:sa,package_spec:r,command:zd,args:s,command_line:c};if(e.dry_run)return[{text:[`package: ${sa}`,`command: ${c}`,"dry-run: no update performed"].join(`
166
- `),data:{op:"update",changed:!1,update:a}},B];let d=await t(zd,s);if(d.error)throw new S(`Failed to start npm: ${d.error.message}`,{exitCode:ee,errorCode:"UPDATE_SPAWN_FAILED",hint:`Run '${c}' after fixing the npm installation.`,data:{update:a,cause:d.error.message}});if(d.exitCode!==B){let f=[`exit: ${d.exitCode===null?`signal ${d.signal??"unknown"}`:String(d.exitCode)}`,...Zx(d.stderr,5).map(u=>`stderr: ${u}`)];throw new S("npm could not update scriptctl.",{exitCode:ee,errorCode:"UPDATE_COMMAND_FAILED",hint:`Run '${c}' after resolving the npm error.`,data:{update:a,actual:f}})}let p=n(),l=p!==i;return[{text:l?`Updated ${i} \u2192 ${p}.`:`Already up to date (${p}).`,data:{op:"update",changed:l,status:l?"updated":"already_latest",previous_version:i,version:p}},B]}function Kf(e,t){e.command("doctor").description("Check configuration and runtime dependencies").option("--llm-config <path>","LLM configuration file").action(H(Jf,t)),e.command("update").description("Update scriptctl to the latest release").option("-n, --dry-run","Show the update without installing").option("--patch","Allow a patch-level update").action(H(jf,t));let n=e.command("changelog [version]").description("Show release notes").option("--from <version>","Start version").option("--to <version>","End version").option("--unreleased","Show unreleased changes").action(H(_f,t));Me(n,["Release version"])}import*as Zr from"node:fs";import*as Sa from"node:path";import{fileURLToPath as sS,pathToFileURL as aS}from"node:url";import*as rt from"node:fs";import*as it from"node:path";import{createHash as Nm}from"node:crypto";import{z as ot}from"zod";import*as bo from"node:fs";var zf=null,Xx=0;function Q(e,t){zf&&zf.push({fn:e,note:t,ms:Math.round((performance.now()-Xx)*100)/100})}var e5=[["actor","actors","actor"],["location","locations","location"],["prop","props","prop"]];function ko(e){return Array.isArray(e)?e:[]}function ke(e){return typeof e=="string"?e:""}function Qn(e,t,n,o){if(t){if(e.has(t)&&e.get(t)!==n){o.add(t);return}e.set(t,n)}}function Fd(e){return Oo(JSON.parse(bo.readFileSync(e,"utf8")),e)}function Oo(e,t=""){let n=e?.version;if(n!==3&&n!==4)throw new Error(`Unsupported script.version: ${JSON.stringify(n)} (expected 3 or 4)`);let o={version:n,path:t,raw:e,episodes:[],assets:[],byId:new Map,eps:new Map,scenes:new Map,actions:new Map};for(let[a,d,p]of e5)for(let l of ko(e[d])){let f={id:ke(l[`${p}_id`]),kind:a,name:ke(l[`${p}_name`]),aliases:ko(l.aliases).map(ke).filter(Boolean),importance:ke(l.importance),desc:ke(l.description),states:ko(l.states).map(u=>({id:ke(u.state_id),name:ke(u.state_name),desc:ke(u.description)})),raw:l,label:""};o.assets.push(f),o.byId.set(f.id,f)}let i=new Map;for(let a of o.assets)for(let d of[a.name,...a.aliases])i.set(d,(i.get(d)??0)+1);for(let a of o.assets)a.label=[a.name,...a.aliases].filter(d=>i.get(d)===1).sort((d,p)=>d.length-p.length)[0]??a.name;let r=new Set,s=0,c=0;ko(e.episodes).forEach((a,d)=>{let p={anchor:String(d+1),id:ke(a.episode_id),no:d+1,title:ke(a.title)||void 0,synopsis:ke(a.synopsis)||void 0,scenes:[],raw:a};ko(a.scenes).forEach((l,f)=>{s++;let u={anchor:n===4?ke(l.scene_id):`${d+1}-${f+1}`,id:ke(l.scene_id),no:f+1,gno:s,env:l.environment??{},location:Hd(l.location,"location_id"),actors:ko(l.actors).map(g=>Hd(g,"actor_id")).filter(Boolean),props:ko(l.props).map(g=>Hd(g,"prop_id")).filter(Boolean),actions:[],raw:l,ep:p};ko(l.actions).forEach((g,h)=>{c++;let m={anchor:n===4?ke(g.action_id):`${d+1}-${f+1}-${h+1}`,no:h+1,gno:c,type:ke(g.type)||"action",content:ke(g.content),speaker:t5(g.speaker),paren:typeof g.parenthetical=="string"?g.parenthetical:typeof g.emotion=="string"?g.emotion:void 0,ts:ke(g.extend?.timestamp)||void 0,raw:g,scene:u};u.actions.push(m),Qn(o.actions,m.anchor,m,r),Qn(o.actions,`${d+1}-${f+1}-${h+1}`,m,r),n===3&&Qn(o.actions,`${p.id}/${u.id}#${h}`,m,r)}),p.scenes.push(u),Qn(o.scenes,u.anchor,u,r),Qn(o.scenes,`${d+1}-${f+1}`,u,r),Qn(o.scenes,`${p.id}/${u.id}`,u,r),Qn(o.scenes,u.id,u,r)}),o.episodes.push(p),Qn(o.eps,String(d+1),p,r),Qn(o.eps,p.id,p,r)});for(let a of r)o.actions.delete(a),o.scenes.delete(a),o.eps.delete(a);return Q(t?"model.load":"model.parse",`v${n} \xB7 ${o.episodes.length} ep \xB7 ${o.scenes.size} scene keys \xB7 ${o.actions.size} action keys \xB7 ${o.assets.length} assets \xB7 ${r.size} ambiguous keys dropped`),o}function Hd(e,t){if(!e||typeof e!="object")return null;let n=ke(e[t]);if(!n)return null;let o=Array.isArray(e.state_ids)?e.state_ids.map(ke):e.state_id?[ke(e.state_id)]:[];return{id:n,states:o,raw:e}}function t5(e){if(!(!e||typeof e!="object")){if(e.actor_id)return{id:ke(e.actor_id),state:ke(e.state_id)||void 0};if(e.kind)return{kind:ke(e.kind),label:ke(e.label)||void 0}}}function Te(e,t){let n=t.trim();if(!n)return{t:"script",doc:e};let o=n.indexOf("/");if(o>0&&!e.scenes.has(n)){let p=n.slice(0,o),l=n.slice(o+1),f=e.byId.get(p)??n5(e,p);if(f){let u=f.states.filter(g=>g.id===l||g.name===l);if(u.length===1)return Q("resolve",`"${n}" -> state ${f.id}/${u[0].id} "${u[0].name}"`),{t:"state",asset:f,state:u[0]};throw u.length>1?new Error(`${f.name} has ${u.length} states named "${l}"; address it by state id`):new Error(`${f.name} has no state "${l}" (has: ${f.states.map(g=>`${g.id}(${g.name})`).join(", ")})`)}}let i=e.actions.get(n);if(i)return Q("resolve",`"${n}" -> action map hit -> ${i.anchor}`),{t:"action",action:i};let r=e.scenes.get(n);if(r)return Q("resolve",`"${n}" -> scene map hit -> ${r.anchor}`),{t:"scene",scene:r};let s=e.eps.get(n);if(s)return Q("resolve",`"${n}" -> episode map hit -> ${s.id}`),{t:"ep",ep:s};let c=e.byId.get(n);if(c)return Q("resolve",`"${n}" -> asset id hit -> ${c.name}`),{t:"asset",asset:c};let a=e.assets.filter(p=>p.name===n||p.aliases.includes(n));if(a.length===1)return Q("resolve",`"${n}" -> exact name/alias -> ${a[0].id} ${a[0].name}`),{t:"asset",asset:a[0]};if(a.length>1)throw new Error(`Ambiguous name "${n}": ${a.map(p=>`${p.id}(${p.name})`).join(", ")}`);let d=e.assets.filter(p=>p.name.includes(n)||p.aliases.some(l=>l.includes(n)));if(d.length===1)return Q("resolve",`"${n}" -> substring name match -> ${d[0].id} ${d[0].name}`),{t:"asset",asset:d[0]};throw new Error(`Unknown address "${n}". Use an ordinal (3 / 3-2 / 3-2-5), a canonical ID, or an asset name.`+(d.length?` Did you mean: ${d.slice(0,5).map(p=>p.name).join(", ")}?`:""))}function n5(e,t){let n=e.assets.filter(i=>i.name===t||i.aliases.includes(t));if(n.length===1)return n[0];if(n.length>1)return;let o=e.assets.filter(i=>i.name.includes(t)||i.aliases.some(r=>r.includes(t)));return o.length===1?o[0]:void 0}function ri(e,t){return e.byId.get(t)?.label||t}function si(e,t,n){return e.byId.get(t)?.states.find(i=>i.id===n)?.name||n}function bn(e){return e.episodes.flatMap(t=>t.scenes.flatMap(n=>n.actions))}var o5={ep:"episode",scn:"scene",ac:"action",act:"actor",loc:"location",prp:"prop",st:"state"};function vo(e,t){let n=Ar(o5[e],t);return t.add(n),Q("newId",`${n} (collision-checked against ${t.size-1} live ids)`),n}function be(e){if(Object.assign(e,Oo(e.raw,e.path)),!e.path){Q("save","skipped: document is not bound to a file");return}Hf(e,e.path)}function Hf(e,t=e.path){if(!t)throw new Error("commit needs a path: this document is not bound to a file");let n=`${t}.tmp-${process.pid}`;bo.writeFileSync(n,JSON.stringify(e.raw,null,2)+`
167
- `),bo.renameSync(n,t),Q("commit",`${bo.statSync(t).size} bytes -> ${t} (tmp + atomic rename)`)}var i5={system:"\u65C1\u767D",broadcast:"\u5E7F\u64AD",offscreen:"\u753B\u5916",group:"\u7FA4\u58F0"},Ff="\u5FC3\u58F0";function r5(e,t){if(t.kind)return i5[t.kind]??t.kind;let n=ri(e,t.id);return t.state?`${n}\xB7${si(e,t.id,t.state)}`:n}function zr(e,t,n,o={}){let i=(o.plain?"":t.anchor).padEnd(n),r=o.timestamps?`${t.ts??"[\u65F6\u95F4\u7F3A\u5931]"} `:!o.plain&&t.ts?`${t.ts} `:"",s=(()=>{if(t.type==="transition")return`\u2192 ${t.content}`;if(t.type==="dialogue"||t.type==="inner_thought"){let a=t.speaker?r5(e,t.speaker):"?",d=[t.type==="inner_thought"?Ff:"",t.paren??""].filter(Boolean);return`${t.speaker?.kind&&t.speaker.label?`${a}\xB7${t.speaker.label}`:a}${d.length?`(${d.join("/")})`:""}\uFF1A${t.content}`}return t.content})(),c=`${i}${i?" ":""}`;return`${o.timestamps?r+c:c+r}${s}`.replace(/\n/g,"\\n")}function Qd(e,t){let n=ri(e,t.id);return t.states.length===1&&t.states[0]==="default"?n:`${n}(${t.states.map(o=>si(e,t.id,o)).join("+")})`}function Qi(e,t){let n=[t.env?.space,t.env?.time].filter(Boolean).join("/").toUpperCase(),o=t.location?Qd(e,t.location):"\u2014",i=`## ${t.ep.no}-${t.no} ${t.anchor===`${t.ep.no}-${t.no}`?t.id:t.anchor} ${n||"\u2014"} ${o} ${t.actions.length} actions`,r=t.actors.map(a=>Qd(e,a)).join(", "),s=t.props.map(a=>Qd(e,a)).join(", "),c=[r&&`cast: ${r}`,s&&`props: ${s}`].filter(Boolean).join(" ");return c?`${i}
168
- # ${c}`:i}function Yd(e,t,n={}){let o=n.plain?0:Math.max(0,...t.actions.map(i=>i.anchor.length));return Q("formatScene",`${t.anchor}: ${t.actions.length} actions, gutter=${o}`),[Qi(e,t),...t.actions.map(i=>zr(e,i,o,n))].join(`
169
- `)}var s5=/^([A-Za-z][A-Za-z0-9_]*|\d+(?:-\d+){0,2})\s\s+/;function Qf(e,t){let n=e.trimEnd();if(!n.trim())return null;let o,i=n.match(s5);i&&(o=i[1],n=n.slice(i[0].length)),n=n.replace(/\\n/g,`
170
- `);let r,s=n.match(/^((?:\d+:)?\d+:\d{2}(?:\.\d{1,3})?)\s/);if(s&&(r=s[1],n=n.slice(s[0].length)),n.startsWith("\u2192"))return{anchor:o,ts:r,type:"transition",content:n.slice(1).trim()};let c=n.indexOf("\uFF1A");if(c>0){let d=n.slice(0,c).match(/^([^()]+)(?:\((.*)\))?$/);if(d&&t(d[1].trim())){let p=(d[2]??"").split("/").map(u=>u.trim()).filter(Boolean),l=p[0]===Ff,f=(l?p.slice(1):p).join("/");return{anchor:o,ts:r,type:l?"inner_thought":"dialogue",speakerName:d[1].trim(),paren:f||void 0,content:n.slice(c+1).trim()}}}return{anchor:o,ts:r,type:"action",content:n.trim()}}var a5=/^(scn[1-9A-HJ-NP-Za-km-z]{6}|scn_\d+)$/,c5=/^[A-Z.\/]+$/,d5=/^\d+\s+actions?$/,p5={EXT:"exterior",EXTERIOR:"exterior",INT:"interior",INTERIOR:"interior"};function Yf(e){let t=e.findIndex(i=>i.startsWith("##"));if(t<0)return{body:e};let n=e[t+1]?.startsWith("#")&&!e[t+1].startsWith("##"),o=e.filter((i,r)=>r!==t&&!(n&&r===t+1));return{head:e[t],meta:n?e[t+1]:void 0,body:o}}function qd(e,t){let n={env:{},cast:[],props:[]},o=e.replace(/^##\s*/,"").split(/\s{2,}/).map(i=>i.trim()).filter(Boolean);for(let i of o)if(!(/^\d+-\d+$/.test(i)||d5.test(i))){if(a5.test(i)){n.anchor=i;continue}if(c5.test(i)&&i!=="\u2014"){let[r,s]=i.split("/");r&&(n.env.space=p5[r]??r.toLowerCase()),s&&(n.env.time=s.toLowerCase());continue}i!=="\u2014"&&n.location===void 0&&(n.location=i)}if(t){let i=t.replace(/^#\s*/,""),r=i.match(/cast:\s*([^]*?)(?:\s\sprops:|$)/),s=i.match(/props:\s*([^]*)$/),c=a=>(a??"").split(",").map(d=>d.trim()).filter(Boolean);n.cast=c(r?.[1]),n.props=c(s?.[1])}return n}function qf(e){let t=e.trim().match(/^(.*?)\s*\(([^)]*)\)$/);return t?{name:t[1].trim(),states:t[2].split("+").map(n=>n.trim()).filter(Boolean)}:{name:e.trim(),states:[]}}function Yi(e,t){throw Object.assign(new Error(e),t)}function Wd(e){return e.episodes.flatMap(t=>t.scenes.flatMap(n=>n.actions.map((o,i)=>({address:e.version===4?o.anchor:`${t.id}/${n.id}#${i}`,episodeId:t.id,episodeNo:t.no,timestamp:o.ts}))))}function Zd(e){try{return lo(e.timestamp??"")}catch(t){if(!(t instanceof et))throw t;return Yi(`Action ${e.address} has an invalid stored timestamp.`,{code:"ACTION_SPAN_TIMESTAMP_INVALID",hint:`Fix it with \`scriptctl edit ${e.address} --ts <time>\` or remove it.`,data:{expected:["valid action.extend.timestamp"],actual:[`${e.address}: ${JSON.stringify(e.timestamp??"")}`]}})}}function Zf(e,t){return Yi("Action timestamps run backward within the selected episode.",{code:"ACTION_SPAN_TIMESTAMP_NON_MONOTONIC",hint:"Fix the stored timestamps so they do not move backward in document order, then rerun `span`.",data:{actual:[`${e.address}: ${e.timestamp}`,`${t.address}: ${t.timestamp}`]}})}function Xd(e,t){t.length===0&&Yi("The action selection matched nothing.",{code:"ACTION_SPAN_NO_MATCH",hint:"Check the selector with `scriptctl actions` and rerun with `--span`.",data:{actual:["0 matched actions"]}});let n=new Set(t),o=e.filter(g=>n.has(g.address));o.length!==n.size&&Yi("The resolved action selection is inconsistent with the script timeline.",{code:"ACTION_SPAN_SELECTION_INCONSISTENT",data:{expected:[`${n.size} timeline actions`],actual:[`${o.length} timeline actions`]}});let i=new Set(o.map(g=>g.episodeId));i.size!==1&&Yi("An action timestamp span must stay within one episode.",{code:"ACTION_SPAN_CROSSES_EPISODES",hint:"Split the selector into one `span` call per episode.",data:{actual:[...i]}});let r=o[0],s=o[o.length-1];r.timestamp||Yi(`The first selected Action ${r.address} has no timestamp.`,{code:"ACTION_SPAN_START_TIMESTAMP_MISSING",hint:`Set it with \`scriptctl timestamp ${r.address} --set <time>\`, then rerun.`,data:{actual:[r.address]}});let c=Zd(r),a=r,d=c,p="";for(let g of o){if(!g.timestamp)continue;let h=Zd(g);h.milliseconds<d.milliseconds&&Zf(a,g),a=g,d=h,g.address===s.address&&(p=h.canonical)}let l=e.findIndex(g=>g.address===s.address),f,u;for(let g=l+1;g<e.length;g+=1){let h=e[g];if(h.episodeId!==r.episodeId)break;if(!h.timestamp)continue;let m=Zd(h);if(m.milliseconds<d.milliseconds&&Zf(a,h),m.milliseconds!==d.milliseconds){f=h,u=m;break}}return Q("span",`${r.episodeId} ${c.canonical}..${u?.canonical??"(open)"} over ${o.length} action(s)`),{episode_id:r.episodeId,ep_no:r.episodeNo,start_timestamp:c.canonical,last_selected_timestamp:p,end_timestamp:u?.canonical??"",end_open:u===void 0,end_exclusive:!0,start_action:r.address,last_action:s.address,end_boundary_action:f?.address??"",matched_actions:o.length}}var ep=["episode_id","ep_no","start_timestamp","last_selected_timestamp","end_timestamp","end_open","end_exclusive","start_action","last_action","end_boundary_action","matched_actions"];function tp(e,t){return t.map(n=>{if(e.version===4)return n.anchor;let o=n.scene.actions.indexOf(n);return`${n.scene.ep.id}/${n.scene.id}#${o}`})}function np(e,t,n={}){let o=n.offset??0,i=n.limit??20,r=n.context??3;for(let[f,u,g]of[["offset",o,0],["limit",i,1],["context",r,0]])if(!Number.isSafeInteger(u)||u<g)throw new Error(`${f} must be an integer >= ${g}`);let s=Te(e,t);if(s.t!=="asset"&&s.t!=="state")throw new Error("references requires an asset or asset/state address; use read for episodes/scenes/actions");let c=s.asset,a=s.t==="state"?s.state.id:null,d=[...new Set([c.id,c.name,...c.aliases])].filter(Boolean),p=[];for(let f of e.episodes)for(let u of f.scenes){let g=[...u.location?[u.location]:[],...u.actors,...u.props].filter(h=>h.id===c.id&&(a===null||h.states.includes(a)));g.length&&p.push({kind:"scene_binding",scene:u,matched:g.flatMap(h=>h.states)});for(let h of u.actions)if(h.speaker?.id===c.id&&(a===null||h.speaker.state===a)&&p.push({kind:"speaker",scene:u,action:h,matched:[c.id]}),a===null){let m=d.filter(w=>h.content.includes(w));m.length&&p.push({kind:"text_mention",scene:u,action:h,matched:m})}}let l=o+i;return{asset_id:c.id,state_id:a,total:p.length,next_offset:l<p.length?l:null,items:p.slice(o,l).map(({kind:f,scene:u,action:g,matched:h})=>{let m=g?u.actions.indexOf(g):-1,w=g?u.actions.slice(Math.max(0,m-r),m+r+1):[],y=Math.max(0,...w.map(_=>_.anchor.length));return{kind:f,address:g?.anchor??u.anchor,scene_address:u.anchor,episode:u.ep.no,matched:h,text:[Qi(e,u),...w.map(_=>(_===g?"> ":" ")+zr(e,_,y))].join(`
171
- `)}})}}function op(e){return[`${e.asset_id}${e.state_id===null?"":"/"+e.state_id} ${e.total} references \xB7 showing ${e.items.length}`,"scene_binding=explicit scene presence; speaker=explicit speaker; text_mention=name/alias mention only (not proof of presence).",...e.items.map(t=>`${t.address} ${t.kind} ep=${t.episode}
156
+ `),{files:{upload:c=>Uf({apiKey:e,filePath:c.file,mimeType:c.config?.mimeType??"video/mp4",timeoutMs:t,proxyUrl:s,baseUrl:n}),get:c=>r.files.get(c),delete:c=>r.files.delete(c)},models:{generateContent:c=>r.models.generateContent(c),generateContentStream:c=>r.models.generateContentStream(c)}}}var zr=class{constructor(t,n,o,i){this.provider=t;this.transport=new Hi(t,n,o,i)}provider;transport;prepare(t,n){return this.transport.prepare(t,"application/pdf",this.provider.documentUploadMode??"file-api",n)}generate(t){return this.transport.generateMedia(t)}release(t,n){return this.transport.release(t,n)}};var ia=class extends Hi{generate(t){let n=t.media;if(n.kind==="local-fallback"||n.kind==="local")throw new T("invalid_response","A local fallback video cannot be sent to Gemini.");return this.generateMedia({...t,media:n},{fps:t.fps})}};function Tf(e,t){if(!Fn(e)||!Fn(e.usage))return{};let n=e.usage,o=a=>{let d=typeof a=="number"?a:0;return Number.isFinite(d)?d:0},i=Fn(n.prompt_tokens_details)?n.prompt_tokens_details:{},r=o(n.prompt_tokens),s=o(i.cached_tokens)||o(n.cache_read_input_tokens),c=o(i.cache_creation_tokens)||o(n.cache_creation_input_tokens);return{inputTokens:t?r:r+s+c,outputTokens:o(n.completion_tokens),cachedInputTokens:s,cacheCreationTokens:c}}function Fn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dx(e){let t=e.trim().replace(/\/+$/,"");return t.endsWith("/chat/completions")?t:t.endsWith("/v1")?`${t}/chat/completions`:`${t}/v1/chat/completions`}function Vf(e){return!Fn(e)||!Array.isArray(e.choices)?null:e.choices.find(Fn)??null}function $f(e){return e&&typeof e.finish_reason=="string"?e.finish_reason:""}function Gf(e){return e&&Fn(e.message)?e.message:null}function Gx(e){let t=Gf(e)?.content;return typeof t=="string"?t.trim():Array.isArray(t)?t.flatMap(n=>Fn(n)&&typeof n.text=="string"?[n.text]:[]).join(`
157
+ `).trim():""}function Df(e){try{return JSON.parse(e)}catch{throw new T("invalid_response","Provider returned invalid JSON.",{details:[e.slice(0,500)]})}}var ra=class{constructor(t,n,o){this.provider=t;this.model=n;this.apiKey=o;if(!t.baseUrl&&t.protocol!=="google-vertex")throw new T("endpoint","OpenAI-compatible provider endpoint (baseUrl) is not set \u2014 the built-in gateway reads PROJECT_LITELLM_GATEWAY_BASE_URL.");this.url=t.protocol==="google-vertex"?`https://aiplatform.googleapis.com/v1/projects/${na()}/locations/global/endpoints/openapi/chat/completions`:t.protocol==="google-gemini"?`${t.baseUrl.trim().replace(/\/+$/,"")}/v1beta/openai/chat/completions`:Dx(t.baseUrl);try{this.host=new URL(this.url).host}catch{this.host=this.url}}provider;model;apiKey;url;host;async post(t,n){let o=await en(this.provider.maxAttempts,async()=>{let i=AbortSignal.timeout(this.provider.timeoutMs),r=n?AbortSignal.any([n,i]):i,s;try{s=await fetch(this.url,{method:"POST",headers:{authorization:`Bearer ${this.provider.protocol==="google-vertex"?await Mf.getAccessToken():this.apiKey}`,"content-type":"application/json"},body:JSON.stringify(t),signal:r})}catch(a){let d=a instanceof Error?a.message:String(a),p=r.aborted&&!n?.aborted;throw new T(p?"timeout":"request_failed",p?`OpenAI-compatible request timed out reaching ${this.host}.`:`OpenAI-compatible request could not reach ${this.host}: ${d}`,{retryable:!n?.aborted,details:[d.slice(0,500)]})}let c=await s.text();if(!s.ok){let a=s.status===408||s.status===429||s.status>=500,d=s.status===401||s.status===403?"auth":s.status===429?"rate_limited":"request_failed";throw new T(d,`OpenAI-compatible request to ${this.host} failed (status ${s.status}).`,{retryable:a,details:[`status: ${s.status}`,c.slice(0,500)]})}return Df(c)});return{payload:o.value,attempts:o.attempts,failedUsage:o.failedUsage}}baseBody(t){let n=[];return t.system.trim()&&n.push({role:"system",content:t.system}),n.push({role:"user",content:t.user}),{model:this.provider.protocol==="google-vertex"?`google/${this.model.model.replace(/^google\//,"")}`:this.model.model,messages:n,...t.responseFormat==="json_object"?{response_format:{type:"json_object"}}:{},...this.model.reasoning?{reasoning_effort:this.model.reasoning}:{},...this.model.temperature!==void 0?{temperature:this.model.temperature}:{}}}async generateText(t){let{payload:n,attempts:o,failedUsage:i}=await this.post(this.baseBody(t),t.signal),r=Xt(i,Tf(n,this.provider.protocol==="google-vertex"||this.provider.protocol==="google-gemini"));try{let s=Vf(n),c=$f(s);if(c==="length")throw new T("truncated","Provider output was truncated.");if(c==="content_filter"||c.startsWith("content_filter:"))throw new T("content_filtered",`Provider filtered the response (${c}).`);let a=Gx(s);if(!a)throw new T("empty_response","Provider returned an empty text response.");return{text:a,finishReason:c,attempts:o,usage:r,raw:n}}catch(s){throw s instanceof T&&(s.attempts=o,s.usage=r),s}}async generateTool(t){let{payload:n,attempts:o,failedUsage:i}=await this.post({...this.baseBody(t),tools:[{type:"function",function:{name:t.tool.name,description:t.tool.description,parameters:t.tool.inputSchema}}],tool_choice:{type:"function",function:{name:t.tool.name}},parallel_tool_calls:!1},t.signal),r=Xt(i,Tf(n,this.provider.protocol==="google-vertex"||this.provider.protocol==="google-gemini"));try{let s=Vf(n),c=$f(s);if(c==="length")throw new T("truncated","Provider tool output was truncated.");if(c==="content_filter"||c.startsWith("content_filter:"))throw new T("content_filtered",`Provider filtered the response (${c}).`);let a=Gf(s)?.tool_calls;if(!Array.isArray(a))throw new T("invalid_response","Provider did not return a tool call.");for(let d of a){if(!Fn(d)||!Fn(d.function))continue;let p=d.function;if(!(p.name!==t.tool.name||typeof p.arguments!="string"))return{input:Df(p.arguments),finishReason:c,attempts:o,usage:r,raw:n}}throw new T("invalid_response","Provider did not return the required tool call.")}catch(s){throw s instanceof T&&(s.attempts=o,s.usage=r),s}}};var kn={model:"ep-20260721150136-98dj9",modelEnv:"ARK_MODEL",baseUrl:"https://ark.cn-beijing.volces.com/api/v3",apiKeyEnv:"ARK_API_KEY",timeoutMs:6e5,maxAttempts:3},Jf=["gemini-3.8-flash","gemini-3.7-flash","gemini-3.6-flash"],Fi={protocol:"google-gemini",baseUrl:"https://grsai.dakka.com.cn",apiKeyEnv:"GRSAI_API_KEY",timeoutMs:6e5,maxAttempts:3,videoResponseSchemaField:"responseSchema",videoUploadMode:"base64"};function Kf(e){return e?.trim().replace(/\/+$/,"")??"anthropic-sdk-default"}function sa(e,t,n){let o=An[e],i=JSON.stringify({task:e,taskVersion:o.version,protocol:t.protocol,baseUrl:Kf(t.baseUrl),model:n.model,thinkingBudgetTokens:n.thinkingBudgetTokens??null,...o.mode==="video"&&t.videoResponseSchemaField==="responseSchema"?{videoResponseSchemaField:t.videoResponseSchemaField}:{},...o.mode==="document"&&t.documentResponseSchemaField==="responseSchema"?{documentResponseSchemaField:t.documentResponseSchemaField}:{}});return Bf.createHash("sha256").update(i).digest("hex")}function Ge(e,t,n){return new x(e,{exitCode:k,errorCode:"LLM_CONFIG_INVALID",hint:"Fix the selected LLM configuration and run `scriptctl doctor`.",data:{expected:t,actual:n}})}function Qi(e){return new x("The selected LLM provider credential is not configured.",{exitCode:X,errorCode:"LLM_CREDENTIAL_MISSING",hint:"Configure the credential and rerun `scriptctl doctor`.",data:{expected:["credential environment variable referenced by the selected provider"],actual:[`provider: ${e}`,"credential: missing"]}})}function oi(e,t){return Ut(Li(e.failure),{...Ar(e.failure),provider:t.provider,model:t.model,retryable:e.failure.retryable,message:e.message})}function Yi(e,t){if(t.length===1)return e;let n=au(t,"All configured model routes failed.");return new T(e.code,n.message,{retryable:n.retryable,classification:Li(n),context:Ar(n),modelFailures:t,details:t.map(hn)})}function Bx(e){return["google-gemini","google-vertex"].includes(e.protocol)||/(^|\/)gemini-/i.test(e.model)}function zd(e){let t=e.info.model.slice(0,e.info.model.lastIndexOf("/")+1);return[...new Set([e.info.model,...Jf.map(o=>t+o)])].map(o=>{if(o===e.info.model)return e;let i={...e.modelConfig,model:o};return{...e,modelConfig:i,info:{...e.info,model:o,fingerprint:sa(e.info.task,e.providerConfig,i)}}})}function ko(e,t){return!t?.aborted&&e instanceof T&&e.code!=="cancelled"}var Hr=class{constructor(t,n={}){this.config=t;this.options=n}config;options;adapters=new Map;videoAdapters=new Map;doubaoAdapters=new Map;resolvedRoutes=new Map;usageLog=[];get configSource(){return this.config.source}resolve(t){let n=this.resolvedRoutes.get(t);if(n)return n;let o=An[t];if(o.mode==="video"&&this.options.videoProvider?.provider==="doubao"){let l=this.resolveDoubao(t,!0);return this.resolvedRoutes.set(t,l),l}let i=this.options.profile??this.config.tasks[t]??o.defaultProfile,r=this.config.models[i];if(!r)throw Ge("The task route references a missing model profile.",[i],[`task: ${t}`]);let s=this.config.providers[r.provider];if(!s)throw Ge("The model profile references a missing provider.",[r.provider],[`profile: ${i}`]);if(s.protocol==="openai-compatible"&&!s.baseUrl)throw Ge("OpenAI-compatible providers require an explicit endpoint \u2014 set the provider's baseUrl, or PROJECT_LITELLM_GATEWAY_BASE_URL for the built-in gateway.",["provider.baseUrl"],[`provider: ${r.provider}`]);if(r.thinkingBudgetTokens!==void 0&&o.mode==="tool")throw Ge("Anthropic thinking cannot be combined with a forced tool call.",["a text task or a profile without thinking"],[`task: ${t}`,`profile: ${i}`]);if(o.mode!=="document"&&r.thinkingBudgetTokens!==void 0&&r.thinkingBudgetTokens>=o.maxOutputTokens)throw Ge("The thinking token budget must be smaller than the task output budget.",[`thinking budget < ${o.maxOutputTokens}`],[`task: ${t}`,`thinking budget: ${r.thinkingBudgetTokens}`]);let c=o.mode==="video"?this.options.videoProvider:void 0,a=c?.baseUrl?{...s,protocol:"google-gemini",baseUrl:Td(c.baseUrl,"--provider-base-url")}:s,d=c?.model?{...r,model:c.model.trim()}:r;if(c?.model!==void 0&&!d.model)throw Ge("The video provider model cannot be empty.",["non-empty --provider-model"],["model: empty"]);let p={info:{task:t,profile:i,provider:r.provider,protocol:a.protocol,baseUrl:a.baseUrl,model:d.model,fingerprint:sa(t,a,d),...o.mode==="video"&&a.videoUploadMode?{videoUploadMode:a.videoUploadMode}:{}},providerConfig:a,modelConfig:d};return this.resolvedRoutes.set(t,p),p}route(t){return this.resolve(t).info}routes(){return bf.map(t=>this.route(t))}emptyUsage(){return{calls:0,succeeded:0,failed:0,reused:0,attempts:0,durationMs:0,inputTokens:0,outputTokens:0,cachedInputTokens:0,cacheCreationTokens:0}}recordReuse(t){let n=new Date().toISOString();this.recordEvent(this.route(t),"reused",n,n,0,{})}usage(){let t=new Map;for(let n of this.usageLog){let o=`${n.task}\0${n.provider}\0${n.protocol}\0${n.model}\0${n.fingerprint}`,i=t.get(o)??{task:n.task,profile:n.profile,provider:n.provider,protocol:n.protocol,baseUrl:n.baseUrl,model:n.model,fingerprint:n.fingerprint,...this.emptyUsage()};n.status==="reused"?i.reused+=1:(i.calls+=1,i[n.status]+=1,i.attempts+=n.attempts,i.durationMs+=n.durationMs,i.inputTokens+=n.inputTokens,i.outputTokens+=n.outputTokens,i.cachedInputTokens+=n.cachedInputTokens,i.cacheCreationTokens+=n.cacheCreationTokens),t.set(o,i)}return[...t.values()]}usageEvents(){return this.usageLog.map(t=>({...t}))}recordEvent(t,n,o,i,r,s,c=0,a){this.usageLog.push({...t,sequence:this.usageLog.length+1,status:n,attempts:c,startedAt:o,endedAt:i,durationMs:r,inputTokens:s.inputTokens??0,outputTokens:s.outputTokens??0,cachedInputTokens:s.cachedInputTokens??0,cacheCreationTokens:s.cacheCreationTokens??0,...a?{errorCode:a}:{}})}async tracked(t,n){let o=Date.now(),i=new Date(o).toISOString();try{let r=await n(),s=Date.now();return this.recordEvent(t,"succeeded",i,new Date(s).toISOString(),s-o,r.usage??{},r.attempts),r}catch(r){let s=Date.now(),c=r instanceof T?r:null;throw this.recordEvent(t,"failed",i,new Date(s).toISOString(),s-o,c?.usage??{},c?.attempts??1,c?.code),r}}resolveDoubao(t,n){let o=n?this.options.videoProvider:void 0,i=n?(o?.model??process.env.ARK_MODEL??"").trim():this.doubaoModel();if(!i)throw Ge("Doubao requires --provider-model or ARK_MODEL.",["--provider-model <id> or ARK_MODEL"],["model: empty"]);let r={protocol:"openai-compatible",baseUrl:o?.baseUrl?Td(o.baseUrl,"--provider-base-url"):kn.baseUrl,apiKeyEnv:kn.apiKeyEnv,timeoutMs:kn.timeoutMs,maxAttempts:kn.maxAttempts},s={provider:"doubao",model:i};return{info:{task:t,profile:n?"doubao":"doubao-fallback",provider:"doubao",protocol:r.protocol,baseUrl:r.baseUrl,model:i,fingerprint:sa(t,r,s)},providerConfig:r,modelConfig:s}}doubaoRoute(t){return this.resolveDoubao(t,!1).info}adapter(t){let n=`${t.info.provider}\0${t.info.model}\0${t.modelConfig.thinkingBudgetTokens??""}`,o=this.adapters.get(n);if(o)return o;let i=(process.env[t.providerConfig.apiKeyEnv]??"").trim();if(!i&&t.providerConfig.protocol!=="google-vertex")throw Qi(t.info.provider);let r=t.providerConfig.protocol==="anthropic"?new Ws(t.providerConfig,t.modelConfig,i):new ra(t.providerConfig,t.modelConfig,i);return this.adapters.set(n,r),r}videoAdapter(t){if(!["google-gemini","google-vertex"].includes(t.providerConfig.protocol))throw Ge("Video tasks require a google-gemini provider.",["provider.protocol: google-gemini"],[`provider: ${t.info.provider}`,`protocol: ${t.providerConfig.protocol}`]);let n=t.info.model,o=`${t.info.provider} ${t.providerConfig.baseUrl??"official"} ${n}`,i=this.videoAdapters.get(o);if(i)return i;let r=this.videoCredential(t);if(!r&&t.providerConfig.protocol!=="google-vertex")throw Qi(t.info.provider);let s=new ia(t.providerConfig,t.modelConfig,r);return this.videoAdapters.set(o,s),s}videoCredential(t){let n=this.resolve(t.info.task).info,o=t.info.provider===n.provider&&t.info.baseUrl===n.baseUrl?this.options.videoProvider?.apiKey:void 0,i=o?.kind==="literal"?o.value.trim():o?.kind==="env"?(process.env[o.name]??"").trim():(process.env[t.providerConfig.apiKeyEnv]??"").trim();if(!i&&(o||t.providerConfig.protocol!=="google-vertex"))throw Qi(t.info.provider);return i}grsaiVideoRoutes(t){return!(process.env[Fi.apiKeyEnv]??"").trim()||Kf(t.providerConfig.baseUrl)===Fi.baseUrl?[]:Jf.map(n=>{let o={provider:"grsai",model:n};return{providerConfig:Fi,modelConfig:o,info:{task:t.info.task,profile:"grsai-fallback",provider:"grsai",protocol:Fi.protocol,baseUrl:Fi.baseUrl,model:n,videoUploadMode:"base64",fingerprint:sa(t.info.task,Fi,o)}}})}grsaiVideoMedia(t){if(t.media.kind==="base64")return t.media;let n=t.media.kind==="local-fallback"?t.media.path:t.localPath;if(!n)throw Ge("GrsAI video fallback requires the local video.",["localPath"],["localPath: missing"]);let o=t.localMime??(t.media.kind==="file-api"?t.media.file.mimeType:t.media.mimeType);return{kind:"base64",data:Hd.readFileSync(n,"base64"),mimeType:o}}documentPort(t){if(An[t].mode!=="document")throw Ge("The task does not support document generation.",["document task"],[t]);let n=this.resolve(t);if(n.providerConfig.protocol!=="google-gemini"&&n.providerConfig.protocol!=="google-vertex")throw Ge("PDF tasks require a Gemini provider.",["google-gemini or google-vertex"],[n.providerConfig.protocol]);let o=(process.env[n.providerConfig.apiKeyEnv]??"").trim();if(!o&&n.providerConfig.protocol!=="google-vertex")throw Qi(n.info.provider);let i=new zr(n.providerConfig,n.modelConfig,o),r=new WeakMap;return{prepare:async(s,c)=>{let a;try{a=await i.prepare(s,c)}catch(d){if(!ko(d,c))throw d;process.stderr.write(`\u21AA\uFE0F PDF \u4E0A\u4F20\u5931\u8D25\uFF0C\u4F7F\u7528\u539F\u6587\u6863\u5B57\u8282\u7EE7\u7EED\u6A21\u578B\u8BF7\u6C42 (${hn(d.failure)})
158
+ `),a={kind:"base64",data:Hd.readFileSync(s).toString("base64"),mimeType:"application/pdf"}}return r.set(a,s),a},generate:async s=>{let c=zd(n),a=[];for(let[d,p]of c.entries()){s.signal?.throwIfAborted();let l=d===0?i:new zr(p.providerConfig,p.modelConfig,o);try{return await this.tracked(p.info,()=>l.generate(s))}catch(f){if(!ko(f,s.signal))throw f;let u=oi(f,p.info);a.push(u);let m=c[d+1];if(m){process.stderr.write(`\u21AA\uFE0F ${p.info.model} \u6587\u6863\u8BF7\u6C42\u5931\u8D25\uFF0C\u5207\u6362\u5230 ${m.info.model} (${hn(u)})
159
+ `);continue}let h=this.arkAdapter();if(!h)throw Yi(f,a);let g=this.doubaoRoute(t);process.stderr.write(`\u21AA\uFE0F \u6587\u6863\u6A21\u578B\u8DEF\u7531\u5DF2\u8017\u5C3D\uFF0C\u56DE\u9000\u5230\u8C46\u5305 ${g.model}
160
+ `);try{return await this.tracked(g,()=>h.generateDocument(s,r.get(s.media)))}catch(w){throw ko(w,s.signal)?Yi(w,[...a,oi(w,g)]):w}}}throw new Error("Document model routes cannot be empty.")},release:async(s,c)=>{r.delete(s),await i.release(s,c)}}}videoPort(t){let n=An[t];if(n.mode!=="video")throw Ge("The task does not support video generation.",["video task"],[`task: ${t}`]);let o=this.resolve(t);if(this.options.videoProvider?.provider==="doubao"){let r=this.doubaoAdapter(o);if(!r)throw Qi("doubao");return{prepare:async(s,c,a,d)=>{if(a!=="file-api")throw Ge("Doubao requires file-api upload mode.",["file-api"],[a]);return d?.throwIfAborted(),{kind:"local",path:s,mimeType:c}},generate:s=>{if(s.media.kind!=="local")throw Ge("Doubao requires locally prepared video.",["local media"],[s.media.kind]);s.signal?.throwIfAborted();let{path:c,mimeType:a}=s.media;return this.tracked(o.info,()=>r.run({localPath:c,localMime:a,user:s.user,fps:s.fps,maxOutputTokens:n.maxOutputTokens,...s.system?{system:s.system}:{},...s.responseJsonSchema?{responseJsonSchema:s.responseJsonSchema}:{},...s.acceptsText?{acceptsText:s.acceptsText}:{},...s.signal?{signal:s.signal}:{}}))},release:async()=>{}}}if(!["google-gemini","google-vertex"].includes(o.providerConfig.protocol))throw Ge("Video tasks require a google-gemini provider.",["provider.protocol: google-gemini"],[`provider: ${o.info.provider}`,`protocol: ${o.providerConfig.protocol}`]);let i=this.videoAdapter(o);return{prepare:async(r,s,c,a)=>{let d=Date.now();try{return await i.prepare(r,s,c,a)}catch(p){if(!ko(p,a)||!this.grsaiVideoRoutes(o).length&&!this.doubaoAdapter())throw p;return this.recordEvent(o.info,"failed",new Date(d).toISOString(),new Date().toISOString(),Date.now()-d,p.usage,p.attempts,p.code),{kind:"local-fallback",path:r,mimeType:s,primaryFailure:oi(p,o.info)}}},release:(r,s)=>r.kind==="local-fallback"?Promise.resolve():i.release(r,s),generate:async r=>{r.signal?.throwIfAborted();let s=[...r.media.kind==="local-fallback"?[]:zd(o),...this.grsaiVideoRoutes(o)],c=r.media.kind==="local-fallback"?[r.media.primaryFailure]:[],a;for(let[d,p]of s.entries()){r.signal?.throwIfAborted();try{let l=p.providerConfig===o.providerConfig?r.media:a??=this.grsaiVideoMedia(r);return await this.tracked(p.info,()=>this.videoAdapter(p).generate({...r,media:l,maxOutputTokens:n.maxOutputTokens}))}catch(l){if(!ko(l,r.signal))throw l;let f=oi(l,p.info);c.push(f);let u=s[d+1];if(u){process.stderr.write(`\u21AA\uFE0F ${p.info.provider}/${p.info.model} \u8BF7\u6C42\u5931\u8D25\uFF0C\u5207\u6362\u5230 ${u.info.provider}/${u.info.model} (${hn(f)})
161
+ `);continue}if(!this.doubaoAdapter()||!r.localPath&&r.media.kind!=="local-fallback")throw Yi(l,c);return this.generateDoubaoVideo(t,r,c)}}return this.generateDoubaoVideo(t,r,c)}}}async generateDoubaoVideo(t,n,o){let i=this.doubaoAdapter();if(!i)throw Qi("doubao");let r=n.media.kind==="local-fallback"?n.media.path:n.localPath;if(!r)throw Ge("Doubao video fallback requires the local video.",["localPath"],["localPath: missing"]);let s=n.localMime??(n.media.kind==="file-api"?n.media.file.mimeType:n.media.mimeType),c=An[t];if(c.mode!=="video")throw Ge("Expected a video task.",["video task"],[t]);let a=this.doubaoRoute(t);process.stderr.write(`\u21AA\uFE0F Gemini \u8DEF\u7531\u5DF2\u8017\u5C3D\uFF0C\u56DE\u9000\u5230\u8C46\u5305 ${a.model}
162
+ `);try{return await this.tracked(a,()=>i.run({localPath:r,localMime:s,user:n.user,fps:n.fps,maxOutputTokens:c.maxOutputTokens,...n.system?{system:n.system}:{},...n.responseJsonSchema?{responseJsonSchema:n.responseJsonSchema}:{},...n.acceptsText?{acceptsText:n.acceptsText}:{},...n.signal?{signal:n.signal}:{}}))}catch(d){throw ko(d,n.signal)?Yi(d,[...o,oi(d,a)]):d}}doubaoAdapter(t){return this.arkAdapter(t)}doubaoTextAdapter(){return this.arkAdapter()}arkAdapter(t){let n=t?this.videoCredential(t):(process.env[kn.apiKeyEnv]??"").trim();if(!n)return null;let o=t?.info.model??this.doubaoModel(),i=t?.providerConfig.baseUrl??kn.baseUrl,r=`doubao ${i} ${o}`,s=this.doubaoAdapters.get(r);if(s)return s;let c=new ta(o,kn.timeoutMs,kn.maxAttempts,n,i);return this.doubaoAdapters.set(r,c),c}doubaoModel(){return(process.env[kn.modelEnv]??"").trim()||kn.model}async withTextFallback(t,n,o){let i=this.resolve(t),r=Bx(i.info),s=r?zd(i):[i],c=[];for(let[a,d]of s.entries()){n?.throwIfAborted();let p=this.adapter(d);try{return await this.tracked(d.info,()=>o(p))}catch(l){if(!ko(l,n)||!r&&l.code!=="content_filtered")throw l;let f=oi(l,d.info);c.push(f);let u=s[a+1];if(u){process.stderr.write(`\u21AA\uFE0F ${d.info.model} \u8BF7\u6C42\u5931\u8D25\uFF0C\u5207\u6362\u5230 ${u.info.model} (${hn(f)})
163
+ `);continue}let m=this.doubaoTextAdapter();if(!m)throw Yi(l,c);let h=this.doubaoRoute(t);process.stderr.write(`\u21AA\uFE0F \u4E3B\u6A21\u578B\u8DEF\u7531\u5DF2\u8017\u5C3D\uFF0C\u56DE\u9000\u5230\u8C46\u5305 ${h.model}
164
+ `);try{return await this.tracked(h,()=>o(m))}catch(g){throw ko(g,n)?Yi(g,[...c,oi(g,h)]):g}}}throw new Error("Text model routes cannot be empty.")}async generateText(t,n){let o=An[t];if(o.mode!=="text")throw Ge("The task does not support text generation.",["text task"],[`task: ${t}`]);return this.withTextFallback(t,n.signal,i=>i.generateText({...n,maxOutputTokens:o.maxOutputTokens}))}async generateTool(t,n){let o=An[t];if(o.mode!=="tool")throw Ge("The task does not support tool generation.",["tool task"],[`task: ${t}`]);return this.withTextFallback(t,n.signal,i=>i.generateTool({...n,maxOutputTokens:o.maxOutputTokens}))}};function jf(e,t){return new Hr(Ao(e),t)}var Kx=Jx(import.meta.url);function aa(e){try{return Kx.resolve(e),!0}catch{return!1}}function jx(e){let t=!1;try{Bt.statSync(e).isDirectory()&&(Bt.accessSync(e,Bt.constants.W_OK),t=!0)}catch{t=!1}let n=!1;try{n=Bt.statSync(ii.join(e,"script.json")).isFile()}catch{n=!1}return{writable:t,hasScript:n}}function zx(){return ii.join(ii.dirname(ii.resolve("workspace")),"output")}function zf(e={}){let t=Md(),n=[],o=new Set;for(let R of t)try{if(!Bt.existsSync(R)||!Bt.statSync(R).isFile())continue;let J=Bt.realpathSync(R);if(o.has(J))continue;o.add(J),n.push(R)}catch{}let i=typeof e.llm_config=="string"?e.llm_config.trim():"",r=Ao(i||void 0),c=new Hr(r).routes(),a=Object.entries(r.providers).map(([R,J])=>({alias:R,configured:!!(process.env[J.apiKeyEnv]??"").trim(),env:J.apiKeyEnv})),d=Object.entries(r.providers).filter(([,R])=>R.protocol==="openai-compatible").map(([R,J])=>{let W="not set";if(J.baseUrl)try{W=new URL(J.baseUrl).host}catch{W=J.baseUrl}return{alias:R,host:W}}),{mode:p}=kf(),l=(process.env.SCRIPTCTL_OUTPUT_DIR??"").trim()||zx(),f=p==="local"?jx(l):null,u=!!process.env.AWB_BASE_URL,m=!!process.env.LINGJING_AWB_ACCESS_KEY,h=!!process.env.SANDBOX_PROJECT_GROUP_NO,g={"@anthropic-ai/sdk":aa("@anthropic-ai/sdk"),"@google/genai":aa("@google/genai"),jszip:aa("jszip"),"fast-xml-parser":aa("fast-xml-parser")},w=Object.entries(g).filter(([,R])=>!R).map(([R])=>R),y=process.versions.node,_=`env_file: ${n[0]??"missing"}`,S=R=>R?"configured":"not configured",A=[`node: ${y}`,"storage: local-filesystem",_,`llm config: ${r.source}`,`llm routes: ${c.length}`,...a.map(R=>`llm provider ${R.alias}: ${S(R.configured)}`),...d.map(R=>`llm provider ${R.alias} endpoint: ${R.host}`)];p===null?A.push("output target: not configured"):p==="local"&&f?(A.push(`output writable: ${S(f.writable)}`),A.push(`output snapshot: ${f.hasScript?"present":"absent"}`)):(A.push(`gateway endpoint: ${S(u)}`),A.push(`gateway access credential: ${S(m)}`),A.push(`gateway project identifier: ${S(h)}`));for(let[R,J]of Object.entries(g))A.push(`dependency ${R}: ${J?"ok":"missing"}`);let b=[];w.length>0&&b.push("Install missing CLI dependencies (see above)."),a.some(R=>!R.configured)&&b.push("Configure every credential referenced by the selected LLM configuration."),d.some(R=>R.host==="not set")&&b.push("An openai-compatible provider has no endpoint \u2014 set PROJECT_LITELLM_GATEWAY_BASE_URL (built-in gateway) or the provider's baseUrl."),p===null?b.push("Configure an output target before running `publish` / script CRUD."):p==="local"?f&&!f.writable&&b.push("Output target is not writable; check directory permissions."):(!u||!m||!h)&&b.push("Configure gateway credentials before running `publish` / script CRUD against the remote project."),b.length===0&&b.push("Environment looks ready.");let[U,M]=y.split(".").map(R=>parseInt(R,10)),I=(U??0)>20||(U??0)===20&&(M??0)>=0,v=p===null?{configured:!1}:p==="local"?{dir:{ok:!!f?.writable,writable:!!f?.writable,hasScript:!!f?.hasScript}}:{endpoint:{ok:u},access:{ok:m},project:{ok:h}},L={node:{version:y,ok:I},storage:{backend:"local-filesystem",ok:!0},env:{ok:n.length>0,paths:n},llm:{config_source:r.source,...r.sourcePath?{config_path:r.sourcePath}:{},providers:a.map(R=>({alias:R.alias,ok:R.configured,credential_env:R.env,...d.find(J=>J.alias===R.alias)?{endpoint:d.find(J=>J.alias===R.alias).host}:{}})),profiles:Object.keys(r.models),routes:c.map(R=>({task:R.task,profile:R.profile,provider:R.provider,protocol:R.protocol,model:R.model}))},output:v,dependencies:g};return[{text:[...A,...b].join(`
165
+ `),data:{checks:L}},G]}import{spawn as Hx}from"node:child_process";var ca="@lingjingai/scriptctl",Fx=`${ca}@latest`,Fd="npm";function Qx(){return ji()}function Yx(e){let t=/^(\d+)\.(\d+)\.\d+/.exec(e);return t?`${ca}@~${t[1]}.${t[2]}.0`:null}function qx(e){return["install","-g",e]}function Zx(e,t){return[e,...t].join(" ")}function Wx(e,t){return e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0).slice(-t)}function Xx(e,t){return new Promise(n=>{let o=Hx(e,[...t],{stdio:["ignore","pipe","pipe"]}),i=[],r=[];o.stdout.setEncoding("utf-8"),o.stderr.setEncoding("utf-8"),o.stdout.on("data",s=>i.push(s)),o.stderr.on("data",s=>r.push(s)),o.once("error",s=>{n({exitCode:null,signal:null,stdout:i.join(""),stderr:r.join(""),error:s})}),o.once("close",(s,c)=>{n({exitCode:s,signal:c,stdout:i.join(""),stderr:r.join("")})})})}async function Hf(e,t=Xx,n=Qx){let o=!!e.patch,i=n(),r=o?Yx(i):Fx;if(!r)throw new x(`Cannot compute a patch update range from version ${i}.`,{exitCode:X,errorCode:"UPDATE_VERSION_INVALID",hint:"Run `scriptctl update` without --patch to install the latest version.",data:{version:i}});let s=[...qx(r)],c=Zx(Fd,s),a={package:ca,package_spec:r,command:Fd,args:s,command_line:c};if(e.dry_run)return[{text:[`package: ${ca}`,`command: ${c}`,"dry-run: no update performed"].join(`
166
+ `),data:{op:"update",changed:!1,update:a}},G];let d=await t(Fd,s);if(d.error)throw new x(`Failed to start npm: ${d.error.message}`,{exitCode:X,errorCode:"UPDATE_SPAWN_FAILED",hint:`Run '${c}' after fixing the npm installation.`,data:{update:a,cause:d.error.message}});if(d.exitCode!==G){let f=[`exit: ${d.exitCode===null?`signal ${d.signal??"unknown"}`:String(d.exitCode)}`,...Wx(d.stderr,5).map(u=>`stderr: ${u}`)];throw new x("npm could not update scriptctl.",{exitCode:X,errorCode:"UPDATE_COMMAND_FAILED",hint:`Run '${c}' after resolving the npm error.`,data:{update:a,actual:f}})}let p=n(),l=p!==i;return[{text:l?`Updated ${i} \u2192 ${p}.`:`Already up to date (${p}).`,data:{op:"update",changed:l,status:l?"updated":"already_latest",previous_version:i,version:p}},G]}function Ff(e,t){e.command("doctor").description("Check configuration and runtime dependencies").option("--llm-config <path>","LLM configuration file").action(H(zf,t)),e.command("update").description("Update scriptctl to the latest release").option("-n, --dry-run","Show the update without installing").option("--patch","Allow a patch-level update").action(H(Hf,t));let n=e.command("changelog [version]").description("Show release notes").option("--from <version>","Start version").option("--to <version>","End version").option("--unreleased","Show unreleased changes").action(H(xf,t));Me(n,["Release version"])}import*as pi from"node:fs";import*as Aa from"node:path";import{fileURLToPath as aS,pathToFileURL as cS}from"node:url";import*as rt from"node:fs";import*as it from"node:path";import{createHash as Pm}from"node:crypto";import{z as ot}from"zod";import*as Oo from"node:fs";var Qf=null,e5=0;function F(e,t){Qf&&Qf.push({fn:e,note:t,ms:Math.round((performance.now()-e5)*100)/100})}var t5=[["actor","actors","actor"],["location","locations","location"],["prop","props","prop"]];function bo(e){return Array.isArray(e)?e:[]}function ke(e){return typeof e=="string"?e:""}function Qn(e,t,n,o){if(t){if(e.has(t)&&e.get(t)!==n){o.add(t);return}e.set(t,n)}}function Yd(e){return vo(JSON.parse(Oo.readFileSync(e,"utf8")),e)}function vo(e,t=""){let n=e?.version;if(n!==3&&n!==4)throw new Error(`Unsupported script.version: ${JSON.stringify(n)} (expected 3 or 4)`);let o={version:n,path:t,raw:e,episodes:[],assets:[],byId:new Map,eps:new Map,scenes:new Map,actions:new Map};for(let[a,d,p]of t5)for(let l of bo(e[d])){let f={id:ke(l[`${p}_id`]),kind:a,name:ke(l[`${p}_name`]),aliases:bo(l.aliases).map(ke).filter(Boolean),importance:ke(l.importance),desc:ke(l.description),states:bo(l.states).map(u=>({id:ke(u.state_id),name:ke(u.state_name),desc:ke(u.description)})),raw:l,label:""};o.assets.push(f),o.byId.set(f.id,f)}let i=new Map;for(let a of o.assets)for(let d of[a.name,...a.aliases])i.set(d,(i.get(d)??0)+1);for(let a of o.assets)a.label=[a.name,...a.aliases].filter(d=>i.get(d)===1).sort((d,p)=>d.length-p.length)[0]??a.name;let r=new Set,s=0,c=0;bo(e.episodes).forEach((a,d)=>{let p={anchor:String(d+1),id:ke(a.episode_id),no:d+1,title:ke(a.title)||void 0,synopsis:ke(a.synopsis)||void 0,scenes:[],raw:a};bo(a.scenes).forEach((l,f)=>{s++;let u={anchor:n===4?ke(l.scene_id):`${d+1}-${f+1}`,id:ke(l.scene_id),no:f+1,gno:s,env:l.environment??{},location:Qd(l.location,"location_id"),actors:bo(l.actors).map(m=>Qd(m,"actor_id")).filter(Boolean),props:bo(l.props).map(m=>Qd(m,"prop_id")).filter(Boolean),actions:[],raw:l,ep:p};bo(l.actions).forEach((m,h)=>{c++;let g={anchor:n===4?ke(m.action_id):`${d+1}-${f+1}-${h+1}`,no:h+1,gno:c,type:ke(m.type)||"action",content:ke(m.content),speaker:n5(m.speaker),paren:typeof m.parenthetical=="string"?m.parenthetical:typeof m.emotion=="string"?m.emotion:void 0,ts:ke(m.extend?.timestamp)||void 0,raw:m,scene:u};u.actions.push(g),Qn(o.actions,g.anchor,g,r),Qn(o.actions,`${d+1}-${f+1}-${h+1}`,g,r),n===3&&Qn(o.actions,`${p.id}/${u.id}#${h}`,g,r)}),p.scenes.push(u),Qn(o.scenes,u.anchor,u,r),Qn(o.scenes,`${d+1}-${f+1}`,u,r),Qn(o.scenes,`${p.id}/${u.id}`,u,r),Qn(o.scenes,u.id,u,r)}),o.episodes.push(p),Qn(o.eps,String(d+1),p,r),Qn(o.eps,p.id,p,r)});for(let a of r)o.actions.delete(a),o.scenes.delete(a),o.eps.delete(a);return F(t?"model.load":"model.parse",`v${n} \xB7 ${o.episodes.length} ep \xB7 ${o.scenes.size} scene keys \xB7 ${o.actions.size} action keys \xB7 ${o.assets.length} assets \xB7 ${r.size} ambiguous keys dropped`),o}function Qd(e,t){if(!e||typeof e!="object")return null;let n=ke(e[t]);if(!n)return null;let o=Array.isArray(e.state_ids)?e.state_ids.map(ke):e.state_id?[ke(e.state_id)]:[];return{id:n,states:o,raw:e}}function n5(e){if(!(!e||typeof e!="object")){if(e.actor_id)return{id:ke(e.actor_id),state:ke(e.state_id)||void 0};if(e.kind)return{kind:ke(e.kind),label:ke(e.label)||void 0}}}function Te(e,t){let n=t.trim();if(!n)return{t:"script",doc:e};let o=n.indexOf("/");if(o>0&&!e.scenes.has(n)){let p=n.slice(0,o),l=n.slice(o+1),f=e.byId.get(p)??o5(e,p);if(f){let u=f.states.filter(m=>m.id===l||m.name===l);if(u.length===1)return F("resolve",`"${n}" -> state ${f.id}/${u[0].id} "${u[0].name}"`),{t:"state",asset:f,state:u[0]};throw u.length>1?new Error(`${f.name} has ${u.length} states named "${l}"; address it by state id`):new Error(`${f.name} has no state "${l}" (has: ${f.states.map(m=>`${m.id}(${m.name})`).join(", ")})`)}}let i=e.actions.get(n);if(i)return F("resolve",`"${n}" -> action map hit -> ${i.anchor}`),{t:"action",action:i};let r=e.scenes.get(n);if(r)return F("resolve",`"${n}" -> scene map hit -> ${r.anchor}`),{t:"scene",scene:r};let s=e.eps.get(n);if(s)return F("resolve",`"${n}" -> episode map hit -> ${s.id}`),{t:"ep",ep:s};let c=e.byId.get(n);if(c)return F("resolve",`"${n}" -> asset id hit -> ${c.name}`),{t:"asset",asset:c};let a=e.assets.filter(p=>p.name===n||p.aliases.includes(n));if(a.length===1)return F("resolve",`"${n}" -> exact name/alias -> ${a[0].id} ${a[0].name}`),{t:"asset",asset:a[0]};if(a.length>1)throw new Error(`Ambiguous name "${n}": ${a.map(p=>`${p.id}(${p.name})`).join(", ")}`);let d=e.assets.filter(p=>p.name.includes(n)||p.aliases.some(l=>l.includes(n)));if(d.length===1)return F("resolve",`"${n}" -> substring name match -> ${d[0].id} ${d[0].name}`),{t:"asset",asset:d[0]};throw new Error(`Unknown address "${n}". Use an ordinal (3 / 3-2 / 3-2-5), a canonical ID, or an asset name.`+(d.length?` Did you mean: ${d.slice(0,5).map(p=>p.name).join(", ")}?`:""))}function o5(e,t){let n=e.assets.filter(i=>i.name===t||i.aliases.includes(t));if(n.length===1)return n[0];if(n.length>1)return;let o=e.assets.filter(i=>i.name.includes(t)||i.aliases.some(r=>r.includes(t)));return o.length===1?o[0]:void 0}function ri(e,t){return e.byId.get(t)?.label||t}function si(e,t,n){return e.byId.get(t)?.states.find(i=>i.id===n)?.name||n}function bn(e){return e.episodes.flatMap(t=>t.scenes.flatMap(n=>n.actions))}var i5={ep:"episode",scn:"scene",ac:"action",act:"actor",loc:"location",prp:"prop",st:"state"};function Ro(e,t){let n=br(i5[e],t);return t.add(n),F("newId",`${n} (collision-checked against ${t.size-1} live ids)`),n}function be(e){if(Object.assign(e,vo(e.raw,e.path)),!e.path){F("save","skipped: document is not bound to a file");return}Yf(e,e.path)}function Yf(e,t=e.path){if(!t)throw new Error("commit needs a path: this document is not bound to a file");let n=`${t}.tmp-${process.pid}`;Oo.writeFileSync(n,JSON.stringify(e.raw,null,2)+`
167
+ `),Oo.renameSync(n,t),F("commit",`${Oo.statSync(t).size} bytes -> ${t} (tmp + atomic rename)`)}var r5={system:"\u65C1\u767D",broadcast:"\u5E7F\u64AD",offscreen:"\u753B\u5916",group:"\u7FA4\u58F0"},qf="\u5FC3\u58F0";function s5(e,t){if(t.kind)return r5[t.kind]??t.kind;let n=ri(e,t.id);return t.state?`${n}\xB7${si(e,t.id,t.state)}`:n}function Fr(e,t,n,o={}){let i=(o.plain?"":t.anchor).padEnd(n),r=o.timestamps?`${t.ts??"[\u65F6\u95F4\u7F3A\u5931]"} `:!o.plain&&t.ts?`${t.ts} `:"",s=(()=>{if(t.type==="transition")return`\u2192 ${t.content}`;if(t.type==="dialogue"||t.type==="inner_thought"){let a=t.speaker?s5(e,t.speaker):"?",d=[t.type==="inner_thought"?qf:"",t.paren??""].filter(Boolean);return`${t.speaker?.kind&&t.speaker.label?`${a}\xB7${t.speaker.label}`:a}${d.length?`(${d.join("/")})`:""}\uFF1A${t.content}`}return t.content})(),c=`${i}${i?" ":""}`;return`${o.timestamps?r+c:c+r}${s}`.replace(/\n/g,"\\n")}function qd(e,t){let n=ri(e,t.id);return t.states.length===1&&t.states[0]==="default"?n:`${n}(${t.states.map(o=>si(e,t.id,o)).join("+")})`}function qi(e,t){let n=[t.env?.space,t.env?.time].filter(Boolean).join("/").toUpperCase(),o=t.location?qd(e,t.location):"\u2014",i=`## ${t.ep.no}-${t.no} ${t.anchor===`${t.ep.no}-${t.no}`?t.id:t.anchor} ${n||"\u2014"} ${o} ${t.actions.length} actions`,r=t.actors.map(a=>qd(e,a)).join(", "),s=t.props.map(a=>qd(e,a)).join(", "),c=[r&&`cast: ${r}`,s&&`props: ${s}`].filter(Boolean).join(" ");return c?`${i}
168
+ # ${c}`:i}function Zd(e,t,n={}){let o=n.plain?0:Math.max(0,...t.actions.map(i=>i.anchor.length));return F("formatScene",`${t.anchor}: ${t.actions.length} actions, gutter=${o}`),[qi(e,t),...t.actions.map(i=>Fr(e,i,o,n))].join(`
169
+ `)}var a5=/^([A-Za-z][A-Za-z0-9_]*|\d+(?:-\d+){0,2})\s\s+/;function Zf(e,t){let n=e.trimEnd();if(!n.trim())return null;let o,i=n.match(a5);i&&(o=i[1],n=n.slice(i[0].length)),n=n.replace(/\\n/g,`
170
+ `);let r,s=n.match(/^((?:\d+:)?\d+:\d{2}(?:\.\d{1,3})?)\s/);if(s&&(r=s[1],n=n.slice(s[0].length)),n.startsWith("\u2192"))return{anchor:o,ts:r,type:"transition",content:n.slice(1).trim()};let c=n.indexOf("\uFF1A");if(c>0){let d=n.slice(0,c).match(/^([^()]+)(?:\((.*)\))?$/);if(d&&t(d[1].trim())){let p=(d[2]??"").split("/").map(u=>u.trim()).filter(Boolean),l=p[0]===qf,f=(l?p.slice(1):p).join("/");return{anchor:o,ts:r,type:l?"inner_thought":"dialogue",speakerName:d[1].trim(),paren:f||void 0,content:n.slice(c+1).trim()}}}return{anchor:o,ts:r,type:"action",content:n.trim()}}var c5=/^(scn[1-9A-HJ-NP-Za-km-z]{6}|scn_\d+)$/,d5=/^[A-Z.\/]+$/,p5=/^\d+\s+actions?$/,l5={EXT:"exterior",EXTERIOR:"exterior",INT:"interior",INTERIOR:"interior"};function Wf(e){let t=e.findIndex(i=>i.startsWith("##"));if(t<0)return{body:e};let n=e[t+1]?.startsWith("#")&&!e[t+1].startsWith("##"),o=e.filter((i,r)=>r!==t&&!(n&&r===t+1));return{head:e[t],meta:n?e[t+1]:void 0,body:o}}function Wd(e,t){let n={env:{},cast:[],props:[]},o=e.replace(/^##\s*/,"").split(/\s{2,}/).map(i=>i.trim()).filter(Boolean);for(let i of o)if(!(/^\d+-\d+$/.test(i)||p5.test(i))){if(c5.test(i)){n.anchor=i;continue}if(d5.test(i)&&i!=="\u2014"){let[r,s]=i.split("/");r&&(n.env.space=l5[r]??r.toLowerCase()),s&&(n.env.time=s.toLowerCase());continue}i!=="\u2014"&&n.location===void 0&&(n.location=i)}if(t){let i=t.replace(/^#\s*/,""),r=i.match(/cast:\s*([^]*?)(?:\s\sprops:|$)/),s=i.match(/props:\s*([^]*)$/),c=a=>(a??"").split(",").map(d=>d.trim()).filter(Boolean);n.cast=c(r?.[1]),n.props=c(s?.[1])}return n}function Xf(e){let t=e.trim().match(/^(.*?)\s*\(([^)]*)\)$/);return t?{name:t[1].trim(),states:t[2].split("+").map(n=>n.trim()).filter(Boolean)}:{name:e.trim(),states:[]}}function Zi(e,t){throw Object.assign(new Error(e),t)}function ep(e){return e.episodes.flatMap(t=>t.scenes.flatMap(n=>n.actions.map((o,i)=>({address:e.version===4?o.anchor:`${t.id}/${n.id}#${i}`,episodeId:t.id,episodeNo:t.no,timestamp:o.ts}))))}function Xd(e){try{return uo(e.timestamp??"")}catch(t){if(!(t instanceof et))throw t;return Zi(`Action ${e.address} has an invalid stored timestamp.`,{code:"ACTION_SPAN_TIMESTAMP_INVALID",hint:`Fix it with \`scriptctl edit ${e.address} --ts <time>\` or remove it.`,data:{expected:["valid action.extend.timestamp"],actual:[`${e.address}: ${JSON.stringify(e.timestamp??"")}`]}})}}function em(e,t){return Zi("Action timestamps run backward within the selected episode.",{code:"ACTION_SPAN_TIMESTAMP_NON_MONOTONIC",hint:"Fix the stored timestamps so they do not move backward in document order, then rerun `span`.",data:{actual:[`${e.address}: ${e.timestamp}`,`${t.address}: ${t.timestamp}`]}})}function tp(e,t){t.length===0&&Zi("The action selection matched nothing.",{code:"ACTION_SPAN_NO_MATCH",hint:"Check the selector with `scriptctl actions` and rerun with `--span`.",data:{actual:["0 matched actions"]}});let n=new Set(t),o=e.filter(m=>n.has(m.address));o.length!==n.size&&Zi("The resolved action selection is inconsistent with the script timeline.",{code:"ACTION_SPAN_SELECTION_INCONSISTENT",data:{expected:[`${n.size} timeline actions`],actual:[`${o.length} timeline actions`]}});let i=new Set(o.map(m=>m.episodeId));i.size!==1&&Zi("An action timestamp span must stay within one episode.",{code:"ACTION_SPAN_CROSSES_EPISODES",hint:"Split the selector into one `span` call per episode.",data:{actual:[...i]}});let r=o[0],s=o[o.length-1];r.timestamp||Zi(`The first selected Action ${r.address} has no timestamp.`,{code:"ACTION_SPAN_START_TIMESTAMP_MISSING",hint:`Set it with \`scriptctl timestamp ${r.address} --set <time>\`, then rerun.`,data:{actual:[r.address]}});let c=Xd(r),a=r,d=c,p="";for(let m of o){if(!m.timestamp)continue;let h=Xd(m);h.milliseconds<d.milliseconds&&em(a,m),a=m,d=h,m.address===s.address&&(p=h.canonical)}let l=e.findIndex(m=>m.address===s.address),f,u;for(let m=l+1;m<e.length;m+=1){let h=e[m];if(h.episodeId!==r.episodeId)break;if(!h.timestamp)continue;let g=Xd(h);if(g.milliseconds<d.milliseconds&&em(a,h),g.milliseconds!==d.milliseconds){f=h,u=g;break}}return F("span",`${r.episodeId} ${c.canonical}..${u?.canonical??"(open)"} over ${o.length} action(s)`),{episode_id:r.episodeId,ep_no:r.episodeNo,start_timestamp:c.canonical,last_selected_timestamp:p,end_timestamp:u?.canonical??"",end_open:u===void 0,end_exclusive:!0,start_action:r.address,last_action:s.address,end_boundary_action:f?.address??"",matched_actions:o.length}}var np=["episode_id","ep_no","start_timestamp","last_selected_timestamp","end_timestamp","end_open","end_exclusive","start_action","last_action","end_boundary_action","matched_actions"];function op(e,t){return t.map(n=>{if(e.version===4)return n.anchor;let o=n.scene.actions.indexOf(n);return`${n.scene.ep.id}/${n.scene.id}#${o}`})}function ip(e,t,n={}){let o=n.offset??0,i=n.limit??20,r=n.context??3;for(let[f,u,m]of[["offset",o,0],["limit",i,1],["context",r,0]])if(!Number.isSafeInteger(u)||u<m)throw new Error(`${f} must be an integer >= ${m}`);let s=Te(e,t);if(s.t!=="asset"&&s.t!=="state")throw new Error("references requires an asset or asset/state address; use read for episodes/scenes/actions");let c=s.asset,a=s.t==="state"?s.state.id:null,d=[...new Set([c.id,c.name,...c.aliases])].filter(Boolean),p=[];for(let f of e.episodes)for(let u of f.scenes){let m=[...u.location?[u.location]:[],...u.actors,...u.props].filter(h=>h.id===c.id&&(a===null||h.states.includes(a)));m.length&&p.push({kind:"scene_binding",scene:u,matched:m.flatMap(h=>h.states)});for(let h of u.actions)if(h.speaker?.id===c.id&&(a===null||h.speaker.state===a)&&p.push({kind:"speaker",scene:u,action:h,matched:[c.id]}),a===null){let g=d.filter(w=>h.content.includes(w));g.length&&p.push({kind:"text_mention",scene:u,action:h,matched:g})}}let l=o+i;return{asset_id:c.id,state_id:a,total:p.length,next_offset:l<p.length?l:null,items:p.slice(o,l).map(({kind:f,scene:u,action:m,matched:h})=>{let g=m?u.actions.indexOf(m):-1,w=m?u.actions.slice(Math.max(0,g-r),g+r+1):[],y=Math.max(0,...w.map(_=>_.anchor.length));return{kind:f,address:m?.anchor??u.anchor,scene_address:u.anchor,episode:u.ep.no,matched:h,text:[qi(e,u),...w.map(_=>(_===m?"> ":" ")+Fr(e,_,y))].join(`
171
+ `)}})}}function rp(e){return[`${e.asset_id}${e.state_id===null?"":"/"+e.state_id} ${e.total} references \xB7 showing ${e.items.length}`,"scene_binding=explicit scene presence; speaker=explicit speaker; text_mention=name/alias mention only (not proof of presence).",...e.items.map(t=>`${t.address} ${t.kind} ep=${t.episode}
172
172
  ${t.text}`),e.next_offset===null?"end":`Continue: --offset ${e.next_offset}`].join(`
173
173
 
174
- `)}var l5=["\u65C1\u767D","\u5E7F\u64AD","\u753B\u5916","\u7FA4\u58F0"],u5={\u65C1\u767D:"system",\u5E7F\u64AD:"broadcast",\u753B\u5916:"offscreen",\u7FA4\u58F0:"group"};function f5(e){let t=new Set(l5);for(let n of e.assets){t.add(n.name);for(let o of n.aliases)t.add(o)}return n=>t.has(n)||t.has(n.split("\xB7")[0])}function ca(e,t="",n={}){let o=Te(e,t);switch(Q("read",`dispatch on node kind "${o.t}"`),o.t){case"script":return g5(e);case"ep":return h5(e,o.ep,n);case"scene":return Yd(e,o.scene,n);case"asset":return y5(e,o.asset);case"state":return w5(e,o.asset,o.state);case"action":{let i=n.context??3,r=o.action.scene.actions,s=r.indexOf(o.action),c=r.slice(Math.max(0,s-i),s+i+1),a=n.plain?0:Math.max(...c.map(l=>l.anchor.length)),d=o.action.raw.transition_prompt,p=Object.entries(o.action.raw.extend??{}).filter(([l])=>l!=="timestamp");return[Qi(e,o.action.scene),...c.map(l=>(l===o.action?"> ":" ")+zr(e,l,a,n)),d?`transition: ${ri(e,d.target)} | ${d.process} | ${d.contrast}`:"",p.length?`extend: ${p.map(([l,f])=>`${l}=${JSON.stringify(f)}`).join(", ")}`:""].filter(Boolean).join(`
175
- `)}}}function m5(e){return e.actions.reduce((t,n)=>t+n.content.length,0)}function g5(e){let t=e.raw,n=e.episodes.reduce((r,s)=>r+s.scenes.length,0),o=e.episodes.reduce((r,s)=>r+s.scenes.reduce((c,a)=>c+a.actions.length,0),0),i=[`${t.title||"(untitled)"} v${e.version} ${e.episodes.length} ep \xB7 ${n} scenes \xB7 ${o} actions`];for(let r of["logline","theme","synopsis","worldview","style"])t[r]&&i.push(`${r}: ${Hr(String(t[r]),300)}`);Array.isArray(t.main_characters)&&t.main_characters.length&&i.push(`main: ${t.main_characters.map(r=>`${r.name}=${r.role}`).join(", ")}`);for(let r of["actor","location","prop"]){let s=e.assets.filter(c=>c.kind===r);if(s.length){i.push("",`${r}s (${s.length})`);for(let c of s.slice(0,40)){let a=c.aliases.length?` ~${c.aliases.join(",")}`:"",d=c.importance?` [${c.importance}]`:"";i.push(` ${c.id} ${c.name}${d} ${c.states.length}st${a}`)}s.length>40&&i.push(` \u2026 ${s.length-40} more`)}}i.push("","episodes");for(let r of e.episodes){let s=r.scenes.reduce((c,a)=>c+m5(a),0);i.push(` ${r.no} ${r.id} ${r.scenes.length} scenes ${s} chars${r.title?` ${r.title}`:""}`+(r.synopsis?` ${Hr(r.synopsis,120)}`:""))}return i.join(`
176
- `)}function h5(e,t,n){let o=`# EP${String(t.no).padStart(2,"0")} ${t.id} ${t.scenes.length} scenes`+(t.title?` ${t.title}`:"");return n.depth==="outline"?[o,...t.scenes.map(i=>Qi(e,i))].join(`
177
- `):[o,...t.scenes.map(i=>Yd(e,i,n))].join(`
174
+ `)}var u5=["\u65C1\u767D","\u5E7F\u64AD","\u753B\u5916","\u7FA4\u58F0"],f5={\u65C1\u767D:"system",\u5E7F\u64AD:"broadcast",\u753B\u5916:"offscreen",\u7FA4\u58F0:"group"};function m5(e){let t=new Set(u5);for(let n of e.assets){t.add(n.name);for(let o of n.aliases)t.add(o)}return n=>t.has(n)||t.has(n.split("\xB7")[0])}function pa(e,t="",n={}){let o=Te(e,t);switch(F("read",`dispatch on node kind "${o.t}"`),o.t){case"script":return h5(e);case"ep":return y5(e,o.ep,n);case"scene":return Zd(e,o.scene,n);case"asset":return w5(e,o.asset);case"state":return _5(e,o.asset,o.state);case"action":{let i=n.context??3,r=o.action.scene.actions,s=r.indexOf(o.action),c=r.slice(Math.max(0,s-i),s+i+1),a=n.plain?0:Math.max(...c.map(l=>l.anchor.length)),d=o.action.raw.transition_prompt,p=Object.entries(o.action.raw.extend??{}).filter(([l])=>l!=="timestamp");return[qi(e,o.action.scene),...c.map(l=>(l===o.action?"> ":" ")+Fr(e,l,a,n)),d?`transition: ${ri(e,d.target)} | ${d.process} | ${d.contrast}`:"",p.length?`extend: ${p.map(([l,f])=>`${l}=${JSON.stringify(f)}`).join(", ")}`:""].filter(Boolean).join(`
175
+ `)}}}function g5(e){return e.actions.reduce((t,n)=>t+n.content.length,0)}function h5(e){let t=e.raw,n=e.episodes.reduce((r,s)=>r+s.scenes.length,0),o=e.episodes.reduce((r,s)=>r+s.scenes.reduce((c,a)=>c+a.actions.length,0),0),i=[`${t.title||"(untitled)"} v${e.version} ${e.episodes.length} ep \xB7 ${n} scenes \xB7 ${o} actions`];for(let r of["logline","theme","synopsis","worldview","style"])t[r]&&i.push(`${r}: ${Qr(String(t[r]),300)}`);Array.isArray(t.main_characters)&&t.main_characters.length&&i.push(`main: ${t.main_characters.map(r=>`${r.name}=${r.role}`).join(", ")}`);for(let r of["actor","location","prop"]){let s=e.assets.filter(c=>c.kind===r);if(s.length){i.push("",`${r}s (${s.length})`);for(let c of s.slice(0,40)){let a=c.aliases.length?` ~${c.aliases.join(",")}`:"",d=c.importance?` [${c.importance}]`:"";i.push(` ${c.id} ${c.name}${d} ${c.states.length}st${a}`)}s.length>40&&i.push(` \u2026 ${s.length-40} more`)}}i.push("","episodes");for(let r of e.episodes){let s=r.scenes.reduce((c,a)=>c+g5(a),0);i.push(` ${r.no} ${r.id} ${r.scenes.length} scenes ${s} chars${r.title?` ${r.title}`:""}`+(r.synopsis?` ${Qr(r.synopsis,120)}`:""))}return i.join(`
176
+ `)}function y5(e,t,n){let o=`# EP${String(t.no).padStart(2,"0")} ${t.id} ${t.scenes.length} scenes`+(t.title?` ${t.title}`:"");return n.depth==="outline"?[o,...t.scenes.map(i=>qi(e,i))].join(`
177
+ `):[o,...t.scenes.map(i=>Zd(e,i,n))].join(`
178
178
 
179
- `)}function y5(e,t){let n=t.raw.role_type?` <${t.raw.role_type}>`:"",o=[`${t.id} ${t.name} ${t.kind}${t.importance?` [${t.importance}]`:""}${n}`];t.aliases.length&&o.push(`aliases: ${t.aliases.join(", ")}`),t.desc&&o.push(t.desc),o.push(`states (${t.states.length})`);for(let s of t.states)o.push(` ${s.id} ${s.name} ${Hr(s.desc,160)}`);let i=[],r=new Map;for(let s of e.episodes)for(let c of s.scenes){let a=[c.location,...c.actors,...c.props].find(d=>d&&d.id===t.id);if(a){i.push(c);for(let d of a.states)r.set(d,(r.get(d)??0)+1)}}if(i.length){let s=[...new Set(i.map(a=>a.ep.no))];o.push(`appears: ${i.length} scenes across ${s.length} ep first ${i[0].ep.no}-${i[0].no} last ${i.at(-1).ep.no}-${i.at(-1).no}`),o.push(`state usage: ${[...r].map(([a,d])=>`${si(e,t.id,a)}\xD7${d}`).join(", ")}`);let c=t.states.filter(a=>!r.has(a.id));c.length&&o.push(`unused states: ${c.map(a=>`${a.id}(${a.name})`).join(", ")}`)}else o.push("appears: never referenced");return o.join(`
180
- `)}function w5(e,t,n){let o=[];for(let r of e.episodes)for(let s of r.scenes)[s.location,...s.actors,...s.props].find(a=>a&&a.id===t.id)?.states.includes(n.id)&&o.push(s);let i=bn(e).filter(r=>r.speaker?.id===t.id&&r.speaker.state===n.id);return[`${t.id}/${n.id} ${n.name} (${t.kind} ${t.name})`,n.desc,o.length?`bound in ${o.length} scene(s): ${o.slice(0,12).map(r=>`${r.ep.no}-${r.no}`).join(", ")}`+(o.length>12?" \u2026":""):"bound in no scene",i.length?`named by ${i.length} speaker reference(s)`:""].filter(Boolean).join(`
181
- `)}function Hr(e,t){return e.length>t?e.slice(0,t)+"\u2026":e}function rp(e,t){let n=bn(e);if(Q("find",`pool = all actions (${n.length})`),t.in){let o=Te(e,t.in);if(o.t==="ep")n=o.ep.scenes.flatMap(i=>i.actions);else if(o.t==="scene")n=o.scene.actions;else if(o.t==="action")n=[o.action];else throw new Error(`--in must address an episode, scene or action (got ${o.t})`);Q("find",`--in ${t.in} narrows pool to ${n.length}`)}if(t.type&&(n=n.filter(o=>o.type===t.type),Q("find",`--type ${t.type} -> ${n.length}`)),t.speaker){let o=Te(e,t.speaker);if(o.t!=="asset")throw new Error("--speaker must name an actor");n=n.filter(i=>i.speaker?.id===o.asset.id),Q("find",`--speaker ${t.speaker} -> ${o.asset.id} -> ${n.length}`)}return n}function tm(e,t,n={}){let o=rp(e,n),i=t?new RegExp(t,"u"):null,r=o.filter(f=>!i||i.test(f.content));Q("find",`regex /${t}/ -> ${r.length} hits`);let s=n.limit??40,c=n.window??16,a=r.slice(0,s),d=Math.max(0,...a.map(f=>f.anchor.length)),p=`${r.length} hit${r.length===1?"":"s"}`+(t?` for /${t}/`:"")+(r.length>a.length?` (showing ${a.length})`:""),l=a.map(f=>{let u=`${f.scene.ep.no}-${f.scene.no}-${f.no}`,g=u===f.anchor?"":u.padEnd(8)+" ",h=f.speaker?.id?ri(e,f.speaker.id)+"\uFF1A":"",m=n.full||!i?f.content:_5(f.content,i,c);return`${f.anchor.padEnd(d)} ${g}${h}${m}`});return[p,...l].join(`
182
- `)}function _5(e,t,n){let o=e.match(t);if(!o||o.index===void 0)return Hr(e,n*2);let i=Math.max(0,o.index-n),r=Math.min(e.length,o.index+o[0].length+n);return(i>0?"\u2026":"")+e.slice(i,r)+(r<e.length?"\u2026":"")}function sp(e,t){return Xd(Wd(e),tp(e,rp(e,{in:t})))}function nm(e,t){let n=sp(e,t);return ep.map(o=>`${o}=${n[o]}`).join(" ")}var E5=["content","paren","speaker","ts","type","transition"],x5=["name","desc","importance","aliases","role"],S5=["name","desc"],I5=["title","synopsis"],A5=["space","time"],k5=["title","worldview","style","synopsis","logline","theme","main"];function Fr(e,t,n,o){let i=Object.keys(n).filter(s=>n[s]!==void 0);if(!i.length)throw new Error(`Nothing to change on ${e}; pass at least one field`);let r=i.filter(s=>!o.includes(s));if(r.length){let s=/^[aeiou]/.test(t)?"an":"a";throw new Error(`${e} is ${s} ${t}; it has no ${r.join(", ")} \u2014 ${s} ${t} takes ${o.join(", ")}`)}return i}function om(e,t,n){let o=Te(e,t);if(o.t==="asset")return O5(e,t,o.asset,n);if(o.t==="state")return v5(e,t,o.asset,o.state,n);if(o.t==="script")return Wf(e,t||"script","script",o.doc.raw,n,k5);if(o.t==="ep")return Wf(e,t,"episode",o.ep.raw,n,I5);if(o.t==="scene")return b5(e,t,o.scene,n);let i=o.action,r=i.raw,s=Fr(i.anchor,"action",n,E5),c=pt(e);if(Q("edit",`${i.anchor}: ${s.join(", ")}`),n.type!==void 0&&(r.type=ai("type",n.type,qt,Tn)),n.content!==void 0&&(r.content=n.content),n.paren!==void 0&&aa(e,r,n.paren),n.speaker===null?delete r.speaker:n.speaker!==void 0&&(r.speaker=ap(e,n.speaker)),n.ts!==void 0&&sm(r,n.ts),n.transition!==void 0)if(n.transition===null)delete r.transition_prompt;else{let[a,d,p]=n.transition.split("|").map(f=>f.trim());if(!a||!d||!p)throw new Error(`transition takes "target|process|contrast" (got "${n.transition}")`);let l=Te(e,a);if(l.t!=="asset")throw new Error(`transition target must be an asset (got ${a})`);r.transition_prompt={target:l.asset.id,process:d,contrast:p}}return be(e),`${i.anchor} ${s.join("+")} ${da(r)}`+Ge(e,c)}function Wf(e,t,n,o,i,r){let s=Fr(t,n,i,r),c=pt(e);for(let a of s)if(a==="main")o.main_characters=i.main.split(",").map(d=>{let[p,l]=d.split("=").map(f=>f.trim());if(!p||!l)throw new Error(`main takes "\u540D\u5B57=\u89D2\u8272\u5B9A\u4F4D,\u2026" (got "${d}")`);return{name:p,role:l}});else{if(a==="aliases"||a==="role")throw new Error(`${t} is ${n}; it has no ${a}`);o[a]=i[a]}return Q("edit",`${n} ${t}: ${s.join(", ")}`),be(e),`${t} ${s.join("+")}`+Ge(e,c)}function b5(e,t,n,o){let i=Fr(t,"scene",o,A5),r=pt(e),s={...n.raw.environment??{}};return o.space!==void 0&&(s.space=ai("space",o.space,su,kc)),o.time!==void 0&&(s.time=ai("time",o.time,Ac,Ls)),n.raw.environment=s,Q("edit",`scene ${n.anchor}: ${i.join(", ")}`),be(e),`${n.anchor} ${i.join("+")} ${[s.space,s.time].filter(Boolean).join("/")}`+Ge(e,r)}function O5(e,t,n,o){let i=Fr(t,"asset",o,x5),r=pt(e);if(o.name!==void 0){let s=e.assets.find(c=>c!==n&&(c.name===o.name||c.aliases.includes(o.name)));if(s)throw new Error(`"${o.name}" already names ${s.kind} ${s.id}`);n.raw[`${n.kind}_name`]=o.name}if(o.desc!==void 0&&(n.raw.description=o.desc),o.importance!==void 0&&(n.raw.importance=um(o.importance)),o.role!==void 0){if(n.kind!=="actor")throw new Error(`role only applies to actors (${n.name} is a ${n.kind})`);o.role?n.raw.role_type=ai("role",o.role,po,Li):delete n.raw.role_type}return o.aliases!==void 0&&(o.aliases.length?n.raw.aliases=o.aliases:delete n.raw.aliases),Q("edit",`asset ${n.id}: ${i.join(", ")}`),be(e),`${n.id} ${i.join("+")} ${o.name??n.name}`+Ge(e,r)}function v5(e,t,n,o,i){let r=Fr(t,"state",i,S5),s=pt(e),c=n.raw.states.find(a=>a.state_id===o.id);if(i.name!==void 0){if(n.states.some(a=>a.id!==o.id&&a.name===i.name))throw new Error(`${n.name} already has a state named "${i.name}"`);c.state_name=i.name}return i.desc!==void 0&&(c.description=i.desc),Q("edit",`state ${n.id}/${o.id}: ${r.join(", ")}`),be(e),`${n.id}/${o.id} ${r.join("+")} ${i.name??o.name}`+Ge(e,s)}function im(e,t,n,o,i,r,s,c){let a=Te(e,t);if(a.t!=="action")throw new Error(`${t} is a ${a.t}; insert needs a sibling action`);let d=a.action,p=pt(e),l={type:ai("type",o,qt,Tn),content:i};if(e.version===4&&(l.action_id=vo("ac",new Set(e.actions.keys()))),o==="dialogue"||o==="inner_thought"){if(!r)throw new Error(`a ${o} needs a speaker`);l.speaker=ap(e,r),s!==void 0&&aa(e,l,s)}else if(r||s)throw new Error(`a ${o} takes neither speaker nor paren`);c!==void 0&&(l.extend=c);let f=d.scene.raw.actions,u=f.indexOf(d.raw)+(n==="before"?0:1);return f.splice(u,0,l),Q("insert",`${l.action_id??`${d.scene.anchor}#${u}`} ${n} ${d.anchor}`),be(e),`${l.action_id??`${d.scene.anchor}#${u}`} ${n} ${d.anchor} ${da(l)}`+Ge(e,p)}function rm(e,t,n,o="after"){let i=Te(e,t);if(i.t!=="action")throw new Error(`${t} is a ${i.t}; move targets one action`);let r=Te(e,n);if(r.t!=="action")throw new Error(`${n} is a ${r.t}; move --to takes a sibling action`);if(i.action===r.action)throw new Error(`${t} cannot move relative to itself`);let s=pt(e),c=i.action.scene.raw.actions;c.splice(c.indexOf(i.action.raw),1);let a=r.action.scene.raw.actions;return a.splice(a.indexOf(r.action.raw)+(o==="before"?0:1),0,i.action.raw),Q("move",`${i.action.scene.anchor} -> ${r.action.scene.anchor}, identity ${i.action.anchor} preserved`),be(e),`${i.action.anchor} ${o} ${r.action.anchor} (${i.action.scene.anchor} -> ${r.action.scene.anchor})`+Ge(e,s)}function aa(e,t,n){let o=e.version===4?"parenthetical":"emotion";n===null?delete t[o]:t[o]=n}function sm(e,t){if(t===null){e.extend&&delete e.extend.timestamp;return}let n;try{n=lo(t).canonical}catch(o){throw o instanceof et?new Error(`${o.message} (got ${JSON.stringify(t)})`):o}e.extend={...e.extend??{},timestamp:n}}function ap(e,t){let n=e.assets.find(a=>a.name===t||a.aliases.includes(t)),[o,i]=n?[t,void 0]:R5(t,"\xB7"),r=u5[o];if(r)return i?{kind:r,label:i}:{kind:r};let s=Te(e,o);if(s.t!=="asset"||s.asset.kind!=="actor")throw new Error(`Not an actor: ${t}`);let c={actor_id:s.asset.id};if(i){let a=s.asset.states.find(d=>d.name===i||d.id===i);if(!a)throw new Error(`Unknown state "${i}" on ${s.asset.name}`);c.state_id=a.id}return c}function R5(e,t){let n=e.indexOf(t);return n<0?[e,void 0]:[e.slice(0,n),e.slice(n+t.length)]}function da(e){return Hr(String(e.content??""),40)}function am(e,t,n,o={}){let i=Oo(structuredClone(e.raw)),r=M5(i,t,n,o);return e.raw=i.raw,be(e),r}function M5(e,t,n,o){if(t==="+"||Number(t)===e.episodes.length+1){let r={scenes:[]};return e.version===4&&(r.episode_id=vo("ep",new Set(e.eps.keys()))),e.raw.episodes.push(r),Q("write",`appending episode ${e.episodes.length+1}`),Xf(e,r,e.episodes.length+1,n,o,!0)}let i=Te(e,t);if(i.t==="scene")return N5(e,i.scene,n,o);if(i.t==="ep")return Xf(e,i.ep.raw,i.ep.no,n,o,!1);throw new Error(`write targets a scene or an episode (got ${i.t})`)}function N5(e,t,n,o){let i=pt(e),r=dm(e,t.raw,t,n,new Set(e.actions.keys()),o);return be(e),cm(t.anchor,r)+Ge(e,i)}function cm(e,t){return`${e}: ${t.total} actions (${t.kept} kept, ${t.created} new, ${t.dropped.length} deleted)`+(t.dropped.length?`
183
- deleted: ${t.dropped.map(n=>`${n.anchor} ${da(n.raw)}`).join(`
184
- `)}`:"")}function dm(e,t,n,o,i,r,s,c){let a=f5(e),{head:d,meta:p,body:l}=Yf(o.split(`
185
- `));if(d){let y=qd(d,p);t.environment=y.env.space||y.env.time?y.env:void 0,t.environment===void 0&&delete t.environment,t.location=y.location?ip(e,y.location,"location"):null,t.actors=y.cast.map(_=>ip(e,_,"actor")),t.props=y.props.map(_=>ip(e,_,"prop"))}let f=s??new Map((n?.actions??[]).map(y=>[y.anchor,y])),u=c??new Set,g=new Set,h=[],m=0,w=n?n.anchor:"this new scene";for(let y of l){let _=Qf(y,a);if(!_)continue;let x=_.anchor?f.get(_.anchor):void 0;if(_.anchor&&!x)throw new Error(`Anchor ${_.anchor} is not in ${w} \u2014 move it with \`move\`, or drop the anchor to create a new action`);if(x&&u.has(x.anchor))throw new Error(`Anchor ${_.anchor} appears twice in ${w} \u2014 drop the anchor from the copy to make it a new action`);let E=x?x.raw:{};!x&&e.version===4&&(E.action_id=vo("ac",i)),E.type=ai("type",_.type,qt,Tn),E.content=_.content,_.type==="dialogue"||_.type==="inner_thought"?(E.speaker=ap(e,_.speakerName),aa(e,E,_.paren??null)):(delete E.speaker,aa(e,E,null)),sm(E,_.ts??null),x?(g.add(x.anchor),u.add(x.anchor)):m++,h.push(E)}if(!h.length&&(n?.actions.length??0)>0&&!r.allowDelete)throw new Error(`That would leave ${w} with no actions${n?` (deleting all ${n.actions.length})`:""} \u2014 the body after the \`##\` header is empty; pass --allow-delete if that is the intent`);if(h.length&&!g.size&&(n?.actions.length??0)>0&&!r.allowDelete)throw new Error(`None of the ${h.length} line(s) carry an anchor from ${w}, so all ${n.actions.length} existing action(s) would be replaced by new ids \u2014 \`read --plain\` output cannot be written back; re-read without --plain, or pass --allow-delete to rewrite the scene from scratch`);return t.actions=h,{total:h.length,kept:g.size,created:m,dropped:s?[]:(n?.actions??[]).filter(y=>!g.has(y.anchor))}}function Xf(e,t,n,o,i,r){let s=pt(e),c=r?[]:e.episodes[n-1].scenes,a=new Map;for(let x of c)a.set(x.anchor,x),a.set(x.id,x);let d=[];for(let x of o.split(`
186
- `))x.startsWith("##")?d.push(x):d.length&&(d[d.length-1]+=`
187
- `+x);if(!d.length)throw new Error("No scene headers found \u2014 an episode body needs `## \u2026` lines");let p=new Set(e.actions.keys()),l=new Set(e.scenes.keys()),f=new Map;for(let x of c)for(let E of x.actions)f.set(E.anchor,E);let u=new Set,g=new Set,h=[],m=[],w=0;for(let x of d){let E=qd(x.split(`
188
- `)[0]),A=E.anchor?a.get(E.anchor):void 0;if(E.anchor&&!A)throw new Error(`Scene ${E.anchor} is not in episode ${n} \u2014 drop the id from the header to create a new scene here`);let b=A?A.raw:{};A?g.add(A.anchor):(e.version===4?b.scene_id=vo("scn",l):b.scene_id=`scn_${String(c.length+w+1).padStart(3,"0")}`,w++);let C=dm(e,b,A??null,x,p,i,f,u);h.push(b),m.push(cm(A?A.anchor:`new ${b.scene_id}`,C))}let y=[...f.values()].filter(x=>!u.has(x.anchor));if(y.length&&!i.allowDelete)throw new Error(`This would delete ${y.length} action(s) from episode ${n}: `+y.slice(0,6).map(x=>`${x.anchor}(${x.scene.anchor})`).join(", ")+(y.length>6?" \u2026":"")+" \u2014 keep their lines, or pass --allow-delete if that is the intent");let _=c.filter(x=>!g.has(x.anchor));if(_.length&&!i.allowDelete)throw new Error(`This would delete ${_.length} whole scene(s) from episode ${n}: `+_.map(x=>`${x.anchor}(${x.actions.length} actions)`).join(", ")+" \u2014 include their `##` headers to keep them, or pass --allow-delete if that is the intent");return Q("write",`episode ${n}: ${d.length} scene blocks, ${w} new, ${_.length} deleted`),t.scenes=h,be(e),`EP${n}: ${h.length} scenes (${h.length-w} kept, ${w} new, ${_.length} deleted, ${y.length} actions deleted)
189
- `+m.map(x=>" "+x.replace(/\n/g,`
179
+ `)}function w5(e,t){let n=t.raw.role_type?` <${t.raw.role_type}>`:"",o=[`${t.id} ${t.name} ${t.kind}${t.importance?` [${t.importance}]`:""}${n}`];t.aliases.length&&o.push(`aliases: ${t.aliases.join(", ")}`),t.desc&&o.push(t.desc),o.push(`states (${t.states.length})`);for(let s of t.states)o.push(` ${s.id} ${s.name} ${Qr(s.desc,160)}`);let i=[],r=new Map;for(let s of e.episodes)for(let c of s.scenes){let a=[c.location,...c.actors,...c.props].find(d=>d&&d.id===t.id);if(a){i.push(c);for(let d of a.states)r.set(d,(r.get(d)??0)+1)}}if(i.length){let s=[...new Set(i.map(a=>a.ep.no))];o.push(`appears: ${i.length} scenes across ${s.length} ep first ${i[0].ep.no}-${i[0].no} last ${i.at(-1).ep.no}-${i.at(-1).no}`),o.push(`state usage: ${[...r].map(([a,d])=>`${si(e,t.id,a)}\xD7${d}`).join(", ")}`);let c=t.states.filter(a=>!r.has(a.id));c.length&&o.push(`unused states: ${c.map(a=>`${a.id}(${a.name})`).join(", ")}`)}else o.push("appears: never referenced");return o.join(`
180
+ `)}function _5(e,t,n){let o=[];for(let r of e.episodes)for(let s of r.scenes)[s.location,...s.actors,...s.props].find(a=>a&&a.id===t.id)?.states.includes(n.id)&&o.push(s);let i=bn(e).filter(r=>r.speaker?.id===t.id&&r.speaker.state===n.id);return[`${t.id}/${n.id} ${n.name} (${t.kind} ${t.name})`,n.desc,o.length?`bound in ${o.length} scene(s): ${o.slice(0,12).map(r=>`${r.ep.no}-${r.no}`).join(", ")}`+(o.length>12?" \u2026":""):"bound in no scene",i.length?`named by ${i.length} speaker reference(s)`:""].filter(Boolean).join(`
181
+ `)}function Qr(e,t){return e.length>t?e.slice(0,t)+"\u2026":e}function ap(e,t){let n=bn(e);if(F("find",`pool = all actions (${n.length})`),t.in){let o=Te(e,t.in);if(o.t==="ep")n=o.ep.scenes.flatMap(i=>i.actions);else if(o.t==="scene")n=o.scene.actions;else if(o.t==="action")n=[o.action];else throw new Error(`--in must address an episode, scene or action (got ${o.t})`);F("find",`--in ${t.in} narrows pool to ${n.length}`)}if(t.type&&(n=n.filter(o=>o.type===t.type),F("find",`--type ${t.type} -> ${n.length}`)),t.speaker){let o=Te(e,t.speaker);if(o.t!=="asset")throw new Error("--speaker must name an actor");n=n.filter(i=>i.speaker?.id===o.asset.id),F("find",`--speaker ${t.speaker} -> ${o.asset.id} -> ${n.length}`)}return n}function im(e,t,n={}){let o=ap(e,n),i=t?new RegExp(t,"u"):null,r=o.filter(f=>!i||i.test(f.content));F("find",`regex /${t}/ -> ${r.length} hits`);let s=n.limit??40,c=n.window??16,a=r.slice(0,s),d=Math.max(0,...a.map(f=>f.anchor.length)),p=`${r.length} hit${r.length===1?"":"s"}`+(t?` for /${t}/`:"")+(r.length>a.length?` (showing ${a.length})`:""),l=a.map(f=>{let u=`${f.scene.ep.no}-${f.scene.no}-${f.no}`,m=u===f.anchor?"":u.padEnd(8)+" ",h=f.speaker?.id?ri(e,f.speaker.id)+"\uFF1A":"",g=n.full||!i?f.content:E5(f.content,i,c);return`${f.anchor.padEnd(d)} ${m}${h}${g}`});return[p,...l].join(`
182
+ `)}function E5(e,t,n){let o=e.match(t);if(!o||o.index===void 0)return Qr(e,n*2);let i=Math.max(0,o.index-n),r=Math.min(e.length,o.index+o[0].length+n);return(i>0?"\u2026":"")+e.slice(i,r)+(r<e.length?"\u2026":"")}function cp(e,t){return tp(ep(e),op(e,ap(e,{in:t})))}function rm(e,t){let n=cp(e,t);return np.map(o=>`${o}=${n[o]}`).join(" ")}var x5=["content","paren","speaker","ts","type","transition"],S5=["name","desc","importance","aliases","role"],I5=["name","desc"],A5=["title","synopsis"],k5=["space","time"],b5=["title","worldview","style","synopsis","logline","theme","main"];function Yr(e,t,n,o){let i=Object.keys(n).filter(s=>n[s]!==void 0);if(!i.length)throw new Error(`Nothing to change on ${e}; pass at least one field`);let r=i.filter(s=>!o.includes(s));if(r.length){let s=/^[aeiou]/.test(t)?"an":"a";throw new Error(`${e} is ${s} ${t}; it has no ${r.join(", ")} \u2014 ${s} ${t} takes ${o.join(", ")}`)}return i}function sm(e,t,n){let o=Te(e,t);if(o.t==="asset")return v5(e,t,o.asset,n);if(o.t==="state")return R5(e,t,o.asset,o.state,n);if(o.t==="script")return tm(e,t||"script","script",o.doc.raw,n,b5);if(o.t==="ep")return tm(e,t,"episode",o.ep.raw,n,A5);if(o.t==="scene")return O5(e,t,o.scene,n);let i=o.action,r=i.raw,s=Yr(i.anchor,"action",n,x5),c=pt(e);if(F("edit",`${i.anchor}: ${s.join(", ")}`),n.type!==void 0&&(r.type=ai("type",n.type,qt,Tn)),n.content!==void 0&&(r.content=n.content),n.paren!==void 0&&da(e,r,n.paren),n.speaker===null?delete r.speaker:n.speaker!==void 0&&(r.speaker=dp(e,n.speaker)),n.ts!==void 0&&dm(r,n.ts),n.transition!==void 0)if(n.transition===null)delete r.transition_prompt;else{let[a,d,p]=n.transition.split("|").map(f=>f.trim());if(!a||!d||!p)throw new Error(`transition takes "target|process|contrast" (got "${n.transition}")`);let l=Te(e,a);if(l.t!=="asset")throw new Error(`transition target must be an asset (got ${a})`);r.transition_prompt={target:l.asset.id,process:d,contrast:p}}return be(e),`${i.anchor} ${s.join("+")} ${la(r)}`+Be(e,c)}function tm(e,t,n,o,i,r){let s=Yr(t,n,i,r),c=pt(e);for(let a of s)if(a==="main")o.main_characters=i.main.split(",").map(d=>{let[p,l]=d.split("=").map(f=>f.trim());if(!p||!l)throw new Error(`main takes "\u540D\u5B57=\u89D2\u8272\u5B9A\u4F4D,\u2026" (got "${d}")`);return{name:p,role:l}});else{if(a==="aliases"||a==="role")throw new Error(`${t} is ${n}; it has no ${a}`);o[a]=i[a]}return F("edit",`${n} ${t}: ${s.join(", ")}`),be(e),`${t} ${s.join("+")}`+Be(e,c)}function O5(e,t,n,o){let i=Yr(t,"scene",o,k5),r=pt(e),s={...n.raw.environment??{}};return o.space!==void 0&&(s.space=ai("space",o.space,cu,Oc)),o.time!==void 0&&(s.time=ai("time",o.time,bc,Us)),n.raw.environment=s,F("edit",`scene ${n.anchor}: ${i.join(", ")}`),be(e),`${n.anchor} ${i.join("+")} ${[s.space,s.time].filter(Boolean).join("/")}`+Be(e,r)}function v5(e,t,n,o){let i=Yr(t,"asset",o,S5),r=pt(e);if(o.name!==void 0){let s=e.assets.find(c=>c!==n&&(c.name===o.name||c.aliases.includes(o.name)));if(s)throw new Error(`"${o.name}" already names ${s.kind} ${s.id}`);n.raw[`${n.kind}_name`]=o.name}if(o.desc!==void 0&&(n.raw.description=o.desc),o.importance!==void 0&&(n.raw.importance=gm(o.importance)),o.role!==void 0){if(n.kind!=="actor")throw new Error(`role only applies to actors (${n.name} is a ${n.kind})`);o.role?n.raw.role_type=ai("role",o.role,lo,Ui):delete n.raw.role_type}return o.aliases!==void 0&&(o.aliases.length?n.raw.aliases=o.aliases:delete n.raw.aliases),F("edit",`asset ${n.id}: ${i.join(", ")}`),be(e),`${n.id} ${i.join("+")} ${o.name??n.name}`+Be(e,r)}function R5(e,t,n,o,i){let r=Yr(t,"state",i,I5),s=pt(e),c=n.raw.states.find(a=>a.state_id===o.id);if(i.name!==void 0){if(n.states.some(a=>a.id!==o.id&&a.name===i.name))throw new Error(`${n.name} already has a state named "${i.name}"`);c.state_name=i.name}return i.desc!==void 0&&(c.description=i.desc),F("edit",`state ${n.id}/${o.id}: ${r.join(", ")}`),be(e),`${n.id}/${o.id} ${r.join("+")} ${i.name??o.name}`+Be(e,s)}function am(e,t,n,o,i,r,s,c){let a=Te(e,t);if(a.t!=="action")throw new Error(`${t} is a ${a.t}; insert needs a sibling action`);let d=a.action,p=pt(e),l={type:ai("type",o,qt,Tn),content:i};if(e.version===4&&(l.action_id=Ro("ac",new Set(e.actions.keys()))),o==="dialogue"||o==="inner_thought"){if(!r)throw new Error(`a ${o} needs a speaker`);l.speaker=dp(e,r),s!==void 0&&da(e,l,s)}else if(r||s)throw new Error(`a ${o} takes neither speaker nor paren`);c!==void 0&&(l.extend=c);let f=d.scene.raw.actions,u=f.indexOf(d.raw)+(n==="before"?0:1);return f.splice(u,0,l),F("insert",`${l.action_id??`${d.scene.anchor}#${u}`} ${n} ${d.anchor}`),be(e),`${l.action_id??`${d.scene.anchor}#${u}`} ${n} ${d.anchor} ${la(l)}`+Be(e,p)}function cm(e,t,n,o="after"){let i=Te(e,t);if(i.t!=="action")throw new Error(`${t} is a ${i.t}; move targets one action`);let r=Te(e,n);if(r.t!=="action")throw new Error(`${n} is a ${r.t}; move --to takes a sibling action`);if(i.action===r.action)throw new Error(`${t} cannot move relative to itself`);let s=pt(e),c=i.action.scene.raw.actions;c.splice(c.indexOf(i.action.raw),1);let a=r.action.scene.raw.actions;return a.splice(a.indexOf(r.action.raw)+(o==="before"?0:1),0,i.action.raw),F("move",`${i.action.scene.anchor} -> ${r.action.scene.anchor}, identity ${i.action.anchor} preserved`),be(e),`${i.action.anchor} ${o} ${r.action.anchor} (${i.action.scene.anchor} -> ${r.action.scene.anchor})`+Be(e,s)}function da(e,t,n){let o=e.version===4?"parenthetical":"emotion";n===null?delete t[o]:t[o]=n}function dm(e,t){if(t===null){e.extend&&delete e.extend.timestamp;return}let n;try{n=uo(t).canonical}catch(o){throw o instanceof et?new Error(`${o.message} (got ${JSON.stringify(t)})`):o}e.extend={...e.extend??{},timestamp:n}}function dp(e,t){let n=e.assets.find(a=>a.name===t||a.aliases.includes(t)),[o,i]=n?[t,void 0]:M5(t,"\xB7"),r=f5[o];if(r)return i?{kind:r,label:i}:{kind:r};let s=Te(e,o);if(s.t!=="asset"||s.asset.kind!=="actor")throw new Error(`Not an actor: ${t}`);let c={actor_id:s.asset.id};if(i){let a=s.asset.states.find(d=>d.name===i||d.id===i);if(!a)throw new Error(`Unknown state "${i}" on ${s.asset.name}`);c.state_id=a.id}return c}function M5(e,t){let n=e.indexOf(t);return n<0?[e,void 0]:[e.slice(0,n),e.slice(n+t.length)]}function la(e){return Qr(String(e.content??""),40)}function pm(e,t,n,o={}){let i=vo(structuredClone(e.raw)),r=N5(i,t,n,o);return e.raw=i.raw,be(e),r}function N5(e,t,n,o){if(t==="+"||Number(t)===e.episodes.length+1){let r={scenes:[]};return e.version===4&&(r.episode_id=Ro("ep",new Set(e.eps.keys()))),e.raw.episodes.push(r),F("write",`appending episode ${e.episodes.length+1}`),nm(e,r,e.episodes.length+1,n,o,!0)}let i=Te(e,t);if(i.t==="scene")return L5(e,i.scene,n,o);if(i.t==="ep")return nm(e,i.ep.raw,i.ep.no,n,o,!1);throw new Error(`write targets a scene or an episode (got ${i.t})`)}function L5(e,t,n,o){let i=pt(e),r=um(e,t.raw,t,n,new Set(e.actions.keys()),o);return be(e),lm(t.anchor,r)+Be(e,i)}function lm(e,t){return`${e}: ${t.total} actions (${t.kept} kept, ${t.created} new, ${t.dropped.length} deleted)`+(t.dropped.length?`
183
+ deleted: ${t.dropped.map(n=>`${n.anchor} ${la(n.raw)}`).join(`
184
+ `)}`:"")}function um(e,t,n,o,i,r,s,c){let a=m5(e),{head:d,meta:p,body:l}=Wf(o.split(`
185
+ `));if(d){let y=Wd(d,p);t.environment=y.env.space||y.env.time?y.env:void 0,t.environment===void 0&&delete t.environment,t.location=y.location?sp(e,y.location,"location"):null,t.actors=y.cast.map(_=>sp(e,_,"actor")),t.props=y.props.map(_=>sp(e,_,"prop"))}let f=s??new Map((n?.actions??[]).map(y=>[y.anchor,y])),u=c??new Set,m=new Set,h=[],g=0,w=n?n.anchor:"this new scene";for(let y of l){let _=Zf(y,a);if(!_)continue;let S=_.anchor?f.get(_.anchor):void 0;if(_.anchor&&!S)throw new Error(`Anchor ${_.anchor} is not in ${w} \u2014 move it with \`move\`, or drop the anchor to create a new action`);if(S&&u.has(S.anchor))throw new Error(`Anchor ${_.anchor} appears twice in ${w} \u2014 drop the anchor from the copy to make it a new action`);let E=S?S.raw:{};!S&&e.version===4&&(E.action_id=Ro("ac",i)),E.type=ai("type",_.type,qt,Tn),E.content=_.content,_.type==="dialogue"||_.type==="inner_thought"?(E.speaker=dp(e,_.speakerName),da(e,E,_.paren??null)):(delete E.speaker,da(e,E,null)),dm(E,_.ts??null),S?(m.add(S.anchor),u.add(S.anchor)):g++,h.push(E)}if(!h.length&&(n?.actions.length??0)>0&&!r.allowDelete)throw new Error(`That would leave ${w} with no actions${n?` (deleting all ${n.actions.length})`:""} \u2014 the body after the \`##\` header is empty; pass --allow-delete if that is the intent`);if(h.length&&!m.size&&(n?.actions.length??0)>0&&!r.allowDelete)throw new Error(`None of the ${h.length} line(s) carry an anchor from ${w}, so all ${n.actions.length} existing action(s) would be replaced by new ids \u2014 \`read --plain\` output cannot be written back; re-read without --plain, or pass --allow-delete to rewrite the scene from scratch`);return t.actions=h,{total:h.length,kept:m.size,created:g,dropped:s?[]:(n?.actions??[]).filter(y=>!m.has(y.anchor))}}function nm(e,t,n,o,i,r){let s=pt(e),c=r?[]:e.episodes[n-1].scenes,a=new Map;for(let S of c)a.set(S.anchor,S),a.set(S.id,S);let d=[];for(let S of o.split(`
186
+ `))S.startsWith("##")?d.push(S):d.length&&(d[d.length-1]+=`
187
+ `+S);if(!d.length)throw new Error("No scene headers found \u2014 an episode body needs `## \u2026` lines");let p=new Set(e.actions.keys()),l=new Set(e.scenes.keys()),f=new Map;for(let S of c)for(let E of S.actions)f.set(E.anchor,E);let u=new Set,m=new Set,h=[],g=[],w=0;for(let S of d){let E=Wd(S.split(`
188
+ `)[0]),A=E.anchor?a.get(E.anchor):void 0;if(E.anchor&&!A)throw new Error(`Scene ${E.anchor} is not in episode ${n} \u2014 drop the id from the header to create a new scene here`);let b=A?A.raw:{};A?m.add(A.anchor):(e.version===4?b.scene_id=Ro("scn",l):b.scene_id=`scn_${String(c.length+w+1).padStart(3,"0")}`,w++);let U=um(e,b,A??null,S,p,i,f,u);h.push(b),g.push(lm(A?A.anchor:`new ${b.scene_id}`,U))}let y=[...f.values()].filter(S=>!u.has(S.anchor));if(y.length&&!i.allowDelete)throw new Error(`This would delete ${y.length} action(s) from episode ${n}: `+y.slice(0,6).map(S=>`${S.anchor}(${S.scene.anchor})`).join(", ")+(y.length>6?" \u2026":"")+" \u2014 keep their lines, or pass --allow-delete if that is the intent");let _=c.filter(S=>!m.has(S.anchor));if(_.length&&!i.allowDelete)throw new Error(`This would delete ${_.length} whole scene(s) from episode ${n}: `+_.map(S=>`${S.anchor}(${S.actions.length} actions)`).join(", ")+" \u2014 include their `##` headers to keep them, or pass --allow-delete if that is the intent");return F("write",`episode ${n}: ${d.length} scene blocks, ${w} new, ${_.length} deleted`),t.scenes=h,be(e),`EP${n}: ${h.length} scenes (${h.length-w} kept, ${w} new, ${_.length} deleted, ${y.length} actions deleted)
189
+ `+g.map(S=>" "+S.replace(/\n/g,`
190
190
  `)).join(`
191
191
  `)+(_.length?`
192
- deleted scenes: ${_.map(x=>x.anchor).join(", ")}`:"")+Ge(e,s)}function ip(e,t,n){let{name:o,states:i}=qf(t),r=Te(e,o);if(r.t!=="asset"||r.asset.kind!==n)throw new Error(`"${o}" is not a registered ${n} \u2014 create it with \`asset\` first`);let s=(i.length?i:["default"]).map(d=>{let p=r.asset.states.filter(l=>l.name===d||l.id===d);if(!p.length)throw new Error(`${r.asset.name} has no state "${d}" (has: ${r.asset.states.map(l=>l.name).join(", ")})`);if(p.length>1)throw new Error(`${r.asset.name} has ${p.length} states named "${d}"; use the state id`);return p[0].id}),c=[...new Set(s)].sort(),a=`${n}_id`;return e.version===4?{[a]:r.asset.id,state_ids:c}:{[a]:r.asset.id,state_id:c[0]}}function pm(e,t,n,o,i=!1){let r=Te(e,t);if(r.t!=="scene")throw new Error(`${t} is a ${r.t}; ref targets one scene`);let s=r.scene,c=Te(e,n);if(c.t!=="asset")throw new Error(`${n} is a ${c.t}; ref takes an actor, location or prop`);let a=c.asset,d=a.kind==="actor"?"actors":a.kind==="prop"?"props":"location",p=pt(e);if(i){if(a.kind==="location"){if(s.location?.id!==a.id)throw new Error(`${s.anchor}'s location is ${s.location?ri(e,s.location.id):"empty"}, not ${a.name}`);s.raw.location=null}else{let h=s.raw[d],m=h.findIndex(w=>w[`${a.kind}_id`]===a.id);if(m<0)throw new Error(`${s.anchor} does not reference ${a.name}`);h.splice(m,1)}return Q("ref",`${s.anchor} -= ${a.id}`),be(e),`${s.anchor} removed ${a.name}`+Ge(e,p)}if(!o.length)throw new Error(`ref needs at least one state for ${a.name} (has: ${a.states.map(h=>h.name).join(", ")}) \u2014 nothing is implied, not even default`);let l=[...new Set(o.map(h=>{let m=a.states.filter(w=>w.name===h||w.id===h);if(!m.length)throw new Error(`${a.name} has no state "${h}" (has: ${a.states.map(w=>w.name).join(", ")})`);if(m.length>1)throw new Error(`${a.name} has ${m.length} states named "${h}"; use the state id`);return m[0].id}))].sort(),f=`${a.kind}_id`,u=e.version===4?{[f]:a.id,state_ids:l}:{[f]:a.id,state_id:l[0]};if(e.version===3&&l.length>1)throw new Error("Script v3 holds one state per reference; pass a single state");let g;if(a.kind==="location")g=s.location?s.location.id===a.id?"restated":"replaced":"set",s.raw.location=u;else{let h=s.raw[d],m=h.findIndex(w=>w[f]===a.id);m<0?(h.push(u),g="added"):(h[m]=u,g="restated")}return Q("ref",`${s.anchor} ${g} ${a.id} = [${l.join(", ")}]`),be(e),`${s.anchor} ${g} ${a.name}(${l.map(h=>si(e,a.id,h)).join("+")})`+Ge(e,p)}function lm(e,t,n,o={}){if(!t)throw new Error("replace needs a pattern; an empty one would rewrite every action");let i=new RegExp(t,"gu"),r=pt(e),s=rp(e,o),c=s.filter(p=>(i.lastIndex=0,i.test(p.content)));if(Q("replace",`/${t}/ matched ${c.length} of ${s.length} actions in scope`),!c.length)return`0 hits for /${t}/ \u2014 nothing to do`;let a=Math.max(...c.map(p=>p.anchor.length)),d=c.map(p=>{let l=p.content.replace(i,n);return`${p.anchor.padEnd(a)} ${p.scene.ep.no}-${p.scene.no}-${p.no}
192
+ deleted scenes: ${_.map(S=>S.anchor).join(", ")}`:"")+Be(e,s)}function sp(e,t,n){let{name:o,states:i}=Xf(t),r=Te(e,o);if(r.t!=="asset"||r.asset.kind!==n)throw new Error(`"${o}" is not a registered ${n} \u2014 create it with \`asset\` first`);let s=(i.length?i:["default"]).map(d=>{let p=r.asset.states.filter(l=>l.name===d||l.id===d);if(!p.length)throw new Error(`${r.asset.name} has no state "${d}" (has: ${r.asset.states.map(l=>l.name).join(", ")})`);if(p.length>1)throw new Error(`${r.asset.name} has ${p.length} states named "${d}"; use the state id`);return p[0].id}),c=[...new Set(s)].sort(),a=`${n}_id`;return e.version===4?{[a]:r.asset.id,state_ids:c}:{[a]:r.asset.id,state_id:c[0]}}function fm(e,t,n,o,i=!1){let r=Te(e,t);if(r.t!=="scene")throw new Error(`${t} is a ${r.t}; ref targets one scene`);let s=r.scene,c=Te(e,n);if(c.t!=="asset")throw new Error(`${n} is a ${c.t}; ref takes an actor, location or prop`);let a=c.asset,d=a.kind==="actor"?"actors":a.kind==="prop"?"props":"location",p=pt(e);if(i){if(a.kind==="location"){if(s.location?.id!==a.id)throw new Error(`${s.anchor}'s location is ${s.location?ri(e,s.location.id):"empty"}, not ${a.name}`);s.raw.location=null}else{let h=s.raw[d],g=h.findIndex(w=>w[`${a.kind}_id`]===a.id);if(g<0)throw new Error(`${s.anchor} does not reference ${a.name}`);h.splice(g,1)}return F("ref",`${s.anchor} -= ${a.id}`),be(e),`${s.anchor} removed ${a.name}`+Be(e,p)}if(!o.length)throw new Error(`ref needs at least one state for ${a.name} (has: ${a.states.map(h=>h.name).join(", ")}) \u2014 nothing is implied, not even default`);let l=[...new Set(o.map(h=>{let g=a.states.filter(w=>w.name===h||w.id===h);if(!g.length)throw new Error(`${a.name} has no state "${h}" (has: ${a.states.map(w=>w.name).join(", ")})`);if(g.length>1)throw new Error(`${a.name} has ${g.length} states named "${h}"; use the state id`);return g[0].id}))].sort(),f=`${a.kind}_id`,u=e.version===4?{[f]:a.id,state_ids:l}:{[f]:a.id,state_id:l[0]};if(e.version===3&&l.length>1)throw new Error("Script v3 holds one state per reference; pass a single state");let m;if(a.kind==="location")m=s.location?s.location.id===a.id?"restated":"replaced":"set",s.raw.location=u;else{let h=s.raw[d],g=h.findIndex(w=>w[f]===a.id);g<0?(h.push(u),m="added"):(h[g]=u,m="restated")}return F("ref",`${s.anchor} ${m} ${a.id} = [${l.join(", ")}]`),be(e),`${s.anchor} ${m} ${a.name}(${l.map(h=>si(e,a.id,h)).join("+")})`+Be(e,p)}function mm(e,t,n,o={}){if(!t)throw new Error("replace needs a pattern; an empty one would rewrite every action");let i=new RegExp(t,"gu"),r=pt(e),s=ap(e,o),c=s.filter(p=>(i.lastIndex=0,i.test(p.content)));if(F("replace",`/${t}/ matched ${c.length} of ${s.length} actions in scope`),!c.length)return`0 hits for /${t}/ \u2014 nothing to do`;let a=Math.max(...c.map(p=>p.anchor.length)),d=c.map(p=>{let l=p.content.replace(i,n);return`${p.anchor.padEnd(a)} ${p.scene.ep.no}-${p.scene.no}-${p.no}
193
193
  ${" ".repeat(a)} - ${p.content}
194
194
  ${" ".repeat(a)} + ${l}`});if(!o.apply)return`${c.length} action(s) would change (dry run \u2014 pass apply to write)
195
195
  `+d.join(`
196
- `);for(let p of c)i.lastIndex=0,p.raw.content=p.content.replace(i,n);return be(e),Q("replace",`wrote ${c.length} actions`),`${c.length} action(s) changed`+Ge(e,r)+`
196
+ `);for(let p of c)i.lastIndex=0,p.raw.content=p.content.replace(i,n);return be(e),F("replace",`wrote ${c.length} actions`),`${c.length} action(s) changed`+Be(e,r)+`
197
197
  `+d.join(`
198
- `)}function ai(e,t,n,o){if(!n.has(t))throw new Error(`${e} must be one of ${o.join(" | ")} (got "${t}")`);return t}function um(e){return ai("importance",e,Pt,$n)}function qi(e){return e.version===4?Pe(e.raw):wt(e.raw)}function fm(e){let t=qi(e);return[`${e.episodes.length} episodes / ${e.scenes.size?[...new Set(e.episodes.flatMap(o=>o.scenes))].length:0} scenes / ${bn(e).length} actions \u2014 ${t.ok?"ok":`${t.errors.length} error(s)`}`+(t.warnings.length?`, ${t.warnings.length} warning(s)`:""),...dp([...t.errors.map(o=>["error",o]),...t.warnings.map(o=>["warning",o])])].join(`
199
- `)}function cp(e,t={}){let n=qi(e),o=[...n.errors.map(i=>["error",i]),...n.warnings.map(i=>["warning",i])];return t.severity&&(o=o.filter(([i])=>i===t.severity)),t.code&&(o=o.filter(([,i])=>i.code===t.code)),Q("issues",`${o.length} matching issue(s)`),o.length?dp(o).join(`
200
- `):"No issues."}function dp(e){return e.map(([t,n])=>`${t} ${n.code} ${n.path} ${n.message}`+(n.repair_hint?`
201
- fix: ${n.repair_hint}`:""))}function pt(e){return qi(e)}function Ge(e,t){let n=qi(e),o=[...vc(t.errors,n.errors).map(i=>["error",i]),...vc(t.warnings,n.warnings).map(i=>["warning",i])];return o.length?(Q("check",`${o.length} issue(s) introduced by this edit`),`
198
+ `)}function ai(e,t,n,o){if(!n.has(t))throw new Error(`${e} must be one of ${o.join(" | ")} (got "${t}")`);return t}function gm(e){return ai("importance",e,Pt,$n)}function Wi(e){return e.version===4?Pe(e.raw):wt(e.raw)}function hm(e){let t=Wi(e);return[`${e.episodes.length} episodes / ${e.scenes.size?[...new Set(e.episodes.flatMap(o=>o.scenes))].length:0} scenes / ${bn(e).length} actions \u2014 ${t.ok?"ok":`${t.errors.length} error(s)`}`+(t.warnings.length?`, ${t.warnings.length} warning(s)`:""),...lp([...t.errors.map(o=>["error",o]),...t.warnings.map(o=>["warning",o])])].join(`
199
+ `)}function pp(e,t={}){let n=Wi(e),o=[...n.errors.map(i=>["error",i]),...n.warnings.map(i=>["warning",i])];return t.severity&&(o=o.filter(([i])=>i===t.severity)),t.code&&(o=o.filter(([,i])=>i.code===t.code)),F("issues",`${o.length} matching issue(s)`),o.length?lp(o).join(`
200
+ `):"No issues."}function lp(e){return e.map(([t,n])=>`${t} ${n.code} ${n.path} ${n.message}`+(n.repair_hint?`
201
+ fix: ${n.repair_hint}`:""))}function pt(e){return Wi(e)}function Be(e,t){let n=Wi(e),o=[...Mc(t.errors,n.errors).map(i=>["error",i]),...Mc(t.warnings,n.warnings).map(i=>["warning",i])];return o.length?(F("check",`${o.length} issue(s) introduced by this edit`),`
202
202
  introduced ${o.length} issue(s):
203
- `+dp(o).join(`
204
- `)):""}var pp={actor:"actors",location:"locations",prop:"props"},em={actor:"act",location:"loc",prop:"prp"};function mm(e,t,n,o,i="featured",r=[]){if(!n.trim())throw new Error("asset needs a name");let s=pt(e),c=e.assets.find(l=>l.name===n||l.aliases.includes(n));if(c)throw new Error(`"${n}" already names ${c.kind} ${c.id}; read it instead`);let a=pp[t],d=e.version===4?vo(em[t],new Set(e.assets.map(l=>l.id))):`${em[t]}_${String(e.raw[a].length+1).padStart(3,"0")}`,p={[`${t}_id`]:d,[`${t}_name`]:n,importance:um(i),description:o,states:[{state_id:"default",state_name:n,description:o}]};return r.length&&(p.aliases=r),e.raw[a].push(p),Q("asset",`${t} ${d} "${n}" + default state`),be(e),`${d} ${n} ${t} states: default`+Ge(e,s)}function gm(e,t,n,o){let i=Te(e,t);if(i.t!=="asset")throw new Error(`${t} is a ${i.t}; state targets an asset`);let r=pt(e);if(i.asset.states.some(c=>c.name===n))throw new Error(`${i.asset.name} already has a state named "${n}"`);let s=e.version===4?vo("st",new Set(i.asset.states.map(c=>c.id))):`st_${String(i.asset.states.length).padStart(3,"0")}`;return i.asset.raw.states.push({state_id:s,state_name:n,description:o}),Q("state",`${i.asset.id} + ${s} "${n}"`),be(e),`${i.asset.id}/${s} ${n} (${i.asset.name} now has ${i.asset.states.length+1} states)`+Ge(e,r)}function L5(e,t){let n=Te(e,t);switch(n.t){case"script":return{raw:n.doc.raw,label:"script"};case"ep":return{raw:n.ep.raw,label:n.ep.id};case"scene":return{raw:n.scene.raw,label:n.scene.anchor};case"action":return{raw:n.action.raw,label:n.action.anchor};case"asset":return{raw:n.asset.raw,label:n.asset.id};case"state":return{raw:n.asset.raw.states.find(i=>i.state_id===n.state.id),label:`${n.asset.id}/${n.state.id}`}}}function hm(e,t,n,o,i=!1){let{raw:r,label:s}=L5(e,t),c=r.extend??{};if(!n){let a=Object.keys(c);return a.length?`${s} extend:
203
+ `+lp(o).join(`
204
+ `)):""}var up={actor:"actors",location:"locations",prop:"props"},om={actor:"act",location:"loc",prop:"prp"};function ym(e,t,n,o,i="featured",r=[]){if(!n.trim())throw new Error("asset needs a name");let s=pt(e),c=e.assets.find(l=>l.name===n||l.aliases.includes(n));if(c)throw new Error(`"${n}" already names ${c.kind} ${c.id}; read it instead`);let a=up[t],d=e.version===4?Ro(om[t],new Set(e.assets.map(l=>l.id))):`${om[t]}_${String(e.raw[a].length+1).padStart(3,"0")}`,p={[`${t}_id`]:d,[`${t}_name`]:n,importance:gm(i),description:o,states:[{state_id:"default",state_name:n,description:o}]};return r.length&&(p.aliases=r),e.raw[a].push(p),F("asset",`${t} ${d} "${n}" + default state`),be(e),`${d} ${n} ${t} states: default`+Be(e,s)}function wm(e,t,n,o){let i=Te(e,t);if(i.t!=="asset")throw new Error(`${t} is a ${i.t}; state targets an asset`);let r=pt(e);if(i.asset.states.some(c=>c.name===n))throw new Error(`${i.asset.name} already has a state named "${n}"`);let s=e.version===4?Ro("st",new Set(i.asset.states.map(c=>c.id))):`st_${String(i.asset.states.length).padStart(3,"0")}`;return i.asset.raw.states.push({state_id:s,state_name:n,description:o}),F("state",`${i.asset.id} + ${s} "${n}"`),be(e),`${i.asset.id}/${s} ${n} (${i.asset.name} now has ${i.asset.states.length+1} states)`+Be(e,r)}function U5(e,t){let n=Te(e,t);switch(n.t){case"script":return{raw:n.doc.raw,label:"script"};case"ep":return{raw:n.ep.raw,label:n.ep.id};case"scene":return{raw:n.scene.raw,label:n.scene.anchor};case"action":return{raw:n.action.raw,label:n.action.anchor};case"asset":return{raw:n.asset.raw,label:n.asset.id};case"state":return{raw:n.asset.raw.states.find(i=>i.state_id===n.state.id),label:`${n.asset.id}/${n.state.id}`}}}function _m(e,t,n,o,i=!1){let{raw:r,label:s}=U5(e,t),c=r.extend??{};if(!n){let a=Object.keys(c);return a.length?`${s} extend:
205
205
  `+a.map(d=>` ${d} = ${JSON.stringify(c[d])}`).join(`
206
- `):`${s} has no extend data`}if(i){if(!(n in c))throw new Error(`${s} has no extend key "${n}"`);return delete c[n],Object.keys(c).length?r.extend=c:delete r.extend,Q("ext",`${s} -= ${n}`),be(e),`${s} removed extend.${n}`}if(o===void 0){if(!(n in c))throw new Error(`${s} has no extend key "${n}"`);return`${s} extend.${n} = ${JSON.stringify(c[n])}`}return r.extend={...c,[n]:o},Q("ext",`${s} extend.${n} = ${o}`),be(e),`${s} extend.${n} = ${JSON.stringify(o)}`}function ym(e,t,n={}){let o=Te(e,t),i=pt(e);if(o.t==="action"){let r=o.action.scene.raw.actions;return r.splice(r.indexOf(o.action.raw),1),Q("del",`action ${o.action.anchor} from ${o.action.scene.anchor}`),be(e),`deleted ${o.action.anchor} ${da(o.action.raw)}`+Ge(e,i)}if(o.t==="scene"){if(o.scene.actions.length&&!n.force)throw new Error(`${o.scene.anchor} still holds ${o.scene.actions.length} action(s) \u2014 pass --force to delete the scene and everything in it`);let r=o.scene.ep.raw.scenes;return r.splice(r.indexOf(o.scene.raw),1),Q("del",`scene ${o.scene.anchor} (${o.scene.actions.length} actions)`),be(e),`deleted scene ${o.scene.anchor} with ${o.scene.actions.length} action(s)`+Ge(e,i)}if(o.t==="ep"){let r=o.ep.scenes.reduce((c,a)=>c+a.actions.length,0);if(o.ep.scenes.length&&!n.force)throw new Error(`episode ${o.ep.no} still holds ${o.ep.scenes.length} scene(s) / ${r} action(s) \u2014 pass --force to delete the episode and everything in it`);let s=e.raw.episodes;return s.splice(s.indexOf(o.ep.raw),1),Q("del",`episode ${o.ep.no}`),be(e),`deleted episode ${o.ep.no} (${o.ep.id}) with ${o.ep.scenes.length} scene(s) / ${r} action(s)`}if(o.t==="asset")return U5(e,o.asset,n)+Ge(e,i);if(o.t==="state")return P5(e,o.asset,o.state,n)+Ge(e,i);throw new Error(`del takes an action, scene, episode, asset or state (got ${o.t})`)}function wm(e,t){let n=[];for(let o of e.episodes)for(let i of o.scenes)[i.location,...i.actors,...i.props].some(r=>r&&r.id===t)&&n.push(i);return{scenes:n,speakers:bn(e).filter(o=>o.speaker?.id===t)}}function U5(e,t,n){let{scenes:o,speakers:i}=wm(e,t.id),r=o.length+i.length;if(r&&!n.replacement&&!n.force)throw new Error(`${t.name} is still referenced by ${o.length} scene(s) and ${i.length} speaker(s) \u2014 merge it into another asset with \`merge ${t.id} <other>\`, or pass --force to strip every reference`);if(n.replacement)return lp(e,t.id,n.replacement);for(let a of o){a.raw.location?.[`${t.kind}_id`]===t.id&&(a.raw.location=null);for(let d of["actors","props"]){let p=a.raw[d];if(!p)continue;let l=p.findIndex(f=>f[`${t.kind}_id`]===t.id);l>=0&&p.splice(l,1)}}for(let a of i)delete a.raw.speaker;let s=pp[t.kind],c=e.raw[s];return c.splice(c.indexOf(t.raw),1),Q("del",`asset ${t.id}, stripped ${o.length} scene refs + ${i.length} speakers`),be(e),`deleted ${t.kind} ${t.id} ${t.name}`+(r?`
207
- stripped ${o.length} scene reference(s) and ${i.length} speaker(s)`:"")}function P5(e,t,n,o){if(n.id==="default")throw new Error("every asset keeps its default state; delete the asset instead");let i=e.episodes.flatMap(d=>d.scenes).filter(d=>[d.location,...d.actors,...d.props].some(p=>p&&p.id===t.id&&p.states.includes(n.id))),r=bn(e).filter(d=>d.speaker?.id===t.id&&d.speaker.state===n.id),s=i.length+r.length,c="";if(s){if(!o.replacement&&!o.force)throw new Error(`${t.name}/${n.name} is bound in ${i.length} scene(s) and named by ${r.length} speaker(s) \u2014 pass --replacement <state> to rewire them, or --force to drop the bindings`);let d;if(o.replacement){let p=t.states.filter(l=>l.id===o.replacement||l.name===o.replacement);if(p.length!==1)throw new Error(`${t.name} has no single state "${o.replacement}"`);if(p[0].id===n.id)throw new Error("replacement must differ from the state being deleted");d=p[0].id}for(let p of i)for(let l of[p.raw.location,...p.raw.actors??[],...p.raw.props??[]])if(!(!l||l[`${t.kind}_id`]!==t.id))if(e.version===4){let f=new Set(l.state_ids.filter(u=>u!==n.id));d&&f.add(d),f.size||f.add("default"),l.state_ids=[...f].sort()}else l.state_id=d??"default";for(let p of r)d?p.raw.speaker.state_id=d:delete p.raw.speaker.state_id;c=`
208
- ${d?"rewired":"cleared"} ${i.length} scene binding(s) and ${r.length} speaker(s)${d?` to ${si(e,t.id,d)}`:""}`}let a=t.raw.states;return a.splice(a.findIndex(d=>d.state_id===n.id),1),Q("del",`state ${t.id}/${n.id}`),be(e),`deleted state ${t.id}/${n.id} ${n.name}`+c}function lp(e,t,n){let o=Te(e,t),i=Te(e,n);if(o.t!=="asset"||i.t!=="asset")throw new Error("merge takes two assets");if(o.asset===i.asset)throw new Error(`cannot merge ${o.asset.name} into itself`);if(o.asset.kind!==i.asset.kind)throw new Error(`cannot merge a ${o.asset.kind} into a ${i.asset.kind}`);let r=pt(e),s=o.asset,c=i.asset,a=`${s.kind}_id`,d=new Set(c.states.map(g=>g.id)),p=new Map;for(let g of s.states){let h=c.states.find(w=>w.name===g.name);if(h){p.set(g.id,h.id);continue}if(g.id==="default"){p.set(g.id,"default");continue}let m=e.version===4?vo("st",d):`st_${String(c.states.length+p.size).padStart(3,"0")}`;c.raw.states.push({state_id:m,state_name:g.name,description:g.desc}),p.set(g.id,m)}let{scenes:l,speakers:f}=wm(e,s.id);for(let g of l)for(let h of["location","actors","props"]){let m=g.raw[h],w=h==="location"?m?[m]:[]:m??[];for(let y of w)y[a]===s.id&&(y[a]=c.id,e.version===4?y.state_ids=[...new Set(y.state_ids.map(_=>p.get(_)??"default"))].sort():y.state_id=p.get(y.state_id)??"default");if(h!=="location"&&Array.isArray(m)){let y=[];for(let _ of m){let x=y.find(E=>E[a]===_[a]);if(!x){y.push(_);continue}e.version===4&&(x.state_ids=[...new Set([...x.state_ids,..._.state_ids])].sort())}g.raw[h]=y}}for(let g of f)g.raw.speaker.actor_id=c.id,g.raw.speaker.state_id&&(g.raw.speaker.state_id=p.get(g.raw.speaker.state_id)??"default");let u=e.raw[pp[s.kind]];return u.splice(u.indexOf(s.raw),1),Q("merge",`${s.id} -> ${c.id}: ${l.length} scenes, ${f.length} speakers`),be(e),`merged ${s.id} ${s.name} into ${c.id} ${c.name}
209
- moved ${l.length} scene reference(s), ${f.length} speaker(s), ${[...p].filter(([g,h])=>g!==h).length} state mapping(s)`+Ge(e,r)}import{z as Vt}from"zod";var C5=Vt.string().min(1),T5=Vt.array(Vt.number().int().min(1)).min(1).describe("1-based PDF \u7269\u7406\u9875\u7801\uFF1B\u8DE8\u9875\u753B\u683C\u6216\u540C\u4E00\u6C14\u6CE1\u586B\u5199\u76F8\u5173\u7684\u5168\u90E8\u9875\u7801\uFF1B\u540C\u4E00\u4E2A\u8DE8\u9875\u6C14\u6CE1\u5408\u4E3A\u4E00\u6761\u5B8C\u6574\u5BF9\u767D\uFF0C\u6309\u5347\u5E8F\u6392\u5217"),pa=Vt.number().min(0).max(1e3),la=Vt.object({page:Vt.number().int().min(1),kind:Vt.enum(["panel","bubble","text"]),box:Vt.object({top:pa,left:pa,bottom:pa,right:pa}).describe("\u76F8\u5BF9\u4E8E\u5B8C\u6574 PDF \u7269\u7406\u9875\u7684\u77E9\u5F62\uFF0C\u5DE6\u4E0A\u89D2\u4E3A\u539F\u70B9\uFF0C\u6A2A\u7EB5\u5404\u5F52\u4E00\u5316\u5230 0\u20131000\uFF1B\u4E0D\u662F\u88C1\u526A\u56FE\u6216\u753B\u683C\u5185\u7684\u5750\u6807")}),ua=Vt.array(la).min(1).describe("\u672C\u6761\u6B63\u6587\u5B9E\u9645\u5BF9\u5E94\u7684\u753B\u683C(panel)\u3001\u6C14\u6CE1(bubble)\u6216\u72EC\u7ACB\u6587\u5B57\u5757(text)\uFF1B\u6309\u9605\u8BFB\u987A\u5E8F\u5217\u51FA\u5168\u90E8\u533A\u57DF\u3002\u8DE8\u9875\u533A\u57DF\u5404\u9875\u5206\u522B\u7ED9\u6846\uFF0C\u4E0D\u7528\u6574\u9875\u4EE3\u66FF\u5177\u4F53\u5185\u5BB9");function Qr(e,t){let n=[];for(let o of t){e.includes(o.page)||n.push(`Region page ${o.page} is absent from action pages.`);let{top:i,left:r,bottom:s,right:c}=o.box;(s<=i||c<=r)&&n.push(`Region on page ${o.page} has an empty or inverted box.`)}for(let o of e)t.some(i=>i.page===o)||n.push(`Page ${o} has no source region.`);return n}var _m=Vt.object({kind:Vt.literal("comic"),document_id:C5,pages:T5,regions:ua.optional()}),ci=Vt.object({scriptctl:Vt.object({source:_m})});import{z as K}from"zod";var nt=K.string().min(1),di=K.array(nt),Em=K.object({name:nt,description:nt}),fp=K.string().length(0),xm=K.object({apparent_gender:K.string(),apparent_age:K.string(),face_shape:K.string(),brows_eyes:K.string(),nose:K.string(),mouth:K.string(),skin_features:K.string(),hair:K.string(),build:K.string(),persistent_marks:di,voice:fp.describe("\u6F2B\u753B\u6CA1\u6709\u539F\u58F0\u97F3\u8F68\uFF0C\u586B\u7A7A\u4E32")}),V5=K.object({name:nt,kind:K.enum(["actor","location","prop"]),status:K.enum(["canonical","provisional"]),importance:K.enum(["featured","background"]),recognition_anchors:di,identity_profile:xm,appearance:K.string(),role:K.string(),states:K.array(Em),aliases:di}),$5=K.object({new_entities:K.array(V5),enrich:K.array(K.object({name:nt,add_recognition_anchors:di,identity_profile_patch:xm,appearance:K.string(),role:K.string(),add_aliases:di,add_states:K.array(Em)})),canonicalize:K.array(K.object({from_name:nt,canonical_name:nt,evidence:nt.describe("\u672C\u8BDD PDF \u9875\u7801\u548C\u76F4\u63A5\u51FA\u73B0\u7684\u59D3\u540D\u539F\u6587")}))}),Sm=K.array(K.number().int().min(1)).min(1).describe("1-based PDF \u7269\u7406\u9875\u7801\uFF1B\u8DE8\u9875\u753B\u683C\u6216\u540C\u4E00\u6C14\u6CE1\u586B\u5199\u76F8\u5173\u7684\u5168\u90E8\u9875\u7801\uFF1B\u540C\u4E00\u4E2A\u8DE8\u9875\u6C14\u6CE1\u5408\u4E3A\u4E00\u6761\u5B8C\u6574\u5BF9\u767D\uFF0C\u6309\u5347\u5E8F\u6392\u5217"),Im="\u4EBA\u7269\u89C4\u8303\u540D\uFF1B\u5BA2\u89C2\u65C1\u767D\u7528 offscreen:\u65C1\u767D\uFF0C\u7CFB\u7EDF\u53D1\u58F0\u7528 system:\u7CFB\u7EDF\uFF0C\u7FA4\u4F53\u7528 group:\u79F0\u547C",Am="\u4E25\u683C\u6309\u6F2B\u753B\u9605\u8BFB\u987A\u5E8F\u6392\u5217\uFF0C\u753B\u9762\u548C\u5BF9\u767D\u4EA4\u9519\uFF1B\u9010\u683C\u5B8C\u6574\u8F6C\u5199",km=K.object({type:K.enum(["dialogue","inner_thought"]),content:nt,pages:Sm,regions:ua,speaker:nt.describe(Im),parenthetical:K.string()}),D5=K.discriminatedUnion("type",[K.object({type:K.enum(["action","transition"]),content:nt,pages:Sm,regions:ua}),km]),bm=K.object({space:K.union([K.enum(["interior","exterior"]),fp]),time:K.union([K.enum(["day","night","dawn","dusk"]),fp]),location:K.string().describe("\u672C\u573A\u5730\u70B9\u7684\u89C4\u8303\u540D\uFF0C\u5FC5\u987B\u5DF2\u5728\u5DF2\u77E5\u8BBE\u5B9A\u6216\u672C\u6B21 registry_delta \u767B\u8BB0\uFF1B\u7A7A\u95F4\u65E0\u6CD5\u786E\u8BA4\u586B\u7A7A\u4E32"),characters:K.array(K.object({name:nt,states:di})),props:di,actions:K.array(D5).min(1).describe(Am)}),fa=K.object({registry_delta:$5,synopsis:nt,scenes:K.array(bm).min(1),open_threads:K.object({opened:K.array(K.object({text:nt})),closed:K.array(K.object({ref:nt}))}),ignored_pages:K.array(K.object({page:K.number().int().min(1),reason:nt.describe("\u53EA\u7528\u4E8E\u6574\u9875\u7A7A\u767D\u3001\u5C01\u9762\u6216\u5236\u4F5C\u4FE1\u606F\uFF1B\u542B\u5267\u60C5\u6216\u53F0\u8BCD\u7684\u9875\u9762\u5FC5\u987B\u8F6C\u5199")}))}),Om=fa.extend({scenes:K.array(bm.extend({actions:K.array(km.extend({type:K.enum(["action","transition","dialogue","inner_thought"]),speaker:K.string().describe(`${Im}\uFF1Baction/transition \u586B\u7A7A\u4E32`)})).min(1).describe(Am)})).min(1)});import*as ve from"node:fs";import*as St from"node:path";import{spawn as G5}from"node:child_process";import{createHash as B5}from"node:crypto";import{PDFDocument as vm}from"pdf-lib";var mp=1200;function Rm(e,t){return new Promise((n,o)=>{let i=G5("pdftoppm",["-cropbox","-scale-to-x",String(mp),"-scale-to-y","-1","-jpeg","-jpegopt","quality=92",e,t],{stdio:["ignore","ignore","pipe"]}),r="";i.stderr.on("data",s=>{r+=String(s)}),i.on("error",s=>o(new S(`Cannot render comic pages: ${s.message}`,{exitCode:k,errorCode:"VIEW_PDF_RENDER_FAILED",hint:"Install Poppler (pdftoppm), then rerun scriptctl view."}))),i.on("close",s=>{s===0?n():o(new S(`PDF page rendering failed: ${r.trim()}`,{exitCode:k,errorCode:"VIEW_PDF_RENDER_FAILED",data:{actual:[e]}}))})})}async function ma(e,t){let n=`review-pages/cropbox-w${mp}-q92/${e.sha256}`,o=St.join(t,n),i=String(e.page_count).length,r=Array.from({length:e.page_count},(s,c)=>`page-${String(c+1).padStart(i,"0")}.jpg`);if(!r.every(s=>ve.existsSync(St.join(o,s)))){let s=`${o}.part`;ve.rmSync(s,{recursive:!0,force:!0}),ve.mkdirSync(s,{recursive:!0}),process.stderr.write(`\u6E32\u67D3\u6F2B\u753B\u539F\u9875 \xB7 ${e.title} \xB7 ${e.page_count} \u9875
210
- `),await Rm(e.path,St.join(s,"page"));for(let c of r)if(!ve.existsSync(St.join(s,c))||ve.statSync(St.join(s,c)).size===0)throw new S(`PDF renderer did not produce ${c}.`,{exitCode:k,errorCode:"VIEW_PDF_RENDER_FAILED"});ve.rmSync(o,{recursive:!0,force:!0}),ve.renameSync(s,o)}return r.map(s=>`${n}/${s}`)}async function Mm(e,t,n){la.parse(t);let o=Qr([t.page],[t]);if(t.page>e.page_count||o.length)throw new Error(`Invalid comic region: ${o.join("; ")}`);let i=B5("sha256").update(JSON.stringify(t)).digest("hex"),r=`review-pages/cropbox-w${mp}-q92/${e.sha256}/regions/${i}.jpg`,s=St.join(n,r);if(ve.existsSync(s)&&ve.statSync(s).size>0)return r;let c=await vm.load(ve.readFileSync(e.path)),a=await vm.create(),[d]=await a.copyPages(c,[t.page-1]),p=d.getCropBox(),l=(d.getRotation().angle%360+360)%360,{left:f,right:u,top:g,bottom:h}=t.box,m=f/1e3,w=u/1e3,y=g/1e3,_=h/1e3,x=l===90?[y,m,_,w]:l===180?[1-w,y,1-m,_]:l===270?[1-_,1-w,1-y,1-m]:[m,1-_,w,1-y];d.setCropBox(p.x+x[0]*p.width,p.y+x[1]*p.height,(x[2]-x[0])*p.width,(x[3]-x[1])*p.height),a.addPage(d),ve.mkdirSync(St.dirname(s),{recursive:!0});let E=ve.mkdtempSync(St.join(St.dirname(s),".region-"));try{let A=St.join(E,"crop.pdf");ve.writeFileSync(A,await a.save()),await Rm(A,St.join(E,"page")),ve.renameSync(St.join(E,"page-1.jpg"),s)}finally{ve.rmSync(E,{recursive:!0,force:!0})}return r}var J5=ot.object({episode:ot.number().int().positive(),document_id:ot.string().min(1),source_number:ot.number().nullable(),title:ot.string(),path:ot.string(),sha256:ot.string(),page_count:ot.number().int().positive(),size_bytes:ot.number()}),j5=ot.object({source:ot.object({kind:ot.enum(["comic-file","comic-directory"])}),episodes:ot.array(J5)});function tn(e){throw new S(e,{exitCode:k,errorCode:"REVIEW_COMIC_SOURCE_INVALID",hint:"Pass -s to the comic ingest workspace, or to its original PDF files with manifest.json beside script.json. Keep the original source PDFs unchanged."})}function K5(e){let t=it.join(e,"manifest.json");if(!rt.existsSync(t))return!1;let n=ot.object({source:ot.object({kind:ot.string()}).optional()}).parse(JSON.parse(rt.readFileSync(t,"utf8")));return n.source?.kind==="comic-file"||n.source?.kind==="comic-directory"}async function Lm(e,t,n){let o=rt.statSync(e).isDirectory()&&K5(e)?it.resolve(e):it.dirname(it.resolve(t)),i=it.join(o,"manifest.json");rt.existsSync(i)||tn("Comic review needs the ingest manifest to verify source identity.");let r=j5.safeParse(JSON.parse(rt.readFileSync(i,"utf8")));r.success||tn(`Invalid comic manifest: ${r.error.message}`);let s=r.data,c=Oo(JSON.parse(rt.readFileSync(t,"utf8")));c.version!==4&&tn("Comic source review requires the ingested Script v4.");let a=c.episodes.filter(w=>!n?.length||n.includes(w.no));a.length||tn("No selected episodes exist in this script.");let d=it.resolve(e)===o?void 0:rt.statSync(e).isFile()?[it.resolve(e)]:rt.readdirSync(e).filter(w=>/\.pdf$/i.test(w)).map(w=>it.resolve(e,w)),p=new Map;for(let w of d??[])p.set(Nm("sha256").update(rt.readFileSync(w)).digest("hex"),w);let l=new Map,f=[];for(let w of a){let y=new Set(w.scenes.flatMap(_=>_.actions.flatMap(x=>{let E=ci.safeParse(x.raw.extend);return E.success?[E.data.scriptctl.source.document_id]:[]})));y.size||tn(`Episode ${w.no} has no comic document identity; cannot safely match an original PDF.`);for(let _ of y){let x=s.episodes.find(C=>C.document_id===_);x||tn(`Unknown comic document: ${_}`),f.some(C=>C.document_id===_&&C.episode!==w.no)&&tn(`Comic document ${_} is bound to multiple script episodes.`);let E=d?p.get(x.sha256):it.resolve(o,x.path);(!E||!rt.existsSync(E))&&tn(`Original PDF missing or changed: ${x.title}`),Nm("sha256").update(rt.readFileSync(E)).digest("hex")!==x.sha256&&tn(`Original PDF content changed: ${x.title}`);let b={...x,path:E};l.set(_,b),f.push({document_id:_,episode:w.no,title:x.title,page_count:x.page_count})}}let u=new Map,g=it.dirname(it.resolve(t));function h(w){let y=l.get(w);return y||tn(`Comic document not available: ${w}`)}function m(w,y){return{path:w,label:y,data:rt.readFileSync(w).toString("base64")}}return{documents:f,async page(w,y){let _=h(w);(!Number.isInteger(y)||y<1||y>_.page_count)&&tn(`Invalid page ${y} in ${w}.`);let x=u.get(w);x||(x=ma(_,g),u.set(w,x));let E=await x;return m(it.join(g,E[y-1]),`${w} \u7B2C ${y} \u9875\u6982\u89C8\uFF1B\u6587\u5B57\u4E0D\u6E05\u65F6\u7528 region \u653E\u5927`)},async region(w,y){let _=await Mm(h(w),y,g);return m(it.join(g,_),`${w} \u7B2C ${y.page} \u9875 ${JSON.stringify(y.box)}`)}}}import*as vn from"node:fs";import*as qr from"node:path";import{z as wp}from"zod";import*as Wi from"node:fs";import*as Zi from"node:path";var hp=[".txt",".md",".docx"],yp={".mp4":"video/mp4",".mov":"video/mov",".avi":"video/avi",".mpeg":"video/mpeg",".mpg":"video/mpg",".webm":"video/webm",".flv":"video/x-flv",".wmv":"video/wmv"},Yr=class extends Error{constructor(n){super(`Unsupported input: ${n}`);this.received=n}received};function gp(e){return Zi.extname(e).toLowerCase()}function Um(e){return Object.hasOwn(yp,e)}function On(e){if(Wi.statSync(e).isDirectory()){let o=Wi.readdirSync(e).filter(r=>!r.startsWith(".")&&gp(r)===".pdf"&&Wi.statSync(Zi.join(e,r)).isFile()).sort().map(r=>Zi.join(e,r)),i=Wi.readdirSync(e).filter(r=>!r.startsWith(".")).filter(r=>Um(gp(r))).sort().map(r=>Zi.join(e,r));if(o.length&&i.length)throw new Yr("directory mixes PDF comics and video episodes; use a directory with one source kind");if(o.length)return{kind:"comic-directory",path:e,files:o};if(i.length===0)throw new Yr(`directory has no supported video or PDF files: ${e}`);return{kind:"video-directory",path:e,files:i}}let n=gp(e);if(n===".pdf")return{kind:"comic-file",path:e,ext:n};if(hp.includes(n))return{kind:"text",path:e,ext:n};if(Um(n))return{kind:"video-file",path:e,ext:n};throw new Yr(`file extension ${n||"(none)"} is not supported by ingest (txt/md/docx/video/pdf only)`)}var Pm=/\.(mp4|mov|mkv|m4v|webm|avi|mpeg|mpg|flv|wmv)$/i;function Cm(e,t=!1){if(t)return"video";if(!e)return"script";if(!vn.existsSync(e))throw new S("Review source not found.",{exitCode:k,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass an existing original source or ingest workspace, or omit -s for script-only review."});if(vn.statSync(e).isFile()){if(/\.pdf$/i.test(e))return"comic";if(hp.some(n=>qr.extname(e).toLowerCase()===n))return"text";if(Pm.test(e))return"video"}else{let n=vn.readdirSync(e).filter(s=>!s.startsWith(".")&&vn.statSync(qr.join(e,s)).isFile()),o=n.some(s=>/\.pdf$/i.test(s)),i=n.some(s=>Pm.test(s));if(o&&i)throw new S("Review source mixes PDF and video files.",{exitCode:k,errorCode:"REVIEW_SOURCE_AMBIGUOUS",hint:"Use a source directory containing only one media kind."});if(i)return"video";if(o)return"comic";let r=qr.join(e,"manifest.json");if(vn.existsSync(r)){let s=wp.object({source:wp.object({kind:wp.string()})}).parse(JSON.parse(vn.readFileSync(r,"utf8")));if(s.source.kind==="text")return"text";if(["comic-file","comic-directory"].includes(s.source.kind))return"comic"}}throw new S("Unsupported review source.",{exitCode:k,errorCode:"REVIEW_SOURCE_UNSUPPORTED",hint:"Use a text/comic ingest workspace, original txt/md/docx/PDF, a video file or a directory of videos."})}import*as Zn from"node:fs";import*as Kt from"node:path";import{z as Ye}from"zod";import{z as Yn}from"zod";var z5=Yn.object({start_line:Yn.number().int().positive(),end_line:Yn.number().int().positive()}),_p=Yn.object({kind:Yn.literal("text"),document_id:Yn.string().min(1),ranges:Yn.array(z5).min(1).describe("\u5B8C\u6574\u89C4\u8303\u5316\u539F\u6587\u7684 1-based \u95ED\u533A\u95F4\uFF1B\u53EF\u4EE5\u662F\u5305\u542B\u76F8\u90BB\u5185\u5BB9\u7684\u5019\u9009\u7A97\u53E3\uFF0C\u9700\u8BFB\u53D6\u539F\u6587\u786E\u8BA4\u5BF9\u5E94\u5173\u7CFB")}),bN=Yn.object({scriptctl:Yn.object({source:_p})});function ga(e){return`text-${e}`}import*as jm from"node:fs";import*as Tm from"node:fs";import Vm from"jszip";import{XMLParser as Q5}from"fast-xml-parser";function $m(e){return e==null?"":String(e)}function Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(e){return Array.isArray(e)}function Dm(e){if(e.length===0)return"";let t=[],n="";for(let o=1;o<e.length;o++){let i=e[o];if(i.filter(p=>p).length===0)continue;let s=i[0]??"";if(s.includes("\u{1F3AC}")||/第\s*\d+\s*集/.test(s)){t.push(`
206
+ `):`${s} has no extend data`}if(i){if(!(n in c))throw new Error(`${s} has no extend key "${n}"`);return delete c[n],Object.keys(c).length?r.extend=c:delete r.extend,F("ext",`${s} -= ${n}`),be(e),`${s} removed extend.${n}`}if(o===void 0){if(!(n in c))throw new Error(`${s} has no extend key "${n}"`);return`${s} extend.${n} = ${JSON.stringify(c[n])}`}return r.extend={...c,[n]:o},F("ext",`${s} extend.${n} = ${o}`),be(e),`${s} extend.${n} = ${JSON.stringify(o)}`}function Em(e,t,n={}){let o=Te(e,t),i=pt(e);if(o.t==="action"){let r=o.action.scene.raw.actions;return r.splice(r.indexOf(o.action.raw),1),F("del",`action ${o.action.anchor} from ${o.action.scene.anchor}`),be(e),`deleted ${o.action.anchor} ${la(o.action.raw)}`+Be(e,i)}if(o.t==="scene"){if(o.scene.actions.length&&!n.force)throw new Error(`${o.scene.anchor} still holds ${o.scene.actions.length} action(s) \u2014 pass --force to delete the scene and everything in it`);let r=o.scene.ep.raw.scenes;return r.splice(r.indexOf(o.scene.raw),1),F("del",`scene ${o.scene.anchor} (${o.scene.actions.length} actions)`),be(e),`deleted scene ${o.scene.anchor} with ${o.scene.actions.length} action(s)`+Be(e,i)}if(o.t==="ep"){let r=o.ep.scenes.reduce((c,a)=>c+a.actions.length,0);if(o.ep.scenes.length&&!n.force)throw new Error(`episode ${o.ep.no} still holds ${o.ep.scenes.length} scene(s) / ${r} action(s) \u2014 pass --force to delete the episode and everything in it`);let s=e.raw.episodes;return s.splice(s.indexOf(o.ep.raw),1),F("del",`episode ${o.ep.no}`),be(e),`deleted episode ${o.ep.no} (${o.ep.id}) with ${o.ep.scenes.length} scene(s) / ${r} action(s)`}if(o.t==="asset")return P5(e,o.asset,n)+Be(e,i);if(o.t==="state")return C5(e,o.asset,o.state,n)+Be(e,i);throw new Error(`del takes an action, scene, episode, asset or state (got ${o.t})`)}function xm(e,t){let n=[];for(let o of e.episodes)for(let i of o.scenes)[i.location,...i.actors,...i.props].some(r=>r&&r.id===t)&&n.push(i);return{scenes:n,speakers:bn(e).filter(o=>o.speaker?.id===t)}}function P5(e,t,n){let{scenes:o,speakers:i}=xm(e,t.id),r=o.length+i.length;if(r&&!n.replacement&&!n.force)throw new Error(`${t.name} is still referenced by ${o.length} scene(s) and ${i.length} speaker(s) \u2014 merge it into another asset with \`merge ${t.id} <other>\`, or pass --force to strip every reference`);if(n.replacement)return fp(e,t.id,n.replacement);for(let a of o){a.raw.location?.[`${t.kind}_id`]===t.id&&(a.raw.location=null);for(let d of["actors","props"]){let p=a.raw[d];if(!p)continue;let l=p.findIndex(f=>f[`${t.kind}_id`]===t.id);l>=0&&p.splice(l,1)}}for(let a of i)delete a.raw.speaker;let s=up[t.kind],c=e.raw[s];return c.splice(c.indexOf(t.raw),1),F("del",`asset ${t.id}, stripped ${o.length} scene refs + ${i.length} speakers`),be(e),`deleted ${t.kind} ${t.id} ${t.name}`+(r?`
207
+ stripped ${o.length} scene reference(s) and ${i.length} speaker(s)`:"")}function C5(e,t,n,o){if(n.id==="default")throw new Error("every asset keeps its default state; delete the asset instead");let i=e.episodes.flatMap(d=>d.scenes).filter(d=>[d.location,...d.actors,...d.props].some(p=>p&&p.id===t.id&&p.states.includes(n.id))),r=bn(e).filter(d=>d.speaker?.id===t.id&&d.speaker.state===n.id),s=i.length+r.length,c="";if(s){if(!o.replacement&&!o.force)throw new Error(`${t.name}/${n.name} is bound in ${i.length} scene(s) and named by ${r.length} speaker(s) \u2014 pass --replacement <state> to rewire them, or --force to drop the bindings`);let d;if(o.replacement){let p=t.states.filter(l=>l.id===o.replacement||l.name===o.replacement);if(p.length!==1)throw new Error(`${t.name} has no single state "${o.replacement}"`);if(p[0].id===n.id)throw new Error("replacement must differ from the state being deleted");d=p[0].id}for(let p of i)for(let l of[p.raw.location,...p.raw.actors??[],...p.raw.props??[]])if(!(!l||l[`${t.kind}_id`]!==t.id))if(e.version===4){let f=new Set(l.state_ids.filter(u=>u!==n.id));d&&f.add(d),f.size||f.add("default"),l.state_ids=[...f].sort()}else l.state_id=d??"default";for(let p of r)d?p.raw.speaker.state_id=d:delete p.raw.speaker.state_id;c=`
208
+ ${d?"rewired":"cleared"} ${i.length} scene binding(s) and ${r.length} speaker(s)${d?` to ${si(e,t.id,d)}`:""}`}let a=t.raw.states;return a.splice(a.findIndex(d=>d.state_id===n.id),1),F("del",`state ${t.id}/${n.id}`),be(e),`deleted state ${t.id}/${n.id} ${n.name}`+c}function fp(e,t,n){let o=Te(e,t),i=Te(e,n);if(o.t!=="asset"||i.t!=="asset")throw new Error("merge takes two assets");if(o.asset===i.asset)throw new Error(`cannot merge ${o.asset.name} into itself`);if(o.asset.kind!==i.asset.kind)throw new Error(`cannot merge a ${o.asset.kind} into a ${i.asset.kind}`);let r=pt(e),s=o.asset,c=i.asset,a=`${s.kind}_id`,d=new Set(c.states.map(m=>m.id)),p=new Map;for(let m of s.states){let h=c.states.find(w=>w.name===m.name);if(h){p.set(m.id,h.id);continue}if(m.id==="default"){p.set(m.id,"default");continue}let g=e.version===4?Ro("st",d):`st_${String(c.states.length+p.size).padStart(3,"0")}`;c.raw.states.push({state_id:g,state_name:m.name,description:m.desc}),p.set(m.id,g)}let{scenes:l,speakers:f}=xm(e,s.id);for(let m of l)for(let h of["location","actors","props"]){let g=m.raw[h],w=h==="location"?g?[g]:[]:g??[];for(let y of w)y[a]===s.id&&(y[a]=c.id,e.version===4?y.state_ids=[...new Set(y.state_ids.map(_=>p.get(_)??"default"))].sort():y.state_id=p.get(y.state_id)??"default");if(h!=="location"&&Array.isArray(g)){let y=[];for(let _ of g){let S=y.find(E=>E[a]===_[a]);if(!S){y.push(_);continue}e.version===4&&(S.state_ids=[...new Set([...S.state_ids,..._.state_ids])].sort())}m.raw[h]=y}}for(let m of f)m.raw.speaker.actor_id=c.id,m.raw.speaker.state_id&&(m.raw.speaker.state_id=p.get(m.raw.speaker.state_id)??"default");let u=e.raw[up[s.kind]];return u.splice(u.indexOf(s.raw),1),F("merge",`${s.id} -> ${c.id}: ${l.length} scenes, ${f.length} speakers`),be(e),`merged ${s.id} ${s.name} into ${c.id} ${c.name}
209
+ moved ${l.length} scene reference(s), ${f.length} speaker(s), ${[...p].filter(([m,h])=>m!==h).length} state mapping(s)`+Be(e,r)}import{z as Vt}from"zod";var T5=Vt.string().min(1),V5=Vt.array(Vt.number().int().min(1)).min(1).describe("1-based PDF \u7269\u7406\u9875\u7801\uFF1B\u8DE8\u9875\u753B\u683C\u6216\u540C\u4E00\u6C14\u6CE1\u586B\u5199\u76F8\u5173\u7684\u5168\u90E8\u9875\u7801\uFF1B\u540C\u4E00\u4E2A\u8DE8\u9875\u6C14\u6CE1\u5408\u4E3A\u4E00\u6761\u5B8C\u6574\u5BF9\u767D\uFF0C\u6309\u5347\u5E8F\u6392\u5217"),ua=Vt.number().min(0).max(1e3),fa=Vt.object({page:Vt.number().int().min(1),kind:Vt.enum(["panel","bubble","text"]),box:Vt.object({top:ua,left:ua,bottom:ua,right:ua}).describe("\u76F8\u5BF9\u4E8E\u5B8C\u6574 PDF \u7269\u7406\u9875\u7684\u77E9\u5F62\uFF0C\u5DE6\u4E0A\u89D2\u4E3A\u539F\u70B9\uFF0C\u6A2A\u7EB5\u5404\u5F52\u4E00\u5316\u5230 0\u20131000\uFF1B\u4E0D\u662F\u88C1\u526A\u56FE\u6216\u753B\u683C\u5185\u7684\u5750\u6807")}),ma=Vt.array(fa).min(1).describe("\u672C\u6761\u6B63\u6587\u5B9E\u9645\u5BF9\u5E94\u7684\u753B\u683C(panel)\u3001\u6C14\u6CE1(bubble)\u6216\u72EC\u7ACB\u6587\u5B57\u5757(text)\uFF1B\u6309\u9605\u8BFB\u987A\u5E8F\u5217\u51FA\u5168\u90E8\u533A\u57DF\u3002\u8DE8\u9875\u533A\u57DF\u5404\u9875\u5206\u522B\u7ED9\u6846\uFF0C\u4E0D\u7528\u6574\u9875\u4EE3\u66FF\u5177\u4F53\u5185\u5BB9");function qr(e,t){let n=[];for(let o of t){e.includes(o.page)||n.push(`Region page ${o.page} is absent from action pages.`);let{top:i,left:r,bottom:s,right:c}=o.box;(s<=i||c<=r)&&n.push(`Region on page ${o.page} has an empty or inverted box.`)}for(let o of e)t.some(i=>i.page===o)||n.push(`Page ${o} has no source region.`);return n}var Sm=Vt.object({kind:Vt.literal("comic"),document_id:T5,pages:V5,regions:ma.optional()}),ci=Vt.object({scriptctl:Vt.object({source:Sm})});import{z as j}from"zod";var nt=j.string().min(1),di=j.array(nt),Im=j.object({name:nt,description:nt}),gp=j.string().length(0),Am=j.object({apparent_gender:j.string(),apparent_age:j.string(),face_shape:j.string(),brows_eyes:j.string(),nose:j.string(),mouth:j.string(),skin_features:j.string(),hair:j.string(),build:j.string(),persistent_marks:di,voice:gp.describe("\u6F2B\u753B\u6CA1\u6709\u539F\u58F0\u97F3\u8F68\uFF0C\u586B\u7A7A\u4E32")}),$5=j.object({name:nt,kind:j.enum(["actor","location","prop"]),status:j.enum(["canonical","provisional"]),importance:j.enum(["featured","background"]),recognition_anchors:di,identity_profile:Am,appearance:j.string(),role:j.string(),states:j.array(Im),aliases:di}),D5=j.object({new_entities:j.array($5),enrich:j.array(j.object({name:nt,add_recognition_anchors:di,identity_profile_patch:Am,appearance:j.string(),role:j.string(),add_aliases:di,add_states:j.array(Im)})),canonicalize:j.array(j.object({from_name:nt,canonical_name:nt,evidence:nt.describe("\u672C\u8BDD PDF \u9875\u7801\u548C\u76F4\u63A5\u51FA\u73B0\u7684\u59D3\u540D\u539F\u6587")}))}),km=j.array(j.number().int().min(1)).min(1).describe("1-based PDF \u7269\u7406\u9875\u7801\uFF1B\u8DE8\u9875\u753B\u683C\u6216\u540C\u4E00\u6C14\u6CE1\u586B\u5199\u76F8\u5173\u7684\u5168\u90E8\u9875\u7801\uFF1B\u540C\u4E00\u4E2A\u8DE8\u9875\u6C14\u6CE1\u5408\u4E3A\u4E00\u6761\u5B8C\u6574\u5BF9\u767D\uFF0C\u6309\u5347\u5E8F\u6392\u5217"),bm="\u4EBA\u7269\u89C4\u8303\u540D\uFF1B\u5BA2\u89C2\u65C1\u767D\u7528 offscreen:\u65C1\u767D\uFF0C\u7CFB\u7EDF\u53D1\u58F0\u7528 system:\u7CFB\u7EDF\uFF0C\u7FA4\u4F53\u7528 group:\u79F0\u547C",Om="\u4E25\u683C\u6309\u6F2B\u753B\u9605\u8BFB\u987A\u5E8F\u6392\u5217\uFF0C\u753B\u9762\u548C\u5BF9\u767D\u4EA4\u9519\uFF1B\u9010\u683C\u5B8C\u6574\u8F6C\u5199",vm=j.object({type:j.enum(["dialogue","inner_thought"]),content:nt,pages:km,regions:ma,speaker:nt.describe(bm),parenthetical:j.string()}),G5=j.discriminatedUnion("type",[j.object({type:j.enum(["action","transition"]),content:nt,pages:km,regions:ma}),vm]),Rm=j.object({space:j.union([j.enum(["interior","exterior"]),gp]),time:j.union([j.enum(["day","night","dawn","dusk"]),gp]),location:j.string().describe("\u672C\u573A\u5730\u70B9\u7684\u89C4\u8303\u540D\uFF0C\u5FC5\u987B\u5DF2\u5728\u5DF2\u77E5\u8BBE\u5B9A\u6216\u672C\u6B21 registry_delta \u767B\u8BB0\uFF1B\u7A7A\u95F4\u65E0\u6CD5\u786E\u8BA4\u586B\u7A7A\u4E32"),characters:j.array(j.object({name:nt,states:di})),props:di,actions:j.array(G5).min(1).describe(Om)}),ga=j.object({registry_delta:D5,synopsis:nt,scenes:j.array(Rm).min(1),open_threads:j.object({opened:j.array(j.object({text:nt})),closed:j.array(j.object({ref:nt}))}),ignored_pages:j.array(j.object({page:j.number().int().min(1),reason:nt.describe("\u53EA\u7528\u4E8E\u6574\u9875\u7A7A\u767D\u3001\u5C01\u9762\u6216\u5236\u4F5C\u4FE1\u606F\uFF1B\u542B\u5267\u60C5\u6216\u53F0\u8BCD\u7684\u9875\u9762\u5FC5\u987B\u8F6C\u5199")}))}),Mm=ga.extend({scenes:j.array(Rm.extend({actions:j.array(vm.extend({type:j.enum(["action","transition","dialogue","inner_thought"]),speaker:j.string().describe(`${bm}\uFF1Baction/transition \u586B\u7A7A\u4E32`)})).min(1).describe(Om)})).min(1)});import*as ve from"node:fs";import*as St from"node:path";import{spawn as B5}from"node:child_process";import{createHash as J5}from"node:crypto";import{PDFDocument as Nm}from"pdf-lib";var hp=1200;function Lm(e,t){return new Promise((n,o)=>{let i=B5("pdftoppm",["-cropbox","-scale-to-x",String(hp),"-scale-to-y","-1","-jpeg","-jpegopt","quality=92",e,t],{stdio:["ignore","ignore","pipe"]}),r="";i.stderr.on("data",s=>{r+=String(s)}),i.on("error",s=>o(new x(`Cannot render comic pages: ${s.message}`,{exitCode:k,errorCode:"VIEW_PDF_RENDER_FAILED",hint:"Install Poppler (pdftoppm), then rerun scriptctl view."}))),i.on("close",s=>{s===0?n():o(new x(`PDF page rendering failed: ${r.trim()}`,{exitCode:k,errorCode:"VIEW_PDF_RENDER_FAILED",data:{actual:[e]}}))})})}async function ha(e,t){let n=`review-pages/cropbox-w${hp}-q92/${e.sha256}`,o=St.join(t,n),i=String(e.page_count).length,r=Array.from({length:e.page_count},(s,c)=>`page-${String(c+1).padStart(i,"0")}.jpg`);if(!r.every(s=>ve.existsSync(St.join(o,s)))){let s=`${o}.part`;ve.rmSync(s,{recursive:!0,force:!0}),ve.mkdirSync(s,{recursive:!0}),process.stderr.write(`\u6E32\u67D3\u6F2B\u753B\u539F\u9875 \xB7 ${e.title} \xB7 ${e.page_count} \u9875
210
+ `),await Lm(e.path,St.join(s,"page"));for(let c of r)if(!ve.existsSync(St.join(s,c))||ve.statSync(St.join(s,c)).size===0)throw new x(`PDF renderer did not produce ${c}.`,{exitCode:k,errorCode:"VIEW_PDF_RENDER_FAILED"});ve.rmSync(o,{recursive:!0,force:!0}),ve.renameSync(s,o)}return r.map(s=>`${n}/${s}`)}async function Um(e,t,n){fa.parse(t);let o=qr([t.page],[t]);if(t.page>e.page_count||o.length)throw new Error(`Invalid comic region: ${o.join("; ")}`);let i=J5("sha256").update(JSON.stringify(t)).digest("hex"),r=`review-pages/cropbox-w${hp}-q92/${e.sha256}/regions/${i}.jpg`,s=St.join(n,r);if(ve.existsSync(s)&&ve.statSync(s).size>0)return r;let c=await Nm.load(ve.readFileSync(e.path)),a=await Nm.create(),[d]=await a.copyPages(c,[t.page-1]),p=d.getCropBox(),l=(d.getRotation().angle%360+360)%360,{left:f,right:u,top:m,bottom:h}=t.box,g=f/1e3,w=u/1e3,y=m/1e3,_=h/1e3,S=l===90?[y,g,_,w]:l===180?[1-w,y,1-g,_]:l===270?[1-_,1-w,1-y,1-g]:[g,1-_,w,1-y];d.setCropBox(p.x+S[0]*p.width,p.y+S[1]*p.height,(S[2]-S[0])*p.width,(S[3]-S[1])*p.height),a.addPage(d),ve.mkdirSync(St.dirname(s),{recursive:!0});let E=ve.mkdtempSync(St.join(St.dirname(s),".region-"));try{let A=St.join(E,"crop.pdf");ve.writeFileSync(A,await a.save()),await Lm(A,St.join(E,"page")),ve.renameSync(St.join(E,"page-1.jpg"),s)}finally{ve.rmSync(E,{recursive:!0,force:!0})}return r}var K5=ot.object({episode:ot.number().int().positive(),document_id:ot.string().min(1),source_number:ot.number().nullable(),title:ot.string(),path:ot.string(),sha256:ot.string(),page_count:ot.number().int().positive(),size_bytes:ot.number()}),j5=ot.object({source:ot.object({kind:ot.enum(["comic-file","comic-directory"])}),episodes:ot.array(K5)});function tn(e){throw new x(e,{exitCode:k,errorCode:"REVIEW_COMIC_SOURCE_INVALID",hint:"Pass -s to the comic ingest workspace, or to its original PDF files with manifest.json beside script.json. Keep the original source PDFs unchanged."})}function z5(e){let t=it.join(e,"manifest.json");if(!rt.existsSync(t))return!1;let n=ot.object({source:ot.object({kind:ot.string()}).optional()}).parse(JSON.parse(rt.readFileSync(t,"utf8")));return n.source?.kind==="comic-file"||n.source?.kind==="comic-directory"}async function Cm(e,t,n){let o=rt.statSync(e).isDirectory()&&z5(e)?it.resolve(e):it.dirname(it.resolve(t)),i=it.join(o,"manifest.json");rt.existsSync(i)||tn("Comic review needs the ingest manifest to verify source identity.");let r=j5.safeParse(JSON.parse(rt.readFileSync(i,"utf8")));r.success||tn(`Invalid comic manifest: ${r.error.message}`);let s=r.data,c=vo(JSON.parse(rt.readFileSync(t,"utf8")));c.version!==4&&tn("Comic source review requires the ingested Script v4.");let a=c.episodes.filter(w=>!n?.length||n.includes(w.no));a.length||tn("No selected episodes exist in this script.");let d=it.resolve(e)===o?void 0:rt.statSync(e).isFile()?[it.resolve(e)]:rt.readdirSync(e).filter(w=>/\.pdf$/i.test(w)).map(w=>it.resolve(e,w)),p=new Map;for(let w of d??[])p.set(Pm("sha256").update(rt.readFileSync(w)).digest("hex"),w);let l=new Map,f=[];for(let w of a){let y=new Set(w.scenes.flatMap(_=>_.actions.flatMap(S=>{let E=ci.safeParse(S.raw.extend);return E.success?[E.data.scriptctl.source.document_id]:[]})));y.size||tn(`Episode ${w.no} has no comic document identity; cannot safely match an original PDF.`);for(let _ of y){let S=s.episodes.find(U=>U.document_id===_);S||tn(`Unknown comic document: ${_}`),f.some(U=>U.document_id===_&&U.episode!==w.no)&&tn(`Comic document ${_} is bound to multiple script episodes.`);let E=d?p.get(S.sha256):it.resolve(o,S.path);(!E||!rt.existsSync(E))&&tn(`Original PDF missing or changed: ${S.title}`),Pm("sha256").update(rt.readFileSync(E)).digest("hex")!==S.sha256&&tn(`Original PDF content changed: ${S.title}`);let b={...S,path:E};l.set(_,b),f.push({document_id:_,episode:w.no,title:S.title,page_count:S.page_count})}}let u=new Map,m=it.dirname(it.resolve(t));function h(w){let y=l.get(w);return y||tn(`Comic document not available: ${w}`)}function g(w,y){return{path:w,label:y,data:rt.readFileSync(w).toString("base64")}}return{documents:f,async page(w,y){let _=h(w);(!Number.isInteger(y)||y<1||y>_.page_count)&&tn(`Invalid page ${y} in ${w}.`);let S=u.get(w);S||(S=ha(_,m),u.set(w,S));let E=await S;return g(it.join(m,E[y-1]),`${w} \u7B2C ${y} \u9875\u6982\u89C8\uFF1B\u6587\u5B57\u4E0D\u6E05\u65F6\u7528 region \u653E\u5927`)},async region(w,y){let _=await Um(h(w),y,m);return g(it.join(m,_),`${w} \u7B2C ${y.page} \u9875 ${JSON.stringify(y.box)}`)}}}import*as vn from"node:fs";import*as Wr from"node:path";import{z as Ep}from"zod";import*as er from"node:fs";import*as Xi from"node:path";var wp=[".txt",".md",".docx"],_p={".mp4":"video/mp4",".mov":"video/mov",".avi":"video/avi",".mpeg":"video/mpeg",".mpg":"video/mpg",".webm":"video/webm",".flv":"video/x-flv",".wmv":"video/wmv"},Zr=class extends Error{constructor(n){super(`Unsupported input: ${n}`);this.received=n}received};function yp(e){return Xi.extname(e).toLowerCase()}function Tm(e){return Object.hasOwn(_p,e)}function On(e){if(er.statSync(e).isDirectory()){let o=er.readdirSync(e).filter(r=>!r.startsWith(".")&&yp(r)===".pdf"&&er.statSync(Xi.join(e,r)).isFile()).sort().map(r=>Xi.join(e,r)),i=er.readdirSync(e).filter(r=>!r.startsWith(".")).filter(r=>Tm(yp(r))).sort().map(r=>Xi.join(e,r));if(o.length&&i.length)throw new Zr("directory mixes PDF comics and video episodes; use a directory with one source kind");if(o.length)return{kind:"comic-directory",path:e,files:o};if(i.length===0)throw new Zr(`directory has no supported video or PDF files: ${e}`);return{kind:"video-directory",path:e,files:i}}let n=yp(e);if(n===".pdf")return{kind:"comic-file",path:e,ext:n};if(wp.includes(n))return{kind:"text",path:e,ext:n};if(Tm(n))return{kind:"video-file",path:e,ext:n};throw new Zr(`file extension ${n||"(none)"} is not supported by ingest (txt/md/docx/video/pdf only)`)}var Vm=/\.(mp4|mov|mkv|m4v|webm|avi|mpeg|mpg|flv|wmv)$/i;function $m(e,t=!1){if(t)return"video";if(!e)return"script";if(!vn.existsSync(e))throw new x("Review source not found.",{exitCode:k,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass an existing original source or ingest workspace, or omit -s for script-only review."});if(vn.statSync(e).isFile()){if(/\.pdf$/i.test(e))return"comic";if(wp.some(n=>Wr.extname(e).toLowerCase()===n))return"text";if(Vm.test(e))return"video"}else{let n=vn.readdirSync(e).filter(s=>!s.startsWith(".")&&vn.statSync(Wr.join(e,s)).isFile()),o=n.some(s=>/\.pdf$/i.test(s)),i=n.some(s=>Vm.test(s));if(o&&i)throw new x("Review source mixes PDF and video files.",{exitCode:k,errorCode:"REVIEW_SOURCE_AMBIGUOUS",hint:"Use a source directory containing only one media kind."});if(i)return"video";if(o)return"comic";let r=Wr.join(e,"manifest.json");if(vn.existsSync(r)){let s=Ep.object({source:Ep.object({kind:Ep.string()})}).parse(JSON.parse(vn.readFileSync(r,"utf8")));if(s.source.kind==="text")return"text";if(["comic-file","comic-directory"].includes(s.source.kind))return"comic"}}throw new x("Unsupported review source.",{exitCode:k,errorCode:"REVIEW_SOURCE_UNSUPPORTED",hint:"Use a text/comic ingest workspace, original txt/md/docx/PDF, a video file or a directory of videos."})}import*as Zn from"node:fs";import*as jt from"node:path";import{z as Ye}from"zod";import{z as Yn}from"zod";var H5=Yn.object({start_line:Yn.number().int().positive(),end_line:Yn.number().int().positive()}),xp=Yn.object({kind:Yn.literal("text"),document_id:Yn.string().min(1),ranges:Yn.array(H5).min(1).describe("\u5B8C\u6574\u89C4\u8303\u5316\u539F\u6587\u7684 1-based \u95ED\u533A\u95F4\uFF1B\u53EF\u4EE5\u662F\u5305\u542B\u76F8\u90BB\u5185\u5BB9\u7684\u5019\u9009\u7A97\u53E3\uFF0C\u9700\u8BFB\u53D6\u539F\u6587\u786E\u8BA4\u5BF9\u5E94\u5173\u7CFB")}),ON=Yn.object({scriptctl:Yn.object({source:xp})});function ya(e){return`text-${e}`}import*as Hm from"node:fs";import*as Dm from"node:fs";import Gm from"jszip";import{XMLParser as Y5}from"fast-xml-parser";function Bm(e){return e==null?"":String(e)}function Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ne(e){return Array.isArray(e)}function Jm(e){if(e.length===0)return"";let t=[],n="";for(let o=1;o<e.length;o++){let i=e[o];if(i.filter(p=>p).length===0)continue;let s=i[0]??"";if(s.includes("\u{1F3AC}")||/第\s*\d+\s*集/.test(s)){t.push(`
211
211
  ${s}`);continue}let c=i.length>1?i[1]??"":"";c||(c=n),n=c;let a=[];s&&a.push(`${s}.`);let d=i.slice(2).filter(p=>p);c&&d.length>0?a.push(`${c}\uFF0C${d.join(" ")}`):c?a.push(c):a.push(...d),t.push(a.join(" "))}return t.join(`
212
- `)}function Xi(e,t){let n=e[":@"];return Jt(n)?$m(n[t]).trim():""}function ha(e,t){for(let[n,o]of Object.entries(e))if(qn(n)===t&&Ne(o))return o;return null}function ya(e){let t=[],n=o=>{if(Ne(o)){for(let i of o)if(Jt(i))for(let[r,s]of Object.entries(i))r==="#text"&&s!==null&&s!==void 0?t.push($m(s)):r!==":@"&&Ne(s)&&n(s)}};return n(e),t.join("")}function wa(e){let t=Gm.parse(e);if(!Ne(t))throw new Error("xlsx xml part has an unexpected shape");return t}function Ro(e,t){let n=[],o=i=>{let r=Ne(i)?i.filter(Jt):Jt(i)?[i]:[];for(let s of r)for(let[c,a]of Object.entries(s))qn(c)===t&&Ne(a)&&n.push(s),Ne(a)&&o(a)};return o(e),n}function Y5(e){let t=/^[A-Z]+/i.exec(e.trim());if(!t)return null;let n=0;for(let o of t[0].toUpperCase())n=n*26+o.charCodeAt(0)-64;return n-1}function q5(e,t){let o=(t.startsWith("/")?t.slice(1):`${e}/${t}`).split("/"),i=[];for(let r of o)!r||r==="."||(r===".."?i.pop():i.push(r));return i.join("/")}async function _a(e,t){let n=e.file(t);return n?n.async("string"):null}async function Z5(e){let t=await _a(e,"xl/sharedStrings.xml");if(!t)return[];let n=wa(t),o=[];for(let i of Ro(n,"si"))o.push(ya(ha(i,"si")??[]));return o}async function W5(e){let t=await _a(e,"xl/workbook.xml"),n=await _a(e,"xl/_rels/workbook.xml.rels");if(!t||!n)throw new Error("xlsx missing workbook metadata");let o=new Map;for(let r of Ro(wa(n),"Relationship")){let s=Xi(r,"@_Id"),c=Xi(r,"@_Target");s&&c&&o.set(s,q5("xl",c))}let i=[];for(let r of Ro(wa(t),"sheet")){let s=Xi(r,"@_name"),c=Xi(r,"@_r:id"),a=o.get(c);s&&a&&i.push({name:s,path:a})}if(i.length===0)throw new Error("xlsx workbook contains no readable sheets");return i}function X5(e,t){let n=Xi(e,"@_t");if(n==="inlineStr"){let s=Ro(e,"is")[0],c=s?ha(s,"is"):null;return c?ya(c).trim():""}let o=Ro(e,"v")[0],i=o?ha(o,"v"):null,r=i?ya(i).trim():"";if(!r&&n==="str"){let s=Ro(e,"is")[0],c=s?ha(s,"is"):null;return c?ya(c).trim():""}if(n==="s"){let s=Number.parseInt(r,10);return Number.isInteger(s)?(t[s]??"").trim():""}return n==="b"?r==="1"?"TRUE":r==="0"?"FALSE":r:r}async function eS(e){let t=await Vm.loadAsync(e),[n,o]=await Promise.all([Z5(t),W5(t)]),i=[];for(let r of o){let s=await _a(t,r.path);if(!s)throw new Error(`xlsx missing worksheet part: ${r.path}`);let c=[];for(let a of Ro(wa(s),"row")){let d=[];for(let p of Ro(a,"c")){let l=Xi(p,"@_r"),f=l?Y5(l):null,u=X5(p,n),g=f??d.length;for(;d.length<g;)d.push("");d[g]=u.trim()}d.some(p=>p)&&c.push(d)}i.push({name:r.name,rows:c})}return i}var Gm=new Q5({ignoreAttributes:!1,attributeNamePrefix:"@_",preserveOrder:!0,trimValues:!1,textNodeName:"#text"});function qn(e){let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function Ep(e){let t=[];function n(o){if(Ne(o)){for(let i of o)if(Jt(i))for(let[r,s]of Object.entries(i)){if(r===":@"||r==="#text"&&typeof s=="string")continue;let c=qn(r);if(c==="t"){if(Ne(s)){for(let a of s)if(Jt(a)){let d=a["#text"];typeof d=="string"&&t.push(d)}}}else c==="tab"?t.push(" "):c==="br"||c==="cr"?t.push(`
213
- `):Ne(s)&&n(s)}}}return n(e),t.join("").trim()}function tS(e){let t=[];for(let n of e)if(Jt(n))for(let[o,i]of Object.entries(n)){if(qn(o)!=="tr")continue;let r=[];if(Ne(i)){for(let s of i)if(Jt(s)){for(let[c,a]of Object.entries(s))if(qn(c)==="tc"&&Ne(a)){let d=[],p=l=>{if(Ne(l)){for(let f of l)if(Jt(f))for(let[u,g]of Object.entries(f))if(qn(u)==="p"&&Ne(g)){let h=Ep(g);h&&d.push(h)}else Ne(g)&&p(g)}};p(a),r.push(d.join(" ").trim())}}}r.some(s=>s)&&t.push(r)}return Dm(t)}async function nS(e){let t=[],n=[];e.forEach(i=>{i.includes("embeddings")&&i.endsWith(".xlsx")&&n.push(i)}),n.sort();let o=0;for(let i of n){o+=1;let r=e.file(i);if(!r)continue;let s=await r.async("nodebuffer"),c=await eS(s);for(let a of c)a.rows.length>0&&t.push([`Embedded Sheet ${o}: ${a.name}`,Dm(a.rows)])}return t}async function Bm(e){let t;try{t=await Vm.loadAsync(Tm.readFileSync(e))}catch{throw new Error("source is not a valid docx zip file")}let n=t.file("word/document.xml");if(!n)throw new Error("docx missing word/document.xml");let o=await n.async("string"),i=Gm.parse(o),r=null,s=d=>{if(Ne(d)){for(let p of d)if(Jt(p))for(let[l,f]of Object.entries(p)){if(qn(l)==="body"&&Ne(f)){r=f;return}Ne(f)&&s(f)}}};s(i);let c=[];if(r===null){let d=p=>{if(Ne(p)){for(let l of p)if(Jt(l))for(let[f,u]of Object.entries(l))if(qn(f)==="p"&&Ne(u)){let g=Ep(u);g&&c.push(g)}else Ne(u)&&d(u)}};d(i)}else for(let d of r)if(Jt(d))for(let[p,l]of Object.entries(d)){if(p.startsWith("@_")||p===":@"||p==="#text"||!Ne(l))continue;let f=qn(p);if(f==="p"){let u=Ep(l);u&&c.push(u)}else if(f==="tbl"){let u=tS(l);u&&c.push(u)}}let a=await nS(t);for(let[d,p]of a)c.push(`
212
+ `)}function tr(e,t){let n=e[":@"];return Jt(n)?Bm(n[t]).trim():""}function wa(e,t){for(let[n,o]of Object.entries(e))if(qn(n)===t&&Ne(o))return o;return null}function _a(e){let t=[],n=o=>{if(Ne(o)){for(let i of o)if(Jt(i))for(let[r,s]of Object.entries(i))r==="#text"&&s!==null&&s!==void 0?t.push(Bm(s)):r!==":@"&&Ne(s)&&n(s)}};return n(e),t.join("")}function Ea(e){let t=Km.parse(e);if(!Ne(t))throw new Error("xlsx xml part has an unexpected shape");return t}function Mo(e,t){let n=[],o=i=>{let r=Ne(i)?i.filter(Jt):Jt(i)?[i]:[];for(let s of r)for(let[c,a]of Object.entries(s))qn(c)===t&&Ne(a)&&n.push(s),Ne(a)&&o(a)};return o(e),n}function q5(e){let t=/^[A-Z]+/i.exec(e.trim());if(!t)return null;let n=0;for(let o of t[0].toUpperCase())n=n*26+o.charCodeAt(0)-64;return n-1}function Z5(e,t){let o=(t.startsWith("/")?t.slice(1):`${e}/${t}`).split("/"),i=[];for(let r of o)!r||r==="."||(r===".."?i.pop():i.push(r));return i.join("/")}async function xa(e,t){let n=e.file(t);return n?n.async("string"):null}async function W5(e){let t=await xa(e,"xl/sharedStrings.xml");if(!t)return[];let n=Ea(t),o=[];for(let i of Mo(n,"si"))o.push(_a(wa(i,"si")??[]));return o}async function X5(e){let t=await xa(e,"xl/workbook.xml"),n=await xa(e,"xl/_rels/workbook.xml.rels");if(!t||!n)throw new Error("xlsx missing workbook metadata");let o=new Map;for(let r of Mo(Ea(n),"Relationship")){let s=tr(r,"@_Id"),c=tr(r,"@_Target");s&&c&&o.set(s,Z5("xl",c))}let i=[];for(let r of Mo(Ea(t),"sheet")){let s=tr(r,"@_name"),c=tr(r,"@_r:id"),a=o.get(c);s&&a&&i.push({name:s,path:a})}if(i.length===0)throw new Error("xlsx workbook contains no readable sheets");return i}function eS(e,t){let n=tr(e,"@_t");if(n==="inlineStr"){let s=Mo(e,"is")[0],c=s?wa(s,"is"):null;return c?_a(c).trim():""}let o=Mo(e,"v")[0],i=o?wa(o,"v"):null,r=i?_a(i).trim():"";if(!r&&n==="str"){let s=Mo(e,"is")[0],c=s?wa(s,"is"):null;return c?_a(c).trim():""}if(n==="s"){let s=Number.parseInt(r,10);return Number.isInteger(s)?(t[s]??"").trim():""}return n==="b"?r==="1"?"TRUE":r==="0"?"FALSE":r:r}async function tS(e){let t=await Gm.loadAsync(e),[n,o]=await Promise.all([W5(t),X5(t)]),i=[];for(let r of o){let s=await xa(t,r.path);if(!s)throw new Error(`xlsx missing worksheet part: ${r.path}`);let c=[];for(let a of Mo(Ea(s),"row")){let d=[];for(let p of Mo(a,"c")){let l=tr(p,"@_r"),f=l?q5(l):null,u=eS(p,n),m=f??d.length;for(;d.length<m;)d.push("");d[m]=u.trim()}d.some(p=>p)&&c.push(d)}i.push({name:r.name,rows:c})}return i}var Km=new Y5({ignoreAttributes:!1,attributeNamePrefix:"@_",preserveOrder:!0,trimValues:!1,textNodeName:"#text"});function qn(e){let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function Sp(e){let t=[];function n(o){if(Ne(o)){for(let i of o)if(Jt(i))for(let[r,s]of Object.entries(i)){if(r===":@"||r==="#text"&&typeof s=="string")continue;let c=qn(r);if(c==="t"){if(Ne(s)){for(let a of s)if(Jt(a)){let d=a["#text"];typeof d=="string"&&t.push(d)}}}else c==="tab"?t.push(" "):c==="br"||c==="cr"?t.push(`
213
+ `):Ne(s)&&n(s)}}}return n(e),t.join("").trim()}function nS(e){let t=[];for(let n of e)if(Jt(n))for(let[o,i]of Object.entries(n)){if(qn(o)!=="tr")continue;let r=[];if(Ne(i)){for(let s of i)if(Jt(s)){for(let[c,a]of Object.entries(s))if(qn(c)==="tc"&&Ne(a)){let d=[],p=l=>{if(Ne(l)){for(let f of l)if(Jt(f))for(let[u,m]of Object.entries(f))if(qn(u)==="p"&&Ne(m)){let h=Sp(m);h&&d.push(h)}else Ne(m)&&p(m)}};p(a),r.push(d.join(" ").trim())}}}r.some(s=>s)&&t.push(r)}return Jm(t)}async function oS(e){let t=[],n=[];e.forEach(i=>{i.includes("embeddings")&&i.endsWith(".xlsx")&&n.push(i)}),n.sort();let o=0;for(let i of n){o+=1;let r=e.file(i);if(!r)continue;let s=await r.async("nodebuffer"),c=await tS(s);for(let a of c)a.rows.length>0&&t.push([`Embedded Sheet ${o}: ${a.name}`,Jm(a.rows)])}return t}async function jm(e){let t;try{t=await Gm.loadAsync(Dm.readFileSync(e))}catch{throw new Error("source is not a valid docx zip file")}let n=t.file("word/document.xml");if(!n)throw new Error("docx missing word/document.xml");let o=await n.async("string"),i=Km.parse(o),r=null,s=d=>{if(Ne(d)){for(let p of d)if(Jt(p))for(let[l,f]of Object.entries(p)){if(qn(l)==="body"&&Ne(f)){r=f;return}Ne(f)&&s(f)}}};s(i);let c=[];if(r===null){let d=p=>{if(Ne(p)){for(let l of p)if(Jt(l))for(let[f,u]of Object.entries(l))if(qn(f)==="p"&&Ne(u)){let m=Sp(u);m&&c.push(m)}else Ne(u)&&d(u)}};d(i)}else for(let d of r)if(Jt(d))for(let[p,l]of Object.entries(d)){if(p.startsWith("@_")||p===":@"||p==="#text"||!Ne(l))continue;let f=qn(p);if(f==="p"){let u=Sp(l);u&&c.push(u)}else if(f==="tbl"){let u=nS(l);u&&c.push(u)}}let a=await oS(t);for(let[d,p]of a)c.push(`
214
214
  ## ${d}
215
215
  `),c.push(p);return[c.join(`
216
216
 
217
- `),a.length>0]}var xp=class extends Error{};function Jm(e){return e.replace(/^/,"").replace(/\r\n?/g,`
218
- `)}function oS(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{throw new xp("source is not valid UTF-8")}}async function Ea(e,t){if(t===".docx"){let[n]=await Bm(e);return Jm(n)}return Jm(oS(jm.readFileSync(e)))}import{z as xa}from"zod";function Sp(e,t){let n=/^text:[^:]+:\d+:(\d+):(\d+):\d+$/.exec(e);if(!n)throw new Error(`Invalid text ingest identity: ${e}`);let o=Number(n[1]),i=Number(n[2]);if(o>=i)throw new Error(`Empty text ingest window: ${e}`);return{start_line:t+o+1,end_line:t+i}}function Ip(e,t,n){return{kind:"text",document_id:t,ranges:[Sp(e,n)]}}function Km(e,t,n){for(let o of e.episodes)for(let i of o.scenes)for(let r of i.actions){let s=xa.object({scriptctl:xa.record(xa.string(),xa.json()).optional()}).parse(r.extend??{});r.extend={...r.extend,scriptctl:{...s.scriptctl,source:Ip(r.identity_key,t,n)}}}}var iS=Ye.object({source:Ye.object({kind:Ye.literal("text"),sha256:Ye.string().length(64),path:Ye.string()})}),rS=Ye.object({version:Ye.literal(3),episode:Ye.record(Ye.string(),Ye.string()),action:Ye.record(Ye.string(),Ye.string())});function jt(e){throw new S(e,{exitCode:k,errorCode:"REVIEW_TEXT_SOURCE_INVALID",hint:"Pass -s to the text ingest workspace, or its original txt/md/docx with the ingest workspace beside script.json. Keep pass1/source.txt, body_start.json and v4_identity_map.json."})}async function zm(e,t,n){let o=Zn.statSync(e).isDirectory(),i=o?Kt.resolve(e):Kt.dirname(Kt.resolve(t)),r=y=>{let _=Kt.join(i,y);return Zn.existsSync(_)||jt(`Text ingest artifact missing: ${_}`),JSON.parse(Zn.readFileSync(_,"utf8"))},s=iS.parse(r("manifest.json")),c=Kt.join(i,"pass1/source.txt");Zn.existsSync(c)||jt("Text review requires the normalized original source snapshot.");let a=Zn.readFileSync(c,"utf8");if(Ee(a)!==s.source.sha256&&jt("The original text snapshot has changed since ingest."),!o){let y=await Ea(e,Kt.extname(e).toLowerCase());Ee(y)!==s.source.sha256&&jt("The supplied text does not match this ingest source.")}let d=a.split(`
219
- `),{line:p}=Ye.object({line:Ye.number().int().nonnegative()}).parse(r("pass1/body_start.json"));p>=d.length&&jt("Text body start is outside the source snapshot.");let l=rS.parse(r("v4_identity_map.json")),f=Oo(JSON.parse(Zn.readFileSync(t,"utf8")));f.version!==4&&jt("Text source review requires the ingested Script v4.");let u=ga(s.source.sha256),g=Object.entries(l.episode).map(([y,_])=>({id:_,...Sp(y,p)})).sort((y,_)=>y.start_line-_.start_line);g.some(y=>y.end_line>d.length)&&jt("An episode's ingest window is outside the original source.");let h=f.episodes.filter(y=>!n?.length||n.includes(y.no)).map(y=>{let _=g.filter(A=>A.id===y.id);_.length!==1&&jt(`Episode ${y.no} has no unambiguous text source identity.`);let x=_[0],E=g[g.indexOf(x)+1];return{episode:y.no,start_line:g.indexOf(x)===0?p+1:x.start_line,end_line:E?E.end_line:d.length}});h.length||jt("No selected episodes exist in this script.");let m=new Map,w=new Map(Object.entries(l.action).map(([y,_])=>[_,Ip(y,u,p)]));for(let y of bn(f)){if(!h.some(E=>E.episode===y.scene.ep.no))continue;let _=Ye.object({scriptctl:Ye.object({source:_p.optional()}).optional()}).safeParse(y.raw.extend??{});_.success||jt(`Invalid text source metadata on ${y.anchor}.`);let x=_.data.scriptctl?.source??w.get(y.anchor);x&&(x.document_id!==u&&jt(`Action ${y.anchor} belongs to a different text document.`),x.ranges.some(E=>E.start_line>E.end_line||E.end_line>d.length)&&jt(`Invalid source lines on ${y.anchor}.`),m.set(y.anchor,x))}return{document_id:u,title:Kt.basename(s.source.path),path:c,lines:d,episodes:h,references:m}}var Hm="review-agent";function Ap(e,t){let n=t||Hm,o=e.models[n];if(!o)throw new S(`LLM profile "${n}" is not defined.`,{exitCode:k,errorCode:"REVIEW_PROFILE_UNKNOWN",hint:`Define it under models, or pick one of: ${Object.keys(e.models).join(", ")}.`,data:{expected:["a defined models entry"],actual:[n]}});let i=e.providers[o.provider];if(!i)throw new S(`Provider "${o.provider}" is not defined.`,{exitCode:k,errorCode:"REVIEW_PROVIDER_UNKNOWN",hint:`Available providers: ${Object.keys(e.providers).join(", ")}.`,data:{expected:["a defined providers entry"],actual:[o.provider]}});let r=(process.env[i.apiKeyEnv]??"").trim();if(!r&&i.protocol!=="google-vertex")throw new S(`${i.apiKeyEnv} is not set.`,{exitCode:k,errorCode:"REVIEW_API_KEY_MISSING",hint:`Export ${i.apiKeyEnv} for provider ${o.provider}.`,data:{expected:[i.apiKeyEnv],actual:["<empty>"]}});return{provider:o.provider,model:o.model,baseUrl:i.baseUrl,apiKey:r,maxAttempts:i.maxAttempts}}async function nn(){let e=Sa.dirname(sS(import.meta.url)),t=Sa.join(e,"review-agent.js"),n=Zr.existsSync(t)?aS(t).href:"@lingjingai/review-agent";try{return await import(n)}catch(o){throw new S("The review agent is not installed.",{exitCode:ee,errorCode:"REVIEW_AGENT_MISSING",hint:"Reinstall scriptctl without --omit=optional, or install @mastra/core and @ai-sdk/google.",data:{expected:["@lingjingai/review-agent"],actual:[String(o.message).slice(0,200)]}})}}function Wr(e){let t=e.trim();if(!t)return;let n=t.split(",").map(o=>Number(o.trim()));if(n.some(o=>!Number.isInteger(o)||o<1))throw new S("--episodes takes a comma-separated list of 1-based episode numbers.",{exitCode:k,errorCode:"REVIEW_EPISODES_INVALID",hint:"For example: --episodes 1,2,5",data:{expected:["1-based episode numbers"],actual:[t]}});return n}function st(e,t,n){let o=e[t];if(o===void 0)return n;let i=Number(o);if(!Number.isFinite(i)||i<=0)throw new S(`--${t.replace(/_/g,"-")} must be a positive number.`,{exitCode:k,errorCode:"REVIEW_OPTION_INVALID",hint:`Pass a positive number for --${t.replace(/_/g,"-")}.`,data:{expected:["a positive number"],actual:[String(o)]}});return i}async function Fm(e){let t=Io(v(e.llm_config).trim()||void 0),n=v(e.model).trim(),o=v(e.source_path).trim(),i=(Array.isArray(e.video)?e.video:[]).map(f=>f.trim()).filter(f=>f.length>0),r=Cm(o,i.length>0),c=Ap(t,n||(r==="comic"?"review-comic":r==="text"?"review-text":Hm));if(e.check){let f=await nn(),g=typeof{script:f.reviewPlainScript,text:f.reviewTextScript,comic:f.reviewComicScript,video:f.reviewVideoScript}[r]=="function";return[{text:g?`ready: ${c.provider}/${c.model}`:"the review agent bundle is present but exports no reviewScript",data:{ready:g,review_kind:r,provider:c.provider,model:c.model,llm_config:t.sourcePath??"builtin"}},g?B:ee]}let a=ge(e);if(!Zr.existsSync(a))throw new S("Local script file not found.",{exitCode:k,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[a]}});let d=i.filter(f=>!Zr.existsSync(f));if(d.length>0)throw new S("A --video path does not exist.",{exitCode:k,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass --video once per episode, in episode order.",data:{expected:["existing video files"],actual:d.slice(0,5)}});if(o&&!Zr.existsSync(o))throw new S("Review source not found.",{exitCode:k,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass an existing source or ingest workspace, or omit -s for script-only review.",data:{expected:["existing source or ingest workspace"],actual:[o]}});let p=await nn(),l=f=>process.stdout.write(JSON.stringify(f)+`
220
- `);try{let f={scriptPath:a,...Wr(v(e.episodes))?{episodes:Wr(v(e.episodes))}:{},concurrency:st(e,"concurrency",5),converge:e.converge!==!1,convergeOnly:e.converge_only===!0,apiKey:c.apiKey,maxAttempts:c.maxAttempts,model:c.model,...c.baseUrl?{baseUrl:c.baseUrl}:{},maxSteps:st(e,"max_steps",300),episodeTimeoutMs:st(e,"episode_timeout_ms",48e4),onEvent:l};if(r==="comic"){let u=await Lm(o,a,f.converge?void 0:f.episodes);await p.reviewComicScript({...f,comic:u})}else if(r==="text"){let u=await zm(o,a,f.converge?void 0:f.episodes);await p.reviewTextScript({...f,text:u})}else r==="video"?await p.reviewVideoScript({...f,source:o,videos:i,mediaModel:c.model,mediaBudget:st(e,"media_budget",1)}):await p.reviewPlainScript(f)}catch(f){throw f instanceof S?f:new S("Review failed.",{exitCode:ee,errorCode:"REVIEW_FAILED",hint:r==="video"?"Read the error details, NDJSON asr-compared/episode reports and .review/asr/ evidence before retrying.":`Read the error details and episode reports${r==="script"?"":` in .review/${r}/`} before retrying.`,data:{expected:["a completed review run"],actual:[f instanceof Error?f.message:String(f)]}})}return[{text:"",data:{}},B]}import*as pi from"node:fs";import*as ce from"node:fs";import*as we from"node:path";import{createHash as cS}from"node:crypto";var Xr=["analyze","direction","plan","write","review"],dS={analyze:"reskin",direction:"reskin-claude",plan:"reskin-claude",write:"reskin",review:"reskin-claude"},pS={"claude-opus-5-5":{input:4,cached_input:.2,output:20}};function kp(e,t){let n=we.join(e,t);return{root:n,source:we.join(n,"0_input","script.json"),analysis:we.join(n,"1_src","\u62C6\u89E3.json"),direction:we.join(n,"2_new","\u6362\u58F3\u65B9\u5411.json"),brief:we.join(n,"2_new","\u6362\u58F3\u65B9\u5411.md"),plan:we.join(n,"2_new","\u6362\u58F3\u65B9\u6848.json"),script:we.join(n,"4_output","script.json"),prereview:we.join(n,"4_output","script.prereview.json"),log:o=>we.join(n,"logs",`${o}.ndjson`),status:we.join(n,"status.json")}}function Aa(e,t){ce.mkdirSync(we.dirname(e),{recursive:!0}),ce.writeFileSync(`${e}.tmp`,JSON.stringify(t,null,2)+`
221
- `),ce.renameSync(`${e}.tmp`,e)}function Ia(e){return ce.existsSync(e)?JSON.parse(ce.readFileSync(e,"utf8")):null}function lS(e,t){let n=Object.keys(e).filter(o=>t.startsWith(o)).sort((o,i)=>i.length-o.length)[0];return n?e[n]:null}function Qm(e,t){let n=0,o=[];for(let[i,r]of Object.entries(e)){let s=lS(t,i);if(!s){o.push(i);continue}n+=((r.input-r.cached_input)*s.input+r.cached_input*s.cached_input+r.output*s.output)/1e6}return{usd:n,unpriced:o}}function uS(e,t){for(let n of t){let o=e[n.model]??={calls:0,input:0,cached_input:0,output:0};o.calls+=1,o.input+=n.input_tokens,o.cached_input+=n.cached_input_tokens,o.output+=n.output_tokens}}var fS=new Set(["unit-done","episode","global","direction-done"]);function mS(e,t){return cS("sha256").update(JSON.stringify([ce.readFileSync(e,"utf8"),t.notes??"",t.custom??"",t.market??"",t.rating??"",t.avoid??[]])).digest("hex")}function gS(e,t,n){let o=n.market?.trim();return[`# ${e.title}`,`\u76EE\u6807\u5E02\u573A\uFF1A${o||"\u540C\u539F\u5267"}`,o&&n.language?.trim()?`\u53F0\u8BCD\u8BED\u8A00\uFF1A${n.language.trim()}`:"",`\u5C3A\u5EA6\uFF1A${n.rating?.trim()||"\u540C\u539F\u5267"}`,`\u6362\u58F3\uFF1A${e.shell}`,`\u6362\u6CD5\uFF1A${e.approach}`,e.keeps?`\u6CBF\u7528\u539F\u5267\uFF1A${e.keeps}`:"",e.changes?`\u5FC5\u987B\u6539\u52A8\uFF1A${e.changes}`:"",e.risks?`\u98CE\u9669\uFF1A${e.risks}`:"",t.verdict&&t.reason?`\u65B9\u5411\u5224\u65AD\uFF08${t.verdict}\uFF09\uFF1A${t.reason}`:"",n.notes?.trim()?`\u7528\u6237\u8981\u6C42\uFF1A${n.notes.trim()}`:""].filter(Boolean).join(`
217
+ `),a.length>0]}var Ip=class extends Error{};function zm(e){return e.replace(/^/,"").replace(/\r\n?/g,`
218
+ `)}function iS(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{throw new Ip("source is not valid UTF-8")}}async function Sa(e,t){if(t===".docx"){let[n]=await jm(e);return zm(n)}return zm(iS(Hm.readFileSync(e)))}import{z as Ia}from"zod";function Ap(e,t){let n=/^text:[^:]+:\d+:(\d+):(\d+):\d+$/.exec(e);if(!n)throw new Error(`Invalid text ingest identity: ${e}`);let o=Number(n[1]),i=Number(n[2]);if(o>=i)throw new Error(`Empty text ingest window: ${e}`);return{start_line:t+o+1,end_line:t+i}}function kp(e,t,n){return{kind:"text",document_id:t,ranges:[Ap(e,n)]}}function Fm(e,t,n){for(let o of e.episodes)for(let i of o.scenes)for(let r of i.actions){let s=Ia.object({scriptctl:Ia.record(Ia.string(),Ia.json()).optional()}).parse(r.extend??{});r.extend={...r.extend,scriptctl:{...s.scriptctl,source:kp(r.identity_key,t,n)}}}}var rS=Ye.object({source:Ye.object({kind:Ye.literal("text"),sha256:Ye.string().length(64),path:Ye.string()})}),sS=Ye.object({version:Ye.literal(3),episode:Ye.record(Ye.string(),Ye.string()),action:Ye.record(Ye.string(),Ye.string())});function Kt(e){throw new x(e,{exitCode:k,errorCode:"REVIEW_TEXT_SOURCE_INVALID",hint:"Pass -s to the text ingest workspace, or its original txt/md/docx with the ingest workspace beside script.json. Keep pass1/source.txt, body_start.json and v4_identity_map.json."})}async function Qm(e,t,n){let o=Zn.statSync(e).isDirectory(),i=o?jt.resolve(e):jt.dirname(jt.resolve(t)),r=y=>{let _=jt.join(i,y);return Zn.existsSync(_)||Kt(`Text ingest artifact missing: ${_}`),JSON.parse(Zn.readFileSync(_,"utf8"))},s=rS.parse(r("manifest.json")),c=jt.join(i,"pass1/source.txt");Zn.existsSync(c)||Kt("Text review requires the normalized original source snapshot.");let a=Zn.readFileSync(c,"utf8");if(_e(a)!==s.source.sha256&&Kt("The original text snapshot has changed since ingest."),!o){let y=await Sa(e,jt.extname(e).toLowerCase());_e(y)!==s.source.sha256&&Kt("The supplied text does not match this ingest source.")}let d=a.split(`
219
+ `),{line:p}=Ye.object({line:Ye.number().int().nonnegative()}).parse(r("pass1/body_start.json"));p>=d.length&&Kt("Text body start is outside the source snapshot.");let l=sS.parse(r("v4_identity_map.json")),f=vo(JSON.parse(Zn.readFileSync(t,"utf8")));f.version!==4&&Kt("Text source review requires the ingested Script v4.");let u=ya(s.source.sha256),m=Object.entries(l.episode).map(([y,_])=>({id:_,...Ap(y,p)})).sort((y,_)=>y.start_line-_.start_line);m.some(y=>y.end_line>d.length)&&Kt("An episode's ingest window is outside the original source.");let h=f.episodes.filter(y=>!n?.length||n.includes(y.no)).map(y=>{let _=m.filter(A=>A.id===y.id);_.length!==1&&Kt(`Episode ${y.no} has no unambiguous text source identity.`);let S=_[0],E=m[m.indexOf(S)+1];return{episode:y.no,start_line:m.indexOf(S)===0?p+1:S.start_line,end_line:E?E.end_line:d.length}});h.length||Kt("No selected episodes exist in this script.");let g=new Map,w=new Map(Object.entries(l.action).map(([y,_])=>[_,kp(y,u,p)]));for(let y of bn(f)){if(!h.some(E=>E.episode===y.scene.ep.no))continue;let _=Ye.object({scriptctl:Ye.object({source:xp.optional()}).optional()}).safeParse(y.raw.extend??{});_.success||Kt(`Invalid text source metadata on ${y.anchor}.`);let S=_.data.scriptctl?.source??w.get(y.anchor);S&&(S.document_id!==u&&Kt(`Action ${y.anchor} belongs to a different text document.`),S.ranges.some(E=>E.start_line>E.end_line||E.end_line>d.length)&&Kt(`Invalid source lines on ${y.anchor}.`),g.set(y.anchor,S))}return{document_id:u,title:jt.basename(s.source.path),path:c,lines:d,episodes:h,references:g}}var Ym="review-agent";function bp(e,t){let n=t||Ym,o=e.models[n];if(!o)throw new x(`LLM profile "${n}" is not defined.`,{exitCode:k,errorCode:"REVIEW_PROFILE_UNKNOWN",hint:`Define it under models, or pick one of: ${Object.keys(e.models).join(", ")}.`,data:{expected:["a defined models entry"],actual:[n]}});let i=e.providers[o.provider];if(!i)throw new x(`Provider "${o.provider}" is not defined.`,{exitCode:k,errorCode:"REVIEW_PROVIDER_UNKNOWN",hint:`Available providers: ${Object.keys(e.providers).join(", ")}.`,data:{expected:["a defined providers entry"],actual:[o.provider]}});let r=(process.env[i.apiKeyEnv]??"").trim();if(!r&&i.protocol!=="google-vertex")throw new x(`${i.apiKeyEnv} is not set.`,{exitCode:k,errorCode:"REVIEW_API_KEY_MISSING",hint:`Export ${i.apiKeyEnv} for provider ${o.provider}.`,data:{expected:[i.apiKeyEnv],actual:["<empty>"]}});return{provider:o.provider,model:o.model,baseUrl:i.baseUrl,apiKey:r,maxAttempts:i.maxAttempts}}async function nn(){let e=Aa.dirname(aS(import.meta.url)),t=Aa.join(e,"review-agent.js"),n=pi.existsSync(t)?cS(t).href:"@lingjingai/review-agent";try{return await import(n)}catch(o){throw new x("The review agent is not installed.",{exitCode:X,errorCode:"REVIEW_AGENT_MISSING",hint:"Reinstall scriptctl without --omit=optional, or install @mastra/core and @ai-sdk/google.",data:{expected:["@lingjingai/review-agent"],actual:[String(o.message).slice(0,200)]}})}}function Xr(e){let t=e.trim();if(!t)return;let n=t.split(",").map(o=>Number(o.trim()));if(n.some(o=>!Number.isInteger(o)||o<1))throw new x("--episodes takes a comma-separated list of 1-based episode numbers.",{exitCode:k,errorCode:"REVIEW_EPISODES_INVALID",hint:"For example: --episodes 1,2,5",data:{expected:["1-based episode numbers"],actual:[t]}});return n}function st(e,t,n){let o=e[t];if(o===void 0)return n;let i=Number(o);if(!Number.isFinite(i)||i<=0)throw new x(`--${t.replace(/_/g,"-")} must be a positive number.`,{exitCode:k,errorCode:"REVIEW_OPTION_INVALID",hint:`Pass a positive number for --${t.replace(/_/g,"-")}.`,data:{expected:["a positive number"],actual:[String(o)]}});return i}async function qm(e){let t=Ao(O(e.llm_config).trim()||void 0),n=O(e.model).trim(),o=O(e.source_path).trim(),i=(Array.isArray(e.video)?e.video:[]).map(f=>f.trim()).filter(f=>f.length>0),r=$m(o,i.length>0),c=bp(t,n||(r==="comic"?"review-comic":r==="text"?"review-text":Ym));if(e.check){let f=await nn(),m=typeof{script:f.reviewPlainScript,text:f.reviewTextScript,comic:f.reviewComicScript,video:f.reviewVideoScript}[r]=="function";return[{text:m?`ready: ${c.provider}/${c.model}`:"the review agent bundle is present but exports no reviewScript",data:{ready:m,review_kind:r,provider:c.provider,model:c.model,llm_config:t.sourcePath??"builtin"}},m?G:X]}let a=me(e);if(!pi.existsSync(a))throw new x("Local script file not found.",{exitCode:k,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[a]}});let d=i.filter(f=>!pi.existsSync(f));if(d.length>0)throw new x("A --video path does not exist.",{exitCode:k,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass --video once per episode, in episode order.",data:{expected:["existing video files"],actual:d.slice(0,5)}});if(o&&!pi.existsSync(o))throw new x("Review source not found.",{exitCode:k,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass an existing source or ingest workspace, or omit -s for script-only review.",data:{expected:["existing source or ingest workspace"],actual:[o]}});let p=await nn(),l=f=>process.stdout.write(JSON.stringify(f)+`
220
+ `);try{let f={scriptPath:a,...Xr(O(e.episodes))?{episodes:Xr(O(e.episodes))}:{},concurrency:st(e,"concurrency",5),converge:e.converge!==!1,convergeOnly:e.converge_only===!0,resumeUnits:(Array.isArray(e.resume_log)?e.resume_log:[]).flatMap(u=>pi.readFileSync(u,"utf8").split(`
221
+ `).flatMap(m=>{let h;try{h=JSON.parse(m)}catch{return[]}return h&&(h.type==="episode"||h.type==="global")?[h]:[]})),apiKey:c.apiKey,maxAttempts:c.maxAttempts,model:c.model,...c.baseUrl?{baseUrl:c.baseUrl}:{},maxSteps:st(e,"max_steps",300),episodeTimeoutMs:st(e,"episode_timeout_ms",48e4),onEvent:l};if(r==="comic"){let u=await Cm(o,a,f.converge?void 0:f.episodes);await p.reviewComicScript({...f,comic:u})}else if(r==="text"){let u=await Qm(o,a,f.converge?void 0:f.episodes);await p.reviewTextScript({...f,text:u})}else r==="video"?await p.reviewVideoScript({...f,source:o,videos:i,mediaModel:c.model,mediaBudget:st(e,"media_budget",1)}):await p.reviewPlainScript(f)}catch(f){throw f instanceof x?f:new x("Review failed.",{exitCode:X,errorCode:"REVIEW_FAILED",hint:r==="video"?"Read the error details, NDJSON asr-compared/episode reports and .review/asr/ evidence before retrying.":`Read the error details and episode reports${r==="script"?"":` in .review/${r}/`} before retrying.`,data:{expected:["a completed review run"],actual:[f instanceof Error?f.message:String(f)]}})}return[{text:"",data:{}},G]}import*as li from"node:fs";import*as ge from"node:fs";import*as Ee from"node:path";import{createHash as dS}from"node:crypto";var es=["analyze","direction","plan","write","review"],pS={analyze:"reskin",direction:"reskin-claude",plan:"reskin-claude",write:"reskin",review:"reskin-claude"},lS={"claude-opus-5-5":{input:4,cached_input:.2,output:20}};function Op(e,t){let n=Ee.join(e,t);return{root:n,source:Ee.join(n,"0_input","script.json"),analysis:Ee.join(n,"1_src","\u62C6\u89E3.json"),direction:Ee.join(n,"2_new","\u6362\u58F3\u65B9\u5411.json"),brief:Ee.join(n,"2_new","\u6362\u58F3\u65B9\u5411.md"),plan:Ee.join(n,"2_new","\u6362\u58F3\u65B9\u6848.json"),script:Ee.join(n,"4_output","script.json"),log:o=>Ee.join(n,"logs",`${o}.ndjson`),status:Ee.join(n,"status.json")}}function ba(e,t){ge.mkdirSync(Ee.dirname(e),{recursive:!0}),ge.writeFileSync(`${e}.tmp`,JSON.stringify(t,null,2)+`
222
+ `),ge.renameSync(`${e}.tmp`,e)}function ka(e){return ge.existsSync(e)?JSON.parse(ge.readFileSync(e,"utf8")):null}function uS(e,t){let n=Object.keys(e).filter(o=>t.startsWith(o)).sort((o,i)=>i.length-o.length)[0];return n?e[n]:null}function Zm(e,t){let n=0,o=[];for(let[i,r]of Object.entries(e)){let s=uS(t,i);if(!s){o.push(i);continue}n+=((r.input-r.cached_input)*s.input+r.cached_input*s.cached_input+r.output*s.output)/1e6}return{usd:n,unpriced:o}}function fS(e,t){for(let n of t){let o=e[n.model]??={calls:0,input:0,cached_input:0,output:0};o.calls+=1,o.input+=n.input_tokens,o.cached_input+=n.cached_input_tokens,o.output+=n.output_tokens}}var mS=new Set(["unit-done","episode","global","direction-done"]);function gS(e,t){return dS("sha256").update(JSON.stringify([ge.readFileSync(e,"utf8"),t.notes??"",t.custom??"",t.market??"",t.rating??"",t.avoid??[]])).digest("hex")}function hS(e,t,n){let o=n.market?.trim();return[`# ${e.title}`,`\u76EE\u6807\u5E02\u573A\uFF1A${o||"\u540C\u539F\u5267"}`,o&&n.language?.trim()?`\u53F0\u8BCD\u8BED\u8A00\uFF1A${n.language.trim()}`:"",`\u5C3A\u5EA6\uFF1A${n.rating?.trim()||"\u540C\u539F\u5267"}`,`\u6362\u58F3\uFF1A${e.shell}`,`\u6362\u6CD5\uFF1A${e.approach}`,e.keeps?`\u6CBF\u7528\u539F\u5267\uFF1A${e.keeps}`:"",e.changes?`\u5FC5\u987B\u6539\u52A8\uFF1A${e.changes}`:"",e.risks?`\u98CE\u9669\uFF1A${e.risks}`:"",t.verdict&&t.reason?`\u65B9\u5411\u5224\u65AD\uFF08${t.verdict}\uFF09\uFF1A${t.reason}`:"",n.notes?.trim()?`\u7528\u6237\u8981\u6C42\uFF1A${n.notes.trim()}`:""].filter(Boolean).join(`
222
223
 
223
224
  `)+`
224
- `}function qm(e){let t=JSON.parse(ce.readFileSync(e,"utf8")),n=Array.isArray(t)?{dramas:t}:t;if(!Array.isArray(n.dramas)||!n.dramas.length)throw new Error("\u6E05\u5355\u91CC\u6CA1\u6709 dramas\u3002");let o=we.dirname(we.resolve(e)),i=new Set;return{dramas:n.dramas.map((s,c)=>{if(!s.source?.trim())throw new Error(`\u7B2C ${c+1} \u90E8\u5267\u6CA1\u6709 source\u3002`);let a=we.resolve(o,s.source.trim()),d=(s.id?.trim()||we.basename(we.dirname(a))).replace(/[\\/]/g,"-");if(i.has(d))throw new Error(`\u5267\u7684 id \u91CD\u590D\uFF1A${d}\uFF1B\u7ED9\u6BCF\u90E8\u5267\u5199\u4E0D\u540C\u7684 id\u3002`);if(i.add(d),s.pick!==void 0&&s.pick!=="recommended"&&!(Number.isInteger(s.pick)&&Number(s.pick)>=1))throw new Error(`${d} \u7684 pick \u5199\u5019\u9009\u5E8F\u53F7\uFF08\u4ECE 1 \u5F00\u59CB\uFF09\u6216 recommended\u3002`);return{...s,id:d,source:a}}),models:{...dS,...n.models??{}},prices:{...pS,...n.prices??{}},...n.pick!==void 0?{pick:n.pick}:{}}}async function hS(e,t,n){let o=[...e];await Promise.all(Array.from({length:Math.max(1,Math.min(t,o.length))},async()=>{for(let i=o.shift();i!==void 0;i=o.shift())await n(i)}))}var Rn=class extends Error{constructor(n,o){super(o);this.state=n}state};async function Zm(e,t,n){let o=n.now??Date.now,i=new Map,r=()=>wS(n.outputDir,e,[...i.values()]);async function s(c){let a=kp(n.outputDir,c.id),d={...Ia(a.status)??{id:c.id,steps:{}},state:"running",reason:"",step:null,updated_at:""};i.set(c.id,d);let p=()=>{d.updated_at=new Date(o()).toISOString(),Aa(a.status,d),r()},l=O=>n.onEvent?.({drama:c.id,...O});if(!ce.existsSync(a.source)){if(!ce.existsSync(c.source))throw new Rn("failed",`\u539F\u5267\u5267\u672C\u4E0D\u5B58\u5728\uFF1A${c.source}`);ce.mkdirSync(we.dirname(a.source),{recursive:!0}),ce.copyFileSync(c.source,a.source)}async function f(O,N){let U=d.steps[O]??{state:"running",runs:0,wall_ms:0,usage:{}};U.state="running",d.steps[O]=U,d.step=O,p(),l({type:"step-started",step:O}),ce.mkdirSync(we.dirname(a.log(O)),{recursive:!0});let M=F=>{ce.appendFileSync(a.log(O),JSON.stringify(F)+`
225
- `),fS.has(String(F.type))&&Array.isArray(F.usage)&&uS(U.usage,F.usage)},V=null;for(let F=1;F<=n.attempts;F+=1){let Re=o();U.runs+=1;try{V=await N(M)}catch(X){V=X instanceof Error?X.message:String(X)}if(U.wall_ms+=o()-Re,p(),!V)break}if(U.state=V?"failed":"completed",V?U.error=V:delete U.error,p(),l({type:"step-done",step:O,state:U.state,error:V}),V)throw new Rn("failed",`${O}\uFF1A${V}`)}let u=O=>d.steps[O]?.state==="completed",g=O=>n.until===O;if((!u("analyze")||!ce.existsSync(a.analysis))&&await f("analyze",async O=>{let N=await t.analyzeReskinSource({...n.config(e.models.analyze),sourcePath:a.source,outputPath:a.analysis,onEvent:O});return N.state==="completed"?null:N.error||"\u62C6\u89E3\u672A\u5B8C\u6210"}),g("analyze"))return;let h=Ia(a.analysis)?.profile?.suitability;if(typeof h?.score=="number"&&h.score<3&&c.pick===void 0)throw d.step="analyze",new Rn("stopped",`\u8FD9\u90E8\u539F\u5267\u4E0D\u592A\u9002\u5408\u6362\u58F3\uFF08\u62C6\u89E3\u9002\u5408\u5EA6 ${h.score}/5\uFF09${h.reason?`\uFF1A${h.reason}`:""}\u3002\u770B\u8FC7\u540E\u4ECD\u8981\u505A\uFF0C\u7ED9\u8FD9\u90E8\u5267\u5199 pick \u518D\u8FD0\u884C`);let m=mS(a.analysis,c),w=Ia(a.direction);(w?.key!==m||w.result.state!=="completed")&&(w=null,await f("direction",async O=>{let N=await t.proposeReskinDirections({...n.config(e.models.direction),sourcePath:a.source,analysisPath:a.analysis,notes:c.notes??"",custom:c.custom??"",market:c.market??"",rating:c.rating??"",avoid:c.avoid??[],onEvent:O});return N.type!=="direction-done"||N.state!=="completed"?N.type==="direction-done"&&N.error||"\u65B9\u5411\u672A\u5B8C\u6210":(w={key:m,result:N},Aa(a.direction,w),null)}));let y=w.result,_=!!c.custom?.trim(),x=_?1:c.pick??e.pick,E=x==="recommended"?y.recommended:x??null;if(d.direction={mode:_?"custom":"candidates",suitability:y.suitability,verdict:y.verdict,verdict_reason:y.reason,candidates:y.candidates.map(({title:O,shell:N,feasibility:U,distinctiveness:M})=>({title:O,shell:N,feasibility:U,distinctiveness:M})),recommended:y.recommended,recommendation:y.recommendation,picked:E},d.step="direction",y.verdict==="\u4E0D\u53EF\u884C")throw new Rn("stopped",`\u6307\u5B9A\u7684\u65B9\u5411\u4E0D\u53EF\u884C\uFF1A${y.reason}`);if(y.suitability&&y.suitability.score<3&&c.pick===void 0)throw new Rn("stopped",`\u8FD9\u90E8\u539F\u5267\u4E0D\u592A\u9002\u5408\u6362\u58F3\uFF08\u9002\u5408\u5EA6 ${y.suitability.score}/5\uFF09\uFF1A${y.suitability.reason}\u3002\u770B\u8FC7\u540E\u4ECD\u8981\u505A\uFF0C\u7ED9\u8FD9\u90E8\u5267\u5199 pick \u518D\u8FD0\u884C`);if(E===null)throw new Rn("stopped",`\u5F85\u4EBA\u5DE5\u9009\u62E9\u65B9\u5411\uFF1A\u5728\u6E05\u5355\u91CC\u7ED9\u8FD9\u90E8\u5267\u5199 pick\uFF081\u2013${y.candidates.length}\uFF0C\u63A8\u8350 ${y.recommended}\uFF09\u540E\u518D\u8FD0\u884C`);let A=y.candidates[E-1];if(!A)throw new Rn("stopped",`pick ${E} \u8D85\u51FA\u5019\u9009\u8303\u56F4\uFF08\u5171 ${y.candidates.length} \u4E2A\uFF09`);let b=gS(A,y,c),C=ce.existsSync(a.brief)?ce.readFileSync(a.brief,"utf8"):null;if(C!==b){let O=we.dirname(a.script);C!==null&&ce.existsSync(O)&&ce.renameSync(O,`${O}.${new Date(o()).toISOString().replace(/[:.]/g,"-")}`);for(let N of["plan","write","review"])delete d.steps[N];delete d.review,ce.mkdirSync(we.dirname(a.brief),{recursive:!0}),ce.writeFileSync(a.brief,b)}if(p(),g("direction")||(u("plan")||await f("plan",async O=>{let N=await t.buildReskinPlan({...n.config(e.models.plan),sourcePath:a.source,analysisPath:a.analysis,directionPath:a.brief,planPath:a.plan,onEvent:O});return N.state==="completed"?null:N.error||"\u65B9\u6848\u672A\u5B8C\u6210"}),g("plan"))||(u("write")||await f("write",async O=>{let N=await t.writeReskinScript({...n.config(e.models.write),sourcePath:a.source,analysisPath:a.analysis,planPath:a.plan,scriptPath:a.script,concurrency:Math.max(1,Math.floor(8/n.concurrency)),episodeTimeoutMs:48e4,onEvent:O});return N.type==="done"&&!N.failed?.length?null:`\u8FD9\u4E9B\u96C6\u6CA1\u6709\u5199\u6210\uFF1A${(N.failed??[]).join("\u3001")}`}),g("write")))return;ce.existsSync(a.prereview)||ce.copyFileSync(a.script,a.prereview);let R=JSON.parse(ce.readFileSync(a.script,"utf8")).episodes?.length??0,I=d.review??={episodes:[],converged:!1};u("review")||await f("review",async O=>{let N=Array.from({length:R},(V,F)=>F+1).filter(V=>!I.episodes.includes(V)),U=V=>{O(V),V.type==="episode"&&V.state==="completed"&&!I.episodes.includes(Number(V.episode_number))&&(I.episodes.push(Number(V.episode_number)),I.episodes.sort((F,Re)=>F-Re),p()),V.type==="global"&&V.state==="completed"&&(I.converged=!0)};await t.reviewReskinScript({...n.config(e.models.review),scriptPath:a.script,sourcePath:a.source,analysisPath:a.analysis,planPath:a.plan,...N.length?{episodes:N}:{},convergeOnly:N.length===0,concurrency:5,converge:!0,maxSteps:300,episodeTimeoutMs:8*6e4,onEvent:U});let M=R-I.episodes.length;return M?`\u8FD8\u6709 ${M} \u96C6\u6CA1\u6709\u5BA1\u5B8C`:I.converged?null:"\u5168\u5267\u6536\u5C3E\u6CA1\u6709\u5B8C\u6210"})}for(let c of e.dramas){let a=Ia(kp(n.outputDir,c.id).status);i.set(c.id,{...a??{id:c.id,steps:{},step:null,reason:"",updated_at:""},state:"pending"})}return r(),await hS(e.dramas,n.concurrency,async c=>{try{await s(c);let d=i.get(c.id);d.state=n.until&&n.until!=="review"?"stopped":"completed",d.reason=d.state==="stopped"?`\u6309 --until \u505C\u5728 ${n.until}`:""}catch(d){let p=i.get(c.id)??{id:c.id,steps:{},step:null,reason:"",state:"failed",updated_at:""};i.set(c.id,p),p.state=d instanceof Rn?d.state:"failed",p.reason=d instanceof Error?d.message:String(d)}let a=i.get(c.id);a.updated_at=new Date(o()).toISOString(),Aa(kp(n.outputDir,c.id).status,a),r(),n.onEvent?.({type:"drama-done",drama:c.id,state:a.state,step:a.step,reason:a.reason})}),e.dramas.map(c=>i.get(c.id))}function yS(e){let t=e.split(`
226
- `)[0].replace(/\|/g,"\uFF0F");return t.length>160?`${t.slice(0,160)}\u2026`:t}function Ym(e){return`${Math.round(e/6e4)} \u5206\u949F`}function wS(e,t,n){let o=n.map(s=>{let c=Object.fromEntries(Xr.filter(p=>s.steps[p]).map(p=>{let l=s.steps[p];return[p,{state:l.state,runs:l.runs,wall_ms:l.wall_ms,...Qm(l.usage,t.prices),usage:l.usage}]})),a={};for(let p of Object.values(s.steps))for(let[l,f]of Object.entries(p.usage)){let u=a[l]??={calls:0,input:0,cached_input:0,output:0};u.calls+=f.calls,u.input+=f.input,u.cached_input+=f.cached_input,u.output+=f.output}let d=Object.values(s.steps).reduce((p,l)=>p+l.wall_ms,0);return{id:s.id,state:s.state,step:s.step,reason:s.reason,wall_ms:d,...Qm(a,t.prices),usage:a,steps:c,direction:s.direction??null}});Aa(we.join(e,"batch-report.json"),{updated_at:new Date().toISOString(),dramas:o});let i={pending:"\u7B49\u5F85",running:"\u8FDB\u884C\u4E2D",completed:"\u5B8C\u6210",stopped:"\u505C\u4E0B",failed:"\u5931\u8D25"},r=["# \u6362\u58F3\u6279\u91CF\u8FD0\u884C","","| \u5267 | \u72B6\u6001 | \u6B65\u9AA4 | \u7528\u65F6 | \u8D39\u7528\uFF08\u7F8E\u5143\uFF09 | \u8BF4\u660E |","| --- | --- | --- | --- | --- | --- |",...o.map(s=>`| ${s.id} | ${i[s.state]} | ${s.step??""} | ${Ym(s.wall_ms)} | ${s.usd.toFixed(2)}${s.unpriced.length?`\uFF08\u672A\u8BA1\u4EF7\uFF1A${s.unpriced.join("\u3001")}\uFF09`:""} | ${yS(s.reason)} |`),"",...o.flatMap(s=>[`## ${s.id}`,"","| \u6B65\u9AA4 | \u72B6\u6001 | \u8FD0\u884C\u6B21\u6570 | \u7528\u65F6 | \u8F93\u5165 tok | \u7F13\u5B58\u547D\u4E2D | \u8F93\u51FA tok | \u8D39\u7528 |","| --- | --- | --- | --- | --- | --- | --- | --- |",...Object.entries(s.steps).map(([c,a])=>{let d=Object.values(a.usage).reduce((p,l)=>({input:p.input+l.input,cached:p.cached+l.cached_input,output:p.output+l.output}),{input:0,cached:0,output:0});return`| ${c} | ${a.state} | ${a.runs} | ${Ym(a.wall_ms)} | ${(d.input/1e6).toFixed(2)}M | ${d.input?Math.round(d.cached/d.input*100):0}% | ${(d.output/1e6).toFixed(2)}M | ${a.usd.toFixed(2)} |`}),...s.direction?["",s.direction.suitability?`\u9002\u5408\u5EA6 ${s.direction.suitability.score}/5\uFF1A${s.direction.suitability.reason}`:"",s.direction.verdict?`\u6307\u5B9A\u65B9\u5411\u5224\u65AD\uFF1A${s.direction.verdict}\uFF1B${s.direction.verdict_reason}`:"",...s.direction.candidates.map((c,a)=>`${a+1}. ${c.title}\uFF1A${c.shell}\uFF08\u53EF\u884C\u6027 ${c.feasibility}\uFF0C\u5DEE\u5F02\u5EA6 ${c.distinctiveness}\uFF09${a+1===s.direction.recommended&&s.direction.mode==="candidates"?" \u2190 \u63A8\u8350":""}${a+1===s.direction.picked?" \u2190 \u9009\u5B9A":""}`)].filter(Boolean):[],""])];ce.writeFileSync(we.join(e,"batch-report.md"),r.join(`
227
- `))}var Wm="reskin",_S=["minimal","low","medium","high"],bp=["overall","events","beats"];function lt(e,t){if(!e||!pi.existsSync(e))throw new S(`${t} not found.`,{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:`Pass an existing ${t}.`,data:{expected:[`existing ${t}`],actual:[e||"<empty>"]}});return e}function Xm(e,t){let n=Ap(e,t),o=e.providers[e.models[t].provider]?.protocol,i=e.models[t].reasoning,r=o?.startsWith("google")&&_S.includes(i??"")?i:void 0;return{profile:n,config:{apiKey:n.apiKey,model:n.model,maxAttempts:n.maxAttempts,...n.baseUrl?{baseUrl:n.baseUrl}:{},...o?{protocol:o}:{},...r?{thinking:r}:{}}}}function Mo(e){let t=Io(v(e.llm_config).trim()||void 0),n=v(e.model).trim()||(t.models[Wm]?Wm:"review-agent"),{profile:o,config:i}=Xm(t,n),r=(t.models[n].fallbacks??[]).flatMap(s=>{try{return[Xm(t,s).config]}catch{return[]}});return{llm:t,name:n,profile:o,config:{...i,singleModel:e.fallback===!1,...r.length?{fallbacks:r}:{}}}}function er(e,t){return e instanceof S?e:new S("Reskin failed.",{exitCode:ee,errorCode:t,hint:"Read the NDJSON events and the saved plan or script before retrying; completed work is kept.",data:{expected:["a completed reskin run"],actual:[e instanceof Error?e.message:String(e)]}})}var li=e=>process.stdout.write(JSON.stringify(e)+`
228
- `);async function tr(e,t){let{llm:n,name:o,profile:i}=Mo(e),s=typeof(await nn())[t]=="function";return[{text:s?`ready: ${o} ${i.provider}/${i.model}`:"the agent bundle exports no reskin commands",data:{ready:s,profile:o,provider:i.provider,model:i.model,llm_config:n.sourcePath??"builtin"}},s?B:ee]}async function eg(e){if(e.check)return tr(e,"analyzeReskinSource");let{config:t}=Mo(e),n=lt(ge(e),"source script"),o=v(e.output).trim();if(!o)throw new S("Analysis output path missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass -o <\u62C6\u89E3.json>.",data:{expected:["analysis output path"],actual:["<empty>"]}});let i=await nn();try{let r=await i.analyzeReskinSource({...t,sourcePath:n,outputPath:o,force:e.force===!0,...e.concurrency!==void 0?{concurrency:st(e,"concurrency",5)}:{},...e.unit_timeout_ms!==void 0?{unitTimeoutMs:st(e,"unit_timeout_ms",6e5)}:{},onEvent:li});return[{text:"",data:{}},r.type==="analyze-done"&&r.state==="completed"?B:ee]}catch(r){throw er(r,"RESKIN_ANALYZE_FAILED")}}async function tg(e){if(e.check)return tr(e,"assessReskinPaths");let{config:t}=Mo(e),n=lt(v(e.analysis).trim(),"analysis"),o=v(e.markets).split(/[,,]/).map(s=>s.trim()).filter(Boolean);if(!o.length)throw new S("Candidate markets missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass --markets, e.g. --markets \u4E2D\u56FD,\u5370\u5C3C,\u7F8E\u56FD.",data:{expected:["comma-separated markets"],actual:["<empty>"]}});let i=v(e.output).trim(),r=await nn();try{let s=await r.assessReskinPaths({...t,analysisPath:n,markets:o,notes:v(e.notes),onEvent:li});return i&&s.type==="paths-done"&&s.state==="completed"&&pi.writeFileSync(i,JSON.stringify(s,null,2)+`
229
- `),[{text:"",data:{}},s.type==="paths-done"&&s.state==="completed"?B:ee]}catch(s){throw er(s,"RESKIN_PATHS_FAILED")}}async function ng(e){if(e.check)return tr(e,"proposeReskinDirections");let{config:t}=Mo(e),n=lt(ge(e),"source script"),o=lt(v(e.analysis).trim(),"analysis"),i=v(e.output).trim(),r=await nn();try{let s=await r.proposeReskinDirections({...t,sourcePath:n,analysisPath:o,notes:v(e.notes),custom:v(e.custom),market:v(e.market).trim(),rating:v(e.rating).trim(),avoid:(Array.isArray(e.avoid)?e.avoid:[]).map(c=>String(c).trim()).filter(Boolean),onEvent:li});return i&&s.type==="direction-done"&&s.state==="completed"&&pi.writeFileSync(i,JSON.stringify(s,null,2)+`
230
- `),[{text:"",data:{}},s.type==="direction-done"&&s.state==="completed"?B:ee]}catch(s){throw er(s,"RESKIN_DIRECTION_FAILED")}}async function og(e){if(e.check)return tr(e,"buildReskinPlan");let{config:t}=Mo(e),n=lt(ge(e),"source script"),o=lt(v(e.analysis).trim(),"analysis"),i=lt(v(e.direction).trim(),"direction"),r=v(e.output).trim(),s=v(e.until).trim();if(!r)throw new S("Plan output path missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass -o <\u6362\u58F3\u65B9\u6848.json>.",data:{expected:["plan output path"],actual:["<empty>"]}});if(s&&!bp.includes(s))throw new S("Unknown plan layer.",{exitCode:k,errorCode:"RESKIN_LAYER_UNKNOWN",hint:`Pass --until ${bp.join("|")}.`,data:{expected:[...bp],actual:[s]}});let c=await nn();try{let a=await c.buildReskinPlan({...t,sourcePath:n,analysisPath:o,directionPath:i,planPath:r,...s?{until:s}:{},force:e.force===!0,...e.unit_timeout_ms!==void 0?{unitTimeoutMs:st(e,"unit_timeout_ms",18e5)}:{},onEvent:li}),d=a.type==="plan-done"&&a.state!=="failed";return[{text:"",data:{}},d?B:ee]}catch(a){throw er(a,"RESKIN_PLAN_FAILED")}}async function ig(e){if(e.check)return tr(e,"writeReskinScript");let{config:t}=Mo(e),n=ge(e),o=lt(v(e.source).trim(),"source script"),i=lt(v(e.analysis).trim(),"analysis"),r=lt(v(e.plan).trim(),"plan"),s=Wr(v(e.episodes)),c=await nn();try{let a=await c.writeReskinScript({...t,sourcePath:o,analysisPath:i,planPath:r,scriptPath:n,...s?{episodes:s}:{},force:e.force===!0,concurrency:st(e,"concurrency",8),episodeTimeoutMs:st(e,"episode_timeout_ms",48e4),onEvent:li});return[{text:"",data:{}},a.type==="done"&&a.failed.length===0?B:ee]}catch(a){throw er(a,"RESKIN_WRITE_FAILED")}}async function rg(e){if(e.check)return tr(e,"reviewReskinScript");let{config:t}=Mo(e),n=lt(ge(e),"reskinned script"),o=lt(v(e.source).trim(),"source script"),i=lt(v(e.analysis).trim(),"analysis"),r=lt(v(e.plan).trim(),"plan"),s=Wr(v(e.episodes)),c=await nn();try{await c.reviewReskinScript({...t,scriptPath:n,sourcePath:o,analysisPath:i,planPath:r,...s?{episodes:s}:{},concurrency:st(e,"concurrency",10),converge:e.converge!==!1,convergeOnly:e.converge_only===!0,maxSteps:st(e,"max_steps",300),episodeTimeoutMs:st(e,"episode_timeout_ms",8*6e4),onEvent:li})}catch(a){throw er(a,"RESKIN_REVIEW_FAILED")}return[{text:"",data:{}},B]}async function sg(e){let t=e._args??[],n=lt(v(t[0]).trim(),"batch manifest"),o=v(e.output).trim();if(!o)throw new S("Batch output folder missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass -o <folder>; each drama gets its own project folder inside it.",data:{expected:["batch output folder"],actual:["<empty>"]}});let i=v(e.until).trim();if(i&&!Xr.includes(i))throw new S("Unknown batch step.",{exitCode:k,errorCode:"RESKIN_LAYER_UNKNOWN",hint:`Pass --until ${Xr.join("|")}.`,data:{expected:[...Xr],actual:[i]}});let r;try{r=qm(n)}catch(l){throw new S("Batch manifest is invalid.",{exitCode:k,errorCode:"RESKIN_BATCH_INVALID",hint:"Fix the manifest and run again.",data:{expected:["{ dramas: [{ source, ... }] }"],actual:[l instanceof Error?l.message:String(l)]}})}let s=v(e.pick).trim();s&&(r.pick=s==="recommended"?"recommended":st(e,"pick",1));let c=new Map(Object.values(r.models).map(l=>[l,Mo({...e,model:l}).config])),a=await nn();pi.mkdirSync(o,{recursive:!0});let p=(await Zm(r,a,{outputDir:o,until:i||void 0,concurrency:st(e,"concurrency",2),attempts:st(e,"attempts",3),config:l=>c.get(l),onEvent:li})).filter(l=>l.state==="failed").length;return[{text:"",data:{}},p?ee:B]}function ag(e,t){te(e.command("review"),"write").description("\u6D3E\u53D1 agent \u5BA1\u6838\u5267\u672C\uFF1A\u7ED9 -s \u5BF9\u7167\u6587\u672C\u3001\u6F2B\u753B\u6216\u89C6\u9891\u539F\u7A3F\uFF0C\u4E0D\u7ED9\u5219\u68C0\u67E5\u5267\u672C\u5185\u90E8\u4E00\u81F4\u6027").option("-s, --source-path <path>","\u6587\u672C/\u6F2B\u753B ingest \u5DE5\u4F5C\u533A\u3001\u539F txt/md/docx/PDF \u6216\u89C6\u9891\u6587\u4EF6/\u76EE\u5F55").option("--video <path>","\u7B2C N \u96C6\u7684\u89C6\u9891\uFF1B\u6309\u96C6\u987A\u5E8F\u91CD\u590D\u4F20\uFF0C\u8986\u76D6 -s \u7684\u76EE\u5F55\u6392\u5E8F",(i,r)=>[...r,i],[]).option("--episodes <list>","\u53EA\u5BA1\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u5267\uFF09").option("--concurrency <n>","\u540C\u65F6\u5728\u98DE\u7684\u96C6\u6570",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u8D85\u65F6\uFF1B\u5230\u70B9\u6536\u5C3E\u5E76\u4FDD\u7559\u5DF2\u8BB0\u5F55\u7684\u7ED3\u8BBA",Number).option("--max-steps <n>","\u5355\u96C6\u6700\u591A\u51E0\u6B65\u5DE5\u5177\u8C03\u7528",Number).option("--media-budget <n>","\u5355\u96C6\u6700\u591A\u51E0\u6B21\u89C6\u9891\u6838\u5BF9",Number).option("--converge-only","\u53EA\u6267\u884C\u5168\u5267\u6536\u655B\uFF0C\u4E0D\u91CD\u65B0\u5BA1\u6838\u5404\u96C6").option("--no-converge","\u8DF3\u8FC7\u5168\u5267\u6536\u655B\u9636\u6BB5").option("--model <profile>","\u8986\u76D6 LLM profile\uFF08\u89C6\u9891/\u7EAF\u5267\u672C\u9ED8\u8BA4 review-agent\uFF0C\u6587\u672C review-text\uFF0C\u6F2B\u753B review-comic\uFF09").option("--llm-config <path>","LLM configuration file").option("--check","\u53EA\u68C0\u67E5\u6A21\u578B\u4E0E agent \u662F\u5426\u5C31\u7EEA\uFF0C\u4E0D\u5BA1\u6838").action(H(Fm,t));let n=e.command("reskin").description("\u6362\u58F3\u4EFF\u5199\uFF1A\u62C6\u89E3\u539F\u5267\uFF0C\u63D0\u51FA\u65B0\u58F3\u65B9\u5411\uFF0C\u9010\u5C42\u5B9A\u6362\u58F3\u65B9\u6848\uFF08\u6574\u4F53\u65B9\u6848 \u2192 \u4E8B\u4EF6 \u2192 \u8282\u62CD\uFF09\uFF0C\u6309\u7ED3\u6784\u8868\u9010\u96C6\u5199\u65B0\u5267\uFF0C\u518D\u505A\u6362\u58F3\u5BA1\u6838"),o=i=>i.option("--model <profile>","\u8986\u76D6 LLM profile\uFF08\u9ED8\u8BA4 reskin\uFF09").option("--no-fallback","\u53EA\u7528\u6240\u9009\u6A21\u578B\uFF0C\u5931\u8D25\u65F6\u4E0D\u6362\u7528\u5176\u4ED6\u6A21\u578B\uFF08\u9ED8\u8BA4\u6309\u914D\u7F6E\u7684\u964D\u7EA7\u987A\u5E8F\u6362\u7528\uFF09").option("--llm-config <path>","LLM configuration file").option("--check","\u53EA\u68C0\u67E5\u6A21\u578B\u4E0E agent \u662F\u5426\u5C31\u7EEA");o(te(n.command("analyze"),"read").description("\u62C6\u89E3\u539F\u5267\uFF1A\u5148\u901A\u8BFB\u5168\u5267\u5212\u5206\u9636\u6BB5\u4E0E\u4E8B\u4EF6\uFF0C\u518D\u6309\u9636\u6BB5\u5E76\u884C\u5199\u4E8B\u4EF6\u4E8B\u5B9E\u3001\u6309\u96C6\u5E76\u884C\u5207\u8282\u62CD\uFF0C\u540C\u65F6\u5F52\u7EB3\u5168\u5267\u753B\u50CF\uFF08\u539F\u5267\u5730\u533A\u4E0E\u53F0\u8BCD\u8BED\u8A00\u3001\u6362\u58F3\u9002\u5408\u5EA6\uFF09\u3002-p \u4E3A\u539F\u5267\u5267\u672C\uFF1B\u5DF2\u5B8C\u6210\u7684\u5355\u5143\u4FDD\u5B58\u5728\u8F93\u51FA\u6587\u4EF6\u65C1\u7684 .cache/analyze.json\uFF0C\u518D\u6B21\u8FD0\u884C\u4ECE\u65AD\u70B9\u7EE7\u7EED").option("-o, --output <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--force","\u5FFD\u7565\u5DF2\u4FDD\u5B58\u7684\u8FDB\u5EA6\u91CD\u65B0\u62C6\u89E3").option("--concurrency <n>","\u5E76\u884C\u7684\u5355\u5143\u6570",Number).option("--unit-timeout-ms <ms>","\u5355\u4E2A\u5355\u5143\u7684\u8D85\u65F6",Number)).action(H(eg,t)),o(n.command("paths").description("\u9009\u9898\u5224\u65AD\uFF1A\u8BFB\u539F\u5267\u62C6\u89E3\u7684\u753B\u50CF\u4E0E\u5927\u7EB2\uFF0C\u9010\u4E2A\u5019\u9009\u5E02\u573A\u5217\u51FA\u8D70\u5F97\u901A\u7684\u6539\u7F16\u8DEF\u5F84\uFF08\u540C\u5E02\u573A\u6362\u8F7D\u4F53\u3001\u8DE8\u5E02\u573A\u672C\u5730\u5316\u3001\u8DE8\u5E02\u573A\u6362\u58F3\u3001\u6362\u4E16\u754C\u89C2\uFF09\uFF0C\u7ED9\u51FA\u5EFA\u8BAE\u505A\u51E0\u4E2A\u7248\u672C").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--markets <list>","\u5019\u9009\u5E02\u573A\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u5FC5\u586B\uFF09\uFF0C\u5982 \u4E2D\u56FD,\u5370\u5C3C,\u7F8E\u56FD").option("--notes <text>","\u7528\u6237\u8981\u6C42\u4E0E\u4E1A\u52A1\u4F18\u5148").option("-o, --output <path>","\u628A\u7ED3\u679C\u53E6\u5B58\u4E3A JSON")).action(H(tg,t)),o(te(n.command("direction"),"read").description("\u63D0\u51FA 2\u20133 \u4E2A\u5019\u9009\u65B0\u58F3\uFF1B\u7ED9\u51FA --custom \u65F6\u5224\u65AD\u7528\u6237\u6307\u5B9A\u7684\u65B9\u5411\u662F\u5426\u53EF\u884C\u5E76\u6309\u5B83\u8BBE\u8BA1\u4E00\u4E2A\u5019\u9009\u3002-p \u4E3A\u539F\u5267\u5267\u672C").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--notes <text>","\u7528\u6237\u7684\u6362\u58F3\u8981\u6C42").option("--custom <text>","\u7528\u6237\u6307\u5B9A\u7684\u6362\u58F3\u65B9\u5411").option("--market <text>","\u65B0\u5267\u9762\u5411\u7684\u76EE\u6807\u5E02\u573A\uFF0C\u9ED8\u8BA4\u540C\u539F\u5267").option("--rating <text>","\u5C3A\u5EA6\u8981\u6C42\uFF0C\u9ED8\u8BA4\u540C\u539F\u5267").option("--avoid <shell>","\u8FD9\u90E8\u539F\u5267\u5DF2\u505A\u8FC7\u7684\u7248\u672C\u7684\u58F3\uFF0C\u53EF\u91CD\u590D\u7ED9\u51FA\uFF1B\u65B0\u5019\u9009\u4E0E\u5B83\u4EEC\u660E\u663E\u4E0D\u540C",(i,r=[])=>[...r,i]).option("-o, --output <path>","\u628A\u7ED3\u679C\u53E6\u5B58\u4E3A JSON")).action(H(ng,t)),o(te(n.command("plan"),"read").description("\u9010\u5C42\u751F\u6210\u6362\u58F3\u65B9\u6848\uFF1A\u6574\u4F53\u65B9\u6848\uFF08\u542B\u9636\u6BB5\u8D70\u5411\uFF09\u2192 \u5404\u9636\u6BB5\u4E8B\u4EF6 \u2192 \u5404\u9636\u6BB5\u8282\u62CD\uFF0C\u4E0B\u5C42\u53EF\u56DE\u6539\u4E0A\u5C42\u5E76\u590D\u67E5\u53D7\u5F71\u54CD\u7684\u90E8\u5206\u3002-p \u4E3A\u539F\u5267\u5267\u672C\uFF1B\u5DF2\u6709\u65B9\u6848\u65F6\u4ECE\u672A\u5B8C\u6210\u7684\u90E8\u5206\u7EE7\u7EED").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--direction <path>","\u9009\u5B9A\u7684\u6362\u58F3\u65B9\u5411\u8BF4\u660E\uFF08\u5FC5\u586B\uFF09").option("-o, --output <path>","\u6362\u58F3\u65B9\u6848 JSON\uFF08\u5FC5\u586B\uFF09").option("--until <layer>","\u505A\u5230\u8FD9\u4E00\u5C42\u540E\u6682\u505C\uFF1Aoverall | events | beats").option("--force","\u5FFD\u7565\u5DF2\u6709\u65B9\u6848\u91CD\u65B0\u751F\u6210").option("--unit-timeout-ms <ms>","\u5355\u4E2A\u5355\u5143\u7684\u8D85\u65F6",Number)).action(H(og,t)),o(te(n.command("write"),"write").description("\u6309\u6362\u58F3\u65B9\u6848\u7684\u7ED3\u6784\u8868\u5199\u65B0\u5267\uFF1A\u5148\u5E76\u884C\u5199\u9694\u4E00\u96C6\u7684\u5404\u96C6\uFF0C\u518D\u5199\u5B83\u4EEC\u4E4B\u95F4\u7684\u96C6\uFF0C\u540E\u8005\u8BFB\u4E24\u5934\u5DF2\u5199\u7684\u6B63\u6587\u63A5\u4E0A\u8854\u63A5\u3002-p \u4E3A\u65B0\u5267\u5267\u672C\uFF0C\u4E0D\u5B58\u5728\u6216\u6362\u540D\u6362\u5916\u89C2\u53D8\u5316\u65F6\u4ECE\u539F\u5267\u590D\u5236\uFF1B\u6BCF\u6761\u6B63\u6587\u8BB0\u4E0B\u6240\u5C5E\u7684\u65B0\u8282\u62CD\uFF0C\u4E0D\u5199\u65F6\u95F4\u6233").option("--source <path>","\u539F\u5267\u5267\u672C\uFF08\u5FC5\u586B\uFF09").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--plan <path>","\u5DF2\u5B8C\u6210\u7684\u6362\u58F3\u65B9\u6848 JSON\uFF08\u5FC5\u586B\uFF09").option("--episodes <list>","\u53EA\u5199\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u5267\u672A\u5B8C\u6210\u7684\u96C6\uFF09").option("--force","\u6240\u9009\u7684\u96C6\u5DF2\u5199\u8FC7\u4E5F\u91CD\u5199").option("--concurrency <n>","\u540C\u65F6\u5199\u7684\u96C6\u6570\uFF08\u9ED8\u8BA4 8\uFF09\uFF1B1 \u4E3A\u4E25\u683C\u6309\u96C6\u5E8F\u9010\u96C6\u5199",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u8D85\u65F6",Number)).action(H(ig,t)),o(te(n.command("review"),"write").description("\u6362\u58F3\u5BA1\u6838\uFF1A\u6309\u96C6\u5E8F\u901A\u8BFB\uFF0C\u9010\u96C6\u5BA1\u6362\u5F97\u662F\u5426\u5408\u7406\u3001\u662F\u5426\u770B\u5F97\u61C2\u4E0E\u901A\u987A\u3001\u524D\u540E\u662F\u5426\u8FDE\u8D2F\u3001\u9020\u578B\u4E0E\u573A\u666F\u5F15\u7528\u662F\u5426\u51C6\u786E\uFF0C\u5904\u7406\u7A0B\u5E8F\u68C0\u67E5\u7ED3\u679C\uFF0C\u518D\u505A\u5168\u5267\u6536\u5C3E\u3002-p \u4E3A\u65B0\u5267\u5267\u672C\uFF1B\u4E8B\u4EF6\u683C\u5F0F\u4E0E review \u76F8\u540C").option("--source <path>","\u539F\u5267\u5267\u672C\uFF08\u5FC5\u586B\uFF09").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--plan <path>","\u6362\u58F3\u65B9\u6848 JSON\uFF08\u5FC5\u586B\uFF09").option("--episodes <list>","\u53EA\u5BA1\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u90E8\uFF09").option("--concurrency <n>","\u540C\u65F6\u8FDB\u884C\u7684\u901A\u8BFB\u6BB5\u6570\uFF08\u9ED8\u8BA4 10\uFF0C\u6BCF\u6BB5\u7EA6 6 \u96C6\uFF09",Number).option("--max-steps <n>","\u6BCF\u96C6\u6700\u591A\u51E0\u6B65\u5DE5\u5177\u8C03\u7528",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u8D85\u65F6",Number).option("--converge-only","\u53EA\u6267\u884C\u5168\u5267\u6536\u5C3E").option("--no-converge","\u8DF3\u8FC7\u5168\u5267\u6536\u5C3E")).action(H(rg,t)),n.command("batch").argument("<manifest>","\u6279\u91CF\u6E05\u5355 JSON\uFF1A{ dramas: [{ id, source, market, language, rating, notes, custom, pick, avoid }], models, prices, pick }").description("\u65E0\u4EBA\u503C\u5B88\u6279\u91CF\u6362\u58F3\uFF1A\u6BCF\u90E8\u5267\u5728 -o \u4E0B\u6709\u81EA\u5DF1\u7684\u9879\u76EE\u76EE\u5F55\uFF0C\u4F9D\u6B21\u62C6\u89E3 \u2192 \u65B9\u5411 \u2192 \u65B9\u6848 \u2192 \u5199\u4F5C \u2192 \u5BA1\u6838\uFF0C\u6BCF\u6B65\u4ECE\u5DF2\u4FDD\u5B58\u7684\u8FDB\u5EA6\u7EE7\u7EED\u3002\u62C6\u89E3\u8BC4\u51FA\u7684\u9002\u5408\u5EA6\u4F4E\u4E8E 3 \u4E14\u6CA1\u5199 pick \u65F6\u505C\u5728\u62C6\u89E3\u540E\uFF0C\u6307\u5B9A\u65B9\u5411\u4E0D\u53EF\u884C\u6216\u9700\u8981\u4EBA\u5DE5\u9009\u65B9\u5411\u65F6\u505C\u5728\u65B9\u5411\u6B65\uFF1B\u8865\u4E0A pick \u540E\u518D\u8FD0\u884C\u5373\u4ECE\u65B9\u5411\u7EE7\u7EED\u3002\u8FDB\u5EA6\u4E0E\u62A5\u544A\u5199\u5728 -o \u4E0B\u7684 batch-report.json / batch-report.md").option("-o, --output <dir>","\u6279\u91CF\u8F93\u51FA\u76EE\u5F55\uFF08\u5FC5\u586B\uFF09").option("--concurrency <n>","\u540C\u65F6\u8FDB\u884C\u7684\u5267\u6570\uFF08\u9ED8\u8BA4 2\uFF09",Number).option("--attempts <n>","\u6BCF\u6B65\u6700\u591A\u8FD0\u884C\u51E0\u6B21\uFF0C\u6BCF\u6B21\u4ECE\u4E0A\u6B21\u8FDB\u5EA6\u7EE7\u7EED\uFF08\u9ED8\u8BA4 3\uFF09",Number).option("--pick <n|recommended>","\u6CA1\u5199 pick \u7684\u5267\u7528\u8FD9\u4E2A\u5019\u9009\uFF1B\u4E0D\u7ED9\u65F6\u505C\u4E0B\u7B49\u4EBA\u5DE5\u9009\u62E9").option("--until <step>","\u505A\u5230\u8FD9\u4E00\u6B65\u540E\u505C\u4E0B\uFF1Aanalyze | direction | plan | write | review").option("--no-fallback","\u53EA\u7528\u6240\u9009\u6A21\u578B\uFF0C\u5931\u8D25\u65F6\u4E0D\u6362\u7528\u5176\u4ED6\u6A21\u578B\uFF08\u9ED8\u8BA4\u6309\u914D\u7F6E\u7684\u964D\u7EA7\u987A\u5E8F\u6362\u7528\uFF09").option("--llm-config <path>","LLM configuration file").action(H(sg,t))}import*as cg from"node:fs";var No="\u5730\u5740\uFF1A\u96C6 `3`\u3001\u573A `3-2`\u3001\u5355\u6761 `3-2-5`\u3001\u6B63\u5F0F ID\u3001\u8D44\u4EA7\u540D\u3001\u6216 `<\u8D44\u4EA7>/<\u72B6\u6001>`";function je(e){let t=ge(e);if(!cg.existsSync(t))throw new S("Local script file not found.",{exitCode:k,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[t]}});return Fd(t)}function he(e,t){let n=e[t];return typeof n=="string"?n:void 0}function ui(e,t){let n=e[t];if(n==null||n==="")return;let o=Number(n);if(!Number.isFinite(o))throw new S(`--${t} must be a number.`,{exitCode:k,errorCode:"OPTION_NOT_NUMBER",data:{actual:[String(n)]}});return o}function ye(e,t=0){return(e._args??[])[t]??""}function Op(e){return Array.isArray(e)?e.map(String):typeof e=="string"?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function at(e,t,n=()=>({})){try{let o=e();return[{text:o,data:{op:t,changed:!1,text:o,...n()}},B]}catch(o){throw o instanceof S?o:new S(o instanceof Error?o.message:String(o),{exitCode:k,errorCode:o?.code??"SCRIPT_TOOL_FAILED"})}}function dg(e,t){let n=te(e.command("read [addr]"),"read").description(`\u8BFB\u4EFB\u610F\u8282\u70B9\uFF1B\u4E0D\u7ED9\u5730\u5740\u8FD4\u56DE\u5267\u672C\u5361\u3002${No}`).option("--outline","\u53EA\u8981\u573A\u7ED3\u6784\uFF0C\u4E0D\u8981\u6B63\u6587").option("--context <n>","\u5355\u6761 action \u524D\u540E\u5404\u5E26\u51E0\u6761\uFF08\u9ED8\u8BA4 3\uFF09").option("--plain","\u53BB\u6389\u951A\u70B9\u4E0E\u65F6\u95F4\u6233\uFF08\u53EA\u8BFB\uFF0C\u4E0D\u53EF\u56DE\u5199\uFF09").action(H(y=>{let _=je(y);return at(()=>ca(_,ye(y),{...y.outline?{depth:"outline"}:{},...y.plain?{plain:!0}:{},...ui(y,"context")!==void 0?{context:ui(y,"context")}:{}}),"read",()=>ye(y)?{}:{document:_.raw})},t));Me(n,[No]);let o=te(e.command("scan <episode>"),"read").description("\u4E00\u6B21\u8FD4\u56DE\u67D0\u96C6\u7684\u5B8C\u6574\u4E0A\u4E0B\u6587\uFF1A\u573A\u7ED3\u6784 + \u5168\u90E8\u6B63\u6587 + \u5F53\u524D\u6821\u9A8C\u95EE\u9898").action(H(y=>at(()=>{let _=je(y),x=ye(y);return[`## \u573A\u7ED3\u6784
231
- ${ca(_,x,{depth:"outline"})}`,`## \u6B63\u6587
232
- ${ca(_,x)}`,`## \u5F53\u524D\u6821\u9A8C\u95EE\u9898
233
- ${cp(_,{})}`].join(`
225
+ `}function Xm(e){let t=JSON.parse(ge.readFileSync(e,"utf8")),n=Array.isArray(t)?{dramas:t}:t;if(!Array.isArray(n.dramas)||!n.dramas.length)throw new Error("\u6E05\u5355\u91CC\u6CA1\u6709 dramas\u3002");let o=Ee.dirname(Ee.resolve(e)),i=new Set;return{dramas:n.dramas.map((s,c)=>{if(!s.source?.trim())throw new Error(`\u7B2C ${c+1} \u90E8\u5267\u6CA1\u6709 source\u3002`);let a=Ee.resolve(o,s.source.trim()),d=(s.id?.trim()||Ee.basename(Ee.dirname(a))).replace(/[\\/]/g,"-");if(i.has(d))throw new Error(`\u5267\u7684 id \u91CD\u590D\uFF1A${d}\uFF1B\u7ED9\u6BCF\u90E8\u5267\u5199\u4E0D\u540C\u7684 id\u3002`);if(i.add(d),s.pick!==void 0&&s.pick!=="recommended"&&!(Number.isInteger(s.pick)&&Number(s.pick)>=1))throw new Error(`${d} \u7684 pick \u5199\u5019\u9009\u5E8F\u53F7\uFF08\u4ECE 1 \u5F00\u59CB\uFF09\u6216 recommended\u3002`);return{...s,id:d,source:a}}),models:{...pS,...n.models??{}},prices:{...lS,...n.prices??{}},...n.pick!==void 0?{pick:n.pick}:{}}}async function yS(e,t,n){let o=[...e];await Promise.all(Array.from({length:Math.max(1,Math.min(t,o.length))},async()=>{for(let i=o.shift();i!==void 0;i=o.shift())await n(i)}))}var Rn=class extends Error{constructor(n,o){super(o);this.state=n}state};async function eg(e,t,n){let o=n.now??Date.now,i=new Map,r=()=>_S(n.outputDir,e,[...i.values()]);async function s(c){let a=Op(n.outputDir,c.id),d={...ka(a.status)??{id:c.id,steps:{}},state:"running",reason:"",step:null,updated_at:""};i.set(c.id,d);let p=()=>{d.updated_at=new Date(o()).toISOString(),ba(a.status,d),r()},l=I=>n.onEvent?.({drama:c.id,...I});if(!ge.existsSync(a.source)){if(!ge.existsSync(c.source))throw new Rn("failed",`\u539F\u5267\u5267\u672C\u4E0D\u5B58\u5728\uFF1A${c.source}`);ge.mkdirSync(Ee.dirname(a.source),{recursive:!0}),ge.copyFileSync(c.source,a.source)}async function f(I,v){let L=d.steps[I]??{state:"running",runs:0,wall_ms:0,usage:{}};L.state="running",d.steps[I]=L,d.step=I,p(),l({type:"step-started",step:I}),ge.mkdirSync(Ee.dirname(a.log(I)),{recursive:!0});let C=J=>{ge.appendFileSync(a.log(I),JSON.stringify(J)+`
226
+ `),mS.has(String(J.type))&&Array.isArray(J.usage)&&fS(L.usage,J.usage)},R=null;for(let J=1;J<=n.attempts;J+=1){let W=o();L.runs+=1;try{R=await v(C)}catch(Re){R=Re instanceof Error?Re.message:String(Re)}if(L.wall_ms+=o()-W,p(),!R)break}if(L.state=R?"failed":"completed",R?L.error=R:delete L.error,p(),l({type:"step-done",step:I,state:L.state,error:R}),R)throw new Rn("failed",`${I}\uFF1A${R}`)}let u=I=>d.steps[I]?.state==="completed",m=I=>n.until===I;if((!u("analyze")||!ge.existsSync(a.analysis))&&await f("analyze",async I=>{let v=await t.analyzeReskinSource({...n.config(e.models.analyze),sourcePath:a.source,outputPath:a.analysis,onEvent:I});return v.state==="completed"?null:v.error||"\u62C6\u89E3\u672A\u5B8C\u6210"}),m("analyze"))return;let h=ka(a.analysis)?.profile?.suitability;if(typeof h?.score=="number"&&h.score<3&&c.pick===void 0)throw d.step="analyze",new Rn("stopped",`\u8FD9\u90E8\u539F\u5267\u4E0D\u592A\u9002\u5408\u6362\u58F3\uFF08\u62C6\u89E3\u9002\u5408\u5EA6 ${h.score}/5\uFF09${h.reason?`\uFF1A${h.reason}`:""}\u3002\u770B\u8FC7\u540E\u4ECD\u8981\u505A\uFF0C\u7ED9\u8FD9\u90E8\u5267\u5199 pick \u518D\u8FD0\u884C`);let g=gS(a.analysis,c),w=ka(a.direction);(w?.key!==g||w.result.state!=="completed")&&(w=null,await f("direction",async I=>{let v=await t.proposeReskinDirections({...n.config(e.models.direction),sourcePath:a.source,analysisPath:a.analysis,notes:c.notes??"",custom:c.custom??"",market:c.market??"",rating:c.rating??"",avoid:c.avoid??[],onEvent:I});return v.type!=="direction-done"||v.state!=="completed"?v.type==="direction-done"&&v.error||"\u65B9\u5411\u672A\u5B8C\u6210":(w={key:g,result:v},ba(a.direction,w),null)}));let y=w.result,_=!!c.custom?.trim(),S=_?1:c.pick??e.pick,E=S==="recommended"?y.recommended:S??null;if(d.direction={mode:_?"custom":"candidates",suitability:y.suitability,verdict:y.verdict,verdict_reason:y.reason,candidates:y.candidates.map(({title:I,shell:v,feasibility:L,distinctiveness:C})=>({title:I,shell:v,feasibility:L,distinctiveness:C})),recommended:y.recommended,recommendation:y.recommendation,picked:E},d.step="direction",y.verdict==="\u4E0D\u53EF\u884C")throw new Rn("stopped",`\u6307\u5B9A\u7684\u65B9\u5411\u4E0D\u53EF\u884C\uFF1A${y.reason}`);if(y.suitability&&y.suitability.score<3&&c.pick===void 0)throw new Rn("stopped",`\u8FD9\u90E8\u539F\u5267\u4E0D\u592A\u9002\u5408\u6362\u58F3\uFF08\u9002\u5408\u5EA6 ${y.suitability.score}/5\uFF09\uFF1A${y.suitability.reason}\u3002\u770B\u8FC7\u540E\u4ECD\u8981\u505A\uFF0C\u7ED9\u8FD9\u90E8\u5267\u5199 pick \u518D\u8FD0\u884C`);if(E===null)throw new Rn("stopped",`\u5F85\u4EBA\u5DE5\u9009\u62E9\u65B9\u5411\uFF1A\u5728\u6E05\u5355\u91CC\u7ED9\u8FD9\u90E8\u5267\u5199 pick\uFF081\u2013${y.candidates.length}\uFF0C\u63A8\u8350 ${y.recommended}\uFF09\u540E\u518D\u8FD0\u884C`);let A=y.candidates[E-1];if(!A)throw new Rn("stopped",`pick ${E} \u8D85\u51FA\u5019\u9009\u8303\u56F4\uFF08\u5171 ${y.candidates.length} \u4E2A\uFF09`);let b=hS(A,y,c),U=ge.existsSync(a.brief)?ge.readFileSync(a.brief,"utf8"):null;if(U!==b){let I=Ee.dirname(a.script);U!==null&&ge.existsSync(I)&&ge.renameSync(I,`${I}.${new Date(o()).toISOString().replace(/[:.]/g,"-")}`);for(let v of["plan","write","review"])delete d.steps[v];delete d.review,ge.mkdirSync(Ee.dirname(a.brief),{recursive:!0}),ge.writeFileSync(a.brief,b)}if(p(),m("direction")||(u("plan")||await f("plan",async I=>{let v=await t.buildReskinPlan({...n.config(e.models.plan),sourcePath:a.source,analysisPath:a.analysis,directionPath:a.brief,planPath:a.plan,onEvent:I});return v.state==="completed"?null:v.error||"\u65B9\u6848\u672A\u5B8C\u6210"}),m("plan"))||(u("write")||await f("write",async I=>{let v=await t.writeReskinScript({...n.config(e.models.write),reviewModel:n.config(e.models.review),sourcePath:a.source,analysisPath:a.analysis,planPath:a.plan,scriptPath:a.script,concurrency:Math.max(1,Math.floor(6/n.concurrency)),episodeTimeoutMs:48e4,onEvent:I});return v.type==="done"&&!v.failed?.length?null:`\u8FD9\u4E9B\u96C6\u6CA1\u6709\u5199\u6210\uFF1A${(v.failed??[]).join("\u3001")}`}),m("write")))return;let M=d.review??={converged:!1};u("review")||await f("review",async I=>{M.converged=!1;let v=!1,L=0,C=R=>{I(R),R.type==="global"&&L++,(R.type==="global"||R.type==="episode")&&R.state==="failed"&&(v=!0),R.type==="done"&&(M.converged=L>0&&!v)};return await t.reviewReskinScript({...n.config(e.models.review),scriptPath:a.script,sourcePath:a.source,analysisPath:a.analysis,planPath:a.plan,convergeOnly:!0,concurrency:5,maxSteps:300,episodeTimeoutMs:8*6e4,onEvent:C}),M.converged?null:"\u5168\u5267\u6536\u5C3E\u6CA1\u6709\u5B8C\u6210"})}for(let c of e.dramas){let a=ka(Op(n.outputDir,c.id).status);i.set(c.id,{...a??{id:c.id,steps:{},step:null,reason:"",updated_at:""},state:"pending"})}return r(),await yS(e.dramas,n.concurrency,async c=>{try{await s(c);let d=i.get(c.id);d.state=n.until&&n.until!=="review"?"stopped":"completed",d.reason=d.state==="stopped"?`\u6309 --until \u505C\u5728 ${n.until}`:""}catch(d){let p=i.get(c.id)??{id:c.id,steps:{},step:null,reason:"",state:"failed",updated_at:""};i.set(c.id,p),p.state=d instanceof Rn?d.state:"failed",p.reason=d instanceof Error?d.message:String(d)}let a=i.get(c.id);a.updated_at=new Date(o()).toISOString(),ba(Op(n.outputDir,c.id).status,a),r(),n.onEvent?.({type:"drama-done",drama:c.id,state:a.state,step:a.step,reason:a.reason})}),e.dramas.map(c=>i.get(c.id))}function wS(e){let t=e.split(`
227
+ `)[0].replace(/\|/g,"\uFF0F");return t.length>160?`${t.slice(0,160)}\u2026`:t}function Wm(e){return`${Math.round(e/6e4)} \u5206\u949F`}function _S(e,t,n){let o=n.map(s=>{let c=Object.fromEntries(es.filter(p=>s.steps[p]).map(p=>{let l=s.steps[p];return[p,{state:l.state,runs:l.runs,wall_ms:l.wall_ms,...Zm(l.usage,t.prices),usage:l.usage}]})),a={};for(let p of Object.values(s.steps))for(let[l,f]of Object.entries(p.usage)){let u=a[l]??={calls:0,input:0,cached_input:0,output:0};u.calls+=f.calls,u.input+=f.input,u.cached_input+=f.cached_input,u.output+=f.output}let d=Object.values(s.steps).reduce((p,l)=>p+l.wall_ms,0);return{id:s.id,state:s.state,step:s.step,reason:s.reason,wall_ms:d,...Zm(a,t.prices),usage:a,steps:c,direction:s.direction??null}});ba(Ee.join(e,"batch-report.json"),{updated_at:new Date().toISOString(),dramas:o});let i={pending:"\u7B49\u5F85",running:"\u8FDB\u884C\u4E2D",completed:"\u5B8C\u6210",stopped:"\u505C\u4E0B",failed:"\u5931\u8D25"},r=["# \u6362\u58F3\u6279\u91CF\u8FD0\u884C","","| \u5267 | \u72B6\u6001 | \u6B65\u9AA4 | \u7528\u65F6 | \u8D39\u7528\uFF08\u7F8E\u5143\uFF09 | \u8BF4\u660E |","| --- | --- | --- | --- | --- | --- |",...o.map(s=>`| ${s.id} | ${i[s.state]} | ${s.step??""} | ${Wm(s.wall_ms)} | ${s.usd.toFixed(2)}${s.unpriced.length?`\uFF08\u672A\u8BA1\u4EF7\uFF1A${s.unpriced.join("\u3001")}\uFF09`:""} | ${wS(s.reason)} |`),"",...o.flatMap(s=>[`## ${s.id}`,"","| \u6B65\u9AA4 | \u72B6\u6001 | \u8FD0\u884C\u6B21\u6570 | \u7528\u65F6 | \u8F93\u5165 tok | \u7F13\u5B58\u547D\u4E2D | \u8F93\u51FA tok | \u8D39\u7528 |","| --- | --- | --- | --- | --- | --- | --- | --- |",...Object.entries(s.steps).map(([c,a])=>{let d=Object.values(a.usage).reduce((p,l)=>({input:p.input+l.input,cached:p.cached+l.cached_input,output:p.output+l.output}),{input:0,cached:0,output:0});return`| ${c} | ${a.state} | ${a.runs} | ${Wm(a.wall_ms)} | ${(d.input/1e6).toFixed(2)}M | ${d.input?Math.round(d.cached/d.input*100):0}% | ${(d.output/1e6).toFixed(2)}M | ${a.usd.toFixed(2)} |`}),...s.direction?["",s.direction.suitability?`\u9002\u5408\u5EA6 ${s.direction.suitability.score}/5\uFF1A${s.direction.suitability.reason}`:"",s.direction.verdict?`\u6307\u5B9A\u65B9\u5411\u5224\u65AD\uFF1A${s.direction.verdict}\uFF1B${s.direction.verdict_reason}`:"",...s.direction.candidates.map((c,a)=>`${a+1}. ${c.title}\uFF1A${c.shell}\uFF08\u53EF\u884C\u6027 ${c.feasibility}\uFF0C\u5DEE\u5F02\u5EA6 ${c.distinctiveness}\uFF09${a+1===s.direction.recommended&&s.direction.mode==="candidates"?" \u2190 \u63A8\u8350":""}${a+1===s.direction.picked?" \u2190 \u9009\u5B9A":""}`)].filter(Boolean):[],""])];ge.writeFileSync(Ee.join(e,"batch-report.md"),r.join(`
228
+ `))}var tg="reskin",ES=["minimal","low","medium","high"],vp=["overall","events","beats"];function lt(e,t){if(!e||!li.existsSync(e))throw new x(`${t} not found.`,{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:`Pass an existing ${t}.`,data:{expected:[`existing ${t}`],actual:[e||"<empty>"]}});return e}function ng(e,t){let n=bp(e,t),o=e.providers[e.models[t].provider]?.protocol,i=e.models[t].reasoning,r=o?.startsWith("google")&&ES.includes(i??"")?i:void 0;return{profile:n,config:{apiKey:n.apiKey,model:n.model,maxAttempts:n.maxAttempts,...n.baseUrl?{baseUrl:n.baseUrl}:{},...o?{protocol:o}:{},...r?{thinking:r}:{}}}}function Wn(e){let t=Ao(O(e.llm_config).trim()||void 0),n=O(e.model).trim()||(t.models[tg]?tg:"review-agent"),{profile:o,config:i}=ng(t,n),r=(t.models[n].fallbacks??[]).flatMap(s=>{try{return[ng(t,s).config]}catch{return[]}});return{llm:t,name:n,profile:o,config:{...i,singleModel:e.fallback===!1,...r.length?{fallbacks:r}:{}}}}function nr(e,t){return e instanceof x?e:new x("Reskin failed.",{exitCode:X,errorCode:t,hint:"Read the NDJSON events and the saved plan or script before retrying; completed work is kept.",data:{expected:["a completed reskin run"],actual:[e instanceof Error?e.message:String(e)]}})}var ui=e=>process.stdout.write(JSON.stringify(e)+`
229
+ `);async function or(e,t){let{llm:n,name:o,profile:i}=Wn(e),s=typeof(await nn())[t]=="function";return[{text:s?`ready: ${o} ${i.provider}/${i.model}`:"the agent bundle exports no reskin commands",data:{ready:s,profile:o,provider:i.provider,model:i.model,llm_config:n.sourcePath??"builtin"}},s?G:X]}async function og(e){if(e.check)return or(e,"analyzeReskinSource");let{config:t}=Wn(e),n=lt(me(e),"source script"),o=O(e.output).trim();if(!o)throw new x("Analysis output path missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass -o <\u62C6\u89E3.json>.",data:{expected:["analysis output path"],actual:["<empty>"]}});let i=await nn();try{let r=await i.analyzeReskinSource({...t,sourcePath:n,outputPath:o,force:e.force===!0,...e.concurrency!==void 0?{concurrency:st(e,"concurrency",5)}:{},...e.unit_timeout_ms!==void 0?{unitTimeoutMs:st(e,"unit_timeout_ms",6e5)}:{},onEvent:ui});return[{text:"",data:{}},r.type==="analyze-done"&&r.state==="completed"?G:X]}catch(r){throw nr(r,"RESKIN_ANALYZE_FAILED")}}async function ig(e){if(e.check)return or(e,"assessReskinPaths");let{config:t}=Wn(e),n=lt(O(e.analysis).trim(),"analysis"),o=O(e.markets).split(/[,,]/).map(s=>s.trim()).filter(Boolean);if(!o.length)throw new x("Candidate markets missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass --markets, e.g. --markets \u4E2D\u56FD,\u5370\u5C3C,\u7F8E\u56FD.",data:{expected:["comma-separated markets"],actual:["<empty>"]}});let i=O(e.output).trim(),r=await nn();try{let s=await r.assessReskinPaths({...t,analysisPath:n,markets:o,notes:O(e.notes),onEvent:ui});return i&&s.type==="paths-done"&&s.state==="completed"&&li.writeFileSync(i,JSON.stringify(s,null,2)+`
230
+ `),[{text:"",data:{}},s.type==="paths-done"&&s.state==="completed"?G:X]}catch(s){throw nr(s,"RESKIN_PATHS_FAILED")}}async function rg(e){if(e.check)return or(e,"proposeReskinDirections");let{config:t}=Wn(e),n=lt(me(e),"source script"),o=lt(O(e.analysis).trim(),"analysis"),i=O(e.output).trim(),r=await nn();try{let s=await r.proposeReskinDirections({...t,sourcePath:n,analysisPath:o,notes:O(e.notes),custom:O(e.custom),market:O(e.market).trim(),rating:O(e.rating).trim(),avoid:(Array.isArray(e.avoid)?e.avoid:[]).map(c=>String(c).trim()).filter(Boolean),onEvent:ui});return i&&s.type==="direction-done"&&s.state==="completed"&&li.writeFileSync(i,JSON.stringify(s,null,2)+`
231
+ `),[{text:"",data:{}},s.type==="direction-done"&&s.state==="completed"?G:X]}catch(s){throw nr(s,"RESKIN_DIRECTION_FAILED")}}async function sg(e){if(e.check)return or(e,"buildReskinPlan");let{config:t}=Wn(e),n=lt(me(e),"source script"),o=lt(O(e.analysis).trim(),"analysis"),i=lt(O(e.direction).trim(),"direction"),r=O(e.output).trim(),s=O(e.until).trim();if(!r)throw new x("Plan output path missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass -o <\u6362\u58F3\u65B9\u6848.json>.",data:{expected:["plan output path"],actual:["<empty>"]}});if(s&&!vp.includes(s))throw new x("Unknown plan layer.",{exitCode:k,errorCode:"RESKIN_LAYER_UNKNOWN",hint:`Pass --until ${vp.join("|")}.`,data:{expected:[...vp],actual:[s]}});let c=await nn();try{let a=await c.buildReskinPlan({...t,sourcePath:n,analysisPath:o,directionPath:i,planPath:r,...s?{until:s}:{},force:e.force===!0,...e.unit_timeout_ms!==void 0?{unitTimeoutMs:st(e,"unit_timeout_ms",18e5)}:{},onEvent:ui}),d=a.type==="plan-done"&&a.state!=="failed";return[{text:"",data:{}},d?G:X]}catch(a){throw nr(a,"RESKIN_PLAN_FAILED")}}async function ag(e){let t=O(e.review_model).trim()?Wn({...e,model:e.review_model}).config:void 0;if(e.check)return or(e,"writeReskinScript");let{config:n}=Wn(e),o=me(e),i=lt(O(e.source).trim(),"source script"),r=lt(O(e.analysis).trim(),"analysis"),s=lt(O(e.plan).trim(),"plan"),c=Xr(O(e.episodes)),a=await nn();try{let d=await a.writeReskinScript({...n,sourcePath:i,analysisPath:r,planPath:s,scriptPath:o,...c?{episodes:c}:{},force:e.force===!0,concurrency:st(e,"concurrency",6),...t?{reviewModel:t}:{},episodeTimeoutMs:st(e,"episode_timeout_ms",48e4),onEvent:ui});return[{text:"",data:{}},d.type==="done"&&d.failed.length===0?G:X]}catch(d){throw nr(d,"RESKIN_WRITE_FAILED")}}async function cg(e){if(e.check)return or(e,"reviewReskinScript");let{config:t}=Wn(e),n=lt(me(e),"reskinned script"),o=lt(O(e.source).trim(),"source script"),i=lt(O(e.analysis).trim(),"analysis"),r=lt(O(e.plan).trim(),"plan"),s=Xr(O(e.episodes)),c=await nn();try{let a=await c.reviewReskinScript({...t,scriptPath:n,sourcePath:o,analysisPath:i,planPath:r,...s?{episodes:s}:{},concurrency:st(e,"concurrency",10),converge:e.converge!==!1,convergeOnly:e.converge_only===!0,maxSteps:st(e,"max_steps",300),episodeTimeoutMs:st(e,"episode_timeout_ms",48e4),onEvent:ui});return[{text:"",data:{}},a.some(d=>(d.type==="episode"||d.type==="global")&&d.state==="failed")?X:G]}catch(a){throw nr(a,"RESKIN_REVIEW_FAILED")}}async function dg(e){let t=e._args??[],n=lt(O(t[0]).trim(),"batch manifest"),o=O(e.output).trim();if(!o)throw new x("Batch output folder missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass -o <folder>; each drama gets its own project folder inside it.",data:{expected:["batch output folder"],actual:["<empty>"]}});let i=O(e.until).trim();if(i&&!es.includes(i))throw new x("Unknown batch step.",{exitCode:k,errorCode:"RESKIN_LAYER_UNKNOWN",hint:`Pass --until ${es.join("|")}.`,data:{expected:[...es],actual:[i]}});let r;try{r=Xm(n)}catch(l){throw new x("Batch manifest is invalid.",{exitCode:k,errorCode:"RESKIN_BATCH_INVALID",hint:"Fix the manifest and run again.",data:{expected:["{ dramas: [{ source, ... }] }"],actual:[l instanceof Error?l.message:String(l)]}})}let s=O(e.pick).trim();s&&(r.pick=s==="recommended"?"recommended":st(e,"pick",1));let c=new Map(Object.values(r.models).map(l=>[l,Wn({...e,model:l}).config])),a=await nn();li.mkdirSync(o,{recursive:!0});let p=(await eg(r,a,{outputDir:o,until:i||void 0,concurrency:st(e,"concurrency",2),attempts:st(e,"attempts",3),config:l=>c.get(l),onEvent:ui})).filter(l=>l.state==="failed").length;return[{text:"",data:{}},p?X:G]}function pg(e,t){ee(e.command("review"),"write").description("\u6D3E\u53D1 agent \u5BA1\u6838\u5267\u672C\uFF1A\u7ED9 -s \u5BF9\u7167\u6587\u672C\u3001\u6F2B\u753B\u6216\u89C6\u9891\u539F\u7A3F\uFF0C\u4E0D\u7ED9\u5219\u68C0\u67E5\u5267\u672C\u5185\u90E8\u4E00\u81F4\u6027").option("-s, --source-path <path>","\u6587\u672C/\u6F2B\u753B ingest \u5DE5\u4F5C\u533A\u3001\u539F txt/md/docx/PDF \u6216\u89C6\u9891\u6587\u4EF6/\u76EE\u5F55").option("--video <path>","\u7B2C N \u96C6\u7684\u89C6\u9891\uFF1B\u6309\u96C6\u987A\u5E8F\u91CD\u590D\u4F20\uFF0C\u8986\u76D6 -s \u7684\u76EE\u5F55\u6392\u5E8F",(i,r)=>[...r,i],[]).option("--episodes <list>","\u53EA\u5BA1\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u5267\uFF09").option("--concurrency <n>","\u540C\u65F6\u5728\u98DE\u7684\u96C6\u6570",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u8D85\u65F6\uFF1B\u5230\u70B9\u6536\u5C3E\u5E76\u4FDD\u7559\u5DF2\u8BB0\u5F55\u7684\u7ED3\u8BBA",Number).option("--max-steps <n>","\u5355\u96C6\u6700\u591A\u51E0\u6B65\u5DE5\u5177\u8C03\u7528",Number).option("--media-budget <n>","\u5355\u96C6\u6700\u591A\u51E0\u6B21\u89C6\u9891\u6838\u5BF9",Number).option("--converge-only","\u53EA\u6267\u884C\u5168\u5267\u6536\u655B\uFF0C\u4E0D\u91CD\u65B0\u5BA1\u6838\u5404\u96C6").option("--resume-log <path>","\u4ECE\u5F53\u524D\u5267\u672C\u7684\u65E2\u6709\u5BA1\u6838\u65E5\u5FD7\u7EED\u8DD1\uFF0C\u4FDD\u7559\u5DF2\u5B8C\u6210\u5355\u5143\uFF1B\u591A\u4EFD\u65E5\u5FD7\u6309\u65F6\u95F4\u5148\u540E\u91CD\u590D\u4F20\u5165",(i,r=[])=>[...r,i]).option("--no-converge","\u8DF3\u8FC7\u5168\u5267\u6536\u655B\u9636\u6BB5").option("--model <profile>","\u8986\u76D6 LLM profile\uFF08\u89C6\u9891/\u7EAF\u5267\u672C\u9ED8\u8BA4 review-agent\uFF0C\u6587\u672C review-text\uFF0C\u6F2B\u753B review-comic\uFF09").option("--llm-config <path>","LLM configuration file").option("--check","\u53EA\u68C0\u67E5\u6A21\u578B\u4E0E agent \u662F\u5426\u5C31\u7EEA\uFF0C\u4E0D\u5BA1\u6838").action(H(qm,t));let n=e.command("reskin").description("\u6362\u58F3\u4EFF\u5199\uFF1A\u62C6\u89E3\u539F\u5267\uFF0C\u63D0\u51FA\u65B0\u58F3\u65B9\u5411\uFF0C\u9010\u5C42\u5B9A\u6362\u58F3\u65B9\u6848\uFF08\u6574\u4F53\u65B9\u6848 \u2192 \u4E8B\u4EF6 \u2192 \u8282\u62CD\uFF09\uFF0C\u6309\u7ED3\u6784\u8868\u9010\u96C6\u5199\u65B0\u5267\uFF0C\u518D\u505A\u6362\u58F3\u5BA1\u6838"),o=i=>i.option("--model <profile>","\u8986\u76D6 LLM profile\uFF08\u9ED8\u8BA4 reskin\uFF09").option("--no-fallback","\u53EA\u7528\u6240\u9009\u6A21\u578B\uFF0C\u5931\u8D25\u65F6\u4E0D\u6362\u7528\u5176\u4ED6\u6A21\u578B\uFF08\u9ED8\u8BA4\u6309\u914D\u7F6E\u7684\u964D\u7EA7\u987A\u5E8F\u6362\u7528\uFF09").option("--llm-config <path>","LLM configuration file").option("--check","\u53EA\u68C0\u67E5\u6A21\u578B\u4E0E agent \u662F\u5426\u5C31\u7EEA");o(ee(n.command("analyze"),"read").description("\u62C6\u89E3\u539F\u5267\uFF1A\u5148\u901A\u8BFB\u5168\u5267\u5212\u5206\u9636\u6BB5\u4E0E\u4E8B\u4EF6\uFF0C\u518D\u6309\u9636\u6BB5\u5E76\u884C\u5199\u4E8B\u4EF6\u4E8B\u5B9E\u3001\u6309\u96C6\u5E76\u884C\u5207\u8282\u62CD\uFF0C\u540C\u65F6\u5F52\u7EB3\u5168\u5267\u753B\u50CF\uFF08\u539F\u5267\u5730\u533A\u4E0E\u53F0\u8BCD\u8BED\u8A00\u3001\u6362\u58F3\u9002\u5408\u5EA6\uFF09\u3002-p \u4E3A\u539F\u5267\u5267\u672C\uFF1B\u5DF2\u5B8C\u6210\u7684\u5355\u5143\u4FDD\u5B58\u5728\u8F93\u51FA\u6587\u4EF6\u65C1\u7684 .cache/analyze.json\uFF0C\u518D\u6B21\u8FD0\u884C\u4ECE\u65AD\u70B9\u7EE7\u7EED").option("-o, --output <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--force","\u5FFD\u7565\u5DF2\u4FDD\u5B58\u7684\u8FDB\u5EA6\u91CD\u65B0\u62C6\u89E3").option("--concurrency <n>","\u5E76\u884C\u7684\u5355\u5143\u6570",Number).option("--unit-timeout-ms <ms>","\u5355\u4E2A\u5355\u5143\u7684\u8D85\u65F6",Number)).action(H(og,t)),o(n.command("paths").description("\u9009\u9898\u5224\u65AD\uFF1A\u8BFB\u539F\u5267\u62C6\u89E3\u7684\u753B\u50CF\u4E0E\u5927\u7EB2\uFF0C\u9010\u4E2A\u5019\u9009\u5E02\u573A\u5217\u51FA\u8D70\u5F97\u901A\u7684\u6539\u7F16\u8DEF\u5F84\uFF08\u540C\u5E02\u573A\u6362\u8F7D\u4F53\u3001\u8DE8\u5E02\u573A\u672C\u5730\u5316\u3001\u8DE8\u5E02\u573A\u6362\u58F3\u3001\u6362\u4E16\u754C\u89C2\uFF09\uFF0C\u7ED9\u51FA\u5EFA\u8BAE\u505A\u51E0\u4E2A\u7248\u672C").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--markets <list>","\u5019\u9009\u5E02\u573A\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u5FC5\u586B\uFF09\uFF0C\u5982 \u4E2D\u56FD,\u5370\u5C3C,\u7F8E\u56FD").option("--notes <text>","\u7528\u6237\u8981\u6C42\u4E0E\u4E1A\u52A1\u4F18\u5148").option("-o, --output <path>","\u628A\u7ED3\u679C\u53E6\u5B58\u4E3A JSON")).action(H(ig,t)),o(ee(n.command("direction"),"read").description("\u63D0\u51FA 2\u20133 \u4E2A\u5019\u9009\u65B0\u58F3\uFF1B\u7ED9\u51FA --custom \u65F6\u5224\u65AD\u7528\u6237\u6307\u5B9A\u7684\u65B9\u5411\u662F\u5426\u53EF\u884C\u5E76\u6309\u5B83\u8BBE\u8BA1\u4E00\u4E2A\u5019\u9009\u3002-p \u4E3A\u539F\u5267\u5267\u672C").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--notes <text>","\u7528\u6237\u7684\u6362\u58F3\u8981\u6C42").option("--custom <text>","\u7528\u6237\u6307\u5B9A\u7684\u6362\u58F3\u65B9\u5411").option("--market <text>","\u65B0\u5267\u9762\u5411\u7684\u76EE\u6807\u5E02\u573A\uFF0C\u9ED8\u8BA4\u540C\u539F\u5267").option("--rating <text>","\u5C3A\u5EA6\u8981\u6C42\uFF0C\u9ED8\u8BA4\u540C\u539F\u5267").option("--avoid <shell>","\u8FD9\u90E8\u539F\u5267\u5DF2\u505A\u8FC7\u7684\u7248\u672C\u7684\u58F3\uFF0C\u53EF\u91CD\u590D\u7ED9\u51FA\uFF1B\u65B0\u5019\u9009\u4E0E\u5B83\u4EEC\u660E\u663E\u4E0D\u540C",(i,r=[])=>[...r,i]).option("-o, --output <path>","\u628A\u7ED3\u679C\u53E6\u5B58\u4E3A JSON")).action(H(rg,t)),o(ee(n.command("plan"),"read").description("\u9010\u5C42\u751F\u6210\u6362\u58F3\u65B9\u6848\uFF1A\u6574\u4F53\u65B9\u6848\uFF08\u542B\u9636\u6BB5\u8D70\u5411\uFF09\u2192 \u5404\u9636\u6BB5\u4E8B\u4EF6 \u2192 \u5404\u9636\u6BB5\u8282\u62CD\uFF0C\u4E0B\u5C42\u53EF\u56DE\u6539\u4E0A\u5C42\u5E76\u590D\u67E5\u53D7\u5F71\u54CD\u7684\u90E8\u5206\u3002-p \u4E3A\u539F\u5267\u5267\u672C\uFF1B\u5DF2\u6709\u65B9\u6848\u65F6\u4ECE\u672A\u5B8C\u6210\u7684\u90E8\u5206\u7EE7\u7EED").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--direction <path>","\u9009\u5B9A\u7684\u6362\u58F3\u65B9\u5411\u8BF4\u660E\uFF08\u5FC5\u586B\uFF09").option("-o, --output <path>","\u6362\u58F3\u65B9\u6848 JSON\uFF08\u5FC5\u586B\uFF09").option("--until <layer>","\u505A\u5230\u8FD9\u4E00\u5C42\u540E\u6682\u505C\uFF1Aoverall | events | beats").option("--force","\u5FFD\u7565\u5DF2\u6709\u65B9\u6848\u91CD\u65B0\u751F\u6210").option("--unit-timeout-ms <ms>","\u5355\u4E2A\u5355\u5143\u7684\u8D85\u65F6",Number)).action(H(sg,t)),o(ee(n.command("write"),"write").description("\u6309\u6362\u58F3\u65B9\u6848\u7684\u7ED3\u6784\u8868\u5199\u65B0\u5267\uFF1A\u9636\u6BB5\u5185\u6309\u96C6\u5E8F\u5199\uFF0C\u9636\u6BB5\u4E4B\u95F4\u5E76\u884C\uFF1B\u53EF\u9010\u96C6\u5BA1\u6838\u5E76\u4F20\u9012\u8D26\u672C\u3002-p \u4E3A\u65B0\u5267\u5267\u672C\uFF0C\u4E0D\u5B58\u5728\u6216\u6362\u540D\u6362\u5916\u89C2\u53D8\u5316\u65F6\u4ECE\u539F\u5267\u590D\u5236\uFF1B\u6BCF\u6761\u6B63\u6587\u8BB0\u4E0B\u6240\u5C5E\u7684\u65B0\u8282\u62CD\uFF0C\u4E0D\u5199\u65F6\u95F4\u6233").option("--source <path>","\u539F\u5267\u5267\u672C\uFF08\u5FC5\u586B\uFF09").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--plan <path>","\u5DF2\u5B8C\u6210\u7684\u6362\u58F3\u65B9\u6848 JSON\uFF08\u5FC5\u586B\uFF09").option("--episodes <list>","\u53EA\u5199\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u5267\u672A\u5B8C\u6210\u7684\u96C6\uFF09").option("--force","\u6240\u9009\u7684\u96C6\u5DF2\u5199\u8FC7\u4E5F\u91CD\u5199").option("--review-model <profile>","\u9010\u96C6\u5199\u5B8C\u5373\u7528\u6B64 profile \u5BA1\u6838\uFF0C\u8D26\u672C\u4F20\u7ED9\u4E0B\u4E00\u96C6").option("--concurrency <n>","\u540C\u65F6\u8FD0\u884C\u7684\u9636\u6BB5\u94FE\u6570\uFF08\u9ED8\u8BA4 6\uFF09",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u8D85\u65F6",Number)).action(H(ag,t)),o(ee(n.command("review"),"write").description("\u6362\u58F3\u5BA1\u6838\uFF1A\u6309\u96C6\u5E8F\u901A\u8BFB\uFF0C\u9010\u96C6\u5BA1\u6362\u5F97\u662F\u5426\u5408\u7406\u3001\u662F\u5426\u770B\u5F97\u61C2\u4E0E\u901A\u987A\u3001\u524D\u540E\u662F\u5426\u8FDE\u8D2F\u3001\u9020\u578B\u4E0E\u573A\u666F\u5F15\u7528\u662F\u5426\u51C6\u786E\uFF0C\u5904\u7406\u7A0B\u5E8F\u68C0\u67E5\u7ED3\u679C\uFF0C\u518D\u505A\u5168\u5267\u6536\u5C3E\u3002-p \u4E3A\u65B0\u5267\u5267\u672C\uFF1B\u4E8B\u4EF6\u683C\u5F0F\u4E0E review \u76F8\u540C").option("--source <path>","\u539F\u5267\u5267\u672C\uFF08\u5FC5\u586B\uFF09").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--plan <path>","\u6362\u58F3\u65B9\u6848 JSON\uFF08\u5FC5\u586B\uFF09").option("--episodes <list>","\u53EA\u5BA1\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u90E8\uFF09").option("--concurrency <n>","\u540C\u65F6\u8FDB\u884C\u7684\u9636\u6BB5\u94FE\u6570\uFF08\u9ED8\u8BA4 10\uFF09",Number).option("--max-steps <n>","\u6BCF\u96C6\u6700\u591A\u51E0\u6B65\u5DE5\u5177\u8C03\u7528",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u8D85\u65F6",Number).option("--converge-only","\u53EA\u6267\u884C\u9636\u6BB5\u9996\u96C6\u63A5\u7F1D\u590D\u6838\u4E0E\u5168\u5267\u6536\u5C3E").option("--no-converge","\u8DF3\u8FC7\u5168\u5267\u6536\u5C3E")).action(H(cg,t)),n.command("batch").argument("<manifest>","\u6279\u91CF\u6E05\u5355 JSON\uFF1A{ dramas: [{ id, source, market, language, rating, notes, custom, pick, avoid }], models, prices, pick }").description("\u65E0\u4EBA\u503C\u5B88\u6279\u91CF\u6362\u58F3\uFF1A\u6BCF\u90E8\u5267\u5728 -o \u4E0B\u6709\u81EA\u5DF1\u7684\u9879\u76EE\u76EE\u5F55\uFF0C\u4F9D\u6B21\u62C6\u89E3 \u2192 \u65B9\u5411 \u2192 \u65B9\u6848 \u2192 \u5199\u4F5C \u2192 \u5BA1\u6838\uFF0C\u6BCF\u6B65\u4ECE\u5DF2\u4FDD\u5B58\u7684\u8FDB\u5EA6\u7EE7\u7EED\u3002\u62C6\u89E3\u8BC4\u51FA\u7684\u9002\u5408\u5EA6\u4F4E\u4E8E 3 \u4E14\u6CA1\u5199 pick \u65F6\u505C\u5728\u62C6\u89E3\u540E\uFF0C\u6307\u5B9A\u65B9\u5411\u4E0D\u53EF\u884C\u6216\u9700\u8981\u4EBA\u5DE5\u9009\u65B9\u5411\u65F6\u505C\u5728\u65B9\u5411\u6B65\uFF1B\u8865\u4E0A pick \u540E\u518D\u8FD0\u884C\u5373\u4ECE\u65B9\u5411\u7EE7\u7EED\u3002\u8FDB\u5EA6\u4E0E\u62A5\u544A\u5199\u5728 -o \u4E0B\u7684 batch-report.json / batch-report.md").option("-o, --output <dir>","\u6279\u91CF\u8F93\u51FA\u76EE\u5F55\uFF08\u5FC5\u586B\uFF09").option("--concurrency <n>","\u540C\u65F6\u8FDB\u884C\u7684\u5267\u6570\uFF08\u9ED8\u8BA4 2\uFF09",Number).option("--attempts <n>","\u6BCF\u6B65\u6700\u591A\u8FD0\u884C\u51E0\u6B21\uFF0C\u6BCF\u6B21\u4ECE\u4E0A\u6B21\u8FDB\u5EA6\u7EE7\u7EED\uFF08\u9ED8\u8BA4 3\uFF09",Number).option("--pick <n|recommended>","\u6CA1\u5199 pick \u7684\u5267\u7528\u8FD9\u4E2A\u5019\u9009\uFF1B\u4E0D\u7ED9\u65F6\u505C\u4E0B\u7B49\u4EBA\u5DE5\u9009\u62E9").option("--until <step>","\u505A\u5230\u8FD9\u4E00\u6B65\u540E\u505C\u4E0B\uFF1Aanalyze | direction | plan | write | review").option("--no-fallback","\u53EA\u7528\u6240\u9009\u6A21\u578B\uFF0C\u5931\u8D25\u65F6\u4E0D\u6362\u7528\u5176\u4ED6\u6A21\u578B\uFF08\u9ED8\u8BA4\u6309\u914D\u7F6E\u7684\u964D\u7EA7\u987A\u5E8F\u6362\u7528\uFF09").option("--llm-config <path>","LLM configuration file").action(H(dg,t))}import*as lg from"node:fs";var No="\u5730\u5740\uFF1A\u96C6 `3`\u3001\u573A `3-2`\u3001\u5355\u6761 `3-2-5`\u3001\u6B63\u5F0F ID\u3001\u8D44\u4EA7\u540D\u3001\u6216 `<\u8D44\u4EA7>/<\u72B6\u6001>`";function Ke(e){let t=me(e);if(!lg.existsSync(t))throw new x("Local script file not found.",{exitCode:k,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[t]}});return Yd(t)}function he(e,t){let n=e[t];return typeof n=="string"?n:void 0}function fi(e,t){let n=e[t];if(n==null||n==="")return;let o=Number(n);if(!Number.isFinite(o))throw new x(`--${t} must be a number.`,{exitCode:k,errorCode:"OPTION_NOT_NUMBER",data:{actual:[String(n)]}});return o}function ye(e,t=0){return(e._args??[])[t]??""}function Rp(e){return Array.isArray(e)?e.map(String):typeof e=="string"?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function at(e,t,n=()=>({})){try{let o=e();return[{text:o,data:{op:t,changed:!1,text:o,...n()}},G]}catch(o){throw o instanceof x?o:new x(o instanceof Error?o.message:String(o),{exitCode:k,errorCode:o?.code??"SCRIPT_TOOL_FAILED"})}}function ug(e,t){let n=ee(e.command("read [addr]"),"read").description(`\u8BFB\u4EFB\u610F\u8282\u70B9\uFF1B\u4E0D\u7ED9\u5730\u5740\u8FD4\u56DE\u5267\u672C\u5361\u3002${No}`).option("--outline","\u53EA\u8981\u573A\u7ED3\u6784\uFF0C\u4E0D\u8981\u6B63\u6587").option("--context <n>","\u5355\u6761 action \u524D\u540E\u5404\u5E26\u51E0\u6761\uFF08\u9ED8\u8BA4 3\uFF09").option("--plain","\u53BB\u6389\u951A\u70B9\u4E0E\u65F6\u95F4\u6233\uFF08\u53EA\u8BFB\uFF0C\u4E0D\u53EF\u56DE\u5199\uFF09").action(H(y=>{let _=Ke(y);return at(()=>pa(_,ye(y),{...y.outline?{depth:"outline"}:{},...y.plain?{plain:!0}:{},...fi(y,"context")!==void 0?{context:fi(y,"context")}:{}}),"read",()=>ye(y)?{}:{document:_.raw})},t));Me(n,[No]);let o=ee(e.command("scan <episode>"),"read").description("\u4E00\u6B21\u8FD4\u56DE\u67D0\u96C6\u7684\u5B8C\u6574\u4E0A\u4E0B\u6587\uFF1A\u573A\u7ED3\u6784 + \u5168\u90E8\u6B63\u6587 + \u5F53\u524D\u6821\u9A8C\u95EE\u9898").action(H(y=>at(()=>{let _=Ke(y),S=ye(y);return[`## \u573A\u7ED3\u6784
232
+ ${pa(_,S,{depth:"outline"})}`,`## \u6B63\u6587
233
+ ${pa(_,S)}`,`## \u5F53\u524D\u6821\u9A8C\u95EE\u9898
234
+ ${pp(_,{})}`].join(`
234
235
 
235
- `)},"scan"),t));Me(o,["\u96C6\u53F7\uFF0C\u4ECE 1 \u5F00\u59CB"]);let i=te(e.command("find [query]"),"read").description("\u6309\u6B63\u6587\u6B63\u5219 / \u8BF4\u8BDD\u4EBA / \u7C7B\u578B\u5B9A\u4F4D action\uFF0C\u8FD4\u56DE\u951A\u70B9 + \u547D\u4E2D\u7A97\u53E3").option("-i, --in <addr>",`\u9650\u5236\u8303\u56F4\uFF0C${No}`).option("-a, --speaker <name>","\u4EBA\u7269\u540D\u6216 actor id").option("-t, --type <type>","action | dialogue | inner_thought | transition").option("--limit <n>","\u6700\u591A\u8FD4\u56DE\u51E0\u6761\uFF08\u9ED8\u8BA4 40\uFF09").option("--full","\u8FD4\u56DE\u6574\u6761\u6B63\u6587\u800C\u4E0D\u662F\u547D\u4E2D\u7A97\u53E3").action(H(y=>at(()=>tm(je(y),ye(y),{...he(y,"in")?{in:he(y,"in")}:{},...he(y,"speaker")?{speaker:he(y,"speaker")}:{},...he(y,"type")?{type:he(y,"type")}:{},...ui(y,"limit")!==void 0?{limit:ui(y,"limit")}:{},...y.full?{full:!0}:{}}),"find"),t));Me(i,["\u6B63\u5219\uFF1B\u53EA\u6309 speaker/type \u8FC7\u6EE4\u65F6\u53EF\u7701\u7565"]);let r=te(e.command("refs <addr>"),"read").description("\u53EA\u8BFB\u5B9A\u4F4D\u8D44\u4EA7/\u9020\u578B\u7684\u573A\u666F\u7ED1\u5B9A\u3001\u8BF4\u8BDD\u5F15\u7528\u548C\u6B63\u6587\u63D0\u53CA\uFF0C\u8FD4\u56DE\u53EF read \u7684\u5730\u5740\u53CA\u4E0A\u4E0B\u6587").option("--offset <n>","\u4ECE\u7B2C\u51E0\u6761\u5F15\u7528\u7EE7\u7EED\uFF08\u4ECE 0 \u5F00\u59CB\uFF09").option("--limit <n>","\u672C\u6279\u5F15\u7528\u6570\uFF08\u9ED8\u8BA4 20\uFF09").option("--context <n>","\u6B63\u6587\u547D\u4E2D\u524D\u540E\u5404\u51E0\u6761 action\uFF08\u9ED8\u8BA4 3\uFF09").action(H(y=>{let _=np(je(y),ye(y),{offset:ui(y,"offset"),limit:ui(y,"limit"),context:ui(y,"context")});return[{text:op(_),data:{op:"refs",changed:!1,..._}},B]},t));Me(r,["\u4EBA\u7269/\u573A\u666F/\u9053\u5177 ID \u6216\u540D\u79F0\uFF0C\u6216 <\u8D44\u4EA7>/<\u9020\u578B>\uFF1B\u6B63\u6587\u63D0\u53CA\u4E0D\u7B49\u4E8E\u5B9E\u9645\u51FA\u573A"]);let s=te(e.command("span <range>"),"read").description("\u628A\u4E00\u6BB5 action \u6362\u7B97\u6210\u96C6\u5185\u89C6\u9891\u65F6\u95F4\u7A97\u53E3\uFF08\u534A\u5F00\u533A\u95F4\uFF09").action(H(y=>{let _=je(y);return at(()=>nm(_,ye(y)),"span",()=>({rows:[sp(_,ye(y))]}))},t));Me(s,[`${No}\uFF0C\u6216 \`\u8D77ID..\u6B62ID\``]),te(e.command("validate"),"read").description("\u8DD1\u6574\u672C\u6821\u9A8C").action(H(y=>{let _=je(y),x=qi(_);return[{text:fm(_),data:{op:"script.validate",changed:!1,passed:x.ok,script_path:_.path,stats:{actors:_.assets.filter(E=>E.kind==="actor").length,locations:_.assets.filter(E=>E.kind==="location").length,props:_.assets.filter(E=>E.kind==="prop").length,episodes:_.episodes.length,scenes:_.episodes.reduce((E,A)=>E+A.scenes.length,0),actions:bn(_).length},issues:[...x.errors.map(E=>({...E,severity:"error"})),...x.warnings.map(E=>({...E,severity:"warning"}))]}},x.ok?B:co]},t)),te(e.command("issues"),"read").description("\u5217\u5F53\u524D\u6821\u9A8C\u95EE\u9898").option("--severity <severity>","error | warning").option("--code <code>","\u6309 issue code \u8FC7\u6EE4").action(H(y=>at(()=>cp(je(y),{...he(y,"severity")?{severity:he(y,"severity")}:{},...he(y,"code")?{code:he(y,"code")}:{}}),"issues"),t));let c=te(e.command("edit <addr>"),"write").description(`\u6539\u4E00\u4E2A\u8282\u70B9\u7684\u5B57\u6BB5\uFF1B\u5730\u5740\u51B3\u5B9A\u54EA\u4E9B\u5B57\u6BB5\u5408\u6CD5\u3002${No}`).option("--content <text>","action \u6B63\u6587").option("--paren <text>","\u8868\u6F14\u63D0\u793A").option("--no-paren","\u5220\u9664\u8868\u6F14\u63D0\u793A\u5B57\u6BB5").option("--speaker <name>","\u4EBA\u7269\u540D\u6216 `\u540D\u5B57\xB7\u72B6\u6001`\uFF1B\u65C1\u767D/\u5E7F\u64AD/\u753B\u5916/\u7FA4\u58F0\u4EA6\u53EF").option("--ts <time>","\u65F6\u95F4\u6233").option("--no-ts","\u5220\u9664\u65F6\u95F4\u6233").option("--type <type>","action | dialogue | inner_thought | transition").option("--transition <spec>","\u8F6C\u573A\u63D0\u793A `\u76EE\u6807|\u8FC7\u7A0B|\u5BF9\u6BD4`").option("--no-transition","\u5220\u9664\u8F6C\u573A\u63D0\u793A").option("--name <text>","\u8D44\u4EA7 / \u72B6\u6001\u540D").option("--desc <text>","\u8D44\u4EA7 / \u72B6\u6001\u63CF\u8FF0").option("--importance <tier>","featured | background").option("--role <type>","\u4E3B\u89D2 | \u914D\u89D2").option("--alias <list>","\u8D44\u4EA7\u522B\u540D\uFF0C\u9017\u53F7\u5206\u9694").option("--space <space>","\u573A\uFF1Ainterior | exterior").option("--time <time>","\u573A\uFF1Aday | night | dawn | dusk").option("--title <text>","\u96C6 / \u5267\u672C\u6807\u9898").option("--synopsis <text>","\u96C6 / \u5267\u672C\u6897\u6982").option("--logline <text>","\u5267\u672C logline").option("--theme <text>","\u5267\u672C\u4E3B\u9898").option("--worldview <text>","\u5267\u672C\u4E16\u754C\u89C2").option("--style <text>","\u5267\u672C\u98CE\u683C").option("--main <list>","\u4E3B\u8981\u4EBA\u7269 `\u540D\u5B57=\u5B9A\u4F4D,\u2026`").action(H(y=>{let _={};for(let x of["content","speaker","type","name","desc","importance","role","space","time","title","synopsis","logline","theme","worldview","style","main"]){let E=he(y,x);E!==void 0&&(_[x]=E)}for(let x of["paren","ts","transition"])if(y[x]===!1)_[x]=null;else{let E=he(y,x);E!==void 0&&(_[x]=E)}return y.alias!==void 0&&(_.aliases=Op(y.alias)),at(()=>om(je(y),ye(y),_),"edit")},t));Me(c,[No]);let a=te(e.command("insert <addr> <content>"),"write").description("\u5728\u67D0\u6761 action \u524D/\u540E\u63D2\u5165\u4E00\u6761\u65B0 action").requiredOption("-t, --type <type>","action | dialogue | inner_thought | transition").option("--before","\u63D2\u5230\u76EE\u6807\u4E4B\u524D\uFF08\u9ED8\u8BA4\u4E4B\u540E\uFF09").option("-a, --speaker <name>","dialogue / inner_thought \u5FC5\u586B").option("--paren <text>","\u8868\u6F14\u63D0\u793A").action(H(y=>at(()=>im(je(y),ye(y),y.before?"before":"after",he(y,"type"),ye(y,1),he(y,"speaker"),he(y,"paren")),"insert"),t));Me(a,["\u76F8\u90BB action \u7684\u5730\u5740","\u65B0 action \u7684\u6B63\u6587"]);let d=te(e.command("move <addr> <to>"),"write").description("\u628A\u4E00\u6761 action \u632A\u5230\u53E6\u4E00\u6761\u65C1\u8FB9\uFF1B\u8DE8\u573A\u4E5F\u4FDD\u6301 action_id").option("--before","\u632A\u5230\u76EE\u6807\u4E4B\u524D\uFF08\u9ED8\u8BA4\u4E4B\u540E\uFF09").action(H(y=>at(()=>rm(je(y),ye(y),ye(y,1),y.before?"before":"after"),"move"),t));Me(d,["\u8981\u632A\u7684 action","\u76EE\u6807\u90BB\u5C45 action"]);let p=te(e.command("write <addr>"),"write").description("\u7528 read \u8F93\u51FA\u7684\u540C\u4E00\u4EFD\u6B63\u6587\u683C\u5F0F\u56DE\u5199\u6574\u573A / \u6574\u96C6 / \u65B0\u96C6\uFF08`+`\uFF09").option("-f, --file <path>","\u6B63\u6587\u6587\u4EF6\uFF1B\u7701\u7565\u5219\u8BFB stdin").option("--allow-delete","\u5141\u8BB8\u5220\u9664\u6587\u672C\u91CC\u6D88\u5931\u7684\u573A / action").action(H(async y=>{let _=await import("node:fs"),x=he(y,"file"),E=x?_.readFileSync(x,"utf8"):_.readFileSync(0,"utf8");return at(()=>am(je(y),ye(y),E,{allowDelete:!!y.allow_delete}),"write")},t));Me(p,["\u573A / \u96C6\u5730\u5740\uFF0C\u6216 `+` \u8FFD\u52A0\u65B0\u96C6"]);let l=te(e.command("replace <pattern> <to>"),"write").description("\u6279\u91CF\u66FF\u6362\u6B63\u6587\uFF1B\u9ED8\u8BA4\u53EA\u9884\u89C8\uFF0C--apply \u624D\u843D\u76D8\u3002\u8FC7\u6EE4\u53C2\u6570\u4E0E find \u76F8\u540C").option("-i, --in <addr>","\u9650\u5236\u8303\u56F4").option("-a, --speaker <name>","\u9650\u5B9A\u8BF4\u8BDD\u4EBA").option("-t, --type <type>","\u9650\u5B9A action \u7C7B\u578B").option("--apply","\u771F\u7684\u5199\u5165").action(H(y=>at(()=>lm(je(y),ye(y),ye(y,1),{...he(y,"in")?{in:he(y,"in")}:{},...he(y,"speaker")?{speaker:he(y,"speaker")}:{},...he(y,"type")?{type:he(y,"type")}:{},...y.apply?{apply:!0}:{}}),"replace"),t));Me(l,["\u6B63\u5219","\u66FF\u6362\u6210\u4EC0\u4E48"]);let f=te(e.command("ref <scene> <asset>"),"write").description("\u6539\u4E00\u4E2A\u573A\u5BF9\u67D0\u8D44\u4EA7\u7684\u5F15\u7528\uFF1B--state \u662F\u5B8C\u6574\u72B6\u6001\u96C6\u5408\u800C\u975E\u8FFD\u52A0").option("--state <list>","\u5B8C\u6574\u72B6\u6001\u96C6\u5408\uFF08\u540D\u5B57\u6216 ID\uFF09\uFF0C\u9017\u53F7\u5206\u9694\u6216\u91CD\u590D\u7ED9\u51FA",ES,[]).option("--remove","\u5220\u9664\u6574\u6761\u5F15\u7528").action(H(y=>at(()=>pm(je(y),ye(y),ye(y,1),Op(y.state).flatMap(_=>_.split(",")).map(_=>_.trim()).filter(Boolean),!!y.remove),"ref"),t));Me(f,["\u573A\u5730\u5740","\u4EBA\u7269 / \u5730\u70B9 / \u9053\u5177\u7684\u540D\u5B57\u6216 ID"]);let u=te(e.command("asset <kind> <name>"),"write").description("\u767B\u8BB0\u4E00\u4E2A\u65B0\u7684 actor / location / prop").requiredOption("--desc <text>","\u63CF\u8FF0").option("--importance <tier>","featured | background","featured").option("--alias <list>","\u522B\u540D\uFF0C\u9017\u53F7\u5206\u9694").action(H(y=>at(()=>mm(je(y),ye(y),ye(y,1),he(y,"desc")??"",he(y,"importance")??"featured",Op(y.alias)),"asset"),t));Me(u,["actor | location | prop","\u540D\u5B57"]);let g=te(e.command("state <asset> <name>"),"write").description("\u7ED9\u5DF2\u6709\u8D44\u4EA7\u52A0\u4E00\u4E2A\u72B6\u6001\uFF08\u9020\u578B\u6863\u4F4D\uFF09").requiredOption("--desc <text>","\u63CF\u8FF0").action(H(y=>at(()=>gm(je(y),ye(y),ye(y,1),he(y,"desc")??""),"state"),t));Me(g,["\u8D44\u4EA7\u540D\u6216 ID","\u72B6\u6001\u540D"]);let h=te(e.command("del <addr>"),"write").description("\u5220\u9664 action / \u573A / \u96C6 / \u8D44\u4EA7 / \u72B6\u6001").option("--replacement <state>","\u5220\u72B6\u6001\u65F6\u628A\u5F15\u7528\u6539\u5199\u5230\u8FD9\u4E2A\u72B6\u6001").option("--force","\u5BB9\u5668\u975E\u7A7A\u65F6\u4ECD\u7136\u5220\u9664").action(H(y=>at(()=>ym(je(y),ye(y),{...he(y,"replacement")?{replacement:he(y,"replacement")}:{},...y.force?{force:!0}:{}}),"del"),t));Me(h,[No]);let m=te(e.command("merge <src> <dst>"),"write").description("\u628A\u4E00\u4E2A\u8D44\u4EA7\u5E76\u5165\u53E6\u4E00\u4E2A\uFF1A\u5168\u90E8\u573A\u666F\u5F15\u7528\u4E0E speaker \u6539\u5199\u8FC7\u53BB").action(H(y=>at(()=>lp(je(y),ye(y),ye(y,1)),"merge"),t));Me(m,["\u88AB\u5E76\u5165\u7684\u8D44\u4EA7","\u4FDD\u7559\u7684\u8D44\u4EA7"]);let w=te(e.command("ext <addr> [key] [value]"),"write").description("\u8BFB\u6216\u5199\u4EFB\u610F\u8282\u70B9\u7684 extend \u6570\u636E").option("--remove","\u5220\u9664\u8BE5 key").action(H(y=>at(()=>hm(je(y),ye(y),ye(y,1)||void 0,ye(y,2)||void 0,!!y.remove),"ext"),t));Me(w,[No,"extend key","\u503C"])}function ES(e,t){return[...t,e]}import*as Ay from"node:path";var Wn={createExecutor:Bf};import*as el from"node:fs";import*as cr from"node:path";var Mn=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();var es=e=>String(e).padStart(3,"0"),vp=e=>e.normalize("NFC").replace(/\s+/g," ").trim();function pg(e,t={}){let n=[],o=[],i=null,r=null,s=0,c=0,a=new Map,d=(l,f)=>{let u=`text:${l}:${f.chunk}:${f.line_start}:${f.line_end}`,g=(a.get(u)??0)+1;return a.set(u,g),`${u}:${g}`},p=(l,f)=>{let u=l.actors.find(g=>vp(g.name)===vp(f.name));u?f.state&&!u.state&&(u.state=f.state):l.actors.push(f)};for(let l of e)switch(l.kind){case"episode":{s++,i={identity_key:d("episode",l.source),episode_id:`ep_${es(s)}`,scenes:[]},l.title!==void 0&&(i.title=l.title),n.push(i),r=null;break}case"scene":{i||(s++,i={identity_key:d("synthetic-episode",l.source),episode_id:`ep_${es(s)}`,scenes:[]},n.push(i)),c++,r={identity_key:d("scene",l.source),scene_id:`scn_${es(c)}`,location:l.location?{...l.location}:null,actors:(l.actors??[]).map(f=>({...f})),props:(l.props??[]).map(f=>({...f})),actions:[]},l.environment&&(r.environment=l.environment),i.scenes.push(r);break}case"note":o.push({content:l.content,...l.category?{category:l.category}:{},source:l.source});break;case"action":case"transition":{if(!r){o.push({content:l.content,category:"preamble",source:l.source});break}r.actions.push({identity_key:d(l.kind,l.source),type:l.kind,content:l.content});break}case"dialogue":case"inner_thought":{if(!r){o.push({content:l.content,category:"preamble",source:l.source});break}let f={identity_key:d(l.kind,l.source),type:l.kind,content:l.content,speaker:l.speaker};l.emotion!==void 0&&(f.emotion=l.emotion),r.actions.push(f),"name"in l.speaker&&p(r,l.speaker.state!==void 0?{name:l.speaker.name,state:l.speaker.state}:{name:l.speaker.name});break}}return{script:{title:t.title??"",episodes:n},notes:o}}var ts=class{constructor(t,n,o){this.prefix=t;this.kind=n;this.nextStateId=o}prefix;kind;nextStateId;byNorm=new Map;order=[];ensure(t,n){let o=vp(t),i=this.byNorm.get(o);return i||(i={provisional_id:`${this.prefix}_${es(this.order.length+1)}`,kind:this.kind,names:[],states:[],occurrences:[]},this.byNorm.set(o,i),this.order.push(i)),i.names.includes(t)||i.names.push(t),i.occurrences.push(n),i}stateId(t,n){let o=Mn(n),i=t.states.find(s=>Mn(s.name)===o);if(i)return i.id;let r=this.nextStateId();return t.states.push({name:n,id:r}),r}list(){return this.order}};function xS(e){let t=[{state_id:"default",state_name:"default",description:""}];for(let n of e.states)t.push({state_id:n.id,state_name:n.name,description:""});return t}function ka(e){let t=0,n=()=>`st_${es(++t)}`,o=new ts("act","actor",n),i=new ts("loc","location",n),r=new ts("prp","prop",n),s={episode:{},scene:{},action:{}},c={episode:new Set,scene:new Set,action:new Set},a=(u,g,h)=>{if(!h||c[u].has(h))throw new Error(`Duplicate or missing ${u} source identity: ${h}`);c[u].add(h),s[u][g]=h},d=(u,g,h,m)=>{let w=u.ensure(g.name,h),y={[m]:w.provisional_id};return g.state!==void 0&&(y.state_id=u.stateId(w,g.state)),y},p=e.episodes.map((u,g)=>(a("episode",u.episode_id,u.identity_key),{episode_id:u.episode_id,...u.title?{title:u.title}:{},scenes:u.scenes.map((h,m)=>{let w=`${u.episode_id}/${h.scene_id}`;a("scene",w,h.identity_key);let y={episode:g,scene:m},_=h.location?d(i,h.location,y,"location_id"):null,x=h.actors.map(b=>d(o,b,y,"actor_id")),E=h.props.map(b=>d(r,b,y,"prop_id")),A=h.actions.map((b,C)=>{a("action",`${w}#${C}`,b.identity_key);let R={type:b.type,content:b.content};if(b.speaker)if("name"in b.speaker){let I=o.ensure(b.speaker.name,y),O={actor_id:I.provisional_id};b.speaker.state!==void 0&&(O.state_id=o.stateId(I,b.speaker.state)),R.speaker=O}else R.speaker=b.speaker.label!==void 0?{kind:b.speaker.kind,label:b.speaker.label}:{kind:b.speaker.kind};return(b.type==="dialogue"||b.type==="inner_thought")&&(b.parenthetical!==void 0?R.emotion=b.parenthetical:b.emotion!==void 0&&(R.emotion=b.emotion)),b.extend!==void 0&&(R.extend=b.extend),R});return{scene_id:h.scene_id,...h.environment?{environment:h.environment}:{},location:_,actors:x,props:E,actions:A}})})),l=(u,g,h)=>u.list().map(m=>({[g]:m.provisional_id,[h]:m.names[0]??m.provisional_id,aliases:m.names.slice(1),description:"",states:xS(m)}));return{script:{version:3,title:e.title,worldview:"",style:"",actors:l(o,"actor_id","actor_name"),locations:l(i,"location_id","location_name"),props:l(r,"prop_id","prop_name"),episodes:p},assets:[...o.list(),...i.list(),...r.list()],identityKeys:s}}function lg(e,t={}){let n=t.maxChars??500,o=e.split(`
236
+ `)},"scan"),t));Me(o,["\u96C6\u53F7\uFF0C\u4ECE 1 \u5F00\u59CB"]);let i=ee(e.command("find [query]"),"read").description("\u6309\u6B63\u6587\u6B63\u5219 / \u8BF4\u8BDD\u4EBA / \u7C7B\u578B\u5B9A\u4F4D action\uFF0C\u8FD4\u56DE\u951A\u70B9 + \u547D\u4E2D\u7A97\u53E3").option("-i, --in <addr>",`\u9650\u5236\u8303\u56F4\uFF0C${No}`).option("-a, --speaker <name>","\u4EBA\u7269\u540D\u6216 actor id").option("-t, --type <type>","action | dialogue | inner_thought | transition").option("--limit <n>","\u6700\u591A\u8FD4\u56DE\u51E0\u6761\uFF08\u9ED8\u8BA4 40\uFF09").option("--full","\u8FD4\u56DE\u6574\u6761\u6B63\u6587\u800C\u4E0D\u662F\u547D\u4E2D\u7A97\u53E3").action(H(y=>at(()=>im(Ke(y),ye(y),{...he(y,"in")?{in:he(y,"in")}:{},...he(y,"speaker")?{speaker:he(y,"speaker")}:{},...he(y,"type")?{type:he(y,"type")}:{},...fi(y,"limit")!==void 0?{limit:fi(y,"limit")}:{},...y.full?{full:!0}:{}}),"find"),t));Me(i,["\u6B63\u5219\uFF1B\u53EA\u6309 speaker/type \u8FC7\u6EE4\u65F6\u53EF\u7701\u7565"]);let r=ee(e.command("refs <addr>"),"read").description("\u53EA\u8BFB\u5B9A\u4F4D\u8D44\u4EA7/\u9020\u578B\u7684\u573A\u666F\u7ED1\u5B9A\u3001\u8BF4\u8BDD\u5F15\u7528\u548C\u6B63\u6587\u63D0\u53CA\uFF0C\u8FD4\u56DE\u53EF read \u7684\u5730\u5740\u53CA\u4E0A\u4E0B\u6587").option("--offset <n>","\u4ECE\u7B2C\u51E0\u6761\u5F15\u7528\u7EE7\u7EED\uFF08\u4ECE 0 \u5F00\u59CB\uFF09").option("--limit <n>","\u672C\u6279\u5F15\u7528\u6570\uFF08\u9ED8\u8BA4 20\uFF09").option("--context <n>","\u6B63\u6587\u547D\u4E2D\u524D\u540E\u5404\u51E0\u6761 action\uFF08\u9ED8\u8BA4 3\uFF09").action(H(y=>{let _=ip(Ke(y),ye(y),{offset:fi(y,"offset"),limit:fi(y,"limit"),context:fi(y,"context")});return[{text:rp(_),data:{op:"refs",changed:!1,..._}},G]},t));Me(r,["\u4EBA\u7269/\u573A\u666F/\u9053\u5177 ID \u6216\u540D\u79F0\uFF0C\u6216 <\u8D44\u4EA7>/<\u9020\u578B>\uFF1B\u6B63\u6587\u63D0\u53CA\u4E0D\u7B49\u4E8E\u5B9E\u9645\u51FA\u573A"]);let s=ee(e.command("span <range>"),"read").description("\u628A\u4E00\u6BB5 action \u6362\u7B97\u6210\u96C6\u5185\u89C6\u9891\u65F6\u95F4\u7A97\u53E3\uFF08\u534A\u5F00\u533A\u95F4\uFF09").action(H(y=>{let _=Ke(y);return at(()=>rm(_,ye(y)),"span",()=>({rows:[cp(_,ye(y))]}))},t));Me(s,[`${No}\uFF0C\u6216 \`\u8D77ID..\u6B62ID\``]),ee(e.command("validate"),"read").description("\u8DD1\u6574\u672C\u6821\u9A8C").action(H(y=>{let _=Ke(y),S=Wi(_);return[{text:hm(_),data:{op:"script.validate",changed:!1,passed:S.ok,script_path:_.path,stats:{actors:_.assets.filter(E=>E.kind==="actor").length,locations:_.assets.filter(E=>E.kind==="location").length,props:_.assets.filter(E=>E.kind==="prop").length,episodes:_.episodes.length,scenes:_.episodes.reduce((E,A)=>E+A.scenes.length,0),actions:bn(_).length},issues:[...S.errors.map(E=>({...E,severity:"error"})),...S.warnings.map(E=>({...E,severity:"warning"}))]}},S.ok?G:po]},t)),ee(e.command("issues"),"read").description("\u5217\u5F53\u524D\u6821\u9A8C\u95EE\u9898").option("--severity <severity>","error | warning").option("--code <code>","\u6309 issue code \u8FC7\u6EE4").action(H(y=>at(()=>pp(Ke(y),{...he(y,"severity")?{severity:he(y,"severity")}:{},...he(y,"code")?{code:he(y,"code")}:{}}),"issues"),t));let c=ee(e.command("edit <addr>"),"write").description(`\u6539\u4E00\u4E2A\u8282\u70B9\u7684\u5B57\u6BB5\uFF1B\u5730\u5740\u51B3\u5B9A\u54EA\u4E9B\u5B57\u6BB5\u5408\u6CD5\u3002${No}`).option("--content <text>","action \u6B63\u6587").option("--paren <text>","\u8868\u6F14\u63D0\u793A").option("--no-paren","\u5220\u9664\u8868\u6F14\u63D0\u793A\u5B57\u6BB5").option("--speaker <name>","\u4EBA\u7269\u540D\u6216 `\u540D\u5B57\xB7\u72B6\u6001`\uFF1B\u65C1\u767D/\u5E7F\u64AD/\u753B\u5916/\u7FA4\u58F0\u4EA6\u53EF").option("--ts <time>","\u65F6\u95F4\u6233").option("--no-ts","\u5220\u9664\u65F6\u95F4\u6233").option("--type <type>","action | dialogue | inner_thought | transition").option("--transition <spec>","\u8F6C\u573A\u63D0\u793A `\u76EE\u6807|\u8FC7\u7A0B|\u5BF9\u6BD4`").option("--no-transition","\u5220\u9664\u8F6C\u573A\u63D0\u793A").option("--name <text>","\u8D44\u4EA7 / \u72B6\u6001\u540D").option("--desc <text>","\u8D44\u4EA7 / \u72B6\u6001\u63CF\u8FF0").option("--importance <tier>","featured | background").option("--role <type>","\u4E3B\u89D2 | \u914D\u89D2").option("--alias <list>","\u8D44\u4EA7\u522B\u540D\uFF0C\u9017\u53F7\u5206\u9694").option("--space <space>","\u573A\uFF1Ainterior | exterior").option("--time <time>","\u573A\uFF1Aday | night | dawn | dusk").option("--title <text>","\u96C6 / \u5267\u672C\u6807\u9898").option("--synopsis <text>","\u96C6 / \u5267\u672C\u6897\u6982").option("--logline <text>","\u5267\u672C logline").option("--theme <text>","\u5267\u672C\u4E3B\u9898").option("--worldview <text>","\u5267\u672C\u4E16\u754C\u89C2").option("--style <text>","\u5267\u672C\u98CE\u683C").option("--main <list>","\u4E3B\u8981\u4EBA\u7269 `\u540D\u5B57=\u5B9A\u4F4D,\u2026`").action(H(y=>{let _={};for(let S of["content","speaker","type","name","desc","importance","role","space","time","title","synopsis","logline","theme","worldview","style","main"]){let E=he(y,S);E!==void 0&&(_[S]=E)}for(let S of["paren","ts","transition"])if(y[S]===!1)_[S]=null;else{let E=he(y,S);E!==void 0&&(_[S]=E)}return y.alias!==void 0&&(_.aliases=Rp(y.alias)),at(()=>sm(Ke(y),ye(y),_),"edit")},t));Me(c,[No]);let a=ee(e.command("insert <addr> <content>"),"write").description("\u5728\u67D0\u6761 action \u524D/\u540E\u63D2\u5165\u4E00\u6761\u65B0 action").requiredOption("-t, --type <type>","action | dialogue | inner_thought | transition").option("--before","\u63D2\u5230\u76EE\u6807\u4E4B\u524D\uFF08\u9ED8\u8BA4\u4E4B\u540E\uFF09").option("-a, --speaker <name>","dialogue / inner_thought \u5FC5\u586B").option("--paren <text>","\u8868\u6F14\u63D0\u793A").action(H(y=>at(()=>am(Ke(y),ye(y),y.before?"before":"after",he(y,"type"),ye(y,1),he(y,"speaker"),he(y,"paren")),"insert"),t));Me(a,["\u76F8\u90BB action \u7684\u5730\u5740","\u65B0 action \u7684\u6B63\u6587"]);let d=ee(e.command("move <addr> <to>"),"write").description("\u628A\u4E00\u6761 action \u632A\u5230\u53E6\u4E00\u6761\u65C1\u8FB9\uFF1B\u8DE8\u573A\u4E5F\u4FDD\u6301 action_id").option("--before","\u632A\u5230\u76EE\u6807\u4E4B\u524D\uFF08\u9ED8\u8BA4\u4E4B\u540E\uFF09").action(H(y=>at(()=>cm(Ke(y),ye(y),ye(y,1),y.before?"before":"after"),"move"),t));Me(d,["\u8981\u632A\u7684 action","\u76EE\u6807\u90BB\u5C45 action"]);let p=ee(e.command("write <addr>"),"write").description("\u7528 read \u8F93\u51FA\u7684\u540C\u4E00\u4EFD\u6B63\u6587\u683C\u5F0F\u56DE\u5199\u6574\u573A / \u6574\u96C6 / \u65B0\u96C6\uFF08`+`\uFF09").option("-f, --file <path>","\u6B63\u6587\u6587\u4EF6\uFF1B\u7701\u7565\u5219\u8BFB stdin").option("--allow-delete","\u5141\u8BB8\u5220\u9664\u6587\u672C\u91CC\u6D88\u5931\u7684\u573A / action").action(H(async y=>{let _=await import("node:fs"),S=he(y,"file"),E=S?_.readFileSync(S,"utf8"):_.readFileSync(0,"utf8");return at(()=>pm(Ke(y),ye(y),E,{allowDelete:!!y.allow_delete}),"write")},t));Me(p,["\u573A / \u96C6\u5730\u5740\uFF0C\u6216 `+` \u8FFD\u52A0\u65B0\u96C6"]);let l=ee(e.command("replace <pattern> <to>"),"write").description("\u6279\u91CF\u66FF\u6362\u6B63\u6587\uFF1B\u9ED8\u8BA4\u53EA\u9884\u89C8\uFF0C--apply \u624D\u843D\u76D8\u3002\u8FC7\u6EE4\u53C2\u6570\u4E0E find \u76F8\u540C").option("-i, --in <addr>","\u9650\u5236\u8303\u56F4").option("-a, --speaker <name>","\u9650\u5B9A\u8BF4\u8BDD\u4EBA").option("-t, --type <type>","\u9650\u5B9A action \u7C7B\u578B").option("--apply","\u771F\u7684\u5199\u5165").action(H(y=>at(()=>mm(Ke(y),ye(y),ye(y,1),{...he(y,"in")?{in:he(y,"in")}:{},...he(y,"speaker")?{speaker:he(y,"speaker")}:{},...he(y,"type")?{type:he(y,"type")}:{},...y.apply?{apply:!0}:{}}),"replace"),t));Me(l,["\u6B63\u5219","\u66FF\u6362\u6210\u4EC0\u4E48"]);let f=ee(e.command("ref <scene> <asset>"),"write").description("\u6539\u4E00\u4E2A\u573A\u5BF9\u67D0\u8D44\u4EA7\u7684\u5F15\u7528\uFF1B--state \u662F\u5B8C\u6574\u72B6\u6001\u96C6\u5408\u800C\u975E\u8FFD\u52A0").option("--state <list>","\u5B8C\u6574\u72B6\u6001\u96C6\u5408\uFF08\u540D\u5B57\u6216 ID\uFF09\uFF0C\u9017\u53F7\u5206\u9694\u6216\u91CD\u590D\u7ED9\u51FA",xS,[]).option("--remove","\u5220\u9664\u6574\u6761\u5F15\u7528").action(H(y=>at(()=>fm(Ke(y),ye(y),ye(y,1),Rp(y.state).flatMap(_=>_.split(",")).map(_=>_.trim()).filter(Boolean),!!y.remove),"ref"),t));Me(f,["\u573A\u5730\u5740","\u4EBA\u7269 / \u5730\u70B9 / \u9053\u5177\u7684\u540D\u5B57\u6216 ID"]);let u=ee(e.command("asset <kind> <name>"),"write").description("\u767B\u8BB0\u4E00\u4E2A\u65B0\u7684 actor / location / prop").requiredOption("--desc <text>","\u63CF\u8FF0").option("--importance <tier>","featured | background","featured").option("--alias <list>","\u522B\u540D\uFF0C\u9017\u53F7\u5206\u9694").action(H(y=>at(()=>ym(Ke(y),ye(y),ye(y,1),he(y,"desc")??"",he(y,"importance")??"featured",Rp(y.alias)),"asset"),t));Me(u,["actor | location | prop","\u540D\u5B57"]);let m=ee(e.command("state <asset> <name>"),"write").description("\u7ED9\u5DF2\u6709\u8D44\u4EA7\u52A0\u4E00\u4E2A\u72B6\u6001\uFF08\u9020\u578B\u6863\u4F4D\uFF09").requiredOption("--desc <text>","\u63CF\u8FF0").action(H(y=>at(()=>wm(Ke(y),ye(y),ye(y,1),he(y,"desc")??""),"state"),t));Me(m,["\u8D44\u4EA7\u540D\u6216 ID","\u72B6\u6001\u540D"]);let h=ee(e.command("del <addr>"),"write").description("\u5220\u9664 action / \u573A / \u96C6 / \u8D44\u4EA7 / \u72B6\u6001").option("--replacement <state>","\u5220\u72B6\u6001\u65F6\u628A\u5F15\u7528\u6539\u5199\u5230\u8FD9\u4E2A\u72B6\u6001").option("--force","\u5BB9\u5668\u975E\u7A7A\u65F6\u4ECD\u7136\u5220\u9664").action(H(y=>at(()=>Em(Ke(y),ye(y),{...he(y,"replacement")?{replacement:he(y,"replacement")}:{},...y.force?{force:!0}:{}}),"del"),t));Me(h,[No]);let g=ee(e.command("merge <src> <dst>"),"write").description("\u628A\u4E00\u4E2A\u8D44\u4EA7\u5E76\u5165\u53E6\u4E00\u4E2A\uFF1A\u5168\u90E8\u573A\u666F\u5F15\u7528\u4E0E speaker \u6539\u5199\u8FC7\u53BB").action(H(y=>at(()=>fp(Ke(y),ye(y),ye(y,1)),"merge"),t));Me(g,["\u88AB\u5E76\u5165\u7684\u8D44\u4EA7","\u4FDD\u7559\u7684\u8D44\u4EA7"]);let w=ee(e.command("ext <addr> [key] [value]"),"write").description("\u8BFB\u6216\u5199\u4EFB\u610F\u8282\u70B9\u7684 extend \u6570\u636E").option("--remove","\u5220\u9664\u8BE5 key").action(H(y=>at(()=>_m(Ke(y),ye(y),ye(y,1)||void 0,ye(y,2)||void 0,!!y.remove),"ext"),t));Me(w,[No,"extend key","\u503C"])}function xS(e,t){return[...t,e]}import*as Oy from"node:path";var Xn={createExecutor:jf};import*as nl from"node:fs";import*as pr from"node:path";var Mn=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();var ts=e=>String(e).padStart(3,"0"),Mp=e=>e.normalize("NFC").replace(/\s+/g," ").trim();function fg(e,t={}){let n=[],o=[],i=null,r=null,s=0,c=0,a=new Map,d=(l,f)=>{let u=`text:${l}:${f.chunk}:${f.line_start}:${f.line_end}`,m=(a.get(u)??0)+1;return a.set(u,m),`${u}:${m}`},p=(l,f)=>{let u=l.actors.find(m=>Mp(m.name)===Mp(f.name));u?f.state&&!u.state&&(u.state=f.state):l.actors.push(f)};for(let l of e)switch(l.kind){case"episode":{s++,i={identity_key:d("episode",l.source),episode_id:`ep_${ts(s)}`,scenes:[]},l.title!==void 0&&(i.title=l.title),n.push(i),r=null;break}case"scene":{i||(s++,i={identity_key:d("synthetic-episode",l.source),episode_id:`ep_${ts(s)}`,scenes:[]},n.push(i)),c++,r={identity_key:d("scene",l.source),scene_id:`scn_${ts(c)}`,location:l.location?{...l.location}:null,actors:(l.actors??[]).map(f=>({...f})),props:(l.props??[]).map(f=>({...f})),actions:[]},l.environment&&(r.environment=l.environment),i.scenes.push(r);break}case"note":o.push({content:l.content,...l.category?{category:l.category}:{},source:l.source});break;case"action":case"transition":{if(!r){o.push({content:l.content,category:"preamble",source:l.source});break}r.actions.push({identity_key:d(l.kind,l.source),type:l.kind,content:l.content});break}case"dialogue":case"inner_thought":{if(!r){o.push({content:l.content,category:"preamble",source:l.source});break}let f={identity_key:d(l.kind,l.source),type:l.kind,content:l.content,speaker:l.speaker};l.emotion!==void 0&&(f.emotion=l.emotion),r.actions.push(f),"name"in l.speaker&&p(r,l.speaker.state!==void 0?{name:l.speaker.name,state:l.speaker.state}:{name:l.speaker.name});break}}return{script:{title:t.title??"",episodes:n},notes:o}}var ns=class{constructor(t,n,o){this.prefix=t;this.kind=n;this.nextStateId=o}prefix;kind;nextStateId;byNorm=new Map;order=[];ensure(t,n){let o=Mp(t),i=this.byNorm.get(o);return i||(i={provisional_id:`${this.prefix}_${ts(this.order.length+1)}`,kind:this.kind,names:[],states:[],occurrences:[]},this.byNorm.set(o,i),this.order.push(i)),i.names.includes(t)||i.names.push(t),i.occurrences.push(n),i}stateId(t,n){let o=Mn(n),i=t.states.find(s=>Mn(s.name)===o);if(i)return i.id;let r=this.nextStateId();return t.states.push({name:n,id:r}),r}list(){return this.order}};function SS(e){let t=[{state_id:"default",state_name:"default",description:""}];for(let n of e.states)t.push({state_id:n.id,state_name:n.name,description:""});return t}function Oa(e){let t=0,n=()=>`st_${ts(++t)}`,o=new ns("act","actor",n),i=new ns("loc","location",n),r=new ns("prp","prop",n),s={episode:{},scene:{},action:{}},c={episode:new Set,scene:new Set,action:new Set},a=(u,m,h)=>{if(!h||c[u].has(h))throw new Error(`Duplicate or missing ${u} source identity: ${h}`);c[u].add(h),s[u][m]=h},d=(u,m,h,g)=>{let w=u.ensure(m.name,h),y={[g]:w.provisional_id};return m.state!==void 0&&(y.state_id=u.stateId(w,m.state)),y},p=e.episodes.map((u,m)=>(a("episode",u.episode_id,u.identity_key),{episode_id:u.episode_id,...u.title?{title:u.title}:{},scenes:u.scenes.map((h,g)=>{let w=`${u.episode_id}/${h.scene_id}`;a("scene",w,h.identity_key);let y={episode:m,scene:g},_=h.location?d(i,h.location,y,"location_id"):null,S=h.actors.map(b=>d(o,b,y,"actor_id")),E=h.props.map(b=>d(r,b,y,"prop_id")),A=h.actions.map((b,U)=>{a("action",`${w}#${U}`,b.identity_key);let M={type:b.type,content:b.content};if(b.speaker)if("name"in b.speaker){let I=o.ensure(b.speaker.name,y),v={actor_id:I.provisional_id};b.speaker.state!==void 0&&(v.state_id=o.stateId(I,b.speaker.state)),M.speaker=v}else M.speaker=b.speaker.label!==void 0?{kind:b.speaker.kind,label:b.speaker.label}:{kind:b.speaker.kind};return(b.type==="dialogue"||b.type==="inner_thought")&&(b.parenthetical!==void 0?M.emotion=b.parenthetical:b.emotion!==void 0&&(M.emotion=b.emotion)),b.extend!==void 0&&(M.extend=b.extend),M});return{scene_id:h.scene_id,...h.environment?{environment:h.environment}:{},location:_,actors:S,props:E,actions:A}})})),l=(u,m,h)=>u.list().map(g=>({[m]:g.provisional_id,[h]:g.names[0]??g.provisional_id,aliases:g.names.slice(1),description:"",states:SS(g)}));return{script:{version:3,title:e.title,worldview:"",style:"",actors:l(o,"actor_id","actor_name"),locations:l(i,"location_id","location_name"),props:l(r,"prop_id","prop_name"),episodes:p},assets:[...o.list(),...i.list(),...r.list()],identityKeys:s}}function mg(e,t={}){let n=t.maxChars??500,o=e.split(`
236
237
  `),i=[],r=0,s=0,c=a=>{let d=o.slice(r,a).join(`
237
- `);return d.trim()===""?!1:(i.push({index:i.length,core_line_start:r,core_line_end:a,text:d}),r=a,s=0,!0)};for(let a=0;a<o.length;a++){let d=o[a],l=s+(a===r?0:1)+d.length;d.trim()!==""&&a>r&&l>n&&c(a)?s=d.length:s=l}return c(o.length),i}var ug=["episode","scene","action","dialogue","inner_thought","transition","note"];var SS={day:"day",\u65E5:"day",\u767D\u5929:"day",\u65E5\u95F4:"day",\u663C:"day",\u663C\u95F4:"day",night:"night",\u591C:"night",\u591C\u665A:"night",\u591C\u95F4:"night",\u665A:"night",dawn:"dawn",\u6668:"dawn",\u6E05\u6668:"dawn",\u65E9\u6668:"dawn",\u9ECE\u660E:"dawn",\u62C2\u6653:"dawn",dusk:"dusk",\u660F:"dusk",\u9EC4\u660F:"dusk",\u508D\u665A:"dusk",\u65E5\u843D:"dusk"};function Lo(e){if(typeof e!="string")return;let t=e.normalize("NFC").replace(/\s+/g,"").trim().toLocaleLowerCase();return SS[t]}var _e=class extends Error{constructor(n,o){super(`line ${o}: ${n}`);this.line=o}line};function or(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function on(e,t,n){for(let o of Object.keys(e))if(!t.includes(o))throw new _e(`unknown field '${o}'`,n)}function IS(e,t){if(!or(e))throw new _e("missing source",t);on(e,["chunk","line_start","line_end"],t);let{chunk:n,line_start:o,line_end:i}=e;if(![n,o,i].every(r=>typeof r=="number"&&Number.isInteger(r)&&r>=0))throw new _e("source needs integer chunk/line_start/line_end",t);if(o>=i)throw new _e("source line_start must be < line_end",t);return{chunk:n,line_start:o,line_end:i}}function nr(e,t,n){let o=e[t];if(typeof o!="string"||o==="")throw new _e(`'${t}' must be a non-empty string`,n);return o}function Uo(e,t,n){if(!(t in e)||e[t]===void 0)return;let o=e[t];if(typeof o!="string"||o==="")throw new _e(`'${t}' must be a non-empty string`,n);return o}function fg(e,t,n){if(!Array.isArray(e))throw new _e(`'${t}' must be an array`,n);return e.map(o=>{if(!or(o))throw new _e(`'${t}' entries must be objects`,n);on(o,["name","state"],n);let i={name:nr(o,"name",n)},r=Uo(o,"state",n);return r!==void 0&&(i.state=r),i})}function AS(e,t){if(!or(e))throw new _e("dialogue/inner_thought needs a speaker",t);if("kind"in e){on(e,["kind","label"],t);let r=e.kind;if(typeof r!="string"||!Vn.includes(r))throw new _e(`speaker.kind must be one of ${Vn.join("|")}`,t);let s={kind:r},c=Uo(e,"label",t);return c!==void 0&&(s.label=c),s}on(e,["name","state"],t);let n=nr(e,"name",t);if(!/[\p{L}\p{N}]/u.test(n))throw new _e("speaker.name must contain a letter or number",t);let o={name:n},i=Uo(e,"state",t);return i!==void 0&&(o.state=i),o}function kS(e,t){let n=e.kind;if(typeof n!="string"||!ug.includes(n))throw new _e(`unknown or missing kind '${String(n)}'`,t);let o=IS(e.source,t);switch(n){case"episode":{on(e,["kind","episode","title","source"],t);let i=e.episode;if(typeof i!="number"||!Number.isInteger(i))throw new _e("episode must be an integer",t);let r={kind:n,episode:i,source:o},s=Uo(e,"title",t);return s!==void 0&&(r.title=s),r}case"scene":{on(e,["kind","scene","environment","location","actors","props","source"],t);let i={kind:n,source:o};if("scene"in e&&e.scene!==void 0){if(typeof e.scene!="number"||!Number.isInteger(e.scene))throw new _e("scene must be an integer",t);i.scene=e.scene}if("environment"in e&&e.environment!==void 0){if(!or(e.environment))throw new _e("environment must be an object",t);on(e.environment,["space","time"],t);let r={},s=Uo(e.environment,"space",t);s!==void 0&&(r.space=s);let c=Uo(e.environment,"time",t);if(c!==void 0){let a=Lo(c);if(!a)throw new _e("environment.time must be day|night|dawn|dusk or a recognized Chinese equivalent",t);r.time=a}i.environment=r}if("location"in e&&e.location!==void 0){if(!or(e.location))throw new _e("location must be an object",t);on(e.location,["name","state"],t);let r={name:nr(e.location,"name",t)},s=Uo(e.location,"state",t);s!==void 0&&(r.state=s),i.location=r}return"actors"in e&&e.actors!==void 0&&(i.actors=fg(e.actors,"actors",t)),"props"in e&&e.props!==void 0&&(i.props=fg(e.props,"props",t)),i}case"action":case"transition":{on(e,["kind","content","source"],t);let i=nr(e,"content",t);return{kind:n,content:i,source:o}}case"dialogue":case"inner_thought":{on(e,["kind","speaker","content","emotion","source"],t);let i=nr(e,"content",t),r=AS(e.speaker,t),s={kind:n,speaker:r,content:i,source:o},c=Uo(e,"emotion",t);return c!==void 0&&(s.emotion=c),s}case"note":{on(e,["kind","content","category","source"],t);let i=nr(e,"content",t),r={kind:n,content:i,source:o};if("category"in e&&e.category!==void 0){let s=e.category;if(s!=="author_note"&&s!=="format_note"&&s!=="unclassified")throw new _e("note.category must be author_note|format_note|unclassified",t);r.category=s}return r}default:throw new _e(`unhandled kind '${n}'`,t)}}function ns(e,t=0){let n=[],o=e.split(`
238
- `);for(let i=0;i<o.length;i++){let r=o[i].trim();if(r==="")continue;let s;try{s=JSON.parse(r)}catch{throw new _e("invalid JSON",i+1+t)}if(!or(s))throw new _e("record must be a JSON object",i+1+t);n.push(kS(s,i+1+t))}return n}var ne=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),fi=e=>{let t=/[((]/.exec(e);return!t||t.index===0?e:e.slice(0,t.index).trim()},bS=e=>e.startEp===e.endEp?`\u7B2C${e.startEp}\u96C6`:`\u7B2C${e.startEp}\u96C6\u2013\u7B2C${e.endEp}\u96C6`,Mp=e=>e.startEp===e.endEp?`\u7B2C${e.startEp}\u96C6`:`\u7B2C${e.startEp}\u96C6\u2013\u7B2C${e.endEp}\u96C6`,yg=()=>({newEntities:[],merges:[],looks:[],lookChanges:[],subEvents:[],summary:""}),wg=()=>({entities:[],lookChanges:{},recent:[],synopsis:[]}),Np={recentEpisodes:6,synopsisChars:3500,arcFold:10},OS=1e4;function _g(e){let t=0,n=0;for(let o of e){n++;let i=o.codePointAt(0);(i>=13312&&i<=40959||i>=12288&&i<=12543||i>=65280&&i<=65519||i>=63744&&i<=64255)&&t++}return Math.round(t*.7+(n-t)*.25)}function Eg(e,t=OS){let n=[],o=0,i=0;for(let r=0;r<e.length;r++)r>o&&i+e[r]>t&&(n.push([o+1,r]),o=r,i=0),i+=e[r];return o<e.length&&n.push([o+1,e.length]),n}var vS={actor:"\u4EBA\u7269",location:"\u573A\u666F",prop:"\u9053\u5177"};function zt(e,t){let n=ne(t);return e.entities.find(o=>ne(o.canonical)===n||o.aliases.some(i=>ne(i)===n))}var mg=(e,t)=>{ne(t)!==ne(e.canonical)&&!e.aliases.some(n=>ne(n)===ne(t))&&e.aliases.push(t)},RS=["\u5E74\u8F7B","\u5E74\u8001","\u5E74\u5E7C","\u5E74\u5C11","\u4E2D\u5E74","\u9752\u5E74","\u5C11\u5E74","\u8001\u5E74","\u5E7C\u5E74","\u8001","\u5C0F","\u5927","\u5C11","\u5E7C"];function MS(e,t){let n=ne(e),o=ne(t);if(n===o||!n.includes(o))return!1;let i=n.replace(o,"").trim();return i.length>0&&!RS.some(r=>i===r||i.startsWith(r))}function NS(e){let t=e.filter(n=>e.some(o=>o!==n&&MS(n,o)));return t.length?t.reduce((n,o)=>o.length>n.length?o:n):e[0]}var gg=["\u4F17\u4EBA","\u7FA4\u4F17","\u6C11\u4F17","\u89C2\u4F17","\u4EBA\u7FA4","\u4EBA\u4EEC","\u5927\u5BB6","\u8DEF\u4EBA","\u884C\u4EBA","\u770B\u5BA2","\u56F4\u89C2\u8005","\u6751\u6C11","\u58EB\u5175","\u767E\u59D3","\u5B66\u751F","\u540C\u5B66","\u4E2B\u9B1F","\u968F\u4ECE","\u4F8D\u536B","\u5BB6\u4E01","\u4EC6\u4EBA","\u4E0B\u4EBA","\u5B69\u5B50","\u8F7F\u592B","\u62A4\u536B","\u624B\u4E0B","\u5C0F\u5F1F","\u55BD\u5570","\u5B98\u5175","\u8859\u5F79","\u592A\u76D1","\u5BAB\u5973","\u5A62\u5973","\u5546\u8D29","\u98DF\u5BA2"],LS=["\u4F17\u4EBA","\u7FA4\u4F17","\u6C11\u4F17","\u89C2\u4F17","\u4EBA\u7FA4","\u4EBA\u4EEC","\u5927\u5BB6","\u767E\u59D3","\u5B98\u5175"],US=/^(?:一群|一众|全体|所有|几名|数名|多名|[0-9零一二两三四五六七八九十百千]+名?)/;function ct(e){let t=ne(e).replace(/[0-9零一二两三四五六七八九十百千]+名?$/,"").trim();return t?t.endsWith("\u4EEC")||gg.includes(t)||LS.some(n=>t.endsWith(n))?!0:US.test(t)&&gg.some(n=>t.endsWith(n)):!1}function Po(e,t){let n=fi(t);return zt(e,n)?.canonical??n}function PS(e,t){let n=ne(t);return e.looks.find(o=>ne(o.name)===n||o.aliases.some(i=>ne(i)===n))?.name??t}var CS=["\u5E38\u6001","\u65E5\u5E38","\u5E73\u65F6","\u57FA\u7840","\u666E\u901A"];function Lp(e){if(e.looks.length!==0)return(e.looks.find(t=>CS.some(n=>t.name.includes(n)))??e.looks[0]).name}function Rp(e,t,n,o){let i=ne(fi(n));if(i)return e.entities.find(r=>r.kind===t&&r!==o&&(ne(r.canonical)===i||r.aliases.some(s=>ne(s)===i)))}function hg(e){let t=[e.canonical,...e.aliases],n=NS(t);ne(n)!==ne(e.canonical)&&(e.canonical=n,e.aliases=t.filter(o=>ne(o)!==ne(n)))}function os(e,t,n,o=n){for(let r of t.newEntities){let s=fi(r.name);if(!s)continue;let c=Rp(e,r.kind,s);if(!c){let d=[];for(let p of r.aliases){let l=fi(p);l&&ne(l)!==ne(s)&&!Rp(e,r.kind,l)&&d.push(l)}e.entities.push({kind:r.kind,canonical:s,aliases:[...new Set(d)],description:r.description,looks:[{name:r.defaultLook.name,aliases:[],description:r.defaultLook.description}],lastSeen:o});continue}for(let d of r.aliases){let p=fi(d);p&&!Rp(e,r.kind,p,c)&&mg(c,p)}!c.description&&r.description&&(c.description=r.description);let a=c.looks.find(d=>ne(d.name)===ne(r.defaultLook.name));a?a.description=r.defaultLook.description:c.looks.unshift({name:r.defaultLook.name,aliases:[],description:r.defaultLook.description}),hg(c)}for(let{from:r,into:s}of t.merges){let c=fi(s);if(!c)continue;let a=zt(e,c);if(!a)continue;let d=fi(r);!d||ne(d)===ne(a.canonical)||zt(e,d)||(mg(a,d),hg(a))}for(let{entity:r,names:s,description:c}of t.looks){let a=zt(e,r);if(!a)continue;let d=s.map(f=>f.trim()).filter(Boolean);if(!d.length)continue;let p=d[0],l=a.looks.find(f=>ne(f.name)===ne(p)||d.some(u=>f.aliases.some(g=>ne(g)===ne(u))));if(l){c&&(l.description=c);for(let f of d)ne(f)!==ne(l.name)&&!l.aliases.some(u=>ne(u)===ne(f))&&l.aliases.push(f)}else a.looks.push({name:p,aliases:d.slice(1),description:c})}for(let r of t.lookChanges){let s=r.scene.trim(),c=Po(e,r.entity),a=r.look.trim();if(!s||!c||!a)continue;let d=zt(e,c),p=d?PS(d,a):a;(e.lookChanges[s]??=[]).push({entity:c,look:p}),d&&(d.currentLook=p)}let i=new Set;for(let r of t.newEntities){i.add(r.name);for(let s of r.aliases)i.add(s)}for(let r of t.merges)i.add(r.from),i.add(r.into);for(let r of t.looks)i.add(r.entity);for(let r of t.lookChanges)i.add(r.entity);for(let r of i){let s=zt(e,r);s&&(s.lastSeen=o)}return e.recent.push({startEp:n,endEp:o,summary:t.summary,subEvents:t.subEvents}),e}var TS=e=>e.summary.length+e.subEvents.reduce((t,n)=>t+n.length,0);function xg(e,t=Np){for(;e.recent.length>t.recentEpisodes||e.recent.length>1&&e.recent.reduce((n,o)=>n+TS(o),0)>6e3;){let n=e.recent.shift();n.summary.trim()&&e.synopsis.push({startEp:n.startEp,endEp:n.endEp,line:n.summary.trim()})}return e}function Up(e,t=Np){return e.synopsis.reduce((o,i)=>o+i.line.length,0)<=t.synopsisChars||e.synopsis.length<=t.arcFold?null:e.synopsis.slice(0,t.arcFold)}function Sg(e,t,n=Np){let o=e.synopsis.splice(0,n.arcFold);o.length&&e.synopsis.unshift({startEp:o[0].startEp,endEp:o[o.length-1].endEp,line:t.trim()})}var VS=6;function ba(e,t){let n=i=>t===void 0||i.lastSeen>=t-VS,o=["# \u8BBE\u5B9A"];for(let i of["actor","location","prop"]){let r=e.entities.filter(s=>s.kind===i);if(r.length){o.push(`## ${vS[i]}`);for(let s of r){let c=[...s.aliases.length?[`\u522B\u540D ${s.aliases.join("\u3001")}`]:[],...s.currentLook?[`\u5F53\u524D\u9020\u578B ${s.currentLook}`]:[]];if(o.push(`- ${s.canonical}\uFF5C${c.join("\uFF5C")}`),!!n(s)){s.description&&o.push(` \u7B80\u4ECB\uFF1A${s.description}`);for(let a of s.looks){let d=a.aliases.length?`${a.name}(=${a.aliases.join("=")})`:a.name;o.push(` \u9020\u578B ${d}${a.description?`\uFF1A${a.description}`:""}`)}}}}}if(e.synopsis.length){o.push("","# \u524D\u60C5");for(let i of e.synopsis)o.push(`- ${Mp(i)}\uFF1A${i.line}`)}if(e.recent.length){o.push("","# \u6700\u8FD1");for(let i of e.recent){o.push(`## ${bS(i)}`),i.summary.trim()&&o.push(`\u6897\u6982\uFF1A${i.summary.trim()}`);for(let r of i.subEvents)o.push(`- ${r}`)}}return o.join(`
239
- `)}var $S=/(?:^|[,。!?;:、\s“”"'((])(他们|她们|它们|其中一人|另一个人|前者|后者|对方|有人|两人|他|她|它)(?!人)/;function ir(e){let t=[],n=(o,i,r)=>{t.push({code:o,path:i,message:r})};return e.actors.forEach((o,i)=>{ct(o.actor_name)&&n("production_crowd_actor",`$.actors[${i}].actor_name`,`${o.actor_name} is a group speaker, not an actor asset`)}),e.episodes.forEach((o,i)=>{o.scenes.forEach((r,s)=>{let c=`$.episodes[${i}].scenes[${s}]`;r.location===null&&n("production_location_missing",`${c}.location`,"production scene needs one stable location"),r.actions.forEach((a,d)=>{let p=`${c}.actions[${d}]`;if(a.type==="action"){let l=$S.exec(a.content);l&&n("production_action_pronoun",`${p}.content`,`action uses ambiguous reference ${l[1]}`)}})})}),t}var qe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ut=e=>Array.isArray(e),Oa=e=>String(e).padStart(3,"0"),Pp=[{key:"actors",idField:"actor_id",prefix:"act"},{key:"locations",idField:"location_id",prefix:"loc"},{key:"props",idField:"prop_id",prefix:"prp"}];function va(e){if(!qe(e))throw new Error("renumberIds expects a script object");let t=JSON.parse(JSON.stringify(e)),n={episodes:{},scenes:{},actors:{},locations:{},props:{},states:{}},o={actors:[],locations:[],props:[]},i={actors:new Set,locations:new Set,props:new Set},r=(a,d)=>{typeof d=="string"&&!i[a].has(d)&&(i[a].add(d),o[a].push(d))};for(let a of ut(t.episodes)?t.episodes:[])if(!(!qe(a)||!ut(a.scenes))){for(let d of a.scenes)if(qe(d)){qe(d.location)&&r("locations",d.location.location_id);for(let p of ut(d.actors)?d.actors:[])qe(p)&&r("actors",p.actor_id);for(let p of ut(d.props)?d.props:[])qe(p)&&r("props",p.prop_id);for(let p of ut(d.actions)?d.actions:[])qe(p)&&qe(p.speaker)&&r("actors",p.speaker.actor_id)}}for(let{key:a,idField:d}of Pp)for(let p of ut(t[a])?t[a]:[])qe(p)&&r(a,p[d]);for(let{key:a,prefix:d}of Pp)o[a].forEach((p,l)=>{n[a][p]=`${d}_${Oa(l+1)}`});for(let{key:a,idField:d}of Pp){let p=(ut(t[a])?t[a]:[]).filter(qe),l=n[a],f=new Map;for(let u of p){let g=u[d],h=l[g]??g;u[d]=h;let m=0;for(let w of ut(u.states)?u.states:[]){if(!qe(w)||typeof w.state_id!="string"||w.state_id==="default")continue;let y=`st_${Oa(++m)}`;n.states[w.state_id]=y,w.state_id=y}f.set(h,u)}t[a]=[...f.entries()].sort((u,g)=>u[0]<g[0]?-1:1).map(u=>u[1])}let s=0;(ut(t.episodes)?t.episodes:[]).forEach((a,d)=>{if(qe(a)){if(typeof a.episode_id=="string"){let p=`ep_${Oa(d+1)}`;n.episodes[a.episode_id]=p,a.episode_id=p}for(let p of ut(a.scenes)?a.scenes:[])if(qe(p)&&typeof p.scene_id=="string"){let l=`scn_${Oa(++s)}`;n.scenes[p.scene_id]=l,p.scene_id=l}}});let c=(a,d,p)=>{!qe(a)||typeof a[d]!="string"||(a[d]=n[p][a[d]]??a[d],typeof a.state_id=="string"&&n.states[a.state_id]&&(a.state_id=n.states[a.state_id]))};for(let a of ut(t.episodes)?t.episodes:[])if(!(!qe(a)||!ut(a.scenes))){for(let d of a.scenes)if(qe(d)){c(d.location,"location_id","locations");for(let p of ut(d.actors)?d.actors:[])c(p,"actor_id","actors");for(let p of ut(d.props)?d.props:[])c(p,"prop_id","props");for(let p of ut(d.actions)?d.actions:[])qe(p)&&c(p.speaker,"actor_id","actors")}}return{script:t,idMap:n}}import{createHash as DS}from"node:crypto";function is(e){let t=v(e).trim();if(!t.includes(":"))throw new S("Target invalid.",{exitCode:J,errorCode:"TARGET_INVALID",hint:"Use a concrete asset target.",data:{expected:["target: actor:<id>, location:<id>, or prop:<id>"],actual:[t||"<empty>"]}});let n=t.indexOf(":"),o=t.slice(0,n).trim(),i=t.slice(n+1).trim();if(!nu.has(o)||!i)throw new S("Target invalid.",{exitCode:J,errorCode:"TARGET_INVALID",hint:"Use actor, location, or prop with a non-empty id.",data:{expected:["target: actor:<id>, location:<id>, or prop:<id>"],actual:[t]}});return[o,i]}function Co(){return{version:3,actor:{},location:{},prop:{},state:{},episode:{},scene:{},action:{}}}function Ht(e,t){let n=e.get(t);if(n===void 0)throw new Error(`Missing mapped ID for ${t}`);return n}function rr(e,t=Co(),n={}){if(t.version!==3)throw new Error(`Unsupported v4 identity map version: ${String(t.version)}`);let o=structuredClone(t),i={actor:new Map,location:new Map,prop:new Map},r={actor:new Set,location:new Set,prop:new Set,episode:new Set,scene:new Set,action:new Set},s=(I,O,N,U)=>{let M=N[O];if(M!==void 0){if(!$(I,M))throw new Error(`Invalid persisted ${I} ID for ${O}: ${M}`);if(U.has(M))throw new Error(`Duplicate persisted ${I} ID: ${M}`);return U.add(M),M}let V=Fo(I,U);return U.add(V),N[O]=V,V},c=(I,O)=>n[I]?.[O]??O;for(let I of e.actors){let O=s("actor",c("actor",I.actor_id),o.actor,r.actor);i.actor.set(I.actor_id,O)}for(let I of e.locations){let O=s("location",c("location",I.location_id),o.location,r.location);i.location.set(I.location_id,O)}for(let I of e.props){let O=s("prop",c("prop",I.prop_id),o.prop,r.prop);i.prop.set(I.prop_id,O)}let a=new Map,d=(I,O,N)=>{let U=new Map,M=new Set,V=c(I,O),F=o.state[V]??{};o.state[V]=F;let Re=N.map(X=>{let j;if(X.state_id==="default")j="default";else{let Ot=n.state?.[O]?.[X.state_id]??X.state_id,P=F[Ot];if(P!==void 0){if(!$("state",P))throw new Error(`Invalid persisted state ID for ${O}/${X.state_id}: ${P}`);if(M.has(P))throw new Error(`Duplicate persisted state ID on ${O}: ${P}`);j=P}else j=Fo("state",M),F[Ot]=j}return M.add(j),U.set(X.state_id,j),{...X,state_id:j}});return a.set(O,U),Re},p=(I,O)=>O===void 0?void 0:Ht(a.get(I)??new Map,O),l=e.actors.map(I=>({...I,actor_id:Ht(i.actor,I.actor_id),states:d("actor",I.actor_id,I.states)})),f=e.locations.map(I=>({...I,location_id:Ht(i.location,I.location_id),states:d("location",I.location_id,I.states)})),u=e.props.map(I=>({...I,prop_id:Ht(i.prop,I.prop_id),states:d("prop",I.prop_id,I.states)})),g=I=>{if("actor_id"in I){let O=p(I.actor_id,I.state_id);return{actor_id:Ht(i.actor,I.actor_id),...O===void 0?{}:{state_id:O}}}return I.label===void 0?{kind:I.kind}:{kind:I.kind,label:I.label}},h=I=>{if(I.includes(":")){let[N,U]=is(I);return Ht(N==="actor"?i.actor:N==="location"?i.location:i.prop,U)}let O=i.actor.get(I)??i.location.get(I)??i.prop.get(I);if(O===void 0)throw new Error(`Missing transition target mapping for ${I}`);return O},m=(I,O)=>{let N=s("action",O,o.action,r.action),U=I.transition_prompt===void 0?{}:{transition_prompt:{...I.transition_prompt,target:h(I.transition_prompt.target)}};if(I.type==="dialogue"||I.type==="inner_thought"){if(I.speaker===void 0)throw new Error(`Speaking action ${I.content.slice(0,40)} has no speaker`);return{action_id:N,type:I.type,content:I.content,speaker:g(I.speaker),...I.emotion===void 0?{}:{parenthetical:I.emotion},...U,...I.extend===void 0?{}:{extend:I.extend}}}return{action_id:N,type:I.type,content:I.content,...U,...I.extend===void 0?{}:{extend:I.extend}}},w=(I,O)=>[p(I,O??"default")??"default"],y=(I,O)=>{let N=new Map;for(let U of I){let M=Ht(i.actor,U.actor_id),V=N.get(M)??new Set;w(U.actor_id,U.state_id).forEach(F=>V.add(F)),N.set(M,V)}for(let U of O){if(U.speaker===void 0||!("actor_id"in U.speaker))continue;let M=U.speaker.actor_id,V=Ht(i.actor,M),F=N.get(V)??new Set;w(M,U.speaker.state_id).forEach(Re=>F.add(Re)),N.set(V,F)}return[...N].map(([U,M])=>({actor_id:U,state_ids:[...M].sort()}))},_=I=>{let O=new Map;for(let N of I){let U=Ht(i.prop,N.prop_id),M=O.get(U)??new Set;w(N.prop_id,N.state_id).forEach(V=>M.add(V)),O.set(U,M)}return[...O].map(([N,U])=>({prop_id:N,state_ids:[...U].sort()}))},x=new Set,E=new Set,A=new Set,b={version:4,title:e.title,worldview:e.worldview,style:e.style,...e.worldview_raw===void 0?{}:{worldview_raw:e.worldview_raw},...e.synopsis===void 0?{}:{synopsis:e.synopsis},...e.logline===void 0?{}:{logline:e.logline},...e.theme===void 0?{}:{theme:e.theme},...e.main_characters===void 0?{}:{main_characters:e.main_characters},...e.extend===void 0?{}:{extend:e.extend},actors:l,locations:f,props:u,episodes:e.episodes.map(I=>{let O=n.episode?.[I.episode_id]??I.episode_id;x.add(O);let N=s("episode",O,o.episode,r.episode);return{...I,episode_id:N,scenes:I.scenes.map(U=>{let M=`${I.episode_id}/${U.scene_id}`,V=n.scene?.[M]??M;E.add(V);let F=s("scene",V,o.scene,r.scene),Re=new Map;return{...U,scene_id:F,location:U.location===null?null:{location_id:Ht(i.location,U.location.location_id),state_ids:w(U.location.location_id,U.location.state_id)},actors:y(U.actors,U.actions),props:_(U.props),actions:U.actions.map((X,j)=>{let Ot=`${M}#${j}`,P=JSON.stringify(In(X)),de=(Re.get(P)??0)+1;Re.set(P,de);let Se=DS("sha256").update(P).digest("hex"),vt=n.action?.[Ot]??`${V}:action:${Se}:${de}`;return A.add(vt),m(X,vt)})}})}})},C=(I,O)=>{for(let N of Object.keys(I))O.has(N)||delete I[N]};C(o.actor,new Set(e.actors.map(I=>c("actor",I.actor_id)))),C(o.location,new Set(e.locations.map(I=>c("location",I.location_id)))),C(o.prop,new Set(e.props.map(I=>c("prop",I.prop_id)))),C(o.episode,x),C(o.scene,E),C(o.action,A);let R=[...e.actors.map(I=>({id:c("actor",I.actor_id),oldId:I.actor_id,states:I.states})),...e.locations.map(I=>({id:c("location",I.location_id),oldId:I.location_id,states:I.states})),...e.props.map(I=>({id:c("prop",I.prop_id),oldId:I.prop_id,states:I.states}))];C(o.state,new Set(R.map(I=>I.id)));for(let I of R)C(o.state[I.id]??{},new Set(I.states.map(O=>n.state?.[I.oldId]?.[O.state_id]??O.state_id)));return{script:b,identityMap:o}}import*as Le from"node:fs";import*as mi from"node:path";function gi(e,t){let n=mi.dirname(e);Le.mkdirSync(n,{recursive:!0});let o=mi.join(n,`.${mi.basename(e)}.${process.pid}.tmp`),i=Le.openSync(o,"w");try{Le.writeFileSync(i,t),Le.fsyncSync(i)}finally{Le.closeSync(i)}Le.renameSync(o,e)}function GS(e,t){gi(e,JSON.stringify(t,null,2)+`
240
- `)}function BS(e){return JSON.parse(Le.readFileSync(e,"utf-8"))}var ft=class{constructor(t){this.root=t}root;abs(t){return mi.join(this.root,t)}ensure(){Le.mkdirSync(this.root,{recursive:!0})}passDir(t){let n=this.abs(t);return Le.mkdirSync(n,{recursive:!0}),n}readText(t){return Le.readFileSync(this.abs(t),"utf-8")}writeText(t,n){gi(this.abs(t),n)}writeJson(t,n){GS(this.abs(t),n)}readJson(t){return BS(this.abs(t))}has(t){return Le.existsSync(this.abs(t))}path(t){return this.abs(t)}clearError(t){let n=this.abs(t);Le.existsSync(n)&&Le.rmSync(n)}};function rn(e,t){e=e-0;let n=Cp(),o=n[e];if(rn.wCYmoh===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,g=0;u=c.charAt(g++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};rn.ccSjUe=i,rn.dKlJjl={},rn.wCYmoh=!0}let r=n[0];rn.sBhMJx!==r&&(rn.dKlJjl={},rn.sBhMJx=r);let s=rn.dKlJjl[e];return s===void 0?(o=rn.ccSjUe(o),rn.dKlJjl[e]=o):o=s,o}var q=rn,JS=[q(40),q(37),q(24),q(75),q(5),q(21),"",q(65),q(13),q(34),q(62),"",q(70),q(35),q(42),q(27),q(39),q(43),q(0),q(68),q(55),"",q(77),q(18),q(58),q(10),q(11),q(51),q(59),q(66),q(8),q(3),q(76),"",q(15),q(4),q(9),q(6),q(20),q(14),q(45),q(48),q(38),q(54)][q(74)](`
241
- `);function jS(e){let t=q,n=e[t(73)]===0?t(47):t(23);return[t(78),n,t(49),"",e[t(53)]][t(74)](`
242
- `)}function Ra(e,t){let n=q;return new S(e,{exitCode:ee,errorCode:n(12),hint:n(44),data:{actual:t}})}function KS(e){let t=q;return typeof e!==t(29)||e===null||Array[t(46)](e)?!1:Object[t(61)](e)[t(1)]===1&&t(33)in e&&Array[t(46)](e[t(33)])}function Tp(e,t){let n=q;if(!KS(e))throw Ra(n(19)+t[n(73)]+n(63),[n(31)]);let o={chunk:t[n(73)],line_start:t[n(64)],line_end:t[n(36)]},i;try{let r=e[n(33)][n(25)](s=>{let c=n;if(typeof s!==c(29)||s===null||Array[c(46)](s)||Object[c(26)](s,c(56))){if(c(72)!==c(30))throw new _e(c(57),1);if(typeof _0x5a19bf!==c(29)||_0x5b66f6===null||_0x10f05d[c(46)](_0x23b052)||_0x733702[c(26)](_0x1cb121,c(56)))throw new _0x3dba95(c(57),1);return _0x5020a9[c(32)]({..._0x80cb75,source:_0x442727})}return JSON[c(32)]({...s,source:o})})[n(74)](`
243
- `);i=ns(r)}catch(r){throw r instanceof _e?Ra(n(19)+t[n(73)]+": "+r[n(17)],[r[n(17)]]):r}if(i[n(1)]===0&&t[n(53)][n(52)]()!=="")throw n(60)===n(22)?_0x1b2e63(n(19)+_0x2d4dff[n(73)]+n(63),[n(31)]):Ra(n(19)+t[n(73)]+n(69),[n(2)]);return i}function Cp(){let e=["lsdOVAZLNlRVVjP7iMTPBMqIoIj0CMfUC2L0Aw9UiIWIy29UDgvUDci6iUw/OowUNUI9RoAnOUAiKoEUGos9K+s4REAwH+EAHoI9RowCUUAwH+wTLYj944cc5BI46kEb5Qc85BYp6k+n5lMF6kAb57+76k+r77Ym5l6l5AAcigbgteftsejbq0TGiokgKIbG6zEQ5zUEyooaGwbcqunlifrpifbsrvnftLrGiokgKIbG5zUE5yIW546W5A6EyooaGG","BgvUz3rO","CMvJB3jKCZOGma","icdOKAhOR63LIQJKVzWGyfvTihbYyxrVigrLig9MzxjLBMrHCYbJywKGzgeGBwvZysbLihnLigvZCgfSAgeGCgvSBYbJAmoJBY5GiokgKIbHy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KW","Aw5KzxG","AM9PBG","6l+z5PIV5l6B5lIT5PAh57Yw5yMN5Asn5Qc455Qe5Qch5yEg56I/77YAzgLHBg9NDwuG5zkmigLUBMvYx3rOB3vNAhqG55QeignVBNrLBNqG6ycq5A2x5l+D55wz5RQq5PAh5PYS5A6E6zMf6k+T6kIa5lIo5As55P2c6k+T6kIa77Ym57UD5lIn57+76k+r77YB6zMK5Q2K5lUL5Asw77Ymywn0Aw9U44cbDhjHBNnPDgLVBUoaGw5VDgxJGifLBw90Aw9Uios7PEwpIUwCUUAzR+EAHoMaMUEuQowCSoEcUEApJ+I/SoMdVEs9V+EuQoIhQUEeTUoaGEwhHUEHRUEAHoEUGos9K+s4REAwH+oaGUs6UUEjQEwNK+wqJEwCQcbZCgvHA2vYlM5HBwxJGifZy2vUzs5Hy3rVCNpJGifHy3rPB24G5zkm5zco57UT6lwe5lQN55M76k6W5lIT6yo95B+f6Ag75Rk/55sO5RQq5PAh5PYS55Qe5y6F5AEl5OU85yAz77Ym5lIn57+76k+r44cb5lIn6z+Z6k+r44cb5lIn5Ps55OIq5lIT5PAh5zcn77YB5zob54Mm5zkm5RkH5PYj6ycA6kgm6k+r5zcn55Qe5yw25lUw5lIt5zcn5l+D55wz5y6F5PAh44cc5lIn5B6x5OQk5Pw05y+L5Asw6k+T5yQO5l2C5OIw546V5Akd5O+p6l+W5y6F5Qc355wz5zYOigfJDgLVBIdKUk3JGii","icdLKiZKUidLJ6xNLlhLPjRKURRLKiZML7BOR7tML7BVViZKUlRMR4/KUkROR7tOR53KURRLKitLHPNKUidMNAhNM7JPGRSGzgLHBg9NDwxVViXJB250zw50ioEBUowqJooaGG","6l2S5O2I6kEe5yIz77YA","44cq5B6f6kEe6iYd5yYw55Qe5y6F5PAh54Mh5Q6144cr"];return Cp=function(){return e},Cp()}async function Ig(e,t,n){let o=q,i=await e[o(41)](o(71),{system:JS,user:jS(t),responseFormat:o(16),...n?{signal:n}:{}}),r;try{r=JSON[o(28)](i[o(53)])}catch{if(o(67)!==o(67))_0x10022d=_0x3c4a29[o(28)](_0x5ecbb9[o(53)]);else throw Ra(o(19)+t[o(73)]+o(50),[i[o(53)][o(7)](0,500)])}return{raw:i[o(53)],records:Tp(r,t)}}var $p=sn,zS=$p(1);function HS(e){let t=$p,n=e[t(5)](/起点\s*[::]\s*(\d+)/);return n?{found:!0,line:Math[t(3)](Number(n[1]))}:{found:!1,line:null}}function Vp(){let e=["Dgv4Da","5l2G5PIV55+T5yMN5yMN5PYS55Qe44cm5Q2J5PAh6lw354k55A6A5l2n5zMO44cn44cc5lIa5lU95PAh5lU25BI45BI45zYO55YF5Q2J55Qe5yMN5PYS5Q2J5PAh5lMl5yMn77Ym5y6l552a5lIa5AsN5Q61kIRPNz7MRApMLOCQkUEAHoETUEwKH+ADKoAwMEoaGUs9OoIMGEwiPoAwRE+8MIOQ55YF5Q2J55Qe5yMN5PYS5Q2J5PAhkIRMMk/KUi3MMk/LNkJMIjhNU5NKVAdNMOtOV5NMRRxLUkBOOyZLJ7FNMOtMLOFMNkZPH4ZLVidLP4VVViZLPOlMNPZMMk/VViZMIQxLKyRLROpNMOtOTBFLP4VOOyZLJ7FJGiikcUoaKoATO+AwH+MvV+s7Gos5IoAGT+oaKEMaKowCUUEAHowjP+ACRo+8MUs7PEoaJoESRe7PM4BJGi3KUlRPM4BLPltVViZKUiVPNAlNTkFOT5/JGiZLNlPylvKGioAxPs/LHOuG5zYW54k544cn6l+z56En5BIM5zY65QYH57Yw5y+355Qe5zY65PMV5As077Ym5yAn5B6a5lIl5PIV44cm5lI76kAb5lQ654MP77YAl+s6UUEjQE+8MUoaJEwsJos4GoADOEADOEs7PsdILRmG5BYa5As055Qe5yQO5l2C44cb5lUL5y+k5BIM6k+06k+D5lQ655Qe5y+W6k+n44cc6l+z5OMn5PIV5Q2J5PAh44cccGRJGjdLIy3OQidPLB/KU4dKUyJMOlFVViZNU53KUi3NRPFMRApMLOFJGjhVVjOklsdPOBNNM67LN7RMNkZKV6hMGA8Gl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5lIa5Q6177Ym5Q+p6kgm5lUL44cm6kgm5y+3pfrbqJ7LHOxLRRNJGi3NU5NLH7RJGilLIktMLQ3NNj/MRApNMOtLIAFMNkZMRApMLOFMMk/LKkBLNkJOV5NMRRxPH4ZLVidLP4VVViZMJiNMOlZLVi/LJ6RLM57KUidOOyZJGiikcG"];return Vp=function(){return e},Vp()}async function Ag(e,t,n){let o=$p,i=await e[o(4)](o(2),{system:zS,user:o(6)+t,...n?{signal:n}:{}});return HS(i[o(0)])}function sn(e,t){e=e-0;let n=Vp(),o=n[e];if(sn.sLepLJ===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,g=0;u=c.charAt(g++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};sn.TPTWLA=i,sn.iYuNay={},sn.sLepLJ=!0}let r=n[0];sn.inDmHY!==r&&(sn.iYuNay={},sn.inDmHY=r);let s=sn.iYuNay[e];return s===void 0?(o=sn.TPTWLA(o),sn.iYuNay[e]=o):o=s,o}var kg=50,FS=10;async function bg(e,t,n){let o=t.split(`
244
- `),i=kg-FS;try{for(let r=0;r<o.length;r+=i){let s=Math.min(r+kg,o.length),c=o.slice(r,s).map((d,p)=>`${r+p+1} ${d}`).join(`
245
- `),a=await Ag(e,c,n);if(a.found&&a.line!==null)return{line:Math.min(Math.max(a.line-1,0),o.length-1),scannedLines:s,found:!0};if(s>=o.length)break}}catch(r){return{line:0,scannedLines:0,found:!1,error:r instanceof Error?r.message:String(r)}}return{line:0,scannedLines:o.length,found:!1}}async function Og(e,t,n){let o=new Array(e.length),i=0,r=Array.from({length:Math.max(1,Math.min(t,e.length))},async()=>{for(;;){let s=i++;if(s>=e.length)return;try{o[s]={index:s,ok:!0,value:await n(e[s],s)}}catch(c){o[s]={index:s,ok:!1,error:c}}}});return await Promise.all(r),o}var Ft=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),an=e=>Array.isArray(e);function Dp(e){let t=new Map;if(!an(e))return t;for(let n of e){if(!Ft(n))continue;let o=n.actor_id??n.location_id??n.prop_id;typeof o=="string"&&t.set(o,n)}return t}function QS(e){let t=[],n=(o,i)=>{!Ft(o)||typeof o[i]!="string"||t.push({assetId:o[i],holder:o,explicit:typeof o.state_id=="string"?o.state_id:void 0})};for(let o of an(e.episodes)?e.episodes:[])if(!(!Ft(o)||!an(o.scenes))){for(let i of o.scenes)if(Ft(i)){n(i.location,"location_id");for(let r of an(i.actors)?i.actors:[])n(r,"actor_id");for(let r of an(i.props)?i.props:[])n(r,"prop_id");for(let r of an(i.actions)?i.actions:[])Ft(r)&&n(r.speaker,"actor_id")}}return t}function YS(e,t){let n=e.filter(i=>(t.get(i.state_id)??0)>0);if(n.length===0)return null;let o=n[0];for(let i of n.slice(1)){let r=t.get(i.state_id)??0,s=t.get(o.state_id)??0;(r>s||r===s&&i.state_name<o.state_name)&&(o=i)}return o.state_id}function Ma(e){if(!Ft(e))throw new Error("govern expects a script object");let t=JSON.parse(JSON.stringify(e));for(let p of an(t.episodes)?t.episodes:[])if(!(!Ft(p)||!an(p.scenes)))for(let l of p.scenes){if(!Ft(l))continue;let f=an(l.actors)?l.actors.filter(Ft):[],u=new Set(f.map(g=>g.actor_id).filter(g=>typeof g=="string"));for(let g of an(l.actions)?l.actions:[])!Ft(g)||!Ft(g.speaker)||typeof g.speaker.actor_id!="string"||u.has(g.speaker.actor_id)||(f.push({actor_id:g.speaker.actor_id}),u.add(g.speaker.actor_id));l.actors=f}let n=Dp(t.actors),o=Dp(t.locations),i=Dp(t.props),r=new Map([...n,...o,...i]),s=QS(t),c=new Map;for(let p of s){if(p.explicit===void 0)continue;c.has(p.assetId)||c.set(p.assetId,new Map);let l=c.get(p.assetId);l.set(p.explicit,(l.get(p.explicit)??0)+1)}let a=new Map;for(let[p,l]of r){let f=(an(l.states)?l.states:[]).filter(Ft),u=new Map,g=YS(f,c.get(p)??new Map),h;if(g===null){let m=f.find(w=>w.state_id==="default");h=[{state_id:"default",state_name:m?.state_name??"default",description:m?.description??""}]}else{h=[];for(let m of f)m.state_id!=="default"&&(m.state_id===g?(u.set(m.state_id,"default"),h.unshift({state_id:"default",state_name:m.state_name,description:m.description??""})):(u.set(m.state_id,m.state_id),h.push({state_id:m.state_id,state_name:m.state_name,description:m.description??""})))}l.states=h,a.set(p,u)}let d=new Map;for(let p of s){let l=a.get(p.assetId),f;p.explicit!==void 0?(f=l?.get(p.explicit)??p.explicit,d.set(p.assetId,f)):f=d.get(p.assetId)??"default",p.holder.state_id=f}return t}var vg=cn;function cn(e,t){e=e-0;let n=Gp(),o=n[e];if(cn.vcGzia===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,g=0;u=c.charAt(g++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};cn.alaGPc=i,cn.IPZchV={},cn.vcGzia=!0}let r=n[0];cn.cEXTRr!==r&&(cn.IPZchV={},cn.cEXTRr=r);let s=cn.IPZchV[e];return s===void 0?(o=cn.alaGPc(o),cn.IPZchV[e]=o):o=s,o}var qS=vg(6);async function Rg(e,t,n,o){let i=vg;return(await e[i(4)](i(2),{system:qS,user:i(0)+t+i(3)+n,...o?{signal:o}:{}}))[i(5)][i(1)]()}function Gp(){let e=["5OQk5lIl6z2Iia","DhjPBq","Aw5Nzxn0lMfYyY1ZDw1Tyxj5","ioEAHoMaKoADOEwjP+AdHEA1K+E8QEAiKos4GoAUTEEVH+EROoAIL+AMGIGYmddIGjmZmJaG5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MLOCS5lIn6kAb5lU75l2v5yMn5zco57Ya6k+05PIo44cc"];return Gp=function(){return e},Gp()}var Ug={type:"object",required:["issues"],additionalProperties:!1,properties:{issues:{type:"array",items:{type:"object",required:["type","asset_ids","state_ids","names","evidence","recommendation","suggested_survivor","action","confidence"],additionalProperties:!1,properties:{type:{type:"string",enum:["duplicate_actor","duplicate_location","duplicate_prop","duplicate_state","suspicious_singleton_state","unused_state","needs_human_review"]},asset_ids:{type:"array",items:{type:"string"}},state_ids:{type:"array",items:{type:"string"}},names:{type:"array",items:{type:"string"}},evidence:{type:"string"},recommendation:{type:"string"},suggested_survivor:{type:["string","null"]},action:{type:"string",enum:["merge","delete","review"]},confidence:{type:"string",enum:["high","medium","low"]}}}}}},Bp={type:"array",items:{type:"object",required:["asset_id","state_id"],additionalProperties:!1,properties:{asset_id:{type:"string"},state_id:{type:["string","null"]}}}},wU={type:"object",required:["scenes"],additionalProperties:!1,properties:{scenes:{type:"array",items:{type:"object",required:["scene_id"],additionalProperties:!1,properties:{scene_id:{type:"string"},actors:{...Bp,items:{type:"object",required:["actor_id","state_id"],additionalProperties:!1,properties:{actor_id:{type:"string"},state_id:{type:["string","null"]}}}},locations:{...Bp,items:{type:"object",required:["location_id","state_id"],additionalProperties:!1,properties:{location_id:{type:"string"},state_id:{type:["string","null"]}}}},props:{...Bp,items:{type:"object",required:["prop_id","state_id"],additionalProperties:!1,properties:{prop_id:{type:"string"},state_id:{type:["string","null"]}}}},state_changes:{type:"array",items:{type:"object",required:["action_index","target_kind","target_id","to_state_id"],additionalProperties:!1,properties:{action_index:{type:"integer"},target_kind:{type:"string",enum:["actor","location","prop"]},target_id:{type:"string"},from_state_id:{type:["string","null"]},to_state_id:{type:"string"},effective_from:{type:"string",enum:["before_action","after_action"]}}}}}}}}},Pg={type:"object",required:["name","description"],additionalProperties:!1,properties:{name:{type:"string",enum:["\u5E38\u6001"],description:"\u5B9E\u4F53\u9996\u6B21\u767B\u8BB0\u65F6\u7684\u9ED8\u8BA4\u9020\u578B\u540D\uFF0C\u56FA\u5B9A\u4E3A\u5E38\u6001"},description:{type:"string",description:"\u9ED8\u8BA4\u9020\u578B\u7684\u53EF\u89C1\u5916\u89C2\uFF0C\u53EA\u5199\u5916\u8C8C\u3001\u670D\u9970\u3001\u6750\u8D28\u3001\u989C\u8272\u3001\u5E03\u666F\u6216\u5F62\u5236\uFF0C\u975E\u7A7A"}}},Cg={type:"object",required:["newEntities","merges","looks","lookChanges","subEvents","summary"],additionalProperties:!1,properties:{newEntities:{type:"array",description:"\u672C\u6BB5\u65B0\u767B\u8BB0\u7684\u5B9E\u4F53(\u4EBA\u7269/\u573A\u666F/\u9053\u5177)\u3002name=canonical\uFF0Caliases \u5217\u5168\u8FD9\u6BB5\u91CC\u5B83\u7684\u6240\u6709\u5176\u4ED6\u53EB\u6CD5",items:{type:"object",required:["kind","name","description","aliases","defaultLook"],additionalProperties:!1,properties:{kind:{type:"string",enum:["actor","location","prop"]},name:{type:"string",description:"\u7EAF canonical \u540D\uFF0C\u4E0D\u542B\u62EC\u53F7/\u659C\u6760/\u8BD1\u540D\u5939\u6CE8/\u5BF9\u767D\u6807\u8BB0"},description:{type:"string",description:"\u4E00\u53E5\u8BDD\u8BF4\u660E\u8FD9\u4E2A\u5B9E\u4F53\u672C\u8EAB\u662F\u8C01/\u4EC0\u4E48\u8EAB\u4EFD/\u4EC0\u4E48\u4E1C\u897F\uFF0C\u975E\u7A7A\uFF1B\u4EBA\u7269\u53EA\u5199\u8EAB\u4EFD\u3001\u89D2\u8272\u548C\u5173\u7CFB\uFF0C\u4E0D\u5199\u670D\u88C5\u9020\u578B"},aliases:{type:"array",items:{type:"string"},description:"\u8FD9\u6BB5\u91CC\u8BE5\u5B9E\u4F53\u7684\u6240\u6709\u5176\u4ED6\u53EB\u6CD5\uFF1A\u522B\u540D/\u8BD1\u540D/\u524D\u4E16\u540D/\u77ED\u540D\u5168\u540D/\u5BF9\u767D\u8BF4\u8BDD\u4EBA\u5728\u6B63\u6587\u91CC\u7684\u5199\u6CD5\uFF0C\u9010\u4E2A\u5355\u5217(\u7EAF\u540D\uFF0C\u4E0D\u5E26\u5BF9\u767D/\u60C5\u7EEA\u6807\u8BB0)"},defaultLook:Pg}}},merges:{type:"array",description:"\u672C\u6BB5\u91CC\u67D0\u4E2A\u5C1A\u672A\u767B\u8BB0\u7684\u79F0\u547C\uFF0C\u5176\u5B9E\u662F\u67D0\u4E2A\u5DF2\u767B\u8BB0\u5B9E\u4F53\u7684\u522B\u540D",items:{type:"object",required:["from","into"],additionalProperties:!1,properties:{from:{type:"string",description:"\u672C\u6BB5\u8FD9\u4E2A\u79F0\u547C(\u5C1A\u672A\u4F5C\u4E3A\u72EC\u7ACB\u5B9E\u4F53\u767B\u8BB0\u8FC7)"},into:{type:"string",description:"\u5B83\u6240\u6307\u7684\u5DF2\u767B\u8BB0\u5B9E\u4F53\u7684 canonical \u540D"}}}},looks:{type:"array",description:"\u9ED8\u8BA4\u9020\u578B\u4E4B\u5916\u3001\u9700\u8981\u5355\u72EC\u590D\u73B0\u7684\u65B0\u589E\u9020\u578B",items:{type:"object",required:["entity","name","aliases","description"],additionalProperties:!1,properties:{entity:{type:"string",description:"\u5B9E\u4F53 canonical \u540D"},name:{type:"string",description:"\u9020\u578B\u540D\uFF0C\u5FC5\u987B\u4E2D\u6587\uFF0C\u82F1\u6587\u4E13\u540D\u5148\u8BD1\u6210\u4E2D\u6587"},aliases:{type:"array",items:{type:"string"},description:"\u540C\u4E49\u9020\u578B\u540D"},description:{type:"string",description:"\u8FD9\u5957\u5916\u89C2\u4E00\u53E5\u8BDD"}}}},lookChanges:{type:"array",description:"\u9020\u578B\u53D8\u5316\uFF1A\u540C\u4E00\u573A\u540C\u4E00\u5B9E\u4F53\u53EF\u6309\u6B63\u6587\u987A\u5E8F\u5217\u51FA\u53D8\u5316\u524D\u540E\u5168\u90E8\u9020\u578B\uFF0C\u6700\u540E\u4E00\u6761\u7531\u540E\u7EED\u4E0D\u53D8\u7684\u573A\u7EE7\u627F\uFF1B\u56DE\u5FC6/\u9884\u6F14\u53CA\u8FD4\u56DE\u73B0\u5B9E\u5747\u663E\u5F0F\u6807\u72B6\u6001",items:{type:"object",required:["scene","entity","look"],additionalProperties:!1,properties:{scene:{type:"string",description:"\u53D8\u5316\u53D1\u751F\u7684\u573A\u666F id\uFF0C\u5982 scn_012"},entity:{type:"string",description:"\u5B9E\u4F53 canonical \u540D"},look:{type:"string",description:"\u672C\u573A\u5B9E\u9645\u51FA\u73B0\u7684\u5DF2\u767B\u8BB0\u9020\u578B\u540D\uFF1B\u540C\u573A\u591A\u9879\u6309\u6B63\u6587\u5148\u540E\u6392\u5217"}}}},subEvents:{type:"array",items:{type:"string"},description:"\u672C\u6BB5\u5173\u952E\u5267\u60C5\u539F\u5B50\uFF0C\u6BCF\u6761\u4E00\u53E5\u8BDD"},summary:{type:"string",description:"\u672C\u6BB5\u4E00\u53E5\u8BDD\u6897\u6982"}}},ZS={type:"string",enum:["actor","location","prop"]},Tg={type:"string",description:"\u9020\u578B\u6863\u4F4D\u540D\uFF0C\u53EA\u586B\u540D\u5B57\u672C\u8EAB\uFF1B\u7981\u6B62\u62EC\u53F7\u3001\u659C\u6760\u3001\u9017\u53F7\u6216\u63CF\u8FF0\u6027\u6587\u5B57"},Mg={type:"string",minLength:5,pattern:"^[0-9]{2}:[0-5][0-9](\\.[0-9]{1,3})?$",description:"\u5FC5\u586B\u3002\u672C\u955C\u5934\u6216\u58F0\u97F3\u771F\u6B63\u5F00\u59CB\u7684\u539F\u7247\u65F6\u95F4\uFF0C\u4F7F\u7528 MM:SS\uFF0C\u53EF\u4FDD\u7559\u539F\u7247\u4F9D\u636E\u652F\u6301\u7684 1\u20133 \u4F4D\u5C0F\u6570\uFF0C\u5982 00:03.240\u3002\u53EA\u6709\u6574\u79D2\u4F9D\u636E\u65F6\u5199\u6574\u79D2\uFF0C\u4E0D\u8865\u9020\u5C0F\u6570\u3002SS \u4E3A 00\u201359\uFF0C\u6574\u5206\u949F\u5199\u4E0B\u4E00\u5206\u949F\u7684 :00"},Ng={type:"object",required:["name","description"],additionalProperties:!1,properties:{name:Tg,description:{type:"string",description:"\u8BE5\u72B6\u6001\u53EF\u590D\u73B0\u7684\u6301\u7EED\u53EF\u89C1\u5916\u89C2\uFF0C\u975E\u7A7A\u3002\u4EBA\u7269\u7EFC\u5408\u591A\u4E2A\u6E05\u6670\u955C\u5934\u5E76\u4ECE\u5934\u5230\u811A\u5199\u8BE5\u9020\u578B\u7279\u6709\u7684\u5986\u53D1\u5934\u9970\u3001\u9888\u9970\u3001\u5916\u5957\u3001\u4E0A\u88C5\u3001\u4E0B\u88C5/\u8FDE\u4F53\u8863\u88D9\u3001\u889C\u7C7B\u3001\u978B\u5C65\u3001\u624B\u5957\u548C\u9970\u54C1\uFF1B\u6BCF\u4EF6\u53EF\u89C1\u5355\u54C1\u5199\u989C\u8272\u3001\u6750\u8D28/\u5149\u6CFD/\u7EB9\u7406\u3001\u7248\u578B\u677E\u7D27\u3001\u9886\u8896\u7ED3\u6784\u3001\u5F00\u5408\u3001\u8170\u7EBF\u3001\u957F\u5EA6\u3001\u4E0B\u6446\u3001\u56FE\u6848\u6587\u5B57\u3001\u6EDA\u8FB9\u91D1\u5C5E\u4EF6\u3001\u53E0\u7A7F\u5173\u7CFB\u4E0E\u6240\u5728\u4F4D\u7F6E\uFF1B\u6301\u7EED\u7834\u635F\u6C61\u6E0D\u5199\u90E8\u4F4D\u3001\u8303\u56F4\u548C\u989C\u8272\u3002\u53EA\u7701\u7565\u770B\u4E0D\u89C1\u6216\u4E0D\u80FD\u786E\u8BA4\u7684\u9879\uFF0C\u4E0D\u7528\u4E00\u53E5\u7B3C\u7EDF\u670D\u88C5\u6982\u62EC\uFF0C\u4E0D\u4ECE\u5C40\u90E8\u8865\u9020\u5168\u8EAB\u3002\u5730\u70B9\u548C\u9053\u5177\u5199\u76F8\u5BF9\u5E38\u6001\u7684\u6301\u7EED\u5916\u89C2\u5DEE\u5F02\u3002\u53EA\u5199\u753B\u9762\u4E8B\u5B9E\uFF0C\u4E0D\u5199\u52A8\u4F5C\u3001\u59FF\u6001\u3001\u60C5\u7EEA\u3001\u5FC3\u7406\u6216\u5267\u60C5\u8BC4\u4EF7"}}},Lg={type:"object",required:["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","persistent_marks","voice"],additionalProperties:!1,properties:{apparent_gender:{type:"string",description:"\u753B\u9762\u5448\u73B0\u7684\u6027\u522B\uFF1B\u65E0\u6CD5\u786E\u8BA4\u586B\u7A7A\u4E32"},apparent_age:{type:"string",description:"\u53EF\u89C1\u5E74\u9F84\u6BB5\uFF0C\u4F7F\u7528\u7A84\u800C\u5BA1\u614E\u7684\u8303\u56F4\uFF0C\u5982\u300E\u7EA625-30\u5C81\u300F\uFF1B\u65E0\u6CD5\u786E\u8BA4\u586B\u7A7A\u4E32"},face_shape:{type:"string",description:"\u8138\u90E8\u8F6E\u5ED3\u3001\u98A7\u9AA8\u3001\u4E0B\u988C\u4E0E\u4E0B\u5DF4\u7684\u5BA2\u89C2\u5F62\u6001\uFF1B\u4E0D\u5199\u5BA1\u7F8E\u3001\u6C14\u8D28\u3001\u8868\u60C5\u6216\u5267\u60C5\u5F62\u6001"},brows_eyes:{type:"string",description:"\u7709\u5F62\u3001\u7709\u8272\u3001\u773C\u578B\u3001\u773C\u8DDD\u3001\u5355\u53CC\u773C\u76AE\u53CA\u773C\u5C3E\u7684\u9759\u6001\u5F62\u6001\uFF1B\u4E0D\u5199\u76EE\u5149\u3001\u795E\u60C5\u3001\u60C5\u7EEA\u3001\u5986\u5BB9\u3001\u9690\u5F62\u773C\u955C\u6216\u53D8\u8EAB\u989C\u8272"},nose:{type:"string",description:"\u9F3B\u6881\u3001\u9F3B\u5934\u3001\u9F3B\u7FFC\u7684\u5BA2\u89C2\u5F62\u6001"},mouth:{type:"string",description:"\u9759\u6B62\u65F6\u7684\u5507\u539A\u8584\u3001\u5507\u5CF0\u3001\u5634\u89D2\u7ED3\u6784\u548C\u53E3\u5468\u7279\u5F81\uFF1B\u4E0D\u5199\u8BF4\u8BDD\u52A8\u4F5C\u3001\u8868\u60C5\u6216\u5507\u5986"},skin_features:{type:"string",description:"\u7A33\u5B9A\u80A4\u8272\u3001\u9762\u90E8\u7EB9\u7406\u3001\u75E3\u3001\u96C0\u6591\u3001\u65E7\u75A4\u7B49\u8DE8\u573A\u666F\u53EF\u89C1\u7279\u5F81\uFF1B\u4E0D\u5199\u4E34\u65F6\u4F24\u75D5\u3001\u8840\u8FF9\u3001\u6C61\u6E0D\u6216\u5986\u5BB9"},hair:{type:"string",description:"\u7A33\u5B9A\u53D1\u8272\u3001\u53D1\u9645\u7EBF\u3001\u957F\u5EA6\u3001\u5377\u76F4\u548C\u5E38\u6001\u53D1\u578B\uFF1B\u4E0D\u5199\u5047\u53D1\u3001\u53D8\u8EAB\u5F62\u6001\u6216\u4E00\u6B21\u6027\u9020\u578B\uFF0C\u4E34\u65F6\u5DEE\u5F02\u5199\u5165 states"},build:{type:"string",description:"\u53EF\u7531\u753B\u9762\u786E\u8BA4\u7684\u8EAB\u9AD8\u76F8\u5BF9\u5173\u7CFB\u3001\u80A9\u5BBD\u3001\u9AA8\u67B6\u548C\u4F53\u578B\uFF1B\u4E0D\u5199\u59FF\u6001\u3001\u52A8\u4F5C\u3001\u6C14\u8D28\u6216\u5BA1\u7F8E\u8BCD"},persistent_marks:{type:"array",items:{type:"string"},description:"\u7EB9\u8EAB\u3001\u65E7\u75A4\u3001\u75E3\u3001\u80CE\u8BB0\u3001\u56FA\u5B9A\u7A7F\u5B54\u7B49\u4E0D\u53EF\u968F\u6362\u88C5\u6458\u9664\u7684\u8EAB\u4F53\u6807\u8BB0\uFF1B\u4E0D\u5199\u8033\u73AF\u3001\u9879\u94FE\u3001\u773C\u955C\u7B49\u914D\u9970\uFF0C\u6CA1\u6709\u586B\u7A7A\u6570\u7EC4"},voice:{type:"string",description:"\u4ECE\u6E05\u6670\u539F\u58F0\u53EF\u786E\u8BA4\u7684\u97F3\u9AD8\u3001\u97F3\u8272\u3001\u8BED\u901F\u3001\u53E3\u97F3\u6216\u7A33\u5B9A\u53D1\u58F0\u8D28\u611F\uFF1B\u4E0D\u5199\u5F53\u4E0B\u60C5\u7EEA\u3001\u6001\u5EA6\u6216\u89D2\u8272\u6027\u683C\uFF0C\u542C\u4E0D\u6E05\u586B\u7A7A\u4E32"}}},Vg={type:"object",required:["synopsis","scenes","registry_delta","open_threads"],additionalProperties:!1,properties:{synopsis:{type:"string",description:"\u672C\u96C6\u5267\u60C5\u6897\u6982\uFF0C\u6309\u53D1\u751F\u987A\u5E8F\uFF0C200-300 \u5B57\u7EAF\u6587\u672C"},scenes:{type:"array",minItems:1,description:"\u672C\u96C6\u6240\u6709\u573A\u666F\u5355\u5143\uFF0C\u6309\u65F6\u95F4\u987A\u5E8F\u6392\u5217\u3002\u573A\u5185\u5C3D\u91CF\u5FE0\u5B9E\u8FD8\u539F\u539F\u7247\u5206\u955C\uFF1A\u6BCF\u6B21\u5207\u955C\u3001\u8FDE\u7EED\u955C\u5934\u5185\u7684\u6444\u5F71\u53D8\u5316\u3001\u53EF\u89C1\u8868\u6F14\u548C\u58F0\u97F3\u4E8B\u4EF6\u6309\u5B9E\u9645\u65F6\u95F4\u4EA4\u9519\u4FDD\u7559\uFF0C\u91CD\u590D\u955C\u5934\u4E5F\u4E0D\u53BB\u91CD\uFF1B\u5730\u70B9\u3001\u660E\u663E\u65F6\u6BB5\u6216\u53D9\u4E8B\u7EBF\u53D8\u5316\u65F6\u62C6\u573A\uFF0C\u666E\u901A\u5207\u955C\u4E0D\u5355\u72EC\u62C6 scene\uFF1B\u540C\u4E00\u8FDE\u7EED\u573A\u5185\u7684\u4EBA\u7269\u9020\u578B\u53D8\u5316\u4FDD\u7559\u5728\u540C\u4E00\u573A\uFF1B\u8DE8\u5730\u70B9\u8499\u592A\u5947\u62C6\u6210\u591A\u4E2A\u77ED\u573A",items:{type:"object",required:["space","time","timeRange","location","characters","props","shots","voices"],additionalProperties:!1,properties:{space:{type:"string",description:"\u5185\u666F\u586B\u300C\u5185\u300D/\u5916\u666F\u586B\u300C\u5916\u300D\uFF1B\u4E0D\u786E\u5B9A\u586B\u7A7A\u4E32"},time:{type:"string",enum:["\u65E5","\u591C","\u6668","\u660F"],description:"\u672C\u573A\u5FC5\u987B\u9009\u62E9\u4E00\u4E2A\u65F6\u6BB5\uFF1A\u767D\u5929/\u65E5\u95F4\u586B\u300C\u65E5\u300D\uFF0C\u591C\u665A/\u591C\u95F4\u586B\u300C\u591C\u300D\uFF0C\u6E05\u6668/\u9ECE\u660E\u586B\u300C\u6668\u300D\uFF0C\u9EC4\u660F/\u508D\u665A\u586B\u300C\u660F\u300D\u3002\u7ED3\u5408\u7167\u660E\u3001\u4F5C\u606F\u3001\u5929\u7A7A\u548C\u5267\u60C5\u4E0A\u4E0B\u6587\u5224\u65AD\uFF0C\u4E0D\u5F97\u7559\u7A7A"},timeRange:{type:"string",description:"\u672C\u573A\u8D77\u6B62\u65F6\u95F4 MM:SS-MM:SS\uFF0C\u53EF\u4FDD\u7559\u539F\u7247\u4F9D\u636E\u652F\u6301\u7684 1\u20133 \u4F4D\u5C0F\u6570\uFF1BSS \u4E3A 00\u201359\uFF0C\u6574\u5206\u949F\u5199\u4E0B\u4E00\u5206\u949F\u7684 :00"},location:{type:"string",description:"\u672C\u573A\u552F\u4E00\u7A33\u5B9A\u4E3B\u7A7A\u95F4\u5730\u70B9\u540D\uFF0C\u6CBF\u7528\u89C4\u8303\u540D\uFF1B\u5BA2\u5385/\u5367\u5BA4/\u536B\u751F\u95F4/\u5927\u5385/\u5E7F\u573A/\u821E\u53F0/\u540E\u53F0\u5206\u522B\u5EFA\u5730\u70B9\uFF0C\u76F8\u5173\u7A7A\u95F4\u7528\u300E\u8C6A\u5B85\xB7\u5BA2\u5385\u300F\u5F0F\u547D\u540D"},characters:{type:"array",description:"\u672C\u573A\u5728\u573A\u7684\u5177\u4F53\u5355\u4EBA\u89D2\u8272\uFF08\u7FA4\u4F17\u4E0D\u5217\uFF09\u3002\u540C\u4E00\u89D2\u8272\u53EA\u80FD\u51FA\u73B0\u4E00\u6B21\uFF1B\u5176 states \u586B\u672C\u573A\u51FA\u73B0\u8FC7\u7684\u5168\u90E8\u7A33\u5B9A\u9020\u578B/\u72B6\u6001\u96C6\u5408",items:{type:"object",required:["name","states"],additionalProperties:!1,properties:{name:{type:"string",description:"\u89D2\u8272\u89C4\u8303\u540D"},states:{type:"array",items:Tg,description:"\u672C\u573A\u8BE5\u89D2\u8272\u51FA\u73B0\u8FC7\u7684\u5168\u90E8\u9020\u578B/\u72B6\u6001\u540D\u96C6\u5408\u3002\u6BCF\u4E2A\u72B6\u6001\u662F\u6574\u5957\u7740\u88C5\u6863\u4F4D\u540D\uFF0C\u53EA\u586B\u540D\u5B57\u672C\u8EAB\uFF1B\u7981\u6B62\u62EC\u53F7\u3001\u659C\u6760\u3001\u9017\u53F7\u6216\u63CF\u8FF0\u6587\u5B57\uFF08\u9519\u8BEF\uFF1A\u300E\u9ED1\u4E1D\u77ED\u88D9\uFF08\u8EAB\u7A7F\u6536\u94F6\u77ED\u8896\uFF09\u300F\u300E\u9ED1\u4E1D\u77ED\u88D9/\u7EF7\u5E26\u77ED\u88D9\u300F\uFF1B\u6B63\u786E\uFF1A\u300E\u9ED1\u4E1D\u77ED\u88D9\u300F\uFF09\u3002\u540C\u4E00\u5957\u9020\u578B\u6CBF\u7528\u5DF2\u77E5\u8BBE\u5B9A\u91CC\u7684\u65E2\u6709\u540D\uFF1B\u6CA1\u6362\u88C5\u6216\u770B\u4E0D\u6E05\u586B\u7A7A\u6570\u7EC4\u3002\u4E0D\u5F97\u4E3A\u540C\u4E00\u89D2\u8272\u62C6\u6210\u591A\u6761\u8BB0\u5F55"}}}},props:{type:"array",items:{type:"string"},description:"\u672C\u573A\u5728\u573A\u7684\u5173\u952E\u9053\u5177\u540D"},shots:{type:"array",description:"\u672C\u573A\u72EC\u7ACB\u7684\u9010\u955C\u6E05\u5355\uFF0C\u4E0E\u58F0\u97F3\u5206\u5F00\u76D8\u70B9\u3002\u539F\u7247\u6BCF\u6B21\u5207\u955C\u90FD\u5FC5\u987B\u6709\u4E00\u6761\uFF0C\u91CD\u590D\u955C\u5934\u4E5F\u4E0D\u53BB\u91CD\uFF1B\u8FDE\u7EED\u955C\u5934\u5185\u7684\u6444\u5F71\u6216\u8868\u6F14\u53D8\u5316\u53E6\u589E\u4E00\u6761\u3002\u4E0D\u56E0\u4E3A\u53F0\u8BCD\u8FDE\u7EED\u6216\u5267\u60C5\u76EE\u7684\u76F8\u540C\u800C\u7701\u7565\u5206\u955C",items:{type:"object",required:["ts","camera","visual"],additionalProperties:!1,properties:{ts:Mg,camera:{type:"string",description:"\u672C\u955C\u5934\u53EF\u786E\u8BA4\u7684\u5207\u6362\u5173\u7CFB\u3001\u666F\u522B\u3001\u89D2\u5EA6\u3001\u673A\u4F4D\u3001\u8FD0\u955C\u3001\u6784\u56FE\u3001\u7126\u70B9\u548C\u753B\u9762\u4E3B\u4F53\uFF1B\u53EA\u5199\u539F\u7247\u80FD\u786E\u8BA4\u7684\u6444\u5F71\u4E8B\u5B9E\uFF0C\u4E0D\u63A8\u6D4B\u955C\u5934\u53C2\u6570\u6216\u62CD\u6444\u610F\u56FE"},visual:{type:"string",description:"\u672C\u955C\u5934\u5B9E\u9645\u53EF\u89C1\u7684\u73AF\u5883\u3001\u4EBA\u7269\u5360\u4F4D\u4E0E\u7AD9\u4F4D\u3001\u59FF\u6001\u3001\u9762\u5411\u3001\u89C6\u7EBF\u3001\u8868\u60C5\u3001\u63A5\u89E6\u3001\u52A8\u4F5C\u5BF9\u8C61\u3001\u9053\u5177\u548C\u7ED3\u679C\uFF1B\u53EA\u5199\u753B\u9762\u4E8B\u5B9E\uFF0C\u4E0D\u7528\u60C5\u7EEA\u3001\u6001\u5EA6\u6216\u5FC3\u7406\u6982\u62EC"}}}},voices:{type:"array",description:"\u672C\u573A\u72EC\u7ACB\u7684\u58F0\u97F3\u6E05\u5355\u3002\u5B8C\u6574\u4FDD\u7559\u51FA\u955C\u5BF9\u767D\u3001\u753B\u5916\u5BF9\u767D\u3001\u89D2\u8272\u5185\u5FC3\u72EC\u767D/\u81EA\u8FF0\u3001\u5BA2\u89C2\u65C1\u767D\u3001\u7535\u8BDD/\u5E7F\u64AD/\u8BBE\u5907\u58F0\u548C\u7FA4\u4F53\u58F0\u3002\u53F0\u8BCD\u8DE8\u955C\u65F6\u6309\u81EA\u7136\u8BED\u53E5\u62C6\u5206\uFF0C\u4E0D\u5F97\u628A\u8DE8\u591A\u4E2A\u955C\u5934\u7684\u591A\u53E5\u53F0\u8BCD\u5408\u5E76\u6210\u4E00\u6761",items:{type:"object",required:["kind","speaker","parenthetical","ts","content"],additionalProperties:!1,properties:{kind:{type:"string",enum:["dlg","think"],description:"dlg=\u4EBA\u7269\u5BF9\u4ED6\u4EBA\u8BF4\u51FA\u7684\u58F0\u97F3\u6216\u5BA2\u89C2\u65C1\u767D\uFF1Bthink=\u97F3\u8F68\u5B9E\u9645\u5305\u542B\u3001\u660E\u786E\u5C5E\u4E8E\u67D0\u89D2\u8272\u7684\u5185\u5FC3\u72EC\u767D/\u7B2C\u4E00\u4EBA\u79F0\u81EA\u8FF0"},speaker:{type:"string",description:"\u8BF4\u8BDD\u4EBA\u89C4\u8303\u540D\uFF1B\u5BA2\u89C2\u53D9\u8FF0\u8005\u6216\u8EAB\u4EFD\u4E0D\u660E\u65C1\u767D\u7528\u300Ebroadcast:\u65C1\u767D\u300F\uFF0C\u5E7F\u64AD\u7528\u300Ebroadcast:\u540D\u300F\uFF0C\u65E0\u6CD5\u533A\u5206\u6210\u5458\u7684\u7FA4\u4F53\u5171\u540C\u53D1\u58F0\u7528\u300Egroup:\u7FA4\u4F53\u540D\u300F"},parenthetical:{type:"string",description:"\u53EF\u786E\u8BA4\u7684\u53D1\u58F0\u65B9\u5F0F\u3001\u58F0\u97F3\u6765\u6E90\uFF0C\u6216\u4E0E\u53F0\u8BCD\u540C\u65F6\u53D1\u751F\u7684\u77ED\u4FC3\u53EF\u89C1\u8868\u6F14\uFF1B\u6CA1\u6709\u5219\u586B\u7A7A\u4E32\u3002\u6444\u5F71\u8C03\u5EA6\u548C\u5F71\u54CD\u8FDE\u7EED\u6027\u7684\u52A8\u4F5C\u5C5E\u4E8E shots\uFF0C\u4E0D\u5199\u5728\u8FD9\u91CC\uFF1B\u4E0D\u7528\u62BD\u8C61\u60C5\u7EEA\u3001\u6001\u5EA6\u6216\u5FC3\u7406\u6807\u7B7E"},ts:Mg,content:{type:"string",description:"\u9010\u5B57\u4FDD\u7559\u97F3\u8F68\u5B9E\u9645\u8BED\u8A00\u548C\u5939\u6742\u8BED\u8A00\uFF0C\u4E0D\u7FFB\u8BD1\u3001\u4E0D\u6539\u5199\u3001\u4E0D\u7528\u7FFB\u8BD1\u5B57\u5E55\u66FF\u6362\u5916\u8BED\u539F\u58F0"}}}}}}},registry_delta:{type:"object",description:"\u5BF9\u5DF2\u77E5\u8BBE\u5B9A\u7684\u589E\u91CF\u7EF4\u62A4\u3002\u5DF2\u6709\u4E14\u65E0\u65B0\u4FE1\u606F\u7684\u5B9E\u4F53\u4E00\u4E2A\u5B57\u90FD\u522B\u5199",required:["new_entities","enrich","canonicalize"],additionalProperties:!1,properties:{new_entities:{type:"array",description:"\u672C\u96C6\u9996\u6B21\u51FA\u73B0\u3001\u4E14\u5DF2\u77E5\u8BBE\u5B9A\u91CC\u6CA1\u6709\u7684\u5B9E\u4F53\u3002\u5FC5\u987B\u8986\u76D6 scenes.location\u3001scenes.characters\u3001scenes.props \u548C\u4EBA\u7269 voices.speaker \u4E2D\u6240\u6709\u65E0\u6CD5\u89E3\u6790\u5230\u5DF2\u77E5\u8BBE\u5B9A\u6216 canonicalize \u76EE\u6807\u7684\u540D\u79F0\uFF1B\u53EA\u767B\u8BB0\u5177\u4F53\u5355\u4EBA\u89D2\u8272\u3001\u7A33\u5B9A\u5730\u70B9\u548C\u5173\u952E\u9053\u5177\uFF0C\u7FA4\u4F17\u4E0D\u767B\u8BB0",items:{type:"object",required:["name","kind","status","importance","recognition_anchors","identity_profile","appearance","role","states","aliases"],additionalProperties:!1,properties:{name:{type:"string",description:"\u89C4\u8303\u540D\uFF1B\u8BA4\u4E0D\u51FA\u4E14\u65E0\u672C\u540D\u7684\u4EBA\u7528\u300E\u7A33\u5B9A\u5916\u89C2\u7279\u5F81+\u5E74\u9F84\u6BB5+\u6027\u522B\u300F\u6784\u6210\u4E0D\u542B\u59D3\u7684\u63CF\u8FF0\u540D\uFF0C\u7EDD\u4E0D\u7F16\u5E26\u59D3\u5047\u540D"},kind:ZS,status:{type:"string",enum:["canonical","provisional"],description:"canonical=\u8EAB\u4EFD\u5DF2\u786E\u8BA4\uFF1Bprovisional=\u8BA4\u4E0D\u51FA/\u672A\u70B9\u540D\uFF0C\u5F85\u540E\u7EED\u7528\u76F4\u63A5\u547D\u540D\u8BC1\u636E\u5347\u7EA7\u89C4\u8303\u540D"},importance:{type:"string",enum:["featured","background"]},recognition_anchors:{type:"array",items:{type:"string"},description:"\u4EBA\u7269\u586B\u5199 3-6 \u6761\u8DE8\u96C6\u91CD\u8BA4\u951A\u70B9\uFF0C\u6BCF\u6761\u7EC4\u5408\u81F3\u5C11\u4E24\u4E2A\u53EF\u5728 identity_profile \u627E\u5230\u4F9D\u636E\u7684\u7A33\u5B9A\u7279\u5F81\uFF1B\u7981\u6B62\u670D\u88C5\u3001\u53F7\u7801\u3001\u5E3D\u5B50\u3001\u773C\u955C/\u914D\u9970\u3001\u5986\u5BB9\u3001\u8868\u60C5\u52A8\u4F5C\u3001\u4E34\u65F6\u4F24\u75D5\u6C61\u6E0D\u3001\u5267\u60C5\u8EAB\u4EFD\u80FD\u529B\u5173\u7CFB\u3001\u53D8\u8EAB\u5F62\u6001\u6216\u573A\u666F\u7269\u4EF6\uFF1B\u5730\u70B9/\u9053\u5177\u586B\u7A7A\u6570\u7EC4"},identity_profile:Lg,appearance:{type:"string",description:"\u5730\u70B9/\u9053\u5177\u7684\u7A33\u5B9A\u53EF\u89C1\u63CF\u8FF0\uFF0C\u4EBA\u7269\u586B\u7A7A\u4E32\u3002\u5730\u70B9\u5199\u7A7A\u95F4\u7ED3\u6784\u3001\u6750\u8D28\u3001\u8272\u5F69\u548C\u56FA\u5B9A\u9648\u8BBE\uFF1B\u9053\u5177\u5199\u5F62\u5236\u3001\u6750\u8D28\u3001\u989C\u8272\u548C\u5C3A\u5BF8\u5173\u7CFB"},role:{type:"string",description:"\u5B9E\u4F53\u7684\u8EAB\u4EFD\u3001\u5173\u7CFB\u6216\u7528\u9014\uFF0C\u975E\u7A7A\uFF1B\u53EA\u5199\u539F\u7247\u53EF\u786E\u8BA4\u7684\u8BBE\u5B9A"},states:{type:"array",items:Ng,description:"\u672C\u96C6\u8BE5\u5B9E\u4F53\u51FA\u73B0\u7684\u6301\u4E45\u89C6\u89C9\u72B6\u6001\u3002\u6BCF\u9879\u540C\u65F6\u7ED9\u51FA\u7B80\u6D01\u7A33\u5B9A\u72B6\u6001\u540D\u4E0E\u4ECE\u591A\u4E2A\u6E05\u6670\u955C\u5934\u6C47\u603B\u7684\u53EF\u590D\u73B0\u8BE6\u7EC6\u63CF\u8FF0\uFF1B\u6CA1\u6709\u72EC\u7ACB\u72B6\u6001\u586B\u7A7A\u6570\u7EC4"},aliases:{type:"array",items:{type:"string"},description:"\u672C\u96C6\u89C1\u5230\u7684\u5176\u5B83\u79F0\u547C"}}}},enrich:{type:"array",description:"\u5BF9\u5DF2\u77E5\u8BBE\u5B9A\u91CC\u5DF2\u6709\u5B9E\u4F53\u7684\u8865\u5145/\u66F4\u6B63\uFF0C\u53EA\u5199\u53D1\u751F\u53D8\u5316\u7684\u5B57\u6BB5\uFF1B\u65E0\u53D8\u5316\u7684\u5B57\u6BB5\u586B\u7A7A\u4E32/\u7A7A\u6570\u7EC4\uFF0C\u6574\u4F53\u65E0\u53D8\u5316\u7684\u5B9E\u4F53\u4E0D\u8981\u51FA\u73B0",items:{type:"object",required:["name","add_recognition_anchors","identity_profile_patch","appearance","role","add_aliases","add_states"],additionalProperties:!1,properties:{name:{type:"string",description:"\u5DF2\u77E5\u5B9E\u4F53\u7684\u89C4\u8303\u540D"},add_recognition_anchors:{type:"array",items:{type:"string"},description:"\u672C\u96C6\u65B0\u589E\u3001\u4E14\u6BCF\u4E2A\u8BCD\u90FD\u80FD\u7531 identity_profile \u7A33\u5B9A\u5B57\u6BB5\u652F\u6301\u7684\u9AD8\u533A\u5206\u5EA6\u4EBA\u7269\u91CD\u8BA4\u951A\u70B9\uFF1B\u7981\u6B62\u670D\u88C5\u914D\u9970\u3001\u8868\u60C5\u52A8\u4F5C\u3001\u4E34\u65F6\u5916\u89C2\u3001\u5267\u60C5\u8BBE\u5B9A\u548C\u53D8\u8EAB\u5F62\u6001\uFF1B\u6CA1\u6709\u586B\u7A7A\u6570\u7EC4"},identity_profile_patch:Lg,appearance:{type:"string",description:"\u5730\u70B9/\u9053\u5177\u66F4\u51C6\u786E\u7684\u7A33\u5B9A\u5916\u89C2\uFF1B\u4EBA\u7269\u6216\u65E0\u66F4\u65B0\u586B\u7A7A\u4E32"},role:{type:"string",description:"\u66F4\u660E\u786E\u7684\u8EAB\u4EFD\uFF1B\u65E0\u66F4\u65B0\u586B\u7A7A\u4E32"},add_aliases:{type:"array",items:{type:"string"},description:"\u672C\u96C6\u65B0\u51FA\u73B0\u7684\u79F0\u547C"},add_states:{type:"array",items:Ng,description:"\u672C\u96C6\u9996\u6B21\u51FA\u73B0\u7684\u65B0\u72B6\u6001\uFF0C\u6216\u672C\u96C6\u4ECE\u66F4\u591A\u89D2\u5EA6\u83B7\u5F97\u4E86\u66F4\u6E05\u6670\u7EC6\u8282\u7684\u65E2\u6709\u72B6\u6001\uFF1B\u65E2\u6709\u72B6\u6001\u9010\u5B57\u6CBF\u7528\u5176 name\uFF0C\u4EE5\u540C\u540D\u9879\u8865\u5168\u6216\u66F4\u65B0\u8BE6\u7EC6 description\uFF0C\u4E0D\u53E6\u5EFA\u8FD1\u4E49\u72B6\u6001"}}}},canonicalize:{type:"array",description:"\u4EC5\u51ED\u672C\u96C6\u76F4\u63A5\u51FA\u73B0\u7684\u4E66\u9762\u6B63\u5F0F\u59D3\u540D\u6216\u53F0\u8BCD\u672C\u540D\uFF0C\u628A\u5DF2\u77E5\u4EBA\u7269\u7684\u63CF\u8FF0\u540D\u3001\u7B80\u79F0\u6216\u4E0D\u5B8C\u6574\u59D3\u540D\u5347\u7EA7\u4E3A\u66F4\u51C6\u786E\u7684\u89C4\u8303\u540D\uFF1B\u5267\u60C5\u63A8\u65AD\u4E0D\u80FD\u5355\u72EC\u4F5C\u4E3A\u6539\u540D\u8BC1\u636E",items:{type:"object",required:["from_name","canonical_name","evidence"],additionalProperties:!1,properties:{from_name:{type:"string",description:"\u5DF2\u77E5\u8BBE\u5B9A\u4E2D\u7684\u5F53\u524D\u89C4\u8303\u540D\u6216\u65E2\u6709\u522B\u540D"},canonical_name:{type:"string",description:"\u4E66\u9762\u6B63\u5F0F\u59D3\u540D\u6216\u53F0\u8BCD\u76F4\u63A5\u8BF4\u51FA\u7684\u672C\u540D"},evidence:{type:"string",description:"\u76F4\u63A5\u547D\u540D\u8BC1\u636E\uFF0C\u5FC5\u987B\u5305\u542B MM:SS \u65F6\u95F4\u6233\u4EE5\u53CA\u753B\u9762\u539F\u6587\u6216\u542C\u5230\u7684\u539F\u8BDD"}}}}}},open_threads:{type:"object",required:["opened","closed"],additionalProperties:!1,properties:{opened:{type:"array",description:"\u672C\u96C6\u65B0\u5F00\u3001\u5C1A\u672A\u4EA4\u4EE3\u7ED3\u679C\u7684\u60AC\u5FF5/\u5173\u7CFB\u53D8\u5316",items:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}},closed:{type:"array",description:"\u672C\u96C6\u4EA4\u4EE3\u4E86\u7ED3\u679C\u3001\u8981\u5173\u95ED\u7684\u5DF2\u77E5\u7EBF\u7D22 id\uFF08\u5982 t3_1\uFF09",items:{type:"object",required:["ref"],additionalProperties:!1,properties:{ref:{type:"string"}}}}}}}},$g={type:"object",required:["merges","newEntities"],additionalProperties:!1,properties:{merges:{type:"array",description:"\u672A\u767B\u8BB0\u540D\u5B57\u5176\u5B9E\u662F\u67D0\u5DF2\u767B\u8BB0\u5B9E\u4F53\u7684\u522B\u540D",items:{type:"object",required:["from","into"],additionalProperties:!1,properties:{from:{type:"string",description:"\u8FD9\u4E2A\u672A\u767B\u8BB0\u7684\u540D\u5B57"},into:{type:"string",description:"\u5B83\u6240\u6307\u7684\u5DF2\u767B\u8BB0\u5B9E\u4F53 canonical \u540D"}}}},newEntities:{type:"array",description:"\u786E\u5B9E\u662F\u5168\u65B0\u5B9E\u4F53\u7684\u540D\u5B57\uFF0C\u5404\u767B\u8BB0\u4E00\u6761",items:{type:"object",required:["kind","name","description","aliases","defaultLook"],additionalProperties:!1,properties:{kind:{type:"string",enum:["actor","location","prop"]},name:{type:"string",description:"\u7EAF canonical \u540D"},description:{type:"string",description:"\u4E00\u53E5\u8BDD\u8EAB\u4EFD\uFF0C\u975E\u7A7A\uFF1B\u4EBA\u7269\u4E0D\u5199\u670D\u88C5\u9020\u578B"},aliases:{type:"array",items:{type:"string"},description:"\u5176\u4ED6\u53EB\u6CD5"},defaultLook:Pg}}}}};var z=dn;function dn(e,t){e=e-0;let n=Jp(),o=n[e];if(dn.AowUYu===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,g=0;u=c.charAt(g++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};dn.vGSHGD=i,dn.ykrKeL={},dn.AowUYu=!0}let r=n[0];dn.qbkWqr!==r&&(dn.ykrKeL={},dn.qbkWqr=r);let s=dn.ykrKeL[e];return s===void 0?(o=dn.vGSHGD(o),dn.ykrKeL[e]=o):o=s,o}var WS=[z(37),z(84),z(100),z(83),z(39),"",z(71),z(55),z(1),z(47),z(10),z(70),z(56),z(46),z(92),z(2),z(61),z(24),z(82),z(51),z(79),z(88),z(58),z(30),z(65),z(73),z(27),z(59),z(86)][z(33)](`
246
- `);function XS(e,t){let n=z;return[n(4),e[n(50)]()||n(5),"",n(66),t[n(50)]()][n(33)](`
247
- `)}async function Dg(e,t,n,o){let i=z,r=await e[i(45)](i(69),{system:WS,user:XS(t,n),tool:{name:i(44),description:i(22),inputSchema:Cg},...o?{signal:o}:{}});return{delta:rs(r[i(49)]),raw:JSON[i(38)](r[i(49)])}}var eI=new Set([z(60),z(40),z(99)]),wi=e=>typeof e===z(78)&&e!==null&&!Array[z(13)](e),Xn=e=>typeof e===z(9)?e[z(50)]():"";function Na(e,t){let n=z,o=Xn(e);if(!o)throw new Ve(t+n(36));return o}function tI(e,t){let n=z;if(!wi(e))throw new Ve(t+n(31));let o=Na(e[n(32)],t+n(90));if(o!=="\u5E38\u6001")throw new Ve(t+n(29));return{name:o,description:Na(e[n(15)],t+n(93))}}var Ve=class extends Error{[z(12)]=z(34);constructor(t){let n=z;super(t),this[n(32)]=n(0)}};function nI(e){let t=z,n="",o=!1;for(let i=0;i<e[t(28)];i++){let r=e[i];if(!o)if(t(48)!==t(67)){n+=r,r==='"'&&(o=!0);continue}else throw new _0x293dd1(_0x17bbe5+t(89)+(_0x24ef46 instanceof _0x59e65f?_0x136fee[t(20)]:_0x3dfec6(_0x4eb04e)));if(r==="\\"&&i+1<e[t(28)]){n+=r+e[i+1],i++;continue}if(r==='"'){let s=i+1;for(;s<e[t(28)]&&/\s/[t(77)](e[s]);)s++;let c=s<e[t(28)]?e[s]:"";if(c===""||c===","||c==="}"||c==="]"||c===":")if(t(35)===t(35))n+=r,o=!1;else return[t(4),_0x49903e[t(50)]()||t(5),"",t(66),_0x1df459[t(50)]()][t(33)](`
248
- `);else n+='\\"';continue}n+=r}return n}function oI(e,t){let n=z,o=r=>JSON[n(101)](r),i;try{i=o(e)}catch(r){let s=nI(e);if(s===e)throw new Ve(t+n(89)+(r instanceof Error?r[n(20)]:String(r)));try{i=o(s)}catch(c){throw new Ve(t+n(26)+(c instanceof Error?c[n(20)]:String(c)))}}if(!Array[n(13)](i))if(n(6)===n(54))_0x291b73=_0x1aa471(_0x238c2b);else throw new Ve(t+n(91)+typeof i);return i}function hi(e,t){let n=z;if(e==null)return[];if(Array[n(13)](e))return e;if(typeof e===n(9)){let o=e[n(50)]();return o?oI(o,t):[]}throw new Ve(t+n(19)+typeof e)}var iI=/[((]([^))]*)[))]?/;function Jp(){let e=["u2vYAwfSrgvSDgftAgfWzuvYCM9Y","icdcTYbHBgLHC2vZid0G6l+z5Q616yEm6k+L5A6E5l2t55QekIRMIydMNiNLHBBKU5BLJ6VMS5uQkU+8JoMaKos4QUwnLEwiL++8IoE6R+wqJE+8JowiQ+w4PUoaJU+8Iow/G++8IEoaJ+oaJU+8MUoaJ+oaJU+8JoMTGUIVREoaJ+I/MEEXU+wVUEEzVs/MG4xNU6RMOiFORRdVViNVVjRLIkVLKi3JGihOR5hLKi3JGihLIy3KUjBLKi3JGihNN63LKi0V5ywO5zcn44cb6iUX5PAh5y6F5zcn77YmkIRLSktLHBBLR7NNMB3OR7tOR53KURRLNkJMRApMLOFPH4ZNMOtLHPNMS5uQkUoaGUATO+AwH+IVToIVNEs6UUwgMEoaJUs8IUAwH8k35BId6Bkb5ywl5PAV44cp6icm5l2GignHBM9UAwnHBcdMMk/JGi7LPkFNIzVJGi/IHPiG5OQk44co5lYk5PAhWRFLUipPSOhLHyVMLQ/JGi/MLl7OV5SGywXPyxnLC++8M+wgMEoaJUwKP+MQQooaJ+IaJcbJyw5VBMLJywWG5PIV44co5AsN6AQO5As044cp4OAsigfSAwfZzxmG5Ps+44co5AsN6AQO44cp44cc57o757UF6z2GigfSAwfZzx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k5lIa5Q615l2G5BEY5BU656Ul55Qe55M76k6W77YB5BYa56+h5PE25lI656M677Yj","77Yi56M677Ym5lUo6l+z5lIa5Q615BYa5AEl5BU656Ul77Yj","zfnRChe","Bg9VA3mU","rejIDvm","C3rYAw5N","icdcTYbRAw5KpwfJDg9Yl2XVy2f0Aw9Ul3bYB3dJGii","zNjVBq","y29Kzq","AxnbCNjHEq","zxHLyW","zgvZy3jPChrPB24","ywXPyxnLCW","zw50Axr5","zMLSDgvY","oIbLEhbLy3rLzcbHCNjHEsWGz290ia","BwvZC2fNzq","zgvSDge6ihrVCc1SzxzLBcbku09oihn0CMLUzYbTDxn0igjLigfUig9IAMvJDcWGz290ia","6l+u5zUE5PYS5Q6155Qe6lwe5lQNl+MaOowEIY/LNlRMMA8GrgvSDge","Cvjbrwe","kIRMRApMLOFPH4ZMR4/KUkRLKOZLT7lNMBVORRaGy2fUB25Py2fSiowgMEAZLEs4JEwqJoEAHowqJEwTL++8JoMdVEIMGEEuQcbTzxjNzxmG5B2s6l+h5y67kIRIGjtIGjtNS7VNU5/KVjRNHACGBwvYz2vZicSGywXPyxnLCYdMIORMRApMLOFVViJLR7NNMB3OR7tOR53KURRJGihML4hNMB3MLOFMNkZVViNPH4ZNMOtOV5NKUPVLHPNMS5xNM7tMJQxMLlNLHPNMIjaGy2fUB25Py2fS44cckIRMVi/MJONMN5dKUkRLHPNMS5xVViZLROpLSlhKVjRLJ5JMIjdKUidKUkRMUlJNPRVNMOtPH43LPi3LRP7KVzpJGiiQkIdMIydKU6xMNkZMRRxMRApMLOFPH4ZLH7RNJRdNMOtMR4/KUkRKURRLKi0V56EW5zg877Ym6kAb5lMi5PYS6lQR5BcX5PIV5P+qignHBM9UAwnHBo+8JoIMGEs5IowCQcbHBgLHC2vZl21LCMDLCYdPH4ZNMBVORRdOV4FJGii","BMv3rw50AxrPzxm","oIbLEhbLy3rLzcbku09oigfYCMf5ihn0CMLUzYWGCgfYC2uGzMfPBgvKigfMDgvYihf1B3rL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Lzcbku09oigfYCMf5ihn0CMLUzYWGCgfYC2uGzMfPBgvKoIa","lM5HBwu","oIbLEhbLy3rLzcbku09oigfYCMf5ihn0CMLUzYWGz290ia","icdcTYdLT7lNMBVORRdOV4FNMOtLRP7KVzpKUi3OPOhPH43LPi3NMBVORRdVVjVOI6xLROpOV5NMRRxMNiNKUOBMLRdLJ6VMS5xVViZNLkGGBwvYz2vZioIHPE+8Jos4JEEuQowCQcbUzxDfBNrPDgLLCYdLHO3LIjFKUidPGy3JGii","lMrLC2nYAxb0Aw9U","Bg9VA3mUywXPyxnLCW","DgPUuMy","C3vIrxzLBNrZ","C3vTBwfYEq","C2XPy2u","ChjVCa","kIRJGjdMNkZMRRxMRApMLOFJGjhLJ6/OG73LJixLKkVOI6xLUBlPM4yQkU+8IoAVJ+MBHUs7PsbGiYbLCf9otK5Giow8GowKTo+8IE+8M+AkIUwUG+s7Row9K+s9NoI/NUE7REAoQoI/M+EAHos4GoAUTEAvTos9K+wKHoEqHU+8JoI3QoMBHUAYV+EuQowqJos4GcbJyw5VBMLJywWG5zcn5A2x44cc","CgfYC2u","C3bSAxq","Bg9VAW"];return Jp=function(){return e},Jp()}function jp(e){let t=z,n=Xn(e),o=iI[t(14)](n);if(!o)return{name:n,aliases:[]};let i=n[t(98)](0,o[t(64)])[t(50)]();if(!i)return{name:n,aliases:[]};let r=(o[1]??"")[t(102)](/[//,,、;;]/)[t(63)](s=>s[t(50)]())[t(18)](Boolean);return{name:i,aliases:r}}var yi=e=>jp(Xn(e))[z(32)];function rI(e){let t=z;if(wi(e))return e;if(typeof e===t(9))if(t(74)!==t(72)){let n=e[t(50)]();if(!n)return null;let o;try{t(41)!==t(8)?o=JSON[t(101)](n):_0x2b8a69+='\\"'}catch(i){throw t(23)!==t(23)?new _0x35d905(t(21)+typeof _0x315295):new Ve(t(53)+(i instanceof Error?i[t(20)]:String(i)))}if(!wi(o)){if(t(3)===t(3))throw new Ve(t(21)+typeof o);{let i=_0x2bdcc7(_0x2ac405);if(i===_0x1e5cf5)throw new _0x4316f0(_0x174809+t(89)+(_0x4121a6 instanceof _0x360b19?_0x4fe8c8[t(20)]:_0x4a58de(_0x51367b)));try{_0x35ac52=_0x593204(i)}catch(r){throw new _0x445300(_0x1d355a+t(26)+(r instanceof _0xcc0770?r[t(20)]:_0x4eee3d(r)))}}}return o}else _0x2ddf79+=_0x1d0308,_0x1ed397=!1;return null}function rs(e){let t=z,n=yg(),o=rI(e);if(!o)return n;for(let i of hi(o[t(25)],t(25))){if(!wi(i))continue;let r=Xn(i[t(52)]),{name:s,aliases:c}=jp(Xn(i[t(32)]));if(!eI[t(62)](r)||!s)continue;let a=Na(i[t(15)],t(81)+s+t(93)),d=tI(i[t(75)],t(81)+s+t(43)),p=[...c];for(let f of hi(i[t(16)],t(68))){let{name:u,aliases:g}=jp(Xn(f));u&&p[t(76)](u),p[t(76)](...g)}let l=[...new Set(p[t(18)](f=>f&&f!==s))];n[t(25)][t(76)]({name:s,kind:r,description:a,aliases:l,defaultLook:d})}for(let i of hi(o[t(57)],t(57))){if(!wi(i))continue;let r=yi(i[t(11)]),s=yi(i[t(80)]);r&&s&&r!==s&&n[t(57)][t(76)]({from:r,into:s})}for(let i of hi(o[t(42)],t(42))){if(t(95)!==t(95))throw new _0x2df008(_0x519dc7+t(26)+(_0x40bcf4 instanceof _0x3611af?_0x4f83a8[t(20)]:_0x281cd0(_0x1f7db9)));{if(!wi(i))continue;let r=yi(i[t(17)]),s=yi(i[t(32)]);if(!r||!s)continue;let c=[s,...hi(i[t(16)],t(94))[t(63)](yi)[t(18)](Boolean)];n[t(42)][t(76)]({entity:r,names:c,description:Na(i[t(15)],t(7)+r+"."+s+t(93))})}}for(let i of hi(o[t(85)],t(85))){if(!wi(i))continue;let r=Xn(i[t(87)]),s=yi(i[t(17)]),c=yi(i[t(103)]);r&&s&&c&&n[t(85)][t(76)]({scene:r,entity:s,look:c})}return n[t(96)]=hi(o[t(96)],t(96))[t(63)](Xn)[t(18)](Boolean),n[t(97)]=Xn(o[t(97)]),n}var Ze=pn,sI=[Ze(1),Ze(29),Ze(18),Ze(32),Ze(0),Ze(7),Ze(15),Ze(8),Ze(3)][Ze(21)](`
249
- `);function aI(e,t){let n=Ze;return[n(13),e[n(27)]()||n(19),"",n(4),t[n(14)](o=>"- "+o)[n(21)](`
238
+ `);return d.trim()===""?!1:(i.push({index:i.length,core_line_start:r,core_line_end:a,text:d}),r=a,s=0,!0)};for(let a=0;a<o.length;a++){let d=o[a],l=s+(a===r?0:1)+d.length;d.trim()!==""&&a>r&&l>n&&c(a)?s=d.length:s=l}return c(o.length),i}var gg=["episode","scene","action","dialogue","inner_thought","transition","note"];var IS={day:"day",\u65E5:"day",\u767D\u5929:"day",\u65E5\u95F4:"day",\u663C:"day",\u663C\u95F4:"day",night:"night",\u591C:"night",\u591C\u665A:"night",\u591C\u95F4:"night",\u665A:"night",dawn:"dawn",\u6668:"dawn",\u6E05\u6668:"dawn",\u65E9\u6668:"dawn",\u9ECE\u660E:"dawn",\u62C2\u6653:"dawn",dusk:"dusk",\u660F:"dusk",\u9EC4\u660F:"dusk",\u508D\u665A:"dusk",\u65E5\u843D:"dusk"};function Lo(e){if(typeof e!="string")return;let t=e.normalize("NFC").replace(/\s+/g,"").trim().toLocaleLowerCase();return IS[t]}var we=class extends Error{constructor(n,o){super(`line ${o}: ${n}`);this.line=o}line};function rr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function on(e,t,n){for(let o of Object.keys(e))if(!t.includes(o))throw new we(`unknown field '${o}'`,n)}function AS(e,t){if(!rr(e))throw new we("missing source",t);on(e,["chunk","line_start","line_end"],t);let{chunk:n,line_start:o,line_end:i}=e;if(![n,o,i].every(r=>typeof r=="number"&&Number.isInteger(r)&&r>=0))throw new we("source needs integer chunk/line_start/line_end",t);if(o>=i)throw new we("source line_start must be < line_end",t);return{chunk:n,line_start:o,line_end:i}}function ir(e,t,n){let o=e[t];if(typeof o!="string"||o==="")throw new we(`'${t}' must be a non-empty string`,n);return o}function Uo(e,t,n){if(!(t in e)||e[t]===void 0)return;let o=e[t];if(typeof o!="string"||o==="")throw new we(`'${t}' must be a non-empty string`,n);return o}function hg(e,t,n){if(!Array.isArray(e))throw new we(`'${t}' must be an array`,n);return e.map(o=>{if(!rr(o))throw new we(`'${t}' entries must be objects`,n);on(o,["name","state"],n);let i={name:ir(o,"name",n)},r=Uo(o,"state",n);return r!==void 0&&(i.state=r),i})}function kS(e,t){if(!rr(e))throw new we("dialogue/inner_thought needs a speaker",t);if("kind"in e){on(e,["kind","label"],t);let r=e.kind;if(typeof r!="string"||!Vn.includes(r))throw new we(`speaker.kind must be one of ${Vn.join("|")}`,t);let s={kind:r},c=Uo(e,"label",t);return c!==void 0&&(s.label=c),s}on(e,["name","state"],t);let n=ir(e,"name",t);if(!/[\p{L}\p{N}]/u.test(n))throw new we("speaker.name must contain a letter or number",t);let o={name:n},i=Uo(e,"state",t);return i!==void 0&&(o.state=i),o}function bS(e,t){let n=e.kind;if(typeof n!="string"||!gg.includes(n))throw new we(`unknown or missing kind '${String(n)}'`,t);let o=AS(e.source,t);switch(n){case"episode":{on(e,["kind","episode","title","source"],t);let i=e.episode;if(typeof i!="number"||!Number.isInteger(i))throw new we("episode must be an integer",t);let r={kind:n,episode:i,source:o},s=Uo(e,"title",t);return s!==void 0&&(r.title=s),r}case"scene":{on(e,["kind","scene","environment","location","actors","props","source"],t);let i={kind:n,source:o};if("scene"in e&&e.scene!==void 0){if(typeof e.scene!="number"||!Number.isInteger(e.scene))throw new we("scene must be an integer",t);i.scene=e.scene}if("environment"in e&&e.environment!==void 0){if(!rr(e.environment))throw new we("environment must be an object",t);on(e.environment,["space","time"],t);let r={},s=Uo(e.environment,"space",t);s!==void 0&&(r.space=s);let c=Uo(e.environment,"time",t);if(c!==void 0){let a=Lo(c);if(!a)throw new we("environment.time must be day|night|dawn|dusk or a recognized Chinese equivalent",t);r.time=a}i.environment=r}if("location"in e&&e.location!==void 0){if(!rr(e.location))throw new we("location must be an object",t);on(e.location,["name","state"],t);let r={name:ir(e.location,"name",t)},s=Uo(e.location,"state",t);s!==void 0&&(r.state=s),i.location=r}return"actors"in e&&e.actors!==void 0&&(i.actors=hg(e.actors,"actors",t)),"props"in e&&e.props!==void 0&&(i.props=hg(e.props,"props",t)),i}case"action":case"transition":{on(e,["kind","content","source"],t);let i=ir(e,"content",t);return{kind:n,content:i,source:o}}case"dialogue":case"inner_thought":{on(e,["kind","speaker","content","emotion","source"],t);let i=ir(e,"content",t),r=kS(e.speaker,t),s={kind:n,speaker:r,content:i,source:o},c=Uo(e,"emotion",t);return c!==void 0&&(s.emotion=c),s}case"note":{on(e,["kind","content","category","source"],t);let i=ir(e,"content",t),r={kind:n,content:i,source:o};if("category"in e&&e.category!==void 0){let s=e.category;if(s!=="author_note"&&s!=="format_note"&&s!=="unclassified")throw new we("note.category must be author_note|format_note|unclassified",t);r.category=s}return r}default:throw new we(`unhandled kind '${n}'`,t)}}function os(e,t=0){let n=[],o=e.split(`
239
+ `);for(let i=0;i<o.length;i++){let r=o[i].trim();if(r==="")continue;let s;try{s=JSON.parse(r)}catch{throw new we("invalid JSON",i+1+t)}if(!rr(s))throw new we("record must be a JSON object",i+1+t);n.push(bS(s,i+1+t))}return n}var te=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),mi=e=>{let t=/[((]/.exec(e);return!t||t.index===0?e:e.slice(0,t.index).trim()},OS=e=>e.startEp===e.endEp?`\u7B2C${e.startEp}\u96C6`:`\u7B2C${e.startEp}\u96C6\u2013\u7B2C${e.endEp}\u96C6`,Lp=e=>e.startEp===e.endEp?`\u7B2C${e.startEp}\u96C6`:`\u7B2C${e.startEp}\u96C6\u2013\u7B2C${e.endEp}\u96C6`,Eg=()=>({newEntities:[],merges:[],looks:[],lookChanges:[],subEvents:[],summary:""}),xg=()=>({entities:[],lookChanges:{},recent:[],synopsis:[]}),Up={recentEpisodes:6,synopsisChars:3500,arcFold:10},vS=1e4;function Sg(e){let t=0,n=0;for(let o of e){n++;let i=o.codePointAt(0);(i>=13312&&i<=40959||i>=12288&&i<=12543||i>=65280&&i<=65519||i>=63744&&i<=64255)&&t++}return Math.round(t*.7+(n-t)*.25)}function Ig(e,t=vS){let n=[],o=0,i=0;for(let r=0;r<e.length;r++)r>o&&i+e[r]>t&&(n.push([o+1,r]),o=r,i=0),i+=e[r];return o<e.length&&n.push([o+1,e.length]),n}var RS={actor:"\u4EBA\u7269",location:"\u573A\u666F",prop:"\u9053\u5177"};function zt(e,t){let n=te(t);return e.entities.find(o=>te(o.canonical)===n||o.aliases.some(i=>te(i)===n))}var yg=(e,t)=>{te(t)!==te(e.canonical)&&!e.aliases.some(n=>te(n)===te(t))&&e.aliases.push(t)},MS=["\u5E74\u8F7B","\u5E74\u8001","\u5E74\u5E7C","\u5E74\u5C11","\u4E2D\u5E74","\u9752\u5E74","\u5C11\u5E74","\u8001\u5E74","\u5E7C\u5E74","\u8001","\u5C0F","\u5927","\u5C11","\u5E7C"];function NS(e,t){let n=te(e),o=te(t);if(n===o||!n.includes(o))return!1;let i=n.replace(o,"").trim();return i.length>0&&!MS.some(r=>i===r||i.startsWith(r))}function LS(e){let t=e.filter(n=>e.some(o=>o!==n&&NS(n,o)));return t.length?t.reduce((n,o)=>o.length>n.length?o:n):e[0]}var wg=["\u4F17\u4EBA","\u7FA4\u4F17","\u6C11\u4F17","\u89C2\u4F17","\u4EBA\u7FA4","\u4EBA\u4EEC","\u5927\u5BB6","\u8DEF\u4EBA","\u884C\u4EBA","\u770B\u5BA2","\u56F4\u89C2\u8005","\u6751\u6C11","\u58EB\u5175","\u767E\u59D3","\u5B66\u751F","\u540C\u5B66","\u4E2B\u9B1F","\u968F\u4ECE","\u4F8D\u536B","\u5BB6\u4E01","\u4EC6\u4EBA","\u4E0B\u4EBA","\u5B69\u5B50","\u8F7F\u592B","\u62A4\u536B","\u624B\u4E0B","\u5C0F\u5F1F","\u55BD\u5570","\u5B98\u5175","\u8859\u5F79","\u592A\u76D1","\u5BAB\u5973","\u5A62\u5973","\u5546\u8D29","\u98DF\u5BA2"],US=["\u4F17\u4EBA","\u7FA4\u4F17","\u6C11\u4F17","\u89C2\u4F17","\u4EBA\u7FA4","\u4EBA\u4EEC","\u5927\u5BB6","\u767E\u59D3","\u5B98\u5175"],PS=/^(?:一群|一众|全体|所有|几名|数名|多名|[0-9零一二两三四五六七八九十百千]+名?)/;function ct(e){let t=te(e).replace(/[0-9零一二两三四五六七八九十百千]+名?$/,"").trim();return t?t.endsWith("\u4EEC")||wg.includes(t)||US.some(n=>t.endsWith(n))?!0:PS.test(t)&&wg.some(n=>t.endsWith(n)):!1}function Po(e,t){let n=mi(t);return zt(e,n)?.canonical??n}function CS(e,t){let n=te(t);return e.looks.find(o=>te(o.name)===n||o.aliases.some(i=>te(i)===n))?.name??t}var TS=["\u5E38\u6001","\u65E5\u5E38","\u5E73\u65F6","\u57FA\u7840","\u666E\u901A"];function Pp(e){if(e.looks.length!==0)return(e.looks.find(t=>TS.some(n=>t.name.includes(n)))??e.looks[0]).name}function Np(e,t,n,o){let i=te(mi(n));if(i)return e.entities.find(r=>r.kind===t&&r!==o&&(te(r.canonical)===i||r.aliases.some(s=>te(s)===i)))}function _g(e){let t=[e.canonical,...e.aliases],n=LS(t);te(n)!==te(e.canonical)&&(e.canonical=n,e.aliases=t.filter(o=>te(o)!==te(n)))}function is(e,t,n,o=n){for(let r of t.newEntities){let s=mi(r.name);if(!s)continue;let c=Np(e,r.kind,s);if(!c){let d=[];for(let p of r.aliases){let l=mi(p);l&&te(l)!==te(s)&&!Np(e,r.kind,l)&&d.push(l)}e.entities.push({kind:r.kind,canonical:s,aliases:[...new Set(d)],description:r.description,looks:[{name:r.defaultLook.name,aliases:[],description:r.defaultLook.description}],lastSeen:o});continue}for(let d of r.aliases){let p=mi(d);p&&!Np(e,r.kind,p,c)&&yg(c,p)}!c.description&&r.description&&(c.description=r.description);let a=c.looks.find(d=>te(d.name)===te(r.defaultLook.name));a?a.description=r.defaultLook.description:c.looks.unshift({name:r.defaultLook.name,aliases:[],description:r.defaultLook.description}),_g(c)}for(let{from:r,into:s}of t.merges){let c=mi(s);if(!c)continue;let a=zt(e,c);if(!a)continue;let d=mi(r);!d||te(d)===te(a.canonical)||zt(e,d)||(yg(a,d),_g(a))}for(let{entity:r,names:s,description:c}of t.looks){let a=zt(e,r);if(!a)continue;let d=s.map(f=>f.trim()).filter(Boolean);if(!d.length)continue;let p=d[0],l=a.looks.find(f=>te(f.name)===te(p)||d.some(u=>f.aliases.some(m=>te(m)===te(u))));if(l){c&&(l.description=c);for(let f of d)te(f)!==te(l.name)&&!l.aliases.some(u=>te(u)===te(f))&&l.aliases.push(f)}else a.looks.push({name:p,aliases:d.slice(1),description:c})}for(let r of t.lookChanges){let s=r.scene.trim(),c=Po(e,r.entity),a=r.look.trim();if(!s||!c||!a)continue;let d=zt(e,c),p=d?CS(d,a):a;(e.lookChanges[s]??=[]).push({entity:c,look:p}),d&&(d.currentLook=p)}let i=new Set;for(let r of t.newEntities){i.add(r.name);for(let s of r.aliases)i.add(s)}for(let r of t.merges)i.add(r.from),i.add(r.into);for(let r of t.looks)i.add(r.entity);for(let r of t.lookChanges)i.add(r.entity);for(let r of i){let s=zt(e,r);s&&(s.lastSeen=o)}return e.recent.push({startEp:n,endEp:o,summary:t.summary,subEvents:t.subEvents}),e}var VS=e=>e.summary.length+e.subEvents.reduce((t,n)=>t+n.length,0);function Ag(e,t=Up){for(;e.recent.length>t.recentEpisodes||e.recent.length>1&&e.recent.reduce((n,o)=>n+VS(o),0)>6e3;){let n=e.recent.shift();n.summary.trim()&&e.synopsis.push({startEp:n.startEp,endEp:n.endEp,line:n.summary.trim()})}return e}function Cp(e,t=Up){return e.synopsis.reduce((o,i)=>o+i.line.length,0)<=t.synopsisChars||e.synopsis.length<=t.arcFold?null:e.synopsis.slice(0,t.arcFold)}function kg(e,t,n=Up){let o=e.synopsis.splice(0,n.arcFold);o.length&&e.synopsis.unshift({startEp:o[0].startEp,endEp:o[o.length-1].endEp,line:t.trim()})}var $S=6;function va(e,t){let n=i=>t===void 0||i.lastSeen>=t-$S,o=["# \u8BBE\u5B9A"];for(let i of["actor","location","prop"]){let r=e.entities.filter(s=>s.kind===i);if(r.length){o.push(`## ${RS[i]}`);for(let s of r){let c=[...s.aliases.length?[`\u522B\u540D ${s.aliases.join("\u3001")}`]:[],...s.currentLook?[`\u5F53\u524D\u9020\u578B ${s.currentLook}`]:[]];if(o.push(`- ${s.canonical}\uFF5C${c.join("\uFF5C")}`),!!n(s)){s.description&&o.push(` \u7B80\u4ECB\uFF1A${s.description}`);for(let a of s.looks){let d=a.aliases.length?`${a.name}(=${a.aliases.join("=")})`:a.name;o.push(` \u9020\u578B ${d}${a.description?`\uFF1A${a.description}`:""}`)}}}}}if(e.synopsis.length){o.push("","# \u524D\u60C5");for(let i of e.synopsis)o.push(`- ${Lp(i)}\uFF1A${i.line}`)}if(e.recent.length){o.push("","# \u6700\u8FD1");for(let i of e.recent){o.push(`## ${OS(i)}`),i.summary.trim()&&o.push(`\u6897\u6982\uFF1A${i.summary.trim()}`);for(let r of i.subEvents)o.push(`- ${r}`)}}return o.join(`
240
+ `)}var DS=/(?:^|[,。!?;:、\s“”"'((])(他们|她们|它们|其中一人|另一个人|前者|后者|对方|有人|两人|他|她|它)(?!人)/;function sr(e){let t=[],n=(o,i,r)=>{t.push({code:o,path:i,message:r})};return e.actors.forEach((o,i)=>{ct(o.actor_name)&&n("production_crowd_actor",`$.actors[${i}].actor_name`,`${o.actor_name} is a group speaker, not an actor asset`)}),e.episodes.forEach((o,i)=>{o.scenes.forEach((r,s)=>{let c=`$.episodes[${i}].scenes[${s}]`;r.location===null&&n("production_location_missing",`${c}.location`,"production scene needs one stable location"),r.actions.forEach((a,d)=>{let p=`${c}.actions[${d}]`;if(a.type==="action"){let l=DS.exec(a.content);l&&n("production_action_pronoun",`${p}.content`,`action uses ambiguous reference ${l[1]}`)}})})}),t}var qe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ut=e=>Array.isArray(e),Ra=e=>String(e).padStart(3,"0"),Tp=[{key:"actors",idField:"actor_id",prefix:"act"},{key:"locations",idField:"location_id",prefix:"loc"},{key:"props",idField:"prop_id",prefix:"prp"}];function Ma(e){if(!qe(e))throw new Error("renumberIds expects a script object");let t=JSON.parse(JSON.stringify(e)),n={episodes:{},scenes:{},actors:{},locations:{},props:{},states:{}},o={actors:[],locations:[],props:[]},i={actors:new Set,locations:new Set,props:new Set},r=(a,d)=>{typeof d=="string"&&!i[a].has(d)&&(i[a].add(d),o[a].push(d))};for(let a of ut(t.episodes)?t.episodes:[])if(!(!qe(a)||!ut(a.scenes))){for(let d of a.scenes)if(qe(d)){qe(d.location)&&r("locations",d.location.location_id);for(let p of ut(d.actors)?d.actors:[])qe(p)&&r("actors",p.actor_id);for(let p of ut(d.props)?d.props:[])qe(p)&&r("props",p.prop_id);for(let p of ut(d.actions)?d.actions:[])qe(p)&&qe(p.speaker)&&r("actors",p.speaker.actor_id)}}for(let{key:a,idField:d}of Tp)for(let p of ut(t[a])?t[a]:[])qe(p)&&r(a,p[d]);for(let{key:a,prefix:d}of Tp)o[a].forEach((p,l)=>{n[a][p]=`${d}_${Ra(l+1)}`});for(let{key:a,idField:d}of Tp){let p=(ut(t[a])?t[a]:[]).filter(qe),l=n[a],f=new Map;for(let u of p){let m=u[d],h=l[m]??m;u[d]=h;let g=0;for(let w of ut(u.states)?u.states:[]){if(!qe(w)||typeof w.state_id!="string"||w.state_id==="default")continue;let y=`st_${Ra(++g)}`;n.states[w.state_id]=y,w.state_id=y}f.set(h,u)}t[a]=[...f.entries()].sort((u,m)=>u[0]<m[0]?-1:1).map(u=>u[1])}let s=0;(ut(t.episodes)?t.episodes:[]).forEach((a,d)=>{if(qe(a)){if(typeof a.episode_id=="string"){let p=`ep_${Ra(d+1)}`;n.episodes[a.episode_id]=p,a.episode_id=p}for(let p of ut(a.scenes)?a.scenes:[])if(qe(p)&&typeof p.scene_id=="string"){let l=`scn_${Ra(++s)}`;n.scenes[p.scene_id]=l,p.scene_id=l}}});let c=(a,d,p)=>{!qe(a)||typeof a[d]!="string"||(a[d]=n[p][a[d]]??a[d],typeof a.state_id=="string"&&n.states[a.state_id]&&(a.state_id=n.states[a.state_id]))};for(let a of ut(t.episodes)?t.episodes:[])if(!(!qe(a)||!ut(a.scenes))){for(let d of a.scenes)if(qe(d)){c(d.location,"location_id","locations");for(let p of ut(d.actors)?d.actors:[])c(p,"actor_id","actors");for(let p of ut(d.props)?d.props:[])c(p,"prop_id","props");for(let p of ut(d.actions)?d.actions:[])qe(p)&&c(p.speaker,"actor_id","actors")}}return{script:t,idMap:n}}import{createHash as GS}from"node:crypto";function rs(e){let t=O(e).trim();if(!t.includes(":"))throw new x("Target invalid.",{exitCode:B,errorCode:"TARGET_INVALID",hint:"Use a concrete asset target.",data:{expected:["target: actor:<id>, location:<id>, or prop:<id>"],actual:[t||"<empty>"]}});let n=t.indexOf(":"),o=t.slice(0,n).trim(),i=t.slice(n+1).trim();if(!iu.has(o)||!i)throw new x("Target invalid.",{exitCode:B,errorCode:"TARGET_INVALID",hint:"Use actor, location, or prop with a non-empty id.",data:{expected:["target: actor:<id>, location:<id>, or prop:<id>"],actual:[t]}});return[o,i]}function Co(){return{version:3,actor:{},location:{},prop:{},state:{},episode:{},scene:{},action:{}}}function Ht(e,t){let n=e.get(t);if(n===void 0)throw new Error(`Missing mapped ID for ${t}`);return n}function ar(e,t=Co(),n={}){if(t.version!==3)throw new Error(`Unsupported v4 identity map version: ${String(t.version)}`);let o=structuredClone(t),i={actor:new Map,location:new Map,prop:new Map},r={actor:new Set,location:new Set,prop:new Set,episode:new Set,scene:new Set,action:new Set},s=(I,v,L,C)=>{let R=L[v];if(R!==void 0){if(!V(I,R))throw new Error(`Invalid persisted ${I} ID for ${v}: ${R}`);if(C.has(R))throw new Error(`Duplicate persisted ${I} ID: ${R}`);return C.add(R),R}let J=Fo(I,C);return C.add(J),L[v]=J,J},c=(I,v)=>n[I]?.[v]??v;for(let I of e.actors){let v=s("actor",c("actor",I.actor_id),o.actor,r.actor);i.actor.set(I.actor_id,v)}for(let I of e.locations){let v=s("location",c("location",I.location_id),o.location,r.location);i.location.set(I.location_id,v)}for(let I of e.props){let v=s("prop",c("prop",I.prop_id),o.prop,r.prop);i.prop.set(I.prop_id,v)}let a=new Map,d=(I,v,L)=>{let C=new Map,R=new Set,J=c(I,v),W=o.state[J]??{};o.state[J]=W;let Re=L.map(ie=>{let K;if(ie.state_id==="default")K="default";else{let Ot=n.state?.[v]?.[ie.state_id]??ie.state_id,P=W[Ot];if(P!==void 0){if(!V("state",P))throw new Error(`Invalid persisted state ID for ${v}/${ie.state_id}: ${P}`);if(R.has(P))throw new Error(`Duplicate persisted state ID on ${v}: ${P}`);K=P}else K=Fo("state",R),W[Ot]=K}return R.add(K),C.set(ie.state_id,K),{...ie,state_id:K}});return a.set(v,C),Re},p=(I,v)=>v===void 0?void 0:Ht(a.get(I)??new Map,v),l=e.actors.map(I=>({...I,actor_id:Ht(i.actor,I.actor_id),states:d("actor",I.actor_id,I.states)})),f=e.locations.map(I=>({...I,location_id:Ht(i.location,I.location_id),states:d("location",I.location_id,I.states)})),u=e.props.map(I=>({...I,prop_id:Ht(i.prop,I.prop_id),states:d("prop",I.prop_id,I.states)})),m=I=>{if("actor_id"in I){let v=p(I.actor_id,I.state_id);return{actor_id:Ht(i.actor,I.actor_id),...v===void 0?{}:{state_id:v}}}return I.label===void 0?{kind:I.kind}:{kind:I.kind,label:I.label}},h=I=>{if(I.includes(":")){let[L,C]=rs(I);return Ht(L==="actor"?i.actor:L==="location"?i.location:i.prop,C)}let v=i.actor.get(I)??i.location.get(I)??i.prop.get(I);if(v===void 0)throw new Error(`Missing transition target mapping for ${I}`);return v},g=(I,v)=>{let L=s("action",v,o.action,r.action),C=I.transition_prompt===void 0?{}:{transition_prompt:{...I.transition_prompt,target:h(I.transition_prompt.target)}};if(I.type==="dialogue"||I.type==="inner_thought"){if(I.speaker===void 0)throw new Error(`Speaking action ${I.content.slice(0,40)} has no speaker`);return{action_id:L,type:I.type,content:I.content,speaker:m(I.speaker),...I.emotion===void 0?{}:{parenthetical:I.emotion},...C,...I.extend===void 0?{}:{extend:I.extend}}}return{action_id:L,type:I.type,content:I.content,...C,...I.extend===void 0?{}:{extend:I.extend}}},w=(I,v)=>[p(I,v??"default")??"default"],y=(I,v)=>{let L=new Map;for(let C of I){let R=Ht(i.actor,C.actor_id),J=L.get(R)??new Set;w(C.actor_id,C.state_id).forEach(W=>J.add(W)),L.set(R,J)}for(let C of v){if(C.speaker===void 0||!("actor_id"in C.speaker))continue;let R=C.speaker.actor_id,J=Ht(i.actor,R),W=L.get(J)??new Set;w(R,C.speaker.state_id).forEach(Re=>W.add(Re)),L.set(J,W)}return[...L].map(([C,R])=>({actor_id:C,state_ids:[...R].sort()}))},_=I=>{let v=new Map;for(let L of I){let C=Ht(i.prop,L.prop_id),R=v.get(C)??new Set;w(L.prop_id,L.state_id).forEach(J=>R.add(J)),v.set(C,R)}return[...v].map(([L,C])=>({prop_id:L,state_ids:[...C].sort()}))},S=new Set,E=new Set,A=new Set,b={version:4,title:e.title,worldview:e.worldview,style:e.style,...e.worldview_raw===void 0?{}:{worldview_raw:e.worldview_raw},...e.synopsis===void 0?{}:{synopsis:e.synopsis},...e.logline===void 0?{}:{logline:e.logline},...e.theme===void 0?{}:{theme:e.theme},...e.main_characters===void 0?{}:{main_characters:e.main_characters},...e.extend===void 0?{}:{extend:e.extend},actors:l,locations:f,props:u,episodes:e.episodes.map(I=>{let v=n.episode?.[I.episode_id]??I.episode_id;S.add(v);let L=s("episode",v,o.episode,r.episode);return{...I,episode_id:L,scenes:I.scenes.map(C=>{let R=`${I.episode_id}/${C.scene_id}`,J=n.scene?.[R]??R;E.add(J);let W=s("scene",J,o.scene,r.scene),Re=new Map;return{...C,scene_id:W,location:C.location===null?null:{location_id:Ht(i.location,C.location.location_id),state_ids:w(C.location.location_id,C.location.state_id)},actors:y(C.actors,C.actions),props:_(C.props),actions:C.actions.map((ie,K)=>{let Ot=`${R}#${K}`,P=JSON.stringify(In(ie)),ce=(Re.get(P)??0)+1;Re.set(P,ce);let Se=GS("sha256").update(P).digest("hex"),vt=n.action?.[Ot]??`${J}:action:${Se}:${ce}`;return A.add(vt),g(ie,vt)})}})}})},U=(I,v)=>{for(let L of Object.keys(I))v.has(L)||delete I[L]};U(o.actor,new Set(e.actors.map(I=>c("actor",I.actor_id)))),U(o.location,new Set(e.locations.map(I=>c("location",I.location_id)))),U(o.prop,new Set(e.props.map(I=>c("prop",I.prop_id)))),U(o.episode,S),U(o.scene,E),U(o.action,A);let M=[...e.actors.map(I=>({id:c("actor",I.actor_id),oldId:I.actor_id,states:I.states})),...e.locations.map(I=>({id:c("location",I.location_id),oldId:I.location_id,states:I.states})),...e.props.map(I=>({id:c("prop",I.prop_id),oldId:I.prop_id,states:I.states}))];U(o.state,new Set(M.map(I=>I.id)));for(let I of M)U(o.state[I.id]??{},new Set(I.states.map(v=>n.state?.[I.oldId]?.[v.state_id]??v.state_id)));return{script:b,identityMap:o}}import*as Le from"node:fs";import*as gi from"node:path";function hi(e,t){let n=gi.dirname(e);Le.mkdirSync(n,{recursive:!0});let o=gi.join(n,`.${gi.basename(e)}.${process.pid}.tmp`),i=Le.openSync(o,"w");try{Le.writeFileSync(i,t),Le.fsyncSync(i)}finally{Le.closeSync(i)}Le.renameSync(o,e)}function BS(e,t){hi(e,JSON.stringify(t,null,2)+`
241
+ `)}function JS(e){return JSON.parse(Le.readFileSync(e,"utf-8"))}var ft=class{constructor(t){this.root=t}root;abs(t){return gi.join(this.root,t)}ensure(){Le.mkdirSync(this.root,{recursive:!0})}passDir(t){let n=this.abs(t);return Le.mkdirSync(n,{recursive:!0}),n}readText(t){return Le.readFileSync(this.abs(t),"utf-8")}writeText(t,n){hi(this.abs(t),n)}writeJson(t,n){BS(this.abs(t),n)}readJson(t){return JS(this.abs(t))}has(t){return Le.existsSync(this.abs(t))}path(t){return this.abs(t)}clearError(t){let n=this.abs(t);Le.existsSync(n)&&Le.rmSync(n)}};function rn(e,t){e=e-0;let n=Vp(),o=n[e];if(rn.wCYmoh===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};rn.ccSjUe=i,rn.dKlJjl={},rn.wCYmoh=!0}let r=n[0];rn.sBhMJx!==r&&(rn.dKlJjl={},rn.sBhMJx=r);let s=rn.dKlJjl[e];return s===void 0?(o=rn.ccSjUe(o),rn.dKlJjl[e]=o):o=s,o}var Y=rn,KS=[Y(40),Y(37),Y(24),Y(75),Y(5),Y(21),"",Y(65),Y(13),Y(34),Y(62),"",Y(70),Y(35),Y(42),Y(27),Y(39),Y(43),Y(0),Y(68),Y(55),"",Y(77),Y(18),Y(58),Y(10),Y(11),Y(51),Y(59),Y(66),Y(8),Y(3),Y(76),"",Y(15),Y(4),Y(9),Y(6),Y(20),Y(14),Y(45),Y(48),Y(38),Y(54)][Y(74)](`
242
+ `);function jS(e){let t=Y,n=e[t(73)]===0?t(47):t(23);return[t(78),n,t(49),"",e[t(53)]][t(74)](`
243
+ `)}function Na(e,t){let n=Y;return new x(e,{exitCode:X,errorCode:n(12),hint:n(44),data:{actual:t}})}function zS(e){let t=Y;return typeof e!==t(29)||e===null||Array[t(46)](e)?!1:Object[t(61)](e)[t(1)]===1&&t(33)in e&&Array[t(46)](e[t(33)])}function $p(e,t){let n=Y;if(!zS(e))throw Na(n(19)+t[n(73)]+n(63),[n(31)]);let o={chunk:t[n(73)],line_start:t[n(64)],line_end:t[n(36)]},i;try{let r=e[n(33)][n(25)](s=>{let c=n;if(typeof s!==c(29)||s===null||Array[c(46)](s)||Object[c(26)](s,c(56))){if(c(72)!==c(30))throw new we(c(57),1);if(typeof _0x5a19bf!==c(29)||_0x5b66f6===null||_0x10f05d[c(46)](_0x23b052)||_0x733702[c(26)](_0x1cb121,c(56)))throw new _0x3dba95(c(57),1);return _0x5020a9[c(32)]({..._0x80cb75,source:_0x442727})}return JSON[c(32)]({...s,source:o})})[n(74)](`
244
+ `);i=os(r)}catch(r){throw r instanceof we?Na(n(19)+t[n(73)]+": "+r[n(17)],[r[n(17)]]):r}if(i[n(1)]===0&&t[n(53)][n(52)]()!=="")throw n(60)===n(22)?_0x1b2e63(n(19)+_0x2d4dff[n(73)]+n(63),[n(31)]):Na(n(19)+t[n(73)]+n(69),[n(2)]);return i}function Vp(){let e=["lsdOVAZLNlRVVjP7iMTPBMqIoIj0CMfUC2L0Aw9UiIWIy29UDgvUDci6iUw/OowUNUI9RoAnOUAiKoEUGos9K+s4REAwH+EAHoI9RowCUUAwH+wTLYj944cc5BI46kEb5Qc85BYp6k+n5lMF6kAb57+76k+r77Ym5l6l5AAcigbgteftsejbq0TGiokgKIbG6zEQ5zUEyooaGwbcqunlifrpifbsrvnftLrGiokgKIbG5zUE5yIW546W5A6EyooaGG","BgvUz3rO","CMvJB3jKCZOGma","icdOKAhOR63LIQJKVzWGyfvTihbYyxrVigrLig9MzxjLBMrHCYbJywKGzgeGBwvZysbLihnLigvZCgfSAgeGCgvSBYbJAmoJBY5GiokgKIbHy3rPB24Uy29UDgvUDd1G5lIa55Uy5l6B5zob5lUo5Qgm5lIk5O6j6jc977Ym5PwJ6jc95lIa5zYW44ccyooaGUs6UUEjQEIVTowhUUEAHoIrOEIVREwVUEEzVEs7JEMaKowTL+s/NEEvME+8Jos4JEE/U+IVKE+8M1jPy2HHCMtJGiffBwLSEsdNRyNKURRNIANLKi3LP4VNU4JKV53MJihLJP/MLOFMI7ZLHPNJGii","5Q2J5PAh5y+J5B6e77YAzgLHBg9NDwxJGifPBM5LCL90Ag91z2H0ioEAHcbJB250zw50ioMaKowTL+w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uQowCSoEcUEApJ+I/SoMdVEs9V+EuQoIhQUEeTUoaGEwhHUEHRUEAHoEUGos9K+s4REAwH+oaGUs6UUEjQEwNK+wqJEwCQcbZCgvHA2vYlM5HBwxJGifZy2vUzs5Hy3rVCNpJGifHy3rPB24G5zkm5zco57UT6lwe5lQN55M76k6W5lIT6yo95B+f6Ag75Rk/55sO5RQq5PAh5PYS55Qe5y6F5AEl5OU85yAz77Ym5lIn57+76k+r44cb5lIn6z+Z6k+r44cb5lIn5Ps55OIq5lIT5PAh5zcn77YB5zob54Mm5zkm5RkH5PYj6ycA6kgm6k+r5zcn55Qe5yw25lUw5lIt5zcn5l+D55wz5y6F5PAh44cc5lIn5B6x5OQk5Pw05y+L5Asw6k+T5yQO5l2C5OIw546V5Akd5O+p6l+W5y6F5Qc355wz5zYOigfJDgLVBIdKUk3JGii","icdLKiZKUidLJ6xNLlhLPjRKURRLKiZML7BOR7tML7BVViZKUlRMR4/KUkROR7tOR53KURRLKitLHPNKUidMNAhNM7JPGRSGzgLHBg9NDwxVViXJB250zw50ioEBUowqJooaGG","6l2S5O2I6kEe5yIz77YA","44cq5B6f6kEe6iYd5yYw55Qe5y6F5PAh54Mh5Q6144cr"];return Vp=function(){return e},Vp()}async function bg(e,t,n){let o=Y,i=await e[o(41)](o(71),{system:KS,user:jS(t),responseFormat:o(16),...n?{signal:n}:{}}),r;try{r=JSON[o(28)](i[o(53)])}catch{if(o(67)!==o(67))_0x10022d=_0x3c4a29[o(28)](_0x5ecbb9[o(53)]);else throw Na(o(19)+t[o(73)]+o(50),[i[o(53)][o(7)](0,500)])}return{raw:i[o(53)],records:$p(r,t)}}var Gp=sn,HS=Gp(1);function FS(e){let t=Gp,n=e[t(5)](/起点\s*[::]\s*(\d+)/);return n?{found:!0,line:Math[t(3)](Number(n[1]))}:{found:!1,line:null}}function Dp(){let e=["Dgv4Da","5l2G5PIV55+T5yMN5yMN5PYS55Qe44cm5Q2J5PAh6lw354k55A6A5l2n5zMO44cn44cc5l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rIIOQ5PYS56Qx5y+J5yAfkIROG73NOA7ORQtNMOtOOyZLJ7FVVjVLPOlMNPZOV5NMRRxOV5JLHAJMMk/LIy3OQidJGihMIjBMRApMLOFOV5JMSQhLH7RNJRdVViZLSlhMIQxLKyRJGi7ML6dJGi/VViZMIjhKVjRMIORKUiVKUidMRRxNU5NKVAdJGiiklsdLROhLJ6/NQi3LVQ7PNAdLIy3KUz/KUi3OPOhOT7pOV4FNRkWGmsdPM4BVVjRMI7/KUi3LH4BOR6xLJ5BPM4BLPltOV5JMMk/LNlRMRkhOOyZML7BVViZLJ5BMM7tPNAdLIy3NMOtPGQpKUidOOyZJGiiklsdOOyZLJ7FLV4xPOBVLJP/MOlFNHAFMIOtMIjhNU5NKVAdNMOtOOyZPPPBMLBdLRzFJGiikcUoaKoI+K+whUUAGVow8J+oaKEwpQUI+K+whUUs4GoIHJo+8Jos4JEIMGEs7U+s9LEINO+MhIU+8MGOTioAjVUwiSoATO+AwH+I1T+EcUE+8MMdOTBFNGRK6idZOOyZLJ7C+yo+8Ios+I+wMGIbG6lw354k5oIaXndbG77YjcI0G5PYS56Qx5y+J5ywO5PIV5yMn6kIaic8G6l+y5RkH5yIW5Q2J5PAh77YAyoI1T+EcUtOG5PEGya","Aw5Nzxn0lMjVzhKTC3rHCNq","Dhj1BMm","z2vUzxjHDgvuzxH0","Bwf0y2G","5lIl6z2I5PIV5RQq5PAh5lU255Qe5lIa5Q6177Ym5Q+p6kgm5lUL44cm6kgm5y+3pfrbqJ7LHOxLRRNJGi3NU5NLH7RJGilLIktMLQ3NNj/MRApNMOtLIAFMNkZMRApMLOFMMk/LKkBLNkJOV5NMRRxPH4ZLVidLP4VVViZMJiNMOlZLVi/LJ6RLM57KUidOOyZJGiikcG"];return Dp=function(){return e},Dp()}async function Og(e,t,n){let o=Gp,i=await e[o(4)](o(2),{system:HS,user:o(6)+t,...n?{signal:n}:{}});return FS(i[o(0)])}function sn(e,t){e=e-0;let n=Dp(),o=n[e];if(sn.sLepLJ===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};sn.TPTWLA=i,sn.iYuNay={},sn.sLepLJ=!0}let r=n[0];sn.inDmHY!==r&&(sn.iYuNay={},sn.inDmHY=r);let s=sn.iYuNay[e];return s===void 0?(o=sn.TPTWLA(o),sn.iYuNay[e]=o):o=s,o}var vg=50,QS=10;async function Rg(e,t,n){let o=t.split(`
245
+ `),i=vg-QS;try{for(let r=0;r<o.length;r+=i){let s=Math.min(r+vg,o.length),c=o.slice(r,s).map((d,p)=>`${r+p+1} ${d}`).join(`
246
+ `),a=await Og(e,c,n);if(a.found&&a.line!==null)return{line:Math.min(Math.max(a.line-1,0),o.length-1),scannedLines:s,found:!0};if(s>=o.length)break}}catch(r){return{line:0,scannedLines:0,found:!1,error:r instanceof Error?r.message:String(r)}}return{line:0,scannedLines:o.length,found:!1}}async function Mg(e,t,n){let o=new Array(e.length),i=0,r=Array.from({length:Math.max(1,Math.min(t,e.length))},async()=>{for(;;){let s=i++;if(s>=e.length)return;try{o[s]={index:s,ok:!0,value:await n(e[s],s)}}catch(c){o[s]={index:s,ok:!1,error:c}}}});return await Promise.all(r),o}var Ft=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),an=e=>Array.isArray(e);function Bp(e){let t=new Map;if(!an(e))return t;for(let n of e){if(!Ft(n))continue;let o=n.actor_id??n.location_id??n.prop_id;typeof o=="string"&&t.set(o,n)}return t}function YS(e){let t=[],n=(o,i)=>{!Ft(o)||typeof o[i]!="string"||t.push({assetId:o[i],holder:o,explicit:typeof o.state_id=="string"?o.state_id:void 0})};for(let o of an(e.episodes)?e.episodes:[])if(!(!Ft(o)||!an(o.scenes))){for(let i of o.scenes)if(Ft(i)){n(i.location,"location_id");for(let r of an(i.actors)?i.actors:[])n(r,"actor_id");for(let r of an(i.props)?i.props:[])n(r,"prop_id");for(let r of an(i.actions)?i.actions:[])Ft(r)&&n(r.speaker,"actor_id")}}return t}function qS(e,t){let n=e.filter(i=>(t.get(i.state_id)??0)>0);if(n.length===0)return null;let o=n[0];for(let i of n.slice(1)){let r=t.get(i.state_id)??0,s=t.get(o.state_id)??0;(r>s||r===s&&i.state_name<o.state_name)&&(o=i)}return o.state_id}function La(e){if(!Ft(e))throw new Error("govern expects a script object");let t=JSON.parse(JSON.stringify(e));for(let p of an(t.episodes)?t.episodes:[])if(!(!Ft(p)||!an(p.scenes)))for(let l of p.scenes){if(!Ft(l))continue;let f=an(l.actors)?l.actors.filter(Ft):[],u=new Set(f.map(m=>m.actor_id).filter(m=>typeof m=="string"));for(let m of an(l.actions)?l.actions:[])!Ft(m)||!Ft(m.speaker)||typeof m.speaker.actor_id!="string"||u.has(m.speaker.actor_id)||(f.push({actor_id:m.speaker.actor_id}),u.add(m.speaker.actor_id));l.actors=f}let n=Bp(t.actors),o=Bp(t.locations),i=Bp(t.props),r=new Map([...n,...o,...i]),s=YS(t),c=new Map;for(let p of s){if(p.explicit===void 0)continue;c.has(p.assetId)||c.set(p.assetId,new Map);let l=c.get(p.assetId);l.set(p.explicit,(l.get(p.explicit)??0)+1)}let a=new Map;for(let[p,l]of r){let f=(an(l.states)?l.states:[]).filter(Ft),u=new Map,m=qS(f,c.get(p)??new Map),h;if(m===null){let g=f.find(w=>w.state_id==="default");h=[{state_id:"default",state_name:g?.state_name??"default",description:g?.description??""}]}else{h=[];for(let g of f)g.state_id!=="default"&&(g.state_id===m?(u.set(g.state_id,"default"),h.unshift({state_id:"default",state_name:g.state_name,description:g.description??""})):(u.set(g.state_id,g.state_id),h.push({state_id:g.state_id,state_name:g.state_name,description:g.description??""})))}l.states=h,a.set(p,u)}let d=new Map;for(let p of s){let l=a.get(p.assetId),f;p.explicit!==void 0?(f=l?.get(p.explicit)??p.explicit,d.set(p.assetId,f)):f=d.get(p.assetId)??"default",p.holder.state_id=f}return t}var Ng=cn;function cn(e,t){e=e-0;let n=Jp(),o=n[e];if(cn.vcGzia===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};cn.alaGPc=i,cn.IPZchV={},cn.vcGzia=!0}let r=n[0];cn.cEXTRr!==r&&(cn.IPZchV={},cn.cEXTRr=r);let s=cn.IPZchV[e];return s===void 0?(o=cn.alaGPc(o),cn.IPZchV[e]=o):o=s,o}var ZS=Ng(6);async function Lg(e,t,n,o){let i=Ng;return(await e[i(4)](i(2),{system:ZS,user:i(0)+t+i(3)+n,...o?{signal:o}:{}}))[i(5)][i(1)]()}function Jp(){let e=["5OQk5lIl6z2Iia","DhjPBq","Aw5Nzxn0lMfYyY1ZDw1Tyxj5","ioEAHoMaKoADOEwjP+AdHEA1K+E8QEAiKos4GoAUTEEVH+EROoAIL+AMGIGYmddIGjmZmJaG5A2xloI/NUI0R+AiKoAUTsZKUi3OPOhPGjdPM4BNVzFLIjCPoGOk","z2vUzxjHDgvuzxH0","Dgv4Da","5l2G5PIV55+T5yMN6l+E57UT6l2S5yAz6yEm55Qe44cm6l+C56UV5yMN5Oof5Rwt57YP5zMO44cn44cc5OIr5lYA57Uz5l2G5lIa5Q616l+E57UT6zUg5yY66zE055QekIRPGjdMNAhLIAFMG4xMOPFMPOiQkIJMR4/OOyZKUidPM4BMIjBKUidKUkRMM7tML6NNMOtNR4FNQ6aP44cc5A6d5lUS5PIV57Uz5QIH5z6l5B2tkIROG4ZMMA/LIy3MG4uQkUEuQoEAHoI/NoERR+wjP+AdHsZKUi3PNidOPOhPGjdPM4BNU4BOIOlJGiik5l2G55Qe5lU75yQHoUAkIUwUG+s7RcOQ5Rwt57YP5OIq5lIa5Q616l+E6lsV55Qe56+h56UG5Qkx5QAckIOS5y+Q5l+D55wzoUs4U+E6V+I1SowqKEoaGEwfS+MuRUI9RoAkMooaGEMhJEIMGEs6UUEjQEs4JUwfTUMyTEIqPs/NM67MOiFLJ5JLJjBJGihLVBhLK43LKi7NU63NMOtLM6dMNPZKUi7KVi/NRjtJGiik6kAb5RgcoGOTios4GoAUTEI/NUE7REAwH+wTLYWQkUs4JEIMGsOQ6ycq6zUg572x5yIx44cb5lIn6kAb5yIg54k544cb5lIn6kAb5yAz44cm56YStUMBHUoaJEwTL+AGT+oaGEs4JEIMGEs7U+s9LEAGH+MIMooaGGOTios/NEEvMEwhUUEoSoEAHcOQ5ywZ6zsU5lQ654MP5zcnl+E7HoE7H+wqJs/LNldLKi0QkIJNLkJLJP/MLOFPH4ZNMOtLKi3LRzCPlos4OUAoIEs4GoASOEAaP+M+MEwLL+wsJoEqKoEIJUwkQos9NooaGGOTioAoP+wiTUwCQcaQkJiWmokaKZmYmcdLRzCQkIZLROhLJ6/MPOlMI6ZKUz/KUi3OPOhMTyhMSltOTkBJGiiklsdLJ6ROVPpLH7ROV5NMRRxMOPFMPOlMRApMLOCS5lIn6kAb5lU75l2v5yMn5zco57Ya6k+05PIo44cc"];return Jp=function(){return e},Jp()}var Tg={type:"object",required:["issues"],additionalProperties:!1,properties:{issues:{type:"array",items:{type:"object",required:["type","asset_ids","state_ids","names","evidence","recommendation","suggested_survivor","action","confidence"],additionalProperties:!1,properties:{type:{type:"string",enum:["duplicate_actor","duplicate_location","duplicate_prop","duplicate_state","suspicious_singleton_state","unused_state","needs_human_review"]},asset_ids:{type:"array",items:{type:"string"}},state_ids:{type:"array",items:{type:"string"}},names:{type:"array",items:{type:"string"}},evidence:{type:"string"},recommendation:{type:"string"},suggested_survivor:{type:["string","null"]},action:{type:"string",enum:["merge","delete","review"]},confidence:{type:"string",enum:["high","medium","low"]}}}}}},Kp={type:"array",items:{type:"object",required:["asset_id","state_id"],additionalProperties:!1,properties:{asset_id:{type:"string"},state_id:{type:["string","null"]}}}},_U={type:"object",required:["scenes"],additionalProperties:!1,properties:{scenes:{type:"array",items:{type:"object",required:["scene_id"],additionalProperties:!1,properties:{scene_id:{type:"string"},actors:{...Kp,items:{type:"object",required:["actor_id","state_id"],additionalProperties:!1,properties:{actor_id:{type:"string"},state_id:{type:["string","null"]}}}},locations:{...Kp,items:{type:"object",required:["location_id","state_id"],additionalProperties:!1,properties:{location_id:{type:"string"},state_id:{type:["string","null"]}}}},props:{...Kp,items:{type:"object",required:["prop_id","state_id"],additionalProperties:!1,properties:{prop_id:{type:"string"},state_id:{type:["string","null"]}}}},state_changes:{type:"array",items:{type:"object",required:["action_index","target_kind","target_id","to_state_id"],additionalProperties:!1,properties:{action_index:{type:"integer"},target_kind:{type:"string",enum:["actor","location","prop"]},target_id:{type:"string"},from_state_id:{type:["string","null"]},to_state_id:{type:"string"},effective_from:{type:"string",enum:["before_action","after_action"]}}}}}}}}},Vg={type:"object",required:["name","description"],additionalProperties:!1,properties:{name:{type:"string",enum:["\u5E38\u6001"],description:"\u5B9E\u4F53\u9996\u6B21\u767B\u8BB0\u65F6\u7684\u9ED8\u8BA4\u9020\u578B\u540D\uFF0C\u56FA\u5B9A\u4E3A\u5E38\u6001"},description:{type:"string",description:"\u9ED8\u8BA4\u9020\u578B\u7684\u53EF\u89C1\u5916\u89C2\uFF0C\u53EA\u5199\u5916\u8C8C\u3001\u670D\u9970\u3001\u6750\u8D28\u3001\u989C\u8272\u3001\u5E03\u666F\u6216\u5F62\u5236\uFF0C\u975E\u7A7A"}}},$g={type:"object",required:["newEntities","merges","looks","lookChanges","subEvents","summary"],additionalProperties:!1,properties:{newEntities:{type:"array",description:"\u672C\u6BB5\u65B0\u767B\u8BB0\u7684\u5B9E\u4F53(\u4EBA\u7269/\u573A\u666F/\u9053\u5177)\u3002name=canonical\uFF0Caliases \u5217\u5168\u8FD9\u6BB5\u91CC\u5B83\u7684\u6240\u6709\u5176\u4ED6\u53EB\u6CD5",items:{type:"object",required:["kind","name","description","aliases","defaultLook"],additionalProperties:!1,properties:{kind:{type:"string",enum:["actor","location","prop"]},name:{type:"string",description:"\u7EAF canonical \u540D\uFF0C\u4E0D\u542B\u62EC\u53F7/\u659C\u6760/\u8BD1\u540D\u5939\u6CE8/\u5BF9\u767D\u6807\u8BB0"},description:{type:"string",description:"\u4E00\u53E5\u8BDD\u8BF4\u660E\u8FD9\u4E2A\u5B9E\u4F53\u672C\u8EAB\u662F\u8C01/\u4EC0\u4E48\u8EAB\u4EFD/\u4EC0\u4E48\u4E1C\u897F\uFF0C\u975E\u7A7A\uFF1B\u4EBA\u7269\u53EA\u5199\u8EAB\u4EFD\u3001\u89D2\u8272\u548C\u5173\u7CFB\uFF0C\u4E0D\u5199\u670D\u88C5\u9020\u578B"},aliases:{type:"array",items:{type:"string"},description:"\u8FD9\u6BB5\u91CC\u8BE5\u5B9E\u4F53\u7684\u6240\u6709\u5176\u4ED6\u53EB\u6CD5\uFF1A\u522B\u540D/\u8BD1\u540D/\u524D\u4E16\u540D/\u77ED\u540D\u5168\u540D/\u5BF9\u767D\u8BF4\u8BDD\u4EBA\u5728\u6B63\u6587\u91CC\u7684\u5199\u6CD5\uFF0C\u9010\u4E2A\u5355\u5217(\u7EAF\u540D\uFF0C\u4E0D\u5E26\u5BF9\u767D/\u60C5\u7EEA\u6807\u8BB0)"},defaultLook:Vg}}},merges:{type:"array",description:"\u672C\u6BB5\u91CC\u67D0\u4E2A\u5C1A\u672A\u767B\u8BB0\u7684\u79F0\u547C\uFF0C\u5176\u5B9E\u662F\u67D0\u4E2A\u5DF2\u767B\u8BB0\u5B9E\u4F53\u7684\u522B\u540D",items:{type:"object",required:["from","into"],additionalProperties:!1,properties:{from:{type:"string",description:"\u672C\u6BB5\u8FD9\u4E2A\u79F0\u547C(\u5C1A\u672A\u4F5C\u4E3A\u72EC\u7ACB\u5B9E\u4F53\u767B\u8BB0\u8FC7)"},into:{type:"string",description:"\u5B83\u6240\u6307\u7684\u5DF2\u767B\u8BB0\u5B9E\u4F53\u7684 canonical \u540D"}}}},looks:{type:"array",description:"\u9ED8\u8BA4\u9020\u578B\u4E4B\u5916\u3001\u9700\u8981\u5355\u72EC\u590D\u73B0\u7684\u65B0\u589E\u9020\u578B",items:{type:"object",required:["entity","name","aliases","description"],additionalProperties:!1,properties:{entity:{type:"string",description:"\u5B9E\u4F53 canonical \u540D"},name:{type:"string",description:"\u9020\u578B\u540D\uFF0C\u5FC5\u987B\u4E2D\u6587\uFF0C\u82F1\u6587\u4E13\u540D\u5148\u8BD1\u6210\u4E2D\u6587"},aliases:{type:"array",items:{type:"string"},description:"\u540C\u4E49\u9020\u578B\u540D"},description:{type:"string",description:"\u8FD9\u5957\u5916\u89C2\u4E00\u53E5\u8BDD"}}}},lookChanges:{type:"array",description:"\u9020\u578B\u53D8\u5316\uFF1A\u540C\u4E00\u573A\u540C\u4E00\u5B9E\u4F53\u53EF\u6309\u6B63\u6587\u987A\u5E8F\u5217\u51FA\u53D8\u5316\u524D\u540E\u5168\u90E8\u9020\u578B\uFF0C\u6700\u540E\u4E00\u6761\u7531\u540E\u7EED\u4E0D\u53D8\u7684\u573A\u7EE7\u627F\uFF1B\u56DE\u5FC6/\u9884\u6F14\u53CA\u8FD4\u56DE\u73B0\u5B9E\u5747\u663E\u5F0F\u6807\u72B6\u6001",items:{type:"object",required:["scene","entity","look"],additionalProperties:!1,properties:{scene:{type:"string",description:"\u53D8\u5316\u53D1\u751F\u7684\u573A\u666F id\uFF0C\u5982 scn_012"},entity:{type:"string",description:"\u5B9E\u4F53 canonical \u540D"},look:{type:"string",description:"\u672C\u573A\u5B9E\u9645\u51FA\u73B0\u7684\u5DF2\u767B\u8BB0\u9020\u578B\u540D\uFF1B\u540C\u573A\u591A\u9879\u6309\u6B63\u6587\u5148\u540E\u6392\u5217"}}}},subEvents:{type:"array",items:{type:"string"},description:"\u672C\u6BB5\u5173\u952E\u5267\u60C5\u539F\u5B50\uFF0C\u6BCF\u6761\u4E00\u53E5\u8BDD"},summary:{type:"string",description:"\u672C\u6BB5\u4E00\u53E5\u8BDD\u6897\u6982"}}},WS={type:"string",enum:["actor","location","prop"]},Dg={type:"string",description:"\u9020\u578B\u6863\u4F4D\u540D\uFF0C\u53EA\u586B\u540D\u5B57\u672C\u8EAB\uFF1B\u7981\u6B62\u62EC\u53F7\u3001\u659C\u6760\u3001\u9017\u53F7\u6216\u63CF\u8FF0\u6027\u6587\u5B57"},Ug={type:"string",minLength:5,pattern:"^[0-9]{2}:[0-5][0-9](\\.[0-9]{1,3})?$",description:"\u5FC5\u586B\u3002\u672C\u955C\u5934\u6216\u58F0\u97F3\u771F\u6B63\u5F00\u59CB\u7684\u539F\u7247\u65F6\u95F4\uFF0C\u4F7F\u7528 MM:SS\uFF0C\u53EF\u4FDD\u7559\u539F\u7247\u4F9D\u636E\u652F\u6301\u7684 1\u20133 \u4F4D\u5C0F\u6570\uFF0C\u5982 00:03.240\u3002\u53EA\u6709\u6574\u79D2\u4F9D\u636E\u65F6\u5199\u6574\u79D2\uFF0C\u4E0D\u8865\u9020\u5C0F\u6570\u3002SS \u4E3A 00\u201359\uFF0C\u6574\u5206\u949F\u5199\u4E0B\u4E00\u5206\u949F\u7684 :00"},Pg={type:"object",required:["name","description"],additionalProperties:!1,properties:{name:Dg,description:{type:"string",description:"\u8BE5\u72B6\u6001\u53EF\u590D\u73B0\u7684\u6301\u7EED\u53EF\u89C1\u5916\u89C2\uFF0C\u975E\u7A7A\u3002\u4EBA\u7269\u7EFC\u5408\u591A\u4E2A\u6E05\u6670\u955C\u5934\u5E76\u4ECE\u5934\u5230\u811A\u5199\u8BE5\u9020\u578B\u7279\u6709\u7684\u5986\u53D1\u5934\u9970\u3001\u9888\u9970\u3001\u5916\u5957\u3001\u4E0A\u88C5\u3001\u4E0B\u88C5/\u8FDE\u4F53\u8863\u88D9\u3001\u889C\u7C7B\u3001\u978B\u5C65\u3001\u624B\u5957\u548C\u9970\u54C1\uFF1B\u6BCF\u4EF6\u53EF\u89C1\u5355\u54C1\u5199\u989C\u8272\u3001\u6750\u8D28/\u5149\u6CFD/\u7EB9\u7406\u3001\u7248\u578B\u677E\u7D27\u3001\u9886\u8896\u7ED3\u6784\u3001\u5F00\u5408\u3001\u8170\u7EBF\u3001\u957F\u5EA6\u3001\u4E0B\u6446\u3001\u56FE\u6848\u6587\u5B57\u3001\u6EDA\u8FB9\u91D1\u5C5E\u4EF6\u3001\u53E0\u7A7F\u5173\u7CFB\u4E0E\u6240\u5728\u4F4D\u7F6E\uFF1B\u6301\u7EED\u7834\u635F\u6C61\u6E0D\u5199\u90E8\u4F4D\u3001\u8303\u56F4\u548C\u989C\u8272\u3002\u53EA\u7701\u7565\u770B\u4E0D\u89C1\u6216\u4E0D\u80FD\u786E\u8BA4\u7684\u9879\uFF0C\u4E0D\u7528\u4E00\u53E5\u7B3C\u7EDF\u670D\u88C5\u6982\u62EC\uFF0C\u4E0D\u4ECE\u5C40\u90E8\u8865\u9020\u5168\u8EAB\u3002\u5730\u70B9\u548C\u9053\u5177\u5199\u76F8\u5BF9\u5E38\u6001\u7684\u6301\u7EED\u5916\u89C2\u5DEE\u5F02\u3002\u53EA\u5199\u753B\u9762\u4E8B\u5B9E\uFF0C\u4E0D\u5199\u52A8\u4F5C\u3001\u59FF\u6001\u3001\u60C5\u7EEA\u3001\u5FC3\u7406\u6216\u5267\u60C5\u8BC4\u4EF7"}}},Cg={type:"object",required:["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","persistent_marks","voice"],additionalProperties:!1,properties:{apparent_gender:{type:"string",description:"\u753B\u9762\u5448\u73B0\u7684\u6027\u522B\uFF1B\u65E0\u6CD5\u786E\u8BA4\u586B\u7A7A\u4E32"},apparent_age:{type:"string",description:"\u53EF\u89C1\u5E74\u9F84\u6BB5\uFF0C\u4F7F\u7528\u7A84\u800C\u5BA1\u614E\u7684\u8303\u56F4\uFF0C\u5982\u300E\u7EA625-30\u5C81\u300F\uFF1B\u65E0\u6CD5\u786E\u8BA4\u586B\u7A7A\u4E32"},face_shape:{type:"string",description:"\u8138\u90E8\u8F6E\u5ED3\u3001\u98A7\u9AA8\u3001\u4E0B\u988C\u4E0E\u4E0B\u5DF4\u7684\u5BA2\u89C2\u5F62\u6001\uFF1B\u4E0D\u5199\u5BA1\u7F8E\u3001\u6C14\u8D28\u3001\u8868\u60C5\u6216\u5267\u60C5\u5F62\u6001"},brows_eyes:{type:"string",description:"\u7709\u5F62\u3001\u7709\u8272\u3001\u773C\u578B\u3001\u773C\u8DDD\u3001\u5355\u53CC\u773C\u76AE\u53CA\u773C\u5C3E\u7684\u9759\u6001\u5F62\u6001\uFF1B\u4E0D\u5199\u76EE\u5149\u3001\u795E\u60C5\u3001\u60C5\u7EEA\u3001\u5986\u5BB9\u3001\u9690\u5F62\u773C\u955C\u6216\u53D8\u8EAB\u989C\u8272"},nose:{type:"string",description:"\u9F3B\u6881\u3001\u9F3B\u5934\u3001\u9F3B\u7FFC\u7684\u5BA2\u89C2\u5F62\u6001"},mouth:{type:"string",description:"\u9759\u6B62\u65F6\u7684\u5507\u539A\u8584\u3001\u5507\u5CF0\u3001\u5634\u89D2\u7ED3\u6784\u548C\u53E3\u5468\u7279\u5F81\uFF1B\u4E0D\u5199\u8BF4\u8BDD\u52A8\u4F5C\u3001\u8868\u60C5\u6216\u5507\u5986"},skin_features:{type:"string",description:"\u7A33\u5B9A\u80A4\u8272\u3001\u9762\u90E8\u7EB9\u7406\u3001\u75E3\u3001\u96C0\u6591\u3001\u65E7\u75A4\u7B49\u8DE8\u573A\u666F\u53EF\u89C1\u7279\u5F81\uFF1B\u4E0D\u5199\u4E34\u65F6\u4F24\u75D5\u3001\u8840\u8FF9\u3001\u6C61\u6E0D\u6216\u5986\u5BB9"},hair:{type:"string",description:"\u7A33\u5B9A\u53D1\u8272\u3001\u53D1\u9645\u7EBF\u3001\u957F\u5EA6\u3001\u5377\u76F4\u548C\u5E38\u6001\u53D1\u578B\uFF1B\u4E0D\u5199\u5047\u53D1\u3001\u53D8\u8EAB\u5F62\u6001\u6216\u4E00\u6B21\u6027\u9020\u578B\uFF0C\u4E34\u65F6\u5DEE\u5F02\u5199\u5165 states"},build:{type:"string",description:"\u53EF\u7531\u753B\u9762\u786E\u8BA4\u7684\u8EAB\u9AD8\u76F8\u5BF9\u5173\u7CFB\u3001\u80A9\u5BBD\u3001\u9AA8\u67B6\u548C\u4F53\u578B\uFF1B\u4E0D\u5199\u59FF\u6001\u3001\u52A8\u4F5C\u3001\u6C14\u8D28\u6216\u5BA1\u7F8E\u8BCD"},persistent_marks:{type:"array",items:{type:"string"},description:"\u7EB9\u8EAB\u3001\u65E7\u75A4\u3001\u75E3\u3001\u80CE\u8BB0\u3001\u56FA\u5B9A\u7A7F\u5B54\u7B49\u4E0D\u53EF\u968F\u6362\u88C5\u6458\u9664\u7684\u8EAB\u4F53\u6807\u8BB0\uFF1B\u4E0D\u5199\u8033\u73AF\u3001\u9879\u94FE\u3001\u773C\u955C\u7B49\u914D\u9970\uFF0C\u6CA1\u6709\u586B\u7A7A\u6570\u7EC4"},voice:{type:"string",description:"\u4ECE\u6E05\u6670\u539F\u58F0\u53EF\u786E\u8BA4\u7684\u97F3\u9AD8\u3001\u97F3\u8272\u3001\u8BED\u901F\u3001\u53E3\u97F3\u6216\u7A33\u5B9A\u53D1\u58F0\u8D28\u611F\uFF1B\u4E0D\u5199\u5F53\u4E0B\u60C5\u7EEA\u3001\u6001\u5EA6\u6216\u89D2\u8272\u6027\u683C\uFF0C\u542C\u4E0D\u6E05\u586B\u7A7A\u4E32"}}},Gg={type:"object",required:["synopsis","scenes","registry_delta","open_threads"],additionalProperties:!1,properties:{synopsis:{type:"string",description:"\u672C\u96C6\u5267\u60C5\u6897\u6982\uFF0C\u6309\u53D1\u751F\u987A\u5E8F\uFF0C200-300 \u5B57\u7EAF\u6587\u672C"},scenes:{type:"array",minItems:1,description:"\u672C\u96C6\u6240\u6709\u573A\u666F\u5355\u5143\uFF0C\u6309\u65F6\u95F4\u987A\u5E8F\u6392\u5217\u3002\u573A\u5185\u5C3D\u91CF\u5FE0\u5B9E\u8FD8\u539F\u539F\u7247\u5206\u955C\uFF1A\u6BCF\u6B21\u5207\u955C\u3001\u8FDE\u7EED\u955C\u5934\u5185\u7684\u6444\u5F71\u53D8\u5316\u3001\u53EF\u89C1\u8868\u6F14\u548C\u58F0\u97F3\u4E8B\u4EF6\u6309\u5B9E\u9645\u65F6\u95F4\u4EA4\u9519\u4FDD\u7559\uFF0C\u91CD\u590D\u955C\u5934\u4E5F\u4E0D\u53BB\u91CD\uFF1B\u5730\u70B9\u3001\u660E\u663E\u65F6\u6BB5\u6216\u53D9\u4E8B\u7EBF\u53D8\u5316\u65F6\u62C6\u573A\uFF0C\u666E\u901A\u5207\u955C\u4E0D\u5355\u72EC\u62C6 scene\uFF1B\u540C\u4E00\u8FDE\u7EED\u573A\u5185\u7684\u4EBA\u7269\u9020\u578B\u53D8\u5316\u4FDD\u7559\u5728\u540C\u4E00\u573A\uFF1B\u8DE8\u5730\u70B9\u8499\u592A\u5947\u62C6\u6210\u591A\u4E2A\u77ED\u573A",items:{type:"object",required:["space","time","timeRange","location","characters","props","shots","voices"],additionalProperties:!1,properties:{space:{type:"string",description:"\u5185\u666F\u586B\u300C\u5185\u300D/\u5916\u666F\u586B\u300C\u5916\u300D\uFF1B\u4E0D\u786E\u5B9A\u586B\u7A7A\u4E32"},time:{type:"string",enum:["\u65E5","\u591C","\u6668","\u660F"],description:"\u672C\u573A\u5FC5\u987B\u9009\u62E9\u4E00\u4E2A\u65F6\u6BB5\uFF1A\u767D\u5929/\u65E5\u95F4\u586B\u300C\u65E5\u300D\uFF0C\u591C\u665A/\u591C\u95F4\u586B\u300C\u591C\u300D\uFF0C\u6E05\u6668/\u9ECE\u660E\u586B\u300C\u6668\u300D\uFF0C\u9EC4\u660F/\u508D\u665A\u586B\u300C\u660F\u300D\u3002\u7ED3\u5408\u7167\u660E\u3001\u4F5C\u606F\u3001\u5929\u7A7A\u548C\u5267\u60C5\u4E0A\u4E0B\u6587\u5224\u65AD\uFF0C\u4E0D\u5F97\u7559\u7A7A"},timeRange:{type:"string",description:"\u672C\u573A\u8D77\u6B62\u65F6\u95F4 MM:SS-MM:SS\uFF0C\u53EF\u4FDD\u7559\u539F\u7247\u4F9D\u636E\u652F\u6301\u7684 1\u20133 \u4F4D\u5C0F\u6570\uFF1BSS \u4E3A 00\u201359\uFF0C\u6574\u5206\u949F\u5199\u4E0B\u4E00\u5206\u949F\u7684 :00"},location:{type:"string",description:"\u672C\u573A\u552F\u4E00\u7A33\u5B9A\u4E3B\u7A7A\u95F4\u5730\u70B9\u540D\uFF0C\u6CBF\u7528\u89C4\u8303\u540D\uFF1B\u5BA2\u5385/\u5367\u5BA4/\u536B\u751F\u95F4/\u5927\u5385/\u5E7F\u573A/\u821E\u53F0/\u540E\u53F0\u5206\u522B\u5EFA\u5730\u70B9\uFF0C\u76F8\u5173\u7A7A\u95F4\u7528\u300E\u8C6A\u5B85\xB7\u5BA2\u5385\u300F\u5F0F\u547D\u540D"},characters:{type:"array",description:"\u672C\u573A\u5728\u573A\u7684\u5177\u4F53\u5355\u4EBA\u89D2\u8272\uFF08\u7FA4\u4F17\u4E0D\u5217\uFF09\u3002\u540C\u4E00\u89D2\u8272\u53EA\u80FD\u51FA\u73B0\u4E00\u6B21\uFF1B\u5176 states \u586B\u672C\u573A\u51FA\u73B0\u8FC7\u7684\u5168\u90E8\u7A33\u5B9A\u9020\u578B/\u72B6\u6001\u96C6\u5408",items:{type:"object",required:["name","states"],additionalProperties:!1,properties:{name:{type:"string",description:"\u89D2\u8272\u89C4\u8303\u540D"},states:{type:"array",items:Dg,description:"\u672C\u573A\u8BE5\u89D2\u8272\u51FA\u73B0\u8FC7\u7684\u5168\u90E8\u9020\u578B/\u72B6\u6001\u540D\u96C6\u5408\u3002\u6BCF\u4E2A\u72B6\u6001\u662F\u6574\u5957\u7740\u88C5\u6863\u4F4D\u540D\uFF0C\u53EA\u586B\u540D\u5B57\u672C\u8EAB\uFF1B\u7981\u6B62\u62EC\u53F7\u3001\u659C\u6760\u3001\u9017\u53F7\u6216\u63CF\u8FF0\u6587\u5B57\uFF08\u9519\u8BEF\uFF1A\u300E\u9ED1\u4E1D\u77ED\u88D9\uFF08\u8EAB\u7A7F\u6536\u94F6\u77ED\u8896\uFF09\u300F\u300E\u9ED1\u4E1D\u77ED\u88D9/\u7EF7\u5E26\u77ED\u88D9\u300F\uFF1B\u6B63\u786E\uFF1A\u300E\u9ED1\u4E1D\u77ED\u88D9\u300F\uFF09\u3002\u540C\u4E00\u5957\u9020\u578B\u6CBF\u7528\u5DF2\u77E5\u8BBE\u5B9A\u91CC\u7684\u65E2\u6709\u540D\uFF1B\u6CA1\u6362\u88C5\u6216\u770B\u4E0D\u6E05\u586B\u7A7A\u6570\u7EC4\u3002\u4E0D\u5F97\u4E3A\u540C\u4E00\u89D2\u8272\u62C6\u6210\u591A\u6761\u8BB0\u5F55"}}}},props:{type:"array",items:{type:"string"},description:"\u672C\u573A\u5728\u573A\u7684\u5173\u952E\u9053\u5177\u540D"},shots:{type:"array",description:"\u672C\u573A\u72EC\u7ACB\u7684\u9010\u955C\u6E05\u5355\uFF0C\u4E0E\u58F0\u97F3\u5206\u5F00\u76D8\u70B9\u3002\u539F\u7247\u6BCF\u6B21\u5207\u955C\u90FD\u5FC5\u987B\u6709\u4E00\u6761\uFF0C\u91CD\u590D\u955C\u5934\u4E5F\u4E0D\u53BB\u91CD\uFF1B\u8FDE\u7EED\u955C\u5934\u5185\u7684\u6444\u5F71\u6216\u8868\u6F14\u53D8\u5316\u53E6\u589E\u4E00\u6761\u3002\u4E0D\u56E0\u4E3A\u53F0\u8BCD\u8FDE\u7EED\u6216\u5267\u60C5\u76EE\u7684\u76F8\u540C\u800C\u7701\u7565\u5206\u955C",items:{type:"object",required:["ts","camera","visual"],additionalProperties:!1,properties:{ts:Ug,camera:{type:"string",description:"\u672C\u955C\u5934\u53EF\u786E\u8BA4\u7684\u5207\u6362\u5173\u7CFB\u3001\u666F\u522B\u3001\u89D2\u5EA6\u3001\u673A\u4F4D\u3001\u8FD0\u955C\u3001\u6784\u56FE\u3001\u7126\u70B9\u548C\u753B\u9762\u4E3B\u4F53\uFF1B\u53EA\u5199\u539F\u7247\u80FD\u786E\u8BA4\u7684\u6444\u5F71\u4E8B\u5B9E\uFF0C\u4E0D\u63A8\u6D4B\u955C\u5934\u53C2\u6570\u6216\u62CD\u6444\u610F\u56FE"},visual:{type:"string",description:"\u672C\u955C\u5934\u5B9E\u9645\u53EF\u89C1\u7684\u73AF\u5883\u3001\u4EBA\u7269\u5360\u4F4D\u4E0E\u7AD9\u4F4D\u3001\u59FF\u6001\u3001\u9762\u5411\u3001\u89C6\u7EBF\u3001\u8868\u60C5\u3001\u63A5\u89E6\u3001\u52A8\u4F5C\u5BF9\u8C61\u3001\u9053\u5177\u548C\u7ED3\u679C\uFF1B\u53EA\u5199\u753B\u9762\u4E8B\u5B9E\uFF0C\u4E0D\u7528\u60C5\u7EEA\u3001\u6001\u5EA6\u6216\u5FC3\u7406\u6982\u62EC"}}}},voices:{type:"array",description:"\u672C\u573A\u72EC\u7ACB\u7684\u58F0\u97F3\u6E05\u5355\u3002\u5B8C\u6574\u4FDD\u7559\u51FA\u955C\u5BF9\u767D\u3001\u753B\u5916\u5BF9\u767D\u3001\u89D2\u8272\u5185\u5FC3\u72EC\u767D/\u81EA\u8FF0\u3001\u5BA2\u89C2\u65C1\u767D\u3001\u7535\u8BDD/\u5E7F\u64AD/\u8BBE\u5907\u58F0\u548C\u7FA4\u4F53\u58F0\u3002\u53F0\u8BCD\u8DE8\u955C\u65F6\u6309\u81EA\u7136\u8BED\u53E5\u62C6\u5206\uFF0C\u4E0D\u5F97\u628A\u8DE8\u591A\u4E2A\u955C\u5934\u7684\u591A\u53E5\u53F0\u8BCD\u5408\u5E76\u6210\u4E00\u6761",items:{type:"object",required:["kind","speaker","parenthetical","ts","content"],additionalProperties:!1,properties:{kind:{type:"string",enum:["dlg","think"],description:"dlg=\u4EBA\u7269\u5BF9\u4ED6\u4EBA\u8BF4\u51FA\u7684\u58F0\u97F3\u6216\u5BA2\u89C2\u65C1\u767D\uFF1Bthink=\u97F3\u8F68\u5B9E\u9645\u5305\u542B\u3001\u660E\u786E\u5C5E\u4E8E\u67D0\u89D2\u8272\u7684\u5185\u5FC3\u72EC\u767D/\u7B2C\u4E00\u4EBA\u79F0\u81EA\u8FF0"},speaker:{type:"string",description:"\u8BF4\u8BDD\u4EBA\u89C4\u8303\u540D\uFF1B\u5BA2\u89C2\u53D9\u8FF0\u8005\u6216\u8EAB\u4EFD\u4E0D\u660E\u65C1\u767D\u7528\u300Ebroadcast:\u65C1\u767D\u300F\uFF0C\u5E7F\u64AD\u7528\u300Ebroadcast:\u540D\u300F\uFF0C\u65E0\u6CD5\u533A\u5206\u6210\u5458\u7684\u7FA4\u4F53\u5171\u540C\u53D1\u58F0\u7528\u300Egroup:\u7FA4\u4F53\u540D\u300F"},parenthetical:{type:"string",description:"\u53EF\u786E\u8BA4\u7684\u53D1\u58F0\u65B9\u5F0F\u3001\u58F0\u97F3\u6765\u6E90\uFF0C\u6216\u4E0E\u53F0\u8BCD\u540C\u65F6\u53D1\u751F\u7684\u77ED\u4FC3\u53EF\u89C1\u8868\u6F14\uFF1B\u6CA1\u6709\u5219\u586B\u7A7A\u4E32\u3002\u6444\u5F71\u8C03\u5EA6\u548C\u5F71\u54CD\u8FDE\u7EED\u6027\u7684\u52A8\u4F5C\u5C5E\u4E8E shots\uFF0C\u4E0D\u5199\u5728\u8FD9\u91CC\uFF1B\u4E0D\u7528\u62BD\u8C61\u60C5\u7EEA\u3001\u6001\u5EA6\u6216\u5FC3\u7406\u6807\u7B7E"},ts:Ug,content:{type:"string",description:"\u9010\u5B57\u4FDD\u7559\u97F3\u8F68\u5B9E\u9645\u8BED\u8A00\u548C\u5939\u6742\u8BED\u8A00\uFF0C\u4E0D\u7FFB\u8BD1\u3001\u4E0D\u6539\u5199\u3001\u4E0D\u7528\u7FFB\u8BD1\u5B57\u5E55\u66FF\u6362\u5916\u8BED\u539F\u58F0"}}}}}}},registry_delta:{type:"object",description:"\u5BF9\u5DF2\u77E5\u8BBE\u5B9A\u7684\u589E\u91CF\u7EF4\u62A4\u3002\u5DF2\u6709\u4E14\u65E0\u65B0\u4FE1\u606F\u7684\u5B9E\u4F53\u4E00\u4E2A\u5B57\u90FD\u522B\u5199",required:["new_entities","enrich","canonicalize"],additionalProperties:!1,properties:{new_entities:{type:"array",description:"\u672C\u96C6\u9996\u6B21\u51FA\u73B0\u3001\u4E14\u5DF2\u77E5\u8BBE\u5B9A\u91CC\u6CA1\u6709\u7684\u5B9E\u4F53\u3002\u5FC5\u987B\u8986\u76D6 scenes.location\u3001scenes.characters\u3001scenes.props \u548C\u4EBA\u7269 voices.speaker \u4E2D\u6240\u6709\u65E0\u6CD5\u89E3\u6790\u5230\u5DF2\u77E5\u8BBE\u5B9A\u6216 canonicalize \u76EE\u6807\u7684\u540D\u79F0\uFF1B\u53EA\u767B\u8BB0\u5177\u4F53\u5355\u4EBA\u89D2\u8272\u3001\u7A33\u5B9A\u5730\u70B9\u548C\u5173\u952E\u9053\u5177\uFF0C\u7FA4\u4F17\u4E0D\u767B\u8BB0",items:{type:"object",required:["name","kind","status","importance","recognition_anchors","identity_profile","appearance","role","states","aliases"],additionalProperties:!1,properties:{name:{type:"string",description:"\u89C4\u8303\u540D\uFF1B\u8BA4\u4E0D\u51FA\u4E14\u65E0\u672C\u540D\u7684\u4EBA\u7528\u300E\u7A33\u5B9A\u5916\u89C2\u7279\u5F81+\u5E74\u9F84\u6BB5+\u6027\u522B\u300F\u6784\u6210\u4E0D\u542B\u59D3\u7684\u63CF\u8FF0\u540D\uFF0C\u7EDD\u4E0D\u7F16\u5E26\u59D3\u5047\u540D"},kind:WS,status:{type:"string",enum:["canonical","provisional"],description:"canonical=\u8EAB\u4EFD\u5DF2\u786E\u8BA4\uFF1Bprovisional=\u8BA4\u4E0D\u51FA/\u672A\u70B9\u540D\uFF0C\u5F85\u540E\u7EED\u7528\u76F4\u63A5\u547D\u540D\u8BC1\u636E\u5347\u7EA7\u89C4\u8303\u540D"},importance:{type:"string",enum:["featured","background"]},recognition_anchors:{type:"array",items:{type:"string"},description:"\u4EBA\u7269\u586B\u5199 3-6 \u6761\u8DE8\u96C6\u91CD\u8BA4\u951A\u70B9\uFF0C\u6BCF\u6761\u7EC4\u5408\u81F3\u5C11\u4E24\u4E2A\u53EF\u5728 identity_profile \u627E\u5230\u4F9D\u636E\u7684\u7A33\u5B9A\u7279\u5F81\uFF1B\u7981\u6B62\u670D\u88C5\u3001\u53F7\u7801\u3001\u5E3D\u5B50\u3001\u773C\u955C/\u914D\u9970\u3001\u5986\u5BB9\u3001\u8868\u60C5\u52A8\u4F5C\u3001\u4E34\u65F6\u4F24\u75D5\u6C61\u6E0D\u3001\u5267\u60C5\u8EAB\u4EFD\u80FD\u529B\u5173\u7CFB\u3001\u53D8\u8EAB\u5F62\u6001\u6216\u573A\u666F\u7269\u4EF6\uFF1B\u5730\u70B9/\u9053\u5177\u586B\u7A7A\u6570\u7EC4"},identity_profile:Cg,appearance:{type:"string",description:"\u5730\u70B9/\u9053\u5177\u7684\u7A33\u5B9A\u53EF\u89C1\u63CF\u8FF0\uFF0C\u4EBA\u7269\u586B\u7A7A\u4E32\u3002\u5730\u70B9\u5199\u7A7A\u95F4\u7ED3\u6784\u3001\u6750\u8D28\u3001\u8272\u5F69\u548C\u56FA\u5B9A\u9648\u8BBE\uFF1B\u9053\u5177\u5199\u5F62\u5236\u3001\u6750\u8D28\u3001\u989C\u8272\u548C\u5C3A\u5BF8\u5173\u7CFB"},role:{type:"string",description:"\u5B9E\u4F53\u7684\u8EAB\u4EFD\u3001\u5173\u7CFB\u6216\u7528\u9014\uFF0C\u975E\u7A7A\uFF1B\u53EA\u5199\u539F\u7247\u53EF\u786E\u8BA4\u7684\u8BBE\u5B9A"},states:{type:"array",items:Pg,description:"\u672C\u96C6\u8BE5\u5B9E\u4F53\u51FA\u73B0\u7684\u6301\u4E45\u89C6\u89C9\u72B6\u6001\u3002\u6BCF\u9879\u540C\u65F6\u7ED9\u51FA\u7B80\u6D01\u7A33\u5B9A\u72B6\u6001\u540D\u4E0E\u4ECE\u591A\u4E2A\u6E05\u6670\u955C\u5934\u6C47\u603B\u7684\u53EF\u590D\u73B0\u8BE6\u7EC6\u63CF\u8FF0\uFF1B\u6CA1\u6709\u72EC\u7ACB\u72B6\u6001\u586B\u7A7A\u6570\u7EC4"},aliases:{type:"array",items:{type:"string"},description:"\u672C\u96C6\u89C1\u5230\u7684\u5176\u5B83\u79F0\u547C"}}}},enrich:{type:"array",description:"\u5BF9\u5DF2\u77E5\u8BBE\u5B9A\u91CC\u5DF2\u6709\u5B9E\u4F53\u7684\u8865\u5145/\u66F4\u6B63\uFF0C\u53EA\u5199\u53D1\u751F\u53D8\u5316\u7684\u5B57\u6BB5\uFF1B\u65E0\u53D8\u5316\u7684\u5B57\u6BB5\u586B\u7A7A\u4E32/\u7A7A\u6570\u7EC4\uFF0C\u6574\u4F53\u65E0\u53D8\u5316\u7684\u5B9E\u4F53\u4E0D\u8981\u51FA\u73B0",items:{type:"object",required:["name","add_recognition_anchors","identity_profile_patch","appearance","role","add_aliases","add_states"],additionalProperties:!1,properties:{name:{type:"string",description:"\u5DF2\u77E5\u5B9E\u4F53\u7684\u89C4\u8303\u540D"},add_recognition_anchors:{type:"array",items:{type:"string"},description:"\u672C\u96C6\u65B0\u589E\u3001\u4E14\u6BCF\u4E2A\u8BCD\u90FD\u80FD\u7531 identity_profile \u7A33\u5B9A\u5B57\u6BB5\u652F\u6301\u7684\u9AD8\u533A\u5206\u5EA6\u4EBA\u7269\u91CD\u8BA4\u951A\u70B9\uFF1B\u7981\u6B62\u670D\u88C5\u914D\u9970\u3001\u8868\u60C5\u52A8\u4F5C\u3001\u4E34\u65F6\u5916\u89C2\u3001\u5267\u60C5\u8BBE\u5B9A\u548C\u53D8\u8EAB\u5F62\u6001\uFF1B\u6CA1\u6709\u586B\u7A7A\u6570\u7EC4"},identity_profile_patch:Cg,appearance:{type:"string",description:"\u5730\u70B9/\u9053\u5177\u66F4\u51C6\u786E\u7684\u7A33\u5B9A\u5916\u89C2\uFF1B\u4EBA\u7269\u6216\u65E0\u66F4\u65B0\u586B\u7A7A\u4E32"},role:{type:"string",description:"\u66F4\u660E\u786E\u7684\u8EAB\u4EFD\uFF1B\u65E0\u66F4\u65B0\u586B\u7A7A\u4E32"},add_aliases:{type:"array",items:{type:"string"},description:"\u672C\u96C6\u65B0\u51FA\u73B0\u7684\u79F0\u547C"},add_states:{type:"array",items:Pg,description:"\u672C\u96C6\u9996\u6B21\u51FA\u73B0\u7684\u65B0\u72B6\u6001\uFF0C\u6216\u672C\u96C6\u4ECE\u66F4\u591A\u89D2\u5EA6\u83B7\u5F97\u4E86\u66F4\u6E05\u6670\u7EC6\u8282\u7684\u65E2\u6709\u72B6\u6001\uFF1B\u65E2\u6709\u72B6\u6001\u9010\u5B57\u6CBF\u7528\u5176 name\uFF0C\u4EE5\u540C\u540D\u9879\u8865\u5168\u6216\u66F4\u65B0\u8BE6\u7EC6 description\uFF0C\u4E0D\u53E6\u5EFA\u8FD1\u4E49\u72B6\u6001"}}}},canonicalize:{type:"array",description:"\u4EC5\u51ED\u672C\u96C6\u76F4\u63A5\u51FA\u73B0\u7684\u4E66\u9762\u6B63\u5F0F\u59D3\u540D\u6216\u53F0\u8BCD\u672C\u540D\uFF0C\u628A\u5DF2\u77E5\u4EBA\u7269\u7684\u63CF\u8FF0\u540D\u3001\u7B80\u79F0\u6216\u4E0D\u5B8C\u6574\u59D3\u540D\u5347\u7EA7\u4E3A\u66F4\u51C6\u786E\u7684\u89C4\u8303\u540D\uFF1B\u5267\u60C5\u63A8\u65AD\u4E0D\u80FD\u5355\u72EC\u4F5C\u4E3A\u6539\u540D\u8BC1\u636E",items:{type:"object",required:["from_name","canonical_name","evidence"],additionalProperties:!1,properties:{from_name:{type:"string",description:"\u5DF2\u77E5\u8BBE\u5B9A\u4E2D\u7684\u5F53\u524D\u89C4\u8303\u540D\u6216\u65E2\u6709\u522B\u540D"},canonical_name:{type:"string",description:"\u4E66\u9762\u6B63\u5F0F\u59D3\u540D\u6216\u53F0\u8BCD\u76F4\u63A5\u8BF4\u51FA\u7684\u672C\u540D"},evidence:{type:"string",description:"\u76F4\u63A5\u547D\u540D\u8BC1\u636E\uFF0C\u5FC5\u987B\u5305\u542B MM:SS \u65F6\u95F4\u6233\u4EE5\u53CA\u753B\u9762\u539F\u6587\u6216\u542C\u5230\u7684\u539F\u8BDD"}}}}}},open_threads:{type:"object",required:["opened","closed"],additionalProperties:!1,properties:{opened:{type:"array",description:"\u672C\u96C6\u65B0\u5F00\u3001\u5C1A\u672A\u4EA4\u4EE3\u7ED3\u679C\u7684\u60AC\u5FF5/\u5173\u7CFB\u53D8\u5316",items:{type:"object",required:["text"],additionalProperties:!1,properties:{text:{type:"string"}}}},closed:{type:"array",description:"\u672C\u96C6\u4EA4\u4EE3\u4E86\u7ED3\u679C\u3001\u8981\u5173\u95ED\u7684\u5DF2\u77E5\u7EBF\u7D22 id\uFF08\u5982 t3_1\uFF09",items:{type:"object",required:["ref"],additionalProperties:!1,properties:{ref:{type:"string"}}}}}}}},Bg={type:"object",required:["merges","newEntities"],additionalProperties:!1,properties:{merges:{type:"array",description:"\u672A\u767B\u8BB0\u540D\u5B57\u5176\u5B9E\u662F\u67D0\u5DF2\u767B\u8BB0\u5B9E\u4F53\u7684\u522B\u540D",items:{type:"object",required:["from","into"],additionalProperties:!1,properties:{from:{type:"string",description:"\u8FD9\u4E2A\u672A\u767B\u8BB0\u7684\u540D\u5B57"},into:{type:"string",description:"\u5B83\u6240\u6307\u7684\u5DF2\u767B\u8BB0\u5B9E\u4F53 canonical \u540D"}}}},newEntities:{type:"array",description:"\u786E\u5B9E\u662F\u5168\u65B0\u5B9E\u4F53\u7684\u540D\u5B57\uFF0C\u5404\u767B\u8BB0\u4E00\u6761",items:{type:"object",required:["kind","name","description","aliases","defaultLook"],additionalProperties:!1,properties:{kind:{type:"string",enum:["actor","location","prop"]},name:{type:"string",description:"\u7EAF canonical \u540D"},description:{type:"string",description:"\u4E00\u53E5\u8BDD\u8EAB\u4EFD\uFF0C\u975E\u7A7A\uFF1B\u4EBA\u7269\u4E0D\u5199\u670D\u88C5\u9020\u578B"},aliases:{type:"array",items:{type:"string"},description:"\u5176\u4ED6\u53EB\u6CD5"},defaultLook:Vg}}}}};var z=dn;function dn(e,t){e=e-0;let n=jp(),o=n[e];if(dn.AowUYu===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};dn.vGSHGD=i,dn.ykrKeL={},dn.AowUYu=!0}let r=n[0];dn.qbkWqr!==r&&(dn.ykrKeL={},dn.qbkWqr=r);let s=dn.ykrKeL[e];return s===void 0?(o=dn.vGSHGD(o),dn.ykrKeL[e]=o):o=s,o}var XS=[z(37),z(84),z(100),z(83),z(39),"",z(71),z(55),z(1),z(47),z(10),z(70),z(56),z(46),z(92),z(2),z(61),z(24),z(82),z(51),z(79),z(88),z(58),z(30),z(65),z(73),z(27),z(59),z(86)][z(33)](`
247
+ `);function eI(e,t){let n=z;return[n(4),e[n(50)]()||n(5),"",n(66),t[n(50)]()][n(33)](`
248
+ `)}async function Jg(e,t,n,o){let i=z,r=await e[i(45)](i(69),{system:XS,user:eI(t,n),tool:{name:i(44),description:i(22),inputSchema:$g},...o?{signal:o}:{}});return{delta:ss(r[i(49)]),raw:JSON[i(38)](r[i(49)])}}var tI=new Set([z(60),z(40),z(99)]),_i=e=>typeof e===z(78)&&e!==null&&!Array[z(13)](e),eo=e=>typeof e===z(9)?e[z(50)]():"";function Ua(e,t){let n=z,o=eo(e);if(!o)throw new Ve(t+n(36));return o}function nI(e,t){let n=z;if(!_i(e))throw new Ve(t+n(31));let o=Ua(e[n(32)],t+n(90));if(o!=="\u5E38\u6001")throw new Ve(t+n(29));return{name:o,description:Ua(e[n(15)],t+n(93))}}var Ve=class extends Error{[z(12)]=z(34);constructor(t){let n=z;super(t),this[n(32)]=n(0)}};function oI(e){let t=z,n="",o=!1;for(let i=0;i<e[t(28)];i++){let r=e[i];if(!o)if(t(48)!==t(67)){n+=r,r==='"'&&(o=!0);continue}else throw new _0x293dd1(_0x17bbe5+t(89)+(_0x24ef46 instanceof _0x59e65f?_0x136fee[t(20)]:_0x3dfec6(_0x4eb04e)));if(r==="\\"&&i+1<e[t(28)]){n+=r+e[i+1],i++;continue}if(r==='"'){let s=i+1;for(;s<e[t(28)]&&/\s/[t(77)](e[s]);)s++;let c=s<e[t(28)]?e[s]:"";if(c===""||c===","||c==="}"||c==="]"||c===":")if(t(35)===t(35))n+=r,o=!1;else return[t(4),_0x49903e[t(50)]()||t(5),"",t(66),_0x1df459[t(50)]()][t(33)](`
249
+ `);else n+='\\"';continue}n+=r}return n}function iI(e,t){let n=z,o=r=>JSON[n(101)](r),i;try{i=o(e)}catch(r){let s=oI(e);if(s===e)throw new Ve(t+n(89)+(r instanceof Error?r[n(20)]:String(r)));try{i=o(s)}catch(c){throw new Ve(t+n(26)+(c instanceof Error?c[n(20)]:String(c)))}}if(!Array[n(13)](i))if(n(6)===n(54))_0x291b73=_0x1aa471(_0x238c2b);else throw new Ve(t+n(91)+typeof i);return i}function yi(e,t){let n=z;if(e==null)return[];if(Array[n(13)](e))return e;if(typeof e===n(9)){let o=e[n(50)]();return o?iI(o,t):[]}throw new Ve(t+n(19)+typeof e)}var rI=/[((]([^))]*)[))]?/;function jp(){let e=["u2vYAwfSrgvSDgftAgfWzuvYCM9Y","icdcTYbHBgLHC2vZid0G6l+z5Q616yEm6k+L5A6E5l2t55QekIRMIydMNiNLHBBKU5BLJ6VMS5uQkU+8JoMaKos4QUwnLEwiL++8IoE6R+wqJE+8JowiQ+w4PUoaJU+8Iow/G++8IEoaJ+oaJU+8MUoaJ+oaJU+8JoMTGUIVREoaJ+I/MEEXU+wVUEEzVs/MG4xNU6RMOiFORRdVViNVVjRLIkVLKi3JGihOR5hLKi3JGihLIy3KUjBLKi3JGihNN63LKi0V5ywO5zcn44cb6iUX5PAh5y6F5zcn77YmkIRLSktLHBBLR7NNMB3OR7tOR53KURRLNkJMRApMLOFPH4ZNMOtLHPNMS5uQkUoaGUATO+AwH+IVToIVNEs6UUwgMEoaJUs8IUAwH8k35BId6Bkb5ywl5PAV44cp6icm5l2GignHBM9UAwnHBcdMMk/JGi7LPkFNIzVJGi/IHPiG5OQk44co5lYk5PAhWRFLUipPSOhLHyVMLQ/JGi/MLl7OV5SGywXPyxnLC++8M+wgMEoaJUwKP+MQQooaJ+IaJcbJyw5VBMLJywWG5PIV44co5AsN6AQO5As044cp4OAsigfSAwfZzxmG5Ps+44co5AsN6AQO44cp44cc57o757UF6z2GigfSAwfZzxmG5OQk5Q2J5PAh6yEm55Qe6k+06k+D5lQ6l+ENSowrVow9KUwiSos9OoI/MEs4QUwUNUs9K++8JcOQywXPyxnLCYdMVi/KUOBLSlhKVjRMLRdPGkdPH43LPi3PRlZLVBeQkUoaGG","kIPTzxjNzxmG4Ocu4OcuioACRoAUTEwgKUwhUUs4Gos4QUENSowrVo+8JowfTUwUNUAyR+AFKos4QUoaKow3SUEFPEIUVUwUMUoaKEMhJow3SUEzU+IUSowUNUs9K+EAHowiQ+wqJE+8IowWMUACQUEzU+IUSoI/H+I/MEs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UywXPyxnLCW","DgPUuMy","C3vIrxzLBNrZ","C3vTBwfYEq","C2XPy2u","ChjVCa","kIRJGjdMNkZMRRxMRApMLOFJGjhLJ6/OG73LJixLKkVOI6xLUBlPM4yQkU+8IoAVJ+MBHUs7PsbGiYbLCf9otK5Giow8GowKTo+8IE+8M+AkIUwUG+s7Row9K+s9NoI/NUE7REAoQoI/M+EAHos4GoAUTEAvTos9K+wKHoEqHU+8JoI3QoMBHUAYV+EuQowqJos4GcbJyw5VBMLJywWG5zcn5A2x44cc","CgfYC2u","C3bSAxq","Bg9VAW"];return jp=function(){return e},jp()}function zp(e){let t=z,n=eo(e),o=rI[t(14)](n);if(!o)return{name:n,aliases:[]};let i=n[t(98)](0,o[t(64)])[t(50)]();if(!i)return{name:n,aliases:[]};let r=(o[1]??"")[t(102)](/[//,,、;;]/)[t(63)](s=>s[t(50)]())[t(18)](Boolean);return{name:i,aliases:r}}var wi=e=>zp(eo(e))[z(32)];function sI(e){let t=z;if(_i(e))return e;if(typeof e===t(9))if(t(74)!==t(72)){let n=e[t(50)]();if(!n)return null;let o;try{t(41)!==t(8)?o=JSON[t(101)](n):_0x2b8a69+='\\"'}catch(i){throw t(23)!==t(23)?new _0x35d905(t(21)+typeof _0x315295):new Ve(t(53)+(i instanceof Error?i[t(20)]:String(i)))}if(!_i(o)){if(t(3)===t(3))throw new Ve(t(21)+typeof o);{let i=_0x2bdcc7(_0x2ac405);if(i===_0x1e5cf5)throw new _0x4316f0(_0x174809+t(89)+(_0x4121a6 instanceof _0x360b19?_0x4fe8c8[t(20)]:_0x4a58de(_0x51367b)));try{_0x35ac52=_0x593204(i)}catch(r){throw new _0x445300(_0x1d355a+t(26)+(r instanceof _0xcc0770?r[t(20)]:_0x4eee3d(r)))}}}return o}else _0x2ddf79+=_0x1d0308,_0x1ed397=!1;return null}function ss(e){let t=z,n=Eg(),o=sI(e);if(!o)return n;for(let i of yi(o[t(25)],t(25))){if(!_i(i))continue;let r=eo(i[t(52)]),{name:s,aliases:c}=zp(eo(i[t(32)]));if(!tI[t(62)](r)||!s)continue;let a=Ua(i[t(15)],t(81)+s+t(93)),d=nI(i[t(75)],t(81)+s+t(43)),p=[...c];for(let f of yi(i[t(16)],t(68))){let{name:u,aliases:m}=zp(eo(f));u&&p[t(76)](u),p[t(76)](...m)}let l=[...new Set(p[t(18)](f=>f&&f!==s))];n[t(25)][t(76)]({name:s,kind:r,description:a,aliases:l,defaultLook:d})}for(let i of yi(o[t(57)],t(57))){if(!_i(i))continue;let r=wi(i[t(11)]),s=wi(i[t(80)]);r&&s&&r!==s&&n[t(57)][t(76)]({from:r,into:s})}for(let i of yi(o[t(42)],t(42))){if(t(95)!==t(95))throw new _0x2df008(_0x519dc7+t(26)+(_0x40bcf4 instanceof _0x3611af?_0x4f83a8[t(20)]:_0x281cd0(_0x1f7db9)));{if(!_i(i))continue;let r=wi(i[t(17)]),s=wi(i[t(32)]);if(!r||!s)continue;let c=[s,...yi(i[t(16)],t(94))[t(63)](wi)[t(18)](Boolean)];n[t(42)][t(76)]({entity:r,names:c,description:Ua(i[t(15)],t(7)+r+"."+s+t(93))})}}for(let i of yi(o[t(85)],t(85))){if(!_i(i))continue;let r=eo(i[t(87)]),s=wi(i[t(17)]),c=wi(i[t(103)]);r&&s&&c&&n[t(85)][t(76)]({scene:r,entity:s,look:c})}return n[t(96)]=yi(o[t(96)],t(96))[t(63)](eo)[t(18)](Boolean),n[t(97)]=eo(o[t(97)]),n}var Ze=pn,aI=[Ze(1),Ze(29),Ze(18),Ze(32),Ze(0),Ze(7),Ze(15),Ze(8),Ze(3)][Ze(21)](`
250
+ `);function cI(e,t){let n=Ze;return[n(13),e[n(27)]()||n(19),"",n(4),t[n(14)](o=>"- "+o)[n(21)](`
250
251
  `)][n(21)](`
251
- `)}async function Gg(e,t,n,o){let i=Ze,r=await e[i(24)](i(26),{system:sI,user:aI(t,n),tool:{name:i(11),description:i(12),inputSchema:$g},...o?{signal:o}:{}});return{delta:zp(r[i(5)],n),raw:JSON[i(30)](r[i(5)])}}var La=e=>e[Ze(23)](Ze(6))[Ze(31)](/\s+/g," ")[Ze(27)]();function zp(e,t=[]){let n=Ze,o=rs(e),i=new Set;for(let s of o[n(22)])i[n(9)](La(s[n(33)]));for(let s of o[n(25)]){i[n(9)](La(s[n(10)]));for(let c of s[n(28)])i[n(9)](La(c))}let r=t[n(20)](s=>!i[n(2)](La(s)));if(r[n(17)])throw new Ve(n(16)+r[n(21)]("\u3001"));return o}function pn(e,t){e=e-0;let n=Kp(),o=n[e];if(pn.brkHeO===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,g=0;u=c.charAt(g++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};pn.xoIkcy=i,pn.GcFqUp={},pn.brkHeO=!0}let r=n[0];pn.pyAYZq!==r&&(pn.GcFqUp={},pn.pyAYZq=r);let s=pn.GcFqUp[e];return s===void 0?(o=pn.xoIkcy(o),pn.GcFqUp[e]=o):o=s,o}function Kp(){let e=["5PAW5lQ654MP55QeignHBM9UAwnHBcbUyw1LioEBToAoPEs9V+EuQooaKow+HEw9KUs4GowqJEwTL+oaKEMhJoEAHowoN+AwH+wNK+wqJEAlVowgME+8M+wKLUIVREwNK+wqJEs4JEE/U+IVKEoaGEs4JEMFS+IVKEoaGEs4JEAuUEAiKos4REAwH+wqJEoaGG","5l2G5PIV5yMN5PYS5A6E5l2t5B2s5lIa5l+U5Asn5zMO44cc44cq5BEY55+L6k6+5A6A44cr5PIV5BEY5BU656Ul55Qe5A6E5l2t55M76k6W77YiCMvNAxn0zxlVViNJGilKUiVPNAlJGjdLVOxLVzlKUidLKi3LRzFJGjhMMk/MRApMLOFPH4ZLH7RNJRdJGihKVy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o+8Jos5N+s4JEIMGsbTzxjNzsdPLjNKURRJGii","BMfTzs1MAxGGzgLKig5VDcbJB3zLCJOG","BgvUz3rO","icdcTYaQkUAyRYOQ77Yi5A2x6z2I5y+y5l2t5AAciowKP+MQQd3LPkFPQQJLPltJGihOI4/OI6xPM6O96iUL6zUQ77YB5OIw5yMN5Oofl+I6Q+s7VEIdVEEHRUwUMUAyR+wqJos4Gos4QU+8JowMGUwjJEs4LUwqJs/LJjBLKi0V5ywO5zcn55+T5zcn77Yj4OAsioAuVUI/MYbGBwvYz2vZyo+8MNTMCM9ToIdOV5NKUkRLKi3LRzCSigLUDg86iow3SUEzU+IUSowUNUs9K+EAHcbJyw5VBMLJywX944cc","77Yi56M677Yj","zMLSDgvY","AM9PBG","BwvYz2vZ","BM9YBwfSAxPL","z2vUzxjHDgvuB29S","BMv3rw50AxrPzxm","Aw5Nzxn0lM5HBwuTzML4","DhjPBq","ywXPyxnLCW","5A+5kIRMR4/KUidKUkOQkUw+HEw9KUs4GowqJEwTL++8JowiPoAwREwUG+AyR+s4JEAyRYbYzwDPC3rLCIdPH4ZMN5dKUkRLT7lNMBVORRdLRP7KVzpNMOtLJ6BKUidNP43LJ6VMS5xVVjO","C3rYAw5NAwz5","CMvWBgfJzq","icdcTYaQkUs4JEAyRYOQ77Yi5A6d56gU5A6E5PIVihjLz2LZDgvYioMhJos7JUAYOEEzU+IUSoI/H+EAHos4Gos4QUAwSowUNUs9K++8IEkgKIdMLl7OV5SGyg5LD0vUDgL0AwvZyo+8MNTRAw5KlcbUyw1LkoE6RYbJyw5VBMLJywWPlcbKzxnJCMLWDgLVBIJKUidLJ6xOR53OUQVKU70PlcbHBgLHC2vZlcbKzwzHDwX0tg9VAZP7BMfTztON5BI45OcbjYWGzgvZy3jPChrPB2465y+V6kEb5Asw6kEcFx3JGii","zNjVBq"];return Kp=function(){return e},Kp()}var It=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),At=e=>Array.isArray(e),cI=5,_i=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),Bg=e=>{try{return JSON.parse(e)}catch{return null}},dI=new Set(["timeout","rate_limited","request_failed","endpoint","empty_response","invalid_response","truncated","serial_delta_shape"]),Hg=e=>!!e&&typeof e=="object"&&"code"in e&&dI.has(String(e.code)),Fg=e=>new Promise(t=>setTimeout(t,e)),sr=(e,t)=>e===t?`episode ${e}`:`episodes ${e}-${t}`;async function Jg(e,t,n,o,i,r){for(let s=1;;s++)try{return await Dg(e,o,i,r)}catch(c){if(Hg(c)&&s<3&&!r?.aborted){await Fg(3e3*s);continue}throw new S(`serial govern failed at ${sr(t,n)}.`,{exitCode:k,errorCode:"INGEST_SERIAL_FAILED",hint:c instanceof Ve?`Model returned a malformed serial delta (${c.message}). Rerun \`scriptctl ingest\` (optionally --force) to retry ${sr(t,n)}.`:`Rerun \`scriptctl ingest\` to resume from ${sr(t,n)} (earlier windows are cached).`,data:{actual:[c instanceof Error?c.message:String(c)]}})}}function Qg(e,t){let n=t.merges.map(o=>o.into).filter(o=>!zt(e,o));if(n.length)throw new Ve(`name-fix merge target is not registered: ${[...new Set(n)].join("\u3001")}`)}async function jg(e,t,n,o,i,r,s){for(let c=1;;c++)try{let a=await Gg(e,o,i,s);return Qg(r,a.delta),a}catch(a){if(Hg(a)&&c<3&&!s?.aborted){await Fg(3e3*c);continue}throw new S(`serial name repair failed at ${sr(t,n)}.`,{exitCode:k,errorCode:"INGEST_SERIAL_NAME_FIX_FAILED",hint:a instanceof Ve?`Model returned an incomplete name repair (${a.message}). Rerun \`scriptctl ingest\` to retry ${sr(t,n)}.`:`Rerun \`scriptctl ingest\` to resume from ${sr(t,n)} (earlier windows are cached).`,data:{actual:[a instanceof Error?a.message:String(a)]}})}}async function Yg(e,t){let n=wg(),o=e.episodes??[],i=0,r=o.map(fI),s=Eg(r.map(_g),t.windowTokens);for(let a=0;a<s.length;a++){let[d,p]=s[a],l=ba(n,p),f=r.slice(d-1,p).join(`
252
+ `)}async function Kg(e,t,n,o){let i=Ze,r=await e[i(24)](i(26),{system:aI,user:cI(t,n),tool:{name:i(11),description:i(12),inputSchema:Bg},...o?{signal:o}:{}});return{delta:Fp(r[i(5)],n),raw:JSON[i(30)](r[i(5)])}}var Pa=e=>e[Ze(23)](Ze(6))[Ze(31)](/\s+/g," ")[Ze(27)]();function Fp(e,t=[]){let n=Ze,o=ss(e),i=new Set;for(let s of o[n(22)])i[n(9)](Pa(s[n(33)]));for(let s of o[n(25)]){i[n(9)](Pa(s[n(10)]));for(let c of s[n(28)])i[n(9)](Pa(c))}let r=t[n(20)](s=>!i[n(2)](Pa(s)));if(r[n(17)])throw new Ve(n(16)+r[n(21)]("\u3001"));return o}function pn(e,t){e=e-0;let n=Hp(),o=n[e];if(pn.brkHeO===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};pn.xoIkcy=i,pn.GcFqUp={},pn.brkHeO=!0}let r=n[0];pn.pyAYZq!==r&&(pn.GcFqUp={},pn.pyAYZq=r);let s=pn.GcFqUp[e];return s===void 0?(o=pn.xoIkcy(o),pn.GcFqUp[e]=o):o=s,o}function Hp(){let e=["5PAW5lQ654MP55QeignHBM9UAwnHBcbUyw1LioEBToAoPEs9V+EuQooaKow+HEw9KUs4GowqJEwTL+oaKEMhJoEAHowoN+AwH+wNK+wqJEAlVowgME+8M+wKLUIVREwNK+wqJEs4JEE/U+IVKEoaGEs4JEMFS+IVKEoaGEs4JEAuUEAiKos4REAwH+wqJEoaGG","5l2G5PIV5yMN5PYS5A6E5l2t5B2s5lIa5l+U5Asn5zMO44cc44cq5BEY55+L6k6+5A6A44cr5PIV5BEY5BU656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V6kEb5Asw6kEcFx3JGii","zNjVBq"];return Hp=function(){return e},Hp()}var It=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),At=e=>Array.isArray(e),dI=5,Ei=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),jg=e=>{try{return JSON.parse(e)}catch{return null}},pI=new Set(["timeout","rate_limited","request_failed","endpoint","empty_response","invalid_response","truncated","serial_delta_shape"]),Yg=e=>!!e&&typeof e=="object"&&"code"in e&&pI.has(String(e.code)),qg=e=>new Promise(t=>setTimeout(t,e)),cr=(e,t)=>e===t?`episode ${e}`:`episodes ${e}-${t}`;async function zg(e,t,n,o,i,r){for(let s=1;;s++)try{return await Jg(e,o,i,r)}catch(c){if(Yg(c)&&s<3&&!r?.aborted){await qg(3e3*s);continue}throw new x(`serial govern failed at ${cr(t,n)}.`,{exitCode:k,errorCode:"INGEST_SERIAL_FAILED",hint:c instanceof Ve?`Model returned a malformed serial delta (${c.message}). Rerun \`scriptctl ingest\` (optionally --force) to retry ${cr(t,n)}.`:`Rerun \`scriptctl ingest\` to resume from ${cr(t,n)} (earlier windows are cached).`,data:{actual:[c instanceof Error?c.message:String(c)]}})}}function Zg(e,t){let n=t.merges.map(o=>o.into).filter(o=>!zt(e,o));if(n.length)throw new Ve(`name-fix merge target is not registered: ${[...new Set(n)].join("\u3001")}`)}async function Hg(e,t,n,o,i,r,s){for(let c=1;;c++)try{let a=await Kg(e,o,i,s);return Zg(r,a.delta),a}catch(a){if(Yg(a)&&c<3&&!s?.aborted){await qg(3e3*c);continue}throw new x(`serial name repair failed at ${cr(t,n)}.`,{exitCode:k,errorCode:"INGEST_SERIAL_NAME_FIX_FAILED",hint:a instanceof Ve?`Model returned an incomplete name repair (${a.message}). Rerun \`scriptctl ingest\` to retry ${cr(t,n)}.`:`Rerun \`scriptctl ingest\` to resume from ${cr(t,n)} (earlier windows are cached).`,data:{actual:[a instanceof Error?a.message:String(a)]}})}}async function Wg(e,t){let n=xg(),o=e.episodes??[],i=0,r=o.map(mI),s=Ig(r.map(Sg),t.windowTokens);for(let a=0;a<s.length;a++){let[d,p]=s[a],l=va(n,p),f=r.slice(d-1,p).join(`
252
253
 
253
254
  `),u=t.sourceRef?`# \u539F\u6587\u8BBE\u5B9A\uFF08\u53C2\u8003\uFF0C\u6765\u81EA\u539F\u7A3F\u5F00\u5934\uFF09
254
255
  ${t.sourceRef}
255
256
 
256
- ${l}`:l,g=Date.now(),h=t.force?void 0:t.checkpoint?.readUpdate(d,p),m,w=!1;if(h!==void 0){let _=Bg(h);try{if(_==null)throw new Ve("checkpoint top-level JSON is unparseable");m=rs(_),w=!0,i++,t.executor.recordReuse("ingest.episode-assets")}catch(x){if(!(x instanceof Ve))throw x;let E=await Jg(t.executor,d,p,u,f,t.signal);m=E.delta,t.checkpoint?.writeStep(d,p,l,E.raw)}}else{let _=await Jg(t.executor,d,p,u,f,t.signal);m=_.delta,t.checkpoint?.writeStep(d,p,l,_.raw)}os(n,m,d,p);let y=pI(o.slice(d-1,p),n);if(y.length){let _=t.force?void 0:t.checkpoint?.readNameFix?.(d,p);if(_!==void 0){let x=Bg(_);try{if(x==null)throw new Ve("name-fix checkpoint top-level JSON is unparseable");let E=zp(x,y);Qg(n,E),os(n,E,d,p),i++,t.executor.recordReuse("ingest.name-fix")}catch(E){if(!(E instanceof Ve))throw E;let A=await jg(t.executor,d,p,ba(n,p),y,n,t.signal);t.checkpoint?.writeNameFix?.(d,p,A.raw),os(n,A.delta,d,p)}}else{let x=await jg(t.executor,d,p,ba(n,p),y,n,t.signal);t.checkpoint?.writeNameFix?.(d,p,x.raw),os(n,x.delta,d,p)}}xg(n);for(let _=Up(n);_;_=Up(n)){let x=_[0].startEp,E=_[_.length-1].endEp,A=t.force?void 0:t.checkpoint?.readArc?.(x,E),b;if(A!==void 0)b=A,i++,t.executor.recordReuse("ingest.arc-summary");else{let C=_.map(R=>`${Mp(R)}\uFF1A${R.line}`).join(`
257
- `);b=await Rg(t.executor,`\u7B2C${x}\u96C6\u2013\u7B2C${E}\u96C6`,C,t.signal),t.checkpoint?.writeArc?.(x,E,b)}Sg(n,b)}t.onWindow?.({startEp:d,endEp:p,ms:Date.now()-g,cached:w,index:a,total:s.length,totalEpisodes:o.length})}return{...mI(e,n),episodes:o.length,reused:i}}function pI(e,t){let n=new Set,o=i=>{if(!i)return;let r=Po(t,i);ct(r)||zt(t,r)||n.add(r)};for(let i of e)for(let r of i.scenes){o(r.location?.name);for(let s of r.actors)o(s.name);for(let s of r.actions)s.speaker&&"name"in s.speaker&&o(s.speaker.name)}return[...n]}var lI={interior:"\u5185",exterior:"\u5916"},uI={day:"\u65E5",night:"\u591C"};function fI(e){let t=[`# ${e.episode_id}${e.title?` ${e.title}`:""}`];for(let n of e.scenes){t.push(`## ${n.scene_id}`);let o=[lI[n.environment?.space??""],uI[n.environment?.time??""]].filter(Boolean).join(" ");o&&t.push(`\u65F6\u7A7A\uFF1A${o}`),n.location?.name&&t.push(`\u5730\u70B9\uFF1A${n.location.name}`),n.actors.length&&t.push(`\u5728\u573A\uFF1A${n.actors.map(i=>i.state?`${i.name}\u3010${i.state}\u3011`:i.name).join("\u3001")}`),n.props.length&&t.push(`\u9053\u5177\uFF1A${n.props.map(i=>i.state?`${i.name}\u3010${i.state}\u3011`:i.name).join("\u3001")}`);for(let i of n.actions){let r=i.speaker?"name"in i.speaker?i.speaker.name:`[${i.speaker.kind}]`:"",s=i.emotion?`\uFF08${i.emotion}\uFF09`:"";i.type==="dialogue"?t.push(`${r}${s}\uFF1A${i.content}`):i.type==="inner_thought"?t.push(`${r}\uFF08\u5FC3\uFF09${s}\uFF1A${i.content}`):i.type==="transition"?t.push(`\u3010\u8F6C\u573A\u3011${i.content}`):t.push(i.content)}}return t.join(`
258
- `)}function mI(e,t){let n=JSON.parse(JSON.stringify(e)),o=new Map;for(let c of n.episodes)for(let a of c.scenes){let d=m=>!!zt(t,m),p=a.location?Po(t,a.location.name):null,l=Kg(a.actors.map(m=>Po(t,m.name)).filter(m=>!ct(m)&&d(m))),f=Kg(a.props.map(m=>Po(t,m.name)).filter(d)),u=[];for(let m of a.actions)if(m.speaker&&"name"in m.speaker){let w=Po(t,m.speaker.name);ct(w)?m.speaker={kind:"group",label:w}:(m.speaker.name=w,d(w)&&u.push(w))}for(let m of u)l.some(w=>_i(w)===_i(m))||l.push(m);let g=new Map;for(let m of t.lookChanges[a.scene_id]??[]){let w=Po(t,m.entity),y=g.get(w)??[];y.includes(m.look)||y.push(m.look),g.set(w,y),o.set(w,m.look)}let h=m=>g.get(m)?.map(w=>({name:m,state:w}))??[zg(t,m,o)];a.location=p&&d(p)?zg(t,p,o):null,a.actors=l.flatMap(h),a.props=f.flatMap(h)}let i=ka(n),r=i.script;yI(r,t),wI(r);let s=Ma(r);return hI(s),_I(s),{doc:s,identityKeys:i.identityKeys}}var gI="\u5E38\u6001";function Kg(e){let t=new Set;return e.filter(n=>{let o=_i(n);return!n||t.has(o)?!1:(t.add(o),!0)})}function zg(e,t,n){let o=zt(e,t),i=n.get(t)??(o?Lp(o):void 0)??gI;return{name:t,state:i}}function hI(e){for(let t of["actors","locations","props"])for(let n of At(e[t])?e[t]:[])if(It(n))for(let o of At(n.states)?n.states:[])It(o)&&o.state_id==="default"&&o.state_name==="default"&&(o.state_name="\u5E38\u6001")}function yI(e,t){for(let[n,o]of[["actors","actor_name"],["locations","location_name"],["props","prop_name"]])for(let i of At(e[n])?e[n]:[]){if(!It(i))continue;let r=zt(t,String(i[o])),s=At(i.states)?i.states:[];if(r){r.description&&(i.description=r.description),r.aliases.length&&(i.aliases=[...new Set([...At(i.aliases)?i.aliases:[],...r.aliases])]);let c=Lp(r),a=c?r.looks.find(d=>_i(d.name)===_i(c))?.description??"":"";for(let d of s){if(!It(d))continue;if(d.state_id==="default"){a&&(d.description=a);continue}let p=r.looks.find(l=>_i(l.name)===_i(String(d.state_name)));p?.description&&(d.description=p.description)}}}}function wI(e){let t=new Map,n=new Map,o=new Map,i=0,r=c=>{typeof c=="string"&&(t.has(c)||t.set(c,i),n.set(c,i),o.set(c,(o.get(c)??0)+1))};for(let c of At(e.episodes)?e.episodes:[])if(!(!It(c)||!At(c.scenes)))for(let a of c.scenes){if(!It(a))continue;let p=[...At(a.actors)?a.actors:[],...At(a.props)?a.props:[],...It(a.location)?[a.location]:[]].filter(It).map(l=>l.actor_id??l.prop_id??l.location_id);for(let l of p)r(l);for(let l of At(a.actions)?a.actions:[])It(l)&&It(l.speaker)&&typeof l.speaker.actor_id=="string"&&r(l.speaker.actor_id),i++}let s=c=>(o.get(c)??0)>=2&&n.get(c)-t.get(c)>=cI;for(let[c,a]of[["actors","actor_id"],["props","prop_id"]])for(let d of At(e[c])?e[c]:[])It(d)&&(d.importance=s(String(d[a]))?"featured":"background");for(let c of At(e.locations)?e.locations:[])It(c)&&(c.importance="featured")}function _I(e){let t=n=>typeof n=="string"?n.trim():"";for(let[n,o]of[["actors","actor_name"],["locations","location_name"],["props","prop_name"]])for(let i of At(e[n])?e[n]:[]){if(!It(i))continue;let r=String(i[o]??""),s=At(i.states)?i.states:[];if(!t(i.description))throw new S(`Ingested asset "${r}" is missing its identity description.`,{exitCode:k,errorCode:"ASSET_DESCRIPTION_MISSING",hint:"Rerun `scriptctl ingest --force` so the serial asset window can regenerate this entity."});for(let c of s){if(!It(c)||t(c.description))continue;let a=String(c.state_name??"");throw new S(`Ingested asset "${r}" has no visual description for look "${a}".`,{exitCode:k,errorCode:c.state_id==="default"?"DEFAULT_LOOK_DESCRIPTION_MISSING":"LOOK_DESCRIPTION_MISSING",hint:"Rerun `scriptctl ingest --force` so the serial asset window can regenerate this look."})}}}var Nn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),eo=e=>Array.isArray(e)?e:[],We=e=>typeof e=="string"?e.trim():"";function Hp(e){return e.normalize("NFKC").toLowerCase().replace(/[\p{White_Space}\p{P}\p{S}]+/gu,"")}var EI={actor:{list:"actors",id:"actor_id",name:"actor_name"},location:{list:"locations",id:"location_id",name:"location_name"},prop:{list:"props",id:"prop_id",name:"prop_name"}},qg=(e,t,n=8)=>{!t||e.includes(t)||e.length>=n||e.push(t)};function Zg(e){let t=Nn(e)?e:{},n={actor:[],location:[],prop:[]},o=new Map;for(let c of["actor","location","prop"]){let a=EI[c];for(let d of eo(t[a.list])){if(!Nn(d))continue;let p=We(d[a.id]),l=We(d[a.name]);if(!p)continue;let f=[...new Set(eo(d.aliases).map(We).filter(Boolean))],u=new Map,g=[];for(let m of eo(d.states)){if(!Nn(m))continue;let w=We(m.state_id);if(!w)continue;let y=We(m.state_name),_={address:`${p}/${w}`,state_id:w,state_name:y,description:We(m.description),format_key:Hp(y),reference_count:0,episode_count:0,scene_count:0,references:[],frequency_flag:null,episodeIds:new Set,sceneIds:new Set};g.push(_),u.set(w,_)}let h={kind:c,id:p,name:l,aliases:f,description:We(d.description),importance:We(d.importance),format_key:Hp(l),alias_format_keys:f.map(Hp),reference_count:0,episode_count:0,scene_count:0,references:[],states:g,episodeIds:new Set,sceneIds:new Set,stateById:u};n[c].push(h),o.set(p,h)}}let i=c=>{let a=eo(c.state_ids).map(We).filter(Boolean);if(a.length>0)return[...new Set(a)];let d=We(c.state_id);return d?[d]:[]},r=(c,a,d,p,l,f)=>{let u=o.get(a);if(!u||u.kind!==c)return;u.reference_count+=1,u.episodeIds.add(p),u.sceneIds.add(`${p}/${l}`),qg(u.references,f);let g=d.length>0?d:u.stateById.has("default")?["default"]:[];for(let h of g){let m=u.stateById.get(h);m&&(m.reference_count+=1,m.episodeIds.add(p),m.sceneIds.add(`${p}/${l}`),qg(m.references,f))}};for(let c of eo(t.episodes)){if(!Nn(c))continue;let a=We(c.episode_id)||"<episode>";for(let d of eo(c.scenes)){if(!Nn(d))continue;let p=We(d.scene_id)||"<scene>",l=`${a}/${p}`;Nn(d.location)&&r("location",We(d.location.location_id),i(d.location),a,p,`${l}.location`);for(let f of eo(d.actors))Nn(f)&&r("actor",We(f.actor_id),i(f),a,p,`${l}.actors`);for(let f of eo(d.props))Nn(f)&&r("prop",We(f.prop_id),i(f),a,p,`${l}.props`);eo(d.actions).forEach((f,u)=>{if(!Nn(f)||!Nn(f.speaker))return;let g=We(f.speaker.actor_id);g&&r("actor",g,i(f.speaker),a,p,`${l}#${u+1}.speaker`)})}}let s=c=>{c.episode_count=c.episodeIds.size,c.scene_count=c.sceneIds.size;for(let a of c.states)a.episode_count=a.episodeIds.size,a.scene_count=a.sceneIds.size,a.frequency_flag=a.state_id==="default"?null:a.scene_count===0?"unused":a.scene_count===1?"singleton":null;return{kind:c.kind,id:c.id,name:c.name,aliases:c.aliases,description:c.description,importance:c.importance,format_key:c.format_key,alias_format_keys:c.alias_format_keys,reference_count:c.reference_count,episode_count:c.episode_count,scene_count:c.scene_count,references:c.references,states:c.states.map(a=>({address:a.address,state_id:a.state_id,state_name:a.state_name,description:a.description,format_key:a.format_key,reference_count:a.reference_count,episode_count:a.episode_count,scene_count:a.scene_count,references:a.references,frequency_flag:a.frequency_flag}))}};return{title:We(t.title),actors:n.actor.map(s),locations:n.location.map(s),props:n.prop.map(s)}}var G=un,Xg=["id",G(38),G(13),G(90),G(40),G(34),G(6),G(82),G(35),G(62)];function Yp(){let e=["yxnZzxrFAwrZ","DgL0Bgv8","5l6l5AAc44co5P6x5PYj57kU44cp5zkm44co5P6xioACIEEYRUoaJ+wpQUAyR+AGVow8J+s4JEwqJo+8Jos9HUs4JEIdVEwpQUAmIEwqJEENSoEBUos8Vow6PUwqIow5TUoaGUw/HEMHU+E7VowqIos6UUEjQEwfS+EZU+oaGEwjP+AdHEI6Q+s7VEoaGEwKLUIYJoApJ+I/SooaGEIHJos4UUI9QoI/UEoaGEwVUEEzVEw9KUwXNUoaGEwhUUEoSos9JEE9RUwsJoI3QoMBHUI/NUE7REAaP+wiPoAwREoaGUwNK+wqJEEBUos8VooaGEI6Q+s7VEEBUoI/KEAiLUE7J+w4UowqJoAHHUEAHos4JEwqJos6UUEjQEE7NEs4JEIdVEIVR+wqIooaGG","zxbPC29Kzv9JB3vUDa","CMvMzxjLBMnLCW","yw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W54k55OIw5zcm5lIa5lU25yw35l2t6ygt5yw35PIV5zcM5zUG5zcn56EW44cb5yMn5zco57Ya44cb5B2s5BgE5O+p6l+W44cb566a56EW44cb566a57Mb5l2t44cb6l2S5B2v5BEU5BYc5OIw6kEc5A+F6kEs5BQM5lIn5zcm6icm6yEn5Asn55M76k6W44cc5yY65yIg5zcm5lIa5zYW54k555Qe5lIn5zcm5zcn56EW5lIo5zcm5lIa5BU6562r5lIT55Qe5lIn5zcm54US56Ul56M66zE077Ym5lMF5yY65yIg5zcm5lIa5lU25yw35l2t6ygt5yw35lIo5zcm57g75l2g5A6E6zMf5lIn5zcm55Qe5AsA5lU26ygt5yw344cc","yxnZzxqGyxvKAxqGCMvZCg9UC2uGBxvZDcbIzsbHiePtt04GB2jQzwn0","CMvJB21Tzw5KyxrPB24","AgLNAa","zw1PDf9HC3nLDf9HDwrPDa","Bg93","ywn0Aw9U","C3rHDgvFAwrZ","zMLSDgvY","qvntrvrFqvvesvrFu05bufnit1rFvJe","zM9YBwf0x2TLEsdLJ6RMIPJLJ6dNQBRNMB3JGihMOiFNGRNJGihLPkFLSi/LHPNJGihLHAJLJyROP5lNRyNMOlZLVi/LT67LVilVViZMMk/LJ6ZLM57OR4hMJA7OGiZKUi3MMk/LKiZKUidLRP7KVzpNMOtMNidNU4JNU5pORRRJGii","AxnbCNjHEq","zxbPC29Kzxm","zgvZy3jPChrPB24","CMvWBgfJzq","BwvKAxvT","BMfTzq","u19dt0Xvtu5tFa","CMvMCW","5l2G5Q2J5zYO5A+55lIa6yoO5BEY57Up5A6m5OIq6kEJ5P6q55Qe5A6m5Pw05yMN5PYS6l+B6kgm5ywO5Bga6lwe5lQN5lIa6iE05OcN5A6H6k6H44cc55UU5Qch5PIV5y+r546W5zcm5lIa5A6E5l2t6kkR6yEn5Asn5BU65QgJ44cb5zcm5lIa56IZ5A6A6kEg6kEj54Q25Ocb6kkR6yEn5Asn5OUg5yIg77Ym5lUL5y+k6zI25Q615Asw6lkm6kkR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6l2S5B2v6k+V5BEU77YB5zcn56EW6zMe5BIM6lQR5lU944cb5Oof57UQ44cb5A+555M95OIw54Q25Ocb6k+05PIo77YB5yMn5PYF6lQR5lU95PYQ5PIo44cb5zco5PYF5y+i5lUL55YF5zcn6yEn5PAW55M76k6W44cc","5zYO5zcm5lIa5lIQ5lQ654MP44cb5zYW54k55OIw6ygt5yw35yAf6yoO77Ym5Qoa5P+L5PIV5zcM5zUG5O+p6l+W5PA55BYp44cb6AkC6iMY57ks5BQM44cb5O6Q6l6E6k+M55wL5OIw6kEc5A+F6kEs5BQM5lIn5zcm77Ym5OQk5zcm5lIa5lIQ56IZ5A6A6kEg6kEj54Q25Ocb5OUg5OIq5AsA5lIQihn0yxrL44cc6yEn54k55ywZ5RoO5zcm5lMjl+I/KEs5IEEkTUAaGEoaGEwqJos4GowLL+ACJEIJHEIIQ+MhJEAwSowrVEwqJEoaGEs7HEwfIEE6V+AiLUwXGoMdQoE7HUIkGUMaOoAiKoEAHow3RUw8GU+8Jos7PEwpIUEkTUAaGEwqJEA3T+wfPEAdHEE7QUoaGEwkQos9NoAiLUwCUUAzR+IVToAyJUoaGG","BwvYz2u","zhvWBgLJyxrLx3n0yxrL","BMfTzxm","vw9trNG","6l+u5zUE5ywO5yMN6lwe5lQN5lIa6iE05OcN5A6H6k6H5y+r546W","Aw1WB3j0yw5Jzq","5lQm44cb6kEg6kEj54Q25Ocb5lIa6iE05OcN","5lIj44cb5l2o6Akr5lIo5BYc5BI454Q25Ocb","DhjPBq"];return Yp=function(){return e},Yp()}var eh=[G(5),G(38),G(40),G(34),G(6),G(11),G(82),G(35),G(62)],xI=[G(41),G(20),G(14)+Xg[G(45)](G(68))+G(61),G(77)+eh[G(45)](G(68))+G(79),G(58),G(32),"",G(75),G(83),G(2),"",G(91),G(84),G(53),"",G(92),G(56),"",G(60),G(22),G(74),"",G(7),G(52),G(9),G(8),G(67),G(43)][G(45)](`
259
- `),SI=new Set([G(80),G(55),G(10),G(86),G(57),G(70),G(65)]),II=new Set([G(85),G(78),G(21)]),AI=new Set([G(25),G(37),G(27)]);function ln(e){let t=G,n=e[t(93)]();return n?n[t(36)](/\\/g,"\\\\")[t(36)](/\r\n?|\n/g,"\\n")[t(36)](/\|/g,"\\|")[t(36)](/;/g,"\\;"):"-"}function Fp(e){let t=G;return e[t(18)]>0?e[t(69)](ln)[t(45)](";"):"-"}function kI(e){let t=G,n=[t(31),t(1)+ln(e[t(42)]),t(46)+Xg[t(45)]("|"),t(39)+eh[t(45)]("|")],o=(i,r)=>{let s=t;n[s(71)]("["+i+":"+r[s(18)]+"]");for(let c of r)if(s(88)!==s(88)){_0x4c5672[s(71)](["A",_0x3346d3(_0x10ff10.id),_0x491f28(_0x2e3418[s(38)]),_0x43a7a6(_0x21c903[s(13)]),_0x59e3d3(_0x33921a[s(90)]),_0x5b4072(_0x3f99c5[s(19)]),_0x1e2ca7(_0x46d1f3[s(3)]),_0x7f6b22(_0xcfe569[s(64)]),_0x376ad7(_0x21b2b4[s(82)]),_0x4dc2db(_0xcd97ac[s(35)]),_0x390c6b(_0x4f88f5[s(4)])][s(45)]("|"));for(let a of _0xef23b5[s(17)])_0x5593cc[s(71)](["S",_0x265c62(a[s(5)]),_0x1ae902(a[s(49)]),_0xabc48e(a[s(19)]),_0x4a1d6b(a[s(3)]),_0x514694(a[s(64)]),a[s(15)]??"-",_0x5aa3d6(a[s(82)]),_0x32748e(a[s(35)]),_0x3d8f50(a[s(4)])][s(45)]("|"))}else{n[s(71)](["A",ln(c.id),ln(c[s(38)]),Fp(c[s(13)]),ln(c[s(90)]),String(c[s(19)]),String(c[s(3)]),String(c[s(64)]),ln(c[s(82)]),ln(c[s(35)]),Fp(c[s(4)])][s(45)]("|"));for(let a of c[s(17)])n[s(71)](["S",ln(a[s(5)]),ln(a[s(49)]),String(a[s(19)]),String(a[s(3)]),String(a[s(64)]),a[s(15)]??"-",ln(a[s(82)]),ln(a[s(35)]),Fp(a[s(4)])][s(45)]("|"))}};return o(t(47),e[t(47)]),o(t(81),e[t(81)]),o(t(54),e[t(54)]),n[t(45)](`
260
- `)}function un(e,t){e=e-0;let n=Yp(),o=n[e];if(un.qyTtRy===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,g=0;u=c.charAt(g++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};un.uxwRFZ=i,un.OXUPnC={},un.qyTtRy=!0}let r=n[0];un.TDHWfX!==r&&(un.OXUPnC={},un.TDHWfX=r);let s=un.OXUPnC[e];return s===void 0?(o=un.uxwRFZ(o),un.OXUPnC[e]=o):o=s,o}var Wg=e=>typeof e===G(48)&&e!==null&&!Array[G(33)](e),th=e=>Array[G(33)](e)?e:[],Ei=e=>typeof e===G(63)?e[G(93)]():"",Qp=e=>[...new Set(th(e)[G(69)](Ei)[G(30)](Boolean))];function bI(e,t){let n=G;if(!Wg(e))throw new Error(n(23));let o=new Set([...t[n(47)],...t[n(81)],...t[n(54)]][n(69)](s=>s.id)),i=new Set([...t[n(47)],...t[n(81)],...t[n(54)]][n(59)](s=>s[n(17)][n(69)](c=>c[n(5)]))),r=[];for(let s of th(e[n(73)])){if(!Wg(s))continue;let c=Ei(s[n(50)]),a=Ei(s[n(28)]),d=Ei(s[n(76)]);if(!SI[n(44)](c)||!II[n(44)](a)||!AI[n(44)](d))continue;let p=Qp(s[n(0)])[n(30)](g=>o[n(44)](g)),l=Qp(s[n(29)])[n(30)](g=>i[n(44)](g));if(p[n(18)]===0&&l[n(18)]===0)continue;let f=Ei(s[n(51)]),u=f&&(o[n(44)](f)||i[n(44)](f))?f:null;r[n(71)]({type:c,asset_ids:p,state_ids:l,names:Qp(s[n(87)]),evidence:Ei(s[n(16)]),recommendation:Ei(s[n(24)]),suggested_survivor:u,action:a,confidence:d})}return r}async function nh(e,t,n){let o=G,i=await e[o(12)](o(66),{system:xI,user:kI(t),tool:{name:o(26),description:o(89),inputSchema:Ug},...n?{signal:n}:{}});return bI(i[o(72)],t)}var oh="1",OI=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.audit_version===oh&&n.script_hash===t&&n.summary!==null&&typeof n.summary=="object"&&Array.isArray(n.issues)};function vI(e,t){return{audit_version:oh,script_hash:e,created_at:new Date().toISOString(),summary:{issues:t.length,high:t.filter(n=>n.confidence==="high").length,medium:t.filter(n=>n.confidence==="medium").length,low:t.filter(n=>n.confidence==="low").length},issues:t}}async function qp(e,t,n){let o=Be(e),i=Zg(e),r=await nh(t,i,n);return vI(o,r)}async function RI(e){let t=Be(e.script);if(!e.force&&e.exists())try{let o=e.read();if(OI(o,t))return e.executor.recordReuse("ingest.asset-audit"),{report:o,reused:!0}}catch{}let n=await qp(e.script,e.executor,e.signal);return e.write(n),{report:n,reused:!1}}async function ih(e,t,n,o={}){return RI({script:t,executor:n,read:()=>e.readJson("asset-audit.json"),write:i=>e.writeJson("asset-audit.json",i),exists:()=>e.has("asset-audit.json"),...o.force?{force:!0}:{},...o.signal?{signal:o.signal}:{}})}var MI={duplicate_actor:"duplicate actor",duplicate_location:"duplicate location",duplicate_prop:"duplicate prop",duplicate_state:"duplicate state",suspicious_singleton_state:"suspicious singleton state",unused_state:"unused state",needs_human_review:"asset needs human review"};function Zp(e){let t=[...e.asset_ids,...e.state_ids].join(", ")||"<unknown>",n=e.evidence||e.recommendation||"review the referenced assets";return`${MI[e.type]} [${t}]: ${n}`}function rh(e){return e.issues.map(t=>({code:`asset_audit_${t.type}`,path:"$",message:`${Zp(t)}; action=${t.action}; confidence=${t.confidence}`}))}var ar=class{constructor(t,n=()=>Date.now()){this.flush=t;this.now=n;this.t={startedMs:this.now(),endedMs:null,phases:[],serial:null},this.flush(this.t)}flush;now;t;phaseStart(t){this.t.phases.push({name:t,startedMs:this.now(),endedMs:null}),this.flush(this.t)}phaseEnd(t){for(let n=this.t.phases.length-1;n>=0;n--){let o=this.t.phases[n];if(o.name===t&&o.endedMs===null){o.endedMs=this.now(),this.flush(this.t);return}}}serialStart(t,n){this.t.serial={totalWindows:t,totalEpisodes:n,windows:[]},this.flush(this.t)}windowDone(t,n,o,i){this.t.serial||(this.t.serial={totalWindows:0,totalEpisodes:0,windows:[]}),this.t.serial.windows.push({start:t,end:n,ms:o,cached:i}),this.flush(this.t)}finish(){this.t.endedMs=this.now(),this.flush(this.t)}};function sh(e,t){let n=(e.endedMs??t)-e.startedMs,o=e.phases.map(r=>({name:r.name,ms:(r.endedMs??t)-r.startedMs,running:r.endedMs===null})),i=null;if(e.serial){let r=e.serial.windows,s=r.filter(p=>!p.cached),c=s.length?s.reduce((p,l)=>p+l.ms,0)/s.length:null,a=r.reduce((p,l)=>p+(l.end-l.start+1),0),d=Math.max(0,e.serial.totalWindows-r.length);i={doneWindows:r.length,totalWindows:e.serial.totalWindows,doneEpisodes:a,totalEpisodes:e.serial.totalEpisodes,avgWindowMs:c!=null?Math.round(c):null,etaMs:c!=null?Math.round(c*d):null}}return{elapsedMs:n,done:e.endedMs!==null,phases:o,serial:i}}import*as ch from"node:crypto";function Xp(){return{calls:0,succeeded:0,failed:0,reused:0,attempts:0,durationMs:0,inputTokens:0,outputTokens:0,cachedInputTokens:0,cacheCreationTokens:0,totalTokens:0}}function NI(e,t){if(t.status==="reused"){e.reused+=1;return}e.calls+=1,t.status==="succeeded"?e.succeeded+=1:e.failed+=1,e.attempts+=t.attempts,e.durationMs+=t.durationMs,e.inputTokens+=t.inputTokens,e.outputTokens+=t.outputTokens,e.cachedInputTokens+=t.cachedInputTokens,e.cacheCreationTokens+=t.cacheCreationTokens,e.totalTokens=e.inputTokens+e.outputTokens}function Ua(e){let t=Xp();for(let n of e)NI(t,n);return t}var as=e=>`${e.provider}\0${e.protocol}\0${e.model}`;function dh(e){let t=new Map;for(let n of e){let o=as(n),i=t.get(o)??{identity:{provider:n.provider,protocol:n.protocol,model:n.model},profiles:new Set,fingerprints:new Set,records:[]};i.profiles.add(n.profile),i.fingerprints.add(n.fingerprint),i.records.push(n),t.set(o,i)}return[...t.values()].map(n=>({...n.identity,profiles:[...n.profiles].sort(),fingerprints:[...n.fingerprints].sort(),totals:Ua(n.records)})).sort((n,o)=>as(n).localeCompare(as(o)))}function Wp(e){let t=new Map;for(let n of e){let o=t.get(n.task)??[];o.push(n),t.set(n.task,o)}return[...t.entries()].map(([n,o])=>({task:n,totals:Ua(o),byModel:dh(o)})).sort((n,o)=>n.task.localeCompare(o.task))}function ah(e){return dh(e).map(t=>{let n=e.filter(o=>as(o)===as(t));return{...t,byTask:Wp(n).map(({task:o,totals:i})=>({task:o,totals:i}))}})}function LI(e){let t=e.updatedAt,n=new Map;for(let c of e.episodes)n.set(c.episode,c.runs);let o=new Map,i=new Map;for(let[c,a]of n){o.set(c,[]);for(let d of a)for(let p of d.recordIds){let l=i.get(p)??new Set;l.add(c),i.set(p,l)}}for(let c of e.records)for(let a of i.get(c.id)??[])o.get(a).push(c);let r=[...n.entries()].map(([c,a])=>{let d=o.get(c);return{episode:c,totals:Ua(d),byTask:Wp(d),byModel:ah(d),durationMs:a.reduce((p,l)=>p+l.durationMs,0),runs:a}}).sort((c,a)=>c.episode-a.episode),s=Ua(e.records);return{...e,updatedAt:t,totals:s,byTask:Wp(e.records),byModel:ah(e.records),episodes:r,timing:{totalDurationMs:e.runs.reduce((c,a)=>c+a.durationMs,0),modelDurationMs:s.durationMs,episodeDurationMs:r.reduce((c,a)=>c+a.durationMs,0)}}}function UI(e){return{version:2,createdAt:e,updatedAt:e,totals:Xp(),byTask:[],byModel:[],episodes:[],runs:[],records:[],timing:{totalDurationMs:0,modelDurationMs:0,episodeDurationMs:0}}}function ss(e){return new Date(e).toISOString()}var To=class{constructor(t,n,o=()=>Date.now()){this.store=t;this.executor=n;this.now=o;this.startedAtMs=this.now(),this.cursor=n.usageEvents().length;let i=ss(this.startedAtMs);if(this.report=t.has("usage.json")?t.readJson("usage.json"):UI(i),this.report.version!==2)throw new Error("workspace/usage.json uses an incompatible schema; rerun ingest with --force to rebuild the workspace.");for(let r of this.report.runs)r.status==="running"&&(r.status="interrupted",r.endedAt=this.report.updatedAt,r.durationMs=Math.max(0,Date.parse(this.report.updatedAt)-Date.parse(r.startedAt)));this.report.runs.push({id:this.runId,status:"running",startedAt:i,endedAt:null,durationMs:0}),this.write(this.startedAtMs)}store;executor;now;runId=ch.randomUUID();startedAtMs;cursor;report;flush(t){this.write(this.append(t))}recordReusedEpisodes(t,n){if(n.length!==0){for(let o of n){this.executor.recordReuse(t);let i=this.now();this.append({scope:{kind:"episode",episode:o},status:"reused",startedAtMs:i,endedAtMs:i})}this.write(this.now())}}append(t){let n=t.endedAtMs??this.now(),o=t.startedAtMs??n,i=this.executor.usageEvents(),s=i.slice(this.cursor).map(c=>this.toRecord(c,t.scope));if(this.cursor=i.length,this.report.records.push(...s),t.scope.kind==="episode"){let c=t.scope.episode,a=this.report.episodes.find(p=>p.episode===c),d=a?.runs??[];d.push({runId:this.runId,status:t.status??"succeeded",startedAt:ss(o),endedAt:ss(n),durationMs:Math.max(0,n-o),stages:t.stages??{},recordIds:s.map(p=>p.id)}),a||this.report.episodes.push({episode:c,totals:Xp(),byTask:[],byModel:[],durationMs:0,runs:d})}return n}finish(t){let n=this.now();this.executor.usageEvents().length>this.cursor&&this.flush({scope:{kind:"run"},status:t==="succeeded"?"succeeded":"failed",endedAtMs:n});let o=this.report.runs.find(i=>i.id===this.runId);o&&(o.status=t,o.endedAt=ss(n),o.durationMs=Math.max(0,n-this.startedAtMs)),this.write(n)}toRecord(t,n){return{...t,id:`${this.runId}:${t.sequence}`,runId:this.runId,scope:n}}write(t){let n=this.report.runs.find(o=>o.id===this.runId);n?.status==="running"&&(n.durationMs=Math.max(0,t-this.startedAtMs)),this.report.updatedAt=ss(t),this.report=LI(this.report),this.store.writeJson("usage.json",this.report)}};var tl="12",Pa=e=>String(e).padStart(3,"0"),ph=e=>e.map(t=>JSON.stringify(t)).join(`
257
+ ${l}`:l,m=Date.now(),h=t.force?void 0:t.checkpoint?.readUpdate(d,p),g,w=!1;if(h!==void 0){let _=jg(h);try{if(_==null)throw new Ve("checkpoint top-level JSON is unparseable");g=ss(_),w=!0,i++,t.executor.recordReuse("ingest.episode-assets")}catch(S){if(!(S instanceof Ve))throw S;let E=await zg(t.executor,d,p,u,f,t.signal);g=E.delta,t.checkpoint?.writeStep(d,p,l,E.raw)}}else{let _=await zg(t.executor,d,p,u,f,t.signal);g=_.delta,t.checkpoint?.writeStep(d,p,l,_.raw)}is(n,g,d,p);let y=lI(o.slice(d-1,p),n);if(y.length){let _=t.force?void 0:t.checkpoint?.readNameFix?.(d,p);if(_!==void 0){let S=jg(_);try{if(S==null)throw new Ve("name-fix checkpoint top-level JSON is unparseable");let E=Fp(S,y);Zg(n,E),is(n,E,d,p),i++,t.executor.recordReuse("ingest.name-fix")}catch(E){if(!(E instanceof Ve))throw E;let A=await Hg(t.executor,d,p,va(n,p),y,n,t.signal);t.checkpoint?.writeNameFix?.(d,p,A.raw),is(n,A.delta,d,p)}}else{let S=await Hg(t.executor,d,p,va(n,p),y,n,t.signal);t.checkpoint?.writeNameFix?.(d,p,S.raw),is(n,S.delta,d,p)}}Ag(n);for(let _=Cp(n);_;_=Cp(n)){let S=_[0].startEp,E=_[_.length-1].endEp,A=t.force?void 0:t.checkpoint?.readArc?.(S,E),b;if(A!==void 0)b=A,i++,t.executor.recordReuse("ingest.arc-summary");else{let U=_.map(M=>`${Lp(M)}\uFF1A${M.line}`).join(`
258
+ `);b=await Lg(t.executor,`\u7B2C${S}\u96C6\u2013\u7B2C${E}\u96C6`,U,t.signal),t.checkpoint?.writeArc?.(S,E,b)}kg(n,b)}t.onWindow?.({startEp:d,endEp:p,ms:Date.now()-m,cached:w,index:a,total:s.length,totalEpisodes:o.length})}return{...gI(e,n),episodes:o.length,reused:i}}function lI(e,t){let n=new Set,o=i=>{if(!i)return;let r=Po(t,i);ct(r)||zt(t,r)||n.add(r)};for(let i of e)for(let r of i.scenes){o(r.location?.name);for(let s of r.actors)o(s.name);for(let s of r.actions)s.speaker&&"name"in s.speaker&&o(s.speaker.name)}return[...n]}var uI={interior:"\u5185",exterior:"\u5916"},fI={day:"\u65E5",night:"\u591C"};function mI(e){let t=[`# ${e.episode_id}${e.title?` ${e.title}`:""}`];for(let n of e.scenes){t.push(`## ${n.scene_id}`);let o=[uI[n.environment?.space??""],fI[n.environment?.time??""]].filter(Boolean).join(" ");o&&t.push(`\u65F6\u7A7A\uFF1A${o}`),n.location?.name&&t.push(`\u5730\u70B9\uFF1A${n.location.name}`),n.actors.length&&t.push(`\u5728\u573A\uFF1A${n.actors.map(i=>i.state?`${i.name}\u3010${i.state}\u3011`:i.name).join("\u3001")}`),n.props.length&&t.push(`\u9053\u5177\uFF1A${n.props.map(i=>i.state?`${i.name}\u3010${i.state}\u3011`:i.name).join("\u3001")}`);for(let i of n.actions){let r=i.speaker?"name"in i.speaker?i.speaker.name:`[${i.speaker.kind}]`:"",s=i.emotion?`\uFF08${i.emotion}\uFF09`:"";i.type==="dialogue"?t.push(`${r}${s}\uFF1A${i.content}`):i.type==="inner_thought"?t.push(`${r}\uFF08\u5FC3\uFF09${s}\uFF1A${i.content}`):i.type==="transition"?t.push(`\u3010\u8F6C\u573A\u3011${i.content}`):t.push(i.content)}}return t.join(`
259
+ `)}function gI(e,t){let n=JSON.parse(JSON.stringify(e)),o=new Map;for(let c of n.episodes)for(let a of c.scenes){let d=g=>!!zt(t,g),p=a.location?Po(t,a.location.name):null,l=Fg(a.actors.map(g=>Po(t,g.name)).filter(g=>!ct(g)&&d(g))),f=Fg(a.props.map(g=>Po(t,g.name)).filter(d)),u=[];for(let g of a.actions)if(g.speaker&&"name"in g.speaker){let w=Po(t,g.speaker.name);ct(w)?g.speaker={kind:"group",label:w}:(g.speaker.name=w,d(w)&&u.push(w))}for(let g of u)l.some(w=>Ei(w)===Ei(g))||l.push(g);let m=new Map;for(let g of t.lookChanges[a.scene_id]??[]){let w=Po(t,g.entity),y=m.get(w)??[];y.includes(g.look)||y.push(g.look),m.set(w,y),o.set(w,g.look)}let h=g=>m.get(g)?.map(w=>({name:g,state:w}))??[Qg(t,g,o)];a.location=p&&d(p)?Qg(t,p,o):null,a.actors=l.flatMap(h),a.props=f.flatMap(h)}let i=Oa(n),r=i.script;wI(r,t),_I(r);let s=La(r);return yI(s),EI(s),{doc:s,identityKeys:i.identityKeys}}var hI="\u5E38\u6001";function Fg(e){let t=new Set;return e.filter(n=>{let o=Ei(n);return!n||t.has(o)?!1:(t.add(o),!0)})}function Qg(e,t,n){let o=zt(e,t),i=n.get(t)??(o?Pp(o):void 0)??hI;return{name:t,state:i}}function yI(e){for(let t of["actors","locations","props"])for(let n of At(e[t])?e[t]:[])if(It(n))for(let o of At(n.states)?n.states:[])It(o)&&o.state_id==="default"&&o.state_name==="default"&&(o.state_name="\u5E38\u6001")}function wI(e,t){for(let[n,o]of[["actors","actor_name"],["locations","location_name"],["props","prop_name"]])for(let i of At(e[n])?e[n]:[]){if(!It(i))continue;let r=zt(t,String(i[o])),s=At(i.states)?i.states:[];if(r){r.description&&(i.description=r.description),r.aliases.length&&(i.aliases=[...new Set([...At(i.aliases)?i.aliases:[],...r.aliases])]);let c=Pp(r),a=c?r.looks.find(d=>Ei(d.name)===Ei(c))?.description??"":"";for(let d of s){if(!It(d))continue;if(d.state_id==="default"){a&&(d.description=a);continue}let p=r.looks.find(l=>Ei(l.name)===Ei(String(d.state_name)));p?.description&&(d.description=p.description)}}}}function _I(e){let t=new Map,n=new Map,o=new Map,i=0,r=c=>{typeof c=="string"&&(t.has(c)||t.set(c,i),n.set(c,i),o.set(c,(o.get(c)??0)+1))};for(let c of At(e.episodes)?e.episodes:[])if(!(!It(c)||!At(c.scenes)))for(let a of c.scenes){if(!It(a))continue;let p=[...At(a.actors)?a.actors:[],...At(a.props)?a.props:[],...It(a.location)?[a.location]:[]].filter(It).map(l=>l.actor_id??l.prop_id??l.location_id);for(let l of p)r(l);for(let l of At(a.actions)?a.actions:[])It(l)&&It(l.speaker)&&typeof l.speaker.actor_id=="string"&&r(l.speaker.actor_id),i++}let s=c=>(o.get(c)??0)>=2&&n.get(c)-t.get(c)>=dI;for(let[c,a]of[["actors","actor_id"],["props","prop_id"]])for(let d of At(e[c])?e[c]:[])It(d)&&(d.importance=s(String(d[a]))?"featured":"background");for(let c of At(e.locations)?e.locations:[])It(c)&&(c.importance="featured")}function EI(e){let t=n=>typeof n=="string"?n.trim():"";for(let[n,o]of[["actors","actor_name"],["locations","location_name"],["props","prop_name"]])for(let i of At(e[n])?e[n]:[]){if(!It(i))continue;let r=String(i[o]??""),s=At(i.states)?i.states:[];if(!t(i.description))throw new x(`Ingested asset "${r}" is missing its identity description.`,{exitCode:k,errorCode:"ASSET_DESCRIPTION_MISSING",hint:"Rerun `scriptctl ingest --force` so the serial asset window can regenerate this entity."});for(let c of s){if(!It(c)||t(c.description))continue;let a=String(c.state_name??"");throw new x(`Ingested asset "${r}" has no visual description for look "${a}".`,{exitCode:k,errorCode:c.state_id==="default"?"DEFAULT_LOOK_DESCRIPTION_MISSING":"LOOK_DESCRIPTION_MISSING",hint:"Rerun `scriptctl ingest --force` so the serial asset window can regenerate this look."})}}}var Nn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),to=e=>Array.isArray(e)?e:[],We=e=>typeof e=="string"?e.trim():"";function Qp(e){return e.normalize("NFKC").toLowerCase().replace(/[\p{White_Space}\p{P}\p{S}]+/gu,"")}var xI={actor:{list:"actors",id:"actor_id",name:"actor_name"},location:{list:"locations",id:"location_id",name:"location_name"},prop:{list:"props",id:"prop_id",name:"prop_name"}},Xg=(e,t,n=8)=>{!t||e.includes(t)||e.length>=n||e.push(t)};function eh(e){let t=Nn(e)?e:{},n={actor:[],location:[],prop:[]},o=new Map;for(let c of["actor","location","prop"]){let a=xI[c];for(let d of to(t[a.list])){if(!Nn(d))continue;let p=We(d[a.id]),l=We(d[a.name]);if(!p)continue;let f=[...new Set(to(d.aliases).map(We).filter(Boolean))],u=new Map,m=[];for(let g of to(d.states)){if(!Nn(g))continue;let w=We(g.state_id);if(!w)continue;let y=We(g.state_name),_={address:`${p}/${w}`,state_id:w,state_name:y,description:We(g.description),format_key:Qp(y),reference_count:0,episode_count:0,scene_count:0,references:[],frequency_flag:null,episodeIds:new Set,sceneIds:new Set};m.push(_),u.set(w,_)}let h={kind:c,id:p,name:l,aliases:f,description:We(d.description),importance:We(d.importance),format_key:Qp(l),alias_format_keys:f.map(Qp),reference_count:0,episode_count:0,scene_count:0,references:[],states:m,episodeIds:new Set,sceneIds:new Set,stateById:u};n[c].push(h),o.set(p,h)}}let i=c=>{let a=to(c.state_ids).map(We).filter(Boolean);if(a.length>0)return[...new Set(a)];let d=We(c.state_id);return d?[d]:[]},r=(c,a,d,p,l,f)=>{let u=o.get(a);if(!u||u.kind!==c)return;u.reference_count+=1,u.episodeIds.add(p),u.sceneIds.add(`${p}/${l}`),Xg(u.references,f);let m=d.length>0?d:u.stateById.has("default")?["default"]:[];for(let h of m){let g=u.stateById.get(h);g&&(g.reference_count+=1,g.episodeIds.add(p),g.sceneIds.add(`${p}/${l}`),Xg(g.references,f))}};for(let c of to(t.episodes)){if(!Nn(c))continue;let a=We(c.episode_id)||"<episode>";for(let d of to(c.scenes)){if(!Nn(d))continue;let p=We(d.scene_id)||"<scene>",l=`${a}/${p}`;Nn(d.location)&&r("location",We(d.location.location_id),i(d.location),a,p,`${l}.location`);for(let f of to(d.actors))Nn(f)&&r("actor",We(f.actor_id),i(f),a,p,`${l}.actors`);for(let f of to(d.props))Nn(f)&&r("prop",We(f.prop_id),i(f),a,p,`${l}.props`);to(d.actions).forEach((f,u)=>{if(!Nn(f)||!Nn(f.speaker))return;let m=We(f.speaker.actor_id);m&&r("actor",m,i(f.speaker),a,p,`${l}#${u+1}.speaker`)})}}let s=c=>{c.episode_count=c.episodeIds.size,c.scene_count=c.sceneIds.size;for(let a of c.states)a.episode_count=a.episodeIds.size,a.scene_count=a.sceneIds.size,a.frequency_flag=a.state_id==="default"?null:a.scene_count===0?"unused":a.scene_count===1?"singleton":null;return{kind:c.kind,id:c.id,name:c.name,aliases:c.aliases,description:c.description,importance:c.importance,format_key:c.format_key,alias_format_keys:c.alias_format_keys,reference_count:c.reference_count,episode_count:c.episode_count,scene_count:c.scene_count,references:c.references,states:c.states.map(a=>({address:a.address,state_id:a.state_id,state_name:a.state_name,description:a.description,format_key:a.format_key,reference_count:a.reference_count,episode_count:a.episode_count,scene_count:a.scene_count,references:a.references,frequency_flag:a.frequency_flag}))}};return{title:We(t.title),actors:n.actor.map(s),locations:n.location.map(s),props:n.prop.map(s)}}var D=un,nh=["id",D(38),D(13),D(90),D(40),D(34),D(6),D(82),D(35),D(62)];function Zp(){let e=["yxnZzxrFAwrZ","DgL0Bgv8","5l6l5AAc44co5P6x5PYj57kU44cp5zkm44co5P6xioACIEEYRUoaJ+wpQUAyR+AGVow8J+s4JEwqJo+8Jos9HUs4JEIdVEwpQUAmIEwqJEENSoEBUos8Vow6PUwqIow5TUoaGUw/HEMHU+E7VowqIos6UUEjQEwfS+EZU+oaGEwjP+AdHEI6Q+s7VEoaGEwKLUIYJoApJ+I/SooaGEIHJos4UUI9QoI/UEoaGEwVUEEzVEw9KUwXNUoaGEwhUUEoSos9JEE9RUwsJoI3QoMBHUI/NUE7REAaP+wiPoAwREoaGUwNK+wqJEEBUos8VooaGEI6Q+s7VEEBUoI/KEAiLUE7J+w4UowqJoAHHUEAHos4JEwqJos6UUEjQEE7NEs4JEIdVEIVR+wqIooaGG","zxbPC29Kzv9JB3vUDa","CMvMzxjLBMnLCW","ywrKCMvZCW","C2nLBMvZ","5lQu44cb5A6H6k6H6l6555wm5lIo6l6t5yE6","6lcd55sOigvTAxrFyxnZzxrFyxvKAxqG5BEL5yw36l+u5zUE5A6H6k6H57Ut5P6C44cc","5Q+p5lIQ6zEU6Aky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PAW55M76k6W44cc","5zYO5zcm5lIa5lIQ5lQ654MP44cb5zYW54k55OIw6ygt5yw35yAf6yoO77Ym5Qoa5P+L5PIV5zcM5zUG5O+p6l+W5PA55BYp44cb6AkC6iMY57ks5BQM44cb5O6Q6l6E6k+M55wL5OIw6kEc5A+F6kEs5BQM5lIn5zcm77Ym5OQk5zcm5lIa5lIQ56IZ5A6A6kEg6kEj54Q25Ocb5OUg5OIq5AsA5lIQihn0yxrL44cc6yEn54k55ywZ5RoO5zcm5lMjl+I/KEs5IEEkTUAaGEoaGEwqJos4GowLL+ACJEIJHEIIQ+MhJEAwSowrVEwqJEoaGEs7HEwfIEE6V+AiLUwXGoMdQoE7HUIkGUMaOoAiKoEAHow3RUw8GU+8Jos7PEwpIUEkTUAaGEwqJEA3T+wfPEAdHEE7QUoaGEwkQos9NoAiLUwCUUAzR+IVToAyJUoaGG","BwvYz2u","zhvWBgLJyxrLx3n0yxrL","BMfTzxm","vw9trNG","6l+u5zUE5ywO5yMN6lwe5lQN5lIa6iE05OcN5A6H6k6H5y+r546W","Aw1WB3j0yw5Jzq","5lQm44cb6kEg6kEj54Q25Ocb5lIa6iE05OcN","5lIj44cb5l2o6Akr5lIo5BYc5BI454Q25Ocb","DhjPBq"];return Zp=function(){return e},Zp()}var oh=[D(5),D(38),D(40),D(34),D(6),D(11),D(82),D(35),D(62)],SI=[D(41),D(20),D(14)+nh[D(45)](D(68))+D(61),D(77)+oh[D(45)](D(68))+D(79),D(58),D(32),"",D(75),D(83),D(2),"",D(91),D(84),D(53),"",D(92),D(56),"",D(60),D(22),D(74),"",D(7),D(52),D(9),D(8),D(67),D(43)][D(45)](`
260
+ `),II=new Set([D(80),D(55),D(10),D(86),D(57),D(70),D(65)]),AI=new Set([D(85),D(78),D(21)]),kI=new Set([D(25),D(37),D(27)]);function ln(e){let t=D,n=e[t(93)]();return n?n[t(36)](/\\/g,"\\\\")[t(36)](/\r\n?|\n/g,"\\n")[t(36)](/\|/g,"\\|")[t(36)](/;/g,"\\;"):"-"}function Yp(e){let t=D;return e[t(18)]>0?e[t(69)](ln)[t(45)](";"):"-"}function bI(e){let t=D,n=[t(31),t(1)+ln(e[t(42)]),t(46)+nh[t(45)]("|"),t(39)+oh[t(45)]("|")],o=(i,r)=>{let s=t;n[s(71)]("["+i+":"+r[s(18)]+"]");for(let c of r)if(s(88)!==s(88)){_0x4c5672[s(71)](["A",_0x3346d3(_0x10ff10.id),_0x491f28(_0x2e3418[s(38)]),_0x43a7a6(_0x21c903[s(13)]),_0x59e3d3(_0x33921a[s(90)]),_0x5b4072(_0x3f99c5[s(19)]),_0x1e2ca7(_0x46d1f3[s(3)]),_0x7f6b22(_0xcfe569[s(64)]),_0x376ad7(_0x21b2b4[s(82)]),_0x4dc2db(_0xcd97ac[s(35)]),_0x390c6b(_0x4f88f5[s(4)])][s(45)]("|"));for(let a of _0xef23b5[s(17)])_0x5593cc[s(71)](["S",_0x265c62(a[s(5)]),_0x1ae902(a[s(49)]),_0xabc48e(a[s(19)]),_0x4a1d6b(a[s(3)]),_0x514694(a[s(64)]),a[s(15)]??"-",_0x5aa3d6(a[s(82)]),_0x32748e(a[s(35)]),_0x3d8f50(a[s(4)])][s(45)]("|"))}else{n[s(71)](["A",ln(c.id),ln(c[s(38)]),Yp(c[s(13)]),ln(c[s(90)]),String(c[s(19)]),String(c[s(3)]),String(c[s(64)]),ln(c[s(82)]),ln(c[s(35)]),Yp(c[s(4)])][s(45)]("|"));for(let a of c[s(17)])n[s(71)](["S",ln(a[s(5)]),ln(a[s(49)]),String(a[s(19)]),String(a[s(3)]),String(a[s(64)]),a[s(15)]??"-",ln(a[s(82)]),ln(a[s(35)]),Yp(a[s(4)])][s(45)]("|"))}};return o(t(47),e[t(47)]),o(t(81),e[t(81)]),o(t(54),e[t(54)]),n[t(45)](`
261
+ `)}function un(e,t){e=e-0;let n=Zp(),o=n[e];if(un.qyTtRy===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};un.uxwRFZ=i,un.OXUPnC={},un.qyTtRy=!0}let r=n[0];un.TDHWfX!==r&&(un.OXUPnC={},un.TDHWfX=r);let s=un.OXUPnC[e];return s===void 0?(o=un.uxwRFZ(o),un.OXUPnC[e]=o):o=s,o}var th=e=>typeof e===D(48)&&e!==null&&!Array[D(33)](e),ih=e=>Array[D(33)](e)?e:[],xi=e=>typeof e===D(63)?e[D(93)]():"",qp=e=>[...new Set(ih(e)[D(69)](xi)[D(30)](Boolean))];function OI(e,t){let n=D;if(!th(e))throw new Error(n(23));let o=new Set([...t[n(47)],...t[n(81)],...t[n(54)]][n(69)](s=>s.id)),i=new Set([...t[n(47)],...t[n(81)],...t[n(54)]][n(59)](s=>s[n(17)][n(69)](c=>c[n(5)]))),r=[];for(let s of ih(e[n(73)])){if(!th(s))continue;let c=xi(s[n(50)]),a=xi(s[n(28)]),d=xi(s[n(76)]);if(!II[n(44)](c)||!AI[n(44)](a)||!kI[n(44)](d))continue;let p=qp(s[n(0)])[n(30)](m=>o[n(44)](m)),l=qp(s[n(29)])[n(30)](m=>i[n(44)](m));if(p[n(18)]===0&&l[n(18)]===0)continue;let f=xi(s[n(51)]),u=f&&(o[n(44)](f)||i[n(44)](f))?f:null;r[n(71)]({type:c,asset_ids:p,state_ids:l,names:qp(s[n(87)]),evidence:xi(s[n(16)]),recommendation:xi(s[n(24)]),suggested_survivor:u,action:a,confidence:d})}return r}async function rh(e,t,n){let o=D,i=await e[o(12)](o(66),{system:SI,user:bI(t),tool:{name:o(26),description:o(89),inputSchema:Tg},...n?{signal:n}:{}});return OI(i[o(72)],t)}var sh="1",vI=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.audit_version===sh&&n.script_hash===t&&n.summary!==null&&typeof n.summary=="object"&&Array.isArray(n.issues)};function RI(e,t){return{audit_version:sh,script_hash:e,created_at:new Date().toISOString(),summary:{issues:t.length,high:t.filter(n=>n.confidence==="high").length,medium:t.filter(n=>n.confidence==="medium").length,low:t.filter(n=>n.confidence==="low").length},issues:t}}async function Wp(e,t,n){let o=Je(e),i=eh(e),r=await rh(t,i,n);return RI(o,r)}async function MI(e){let t=Je(e.script);if(!e.force&&e.exists())try{let o=e.read();if(vI(o,t))return e.executor.recordReuse("ingest.asset-audit"),{report:o,reused:!0}}catch{}let n=await Wp(e.script,e.executor,e.signal);return e.write(n),{report:n,reused:!1}}async function ah(e,t,n,o={}){return MI({script:t,executor:n,read:()=>e.readJson("asset-audit.json"),write:i=>e.writeJson("asset-audit.json",i),exists:()=>e.has("asset-audit.json"),...o.force?{force:!0}:{},...o.signal?{signal:o.signal}:{}})}var NI={duplicate_actor:"duplicate actor",duplicate_location:"duplicate location",duplicate_prop:"duplicate prop",duplicate_state:"duplicate state",suspicious_singleton_state:"suspicious singleton state",unused_state:"unused state",needs_human_review:"asset needs human review"};function Xp(e){let t=[...e.asset_ids,...e.state_ids].join(", ")||"<unknown>",n=e.evidence||e.recommendation||"review the referenced assets";return`${NI[e.type]} [${t}]: ${n}`}function ch(e){return e.issues.map(t=>({code:`asset_audit_${t.type}`,path:"$",message:`${Xp(t)}; action=${t.action}; confidence=${t.confidence}`}))}var dr=class{constructor(t,n=()=>Date.now()){this.flush=t;this.now=n;this.t={startedMs:this.now(),endedMs:null,phases:[],serial:null},this.flush(this.t)}flush;now;t;phaseStart(t){this.t.phases.push({name:t,startedMs:this.now(),endedMs:null}),this.flush(this.t)}phaseEnd(t){for(let n=this.t.phases.length-1;n>=0;n--){let o=this.t.phases[n];if(o.name===t&&o.endedMs===null){o.endedMs=this.now(),this.flush(this.t);return}}}serialStart(t,n){this.t.serial={totalWindows:t,totalEpisodes:n,windows:[]},this.flush(this.t)}windowDone(t,n,o,i){this.t.serial||(this.t.serial={totalWindows:0,totalEpisodes:0,windows:[]}),this.t.serial.windows.push({start:t,end:n,ms:o,cached:i}),this.flush(this.t)}finish(){this.t.endedMs=this.now(),this.flush(this.t)}};function dh(e,t){let n=(e.endedMs??t)-e.startedMs,o=e.phases.map(r=>({name:r.name,ms:(r.endedMs??t)-r.startedMs,running:r.endedMs===null})),i=null;if(e.serial){let r=e.serial.windows,s=r.filter(p=>!p.cached),c=s.length?s.reduce((p,l)=>p+l.ms,0)/s.length:null,a=r.reduce((p,l)=>p+(l.end-l.start+1),0),d=Math.max(0,e.serial.totalWindows-r.length);i={doneWindows:r.length,totalWindows:e.serial.totalWindows,doneEpisodes:a,totalEpisodes:e.serial.totalEpisodes,avgWindowMs:c!=null?Math.round(c):null,etaMs:c!=null?Math.round(c*d):null}}return{elapsedMs:n,done:e.endedMs!==null,phases:o,serial:i}}import*as lh from"node:crypto";function tl(){return{calls:0,succeeded:0,failed:0,reused:0,attempts:0,durationMs:0,inputTokens:0,outputTokens:0,cachedInputTokens:0,cacheCreationTokens:0,totalTokens:0}}function LI(e,t){if(t.status==="reused"){e.reused+=1;return}e.calls+=1,t.status==="succeeded"?e.succeeded+=1:e.failed+=1,e.attempts+=t.attempts,e.durationMs+=t.durationMs,e.inputTokens+=t.inputTokens,e.outputTokens+=t.outputTokens,e.cachedInputTokens+=t.cachedInputTokens,e.cacheCreationTokens+=t.cacheCreationTokens,e.totalTokens=e.inputTokens+e.outputTokens}function Ca(e){let t=tl();for(let n of e)LI(t,n);return t}var cs=e=>`${e.provider}\0${e.protocol}\0${e.model}`;function uh(e){let t=new Map;for(let n of e){let o=cs(n),i=t.get(o)??{identity:{provider:n.provider,protocol:n.protocol,model:n.model},profiles:new Set,fingerprints:new Set,records:[]};i.profiles.add(n.profile),i.fingerprints.add(n.fingerprint),i.records.push(n),t.set(o,i)}return[...t.values()].map(n=>({...n.identity,profiles:[...n.profiles].sort(),fingerprints:[...n.fingerprints].sort(),totals:Ca(n.records)})).sort((n,o)=>cs(n).localeCompare(cs(o)))}function el(e){let t=new Map;for(let n of e){let o=t.get(n.task)??[];o.push(n),t.set(n.task,o)}return[...t.entries()].map(([n,o])=>({task:n,totals:Ca(o),byModel:uh(o)})).sort((n,o)=>n.task.localeCompare(o.task))}function ph(e){return uh(e).map(t=>{let n=e.filter(o=>cs(o)===cs(t));return{...t,byTask:el(n).map(({task:o,totals:i})=>({task:o,totals:i}))}})}function UI(e){let t=e.updatedAt,n=new Map;for(let c of e.episodes)n.set(c.episode,c.runs);let o=new Map,i=new Map;for(let[c,a]of n){o.set(c,[]);for(let d of a)for(let p of d.recordIds){let l=i.get(p)??new Set;l.add(c),i.set(p,l)}}for(let c of e.records)for(let a of i.get(c.id)??[])o.get(a).push(c);let r=[...n.entries()].map(([c,a])=>{let d=o.get(c);return{episode:c,totals:Ca(d),byTask:el(d),byModel:ph(d),durationMs:a.reduce((p,l)=>p+l.durationMs,0),runs:a}}).sort((c,a)=>c.episode-a.episode),s=Ca(e.records);return{...e,updatedAt:t,totals:s,byTask:el(e.records),byModel:ph(e.records),episodes:r,timing:{totalDurationMs:e.runs.reduce((c,a)=>c+a.durationMs,0),modelDurationMs:s.durationMs,episodeDurationMs:r.reduce((c,a)=>c+a.durationMs,0)}}}function PI(e){return{version:2,createdAt:e,updatedAt:e,totals:tl(),byTask:[],byModel:[],episodes:[],runs:[],records:[],timing:{totalDurationMs:0,modelDurationMs:0,episodeDurationMs:0}}}function as(e){return new Date(e).toISOString()}var To=class{constructor(t,n,o=()=>Date.now()){this.store=t;this.executor=n;this.now=o;this.startedAtMs=this.now(),this.cursor=n.usageEvents().length;let i=as(this.startedAtMs);if(this.report=t.has("usage.json")?t.readJson("usage.json"):PI(i),this.report.version!==2)throw new Error("workspace/usage.json uses an incompatible schema; rerun ingest with --force to rebuild the workspace.");for(let r of this.report.runs)r.status==="running"&&(r.status="interrupted",r.endedAt=this.report.updatedAt,r.durationMs=Math.max(0,Date.parse(this.report.updatedAt)-Date.parse(r.startedAt)));this.report.runs.push({id:this.runId,status:"running",startedAt:i,endedAt:null,durationMs:0}),this.write(this.startedAtMs)}store;executor;now;runId=lh.randomUUID();startedAtMs;cursor;report;flush(t){this.write(this.append(t))}recordReusedEpisodes(t,n){if(n.length!==0){for(let o of n){this.executor.recordReuse(t);let i=this.now();this.append({scope:{kind:"episode",episode:o},status:"reused",startedAtMs:i,endedAtMs:i})}this.write(this.now())}}append(t){let n=t.endedAtMs??this.now(),o=t.startedAtMs??n,i=this.executor.usageEvents(),s=i.slice(this.cursor).map(c=>this.toRecord(c,t.scope));if(this.cursor=i.length,this.report.records.push(...s),t.scope.kind==="episode"){let c=t.scope.episode,a=this.report.episodes.find(p=>p.episode===c),d=a?.runs??[];d.push({runId:this.runId,status:t.status??"succeeded",startedAt:as(o),endedAt:as(n),durationMs:Math.max(0,n-o),stages:t.stages??{},recordIds:s.map(p=>p.id)}),a||this.report.episodes.push({episode:c,totals:tl(),byTask:[],byModel:[],durationMs:0,runs:d})}return n}finish(t){let n=this.now();this.executor.usageEvents().length>this.cursor&&this.flush({scope:{kind:"run"},status:t==="succeeded"?"succeeded":"failed",endedAtMs:n});let o=this.report.runs.find(i=>i.id===this.runId);o&&(o.status=t,o.endedAt=as(n),o.durationMs=Math.max(0,n-this.startedAtMs)),this.write(n)}toRecord(t,n){return{...t,id:`${this.runId}:${t.sequence}`,runId:this.runId,scope:n}}write(t){let n=this.report.runs.find(o=>o.id===this.runId);n?.status==="running"&&(n.durationMs=Math.max(0,t-this.startedAtMs)),this.report.updatedAt=as(t),this.report=UI(this.report),this.store.writeJson("usage.json",this.report)}};var ol="12",Ta=e=>String(e).padStart(3,"0"),fh=e=>e.map(t=>JSON.stringify(t)).join(`
261
262
  `)+`
262
- `;function PI(e,t,n){if(e.has("manifest.json")){let o=e.readJson("manifest.json");if(o.source?.sha256&&o.source.sha256!==t)throw new S("This workspace was built from a different source. --force cannot switch sources.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Choose a fresh --workspace-path for the new source.",data:{actual:["workspace source differs from --source-path"]}});if(!n&&o.pipeline_version&&o.pipeline_version!==tl)throw new S("This workspace was created by an older text-ingest pipeline.",{exitCode:k,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Rerun `scriptctl ingest --force` with the same source to rebuild its checkpoints.",data:{actual:[`workspace pipeline ${o.pipeline_version}; current ${tl}`]}})}if(n){for(let o of["pass1","pass2","pass3","pass5","serial"])el.rmSync(e.path(o),{recursive:!0,force:!0});for(let o of["body.json","script.initial.json","script.json","validation.json","asset-audit.json","notes.json","issues.json","provisional_assets.json","usage.json","v4_identity_map.json"])el.rmSync(e.path(o),{force:!0})}}async function lh(e){let t=On(e.sourcePath);if(t.kind!=="text")throw new S("runTextIngest received a non-text source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=await Ea(t.path,t.ext),o=Ee(n),i=new ft(e.workspacePath);i.ensure(),PI(i,o,e.force??!1);let r=new ar(a=>i.writeJson("timings.json",a)),s=new To(i,e.executor),c="failed";try{let a=Date.now(),d=0;if(!e.force&&i.has("pass1/body_start.json"))d=i.readJson("pass1/body_start.json").line??0,e.executor.recordReuse("ingest.body-start");else{let P=await bg(e.executor,n,e.signal);d=P.line,i.writeJson("pass1/body_start.json",P)}let p=n.split(`
263
+ `;function CI(e,t,n){if(e.has("manifest.json")){let o=e.readJson("manifest.json");if(o.source?.sha256&&o.source.sha256!==t)throw new x("This workspace was built from a different source. --force cannot switch sources.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Choose a fresh --workspace-path for the new source.",data:{actual:["workspace source differs from --source-path"]}});if(!n&&o.pipeline_version&&o.pipeline_version!==ol)throw new x("This workspace was created by an older text-ingest pipeline.",{exitCode:k,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Rerun `scriptctl ingest --force` with the same source to rebuild its checkpoints.",data:{actual:[`workspace pipeline ${o.pipeline_version}; current ${ol}`]}})}if(n){for(let o of["pass1","pass2","pass3","pass5","serial"])nl.rmSync(e.path(o),{recursive:!0,force:!0});for(let o of["body.json","script.initial.json","script.json","validation.json","asset-audit.json","notes.json","issues.json","provisional_assets.json","usage.json","v4_identity_map.json"])nl.rmSync(e.path(o),{force:!0})}}async function mh(e){let t=On(e.sourcePath);if(t.kind!=="text")throw new x("runTextIngest received a non-text source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=await Sa(t.path,t.ext),o=_e(n),i=new ft(e.workspacePath);i.ensure(),CI(i,o,e.force??!1);let r=new dr(a=>i.writeJson("timings.json",a)),s=new To(i,e.executor),c="failed";try{let a=Date.now(),d=0;if(!e.force&&i.has("pass1/body_start.json"))d=i.readJson("pass1/body_start.json").line??0,e.executor.recordReuse("ingest.body-start");else{let P=await Rg(e.executor,n,e.signal);d=P.line,i.writeJson("pass1/body_start.json",P)}let p=n.split(`
263
264
  `),l=d>0?p.slice(d).join(`
264
265
  `):n,f=d>0?p.slice(0,d).join(`
265
- `).trim().slice(0,6e3):"",u=lg(l);i.writeText("pass1/source.txt",n),i.writeJson("pass1/chunks.json",u.map(P=>({index:P.index,core_line_start:P.core_line_start,core_line_end:P.core_line_end}))),i.writeJson("manifest.json",{version:1,pipeline_version:tl,updated:new Date().toISOString(),source:{path:cr.resolve(t.path),sha256:o,kind:"text",ext:t.ext},chunks:u.length}),s.flush({scope:{kind:"phase",phase:"prepare"},status:"succeeded",startedAtMs:a});let g=0;r.phaseStart("normalize");let h=await Og(u,e.concurrency??30,async P=>{let de=`pass2/chunk_${Pa(P.index)}.json`,Se=`pass2/chunk_${Pa(P.index)}.error.json`;if(i.has(de)&&!e.force){let Ri=Tp(i.readJson(de),P);return i.clearError(Se),g++,e.executor.recordReuse("ingest.text-normalize"),Ri}let{raw:vt,records:Cn}=await Ig(e.executor,P,e.signal);return i.writeText(de,vt),i.writeText(`pass2/chunk_${Pa(P.index)}.jsonl`,ph(Cn)),i.clearError(Se),Cn}),m=h.filter(P=>!P.ok);for(let P of m){let de=P.error instanceof Error?P.error.message:String(P.error);i.writeJson(`pass2/chunk_${Pa(P.index)}.error.json`,{chunk:P.index,error:de})}if(s.flush({scope:{kind:"phase",phase:"normalize"},status:m.length?"failed":"succeeded"}),m.length>0)throw new S(`${m.length}/${u.length} chunk(s) failed normalization.`,{exitCode:k,errorCode:"INGEST_NORMALIZE_INCOMPLETE",hint:"Inspect pass2/chunk_NNN.error.json and rerun `scriptctl ingest` to resume.",data:{actual:m.map(P=>`chunk ${P.index}`)}});r.phaseEnd("normalize");let w,y,_;if(!e.force&&i.has("body.json"))w=i.readJson("body.json"),y=i.has("pass3/script.jsonl")?ns(i.readText("pass3/script.jsonl")).length:0,_=i.has("notes.json")?i.readJson("notes.json").length:0,g++;else{let P=[];for(let Cn of h)Cn.ok&&P.push(...Cn.value);i.writeText("pass3/script.jsonl",ph(P));let de=ns(i.readText("pass3/script.jsonl")),Se=CI(t.path),vt=pg(de,{title:Se});i.writeJson("notes.json",vt.notes),w=vt.script,i.writeJson("body.json",w),y=P.length,_=vt.notes.length}Km(w,ga(o),d);let x=P=>String(P).padStart(3,"0"),E=(P,de)=>`serial/win_${x(P)}_${x(de)}.json`,A={readUpdate:(P,de)=>i.has(E(P,de))?i.readText(E(P,de)):void 0,writeStep:(P,de,Se,vt)=>{i.writeText(`serial/context_${x(P)}.md`,Se),i.writeText(E(P,de),vt)},readArc:(P,de)=>{let Se=`serial/arc_${x(P)}_${x(de)}.md`;return i.has(Se)?i.readText(Se):void 0},writeArc:(P,de,Se)=>{i.writeText(`serial/arc_${x(P)}_${x(de)}.md`,Se)},readNameFix:(P,de)=>{let Se=`serial/fix_${x(P)}_${x(de)}.json`;return i.has(Se)?i.readText(Se):void 0},writeNameFix:(P,de,Se)=>i.writeText(`serial/fix_${x(P)}_${x(de)}.json`,Se)};r.phaseStart("serial");let b=await Yg(w,{executor:e.executor,checkpoint:A,force:e.force??!1,...f?{sourceRef:f}:{},onWindow:P=>{P.index===0&&r.serialStart(P.total,P.totalEpisodes),r.windowDone(P.startEp,P.endEp,P.ms,P.cached);let de=P.startEp===P.endEp?{kind:"episode",episode:P.startEp}:{kind:"episode-range",startEpisode:P.startEp,endEpisode:P.endEp},Se=Date.now();s.flush({scope:de,status:P.cached?"reused":"succeeded",startedAtMs:Se-P.ms,endedAtMs:Se})},...e.signal?{signal:e.signal}:{}}),C=b.doc;g+=b.reused,r.phaseEnd("serial"),r.phaseStart("govern");let{script:R,idMap:I}=va(C);i.writeJson("id_map.json",I);let O=wt(R);if(!O.ok)throw i.writeJson("validation.json",O),new S("Intermediate script failed validation before v4 identity assignment.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:O.errors.slice(0,5).map(P=>`${P.path}: ${P.message}`)}});let N=!e.force&&i.has("v4_identity_map.json")?i.readJson("v4_identity_map.json"):void 0,U=rr(Tt(C),N,b.identityKeys),M=U.script,V=Pe(M),F=[],Re=Date.now(),X="failed";try{if(V.ok){let P=await ih(i,M,e.executor,{force:e.force??!1,...e.signal?{signal:e.signal}:{}});F=rh(P.report)}X="succeeded"}finally{s.flush({scope:{kind:"phase",phase:"asset-audit"},status:X,startedAtMs:Re})}let j={...V,warnings:[...V.warnings,...ir(M),...F]};if(i.writeJson("pass5/script.json",M),i.writeJson("v4_identity_map.json",U.identityMap),i.writeJson("validation.json",j),!j.ok)throw new S("Final script.json failed v4 validation.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:j.errors.slice(0,5).map(P=>`${P.path}: ${P.message}`)}});i.writeJson("script.json",M),r.phaseEnd("govern"),r.finish();let Ot=M;return c="succeeded",{workspacePath:i.root,chunks:u.length,reused:g,records:y,notes:_,assets:{actors:Ot.actors?.length??0,locations:Ot.locations?.length??0,props:Ot.props?.length??0},scriptPath:i.path("script.json"),validation:{ok:j.ok,errors:j.errors.length,warnings:j.warnings.length}}}finally{s.finish(c)}}function CI(e){return cr.basename(e,cr.extname(e))}import*as oo from"node:fs";import*as Si from"node:path";import{createHash as rA}from"node:crypto";var TI=()=>({apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:[],voice:""});function Vo(){return{lastEpisode:0,registry:[],digests:[],openThreads:[]}}var xe=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),cs=(e,t)=>e.length>t?`${e.slice(0,t)}\u2026`:e;function VI(e,t){let n=xe(t);return e.find(o=>xe(o.name)===n||xe(o.identitySeed)===n||o.aliases.some(i=>xe(i)===n))}var $I=3,DI=12e3;function xi(e,t){let n=(t??"").trim();n&&!e.includes(n)&&e.push(n)}var GI=["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","voice"];function Ca(e,t,n){if(!t)return e;let o=e?{...e,persistent_marks:[...e.persistent_marks]}:TI();for(let i of GI){let r=t[i]?.trim()??"";r&&(n||!o[i])&&(o[i]=r)}for(let i of t.persistent_marks??[])xi(o.persistent_marks,i);return o}function nl(e,t,n){let o=t.name.trim();if(!o)return;let i=t.description.trim(),r=e.find(s=>Mn(s.name)===Mn(o));if(!r){e.push({name:o,description:i});return}i&&(n||!r.description)&&(r.description=i)}function uh(e,t,n,o=!1){let i=(s,c)=>{let a=(c??"").trim();return a&&(o||!s)?a:s};for(let s of t.add_recognition_anchors??[])xi(e.recognitionAnchors,s);e.identityProfile=Ca(e.identityProfile,t.identity_profile_patch,o);let r=i(e.appearance,t.appearance);r&&(e.appearance=r),e.role=i(e.role,t.role)??e.role;for(let s of t.add_aliases??[])xi(e.aliases,s);for(let s of t.add_states??[])nl(e.states,s,o);e.lastEpisode=n}function ds(e,t,n){let o=r=>VI(e.registry,r);for(let r of t.registry_delta.new_entities){let s=r.name.trim();if(!s||r.kind==="actor"&&ct(s))continue;let c=o(s);if(c){uh(c,{add_recognition_anchors:r.recognition_anchors,identity_profile_patch:r.identity_profile,appearance:r.appearance,role:r.role,add_aliases:r.aliases,add_states:r.states},n);continue}let a=[];for(let p of r.states??[])nl(a,p,!1);let d=[];for(let p of r.aliases??[])xi(d,p);e.registry.push({identitySeed:s,name:s,kind:r.kind,status:r.status,importance:r.importance,recognitionAnchors:[...new Set((r.recognition_anchors??[]).map(p=>p.trim()).filter(Boolean))],...r.identity_profile?{identityProfile:Ca(void 0,r.identity_profile,!0)}:{},...r.appearance?{appearance:r.appearance.trim()}:{},role:(r.role??"").trim(),aliases:d,states:a,firstEpisode:n,lastEpisode:n})}for(let r of t.registry_delta.enrich){let s=o(r.name);s&&uh(s,r,n,!0)}for(let r of t.registry_delta.canonicalize){let s=o(r.from_name),c=r.canonical_name.trim();if(!s||!c||xe(c)===xe(s.name))continue;let a=o(c);if(a&&a!==s){let d=s.firstEpisode<a.firstEpisode?s:a,p=d===s?a:s,l=d.states.map(g=>({...g})),f=new Set([...s.aliases,...a.aliases,s.identitySeed,a.identitySeed,s.name,a.name,r.from_name].map(g=>g.trim()).filter(Boolean));d.name=c,d.status="canonical",d.importance=s.importance==="featured"||a.importance==="featured"?"featured":"background",d.recognitionAnchors=[];for(let g of[...s.recognitionAnchors,...a.recognitionAnchors])xi(d.recognitionAnchors,g);let u=Ca(void 0,s.identityProfile,!0);d.identityProfile=Ca(u,a.identityProfile,!0),(a.appearance||s.appearance)&&(d.appearance=a.appearance||s.appearance),d.role=a.role||s.role,d.states=[];for(let g of[...l,...p.states])nl(d.states,g,!1);d.aliases=[...f].filter(g=>xe(g)!==xe(c)),d.firstEpisode=Math.min(s.firstEpisode,a.firstEpisode),d.lastEpisode=Math.max(s.lastEpisode,a.lastEpisode,n),e.registry.splice(e.registry.indexOf(p),1);continue}xi(s.aliases,s.name),xi(s.aliases,r.from_name),s.name=c,s.status="canonical",s.aliases=s.aliases.filter(d=>xe(d)!==xe(c)),s.lastEpisode=n}let i=0;for(let r of t.open_threads.opened){let s=r.text.trim();s&&e.openThreads.push({id:`t${n}_${++i}`,text:s,sinceEpisode:n})}for(let r of t.open_threads.closed){let s=r.ref.trim();s&&(e.openThreads=e.openThreads.filter(c=>c.id!==s&&c.text!==s))}return e.digests.push({episode:n,synopsis:(t.synopsis??"").trim()}),e.lastEpisode=n,e}function gh(e,t){return e.digests.push({episode:t,synopsis:"",outcome:"skipped"}),e.lastEpisode=t,e}function BI(e,t){let n=[],o=e.status==="provisional"?"\xB7\u5F85\u5B9A \u26A0":`\xB7${e.importance}`;n.push(`### ${e.name} ${o}`),e.role&&n.push(`- \u4F5C\u7528: ${cs(e.role,t?40:200)}`),e.recognitionAnchors.length&&n.push(`- \u8BC6\u522B\u951A\u70B9: ${e.recognitionAnchors.join("\uFF1B")}`);let i=e.identityProfile;if(i){let r=[i.apparent_gender,i.apparent_age].filter(Boolean).join("\uFF0C");r&&n.push(`- \u5E74\u9F84\u6027\u522B: ${r}`),i.face_shape&&n.push(`- \u8138\u578B\u4E0B\u988C: ${i.face_shape}`),i.brows_eyes&&n.push(`- \u7709\u773C: ${i.brows_eyes}`),i.nose&&n.push(`- \u9F3B\u90E8: ${i.nose}`),i.mouth&&n.push(`- \u5507\u5F62\u5634\u89D2: ${i.mouth}`),i.skin_features&&n.push(`- \u80A4\u8272\u9762\u90E8: ${i.skin_features}`),i.hair&&n.push(`- \u53D1\u578B: ${i.hair}`),i.build&&n.push(`- \u4F53\u6001: ${i.build}`),i.persistent_marks.length&&n.push(`- \u56FA\u5B9A\u6807\u8BB0: ${i.persistent_marks.join("\uFF1B")}`),i.voice&&n.push(`- \u58F0\u7EBF: ${i.voice}`)}return e.aliases.length&&n.push(`- \u66FE\u7528\u79F0\u547C: ${e.aliases.join("\u3001")}`),e.states.length&&n.push(`- \u5DF2\u77E5\u9020\u578B: ${e.states.map(r=>{let s=cs(r.description,t?30:90);return s?`${r.name}\uFF08${s}\uFF09`:r.name}).join(" / ")}`),n.push(`- \u51FA\u73B0: ep ${e.firstEpisode}\u2013${e.lastEpisode}`),e.status==="provisional"&&n.push(`- \u8EAB\u4EFD\u672A\u786E\u8BA4\uFF1A\u672C\u96C6\u82E5\u51FA\u73B0\u4E66\u9762\u59D3\u540D\u6216\u53F0\u8BCD\u672C\u540D\uFF0C\u7528 canonicalize \u4ECE\u300C${e.name}\u300D\u5347\u7EA7\u89C4\u8303\u540D`),n}function fh(e,t){let n=cs(e.appearance||e.role||"",t?30:60),o=e.states.map(i=>i.description?`${i.name}\uFF08${cs(i.description,t?20:60)}\uFF09`:i.name).join(" / ");return`- ${e.name} \xB7${e.importance}${n?`\uFF1A${n}`:""}${o?`\uFF1B\u72B6\u6001\uFF1A${o}`:""}`}function mh(e,t,n){let o=[];o.push(`# \u5DF2\u77E5\u8BBE\u5B9A\uFF08\u89E3\u6790\u7B2C ${e.lastEpisode+1} \u96C6\u65F6\u5BF9\u7167\u672C\u8868\uFF09`,""),o.push("\u8BA4\u5F97\u51FA\u7684\u4EBA/\u7269\u6CBF\u7528\u5176**\u89C4\u8303\u540D**\uFF0C\u522B\u81EA\u5DF1\u65B0\u8D77\u540D\uFF1B\u4EBA\u7269\u4F18\u5148\u6BD4\u5BF9\u8BC6\u522B\u951A\u70B9\u4E0E\u7ED3\u6784\u5316\u8EAB\u4EFD\u753B\u50CF\uFF0C\u670D\u88C5\u53EA\u4F5C\u5F31\u8F85\u52A9\u3002","");let i=e.registry.filter(a=>a.kind==="actor"),r=e.registry.filter(a=>a.kind==="location"),s=e.registry.filter(a=>a.kind==="prop");if(i.length){o.push("## \u4EBA\u7269","");for(let a of i)o.push(...BI(a,n),"")}if(r.length||s.length){o.push("## \u573A\u666F / \u9053\u5177","");for(let a of r)o.push(fh(a,n));for(let a of s)o.push(fh(a,n));o.push("")}let c=e.digests.filter(a=>a.episode>e.lastEpisode-t);if(c.length){o.push("## \u5267\u60C5\u8FDB\u5C55","");for(let a of[...c].sort((d,p)=>d.episode-p.episode))o.push(a.outcome==="skipped"?`\u7B2C${a.episode}\u96C6\u5DF2\u4EBA\u5DE5\u8DF3\u8FC7\uFF0C\u5267\u60C5\u672A\u77E5\u3002`:`\u7B2C${a.episode}\u96C6\uFF1A${n?cs(a.synopsis,40):a.synopsis}`);o.push("")}if(e.openThreads.length){o.push("## \u672A\u95ED\u5408\u7EBF\u7D22\uFF08\u82E5\u672C\u96C6\u4EA4\u4EE3\u4E86\uFF0C\u7528 open_threads.closed \u5F15\u7528\u5176 [id] \u5173\u95ED\uFF09","");for(let a of e.openThreads)o.push(`- [${a.id}] ${a.text}`);o.push("")}return o.join(`
266
- `)}function Ta(e){for(let t=$I;t>=1;t--){let n=mh(e,t,!1);if(n.length<=DI)return n}return mh(e,1,!0)}function $o(e){let t=new Map;for(let n of e)for(let o of[n.identitySeed,...n.aliases])xe(o)!==xe(n.name)&&t.set(o,n.name);return t}function JI(e){let t=e.identityProfile,n=[];if(t){let o=[t.apparent_gender,t.apparent_age].filter(Boolean).join("\uFF0C");o&&n.push(`\u5916\u89C2\u5E74\u9F84\u4E0E\u6027\u522B\uFF1A${o}`),t.face_shape&&n.push(`\u8138\u578B\u4E0B\u988C\uFF1A${t.face_shape}`),t.brows_eyes&&n.push(`\u7709\u773C\uFF1A${t.brows_eyes}`),t.nose&&n.push(`\u9F3B\u90E8\uFF1A${t.nose}`),t.mouth&&n.push(`\u5507\u5F62\u53E3\u5468\uFF1A${t.mouth}`),t.skin_features&&n.push(`\u80A4\u8272\u9762\u90E8\uFF1A${t.skin_features}`),t.hair&&n.push(`\u5934\u53D1\uFF1A${t.hair}`),t.build&&n.push(`\u9AA8\u67B6\u4F53\u578B\uFF1A${t.build}`),t.persistent_marks.length&&n.push(`\u56FA\u5B9A\u6807\u8BB0\uFF1A${t.persistent_marks.join("\u3001")}`),t.voice&&n.push(`\u58F0\u7EBF\uFF1A${t.voice}`)}return e.recognitionAnchors.length&&n.push(`\u8BC6\u522B\u951A\u70B9\uFF1A${e.recognitionAnchors.join("\uFF1B")}`),e.role&&n.push(`\u89D2\u8272\u8BED\u5883\uFF1A${e.role}`),n.map(o=>o.replace(/[。;]+$/,"")).join("\uFF1B")}function hh(e,t){let n=new Map,o=new Map,i=(s,c)=>{let a=xe(s),d=c.trim();!d||xe(d)===a||(o.has(a)||o.set(a,new Set),o.get(a).add(d))};for(let s of t){n.set(xe(s.name),s.importance);for(let c of s.aliases)n.set(xe(c),s.importance);n.set(xe(s.identitySeed),s.importance);for(let c of new Set([s.identitySeed,...s.aliases]))i(s.name,c)}let r=(s,c)=>{for(let a of s??[]){let d=String(a[c]??""),p=[d,...a.aliases??[]],l;for(let g of p)if(l=t.find(h=>xe(h.name)===xe(g)||xe(h.identitySeed)===xe(g)||h.aliases.some(m=>xe(m)===xe(g))),l)break;a.importance=l?.importance??n.get(xe(d))??"featured";let f=o.get(xe(d));if(f?.size&&(a.aliases=[...new Set([...a.aliases??[],...f])]),!l)continue;let u=l.kind==="actor"?JI(l):[l.appearance,l.role].map(g=>(g?.trim()??"").replace(/[。;]+$/,"")).filter(Boolean).join("\uFF1B");u&&(a.description=`${u}\u3002`);for(let g of a.states??[]){let h=l.states.find(m=>Mn(m.name)===Mn(g.state_name));h?.description?g.description=h.description:g.state_name==="default"&&l.kind!=="actor"&&l.appearance&&(g.description=l.appearance)}}};return r(e.actors,"actor_name"),r(e.locations,"location_name"),r(e.props,"prop_name"),e}function yh(e,t,n){let o=$o(t.registry),i=d=>o.get(d)??d,r=d=>{let p=d.indexOf(":"),l=d.slice(0,p);return p>0&&(l==="system"||l==="broadcast"||l==="offscreen"||l==="group")?{kind:l,label:d.slice(p+1)}:ct(d)?{kind:"group",label:d}:{name:i(d)}},s=0,c={title:n,episodes:e.map(d=>({identity_key:`comic:${d.document_id}`,episode_id:`ep_${String(d.episode).padStart(3,"0")}`,title:d.title,scenes:d.output.scenes.map((p,l)=>{let f=`comic:${d.document_id}:scene:${l+1}`,u=p.characters.flatMap(h=>h.states.length?h.states.map(m=>({name:i(h.name),state:m})):[{name:i(h.name)}]),g=p.actions.map((h,m)=>{let w={kind:"comic",document_id:d.document_id,pages:h.pages,regions:h.regions},y={identity_key:`${f}:action:${m+1}`,type:h.type,content:h.content,extend:{scriptctl:{source:w}}};if((h.type==="dialogue"||h.type==="inner_thought")&&(y.speaker=r(h.speaker),h.parenthetical&&(y.parenthetical=h.parenthetical),"name"in y.speaker)){let _=y.speaker.name;u.some(x=>x.name===_)||u.push({name:_})}return y});return{identity_key:f,scene_id:`scn_${String(++s).padStart(3,"0")}`,environment:{...p.space?{space:p.space}:{},...p.time?{time:Lo(p.time)}:{}},location:p.location?{name:i(p.location)}:null,actors:u,props:[...new Set(p.props.map(i))].map(h=>({name:h})),actions:g}})}))},a=new Set(t.registry.map(d=>`${d.kind}:${d.name}`));for(let d of c.episodes)for(let p of d.scenes){let f=[...p.actors.map(u=>`actor:${u.name}`),...p.props.map(u=>`prop:${u.name}`),...p.location?[`location:${p.location.name}`]:[]].filter(u=>!a.has(u));if(f.length)throw new S(`Comic scene references assets absent from the registry: ${f.join(", ")}`,{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"The episode must register every referenced character, location and key prop.",data:{actual:f}})}return c}var dr=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();function jI(e,t,n){let o=$o(t),i=l=>o.get(l)??l,r=new Map;for(let l of t){let f=i(l.name),g=t.find(m=>m.kind===l.kind&&dr(m.name)===dr(f))??l,h=`${l.kind}:${dr(f)}`;r.has(h)||r.set(h,`${n}:${g.kind}:${g.firstEpisode}:${dr(g.identitySeed)}`)}let s={},c={},a={},d={},p={actor:s,location:c,prop:a};for(let l of e){let f=l.names[0]??l.provisional_id,u=r.get(`${l.kind}:${dr(f)}`)??`${n}:${l.kind}:source:${dr(f)}`;p[l.kind][l.provisional_id]=u,d[l.provisional_id]=Object.fromEntries(l.states.map(g=>[g.id,`${u}:state:${Mn(g.name)}`]))}return{actor:s,location:c,prop:a,state:d}}function Va(e,t,n,o){let{script:i,assets:r,identityKeys:s}=ka(e);hh(i,t.registry);let c=Ma(i),{script:a,idMap:d}=va(c),p=wt(a);if(!p.ok)return{initial:i,final:a,idMap:d,validation:p,identityMap:o,scriptV4:null};let l=rr(Tt(c),o,{...jI(r,t.registry,n),...s}),f=l.script,u=Pe(f);return{initial:i,final:f,scriptV4:f,idMap:d,identityMap:l.identityMap,validation:{...u,warnings:[...u.warnings,...ir(f)]}}}import*as wh from"node:fs";import*as to from"node:path";import{createHash as KI}from"node:crypto";import{PDFDocument as zI}from"pdf-lib";import*as $a from"node:path";function Da(e){let t=$a.basename(e,$a.extname(e)),n=t.match(/第\s*0*(\d+)\s*[集话回]/u)??t.match(/(?:^|[._\-\s])(?:ep(?:isode)?|e)\s*[._\-\s]*0*(\d+)(?=$|[._\-\s])/iu);if(n)return Number(n[1]);let o=t.match(/\d+/);return o?Number(o[0]):null}function HI(e){let t=e.kind==="comic-file"?[e.path]:e.files,n=t.map(i=>({path:i,sourceNumber:Da(i)})),o=n.flatMap(i=>i.sourceNumber===null?[]:[i.sourceNumber]);if(o.length>0&&o.length!==t.length||new Set(o).size!==o.length)throw new S("Comic chapter ordering is ambiguous.",{exitCode:k,errorCode:"INGEST_COMIC_DISCOVERY",hint:"Give every PDF a unique chapter number, or use unnumbered filenames that sort in reading order.",data:{actual:t.map(i=>to.basename(i))}});return n.sort((i,r)=>i.sourceNumber!==null&&r.sourceNumber!==null?i.sourceNumber-r.sourceNumber:to.basename(i.path).localeCompare(to.basename(r.path),"zh-Hans",{numeric:!0}))}async function _h(e){let t=[];for(let[n,o]of HI(e).entries()){let i=wh.readFileSync(o.path),s=(await zI.load(i,{updateMetadata:!1})).getPageCount();if(!s)throw new S("PDF is outside the document provider limits.",{exitCode:k,errorCode:"INGEST_COMIC_SIZE",hint:"Provide a PDF containing at least one readable page.",data:{actual:[`${o.path}: ${s} pages, ${i.length} bytes`]}});t.push({episode:n+1,document_id:`chapter-${String(n+1).padStart(3,"0")}`,source_number:o.sourceNumber,title:to.basename(o.path,to.extname(o.path)),path:to.resolve(o.path),sha256:KI("sha256").update(i).digest("hex"),page_count:s,size_bytes:i.length})}return t}function Eh(e,t){let n=e.find((o,i)=>{let r=t[i];return!r||o.sha256!==r.sha256||o.source_number!==r.source_number||o.title!==r.title});if(n)throw new S("The comic source prefix changed.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Restore the original chapters or use a fresh workspace. Only tail chapters may be appended.",data:{actual:[n.title]}})}import{PDFDocument as FI,StandardFonts as QI,rgb as YI,pushGraphicsState as qI,popGraphicsState as ZI,concatTransformationMatrix as Ga}from"pdf-lib";async function xh(e){let t=await FI.load(e),n=await t.embedFont(QI.Helvetica),o=YI(0,.45,.85);for(let i of t.getPages()){let r=i.getCropBox(),s=(i.getRotation().angle%360+360)%360,c=s===90||s===270,a=c?r.height:r.width,d=c?r.width:r.height;switch(i.pushOperators(qI()),s){case 90:i.pushOperators(Ga(0,1,-1,0,r.x+r.width,r.y));break;case 180:i.pushOperators(Ga(-1,0,0,-1,r.x+r.width,r.y+r.height));break;case 270:i.pushOperators(Ga(0,-1,1,0,r.x,r.y+r.height));break;default:i.pushOperators(Ga(1,0,0,1,r.x,r.y))}let p=a/70;for(let l=0;l<=1e3;l+=50){let f=d*(1-l/1e3);i.drawLine({start:{x:0,y:f},end:{x:a,y:f},thickness:.5,color:o,opacity:.3});let u=`y=${l}`,g=Math.max(1,Math.min(d-p,f+1));for(let h of[1,a-n.widthOfTextAtSize(u,p)-1])i.drawText(u,{x:h,y:g,size:p,font:n,color:o})}for(let l=100;l<1e3;l+=100){let f=a*l/1e3;i.drawLine({start:{x:f,y:0},end:{x:f,y:d},thickness:.5,color:o,opacity:.3});for(let u=0;u<1e3;u+=250)i.drawText(`x=${l}`,{x:f+1,y:d*(1-u/1e3)-p,size:p,font:n,color:o})}i.pushOperators(ZI())}return t.save()}import*as Sh from"node:fs";import*as Ih from"node:path";import WI from"proper-lockfile";async function Do(e,t){let n=Ih.resolve(e);Sh.mkdirSync(n,{recursive:!0});let o=null;try{o=await WI.lock(n,{realpath:!1,stale:12e4,update:1e4,retries:0})}catch(i){throw new S("The ingest workspace is busy.",{exitCode:ee,errorCode:"INGEST_WORKSPACE_BUSY",hint:"Wait for the other ingest or skip command to finish, then retry.",data:{actual:[n,i instanceof Error?i.message:String(i)]}})}try{return await t()}finally{await o()}}import*as no from"node:fs";import*as il from"node:path";import{PDFDocument as ol}from"pdf-lib";import{z as pr}from"zod";var Ah=pr.object({starts:pr.array(pr.object({page:pr.number().int().min(1),title:pr.string().min(1)}))}),XI="\u9605\u8BFB\u6F2B\u753B PDF \u5E76\u8BC6\u522B\u5B9E\u9645\u8BDD/\u7AE0\u8282\u8FB9\u754C\u3002\u53EA\u8F93\u51FA\u672C\u6BB5\u5185\u786E\u5B9E\u5F00\u59CB\u7684\u65B0\u8BDD\u7684\u8D77\u59CB\u7269\u7406\u9875\u7801\u548C\u539F\u7A3F\u6807\u9898\u3002\u4F9D\u636E\u8BDD\u53F7\u3001\u7AE0\u8282\u6249\u9875\u3001\u6807\u9898\u53CA\u53D9\u4E8B\u8FDE\u7EED\u6027\u7EFC\u5408\u5224\u65AD\uFF1B\u573A\u666F\u5207\u6362\u3001\u56DE\u5FC6\u3001\u6362\u9875\u548C\u5E7F\u544A\u4E0D\u662F\u65B0\u8BDD\u3002\u8F93\u5165\u53EF\u80FD\u4ECE\u4E00\u8BDD\u4E2D\u95F4\u5F00\u59CB\uFF0C\u5EF6\u7EED\u524D\u6BB5\u7684\u5185\u5BB9\u4E0D\u7B97\u65B0\u8BDD\u3002\u7B2C\u4E00\u6BB5\u4ECE\u539F\u6587\u6863\u7B2C\u4E00\u9875\u5F00\u59CB\u65F6\uFF0C\u4E3A\u7B2C\u4E00\u8BDD\u5EFA\u7ACB\u8D77\u70B9\uFF0C\u5C01\u9762\u548C\u76EE\u5F55\u968F\u9996\u8BDD\u4FDD\u7559\u3002\u591A\u8BDD\u5408\u96C6\u9010\u9879\u5217\u51FA\u5404\u8BDD\uFF1B\u5355\u8BDD\u6587\u4EF6\u53EA\u6709\u4E00\u4E2A\u8D77\u70B9\u3002page \u4F7F\u7528\u672C\u6B21\u8F93\u5165 PDF \u4ECE 1 \u5F00\u59CB\u7684\u7269\u7406\u9875\u7801\u3002\u6807\u9898\u4FDD\u7559\u539F\u8BDD\u53F7\u548C\u53EF\u8BFB\u8BDD\u540D\uFF1B\u65E0\u6CD5\u786E\u8BA4\u8BDD\u53F7\u65F6\u4F7F\u7528\u7B80\u77ED\u5185\u5BB9\u6807\u9898\u3002";async function kh(e,t,n,o){let i=[];for(let r of e){let s=`sources/${r.sha256}.chapters.json`,c,a=await ol.load(no.readFileSync(r.path));if(t.has(s))c=t.readJson(s);else{c=[];for(let d=0;d<r.page_count;){let p=Math.min(40,r.page_count-d),l;for(;;){let g=await ol.create();for(let h of await g.copyPages(a,Array.from({length:p},(m,w)=>d+w)))g.addPage(h);if(l=await g.save(),l.length<=4e7||p===1)break;p=Math.ceil(p/2)}let f=t.path(`sources/${r.sha256}.scan.pdf`);no.mkdirSync(il.dirname(f),{recursive:!0}),gi(f,Buffer.from(l)),process.stderr.write(`\u8BC6\u522B\u6F2B\u753B\u7AE0\u8282 \xB7 ${r.title} \xB7 \u539F\u7A3F ${d+1}\u2013${d+p} / ${r.page_count} \u9875
267
- `);let u=await n.prepare(f,o);try{let g=await n.generate({media:u,system:XI,user:`\u539F\u6587\u4EF6\uFF1A${r.title}\uFF0C\u5171 ${r.page_count} \u9875\u3002\u672C\u6BB5\u4E3A\u539F\u7A3F\u7B2C ${d+1}\u2013${d+p} \u9875\u3002\u5DF2\u8BC6\u522B\u8D77\u70B9\uFF1A${JSON.stringify(c)}\u3002`,responseJsonSchema:pr.toJSONSchema(Ah,{target:"openapi-3.0"}),signal:o}),h=Ah.parse(JSON.parse(g.text));c.push(...h.starts.filter(m=>m.page<=p).map(m=>({...m,page:d+m.page})))}finally{await n.release(u,o)}d+=p}c=[...new Map(c.sort((d,p)=>d.page-p.page).map(d=>[d.page,d])).values()],c.length?c[0].page=1:c.push({page:1,title:r.title}),t.writeJson(s,c)}for(let[d,p]of c.entries()){let l=(c[d+1]?.page??r.page_count+1)-1,f=i.length+1,u=c.length===1?r.path:t.path(`sources/${r.sha256}.${p.page}-${l}.pdf`);if(!no.existsSync(u)){let g=await ol.create();for(let h of await g.copyPages(a,Array.from({length:l-p.page+1},(m,w)=>p.page-1+w)))g.addPage(h);no.mkdirSync(il.dirname(u),{recursive:!0}),gi(u,Buffer.from(await g.save()))}i.push({...r,episode:f,document_id:`chapter-${String(f).padStart(3,"0")}`,title:c.length===1?r.title:p.title,path:u,page_count:l-p.page+1,size_bytes:no.statSync(u).size,original_path:r.path,original_page_count:r.page_count,start_page:p.page,end_page:l})}}return i}import{z as bh}from"zod";var Ba=fn,eA=Ba(16);function fn(e,t){e=e-0;let n=rl(),o=n[e];if(fn.YRXMyC===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,g=0;u=c.charAt(g++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};fn.NlCFnI=i,fn.oGorNA={},fn.YRXMyC=!0}let r=n[0];fn.WQOQgA!==r&&(fn.oGorNA={},fn.WQOQgA=r);let s=fn.oGorNA[e];return s===void 0?(o=fn.NlCFnI(o),fn.oGorNA[e]=o):o=s,o}function sl(e,t){let n=Ba,o=fa[n(24)](JSON[n(18)](e)),i=a=>{let d=n;throw new S(d(44)+a[d(4)]("; "),{exitCode:k,errorCode:d(7),hint:d(2),data:{actual:a}})};if(!o[n(28)])return i(o[n(13)][n(19)][n(25)](0,8)[n(21)](a=>a[n(42)][n(4)](".")+": "+a[n(37)]));let r=o[n(34)],s=new Set;for(let a of r[n(20)])for(let d of a[n(12)]){if(d[n(27)][n(43)]((l,f)=>l>t||f>0&&l<=d[n(27)][f-1]))return i([n(30)+d[n(27)][n(4)](", ")+n(5)+t+n(33)]);let p=Qr(d[n(27)],d[n(38)]);if(p[n(26)])return i(p);for(let l of d[n(27)])s[n(40)](l)}for(let a of r[n(0)]){if(a[n(1)]>t||s[n(36)](a[n(1)]))return i([n(15)+a[n(1)]]);s[n(40)](a[n(1)])}let c=Array[n(29)]({length:t},(a,d)=>d+1)[n(31)](a=>!s[n(36)](a));return c[n(26)]?i([n(6)+c[n(4)](", ")]):r}async function Oh(e,t,n,o,i,r,s){let c=Ba,a=await e[c(22)]({media:t,system:eA,user:c(11)+n+c(9)+o+c(3)+i,responseJsonSchema:bh[c(17)](Om,{target:c(23)}),signal:s});return r(a[c(10)]),sl(a[c(10)],o)}function rl(){let e=["AwDUB3jLzf9WywDLCW","CgfNzq","sw5ZCgvJDcbLCc8QlNjLC3bVBNnLlMPZB24Gyw5KihjLCNvUigLUz2vZDcb3AxrOihrOzsbZyw1LihnVDxjJzsbHBMqGD29YA3nWywnLlG","ioMHTE+8JoIVT+wUJoAvToMyHEIVU+w5TUAmIEMHUUw6J+MaKoAGVoI9RowgMEwfQoMdQowjP+AdHEoaGGOk","AM9PBG","oYbKB2n1BwvUDcbOyxmG","ugfNzxmGywjZzw50igzYB20GDhjHBNnJCMLWDdOG","su5hrvnux0nptuLdx1nfuKLbtf9gquLmruq","C2HHCgu","44cc5PYSifberIdLHBeG","Dgv4Da","5B2t5yMn6k+D77YA","ywn0Aw9UCW","zxjYB3i","C3rYAw5NAwz5","sw52ywXPzcbVCIbKDxbSAwnHDguGAwDUB3jLzcbWywDLoIa","5l2G5PIV5RYR55s76l2S5yMN5PYS55Qe5lIY6kgm6kEJ5P6q5zMO44cc6l6t5ywL5PIV5A6m5Pw05lIa6k+DifberIdLKOZLIy3PNAlLKitOR53NTk/NP6/NMOtLT7lNN6xORR7LRPRJGilOVPpLH7RKUidKUkRNRkBLKiGGC2nOzw1HioEAHcbku09oiowVUEIXOE+8JowqJoAxTUwmHEwqQ+ACRoIVNEMaKoAGVowjP+ACRooaGEI1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oEAHos6UUEjQEoaGEwCSoEcUEwsJowfS+MuRUMbK+wfT++8JoINHoImG+wqJEs4JUw8LEEuQoMaKowTL+s4GoIhTooaGUs+NEAnRUwoN+EOV+ApJ+I/SowpR+INGEwKLUINGU+8M+wqJos4GoI6Q+s7VEEuQowiQ+wqJEwsJcbJyw5VBMLJywXPEMuG5B2s5BM244cc5l+D55wz5BEY6l2S5B2v5Q2J5PAh55Qe5ywO6yoO5yAf5A6544cc","ihbHz2vZlG","zgf0yq","cUMCGoIMGEINO+wgS++8MG","AgfZ","BwvZC2fNzq","CMvNAw9UCW","CMvNAxn0CNLFzgvSDge","ywrK","cUw3SUACIEI9Row9LE+8MG","Cgf0Aa","C29Tzq","q29TAwmGzxbPC29KzsbMywLSzwqGDhjHBNnJCMLWDcb2ywXPzgf0Aw9UoIa"];return rl=function(){return e},rl()}async function vh(e,t,n,o,i,r){let s=Ba,c=fa[s(8)][s(39)],a=await e[s(22)]({media:t,signal:r,system:s(32),user:o+s(35)+i+s(41)+JSON[s(14)](n),responseJsonSchema:bh[s(17)](c,{target:s(23)})});return c[s(18)](JSON[s(18)](a[s(10)]))}function Ja(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tA(e){switch(e.errorCode){case"LLM_CREDENTIAL_MISSING":return{failure_type:"authentication",failure_code:"authentication_failed"};case"LLM_CONFIG_INVALID":return{failure_type:"provider",failure_code:"request_rejected"};case"INGEST_VIDEO_INLINE_TOO_LARGE":return{failure_type:"media",failure_code:"media_too_large"};case"INGEST_COMIC_SERIAL_FAILED":case"INGEST_VIDEO_SERIAL_FAILED":return{failure_type:"pipeline",failure_code:"serial_parse_failed"};case"INGEST_VIDEO_TIMESTAMP_MISSING":return{failure_type:"validation",failure_code:"script_validation_failed"};case"INGEST_SOURCE_MISMATCH":return{failure_type:"pipeline",failure_code:"source_mismatch"};case"INGEST_PIPELINE_MISMATCH":return{failure_type:"pipeline",failure_code:"pipeline_mismatch"};case"INGEST_VALIDATION_FAILED":return{failure_type:"validation",failure_code:"script_validation_failed"};default:return{failure_type:"unknown",failure_code:"unknown"}}}function nA(e){if(e instanceof T)return{failure:e.failure,attempts:e.modelFailures};if(e instanceof S){let t=e.errorCode==="INGEST_VALIDATION_FAILED"||e.errorCode==="INGEST_VIDEO_SERIAL_FAILED"||e.errorCode==="INGEST_COMIC_SERIAL_FAILED";return{failure:Ut(tA(e),{retryable:t,message:e.message}),attempts:[]}}return{failure:Ut({failure_type:"unknown",failure_code:"unknown"},{retryable:!1,message:e instanceof Error?e.message:String(e)}),attempts:[]}}function ja(e,t,n){let o=nA(e);return{schema_version:1,unit:{kind:"episode",episode:t},phase:n,occurred_at:new Date().toISOString(),...o}}function Mh(e){return e.retryable?"Inspect the episode error sidecar and rerun `scriptctl ingest` to resume from this episode.":e.failure_type==="policy"?"Inspect the provider policy reason in the episode error sidecar; rerunning the same source is unlikely to help.":e.failure_type==="authentication"||e.failure_type==="authorization"?"Fix the provider credential or permission reported in the episode error sidecar before rerunning.":"Inspect the typed episode error sidecar and resolve the terminal failure before rerunning."}function Rh(e,t){return typeof e=="string"&&t.some(n=>n===e)}function lr(e){return typeof e=="string"?e:void 0}function oA(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!Ja(n)||typeof n.category!="string"||typeof n.probability!="string"||typeof n.blocked!="boolean")return;t.push({category:n.category,probability:n.probability,blocked:n.blocked})}return t}function iA(e){let t=e.provider_source,n=e.provider_reason;return{provider:lr(e.provider),model:lr(e.model),operation:lr(e.operation),http_status:typeof e.http_status=="number"?e.http_status:void 0,system_code:lr(e.system_code),provider_source:Rh(t,["prompt","candidate"])?t:void 0,provider_reason:Rh(n,["SAFETY","PROHIBITED_CONTENT","BLOCKLIST","SPII","RECITATION","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION","OTHER","UNSPECIFIED","UNKNOWN"])?n:void 0,provider_reason_raw:lr(e.provider_reason_raw),finish_message:lr(e.finish_message),safety_ratings:oA(e.safety_ratings),details:Array.isArray(e.details)&&e.details.every(i=>typeof i=="string")?e.details:void 0}}function ps(e){if(!Ja(e))return null;let t=iu(e.failure_type,e.failure_code);return!t||typeof e.retryable!="boolean"||typeof e.message!="string"?null:Ut(t,{...iA(e),retryable:e.retryable,message:e.message})}function ls(e){if(!Ja(e)||e.schema_version!==1)return null;let t=e.unit;if(!Ja(t)||t.kind!=="episode"||typeof t.episode!="number"||typeof e.phase!="string"||typeof e.occurred_at!="string")return null;let n=ps(e.failure);if(!n||!Array.isArray(e.attempts))return null;let o=[];for(let i of e.attempts){let r=ps(i);if(!r)return null;o.push(r)}return{schema_version:1,unit:{kind:"episode",episode:t.episode},phase:e.phase,occurred_at:e.occurred_at,failure:n,attempts:o}}var Nh="comic-1",Ka=e=>String(e).padStart(3,"0"),Lh=["script.initial.json","id_map.json","validation.json","context.json","v4_identity_map.json","script.json"];function za(e,t,n){let o=Va(yh(e,t.context,n),t.context,"comic",t.identityMap);if(!o.scriptV4||!o.validation.ok)throw new S("Comic script failed validation.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect the current episode response and rerun ingest with the same source and workspace.",data:{actual:o.validation.errors.slice(0,8).map(i=>`${i.path}: ${i.message}`)}});for(let[i,r]of o.scriptV4.episodes.entries())r.synopsis=e[i].output.synopsis;return{...o,scriptV4:o.scriptV4}}function al(e,t,n){e.writeJson("script.initial.json",t.initial),e.writeJson("id_map.json",t.idMap),e.writeJson("validation.json",t.validation),e.writeJson("context.json",n),e.writeJson("v4_identity_map.json",t.identityMap),e.writeJson("script.json",t.scriptV4)}async function sA(e){let t=On(e.sourcePath);if(t.kind!=="comic-file"&&t.kind!=="comic-directory")throw new S("Expected PDF comic source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=new ft(Si.resolve(e.workspacePath));n.ensure();let o=n.has("manifest.json")?n.readJson("manifest.json"):null;if(o&&o.pipeline_version!==Nh)throw new S("This workspace belongs to another ingest pipeline.",{exitCode:k,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Choose a fresh workspace."});if(!o&&n.has("script.json"))throw new S("Workspace already contains an unmanaged script.json.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Choose a fresh workspace."});let i=await _h(t),r=o&&!o.episodes.some(w=>w.original_path)?i:await kh(i,n,e.executor.documentPort("ingest.comic-serial"),e.signal);o&&Eh(o.episodes,r);let s={version:1,pipeline_version:Nh,updated:new Date().toISOString(),source:{kind:t.kind,path:Si.resolve(t.path),sha256:rA("sha256").update(r.map(w=>w.sha256).join(`
268
- `)).digest("hex")},episodes:r,...o?.current_error?{current_error:o.current_error}:{}};if(e.force){for(let w of o?.episodes??[])for(let y of["json","response.json","context.md","error.json","input.pdf"])oo.rmSync(n.path(`ep/ep_${Ka(w.episode)}.${y}`),{force:!0});for(let w of["checkpoint.json","timings.json",...Lh])oo.rmSync(n.path(w),{force:!0});delete s.current_error}n.writeJson("manifest.json",s);let c=n.has("checkpoint.json")?n.readJson("checkpoint.json"):{context:Vo(),identityMap:Co()},a=r.slice(0,c.context.lastEpisode).map(w=>n.readJson(`ep/ep_${Ka(w.episode)}.json`)),d=oo.realpathSync(t.path),p=Si.basename(d,t.kind==="comic-file"?Si.extname(d):""),l=new To(n,e.executor),f=new ar(w=>n.writeJson("timings.json",w));f.phaseStart("serial"),f.serialStart(r.length,r.length);let u="failed",g=0,h=a.length,m;try{if(a.length>0){al(n,za(a,c,p),c.context);for(let _ of a)n.clearError(`ep/ep_${Ka(_.episode)}.error.json`);s.current_error&&s.current_error.unit.episode<=c.context.lastEpisode&&(delete s.current_error,s.updated=new Date().toISOString(),n.writeJson("manifest.json",s))}else for(let _ of Lh)oo.rmSync(n.path(_),{force:!0});for(let _ of r){if(e.signal?.throwIfAborted(),_.episode<=c.context.lastEpisode){e.executor.recordReuse("ingest.comic-serial");let R=Date.now();l.flush({scope:{kind:"episode",episode:_.episode},status:"reused",startedAtMs:R,endedAtMs:R}),f.windowDone(_.episode,_.episode,0,!0);continue}if(e.step&&g>=1)break;let x=Date.now(),E=`ep/ep_${Ka(_.episode)}`,A=s.current_error?.unit.episode===_.episode?s.current_error.failure.message:void 0,b=Ta(c.context)+(A?`
266
+ `).trim().slice(0,6e3):"",u=mg(l);i.writeText("pass1/source.txt",n),i.writeJson("pass1/chunks.json",u.map(P=>({index:P.index,core_line_start:P.core_line_start,core_line_end:P.core_line_end}))),i.writeJson("manifest.json",{version:1,pipeline_version:ol,updated:new Date().toISOString(),source:{path:pr.resolve(t.path),sha256:o,kind:"text",ext:t.ext},chunks:u.length}),s.flush({scope:{kind:"phase",phase:"prepare"},status:"succeeded",startedAtMs:a});let m=0;r.phaseStart("normalize");let h=await Mg(u,e.concurrency??30,async P=>{let ce=`pass2/chunk_${Ta(P.index)}.json`,Se=`pass2/chunk_${Ta(P.index)}.error.json`;if(i.has(ce)&&!e.force){let Mi=$p(i.readJson(ce),P);return i.clearError(Se),m++,e.executor.recordReuse("ingest.text-normalize"),Mi}let{raw:vt,records:Cn}=await bg(e.executor,P,e.signal);return i.writeText(ce,vt),i.writeText(`pass2/chunk_${Ta(P.index)}.jsonl`,fh(Cn)),i.clearError(Se),Cn}),g=h.filter(P=>!P.ok);for(let P of g){let ce=P.error instanceof Error?P.error.message:String(P.error);i.writeJson(`pass2/chunk_${Ta(P.index)}.error.json`,{chunk:P.index,error:ce})}if(s.flush({scope:{kind:"phase",phase:"normalize"},status:g.length?"failed":"succeeded"}),g.length>0)throw new x(`${g.length}/${u.length} chunk(s) failed normalization.`,{exitCode:k,errorCode:"INGEST_NORMALIZE_INCOMPLETE",hint:"Inspect pass2/chunk_NNN.error.json and rerun `scriptctl ingest` to resume.",data:{actual:g.map(P=>`chunk ${P.index}`)}});r.phaseEnd("normalize");let w,y,_;if(!e.force&&i.has("body.json"))w=i.readJson("body.json"),y=i.has("pass3/script.jsonl")?os(i.readText("pass3/script.jsonl")).length:0,_=i.has("notes.json")?i.readJson("notes.json").length:0,m++;else{let P=[];for(let Cn of h)Cn.ok&&P.push(...Cn.value);i.writeText("pass3/script.jsonl",fh(P));let ce=os(i.readText("pass3/script.jsonl")),Se=TI(t.path),vt=fg(ce,{title:Se});i.writeJson("notes.json",vt.notes),w=vt.script,i.writeJson("body.json",w),y=P.length,_=vt.notes.length}Fm(w,ya(o),d);let S=P=>String(P).padStart(3,"0"),E=(P,ce)=>`serial/win_${S(P)}_${S(ce)}.json`,A={readUpdate:(P,ce)=>i.has(E(P,ce))?i.readText(E(P,ce)):void 0,writeStep:(P,ce,Se,vt)=>{i.writeText(`serial/context_${S(P)}.md`,Se),i.writeText(E(P,ce),vt)},readArc:(P,ce)=>{let Se=`serial/arc_${S(P)}_${S(ce)}.md`;return i.has(Se)?i.readText(Se):void 0},writeArc:(P,ce,Se)=>{i.writeText(`serial/arc_${S(P)}_${S(ce)}.md`,Se)},readNameFix:(P,ce)=>{let Se=`serial/fix_${S(P)}_${S(ce)}.json`;return i.has(Se)?i.readText(Se):void 0},writeNameFix:(P,ce,Se)=>i.writeText(`serial/fix_${S(P)}_${S(ce)}.json`,Se)};r.phaseStart("serial");let b=await Wg(w,{executor:e.executor,checkpoint:A,force:e.force??!1,...f?{sourceRef:f}:{},onWindow:P=>{P.index===0&&r.serialStart(P.total,P.totalEpisodes),r.windowDone(P.startEp,P.endEp,P.ms,P.cached);let ce=P.startEp===P.endEp?{kind:"episode",episode:P.startEp}:{kind:"episode-range",startEpisode:P.startEp,endEpisode:P.endEp},Se=Date.now();s.flush({scope:ce,status:P.cached?"reused":"succeeded",startedAtMs:Se-P.ms,endedAtMs:Se})},...e.signal?{signal:e.signal}:{}}),U=b.doc;m+=b.reused,r.phaseEnd("serial"),r.phaseStart("govern");let{script:M,idMap:I}=Ma(U);i.writeJson("id_map.json",I);let v=wt(M);if(!v.ok)throw i.writeJson("validation.json",v),new x("Intermediate script failed validation before v4 identity assignment.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:v.errors.slice(0,5).map(P=>`${P.path}: ${P.message}`)}});let L=!e.force&&i.has("v4_identity_map.json")?i.readJson("v4_identity_map.json"):void 0,C=ar(Tt(U),L,b.identityKeys),R=C.script,J=Pe(R),W=[],Re=Date.now(),ie="failed";try{if(J.ok){let P=await ah(i,R,e.executor,{force:e.force??!1,...e.signal?{signal:e.signal}:{}});W=ch(P.report)}ie="succeeded"}finally{s.flush({scope:{kind:"phase",phase:"asset-audit"},status:ie,startedAtMs:Re})}let K={...J,warnings:[...J.warnings,...sr(R),...W]};if(i.writeJson("pass5/script.json",R),i.writeJson("v4_identity_map.json",C.identityMap),i.writeJson("validation.json",K),!K.ok)throw new x("Final script.json failed v4 validation.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:K.errors.slice(0,5).map(P=>`${P.path}: ${P.message}`)}});i.writeJson("script.json",R),r.phaseEnd("govern"),r.finish();let Ot=R;return c="succeeded",{workspacePath:i.root,chunks:u.length,reused:m,records:y,notes:_,assets:{actors:Ot.actors?.length??0,locations:Ot.locations?.length??0,props:Ot.props?.length??0},scriptPath:i.path("script.json"),validation:{ok:K.ok,errors:K.errors.length,warnings:K.warnings.length}}}finally{s.finish(c)}}function TI(e){return pr.basename(e,pr.extname(e))}import*as io from"node:fs";import*as Ii from"node:path";import{createHash as sA}from"node:crypto";var VI=()=>({apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:[],voice:""});function Vo(){return{lastEpisode:0,registry:[],digests:[],openThreads:[]}}var xe=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),ds=(e,t)=>e.length>t?`${e.slice(0,t)}\u2026`:e;function $I(e,t){let n=xe(t);return e.find(o=>xe(o.name)===n||xe(o.identitySeed)===n||o.aliases.some(i=>xe(i)===n))}var DI=3,GI=12e3;function Si(e,t){let n=(t??"").trim();n&&!e.includes(n)&&e.push(n)}var BI=["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","voice"];function Va(e,t,n){if(!t)return e;let o=e?{...e,persistent_marks:[...e.persistent_marks]}:VI();for(let i of BI){let r=t[i]?.trim()??"";r&&(n||!o[i])&&(o[i]=r)}for(let i of t.persistent_marks??[])Si(o.persistent_marks,i);return o}function il(e,t,n){let o=t.name.trim();if(!o)return;let i=t.description.trim(),r=e.find(s=>Mn(s.name)===Mn(o));if(!r){e.push({name:o,description:i});return}i&&(n||!r.description)&&(r.description=i)}function gh(e,t,n,o=!1){let i=(s,c)=>{let a=(c??"").trim();return a&&(o||!s)?a:s};for(let s of t.add_recognition_anchors??[])Si(e.recognitionAnchors,s);e.identityProfile=Va(e.identityProfile,t.identity_profile_patch,o);let r=i(e.appearance,t.appearance);r&&(e.appearance=r),e.role=i(e.role,t.role)??e.role;for(let s of t.add_aliases??[])Si(e.aliases,s);for(let s of t.add_states??[])il(e.states,s,o);e.lastEpisode=n}function ps(e,t,n){let o=r=>$I(e.registry,r);for(let r of t.registry_delta.new_entities){let s=r.name.trim();if(!s||r.kind==="actor"&&ct(s))continue;let c=o(s);if(c){gh(c,{add_recognition_anchors:r.recognition_anchors,identity_profile_patch:r.identity_profile,appearance:r.appearance,role:r.role,add_aliases:r.aliases,add_states:r.states},n);continue}let a=[];for(let p of r.states??[])il(a,p,!1);let d=[];for(let p of r.aliases??[])Si(d,p);e.registry.push({identitySeed:s,name:s,kind:r.kind,status:r.status,importance:r.importance,recognitionAnchors:[...new Set((r.recognition_anchors??[]).map(p=>p.trim()).filter(Boolean))],...r.identity_profile?{identityProfile:Va(void 0,r.identity_profile,!0)}:{},...r.appearance?{appearance:r.appearance.trim()}:{},role:(r.role??"").trim(),aliases:d,states:a,firstEpisode:n,lastEpisode:n})}for(let r of t.registry_delta.enrich){let s=o(r.name);s&&gh(s,r,n,!0)}for(let r of t.registry_delta.canonicalize){let s=o(r.from_name),c=r.canonical_name.trim();if(!s||!c||xe(c)===xe(s.name))continue;let a=o(c);if(a&&a!==s){let d=s.firstEpisode<a.firstEpisode?s:a,p=d===s?a:s,l=d.states.map(m=>({...m})),f=new Set([...s.aliases,...a.aliases,s.identitySeed,a.identitySeed,s.name,a.name,r.from_name].map(m=>m.trim()).filter(Boolean));d.name=c,d.status="canonical",d.importance=s.importance==="featured"||a.importance==="featured"?"featured":"background",d.recognitionAnchors=[];for(let m of[...s.recognitionAnchors,...a.recognitionAnchors])Si(d.recognitionAnchors,m);let u=Va(void 0,s.identityProfile,!0);d.identityProfile=Va(u,a.identityProfile,!0),(a.appearance||s.appearance)&&(d.appearance=a.appearance||s.appearance),d.role=a.role||s.role,d.states=[];for(let m of[...l,...p.states])il(d.states,m,!1);d.aliases=[...f].filter(m=>xe(m)!==xe(c)),d.firstEpisode=Math.min(s.firstEpisode,a.firstEpisode),d.lastEpisode=Math.max(s.lastEpisode,a.lastEpisode,n),e.registry.splice(e.registry.indexOf(p),1);continue}Si(s.aliases,s.name),Si(s.aliases,r.from_name),s.name=c,s.status="canonical",s.aliases=s.aliases.filter(d=>xe(d)!==xe(c)),s.lastEpisode=n}let i=0;for(let r of t.open_threads.opened){let s=r.text.trim();s&&e.openThreads.push({id:`t${n}_${++i}`,text:s,sinceEpisode:n})}for(let r of t.open_threads.closed){let s=r.ref.trim();s&&(e.openThreads=e.openThreads.filter(c=>c.id!==s&&c.text!==s))}return e.digests.push({episode:n,synopsis:(t.synopsis??"").trim()}),e.lastEpisode=n,e}function wh(e,t){return e.digests.push({episode:t,synopsis:"",outcome:"skipped"}),e.lastEpisode=t,e}function JI(e,t){let n=[],o=e.status==="provisional"?"\xB7\u5F85\u5B9A \u26A0":`\xB7${e.importance}`;n.push(`### ${e.name} ${o}`),e.role&&n.push(`- \u4F5C\u7528: ${ds(e.role,t?40:200)}`),e.recognitionAnchors.length&&n.push(`- \u8BC6\u522B\u951A\u70B9: ${e.recognitionAnchors.join("\uFF1B")}`);let i=e.identityProfile;if(i){let r=[i.apparent_gender,i.apparent_age].filter(Boolean).join("\uFF0C");r&&n.push(`- \u5E74\u9F84\u6027\u522B: ${r}`),i.face_shape&&n.push(`- \u8138\u578B\u4E0B\u988C: ${i.face_shape}`),i.brows_eyes&&n.push(`- \u7709\u773C: ${i.brows_eyes}`),i.nose&&n.push(`- \u9F3B\u90E8: ${i.nose}`),i.mouth&&n.push(`- \u5507\u5F62\u5634\u89D2: ${i.mouth}`),i.skin_features&&n.push(`- \u80A4\u8272\u9762\u90E8: ${i.skin_features}`),i.hair&&n.push(`- \u53D1\u578B: ${i.hair}`),i.build&&n.push(`- \u4F53\u6001: ${i.build}`),i.persistent_marks.length&&n.push(`- \u56FA\u5B9A\u6807\u8BB0: ${i.persistent_marks.join("\uFF1B")}`),i.voice&&n.push(`- \u58F0\u7EBF: ${i.voice}`)}return e.aliases.length&&n.push(`- \u66FE\u7528\u79F0\u547C: ${e.aliases.join("\u3001")}`),e.states.length&&n.push(`- \u5DF2\u77E5\u9020\u578B: ${e.states.map(r=>{let s=ds(r.description,t?30:90);return s?`${r.name}\uFF08${s}\uFF09`:r.name}).join(" / ")}`),n.push(`- \u51FA\u73B0: ep ${e.firstEpisode}\u2013${e.lastEpisode}`),e.status==="provisional"&&n.push(`- \u8EAB\u4EFD\u672A\u786E\u8BA4\uFF1A\u672C\u96C6\u82E5\u51FA\u73B0\u4E66\u9762\u59D3\u540D\u6216\u53F0\u8BCD\u672C\u540D\uFF0C\u7528 canonicalize \u4ECE\u300C${e.name}\u300D\u5347\u7EA7\u89C4\u8303\u540D`),n}function hh(e,t){let n=ds(e.appearance||e.role||"",t?30:60),o=e.states.map(i=>i.description?`${i.name}\uFF08${ds(i.description,t?20:60)}\uFF09`:i.name).join(" / ");return`- ${e.name} \xB7${e.importance}${n?`\uFF1A${n}`:""}${o?`\uFF1B\u72B6\u6001\uFF1A${o}`:""}`}function yh(e,t,n){let o=[];o.push(`# \u5DF2\u77E5\u8BBE\u5B9A\uFF08\u89E3\u6790\u7B2C ${e.lastEpisode+1} \u96C6\u65F6\u5BF9\u7167\u672C\u8868\uFF09`,""),o.push("\u8BA4\u5F97\u51FA\u7684\u4EBA/\u7269\u6CBF\u7528\u5176**\u89C4\u8303\u540D**\uFF0C\u522B\u81EA\u5DF1\u65B0\u8D77\u540D\uFF1B\u4EBA\u7269\u4F18\u5148\u6BD4\u5BF9\u8BC6\u522B\u951A\u70B9\u4E0E\u7ED3\u6784\u5316\u8EAB\u4EFD\u753B\u50CF\uFF0C\u670D\u88C5\u53EA\u4F5C\u5F31\u8F85\u52A9\u3002","");let i=e.registry.filter(a=>a.kind==="actor"),r=e.registry.filter(a=>a.kind==="location"),s=e.registry.filter(a=>a.kind==="prop");if(i.length){o.push("## \u4EBA\u7269","");for(let a of i)o.push(...JI(a,n),"")}if(r.length||s.length){o.push("## \u573A\u666F / \u9053\u5177","");for(let a of r)o.push(hh(a,n));for(let a of s)o.push(hh(a,n));o.push("")}let c=e.digests.filter(a=>a.episode>e.lastEpisode-t);if(c.length){o.push("## \u5267\u60C5\u8FDB\u5C55","");for(let a of[...c].sort((d,p)=>d.episode-p.episode))o.push(a.outcome==="skipped"?`\u7B2C${a.episode}\u96C6\u5DF2\u4EBA\u5DE5\u8DF3\u8FC7\uFF0C\u5267\u60C5\u672A\u77E5\u3002`:`\u7B2C${a.episode}\u96C6\uFF1A${n?ds(a.synopsis,40):a.synopsis}`);o.push("")}if(e.openThreads.length){o.push("## \u672A\u95ED\u5408\u7EBF\u7D22\uFF08\u82E5\u672C\u96C6\u4EA4\u4EE3\u4E86\uFF0C\u7528 open_threads.closed \u5F15\u7528\u5176 [id] \u5173\u95ED\uFF09","");for(let a of e.openThreads)o.push(`- [${a.id}] ${a.text}`);o.push("")}return o.join(`
267
+ `)}function $a(e){for(let t=DI;t>=1;t--){let n=yh(e,t,!1);if(n.length<=GI)return n}return yh(e,1,!0)}function $o(e){let t=new Map;for(let n of e)for(let o of[n.identitySeed,...n.aliases])xe(o)!==xe(n.name)&&t.set(o,n.name);return t}function KI(e){let t=e.identityProfile,n=[];if(t){let o=[t.apparent_gender,t.apparent_age].filter(Boolean).join("\uFF0C");o&&n.push(`\u5916\u89C2\u5E74\u9F84\u4E0E\u6027\u522B\uFF1A${o}`),t.face_shape&&n.push(`\u8138\u578B\u4E0B\u988C\uFF1A${t.face_shape}`),t.brows_eyes&&n.push(`\u7709\u773C\uFF1A${t.brows_eyes}`),t.nose&&n.push(`\u9F3B\u90E8\uFF1A${t.nose}`),t.mouth&&n.push(`\u5507\u5F62\u53E3\u5468\uFF1A${t.mouth}`),t.skin_features&&n.push(`\u80A4\u8272\u9762\u90E8\uFF1A${t.skin_features}`),t.hair&&n.push(`\u5934\u53D1\uFF1A${t.hair}`),t.build&&n.push(`\u9AA8\u67B6\u4F53\u578B\uFF1A${t.build}`),t.persistent_marks.length&&n.push(`\u56FA\u5B9A\u6807\u8BB0\uFF1A${t.persistent_marks.join("\u3001")}`),t.voice&&n.push(`\u58F0\u7EBF\uFF1A${t.voice}`)}return e.recognitionAnchors.length&&n.push(`\u8BC6\u522B\u951A\u70B9\uFF1A${e.recognitionAnchors.join("\uFF1B")}`),e.role&&n.push(`\u89D2\u8272\u8BED\u5883\uFF1A${e.role}`),n.map(o=>o.replace(/[。;]+$/,"")).join("\uFF1B")}function _h(e,t){let n=new Map,o=new Map,i=(s,c)=>{let a=xe(s),d=c.trim();!d||xe(d)===a||(o.has(a)||o.set(a,new Set),o.get(a).add(d))};for(let s of t){n.set(xe(s.name),s.importance);for(let c of s.aliases)n.set(xe(c),s.importance);n.set(xe(s.identitySeed),s.importance);for(let c of new Set([s.identitySeed,...s.aliases]))i(s.name,c)}let r=(s,c)=>{for(let a of s??[]){let d=String(a[c]??""),p=[d,...a.aliases??[]],l;for(let m of p)if(l=t.find(h=>xe(h.name)===xe(m)||xe(h.identitySeed)===xe(m)||h.aliases.some(g=>xe(g)===xe(m))),l)break;a.importance=l?.importance??n.get(xe(d))??"featured";let f=o.get(xe(d));if(f?.size&&(a.aliases=[...new Set([...a.aliases??[],...f])]),!l)continue;let u=l.kind==="actor"?KI(l):[l.appearance,l.role].map(m=>(m?.trim()??"").replace(/[。;]+$/,"")).filter(Boolean).join("\uFF1B");u&&(a.description=`${u}\u3002`);for(let m of a.states??[]){let h=l.states.find(g=>Mn(g.name)===Mn(m.state_name));h?.description?m.description=h.description:m.state_name==="default"&&l.kind!=="actor"&&l.appearance&&(m.description=l.appearance)}}};return r(e.actors,"actor_name"),r(e.locations,"location_name"),r(e.props,"prop_name"),e}function Eh(e,t,n){let o=$o(t.registry),i=d=>o.get(d)??d,r=d=>{let p=d.indexOf(":"),l=d.slice(0,p);return p>0&&(l==="system"||l==="broadcast"||l==="offscreen"||l==="group")?{kind:l,label:d.slice(p+1)}:ct(d)?{kind:"group",label:d}:{name:i(d)}},s=0,c={title:n,episodes:e.map(d=>({identity_key:`comic:${d.document_id}`,episode_id:`ep_${String(d.episode).padStart(3,"0")}`,title:d.title,scenes:d.output.scenes.map((p,l)=>{let f=`comic:${d.document_id}:scene:${l+1}`,u=p.characters.flatMap(h=>h.states.length?h.states.map(g=>({name:i(h.name),state:g})):[{name:i(h.name)}]),m=p.actions.map((h,g)=>{let w={kind:"comic",document_id:d.document_id,pages:h.pages,regions:h.regions},y={identity_key:`${f}:action:${g+1}`,type:h.type,content:h.content,extend:{scriptctl:{source:w}}};if((h.type==="dialogue"||h.type==="inner_thought")&&(y.speaker=r(h.speaker),h.parenthetical&&(y.parenthetical=h.parenthetical),"name"in y.speaker)){let _=y.speaker.name;u.some(S=>S.name===_)||u.push({name:_})}return y});return{identity_key:f,scene_id:`scn_${String(++s).padStart(3,"0")}`,environment:{...p.space?{space:p.space}:{},...p.time?{time:Lo(p.time)}:{}},location:p.location?{name:i(p.location)}:null,actors:u,props:[...new Set(p.props.map(i))].map(h=>({name:h})),actions:m}})}))},a=new Set(t.registry.map(d=>`${d.kind}:${d.name}`));for(let d of c.episodes)for(let p of d.scenes){let f=[...p.actors.map(u=>`actor:${u.name}`),...p.props.map(u=>`prop:${u.name}`),...p.location?[`location:${p.location.name}`]:[]].filter(u=>!a.has(u));if(f.length)throw new x(`Comic scene references assets absent from the registry: ${f.join(", ")}`,{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"The episode must register every referenced character, location and key prop.",data:{actual:f}})}return c}var lr=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();function jI(e,t,n){let o=$o(t),i=l=>o.get(l)??l,r=new Map;for(let l of t){let f=i(l.name),m=t.find(g=>g.kind===l.kind&&lr(g.name)===lr(f))??l,h=`${l.kind}:${lr(f)}`;r.has(h)||r.set(h,`${n}:${m.kind}:${m.firstEpisode}:${lr(m.identitySeed)}`)}let s={},c={},a={},d={},p={actor:s,location:c,prop:a};for(let l of e){let f=l.names[0]??l.provisional_id,u=r.get(`${l.kind}:${lr(f)}`)??`${n}:${l.kind}:source:${lr(f)}`;p[l.kind][l.provisional_id]=u,d[l.provisional_id]=Object.fromEntries(l.states.map(m=>[m.id,`${u}:state:${Mn(m.name)}`]))}return{actor:s,location:c,prop:a,state:d}}function Da(e,t,n,o){let{script:i,assets:r,identityKeys:s}=Oa(e);_h(i,t.registry);let c=La(i),{script:a,idMap:d}=Ma(c),p=wt(a);if(!p.ok)return{initial:i,final:a,idMap:d,validation:p,identityMap:o,scriptV4:null};let l=ar(Tt(c),o,{...jI(r,t.registry,n),...s}),f=l.script,u=Pe(f);return{initial:i,final:f,scriptV4:f,idMap:d,identityMap:l.identityMap,validation:{...u,warnings:[...u.warnings,...sr(f)]}}}import*as xh from"node:fs";import*as no from"node:path";import{createHash as zI}from"node:crypto";import{PDFDocument as HI}from"pdf-lib";import*as Ga from"node:path";function Ba(e){let t=Ga.basename(e,Ga.extname(e)),n=t.match(/第\s*0*(\d+)\s*[集话回]/u)??t.match(/(?:^|[._\-\s])(?:ep(?:isode)?|e)\s*[._\-\s]*0*(\d+)(?=$|[._\-\s])/iu);if(n)return Number(n[1]);let o=t.match(/\d+/);return o?Number(o[0]):null}function FI(e){let t=e.kind==="comic-file"?[e.path]:e.files,n=t.map(i=>({path:i,sourceNumber:Ba(i)})),o=n.flatMap(i=>i.sourceNumber===null?[]:[i.sourceNumber]);if(o.length>0&&o.length!==t.length||new Set(o).size!==o.length)throw new x("Comic chapter ordering is ambiguous.",{exitCode:k,errorCode:"INGEST_COMIC_DISCOVERY",hint:"Give every PDF a unique chapter number, or use unnumbered filenames that sort in reading order.",data:{actual:t.map(i=>no.basename(i))}});return n.sort((i,r)=>i.sourceNumber!==null&&r.sourceNumber!==null?i.sourceNumber-r.sourceNumber:no.basename(i.path).localeCompare(no.basename(r.path),"zh-Hans",{numeric:!0}))}async function Sh(e){let t=[];for(let[n,o]of FI(e).entries()){let i=xh.readFileSync(o.path),s=(await HI.load(i,{updateMetadata:!1})).getPageCount();if(!s)throw new x("PDF is outside the document provider limits.",{exitCode:k,errorCode:"INGEST_COMIC_SIZE",hint:"Provide a PDF containing at least one readable page.",data:{actual:[`${o.path}: ${s} pages, ${i.length} bytes`]}});t.push({episode:n+1,document_id:`chapter-${String(n+1).padStart(3,"0")}`,source_number:o.sourceNumber,title:no.basename(o.path,no.extname(o.path)),path:no.resolve(o.path),sha256:zI("sha256").update(i).digest("hex"),page_count:s,size_bytes:i.length})}return t}function Ih(e,t){let n=e.find((o,i)=>{let r=t[i];return!r||o.sha256!==r.sha256||o.source_number!==r.source_number||o.title!==r.title});if(n)throw new x("The comic source prefix changed.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Restore the original chapters or use a fresh workspace. Only tail chapters may be appended.",data:{actual:[n.title]}})}import{PDFDocument as QI,StandardFonts as YI,rgb as qI,pushGraphicsState as ZI,popGraphicsState as WI,concatTransformationMatrix as Ja}from"pdf-lib";async function Ah(e){let t=await QI.load(e),n=await t.embedFont(YI.Helvetica),o=qI(0,.45,.85);for(let i of t.getPages()){let r=i.getCropBox(),s=(i.getRotation().angle%360+360)%360,c=s===90||s===270,a=c?r.height:r.width,d=c?r.width:r.height;switch(i.pushOperators(ZI()),s){case 90:i.pushOperators(Ja(0,1,-1,0,r.x+r.width,r.y));break;case 180:i.pushOperators(Ja(-1,0,0,-1,r.x+r.width,r.y+r.height));break;case 270:i.pushOperators(Ja(0,-1,1,0,r.x,r.y+r.height));break;default:i.pushOperators(Ja(1,0,0,1,r.x,r.y))}let p=a/70;for(let l=0;l<=1e3;l+=50){let f=d*(1-l/1e3);i.drawLine({start:{x:0,y:f},end:{x:a,y:f},thickness:.5,color:o,opacity:.3});let u=`y=${l}`,m=Math.max(1,Math.min(d-p,f+1));for(let h of[1,a-n.widthOfTextAtSize(u,p)-1])i.drawText(u,{x:h,y:m,size:p,font:n,color:o})}for(let l=100;l<1e3;l+=100){let f=a*l/1e3;i.drawLine({start:{x:f,y:0},end:{x:f,y:d},thickness:.5,color:o,opacity:.3});for(let u=0;u<1e3;u+=250)i.drawText(`x=${l}`,{x:f+1,y:d*(1-u/1e3)-p,size:p,font:n,color:o})}i.pushOperators(WI())}return t.save()}import*as kh from"node:fs";import*as bh from"node:path";import XI from"proper-lockfile";async function Do(e,t){let n=bh.resolve(e);kh.mkdirSync(n,{recursive:!0});let o=null;try{o=await XI.lock(n,{realpath:!1,stale:12e4,update:1e4,retries:0})}catch(i){throw new x("The ingest workspace is busy.",{exitCode:X,errorCode:"INGEST_WORKSPACE_BUSY",hint:"Wait for the other ingest or skip command to finish, then retry.",data:{actual:[n,i instanceof Error?i.message:String(i)]}})}try{return await t()}finally{await o()}}import*as oo from"node:fs";import*as sl from"node:path";import{PDFDocument as rl}from"pdf-lib";import{z as ur}from"zod";var Oh=ur.object({starts:ur.array(ur.object({page:ur.number().int().min(1),title:ur.string().min(1)}))}),eA="\u9605\u8BFB\u6F2B\u753B PDF \u5E76\u8BC6\u522B\u5B9E\u9645\u8BDD/\u7AE0\u8282\u8FB9\u754C\u3002\u53EA\u8F93\u51FA\u672C\u6BB5\u5185\u786E\u5B9E\u5F00\u59CB\u7684\u65B0\u8BDD\u7684\u8D77\u59CB\u7269\u7406\u9875\u7801\u548C\u539F\u7A3F\u6807\u9898\u3002\u4F9D\u636E\u8BDD\u53F7\u3001\u7AE0\u8282\u6249\u9875\u3001\u6807\u9898\u53CA\u53D9\u4E8B\u8FDE\u7EED\u6027\u7EFC\u5408\u5224\u65AD\uFF1B\u573A\u666F\u5207\u6362\u3001\u56DE\u5FC6\u3001\u6362\u9875\u548C\u5E7F\u544A\u4E0D\u662F\u65B0\u8BDD\u3002\u8F93\u5165\u53EF\u80FD\u4ECE\u4E00\u8BDD\u4E2D\u95F4\u5F00\u59CB\uFF0C\u5EF6\u7EED\u524D\u6BB5\u7684\u5185\u5BB9\u4E0D\u7B97\u65B0\u8BDD\u3002\u7B2C\u4E00\u6BB5\u4ECE\u539F\u6587\u6863\u7B2C\u4E00\u9875\u5F00\u59CB\u65F6\uFF0C\u4E3A\u7B2C\u4E00\u8BDD\u5EFA\u7ACB\u8D77\u70B9\uFF0C\u5C01\u9762\u548C\u76EE\u5F55\u968F\u9996\u8BDD\u4FDD\u7559\u3002\u591A\u8BDD\u5408\u96C6\u9010\u9879\u5217\u51FA\u5404\u8BDD\uFF1B\u5355\u8BDD\u6587\u4EF6\u53EA\u6709\u4E00\u4E2A\u8D77\u70B9\u3002page \u4F7F\u7528\u672C\u6B21\u8F93\u5165 PDF \u4ECE 1 \u5F00\u59CB\u7684\u7269\u7406\u9875\u7801\u3002\u6807\u9898\u4FDD\u7559\u539F\u8BDD\u53F7\u548C\u53EF\u8BFB\u8BDD\u540D\uFF1B\u65E0\u6CD5\u786E\u8BA4\u8BDD\u53F7\u65F6\u4F7F\u7528\u7B80\u77ED\u5185\u5BB9\u6807\u9898\u3002";async function vh(e,t,n,o){let i=[];for(let r of e){let s=`sources/${r.sha256}.chapters.json`,c,a=await rl.load(oo.readFileSync(r.path));if(t.has(s))c=t.readJson(s);else{c=[];for(let d=0;d<r.page_count;){let p=Math.min(40,r.page_count-d),l;for(;;){let m=await rl.create();for(let h of await m.copyPages(a,Array.from({length:p},(g,w)=>d+w)))m.addPage(h);if(l=await m.save(),l.length<=4e7||p===1)break;p=Math.ceil(p/2)}let f=t.path(`sources/${r.sha256}.scan.pdf`);oo.mkdirSync(sl.dirname(f),{recursive:!0}),hi(f,Buffer.from(l)),process.stderr.write(`\u8BC6\u522B\u6F2B\u753B\u7AE0\u8282 \xB7 ${r.title} \xB7 \u539F\u7A3F ${d+1}\u2013${d+p} / ${r.page_count} \u9875
268
+ `);let u=await n.prepare(f,o);try{let m=await n.generate({media:u,system:eA,user:`\u539F\u6587\u4EF6\uFF1A${r.title}\uFF0C\u5171 ${r.page_count} \u9875\u3002\u672C\u6BB5\u4E3A\u539F\u7A3F\u7B2C ${d+1}\u2013${d+p} \u9875\u3002\u5DF2\u8BC6\u522B\u8D77\u70B9\uFF1A${JSON.stringify(c)}\u3002`,responseJsonSchema:ur.toJSONSchema(Oh,{target:"openapi-3.0"}),signal:o}),h=Oh.parse(JSON.parse(m.text));c.push(...h.starts.filter(g=>g.page<=p).map(g=>({...g,page:d+g.page})))}finally{await n.release(u,o)}d+=p}c=[...new Map(c.sort((d,p)=>d.page-p.page).map(d=>[d.page,d])).values()],c.length?c[0].page=1:c.push({page:1,title:r.title}),t.writeJson(s,c)}for(let[d,p]of c.entries()){let l=(c[d+1]?.page??r.page_count+1)-1,f=i.length+1,u=c.length===1?r.path:t.path(`sources/${r.sha256}.${p.page}-${l}.pdf`);if(!oo.existsSync(u)){let m=await rl.create();for(let h of await m.copyPages(a,Array.from({length:l-p.page+1},(g,w)=>p.page-1+w)))m.addPage(h);oo.mkdirSync(sl.dirname(u),{recursive:!0}),hi(u,Buffer.from(await m.save()))}i.push({...r,episode:f,document_id:`chapter-${String(f).padStart(3,"0")}`,title:c.length===1?r.title:p.title,path:u,page_count:l-p.page+1,size_bytes:oo.statSync(u).size,original_path:r.path,original_page_count:r.page_count,start_page:p.page,end_page:l})}}return i}import{z as Rh}from"zod";var Ka=fn,tA=Ka(16);function fn(e,t){e=e-0;let n=al(),o=n[e];if(fn.YRXMyC===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};fn.NlCFnI=i,fn.oGorNA={},fn.YRXMyC=!0}let r=n[0];fn.WQOQgA!==r&&(fn.oGorNA={},fn.WQOQgA=r);let s=fn.oGorNA[e];return s===void 0?(o=fn.NlCFnI(o),fn.oGorNA[e]=o):o=s,o}function cl(e,t){let n=Ka,o=ga[n(24)](JSON[n(18)](e)),i=a=>{let d=n;throw new x(d(44)+a[d(4)]("; "),{exitCode:k,errorCode:d(7),hint:d(2),data:{actual:a}})};if(!o[n(28)])return i(o[n(13)][n(19)][n(25)](0,8)[n(21)](a=>a[n(42)][n(4)](".")+": "+a[n(37)]));let r=o[n(34)],s=new Set;for(let a of r[n(20)])for(let d of a[n(12)]){if(d[n(27)][n(43)]((l,f)=>l>t||f>0&&l<=d[n(27)][f-1]))return i([n(30)+d[n(27)][n(4)](", ")+n(5)+t+n(33)]);let p=qr(d[n(27)],d[n(38)]);if(p[n(26)])return i(p);for(let l of d[n(27)])s[n(40)](l)}for(let a of r[n(0)]){if(a[n(1)]>t||s[n(36)](a[n(1)]))return i([n(15)+a[n(1)]]);s[n(40)](a[n(1)])}let c=Array[n(29)]({length:t},(a,d)=>d+1)[n(31)](a=>!s[n(36)](a));return c[n(26)]?i([n(6)+c[n(4)](", ")]):r}async function Mh(e,t,n,o,i,r,s){let c=Ka,a=await e[c(22)]({media:t,system:tA,user:c(11)+n+c(9)+o+c(3)+i,responseJsonSchema:Rh[c(17)](Mm,{target:c(23)}),signal:s});return r(a[c(10)]),cl(a[c(10)],o)}function al(){let e=["AwDUB3jLzf9WywDLCW","CgfNzq","sw5ZCgvJDcbLCc8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ym5yAf5A656Ag65BQp5Q2J56gU77YB5lUf5Pw06Ag156M655M944cb5Bcb6z2I44cb5yI25l2C5l+H5OgV5y+V5lUL5yIx5ywLigLNBM9YzwrFCgfNzxmG5BM25yAz5y6F5zUG44cc5lIn6kAb5zYOigfJDgLVBNmG5lIoigLNBM9YzwrFCgfNzxmG5zcm5PE255M76k6W5zcm5lIa6Ag144ccC3LUB3bZAxmG5y+Q5QAc5OUS5PYS6k+D77Ym5lIn6io95lUJ5PU/5Q2J5PAh44cc","Dg9ku09ou2nOzw1H","CgfYC2u","AxnZDwvZ","C2nLBMvZ","BwfW","z2vUzxjHDgu","B3bLBMfWAs0ZlJa","C2fMzvbHCNnL","C2XPy2u","BgvUz3rO","CgfNzxm","C3vJy2vZCW","zNjVBq","sw52ywXPzcbVCIb1BM9YzgvYzwqGC291CMnLihbHz2vZoIa","zMLSDgvY","5Qc55O2U5y6F5RYR55s75zkm5BEY6l2S5B2v5Q2J5PAh5Pw055cg5A6m5Pw06lwe5lQN55M76k6W44cc6l+u5zUEihjLz2LZDhj5x2rLBhrHiowVUEIXOE+8Jos/NEEvMEATO+EHRUEzU+IUSo+8JoIHPEM9KoATO+AwH+wUNUMzHEw8LEEuQoEAHos6UUEjQEoaGEwCSoEcUEwsJowfS+MuRUMbK+wfT++8JoINHoImG+wqJEs4JUw8LEEuQoMaKowTL+s4GoIhTooaGUs+NEAnRUwoN+EOV+ApJ+I/SowpR+INGEwKLUINGU+8M+wqJos4GoI6Q+s7VEEuQowiQ+wqJEwsJcbJyw5VBMLJywXPEMuG5B2s5BM244cc5l+D55wz5BEY6l2S5B2v5Q2J5PAh55Qe5ywO6yoO5yAf5A6544cc","ihbHz2vZlG","zgf0yq","cUMCGoIMGEINO+wgS++8MG","AgfZ","BwvZC2fNzq","CMvNAw9UCW","CMvNAxn0CNLFzgvSDge","ywrK","cUw3SUACIEI9Row9LE+8MG","Cgf0Aa","C29Tzq","q29TAwmGzxbPC29KzsbMywLSzwqGDhjHBNnJCMLWDcb2ywXPzgf0Aw9UoIa"];return al=function(){return e},al()}async function Nh(e,t,n,o,i,r){let s=Ka,c=ga[s(8)][s(39)],a=await e[s(22)]({media:t,signal:r,system:s(32),user:o+s(35)+i+s(41)+JSON[s(14)](n),responseJsonSchema:Rh[s(17)](c,{target:s(23)})});return c[s(18)](JSON[s(18)](a[s(10)]))}function ja(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function nA(e){switch(e.errorCode){case"LLM_CREDENTIAL_MISSING":return{failure_type:"authentication",failure_code:"authentication_failed"};case"LLM_CONFIG_INVALID":return{failure_type:"provider",failure_code:"request_rejected"};case"INGEST_VIDEO_INLINE_TOO_LARGE":return{failure_type:"media",failure_code:"media_too_large"};case"INGEST_COMIC_SERIAL_FAILED":case"INGEST_VIDEO_SERIAL_FAILED":return{failure_type:"pipeline",failure_code:"serial_parse_failed"};case"INGEST_VIDEO_TIMESTAMP_MISSING":return{failure_type:"validation",failure_code:"script_validation_failed"};case"INGEST_SOURCE_MISMATCH":return{failure_type:"pipeline",failure_code:"source_mismatch"};case"INGEST_PIPELINE_MISMATCH":return{failure_type:"pipeline",failure_code:"pipeline_mismatch"};case"INGEST_VALIDATION_FAILED":return{failure_type:"validation",failure_code:"script_validation_failed"};default:return{failure_type:"unknown",failure_code:"unknown"}}}function oA(e){if(e instanceof T)return{failure:e.failure,attempts:e.modelFailures};if(e instanceof x){let t=e.errorCode==="INGEST_VALIDATION_FAILED"||e.errorCode==="INGEST_VIDEO_SERIAL_FAILED"||e.errorCode==="INGEST_COMIC_SERIAL_FAILED";return{failure:Ut(nA(e),{retryable:t,message:e.message}),attempts:[]}}return{failure:Ut({failure_type:"unknown",failure_code:"unknown"},{retryable:!1,message:e instanceof Error?e.message:String(e)}),attempts:[]}}function za(e,t,n){let o=oA(e);return{schema_version:1,unit:{kind:"episode",episode:t},phase:n,occurred_at:new Date().toISOString(),...o}}function Uh(e){return e.retryable?"Inspect the episode error sidecar and rerun `scriptctl ingest` to resume from this episode.":e.failure_type==="policy"?"Inspect the provider policy reason in the episode error sidecar; rerunning the same source is unlikely to help.":e.failure_type==="authentication"||e.failure_type==="authorization"?"Fix the provider credential or permission reported in the episode error sidecar before rerunning.":"Inspect the typed episode error sidecar and resolve the terminal failure before rerunning."}function Lh(e,t){return typeof e=="string"&&t.some(n=>n===e)}function fr(e){return typeof e=="string"?e:void 0}function iA(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!ja(n)||typeof n.category!="string"||typeof n.probability!="string"||typeof n.blocked!="boolean")return;t.push({category:n.category,probability:n.probability,blocked:n.blocked})}return t}function rA(e){let t=e.provider_source,n=e.provider_reason;return{provider:fr(e.provider),model:fr(e.model),operation:fr(e.operation),http_status:typeof e.http_status=="number"?e.http_status:void 0,system_code:fr(e.system_code),provider_source:Lh(t,["prompt","candidate"])?t:void 0,provider_reason:Lh(n,["SAFETY","PROHIBITED_CONTENT","BLOCKLIST","SPII","RECITATION","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION","OTHER","UNSPECIFIED","UNKNOWN"])?n:void 0,provider_reason_raw:fr(e.provider_reason_raw),finish_message:fr(e.finish_message),safety_ratings:iA(e.safety_ratings),details:Array.isArray(e.details)&&e.details.every(i=>typeof i=="string")?e.details:void 0}}function ls(e){if(!ja(e))return null;let t=su(e.failure_type,e.failure_code);return!t||typeof e.retryable!="boolean"||typeof e.message!="string"?null:Ut(t,{...rA(e),retryable:e.retryable,message:e.message})}function us(e){if(!ja(e)||e.schema_version!==1)return null;let t=e.unit;if(!ja(t)||t.kind!=="episode"||typeof t.episode!="number"||typeof e.phase!="string"||typeof e.occurred_at!="string")return null;let n=ls(e.failure);if(!n||!Array.isArray(e.attempts))return null;let o=[];for(let i of e.attempts){let r=ls(i);if(!r)return null;o.push(r)}return{schema_version:1,unit:{kind:"episode",episode:t.episode},phase:e.phase,occurred_at:e.occurred_at,failure:n,attempts:o}}var Ph="comic-1",Ha=e=>String(e).padStart(3,"0"),Ch=["script.initial.json","id_map.json","validation.json","context.json","v4_identity_map.json","script.json"];function Fa(e,t,n){let o=Da(Eh(e,t.context,n),t.context,"comic",t.identityMap);if(!o.scriptV4||!o.validation.ok)throw new x("Comic script failed validation.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect the current episode response and rerun ingest with the same source and workspace.",data:{actual:o.validation.errors.slice(0,8).map(i=>`${i.path}: ${i.message}`)}});for(let[i,r]of o.scriptV4.episodes.entries())r.synopsis=e[i].output.synopsis;return{...o,scriptV4:o.scriptV4}}function dl(e,t,n){e.writeJson("script.initial.json",t.initial),e.writeJson("id_map.json",t.idMap),e.writeJson("validation.json",t.validation),e.writeJson("context.json",n),e.writeJson("v4_identity_map.json",t.identityMap),e.writeJson("script.json",t.scriptV4)}async function aA(e){let t=On(e.sourcePath);if(t.kind!=="comic-file"&&t.kind!=="comic-directory")throw new x("Expected PDF comic source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=new ft(Ii.resolve(e.workspacePath));n.ensure();let o=n.has("manifest.json")?n.readJson("manifest.json"):null;if(o&&o.pipeline_version!==Ph)throw new x("This workspace belongs to another ingest pipeline.",{exitCode:k,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Choose a fresh workspace."});if(!o&&n.has("script.json"))throw new x("Workspace already contains an unmanaged script.json.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Choose a fresh workspace."});let i=await Sh(t),r=o&&!o.episodes.some(w=>w.original_path)?i:await vh(i,n,e.executor.documentPort("ingest.comic-serial"),e.signal);o&&Ih(o.episodes,r);let s={version:1,pipeline_version:Ph,updated:new Date().toISOString(),source:{kind:t.kind,path:Ii.resolve(t.path),sha256:sA("sha256").update(r.map(w=>w.sha256).join(`
269
+ `)).digest("hex")},episodes:r,...o?.current_error?{current_error:o.current_error}:{}};if(e.force){for(let w of o?.episodes??[])for(let y of["json","response.json","context.md","error.json","input.pdf"])io.rmSync(n.path(`ep/ep_${Ha(w.episode)}.${y}`),{force:!0});for(let w of["checkpoint.json","timings.json",...Ch])io.rmSync(n.path(w),{force:!0});delete s.current_error}n.writeJson("manifest.json",s);let c=n.has("checkpoint.json")?n.readJson("checkpoint.json"):{context:Vo(),identityMap:Co()},a=r.slice(0,c.context.lastEpisode).map(w=>n.readJson(`ep/ep_${Ha(w.episode)}.json`)),d=io.realpathSync(t.path),p=Ii.basename(d,t.kind==="comic-file"?Ii.extname(d):""),l=new To(n,e.executor),f=new dr(w=>n.writeJson("timings.json",w));f.phaseStart("serial"),f.serialStart(r.length,r.length);let u="failed",m=0,h=a.length,g;try{if(a.length>0){dl(n,Fa(a,c,p),c.context);for(let _ of a)n.clearError(`ep/ep_${Ha(_.episode)}.error.json`);s.current_error&&s.current_error.unit.episode<=c.context.lastEpisode&&(delete s.current_error,s.updated=new Date().toISOString(),n.writeJson("manifest.json",s))}else for(let _ of Ch)io.rmSync(n.path(_),{force:!0});for(let _ of r){if(e.signal?.throwIfAborted(),_.episode<=c.context.lastEpisode){e.executor.recordReuse("ingest.comic-serial");let M=Date.now();l.flush({scope:{kind:"episode",episode:_.episode},status:"reused",startedAtMs:M,endedAtMs:M}),f.windowDone(_.episode,_.episode,0,!0);continue}if(e.step&&m>=1)break;let S=Date.now(),E=`ep/ep_${Ha(_.episode)}`,A=s.current_error?.unit.episode===_.episode?s.current_error.failure.message:void 0,b=$a(c.context)+(A?`
269
270
 
270
271
  \u672C\u8BDD\u4E0A\u4E00\u6B21\u8F93\u51FA\u5C1A\u672A\u88AB\u63A5\u53D7\uFF0C\u5931\u8D25\u539F\u56E0\uFF1A${A}\u3002\u8BF7\u6839\u636E\u539F PDF \u8FD4\u56DE\u4FEE\u6B63\u540E\u7684\u5B8C\u6574\u672C\u8BDD\uFF1B\u5C24\u5176\u9010\u9879\u6838\u5BF9\u6BCF\u4E2A\u5730\u70B9\u3001\u4EBA\u7269\u548C\u5173\u952E\u9053\u5177\u5F15\u7528\u662F\u5426\u5DF2\u7ECF\u767B\u8BB0\u3002`:"");n.writeText(`${E}.context.md`,b),process.stderr.write(`\u6F2B\u753B ${_.episode}/${r.length} \xB7 ${_.title} \xB7 ${_.page_count} \u9875
271
- `);let C="upload";try{m??=e.executor.documentPort("ingest.comic-serial");let R=n.path(`${E}.input.pdf`);gi(R,Buffer.from(await xh(oo.readFileSync(_.path))));let I=await m.prepare(R,e.signal),O;try{C="generate";let X=A&&n.has(`${E}.response.json`)&&s.current_error?.phase==="validation"?sl(oo.readFileSync(n.path(`${E}.response.json`),"utf8"),_.page_count):await Oh(m,I,_.title,_.page_count,b,j=>n.writeText(`${E}.response.json`,j),e.signal);O={episode:_.episode,document_id:_.document_id,title:_.title,output:X}}finally{await m.release(I,e.signal)}C="validation";let N=ds(structuredClone(c.context),O.output,_.episode),U=[...a,O],M;try{M=za(U,{context:N,identityMap:c.identityMap},p)}catch(X){if(!(X instanceof S)||X.errorCode!=="INGEST_VALIDATION_FAILED")throw X;process.stderr.write(`\u6B63\u5728\u6839\u636E\u539F\u7A3F\u8865\u5168\u4EBA\u7269\u3001\u5730\u70B9\u548C\u9053\u5177\u767B\u8BB0\uFF0C\u4FDD\u7559\u5DF2\u8F6C\u5F55\u6B63\u6587\u2026
272
- `);let j=await m.prepare(R,e.signal);try{O.output.registry_delta=await vh(m,j,O.output,b,X.message,e.signal),n.writeJson(`${E}.response.json`,O.output)}finally{await m.release(j,e.signal)}N=ds(structuredClone(c.context),O.output,_.episode),M=za(U,{context:N,identityMap:c.identityMap},p)}let V={context:N,identityMap:M.identityMap};C="checkpoint",n.writeJson(`${E}.json`,O),n.writeJson("checkpoint.json",V),c=V,a.push(O),C="publish",al(n,M,c.context),n.clearError(`${E}.error.json`),delete s.current_error,s.updated=new Date().toISOString(),n.writeJson("manifest.json",s),g++;let F=Date.now();f.windowDone(_.episode,_.episode,F-x,!1),l.flush({scope:{kind:"episode",episode:_.episode},status:"succeeded",startedAtMs:x,endedAtMs:F});let Re=O.output.scenes.reduce((X,j)=>X+j.actions.length,0);process.stderr.write(` \u5DF2\u4FDD\u5B58\uFF1A${O.output.scenes.length} \u573A / ${Re} \u6761\u6B63\u6587
273
- `)}catch(R){let I=ja(R,_.episode,C);throw n.writeJson(`${E}.error.json`,I),n.writeJson("manifest.json",{...s,updated:I.occurred_at,current_error:I}),l.flush({scope:{kind:"episode",episode:_.episode},status:"failed",startedAtMs:x,endedAtMs:Date.now()}),R}}let w=za(a,c,p);al(n,w,c.context);let y=a.length===r.length;return u="succeeded",{workspace:n.root,script_path:n.path("script.json"),kind:"comic",episodes:r.length,processed:g,reused:h,completed:a.length,remaining:r.length-a.length,complete:y,next_episode:y?null:a.length+1,assets:{actors:w.scriptV4.actors.length,locations:w.scriptV4.locations.length,props:w.scriptV4.props.length}}}finally{f.phaseEnd("serial"),f.finish(),l.finish(u)}}async function Uh(e){return Do(e.workspacePath,()=>sA(e))}import*as kt from"node:fs";import*as Qt from"node:path";function aA(e,t){return e.episode!==t.episode?`episode ${e.episode} was replaced by episode ${t.episode}`:e.ext!==t.ext||e.mime!==t.mime?`episode ${e.episode} changed media type`:e.sha256!==t.sha256?`episode ${e.episode} content changed`:null}function Ph(e,t){if(t.length<e.length)return{kind:"incompatible",reason:`source removed ${e.length-t.length} previously accepted episode(s)`};for(let o=0;o<e.length;o+=1){let i=aA(e[o],t[o]);if(i)return{kind:"incompatible",reason:i}}let n=t.slice(e.length);return n.length===0?{kind:"unchanged",appended:[]}:{kind:"append",appended:n}}function Ha(e){for(let t=0;t<e.length;t+=1){let n=t+1,o=e[t].episode;if(o!==n)return`expected episode ${n}, found episode ${o}`}return null}function ur(e){let t=typeof e=="string"?e.trim():"",n=t.match(/^(?:(\d+):)?(\d+):(\d{2})(\.\d{1,3})?$/);if(!n)return t;let o=Number(n[1]??0),i=Number(n[2]),r=Number(n[3]);if(![o,i,r].every(Number.isSafeInteger))return t;let s=o*3600+i*60+r,c=Math.floor(s/3600),a=Math.floor(s%3600/60),d=s%60;return(c>0?`${c}:${String(a).padStart(2,"0")}:${String(d).padStart(2,"0")}`:`${String(a).padStart(2,"0")}:${String(d).padStart(2,"0")}`)+(n[4]??"")}function fr(e,t){if(!e)return e;let n=e.match(/^(\w+):(.+)$/);return n?`${n[1]}:${t.get(n[2])??n[2]}`:t.get(e)??e}var Ch=e=>String(e).padStart(3,"0"),cA={\u5185:"interior",\u5916:"exterior"},dA={act:"action",dlg:"dialogue",think:"inner_thought"},cl={broadcast:"broadcast",system:"system",group:"group",offscreen:"offscreen",prop:"offscreen",location:"offscreen"};function pA(e){let t=e.match(/^(\w+):(.+)$/);if(t&&cl[t[1]]){let n=t[2].trim();return n?{kind:cl[t[1]],label:n}:{kind:cl[t[1]]}}return ct(e)?{kind:"group",label:e.trim()}:{name:e}}function Th(e,t){let n=0,o=e.map((i,r)=>{let s=`video:episode:${i.episode}`,c=new Map;return{identity_key:s,episode_id:`ep_${Ch(r+1)}`,scenes:i.scenes.map(a=>{let d=a.timeRange?.trim()?`time:${a.timeRange.trim()}`:`index:${a.index}`,p=(c.get(d)??0)+1;c.set(d,p);let l=`${s}:scene:${d}:${p}`,f={},u=cA[(a.environment.space??"").trim()],g=Lo(a.environment.time);u&&(f.space=u),g&&(f.time=g);let h=[],m=A=>{h.some(b=>b.name===A)||h.push({name:A})};for(let A of a.characters)A.name&&!ct(A.name)&&(A.states.length===0?h.push({name:A.name}):h.push(...A.states.map(b=>({name:A.name,state:b}))));let w=new Map,y=a.anchors.map(A=>{let b=ur(A.ts),C=b?`time:${b}`:`content:${JSON.stringify([A.kind,A.speaker??"",A.content])}`,R=(w.get(C)??0)+1;w.set(C,R);let I={identity_key:`${l}:action:${C}:${R}`,type:dA[A.kind]??"action",content:A.content};if((A.kind==="dlg"||A.kind==="think")&&A.speaker){let N=pA(A.speaker);I.speaker=N,"name"in N&&m(N.name)}A.parenthetical&&(I.parenthetical=A.parenthetical);let O=ur(A.ts);return O&&(I.extend={timestamp:O}),I}),_=(a.location??"").trim(),x=[],E=new Set;for(let A of a.props??[]){if(!A)continue;let b=A.normalize("NFC").replace(/\s+/g," ").trim();!b||E.has(b)||(E.add(b),x.push({name:A}))}return{identity_key:l,scene_id:`scn_${Ch(++n)}`,...f.space||f.time?{environment:f}:{},location:_?{name:_}:null,actors:h,props:x,actions:y}})}});return{title:t,episodes:o}}var lA=60,uA=6,fA=[-1e3,0,1e3],Gh=/(?:身穿|穿着|服装|造型|衣|裙|袍|衫|夹克|制服|西装|盔甲|装甲|防弹服|套装|裤|靴)/u,dl=/(?:全身|半身|上半身|四分之三身|躯干|胸前|腰部)/u,pl=/(?:站(?:在|立)|坐(?:在|下|起)|跪(?:在|下|倒)?|蹲(?:在|下)?|走(?:在|出|向)|行走|迈步|奔跑|跳起|跃起|转身|抬头|转头)/u,Vh=/(?:特写|近景|脸|面容|五官|正脸|侧脸|侧前脸|双眼|眼眶|眉头|嘴角)/u,Bh=/(?:背对|背影|远处|极远|模糊|运动模糊|脸被遮|面部遮挡|只露出|纯道具|空镜)/u,Jh=/(?:双脚|脚部|膝盖|伤口|手部特写)/u,jh=/(?:画外音|旁白|未入镜|镜外|电话音|广播|\bO\.?S\.?\b)/iu;function Go(e){return e.normalize("NFC").replace(/\s+/g," ").trim()}function Kh(e){let t=e.trim().match(/^(?:(\d{1,2}):)?(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?$/);if(!t)return null;let n=Number(t[1]??0),o=Number(t[2]),i=Number(t[3]);if(o>=60&&t[1]!==void 0||i>=60)return null;let r=String(t[4]??"").padEnd(3,"0");return((n*60+o)*60+i)*1e3+Number(r||0)}function zh(e){let t=e.trim().match(/^(\d+):(\d{2})$/);return t?Number(t[1])*1e3+Number(t[2])*10:null}function Hh(e,t="clock"){return t==="legacy_centiseconds"?zh(e):Kh(e)}function ll(e,t){return e===null?!1:t===void 0||e<=t}function mA(e,t){if(t===void 0)return"clock";let n=e.scenes.flatMap(r=>r.actions.map(Fh)).filter(Boolean),o=n.filter(r=>ll(Kh(r),t)).length;return n.filter(r=>ll(zh(r),t)).length>o?"legacy_centiseconds":"clock"}function $h(e){let t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3),o=e%1e3;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}.${String(o).padStart(3,"0")}`}function Fh(e){let t=e.extend?.timestamp;return typeof t=="string"?t.trim():""}function gA(e,t){let n=new Set([e.actor_name,...e.aliases??[]].map(Go).filter(Boolean));for(let[o,i]of t)Go(i)===Go(e.actor_name)&&n.add(Go(o));return[...n].sort((o,i)=>i.length-o.length)}function Qh(e,t){let n=t.map(o=>e.indexOf(o)).filter(o=>o>=0);return n.length>0?Math.min(...n):-1}function Yh(e,t,n){return t.filter(o=>Qh(e,n.get(o.actor_id)??[])>=0).length}function hA({action:e,actor:t,actorCount:n,allActors:o,surfaces:i,surfacesByActor:r,stateName:s}){let c=e.type==="action"||e.type==="transition",a=Go(c?e.content:"parenthetical"in e?e.parenthetical??"":""),d=Qh(a,i),p=d>=0&&d<=12,l=d>=0,u=e.type==="dialogue"&&"speaker"in e&&"actor_id"in e.speaker&&e.speaker.actor_id===t.actor_id&&!jh.test(a),g=n===1&&(c&&a.length>0||u&&a.length>0&&(pl.test(a)||Vh.test(a)));if(!l&&!u&&!g)return null;let h=p||u?"target_anchor":"scene_fallback",m=u?250:p?65:l?50:45,w=u?250:p?65:l?50:45;n===1&&(m+=20,w+=20);let y=Go(s);return y&&y!=="default"&&y!=="\u9ED8\u8BA4"&&a.includes(y)&&(m+=35),Gh.test(a)&&(m+=30),dl.test(a)?(m+=25,w+=15):pl.test(a)&&(m+=15,w+=5),Vh.test(a)&&(w+=30,dl.test(a)||(m-=20)),Bh.test(a)&&(m-=70,w-=70),Jh.test(a)&&(m-=40),Yh(a,o,r)>=2&&(m-=15,w-=15),{stateScore:m,identityScore:w,selection:h}}function yA(e,t,n){let o=e.type==="action"||e.type==="transition",i="parenthetical"in e?Go(e.parenthetical??""):"";if(!o&&jh.test(i))return null;let r=Go(o?e.content:i),s=o?0:-40;return s-=Yh(r,t,n)*20,Gh.test(r)&&(s+=10),dl.test(r)?s+=10:pl.test(r)&&(s+=5),Bh.test(r)&&(s-=20),Jh.test(r)&&(s-=10),{stateScore:s,identityScore:Number.NEGATIVE_INFINITY,selection:"scene_fallback"}}function us(e,t,n){let o=(n.get(`${e.episode}:${e.milliseconds}`)?.size??0)>1;return e[t]-(o?35:0)}function qh(e,t,n,o,i){let r=new Map;for(let a of e){let d=`${a.episode}:${a.milliseconds}`,p=r.get(d);(!p||us(a,t,n)>us(p,t,n))&&r.set(d,a)}let s=[...r.values()].sort((a,d)=>us(d,t,n)-us(a,t,n)||a.episode-d.episode||a.milliseconds-d.milliseconds).filter(a=>i===null||us(a,t,n)>=i),c=[];for(let a of s)if(!c.some(p=>p.episode===a.episode&&p.sceneId===a.sceneId&&Math.abs(p.milliseconds-a.milliseconds)<3e3)&&(c.push(a),c.length>=o))break;return c}function wA(e,t,n){return qh(e,t,n,1,null)[0]??null}function Dh(e){return e.replace(/[^0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function Fa(e,t,n,o,i){let r=new Map(o.map(m=>[m.episode,m])),s=$o(n.registry),c=new Map(t.actors.map(m=>[m.actor_id,m])),a=new Map(t.actors.map(m=>[m.actor_id,gA(m,s)])),d=new Map,p=new Map,l=new Map,f=new Map;for(let m=0;m<t.episodes.length;m+=1){let w=t.episodes[m],y=m+1,_=r.get(y);if(!_)continue;let x=mA(w,_.duration_ms);for(let E=0;E<w.scenes.length;E+=1){let A=w.scenes[E],b=A.actors.map(C=>c.get(C.actor_id)).filter(C=>!!C);for(let C of A.actors){d.set(C.actor_id,(d.get(C.actor_id)??0)+1);let R=c.get(C.actor_id);if(!R)continue;let I=a.get(R.actor_id)??[R.actor_name],O=[],N=C.state_ids.length===1?C.state_ids[0]:null,U=N?R.states.find(M=>M.state_id===N):null;for(let M of A.actions){let V=Fh(M),F=Hh(V,x);if(!ll(F,_.duration_ms))continue;let Re=hA({action:M,actor:R,actorCount:b.length,allActors:b,surfaces:I,surfacesByActor:a,stateName:U?.state_name??"default"}),X=Re??(U?yA(M,b,a):null);if(!X)continue;let j={actorId:R.actor_id,episode:y,episodeId:w.episode_id,sceneId:A.scene_id,timestamp:$h(F),milliseconds:F,durationMs:_.duration_ms,stateScore:X.stateScore,identityScore:X.identityScore,selection:X.selection,sourcePath:_.path,sourceSha256:_.sha256};if(O.push(j),Re){let Ot=`${y}:${F}`,P=f.get(Ot)??new Set;P.add(R.actor_id),f.set(Ot,P)}}if(O.length>0){let M=p.get(R.actor_id)??[];if(M.push(...O),p.set(R.actor_id,M),U){let V=`${R.actor_id}:${U.state_id}`,F=l.get(V)??[];F.push(...O),l.set(V,F)}}}}}let u=(m,w)=>{let y=c.get(m),_=c.get(w),x=y?.importance==="background"?1:0,E=_?.importance==="background"?1:0;return x-E||(d.get(w)??0)-(d.get(m)??0)||(y?.actor_name??m).localeCompare(_?.actor_name??w,"zh-CN")},g=[...l.entries()].flatMap(([m,w])=>{let[y,_]=m.split(":"),x=y?c.get(y):void 0,E=x?.states.find(R=>R.state_id===_),A=wA(w,"stateScore",f);if(!x||!E||!A)return[];let b=`state:${x.actor_id}:${E.state_id}`,C=fA.map(R=>{let I=A.durationMs===void 0?Number.POSITIVE_INFINITY:Math.max(0,A.durationMs-50),O=Math.min(I,Math.max(0,A.milliseconds+R)),N=$h(O);return{evidence_id:`${b}:${A.episode}:${N}`,episode:A.episode,episode_id:A.episodeId,scene_id:A.sceneId,timestamp:N,offset_ms:R,selection:A.selection,source_sha256:A.sourceSha256,source_path:A.sourcePath,frame_path:`evidence/frames/${x.actor_id}/${E.state_id}/ep_${String(A.episode).padStart(3,"0")}_${Dh(N)}.jpg`,frame_status:"pending"}}).filter((R,I,O)=>O.findIndex(N=>N.timestamp===R.timestamp)===I);return[{evidence_id:b,asset_kind:"actor",actor_id:x.actor_id,actor_name:x.actor_name,state_id:E.state_id,state_name:E.state_name,samples:C}]}).sort((m,w)=>u(m.actor_id,w.actor_id)||m.state_name.localeCompare(w.state_name,"zh-CN")),h=[...p.entries()].flatMap(([m,w])=>{let y=c.get(m),_=qh(w,"identityScore",f,uA,lA);if(!y||_.length===0)return[];let x=`identity:${y.actor_id}`;return[{evidence_id:x,asset_kind:"actor",actor_id:y.actor_id,actor_name:y.actor_name,samples:_.map(E=>({evidence_id:`${x}:${E.episode}:${E.timestamp}`,episode:E.episode,episode_id:E.episodeId,scene_id:E.sceneId,timestamp:E.timestamp,offset_ms:0,selection:E.selection,source_sha256:E.sourceSha256,source_path:E.sourcePath,frame_path:`evidence/frames/${y.actor_id}/identity/ep_${String(E.episode).padStart(3,"0")}_${Dh(E.timestamp)}.jpg`,frame_status:"pending"}))}]}).sort((m,w)=>u(m.actor_id,w.actor_id));return{version:2,source_sha256:i,items:g,identities:h}}function Zh(e){return Hh(e)}function Wh(e,t){let n=e.scenes.map((o,i)=>{let r={};o.environment?.space&&(r.space=o.environment.space),o.environment?.time&&(r.time=o.environment.time);let s=(o.anchors??[]).map(c=>({kind:c.kind,...c.speaker?{speaker:c.speaker}:{},...c.parenthetical?{parenthetical:c.parenthetical}:{},...c.ts?{ts:c.ts}:{},content:c.content??""}));return{index:i+1,environment:r,...o.timeRange?{timeRange:o.timeRange}:{},...o.location?{location:o.location}:{},characters:(o.characters??[]).filter(c=>c.name).map(c=>({name:c.name,states:[...c.states]})),props:(o.props??[]).filter(Boolean),anchors:s}});return{episode:t,synopsis:(e.synopsis??"").trim(),scenes:n,actors:[],locations:[],props:[],speakers:[],actorStates:[],locationStates:[],propStates:[]}}import*as Qa from"node:path";function ey(e){return Qa.extname(e).toLowerCase()}function _A(e){return yp[ey(e)]??"application/octet-stream"}function Xh(e,t){return new S(e,{exitCode:k,errorCode:"INGEST_VIDEO_DISCOVERY",hint:"Name every episode file with a number, or none of them, and rerun `scriptctl ingest`.",data:{actual:t}})}function ul(e,t){return{episode:t,path:e,ext:ey(e),mime:_A(e)}}function Ya(e){if(e.kind!=="video-file"&&e.kind!=="video-directory")throw new S("Expected video source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});if(e.kind==="video-file")return[ul(e.path,1)];let t=e.files,n=t.map(Da),o=n.filter(r=>r!==null);if(o.length===0)return t.map((r,s)=>ul(r,s+1));if(o.length!==t.length){let r=t.filter((s,c)=>n[c]===null).map(s=>Qa.basename(s));throw Xh("Some episode files carry a number and some do not.",[`unnumbered: ${r.join(", ")}`])}let i=new Set;for(let r of o){if(i.has(r))throw Xh("Two episode files resolve to the same number.",[`duplicate episode: ${r}`]);i.add(r)}return t.map((r,s)=>ul(r,n[s])).sort((r,s)=>r.episode-s.episode)}import*as ty from"node:fs";import*as ny from"node:path";function oy(e,t=[],n){let o=new Map(t.map(r=>[r.episode,r])),i=n?Date.parse(n):Number.NaN;return e.map(r=>{let s=ny.resolve(r.path),c=ty.statSync(s),a=c.size,d=Math.trunc(c.mtimeMs),p=o.get(r.episode),l=p&&p.size_bytes===a&&p.mtime_ms===d,f=p&&p.size_bytes===void 0&&p.mtime_ms===void 0&&p.path===s&&Number.isFinite(i)&&c.mtimeMs<=i,u=p&&p.ext===r.ext&&p.mime===r.mime&&(l||f)?p.sha256:Ic(s);return{episode:r.episode,path:s,ext:r.ext,mime:r.mime,sha256:u,size_bytes:a,mtime_ms:d}})}function qa(e){return Ee(JSON.stringify(e.map(t=>({episode:t.episode,ext:t.ext,mime:t.mime,sha256:t.sha256}))))}import{spawn as EA}from"node:child_process";import*as mt from"node:fs";import*as iy from"node:path";var xA=20*1024*1024,SA="scale='if(gt(a,1),min(1280,iw),-2)':'if(gt(a,1),-2,min(1280,ih))'";function IA(e,t){return["-y","-loglevel","error","-i",e,"-vf",SA,"-c:v","libx264","-preset","medium","-crf","27","-pix_fmt","yuv420p","-c:a","aac","-b:a","96k","-movflags","+faststart","-f","mp4",t]}function AA(e,t,n){return new Promise((o,i)=>{if(n?.aborted){i(new Error("aborted"));return}let r=EA("ffmpeg",IA(e,t),{stdio:["ignore","ignore","pipe"]}),s="";r.stderr?.on("data",a=>{s+=String(a)});let c=()=>{r.kill("SIGKILL")};n?.addEventListener("abort",c,{once:!0}),r.on("error",a=>{n?.removeEventListener("abort",c),i(a)}),r.on("close",a=>{n?.removeEventListener("abort",c),a===0?o():i(new Error(`ffmpeg exited ${a}: ${s.trim().slice(0,300)}`))})})}async function ry(e,t,n,o){if(mt.existsSync(t)&&(mt.statSync(t).size??0)>0)return{path:t,mime:"video/mp4",transcoded:!0};let i=0;try{i=mt.statSync(e).size}catch{}if(i>0&&i<=xA)return{path:e,mime:n,transcoded:!1,note:`already ${(i/1024/1024).toFixed(1)}MB (\u226420MB)`};let r=`${t}.part`;try{if(mt.mkdirSync(iy.dirname(t),{recursive:!0}),mt.rmSync(r,{force:!0}),await AA(e,r,o),!mt.existsSync(r)||mt.statSync(r).size===0)throw new Error("ffmpeg produced no output");return mt.renameSync(r,t),{path:t,mime:"video/mp4",transcoded:!0}}catch(s){try{mt.rmSync(r,{force:!0}),mt.rmSync(t,{force:!0})}catch{}if(o?.aborted)throw s instanceof Error?s:new Error(String(s));let c=s instanceof Error?s.message:String(s);return{path:e,mime:n,transcoded:!1,note:`transcode failed, uploading original (${c})`}}}import{spawn as kA}from"node:child_process";import*as Ke from"node:fs";import*as sy from"node:path";var bA="scale='if(gt(a,1),min(960,iw),-2)':'if(gt(a,1),-2,min(960,ih))'",OA=4;function vA(e){let t=Zh(e);return t===null?null:(t/1e3).toFixed(3)}var RA=async(e,t,n,o)=>{if(o?.aborted)throw new Error("aborted");let i=vA(t);if(i===null)return{ok:!1,error:"invalid timestamp"};try{if(!Ke.existsSync(e)||Ke.statSync(e).size===0)return{ok:!1,error:"source video is unavailable or empty"}}catch{return{ok:!1,error:"source video is unavailable"}}Ke.mkdirSync(sy.dirname(n),{recursive:!0});let r=`${n}.part`;return Ke.rmSync(r,{force:!0}),new Promise((s,c)=>{let a=kA("ffmpeg",["-y","-loglevel","error","-ss",i,"-i",e,"-frames:v","1","-vf",bA,"-q:v","3","-f","image2",r],{stdio:["ignore","ignore","pipe"]});a.stderr?.resume();let d=()=>{a.kill("SIGKILL")};o?.addEventListener("abort",d,{once:!0}),a.on("error",()=>{o?.removeEventListener("abort",d),Ke.rmSync(r,{force:!0}),o?.aborted?c(new Error("aborted")):s({ok:!1,error:"frame extractor unavailable"})}),a.on("close",p=>{if(o?.removeEventListener("abort",d),o?.aborted){Ke.rmSync(r,{force:!0}),c(new Error("aborted"));return}if(p===0&&Ke.existsSync(r)&&Ke.statSync(r).size>0){Ke.renameSync(r,n),s({ok:!0});return}Ke.rmSync(r,{force:!0}),s({ok:!1,error:`frame extraction failed (exit ${p??"unknown"})`})})})};function MA(e){let{source_path:t,...n}=e;return n}async function Za(e,t,n,o=RA,i={}){let r=i.reuseExistingFrames!==!1,s=[...t.items.flatMap(g=>g.samples),...(t.identities??[]).flatMap(g=>g.samples)],c=new Map,a=0,d=async()=>{for(;;){let g=a;if(a+=1,g>=s.length)return;if(n?.aborted)throw new Error("aborted");let h=s[g],m=e.path(h.frame_path),w;r&&Ke.existsSync(m)&&Ke.statSync(m).size>0?w={ok:!0}:(Ke.rmSync(m,{force:!0}),w=await o(h.source_path,h.timestamp,m,n)),c.set(h,MA({...h,frame_status:w.ok?"ready":"unavailable",...w.error?{error:w.error}:{}}))}};await Promise.all(Array.from({length:Math.min(OA,s.length)},()=>d()));let p=g=>g.map(h=>c.get(h)),l=t.items.map(g=>({...g,samples:p(g.samples)})),f=(t.identities??[]).map(g=>({...g,samples:p(g.samples)})),u={version:2,generated_at:new Date().toISOString(),source_sha256:t.source_sha256,items:l,...f.length>0?{identities:f}:{}};if(e.has("evidence/state-evidence.json"))try{let g=e.readJson("evidence/state-evidence.json"),h=m=>JSON.stringify({version:m.version,source_sha256:m.source_sha256,items:m.items,identities:m.identities??[]});if(h(g)===h(u))return g}catch{}return e.writeJson("evidence/state-evidence.json",u),u}var NA=new Set(["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","voice"]),ay=()=>({apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:[],voice:""}),mr=(e,t)=>{let n=e.split("|"),o=n.slice(0,t-1).map(r=>r.trim()),i=n.slice(t-1).join("|").trim();for(;o.length<t-1;)o.push("");return[...o,i]};function fl(e){let t=[],n=[],o=[],i=[],r=[],s=[],c=[],a="",d,p,l=!1,f=0;for(let u of e.split(/\r?\n/)){let g=u.replace(/|/g,"|").trim().replace(/^[-*]\s+/,"");if(!g||g.startsWith("```"))continue;f++;let m=d&&!p&&/^\d{2}:\d{2}\|[^|]*\|/.test(g)&&g.split("|").length===3?["","shot",g]:/^([a-z_]+):?\s*(.*)$/.exec(g),w=m?.[1]??"",y=m?.[2]??"",_=x=>p[x];if(w==="synopsis"){a=y;continue}if(w==="scene"){let[x,E,A,b]=mr(y,4);d={space:x,time:E,timeRange:A,location:b,characters:[],props:[],shots:[],voices:[]},t.push(d),p=void 0;continue}if(d&&!p){if(w==="char"){let[x,...E]=y.split("|").map(A=>A.trim());x&&d.characters.push({name:x,states:E.filter(Boolean)});continue}if(w==="props"){d.props.push(...y.split("|").map(x=>x.trim()).filter(Boolean));continue}if(w==="shot"){let[x,E,A]=mr(y,3);d.shots.push({ts:x,camera:E,visual:A});continue}if(w==="dlg"||w==="think"){let[x,E,A,b]=mr(y,4);d.voices.push({kind:w,speaker:E,parenthetical:A,ts:x,content:b});continue}}if(w==="new"){let[x,E,A,b]=mr(y,4);p={name:E,kind:x,status:A,importance:b,recognition_anchors:[],identity_profile:ay(),appearance:"",role:"",states:[],aliases:[]},l=!1,n.push(p);continue}if(w==="enrich"){p={name:y.trim(),add_recognition_anchors:[],identity_profile_patch:ay(),appearance:"",role:"",add_aliases:[],add_states:[]},l=!0,o.push(p);continue}if(w==="rename"){let[x,E,A]=mr(y,3);i.push({from_name:x,canonical_name:E,evidence:A}),p=void 0;continue}if(w==="open"){r.push({text:y.trim()}),p=void 0;continue}if(w==="close"){s.push({ref:y.trim()}),p=void 0;continue}if(p){let x=p[l?"identity_profile_patch":"identity_profile"];if(NA.has(w)){x[w]=y.trim();continue}let E=y.split("|").map(A=>A.trim()).filter(Boolean);if(w==="mark"){x.persistent_marks.push(...E);continue}if(w==="anchor"||w==="anchors"){_(l?"add_recognition_anchors":"recognition_anchors").push(...E);continue}if(w==="alias"){_(l?"add_aliases":"aliases").push(...E);continue}if(w==="role"||w==="appearance"){p[w]=y.trim();continue}if(w==="state"){let[A,b]=mr(y,2);_(l?"add_states":"states").push({name:A,description:b});continue}}c.push(g)}return{value:{synopsis:a,scenes:t,registry_delta:{new_entities:n,enrich:o,canonicalize:i},open_threads:{opened:r,closed:s}},recognized:f-c.length,unknown:c}}var cy=e=>fl(e).recognized>0,dy=`\u3010\u8F93\u51FA\u683C\u5F0F\uFF1A\u884C\u5F0F DSL\u3011\u53EA\u8F93\u51FA\u4E0B\u5217\u683C\u5F0F\u7684\u7EAF\u6587\u672C\uFF0C\u4E0D\u8981 JSON\u3001Markdown \u4EE3\u7801\u5757\u3001\u6807\u9898\u6216\u4EFB\u4F55\u89E3\u91CA\u3002\u4E00\u884C\u4E00\u6761\u8BB0\u5F55\uFF1A\u884C\u9996\u662F\u5C0F\u5199\u6807\u7B7E\uFF0C\u6807\u7B7E\u540E\u4E00\u4E2A\u7A7A\u683C\uFF0C\u5B57\u6BB5\u4E4B\u95F4\u7528\u534A\u89D2 | \u5206\u9694\uFF1B\u6700\u540E\u4E00\u4E2A\u5B57\u6BB5\u53EF\u4EE5\u5305\u542B\u4EFB\u610F\u6587\u5B57\u3002\u4EFB\u4F55\u503C\u5185\u90FD\u4E0D\u6362\u884C\u3001\u4E0D\u5199 |\u3002\u53EF\u9009\u5B57\u6BB5\u4E3A\u7A7A\u65F6\u4FDD\u7559\u5206\u9694\u7B26\u3002\u89C4\u5219\u6B63\u6587\u91CC\u7684\u5B57\u6BB5\u540D\u4E0E\u672C\u683C\u5F0F\u5BF9\u5E94\uFF1Ascenes=scene \u5757\uFF0Cshots=shot \u884C\uFF0Cvoices=dlg/think \u884C\uFF0Cregistry_delta.new_entities=new \u5757\uFF0Cenrich=enrich \u5757\uFF0Ccanonicalize=rename \u884C\uFF0Copen_threads=open/close \u884C\uFF0Cidentity_profile=\u753B\u50CF\u952E\u884C\uFF0Crecognition_anchors=anchor \u884C\u3002
272
+ `);let U="upload";try{g??=e.executor.documentPort("ingest.comic-serial");let M=n.path(`${E}.input.pdf`);hi(M,Buffer.from(await Ah(io.readFileSync(_.path))));let I=await g.prepare(M,e.signal),v;try{U="generate";let ie=A&&n.has(`${E}.response.json`)&&s.current_error?.phase==="validation"?cl(io.readFileSync(n.path(`${E}.response.json`),"utf8"),_.page_count):await Mh(g,I,_.title,_.page_count,b,K=>n.writeText(`${E}.response.json`,K),e.signal);v={episode:_.episode,document_id:_.document_id,title:_.title,output:ie}}finally{await g.release(I,e.signal)}U="validation";let L=ps(structuredClone(c.context),v.output,_.episode),C=[...a,v],R;try{R=Fa(C,{context:L,identityMap:c.identityMap},p)}catch(ie){if(!(ie instanceof x)||ie.errorCode!=="INGEST_VALIDATION_FAILED")throw ie;process.stderr.write(`\u6B63\u5728\u6839\u636E\u539F\u7A3F\u8865\u5168\u4EBA\u7269\u3001\u5730\u70B9\u548C\u9053\u5177\u767B\u8BB0\uFF0C\u4FDD\u7559\u5DF2\u8F6C\u5F55\u6B63\u6587\u2026
273
+ `);let K=await g.prepare(M,e.signal);try{v.output.registry_delta=await Nh(g,K,v.output,b,ie.message,e.signal),n.writeJson(`${E}.response.json`,v.output)}finally{await g.release(K,e.signal)}L=ps(structuredClone(c.context),v.output,_.episode),R=Fa(C,{context:L,identityMap:c.identityMap},p)}let J={context:L,identityMap:R.identityMap};U="checkpoint",n.writeJson(`${E}.json`,v),n.writeJson("checkpoint.json",J),c=J,a.push(v),U="publish",dl(n,R,c.context),n.clearError(`${E}.error.json`),delete s.current_error,s.updated=new Date().toISOString(),n.writeJson("manifest.json",s),m++;let W=Date.now();f.windowDone(_.episode,_.episode,W-S,!1),l.flush({scope:{kind:"episode",episode:_.episode},status:"succeeded",startedAtMs:S,endedAtMs:W});let Re=v.output.scenes.reduce((ie,K)=>ie+K.actions.length,0);process.stderr.write(` \u5DF2\u4FDD\u5B58\uFF1A${v.output.scenes.length} \u573A / ${Re} \u6761\u6B63\u6587
274
+ `)}catch(M){let I=za(M,_.episode,U);throw n.writeJson(`${E}.error.json`,I),n.writeJson("manifest.json",{...s,updated:I.occurred_at,current_error:I}),l.flush({scope:{kind:"episode",episode:_.episode},status:"failed",startedAtMs:S,endedAtMs:Date.now()}),M}}let w=Fa(a,c,p);dl(n,w,c.context);let y=a.length===r.length;return u="succeeded",{workspace:n.root,script_path:n.path("script.json"),kind:"comic",episodes:r.length,processed:m,reused:h,completed:a.length,remaining:r.length-a.length,complete:y,next_episode:y?null:a.length+1,assets:{actors:w.scriptV4.actors.length,locations:w.scriptV4.locations.length,props:w.scriptV4.props.length}}}finally{f.phaseEnd("serial"),f.finish(),l.finish(u)}}async function Th(e){return Do(e.workspacePath,()=>aA(e))}import*as kt from"node:fs";import*as Qt from"node:path";function cA(e,t){return e.episode!==t.episode?`episode ${e.episode} was replaced by episode ${t.episode}`:e.ext!==t.ext||e.mime!==t.mime?`episode ${e.episode} changed media type`:e.sha256!==t.sha256?`episode ${e.episode} content changed`:null}function Vh(e,t){if(t.length<e.length)return{kind:"incompatible",reason:`source removed ${e.length-t.length} previously accepted episode(s)`};for(let o=0;o<e.length;o+=1){let i=cA(e[o],t[o]);if(i)return{kind:"incompatible",reason:i}}let n=t.slice(e.length);return n.length===0?{kind:"unchanged",appended:[]}:{kind:"append",appended:n}}function Qa(e){for(let t=0;t<e.length;t+=1){let n=t+1,o=e[t].episode;if(o!==n)return`expected episode ${n}, found episode ${o}`}return null}function mr(e){let t=typeof e=="string"?e.trim():"",n=t.match(/^(?:(\d+):)?(\d+):(\d{2})(\.\d{1,3})?$/);if(!n)return t;let o=Number(n[1]??0),i=Number(n[2]),r=Number(n[3]);if(![o,i,r].every(Number.isSafeInteger))return t;let s=o*3600+i*60+r,c=Math.floor(s/3600),a=Math.floor(s%3600/60),d=s%60;return(c>0?`${c}:${String(a).padStart(2,"0")}:${String(d).padStart(2,"0")}`:`${String(a).padStart(2,"0")}:${String(d).padStart(2,"0")}`)+(n[4]??"")}function gr(e,t){if(!e)return e;let n=e.match(/^(\w+):(.+)$/);return n?`${n[1]}:${t.get(n[2])??n[2]}`:t.get(e)??e}var $h=e=>String(e).padStart(3,"0"),dA={\u5185:"interior",\u5916:"exterior"},pA={act:"action",dlg:"dialogue",think:"inner_thought"},pl={broadcast:"broadcast",system:"system",group:"group",offscreen:"offscreen",prop:"offscreen",location:"offscreen"};function lA(e){let t=e.match(/^(\w+):(.+)$/);if(t&&pl[t[1]]){let n=t[2].trim();return n?{kind:pl[t[1]],label:n}:{kind:pl[t[1]]}}return ct(e)?{kind:"group",label:e.trim()}:{name:e}}function Dh(e,t){let n=0,o=e.map((i,r)=>{let s=`video:episode:${i.episode}`,c=new Map;return{identity_key:s,episode_id:`ep_${$h(r+1)}`,scenes:i.scenes.map(a=>{let d=a.timeRange?.trim()?`time:${a.timeRange.trim()}`:`index:${a.index}`,p=(c.get(d)??0)+1;c.set(d,p);let l=`${s}:scene:${d}:${p}`,f={},u=dA[(a.environment.space??"").trim()],m=Lo(a.environment.time);u&&(f.space=u),m&&(f.time=m);let h=[],g=A=>{h.some(b=>b.name===A)||h.push({name:A})};for(let A of a.characters)A.name&&!ct(A.name)&&(A.states.length===0?h.push({name:A.name}):h.push(...A.states.map(b=>({name:A.name,state:b}))));let w=new Map,y=a.anchors.map(A=>{let b=mr(A.ts),U=b?`time:${b}`:`content:${JSON.stringify([A.kind,A.speaker??"",A.content])}`,M=(w.get(U)??0)+1;w.set(U,M);let I={identity_key:`${l}:action:${U}:${M}`,type:pA[A.kind]??"action",content:A.content};if((A.kind==="dlg"||A.kind==="think")&&A.speaker){let L=lA(A.speaker);I.speaker=L,"name"in L&&g(L.name)}A.parenthetical&&(I.parenthetical=A.parenthetical);let v=mr(A.ts);return v&&(I.extend={timestamp:v}),I}),_=(a.location??"").trim(),S=[],E=new Set;for(let A of a.props??[]){if(!A)continue;let b=A.normalize("NFC").replace(/\s+/g," ").trim();!b||E.has(b)||(E.add(b),S.push({name:A}))}return{identity_key:l,scene_id:`scn_${$h(++n)}`,...f.space||f.time?{environment:f}:{},location:_?{name:_}:null,actors:h,props:S,actions:y}})}});return{title:t,episodes:o}}var uA=60,fA=6,mA=[-1e3,0,1e3],Kh=/(?:身穿|穿着|服装|造型|衣|裙|袍|衫|夹克|制服|西装|盔甲|装甲|防弹服|套装|裤|靴)/u,ll=/(?:全身|半身|上半身|四分之三身|躯干|胸前|腰部)/u,ul=/(?:站(?:在|立)|坐(?:在|下|起)|跪(?:在|下|倒)?|蹲(?:在|下)?|走(?:在|出|向)|行走|迈步|奔跑|跳起|跃起|转身|抬头|转头)/u,Gh=/(?:特写|近景|脸|面容|五官|正脸|侧脸|侧前脸|双眼|眼眶|眉头|嘴角)/u,jh=/(?:背对|背影|远处|极远|模糊|运动模糊|脸被遮|面部遮挡|只露出|纯道具|空镜)/u,zh=/(?:双脚|脚部|膝盖|伤口|手部特写)/u,Hh=/(?:画外音|旁白|未入镜|镜外|电话音|广播|\bO\.?S\.?\b)/iu;function Go(e){return e.normalize("NFC").replace(/\s+/g," ").trim()}function Fh(e){let t=e.trim().match(/^(?:(\d{1,2}):)?(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?$/);if(!t)return null;let n=Number(t[1]??0),o=Number(t[2]),i=Number(t[3]);if(o>=60&&t[1]!==void 0||i>=60)return null;let r=String(t[4]??"").padEnd(3,"0");return((n*60+o)*60+i)*1e3+Number(r||0)}function Qh(e){let t=e.trim().match(/^(\d+):(\d{2})$/);return t?Number(t[1])*1e3+Number(t[2])*10:null}function Yh(e,t="clock"){return t==="legacy_centiseconds"?Qh(e):Fh(e)}function fl(e,t){return e===null?!1:t===void 0||e<=t}function gA(e,t){if(t===void 0)return"clock";let n=e.scenes.flatMap(r=>r.actions.map(qh)).filter(Boolean),o=n.filter(r=>fl(Fh(r),t)).length;return n.filter(r=>fl(Qh(r),t)).length>o?"legacy_centiseconds":"clock"}function Bh(e){let t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3),o=e%1e3;return`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}.${String(o).padStart(3,"0")}`}function qh(e){let t=e.extend?.timestamp;return typeof t=="string"?t.trim():""}function hA(e,t){let n=new Set([e.actor_name,...e.aliases??[]].map(Go).filter(Boolean));for(let[o,i]of t)Go(i)===Go(e.actor_name)&&n.add(Go(o));return[...n].sort((o,i)=>i.length-o.length)}function Zh(e,t){let n=t.map(o=>e.indexOf(o)).filter(o=>o>=0);return n.length>0?Math.min(...n):-1}function Wh(e,t,n){return t.filter(o=>Zh(e,n.get(o.actor_id)??[])>=0).length}function yA({action:e,actor:t,actorCount:n,allActors:o,surfaces:i,surfacesByActor:r,stateName:s}){let c=e.type==="action"||e.type==="transition",a=Go(c?e.content:"parenthetical"in e?e.parenthetical??"":""),d=Zh(a,i),p=d>=0&&d<=12,l=d>=0,u=e.type==="dialogue"&&"speaker"in e&&"actor_id"in e.speaker&&e.speaker.actor_id===t.actor_id&&!Hh.test(a),m=n===1&&(c&&a.length>0||u&&a.length>0&&(ul.test(a)||Gh.test(a)));if(!l&&!u&&!m)return null;let h=p||u?"target_anchor":"scene_fallback",g=u?250:p?65:l?50:45,w=u?250:p?65:l?50:45;n===1&&(g+=20,w+=20);let y=Go(s);return y&&y!=="default"&&y!=="\u9ED8\u8BA4"&&a.includes(y)&&(g+=35),Kh.test(a)&&(g+=30),ll.test(a)?(g+=25,w+=15):ul.test(a)&&(g+=15,w+=5),Gh.test(a)&&(w+=30,ll.test(a)||(g-=20)),jh.test(a)&&(g-=70,w-=70),zh.test(a)&&(g-=40),Wh(a,o,r)>=2&&(g-=15,w-=15),{stateScore:g,identityScore:w,selection:h}}function wA(e,t,n){let o=e.type==="action"||e.type==="transition",i="parenthetical"in e?Go(e.parenthetical??""):"";if(!o&&Hh.test(i))return null;let r=Go(o?e.content:i),s=o?0:-40;return s-=Wh(r,t,n)*20,Kh.test(r)&&(s+=10),ll.test(r)?s+=10:ul.test(r)&&(s+=5),jh.test(r)&&(s-=20),zh.test(r)&&(s-=10),{stateScore:s,identityScore:Number.NEGATIVE_INFINITY,selection:"scene_fallback"}}function fs(e,t,n){let o=(n.get(`${e.episode}:${e.milliseconds}`)?.size??0)>1;return e[t]-(o?35:0)}function Xh(e,t,n,o,i){let r=new Map;for(let a of e){let d=`${a.episode}:${a.milliseconds}`,p=r.get(d);(!p||fs(a,t,n)>fs(p,t,n))&&r.set(d,a)}let s=[...r.values()].sort((a,d)=>fs(d,t,n)-fs(a,t,n)||a.episode-d.episode||a.milliseconds-d.milliseconds).filter(a=>i===null||fs(a,t,n)>=i),c=[];for(let a of s)if(!c.some(p=>p.episode===a.episode&&p.sceneId===a.sceneId&&Math.abs(p.milliseconds-a.milliseconds)<3e3)&&(c.push(a),c.length>=o))break;return c}function _A(e,t,n){return Xh(e,t,n,1,null)[0]??null}function Jh(e){return e.replace(/[^0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function Ya(e,t,n,o,i){let r=new Map(o.map(g=>[g.episode,g])),s=$o(n.registry),c=new Map(t.actors.map(g=>[g.actor_id,g])),a=new Map(t.actors.map(g=>[g.actor_id,hA(g,s)])),d=new Map,p=new Map,l=new Map,f=new Map;for(let g=0;g<t.episodes.length;g+=1){let w=t.episodes[g],y=g+1,_=r.get(y);if(!_)continue;let S=gA(w,_.duration_ms);for(let E=0;E<w.scenes.length;E+=1){let A=w.scenes[E],b=A.actors.map(U=>c.get(U.actor_id)).filter(U=>!!U);for(let U of A.actors){d.set(U.actor_id,(d.get(U.actor_id)??0)+1);let M=c.get(U.actor_id);if(!M)continue;let I=a.get(M.actor_id)??[M.actor_name],v=[],L=U.state_ids.length===1?U.state_ids[0]:null,C=L?M.states.find(R=>R.state_id===L):null;for(let R of A.actions){let J=qh(R),W=Yh(J,S);if(!fl(W,_.duration_ms))continue;let Re=yA({action:R,actor:M,actorCount:b.length,allActors:b,surfaces:I,surfacesByActor:a,stateName:C?.state_name??"default"}),ie=Re??(C?wA(R,b,a):null);if(!ie)continue;let K={actorId:M.actor_id,episode:y,episodeId:w.episode_id,sceneId:A.scene_id,timestamp:Bh(W),milliseconds:W,durationMs:_.duration_ms,stateScore:ie.stateScore,identityScore:ie.identityScore,selection:ie.selection,sourcePath:_.path,sourceSha256:_.sha256};if(v.push(K),Re){let Ot=`${y}:${W}`,P=f.get(Ot)??new Set;P.add(M.actor_id),f.set(Ot,P)}}if(v.length>0){let R=p.get(M.actor_id)??[];if(R.push(...v),p.set(M.actor_id,R),C){let J=`${M.actor_id}:${C.state_id}`,W=l.get(J)??[];W.push(...v),l.set(J,W)}}}}}let u=(g,w)=>{let y=c.get(g),_=c.get(w),S=y?.importance==="background"?1:0,E=_?.importance==="background"?1:0;return S-E||(d.get(w)??0)-(d.get(g)??0)||(y?.actor_name??g).localeCompare(_?.actor_name??w,"zh-CN")},m=[...l.entries()].flatMap(([g,w])=>{let[y,_]=g.split(":"),S=y?c.get(y):void 0,E=S?.states.find(M=>M.state_id===_),A=_A(w,"stateScore",f);if(!S||!E||!A)return[];let b=`state:${S.actor_id}:${E.state_id}`,U=mA.map(M=>{let I=A.durationMs===void 0?Number.POSITIVE_INFINITY:Math.max(0,A.durationMs-50),v=Math.min(I,Math.max(0,A.milliseconds+M)),L=Bh(v);return{evidence_id:`${b}:${A.episode}:${L}`,episode:A.episode,episode_id:A.episodeId,scene_id:A.sceneId,timestamp:L,offset_ms:M,selection:A.selection,source_sha256:A.sourceSha256,source_path:A.sourcePath,frame_path:`evidence/frames/${S.actor_id}/${E.state_id}/ep_${String(A.episode).padStart(3,"0")}_${Jh(L)}.jpg`,frame_status:"pending"}}).filter((M,I,v)=>v.findIndex(L=>L.timestamp===M.timestamp)===I);return[{evidence_id:b,asset_kind:"actor",actor_id:S.actor_id,actor_name:S.actor_name,state_id:E.state_id,state_name:E.state_name,samples:U}]}).sort((g,w)=>u(g.actor_id,w.actor_id)||g.state_name.localeCompare(w.state_name,"zh-CN")),h=[...p.entries()].flatMap(([g,w])=>{let y=c.get(g),_=Xh(w,"identityScore",f,fA,uA);if(!y||_.length===0)return[];let S=`identity:${y.actor_id}`;return[{evidence_id:S,asset_kind:"actor",actor_id:y.actor_id,actor_name:y.actor_name,samples:_.map(E=>({evidence_id:`${S}:${E.episode}:${E.timestamp}`,episode:E.episode,episode_id:E.episodeId,scene_id:E.sceneId,timestamp:E.timestamp,offset_ms:0,selection:E.selection,source_sha256:E.sourceSha256,source_path:E.sourcePath,frame_path:`evidence/frames/${y.actor_id}/identity/ep_${String(E.episode).padStart(3,"0")}_${Jh(E.timestamp)}.jpg`,frame_status:"pending"}))}]}).sort((g,w)=>u(g.actor_id,w.actor_id));return{version:2,source_sha256:i,items:m,identities:h}}function ey(e){return Yh(e)}function ty(e,t){let n=e.scenes.map((o,i)=>{let r={};o.environment?.space&&(r.space=o.environment.space),o.environment?.time&&(r.time=o.environment.time);let s=(o.anchors??[]).map(c=>({kind:c.kind,...c.speaker?{speaker:c.speaker}:{},...c.parenthetical?{parenthetical:c.parenthetical}:{},...c.ts?{ts:c.ts}:{},content:c.content??""}));return{index:i+1,environment:r,...o.timeRange?{timeRange:o.timeRange}:{},...o.location?{location:o.location}:{},characters:(o.characters??[]).filter(c=>c.name).map(c=>({name:c.name,states:[...c.states]})),props:(o.props??[]).filter(Boolean),anchors:s}});return{episode:t,synopsis:(e.synopsis??"").trim(),scenes:n,actors:[],locations:[],props:[],speakers:[],actorStates:[],locationStates:[],propStates:[]}}import*as qa from"node:path";function oy(e){return qa.extname(e).toLowerCase()}function EA(e){return _p[oy(e)]??"application/octet-stream"}function ny(e,t){return new x(e,{exitCode:k,errorCode:"INGEST_VIDEO_DISCOVERY",hint:"Name every episode file with a number, or none of them, and rerun `scriptctl ingest`.",data:{actual:t}})}function ml(e,t){return{episode:t,path:e,ext:oy(e),mime:EA(e)}}function Za(e){if(e.kind!=="video-file"&&e.kind!=="video-directory")throw new x("Expected video source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});if(e.kind==="video-file")return[ml(e.path,1)];let t=e.files,n=t.map(Ba),o=n.filter(r=>r!==null);if(o.length===0)return t.map((r,s)=>ml(r,s+1));if(o.length!==t.length){let r=t.filter((s,c)=>n[c]===null).map(s=>qa.basename(s));throw ny("Some episode files carry a number and some do not.",[`unnumbered: ${r.join(", ")}`])}let i=new Set;for(let r of o){if(i.has(r))throw ny("Two episode files resolve to the same number.",[`duplicate episode: ${r}`]);i.add(r)}return t.map((r,s)=>ml(r,n[s])).sort((r,s)=>r.episode-s.episode)}import*as iy from"node:fs";import*as ry from"node:path";function sy(e,t=[],n){let o=new Map(t.map(r=>[r.episode,r])),i=n?Date.parse(n):Number.NaN;return e.map(r=>{let s=ry.resolve(r.path),c=iy.statSync(s),a=c.size,d=Math.trunc(c.mtimeMs),p=o.get(r.episode),l=p&&p.size_bytes===a&&p.mtime_ms===d,f=p&&p.size_bytes===void 0&&p.mtime_ms===void 0&&p.path===s&&Number.isFinite(i)&&c.mtimeMs<=i,u=p&&p.ext===r.ext&&p.mime===r.mime&&(l||f)?p.sha256:kc(s);return{episode:r.episode,path:s,ext:r.ext,mime:r.mime,sha256:u,size_bytes:a,mtime_ms:d}})}function Wa(e){return _e(JSON.stringify(e.map(t=>({episode:t.episode,ext:t.ext,mime:t.mime,sha256:t.sha256}))))}import{spawn as xA}from"node:child_process";import*as mt from"node:fs";import*as ay from"node:path";var SA=20*1024*1024,IA="scale='if(gt(a,1),min(1280,iw),-2)':'if(gt(a,1),-2,min(1280,ih))'";function AA(e,t){return["-y","-loglevel","error","-i",e,"-vf",IA,"-c:v","libx264","-preset","medium","-crf","27","-pix_fmt","yuv420p","-c:a","aac","-b:a","96k","-movflags","+faststart","-f","mp4",t]}function kA(e,t,n){return new Promise((o,i)=>{if(n?.aborted){i(new Error("aborted"));return}let r=xA("ffmpeg",AA(e,t),{stdio:["ignore","ignore","pipe"]}),s="";r.stderr?.on("data",a=>{s+=String(a)});let c=()=>{r.kill("SIGKILL")};n?.addEventListener("abort",c,{once:!0}),r.on("error",a=>{n?.removeEventListener("abort",c),i(a)}),r.on("close",a=>{n?.removeEventListener("abort",c),a===0?o():i(new Error(`ffmpeg exited ${a}: ${s.trim().slice(0,300)}`))})})}async function cy(e,t,n,o){if(mt.existsSync(t)&&(mt.statSync(t).size??0)>0)return{path:t,mime:"video/mp4",transcoded:!0};let i=0;try{i=mt.statSync(e).size}catch{}if(i>0&&i<=SA)return{path:e,mime:n,transcoded:!1,note:`already ${(i/1024/1024).toFixed(1)}MB (\u226420MB)`};let r=`${t}.part`;try{if(mt.mkdirSync(ay.dirname(t),{recursive:!0}),mt.rmSync(r,{force:!0}),await kA(e,r,o),!mt.existsSync(r)||mt.statSync(r).size===0)throw new Error("ffmpeg produced no output");return mt.renameSync(r,t),{path:t,mime:"video/mp4",transcoded:!0}}catch(s){try{mt.rmSync(r,{force:!0}),mt.rmSync(t,{force:!0})}catch{}if(o?.aborted)throw s instanceof Error?s:new Error(String(s));let c=s instanceof Error?s.message:String(s);return{path:e,mime:n,transcoded:!1,note:`transcode failed, uploading original (${c})`}}}import{spawn as bA}from"node:child_process";import*as je from"node:fs";import*as dy from"node:path";var OA="scale='if(gt(a,1),min(960,iw),-2)':'if(gt(a,1),-2,min(960,ih))'",vA=4;function RA(e){let t=ey(e);return t===null?null:(t/1e3).toFixed(3)}var MA=async(e,t,n,o)=>{if(o?.aborted)throw new Error("aborted");let i=RA(t);if(i===null)return{ok:!1,error:"invalid timestamp"};try{if(!je.existsSync(e)||je.statSync(e).size===0)return{ok:!1,error:"source video is unavailable or empty"}}catch{return{ok:!1,error:"source video is unavailable"}}je.mkdirSync(dy.dirname(n),{recursive:!0});let r=`${n}.part`;return je.rmSync(r,{force:!0}),new Promise((s,c)=>{let a=bA("ffmpeg",["-y","-loglevel","error","-ss",i,"-i",e,"-frames:v","1","-vf",OA,"-q:v","3","-f","image2",r],{stdio:["ignore","ignore","pipe"]});a.stderr?.resume();let d=()=>{a.kill("SIGKILL")};o?.addEventListener("abort",d,{once:!0}),a.on("error",()=>{o?.removeEventListener("abort",d),je.rmSync(r,{force:!0}),o?.aborted?c(new Error("aborted")):s({ok:!1,error:"frame extractor unavailable"})}),a.on("close",p=>{if(o?.removeEventListener("abort",d),o?.aborted){je.rmSync(r,{force:!0}),c(new Error("aborted"));return}if(p===0&&je.existsSync(r)&&je.statSync(r).size>0){je.renameSync(r,n),s({ok:!0});return}je.rmSync(r,{force:!0}),s({ok:!1,error:`frame extraction failed (exit ${p??"unknown"})`})})})};function NA(e){let{source_path:t,...n}=e;return n}async function Xa(e,t,n,o=MA,i={}){let r=i.reuseExistingFrames!==!1,s=[...t.items.flatMap(m=>m.samples),...(t.identities??[]).flatMap(m=>m.samples)],c=new Map,a=0,d=async()=>{for(;;){let m=a;if(a+=1,m>=s.length)return;if(n?.aborted)throw new Error("aborted");let h=s[m],g=e.path(h.frame_path),w;r&&je.existsSync(g)&&je.statSync(g).size>0?w={ok:!0}:(je.rmSync(g,{force:!0}),w=await o(h.source_path,h.timestamp,g,n)),c.set(h,NA({...h,frame_status:w.ok?"ready":"unavailable",...w.error?{error:w.error}:{}}))}};await Promise.all(Array.from({length:Math.min(vA,s.length)},()=>d()));let p=m=>m.map(h=>c.get(h)),l=t.items.map(m=>({...m,samples:p(m.samples)})),f=(t.identities??[]).map(m=>({...m,samples:p(m.samples)})),u={version:2,generated_at:new Date().toISOString(),source_sha256:t.source_sha256,items:l,...f.length>0?{identities:f}:{}};if(e.has("evidence/state-evidence.json"))try{let m=e.readJson("evidence/state-evidence.json"),h=g=>JSON.stringify({version:g.version,source_sha256:g.source_sha256,items:g.items,identities:g.identities??[]});if(h(m)===h(u))return m}catch{}return e.writeJson("evidence/state-evidence.json",u),u}var LA=new Set(["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","voice"]),py=()=>({apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:[],voice:""}),hr=(e,t)=>{let n=e.split("|"),o=n.slice(0,t-1).map(r=>r.trim()),i=n.slice(t-1).join("|").trim();for(;o.length<t-1;)o.push("");return[...o,i]};function gl(e){let t=[],n=[],o=[],i=[],r=[],s=[],c=[],a="",d,p,l=!1,f=0;for(let u of e.split(/\r?\n/)){let m=u.replace(/|/g,"|").trim().replace(/^[-*]\s+/,"");if(!m||m.startsWith("```"))continue;f++;let g=d&&!p&&/^\d{2}:\d{2}\|[^|]*\|/.test(m)&&m.split("|").length===3?["","shot",m]:/^([a-z_]+):?\s*(.*)$/.exec(m),w=g?.[1]??"",y=g?.[2]??"",_=S=>p[S];if(w==="synopsis"){a=y;continue}if(w==="scene"){let[S,E,A,b]=hr(y,4);d={space:S,time:E,timeRange:A,location:b,characters:[],props:[],shots:[],voices:[]},t.push(d),p=void 0;continue}if(d&&!p){if(w==="char"){let[S,...E]=y.split("|").map(A=>A.trim());S&&d.characters.push({name:S,states:E.filter(Boolean)});continue}if(w==="props"){d.props.push(...y.split("|").map(S=>S.trim()).filter(Boolean));continue}if(w==="shot"){let[S,E,A]=hr(y,3);d.shots.push({ts:S,camera:E,visual:A});continue}if(w==="dlg"||w==="think"){let[S,E,A,b]=hr(y,4);d.voices.push({kind:w,speaker:E,parenthetical:A,ts:S,content:b});continue}}if(w==="new"){let[S,E,A,b]=hr(y,4);p={name:E,kind:S,status:A,importance:b,recognition_anchors:[],identity_profile:py(),appearance:"",role:"",states:[],aliases:[]},l=!1,n.push(p);continue}if(w==="enrich"){p={name:y.trim(),add_recognition_anchors:[],identity_profile_patch:py(),appearance:"",role:"",add_aliases:[],add_states:[]},l=!0,o.push(p);continue}if(w==="rename"){let[S,E,A]=hr(y,3);i.push({from_name:S,canonical_name:E,evidence:A}),p=void 0;continue}if(w==="open"){r.push({text:y.trim()}),p=void 0;continue}if(w==="close"){s.push({ref:y.trim()}),p=void 0;continue}if(p){let S=p[l?"identity_profile_patch":"identity_profile"];if(LA.has(w)){S[w]=y.trim();continue}let E=y.split("|").map(A=>A.trim()).filter(Boolean);if(w==="mark"){S.persistent_marks.push(...E);continue}if(w==="anchor"||w==="anchors"){_(l?"add_recognition_anchors":"recognition_anchors").push(...E);continue}if(w==="alias"){_(l?"add_aliases":"aliases").push(...E);continue}if(w==="role"||w==="appearance"){p[w]=y.trim();continue}if(w==="state"){let[A,b]=hr(y,2);_(l?"add_states":"states").push({name:A,description:b});continue}}c.push(m)}return{value:{synopsis:a,scenes:t,registry_delta:{new_entities:n,enrich:o,canonicalize:i},open_threads:{opened:r,closed:s}},recognized:f-c.length,unknown:c}}var ly=e=>gl(e).recognized>0,uy=`\u3010\u8F93\u51FA\u683C\u5F0F\uFF1A\u884C\u5F0F DSL\u3011\u53EA\u8F93\u51FA\u4E0B\u5217\u683C\u5F0F\u7684\u7EAF\u6587\u672C\uFF0C\u4E0D\u8981 JSON\u3001Markdown \u4EE3\u7801\u5757\u3001\u6807\u9898\u6216\u4EFB\u4F55\u89E3\u91CA\u3002\u4E00\u884C\u4E00\u6761\u8BB0\u5F55\uFF1A\u884C\u9996\u662F\u5C0F\u5199\u6807\u7B7E\uFF0C\u6807\u7B7E\u540E\u4E00\u4E2A\u7A7A\u683C\uFF0C\u5B57\u6BB5\u4E4B\u95F4\u7528\u534A\u89D2 | \u5206\u9694\uFF1B\u6700\u540E\u4E00\u4E2A\u5B57\u6BB5\u53EF\u4EE5\u5305\u542B\u4EFB\u610F\u6587\u5B57\u3002\u4EFB\u4F55\u503C\u5185\u90FD\u4E0D\u6362\u884C\u3001\u4E0D\u5199 |\u3002\u53EF\u9009\u5B57\u6BB5\u4E3A\u7A7A\u65F6\u4FDD\u7559\u5206\u9694\u7B26\u3002\u89C4\u5219\u6B63\u6587\u91CC\u7684\u5B57\u6BB5\u540D\u4E0E\u672C\u683C\u5F0F\u5BF9\u5E94\uFF1Ascenes=scene \u5757\uFF0Cshots=shot \u884C\uFF0Cvoices=dlg/think \u884C\uFF0Cregistry_delta.new_entities=new \u5757\uFF0Cenrich=enrich \u5757\uFF0Ccanonicalize=rename \u884C\uFF0Copen_threads=open/close \u884C\uFF0Cidentity_profile=\u753B\u50CF\u952E\u884C\uFF0Crecognition_anchors=anchor \u884C\u3002
274
275
  \u6309\u4EE5\u4E0B\u987A\u5E8F\u8F93\u51FA\uFF1A
275
276
  synopsis \u672C\u96C6\u5267\u60C5\u6897\u6982\uFF0C\u6309\u53D1\u751F\u987A\u5E8F\uFF0C200-300 \u5B57\u7EAF\u6587\u672C
276
277
  scene \u5185\u6216\u5916\uFF08\u4E0D\u786E\u5B9A\u7559\u7A7A\uFF09|\u65E5\u3001\u591C\u3001\u6668\u3001\u660F\u5FC5\u9009\u5176\u4E00|\u672C\u573A\u8D77\u6B62 MM:SS-MM:SS\uFF08SS \u4E3A 00-59\uFF0C\u6574\u5206\u949F\u5199\u6210\u4E0B\u4E00\u5206\u949F\u7684 :00\uFF0C\u7981\u6B62 :60\uFF09|\u672C\u573A\u552F\u4E00\u7A33\u5B9A\u4E3B\u7A7A\u95F4\u5730\u70B9\u89C4\u8303\u540D
@@ -320,24 +321,25 @@ hair \u2026\u2026
320
321
  build \u2026\u2026
321
322
  voice
322
323
  state \u9ED1\u897F\u88C5|\u2026\u2026\uFF08\u4ECE\u5934\u5230\u811A\u9010\u4EF6\u5199\u6E05\u989C\u8272\u3001\u6750\u8D28\u3001\u7248\u578B\u4E0E\u914D\u9970\uFF09
323
- open \u6797\u665A\u662F\u5426\u7B7E\u4E0B\u79BB\u5A5A\u534F\u8BAE`;function gl(){let e=["zxbxy2G","BM9Zzq","C3bSAxq","zxzPzgvUy2u","sw5ZCgvJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbPBMDLC3qGDg8GCMvZDw1LlG","zxnqtgG","CMvNAxn0CNLFzgvSDge","oIbZzxjPywWGB3v0Chv0ihrVBYbZAg9YDcaOzMLUAxnOuMvHC29Upq","igfUy2HVCNmGC3rPBgWGAgf2zsbUBYb0Aw1LC3rHBxaGywz0zxiGmYbYzxrYAwvZlG","ioMBHU+8MUwVUEEfP+ACRoMBHUwoN+INHUMIKE+8JoAmIEACRos7U+wkOEwUMUs5IEEAHoIHJow8JYbeu0WG6l+u5zUE57QV5PAh5PYS44cc5y+Q6l+u5zUEierttcdMNkZOUQVVViZKUi3OPOhOVPpLH7ROP6pPH4RJGihLIy3OQidJGifku09oioAiLIbnyxjRzg93BIdKU6pNOihLNzFJGii","yNvPBgq","C2HVDhm","C2v0","Bg9JyxrPB24","C3rYAw5NAwz5","sw5ZCgvJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbGC2nYAxb0y3rSigLUz2vZDgaGDg8GCMvZDw1LlG","y2fUB25Py2fSAxPL","6kEJ5P6q56YSia","su5hrvnux1zjrevpx1rjtuvtvefnuf9nsvntsu5h","ywn0","oIbZzxjPywWGB3v0Chv0ihDHCYbUB3qGDMfSAwqGsLnptIaOzMLUAxnOuMvHC29Upq","C3LUB3bZAxm","AM9PBG","z2v0","BM9YBwfSAxPL","ywXPyxnLCW","DMfSDwu","6l+u5zUE5A6m5Pw0iePtt04","yxbWyxjLBNrFz2vUzgvY","BgvUz3rOoIa","ywrKx3jLy29NBML0Aw9Ux2fUy2HVCNm","C2nLBMvZ","su5hrvnux1zjrevpx1nfuKLbtf9gquLmruq","zMLSDgvY","yxbWzwfYyw5Jzq","DM9Py2vZ","DM9Py2u","ChvZAa","ChjVChm","xsaO","DgHPBMS","CMvWBgfJzufSBa","C2nLBMvZioMaKowCUUIMHUEBLUwfQoMBHU+8M+AVJ+wCUUwfIoElRoERI+wUJoAiKoMaKoMvNcbZAg90C++8JowgJEElRoERI+wUJoAiKcb2B2LJzxpJGijZAg90CYdLV4xPOBVOPOBNM5BMR4/MRkhLIiFPLzZLKOZLJ6/NOA7ORQt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HEq","ue9tsvrjvKvFsu5gsu5jvfK","ChjVDMLZAw9UywW","ywn0B3i","AwrLBNrPDhLFChjVzMLSzv9WyxrJAa","DgLTzxn0yw1Wx21PC3nPBMC","CgfYzw50Agv0AwnHBa","zxbPC29Kzsa","AxngAw5PDgu","C29YDa","xs5HBMnOB3jZwW","ywrKx2fSAwfZzxm","44cc6k+36yEn5PAW6kEc55Yl5B2t5yMn6zUg77Ym5lI65Q+p5lIa5P2HihnOB3rZiowsJcb2B2LJzxmG5AgR5yAz55YF5A6E6lw354k5ihrZ77Yitu06u1pVViZLJ6/KV53NLzNOR4hMJA7MLk/MJihNMOqGmEkaKZmG5l2n5Bcp5PwW77Yj77Ym5lIn5B6x57Y65AsX44cb55wz56M65OIw5AgRig51BgZVVjS","zMXHDe1HCa","zgXN","DhjPBq","ChjVCa","zNjVBv9Uyw1L","yM9jAMm","rxbPC29Kzsa","rfnm","sMfIsvG","DgLTzvjHBMDL","yNjVD3nFzxLLCW","AgfPCG","CMvWBgfJzq","C3bLywTLCG","CMvJB2DUAxrPB25Fyw5JAg9YCW","AwrLBNrPDhLFChjVzMLSzq","cGRKUiRMRkhOVPpLH7RMNiKG","zhnS","BMv3x2vUDgL0AwvZ","6l+u5zUE5A6m5Pw0iertta","yMfJA2DYB3vUza","kIRLJ6ROVPpLH7ROR6uGrfnmioAwH+ACRo+8Jos4JEIMGEs7U+s9LEMINEwKLUAwH+wTL+oaGEINO+MhIUAiLUs7O+EGGEwDL+wmHEIJUEoaGIOQ","C3rHDgvZ","BwLTzq","zgvZy3jPChrPB24","Bw91DgG","5l2G5PIV55+T5yMN6kEg6Akr6l2S5yMN5PYS55Qe5lIY6kgm6kEJ5P6q5zMO44cc6l6t5ywL5PIVkIRMN5dKUidPM4yQkUERLUwXJ+EFREwjP+INHUMIKE+8IdeTmIdLIiBPKP/VViKRios4Gos7VEwiSos4IUs4GoMBHUs4UUATOUE0R+ENR+EAHcOQ5BEY55+L6k6+5A6AkIRVViJKURRNIANOI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PBL9Mzwf0DxjLCW","tKzd","Aw1WB3j0yw5Jzq","y2HHCMfJDgvYCW","sLnptG","yw5JAg9YCW","kIRLJ6ROVPpLH7ROR6uGsLnptU+8Jos4JEIMGEs7U+s9LEMINEwKLUAwH+wTL+oaGEINO+MhIUAiLUs7O+EGGEwDL+wmHEIJUEoaGIOQ","wMLKv0O","y2fTzxjH","C3rYAw5N","zMLUza","B3bLBL90AhjLywrZ","CMvM","C3rHDhvZ","zMfJzv9ZAgfWzq","Aw5JBhvKzxm","ENLTtMS","pt09pt09pt09psdLT7lNN6xORR7LRPRVViJLIldKUiRKUidPM4BKUlRMRAlVViZOP4tOJipLKi3KU6xMRAtKUlRLH4BVViKGpt09pt09pt09pqO","C2XPy2u","B3bLBMvK","shfxCei","BwfW","5l2G6kAb6l6t5yE6kIRKUidKUkRNU5pMNOtLJjyGsLnptIdLR7NOSAeQkU+8Ios4PEAGVoESPUwqIoACRos7U+wkOEwUMUs5IEEAHcbku09oioE7K+AEHo+8Iq","5l2G6kAb6l6t5yE6kIRKUidKU73KUkxMOlZNRkBLKiJMNkZKU7VLIQhOOyZLVi8GrfnmioEAHoE6R+AwH+ACRcOQ","DgLTzq","zw50CMLLCW","BMfTzq","C29Tzq","y2XVC2vK","t0LLAhG","BgvUz3rO","77Ym5lIn6kAb5y+Q6l+u5zUE5l+U6kgL5A2x5Q6144cc","u2XXEg8","sxjqD0u","ywrK","y29UDgvUDa","uvznzLu","AgfZ","B2jQzwn0","CgfYC2u","y2fUB25Py2fSx25HBwu","DMLZDwfS","yxbWyxjLBNrFywDL","ywrKx3n0yxrLCW","AMnpA3K"];return gl=function(){return e},gl()}var W=mn,fy=W(101),LA=fy[W(87)](W(125),W(126))[W(87)](W(109),W(96))[W(41)](W(107),W(82))+`
324
- `+dy;function UA(e,t,n=W(92)){let o=W,i=t[o(77)]()?o(120)+t+`
325
- `:o(61);return(n===o(92)?o(17)+e+o(9):o(17)+e+o(48))+o(42)+i}function ml(e,t){let n=W;return new S(e,{exitCode:ee,errorCode:n(32),hint:n(15),data:{actual:t}})}var hl=e=>{let t=W;return typeof e===t(112)?e[t(87)](/\u0000/g,""):Array[t(62)](e)?e[t(124)](hl):gt(e)?Object[t(44)](Object[t(128)](e)[t(124)](([n,o])=>[n,hl(o)])):e},gt=e=>typeof e===W(141)&&e!==null&&!Array[W(62)](e),oe=e=>typeof e===W(112)?e[W(77)]():"";function mn(e,t){e=e-0;let n=gl(),o=n[e];if(mn.gZtclG===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,g=0;u=c.charAt(g++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};mn.aBGiXz=i,mn.gQNlPj={},mn.gZtclG=!0}let r=n[0];mn.pKGWyC!==r&&(mn.gQNlPj={},mn.pKGWyC=r);let s=mn.gQNlPj[e];return s===void 0?(o=mn.aBGiXz(o),mn.gQNlPj[e]=o):o=s,o}var Xe=e=>Array[W(62)](e)?e:[],my=e=>{let t=W,n=oe(e);return n?n[t(2)](/[((//,,、]/)[0][t(77)]():""},PA=e=>[...new Set(Xe(e)[W(124)](my)[W(33)](Boolean))],py=e=>{let t=W,n=[];for(let o of Xe(e)){if(!gt(o))continue;let i=my(o[t(129)]);if(!i)continue;let r=oe(o[t(99)]),s=n[t(113)](c=>c[t(129)]===i);if(s)if(t(123)===t(123))!s[t(99)]&&r&&(s[t(99)]=r);else{if(!_0x4fefa9)return _0x14b3cd[t(63)];let c=_0xeb3cd0[t(2)](":")[t(124)](_0xeecdfb);return c[t(130)](a=>!_0x4d3111[t(70)](a))?_0x4fd60b[t(63)]:c[t(133)]===2?c[0]*60+c[1]:c[t(133)]===3?c[0]*3600+c[1]*60+c[2]:_0x317d01[t(63)]}else{if(t(135)!==t(135))return typeof _0x58acf5===t(112)?_0x25ba9a[t(87)](/\u0000/g,""):_0x228179[t(62)](_0xf2a68c)?_0x3016f9[t(124)](_0x23cb72):_0x4cc138(_0x29f08c)?_0xfb78c4[t(44)](_0x47255e[t(128)](_0x42e29b)[t(124)](([c,a])=>[c,_0x369fa8(a)])):_0x9d75f0;n[t(37)]({name:i,description:r})}}return n},CA=[W(28),W(145),W(117),W(85),W(1),W(100),W(103),W(86),W(10),W(36)],ly=e=>{let t=W;if(!gt(e))return;let n={apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:Xe(e[t(56)])[t(124)](oe)[t(33)](Boolean),voice:""};for(let o of CA)n[o]=oe(e[o]);return n},uy=e=>{let t=W;if(!e)return Number[t(63)];let n=e[t(2)](":")[t(124)](Number);return n[t(130)](o=>!Number[t(70)](o))?Number[t(63)]:n[t(133)]===2?n[0]*60+n[1]:n[t(133)]===3?n[0]*3600+n[1]*60+n[2]:Number[t(63)]},TA=(e,t)=>{let n=W;return e?t?e[n(87)](/[。!?;]+$/,"")+"\u3002"+t:e:t};function VA(e){let t=W,n={synopsis:"",scenes:[],registry_delta:{new_entities:[],enrich:[],canonicalize:[]},open_threads:{opened:[],closed:[]}};if(!gt(e))return n;n[t(21)]=oe(e[t(21)]);for(let r of Xe(e[t(31)]))if(t(119)!==t(119))_0x171853=_0x5698d3?_0xdfd470(_0xc7aaa6)[t(26)]:_0x303303[t(142)](_0x2b1435);else{if(!gt(r))continue;let s={},c=oe(r[t(46)]);c&&(s[t(46)]=c);let a=Lo(r[t(127)]);a&&(s[t(127)]=a);let d=new Map;for(let m of Xe(r[t(106)]))if(t(147)!==t(132)){if(!gt(m))continue;let w=oe(m[t(129)]);if(!w||ct(w))continue;let y=d[t(23)](w)??{name:w,states:[]};for(let _ of PA(m[t(97)]))y[t(97)][t(118)](_)||y[t(97)][t(37)](_);d[t(12)](w,y)}else _0x43ae3e[t(37)]({name:_0x30070f,description:_0x3acf4d});let p=[],l=new Set;for(let m of Xe(r[t(38)])[t(124)](oe)[t(33)](Boolean)){let w=m[t(24)](t(104))[t(87)](/\s+/g," ")[t(77)]();!w||l[t(140)](w)||(l[t(137)](w),p[t(37)](m[t(77)]()))}let f=[];for(let m of Xe(r[t(11)])){if(!gt(m))continue;let w=TA(oe(m[t(111)]),oe(m[t(144)]));if(!w)continue;let y={kind:t(19),content:w},_=ur(m.ts);_&&(y.ts=_),f[t(37)](y)}for(let m of Xe(r[t(35)])){if(!gt(m))continue;let w=oe(m[t(51)]);if(w!==t(76)&&w!==t(40))continue;let y=oe(m[t(138)]);if(!y)continue;let _={kind:w,content:y},x=oe(m[t(88)]);x&&(_[t(88)]=x);let E=oe(m[t(68)]);E&&(_[t(68)]=E);let A=ur(m.ts);A&&(_.ts=A),f[t(37)](_)}f[t(71)]((m,w)=>{let y=t;if(y(139)===y(0)){if(!_0x7b5917(_0x553832))return;let _={apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:_0x1b0acf(_0x3a2287[y(56)])[y(124)](_0x1a9cb2)[y(33)](_0x4a9371),voice:""};for(let x of _0x5a88ec)_[x]=_0x3e883f(_0x223fcf[x]);return _}else{let _=uy(m.ts)-uy(w.ts);return _!==0?_:m[y(51)]===y(19)&&w[y(51)]!==y(19)?-1:m[y(51)]!==y(19)&&w[y(51)]===y(19)?1:0}});let u={environment:s,characters:[...d[t(47)]()],props:p,anchors:f},g=oe(r[t(84)]);g&&(u[t(84)]=g);let h=oe(r[t(13)]);h&&(u[t(13)]=h),n[t(31)][t(37)](u)}let o=gt(e[t(6)])?e[t(6)]:{};for(let r of Xe(o[t(93)])){if(!gt(r))continue;let s=oe(r[t(129)]),c=oe(r[t(51)]);if(!s||c!==t(65)&&c!==t(13)&&c!==t(78)||c===t(65)&&ct(s))continue;let a={name:s,kind:c,status:oe(r[t(116)])===t(64)?t(64):t(60),importance:oe(r[t(105)])===t(95)?t(95):t(59)},d=Xe(r[t(89)])[t(124)](oe)[t(33)](Boolean);d[t(133)]&&(a[t(89)]=d);let p=ly(r[t(90)]);p&&(a[t(90)]=p);let l=oe(r[t(34)]);l&&(a[t(34)]=l);let f=oe(r[t(45)]);f&&(a[t(45)]=f);let u=py(r[t(97)]);u[t(133)]&&(a[t(97)]=u);let g=Xe(r[t(25)])[t(124)](oe)[t(33)](Boolean);g[t(133)]&&(a[t(25)]=g),n[t(6)][t(93)][t(37)](a)}for(let r of Xe(o[t(52)])){if(!gt(r))continue;let s=oe(r[t(129)]);if(!s)continue;let c={name:s},a=Xe(r[t(30)])[t(124)](oe)[t(33)](Boolean);a[t(133)]&&(c[t(30)]=a);let d=ly(r[t(66)]);d&&(c[t(66)]=d);let p=oe(r[t(34)]);p&&(c[t(34)]=p);let l=oe(r[t(45)]);l&&(c[t(45)]=l);let f=Xe(r[t(73)])[t(124)](oe)[t(33)](Boolean);f[t(133)]&&(c[t(73)]=f);let u=py(r[t(146)]);u[t(133)]&&(c[t(146)]=u),Object[t(43)](c)[t(133)]>1&&n[t(6)][t(52)][t(37)](c)}for(let r of Xe(o[t(16)]))if(t(136)!==t(83)){if(!gt(r))continue;let s=oe(r[t(79)]),c=oe(r[t(143)]);s&&c&&n[t(6)][t(16)][t(37)]({from_name:s,canonical_name:c,evidence:oe(r[t(3)])})}else return new _0x440f14(_0x3f4bc4,{exitCode:_0x3e41db,errorCode:t(32),hint:t(15),data:{actual:_0x4f523a}});let i=gt(e[t(114)])?e[t(114)]:{};for(let r of Xe(i[t(122)])){if(!gt(r))continue;let s=oe(r[t(58)]);s&&n[t(114)][t(122)][t(37)]({text:s})}for(let r of Xe(i[t(131)])){if(!gt(r))continue;let s=oe(r[t(115)]);s&&n[t(114)][t(131)][t(37)]({ref:s})}return n}async function gy(e,t,n,o,i,{format:r=W(92),signal:s,local:c,onTimestampMissing:a}={}){let d=W,p=r===d(92),l="";for(let f=0;;f++){let u=await e[d(49)]({media:t,system:p?LA:fy,user:UA(n,o+l,r),fps:i,...p?{acceptsText:cy}:{responseJsonSchema:Vg},...c?{localPath:c[d(53)],localMime:c[d(98)]}:{},...s?{signal:s}:{}}),g=u[d(58)][d(77)]();if(g[d(133)]<40)throw ml(d(69)+n+d(7)+u[d(57)]+")",[d(29)+g[d(133)]]);let h;try{if(d(80)!==d(80)){let x=_0x105277(_0x6cdb53.ts)-_0x14233a(_0x581e0d.ts);return x!==0?x:_0x5b408b[d(51)]===d(19)&&_0x228882[d(51)]!==d(19)?-1:_0x2cad90[d(51)]!==d(19)&&_0x1e0f9a[d(51)]===d(19)?1:0}else h=p?fl(g)[d(26)]:JSON[d(142)](g)}catch{if(d(5)!==d(5))return _0x1f42c4?_0x45d5ba?_0x37ff1a[d(87)](/[。!?;]+$/,"")+"\u3002"+_0x5874dd:_0x5cf61d:_0x2749cd;throw ml(d(69)+n+d(20)+u[d(57)]+")",[g[d(121)](0,200)])}let m=hl(h),w=VA(m);if(w[d(31)][d(133)]===0)throw ml(d(69)+n+d(102),[g[d(121)](0,200)]);let y=w[d(31)][d(75)]((x,E)=>x[d(108)][d(75)]((A,b)=>A.ts?[]:[d(50)+E+d(72)+b+d(39)+A[d(51)]+")"]));if(y[d(133)]>0)if(d(110)!==d(110)){let x=_0x180e17(_0x20bcd6);return x?x[d(2)](/[((//,,、]/)[0][d(77)]():""}else{if(a?.({event:d(67),at:new Date()[d(54)](),episode:n,attempt:f+1,missing_count:y[d(133)],missing_paths:y,retries_exhausted:f===3}),f===3)throw new S(d(81)+n+": "+y[d(133)]+d(8),{exitCode:ee,errorCode:d(18),hint:d(4),data:{actual:y}});l=d(91)+y[d(133)]+d(55)+y[d(22)]("\u3001")+d(74)+d(p?94:27)+d(134);continue}return{transcript:p?g[d(87)](/\u0000/g,""):JSON[d(14)](m,null,2),output:w}}}function Wa(e){return new S("The video skip ledger is invalid.",{exitCode:k,errorCode:"INGEST_SKIP_LEDGER_INVALID",hint:"Repair or remove skipped.json, then retry.",data:{actual:[e]}})}function $A(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(!Number.isInteger(t.episode)||Number(t.episode)<=0||typeof t.skipped_at!="string"||typeof t.reason!="string"||t.reason.trim().length===0||typeof t.source_sha256!="string"||t.source_sha256.length===0||!Array.isArray(t.attempts))return null;let n=ps(t.failure);if(!n)return null;let o=[];for(let i of t.attempts){let r=ps(i);if(!r)return null;o.push(r)}return{episode:Number(t.episode),skipped_at:t.skipped_at,reason:t.reason,source_sha256:t.source_sha256,failure:n,attempts:o}}function yl(e){if(!e.has("skipped.json"))return{schema_version:1,episodes:[]};let t=e.readJson("skipped.json");if(typeof t!="object"||t===null||Array.isArray(t))throw Wa("root must be an object");let n=t;if(n.schema_version!==1||!Array.isArray(n.episodes))throw Wa("schema_version must be 1 and episodes must be an array");let o=[],i=new Set;for(let r of n.episodes){let s=$A(r);if(!s)throw Wa("one or more episode records are malformed");if(i.has(s.episode))throw Wa(`episode ${s.episode} appears more than once`);i.add(s.episode),o.push(s)}return o.sort((r,s)=>r.episode-s.episode),{schema_version:1,episodes:o}}function hy(e,t){e.writeJson("skipped.json",t)}function Xa(e,t){let n=new Map(t.map(o=>[o.episode,o.sha256]));for(let o of e){let i=n.get(o.episode);if(i!==o.source_sha256)throw new S("The video skip ledger no longer matches the source.",{exitCode:k,errorCode:"INGEST_SKIP_SOURCE_MISMATCH",hint:"Restore the source episode recorded by this workspace, or rebuild the same source with --force.",data:{actual:[`episode=${o.episode}`,`ledger_sha256=${o.source_sha256}`,`source_sha256=${i??"<missing>"}`]}})}}function DA(e){return{episode:e,synopsis:"",scenes:[],actors:[],locations:[],props:[],speakers:[],actorStates:[],locationStates:[],propStates:[]}}function ec(e,t,n,o){let i=new Set(o.map(s=>s.episode)),r=[];for(let s of t){if(s.episode>n)break;let c=`ep/ep_${String(s.episode).padStart(3,"0")}.json`;e.has(c)?r.push(e.readJson(c)):i.has(s.episode)&&r.push(DA(s.episode))}return r}function fs(e,t,n){for(let i of n)i.episode<=t.lastEpisode&&e.clearError(`ep/ep_${String(i.episode).padStart(3,"0")}.error.json`);let o=new Map(n.map(i=>[i.episode,i]));for(;;){let i=t.lastEpisode+1;if(!o.has(i))break;gh(t,i),e.writeJson("context.json",t),e.clearError(`ep/ep_${String(i).padStart(3,"0")}.error.json`)}return t}function yy(e,t){for(let n of t){let o=e.episodes[n.episode-1];o&&(o.extend={scriptctl:{ingest:{outcome:"skipped",source_episode:n.episode}}})}}var ms="19",GA=new Set([ms]),Ii=e=>String(e).padStart(3,"0"),wl=2;function _y(e){try{return kt.statSync(e).size}catch{return 0}}function BA(e,t){let n=_y(e);if(!(n<Cd))throw new S(`Episode ${t} is too large for inline base64 video input.`,{exitCode:k,errorCode:"INGEST_VIDEO_INLINE_TOO_LARGE",hint:"Use --upload-mode file-api, or provide a source that transcodes below the Gemini inline limit.",data:{expected:[`video smaller than ${Cd} bytes after ingest transcoding`],actual:[`${n} bytes`]}})}function wy(e,t){try{let n=t.uploadBytes?(t.uploadBytes/1024/1024).toFixed(1):"?",o=JSON.stringify({...t,uploadMB:n,at:new Date().toISOString()})+`
326
- `;kt.appendFileSync(e.path("timing.jsonl"),o)}catch{}}function Ey(e){return new S("This workspace's accepted video sequence no longer matches the source.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Restore the accepted episode prefix, or choose a fresh --workspace-path for a different source.",data:{actual:[e]}})}function _l(e){if(!e.has("manifest.json"))return null;let t=e.readJson("manifest.json");if(!t.pipeline_version||!GA.has(t.pipeline_version))throw new S("This workspace uses an incompatible video-ingest pipeline.",{exitCode:k,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Choose a fresh --workspace-path and run ingest again.",data:{actual:[`workspace pipeline ${t.pipeline_version??"(missing)"}; current ${ms}`]}});return e.readJson("manifest.json")}function El(e,t){if(t.pipeline_version===ms)return t;let n={...t,pipeline_version:ms,updated:new Date().toISOString()};return e.writeJson("manifest.json",n),n}function JA(e,t,n){if(e&&e.source.kind!==t)throw Ey(`source kind changed from ${e.source.kind} to ${t}`)}function jA(e,t,n,o){if(t){let i=Ph(t.episodes,n);if(i.kind==="incompatible")throw Ey(i.reason)}if(o){kt.rmSync(e.path("ep"),{recursive:!0,force:!0}),kt.rmSync(e.path("cache"),{recursive:!0,force:!0}),kt.rmSync(e.path("evidence"),{recursive:!0,force:!0});for(let i of["context.json","script.initial.json","script.json","validation.json","asset-audit.json","id_map.json","timing.jsonl","usage.json","v4_identity_map.json","skipped.json"])kt.rmSync(e.path(i),{force:!0})}}function KA(e,t){return e.map(n=>{let o=structuredClone(n);for(let i of o.actors)i.name=fr(i.name,t)??i.name;for(let i of o.scenes){for(let c of i.characters)c.name=fr(c.name,t)??c.name;i.location&&(i.location=fr(i.location,t)??i.location);let r=[],s=new Set;for(let c of i.props){let a=(fr(c,t)??c).trim();if(!a)continue;let d=a.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();s.has(d)||(s.add(d),r.push(a))}i.props=r;for(let c of i.anchors)c.speaker=fr(c.speaker,t)}return o})}function zA(e,t){let n=t.slice(0,8).map(o=>`- ${o.path}: ${o.message}`).join(`
324
+ open \u6797\u665A\u662F\u5426\u7B7E\u4E0B\u79BB\u5A5A\u534F\u8BAE`;var Z=mn,hy=Z(133),UA=hy[Z(84)](Z(24),Z(105))[Z(84)](Z(111),Z(0))[Z(16)](Z(82),Z(93))+`
325
+ `+uy;function PA(e,t,n=Z(35)){let o=Z,i=t[o(43)]()?o(10)+t+`
326
+ `:o(47);return(n===o(35)?o(45)+e+o(102):o(45)+e+o(136))+o(67)+i}function hl(e,t){let n=Z;return new x(e,{exitCode:X,errorCode:n(92),hint:n(123),data:{actual:t}})}var yl=e=>{let t=Z;return typeof e===t(130)?e[t(84)](/\u0000/g,""):Array[t(114)](e)?e[t(26)](yl):gt(e)?Object[t(34)](Object[t(121)](e)[t(26)](([n,o])=>[n,yl(o)])):e};function wl(){let e=["kIRLJ6ROVPpLH7ROR6uGrfnmioAwH+ACRo+8Jos4JEIMGEs7U+s9LEMINEwKLUAwH+wTL+oaGEINO+MhIUAiLUs7O+EGGEwDL+wmHEIJUEoaGIOQ","BwLTzq","BM9YBwfSAxPL","C3rHDhvZ","zMLUza","Aw5JBhvKzxm","z2v0","y2HHCMfJDgvYCW","xs5HBMnOB3jZwW","ywrKx3n0yxrLCW","pt09pt09pt09psdLT7lNN6xORR7LRPRVViJLIldKUiRKUidPM4BKUlRMRAlVViZOP4tOJipLKi3KU6xMRAtKUlRLH4BVViKGpt09pt09pt09pqO","AM9PBG","C3rYAw5NAwz5","AwrLBNrPDhLFChjVzMLSzq","B3bLBMvK","C3LUB3bZAxm","CMvWBgfJzufSBa","vLj1quS","C2XPy2u","ww9Ysgi","AxngAw5PDgu","yNvPBgq","yxbWyxjLBNrFywDL","y29UDgvUDa","5l2G6kAb6l6t5yE6kIRKUidKUkRNU5pMNOtLJjyGsLnptIdLR7NOSAeQkU+8Ios4PEAGVoESPUwqIoACRos7U+wkOEwUMUs5IEEAHcbku09oioE7K+AEHo+8Iq","CMvJB2DUAxrPB25Fyw5JAg9YCW","BwfW","AwrLBNrPDhLFChjVzMLSzv9WyxrJAa","DMfSDwu","zw5YAwnO","zMXHDe1HCa","Bw91DgG","C29YDa","A2v5CW","zNjVBuvUDhjPzxm","zhnS","yNjVD3nFzxLLCW","A2LUza","C3rHDgvZ","ywrKx3jLy29NBML0Aw9Ux2fUy2HVCNm","6l+u5zUE5A6m5Pw0iePtt04","ChjVDMLZAw9UywW","oIbZzxjPywWGB3v0Chv0ihrVBYbZAg9YDcaOzMLUAxnOuMvHC29Upq","DhjPBq","sw5ZCgvJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbPBMDLC3qGDg8GCMvZDw1LlG","6kEJ5P6q56YSia","CgfYC2u","77Yi6l+z5PIV56YS5lIa6zUg77Ym5PQc5PEG5BEY55+L6k6+5A6A44cc77YjcG","6l+u5zUE5A6m5Pw0iert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iikcG","DMLZDwfS","C3bLywTLCG","oIbZzxjPywWGB3v0Chv0ihDHCYbUB3qGDMfSAwqGsLnptIaOzMLUAxnOuMvHC29Upq","zMfJzv9ZAgfWzq","y2fUB25Py2fSAxPL","44cc6k+36yEn5PAW6kEc55Yl5B2t5yMn6zUg77Ym5lI65Q+p5lIa5P2HihnOB3rZiowsJcb2B2LJzxmG5AgR5yAz55YF5A6E6lw354k5ihrZ77Yitu06u1pVViZLJ6/KV53NLzNOR4hMJA7MLk/MJihNMOqGmEkaKZmG5l2n5Bcp5PwW77Yj77Ym5lIn5B6x57Y65AsX44cb55wz56M65OIw5AgRig51BgZVVjS","Dg9ju09tDhjPBMC","Dg1tBuS","C3bSAxq","xsaO","zMLSDgvY","DgLTzxn0yw1Wx21PC3nPBMC","B2jQzwn0","zgXN","sLnptG","DgLTzq","CMvWBgfJzq","DgHPBMS","C2nLBMvZ","rxbPC29Kzsa","CMvNAxn0CNLFzgvSDge","CM9Szq","BMv3x2vUDgL0AwvZ","cGRKUiRMRkhOVPpLH7RMNiKG","su5hrvnux1zjrevpx1nfuKLbtf9gquLmruq","rfnm","AgfPCG","uuruqwC","CMvM","Cgf0Aa","y2XVC2vK","ChvZAa","z2vUzxjHDgu","igfUy2HVCNmGC3rPBgWGAgf2zsbUBYb0Aw1LC3rHBxaGywz0zxiGmYbYzxrYAwvZlG","ioMBHU+8MUwVUEEfP+ACRoMBHUwoN+INHUMIKE+8JoAmIEACRos7U+wkOEwUMUs5IEEAHoIHJow8JYbeu0WG6l+u5zUE57QV5PAh5PYS44cc5y+Q6l+u5zUEierttcdMNkZOUQVVViZKUi3OPOhOVPpLH7ROP6pPH4RJGihLIy3OQidJGifku09oioAiLIbnyxjRzg93BIdKU6pNOihLNzFJGii","ywXPyxnLCW","ywn0B3i","5l2G6kAb6l6t5yE6kIRKUidKU73KUkxMOlZNRkBLKiJMNkZKU7VLIQhOOyZLVi8GrfnmioEAHoE6R+AwH+ACRcOQ","svDIz1q","ChjVCa","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5P2H44cc5lIK5lQ65zcm5PE26k+06k+D5PE26l6t5yE655U46yk75lIK5P2HihzVAwnL77Ym56YS5lQm5P2HihbHCMvUDgHLDgLJywWG5lUL44co5zcm5PE244cp5BYa5As044cc5yw35l2t5y2v5lQ65l2/55sO6kEe6iYd5zcn77YB5PEG5Rov5yY65yIg5OIq5zgy55Qe5lYx5lQ644cb576K5lYx44cb6lEV5lQ6562j5ywX5zcm5y+r5AoW5PE2ihnWzwfRzxiG5yAz44coz3jVDxa6576K5l2t5zcn44cp77Ym5lIn5yIx5ywLignOyxjHy3rLCNmG5zkmihjLz2LZDhj5x2rLBhrH44cccUoaKoIsMEwKQUwLH+oaKEwqJowCSoEcUEI/NUE7REIsMEwKQUwLH+s/NEEvMEs4GowCUU+8M+I3QowCSoEcUEIsMEwKQUwLH+AmIEwjQUI+KEMHUUw6J+AlHUAiKowKMUs4QUEFRsbZy2vUzE+8JoAVJ+wCUUE7KEwUMUIhQUw3SEEAHcbSB2nHDgLVBUoaGwnOyxjHy3rLCNpJGifWCM9WCYdLKOWGC3rHDgxVViZLUBBNLkGGC2HVDhmG5PIo56gU6jkz5AsQ5Awh5BYa5AEl44cb5yIh5O2I5zkm57Ut5P2F44cc","DM9Py2u","B21zr0m","ioMBHU+8MUwVUEEfP+ACRoMBHUwoN+INHUMIKE+8JoAmIEACRos7U+wkOEwUMUs5IEEAHcbku09oioE7K+AEHoI/LowBNUs4Gos4QIbku09oiowVUEIXOEoaGUwpQUI/LowBNIbku09oioACRoI6Q++8Jos4JEIMGEI+K+whUUINO+MhIUoaGEwjJEIOGoAiLIbnyxjRzg93BIdKU6pNOihLNzFJGii","DgLTzvjHBMDL","B3bLBL90AhjLywrZ","Aw1WB3j0yw5Jzq","y2fTzxjH","ywrK","zMvHDhvYzwq","C2nLBMvZwW","C2v0","yxbWzwfYyw5Jzq"];return wl=function(){return e},wl()}function mn(e,t){e=e-0;let n=wl(),o=n[e];if(mn.GXuCDP===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,m=0;u=c.charAt(m++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=a.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};mn.TayOYa=i,mn.winblo={},mn.GXuCDP=!0}let r=n[0];mn.qurXzJ!==r&&(mn.winblo={},mn.qurXzJ=r);let s=mn.winblo[e];return s===void 0?(o=mn.TayOYa(o),mn.winblo[e]=o):o=s,o}var gt=e=>typeof e===Z(80)&&e!==null&&!Array[Z(114)](e),ne=e=>typeof e===Z(130)?e[Z(43)]():"",Xe=e=>Array[Z(114)](e)?e:[],yy=e=>{let t=Z,n=ne(e);return n?n[t(76)](/[((//,,、]/)[0][t(43)]():""},CA=e=>[...new Set(Xe(e)[Z(26)](yy)[Z(78)](Boolean))],fy=e=>{let t=Z,n=[];for(let o of Xe(e))if(t(75)===t(75)){if(!gt(o))continue;let i=yy(o[t(112)]);if(!i)continue;let r=ne(o[t(115)]),s=n[t(4)](c=>c[t(112)]===i);s?t(19)!==t(19)?_0xc4ffd4[t(38)][t(5)](_0x35dc37)||_0x31794b[t(38)][t(99)](_0x19a827):!s[t(115)]&&r&&(s[t(115)]=r):n[t(99)]({name:i,description:r})}else{let i=_0x1f0db4(_0x508e13);return i?i[t(76)](/[((//,,、]/)[0][t(43)]():""}return n},TA=[Z(54),Z(22),Z(71),Z(36),Z(57),Z(31),Z(108),Z(94),Z(21),Z(134)],my=e=>{let t=Z;if(!gt(e))return;let n={apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:Xe(e[t(116)])[t(26)](ne)[t(78)](Boolean),voice:""};for(let o of TA)n[o]=ne(e[o]);return n},gy=e=>{let t=Z;if(!e)return Number[t(60)];let n=e[t(76)](":")[t(26)](Number);return n[t(125)](o=>!Number[t(20)](o))?Number[t(60)]:n[t(66)]===2?n[0]*60+n[1]:n[t(66)]===3?n[0]*3600+n[1]*60+n[2]:Number[t(60)]},VA=(e,t)=>{let n=Z;return e?t?e[n(84)](/[。!?;]+$/,"")+"\u3002"+t:e:t};function $A(e){let t=Z,n={synopsis:"",scenes:[],registry_delta:{new_entities:[],enrich:[],canonicalize:[]},open_threads:{opened:[],closed:[]}};if(!gt(e))return n;n[t(15)]=ne(e[t(15)]);for(let r of Xe(e[t(86)])){if(!gt(r))continue;let s={},c=ne(r[t(122)]);c&&(s[t(122)]=c);let a=Lo(r[t(83)]);a&&(s[t(83)]=a);let d=new Map;for(let g of Xe(r[t(7)])){if(!gt(g))continue;let w=ne(g[t(112)]);if(!w||ct(w))continue;let y=d[t(6)](w)??{name:w,states:[]};for(let _ of CA(g[t(38)]))y[t(38)][t(5)](_)||y[t(38)][t(99)](_);d[t(144)](w,y)}let p=[],l=new Set;for(let g of Xe(r[t(64)])[t(26)](ne)[t(78)](Boolean)){let w=g[t(2)](t(119))[t(84)](/\s+/g," ")[t(43)]();!w||l[t(63)](w)||(l[t(141)](w),p[t(99)](g[t(43)]()))}let f=[];for(let g of Xe(r[t(109)])){if(!gt(g))continue;let w=VA(ne(g[t(140)]),ne(g[t(68)]));if(!w)continue;let y={kind:t(120),content:w},_=mr(g.ts);_&&(y.ts=_),f[t(99)](y)}for(let g of Xe(r[t(118)]))if(t(95)===t(51))_0x30ee81[t(99)]({name:_0x355c5a,description:_0x4da21c});else{if(!gt(g))continue;let w=ne(g[t(37)]);if(w!==t(81)&&w!==t(85))continue;let y=ne(g[t(23)]);if(!y)continue;let _={kind:w,content:y},S=ne(g[t(69)]);S&&(_[t(69)]=S);let E=ne(g[t(128)]);E&&(_[t(128)]=E);let A=mr(g.ts);A&&(_.ts=A),f[t(99)](_)}f[t(32)]((g,w)=>{let y=t,_=gy(g.ts)-gy(w.ts);return _!==0?_:g[y(37)]===y(120)&&w[y(37)]!==y(120)?-1:g[y(37)]!==y(120)&&w[y(37)]===y(120)?1:0});let u={environment:s,characters:[...d[t(113)]()],props:p,anchors:f},m=ne(r[t(137)]);m&&(u[t(137)]=m);let h=ne(r[t(65)]);h&&(u[t(65)]=h),n[t(86)][t(99)](u)}let o=gt(e[t(88)])?e[t(88)]:{};for(let r of Xe(o[t(90)]))if(t(131)!==t(131))_0x1b303d=_0x22fe59?_0x21844b(_0x3851db)[t(28)]:_0x368603[t(46)](_0xace99f);else{if(!gt(r))continue;let s=ne(r[t(112)]),c=ne(r[t(37)]);if(!s||c!==t(104)&&c!==t(65)&&c!==t(107)||c===t(104)&&ct(s))continue;let a={name:s,kind:c,status:ne(r[t(3)])===t(41)?t(41):t(55),importance:ne(r[t(139)])===t(127)?t(127):t(142)},d=Xe(r[t(25)])[t(26)](ne)[t(78)](Boolean);d[t(66)]&&(a[t(25)]=d);let p=my(r[t(13)]);p&&(a[t(13)]=p);let l=ne(r[t(145)]);l&&(a[t(145)]=l);let f=ne(r[t(89)]);f&&(a[t(89)]=f);let u=fy(r[t(38)]);u[t(66)]&&(a[t(38)]=u);let m=Xe(r[t(103)])[t(26)](ne)[t(78)](Boolean);m[t(66)]&&(a[t(103)]=m),n[t(88)][t(90)][t(99)](a)}for(let r of Xe(o[t(29)]))if(t(17)!==t(106)){if(!gt(r))continue;let s=ne(r[t(112)]);if(!s)continue;let c={name:s},a=Xe(r[t(39)])[t(26)](ne)[t(78)](Boolean);a[t(66)]&&(c[t(39)]=a);let d=my(r[t(27)]);d&&(c[t(27)]=d);let p=ne(r[t(145)]);p&&(c[t(145)]=p);let l=ne(r[t(89)]);l&&(c[t(89)]=l);let f=Xe(r[t(117)])[t(26)](ne)[t(78)](Boolean);f[t(66)]&&(c[t(117)]=f);let u=fy(r[t(9)]);u[t(66)]&&(c[t(9)]=u),Object[t(33)](c)[t(66)]>1&&n[t(88)][t(29)][t(99)](c)}else{let s=_0x4a8d4e[t(43)]()?t(10)+_0x17dc83+`
327
+ `:t(47);return(_0x555352===t(35)?t(45)+_0x3bae08+t(102):t(45)+_0x5ba912+t(136))+t(67)+s}for(let r of Xe(o[t(72)])){if(!gt(r))continue;let s=ne(r[t(62)]),c=ne(r[t(124)]);s&&c&&n[t(88)][t(72)][t(99)]({from_name:s,canonical_name:c,evidence:ne(r[t(126)])})}let i=gt(e[t(138)])?e[t(138)]:{};for(let r of Xe(i[t(14)])){if(!gt(r))continue;let s=ne(r[t(59)]);s&&n[t(138)][t(14)][t(99)]({text:s})}for(let r of Xe(i[t(98)])){if(t(110)===t(61))return typeof _0xd82b7a===t(130)?_0x43c45c[t(84)](/\u0000/g,""):_0x32503f[t(114)](_0x19e475)?_0x1c6321[t(26)](_0x5bbfe2):_0x4da7c2(_0x460c3a)?_0x2437df[t(34)](_0x347e13[t(121)](_0x72cf43)[t(26)](([s,c])=>[s,_0x5e22de(c)])):_0x2793c2;{if(!gt(r))continue;let s=ne(r[t(96)]);s&&n[t(138)][t(98)][t(99)]({ref:s})}}return n}async function wy(e,t,n,o,i,{format:r=Z(35),signal:s,local:c,onTimestampMissing:a}={}){let d=Z,p=r===d(35),l="";for(let f=0;;f++){let u=await e[d(100)]({media:t,system:p?UA:hy,user:PA(n,o+l,r),fps:i,...p?{acceptsText:ly}:{responseJsonSchema:Gg},...c?{localPath:c[d(97)],localMime:c[d(1)]}:{},...s?{signal:s}:{}}),m=u[d(59)][d(43)]();if(m[d(66)]<40)throw hl(d(132)+n+d(42)+u[d(50)]+")",[d(129)+m[d(66)]]);let h;try{h=p?gl(m)[d(28)]:JSON[d(46)](m)}catch{throw hl(d(132)+n+d(70)+u[d(50)]+")",[m[d(18)](0,200)])}let g=yl(h),w=$A(g);if(w[d(86)][d(66)]===0)throw hl(d(132)+n+d(52),[m[d(18)](0,200)]);let y=w[d(86)][d(30)]((S,E)=>S[d(56)][d(30)]((A,b)=>A.ts?[]:[d(143)+E+d(8)+b+d(77)+A[d(37)]+")"]));if(y[d(66)]>0){if(a?.({event:d(79),at:new Date()[d(74)](),episode:n,attempt:f+1,missing_count:y[d(66)],missing_paths:y,retries_exhausted:f===3}),f===3)if(d(135)!==d(135))!_0x500af0[d(115)]&&_0x8adabe&&(_0x7f882f[d(115)]=_0x30b2fe);else throw new x(d(87)+n+": "+y[d(66)]+d(101),{exitCode:X,errorCode:d(53),hint:d(44),data:{actual:y}});l=d(91)+y[d(66)]+d(58)+y[d(11)]("\u3001")+d(73)+d(p?48:40)+d(49);continue}return{transcript:p?m[d(84)](/\u0000/g,""):JSON[d(12)](g,null,2),output:w}}}function ec(e){return new x("The video skip ledger is invalid.",{exitCode:k,errorCode:"INGEST_SKIP_LEDGER_INVALID",hint:"Repair or remove skipped.json, then retry.",data:{actual:[e]}})}function DA(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(!Number.isInteger(t.episode)||Number(t.episode)<=0||typeof t.skipped_at!="string"||typeof t.reason!="string"||t.reason.trim().length===0||typeof t.source_sha256!="string"||t.source_sha256.length===0||!Array.isArray(t.attempts))return null;let n=ls(t.failure);if(!n)return null;let o=[];for(let i of t.attempts){let r=ls(i);if(!r)return null;o.push(r)}return{episode:Number(t.episode),skipped_at:t.skipped_at,reason:t.reason,source_sha256:t.source_sha256,failure:n,attempts:o}}function _l(e){if(!e.has("skipped.json"))return{schema_version:1,episodes:[]};let t=e.readJson("skipped.json");if(typeof t!="object"||t===null||Array.isArray(t))throw ec("root must be an object");let n=t;if(n.schema_version!==1||!Array.isArray(n.episodes))throw ec("schema_version must be 1 and episodes must be an array");let o=[],i=new Set;for(let r of n.episodes){let s=DA(r);if(!s)throw ec("one or more episode records are malformed");if(i.has(s.episode))throw ec(`episode ${s.episode} appears more than once`);i.add(s.episode),o.push(s)}return o.sort((r,s)=>r.episode-s.episode),{schema_version:1,episodes:o}}function _y(e,t){e.writeJson("skipped.json",t)}function tc(e,t){let n=new Map(t.map(o=>[o.episode,o.sha256]));for(let o of e){let i=n.get(o.episode);if(i!==o.source_sha256)throw new x("The video skip ledger no longer matches the source.",{exitCode:k,errorCode:"INGEST_SKIP_SOURCE_MISMATCH",hint:"Restore the source episode recorded by this workspace, or rebuild the same source with --force.",data:{actual:[`episode=${o.episode}`,`ledger_sha256=${o.source_sha256}`,`source_sha256=${i??"<missing>"}`]}})}}function GA(e){return{episode:e,synopsis:"",scenes:[],actors:[],locations:[],props:[],speakers:[],actorStates:[],locationStates:[],propStates:[]}}function nc(e,t,n,o){let i=new Set(o.map(s=>s.episode)),r=[];for(let s of t){if(s.episode>n)break;let c=`ep/ep_${String(s.episode).padStart(3,"0")}.json`;e.has(c)?r.push(e.readJson(c)):i.has(s.episode)&&r.push(GA(s.episode))}return r}function ms(e,t,n){for(let i of n)i.episode<=t.lastEpisode&&e.clearError(`ep/ep_${String(i.episode).padStart(3,"0")}.error.json`);let o=new Map(n.map(i=>[i.episode,i]));for(;;){let i=t.lastEpisode+1;if(!o.has(i))break;wh(t,i),e.writeJson("context.json",t),e.clearError(`ep/ep_${String(i).padStart(3,"0")}.error.json`)}return t}function Ey(e,t){for(let n of t){let o=e.episodes[n.episode-1];o&&(o.extend={scriptctl:{ingest:{outcome:"skipped",source_episode:n.episode}}})}}var gs="19",BA=new Set([gs]),Ai=e=>String(e).padStart(3,"0"),El=2;function Sy(e){try{return kt.statSync(e).size}catch{return 0}}function JA(e,t){let n=Sy(e);if(!(n<Vd))throw new x(`Episode ${t} is too large for inline base64 video input.`,{exitCode:k,errorCode:"INGEST_VIDEO_INLINE_TOO_LARGE",hint:"Use --upload-mode file-api, or provide a source that transcodes below the Gemini inline limit.",data:{expected:[`video smaller than ${Vd} bytes after ingest transcoding`],actual:[`${n} bytes`]}})}function xy(e,t){try{let n=t.uploadBytes?(t.uploadBytes/1024/1024).toFixed(1):"?",o=JSON.stringify({...t,uploadMB:n,at:new Date().toISOString()})+`
328
+ `;kt.appendFileSync(e.path("timing.jsonl"),o)}catch{}}function Iy(e){return new x("This workspace's accepted video sequence no longer matches the source.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Restore the accepted episode prefix, or choose a fresh --workspace-path for a different source.",data:{actual:[e]}})}function xl(e){if(!e.has("manifest.json"))return null;let t=e.readJson("manifest.json");if(!t.pipeline_version||!BA.has(t.pipeline_version))throw new x("This workspace uses an incompatible video-ingest pipeline.",{exitCode:k,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Choose a fresh --workspace-path and run ingest again.",data:{actual:[`workspace pipeline ${t.pipeline_version??"(missing)"}; current ${gs}`]}});return e.readJson("manifest.json")}function Sl(e,t){if(t.pipeline_version===gs)return t;let n={...t,pipeline_version:gs,updated:new Date().toISOString()};return e.writeJson("manifest.json",n),n}function KA(e,t,n){if(e&&e.source.kind!==t)throw Iy(`source kind changed from ${e.source.kind} to ${t}`)}function jA(e,t,n,o){if(t){let i=Vh(t.episodes,n);if(i.kind==="incompatible")throw Iy(i.reason)}if(o){kt.rmSync(e.path("ep"),{recursive:!0,force:!0}),kt.rmSync(e.path("cache"),{recursive:!0,force:!0}),kt.rmSync(e.path("evidence"),{recursive:!0,force:!0});for(let i of["context.json","script.initial.json","script.json","validation.json","asset-audit.json","id_map.json","timing.jsonl","usage.json","v4_identity_map.json","skipped.json"])kt.rmSync(e.path(i),{force:!0})}}function zA(e,t){return e.map(n=>{let o=structuredClone(n);for(let i of o.actors)i.name=gr(i.name,t)??i.name;for(let i of o.scenes){for(let c of i.characters)c.name=gr(c.name,t)??c.name;i.location&&(i.location=gr(i.location,t)??i.location);let r=[],s=new Set;for(let c of i.props){let a=(gr(c,t)??c).trim();if(!a)continue;let d=a.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();s.has(d)||(s.add(d),r.push(a))}i.props=r;for(let c of i.anchors)c.speaker=gr(c.speaker,t)}return o})}function HA(e,t){let n=t.slice(0,8).map(o=>`- ${o.path}: ${o.message}`).join(`
327
329
  `);return`${e}
328
330
 
329
331
  ========== \u4E0A\u4E00\u6B21\u8F93\u51FA\u7684\u6574\u5408\u6821\u9A8C\u53CD\u9988 ==========
330
332
  \u4E0A\u4E00\u6B21\u5BF9\u672C\u96C6\u7684\u7ED3\u6784\u5316\u8F93\u51FA\u6CA1\u6709\u5199\u5165 checkpoint\uFF0C\u56E0\u4E3A\u4E0E\u65E2\u6709\u5267\u672C\u5408\u5E76\u540E\u8FDD\u53CD\u4E86\u4EE5\u4E0B\u7EA6\u675F\uFF1A
331
333
  ${n}
332
- \u8BF7\u91CD\u65B0\u89C2\u770B\u672C\u96C6\u5E76\u8FD4\u56DE\u5B8C\u6574\u8F93\u51FA\u3002\u4FDD\u6301\u539F\u7247\u4E8B\u5B9E\u3001\u5BF9\u767D\u3001\u955C\u5934\u4E0E\u5DF2\u77E5\u4EBA\u7269\u4E0D\u53D8\uFF0C\u53EA\u4FEE\u6B63\u5BFC\u81F4\u6821\u9A8C\u5931\u8D25\u7684\u4EBA\u7269\u547D\u540D\u3001\u8D44\u4EA7\u7ED1\u5B9A\u6216 registry_delta\u3002\u4EBA\u7269\u89C4\u8303\u540D\u4E0D\u5F97\u7528\u62EC\u53F7\u5907\u6CE8\u533A\u5206\u89D2\u8272\uFF1B\u89D2\u8272\u804C\u80FD\u5199\u5165 role\uFF0C\u4E0D\u540C\u4EBA\u7269\u4F7F\u7528\u5F52\u4E00\u540E\u4ECD\u552F\u4E00\u7684\u89C4\u8303\u540D\u3002`}function xy(e,t,n,o,i=[]){let r=$o(t.registry),s=KA(e,r),c=Th(s,n),a=Va(c,t,"video",o);if(!a.scriptV4)return a;let{scriptV4:d,initial:p,idMap:l,identityMap:f}=a;yy(d,i);let u=Pe(d),g=[...d.actors.map((m,w)=>({asset:m,path:`$.actors[${w}]`})),...d.locations.map((m,w)=>({asset:m,path:`$.locations[${w}]`})),...d.props.map((m,w)=>({asset:m,path:`$.props[${w}]`}))].flatMap(({asset:m,path:w})=>[...m.description.trim()?[]:[{code:"video_asset_description_missing",path:`${w}.description`,message:"video asset needs a source-grounded description"}],...m.states.flatMap((y,_)=>y.description.trim()?[]:[{code:"video_state_description_missing",path:`${w}.states[${_}].description`,message:"video asset state needs a source-grounded visual description"}])]),h={...u,warnings:[...u.warnings,...ir(d),...g,...i.map(m=>({code:"episode_skipped",path:`$.episodes[${m.episode-1}]`,message:`Episode ${m.episode} was manually skipped: ${m.reason}`}))]};return{initial:p,final:d,idMap:l,validation:h,identityMap:f}}function tc(e,t,n,o,i,r){let s=xy(ec(e,t,n.lastEpisode,r),n,o,i,r.filter(l=>l.episode<=n.lastEpisode)),{initial:c,final:a,idMap:d,validation:p}=s;if(e.writeJson("script.initial.json",c),e.writeJson("id_map.json",d),e.writeJson("validation.json",p),e.writeJson("v4_identity_map.json",s.identityMap),!p.ok)throw new S("Final script.json failed validation.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:p.errors.slice(0,5).map(l=>`${l.path}: ${l.message}`)}});return e.writeJson("script.json",a),s}async function HA(e,t,n,o,i,r,s){return Za(e,Fa(t,n,o,i,r),s)}async function FA(e){let t=On(e.sourcePath);if(t.kind!=="video-file"&&t.kind!=="video-directory")throw new S("runVideoIngest requires a video source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=[...Ya(t)].sort((m,w)=>m.episode-w.episode),o=Ha(n);if(o)throw new S("Video episodes must form one continuous sequence starting at episode 1.",{exitCode:k,errorCode:"INGEST_VIDEO_SEQUENCE",hint:"Add or rename files so the discovered episode numbers are 1..N with no gaps.",data:{actual:[o]}});let i=e.fps??3,r=e.force??!1,s=e.step??!1,c=e.uploadMode??"file-api",a=e.signal,d=new ft(e.workspacePath);d.ensure();let p=_l(d),l=Qt.resolve(t.path);JA(p,t.kind,l);let f=oy(n,p?.episodes??[],p?.updated);jA(d,p,f,r);let u={version:2,pipeline_version:ms,updated:new Date().toISOString(),source:{kind:t.kind,path:l,sha256:qa(f)},episodes:f,fps:i,skips:r?[]:p?.skips??[]};d.writeJson("manifest.json",u);let g=new To(d,e.executor),h="failed";try{let m=null,w=nc(e.sourcePath),y=!r&&d.has("context.json")?d.readJson("context.json"):Vo(),_={schema_version:1,episodes:u.skips??[]};Xa(_.episodes,f),r||fs(d,y,_.episodes);let x=new Set(_.episodes.map(j=>j.episode)),E=!r&&d.has("v4_identity_map.json")?d.readJson("v4_identity_map.json"):Co(),A=new Set(n.filter(j=>!r&&!x.has(j.episode)&&j.episode<=y.lastEpisode&&d.has(`ep/ep_${Ii(j.episode)}.json`)).map(j=>j.episode));g.recordReusedEpisodes("ingest.video-serial",[...A]);let b=A.size,C=0;for(let j of n){let Ot=`ep/ep_${Ii(j.episode)}.json`;if(!r&&x.has(j.episode)&&j.episode<=y.lastEpisode||A.has(j.episode))continue;if(s&&C>=1)break;let P=Ta(y);d.writeText(`ep/ep_${Ii(j.episode)}.context.md`,P);let de,Se,vt,Cn,Ri=Date.now(),Rt={episode:j.episode,uploadMode:c,status:"succeeded",totalMs:0},bs="transcode";try{let gn=Date.now(),ht=await ry(j.path,d.path(`cache/ep_${Ii(j.episode)}.mp4`),j.mime,a);Rt.transcodeMs=Date.now()-gn,Rt.uploadBytes=_y(ht.path),Rt.transcoded=ht.transcoded,ht.note&&(Rt.note=ht.note),c==="base64"&&BA(ht.path,j.episode),bs="upload",m??=e.executor.videoPort("ingest.video-serial");let hc=Date.now(),ao=await m.prepare(ht.path,ht.mime,c,a);Rt.uploadMs=Date.now()-hc;try{bs="generate";let yc=Date.now(),bw=ec(d,n,y.lastEpisode,_.episodes),wc=P;for(let Os=1;Os<=wl;Os++){let vs;try{vs=await gy(m,ao,j.episode,wc,i,{format:e.outputFormat??"dsl",...a?{signal:a}:{},local:{path:ht.path,mime:ht.mime},onTimestampMissing:Yt=>kt.appendFileSync(d.path("ingest-validation.jsonl"),JSON.stringify(Yt)+`
333
- `)})}catch(Yt){if(!(Yt instanceof S)||Yt.errorCode!=="INGEST_VIDEO_SERIAL_FAILED"||Os===wl)throw Yt;wc=`${P}
334
+ \u8BF7\u91CD\u65B0\u89C2\u770B\u672C\u96C6\u5E76\u8FD4\u56DE\u5B8C\u6574\u8F93\u51FA\u3002\u4FDD\u6301\u539F\u7247\u4E8B\u5B9E\u3001\u5BF9\u767D\u3001\u955C\u5934\u4E0E\u5DF2\u77E5\u4EBA\u7269\u4E0D\u53D8\uFF0C\u53EA\u4FEE\u6B63\u5BFC\u81F4\u6821\u9A8C\u5931\u8D25\u7684\u4EBA\u7269\u547D\u540D\u3001\u8D44\u4EA7\u7ED1\u5B9A\u6216 registry_delta\u3002\u4EBA\u7269\u89C4\u8303\u540D\u4E0D\u5F97\u7528\u62EC\u53F7\u5907\u6CE8\u533A\u5206\u89D2\u8272\uFF1B\u89D2\u8272\u804C\u80FD\u5199\u5165 role\uFF0C\u4E0D\u540C\u4EBA\u7269\u4F7F\u7528\u5F52\u4E00\u540E\u4ECD\u552F\u4E00\u7684\u89C4\u8303\u540D\u3002`}function Ay(e,t,n,o,i=[]){let r=$o(t.registry),s=zA(e,r),c=Dh(s,n),a=Da(c,t,"video",o);if(!a.scriptV4)return a;let{scriptV4:d,initial:p,idMap:l,identityMap:f}=a;Ey(d,i);let u=Pe(d),m=[...d.actors.map((g,w)=>({asset:g,path:`$.actors[${w}]`})),...d.locations.map((g,w)=>({asset:g,path:`$.locations[${w}]`})),...d.props.map((g,w)=>({asset:g,path:`$.props[${w}]`}))].flatMap(({asset:g,path:w})=>[...g.description.trim()?[]:[{code:"video_asset_description_missing",path:`${w}.description`,message:"video asset needs a source-grounded description"}],...g.states.flatMap((y,_)=>y.description.trim()?[]:[{code:"video_state_description_missing",path:`${w}.states[${_}].description`,message:"video asset state needs a source-grounded visual description"}])]),h={...u,warnings:[...u.warnings,...sr(d),...m,...i.map(g=>({code:"episode_skipped",path:`$.episodes[${g.episode-1}]`,message:`Episode ${g.episode} was manually skipped: ${g.reason}`}))]};return{initial:p,final:d,idMap:l,validation:h,identityMap:f}}function oc(e,t,n,o,i,r){let s=Ay(nc(e,t,n.lastEpisode,r),n,o,i,r.filter(l=>l.episode<=n.lastEpisode)),{initial:c,final:a,idMap:d,validation:p}=s;if(e.writeJson("script.initial.json",c),e.writeJson("id_map.json",d),e.writeJson("validation.json",p),e.writeJson("v4_identity_map.json",s.identityMap),!p.ok)throw new x("Final script.json failed validation.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:p.errors.slice(0,5).map(l=>`${l.path}: ${l.message}`)}});return e.writeJson("script.json",a),s}async function FA(e,t,n,o,i,r,s){return Xa(e,Ya(t,n,o,i,r),s)}async function QA(e){let t=On(e.sourcePath);if(t.kind!=="video-file"&&t.kind!=="video-directory")throw new x("runVideoIngest requires a video source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=[...Za(t)].sort((g,w)=>g.episode-w.episode),o=Qa(n);if(o)throw new x("Video episodes must form one continuous sequence starting at episode 1.",{exitCode:k,errorCode:"INGEST_VIDEO_SEQUENCE",hint:"Add or rename files so the discovered episode numbers are 1..N with no gaps.",data:{actual:[o]}});let i=e.fps??3,r=e.force??!1,s=e.step??!1,c=e.uploadMode??"file-api",a=e.signal,d=new ft(e.workspacePath);d.ensure();let p=xl(d),l=Qt.resolve(t.path);KA(p,t.kind,l);let f=sy(n,p?.episodes??[],p?.updated);jA(d,p,f,r);let u={version:2,pipeline_version:gs,updated:new Date().toISOString(),source:{kind:t.kind,path:l,sha256:Wa(f)},episodes:f,fps:i,skips:r?[]:p?.skips??[]};d.writeJson("manifest.json",u);let m=new To(d,e.executor),h="failed";try{let g=null,w=ic(e.sourcePath),y=!r&&d.has("context.json")?d.readJson("context.json"):Vo(),_={schema_version:1,episodes:u.skips??[]};tc(_.episodes,f),r||ms(d,y,_.episodes);let S=new Set(_.episodes.map(K=>K.episode)),E=!r&&d.has("v4_identity_map.json")?d.readJson("v4_identity_map.json"):Co(),A=new Set(n.filter(K=>!r&&!S.has(K.episode)&&K.episode<=y.lastEpisode&&d.has(`ep/ep_${Ai(K.episode)}.json`)).map(K=>K.episode));m.recordReusedEpisodes("ingest.video-serial",[...A]);let b=A.size,U=0;for(let K of n){let Ot=`ep/ep_${Ai(K.episode)}.json`;if(!r&&S.has(K.episode)&&K.episode<=y.lastEpisode||A.has(K.episode))continue;if(s&&U>=1)break;let P=$a(y);d.writeText(`ep/ep_${Ai(K.episode)}.context.md`,P);let ce,Se,vt,Cn,Mi=Date.now(),Rt={episode:K.episode,uploadMode:c,status:"succeeded",totalMs:0},Os="transcode";try{let gn=Date.now(),ht=await cy(K.path,d.path(`cache/ep_${Ai(K.episode)}.mp4`),K.mime,a);Rt.transcodeMs=Date.now()-gn,Rt.uploadBytes=Sy(ht.path),Rt.transcoded=ht.transcoded,ht.note&&(Rt.note=ht.note),c==="base64"&&JA(ht.path,K.episode),Os="upload",g??=e.executor.videoPort("ingest.video-serial");let wc=Date.now(),co=await g.prepare(ht.path,ht.mime,c,a);Rt.uploadMs=Date.now()-wc;try{Os="generate";let _c=Date.now(),Rw=nc(d,n,y.lastEpisode,_.episodes),Ec=P;for(let vs=1;vs<=El;vs++){let Rs;try{Rs=await wy(g,co,K.episode,Ec,i,{format:e.outputFormat??"dsl",...a?{signal:a}:{},local:{path:ht.path,mime:ht.mime},onTimestampMissing:Yt=>kt.appendFileSync(d.path("ingest-validation.jsonl"),JSON.stringify(Yt)+`
335
+ `)})}catch(Yt){if(!(Yt instanceof x)||Yt.errorCode!=="INGEST_VIDEO_SERIAL_FAILED"||vs===El)throw Yt;Ec=`${P}
334
336
 
335
- \u4E0A\u4E00\u6B21\u8F93\u51FA\u672A\u88AB\u63A5\u53D7\uFF0C\u4E5F\u672A\u63A8\u8FDB checkpoint\uFF1A${Yt.message}\u3002\u8BF7\u91CD\u65B0\u89C2\u770B\u5F53\u524D\u96C6\uFF0C\u53EA\u6309\u89C6\u9891\u4E8B\u5B9E\u8FD4\u56DE\u7B26\u5408\u672C\u4EFB\u52A1\u8F93\u51FA\u683C\u5F0F\u7684\u5B8C\u6574\u7ED3\u679C\uFF0Cscenes \u81F3\u5C11\u5305\u542B\u4E00\u4E2A\u5B9E\u9645\u573A\u666F\uFF1B\u4E0D\u8981\u53EA\u5199\u6897\u6982\u6216\u8BBE\u5B9A\u589E\u91CF\u3002`;continue}let Xl=Wh(vs.output,j.episode),_c=structuredClone(y);ds(_c,vs.output,j.episode);let Rs=xy([...bw,Xl],_c,w,E,_.episodes.filter(Yt=>Yt.episode<=j.episode));if(Rs.validation.ok){de=vs.transcript,Se=Xl,vt=_c,Cn=Rs;break}if(bs="validation",Os===wl)throw new S("Final script.json failed validation after model correction.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Rerun ingest to continue with the next configured model route.",data:{actual:Rs.validation.errors.slice(0,8).map(Yt=>`${Yt.path}: ${Yt.message}`)}});wc=zA(P,Rs.validation.errors)}Rt.generateMs=Date.now()-yc}finally{await m.release(ao,a).catch(()=>{}),ht.transcoded&&kt.rmSync(ht.path,{force:!0})}}catch(gn){let ht=Date.now();Rt.status="failed",Rt.totalMs=ht-Ri,wy(d,Rt),g.flush({scope:{kind:"episode",episode:j.episode},status:"failed",startedAtMs:Ri,endedAtMs:ht,stages:Rt});let hc=gn instanceof S&&gn.errorCode==="INGEST_VIDEO_SERIAL_FAILED"?"parse":bs,ao=ja(gn,j.episode,hc),yc=hn(ao.failure);throw d.writeJson(`ep/ep_${Ii(j.episode)}.error.json`,ao),d.writeJson("manifest.json",{...u,updated:ao.occurred_at,current_error:ao}),gn instanceof S&&(gn.errorCode==="INGEST_VIDEO_INLINE_TOO_LARGE"||gn.errorCode==="INGEST_VALIDATION_FAILED"||gn.errorCode==="INGEST_VIDEO_TIMESTAMP_MISSING")?gn:new S(`Episode ${j.episode} failed serial parse; later episodes depend on its context.`,{exitCode:k,errorCode:"INGEST_SERIAL_INCOMPLETE",hint:Mh(ao.failure),data:{actual:[yc]}})}y=vt,C+=1,d.writeText(`ep/ep_${Ii(j.episode)}.${(e.outputFormat??"dsl")==="dsl"?"ep":"md"}`,de),d.writeJson(Ot,Se),d.writeJson("context.json",y),d.clearError(`ep/ep_${Ii(j.episode)}.error.json`);let Wl=Date.now();Rt.totalMs=Wl-Ri,wy(d,Rt),g.flush({scope:{kind:"episode",episode:j.episode},status:"succeeded",startedAtMs:Ri,endedAtMs:Wl,stages:Rt}),E=Cn.identityMap,d.writeJson("v4_identity_map.json",E),d.writeJson("script.json",Cn.final)}let R=Math.min(y.lastEpisode,n.length),I=n.length-R,O=I===0,N=O?null:n[R]?.episode??null,U=tc(d,n.slice(0,R),y,w,E,_.episodes),{final:M,validation:V}=U,F=O?await HA(d,ec(d,n,y.lastEpisode,_.episodes),M,y,f,u.source.sha256,a):{items:[]},Re=F.items.flatMap(j=>j.samples),X=M;return h="succeeded",{workspacePath:d.root,episodes:n.length,processed:C,reused:b,skipped:_.episodes.length,skippedEpisodes:_.episodes.map(j=>j.episode),completed:R,remaining:I,complete:O,nextEpisode:N,uploadMode:c,assets:{actors:X.actors?.length??0,locations:X.locations?.length??0,props:X.props?.length??0},evidence:{states:F.items.length,samples:Re.length,ready:Re.filter(j=>j.frame_status==="ready").length},scriptPath:d.path("script.json"),validation:{ok:V.ok,errors:V.errors.length,warnings:V.warnings.length}}}finally{g.finish(h)}}async function Sy(e){return Do(e.workspacePath,()=>FA(e))}function nc(e){let t=Qt.resolve(e),n=kt.existsSync(t)&&kt.statSync(t).isDirectory(),i=(n?"":Qt.basename(t,Qt.extname(t))).replace(/(?:[-_\s]*第\s*\d+\s*[集话]|[-_\s]+(?:ep\s*)?\d+)$/i,"").trim();if(i&&!/^(?:\d+|ep\s*\d+|videos?|source|源视频)$/i.test(i))return i;for(n||(t=Qt.dirname(t));t!==Qt.dirname(t);){let r=Qt.basename(t).trim();if(r&&!/^(?:videos?|source|源视频)$/i.test(r))return r;t=Qt.dirname(t)}return"\u672A\u547D\u540D\u5267\u672C"}var gr=e=>e==null?"":String(e),Iy=(e,t)=>{let n=Number(e);return Number.isInteger(n)&&n>0?n:t},QA=["fps","video_provider","upload_mode","provider_base_url","provider_api_key","provider_api_key_env","provider_model","video_output","step"];function io(e,t){return new S(e,{exitCode:k,errorCode:"INGEST_VIDEO_OPTION_INVALID",hint:"Use these options only with a video file or video episode directory.",data:{actual:t}})}function oc(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0}function Ai(e,t,n){if(!oc(e,t))return;let o=gr(e[t]).trim();if(!o)throw io(`${n} requires a non-empty value.`,[n]);return o}function YA(e){let t=Ai(e,"upload_mode","--upload-mode");if(t!==void 0){if(t!=="file-api"&&t!=="base64")throw io("Video upload mode must be file-api or base64.",[`--upload-mode ${t}`]);return t}}function qA(e){let t=Ai(e,"video_output","--video-output");if(t!==void 0&&t!=="dsl"&&t!=="json")throw io("Video output format must be dsl or json.",[`--video-output ${t}`]);return t}function ZA(e){let t=Ai(e,"video_provider","--video-provider");if(t!==void 0&&t!=="gemini"&&t!=="doubao")throw io("Video provider must be gemini or doubao.",["--video-provider gemini|doubao"]);let n=oc(e,"provider_api_key"),o=oc(e,"provider_api_key_env");if(n&&o)throw io("Provider API key options are mutually exclusive.",["--provider-api-key","--provider-api-key-env"]);let i=Ai(e,"provider_base_url","--provider-base-url"),r=Ai(e,"provider_api_key","--provider-api-key"),s=Ai(e,"provider_api_key_env","--provider-api-key-env"),c=Ai(e,"provider_model","--provider-model");if(s!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw io("Provider API key environment variable name is invalid.",[s]);let a;if(r!==void 0?a={kind:"literal",value:r}:s!==void 0&&(a={kind:"env",name:s}),!(!t&&!i&&!a&&!c))return{...t?{provider:t}:{},...i?{baseUrl:i}:{},...a?{apiKey:a}:{},...c?{model:c}:{}}}async function ky(e,t=Wn){let n=gr(e.source_path).trim();if(!n)throw new S("ingest needs a source file or directory.",{exitCode:k,errorCode:"INGEST_NO_SOURCE",hint:"Pass a txt/md/docx file, a video source or a PDF comic source: scriptctl ingest --source-path <path>.",data:{expected:["--source-path <file|dir>"]}});let o=Ay.resolve(gr(e.workspace_path||"workspace")),i=On(n),r=QA.filter(d=>{let p=e[d];return typeof p=="boolean"?p:oc(e,d)});if(i.kind==="text"&&r.length>0)throw io("Video ingest options cannot be used with a text source.",r.map(d=>`--${d.replace(/_/g,"-")}`));if(i.kind==="comic-file"||i.kind==="comic-directory"){let d=r.filter(f=>f!=="step");if(d.length)throw io("Video provider options cannot be used with PDF comics; select the comic model with --llm-config.",d);let p=t.createExecutor(gr(e.llm_config).trim()||void 0),l=await Uh({sourcePath:n,workspacePath:o,executor:p,force:!!e.force,step:!!e.step});return[{text:`workspace: ${l.workspace}
337
+ \u4E0A\u4E00\u6B21\u8F93\u51FA\u672A\u88AB\u63A5\u53D7\uFF0C\u4E5F\u672A\u63A8\u8FDB checkpoint\uFF1A${Yt.message}\u3002\u8BF7\u91CD\u65B0\u89C2\u770B\u5F53\u524D\u96C6\uFF0C\u53EA\u6309\u89C6\u9891\u4E8B\u5B9E\u8FD4\u56DE\u7B26\u5408\u672C\u4EFB\u52A1\u8F93\u51FA\u683C\u5F0F\u7684\u5B8C\u6574\u7ED3\u679C\uFF0Cscenes \u81F3\u5C11\u5305\u542B\u4E00\u4E2A\u5B9E\u9645\u573A\u666F\uFF1B\u4E0D\u8981\u53EA\u5199\u6897\u6982\u6216\u8BBE\u5B9A\u589E\u91CF\u3002`;continue}let tu=ty(Rs.output,K.episode),xc=structuredClone(y);ps(xc,Rs.output,K.episode);let Ms=Ay([...Rw,tu],xc,w,E,_.episodes.filter(Yt=>Yt.episode<=K.episode));if(Ms.validation.ok){ce=Rs.transcript,Se=tu,vt=xc,Cn=Ms;break}if(Os="validation",vs===El)throw new x("Final script.json failed validation after model correction.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Rerun ingest to continue with the next configured model route.",data:{actual:Ms.validation.errors.slice(0,8).map(Yt=>`${Yt.path}: ${Yt.message}`)}});Ec=HA(P,Ms.validation.errors)}Rt.generateMs=Date.now()-_c}finally{await g.release(co,a).catch(()=>{}),ht.transcoded&&kt.rmSync(ht.path,{force:!0})}}catch(gn){let ht=Date.now();Rt.status="failed",Rt.totalMs=ht-Mi,xy(d,Rt),m.flush({scope:{kind:"episode",episode:K.episode},status:"failed",startedAtMs:Mi,endedAtMs:ht,stages:Rt});let wc=gn instanceof x&&gn.errorCode==="INGEST_VIDEO_SERIAL_FAILED"?"parse":Os,co=za(gn,K.episode,wc),_c=hn(co.failure);throw d.writeJson(`ep/ep_${Ai(K.episode)}.error.json`,co),d.writeJson("manifest.json",{...u,updated:co.occurred_at,current_error:co}),gn instanceof x&&(gn.errorCode==="INGEST_VIDEO_INLINE_TOO_LARGE"||gn.errorCode==="INGEST_VALIDATION_FAILED"||gn.errorCode==="INGEST_VIDEO_TIMESTAMP_MISSING")?gn:new x(`Episode ${K.episode} failed serial parse; later episodes depend on its context.`,{exitCode:k,errorCode:"INGEST_SERIAL_INCOMPLETE",hint:Uh(co.failure),data:{actual:[_c]}})}y=vt,U+=1,d.writeText(`ep/ep_${Ai(K.episode)}.${(e.outputFormat??"dsl")==="dsl"?"ep":"md"}`,ce),d.writeJson(Ot,Se),d.writeJson("context.json",y),d.clearError(`ep/ep_${Ai(K.episode)}.error.json`);let eu=Date.now();Rt.totalMs=eu-Mi,xy(d,Rt),m.flush({scope:{kind:"episode",episode:K.episode},status:"succeeded",startedAtMs:Mi,endedAtMs:eu,stages:Rt}),E=Cn.identityMap,d.writeJson("v4_identity_map.json",E),d.writeJson("script.json",Cn.final)}let M=Math.min(y.lastEpisode,n.length),I=n.length-M,v=I===0,L=v?null:n[M]?.episode??null,C=oc(d,n.slice(0,M),y,w,E,_.episodes),{final:R,validation:J}=C,W=v?await FA(d,nc(d,n,y.lastEpisode,_.episodes),R,y,f,u.source.sha256,a):{items:[]},Re=W.items.flatMap(K=>K.samples),ie=R;return h="succeeded",{workspacePath:d.root,episodes:n.length,processed:U,reused:b,skipped:_.episodes.length,skippedEpisodes:_.episodes.map(K=>K.episode),completed:M,remaining:I,complete:v,nextEpisode:L,uploadMode:c,assets:{actors:ie.actors?.length??0,locations:ie.locations?.length??0,props:ie.props?.length??0},evidence:{states:W.items.length,samples:Re.length,ready:Re.filter(K=>K.frame_status==="ready").length},scriptPath:d.path("script.json"),validation:{ok:J.ok,errors:J.errors.length,warnings:J.warnings.length}}}finally{m.finish(h)}}async function ky(e){return Do(e.workspacePath,()=>QA(e))}function ic(e){let t=Qt.resolve(e),n=kt.existsSync(t)&&kt.statSync(t).isDirectory(),i=(n?"":Qt.basename(t,Qt.extname(t))).replace(/(?:[-_\s]*第\s*\d+\s*[集话]|[-_\s]+(?:ep\s*)?\d+)$/i,"").trim();if(i&&!/^(?:\d+|ep\s*\d+|videos?|source|源视频)$/i.test(i))return i;for(n||(t=Qt.dirname(t));t!==Qt.dirname(t);){let r=Qt.basename(t).trim();if(r&&!/^(?:videos?|source|源视频)$/i.test(r))return r;t=Qt.dirname(t)}return"\u672A\u547D\u540D\u5267\u672C"}var yr=e=>e==null?"":String(e),by=(e,t)=>{let n=Number(e);return Number.isInteger(n)&&n>0?n:t},YA=["fps","video_provider","upload_mode","provider_base_url","provider_api_key","provider_api_key_env","provider_model","video_output","step"];function ro(e,t){return new x(e,{exitCode:k,errorCode:"INGEST_VIDEO_OPTION_INVALID",hint:"Use these options only with a video file or video episode directory.",data:{actual:t}})}function rc(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0}function ki(e,t,n){if(!rc(e,t))return;let o=yr(e[t]).trim();if(!o)throw ro(`${n} requires a non-empty value.`,[n]);return o}function qA(e){let t=ki(e,"upload_mode","--upload-mode");if(t!==void 0){if(t!=="file-api"&&t!=="base64")throw ro("Video upload mode must be file-api or base64.",[`--upload-mode ${t}`]);return t}}function ZA(e){let t=ki(e,"video_output","--video-output");if(t!==void 0&&t!=="dsl"&&t!=="json")throw ro("Video output format must be dsl or json.",[`--video-output ${t}`]);return t}function WA(e){let t=ki(e,"video_provider","--video-provider");if(t!==void 0&&t!=="gemini"&&t!=="doubao")throw ro("Video provider must be gemini or doubao.",["--video-provider gemini|doubao"]);let n=rc(e,"provider_api_key"),o=rc(e,"provider_api_key_env");if(n&&o)throw ro("Provider API key options are mutually exclusive.",["--provider-api-key","--provider-api-key-env"]);let i=ki(e,"provider_base_url","--provider-base-url"),r=ki(e,"provider_api_key","--provider-api-key"),s=ki(e,"provider_api_key_env","--provider-api-key-env"),c=ki(e,"provider_model","--provider-model");if(s!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw ro("Provider API key environment variable name is invalid.",[s]);let a;if(r!==void 0?a={kind:"literal",value:r}:s!==void 0&&(a={kind:"env",name:s}),!(!t&&!i&&!a&&!c))return{...t?{provider:t}:{},...i?{baseUrl:i}:{},...a?{apiKey:a}:{},...c?{model:c}:{}}}async function vy(e,t=Xn){let n=yr(e.source_path).trim();if(!n)throw new x("ingest needs a source file or directory.",{exitCode:k,errorCode:"INGEST_NO_SOURCE",hint:"Pass a txt/md/docx file, a video source or a PDF comic source: scriptctl ingest --source-path <path>.",data:{expected:["--source-path <file|dir>"]}});let o=Oy.resolve(yr(e.workspace_path||"workspace")),i=On(n),r=YA.filter(d=>{let p=e[d];return typeof p=="boolean"?p:rc(e,d)});if(i.kind==="text"&&r.length>0)throw ro("Video ingest options cannot be used with a text source.",r.map(d=>`--${d.replace(/_/g,"-")}`));if(i.kind==="comic-file"||i.kind==="comic-directory"){let d=r.filter(f=>f!=="step");if(d.length)throw ro("Video provider options cannot be used with PDF comics; select the comic model with --llm-config.",d);let p=t.createExecutor(yr(e.llm_config).trim()||void 0),l=await Th({sourcePath:n,workspacePath:o,executor:p,force:!!e.force,step:!!e.step});return[{text:`workspace: ${l.workspace}
336
338
  ${l.completed}/${l.episodes} chapters complete (${l.processed} processed / ${l.reused} reused) \u2192 ${l.script_path}
337
- assets: ${l.assets.actors} actors / ${l.assets.locations} locations / ${l.assets.props} props`,data:l},B]}if(i.kind!=="text"){let d=YA(e),p=qA(e),l=ZA(e),f=l?{videoProvider:l}:void 0,u=t.createExecutor(gr(e.llm_config).trim()||void 0,f),g=u.route("ingest.video-serial"),h=d??g.videoUploadMode??"file-api";if(l?.provider==="doubao"&&h!=="file-api")throw io("Doubao requires --upload-mode file-api.",["--upload-mode file-api"]);let m=await Sy({sourcePath:n,workspacePath:o,executor:u,fps:Iy(e.fps,3),force:!!e.force,step:!!e.step,uploadMode:h,...p?{outputFormat:p}:{}}),w=[`workspace: ${m.workspacePath}`,`${m.completed}/${m.episodes} episodes complete (${m.processed} processed / ${m.reused} reused / ${m.remaining} remaining) \u2192 ${m.scriptPath}`,...m.skipped>0?[`skipped: ${m.skippedEpisodes.join(", ")}`]:[],`assets: ${m.assets.actors} actors / ${m.assets.locations} locations / ${m.assets.props} props`],y=[...u.usageEvents()].reverse().find(_=>_.task==="ingest.video-serial"&&_.status==="succeeded")??g;return[{text:w.join(`
338
- `),data:{workspace:m.workspacePath,script_path:m.scriptPath,episodes:m.episodes,processed:m.processed,reused:m.reused,parsed:m.completed-m.skipped,skipped:m.skipped,skipped_episodes:m.skippedEpisodes,has_skips:m.skipped>0,completed:m.completed,remaining:m.remaining,complete:m.complete,next_episode:m.nextEpisode,upload_mode:m.uploadMode,route:{protocol:y.protocol,provider:y.provider,base_url:y.baseUrl,model:y.model},assets:m.assets}},B]}let s=t.createExecutor(gr(e.llm_config).trim()||void 0),c=await lh({sourcePath:n,workspacePath:o,executor:s,concurrency:Iy(e.concurrency,30),force:!!e.force});return[{text:[`workspace: ${c.workspacePath}`,`${c.records} records, ${c.chunks} chunks \u2192 ${c.scriptPath}`,`assets: ${c.assets.actors} actors / ${c.assets.locations} locations / ${c.assets.props} props`].join(`
339
- `),data:{workspace:c.workspacePath,script_path:c.scriptPath,records:c.records,chunks:c.chunks,assets:c.assets}},B]}import*as $t from"node:fs";import*as Dt from"node:path";var WA=e=>e==null?"":String(e);function by(e){try{let t=JSON.parse($t.readFileSync(Dt.join(e,"timings.json"),"utf-8"));return sh(t,Date.now())}catch{return null}}function ic(e,t,n){let o=Dt.join(e,t),i;try{i=$t.readdirSync(o)}catch{return[]}return i.filter(r=>r.endsWith(n)).sort()}var XA=(e,t,n)=>ic(e,t,n).length,Al=(e,t)=>$t.existsSync(Dt.join(e,t));function ek(e){try{return JSON.parse($t.readFileSync(Dt.join(e,"manifest.json"),"utf-8"))}catch{return null}}function tk(e){try{let t=JSON.parse($t.readFileSync(Dt.join(e,"validation.json"),"utf-8"));return{ok:!!t.ok,errors:t.errors?.length??0,warnings:t.warnings?.length??0}}catch{return null}}function xl(e,t,n){return{pass:e,unit:t,phase:e,attempts:[],...Ut({failure_type:"unknown",failure_code:"legacy_unclassified"},{retryable:e==="pass2",message:n})}}function nk(e,t,n){try{let o=JSON.parse($t.readFileSync(Dt.join(e,t,`${n}.error.json`),"utf-8")),i=ls(o);return i?{pass:t,unit:n,phase:i.phase,attempts:i.attempts,...i.failure}:typeof o=="object"&&o!==null&&"error"in o&&typeof o.error=="string"?xl(t,n,o.error):xl(t,n,"Error sidecar has an unsupported schema.")}catch{return xl(t,n,"Error sidecar is unreadable.")}}function ok(e,t,n=new Set){return ic(e,t,".error.json").map(o=>o.replace(/\.error\.json$/,"")).filter(o=>!n.has(o)).map(o=>nk(e,t,o))}function ik(e,t,n){let o=ls(e.current_error);if(!o)return[];let i=`ep_${String(o.unit.episode).padStart(3,"0")}`;return o.unit.episode<=t||n.has(i)?[]:[{pass:"ep",unit:i,phase:o.phase,attempts:o.attempts,...o.failure}]}function Sl(e){let t={};for(let o of e)t[o.failure_type]=(t[o.failure_type]??0)+1;let n=e.filter(o=>o.retryable).length;return{total:e.length,retryable:n,terminal:e.length-n,by_type:t}}function rk(e){try{let t=JSON.parse($t.readFileSync(Dt.join(e,"body.json"),"utf-8"));return Array.isArray(t.episodes)?t.episodes.length:0}catch{return 0}}function sk(e){try{let t=JSON.parse($t.readFileSync(Dt.join(e,"script.json"),"utf-8"));return t.version===4&&Array.isArray(t.episodes)?t.episodes.length:null}catch{return null}}function ak(e,t,n){try{let o;return n==="comic"?o=JSON.parse($t.readFileSync(Dt.join(e,"checkpoint.json"),"utf-8")).context:o=JSON.parse($t.readFileSync(Dt.join(e,"context.json"),"utf-8")),typeof o.lastEpisode=="number"&&Number.isInteger(o.lastEpisode)?Math.min(Math.max(o.lastEpisode,0),t):0}catch{return 0}}function ck(e,t){let n=t.chunks??0,o={total:n,done:ic(e,"pass2",".json").filter(a=>/^chunk_\d+\.json$/.test(a)).length,failed:XA(e,"pass2",".error.json")},i=rk(e),r=ic(e,"serial",".json").reduce((a,d)=>{let p=d.match(/^win_(\d+)_(\d+)\.json$/);return p?a+(Number(p[2])-Number(p[1])+1):a},0),s={total:i,done:r,failed:0};return{passes:[{name:"normalize",done:n>0&&o.done>=n&&o.failed===0,unit:o},{name:"assemble",done:Al(e,"body.json")},{name:"serial",done:i>0&&r>=i,unit:s},{name:"govern",done:Al(e,"script.json")}],units:o}}function dk(e,t,n,o,i){let r=t.episodes?.length??0,s=o-n.filter(d=>d.episode<=o).length,c={total:r,done:o,failed:i};return{passes:[{name:"serial",done:r>0&&c.done>=r&&c.failed===0,unit:c},{name:"finalize",done:o>=r&&sk(e)===o}],units:c,parsed:s}}function gs(e){let t=Dt.resolve(e),n=ek(t);if(!n)return{workspace:t,exists:!1,kind:null,state:"empty",phase:"none",passes:[],units:null,script:!1,validation:null,failure_summary:Sl([]),errors:[],updated:null,timings:null};let o=n.source?.kind==="text"?"text":n.source?.kind?.startsWith("comic-")?"comic":"video",i=n.episodes?.length??0,r=o!=="text"?ak(t,i,o):0,s=o!=="text"&&r<i,c=o==="video"?n.skips??[]:[],a=new Set(c.map(E=>`ep_${String(E.episode).padStart(3,"0")}`)),d=o!=="text"&&r<i?ik(n,r,a):[],p=o!=="text"?dk(t,n,c,r,d.length):null,{passes:l,units:f}=o==="text"?ck(t,n):p,u=o==="text"?ok(t,"pass2"):d;if(s){let E=c.filter(A=>A.episode<=r);return{workspace:t,exists:!0,kind:o,state:u.length>0?"failed":"incomplete",phase:"serial",passes:l,units:f,script:r>0,validation:null,failure_summary:Sl(u),errors:u,updated:n.updated??null,timings:by(t),completed:r,remaining:i-r,complete:!1,next_episode:r+1,parsed:p?.parsed??r,skipped:E.length,skipped_episodes:c.map(A=>A.episode),has_skips:c.length>0,skips:c.map(A=>({episode:A.episode,skipped_at:A.skipped_at,reason:A.reason,failure_type:A.failure.failure_type,failure_code:A.failure.failure_code}))}}let g=Al(t,"script.json"),h=tk(t);h&&!h.ok&&u.push({pass:"finalize",unit:"script",phase:"validation",attempts:[],...Ut({failure_type:"validation",failure_code:"script_validation_failed"},{retryable:!1,message:`Script validation failed with ${h.errors} error(s).`})});let m,w=l.length>0&&l.every(E=>E.done);(o==="text"||w)&&g&&h?.ok?m="ready":u.length>0||h&&!h.ok?m="failed":m="incomplete";let y=l.find(E=>!E.done),_=m==="ready"?"done":y?y.name:"done",x=o!=="text"?{completed:f.done,remaining:Math.max(0,f.total-f.done),complete:f.total>0&&f.done>=f.total&&f.failed===0,next_episode:f.done>=f.total?null:f.done+1,parsed:p?.parsed??0,skipped:c.filter(E=>E.episode<=f.done).length,skipped_episodes:c.map(E=>E.episode),has_skips:c.length>0,skips:c.map(E=>({episode:E.episode,skipped_at:E.skipped_at,reason:E.reason,failure_type:E.failure.failure_type,failure_code:E.failure.failure_code}))}:{};return{workspace:t,exists:!0,kind:o,state:m,phase:_,passes:l,units:f,script:g,validation:h,failure_summary:Sl(u),errors:u,updated:n.updated??null,timings:by(t),...x}}function pk(e){let t=`${e.done}/${e.total}`;return e.failed>0?`${t} (${e.failed} failed)`:t}function lk(e){if(!e.exists)return[`no ingest workspace at ${e.workspace}`];let t=`${e.kind} ingest: ${e.state} (phase=${e.phase})`,n=e.passes.map(i=>`${i.name} ${i.unit?pk(i.unit):i.done?"\u2713":"-"}`).join(" "),o=[t,n];if(e.timings&&o.push(uk(e.timings)),e.validation&&o.push(`validation: ${e.validation.ok?"ok":`${e.validation.errors} errors`}, ${e.validation.warnings} warnings`),e.has_skips&&o.push(`skipped episodes: ${e.skipped_episodes?.join(", ")}`),e.state==="failed"){for(let i of e.errors.slice(0,3))o.push(`${i.unit}: ${i.failure_type}/${i.failure_code} \xB7 ${i.retryable?"retryable":"terminal"}`);e.failure_summary.retryable>0&&o.push("rerun `scriptctl ingest` to resume retryable failures"),(e.failure_summary.by_type.policy??0)>0&&o.push("provider policy blocked the source; rerunning the same source is unlikely to help"),((e.failure_summary.by_type.authentication??0)>0||(e.failure_summary.by_type.authorization??0)>0)&&o.push("check provider credentials and permissions before rerunning")}return o}function Il(e){let t=Math.round(e/1e3);return t>=60?`${Math.floor(t/60)}m${String(t%60).padStart(2,"0")}s`:`${t}s`}function uk(e){let t=[`elapsed ${Il(e.elapsedMs)}${e.done?"":" (running)"}`],n=e.serial;return n&&(t.push(`serial ${n.doneWindows}/${n.totalWindows} windows (${n.doneEpisodes}/${n.totalEpisodes} eps)`),n.avgWindowMs!=null&&t.push(`~${Il(n.avgWindowMs)}/window`),n.etaMs!=null&&!e.done&&t.push(`eta ~${Il(n.etaMs)}`)),t.join(" \xB7 ")}function Oy(e){let t=WA(e.workspace_path||"workspace"),n=gs(t);return[{text:lk(n).join(`
340
- `),data:{status:n}},B]}import*as rc from"node:path";function Ln(e,t,n,o){return new S(e,{exitCode:k,errorCode:t,hint:n,data:{actual:o}})}function fk(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw Ln("--episode must be a positive integer.","INGEST_SKIP_EPISODE_INVALID","Pass the current next_episode from `scriptctl ingest status`.",[String(e)]);return t}async function mk(e,t,n){let o=new ft(e);if(!o.has("manifest.json"))throw Ln("The ingest workspace does not exist.","INGEST_SKIP_WORKSPACE_MISSING","Run video ingest first, then retry the failed episode or skip it.",[e]);let i=o.readJson("manifest.json");if(i.source?.kind!=="video-file"&&i.source?.kind!=="video-directory")throw Ln("Only video ingest episodes can be skipped.","INGEST_SKIP_WRONG_PIPELINE","Use skip only with a video ingest workspace.",[e]);let r=_l(o);if(!r)throw Ln("The video ingest manifest is missing.","INGEST_SKIP_WORKSPACE_MISSING","Run video ingest first.",[e]);let s=r.episodes.find(w=>w.episode===t);if(!s)throw Ln("The requested episode is not in the video source.","INGEST_SKIP_EPISODE_NOT_FOUND","Pass an episode listed in manifest.json.",[`episode=${t}`]);let c=yl(o);Xa(c.episodes,r.episodes);let a=o.has("context.json")?o.readJson("context.json"):Vo();if(c.episodes.find(w=>w.episode===t)){let w=El(o,r);a=fs(o,a,c.episodes);let y=o.has("v4_identity_map.json")?o.readJson("v4_identity_map.json"):Co();return tc(o,w.episodes,a,nc(w.source.path),y,c.episodes),!1}let p=a.lastEpisode+1;if(t!==p)throw Ln("Only the next unresolved video episode can be skipped.","INGEST_SKIP_NOT_NEXT","Read status.next_episode and skip exactly that episode.",[`requested=${t}`,`next_episode=${p}`]);let l=`ep/ep_${String(t).padStart(3,"0")}`;if(o.has(`${l}.json`))throw Ln("A parsed episode cannot be skipped.","INGEST_SKIP_ALREADY_PARSED","Continue ingest from the next unresolved episode.",[`episode=${t}`]);if(!o.has(`${l}.error.json`))throw Ln("The episode has no recorded ingest failure.","INGEST_SKIP_FAILURE_REQUIRED","Run ingest for this episode first; a typed error sidecar is required before manual skip.",[`episode=${t}`]);let f=ls(o.readJson(`${l}.error.json`));if(!f||f.unit.episode!==t)throw Ln("The episode error sidecar is invalid.","INGEST_SKIP_FAILURE_INVALID","Regenerate the typed failure by rerunning video ingest.",[`${l}.error.json`]);let u={episode:t,skipped_at:new Date().toISOString(),reason:n,source_sha256:s.sha256,failure:f.failure,attempts:f.attempts},g=El(o,r),h=[...c.episodes,u];o.writeJson("manifest.json",{...g,updated:u.skipped_at,current_error:void 0,skips:h}),hy(o,{schema_version:1,episodes:h}),a=fs(o,a,h);let m=o.has("v4_identity_map.json")?o.readJson("v4_identity_map.json"):Co();return tc(o,g.episodes,a,nc(g.source.path),m,[...c.episodes,u]),!0}async function vy(e){let t=rc.resolve(typeof e.workspace_path=="string"?e.workspace_path:"workspace"),n=fk(e.episode),o=typeof e.reason=="string"?e.reason.trim():"";if(!o)throw Ln("--reason is required.","INGEST_SKIP_REASON_REQUIRED","Record why this episode cannot be parsed.",["--reason <text>"]);let i=await Do(t,()=>mk(t,n,o)),r=gs(t),s=yl(new ft(t)).episodes.map(c=>c.episode);return[{text:i?`Episode ${n} skipped; ingest can continue at episode ${r.next_episode??"end"}.`:`Episode ${n} was already skipped; no changes made.`,data:{workspace:t,episode:n,changed:i,skipped_episodes:s,complete:r.complete??!1,next_episode:r.next_episode??null,script_path:rc.join(t,"script.json")}},B]}import*as ac from"node:fs";import*as ki from"node:path";import{spawnSync as gk}from"node:child_process";function sc(e,t,n,o){return new S(e,{exitCode:k,errorCode:t,hint:n,data:{actual:o}})}function hk(e){let t=Ya(On(e)),n=Ha(t);if(n)throw sc("Video episode files are not a continuous 1..N sequence.","EVIDENCE_VIDEO_SEQUENCE_INVALID","Rename the linked videos so every script episode has one matching numbered file.",[n]);return t.map(o=>{let i=ki.resolve(o.path),r=ac.statSync(i),s=r.size,c=Math.trunc(r.mtimeMs),a=gk("ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",i],{encoding:"utf-8"}),d=Number(a.stdout.trim()),p=a.status===0&&Number.isFinite(d)&&d>0?Math.round(d*1e3):void 0;return{episode:o.episode,path:i,ext:o.ext,mime:o.mime,sha256:Ee(JSON.stringify({absolutePath:i,sizeBytes:s,mtimeMs:c})),size_bytes:s,mtime_ms:c,duration_ms:p}})}async function yk(e){let t=ki.resolve(e.scriptPath),n=ki.resolve(e.sourcePath),o=ki.resolve(e.workspacePath),i=Vi(JSON.parse(ac.readFileSync(t,"utf-8"))),r=hk(n);if(r.length!==i.episodes.length)throw sc("The linked video count does not match the script episode count.","EVIDENCE_VIDEO_EPISODE_COUNT_MISMATCH","Bind the complete source-video folder for this script, then retry.",[`script=${i.episodes.length}`,`videos=${r.length}`]);let s=qa(r),c=Fa([],i,Vo(),r,s),a=await Do(o,async()=>{let p=new ft(o);return p.ensure(),Za(p,c,e.signal,e.extractor,{reuseExistingFrames:e.force!==!0})}),d=[...a.items.flatMap(p=>p.samples),...(a.identities??[]).flatMap(p=>p.samples)];return{output:ki.join(o,"evidence","state-evidence.json"),states:a.items.length,identities:a.identities?.length??0,samples:d.length,ready:d.filter(p=>p.frame_status==="ready").length,unavailable:d.filter(p=>p.frame_status==="unavailable").length,sourceSha256:s}}async function Ry(e){let t=ge(e),n=typeof e.source_path=="string"?e.source_path.trim():"",o=typeof e.workspace_path=="string"?e.workspace_path.trim():"";if(!n)throw sc("--source-path is required.","EVIDENCE_SOURCE_REQUIRED","Pass the linked source-video file or folder.",["--source-path <path>"]);if(!o)throw sc("--workspace-path is required.","EVIDENCE_WORKSPACE_REQUIRED","Pass the project workspace directory.",["--workspace-path <path>"]);let i=await yk({scriptPath:t,sourcePath:n,workspacePath:o,force:e.force===!0});return[{text:`Generated ${i.ready}/${i.samples} original-video reference frames for ${i.states} actor states.`,data:{output:i.output,states:i.states,identities:i.identities,samples:i.samples,ready:i.ready,unavailable:i.unavailable,source_sha256:i.sourceSha256}},B]}import*as Jo from"node:fs";import*as cc from"node:path";var bt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ro=e=>Array.isArray(e),ze=e=>typeof e=="string"?e:"",wk={interior:"\u5185",exterior:"\u5916"},_k={day:"\u65E5",night:"\u591C"},Ek=e=>{let t=e.match(/(\d+)/);return t?Number(t[1]):0},xk=e=>{let t=e.match(/(\d+)/);return t?Number(t[1]):0};function kl(e,t,n){let o=new Map;if(ro(e))for(let i of e)bt(i)&&typeof i[t]=="string"&&o.set(i[t],ze(i[n]));return o}function Sk(e,t){let n=new Map;if(ro(e))for(let o of e){if(!bt(o)||typeof o[t]!="string")continue;let i=new Map;for(let r of ro(o.states)?o.states:[])bt(r)&&typeof r.state_id=="string"&&i.set(r.state_id,ze(r.state_name));n.set(o[t],i)}return n}function Ik(e,t){return bt(e)?typeof e.actor_id=="string"?t.get(e.actor_id)??e.actor_id:typeof e.kind=="string"?`${e.kind}${e.label?`:${ze(e.label)}`:""}`:"":""}function Ak(e){let t=kl(e.actors,"actor_id","actor_name"),n=kl(e.locations,"location_id","location_name"),o=kl(e.props,"prop_id","prop_name"),i=Sk(e.actors,"actor_id"),r=(ro(e.episodes)?e.episodes:[]).filter(bt).map(c=>({episode:Ek(ze(c.episode_id)),synopsis:ze(c.synopsis),scenes:(ro(c.scenes)?c.scenes:[]).filter(bt).map(a=>{let d=bt(a.location)?n.get(ze(a.location.location_id))??ze(a.location.location_id):"",p=[],l={};for(let g of ro(a.actors)?a.actors:[]){if(!bt(g)||typeof g.actor_id!="string")continue;let h=t.get(g.actor_id)??g.actor_id;if(p.includes(h)||p.push(h),typeof g.state_id=="string"){let w=(i.get(g.actor_id)?.get(g.state_id)??"")||(g.state_id!=="default"?g.state_id:"");w&&(l[h]=w)}}let f=[];for(let g of ro(a.props)?a.props:[])if(bt(g)&&typeof g.prop_id=="string"){let h=o.get(g.prop_id)??g.prop_id;f.includes(h)||f.push(h)}let u=bt(a.environment)?a.environment:{};return{scene_num:xk(ze(a.scene_id)),location_name:d,environment:{space:wk[ze(u.space)]??ze(u.space),time:_k[ze(u.time)]??ze(u.time)},actor_names:p,actor_states:l,prop_names:f,actions:(ro(a.actions)?a.actions:[]).filter(bt).map(g=>({type:ze(g.type),content:ze(g.content),speaker:Ik(g.speaker,t),emotion:typeof g.emotion=="string"?g.emotion:void 0,extend:bt(g.extend)&&typeof g.extend.timestamp=="string"?{timestamp:g.extend.timestamp}:void 0}))}})})),s=(ro(e.actors)?e.actors:[]).filter(bt).map(c=>({asset_name:ze(c.actor_name),description:ze(c.description),extend:{}}));return{title:ze(e.title),actors:s,episodes:r}}function My(e){if(!bt(e))throw new Error("review renderer expects a script object");let t=Ak(e),n=JSON.stringify(t),o=ze(t.title);return`<!DOCTYPE html>
339
+ assets: ${l.assets.actors} actors / ${l.assets.locations} locations / ${l.assets.props} props`,data:l},G]}if(i.kind!=="text"){let d=qA(e),p=ZA(e),l=WA(e),f=l?{videoProvider:l}:void 0,u=t.createExecutor(yr(e.llm_config).trim()||void 0,f),m=u.route("ingest.video-serial"),h=d??m.videoUploadMode??"file-api";if(l?.provider==="doubao"&&h!=="file-api")throw ro("Doubao requires --upload-mode file-api.",["--upload-mode file-api"]);let g=await ky({sourcePath:n,workspacePath:o,executor:u,fps:by(e.fps,3),force:!!e.force,step:!!e.step,uploadMode:h,...p?{outputFormat:p}:{}}),w=[`workspace: ${g.workspacePath}`,`${g.completed}/${g.episodes} episodes complete (${g.processed} processed / ${g.reused} reused / ${g.remaining} remaining) \u2192 ${g.scriptPath}`,...g.skipped>0?[`skipped: ${g.skippedEpisodes.join(", ")}`]:[],`assets: ${g.assets.actors} actors / ${g.assets.locations} locations / ${g.assets.props} props`],y=[...u.usageEvents()].reverse().find(_=>_.task==="ingest.video-serial"&&_.status==="succeeded")??m;return[{text:w.join(`
340
+ `),data:{workspace:g.workspacePath,script_path:g.scriptPath,episodes:g.episodes,processed:g.processed,reused:g.reused,parsed:g.completed-g.skipped,skipped:g.skipped,skipped_episodes:g.skippedEpisodes,has_skips:g.skipped>0,completed:g.completed,remaining:g.remaining,complete:g.complete,next_episode:g.nextEpisode,upload_mode:g.uploadMode,route:{protocol:y.protocol,provider:y.provider,base_url:y.baseUrl,model:y.model},assets:g.assets}},G]}let s=t.createExecutor(yr(e.llm_config).trim()||void 0),c=await mh({sourcePath:n,workspacePath:o,executor:s,concurrency:by(e.concurrency,30),force:!!e.force});return[{text:[`workspace: ${c.workspacePath}`,`${c.records} records, ${c.chunks} chunks \u2192 ${c.scriptPath}`,`assets: ${c.assets.actors} actors / ${c.assets.locations} locations / ${c.assets.props} props`].join(`
341
+ `),data:{workspace:c.workspacePath,script_path:c.scriptPath,records:c.records,chunks:c.chunks,assets:c.assets}},G]}import*as $t from"node:fs";import*as Dt from"node:path";var XA=e=>e==null?"":String(e);function Ry(e){try{let t=JSON.parse($t.readFileSync(Dt.join(e,"timings.json"),"utf-8"));return dh(t,Date.now())}catch{return null}}function sc(e,t,n){let o=Dt.join(e,t),i;try{i=$t.readdirSync(o)}catch{return[]}return i.filter(r=>r.endsWith(n)).sort()}var ek=(e,t,n)=>sc(e,t,n).length,bl=(e,t)=>$t.existsSync(Dt.join(e,t));function tk(e){try{return JSON.parse($t.readFileSync(Dt.join(e,"manifest.json"),"utf-8"))}catch{return null}}function nk(e){try{let t=JSON.parse($t.readFileSync(Dt.join(e,"validation.json"),"utf-8"));return{ok:!!t.ok,errors:t.errors?.length??0,warnings:t.warnings?.length??0}}catch{return null}}function Il(e,t,n){return{pass:e,unit:t,phase:e,attempts:[],...Ut({failure_type:"unknown",failure_code:"legacy_unclassified"},{retryable:e==="pass2",message:n})}}function ok(e,t,n){try{let o=JSON.parse($t.readFileSync(Dt.join(e,t,`${n}.error.json`),"utf-8")),i=us(o);return i?{pass:t,unit:n,phase:i.phase,attempts:i.attempts,...i.failure}:typeof o=="object"&&o!==null&&"error"in o&&typeof o.error=="string"?Il(t,n,o.error):Il(t,n,"Error sidecar has an unsupported schema.")}catch{return Il(t,n,"Error sidecar is unreadable.")}}function ik(e,t,n=new Set){return sc(e,t,".error.json").map(o=>o.replace(/\.error\.json$/,"")).filter(o=>!n.has(o)).map(o=>ok(e,t,o))}function rk(e,t,n){let o=us(e.current_error);if(!o)return[];let i=`ep_${String(o.unit.episode).padStart(3,"0")}`;return o.unit.episode<=t||n.has(i)?[]:[{pass:"ep",unit:i,phase:o.phase,attempts:o.attempts,...o.failure}]}function Al(e){let t={};for(let o of e)t[o.failure_type]=(t[o.failure_type]??0)+1;let n=e.filter(o=>o.retryable).length;return{total:e.length,retryable:n,terminal:e.length-n,by_type:t}}function sk(e){try{let t=JSON.parse($t.readFileSync(Dt.join(e,"body.json"),"utf-8"));return Array.isArray(t.episodes)?t.episodes.length:0}catch{return 0}}function ak(e){try{let t=JSON.parse($t.readFileSync(Dt.join(e,"script.json"),"utf-8"));return t.version===4&&Array.isArray(t.episodes)?t.episodes.length:null}catch{return null}}function ck(e,t,n){try{let o;return n==="comic"?o=JSON.parse($t.readFileSync(Dt.join(e,"checkpoint.json"),"utf-8")).context:o=JSON.parse($t.readFileSync(Dt.join(e,"context.json"),"utf-8")),typeof o.lastEpisode=="number"&&Number.isInteger(o.lastEpisode)?Math.min(Math.max(o.lastEpisode,0),t):0}catch{return 0}}function dk(e,t){let n=t.chunks??0,o={total:n,done:sc(e,"pass2",".json").filter(a=>/^chunk_\d+\.json$/.test(a)).length,failed:ek(e,"pass2",".error.json")},i=sk(e),r=sc(e,"serial",".json").reduce((a,d)=>{let p=d.match(/^win_(\d+)_(\d+)\.json$/);return p?a+(Number(p[2])-Number(p[1])+1):a},0),s={total:i,done:r,failed:0};return{passes:[{name:"normalize",done:n>0&&o.done>=n&&o.failed===0,unit:o},{name:"assemble",done:bl(e,"body.json")},{name:"serial",done:i>0&&r>=i,unit:s},{name:"govern",done:bl(e,"script.json")}],units:o}}function pk(e,t,n,o,i){let r=t.episodes?.length??0,s=o-n.filter(d=>d.episode<=o).length,c={total:r,done:o,failed:i};return{passes:[{name:"serial",done:r>0&&c.done>=r&&c.failed===0,unit:c},{name:"finalize",done:o>=r&&ak(e)===o}],units:c,parsed:s}}function hs(e){let t=Dt.resolve(e),n=tk(t);if(!n)return{workspace:t,exists:!1,kind:null,state:"empty",phase:"none",passes:[],units:null,script:!1,validation:null,failure_summary:Al([]),errors:[],updated:null,timings:null};let o=n.source?.kind==="text"?"text":n.source?.kind?.startsWith("comic-")?"comic":"video",i=n.episodes?.length??0,r=o!=="text"?ck(t,i,o):0,s=o!=="text"&&r<i,c=o==="video"?n.skips??[]:[],a=new Set(c.map(E=>`ep_${String(E.episode).padStart(3,"0")}`)),d=o!=="text"&&r<i?rk(n,r,a):[],p=o!=="text"?pk(t,n,c,r,d.length):null,{passes:l,units:f}=o==="text"?dk(t,n):p,u=o==="text"?ik(t,"pass2"):d;if(s){let E=c.filter(A=>A.episode<=r);return{workspace:t,exists:!0,kind:o,state:u.length>0?"failed":"incomplete",phase:"serial",passes:l,units:f,script:r>0,validation:null,failure_summary:Al(u),errors:u,updated:n.updated??null,timings:Ry(t),completed:r,remaining:i-r,complete:!1,next_episode:r+1,parsed:p?.parsed??r,skipped:E.length,skipped_episodes:c.map(A=>A.episode),has_skips:c.length>0,skips:c.map(A=>({episode:A.episode,skipped_at:A.skipped_at,reason:A.reason,failure_type:A.failure.failure_type,failure_code:A.failure.failure_code}))}}let m=bl(t,"script.json"),h=nk(t);h&&!h.ok&&u.push({pass:"finalize",unit:"script",phase:"validation",attempts:[],...Ut({failure_type:"validation",failure_code:"script_validation_failed"},{retryable:!1,message:`Script validation failed with ${h.errors} error(s).`})});let g,w=l.length>0&&l.every(E=>E.done);(o==="text"||w)&&m&&h?.ok?g="ready":u.length>0||h&&!h.ok?g="failed":g="incomplete";let y=l.find(E=>!E.done),_=g==="ready"?"done":y?y.name:"done",S=o!=="text"?{completed:f.done,remaining:Math.max(0,f.total-f.done),complete:f.total>0&&f.done>=f.total&&f.failed===0,next_episode:f.done>=f.total?null:f.done+1,parsed:p?.parsed??0,skipped:c.filter(E=>E.episode<=f.done).length,skipped_episodes:c.map(E=>E.episode),has_skips:c.length>0,skips:c.map(E=>({episode:E.episode,skipped_at:E.skipped_at,reason:E.reason,failure_type:E.failure.failure_type,failure_code:E.failure.failure_code}))}:{};return{workspace:t,exists:!0,kind:o,state:g,phase:_,passes:l,units:f,script:m,validation:h,failure_summary:Al(u),errors:u,updated:n.updated??null,timings:Ry(t),...S}}function lk(e){let t=`${e.done}/${e.total}`;return e.failed>0?`${t} (${e.failed} failed)`:t}function uk(e){if(!e.exists)return[`no ingest workspace at ${e.workspace}`];let t=`${e.kind} ingest: ${e.state} (phase=${e.phase})`,n=e.passes.map(i=>`${i.name} ${i.unit?lk(i.unit):i.done?"\u2713":"-"}`).join(" "),o=[t,n];if(e.timings&&o.push(fk(e.timings)),e.validation&&o.push(`validation: ${e.validation.ok?"ok":`${e.validation.errors} errors`}, ${e.validation.warnings} warnings`),e.has_skips&&o.push(`skipped episodes: ${e.skipped_episodes?.join(", ")}`),e.state==="failed"){for(let i of e.errors.slice(0,3))o.push(`${i.unit}: ${i.failure_type}/${i.failure_code} \xB7 ${i.retryable?"retryable":"terminal"}`);e.failure_summary.retryable>0&&o.push("rerun `scriptctl ingest` to resume retryable failures"),(e.failure_summary.by_type.policy??0)>0&&o.push("provider policy blocked the source; rerunning the same source is unlikely to help"),((e.failure_summary.by_type.authentication??0)>0||(e.failure_summary.by_type.authorization??0)>0)&&o.push("check provider credentials and permissions before rerunning")}return o}function kl(e){let t=Math.round(e/1e3);return t>=60?`${Math.floor(t/60)}m${String(t%60).padStart(2,"0")}s`:`${t}s`}function fk(e){let t=[`elapsed ${kl(e.elapsedMs)}${e.done?"":" (running)"}`],n=e.serial;return n&&(t.push(`serial ${n.doneWindows}/${n.totalWindows} windows (${n.doneEpisodes}/${n.totalEpisodes} eps)`),n.avgWindowMs!=null&&t.push(`~${kl(n.avgWindowMs)}/window`),n.etaMs!=null&&!e.done&&t.push(`eta ~${kl(n.etaMs)}`)),t.join(" \xB7 ")}function My(e){let t=XA(e.workspace_path||"workspace"),n=hs(t);return[{text:uk(n).join(`
342
+ `),data:{status:n}},G]}import*as ac from"node:path";function Ln(e,t,n,o){return new x(e,{exitCode:k,errorCode:t,hint:n,data:{actual:o}})}function mk(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw Ln("--episode must be a positive integer.","INGEST_SKIP_EPISODE_INVALID","Pass the current next_episode from `scriptctl ingest status`.",[String(e)]);return t}async function gk(e,t,n){let o=new ft(e);if(!o.has("manifest.json"))throw Ln("The ingest workspace does not exist.","INGEST_SKIP_WORKSPACE_MISSING","Run video ingest first, then retry the failed episode or skip it.",[e]);let i=o.readJson("manifest.json");if(i.source?.kind!=="video-file"&&i.source?.kind!=="video-directory")throw Ln("Only video ingest episodes can be skipped.","INGEST_SKIP_WRONG_PIPELINE","Use skip only with a video ingest workspace.",[e]);let r=xl(o);if(!r)throw Ln("The video ingest manifest is missing.","INGEST_SKIP_WORKSPACE_MISSING","Run video ingest first.",[e]);let s=r.episodes.find(w=>w.episode===t);if(!s)throw Ln("The requested episode is not in the video source.","INGEST_SKIP_EPISODE_NOT_FOUND","Pass an episode listed in manifest.json.",[`episode=${t}`]);let c=_l(o);tc(c.episodes,r.episodes);let a=o.has("context.json")?o.readJson("context.json"):Vo();if(c.episodes.find(w=>w.episode===t)){let w=Sl(o,r);a=ms(o,a,c.episodes);let y=o.has("v4_identity_map.json")?o.readJson("v4_identity_map.json"):Co();return oc(o,w.episodes,a,ic(w.source.path),y,c.episodes),!1}let p=a.lastEpisode+1;if(t!==p)throw Ln("Only the next unresolved video episode can be skipped.","INGEST_SKIP_NOT_NEXT","Read status.next_episode and skip exactly that episode.",[`requested=${t}`,`next_episode=${p}`]);let l=`ep/ep_${String(t).padStart(3,"0")}`;if(o.has(`${l}.json`))throw Ln("A parsed episode cannot be skipped.","INGEST_SKIP_ALREADY_PARSED","Continue ingest from the next unresolved episode.",[`episode=${t}`]);if(!o.has(`${l}.error.json`))throw Ln("The episode has no recorded ingest failure.","INGEST_SKIP_FAILURE_REQUIRED","Run ingest for this episode first; a typed error sidecar is required before manual skip.",[`episode=${t}`]);let f=us(o.readJson(`${l}.error.json`));if(!f||f.unit.episode!==t)throw Ln("The episode error sidecar is invalid.","INGEST_SKIP_FAILURE_INVALID","Regenerate the typed failure by rerunning video ingest.",[`${l}.error.json`]);let u={episode:t,skipped_at:new Date().toISOString(),reason:n,source_sha256:s.sha256,failure:f.failure,attempts:f.attempts},m=Sl(o,r),h=[...c.episodes,u];o.writeJson("manifest.json",{...m,updated:u.skipped_at,current_error:void 0,skips:h}),_y(o,{schema_version:1,episodes:h}),a=ms(o,a,h);let g=o.has("v4_identity_map.json")?o.readJson("v4_identity_map.json"):Co();return oc(o,m.episodes,a,ic(m.source.path),g,[...c.episodes,u]),!0}async function Ny(e){let t=ac.resolve(typeof e.workspace_path=="string"?e.workspace_path:"workspace"),n=mk(e.episode),o=typeof e.reason=="string"?e.reason.trim():"";if(!o)throw Ln("--reason is required.","INGEST_SKIP_REASON_REQUIRED","Record why this episode cannot be parsed.",["--reason <text>"]);let i=await Do(t,()=>gk(t,n,o)),r=hs(t),s=_l(new ft(t)).episodes.map(c=>c.episode);return[{text:i?`Episode ${n} skipped; ingest can continue at episode ${r.next_episode??"end"}.`:`Episode ${n} was already skipped; no changes made.`,data:{workspace:t,episode:n,changed:i,skipped_episodes:s,complete:r.complete??!1,next_episode:r.next_episode??null,script_path:ac.join(t,"script.json")}},G]}import*as dc from"node:fs";import*as bi from"node:path";import{spawnSync as hk}from"node:child_process";function cc(e,t,n,o){return new x(e,{exitCode:k,errorCode:t,hint:n,data:{actual:o}})}function yk(e){let t=Za(On(e)),n=Qa(t);if(n)throw cc("Video episode files are not a continuous 1..N sequence.","EVIDENCE_VIDEO_SEQUENCE_INVALID","Rename the linked videos so every script episode has one matching numbered file.",[n]);return t.map(o=>{let i=bi.resolve(o.path),r=dc.statSync(i),s=r.size,c=Math.trunc(r.mtimeMs),a=hk("ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",i],{encoding:"utf-8"}),d=Number(a.stdout.trim()),p=a.status===0&&Number.isFinite(d)&&d>0?Math.round(d*1e3):void 0;return{episode:o.episode,path:i,ext:o.ext,mime:o.mime,sha256:_e(JSON.stringify({absolutePath:i,sizeBytes:s,mtimeMs:c})),size_bytes:s,mtime_ms:c,duration_ms:p}})}async function wk(e){let t=bi.resolve(e.scriptPath),n=bi.resolve(e.sourcePath),o=bi.resolve(e.workspacePath),i=$i(JSON.parse(dc.readFileSync(t,"utf-8"))),r=yk(n);if(r.length!==i.episodes.length)throw cc("The linked video count does not match the script episode count.","EVIDENCE_VIDEO_EPISODE_COUNT_MISMATCH","Bind the complete source-video folder for this script, then retry.",[`script=${i.episodes.length}`,`videos=${r.length}`]);let s=Wa(r),c=Ya([],i,Vo(),r,s),a=await Do(o,async()=>{let p=new ft(o);return p.ensure(),Xa(p,c,e.signal,e.extractor,{reuseExistingFrames:e.force!==!0})}),d=[...a.items.flatMap(p=>p.samples),...(a.identities??[]).flatMap(p=>p.samples)];return{output:bi.join(o,"evidence","state-evidence.json"),states:a.items.length,identities:a.identities?.length??0,samples:d.length,ready:d.filter(p=>p.frame_status==="ready").length,unavailable:d.filter(p=>p.frame_status==="unavailable").length,sourceSha256:s}}async function Ly(e){let t=me(e),n=typeof e.source_path=="string"?e.source_path.trim():"",o=typeof e.workspace_path=="string"?e.workspace_path.trim():"";if(!n)throw cc("--source-path is required.","EVIDENCE_SOURCE_REQUIRED","Pass the linked source-video file or folder.",["--source-path <path>"]);if(!o)throw cc("--workspace-path is required.","EVIDENCE_WORKSPACE_REQUIRED","Pass the project workspace directory.",["--workspace-path <path>"]);let i=await wk({scriptPath:t,sourcePath:n,workspacePath:o,force:e.force===!0});return[{text:`Generated ${i.ready}/${i.samples} original-video reference frames for ${i.states} actor states.`,data:{output:i.output,states:i.states,identities:i.identities,samples:i.samples,ready:i.ready,unavailable:i.unavailable,source_sha256:i.sourceSha256}},G]}import*as Jo from"node:fs";import*as pc from"node:path";var bt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),so=e=>Array.isArray(e),ze=e=>typeof e=="string"?e:"",_k={interior:"\u5185",exterior:"\u5916"},Ek={day:"\u65E5",night:"\u591C"},xk=e=>{let t=e.match(/(\d+)/);return t?Number(t[1]):0},Sk=e=>{let t=e.match(/(\d+)/);return t?Number(t[1]):0};function Ol(e,t,n){let o=new Map;if(so(e))for(let i of e)bt(i)&&typeof i[t]=="string"&&o.set(i[t],ze(i[n]));return o}function Ik(e,t){let n=new Map;if(so(e))for(let o of e){if(!bt(o)||typeof o[t]!="string")continue;let i=new Map;for(let r of so(o.states)?o.states:[])bt(r)&&typeof r.state_id=="string"&&i.set(r.state_id,ze(r.state_name));n.set(o[t],i)}return n}function Ak(e,t){return bt(e)?typeof e.actor_id=="string"?t.get(e.actor_id)??e.actor_id:typeof e.kind=="string"?`${e.kind}${e.label?`:${ze(e.label)}`:""}`:"":""}function kk(e){let t=Ol(e.actors,"actor_id","actor_name"),n=Ol(e.locations,"location_id","location_name"),o=Ol(e.props,"prop_id","prop_name"),i=Ik(e.actors,"actor_id"),r=(so(e.episodes)?e.episodes:[]).filter(bt).map(c=>({episode:xk(ze(c.episode_id)),synopsis:ze(c.synopsis),scenes:(so(c.scenes)?c.scenes:[]).filter(bt).map(a=>{let d=bt(a.location)?n.get(ze(a.location.location_id))??ze(a.location.location_id):"",p=[],l={};for(let m of so(a.actors)?a.actors:[]){if(!bt(m)||typeof m.actor_id!="string")continue;let h=t.get(m.actor_id)??m.actor_id;if(p.includes(h)||p.push(h),typeof m.state_id=="string"){let w=(i.get(m.actor_id)?.get(m.state_id)??"")||(m.state_id!=="default"?m.state_id:"");w&&(l[h]=w)}}let f=[];for(let m of so(a.props)?a.props:[])if(bt(m)&&typeof m.prop_id=="string"){let h=o.get(m.prop_id)??m.prop_id;f.includes(h)||f.push(h)}let u=bt(a.environment)?a.environment:{};return{scene_num:Sk(ze(a.scene_id)),location_name:d,environment:{space:_k[ze(u.space)]??ze(u.space),time:Ek[ze(u.time)]??ze(u.time)},actor_names:p,actor_states:l,prop_names:f,actions:(so(a.actions)?a.actions:[]).filter(bt).map(m=>({type:ze(m.type),content:ze(m.content),speaker:Ak(m.speaker,t),emotion:typeof m.emotion=="string"?m.emotion:void 0,extend:bt(m.extend)&&typeof m.extend.timestamp=="string"?{timestamp:m.extend.timestamp}:void 0}))}})})),s=(so(e.actors)?e.actors:[]).filter(bt).map(c=>({asset_name:ze(c.actor_name),description:ze(c.description),extend:{}}));return{title:ze(e.title),actors:s,episodes:r}}function Uy(e){if(!bt(e))throw new Error("review renderer expects a script object");let t=kk(e),n=JSON.stringify(t),o=ze(t.title);return`<!DOCTYPE html>
341
343
  <html lang="zh">
342
344
  <head>
343
345
  <meta charset="utf-8">
@@ -658,10 +660,10 @@ tabScript.addEventListener('click',()=>switchTab('script'));
658
660
  tabAssets.addEventListener('click',()=>switchTab('assets'));
659
661
  </script>
660
662
  </body>
661
- </html>`}import*as Ny from"node:http";import*as Bo from"node:fs";import*as Un from"node:path";import{spawn as kk}from"node:child_process";var bk=e=>e==null?"":String(e);function Ok(e){let t=r=>{try{let s=Bo.statSync(Un.join(e,r));return{rel:r,size:s.size,mtime:s.mtimeMs}}catch{return null}},n=(r,s)=>{let c=[];try{c=Bo.readdirSync(Un.join(e,r))}catch{return[]}return c.filter(s).sort().map(a=>t(`${r}/${a}`)).filter(a=>!!a)},o=r=>r.filter(s=>!!s),i=r=>n("ep",s=>s.endsWith(r)&&!s.endsWith(".error.json"));return{\u7ED3\u679C:o([t("script.json"),t("validation.json"),t("asset-audit.json"),t("usage.json"),t("review.html"),t("timings.json")]),\u4E0A\u4E0B\u6587:n("serial",r=>r.startsWith("context_")&&r.endsWith(".md")),\u6BCF\u7A97\u66F4\u65B0:n("serial",r=>r.startsWith("win_")&&r.endsWith(".json")),\u7BC7\u7AE0\u6897\u6982:n("serial",r=>r.startsWith("arc_")&&r.endsWith(".md")),\u524D\u6BB5:n("pass2",r=>/^chunk_\d+\.json$/.test(r)),\u8F6C\u5F55:[...i(".ep"),...i(".md").filter(r=>!r.rel.endsWith(".context.md"))].sort((r,s)=>r.rel.localeCompare(s.rel)),\u9001\u6A21\u4E0A\u4E0B\u6587:i(".context.md"),\u89E3\u6790:i(".json"),\u82B1\u540D\u518C:o([t("context.json")]),\u8BA1\u65F6:o([t("timing.jsonl")]),\u4E2D\u95F4\u4EA7\u7269:o([t("script.initial.json"),t("provisional_assets.json"),t("notes.json"),t("id_map.json"),t("manifest.json")])}}function vk(e){let t="";try{t=Bo.readFileSync(Un.join(e,"timing.jsonl"),"utf-8")}catch{return{episodes:[],totalMs:0}}let n=[],o=0;for(let i of t.split(/\r?\n/)){let r=i.trim();if(r)try{let s=JSON.parse(r);if(typeof s.episode!="number")continue;let c={episode:s.episode};typeof s.transcodeMs=="number"&&(c.transcodeMs=s.transcodeMs,o+=s.transcodeMs),typeof s.uploadMs=="number"&&(c.uploadMs=s.uploadMs,o+=s.uploadMs),typeof s.generateMs=="number"&&(c.generateMs=s.generateMs,o+=s.generateMs),typeof s.uploadMB=="string"&&(c.uploadMB=s.uploadMB),typeof s.transcoded=="boolean"&&(c.transcoded=s.transcoded),n.push(c)}catch{}}return{episodes:n,totalMs:o}}function Rk(e){try{return JSON.parse(Bo.readFileSync(Un.join(e,"usage.json"),"utf-8"))}catch{return null}}function Mk(e,t){let n=Un.resolve(e,t);if(n!==e&&!n.startsWith(e+Un.sep))return{ok:!1};try{return{ok:!0,text:Bo.readFileSync(n,"utf-8")}}catch{return{ok:!1}}}function hs(e,t,n,o){e.writeHead(t,{"Content-Type":n,"Cache-Control":"no-store"}),e.end(o)}async function Ly(e){let t=Un.resolve(bk(e.workspace_path||"workspace")),n=Number(e.port)||0,o=Ny.createServer((s,c)=>{let a=new URL(s.url??"/","http://localhost");if(a.pathname==="/")return hs(c,200,"text/html; charset=utf-8",Nk);if(a.pathname==="/api/state"){let d=gs(t);return hs(c,200,"application/json",JSON.stringify({root:t,status:d,groups:Ok(t),timing:vk(t),usage:Rk(t)}))}if(a.pathname==="/api/file"){let d=a.searchParams.get("path")??"",p=Mk(t,d);return p.ok?hs(c,200,"text/plain; charset=utf-8",p.text):hs(c,404,"text/plain","not found")}hs(c,404,"text/plain","not found")}),r=`http://127.0.0.1:${await new Promise((s,c)=>{o.once("error",c),o.listen(n,"127.0.0.1",()=>s(o.address().port))})}/`;if(process.stderr.write(`Ingest monitor: ${r}
663
+ </html>`}import*as Py from"node:http";import*as Bo from"node:fs";import*as Un from"node:path";import{spawn as bk}from"node:child_process";var Ok=e=>e==null?"":String(e);function vk(e){let t=r=>{try{let s=Bo.statSync(Un.join(e,r));return{rel:r,size:s.size,mtime:s.mtimeMs}}catch{return null}},n=(r,s)=>{let c=[];try{c=Bo.readdirSync(Un.join(e,r))}catch{return[]}return c.filter(s).sort().map(a=>t(`${r}/${a}`)).filter(a=>!!a)},o=r=>r.filter(s=>!!s),i=r=>n("ep",s=>s.endsWith(r)&&!s.endsWith(".error.json"));return{\u7ED3\u679C:o([t("script.json"),t("validation.json"),t("asset-audit.json"),t("usage.json"),t("review.html"),t("timings.json")]),\u4E0A\u4E0B\u6587:n("serial",r=>r.startsWith("context_")&&r.endsWith(".md")),\u6BCF\u7A97\u66F4\u65B0:n("serial",r=>r.startsWith("win_")&&r.endsWith(".json")),\u7BC7\u7AE0\u6897\u6982:n("serial",r=>r.startsWith("arc_")&&r.endsWith(".md")),\u524D\u6BB5:n("pass2",r=>/^chunk_\d+\.json$/.test(r)),\u8F6C\u5F55:[...i(".ep"),...i(".md").filter(r=>!r.rel.endsWith(".context.md"))].sort((r,s)=>r.rel.localeCompare(s.rel)),\u9001\u6A21\u4E0A\u4E0B\u6587:i(".context.md"),\u89E3\u6790:i(".json"),\u82B1\u540D\u518C:o([t("context.json")]),\u8BA1\u65F6:o([t("timing.jsonl")]),\u4E2D\u95F4\u4EA7\u7269:o([t("script.initial.json"),t("provisional_assets.json"),t("notes.json"),t("id_map.json"),t("manifest.json")])}}function Rk(e){let t="";try{t=Bo.readFileSync(Un.join(e,"timing.jsonl"),"utf-8")}catch{return{episodes:[],totalMs:0}}let n=[],o=0;for(let i of t.split(/\r?\n/)){let r=i.trim();if(r)try{let s=JSON.parse(r);if(typeof s.episode!="number")continue;let c={episode:s.episode};typeof s.transcodeMs=="number"&&(c.transcodeMs=s.transcodeMs,o+=s.transcodeMs),typeof s.uploadMs=="number"&&(c.uploadMs=s.uploadMs,o+=s.uploadMs),typeof s.generateMs=="number"&&(c.generateMs=s.generateMs,o+=s.generateMs),typeof s.uploadMB=="string"&&(c.uploadMB=s.uploadMB),typeof s.transcoded=="boolean"&&(c.transcoded=s.transcoded),n.push(c)}catch{}}return{episodes:n,totalMs:o}}function Mk(e){try{return JSON.parse(Bo.readFileSync(Un.join(e,"usage.json"),"utf-8"))}catch{return null}}function Nk(e,t){let n=Un.resolve(e,t);if(n!==e&&!n.startsWith(e+Un.sep))return{ok:!1};try{return{ok:!0,text:Bo.readFileSync(n,"utf-8")}}catch{return{ok:!1}}}function ys(e,t,n,o){e.writeHead(t,{"Content-Type":n,"Cache-Control":"no-store"}),e.end(o)}async function Cy(e){let t=Un.resolve(Ok(e.workspace_path||"workspace")),n=Number(e.port)||0,o=Py.createServer((s,c)=>{let a=new URL(s.url??"/","http://localhost");if(a.pathname==="/")return ys(c,200,"text/html; charset=utf-8",Lk);if(a.pathname==="/api/state"){let d=hs(t);return ys(c,200,"application/json",JSON.stringify({root:t,status:d,groups:vk(t),timing:Rk(t),usage:Mk(t)}))}if(a.pathname==="/api/file"){let d=a.searchParams.get("path")??"",p=Nk(t,d);return p.ok?ys(c,200,"text/plain; charset=utf-8",p.text):ys(c,404,"text/plain","not found")}ys(c,404,"text/plain","not found")}),r=`http://127.0.0.1:${await new Promise((s,c)=>{o.once("error",c),o.listen(n,"127.0.0.1",()=>s(o.address().port))})}/`;if(process.stderr.write(`Ingest monitor: ${r}
662
664
  Workspace: ${t}
663
665
  Press Ctrl-C to stop.
664
- `),process.platform==="darwin"&&process.stderr.isTTY)try{kk("open",[r],{detached:!0,stdio:"ignore"}).unref()}catch{}return process.once("SIGINT",()=>o.close()),process.once("SIGTERM",()=>o.close()),[{text:r,data:{url:r,workspace:t}},B]}var Nk=`<!doctype html><html lang="zh"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
666
+ `),process.platform==="darwin"&&process.stderr.isTTY)try{bk("open",[r],{detached:!0,stdio:"ignore"}).unref()}catch{}return process.once("SIGINT",()=>o.close()),process.once("SIGTERM",()=>o.close()),[{text:r,data:{url:r,workspace:t}},G]}var Lk=`<!doctype html><html lang="zh"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
665
667
  <title>scriptctl ingest \u76D1\u542C</title>
666
668
  <style>
667
669
  :root{--bg:#f6f7f9;--panel:#ffffff;--panel2:#f0f2f5;--line:#e3e6ea;--fg:#1f2430;--dim:#6b7280;--acc:#2563eb;--ok:#16a34a;--warn:#d97706;--err:#dc2626}
@@ -859,7 +861,7 @@ function poll(){
859
861
  }).catch(function(){$('#tick').textContent='\u25CF \u79BB\u7EBF'});
860
862
  }
861
863
  poll();setInterval(poll,1500);setInterval(renderTiming,1000);
862
- </script></body></html>`;function Uy(e,t){let n=new Map(e.actors.map(s=>[s.actor_id,s.actor_name])),o=new Map(e.locations.map(s=>[s.location_id,s.location_name])),i={title:e.title,documents:t,episodes:e.episodes.map((s,c)=>({title:s.title??`\u7B2C ${c+1} \u8BDD`,synopsis:s.synopsis??"",scenes:s.scenes.map((a,d)=>({title:`${d+1} \xB7 ${a.location?o.get(a.location.location_id):"\u672A\u660E\u786E\u5730\u70B9"}`,actions:a.actions.map(p=>{let l=ci.safeParse(p.extend);return{id:p.action_id,type:p.type,content:p.content,source:l.success?l.data.scriptctl.source:null,speaker:"speaker"in p?"actor_id"in p.speaker?n.get(p.speaker.actor_id):p.speaker.label??p.speaker.kind:"",parenthetical:"parenthetical"in p?p.parenthetical:""}})}))})),actors:e.actors.map(s=>({name:s.actor_name,description:s.description,states:s.states}))};return`<!doctype html>
864
+ </script></body></html>`;function Ty(e,t){let n=new Map(e.actors.map(s=>[s.actor_id,s.actor_name])),o=new Map(e.locations.map(s=>[s.location_id,s.location_name])),i={title:e.title,documents:t,episodes:e.episodes.map((s,c)=>({title:s.title??`\u7B2C ${c+1} \u8BDD`,synopsis:s.synopsis??"",scenes:s.scenes.map((a,d)=>({title:`${d+1} \xB7 ${a.location?o.get(a.location.location_id):"\u672A\u660E\u786E\u5730\u70B9"}`,actions:a.actions.map(p=>{let l=ci.safeParse(p.extend);return{id:p.action_id,type:p.type,content:p.content,source:l.success?l.data.scriptctl.source:null,speaker:"speaker"in p?"actor_id"in p.speaker?n.get(p.speaker.actor_id):p.speaker.label??p.speaker.kind:"",parenthetical:"parenthetical"in p?p.parenthetical:""}})}))})),actors:e.actors.map(s=>({name:s.actor_name,description:s.description,states:s.states}))};return`<!doctype html>
863
865
  <html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
864
866
  <title>\u6F2B\u753B\u5267\u672C\u5BA1\u9605</title>
865
867
  <style>
@@ -1008,39 +1010,39 @@ if(model.episodes.length){
1008
1010
  const action=actions.find(action=>action.id===requested.get('action'));
1009
1011
  if(action?.source){const page=Number(requested.get('page'));selectAction(action,action.source.pages.includes(page)?page:action.source.pages[0],true,requested.has('region')?Number(requested.get('region')):undefined);}
1010
1012
  }
1011
- </script></html>`}var Lk=e=>e==null?"":String(e),Uk=e=>String(e).padStart(3,"0");function Pk(e){if(!e.has("manifest.json"))return;let t=e.readJson("manifest.json");if(!Array.isArray(t.episodes))return;let n=e.path("src");Jo.mkdirSync(n,{recursive:!0});for(let o of t.episodes){if(typeof o.episode!="number"||typeof o.path!="string")continue;let i=cc.join(n,`ep_${Uk(o.episode)}.mp4`);try{Jo.rmSync(i,{force:!0}),Jo.symlinkSync(o.path,i)}catch{}}}async function Py(e){if(e.watch){if((process.env.SANDBOX_PROJECT_GROUP_NO??"").trim())throw new S("`view --watch` runs a local web server and opens a browser; it is local-only and unavailable in the sandbox.",{exitCode:k,errorCode:"VIEW_WATCH_SANDBOX",hint:"Use `scriptctl ingest status` for progress in the sandbox; run `view --watch` on your local machine."});return Ly(e)}let t=Lk(e.workspace_path||"workspace"),n=new ft(cc.resolve(t));if(!n.has("script.json"))throw new S("workspace has no script.json to render.",{exitCode:k,errorCode:"VIEW_NO_SCRIPT",hint:"Run `scriptctl ingest --source-path <src> --workspace-path <dir>` first.",data:{actual:[n.path("script.json")]}});let o=n.has("manifest.json")?n.readJson("manifest.json"):null,i;if(o?.source?.kind==="comic-file"||o?.source?.kind==="comic-directory"){let s=n.readJson("manifest.json"),c=Vi(n.readJson("script.json")),a=new Set;for(let p of c.episodes)for(let l of p.scenes)for(let f of l.actions){let u=ci.safeParse(f.extend);u.success&&a.add(u.data.scriptctl.source.document_id)}let d=[];n.passDir("src");for(let p of a){let l=s.episodes.find(g=>g.document_id===p);if(!l)throw new S(`Unknown comic source document: ${p}`,{exitCode:k,errorCode:"VIEW_COMIC_SOURCE_MISSING"});let f=n.path(`src/${l.document_id}.pdf`);Jo.rmSync(f,{force:!0}),Jo.symlinkSync(l.path,f);let u=await ma(l,n.root);d.push({id:l.document_id,title:l.title,pdf:`src/${l.document_id}.pdf`,images:u})}i=Uy(c,d)}else Pk(n),i=My(n.readJson("script.json"));n.writeText("review.html",i);let r=n.path("review.html");return[{text:r,data:{output:r}},B]}import*as bi from"node:path";import Ck from"fast-json-patch";var{compare:Cy}=Ck;var Ty="/api/anime/workbench/v2/script/project-groups",Tk="/api/anime/workbench/projectGroup/updateProjectGroupInfo",Vk=5e3,Vy=8*1024*1024;function $k(e){let t=e.trim().replace(/\/+$/,"");for(let n of["/api/anime/workbench","/api/sandbox"])if(t.endsWith(n)){t=t.slice(0,-n.length);break}return t.replace(/\/+$/,"")}function $y(e){return encodeURIComponent(String(e))}function Dk(e,t,n){if(t===404&&n.includes("/imports"))return new me("backend lacks episode import API",{status:t,payload:e});let o=null;try{o=e?JSON.parse(e):null}catch{o=null}if(o&&typeof o=="object"){let i=o,r=String(i.msg??i.message??`HTTP ${t}`);return new me(r,{status:t,code:i.code??null,payload:i})}return new me(e||`HTTP ${t}`,{status:t,payload:e})}function Dy(e,t){let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(!(n<=Vy))throw new me(`script ${e} body too large: ${n} bytes (limit ${Vy})`)}async function Gy(e,t,n,o,i,r={}){let s=r.body===void 0?void 0:JSON.stringify(r.body),c={Accept:"application/json","X-Access-Key":t};s!==void 0&&(c["Content-Type"]="application/json; charset=utf-8");let a=new AbortController,d=setTimeout(()=>a.abort(),n),p,l;try{let h=await fetch(`${e}${i}`,{method:o,headers:c,body:s,signal:a.signal});p=h.status,l=await h.text()}catch(h){if(h instanceof Error&&h.name==="AbortError")throw new me("Gateway request timed out");let m=h instanceof Error?h.message:String(h);throw new me(`Gateway request failed: ${m}`)}finally{clearTimeout(d)}if(p>=400)throw Dk(l,p,i);let f=null;if(l)try{f=JSON.parse(l)}catch{throw new me("Gateway response is not valid JSON",{status:p,payload:l})}if(f===null)return null;if(typeof f!="object")return f;let u=f,g=u.code;if(g!=null&&String(g)!=="200"){let h=String(u.msg??u.message??"script-output API failed");if(r.allowMissing&&typeof h=="string"&&h.includes("\u5267\u672C\u4E0D\u5B58\u5728"))return null;throw new me(h,{status:p,code:g,payload:u})}return"data"in u?u.data:u}var bl=class e{gatewayBase;projectGroupNo;accessKey;timeoutMs;constructor(t){this.gatewayBase=t.gatewayBase,this.projectGroupNo=t.projectGroupNo,this.accessKey=t.accessKey,this.timeoutMs=t.timeoutMs??3e5}static fromEnv(t){let n=(t??process.env.SANDBOX_PROJECT_GROUP_NO??"").trim();if(!n)throw new me("projectGroupNo missing; pass --project-group-no or set SANDBOX_PROJECT_GROUP_NO",{configMissing:"project"});let o=$k(process.env.AWB_BASE_URL||"");if(!o)throw new me("gateway URL missing; set AWB_BASE_URL",{configMissing:"gateway"});let i=(process.env.LINGJING_AWB_ACCESS_KEY||"").trim();if(!i)throw new me("access key missing; set LINGJING_AWB_ACCESS_KEY",{configMissing:"access"});return new e({gatewayBase:o,projectGroupNo:n,accessKey:i})}get projectPrefix(){return`${Ty}/${$y(this.projectGroupNo)}`}async getScript(){return await this.request("GET",this.projectPrefix,{allowMissing:!0})}async getRevision(){return await this.request("GET",`${this.projectPrefix}/revision`,{allowMissing:!0})}async getSnapshot(){return await this.request("GET",`${this.projectPrefix}/snapshot`,{allowMissing:!0})}async publishPatch(t){return await this.request("PATCH",`${this.projectPrefix}/publish`,{body:{baseRevision:t.baseRevision,patch:Cy(t.old,t.edited),validation:t.validation}})}async replaceScript(t){let n={requestId:t.requestId,baseRevision:t.baseRevision,source:t.source??"ctl",script:t.script};return Dy("root",n),await this.request("PUT",this.projectPrefix,{body:n})}async patchScript(t){let n=Cy(t.old,t.edited),o={requestId:t.requestId,baseRevision:t.baseRevision,source:t.source??"ctl",patch:n};return Dy("patch",o),await this.request("PATCH",this.projectPrefix,{body:o})}async saveValidationResult(t){return await this.request("POST",`${Ty}/${$y(this.projectGroupNo)}/validation-result`,{body:{revision:t.revision,validationStatus:t.validationStatus,validationSummary:t.validationSummary,issues:t.issues}})}async updateEpisodeCount(t){await Gy(this.gatewayBase,this.accessKey,Math.min(this.timeoutMs,Vk),"POST",Tk,{body:{projectGroupNo:this.projectGroupNo,episodeCount:t}})}async request(t,n,o={}){return Gy(this.gatewayBase,this.accessKey,this.timeoutMs,t,n,o)}};function Ol(e){return bl.fromEnv(e)}var ys=class{workspace;script;version;baseline;baselineHash;scriptPath;client;projectGroupNo;revision;constructor(t){this.workspace=t.workspace,this.script=t.script,this.version=Qo(t.script),this.baseline=structuredClone(t.script),this.baselineHash=Be(t.script),this.scriptPath=t.scriptPath??null,this.client=t.client??null,this.projectGroupNo=t.projectGroupNo??null,this.revision=t.revision??null}get remote(){return this.client!==null}get artifactLabel(){return this.remote?`script-output/${this.projectGroupNo}@revision/${this.revision??0}`:this.scriptPath??""}};function jo(e,t){let n=t.message||"script-output API failed",o=String(t.code)==="9002"||n.includes("\u7248\u672C\u51B2\u7A81"),i=n.includes("\u5267\u672C\u4E0D\u5B58\u5728"),r=o?"Script has been updated by another revision; keep local work and merge before retrying.":i?"Script not found on the gateway.":"Gateway request failed.";return new S(r,{exitCode:t.status!==null&&t.status>=500?ee:k,errorCode:o?"REVISION_CONFLICT":i?"SCRIPT_NOT_FOUND":"SCRIPT_API_FAILED",hint:o?"Keep the local file, inspect the latest remote snapshot, and merge before publishing again.":i?"Run `scriptctl publish` to publish a script first.":"Run `scriptctl doctor` to verify gateway configuration; retry if it was transient.",data:{expected:["successful script-output gateway request"],actual:[n,`status: ${t.status??"<unknown>"}`]}})}async function ws(e){let t=v(e.workspace_path||"workspace"),n=ge(e);if(!zo(n))throw new S("Local script file not found.",{exitCode:k,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[n]}});let o;try{o=xr(n)}catch(i){throw new S("script JSON invalid.",{exitCode:k,errorCode:"SCRIPT_JSON_INVALID",hint:"Fix the local script JSON syntax before editing.",data:{expected:["valid JSON"],actual:[`${n}: ${i.message}`]}})}if(!ie(o))throw new S("script root invalid.",{exitCode:J,errorCode:"SCRIPT_ROOT_INVALID",hint:"Use a valid script document object.",data:{expected:["script root object"],actual:[Array.isArray(o)?"array":typeof o]}});return new ys({workspace:t,scriptPath:n,script:o})}function _s(e,t={}){let n=vl(e.script);return e.remote&&(n.script_path=e.artifactLabel),n}function Gk(e,t){let{ok:n,errors:o,warnings:i}=t,r=[...o.map(d=>({severity:"error",code:d.code,path:d.path,summary:d.message,...d.repair_hint?{repair_hint:d.repair_hint}:{}})),...i.map(d=>({severity:"warning",code:d.code,path:d.path,summary:d.message,...d.repair_hint?{repair_hint:d.repair_hint}:{}}))],s=re(e.episodes),c=0,a=0;for(let d of s)for(let p of re(d.scenes))c+=1,a+=re(p.actions).length;return{passed:n,has_blocking:!n,issues:r,stats:{actors:re(e.actors).length,locations:re(e.locations).length,props:re(e.props).length,episodes:s.length,scenes:c,actions:a}}}function vl(e){return Gk(e,Mr(e))}function Bk(e){if(e.path)return v(e.path);let t=[];return e.episode!==null&&e.episode!==void 0&&t.push(v(e.episode)),e.scene!==null&&e.scene!==void 0&&t.push(v(e.scene)),e.action_index!==null&&e.action_index!==void 0&&t.push(`action[${e.action_index}]`),t.length>0?t.join("/"):null}function Jk(e){let t=v(e||"info");return t==="blocking"||t==="error"?"error":t==="warning"?"warning":"info"}function jk(e){let t=re(e.issues),n=e.passed?"valid":"invalid",o={passed:!!e.passed,hasBlocking:!!e.has_blocking,stats:e.stats??{},issueCount:t.length},i=[];for(let r of t){if(!ie(r))continue;let s={...r};for(let c of["severity","code","path","summary","repair_hint"])delete s[c];i.push({severity:Jk(r.severity),code:v(r.code||"SCRIPT_VALIDATION_ISSUE"),path:Bk(r),summary:v(r.summary),repairHint:r.repair_hint,payload:s})}return[n,o,i]}async function Rl(e,t,n){if(!e.remote||e.client===null)return;let o=Number(n??e.revision??0);if(o<=0)return;let[i,r,s]=jk(t);try{await e.client.saveValidationResult({revision:o,validationStatus:i,validationSummary:r,issues:s})}catch(c){throw c instanceof me?jo("SCRIPT API BLOCKED: Validation sync failed",c):c}}async function Ml(e,t,n){if(e.scriptPath===null)throw new Error("local script session missing script path");return Gt(e.scriptPath,e.baselineHash),Fe(e.scriptPath,e.script),[null,!1]}async function By(e,t=Wn){let n=await ws(e),o=t.createExecutor(v(e.llm_config).trim()||void 0),i=await qp(n.script,o);n.scriptPath&&Gt(n.scriptPath,n.baselineHash);let r=n.scriptPath?bi.dirname(n.scriptPath):bi.resolve(n.workspace),s=bi.resolve(v(e.output).trim()||bi.join(r,"asset-audit.json"));Fe(s,i);let c=i.issues.length>0,a=i.issues.map(Zp);return[{text:[`${i.summary.issues} issues; confidence high=${i.summary.high} medium=${i.summary.medium} low=${i.summary.low}`,...a,`output: ${s}`,...c?["Inspect each finding, repair confirmed duplicates, then rerun `scriptctl audit-assets` and `scriptctl validate`."]:[]].join(`
1012
- `),data:{op:"script.audit-assets",changed:!1,issues:i.issues,output:s,asset_audit:i,config_source:o.configSource,llm_routes:o.usage()}},c?co:B]}function Jy(e=""){return{version:4,title:e,worldview:"",style:"",actors:[],locations:[],props:[],episodes:[]}}function Ko(e){let t=ie(e.location)?e.location:null;return{actors:Bn(e.actors)?e.actors:[],props:Bn(e.props)?e.props:[],locations:t&&String(t.location_id??"").trim()?[t]:[]}}function Zy(e,t,n){let o=!!t.passed,i=[`created: blank script (Script v${e.version})`,`validation: ${o?"passed":"needs repair"}`];return e.remote&&(i.push(`revision: ${e.revision}`),n!==null&&i.push(`idempotent: ${String(n).toLowerCase()}`)),{text:i.join(`
1013
- `),data:{op:"script.create",changed:!0,validation:t,script_path:e.artifactLabel,...e.remote?{revision:e.revision,idempotent:n}:{}}}}async function Wy(e){let t=v(e.workspace_path||"workspace"),n=!!e.force,o=v(e.title).trim(),i=Jy(o),r=ge(e);if(zo(r)&&!n)throw new S("A script already exists at the target.",{exitCode:k,errorCode:"SCRIPT_EXISTS",hint:"Edit the existing script with the atomic verbs, or pass --force to overwrite with a blank scaffold.",data:{expected:["a non-existent target, or --force to overwrite"],actual:[r]}});Fe(r,i);let s=new ys({workspace:t,scriptPath:r,script:i}),c=_s(s),a=!!c.passed;return[Zy(s,c,null),a?B:co]}import*as yr from"node:fs";import*as vi from"node:path";function ob(e){let t={};for(let n of e.episodes)for(let o of n.scenes){let i=`${n.episode_id}/${o.scene_id}`;o.actions.forEach((r,s)=>{let c=`${i}#${s}`;t[c]=c})}return t}function Oi(e){return ie(e)&&Object.values(e).every(t=>typeof t=="string")}function ib(e){return ie(e)&&Object.values(e).every(Oi)}function rb(e){return ie(e)&&e.version===3&&Oi(e.actor)&&Oi(e.location)&&Oi(e.prop)&&ib(e.state)&&Oi(e.episode)&&Oi(e.scene)&&Oi(e.action)}function sb(e){if(e!==void 0){if(rb(e.identityMap))return e.identityMap;throw new S("Migration manifest contains an invalid v3-to-v4 identity map.",{exitCode:k,errorCode:"MIGRATE_MANIFEST_INVALID"})}}function Xy(e,t){let n=Tt(e),o=rr(n,sb(t),{action:ob(n)});return{script:o.script,artifact:{sourceVersion:3,targetVersion:4,identityMap:o.identityMap}}}var ab=[{sourceVersion:3,targetVersion:4,migrate:Xy}];function cb(e){return ie(e)&&mo(e.source_version)&&mo(e.target_version)&&e.source_version<e.target_version&&"identity_map"in e}function ew(e){if(!Array.isArray(e))throw new S("Migration manifest steps must be an array.",{exitCode:k,errorCode:"MIGRATE_MANIFEST_INVALID"});return e.map(t=>{if(!cb(t))throw new S("Migration manifest contains an invalid step artifact.",{exitCode:k,errorCode:"MIGRATE_MANIFEST_INVALID"});return{sourceVersion:t.source_version,targetVersion:t.target_version,identityMap:t.identity_map}})}function db(e,t){return ab.find(n=>n.sourceVersion===e&&n.targetVersion<=t)}function pb(e,t){return e.find(n=>n.sourceVersion===t.sourceVersion&&n.targetVersion===t.targetVersion)}function tw(e,t,n=[]){let o=Qo(e);if(t<o)throw new S("A migration target must be newer than the source script.",{exitCode:k,errorCode:"MIGRATE_TARGET_OLDER",data:{expected:[String(o)],actual:[String(t)]}});let i=Gs(e),r=o,s=[];for(;r<t;){let c=db(r,t);if(c===void 0)throw new S(`No migration path exists from Script v${r} to Script v${t}.`,{exitCode:k,errorCode:"MIGRATE_PATH_UNSUPPORTED",data:{actual:[String(r),String(t)]}});let a=c.migrate(i,pb(n,c));i=a.script,r=c.targetVersion,s.push(a.artifact)}return{sourceVersion:o,targetVersion:t,script:i,steps:s}}function Es(e,t){let n=e[t];return typeof n=="string"?n.trim():""}function lb(e,t){let n=Es(e,t);return/^\d+$/.test(n)?Number(n):null}function ub(e){let t=lb(e,"to");if(mo(t))return t;throw new S("A supported migration target version is required.",{exitCode:J,errorCode:"MIGRATE_TARGET_INVALID",hint:"Pass --to <version> with a supported Script version.",data:{expected:zc.map(String),actual:[Es(e,"to")||"<empty>"]}})}function fb(e){let t=vi.extname(e);return`${t.length>0?e.slice(0,-t.length):e}.migration.json`}function mb(e,t,n){let o=[e,t,n].map(i=>vi.resolve(i));if(o[0]===o[1])throw new S("The migration destination must differ from the source.",{exitCode:J,errorCode:"MIGRATE_SAME_PATH",hint:"Choose a separate --output path. The source file stays unchanged.",data:{actual:[e]}});if(o[0]===o[2]||o[1]===o[2])throw new S("The migration manifest needs its own file path.",{exitCode:J,errorCode:"MIGRATE_MANIFEST_PATH",hint:"Choose a --manifest path separate from the source and output files.",data:{actual:[n]}})}function nw(e,t){if(!t&&yr.existsSync(e))throw new S("Migration destination already exists.",{exitCode:J,errorCode:"MIGRATE_OUTPUT_EXISTS",hint:"Choose a new path, or pass --force to replace the migration artifact.",data:{actual:[e]}})}function gb(e){let t;try{t=yr.readFileSync(e,"utf8")}catch(n){throw new S("Cannot read the source script.",{exitCode:J,errorCode:"MIGRATE_SOURCE_READ_FAILED",hint:"Pass an existing JSON file with --script-path.",data:{actual:[e,n instanceof Error?n.message:String(n)]}})}try{return{raw:t,value:JSON.parse(t)}}catch(n){throw new S("The source script is not valid JSON.",{exitCode:J,errorCode:"MIGRATE_SOURCE_JSON_INVALID",hint:"Repair the JSON syntax, then rerun migrate.",data:{actual:[n instanceof Error?n.message:String(n)]}})}}function hb(e,t){if(!t||!yr.existsSync(e))return;let n;try{n=JSON.parse(yr.readFileSync(e,"utf8"))}catch(o){throw new S("Cannot reuse the existing migration manifest.",{exitCode:J,errorCode:"MIGRATE_MANIFEST_INVALID",hint:"Restore the migration manifest, or choose a new --manifest path.",data:{actual:[e,o instanceof Error?o.message:String(o)]}})}if(!ie(n)||n.version!==1||!mo(n.source_version)||!mo(n.target_version)||typeof n.source_path!="string"||typeof n.source_sha256!="string")throw new S("Cannot reuse the existing migration manifest.",{exitCode:J,errorCode:"MIGRATE_MANIFEST_INVALID",hint:"Restore the migration manifest, or choose a new --manifest path.",data:{actual:[e]}});return{version:1,source_version:n.source_version,target_version:n.target_version,source_path:n.source_path,source_sha256:n.source_sha256,steps:ew(n.steps)}}async function ow(e){let t=Es(e,"script_path"),n=Es(e,"output");if(!t||!n)throw new S("Migration paths are required.",{exitCode:J,errorCode:"MIGRATE_PATH_MISSING",hint:"Pass --script-path <source.json> and --output <target.json>.",data:{expected:["--script-path <source.json>","--output <target.json>"]}});let o=vi.resolve(t),i=vi.resolve(n),r=vi.resolve(Es(e,"manifest")||fb(i)),s=ub(e),c=!!e.force;return mb(o,i,r),Ts(i,async()=>{nw(i,c),nw(r,c);let a=gb(o),d=Qo(a.value);if(s<=d)throw new S("The migration target must be newer than the source script.",{exitCode:J,errorCode:"MIGRATE_TARGET_NOT_NEWER",data:{expected:[`>${d}`],actual:[String(s)]}});let p=Mr(a.value),l=hb(r,c),f=tw(a.value,s,l?.steps),u=Mr(f.script),g={version:1,source_version:f.sourceVersion,target_version:f.targetVersion,source_path:o,source_sha256:Ee(a.raw),steps:f.steps};Fe(r,{...g,steps:g.steps.map(w=>({source_version:w.sourceVersion,target_version:w.targetVersion,identity_map:w.identityMap}))}),Fe(i,f.script);let h={op:"script.migrate",changed:!0,source_script_path:o,script_path:i,manifest_path:r,source_version:f.sourceVersion,target_version:f.targetVersion,source_validation:{ok:p.ok,errors:p.errors.length,warnings:p.warnings.length},validation:{ok:u.ok,errors:u.errors.length,warnings:u.warnings.length,issues:u.errors.slice(0,100)}};return[{text:u.ok?[`Script v${f.targetVersion}: ${i}`,`Migration manifest: ${r}`,"validation: ok"].join(`
1013
+ </script></html>`}var Uk=e=>e==null?"":String(e),Pk=e=>String(e).padStart(3,"0");function Ck(e){if(!e.has("manifest.json"))return;let t=e.readJson("manifest.json");if(!Array.isArray(t.episodes))return;let n=e.path("src");Jo.mkdirSync(n,{recursive:!0});for(let o of t.episodes){if(typeof o.episode!="number"||typeof o.path!="string")continue;let i=pc.join(n,`ep_${Pk(o.episode)}.mp4`);try{Jo.rmSync(i,{force:!0}),Jo.symlinkSync(o.path,i)}catch{}}}async function Vy(e){if(e.watch){if((process.env.SANDBOX_PROJECT_GROUP_NO??"").trim())throw new x("`view --watch` runs a local web server and opens a browser; it is local-only and unavailable in the sandbox.",{exitCode:k,errorCode:"VIEW_WATCH_SANDBOX",hint:"Use `scriptctl ingest status` for progress in the sandbox; run `view --watch` on your local machine."});return Cy(e)}let t=Uk(e.workspace_path||"workspace"),n=new ft(pc.resolve(t));if(!n.has("script.json"))throw new x("workspace has no script.json to render.",{exitCode:k,errorCode:"VIEW_NO_SCRIPT",hint:"Run `scriptctl ingest --source-path <src> --workspace-path <dir>` first.",data:{actual:[n.path("script.json")]}});let o=n.has("manifest.json")?n.readJson("manifest.json"):null,i;if(o?.source?.kind==="comic-file"||o?.source?.kind==="comic-directory"){let s=n.readJson("manifest.json"),c=$i(n.readJson("script.json")),a=new Set;for(let p of c.episodes)for(let l of p.scenes)for(let f of l.actions){let u=ci.safeParse(f.extend);u.success&&a.add(u.data.scriptctl.source.document_id)}let d=[];n.passDir("src");for(let p of a){let l=s.episodes.find(m=>m.document_id===p);if(!l)throw new x(`Unknown comic source document: ${p}`,{exitCode:k,errorCode:"VIEW_COMIC_SOURCE_MISSING"});let f=n.path(`src/${l.document_id}.pdf`);Jo.rmSync(f,{force:!0}),Jo.symlinkSync(l.path,f);let u=await ha(l,n.root);d.push({id:l.document_id,title:l.title,pdf:`src/${l.document_id}.pdf`,images:u})}i=Ty(c,d)}else Ck(n),i=Uy(n.readJson("script.json"));n.writeText("review.html",i);let r=n.path("review.html");return[{text:r,data:{output:r}},G]}import*as Oi from"node:path";import Tk from"fast-json-patch";var{compare:$y}=Tk;var Dy="/api/anime/workbench/v2/script/project-groups",Vk="/api/anime/workbench/projectGroup/updateProjectGroupInfo",$k=5e3,Gy=8*1024*1024;function Dk(e){let t=e.trim().replace(/\/+$/,"");for(let n of["/api/anime/workbench","/api/sandbox"])if(t.endsWith(n)){t=t.slice(0,-n.length);break}return t.replace(/\/+$/,"")}function By(e){return encodeURIComponent(String(e))}function Gk(e,t,n){if(t===404&&n.includes("/imports"))return new fe("backend lacks episode import API",{status:t,payload:e});let o=null;try{o=e?JSON.parse(e):null}catch{o=null}if(o&&typeof o=="object"){let i=o,r=String(i.msg??i.message??`HTTP ${t}`);return new fe(r,{status:t,code:i.code??null,payload:i})}return new fe(e||`HTTP ${t}`,{status:t,payload:e})}function Jy(e,t){let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(!(n<=Gy))throw new fe(`script ${e} body too large: ${n} bytes (limit ${Gy})`)}async function Ky(e,t,n,o,i,r={}){let s=r.body===void 0?void 0:JSON.stringify(r.body),c={Accept:"application/json","X-Access-Key":t};s!==void 0&&(c["Content-Type"]="application/json; charset=utf-8");let a=new AbortController,d=setTimeout(()=>a.abort(),n),p,l;try{let h=await fetch(`${e}${i}`,{method:o,headers:c,body:s,signal:a.signal});p=h.status,l=await h.text()}catch(h){if(h instanceof Error&&h.name==="AbortError")throw new fe("Gateway request timed out");let g=h instanceof Error?h.message:String(h);throw new fe(`Gateway request failed: ${g}`)}finally{clearTimeout(d)}if(p>=400)throw Gk(l,p,i);let f=null;if(l)try{f=JSON.parse(l)}catch{throw new fe("Gateway response is not valid JSON",{status:p,payload:l})}if(f===null)return null;if(typeof f!="object")return f;let u=f,m=u.code;if(m!=null&&String(m)!=="200"){let h=String(u.msg??u.message??"script-output API failed");if(r.allowMissing&&typeof h=="string"&&h.includes("\u5267\u672C\u4E0D\u5B58\u5728"))return null;throw new fe(h,{status:p,code:m,payload:u})}return"data"in u?u.data:u}var vl=class e{gatewayBase;projectGroupNo;accessKey;timeoutMs;constructor(t){this.gatewayBase=t.gatewayBase,this.projectGroupNo=t.projectGroupNo,this.accessKey=t.accessKey,this.timeoutMs=t.timeoutMs??3e5}static fromEnv(t){let n=(t??process.env.SANDBOX_PROJECT_GROUP_NO??"").trim();if(!n)throw new fe("projectGroupNo missing; pass --project-group-no or set SANDBOX_PROJECT_GROUP_NO",{configMissing:"project"});let o=Dk(process.env.AWB_BASE_URL||"");if(!o)throw new fe("gateway URL missing; set AWB_BASE_URL",{configMissing:"gateway"});let i=(process.env.LINGJING_AWB_ACCESS_KEY||"").trim();if(!i)throw new fe("access key missing; set LINGJING_AWB_ACCESS_KEY",{configMissing:"access"});return new e({gatewayBase:o,projectGroupNo:n,accessKey:i})}get projectPrefix(){return`${Dy}/${By(this.projectGroupNo)}`}async getScript(){return await this.request("GET",this.projectPrefix,{allowMissing:!0})}async getRevision(){return await this.request("GET",`${this.projectPrefix}/revision`,{allowMissing:!0})}async getSnapshot(){return await this.request("GET",`${this.projectPrefix}/snapshot`,{allowMissing:!0})}async publishPatch(t){return await this.request("PATCH",`${this.projectPrefix}/publish`,{body:{baseRevision:t.baseRevision,patch:$y(t.old,t.edited),validation:t.validation}})}async replaceScript(t){let n={requestId:t.requestId,baseRevision:t.baseRevision,source:t.source??"ctl",script:t.script};return Jy("root",n),await this.request("PUT",this.projectPrefix,{body:n})}async patchScript(t){let n=$y(t.old,t.edited),o={requestId:t.requestId,baseRevision:t.baseRevision,source:t.source??"ctl",patch:n};return Jy("patch",o),await this.request("PATCH",this.projectPrefix,{body:o})}async saveValidationResult(t){return await this.request("POST",`${Dy}/${By(this.projectGroupNo)}/validation-result`,{body:{revision:t.revision,validationStatus:t.validationStatus,validationSummary:t.validationSummary,issues:t.issues}})}async updateEpisodeCount(t){await Ky(this.gatewayBase,this.accessKey,Math.min(this.timeoutMs,$k),"POST",Vk,{body:{projectGroupNo:this.projectGroupNo,episodeCount:t}})}async request(t,n,o={}){return Ky(this.gatewayBase,this.accessKey,this.timeoutMs,t,n,o)}};function Rl(e){return vl.fromEnv(e)}var ws=class{workspace;script;version;baseline;baselineHash;scriptPath;client;projectGroupNo;revision;constructor(t){this.workspace=t.workspace,this.script=t.script,this.version=Qo(t.script),this.baseline=structuredClone(t.script),this.baselineHash=Je(t.script),this.scriptPath=t.scriptPath??null,this.client=t.client??null,this.projectGroupNo=t.projectGroupNo??null,this.revision=t.revision??null}get remote(){return this.client!==null}get artifactLabel(){return this.remote?`script-output/${this.projectGroupNo}@revision/${this.revision??0}`:this.scriptPath??""}};function Ko(e,t){let n=t.message||"script-output API failed",o=String(t.code)==="9002"||n.includes("\u7248\u672C\u51B2\u7A81"),i=n.includes("\u5267\u672C\u4E0D\u5B58\u5728"),r=o?"Script has been updated by another revision; keep local work and merge before retrying.":i?"Script not found on the gateway.":"Gateway request failed.";return new x(r,{exitCode:t.status!==null&&t.status>=500?X:k,errorCode:o?"REVISION_CONFLICT":i?"SCRIPT_NOT_FOUND":"SCRIPT_API_FAILED",hint:o?"Keep the local file, inspect the latest remote snapshot, and merge before publishing again.":i?"Run `scriptctl publish` to publish a script first.":"Run `scriptctl doctor` to verify gateway configuration; retry if it was transient.",data:{expected:["successful script-output gateway request"],actual:[n,`status: ${t.status??"<unknown>"}`]}})}async function _s(e){let t=O(e.workspace_path||"workspace"),n=me(e);if(!zo(n))throw new x("Local script file not found.",{exitCode:k,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[n]}});let o;try{o=Ir(n)}catch(i){throw new x("script JSON invalid.",{exitCode:k,errorCode:"SCRIPT_JSON_INVALID",hint:"Fix the local script JSON syntax before editing.",data:{expected:["valid JSON"],actual:[`${n}: ${i.message}`]}})}if(!oe(o))throw new x("script root invalid.",{exitCode:B,errorCode:"SCRIPT_ROOT_INVALID",hint:"Use a valid script document object.",data:{expected:["script root object"],actual:[Array.isArray(o)?"array":typeof o]}});return new ws({workspace:t,scriptPath:n,script:o})}function Es(e,t={}){let n=Ml(e.script);return e.remote&&(n.script_path=e.artifactLabel),n}function Bk(e,t){let{ok:n,errors:o,warnings:i}=t,r=[...o.map(d=>({severity:"error",code:d.code,path:d.path,summary:d.message,...d.repair_hint?{repair_hint:d.repair_hint}:{}})),...i.map(d=>({severity:"warning",code:d.code,path:d.path,summary:d.message,...d.repair_hint?{repair_hint:d.repair_hint}:{}}))],s=re(e.episodes),c=0,a=0;for(let d of s)for(let p of re(d.scenes))c+=1,a+=re(p.actions).length;return{passed:n,has_blocking:!n,issues:r,stats:{actors:re(e.actors).length,locations:re(e.locations).length,props:re(e.props).length,episodes:s.length,scenes:c,actions:a}}}function Ml(e){return Bk(e,Lr(e))}function Jk(e){if(e.path)return O(e.path);let t=[];return e.episode!==null&&e.episode!==void 0&&t.push(O(e.episode)),e.scene!==null&&e.scene!==void 0&&t.push(O(e.scene)),e.action_index!==null&&e.action_index!==void 0&&t.push(`action[${e.action_index}]`),t.length>0?t.join("/"):null}function Kk(e){let t=O(e||"info");return t==="blocking"||t==="error"?"error":t==="warning"?"warning":"info"}function jk(e){let t=re(e.issues),n=e.passed?"valid":"invalid",o={passed:!!e.passed,hasBlocking:!!e.has_blocking,stats:e.stats??{},issueCount:t.length},i=[];for(let r of t){if(!oe(r))continue;let s={...r};for(let c of["severity","code","path","summary","repair_hint"])delete s[c];i.push({severity:Kk(r.severity),code:O(r.code||"SCRIPT_VALIDATION_ISSUE"),path:Jk(r),summary:O(r.summary),repairHint:r.repair_hint,payload:s})}return[n,o,i]}async function Nl(e,t,n){if(!e.remote||e.client===null)return;let o=Number(n??e.revision??0);if(o<=0)return;let[i,r,s]=jk(t);try{await e.client.saveValidationResult({revision:o,validationStatus:i,validationSummary:r,issues:s})}catch(c){throw c instanceof fe?Ko("SCRIPT API BLOCKED: Validation sync failed",c):c}}async function Ll(e,t,n){if(e.scriptPath===null)throw new Error("local script session missing script path");return Gt(e.scriptPath,e.baselineHash),Fe(e.scriptPath,e.script),[null,!1]}async function jy(e,t=Xn){let n=await _s(e),o=t.createExecutor(O(e.llm_config).trim()||void 0),i=await Wp(n.script,o);n.scriptPath&&Gt(n.scriptPath,n.baselineHash);let r=n.scriptPath?Oi.dirname(n.scriptPath):Oi.resolve(n.workspace),s=Oi.resolve(O(e.output).trim()||Oi.join(r,"asset-audit.json"));Fe(s,i);let c=i.issues.length>0,a=i.issues.map(Xp);return[{text:[`${i.summary.issues} issues; confidence high=${i.summary.high} medium=${i.summary.medium} low=${i.summary.low}`,...a,`output: ${s}`,...c?["Inspect each finding, repair confirmed duplicates, then rerun `scriptctl audit-assets` and `scriptctl validate`."]:[]].join(`
1014
+ `),data:{op:"script.audit-assets",changed:!1,issues:i.issues,output:s,asset_audit:i,config_source:o.configSource,llm_routes:o.usage()}},c?po:G]}function zy(e=""){return{version:4,title:e,worldview:"",style:"",actors:[],locations:[],props:[],episodes:[]}}function jo(e){let t=oe(e.location)?e.location:null;return{actors:Bn(e.actors)?e.actors:[],props:Bn(e.props)?e.props:[],locations:t&&String(t.location_id??"").trim()?[t]:[]}}function ew(e,t,n){let o=!!t.passed,i=[`created: blank script (Script v${e.version})`,`validation: ${o?"passed":"needs repair"}`];return e.remote&&(i.push(`revision: ${e.revision}`),n!==null&&i.push(`idempotent: ${String(n).toLowerCase()}`)),{text:i.join(`
1015
+ `),data:{op:"script.create",changed:!0,validation:t,script_path:e.artifactLabel,...e.remote?{revision:e.revision,idempotent:n}:{}}}}async function tw(e){let t=O(e.workspace_path||"workspace"),n=!!e.force,o=O(e.title).trim(),i=zy(o),r=me(e);if(zo(r)&&!n)throw new x("A script already exists at the target.",{exitCode:k,errorCode:"SCRIPT_EXISTS",hint:"Edit the existing script with the atomic verbs, or pass --force to overwrite with a blank scaffold.",data:{expected:["a non-existent target, or --force to overwrite"],actual:[r]}});Fe(r,i);let s=new ws({workspace:t,scriptPath:r,script:i}),c=Es(s),a=!!c.passed;return[ew(s,c,null),a?G:po]}import*as _r from"node:fs";import*as Ri from"node:path";function ib(e){let t={};for(let n of e.episodes)for(let o of n.scenes){let i=`${n.episode_id}/${o.scene_id}`;o.actions.forEach((r,s)=>{let c=`${i}#${s}`;t[c]=c})}return t}function vi(e){return oe(e)&&Object.values(e).every(t=>typeof t=="string")}function rb(e){return oe(e)&&Object.values(e).every(vi)}function sb(e){return oe(e)&&e.version===3&&vi(e.actor)&&vi(e.location)&&vi(e.prop)&&rb(e.state)&&vi(e.episode)&&vi(e.scene)&&vi(e.action)}function ab(e){if(e!==void 0){if(sb(e.identityMap))return e.identityMap;throw new x("Migration manifest contains an invalid v3-to-v4 identity map.",{exitCode:k,errorCode:"MIGRATE_MANIFEST_INVALID"})}}function nw(e,t){let n=Tt(e),o=ar(n,ab(t),{action:ib(n)});return{script:o.script,artifact:{sourceVersion:3,targetVersion:4,identityMap:o.identityMap}}}var cb=[{sourceVersion:3,targetVersion:4,migrate:nw}];function db(e){return oe(e)&&go(e.source_version)&&go(e.target_version)&&e.source_version<e.target_version&&"identity_map"in e}function ow(e){if(!Array.isArray(e))throw new x("Migration manifest steps must be an array.",{exitCode:k,errorCode:"MIGRATE_MANIFEST_INVALID"});return e.map(t=>{if(!db(t))throw new x("Migration manifest contains an invalid step artifact.",{exitCode:k,errorCode:"MIGRATE_MANIFEST_INVALID"});return{sourceVersion:t.source_version,targetVersion:t.target_version,identityMap:t.identity_map}})}function pb(e,t){return cb.find(n=>n.sourceVersion===e&&n.targetVersion<=t)}function lb(e,t){return e.find(n=>n.sourceVersion===t.sourceVersion&&n.targetVersion===t.targetVersion)}function iw(e,t,n=[]){let o=Qo(e);if(t<o)throw new x("A migration target must be newer than the source script.",{exitCode:k,errorCode:"MIGRATE_TARGET_OLDER",data:{expected:[String(o)],actual:[String(t)]}});let i=Bs(e),r=o,s=[];for(;r<t;){let c=pb(r,t);if(c===void 0)throw new x(`No migration path exists from Script v${r} to Script v${t}.`,{exitCode:k,errorCode:"MIGRATE_PATH_UNSUPPORTED",data:{actual:[String(r),String(t)]}});let a=c.migrate(i,lb(n,c));i=a.script,r=c.targetVersion,s.push(a.artifact)}return{sourceVersion:o,targetVersion:t,script:i,steps:s}}function xs(e,t){let n=e[t];return typeof n=="string"?n.trim():""}function ub(e,t){let n=xs(e,t);return/^\d+$/.test(n)?Number(n):null}function fb(e){let t=ub(e,"to");if(go(t))return t;throw new x("A supported migration target version is required.",{exitCode:B,errorCode:"MIGRATE_TARGET_INVALID",hint:"Pass --to <version> with a supported Script version.",data:{expected:Fc.map(String),actual:[xs(e,"to")||"<empty>"]}})}function mb(e){let t=Ri.extname(e);return`${t.length>0?e.slice(0,-t.length):e}.migration.json`}function gb(e,t,n){let o=[e,t,n].map(i=>Ri.resolve(i));if(o[0]===o[1])throw new x("The migration destination must differ from the source.",{exitCode:B,errorCode:"MIGRATE_SAME_PATH",hint:"Choose a separate --output path. The source file stays unchanged.",data:{actual:[e]}});if(o[0]===o[2]||o[1]===o[2])throw new x("The migration manifest needs its own file path.",{exitCode:B,errorCode:"MIGRATE_MANIFEST_PATH",hint:"Choose a --manifest path separate from the source and output files.",data:{actual:[n]}})}function rw(e,t){if(!t&&_r.existsSync(e))throw new x("Migration destination already exists.",{exitCode:B,errorCode:"MIGRATE_OUTPUT_EXISTS",hint:"Choose a new path, or pass --force to replace the migration artifact.",data:{actual:[e]}})}function hb(e){let t;try{t=_r.readFileSync(e,"utf8")}catch(n){throw new x("Cannot read the source script.",{exitCode:B,errorCode:"MIGRATE_SOURCE_READ_FAILED",hint:"Pass an existing JSON file with --script-path.",data:{actual:[e,n instanceof Error?n.message:String(n)]}})}try{return{raw:t,value:JSON.parse(t)}}catch(n){throw new x("The source script is not valid JSON.",{exitCode:B,errorCode:"MIGRATE_SOURCE_JSON_INVALID",hint:"Repair the JSON syntax, then rerun migrate.",data:{actual:[n instanceof Error?n.message:String(n)]}})}}function yb(e,t){if(!t||!_r.existsSync(e))return;let n;try{n=JSON.parse(_r.readFileSync(e,"utf8"))}catch(o){throw new x("Cannot reuse the existing migration manifest.",{exitCode:B,errorCode:"MIGRATE_MANIFEST_INVALID",hint:"Restore the migration manifest, or choose a new --manifest path.",data:{actual:[e,o instanceof Error?o.message:String(o)]}})}if(!oe(n)||n.version!==1||!go(n.source_version)||!go(n.target_version)||typeof n.source_path!="string"||typeof n.source_sha256!="string")throw new x("Cannot reuse the existing migration manifest.",{exitCode:B,errorCode:"MIGRATE_MANIFEST_INVALID",hint:"Restore the migration manifest, or choose a new --manifest path.",data:{actual:[e]}});return{version:1,source_version:n.source_version,target_version:n.target_version,source_path:n.source_path,source_sha256:n.source_sha256,steps:ow(n.steps)}}async function sw(e){let t=xs(e,"script_path"),n=xs(e,"output");if(!t||!n)throw new x("Migration paths are required.",{exitCode:B,errorCode:"MIGRATE_PATH_MISSING",hint:"Pass --script-path <source.json> and --output <target.json>.",data:{expected:["--script-path <source.json>","--output <target.json>"]}});let o=Ri.resolve(t),i=Ri.resolve(n),r=Ri.resolve(xs(e,"manifest")||mb(i)),s=fb(e),c=!!e.force;return gb(o,i,r),Vs(i,async()=>{rw(i,c),rw(r,c);let a=hb(o),d=Qo(a.value);if(s<=d)throw new x("The migration target must be newer than the source script.",{exitCode:B,errorCode:"MIGRATE_TARGET_NOT_NEWER",data:{expected:[`>${d}`],actual:[String(s)]}});let p=Lr(a.value),l=yb(r,c),f=iw(a.value,s,l?.steps),u=Lr(f.script),m={version:1,source_version:f.sourceVersion,target_version:f.targetVersion,source_path:o,source_sha256:_e(a.raw),steps:f.steps};Fe(r,{...m,steps:m.steps.map(w=>({source_version:w.sourceVersion,target_version:w.targetVersion,identity_map:w.identityMap}))}),Fe(i,f.script);let h={op:"script.migrate",changed:!0,source_script_path:o,script_path:i,manifest_path:r,source_version:f.sourceVersion,target_version:f.targetVersion,source_validation:{ok:p.ok,errors:p.errors.length,warnings:p.warnings.length},validation:{ok:u.ok,errors:u.errors.length,warnings:u.warnings.length,issues:u.errors.slice(0,100)}};return[{text:u.ok?[`Script v${f.targetVersion}: ${i}`,`Migration manifest: ${r}`,"validation: ok"].join(`
1014
1016
  `):[`Script v${f.targetVersion}: ${i}`,`Migration manifest: ${r}`,`validation: ${u.errors.length} errors; repair before production use`].join(`
1015
- `),data:h},u.ok?B:co]})}import*as wr from"node:path";import*as rw from"node:path";function iw(e,t){let n=Ee(t);return rw.join(e,`${n}.json`)}function xs(e){return{read(t){let n=iw(e,t);return zo(n)?xr(n):null},write(t){Sc(iw(e,t.key),t)}}}function $l(){return{read(){return null},write(){}}}function Dl(e){if(Array.isArray(e))return`[${e.map(t=>Dl(t)).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Dl(t[n])}`).join(",")}}`}return JSON.stringify(e)}function Gl(e){return Ee(Dl(e))}function Bl(e,t,n){return{key:e,signature:t,value:n,createdAt:new Date().toISOString()}}function yb(e,t){return[e.trim(),t.trim()].filter(Boolean).join(`
1017
+ `),data:h},u.ok?G:po]})}import*as Er from"node:path";import*as cw from"node:path";function aw(e,t){let n=_e(t);return cw.join(e,`${n}.json`)}function Ss(e){return{read(t){let n=aw(e,t);return zo(n)?Ir(n):null},write(t){Ac(aw(e,t.key),t)}}}function Gl(){return{read(){return null},write(){}}}function Bl(e){if(Array.isArray(e))return`[${e.map(t=>Bl(t)).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Bl(t[n])}`).join(",")}}`}return JSON.stringify(e)}function Jl(e){return _e(Bl(e))}function Kl(e,t,n){return{key:e,signature:t,value:n,createdAt:new Date().toISOString()}}function wb(e,t){return[e.trim(),t.trim()].filter(Boolean).join(`
1016
1018
 
1017
- `)}function aw(e,t){return{system:yb(e.instruction,e.format),user:e.input?e.input({parcel:t}):String(t)}}function wb(e,t,n){if(e.kind==="llm"){if(!n.executor)throw new Error("loom llm task requires run({ executor })");let o=aw(e,t),i=n.executor.route(e.taskId);return{request:o,payload:{step:"extract",kind:"llm",taskId:e.taskId,version:e.version??"",routeFingerprint:i.fingerprint,system:o.system,user:o.user,salt:n.checkpointSalt}}}return{payload:{step:"extract",kind:"fn",version:e.version??"",parcel:t,salt:n.checkpointSalt}}}function pc(e){return{kind:"root",children:e}}function zl(e,t,n){return{kind:"scope",scope:e,data:n,children:t}}function Ss(e){return{kind:"parcel",data:e}}function As(e){return{kind:"llm",...e}}var Jl=class e{constructor(t,n=[]){this.input=t;this.steps=n}input;steps;split(t){return new e(this.input,[...this.steps,{kind:"split",spec:t}])}extract(t){return new e(this.input,[...this.steps,{kind:"extract",task:t}])}reduce(t,n){let o=typeof n=="function"?{run:n}:n;return new e(this.input,[...this.steps,{kind:"reduce",scope:t,task:o}])}plan(){return{input:this.input,steps:[...this.steps]}}async run(t={}){return await Ab(this.input,this.steps,t)}};function lc(e){return new Jl(e)}async function _b(e,t,n){if(e.length===0)return[];let o=new Array(e.length),i=0,r=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:r},async()=>{for(;;){let s=i++;if(s>=e.length)break;o[s]=await n(e[s],s)}})),o}function Eb(e,t){let n=t.partition(e);return pc(n.map(o=>{let i=t.chunk(o).map(r=>Ss(r));return zl(t.scope,i,o)}))}function jl(e,t=[]){if(e.kind==="parcel")return[{parcel:e.data,path:t}];let n=(e.kind==="root",e.children),o=[];for(let i=0;i<n.length;i++){let r=n[i],s=r.kind==="scope"?[...t,`${r.scope}:${i}`]:[...t,`parcel:${i}`];o.push(...jl(r,s))}return o}function Is(e,t){return e?.(t),t}async function xb(e,t){return Is(e.validate,await e.run({parcel:t}))}async function Sb(e,t,n){if(!n.executor)throw new Error("loom llm task requires run({ executor })");return n.executor.generateText(e.taskId,{system:t.system,user:t.user,signal:n.signal})}function sw(e,t,n){return Is(e.validate,e.parse({text:n.text,parcel:t,raw:n.raw}))}function cw(e,t,n){if(e.kind==="parcel"){let i=t[n.index];return n.index+=1,Ss(i)}let o=e.children.map(i=>cw(i,t,n));return e.kind==="root"?pc(o):zl(e.scope,o,e.data)}function Ib(e){return e.children.every(t=>t.kind==="parcel")}async function dw(e,t,n,o,i){if(e.kind==="parcel")return e;let r=[];for(let w=0;w<e.children.length;w++){let y=e.children[w];r.push(await dw(y,t,n,o,[...i,`${y.kind}:${w}`]))}let s=e.kind==="root"?pc(r):zl(e.scope,r,e.data),c=t==="root"&&s.kind==="root",a=s.kind==="scope"&&s.scope===t;if(!c&&!a||!Ib(s))return s;let d=s.children.map(w=>w.data),p=s.kind==="scope"?s.data:null,l=s.kind==="scope"?s.scope:"root",f=n.version??"",u=`reduce:${t}:${i.join("/")}:${Gl({items:d,scopeData:p,version:f,salt:o.checkpointSalt})}`,g=Gl({step:"reduce",scope:t,version:f,items:d,scopeData:p,salt:o.checkpointSalt}),h=await Kl(o.checkpoint,u,g);if(h.hit)return o.report.reused+=1,Ss(Is(n.validate,h.value));let m=Is(n.validate,await n.run(d,{scope:p,scopeName:l}));return o.report.ran+=1,await o.checkpoint.write(Bl(u,g,m)),Ss(m)}async function Kl(e,t,n){let o=await e.read(t);return o&&o.signature===n?{hit:!0,value:o.value}:{hit:!1}}async function Ab(e,t,n){let o={executor:n.executor,signal:n.signal,checkpointSalt:n.checkpointSalt,checkpoint:n.checkpoint??$l(),concurrency:n.concurrency??4,report:{reused:0,ran:0}},i=null,r=e;for(let c of t){if(c.kind==="split"){i=Eb(r,c.spec),r=i;continue}if(i||(i=pc([Ss(r)])),c.kind==="extract"){let a=jl(i),d=await _b(a,o.concurrency,async p=>{let l=wb(c.task,p.parcel,o),f=Gl(l.payload),u=`extract:${p.path.join("/")}:${f}`;if(c.task.kind==="llm"){let m=await Kl(o.checkpoint,u,f);if(m.hit)return o.report.reused+=1,o.executor?.recordReuse(c.task.taskId),sw(c.task,p.parcel,m.value);let w=l.request??aw(c.task,p.parcel),y=await Sb(c.task,w,o),_=sw(c.task,p.parcel,y);return o.report.ran+=1,await o.checkpoint.write(Bl(u,f,y)),_}let g=await Kl(o.checkpoint,u,f);if(g.hit)return o.report.reused+=1,Is(c.task.validate,g.value);let h=await xb(c.task,p.parcel);return o.report.ran+=1,await o.checkpoint.write(Bl(u,f,h)),h});i=cw(i,d,{index:0}),r=i;continue}i=await dw(i,c.scope,c.task,o,[]),r=i}if(!i)return{value:r,report:o.report};let s=jl(i);if(s.length!==1)throw new Error(`loom plan ended with ${s.length} result(s); reduce to root before run completes`);return{value:s[0].parcel,report:o.report}}var uw={episodeInputMaxChars:6e3,episodeChunkTargetChars:4800,arcEpisodeCount:10,finalMaxInputChars:12e3},kb="\u4ECE\u5F53\u524D\u5267\u672C\u7247\u6BB5\u4E2D\u63D0\u53D6\u5267\u60C5\u6897\u6982\u548C\u5173\u952E\u4E8B\u4EF6\u3002\u53EA\u57FA\u4E8E\u5F53\u524D\u7247\u6BB5\uFF0C\u4E0D\u8981\u63A8\u6D4B\u540E\u7EED\u3002",bb=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u7247\u6BB5\u6897\u6982","<\u5982\u679C\u5F53\u524D\u96C6\u53EA\u6709\u4E00\u4E2A\u7247\u6BB5\uFF0C\u5199 200-300 \u5B57\uFF1B\u5982\u679C\u5F53\u524D\u96C6\u88AB\u5207\u6210\u591A\u4E2A\u7247\u6BB5\uFF0C\u5199 80-150 \u5B57\u3002\u6309\u53D1\u751F\u987A\u5E8F\u6982\u62EC\uFF0C\u53EA\u5199\u5F53\u524D\u7247\u6BB5\u3002>","","## \u5173\u952E\u4E8B\u4EF6","- <\u4E8B\u4EF61>","- <\u4E8B\u4EF62>","","## \u4EBA\u7269\u53D8\u5316","- <\u4EBA\u7269\u540D> | <\u53D8\u5316>","","## \u7ED3\u5C3E\u94A9\u5B50","<\u6709\u5219\u5199\u4E00\u53E5\uFF1B\u6CA1\u6709\u5219\u7559\u7A7A>"].join(`
1018
- `),Ob="\u628A\u540C\u4E00\u96C6\u7684\u591A\u4E2A\u7247\u6BB5\u6897\u6982\u5408\u5E76\u4E3A\u4E00\u96C6\u6897\u6982\u3002\u53EA\u4F7F\u7528\u8F93\u5165\u7247\u6BB5\uFF0C\u4E0D\u8981\u65B0\u589E\u5267\u60C5\u3002",vb=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u5206\u96C6\u6897\u6982","<200-300 \u5B57\uFF0C\u6309\u5267\u60C5\u53D1\u751F\u987A\u5E8F\u5199\u6210\u8FDE\u8D2F\u6BB5\u843D\u3002>","","## \u5355\u53E5\u6897\u6982","<30-50 \u5B57\uFF0C\u6982\u62EC\u672C\u96C6\u4E3B\u7EBF\u3002>","","## \u5173\u952E\u4E8B\u4EF6","- <\u4E8B\u4EF61>","- <\u4E8B\u4EF62>"].join(`
1019
- `),Rb="\u628A\u4E00\u7EC4\u8FDE\u7EED\u5206\u96C6\u6897\u6982\u538B\u7F29\u4E3A\u9636\u6BB5\u6897\u6982\u3002\u53EA\u4F7F\u7528\u8F93\u5165\u5206\u96C6\uFF0C\u4E0D\u8981\u65B0\u589E\u5267\u60C5\u3002",Mb=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u9636\u6BB5\u6897\u6982","<400-600 \u5B57\uFF0C\u6982\u62EC\u8FD9\u4E00\u9636\u6BB5\u7684\u4E3B\u7EBF\u63A8\u8FDB\u3002>","","## \u5173\u952E\u8F6C\u6298","- <\u8F6C\u62981>","- <\u8F6C\u62982>","","## \u672A\u89E3\u51B3\u60AC\u5FF5","- <\u60AC\u5FF51>"].join(`
1020
- `),Nb="\u6839\u636E\u5206\u96C6\u7D22\u5F15\u548C\u9636\u6BB5\u6897\u6982\u751F\u6210\u5168\u5267\u603B\u89C8\u3002\u53EA\u4F7F\u7528\u8F93\u5165\u5185\u5BB9\uFF0C\u4E0D\u8981\u65B0\u589E\u5267\u60C5\u3001\u4EBA\u7269\u6216\u5173\u7CFB\u3002",Lb=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u5168\u6587\u6897\u6982","<800-1200 \u5B57\uFF0C\u8986\u76D6\u5168\u5267\u4E3B\u7EBF\u3001\u5173\u952E\u5173\u7CFB\u3001\u4E3B\u8981\u51B2\u7A81\u548C\u7ED3\u5C40\u8D70\u5411\u3002>","","## \u4E3B\u9898","<\u4E00\u53E5\u8BDD\u6216\u4E00\u4E2A\u77ED\u8BED>","","## \u4E00\u53E5\u8BDD","<\u4E00\u53E5\u5B8C\u6574 logline>","","## \u98CE\u683C","<\u7C7B\u578B / \u6C14\u8D28 / \u53D9\u4E8B\u98CE\u683C>","","## \u4E3B\u8981\u4EBA\u7269","- <\u540D\u5B57> | <\u89D2\u8272\u5B9A\u4F4D>"].join(`
1021
- `);function Ub(e,t,n){let o=v(t.episode_id).trim()||`ep_${String(n+1).padStart(3,"0")}`,i=Yb(o,n),r=v(t.title).trim(),s=[],c=v(e.title).trim();c&&s.push(`\u5267\u540D\uFF1A${c}`),s.push(`\u96C6\u6570\uFF1A\u7B2C${i}\u96C6`),r&&s.push(`\u6807\u9898\uFF1A${r}`),s.push("");for(let a of re(t.scenes)){s.push(Fb(e,a));for(let d of re(a.actions)){let p=Qb(e,d);p&&s.push(p)}s.push("")}return{episodeIndex:n,episodeId:o,episodeNo:i,title:r,existingSynopsis:v(t.synopsis).trim(),text:s.join(`
1022
- `).trim()}}function Pb(e,t=uw){let n=e.text.split(/\r?\n/),o=n.flatMap(c=>Kb(c,t.episodeChunkTargetChars));if(e.text.length<=t.episodeInputMaxChars&&o.length===n.length)return[{episodeIndex:e.episodeIndex,episodeId:e.episodeId,episodeNo:e.episodeNo,title:e.title,part:1,partCount:1,text:e.text,sourceHash:Ee(e.text)}];let i=[],r=[],s=0;for(let c of o){let a=c.length+(r.length>0?1:0);r.length>0&&s+a>t.episodeChunkTargetChars&&(i.push(r.join(`
1019
+ `)}function pw(e,t){return{system:wb(e.instruction,e.format),user:e.input?e.input({parcel:t}):String(t)}}function _b(e,t,n){if(e.kind==="llm"){if(!n.executor)throw new Error("loom llm task requires run({ executor })");let o=pw(e,t),i=n.executor.route(e.taskId);return{request:o,payload:{step:"extract",kind:"llm",taskId:e.taskId,version:e.version??"",routeFingerprint:i.fingerprint,system:o.system,user:o.user,salt:n.checkpointSalt}}}return{payload:{step:"extract",kind:"fn",version:e.version??"",parcel:t,salt:n.checkpointSalt}}}function uc(e){return{kind:"root",children:e}}function Fl(e,t,n){return{kind:"scope",scope:e,data:n,children:t}}function Is(e){return{kind:"parcel",data:e}}function ks(e){return{kind:"llm",...e}}var jl=class e{constructor(t,n=[]){this.input=t;this.steps=n}input;steps;split(t){return new e(this.input,[...this.steps,{kind:"split",spec:t}])}extract(t){return new e(this.input,[...this.steps,{kind:"extract",task:t}])}reduce(t,n){let o=typeof n=="function"?{run:n}:n;return new e(this.input,[...this.steps,{kind:"reduce",scope:t,task:o}])}plan(){return{input:this.input,steps:[...this.steps]}}async run(t={}){return await kb(this.input,this.steps,t)}};function fc(e){return new jl(e)}async function Eb(e,t,n){if(e.length===0)return[];let o=new Array(e.length),i=0,r=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:r},async()=>{for(;;){let s=i++;if(s>=e.length)break;o[s]=await n(e[s],s)}})),o}function xb(e,t){let n=t.partition(e);return uc(n.map(o=>{let i=t.chunk(o).map(r=>Is(r));return Fl(t.scope,i,o)}))}function zl(e,t=[]){if(e.kind==="parcel")return[{parcel:e.data,path:t}];let n=(e.kind==="root",e.children),o=[];for(let i=0;i<n.length;i++){let r=n[i],s=r.kind==="scope"?[...t,`${r.scope}:${i}`]:[...t,`parcel:${i}`];o.push(...zl(r,s))}return o}function As(e,t){return e?.(t),t}async function Sb(e,t){return As(e.validate,await e.run({parcel:t}))}async function Ib(e,t,n){if(!n.executor)throw new Error("loom llm task requires run({ executor })");return n.executor.generateText(e.taskId,{system:t.system,user:t.user,signal:n.signal})}function dw(e,t,n){return As(e.validate,e.parse({text:n.text,parcel:t,raw:n.raw}))}function lw(e,t,n){if(e.kind==="parcel"){let i=t[n.index];return n.index+=1,Is(i)}let o=e.children.map(i=>lw(i,t,n));return e.kind==="root"?uc(o):Fl(e.scope,o,e.data)}function Ab(e){return e.children.every(t=>t.kind==="parcel")}async function uw(e,t,n,o,i){if(e.kind==="parcel")return e;let r=[];for(let w=0;w<e.children.length;w++){let y=e.children[w];r.push(await uw(y,t,n,o,[...i,`${y.kind}:${w}`]))}let s=e.kind==="root"?uc(r):Fl(e.scope,r,e.data),c=t==="root"&&s.kind==="root",a=s.kind==="scope"&&s.scope===t;if(!c&&!a||!Ab(s))return s;let d=s.children.map(w=>w.data),p=s.kind==="scope"?s.data:null,l=s.kind==="scope"?s.scope:"root",f=n.version??"",u=`reduce:${t}:${i.join("/")}:${Jl({items:d,scopeData:p,version:f,salt:o.checkpointSalt})}`,m=Jl({step:"reduce",scope:t,version:f,items:d,scopeData:p,salt:o.checkpointSalt}),h=await Hl(o.checkpoint,u,m);if(h.hit)return o.report.reused+=1,Is(As(n.validate,h.value));let g=As(n.validate,await n.run(d,{scope:p,scopeName:l}));return o.report.ran+=1,await o.checkpoint.write(Kl(u,m,g)),Is(g)}async function Hl(e,t,n){let o=await e.read(t);return o&&o.signature===n?{hit:!0,value:o.value}:{hit:!1}}async function kb(e,t,n){let o={executor:n.executor,signal:n.signal,checkpointSalt:n.checkpointSalt,checkpoint:n.checkpoint??Gl(),concurrency:n.concurrency??4,report:{reused:0,ran:0}},i=null,r=e;for(let c of t){if(c.kind==="split"){i=xb(r,c.spec),r=i;continue}if(i||(i=uc([Is(r)])),c.kind==="extract"){let a=zl(i),d=await Eb(a,o.concurrency,async p=>{let l=_b(c.task,p.parcel,o),f=Jl(l.payload),u=`extract:${p.path.join("/")}:${f}`;if(c.task.kind==="llm"){let g=await Hl(o.checkpoint,u,f);if(g.hit)return o.report.reused+=1,o.executor?.recordReuse(c.task.taskId),dw(c.task,p.parcel,g.value);let w=l.request??pw(c.task,p.parcel),y=await Ib(c.task,w,o),_=dw(c.task,p.parcel,y);return o.report.ran+=1,await o.checkpoint.write(Kl(u,f,y)),_}let m=await Hl(o.checkpoint,u,f);if(m.hit)return o.report.reused+=1,As(c.task.validate,m.value);let h=await Sb(c.task,p.parcel);return o.report.ran+=1,await o.checkpoint.write(Kl(u,f,h)),h});i=lw(i,d,{index:0}),r=i;continue}i=await uw(i,c.scope,c.task,o,[]),r=i}if(!i)return{value:r,report:o.report};let s=zl(i);if(s.length!==1)throw new Error(`loom plan ended with ${s.length} result(s); reduce to root before run completes`);return{value:s[0].parcel,report:o.report}}var gw={episodeInputMaxChars:6e3,episodeChunkTargetChars:4800,arcEpisodeCount:10,finalMaxInputChars:12e3},bb="\u4ECE\u5F53\u524D\u5267\u672C\u7247\u6BB5\u4E2D\u63D0\u53D6\u5267\u60C5\u6897\u6982\u548C\u5173\u952E\u4E8B\u4EF6\u3002\u53EA\u57FA\u4E8E\u5F53\u524D\u7247\u6BB5\uFF0C\u4E0D\u8981\u63A8\u6D4B\u540E\u7EED\u3002",Ob=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u7247\u6BB5\u6897\u6982","<\u5982\u679C\u5F53\u524D\u96C6\u53EA\u6709\u4E00\u4E2A\u7247\u6BB5\uFF0C\u5199 200-300 \u5B57\uFF1B\u5982\u679C\u5F53\u524D\u96C6\u88AB\u5207\u6210\u591A\u4E2A\u7247\u6BB5\uFF0C\u5199 80-150 \u5B57\u3002\u6309\u53D1\u751F\u987A\u5E8F\u6982\u62EC\uFF0C\u53EA\u5199\u5F53\u524D\u7247\u6BB5\u3002>","","## \u5173\u952E\u4E8B\u4EF6","- <\u4E8B\u4EF61>","- <\u4E8B\u4EF62>","","## \u4EBA\u7269\u53D8\u5316","- <\u4EBA\u7269\u540D> | <\u53D8\u5316>","","## \u7ED3\u5C3E\u94A9\u5B50","<\u6709\u5219\u5199\u4E00\u53E5\uFF1B\u6CA1\u6709\u5219\u7559\u7A7A>"].join(`
1020
+ `),vb="\u628A\u540C\u4E00\u96C6\u7684\u591A\u4E2A\u7247\u6BB5\u6897\u6982\u5408\u5E76\u4E3A\u4E00\u96C6\u6897\u6982\u3002\u53EA\u4F7F\u7528\u8F93\u5165\u7247\u6BB5\uFF0C\u4E0D\u8981\u65B0\u589E\u5267\u60C5\u3002",Rb=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u5206\u96C6\u6897\u6982","<200-300 \u5B57\uFF0C\u6309\u5267\u60C5\u53D1\u751F\u987A\u5E8F\u5199\u6210\u8FDE\u8D2F\u6BB5\u843D\u3002>","","## \u5355\u53E5\u6897\u6982","<30-50 \u5B57\uFF0C\u6982\u62EC\u672C\u96C6\u4E3B\u7EBF\u3002>","","## \u5173\u952E\u4E8B\u4EF6","- <\u4E8B\u4EF61>","- <\u4E8B\u4EF62>"].join(`
1021
+ `),Mb="\u628A\u4E00\u7EC4\u8FDE\u7EED\u5206\u96C6\u6897\u6982\u538B\u7F29\u4E3A\u9636\u6BB5\u6897\u6982\u3002\u53EA\u4F7F\u7528\u8F93\u5165\u5206\u96C6\uFF0C\u4E0D\u8981\u65B0\u589E\u5267\u60C5\u3002",Nb=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u9636\u6BB5\u6897\u6982","<400-600 \u5B57\uFF0C\u6982\u62EC\u8FD9\u4E00\u9636\u6BB5\u7684\u4E3B\u7EBF\u63A8\u8FDB\u3002>","","## \u5173\u952E\u8F6C\u6298","- <\u8F6C\u62981>","- <\u8F6C\u62982>","","## \u672A\u89E3\u51B3\u60AC\u5FF5","- <\u60AC\u5FF51>"].join(`
1022
+ `),Lb="\u6839\u636E\u5206\u96C6\u7D22\u5F15\u548C\u9636\u6BB5\u6897\u6982\u751F\u6210\u5168\u5267\u603B\u89C8\u3002\u53EA\u4F7F\u7528\u8F93\u5165\u5185\u5BB9\uFF0C\u4E0D\u8981\u65B0\u589E\u5267\u60C5\u3001\u4EBA\u7269\u6216\u5173\u7CFB\u3002",Ub=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u5168\u6587\u6897\u6982","<800-1200 \u5B57\uFF0C\u8986\u76D6\u5168\u5267\u4E3B\u7EBF\u3001\u5173\u952E\u5173\u7CFB\u3001\u4E3B\u8981\u51B2\u7A81\u548C\u7ED3\u5C40\u8D70\u5411\u3002>","","## \u4E3B\u9898","<\u4E00\u53E5\u8BDD\u6216\u4E00\u4E2A\u77ED\u8BED>","","## \u4E00\u53E5\u8BDD","<\u4E00\u53E5\u5B8C\u6574 logline>","","## \u98CE\u683C","<\u7C7B\u578B / \u6C14\u8D28 / \u53D9\u4E8B\u98CE\u683C>","","## \u4E3B\u8981\u4EBA\u7269","- <\u540D\u5B57> | <\u89D2\u8272\u5B9A\u4F4D>"].join(`
1023
+ `);function Pb(e,t,n){let o=O(t.episode_id).trim()||`ep_${String(n+1).padStart(3,"0")}`,i=qb(o,n),r=O(t.title).trim(),s=[],c=O(e.title).trim();c&&s.push(`\u5267\u540D\uFF1A${c}`),s.push(`\u96C6\u6570\uFF1A\u7B2C${i}\u96C6`),r&&s.push(`\u6807\u9898\uFF1A${r}`),s.push("");for(let a of re(t.scenes)){s.push(Qb(e,a));for(let d of re(a.actions)){let p=Yb(e,d);p&&s.push(p)}s.push("")}return{episodeIndex:n,episodeId:o,episodeNo:i,title:r,existingSynopsis:O(t.synopsis).trim(),text:s.join(`
1024
+ `).trim()}}function Cb(e,t=gw){let n=e.text.split(/\r?\n/),o=n.flatMap(c=>zb(c,t.episodeChunkTargetChars));if(e.text.length<=t.episodeInputMaxChars&&o.length===n.length)return[{episodeIndex:e.episodeIndex,episodeId:e.episodeId,episodeNo:e.episodeNo,title:e.title,part:1,partCount:1,text:e.text,sourceHash:_e(e.text)}];let i=[],r=[],s=0;for(let c of o){let a=c.length+(r.length>0?1:0);r.length>0&&s+a>t.episodeChunkTargetChars&&(i.push(r.join(`
1023
1025
  `).trim()),r=[],s=0);let d=c.length+(r.length>0?1:0);r.push(c),s+=d}return r.length>0&&i.push(r.join(`
1024
- `).trim()),i.map((c,a)=>({episodeIndex:e.episodeIndex,episodeId:e.episodeId,episodeNo:e.episodeNo,title:e.title,part:a+1,partCount:i.length,text:c,sourceHash:Ee(c)}))}function Cb(e,t){let n=fc(e);return{episodeIndex:t.episodeIndex,episodeId:t.episodeId,episodeNo:t.episodeNo,title:t.title,part:t.part,partCount:t.partCount,synopsis:so(n,"\u7247\u6BB5\u6897\u6982"),events:_r(n.get("\u5173\u952E\u4E8B\u4EF6")??""),characterChanges:Zb(n.get("\u4EBA\u7269\u53D8\u5316")??""),hook:(n.get("\u7ED3\u5C3E\u94A9\u5B50")??"").trim()}}function Tb(e,t){let n=iO(t.scope,"episode"),o=[...e].sort((i,r)=>i.part-r.part);return{episodeIndex:n.episodeIndex,episodeId:n.episodeId,episodeNo:n.episodeNo,title:n.title,synopsis:o.map(i=>i.synopsis).filter(i=>i.trim()).join(`
1025
- `),oneLine:sO(o.map(i=>i.synopsis)),events:Ql(o.flatMap(i=>i.events))}}function Vb(e,t){let n=fc(e);return{episodeIndex:t.episodeIndex,episodeId:t.episodeId,episodeNo:t.episodeNo,title:t.title,synopsis:so(n,"\u5206\u96C6\u6897\u6982"),oneLine:so(n,"\u5355\u53E5\u6897\u6982"),events:_r(n.get("\u5173\u952E\u4E8B\u4EF6")??"")}}function $b(e,t){let n=[];for(let o=0;o<e.length;o+=t){let i=e.slice(o,o+t),r=i[0],s=i[i.length-1];n.push({index:n.length+1,startEpisodeNo:r.episodeNo,endEpisodeNo:s.episodeNo,text:tO(i)})}return n}function Db(e,t){let n=[];for(let o=0;o<e.length;o+=t){let i=e.slice(o,o+t),r=i[0],s=i[i.length-1];n.push({index:n.length+1,startEpisodeNo:r.startEpisodeNo,endEpisodeNo:s.endEpisodeNo,text:nO(i)})}return n}function Gb(e,t){let n=fc(e);return{index:t.index,startEpisodeNo:t.startEpisodeNo,endEpisodeNo:t.endEpisodeNo,synopsis:so(n,"\u9636\u6BB5\u6897\u6982"),turns:_r(n.get("\u5173\u952E\u8F6C\u6298")??""),openQuestions:_r(n.get("\u672A\u89E3\u51B3\u60AC\u5FF5")??"")}}function Bb(e){let t=[...e].sort((i,r)=>i.startEpisodeNo-r.startEpisodeNo),n=t[0],o=t[t.length-1];if(!n||!o)throw new Error("arc reduce requires at least one item");return{index:n.index,startEpisodeNo:n.startEpisodeNo,endEpisodeNo:o.endEpisodeNo,synopsis:t.map(i=>`\u7B2C${i.startEpisodeNo}-${i.endEpisodeNo}\u96C6\uFF1A${i.synopsis}`).join(`
1026
- `),turns:Ql(t.flatMap(i=>i.turns)),openQuestions:Ql(t.flatMap(i=>i.openQuestions))}}function Hl(e,t){let n=["\u5206\u96C6\u7D22\u5F15\uFF1A"];for(let o of[...e].sort((i,r)=>i.episodeNo-r.episodeNo))n.push(`\u7B2C${o.episodeNo}\u96C6\uFF1A${o.oneLine||o.synopsis}`);n.push("","\u9636\u6BB5\u6897\u6982\uFF1A");for(let o of[...t].sort((i,r)=>i.startEpisodeNo-r.startEpisodeNo))n.push(`\u7B2C${o.startEpisodeNo}-${o.endEpisodeNo}\u96C6\uFF1A${o.synopsis}`);return n.join(`
1027
- `)}function Jb(e){let t=fc(e);return{synopsis:so(t,"\u5168\u6587\u6897\u6982"),theme:so(t,"\u4E3B\u9898"),logline:so(t,"\u4E00\u53E5\u8BDD"),style:so(t,"\u98CE\u683C"),mainCharacters:Wb(so(t,"\u4E3B\u8981\u4EBA\u7269"))}}async function jb(e){let t=e.config??uw,n=re(e.script.episodes);if(n.length===0)throw new S("No episodes found in script.",{exitCode:J,errorCode:"SCRIPT_EPISODES_MISSING",hint:"Create or parse episodes before generating synopsis.",data:{expected:["script.episodes[] with at least one episode"],actual:["episodes: 0"]}});let o=n.map((u,g)=>Ub(e.script,u,g)),i=e.overwrite?o:o.filter(u=>!u.existingSynopsis),r=i.length===0?[]:await lc(e.script).split({scope:"episode",partition:()=>i,chunk:u=>Pb(u,t)}).extract(As({taskId:"synopsis.chunk",instruction:kb,format:bb,input:({parcel:u})=>Xb(u),parse:({text:u,parcel:g})=>Cb(u,g)})).reduce("episode",Tb).extract(As({taskId:"synopsis.episode",instruction:Ob,format:vb,input:({parcel:u})=>eO(u),parse:({text:u,parcel:g})=>Vb(u,g)})).reduce("root",u=>[...u].sort((g,h)=>g.episodeNo-h.episodeNo)).run({concurrency:e.concurrency,checkpoint:xs(wr.join(e.checkpointDir,"episode")),checkpointSalt:e.checkpointSalt,executor:e.executor}),s=Array.isArray(r)?r:r.value,c=new Map(s.map(u=>[u.episodeIndex,u])),a=o.map(u=>c.get(u.episodeIndex)??{episodeIndex:u.episodeIndex,episodeId:u.episodeId,episodeNo:u.episodeNo,title:u.title,synopsis:u.existingSynopsis,oneLine:aO(u.existingSynopsis),events:[]}),d=a.filter(u=>!u.synopsis.trim()).map(u=>u.episodeId);if(d.length>0)throw new S("Some episode synopses are still missing.",{exitCode:ee,errorCode:"EPISODE_SYNOPSIS_MISSING",hint:"Use --overwrite to regenerate, or manually set missing episode synopses.",data:{expected:["every episode has synopsis"],actual:d}});let p=e.overwrite||dO(e.script),l=p?await zb({episodes:a,executor:e.executor,checkpointDir:wr.join(e.checkpointDir,"arc"),checkpointSalt:e.checkpointSalt,concurrency:e.concurrency,config:t}):{value:[],report:{reused:0,ran:0}},f=p?await Hb({episodes:a,arcs:l.value,executor:e.executor,checkpointDir:wr.join(e.checkpointDir,"final"),checkpointSalt:e.checkpointSalt,config:t}):{value:pO(e.script),report:{reused:0,ran:0}};return{episodeBriefs:a,overview:f.value,overviewGenerated:p,report:{reused:(Array.isArray(r)?0:r.report.reused)+l.report.reused+f.report.reused,ran:(Array.isArray(r)?0:r.report.ran)+l.report.ran+f.report.ran}}}async function fw(e,t=Wn){let n=cO(e.concurrency,eu,"--concurrency"),o=!!e.overwrite,i=!!e.apply,r=!!e.dry_run;if(i&&r)throw new S("--apply and --dry-run are mutually exclusive.",{exitCode:J,errorCode:"SYNOPSIS_GENERATE_FLAG_CONFLICT",hint:"Pick one mode and retry.",data:{expected:["at most one of --apply / --dry-run"],actual:["--apply","--dry-run"]}});let s=v(e.workspace_path||"workspace"),c=await ws(e),a=t.createExecutor(v(e.llm_config).trim()||void 0),d=v(e.checkpoint).trim()||wr.join(ou(s),"loom","synopsis-generate"),p=await jb({script:c.script,executor:a,checkpointDir:d,concurrency:n,overwrite:o}),l=new Set,f=re(c.script.episodes);for(let A of p.episodeBriefs){let b=f[A.episodeIndex];b&&(o||!v(b.synopsis).trim())&&v(b.synopsis)!==A.synopsis&&(b.synopsis=A.synopsis,l.add(A.episodeId))}let u=!1;if(u=uc(c.script,"synopsis",p.overview.synopsis,o)||u,u=uc(c.script,"theme",p.overview.theme,o)||u,u=uc(c.script,"logline",p.overview.logline,o)||u,u=uc(c.script,"style",p.overview.style,o)||u,o||re(c.script.main_characters).length===0){let A=p.overview.mainCharacters.map(b=>({name:b.name,role:b.role}));JSON.stringify(c.script.main_characters??[])!==JSON.stringify(A)&&(c.script.main_characters=A,u=!0)}let g=l.size>0||u,h=_s(c),m=!!h.passed,w=[`${p.episodeBriefs.length} episodes; ${l.size} synopses ${i?"written":"would change"}; overview ${p.overviewGenerated?"generated":"reused"}; validation ${m?i?"passed":"would pass":i?"needs repair":"would need repair"}${i?"":"; dry-run, no write"}`,`loom: ran=${p.report.ran}, reused=${p.report.reused}`,`llm config: ${a.configSource}; routes: ${a.usage().length}`],y,_;i&&g&&([y,_]=await Ml(c,e,"synopsis.generate"),await Rl(c,h,y),c.remote&&w.push(`revision ${y}; idempotent ${String(_).toLowerCase()}`));let x=gd(re(h.issues));return i||w.push("Run again with --apply to write the generated synopsis fields."),[{text:[...w,...x].join(`
1028
- `),data:{op:i?"synopsis.generate":"synopsis.generate.dry-run",changed:i&&g,revision:y,idempotent:_,validation:h,issues:x,script_path:c.artifactLabel,episode_synopses:p.episodeBriefs.map(A=>({episode_id:A.episodeId,title:A.title,synopsis:A.synopsis,one_line:A.oneLine})),config_source:a.configSource,llm_routes:a.usage()}},B]}function Kb(e,t){if(e.length<=t)return[e];let n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}async function zb(e){let t=$b(e.episodes,e.config.arcEpisodeCount),n=1,o={reused:0,ran:0};for(;;){let i=await lc(t).split({scope:"arc",partition:c=>c,chunk:c=>[c]}).extract(As({taskId:"synopsis.arc",instruction:Rb,format:Mb,input:({parcel:c})=>oO(c),parse:({text:c,parcel:a})=>Gb(c,a)})).reduce("arc",c=>rO(c,"arc")).reduce("root",c=>[...c].sort((a,d)=>a.startEpisodeNo-d.startEpisodeNo)).run({concurrency:e.concurrency,checkpoint:xs(wr.join(e.checkpointDir,`level-${n}`)),checkpointSalt:e.checkpointSalt,executor:e.executor});o.reused+=i.report.reused,o.ran+=i.report.ran;let r=i.value;if(Hl(e.episodes,r).length<=e.config.finalMaxInputChars||r.length<=1)return{value:r,report:o};t=Db(r,e.config.arcEpisodeCount),n+=1}}async function Hb(e){let t=e.arcs;for(;Hl(e.episodes,t).length>e.config.finalMaxInputChars&&t.length>1;)t=[Bb(t)];let n=await lc({episodes:e.episodes,arcs:t}).extract(As({taskId:"synopsis.script-overview",instruction:Nb,format:Lb,input:({parcel:o})=>Hl(o.episodes,o.arcs),parse:({text:o})=>Jb(o)})).run({concurrency:1,checkpoint:xs(e.checkpointDir),checkpointSalt:e.checkpointSalt,executor:e.executor});return{value:n.value,report:n.report}}function Fb(e,t){let n=ie(t.environment)?t.environment:{},o=v(n.space).trim(),i=v(n.time).trim(),r=Ko(t),s=re(r.locations).map(p=>Fl(e,"locations","location_id","location_name",v(p.location_id))).filter(p=>p),c=re(r.actors).map(p=>Fl(e,"actors","actor_id","actor_name",v(p.actor_id))).filter(p=>p),a=s.join("\u3001")||"-";return`[\u573A\u666F] ${[o,i].filter(p=>p).join(" ")||"-"}\uFF5C${a}\uFF5C\u51FA\u573A\uFF1A${c.join("\u3001")||"-"}`}function Qb(e,t){let n=v(t.type).trim();if(n==="dialogue"){let i=pw(e,t),r=v(t.content).trim();return r?`[\u5BF9\u767D] ${i?`${i}\uFF1A`:""}${r}`:""}if(n==="inner_thought"){let i=pw(e,t),r=v(t.content).trim();return r?`[\u5FC3\u58F0] ${i?`${i}\uFF1A`:""}${r}`:""}let o=v(t.content).trim();return o?`[\u52A8\u4F5C] ${o}`:""}function pw(e,t){let n=t.speaker;if(!ie(n))return"";let o=v(n.actor_id).trim();if(o)return Fl(e,"actors","actor_id","actor_name",o)||o;let i=v(n.kind).trim();return i?v(n.label).trim()||i:""}function Fl(e,t,n,o,i){let r=re(e[t]).find(s=>v(s[n])===i);return r?v(r[o]).trim():""}function Yb(e,t){let n=/^ep_(\d+)$/.exec(e);return n?Number(n[1]):t+1}function fc(e){let t=new Map,n=null,o=[],i=()=>{n&&t.set(n,o.join(`
1029
- `).trim()),o=[]};for(let r of e.split(/\r?\n/)){let s=qb(r);if(s){if(n===s.name&&s.inline){o.push(r);continue}i(),n=s.name,s.inline&&o.push(s.inline);continue}n&&o.push(r)}return i(),t}var lw=new Set(["\u7247\u6BB5\u6897\u6982","\u5173\u952E\u4E8B\u4EF6","\u4EBA\u7269\u53D8\u5316","\u7ED3\u5C3E\u94A9\u5B50","\u5206\u96C6\u6897\u6982","\u5355\u53E5\u6897\u6982","\u9636\u6BB5\u6897\u6982","\u5173\u952E\u8F6C\u6298","\u672A\u89E3\u51B3\u60AC\u5FF5","\u5168\u6587\u6897\u6982","\u4E3B\u9898","\u4E00\u53E5\u8BDD","\u98CE\u683C","\u4E3B\u8981\u4EBA\u7269"]);function qb(e){let t=e.trim(),n=/^#{1,6}\s+(.+?)\s*$/.exec(t);if(n){let r=n[1].trim();return lw.has(r)?{name:r,inline:""}:null}let o=t.search(/[::]/),i=(o>=0?t.slice(0,o):t).trim();return lw.has(i)?{name:i,inline:o>=0?t.slice(o+1).trim():""}:null}function so(e,t){let n=(e.get(t)??"").trim();if(!n)throw new Error(`synopsis output missing section: ${t}`);return n}function _r(e){return e.split(/\r?\n/).map(t=>t.trim()).map(t=>t.replace(/^[-*]\s*/,"").trim()).filter(t=>t.length>0)}function Zb(e){return _r(e).map(t=>{let[n,...o]=t.split("|");return{name:v(n).trim(),change:o.join("|").trim()}}).filter(t=>t.name&&t.change)}function Wb(e){return _r(e).map(t=>{let[n,...o]=t.split("|");return{name:v(n).trim(),role:o.join("|").trim()}}).filter(t=>t.name&&t.role)}function Xb(e){return[`\u5F53\u524D\u5206\u96C6\uFF1A\u7B2C${e.episodeNo}\u96C6 ${e.title||""}`.trim(),`\u5F53\u524D\u7247\u6BB5\uFF1A${e.part}/${e.partCount}`,"","\u8FD9\u662F\u5F53\u524D\u4EFB\u52A1\u7684\u539F\u6587\uFF1A",e.text].join(`
1030
- `)}function eO(e){return[`\u5F53\u524D\u5206\u96C6\uFF1A\u7B2C${e.episodeNo}\u96C6 ${e.title||""}`.trim(),"","\u7247\u6BB5\u6897\u6982\uFF1A",e.synopsis,"","\u7247\u6BB5\u5173\u952E\u4E8B\u4EF6\uFF1A",...e.events.map(t=>`- ${t}`)].join(`
1031
- `)}function tO(e){let t=[];for(let n of e){if(t.push(`\u7B2C${n.episodeNo}\u96C6 ${n.title||""}`.trim()),t.push(`\u5355\u53E5\uFF1A${n.oneLine}`),t.push(`\u6897\u6982\uFF1A${n.synopsis}`),n.events.length>0){t.push("\u5173\u952E\u4E8B\u4EF6\uFF1A");for(let o of n.events)t.push(`- ${o}`)}t.push("")}return t.join(`
1032
- `).trim()}function nO(e){let t=[];for(let n of e){if(t.push(`\u7B2C${n.startEpisodeNo}-${n.endEpisodeNo}\u96C6`),t.push(`\u9636\u6BB5\u6897\u6982\uFF1A${n.synopsis}`),n.turns.length>0){t.push("\u5173\u952E\u8F6C\u6298\uFF1A");for(let o of n.turns)t.push(`- ${o}`)}if(n.openQuestions.length>0){t.push("\u672A\u89E3\u51B3\u60AC\u5FF5\uFF1A");for(let o of n.openQuestions)t.push(`- ${o}`)}t.push("")}return t.join(`
1033
- `).trim()}function oO(e){return[`\u5F53\u524D\u9636\u6BB5\uFF1A\u7B2C${e.startEpisodeNo}-${e.endEpisodeNo}\u96C6`,"","\u5206\u96C6\u6897\u6982\uFF1A",e.text].join(`
1034
- `)}function iO(e,t){if(e===null)throw new Error(`${t} scope missing`);return e}function rO(e,t){let n=e[0];if(!n||e.length!==1)throw new Error(`${t} reduce requires exactly one item`);return n}function sO(e){return e.map(t=>t.trim()).find(t=>t.length>0)??""}function Ql(e){let t=new Set,n=[];for(let o of e.map(i=>i.trim()).filter(i=>i.length>0))t.has(o)||(t.add(o),n.push(o));return n}function aO(e){let t=e.replace(/\s+/g," ").trim();return t.length>50?t.slice(0,50):t}function cO(e,t,n){if(e==null||e==="")return t;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new S(`${n} must be a positive integer.`,{exitCode:J,errorCode:"NUMERIC_OPTION_INVALID",hint:`Pass ${n} ${t}.`,data:{expected:[`${n}: positive integer`],actual:[v(e)]}});return Math.floor(o)}function uc(e,t,n,o){return!o&&v(e[t]).trim()||v(e[t])===n?!1:(e[t]=n,!0)}function dO(e){return!v(e.synopsis).trim()||!v(e.theme).trim()||!v(e.logline).trim()||!v(e.style).trim()||re(e.main_characters).length===0}function pO(e){return{synopsis:v(e.synopsis).trim(),theme:v(e.theme).trim(),logline:v(e.logline).trim(),style:v(e.style).trim(),mainCharacters:re(e.main_characters).map(t=>({name:v(t.name).trim(),role:v(t.role).trim()})).filter(t=>t.name&&t.role)}}import*as ks from"node:fs";var gw=3;function Yl(e){return v(e.project_group_no||process.env.SANDBOX_PROJECT_GROUP_NO).trim()}function ql(e){try{return Ol(e)}catch(t){throw t instanceof me?jo("SCRIPT API BLOCKED: gateway not configured",t):t}}function hw(e,t){let n=Yl(e);if(n&&n!==t.projectGroupNo)throw mw(t,`configured projectGroupNo=${n}`);let o=ql(t.projectGroupNo);if(o.gatewayBase!==t.apiBaseUrl)throw mw(t,`configured apiBaseUrl=${o.gatewayBase}`);return o}function mw(e,t){return new S("The configured remote does not match this working copy.",{exitCode:k,errorCode:"WORKING_COPY_REMOTE_MISMATCH",hint:"Restore the checkout environment for this working copy, or checkout another file.",data:{expected:[`projectGroupNo=${e.projectGroupNo}`,`apiBaseUrl=${e.apiBaseUrl}`],actual:[t]}})}function Zl(e){let t;try{t=JSON.parse(ks.readFileSync(e,"utf-8"))}catch(n){throw new S("The local script is missing or invalid JSON.",{exitCode:k,errorCode:"SCRIPT_JSON_INVALID",hint:"Fix the local script JSON before continuing.",data:{actual:[e,n instanceof Error?n.message:String(n)]}})}if(!ie(t))throw new S("The script root must be a JSON object.",{exitCode:k,errorCode:"SCRIPT_ROOT_INVALID",hint:"Replace the file with a valid Script v3 JSON object.",data:{actual:[e,Array.isArray(t)?"array":typeof t]}});return t}function yw(e){return String(e.code)==="9002"||e.message.includes("\u7248\u672C\u51B2\u7A81")}function mc(e){let t=e.status!==null&&e.status>=200&&e.status<300&&e.code===null;return e.status===null||e.status>=500||t}function ww(e){let t=Number(e.revision);if(!Number.isInteger(t)||t<0)throw new S("The gateway returned an invalid snapshot revision.",{exitCode:ee,errorCode:"PUBLISH_OUTCOME_UNKNOWN",hint:"Inspect the remote script before retrying.",data:{actual:[JSON.stringify(e)]}});return t}function _w(e,t){return new S("The publish outcome could not be confirmed after retrying.",{exitCode:ee,errorCode:"PUBLISH_OUTCOME_UNKNOWN",hint:"Run publish again; it will inspect the latest snapshot before sending another patch.",data:{actual:[...t,`baseRevision=${e}`]}})}async function lO(e,t,n,o,i,r){let s=[];for(let c=1;c<=gw;c+=1){let a;try{a=await e.getSnapshot()}catch(p){if(p instanceof me&&mc(p)){s.push(`snapshot attempt ${c}: ${p.message}`);continue}throw p instanceof me?jo("PUBLISH BLOCKED: snapshot query failed",p):p}if(a===null||!ie(a.script))throw new S("The managed working copy no longer has a remote script.",{exitCode:k,errorCode:"REMOTE_SCRIPT_NOT_FOUND",hint:"Publish a new unmanaged file to create the remote script, or restore the remote project.",data:{actual:[`projectGroupNo=${e.projectGroupNo}`]}});let d=ww(a);if(Be(a.script)===o&&a.validationStatus==="valid")return{revision:d,patchedFromRevision:d,attempts:c,recovered:d!==i.baseRevision};Gt(t,o);try{let p=await e.publishPatch({baseRevision:d,old:a.script,edited:n,validation:r}),l=ie(p)?Number(p.revision):Number.NaN;if(Number.isInteger(l)&&l>d)return{revision:l,patchedFromRevision:d,attempts:c,recovered:c>1};s.push(`patch attempt ${c}: invalid response ${JSON.stringify(p)}`)}catch(p){if(p instanceof me&&(yw(p)||mc(p))){s.push(`patch attempt ${c}: ${p.message}`);continue}throw p instanceof me?jo("PUBLISH BLOCKED: patch failed",p):p}}throw _w(i.baseRevision,s)}async function uO(e,t,n,o,i){let r=[];for(let s=1;s<=gw;s+=1){let c;try{c=await e.getSnapshot()}catch(a){if(a instanceof me&&mc(a)){r.push(`snapshot attempt ${s}: ${a.message}`);continue}throw a instanceof me?jo("PUBLISH BLOCKED: snapshot query failed",a):a}if(c!==null){let a=ww(c);if(ie(c.script)&&Be(c.script)===o&&c.validationStatus==="valid")return{revision:a,patchedFromRevision:0,attempts:s,recovered:!0};throw new S("An unmanaged local script cannot replace an existing remote script.",{exitCode:k,errorCode:"REMOTE_SCRIPT_EXISTS",hint:"Checkout the remote script, apply the local changes to that managed working copy, then publish.",data:{actual:[`projectGroupNo=${e.projectGroupNo}`,`revision=${a}`]}})}Gt(t,o);try{let a=await e.publishPatch({baseRevision:0,old:{},edited:n,validation:i}),d=ie(a)?Number(a.revision):Number.NaN;if(Number.isInteger(d)&&d>0)return{revision:d,patchedFromRevision:0,attempts:s,recovered:s>1};r.push(`patch attempt ${s}: invalid response ${JSON.stringify(a)}`)}catch(a){if(a instanceof me&&(yw(a)||mc(a))){r.push(`patch attempt ${s}: ${a.message}`);continue}throw a instanceof me?jo("PUBLISH BLOCKED: patch failed",a):a}}throw _w(0,r)}async function Ew(e){let t=ge(e),n=!!e.discard_local,o=Rr(t),i=$s(t),r=ks.existsSync(t),s=Or(t);if(r&&i===null&&!n)throw new S("The target is an unmanaged local script.",{exitCode:k,errorCode:"LOCAL_TARGET_EXISTS",hint:`Run \`scriptctl checkout --script-path ${t} --discard-local\` only if the local file may be discarded.`,data:{actual:[t]}});if(r&&i!==null&&!n&&Be(Zl(t))!==i.baseContentHash)throw new S("The working copy has unpublished local changes.",{exitCode:k,errorCode:"WORKING_COPY_DIRTY",hint:"Publish the local changes, or pass --discard-local to replace them with the remote snapshot.",data:{actual:[t,`baseRevision=${i.baseRevision}`]}});let c=i!==null&&!n?hw(e,i):ql(Yl(e)||null),a;try{a=await c.getSnapshot()}catch(l){throw l instanceof me?jo("CHECKOUT BLOCKED: snapshot query failed",l):l}if(a===null||!ie(a.script))throw new S("No remote script_v2 snapshot exists for this project.",{exitCode:k,errorCode:"REMOTE_SCRIPT_NOT_FOUND",hint:"Use the ingest/create workflow and publish the first script instead of checkout.",data:{actual:[`projectGroupNo=${c.projectGroupNo}`]}});vr(t,s);let d=Be(a.script);return Fe(t,a.script),Ds(t,{schemaVersion:1,projectGroupNo:c.projectGroupNo,apiBaseUrl:c.gatewayBase,baseRevision:Number(a.revision),baseContentHash:d}),[{text:n&&r?`Discarded the local file and checked out revision ${a.revision} to ${t}`:`Checked out revision ${a.revision} to ${t}`,data:{changed:!0,script_path:t,metadata_path:o.metadataPath,managed:!0,dirty:!1,discarded_local:n&&r,project_group_no:c.projectGroupNo,base_revision:Number(a.revision)}},B]}function xw(e){let t=ge(e),n=ks.existsSync(t),o=$s(t),i=n&&o!==null?Be(Zl(t))!==o.baseContentHash:null;return[{text:o===null?`${t}: unmanaged local script`:`${t}: ${i?"dirty":"clean"} at revision ${o.baseRevision}`,data:{script_path:t,exists:n,managed:o!==null,dirty:i,...o===null?{}:{project_group_no:o.projectGroupNo,api_base_url:o.apiBaseUrl,base_revision:o.baseRevision}}},B]}async function Sw(e){let t=ge(e),n=Zl(t),o=Be(n),i=$s(t);if(i!==null&&i.baseContentHash===o)return[{text:`No local changes; revision remains ${i.baseRevision}`,data:{changed:!1,published:!1,reason:"NO_CHANGES",revision:i.baseRevision,script_path:t}},B];let r=vl(n);if(!r.passed)throw new S("The local script does not pass its declared Script version validation.",{exitCode:k,errorCode:"PUBLISH_VALIDATION_FAILED",hint:`Run \`scriptctl validate --script-path ${t}\`, repair the issues, then publish again.`,data:{actual:r.issues.slice(0,5).map(p=>`${p.path??"<root>"}: ${p.summary}`)}});let s=Gs(n).episodes.length,c={status:"valid",summary:{passed:!0,hasBlocking:!1,stats:r.stats??{},issueCount:0}};if(i!==null){let p=hw(e,i),l=await lO(p,t,n,o,i,c);return Ds(t,{schemaVersion:1,projectGroupNo:p.projectGroupNo,apiBaseUrl:p.gatewayBase,baseRevision:l.revision,baseContentHash:o}),await Rd(p,s),[{text:`Published local content over revision ${l.patchedFromRevision} \u2192 ${l.revision}`,data:{changed:!0,published:!0,created:!1,transport:"patch",script_path:t,project_group_no:p.projectGroupNo,base_revision:l.patchedFromRevision,revision:l.revision,attempts:l.attempts,recovered:l.recovered}},B]}let a=ql(Yl(e)||null),d=await uO(a,t,n,o,c);return Ds(t,{schemaVersion:1,projectGroupNo:a.projectGroupNo,apiBaseUrl:a.gatewayBase,baseRevision:d.revision,baseContentHash:o}),await Rd(a,s),[{text:`Published revision ${d.patchedFromRevision} \u2192 ${d.revision}`,data:{changed:!0,published:!0,created:!0,transport:"patch",script_path:t,project_group_no:a.projectGroupNo,base_revision:d.patchedFromRevision,revision:d.revision,attempts:d.attempts,recovered:d.recovered}},B]}function Iw(e,t,n){e.command("migrate").description("Create a newer Script schema copy through the registered migration chain").requiredOption("-p, --script-path <path>","Source Script JSON file").requiredOption("-o, --output <file>","Destination Script JSON file").requiredOption("--to <version>","Target Script version").option("--manifest <file>","Migration manifest output").option("--force","Replace existing migration artifacts").addHelpText("after",`
1026
+ `).trim()),i.map((c,a)=>({episodeIndex:e.episodeIndex,episodeId:e.episodeId,episodeNo:e.episodeNo,title:e.title,part:a+1,partCount:i.length,text:c,sourceHash:_e(c)}))}function Tb(e,t){let n=gc(e);return{episodeIndex:t.episodeIndex,episodeId:t.episodeId,episodeNo:t.episodeNo,title:t.title,part:t.part,partCount:t.partCount,synopsis:ao(n,"\u7247\u6BB5\u6897\u6982"),events:xr(n.get("\u5173\u952E\u4E8B\u4EF6")??""),characterChanges:Wb(n.get("\u4EBA\u7269\u53D8\u5316")??""),hook:(n.get("\u7ED3\u5C3E\u94A9\u5B50")??"").trim()}}function Vb(e,t){let n=rO(t.scope,"episode"),o=[...e].sort((i,r)=>i.part-r.part);return{episodeIndex:n.episodeIndex,episodeId:n.episodeId,episodeNo:n.episodeNo,title:n.title,synopsis:o.map(i=>i.synopsis).filter(i=>i.trim()).join(`
1027
+ `),oneLine:aO(o.map(i=>i.synopsis)),events:ql(o.flatMap(i=>i.events))}}function $b(e,t){let n=gc(e);return{episodeIndex:t.episodeIndex,episodeId:t.episodeId,episodeNo:t.episodeNo,title:t.title,synopsis:ao(n,"\u5206\u96C6\u6897\u6982"),oneLine:ao(n,"\u5355\u53E5\u6897\u6982"),events:xr(n.get("\u5173\u952E\u4E8B\u4EF6")??"")}}function Db(e,t){let n=[];for(let o=0;o<e.length;o+=t){let i=e.slice(o,o+t),r=i[0],s=i[i.length-1];n.push({index:n.length+1,startEpisodeNo:r.episodeNo,endEpisodeNo:s.episodeNo,text:nO(i)})}return n}function Gb(e,t){let n=[];for(let o=0;o<e.length;o+=t){let i=e.slice(o,o+t),r=i[0],s=i[i.length-1];n.push({index:n.length+1,startEpisodeNo:r.startEpisodeNo,endEpisodeNo:s.endEpisodeNo,text:oO(i)})}return n}function Bb(e,t){let n=gc(e);return{index:t.index,startEpisodeNo:t.startEpisodeNo,endEpisodeNo:t.endEpisodeNo,synopsis:ao(n,"\u9636\u6BB5\u6897\u6982"),turns:xr(n.get("\u5173\u952E\u8F6C\u6298")??""),openQuestions:xr(n.get("\u672A\u89E3\u51B3\u60AC\u5FF5")??"")}}function Jb(e){let t=[...e].sort((i,r)=>i.startEpisodeNo-r.startEpisodeNo),n=t[0],o=t[t.length-1];if(!n||!o)throw new Error("arc reduce requires at least one item");return{index:n.index,startEpisodeNo:n.startEpisodeNo,endEpisodeNo:o.endEpisodeNo,synopsis:t.map(i=>`\u7B2C${i.startEpisodeNo}-${i.endEpisodeNo}\u96C6\uFF1A${i.synopsis}`).join(`
1028
+ `),turns:ql(t.flatMap(i=>i.turns)),openQuestions:ql(t.flatMap(i=>i.openQuestions))}}function Ql(e,t){let n=["\u5206\u96C6\u7D22\u5F15\uFF1A"];for(let o of[...e].sort((i,r)=>i.episodeNo-r.episodeNo))n.push(`\u7B2C${o.episodeNo}\u96C6\uFF1A${o.oneLine||o.synopsis}`);n.push("","\u9636\u6BB5\u6897\u6982\uFF1A");for(let o of[...t].sort((i,r)=>i.startEpisodeNo-r.startEpisodeNo))n.push(`\u7B2C${o.startEpisodeNo}-${o.endEpisodeNo}\u96C6\uFF1A${o.synopsis}`);return n.join(`
1029
+ `)}function Kb(e){let t=gc(e);return{synopsis:ao(t,"\u5168\u6587\u6897\u6982"),theme:ao(t,"\u4E3B\u9898"),logline:ao(t,"\u4E00\u53E5\u8BDD"),style:ao(t,"\u98CE\u683C"),mainCharacters:Xb(ao(t,"\u4E3B\u8981\u4EBA\u7269"))}}async function jb(e){let t=e.config??gw,n=re(e.script.episodes);if(n.length===0)throw new x("No episodes found in script.",{exitCode:B,errorCode:"SCRIPT_EPISODES_MISSING",hint:"Create or parse episodes before generating synopsis.",data:{expected:["script.episodes[] with at least one episode"],actual:["episodes: 0"]}});let o=n.map((u,m)=>Pb(e.script,u,m)),i=e.overwrite?o:o.filter(u=>!u.existingSynopsis),r=i.length===0?[]:await fc(e.script).split({scope:"episode",partition:()=>i,chunk:u=>Cb(u,t)}).extract(ks({taskId:"synopsis.chunk",instruction:bb,format:Ob,input:({parcel:u})=>eO(u),parse:({text:u,parcel:m})=>Tb(u,m)})).reduce("episode",Vb).extract(ks({taskId:"synopsis.episode",instruction:vb,format:Rb,input:({parcel:u})=>tO(u),parse:({text:u,parcel:m})=>$b(u,m)})).reduce("root",u=>[...u].sort((m,h)=>m.episodeNo-h.episodeNo)).run({concurrency:e.concurrency,checkpoint:Ss(Er.join(e.checkpointDir,"episode")),checkpointSalt:e.checkpointSalt,executor:e.executor}),s=Array.isArray(r)?r:r.value,c=new Map(s.map(u=>[u.episodeIndex,u])),a=o.map(u=>c.get(u.episodeIndex)??{episodeIndex:u.episodeIndex,episodeId:u.episodeId,episodeNo:u.episodeNo,title:u.title,synopsis:u.existingSynopsis,oneLine:cO(u.existingSynopsis),events:[]}),d=a.filter(u=>!u.synopsis.trim()).map(u=>u.episodeId);if(d.length>0)throw new x("Some episode synopses are still missing.",{exitCode:X,errorCode:"EPISODE_SYNOPSIS_MISSING",hint:"Use --overwrite to regenerate, or manually set missing episode synopses.",data:{expected:["every episode has synopsis"],actual:d}});let p=e.overwrite||pO(e.script),l=p?await Hb({episodes:a,executor:e.executor,checkpointDir:Er.join(e.checkpointDir,"arc"),checkpointSalt:e.checkpointSalt,concurrency:e.concurrency,config:t}):{value:[],report:{reused:0,ran:0}},f=p?await Fb({episodes:a,arcs:l.value,executor:e.executor,checkpointDir:Er.join(e.checkpointDir,"final"),checkpointSalt:e.checkpointSalt,config:t}):{value:lO(e.script),report:{reused:0,ran:0}};return{episodeBriefs:a,overview:f.value,overviewGenerated:p,report:{reused:(Array.isArray(r)?0:r.report.reused)+l.report.reused+f.report.reused,ran:(Array.isArray(r)?0:r.report.ran)+l.report.ran+f.report.ran}}}async function hw(e,t=Xn){let n=dO(e.concurrency,nu,"--concurrency"),o=!!e.overwrite,i=!!e.apply,r=!!e.dry_run;if(i&&r)throw new x("--apply and --dry-run are mutually exclusive.",{exitCode:B,errorCode:"SYNOPSIS_GENERATE_FLAG_CONFLICT",hint:"Pick one mode and retry.",data:{expected:["at most one of --apply / --dry-run"],actual:["--apply","--dry-run"]}});let s=O(e.workspace_path||"workspace"),c=await _s(e),a=O(e.model).trim(),d=t.createExecutor(O(e.llm_config).trim()||void 0,a?{profile:a}:void 0),p=O(e.checkpoint).trim()||Er.join(ru(s),"loom","synopsis-generate"),l=await jb({script:c.script,executor:d,checkpointDir:p,concurrency:n,overwrite:o}),f=new Set,u=re(c.script.episodes);for(let b of l.episodeBriefs){let U=u[b.episodeIndex];U&&(o||!O(U.synopsis).trim())&&O(U.synopsis)!==b.synopsis&&(U.synopsis=b.synopsis,f.add(b.episodeId))}let m=!1;if(m=mc(c.script,"synopsis",l.overview.synopsis,o)||m,m=mc(c.script,"theme",l.overview.theme,o)||m,m=mc(c.script,"logline",l.overview.logline,o)||m,m=mc(c.script,"style",l.overview.style,o)||m,o||re(c.script.main_characters).length===0){let b=l.overview.mainCharacters.map(U=>({name:U.name,role:U.role}));JSON.stringify(c.script.main_characters??[])!==JSON.stringify(b)&&(c.script.main_characters=b,m=!0)}let h=f.size>0||m,g=Es(c),w=!!g.passed,y=[`${l.episodeBriefs.length} episodes; ${f.size} synopses ${i?"written":"would change"}; overview ${l.overviewGenerated?"generated":"reused"}; validation ${w?i?"passed":"would pass":i?"needs repair":"would need repair"}${i?"":"; dry-run, no write"}`,`loom: ran=${l.report.ran}, reused=${l.report.reused}`,`llm config: ${d.configSource}; routes: ${d.usage().length}`],_,S;i&&h&&([_,S]=await Ll(c,e,"synopsis.generate"),await Nl(c,g,_),c.remote&&y.push(`revision ${_}; idempotent ${String(S).toLowerCase()}`));let E=yd(re(g.issues));return i||y.push("Run again with --apply to write the generated synopsis fields."),[{text:[...y,...E].join(`
1030
+ `),data:{op:i?"synopsis.generate":"synopsis.generate.dry-run",changed:i&&h,revision:_,idempotent:S,validation:g,issues:E,script_path:c.artifactLabel,episode_synopses:l.episodeBriefs.map(b=>({episode_id:b.episodeId,title:b.title,synopsis:b.synopsis,one_line:b.oneLine})),config_source:d.configSource,llm_routes:d.usage()}},G]}function zb(e,t){if(e.length<=t)return[e];let n=[];for(let o=0;o<e.length;o+=t)n.push(e.slice(o,o+t));return n}async function Hb(e){let t=Db(e.episodes,e.config.arcEpisodeCount),n=1,o={reused:0,ran:0};for(;;){let i=await fc(t).split({scope:"arc",partition:c=>c,chunk:c=>[c]}).extract(ks({taskId:"synopsis.arc",instruction:Mb,format:Nb,input:({parcel:c})=>iO(c),parse:({text:c,parcel:a})=>Bb(c,a)})).reduce("arc",c=>sO(c,"arc")).reduce("root",c=>[...c].sort((a,d)=>a.startEpisodeNo-d.startEpisodeNo)).run({concurrency:e.concurrency,checkpoint:Ss(Er.join(e.checkpointDir,`level-${n}`)),checkpointSalt:e.checkpointSalt,executor:e.executor});o.reused+=i.report.reused,o.ran+=i.report.ran;let r=i.value;if(Ql(e.episodes,r).length<=e.config.finalMaxInputChars||r.length<=1)return{value:r,report:o};t=Gb(r,e.config.arcEpisodeCount),n+=1}}async function Fb(e){let t=e.arcs;for(;Ql(e.episodes,t).length>e.config.finalMaxInputChars&&t.length>1;)t=[Jb(t)];let n=await fc({episodes:e.episodes,arcs:t}).extract(ks({taskId:"synopsis.script-overview",instruction:Lb,format:Ub,input:({parcel:o})=>Ql(o.episodes,o.arcs),parse:({text:o})=>Kb(o)})).run({concurrency:1,checkpoint:Ss(e.checkpointDir),checkpointSalt:e.checkpointSalt,executor:e.executor});return{value:n.value,report:n.report}}function Qb(e,t){let n=oe(t.environment)?t.environment:{},o=O(n.space).trim(),i=O(n.time).trim(),r=jo(t),s=re(r.locations).map(p=>Yl(e,"locations","location_id","location_name",O(p.location_id))).filter(p=>p),c=re(r.actors).map(p=>Yl(e,"actors","actor_id","actor_name",O(p.actor_id))).filter(p=>p),a=s.join("\u3001")||"-";return`[\u573A\u666F] ${[o,i].filter(p=>p).join(" ")||"-"}\uFF5C${a}\uFF5C\u51FA\u573A\uFF1A${c.join("\u3001")||"-"}`}function Yb(e,t){let n=O(t.type).trim();if(n==="dialogue"){let i=fw(e,t),r=O(t.content).trim();return r?`[\u5BF9\u767D] ${i?`${i}\uFF1A`:""}${r}`:""}if(n==="inner_thought"){let i=fw(e,t),r=O(t.content).trim();return r?`[\u5FC3\u58F0] ${i?`${i}\uFF1A`:""}${r}`:""}let o=O(t.content).trim();return o?`[\u52A8\u4F5C] ${o}`:""}function fw(e,t){let n=t.speaker;if(!oe(n))return"";let o=O(n.actor_id).trim();if(o)return Yl(e,"actors","actor_id","actor_name",o)||o;let i=O(n.kind).trim();return i?O(n.label).trim()||i:""}function Yl(e,t,n,o,i){let r=re(e[t]).find(s=>O(s[n])===i);return r?O(r[o]).trim():""}function qb(e,t){let n=/^ep_(\d+)$/.exec(e);return n?Number(n[1]):t+1}function gc(e){let t=new Map,n=null,o=[],i=()=>{n&&t.set(n,o.join(`
1031
+ `).trim()),o=[]};for(let r of e.split(/\r?\n/)){let s=Zb(r);if(s){if(n===s.name&&s.inline){o.push(r);continue}i(),n=s.name,s.inline&&o.push(s.inline);continue}n&&o.push(r)}return i(),t}var mw=new Set(["\u7247\u6BB5\u6897\u6982","\u5173\u952E\u4E8B\u4EF6","\u4EBA\u7269\u53D8\u5316","\u7ED3\u5C3E\u94A9\u5B50","\u5206\u96C6\u6897\u6982","\u5355\u53E5\u6897\u6982","\u9636\u6BB5\u6897\u6982","\u5173\u952E\u8F6C\u6298","\u672A\u89E3\u51B3\u60AC\u5FF5","\u5168\u6587\u6897\u6982","\u4E3B\u9898","\u4E00\u53E5\u8BDD","\u98CE\u683C","\u4E3B\u8981\u4EBA\u7269"]);function Zb(e){let t=e.trim(),n=/^#{1,6}\s+(.+?)\s*$/.exec(t);if(n){let r=n[1].trim();return mw.has(r)?{name:r,inline:""}:null}let o=t.search(/[::]/),i=(o>=0?t.slice(0,o):t).trim();return mw.has(i)?{name:i,inline:o>=0?t.slice(o+1).trim():""}:null}function ao(e,t){let n=(e.get(t)??"").trim();if(!n)throw new Error(`synopsis output missing section: ${t}`);return n}function xr(e){return e.split(/\r?\n/).map(t=>t.trim()).map(t=>t.replace(/^[-*]\s*/,"").trim()).filter(t=>t.length>0)}function Wb(e){return xr(e).map(t=>{let[n,...o]=t.split("|");return{name:O(n).trim(),change:o.join("|").trim()}}).filter(t=>t.name&&t.change)}function Xb(e){return xr(e).map(t=>{let[n,...o]=t.split("|");return{name:O(n).trim(),role:o.join("|").trim()}}).filter(t=>t.name&&t.role)}function eO(e){return[`\u5F53\u524D\u5206\u96C6\uFF1A\u7B2C${e.episodeNo}\u96C6 ${e.title||""}`.trim(),`\u5F53\u524D\u7247\u6BB5\uFF1A${e.part}/${e.partCount}`,"","\u8FD9\u662F\u5F53\u524D\u4EFB\u52A1\u7684\u539F\u6587\uFF1A",e.text].join(`
1032
+ `)}function tO(e){return[`\u5F53\u524D\u5206\u96C6\uFF1A\u7B2C${e.episodeNo}\u96C6 ${e.title||""}`.trim(),"","\u7247\u6BB5\u6897\u6982\uFF1A",e.synopsis,"","\u7247\u6BB5\u5173\u952E\u4E8B\u4EF6\uFF1A",...e.events.map(t=>`- ${t}`)].join(`
1033
+ `)}function nO(e){let t=[];for(let n of e){if(t.push(`\u7B2C${n.episodeNo}\u96C6 ${n.title||""}`.trim()),t.push(`\u5355\u53E5\uFF1A${n.oneLine}`),t.push(`\u6897\u6982\uFF1A${n.synopsis}`),n.events.length>0){t.push("\u5173\u952E\u4E8B\u4EF6\uFF1A");for(let o of n.events)t.push(`- ${o}`)}t.push("")}return t.join(`
1034
+ `).trim()}function oO(e){let t=[];for(let n of e){if(t.push(`\u7B2C${n.startEpisodeNo}-${n.endEpisodeNo}\u96C6`),t.push(`\u9636\u6BB5\u6897\u6982\uFF1A${n.synopsis}`),n.turns.length>0){t.push("\u5173\u952E\u8F6C\u6298\uFF1A");for(let o of n.turns)t.push(`- ${o}`)}if(n.openQuestions.length>0){t.push("\u672A\u89E3\u51B3\u60AC\u5FF5\uFF1A");for(let o of n.openQuestions)t.push(`- ${o}`)}t.push("")}return t.join(`
1035
+ `).trim()}function iO(e){return[`\u5F53\u524D\u9636\u6BB5\uFF1A\u7B2C${e.startEpisodeNo}-${e.endEpisodeNo}\u96C6`,"","\u5206\u96C6\u6897\u6982\uFF1A",e.text].join(`
1036
+ `)}function rO(e,t){if(e===null)throw new Error(`${t} scope missing`);return e}function sO(e,t){let n=e[0];if(!n||e.length!==1)throw new Error(`${t} reduce requires exactly one item`);return n}function aO(e){return e.map(t=>t.trim()).find(t=>t.length>0)??""}function ql(e){let t=new Set,n=[];for(let o of e.map(i=>i.trim()).filter(i=>i.length>0))t.has(o)||(t.add(o),n.push(o));return n}function cO(e){let t=e.replace(/\s+/g," ").trim();return t.length>50?t.slice(0,50):t}function dO(e,t,n){if(e==null||e==="")return t;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new x(`${n} must be a positive integer.`,{exitCode:B,errorCode:"NUMERIC_OPTION_INVALID",hint:`Pass ${n} ${t}.`,data:{expected:[`${n}: positive integer`],actual:[O(e)]}});return Math.floor(o)}function mc(e,t,n,o){return!o&&O(e[t]).trim()||O(e[t])===n?!1:(e[t]=n,!0)}function pO(e){return!O(e.synopsis).trim()||!O(e.theme).trim()||!O(e.logline).trim()||!O(e.style).trim()||re(e.main_characters).length===0}function lO(e){return{synopsis:O(e.synopsis).trim(),theme:O(e.theme).trim(),logline:O(e.logline).trim(),style:O(e.style).trim(),mainCharacters:re(e.main_characters).map(t=>({name:O(t.name).trim(),role:O(t.role).trim()})).filter(t=>t.name&&t.role)}}import*as bs from"node:fs";var ww=3;function Zl(e){return O(e.project_group_no||process.env.SANDBOX_PROJECT_GROUP_NO).trim()}function Wl(e){try{return Rl(e)}catch(t){throw t instanceof fe?Ko("SCRIPT API BLOCKED: gateway not configured",t):t}}function _w(e,t){let n=Zl(e);if(n&&n!==t.projectGroupNo)throw yw(t,`configured projectGroupNo=${n}`);let o=Wl(t.projectGroupNo);if(o.gatewayBase!==t.apiBaseUrl)throw yw(t,`configured apiBaseUrl=${o.gatewayBase}`);return o}function yw(e,t){return new x("The configured remote does not match this working copy.",{exitCode:k,errorCode:"WORKING_COPY_REMOTE_MISMATCH",hint:"Restore the checkout environment for this working copy, or checkout another file.",data:{expected:[`projectGroupNo=${e.projectGroupNo}`,`apiBaseUrl=${e.apiBaseUrl}`],actual:[t]}})}function Xl(e){let t;try{t=JSON.parse(bs.readFileSync(e,"utf-8"))}catch(n){throw new x("The local script is missing or invalid JSON.",{exitCode:k,errorCode:"SCRIPT_JSON_INVALID",hint:"Fix the local script JSON before continuing.",data:{actual:[e,n instanceof Error?n.message:String(n)]}})}if(!oe(t))throw new x("The script root must be a JSON object.",{exitCode:k,errorCode:"SCRIPT_ROOT_INVALID",hint:"Replace the file with a valid Script v3 JSON object.",data:{actual:[e,Array.isArray(t)?"array":typeof t]}});return t}function Ew(e){return String(e.code)==="9002"||e.message.includes("\u7248\u672C\u51B2\u7A81")}function hc(e){let t=e.status!==null&&e.status>=200&&e.status<300&&e.code===null;return e.status===null||e.status>=500||t}function xw(e){let t=Number(e.revision);if(!Number.isInteger(t)||t<0)throw new x("The gateway returned an invalid snapshot revision.",{exitCode:X,errorCode:"PUBLISH_OUTCOME_UNKNOWN",hint:"Inspect the remote script before retrying.",data:{actual:[JSON.stringify(e)]}});return t}function Sw(e,t){return new x("The publish outcome could not be confirmed after retrying.",{exitCode:X,errorCode:"PUBLISH_OUTCOME_UNKNOWN",hint:"Run publish again; it will inspect the latest snapshot before sending another patch.",data:{actual:[...t,`baseRevision=${e}`]}})}async function uO(e,t,n,o,i,r){let s=[];for(let c=1;c<=ww;c+=1){let a;try{a=await e.getSnapshot()}catch(p){if(p instanceof fe&&hc(p)){s.push(`snapshot attempt ${c}: ${p.message}`);continue}throw p instanceof fe?Ko("PUBLISH BLOCKED: snapshot query failed",p):p}if(a===null||!oe(a.script))throw new x("The managed working copy no longer has a remote script.",{exitCode:k,errorCode:"REMOTE_SCRIPT_NOT_FOUND",hint:"Publish a new unmanaged file to create the remote script, or restore the remote project.",data:{actual:[`projectGroupNo=${e.projectGroupNo}`]}});let d=xw(a);if(Je(a.script)===o&&a.validationStatus==="valid")return{revision:d,patchedFromRevision:d,attempts:c,recovered:d!==i.baseRevision};Gt(t,o);try{let p=await e.publishPatch({baseRevision:d,old:a.script,edited:n,validation:r}),l=oe(p)?Number(p.revision):Number.NaN;if(Number.isInteger(l)&&l>d)return{revision:l,patchedFromRevision:d,attempts:c,recovered:c>1};s.push(`patch attempt ${c}: invalid response ${JSON.stringify(p)}`)}catch(p){if(p instanceof fe&&(Ew(p)||hc(p))){s.push(`patch attempt ${c}: ${p.message}`);continue}throw p instanceof fe?Ko("PUBLISH BLOCKED: patch failed",p):p}}throw Sw(i.baseRevision,s)}async function fO(e,t,n,o,i){let r=[];for(let s=1;s<=ww;s+=1){let c;try{c=await e.getSnapshot()}catch(a){if(a instanceof fe&&hc(a)){r.push(`snapshot attempt ${s}: ${a.message}`);continue}throw a instanceof fe?Ko("PUBLISH BLOCKED: snapshot query failed",a):a}if(c!==null){let a=xw(c);if(oe(c.script)&&Je(c.script)===o&&c.validationStatus==="valid")return{revision:a,patchedFromRevision:0,attempts:s,recovered:!0};throw new x("An unmanaged local script cannot replace an existing remote script.",{exitCode:k,errorCode:"REMOTE_SCRIPT_EXISTS",hint:"Checkout the remote script, apply the local changes to that managed working copy, then publish.",data:{actual:[`projectGroupNo=${e.projectGroupNo}`,`revision=${a}`]}})}Gt(t,o);try{let a=await e.publishPatch({baseRevision:0,old:{},edited:n,validation:i}),d=oe(a)?Number(a.revision):Number.NaN;if(Number.isInteger(d)&&d>0)return{revision:d,patchedFromRevision:0,attempts:s,recovered:s>1};r.push(`patch attempt ${s}: invalid response ${JSON.stringify(a)}`)}catch(a){if(a instanceof fe&&(Ew(a)||hc(a))){r.push(`patch attempt ${s}: ${a.message}`);continue}throw a instanceof fe?Ko("PUBLISH BLOCKED: patch failed",a):a}}throw Sw(0,r)}async function Iw(e){let t=me(e),n=!!e.discard_local,o=Nr(t),i=Ds(t),r=bs.existsSync(t),s=Rr(t);if(r&&i===null&&!n)throw new x("The target is an unmanaged local script.",{exitCode:k,errorCode:"LOCAL_TARGET_EXISTS",hint:`Run \`scriptctl checkout --script-path ${t} --discard-local\` only if the local file may be discarded.`,data:{actual:[t]}});if(r&&i!==null&&!n&&Je(Xl(t))!==i.baseContentHash)throw new x("The working copy has unpublished local changes.",{exitCode:k,errorCode:"WORKING_COPY_DIRTY",hint:"Publish the local changes, or pass --discard-local to replace them with the remote snapshot.",data:{actual:[t,`baseRevision=${i.baseRevision}`]}});let c=i!==null&&!n?_w(e,i):Wl(Zl(e)||null),a;try{a=await c.getSnapshot()}catch(l){throw l instanceof fe?Ko("CHECKOUT BLOCKED: snapshot query failed",l):l}if(a===null||!oe(a.script))throw new x("No remote script_v2 snapshot exists for this project.",{exitCode:k,errorCode:"REMOTE_SCRIPT_NOT_FOUND",hint:"Use the ingest/create workflow and publish the first script instead of checkout.",data:{actual:[`projectGroupNo=${c.projectGroupNo}`]}});Mr(t,s);let d=Je(a.script);return Fe(t,a.script),Gs(t,{schemaVersion:1,projectGroupNo:c.projectGroupNo,apiBaseUrl:c.gatewayBase,baseRevision:Number(a.revision),baseContentHash:d}),[{text:n&&r?`Discarded the local file and checked out revision ${a.revision} to ${t}`:`Checked out revision ${a.revision} to ${t}`,data:{changed:!0,script_path:t,metadata_path:o.metadataPath,managed:!0,dirty:!1,discarded_local:n&&r,project_group_no:c.projectGroupNo,base_revision:Number(a.revision)}},G]}function Aw(e){let t=me(e),n=bs.existsSync(t),o=Ds(t),i=n&&o!==null?Je(Xl(t))!==o.baseContentHash:null;return[{text:o===null?`${t}: unmanaged local script`:`${t}: ${i?"dirty":"clean"} at revision ${o.baseRevision}`,data:{script_path:t,exists:n,managed:o!==null,dirty:i,...o===null?{}:{project_group_no:o.projectGroupNo,api_base_url:o.apiBaseUrl,base_revision:o.baseRevision}}},G]}async function kw(e){let t=me(e),n=Xl(t),o=Je(n),i=Ds(t);if(i!==null&&i.baseContentHash===o)return[{text:`No local changes; revision remains ${i.baseRevision}`,data:{changed:!1,published:!1,reason:"NO_CHANGES",revision:i.baseRevision,script_path:t}},G];let r=Ml(n);if(!r.passed)throw new x("The local script does not pass its declared Script version validation.",{exitCode:k,errorCode:"PUBLISH_VALIDATION_FAILED",hint:`Run \`scriptctl validate --script-path ${t}\`, repair the issues, then publish again.`,data:{actual:r.issues.slice(0,5).map(p=>`${p.path??"<root>"}: ${p.summary}`)}});let s=Bs(n).episodes.length,c={status:"valid",summary:{passed:!0,hasBlocking:!1,stats:r.stats??{},issueCount:0}};if(i!==null){let p=_w(e,i),l=await uO(p,t,n,o,i,c);return Gs(t,{schemaVersion:1,projectGroupNo:p.projectGroupNo,apiBaseUrl:p.gatewayBase,baseRevision:l.revision,baseContentHash:o}),await Nd(p,s),[{text:`Published local content over revision ${l.patchedFromRevision} \u2192 ${l.revision}`,data:{changed:!0,published:!0,created:!1,transport:"patch",script_path:t,project_group_no:p.projectGroupNo,base_revision:l.patchedFromRevision,revision:l.revision,attempts:l.attempts,recovered:l.recovered}},G]}let a=Wl(Zl(e)||null),d=await fO(a,t,n,o,c);return Gs(t,{schemaVersion:1,projectGroupNo:a.projectGroupNo,apiBaseUrl:a.gatewayBase,baseRevision:d.revision,baseContentHash:o}),await Nd(a,s),[{text:`Published revision ${d.patchedFromRevision} \u2192 ${d.revision}`,data:{changed:!0,published:!0,created:!0,transport:"patch",script_path:t,project_group_no:a.projectGroupNo,base_revision:d.patchedFromRevision,revision:d.revision,attempts:d.attempts,recovered:d.recovered}},G]}function bw(e,t,n){e.command("migrate").description("Create a newer Script schema copy through the registered migration chain").requiredOption("-p, --script-path <path>","Source Script JSON file").requiredOption("-o, --output <file>","Destination Script JSON file").requiredOption("--to <version>","Target Script version").option("--manifest <file>","Migration manifest output").option("--force","Replace existing migration artifacts").addHelpText("after",`
1035
1037
  Example:
1036
1038
  scriptctl migrate -p ./old-script.json -o ./script-v4.json --to 4
1037
- `).action(H(ow,t));let o=e.command("ingest").description("Convert source files into a Script v4 workspace").option("-s, --source-path <path>","Text, video or PDF comic file/directory").option("-w, --workspace-path <path>","Workspace directory","workspace").option("--llm-config <path>","LLM configuration file").option("--concurrency <n>","Maximum concurrent model calls").option("--fps <n>","Video sampling rate").option("--upload-mode <mode>","Video transport: file-api or base64 (default follows provider)").option("--video-output <format>","Video model output format: dsl or json (default dsl)").option("--video-provider <provider>","Video provider: gemini or doubao (explicit selection disables fallback)").option("--provider-base-url <url>","Selected video provider service root").option("--provider-api-key <key>","Provider API key (visible in process arguments; prefer --provider-api-key-env)").option("--provider-api-key-env <name>","Environment variable containing the provider API key").option("--provider-model <model>","Selected video provider model (Doubao defaults to ARK_MODEL)").option("--step","Process only the next unfinished video episode or comic chapter").option("--force","Rebuild completed stages").addHelpText("after",`
1039
+ `).action(H(sw,t));let o=e.command("ingest").description("Convert source files into a Script v4 workspace").option("-s, --source-path <path>","Text, video or PDF comic file/directory").option("-w, --workspace-path <path>","Workspace directory","workspace").option("--llm-config <path>","LLM configuration file").option("--concurrency <n>","Maximum concurrent model calls").option("--fps <n>","Video sampling rate").option("--upload-mode <mode>","Video transport: file-api or base64 (default follows provider)").option("--video-output <format>","Video model output format: dsl or json (default dsl)").option("--video-provider <provider>","Video provider: gemini or doubao (explicit selection disables fallback)").option("--provider-base-url <url>","Selected video provider service root").option("--provider-api-key <key>","Provider API key (visible in process arguments; prefer --provider-api-key-env)").option("--provider-api-key-env <name>","Environment variable containing the provider API key").option("--provider-model <model>","Selected video provider model (Doubao defaults to ARK_MODEL)").option("--step","Process only the next unfinished video episode or comic chapter").option("--force","Rebuild completed stages").addHelpText("after",`
1038
1040
  Example:
1039
1041
  scriptctl ingest --source-path ./draft.md --workspace-path ./workspace
1040
- `).action(H(r=>ky(r,n),t));o.command("status").description("Show ingest workspace progress").option("-w, --workspace-path <path>","Workspace directory").action(H(Oy,t)),o.command("skip").description("Manually accept the next failed video episode as empty").option("-w, --workspace-path <path>","Workspace directory").requiredOption("--episode <n>","Failed episode number").requiredOption("--reason <text>","Why this episode is being skipped").addHelpText("after",`
1042
+ `).action(H(r=>vy(r,n),t));o.command("status").description("Show ingest workspace progress").option("-w, --workspace-path <path>","Workspace directory").action(H(My,t)),o.command("skip").description("Manually accept the next failed video episode as empty").option("-w, --workspace-path <path>","Workspace directory").requiredOption("--episode <n>","Failed episode number").requiredOption("--reason <text>","Why this episode is being skipped").addHelpText("after",`
1041
1043
  Example:
1042
1044
  scriptctl ingest skip -w ./workspace --episode 7 --reason "provider policy block"
1043
- `).action(H(vy,t)),e.command("evidence").description("Generate local original-video reference frames from final Script v4 timestamps").option("-p, --script-path <path>","Final Script v4 JSON file").requiredOption("-s, --source-path <path>","Linked source-video file or episode directory").requiredOption("-w, --workspace-path <path>","Project workspace directory").option("--force","Re-extract frames even when deterministic output files already exist").addHelpText("after",`
1045
+ `).action(H(Ny,t)),e.command("evidence").description("Generate local original-video reference frames from final Script v4 timestamps").option("-p, --script-path <path>","Final Script v4 JSON file").requiredOption("-s, --source-path <path>","Linked source-video file or episode directory").requiredOption("-w, --workspace-path <path>","Project workspace directory").option("--force","Re-extract frames even when deterministic output files already exist").addHelpText("after",`
1044
1046
  Example:
1045
1047
  scriptctl evidence -p ./script.json -s /Volumes/NAS/videos -w ./workspace --force
1046
- `).action(H(Ry,t)),e.command("view").description("Render or serve the workspace review page").option("-w, --workspace-path <path>","Workspace directory","workspace").option("--watch","Serve and refresh the review page").option("--port <n>","HTTP server port").action(H(Py,t)),Ed(e.command("checkout")).description("Download a remote script into a managed local copy").option("--discard-local","Replace an existing dirty local copy").action(H(Ew,t)),te(e.command("status"),"read").description("Show local working-copy state").action(H(xw,t)),Ed(e.command("publish")).description("Validate and publish the local working copy").action(H(Sw,t)),te(e.command("create")).description("Create an empty script").option("--title <title>","Script title").option("--force","Replace an existing script file").action(H(Wy,t)),te(e.command("audit-assets"),"read").description("Audit asset consistency with an LLM").option("--llm-config <path>","LLM configuration file").option("-o, --output <path>","Audit JSON output file").action(H(r=>By(r,n),t));let i=e.command("synopsis").description("Generate synopsis fields with an LLM").action(()=>i.outputHelp());te(i.command("generate")).description("Generate synopsis fields with an LLM").option("--llm-config <path>","LLM configuration file").option("--concurrency <n>","Maximum concurrent model calls","30").option("--checkpoint <dir>","Checkpoint directory").option("--overwrite","Regenerate existing synopsis fields").option("--apply","Write generated fields").option("-n, --dry-run","Generate a preview without writing").action(H(r=>fw(r,n),t))}function gO(e,t=Wn){let n=new fO("scriptctl").description("Read, edit, ingest, and publish structured scripts").usage("<command> [options]").exitOverride().allowExcessArguments(!1).allowUnknownOption(!1).showHelpAfterError(!1).configureOutput({writeOut:o=>process.stdout.write(o),writeErr:()=>{}}).option("-j, --json","Output structured JSON").option("--format <format>","Output format (addr)").version(ji(),"-v, --version","Show the scriptctl version");return Iw(n,e,t),dg(n,e),hf(n,e),ag(n,e),Kf(n,e),n}function gc(e,t){let n=t.split("=",1)[0],o=e;for(;o;){let i=o.options.find(r=>r.short===n||r.long===n);if(i)return i;o=o.parent}}function kw(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<2)return{recognized:!1,json:!1,hasAttachedValue:!1};let n=!1;for(let o=1;o<t.length;o+=1){let i=gc(e,`-${t[o]}`);if(!i?.short)return{recognized:!1,json:!1,hasAttachedValue:!1};if(i.short==="-j"&&(n=!0),i.required||i.optional)return{recognized:!0,json:n,valueOption:i,hasAttachedValue:o<t.length-1}}return{recognized:!0,json:n,hasAttachedValue:!1}}function hO(e,t){return t==="--"?!0:t.startsWith("--")?gc(e,t)!==void 0:kw(e,t).recognized}function Aw(e,t,n){return n===void 0||n==="--"?!1:t.required?!hO(e,n):t.optional&&!n.startsWith("-")}function yO(e,t){let n=e;for(let o=0;o<t.length;o+=1){let i=t[o];if(i==="--")break;if(i.startsWith("--")){if(i==="--json")return!0;let s=gc(n,i);s&&!i.includes("=")&&Aw(n,s,t[o+1])&&(o+=1);continue}if(i.startsWith("-")){let s=kw(n,i);if(s.recognized&&s.json)return!0;s.recognized&&s.valueOption&&!s.hasAttachedValue&&Aw(n,s.valueOption,t[o+1])&&(o+=1);continue}let r=n.commands.find(s=>s.name()===i);r&&(n=r)}return!1}function wO(e,t){let n=e;for(let r=0;r<t.length;r+=1){let s=t[r];if(s.startsWith("-")){let a=gc(n,s);a&&!s.includes("=")&&(a.required||a.optional)&&(r+=1);continue}let c=n.commands.find(a=>a.name()===s);if(!c)break;n=c}let o=[],i=n;for(;i&&i.parent;)o.unshift(i.name()),i=i.parent;return["scriptctl",...o,"--help"].join(" ")}function _O(e){return e.message.replace(/^error:\s*/i,"").replace(/\.$/,"")}async function gK(e=null,t=Wn){Sf();let n=e??process.argv.slice(2),o={jsonMode:!1,exitCode:B},i=gO(o,t);if(o.jsonMode=yO(i,n),n.length===0)return i.outputHelp(),B;try{return await i.parseAsync(n,{from:"user"}),o.exitCode}catch(r){if(r instanceof mO)return r.code==="commander.help"||r.code==="commander.helpDisplayed"||r.code==="commander.version"?B:$r(new S(_O(r),{exitCode:J,errorCode:"USAGE_ERROR",hint:`Run '${wO(i,n)}'.`}),o.jsonMode);if(r instanceof S)return $r(r,o.jsonMode);if(r instanceof T)return $r(new S(hn(r.failure),{exitCode:70,errorCode:"RUNTIME_ERROR"}),o.jsonMode);let s=r instanceof Error?r.message:String(r);return $r(new S(s,{exitCode:70,errorCode:"RUNTIME_ERROR"}),o.jsonMode)}}export{gO as a,gK as b};
1048
+ `).action(H(Ly,t)),e.command("view").description("Render or serve the workspace review page").option("-w, --workspace-path <path>","Workspace directory","workspace").option("--watch","Serve and refresh the review page").option("--port <n>","HTTP server port").action(H(Vy,t)),Sd(e.command("checkout")).description("Download a remote script into a managed local copy").option("--discard-local","Replace an existing dirty local copy").action(H(Iw,t)),ee(e.command("status"),"read").description("Show local working-copy state").action(H(Aw,t)),Sd(e.command("publish")).description("Validate and publish the local working copy").action(H(kw,t)),ee(e.command("create")).description("Create an empty script").option("--title <title>","Script title").option("--force","Replace an existing script file").action(H(tw,t)),ee(e.command("audit-assets"),"read").description("Audit asset consistency with an LLM").option("--llm-config <path>","LLM configuration file").option("-o, --output <path>","Audit JSON output file").action(H(r=>jy(r,n),t));let i=e.command("synopsis").description("Generate synopsis fields with an LLM").action(()=>i.outputHelp());ee(i.command("generate")).description("Generate synopsis fields with an LLM").option("--model <profile>","Use this LLM profile for all synopsis stages").option("--llm-config <path>","LLM configuration file").option("--concurrency <n>","Maximum concurrent model calls","30").option("--checkpoint <dir>","Checkpoint directory").option("--overwrite","Regenerate existing synopsis fields").option("--apply","Write generated fields").option("-n, --dry-run","Generate a preview without writing").action(H(r=>hw(r,n),t))}function hO(e,t=Xn){let n=new mO("scriptctl").description("Read, edit, ingest, and publish structured scripts").usage("<command> [options]").exitOverride().allowExcessArguments(!1).allowUnknownOption(!1).showHelpAfterError(!1).configureOutput({writeOut:o=>process.stdout.write(o),writeErr:()=>{}}).option("-j, --json","Output structured JSON").option("--format <format>","Output format (addr)").version(ji(),"-v, --version","Show the scriptctl version");return bw(n,e,t),ug(n,e),wf(n,e),pg(n,e),Ff(n,e),n}function yc(e,t){let n=t.split("=",1)[0],o=e;for(;o;){let i=o.options.find(r=>r.short===n||r.long===n);if(i)return i;o=o.parent}}function vw(e,t){if(!t.startsWith("-")||t.startsWith("--")||t.length<2)return{recognized:!1,json:!1,hasAttachedValue:!1};let n=!1;for(let o=1;o<t.length;o+=1){let i=yc(e,`-${t[o]}`);if(!i?.short)return{recognized:!1,json:!1,hasAttachedValue:!1};if(i.short==="-j"&&(n=!0),i.required||i.optional)return{recognized:!0,json:n,valueOption:i,hasAttachedValue:o<t.length-1}}return{recognized:!0,json:n,hasAttachedValue:!1}}function yO(e,t){return t==="--"?!0:t.startsWith("--")?yc(e,t)!==void 0:vw(e,t).recognized}function Ow(e,t,n){return n===void 0||n==="--"?!1:t.required?!yO(e,n):t.optional&&!n.startsWith("-")}function wO(e,t){let n=e;for(let o=0;o<t.length;o+=1){let i=t[o];if(i==="--")break;if(i.startsWith("--")){if(i==="--json")return!0;let s=yc(n,i);s&&!i.includes("=")&&Ow(n,s,t[o+1])&&(o+=1);continue}if(i.startsWith("-")){let s=vw(n,i);if(s.recognized&&s.json)return!0;s.recognized&&s.valueOption&&!s.hasAttachedValue&&Ow(n,s.valueOption,t[o+1])&&(o+=1);continue}let r=n.commands.find(s=>s.name()===i);r&&(n=r)}return!1}function _O(e,t){let n=e;for(let r=0;r<t.length;r+=1){let s=t[r];if(s.startsWith("-")){let a=yc(n,s);a&&!s.includes("=")&&(a.required||a.optional)&&(r+=1);continue}let c=n.commands.find(a=>a.name()===s);if(!c)break;n=c}let o=[],i=n;for(;i&&i.parent;)o.unshift(i.name()),i=i.parent;return["scriptctl",...o,"--help"].join(" ")}function EO(e){return e.message.replace(/^error:\s*/i,"").replace(/\.$/,"")}async function hj(e=null,t=Xn){Af();let n=e??process.argv.slice(2),o={jsonMode:!1,exitCode:G},i=hO(o,t);if(o.jsonMode=wO(i,n),n.length===0)return i.outputHelp(),G;try{return await i.parseAsync(n,{from:"user"}),o.exitCode}catch(r){if(r instanceof gO)return r.code==="commander.help"||r.code==="commander.helpDisplayed"||r.code==="commander.version"?G:Gr(new x(EO(r),{exitCode:B,errorCode:"USAGE_ERROR",hint:`Run '${_O(i,n)}'.`}),o.jsonMode);if(r instanceof x)return Gr(r,o.jsonMode);if(r instanceof T)return Gr(new x(hn(r.failure),{exitCode:70,errorCode:"RUNTIME_ERROR"}),o.jsonMode);let s=r instanceof Error?r.message:String(r);return Gr(new x(s,{exitCode:70,errorCode:"RUNTIME_ERROR"}),o.jsonMode)}}export{hO as a,hj as b};