@lingjingai/scriptctl 0.63.20 → 0.64.2

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 Mk,CommanderError as Lk}from"commander";import*as Ca from"node:crypto";import*as Xo from"node:fs";import*as zi from"node:path";import*as Re from"node:fs";import*as Et from"node:path";var qr=class{workspace;constructor(t){this.workspace=t}get sourceText(){return Et.join(this.workspace,"source.txt")}get directDir(){return Et.join(this.workspace,"draft","scriptctl","direct")}get directScript(){return Et.join(this.directDir,"script.initial.json")}get validation(){return Et.join(this.directDir,"validation.json")}get runState(){return Et.join(this.directDir,"run_state.json")}get episodeResultsDir(){return Et.join(this.directDir,"episode_results")}get batchResultsDir(){return Et.join(this.directDir,"batch_results")}outputScript(t){return Et.join(t,"script.json")}};function ry(e){let t="";for(let n of e)n==="*"?t+="[^/]*":n==="?"?t+="[^/]":".+^$()[]{}|\\".includes(n)?t+="\\"+n:t+=n;return new RegExp("^"+t+"$")}var Pa=class{exists(t){return Re.existsSync(t)}readText(t){return Re.readFileSync(t,"utf-8")}writeText(t,n){Re.mkdirSync(Et.dirname(t),{recursive:!0}),Re.writeFileSync(t,n,"utf-8")}readJson(t){return JSON.parse(Re.readFileSync(t,"utf-8"))}writeJson(t,n){this.writeText(t,JSON.stringify(n,null,2)+`
2
- `)}list(t,n="*"){if(!Re.existsSync(t))return[];let o=ry(n),i=Re.readdirSync(t),r=[];for(let s of i)o.test(s)&&r.push(Et.join(t,s));return r.sort(),r}delete(t){Re.existsSync(t)&&Re.unlinkSync(t)}deleteTree(t){Re.existsSync(t)&&Re.rmSync(t,{recursive:!0,force:!0})}copyToPath(t,n){Re.mkdirSync(Et.dirname(n),{recursive:!0}),Re.copyFileSync(t,n)}},Zr=new Pa;var B=0,J=64,b=66,me=70,Dn=78,rl=30;var Dk=zi.join("draft","scriptctl","direct"),sy=zi.join("workspace","script.json");var sl=["\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"],al=new Set(["actor","location","prop"]);var Gk=`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 lb,CommanderError as ub}from"commander";import*as ec from"node:crypto";import*as fi from"node:fs";import*as ir from"node:path";import*as Me from"node:fs";import*as bt from"node:path";var ls=class{workspace;constructor(t){this.workspace=t}get sourceText(){return bt.join(this.workspace,"source.txt")}get directDir(){return bt.join(this.workspace,"draft","scriptctl","direct")}get directScript(){return bt.join(this.directDir,"script.initial.json")}get validation(){return bt.join(this.directDir,"validation.json")}get runState(){return bt.join(this.directDir,"run_state.json")}get episodeResultsDir(){return bt.join(this.directDir,"episode_results")}get batchResultsDir(){return bt.join(this.directDir,"batch_results")}outputScript(t){return bt.join(t,"script.json")}};function Vy(e){let t="";for(let n of e)n==="*"?t+="[^/]*":n==="?"?t+="[^/]":".+^$()[]{}|\\".includes(n)?t+="\\"+n:t+=n;return new RegExp("^"+t+"$")}var Xa=class{exists(t){return Me.existsSync(t)}readText(t){return Me.readFileSync(t,"utf-8")}writeText(t,n){Me.mkdirSync(bt.dirname(t),{recursive:!0}),Me.writeFileSync(t,n,"utf-8")}readJson(t){return JSON.parse(Me.readFileSync(t,"utf-8"))}writeJson(t,n){this.writeText(t,JSON.stringify(n,null,2)+`
2
+ `)}list(t,n="*"){if(!Me.existsSync(t))return[];let o=Vy(n),i=Me.readdirSync(t),r=[];for(let s of i)o.test(s)&&r.push(bt.join(t,s));return r.sort(),r}delete(t){Me.existsSync(t)&&Me.unlinkSync(t)}deleteTree(t){Me.existsSync(t)&&Me.rmSync(t,{recursive:!0,force:!0})}copyToPath(t,n){Me.mkdirSync(bt.dirname(n),{recursive:!0}),Me.copyFileSync(t,n)}},us=new Xa;var J=0,G=64,k=66,me=70,Wn=78,Rl=30;var _b=ir.join("draft","scriptctl","direct"),$y=ir.join("workspace","script.json");var Ml=["\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"],Ll=new Set(["actor","location","prop"]);var Eb=`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 Mk,CommanderError as Lk}from"commander";import*as Ca 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`+sl.join(" / ")+`>
82
+ worldview: <\u4E16\u754C\u89C2\uFF0C\u53D6\u8FD9\u4E9B\u679A\u4E3E\u4E4B\u4E00\uFF1A`+Ml.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
- `,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 ay(e){return new qr(e)}function cl(e){return ay(e).directDir}function Se(e){let t=e.script_path??e.scriptPath;return zi.resolve(typeof t=="string"&&t.length>0?t:sy)}function Hi(e){return Zr.readJson(e)}function Ta(e,t){Zr.writeJson(e,t)}function xo(e){return Zr.exists(e)}function Ie(e){return Ca.createHash("sha256").update(e,"utf-8").digest("hex")}function Va(e){let t=Ca.createHash("sha256"),n=Xo.openSync(e,"r");try{let o=Buffer.alloc(1048576);for(;;){let i=Xo.readSync(n,o,0,o.length,null);if(i<=0)break;t.update(o.subarray(0,i))}}finally{Xo.closeSync(n)}return t.digest("hex")}var _t={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 xt(e,t){return typeof e=="string"&&t.some(n=>n===e)}function dl(e,t){switch(e){case"policy":return xt(t,_t.policy)?{failure_type:e,failure_code:t}:null;case"network":return xt(t,_t.network)?{failure_type:e,failure_code:t}:null;case"timeout":return xt(t,_t.timeout)?{failure_type:e,failure_code:t}:null;case"rate_limit":return xt(t,_t.rate_limit)?{failure_type:e,failure_code:t}:null;case"authentication":return xt(t,_t.authentication)?{failure_type:e,failure_code:t}:null;case"authorization":return xt(t,_t.authorization)?{failure_type:e,failure_code:t}:null;case"provider":return xt(t,_t.provider)?{failure_type:e,failure_code:t}:null;case"media":return xt(t,_t.media)?{failure_type:e,failure_code:t}:null;case"response":return xt(t,_t.response)?{failure_type:e,failure_code:t}:null;case"pipeline":return xt(t,_t.pipeline)?{failure_type:e,failure_code:t}:null;case"validation":return xt(t,_t.validation)?{failure_type:e,failure_code:t}:null;case"cancelled":return xt(t,_t.cancelled)?{failure_type:e,failure_code:t}:null;case"unknown":return xt(t,_t.unknown)?{failure_type:e,failure_code:t}:null;default:return null}}function St(e,t){return{...e,...t}}function ei(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 Qi(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 pl(e,t){if(e.length===0)return St({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)?ei(n):{failure_type:"provider",failure_code:"attempts_exhausted"};return St(i,{retryable:e.some(r=>r.retryable),message:t})}function tn(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 kl from"node:crypto";import*as bl from"node:fs";import*as Ol from"node:path";import*as wl from"node:crypto";var wn=["action","dialogue","inner_thought","transition"],Vt=new Set(wn),En=["system","broadcast","offscreen","group"],So=new Set(En),_n=["featured","background"],It=new Set(_n),ti=["\u4E3B\u89D2","\u914D\u89D2"],Gn=new Set(ti),Wr=["day","night","dawn","dusk"],$a=new Set(Wr);function Fi(e){return typeof e=="string"&&$a.has(e)}var Da=["interior","exterior"],ll=new Set(Da);function nt(e){return e.normalize("NFKC").toLowerCase()}function ul(e){return JSON.stringify([e.code,e.path,e.message])}function Ga(e){let t=new Map;for(let n of e){let o=ul(n);t.set(o,(t.get(o)??0)+1)}return t}function Ja(e,t){if(e.ok||t.errors.length>=e.errors.length)return!1;let n=Ga(e.errors),o=Ga(t.errors);for(let[i,r]of o)if(r>(n.get(i)??0))return!1;return!0}function Ba(e,t){let n=Ga(e),o=[];for(let i of t){let r=ul(i),s=n.get(r)??0;s>0?n.set(r,s-1):o.push(i)}return o}import{customAlphabet as cy}from"nanoid";var ni="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Ka=6,oi={episode:"ep",scene:"scn",action:"ac",actor:"act",location:"loc",prop:"prp",state:"st"},dy=cy(ni,Ka),py=`[${ni}]`,fl=Object.fromEntries(Object.entries(oi).map(([e,t])=>[e,new RegExp(`^${t}${py}{${Ka}}$`)]));function V(e,t){return typeof t=="string"&&fl[e].test(t)}var ja="ID_SPACE_EXHAUSTED";function Yi(e,t=new Set,n=dy){let o=oi[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:ja})}var We=class extends Error{input;constructor(t,n){super(n),this.input=t,this.name="TimestampParseError"}},ly=/^(\d+):(\d{2})(?:\.(\d{1,3}))?$/,uy=/^(\d+):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/;function ml(e){return e?Number(e.padEnd(3,"0")):0}function gl(e,t){if(!Number.isSafeInteger(t))throw new We(e,"Timestamp exceeds the supported numeric range.");return t}function hl(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 Jn(e){let t=e.trim();if(!t)throw new We(e,"Timestamp must not be empty.");let n=t.match(uy);if(n){let a=Number(n[1]),d=Number(n[2]),p=Number(n[3]),l=n[4];if(d>59)throw new We(e,"Hour-form timestamps require minutes between 00 and 59.");if(p>59)throw new We(e,"Timestamp seconds must be between 00 and 59.");let f=gl(e,((a*60+d)*60+p)*1e3+ml(l));return{canonical:hl(f,l),milliseconds:f,fractionDigits:l?.length??0}}let o=t.match(ly);if(!o)throw new We(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 We(e,"Timestamp seconds must be between 00 and 59.");let c=gl(e,(i*60+r)*1e3+ml(s));return{canonical:hl(c,s),milliseconds:c,fractionDigits:s?.length??0}}function fy(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 Xr(e,t,n){let o=null;e.forEach((i,r)=>{let s=fy(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=Jn(s)}catch(d){if(!(d instanceof We))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 At=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xn=e=>Array.isArray(e),xe=e=>typeof e=="string",my=["state_changes","actor_id","speakers","lines"];function lt(e){let t=[],n=[],o=(u,g,m,h)=>t.push({code:u,path:g,message:m,...h?{repair_hint:h}:{}}),i=(u,g,m)=>n.push({code:u,path:g,message:m});if(!At(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"])xe(e[u])||o("field",`$.${u}`,`${u} must be a string`);let r=new Map,s=new Map,c=new Map,a=(u,g,m,h,w)=>{if(!xn(u)){o("field",w,`${w} must be an array`);return}u.forEach((y,E)=>{let I=`${w}[${E}]`;if(!At(y)){o("asset",I,"asset must be an object");return}let _=y[m];if(!xe(_)){o("asset_id",`${I}.${m}`,`${m} required`);return}if(s.has(_)&&o("dup_id",`${I}.${m}`,`duplicate id ${_}`),s.set(_,g),!xe(y[h]))o("asset_name",`${I}.${h}`,`${h} required`);else if(g==="actor"){let O=nt(y[h]),S=c.get(O);S!==void 0?o("dup_actor_name",`${I}.${h}`,`actor name ${y[h]} already belongs to ${S}`):c.set(O,_)}(!xe(y.importance)||!_n.includes(y.importance))&&o("importance",`${I}.importance`,`importance must be one of ${_n.join("|")}`),xe(y.description)||o("asset_desc",`${I}.description`,"description must be a string");let A=new Set,k=new Set,P=0;!xn(y.states)||y.states.length===0?o("states",`${I}.states`,"states must be a non-empty array"):y.states.forEach((O,S)=>{let L=`${I}.states[${S}]`;if(!At(O)||!xe(O.state_id)){o("state_id",L,"state_id required");return}A.has(O.state_id)&&o("dup_state",L,`duplicate state_id ${O.state_id}`),A.add(O.state_id),O.state_id==="default"&&P++,xe(O.state_name)?(k.has(O.state_name)&&o("dup_state_name",`${L}.state_name`,`duplicate state_name ${O.state_name}`),k.add(O.state_name)):o("state_name",`${L}.state_name`,"state_name required")}),xn(y.states)&&P!==1&&o("default_state",`${I}.states`,`exactly one 'default' state required, found ${P}`),r.set(_,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,m,h)=>{if(s.get(u)!==m){o("ref",h,`${m} ${u} not found`);return}g!==void 0&&(!xe(g)||!r.get(u)?.has(g))&&o("state_ref",h,`state ${String(g)} not materialized on ${u}`)},p=(u,g,m,h)=>{if(u===void 0){o("field",h,`${h} required (may be empty array)`);return}if(!xn(u)){o("field",h,`${h} must be an array`);return}u.forEach((w,y)=>{if(!At(w)||!xe(w[m])){o("ref",`${h}[${y}]`,`${m} required`);return}d(w[m],w.state_id,g,`${h}[${y}]`)})},l=(u,g,m,h)=>{if(!At(u)){o("action",g,"action must be an object");return}for(let y of my)y in u&&o("legacy_field",`${g}.${y}`,`v3 forbids action.${y}`);let w=u.type;if((!xe(w)||!wn.includes(w))&&o("action_type",`${g}.type`,`invalid action type ${String(w)}`),xe(u.content)||o("content",`${g}.content`,"content must be a plain-text string"),w==="dialogue"||w==="inner_thought"){let y=u.speaker;if(!At(y))o("speaker",`${g}.speaker`,"dialogue/inner_thought needs a speaker");else if("kind"in y)(!xe(y.kind)||!En.includes(y.kind))&&o("speaker_kind",`${g}.speaker.kind`,"invalid non-actor speaker kind");else if(xe(y.actor_id)){if(d(y.actor_id,y.state_id,"actor",`${g}.speaker`),!m.has(y.actor_id)){let E=r.get(y.actor_id),I=xe(y.state_id)&&E?.has(y.state_id)?y.state_id:E?.has("default")?"default":E?.values().next().value,_=h&&I?`scriptctl scene-ref ${h} actor:${y.actor_id} --state ${I} -p "$SCRIPT"`:void 0;o("actor_not_in_scene",`${g}.speaker.actor_id`,`actor ${y.actor_id} is not referenced by this scene`,_)}}else o("speaker",`${g}.speaker`,"speaker needs actor_id or kind")}},f=e.episodes;return xn(f)?f.forEach((u,g)=>{let m=`$.episodes[${g}]`;if(!At(u)||!xe(u.episode_id)){o("episode_id",m,"episode_id required");return}if(!xn(u.scenes)){o("scenes",`${m}.scenes`,"scenes must be an array");return}u.scenes.forEach((h,w)=>{let y=`${m}.scenes[${w}]`;if(!At(h)){o("scene",y,"scene must be an object");return}"context"in h&&o("legacy_field",`${y}.context`,"v3 forbids scene.context"),xe(h.scene_id)||o("scene_id",y,"scene_id required");let E=h.environment;E===void 0||At(E)&&(!xe(E.time)||E.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!At(E)||E.space!==void 0&&!xe(E.space)||!xe(E.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):Fi(E.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk");let I=h.location;if(I!==null&&(!At(I)||!xe(I.location_id)?o("location",`${y}.location`,"location must be null or {location_id}"):d(I.location_id,I.state_id,"location",`${y}.location`)),p(h.actors,"actor","actor_id",`${y}.actors`),p(h.props,"prop","prop_id",`${y}.props`),xn(h.props)){let A=new Set;h.props.forEach((k,P)=>{!At(k)||!xe(k.prop_id)||(A.has(k.prop_id)&&o("dup_prop_ref",`${y}.props[${P}]`,`duplicate prop ref ${k.prop_id}`),A.add(k.prop_id))})}let _=new Set(xn(h.actors)?h.actors.filter(A=>At(A)).map(A=>A.actor_id).filter(A=>xe(A)):[]);if(!xn(h.actions))o("actions",`${y}.actions`,"actions must be an array");else{let A=xe(h.scene_id)?`${u.episode_id}/${h.scene_id}`:void 0;h.actions.forEach((k,P)=>l(k,`${y}.actions[${P}]`,_,A)),Xr(h.actions,`${y}.actions`,o)}})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}var ot=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ce=e=>typeof e=="string",nn=e=>Array.isArray(e);function za(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(za):ot(e)&&Object.values(e).every(za)}function ii(e,t,n){e!==void 0&&(!ot(e)||!Object.values(e).every(za))&&n("extend",t,"extend must be an object containing JSON values")}function gy(e){for(let t=1;t<e.length;t++)if(e[t-1]>e[t])return!1;return!0}function Me(e){let t=[],n=[],o=(u,g,m,h)=>t.push({code:u,path:g,message:m,...h?{repair_hint:h}:{}}),i=(u,g,m,h)=>n.push({code:u,path:g,message:m,...h?{repair_hint:h}:{}});if(!ot(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"])ce(e[u])||o("field",`$.${u}`,`${u} must be a string`);for(let u of["worldview_raw","synopsis","logline","theme"])e[u]!==void 0&&!ce(e[u])&&o("field",`$.${u}`,`${u} must be a string`);e.main_characters!==void 0&&(!nn(e.main_characters)||!e.main_characters.every(u=>ot(u)&&ce(u.name)&&ce(u.role)))&&o("main_characters","$.main_characters","main_characters must contain {name, role} string records"),ii(e.extend,"$.extend",o);let r=new Map,s=new Map,c=new Set,a=(u,g,m,h,w)=>{if(!nn(u)){o("field",w,`${w} must be an array`);return}let y=new Set;u.forEach((E,I)=>{let _=`${w}[${I}]`;if(!ot(E)){o("asset",_,"asset must be an object");return}let A=E[m];if(!V(g,A)){o("asset_id",`${_}.${m}`,`${m} must be ${g} ID`);return}if(y.has(A)&&o("dup_id",`${_}.${m}`,`duplicate ${m} ${A}`),y.add(A),r.set(A,g),!ce(E[h])||E[h].trim()==="")o("asset_name",`${_}.${h}`,`${h} must be a non-empty string`);else if(g==="actor"){let S=E[h].trim().toLocaleLowerCase();c.has(S)&&o("dup_actor_name",`${_}.${h}`,`duplicate actor name ${E[h]}`),c.add(S)}if((!ce(E.importance)||!_n.includes(E.importance))&&o("importance",`${_}.importance`,`importance must be ${_n.join("|")}`),g==="actor"&&E.role_type!==void 0&&(!ce(E.role_type)||!ti.includes(E.role_type))&&o("role_type",`${_}.role_type`,`role_type must be ${ti.join("|")}`),ce(E.description)||o("asset_desc",`${_}.description`,"description must be a string"),E.aliases!==void 0&&(!nn(E.aliases)||!E.aliases.every(ce)))o("aliases",`${_}.aliases`,"aliases must be an array of strings");else if(nn(E.aliases)&&E.aliases.every(ce)){let S=new Set,L=ce(E[h])?E[h]:"";E.aliases.forEach((T,U)=>{T===""&&o("alias_empty",`${_}.aliases[${U}]`,"alias must not be empty"),T===L&&o("alias_equals_name",`${_}.aliases[${U}]`,"alias must differ from the asset name"),S.has(T)&&o("dup_alias",`${_}.aliases[${U}]`,`duplicate alias ${T}`),S.add(T)})}ii(E.extend,`${_}.extend`,o);let k=new Set,P=new Set,O=0;!nn(E.states)||E.states.length===0?o("states",`${_}.states`,"states must be a non-empty array"):E.states.forEach((S,L)=>{let T=`${_}.states[${L}]`;if(!ot(S)){o("state",T,"state must be an object");return}let U=S.state_id;if(U!=="default"&&!V("state",U)){o("state_id",`${T}.state_id`,"state_id must be default or st plus six Base58 characters");return}k.has(U)&&o("dup_state",`${T}.state_id`,`duplicate state_id ${U}`),k.add(U),U==="default"&&O++,!ce(S.state_name)||S.state_name.trim()===""?o("state_name",`${T}.state_name`,"state_name must be a non-empty string"):(P.has(S.state_name)&&o("dup_state_name",`${T}.state_name`,`duplicate state_name ${S.state_name}`),P.add(S.state_name)),ce(S.description)||o("state_description",`${T}.description`,"description must be a string"),ii(S.extend,`${T}.extend`,o)}),O!==1&&o("default_state",`${_}.states`,`exactly one default state required, found ${O}`),s.set(A,k)})};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,m)=>{if(!nn(g)||g.length===0||!g.every(ce))return o("state_ids",m,"state_ids must be a non-empty array of strings"),[];let h=g,w=new Set;return h.forEach((y,E)=>{w.has(y)&&o("dup_state_ref",`${m}[${E}]`,`duplicate state_id ${y}`),w.add(y),s.get(u)?.has(y)||o("state_ref",`${m}[${E}]`,`state ${y} not found on ${u}`)}),gy(h)||o("state_ids_order",m,"state_ids must be sorted lexically"),h},p=new Set,l=new Set,f=new Set;return nn(e.episodes)?e.episodes.forEach((u,g)=>{let m=`$.episodes[${g}]`;if(!ot(u)){o("episode",m,"episode must be an object");return}V("episode",u.episode_id)?(p.has(u.episode_id)&&o("dup_episode_id",`${m}.episode_id`,`duplicate episode_id ${u.episode_id}`),p.add(u.episode_id)):o("episode_id",`${m}.episode_id`,"episode_id must be ep plus six Base58 characters");for(let h of["title","synopsis"])u[h]!==void 0&&!ce(u[h])&&o("field",`${m}.${h}`,`${h} must be a string`);if(ii(u.extend,`${m}.extend`,o),!nn(u.scenes)){o("scenes",`${m}.scenes`,"scenes must be an array");return}u.scenes.forEach((h,w)=>{let y=`${m}.scenes[${w}]`;if(!ot(h)){o("scene",y,"scene must be an object");return}V("scene",h.scene_id)?(l.has(h.scene_id)&&o("dup_scene_id",`${y}.scene_id`,`duplicate scene_id ${h.scene_id}`),l.add(h.scene_id)):o("scene_id",`${y}.scene_id`,"scene_id must be scn plus six Base58 characters"),ii(h.extend,`${y}.extend`,o),h.environment===void 0||ot(h.environment)&&(!ce(h.environment.time)||h.environment.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!ot(h.environment)||h.environment.space!==void 0&&!ce(h.environment.space)||!ce(h.environment.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):Fi(h.environment.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk"),h.location!==null&&(!ot(h.location)||!V("location",h.location.location_id)?o("location",`${y}.location`,"location must be null or a typed v4 location reference"):("state_id"in h.location&&o("v3_field",`${y}.location.state_id`,"Script v4 scene references use state_ids"),r.get(h.location.location_id)!=="location"&&o("location_ref",`${y}.location.location_id`,`location ${h.location.location_id} not found`),d(h.location.location_id,h.location.state_ids,`${y}.location.state_ids`)));let E=new Map,I=(_,A,k,P)=>{if(!nn(_)){o("field",P,`${P} must be an array`);return}let O=new Set;_.forEach((S,L)=>{let T=`${P}[${L}]`;if(!ot(S)||!V(A,S[k])){o("ref",T,`${k} must be a typed v4 ID`);return}let U=S[k];"state_id"in S&&o("v3_field",`${T}.state_id`,"Script v4 scene references use state_ids"),O.has(U)&&o("dup_asset_ref",`${T}.${k}`,`duplicate ${A} ref ${U}`),O.add(U),r.get(U)!==A&&o("asset_ref",`${T}.${k}`,`${A} ${U} not found`);let R=d(U,S.state_ids,`${T}.state_ids`);A==="actor"&&E.set(U,new Set(R))})};if(I(h.actors,"actor","actor_id",`${y}.actors`),I(h.props,"prop","prop_id",`${y}.props`),!nn(h.actions)){o("actions",`${y}.actions`,"actions must be an array");return}h.actions.forEach((_,A)=>{let k=`${y}.actions[${A}]`;if(!ot(_)){o("action",k,"action must be an object");return}if(V("action",_.action_id)?(f.has(_.action_id)&&o("dup_action_id",`${k}.action_id`,`duplicate action_id ${_.action_id}`),f.add(_.action_id)):o("action_id",`${k}.action_id`,"action_id must be ac plus six Base58 characters"),(!ce(_.type)||!wn.includes(_.type))&&o("action_type",`${k}.type`,`invalid action type ${String(_.type)}`),ce(_.content)||o("content",`${k}.content`,"content must be a string"),"emotion"in _&&o("v3_field",`${k}.emotion`,"Script v4 does not allow emotion"),ii(_.extend,`${k}.extend`,o),_.type==="dialogue"||_.type==="inner_thought")if(_.parenthetical!==void 0&&!ce(_.parenthetical)&&o("parenthetical",`${k}.parenthetical`,"parenthetical must be a string"),!ot(_.speaker))o("speaker",`${k}.speaker`,"dialogue/inner_thought requires a speaker");else if(ce(_.speaker.actor_id)){("kind"in _.speaker||"label"in _.speaker)&&o("speaker_shape",`${k}.speaker`,"actor speaker cannot contain non-actor speaker fields");let O=_.speaker.actor_id;(!V("actor",O)||r.get(O)!=="actor")&&o("speaker_actor",`${k}.speaker.actor_id`,`actor ${O} not found`);let S=E.get(O),L=s.get(O),T=ce(_.speaker.state_id)&&L?.has(_.speaker.state_id)?_.speaker.state_id:void 0,U=L?.has("default")?"default":L?.values().next().value,R=T?[T]:U?[U]:[],j=V("scene",h.scene_id)&&V("actor",O)&&R.length>0?`scriptctl scene-ref ${h.scene_id} ${O} ${R.map(Z=>`--state ${Z}`).join(" ")} -p "$SCRIPT"`:void 0;if(S||o("actor_not_in_scene",`${k}.speaker.actor_id`,`actor ${O} is not referenced by this scene`,j),_.speaker.state_id!==void 0&&(!ce(_.speaker.state_id)||!S?.has(_.speaker.state_id))){let Z=T?[...new Set([...S??[],T])].sort():[],Oe=V("scene",h.scene_id)&&V("actor",O)&&Z.length>0?`scriptctl scene-ref ${h.scene_id} ${O} ${Z.map(K=>`--state ${K}`).join(" ")} -p "$SCRIPT"`:j;o("speaker_state",`${k}.speaker.state_id`,`speaker state ${String(_.speaker.state_id)} is not in this scene's actor state_ids`,Oe)}}else ce(_.speaker.kind)?(("actor_id"in _.speaker||"state_id"in _.speaker)&&o("speaker_shape",`${k}.speaker`,"non-actor speaker cannot contain actor speaker fields"),En.includes(_.speaker.kind)||o("speaker_kind",`${k}.speaker.kind`,"invalid non-actor speaker kind"),_.speaker.label!==void 0&&!ce(_.speaker.label)&&o("speaker_label",`${k}.speaker.label`,"speaker label must be a string")):o("speaker",`${k}.speaker`,"speaker needs actor_id or kind");else"parenthetical"in _&&o("parenthetical_type",`${k}.parenthetical`,"parenthetical only belongs to speaking actions"),"speaker"in _&&o("speaker_type",`${k}.speaker`,"speaker only belongs to speaking actions");if(_.transition_prompt!==void 0){let O=_.transition_prompt;!ot(O)||!ce(O.target)||!ce(O.process)||O.process===""||!ce(O.contrast)||O.contrast===""?o("transition_prompt",`${k}.transition_prompt`,"transition_prompt requires non-empty target/process/contrast"):r.has(O.target)||o("transition_target",`${k}.transition_prompt.target`,`asset ${O.target} not found`)}}),Xr(h.actions,`${y}.actions`,o)})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}function Io(e,t=new Set,n){try{return n?Yi(e,t,n):Yi(e,t)}catch(o){throw o?.code!==ja?o:new x(`Could not generate an unused ${e} ID.`,{exitCode:b,errorCode:"ID_SPACE_RETRY_EXHAUSTED",hint:"Retry the command. If this persists, inspect the configured ID generator."})}}function we(e,t=[]){throw new x(e,{exitCode:b,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 Sn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Y(e,t=""){return String(e??"").replace(/\s+/gu," ").trim()||t}function hy(e,t){let n=Number(e);return(!Number.isSafeInteger(n)||n<1)&&we(`${t} must be a positive integer.`,[e]),n}function yy(e){return e===void 0?{}:(Sn(e)||we("Action extensions must be an object."),structuredClone(e))}function wy(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 Bn(e,t,n){for(let o=0;o<128;o+=1){let i=wl.createHash("sha256").update(`${e}:${t}:${o}`).digest(),r="";for(let c=0;c<6;c+=1)r+=ni[i[c]%ni.length];let s=`${oi[e]}${r}`;if(!n.has(s))return n.add(s),s}we(`Could not allocate a stable ${e} ID.`)}function Ey(e){let t=Y(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 _y(e){return`${Math.floor(e/6e4)}:${String(Math.floor(e%6e4/1e3)).padStart(2,"0")}.${String(e%1e3).padStart(3,"0")}`}function xy(e){let t=Number(e.extend?.duration_ms??e.extend?.rewrite_duration_ms);return Number.isFinite(t)&&t>0?Math.round(t):1200}function Sy(e){let t=0;for(let n of e.scenes.flatMap(o=>o.actions))t=(Ey(n.extend?.timestamp)??t)+xy(n);return t}function El(e){return e===void 0?[]:((!Array.isArray(e)||!e.every(Sn))&&we("Asset variants must be an array of readable objects."),e)}function Iy(e,t){let n=e.assets;if(n===void 0)return[];Sn(n)||we("assets must be an object.");let o=n[t];return o===void 0?[]:((!Array.isArray(o)||!o.every(Sn))&&we(`assets.${t} must be an array.`),o)}function Ay(e,t){return e==="actors"?t.actor_name:e==="locations"?t.location_name:t.prop_name}function ky(e,t){return e[t]}function by(e,t){return[Ay(e,t),...t.aliases??[]].map(nt)}function _l(e,t,n){let o=nt(n);return Iy(e,t).find(i=>[i.name,...Array.isArray(i.aliases)?i.aliases:[]].map(r=>nt(Y(r))).includes(o))??null}function xl(e,t){if(!e)return null;let n=nt(t);return El(e.variants).find(o=>{let i=nt(Y(o.name));return i===n||["default","\u9ED8\u8BA4"].includes(n)&&["default","\u9ED8\u8BA4"].includes(i)})??null}function Sl(e,t,n){let o=xl(e,n),i=Y(o?.description);return(!o||!i)&&we(`${t}/${n} is a new variant and requires a readable assets declaration with a self-contained description.`),o}function Oy(e,t){let n=Y(t?.name);return n&&!["default","\u9ED8\u8BA4"].includes(nt(n))?n:e==="actors"?"\u57FA\u7840\u9020\u578B":e==="locations"?"\u5E38\u89C4\u5E03\u7F6E":"\u57FA\u7840\u5916\u89C2"}function vy(e,t,n,o,i,r){let s=_l(t,n,o);s||we(`${o} is not an existing ${n} asset and has no readable declaration.`);let c=Y(s.name,o),a=El(s.variants),d=xl(s,"\u9ED8\u8BA4")??a[0]??null;n==="actors"&&!Y(s.description)&&we(`${c} requires an identity description separate from its appearance variants.`),n==="actors"&&!Y(d?.description)&&we(`${c} requires its first variant to provide a self-contained base appearance description.`);let p=[{state_id:"default",state_name:Oy(n,d),description:Y(d?.description,Y(s.description,`${c}\u7684\u57FA\u7840\u53C2\u8003\u5916\u89C2\u3002`))}];for(let u of a){let g=Y(u.name);if(u===d||!g||["default","\u9ED8\u8BA4"].includes(nt(g)))continue;let m=Bn("state",`${n}:${c}:${g}`,i);p.push({state_id:m,state_name:g,description:Y(Sl(s,c,g).description)}),r.states.push(`${c}/${g}`)}let l={aliases:Array.isArray(s.aliases)?[...new Set(s.aliases.map(u=>Y(u)).filter(u=>u&&u!==c))]:[],importance:s.importance==="background"?"background":"featured",description:Y(s.description,`${c}\u7684\u57FA\u7840\u8BBE\u5B9A\u3002`),states:p};if(n==="actors"){let u={...l,actor_id:Bn("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:Bn("location",c,i),location_name:c};return e.locations.push(u),r.locations.push(c),u}let f={...l,prop_id:Bn("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=Y(o);s||we(`${n} reference requires a readable name.`);let c=nt(s);return ky(e,n).find(d=>by(n,d).includes(c))??vy(e,t,n,s,i,r)}function qi(e,t,n,o,i,r){let s=Y(t,"\u9ED8\u8BA4"),c=nt(s),a=e.states.find(u=>nt(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=_l(n,o,d),l=Sl(p,d,s),f={state_id:Bn("state",`${d}:${s}`,i),state_name:s,description:Y(l.description)};return e.states.push(f),r.states.push(`${d}/${s}`),f.state_id}function yl(e,t){return e===void 0?[]:((!Array.isArray(e)||!e.every(Sn))&&we(`${t} must be an array of readable references.`),e)}function es(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 Ry(e,t){return!!(e&&e.location?.location_id&&t.location?.location_id&&e.location.location_id===t.location.location_id&&Y(e.environment?.space)===Y(t.environment?.space)&&Y(e.environment?.time)===Y(t.environment?.time))}function My(e,t,n,o,i,r,s,c){(!Array.isArray(e)||e.length===0||!e.every(Sn))&&we("scene.actions must contain at least one readable Action.");let a=structuredClone(o),d=r;return{actions:e.map((l,f)=>{let u=Y(l.type,"action");["action","transition","dialogue","inner_thought"].includes(u)||we(`Action ${f+1} has an unsupported type.`,[u]);let g=Y(l.content);g||we(`Action ${f+1} has empty content.`);let m=Math.max(400,Math.min(8e3,Math.round(Number(l.durationMs)||Number(l.weight||1)*1200))),h=yy(l.extensions);h.timestamp=_y(d),h.duration_ms=m,h.rewrite_duration_ms!==void 0&&(h.rewrite_duration_ms=m);let w={action_id:Bn("action",`${i}:${f+1}:${g}`,s),type:u,content:g,extend:h};if(d+=m,u==="action"||u==="transition")return w;let y=Y(l.speaker);y||we(`Action ${f+1} requires a speaker.`);let E=y.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");new RegExp(`^${E}\\s*[:\uFF1A]`,"iu").test(g)&&we(`Action ${f+1} repeats the speaker name in dialogue content.`),/^(?:“[^”]+”|「[^」]+」|『[^』]+』|"[^"]+")$/u.test(g)&&we(`Action ${f+1} wraps dialogue content in quotation marks.`);let I=nt(y);if(["\u65C1\u767D","narrator"].includes(I))return{...w,speaker:{kind:"broadcast",label:"\u65C1\u767D"},...Y(l.parenthetical)?{parenthetical:Y(l.parenthetical)}:{}};if(["\u753B\u5916\u97F3","offscreen"].includes(I))return{...w,speaker:{kind:"offscreen",label:"\u753B\u5916\u97F3"},...Y(l.parenthetical)?{parenthetical:Y(l.parenthetical)}:{}};let _=ts(t,n,"actors",y,s,c),A=Y(l.speakerVariant),k=a.find(O=>O.actor_id===_.actor_id),P;if(A)P=qi(_,A,n,"actors",s,c),k?k.state_ids=[...new Set([...k.state_ids,P])].sort():a.push({actor_id:_.actor_id,state_ids:[P]});else if(!k){let O=qi(_,"\u9ED8\u8BA4",n,"actors",s,c);a.push({actor_id:_.actor_id,state_ids:[O]})}return{...w,speaker:{actor_id:_.actor_id,...P?{state_id:P}:{}},...Y(l.parenthetical)?{parenthetical:Y(l.parenthetical)}:{}}}),actorRefs:a}}function Il(e,t){(!Sn(t)||t.version!==1)&&we("Creative draft version must be 1."),(!Sn(t.episode)||!Sn(t.scene))&&we("Creative draft requires episode and scene objects.");let n=structuredClone(t),o=n.episode,i=n.scene,r=structuredClone(e),s=wy(r),c={actors:[],locations:[],props:[],states:[]},a=hy(o.number,"episode.number");a>r.episodes.length+1&&we("Episodes must be composed in order.",[a]);let d=r.episodes[a-1];d?(Y(d.title)||(d.title=Y(o.title,`\u7B2C ${a} \u96C6`)),Y(d.synopsis)||(d.synopsis=Y(o.synopsis,`\u7B2C ${a} \u96C6\u5267\u60C5\u3002`))):(d={episode_id:Bn("episode",`episode:${a}`,s),title:Y(o.title,`\u7B2C ${a} \u96C6`),synopsis:Y(o.synopsis,`\u7B2C ${a} \u96C6\u5267\u60C5\u3002`),scenes:[]},r.episodes.push(d));let p=ts(r,n,"locations",i.location,s,c),l=qi(p,i.locationVariant,n,"locations",s,c),f=yl(i.actors,"scene.actors").map(S=>{let L=ts(r,n,"actors",S.name,s,c);return{actor_id:L.actor_id,state_ids:[qi(L,S.variant,n,"actors",s,c)]}}),u=es([],f,S=>S.actor_id),g=yl(i.props,"scene.props").map(S=>{let L=ts(r,n,"props",S.name,s,c);return{prop_id:L.prop_id,state_ids:[qi(L,S.variant,n,"props",s,c)]}}),m=es([],g,S=>S.prop_id),h=d.scenes.at(-1),w={scene_id:Bn("scene",`episode:${a}:scene:${d.scenes.length+1}:${Y(i.title)}`,s),environment:{space:Y(i.space,"interior"),time:Y(i.time,"day")},location:{location_id:p.location_id,state_ids:[l]},actors:u,props:m,actions:[],extend:{scene_title:Y(i.title,`\u7B2C ${d.scenes.length+1} \u573A`)}},y=Y(i.boundary,"auto");["auto","new","continue"].includes(y)||we("scene.boundary must be auto, new, or continue.");let E=Ry(h,w);y==="continue"&&!E&&we("scene.boundary=continue requires the same location, space, and time as the previous scene.");let I=y!=="new"&&E,_=I&&h?h:w,A=I?d.scenes.length:d.scenes.length+1,k=es(_.actors,w.actors,S=>S.actor_id),P=My(i.actions,r,n,k,_.scene_id,Sy(d),s,c);_.actors=P.actorRefs,_.props=es(_.props,w.props,S=>S.prop_id),_.location&&w.location&&(_.location.state_ids=[...new Set([..._.location.state_ids,...w.location.state_ids])].sort()),_.actions.push(...P.actions),I||d.scenes.push(_);let O=Me(r);return O.ok||we("Composed screenplay does not pass Script v4 validation.",O.errors.slice(0,12).map(S=>`${S.path}: ${S.message}`)),{script:r,validation:O,episodeNumber:a,sceneNumber:A,sceneId:_.scene_id,actionIds:P.actions.map(S=>S.action_id),joinedPreviousScene:I,created:c}}function Ke(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function on(e,t){return e[t]===void 0||typeof e[t]=="string"}function Ha(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Ha):Ke(e)&&Object.values(e).every(Ha)}function ri(e){return e.extend===void 0||Ke(e.extend)&&Object.values(e.extend).every(Ha)}function Qa(e){return e==="default"||V("state",e)}function Ly(e){return Ke(e)&&Qa(e.state_id)&&typeof e.state_name=="string"&&typeof e.description=="string"&&ri(e)}function Fa(e){return typeof e.importance=="string"&&It.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(Ly)&&ri(e)}function Ny(e){return Ke(e)&&V("actor",e.actor_id)&&typeof e.actor_name=="string"&&(e.role_type===void 0||typeof e.role_type=="string"&&Gn.has(e.role_type))&&Fa(e)}function Uy(e){return Ke(e)&&V("location",e.location_id)&&typeof e.location_name=="string"&&Fa(e)}function Py(e){return Ke(e)&&V("prop",e.prop_id)&&typeof e.prop_name=="string"&&Fa(e)}function Ya(e){return Array.isArray(e)&&e.every(Qa)}function Cy(e){return Ke(e)&&V("actor",e.actor_id)&&Ya(e.state_ids)}function Ty(e){return Ke(e)&&V("location",e.location_id)&&Ya(e.state_ids)}function Vy(e){return Ke(e)&&V("prop",e.prop_id)&&Ya(e.state_ids)}function $y(e){return V("actor",e.actor_id)&&(e.state_id===void 0||Qa(e.state_id))}function Dy(e){return typeof e.kind=="string"&&So.has(e.kind)&&on(e,"label")}function Gy(e){return!(!Ke(e)||!V("action",e.action_id)||typeof e.type!="string"||!Vt.has(e.type)||typeof e.content!="string"||!on(e,"parenthetical")||!ri(e)||(e.type==="dialogue"||e.type==="inner_thought")&&(!Ke(e.speaker)||!$y(e.speaker)&&!Dy(e.speaker))||e.transition_prompt!==void 0&&(!Ke(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 Jy(e){return!(!Ke(e)||!V("scene",e.scene_id)||!Array.isArray(e.actors)||!e.actors.every(Cy)||!Array.isArray(e.props)||!e.props.every(Vy)||!Array.isArray(e.actions)||!e.actions.every(Gy)||!ri(e)||e.location!==null&&!Ty(e.location)||e.environment!==void 0&&(!Ke(e.environment)||!on(e.environment,"space")||!on(e.environment,"time")))}function By(e){return Ke(e)&&V("episode",e.episode_id)&&on(e,"title")&&on(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(Jy)&&ri(e)}function Ky(e){return Ke(e)&&e.version===4&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&on(e,"worldview_raw")&&on(e,"synopsis")&&on(e,"logline")&&on(e,"theme")&&(e.main_characters===void 0||Array.isArray(e.main_characters)&&e.main_characters.every(t=>Ke(t)&&typeof t.name=="string"&&typeof t.role=="string"))&&Array.isArray(e.actors)&&e.actors.every(Ny)&&Array.isArray(e.locations)&&e.locations.every(Uy)&&Array.isArray(e.props)&&e.props.every(Py)&&Array.isArray(e.episodes)&&e.episodes.every(By)&&ri(e)}function si(e){let t=Me(e);if(t.ok)return e;throw new x("The local file is not a valid Script v4 document.",{exitCode:b,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 rn(e){if(Ky(e))return e;throw new x("The local file is not a structurally readable Script v4 document.",{exitCode:b,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 Zi from"node:crypto";import*as Ce from"node:fs";import*as kt from"node:path";import jy from"proper-lockfile";function Za(e){if(Array.isArray(e))return e.map(Za);if(e!==null&&typeof e=="object"){let t=e,n={};for(let o of Object.keys(t).sort())n[o]=Za(t[o]);return n}return e}function $e(e){let t=JSON.stringify(Za(e));return`sha256:${Zi.createHash("sha256").update(t).digest("hex")}`}function Wi(e){return Ce.existsSync(e)?`sha256:${Zi.createHash("sha256").update(Ce.readFileSync(e)).digest("hex")}`:null}function Xi(e,t){let n=Wi(e);if(n!==t)throw new x("The local script changed while the command was running.",{exitCode:b,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and retry the command.",data:{actual:[`loadedFingerprint=${t??"<missing>"}`,`currentFingerprint=${n??"<missing>"}`,e]}})}function er(e){let t=kt.resolve(e),n=kt.join(kt.dirname(t),".scriptctl"),o=kt.basename(t);return{scriptPath:t,stateDir:n,metadataPath:kt.join(n,`${o}.working-copy.json`),lockPath:kt.join(n,o)}}async function ns(e,t){let n=er(e);Ce.mkdirSync(n.stateDir,{recursive:!0});let o=null;try{o=await jy.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:me,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 je(e,t){os(e,`${JSON.stringify(t,null,2)}
123
- `)}function os(e,t){let n=kt.dirname(e);Ce.mkdirSync(n,{recursive:!0});let o=kt.join(n,`.${kt.basename(e)}.${process.pid}.${Zi.randomUUID()}.tmp`),i=Ce.openSync(o,"wx");try{Ce.writeFileSync(i,t,"utf-8"),Ce.fsyncSync(i)}finally{Ce.closeSync(i)}Ce.renameSync(o,e)}function is(e){let t=er(e).metadataPath;if(!Ce.existsSync(t))return null;let n;try{n=JSON.parse(Ce.readFileSync(t,"utf-8"))}catch(i){throw qa(t,i instanceof Error?i.message:String(i))}if(n===null||typeof n!="object"||Array.isArray(n))throw qa(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 qa(t,"required fields are missing or invalid");return{schemaVersion:1,projectGroupNo:o.projectGroupNo,apiBaseUrl:o.apiBaseUrl,baseRevision:Number(o.baseRevision),baseContentHash:o.baseContentHash}}function rs(e,t){je(er(e).metadataPath,t)}function qa(e,t){return new x("Working copy metadata is invalid.",{exitCode:b,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 Rt(e,t){let n;try{n=JSON.parse(Ce.readFileSync(e,"utf-8"))}catch(i){throw new x("The local script changed while the command was running.",{exitCode:b,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=$e(n);if(o!==t)throw new x("The local script changed while the command was running.",{exitCode:b,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 ee(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function In(e){return Array.isArray(e)}function te(e){return Array.isArray(e)?e:[]}function Wa(e,t=[]){throw new x(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 Al(e,t){let n=Ol.resolve(e),o;try{o=bl.readFileSync(n)}catch{throw new x(`${t} does not exist.`,{exitCode:b,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:b,errorCode:"CREATIVE_DRAFT_JSON_INVALID",data:{actual:[n,i instanceof Error?i.message:String(i)]}})}}function vl(e){let t=Array.isArray(e._args)?e._args:[],n=typeof t[0]=="string"?t[0]:"";(!n||n==="-")&&Wa("Creative draft input must be a named JSON file.",[n||"<missing>"]);let o=Al(n,"The creative draft"),i=Se(e),r=Al(i,"The target Script v4 file"),s=rn(r.value),c=$e(s),a=Il(s,o.value),d=`sha256:${kl.createHash("sha256").update(o.bytes).digest("hex")}`,p={version:1,op:"compose",sourceDigest:d,baseline:c,proposed:$e(a.script),episodeNumber:a.episodeNumber,sceneNumber:a.sceneNumber,sceneId:a.sceneId,actionIds:a.actionIds,joinedPreviousScene:a.joinedPreviousScene,created:a.created},l=`sha256:${Ie(JSON.stringify(p))}`,f=e.apply===!0,u=v(e.plan).trim();if(f&&!u&&Wa("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!f&&u&&Wa("--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:b,errorCode:"CREATIVE_DRAFT_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[l],actual:[u]}});return f&&(Rt(i,c),je(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 $l from"node:fs";import*as Dl from"node:path";var $t={line:1,column:1};function zy(e){let t=[];for(let n of e.actors){let o=structuredClone(n);o.states=[],t.push({declarationKind:"actor",value:o,source:$t});for(let i of n.states)t.push(Xa("actor",n.actor_id,i))}for(let n of e.locations){let o=structuredClone(n);o.states=[],t.push({declarationKind:"location",value:o,source:$t});for(let i of n.states)t.push(Xa("location",n.location_id,i))}for(let n of e.props){let o=structuredClone(n);o.states=[],t.push({declarationKind:"prop",value:o,source:$t});for(let i of n.states)t.push(Xa("prop",n.prop_id,i))}return t}function Xa(e,t,n){return{declarationKind:"state",ownerKind:e,ownerId:t,value:structuredClone(n),source:$t}}function Rl(e){let t={kind:"script",title:e.title,worldview:e.worldview,style:e.style,episodes:structuredClone(e.episodes),source:$t};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:zy(e),targets:[t],targetKind:"script"}}function ai(e,t){return{version:1,declarations:[],targets:t,targetKind:e}}function Hy(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function Qy(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function de(e,t,n){let o=[e,...t].map(Hy).join("|"),i=Qy(n);return`[${o}]${i.length>0?` ${i}`:""}`}function tc(e){if(Array.isArray(e))return e.map(tc);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=tc(e[n]);return t}return e}function An(e){return e===void 0?[]:[de("extensions",[],""),...Object.keys(e).sort().map(t=>de("extend",[t],JSON.stringify(tc(e[t]))))]}function Fy(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 Ml(e){let t=An(e.extend);if(e.transition_prompt!==void 0&&t.push(de("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=[Fy(e.speaker)];return e.emotion!==void 0&&i.push(e.emotion),t.push(de(o,i,e.content)),t}let n=e.type==="action"?"act":"trans";return t.push(de(n,e.emotion===void 0?[]:[e.emotion],e.content)),t}function nc(e,t){let n=[...An(e.extend),`<scene ${t}>`];if(e.environment!==void 0&&(e.environment.time!==void 0?n.push(de("environment",[e.environment.space??"",e.environment.time],"")):e.environment.space!==void 0?n.push(de("environment",[e.environment.space],"")):n.push(de("environment",[],""))),e.location===null)n.push(de("location",[],""));else{let o=[e.location.location_id];e.location.state_id!==void 0&&o.push(e.location.state_id),n.push(de("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(de("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(de("prop",i,""))}n.push("","<body>");for(let o of e.actions)n.push(...Ml(o));return n.push("</body>","","</scene>"),n}function ec(e){let t=[...An(e.extend),`<episode id=${e.episode_id}>`];return e.title!==void 0&&t.push(de("title",[],e.title)),e.synopsis!==void 0&&t.push(de("synopsis",[],e.synopsis)),(e.title!==void 0||e.synopsis!==void 0)&&e.scenes.length>0&&t.push(""),e.scenes.forEach((n,o)=>{t.push(...nc(n,`id=${n.scene_id}`)),o<e.scenes.length-1&&t.push("")}),t.push("</episode>"),t}function Yy(e){if(e.declarationKind==="state")return qy(e.ownerKind,e.ownerId,e.value);let t=e.value,n=An(t.extend);t.aliases!==void 0&&n.push(de("aliases",[],""));for(let o of t.aliases??[])n.push(de("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(de("actor",i,o.description))}else if(e.declarationKind==="location"){let o=e.value;n.push(de("location",[o.location_id,o.location_name,o.importance],o.description))}else{let o=e.value;n.push(de("prop",[o.prop_id,o.prop_name,o.importance],o.description))}return n}function qy(e,t,n){return[...An(n.extend),de("state",[`${e}:${t}`,n.state_id,n.state_name],n.description)]}function Zy(e){switch(e.kind){case"script":{let t=[...An(e.extend),"<script>"];if(t.push(de("title",[],e.title)),t.push(de("worldview",[],e.worldview)),e.worldviewRaw!==void 0&&t.push(de("worldview-raw",[],e.worldviewRaw)),t.push(de("style",[],e.style)),e.synopsis!==void 0&&t.push(de("synopsis",[],e.synopsis)),e.logline!==void 0&&t.push(de("logline",[],e.logline)),e.theme!==void 0&&t.push(de("theme",[],e.theme)),e.mainCharacters!==void 0){t.push(de("main-characters",[],""));for(let n of e.mainCharacters)t.push(de("main-character",[n.name,n.role],""))}return e.episodes.length>0&&t.push(""),e.episodes.forEach((n,o)=>{t.push(...ec(n)),o<e.episodes.length-1&&t.push("")}),t.push("</script>"),t}case"episode":return ec(e.value);case"episode-span":{let t=[...An(e.extend),`<episode-span from=${e.from} through=${e.through}>`];return e.episodes.forEach((n,o)=>{t.push(...ec(n)),o<e.episodes.length-1&&t.push("")}),t.push("</episode-span>"),t}case"scene":return nc(e.value,`id=${e.value.scene_id} parent=${e.parent}`);case"scene-span":{let t=[...An(e.extend),`<scene-span parent=${e.parent} from=${e.from} through=${e.through}>`];return e.scenes.forEach((n,o)=>{t.push(...nc(n,`id=${n.scene_id}`)),o<e.scenes.length-1&&t.push("")}),t.push("</scene-span>"),t}case"action-span":{let t=[...An(e.extend),`<action-span parent=${e.parent} from=${e.from} through=${e.through}>`,"<body>"];for(let n of e.actions)t.push(...Ml(n));return t.push("</body>","</action-span>"),t}}}function Ll(e){let t=["<authoring version=1>",""];if(e.declarations.length>0){t.push("<create>");for(let n of e.declarations)t.push(...Yy(n));t.push("</create>","")}return e.targets.forEach((n,o)=>{t.push(...Zy(n)),o<e.targets.length-1&&t.push("")}),t.push("","</authoring>"),`${t.join(`
122
+ `,E=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 Dy(e){return new ls(e)}function Nl(e){return Dy(e).directDir}function Ae(e){let t=e.script_path??e.scriptPath;return ir.resolve(typeof t=="string"&&t.length>0?t:$y)}function rr(e){return us.readJson(e)}function tc(e,t){us.writeJson(e,t)}function Co(e){return us.exists(e)}function he(e){return ec.createHash("sha256").update(e,"utf-8").digest("hex")}function nc(e){let t=ec.createHash("sha256"),n=fi.openSync(e,"r");try{let o=Buffer.alloc(1048576);for(;;){let i=fi.readSync(n,o,0,o.length,null);if(i<=0)break;t.update(o.subarray(0,i))}}finally{fi.closeSync(n)}return t.digest("hex")}var Ot={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 vt(e,t){return typeof e=="string"&&t.some(n=>n===e)}function Ul(e,t){switch(e){case"policy":return vt(t,Ot.policy)?{failure_type:e,failure_code:t}:null;case"network":return vt(t,Ot.network)?{failure_type:e,failure_code:t}:null;case"timeout":return vt(t,Ot.timeout)?{failure_type:e,failure_code:t}:null;case"rate_limit":return vt(t,Ot.rate_limit)?{failure_type:e,failure_code:t}:null;case"authentication":return vt(t,Ot.authentication)?{failure_type:e,failure_code:t}:null;case"authorization":return vt(t,Ot.authorization)?{failure_type:e,failure_code:t}:null;case"provider":return vt(t,Ot.provider)?{failure_type:e,failure_code:t}:null;case"media":return vt(t,Ot.media)?{failure_type:e,failure_code:t}:null;case"response":return vt(t,Ot.response)?{failure_type:e,failure_code:t}:null;case"pipeline":return vt(t,Ot.pipeline)?{failure_type:e,failure_code:t}:null;case"validation":return vt(t,Ot.validation)?{failure_type:e,failure_code:t}:null;case"cancelled":return vt(t,Ot.cancelled)?{failure_type:e,failure_code:t}:null;case"unknown":return vt(t,Ot.unknown)?{failure_type:e,failure_code:t}:null;default:return null}}function Rt(e,t){return{...e,...t}}function mi(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 Cl(e,t){if(e.length===0)return Rt({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)?mi(n):{failure_type:"provider",failure_code:"attempts_exhausted"};return Rt(i,{retryable:e.some(r=>r.retryable),message:t})}function ln(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 Yl from"node:crypto";import*as ql from"node:fs";import*as Zl from"node:path";import*as Bl from"node:crypto";var Rn=["action","dialogue","inner_thought","transition"],zt=new Set(Rn),Mn=["system","broadcast","offscreen","group"],Po=new Set(Mn),Ln=["featured","background"],Mt=new Set(Ln),gi=["\u4E3B\u89D2","\u914D\u89D2"],Xn=new Set(gi),fs=["day","night","dawn","dusk"],oc=new Set(fs);function ar(e){return typeof e=="string"&&oc.has(e)}var ic=["interior","exterior"],Pl=new Set(ic);function ct(e){return e.normalize("NFKC").toLowerCase()}function Tl(e){return JSON.stringify([e.code,e.path,e.message])}function rc(e){let t=new Map;for(let n of e){let o=Tl(n);t.set(o,(t.get(o)??0)+1)}return t}function sc(e,t){if(e.ok||t.errors.length>=e.errors.length)return!1;let n=rc(e.errors),o=rc(t.errors);for(let[i,r]of o)if(r>(n.get(i)??0))return!1;return!0}function ac(e,t){let n=rc(e),o=[];for(let i of t){let r=Tl(i),s=n.get(r)??0;s>0?n.set(r,s-1):o.push(i)}return o}import{customAlphabet as Gy}from"nanoid";var hi="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",cc=6,yi={episode:"ep",scene:"scn",action:"ac",actor:"act",location:"loc",prop:"prp",state:"st"},Jy=Gy(hi,cc),By=`[${hi}]`,Vl=Object.fromEntries(Object.entries(yi).map(([e,t])=>[e,new RegExp(`^${t}${By}{${cc}}$`)]));function V(e,t){return typeof t=="string"&&Vl[e].test(t)}var dc="ID_SPACE_EXHAUSTED";function cr(e,t=new Set,n=Jy){let o=yi[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:dc})}var Xe=class extends Error{input;constructor(t,n){super(n),this.input=t,this.name="TimestampParseError"}},Ky=/^(\d+):(\d{2})(?:\.(\d{1,3}))?$/,jy=/^(\d+):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/;function $l(e){return e?Number(e.padEnd(3,"0")):0}function Dl(e,t){if(!Number.isSafeInteger(t))throw new Xe(e,"Timestamp exceeds the supported numeric range.");return t}function Gl(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 eo(e){let t=e.trim();if(!t)throw new Xe(e,"Timestamp must not be empty.");let n=t.match(jy);if(n){let a=Number(n[1]),d=Number(n[2]),p=Number(n[3]),l=n[4];if(d>59)throw new Xe(e,"Hour-form timestamps require minutes between 00 and 59.");if(p>59)throw new Xe(e,"Timestamp seconds must be between 00 and 59.");let f=Dl(e,((a*60+d)*60+p)*1e3+$l(l));return{canonical:Gl(f,l),milliseconds:f,fractionDigits:l?.length??0}}let o=t.match(Ky);if(!o)throw new Xe(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 Xe(e,"Timestamp seconds must be between 00 and 59.");let c=Dl(e,(i*60+r)*1e3+$l(s));return{canonical:Gl(c,s),milliseconds:c,fractionDigits:s?.length??0}}function zy(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 ms(e,t,n){let o=null;e.forEach((i,r)=>{let s=zy(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=eo(s)}catch(d){if(!(d instanceof Xe))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 ht=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Nn=e=>Array.isArray(e),xe=e=>typeof e=="string",Hy=["state_changes","actor_id","speakers","lines"];function yt(e){let t=[],n=[],o=(u,h,m,g)=>t.push({code:u,path:h,message:m,...g?{repair_hint:g}:{}}),i=(u,h,m)=>n.push({code:u,path:h,message:m});if(!ht(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"])xe(e[u])||o("field",`$.${u}`,`${u} must be a string`);let r=new Map,s=new Map,c=new Map,a=(u,h,m,g,w)=>{if(!Nn(u)){o("field",w,`${w} must be an array`);return}u.forEach((y,x)=>{let S=`${w}[${x}]`;if(!ht(y)){o("asset",S,"asset must be an object");return}let _=y[m];if(!xe(_)){o("asset_id",`${S}.${m}`,`${m} required`);return}if(s.has(_)&&o("dup_id",`${S}.${m}`,`duplicate id ${_}`),s.set(_,h),!xe(y[g]))o("asset_name",`${S}.${g}`,`${g} required`);else if(h==="actor"){let O=ct(y[g]),I=c.get(O);I!==void 0?o("dup_actor_name",`${S}.${g}`,`actor name ${y[g]} already belongs to ${I}`):c.set(O,_)}(!xe(y.importance)||!Ln.includes(y.importance))&&o("importance",`${S}.importance`,`importance must be one of ${Ln.join("|")}`),xe(y.description)||o("asset_desc",`${S}.description`,"description must be a string");let A=new Set,b=new Set,U=0;!Nn(y.states)||y.states.length===0?o("states",`${S}.states`,"states must be a non-empty array"):y.states.forEach((O,I)=>{let L=`${S}.states[${I}]`;if(!ht(O)||!xe(O.state_id)){o("state_id",L,"state_id required");return}A.has(O.state_id)&&o("dup_state",L,`duplicate state_id ${O.state_id}`),A.add(O.state_id),O.state_id==="default"&&U++,xe(O.state_name)?(b.has(O.state_name)&&o("dup_state_name",`${L}.state_name`,`duplicate state_name ${O.state_name}`),b.add(O.state_name)):o("state_name",`${L}.state_name`,"state_name required")}),Nn(y.states)&&U!==1&&o("default_state",`${S}.states`,`exactly one 'default' state required, found ${U}`),r.set(_,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,h,m,g)=>{if(s.get(u)!==m){o("ref",g,`${m} ${u} not found`);return}h!==void 0&&(!xe(h)||!r.get(u)?.has(h))&&o("state_ref",g,`state ${String(h)} not materialized on ${u}`)},p=(u,h,m,g)=>{if(u===void 0){o("field",g,`${g} required (may be empty array)`);return}if(!Nn(u)){o("field",g,`${g} must be an array`);return}u.forEach((w,y)=>{if(!ht(w)||!xe(w[m])){o("ref",`${g}[${y}]`,`${m} required`);return}d(w[m],w.state_id,h,`${g}[${y}]`)})},l=(u,h,m,g)=>{if(!ht(u)){o("action",h,"action must be an object");return}for(let y of Hy)y in u&&o("legacy_field",`${h}.${y}`,`v3 forbids action.${y}`);let w=u.type;if((!xe(w)||!Rn.includes(w))&&o("action_type",`${h}.type`,`invalid action type ${String(w)}`),xe(u.content)||o("content",`${h}.content`,"content must be a plain-text string"),w==="dialogue"||w==="inner_thought"){let y=u.speaker;if(!ht(y))o("speaker",`${h}.speaker`,"dialogue/inner_thought needs a speaker");else if("kind"in y)(!xe(y.kind)||!Mn.includes(y.kind))&&o("speaker_kind",`${h}.speaker.kind`,"invalid non-actor speaker kind");else if(xe(y.actor_id)){if(d(y.actor_id,y.state_id,"actor",`${h}.speaker`),!m.has(y.actor_id)){let x=r.get(y.actor_id),S=xe(y.state_id)&&x?.has(y.state_id)?y.state_id:x?.has("default")?"default":x?.values().next().value,_=g&&S?`scriptctl scene-ref ${g} actor:${y.actor_id} --state ${S} -p "$SCRIPT"`:void 0;o("actor_not_in_scene",`${h}.speaker.actor_id`,`actor ${y.actor_id} is not referenced by this scene`,_)}}else o("speaker",`${h}.speaker`,"speaker needs actor_id or kind")}},f=e.episodes;return Nn(f)?f.forEach((u,h)=>{let m=`$.episodes[${h}]`;if(!ht(u)||!xe(u.episode_id)){o("episode_id",m,"episode_id required");return}if(!Nn(u.scenes)){o("scenes",`${m}.scenes`,"scenes must be an array");return}u.scenes.forEach((g,w)=>{let y=`${m}.scenes[${w}]`;if(!ht(g)){o("scene",y,"scene must be an object");return}"context"in g&&o("legacy_field",`${y}.context`,"v3 forbids scene.context"),xe(g.scene_id)||o("scene_id",y,"scene_id required");let x=g.environment;x===void 0||ht(x)&&(!xe(x.time)||x.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!ht(x)||x.space!==void 0&&!xe(x.space)||!xe(x.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):ar(x.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk"),(g.environment===void 0||ht(g.environment)&&(!xe(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&&(!ht(S)||!xe(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`),Nn(g.props)){let A=new Set;g.props.forEach((b,U)=>{!ht(b)||!xe(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 _=new Set(Nn(g.actors)?g.actors.filter(A=>ht(A)).map(A=>A.actor_id).filter(A=>xe(A)):[]);if(!Nn(g.actions))o("actions",`${y}.actions`,"actions must be an array");else{let A=xe(g.scene_id)?`${u.episode_id}/${g.scene_id}`:void 0;g.actions.forEach((b,U)=>l(b,`${y}.actions[${U}]`,_,A)),ms(g.actions,`${y}.actions`,o)}})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}var et=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),re=e=>typeof e=="string",un=e=>Array.isArray(e);function pc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(pc):et(e)&&Object.values(e).every(pc)}function wi(e,t,n){e!==void 0&&(!et(e)||!Object.values(e).every(pc))&&n("extend",t,"extend must be an object containing JSON values")}function Qy(e){for(let t=1;t<e.length;t++)if(e[t-1]>e[t])return!1;return!0}function Le(e){let t=[],n=[],o=(u,h,m,g)=>t.push({code:u,path:h,message:m,...g?{repair_hint:g}:{}}),i=(u,h,m,g)=>n.push({code:u,path:h,message:m,...g?{repair_hint:g}:{}});if(!et(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"])re(e[u])||o("field",`$.${u}`,`${u} must be a string`);for(let u of["worldview_raw","synopsis","logline","theme"])e[u]!==void 0&&!re(e[u])&&o("field",`$.${u}`,`${u} must be a string`);e.main_characters!==void 0&&(!un(e.main_characters)||!e.main_characters.every(u=>et(u)&&re(u.name)&&re(u.role)))&&o("main_characters","$.main_characters","main_characters must contain {name, role} string records"),wi(e.extend,"$.extend",o);let r=new Map,s=new Map,c=new Set,a=(u,h,m,g,w)=>{if(!un(u)){o("field",w,`${w} must be an array`);return}let y=new Set;u.forEach((x,S)=>{let _=`${w}[${S}]`;if(!et(x)){o("asset",_,"asset must be an object");return}let A=x[m];if(!V(h,A)){o("asset_id",`${_}.${m}`,`${m} must be ${h} ID`);return}if(y.has(A)&&o("dup_id",`${_}.${m}`,`duplicate ${m} ${A}`),y.add(A),r.set(A,h),!re(x[g])||x[g].trim()==="")o("asset_name",`${_}.${g}`,`${g} must be a non-empty string`);else if(h==="actor"){let I=x[g].trim().toLocaleLowerCase();c.has(I)&&o("dup_actor_name",`${_}.${g}`,`duplicate actor name ${x[g]}`),c.add(I)}if((!re(x.importance)||!Ln.includes(x.importance))&&o("importance",`${_}.importance`,`importance must be ${Ln.join("|")}`),h==="actor"&&x.role_type!==void 0&&(!re(x.role_type)||!gi.includes(x.role_type))&&o("role_type",`${_}.role_type`,`role_type must be ${gi.join("|")}`),re(x.description)||o("asset_desc",`${_}.description`,"description must be a string"),x.aliases!==void 0&&(!un(x.aliases)||!x.aliases.every(re)))o("aliases",`${_}.aliases`,"aliases must be an array of strings");else if(un(x.aliases)&&x.aliases.every(re)){let I=new Set,L=re(x[g])?x[g]:"";x.aliases.forEach((T,C)=>{T===""&&o("alias_empty",`${_}.aliases[${C}]`,"alias must not be empty"),T===L&&o("alias_equals_name",`${_}.aliases[${C}]`,"alias must differ from the asset name"),I.has(T)&&o("dup_alias",`${_}.aliases[${C}]`,`duplicate alias ${T}`),I.add(T)})}wi(x.extend,`${_}.extend`,o);let b=new Set,U=new Set,O=0;!un(x.states)||x.states.length===0?o("states",`${_}.states`,"states must be a non-empty array"):x.states.forEach((I,L)=>{let T=`${_}.states[${L}]`;if(!et(I)){o("state",T,"state must be an object");return}let C=I.state_id;if(C!=="default"&&!V("state",C)){o("state_id",`${T}.state_id`,"state_id must be default or st plus six Base58 characters");return}b.has(C)&&o("dup_state",`${T}.state_id`,`duplicate state_id ${C}`),b.add(C),C==="default"&&O++,!re(I.state_name)||I.state_name.trim()===""?o("state_name",`${T}.state_name`,"state_name must be a non-empty string"):(U.has(I.state_name)&&o("dup_state_name",`${T}.state_name`,`duplicate state_name ${I.state_name}`),U.add(I.state_name)),re(I.description)||o("state_description",`${T}.description`,"description must be a string"),wi(I.extend,`${T}.extend`,o)}),O!==1&&o("default_state",`${_}.states`,`exactly one default state required, found ${O}`),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,h,m)=>{if(!un(h)||h.length===0||!h.every(re))return o("state_ids",m,"state_ids must be a non-empty array of strings"),[];let g=h,w=new Set;return g.forEach((y,x)=>{w.has(y)&&o("dup_state_ref",`${m}[${x}]`,`duplicate state_id ${y}`),w.add(y),s.get(u)?.has(y)||o("state_ref",`${m}[${x}]`,`state ${y} not found on ${u}`)}),Qy(g)||o("state_ids_order",m,"state_ids must be sorted lexically"),g},p=new Set,l=new Set,f=new Set;return un(e.episodes)?e.episodes.forEach((u,h)=>{let m=`$.episodes[${h}]`;if(!et(u)){o("episode",m,"episode must be an object");return}V("episode",u.episode_id)?(p.has(u.episode_id)&&o("dup_episode_id",`${m}.episode_id`,`duplicate episode_id ${u.episode_id}`),p.add(u.episode_id)):o("episode_id",`${m}.episode_id`,"episode_id must be ep plus six Base58 characters");for(let g of["title","synopsis"])u[g]!==void 0&&!re(u[g])&&o("field",`${m}.${g}`,`${g} must be a string`);if(wi(u.extend,`${m}.extend`,o),!un(u.scenes)){o("scenes",`${m}.scenes`,"scenes must be an array");return}u.scenes.forEach((g,w)=>{let y=`${m}.scenes[${w}]`;if(!et(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"),wi(g.extend,`${y}.extend`,o),g.environment===void 0||et(g.environment)&&(!re(g.environment.time)||g.environment.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!et(g.environment)||g.environment.space!==void 0&&!re(g.environment.space)||!re(g.environment.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):ar(g.environment.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk"),(g.environment===void 0||et(g.environment)&&(!re(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&&(!et(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 x=new Map,S=(_,A,b,U)=>{if(!un(_)){o("field",U,`${U} must be an array`);return}let O=new Set;_.forEach((I,L)=>{let T=`${U}[${L}]`;if(!et(I)||!V(A,I[b])){o("ref",T,`${b} must be a typed v4 ID`);return}let C=I[b];"state_id"in I&&o("v3_field",`${T}.state_id`,"Script v4 scene references use state_ids"),O.has(C)&&o("dup_asset_ref",`${T}.${b}`,`duplicate ${A} ref ${C}`),O.add(C),r.get(C)!==A&&o("asset_ref",`${T}.${b}`,`${A} ${C} not found`);let R=d(C,I.state_ids,`${T}.state_ids`);A==="actor"&&x.set(C,new Set(R))})};if(S(g.actors,"actor","actor_id",`${y}.actors`),S(g.props,"prop","prop_id",`${y}.props`),!un(g.actions)){o("actions",`${y}.actions`,"actions must be an array");return}g.actions.forEach((_,A)=>{let b=`${y}.actions[${A}]`;if(!et(_)){o("action",b,"action must be an object");return}if(V("action",_.action_id)?(f.has(_.action_id)&&o("dup_action_id",`${b}.action_id`,`duplicate action_id ${_.action_id}`),f.add(_.action_id)):o("action_id",`${b}.action_id`,"action_id must be ac plus six Base58 characters"),(!re(_.type)||!Rn.includes(_.type))&&o("action_type",`${b}.type`,`invalid action type ${String(_.type)}`),re(_.content)||o("content",`${b}.content`,"content must be a string"),"emotion"in _&&o("v3_field",`${b}.emotion`,"Script v4 does not allow emotion"),wi(_.extend,`${b}.extend`,o),_.type==="dialogue"||_.type==="inner_thought")if(_.parenthetical!==void 0&&!re(_.parenthetical)&&o("parenthetical",`${b}.parenthetical`,"parenthetical must be a string"),!et(_.speaker))o("speaker",`${b}.speaker`,"dialogue/inner_thought requires a speaker");else if(re(_.speaker.actor_id)){("kind"in _.speaker||"label"in _.speaker)&&o("speaker_shape",`${b}.speaker`,"actor speaker cannot contain non-actor speaker fields");let O=_.speaker.actor_id;(!V("actor",O)||r.get(O)!=="actor")&&o("speaker_actor",`${b}.speaker.actor_id`,`actor ${O} not found`);let I=x.get(O),L=s.get(O),T=re(_.speaker.state_id)&&L?.has(_.speaker.state_id)?_.speaker.state_id:void 0,C=L?.has("default")?"default":L?.values().next().value,R=T?[T]:C?[C]:[],j=V("scene",g.scene_id)&&V("actor",O)&&R.length>0?`scriptctl scene-ref ${g.scene_id} ${O} ${R.map(Z=>`--state ${Z}`).join(" ")} -p "$SCRIPT"`:void 0;if(I||o("actor_not_in_scene",`${b}.speaker.actor_id`,`actor ${O} is not referenced by this scene`,j),_.speaker.state_id!==void 0&&(!re(_.speaker.state_id)||!I?.has(_.speaker.state_id))){let Z=T?[...new Set([...I??[],T])].sort():[],ve=V("scene",g.scene_id)&&V("actor",O)&&Z.length>0?`scriptctl scene-ref ${g.scene_id} ${O} ${Z.map(K=>`--state ${K}`).join(" ")} -p "$SCRIPT"`:j;o("speaker_state",`${b}.speaker.state_id`,`speaker state ${String(_.speaker.state_id)} is not in this scene's actor state_ids`,ve)}}else re(_.speaker.kind)?(("actor_id"in _.speaker||"state_id"in _.speaker)&&o("speaker_shape",`${b}.speaker`,"non-actor speaker cannot contain actor speaker fields"),Mn.includes(_.speaker.kind)||o("speaker_kind",`${b}.speaker.kind`,"invalid non-actor speaker kind"),_.speaker.label!==void 0&&!re(_.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 _&&o("parenthetical_type",`${b}.parenthetical`,"parenthetical only belongs to speaking actions"),"speaker"in _&&o("speaker_type",`${b}.speaker`,"speaker only belongs to speaking actions");if(_.transition_prompt!==void 0){let O=_.transition_prompt;!et(O)||!re(O.target)||!re(O.process)||O.process===""||!re(O.contrast)||O.contrast===""?o("transition_prompt",`${b}.transition_prompt`,"transition_prompt requires non-empty target/process/contrast"):r.has(O.target)||o("transition_target",`${b}.transition_prompt.target`,`asset ${O.target} not found`)}}),ms(g.actions,`${y}.actions`,o)})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}function To(e,t=new Set,n){try{return n?cr(e,t,n):cr(e,t)}catch(o){throw o?.code!==dc?o:new E(`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 _e(e,t=[]){throw new E(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 Un(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Y(e,t=""){return String(e??"").replace(/\s+/gu," ").trim()||t}function Fy(e,t){let n=Number(e);return(!Number.isSafeInteger(n)||n<1)&&_e(`${t} must be a positive integer.`,[e]),n}function Yy(e){return e===void 0?{}:(Un(e)||_e("Action extensions must be an object."),structuredClone(e))}function qy(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 to(e,t,n){for(let o=0;o<128;o+=1){let i=Bl.createHash("sha256").update(`${e}:${t}:${o}`).digest(),r="";for(let c=0;c<6;c+=1)r+=hi[i[c]%hi.length];let s=`${yi[e]}${r}`;if(!n.has(s))return n.add(s),s}_e(`Could not allocate a stable ${e} ID.`)}function Zy(e){let t=Y(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 Wy(e){return`${Math.floor(e/6e4)}:${String(Math.floor(e%6e4/1e3)).padStart(2,"0")}.${String(e%1e3).padStart(3,"0")}`}function Xy(e){let t=Number(e.extend?.duration_ms??e.extend?.rewrite_duration_ms);return Number.isFinite(t)&&t>0?Math.round(t):1200}function ew(e){let t=0;for(let n of e.scenes.flatMap(o=>o.actions))t=(Zy(n.extend?.timestamp)??t)+Xy(n);return t}function Kl(e){return e===void 0?[]:((!Array.isArray(e)||!e.every(Un))&&_e("Asset variants must be an array of readable objects."),e)}function tw(e,t){let n=e.assets;if(n===void 0)return[];Un(n)||_e("assets must be an object.");let o=n[t];return o===void 0?[]:((!Array.isArray(o)||!o.every(Un))&&_e(`assets.${t} must be an array.`),o)}function nw(e,t){return e==="actors"?t.actor_name:e==="locations"?t.location_name:t.prop_name}function ow(e,t){return e[t]}function iw(e,t){return[nw(e,t),...t.aliases??[]].map(ct)}function jl(e,t,n){let o=ct(n);return tw(e,t).find(i=>[i.name,...Array.isArray(i.aliases)?i.aliases:[]].map(r=>ct(Y(r))).includes(o))??null}function zl(e,t){if(!e)return null;let n=ct(t);return Kl(e.variants).find(o=>{let i=ct(Y(o.name));return i===n||["default","\u9ED8\u8BA4"].includes(n)&&["default","\u9ED8\u8BA4"].includes(i)})??null}function Hl(e,t,n){let o=zl(e,n),i=Y(o?.description);return(!o||!i)&&_e(`${t}/${n} is a new variant and requires a readable assets declaration with a self-contained description.`),o}function rw(e,t){let n=Y(t?.name);return n&&!["default","\u9ED8\u8BA4"].includes(ct(n))?n:e==="actors"?"\u57FA\u7840\u9020\u578B":e==="locations"?"\u5E38\u89C4\u5E03\u7F6E":"\u57FA\u7840\u5916\u89C2"}function sw(e,t,n,o,i,r){let s=jl(t,n,o);s||_e(`${o} is not an existing ${n} asset and has no readable declaration.`);let c=Y(s.name,o),a=Kl(s.variants),d=zl(s,"\u9ED8\u8BA4")??a[0]??null;n==="actors"&&!Y(s.description)&&_e(`${c} requires an identity description separate from its appearance variants.`),n==="actors"&&!Y(d?.description)&&_e(`${c} requires its first variant to provide a self-contained base appearance description.`);let p=[{state_id:"default",state_name:rw(n,d),description:Y(d?.description,Y(s.description,`${c}\u7684\u57FA\u7840\u53C2\u8003\u5916\u89C2\u3002`))}];for(let u of a){let h=Y(u.name);if(u===d||!h||["default","\u9ED8\u8BA4"].includes(ct(h)))continue;let m=to("state",`${n}:${c}:${h}`,i);p.push({state_id:m,state_name:h,description:Y(Hl(s,c,h).description)}),r.states.push(`${c}/${h}`)}let l={aliases:Array.isArray(s.aliases)?[...new Set(s.aliases.map(u=>Y(u)).filter(u=>u&&u!==c))]:[],importance:s.importance==="background"?"background":"featured",description:Y(s.description,`${c}\u7684\u57FA\u7840\u8BBE\u5B9A\u3002`),states:p};if(n==="actors"){let u={...l,actor_id:to("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:to("location",c,i),location_name:c};return e.locations.push(u),r.locations.push(c),u}let f={...l,prop_id:to("prop",c,i),prop_name:c};return e.props.push(f),r.props.push(c),f}function hs(e,t,n,o,i,r){let s=Y(o);s||_e(`${n} reference requires a readable name.`);let c=ct(s);return ow(e,n).find(d=>iw(n,d).includes(c))??sw(e,t,n,s,i,r)}function dr(e,t,n,o,i,r){let s=Y(t,"\u9ED8\u8BA4"),c=ct(s),a=e.states.find(u=>ct(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=jl(n,o,d),l=Hl(p,d,s),f={state_id:to("state",`${d}:${s}`,i),state_name:s,description:Y(l.description)};return e.states.push(f),r.states.push(`${d}/${s}`),f.state_id}function Jl(e,t){return e===void 0?[]:((!Array.isArray(e)||!e.every(Un))&&_e(`${t} must be an array of readable references.`),e)}function gs(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 aw(e,t){return!!(e&&e.location?.location_id&&t.location?.location_id&&e.location.location_id===t.location.location_id&&Y(e.environment?.space)===Y(t.environment?.space)&&Y(e.environment?.time)===Y(t.environment?.time))}function cw(e,t,n,o,i,r,s,c){(!Array.isArray(e)||e.length===0||!e.every(Un))&&_e("scene.actions must contain at least one readable Action.");let a=structuredClone(o),d=r;return{actions:e.map((l,f)=>{let u=Y(l.type,"action");["action","transition","dialogue","inner_thought"].includes(u)||_e(`Action ${f+1} has an unsupported type.`,[u]);let h=Y(l.content);h||_e(`Action ${f+1} has empty content.`);let m=Math.max(400,Math.min(8e3,Math.round(Number(l.durationMs)||Number(l.weight||1)*1200))),g=Yy(l.extensions);g.timestamp=Wy(d),g.duration_ms=m,g.rewrite_duration_ms!==void 0&&(g.rewrite_duration_ms=m);let w={action_id:to("action",`${i}:${f+1}:${h}`,s),type:u,content:h,extend:g};if(d+=m,u==="action"||u==="transition")return w;let y=Y(l.speaker);y||_e(`Action ${f+1} requires a speaker.`);let x=y.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");new RegExp(`^${x}\\s*[:\uFF1A]`,"iu").test(h)&&_e(`Action ${f+1} repeats the speaker name in dialogue content.`),/^(?:“[^”]+”|「[^」]+」|『[^』]+』|"[^"]+")$/u.test(h)&&_e(`Action ${f+1} wraps dialogue content in quotation marks.`);let S=ct(y);if(["\u65C1\u767D","narrator"].includes(S))return{...w,speaker:{kind:"broadcast",label:"\u65C1\u767D"},...Y(l.parenthetical)?{parenthetical:Y(l.parenthetical)}:{}};if(["\u753B\u5916\u97F3","offscreen"].includes(S))return{...w,speaker:{kind:"offscreen",label:"\u753B\u5916\u97F3"},...Y(l.parenthetical)?{parenthetical:Y(l.parenthetical)}:{}};let _=hs(t,n,"actors",y,s,c),A=Y(l.speakerVariant),b=a.find(O=>O.actor_id===_.actor_id),U;if(A)U=dr(_,A,n,"actors",s,c),b?b.state_ids=[...new Set([...b.state_ids,U])].sort():a.push({actor_id:_.actor_id,state_ids:[U]});else if(!b){let O=dr(_,"\u9ED8\u8BA4",n,"actors",s,c);a.push({actor_id:_.actor_id,state_ids:[O]})}return{...w,speaker:{actor_id:_.actor_id,...U?{state_id:U}:{}},...Y(l.parenthetical)?{parenthetical:Y(l.parenthetical)}:{}}}),actorRefs:a}}function Ql(e,t){(!Un(t)||t.version!==1)&&_e("Creative draft version must be 1."),(!Un(t.episode)||!Un(t.scene))&&_e("Creative draft requires episode and scene objects.");let n=structuredClone(t),o=n.episode,i=n.scene,r=structuredClone(e),s=qy(r),c={actors:[],locations:[],props:[],states:[]},a=Fy(o.number,"episode.number");a>r.episodes.length+1&&_e("Episodes must be composed in order.",[a]);let d=r.episodes[a-1];d?(Y(d.title)||(d.title=Y(o.title,`\u7B2C ${a} \u96C6`)),Y(d.synopsis)||(d.synopsis=Y(o.synopsis,`\u7B2C ${a} \u96C6\u5267\u60C5\u3002`))):(d={episode_id:to("episode",`episode:${a}`,s),title:Y(o.title,`\u7B2C ${a} \u96C6`),synopsis:Y(o.synopsis,`\u7B2C ${a} \u96C6\u5267\u60C5\u3002`),scenes:[]},r.episodes.push(d));let p=hs(r,n,"locations",i.location,s,c),l=dr(p,i.locationVariant,n,"locations",s,c),f=Jl(i.actors,"scene.actors").map(I=>{let L=hs(r,n,"actors",I.name,s,c);return{actor_id:L.actor_id,state_ids:[dr(L,I.variant,n,"actors",s,c)]}}),u=gs([],f,I=>I.actor_id),h=Jl(i.props,"scene.props").map(I=>{let L=hs(r,n,"props",I.name,s,c);return{prop_id:L.prop_id,state_ids:[dr(L,I.variant,n,"props",s,c)]}}),m=gs([],h,I=>I.prop_id),g=d.scenes.at(-1),w={scene_id:to("scene",`episode:${a}:scene:${d.scenes.length+1}:${Y(i.title)}`,s),environment:{space:Y(i.space,"interior"),time:Y(i.time,"day")},location:{location_id:p.location_id,state_ids:[l]},actors:u,props:m,actions:[],extend:{scene_title:Y(i.title,`\u7B2C ${d.scenes.length+1} \u573A`)}},y=Y(i.boundary,"auto");["auto","new","continue"].includes(y)||_e("scene.boundary must be auto, new, or continue.");let x=aw(g,w);y==="continue"&&!x&&_e("scene.boundary=continue requires the same location, space, and time as the previous scene.");let S=y!=="new"&&x,_=S&&g?g:w,A=S?d.scenes.length:d.scenes.length+1,b=gs(_.actors,w.actors,I=>I.actor_id),U=cw(i.actions,r,n,b,_.scene_id,ew(d),s,c);_.actors=U.actorRefs,_.props=gs(_.props,w.props,I=>I.prop_id),_.location&&w.location&&(_.location.state_ids=[...new Set([..._.location.state_ids,...w.location.state_ids])].sort()),_.actions.push(...U.actions),S||d.scenes.push(_);let O=Le(r);return O.ok||_e("Composed screenplay does not pass Script v4 validation.",O.errors.slice(0,12).map(I=>`${I.path}: ${I.message}`)),{script:r,validation:O,episodeNumber:a,sceneNumber:A,sceneId:_.scene_id,actionIds:U.actions.map(I=>I.action_id),joinedPreviousScene:S,created:c}}function je(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fn(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):je(e)&&Object.values(e).every(lc)}function xi(e){return e.extend===void 0||je(e.extend)&&Object.values(e.extend).every(lc)}function uc(e){return e==="default"||V("state",e)}function dw(e){return je(e)&&uc(e.state_id)&&typeof e.state_name=="string"&&typeof e.description=="string"&&xi(e)}function fc(e){return typeof e.importance=="string"&&Mt.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(dw)&&xi(e)}function pw(e){return je(e)&&V("actor",e.actor_id)&&typeof e.actor_name=="string"&&(e.role_type===void 0||typeof e.role_type=="string"&&Xn.has(e.role_type))&&fc(e)}function lw(e){return je(e)&&V("location",e.location_id)&&typeof e.location_name=="string"&&fc(e)}function uw(e){return je(e)&&V("prop",e.prop_id)&&typeof e.prop_name=="string"&&fc(e)}function mc(e){return Array.isArray(e)&&e.every(uc)}function fw(e){return je(e)&&V("actor",e.actor_id)&&mc(e.state_ids)}function mw(e){return je(e)&&V("location",e.location_id)&&mc(e.state_ids)}function gw(e){return je(e)&&V("prop",e.prop_id)&&mc(e.state_ids)}function hw(e){return V("actor",e.actor_id)&&(e.state_id===void 0||uc(e.state_id))}function yw(e){return typeof e.kind=="string"&&Po.has(e.kind)&&fn(e,"label")}function ww(e){return!(!je(e)||!V("action",e.action_id)||typeof e.type!="string"||!zt.has(e.type)||typeof e.content!="string"||!fn(e,"parenthetical")||!xi(e)||(e.type==="dialogue"||e.type==="inner_thought")&&(!je(e.speaker)||!hw(e.speaker)&&!yw(e.speaker))||e.transition_prompt!==void 0&&(!je(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 xw(e){return!(!je(e)||!V("scene",e.scene_id)||!Array.isArray(e.actors)||!e.actors.every(fw)||!Array.isArray(e.props)||!e.props.every(gw)||!Array.isArray(e.actions)||!e.actions.every(ww)||!xi(e)||e.location!==null&&!mw(e.location)||e.environment!==void 0&&(!je(e.environment)||!fn(e.environment,"space")||!fn(e.environment,"time")))}function _w(e){return je(e)&&V("episode",e.episode_id)&&fn(e,"title")&&fn(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(xw)&&xi(e)}function Ew(e){return je(e)&&e.version===4&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&fn(e,"worldview_raw")&&fn(e,"synopsis")&&fn(e,"logline")&&fn(e,"theme")&&(e.main_characters===void 0||Array.isArray(e.main_characters)&&e.main_characters.every(t=>je(t)&&typeof t.name=="string"&&typeof t.role=="string"))&&Array.isArray(e.actors)&&e.actors.every(pw)&&Array.isArray(e.locations)&&e.locations.every(lw)&&Array.isArray(e.props)&&e.props.every(uw)&&Array.isArray(e.episodes)&&e.episodes.every(_w)&&xi(e)}function _i(e){let t=Le(e);if(t.ok)return e;throw new E("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 mn(e){if(Ew(e))return e;throw new E("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 pr from"node:crypto";import*as Te from"node:fs";import*as Lt from"node:path";import Sw from"proper-lockfile";function hc(e){if(Array.isArray(e))return e.map(hc);if(e!==null&&typeof e=="object"){let t=e,n={};for(let o of Object.keys(t).sort())n[o]=hc(t[o]);return n}return e}function De(e){let t=JSON.stringify(hc(e));return`sha256:${pr.createHash("sha256").update(t).digest("hex")}`}function lr(e){return Te.existsSync(e)?`sha256:${pr.createHash("sha256").update(Te.readFileSync(e)).digest("hex")}`:null}function ur(e,t){let n=lr(e);if(n!==t)throw new E("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 fr(e){let t=Lt.resolve(e),n=Lt.join(Lt.dirname(t),".scriptctl"),o=Lt.basename(t);return{scriptPath:t,stateDir:n,metadataPath:Lt.join(n,`${o}.working-copy.json`),lockPath:Lt.join(n,o)}}async function ys(e,t){let n=fr(e);Te.mkdirSync(n.stateDir,{recursive:!0});let o=null;try{o=await Sw.lock(n.lockPath,{realpath:!1,stale:12e4,update:1e4,retries:{retries:60,factor:1,minTimeout:500,maxTimeout:500}})}catch(i){throw new E("Timed out waiting for the script file lock.",{exitCode:me,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 ze(e,t){ws(e,`${JSON.stringify(t,null,2)}
123
+ `)}function ws(e,t){let n=Lt.dirname(e);Te.mkdirSync(n,{recursive:!0});let o=Lt.join(n,`.${Lt.basename(e)}.${process.pid}.${pr.randomUUID()}.tmp`),i=Te.openSync(o,"wx");try{Te.writeFileSync(i,t,"utf-8"),Te.fsyncSync(i)}finally{Te.closeSync(i)}Te.renameSync(o,e)}function xs(e){let t=fr(e).metadataPath;if(!Te.existsSync(t))return null;let n;try{n=JSON.parse(Te.readFileSync(t,"utf-8"))}catch(i){throw gc(t,i instanceof Error?i.message:String(i))}if(n===null||typeof n!="object"||Array.isArray(n))throw gc(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 gc(t,"required fields are missing or invalid");return{schemaVersion:1,projectGroupNo:o.projectGroupNo,apiBaseUrl:o.apiBaseUrl,baseRevision:Number(o.baseRevision),baseContentHash:o.baseContentHash}}function _s(e,t){ze(fr(e).metadataPath,t)}function gc(e,t){return new E("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 Tt(e,t){let n;try{n=JSON.parse(Te.readFileSync(e,"utf-8"))}catch(i){throw new E("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=De(n);if(o!==t)throw new E("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 ee(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cn(e){return Array.isArray(e)}function te(e){return Array.isArray(e)?e:[]}function yc(e,t=[]){throw new E(e,{exitCode:G,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 Fl(e,t){let n=Zl.resolve(e),o;try{o=ql.readFileSync(n)}catch{throw new E(`${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 E(`${t} is not valid JSON.`,{exitCode:k,errorCode:"CREATIVE_DRAFT_JSON_INVALID",data:{actual:[n,i instanceof Error?i.message:String(i)]}})}}function Wl(e){let t=Array.isArray(e._args)?e._args:[],n=typeof t[0]=="string"?t[0]:"";(!n||n==="-")&&yc("Creative draft input must be a named JSON file.",[n||"<missing>"]);let o=Fl(n,"The creative draft"),i=Ae(e),r=Fl(i,"The target Script v4 file"),s=mn(r.value),c=De(s),a=Ql(s,o.value),d=`sha256:${Yl.createHash("sha256").update(o.bytes).digest("hex")}`,p={version:1,op:"compose",sourceDigest:d,baseline:c,proposed:De(a.script),episodeNumber:a.episodeNumber,sceneNumber:a.sceneNumber,sceneId:a.sceneId,actionIds:a.actionIds,joinedPreviousScene:a.joinedPreviousScene,created:a.created},l=`sha256:${he(JSON.stringify(p))}`,f=e.apply===!0,u=v(e.plan).trim();if(f&&!u&&yc("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!f&&u&&yc("--plan is only valid together with --apply.",[`plan=${u}`]),f&&u!==l)throw new E("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&&(Tt(i,c),ze(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}},J]}import*as cu from"node:fs";import*as du from"node:path";var Ht={line:1,column:1};function Iw(e){let t=[];for(let n of e.actors){let o=structuredClone(n);o.states=[],t.push({declarationKind:"actor",value:o,source:Ht});for(let i of n.states)t.push(wc("actor",n.actor_id,i))}for(let n of e.locations){let o=structuredClone(n);o.states=[],t.push({declarationKind:"location",value:o,source:Ht});for(let i of n.states)t.push(wc("location",n.location_id,i))}for(let n of e.props){let o=structuredClone(n);o.states=[],t.push({declarationKind:"prop",value:o,source:Ht});for(let i of n.states)t.push(wc("prop",n.prop_id,i))}return t}function wc(e,t,n){return{declarationKind:"state",ownerKind:e,ownerId:t,value:structuredClone(n),source:Ht}}function Xl(e){let t={kind:"script",title:e.title,worldview:e.worldview,style:e.style,episodes:structuredClone(e.episodes),source:Ht};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:Iw(e),targets:[t],targetKind:"script"}}function Ei(e,t){return{version:1,declarations:[],targets:t,targetKind:e}}function Aw(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function kw(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function de(e,t,n){let o=[e,...t].map(Aw).join("|"),i=kw(n);return`[${o}]${i.length>0?` ${i}`:""}`}function _c(e){if(Array.isArray(e))return e.map(_c);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=_c(e[n]);return t}return e}function Pn(e){return e===void 0?[]:[de("extensions",[],""),...Object.keys(e).sort().map(t=>de("extend",[t],JSON.stringify(_c(e[t]))))]}function bw(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 eu(e){let t=Pn(e.extend);if(e.transition_prompt!==void 0&&t.push(de("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=[bw(e.speaker)];return e.emotion!==void 0&&i.push(e.emotion),t.push(de(o,i,e.content)),t}let n=e.type==="action"?"act":"trans";return t.push(de(n,e.emotion===void 0?[]:[e.emotion],e.content)),t}function Ec(e,t){let n=[...Pn(e.extend),`<scene ${t}>`];if(e.environment!==void 0&&(e.environment.time!==void 0?n.push(de("environment",[e.environment.space??"",e.environment.time],"")):e.environment.space!==void 0?n.push(de("environment",[e.environment.space],"")):n.push(de("environment",[],""))),e.location===null)n.push(de("location",[],""));else{let o=[e.location.location_id];e.location.state_id!==void 0&&o.push(e.location.state_id),n.push(de("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(de("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(de("prop",i,""))}n.push("","<body>");for(let o of e.actions)n.push(...eu(o));return n.push("</body>","","</scene>"),n}function xc(e){let t=[...Pn(e.extend),`<episode id=${e.episode_id}>`];return e.title!==void 0&&t.push(de("title",[],e.title)),e.synopsis!==void 0&&t.push(de("synopsis",[],e.synopsis)),(e.title!==void 0||e.synopsis!==void 0)&&e.scenes.length>0&&t.push(""),e.scenes.forEach((n,o)=>{t.push(...Ec(n,`id=${n.scene_id}`)),o<e.scenes.length-1&&t.push("")}),t.push("</episode>"),t}function Ow(e){if(e.declarationKind==="state")return vw(e.ownerKind,e.ownerId,e.value);let t=e.value,n=Pn(t.extend);t.aliases!==void 0&&n.push(de("aliases",[],""));for(let o of t.aliases??[])n.push(de("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(de("actor",i,o.description))}else if(e.declarationKind==="location"){let o=e.value;n.push(de("location",[o.location_id,o.location_name,o.importance],o.description))}else{let o=e.value;n.push(de("prop",[o.prop_id,o.prop_name,o.importance],o.description))}return n}function vw(e,t,n){return[...Pn(n.extend),de("state",[`${e}:${t}`,n.state_id,n.state_name],n.description)]}function Rw(e){switch(e.kind){case"script":{let t=[...Pn(e.extend),"<script>"];if(t.push(de("title",[],e.title)),t.push(de("worldview",[],e.worldview)),e.worldviewRaw!==void 0&&t.push(de("worldview-raw",[],e.worldviewRaw)),t.push(de("style",[],e.style)),e.synopsis!==void 0&&t.push(de("synopsis",[],e.synopsis)),e.logline!==void 0&&t.push(de("logline",[],e.logline)),e.theme!==void 0&&t.push(de("theme",[],e.theme)),e.mainCharacters!==void 0){t.push(de("main-characters",[],""));for(let n of e.mainCharacters)t.push(de("main-character",[n.name,n.role],""))}return e.episodes.length>0&&t.push(""),e.episodes.forEach((n,o)=>{t.push(...xc(n)),o<e.episodes.length-1&&t.push("")}),t.push("</script>"),t}case"episode":return xc(e.value);case"episode-span":{let t=[...Pn(e.extend),`<episode-span from=${e.from} through=${e.through}>`];return e.episodes.forEach((n,o)=>{t.push(...xc(n)),o<e.episodes.length-1&&t.push("")}),t.push("</episode-span>"),t}case"scene":return Ec(e.value,`id=${e.value.scene_id} parent=${e.parent}`);case"scene-span":{let t=[...Pn(e.extend),`<scene-span parent=${e.parent} from=${e.from} through=${e.through}>`];return e.scenes.forEach((n,o)=>{t.push(...Ec(n,`id=${n.scene_id}`)),o<e.scenes.length-1&&t.push("")}),t.push("</scene-span>"),t}case"action-span":{let t=[...Pn(e.extend),`<action-span parent=${e.parent} from=${e.from} through=${e.through}>`,"<body>"];for(let n of e.actions)t.push(...eu(n));return t.push("</body>","</action-span>"),t}}}function tu(e){let t=["<authoring version=1>",""];if(e.declarations.length>0){t.push("<create>");for(let n of e.declarations)t.push(...Ow(n));t.push("</create>","")}return e.targets.forEach((n,o)=>{t.push(...Rw(n)),o<e.targets.length-1&&t.push("")}),t.push("","</authoring>"),`${t.join(`
125
125
  `)}
126
- `}function ze(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ut(e,t){return e[t]===void 0||typeof e[t]=="string"}function oc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(oc):ze(e)&&Object.values(e).every(oc)}function Kn(e){return e.extend===void 0||ze(e.extend)&&Object.values(e.extend).every(oc)}function ic(e){return ze(e)&&typeof e.state_id=="string"&&typeof e.state_name=="string"&&typeof e.description=="string"&&Kn(e)}function Wy(e){return ze(e)&&typeof e.actor_id=="string"&&typeof e.actor_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&It.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(ic)&&Kn(e)}function Xy(e){return ze(e)&&typeof e.location_id=="string"&&typeof e.location_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&It.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(ic)&&Kn(e)}function ew(e){return ze(e)&&typeof e.prop_id=="string"&&typeof e.prop_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&It.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(ic)&&Kn(e)}function tw(e){if(!ze(e)||typeof e.type!="string"||!Vt.has(e.type)||typeof e.content!="string"||!ut(e,"emotion"))return!1;if(e.speaker!==void 0){if(!ze(e.speaker))return!1;if(typeof e.speaker.actor_id=="string"){if(!ut(e.speaker,"state_id"))return!1}else if(typeof e.speaker.kind=="string"){if(!So.has(e.speaker.kind)||!ut(e.speaker,"label"))return!1}else return!1}return e.transition_prompt!==void 0&&(!ze(e.transition_prompt)||typeof e.transition_prompt.target!="string"||typeof e.transition_prompt.process!="string"||typeof e.transition_prompt.contrast!="string")?!1:Kn(e)}function nw(e){return!ze(e)||typeof e.scene_id!="string"||!Array.isArray(e.actors)||!Array.isArray(e.props)||!Array.isArray(e.actions)||!e.actions.every(tw)||!e.actors.every(t=>ze(t)&&typeof t.actor_id=="string"&&ut(t,"state_id"))||!e.props.every(t=>ze(t)&&typeof t.prop_id=="string"&&ut(t,"state_id"))||e.location!==null&&(!ze(e.location)||typeof e.location.location_id!="string"||!ut(e.location,"state_id"))||e.environment!==void 0&&(!ze(e.environment)||!ut(e.environment,"space")||!ut(e.environment,"time"))?!1:Kn(e)}function ow(e){return ze(e)&&typeof e.episode_id=="string"&&ut(e,"title")&&ut(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(nw)&&Kn(e)}function iw(e){return ze(e)&&e.version===3&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&ut(e,"worldview_raw")&&ut(e,"synopsis")&&ut(e,"logline")&&ut(e,"theme")&&(e.main_characters===void 0||Array.isArray(e.main_characters)&&e.main_characters.every(t=>ze(t)&&typeof t.name=="string"&&typeof t.role=="string"))&&Array.isArray(e.actors)&&e.actors.every(Wy)&&Array.isArray(e.locations)&&e.locations.every(Xy)&&Array.isArray(e.props)&&e.props.every(ew)&&Array.isArray(e.episodes)&&e.episodes.every(ow)&&Kn(e)}function bt(e){if(iw(e))return e;throw new x("The local file is not a structurally readable Script v3 document.",{exitCode:b,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 rc=[3,4],rw={3:{version:3,require:bt,requireStructurallyReadable:bt,validate:lt},4:{version:4,require:si,requireStructurallyReadable:rn,validate:Me}};function jn(e){return typeof e=="number"&&rc.some(t=>t===e)}function Ao(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new x("script.json must be an object with an explicit version.",{exitCode:b,errorCode:"SCRIPT_VERSION_MISSING",data:{expected:["version: 3 or version: 4"],actual:[Array.isArray(e)?"array":typeof e]}});let t=e.version;if(jn(t))return t;throw new x("script.json must declare version 3 or version 4.",{exitCode:b,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 sc(e){return rw[Ao(e)]}function ss(e){return sc(e).require(e)}function as(e){return sc(e).requireStructurallyReadable(e)}function tr(e){return sc(e).validate(e)}function cs(e){throw new x("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("/")&&cs(t);let o=t.slice(0,n),i=t.slice(n+1);return i!=="default"&&!V("state",i)&&cs(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}:cs(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}:cs(t)}function ko(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 bo(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 sn(e,t){return ko(e).find(n=>n.episode.episode_id===t)??null}function bn(e,t){return kn(e).find(n=>n.scene.scene_id===t)??null}function zn(e,t){throw new x(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 an(e,t){return/^[1-9]\d*$/.test(e)||zn(t,"Ordinal positions are 1-based positive integers."),Number(e)}function ds(e,t){let n=/^@ep:(\d+)$/.exec(t);if(n){let o=ko(e)[an(n[1],t)-1];return o||zn(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=ko(e)[an(n[1],t)-1],i=o?.episode.scenes[an(n[2],t)-1];return(!o||!i)&&zn(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=ko(e)[an(n[1],t)-1],i=o?.episode.scenes[an(n[2],t)-1],r=i?.actions[an(n[3],t)-1];return(!o||!i||!r)&&zn(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)[an(n[1],t)-1];return o||zn(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)[an(n[1],t)-1],i=o?.scene.actions[an(n[2],t)-1];return(!o||!i)&&zn(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=bo(e)[an(n[1],t)-1];return o||zn(t,"Global action ordinal is outside the current script."),{kind:"action",id:o.action.action_id}}return zn(t,"Ordinal anchor syntax is not supported.")}function ci(e,t){throw new x(e,{exitCode:J,errorCode:"V4_SELECTOR_INVALID",data:{expected:["typed v4 ID or same-kind inclusive range; comma joins regions"],actual:[t]}})}function Nl(e,t){return e.kind==="episode"||e.kind==="scene"||e.kind==="action"?e.kind:ci("Asset and state addresses are not narrative range anchors.",t)}function Ul(e){return e.kind==="state"?`${e.assetId}/${e.stateId}`:e.id}function Pl(e,t,n){return t.startsWith("@")?(n||ci("Ordinal anchors are query-only.",t),ds(e,t)):nr(t)}function sw(e,t,n,o){let i=e.indexOf(t),r=e.indexOf(n);(i<0||r<0)&&ci("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 ps(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=ko(e),r=kn(e),s=bo(e),c=i.map(h=>h.episode.episode_id),a=r.map(h=>h.scene.scene_id),d=s.map(h=>h.action.action_id),p=new Set,l=new Set,f=new Set,u=h=>{p.add(h);let w=i.find(y=>y.episode.episode_id===h)?.episode;w&&w.scenes.forEach(y=>{l.add(y.scene_id),y.actions.forEach(E=>f.add(E.action_id))})},g=h=>{l.add(h);let w=r.find(y=>y.scene.scene_id===h);w&&(p.add(w.episode.episode_id),w.scene.actions.forEach(y=>f.add(y.action_id)))},m=h=>{f.add(h);let w=s.find(y=>y.action.action_id===h);w&&(p.add(w.episode.episode_id),l.add(w.scene.scene_id))};for(let h of o.split(",")){let w=h.trim();w||ci("Selector contains an empty region.",o);let y=w.split("..");y.length>2&&ci("Selector region has too many range delimiters.",w);let E=Pl(e,y[0].trim(),n.allowOrdinals),I=Pl(e,(y[1]??y[0]).trim(),n.allowOrdinals),_=Nl(E,w);Nl(I,w)!==_&&ci("Range endpoints must have the same kind.",w);let A=Ul(E),k=Ul(I),O=sw(_==="episode"?c:_==="scene"?a:d,A,k,w);_==="episode"?O.forEach(u):_==="scene"?O.forEach(g):O.forEach(m)}return{isEmpty:!1,isWholeScript:!1,matchesEpisode:h=>p.has(h),matchesScene:h=>l.has(h),matchesAction:h=>f.has(h)}}function Hn(e,t){throw new x(e,{exitCode:J,errorCode:"AUTHORING_SELECTOR_INVALID",data:{actual:t}})}function aw(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function cw(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function ne(e,t,n=""){let o=[e,...t].map(aw).join("|"),i=cw(n);return`[${o}]${i?` ${i}`:""}`}function dc(e){if(Array.isArray(e))return e.map(dc);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=dc(e[n]);return t}return e}function Qn(e){return e===void 0?[]:[ne("extensions",[]),...Object.keys(e).sort().map(t=>ne("extend",[t],JSON.stringify(dc(e[t]))))]}function dw(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 Cl(e){let t=Qn(e.extend);if(e.transition_prompt!==void 0&&t.push(ne("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,dw(e.speaker)];"parenthetical"in e&&n.push(e.parenthetical??""),t.push(ne(e.type==="dialogue"?"dlg":"think",n,e.content))}else t.push(ne(e.type==="action"?"act":"trans",[e.action_id],e.content));return t}function pc(e,t){let n=[...Qn(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(ne("environment",o))}n.push(e.location===null?ne("location",[]):ne("location",[e.location.location_id,...e.location.state_ids]));for(let o of e.actors)n.push(ne("cast",[o.actor_id,...o.state_ids]));for(let o of e.props)n.push(ne("prop",[o.prop_id,...o.state_ids]));return n.push("","<body>"),e.actions.forEach(o=>n.push(...Cl(o))),n.push("</body>","","</scene>"),n}function lc(e){let t=[...Qn(e.extend),`<episode id=${e.episode_id}>`];return e.title!==void 0&&t.push(ne("title",[],e.title)),e.synopsis!==void 0&&t.push(ne("synopsis",[],e.synopsis)),e.scenes.forEach((n,o)=>{(o>0||e.title!==void 0||e.synopsis!==void 0)&&t.push(""),t.push(...pc(n,`id=${n.scene_id}`))}),t.push("</episode>"),t}function ac(e,t){return[...Qn(t.extend),ne("state",[e,t.state_id,t.state_name],t.description)]}function pw(e){let t=["<create>"];for(let n of e.actors){t.push(...Qn(n.extend)),n.aliases!==void 0&&(t.push(ne("aliases",[])),n.aliases.forEach(i=>t.push(ne("alias",[],i))));let o=[n.actor_id,n.actor_name,n.importance];n.role_type!==void 0&&o.push(n.role_type),t.push(ne("actor",o,n.description)),n.states.forEach(i=>t.push(...ac(n.actor_id,i)))}for(let n of e.locations)t.push(...Qn(n.extend)),n.aliases!==void 0&&(t.push(ne("aliases",[])),n.aliases.forEach(o=>t.push(ne("alias",[],o)))),t.push(ne("location",[n.location_id,n.location_name,n.importance],n.description)),n.states.forEach(o=>t.push(...ac(n.location_id,o)));for(let n of e.props)t.push(...Qn(n.extend)),n.aliases!==void 0&&(t.push(ne("aliases",[])),n.aliases.forEach(o=>t.push(ne("alias",[],o)))),t.push(ne("prop",[n.prop_id,n.prop_name,n.importance],n.description)),n.states.forEach(o=>t.push(...ac(n.prop_id,o)));return t.push("</create>"),t}function lw(e){let t=[...Qn(e.extend),"<script>"];return t.push(ne("title",[],e.title),ne("worldview",[],e.worldview)),e.worldview_raw!==void 0&&t.push(ne("worldview-raw",[],e.worldview_raw)),t.push(ne("style",[],e.style)),e.synopsis!==void 0&&t.push(ne("synopsis",[],e.synopsis)),e.logline!==void 0&&t.push(ne("logline",[],e.logline)),e.theme!==void 0&&t.push(ne("theme",[],e.theme)),e.main_characters!==void 0&&(t.push(ne("main-characters",[])),e.main_characters.forEach(n=>t.push(ne("main-character",[n.name,n.role])))),e.episodes.forEach(n=>t.push("",...lc(n))),t.push("</script>"),t}function uw(e){return e.trim()||Hn("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]?Hn("Selector region is invalid.",[t]):{left:n[0],right:n[1]??n[0]}})}function cc(e,t,n,o,i){let r=-1;return uw(i).map(s=>{let c=f=>{if(!f.startsWith("@"))return f;let u=ds(e,f);return u.kind!==t?Hn("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)&&Hn("Selector endpoint was not found.",[s.left,s.right]);let p=Math.min(a,d),l=Math.max(a,d);return p<=r&&Hn("Selector regions must follow current document order without overlap.",[`${s.left}..${s.right}`]),r=l,n.slice(p,l+1)})}function Tl(e,t,n){let o=["<authoring version=1>",""],i=0;if(t==="script")o.push(...pw(e),"",...lw(e)),i=1;else if(t==="episodes"){let r=ps(e,n,{allowOrdinals:!0}),s=e.episodes.filter(c=>r.matchesEpisode(c.episode_id));s.forEach((c,a)=>{a>0&&o.push(""),o.push(...lc(c))}),i=s.length}else if(t==="episode-spans"){let r=cc(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(...lc(a))),o.push("</episode-span>"),i++}else if(t==="scenes"){let r=ps(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(...pc(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=cc(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)||Hn("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(...pc(p.scene,`id=${p.scene.scene_id}`))),o.push("</scene-span>"),i++}}else{let r=bo(e),s=cc(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)||Hn("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(...Cl(p.action))),o.push("</body>","</action-span>"),i++}}return i===0&&Hn("Selector did not match any authoring targets.",[n||"<empty>"]),o.push("","</authoring>"),{content:`${o.join(`
126
+ `}function He(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function wt(e,t){return e[t]===void 0||typeof e[t]=="string"}function Sc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Sc):He(e)&&Object.values(e).every(Sc)}function no(e){return e.extend===void 0||He(e.extend)&&Object.values(e.extend).every(Sc)}function Ic(e){return He(e)&&typeof e.state_id=="string"&&typeof e.state_name=="string"&&typeof e.description=="string"&&no(e)}function Mw(e){return He(e)&&typeof e.actor_id=="string"&&typeof e.actor_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&Mt.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(Ic)&&no(e)}function Lw(e){return He(e)&&typeof e.location_id=="string"&&typeof e.location_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&Mt.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(Ic)&&no(e)}function Nw(e){return He(e)&&typeof e.prop_id=="string"&&typeof e.prop_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&Mt.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(Ic)&&no(e)}function Uw(e){if(!He(e)||typeof e.type!="string"||!zt.has(e.type)||typeof e.content!="string"||!wt(e,"emotion"))return!1;if(e.speaker!==void 0){if(!He(e.speaker))return!1;if(typeof e.speaker.actor_id=="string"){if(!wt(e.speaker,"state_id"))return!1}else if(typeof e.speaker.kind=="string"){if(!Po.has(e.speaker.kind)||!wt(e.speaker,"label"))return!1}else return!1}return e.transition_prompt!==void 0&&(!He(e.transition_prompt)||typeof e.transition_prompt.target!="string"||typeof e.transition_prompt.process!="string"||typeof e.transition_prompt.contrast!="string")?!1:no(e)}function Cw(e){return!He(e)||typeof e.scene_id!="string"||!Array.isArray(e.actors)||!Array.isArray(e.props)||!Array.isArray(e.actions)||!e.actions.every(Uw)||!e.actors.every(t=>He(t)&&typeof t.actor_id=="string"&&wt(t,"state_id"))||!e.props.every(t=>He(t)&&typeof t.prop_id=="string"&&wt(t,"state_id"))||e.location!==null&&(!He(e.location)||typeof e.location.location_id!="string"||!wt(e.location,"state_id"))||e.environment!==void 0&&(!He(e.environment)||!wt(e.environment,"space")||!wt(e.environment,"time"))?!1:no(e)}function Pw(e){return He(e)&&typeof e.episode_id=="string"&&wt(e,"title")&&wt(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(Cw)&&no(e)}function Tw(e){return He(e)&&e.version===3&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&wt(e,"worldview_raw")&&wt(e,"synopsis")&&wt(e,"logline")&&wt(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(Mw)&&Array.isArray(e.locations)&&e.locations.every(Lw)&&Array.isArray(e.props)&&e.props.every(Nw)&&Array.isArray(e.episodes)&&e.episodes.every(Pw)&&no(e)}function Nt(e){if(Tw(e))return e;throw new E("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 Ac=[3,4],Vw={3:{version:3,require:Nt,requireStructurallyReadable:Nt,validate:yt},4:{version:4,require:_i,requireStructurallyReadable:mn,validate:Le}};function oo(e){return typeof e=="number"&&Ac.some(t=>t===e)}function Vo(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new E("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(oo(t))return t;throw new E("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 kc(e){return Vw[Vo(e)]}function Es(e){return kc(e).require(e)}function Ss(e){return kc(e).requireStructurallyReadable(e)}function mr(e){return kc(e).validate(e)}function Is(e){throw new E("Use a bare typed v4 ID or asset/state address.",{exitCode:G,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 gr(e){let t=typeof e=="string"?e.trim():"",n=t.indexOf("/");if(n>=0){n!==t.lastIndexOf("/")&&Is(t);let o=t.slice(0,n),i=t.slice(n+1);return i!=="default"&&!V("state",i)&&Is(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}:Is(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}:Is(t)}function $o(e){return e.episodes.map((t,n)=>({episode:t,episodeIndex:n}))}function Tn(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 Do(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 gn(e,t){return $o(e).find(n=>n.episode.episode_id===t)??null}function Vn(e,t){return Tn(e).find(n=>n.scene.scene_id===t)??null}function io(e,t){throw new E(t,{exitCode:G,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 hn(e,t){return/^[1-9]\d*$/.test(e)||io(t,"Ordinal positions are 1-based positive integers."),Number(e)}function As(e,t){let n=/^@ep:(\d+)$/.exec(t);if(n){let o=$o(e)[hn(n[1],t)-1];return o||io(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=$o(e)[hn(n[1],t)-1],i=o?.episode.scenes[hn(n[2],t)-1];return(!o||!i)&&io(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=$o(e)[hn(n[1],t)-1],i=o?.episode.scenes[hn(n[2],t)-1],r=i?.actions[hn(n[3],t)-1];return(!o||!i||!r)&&io(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=Tn(e)[hn(n[1],t)-1];return o||io(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=Tn(e)[hn(n[1],t)-1],i=o?.scene.actions[hn(n[2],t)-1];return(!o||!i)&&io(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=Do(e)[hn(n[1],t)-1];return o||io(t,"Global action ordinal is outside the current script."),{kind:"action",id:o.action.action_id}}return io(t,"Ordinal anchor syntax is not supported.")}function Si(e,t){throw new E(e,{exitCode:G,errorCode:"V4_SELECTOR_INVALID",data:{expected:["typed v4 ID or same-kind inclusive range; comma joins regions"],actual:[t]}})}function nu(e,t){return e.kind==="episode"||e.kind==="scene"||e.kind==="action"?e.kind:Si("Asset and state addresses are not narrative range anchors.",t)}function ou(e){return e.kind==="state"?`${e.assetId}/${e.stateId}`:e.id}function iu(e,t,n){return t.startsWith("@")?(n||Si("Ordinal anchors are query-only.",t),As(e,t)):gr(t)}function $w(e,t,n,o){let i=e.indexOf(t),r=e.indexOf(n);(i<0||r<0)&&Si("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=$o(e),r=Tn(e),s=Do(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(x=>f.add(x.action_id))})},h=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)))},m=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||Si("Selector contains an empty region.",o);let y=w.split("..");y.length>2&&Si("Selector region has too many range delimiters.",w);let x=iu(e,y[0].trim(),n.allowOrdinals),S=iu(e,(y[1]??y[0]).trim(),n.allowOrdinals),_=nu(x,w);nu(S,w)!==_&&Si("Range endpoints must have the same kind.",w);let A=ou(x),b=ou(S),O=$w(_==="episode"?c:_==="scene"?a:d,A,b,w);_==="episode"?O.forEach(u):_==="scene"?O.forEach(h):O.forEach(m)}return{isEmpty:!1,isWholeScript:!1,matchesEpisode:g=>p.has(g),matchesScene:g=>l.has(g),matchesAction:g=>f.has(g)}}function ro(e,t){throw new E(e,{exitCode:G,errorCode:"AUTHORING_SELECTOR_INVALID",data:{actual:t}})}function Dw(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function Gw(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function ne(e,t,n=""){let o=[e,...t].map(Dw).join("|"),i=Gw(n);return`[${o}]${i?` ${i}`:""}`}function vc(e){if(Array.isArray(e))return e.map(vc);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=vc(e[n]);return t}return e}function so(e){return e===void 0?[]:[ne("extensions",[]),...Object.keys(e).sort().map(t=>ne("extend",[t],JSON.stringify(vc(e[t]))))]}function Jw(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 ru(e){let t=so(e.extend);if(e.transition_prompt!==void 0&&t.push(ne("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,Jw(e.speaker)];"parenthetical"in e&&n.push(e.parenthetical??""),t.push(ne(e.type==="dialogue"?"dlg":"think",n,e.content))}else t.push(ne(e.type==="action"?"act":"trans",[e.action_id],e.content));return t}function Rc(e,t){let n=[...so(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(ne("environment",o))}n.push(e.location===null?ne("location",[]):ne("location",[e.location.location_id,...e.location.state_ids]));for(let o of e.actors)n.push(ne("cast",[o.actor_id,...o.state_ids]));for(let o of e.props)n.push(ne("prop",[o.prop_id,...o.state_ids]));return n.push("","<body>"),e.actions.forEach(o=>n.push(...ru(o))),n.push("</body>","","</scene>"),n}function Mc(e){let t=[...so(e.extend),`<episode id=${e.episode_id}>`];return e.title!==void 0&&t.push(ne("title",[],e.title)),e.synopsis!==void 0&&t.push(ne("synopsis",[],e.synopsis)),e.scenes.forEach((n,o)=>{(o>0||e.title!==void 0||e.synopsis!==void 0)&&t.push(""),t.push(...Rc(n,`id=${n.scene_id}`))}),t.push("</episode>"),t}function bc(e,t){return[...so(t.extend),ne("state",[e,t.state_id,t.state_name],t.description)]}function Bw(e){let t=["<create>"];for(let n of e.actors){t.push(...so(n.extend)),n.aliases!==void 0&&(t.push(ne("aliases",[])),n.aliases.forEach(i=>t.push(ne("alias",[],i))));let o=[n.actor_id,n.actor_name,n.importance];n.role_type!==void 0&&o.push(n.role_type),t.push(ne("actor",o,n.description)),n.states.forEach(i=>t.push(...bc(n.actor_id,i)))}for(let n of e.locations)t.push(...so(n.extend)),n.aliases!==void 0&&(t.push(ne("aliases",[])),n.aliases.forEach(o=>t.push(ne("alias",[],o)))),t.push(ne("location",[n.location_id,n.location_name,n.importance],n.description)),n.states.forEach(o=>t.push(...bc(n.location_id,o)));for(let n of e.props)t.push(...so(n.extend)),n.aliases!==void 0&&(t.push(ne("aliases",[])),n.aliases.forEach(o=>t.push(ne("alias",[],o)))),t.push(ne("prop",[n.prop_id,n.prop_name,n.importance],n.description)),n.states.forEach(o=>t.push(...bc(n.prop_id,o)));return t.push("</create>"),t}function Kw(e){let t=[...so(e.extend),"<script>"];return t.push(ne("title",[],e.title),ne("worldview",[],e.worldview)),e.worldview_raw!==void 0&&t.push(ne("worldview-raw",[],e.worldview_raw)),t.push(ne("style",[],e.style)),e.synopsis!==void 0&&t.push(ne("synopsis",[],e.synopsis)),e.logline!==void 0&&t.push(ne("logline",[],e.logline)),e.theme!==void 0&&t.push(ne("theme",[],e.theme)),e.main_characters!==void 0&&(t.push(ne("main-characters",[])),e.main_characters.forEach(n=>t.push(ne("main-character",[n.name,n.role])))),e.episodes.forEach(n=>t.push("",...Mc(n))),t.push("</script>"),t}function jw(e){return e.trim()||ro("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]?ro("Selector region is invalid.",[t]):{left:n[0],right:n[1]??n[0]}})}function Oc(e,t,n,o,i){let r=-1;return jw(i).map(s=>{let c=f=>{if(!f.startsWith("@"))return f;let u=As(e,f);return u.kind!==t?ro("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)&&ro("Selector endpoint was not found.",[s.left,s.right]);let p=Math.min(a,d),l=Math.max(a,d);return p<=r&&ro("Selector regions must follow current document order without overlap.",[`${s.left}..${s.right}`]),r=l,n.slice(p,l+1)})}function su(e,t,n){let o=["<authoring version=1>",""],i=0;if(t==="script")o.push(...Bw(e),"",...Kw(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(...Mc(c))}),i=s.length}else if(t==="episode-spans"){let r=Oc(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(...Mc(a))),o.push("</episode-span>"),i++}else if(t==="scenes"){let r=ks(e,n,{allowOrdinals:!0}),s=Tn(e).filter(c=>r.matchesScene(c.scene.scene_id));s.forEach((c,a)=>{a>0&&o.push(""),o.push(...Rc(c.scene,`id=${c.scene.scene_id} parent=${c.episode.episode_id}`))}),i=s.length}else if(t==="scene-spans"){let r=Tn(e),s=Oc(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)||ro("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(...Rc(p.scene,`id=${p.scene.scene_id}`))),o.push("</scene-span>"),i++}}else{let r=Do(e),s=Oc(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)||ro("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(...ru(p.action))),o.push("</body>","</action-span>"),i++}}return i===0&&ro("Selector did not match any authoring targets.",[n||"<empty>"]),o.push("","</authoring>"),{content:`${o.join(`
127
127
  `)}
128
- `,targetCount:i}}function re(e,t,n,o,i=b){throw new x(t,{exitCode:i,errorCode:e,hint:o,data:{actual:n}})}function fw(e){let t=Se(e),n;try{n=JSON.parse($l.readFileSync(t,"utf-8"))}catch(o){re("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 as(n)}function or(e){return e||re("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||re("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&&re("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)&&re("AUTHORING_SELECTOR_INVALID","Selector range endpoint is empty.",[n],"Provide both endpoints.",J),{from:i,through:r}})}function ls(e,t,n){if(t.from==="*"&&t.through==="*")return e.length===0&&re("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)&&re("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)&&re("AUTHORING_SELECTOR_NOT_FOUND",`${n} selector endpoint was not found.`,[t.from,t.through],"Use IDs from the current local script."),o>i&&re("AUTHORING_SELECTOR_REVERSED",`${n} selector is reversed in current document order.`,[t.from,t.through],"Put the earlier document endpoint first."),[o,i]}function Gl(e,t){let n=new Set;for(let o of e){let i=t(o);n.has(i)&&re("AUTHORING_SELECTOR_OVERLAP","Selector regions overlap or repeat a target.",[i],"Use non-overlapping regions."),n.add(i)}return e}function ir(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&&re("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 mw(e,t){let n=[],o=e.episodes.map(r=>r.episode_id);for(let r of or(t)){let[s,c]=ls(o,r,"episode");n.push(...e.episodes.slice(s,c+1))}Gl(n,r=>r.episode_id),ir(n.map(r=>[o.indexOf(r.episode_id)]),"Episode");let i=n.map(r=>({kind:"episode",value:structuredClone(r),source:$t}));return ai("episode",i)}function gw(e,t){let n=e.episodes.map(s=>s.episode_id),o=[],i=new Set,r=[];for(let s of or(t)){let[c,a]=ls(n,s,"episode");for(let d=c;d<=a;d+=1)i.has(d)&&re("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:$t}),r.push([c])}return ir(r,"Episode span"),ai("episode-span",o)}function hw(e){return e.episodes.flatMap(t=>t.scenes.map(n=>({episodeId:t.episode_id,scene:n})))}function uc(e){return`${e.episodeId}/${e.scene.scene_id}`}function yw(e,t){let n=hw(e),o=n.map(uc),i=[];for(let s of or(t)){let[c,a]=ls(o,s,"scene");i.push(...n.slice(c,a+1))}Gl(i,uc),ir(i.map(s=>[o.indexOf(uc(s))]),"Scene");let r=i.map(s=>({kind:"scene",parent:s.episodeId,value:structuredClone(s.scene),source:$t}));return ai("scene",r)}function fc(e){let t=/^([^/#]+)\/([^/#]+)$/.exec(e);return t||re("AUTHORING_SELECTOR_INVALID","Scene selector endpoint must be ep/scn.",[e],"Use ep_ID/scn_ID."),{episodeId:t[1],sceneId:t[2]}}function ww(e,t){let n=[],o=new Set,i=[];for(let r of or(t)){(r.from==="*"||r.through==="*")&&re("AUTHORING_SELECTOR_INVALID","A scene span wildcard has no single parent.",["*"],"Use one explicit region per episode.");let s=fc(r.from),c=fc(r.through);s.episodeId!==c.episodeId&&re("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&&re("AUTHORING_SELECTOR_NOT_FOUND","Scene span parent episode was not found.",[s.episodeId],"Use an existing episode ID."),a.length>1&&re("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]=ls(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)&&re("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:$t}),i.push([e.episodes.indexOf(d),l])}return ir(i,"Scene span"),ai("scene-span",n)}function Vl(e){let t=/^([^/#]+\/[^/#]+)#(\d+)$/.exec(e);t||re("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)||re("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 Ew(e,t){let n=[],o=new Set,i=[];for(let r of or(t)){(r.from==="*"||r.through==="*")&&re("AUTHORING_SELECTOR_INVALID","An action span wildcard has no single parent.",["*"],"Use one explicit region per scene.");let s=Vl(r.from),c=Vl(r.through);s.parent!==c.parent&&re("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=fc(s.parent),d=e.episodes.filter(u=>u.episode_id===a.episodeId);d.length===0&&re("AUTHORING_SELECTOR_NOT_FOUND","Action span parent episode was not found.",[a.episodeId],"Use an existing episode ID."),d.length>1&&re("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&&re("AUTHORING_SELECTOR_NOT_FOUND","Action span parent scene was not found.",[s.parent],"Use an existing scene address."),l.length>1&&re("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&&re("AUTHORING_SELECTOR_REVERSED","Action span is reversed.",[r.from,r.through],"Put the lower current action index first."),c.index>=f.actions.length&&re("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)&&re("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:$t}),i.push([e.episodes.indexOf(p),p.scenes.indexOf(f),s.index])}return ir(i,"Action span"),ai("action-span",n)}function Jl(e,t){let n=v(t.output).trim();n||re("AUTHORING_OUTPUT_REQUIRED","Export requires --output.",["<missing>"],"Pass a destination .scriptctl file.",J);let o=fw(t),i=v(t.in).trim(),r=Dl.resolve(n);if(o.version===4){let p=Tl(rn(o),e,i);return os(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=bt(o),c;e==="script"?c=Rl(s):e==="episodes"?c=mw(s,i):e==="episode-spans"?c=gw(s,i):e==="scenes"?c=yw(s,i):e==="scene-spans"?c=ww(s,i):c=Ew(s,i);let a=Ll(c);return os(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 Nc from"node:crypto";import*as cr from"node:fs";import*as mu from"node:path";function Q(e,t,n,o,i=b){throw new x(t,{exitCode:i,errorCode:e,hint:o[0],data:{actual:n}})}function se(e){return`line ${e.line}, column ${e.column}`}function us(e){if(Array.isArray(e))return e.map(us);if(e!==null&&typeof e=="object"){let t={};for(let[n,o]of Object.entries(e).sort(([i],[r])=>i.localeCompare(r)))t[n]=us(o);return t}return e}function Fn(e,t){return JSON.stringify(us(e))===JSON.stringify(us(t))}function rr(e,t){return"actor_id"in t?t.actor_id:"location_id"in t?t.location_id:t.prop_id}function _w(e,t){return"actor_name"in t?t.actor_name:"location_name"in t?t.location_name:t.prop_name}function xw(e,t){return t==="actor"?e.actors:t==="location"?e.locations:e.props}function Sw(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 Fl(e,t,n){return xw(e,t).find(o=>rr(t,o)===n)}function Iw(e,t){for(let n of["actor","location","prop"]){let o=Fl(e,n,t);if(o!==void 0)return{kind:n,value:o}}}function Aw(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.",[se(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.",[se(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}:${rr(p,l)}`;c.has(u)&&Q("AUTHORING_DECLARATION_DUPLICATE","Asset declaration is duplicated.",[se(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&&rr(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=rr(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.",[se(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.",[se(a.source),`${a.kind}:${d}`],["Keep exactly one default state."]);let p=a.value.aliases??[];(new Set(p).size!==p.length||p.includes(_w(a.kind,a.value)))&&Q("AUTHORING_ALIAS_INVALID","Asset aliases must be unique and must differ from the canonical name.",[se(a.source),`${a.kind}:${d}`],["Remove duplicate aliases and the canonical name from aliases."])}return{assets:t,states:n}}function kw(){return{createdAssets:[],existingAssets:[],createdStates:[],existingStates:[]}}function Yl(e,t){let n=Aw(t),o=kw();for(let i of n.assets){let r=rr(i.kind,i.value),s=`${i.kind}:${r}`,c=Iw(e,r);if(c!==void 0){if(c.kind===i.kind&&Fn(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.",[se(i.source),`${i.kind}:${r}`],["Use the existing identical definition or change it with an explicit mutation verb."])}Sw(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=Fl(e,i.kind,i.ownerId);r===void 0&&Q("AUTHORING_STATE_OWNER_NOT_FOUND","Standalone state owner does not exist.",[se(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&&!Fn(s,i.value)&&Q("AUTHORING_STATE_CONFLICT","Create-only state declaration conflicts with an existing state on the same asset.",[se(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 Bl(e){return{episodes:0,scenes:e===void 0?0:1,actions:e?.actions.length??0}}function Kl(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 jl(e){return{episodes:0,scenes:e.length,actions:e.reduce((t,n)=>t+n.actions.length,0)}}function sr(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 mc(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.",[se(t),...n],["Add the concrete state ID to every location, cast, and prop record."])}function gc(e,t){for(let n of e.scenes)mc(n,t)}function Oo(e,t){return e.episodes.findIndex(n=>n.episode_id===t)}function ms(e,t){return e.scenes.findIndex(n=>n.scene_id===t)}function ql(e,t,n){let o=Oo(e,t);o<0&&Q("AUTHORING_EPISODE_NOT_FOUND","Episode target does not exist.",[t],["Inspect episodes and use an existing parent."]);let i=ms(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 bw(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 ar(e,t){for(let n=1;n<e.length;n+=1)bw(e[n-1].coord,e[n].coord)>=0&&Q("AUTHORING_TARGET_ORDER",t,[se(e[n].source)],["List replace targets in current document order without duplicates."],J)}function Ow(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>{let c=Oo(e,s.value.episode_id);return c<0&&Q("AUTHORING_EPISODE_NOT_FOUND","Episode replace target does not exist.",[se(s.source),s.value.episode_id],["Use --create for a new episode or choose an existing ID."]),{coord:[c],source:s.source}});ar(r,"Episode replace targets are not in document order.")}for(let r of n){gc(r.value,r.source);let s=Oo(e,r.value.episode_id),c=s<0?void 0:e.episodes[s];o==="create"?c!==void 0?Fn(c,r.value)||Q("AUTHORING_CREATE_CONFLICT","Episode create target already exists with different content.",[se(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:Kl(c),after:Kl(r.value),...sr(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 vw(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>({coord:ql(e,s.parent,s.value.scene_id),source:s.source}));ar(r,"Scene replace targets are not in document order.")}for(let r of n){mc(r.value,r.source);let s=Oo(e,r.parent);s<0&&Q("AUTHORING_EPISODE_NOT_FOUND","Scene parent episode does not exist.",[se(r.source),r.parent],["Use an existing episode parent."]);let c=e.episodes[s],a=t.episodes[s],d=ms(c,r.value.scene_id),p=d<0?void 0:c.scenes[d];o==="create"?p!==void 0?Fn(p,r.value)||Q("AUTHORING_CREATE_CONFLICT","Scene create target already exists with different content.",[se(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.",[se(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:Bl(p),after:Bl(r.value),...sr(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 Rw(e,t,n){let o=n.map(r=>{let s=Oo(e,r.from),c=Oo(e,r.through);(s<0||c<0)&&Q("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Episode-span endpoint does not exist.",[se(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.",[se(r.source),`${r.from}..${r.through}`],["Swap from and through."]),r.episodes.length===0&&Q("AUTHORING_EMPTY_SPAN","Episode-span replacement cannot be empty.",[se(r.source)],["Include at least one complete episode."]);for(let a of r.episodes)gc(a,r.source);return{target:r,from:s,through:c}});ar(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.",[se(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),...sr(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 Mw(e,t,n){let o=n.map(s=>{let c=Oo(e,s.parent);c<0&&Q("AUTHORING_EPISODE_NOT_FOUND","Scene-span parent does not exist.",[se(s.source),s.parent],["Use an existing parent episode."]);let a=e.episodes[c],d=ms(a,s.from),p=ms(a,s.through);(d<0||p<0)&&Q("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Scene-span endpoint does not exist in its parent.",[se(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.",[se(s.source),`${s.from}..${s.through}`],["Swap from and through."]),s.scenes.length===0&&Q("AUTHORING_EMPTY_SPAN","Scene-span replacement cannot be empty.",[se(s.source)],["Include at least one complete scene."]);for(let l of s.scenes)mc(l,s.source);return{target:s,epIndex:c,from:d,through:p}});ar(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.",[se(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:jl(p),after:jl(s.scenes),...sr(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 Lw(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.",[se(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]=ql(e,a,d),f=e.episodes[p].scenes[l];return s.from>s.through&&Q("AUTHORING_SPAN_REVERSED","Action-span endpoints are reversed.",[se(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.",[se(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.",[se(s.source)],["Include at least one action."]),{target:s,epIndex:p,scIndex:l,scene:f,from:s.from,through:s.through}});ar(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.",[se(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 Zl(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 Nw(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 zl(e,t){return`${e.code}\0${Nw(e.path,t)}\0${e.message}`}function Uw(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 Pw(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 Hl(e,t,n){let o=lt(t),i=Uw(n),r=()=>({...o,warnings:[...o.warnings,...Pw(e,t,i)]});if(o.ok||e!==null&&Fn(e,t))return r();let s=new Set(e===null?[]:lt(e).errors.map(a=>zl(a,e))),c=o.errors.filter(a=>{if(!s.has(zl(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 Ql(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 Cw(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."],J);for(let i of t.episodes)gc(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=Yl(n,e.declarations);return Zl(n),{script:n,declarations:o}}function Wl(e,t,n){if(t.targetKind==="script"){n!=="create"&&Q("AUTHORING_TARGET_MODE","Script targets support create only.",[n],["Use --create."],J);let a=Cw(t),d=a.script;e!==null&&!Fn(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=Hl(e,d,t.targets);return{script:d,changed:e===null||!Fn(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),...sr(e?.episodes.map(f=>f.episode_id)??[],d.episodes.map(f=>f.episode_id)),untouchedSiblings:0}],retainedOrphanAssets:Ql(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."],J);let o=structuredClone(e),i=structuredClone(e),r=Yl(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."],J),s=Ow(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."],J),s=vw(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."],J),s=Rw(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."],J),s=Mw(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."],J),s=Lw(o,i,a);break}default:Q("AUTHORING_TARGET_MODE","Unsupported authoring target.",[t.targetKind],["Use a supported homogeneous target kind."])}Zl(i);let c=Hl(e,i,t.targets);return{script:i,changed:!Fn(e,i),declarations:r,targets:s,retainedOrphanAssets:Ql(i),validation:c}}function $(e,t,n,o){return new x(e,{exitCode:b,errorCode:"AUTHORING_SOURCE_INVALID",hint:o,data:{actual:[`line ${t.line}, column ${t.column}: ${n}`]}})}function hc(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 di(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 g=1;g<o.length;g+=1){let m=o[g];if(r){r=!1;continue}if(m==="\\"){r=!0;continue}if(m==="]"){i=g;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 g=0;g<s.length;g+=1){let m=s[g];r?(a+=`\\${m}`,r=!1):m==="\\"?r=!0:m==="|"?(c.push(a),a=""):a+=m}r&&(a+="\\"),c.push(a);let[d,...p]=c,l=hc(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(g=>hc(g,n,!0)),content:hc(u,{line:t,column:i+2},!1),source:n}}function ft(){return{extend:{},extendPresent:!1,aliases:[],aliasesPresent:!1,phase:"extend"}}function On(e){return e.extendPresent||e.aliasesPresent||e.prompt!==void 0}function mt(e){return e.extendPresent?e.extend:void 0}function yc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(yc):typeof e!="object"?!1:Object.values(e).every(yc)}function wc(e){if(Array.isArray(e))return e.map(wc);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=wc(e[n]);return t}return e}function Xl(e){return e==="featured"||e==="background"}function Tw(e){return e==="\u4E3B\u89D2"||e==="\u914D\u89D2"}function Vw(e){return e==="system"||e==="broadcast"||e==="offscreen"||e==="group"}function $w(e){return e==="actor"||e==="location"||e==="prop"}function eu(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 Dw(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 cn(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 Gw(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(!So.has(r)||!Vw(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 Jw(e,t){let o={act:"action",dlg:"dialogue",think:"inner_thought",trans:"transition"}[e.type];if(o===void 0||!Vt.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=Gw(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=mt(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 Ec=class{lines;index=0;constructor(t){this.lines=t.replace(/\r\n?/g,`
128
+ `,targetCount:i}}function se(e,t,n,o,i=k){throw new E(t,{exitCode:i,errorCode:e,hint:o,data:{actual:n}})}function zw(e){let t=Ae(e),n;try{n=JSON.parse(cu.readFileSync(t,"utf-8"))}catch(o){se("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 Ss(n)}function hr(e){return e||se("AUTHORING_SELECTOR_REQUIRED","This export kind requires --in.",["<missing>"],"Pass one or more comma-separated point or from..through regions.",G),e.split(",").map(t=>{let n=t.trim();n||se("AUTHORING_SELECTOR_INVALID","Selector contains an empty region.",[e],"Remove empty comma-separated regions.",G);let o=n.indexOf("..");if(o<0)return{from:n,through:n};n.indexOf("..",o+2)>=0&&se("AUTHORING_SELECTOR_INVALID","Selector region has more than one range delimiter.",[n],"Use point or from..through.",G);let i=n.slice(0,o),r=n.slice(o+2);return(!i||!r)&&se("AUTHORING_SELECTOR_INVALID","Selector range endpoint is empty.",[n],"Provide both endpoints.",G),{from:i,through:r}})}function bs(e,t,n){if(t.from==="*"&&t.through==="*")return e.length===0&&se("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)&&se("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)&&se("AUTHORING_SELECTOR_NOT_FOUND",`${n} selector endpoint was not found.`,[t.from,t.through],"Use IDs from the current local script."),o>i&&se("AUTHORING_SELECTOR_REVERSED",`${n} selector is reversed in current document order.`,[t.from,t.through],"Put the earlier document endpoint first."),[o,i]}function pu(e,t){let n=new Set;for(let o of e){let i=t(o);n.has(i)&&se("AUTHORING_SELECTOR_OVERLAP","Selector regions overlap or repeat a target.",[i],"Use non-overlapping regions."),n.add(i)}return e}function yr(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&&se("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 Hw(e,t){let n=[],o=e.episodes.map(r=>r.episode_id);for(let r of hr(t)){let[s,c]=bs(o,r,"episode");n.push(...e.episodes.slice(s,c+1))}pu(n,r=>r.episode_id),yr(n.map(r=>[o.indexOf(r.episode_id)]),"Episode");let i=n.map(r=>({kind:"episode",value:structuredClone(r),source:Ht}));return Ei("episode",i)}function Qw(e,t){let n=e.episodes.map(s=>s.episode_id),o=[],i=new Set,r=[];for(let s of hr(t)){let[c,a]=bs(n,s,"episode");for(let d=c;d<=a;d+=1)i.has(d)&&se("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:Ht}),r.push([c])}return yr(r,"Episode span"),Ei("episode-span",o)}function Fw(e){return e.episodes.flatMap(t=>t.scenes.map(n=>({episodeId:t.episode_id,scene:n})))}function Lc(e){return`${e.episodeId}/${e.scene.scene_id}`}function Yw(e,t){let n=Fw(e),o=n.map(Lc),i=[];for(let s of hr(t)){let[c,a]=bs(o,s,"scene");i.push(...n.slice(c,a+1))}pu(i,Lc),yr(i.map(s=>[o.indexOf(Lc(s))]),"Scene");let r=i.map(s=>({kind:"scene",parent:s.episodeId,value:structuredClone(s.scene),source:Ht}));return Ei("scene",r)}function Nc(e){let t=/^([^/#]+)\/([^/#]+)$/.exec(e);return t||se("AUTHORING_SELECTOR_INVALID","Scene selector endpoint must be ep/scn.",[e],"Use ep_ID/scn_ID."),{episodeId:t[1],sceneId:t[2]}}function qw(e,t){let n=[],o=new Set,i=[];for(let r of hr(t)){(r.from==="*"||r.through==="*")&&se("AUTHORING_SELECTOR_INVALID","A scene span wildcard has no single parent.",["*"],"Use one explicit region per episode.");let s=Nc(r.from),c=Nc(r.through);s.episodeId!==c.episodeId&&se("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&&se("AUTHORING_SELECTOR_NOT_FOUND","Scene span parent episode was not found.",[s.episodeId],"Use an existing episode ID."),a.length>1&&se("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]=bs(p,{from:s.sceneId,through:c.sceneId},"scene");for(let u=l;u<=f;u+=1){let h=`${d.episode_id}/${p[u]}`;o.has(h)&&se("AUTHORING_SELECTOR_OVERLAP","Scene span regions overlap.",[h],"Use non-overlapping regions."),o.add(h)}n.push({kind:"scene-span",parent:d.episode_id,from:p[l],through:p[f],scenes:structuredClone(d.scenes.slice(l,f+1)),source:Ht}),i.push([e.episodes.indexOf(d),l])}return yr(i,"Scene span"),Ei("scene-span",n)}function au(e){let t=/^([^/#]+\/[^/#]+)#(\d+)$/.exec(e);t||se("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)||se("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 Zw(e,t){let n=[],o=new Set,i=[];for(let r of hr(t)){(r.from==="*"||r.through==="*")&&se("AUTHORING_SELECTOR_INVALID","An action span wildcard has no single parent.",["*"],"Use one explicit region per scene.");let s=au(r.from),c=au(r.through);s.parent!==c.parent&&se("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=Nc(s.parent),d=e.episodes.filter(u=>u.episode_id===a.episodeId);d.length===0&&se("AUTHORING_SELECTOR_NOT_FOUND","Action span parent episode was not found.",[a.episodeId],"Use an existing episode ID."),d.length>1&&se("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&&se("AUTHORING_SELECTOR_NOT_FOUND","Action span parent scene was not found.",[s.parent],"Use an existing scene address."),l.length>1&&se("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&&se("AUTHORING_SELECTOR_REVERSED","Action span is reversed.",[r.from,r.through],"Put the lower current action index first."),c.index>=f.actions.length&&se("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 h=`${s.parent}#${u}`;o.has(h)&&se("AUTHORING_SELECTOR_OVERLAP","Action span regions overlap.",[h],"Use non-overlapping regions."),o.add(h)}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:Ht}),i.push([e.episodes.indexOf(p),p.scenes.indexOf(f),s.index])}return yr(i,"Action span"),Ei("action-span",n)}function lu(e,t){let n=v(t.output).trim();n||se("AUTHORING_OUTPUT_REQUIRED","Export requires --output.",["<missing>"],"Pass a destination .scriptctl file.",G);let o=zw(t),i=v(t.in).trim(),r=du.resolve(n);if(o.version===4){let p=su(mn(o),e,i);return ws(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}},J]}let s=Nt(o),c;e==="script"?c=Xl(s):e==="episodes"?c=Hw(s,i):e==="episode-spans"?c=Qw(s,i):e==="scenes"?c=Yw(s,i):e==="scene-spans"?c=qw(s,i):c=Zw(s,i);let a=tu(c);return ws(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}},J]}import*as Zc from"node:crypto";import*as Er from"node:fs";import*as $u from"node:path";function Q(e,t,n,o,i=k){throw new E(t,{exitCode:i,errorCode:e,hint:o[0],data:{actual:n}})}function ae(e){return`line ${e.line}, column ${e.column}`}function Os(e){if(Array.isArray(e))return e.map(Os);if(e!==null&&typeof e=="object"){let t={};for(let[n,o]of Object.entries(e).sort(([i],[r])=>i.localeCompare(r)))t[n]=Os(o);return t}return e}function ao(e,t){return JSON.stringify(Os(e))===JSON.stringify(Os(t))}function wr(e,t){return"actor_id"in t?t.actor_id:"location_id"in t?t.location_id:t.prop_id}function Ww(e,t){return"actor_name"in t?t.actor_name:"location_name"in t?t.location_name:t.prop_name}function Xw(e,t){return t==="actor"?e.actors:t==="location"?e.locations:e.props}function ex(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 wu(e,t,n){return Xw(e,t).find(o=>wr(t,o)===n)}function tx(e,t){for(let n of["actor","location","prop"]){let o=wu(e,n,t);if(o!==void 0)return{kind:n,value:o}}}function nx(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.",[ae(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.",[ae(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}:${wr(p,l)}`;c.has(u)&&Q("AUTHORING_DECLARATION_DUPLICATE","Asset declaration is duplicated.",[ae(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&&wr(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=wr(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.",[ae(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.",[ae(a.source),`${a.kind}:${d}`],["Keep exactly one default state."]);let p=a.value.aliases??[];(new Set(p).size!==p.length||p.includes(Ww(a.kind,a.value)))&&Q("AUTHORING_ALIAS_INVALID","Asset aliases must be unique and must differ from the canonical name.",[ae(a.source),`${a.kind}:${d}`],["Remove duplicate aliases and the canonical name from aliases."])}return{assets:t,states:n}}function ox(){return{createdAssets:[],existingAssets:[],createdStates:[],existingStates:[]}}function xu(e,t){let n=nx(t),o=ox();for(let i of n.assets){let r=wr(i.kind,i.value),s=`${i.kind}:${r}`,c=tx(e,r);if(c!==void 0){if(c.kind===i.kind&&ao(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.",[ae(i.source),`${i.kind}:${r}`],["Use the existing identical definition or change it with an explicit mutation verb."])}ex(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=wu(e,i.kind,i.ownerId);r===void 0&&Q("AUTHORING_STATE_OWNER_NOT_FOUND","Standalone state owner does not exist.",[ae(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&&!ao(s,i.value)&&Q("AUTHORING_STATE_CONFLICT","Create-only state declaration conflicts with an existing state on the same asset.",[ae(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 uu(e){return{episodes:0,scenes:e===void 0?0:1,actions:e?.actions.length??0}}function fu(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 vs(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 mu(e){return{episodes:0,scenes:e.length,actions:e.reduce((t,n)=>t+n.actions.length,0)}}function xr(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 Uc(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.",[ae(t),...n],["Add the concrete state ID to every location, cast, and prop record."])}function Cc(e,t){for(let n of e.scenes)Uc(n,t)}function Go(e,t){return e.episodes.findIndex(n=>n.episode_id===t)}function Rs(e,t){return e.scenes.findIndex(n=>n.scene_id===t)}function _u(e,t,n){let o=Go(e,t);o<0&&Q("AUTHORING_EPISODE_NOT_FOUND","Episode target does not exist.",[t],["Inspect episodes and use an existing parent."]);let i=Rs(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 ix(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)ix(e[n-1].coord,e[n].coord)>=0&&Q("AUTHORING_TARGET_ORDER",t,[ae(e[n].source)],["List replace targets in current document order without duplicates."],G)}function rx(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>{let c=Go(e,s.value.episode_id);return c<0&&Q("AUTHORING_EPISODE_NOT_FOUND","Episode replace target does not exist.",[ae(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){Cc(r.value,r.source);let s=Go(e,r.value.episode_id),c=s<0?void 0:e.episodes[s];o==="create"?c!==void 0?ao(c,r.value)||Q("AUTHORING_CREATE_CONFLICT","Episode create target already exists with different content.",[ae(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:fu(c),after:fu(r.value),...xr(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 sx(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>({coord:_u(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){Uc(r.value,r.source);let s=Go(e,r.parent);s<0&&Q("AUTHORING_EPISODE_NOT_FOUND","Scene parent episode does not exist.",[ae(r.source),r.parent],["Use an existing episode parent."]);let c=e.episodes[s],a=t.episodes[s],d=Rs(c,r.value.scene_id),p=d<0?void 0:c.scenes[d];o==="create"?p!==void 0?ao(p,r.value)||Q("AUTHORING_CREATE_CONFLICT","Scene create target already exists with different content.",[ae(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.",[ae(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:uu(p),after:uu(r.value),...xr(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 ax(e,t,n){let o=n.map(r=>{let s=Go(e,r.from),c=Go(e,r.through);(s<0||c<0)&&Q("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Episode-span endpoint does not exist.",[ae(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.",[ae(r.source),`${r.from}..${r.through}`],["Swap from and through."]),r.episodes.length===0&&Q("AUTHORING_EMPTY_SPAN","Episode-span replacement cannot be empty.",[ae(r.source)],["Include at least one complete episode."]);for(let a of r.episodes)Cc(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.",[ae(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:vs(a),after:vs(r.episodes),...xr(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 cx(e,t,n){let o=n.map(s=>{let c=Go(e,s.parent);c<0&&Q("AUTHORING_EPISODE_NOT_FOUND","Scene-span parent does not exist.",[ae(s.source),s.parent],["Use an existing parent episode."]);let a=e.episodes[c],d=Rs(a,s.from),p=Rs(a,s.through);(d<0||p<0)&&Q("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Scene-span endpoint does not exist in its parent.",[ae(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.",[ae(s.source),`${s.from}..${s.through}`],["Swap from and through."]),s.scenes.length===0&&Q("AUTHORING_EMPTY_SPAN","Scene-span replacement cannot be empty.",[ae(s.source)],["Include at least one complete scene."]);for(let l of s.scenes)Uc(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.",[ae(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:mu(p),after:mu(s.scenes),...xr(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 dx(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.",[ae(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]=_u(e,a,d),f=e.episodes[p].scenes[l];return s.from>s.through&&Q("AUTHORING_SPAN_REVERSED","Action-span endpoints are reversed.",[ae(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.",[ae(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.",[ae(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.",[ae(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 Eu(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 px(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${px(e.path,t)}\0${e.message}`}function lx(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 ux(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 hu(e,t,n){let o=yt(t),i=lx(n),r=()=>({...o,warnings:[...o.warnings,...ux(e,t,i)]});if(o.ok||e!==null&&ao(e,t))return r();let s=new Set(e===null?[]:yt(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&&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 yu(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 fx(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."],G);for(let i of t.episodes)Cc(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=xu(n,e.declarations);return Eu(n),{script:n,declarations:o}}function Su(e,t,n){if(t.targetKind==="script"){n!=="create"&&Q("AUTHORING_TARGET_MODE","Script targets support create only.",[n],["Use --create."],G);let a=fx(t),d=a.script;e!==null&&!ao(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=hu(e,d,t.targets);return{script:d,changed:e===null||!ao(e,d),declarations:p,targets:[{kind:"script",address:"global",before:e===null?{episodes:0,scenes:0,actions:0}:vs(e.episodes),after:vs(d.episodes),...xr(e?.episodes.map(f=>f.episode_id)??[],d.episodes.map(f=>f.episode_id)),untouchedSiblings:0}],retainedOrphanAssets:yu(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."],G);let o=structuredClone(e),i=structuredClone(e),r=xu(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."],G),s=rx(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."],G),s=sx(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."],G),s=ax(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."],G),s=cx(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."],G),s=dx(o,i,a);break}default:Q("AUTHORING_TARGET_MODE","Unsupported authoring target.",[t.targetKind],["Use a supported homogeneous target kind."])}Eu(i);let c=hu(e,i,t.targets);return{script:i,changed:!ao(e,i),declarations:r,targets:s,retainedOrphanAssets:yu(i),validation:c}}function $(e,t,n,o){return new E(e,{exitCode:k,errorCode:"AUTHORING_SOURCE_INVALID",hint:o,data:{actual:[`line ${t.line}, column ${t.column}: ${n}`]}})}function Pc(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 Ii(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 h=1;h<o.length;h+=1){let m=o[h];if(r){r=!1;continue}if(m==="\\"){r=!0;continue}if(m==="]"){i=h;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 h=0;h<s.length;h+=1){let m=s[h];r?(a+=`\\${m}`,r=!1):m==="\\"?r=!0:m==="|"?(c.push(a),a=""):a+=m}r&&(a+="\\"),c.push(a);let[d,...p]=c,l=Pc(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(h=>Pc(h,n,!0)),content:Pc(u,{line:t,column:i+2},!1),source:n}}function xt(){return{extend:{},extendPresent:!1,aliases:[],aliasesPresent:!1,phase:"extend"}}function $n(e){return e.extendPresent||e.aliasesPresent||e.prompt!==void 0}function _t(e){return e.extendPresent?e.extend:void 0}function Tc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Tc):typeof e!="object"?!1:Object.values(e).every(Tc)}function Vc(e){if(Array.isArray(e))return e.map(Vc);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=Vc(e[n]);return t}return e}function Iu(e){return e==="featured"||e==="background"}function mx(e){return e==="\u4E3B\u89D2"||e==="\u914D\u89D2"}function gx(e){return e==="system"||e==="broadcast"||e==="offscreen"||e==="group"}function hx(e){return e==="actor"||e==="location"||e==="prop"}function Au(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 yx(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 yn(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 wx(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(!Po.has(r)||!gx(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 xx(e,t){let o={act:"action",dlg:"dialogue",think:"inner_thought",trans:"transition"}[e.type];if(o===void 0||!zt.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=wx(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=_t(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 $c=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(cn(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=ft();for(;;){if(this.skipBlank(),this.peekClose("authoring")){On(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.");On(r)&&this.throwUnsupportedModifiers(r,"create"),n.push(...this.parseCreate()),i=!0;continue}i=!0,o.push(this.parseTarget(r)),r=ft()}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");cn(t,[]);let n=[],o=ft();for(;;){if(this.skipBlank(),this.peekClose("create"))return On(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||!It.has(c)||!Xl(c))throw $("Actor declaration is invalid.",i.source,i.slots.join("|"),"Provide id, name, and featured|background importance.");if(a!==void 0&&(!Gn.has(a)||!Tw(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=mt(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=ft();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||!It.has(c)||!Xl(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=mt(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=ft();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||!$w(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=mt(o);l!==void 0&&(p.extend=l),n.push({declarationKind:"state",ownerKind:d,ownerId:a[2],value:p,source:i.source}),o=ft();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,...mt(t)?{extend:mt(t)}:{}};case"episode-span":return this.parseEpisodeSpan(t);case"scene":return cn(n,["id","parent"]),{kind:"scene",parent:n.attrs.get("parent"),value:this.parseScene(t,!0),source:n.source,...mt(t)?{extend:mt(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");cn(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=ft();for(;;){if(this.skipBlank(),this.peekClose("script")){On(d)&&this.throwDangling(d),this.takeClose("script");break}let g=this.peekSemantic();if(g?.record!==void 0){let m=this.takeRecord();if(m.type==="extensions"||m.type==="extend"||m.type==="aliases"||m.type==="alias"||m.type==="prompt"){d=this.addModifier(d,m);continue}On(d)&&this.throwUnsupportedModifiers(d,m.type);let h=o.indexOf(m.type),w=m.type==="main-character";if(a||h<0||h<c||!w&&i.has(m.type))throw $("Metadata record in <script> is invalid or out of order.",m.source,m.type,`Use ${o.join(", ")} in canonical order before episode blocks.`);if(c=h,m.type==="main-characters"){if(m.slots.length!==0||m.content!=="")throw $("Main characters marker is invalid.",m.source,m.content,"Use [main-characters] with no slots or content.");i.set(m.type,"")}else if(w){if(m.slots.length!==2||!m.slots[0]||!m.slots[1]||m.content!=="")throw $("Main character record is invalid.",m.source,m.slots.join("|"),"Use [main-character|name|role] with no content.");r.push({name:m.slots[0],role:m.slots[1]})}else{if(m.slots.length!==0)throw $("Script metadata record has unexpected slots.",m.source,m.slots.join("|"),`Use [${m.type}] content.`);i.set(m.type,m.content)}continue}if(g?.tag===void 0||g.tag.closing||g.tag.name!=="episode"){let m=g?.tag?.source??{line:this.index+1,column:1};throw $("Unexpected member in <script>.",m,this.lines[this.index]??"<eof>","Use metadata records followed by <episode> blocks.")}a=!0,s.push(this.parseEpisode(d)),d=ft()}let p=this.requiredMetadata(i,"title",n.source),l=this.requiredMetadata(i,"worldview",n.source),f=this.requiredMetadata(i,"style",n.source),u=mt(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");cn(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=mt(t);return r!==void 0&&(i.extend=r),i}parseScene(t,n){let o=this.takeOpen("scene");cn(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 g=f?.tag?.source??{line:this.index+1,column:1};throw $("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 $("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 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 $("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=mt(t);return l!==void 0&&(p.extend=l),p}parseBody(){let t=this.takeOpen("body");cn(t,[]);let n=[],o=ft();for(;;){if(this.skipBlank(),this.peekClose("body"))return On(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(Jw(i,o)),o=ft()}}parseEpisodeSpan(t){let n=this.takeOpen("episode-span");cn(n,["from","through"]);let o=this.parseOnlyChildren("episode-span","episode",r=>this.parseEpisode(r)),i=mt(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");cn(n,["parent","from","through"]);let o=this.parseOnlyChildren("scene-span","scene",r=>this.parseScene(r,!1)),i=mt(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");cn(n,["parent","from","through"]),this.skipBlank();let o=this.parseBody();this.skipBlank(),this.takeClose("action-span");let i=mt(t);return{kind:"action-span",parent:n.attrs.get("parent"),from:eu(n.attrs.get("from"),n.source,"action-span from",!0),through:eu(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=ft();for(;;){if(this.skipBlank(),this.peekClose(t))return On(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}On(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=ft()}}parseOnlyChildren(t,n,o){let i=[],r=ft();for(;;){if(this.skipBlank(),this.peekClose(t))return On(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=ft()}}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(!yc(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]=wc(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=Dw(t,this.index+1);if(n!==null)return{tag:n};if(t.trimStart().startsWith("["))return{record:di(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 tu(e){return new Ec(e).parse()}function M(e,t,n){throw new x(e,{exitCode:b,errorCode:"AUTHORING_SOURCE_INVALID",data:{actual:[`line ${t}: ${n}`]}})}function Ic(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==="")&&M("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]))&&M("Tag attributes are invalid.",t,a),r.set(d[1],d[2])}return{name:i[1],closing:!1,attrs:r,line:t}}function Te(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)&&M("Tag attributes do not match the canonical grammar.",e.line,[...r.map(s=>`missing:${s}`),...i.map(s=>`unknown:${s}`)].join(","))}var Ac=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||M("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=Ic(o.raw,o.line);return(!i||i.name!==t||i.closing!==n)&&M(`Expected ${n?"</":"<"}${t}>.`,o.line,o.raw),i}record(){let t=this.take();return di(t.raw,t.line)}nextTag(){let t=this.peek();return Ic(t.raw,t.line)}nextRecord(){let t=this.peek();return t.raw.startsWith("[")?di(t.raw,t.line):null}};function kc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(kc):typeof e=="object"&&Object.values(e).every(kc)}function vo(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]))&&M("extend record is invalid or duplicated.",r.source.line,r.type);let s=r.slots[0];i!==null&&i>=s&&M("extend keys must use ascending canonical order.",r.source.line,s);let c;try{c=JSON.parse(r.content)}catch{M("extend content must be JSON.",r.source.line,r.content)}kc(c)||M("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&&M("alias takes no slots.",i.source.line,i.type),i.content===""&&M("alias must not be empty.",i.source.line,i.type),o.includes(i.content)&&M("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===""))&&M("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)&&M("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 _c(e,t){return e!=="featured"&&e!=="background"&&M("Importance is invalid.",t,e),e}function Bw(e,t){if(e!==void 0)return e!=="\u4E3B\u89D2"&&e!=="\u914D\u89D2"&&M("Role type is invalid.",t,e),e}function vc(e,t){return e==="default"||V("state",e)?e:M("State ID is invalid.",t,e)}function Kw(e){let t=e.tag("create",!1);Te(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")&&M("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=vo(e),d=e.record();if(d.type==="actor"){r>0&&M("Create declarations are not in canonical order.",d.source.line,d.type),s(d.source.line),a.prompt!==void 0&&M("prompt cannot modify an asset.",d.source.line,d.type),(d.slots.length<3||d.slots.length>4||!V("actor",d.slots[0]))&&M("actor declaration is invalid.",d.source.line,d.type);let p=Bw(d.slots[3],d.source.line),l={actor_id:d.slots[0],actor_name:d.slots[1],importance:_c(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)&&M("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&&M("Create declarations are not in canonical order.",d.source.line,d.type),r=p,s(d.source.line),a.prompt!==void 0&&M("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])))&&M(`${l} declaration is invalid.`,d.source.line,d.type),l==="location"){let f=d.slots[0];V("location",f)||M("location ID is invalid.",d.source.line,f);let u={location_id:f,location_name:d.slots[1],importance:_c(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)&&M("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)||M("prop ID is invalid.",d.source.line,f);let u={prop_id:f,prop_name:d.slots[1],importance:_c(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)&&M("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)&&M("state declaration is invalid.",d.source.line,d.type);let p=d.slots[0],l=o.get(p);l&&i!==p&&M("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:vc(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"&&M("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),M("Unknown create declaration.",d.source.line,d.type)}s(e.peek().line);let c=e.tag("create",!0);return Te(c,[]),n}function jw(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:vc(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)}:M("Speaker is invalid.",t,e)}function nu(e){let t=vo(e);t.aliases!==void 0&&M("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]))&&M("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"?M("Unknown Action record.",n.source.line,n.type):((n.slots.length!==2&&n.slots.length!==3||!V("action",n.slots[0]))&&M("Speaking Action record is invalid.",n.source.line,n.type),{action_id:n.slots[0],type:n.type==="dlg"?"dialogue":"inner_thought",speaker:jw(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 xc(e,t){e.length===0&&M("Scene reference needs at least one state.",t,"<empty>");let n=e.map(o=>vc(o,t));return new Set(n).size!==n.length&&M("Scene reference repeats a state.",t,n.join(",")),n.sort()}function bc(e,t,n,o){Te(t,n===void 0?["id","parent"]:["id"]);let i=t.attrs.get("id")??"";V("scene",i)||M("Scene ID is invalid.",t.line,i);let r=t.attrs.get("parent")??n;r!==void 0&&!V("episode",r)&&M("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 m=e.record(),h=m.type==="environment"?0:m.type==="location"?1:m.type==="cast"?2:m.type==="prop"?3:-1;h<f&&M("Scene records are not in canonical order.",m.source.line,m.type),f=h,m.type==="environment"?(s!==void 0&&M("Scene environment is duplicated.",m.source.line,m.type),m.slots.length>2&&M("environment has too many slots.",m.source.line,m.type),s={...m.slots[0]===void 0?{}:{space:m.slots[0]},...m.slots[1]===void 0?{}:{time:m.slots[1]}}):m.type==="location"?(c!==void 0&&M("Scene location is duplicated.",m.source.line,m.type),m.slots.length===0?c=null:(V("location",m.slots[0])||M("Location ref ID is invalid.",m.source.line,m.slots[0]),c={location_id:m.slots[0],state_ids:xc(m.slots.slice(1),m.source.line)})):m.type==="cast"?(V("actor",m.slots[0])||M("Cast ref ID is invalid.",m.source.line,m.slots[0]??""),p.has(m.slots[0])&&M("Scene repeats an actor reference.",m.source.line,m.slots[0]),p.add(m.slots[0]),a.push({actor_id:m.slots[0],state_ids:xc(m.slots.slice(1),m.source.line)})):m.type==="prop"?(V("prop",m.slots[0])||M("Prop ref ID is invalid.",m.source.line,m.slots[0]??""),l.has(m.slots[0])&&M("Scene repeats a prop reference.",m.source.line,m.slots[0]),l.add(m.slots[0]),d.push({prop_id:m.slots[0],state_ids:xc(m.slots.slice(1),m.source.line)})):M("Unknown scene header record.",m.source.line,m.type)}c===void 0&&M("Scene must declare location or [location].",e.peek().line,i);let u=e.tag("body",!1);Te(u,[]);let g=[];for(;e.nextTag()?.name!=="body"||e.nextTag()?.closing!==!0;)g.push(nu(e));return Te(e.tag("body",!0),[]),Te(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 Oc(e,t,n){Te(t,["id"]);let o=t.attrs.get("id")??"";V("episode",o)||M("Episode ID is invalid.",t.line,o);let i,r,s=[],c=0;for(;e.nextTag()?.name!=="episode"||e.nextTag()?.closing!==!0;){let a=vo(e);(a.aliases!==void 0||a.prompt!==void 0)&&M("Invalid episode child modifier.",e.peek().line,"modifier");let d=e.nextTag();if(d?.name==="scene"&&!d.closing){c=2,e.take(),s.push(bc(e,d,o,a.extend).value);continue}a.extend!==void 0&&M("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&&M("Episode records are not in canonical order.",p.source.line,p.type),c=l,p.type==="title"?(i!==void 0&&M("Episode title is duplicated.",p.source.line,p.type),p.slots.length!==0&&M("Episode title takes no slots.",p.source.line,p.type),i=p.content):p.type==="synopsis"?(r!==void 0&&M("Episode synopsis is duplicated.",p.source.line,p.type),p.slots.length!==0&&M("Episode synopsis takes no slots.",p.source.line,p.type),r=p.content):M("Unknown episode record.",p.source.line,p.type)}return Te(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 Sc(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]))&&M(`Span range must contain two ${t} IDs.`,e.line,n),[o[0],o[1]]}function zw(e,t,n){Te(t,[]);let o,i,r,s,c,a,d,p,l=[],f=0;for(;e.nextTag()?.name!=="script"||e.nextTag()?.closing!==!0;){let u=vo(e);(u.aliases!==void 0||u.prompt!==void 0)&&M("Invalid script child modifier.",e.peek().line,"modifier");let g=e.nextTag();if(g?.name==="episode"&&!g.closing){f=8,e.take(),l.push(Oc(e,g,u.extend));continue}u.extend!==void 0&&M("extend must precede an episode here.",e.peek().line,"extend");let m=e.record(),h=m.type==="title"?0:m.type==="worldview"?1:m.type==="worldview-raw"?2:m.type==="style"?3:m.type==="synopsis"?4:m.type==="logline"?5:m.type==="theme"?6:m.type==="main-characters"||m.type==="main-character"?7:-1;h<f&&M("Script records are not in canonical order.",m.source.line,m.type),f=h,m.type!=="main-character"&&m.slots.length!==0&&M("Script metadata record takes no slots.",m.source.line,m.type),m.type==="title"?(o!==void 0&&M("Script title is duplicated.",m.source.line,m.type),o=m.content):m.type==="worldview"?(i!==void 0&&M("Script worldview is duplicated.",m.source.line,m.type),i=m.content):m.type==="worldview-raw"?(r!==void 0&&M("Script worldview-raw is duplicated.",m.source.line,m.type),r=m.content):m.type==="style"?(s!==void 0&&M("Script style is duplicated.",m.source.line,m.type),s=m.content):m.type==="synopsis"?(c!==void 0&&M("Script synopsis is duplicated.",m.source.line,m.type),c=m.content):m.type==="logline"?(a!==void 0&&M("Script logline is duplicated.",m.source.line,m.type),a=m.content):m.type==="theme"?(d!==void 0&&M("Script theme is duplicated.",m.source.line,m.type),d=m.content):m.type==="main-characters"?(p!==void 0&&M("Script main-characters is duplicated.",m.source.line,m.type),p=[]):m.type==="main-character"&&p!==void 0&&m.slots.length===2&&m.content===""?p.push({name:m.slots[0],role:m.slots[1]}):M("Unknown script record.",m.source.line,m.type)}return Te(e.tag("script",!0),[]),(o===void 0||i===void 0||s===void 0)&&M("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 ou(e){let t=new Ac(e),n=t.tag("authoring",!1);Te(n,["version"]),n.attrs.get("version")!=="1"&&M("authoring version must be 1.",1,n.attrs.get("version")??"<missing>");let o=t.nextTag()?.name==="create"?Kw(t):[],i=[];for(;t.nextTag()?.name!=="authoring"||t.nextTag()?.closing!==!0;){let s=vo(t);(s.aliases!==void 0||s.prompt!==void 0)&&M("Invalid target modifier.",t.peek().line,"modifier");let c=t.take(),a=Ic(c.raw,c.line);if((!a||a.closing)&&M("Expected an authoring target.",c.line,c.raw),a.name==="script")i.push(zw(t,a,s.extend));else if(a.name==="episode")i.push({kind:"episode",value:Oc(t,a,s.extend)});else if(a.name==="scene"){let d=bc(t,a,void 0,s.extend);d.parent||M("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&&M("A span cannot carry node extensions.",c.line,c.raw),Te(a,["range"]);let[d,p]=Sc(a,"episode"),l=[];for(;t.nextTag()?.name!=="episode-span"||t.nextTag()?.closing!==!0;){let f=vo(t);(f.aliases!==void 0||f.prompt!==void 0)&&M("Invalid episode child modifier.",t.peek().line,"modifier");let u=t.tag("episode",!1);l.push(Oc(t,u,f.extend))}Te(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&&M("A span cannot carry node extensions.",c.line,c.raw),Te(a,["parent","range"]);let[d,p]=Sc(a,"scene"),l=a.attrs.get("parent")??M("scene-span needs parent.",c.line,c.raw);V("episode",l)||M("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=vo(t);(u.aliases!==void 0||u.prompt!==void 0)&&M("Invalid scene child modifier.",t.peek().line,"modifier");let g=t.tag("scene",!1);f.push(bc(t,g,l,u.extend).value)}Te(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&&M("A span cannot carry node extensions.",c.line,c.raw),Te(a,["parent","range"]);let[d,p]=Sc(a,"action"),l=a.attrs.get("parent")??M("action-span needs parent.",c.line,c.raw);V("scene",l)||M("action-span parent must be a Scene ID.",c.line,l),Te(t.tag("body",!1),[]);let f=[];for(;t.nextTag()?.name!=="body"||t.nextTag()?.closing!==!0;)f.push(nu(t));Te(t.tag("body",!0),[]),Te(t.tag("action-span",!0),[]),i.push({kind:"action-span",parent:l,from:d,through:p,values:f})}else M("Unknown authoring target.",c.line,a.name)}Te(t.tag("authoring",!0),[]),(t.index!==t.lines.length||i.length===0)&&M("Authoring file has trailing content or no targets.",t.peek().line,"<root>");let r=i[0].kind;return i.every(s=>s.kind===r)||M("All targets must have the same kind.",1,r),{declarations:o,targets:i,targetKind:r}}function dn(e){if(Array.isArray(e))return e.map(t=>dn(t));if(ee(e)){let t={};for(let n of Object.keys(e).sort())t[n]=dn(e[n]);return t}return e}function Rc(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 iu(e,t){if(!(t.ok||e!==null&&Ja(Me(e),t)))throw new x("The proposed document is not a valid or strictly improved Script v4.",{exitCode:b,errorCode:"AUTHORING_VALIDATION_FAILED",data:{actual:t.errors.slice(0,20).map(n=>`${n.path}: ${n.message}`)}})}function Le(e,t){throw new x(e,{exitCode:b,errorCode:"AUTHORING_APPLY_INVALID",data:{actual:t}})}function Lc(e){return{ids:e.map(t=>t.action_id),counts:{episodes:0,scenes:0,actions:e.length}}}function pi(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 Yn(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 Hw(e){return e.kind==="script"?Yn(e.value.episodes):e.kind==="episode"?Yn([e.value]):e.kind==="episode-span"?Yn(e.values):e.kind==="scene"?pi([e.value]):e.kind==="scene-span"?pi(e.values):Lc(e.values)}function Qw(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 Mc(e,t){return JSON.stringify(dn(e))===JSON.stringify(dn(t))}function ru(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 su(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 au(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 cu(e,t){let n=e===null?[]:au(e),o=au(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 Fw(e,t){for(let n of t)if(n.kind==="actor")e.actors.some(o=>o.actor_id===n.value.actor_id)&&Le("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)&&Le("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)&&Le("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||Le("State declaration owner was not found.",[n.ownerId]),o.states.some(i=>i.state_id===n.value.state_id)&&Le("State declaration cannot redefine an existing state.",[`${n.ownerId}/${n.value.state_id}`]),o.states.push(structuredClone(n.value))}}function Dt(e,t,n){let o=e.indexOf(t),i=e.indexOf(n);return(o<0||i<0)&&Le("Span endpoint was not found.",[t,n]),[Math.min(o,i),Math.max(o,i)]}function Yw(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"?Dt(o,t.value.episode_id,t.value.episode_id):Dt(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"?Dt(o,t.value.scene_id,t.value.scene_id):Dt(o,t.from,t.through)}let n=e.episodes.flatMap(o=>o.scenes.flatMap(i=>i.actions.map(r=>r.action_id)));return Dt(n,t.from,t.through)}function qw(e,t){let n=-1;for(let o of t){let[i,r]=Yw(e,o);i<=n&&Le("Replace targets must follow current document order without overlap.",[uu(o)]),n=r}}function uu(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 du(e,t){if(t.kind==="script")return{...Yn(e.episodes),siblings:0};if(t.kind==="episode"){let r=sn(e,t.value.episode_id);return{...Yn(r?[r.episode]:[]),siblings:Math.max(0,e.episodes.length-(r?1:0))}}if(t.kind==="episode-span"){let[r,s]=Dt(e.episodes.map(c=>c.episode_id),t.from,t.through);return{...Yn(e.episodes.slice(r,s+1)),siblings:e.episodes.length-(s-r+1)}}if(t.kind==="scene"){let r=bn(e,t.value.scene_id),s=sn(e,t.parent)?.episode;return{...pi(r?[r.scene]:[]),siblings:r?Math.max(0,r.episode.scenes.length-1):s?.scenes.length??0}}if(t.kind==="scene-span"){let r=sn(e,t.parent)?.episode;if(!r)return{...pi([]),siblings:0};let[s,c]=Dt(r.scenes.map(a=>a.scene_id),t.from,t.through);return{...pi(r.scenes.slice(s,c+1)),siblings:r.scenes.length-(c-s+1)}}let n=bn(e,t.parent)?.scene;if(!n)return{...Lc([]),siblings:0};let[o,i]=Dt(n.actions.map(r=>r.action_id),t.from,t.through);return{...Lc(n.actions.slice(o,i+1)),siblings:n.actions.length-(i-o+1)}}function pu(e,t){let n=Hw(e),o=new Set(t.ids),i=new Set(n.ids);return{kind:e.kind,address:uu(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 Zw(e,t){if(t.kind==="script"&&Le("An existing Script v4 is not replaced through a script root.",["script"]),t.kind==="episode"){let n=sn(e,t.value.episode_id);n||Le("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]=Dt(e.episodes.map(i=>i.episode_id),t.from,t.through);t.values.length===0&&Le("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=bn(e,t.value.scene_id);(!n||n.episode.episode_id!==t.parent)&&Le("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=sn(e,t.parent)?.episode;n||Le("Scene span parent was not found.",[t.parent]);let[o,i]=Dt(n.scenes.map(r=>r.scene_id),t.from,t.through);t.values.length===0&&Le("Scene span replacement cannot be empty.",[t.from,t.through]),n.scenes.splice(o,i-o+1,...structuredClone(t.values))}else{let n=bn(e,t.parent)?.scene;n||Le("Action span parent was not found.",[t.parent]);let[o,i]=Dt(n.actions.map(r=>r.action_id),t.from,t.through);t.values.length===0&&Le("Action span replacement cannot be empty.",[t.from,t.through]),n.actions.splice(o,i-o+1,...structuredClone(t.values))}}function Ww(e,t){if(t.kind==="episode")e.episodes.push(structuredClone(t.value));else if(t.kind==="scene"){let n=sn(e,t.parent)?.episode;n||Le("Scene create parent was not found.",[t.parent]),n.scenes.push(structuredClone(t.value))}else Le("This target kind does not support create against an existing script.",[t.kind])}function lu(e){if(e.targets.length!==1||e.targets[0].kind!=="script")return Le("Script create requires exactly one script target.",[e.targetKind]);if(e.declarations.some(n=>n.kind==="state"))return Le("Standalone state declarations need an existing owner.",["state"]);let t=e.targets[0];return{version:4,...structuredClone(t.value),...Qw(e.declarations)}}function fu(e,t,n){let o;if(e===null)n!=="create"&&Le("A missing target requires one script create target.",[n,t.targetKind]),o=lu(t);else if(n==="create"&&t.targetKind==="script")o=lu(t),Mc(o,e)||Le("Script create retry differs from the existing script.",["script"]);else{o=structuredClone(e),n==="replace"&&qw(e,t.targets),Fw(o,t.declarations);let r=t.targets.map(a=>du(e,a));if(n==="replace")for(let a of[...t.targets].reverse())Zw(o,a);else for(let a of t.targets)Ww(o,a);let s=t.targets.map((a,d)=>pu(a,r[d])),c=Me(o);return iu(e,c),{script:o,changed:!Mc(e,o),validation:c,targets:s,declarations:ru(e,t.declarations),retainedOrphanAssets:su(o),identity:cu(e,o)}}let i=Me(o);return iu(e,i),{script:o,changed:e===null||!Mc(e,o),validation:i,declarations:ru(e,t.declarations),retainedOrphanAssets:su(o),identity:cu(e,o),targets:t.targets.map(r=>{let s=e===null?{...Yn([]),siblings:0}:du(e,r);return pu(r,s)})}}function Ro(e,t){throw new x(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 Xw(e){(!e||e==="-")&&Ro("Authoring input must be a named file.",[e||"<missing>"]);let t=mu.resolve(e),n;try{n=cr.statSync(t)}catch{throw new x("The authoring source file does not exist.",{exitCode:b,errorCode:"AUTHORING_SOURCE_UNAVAILABLE",hint:"Write the complete authoring draft to a file, then rerun the command.",data:{actual:[t]}})}n.isFile()||Ro("Authoring input must be a regular file.",[t]);let o=cr.readFileSync(t);return{absolutePath:t,bytes:o,text:o.toString("utf-8")}}function eE(e){let t=Wi(e);if(t===null)return{script:null,baseline:"missing",fingerprint:t};let n;try{n=JSON.parse(cr.readFileSync(e,"utf-8"))}catch(i){throw new x("The local script is not valid JSON.",{exitCode:b,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=as(n);return{script:o,baseline:$e(o),fingerprint:t}}function tE(e){let t=e.create===!0,n=e.replace===!0;return t===n&&Ro("Choose exactly one authoring mode.",[`create=${t}`,`replace=${n}`]),t?"create":"replace"}function gu(e){return`sha256:${Ie(JSON.stringify(e))}`}function nE(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 oE(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 iE(e,t,n,o,i){let r=ou(t.text),s=i.script===null?null:rn(i.script),c=fu(s,r,n),a=`sha256:${Nc.createHash("sha256").update(t.bytes).digest("hex")}`,d={version:1,sourceDigest:a,mode:n,targetKind:r.targetKind,targets:c.targets.map(h=>h.address),baseline:i.baseline,plan:{targets:c.targets,declarations:c.declarations,retainedOrphanAssets:c.retainedOrphanAssets,identity:c.identity,validation:c.validation}},p=gu(d),l=e.apply===!0,f=v(e.plan).trim();if(l&&!f&&Ro("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!l&&f&&Ro("--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:b,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?Xi(o,i.fingerprint):Rt(o,i.baseline),je(o,c.script));let u=c.targets.map((h,w)=>`target[${w}]=${h.address} kind=${h.kind} before=${JSON.stringify(h.before)} after=${JSON.stringify(h.after)} retained=${JSON.stringify(h.retainedIds)} created=${JSON.stringify(h.createdIds)} removed=${JSON.stringify(h.removedIds)} untouched_siblings=${h.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 hu(e){let t=Array.isArray(e._args)?e._args:[],n=typeof t[0]=="string"?t[0]:"",o=Xw(n),i=tE(e),r=Se(e),s=eE(r);if(s.script===null||s.script.version===4)return iE(e,o,i,r,s);let c=tu(o.text),a=Wl(bt(s.script),c,i),d=`sha256:${Nc.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=gu(p),f=e.apply===!0,u=v(e.plan).trim();if(f&&!u&&Ro("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!f&&u&&Ro("--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:b,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?Xi(r,s.fingerprint):Rt(r,s.baseline),je(r,a.script));let g=nE(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}`,...oE(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 wu(e){return Array.isArray(e.rows)}function rE(e){return e.endsWith(`
131
+ `)}parse(){this.skipBlank();let t=this.takeOpen("authoring");if(yn(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=xt();for(;;){if(this.skipBlank(),this.peekClose("authoring")){$n(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.");$n(r)&&this.throwUnsupportedModifiers(r,"create"),n.push(...this.parseCreate()),i=!0;continue}i=!0,o.push(this.parseTarget(r)),r=xt()}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");yn(t,[]);let n=[],o=xt();for(;;){if(this.skipBlank(),this.peekClose("create"))return $n(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||!Mt.has(c)||!Iu(c))throw $("Actor declaration is invalid.",i.source,i.slots.join("|"),"Provide id, name, and featured|background importance.");if(a!==void 0&&(!Xn.has(a)||!mx(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=_t(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=xt();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||!Mt.has(c)||!Iu(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=_t(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=xt();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||!hx(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=_t(o);l!==void 0&&(p.extend=l),n.push({declarationKind:"state",ownerKind:d,ownerId:a[2],value:p,source:i.source}),o=xt();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,..._t(t)?{extend:_t(t)}:{}};case"episode-span":return this.parseEpisodeSpan(t);case"scene":return yn(n,["id","parent"]),{kind:"scene",parent:n.attrs.get("parent"),value:this.parseScene(t,!0),source:n.source,..._t(t)?{extend:_t(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");yn(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=xt();for(;;){if(this.skipBlank(),this.peekClose("script")){$n(d)&&this.throwDangling(d),this.takeClose("script");break}let h=this.peekSemantic();if(h?.record!==void 0){let m=this.takeRecord();if(m.type==="extensions"||m.type==="extend"||m.type==="aliases"||m.type==="alias"||m.type==="prompt"){d=this.addModifier(d,m);continue}$n(d)&&this.throwUnsupportedModifiers(d,m.type);let g=o.indexOf(m.type),w=m.type==="main-character";if(a||g<0||g<c||!w&&i.has(m.type))throw $("Metadata record in <script> is invalid or out of order.",m.source,m.type,`Use ${o.join(", ")} in canonical order before episode blocks.`);if(c=g,m.type==="main-characters"){if(m.slots.length!==0||m.content!=="")throw $("Main characters marker is invalid.",m.source,m.content,"Use [main-characters] with no slots or content.");i.set(m.type,"")}else if(w){if(m.slots.length!==2||!m.slots[0]||!m.slots[1]||m.content!=="")throw $("Main character record is invalid.",m.source,m.slots.join("|"),"Use [main-character|name|role] with no content.");r.push({name:m.slots[0],role:m.slots[1]})}else{if(m.slots.length!==0)throw $("Script metadata record has unexpected slots.",m.source,m.slots.join("|"),`Use [${m.type}] content.`);i.set(m.type,m.content)}continue}if(h?.tag===void 0||h.tag.closing||h.tag.name!=="episode"){let m=h?.tag?.source??{line:this.index+1,column:1};throw $("Unexpected member in <script>.",m,this.lines[this.index]??"<eof>","Use metadata records followed by <episode> blocks.")}a=!0,s.push(this.parseEpisode(d)),d=xt()}let p=this.requiredMetadata(i,"title",n.source),l=this.requiredMetadata(i,"worldview",n.source),f=this.requiredMetadata(i,"style",n.source),u=_t(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");yn(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=_t(t);return r!==void 0&&(i.extend=r),i}parseScene(t,n){let o=this.takeOpen("scene");yn(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 h=f?.tag?.source??{line:this.index+1,column:1};throw $("Only scene records and <body> are allowed here.",h,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 h=u.slots[0];h===void 0||h===""?r=null:r=u.slots.length===2?{location_id:h,state_id:u.slots[1]}:{location_id:h};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=_t(t);return l!==void 0&&(p.extend=l),p}parseBody(){let t=this.takeOpen("body");yn(t,[]);let n=[],o=xt();for(;;){if(this.skipBlank(),this.peekClose("body"))return $n(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(xx(i,o)),o=xt()}}parseEpisodeSpan(t){let n=this.takeOpen("episode-span");yn(n,["from","through"]);let o=this.parseOnlyChildren("episode-span","episode",r=>this.parseEpisode(r)),i=_t(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");yn(n,["parent","from","through"]);let o=this.parseOnlyChildren("scene-span","scene",r=>this.parseScene(r,!1)),i=_t(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");yn(n,["parent","from","through"]),this.skipBlank();let o=this.parseBody();this.skipBlank(),this.takeClose("action-span");let i=_t(t);return{kind:"action-span",parent:n.attrs.get("parent"),from:Au(n.attrs.get("from"),n.source,"action-span from",!0),through:Au(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=xt();for(;;){if(this.skipBlank(),this.peekClose(t))return $n(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}$n(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=xt()}}parseOnlyChildren(t,n,o){let i=[],r=xt();for(;;){if(this.skipBlank(),this.peekClose(t))return $n(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=xt()}}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(!Tc(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]=Vc(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=yx(t,this.index+1);if(n!==null)return{tag:n};if(t.trimStart().startsWith("["))return{record:Ii(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 ku(e){return new $c(e).parse()}function M(e,t,n){throw new E(e,{exitCode:k,errorCode:"AUTHORING_SOURCE_INVALID",data:{actual:[`line ${t}: ${n}`]}})}function Bc(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==="")&&M("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]))&&M("Tag attributes are invalid.",t,a),r.set(d[1],d[2])}return{name:i[1],closing:!1,attrs:r,line:t}}function Ve(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)&&M("Tag attributes do not match the canonical grammar.",e.line,[...r.map(s=>`missing:${s}`),...i.map(s=>`unknown:${s}`)].join(","))}var Kc=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||M("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=Bc(o.raw,o.line);return(!i||i.name!==t||i.closing!==n)&&M(`Expected ${n?"</":"<"}${t}>.`,o.line,o.raw),i}record(){let t=this.take();return Ii(t.raw,t.line)}nextTag(){let t=this.peek();return Bc(t.raw,t.line)}nextRecord(){let t=this.peek();return t.raw.startsWith("[")?Ii(t.raw,t.line):null}};function jc(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(jc):typeof e=="object"&&Object.values(e).every(jc)}function Jo(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]))&&M("extend record is invalid or duplicated.",r.source.line,r.type);let s=r.slots[0];i!==null&&i>=s&&M("extend keys must use ascending canonical order.",r.source.line,s);let c;try{c=JSON.parse(r.content)}catch{M("extend content must be JSON.",r.source.line,r.content)}jc(c)||M("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&&M("alias takes no slots.",i.source.line,i.type),i.content===""&&M("alias must not be empty.",i.source.line,i.type),o.includes(i.content)&&M("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===""))&&M("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)&&M("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 Dc(e,t){return e!=="featured"&&e!=="background"&&M("Importance is invalid.",t,e),e}function _x(e,t){if(e!==void 0)return e!=="\u4E3B\u89D2"&&e!=="\u914D\u89D2"&&M("Role type is invalid.",t,e),e}function Qc(e,t){return e==="default"||V("state",e)?e:M("State ID is invalid.",t,e)}function Ex(e){let t=e.tag("create",!1);Ve(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")&&M("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=Jo(e),d=e.record();if(d.type==="actor"){r>0&&M("Create declarations are not in canonical order.",d.source.line,d.type),s(d.source.line),a.prompt!==void 0&&M("prompt cannot modify an asset.",d.source.line,d.type),(d.slots.length<3||d.slots.length>4||!V("actor",d.slots[0]))&&M("actor declaration is invalid.",d.source.line,d.type);let p=_x(d.slots[3],d.source.line),l={actor_id:d.slots[0],actor_name:d.slots[1],importance:Dc(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)&&M("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&&M("Create declarations are not in canonical order.",d.source.line,d.type),r=p,s(d.source.line),a.prompt!==void 0&&M("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])))&&M(`${l} declaration is invalid.`,d.source.line,d.type),l==="location"){let f=d.slots[0];V("location",f)||M("location ID is invalid.",d.source.line,f);let u={location_id:f,location_name:d.slots[1],importance:Dc(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)&&M("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)||M("prop ID is invalid.",d.source.line,f);let u={prop_id:f,prop_name:d.slots[1],importance:Dc(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)&&M("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)&&M("state declaration is invalid.",d.source.line,d.type);let p=d.slots[0],l=o.get(p);l&&i!==p&&M("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:Qc(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"&&M("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),M("Unknown create declaration.",d.source.line,d.type)}s(e.peek().line);let c=e.tag("create",!0);return Ve(c,[]),n}function Sx(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:Qc(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)}:M("Speaker is invalid.",t,e)}function bu(e){let t=Jo(e);t.aliases!==void 0&&M("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]))&&M("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"?M("Unknown Action record.",n.source.line,n.type):((n.slots.length!==2&&n.slots.length!==3||!V("action",n.slots[0]))&&M("Speaking Action record is invalid.",n.source.line,n.type),{action_id:n.slots[0],type:n.type==="dlg"?"dialogue":"inner_thought",speaker:Sx(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 Gc(e,t){e.length===0&&M("Scene reference needs at least one state.",t,"<empty>");let n=e.map(o=>Qc(o,t));return new Set(n).size!==n.length&&M("Scene reference repeats a state.",t,n.join(",")),n.sort()}function zc(e,t,n,o){Ve(t,n===void 0?["id","parent"]:["id"]);let i=t.attrs.get("id")??"";V("scene",i)||M("Scene ID is invalid.",t.line,i);let r=t.attrs.get("parent")??n;r!==void 0&&!V("episode",r)&&M("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 m=e.record(),g=m.type==="environment"?0:m.type==="location"?1:m.type==="cast"?2:m.type==="prop"?3:-1;g<f&&M("Scene records are not in canonical order.",m.source.line,m.type),f=g,m.type==="environment"?(s!==void 0&&M("Scene environment is duplicated.",m.source.line,m.type),m.slots.length>2&&M("environment has too many slots.",m.source.line,m.type),s={...m.slots[0]===void 0?{}:{space:m.slots[0]},...m.slots[1]===void 0?{}:{time:m.slots[1]}}):m.type==="location"?(c!==void 0&&M("Scene location is duplicated.",m.source.line,m.type),m.slots.length===0?c=null:(V("location",m.slots[0])||M("Location ref ID is invalid.",m.source.line,m.slots[0]),c={location_id:m.slots[0],state_ids:Gc(m.slots.slice(1),m.source.line)})):m.type==="cast"?(V("actor",m.slots[0])||M("Cast ref ID is invalid.",m.source.line,m.slots[0]??""),p.has(m.slots[0])&&M("Scene repeats an actor reference.",m.source.line,m.slots[0]),p.add(m.slots[0]),a.push({actor_id:m.slots[0],state_ids:Gc(m.slots.slice(1),m.source.line)})):m.type==="prop"?(V("prop",m.slots[0])||M("Prop ref ID is invalid.",m.source.line,m.slots[0]??""),l.has(m.slots[0])&&M("Scene repeats a prop reference.",m.source.line,m.slots[0]),l.add(m.slots[0]),d.push({prop_id:m.slots[0],state_ids:Gc(m.slots.slice(1),m.source.line)})):M("Unknown scene header record.",m.source.line,m.type)}c===void 0&&M("Scene must declare location or [location].",e.peek().line,i);let u=e.tag("body",!1);Ve(u,[]);let h=[];for(;e.nextTag()?.name!=="body"||e.nextTag()?.closing!==!0;)h.push(bu(e));return Ve(e.tag("body",!0),[]),Ve(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:h,...o===void 0?{}:{extend:o}}}}function Hc(e,t,n){Ve(t,["id"]);let o=t.attrs.get("id")??"";V("episode",o)||M("Episode ID is invalid.",t.line,o);let i,r,s=[],c=0;for(;e.nextTag()?.name!=="episode"||e.nextTag()?.closing!==!0;){let a=Jo(e);(a.aliases!==void 0||a.prompt!==void 0)&&M("Invalid episode child modifier.",e.peek().line,"modifier");let d=e.nextTag();if(d?.name==="scene"&&!d.closing){c=2,e.take(),s.push(zc(e,d,o,a.extend).value);continue}a.extend!==void 0&&M("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&&M("Episode records are not in canonical order.",p.source.line,p.type),c=l,p.type==="title"?(i!==void 0&&M("Episode title is duplicated.",p.source.line,p.type),p.slots.length!==0&&M("Episode title takes no slots.",p.source.line,p.type),i=p.content):p.type==="synopsis"?(r!==void 0&&M("Episode synopsis is duplicated.",p.source.line,p.type),p.slots.length!==0&&M("Episode synopsis takes no slots.",p.source.line,p.type),r=p.content):M("Unknown episode record.",p.source.line,p.type)}return Ve(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 Jc(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]))&&M(`Span range must contain two ${t} IDs.`,e.line,n),[o[0],o[1]]}function Ix(e,t,n){Ve(t,[]);let o,i,r,s,c,a,d,p,l=[],f=0;for(;e.nextTag()?.name!=="script"||e.nextTag()?.closing!==!0;){let u=Jo(e);(u.aliases!==void 0||u.prompt!==void 0)&&M("Invalid script child modifier.",e.peek().line,"modifier");let h=e.nextTag();if(h?.name==="episode"&&!h.closing){f=8,e.take(),l.push(Hc(e,h,u.extend));continue}u.extend!==void 0&&M("extend must precede an episode here.",e.peek().line,"extend");let m=e.record(),g=m.type==="title"?0:m.type==="worldview"?1:m.type==="worldview-raw"?2:m.type==="style"?3:m.type==="synopsis"?4:m.type==="logline"?5:m.type==="theme"?6:m.type==="main-characters"||m.type==="main-character"?7:-1;g<f&&M("Script records are not in canonical order.",m.source.line,m.type),f=g,m.type!=="main-character"&&m.slots.length!==0&&M("Script metadata record takes no slots.",m.source.line,m.type),m.type==="title"?(o!==void 0&&M("Script title is duplicated.",m.source.line,m.type),o=m.content):m.type==="worldview"?(i!==void 0&&M("Script worldview is duplicated.",m.source.line,m.type),i=m.content):m.type==="worldview-raw"?(r!==void 0&&M("Script worldview-raw is duplicated.",m.source.line,m.type),r=m.content):m.type==="style"?(s!==void 0&&M("Script style is duplicated.",m.source.line,m.type),s=m.content):m.type==="synopsis"?(c!==void 0&&M("Script synopsis is duplicated.",m.source.line,m.type),c=m.content):m.type==="logline"?(a!==void 0&&M("Script logline is duplicated.",m.source.line,m.type),a=m.content):m.type==="theme"?(d!==void 0&&M("Script theme is duplicated.",m.source.line,m.type),d=m.content):m.type==="main-characters"?(p!==void 0&&M("Script main-characters is duplicated.",m.source.line,m.type),p=[]):m.type==="main-character"&&p!==void 0&&m.slots.length===2&&m.content===""?p.push({name:m.slots[0],role:m.slots[1]}):M("Unknown script record.",m.source.line,m.type)}return Ve(e.tag("script",!0),[]),(o===void 0||i===void 0||s===void 0)&&M("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 Ou(e){let t=new Kc(e),n=t.tag("authoring",!1);Ve(n,["version"]),n.attrs.get("version")!=="1"&&M("authoring version must be 1.",1,n.attrs.get("version")??"<missing>");let o=t.nextTag()?.name==="create"?Ex(t):[],i=[];for(;t.nextTag()?.name!=="authoring"||t.nextTag()?.closing!==!0;){let s=Jo(t);(s.aliases!==void 0||s.prompt!==void 0)&&M("Invalid target modifier.",t.peek().line,"modifier");let c=t.take(),a=Bc(c.raw,c.line);if((!a||a.closing)&&M("Expected an authoring target.",c.line,c.raw),a.name==="script")i.push(Ix(t,a,s.extend));else if(a.name==="episode")i.push({kind:"episode",value:Hc(t,a,s.extend)});else if(a.name==="scene"){let d=zc(t,a,void 0,s.extend);d.parent||M("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&&M("A span cannot carry node extensions.",c.line,c.raw),Ve(a,["range"]);let[d,p]=Jc(a,"episode"),l=[];for(;t.nextTag()?.name!=="episode-span"||t.nextTag()?.closing!==!0;){let f=Jo(t);(f.aliases!==void 0||f.prompt!==void 0)&&M("Invalid episode child modifier.",t.peek().line,"modifier");let u=t.tag("episode",!1);l.push(Hc(t,u,f.extend))}Ve(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&&M("A span cannot carry node extensions.",c.line,c.raw),Ve(a,["parent","range"]);let[d,p]=Jc(a,"scene"),l=a.attrs.get("parent")??M("scene-span needs parent.",c.line,c.raw);V("episode",l)||M("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=Jo(t);(u.aliases!==void 0||u.prompt!==void 0)&&M("Invalid scene child modifier.",t.peek().line,"modifier");let h=t.tag("scene",!1);f.push(zc(t,h,l,u.extend).value)}Ve(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&&M("A span cannot carry node extensions.",c.line,c.raw),Ve(a,["parent","range"]);let[d,p]=Jc(a,"action"),l=a.attrs.get("parent")??M("action-span needs parent.",c.line,c.raw);V("scene",l)||M("action-span parent must be a Scene ID.",c.line,l),Ve(t.tag("body",!1),[]);let f=[];for(;t.nextTag()?.name!=="body"||t.nextTag()?.closing!==!0;)f.push(bu(t));Ve(t.tag("body",!0),[]),Ve(t.tag("action-span",!0),[]),i.push({kind:"action-span",parent:l,from:d,through:p,values:f})}else M("Unknown authoring target.",c.line,a.name)}Ve(t.tag("authoring",!0),[]),(t.index!==t.lines.length||i.length===0)&&M("Authoring file has trailing content or no targets.",t.peek().line,"<root>");let r=i[0].kind;return i.every(s=>s.kind===r)||M("All targets must have the same kind.",1,r),{declarations:o,targets:i,targetKind:r}}function wn(e){if(Array.isArray(e))return e.map(t=>wn(t));if(ee(e)){let t={};for(let n of Object.keys(e).sort())t[n]=wn(e[n]);return t}return e}function Fc(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 vu(e,t){if(!(t.ok||e!==null&&sc(Le(e),t)))throw new E("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 Ne(e,t){throw new E(e,{exitCode:k,errorCode:"AUTHORING_APPLY_INVALID",data:{actual:t}})}function qc(e){return{ids:e.map(t=>t.action_id),counts:{episodes:0,scenes:0,actions:e.length}}}function Ai(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 co(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 Ax(e){return e.kind==="script"?co(e.value.episodes):e.kind==="episode"?co([e.value]):e.kind==="episode-span"?co(e.values):e.kind==="scene"?Ai([e.value]):e.kind==="scene-span"?Ai(e.values):qc(e.values)}function kx(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 Yc(e,t){return JSON.stringify(wn(e))===JSON.stringify(wn(t))}function Ru(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 Mu(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 Lu(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 Nu(e,t){let n=e===null?[]:Lu(e),o=Lu(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 bx(e,t){for(let n of t)if(n.kind==="actor")e.actors.some(o=>o.actor_id===n.value.actor_id)&&Ne("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)&&Ne("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)&&Ne("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||Ne("State declaration owner was not found.",[n.ownerId]),o.states.some(i=>i.state_id===n.value.state_id)&&Ne("State declaration cannot redefine an existing state.",[`${n.ownerId}/${n.value.state_id}`]),o.states.push(structuredClone(n.value))}}function Qt(e,t,n){let o=e.indexOf(t),i=e.indexOf(n);return(o<0||i<0)&&Ne("Span endpoint was not found.",[t,n]),[Math.min(o,i),Math.max(o,i)]}function Ox(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"?Qt(o,t.value.episode_id,t.value.episode_id):Qt(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"?Qt(o,t.value.scene_id,t.value.scene_id):Qt(o,t.from,t.through)}let n=e.episodes.flatMap(o=>o.scenes.flatMap(i=>i.actions.map(r=>r.action_id)));return Qt(n,t.from,t.through)}function vx(e,t){let n=-1;for(let o of t){let[i,r]=Ox(e,o);i<=n&&Ne("Replace targets must follow current document order without overlap.",[Tu(o)]),n=r}}function Tu(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 Uu(e,t){if(t.kind==="script")return{...co(e.episodes),siblings:0};if(t.kind==="episode"){let r=gn(e,t.value.episode_id);return{...co(r?[r.episode]:[]),siblings:Math.max(0,e.episodes.length-(r?1:0))}}if(t.kind==="episode-span"){let[r,s]=Qt(e.episodes.map(c=>c.episode_id),t.from,t.through);return{...co(e.episodes.slice(r,s+1)),siblings:e.episodes.length-(s-r+1)}}if(t.kind==="scene"){let r=Vn(e,t.value.scene_id),s=gn(e,t.parent)?.episode;return{...Ai(r?[r.scene]:[]),siblings:r?Math.max(0,r.episode.scenes.length-1):s?.scenes.length??0}}if(t.kind==="scene-span"){let r=gn(e,t.parent)?.episode;if(!r)return{...Ai([]),siblings:0};let[s,c]=Qt(r.scenes.map(a=>a.scene_id),t.from,t.through);return{...Ai(r.scenes.slice(s,c+1)),siblings:r.scenes.length-(c-s+1)}}let n=Vn(e,t.parent)?.scene;if(!n)return{...qc([]),siblings:0};let[o,i]=Qt(n.actions.map(r=>r.action_id),t.from,t.through);return{...qc(n.actions.slice(o,i+1)),siblings:n.actions.length-(i-o+1)}}function Cu(e,t){let n=Ax(e),o=new Set(t.ids),i=new Set(n.ids);return{kind:e.kind,address:Tu(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 Rx(e,t){if(t.kind==="script"&&Ne("An existing Script v4 is not replaced through a script root.",["script"]),t.kind==="episode"){let n=gn(e,t.value.episode_id);n||Ne("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]=Qt(e.episodes.map(i=>i.episode_id),t.from,t.through);t.values.length===0&&Ne("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=Vn(e,t.value.scene_id);(!n||n.episode.episode_id!==t.parent)&&Ne("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=gn(e,t.parent)?.episode;n||Ne("Scene span parent was not found.",[t.parent]);let[o,i]=Qt(n.scenes.map(r=>r.scene_id),t.from,t.through);t.values.length===0&&Ne("Scene span replacement cannot be empty.",[t.from,t.through]),n.scenes.splice(o,i-o+1,...structuredClone(t.values))}else{let n=Vn(e,t.parent)?.scene;n||Ne("Action span parent was not found.",[t.parent]);let[o,i]=Qt(n.actions.map(r=>r.action_id),t.from,t.through);t.values.length===0&&Ne("Action span replacement cannot be empty.",[t.from,t.through]),n.actions.splice(o,i-o+1,...structuredClone(t.values))}}function Mx(e,t){if(t.kind==="episode")e.episodes.push(structuredClone(t.value));else if(t.kind==="scene"){let n=gn(e,t.parent)?.episode;n||Ne("Scene create parent was not found.",[t.parent]),n.scenes.push(structuredClone(t.value))}else Ne("This target kind does not support create against an existing script.",[t.kind])}function Pu(e){if(e.targets.length!==1||e.targets[0].kind!=="script")return Ne("Script create requires exactly one script target.",[e.targetKind]);if(e.declarations.some(n=>n.kind==="state"))return Ne("Standalone state declarations need an existing owner.",["state"]);let t=e.targets[0];return{version:4,...structuredClone(t.value),...kx(e.declarations)}}function Vu(e,t,n){let o;if(e===null)n!=="create"&&Ne("A missing target requires one script create target.",[n,t.targetKind]),o=Pu(t);else if(n==="create"&&t.targetKind==="script")o=Pu(t),Yc(o,e)||Ne("Script create retry differs from the existing script.",["script"]);else{o=structuredClone(e),n==="replace"&&vx(e,t.targets),bx(o,t.declarations);let r=t.targets.map(a=>Uu(e,a));if(n==="replace")for(let a of[...t.targets].reverse())Rx(o,a);else for(let a of t.targets)Mx(o,a);let s=t.targets.map((a,d)=>Cu(a,r[d])),c=Le(o);return vu(e,c),{script:o,changed:!Yc(e,o),validation:c,targets:s,declarations:Ru(e,t.declarations),retainedOrphanAssets:Mu(o),identity:Nu(e,o)}}let i=Le(o);return vu(e,i),{script:o,changed:e===null||!Yc(e,o),validation:i,declarations:Ru(e,t.declarations),retainedOrphanAssets:Mu(o),identity:Nu(e,o),targets:t.targets.map(r=>{let s=e===null?{...co([]),siblings:0}:Uu(e,r);return Cu(r,s)})}}function Bo(e,t){throw new E(e,{exitCode:G,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 Lx(e){(!e||e==="-")&&Bo("Authoring input must be a named file.",[e||"<missing>"]);let t=$u.resolve(e),n;try{n=Er.statSync(t)}catch{throw new E("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()||Bo("Authoring input must be a regular file.",[t]);let o=Er.readFileSync(t);return{absolutePath:t,bytes:o,text:o.toString("utf-8")}}function Nx(e){let t=lr(e);if(t===null)return{script:null,baseline:"missing",fingerprint:t};let n;try{n=JSON.parse(Er.readFileSync(e,"utf-8"))}catch(i){throw new E("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=Ss(n);return{script:o,baseline:De(o),fingerprint:t}}function Ux(e){let t=e.create===!0,n=e.replace===!0;return t===n&&Bo("Choose exactly one authoring mode.",[`create=${t}`,`replace=${n}`]),t?"create":"replace"}function Du(e){return`sha256:${he(JSON.stringify(e))}`}function Cx(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 Px(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 Tx(e,t,n,o,i){let r=Ou(t.text),s=i.script===null?null:mn(i.script),c=Vu(s,r,n),a=`sha256:${Zc.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=Du(d),l=e.apply===!0,f=v(e.plan).trim();if(l&&!f&&Bo("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!l&&f&&Bo("--plan is only valid together with --apply.",[`plan=${f}`]),l&&f!==p)throw new E("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?ur(o,i.fingerprint):Tt(o,i.baseline),ze(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}},J]}function Gu(e){let t=Array.isArray(e._args)?e._args:[],n=typeof t[0]=="string"?t[0]:"",o=Lx(n),i=Ux(e),r=Ae(e),s=Nx(r);if(s.script===null||s.script.version===4)return Tx(e,o,i,r,s);let c=ku(o.text),a=Su(Nt(s.script),c,i),d=`sha256:${Zc.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=Du(p),f=e.apply===!0,u=v(e.plan).trim();if(f&&!u&&Bo("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!f&&u&&Bo("--plan is only valid together with --apply.",[`plan=${u}`]),f&&u!==l)throw new E("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?ur(r,s.fingerprint):Tt(r,s.baseline),ze(r,a.script));let h=Cx(a);return[{text:[`${f?"Applied":"Planned"} ${a.targets.length} ${c.targetKind} target(s); episodes ${h.before.episodes}\u2192${h.after.episodes}, scenes ${h.before.scenes}\u2192${h.after.scenes}, actions ${h.before.actions}\u2192${h.after.actions}`,`plan: ${l}`,...Px(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:h,validation:a.validation,retained_orphan_assets:a.retainedOrphanAssets,applied:f,script_version:3}},J]}function Bu(e){return Array.isArray(e.rows)}function Vx(e){return e.endsWith(`
134
134
  `)?e:`${e}
135
- `}function yu(e){return Array.isArray(e)?e.map(t=>String(t).replace(/[\r\n]+/g," ")):[]}function sE(e){return e==null?"":(typeof e=="string"?e:JSON.stringify(e)).replace(/\t/g," ").replace(/\r?\n/g," ")}function aE(e){if(!wu(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=>sE(n[o])).join(" "))].join(`
136
- `)}function Eu(e,t,n,o){if(!(e.text===""&&Object.keys(e.data).length===0)){if(o==="addr"&&wu(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 Ju(e){return Array.isArray(e)?e.map(t=>String(t).replace(/[\r\n]+/g," ")):[]}function $x(e){return e==null?"":(typeof e=="string"?e:JSON.stringify(e)).replace(/\t/g," ").replace(/\r?\n/g," ")}function Dx(e){if(!Bu(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=>$x(n[o])).join(" "))].join(`
136
+ `)}function Ku(e,t,n,o){if(!(e.text===""&&Object.keys(e.data).length===0)){if(o==="addr"&&Bu(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(rE(aE(e.data)??e.text))}}function dr(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=yu(e.data.actual),o=yu(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===J,exit_code:t,...e.data};i.ok=t===J,i.exit_code=t,process.stdout.write(JSON.stringify(i,null,2)+`
139
+ `)}else process.stdout.write(Vx(Dx(e.data)??e.text))}}function Sr(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=Ju(e.data.actual),o=Ju(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 Uc=new WeakMap;function cE(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function dE(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[cE(t),n]))}function pE(e){let t=[],n=e;for(;n;)t.unshift(n),n=n.parent;return Object.assign({},...t.map(o=>o.opts()))}function q(e,t){return async(...n)=>{let o=n[n.length-1],i=n.slice(0,-2).filter(d=>d!==void 0),r=dE(pE(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]=Uc.get(o)==="write"?await ns(Se(r),s):await s();Eu(c,a,t.jsonMode,t.format),t.exitCode=a}}function Ae(e,t){return e.registeredArguments.forEach((n,o)=>{n.description=t[o]??""}),e}function ae(e,t="write"){return Uc.set(e,t),e.option("-p, --script-path <path>","Script JSON file (default: ./workspace/script.json)")}function Pc(e){return Uc.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 _u(e,t){let n=e.command("authoring").description("Structured screenplay compilation and atomic application transactions"),o=ae(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(q(hu,t));Ae(o,["Structured .scriptctl file"]);let i=ae(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(q(vl,t));Ae(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=ae(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(q(d=>Jl(c,d),t))}}import*as hs from"node:fs";import*as Jc from"node:path";import*as Vc from"node:fs";import*as li from"node:path";import{fileURLToPath as lE}from"node:url";var Tc="@lingjingai/scriptctl",Cc="";function $c(){if(Cc)return Cc;let e=li.dirname(lE(import.meta.url));for(;;){try{let n=Vc.readFileSync(li.join(e,"package.json"),"utf-8");if(JSON.parse(n).name===Tc)return Cc=e,e}catch{}let t=li.dirname(e);if(t===e)throw new Error(`${Tc} package root not found`);e=t}}function ui(){let e=Vc.readFileSync(li.join($c(),"package.json"),"utf-8"),t=JSON.parse(e).version;if(typeof t!="string")throw new Error(`${Tc} package.json has no string version`);return t}var xu=/^\d+\.\d+\.\d+$/,uE="unreleased";function Su(){return Jc.join($c(),"changes")}function fE(){return ui()}function pr(e){if(!xu.test(e))throw new x("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 Gc(e,t){let n=pr(e),o=pr(t);for(let i=0;i<3;i++)if(n[i]!==o[i])return n[i]-o[i];return 0}function mE(){let e=Su();return hs.readdirSync(e).filter(t=>t.endsWith(".md")).map(t=>t.slice(0,-3)).filter(t=>xu.test(t)).sort(Gc)}function gs(e){return hs.readFileSync(Jc.join(Su(),`${e}.md`),"utf-8").trimEnd()}function Dc(e,t){return new x(`No changelog entry exists for ${e}.`,{exitCode:b,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:b,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 hE(e){return e.map(gs).join(`
142
+ `)}return e.exitCode}var Wc=new WeakMap;function Gx(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function Jx(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[Gx(t),n]))}function Bx(e){let t=[],n=e;for(;n;)t.unshift(n),n=n.parent;return Object.assign({},...t.map(o=>o.opts()))}function q(e,t){return async(...n)=>{let o=n[n.length-1],i=n.slice(0,-2).filter(d=>d!==void 0),r=Jx(Bx(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]=Wc.get(o)==="write"?await ys(Ae(r),s):await s();Ku(c,a,t.jsonMode,t.format),t.exitCode=a}}function ke(e,t){return e.registeredArguments.forEach((n,o)=>{n.description=t[o]??""}),e}function ce(e,t="write"){return Wc.set(e,t),e.option("-p, --script-path <path>","Script JSON file (default: ./workspace/script.json)")}function Xc(e){return Wc.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 ju(e,t){let n=e.command("authoring").description("Structured screenplay compilation and atomic application transactions"),o=ce(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(q(Gu,t));ke(o,["Structured .scriptctl file"]);let i=ce(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(q(Wl,t));ke(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=ce(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(q(d=>lu(c,d),t))}}import*as Ls from"node:fs";import*as sd from"node:path";import*as nd from"node:fs";import*as ki from"node:path";import{fileURLToPath as Kx}from"node:url";var td="@lingjingai/scriptctl",ed="";function od(){if(ed)return ed;let e=ki.dirname(Kx(import.meta.url));for(;;){try{let n=nd.readFileSync(ki.join(e,"package.json"),"utf-8");if(JSON.parse(n).name===td)return ed=e,e}catch{}let t=ki.dirname(e);if(t===e)throw new Error(`${td} package root not found`);e=t}}function bi(){let e=nd.readFileSync(ki.join(od(),"package.json"),"utf-8"),t=JSON.parse(e).version;if(typeof t!="string")throw new Error(`${td} package.json has no string version`);return t}var zu=/^\d+\.\d+\.\d+$/,jx="unreleased";function Hu(){return sd.join(od(),"changes")}function zx(){return bi()}function Ir(e){if(!zu.test(e))throw new E("Version must use x.y.z.",{exitCode:G,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 rd(e,t){let n=Ir(e),o=Ir(t);for(let i=0;i<3;i++)if(n[i]!==o[i])return n[i]-o[i];return 0}function Hx(){let e=Hu();return Ls.readdirSync(e).filter(t=>t.endsWith(".md")).map(t=>t.slice(0,-3)).filter(t=>zu.test(t)).sort(rd)}function Ms(e){return Ls.readFileSync(sd.join(Hu(),`${e}.md`),"utf-8").trimEnd()}function id(e,t){return new E(`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 Qx(e,t){return new E(`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 Fx(e){return e.map(Ms).join(`
143
143
 
144
- `)}function Iu(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: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 x("--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 x("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=gs(uE);return[{text:d,data:{content:d,versions:[],unreleased:!0}},B]}let s=mE(),c=fE();if(n){if(pr(n),!s.includes(n))throw Dc(n,s);let d=gs(n);return[{text:d,data:{content:d,versions:[n],unreleased:!1}},B]}if(o||i){if(!o)throw new x("--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>"]}});pr(o);let d=i||c;if(pr(d),!s.includes(d))throw Dc(d,s);let p=s.filter(f=>Gc(f,o)>0&&Gc(f,d)<=0);if(p.length===0)throw gE(o,d);let l=hE(p);return[{text:l,data:{content:l,versions:p,from:o,to:d,unreleased:!1}},B]}if(!s.includes(c))throw Dc(c,s);let a=gs(c);return[{text:a,data:{content:a,versions:[c],unreleased:!1}},B]}import*as Mt from"node:fs";import*as Po from"node:path";import{createRequire as E_}from"node:module";import*as vn from"node:fs";import*as qn from"node:path";import*as ku from"node:os";import{fileURLToPath as yE}from"node:url";function Au(e){return e.startsWith("~")?qn.join(ku.homedir(),e.slice(1)):e}function wE(e){let t=vn.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 Bc(){let e=[],t=(process.env.SCRIPTCTL_ENV_FILE??"").trim();t&&e.push(Au(t));let n=(process.env.SCRIPTCTL_SKILL_DIR??"").trim();n&&e.push(qn.join(Au(n),".env"));let o;try{o=yE(import.meta.url)}catch{o=process.cwd()}let i=qn.resolve(o),r=new Set;for(;;){let s=qn.dirname(i);if(s===i||r.has(s))break;r.add(s),e.push(qn.join(s,".env")),i=s}return e}function bu(){let e=process.env.SCRIPTCTL_NO_DOTENV;if(e==="1"||e==="true"||e==="True")return;let t=new Set;for(let n of Bc()){let o;try{o=vn.existsSync(n)?vn.realpathSync(n):n}catch{o=n}t.has(o)||!vn.existsSync(n)||!vn.statSync(n).isFile()||(t.add(o),wE(n))}}var pe=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 Kc(e,t){if(e.updateEpisodeCount)try{await e.updateEpisodeCount(t)}catch{}}function Ou(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 fr from"node:fs";import*as Ru from"node:os";import*as lr from"node:path";import{parseDocument as EE}from"yaml";function oe(e,t,n){return{id:e,mode:t,version:"1",maxOutputTokens:n,defaultProfile:"default"}}var pn={"direct.episode-titles":oe("direct.episode-titles","tool",4096),"direct.batch-extract":oe("direct.batch-extract","text",16e3),"direct.episode-synopsis":oe("direct.episode-synopsis","tool",2048),"direct.synopsis-reduction":oe("direct.synopsis-reduction","tool",4096),"direct.script-synopsis":oe("direct.script-synopsis","tool",2048),"direct.asset-grouping":oe("direct.asset-grouping","text",8e3),"direct.asset-curation":oe("direct.asset-curation","text",2e4),"direct.asset-curation-audit":oe("direct.asset-curation-audit","text",2e4),"direct.location-canonicalization":oe("direct.location-canonicalization","text",2e4),"direct.state-curation":oe("direct.state-curation","text",2e4),"direct.state-binding":oe("direct.state-binding","tool",16e3),"metadata.global":oe("metadata.global","text",16e3),"metadata.descriptions":oe("metadata.descriptions","text",16e3),"synopsis.chunk":oe("synopsis.chunk","text",4096),"synopsis.episode":oe("synopsis.episode","text",4096),"synopsis.arc":oe("synopsis.arc","text",16e3),"synopsis.script-overview":oe("synopsis.script-overview","text",16e3),"ingest.body-start":oe("ingest.body-start","text",16e3),"ingest.arc-summary":oe("ingest.arc-summary","text",4096),"ingest.text-normalize":oe("ingest.text-normalize","text",32e3),"ingest.episode-assets":oe("ingest.episode-assets","tool",32e3),"ingest.name-fix":oe("ingest.name-fix","tool",16e3),"ingest.mention-resolve":oe("ingest.mention-resolve","text",8e3),"ingest.asset-extract":oe("ingest.asset-extract","text",8e3),"ingest.asset-curate":oe("ingest.asset-curate","text",32e3),"ingest.asset-recall":oe("ingest.asset-recall","text",65536),"ingest.asset-refine":oe("ingest.asset-refine","text",32e3),"ingest.state-reconcile":oe("ingest.state-reconcile","text",32e3),"ingest.asset-audit":oe("ingest.asset-audit","tool",32e3),"ingest.speaker-audit":oe("ingest.speaker-audit","tool",16e3),"ingest.comic-serial":{id:"ingest.comic-serial",mode:"document",version:"1",defaultProfile:"default"},"ingest.video-serial":oe("ingest.video-serial","video",65536)},vu=Object.keys(pn).filter(jc);function jc(e){return Object.hasOwn(pn,e)}var _E=new Set(["protocol","baseUrl","apiKey","timeoutMs","maxAttempts","videoResponseSchemaField","videoUploadMode","documentResponseSchemaField","documentUploadMode"]),xE=new Set(["provider","model","thinking","reasoning","temperature"]),SE=new Set(["env"]),IE=new Set(["budgetTokens"]);function Ne(e,t=[]){return new x(e,{exitCode:b,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 Qc(e,t){let n;try{n=new URL(e)}catch{throw Ne(`${t} must be an absolute URL.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Ne(`${t} must use http or https.`);return n.toString().replace(/\/$/,"")}function Fc(e,t="provider base URL"){return Qc(e,t)}function AE(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zn(e,t){if(!AE(e))throw Ne(`${t} must be a mapping.`,[`${t}: ${typeof e}`]);return e}function Mo(e,t){if(typeof e!="string"||!e.trim())throw Ne(`${t} must be a non-empty string.`);return e.trim()}function Hc(e,t,n,o){if(!Number.isInteger(e)||typeof e!="number"||e<n||o!==void 0&&e>o)throw Ne(`${t} must be an integer in ${o===void 0?`[${n}, +\u221E)`:`[${n}, ${o}]`}.`);return e}function ur(e,t,n){let o=Object.keys(e).filter(i=>!t.has(i));if(o.length>0)throw Ne(`${n} contains unknown fields.`,o)}function kE(e,t){let n=Zn(t,`providers.${e}`);ur(n,_E,`providers.${e}`);let o=Mo(n.protocol,`providers.${e}.protocol`);if(o!=="anthropic"&&o!=="openai-compatible"&&o!=="google-gemini"&&o!=="google-vertex")throw Ne(`providers.${e}.protocol is unsupported.`,[o]);let i=n.baseUrl===void 0&&o!=="openai-compatible"?null:Qc(Mo(n.baseUrl,`providers.${e}.baseUrl`),`providers.${e}.baseUrl`),r="";if(o!=="google-vertex"){let c=Zn(n.apiKey,`providers.${e}.apiKey`);if(ur(c,SE,`providers.${e}.apiKey`),r=Mo(c.env,`providers.${e}.apiKey.env`),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw Ne(`providers.${e}.apiKey.env must be an environment variable name.`)}let s={protocol:o,baseUrl:i,apiKeyEnv:r,timeoutMs:Hc(n.timeoutMs,`providers.${e}.timeoutMs`,1),maxAttempts:Hc(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 Ne(`providers.${e}.${c} requires a Gemini ${c.startsWith("video")?"video":"document"} provider.`);if(a!=="responseJsonSchema"&&a!=="responseSchema")throw Ne(`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 Ne(`providers.${e}.${c} requires a Gemini ${c.startsWith("video")?"video":"document"} provider.`);if(a!=="file-api"&&a!=="base64")throw Ne(`providers.${e}.${c} must be file-api or base64.`);s[c]=a}}return s}function bE(e,t,n){let o=Zn(t,`models.${e}`);ur(o,xE,`models.${e}`);let i=Mo(o.provider,`models.${e}.provider`),r=n[i];if(!r)throw Ne(`models.${e} references an unknown provider.`,[i]);let s={provider:i,model:Mo(o.model,`models.${e}.model`)};if(o.reasoning!==void 0&&(s.reasoning=Mo(o.reasoning,`models.${e}.reasoning`)),o.temperature!==void 0){let c=o.temperature;if(typeof c!="number"||!Number.isFinite(c)||c<0)throw Ne(`models.${e}.temperature must be a number \u2265 0.`);s.temperature=c}if(o.thinking!==void 0){if(r.protocol!=="anthropic")throw Ne(`models.${e}.thinking is only valid for anthropic providers.`);let c=Zn(o.thinking,`models.${e}.thinking`);ur(c,IE,`models.${e}.thinking`),s.thinkingBudgetTokens=Hc(c.budgetTokens,`models.${e}.thinking.budgetTokens`,1024)}return s}function OE(e,t){let n=Zn(e,"config");if(ur(n,new Set(["version","providers","models","tasks"]),"config"),n.version!==1)throw Ne("config.version must be 1.");let o=Zn(n.providers,"providers"),i={};for(let[a,d]of Object.entries(o))i[a]=kE(a,d);let r=Zn(n.models,"models"),s={};for(let[a,d]of Object.entries(r))s[a]=bE(a,d,i);if(!s.default)throw Ne("models.default is required.");let c={};if(n.tasks!==void 0){let a=Zn(n.tasks,"tasks");for(let[d,p]of Object.entries(a)){if(!jc(d))throw Ne("tasks contains an unknown task id.",[d]);let l=Mo(p,`tasks.${d}`);if(!s[l])throw Ne(`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 fi={version:1,providers:{gw:{protocol:"openai-compatible",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},"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-agent":{provider:"google-gemini",model:"gemini-3.8-flash",temperature:0}},tasks:{"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 vE(){let e=(process.env.PROJECT_LITELLM_GATEWAY_BASE_URL??"").trim(),t=e?Qc(e,"PROJECT_LITELLM_GATEWAY_BASE_URL"):null;return{...fi,providers:{gw:{...fi.providers.gw,baseUrl:t},"google-gemini":{...fi.providers["google-gemini"]},nnyyai:{...fi.providers.nnyyai}},models:{...fi.models},tasks:{...fi.tasks}}}function RE(){let e=(process.env.XDG_CONFIG_HOME??"").trim();return e?lr.join(e,"scriptctl","llm.yaml"):lr.join(Ru.homedir(),".config","scriptctl","llm.yaml")}function zc(e){if(!fr.existsSync(e))throw Ne("LLM configuration file does not exist.",[e]);let t=EE(fr.readFileSync(e,"utf-8"),{uniqueKeys:!0});if(t.errors.length>0)throw Ne("LLM configuration YAML is invalid.",t.errors.map(o=>o.message));let n=t.toJS();return OE(n,lr.resolve(e))}function mi(e){let t=(e??"").trim();if(t)return zc(t);let n=(process.env.SCRIPTCTL_LLM_CONFIG??"").trim();if(n)return zc(n);let o=RE();return fr.existsSync(o)?zc(o):vE()}import*as Ku from"node:crypto";import*as ju from"node:fs";import NE,{APIConnectionError as UE,APIConnectionTimeoutError as PE,APIError as CE,APIUserAbortError as TE}from"@anthropic-ai/sdk";var Yc=1e8;function ME(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 C=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=St(o.classification??ME(t),{retryable:this.retryable,message:n,...o.context,...this.details.length>0?{details:this.details}:{}}),this.modelFailures=o.modelFailures??[]}};function LE(e){return new Promise(t=>setTimeout(t,e))}function Gt(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 Jt(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 C&&(n=Gt(n,i.usage),i.attempts=o,i.usage=n),!(i instanceof C)||!i.retryable||o===e)throw i;await LE(Math.min(3e4,1e3*2**(o-1)))}throw new Error("unreachable retry state")}function Mu(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 Lu(e){if(e instanceof C)return e;if(e instanceof TE)return new C("request_failed","Anthropic request was aborted.");if(e instanceof PE)return new C("timeout","Anthropic request timed out.",{retryable:!0});if(e instanceof UE)return new C("request_failed","Anthropic connection failed.",{retryable:!0,details:[e.message.slice(0,500)]});if(e instanceof CE){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 C(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 C("request_failed","Anthropic request failed.",{details:[t.slice(0,500)]})}var ys=class{constructor(t,n,o){this.provider=t;this.model=n;let i={apiKey:o};t.baseUrl&&(i.baseURL=t.baseUrl),this.client=new NE({...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 Jt(this.provider.maxAttempts,async()=>{try{let o=await this.client.messages.create(this.params(t),{timeout:this.provider.timeoutMs,signal:t.signal}),i=Mu(o);if(o.stop_reason==="max_tokens")throw new C("truncated","Provider output was truncated.",{usage:i});if(o.stop_reason==="refusal")throw new C("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 C("empty_response","Provider returned an empty text response.",{usage:i});return{text:r,finishReason:o.stop_reason??"",usage:i,raw:o}}catch(o){throw Lu(o)}});return{...n.value,attempts:n.attempts,usage:Gt(n.failedUsage,n.value.usage)}}async generateTool(t){let n=await Jt(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=Mu(i);if(i.stop_reason==="max_tokens")throw new C("truncated","Provider tool output was truncated.",{usage:r});if(i.stop_reason==="refusal")throw new C("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 C("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 Lu(o)}});return{...n.value,attempts:n.attempts,usage:Gt(n.failedUsage,n.value.usage)}}};import*as Xc from"node:fs";import*as ed from"node:path";import{File as BE}from"node:buffer";import{Agent as KE,fetch as Es,FormData as jE}from"undici";function VE(e){return typeof e=="object"&&e!==null}function qc(e){let t=[],n=new Set,o=e;for(;VE(o)&&!n.has(o);)n.add(o),t.push(o),o=o.cause;return t}function ws(e){for(let t of qc(e)){if(typeof t.status=="number")return t.status;if(typeof t.statusCode=="number")return t.statusCode}return null}function $E(e){for(let t of qc(e))if(typeof t.code=="string")return t.code}function DE(e){for(let t of qc(e))if(typeof t.name=="string")return t.name}function GE(e){let t=DE(e);return t==="AbortError"||t==="TimeoutError"||t==="RequestTimeoutError"||t==="APIConnectionTimeoutError"}function JE(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 Lo(e,t,n,o,i={}){if(t?.aborted)return new C("cancelled",n,{details:[o],classification:{failure_type:"cancelled",failure_code:"cancelled"},context:i});let r=$E(e),s=GE(e)?{failure_type:"timeout",failure_code:"request_timeout"}:JE(r),c=s.failure_type==="timeout"?"timeout":"network";return new C(c,n,{retryable:!0,details:[o],classification:s,context:{...i,...r?{system_code:r}:{}}})}function No(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 C(i,t,{retryable:s,details:[`status: ${e}`,n],classification:r,context:{...o,http_status:e}})}var zE=2e3;function HE(e){return new Promise(t=>setTimeout(t,e))}function Zc(e,t,n,o){if(e instanceof C)return e;let i=e instanceof Error?e.message:String(e),r=ws(e),s={provider:"doubao",model:o,operation:n};return r!==null?No(r,`Doubao ${n} failed.`,i.slice(0,500),s):Lo(e,t,`Doubao ${n} failed.`,i.slice(0,500),s)}function QE(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 FE(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 _s=class{constructor(t,n,o,i,r,s){this.model=t;this.timeoutMs=n;this.maxAttempts=o;this.client=s??YE(i,r,n)}model;timeoutMs;maxAttempts;client;async run(t){let{value:n}=await Jt(this.maxAttempts,async()=>{try{return await this.client.uploadFile({filePath:t.localPath,mimeType:t.localMime,fps:t.fps})}catch(i){throw Zc(i,t.signal,"upload",this.model)}});if(!n.id)throw new C("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 C("cancelled","Doubao upload aborted.",{context:{provider:"doubao",model:this.model,operation:"file_poll"}});if(Date.now()>=o)throw new C("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 HE(zE);let r;try{r=await this.client.getFile({id:t})}catch(s){throw Zc(s,n,"file_poll",this.model)}i=(r.status??"").toLowerCase()}if(i==="failed"||i==="error")throw new C("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)}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?Xc.readFileSync(n).toString("base64"):void 0;if(!o)throw new C("invalid_response","Doubao PDF recovery requires the original document bytes.");let i={model:this.model,input:[{role:"user",content:[{type:"input_file",filename:n?ed.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){let{value:i,attempts:r,failedUsage:s}=await Jt(this.maxAttempts,async()=>{let c;try{c=await this.client.createResponse(t,n)}catch(l){throw Zc(l,n,"generate",this.model)}let a=(c.status??"").toLowerCase(),d=QE(c.usage);if(a==="incomplete"){let l=c.incomplete_details?.reason??"unknown";throw l==="max_output_tokens"||l==="length"?new C("truncated","Doubao output was truncated.",{usage:d}):new C("content_filtered",`Doubao response incomplete (reason=${l}).`,{usage:d})}let p=FE(c);if(!p)throw new C("empty_response","Doubao returned an empty response.",{retryable:!0,usage:d});if(o)try{JSON.parse(p)}catch{throw new C("invalid_response","Doubao returned malformed JSON for a structured response.",{retryable:!0,usage:d,context:{provider:"doubao",model:this.model,operation:"generate"}})}return{text:p,usage:d,raw:c}});return{text:i.text,finishReason:"STOP",attempts:r,usage:Gt(s,i.usage),raw:i.raw}}},Wc=class extends Error{constructor(n,o){super(o);this.status=n;this.name="HttpError"}status};function YE(e,t,n){let o=t.replace(/\/$/,""),i={Authorization:`Bearer ${e}`},r=new KE({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 Wc(a.status,d.slice(0,500))}return{async uploadFile({filePath:a,mimeType:d,fps:p}){let l=new jE,f=Xc.readFileSync(a);l.append("file",new BE([f],ed.basename(a),{type:d})),l.append("purpose","user_data"),l.append("preprocess_configs[video][fps]",String(p));let u=await Es(`${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 Es(`${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 Es(`${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 Es(`${o}/files/${a}`,{method:"DELETE",headers:i,signal:s(),dispatcher:r});d.ok||await c(d)}}}import{GoogleAuth as qE}from"google-auth-library";function xs(){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 Nu=new qE({scopes:["https://www.googleapis.com/auth/cloud-platform"]});import*as Vu from"node:fs";import{createRequire as i_}from"node:module";import*as Ss from"node:fs";import*as ZE from"node:http";import*as WE from"node:https";import{HttpsProxyAgent as XE}from"https-proxy-agent";var Pu="https://generativelanguage.googleapis.com";function e_(e,t){let n=new URL(e??Pu);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/upload/v1beta/files`,n.searchParams.set("key",t),n}function t_(e,t){let n=new URL(t??Pu),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 gi(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 n_(e){return e?new XE(e):void 0}function Uu(e,t,n,o){return new Promise((i,r)=>{let c=(e.protocol==="http:"?ZE:WE).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 o_(e,t){let n=e[t];return Array.isArray(n)?n[0]??"":n??""}async function Cu(e){let t=Ss.statSync(e.filePath).size,o={agent:n_(e.proxyUrl??""),timeout:e.timeoutMs},i=e_(e.baseUrl,e.apiKey),r=l=>gi(l,e.apiKey),s;try{s=await Uu(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 Lo(l,e.signal,"Gemini upload start failed.",f,{operation:"upload"})}let c=o_(s.headers,"x-goog-upload-url");if(s.status<200||s.status>=300)throw No(s.status,"Gemini upload start failed.",r(s.body).slice(0,300),{operation:"upload"});if(!c)throw new C("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=t_(c,e.baseUrl),d;try{d=await Uu(a,{...o,method:"POST",headers:{"Content-Length":String(t),"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"}},Ss.createReadStream(e.filePath),e.signal)}catch(l){let f=r(l instanceof Error?l.message:String(l));throw Lo(l,e.signal,"Gemini upload transfer failed.",f,{operation:"upload"})}if(d.status<200||d.status>=300)throw No(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 C("invalid_response","Gemini upload returned invalid JSON.",{details:[r(d.body).slice(0,300)]})}if(!p.file)throw new C("invalid_response","Gemini upload returned no file.",{details:[r(d.body).slice(0,300)]});return p.file}var r_=new Set(["SAFETY","PROHIBITED_CONTENT","RECITATION","BLOCKLIST","SPII","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION"]),s_=new Set(["LANGUAGE","OTHER","MALFORMED_FUNCTION_CALL","IMAGE_OTHER","NO_IMAGE","UNEXPECTED_TOOL_CALL","TOO_MANY_TOOL_CALLS","MISSING_THOUGHT_SIGNATURE","MALFORMED_RESPONSE"]);function td(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 Tu(e){if(e?.length)return e.map(t=>({category:t.category??"UNSPECIFIED",probability:t.probability??"UNSPECIFIED",blocked:t.blocked??!1}))}function a_(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 c_(e){return/-c\d+$/.test(e)}function d_(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 p_=2e3;function l_(e){return new Promise(t=>setTimeout(t,e))}function nd(e,t,n,o,i,r){if(e instanceof C)return new C(e.code,gi(e.message,o),{retryable:e.retryable,details:e.details.map(d=>gi(d,o)),attempts:e.attempts,usage:e.usage,classification:ei(e.failure),context:{...Qi(e.failure),provider:i,model:r,operation:n},modelFailures:e.modelFailures});let s=gi(e instanceof Error?e.message:String(e),o),c=ws(e),a={provider:i,model:r,operation:n};return c!==null?No(c,`Gemini ${n} failed.`,s.slice(0,500),a):Lo(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??f_(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:Vu.readFileSync(t,"base64"),mimeType:n}:{kind:"file-api",file:await this.uploadFile(t,n,i)}}async uploadFile(t,n,o){let{value:i}=await Jt(this.provider.maxAttempts,async()=>{try{return await this.client.files.upload({file:t,config:{mimeType:n}})}catch(s){throw nd(s,o,"upload",this.apiKey,this.model.provider,this.model.model)}}),r=await this.pollActive(i,o);if(!r.name||!r.uri)throw new C("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 C("cancelled","Gemini upload aborted.",{context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});if(Date.now()>=i)throw new C("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 l_(p_),!o.name)throw new C("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 nd(r,n,"file_poll",this.apiKey,this.model.provider,this.model.model)}}if((o.state??"").toUpperCase()==="FAILED")throw new C("invalid_response","Gemini file processing failed.",{details:[gi(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&&c_(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 Qu(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 E("changelog accepts at most one version argument.",{exitCode:G,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 E("--unreleased cannot combine with version, --from, or --to.",{exitCode:G,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 E("A version argument cannot combine with --from or --to.",{exitCode:G,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=Ms(jx);return[{text:d,data:{content:d,versions:[],unreleased:!0}},J]}let s=Hx(),c=zx();if(n){if(Ir(n),!s.includes(n))throw id(n,s);let d=Ms(n);return[{text:d,data:{content:d,versions:[n],unreleased:!1}},J]}if(o||i){if(!o)throw new E("--from is required for range queries.",{exitCode:G,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>"]}});Ir(o);let d=i||c;if(Ir(d),!s.includes(d))throw id(d,s);let p=s.filter(f=>rd(f,o)>0&&rd(f,d)<=0);if(p.length===0)throw Qx(o,d);let l=Fx(p);return[{text:l,data:{content:l,versions:p,from:o,to:d,unreleased:!1}},J]}if(!s.includes(c))throw id(c,s);let a=Ms(c);return[{text:a,data:{content:a,versions:[c],unreleased:!1}},J]}import*as Vt from"node:fs";import*as Qo from"node:path";import{createRequire as Z_}from"node:module";import*as Dn from"node:fs";import*as po from"node:path";import*as Yu from"node:os";import{fileURLToPath as Yx}from"node:url";function Fu(e){return e.startsWith("~")?po.join(Yu.homedir(),e.slice(1)):e}function qx(e){let t=Dn.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 ad(){let e=[],t=(process.env.SCRIPTCTL_ENV_FILE??"").trim();t&&e.push(Fu(t));let n=(process.env.SCRIPTCTL_SKILL_DIR??"").trim();n&&e.push(po.join(Fu(n),".env"));let o;try{o=Yx(import.meta.url)}catch{o=process.cwd()}let i=po.resolve(o),r=new Set;for(;;){let s=po.dirname(i);if(s===i||r.has(s))break;r.add(s),e.push(po.join(s,".env")),i=s}return e}function qu(){let e=process.env.SCRIPTCTL_NO_DOTENV;if(e==="1"||e==="true"||e==="True")return;let t=new Set;for(let n of ad()){let o;try{o=Dn.existsSync(n)?Dn.realpathSync(n):n}catch{o=n}t.has(o)||!Dn.existsSync(n)||!Dn.statSync(n).isFile()||(t.add(o),qx(n))}}var pe=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 cd(e,t){if(e.updateEpisodeCount)try{await e.updateEpisodeCount(t)}catch{}}function Zu(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 br from"node:fs";import*as Xu from"node:os";import*as Ar from"node:path";import{parseDocument as Zx}from"yaml";function oe(e,t,n){return{id:e,mode:t,version:"1",maxOutputTokens:n,defaultProfile:"default"}}var xn={"direct.episode-titles":oe("direct.episode-titles","tool",4096),"direct.batch-extract":oe("direct.batch-extract","text",16e3),"direct.episode-synopsis":oe("direct.episode-synopsis","tool",2048),"direct.synopsis-reduction":oe("direct.synopsis-reduction","tool",4096),"direct.script-synopsis":oe("direct.script-synopsis","tool",2048),"direct.asset-grouping":oe("direct.asset-grouping","text",8e3),"direct.asset-curation":oe("direct.asset-curation","text",2e4),"direct.asset-curation-audit":oe("direct.asset-curation-audit","text",2e4),"direct.location-canonicalization":oe("direct.location-canonicalization","text",2e4),"direct.state-curation":oe("direct.state-curation","text",2e4),"direct.state-binding":oe("direct.state-binding","tool",16e3),"metadata.global":oe("metadata.global","text",16e3),"metadata.descriptions":oe("metadata.descriptions","text",16e3),"synopsis.chunk":oe("synopsis.chunk","text",4096),"synopsis.episode":oe("synopsis.episode","text",4096),"synopsis.arc":oe("synopsis.arc","text",16e3),"synopsis.script-overview":oe("synopsis.script-overview","text",16e3),"ingest.body-start":oe("ingest.body-start","text",16e3),"ingest.arc-summary":oe("ingest.arc-summary","text",4096),"ingest.text-normalize":oe("ingest.text-normalize","text",32e3),"ingest.episode-assets":oe("ingest.episode-assets","tool",32e3),"ingest.name-fix":oe("ingest.name-fix","tool",16e3),"ingest.mention-resolve":oe("ingest.mention-resolve","text",8e3),"ingest.asset-extract":oe("ingest.asset-extract","text",8e3),"ingest.asset-curate":oe("ingest.asset-curate","text",32e3),"ingest.asset-recall":oe("ingest.asset-recall","text",65536),"ingest.asset-refine":oe("ingest.asset-refine","text",32e3),"ingest.state-reconcile":oe("ingest.state-reconcile","text",32e3),"ingest.asset-audit":oe("ingest.asset-audit","tool",32e3),"ingest.speaker-audit":oe("ingest.speaker-audit","tool",16e3),"ingest.comic-serial":{id:"ingest.comic-serial",mode:"document",version:"1",defaultProfile:"default"},"ingest.video-serial":oe("ingest.video-serial","video",65536)},Wu=Object.keys(xn).filter(dd);function dd(e){return Object.hasOwn(xn,e)}var Wx=new Set(["protocol","baseUrl","apiKey","timeoutMs","maxAttempts","videoResponseSchemaField","videoUploadMode","documentResponseSchemaField","documentUploadMode"]),Xx=new Set(["provider","model","thinking","reasoning","temperature"]),e_=new Set(["env"]),t_=new Set(["budgetTokens"]);function Ue(e,t=[]){return new E(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 Ue(`${t} must be an absolute URL.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Ue(`${t} must use http or https.`);return n.toString().replace(/\/$/,"")}function fd(e,t="provider base URL"){return ud(e,t)}function n_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function lo(e,t){if(!n_(e))throw Ue(`${t} must be a mapping.`,[`${t}: ${typeof e}`]);return e}function Ko(e,t){if(typeof e!="string"||!e.trim())throw Ue(`${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 Ue(`${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 Ue(`${n} contains unknown fields.`,o)}function o_(e,t){let n=lo(t,`providers.${e}`);kr(n,Wx,`providers.${e}`);let o=Ko(n.protocol,`providers.${e}.protocol`);if(o!=="anthropic"&&o!=="openai-compatible"&&o!=="google-gemini"&&o!=="google-vertex")throw Ue(`providers.${e}.protocol is unsupported.`,[o]);let i=n.baseUrl===void 0&&o!=="openai-compatible"?null:ud(Ko(n.baseUrl,`providers.${e}.baseUrl`),`providers.${e}.baseUrl`),r="";if(o!=="google-vertex"){let c=lo(n.apiKey,`providers.${e}.apiKey`);if(kr(c,e_,`providers.${e}.apiKey`),r=Ko(c.env,`providers.${e}.apiKey.env`),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw Ue(`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 Ue(`providers.${e}.${c} requires a Gemini ${c.startsWith("video")?"video":"document"} provider.`);if(a!=="responseJsonSchema"&&a!=="responseSchema")throw Ue(`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 Ue(`providers.${e}.${c} requires a Gemini ${c.startsWith("video")?"video":"document"} provider.`);if(a!=="file-api"&&a!=="base64")throw Ue(`providers.${e}.${c} must be file-api or base64.`);s[c]=a}}return s}function i_(e,t,n){let o=lo(t,`models.${e}`);kr(o,Xx,`models.${e}`);let i=Ko(o.provider,`models.${e}.provider`),r=n[i];if(!r)throw Ue(`models.${e} references an unknown provider.`,[i]);let s={provider:i,model:Ko(o.model,`models.${e}.model`)};if(o.reasoning!==void 0&&(s.reasoning=Ko(o.reasoning,`models.${e}.reasoning`)),o.temperature!==void 0){let c=o.temperature;if(typeof c!="number"||!Number.isFinite(c)||c<0)throw Ue(`models.${e}.temperature must be a number \u2265 0.`);s.temperature=c}if(o.thinking!==void 0){if(r.protocol!=="anthropic")throw Ue(`models.${e}.thinking is only valid for anthropic providers.`);let c=lo(o.thinking,`models.${e}.thinking`);kr(c,t_,`models.${e}.thinking`),s.thinkingBudgetTokens=ld(c.budgetTokens,`models.${e}.thinking.budgetTokens`,1024)}return s}function r_(e,t){let n=lo(e,"config");if(kr(n,new Set(["version","providers","models","tasks"]),"config"),n.version!==1)throw Ue("config.version must be 1.");let o=lo(n.providers,"providers"),i={};for(let[a,d]of Object.entries(o))i[a]=o_(a,d);let r=lo(n.models,"models"),s={};for(let[a,d]of Object.entries(r))s[a]=i_(a,d,i);if(!s.default)throw Ue("models.default is required.");let c={};if(n.tasks!==void 0){let a=lo(n.tasks,"tasks");for(let[d,p]of Object.entries(a)){if(!dd(d))throw Ue("tasks contains an unknown task id.",[d]);let l=Ko(p,`tasks.${d}`);if(!s[l])throw Ue(`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 Oi={version:1,providers:{gw:{protocol:"openai-compatible",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},"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}},tasks:{"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 s_(){let e=(process.env.PROJECT_LITELLM_GATEWAY_BASE_URL??"").trim(),t=e?ud(e,"PROJECT_LITELLM_GATEWAY_BASE_URL"):null;return{...Oi,providers:{gw:{...Oi.providers.gw,baseUrl:t},"google-gemini":{...Oi.providers["google-gemini"]},nnyyai:{...Oi.providers.nnyyai}},models:{...Oi.models},tasks:{...Oi.tasks}}}function a_(){let e=(process.env.XDG_CONFIG_HOME??"").trim();return e?Ar.join(e,"scriptctl","llm.yaml"):Ar.join(Xu.homedir(),".config","scriptctl","llm.yaml")}function pd(e){if(!br.existsSync(e))throw Ue("LLM configuration file does not exist.",[e]);let t=Zx(br.readFileSync(e,"utf-8"),{uniqueKeys:!0});if(t.errors.length>0)throw Ue("LLM configuration YAML is invalid.",t.errors.map(o=>o.message));let n=t.toJS();return r_(n,Ar.resolve(e))}function vi(e){let t=(e??"").trim();if(t)return pd(t);let n=(process.env.SCRIPTCTL_LLM_CONFIG??"").trim();if(n)return pd(n);let o=a_();return br.existsSync(o)?pd(o):s_()}import*as mf from"node:crypto";import*as gf from"node:fs";import p_,{APIConnectionError as l_,APIConnectionTimeoutError as u_,APIError as f_,APIUserAbortError as m_}from"@anthropic-ai/sdk";var md=1e8;function c_(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 P=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=Rt(o.classification??c_(t),{retryable:this.retryable,message:n,...o.context,...this.details.length>0?{details:this.details}:{}}),this.modelFailures=o.modelFailures??[]}};function d_(e){return new Promise(t=>setTimeout(t,e))}function Ft(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 Yt(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 P&&(n=Ft(n,i.usage),i.attempts=o,i.usage=n),!(i instanceof P)||!i.retryable||o===e)throw i;await d_(Math.min(3e4,1e3*2**(o-1)))}throw new Error("unreachable retry state")}function ef(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 tf(e){if(e instanceof P)return e;if(e instanceof m_)return new P("request_failed","Anthropic request was aborted.");if(e instanceof u_)return new P("timeout","Anthropic request timed out.",{retryable:!0});if(e instanceof l_)return new P("request_failed","Anthropic connection failed.",{retryable:!0,details:[e.message.slice(0,500)]});if(e instanceof f_){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 P(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 P("request_failed","Anthropic request failed.",{details:[t.slice(0,500)]})}var Ns=class{constructor(t,n,o){this.provider=t;this.model=n;let i={apiKey:o};t.baseUrl&&(i.baseURL=t.baseUrl),this.client=new p_({...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 Yt(this.provider.maxAttempts,async()=>{try{let o=await this.client.messages.create(this.params(t),{timeout:this.provider.timeoutMs,signal:t.signal}),i=ef(o);if(o.stop_reason==="max_tokens")throw new P("truncated","Provider output was truncated.",{usage:i});if(o.stop_reason==="refusal")throw new P("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 P("empty_response","Provider returned an empty text response.",{usage:i});return{text:r,finishReason:o.stop_reason??"",usage:i,raw:o}}catch(o){throw tf(o)}});return{...n.value,attempts:n.attempts,usage:Ft(n.failedUsage,n.value.usage)}}async generateTool(t){let n=await Yt(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=ef(i);if(i.stop_reason==="max_tokens")throw new P("truncated","Provider tool output was truncated.",{usage:r});if(i.stop_reason==="refusal")throw new P("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 P("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 tf(o)}});return{...n.value,attempts:n.attempts,usage:Ft(n.failedUsage,n.value.usage)}}};import*as wd from"node:fs";import*as xd from"node:path";import{File as __}from"node:buffer";import{Agent as E_,fetch as Cs,FormData as S_}from"undici";function g_(e){return typeof e=="object"&&e!==null}function gd(e){let t=[],n=new Set,o=e;for(;g_(o)&&!n.has(o);)n.add(o),t.push(o),o=o.cause;return t}function Us(e){for(let t of gd(e)){if(typeof t.status=="number")return t.status;if(typeof t.statusCode=="number")return t.statusCode}return null}function h_(e){for(let t of gd(e))if(typeof t.code=="string")return t.code}function y_(e){for(let t of gd(e))if(typeof t.name=="string")return t.name}function w_(e){let t=y_(e);return t==="AbortError"||t==="TimeoutError"||t==="RequestTimeoutError"||t==="APIConnectionTimeoutError"}function x_(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 jo(e,t,n,o,i={}){if(t?.aborted)return new P("cancelled",n,{details:[o],classification:{failure_type:"cancelled",failure_code:"cancelled"},context:i});let r=h_(e),s=w_(e)?{failure_type:"timeout",failure_code:"request_timeout"}:x_(r),c=s.failure_type==="timeout"?"timeout":"network";return new P(c,n,{retryable:!0,details:[o],classification:s,context:{...i,...r?{system_code:r}:{}}})}function zo(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 P(i,t,{retryable:s,details:[`status: ${e}`,n],classification:r,context:{...o,http_status:e}})}var I_=2e3;function A_(e){return new Promise(t=>setTimeout(t,e))}function hd(e,t,n,o){if(e instanceof P)return e;let i=e instanceof Error?e.message:String(e),r=Us(e),s={provider:"doubao",model:o,operation:n};return r!==null?zo(r,`Doubao ${n} failed.`,i.slice(0,500),s):jo(e,t,`Doubao ${n} failed.`,i.slice(0,500),s)}function k_(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 b_(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 Ps=class{constructor(t,n,o,i,r,s){this.model=t;this.timeoutMs=n;this.maxAttempts=o;this.client=s??O_(i,r,n)}model;timeoutMs;maxAttempts;client;async run(t){let{value:n}=await Yt(this.maxAttempts,async()=>{try{return await this.client.uploadFile({filePath:t.localPath,mimeType:t.localMime,fps:t.fps})}catch(i){throw hd(i,t.signal,"upload",this.model)}});if(!n.id)throw new P("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 P("cancelled","Doubao upload aborted.",{context:{provider:"doubao",model:this.model,operation:"file_poll"}});if(Date.now()>=o)throw new P("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 A_(I_);let r;try{r=await this.client.getFile({id:t})}catch(s){throw hd(s,n,"file_poll",this.model)}i=(r.status??"").toLowerCase()}if(i==="failed"||i==="error")throw new P("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)}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?wd.readFileSync(n).toString("base64"):void 0;if(!o)throw new P("invalid_response","Doubao PDF recovery requires the original document bytes.");let i={model:this.model,input:[{role:"user",content:[{type:"input_file",filename:n?xd.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){let{value:i,attempts:r,failedUsage:s}=await Yt(this.maxAttempts,async()=>{let c;try{c=await this.client.createResponse(t,n)}catch(l){throw hd(l,n,"generate",this.model)}let a=(c.status??"").toLowerCase(),d=k_(c.usage);if(a==="incomplete"){let l=c.incomplete_details?.reason??"unknown";throw l==="max_output_tokens"||l==="length"?new P("truncated","Doubao output was truncated.",{usage:d}):new P("content_filtered",`Doubao response incomplete (reason=${l}).`,{usage:d})}let p=b_(c);if(!p)throw new P("empty_response","Doubao returned an empty response.",{retryable:!0,usage:d});if(o)try{JSON.parse(p)}catch{throw new P("invalid_response","Doubao returned malformed JSON for a structured response.",{retryable:!0,usage:d,context:{provider:"doubao",model:this.model,operation:"generate"}})}return{text:p,usage:d,raw:c}});return{text:i.text,finishReason:"STOP",attempts:r,usage:Ft(s,i.usage),raw:i.raw}}},yd=class extends Error{constructor(n,o){super(o);this.status=n;this.name="HttpError"}status};function O_(e,t,n){let o=t.replace(/\/$/,""),i={Authorization:`Bearer ${e}`},r=new E_({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 yd(a.status,d.slice(0,500))}return{async uploadFile({filePath:a,mimeType:d,fps:p}){let l=new S_,f=wd.readFileSync(a);l.append("file",new __([f],xd.basename(a),{type:d})),l.append("purpose","user_data"),l.append("preprocess_configs[video][fps]",String(p));let u=await Cs(`${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 Cs(`${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 Cs(`${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 Cs(`${o}/files/${a}`,{method:"DELETE",headers:i,signal:s(),dispatcher:r});d.ok||await c(d)}}}import{GoogleAuth as v_}from"google-auth-library";function Ts(){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 nf=new v_({scopes:["https://www.googleapis.com/auth/cloud-platform"]});import*as cf from"node:fs";import{createRequire as T_}from"node:module";import*as Vs from"node:fs";import*as R_ from"node:http";import*as M_ from"node:https";import{HttpsProxyAgent as L_}from"https-proxy-agent";var rf="https://generativelanguage.googleapis.com";function N_(e,t){let n=new URL(e??rf);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/upload/v1beta/files`,n.searchParams.set("key",t),n}function U_(e,t){let n=new URL(t??rf),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 Ri(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 C_(e){return e?new L_(e):void 0}function of(e,t,n,o){return new Promise((i,r)=>{let c=(e.protocol==="http:"?R_:M_).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 P_(e,t){let n=e[t];return Array.isArray(n)?n[0]??"":n??""}async function sf(e){let t=Vs.statSync(e.filePath).size,o={agent:C_(e.proxyUrl??""),timeout:e.timeoutMs},i=N_(e.baseUrl,e.apiKey),r=l=>Ri(l,e.apiKey),s;try{s=await of(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 jo(l,e.signal,"Gemini upload start failed.",f,{operation:"upload"})}let c=P_(s.headers,"x-goog-upload-url");if(s.status<200||s.status>=300)throw zo(s.status,"Gemini upload start failed.",r(s.body).slice(0,300),{operation:"upload"});if(!c)throw new P("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=U_(c,e.baseUrl),d;try{d=await of(a,{...o,method:"POST",headers:{"Content-Length":String(t),"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"}},Vs.createReadStream(e.filePath),e.signal)}catch(l){let f=r(l instanceof Error?l.message:String(l));throw jo(l,e.signal,"Gemini upload transfer failed.",f,{operation:"upload"})}if(d.status<200||d.status>=300)throw zo(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 P("invalid_response","Gemini upload returned invalid JSON.",{details:[r(d.body).slice(0,300)]})}if(!p.file)throw new P("invalid_response","Gemini upload returned no file.",{details:[r(d.body).slice(0,300)]});return p.file}var V_=new Set(["SAFETY","PROHIBITED_CONTENT","RECITATION","BLOCKLIST","SPII","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION"]),$_=new Set(["LANGUAGE","OTHER","MALFORMED_FUNCTION_CALL","IMAGE_OTHER","NO_IMAGE","UNEXPECTED_TOOL_CALL","TOO_MANY_TOOL_CALLS","MISSING_THOUGHT_SIGNATURE","MALFORMED_RESPONSE"]);function _d(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 af(e){if(e?.length)return e.map(t=>({category:t.category??"UNSPECIFIED",probability:t.probability??"UNSPECIFIED",blocked:t.blocked??!1}))}function D_(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 G_(e){return/-c\d+$/.test(e)}function J_(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 B_=2e3;function K_(e){return new Promise(t=>setTimeout(t,e))}function Ed(e,t,n,o,i,r){if(e instanceof P)return new P(e.code,Ri(e.message,o),{retryable:e.retryable,details:e.details.map(d=>Ri(d,o)),attempts:e.attempts,usage:e.usage,classification:mi(e.failure),context:{...sr(e.failure),provider:i,model:r,operation:n},modelFailures:e.modelFailures});let s=Ri(e instanceof Error?e.message:String(e),o),c=Us(e),a={provider:i,model:r,operation:n};return c!==null?zo(c,`Gemini ${n} failed.`,s.slice(0,500),a):jo(e,t,`Gemini ${n} failed.`,s.slice(0,500),a)}var Mi=class{constructor(t,n,o,i){this.provider=t;this.model=n;this.apiKey=o;this.client=i??z_(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 Yt(this.provider.maxAttempts,async()=>{try{return await this.client.files.upload({file:t,config:{mimeType:n}})}catch(s){throw Ed(s,o,"upload",this.apiKey,this.model.provider,this.model.model)}}),r=await this.pollActive(i,o);if(!r.name||!r.uri)throw new P("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 P("cancelled","Gemini upload aborted.",{context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});if(Date.now()>=i)throw new P("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 K_(B_),!o.name)throw new P("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 Ed(r,n,"file_poll",this.apiKey,this.model.provider,this.model.model)}}if((o.state??"").toUpperCase()==="FAILED")throw new P("invalid_response","Gemini file processing failed.",{details:[Ri(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&&G_(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,130 +150,132 @@ ${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 Jt(this.provider.maxAttempts,async()=>{let p;try{if(this.client.models.generateContentStream){let w="",y={},E=await this.client.models.generateContentStream(s);for await(let I of E)I.text&&(w+=I.text),y={...y,...I,usageMetadata:I.usageMetadata??y.usageMetadata,promptFeedback:I.promptFeedback??y.promptFeedback,candidates:I.candidates??y.candidates};p={...y,text:w}}else p=await this.client.models.generateContent(s)}catch(w){throw nd(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=a_(p.usageMetadata),m={provider:this.model.provider,model:this.model.model,operation:"generate"};if(f==="MAX_TOKENS")throw new C("truncated","Gemini output was truncated.",{usage:g,context:m});if(u)throw new C("content_filtered",`Gemini blocked the prompt (blockReason=${u}).`,{usage:g,classification:{failure_type:"policy",failure_code:"content_blocked"},context:{...m,provider_source:"prompt",provider_reason:td(u),...td(u)==="UNKNOWN"?{provider_reason_raw:u}:{},safety_ratings:Tu(p.promptFeedback?.safetyRatings)}});if(r_.has(f))throw new C("content_filtered",`Gemini filtered the response (finishReason=${f}).`,{usage:g,classification:{failure_type:"policy",failure_code:"content_blocked"},context:{...m,provider_source:"candidate",provider_reason:td(f),finish_message:l?.finishMessage,safety_ratings:Tu(l?.safetyRatings)}});let h=(p.text??"").trim();if(!h)throw s_.has(f)?new C("invalid_response",`Gemini returned no usable response (finishReason=${f}).`,{usage:g,context:{...m,provider_reason_raw:f,finish_message:l?.finishMessage}}):new C("empty_response",`Gemini returned an empty response (finishReason=${f||"none"}).`,{retryable:!0,usage:g,context:m});if(t.responseJsonSchema)try{let w=o?d_(h):h;return JSON.parse(w),{text:w,finishReason:f,usage:g,raw:p}}catch{throw new C("invalid_response","Gemini returned malformed JSON for a structured media response.",{retryable:!0,usage:g,context:m})}return{text:h,finishReason:f,usage:g,raw:p}});return{text:c.text,finishReason:c.finishReason,attempts:a,usage:Gt(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){}}},u_=i_(import.meta.url);function f_(e,t,n,o){let{GoogleGenAI:i}=u_("@google/genai"),r=new i({...o?{vertexai:!0,project:xs(),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 Yt(this.provider.maxAttempts,async()=>{let p;try{if(this.client.models.generateContentStream){let w="",y={},x=await this.client.models.generateContentStream(s);for await(let S of x)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 Ed(w,t.signal,"generate",this.apiKey,this.model.provider,this.model.model)}let l=p.candidates?.[0],f=l?.finishReason??"",u=p.promptFeedback?.blockReason??"",h=D_(p.usageMetadata),m={provider:this.model.provider,model:this.model.model,operation:"generate"};if(f==="MAX_TOKENS")throw new P("truncated","Gemini output was truncated.",{usage:h,context:m});if(u)throw new P("content_filtered",`Gemini blocked the prompt (blockReason=${u}).`,{usage:h,classification:{failure_type:"policy",failure_code:"content_blocked"},context:{...m,provider_source:"prompt",provider_reason:_d(u),..._d(u)==="UNKNOWN"?{provider_reason_raw:u}:{},safety_ratings:af(p.promptFeedback?.safetyRatings)}});if(V_.has(f))throw new P("content_filtered",`Gemini filtered the response (finishReason=${f}).`,{usage:h,classification:{failure_type:"policy",failure_code:"content_blocked"},context:{...m,provider_source:"candidate",provider_reason:_d(f),finish_message:l?.finishMessage,safety_ratings:af(l?.safetyRatings)}});let g=(p.text??"").trim();if(!g)throw $_.has(f)?new P("invalid_response",`Gemini returned no usable response (finishReason=${f}).`,{usage:h,context:{...m,provider_reason_raw:f,finish_message:l?.finishMessage}}):new P("empty_response",`Gemini returned an empty response (finishReason=${f||"none"}).`,{retryable:!0,usage:h,context:m});if(t.responseJsonSchema)try{let w=o?J_(g):g;return JSON.parse(w),{text:w,finishReason:f,usage:h,raw:p}}catch{throw new P("invalid_response","Gemini returned malformed JSON for a structured media response.",{retryable:!0,usage:h,context:m})}return{text:g,finishReason:f,usage:h,raw:p}});return{text:c.text,finishReason:c.finishReason,attempts:a,usage:Ft(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){}}},j_=T_(import.meta.url);function z_(e,t,n,o){let{GoogleGenAI:i}=j_("@google/genai"),r=new i({...o?{vertexai:!0,project:Ts(),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=>Cu({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 mr=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 Is=class extends hi{generate(t){let n=t.media;if(n.kind==="local-fallback"||n.kind==="local")throw new C("invalid_response","A local fallback video cannot be sent to Gemini.");return this.generateMedia({...t,media:n},{fps:t.fps})}};function $u(e,t){if(!Rn(e)||!Rn(e.usage))return{};let n=e.usage,o=a=>{let d=typeof a=="number"?a:0;return Number.isFinite(d)?d:0},i=Rn(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 Rn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function m_(e){let t=e.trim().replace(/\/+$/,"");return t.endsWith("/chat/completions")?t:t.endsWith("/v1")?`${t}/chat/completions`:`${t}/v1/chat/completions`}function Du(e){return!Rn(e)||!Array.isArray(e.choices)?null:e.choices.find(Rn)??null}function Gu(e){return e&&typeof e.finish_reason=="string"?e.finish_reason:""}function Bu(e){return e&&Rn(e.message)?e.message:null}function g_(e){let t=Bu(e)?.content;return typeof t=="string"?t.trim():Array.isArray(t)?t.flatMap(n=>Rn(n)&&typeof n.text=="string"?[n.text]:[]).join(`
157
- `).trim():""}function Ju(e){try{return JSON.parse(e)}catch{throw new C("invalid_response","Provider returned invalid JSON.",{details:[e.slice(0,500)]})}}var As=class{constructor(t,n,o){this.provider=t;this.model=n;this.apiKey=o;if(!t.baseUrl&&t.protocol!=="google-vertex")throw new C("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/${xs()}/locations/global/endpoints/openapi/chat/completions`:m_(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 Jt(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 Nu.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 C(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 C(d,`OpenAI-compatible request to ${this.host} failed (status ${s.status}).`,{retryable:a,details:[`status: ${s.status}`,c.slice(0,500)]})}return Ju(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=Gt(i,$u(n,this.provider.protocol==="google-vertex"));try{let s=Du(n),c=Gu(s);if(c==="length")throw new C("truncated","Provider output was truncated.");if(c==="content_filter"||c.startsWith("content_filter:"))throw new C("content_filtered",`Provider filtered the response (${c}).`);let a=g_(s);if(!a)throw new C("empty_response","Provider returned an empty text response.");return{text:a,finishReason:c,attempts:o,usage:r,raw:n}}catch(s){throw s instanceof C&&(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=Gt(i,$u(n,this.provider.protocol==="google-vertex"));try{let s=Du(n),c=Gu(s);if(c==="length")throw new C("truncated","Provider tool output was truncated.");if(c==="content_filter"||c.startsWith("content_filter:"))throw new C("content_filtered",`Provider filtered the response (${c}).`);let a=Bu(s)?.tool_calls;if(!Array.isArray(a))throw new C("invalid_response","Provider did not return a tool call.");for(let d of a){if(!Rn(d)||!Rn(d.function))continue;let p=d.function;if(!(p.name!==t.tool.name||typeof p.arguments!="string"))return{input:Ju(p.arguments),finishReason:c,attempts:o,usage:r,raw:n}}throw new C("invalid_response","Provider did not return the required tool call.")}catch(s){throw s instanceof C&&(s.attempts=o,s.usage=r),s}}};var ln={model:"ep-20260721150136-98dj9",modelEnv:"ARK_MODEL",baseUrl:"https://ark.cn-beijing.volces.com/api/v3",apiKeyEnv:"ARK_API_KEY",timeoutMs:6e5,maxAttempts:3},h_=["gemini-3.8-flash","gemini-3.7-flash","gemini-3.6-flash"];function y_(e){return e?.trim().replace(/\/+$/,"")??"anthropic-sdk-default"}function id(e,t,n){let o=pn[e],i=JSON.stringify({task:e,taskVersion:o.version,protocol:t.protocol,baseUrl:y_(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 Ku.createHash("sha256").update(i).digest("hex")}function De(e,t,n){return new x(e,{exitCode:b,errorCode:"LLM_CONFIG_INVALID",hint:"Fix the selected LLM configuration and run `scriptctl doctor`.",data:{expected:t,actual:n}})}function yi(e){return new x("The selected LLM provider credential is not configured.",{exitCode:me,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 Uo(e,t){return St(ei(e.failure),{...Qi(e.failure),provider:t.provider,model:t.model,retryable:e.failure.retryable,message:e.message})}function wi(e,t){if(t.length===1)return e;let n=pl(t,"All configured model routes failed.");return new C(e.code,n.message,{retryable:n.retryable,classification:ei(n),context:Qi(n),modelFailures:t,details:t.map(tn)})}function w_(e){return["google-gemini","google-vertex"].includes(e.protocol)||/(^|\/)gemini-/i.test(e.model)}function od(e){let t=e.info.model.slice(0,e.info.model.lastIndexOf("/")+1);return[...new Set([e.info.model,...h_.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:id(e.info.task,e.providerConfig,i)}}})}function Wn(e,t){return!t?.aborted&&e instanceof C&&e.code!=="cancelled"}var gr=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=pn[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 De("The task route references a missing model profile.",[i],[`task: ${t}`]);let s=this.config.providers[r.provider];if(!s)throw De("The model profile references a missing provider.",[r.provider],[`profile: ${i}`]);if(s.protocol==="openai-compatible"&&!s.baseUrl)throw De("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 De("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 De("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:Fc(c.baseUrl,"--provider-base-url")}:s,d=c?.model?{...r,model:c.model.trim()}:r;if(c?.model!==void 0&&!d.model)throw De("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:id(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 vu.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 C?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 De("Doubao requires --provider-model or ARK_MODEL.",["--provider-model <id> or ARK_MODEL"],["model: empty"]);let r={protocol:"openai-compatible",baseUrl:o?.baseUrl?Fc(o.baseUrl,"--provider-base-url"):ln.baseUrl,apiKeyEnv:ln.apiKeyEnv,timeoutMs:ln.timeoutMs,maxAttempts:ln.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:id(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 yi(t.info.provider);let r=t.providerConfig.protocol==="anthropic"?new ys(t.providerConfig,t.modelConfig,i):new As(t.providerConfig,t.modelConfig,i);return this.adapters.set(n,r),r}videoAdapter(t){if(!["google-gemini","google-vertex"].includes(t.providerConfig.protocol))throw De("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 yi(t.info.provider);let s=new Is(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 yi(t.info.provider);return o}documentPort(t){if(pn[t].mode!=="document")throw De("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 De("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 yi(n.info.provider);let i=new mr(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(!Wn(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 (${tn(d.failure)})
158
- `),a={kind:"base64",data:ju.readFileSync(s).toString("base64"),mimeType:"application/pdf"}}return r.set(a,s),a},generate:async s=>{let c=od(n),a=[];for(let[d,p]of c.entries()){s.signal?.throwIfAborted();let l=d===0?i:new mr(p.providerConfig,p.modelConfig,o);try{return await this.tracked(p.info,()=>l.generate(s))}catch(f){if(!Wn(f,s.signal))throw f;let u=Uo(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} (${tn(u)})
159
- `);continue}let m=this.arkAdapter();if(!m)throw wi(f,a);let h=this.doubaoRoute(t);process.stderr.write(`\u21AA\uFE0F \u6587\u6863\u6A21\u578B\u8DEF\u7531\u5DF2\u8017\u5C3D\uFF0C\u56DE\u9000\u5230\u8C46\u5305 ${h.model}
160
- `);try{return await this.tracked(h,()=>m.generateDocument(s,r.get(s.media)))}catch(w){throw Wn(w,s.signal)?wi(w,[...a,Uo(w,h)]):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=pn[t];if(n.mode!=="video")throw De("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 yi("doubao");return{prepare:async(s,c,a,d)=>{if(a!=="file-api")throw De("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 De("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.signal?{signal:s.signal}:{}}))},release:async()=>{}}}if(!["google-gemini","google-vertex"].includes(o.providerConfig.protocol))throw De("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(!Wn(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:Uo(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=od(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(!Wn(p,r.signal))throw p;let l=Uo(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} (${tn(l)})
161
- `);continue}if(!this.doubaoAdapter()||!r.localPath)throw wi(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 yi("doubao");let r=n.media.kind==="local-fallback"?n.media.path:n.localPath;if(!r)throw De("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=pn[t];if(c.mode!=="video")throw De("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.signal?{signal:n.signal}:{}}))}catch(d){throw Wn(d,n.signal)?wi(d,[...o,Uo(d,a)]):d}}doubaoAdapter(t){return this.arkAdapter(t)}doubaoTextAdapter(){return this.arkAdapter()}arkAdapter(t){let n=t?this.videoCredential(t):(process.env[ln.apiKeyEnv]??"").trim();if(!n)return null;let o=t?.info.model??this.doubaoModel(),i=t?.providerConfig.baseUrl??ln.baseUrl,r=`doubao ${i} ${o}`,s=this.doubaoAdapters.get(r);if(s)return s;let c=new _s(o,ln.timeoutMs,ln.maxAttempts,n,i);return this.doubaoAdapters.set(r,c),c}doubaoModel(){return(process.env[ln.modelEnv]??"").trim()||ln.model}async withTextFallback(t,n,o){let i=this.resolve(t),r=w_(i.info),s=r?od(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(!Wn(l,n)||!r&&l.code!=="content_filtered")throw l;let f=Uo(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} (${tn(f)})
163
- `);continue}let g=this.doubaoTextAdapter();if(!g)throw wi(l,c);let m=this.doubaoRoute(t);process.stderr.write(`\u21AA\uFE0F \u4E3B\u6A21\u578B\u8DEF\u7531\u5DF2\u8017\u5C3D\uFF0C\u56DE\u9000\u5230\u8C46\u5305 ${m.model}
164
- `);try{return await this.tracked(m,()=>o(g))}catch(h){throw Wn(h,n)?wi(h,[...c,Uo(h,m)]):h}}}throw new Error("Text model routes cannot be empty.")}async generateText(t,n){let o=pn[t];if(o.mode!=="text")throw De("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=pn[t];if(o.mode!=="tool")throw De("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 zu(e,t){return new gr(mi(e),t)}var __=E_(import.meta.url);function ks(e){try{return __.resolve(e),!0}catch{return!1}}function x_(e){let t=!1;try{Mt.statSync(e).isDirectory()&&(Mt.accessSync(e,Mt.constants.W_OK),t=!0)}catch{t=!1}let n=!1;try{n=Mt.statSync(Po.join(e,"script.json")).isFile()}catch{n=!1}return{writable:t,hasScript:n}}function S_(){return Po.join(Po.dirname(Po.resolve("workspace")),"output")}function Hu(e={}){let t=Bc(),n=[],o=new Set;for(let R of t)try{if(!Mt.existsSync(R)||!Mt.statSync(R).isFile())continue;let j=Mt.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=mi(i||void 0),c=new gr(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 Z="not set";if(j.baseUrl)try{Z=new URL(j.baseUrl).host}catch{Z=j.baseUrl}return{alias:R,host:Z}}),{mode:p}=Ou(),l=(process.env.SCRIPTCTL_OUTPUT_DIR??"").trim()||S_(),f=p==="local"?x_(l):null,u=!!process.env.AWB_BASE_URL,g=!!process.env.LINGJING_AWB_ACCESS_KEY,m=!!process.env.SANDBOX_PROJECT_GROUP_NO,h={"@anthropic-ai/sdk":ks("@anthropic-ai/sdk"),"@google/genai":ks("@google/genai"),jszip:ks("jszip"),"fast-xml-parser":ks("fast-xml-parser")},w=Object.entries(h).filter(([,R])=>!R).map(([R])=>R),y=process.versions.node,E=`env_file: ${n[0]??"missing"}`,I=R=>R?"configured":"not configured",A=[`node: ${y}`,"storage: local-filesystem",E,`llm config: ${r.source}`,`llm routes: ${c.length}`,...a.map(R=>`llm provider ${R.alias}: ${I(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: ${I(f.writable)}`),A.push(`output snapshot: ${f.hasScript?"present":"absent"}`)):(A.push(`gateway endpoint: ${I(u)}`),A.push(`gateway access credential: ${I(g)}`),A.push(`gateway project identifier: ${I(m)}`));for(let[R,j]of Object.entries(h))A.push(`dependency ${R}: ${j?"ok":"missing"}`);let k=[];w.length>0&&k.push("Install missing CLI dependencies (see above)."),a.some(R=>!R.configured)&&k.push("Configure every credential referenced by the selected LLM configuration."),d.some(R=>R.host==="not set")&&k.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?k.push("Configure an output target before running `publish` / script CRUD."):p==="local"?f&&!f.writable&&k.push("Output target is not writable; check directory permissions."):(!u||!g||!m)&&k.push("Configure gateway credentials before running `publish` / script CRUD against the remote project."),k.length===0&&k.push("Environment looks ready.");let[P,O]=y.split(".").map(R=>parseInt(R,10)),S=(P??0)>20||(P??0)===20&&(O??0)>=0,L=p===null?{configured:!1}:p==="local"?{dir:{ok:!!f?.writable,writable:!!f?.writable,hasScript:!!f?.hasScript}}:{endpoint:{ok:u},access:{ok:g},project:{ok:m}},T={node:{version:y,ok:S},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:L,dependencies:h};return[{text:[...A,...k].join(`
165
- `),data:{checks:T}},B]}import{spawn as I_}from"node:child_process";var bs="@lingjingai/scriptctl",A_=`${bs}@latest`,rd="npm";function k_(){return ui()}function b_(e){let t=/^(\d+)\.(\d+)\.\d+/.exec(e);return t?`${bs}@~${t[1]}.${t[2]}.0`:null}function O_(e){return["install","-g",e]}function v_(e,t){return[e,...t].join(" ")}function R_(e,t){return e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0).slice(-t)}function M_(e,t){return new Promise(n=>{let o=I_(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 Qu(e,t=M_,n=k_){let o=!!e.patch,i=n(),r=o?b_(i):A_;if(!r)throw new x(`Cannot compute a patch update range from version ${i}.`,{exitCode:me,errorCode:"UPDATE_VERSION_INVALID",hint:"Run `scriptctl update` without --patch to install the latest version.",data:{version:i}});let s=[...O_(r)],c=v_(rd,s),a={package:bs,package_spec:r,command:rd,args:s,command_line:c};if(e.dry_run)return[{text:[`package: ${bs}`,`command: ${c}`,"dry-run: no update performed"].join(`
166
- `),data:{op:"update",changed:!1,update:a}},B];let d=await t(rd,s);if(d.error)throw new x(`Failed to start npm: ${d.error.message}`,{exitCode:me,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)}`,...R_(d.stderr,5).map(u=>`stderr: ${u}`)];throw new x("npm could not update scriptctl.",{exitCode:me,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 Fu(e,t){e.command("doctor").description("Check configuration and runtime dependencies").option("--llm-config <path>","LLM configuration file").action(q(Hu,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(q(Qu,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(q(Iu,t));Ae(n,["Release version"])}import*as hr from"node:fs";import*as vs from"node:path";import{fileURLToPath as L_,pathToFileURL as N_}from"node:url";var U_="review-agent";function P_(e,t){let n=t||U_,o=e.models[n];if(!o)throw new x(`LLM profile "${n}" is not defined.`,{exitCode:b,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:b,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:b,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 Yu(){let e=vs.dirname(L_(import.meta.url)),t=vs.join(e,"review-agent.js"),n=hr.existsSync(t)?N_(t).href:"@lingjingai/review-agent";try{return await import(n)}catch(o){throw new x("The review agent is not installed.",{exitCode:me,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 qu(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:b,errorCode:"REVIEW_EPISODES_INVALID",hint:"For example: --episodes 1,2,5",data:{expected:["1-based episode numbers"],actual:[t]}});return n}function Os(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:b,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 Zu(e){let t=mi(v(e.llm_config).trim()||void 0),n=v(e.model).trim(),o=P_(t,n);if(e.check){let l=typeof(await Yu()).reviewScript=="function";return[{text:l?`ready: ${o.provider}/${o.model}`:"the review agent bundle is present but exports no reviewScript",data:{ready:l,provider:o.provider,model:o.model,llm_config:t.sourcePath??"builtin"}},l?B:me]}let i=Se(e);if(!hr.existsSync(i))throw new x("Local script file not found.",{exitCode:b,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:[i]}});let r=(Array.isArray(e.video)?e.video:[]).map(p=>p.trim()).filter(p=>p.length>0),s=r.filter(p=>!hr.existsSync(p));if(s.length>0)throw new x("A --video path does not exist.",{exitCode:b,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass --video once per episode, in episode order.",data:{expected:["existing video files"],actual:s.slice(0,5)}});let c=v(e.source_path).trim();if(c&&!hr.existsSync(c))throw new x("Video source not found.",{exitCode:b,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass -s to a video file or a directory of per-episode videos, or omit it for a script-only review.",data:{expected:["existing video file or directory"],actual:[c]}});let{reviewScript:a}=await Yu(),d=p=>process.stdout.write(JSON.stringify(p)+`
167
- `);try{await a({scriptPath:i,...c?{source:c}:{},...r.length>0?{videos:r}:{},...qu(v(e.episodes))?{episodes:qu(v(e.episodes))}:{},concurrency:Os(e,"concurrency",5),converge:e.converge!==!1,convergeOnly:e.converge_only===!0,apiKey:o.apiKey,maxAttempts:o.maxAttempts,model:o.model,mediaModel:o.model,...o.baseUrl?{baseUrl:o.baseUrl}:{},maxSteps:Os(e,"max_steps",300),mediaBudget:Os(e,"media_budget",1),episodeTimeoutMs:Os(e,"episode_timeout_ms",8*6e4),onEvent:d})}catch(p){throw p instanceof x?p:new x("Review failed.",{exitCode:me,errorCode:"REVIEW_FAILED",hint:"Read the error details, NDJSON asr-compared/episode reports and .review/asr/ evidence before retrying.",data:{expected:["a completed review run"],actual:[p instanceof Error?p.message:String(p)]}})}return[{text:"",data:{}},B]}function Wu(e,t){ae(e.command("review"),"write").description("\u6D3E\u53D1 agent \u5BA1\u6838\u5267\u672C\uFF1A\u7ED9 -s \u5C31\u6309\u539F\u89C6\u9891\u62C9\u7247\u6838\u5BF9\uFF0C\u4E0D\u7ED9\u5C31\u7EAF\u5267\u672C\u5BA1\u6838").option("-s, --source-path <path>","\u539F\u89C6\u9891\u6587\u4EF6\u6216\u6BCF\u96C6\u4E00\u4E2A\u89C6\u9891\u7684\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",(n,o)=>[...o,n],[]).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\u9ED8\u8BA4 review-agent\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(q(Zu,t))}import*as vf from"node:fs";import*as eo from"node:fs";var Xu=null,C_=0;function H(e,t){Xu&&Xu.push({fn:e,note:t,ms:Math.round((performance.now()-C_)*100)/100})}var T_=[["actor","actors","actor"],["location","locations","location"],["prop","props","prop"]];function Xn(e){return Array.isArray(e)?e:[]}function Ee(e){return typeof e=="string"?e:""}function Mn(e,t,n,o){if(t){if(e.has(t)&&e.get(t)!==n){o.add(t);return}e.set(t,n)}}function ad(e){return Rs(JSON.parse(eo.readFileSync(e,"utf8")),e)}function Rs(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 T_)for(let l of Xn(e[d])){let f={id:Ee(l[`${p}_id`]),kind:a,name:Ee(l[`${p}_name`]),aliases:Xn(l.aliases).map(Ee).filter(Boolean),importance:Ee(l.importance),desc:Ee(l.description),states:Xn(l.states).map(u=>({id:Ee(u.state_id),name:Ee(u.state_name),desc:Ee(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;Xn(e.episodes).forEach((a,d)=>{let p={anchor:String(d+1),id:Ee(a.episode_id),no:d+1,title:Ee(a.title)||void 0,synopsis:Ee(a.synopsis)||void 0,scenes:[],raw:a};Xn(a.scenes).forEach((l,f)=>{s++;let u={anchor:n===4?Ee(l.scene_id):`${d+1}-${f+1}`,id:Ee(l.scene_id),no:f+1,gno:s,env:l.environment??{},location:sd(l.location,"location_id"),actors:Xn(l.actors).map(g=>sd(g,"actor_id")).filter(Boolean),props:Xn(l.props).map(g=>sd(g,"prop_id")).filter(Boolean),actions:[],raw:l,ep:p};Xn(l.actions).forEach((g,m)=>{c++;let h={anchor:n===4?Ee(g.action_id):`${d+1}-${f+1}-${m+1}`,no:m+1,gno:c,type:Ee(g.type)||"action",content:Ee(g.content),speaker:V_(g.speaker),paren:typeof g.parenthetical=="string"?g.parenthetical:typeof g.emotion=="string"?g.emotion:void 0,ts:Ee(g.extend?.timestamp)||void 0,raw:g,scene:u};u.actions.push(h),Mn(o.actions,h.anchor,h,r),Mn(o.actions,`${d+1}-${f+1}-${m+1}`,h,r),n===3&&Mn(o.actions,`${p.id}/${u.id}#${m}`,h,r)}),p.scenes.push(u),Mn(o.scenes,u.anchor,u,r),Mn(o.scenes,`${d+1}-${f+1}`,u,r),Mn(o.scenes,`${p.id}/${u.id}`,u,r),Mn(o.scenes,u.id,u,r)}),o.episodes.push(p),Mn(o.eps,String(d+1),p,r),Mn(o.eps,p.id,p,r)});for(let a of r)o.actions.delete(a),o.scenes.delete(a),o.eps.delete(a);return H(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 sd(e,t){if(!e||typeof e!="object")return null;let n=Ee(e[t]);if(!n)return null;let o=Array.isArray(e.state_ids)?e.state_ids.map(Ee):e.state_id?[Ee(e.state_id)]:[];return{id:n,states:o,raw:e}}function V_(e){if(!(!e||typeof e!="object")){if(e.actor_id)return{id:Ee(e.actor_id),state:Ee(e.state_id)||void 0};if(e.kind)return{kind:Ee(e.kind),label:Ee(e.label)||void 0}}}function Ue(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)??$_(e,p);if(f){let u=f.states.filter(g=>g.id===l||g.name===l);if(u.length===1)return H("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 H("resolve",`"${n}" -> action map hit -> ${i.anchor}`),{t:"action",action:i};let r=e.scenes.get(n);if(r)return H("resolve",`"${n}" -> scene map hit -> ${r.anchor}`),{t:"scene",scene:r};let s=e.eps.get(n);if(s)return H("resolve",`"${n}" -> episode map hit -> ${s.id}`),{t:"ep",ep:s};let c=e.byId.get(n);if(c)return H("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 H("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 H("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 $_(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 Co(e,t){return e.byId.get(t)?.label||t}function To(e,t,n){return e.byId.get(t)?.states.find(i=>i.id===n)?.name||n}function to(e){return e.episodes.flatMap(t=>t.scenes.flatMap(n=>n.actions))}var D_={ep:"episode",scn:"scene",ac:"action",act:"actor",loc:"location",prp:"prop",st:"state"};function no(e,t){let n=Yi(D_[e],t);return t.add(n),H("newId",`${n} (collision-checked against ${t.size-1} live ids)`),n}function _e(e){if(Object.assign(e,Rs(e.raw,e.path)),!e.path){H("save","skipped: document is not bound to a file");return}ef(e,e.path)}function ef(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}`;eo.writeFileSync(n,JSON.stringify(e.raw,null,2)+`
168
- `),eo.renameSync(n,t),H("commit",`${eo.statSync(t).size} bytes -> ${t} (tmp + atomic rename)`)}var G_={system:"\u65C1\u767D",broadcast:"\u5E7F\u64AD",offscreen:"\u753B\u5916",group:"\u7FA4\u58F0"},tf="\u5FC3\u58F0";function J_(e,t){if(t.kind)return G_[t.kind]??t.kind;let n=Co(e,t.id);return t.state?`${n}\xB7${To(e,t.id,t.state)}`:n}function yr(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?J_(e,t.speaker):"?",d=[t.type==="inner_thought"?tf:"",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 cd(e,t){let n=Co(e,t.id);return t.states.length===1&&t.states[0]==="default"?n:`${n}(${t.states.map(o=>To(e,t.id,o)).join("+")})`}function Ei(e,t){let n=[t.env?.space,t.env?.time].filter(Boolean).join("/").toUpperCase(),o=t.location?cd(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=>cd(e,a)).join(", "),s=t.props.map(a=>cd(e,a)).join(", "),c=[r&&`cast: ${r}`,s&&`props: ${s}`].filter(Boolean).join(" ");return c?`${i}
169
- # ${c}`:i}function dd(e,t,n={}){let o=n.plain?0:Math.max(0,...t.actions.map(i=>i.anchor.length));return H("formatScene",`${t.anchor}: ${t.actions.length} actions, gutter=${o}`),[Ei(e,t),...t.actions.map(i=>yr(e,i,o,n))].join(`
170
- `)}var B_=/^([A-Za-z][A-Za-z0-9_]*|\d+(?:-\d+){0,2})\s\s+/;function nf(e,t){let n=e.trimEnd();if(!n.trim())return null;let o,i=n.match(B_);i&&(o=i[1],n=n.slice(i[0].length)),n=n.replace(/\\n/g,`
171
- `);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]===tf,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 K_=/^(scn[1-9A-HJ-NP-Za-km-z]{6}|scn_\d+)$/,j_=/^[A-Z.\/]+$/,z_=/^\d+\s+actions?$/,H_={EXT:"exterior",EXTERIOR:"exterior",INT:"interior",INTERIOR:"interior"};function of(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 pd(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)||z_.test(i))){if(K_.test(i)){n.anchor=i;continue}if(j_.test(i)&&i!=="\u2014"){let[r,s]=i.split("/");r&&(n.env.space=H_[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 rf(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 _i(e,t){throw Object.assign(new Error(e),t)}function ud(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 ld(e){try{return Jn(e.timestamp??"")}catch(t){if(!(t instanceof We))throw t;return _i(`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 sf(e,t){return _i("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 fd(e,t){t.length===0&&_i("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&&_i("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&&_i("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||_i(`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=ld(r),a=r,d=c,p="";for(let g of o){if(!g.timestamp)continue;let m=ld(g);m.milliseconds<d.milliseconds&&sf(a,g),a=g,d=m,g.address===s.address&&(p=m.canonical)}let l=e.findIndex(g=>g.address===s.address),f,u;for(let g=l+1;g<e.length;g+=1){let m=e[g];if(m.episodeId!==r.episodeId)break;if(!m.timestamp)continue;let h=ld(m);if(h.milliseconds<d.milliseconds&&sf(a,m),h.milliseconds!==d.milliseconds){f=m,u=h;break}}return H("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 md=["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 gd(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 hd(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=Ue(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(m=>m.id===c.id&&(a===null||m.states.includes(a)));g.length&&p.push({kind:"scene_binding",scene:u,matched:g.flatMap(m=>m.states)});for(let m of u.actions)if(m.speaker?.id===c.id&&(a===null||m.speaker.state===a)&&p.push({kind:"speaker",scene:u,action:m,matched:[c.id]}),a===null){let h=d.filter(w=>m.content.includes(w));h.length&&p.push({kind:"text_mention",scene:u,action:m,matched:h})}}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:m})=>{let h=g?u.actions.indexOf(g):-1,w=g?u.actions.slice(Math.max(0,h-r),h+r+1):[],y=Math.max(0,...w.map(E=>E.anchor.length));return{kind:f,address:g?.anchor??u.anchor,scene_address:u.anchor,episode:u.ep.no,matched:m,text:[Ei(e,u),...w.map(E=>(E===g?"> ":" ")+yr(e,E,y))].join(`
172
- `)}})}}function yd(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=>sf({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 Or=class{constructor(t,n,o,i){this.provider=t;this.transport=new Mi(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 $s=class extends Mi{generate(t){let n=t.media;if(n.kind==="local-fallback"||n.kind==="local")throw new P("invalid_response","A local fallback video cannot be sent to Gemini.");return this.generateMedia({...t,media:n},{fps:t.fps})}};function df(e,t){if(!Gn(e)||!Gn(e.usage))return{};let n=e.usage,o=a=>{let d=typeof a=="number"?a:0;return Number.isFinite(d)?d:0},i=Gn(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 Gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function H_(e){let t=e.trim().replace(/\/+$/,"");return t.endsWith("/chat/completions")?t:t.endsWith("/v1")?`${t}/chat/completions`:`${t}/v1/chat/completions`}function pf(e){return!Gn(e)||!Array.isArray(e.choices)?null:e.choices.find(Gn)??null}function lf(e){return e&&typeof e.finish_reason=="string"?e.finish_reason:""}function ff(e){return e&&Gn(e.message)?e.message:null}function Q_(e){let t=ff(e)?.content;return typeof t=="string"?t.trim():Array.isArray(t)?t.flatMap(n=>Gn(n)&&typeof n.text=="string"?[n.text]:[]).join(`
157
+ `).trim():""}function uf(e){try{return JSON.parse(e)}catch{throw new P("invalid_response","Provider returned invalid JSON.",{details:[e.slice(0,500)]})}}var Ds=class{constructor(t,n,o){this.provider=t;this.model=n;this.apiKey=o;if(!t.baseUrl&&t.protocol!=="google-vertex")throw new P("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/${Ts()}/locations/global/endpoints/openapi/chat/completions`:H_(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 Yt(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 nf.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 P(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 P(d,`OpenAI-compatible request to ${this.host} failed (status ${s.status}).`,{retryable:a,details:[`status: ${s.status}`,c.slice(0,500)]})}return uf(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=Ft(i,df(n,this.provider.protocol==="google-vertex"));try{let s=pf(n),c=lf(s);if(c==="length")throw new P("truncated","Provider output was truncated.");if(c==="content_filter"||c.startsWith("content_filter:"))throw new P("content_filtered",`Provider filtered the response (${c}).`);let a=Q_(s);if(!a)throw new P("empty_response","Provider returned an empty text response.");return{text:a,finishReason:c,attempts:o,usage:r,raw:n}}catch(s){throw s instanceof P&&(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=Ft(i,df(n,this.provider.protocol==="google-vertex"));try{let s=pf(n),c=lf(s);if(c==="length")throw new P("truncated","Provider tool output was truncated.");if(c==="content_filter"||c.startsWith("content_filter:"))throw new P("content_filtered",`Provider filtered the response (${c}).`);let a=ff(s)?.tool_calls;if(!Array.isArray(a))throw new P("invalid_response","Provider did not return a tool call.");for(let d of a){if(!Gn(d)||!Gn(d.function))continue;let p=d.function;if(!(p.name!==t.tool.name||typeof p.arguments!="string"))return{input:uf(p.arguments),finishReason:c,attempts:o,usage:r,raw:n}}throw new P("invalid_response","Provider did not return the required tool call.")}catch(s){throw s instanceof P&&(s.attempts=o,s.usage=r),s}}};var _n={model:"ep-20260721150136-98dj9",modelEnv:"ARK_MODEL",baseUrl:"https://ark.cn-beijing.volces.com/api/v3",apiKeyEnv:"ARK_API_KEY",timeoutMs:6e5,maxAttempts:3},F_=["gemini-3.8-flash","gemini-3.7-flash","gemini-3.6-flash"];function Y_(e){return e?.trim().replace(/\/+$/,"")??"anthropic-sdk-default"}function Id(e,t,n){let o=xn[e],i=JSON.stringify({task:e,taskVersion:o.version,protocol:t.protocol,baseUrl:Y_(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 mf.createHash("sha256").update(i).digest("hex")}function Ge(e,t,n){return new E(e,{exitCode:k,errorCode:"LLM_CONFIG_INVALID",hint:"Fix the selected LLM configuration and run `scriptctl doctor`.",data:{expected:t,actual:n}})}function Li(e){return new E("The selected LLM provider credential is not configured.",{exitCode:me,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 Ho(e,t){return Rt(mi(e.failure),{...sr(e.failure),provider:t.provider,model:t.model,retryable:e.failure.retryable,message:e.message})}function Ni(e,t){if(t.length===1)return e;let n=Cl(t,"All configured model routes failed.");return new P(e.code,n.message,{retryable:n.retryable,classification:mi(n),context:sr(n),modelFailures:t,details:t.map(ln)})}function q_(e){return["google-gemini","google-vertex"].includes(e.protocol)||/(^|\/)gemini-/i.test(e.model)}function Sd(e){let t=e.info.model.slice(0,e.info.model.lastIndexOf("/")+1);return[...new Set([e.info.model,...F_.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:Id(e.info.task,e.providerConfig,i)}}})}function uo(e,t){return!t?.aborted&&e instanceof P&&e.code!=="cancelled"}var vr=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=xn[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 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:fd(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:Id(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 Wu.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 P?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?fd(o.baseUrl,"--provider-base-url"):_n.baseUrl,apiKeyEnv:_n.apiKeyEnv,timeoutMs:_n.timeoutMs,maxAttempts:_n.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:Id(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 Li(t.info.provider);let r=t.providerConfig.protocol==="anthropic"?new Ns(t.providerConfig,t.modelConfig,i):new Ds(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 Li(t.info.provider);let s=new $s(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 Li(t.info.provider);return o}documentPort(t){if(xn[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 Li(n.info.provider);let i=new Or(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(!uo(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 (${ln(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=Sd(n),a=[];for(let[d,p]of c.entries()){s.signal?.throwIfAborted();let l=d===0?i:new Or(p.providerConfig,p.modelConfig,o);try{return await this.tracked(p.info,()=>l.generate(s))}catch(f){if(!uo(f,s.signal))throw f;let u=Ho(f,p.info);a.push(u);let h=c[d+1];if(h){process.stderr.write(`\u21AA\uFE0F ${p.info.model} \u6587\u6863\u8BF7\u6C42\u5931\u8D25\uFF0C\u5207\u6362\u5230 ${h.info.model} (${ln(u)})
159
+ `);continue}let m=this.arkAdapter();if(!m)throw Ni(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,()=>m.generateDocument(s,r.get(s.media)))}catch(w){throw uo(w,s.signal)?Ni(w,[...a,Ho(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=xn[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 Li("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.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(!uo(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:Ho(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=Sd(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(!uo(p,r.signal))throw p;let l=Ho(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} (${ln(l)})
161
+ `);continue}if(!this.doubaoAdapter()||!r.localPath)throw Ni(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 Li("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=xn[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.signal?{signal:n.signal}:{}}))}catch(d){throw uo(d,n.signal)?Ni(d,[...o,Ho(d,a)]):d}}doubaoAdapter(t){return this.arkAdapter(t)}doubaoTextAdapter(){return this.arkAdapter()}arkAdapter(t){let n=t?this.videoCredential(t):(process.env[_n.apiKeyEnv]??"").trim();if(!n)return null;let o=t?.info.model??this.doubaoModel(),i=t?.providerConfig.baseUrl??_n.baseUrl,r=`doubao ${i} ${o}`,s=this.doubaoAdapters.get(r);if(s)return s;let c=new Ps(o,_n.timeoutMs,_n.maxAttempts,n,i);return this.doubaoAdapters.set(r,c),c}doubaoModel(){return(process.env[_n.modelEnv]??"").trim()||_n.model}async withTextFallback(t,n,o){let i=this.resolve(t),r=q_(i.info),s=r?Sd(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(!uo(l,n)||!r&&l.code!=="content_filtered")throw l;let f=Ho(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} (${ln(f)})
163
+ `);continue}let h=this.doubaoTextAdapter();if(!h)throw Ni(l,c);let m=this.doubaoRoute(t);process.stderr.write(`\u21AA\uFE0F \u4E3B\u6A21\u578B\u8DEF\u7531\u5DF2\u8017\u5C3D\uFF0C\u56DE\u9000\u5230\u8C46\u5305 ${m.model}
164
+ `);try{return await this.tracked(m,()=>o(h))}catch(g){throw uo(g,n)?Ni(g,[...c,Ho(g,m)]):g}}}throw new Error("Text model routes cannot be empty.")}async generateText(t,n){let o=xn[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=xn[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 hf(e,t){return new vr(vi(e),t)}var W_=Z_(import.meta.url);function Gs(e){try{return W_.resolve(e),!0}catch{return!1}}function X_(e){let t=!1;try{Vt.statSync(e).isDirectory()&&(Vt.accessSync(e,Vt.constants.W_OK),t=!0)}catch{t=!1}let n=!1;try{n=Vt.statSync(Qo.join(e,"script.json")).isFile()}catch{n=!1}return{writable:t,hasScript:n}}function eE(){return Qo.join(Qo.dirname(Qo.resolve("workspace")),"output")}function yf(e={}){let t=ad(),n=[],o=new Set;for(let R of t)try{if(!Vt.existsSync(R)||!Vt.statSync(R).isFile())continue;let j=Vt.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=vi(i||void 0),c=new vr(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 Z="not set";if(j.baseUrl)try{Z=new URL(j.baseUrl).host}catch{Z=j.baseUrl}return{alias:R,host:Z}}),{mode:p}=Zu(),l=(process.env.SCRIPTCTL_OUTPUT_DIR??"").trim()||eE(),f=p==="local"?X_(l):null,u=!!process.env.AWB_BASE_URL,h=!!process.env.LINGJING_AWB_ACCESS_KEY,m=!!process.env.SANDBOX_PROJECT_GROUP_NO,g={"@anthropic-ai/sdk":Gs("@anthropic-ai/sdk"),"@google/genai":Gs("@google/genai"),jszip:Gs("jszip"),"fast-xml-parser":Gs("fast-xml-parser")},w=Object.entries(g).filter(([,R])=>!R).map(([R])=>R),y=process.versions.node,x=`env_file: ${n[0]??"missing"}`,S=R=>R?"configured":"not configured",A=[`node: ${y}`,"storage: local-filesystem",x,`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(h)}`),A.push(`gateway project identifier: ${S(m)}`));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||!h||!m)&&b.push("Configure gateway credentials before running `publish` / script CRUD against the remote project."),b.length===0&&b.push("Environment looks ready.");let[U,O]=y.split(".").map(R=>parseInt(R,10)),I=(U??0)>20||(U??0)===20&&(O??0)>=0,L=p===null?{configured:!1}:p==="local"?{dir:{ok:!!f?.writable,writable:!!f?.writable,hasScript:!!f?.hasScript}}:{endpoint:{ok:u},access:{ok:h},project:{ok:m}},T={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:L,dependencies:g};return[{text:[...A,...b].join(`
165
+ `),data:{checks:T}},J]}import{spawn as tE}from"node:child_process";var Js="@lingjingai/scriptctl",nE=`${Js}@latest`,Ad="npm";function oE(){return bi()}function iE(e){let t=/^(\d+)\.(\d+)\.\d+/.exec(e);return t?`${Js}@~${t[1]}.${t[2]}.0`:null}function rE(e){return["install","-g",e]}function sE(e,t){return[e,...t].join(" ")}function aE(e,t){return e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0).slice(-t)}function cE(e,t){return new Promise(n=>{let o=tE(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 wf(e,t=cE,n=oE){let o=!!e.patch,i=n(),r=o?iE(i):nE;if(!r)throw new E(`Cannot compute a patch update range from version ${i}.`,{exitCode:me,errorCode:"UPDATE_VERSION_INVALID",hint:"Run `scriptctl update` without --patch to install the latest version.",data:{version:i}});let s=[...rE(r)],c=sE(Ad,s),a={package:Js,package_spec:r,command:Ad,args:s,command_line:c};if(e.dry_run)return[{text:[`package: ${Js}`,`command: ${c}`,"dry-run: no update performed"].join(`
166
+ `),data:{op:"update",changed:!1,update:a}},J];let d=await t(Ad,s);if(d.error)throw new E(`Failed to start npm: ${d.error.message}`,{exitCode:me,errorCode:"UPDATE_SPAWN_FAILED",hint:`Run '${c}' after fixing the npm installation.`,data:{update:a,cause:d.error.message}});if(d.exitCode!==J){let f=[`exit: ${d.exitCode===null?`signal ${d.signal??"unknown"}`:String(d.exitCode)}`,...aE(d.stderr,5).map(u=>`stderr: ${u}`)];throw new E("npm could not update scriptctl.",{exitCode:me,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}},J]}function xf(e,t){e.command("doctor").description("Check configuration and runtime dependencies").option("--llm-config <path>","LLM configuration file").action(q(yf,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(q(wf,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(q(Qu,t));ke(n,["Release version"])}import*as Pr from"node:fs";import*as oa from"node:path";import{fileURLToPath as h5,pathToFileURL as y5}from"node:url";import*as it from"node:fs";import*as ot from"node:path";import{createHash as sm}from"node:crypto";import{z as nt}from"zod";import*as mo from"node:fs";var _f=null,dE=0;function H(e,t){_f&&_f.push({fn:e,note:t,ms:Math.round((performance.now()-dE)*100)/100})}var pE=[["actor","actors","actor"],["location","locations","location"],["prop","props","prop"]];function fo(e){return Array.isArray(e)?e:[]}function Ee(e){return typeof e=="string"?e:""}function Jn(e,t,n,o){if(t){if(e.has(t)&&e.get(t)!==n){o.add(t);return}e.set(t,n)}}function bd(e){return go(JSON.parse(mo.readFileSync(e,"utf8")),e)}function go(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 pE)for(let l of fo(e[d])){let f={id:Ee(l[`${p}_id`]),kind:a,name:Ee(l[`${p}_name`]),aliases:fo(l.aliases).map(Ee).filter(Boolean),importance:Ee(l.importance),desc:Ee(l.description),states:fo(l.states).map(u=>({id:Ee(u.state_id),name:Ee(u.state_name),desc:Ee(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;fo(e.episodes).forEach((a,d)=>{let p={anchor:String(d+1),id:Ee(a.episode_id),no:d+1,title:Ee(a.title)||void 0,synopsis:Ee(a.synopsis)||void 0,scenes:[],raw:a};fo(a.scenes).forEach((l,f)=>{s++;let u={anchor:n===4?Ee(l.scene_id):`${d+1}-${f+1}`,id:Ee(l.scene_id),no:f+1,gno:s,env:l.environment??{},location:kd(l.location,"location_id"),actors:fo(l.actors).map(h=>kd(h,"actor_id")).filter(Boolean),props:fo(l.props).map(h=>kd(h,"prop_id")).filter(Boolean),actions:[],raw:l,ep:p};fo(l.actions).forEach((h,m)=>{c++;let g={anchor:n===4?Ee(h.action_id):`${d+1}-${f+1}-${m+1}`,no:m+1,gno:c,type:Ee(h.type)||"action",content:Ee(h.content),speaker:lE(h.speaker),paren:typeof h.parenthetical=="string"?h.parenthetical:typeof h.emotion=="string"?h.emotion:void 0,ts:Ee(h.extend?.timestamp)||void 0,raw:h,scene:u};u.actions.push(g),Jn(o.actions,g.anchor,g,r),Jn(o.actions,`${d+1}-${f+1}-${m+1}`,g,r),n===3&&Jn(o.actions,`${p.id}/${u.id}#${m}`,g,r)}),p.scenes.push(u),Jn(o.scenes,u.anchor,u,r),Jn(o.scenes,`${d+1}-${f+1}`,u,r),Jn(o.scenes,`${p.id}/${u.id}`,u,r),Jn(o.scenes,u.id,u,r)}),o.episodes.push(p),Jn(o.eps,String(d+1),p,r),Jn(o.eps,p.id,p,r)});for(let a of r)o.actions.delete(a),o.scenes.delete(a),o.eps.delete(a);return H(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 kd(e,t){if(!e||typeof e!="object")return null;let n=Ee(e[t]);if(!n)return null;let o=Array.isArray(e.state_ids)?e.state_ids.map(Ee):e.state_id?[Ee(e.state_id)]:[];return{id:n,states:o,raw:e}}function lE(e){if(!(!e||typeof e!="object")){if(e.actor_id)return{id:Ee(e.actor_id),state:Ee(e.state_id)||void 0};if(e.kind)return{kind:Ee(e.kind),label:Ee(e.label)||void 0}}}function Ce(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)??uE(e,p);if(f){let u=f.states.filter(h=>h.id===l||h.name===l);if(u.length===1)return H("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(h=>`${h.id}(${h.name})`).join(", ")})`)}}let i=e.actions.get(n);if(i)return H("resolve",`"${n}" -> action map hit -> ${i.anchor}`),{t:"action",action:i};let r=e.scenes.get(n);if(r)return H("resolve",`"${n}" -> scene map hit -> ${r.anchor}`),{t:"scene",scene:r};let s=e.eps.get(n);if(s)return H("resolve",`"${n}" -> episode map hit -> ${s.id}`),{t:"ep",ep:s};let c=e.byId.get(n);if(c)return H("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 H("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 H("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 uE(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 Fo(e,t){return e.byId.get(t)?.label||t}function Yo(e,t,n){return e.byId.get(t)?.states.find(i=>i.id===n)?.name||n}function En(e){return e.episodes.flatMap(t=>t.scenes.flatMap(n=>n.actions))}var fE={ep:"episode",scn:"scene",ac:"action",act:"actor",loc:"location",prp:"prop",st:"state"};function ho(e,t){let n=cr(fE[e],t);return t.add(n),H("newId",`${n} (collision-checked against ${t.size-1} live ids)`),n}function Se(e){if(Object.assign(e,go(e.raw,e.path)),!e.path){H("save","skipped: document is not bound to a file");return}Ef(e,e.path)}function Ef(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}`;mo.writeFileSync(n,JSON.stringify(e.raw,null,2)+`
167
+ `),mo.renameSync(n,t),H("commit",`${mo.statSync(t).size} bytes -> ${t} (tmp + atomic rename)`)}var mE={system:"\u65C1\u767D",broadcast:"\u5E7F\u64AD",offscreen:"\u753B\u5916",group:"\u7FA4\u58F0"},Sf="\u5FC3\u58F0";function gE(e,t){if(t.kind)return mE[t.kind]??t.kind;let n=Fo(e,t.id);return t.state?`${n}\xB7${Yo(e,t.id,t.state)}`:n}function Rr(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?gE(e,t.speaker):"?",d=[t.type==="inner_thought"?Sf:"",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 Od(e,t){let n=Fo(e,t.id);return t.states.length===1&&t.states[0]==="default"?n:`${n}(${t.states.map(o=>Yo(e,t.id,o)).join("+")})`}function Ui(e,t){let n=[t.env?.space,t.env?.time].filter(Boolean).join("/").toUpperCase(),o=t.location?Od(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=>Od(e,a)).join(", "),s=t.props.map(a=>Od(e,a)).join(", "),c=[r&&`cast: ${r}`,s&&`props: ${s}`].filter(Boolean).join(" ");return c?`${i}
168
+ # ${c}`:i}function vd(e,t,n={}){let o=n.plain?0:Math.max(0,...t.actions.map(i=>i.anchor.length));return H("formatScene",`${t.anchor}: ${t.actions.length} actions, gutter=${o}`),[Ui(e,t),...t.actions.map(i=>Rr(e,i,o,n))].join(`
169
+ `)}var hE=/^([A-Za-z][A-Za-z0-9_]*|\d+(?:-\d+){0,2})\s\s+/;function If(e,t){let n=e.trimEnd();if(!n.trim())return null;let o,i=n.match(hE);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]===Sf,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 yE=/^(scn[1-9A-HJ-NP-Za-km-z]{6}|scn_\d+)$/,wE=/^[A-Z.\/]+$/,xE=/^\d+\s+actions?$/,_E={EXT:"exterior",EXTERIOR:"exterior",INT:"interior",INTERIOR:"interior"};function Af(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 Rd(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)||xE.test(i))){if(yE.test(i)){n.anchor=i;continue}if(wE.test(i)&&i!=="\u2014"){let[r,s]=i.split("/");r&&(n.env.space=_E[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 kf(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 Ci(e,t){throw Object.assign(new Error(e),t)}function Ld(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 Md(e){try{return eo(e.timestamp??"")}catch(t){if(!(t instanceof Xe))throw t;return Ci(`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 bf(e,t){return Ci("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 Nd(e,t){t.length===0&&Ci("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(h=>n.has(h.address));o.length!==n.size&&Ci("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(h=>h.episodeId));i.size!==1&&Ci("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||Ci(`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=Md(r),a=r,d=c,p="";for(let h of o){if(!h.timestamp)continue;let m=Md(h);m.milliseconds<d.milliseconds&&bf(a,h),a=h,d=m,h.address===s.address&&(p=m.canonical)}let l=e.findIndex(h=>h.address===s.address),f,u;for(let h=l+1;h<e.length;h+=1){let m=e[h];if(m.episodeId!==r.episodeId)break;if(!m.timestamp)continue;let g=Md(m);if(g.milliseconds<d.milliseconds&&bf(a,m),g.milliseconds!==d.milliseconds){f=m,u=g;break}}return H("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 Ud=["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 Cd(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 Pd(e,t,n={}){let o=n.offset??0,i=n.limit??20,r=n.context??3;for(let[f,u,h]of[["offset",o,0],["limit",i,1],["context",r,0]])if(!Number.isSafeInteger(u)||u<h)throw new Error(`${f} must be an integer >= ${h}`);let s=Ce(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 h=[...u.location?[u.location]:[],...u.actors,...u.props].filter(m=>m.id===c.id&&(a===null||m.states.includes(a)));h.length&&p.push({kind:"scene_binding",scene:u,matched:h.flatMap(m=>m.states)});for(let m of u.actions)if(m.speaker?.id===c.id&&(a===null||m.speaker.state===a)&&p.push({kind:"speaker",scene:u,action:m,matched:[c.id]}),a===null){let g=d.filter(w=>m.content.includes(w));g.length&&p.push({kind:"text_mention",scene:u,action:m,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:h,matched:m})=>{let g=h?u.actions.indexOf(h):-1,w=h?u.actions.slice(Math.max(0,g-r),g+r+1):[],y=Math.max(0,...w.map(x=>x.anchor.length));return{kind:f,address:h?.anchor??u.anchor,scene_address:u.anchor,episode:u.ep.no,matched:m,text:[Ui(e,u),...w.map(x=>(x===h?"> ":" ")+Rr(e,x,y))].join(`
171
+ `)}})}}function Td(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}
173
172
  ${t.text}`),e.next_offset===null?"end":`Continue: --offset ${e.next_offset}`].join(`
174
173
 
175
- `)}var Q_=["\u65C1\u767D","\u5E7F\u64AD","\u753B\u5916","\u7FA4\u58F0"],F_={\u65C1\u767D:"system",\u5E7F\u64AD:"broadcast",\u753B\u5916:"offscreen",\u7FA4\u58F0:"group"};function Y_(e){let t=new Set(Q_);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 Ls(e,t="",n={}){let o=Ue(e,t);switch(H("read",`dispatch on node kind "${o.t}"`),o.t){case"script":return Z_(e);case"ep":return W_(e,o.ep,n);case"scene":return dd(e,o.scene,n);case"asset":return X_(e,o.asset);case"state":return ex(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[Ei(e,o.action.scene),...c.map(l=>(l===o.action?"> ":" ")+yr(e,l,a,n)),d?`transition: ${Co(e,d.target)} | ${d.process} | ${d.contrast}`:"",p.length?`extend: ${p.map(([l,f])=>`${l}=${JSON.stringify(f)}`).join(", ")}`:""].filter(Boolean).join(`
176
- `)}}}function q_(e){return e.actions.reduce((t,n)=>t+n.content.length,0)}function Z_(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}: ${wr(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+q_(a),0);i.push(` ${r.no} ${r.id} ${r.scenes.length} scenes ${s} chars${r.title?` ${r.title}`:""}`+(r.synopsis?` ${wr(r.synopsis,120)}`:""))}return i.join(`
177
- `)}function W_(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=>Ei(e,i))].join(`
178
- `):[o,...t.scenes.map(i=>dd(e,i,n))].join(`
179
-
180
- `)}function X_(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} ${wr(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])=>`${To(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(`
181
- `)}function ex(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=to(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(`
182
- `)}function wr(e,t){return e.length>t?e.slice(0,t)+"\u2026":e}function Ed(e,t){let n=to(e);if(H("find",`pool = all actions (${n.length})`),t.in){let o=Ue(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})`);H("find",`--in ${t.in} narrows pool to ${n.length}`)}if(t.type&&(n=n.filter(o=>o.type===t.type),H("find",`--type ${t.type} -> ${n.length}`)),t.speaker){let o=Ue(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),H("find",`--speaker ${t.speaker} -> ${o.asset.id} -> ${n.length}`)}return n}function pf(e,t,n={}){let o=Ed(e,n),i=t?new RegExp(t,"u"):null,r=o.filter(f=>!i||i.test(f.content));H("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)+" ",m=f.speaker?.id?Co(e,f.speaker.id)+"\uFF1A":"",h=n.full||!i?f.content:tx(f.content,i,c);return`${f.anchor.padEnd(d)} ${g}${m}${h}`});return[p,...l].join(`
183
- `)}function tx(e,t,n){let o=e.match(t);if(!o||o.index===void 0)return wr(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 _d(e,t){return fd(ud(e),gd(e,Ed(e,{in:t})))}function lf(e,t){let n=_d(e,t);return md.map(o=>`${o}=${n[o]}`).join(" ")}var nx=["content","paren","speaker","ts","type","transition"],ox=["name","desc","importance","aliases","role"],ix=["name","desc"],rx=["title","synopsis"],sx=["space","time"],ax=["title","worldview","style","synopsis","logline","theme","main"];function Er(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 uf(e,t,n){let o=Ue(e,t);if(o.t==="asset")return dx(e,t,o.asset,n);if(o.t==="state")return px(e,t,o.asset,o.state,n);if(o.t==="script")return af(e,t||"script","script",o.doc.raw,n,ax);if(o.t==="ep")return af(e,t,"episode",o.ep.raw,n,rx);if(o.t==="scene")return cx(e,t,o.scene,n);let i=o.action,r=i.raw,s=Er(i.anchor,"action",n,nx),c=it(e);if(H("edit",`${i.anchor}: ${s.join(", ")}`),n.type!==void 0&&(r.type=Vo("type",n.type,Vt,wn)),n.content!==void 0&&(r.content=n.content),n.paren!==void 0&&Ms(e,r,n.paren),n.speaker!==void 0&&(r.speaker=xd(e,n.speaker)),n.ts!==void 0&&gf(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=Ue(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 _e(e),`${i.anchor} ${s.join("+")} ${Ns(r)}`+Ve(e,c)}function af(e,t,n,o,i,r){let s=Er(t,n,i,r),c=it(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 H("edit",`${n} ${t}: ${s.join(", ")}`),_e(e),`${t} ${s.join("+")}`+Ve(e,c)}function cx(e,t,n,o){let i=Er(t,"scene",o,sx),r=it(e),s={...n.raw.environment??{}};return o.space!==void 0&&(s.space=Vo("space",o.space,ll,Da)),o.time!==void 0&&(s.time=Vo("time",o.time,$a,Wr)),n.raw.environment=s,H("edit",`scene ${n.anchor}: ${i.join(", ")}`),_e(e),`${n.anchor} ${i.join("+")} ${[s.space,s.time].filter(Boolean).join("/")}`+Ve(e,r)}function dx(e,t,n,o){let i=Er(t,"asset",o,ox),r=it(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=xf(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=Vo("role",o.role,Gn,ti):delete n.raw.role_type}return o.aliases!==void 0&&(o.aliases.length?n.raw.aliases=o.aliases:delete n.raw.aliases),H("edit",`asset ${n.id}: ${i.join(", ")}`),_e(e),`${n.id} ${i.join("+")} ${o.name??n.name}`+Ve(e,r)}function px(e,t,n,o,i){let r=Er(t,"state",i,ix),s=it(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),H("edit",`state ${n.id}/${o.id}: ${r.join(", ")}`),_e(e),`${n.id}/${o.id} ${r.join("+")} ${i.name??o.name}`+Ve(e,s)}function ff(e,t,n,o,i,r,s){let c=Ue(e,t);if(c.t!=="action")throw new Error(`${t} is a ${c.t}; insert needs a sibling action`);let a=c.action,d=it(e),p={type:Vo("type",o,Vt,wn),content:i};if(e.version===4&&(p.action_id=no("ac",new Set(e.actions.keys()))),o==="dialogue"||o==="inner_thought"){if(!r)throw new Error(`a ${o} needs a speaker`);p.speaker=xd(e,r),s!==void 0&&Ms(e,p,s)}else if(r||s)throw new Error(`a ${o} takes neither speaker nor paren`);let l=a.scene.raw.actions,f=l.indexOf(a.raw)+(n==="before"?0:1);return l.splice(f,0,p),H("insert",`${p.action_id??`${a.scene.anchor}#${f}`} ${n} ${a.anchor}`),_e(e),`${p.action_id??`${a.scene.anchor}#${f}`} ${n} ${a.anchor} ${Ns(p)}`+Ve(e,d)}function mf(e,t,n,o="after"){let i=Ue(e,t);if(i.t!=="action")throw new Error(`${t} is a ${i.t}; move targets one action`);let r=Ue(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=it(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),H("move",`${i.action.scene.anchor} -> ${r.action.scene.anchor}, identity ${i.action.anchor} preserved`),_e(e),`${i.action.anchor} ${o} ${r.action.anchor} (${i.action.scene.anchor} -> ${r.action.scene.anchor})`+Ve(e,s)}function Ms(e,t,n){let o=e.version===4?"parenthetical":"emotion";n===null?delete t[o]:t[o]=n}function gf(e,t){if(t===null){e.extend&&delete e.extend.timestamp;return}let n;try{n=Jn(t).canonical}catch(o){throw o instanceof We?new Error(`${o.message} (got ${JSON.stringify(t)})`):o}e.extend={...e.extend??{},timestamp:n}}function xd(e,t){let n=e.assets.find(a=>a.name===t||a.aliases.includes(t)),[o,i]=n?[t,void 0]:lx(t,"\xB7"),r=F_[o];if(r)return i?{kind:r,label:i}:{kind:r};let s=Ue(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 lx(e,t){let n=e.indexOf(t);return n<0?[e,void 0]:[e.slice(0,n),e.slice(n+t.length)]}function Ns(e){return wr(String(e.content??""),40)}function hf(e,t,n,o={}){let i=Rs(structuredClone(e.raw)),r=ux(i,t,n,o);return e.raw=i.raw,_e(e),r}function ux(e,t,n,o){if(t==="+"||Number(t)===e.episodes.length+1){let r={scenes:[]};return e.version===4&&(r.episode_id=no("ep",new Set(e.eps.keys()))),e.raw.episodes.push(r),H("write",`appending episode ${e.episodes.length+1}`),cf(e,r,e.episodes.length+1,n,o,!0)}let i=Ue(e,t);if(i.t==="scene")return fx(e,i.scene,n,o);if(i.t==="ep")return cf(e,i.ep.raw,i.ep.no,n,o,!1);throw new Error(`write targets a scene or an episode (got ${i.t})`)}function fx(e,t,n,o){let i=it(e),r=wf(e,t.raw,t,n,new Set(e.actions.keys()),o);return _e(e),yf(t.anchor,r)+Ve(e,i)}function yf(e,t){return`${e}: ${t.total} actions (${t.kept} kept, ${t.created} new, ${t.dropped.length} deleted)`+(t.dropped.length?`
184
- deleted: ${t.dropped.map(n=>`${n.anchor} ${Ns(n.raw)}`).join(`
185
- `)}`:"")}function wf(e,t,n,o,i,r,s,c){let a=Y_(e),{head:d,meta:p,body:l}=of(o.split(`
186
- `));if(d){let y=pd(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?wd(e,y.location,"location"):null,t.actors=y.cast.map(E=>wd(e,E,"actor")),t.props=y.props.map(E=>wd(e,E,"prop"))}let f=s??new Map((n?.actions??[]).map(y=>[y.anchor,y])),u=c??new Set,g=new Set,m=[],h=0,w=n?n.anchor:"this new scene";for(let y of l){let E=nf(y,a);if(!E)continue;let I=E.anchor?f.get(E.anchor):void 0;if(E.anchor&&!I)throw new Error(`Anchor ${E.anchor} is not in ${w} \u2014 move it with \`move\`, or drop the anchor to create a new action`);if(I&&u.has(I.anchor))throw new Error(`Anchor ${E.anchor} appears twice in ${w} \u2014 drop the anchor from the copy to make it a new action`);let _=I?I.raw:{};!I&&e.version===4&&(_.action_id=no("ac",i)),_.type=Vo("type",E.type,Vt,wn),_.content=E.content,E.type==="dialogue"||E.type==="inner_thought"?(_.speaker=xd(e,E.speakerName),Ms(e,_,E.paren??null)):(delete _.speaker,Ms(e,_,null)),gf(_,E.ts??null),I?(g.add(I.anchor),u.add(I.anchor)):h++,m.push(_)}if(!m.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(m.length&&!g.size&&(n?.actions.length??0)>0&&!r.allowDelete)throw new Error(`None of the ${m.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=m,{total:m.length,kept:g.size,created:h,dropped:s?[]:(n?.actions??[]).filter(y=>!g.has(y.anchor))}}function cf(e,t,n,o,i,r){let s=it(e),c=r?[]:e.episodes[n-1].scenes,a=new Map;for(let I of c)a.set(I.anchor,I),a.set(I.id,I);let d=[];for(let I of o.split(`
187
- `))I.startsWith("##")?d.push(I):d.length&&(d[d.length-1]+=`
188
- `+I);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 I of c)for(let _ of I.actions)f.set(_.anchor,_);let u=new Set,g=new Set,m=[],h=[],w=0;for(let I of d){let _=pd(I.split(`
189
- `)[0]),A=_.anchor?a.get(_.anchor):void 0;if(_.anchor&&!A)throw new Error(`Scene ${_.anchor} is not in episode ${n} \u2014 drop the id from the header to create a new scene here`);let k=A?A.raw:{};A?g.add(A.anchor):(e.version===4?k.scene_id=no("scn",l):k.scene_id=`scn_${String(c.length+w+1).padStart(3,"0")}`,w++);let P=wf(e,k,A??null,I,p,i,f,u);m.push(k),h.push(yf(A?A.anchor:`new ${k.scene_id}`,P))}let y=[...f.values()].filter(I=>!u.has(I.anchor));if(y.length&&!i.allowDelete)throw new Error(`This would delete ${y.length} action(s) from episode ${n}: `+y.slice(0,6).map(I=>`${I.anchor}(${I.scene.anchor})`).join(", ")+(y.length>6?" \u2026":"")+" \u2014 keep their lines, or pass --allow-delete if that is the intent");let E=c.filter(I=>!g.has(I.anchor));if(E.length&&!i.allowDelete)throw new Error(`This would delete ${E.length} whole scene(s) from episode ${n}: `+E.map(I=>`${I.anchor}(${I.actions.length} actions)`).join(", ")+" \u2014 include their `##` headers to keep them, or pass --allow-delete if that is the intent");return H("write",`episode ${n}: ${d.length} scene blocks, ${w} new, ${E.length} deleted`),t.scenes=m,_e(e),`EP${n}: ${m.length} scenes (${m.length-w} kept, ${w} new, ${E.length} deleted, ${y.length} actions deleted)
190
- `+h.map(I=>" "+I.replace(/\n/g,`
174
+ `)}var EE=["\u65C1\u767D","\u5E7F\u64AD","\u753B\u5916","\u7FA4\u58F0"],SE={\u65C1\u767D:"system",\u5E7F\u64AD:"broadcast",\u753B\u5916:"offscreen",\u7FA4\u58F0:"group"};function IE(e){let t=new Set(EE);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 Ks(e,t="",n={}){let o=Ce(e,t);switch(H("read",`dispatch on node kind "${o.t}"`),o.t){case"script":return kE(e);case"ep":return bE(e,o.ep,n);case"scene":return vd(e,o.scene,n);case"asset":return OE(e,o.asset);case"state":return vE(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[Ui(e,o.action.scene),...c.map(l=>(l===o.action?"> ":" ")+Rr(e,l,a,n)),d?`transition: ${Fo(e,d.target)} | ${d.process} | ${d.contrast}`:"",p.length?`extend: ${p.map(([l,f])=>`${l}=${JSON.stringify(f)}`).join(", ")}`:""].filter(Boolean).join(`
175
+ `)}}}function AE(e){return e.actions.reduce((t,n)=>t+n.content.length,0)}function kE(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}: ${Mr(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+AE(a),0);i.push(` ${r.no} ${r.id} ${r.scenes.length} scenes ${s} chars${r.title?` ${r.title}`:""}`+(r.synopsis?` ${Mr(r.synopsis,120)}`:""))}return i.join(`
176
+ `)}function bE(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=>Ui(e,i))].join(`
177
+ `):[o,...t.scenes.map(i=>vd(e,i,n))].join(`
178
+
179
+ `)}function OE(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} ${Mr(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])=>`${Yo(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 vE(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=En(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 Mr(e,t){return e.length>t?e.slice(0,t)+"\u2026":e}function $d(e,t){let n=En(e);if(H("find",`pool = all actions (${n.length})`),t.in){let o=Ce(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})`);H("find",`--in ${t.in} narrows pool to ${n.length}`)}if(t.type&&(n=n.filter(o=>o.type===t.type),H("find",`--type ${t.type} -> ${n.length}`)),t.speaker){let o=Ce(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),H("find",`--speaker ${t.speaker} -> ${o.asset.id} -> ${n.length}`)}return n}function Mf(e,t,n={}){let o=$d(e,n),i=t?new RegExp(t,"u"):null,r=o.filter(f=>!i||i.test(f.content));H("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}`,h=u===f.anchor?"":u.padEnd(8)+" ",m=f.speaker?.id?Fo(e,f.speaker.id)+"\uFF1A":"",g=n.full||!i?f.content:RE(f.content,i,c);return`${f.anchor.padEnd(d)} ${h}${m}${g}`});return[p,...l].join(`
182
+ `)}function RE(e,t,n){let o=e.match(t);if(!o||o.index===void 0)return Mr(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 Dd(e,t){return Nd(Ld(e),Cd(e,$d(e,{in:t})))}function Lf(e,t){let n=Dd(e,t);return Ud.map(o=>`${o}=${n[o]}`).join(" ")}var ME=["content","paren","speaker","ts","type","transition"],LE=["name","desc","importance","aliases","role"],NE=["name","desc"],UE=["title","synopsis"],CE=["space","time"],PE=["title","worldview","style","synopsis","logline","theme","main"];function Lr(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 Nf(e,t,n){let o=Ce(e,t);if(o.t==="asset")return VE(e,t,o.asset,n);if(o.t==="state")return $E(e,t,o.asset,o.state,n);if(o.t==="script")return Of(e,t||"script","script",o.doc.raw,n,PE);if(o.t==="ep")return Of(e,t,"episode",o.ep.raw,n,UE);if(o.t==="scene")return TE(e,t,o.scene,n);let i=o.action,r=i.raw,s=Lr(i.anchor,"action",n,ME),c=dt(e);if(H("edit",`${i.anchor}: ${s.join(", ")}`),n.type!==void 0&&(r.type=qo("type",n.type,zt,Rn)),n.content!==void 0&&(r.content=n.content),n.paren!==void 0&&Bs(e,r,n.paren),n.speaker!==void 0&&(r.speaker=Gd(e,n.speaker)),n.ts!==void 0&&Pf(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=Ce(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 Se(e),`${i.anchor} ${s.join("+")} ${js(r)}`+$e(e,c)}function Of(e,t,n,o,i,r){let s=Lr(t,n,i,r),c=dt(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 H("edit",`${n} ${t}: ${s.join(", ")}`),Se(e),`${t} ${s.join("+")}`+$e(e,c)}function TE(e,t,n,o){let i=Lr(t,"scene",o,CE),r=dt(e),s={...n.raw.environment??{}};return o.space!==void 0&&(s.space=qo("space",o.space,Pl,ic)),o.time!==void 0&&(s.time=qo("time",o.time,oc,fs)),n.raw.environment=s,H("edit",`scene ${n.anchor}: ${i.join(", ")}`),Se(e),`${n.anchor} ${i.join("+")} ${[s.space,s.time].filter(Boolean).join("/")}`+$e(e,r)}function VE(e,t,n,o){let i=Lr(t,"asset",o,LE),r=dt(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=Jf(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=qo("role",o.role,Xn,gi):delete n.raw.role_type}return o.aliases!==void 0&&(o.aliases.length?n.raw.aliases=o.aliases:delete n.raw.aliases),H("edit",`asset ${n.id}: ${i.join(", ")}`),Se(e),`${n.id} ${i.join("+")} ${o.name??n.name}`+$e(e,r)}function $E(e,t,n,o,i){let r=Lr(t,"state",i,NE),s=dt(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),H("edit",`state ${n.id}/${o.id}: ${r.join(", ")}`),Se(e),`${n.id}/${o.id} ${r.join("+")} ${i.name??o.name}`+$e(e,s)}function Uf(e,t,n,o,i,r,s,c){let a=Ce(e,t);if(a.t!=="action")throw new Error(`${t} is a ${a.t}; insert needs a sibling action`);let d=a.action,p=dt(e),l={type:qo("type",o,zt,Rn),content:i};if(e.version===4&&(l.action_id=ho("ac",new Set(e.actions.keys()))),o==="dialogue"||o==="inner_thought"){if(!r)throw new Error(`a ${o} needs a speaker`);l.speaker=Gd(e,r),s!==void 0&&Bs(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),H("insert",`${l.action_id??`${d.scene.anchor}#${u}`} ${n} ${d.anchor}`),Se(e),`${l.action_id??`${d.scene.anchor}#${u}`} ${n} ${d.anchor} ${js(l)}`+$e(e,p)}function Cf(e,t,n,o="after"){let i=Ce(e,t);if(i.t!=="action")throw new Error(`${t} is a ${i.t}; move targets one action`);let r=Ce(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=dt(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),H("move",`${i.action.scene.anchor} -> ${r.action.scene.anchor}, identity ${i.action.anchor} preserved`),Se(e),`${i.action.anchor} ${o} ${r.action.anchor} (${i.action.scene.anchor} -> ${r.action.scene.anchor})`+$e(e,s)}function Bs(e,t,n){let o=e.version===4?"parenthetical":"emotion";n===null?delete t[o]:t[o]=n}function Pf(e,t){if(t===null){e.extend&&delete e.extend.timestamp;return}let n;try{n=eo(t).canonical}catch(o){throw o instanceof Xe?new Error(`${o.message} (got ${JSON.stringify(t)})`):o}e.extend={...e.extend??{},timestamp:n}}function Gd(e,t){let n=e.assets.find(a=>a.name===t||a.aliases.includes(t)),[o,i]=n?[t,void 0]:DE(t,"\xB7"),r=SE[o];if(r)return i?{kind:r,label:i}:{kind:r};let s=Ce(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 DE(e,t){let n=e.indexOf(t);return n<0?[e,void 0]:[e.slice(0,n),e.slice(n+t.length)]}function js(e){return Mr(String(e.content??""),40)}function Tf(e,t,n,o={}){let i=go(structuredClone(e.raw)),r=GE(i,t,n,o);return e.raw=i.raw,Se(e),r}function GE(e,t,n,o){if(t==="+"||Number(t)===e.episodes.length+1){let r={scenes:[]};return e.version===4&&(r.episode_id=ho("ep",new Set(e.eps.keys()))),e.raw.episodes.push(r),H("write",`appending episode ${e.episodes.length+1}`),vf(e,r,e.episodes.length+1,n,o,!0)}let i=Ce(e,t);if(i.t==="scene")return JE(e,i.scene,n,o);if(i.t==="ep")return vf(e,i.ep.raw,i.ep.no,n,o,!1);throw new Error(`write targets a scene or an episode (got ${i.t})`)}function JE(e,t,n,o){let i=dt(e),r=$f(e,t.raw,t,n,new Set(e.actions.keys()),o);return Se(e),Vf(t.anchor,r)+$e(e,i)}function Vf(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} ${js(n.raw)}`).join(`
184
+ `)}`:"")}function $f(e,t,n,o,i,r,s,c){let a=IE(e),{head:d,meta:p,body:l}=Af(o.split(`
185
+ `));if(d){let y=Rd(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?Vd(e,y.location,"location"):null,t.actors=y.cast.map(x=>Vd(e,x,"actor")),t.props=y.props.map(x=>Vd(e,x,"prop"))}let f=s??new Map((n?.actions??[]).map(y=>[y.anchor,y])),u=c??new Set,h=new Set,m=[],g=0,w=n?n.anchor:"this new scene";for(let y of l){let x=If(y,a);if(!x)continue;let S=x.anchor?f.get(x.anchor):void 0;if(x.anchor&&!S)throw new Error(`Anchor ${x.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 ${x.anchor} appears twice in ${w} \u2014 drop the anchor from the copy to make it a new action`);let _=S?S.raw:{};!S&&e.version===4&&(_.action_id=ho("ac",i)),_.type=qo("type",x.type,zt,Rn),_.content=x.content,x.type==="dialogue"||x.type==="inner_thought"?(_.speaker=Gd(e,x.speakerName),Bs(e,_,x.paren??null)):(delete _.speaker,Bs(e,_,null)),Pf(_,x.ts??null),S?(h.add(S.anchor),u.add(S.anchor)):g++,m.push(_)}if(!m.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(m.length&&!h.size&&(n?.actions.length??0)>0&&!r.allowDelete)throw new Error(`None of the ${m.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=m,{total:m.length,kept:h.size,created:g,dropped:s?[]:(n?.actions??[]).filter(y=>!h.has(y.anchor))}}function vf(e,t,n,o,i,r){let s=dt(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 _ of S.actions)f.set(_.anchor,_);let u=new Set,h=new Set,m=[],g=[],w=0;for(let S of d){let _=Rd(S.split(`
188
+ `)[0]),A=_.anchor?a.get(_.anchor):void 0;if(_.anchor&&!A)throw new Error(`Scene ${_.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?h.add(A.anchor):(e.version===4?b.scene_id=ho("scn",l):b.scene_id=`scn_${String(c.length+w+1).padStart(3,"0")}`,w++);let U=$f(e,b,A??null,S,p,i,f,u);m.push(b),g.push(Vf(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 x=c.filter(S=>!h.has(S.anchor));if(x.length&&!i.allowDelete)throw new Error(`This would delete ${x.length} whole scene(s) from episode ${n}: `+x.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 H("write",`episode ${n}: ${d.length} scene blocks, ${w} new, ${x.length} deleted`),t.scenes=m,Se(e),`EP${n}: ${m.length} scenes (${m.length-w} kept, ${w} new, ${x.length} deleted, ${y.length} actions deleted)
189
+ `+g.map(S=>" "+S.replace(/\n/g,`
191
190
  `)).join(`
192
- `)+(E.length?`
193
- deleted scenes: ${E.map(I=>I.anchor).join(", ")}`:"")+Ve(e,s)}function wd(e,t,n){let{name:o,states:i}=rf(t),r=Ue(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 Ef(e,t,n,o,i=!1){let r=Ue(e,t);if(r.t!=="scene")throw new Error(`${t} is a ${r.t}; ref targets one scene`);let s=r.scene,c=Ue(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=it(e);if(i){if(a.kind==="location"){if(s.location?.id!==a.id)throw new Error(`${s.anchor}'s location is ${s.location?Co(e,s.location.id):"empty"}, not ${a.name}`);s.raw.location=null}else{let m=s.raw[d],h=m.findIndex(w=>w[`${a.kind}_id`]===a.id);if(h<0)throw new Error(`${s.anchor} does not reference ${a.name}`);m.splice(h,1)}return H("ref",`${s.anchor} -= ${a.id}`),_e(e),`${s.anchor} removed ${a.name}`+Ve(e,p)}if(!o.length)throw new Error(`ref needs at least one state for ${a.name} (has: ${a.states.map(m=>m.name).join(", ")}) \u2014 nothing is implied, not even default`);let l=[...new Set(o.map(m=>{let h=a.states.filter(w=>w.name===m||w.id===m);if(!h.length)throw new Error(`${a.name} has no state "${m}" (has: ${a.states.map(w=>w.name).join(", ")})`);if(h.length>1)throw new Error(`${a.name} has ${h.length} states named "${m}"; use the state id`);return h[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 m=s.raw[d],h=m.findIndex(w=>w[f]===a.id);h<0?(m.push(u),g="added"):(m[h]=u,g="restated")}return H("ref",`${s.anchor} ${g} ${a.id} = [${l.join(", ")}]`),_e(e),`${s.anchor} ${g} ${a.name}(${l.map(m=>To(e,a.id,m)).join("+")})`+Ve(e,p)}function _f(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=it(e),s=Ed(e,o),c=s.filter(p=>(i.lastIndex=0,i.test(p.content)));if(H("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}
191
+ `)+(x.length?`
192
+ deleted scenes: ${x.map(S=>S.anchor).join(", ")}`:"")+$e(e,s)}function Vd(e,t,n){let{name:o,states:i}=kf(t),r=Ce(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 Df(e,t,n,o,i=!1){let r=Ce(e,t);if(r.t!=="scene")throw new Error(`${t} is a ${r.t}; ref targets one scene`);let s=r.scene,c=Ce(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=dt(e);if(i){if(a.kind==="location"){if(s.location?.id!==a.id)throw new Error(`${s.anchor}'s location is ${s.location?Fo(e,s.location.id):"empty"}, not ${a.name}`);s.raw.location=null}else{let m=s.raw[d],g=m.findIndex(w=>w[`${a.kind}_id`]===a.id);if(g<0)throw new Error(`${s.anchor} does not reference ${a.name}`);m.splice(g,1)}return H("ref",`${s.anchor} -= ${a.id}`),Se(e),`${s.anchor} removed ${a.name}`+$e(e,p)}if(!o.length)throw new Error(`ref needs at least one state for ${a.name} (has: ${a.states.map(m=>m.name).join(", ")}) \u2014 nothing is implied, not even default`);let l=[...new Set(o.map(m=>{let g=a.states.filter(w=>w.name===m||w.id===m);if(!g.length)throw new Error(`${a.name} has no state "${m}" (has: ${a.states.map(w=>w.name).join(", ")})`);if(g.length>1)throw new Error(`${a.name} has ${g.length} states named "${m}"; 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 h;if(a.kind==="location")h=s.location?s.location.id===a.id?"restated":"replaced":"set",s.raw.location=u;else{let m=s.raw[d],g=m.findIndex(w=>w[f]===a.id);g<0?(m.push(u),h="added"):(m[g]=u,h="restated")}return H("ref",`${s.anchor} ${h} ${a.id} = [${l.join(", ")}]`),Se(e),`${s.anchor} ${h} ${a.name}(${l.map(m=>Yo(e,a.id,m)).join("+")})`+$e(e,p)}function Gf(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=dt(e),s=$d(e,o),c=s.filter(p=>(i.lastIndex=0,i.test(p.content)));if(H("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}
194
193
  ${" ".repeat(a)} - ${p.content}
195
194
  ${" ".repeat(a)} + ${l}`});if(!o.apply)return`${c.length} action(s) would change (dry run \u2014 pass apply to write)
196
195
  `+d.join(`
197
- `);for(let p of c)i.lastIndex=0,p.raw.content=p.content.replace(i,n);return _e(e),H("replace",`wrote ${c.length} actions`),`${c.length} action(s) changed`+Ve(e,r)+`
196
+ `);for(let p of c)i.lastIndex=0,p.raw.content=p.content.replace(i,n);return Se(e),H("replace",`wrote ${c.length} actions`),`${c.length} action(s) changed`+$e(e,r)+`
198
197
  `+d.join(`
199
- `)}function Vo(e,t,n,o){if(!n.has(t))throw new Error(`${e} must be one of ${o.join(" | ")} (got "${t}")`);return t}function xf(e){return Vo("importance",e,It,_n)}function xi(e){return e.version===4?Me(e.raw):lt(e.raw)}function Sf(e){let t=xi(e);return[`${e.episodes.length} episodes / ${e.scenes.size?[...new Set(e.episodes.flatMap(o=>o.scenes))].length:0} scenes / ${to(e).length} actions \u2014 ${t.ok?"ok":`${t.errors.length} error(s)`}`+(t.warnings.length?`, ${t.warnings.length} warning(s)`:""),...Id([...t.errors.map(o=>["error",o]),...t.warnings.map(o=>["warning",o])])].join(`
200
- `)}function Sd(e,t={}){let n=xi(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)),H("issues",`${o.length} matching issue(s)`),o.length?Id(o).join(`
201
- `):"No issues."}function Id(e){return e.map(([t,n])=>`${t} ${n.code} ${n.path} ${n.message}`+(n.repair_hint?`
202
- fix: ${n.repair_hint}`:""))}function it(e){return xi(e)}function Ve(e,t){let n=xi(e),o=[...Ba(t.errors,n.errors).map(i=>["error",i]),...Ba(t.warnings,n.warnings).map(i=>["warning",i])];return o.length?(H("check",`${o.length} issue(s) introduced by this edit`),`
198
+ `)}function qo(e,t,n,o){if(!n.has(t))throw new Error(`${e} must be one of ${o.join(" | ")} (got "${t}")`);return t}function Jf(e){return qo("importance",e,Mt,Ln)}function Pi(e){return e.version===4?Le(e.raw):yt(e.raw)}function Bf(e){let t=Pi(e);return[`${e.episodes.length} episodes / ${e.scenes.size?[...new Set(e.episodes.flatMap(o=>o.scenes))].length:0} scenes / ${En(e).length} actions \u2014 ${t.ok?"ok":`${t.errors.length} error(s)`}`+(t.warnings.length?`, ${t.warnings.length} warning(s)`:""),...Bd([...t.errors.map(o=>["error",o]),...t.warnings.map(o=>["warning",o])])].join(`
199
+ `)}function Jd(e,t={}){let n=Pi(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)),H("issues",`${o.length} matching issue(s)`),o.length?Bd(o).join(`
200
+ `):"No issues."}function Bd(e){return e.map(([t,n])=>`${t} ${n.code} ${n.path} ${n.message}`+(n.repair_hint?`
201
+ fix: ${n.repair_hint}`:""))}function dt(e){return Pi(e)}function $e(e,t){let n=Pi(e),o=[...ac(t.errors,n.errors).map(i=>["error",i]),...ac(t.warnings,n.warnings).map(i=>["warning",i])];return o.length?(H("check",`${o.length} issue(s) introduced by this edit`),`
203
202
  introduced ${o.length} issue(s):
204
- `+Id(o).join(`
205
- `)):""}var Ad={actor:"actors",location:"locations",prop:"props"},df={actor:"act",location:"loc",prop:"prp"};function If(e,t,n,o,i="featured",r=[]){if(!n.trim())throw new Error("asset needs a name");let s=it(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=Ad[t],d=e.version===4?no(df[t],new Set(e.assets.map(l=>l.id))):`${df[t]}_${String(e.raw[a].length+1).padStart(3,"0")}`,p={[`${t}_id`]:d,[`${t}_name`]:n,importance:xf(i),description:o,states:[{state_id:"default",state_name:n,description:o}]};return r.length&&(p.aliases=r),e.raw[a].push(p),H("asset",`${t} ${d} "${n}" + default state`),_e(e),`${d} ${n} ${t} states: default`+Ve(e,s)}function Af(e,t,n,o){let i=Ue(e,t);if(i.t!=="asset")throw new Error(`${t} is a ${i.t}; state targets an asset`);let r=it(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?no("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}),H("state",`${i.asset.id} + ${s} "${n}"`),_e(e),`${i.asset.id}/${s} ${n} (${i.asset.name} now has ${i.asset.states.length+1} states)`+Ve(e,r)}function mx(e,t){let n=Ue(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 kf(e,t,n,o,i=!1){let{raw:r,label:s}=mx(e,t),c=r.extend??{};if(!n){let a=Object.keys(c);return a.length?`${s} extend:
203
+ `+Bd(o).join(`
204
+ `)):""}var Kd={actor:"actors",location:"locations",prop:"props"},Rf={actor:"act",location:"loc",prop:"prp"};function Kf(e,t,n,o,i="featured",r=[]){if(!n.trim())throw new Error("asset needs a name");let s=dt(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=Kd[t],d=e.version===4?ho(Rf[t],new Set(e.assets.map(l=>l.id))):`${Rf[t]}_${String(e.raw[a].length+1).padStart(3,"0")}`,p={[`${t}_id`]:d,[`${t}_name`]:n,importance:Jf(i),description:o,states:[{state_id:"default",state_name:n,description:o}]};return r.length&&(p.aliases=r),e.raw[a].push(p),H("asset",`${t} ${d} "${n}" + default state`),Se(e),`${d} ${n} ${t} states: default`+$e(e,s)}function jf(e,t,n,o){let i=Ce(e,t);if(i.t!=="asset")throw new Error(`${t} is a ${i.t}; state targets an asset`);let r=dt(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?ho("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}),H("state",`${i.asset.id} + ${s} "${n}"`),Se(e),`${i.asset.id}/${s} ${n} (${i.asset.name} now has ${i.asset.states.length+1} states)`+$e(e,r)}function BE(e,t){let n=Ce(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 zf(e,t,n,o,i=!1){let{raw:r,label:s}=BE(e,t),c=r.extend??{};if(!n){let a=Object.keys(c);return a.length?`${s} extend:
206
205
  `+a.map(d=>` ${d} = ${JSON.stringify(c[d])}`).join(`
207
- `):`${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,H("ext",`${s} -= ${n}`),_e(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},H("ext",`${s} extend.${n} = ${o}`),_e(e),`${s} extend.${n} = ${JSON.stringify(o)}`}function bf(e,t,n={}){let o=Ue(e,t),i=it(e);if(o.t==="action"){let r=o.action.scene.raw.actions;return r.splice(r.indexOf(o.action.raw),1),H("del",`action ${o.action.anchor} from ${o.action.scene.anchor}`),_e(e),`deleted ${o.action.anchor} ${Ns(o.action.raw)}`+Ve(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),H("del",`scene ${o.scene.anchor} (${o.scene.actions.length} actions)`),_e(e),`deleted scene ${o.scene.anchor} with ${o.scene.actions.length} action(s)`+Ve(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),H("del",`episode ${o.ep.no}`),_e(e),`deleted episode ${o.ep.no} (${o.ep.id}) with ${o.ep.scenes.length} scene(s) / ${r} action(s)`}if(o.t==="asset")return gx(e,o.asset,n)+Ve(e,i);if(o.t==="state")return hx(e,o.asset,o.state,n)+Ve(e,i);throw new Error(`del takes an action, scene, episode, asset or state (got ${o.t})`)}function Of(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:to(e).filter(o=>o.speaker?.id===t)}}function gx(e,t,n){let{scenes:o,speakers:i}=Of(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 kd(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=Ad[t.kind],c=e.raw[s];return c.splice(c.indexOf(t.raw),1),H("del",`asset ${t.id}, stripped ${o.length} scene refs + ${i.length} speakers`),_e(e),`deleted ${t.kind} ${t.id} ${t.name}`+(r?`
208
- stripped ${o.length} scene reference(s) and ${i.length} speaker(s)`:"")}function hx(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=to(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=`
209
- ${d?"rewired":"cleared"} ${i.length} scene binding(s) and ${r.length} speaker(s)${d?` to ${To(e,t.id,d)}`:""}`}let a=t.raw.states;return a.splice(a.findIndex(d=>d.state_id===n.id),1),H("del",`state ${t.id}/${n.id}`),_e(e),`deleted state ${t.id}/${n.id} ${n.name}`+c}function kd(e,t,n){let o=Ue(e,t),i=Ue(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=it(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 m=c.states.find(w=>w.name===g.name);if(m){p.set(g.id,m.id);continue}if(g.id==="default"){p.set(g.id,"default");continue}let h=e.version===4?no("st",d):`st_${String(c.states.length+p.size).padStart(3,"0")}`;c.raw.states.push({state_id:h,state_name:g.name,description:g.desc}),p.set(g.id,h)}let{scenes:l,speakers:f}=Of(e,s.id);for(let g of l)for(let m of["location","actors","props"]){let h=g.raw[m],w=m==="location"?h?[h]:[]:h??[];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(E=>p.get(E)??"default"))].sort():y.state_id=p.get(y.state_id)??"default");if(m!=="location"&&Array.isArray(h)){let y=[];for(let E of h){let I=y.find(_=>_[a]===E[a]);if(!I){y.push(E);continue}e.version===4&&(I.state_ids=[...new Set([...I.state_ids,...E.state_ids])].sort())}g.raw[m]=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[Ad[s.kind]];return u.splice(u.indexOf(s.raw),1),H("merge",`${s.id} -> ${c.id}: ${l.length} scenes, ${f.length} speakers`),_e(e),`merged ${s.id} ${s.name} into ${c.id} ${c.name}
210
- moved ${l.length} scene reference(s), ${f.length} speaker(s), ${[...p].filter(([g,m])=>g!==m).length} state mapping(s)`+Ve(e,r)}var oo="\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 Ge(e){let t=Se(e);if(!vf.existsSync(t))throw new x("Local script file not found.",{exitCode:b,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 ad(t)}function ue(e,t){let n=e[t];return typeof n=="string"?n:void 0}function $o(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:b,errorCode:"OPTION_NOT_NUMBER",data:{actual:[String(n)]}});return o}function fe(e,t=0){return(e._args??[])[t]??""}function bd(e){return Array.isArray(e)?e.map(String):typeof e=="string"?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Xe(e,t,n=()=>({})){try{let o=e();return[{text:o,data:{op:t,changed:!1,text:o,...n()}},B]}catch(o){throw o instanceof x?o:new x(o instanceof Error?o.message:String(o),{exitCode:b,errorCode:o?.code??"SCRIPT_TOOL_FAILED"})}}function Rf(e,t){let n=ae(e.command("read [addr]"),"read").description(`\u8BFB\u4EFB\u610F\u8282\u70B9\uFF1B\u4E0D\u7ED9\u5730\u5740\u8FD4\u56DE\u5267\u672C\u5361\u3002${oo}`).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(q(y=>{let E=Ge(y);return Xe(()=>Ls(E,fe(y),{...y.outline?{depth:"outline"}:{},...y.plain?{plain:!0}:{},...$o(y,"context")!==void 0?{context:$o(y,"context")}:{}}),"read",()=>fe(y)?{}:{document:E.raw})},t));Ae(n,[oo]);let o=ae(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(q(y=>Xe(()=>{let E=Ge(y),I=fe(y);return[`## \u573A\u7ED3\u6784
211
- ${Ls(E,I,{depth:"outline"})}`,`## \u6B63\u6587
212
- ${Ls(E,I)}`,`## \u5F53\u524D\u6821\u9A8C\u95EE\u9898
213
- ${Sd(E,{})}`].join(`
214
-
215
- `)},"scan"),t));Ae(o,["\u96C6\u53F7\uFF0C\u4ECE 1 \u5F00\u59CB"]);let i=ae(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${oo}`).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(q(y=>Xe(()=>pf(Ge(y),fe(y),{...ue(y,"in")?{in:ue(y,"in")}:{},...ue(y,"speaker")?{speaker:ue(y,"speaker")}:{},...ue(y,"type")?{type:ue(y,"type")}:{},...$o(y,"limit")!==void 0?{limit:$o(y,"limit")}:{},...y.full?{full:!0}:{}}),"find"),t));Ae(i,["\u6B63\u5219\uFF1B\u53EA\u6309 speaker/type \u8FC7\u6EE4\u65F6\u53EF\u7701\u7565"]);let r=ae(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(q(y=>{let E=hd(Ge(y),fe(y),{offset:$o(y,"offset"),limit:$o(y,"limit"),context:$o(y,"context")});return[{text:yd(E),data:{op:"refs",changed:!1,...E}},B]},t));Ae(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=ae(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(q(y=>{let E=Ge(y);return Xe(()=>lf(E,fe(y)),"span",()=>({rows:[_d(E,fe(y))]}))},t));Ae(s,[`${oo}\uFF0C\u6216 \`\u8D77ID..\u6B62ID\``]),ae(e.command("validate"),"read").description("\u8DD1\u6574\u672C\u6821\u9A8C").action(q(y=>{let E=Ge(y),I=xi(E);return[{text:Sf(E),data:{op:"script.validate",changed:!1,passed:I.ok,script_path:E.path,stats:{actors:E.assets.filter(_=>_.kind==="actor").length,locations:E.assets.filter(_=>_.kind==="location").length,props:E.assets.filter(_=>_.kind==="prop").length,episodes:E.episodes.length,scenes:E.episodes.reduce((_,A)=>_+A.scenes.length,0),actions:to(E).length},issues:[...I.errors.map(_=>({..._,severity:"error"})),...I.warnings.map(_=>({..._,severity:"warning"}))]}},I.ok?B:Dn]},t)),ae(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(q(y=>Xe(()=>Sd(Ge(y),{...ue(y,"severity")?{severity:ue(y,"severity")}:{},...ue(y,"code")?{code:ue(y,"code")}:{}}),"issues"),t));let c=ae(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${oo}`).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(q(y=>{let E={};for(let I of["content","speaker","type","name","desc","importance","role","space","time","title","synopsis","logline","theme","worldview","style","main"]){let _=ue(y,I);_!==void 0&&(E[I]=_)}for(let I of["paren","ts","transition"])if(y[I]===!1)E[I]=null;else{let _=ue(y,I);_!==void 0&&(E[I]=_)}return y.alias!==void 0&&(E.aliases=bd(y.alias)),Xe(()=>uf(Ge(y),fe(y),E),"edit")},t));Ae(c,[oo]);let a=ae(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(q(y=>Xe(()=>ff(Ge(y),fe(y),y.before?"before":"after",ue(y,"type"),fe(y,1),ue(y,"speaker"),ue(y,"paren")),"insert"),t));Ae(a,["\u76F8\u90BB action \u7684\u5730\u5740","\u65B0 action \u7684\u6B63\u6587"]);let d=ae(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(q(y=>Xe(()=>mf(Ge(y),fe(y),fe(y,1),y.before?"before":"after"),"move"),t));Ae(d,["\u8981\u632A\u7684 action","\u76EE\u6807\u90BB\u5C45 action"]);let p=ae(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(q(async y=>{let E=await import("node:fs"),I=ue(y,"file"),_=I?E.readFileSync(I,"utf8"):E.readFileSync(0,"utf8");return Xe(()=>hf(Ge(y),fe(y),_,{allowDelete:!!y.allow_delete}),"write")},t));Ae(p,["\u573A / \u96C6\u5730\u5740\uFF0C\u6216 `+` \u8FFD\u52A0\u65B0\u96C6"]);let l=ae(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(q(y=>Xe(()=>_f(Ge(y),fe(y),fe(y,1),{...ue(y,"in")?{in:ue(y,"in")}:{},...ue(y,"speaker")?{speaker:ue(y,"speaker")}:{},...ue(y,"type")?{type:ue(y,"type")}:{},...y.apply?{apply:!0}:{}}),"replace"),t));Ae(l,["\u6B63\u5219","\u66FF\u6362\u6210\u4EC0\u4E48"]);let f=ae(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",wx,[]).option("--remove","\u5220\u9664\u6574\u6761\u5F15\u7528").action(q(y=>Xe(()=>Ef(Ge(y),fe(y),fe(y,1),bd(y.state).flatMap(E=>E.split(",")).map(E=>E.trim()).filter(Boolean),!!y.remove),"ref"),t));Ae(f,["\u573A\u5730\u5740","\u4EBA\u7269 / \u5730\u70B9 / \u9053\u5177\u7684\u540D\u5B57\u6216 ID"]);let u=ae(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(q(y=>Xe(()=>If(Ge(y),fe(y),fe(y,1),ue(y,"desc")??"",ue(y,"importance")??"featured",bd(y.alias)),"asset"),t));Ae(u,["actor | location | prop","\u540D\u5B57"]);let g=ae(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(q(y=>Xe(()=>Af(Ge(y),fe(y),fe(y,1),ue(y,"desc")??""),"state"),t));Ae(g,["\u8D44\u4EA7\u540D\u6216 ID","\u72B6\u6001\u540D"]);let m=ae(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(q(y=>Xe(()=>bf(Ge(y),fe(y),{...ue(y,"replacement")?{replacement:ue(y,"replacement")}:{},...y.force?{force:!0}:{}}),"del"),t));Ae(m,[oo]);let h=ae(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(q(y=>Xe(()=>kd(Ge(y),fe(y),fe(y,1)),"merge"),t));Ae(h,["\u88AB\u5E76\u5165\u7684\u8D44\u4EA7","\u4FDD\u7559\u7684\u8D44\u4EA7"]);let w=ae(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(q(y=>Xe(()=>kf(Ge(y),fe(y),fe(y,1)||void 0,fe(y,2)||void 0,!!y.remove),"ext"),t));Ae(w,[oo,"extend key","\u503C"])}function wx(e,t){return[...t,e]}import*as eh from"node:path";import*as Ii from"node:fs";import*as Si from"node:path";var Ex=[".txt",".md",".docx"],vd={".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"},_r=class extends Error{constructor(n){super(`Unsupported input: ${n}`);this.received=n}received};function Od(e){return Si.extname(e).toLowerCase()}function Mf(e){return Object.hasOwn(vd,e)}function un(e){if(Ii.statSync(e).isDirectory()){let o=Ii.readdirSync(e).filter(r=>!r.startsWith(".")&&Od(r)===".pdf"&&Ii.statSync(Si.join(e,r)).isFile()).sort().map(r=>Si.join(e,r)),i=Ii.readdirSync(e).filter(r=>!r.startsWith(".")).filter(r=>Mf(Od(r))).sort().map(r=>Si.join(e,r));if(o.length&&i.length)throw new _r("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 _r(`directory has no supported video or PDF files: ${e}`);return{kind:"video-directory",path:e,files:i}}let n=Od(e);if(n===".pdf")return{kind:"comic-file",path:e,ext:n};if(Ex.includes(n))return{kind:"text",path:e,ext:n};if(Mf(n))return{kind:"video-file",path:e,ext:n};throw new _r(`file extension ${n||"(none)"} is not supported by ingest (txt/md/docx/video/pdf only)`)}var Ln={createExecutor:zu};import*as op from"node:fs";import*as Li from"node:path";var fn=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();var xr=e=>String(e).padStart(3,"0"),Rd=e=>e.normalize("NFC").replace(/\s+/g," ").trim();function Lf(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=>Rd(g.name)===Rd(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_${xr(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_${xr(s)}`,scenes:[]},n.push(i)),c++,r={identity_key:d("scene",l.source),scene_id:`scn_${xr(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 Sr=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=Rd(t),i=this.byNorm.get(o);return i||(i={provisional_id:`${this.prefix}_${xr(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=fn(n),i=t.states.find(s=>fn(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 _x(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 Us(e){let t=0,n=()=>`st_${xr(++t)}`,o=new Sr("act","actor",n),i=new Sr("loc","location",n),r=new Sr("prp","prop",n),s={episode:{},scene:{},action:{}},c={episode:new Set,scene:new Set,action:new Set},a=(u,g,m)=>{if(!m||c[u].has(m))throw new Error(`Duplicate or missing ${u} source identity: ${m}`);c[u].add(m),s[u][g]=m},d=(u,g,m,h)=>{let w=u.ensure(g.name,m),y={[h]: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((m,h)=>{let w=`${u.episode_id}/${m.scene_id}`;a("scene",w,m.identity_key);let y={episode:g,scene:h},E=m.location?d(i,m.location,y,"location_id"):null,I=m.actors.map(k=>d(o,k,y,"actor_id")),_=m.props.map(k=>d(r,k,y,"prop_id")),A=m.actions.map((k,P)=>{a("action",`${w}#${P}`,k.identity_key);let O={type:k.type,content:k.content};if(k.speaker)if("name"in k.speaker){let S=o.ensure(k.speaker.name,y),L={actor_id:S.provisional_id};k.speaker.state!==void 0&&(L.state_id=o.stateId(S,k.speaker.state)),O.speaker=L}else O.speaker=k.speaker.label!==void 0?{kind:k.speaker.kind,label:k.speaker.label}:{kind:k.speaker.kind};return(k.type==="dialogue"||k.type==="inner_thought")&&(k.parenthetical!==void 0?O.emotion=k.parenthetical:k.emotion!==void 0&&(O.emotion=k.emotion)),k.extend!==void 0&&(O.extend=k.extend),O});return{scene_id:m.scene_id,...m.environment?{environment:m.environment}:{},location:E,actors:I,props:_,actions:A}})})),l=(u,g,m)=>u.list().map(h=>({[g]:h.provisional_id,[m]:h.names[0]??h.provisional_id,aliases:h.names.slice(1),description:"",states:_x(h)}));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 Nf(e,t={}){let n=t.maxChars??500,o=e.split(`
216
- `),i=[],r=0,s=0,c=a=>{let d=o.slice(r,a).join(`
217
- `);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 Uf=["episode","scene","action","dialogue","inner_thought","transition","note"];var xx={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 io(e){if(typeof e!="string")return;let t=e.normalize("NFC").replace(/\s+/g,"").trim().toLocaleLowerCase();return xx[t]}var ge=class extends Error{constructor(n,o){super(`line ${o}: ${n}`);this.line=o}line};function ki(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bt(e,t,n){for(let o of Object.keys(e))if(!t.includes(o))throw new ge(`unknown field '${o}'`,n)}function Sx(e,t){if(!ki(e))throw new ge("missing source",t);Bt(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 ge("source needs integer chunk/line_start/line_end",t);if(o>=i)throw new ge("source line_start must be < line_end",t);return{chunk:n,line_start:o,line_end:i}}function Ai(e,t,n){let o=e[t];if(typeof o!="string"||o==="")throw new ge(`'${t}' must be a non-empty string`,n);return o}function ro(e,t,n){if(!(t in e)||e[t]===void 0)return;let o=e[t];if(typeof o!="string"||o==="")throw new ge(`'${t}' must be a non-empty string`,n);return o}function Pf(e,t,n){if(!Array.isArray(e))throw new ge(`'${t}' must be an array`,n);return e.map(o=>{if(!ki(o))throw new ge(`'${t}' entries must be objects`,n);Bt(o,["name","state"],n);let i={name:Ai(o,"name",n)},r=ro(o,"state",n);return r!==void 0&&(i.state=r),i})}function Ix(e,t){if(!ki(e))throw new ge("dialogue/inner_thought needs a speaker",t);if("kind"in e){Bt(e,["kind","label"],t);let r=e.kind;if(typeof r!="string"||!En.includes(r))throw new ge(`speaker.kind must be one of ${En.join("|")}`,t);let s={kind:r},c=ro(e,"label",t);return c!==void 0&&(s.label=c),s}Bt(e,["name","state"],t);let n=Ai(e,"name",t);if(!/[\p{L}\p{N}]/u.test(n))throw new ge("speaker.name must contain a letter or number",t);let o={name:n},i=ro(e,"state",t);return i!==void 0&&(o.state=i),o}function Ax(e,t){let n=e.kind;if(typeof n!="string"||!Uf.includes(n))throw new ge(`unknown or missing kind '${String(n)}'`,t);let o=Sx(e.source,t);switch(n){case"episode":{Bt(e,["kind","episode","title","source"],t);let i=e.episode;if(typeof i!="number"||!Number.isInteger(i))throw new ge("episode must be an integer",t);let r={kind:n,episode:i,source:o},s=ro(e,"title",t);return s!==void 0&&(r.title=s),r}case"scene":{Bt(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 ge("scene must be an integer",t);i.scene=e.scene}if("environment"in e&&e.environment!==void 0){if(!ki(e.environment))throw new ge("environment must be an object",t);Bt(e.environment,["space","time"],t);let r={},s=ro(e.environment,"space",t);s!==void 0&&(r.space=s);let c=ro(e.environment,"time",t);if(c!==void 0){let a=io(c);if(!a)throw new ge("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(!ki(e.location))throw new ge("location must be an object",t);Bt(e.location,["name","state"],t);let r={name:Ai(e.location,"name",t)},s=ro(e.location,"state",t);s!==void 0&&(r.state=s),i.location=r}return"actors"in e&&e.actors!==void 0&&(i.actors=Pf(e.actors,"actors",t)),"props"in e&&e.props!==void 0&&(i.props=Pf(e.props,"props",t)),i}case"action":case"transition":{Bt(e,["kind","content","source"],t);let i=Ai(e,"content",t);return{kind:n,content:i,source:o}}case"dialogue":case"inner_thought":{Bt(e,["kind","speaker","content","emotion","source"],t);let i=Ai(e,"content",t),r=Ix(e.speaker,t),s={kind:n,speaker:r,content:i,source:o},c=ro(e,"emotion",t);return c!==void 0&&(s.emotion=c),s}case"note":{Bt(e,["kind","content","category","source"],t);let i=Ai(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 ge("note.category must be author_note|format_note|unclassified",t);r.category=s}return r}default:throw new ge(`unhandled kind '${n}'`,t)}}function Ir(e,t=0){let n=[],o=e.split(`
218
- `);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 ge("invalid JSON",i+1+t)}if(!ki(s))throw new ge("record must be a JSON object",i+1+t);n.push(Ax(s,i+1+t))}return n}var W=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),Do=e=>{let t=/[((]/.exec(e);return!t||t.index===0?e:e.slice(0,t.index).trim()},kx=e=>e.startEp===e.endEp?`\u7B2C${e.startEp}\u96C6`:`\u7B2C${e.startEp}\u96C6\u2013\u7B2C${e.endEp}\u96C6`,Ld=e=>e.startEp===e.endEp?`\u7B2C${e.startEp}\u96C6`:`\u7B2C${e.startEp}\u96C6\u2013\u7B2C${e.endEp}\u96C6`,$f=()=>({newEntities:[],merges:[],looks:[],lookChanges:[],subEvents:[],summary:""}),Df=()=>({entities:[],lookChanges:{},recent:[],synopsis:[]}),Nd={recentEpisodes:6,synopsisChars:3500,arcFold:10},bx=1e4;function Gf(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 Jf(e,t=bx){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 Ox={actor:"\u4EBA\u7269",location:"\u573A\u666F",prop:"\u9053\u5177"};function Lt(e,t){let n=W(t);return e.entities.find(o=>W(o.canonical)===n||o.aliases.some(i=>W(i)===n))}var Cf=(e,t)=>{W(t)!==W(e.canonical)&&!e.aliases.some(n=>W(n)===W(t))&&e.aliases.push(t)},vx=["\u5E74\u8F7B","\u5E74\u8001","\u5E74\u5E7C","\u5E74\u5C11","\u4E2D\u5E74","\u9752\u5E74","\u5C11\u5E74","\u8001\u5E74","\u5E7C\u5E74","\u8001","\u5C0F","\u5927","\u5C11","\u5E7C"];function Rx(e,t){let n=W(e),o=W(t);if(n===o||!n.includes(o))return!1;let i=n.replace(o,"").trim();return i.length>0&&!vx.some(r=>i===r||i.startsWith(r))}function Mx(e){let t=e.filter(n=>e.some(o=>o!==n&&Rx(n,o)));return t.length?t.reduce((n,o)=>o.length>n.length?o:n):e[0]}var Tf=["\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"],Lx=["\u4F17\u4EBA","\u7FA4\u4F17","\u6C11\u4F17","\u89C2\u4F17","\u4EBA\u7FA4","\u4EBA\u4EEC","\u5927\u5BB6","\u767E\u59D3","\u5B98\u5175"],Nx=/^(?:一群|一众|全体|所有|几名|数名|多名|[0-9零一二两三四五六七八九十百千]+名?)/;function et(e){let t=W(e).replace(/[0-9零一二两三四五六七八九十百千]+名?$/,"").trim();return t?t.endsWith("\u4EEC")||Tf.includes(t)||Lx.some(n=>t.endsWith(n))?!0:Nx.test(t)&&Tf.some(n=>t.endsWith(n)):!1}function so(e,t){let n=Do(t);return Lt(e,n)?.canonical??n}function Ux(e,t){let n=W(t);return e.looks.find(o=>W(o.name)===n||o.aliases.some(i=>W(i)===n))?.name??t}var Px=["\u5E38\u6001","\u65E5\u5E38","\u5E73\u65F6","\u57FA\u7840","\u666E\u901A"];function Ud(e){if(e.looks.length!==0)return(e.looks.find(t=>Px.some(n=>t.name.includes(n)))??e.looks[0]).name}function Md(e,t,n,o){let i=W(Do(n));if(i)return e.entities.find(r=>r.kind===t&&r!==o&&(W(r.canonical)===i||r.aliases.some(s=>W(s)===i)))}function Vf(e){let t=[e.canonical,...e.aliases],n=Mx(t);W(n)!==W(e.canonical)&&(e.canonical=n,e.aliases=t.filter(o=>W(o)!==W(n)))}function Ar(e,t,n,o=n){for(let r of t.newEntities){let s=Do(r.name);if(!s)continue;let c=Md(e,r.kind,s);if(!c){let d=[];for(let p of r.aliases){let l=Do(p);l&&W(l)!==W(s)&&!Md(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=Do(d);p&&!Md(e,r.kind,p,c)&&Cf(c,p)}!c.description&&r.description&&(c.description=r.description);let a=c.looks.find(d=>W(d.name)===W(r.defaultLook.name));a?a.description=r.defaultLook.description:c.looks.unshift({name:r.defaultLook.name,aliases:[],description:r.defaultLook.description}),Vf(c)}for(let{from:r,into:s}of t.merges){let c=Do(s);if(!c)continue;let a=Lt(e,c);if(!a)continue;let d=Do(r);!d||W(d)===W(a.canonical)||Lt(e,d)||(Cf(a,d),Vf(a))}for(let{entity:r,names:s,description:c}of t.looks){let a=Lt(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=>W(f.name)===W(p)||d.some(u=>f.aliases.some(g=>W(g)===W(u))));if(l){c&&(l.description=c);for(let f of d)W(f)!==W(l.name)&&!l.aliases.some(u=>W(u)===W(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=so(e,r.entity),a=r.look.trim();if(!s||!c||!a)continue;let d=Lt(e,c),p=d?Ux(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=Lt(e,r);s&&(s.lastSeen=o)}return e.recent.push({startEp:n,endEp:o,summary:t.summary,subEvents:t.subEvents}),e}var Cx=e=>e.summary.length+e.subEvents.reduce((t,n)=>t+n.length,0);function Bf(e,t=Nd){for(;e.recent.length>t.recentEpisodes||e.recent.length>1&&e.recent.reduce((n,o)=>n+Cx(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 Pd(e,t=Nd){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 Kf(e,t,n=Nd){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 Tx=6;function Ps(e,t){let n=i=>t===void 0||i.lastSeen>=t-Tx,o=["# \u8BBE\u5B9A"];for(let i of["actor","location","prop"]){let r=e.entities.filter(s=>s.kind===i);if(r.length){o.push(`## ${Ox[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(`- ${Ld(i)}\uFF1A${i.line}`)}if(e.recent.length){o.push("","# \u6700\u8FD1");for(let i of e.recent){o.push(`## ${kx(i)}`),i.summary.trim()&&o.push(`\u6897\u6982\uFF1A${i.summary.trim()}`);for(let r of i.subEvents)o.push(`- ${r}`)}}return o.join(`
219
- `)}var Vx=/(?:^|[,。!?;:、\s“”"'((])(他们|她们|它们|其中一人|另一个人|前者|后者|对方|有人|两人|他|她|它)(?!人)/;function bi(e){let t=[],n=(o,i,r)=>{t.push({code:o,path:i,message:r})};return e.actors.forEach((o,i)=>{et(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=Vx.exec(a.content);l&&n("production_action_pronoun",`${p}.content`,`action uses ambiguous reference ${l[1]}`)}})})}),t}var He=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rt=e=>Array.isArray(e),Cs=e=>String(e).padStart(3,"0"),Cd=[{key:"actors",idField:"actor_id",prefix:"act"},{key:"locations",idField:"location_id",prefix:"loc"},{key:"props",idField:"prop_id",prefix:"prp"}];function Ts(e){if(!He(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 rt(t.episodes)?t.episodes:[])if(!(!He(a)||!rt(a.scenes))){for(let d of a.scenes)if(He(d)){He(d.location)&&r("locations",d.location.location_id);for(let p of rt(d.actors)?d.actors:[])He(p)&&r("actors",p.actor_id);for(let p of rt(d.props)?d.props:[])He(p)&&r("props",p.prop_id);for(let p of rt(d.actions)?d.actions:[])He(p)&&He(p.speaker)&&r("actors",p.speaker.actor_id)}}for(let{key:a,idField:d}of Cd)for(let p of rt(t[a])?t[a]:[])He(p)&&r(a,p[d]);for(let{key:a,prefix:d}of Cd)o[a].forEach((p,l)=>{n[a][p]=`${d}_${Cs(l+1)}`});for(let{key:a,idField:d}of Cd){let p=(rt(t[a])?t[a]:[]).filter(He),l=n[a],f=new Map;for(let u of p){let g=u[d],m=l[g]??g;u[d]=m;let h=0;for(let w of rt(u.states)?u.states:[]){if(!He(w)||typeof w.state_id!="string"||w.state_id==="default")continue;let y=`st_${Cs(++h)}`;n.states[w.state_id]=y,w.state_id=y}f.set(m,u)}t[a]=[...f.entries()].sort((u,g)=>u[0]<g[0]?-1:1).map(u=>u[1])}let s=0;(rt(t.episodes)?t.episodes:[]).forEach((a,d)=>{if(He(a)){if(typeof a.episode_id=="string"){let p=`ep_${Cs(d+1)}`;n.episodes[a.episode_id]=p,a.episode_id=p}for(let p of rt(a.scenes)?a.scenes:[])if(He(p)&&typeof p.scene_id=="string"){let l=`scn_${Cs(++s)}`;n.scenes[p.scene_id]=l,p.scene_id=l}}});let c=(a,d,p)=>{!He(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 rt(t.episodes)?t.episodes:[])if(!(!He(a)||!rt(a.scenes))){for(let d of a.scenes)if(He(d)){c(d.location,"location_id","locations");for(let p of rt(d.actors)?d.actors:[])c(p,"actor_id","actors");for(let p of rt(d.props)?d.props:[])c(p,"prop_id","props");for(let p of rt(d.actions)?d.actions:[])He(p)&&c(p.speaker,"actor_id","actors")}}return{script:t,idMap:n}}import{createHash as $x}from"node:crypto";function kr(e){let t=v(e).trim();if(!t.includes(":"))throw new x("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(!al.has(o)||!i)throw new x("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 ao(){return{version:3,actor:{},location:{},prop:{},state:{},episode:{},scene:{},action:{}}}function Nt(e,t){let n=e.get(t);if(n===void 0)throw new Error(`Missing mapped ID for ${t}`);return n}function Oi(e,t=ao(),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=(S,L,T,U)=>{let R=T[L];if(R!==void 0){if(!V(S,R))throw new Error(`Invalid persisted ${S} ID for ${L}: ${R}`);if(U.has(R))throw new Error(`Duplicate persisted ${S} ID: ${R}`);return U.add(R),R}let j=Io(S,U);return U.add(j),T[L]=j,j},c=(S,L)=>n[S]?.[L]??L;for(let S of e.actors){let L=s("actor",c("actor",S.actor_id),o.actor,r.actor);i.actor.set(S.actor_id,L)}for(let S of e.locations){let L=s("location",c("location",S.location_id),o.location,r.location);i.location.set(S.location_id,L)}for(let S of e.props){let L=s("prop",c("prop",S.prop_id),o.prop,r.prop);i.prop.set(S.prop_id,L)}let a=new Map,d=(S,L,T)=>{let U=new Map,R=new Set,j=c(S,L),Z=o.state[j]??{};o.state[j]=Z;let Oe=T.map(K=>{let ve;if(K.state_id==="default")ve="default";else{let Ze=n.state?.[L]?.[K.state_id]??K.state_id,N=Z[Ze];if(N!==void 0){if(!V("state",N))throw new Error(`Invalid persisted state ID for ${L}/${K.state_id}: ${N}`);if(R.has(N))throw new Error(`Duplicate persisted state ID on ${L}: ${N}`);ve=N}else ve=Io("state",R),Z[Ze]=ve}return R.add(ve),U.set(K.state_id,ve),{...K,state_id:ve}});return a.set(L,U),Oe},p=(S,L)=>L===void 0?void 0:Nt(a.get(S)??new Map,L),l=e.actors.map(S=>({...S,actor_id:Nt(i.actor,S.actor_id),states:d("actor",S.actor_id,S.states)})),f=e.locations.map(S=>({...S,location_id:Nt(i.location,S.location_id),states:d("location",S.location_id,S.states)})),u=e.props.map(S=>({...S,prop_id:Nt(i.prop,S.prop_id),states:d("prop",S.prop_id,S.states)})),g=S=>{if("actor_id"in S){let L=p(S.actor_id,S.state_id);return{actor_id:Nt(i.actor,S.actor_id),...L===void 0?{}:{state_id:L}}}return S.label===void 0?{kind:S.kind}:{kind:S.kind,label:S.label}},m=S=>{if(S.includes(":")){let[T,U]=kr(S);return Nt(T==="actor"?i.actor:T==="location"?i.location:i.prop,U)}let L=i.actor.get(S)??i.location.get(S)??i.prop.get(S);if(L===void 0)throw new Error(`Missing transition target mapping for ${S}`);return L},h=(S,L)=>{let T=s("action",L,o.action,r.action),U=S.transition_prompt===void 0?{}:{transition_prompt:{...S.transition_prompt,target:m(S.transition_prompt.target)}};if(S.type==="dialogue"||S.type==="inner_thought"){if(S.speaker===void 0)throw new Error(`Speaking action ${S.content.slice(0,40)} has no speaker`);return{action_id:T,type:S.type,content:S.content,speaker:g(S.speaker),...S.emotion===void 0?{}:{parenthetical:S.emotion},...U,...S.extend===void 0?{}:{extend:S.extend}}}return{action_id:T,type:S.type,content:S.content,...U,...S.extend===void 0?{}:{extend:S.extend}}},w=(S,L)=>[p(S,L??"default")??"default"],y=(S,L)=>{let T=new Map;for(let U of S){let R=Nt(i.actor,U.actor_id),j=T.get(R)??new Set;w(U.actor_id,U.state_id).forEach(Z=>j.add(Z)),T.set(R,j)}for(let U of L){if(U.speaker===void 0||!("actor_id"in U.speaker))continue;let R=U.speaker.actor_id,j=Nt(i.actor,R),Z=T.get(j)??new Set;w(R,U.speaker.state_id).forEach(Oe=>Z.add(Oe)),T.set(j,Z)}return[...T].map(([U,R])=>({actor_id:U,state_ids:[...R].sort()}))},E=S=>{let L=new Map;for(let T of S){let U=Nt(i.prop,T.prop_id),R=L.get(U)??new Set;w(T.prop_id,T.state_id).forEach(j=>R.add(j)),L.set(U,R)}return[...L].map(([T,U])=>({prop_id:T,state_ids:[...U].sort()}))},I=new Set,_=new Set,A=new Set,k={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(S=>{let L=n.episode?.[S.episode_id]??S.episode_id;I.add(L);let T=s("episode",L,o.episode,r.episode);return{...S,episode_id:T,scenes:S.scenes.map(U=>{let R=`${S.episode_id}/${U.scene_id}`,j=n.scene?.[R]??R;_.add(j);let Z=s("scene",j,o.scene,r.scene),Oe=new Map;return{...U,scene_id:Z,location:U.location===null?null:{location_id:Nt(i.location,U.location.location_id),state_ids:w(U.location.location_id,U.location.state_id)},actors:y(U.actors,U.actions),props:E(U.props),actions:U.actions.map((K,ve)=>{let Ze=`${R}#${ve}`,N=JSON.stringify(dn(K)),ie=(Oe.get(N)??0)+1;Oe.set(N,ie);let ye=$x("sha256").update(N).digest("hex"),dt=n.action?.[Ze]??`${j}:action:${ye}:${ie}`;return A.add(dt),h(K,dt)})}})}})},P=(S,L)=>{for(let T of Object.keys(S))L.has(T)||delete S[T]};P(o.actor,new Set(e.actors.map(S=>c("actor",S.actor_id)))),P(o.location,new Set(e.locations.map(S=>c("location",S.location_id)))),P(o.prop,new Set(e.props.map(S=>c("prop",S.prop_id)))),P(o.episode,I),P(o.scene,_),P(o.action,A);let O=[...e.actors.map(S=>({id:c("actor",S.actor_id),oldId:S.actor_id,states:S.states})),...e.locations.map(S=>({id:c("location",S.location_id),oldId:S.location_id,states:S.states})),...e.props.map(S=>({id:c("prop",S.prop_id),oldId:S.prop_id,states:S.states}))];P(o.state,new Set(O.map(S=>S.id)));for(let S of O)P(o.state[S.id]??{},new Set(S.states.map(L=>n.state?.[S.oldId]?.[L.state_id]??L.state_id)));return{script:k,identityMap:o}}import*as Zf from"node:fs";import*as jf from"node:fs";import zf from"jszip";import{XMLParser as Jx}from"fast-xml-parser";function Hf(e){return e==null?"":String(e)}function Ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ke(e){return Array.isArray(e)}function Qf(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,H("ext",`${s} -= ${n}`),Se(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},H("ext",`${s} extend.${n} = ${o}`),Se(e),`${s} extend.${n} = ${JSON.stringify(o)}`}function Hf(e,t,n={}){let o=Ce(e,t),i=dt(e);if(o.t==="action"){let r=o.action.scene.raw.actions;return r.splice(r.indexOf(o.action.raw),1),H("del",`action ${o.action.anchor} from ${o.action.scene.anchor}`),Se(e),`deleted ${o.action.anchor} ${js(o.action.raw)}`+$e(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),H("del",`scene ${o.scene.anchor} (${o.scene.actions.length} actions)`),Se(e),`deleted scene ${o.scene.anchor} with ${o.scene.actions.length} action(s)`+$e(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),H("del",`episode ${o.ep.no}`),Se(e),`deleted episode ${o.ep.no} (${o.ep.id}) with ${o.ep.scenes.length} scene(s) / ${r} action(s)`}if(o.t==="asset")return KE(e,o.asset,n)+$e(e,i);if(o.t==="state")return jE(e,o.asset,o.state,n)+$e(e,i);throw new Error(`del takes an action, scene, episode, asset or state (got ${o.t})`)}function Qf(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:En(e).filter(o=>o.speaker?.id===t)}}function KE(e,t,n){let{scenes:o,speakers:i}=Qf(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 jd(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=Kd[t.kind],c=e.raw[s];return c.splice(c.indexOf(t.raw),1),H("del",`asset ${t.id}, stripped ${o.length} scene refs + ${i.length} speakers`),Se(e),`deleted ${t.kind} ${t.id} ${t.name}`+(r?`
207
+ stripped ${o.length} scene reference(s) and ${i.length} speaker(s)`:"")}function jE(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=En(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 ${Yo(e,t.id,d)}`:""}`}let a=t.raw.states;return a.splice(a.findIndex(d=>d.state_id===n.id),1),H("del",`state ${t.id}/${n.id}`),Se(e),`deleted state ${t.id}/${n.id} ${n.name}`+c}function jd(e,t,n){let o=Ce(e,t),i=Ce(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=dt(e),s=o.asset,c=i.asset,a=`${s.kind}_id`,d=new Set(c.states.map(h=>h.id)),p=new Map;for(let h of s.states){let m=c.states.find(w=>w.name===h.name);if(m){p.set(h.id,m.id);continue}if(h.id==="default"){p.set(h.id,"default");continue}let g=e.version===4?ho("st",d):`st_${String(c.states.length+p.size).padStart(3,"0")}`;c.raw.states.push({state_id:g,state_name:h.name,description:h.desc}),p.set(h.id,g)}let{scenes:l,speakers:f}=Qf(e,s.id);for(let h of l)for(let m of["location","actors","props"]){let g=h.raw[m],w=m==="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(x=>p.get(x)??"default"))].sort():y.state_id=p.get(y.state_id)??"default");if(m!=="location"&&Array.isArray(g)){let y=[];for(let x of g){let S=y.find(_=>_[a]===x[a]);if(!S){y.push(x);continue}e.version===4&&(S.state_ids=[...new Set([...S.state_ids,...x.state_ids])].sort())}h.raw[m]=y}}for(let h of f)h.raw.speaker.actor_id=c.id,h.raw.speaker.state_id&&(h.raw.speaker.state_id=p.get(h.raw.speaker.state_id)??"default");let u=e.raw[Kd[s.kind]];return u.splice(u.indexOf(s.raw),1),H("merge",`${s.id} -> ${c.id}: ${l.length} scenes, ${f.length} speakers`),Se(e),`merged ${s.id} ${s.name} into ${c.id} ${c.name}
209
+ moved ${l.length} scene reference(s), ${f.length} speaker(s), ${[...p].filter(([h,m])=>h!==m).length} state mapping(s)`+$e(e,r)}import{z as Ut}from"zod";var zE=Ut.string().min(1),HE=Ut.array(Ut.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"),zs=Ut.number().min(0).max(1e3),Hs=Ut.object({page:Ut.number().int().min(1),kind:Ut.enum(["panel","bubble","text"]),box:Ut.object({top:zs,left:zs,bottom:zs,right:zs}).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")}),Qs=Ut.array(Hs).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 Nr(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 Ff=Ut.object({kind:Ut.literal("comic"),document_id:zE,pages:HE,regions:Qs.optional()}),Zo=Ut.object({scriptctl:Ut.object({source:Ff})});import{z as B}from"zod";var tt=B.string().min(1),Wo=B.array(tt),Yf=B.object({name:tt,description:tt}),Hd=B.string().length(0),qf=B.object({apparent_gender:B.string(),apparent_age:B.string(),face_shape:B.string(),brows_eyes:B.string(),nose:B.string(),mouth:B.string(),skin_features:B.string(),hair:B.string(),build:B.string(),persistent_marks:Wo,voice:Hd.describe("\u6F2B\u753B\u6CA1\u6709\u539F\u58F0\u97F3\u8F68\uFF0C\u586B\u7A7A\u4E32")}),QE=B.object({name:tt,kind:B.enum(["actor","location","prop"]),status:B.enum(["canonical","provisional"]),importance:B.enum(["featured","background"]),recognition_anchors:Wo,identity_profile:qf,appearance:B.string(),role:B.string(),states:B.array(Yf),aliases:Wo}),FE=B.object({new_entities:B.array(QE),enrich:B.array(B.object({name:tt,add_recognition_anchors:Wo,identity_profile_patch:qf,appearance:B.string(),role:B.string(),add_aliases:Wo,add_states:B.array(Yf)})),canonicalize:B.array(B.object({from_name:tt,canonical_name:tt,evidence:tt.describe("\u672C\u8BDD PDF \u9875\u7801\u548C\u76F4\u63A5\u51FA\u73B0\u7684\u59D3\u540D\u539F\u6587")}))}),Zf=B.array(B.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"),Wf="\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",Xf="\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",em=B.object({type:B.enum(["dialogue","inner_thought"]),content:tt,pages:Zf,regions:Qs,speaker:tt.describe(Wf),parenthetical:B.string()}),YE=B.discriminatedUnion("type",[B.object({type:B.enum(["action","transition"]),content:tt,pages:Zf,regions:Qs}),em]),tm=B.object({space:B.union([B.enum(["interior","exterior"]),Hd]),time:B.union([B.enum(["day","night","dawn","dusk"]),Hd]),location:B.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:B.array(B.object({name:tt,states:Wo})),props:Wo,actions:B.array(YE).min(1).describe(Xf)}),Qd=B.object({registry_delta:FE,synopsis:tt,scenes:B.array(tm).min(1),open_threads:B.object({opened:B.array(B.object({text:tt})),closed:B.array(B.object({ref:tt}))}),ignored_pages:B.array(B.object({page:B.number().int().min(1),reason:tt.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")}))}),nm=Qd.extend({scenes:B.array(tm.extend({actions:B.array(em.extend({type:B.enum(["action","transition","dialogue","inner_thought"]),speaker:B.string().describe(`${Wf}\uFF1Baction/transition \u586B\u7A7A\u4E32`)})).min(1).describe(Xf)})).min(1)});import*as Ie from"node:fs";import*as Et from"node:path";import{spawn as qE}from"node:child_process";import{createHash as ZE}from"node:crypto";import{PDFDocument as om}from"pdf-lib";var Fd=1200;function im(e,t){return new Promise((n,o)=>{let i=qE("pdftoppm",["-cropbox","-scale-to-x",String(Fd),"-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 E(`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 E(`PDF page rendering failed: ${r.trim()}`,{exitCode:k,errorCode:"VIEW_PDF_RENDER_FAILED",data:{actual:[e]}}))})})}async function Fs(e,t){let n=`review-pages/cropbox-w${Fd}-q92/${e.sha256}`,o=Et.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=>Ie.existsSync(Et.join(o,s)))){let s=`${o}.part`;Ie.rmSync(s,{recursive:!0,force:!0}),Ie.mkdirSync(s,{recursive:!0}),process.stderr.write(`\u6E32\u67D3\u6F2B\u753B\u539F\u9875 \xB7 ${e.title} \xB7 ${e.page_count} \u9875
210
+ `),await im(e.path,Et.join(s,"page"));for(let c of r)if(!Ie.existsSync(Et.join(s,c))||Ie.statSync(Et.join(s,c)).size===0)throw new E(`PDF renderer did not produce ${c}.`,{exitCode:k,errorCode:"VIEW_PDF_RENDER_FAILED"});Ie.rmSync(o,{recursive:!0,force:!0}),Ie.renameSync(s,o)}return r.map(s=>`${n}/${s}`)}async function rm(e,t,n){Hs.parse(t);let o=Nr([t.page],[t]);if(t.page>e.page_count||o.length)throw new Error(`Invalid comic region: ${o.join("; ")}`);let i=ZE("sha256").update(JSON.stringify(t)).digest("hex"),r=`review-pages/cropbox-w${Fd}-q92/${e.sha256}/regions/${i}.jpg`,s=Et.join(n,r);if(Ie.existsSync(s)&&Ie.statSync(s).size>0)return r;let c=await om.load(Ie.readFileSync(e.path)),a=await om.create(),[d]=await a.copyPages(c,[t.page-1]),p=d.getCropBox(),l=(d.getRotation().angle%360+360)%360,{left:f,right:u,top:h,bottom:m}=t.box,g=f/1e3,w=u/1e3,y=h/1e3,x=m/1e3,S=l===90?[y,g,x,w]:l===180?[1-w,y,1-g,x]:l===270?[1-x,1-w,1-y,1-g]:[g,1-x,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),Ie.mkdirSync(Et.dirname(s),{recursive:!0});let _=Ie.mkdtempSync(Et.join(Et.dirname(s),".region-"));try{let A=Et.join(_,"crop.pdf");Ie.writeFileSync(A,await a.save()),await im(A,Et.join(_,"page")),Ie.renameSync(Et.join(_,"page-1.jpg"),s)}finally{Ie.rmSync(_,{recursive:!0,force:!0})}return r}var WE=nt.object({episode:nt.number().int().positive(),document_id:nt.string().min(1),source_number:nt.number().nullable(),title:nt.string(),path:nt.string(),sha256:nt.string(),page_count:nt.number().int().positive(),size_bytes:nt.number()}),XE=nt.object({source:nt.object({kind:nt.enum(["comic-file","comic-directory"])}),episodes:nt.array(WE)});function qt(e){throw new E(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 e5(e){let t=ot.join(e,"manifest.json");if(!it.existsSync(t))return!1;let n=nt.object({source:nt.object({kind:nt.string()}).optional()}).parse(JSON.parse(it.readFileSync(t,"utf8")));return n.source?.kind==="comic-file"||n.source?.kind==="comic-directory"}async function am(e,t,n){let o=it.statSync(e).isDirectory()&&e5(e)?ot.resolve(e):ot.dirname(ot.resolve(t)),i=ot.join(o,"manifest.json");it.existsSync(i)||qt("Comic review needs the ingest manifest to verify source identity.");let r=XE.safeParse(JSON.parse(it.readFileSync(i,"utf8")));r.success||qt(`Invalid comic manifest: ${r.error.message}`);let s=r.data,c=go(JSON.parse(it.readFileSync(t,"utf8")));c.version!==4&&qt("Comic source review requires the ingested Script v4.");let a=c.episodes.filter(w=>!n?.length||n.includes(w.no));a.length||qt("No selected episodes exist in this script.");let d=ot.resolve(e)===o?void 0:it.statSync(e).isFile()?[ot.resolve(e)]:it.readdirSync(e).filter(w=>/\.pdf$/i.test(w)).map(w=>ot.resolve(e,w)),p=new Map;for(let w of d??[])p.set(sm("sha256").update(it.readFileSync(w)).digest("hex"),w);let l=new Map,f=[];for(let w of a){let y=new Set(w.scenes.flatMap(x=>x.actions.flatMap(S=>{let _=Zo.safeParse(S.raw.extend);return _.success?[_.data.scriptctl.source.document_id]:[]})));y.size||qt(`Episode ${w.no} has no comic document identity; cannot safely match an original PDF.`);for(let x of y){let S=s.episodes.find(U=>U.document_id===x);S||qt(`Unknown comic document: ${x}`),f.some(U=>U.document_id===x&&U.episode!==w.no)&&qt(`Comic document ${x} is bound to multiple script episodes.`);let _=d?p.get(S.sha256):ot.resolve(o,S.path);(!_||!it.existsSync(_))&&qt(`Original PDF missing or changed: ${S.title}`),sm("sha256").update(it.readFileSync(_)).digest("hex")!==S.sha256&&qt(`Original PDF content changed: ${S.title}`);let b={...S,path:_};l.set(x,b),f.push({document_id:x,episode:w.no,title:S.title,page_count:S.page_count})}}let u=new Map,h=ot.dirname(ot.resolve(t));function m(w){let y=l.get(w);return y||qt(`Comic document not available: ${w}`)}function g(w,y){return{path:w,label:y,data:it.readFileSync(w).toString("base64")}}return{documents:f,async page(w,y){let x=m(w);(!Number.isInteger(y)||y<1||y>x.page_count)&&qt(`Invalid page ${y} in ${w}.`);let S=u.get(w);S||(S=Fs(x,h),u.set(w,S));let _=await S;return g(ot.join(h,_[y-1]),`${w} \u7B2C ${y} \u9875\u6982\u89C8\uFF1B\u6587\u5B57\u4E0D\u6E05\u65F6\u7528 region \u653E\u5927`)},async region(w,y){let x=await rm(m(w),y,h);return g(ot.join(h,x),`${w} \u7B2C ${y.page} \u9875 ${JSON.stringify(y.box)}`)}}}import*as In from"node:fs";import*as Cr from"node:path";import{z as Wd}from"zod";import*as Vi from"node:fs";import*as Ti from"node:path";var qd=[".txt",".md",".docx"],Zd={".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"},Ur=class extends Error{constructor(n){super(`Unsupported input: ${n}`);this.received=n}received};function Yd(e){return Ti.extname(e).toLowerCase()}function cm(e){return Object.hasOwn(Zd,e)}function Sn(e){if(Vi.statSync(e).isDirectory()){let o=Vi.readdirSync(e).filter(r=>!r.startsWith(".")&&Yd(r)===".pdf"&&Vi.statSync(Ti.join(e,r)).isFile()).sort().map(r=>Ti.join(e,r)),i=Vi.readdirSync(e).filter(r=>!r.startsWith(".")).filter(r=>cm(Yd(r))).sort().map(r=>Ti.join(e,r));if(o.length&&i.length)throw new Ur("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 Ur(`directory has no supported video or PDF files: ${e}`);return{kind:"video-directory",path:e,files:i}}let n=Yd(e);if(n===".pdf")return{kind:"comic-file",path:e,ext:n};if(qd.includes(n))return{kind:"text",path:e,ext:n};if(cm(n))return{kind:"video-file",path:e,ext:n};throw new Ur(`file extension ${n||"(none)"} is not supported by ingest (txt/md/docx/video/pdf only)`)}var dm=/\.(mp4|mov|mkv|m4v|webm|avi|mpeg|mpg|flv|wmv)$/i;function pm(e,t=!1){if(t)return"video";if(!e)return"script";if(!In.existsSync(e))throw new E("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(In.statSync(e).isFile()){if(/\.pdf$/i.test(e))return"comic";if(qd.some(n=>Cr.extname(e).toLowerCase()===n))return"text";if(dm.test(e))return"video"}else{let n=In.readdirSync(e).filter(s=>!s.startsWith(".")&&In.statSync(Cr.join(e,s)).isFile()),o=n.some(s=>/\.pdf$/i.test(s)),i=n.some(s=>dm.test(s));if(o&&i)throw new E("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=Cr.join(e,"manifest.json");if(In.existsSync(r)){let s=Wd.object({source:Wd.object({kind:Wd.string()})}).parse(JSON.parse(In.readFileSync(r,"utf8")));if(s.source.kind==="text")return"text";if(["comic-file","comic-directory"].includes(s.source.kind))return"comic"}}throw new E("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 jn from"node:fs";import*as Gt from"node:path";import{z as Qe}from"zod";import{z as Bn}from"zod";var t5=Bn.object({start_line:Bn.number().int().positive(),end_line:Bn.number().int().positive()}),Xd=Bn.object({kind:Bn.literal("text"),document_id:Bn.string().min(1),ranges:Bn.array(t5).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")}),AM=Bn.object({scriptctl:Bn.object({source:Xd})});function Ys(e){return`text-${e}`}import*as wm from"node:fs";import*as lm from"node:fs";import um from"jszip";import{XMLParser as i5}from"fast-xml-parser";function fm(e){return e==null?"":String(e)}function $t(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function be(e){return Array.isArray(e)}function mm(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(`
220
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(`
221
- `)}function vi(e,t){let n=e[":@"];return Ut(n)?Hf(n[t]).trim():""}function Vs(e,t){for(let[n,o]of Object.entries(e))if(Nn(n)===t&&ke(o))return o;return null}function $s(e){let t=[],n=o=>{if(ke(o)){for(let i of o)if(Ut(i))for(let[r,s]of Object.entries(i))r==="#text"&&s!==null&&s!==void 0?t.push(Hf(s)):r!==":@"&&ke(s)&&n(s)}};return n(e),t.join("")}function Ds(e){let t=Ff.parse(e);if(!ke(t))throw new Error("xlsx xml part has an unexpected shape");return t}function co(e,t){let n=[],o=i=>{let r=ke(i)?i.filter(Ut):Ut(i)?[i]:[];for(let s of r)for(let[c,a]of Object.entries(s))Nn(c)===t&&ke(a)&&n.push(s),ke(a)&&o(a)};return o(e),n}function Bx(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 Kx(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 Gs(e,t){let n=e.file(t);return n?n.async("string"):null}async function jx(e){let t=await Gs(e,"xl/sharedStrings.xml");if(!t)return[];let n=Ds(t),o=[];for(let i of co(n,"si"))o.push($s(Vs(i,"si")??[]));return o}async function zx(e){let t=await Gs(e,"xl/workbook.xml"),n=await Gs(e,"xl/_rels/workbook.xml.rels");if(!t||!n)throw new Error("xlsx missing workbook metadata");let o=new Map;for(let r of co(Ds(n),"Relationship")){let s=vi(r,"@_Id"),c=vi(r,"@_Target");s&&c&&o.set(s,Kx("xl",c))}let i=[];for(let r of co(Ds(t),"sheet")){let s=vi(r,"@_name"),c=vi(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 Hx(e,t){let n=vi(e,"@_t");if(n==="inlineStr"){let s=co(e,"is")[0],c=s?Vs(s,"is"):null;return c?$s(c).trim():""}let o=co(e,"v")[0],i=o?Vs(o,"v"):null,r=i?$s(i).trim():"";if(!r&&n==="str"){let s=co(e,"is")[0],c=s?Vs(s,"is"):null;return c?$s(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 Qx(e){let t=await zf.loadAsync(e),[n,o]=await Promise.all([jx(t),zx(t)]),i=[];for(let r of o){let s=await Gs(t,r.path);if(!s)throw new Error(`xlsx missing worksheet part: ${r.path}`);let c=[];for(let a of co(Ds(s),"row")){let d=[];for(let p of co(a,"c")){let l=vi(p,"@_r"),f=l?Bx(l):null,u=Hx(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 Ff=new Jx({ignoreAttributes:!1,attributeNamePrefix:"@_",preserveOrder:!0,trimValues:!1,textNodeName:"#text"});function Nn(e){let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function Td(e){let t=[];function n(o){if(ke(o)){for(let i of o)if(Ut(i))for(let[r,s]of Object.entries(i)){if(r===":@"||r==="#text"&&typeof s=="string")continue;let c=Nn(r);if(c==="t"){if(ke(s)){for(let a of s)if(Ut(a)){let d=a["#text"];typeof d=="string"&&t.push(d)}}}else c==="tab"?t.push(" "):c==="br"||c==="cr"?t.push(`
222
- `):ke(s)&&n(s)}}}return n(e),t.join("").trim()}function Fx(e){let t=[];for(let n of e)if(Ut(n))for(let[o,i]of Object.entries(n)){if(Nn(o)!=="tr")continue;let r=[];if(ke(i)){for(let s of i)if(Ut(s)){for(let[c,a]of Object.entries(s))if(Nn(c)==="tc"&&ke(a)){let d=[],p=l=>{if(ke(l)){for(let f of l)if(Ut(f))for(let[u,g]of Object.entries(f))if(Nn(u)==="p"&&ke(g)){let m=Td(g);m&&d.push(m)}else ke(g)&&p(g)}};p(a),r.push(d.join(" ").trim())}}}r.some(s=>s)&&t.push(r)}return Qf(t)}async function Yx(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 Qx(s);for(let a of c)a.rows.length>0&&t.push([`Embedded Sheet ${o}: ${a.name}`,Qf(a.rows)])}return t}async function Yf(e){let t;try{t=await zf.loadAsync(jf.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=Ff.parse(o),r=null,s=d=>{if(ke(d)){for(let p of d)if(Ut(p))for(let[l,f]of Object.entries(p)){if(Nn(l)==="body"&&ke(f)){r=f;return}ke(f)&&s(f)}}};s(i);let c=[];if(r===null){let d=p=>{if(ke(p)){for(let l of p)if(Ut(l))for(let[f,u]of Object.entries(l))if(Nn(f)==="p"&&ke(u)){let g=Td(u);g&&c.push(g)}else ke(u)&&d(u)}};d(i)}else for(let d of r)if(Ut(d))for(let[p,l]of Object.entries(d)){if(p.startsWith("@_")||p===":@"||p==="#text"||!ke(l))continue;let f=Nn(p);if(f==="p"){let u=Td(l);u&&c.push(u)}else if(f==="tbl"){let u=Fx(l);u&&c.push(u)}}let a=await Yx(t);for(let[d,p]of a)c.push(`
212
+ `)}function $i(e,t){let n=e[":@"];return $t(n)?fm(n[t]).trim():""}function qs(e,t){for(let[n,o]of Object.entries(e))if(Kn(n)===t&&be(o))return o;return null}function Zs(e){let t=[],n=o=>{if(be(o)){for(let i of o)if($t(i))for(let[r,s]of Object.entries(i))r==="#text"&&s!==null&&s!==void 0?t.push(fm(s)):r!==":@"&&be(s)&&n(s)}};return n(e),t.join("")}function Ws(e){let t=gm.parse(e);if(!be(t))throw new Error("xlsx xml part has an unexpected shape");return t}function yo(e,t){let n=[],o=i=>{let r=be(i)?i.filter($t):$t(i)?[i]:[];for(let s of r)for(let[c,a]of Object.entries(s))Kn(c)===t&&be(a)&&n.push(s),be(a)&&o(a)};return o(e),n}function r5(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 s5(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 Xs(e,t){let n=e.file(t);return n?n.async("string"):null}async function a5(e){let t=await Xs(e,"xl/sharedStrings.xml");if(!t)return[];let n=Ws(t),o=[];for(let i of yo(n,"si"))o.push(Zs(qs(i,"si")??[]));return o}async function c5(e){let t=await Xs(e,"xl/workbook.xml"),n=await Xs(e,"xl/_rels/workbook.xml.rels");if(!t||!n)throw new Error("xlsx missing workbook metadata");let o=new Map;for(let r of yo(Ws(n),"Relationship")){let s=$i(r,"@_Id"),c=$i(r,"@_Target");s&&c&&o.set(s,s5("xl",c))}let i=[];for(let r of yo(Ws(t),"sheet")){let s=$i(r,"@_name"),c=$i(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 d5(e,t){let n=$i(e,"@_t");if(n==="inlineStr"){let s=yo(e,"is")[0],c=s?qs(s,"is"):null;return c?Zs(c).trim():""}let o=yo(e,"v")[0],i=o?qs(o,"v"):null,r=i?Zs(i).trim():"";if(!r&&n==="str"){let s=yo(e,"is")[0],c=s?qs(s,"is"):null;return c?Zs(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 p5(e){let t=await um.loadAsync(e),[n,o]=await Promise.all([a5(t),c5(t)]),i=[];for(let r of o){let s=await Xs(t,r.path);if(!s)throw new Error(`xlsx missing worksheet part: ${r.path}`);let c=[];for(let a of yo(Ws(s),"row")){let d=[];for(let p of yo(a,"c")){let l=$i(p,"@_r"),f=l?r5(l):null,u=d5(p,n),h=f??d.length;for(;d.length<h;)d.push("");d[h]=u.trim()}d.some(p=>p)&&c.push(d)}i.push({name:r.name,rows:c})}return i}var gm=new i5({ignoreAttributes:!1,attributeNamePrefix:"@_",preserveOrder:!0,trimValues:!1,textNodeName:"#text"});function Kn(e){let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function ep(e){let t=[];function n(o){if(be(o)){for(let i of o)if($t(i))for(let[r,s]of Object.entries(i)){if(r===":@"||r==="#text"&&typeof s=="string")continue;let c=Kn(r);if(c==="t"){if(be(s)){for(let a of s)if($t(a)){let d=a["#text"];typeof d=="string"&&t.push(d)}}}else c==="tab"?t.push(" "):c==="br"||c==="cr"?t.push(`
213
+ `):be(s)&&n(s)}}}return n(e),t.join("").trim()}function l5(e){let t=[];for(let n of e)if($t(n))for(let[o,i]of Object.entries(n)){if(Kn(o)!=="tr")continue;let r=[];if(be(i)){for(let s of i)if($t(s)){for(let[c,a]of Object.entries(s))if(Kn(c)==="tc"&&be(a)){let d=[],p=l=>{if(be(l)){for(let f of l)if($t(f))for(let[u,h]of Object.entries(f))if(Kn(u)==="p"&&be(h)){let m=ep(h);m&&d.push(m)}else be(h)&&p(h)}};p(a),r.push(d.join(" ").trim())}}}r.some(s=>s)&&t.push(r)}return mm(t)}async function u5(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 p5(s);for(let a of c)a.rows.length>0&&t.push([`Embedded Sheet ${o}: ${a.name}`,mm(a.rows)])}return t}async function hm(e){let t;try{t=await um.loadAsync(lm.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(be(d)){for(let p of d)if($t(p))for(let[l,f]of Object.entries(p)){if(Kn(l)==="body"&&be(f)){r=f;return}be(f)&&s(f)}}};s(i);let c=[];if(r===null){let d=p=>{if(be(p)){for(let l of p)if($t(l))for(let[f,u]of Object.entries(l))if(Kn(f)==="p"&&be(u)){let h=ep(u);h&&c.push(h)}else be(u)&&d(u)}};d(i)}else for(let d of r)if($t(d))for(let[p,l]of Object.entries(d)){if(p.startsWith("@_")||p===":@"||p==="#text"||!be(l))continue;let f=Kn(p);if(f==="p"){let u=ep(l);u&&c.push(u)}else if(f==="tbl"){let u=l5(l);u&&c.push(u)}}let a=await u5(t);for(let[d,p]of a)c.push(`
223
214
  ## ${d}
224
215
  `),c.push(p);return[c.join(`
225
216
 
226
- `),a.length>0]}var Vd=class extends Error{};function qf(e){return e.replace(/^/,"").replace(/\r\n?/g,`
227
- `)}function qx(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{throw new Vd("source is not valid UTF-8")}}async function Wf(e,t){if(t===".docx"){let[n]=await Yf(e);return qf(n)}return qf(qx(Zf.readFileSync(e)))}import*as be from"node:fs";import*as Go from"node:path";function Js(e,t){let n=Go.dirname(e);be.mkdirSync(n,{recursive:!0});let o=Go.join(n,`.${Go.basename(e)}.${process.pid}.tmp`),i=be.openSync(o,"w");try{be.writeFileSync(i,t),be.fsyncSync(i)}finally{be.closeSync(i)}be.renameSync(o,e)}function Zx(e,t){Js(e,JSON.stringify(t,null,2)+`
228
- `)}function Wx(e){return JSON.parse(be.readFileSync(e,"utf-8"))}var st=class{constructor(t){this.root=t}root;abs(t){return Go.join(this.root,t)}ensure(){be.mkdirSync(this.root,{recursive:!0})}passDir(t){let n=this.abs(t);return be.mkdirSync(n,{recursive:!0}),n}readText(t){return be.readFileSync(this.abs(t),"utf-8")}writeText(t,n){Js(this.abs(t),n)}writeJson(t,n){Zx(this.abs(t),n)}readJson(t){return Wx(this.abs(t))}has(t){return be.existsSync(this.abs(t))}path(t){return this.abs(t)}clearError(t){let n=this.abs(t);be.existsSync(n)&&be.rmSync(n)}};function Kt(e,t){e=e-0;let n=$d(),o=n[e];if(Kt.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)};Kt.ccSjUe=i,Kt.dKlJjl={},Kt.wCYmoh=!0}let r=n[0];Kt.sBhMJx!==r&&(Kt.dKlJjl={},Kt.sBhMJx=r);let s=Kt.dKlJjl[e];return s===void 0?(o=Kt.ccSjUe(o),Kt.dKlJjl[e]=o):o=s,o}var F=Kt,Xx=[F(40),F(37),F(24),F(75),F(5),F(21),"",F(65),F(13),F(34),F(62),"",F(70),F(35),F(42),F(27),F(39),F(43),F(0),F(68),F(55),"",F(77),F(18),F(58),F(10),F(11),F(51),F(59),F(66),F(8),F(3),F(76),"",F(15),F(4),F(9),F(6),F(20),F(14),F(45),F(48),F(38),F(54)][F(74)](`
229
- `);function e5(e){let t=F,n=e[t(73)]===0?t(47):t(23);return[t(78),n,t(49),"",e[t(53)]][t(74)](`
230
- `)}function Bs(e,t){let n=F;return new x(e,{exitCode:me,errorCode:n(12),hint:n(44),data:{actual:t}})}function t5(e){let t=F;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 Dd(e,t){let n=F;if(!t5(e))throw Bs(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 ge(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)](`
231
- `);i=Ir(r)}catch(r){throw r instanceof ge?Bs(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)]):Bs(n(19)+t[n(73)]+n(69),[n(2)]);return i}function $d(){let e=["lsdOVAZLNlRVVjP7iMTPBMqIoIj0CMfUC2L0Aw9UiIWIy29UDgvUDci6iUw/OowUNUI9RoAnOUAiKoEUGos9K+s4REAwH+EAHoI9RowCUUAwH+wTLYj944cc5BI46kEb5Qc85BYp6k+n5lMF6kAb57+76k+r77Ym5l6l5AAcigbgteftsejbq0TGiokgKIbG6zEQ5zUEyooaGwbcqunlifrpifbsrvnftLrGiokgKIbG5zUE5yIW546W5A6EyooaGG","BgvUz3rO","CMvJB3jKCZOGma","icdOKAhOR63LIQJKVzWGyfvTihbYyxrVigrLig9MzxjLBMrHCYbJywKGzgeGBwvZysbLihnLigvZCgfSAgeGCgvSBYbJAmoJBY5GiokgKIbHy3rPB24Uy29UDgvUDd1G5lIa55Uy5l6B5zob5lUo5Qgm5lIk5O6j6jc977Ym5PwJ6jc95lIa5zYW44ccyooaGUs6UUEjQEIVTowhUUEAHoIrOEIVREwVUEEzVEs7JEMaKowTL+s/NEEvME+8Jos4JEE/U+IVKE+8M1jPy2HHCMtJGiffBwLSEsdNRyNKURRNIANLKi3LP4VNU4JKV53MJihLJP/MLOFMI7ZLHPNJGii","5Q2J5PAh5y+J5B6e77YAzgLHBg9NDwxJGifPBM5LCL90Ag91z2H0ioEAHcbJB250zw50ioMaKowTL+wUJoAvTos/NEEvME+8Jos4JEA2PUIjSUoaGEs4JEAjQEwgMEoaGEs4JEE6OoMuMEoaGEs4JEE/U+IVKEoaGMfJDgLVBUoaGxrYyw5ZAxrPB27JGifUB3rLiowsJcbLBw90Aw9Uiow/OowUNUI9RoAnOUAiKoEUGos9K+s4REAwH++8M+E/U+IVKEs4JEw+L+AuUEwpMooaGEwiOowhJ+AiLUIHPEMaOowoN+AwH+s6I+wUNUoaGEwBOoAENooaGEMHUUw6J+oaGEwkQos9NoE7K+AENooaGEs6UUEjQEE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54Mm5zkm5RkH5PYj6ycA6kgm6k+r5zcn55Qe5yw25lUw5lIt5zcn5l+D55wz5y6F5PAh44cc5lIn5B6x5OQk5Pw05y+L5Asw6k+T5yQO5l2C5OIw546V5Akd5O+p6l+W5y6F5Qc355wz5zYOigfJDgLVBIdKUk3JGii","icdLKiZKUidLJ6xNLlhLPjRKURRLKiZML7BOR7tML7BVViZKUlRMR4/KUkROR7tOR53KURRLKitLHPNKUidMNAhNM7JPGRSGzgLHBg9NDwxVViXJB250zw50ioEBUowqJooaGG","6l2S5O2I6kEe5yIz77YA","44cq5B6f6kEe6iYd5yYw55Qe5y6F5PAh54Mh5Q6144cr"];return $d=function(){return e},$d()}async function Xf(e,t,n){let o=F,i=await e[o(41)](o(71),{system:Xx,user:e5(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 Bs(o(19)+t[o(73)]+o(50),[i[o(53)][o(7)](0,500)])}return{raw:i[o(53)],records:Dd(r,t)}}var Jd=jt,n5=Jd(1);function o5(e){let t=Jd,n=e[t(5)](/起点\s*[::]\s*(\d+)/);return n?{found:!0,line:Math[t(3)](Number(n[1]))}:{found:!1,line:null}}function Gd(){let e=["Dgv4Da","5l2G5PIV55+T5yMN5yMN5PYS55Qe44cm5Q2J5PAh6lw354k55A6A5l2n5zMO44cn44cc5lIa5lU95PAh5lU25BI45BI45zYO55YF5Q2J55Qe5yMN5PYS5Q2J5PAh5lMl5yMn77Ym5y6l552a5lIa5AsN5Q61kIRPNz7MRApMLOCQkUEAHoETUEwKH+ADKoAwMEoaGUs9OoIMGEwiPoAwRE+8MIOQ55YF5Q2J55Qe5yMN5PYS5Q2J5PAhkIRMMk/KUi3MMk/LNkJMIjhNU5NKVAdNMOtOV5NMRRxLUkBOOyZLJ7FNMOtMLOFMNkZPH4ZLVidLP4VVViZLPOlMNPZMMk/VViZMIQxLKyRL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/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 Gd=function(){return e},Gd()}async function em(e,t,n){let o=Jd,i=await e[o(4)](o(2),{system:n5,user:o(6)+t,...n?{signal:n}:{}});return o5(i[o(0)])}function jt(e,t){e=e-0;let n=Gd(),o=n[e];if(jt.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)};jt.TPTWLA=i,jt.iYuNay={},jt.sLepLJ=!0}let r=n[0];jt.inDmHY!==r&&(jt.iYuNay={},jt.inDmHY=r);let s=jt.iYuNay[e];return s===void 0?(o=jt.TPTWLA(o),jt.iYuNay[e]=o):o=s,o}var tm=50,i5=10;async function nm(e,t,n){let o=t.split(`
232
- `),i=tm-i5;try{for(let r=0;r<o.length;r+=i){let s=Math.min(r+tm,o.length),c=o.slice(r,s).map((d,p)=>`${r+p+1} ${d}`).join(`
233
- `),a=await em(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 om(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 Pt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zt=e=>Array.isArray(e);function Bd(e){let t=new Map;if(!zt(e))return t;for(let n of e){if(!Pt(n))continue;let o=n.actor_id??n.location_id??n.prop_id;typeof o=="string"&&t.set(o,n)}return t}function r5(e){let t=[],n=(o,i)=>{!Pt(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 zt(e.episodes)?e.episodes:[])if(!(!Pt(o)||!zt(o.scenes))){for(let i of o.scenes)if(Pt(i)){n(i.location,"location_id");for(let r of zt(i.actors)?i.actors:[])n(r,"actor_id");for(let r of zt(i.props)?i.props:[])n(r,"prop_id");for(let r of zt(i.actions)?i.actions:[])Pt(r)&&n(r.speaker,"actor_id")}}return t}function s5(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 Ks(e){if(!Pt(e))throw new Error("govern expects a script object");let t=JSON.parse(JSON.stringify(e));for(let p of zt(t.episodes)?t.episodes:[])if(!(!Pt(p)||!zt(p.scenes)))for(let l of p.scenes){if(!Pt(l))continue;let f=zt(l.actors)?l.actors.filter(Pt):[],u=new Set(f.map(g=>g.actor_id).filter(g=>typeof g=="string"));for(let g of zt(l.actions)?l.actions:[])!Pt(g)||!Pt(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=Bd(t.actors),o=Bd(t.locations),i=Bd(t.props),r=new Map([...n,...o,...i]),s=r5(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=(zt(l.states)?l.states:[]).filter(Pt),u=new Map,g=s5(f,c.get(p)??new Map),m;if(g===null){let h=f.find(w=>w.state_id==="default");m=[{state_id:"default",state_name:h?.state_name??"default",description:h?.description??""}]}else{m=[];for(let h of f)h.state_id!=="default"&&(h.state_id===g?(u.set(h.state_id,"default"),m.unshift({state_id:"default",state_name:h.state_name,description:h.description??""})):(u.set(h.state_id,h.state_id),m.push({state_id:h.state_id,state_name:h.state_name,description:h.description??""})))}l.states=m,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 im=Ht;function Ht(e,t){e=e-0;let n=Kd(),o=n[e];if(Ht.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)};Ht.alaGPc=i,Ht.IPZchV={},Ht.vcGzia=!0}let r=n[0];Ht.cEXTRr!==r&&(Ht.IPZchV={},Ht.cEXTRr=r);let s=Ht.IPZchV[e];return s===void 0?(o=Ht.alaGPc(o),Ht.IPZchV[e]=o):o=s,o}var a5=im(6);async function rm(e,t,n,o){let i=im;return(await e[i(4)](i(2),{system:a5,user:i(0)+t+i(3)+n,...o?{signal:o}:{}}))[i(5)][i(1)]()}function Kd(){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 Kd=function(){return e},Kd()}var dm={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"]}}}}}},jd={type:"array",items:{type:"object",required:["asset_id","state_id"],additionalProperties:!1,properties:{asset_id:{type:"string"},state_id:{type:["string","null"]}}}},jM={type:"object",required:["scenes"],additionalProperties:!1,properties:{scenes:{type:"array",items:{type:"object",required:["scene_id"],additionalProperties:!1,properties:{scene_id:{type:"string"},actors:{...jd,items:{type:"object",required:["actor_id","state_id"],additionalProperties:!1,properties:{actor_id:{type:"string"},state_id:{type:["string","null"]}}}},locations:{...jd,items:{type:"object",required:["location_id","state_id"],additionalProperties:!1,properties:{location_id:{type:"string"},state_id:{type:["string","null"]}}}},props:{...jd,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"]}}}}}}}}},pm={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"}}},lm={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:pm}}},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"}}},c5={type:"string",enum:["actor","location","prop"]},um={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"},sm={type:"string",minLength:5,pattern:"^[0-9]{2}:[0-5][0-9]$",description:"\u5FC5\u586B\u4E14\u4E0D\u5F97\u4E3A\u7A7A\u3002\u672C\u955C\u5934\u6216\u58F0\u97F3\u771F\u6B63\u5F00\u59CB\u7684\u65F6\u95F4\u6233\uFF0C\u4E25\u683C\u4F7F\u7528 MM:SS\uFF08\u4F8B\u5982\u300E00:03\u300F\uFF09\uFF1BSS \u5FC5\u987B\u4E3A 00-59\uFF0C\u6574\u5206\u949F\u5199\u6210\u4E0B\u4E00\u5206\u949F\u7684 :00\uFF0C\u7981\u6B62\u5199 :60\u3001null\u3001\u672A\u77E5\u503C\u6216\u5C0F\u6570\u79D2"},am={type:"object",required:["name","description"],additionalProperties:!1,properties:{name:um,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"}}},cm={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"}}},fm={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\uFF1BSS \u5FC5\u987B\u4E3A 00-59\uFF0C\u6574\u5206\u949F\u5199\u6210\u4E0B\u4E00\u5206\u949F\u7684 :00\uFF0C\u7981\u6B62\u5199 :60"},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:um,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:sm,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:sm,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:c5,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:cm,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:am,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:cm,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:am,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"}}}}}}}},mm={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:pm}}}}};var z=Qt;function Qt(e,t){e=e-0;let n=zd(),o=n[e];if(Qt.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)};Qt.vGSHGD=i,Qt.ykrKeL={},Qt.AowUYu=!0}let r=n[0];Qt.qbkWqr!==r&&(Qt.ykrKeL={},Qt.qbkWqr=r);let s=Qt.ykrKeL[e];return s===void 0?(o=Qt.vGSHGD(o),Qt.ykrKeL[e]=o):o=s,o}var d5=[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)](`
234
- `);function p5(e,t){let n=z;return[n(4),e[n(50)]()||n(5),"",n(66),t[n(50)]()][n(33)](`
235
- `)}async function gm(e,t,n,o){let i=z,r=await e[i(45)](i(69),{system:d5,user:p5(t,n),tool:{name:i(44),description:i(22),inputSchema:lm},...o?{signal:o}:{}});return{delta:br(r[i(49)]),raw:JSON[i(38)](r[i(49)])}}var l5=new Set([z(60),z(40),z(99)]),Ko=e=>typeof e===z(78)&&e!==null&&!Array[z(13)](e),Un=e=>typeof e===z(9)?e[z(50)]():"";function js(e,t){let n=z,o=Un(e);if(!o)throw new Pe(t+n(36));return o}function u5(e,t){let n=z;if(!Ko(e))throw new Pe(t+n(31));let o=js(e[n(32)],t+n(90));if(o!=="\u5E38\u6001")throw new Pe(t+n(29));return{name:o,description:js(e[n(15)],t+n(93))}}var Pe=class extends Error{[z(12)]=z(34);constructor(t){let n=z;super(t),this[n(32)]=n(0)}};function f5(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)](`
236
- `);else n+='\\"';continue}n+=r}return n}function m5(e,t){let n=z,o=r=>JSON[n(101)](r),i;try{i=o(e)}catch(r){let s=f5(e);if(s===e)throw new Pe(t+n(89)+(r instanceof Error?r[n(20)]:String(r)));try{i=o(s)}catch(c){throw new Pe(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 Pe(t+n(91)+typeof i);return i}function Jo(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?m5(o,t):[]}throw new Pe(t+n(19)+typeof e)}var g5=/[((]([^))]*)[))]?/;function zd(){let e=["u2vYAwfSrgvSDgftAgfWzuvYCM9Y","icdcTYbHBgLHC2vZid0G6l+z5Q616yEm6k+L5A6E5l2t55QekIRMIydMNiNLHBBKU5BLJ6VMS5uQkU+8JoMaKos4QUwnLEwiL++8IoE6R+wqJE+8JowiQ+w4PUoaJU+8Iow/G++8IEoaJ+oaJU+8MUoaJ+oaJU+8JoMTGUIVREoaJ+I/MEEXU+wVUEEzVs/MG4xNU6RMOiFORRdVViNVVjRLIkVLKi3JGihOR5hLKi3JGihLIy3KUjBLKi3JGihNN63LKi0V5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PYj5B2tigzYB20G56gU5A6E5PIVigLUDg8G55Qe5y+M5lIa5y+R5Rov5PE25OMnig1LCMDL77YB5zcn5A2x5OIw5Asw6kEc55U45lY85l2g5PIV5lIn5zcm6kEs6iMY77Yi5AAc5zcm5lI66AQ36AUf5l2g6lQR5lU95lIn5zcm77Yj57UD5lInig1LCMDL44cckIOGzNjVBsdLT7lNU4/MMk/NI6ZNQ4VNMBVORRdNMOtLRP7KVzpML7BVViZKUi3OPOeGBwvYz2xVViJNS7VNU5/KUi3KVjRLKiJLUBBKUktKUkRLT7lNMBVORRdLRP7KVzpVViNJGii","DxDQzw4","44cq5BEY55+L6k6+5A6A44cr77Yi5OIQ6iEZ5lIk5lIa5Q615l2G5BEY5BU656Ul55Qe55M76k6W77YB5BYa56+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/KVjRNHACGBwvYz2vZicSGywXPyxnLCYdMIORMRApMLOFVViJLR7NNMB3OR7tOR53KURRJGihML4hNMB3MLOFMNkZVViNPH4ZNMOtOV5NKUPVLHPNMS5xNM7tMJQxM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+b77YB6ygt5yw355QeioEGToAnNY/LJ5hLHyNVViNJGiiQkUMaOowEI+wqJEw/HEMHU+EuQos4REAwHYOQ77YA5Q2J5PAh6yEm55Qe6iUX5PAh5lIt5zcn77Yi5Awx6kofl+IbJos4MI/LVAlMGihLKi3VViZLPOiGu2vHBIDZifjLDMvUz2xJGifgBgfTzwnHC3rLCUoaGuDYyxzLifbYAwvZDooaGvnOAwvSzgD1yxjK77Yj5lIa5B6l6k+r5OIq5lIT5PAh5yAn5l2C6ycG5z6l5zcn77Yi6ikw5OgP55Qe5Asn5lUh5Awx6kof44cb54sW5PYV5BIi44cb5Akt56wT5y+444cb55U+5y2R77Yj44cc","oIbLEhbLy3rLzcbku09oigfYCMf5ihn0CMLUzYWGCgfYC2uGzMfPBgvKoIa","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 zd=function(){return e},zd()}function Hd(e){let t=z,n=Un(e),o=g5[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 Bo=e=>Hd(Un(e))[z(32)];function h5(e){let t=z;if(Ko(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 Pe(t(53)+(i instanceof Error?i[t(20)]:String(i)))}if(!Ko(o)){if(t(3)===t(3))throw new Pe(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 br(e){let t=z,n=$f(),o=h5(e);if(!o)return n;for(let i of Jo(o[t(25)],t(25))){if(!Ko(i))continue;let r=Un(i[t(52)]),{name:s,aliases:c}=Hd(Un(i[t(32)]));if(!l5[t(62)](r)||!s)continue;let a=js(i[t(15)],t(81)+s+t(93)),d=u5(i[t(75)],t(81)+s+t(43)),p=[...c];for(let f of Jo(i[t(16)],t(68))){let{name:u,aliases:g}=Hd(Un(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 Jo(o[t(57)],t(57))){if(!Ko(i))continue;let r=Bo(i[t(11)]),s=Bo(i[t(80)]);r&&s&&r!==s&&n[t(57)][t(76)]({from:r,into:s})}for(let i of Jo(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(!Ko(i))continue;let r=Bo(i[t(17)]),s=Bo(i[t(32)]);if(!r||!s)continue;let c=[s,...Jo(i[t(16)],t(94))[t(63)](Bo)[t(18)](Boolean)];n[t(42)][t(76)]({entity:r,names:c,description:js(i[t(15)],t(7)+r+"."+s+t(93))})}}for(let i of Jo(o[t(85)],t(85))){if(!Ko(i))continue;let r=Un(i[t(87)]),s=Bo(i[t(17)]),c=Bo(i[t(103)]);r&&s&&c&&n[t(85)][t(76)]({scene:r,entity:s,look:c})}return n[t(96)]=Jo(o[t(96)],t(96))[t(63)](Un)[t(18)](Boolean),n[t(97)]=Un(o[t(97)]),n}var Qe=Ft,y5=[Qe(1),Qe(29),Qe(18),Qe(32),Qe(0),Qe(7),Qe(15),Qe(8),Qe(3)][Qe(21)](`
237
- `);function w5(e,t){let n=Qe;return[n(13),e[n(27)]()||n(19),"",n(4),t[n(14)](o=>"- "+o)[n(21)](`
217
+ `),a.length>0]}var tp=class extends Error{};function ym(e){return e.replace(/^/,"").replace(/\r\n?/g,`
218
+ `)}function f5(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{throw new tp("source is not valid UTF-8")}}async function ea(e,t){if(t===".docx"){let[n]=await hm(e);return ym(n)}return ym(f5(wm.readFileSync(e)))}import{z as ta}from"zod";function np(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 op(e,t,n){return{kind:"text",document_id:t,ranges:[np(e,n)]}}function xm(e,t,n){for(let o of e.episodes)for(let i of o.scenes)for(let r of i.actions){let s=ta.object({scriptctl:ta.record(ta.string(),ta.json()).optional()}).parse(r.extend??{});r.extend={...r.extend,scriptctl:{...s.scriptctl,source:op(r.identity_key,t,n)}}}}var m5=Qe.object({source:Qe.object({kind:Qe.literal("text"),sha256:Qe.string().length(64),path:Qe.string()})}),g5=Qe.object({version:Qe.literal(3),episode:Qe.record(Qe.string(),Qe.string()),action:Qe.record(Qe.string(),Qe.string())});function Dt(e){throw new E(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 _m(e,t,n){let o=jn.statSync(e).isDirectory(),i=o?Gt.resolve(e):Gt.dirname(Gt.resolve(t)),r=y=>{let x=Gt.join(i,y);return jn.existsSync(x)||Dt(`Text ingest artifact missing: ${x}`),JSON.parse(jn.readFileSync(x,"utf8"))},s=m5.parse(r("manifest.json")),c=Gt.join(i,"pass1/source.txt");jn.existsSync(c)||Dt("Text review requires the normalized original source snapshot.");let a=jn.readFileSync(c,"utf8");if(he(a)!==s.source.sha256&&Dt("The original text snapshot has changed since ingest."),!o){let y=await ea(e,Gt.extname(e).toLowerCase());he(y)!==s.source.sha256&&Dt("The supplied text does not match this ingest source.")}let d=a.split(`
219
+ `),{line:p}=Qe.object({line:Qe.number().int().nonnegative()}).parse(r("pass1/body_start.json"));p>=d.length&&Dt("Text body start is outside the source snapshot.");let l=g5.parse(r("v4_identity_map.json")),f=go(JSON.parse(jn.readFileSync(t,"utf8")));f.version!==4&&Dt("Text source review requires the ingested Script v4.");let u=Ys(s.source.sha256),h=Object.entries(l.episode).map(([y,x])=>({id:x,...np(y,p)})).sort((y,x)=>y.start_line-x.start_line);h.some(y=>y.end_line>d.length)&&Dt("An episode's ingest window is outside the original source.");let m=f.episodes.filter(y=>!n?.length||n.includes(y.no)).map(y=>{let x=h.filter(A=>A.id===y.id);x.length!==1&&Dt(`Episode ${y.no} has no unambiguous text source identity.`);let S=x[0],_=h[h.indexOf(S)+1];return{episode:y.no,start_line:h.indexOf(S)===0?p+1:S.start_line,end_line:_?_.end_line:d.length}});m.length||Dt("No selected episodes exist in this script.");let g=new Map,w=new Map(Object.entries(l.action).map(([y,x])=>[x,op(y,u,p)]));for(let y of En(f)){if(!m.some(_=>_.episode===y.scene.ep.no))continue;let x=Qe.object({scriptctl:Qe.object({source:Xd.optional()}).optional()}).safeParse(y.raw.extend??{});x.success||Dt(`Invalid text source metadata on ${y.anchor}.`);let S=x.data.scriptctl?.source??w.get(y.anchor);S&&(S.document_id!==u&&Dt(`Action ${y.anchor} belongs to a different text document.`),S.ranges.some(_=>_.start_line>_.end_line||_.end_line>d.length)&&Dt(`Invalid source lines on ${y.anchor}.`),g.set(y.anchor,S))}return{document_id:u,title:Gt.basename(s.source.path),path:c,lines:d,episodes:m,references:g}}var Im="review-agent";function w5(e,t){let n=t||Im,o=e.models[n];if(!o)throw new E(`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 E(`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 E(`${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 Em(){let e=oa.dirname(h5(import.meta.url)),t=oa.join(e,"review-agent.js"),n=Pr.existsSync(t)?y5(t).href:"@lingjingai/review-agent";try{return await import(n)}catch(o){throw new E("The review agent is not installed.",{exitCode:me,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 Sm(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 E("--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 na(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 E(`--${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 Am(e){let t=vi(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=pm(o,i.length>0),c=w5(t,n||(r==="comic"?"review-comic":r==="text"?"review-text":Im));if(e.check){let f=await Em(),h=typeof{script:f.reviewPlainScript,text:f.reviewTextScript,comic:f.reviewComicScript,video:f.reviewVideoScript}[r]=="function";return[{text:h?`ready: ${c.provider}/${c.model}`:"the review agent bundle is present but exports no reviewScript",data:{ready:h,review_kind:r,provider:c.provider,model:c.model,llm_config:t.sourcePath??"builtin"}},h?J:me]}let a=Ae(e);if(!Pr.existsSync(a))throw new E("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=>!Pr.existsSync(f));if(d.length>0)throw new E("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&&!Pr.existsSync(o))throw new E("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 Em(),l=f=>process.stdout.write(JSON.stringify(f)+`
220
+ `);try{let f={scriptPath:a,...Sm(v(e.episodes))?{episodes:Sm(v(e.episodes))}:{},concurrency:na(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:na(e,"max_steps",300),episodeTimeoutMs:na(e,"episode_timeout_ms",48e4),onEvent:l};if(r==="comic"){let u=await am(o,a,f.converge?void 0:f.episodes);await p.reviewComicScript({...f,comic:u})}else if(r==="text"){let u=await _m(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:na(e,"media_budget",1)}):await p.reviewPlainScript(f)}catch(f){throw f instanceof E?f:new E("Review failed.",{exitCode:me,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:{}},J]}function km(e,t){ce(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",(n,o)=>[...o,n],[]).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(q(Am,t))}import*as bm from"node:fs";var wo="\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=Ae(e);if(!bm.existsSync(t))throw new E("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 bd(t)}function ue(e,t){let n=e[t];return typeof n=="string"?n:void 0}function Xo(e,t){let n=e[t];if(n==null||n==="")return;let o=Number(n);if(!Number.isFinite(o))throw new E(`--${t} must be a number.`,{exitCode:k,errorCode:"OPTION_NOT_NUMBER",data:{actual:[String(n)]}});return o}function fe(e,t=0){return(e._args??[])[t]??""}function ip(e){return Array.isArray(e)?e.map(String):typeof e=="string"?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function rt(e,t,n=()=>({})){try{let o=e();return[{text:o,data:{op:t,changed:!1,text:o,...n()}},J]}catch(o){throw o instanceof E?o:new E(o instanceof Error?o.message:String(o),{exitCode:k,errorCode:o?.code??"SCRIPT_TOOL_FAILED"})}}function Om(e,t){let n=ce(e.command("read [addr]"),"read").description(`\u8BFB\u4EFB\u610F\u8282\u70B9\uFF1B\u4E0D\u7ED9\u5730\u5740\u8FD4\u56DE\u5267\u672C\u5361\u3002${wo}`).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(q(y=>{let x=Je(y);return rt(()=>Ks(x,fe(y),{...y.outline?{depth:"outline"}:{},...y.plain?{plain:!0}:{},...Xo(y,"context")!==void 0?{context:Xo(y,"context")}:{}}),"read",()=>fe(y)?{}:{document:x.raw})},t));ke(n,[wo]);let o=ce(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(q(y=>rt(()=>{let x=Je(y),S=fe(y);return[`## \u573A\u7ED3\u6784
221
+ ${Ks(x,S,{depth:"outline"})}`,`## \u6B63\u6587
222
+ ${Ks(x,S)}`,`## \u5F53\u524D\u6821\u9A8C\u95EE\u9898
223
+ ${Jd(x,{})}`].join(`
224
+
225
+ `)},"scan"),t));ke(o,["\u96C6\u53F7\uFF0C\u4ECE 1 \u5F00\u59CB"]);let i=ce(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${wo}`).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(q(y=>rt(()=>Mf(Je(y),fe(y),{...ue(y,"in")?{in:ue(y,"in")}:{},...ue(y,"speaker")?{speaker:ue(y,"speaker")}:{},...ue(y,"type")?{type:ue(y,"type")}:{},...Xo(y,"limit")!==void 0?{limit:Xo(y,"limit")}:{},...y.full?{full:!0}:{}}),"find"),t));ke(i,["\u6B63\u5219\uFF1B\u53EA\u6309 speaker/type \u8FC7\u6EE4\u65F6\u53EF\u7701\u7565"]);let r=ce(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(q(y=>{let x=Pd(Je(y),fe(y),{offset:Xo(y,"offset"),limit:Xo(y,"limit"),context:Xo(y,"context")});return[{text:Td(x),data:{op:"refs",changed:!1,...x}},J]},t));ke(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=ce(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(q(y=>{let x=Je(y);return rt(()=>Lf(x,fe(y)),"span",()=>({rows:[Dd(x,fe(y))]}))},t));ke(s,[`${wo}\uFF0C\u6216 \`\u8D77ID..\u6B62ID\``]),ce(e.command("validate"),"read").description("\u8DD1\u6574\u672C\u6821\u9A8C").action(q(y=>{let x=Je(y),S=Pi(x);return[{text:Bf(x),data:{op:"script.validate",changed:!1,passed:S.ok,script_path:x.path,stats:{actors:x.assets.filter(_=>_.kind==="actor").length,locations:x.assets.filter(_=>_.kind==="location").length,props:x.assets.filter(_=>_.kind==="prop").length,episodes:x.episodes.length,scenes:x.episodes.reduce((_,A)=>_+A.scenes.length,0),actions:En(x).length},issues:[...S.errors.map(_=>({..._,severity:"error"})),...S.warnings.map(_=>({..._,severity:"warning"}))]}},S.ok?J:Wn]},t)),ce(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(q(y=>rt(()=>Jd(Je(y),{...ue(y,"severity")?{severity:ue(y,"severity")}:{},...ue(y,"code")?{code:ue(y,"code")}:{}}),"issues"),t));let c=ce(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${wo}`).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(q(y=>{let x={};for(let S of["content","speaker","type","name","desc","importance","role","space","time","title","synopsis","logline","theme","worldview","style","main"]){let _=ue(y,S);_!==void 0&&(x[S]=_)}for(let S of["paren","ts","transition"])if(y[S]===!1)x[S]=null;else{let _=ue(y,S);_!==void 0&&(x[S]=_)}return y.alias!==void 0&&(x.aliases=ip(y.alias)),rt(()=>Nf(Je(y),fe(y),x),"edit")},t));ke(c,[wo]);let a=ce(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(q(y=>rt(()=>Uf(Je(y),fe(y),y.before?"before":"after",ue(y,"type"),fe(y,1),ue(y,"speaker"),ue(y,"paren")),"insert"),t));ke(a,["\u76F8\u90BB action \u7684\u5730\u5740","\u65B0 action \u7684\u6B63\u6587"]);let d=ce(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(q(y=>rt(()=>Cf(Je(y),fe(y),fe(y,1),y.before?"before":"after"),"move"),t));ke(d,["\u8981\u632A\u7684 action","\u76EE\u6807\u90BB\u5C45 action"]);let p=ce(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(q(async y=>{let x=await import("node:fs"),S=ue(y,"file"),_=S?x.readFileSync(S,"utf8"):x.readFileSync(0,"utf8");return rt(()=>Tf(Je(y),fe(y),_,{allowDelete:!!y.allow_delete}),"write")},t));ke(p,["\u573A / \u96C6\u5730\u5740\uFF0C\u6216 `+` \u8FFD\u52A0\u65B0\u96C6"]);let l=ce(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(q(y=>rt(()=>Gf(Je(y),fe(y),fe(y,1),{...ue(y,"in")?{in:ue(y,"in")}:{},...ue(y,"speaker")?{speaker:ue(y,"speaker")}:{},...ue(y,"type")?{type:ue(y,"type")}:{},...y.apply?{apply:!0}:{}}),"replace"),t));ke(l,["\u6B63\u5219","\u66FF\u6362\u6210\u4EC0\u4E48"]);let f=ce(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",x5,[]).option("--remove","\u5220\u9664\u6574\u6761\u5F15\u7528").action(q(y=>rt(()=>Df(Je(y),fe(y),fe(y,1),ip(y.state).flatMap(x=>x.split(",")).map(x=>x.trim()).filter(Boolean),!!y.remove),"ref"),t));ke(f,["\u573A\u5730\u5740","\u4EBA\u7269 / \u5730\u70B9 / \u9053\u5177\u7684\u540D\u5B57\u6216 ID"]);let u=ce(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(q(y=>rt(()=>Kf(Je(y),fe(y),fe(y,1),ue(y,"desc")??"",ue(y,"importance")??"featured",ip(y.alias)),"asset"),t));ke(u,["actor | location | prop","\u540D\u5B57"]);let h=ce(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(q(y=>rt(()=>jf(Je(y),fe(y),fe(y,1),ue(y,"desc")??""),"state"),t));ke(h,["\u8D44\u4EA7\u540D\u6216 ID","\u72B6\u6001\u540D"]);let m=ce(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(q(y=>rt(()=>Hf(Je(y),fe(y),{...ue(y,"replacement")?{replacement:ue(y,"replacement")}:{},...y.force?{force:!0}:{}}),"del"),t));ke(m,[wo]);let g=ce(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(q(y=>rt(()=>jd(Je(y),fe(y),fe(y,1)),"merge"),t));ke(g,["\u88AB\u5E76\u5165\u7684\u8D44\u4EA7","\u4FDD\u7559\u7684\u8D44\u4EA7"]);let w=ce(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(q(y=>rt(()=>zf(Je(y),fe(y),fe(y,1)||void 0,fe(y,2)||void 0,!!y.remove),"ext"),t));ke(w,[wo,"extend key","\u503C"])}function x5(e,t){return[...t,e]}import*as Ch from"node:path";var zn={createExecutor:hf};import*as Lp from"node:fs";import*as zi from"node:path";var An=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();var Tr=e=>String(e).padStart(3,"0"),rp=e=>e.normalize("NFC").replace(/\s+/g," ").trim();function vm(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}`,h=(a.get(u)??0)+1;return a.set(u,h),`${u}:${h}`},p=(l,f)=>{let u=l.actors.find(h=>rp(h.name)===rp(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_${Tr(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_${Tr(s)}`,scenes:[]},n.push(i)),c++,r={identity_key:d("scene",l.source),scene_id:`scn_${Tr(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 Vr=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=rp(t),i=this.byNorm.get(o);return i||(i={provisional_id:`${this.prefix}_${Tr(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=An(n),i=t.states.find(s=>An(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 _5(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 ia(e){let t=0,n=()=>`st_${Tr(++t)}`,o=new Vr("act","actor",n),i=new Vr("loc","location",n),r=new Vr("prp","prop",n),s={episode:{},scene:{},action:{}},c={episode:new Set,scene:new Set,action:new Set},a=(u,h,m)=>{if(!m||c[u].has(m))throw new Error(`Duplicate or missing ${u} source identity: ${m}`);c[u].add(m),s[u][h]=m},d=(u,h,m,g)=>{let w=u.ensure(h.name,m),y={[g]:w.provisional_id};return h.state!==void 0&&(y.state_id=u.stateId(w,h.state)),y},p=e.episodes.map((u,h)=>(a("episode",u.episode_id,u.identity_key),{episode_id:u.episode_id,...u.title?{title:u.title}:{},scenes:u.scenes.map((m,g)=>{let w=`${u.episode_id}/${m.scene_id}`;a("scene",w,m.identity_key);let y={episode:h,scene:g},x=m.location?d(i,m.location,y,"location_id"):null,S=m.actors.map(b=>d(o,b,y,"actor_id")),_=m.props.map(b=>d(r,b,y,"prop_id")),A=m.actions.map((b,U)=>{a("action",`${w}#${U}`,b.identity_key);let O={type:b.type,content:b.content};if(b.speaker)if("name"in b.speaker){let I=o.ensure(b.speaker.name,y),L={actor_id:I.provisional_id};b.speaker.state!==void 0&&(L.state_id=o.stateId(I,b.speaker.state)),O.speaker=L}else O.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?O.emotion=b.parenthetical:b.emotion!==void 0&&(O.emotion=b.emotion)),b.extend!==void 0&&(O.extend=b.extend),O});return{scene_id:m.scene_id,...m.environment?{environment:m.environment}:{},location:x,actors:S,props:_,actions:A}})})),l=(u,h,m)=>u.list().map(g=>({[h]:g.provisional_id,[m]:g.names[0]??g.provisional_id,aliases:g.names.slice(1),description:"",states:_5(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 Rm(e,t={}){let n=t.maxChars??500,o=e.split(`
226
+ `),i=[],r=0,s=0,c=a=>{let d=o.slice(r,a).join(`
227
+ `);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 Mm=["episode","scene","action","dialogue","inner_thought","transition","note"];var E5={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 xo(e){if(typeof e!="string")return;let t=e.normalize("NFC").replace(/\s+/g,"").trim().toLocaleLowerCase();return E5[t]}var ge=class extends Error{constructor(n,o){super(`line ${o}: ${n}`);this.line=o}line};function Gi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zt(e,t,n){for(let o of Object.keys(e))if(!t.includes(o))throw new ge(`unknown field '${o}'`,n)}function S5(e,t){if(!Gi(e))throw new ge("missing source",t);Zt(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 ge("source needs integer chunk/line_start/line_end",t);if(o>=i)throw new ge("source line_start must be < line_end",t);return{chunk:n,line_start:o,line_end:i}}function Di(e,t,n){let o=e[t];if(typeof o!="string"||o==="")throw new ge(`'${t}' must be a non-empty string`,n);return o}function _o(e,t,n){if(!(t in e)||e[t]===void 0)return;let o=e[t];if(typeof o!="string"||o==="")throw new ge(`'${t}' must be a non-empty string`,n);return o}function Lm(e,t,n){if(!Array.isArray(e))throw new ge(`'${t}' must be an array`,n);return e.map(o=>{if(!Gi(o))throw new ge(`'${t}' entries must be objects`,n);Zt(o,["name","state"],n);let i={name:Di(o,"name",n)},r=_o(o,"state",n);return r!==void 0&&(i.state=r),i})}function I5(e,t){if(!Gi(e))throw new ge("dialogue/inner_thought needs a speaker",t);if("kind"in e){Zt(e,["kind","label"],t);let r=e.kind;if(typeof r!="string"||!Mn.includes(r))throw new ge(`speaker.kind must be one of ${Mn.join("|")}`,t);let s={kind:r},c=_o(e,"label",t);return c!==void 0&&(s.label=c),s}Zt(e,["name","state"],t);let n=Di(e,"name",t);if(!/[\p{L}\p{N}]/u.test(n))throw new ge("speaker.name must contain a letter or number",t);let o={name:n},i=_o(e,"state",t);return i!==void 0&&(o.state=i),o}function A5(e,t){let n=e.kind;if(typeof n!="string"||!Mm.includes(n))throw new ge(`unknown or missing kind '${String(n)}'`,t);let o=S5(e.source,t);switch(n){case"episode":{Zt(e,["kind","episode","title","source"],t);let i=e.episode;if(typeof i!="number"||!Number.isInteger(i))throw new ge("episode must be an integer",t);let r={kind:n,episode:i,source:o},s=_o(e,"title",t);return s!==void 0&&(r.title=s),r}case"scene":{Zt(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 ge("scene must be an integer",t);i.scene=e.scene}if("environment"in e&&e.environment!==void 0){if(!Gi(e.environment))throw new ge("environment must be an object",t);Zt(e.environment,["space","time"],t);let r={},s=_o(e.environment,"space",t);s!==void 0&&(r.space=s);let c=_o(e.environment,"time",t);if(c!==void 0){let a=xo(c);if(!a)throw new ge("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(!Gi(e.location))throw new ge("location must be an object",t);Zt(e.location,["name","state"],t);let r={name:Di(e.location,"name",t)},s=_o(e.location,"state",t);s!==void 0&&(r.state=s),i.location=r}return"actors"in e&&e.actors!==void 0&&(i.actors=Lm(e.actors,"actors",t)),"props"in e&&e.props!==void 0&&(i.props=Lm(e.props,"props",t)),i}case"action":case"transition":{Zt(e,["kind","content","source"],t);let i=Di(e,"content",t);return{kind:n,content:i,source:o}}case"dialogue":case"inner_thought":{Zt(e,["kind","speaker","content","emotion","source"],t);let i=Di(e,"content",t),r=I5(e.speaker,t),s={kind:n,speaker:r,content:i,source:o},c=_o(e,"emotion",t);return c!==void 0&&(s.emotion=c),s}case"note":{Zt(e,["kind","content","category","source"],t);let i=Di(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 ge("note.category must be author_note|format_note|unclassified",t);r.category=s}return r}default:throw new ge(`unhandled kind '${n}'`,t)}}function $r(e,t=0){let n=[],o=e.split(`
228
+ `);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 ge("invalid JSON",i+1+t)}if(!Gi(s))throw new ge("record must be a JSON object",i+1+t);n.push(A5(s,i+1+t))}return n}var W=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),ei=e=>{let t=/[((]/.exec(e);return!t||t.index===0?e:e.slice(0,t.index).trim()},k5=e=>e.startEp===e.endEp?`\u7B2C${e.startEp}\u96C6`:`\u7B2C${e.startEp}\u96C6\u2013\u7B2C${e.endEp}\u96C6`,ap=e=>e.startEp===e.endEp?`\u7B2C${e.startEp}\u96C6`:`\u7B2C${e.startEp}\u96C6\u2013\u7B2C${e.endEp}\u96C6`,Pm=()=>({newEntities:[],merges:[],looks:[],lookChanges:[],subEvents:[],summary:""}),Tm=()=>({entities:[],lookChanges:{},recent:[],synopsis:[]}),cp={recentEpisodes:6,synopsisChars:3500,arcFold:10},b5=1e4;function Vm(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 $m(e,t=b5){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 O5={actor:"\u4EBA\u7269",location:"\u573A\u666F",prop:"\u9053\u5177"};function Jt(e,t){let n=W(t);return e.entities.find(o=>W(o.canonical)===n||o.aliases.some(i=>W(i)===n))}var Nm=(e,t)=>{W(t)!==W(e.canonical)&&!e.aliases.some(n=>W(n)===W(t))&&e.aliases.push(t)},v5=["\u5E74\u8F7B","\u5E74\u8001","\u5E74\u5E7C","\u5E74\u5C11","\u4E2D\u5E74","\u9752\u5E74","\u5C11\u5E74","\u8001\u5E74","\u5E7C\u5E74","\u8001","\u5C0F","\u5927","\u5C11","\u5E7C"];function R5(e,t){let n=W(e),o=W(t);if(n===o||!n.includes(o))return!1;let i=n.replace(o,"").trim();return i.length>0&&!v5.some(r=>i===r||i.startsWith(r))}function M5(e){let t=e.filter(n=>e.some(o=>o!==n&&R5(n,o)));return t.length?t.reduce((n,o)=>o.length>n.length?o:n):e[0]}var Um=["\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"],L5=["\u4F17\u4EBA","\u7FA4\u4F17","\u6C11\u4F17","\u89C2\u4F17","\u4EBA\u7FA4","\u4EBA\u4EEC","\u5927\u5BB6","\u767E\u59D3","\u5B98\u5175"],N5=/^(?:一群|一众|全体|所有|几名|数名|多名|[0-9零一二两三四五六七八九十百千]+名?)/;function st(e){let t=W(e).replace(/[0-9零一二两三四五六七八九十百千]+名?$/,"").trim();return t?t.endsWith("\u4EEC")||Um.includes(t)||L5.some(n=>t.endsWith(n))?!0:N5.test(t)&&Um.some(n=>t.endsWith(n)):!1}function Eo(e,t){let n=ei(t);return Jt(e,n)?.canonical??n}function U5(e,t){let n=W(t);return e.looks.find(o=>W(o.name)===n||o.aliases.some(i=>W(i)===n))?.name??t}var C5=["\u5E38\u6001","\u65E5\u5E38","\u5E73\u65F6","\u57FA\u7840","\u666E\u901A"];function dp(e){if(e.looks.length!==0)return(e.looks.find(t=>C5.some(n=>t.name.includes(n)))??e.looks[0]).name}function sp(e,t,n,o){let i=W(ei(n));if(i)return e.entities.find(r=>r.kind===t&&r!==o&&(W(r.canonical)===i||r.aliases.some(s=>W(s)===i)))}function Cm(e){let t=[e.canonical,...e.aliases],n=M5(t);W(n)!==W(e.canonical)&&(e.canonical=n,e.aliases=t.filter(o=>W(o)!==W(n)))}function Dr(e,t,n,o=n){for(let r of t.newEntities){let s=ei(r.name);if(!s)continue;let c=sp(e,r.kind,s);if(!c){let d=[];for(let p of r.aliases){let l=ei(p);l&&W(l)!==W(s)&&!sp(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=ei(d);p&&!sp(e,r.kind,p,c)&&Nm(c,p)}!c.description&&r.description&&(c.description=r.description);let a=c.looks.find(d=>W(d.name)===W(r.defaultLook.name));a?a.description=r.defaultLook.description:c.looks.unshift({name:r.defaultLook.name,aliases:[],description:r.defaultLook.description}),Cm(c)}for(let{from:r,into:s}of t.merges){let c=ei(s);if(!c)continue;let a=Jt(e,c);if(!a)continue;let d=ei(r);!d||W(d)===W(a.canonical)||Jt(e,d)||(Nm(a,d),Cm(a))}for(let{entity:r,names:s,description:c}of t.looks){let a=Jt(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=>W(f.name)===W(p)||d.some(u=>f.aliases.some(h=>W(h)===W(u))));if(l){c&&(l.description=c);for(let f of d)W(f)!==W(l.name)&&!l.aliases.some(u=>W(u)===W(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=Eo(e,r.entity),a=r.look.trim();if(!s||!c||!a)continue;let d=Jt(e,c),p=d?U5(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=Jt(e,r);s&&(s.lastSeen=o)}return e.recent.push({startEp:n,endEp:o,summary:t.summary,subEvents:t.subEvents}),e}var P5=e=>e.summary.length+e.subEvents.reduce((t,n)=>t+n.length,0);function Dm(e,t=cp){for(;e.recent.length>t.recentEpisodes||e.recent.length>1&&e.recent.reduce((n,o)=>n+P5(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 pp(e,t=cp){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 Gm(e,t,n=cp){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 T5=6;function ra(e,t){let n=i=>t===void 0||i.lastSeen>=t-T5,o=["# \u8BBE\u5B9A"];for(let i of["actor","location","prop"]){let r=e.entities.filter(s=>s.kind===i);if(r.length){o.push(`## ${O5[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(`- ${ap(i)}\uFF1A${i.line}`)}if(e.recent.length){o.push("","# \u6700\u8FD1");for(let i of e.recent){o.push(`## ${k5(i)}`),i.summary.trim()&&o.push(`\u6897\u6982\uFF1A${i.summary.trim()}`);for(let r of i.subEvents)o.push(`- ${r}`)}}return o.join(`
229
+ `)}var V5=/(?:^|[,。!?;:、\s“”"'((])(他们|她们|它们|其中一人|另一个人|前者|后者|对方|有人|两人|他|她|它)(?!人)/;function Ji(e){let t=[],n=(o,i,r)=>{t.push({code:o,path:i,message:r})};return e.actors.forEach((o,i)=>{st(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=V5.exec(a.content);l&&n("production_action_pronoun",`${p}.content`,`action uses ambiguous reference ${l[1]}`)}})})}),t}var Fe=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pt=e=>Array.isArray(e),sa=e=>String(e).padStart(3,"0"),lp=[{key:"actors",idField:"actor_id",prefix:"act"},{key:"locations",idField:"location_id",prefix:"loc"},{key:"props",idField:"prop_id",prefix:"prp"}];function aa(e){if(!Fe(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 pt(t.episodes)?t.episodes:[])if(!(!Fe(a)||!pt(a.scenes))){for(let d of a.scenes)if(Fe(d)){Fe(d.location)&&r("locations",d.location.location_id);for(let p of pt(d.actors)?d.actors:[])Fe(p)&&r("actors",p.actor_id);for(let p of pt(d.props)?d.props:[])Fe(p)&&r("props",p.prop_id);for(let p of pt(d.actions)?d.actions:[])Fe(p)&&Fe(p.speaker)&&r("actors",p.speaker.actor_id)}}for(let{key:a,idField:d}of lp)for(let p of pt(t[a])?t[a]:[])Fe(p)&&r(a,p[d]);for(let{key:a,prefix:d}of lp)o[a].forEach((p,l)=>{n[a][p]=`${d}_${sa(l+1)}`});for(let{key:a,idField:d}of lp){let p=(pt(t[a])?t[a]:[]).filter(Fe),l=n[a],f=new Map;for(let u of p){let h=u[d],m=l[h]??h;u[d]=m;let g=0;for(let w of pt(u.states)?u.states:[]){if(!Fe(w)||typeof w.state_id!="string"||w.state_id==="default")continue;let y=`st_${sa(++g)}`;n.states[w.state_id]=y,w.state_id=y}f.set(m,u)}t[a]=[...f.entries()].sort((u,h)=>u[0]<h[0]?-1:1).map(u=>u[1])}let s=0;(pt(t.episodes)?t.episodes:[]).forEach((a,d)=>{if(Fe(a)){if(typeof a.episode_id=="string"){let p=`ep_${sa(d+1)}`;n.episodes[a.episode_id]=p,a.episode_id=p}for(let p of pt(a.scenes)?a.scenes:[])if(Fe(p)&&typeof p.scene_id=="string"){let l=`scn_${sa(++s)}`;n.scenes[p.scene_id]=l,p.scene_id=l}}});let c=(a,d,p)=>{!Fe(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 pt(t.episodes)?t.episodes:[])if(!(!Fe(a)||!pt(a.scenes))){for(let d of a.scenes)if(Fe(d)){c(d.location,"location_id","locations");for(let p of pt(d.actors)?d.actors:[])c(p,"actor_id","actors");for(let p of pt(d.props)?d.props:[])c(p,"prop_id","props");for(let p of pt(d.actions)?d.actions:[])Fe(p)&&c(p.speaker,"actor_id","actors")}}return{script:t,idMap:n}}import{createHash as $5}from"node:crypto";function Gr(e){let t=v(e).trim();if(!t.includes(":"))throw new E("Target invalid.",{exitCode:G,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(!Ll.has(o)||!i)throw new E("Target invalid.",{exitCode:G,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 So(){return{version:3,actor:{},location:{},prop:{},state:{},episode:{},scene:{},action:{}}}function Bt(e,t){let n=e.get(t);if(n===void 0)throw new Error(`Missing mapped ID for ${t}`);return n}function Bi(e,t=So(),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,L,T,C)=>{let R=T[L];if(R!==void 0){if(!V(I,R))throw new Error(`Invalid persisted ${I} ID for ${L}: ${R}`);if(C.has(R))throw new Error(`Duplicate persisted ${I} ID: ${R}`);return C.add(R),R}let j=To(I,C);return C.add(j),T[L]=j,j},c=(I,L)=>n[I]?.[L]??L;for(let I of e.actors){let L=s("actor",c("actor",I.actor_id),o.actor,r.actor);i.actor.set(I.actor_id,L)}for(let I of e.locations){let L=s("location",c("location",I.location_id),o.location,r.location);i.location.set(I.location_id,L)}for(let I of e.props){let L=s("prop",c("prop",I.prop_id),o.prop,r.prop);i.prop.set(I.prop_id,L)}let a=new Map,d=(I,L,T)=>{let C=new Map,R=new Set,j=c(I,L),Z=o.state[j]??{};o.state[j]=Z;let ve=T.map(K=>{let Re;if(K.state_id==="default")Re="default";else{let We=n.state?.[L]?.[K.state_id]??K.state_id,N=Z[We];if(N!==void 0){if(!V("state",N))throw new Error(`Invalid persisted state ID for ${L}/${K.state_id}: ${N}`);if(R.has(N))throw new Error(`Duplicate persisted state ID on ${L}: ${N}`);Re=N}else Re=To("state",R),Z[We]=Re}return R.add(Re),C.set(K.state_id,Re),{...K,state_id:Re}});return a.set(L,C),ve},p=(I,L)=>L===void 0?void 0:Bt(a.get(I)??new Map,L),l=e.actors.map(I=>({...I,actor_id:Bt(i.actor,I.actor_id),states:d("actor",I.actor_id,I.states)})),f=e.locations.map(I=>({...I,location_id:Bt(i.location,I.location_id),states:d("location",I.location_id,I.states)})),u=e.props.map(I=>({...I,prop_id:Bt(i.prop,I.prop_id),states:d("prop",I.prop_id,I.states)})),h=I=>{if("actor_id"in I){let L=p(I.actor_id,I.state_id);return{actor_id:Bt(i.actor,I.actor_id),...L===void 0?{}:{state_id:L}}}return I.label===void 0?{kind:I.kind}:{kind:I.kind,label:I.label}},m=I=>{if(I.includes(":")){let[T,C]=Gr(I);return Bt(T==="actor"?i.actor:T==="location"?i.location:i.prop,C)}let L=i.actor.get(I)??i.location.get(I)??i.prop.get(I);if(L===void 0)throw new Error(`Missing transition target mapping for ${I}`);return L},g=(I,L)=>{let T=s("action",L,o.action,r.action),C=I.transition_prompt===void 0?{}:{transition_prompt:{...I.transition_prompt,target:m(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:T,type:I.type,content:I.content,speaker:h(I.speaker),...I.emotion===void 0?{}:{parenthetical:I.emotion},...C,...I.extend===void 0?{}:{extend:I.extend}}}return{action_id:T,type:I.type,content:I.content,...C,...I.extend===void 0?{}:{extend:I.extend}}},w=(I,L)=>[p(I,L??"default")??"default"],y=(I,L)=>{let T=new Map;for(let C of I){let R=Bt(i.actor,C.actor_id),j=T.get(R)??new Set;w(C.actor_id,C.state_id).forEach(Z=>j.add(Z)),T.set(R,j)}for(let C of L){if(C.speaker===void 0||!("actor_id"in C.speaker))continue;let R=C.speaker.actor_id,j=Bt(i.actor,R),Z=T.get(j)??new Set;w(R,C.speaker.state_id).forEach(ve=>Z.add(ve)),T.set(j,Z)}return[...T].map(([C,R])=>({actor_id:C,state_ids:[...R].sort()}))},x=I=>{let L=new Map;for(let T of I){let C=Bt(i.prop,T.prop_id),R=L.get(C)??new Set;w(T.prop_id,T.state_id).forEach(j=>R.add(j)),L.set(C,R)}return[...L].map(([T,C])=>({prop_id:T,state_ids:[...C].sort()}))},S=new Set,_=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 L=n.episode?.[I.episode_id]??I.episode_id;S.add(L);let T=s("episode",L,o.episode,r.episode);return{...I,episode_id:T,scenes:I.scenes.map(C=>{let R=`${I.episode_id}/${C.scene_id}`,j=n.scene?.[R]??R;_.add(j);let Z=s("scene",j,o.scene,r.scene),ve=new Map;return{...C,scene_id:Z,location:C.location===null?null:{location_id:Bt(i.location,C.location.location_id),state_ids:w(C.location.location_id,C.location.state_id)},actors:y(C.actors,C.actions),props:x(C.props),actions:C.actions.map((K,Re)=>{let We=`${R}#${Re}`,N=JSON.stringify(wn(K)),ie=(ve.get(N)??0)+1;ve.set(N,ie);let we=$5("sha256").update(N).digest("hex"),mt=n.action?.[We]??`${j}:action:${we}:${ie}`;return A.add(mt),g(K,mt)})}})}})},U=(I,L)=>{for(let T of Object.keys(I))L.has(T)||delete I[T]};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,_),U(o.action,A);let O=[...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(O.map(I=>I.id)));for(let I of O)U(o.state[I.id]??{},new Set(I.states.map(L=>n.state?.[I.oldId]?.[L.state_id]??L.state_id)));return{script:b,identityMap:o}}import*as Oe from"node:fs";import*as ti from"node:path";function ca(e,t){let n=ti.dirname(e);Oe.mkdirSync(n,{recursive:!0});let o=ti.join(n,`.${ti.basename(e)}.${process.pid}.tmp`),i=Oe.openSync(o,"w");try{Oe.writeFileSync(i,t),Oe.fsyncSync(i)}finally{Oe.closeSync(i)}Oe.renameSync(o,e)}function D5(e,t){ca(e,JSON.stringify(t,null,2)+`
230
+ `)}function G5(e){return JSON.parse(Oe.readFileSync(e,"utf-8"))}var lt=class{constructor(t){this.root=t}root;abs(t){return ti.join(this.root,t)}ensure(){Oe.mkdirSync(this.root,{recursive:!0})}passDir(t){let n=this.abs(t);return Oe.mkdirSync(n,{recursive:!0}),n}readText(t){return Oe.readFileSync(this.abs(t),"utf-8")}writeText(t,n){ca(this.abs(t),n)}writeJson(t,n){D5(this.abs(t),n)}readJson(t){return G5(this.abs(t))}has(t){return Oe.existsSync(this.abs(t))}path(t){return this.abs(t)}clearError(t){let n=this.abs(t);Oe.existsSync(n)&&Oe.rmSync(n)}};function Wt(e,t){e=e-0;let n=up(),o=n[e];if(Wt.wCYmoh===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=c.charAt(h++);~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)};Wt.ccSjUe=i,Wt.dKlJjl={},Wt.wCYmoh=!0}let r=n[0];Wt.sBhMJx!==r&&(Wt.dKlJjl={},Wt.sBhMJx=r);let s=Wt.dKlJjl[e];return s===void 0?(o=Wt.ccSjUe(o),Wt.dKlJjl[e]=o):o=s,o}var F=Wt,J5=[F(40),F(37),F(24),F(75),F(5),F(21),"",F(65),F(13),F(34),F(62),"",F(70),F(35),F(42),F(27),F(39),F(43),F(0),F(68),F(55),"",F(77),F(18),F(58),F(10),F(11),F(51),F(59),F(66),F(8),F(3),F(76),"",F(15),F(4),F(9),F(6),F(20),F(14),F(45),F(48),F(38),F(54)][F(74)](`
231
+ `);function B5(e){let t=F,n=e[t(73)]===0?t(47):t(23);return[t(78),n,t(49),"",e[t(53)]][t(74)](`
232
+ `)}function da(e,t){let n=F;return new E(e,{exitCode:me,errorCode:n(12),hint:n(44),data:{actual:t}})}function K5(e){let t=F;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 fp(e,t){let n=F;if(!K5(e))throw da(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 ge(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)](`
233
+ `);i=$r(r)}catch(r){throw r instanceof ge?da(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)]):da(n(19)+t[n(73)]+n(69),[n(2)]);return i}function up(){let e=["lsdOVAZLNlRVVjP7iMTPBMqIoIj0CMfUC2L0Aw9UiIWIy29UDgvUDci6iUw/OowUNUI9RoAnOUAiKoEUGos9K+s4REAwH+EAHoI9RowCUUAwH+wTLYj944cc5BI46kEb5Qc85BYp6k+n5lMF6kAb57+76k+r77Ym5l6l5AAcigbgteftsejbq0TGiokgKIbG6zEQ5zUEyooaGwbcqunlifrpifbsrvnftLrGiokgKIbG5zUE5yIW546W5A6EyooaGG","BgvUz3rO","CMvJB3jKCZOGma","icdOKAhOR63LIQJKVzWGyfvTihbYyxrVigrLig9MzxjLBMrHCYbJywKGzgeGBwvZysbLihnLigvZCgfSAgeGCgvSBYbJAmoJBY5GiokgKIbHy3rPB24Uy29UDgvUDd1G5lIa55Uy5l6B5zob5lUo5Qgm5lIk5O6j6jc977Ym5PwJ6jc95lIa5zYW44ccyooaGUs6UUEjQEIVTowhUUEAHoIrOEIVREwVUEEzVEs7JEMaKowTL+s/NEEvME+8Jos4JEE/U+IVKE+8M1jPy2HHCMtJGiffBwLSEsdNRyNKURRNIANLKi3LP4VNU4JKV53MJihLJP/MLOFMI7ZLHPNJGii","5Q2J5PAh5y+J5B6e77YAzgLHBg9NDwxJGifPBM5LCL90Ag91z2H0ioEAHcbJB250zw50ioMaKowTL+wUJoAvTos/NEEvME+8Jos4JEA2PUIjSUoaGEs4JEAjQEwgMEoaGEs4JEE6OoMuMEoaGEs4JEE/U+IVKEoaGMfJDgLVBUoaGxrYyw5ZAxrPB27JGifUB3rLiowsJcbLBw90Aw9Uiow/OowUNUI9RoAnOUAiKoEUGos9K+s4REAwH++8M+E/U+IVKEs4JEw+L+AuUEwpMooaGEwiOowhJ+AiLUIHPEMaOowoN+AwH+s6I+wUNUoaGEwBOoAENooaGEMHUUw6J+oaGEwkQos9NoE7K+AENooaGEs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cn77YB5zob54Mm5zkm5RkH5PYj6ycA6kgm6k+r5zcn55Qe5yw25lUw5lIt5zcn5l+D55wz5y6F5PAh44cc5lIn5B6x5OQk5Pw05y+L5Asw6k+T5yQO5l2C5OIw546V5Akd5O+p6l+W5y6F5Qc355wz5zYOigfJDgLVBIdKUk3JGii","icdLKiZKUidLJ6xNLlhLPjRKURRLKiZML7BOR7tML7BVViZKUlRMR4/KUkROR7tOR53KURRLKitLHPNKUidMNAhNM7JPGRSGzgLHBg9NDwxVViXJB250zw50ioEBUowqJooaGG","6l2S5O2I6kEe5yIz77YA","44cq5B6f6kEe6iYd5yYw55Qe5y6F5PAh54Mh5Q6144cr"];return up=function(){return e},up()}async function Jm(e,t,n){let o=F,i=await e[o(41)](o(71),{system:J5,user:B5(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 da(o(19)+t[o(73)]+o(50),[i[o(53)][o(7)](0,500)])}return{raw:i[o(53)],records:fp(r,t)}}var gp=Xt,j5=gp(1);function z5(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 mp(){let e=["Dgv4Da","5l2G5PIV55+T5yMN5yMN5PYS55Qe44cm5Q2J5PAh6lw354k55A6A5l2n5zMO44cn44cc5lIa5lU95PAh5lU25BI45BI45zYO55YF5Q2J55Qe5yMN5PYS5Q2J5PAh5lMl5yMn77Ym5y6l552a5lIa5AsN5Q61kIRPNz7MRApMLOCQkUEAHoETUEwKH+ADKoAwMEoaGUs9OoIMGEwiPoAwRE+8MIOQ55YF5Q2J55Qe5yMN5PYS5Q2J5PAhkIRMMk/KUi3MMk/LNkJMIjhNU5NKVAdNMOtOV5NMRRxLUkBOOyZLJ7FNMOtMLOFMNkZPH4ZLVidLP4VVViZLPOlMNPZMMk/VViZMIQxLKyRLRO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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 mp=function(){return e},mp()}async function Bm(e,t,n){let o=gp,i=await e[o(4)](o(2),{system:j5,user:o(6)+t,...n?{signal:n}:{}});return z5(i[o(0)])}function Xt(e,t){e=e-0;let n=mp(),o=n[e];if(Xt.sLepLJ===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=c.charAt(h++);~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)};Xt.TPTWLA=i,Xt.iYuNay={},Xt.sLepLJ=!0}let r=n[0];Xt.inDmHY!==r&&(Xt.iYuNay={},Xt.inDmHY=r);let s=Xt.iYuNay[e];return s===void 0?(o=Xt.TPTWLA(o),Xt.iYuNay[e]=o):o=s,o}var Km=50,H5=10;async function jm(e,t,n){let o=t.split(`
234
+ `),i=Km-H5;try{for(let r=0;r<o.length;r+=i){let s=Math.min(r+Km,o.length),c=o.slice(r,s).map((d,p)=>`${r+p+1} ${d}`).join(`
235
+ `),a=await Bm(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 zm(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 Kt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),en=e=>Array.isArray(e);function hp(e){let t=new Map;if(!en(e))return t;for(let n of e){if(!Kt(n))continue;let o=n.actor_id??n.location_id??n.prop_id;typeof o=="string"&&t.set(o,n)}return t}function Q5(e){let t=[],n=(o,i)=>{!Kt(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 en(e.episodes)?e.episodes:[])if(!(!Kt(o)||!en(o.scenes))){for(let i of o.scenes)if(Kt(i)){n(i.location,"location_id");for(let r of en(i.actors)?i.actors:[])n(r,"actor_id");for(let r of en(i.props)?i.props:[])n(r,"prop_id");for(let r of en(i.actions)?i.actions:[])Kt(r)&&n(r.speaker,"actor_id")}}return t}function F5(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 pa(e){if(!Kt(e))throw new Error("govern expects a script object");let t=JSON.parse(JSON.stringify(e));for(let p of en(t.episodes)?t.episodes:[])if(!(!Kt(p)||!en(p.scenes)))for(let l of p.scenes){if(!Kt(l))continue;let f=en(l.actors)?l.actors.filter(Kt):[],u=new Set(f.map(h=>h.actor_id).filter(h=>typeof h=="string"));for(let h of en(l.actions)?l.actions:[])!Kt(h)||!Kt(h.speaker)||typeof h.speaker.actor_id!="string"||u.has(h.speaker.actor_id)||(f.push({actor_id:h.speaker.actor_id}),u.add(h.speaker.actor_id));l.actors=f}let n=hp(t.actors),o=hp(t.locations),i=hp(t.props),r=new Map([...n,...o,...i]),s=Q5(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=(en(l.states)?l.states:[]).filter(Kt),u=new Map,h=F5(f,c.get(p)??new Map),m;if(h===null){let g=f.find(w=>w.state_id==="default");m=[{state_id:"default",state_name:g?.state_name??"default",description:g?.description??""}]}else{m=[];for(let g of f)g.state_id!=="default"&&(g.state_id===h?(u.set(g.state_id,"default"),m.unshift({state_id:"default",state_name:g.state_name,description:g.description??""})):(u.set(g.state_id,g.state_id),m.push({state_id:g.state_id,state_name:g.state_name,description:g.description??""})))}l.states=m,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 Hm=tn;function tn(e,t){e=e-0;let n=yp(),o=n[e];if(tn.vcGzia===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=c.charAt(h++);~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)};tn.alaGPc=i,tn.IPZchV={},tn.vcGzia=!0}let r=n[0];tn.cEXTRr!==r&&(tn.IPZchV={},tn.cEXTRr=r);let s=tn.IPZchV[e];return s===void 0?(o=tn.alaGPc(o),tn.IPZchV[e]=o):o=s,o}var Y5=Hm(6);async function Qm(e,t,n,o){let i=Hm;return(await e[i(4)](i(2),{system:Y5,user:i(0)+t+i(3)+n,...o?{signal:o}:{}}))[i(5)][i(1)]()}function yp(){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 yp=function(){return e},yp()}var Zm={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"]}}}}}},wp={type:"array",items:{type:"object",required:["asset_id","state_id"],additionalProperties:!1,properties:{asset_id:{type:"string"},state_id:{type:["string","null"]}}}},aN={type:"object",required:["scenes"],additionalProperties:!1,properties:{scenes:{type:"array",items:{type:"object",required:["scene_id"],additionalProperties:!1,properties:{scene_id:{type:"string"},actors:{...wp,items:{type:"object",required:["actor_id","state_id"],additionalProperties:!1,properties:{actor_id:{type:"string"},state_id:{type:["string","null"]}}}},locations:{...wp,items:{type:"object",required:["location_id","state_id"],additionalProperties:!1,properties:{location_id:{type:"string"},state_id:{type:["string","null"]}}}},props:{...wp,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"]}}}}}}}}},Wm={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"}}},Xm={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:Wm}}},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"}}},q5={type:"string",enum:["actor","location","prop"]},eg={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"},Fm={type:"string",minLength:5,pattern:"^[0-9]{2}:[0-5][0-9]$",description:"\u5FC5\u586B\u4E14\u4E0D\u5F97\u4E3A\u7A7A\u3002\u672C\u955C\u5934\u6216\u58F0\u97F3\u771F\u6B63\u5F00\u59CB\u7684\u65F6\u95F4\u6233\uFF0C\u4E25\u683C\u4F7F\u7528 MM:SS\uFF08\u4F8B\u5982\u300E00:03\u300F\uFF09\uFF1BSS \u5FC5\u987B\u4E3A 00-59\uFF0C\u6574\u5206\u949F\u5199\u6210\u4E0B\u4E00\u5206\u949F\u7684 :00\uFF0C\u7981\u6B62\u5199 :60\u3001null\u3001\u672A\u77E5\u503C\u6216\u5C0F\u6570\u79D2"},Ym={type:"object",required:["name","description"],additionalProperties:!1,properties:{name:eg,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"}}},qm={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"}}},tg={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\uFF1BSS \u5FC5\u987B\u4E3A 00-59\uFF0C\u6574\u5206\u949F\u5199\u6210\u4E0B\u4E00\u5206\u949F\u7684 :00\uFF0C\u7981\u6B62\u5199 :60"},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:eg,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:Fm,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:Fm,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:q5,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:qm,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:Ym,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:qm,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:Ym,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"}}}}}}}},ng={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:Wm}}}}};var z=nn;function nn(e,t){e=e-0;let n=xp(),o=n[e];if(nn.AowUYu===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=c.charAt(h++);~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)};nn.vGSHGD=i,nn.ykrKeL={},nn.AowUYu=!0}let r=n[0];nn.qbkWqr!==r&&(nn.ykrKeL={},nn.qbkWqr=r);let s=nn.ykrKeL[e];return s===void 0?(o=nn.vGSHGD(o),nn.ykrKeL[e]=o):o=s,o}var Z5=[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)](`
236
+ `);function W5(e,t){let n=z;return[n(4),e[n(50)]()||n(5),"",n(66),t[n(50)]()][n(33)](`
237
+ `)}async function og(e,t,n,o){let i=z,r=await e[i(45)](i(69),{system:Z5,user:W5(t,n),tool:{name:i(44),description:i(22),inputSchema:Xm},...o?{signal:o}:{}});return{delta:Jr(r[i(49)]),raw:JSON[i(38)](r[i(49)])}}var X5=new Set([z(60),z(40),z(99)]),ii=e=>typeof e===z(78)&&e!==null&&!Array[z(13)](e),Hn=e=>typeof e===z(9)?e[z(50)]():"";function la(e,t){let n=z,o=Hn(e);if(!o)throw new Pe(t+n(36));return o}function eS(e,t){let n=z;if(!ii(e))throw new Pe(t+n(31));let o=la(e[n(32)],t+n(90));if(o!=="\u5E38\u6001")throw new Pe(t+n(29));return{name:o,description:la(e[n(15)],t+n(93))}}var Pe=class extends Error{[z(12)]=z(34);constructor(t){let n=z;super(t),this[n(32)]=n(0)}};function tS(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)](`
238
+ `);else n+='\\"';continue}n+=r}return n}function nS(e,t){let n=z,o=r=>JSON[n(101)](r),i;try{i=o(e)}catch(r){let s=tS(e);if(s===e)throw new Pe(t+n(89)+(r instanceof Error?r[n(20)]:String(r)));try{i=o(s)}catch(c){throw new Pe(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 Pe(t+n(91)+typeof i);return i}function ni(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?nS(o,t):[]}throw new Pe(t+n(19)+typeof e)}var oS=/[((]([^))]*)[))]?/;function xp(){let e=["u2vYAwfSrgvSDgftAgfWzuvYCM9Y","icdcTYbHBgLHC2vZid0G6l+z5Q616yEm6k+L5A6E5l2t55QekIRMIydMNiNLHBBKU5BLJ6VMS5uQkU+8JoMaKos4QUwnLEwiL++8IoE6R+wqJE+8JowiQ+w4PUoaJU+8Iow/G++8IEoaJ+oaJU+8MUoaJ+oaJU+8JoMTGUIVREoaJ+I/MEEXU+wVUEEzVs/MG4xNU6RMOiFORRdVViNVVjRLIkVLKi3JGihOR5hLKi3JGihLIy3KUjBLKi3JGihNN63LKi0V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q5PYj5B2tigzYB20G56gU5A6E5PIVigLUDg8G55Qe5y+M5lIa5y+R5Rov5PE25OMnig1LCMDL77YB5zcn5A2x5OIw5Asw6kEc55U45lY85l2g5PIV5lIn5zcm6kEs6iMY77Yi5AAc5zcm5lI66AQ36AUf5l2g6lQR5lU95lIn5zcm77Yj57UD5lInig1LCMDL44cckIOGzNjVBsdLT7lNU4/MMk/NI6ZNQ4VNMBVORRdNMOtLRP7KVzpML7BVViZKUi3OPOeGBwvYz2xVViJNS7VNU5/KUi3KVjRLKiJLUBBKUktKUkRLT7lNMBVORRdLRP7KVzpVViNJGii","DxDQzw4","44cq5BEY55+L6k6+5A6A44cr77Yi5OIQ6iEZ5lIk5lIa5Q615l2G5BEY5BU656Ul55Qe55M76k6W77YB5BYa56+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/KVjRNHACGBwvYz2vZicSGywXPyxnLCYdMIORMRApMLOFVViJLR7NNMB3OR7tOR53KURRJGihML4hNMB3MLOFMNkZVViNPH4ZNMOtOV5NKUPVLHPNMS5xNM7tMJQ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Q+b77YB6ygt5yw355QeioEGToAnNY/LJ5hLHyNVViNJGiiQkUMaOowEI+wqJEw/HEMHU+EuQos4REAwHYOQ77YA5Q2J5PAh6yEm55Qe6iUX5PAh5lIt5zcn77Yi5Awx6kofl+IbJos4MI/LVAlMGihLKi3VViZLPOiGu2vHBIDZifjLDMvUz2xJGifgBgfTzwnHC3rLCUoaGuDYyxzLifbYAwvZDooaGvnOAwvSzgD1yxjK77Yj5lIa5B6l6k+r5OIq5lIT5PAh5yAn5l2C6ycG5z6l5zcn77Yi6ikw5OgP55Qe5Asn5lUh5Awx6kof44cb54sW5PYV5BIi44cb5Akt56wT5y+444cb55U+5y2R77Yj44cc","oIbLEhbLy3rLzcbku09oigfYCMf5ihn0CMLUzYWGCgfYC2uGzMfPBgvKoIa","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 xp=function(){return e},xp()}function _p(e){let t=z,n=Hn(e),o=oS[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 oi=e=>_p(Hn(e))[z(32)];function iS(e){let t=z;if(ii(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 Pe(t(53)+(i instanceof Error?i[t(20)]:String(i)))}if(!ii(o)){if(t(3)===t(3))throw new Pe(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 Jr(e){let t=z,n=Pm(),o=iS(e);if(!o)return n;for(let i of ni(o[t(25)],t(25))){if(!ii(i))continue;let r=Hn(i[t(52)]),{name:s,aliases:c}=_p(Hn(i[t(32)]));if(!X5[t(62)](r)||!s)continue;let a=la(i[t(15)],t(81)+s+t(93)),d=eS(i[t(75)],t(81)+s+t(43)),p=[...c];for(let f of ni(i[t(16)],t(68))){let{name:u,aliases:h}=_p(Hn(f));u&&p[t(76)](u),p[t(76)](...h)}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 ni(o[t(57)],t(57))){if(!ii(i))continue;let r=oi(i[t(11)]),s=oi(i[t(80)]);r&&s&&r!==s&&n[t(57)][t(76)]({from:r,into:s})}for(let i of ni(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(!ii(i))continue;let r=oi(i[t(17)]),s=oi(i[t(32)]);if(!r||!s)continue;let c=[s,...ni(i[t(16)],t(94))[t(63)](oi)[t(18)](Boolean)];n[t(42)][t(76)]({entity:r,names:c,description:la(i[t(15)],t(7)+r+"."+s+t(93))})}}for(let i of ni(o[t(85)],t(85))){if(!ii(i))continue;let r=Hn(i[t(87)]),s=oi(i[t(17)]),c=oi(i[t(103)]);r&&s&&c&&n[t(85)][t(76)]({scene:r,entity:s,look:c})}return n[t(96)]=ni(o[t(96)],t(96))[t(63)](Hn)[t(18)](Boolean),n[t(97)]=Hn(o[t(97)]),n}var Ye=on,rS=[Ye(1),Ye(29),Ye(18),Ye(32),Ye(0),Ye(7),Ye(15),Ye(8),Ye(3)][Ye(21)](`
239
+ `);function sS(e,t){let n=Ye;return[n(13),e[n(27)]()||n(19),"",n(4),t[n(14)](o=>"- "+o)[n(21)](`
238
240
  `)][n(21)](`
239
- `)}async function hm(e,t,n,o){let i=Qe,r=await e[i(24)](i(26),{system:y5,user:w5(t,n),tool:{name:i(11),description:i(12),inputSchema:mm},...o?{signal:o}:{}});return{delta:Fd(r[i(5)],n),raw:JSON[i(30)](r[i(5)])}}var zs=e=>e[Qe(23)](Qe(6))[Qe(31)](/\s+/g," ")[Qe(27)]();function Fd(e,t=[]){let n=Qe,o=br(e),i=new Set;for(let s of o[n(22)])i[n(9)](zs(s[n(33)]));for(let s of o[n(25)]){i[n(9)](zs(s[n(10)]));for(let c of s[n(28)])i[n(9)](zs(c))}let r=t[n(20)](s=>!i[n(2)](zs(s)));if(r[n(17)])throw new Pe(n(16)+r[n(21)]("\u3001"));return o}function Ft(e,t){e=e-0;let n=Qd(),o=n[e];if(Ft.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)};Ft.xoIkcy=i,Ft.GcFqUp={},Ft.brkHeO=!0}let r=n[0];Ft.pyAYZq!==r&&(Ft.GcFqUp={},Ft.pyAYZq=r);let s=Ft.GcFqUp[e];return s===void 0?(o=Ft.xoIkcy(o),Ft.GcFqUp[e]=o):o=s,o}function Qd(){let e=["5PAW5lQ654MP55QeignHBM9UAwnHBcbUyw1LioEBToAoPEs9V+EuQooaKow+HEw9KUs4GowqJEwTL+oaKEMhJoEAHowoN+AwH+wNK+wqJEAlVowgME+8M+wKLUIVREwNK+wqJEs4JEE/U+IVKEoaGEs4JEMFS+IVKEoaGEs4JEAuUEAiKos4REAwH+wqJEoaGG","5l2G5PIV5yMN5PYS5A6E5l2t5B2s5lIa5l+U5Asn5zMO44cc44cq5BEY55+L6k6+5A6A44cr5PIV5BEY5BU656Ul55Qe5A6E5l2t55M76k6W77YiCMvNAxn0zxlVViNJGilKUiVPNAlJGjdLVOxLVzlKUidLKi3LRzFJGjhMMk/MRApMLOFPH4ZLH7RNJRdJGihKVyBOV5JMSQhOG73LR7NLUPtLIlaGCMvNAxn0zxiG6yEm5lU75l2v5A6E5l2t55Qe5zcn5A2x44cc","AgfZ","5y+Q6l6t5yE6ig1LCMDLCYdLKOWGBMv3rw50AxrPzxmG5lIK6Ag577Ym6kAg55UwkIRMR4/KUidKUkOQkUw+HEw9KUs4GowqJEwTL+oaGG","44cq5B6f5B2s5lIa5zcn5A2x44cr77Yi5Q2J5PAh6yEm5yE6546W5l2g5PYQ5A+55BQu5yIW5lU75l2v5BEY55M76k6W5A6E5l2t77Ym6ycq5lIQ5Ase55cg77Yj","Aw5WDxq","tKzd","5lQ654MPigrLC2nYAxb0Aw9UiowpQUwgMEI6Q+s7V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MLJywX944cc","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 Qd=function(){return e},Qd()}var gt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ht=e=>Array.isArray(e),E5=5,jo=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),ym=e=>{try{return JSON.parse(e)}catch{return null}},_5=new Set(["timeout","rate_limited","request_failed","endpoint","empty_response","invalid_response","truncated","serial_delta_shape"]),Sm=e=>!!e&&typeof e=="object"&&"code"in e&&_5.has(String(e.code)),Im=e=>new Promise(t=>setTimeout(t,e)),Ri=(e,t)=>e===t?`episode ${e}`:`episodes ${e}-${t}`;async function wm(e,t,n,o,i,r){for(let s=1;;s++)try{return await gm(e,o,i,r)}catch(c){if(Sm(c)&&s<3&&!r?.aborted){await Im(3e3*s);continue}throw new x(`serial govern failed at ${Ri(t,n)}.`,{exitCode:b,errorCode:"INGEST_SERIAL_FAILED",hint:c instanceof Pe?`Model returned a malformed serial delta (${c.message}). Rerun \`scriptctl ingest\` (optionally --force) to retry ${Ri(t,n)}.`:`Rerun \`scriptctl ingest\` to resume from ${Ri(t,n)} (earlier windows are cached).`,data:{actual:[c instanceof Error?c.message:String(c)]}})}}function Am(e,t){let n=t.merges.map(o=>o.into).filter(o=>!Lt(e,o));if(n.length)throw new Pe(`name-fix merge target is not registered: ${[...new Set(n)].join("\u3001")}`)}async function Em(e,t,n,o,i,r,s){for(let c=1;;c++)try{let a=await hm(e,o,i,s);return Am(r,a.delta),a}catch(a){if(Sm(a)&&c<3&&!s?.aborted){await Im(3e3*c);continue}throw new x(`serial name repair failed at ${Ri(t,n)}.`,{exitCode:b,errorCode:"INGEST_SERIAL_NAME_FIX_FAILED",hint:a instanceof Pe?`Model returned an incomplete name repair (${a.message}). Rerun \`scriptctl ingest\` to retry ${Ri(t,n)}.`:`Rerun \`scriptctl ingest\` to resume from ${Ri(t,n)} (earlier windows are cached).`,data:{actual:[a instanceof Error?a.message:String(a)]}})}}async function km(e,t){let n=Df(),o=e.episodes??[],i=0,r=o.map(A5),s=Jf(r.map(Gf),t.windowTokens);for(let a=0;a<s.length;a++){let[d,p]=s[a],l=Ps(n,p),f=r.slice(d-1,p).join(`
241
+ `)}async function ig(e,t,n,o){let i=Ye,r=await e[i(24)](i(26),{system:rS,user:sS(t,n),tool:{name:i(11),description:i(12),inputSchema:ng},...o?{signal:o}:{}});return{delta:Sp(r[i(5)],n),raw:JSON[i(30)](r[i(5)])}}var ua=e=>e[Ye(23)](Ye(6))[Ye(31)](/\s+/g," ")[Ye(27)]();function Sp(e,t=[]){let n=Ye,o=Jr(e),i=new Set;for(let s of o[n(22)])i[n(9)](ua(s[n(33)]));for(let s of o[n(25)]){i[n(9)](ua(s[n(10)]));for(let c of s[n(28)])i[n(9)](ua(c))}let r=t[n(20)](s=>!i[n(2)](ua(s)));if(r[n(17)])throw new Pe(n(16)+r[n(21)]("\u3001"));return o}function on(e,t){e=e-0;let n=Ep(),o=n[e];if(on.brkHeO===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=c.charAt(h++);~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)};on.xoIkcy=i,on.GcFqUp={},on.brkHeO=!0}let r=n[0];on.pyAYZq!==r&&(on.GcFqUp={},on.pyAYZq=r);let s=on.GcFqUp[e];return s===void 0?(o=on.xoIkcy(o),on.GcFqUp[e]=o):o=s,o}function Ep(){let e=["5PAW5lQ654MP55QeignHBM9UAwnHBcbUyw1LioEBToAoPEs9V+EuQooaKow+HEw9KUs4GowqJEwTL+oaKEMhJoEAHowoN+AwH+wNK+wqJEAlVowgME+8M+wKLUIVREwNK+wqJEs4JEE/U+IVKEoaGEs4JEMFS+IVKEoaGEs4JEAuUEAiKos4REAwH+wqJEoaGG","5l2G5PIV5yMN5PYS5A6E5l2t5B2s5lIa5l+U5Asn5zMO44cc44cq5BEY55+L6k6+5A6A44cr5PIV5BEY5BU656Ul55Qe5A6E5l2t55M76k6W77YiCMvNAxn0zxlVViNJGilKUiVPNAlJGjdLVOxLVzlKUidLKi3LRzFJGjhMMk/MRApMLOFPH4ZLH7RNJRdJGihKVyBOV5JMSQhOG73LR7NLUPtLIlaGCMvNAxn0zxiG6yEm5lU75l2v5A6E5l2t55Qe5zcn5A2x44cc","AgfZ","5y+Q6l6t5yE6ig1LCMDLCYdLKOWGBMv3rw50AxrPzxmG5lIK6Ag577Ym6kAg55UwkIRMR4/KUidKUkOQkUw+HEw9KUs4GowqJEwTL+oaGG","44cq5B6f5B2s5lIa5zcn5A2x44cr77Yi5Q2J5PAh6yEm5yE6546W5l2g5PYQ5A+55BQu5yIW5lU75l2v5BEY55M76k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sioAuVUI/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 Ep=function(){return e},Ep()}var St=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),It=e=>Array.isArray(e),aS=5,ri=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),rg=e=>{try{return JSON.parse(e)}catch{return null}},cS=new Set(["timeout","rate_limited","request_failed","endpoint","empty_response","invalid_response","truncated","serial_delta_shape"]),pg=e=>!!e&&typeof e=="object"&&"code"in e&&cS.has(String(e.code)),lg=e=>new Promise(t=>setTimeout(t,e)),Ki=(e,t)=>e===t?`episode ${e}`:`episodes ${e}-${t}`;async function sg(e,t,n,o,i,r){for(let s=1;;s++)try{return await og(e,o,i,r)}catch(c){if(pg(c)&&s<3&&!r?.aborted){await lg(3e3*s);continue}throw new E(`serial govern failed at ${Ki(t,n)}.`,{exitCode:k,errorCode:"INGEST_SERIAL_FAILED",hint:c instanceof Pe?`Model returned a malformed serial delta (${c.message}). Rerun \`scriptctl ingest\` (optionally --force) to retry ${Ki(t,n)}.`:`Rerun \`scriptctl ingest\` to resume from ${Ki(t,n)} (earlier windows are cached).`,data:{actual:[c instanceof Error?c.message:String(c)]}})}}function ug(e,t){let n=t.merges.map(o=>o.into).filter(o=>!Jt(e,o));if(n.length)throw new Pe(`name-fix merge target is not registered: ${[...new Set(n)].join("\u3001")}`)}async function ag(e,t,n,o,i,r,s){for(let c=1;;c++)try{let a=await ig(e,o,i,s);return ug(r,a.delta),a}catch(a){if(pg(a)&&c<3&&!s?.aborted){await lg(3e3*c);continue}throw new E(`serial name repair failed at ${Ki(t,n)}.`,{exitCode:k,errorCode:"INGEST_SERIAL_NAME_FIX_FAILED",hint:a instanceof Pe?`Model returned an incomplete name repair (${a.message}). Rerun \`scriptctl ingest\` to retry ${Ki(t,n)}.`:`Rerun \`scriptctl ingest\` to resume from ${Ki(t,n)} (earlier windows are cached).`,data:{actual:[a instanceof Error?a.message:String(a)]}})}}async function fg(e,t){let n=Tm(),o=e.episodes??[],i=0,r=o.map(uS),s=$m(r.map(Vm),t.windowTokens);for(let a=0;a<s.length;a++){let[d,p]=s[a],l=ra(n,p),f=r.slice(d-1,p).join(`
240
242
 
241
243
  `),u=t.sourceRef?`# \u539F\u6587\u8BBE\u5B9A\uFF08\u53C2\u8003\uFF0C\u6765\u81EA\u539F\u7A3F\u5F00\u5934\uFF09
242
244
  ${t.sourceRef}
243
245
 
244
- ${l}`:l,g=Date.now(),m=t.force?void 0:t.checkpoint?.readUpdate(d,p),h,w=!1;if(m!==void 0){let E=ym(m);try{if(E==null)throw new Pe("checkpoint top-level JSON is unparseable");h=br(E),w=!0,i++,t.executor.recordReuse("ingest.episode-assets")}catch(I){if(!(I instanceof Pe))throw I;let _=await wm(t.executor,d,p,u,f,t.signal);h=_.delta,t.checkpoint?.writeStep(d,p,l,_.raw)}}else{let E=await wm(t.executor,d,p,u,f,t.signal);h=E.delta,t.checkpoint?.writeStep(d,p,l,E.raw)}Ar(n,h,d,p);let y=x5(o.slice(d-1,p),n);if(y.length){let E=t.force?void 0:t.checkpoint?.readNameFix?.(d,p);if(E!==void 0){let I=ym(E);try{if(I==null)throw new Pe("name-fix checkpoint top-level JSON is unparseable");let _=Fd(I,y);Am(n,_),Ar(n,_,d,p),i++,t.executor.recordReuse("ingest.name-fix")}catch(_){if(!(_ instanceof Pe))throw _;let A=await Em(t.executor,d,p,Ps(n,p),y,n,t.signal);t.checkpoint?.writeNameFix?.(d,p,A.raw),Ar(n,A.delta,d,p)}}else{let I=await Em(t.executor,d,p,Ps(n,p),y,n,t.signal);t.checkpoint?.writeNameFix?.(d,p,I.raw),Ar(n,I.delta,d,p)}}Bf(n);for(let E=Pd(n);E;E=Pd(n)){let I=E[0].startEp,_=E[E.length-1].endEp,A=t.force?void 0:t.checkpoint?.readArc?.(I,_),k;if(A!==void 0)k=A,i++,t.executor.recordReuse("ingest.arc-summary");else{let P=E.map(O=>`${Ld(O)}\uFF1A${O.line}`).join(`
245
- `);k=await rm(t.executor,`\u7B2C${I}\u96C6\u2013\u7B2C${_}\u96C6`,P,t.signal),t.checkpoint?.writeArc?.(I,_,k)}Kf(n,k)}t.onWindow?.({startEp:d,endEp:p,ms:Date.now()-g,cached:w,index:a,total:s.length,totalEpisodes:o.length})}return{...k5(e,n),episodes:o.length,reused:i}}function x5(e,t){let n=new Set,o=i=>{if(!i)return;let r=so(t,i);et(r)||Lt(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 S5={interior:"\u5185",exterior:"\u5916"},I5={day:"\u65E5",night:"\u591C"};function A5(e){let t=[`# ${e.episode_id}${e.title?` ${e.title}`:""}`];for(let n of e.scenes){t.push(`## ${n.scene_id}`);let o=[S5[n.environment?.space??""],I5[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(`
246
- `)}function k5(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=h=>!!Lt(t,h),p=a.location?so(t,a.location.name):null,l=_m(a.actors.map(h=>so(t,h.name)).filter(h=>!et(h)&&d(h))),f=_m(a.props.map(h=>so(t,h.name)).filter(d)),u=[];for(let h of a.actions)if(h.speaker&&"name"in h.speaker){let w=so(t,h.speaker.name);et(w)?h.speaker={kind:"group",label:w}:(h.speaker.name=w,d(w)&&u.push(w))}for(let h of u)l.some(w=>jo(w)===jo(h))||l.push(h);let g=new Map;for(let h of t.lookChanges[a.scene_id]??[]){let w=so(t,h.entity),y=g.get(w)??[];y.includes(h.look)||y.push(h.look),g.set(w,y),o.set(w,h.look)}let m=h=>g.get(h)?.map(w=>({name:h,state:w}))??[xm(t,h,o)];a.location=p&&d(p)?xm(t,p,o):null,a.actors=l.flatMap(m),a.props=f.flatMap(m)}let i=Us(n),r=i.script;v5(r,t),R5(r);let s=Ks(r);return O5(s),M5(s),{doc:s,identityKeys:i.identityKeys}}var b5="\u5E38\u6001";function _m(e){let t=new Set;return e.filter(n=>{let o=jo(n);return!n||t.has(o)?!1:(t.add(o),!0)})}function xm(e,t,n){let o=Lt(e,t),i=n.get(t)??(o?Ud(o):void 0)??b5;return{name:t,state:i}}function O5(e){for(let t of["actors","locations","props"])for(let n of ht(e[t])?e[t]:[])if(gt(n))for(let o of ht(n.states)?n.states:[])gt(o)&&o.state_id==="default"&&o.state_name==="default"&&(o.state_name="\u5E38\u6001")}function v5(e,t){for(let[n,o]of[["actors","actor_name"],["locations","location_name"],["props","prop_name"]])for(let i of ht(e[n])?e[n]:[]){if(!gt(i))continue;let r=Lt(t,String(i[o])),s=ht(i.states)?i.states:[];if(r){r.description&&(i.description=r.description),r.aliases.length&&(i.aliases=[...new Set([...ht(i.aliases)?i.aliases:[],...r.aliases])]);let c=Ud(r),a=c?r.looks.find(d=>jo(d.name)===jo(c))?.description??"":"";for(let d of s){if(!gt(d))continue;if(d.state_id==="default"){a&&(d.description=a);continue}let p=r.looks.find(l=>jo(l.name)===jo(String(d.state_name)));p?.description&&(d.description=p.description)}}}}function R5(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 ht(e.episodes)?e.episodes:[])if(!(!gt(c)||!ht(c.scenes)))for(let a of c.scenes){if(!gt(a))continue;let p=[...ht(a.actors)?a.actors:[],...ht(a.props)?a.props:[],...gt(a.location)?[a.location]:[]].filter(gt).map(l=>l.actor_id??l.prop_id??l.location_id);for(let l of p)r(l);for(let l of ht(a.actions)?a.actions:[])gt(l)&&gt(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)>=E5;for(let[c,a]of[["actors","actor_id"],["props","prop_id"]])for(let d of ht(e[c])?e[c]:[])gt(d)&&(d.importance=s(String(d[a]))?"featured":"background");for(let c of ht(e.locations)?e.locations:[])gt(c)&&(c.importance="featured")}function M5(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 ht(e[n])?e[n]:[]){if(!gt(i))continue;let r=String(i[o]??""),s=ht(i.states)?i.states:[];if(!t(i.description))throw new x(`Ingested asset "${r}" is missing its identity description.`,{exitCode:b,errorCode:"ASSET_DESCRIPTION_MISSING",hint:"Rerun `scriptctl ingest --force` so the serial asset window can regenerate this entity."});for(let c of s){if(!gt(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:b,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 mn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Pn=e=>Array.isArray(e)?e:[],Fe=e=>typeof e=="string"?e.trim():"";function Yd(e){return e.normalize("NFKC").toLowerCase().replace(/[\p{White_Space}\p{P}\p{S}]+/gu,"")}var L5={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"}},bm=(e,t,n=8)=>{!t||e.includes(t)||e.length>=n||e.push(t)};function Om(e){let t=mn(e)?e:{},n={actor:[],location:[],prop:[]},o=new Map;for(let c of["actor","location","prop"]){let a=L5[c];for(let d of Pn(t[a.list])){if(!mn(d))continue;let p=Fe(d[a.id]),l=Fe(d[a.name]);if(!p)continue;let f=[...new Set(Pn(d.aliases).map(Fe).filter(Boolean))],u=new Map,g=[];for(let h of Pn(d.states)){if(!mn(h))continue;let w=Fe(h.state_id);if(!w)continue;let y=Fe(h.state_name),E={address:`${p}/${w}`,state_id:w,state_name:y,description:Fe(h.description),format_key:Yd(y),reference_count:0,episode_count:0,scene_count:0,references:[],frequency_flag:null,episodeIds:new Set,sceneIds:new Set};g.push(E),u.set(w,E)}let m={kind:c,id:p,name:l,aliases:f,description:Fe(d.description),importance:Fe(d.importance),format_key:Yd(l),alias_format_keys:f.map(Yd),reference_count:0,episode_count:0,scene_count:0,references:[],states:g,episodeIds:new Set,sceneIds:new Set,stateById:u};n[c].push(m),o.set(p,m)}}let i=c=>{let a=Pn(c.state_ids).map(Fe).filter(Boolean);if(a.length>0)return[...new Set(a)];let d=Fe(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}`),bm(u.references,f);let g=d.length>0?d:u.stateById.has("default")?["default"]:[];for(let m of g){let h=u.stateById.get(m);h&&(h.reference_count+=1,h.episodeIds.add(p),h.sceneIds.add(`${p}/${l}`),bm(h.references,f))}};for(let c of Pn(t.episodes)){if(!mn(c))continue;let a=Fe(c.episode_id)||"<episode>";for(let d of Pn(c.scenes)){if(!mn(d))continue;let p=Fe(d.scene_id)||"<scene>",l=`${a}/${p}`;mn(d.location)&&r("location",Fe(d.location.location_id),i(d.location),a,p,`${l}.location`);for(let f of Pn(d.actors))mn(f)&&r("actor",Fe(f.actor_id),i(f),a,p,`${l}.actors`);for(let f of Pn(d.props))mn(f)&&r("prop",Fe(f.prop_id),i(f),a,p,`${l}.props`);Pn(d.actions).forEach((f,u)=>{if(!mn(f)||!mn(f.speaker))return;let g=Fe(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:Fe(t.title),actors:n.actor.map(s),locations:n.location.map(s),props:n.prop.map(s)}}var D=qt,Rm=["id",D(38),D(13),D(90),D(40),D(34),D(6),D(82),D(35),D(62)];function Wd(){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+p5lIQ6zEU6Aky5B+f6Ag757Uz5yE65yw35l2t6k+b5O2U5zkm5Pon5l2C5BU66k6U44cc6AUy572U5l+H5BQM5lUn5y+Q5PIV5BU66k6U77YB5A2y5zYO5yAY56Qb5OIw5PEG5Rov56gU6k6K5PE2igfJDgLVBJ1YzxzPzxFJGifJB25MAwrLBMnLpwXVDYdMIjyGBwvKAxvT44cc","zhvWBgLJyxrLx3bYB3a","zNjLCxvLBMn5","z2vUzxjHDgvuB29S","ywXPyxnLCW","qsdOOyZOOAJNPlRKUidPOBNOTytKUQFJGilLJRVMJONLVidLPltNMOqGqsdLKi7VViZLKitLIjFKU47LT6BLIldLJ7pLM7RLRPRKUlRVVjO","zNjLCxvLBMn5x2zSywC","zxzPzgvUy2u","C3rHDgvZ","BgvUz3rO","CMvMzxjLBMnLx2nVDw50","6l6t5ywL5PIV5A6m5Pw06lwe5lQN55M76k6W55Qe57sN5yEr6kgm5BYp5B+R54wN77Ym5lIn5PIViePtt07JGilNRkZKUidOOyWGqvntrvrFqvvesvrFu05bufnit1rFvJeG5PIV5y2p6k6U54Mi5PYS77YBDgL0Bgv8powjP+wqJt4G5PIV5yMN5zcn77YBqv9dt0Xvtu5tl1nFq09mvu1ouYdMMk/LIjFLRPRKUyNVViZKUi3MMk/OTytKUQFMLBdMJA7VVjTBywn0B3jZoK5D44cbw2XVy2f0Aw9UCZPoxEoaGvTWCM9WCZPoxsdLIiBLIkVLVidLP4VKURRNIANJGihLNldNGRNJGihPGzpLHBFLIiBLJlRVViXoioAyR+IVPEwiHUwmUUI1Hos6P+AvSow5TUwgS+wUMUwfTUs4RsbbioIHJoEAHoI1Hos6P+EXU+wEI+oaGG","CMv2Awv3","5Qoa5P+L5zcm5lIa5lIQ54MP55cg5zYW54k55OIw5zcm5lIa5lU25yw35l2t6ygt5yw35PIV5zcM5zUG5zcn56EW44cb5yMn5zco57Ya44cb5B2s5BgE5O+p6l+W44cb566a56EW44cb566a57Mb5l2t44cb6l2S5B2v5BEU5BYc5OIw6kEc5A+F6kEs5BQM5lIn5zcm6icm6yEn5Asn55M76k6W44cc5yY65yIg5zcm5lIa5zYW54k555Qe5lIn5zcm5zcn56EW5lIo5zcm5lIa5BU6562r5lIT55Qe5lIn5zcm54US56Ul56M66zE077Ym5lMF5yY65yIg5zcm5lIa5lU25yw35l2t6ygt5yw35lIo5zcm57g75l2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5OQk5zcm5lIa5lIQ56IZ5A6A6kEg6kEj54Q25Ocb5OUg5OIq5AsA5lIQihn0yxrL44cc6yEn54k55ywZ5RoO5zcm5lMjl+I/KEs5IEEkTUAaGEoaGEwqJos4GowLL+ACJEIJHEIIQ+MhJEAwSowrVEwqJEoaGEs7HEwfIEE6V+AiLUwXGoMdQoE7HUIkGUMaOoAiKoEAHow3RUw8GU+8Jos7PEwpIUEkTUAaGEwqJEA3T+wfPEAdHEE7QUoaGEwkQos9NoAiLUwCUUAzR+IVToAyJUoaGG","BwvYz2u","zhvWBgLJyxrLx3n0yxrL","BMfTzxm","vw9trNG","6l+u5zUE5ywO5yMN6lwe5lQN5lIa6iE05OcN5A6H6k6H5y+r546W","Aw1WB3j0yw5Jzq","5lQm44cb6kEg6kEj54Q25Ocb5lIa6iE05OcN","5lIj44cb5l2o6Akr5lIo5BYc5BI454Q25Ocb","DhjPBq"];return Wd=function(){return e},Wd()}var Mm=[D(5),D(38),D(40),D(34),D(6),D(11),D(82),D(35),D(62)],N5=[D(41),D(20),D(14)+Rm[D(45)](D(68))+D(61),D(77)+Mm[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)](`
247
- `),U5=new Set([D(80),D(55),D(10),D(86),D(57),D(70),D(65)]),P5=new Set([D(85),D(78),D(21)]),C5=new Set([D(25),D(37),D(27)]);function Yt(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 qd(e){let t=D;return e[t(18)]>0?e[t(69)](Yt)[t(45)](";"):"-"}function T5(e){let t=D,n=[t(31),t(1)+Yt(e[t(42)]),t(46)+Rm[t(45)]("|"),t(39)+Mm[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",Yt(c.id),Yt(c[s(38)]),qd(c[s(13)]),Yt(c[s(90)]),String(c[s(19)]),String(c[s(3)]),String(c[s(64)]),Yt(c[s(82)]),Yt(c[s(35)]),qd(c[s(4)])][s(45)]("|"));for(let a of c[s(17)])n[s(71)](["S",Yt(a[s(5)]),Yt(a[s(49)]),String(a[s(19)]),String(a[s(3)]),String(a[s(64)]),a[s(15)]??"-",Yt(a[s(82)]),Yt(a[s(35)]),qd(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)](`
248
- `)}function qt(e,t){e=e-0;let n=Wd(),o=n[e];if(qt.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)};qt.uxwRFZ=i,qt.OXUPnC={},qt.qyTtRy=!0}let r=n[0];qt.TDHWfX!==r&&(qt.OXUPnC={},qt.TDHWfX=r);let s=qt.OXUPnC[e];return s===void 0?(o=qt.uxwRFZ(o),qt.OXUPnC[e]=o):o=s,o}var vm=e=>typeof e===D(48)&&e!==null&&!Array[D(33)](e),Lm=e=>Array[D(33)](e)?e:[],zo=e=>typeof e===D(63)?e[D(93)]():"",Zd=e=>[...new Set(Lm(e)[D(69)](zo)[D(30)](Boolean))];function V5(e,t){let n=D;if(!vm(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 Lm(e[n(73)])){if(!vm(s))continue;let c=zo(s[n(50)]),a=zo(s[n(28)]),d=zo(s[n(76)]);if(!U5[n(44)](c)||!P5[n(44)](a)||!C5[n(44)](d))continue;let p=Zd(s[n(0)])[n(30)](g=>o[n(44)](g)),l=Zd(s[n(29)])[n(30)](g=>i[n(44)](g));if(p[n(18)]===0&&l[n(18)]===0)continue;let f=zo(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:Zd(s[n(87)]),evidence:zo(s[n(16)]),recommendation:zo(s[n(24)]),suggested_survivor:u,action:a,confidence:d})}return r}async function Nm(e,t,n){let o=D,i=await e[o(12)](o(66),{system:N5,user:T5(t),tool:{name:o(26),description:o(89),inputSchema:dm},...n?{signal:n}:{}});return V5(i[o(72)],t)}var Um="1",$5=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.audit_version===Um&&n.script_hash===t&&n.summary!==null&&typeof n.summary=="object"&&Array.isArray(n.issues)};function D5(e,t){return{audit_version:Um,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 Xd(e,t,n){let o=$e(e),i=Om(e),r=await Nm(t,i,n);return D5(o,r)}async function G5(e){let t=$e(e.script);if(!e.force&&e.exists())try{let o=e.read();if($5(o,t))return e.executor.recordReuse("ingest.asset-audit"),{report:o,reused:!0}}catch{}let n=await Xd(e.script,e.executor,e.signal);return e.write(n),{report:n,reused:!1}}async function Pm(e,t,n,o={}){return G5({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 J5={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 ep(e){let t=[...e.asset_ids,...e.state_ids].join(", ")||"<unknown>",n=e.evidence||e.recommendation||"review the referenced assets";return`${J5[e.type]} [${t}]: ${n}`}function Cm(e){return e.issues.map(t=>({code:`asset_audit_${t.type}`,path:"$",message:`${ep(t)}; action=${t.action}; confidence=${t.confidence}`}))}var Mi=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 Tm(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 $m from"node:crypto";function np(){return{calls:0,succeeded:0,failed:0,reused:0,attempts:0,durationMs:0,inputTokens:0,outputTokens:0,cachedInputTokens:0,cacheCreationTokens:0,totalTokens:0}}function B5(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 Hs(e){let t=np();for(let n of e)B5(t,n);return t}var vr=e=>`${e.provider}\0${e.protocol}\0${e.model}`;function Dm(e){let t=new Map;for(let n of e){let o=vr(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:Hs(n.records)})).sort((n,o)=>vr(n).localeCompare(vr(o)))}function tp(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:Hs(o),byModel:Dm(o)})).sort((n,o)=>n.task.localeCompare(o.task))}function Vm(e){return Dm(e).map(t=>{let n=e.filter(o=>vr(o)===vr(t));return{...t,byTask:tp(n).map(({task:o,totals:i})=>({task:o,totals:i}))}})}function K5(e){let t=e.updatedAt,n=new Map;for(let r of e.episodes)n.set(r.episode,r.runs);let o=[...n.entries()].map(([r,s])=>{let c=new Set(s.flatMap(d=>d.recordIds)),a=e.records.filter(d=>c.has(d.id));return{episode:r,totals:Hs(a),byTask:tp(a),byModel:Vm(a),durationMs:s.reduce((d,p)=>d+p.durationMs,0),runs:s}}).sort((r,s)=>r.episode-s.episode),i=Hs(e.records);return{...e,updatedAt:t,totals:i,byTask:tp(e.records),byModel:Vm(e.records),episodes:o,timing:{totalDurationMs:e.runs.reduce((r,s)=>r+s.durationMs,0),modelDurationMs:i.durationMs,episodeDurationMs:o.reduce((r,s)=>r+s.durationMs,0)}}}function j5(e){return{version:2,createdAt:e,updatedAt:e,totals:np(),byTask:[],byModel:[],episodes:[],runs:[],records:[],timing:{totalDurationMs:0,modelDurationMs:0,episodeDurationMs:0}}}function Or(e){return new Date(e).toISOString()}var po=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=Or(this.startedAtMs);if(this.report=t.has("usage.json")?t.readJson("usage.json"):j5(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=$m.randomUUID();startedAtMs;cursor;report;flush(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:Or(o),endedAt:Or(n),durationMs:Math.max(0,n-o),stages:t.stages??{},recordIds:s.map(p=>p.id)}),a||this.report.episodes.push({episode:c,totals:np(),byTask:[],byModel:[],durationMs:0,runs:d})}this.write(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=Or(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=Or(t),this.report=K5(this.report),this.store.writeJson("usage.json",this.report)}};var ip="12",Qs=e=>String(e).padStart(3,"0"),Gm=e=>e.map(t=>JSON.stringify(t)).join(`
246
+ ${l}`:l,h=Date.now(),m=t.force?void 0:t.checkpoint?.readUpdate(d,p),g,w=!1;if(m!==void 0){let x=rg(m);try{if(x==null)throw new Pe("checkpoint top-level JSON is unparseable");g=Jr(x),w=!0,i++,t.executor.recordReuse("ingest.episode-assets")}catch(S){if(!(S instanceof Pe))throw S;let _=await sg(t.executor,d,p,u,f,t.signal);g=_.delta,t.checkpoint?.writeStep(d,p,l,_.raw)}}else{let x=await sg(t.executor,d,p,u,f,t.signal);g=x.delta,t.checkpoint?.writeStep(d,p,l,x.raw)}Dr(n,g,d,p);let y=dS(o.slice(d-1,p),n);if(y.length){let x=t.force?void 0:t.checkpoint?.readNameFix?.(d,p);if(x!==void 0){let S=rg(x);try{if(S==null)throw new Pe("name-fix checkpoint top-level JSON is unparseable");let _=Sp(S,y);ug(n,_),Dr(n,_,d,p),i++,t.executor.recordReuse("ingest.name-fix")}catch(_){if(!(_ instanceof Pe))throw _;let A=await ag(t.executor,d,p,ra(n,p),y,n,t.signal);t.checkpoint?.writeNameFix?.(d,p,A.raw),Dr(n,A.delta,d,p)}}else{let S=await ag(t.executor,d,p,ra(n,p),y,n,t.signal);t.checkpoint?.writeNameFix?.(d,p,S.raw),Dr(n,S.delta,d,p)}}Dm(n);for(let x=pp(n);x;x=pp(n)){let S=x[0].startEp,_=x[x.length-1].endEp,A=t.force?void 0:t.checkpoint?.readArc?.(S,_),b;if(A!==void 0)b=A,i++,t.executor.recordReuse("ingest.arc-summary");else{let U=x.map(O=>`${ap(O)}\uFF1A${O.line}`).join(`
247
+ `);b=await Qm(t.executor,`\u7B2C${S}\u96C6\u2013\u7B2C${_}\u96C6`,U,t.signal),t.checkpoint?.writeArc?.(S,_,b)}Gm(n,b)}t.onWindow?.({startEp:d,endEp:p,ms:Date.now()-h,cached:w,index:a,total:s.length,totalEpisodes:o.length})}return{...fS(e,n),episodes:o.length,reused:i}}function dS(e,t){let n=new Set,o=i=>{if(!i)return;let r=Eo(t,i);st(r)||Jt(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 pS={interior:"\u5185",exterior:"\u5916"},lS={day:"\u65E5",night:"\u591C"};function uS(e){let t=[`# ${e.episode_id}${e.title?` ${e.title}`:""}`];for(let n of e.scenes){t.push(`## ${n.scene_id}`);let o=[pS[n.environment?.space??""],lS[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(`
248
+ `)}function fS(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=>!!Jt(t,g),p=a.location?Eo(t,a.location.name):null,l=cg(a.actors.map(g=>Eo(t,g.name)).filter(g=>!st(g)&&d(g))),f=cg(a.props.map(g=>Eo(t,g.name)).filter(d)),u=[];for(let g of a.actions)if(g.speaker&&"name"in g.speaker){let w=Eo(t,g.speaker.name);st(w)?g.speaker={kind:"group",label:w}:(g.speaker.name=w,d(w)&&u.push(w))}for(let g of u)l.some(w=>ri(w)===ri(g))||l.push(g);let h=new Map;for(let g of t.lookChanges[a.scene_id]??[]){let w=Eo(t,g.entity),y=h.get(w)??[];y.includes(g.look)||y.push(g.look),h.set(w,y),o.set(w,g.look)}let m=g=>h.get(g)?.map(w=>({name:g,state:w}))??[dg(t,g,o)];a.location=p&&d(p)?dg(t,p,o):null,a.actors=l.flatMap(m),a.props=f.flatMap(m)}let i=ia(n),r=i.script;hS(r,t),yS(r);let s=pa(r);return gS(s),wS(s),{doc:s,identityKeys:i.identityKeys}}var mS="\u5E38\u6001";function cg(e){let t=new Set;return e.filter(n=>{let o=ri(n);return!n||t.has(o)?!1:(t.add(o),!0)})}function dg(e,t,n){let o=Jt(e,t),i=n.get(t)??(o?dp(o):void 0)??mS;return{name:t,state:i}}function gS(e){for(let t of["actors","locations","props"])for(let n of It(e[t])?e[t]:[])if(St(n))for(let o of It(n.states)?n.states:[])St(o)&&o.state_id==="default"&&o.state_name==="default"&&(o.state_name="\u5E38\u6001")}function hS(e,t){for(let[n,o]of[["actors","actor_name"],["locations","location_name"],["props","prop_name"]])for(let i of It(e[n])?e[n]:[]){if(!St(i))continue;let r=Jt(t,String(i[o])),s=It(i.states)?i.states:[];if(r){r.description&&(i.description=r.description),r.aliases.length&&(i.aliases=[...new Set([...It(i.aliases)?i.aliases:[],...r.aliases])]);let c=dp(r),a=c?r.looks.find(d=>ri(d.name)===ri(c))?.description??"":"";for(let d of s){if(!St(d))continue;if(d.state_id==="default"){a&&(d.description=a);continue}let p=r.looks.find(l=>ri(l.name)===ri(String(d.state_name)));p?.description&&(d.description=p.description)}}}}function yS(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 It(e.episodes)?e.episodes:[])if(!(!St(c)||!It(c.scenes)))for(let a of c.scenes){if(!St(a))continue;let p=[...It(a.actors)?a.actors:[],...It(a.props)?a.props:[],...St(a.location)?[a.location]:[]].filter(St).map(l=>l.actor_id??l.prop_id??l.location_id);for(let l of p)r(l);for(let l of It(a.actions)?a.actions:[])St(l)&&St(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)>=aS;for(let[c,a]of[["actors","actor_id"],["props","prop_id"]])for(let d of It(e[c])?e[c]:[])St(d)&&(d.importance=s(String(d[a]))?"featured":"background");for(let c of It(e.locations)?e.locations:[])St(c)&&(c.importance="featured")}function wS(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 It(e[n])?e[n]:[]){if(!St(i))continue;let r=String(i[o]??""),s=It(i.states)?i.states:[];if(!t(i.description))throw new E(`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(!St(c)||t(c.description))continue;let a=String(c.state_name??"");throw new E(`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 kn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>Array.isArray(e)?e:[],qe=e=>typeof e=="string"?e.trim():"";function Ip(e){return e.normalize("NFKC").toLowerCase().replace(/[\p{White_Space}\p{P}\p{S}]+/gu,"")}var xS={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"}},mg=(e,t,n=8)=>{!t||e.includes(t)||e.length>=n||e.push(t)};function gg(e){let t=kn(e)?e:{},n={actor:[],location:[],prop:[]},o=new Map;for(let c of["actor","location","prop"]){let a=xS[c];for(let d of Qn(t[a.list])){if(!kn(d))continue;let p=qe(d[a.id]),l=qe(d[a.name]);if(!p)continue;let f=[...new Set(Qn(d.aliases).map(qe).filter(Boolean))],u=new Map,h=[];for(let g of Qn(d.states)){if(!kn(g))continue;let w=qe(g.state_id);if(!w)continue;let y=qe(g.state_name),x={address:`${p}/${w}`,state_id:w,state_name:y,description:qe(g.description),format_key:Ip(y),reference_count:0,episode_count:0,scene_count:0,references:[],frequency_flag:null,episodeIds:new Set,sceneIds:new Set};h.push(x),u.set(w,x)}let m={kind:c,id:p,name:l,aliases:f,description:qe(d.description),importance:qe(d.importance),format_key:Ip(l),alias_format_keys:f.map(Ip),reference_count:0,episode_count:0,scene_count:0,references:[],states:h,episodeIds:new Set,sceneIds:new Set,stateById:u};n[c].push(m),o.set(p,m)}}let i=c=>{let a=Qn(c.state_ids).map(qe).filter(Boolean);if(a.length>0)return[...new Set(a)];let d=qe(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}`),mg(u.references,f);let h=d.length>0?d:u.stateById.has("default")?["default"]:[];for(let m of h){let g=u.stateById.get(m);g&&(g.reference_count+=1,g.episodeIds.add(p),g.sceneIds.add(`${p}/${l}`),mg(g.references,f))}};for(let c of Qn(t.episodes)){if(!kn(c))continue;let a=qe(c.episode_id)||"<episode>";for(let d of Qn(c.scenes)){if(!kn(d))continue;let p=qe(d.scene_id)||"<scene>",l=`${a}/${p}`;kn(d.location)&&r("location",qe(d.location.location_id),i(d.location),a,p,`${l}.location`);for(let f of Qn(d.actors))kn(f)&&r("actor",qe(f.actor_id),i(f),a,p,`${l}.actors`);for(let f of Qn(d.props))kn(f)&&r("prop",qe(f.prop_id),i(f),a,p,`${l}.props`);Qn(d.actions).forEach((f,u)=>{if(!kn(f)||!kn(f.speaker))return;let h=qe(f.speaker.actor_id);h&&r("actor",h,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:qe(t.title),actors:n.actor.map(s),locations:n.location.map(s),props:n.prop.map(s)}}var D=sn,yg=["id",D(38),D(13),D(90),D(40),D(34),D(6),D(82),D(35),D(62)];function bp(){let e=["yxnZzxrFAwrZ","D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zhvWBgLJyxrLx3n0yxrL","BMfTzxm","vw9trNG","6l+u5zUE5ywO5yMN6lwe5lQN5lIa6iE05OcN5A6H6k6H5y+r546W","Aw1WB3j0yw5Jzq","5lQm44cb6kEg6kEj54Q25Ocb5lIa6iE05OcN","5lIj44cb5l2o6Akr5lIo5BYc5BI454Q25Ocb","DhjPBq"];return bp=function(){return e},bp()}var wg=[D(5),D(38),D(40),D(34),D(6),D(11),D(82),D(35),D(62)],_S=[D(41),D(20),D(14)+yg[D(45)](D(68))+D(61),D(77)+wg[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)](`
249
+ `),ES=new Set([D(80),D(55),D(10),D(86),D(57),D(70),D(65)]),SS=new Set([D(85),D(78),D(21)]),IS=new Set([D(25),D(37),D(27)]);function rn(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 Ap(e){let t=D;return e[t(18)]>0?e[t(69)](rn)[t(45)](";"):"-"}function AS(e){let t=D,n=[t(31),t(1)+rn(e[t(42)]),t(46)+yg[t(45)]("|"),t(39)+wg[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",rn(c.id),rn(c[s(38)]),Ap(c[s(13)]),rn(c[s(90)]),String(c[s(19)]),String(c[s(3)]),String(c[s(64)]),rn(c[s(82)]),rn(c[s(35)]),Ap(c[s(4)])][s(45)]("|"));for(let a of c[s(17)])n[s(71)](["S",rn(a[s(5)]),rn(a[s(49)]),String(a[s(19)]),String(a[s(3)]),String(a[s(64)]),a[s(15)]??"-",rn(a[s(82)]),rn(a[s(35)]),Ap(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)](`
250
+ `)}function sn(e,t){e=e-0;let n=bp(),o=n[e];if(sn.qyTtRy===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=c.charAt(h++);~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.uxwRFZ=i,sn.OXUPnC={},sn.qyTtRy=!0}let r=n[0];sn.TDHWfX!==r&&(sn.OXUPnC={},sn.TDHWfX=r);let s=sn.OXUPnC[e];return s===void 0?(o=sn.uxwRFZ(o),sn.OXUPnC[e]=o):o=s,o}var hg=e=>typeof e===D(48)&&e!==null&&!Array[D(33)](e),xg=e=>Array[D(33)](e)?e:[],si=e=>typeof e===D(63)?e[D(93)]():"",kp=e=>[...new Set(xg(e)[D(69)](si)[D(30)](Boolean))];function kS(e,t){let n=D;if(!hg(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 xg(e[n(73)])){if(!hg(s))continue;let c=si(s[n(50)]),a=si(s[n(28)]),d=si(s[n(76)]);if(!ES[n(44)](c)||!SS[n(44)](a)||!IS[n(44)](d))continue;let p=kp(s[n(0)])[n(30)](h=>o[n(44)](h)),l=kp(s[n(29)])[n(30)](h=>i[n(44)](h));if(p[n(18)]===0&&l[n(18)]===0)continue;let f=si(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:kp(s[n(87)]),evidence:si(s[n(16)]),recommendation:si(s[n(24)]),suggested_survivor:u,action:a,confidence:d})}return r}async function _g(e,t,n){let o=D,i=await e[o(12)](o(66),{system:_S,user:AS(t),tool:{name:o(26),description:o(89),inputSchema:Zm},...n?{signal:n}:{}});return kS(i[o(72)],t)}var Eg="1",bS=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.audit_version===Eg&&n.script_hash===t&&n.summary!==null&&typeof n.summary=="object"&&Array.isArray(n.issues)};function OS(e,t){return{audit_version:Eg,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 Op(e,t,n){let o=De(e),i=gg(e),r=await _g(t,i,n);return OS(o,r)}async function vS(e){let t=De(e.script);if(!e.force&&e.exists())try{let o=e.read();if(bS(o,t))return e.executor.recordReuse("ingest.asset-audit"),{report:o,reused:!0}}catch{}let n=await Op(e.script,e.executor,e.signal);return e.write(n),{report:n,reused:!1}}async function Sg(e,t,n,o={}){return vS({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 RS={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 vp(e){let t=[...e.asset_ids,...e.state_ids].join(", ")||"<unknown>",n=e.evidence||e.recommendation||"review the referenced assets";return`${RS[e.type]} [${t}]: ${n}`}function Ig(e){return e.issues.map(t=>({code:`asset_audit_${t.type}`,path:"$",message:`${vp(t)}; action=${t.action}; confidence=${t.confidence}`}))}var ji=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 Ag(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 bg from"node:crypto";function Mp(){return{calls:0,succeeded:0,failed:0,reused:0,attempts:0,durationMs:0,inputTokens:0,outputTokens:0,cachedInputTokens:0,cacheCreationTokens:0,totalTokens:0}}function MS(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 fa(e){let t=Mp();for(let n of e)MS(t,n);return t}var Kr=e=>`${e.provider}\0${e.protocol}\0${e.model}`;function Og(e){let t=new Map;for(let n of e){let o=Kr(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:fa(n.records)})).sort((n,o)=>Kr(n).localeCompare(Kr(o)))}function Rp(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:fa(o),byModel:Og(o)})).sort((n,o)=>n.task.localeCompare(o.task))}function kg(e){return Og(e).map(t=>{let n=e.filter(o=>Kr(o)===Kr(t));return{...t,byTask:Rp(n).map(({task:o,totals:i})=>({task:o,totals:i}))}})}function LS(e){let t=e.updatedAt,n=new Map;for(let r of e.episodes)n.set(r.episode,r.runs);let o=[...n.entries()].map(([r,s])=>{let c=new Set(s.flatMap(d=>d.recordIds)),a=e.records.filter(d=>c.has(d.id));return{episode:r,totals:fa(a),byTask:Rp(a),byModel:kg(a),durationMs:s.reduce((d,p)=>d+p.durationMs,0),runs:s}}).sort((r,s)=>r.episode-s.episode),i=fa(e.records);return{...e,updatedAt:t,totals:i,byTask:Rp(e.records),byModel:kg(e.records),episodes:o,timing:{totalDurationMs:e.runs.reduce((r,s)=>r+s.durationMs,0),modelDurationMs:i.durationMs,episodeDurationMs:o.reduce((r,s)=>r+s.durationMs,0)}}}function NS(e){return{version:2,createdAt:e,updatedAt:e,totals:Mp(),byTask:[],byModel:[],episodes:[],runs:[],records:[],timing:{totalDurationMs:0,modelDurationMs:0,episodeDurationMs:0}}}function Br(e){return new Date(e).toISOString()}var Io=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=Br(this.startedAtMs);if(this.report=t.has("usage.json")?t.readJson("usage.json"):NS(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=bg.randomUUID();startedAtMs;cursor;report;flush(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:Br(o),endedAt:Br(n),durationMs:Math.max(0,n-o),stages:t.stages??{},recordIds:s.map(p=>p.id)}),a||this.report.episodes.push({episode:c,totals:Mp(),byTask:[],byModel:[],durationMs:0,runs:d})}this.write(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=Br(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=Br(t),this.report=LS(this.report),this.store.writeJson("usage.json",this.report)}};var Np="12",ma=e=>String(e).padStart(3,"0"),vg=e=>e.map(t=>JSON.stringify(t)).join(`
249
251
  `)+`
250
- `;function z5(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:b,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!==ip)throw new x("This workspace was created by an older text-ingest pipeline.",{exitCode:b,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 ${ip}`]}})}if(n){for(let o of["pass1","pass2","pass3","pass5","serial"])op.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"])op.rmSync(e.path(o),{force:!0})}}async function Jm(e){let t=un(e.sourcePath);if(t.kind!=="text")throw new x("runTextIngest received a non-text source.",{exitCode:b,errorCode:"INGEST_WRONG_PIPELINE"});let n=await Wf(t.path,t.ext),o=Ie(n),i=new st(e.workspacePath);i.ensure(),z5(i,o,e.force??!1);let r=new Mi(a=>i.writeJson("timings.json",a)),s=new po(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 N=await nm(e.executor,n,e.signal);d=N.line,i.writeJson("pass1/body_start.json",N)}let p=n.split(`
252
+ `;function US(e,t,n){if(e.has("manifest.json")){let o=e.readJson("manifest.json");if(o.source?.sha256&&o.source.sha256!==t)throw new E("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!==Np)throw new E("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 ${Np}`]}})}if(n){for(let o of["pass1","pass2","pass3","pass5","serial"])Lp.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"])Lp.rmSync(e.path(o),{force:!0})}}async function Rg(e){let t=Sn(e.sourcePath);if(t.kind!=="text")throw new E("runTextIngest received a non-text source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=await ea(t.path,t.ext),o=he(n),i=new lt(e.workspacePath);i.ensure(),US(i,o,e.force??!1);let r=new ji(a=>i.writeJson("timings.json",a)),s=new Io(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 N=await jm(e.executor,n,e.signal);d=N.line,i.writeJson("pass1/body_start.json",N)}let p=n.split(`
251
253
  `),l=d>0?p.slice(d).join(`
252
254
  `):n,f=d>0?p.slice(0,d).join(`
253
- `).trim().slice(0,6e3):"",u=Nf(l);i.writeText("pass1/source.txt",n),i.writeJson("pass1/chunks.json",u.map(N=>({index:N.index,core_line_start:N.core_line_start,core_line_end:N.core_line_end}))),i.writeJson("manifest.json",{version:1,pipeline_version:ip,updated:new Date().toISOString(),source:{path:Li.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 m=await om(u,e.concurrency??30,async N=>{let ie=`pass2/chunk_${Qs(N.index)}.json`,ye=`pass2/chunk_${Qs(N.index)}.error.json`;if(i.has(ie)&&!e.force){let tt=Dd(i.readJson(ie),N);return i.clearError(ye),g++,e.executor.recordReuse("ingest.text-normalize"),tt}let{raw:dt,records:en}=await Xf(e.executor,N,e.signal);return i.writeText(ie,dt),i.writeText(`pass2/chunk_${Qs(N.index)}.jsonl`,Gm(en)),i.clearError(ye),en}),h=m.filter(N=>!N.ok);for(let N of h){let ie=N.error instanceof Error?N.error.message:String(N.error);i.writeJson(`pass2/chunk_${Qs(N.index)}.error.json`,{chunk:N.index,error:ie})}if(s.flush({scope:{kind:"phase",phase:"normalize"},status:h.length?"failed":"succeeded"}),h.length>0)throw new x(`${h.length}/${u.length} chunk(s) failed normalization.`,{exitCode:b,errorCode:"INGEST_NORMALIZE_INCOMPLETE",hint:"Inspect pass2/chunk_NNN.error.json and rerun `scriptctl ingest` to resume.",data:{actual:h.map(N=>`chunk ${N.index}`)}});r.phaseEnd("normalize");let w,y,E;if(!e.force&&i.has("body.json"))w=i.readJson("body.json"),y=i.has("pass3/script.jsonl")?Ir(i.readText("pass3/script.jsonl")).length:0,E=i.has("notes.json")?i.readJson("notes.json").length:0,g++;else{let N=[];for(let en of m)en.ok&&N.push(...en.value);i.writeText("pass3/script.jsonl",Gm(N));let ie=Ir(i.readText("pass3/script.jsonl")),ye=H5(t.path),dt=Lf(ie,{title:ye});i.writeJson("notes.json",dt.notes),w=dt.script,i.writeJson("body.json",w),y=N.length,E=dt.notes.length}let I=N=>String(N).padStart(3,"0"),_=(N,ie)=>`serial/win_${I(N)}_${I(ie)}.json`,A={readUpdate:(N,ie)=>i.has(_(N,ie))?i.readText(_(N,ie)):void 0,writeStep:(N,ie,ye,dt)=>{i.writeText(`serial/context_${I(N)}.md`,ye),i.writeText(_(N,ie),dt)},readArc:(N,ie)=>{let ye=`serial/arc_${I(N)}_${I(ie)}.md`;return i.has(ye)?i.readText(ye):void 0},writeArc:(N,ie,ye)=>{i.writeText(`serial/arc_${I(N)}_${I(ie)}.md`,ye)},readNameFix:(N,ie)=>{let ye=`serial/fix_${I(N)}_${I(ie)}.json`;return i.has(ye)?i.readText(ye):void 0},writeNameFix:(N,ie,ye)=>i.writeText(`serial/fix_${I(N)}_${I(ie)}.json`,ye)};r.phaseStart("serial");let k=await km(w,{executor:e.executor,checkpoint:A,force:e.force??!1,...f?{sourceRef:f}:{},onWindow:N=>{N.index===0&&r.serialStart(N.total,N.totalEpisodes),r.windowDone(N.startEp,N.endEp,N.ms,N.cached);let ie=N.startEp===N.endEp?{kind:"episode",episode:N.startEp}:{kind:"episode-range",startEpisode:N.startEp,endEpisode:N.endEp},ye=Date.now();s.flush({scope:ie,status:N.cached?"reused":"succeeded",startedAtMs:ye-N.ms,endedAtMs:ye})},...e.signal?{signal:e.signal}:{}}),P=k.doc;g+=k.reused,r.phaseEnd("serial"),r.phaseStart("govern");let{script:O,idMap:S}=Ts(P);i.writeJson("id_map.json",S);let L=lt(O);if(!L.ok)throw i.writeJson("validation.json",L),new x("Intermediate script failed validation before v4 identity assignment.",{exitCode:b,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:L.errors.slice(0,5).map(N=>`${N.path}: ${N.message}`)}});let T=!e.force&&i.has("v4_identity_map.json")?i.readJson("v4_identity_map.json"):void 0,U=Oi(bt(P),T,k.identityKeys),R=U.script,j=Me(R),Z=[],Oe=Date.now(),K="failed";try{if(j.ok){let N=await Pm(i,R,e.executor,{force:e.force??!1,...e.signal?{signal:e.signal}:{}});Z=Cm(N.report)}K="succeeded"}finally{s.flush({scope:{kind:"phase",phase:"asset-audit"},status:K,startedAtMs:Oe})}let ve={...j,warnings:[...j.warnings,...bi(R),...Z]};if(i.writeJson("pass5/script.json",R),i.writeJson("v4_identity_map.json",U.identityMap),i.writeJson("validation.json",ve),!ve.ok)throw new x("Final script.json failed v4 validation.",{exitCode:b,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:ve.errors.slice(0,5).map(N=>`${N.path}: ${N.message}`)}});i.writeJson("script.json",R),r.phaseEnd("govern"),r.finish();let Ze=R;return c="succeeded",{workspacePath:i.root,chunks:u.length,reused:g,records:y,notes:E,assets:{actors:Ze.actors?.length??0,locations:Ze.locations?.length??0,props:Ze.props?.length??0},scriptPath:i.path("script.json"),validation:{ok:ve.ok,errors:ve.errors.length,warnings:ve.warnings.length}}}finally{s.finish(c)}}function H5(e){return Li.basename(e,Li.extname(e))}import*as mo from"node:fs";import*as Fo from"node:path";import{createHash as SS}from"node:crypto";var Q5=()=>({apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:[],voice:""});function lo(){return{lastEpisode:0,registry:[],digests:[],openThreads:[]}}var he=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),Rr=(e,t)=>e.length>t?`${e.slice(0,t)}\u2026`:e;function F5(e,t){let n=he(t);return e.find(o=>he(o.name)===n||he(o.identitySeed)===n||o.aliases.some(i=>he(i)===n))}var Y5=3,q5=12e3;function Ho(e,t){let n=(t??"").trim();n&&!e.includes(n)&&e.push(n)}var Z5=["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","voice"];function Fs(e,t,n){if(!t)return e;let o=e?{...e,persistent_marks:[...e.persistent_marks]}:Q5();for(let i of Z5){let r=t[i]?.trim()??"";r&&(n||!o[i])&&(o[i]=r)}for(let i of t.persistent_marks??[])Ho(o.persistent_marks,i);return o}function rp(e,t,n){let o=t.name.trim();if(!o)return;let i=t.description.trim(),r=e.find(s=>fn(s.name)===fn(o));if(!r){e.push({name:o,description:i});return}i&&(n||!r.description)&&(r.description=i)}function Bm(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??[])Ho(e.recognitionAnchors,s);e.identityProfile=Fs(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??[])Ho(e.aliases,s);for(let s of t.add_states??[])rp(e.states,s,o);e.lastEpisode=n}function Ys(e,t,n){let o=r=>F5(e.registry,r);for(let r of t.registry_delta.new_entities){let s=r.name.trim();if(!s||r.kind==="actor"&&et(s))continue;let c=o(s);if(c){Bm(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??[])rp(a,p,!1);let d=[];for(let p of r.aliases??[])Ho(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:Fs(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&&Bm(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||he(c)===he(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])Ho(d.recognitionAnchors,g);let u=Fs(void 0,s.identityProfile,!0);d.identityProfile=Fs(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])rp(d.states,g,!1);d.aliases=[...f].filter(g=>he(g)!==he(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}Ho(s.aliases,s.name),Ho(s.aliases,r.from_name),s.name=c,s.status="canonical",s.aliases=s.aliases.filter(d=>he(d)!==he(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 zm(e,t){return e.digests.push({episode:t,synopsis:"",outcome:"skipped"}),e.lastEpisode=t,e}function W5(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: ${Rr(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=Rr(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 Km(e,t){let n=Rr(e.appearance||e.role||"",t?30:60),o=e.states.map(i=>i.description?`${i.name}\uFF08${Rr(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 jm(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(...W5(a,n),"")}if(r.length||s.length){o.push("## \u573A\u666F / \u9053\u5177","");for(let a of r)o.push(Km(a,n));for(let a of s)o.push(Km(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?Rr(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(`
254
- `)}function qs(e){for(let t=Y5;t>=1;t--){let n=jm(e,t,!1);if(n.length<=q5)return n}return jm(e,1,!0)}function uo(e){let t=new Map;for(let n of e)for(let o of[n.identitySeed,...n.aliases])he(o)!==he(n.name)&&t.set(o,n.name);return t}function X5(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 Hm(e,t){let n=new Map,o=new Map,i=(s,c)=>{let a=he(s),d=c.trim();!d||he(d)===a||(o.has(a)||o.set(a,new Set),o.get(a).add(d))};for(let s of t){n.set(he(s.name),s.importance);for(let c of s.aliases)n.set(he(c),s.importance);n.set(he(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(m=>he(m.name)===he(g)||he(m.identitySeed)===he(g)||m.aliases.some(h=>he(h)===he(g))),l)break;a.importance=l?.importance??n.get(he(d))??"featured";let f=o.get(he(d));if(f?.size&&(a.aliases=[...new Set([...a.aliases??[],...f])]),!l)continue;let u=l.kind==="actor"?X5(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 m=l.states.find(h=>fn(h.name)===fn(g.state_name));m?.description?g.description=m.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 Qm(e,t,n){let o=uo(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)}:et(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(m=>m.states.length?m.states.map(h=>({name:i(m.name),state:h})):[{name:i(m.name)}]),g=p.actions.map((m,h)=>{let w={kind:"comic",document_id:d.document_id,pages:m.pages,regions:m.regions},y={identity_key:`${f}:action:${h+1}`,type:m.type,content:m.content,extend:{scriptctl:{source:w}}};if((m.type==="dialogue"||m.type==="inner_thought")&&(y.speaker=r(m.speaker),m.parenthetical&&(y.parenthetical=m.parenthetical),"name"in y.speaker)){let E=y.speaker.name;u.some(I=>I.name===E)||u.push({name:E})}return y});return{identity_key:f,scene_id:`scn_${String(++s).padStart(3,"0")}`,environment:{...p.space?{space:p.space}:{},...p.time?{time:io(p.time)}:{}},location:p.location?{name:i(p.location)}:null,actors:u,props:[...new Set(p.props.map(i))].map(m=>({name:m})),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 x(`Comic scene references assets absent from the registry: ${f.join(", ")}`,{exitCode:b,errorCode:"INGEST_VALIDATION_FAILED",hint:"The episode must register every referenced character, location and key prop.",data:{actual:f}})}return c}var Ni=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();function eS(e,t,n){let o=uo(t),i=l=>o.get(l)??l,r=new Map;for(let l of t){let f=i(l.name),g=t.find(h=>h.kind===l.kind&&Ni(h.name)===Ni(f))??l,m=`${l.kind}:${Ni(f)}`;r.has(m)||r.set(m,`${n}:${g.kind}:${g.firstEpisode}:${Ni(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}:${Ni(f)}`)??`${n}:${l.kind}:source:${Ni(f)}`;p[l.kind][l.provisional_id]=u,d[l.provisional_id]=Object.fromEntries(l.states.map(g=>[g.id,`${u}:state:${fn(g.name)}`]))}return{actor:s,location:c,prop:a,state:d}}function Zs(e,t,n,o){let{script:i,assets:r,identityKeys:s}=Us(e);Hm(i,t.registry);let c=Ks(i),{script:a,idMap:d}=Ts(c),p=lt(a);if(!p.ok)return{initial:i,final:a,idMap:d,validation:p,identityMap:o,scriptV4:null};let l=Oi(bt(c),o,{...eS(r,t.registry,n),...s}),f=l.script,u=Me(f);return{initial:i,final:f,scriptV4:f,idMap:d,identityMap:l.identityMap,validation:{...u,warnings:[...u.warnings,...bi(f)]}}}import*as Fm from"node:fs";import*as Cn from"node:path";import{createHash as tS}from"node:crypto";import{PDFDocument as nS}from"pdf-lib";import*as Ws from"node:path";function Xs(e){let t=Ws.basename(e,Ws.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 oS(e){let t=e.kind==="comic-file"?[e.path]:e.files,n=t.map(i=>({path:i,sourceNumber:Xs(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:b,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=>Cn.basename(i))}});return n.sort((i,r)=>i.sourceNumber!==null&&r.sourceNumber!==null?i.sourceNumber-r.sourceNumber:Cn.basename(i.path).localeCompare(Cn.basename(r.path),"zh-Hans",{numeric:!0}))}async function Ym(e){let t=[];for(let[n,o]of oS(e).entries()){let i=Fm.readFileSync(o.path),s=(await nS.load(i,{updateMetadata:!1})).getPageCount();if(!s||s>1e3||i.length>5e7)throw new x("PDF is outside the document provider limits.",{exitCode:b,errorCode:"INGEST_COMIC_SIZE",hint:"Provide one chapter per PDF, containing 1\u20131000 pages and at most 50 MB.",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:Cn.basename(o.path,Cn.extname(o.path)),path:Cn.resolve(o.path),sha256:tS("sha256").update(i).digest("hex"),page_count:s,size_bytes:i.length})}return t}function qm(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:b,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 iS,StandardFonts as rS,rgb as sS,pushGraphicsState as aS,popGraphicsState as cS,concatTransformationMatrix as ea}from"pdf-lib";async function Zm(e){let t=await iS.load(e),n=await t.embedFont(rS.Helvetica),o=sS(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(aS()),s){case 90:i.pushOperators(ea(0,1,-1,0,r.x+r.width,r.y));break;case 180:i.pushOperators(ea(-1,0,0,-1,r.x+r.width,r.y+r.height));break;case 270:i.pushOperators(ea(0,-1,1,0,r.x,r.y+r.height));break;default:i.pushOperators(ea(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 m of[1,a-n.widthOfTextAtSize(u,p)-1])i.drawText(u,{x:m,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(cS())}return t.save()}import*as Wm from"node:fs";import*as Xm from"node:path";import dS from"proper-lockfile";async function fo(e,t){let n=Xm.resolve(e);Wm.mkdirSync(n,{recursive:!0});let o=null;try{o=await dS.lock(n,{realpath:!1,stale:12e4,update:1e4,retries:0})}catch(i){throw new x("The ingest workspace is busy.",{exitCode:me,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{z as gS}from"zod";import{z as G}from"zod";var Ye=G.string().min(1),Qo=G.array(Ye),eg=G.object({name:Ye,description:Ye}),sp=G.string().length(0),tg=G.object({apparent_gender:G.string(),apparent_age:G.string(),face_shape:G.string(),brows_eyes:G.string(),nose:G.string(),mouth:G.string(),skin_features:G.string(),hair:G.string(),build:G.string(),persistent_marks:Qo,voice:sp.describe("\u6F2B\u753B\u6CA1\u6709\u539F\u58F0\u97F3\u8F68\uFF0C\u586B\u7A7A\u4E32")}),pS=G.object({name:Ye,kind:G.enum(["actor","location","prop"]),status:G.enum(["canonical","provisional"]),importance:G.enum(["featured","background"]),recognition_anchors:Qo,identity_profile:tg,appearance:G.string(),role:G.string(),states:G.array(eg),aliases:Qo}),lS=G.object({new_entities:G.array(pS),enrich:G.array(G.object({name:Ye,add_recognition_anchors:Qo,identity_profile_patch:tg,appearance:G.string(),role:G.string(),add_aliases:Qo,add_states:G.array(eg)})),canonicalize:G.array(G.object({from_name:Ye,canonical_name:Ye,evidence:Ye.describe("\u672C\u8BDD PDF \u9875\u7801\u548C\u76F4\u63A5\u51FA\u73B0\u7684\u59D3\u540D\u539F\u6587")}))}),ap=G.array(G.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"),ta=G.number().min(0).max(1e3),uS=G.object({page:G.number().int().min(1),kind:G.enum(["panel","bubble","text"]),box:G.object({top:ta,left:ta,bottom:ta,right:ta}).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")}),cp=G.array(uS).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 ng(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 og="\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",ig="\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",rg=G.object({type:G.enum(["dialogue","inner_thought"]),content:Ye,pages:ap,regions:cp,speaker:Ye.describe(og),parenthetical:G.string()}),fS=G.discriminatedUnion("type",[G.object({type:G.enum(["action","transition"]),content:Ye,pages:ap,regions:cp}),rg]),sg=G.object({space:G.union([G.enum(["interior","exterior"]),sp]),time:G.union([G.enum(["day","night","dawn","dusk"]),sp]),location:G.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:G.array(G.object({name:Ye,states:Qo})),props:Qo,actions:G.array(fS).min(1).describe(ig)}),dp=G.object({registry_delta:lS,synopsis:Ye,scenes:G.array(sg).min(1),open_threads:G.object({opened:G.array(G.object({text:Ye})),closed:G.array(G.object({ref:Ye}))}),ignored_pages:G.array(G.object({page:G.number().int().min(1),reason:Ye.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")}))}),ag=dp.extend({scenes:G.array(sg.extend({actions:G.array(rg.extend({type:G.enum(["action","transition","dialogue","inner_thought"]),speaker:G.string().describe(`${og}\uFF1Baction/transition \u586B\u7A7A\u4E32`)})).min(1).describe(ig)})).min(1)}),mS=G.object({kind:G.literal("comic"),document_id:Ye,pages:ap,regions:cp.optional()}),na=G.object({scriptctl:G.object({source:mS})});var lp=Zt;function pp(){let e=["q29TAwmGzxbPC29KzsbMywLSzwqGDhjHBNnJCMLWDcb2ywXPzgf0Aw9UoIa","CMvNAw9UCW","Dg9ku09ou2nOzw1H","44cc5PYSifberIdLHBeG","zgf0yq","ioMHTE+8JoIVT+wUJoAvToMyHEIVU+w5TUAmIEMHUUw6J+MaKoAGVoI9RowgMEwfQoMdQowjP+AdHEoaGGOk","BwvZC2fNzq","5l2G5PIV5RYR55s76l2S5yMN5PYS55Qe5lIY6kgm6kEJ5P6q5zMO44cc6l6t5ywL5PIV5A6m5Pw05lIa6k+DifberIdLKOZLIy3PNAlLKitOR53NTk/NP6/NMOtLT7lNN6xORR7LRPRJGilOVPpLH7RKUidKUkRNRkBLKiGGC2nOzw1HioEAHcbku09oiowVUEIXOE+8JowqJoAxTUwmHEwqQ+ACRoIVNEMaKoAGVowjP+ACRooaGEI1Hos6P+wINUMhJ+wsJowjP+AdHEE6V+E0OUoaGGOk6l6t5yE65A2x5Q6177YA5Q+p5P2HigfJDgLVBNmG55Qeihr5CguG5y+Q6io95PIVigfJDgLVBU+8IoEuU+MDOU+8IEoaGxrYyw5ZAxrPB27VViJOVAZLNlRVViNJGifKAwfSB2D1zE+8IowVUEEzVs/LRQlOP4lML4hNMB3VViNJGifPBM5LCL90Ag91z2H077Yi5lQ654MP5B+d5AoW77Yj77YB5Q2J5PAh57UF5lIa5yAz5ywLignVBNrLBNtJGilMR4/MNAhPG73LJixLKkSGCgfNzxmG5PwW5A2x5PwW57Ue44cbCMvNAw9UCYdLR7NOSAhMLBdNU4tJGifZC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k6K5y+W6k+n5zkm55s76z2I5PAh5A2x6yo95BEY5yE6546W77Ym5yAf5A656Ag65BQp5Q2J56gU77YB5lUf5Pw06Ag156M655M944cb5Bcb6z2I44cb5yI25l2C5l+H5OgV5y+V5lUL5yIx5ywLigLNBM9YzwrFCgfNzxmG5BM25yAz5y6F5zUG44cc5lIn6kAb5zYOigfJDgLVBNmG5lIoigLNBM9YzwrFCgfNzxmG5zcm5PE255M76k6W5zcm5lIa6Ag144ccC3LUB3bZAxmG5y+Q5QAc5OUS5PYS6k+D77Ym5lIn6io95lUJ5PU/5Q2J5PAh44cc","ugfNzxmGywjZzw50igzYB20GDhjHBNnJCMLWDdOG","BwfW","C2fMzvbHCNnL","Cgf0Aa","C2nLBMvZ","AgfZ","AM9PBG","BgvUz3rO","CgfNzxm","AxnZDwvZ","CgfYC2u","B3bLBMfWAs0ZlJa","su5hrvnux0nptuLdx1nfuKLbtf9gquLmruq","Dgv4Da","C29Tzq","C2XPy2u","CgfNzq","sw52ywXPzcbVCIb1BM9YzgvYzwqGC291CMnLihbHz2vZoIa","zNjVBq","zxjYB3i","sw52ywXPzcbVCIbKDxbSAwnHDguGAwDUB3jLzcbWywDLoIa","ywn0Aw9UCW","5B2t5yMn6k+D77YA","C3vJy2vZCW","zMLSDgvY","ihbHz2vZlG","oYbKB2n1BwvUDcbOyxmG","z2vUzxjHDgu","sw5ZCgvJDcbLCc8QlNjLC3bVBNnLlMPZB24Gyw5KihjLCNvUigLUz2vZDcb3AxrOihrOzsbZyw1LihnVDxjJzsbHBMqGD29YA3nWywnLlG","AwDUB3jLzf9WywDLCW","ywrK"];return pp=function(){return e},pp()}function Zt(e,t){e=e-0;let n=pp(),o=n[e];if(Zt.RPngbJ===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)};Zt.xePDtj=i,Zt.gnQDUQ={},Zt.RPngbJ=!0}let r=n[0];Zt.rPrOht!==r&&(Zt.gnQDUQ={},Zt.rPrOht=r);let s=Zt.gnQDUQ[e];return s===void 0?(o=Zt.xePDtj(o),Zt.gnQDUQ[e]=o):o=s,o}var hS=lp(7);function yS(e,t){let n=lp,o=dp[n(10)](JSON[n(18)](e)),i=a=>{let d=n;throw new x(d(0)+a[d(14)]("; "),{exitCode:b,errorCode:d(20),hint:d(36),data:{actual:a}})};if(!o[n(31)])return i(o[n(27)][n(17)][n(23)](0,8)[n(9)](a=>a[n(11)][n(14)](".")+": "+a[n(6)]));let r=o[n(4)],s=new Set;for(let a of r[n(12)])for(let d of a[n(29)]){if(d[n(16)][n(22)]((l,f)=>l>t||f>0&&l<=d[n(16)][f-1]))return i([n(25)+d[n(16)][n(14)](", ")+n(34)+t+n(33)]);let p=ng(d[n(16)],d[n(1)]);if(p[n(15)])return i(p);for(let l of d[n(16)])s[n(38)](l)}for(let a of r[n(37)]){if(a[n(24)]>t||s[n(13)](a[n(24)]))return i([n(28)+a[n(24)]]);s[n(38)](a[n(24)])}let c=Array[n(26)]({length:t},(a,d)=>d+1)[n(32)](a=>!s[n(13)](a));return c[n(15)]?i([n(8)+c[n(14)](", ")]):r}async function cg(e,t,n,o,i,r,s){let c=lp,a=await e[c(35)]({media:t,system:hS,user:c(30)+n+c(3)+o+c(5)+i,responseJsonSchema:gS[c(2)](ag,{target:c(19)}),signal:s});return r(a[c(21)]),yS(a[c(21)],o)}function oa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wS(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 ES(e){if(e instanceof C)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:St(wS(e),{retryable:t,message:e.message}),attempts:[]}}return{failure:St({failure_type:"unknown",failure_code:"unknown"},{retryable:!1,message:e instanceof Error?e.message:String(e)}),attempts:[]}}function ia(e,t,n){let o=ES(e);return{schema_version:1,unit:{kind:"episode",episode:t},phase:n,occurred_at:new Date().toISOString(),...o}}function pg(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 dg(e,t){return typeof e=="string"&&t.some(n=>n===e)}function Ui(e){return typeof e=="string"?e:void 0}function _S(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!oa(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 xS(e){let t=e.provider_source,n=e.provider_reason;return{provider:Ui(e.provider),model:Ui(e.model),operation:Ui(e.operation),http_status:typeof e.http_status=="number"?e.http_status:void 0,system_code:Ui(e.system_code),provider_source:dg(t,["prompt","candidate"])?t:void 0,provider_reason:dg(n,["SAFETY","PROHIBITED_CONTENT","BLOCKLIST","SPII","RECITATION","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION","OTHER","UNSPECIFIED","UNKNOWN"])?n:void 0,provider_reason_raw:Ui(e.provider_reason_raw),finish_message:Ui(e.finish_message),safety_ratings:_S(e.safety_ratings),details:Array.isArray(e.details)&&e.details.every(i=>typeof i=="string")?e.details:void 0}}function Mr(e){if(!oa(e))return null;let t=dl(e.failure_type,e.failure_code);return!t||typeof e.retryable!="boolean"||typeof e.message!="string"?null:St(t,{...xS(e),retryable:e.retryable,message:e.message})}function Lr(e){if(!oa(e)||e.schema_version!==1)return null;let t=e.unit;if(!oa(t)||t.kind!=="episode"||typeof t.episode!="number"||typeof e.phase!="string"||typeof e.occurred_at!="string")return null;let n=Mr(e.failure);if(!n||!Array.isArray(e.attempts))return null;let o=[];for(let i of e.attempts){let r=Mr(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 lg="comic-1",ra=e=>String(e).padStart(3,"0"),ug=["script.initial.json","id_map.json","validation.json","context.json","v4_identity_map.json","script.json"];function up(e,t,n){let o=Zs(Qm(e,t.context,n),t.context,"comic",t.identityMap);if(!o.scriptV4||!o.validation.ok)throw new x("Comic script failed validation.",{exitCode:b,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 fp(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 IS(e){let t=un(e.sourcePath);if(t.kind!=="comic-file"&&t.kind!=="comic-directory")throw new x("Expected PDF comic source.",{exitCode:b,errorCode:"INGEST_WRONG_PIPELINE"});let n=new st(Fo.resolve(e.workspacePath));n.ensure();let o=n.has("manifest.json")?n.readJson("manifest.json"):null;if(o&&o.pipeline_version!==lg)throw new x("This workspace belongs to another ingest pipeline.",{exitCode:b,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:b,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Choose a fresh workspace."});let i=await Ym(t);o&&qm(o.episodes,i);let r={version:1,pipeline_version:lg,updated:new Date().toISOString(),source:{kind:t.kind,path:Fo.resolve(t.path),sha256:SS("sha256").update(i.map(h=>h.sha256).join(`
255
- `)).digest("hex")},episodes:i,...o?.current_error?{current_error:o.current_error}:{}};if(e.force){for(let h of o?.episodes??[])for(let w of["json","response.json","context.md","error.json","input.pdf"])mo.rmSync(n.path(`ep/ep_${ra(h.episode)}.${w}`),{force:!0});for(let h of["checkpoint.json","timings.json",...ug])mo.rmSync(n.path(h),{force:!0});delete r.current_error}n.writeJson("manifest.json",r);let s=n.has("checkpoint.json")?n.readJson("checkpoint.json"):{context:lo(),identityMap:ao()},c=i.slice(0,s.context.lastEpisode).map(h=>n.readJson(`ep/ep_${ra(h.episode)}.json`)),a=mo.realpathSync(t.path),d=Fo.basename(a,t.kind==="comic-file"?Fo.extname(a):""),p=new po(n,e.executor),l=new Mi(h=>n.writeJson("timings.json",h));l.phaseStart("serial"),l.serialStart(i.length,i.length);let f="failed",u=0,g=c.length,m;try{if(c.length>0){fp(n,up(c,s,d),s.context);for(let y of c)n.clearError(`ep/ep_${ra(y.episode)}.error.json`);r.current_error&&r.current_error.unit.episode<=s.context.lastEpisode&&(delete r.current_error,r.updated=new Date().toISOString(),n.writeJson("manifest.json",r))}else for(let y of ug)mo.rmSync(n.path(y),{force:!0});for(let y of i){if(e.signal?.throwIfAborted(),y.episode<=s.context.lastEpisode){e.executor.recordReuse("ingest.comic-serial");let P=Date.now();p.flush({scope:{kind:"episode",episode:y.episode},status:"reused",startedAtMs:P,endedAtMs:P}),l.windowDone(y.episode,y.episode,0,!0);continue}if(e.step&&u>=1)break;let E=Date.now(),I=`ep/ep_${ra(y.episode)}`,_=r.current_error?.unit.episode===y.episode?r.current_error.failure.message:void 0,A=qs(s.context)+(_?`
256
-
257
- \u672C\u8BDD\u4E0A\u4E00\u6B21\u8F93\u51FA\u5C1A\u672A\u88AB\u63A5\u53D7\uFF0C\u5931\u8D25\u539F\u56E0\uFF1A${_}\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(`${I}.context.md`,A),process.stderr.write(`\u6F2B\u753B ${y.episode}/${i.length} \xB7 ${y.title} \xB7 ${y.page_count} \u9875
258
- `);let k="upload";try{m??=e.executor.documentPort("ingest.comic-serial");let P=n.path(`${I}.input.pdf`);Js(P,Buffer.from(await Zm(mo.readFileSync(y.path))));let O=await m.prepare(P,e.signal),S;try{k="generate";let Oe=await cg(m,O,y.title,y.page_count,A,K=>n.writeText(`${I}.response.json`,K),e.signal);S={episode:y.episode,document_id:y.document_id,title:y.title,output:Oe}}finally{await m.release(O,e.signal)}k="validation";let L=Ys(structuredClone(s.context),S.output,y.episode),T=[...c,S],U=up(T,{context:L,identityMap:s.identityMap},d),R={context:L,identityMap:U.identityMap};k="checkpoint",n.writeJson(`${I}.json`,S),n.writeJson("checkpoint.json",R),s=R,c.push(S),k="publish",fp(n,U,s.context),n.clearError(`${I}.error.json`),delete r.current_error,r.updated=new Date().toISOString(),n.writeJson("manifest.json",r),u++;let j=Date.now();l.windowDone(y.episode,y.episode,j-E,!1),p.flush({scope:{kind:"episode",episode:y.episode},status:"succeeded",startedAtMs:E,endedAtMs:j});let Z=S.output.scenes.reduce((Oe,K)=>Oe+K.actions.length,0);process.stderr.write(` \u5DF2\u4FDD\u5B58\uFF1A${S.output.scenes.length} \u573A / ${Z} \u6761\u6B63\u6587
259
- `)}catch(P){let O=ia(P,y.episode,k);throw n.writeJson(`${I}.error.json`,O),n.writeJson("manifest.json",{...r,updated:O.occurred_at,current_error:O}),p.flush({scope:{kind:"episode",episode:y.episode},status:"failed",startedAtMs:E,endedAtMs:Date.now()}),P}}let h=up(c,s,d);fp(n,h,s.context);let w=c.length===i.length;return f="succeeded",{workspace:n.root,script_path:n.path("script.json"),kind:"comic",episodes:i.length,processed:u,reused:g,completed:c.length,remaining:i.length-c.length,complete:w,next_episode:w?null:c.length+1,assets:{actors:h.scriptV4.actors.length,locations:h.scriptV4.locations.length,props:h.scriptV4.props.length}}}finally{l.phaseEnd("serial"),l.finish(),p.finish(f)}}async function fg(e){return fo(e.workspacePath,()=>IS(e))}import*as Xt from"node:fs";import*as Vi from"node:path";function AS(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 mg(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=AS(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 sa(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 Pi(e){let t=typeof e=="string"?e.trim().replace(/\.\d+$/,""):"",n=t.match(/^(?:(\d+):)?(\d+):(\d{2})$/);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")}`}function Ci(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 gg=e=>String(e).padStart(3,"0"),kS={\u5185:"interior",\u5916:"exterior"},bS={act:"action",dlg:"dialogue",think:"inner_thought"},mp={broadcast:"broadcast",system:"system",group:"group",offscreen:"offscreen",prop:"offscreen",location:"offscreen"};function OS(e){let t=e.match(/^(\w+):(.+)$/);if(t&&mp[t[1]]){let n=t[2].trim();return n?{kind:mp[t[1]],label:n}:{kind:mp[t[1]]}}return et(e)?{kind:"group",label:e.trim()}:{name:e}}function hg(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_${gg(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=kS[(a.environment.space??"").trim()],g=io(a.environment.time);u&&(f.space=u),g&&(f.time=g);let m=[],h=A=>{m.some(k=>k.name===A)||m.push({name:A})};for(let A of a.characters)A.name&&!et(A.name)&&(A.states.length===0?m.push({name:A.name}):m.push(...A.states.map(k=>({name:A.name,state:k}))));let w=new Map,y=a.anchors.map(A=>{let k=Pi(A.ts),P=k?`time:${k}`:`content:${JSON.stringify([A.kind,A.speaker??"",A.content])}`,O=(w.get(P)??0)+1;w.set(P,O);let S={identity_key:`${l}:action:${P}:${O}`,type:bS[A.kind]??"action",content:A.content};if((A.kind==="dlg"||A.kind==="think")&&A.speaker){let T=OS(A.speaker);S.speaker=T,"name"in T&&h(T.name)}A.parenthetical&&(S.parenthetical=A.parenthetical);let L=Pi(A.ts);return L&&(S.extend={timestamp:L}),S}),E=(a.location??"").trim(),I=[],_=new Set;for(let A of a.props??[]){if(!A)continue;let k=A.normalize("NFC").replace(/\s+/g," ").trim();!k||_.has(k)||(_.add(k),I.push({name:A}))}return{identity_key:l,scene_id:`scn_${gg(++n)}`,...f.space||f.time?{environment:f}:{},location:E?{name:E}:null,actors:m,props:I,actions:y}})}});return{title:t,episodes:o}}var vS=60,RS=6,MS=[-1e3,0,1e3],_g=/(?:身穿|穿着|服装|造型|衣|裙|袍|衫|夹克|制服|西装|盔甲|装甲|防弹服|套装|裤|靴)/u,gp=/(?:全身|半身|上半身|四分之三身|躯干|胸前|腰部)/u,hp=/(?:站(?:在|立)|坐(?:在|下|起)|跪(?:在|下|倒)?|蹲(?:在|下)?|走(?:在|出|向)|行走|迈步|奔跑|跳起|跃起|转身|抬头|转头)/u,yg=/(?:特写|近景|脸|面容|五官|正脸|侧脸|侧前脸|双眼|眼眶|眉头|嘴角)/u,xg=/(?:背对|背影|远处|极远|模糊|运动模糊|脸被遮|面部遮挡|只露出|纯道具|空镜)/u,Sg=/(?:双脚|脚部|膝盖|伤口|手部特写)/u,Ig=/(?:画外音|旁白|未入镜|镜外|电话音|广播|\bO\.?S\.?\b)/iu;function go(e){return e.normalize("NFC").replace(/\s+/g," ").trim()}function Ag(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 kg(e){let t=e.trim().match(/^(\d+):(\d{2})$/);return t?Number(t[1])*1e3+Number(t[2])*10:null}function bg(e,t="clock"){return t==="legacy_centiseconds"?kg(e):Ag(e)}function yp(e,t){return e===null?!1:t===void 0||e<=t}function LS(e,t){if(t===void 0)return"clock";let n=e.scenes.flatMap(r=>r.actions.map(Og)).filter(Boolean),o=n.filter(r=>yp(Ag(r),t)).length;return n.filter(r=>yp(kg(r),t)).length>o?"legacy_centiseconds":"clock"}function wg(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 Og(e){let t=e.extend?.timestamp;return typeof t=="string"?t.trim():""}function NS(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 vg(e,t){let n=t.map(o=>e.indexOf(o)).filter(o=>o>=0);return n.length>0?Math.min(...n):-1}function Rg(e,t,n){return t.filter(o=>vg(e,n.get(o.actor_id)??[])>=0).length}function US({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=vg(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&&!Ig.test(a),g=n===1&&(c&&a.length>0||u&&a.length>0&&(hp.test(a)||yg.test(a)));if(!l&&!u&&!g)return null;let m=p||u?"target_anchor":"scene_fallback",h=u?250:p?65:l?50:45,w=u?250:p?65:l?50:45;n===1&&(h+=20,w+=20);let y=go(s);return y&&y!=="default"&&y!=="\u9ED8\u8BA4"&&a.includes(y)&&(h+=35),_g.test(a)&&(h+=30),gp.test(a)?(h+=25,w+=15):hp.test(a)&&(h+=15,w+=5),yg.test(a)&&(w+=30,gp.test(a)||(h-=20)),xg.test(a)&&(h-=70,w-=70),Sg.test(a)&&(h-=40),Rg(a,o,r)>=2&&(h-=15,w-=15),{stateScore:h,identityScore:w,selection:m}}function PS(e,t,n){let o=e.type==="action"||e.type==="transition",i="parenthetical"in e?go(e.parenthetical??""):"";if(!o&&Ig.test(i))return null;let r=go(o?e.content:i),s=o?0:-40;return s-=Rg(r,t,n)*20,_g.test(r)&&(s+=10),gp.test(r)?s+=10:hp.test(r)&&(s+=5),xg.test(r)&&(s-=20),Sg.test(r)&&(s-=10),{stateScore:s,identityScore:Number.NEGATIVE_INFINITY,selection:"scene_fallback"}}function Nr(e,t,n){let o=(n.get(`${e.episode}:${e.milliseconds}`)?.size??0)>1;return e[t]-(o?35:0)}function Mg(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||Nr(a,t,n)>Nr(p,t,n))&&r.set(d,a)}let s=[...r.values()].sort((a,d)=>Nr(d,t,n)-Nr(a,t,n)||a.episode-d.episode||a.milliseconds-d.milliseconds).filter(a=>i===null||Nr(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 CS(e,t,n){return Mg(e,t,n,1,null)[0]??null}function Eg(e){return e.replace(/[^0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function aa(e,t,n,o,i){let r=new Map(o.map(h=>[h.episode,h])),s=uo(n.registry),c=new Map(t.actors.map(h=>[h.actor_id,h])),a=new Map(t.actors.map(h=>[h.actor_id,NS(h,s)])),d=new Map,p=new Map,l=new Map,f=new Map;for(let h=0;h<t.episodes.length;h+=1){let w=t.episodes[h],y=h+1,E=r.get(y);if(!E)continue;let I=LS(w,E.duration_ms);for(let _=0;_<w.scenes.length;_+=1){let A=w.scenes[_],k=A.actors.map(P=>c.get(P.actor_id)).filter(P=>!!P);for(let P of A.actors){d.set(P.actor_id,(d.get(P.actor_id)??0)+1);let O=c.get(P.actor_id);if(!O)continue;let S=a.get(O.actor_id)??[O.actor_name],L=[],T=P.state_ids.length===1?P.state_ids[0]:null,U=T?O.states.find(R=>R.state_id===T):null;for(let R of A.actions){let j=Og(R),Z=bg(j,I);if(!yp(Z,E.duration_ms))continue;let Oe=US({action:R,actor:O,actorCount:k.length,allActors:k,surfaces:S,surfacesByActor:a,stateName:U?.state_name??"default"}),K=Oe??(U?PS(R,k,a):null);if(!K)continue;let ve={actorId:O.actor_id,episode:y,episodeId:w.episode_id,sceneId:A.scene_id,timestamp:wg(Z),milliseconds:Z,durationMs:E.duration_ms,stateScore:K.stateScore,identityScore:K.identityScore,selection:K.selection,sourcePath:E.path,sourceSha256:E.sha256};if(L.push(ve),Oe){let Ze=`${y}:${Z}`,N=f.get(Ze)??new Set;N.add(O.actor_id),f.set(Ze,N)}}if(L.length>0){let R=p.get(O.actor_id)??[];if(R.push(...L),p.set(O.actor_id,R),U){let j=`${O.actor_id}:${U.state_id}`,Z=l.get(j)??[];Z.push(...L),l.set(j,Z)}}}}}let u=(h,w)=>{let y=c.get(h),E=c.get(w),I=y?.importance==="background"?1:0,_=E?.importance==="background"?1:0;return I-_||(d.get(w)??0)-(d.get(h)??0)||(y?.actor_name??h).localeCompare(E?.actor_name??w,"zh-CN")},g=[...l.entries()].flatMap(([h,w])=>{let[y,E]=h.split(":"),I=y?c.get(y):void 0,_=I?.states.find(O=>O.state_id===E),A=CS(w,"stateScore",f);if(!I||!_||!A)return[];let k=`state:${I.actor_id}:${_.state_id}`,P=MS.map(O=>{let S=A.durationMs===void 0?Number.POSITIVE_INFINITY:Math.max(0,A.durationMs-50),L=Math.min(S,Math.max(0,A.milliseconds+O)),T=wg(L);return{evidence_id:`${k}:${A.episode}:${T}`,episode:A.episode,episode_id:A.episodeId,scene_id:A.sceneId,timestamp:T,offset_ms:O,selection:A.selection,source_sha256:A.sourceSha256,source_path:A.sourcePath,frame_path:`evidence/frames/${I.actor_id}/${_.state_id}/ep_${String(A.episode).padStart(3,"0")}_${Eg(T)}.jpg`,frame_status:"pending"}}).filter((O,S,L)=>L.findIndex(T=>T.timestamp===O.timestamp)===S);return[{evidence_id:k,asset_kind:"actor",actor_id:I.actor_id,actor_name:I.actor_name,state_id:_.state_id,state_name:_.state_name,samples:P}]}).sort((h,w)=>u(h.actor_id,w.actor_id)||h.state_name.localeCompare(w.state_name,"zh-CN")),m=[...p.entries()].flatMap(([h,w])=>{let y=c.get(h),E=Mg(w,"identityScore",f,RS,vS);if(!y||E.length===0)return[];let I=`identity:${y.actor_id}`;return[{evidence_id:I,asset_kind:"actor",actor_id:y.actor_id,actor_name:y.actor_name,samples:E.map(_=>({evidence_id:`${I}:${_.episode}:${_.timestamp}`,episode:_.episode,episode_id:_.episodeId,scene_id:_.sceneId,timestamp:_.timestamp,offset_ms:0,selection:_.selection,source_sha256:_.sourceSha256,source_path:_.sourcePath,frame_path:`evidence/frames/${y.actor_id}/identity/ep_${String(_.episode).padStart(3,"0")}_${Eg(_.timestamp)}.jpg`,frame_status:"pending"}))}]}).sort((h,w)=>u(h.actor_id,w.actor_id));return{version:2,source_sha256:i,items:g,identities:m}}function Lg(e){return bg(e)}function Ng(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 ca from"node:path";function Pg(e){return ca.extname(e).toLowerCase()}function TS(e){return vd[Pg(e)]??"application/octet-stream"}function Ug(e,t){return new x(e,{exitCode:b,errorCode:"INGEST_VIDEO_DISCOVERY",hint:"Name every episode file with a number, or none of them, and rerun `scriptctl ingest`.",data:{actual:t}})}function wp(e,t){return{episode:t,path:e,ext:Pg(e),mime:TS(e)}}function da(e){if(e.kind!=="video-file"&&e.kind!=="video-directory")throw new x("Expected video source.",{exitCode:b,errorCode:"INGEST_WRONG_PIPELINE"});if(e.kind==="video-file")return[wp(e.path,1)];let t=e.files,n=t.map(Xs),o=n.filter(r=>r!==null);if(o.length===0)return t.map((r,s)=>wp(r,s+1));if(o.length!==t.length){let r=t.filter((s,c)=>n[c]===null).map(s=>ca.basename(s));throw Ug("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 Ug("Two episode files resolve to the same number.",[`duplicate episode: ${r}`]);i.add(r)}return t.map((r,s)=>wp(r,n[s])).sort((r,s)=>r.episode-s.episode)}import*as Cg from"node:fs";import*as Tg from"node:path";function Vg(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=Tg.resolve(r.path),c=Cg.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:Va(s);return{episode:r.episode,path:s,ext:r.ext,mime:r.mime,sha256:u,size_bytes:a,mtime_ms:d}})}function pa(e){return Ie(JSON.stringify(e.map(t=>({episode:t.episode,ext:t.ext,mime:t.mime,sha256:t.sha256}))))}import{spawn as VS}from"node:child_process";import*as at from"node:fs";import*as $g from"node:path";var $S=20*1024*1024,DS="scale='if(gt(a,1),min(1280,iw),-2)':'if(gt(a,1),-2,min(1280,ih))'";function GS(e,t){return["-y","-loglevel","error","-i",e,"-vf",DS,"-c:v","libx264","-preset","medium","-crf","27","-pix_fmt","yuv420p","-c:a","aac","-b:a","96k","-movflags","+faststart","-f","mp4",t]}function JS(e,t,n){return new Promise((o,i)=>{if(n?.aborted){i(new Error("aborted"));return}let r=VS("ffmpeg",GS(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 Dg(e,t,n,o){if(at.existsSync(t)&&(at.statSync(t).size??0)>0)return{path:t,mime:"video/mp4",transcoded:!0};let i=0;try{i=at.statSync(e).size}catch{}if(i>0&&i<=$S)return{path:e,mime:n,transcoded:!1,note:`already ${(i/1024/1024).toFixed(1)}MB (\u226420MB)`};let r=`${t}.part`;try{if(at.mkdirSync($g.dirname(t),{recursive:!0}),at.rmSync(r,{force:!0}),await JS(e,r,o),!at.existsSync(r)||at.statSync(r).size===0)throw new Error("ffmpeg produced no output");return at.renameSync(r,t),{path:t,mime:"video/mp4",transcoded:!0}}catch(s){try{at.rmSync(r,{force:!0}),at.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 BS}from"node:child_process";import*as Je from"node:fs";import*as Gg from"node:path";var KS="scale='if(gt(a,1),min(960,iw),-2)':'if(gt(a,1),-2,min(960,ih))'",jS=4;function zS(e){let t=Lg(e);return t===null?null:(t/1e3).toFixed(3)}var HS=async(e,t,n,o)=>{if(o?.aborted)throw new Error("aborted");let i=zS(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(Gg.dirname(n),{recursive:!0});let r=`${n}.part`;return Je.rmSync(r,{force:!0}),new Promise((s,c)=>{let a=BS("ffmpeg",["-y","-loglevel","error","-ss",i,"-i",e,"-frames:v","1","-vf",KS,"-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 QS(e){let{source_path:t,...n}=e;return n}async function la(e,t,n,o=HS,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 m=s[g],h=e.path(m.frame_path),w;r&&Je.existsSync(h)&&Je.statSync(h).size>0?w={ok:!0}:(Je.rmSync(h,{force:!0}),w=await o(m.source_path,m.timestamp,h,n)),c.set(m,QS({...m,frame_status:w.ok?"ready":"unavailable",...w.error?{error:w.error}:{}}))}};await Promise.all(Array.from({length:Math.min(jS,s.length)},()=>d()));let p=g=>g.map(m=>c.get(m)),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"),m=h=>JSON.stringify({version:h.version,source_sha256:h.source_sha256,items:h.items,identities:h.identities??[]});if(m(g)===m(u))return g}catch{}return e.writeJson("evidence/state-evidence.json",u),u}var le=Wt,FS=le(60);function YS(e,t){let n=le,o=t[n(106)]()?n(86)+t+`
260
- `:n(110);return n(47)+e+n(36)+o}function Ep(e,t){let n=le;return new x(e,{exitCode:me,errorCode:n(119),hint:n(113),data:{actual:t}})}var _p=e=>{let t=le;return typeof e===t(32)?e[t(33)](/\u0000/g,""):Array[t(70)](e)?e[t(65)](_p):ct(e)?Object[t(101)](Object[t(18)](e)[t(65)](([n,o])=>[n,_p(o)])):e},ct=e=>typeof e===le(46)&&e!==null&&!Array[le(70)](e);function xp(){let e=["C2v0","CM9Szq","Aw5JBhvKzxm","ywrKx3jLy29NBML0Aw9Ux2fUy2HVCNm","C3rYAw5NAwz5","Bg9JyxrPB24","ywLzwxG","CMvJB2DUAxrPB25Fyw5JAg9YCW","zw5YAwnO","AwrLBNrPDhLFChjVzMLSzq","z2vUzxjHDgu","BMv3x2vUDgL0AwvZ","yw5JAg9YCW","igfUy2HVCNmGC3rPBgWGAgf2zsbUBYb0Aw1LC3rHBxaGywz0zxiGmYbYzxrYAwvZlG","B3bLBMvK","DgHPBMS","CMvNAxn0CNLFzgvSDge","zgvZy3jPChrPB24","zw50CMLLCW","y2fUB25Py2fSAxPL","tefztLm","z2v0","y2HHCMfJDgvYCW","BgvUz3rO","DgLTzxn0yw1Wx21PC3nPBMC","y2fUB25Py2fS","DgLTzq","ywrK","B3bLBL90AhjLywrZ","CgfYC2u","BwLTzq","zMLSDgvY","C3rYAw5N","CMvWBgfJzq","AwrLBNrPDhLFChjVzMLSzv9WyxrJAa","DMfSDwvZ","ioMBHU+8MUwVUEEfP+ACRoMBHUwoN+INHUMIKE+8JoAmIEACRos7U+wkOEwUMUs5IEEAHcbku09oioE7K+AEHoI/LowBNUs4Gos4QIbku09oiowVUEIXOEoaGUwpQUI/LowBNIbku09oioACRoI6Q++8Jos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BRLUO/MI4BMIjdLPjRKUkRNN60GC2nLBMxVViZMR4/LNlRNU5hLRPROH6RLT7hNMOqGBg9JyxrPB27JGifJAgfYywn0zxjZ44cbChjVChmG5zkmihn0yxrL77Ym5BM255sOihnOB3rZioAyJUEHRUIsMEwKQUwLH+w8GowNI+oaGEwiH+AnOUwsJoE7K+ADN+oaGG","C29Tzq","ywn0B3i","BM9YBwfSAxPL","Cgf0Aa","BwfW","zMXHDe1HCa","whbvAKe","sw5ZCgvJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbPBMDLC3qGDg8GCMvZDw1LlG","ywXPyxnLCW","AxnbCNjHEq","rvHms2W","oIbZzxjPywWGB3v0Chv0ihbYB2r1y2vKig5VihnJzw5LCW","ywrKx2fSAwfZzxm","Aw1WB3j0yw5Jzq","cGRKUiRMRkhOVPpLH7RMNiKG","ChjVChm","DuH1qwG","ywn0","tKzd","C29YDa","zMfJzv9ZAgfWzq","AgfZ","BM9Zzq","y29UDgvUDa","BMfTzq","pt09pt09pt09psdLT7lNN6xORR7LRPRVViJLIldKUiRKUidPM4BKUlRMRAlVViZOP4tOJipLKi3KU6xMRAtKUlRLH4BVViKGpt09pt09pt09pqO","C2TPBL9Mzwf0DxjLCW","uLPSD0u","zxzPzgvUy2u","xsaO","DMLZDwfS","yNvPBgq","C2HVDhm","zxbPC29Kzsa","CgvYC2LZDgvUDf9TyxjRCW","44cc6k+36yEn5PAW6kEc55Yl5B2t5yMn6zUg77Ym5lI65Q+p5lIa5P2HihnOB3rZiowsJcb2B2LJzxmG5AgR5yAz55YF5A6E6lw354k5ihrZ77Yitu06u1pVViNVViZKUi3LVPFNVlRLPlhJGihNLzNNQBRMIjBLOASGBNvSBo+8M+I/LowBNUwUJoAvTcbku09o77Ym5lIn6kAb5y+Q6l+u5zUE5l+U6kgL5A2x5Q6144cc","ChjVDMLZAw9UywW","oIbZzxjPywWGB3v0Chv0ihrVBYbZAg9YDcaOzMLUAxnOuMvHC29Upq","ywrKx3n0yxrLCW","rxbPC29Kzsa","zNjVBuvUDhjPzxm","C3LUB3bZAxm","ue9tsvrjvKvFsu5gsu5jvfK","weLmzNa","rMHHqK0","DhjPBq","AgfPCG","zMvHDhvYzwq","y2XVC2vK","77Yi6l+z5PIV56YS5lIa6zUg77Ym5PQc5PEG5BEY55+L6k6+5A6A44cc77YjcG","y2fTzxjH","yNjVD3nFzxLLCW","sw5ZCgvJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbGC2nYAxb0y3rSigLUz2vZDgaGDg8GCMvZDw1LlG","ChvZAa","A2v5CW","CMvM","CgfYzw50Agv0AwnHBa","BgvUz3rOoIa","su5hrvnux1zjrevpx1nfuKLbtf9gquLmruq","AxngAw5PDgu","DM9Py2vZ","oIbZzxjPywWGB3v0Chv0ihDHCYbUB3qGDMfSAwqGsLnptIaOzMLUAxnOuMvHC29Upq","Dgv4Da","zNjVBv9Uyw1L","C3rHDgvZ","Dg9ju09tDhjPBMC","C2nLBMvZ","Bw91DgG","su5hrvnux1zjrevpx1rjtuvtvefnuf9nsvntsu5h","C2nLBMvZwW"];return xp=function(){return e},xp()}var X=e=>typeof e===le(32)?e[le(106)]():"",qe=e=>Array[le(70)](e)?e:[],jg=e=>{let t=le,n=X(e);return n?n[t(59)](/[((//,,、]/)[0][t(106)]():""},qS=e=>[...new Set(qe(e)[le(65)](jg)[le(31)](Boolean))],Jg=e=>{let t=le,n=[];for(let o of qe(e))if(t(20)===t(20)){if(!ct(o))continue;let i=jg(o[t(85)]);if(!i)continue;let r=X(o[t(17)]),s=n[t(58)](c=>c[t(85)]===i);s?!s[t(17)]&&r&&(s[t(17)]=r):n[t(114)]({name:i,description:r})}else throw _0xea1873(t(94)+_0x26d9eb+t(122)+_0x40ae4d[t(40)]+")",[_0x54b3bb[t(42)](0,200)]);return n},ZS=[le(37),le(56),le(81),le(112),le(83),le(128),le(87),le(107),le(92),le(52)],Bg=e=>{let t=le;if(!ct(e))return;let n={apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:qe(e[t(95)])[t(65)](X)[t(31)](Boolean),voice:""};for(let o of ZS)n[o]=X(e[o]);return n},Kg=e=>{let t=le;if(!e)return Number[t(103)];let n=e[t(59)](":")[t(65)](Number);return n[t(61)](o=>!Number[t(120)](o))?Number[t(103)]:n[t(23)]===2?n[0]*60+n[1]:n[t(23)]===3?n[0]*3600+n[1]*60+n[2]:Number[t(103)]},WS=(e,t)=>{let n=le;return e?t?e[n(33)](/[。!?;]+$/,"")+"\u3002"+t:e:t};function Wt(e,t){e=e-0;let n=xp(),o=n[e];if(Wt.yxMOYo===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)};Wt.DlFVxD=i,Wt.iMIPil={},Wt.yxMOYo=!0}let r=n[0];Wt.ISLRJj!==r&&(Wt.iMIPil={},Wt.ISLRJj=r);let s=Wt.iMIPil[e];return s===void 0?(o=Wt.DlFVxD(o),Wt.iMIPil[e]=o):o=s,o}function XS(e){let t=le,n={synopsis:"",scenes:[],registry_delta:{new_entities:[],enrich:[],canonicalize:[]},open_threads:{opened:[],closed:[]}};if(!ct(e))return n;n[t(102)]=X(e[t(102)]);for(let r of qe(e[t(127)])){if(!ct(r))continue;let s={},c=X(r[t(41)]);c&&(s[t(41)]=c);let a=io(r[t(26)]);a&&(s[t(26)]=a);let d=new Map;for(let h of qe(r[t(22)])){if(t(67)!==t(67))throw new _0x25b22d(t(100)+_0x39f21e+": "+_0x1bf283[t(23)]+t(13),{exitCode:_0x26902a,errorCode:t(129),hint:t(68),data:{actual:_0x36fc5d}});{if(!ct(h))continue;let w=X(h[t(85)]);if(!w||et(w))continue;let y=d[t(21)](w)??{name:w,states:[]};for(let E of qS(h[t(125)]))if(t(71)===t(71))y[t(125)][t(2)](E)||y[t(125)][t(114)](E);else{if(!_0x279b30)return _0x499743[t(103)];let I=_0x3e9bd8[t(59)](":")[t(65)](_0xbf8c);return I[t(61)](_=>!_0x2242ca[t(120)](_))?_0x4255ff[t(103)]:I[t(23)]===2?I[0]*60+I[1]:I[t(23)]===3?I[0]*3600+I[1]*60+I[2]:_0x3f6179[t(103)]}d[t(0)](w,y)}}let p=[],l=new Set;for(let h of qe(r[t(76)])[t(65)](X)[t(31)](Boolean)){let w=h[t(63)](t(79))[t(33)](/\s+/g," ")[t(106)]();!w||l[t(82)](w)||(l[t(27)](w),p[t(114)](h[t(106)]()))}let f=[];for(let h of qe(r[t(93)])){if(!ct(h))continue;let w=WS(X(h[t(111)]),X(h[t(91)]));if(!w)continue;let y={kind:t(78),content:w},E=Pi(h.ts);E&&(y.ts=E),f[t(114)](y)}for(let h of qe(r[t(121)])){if(!ct(h))continue;let w=X(h[t(55)]);if(w!==t(48)&&w!==t(15))continue;let y=X(h[t(84)]);if(!y)continue;let E={kind:w,content:y},I=X(h[t(49)]);I&&(E[t(49)]=I);let _=X(h[t(117)]);_&&(E[t(117)]=_);let A=Pi(h.ts);A&&(E.ts=A),f[t(114)](E)}f[t(80)]((h,w)=>{let y=t,E=Kg(h.ts)-Kg(w.ts);return E!==0?E:h[y(55)]===y(78)&&w[y(55)]!==y(78)?-1:h[y(55)]!==y(78)&&w[y(55)]===y(78)?1:0});let u={environment:s,characters:[...d[t(35)]()],props:p,anchors:f},g=X(r[t(57)]);g&&(u[t(57)]=g);let m=X(r[t(5)]);m&&(u[t(5)]=m),n[t(127)][t(114)](u)}let o=ct(e[t(16)])?e[t(16)]:{};for(let r of qe(o[t(11)])){if(!ct(r))continue;let s=X(r[t(85)]),c=X(r[t(55)]);if(!s||c!==t(62)&&c!==t(5)&&c!==t(45)||c===t(62)&&et(s))continue;let a={name:s,kind:c,status:X(r[t(39)])===t(97)?t(97):t(25),importance:X(r[t(74)])===t(53)?t(53):t(108)},d=qe(r[t(7)])[t(65)](X)[t(31)](Boolean);d[t(23)]&&(a[t(7)]=d);let p=Bg(r[t(9)]);p&&(a[t(9)]=p);let l=X(r[t(43)]);l&&(a[t(43)]=l);let f=X(r[t(1)]);f&&(a[t(1)]=f);let u=Jg(r[t(125)]);u[t(23)]&&(a[t(125)]=u);let g=qe(r[t(69)])[t(65)](X)[t(31)](Boolean);g[t(23)]&&(a[t(69)]=g),n[t(16)][t(11)][t(114)](a)}for(let r of qe(o[t(8)]))if(t(6)===t(6)){if(!ct(r))continue;let s=X(r[t(85)]);if(!s)continue;let c={name:s},a=qe(r[t(3)])[t(65)](X)[t(31)](Boolean);a[t(23)]&&(c[t(3)]=a);let d=Bg(r[t(34)]);d&&(c[t(34)]=d);let p=X(r[t(43)]);p&&(c[t(43)]=p);let l=X(r[t(1)]);l&&(c[t(1)]=l);let f=qe(r[t(73)])[t(65)](X)[t(31)](Boolean);f[t(23)]&&(c[t(73)]=f);let u=Jg(r[t(99)]);u[t(23)]&&(c[t(99)]=u),Object[t(115)](c)[t(23)]>1&&n[t(16)][t(8)][t(114)](c)}else return _0x150727?_0x422014?_0x1f4862[t(33)](/[。!?;]+$/,"")+"\u3002"+_0x2651c7:_0x44d23d:_0x1c02e9;for(let r of qe(o[t(19)])){if(!ct(r))continue;let s=X(r[t(124)]),c=X(r[t(50)]);s&&c&&n[t(16)][t(19)][t(114)]({from_name:s,canonical_name:c,evidence:X(r[t(89)])})}let i=ct(e[t(28)])?e[t(28)]:{};for(let r of qe(i[t(14)])){if(!ct(r))continue;let s=X(r[t(123)]);s&&n[t(28)][t(14)][t(114)]({text:s})}for(let r of qe(i[t(109)])){if(!ct(r))continue;let s=X(r[t(116)]);s&&n[t(28)][t(109)][t(114)]({ref:s})}return n}async function zg(e,t,n,o,i,r,s,c){let a=le,d="";for(let p=0;;p++)if(a(77)===a(88))_0x29fde1[a(125)][a(2)](_0xa46e54)||_0x28a8c2[a(125)][a(114)](_0x480bab);else{let l=await e[a(10)]({media:t,system:FS,user:YS(n,o+d),fps:i,responseJsonSchema:fm,...s?{localPath:s[a(64)],localMime:s[a(30)]}:{},...r?{signal:r}:{}}),f=l[a(123)][a(106)]();if(f[a(23)]<40)throw Ep(a(94)+n+a(98)+l[a(40)]+")",[a(118)+f[a(23)]]);let u;try{a(104)!==a(104)?_0x5dc535[a(114)]({name:_0x101a20,description:_0x8301e3}):u=JSON[a(29)](f)}catch{throw Ep(a(94)+n+a(122)+l[a(40)]+")",[f[a(42)](0,200)])}let g=_p(u),m=XS(g);if(m[a(127)][a(23)]===0)throw Ep(a(94)+n+a(72),[f[a(42)](0,200)]);let h=m[a(127)][a(66)]((y,E)=>y[a(12)][a(66)]((I,_)=>I.ts?[]:[a(130)+E+a(51)+_+a(90)+I[a(55)]+")"]));if(h[a(23)]>0){if(c?.({event:a(24),at:new Date()[a(126)](),episode:n,attempt:p+1,missing_count:h[a(23)],missing_paths:h,retries_exhausted:p===3}),p===3){if(a(44)!==a(105))throw new x(a(100)+n+": "+h[a(23)]+a(13),{exitCode:me,errorCode:a(129),hint:a(68),data:{actual:h}});{let y=_0x414037[a(106)]()?a(86)+_0x336d80+`
261
- `:a(110);return a(47)+_0x1bbdb7+a(36)+y}}d=a(75)+h[a(23)]+a(38)+h[a(54)]("\u3001")+a(96);continue}return{md:JSON[a(4)](g,null,2),output:m}}}function ua(e){return new x("The video skip ledger is invalid.",{exitCode:b,errorCode:"INGEST_SKIP_LEDGER_INVALID",hint:"Repair or remove skipped.json, then retry.",data:{actual:[e]}})}function eI(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=Mr(t.failure);if(!n)return null;let o=[];for(let i of t.attempts){let r=Mr(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 Sp(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 ua("root must be an object");let n=t;if(n.schema_version!==1||!Array.isArray(n.episodes))throw ua("schema_version must be 1 and episodes must be an array");let o=[],i=new Set;for(let r of n.episodes){let s=eI(r);if(!s)throw ua("one or more episode records are malformed");if(i.has(s.episode))throw ua(`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 Hg(e,t){e.writeJson("skipped.json",t)}function fa(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:b,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 tI(e){return{episode:e,synopsis:"",scenes:[],actors:[],locations:[],props:[],speakers:[],actorStates:[],locationStates:[],propStates:[]}}function ma(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(tI(s.episode))}return r}function Ur(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;zm(t,i),e.writeJson("context.json",t),e.clearError(`ep/ep_${String(i).padStart(3,"0")}.error.json`)}return t}function Qg(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 Pr="19",nI=new Set([Pr]),Ti=e=>String(e).padStart(3,"0"),Ip=2;function Yg(e){try{return Xt.statSync(e).size}catch{return 0}}function oI(e,t){let n=Yg(e);if(!(n<Yc))throw new x(`Episode ${t} is too large for inline base64 video input.`,{exitCode:b,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 ${Yc} bytes after ingest transcoding`],actual:[`${n} bytes`]}})}function Fg(e,t){try{let n=t.uploadBytes?(t.uploadBytes/1024/1024).toFixed(1):"?",o=JSON.stringify({...t,uploadMB:n,at:new Date().toISOString()})+`
262
- `;Xt.appendFileSync(e.path("timing.jsonl"),o)}catch{}}function qg(e){return new x("This workspace's accepted video sequence no longer matches the source.",{exitCode:b,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Restore the accepted episode prefix, or choose a fresh --workspace-path for a different source.",data:{actual:[e]}})}function Ap(e){if(!e.has("manifest.json"))return null;let t=e.readJson("manifest.json");if(!t.pipeline_version||!nI.has(t.pipeline_version))throw new x("This workspace uses an incompatible video-ingest pipeline.",{exitCode:b,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Choose a fresh --workspace-path and run ingest again.",data:{actual:[`workspace pipeline ${t.pipeline_version??"(missing)"}; current ${Pr}`]}});return e.readJson("manifest.json")}function kp(e,t){if(t.pipeline_version===Pr)return t;let n={...t,pipeline_version:Pr,updated:new Date().toISOString()};return e.writeJson("manifest.json",n),n}function iI(e,t,n){if(e&&e.source.kind!==t)throw qg(`source kind changed from ${e.source.kind} to ${t}`)}function rI(e,t,n,o){if(t){let i=mg(t.episodes,n);if(i.kind==="incompatible")throw qg(i.reason)}if(o){Xt.rmSync(e.path("ep"),{recursive:!0,force:!0}),Xt.rmSync(e.path("cache"),{recursive:!0,force:!0}),Xt.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"])Xt.rmSync(e.path(i),{force:!0})}}function sI(e,t){return e.map(n=>{let o=structuredClone(n);for(let i of o.actors)i.name=Ci(i.name,t)??i.name;for(let i of o.scenes){for(let c of i.characters)c.name=Ci(c.name,t)??c.name;i.location&&(i.location=Ci(i.location,t)??i.location);let r=[],s=new Set;for(let c of i.props){let a=(Ci(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=Ci(c.speaker,t)}return o})}function aI(e,t){let n=t.slice(0,8).map(o=>`- ${o.path}: ${o.message}`).join(`
255
+ `).trim().slice(0,6e3):"",u=Rm(l);i.writeText("pass1/source.txt",n),i.writeJson("pass1/chunks.json",u.map(N=>({index:N.index,core_line_start:N.core_line_start,core_line_end:N.core_line_end}))),i.writeJson("manifest.json",{version:1,pipeline_version:Np,updated:new Date().toISOString(),source:{path:zi.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 h=0;r.phaseStart("normalize");let m=await zm(u,e.concurrency??30,async N=>{let ie=`pass2/chunk_${ma(N.index)}.json`,we=`pass2/chunk_${ma(N.index)}.error.json`;if(i.has(ie)&&!e.force){let at=fp(i.readJson(ie),N);return i.clearError(we),h++,e.executor.recordReuse("ingest.text-normalize"),at}let{raw:mt,records:pn}=await Jm(e.executor,N,e.signal);return i.writeText(ie,mt),i.writeText(`pass2/chunk_${ma(N.index)}.jsonl`,vg(pn)),i.clearError(we),pn}),g=m.filter(N=>!N.ok);for(let N of g){let ie=N.error instanceof Error?N.error.message:String(N.error);i.writeJson(`pass2/chunk_${ma(N.index)}.error.json`,{chunk:N.index,error:ie})}if(s.flush({scope:{kind:"phase",phase:"normalize"},status:g.length?"failed":"succeeded"}),g.length>0)throw new E(`${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(N=>`chunk ${N.index}`)}});r.phaseEnd("normalize");let w,y,x;if(!e.force&&i.has("body.json"))w=i.readJson("body.json"),y=i.has("pass3/script.jsonl")?$r(i.readText("pass3/script.jsonl")).length:0,x=i.has("notes.json")?i.readJson("notes.json").length:0,h++;else{let N=[];for(let pn of m)pn.ok&&N.push(...pn.value);i.writeText("pass3/script.jsonl",vg(N));let ie=$r(i.readText("pass3/script.jsonl")),we=CS(t.path),mt=vm(ie,{title:we});i.writeJson("notes.json",mt.notes),w=mt.script,i.writeJson("body.json",w),y=N.length,x=mt.notes.length}xm(w,Ys(o),d);let S=N=>String(N).padStart(3,"0"),_=(N,ie)=>`serial/win_${S(N)}_${S(ie)}.json`,A={readUpdate:(N,ie)=>i.has(_(N,ie))?i.readText(_(N,ie)):void 0,writeStep:(N,ie,we,mt)=>{i.writeText(`serial/context_${S(N)}.md`,we),i.writeText(_(N,ie),mt)},readArc:(N,ie)=>{let we=`serial/arc_${S(N)}_${S(ie)}.md`;return i.has(we)?i.readText(we):void 0},writeArc:(N,ie,we)=>{i.writeText(`serial/arc_${S(N)}_${S(ie)}.md`,we)},readNameFix:(N,ie)=>{let we=`serial/fix_${S(N)}_${S(ie)}.json`;return i.has(we)?i.readText(we):void 0},writeNameFix:(N,ie,we)=>i.writeText(`serial/fix_${S(N)}_${S(ie)}.json`,we)};r.phaseStart("serial");let b=await fg(w,{executor:e.executor,checkpoint:A,force:e.force??!1,...f?{sourceRef:f}:{},onWindow:N=>{N.index===0&&r.serialStart(N.total,N.totalEpisodes),r.windowDone(N.startEp,N.endEp,N.ms,N.cached);let ie=N.startEp===N.endEp?{kind:"episode",episode:N.startEp}:{kind:"episode-range",startEpisode:N.startEp,endEpisode:N.endEp},we=Date.now();s.flush({scope:ie,status:N.cached?"reused":"succeeded",startedAtMs:we-N.ms,endedAtMs:we})},...e.signal?{signal:e.signal}:{}}),U=b.doc;h+=b.reused,r.phaseEnd("serial"),r.phaseStart("govern");let{script:O,idMap:I}=aa(U);i.writeJson("id_map.json",I);let L=yt(O);if(!L.ok)throw i.writeJson("validation.json",L),new E("Intermediate script failed validation before v4 identity assignment.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:L.errors.slice(0,5).map(N=>`${N.path}: ${N.message}`)}});let T=!e.force&&i.has("v4_identity_map.json")?i.readJson("v4_identity_map.json"):void 0,C=Bi(Nt(U),T,b.identityKeys),R=C.script,j=Le(R),Z=[],ve=Date.now(),K="failed";try{if(j.ok){let N=await Sg(i,R,e.executor,{force:e.force??!1,...e.signal?{signal:e.signal}:{}});Z=Ig(N.report)}K="succeeded"}finally{s.flush({scope:{kind:"phase",phase:"asset-audit"},status:K,startedAtMs:ve})}let Re={...j,warnings:[...j.warnings,...Ji(R),...Z]};if(i.writeJson("pass5/script.json",R),i.writeJson("v4_identity_map.json",C.identityMap),i.writeJson("validation.json",Re),!Re.ok)throw new E("Final script.json failed v4 validation.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:Re.errors.slice(0,5).map(N=>`${N.path}: ${N.message}`)}});i.writeJson("script.json",R),r.phaseEnd("govern"),r.finish();let We=R;return c="succeeded",{workspacePath:i.root,chunks:u.length,reused:h,records:y,notes:x,assets:{actors:We.actors?.length??0,locations:We.locations?.length??0,props:We.props?.length??0},scriptPath:i.path("script.json"),validation:{ok:Re.ok,errors:Re.errors.length,warnings:Re.warnings.length}}}finally{s.finish(c)}}function CS(e){return zi.basename(e,zi.extname(e))}import*as Oo from"node:fs";import*as ci from"node:path";import{createHash as rI}from"node:crypto";var PS=()=>({apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:[],voice:""});function Ao(){return{lastEpisode:0,registry:[],digests:[],openThreads:[]}}var ye=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),jr=(e,t)=>e.length>t?`${e.slice(0,t)}\u2026`:e;function TS(e,t){let n=ye(t);return e.find(o=>ye(o.name)===n||ye(o.identitySeed)===n||o.aliases.some(i=>ye(i)===n))}var VS=3,$S=12e3;function ai(e,t){let n=(t??"").trim();n&&!e.includes(n)&&e.push(n)}var DS=["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","voice"];function ga(e,t,n){if(!t)return e;let o=e?{...e,persistent_marks:[...e.persistent_marks]}:PS();for(let i of DS){let r=t[i]?.trim()??"";r&&(n||!o[i])&&(o[i]=r)}for(let i of t.persistent_marks??[])ai(o.persistent_marks,i);return o}function Up(e,t,n){let o=t.name.trim();if(!o)return;let i=t.description.trim(),r=e.find(s=>An(s.name)===An(o));if(!r){e.push({name:o,description:i});return}i&&(n||!r.description)&&(r.description=i)}function Mg(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??[])ai(e.recognitionAnchors,s);e.identityProfile=ga(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??[])ai(e.aliases,s);for(let s of t.add_states??[])Up(e.states,s,o);e.lastEpisode=n}function ha(e,t,n){let o=r=>TS(e.registry,r);for(let r of t.registry_delta.new_entities){let s=r.name.trim();if(!s||r.kind==="actor"&&st(s))continue;let c=o(s);if(c){Mg(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??[])Up(a,p,!1);let d=[];for(let p of r.aliases??[])ai(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:ga(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&&Mg(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||ye(c)===ye(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(h=>({...h})),f=new Set([...s.aliases,...a.aliases,s.identitySeed,a.identitySeed,s.name,a.name,r.from_name].map(h=>h.trim()).filter(Boolean));d.name=c,d.status="canonical",d.importance=s.importance==="featured"||a.importance==="featured"?"featured":"background",d.recognitionAnchors=[];for(let h of[...s.recognitionAnchors,...a.recognitionAnchors])ai(d.recognitionAnchors,h);let u=ga(void 0,s.identityProfile,!0);d.identityProfile=ga(u,a.identityProfile,!0),(a.appearance||s.appearance)&&(d.appearance=a.appearance||s.appearance),d.role=a.role||s.role,d.states=[];for(let h of[...l,...p.states])Up(d.states,h,!1);d.aliases=[...f].filter(h=>ye(h)!==ye(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}ai(s.aliases,s.name),ai(s.aliases,r.from_name),s.name=c,s.status="canonical",s.aliases=s.aliases.filter(d=>ye(d)!==ye(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 Ug(e,t){return e.digests.push({episode:t,synopsis:"",outcome:"skipped"}),e.lastEpisode=t,e}function GS(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: ${jr(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=jr(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 Lg(e,t){let n=jr(e.appearance||e.role||"",t?30:60),o=e.states.map(i=>i.description?`${i.name}\uFF08${jr(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 Ng(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(...GS(a,n),"")}if(r.length||s.length){o.push("## \u573A\u666F / \u9053\u5177","");for(let a of r)o.push(Lg(a,n));for(let a of s)o.push(Lg(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?jr(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(`
256
+ `)}function ya(e){for(let t=VS;t>=1;t--){let n=Ng(e,t,!1);if(n.length<=$S)return n}return Ng(e,1,!0)}function ko(e){let t=new Map;for(let n of e)for(let o of[n.identitySeed,...n.aliases])ye(o)!==ye(n.name)&&t.set(o,n.name);return t}function JS(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 Cg(e,t){let n=new Map,o=new Map,i=(s,c)=>{let a=ye(s),d=c.trim();!d||ye(d)===a||(o.has(a)||o.set(a,new Set),o.get(a).add(d))};for(let s of t){n.set(ye(s.name),s.importance);for(let c of s.aliases)n.set(ye(c),s.importance);n.set(ye(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 h of p)if(l=t.find(m=>ye(m.name)===ye(h)||ye(m.identitySeed)===ye(h)||m.aliases.some(g=>ye(g)===ye(h))),l)break;a.importance=l?.importance??n.get(ye(d))??"featured";let f=o.get(ye(d));if(f?.size&&(a.aliases=[...new Set([...a.aliases??[],...f])]),!l)continue;let u=l.kind==="actor"?JS(l):[l.appearance,l.role].map(h=>(h?.trim()??"").replace(/[。;]+$/,"")).filter(Boolean).join("\uFF1B");u&&(a.description=`${u}\u3002`);for(let h of a.states??[]){let m=l.states.find(g=>An(g.name)===An(h.state_name));m?.description?h.description=m.description:h.state_name==="default"&&l.kind!=="actor"&&l.appearance&&(h.description=l.appearance)}}};return r(e.actors,"actor_name"),r(e.locations,"location_name"),r(e.props,"prop_name"),e}function Pg(e,t,n){let o=ko(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)}:st(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(m=>m.states.length?m.states.map(g=>({name:i(m.name),state:g})):[{name:i(m.name)}]),h=p.actions.map((m,g)=>{let w={kind:"comic",document_id:d.document_id,pages:m.pages,regions:m.regions},y={identity_key:`${f}:action:${g+1}`,type:m.type,content:m.content,extend:{scriptctl:{source:w}}};if((m.type==="dialogue"||m.type==="inner_thought")&&(y.speaker=r(m.speaker),m.parenthetical&&(y.parenthetical=m.parenthetical),"name"in y.speaker)){let x=y.speaker.name;u.some(S=>S.name===x)||u.push({name:x})}return y});return{identity_key:f,scene_id:`scn_${String(++s).padStart(3,"0")}`,environment:{...p.space?{space:p.space}:{},...p.time?{time:xo(p.time)}:{}},location:p.location?{name:i(p.location)}:null,actors:u,props:[...new Set(p.props.map(i))].map(m=>({name:m})),actions:h}})}))},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 E(`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 Hi=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();function BS(e,t,n){let o=ko(t),i=l=>o.get(l)??l,r=new Map;for(let l of t){let f=i(l.name),h=t.find(g=>g.kind===l.kind&&Hi(g.name)===Hi(f))??l,m=`${l.kind}:${Hi(f)}`;r.has(m)||r.set(m,`${n}:${h.kind}:${h.firstEpisode}:${Hi(h.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}:${Hi(f)}`)??`${n}:${l.kind}:source:${Hi(f)}`;p[l.kind][l.provisional_id]=u,d[l.provisional_id]=Object.fromEntries(l.states.map(h=>[h.id,`${u}:state:${An(h.name)}`]))}return{actor:s,location:c,prop:a,state:d}}function wa(e,t,n,o){let{script:i,assets:r,identityKeys:s}=ia(e);Cg(i,t.registry);let c=pa(i),{script:a,idMap:d}=aa(c),p=yt(a);if(!p.ok)return{initial:i,final:a,idMap:d,validation:p,identityMap:o,scriptV4:null};let l=Bi(Nt(c),o,{...BS(r,t.registry,n),...s}),f=l.script,u=Le(f);return{initial:i,final:f,scriptV4:f,idMap:d,identityMap:l.identityMap,validation:{...u,warnings:[...u.warnings,...Ji(f)]}}}import*as Tg from"node:fs";import*as Fn from"node:path";import{createHash as KS}from"node:crypto";import{PDFDocument as jS}from"pdf-lib";import*as xa from"node:path";function _a(e){let t=xa.basename(e,xa.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 zS(e){let t=e.kind==="comic-file"?[e.path]:e.files,n=t.map(i=>({path:i,sourceNumber:_a(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 E("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=>Fn.basename(i))}});return n.sort((i,r)=>i.sourceNumber!==null&&r.sourceNumber!==null?i.sourceNumber-r.sourceNumber:Fn.basename(i.path).localeCompare(Fn.basename(r.path),"zh-Hans",{numeric:!0}))}async function Vg(e){let t=[];for(let[n,o]of zS(e).entries()){let i=Tg.readFileSync(o.path),s=(await jS.load(i,{updateMetadata:!1})).getPageCount();if(!s||s>1e3||i.length>5e7)throw new E("PDF is outside the document provider limits.",{exitCode:k,errorCode:"INGEST_COMIC_SIZE",hint:"Provide one chapter per PDF, containing 1\u20131000 pages and at most 50 MB.",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:Fn.basename(o.path,Fn.extname(o.path)),path:Fn.resolve(o.path),sha256:KS("sha256").update(i).digest("hex"),page_count:s,size_bytes:i.length})}return t}function $g(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 E("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 HS,StandardFonts as QS,rgb as FS,pushGraphicsState as YS,popGraphicsState as qS,concatTransformationMatrix as Ea}from"pdf-lib";async function Dg(e){let t=await HS.load(e),n=await t.embedFont(QS.Helvetica),o=FS(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(YS()),s){case 90:i.pushOperators(Ea(0,1,-1,0,r.x+r.width,r.y));break;case 180:i.pushOperators(Ea(-1,0,0,-1,r.x+r.width,r.y+r.height));break;case 270:i.pushOperators(Ea(0,-1,1,0,r.x,r.y+r.height));break;default:i.pushOperators(Ea(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}`,h=Math.max(1,Math.min(d-p,f+1));for(let m of[1,a-n.widthOfTextAtSize(u,p)-1])i.drawText(u,{x:m,y:h,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(qS())}return t.save()}import*as Gg from"node:fs";import*as Jg from"node:path";import ZS from"proper-lockfile";async function bo(e,t){let n=Jg.resolve(e);Gg.mkdirSync(n,{recursive:!0});let o=null;try{o=await ZS.lock(n,{realpath:!1,stale:12e4,update:1e4,retries:0})}catch(i){throw new E("The ingest workspace is busy.",{exitCode:me,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{z as WS}from"zod";var Pp=an;function Cp(){let e=["q29TAwmGzxbPC29KzsbMywLSzwqGDhjHBNnJCMLWDcb2ywXPzgf0Aw9UoIa","CMvNAw9UCW","Dg9ku09ou2nOzw1H","44cc5PYSifberIdLHBeG","zgf0yq","ioMHTE+8JoIVT+wUJoAvToMyHEIVU+w5TUAmIEMHUUw6J+MaKoAGVoI9RowgMEwfQoMdQowjP+AdHEoaGGOk","BwvZC2fNzq","5l2G5PIV5RYR55s76l2S5yMN5PYS55Qe5lIY6kgm6kEJ5P6q5zMO44cc6l6t5ywL5PIV5A6m5Pw05lIa6k+DifberIdLKOZLIy3PNAlLKitOR53NTk/NP6/NMOtLT7lNN6xORR7LRPRJGilOVPpLH7RKUidKUkRNRkBLKiGGC2nOzw1HioEAHcbku09oiowVUEIXOE+8JowqJoAxTUwmHEwqQ+ACRoIVNEMaKoAGVowjP+ACRooaGEI1Hos6P+wINUMhJ+wsJowjP+AdHEE6V+E0OUoaGGOk6l6t5yE65A2x5Q6177YA5Q+p5P2HigfJDgLVBNmG55Qeihr5CguG5y+Q6io95PIVigfJDgLVBU+8IoEuU+MDOU+8IEoaGxrYyw5ZAxrPB27VViJOVAZLNlRVViNJGifKAwfSB2D1zE+8IowVUEEzVs/LRQlOP4lML4hNMB3VViNJGifPBM5LCL90Ag91z2H077Yi5lQ654MP5B+d5AoW77Yj77YB5Q2J5PAh57UF5lIa5yAz5ywLignVBNrLBNtJGilMR4/MNAhPG73LJixLKkSGCgfNzxmG5PwW5A2x5PwW57Ue44cbCMvNAw9UCYdLR7NOSAhMLBdNU4tJGifZCgvHA2vYiowsJcbWyxjLBNrOzxrPy2fS44cczgLHBg9NDwuG5lIoigLUBMvYx3rOB3vNAhqG55QeihnWzwfRzxiG5AgR5y+r6k+D6icf77YmCgfYzw50Agv0AwnHBcdLOAV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5lUL5yIx5ywLigLNBM9YzwrFCgfNzxmG5BM25yAz5y6F5zUG44cc5lIn6kAb5zYOigfJDgLVBNmG5lIoigLNBM9YzwrFCgfNzxmG5zcm5PE255M76k6W5zcm5lIa6Ag144ccC3LUB3bZAxmG5y+Q5QAc5OUS5PYS6k+D77Ym5lIn6io95lUJ5PU/5Q2J5PAh44cc","ugfNzxmGywjZzw50igzYB20GDhjHBNnJCMLWDdOG","BwfW","C2fMzvbHCNnL","Cgf0Aa","C2nLBMvZ","AgfZ","AM9PBG","BgvUz3rO","CgfNzxm","AxnZDwvZ","CgfYC2u","B3bLBMfWAs0ZlJa","su5hrvnux0nptuLdx1nfuKLbtf9gquLmruq","Dgv4Da","C29Tzq","C2XPy2u","CgfNzq","sw52ywXPzcbVCIb1BM9YzgvYzwqGC291CMnLihbHz2vZoIa","zNjVBq","zxjYB3i","sw52ywXPzcbVCIbKDxbSAwnHDguGAwDUB3jLzcbWywDLoIa","ywn0Aw9UCW","5B2t5yMn6k+D77YA","C3vJy2vZCW","zMLSDgvY","ihbHz2vZlG","oYbKB2n1BwvUDcbOyxmG","z2vUzxjHDgu","sw5ZCgvJDcbLCc8QlNjLC3bVBNnLlMPZB24Gyw5KihjLCNvUigLUz2vZDcb3AxrOihrOzsbZyw1LihnVDxjJzsbHBMqGD29YA3nWywnLlG","AwDUB3jLzf9WywDLCW","ywrK"];return Cp=function(){return e},Cp()}function an(e,t){e=e-0;let n=Cp(),o=n[e];if(an.RPngbJ===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=c.charAt(h++);~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)};an.xePDtj=i,an.gnQDUQ={},an.RPngbJ=!0}let r=n[0];an.rPrOht!==r&&(an.gnQDUQ={},an.rPrOht=r);let s=an.gnQDUQ[e];return s===void 0?(o=an.xePDtj(o),an.gnQDUQ[e]=o):o=s,o}var XS=Pp(7);function eI(e,t){let n=Pp,o=Qd[n(10)](JSON[n(18)](e)),i=a=>{let d=n;throw new E(d(0)+a[d(14)]("; "),{exitCode:k,errorCode:d(20),hint:d(36),data:{actual:a}})};if(!o[n(31)])return i(o[n(27)][n(17)][n(23)](0,8)[n(9)](a=>a[n(11)][n(14)](".")+": "+a[n(6)]));let r=o[n(4)],s=new Set;for(let a of r[n(12)])for(let d of a[n(29)]){if(d[n(16)][n(22)]((l,f)=>l>t||f>0&&l<=d[n(16)][f-1]))return i([n(25)+d[n(16)][n(14)](", ")+n(34)+t+n(33)]);let p=Nr(d[n(16)],d[n(1)]);if(p[n(15)])return i(p);for(let l of d[n(16)])s[n(38)](l)}for(let a of r[n(37)]){if(a[n(24)]>t||s[n(13)](a[n(24)]))return i([n(28)+a[n(24)]]);s[n(38)](a[n(24)])}let c=Array[n(26)]({length:t},(a,d)=>d+1)[n(32)](a=>!s[n(13)](a));return c[n(15)]?i([n(8)+c[n(14)](", ")]):r}async function Bg(e,t,n,o,i,r,s){let c=Pp,a=await e[c(35)]({media:t,system:XS,user:c(30)+n+c(3)+o+c(5)+i,responseJsonSchema:WS[c(2)](nm,{target:c(19)}),signal:s});return r(a[c(21)]),eI(a[c(21)],o)}function Sa(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tI(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 nI(e){if(e instanceof P)return{failure:e.failure,attempts:e.modelFailures};if(e instanceof E){let t=e.errorCode==="INGEST_VALIDATION_FAILED"||e.errorCode==="INGEST_VIDEO_SERIAL_FAILED"||e.errorCode==="INGEST_COMIC_SERIAL_FAILED";return{failure:Rt(tI(e),{retryable:t,message:e.message}),attempts:[]}}return{failure:Rt({failure_type:"unknown",failure_code:"unknown"},{retryable:!1,message:e instanceof Error?e.message:String(e)}),attempts:[]}}function Ia(e,t,n){let o=nI(e);return{schema_version:1,unit:{kind:"episode",episode:t},phase:n,occurred_at:new Date().toISOString(),...o}}function jg(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 Kg(e,t){return typeof e=="string"&&t.some(n=>n===e)}function Qi(e){return typeof e=="string"?e:void 0}function oI(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!Sa(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 iI(e){let t=e.provider_source,n=e.provider_reason;return{provider:Qi(e.provider),model:Qi(e.model),operation:Qi(e.operation),http_status:typeof e.http_status=="number"?e.http_status:void 0,system_code:Qi(e.system_code),provider_source:Kg(t,["prompt","candidate"])?t:void 0,provider_reason:Kg(n,["SAFETY","PROHIBITED_CONTENT","BLOCKLIST","SPII","RECITATION","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION","OTHER","UNSPECIFIED","UNKNOWN"])?n:void 0,provider_reason_raw:Qi(e.provider_reason_raw),finish_message:Qi(e.finish_message),safety_ratings:oI(e.safety_ratings),details:Array.isArray(e.details)&&e.details.every(i=>typeof i=="string")?e.details:void 0}}function zr(e){if(!Sa(e))return null;let t=Ul(e.failure_type,e.failure_code);return!t||typeof e.retryable!="boolean"||typeof e.message!="string"?null:Rt(t,{...iI(e),retryable:e.retryable,message:e.message})}function Hr(e){if(!Sa(e)||e.schema_version!==1)return null;let t=e.unit;if(!Sa(t)||t.kind!=="episode"||typeof t.episode!="number"||typeof e.phase!="string"||typeof e.occurred_at!="string")return null;let n=zr(e.failure);if(!n||!Array.isArray(e.attempts))return null;let o=[];for(let i of e.attempts){let r=zr(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 zg="comic-1",Aa=e=>String(e).padStart(3,"0"),Hg=["script.initial.json","id_map.json","validation.json","context.json","v4_identity_map.json","script.json"];function Tp(e,t,n){let o=wa(Pg(e,t.context,n),t.context,"comic",t.identityMap);if(!o.scriptV4||!o.validation.ok)throw new E("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 Vp(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 sI(e){let t=Sn(e.sourcePath);if(t.kind!=="comic-file"&&t.kind!=="comic-directory")throw new E("Expected PDF comic source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=new lt(ci.resolve(e.workspacePath));n.ensure();let o=n.has("manifest.json")?n.readJson("manifest.json"):null;if(o&&o.pipeline_version!==zg)throw new E("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 E("Workspace already contains an unmanaged script.json.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Choose a fresh workspace."});let i=await Vg(t);o&&$g(o.episodes,i);let r={version:1,pipeline_version:zg,updated:new Date().toISOString(),source:{kind:t.kind,path:ci.resolve(t.path),sha256:rI("sha256").update(i.map(g=>g.sha256).join(`
257
+ `)).digest("hex")},episodes:i,...o?.current_error?{current_error:o.current_error}:{}};if(e.force){for(let g of o?.episodes??[])for(let w of["json","response.json","context.md","error.json","input.pdf"])Oo.rmSync(n.path(`ep/ep_${Aa(g.episode)}.${w}`),{force:!0});for(let g of["checkpoint.json","timings.json",...Hg])Oo.rmSync(n.path(g),{force:!0});delete r.current_error}n.writeJson("manifest.json",r);let s=n.has("checkpoint.json")?n.readJson("checkpoint.json"):{context:Ao(),identityMap:So()},c=i.slice(0,s.context.lastEpisode).map(g=>n.readJson(`ep/ep_${Aa(g.episode)}.json`)),a=Oo.realpathSync(t.path),d=ci.basename(a,t.kind==="comic-file"?ci.extname(a):""),p=new Io(n,e.executor),l=new ji(g=>n.writeJson("timings.json",g));l.phaseStart("serial"),l.serialStart(i.length,i.length);let f="failed",u=0,h=c.length,m;try{if(c.length>0){Vp(n,Tp(c,s,d),s.context);for(let y of c)n.clearError(`ep/ep_${Aa(y.episode)}.error.json`);r.current_error&&r.current_error.unit.episode<=s.context.lastEpisode&&(delete r.current_error,r.updated=new Date().toISOString(),n.writeJson("manifest.json",r))}else for(let y of Hg)Oo.rmSync(n.path(y),{force:!0});for(let y of i){if(e.signal?.throwIfAborted(),y.episode<=s.context.lastEpisode){e.executor.recordReuse("ingest.comic-serial");let U=Date.now();p.flush({scope:{kind:"episode",episode:y.episode},status:"reused",startedAtMs:U,endedAtMs:U}),l.windowDone(y.episode,y.episode,0,!0);continue}if(e.step&&u>=1)break;let x=Date.now(),S=`ep/ep_${Aa(y.episode)}`,_=r.current_error?.unit.episode===y.episode?r.current_error.failure.message:void 0,A=ya(s.context)+(_?`
258
+
259
+ \u672C\u8BDD\u4E0A\u4E00\u6B21\u8F93\u51FA\u5C1A\u672A\u88AB\u63A5\u53D7\uFF0C\u5931\u8D25\u539F\u56E0\uFF1A${_}\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(`${S}.context.md`,A),process.stderr.write(`\u6F2B\u753B ${y.episode}/${i.length} \xB7 ${y.title} \xB7 ${y.page_count} \u9875
260
+ `);let b="upload";try{m??=e.executor.documentPort("ingest.comic-serial");let U=n.path(`${S}.input.pdf`);ca(U,Buffer.from(await Dg(Oo.readFileSync(y.path))));let O=await m.prepare(U,e.signal),I;try{b="generate";let ve=await Bg(m,O,y.title,y.page_count,A,K=>n.writeText(`${S}.response.json`,K),e.signal);I={episode:y.episode,document_id:y.document_id,title:y.title,output:ve}}finally{await m.release(O,e.signal)}b="validation";let L=ha(structuredClone(s.context),I.output,y.episode),T=[...c,I],C=Tp(T,{context:L,identityMap:s.identityMap},d),R={context:L,identityMap:C.identityMap};b="checkpoint",n.writeJson(`${S}.json`,I),n.writeJson("checkpoint.json",R),s=R,c.push(I),b="publish",Vp(n,C,s.context),n.clearError(`${S}.error.json`),delete r.current_error,r.updated=new Date().toISOString(),n.writeJson("manifest.json",r),u++;let j=Date.now();l.windowDone(y.episode,y.episode,j-x,!1),p.flush({scope:{kind:"episode",episode:y.episode},status:"succeeded",startedAtMs:x,endedAtMs:j});let Z=I.output.scenes.reduce((ve,K)=>ve+K.actions.length,0);process.stderr.write(` \u5DF2\u4FDD\u5B58\uFF1A${I.output.scenes.length} \u573A / ${Z} \u6761\u6B63\u6587
261
+ `)}catch(U){let O=Ia(U,y.episode,b);throw n.writeJson(`${S}.error.json`,O),n.writeJson("manifest.json",{...r,updated:O.occurred_at,current_error:O}),p.flush({scope:{kind:"episode",episode:y.episode},status:"failed",startedAtMs:x,endedAtMs:Date.now()}),U}}let g=Tp(c,s,d);Vp(n,g,s.context);let w=c.length===i.length;return f="succeeded",{workspace:n.root,script_path:n.path("script.json"),kind:"comic",episodes:i.length,processed:u,reused:h,completed:c.length,remaining:i.length-c.length,complete:w,next_episode:w?null:c.length+1,assets:{actors:g.scriptV4.actors.length,locations:g.scriptV4.locations.length,props:g.scriptV4.props.length}}}finally{l.phaseEnd("serial"),l.finish(),p.finish(f)}}async function Qg(e){return bo(e.workspacePath,()=>sI(e))}import*as dn from"node:fs";import*as Zi from"node:path";function aI(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 Fg(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=aI(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 ka(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 Fi(e){let t=typeof e=="string"?e.trim().replace(/\.\d+$/,""):"",n=t.match(/^(?:(\d+):)?(\d+):(\d{2})$/);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")}`}function Yi(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 Yg=e=>String(e).padStart(3,"0"),cI={\u5185:"interior",\u5916:"exterior"},dI={act:"action",dlg:"dialogue",think:"inner_thought"},$p={broadcast:"broadcast",system:"system",group:"group",offscreen:"offscreen",prop:"offscreen",location:"offscreen"};function pI(e){let t=e.match(/^(\w+):(.+)$/);if(t&&$p[t[1]]){let n=t[2].trim();return n?{kind:$p[t[1]],label:n}:{kind:$p[t[1]]}}return st(e)?{kind:"group",label:e.trim()}:{name:e}}function qg(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_${Yg(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=cI[(a.environment.space??"").trim()],h=xo(a.environment.time);u&&(f.space=u),h&&(f.time=h);let m=[],g=A=>{m.some(b=>b.name===A)||m.push({name:A})};for(let A of a.characters)A.name&&!st(A.name)&&(A.states.length===0?m.push({name:A.name}):m.push(...A.states.map(b=>({name:A.name,state:b}))));let w=new Map,y=a.anchors.map(A=>{let b=Fi(A.ts),U=b?`time:${b}`:`content:${JSON.stringify([A.kind,A.speaker??"",A.content])}`,O=(w.get(U)??0)+1;w.set(U,O);let I={identity_key:`${l}:action:${U}:${O}`,type:dI[A.kind]??"action",content:A.content};if((A.kind==="dlg"||A.kind==="think")&&A.speaker){let T=pI(A.speaker);I.speaker=T,"name"in T&&g(T.name)}A.parenthetical&&(I.parenthetical=A.parenthetical);let L=Fi(A.ts);return L&&(I.extend={timestamp:L}),I}),x=(a.location??"").trim(),S=[],_=new Set;for(let A of a.props??[]){if(!A)continue;let b=A.normalize("NFC").replace(/\s+/g," ").trim();!b||_.has(b)||(_.add(b),S.push({name:A}))}return{identity_key:l,scene_id:`scn_${Yg(++n)}`,...f.space||f.time?{environment:f}:{},location:x?{name:x}:null,actors:m,props:S,actions:y}})}});return{title:t,episodes:o}}var lI=60,uI=6,fI=[-1e3,0,1e3],eh=/(?:身穿|穿着|服装|造型|衣|裙|袍|衫|夹克|制服|西装|盔甲|装甲|防弹服|套装|裤|靴)/u,Dp=/(?:全身|半身|上半身|四分之三身|躯干|胸前|腰部)/u,Gp=/(?:站(?:在|立)|坐(?:在|下|起)|跪(?:在|下|倒)?|蹲(?:在|下)?|走(?:在|出|向)|行走|迈步|奔跑|跳起|跃起|转身|抬头|转头)/u,Zg=/(?:特写|近景|脸|面容|五官|正脸|侧脸|侧前脸|双眼|眼眶|眉头|嘴角)/u,th=/(?:背对|背影|远处|极远|模糊|运动模糊|脸被遮|面部遮挡|只露出|纯道具|空镜)/u,nh=/(?:双脚|脚部|膝盖|伤口|手部特写)/u,oh=/(?:画外音|旁白|未入镜|镜外|电话音|广播|\bO\.?S\.?\b)/iu;function vo(e){return e.normalize("NFC").replace(/\s+/g," ").trim()}function ih(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 rh(e){let t=e.trim().match(/^(\d+):(\d{2})$/);return t?Number(t[1])*1e3+Number(t[2])*10:null}function sh(e,t="clock"){return t==="legacy_centiseconds"?rh(e):ih(e)}function Jp(e,t){return e===null?!1:t===void 0||e<=t}function mI(e,t){if(t===void 0)return"clock";let n=e.scenes.flatMap(r=>r.actions.map(ah)).filter(Boolean),o=n.filter(r=>Jp(ih(r),t)).length;return n.filter(r=>Jp(rh(r),t)).length>o?"legacy_centiseconds":"clock"}function Wg(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 ah(e){let t=e.extend?.timestamp;return typeof t=="string"?t.trim():""}function gI(e,t){let n=new Set([e.actor_name,...e.aliases??[]].map(vo).filter(Boolean));for(let[o,i]of t)vo(i)===vo(e.actor_name)&&n.add(vo(o));return[...n].sort((o,i)=>i.length-o.length)}function ch(e,t){let n=t.map(o=>e.indexOf(o)).filter(o=>o>=0);return n.length>0?Math.min(...n):-1}function dh(e,t,n){return t.filter(o=>ch(e,n.get(o.actor_id)??[])>=0).length}function hI({action:e,actor:t,actorCount:n,allActors:o,surfaces:i,surfacesByActor:r,stateName:s}){let c=e.type==="action"||e.type==="transition",a=vo(c?e.content:"parenthetical"in e?e.parenthetical??"":""),d=ch(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&&!oh.test(a),h=n===1&&(c&&a.length>0||u&&a.length>0&&(Gp.test(a)||Zg.test(a)));if(!l&&!u&&!h)return null;let m=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=vo(s);return y&&y!=="default"&&y!=="\u9ED8\u8BA4"&&a.includes(y)&&(g+=35),eh.test(a)&&(g+=30),Dp.test(a)?(g+=25,w+=15):Gp.test(a)&&(g+=15,w+=5),Zg.test(a)&&(w+=30,Dp.test(a)||(g-=20)),th.test(a)&&(g-=70,w-=70),nh.test(a)&&(g-=40),dh(a,o,r)>=2&&(g-=15,w-=15),{stateScore:g,identityScore:w,selection:m}}function yI(e,t,n){let o=e.type==="action"||e.type==="transition",i="parenthetical"in e?vo(e.parenthetical??""):"";if(!o&&oh.test(i))return null;let r=vo(o?e.content:i),s=o?0:-40;return s-=dh(r,t,n)*20,eh.test(r)&&(s+=10),Dp.test(r)?s+=10:Gp.test(r)&&(s+=5),th.test(r)&&(s-=20),nh.test(r)&&(s-=10),{stateScore:s,identityScore:Number.NEGATIVE_INFINITY,selection:"scene_fallback"}}function Qr(e,t,n){let o=(n.get(`${e.episode}:${e.milliseconds}`)?.size??0)>1;return e[t]-(o?35:0)}function ph(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||Qr(a,t,n)>Qr(p,t,n))&&r.set(d,a)}let s=[...r.values()].sort((a,d)=>Qr(d,t,n)-Qr(a,t,n)||a.episode-d.episode||a.milliseconds-d.milliseconds).filter(a=>i===null||Qr(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 wI(e,t,n){return ph(e,t,n,1,null)[0]??null}function Xg(e){return e.replace(/[^0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function ba(e,t,n,o,i){let r=new Map(o.map(g=>[g.episode,g])),s=ko(n.registry),c=new Map(t.actors.map(g=>[g.actor_id,g])),a=new Map(t.actors.map(g=>[g.actor_id,gI(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,x=r.get(y);if(!x)continue;let S=mI(w,x.duration_ms);for(let _=0;_<w.scenes.length;_+=1){let A=w.scenes[_],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 O=c.get(U.actor_id);if(!O)continue;let I=a.get(O.actor_id)??[O.actor_name],L=[],T=U.state_ids.length===1?U.state_ids[0]:null,C=T?O.states.find(R=>R.state_id===T):null;for(let R of A.actions){let j=ah(R),Z=sh(j,S);if(!Jp(Z,x.duration_ms))continue;let ve=hI({action:R,actor:O,actorCount:b.length,allActors:b,surfaces:I,surfacesByActor:a,stateName:C?.state_name??"default"}),K=ve??(C?yI(R,b,a):null);if(!K)continue;let Re={actorId:O.actor_id,episode:y,episodeId:w.episode_id,sceneId:A.scene_id,timestamp:Wg(Z),milliseconds:Z,durationMs:x.duration_ms,stateScore:K.stateScore,identityScore:K.identityScore,selection:K.selection,sourcePath:x.path,sourceSha256:x.sha256};if(L.push(Re),ve){let We=`${y}:${Z}`,N=f.get(We)??new Set;N.add(O.actor_id),f.set(We,N)}}if(L.length>0){let R=p.get(O.actor_id)??[];if(R.push(...L),p.set(O.actor_id,R),C){let j=`${O.actor_id}:${C.state_id}`,Z=l.get(j)??[];Z.push(...L),l.set(j,Z)}}}}}let u=(g,w)=>{let y=c.get(g),x=c.get(w),S=y?.importance==="background"?1:0,_=x?.importance==="background"?1:0;return S-_||(d.get(w)??0)-(d.get(g)??0)||(y?.actor_name??g).localeCompare(x?.actor_name??w,"zh-CN")},h=[...l.entries()].flatMap(([g,w])=>{let[y,x]=g.split(":"),S=y?c.get(y):void 0,_=S?.states.find(O=>O.state_id===x),A=wI(w,"stateScore",f);if(!S||!_||!A)return[];let b=`state:${S.actor_id}:${_.state_id}`,U=fI.map(O=>{let I=A.durationMs===void 0?Number.POSITIVE_INFINITY:Math.max(0,A.durationMs-50),L=Math.min(I,Math.max(0,A.milliseconds+O)),T=Wg(L);return{evidence_id:`${b}:${A.episode}:${T}`,episode:A.episode,episode_id:A.episodeId,scene_id:A.sceneId,timestamp:T,offset_ms:O,selection:A.selection,source_sha256:A.sourceSha256,source_path:A.sourcePath,frame_path:`evidence/frames/${S.actor_id}/${_.state_id}/ep_${String(A.episode).padStart(3,"0")}_${Xg(T)}.jpg`,frame_status:"pending"}}).filter((O,I,L)=>L.findIndex(T=>T.timestamp===O.timestamp)===I);return[{evidence_id:b,asset_kind:"actor",actor_id:S.actor_id,actor_name:S.actor_name,state_id:_.state_id,state_name:_.state_name,samples:U}]}).sort((g,w)=>u(g.actor_id,w.actor_id)||g.state_name.localeCompare(w.state_name,"zh-CN")),m=[...p.entries()].flatMap(([g,w])=>{let y=c.get(g),x=ph(w,"identityScore",f,uI,lI);if(!y||x.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:x.map(_=>({evidence_id:`${S}:${_.episode}:${_.timestamp}`,episode:_.episode,episode_id:_.episodeId,scene_id:_.sceneId,timestamp:_.timestamp,offset_ms:0,selection:_.selection,source_sha256:_.sourceSha256,source_path:_.sourcePath,frame_path:`evidence/frames/${y.actor_id}/identity/ep_${String(_.episode).padStart(3,"0")}_${Xg(_.timestamp)}.jpg`,frame_status:"pending"}))}]}).sort((g,w)=>u(g.actor_id,w.actor_id));return{version:2,source_sha256:i,items:h,identities:m}}function lh(e){return sh(e)}function uh(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 Oa from"node:path";function mh(e){return Oa.extname(e).toLowerCase()}function xI(e){return Zd[mh(e)]??"application/octet-stream"}function fh(e,t){return new E(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 Bp(e,t){return{episode:t,path:e,ext:mh(e),mime:xI(e)}}function va(e){if(e.kind!=="video-file"&&e.kind!=="video-directory")throw new E("Expected video source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});if(e.kind==="video-file")return[Bp(e.path,1)];let t=e.files,n=t.map(_a),o=n.filter(r=>r!==null);if(o.length===0)return t.map((r,s)=>Bp(r,s+1));if(o.length!==t.length){let r=t.filter((s,c)=>n[c]===null).map(s=>Oa.basename(s));throw fh("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 fh("Two episode files resolve to the same number.",[`duplicate episode: ${r}`]);i.add(r)}return t.map((r,s)=>Bp(r,n[s])).sort((r,s)=>r.episode-s.episode)}import*as gh from"node:fs";import*as hh from"node:path";function yh(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=hh.resolve(r.path),c=gh.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:nc(s);return{episode:r.episode,path:s,ext:r.ext,mime:r.mime,sha256:u,size_bytes:a,mtime_ms:d}})}function Ra(e){return he(JSON.stringify(e.map(t=>({episode:t.episode,ext:t.ext,mime:t.mime,sha256:t.sha256}))))}import{spawn as _I}from"node:child_process";import*as ut from"node:fs";import*as wh from"node:path";var EI=20*1024*1024,SI="scale='if(gt(a,1),min(1280,iw),-2)':'if(gt(a,1),-2,min(1280,ih))'";function II(e,t){return["-y","-loglevel","error","-i",e,"-vf",SI,"-c:v","libx264","-preset","medium","-crf","27","-pix_fmt","yuv420p","-c:a","aac","-b:a","96k","-movflags","+faststart","-f","mp4",t]}function AI(e,t,n){return new Promise((o,i)=>{if(n?.aborted){i(new Error("aborted"));return}let r=_I("ffmpeg",II(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 xh(e,t,n,o){if(ut.existsSync(t)&&(ut.statSync(t).size??0)>0)return{path:t,mime:"video/mp4",transcoded:!0};let i=0;try{i=ut.statSync(e).size}catch{}if(i>0&&i<=EI)return{path:e,mime:n,transcoded:!1,note:`already ${(i/1024/1024).toFixed(1)}MB (\u226420MB)`};let r=`${t}.part`;try{if(ut.mkdirSync(wh.dirname(t),{recursive:!0}),ut.rmSync(r,{force:!0}),await AI(e,r,o),!ut.existsSync(r)||ut.statSync(r).size===0)throw new Error("ffmpeg produced no output");return ut.renameSync(r,t),{path:t,mime:"video/mp4",transcoded:!0}}catch(s){try{ut.rmSync(r,{force:!0}),ut.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 kI}from"node:child_process";import*as Be from"node:fs";import*as _h from"node:path";var bI="scale='if(gt(a,1),min(960,iw),-2)':'if(gt(a,1),-2,min(960,ih))'",OI=4;function vI(e){let t=lh(e);return t===null?null:(t/1e3).toFixed(3)}var RI=async(e,t,n,o)=>{if(o?.aborted)throw new Error("aborted");let i=vI(t);if(i===null)return{ok:!1,error:"invalid timestamp"};try{if(!Be.existsSync(e)||Be.statSync(e).size===0)return{ok:!1,error:"source video is unavailable or empty"}}catch{return{ok:!1,error:"source video is unavailable"}}Be.mkdirSync(_h.dirname(n),{recursive:!0});let r=`${n}.part`;return Be.rmSync(r,{force:!0}),new Promise((s,c)=>{let a=kI("ffmpeg",["-y","-loglevel","error","-ss",i,"-i",e,"-frames:v","1","-vf",bI,"-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),Be.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){Be.rmSync(r,{force:!0}),c(new Error("aborted"));return}if(p===0&&Be.existsSync(r)&&Be.statSync(r).size>0){Be.renameSync(r,n),s({ok:!0});return}Be.rmSync(r,{force:!0}),s({ok:!1,error:`frame extraction failed (exit ${p??"unknown"})`})})})};function MI(e){let{source_path:t,...n}=e;return n}async function Ma(e,t,n,o=RI,i={}){let r=i.reuseExistingFrames!==!1,s=[...t.items.flatMap(h=>h.samples),...(t.identities??[]).flatMap(h=>h.samples)],c=new Map,a=0,d=async()=>{for(;;){let h=a;if(a+=1,h>=s.length)return;if(n?.aborted)throw new Error("aborted");let m=s[h],g=e.path(m.frame_path),w;r&&Be.existsSync(g)&&Be.statSync(g).size>0?w={ok:!0}:(Be.rmSync(g,{force:!0}),w=await o(m.source_path,m.timestamp,g,n)),c.set(m,MI({...m,frame_status:w.ok?"ready":"unavailable",...w.error?{error:w.error}:{}}))}};await Promise.all(Array.from({length:Math.min(OI,s.length)},()=>d()));let p=h=>h.map(m=>c.get(m)),l=t.items.map(h=>({...h,samples:p(h.samples)})),f=(t.identities??[]).map(h=>({...h,samples:p(h.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 h=e.readJson("evidence/state-evidence.json"),m=g=>JSON.stringify({version:g.version,source_sha256:g.source_sha256,items:g.items,identities:g.identities??[]});if(m(h)===m(u))return h}catch{}return e.writeJson("evidence/state-evidence.json",u),u}var le=cn,LI=le(60);function NI(e,t){let n=le,o=t[n(106)]()?n(86)+t+`
262
+ `:n(110);return n(47)+e+n(36)+o}function Kp(e,t){let n=le;return new E(e,{exitCode:me,errorCode:n(119),hint:n(113),data:{actual:t}})}var jp=e=>{let t=le;return typeof e===t(32)?e[t(33)](/\u0000/g,""):Array[t(70)](e)?e[t(65)](jp):ft(e)?Object[t(101)](Object[t(18)](e)[t(65)](([n,o])=>[n,jp(o)])):e},ft=e=>typeof e===le(46)&&e!==null&&!Array[le(70)](e);function zp(){let e=["C2v0","CM9Szq","Aw5JBhvKzxm","ywrKx3jLy29NBML0Aw9Ux2fUy2HVCNm","C3rYAw5NAwz5","Bg9JyxrPB24","ywLzwxG","CMvJB2DUAxrPB25Fyw5JAg9YCW","zw5YAwnO","AwrLBNrPDhLFChjVzMLSzq","z2vUzxjHDgu","BMv3x2vUDgL0AwvZ","yw5JAg9YCW","igfUy2HVCNmGC3rPBgWGAgf2zsbUBYb0Aw1LC3rHBxaGywz0zxiGmYbYzxrYAwvZlG","B3bLBMvK","DgHPBMS","CMvNAxn0CNLFzgvSDge","zgvZy3jPChrPB24","zw50CMLLCW","y2fUB25Py2fSAxPL","tefztLm","z2v0","y2HHCMfJDgvYCW","BgvUz3rO","DgLTzxn0yw1Wx21PC3nPBMC","y2fUB25Py2fS","DgLTzq","ywrK","B3bLBL90AhjLywrZ","CgfYC2u","BwLTzq","zMLSDgvY","C3rYAw5N","CMvWBgfJzq","AwrLBNrPDhLFChjVzMLSzv9WyxrJAa","DMfSDwvZ","ioMBHU+8MUwVUEEfP+ACRoMBHUwoN+INHUMIKE+8JoAmIEACRos7U+wkOEwUMUs5IEEAHcbku09oioE7K+AEHoI/LowBNUs4Gos4QIbku09oiowVUEIXOEoaGUwpQUI/LowBNIbku09oioACRoI6Q++8Jos4JEIMGEI+K+whUUINO+MhIUoaGEwjJEIOGoAiLIbnyxjRzg93BIdKU6pNOihLNzFJGijZy2vUzxmG6ycq5zY66kAg55Uw5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44cbChjVChmG5zkmihn0yxrL77Ym5BM255sOihnOB3rZioAyJUEHRUIsMEwKQUwLH+w8GowNI+oaGEwiH+AnOUwsJoE7K+ADN+oaGG","C29Tzq","ywn0B3i","BM9YBwfSAxPL","Cgf0Aa","BwfW","zMXHDe1HCa","whbvAKe","sw5ZCgvJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbPBMDLC3qGDg8GCMvZDw1LlG","ywXPyxnLCW","AxnbCNjHEq","rvHms2W","oIbZzxjPywWGB3v0Chv0ihbYB2r1y2vKig5VihnJzw5LCW","ywrKx2fSAwfZzxm","Aw1WB3j0yw5Jzq","cGRKUiRMRkhOVPpLH7RMNiKG","ChjVChm","DuH1qwG","ywn0","tKzd","C29YDa","zMfJzv9ZAgfWzq","AgfZ","BM9Zzq","y29UDgvUDa","BMfTzq","pt09pt09pt09psdLT7lNN6xORR7LRPRVViJLIldKUiRKUidPM4BKUlRMRAlVViZOP4tOJipLKi3KU6xMRAtKUlRLH4BVViKGpt09pt09pt09pqO","C2TPBL9Mzwf0DxjLCW","uLPSD0u","zxzPzgvUy2u","xsaO","DMLZDwfS","yNvPBgq","C2HVDhm","zxbPC29Kzsa","CgvYC2LZDgvUDf9TyxjRCW","44cc6k+36yEn5PAW6kEc55Yl5B2t5yMn6zUg77Ym5lI65Q+p5lIa5P2HihnOB3rZiowsJcb2B2LJzxmG5AgR5yAz55YF5A6E6lw354k5ihrZ77Yitu06u1pVViNVViZKUi3LVPFNVlRLPlhJGihNLzNNQBRMIjBLOASGBNvSBo+8M+I/LowBNUwUJoAvTcbku09o77Ym5lIn6kAb5y+Q6l+u5zUE5l+U6kgL5A2x5Q6144cc","ChjVDMLZAw9UywW","oIbZzxjPywWGB3v0Chv0ihrVBYbZAg9YDcaOzMLUAxnOuMvHC29Upq","ywrKx3n0yxrLCW","rxbPC29Kzsa","zNjVBuvUDhjPzxm","C3LUB3bZAxm","ue9tsvrjvKvFsu5gsu5jvfK","weLmzNa","rMHHqK0","DhjPBq","AgfPCG","zMvHDhvYzwq","y2XVC2vK","77Yi6l+z5PIV56YS5lIa6zUg77Ym5PQc5PEG5BEY55+L6k6+5A6A44cc77YjcG","y2fTzxjH","yNjVD3nFzxLLCW","sw5ZCgvJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbGC2nYAxb0y3rSigLUz2vZDgaGDg8GCMvZDw1LlG","ChvZAa","A2v5CW","CMvM","CgfYzw50Agv0AwnHBa","BgvUz3rOoIa","su5hrvnux1zjrevpx1nfuKLbtf9gquLmruq","AxngAw5PDgu","DM9Py2vZ","oIbZzxjPywWGB3v0Chv0ihDHCYbUB3qGDMfSAwqGsLnptIaOzMLUAxnOuMvHC29Upq","Dgv4Da","zNjVBv9Uyw1L","C3rHDgvZ","Dg9ju09tDhjPBMC","C2nLBMvZ","Bw91DgG","su5hrvnux1zjrevpx1rjtuvtvefnuf9nsvntsu5h","C2nLBMvZwW"];return zp=function(){return e},zp()}var X=e=>typeof e===le(32)?e[le(106)]():"",Ze=e=>Array[le(70)](e)?e:[],Ah=e=>{let t=le,n=X(e);return n?n[t(59)](/[((//,,、]/)[0][t(106)]():""},UI=e=>[...new Set(Ze(e)[le(65)](Ah)[le(31)](Boolean))],Eh=e=>{let t=le,n=[];for(let o of Ze(e))if(t(20)===t(20)){if(!ft(o))continue;let i=Ah(o[t(85)]);if(!i)continue;let r=X(o[t(17)]),s=n[t(58)](c=>c[t(85)]===i);s?!s[t(17)]&&r&&(s[t(17)]=r):n[t(114)]({name:i,description:r})}else throw _0xea1873(t(94)+_0x26d9eb+t(122)+_0x40ae4d[t(40)]+")",[_0x54b3bb[t(42)](0,200)]);return n},CI=[le(37),le(56),le(81),le(112),le(83),le(128),le(87),le(107),le(92),le(52)],Sh=e=>{let t=le;if(!ft(e))return;let n={apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:Ze(e[t(95)])[t(65)](X)[t(31)](Boolean),voice:""};for(let o of CI)n[o]=X(e[o]);return n},Ih=e=>{let t=le;if(!e)return Number[t(103)];let n=e[t(59)](":")[t(65)](Number);return n[t(61)](o=>!Number[t(120)](o))?Number[t(103)]:n[t(23)]===2?n[0]*60+n[1]:n[t(23)]===3?n[0]*3600+n[1]*60+n[2]:Number[t(103)]},PI=(e,t)=>{let n=le;return e?t?e[n(33)](/[。!?;]+$/,"")+"\u3002"+t:e:t};function cn(e,t){e=e-0;let n=zp(),o=n[e];if(cn.yxMOYo===void 0){var i=function(c){let a="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=c.charAt(h++);~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.DlFVxD=i,cn.iMIPil={},cn.yxMOYo=!0}let r=n[0];cn.ISLRJj!==r&&(cn.iMIPil={},cn.ISLRJj=r);let s=cn.iMIPil[e];return s===void 0?(o=cn.DlFVxD(o),cn.iMIPil[e]=o):o=s,o}function TI(e){let t=le,n={synopsis:"",scenes:[],registry_delta:{new_entities:[],enrich:[],canonicalize:[]},open_threads:{opened:[],closed:[]}};if(!ft(e))return n;n[t(102)]=X(e[t(102)]);for(let r of Ze(e[t(127)])){if(!ft(r))continue;let s={},c=X(r[t(41)]);c&&(s[t(41)]=c);let a=xo(r[t(26)]);a&&(s[t(26)]=a);let d=new Map;for(let g of Ze(r[t(22)])){if(t(67)!==t(67))throw new _0x25b22d(t(100)+_0x39f21e+": "+_0x1bf283[t(23)]+t(13),{exitCode:_0x26902a,errorCode:t(129),hint:t(68),data:{actual:_0x36fc5d}});{if(!ft(g))continue;let w=X(g[t(85)]);if(!w||st(w))continue;let y=d[t(21)](w)??{name:w,states:[]};for(let x of UI(g[t(125)]))if(t(71)===t(71))y[t(125)][t(2)](x)||y[t(125)][t(114)](x);else{if(!_0x279b30)return _0x499743[t(103)];let S=_0x3e9bd8[t(59)](":")[t(65)](_0xbf8c);return S[t(61)](_=>!_0x2242ca[t(120)](_))?_0x4255ff[t(103)]:S[t(23)]===2?S[0]*60+S[1]:S[t(23)]===3?S[0]*3600+S[1]*60+S[2]:_0x3f6179[t(103)]}d[t(0)](w,y)}}let p=[],l=new Set;for(let g of Ze(r[t(76)])[t(65)](X)[t(31)](Boolean)){let w=g[t(63)](t(79))[t(33)](/\s+/g," ")[t(106)]();!w||l[t(82)](w)||(l[t(27)](w),p[t(114)](g[t(106)]()))}let f=[];for(let g of Ze(r[t(93)])){if(!ft(g))continue;let w=PI(X(g[t(111)]),X(g[t(91)]));if(!w)continue;let y={kind:t(78),content:w},x=Fi(g.ts);x&&(y.ts=x),f[t(114)](y)}for(let g of Ze(r[t(121)])){if(!ft(g))continue;let w=X(g[t(55)]);if(w!==t(48)&&w!==t(15))continue;let y=X(g[t(84)]);if(!y)continue;let x={kind:w,content:y},S=X(g[t(49)]);S&&(x[t(49)]=S);let _=X(g[t(117)]);_&&(x[t(117)]=_);let A=Fi(g.ts);A&&(x.ts=A),f[t(114)](x)}f[t(80)]((g,w)=>{let y=t,x=Ih(g.ts)-Ih(w.ts);return x!==0?x:g[y(55)]===y(78)&&w[y(55)]!==y(78)?-1:g[y(55)]!==y(78)&&w[y(55)]===y(78)?1:0});let u={environment:s,characters:[...d[t(35)]()],props:p,anchors:f},h=X(r[t(57)]);h&&(u[t(57)]=h);let m=X(r[t(5)]);m&&(u[t(5)]=m),n[t(127)][t(114)](u)}let o=ft(e[t(16)])?e[t(16)]:{};for(let r of Ze(o[t(11)])){if(!ft(r))continue;let s=X(r[t(85)]),c=X(r[t(55)]);if(!s||c!==t(62)&&c!==t(5)&&c!==t(45)||c===t(62)&&st(s))continue;let a={name:s,kind:c,status:X(r[t(39)])===t(97)?t(97):t(25),importance:X(r[t(74)])===t(53)?t(53):t(108)},d=Ze(r[t(7)])[t(65)](X)[t(31)](Boolean);d[t(23)]&&(a[t(7)]=d);let p=Sh(r[t(9)]);p&&(a[t(9)]=p);let l=X(r[t(43)]);l&&(a[t(43)]=l);let f=X(r[t(1)]);f&&(a[t(1)]=f);let u=Eh(r[t(125)]);u[t(23)]&&(a[t(125)]=u);let h=Ze(r[t(69)])[t(65)](X)[t(31)](Boolean);h[t(23)]&&(a[t(69)]=h),n[t(16)][t(11)][t(114)](a)}for(let r of Ze(o[t(8)]))if(t(6)===t(6)){if(!ft(r))continue;let s=X(r[t(85)]);if(!s)continue;let c={name:s},a=Ze(r[t(3)])[t(65)](X)[t(31)](Boolean);a[t(23)]&&(c[t(3)]=a);let d=Sh(r[t(34)]);d&&(c[t(34)]=d);let p=X(r[t(43)]);p&&(c[t(43)]=p);let l=X(r[t(1)]);l&&(c[t(1)]=l);let f=Ze(r[t(73)])[t(65)](X)[t(31)](Boolean);f[t(23)]&&(c[t(73)]=f);let u=Eh(r[t(99)]);u[t(23)]&&(c[t(99)]=u),Object[t(115)](c)[t(23)]>1&&n[t(16)][t(8)][t(114)](c)}else return _0x150727?_0x422014?_0x1f4862[t(33)](/[。!?;]+$/,"")+"\u3002"+_0x2651c7:_0x44d23d:_0x1c02e9;for(let r of Ze(o[t(19)])){if(!ft(r))continue;let s=X(r[t(124)]),c=X(r[t(50)]);s&&c&&n[t(16)][t(19)][t(114)]({from_name:s,canonical_name:c,evidence:X(r[t(89)])})}let i=ft(e[t(28)])?e[t(28)]:{};for(let r of Ze(i[t(14)])){if(!ft(r))continue;let s=X(r[t(123)]);s&&n[t(28)][t(14)][t(114)]({text:s})}for(let r of Ze(i[t(109)])){if(!ft(r))continue;let s=X(r[t(116)]);s&&n[t(28)][t(109)][t(114)]({ref:s})}return n}async function kh(e,t,n,o,i,r,s,c){let a=le,d="";for(let p=0;;p++)if(a(77)===a(88))_0x29fde1[a(125)][a(2)](_0xa46e54)||_0x28a8c2[a(125)][a(114)](_0x480bab);else{let l=await e[a(10)]({media:t,system:LI,user:NI(n,o+d),fps:i,responseJsonSchema:tg,...s?{localPath:s[a(64)],localMime:s[a(30)]}:{},...r?{signal:r}:{}}),f=l[a(123)][a(106)]();if(f[a(23)]<40)throw Kp(a(94)+n+a(98)+l[a(40)]+")",[a(118)+f[a(23)]]);let u;try{a(104)!==a(104)?_0x5dc535[a(114)]({name:_0x101a20,description:_0x8301e3}):u=JSON[a(29)](f)}catch{throw Kp(a(94)+n+a(122)+l[a(40)]+")",[f[a(42)](0,200)])}let h=jp(u),m=TI(h);if(m[a(127)][a(23)]===0)throw Kp(a(94)+n+a(72),[f[a(42)](0,200)]);let g=m[a(127)][a(66)]((y,x)=>y[a(12)][a(66)]((S,_)=>S.ts?[]:[a(130)+x+a(51)+_+a(90)+S[a(55)]+")"]));if(g[a(23)]>0){if(c?.({event:a(24),at:new Date()[a(126)](),episode:n,attempt:p+1,missing_count:g[a(23)],missing_paths:g,retries_exhausted:p===3}),p===3){if(a(44)!==a(105))throw new E(a(100)+n+": "+g[a(23)]+a(13),{exitCode:me,errorCode:a(129),hint:a(68),data:{actual:g}});{let y=_0x414037[a(106)]()?a(86)+_0x336d80+`
263
+ `:a(110);return a(47)+_0x1bbdb7+a(36)+y}}d=a(75)+g[a(23)]+a(38)+g[a(54)]("\u3001")+a(96);continue}return{md:JSON[a(4)](h,null,2),output:m}}}function La(e){return new E("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 VI(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=zr(t.failure);if(!n)return null;let o=[];for(let i of t.attempts){let r=zr(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 Hp(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 La("root must be an object");let n=t;if(n.schema_version!==1||!Array.isArray(n.episodes))throw La("schema_version must be 1 and episodes must be an array");let o=[],i=new Set;for(let r of n.episodes){let s=VI(r);if(!s)throw La("one or more episode records are malformed");if(i.has(s.episode))throw La(`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 bh(e,t){e.writeJson("skipped.json",t)}function Na(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 E("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 $I(e){return{episode:e,synopsis:"",scenes:[],actors:[],locations:[],props:[],speakers:[],actorStates:[],locationStates:[],propStates:[]}}function Ua(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($I(s.episode))}return r}function Fr(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;Ug(t,i),e.writeJson("context.json",t),e.clearError(`ep/ep_${String(i).padStart(3,"0")}.error.json`)}return t}function Oh(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 Yr="19",DI=new Set([Yr]),qi=e=>String(e).padStart(3,"0"),Qp=2;function Rh(e){try{return dn.statSync(e).size}catch{return 0}}function GI(e,t){let n=Rh(e);if(!(n<md))throw new E(`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 ${md} bytes after ingest transcoding`],actual:[`${n} bytes`]}})}function vh(e,t){try{let n=t.uploadBytes?(t.uploadBytes/1024/1024).toFixed(1):"?",o=JSON.stringify({...t,uploadMB:n,at:new Date().toISOString()})+`
264
+ `;dn.appendFileSync(e.path("timing.jsonl"),o)}catch{}}function Mh(e){return new E("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 Fp(e){if(!e.has("manifest.json"))return null;let t=e.readJson("manifest.json");if(!t.pipeline_version||!DI.has(t.pipeline_version))throw new E("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 ${Yr}`]}});return e.readJson("manifest.json")}function Yp(e,t){if(t.pipeline_version===Yr)return t;let n={...t,pipeline_version:Yr,updated:new Date().toISOString()};return e.writeJson("manifest.json",n),n}function JI(e,t,n){if(e&&e.source.kind!==t)throw Mh(`source kind changed from ${e.source.kind} to ${t}`)}function BI(e,t,n,o){if(t){let i=Fg(t.episodes,n);if(i.kind==="incompatible")throw Mh(i.reason)}if(o){dn.rmSync(e.path("ep"),{recursive:!0,force:!0}),dn.rmSync(e.path("cache"),{recursive:!0,force:!0}),dn.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"])dn.rmSync(e.path(i),{force:!0})}}function KI(e,t){return e.map(n=>{let o=structuredClone(n);for(let i of o.actors)i.name=Yi(i.name,t)??i.name;for(let i of o.scenes){for(let c of i.characters)c.name=Yi(c.name,t)??c.name;i.location&&(i.location=Yi(i.location,t)??i.location);let r=[],s=new Set;for(let c of i.props){let a=(Yi(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=Yi(c.speaker,t)}return o})}function jI(e,t){let n=t.slice(0,8).map(o=>`- ${o.path}: ${o.message}`).join(`
263
265
  `);return`${e}
264
266
 
265
267
  ========== \u4E0A\u4E00\u6B21\u8F93\u51FA\u7684\u6574\u5408\u6821\u9A8C\u53CD\u9988 ==========
266
268
  \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
267
269
  ${n}
268
- \u8BF7\u91CD\u65B0\u89C2\u770B\u672C\u96C6\u5E76\u8FD4\u56DE\u5B8C\u6574 JSON\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 Zg(e,t,n,o,i=[]){let r=uo(t.registry),s=sI(e,r),c=hg(s,n),a=Zs(c,t,"video",o);if(!a.scriptV4)return a;let{scriptV4:d,initial:p,idMap:l,identityMap:f}=a;Qg(d,i);let u=Me(d),g=[...d.actors.map((h,w)=>({asset:h,path:`$.actors[${w}]`})),...d.locations.map((h,w)=>({asset:h,path:`$.locations[${w}]`})),...d.props.map((h,w)=>({asset:h,path:`$.props[${w}]`}))].flatMap(({asset:h,path:w})=>[...h.description.trim()?[]:[{code:"video_asset_description_missing",path:`${w}.description`,message:"video asset needs a source-grounded description"}],...h.states.flatMap((y,E)=>y.description.trim()?[]:[{code:"video_state_description_missing",path:`${w}.states[${E}].description`,message:"video asset state needs a source-grounded visual description"}])]),m={...u,warnings:[...u.warnings,...bi(d),...g,...i.map(h=>({code:"episode_skipped",path:`$.episodes[${h.episode-1}]`,message:`Episode ${h.episode} was manually skipped: ${h.reason}`}))]};return{initial:p,final:d,idMap:l,validation:m,identityMap:f}}function ga(e,t,n,o,i,r){let s=Zg(ma(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:b,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 cI(e,t,n,o,i,r,s){return la(e,aa(t,n,o,i,r),s)}async function dI(e){let t=un(e.sourcePath);if(t.kind!=="video-file"&&t.kind!=="video-directory")throw new x("runVideoIngest requires a video source.",{exitCode:b,errorCode:"INGEST_WRONG_PIPELINE"});let n=[...da(t)].sort((h,w)=>h.episode-w.episode),o=sa(n);if(o)throw new x("Video episodes must form one continuous sequence starting at episode 1.",{exitCode:b,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 st(e.workspacePath);d.ensure();let p=Ap(d),l=Vi.resolve(t.path);iI(p,t.kind,l);let f=Vg(n,p?.episodes??[],p?.updated);rI(d,p,f,r);let u={version:2,pipeline_version:Pr,updated:new Date().toISOString(),source:{kind:t.kind,path:l,sha256:pa(f)},episodes:f,fps:i,skips:r?[]:p?.skips??[]};d.writeJson("manifest.json",u);let g=new po(d,e.executor),m="failed";try{let h=null,w=ha(e.sourcePath),y=!r&&d.has("context.json")?d.readJson("context.json"):lo(),E={schema_version:1,episodes:u.skips??[]};fa(E.episodes,f),r||Ur(d,y,E.episodes);let I=new Set(E.episodes.map(K=>K.episode)),_=!r&&d.has("v4_identity_map.json")?d.readJson("v4_identity_map.json"):ao(),A=0,k=0;for(let K of n){let ve=`ep/ep_${Ti(K.episode)}.json`;if(!r&&I.has(K.episode)&&K.episode<=y.lastEpisode)continue;if(!r&&d.has(ve)&&K.episode<=y.lastEpisode){A++,e.executor.recordReuse("ingest.video-serial");let wt=Date.now();g.flush({scope:{kind:"episode",episode:K.episode},status:"reused",startedAtMs:wt,endedAtMs:wt});continue}if(s&&k>=1)break;let Ze=qs(y);d.writeText(`ep/ep_${Ti(K.episode)}.context.md`,Ze);let N,ie,ye,dt,en=Date.now(),tt={episode:K.episode,uploadMode:c,status:"succeeded",totalMs:0},Hr="transcode";try{let wt=Date.now(),pt=await Dg(K.path,d.path(`cache/ep_${Ti(K.episode)}.mp4`),K.mime,a);tt.transcodeMs=Date.now()-wt,tt.uploadBytes=Yg(pt.path),tt.transcoded=pt.transcoded,pt.note&&(tt.note=pt.note),c==="base64"&&oI(pt.path,K.episode),Hr="upload",h??=e.executor.videoPort("ingest.video-serial");let Ma=Date.now(),$n=await h.prepare(pt.path,pt.mime,c,a);tt.uploadMs=Date.now()-Ma;try{Hr="generate";let La=Date.now(),iy=ma(d,n,y.lastEpisode,E.episodes),Na=Ze;for(let Qr=1;Qr<=Ip;Qr++){let Fr;try{Fr=await zg(h,$n,K.episode,Na,i,a,{path:pt.path,mime:pt.mime},Tt=>Xt.appendFileSync(d.path("ingest-validation.jsonl"),JSON.stringify(Tt)+`
269
- `))}catch(Tt){if(!(Tt instanceof x)||Tt.errorCode!=="INGEST_VIDEO_SERIAL_FAILED"||Qr===Ip)throw Tt;Na=`${Ze}
270
+ \u8BF7\u91CD\u65B0\u89C2\u770B\u672C\u96C6\u5E76\u8FD4\u56DE\u5B8C\u6574 JSON\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 Lh(e,t,n,o,i=[]){let r=ko(t.registry),s=KI(e,r),c=qg(s,n),a=wa(c,t,"video",o);if(!a.scriptV4)return a;let{scriptV4:d,initial:p,idMap:l,identityMap:f}=a;Oh(d,i);let u=Le(d),h=[...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,x)=>y.description.trim()?[]:[{code:"video_state_description_missing",path:`${w}.states[${x}].description`,message:"video asset state needs a source-grounded visual description"}])]),m={...u,warnings:[...u.warnings,...Ji(d),...h,...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:m,identityMap:f}}function Ca(e,t,n,o,i,r){let s=Lh(Ua(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 E("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 zI(e,t,n,o,i,r,s){return Ma(e,ba(t,n,o,i,r),s)}async function HI(e){let t=Sn(e.sourcePath);if(t.kind!=="video-file"&&t.kind!=="video-directory")throw new E("runVideoIngest requires a video source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=[...va(t)].sort((g,w)=>g.episode-w.episode),o=ka(n);if(o)throw new E("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 lt(e.workspacePath);d.ensure();let p=Fp(d),l=Zi.resolve(t.path);JI(p,t.kind,l);let f=yh(n,p?.episodes??[],p?.updated);BI(d,p,f,r);let u={version:2,pipeline_version:Yr,updated:new Date().toISOString(),source:{kind:t.kind,path:l,sha256:Ra(f)},episodes:f,fps:i,skips:r?[]:p?.skips??[]};d.writeJson("manifest.json",u);let h=new Io(d,e.executor),m="failed";try{let g=null,w=Pa(e.sourcePath),y=!r&&d.has("context.json")?d.readJson("context.json"):Ao(),x={schema_version:1,episodes:u.skips??[]};Na(x.episodes,f),r||Fr(d,y,x.episodes);let S=new Set(x.episodes.map(K=>K.episode)),_=!r&&d.has("v4_identity_map.json")?d.readJson("v4_identity_map.json"):So(),A=0,b=0;for(let K of n){let Re=`ep/ep_${qi(K.episode)}.json`;if(!r&&S.has(K.episode)&&K.episode<=y.lastEpisode)continue;if(!r&&d.has(Re)&&K.episode<=y.lastEpisode){A++,e.executor.recordReuse("ingest.video-serial");let kt=Date.now();h.flush({scope:{kind:"episode",episode:K.episode},status:"reused",startedAtMs:kt,endedAtMs:kt});continue}if(s&&b>=1)break;let We=ya(y);d.writeText(`ep/ep_${qi(K.episode)}.context.md`,We);let N,ie,we,mt,pn=Date.now(),at={episode:K.episode,uploadMode:c,status:"succeeded",totalMs:0},as="transcode";try{let kt=Date.now(),gt=await xh(K.path,d.path(`cache/ep_${qi(K.episode)}.mp4`),K.mime,a);at.transcodeMs=Date.now()-kt,at.uploadBytes=Rh(gt.path),at.transcoded=gt.transcoded,gt.note&&(at.note=gt.note),c==="base64"&&GI(gt.path,K.episode),as="upload",g??=e.executor.videoPort("ingest.video-serial");let Ya=Date.now(),Zn=await g.prepare(gt.path,gt.mime,c,a);at.uploadMs=Date.now()-Ya;try{as="generate";let qa=Date.now(),Ty=Ua(d,n,y.lastEpisode,x.episodes),Za=We;for(let cs=1;cs<=Qp;cs++){let ds;try{ds=await kh(g,Zn,K.episode,Za,i,a,{path:gt.path,mime:gt.mime},jt=>dn.appendFileSync(d.path("ingest-validation.jsonl"),JSON.stringify(jt)+`
271
+ `))}catch(jt){if(!(jt instanceof E)||jt.errorCode!=="INGEST_VIDEO_SERIAL_FAILED"||cs===Qp)throw jt;Za=`${We}
270
272
 
271
- \u4E0A\u4E00\u6B21\u8F93\u51FA\u672A\u88AB\u63A5\u53D7\uFF0C\u4E5F\u672A\u63A8\u8FDB checkpoint\uFF1A${Tt.message}\u3002\u8BF7\u91CD\u65B0\u89C2\u770B\u5F53\u524D\u96C6\uFF0C\u53EA\u6309\u89C6\u9891\u4E8B\u5B9E\u8FD4\u56DE\u7B26\u5408 schema \u7684\u5B8C\u6574 JSON\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 il=Ng(Fr.output,K.episode),Ua=structuredClone(y);Ys(Ua,Fr.output,K.episode);let Yr=Zg([...iy,il],Ua,w,_,E.episodes.filter(Tt=>Tt.episode<=K.episode));if(Yr.validation.ok){N=Fr.md,ie=il,ye=Ua,dt=Yr;break}if(Hr="validation",Qr===Ip)throw new x("Final script.json failed validation after model correction.",{exitCode:b,errorCode:"INGEST_VALIDATION_FAILED",hint:"Rerun ingest to continue with the next configured model route.",data:{actual:Yr.validation.errors.slice(0,8).map(Tt=>`${Tt.path}: ${Tt.message}`)}});Na=aI(Ze,Yr.validation.errors)}tt.generateMs=Date.now()-La}finally{await h.release($n,a).catch(()=>{}),pt.transcoded&&Xt.rmSync(pt.path,{force:!0})}}catch(wt){let pt=Date.now();tt.status="failed",tt.totalMs=pt-en,Fg(d,tt),g.flush({scope:{kind:"episode",episode:K.episode},status:"failed",startedAtMs:en,endedAtMs:pt,stages:tt});let Ma=wt instanceof x&&wt.errorCode==="INGEST_VIDEO_SERIAL_FAILED"?"parse":Hr,$n=ia(wt,K.episode,Ma),La=tn($n.failure);throw d.writeJson(`ep/ep_${Ti(K.episode)}.error.json`,$n),d.writeJson("manifest.json",{...u,updated:$n.occurred_at,current_error:$n}),wt instanceof x&&(wt.errorCode==="INGEST_VIDEO_INLINE_TOO_LARGE"||wt.errorCode==="INGEST_VALIDATION_FAILED"||wt.errorCode==="INGEST_VIDEO_TIMESTAMP_MISSING")?wt:new x(`Episode ${K.episode} failed serial parse; later episodes depend on its context.`,{exitCode:b,errorCode:"INGEST_SERIAL_INCOMPLETE",hint:pg($n.failure),data:{actual:[La]}})}y=ye,k+=1,d.writeText(`ep/ep_${Ti(K.episode)}.md`,N),d.writeJson(ve,ie),d.writeJson("context.json",y),d.clearError(`ep/ep_${Ti(K.episode)}.error.json`);let ol=Date.now();tt.totalMs=ol-en,Fg(d,tt),g.flush({scope:{kind:"episode",episode:K.episode},status:"succeeded",startedAtMs:en,endedAtMs:ol,stages:tt}),_=dt.identityMap,d.writeJson("v4_identity_map.json",_),d.writeJson("script.json",dt.final)}let P=Math.min(y.lastEpisode,n.length),O=n.length-P,S=O===0,L=S?null:n[P]?.episode??null,T=ga(d,n.slice(0,P),y,w,_,E.episodes),{final:U,validation:R}=T,j=S?await cI(d,ma(d,n,y.lastEpisode,E.episodes),U,y,f,u.source.sha256,a):{items:[]},Z=j.items.flatMap(K=>K.samples),Oe=U;return m="succeeded",{workspacePath:d.root,episodes:n.length,processed:k,reused:A,skipped:E.episodes.length,skippedEpisodes:E.episodes.map(K=>K.episode),completed:P,remaining:O,complete:S,nextEpisode:L,uploadMode:c,assets:{actors:Oe.actors?.length??0,locations:Oe.locations?.length??0,props:Oe.props?.length??0},evidence:{states:j.items.length,samples:Z.length,ready:Z.filter(K=>K.frame_status==="ready").length},scriptPath:d.path("script.json"),validation:{ok:R.ok,errors:R.errors.length,warnings:R.warnings.length}}}finally{g.finish(m)}}async function Wg(e){return fo(e.workspacePath,()=>dI(e))}function ha(e){return Vi.basename(e,Vi.extname(e))||""}var $i=e=>e==null?"":String(e),Xg=(e,t)=>{let n=Number(e);return Number.isInteger(n)&&n>0?n:t},pI=["fps","video_provider","upload_mode","provider_base_url","provider_api_key","provider_api_key_env","provider_model","step"];function ho(e,t){return new x(e,{exitCode:b,errorCode:"INGEST_VIDEO_OPTION_INVALID",hint:"Use these options only with a video file or video episode directory.",data:{actual:t}})}function ya(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0}function Di(e,t,n){if(!ya(e,t))return;let o=$i(e[t]).trim();if(!o)throw ho(`${n} requires a non-empty value.`,[n]);return o}function lI(e){let t=Di(e,"upload_mode","--upload-mode");if(t!==void 0){if(t!=="file-api"&&t!=="base64")throw ho("Video upload mode must be file-api or base64.",[`--upload-mode ${t}`]);return t}}function uI(e){let t=Di(e,"video_provider","--video-provider");if(t!==void 0&&t!=="gemini"&&t!=="doubao")throw ho("Video provider must be gemini or doubao.",["--video-provider gemini|doubao"]);let n=ya(e,"provider_api_key"),o=ya(e,"provider_api_key_env");if(n&&o)throw ho("Provider API key options are mutually exclusive.",["--provider-api-key","--provider-api-key-env"]);let i=Di(e,"provider_base_url","--provider-base-url"),r=Di(e,"provider_api_key","--provider-api-key"),s=Di(e,"provider_api_key_env","--provider-api-key-env"),c=Di(e,"provider_model","--provider-model");if(s!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw ho("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 th(e,t=Ln){let n=$i(e.source_path).trim();if(!n)throw new x("ingest needs a source file or directory.",{exitCode:b,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=eh.resolve($i(e.workspace_path||"workspace")),i=un(n),r=pI.filter(d=>{let p=e[d];return typeof p=="boolean"?p:ya(e,d)});if(i.kind==="text"&&r.length>0)throw ho("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 ho("Video provider options cannot be used with PDF comics; select the comic model with --llm-config.",d);let p=t.createExecutor($i(e.llm_config).trim()||void 0),l=await fg({sourcePath:n,workspacePath:o,executor:p,force:!!e.force,step:!!e.step});return[{text:`workspace: ${l.workspace}
273
+ \u4E0A\u4E00\u6B21\u8F93\u51FA\u672A\u88AB\u63A5\u53D7\uFF0C\u4E5F\u672A\u63A8\u8FDB checkpoint\uFF1A${jt.message}\u3002\u8BF7\u91CD\u65B0\u89C2\u770B\u5F53\u524D\u96C6\uFF0C\u53EA\u6309\u89C6\u9891\u4E8B\u5B9E\u8FD4\u56DE\u7B26\u5408 schema \u7684\u5B8C\u6574 JSON\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 vl=uh(ds.output,K.episode),Wa=structuredClone(y);ha(Wa,ds.output,K.episode);let ps=Lh([...Ty,vl],Wa,w,_,x.episodes.filter(jt=>jt.episode<=K.episode));if(ps.validation.ok){N=ds.md,ie=vl,we=Wa,mt=ps;break}if(as="validation",cs===Qp)throw new E("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:ps.validation.errors.slice(0,8).map(jt=>`${jt.path}: ${jt.message}`)}});Za=jI(We,ps.validation.errors)}at.generateMs=Date.now()-qa}finally{await g.release(Zn,a).catch(()=>{}),gt.transcoded&&dn.rmSync(gt.path,{force:!0})}}catch(kt){let gt=Date.now();at.status="failed",at.totalMs=gt-pn,vh(d,at),h.flush({scope:{kind:"episode",episode:K.episode},status:"failed",startedAtMs:pn,endedAtMs:gt,stages:at});let Ya=kt instanceof E&&kt.errorCode==="INGEST_VIDEO_SERIAL_FAILED"?"parse":as,Zn=Ia(kt,K.episode,Ya),qa=ln(Zn.failure);throw d.writeJson(`ep/ep_${qi(K.episode)}.error.json`,Zn),d.writeJson("manifest.json",{...u,updated:Zn.occurred_at,current_error:Zn}),kt instanceof E&&(kt.errorCode==="INGEST_VIDEO_INLINE_TOO_LARGE"||kt.errorCode==="INGEST_VALIDATION_FAILED"||kt.errorCode==="INGEST_VIDEO_TIMESTAMP_MISSING")?kt:new E(`Episode ${K.episode} failed serial parse; later episodes depend on its context.`,{exitCode:k,errorCode:"INGEST_SERIAL_INCOMPLETE",hint:jg(Zn.failure),data:{actual:[qa]}})}y=we,b+=1,d.writeText(`ep/ep_${qi(K.episode)}.md`,N),d.writeJson(Re,ie),d.writeJson("context.json",y),d.clearError(`ep/ep_${qi(K.episode)}.error.json`);let Ol=Date.now();at.totalMs=Ol-pn,vh(d,at),h.flush({scope:{kind:"episode",episode:K.episode},status:"succeeded",startedAtMs:pn,endedAtMs:Ol,stages:at}),_=mt.identityMap,d.writeJson("v4_identity_map.json",_),d.writeJson("script.json",mt.final)}let U=Math.min(y.lastEpisode,n.length),O=n.length-U,I=O===0,L=I?null:n[U]?.episode??null,T=Ca(d,n.slice(0,U),y,w,_,x.episodes),{final:C,validation:R}=T,j=I?await zI(d,Ua(d,n,y.lastEpisode,x.episodes),C,y,f,u.source.sha256,a):{items:[]},Z=j.items.flatMap(K=>K.samples),ve=C;return m="succeeded",{workspacePath:d.root,episodes:n.length,processed:b,reused:A,skipped:x.episodes.length,skippedEpisodes:x.episodes.map(K=>K.episode),completed:U,remaining:O,complete:I,nextEpisode:L,uploadMode:c,assets:{actors:ve.actors?.length??0,locations:ve.locations?.length??0,props:ve.props?.length??0},evidence:{states:j.items.length,samples:Z.length,ready:Z.filter(K=>K.frame_status==="ready").length},scriptPath:d.path("script.json"),validation:{ok:R.ok,errors:R.errors.length,warnings:R.warnings.length}}}finally{h.finish(m)}}async function Nh(e){return bo(e.workspacePath,()=>HI(e))}function Pa(e){return Zi.basename(e,Zi.extname(e))||""}var Wi=e=>e==null?"":String(e),Uh=(e,t)=>{let n=Number(e);return Number.isInteger(n)&&n>0?n:t},QI=["fps","video_provider","upload_mode","provider_base_url","provider_api_key","provider_api_key_env","provider_model","step"];function Ro(e,t){return new E(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 Ta(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0}function Xi(e,t,n){if(!Ta(e,t))return;let o=Wi(e[t]).trim();if(!o)throw Ro(`${n} requires a non-empty value.`,[n]);return o}function FI(e){let t=Xi(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 YI(e){let t=Xi(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=Ta(e,"provider_api_key"),o=Ta(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=Xi(e,"provider_base_url","--provider-base-url"),r=Xi(e,"provider_api_key","--provider-api-key"),s=Xi(e,"provider_api_key_env","--provider-api-key-env"),c=Xi(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 Ph(e,t=zn){let n=Wi(e.source_path).trim();if(!n)throw new E("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=Ch.resolve(Wi(e.workspace_path||"workspace")),i=Sn(n),r=QI.filter(d=>{let p=e[d];return typeof p=="boolean"?p:Ta(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(Wi(e.llm_config).trim()||void 0),l=await Qg({sourcePath:n,workspacePath:o,executor:p,force:!!e.force,step:!!e.step});return[{text:`workspace: ${l.workspace}
272
274
  ${l.completed}/${l.episodes} chapters complete (${l.processed} processed / ${l.reused} reused) \u2192 ${l.script_path}
273
- assets: ${l.assets.actors} actors / ${l.assets.locations} locations / ${l.assets.props} props`,data:l},B]}if(i.kind!=="text"){let d=lI(e),p=uI(e),l=p?{videoProvider:p}:void 0,f=t.createExecutor($i(e.llm_config).trim()||void 0,l),u=f.route("ingest.video-serial"),g=d??u.videoUploadMode??"file-api";if(p?.provider==="doubao"&&g!=="file-api")throw ho("Doubao requires --upload-mode file-api.",["--upload-mode file-api"]);let m=await Wg({sourcePath:n,workspacePath:o,executor:f,fps:Xg(e.fps,3),force:!!e.force,step:!!e.step,uploadMode:g}),h=[`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`],w=[...f.usageEvents()].reverse().find(y=>y.task==="ingest.video-serial"&&y.status==="succeeded")??u;return[{text:h.join(`
274
- `),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:w.protocol,provider:w.provider,base_url:w.baseUrl,model:w.model},assets:m.assets}},B]}let s=t.createExecutor($i(e.llm_config).trim()||void 0),c=await Jm({sourcePath:n,workspacePath:o,executor:s,concurrency:Xg(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(`
275
- `),data:{workspace:c.workspacePath,script_path:c.scriptPath,records:c.records,chunks:c.chunks,assets:c.assets}},B]}import*as Ot from"node:fs";import*as vt from"node:path";var fI=e=>e==null?"":String(e);function nh(e){try{let t=JSON.parse(Ot.readFileSync(vt.join(e,"timings.json"),"utf-8"));return Tm(t,Date.now())}catch{return null}}function wa(e,t,n){let o=vt.join(e,t),i;try{i=Ot.readdirSync(o)}catch{return[]}return i.filter(r=>r.endsWith(n)).sort()}var mI=(e,t,n)=>wa(e,t,n).length,Rp=(e,t)=>Ot.existsSync(vt.join(e,t));function gI(e){try{return JSON.parse(Ot.readFileSync(vt.join(e,"manifest.json"),"utf-8"))}catch{return null}}function hI(e){try{let t=JSON.parse(Ot.readFileSync(vt.join(e,"validation.json"),"utf-8"));return{ok:!!t.ok,errors:t.errors?.length??0,warnings:t.warnings?.length??0}}catch{return null}}function bp(e,t,n){return{pass:e,unit:t,phase:e,attempts:[],...St({failure_type:"unknown",failure_code:"legacy_unclassified"},{retryable:e==="pass2",message:n})}}function yI(e,t,n){try{let o=JSON.parse(Ot.readFileSync(vt.join(e,t,`${n}.error.json`),"utf-8")),i=Lr(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"?bp(t,n,o.error):bp(t,n,"Error sidecar has an unsupported schema.")}catch{return bp(t,n,"Error sidecar is unreadable.")}}function wI(e,t,n=new Set){return wa(e,t,".error.json").map(o=>o.replace(/\.error\.json$/,"")).filter(o=>!n.has(o)).map(o=>yI(e,t,o))}function EI(e,t,n){let o=Lr(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 Op(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 _I(e){try{let t=JSON.parse(Ot.readFileSync(vt.join(e,"body.json"),"utf-8"));return Array.isArray(t.episodes)?t.episodes.length:0}catch{return 0}}function xI(e){try{let t=JSON.parse(Ot.readFileSync(vt.join(e,"script.json"),"utf-8"));return t.version===4&&Array.isArray(t.episodes)?t.episodes.length:null}catch{return null}}function SI(e,t,n){try{let o;return n==="comic"?o=JSON.parse(Ot.readFileSync(vt.join(e,"checkpoint.json"),"utf-8")).context:o=JSON.parse(Ot.readFileSync(vt.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 II(e,t){let n=t.chunks??0,o={total:n,done:wa(e,"pass2",".json").filter(a=>/^chunk_\d+\.json$/.test(a)).length,failed:mI(e,"pass2",".error.json")},i=_I(e),r=wa(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:Rp(e,"body.json")},{name:"serial",done:i>0&&r>=i,unit:s},{name:"govern",done:Rp(e,"script.json")}],units:o}}function AI(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&&xI(e)===o}],units:c,parsed:s}}function Cr(e){let t=vt.resolve(e),n=gI(t);if(!n)return{workspace:t,exists:!1,kind:null,state:"empty",phase:"none",passes:[],units:null,script:!1,validation:null,failure_summary:Op([]),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"?SI(t,i,o):0,s=o!=="text"&&r<i,c=o==="video"?n.skips??[]:[],a=new Set(c.map(_=>`ep_${String(_.episode).padStart(3,"0")}`)),d=o!=="text"&&r<i?EI(n,r,a):[],p=o!=="text"?AI(t,n,c,r,d.length):null,{passes:l,units:f}=o==="text"?II(t,n):p,u=o==="text"?wI(t,"pass2"):d;if(s){let _=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:Op(u),errors:u,updated:n.updated??null,timings:nh(t),completed:r,remaining:i-r,complete:!1,next_episode:r+1,parsed:p?.parsed??r,skipped:_.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=Rp(t,"script.json"),m=hI(t);m&&!m.ok&&u.push({pass:"finalize",unit:"script",phase:"validation",attempts:[],...St({failure_type:"validation",failure_code:"script_validation_failed"},{retryable:!1,message:`Script validation failed with ${m.errors} error(s).`})});let h,w=l.length>0&&l.every(_=>_.done);(o==="text"||w)&&g&&m?.ok?h="ready":u.length>0||m&&!m.ok?h="failed":h="incomplete";let y=l.find(_=>!_.done),E=h==="ready"?"done":y?y.name:"done",I=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(_=>_.episode<=f.done).length,skipped_episodes:c.map(_=>_.episode),has_skips:c.length>0,skips:c.map(_=>({episode:_.episode,skipped_at:_.skipped_at,reason:_.reason,failure_type:_.failure.failure_type,failure_code:_.failure.failure_code}))}:{};return{workspace:t,exists:!0,kind:o,state:h,phase:E,passes:l,units:f,script:g,validation:m,failure_summary:Op(u),errors:u,updated:n.updated??null,timings:nh(t),...I}}function kI(e){let t=`${e.done}/${e.total}`;return e.failed>0?`${t} (${e.failed} failed)`:t}function bI(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?kI(i.unit):i.done?"\u2713":"-"}`).join(" "),o=[t,n];if(e.timings&&o.push(OI(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 vp(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 OI(e){let t=[`elapsed ${vp(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(`~${vp(n.avgWindowMs)}/window`),n.etaMs!=null&&!e.done&&t.push(`eta ~${vp(n.etaMs)}`)),t.join(" \xB7 ")}function oh(e){let t=fI(e.workspace_path||"workspace"),n=Cr(t);return[{text:bI(n).join(`
276
- `),data:{status:n}},B]}import*as Ea from"node:path";function gn(e,t,n,o){return new x(e,{exitCode:b,errorCode:t,hint:n,data:{actual:o}})}function vI(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw gn("--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 RI(e,t,n){let o=new st(e);if(!o.has("manifest.json"))throw gn("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 gn("Only video ingest episodes can be skipped.","INGEST_SKIP_WRONG_PIPELINE","Use skip only with a video ingest workspace.",[e]);let r=Ap(o);if(!r)throw gn("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 gn("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=Sp(o);fa(c.episodes,r.episodes);let a=o.has("context.json")?o.readJson("context.json"):lo();if(c.episodes.find(w=>w.episode===t)){let w=kp(o,r);a=Ur(o,a,c.episodes);let y=o.has("v4_identity_map.json")?o.readJson("v4_identity_map.json"):ao();return ga(o,w.episodes,a,ha(w.source.path),y,c.episodes),!1}let p=a.lastEpisode+1;if(t!==p)throw gn("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 gn("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 gn("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=Lr(o.readJson(`${l}.error.json`));if(!f||f.unit.episode!==t)throw gn("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=kp(o,r),m=[...c.episodes,u];o.writeJson("manifest.json",{...g,updated:u.skipped_at,current_error:void 0,skips:m}),Hg(o,{schema_version:1,episodes:m}),a=Ur(o,a,m);let h=o.has("v4_identity_map.json")?o.readJson("v4_identity_map.json"):ao();return ga(o,g.episodes,a,ha(g.source.path),h,[...c.episodes,u]),!0}async function ih(e){let t=Ea.resolve(typeof e.workspace_path=="string"?e.workspace_path:"workspace"),n=vI(e.episode),o=typeof e.reason=="string"?e.reason.trim():"";if(!o)throw gn("--reason is required.","INGEST_SKIP_REASON_REQUIRED","Record why this episode cannot be parsed.",["--reason <text>"]);let i=await fo(t,()=>RI(t,n,o)),r=Cr(t),s=Sp(new st(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:Ea.join(t,"script.json")}},B]}import*as xa from"node:fs";import*as Yo from"node:path";import{spawnSync as MI}from"node:child_process";function _a(e,t,n,o){return new x(e,{exitCode:b,errorCode:t,hint:n,data:{actual:o}})}function LI(e){let t=da(un(e)),n=sa(t);if(n)throw _a("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=Yo.resolve(o.path),r=xa.statSync(i),s=r.size,c=Math.trunc(r.mtimeMs),a=MI("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:Ie(JSON.stringify({absolutePath:i,sizeBytes:s,mtimeMs:c})),size_bytes:s,mtime_ms:c,duration_ms:p}})}async function NI(e){let t=Yo.resolve(e.scriptPath),n=Yo.resolve(e.sourcePath),o=Yo.resolve(e.workspacePath),i=si(JSON.parse(xa.readFileSync(t,"utf-8"))),r=LI(n);if(r.length!==i.episodes.length)throw _a("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=pa(r),c=aa([],i,lo(),r,s),a=await fo(o,async()=>{let p=new st(o);return p.ensure(),la(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:Yo.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 rh(e){let t=Se(e),n=typeof e.source_path=="string"?e.source_path.trim():"",o=typeof e.workspace_path=="string"?e.workspace_path.trim():"";if(!n)throw _a("--source-path is required.","EVIDENCE_SOURCE_REQUIRED","Pass the linked source-video file or folder.",["--source-path <path>"]);if(!o)throw _a("--workspace-path is required.","EVIDENCE_WORKSPACE_REQUIRED","Pass the project workspace directory.",["--workspace-path <path>"]);let i=await NI({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 wo from"node:fs";import*as Sa from"node:path";var yt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Tn=e=>Array.isArray(e),Be=e=>typeof e=="string"?e:"",UI={interior:"\u5185",exterior:"\u5916"},PI={day:"\u65E5",night:"\u591C"},CI=e=>{let t=e.match(/(\d+)/);return t?Number(t[1]):0},TI=e=>{let t=e.match(/(\d+)/);return t?Number(t[1]):0};function Mp(e,t,n){let o=new Map;if(Tn(e))for(let i of e)yt(i)&&typeof i[t]=="string"&&o.set(i[t],Be(i[n]));return o}function VI(e,t){let n=new Map;if(Tn(e))for(let o of e){if(!yt(o)||typeof o[t]!="string")continue;let i=new Map;for(let r of Tn(o.states)?o.states:[])yt(r)&&typeof r.state_id=="string"&&i.set(r.state_id,Be(r.state_name));n.set(o[t],i)}return n}function $I(e,t){return yt(e)?typeof e.actor_id=="string"?t.get(e.actor_id)??e.actor_id:typeof e.kind=="string"?`${e.kind}${e.label?`:${Be(e.label)}`:""}`:"":""}function DI(e){let t=Mp(e.actors,"actor_id","actor_name"),n=Mp(e.locations,"location_id","location_name"),o=Mp(e.props,"prop_id","prop_name"),i=VI(e.actors,"actor_id"),r=(Tn(e.episodes)?e.episodes:[]).filter(yt).map(c=>({episode:CI(Be(c.episode_id)),synopsis:Be(c.synopsis),scenes:(Tn(c.scenes)?c.scenes:[]).filter(yt).map(a=>{let d=yt(a.location)?n.get(Be(a.location.location_id))??Be(a.location.location_id):"",p=[],l={};for(let g of Tn(a.actors)?a.actors:[]){if(!yt(g)||typeof g.actor_id!="string")continue;let m=t.get(g.actor_id)??g.actor_id;if(p.includes(m)||p.push(m),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[m]=w)}}let f=[];for(let g of Tn(a.props)?a.props:[])if(yt(g)&&typeof g.prop_id=="string"){let m=o.get(g.prop_id)??g.prop_id;f.includes(m)||f.push(m)}let u=yt(a.environment)?a.environment:{};return{scene_num:TI(Be(a.scene_id)),location_name:d,environment:{space:UI[Be(u.space)]??Be(u.space),time:PI[Be(u.time)]??Be(u.time)},actor_names:p,actor_states:l,prop_names:f,actions:(Tn(a.actions)?a.actions:[]).filter(yt).map(g=>({type:Be(g.type),content:Be(g.content),speaker:$I(g.speaker,t),emotion:typeof g.emotion=="string"?g.emotion:void 0,extend:yt(g.extend)&&typeof g.extend.timestamp=="string"?{timestamp:g.extend.timestamp}:void 0}))}})})),s=(Tn(e.actors)?e.actors:[]).filter(yt).map(c=>({asset_name:Be(c.actor_name),description:Be(c.description),extend:{}}));return{title:Be(e.title),actors:s,episodes:r}}function sh(e){if(!yt(e))throw new Error("review renderer expects a script object");let t=DI(e),n=JSON.stringify(t),o=Be(t.title);return`<!DOCTYPE html>
275
+ assets: ${l.assets.actors} actors / ${l.assets.locations} locations / ${l.assets.props} props`,data:l},J]}if(i.kind!=="text"){let d=FI(e),p=YI(e),l=p?{videoProvider:p}:void 0,f=t.createExecutor(Wi(e.llm_config).trim()||void 0,l),u=f.route("ingest.video-serial"),h=d??u.videoUploadMode??"file-api";if(p?.provider==="doubao"&&h!=="file-api")throw Ro("Doubao requires --upload-mode file-api.",["--upload-mode file-api"]);let m=await Nh({sourcePath:n,workspacePath:o,executor:f,fps:Uh(e.fps,3),force:!!e.force,step:!!e.step,uploadMode:h}),g=[`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`],w=[...f.usageEvents()].reverse().find(y=>y.task==="ingest.video-serial"&&y.status==="succeeded")??u;return[{text:g.join(`
276
+ `),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:w.protocol,provider:w.provider,base_url:w.baseUrl,model:w.model},assets:m.assets}},J]}let s=t.createExecutor(Wi(e.llm_config).trim()||void 0),c=await Rg({sourcePath:n,workspacePath:o,executor:s,concurrency:Uh(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(`
277
+ `),data:{workspace:c.workspacePath,script_path:c.scriptPath,records:c.records,chunks:c.chunks,assets:c.assets}},J]}import*as Ct from"node:fs";import*as Pt from"node:path";var qI=e=>e==null?"":String(e);function Th(e){try{let t=JSON.parse(Ct.readFileSync(Pt.join(e,"timings.json"),"utf-8"));return Ag(t,Date.now())}catch{return null}}function Va(e,t,n){let o=Pt.join(e,t),i;try{i=Ct.readdirSync(o)}catch{return[]}return i.filter(r=>r.endsWith(n)).sort()}var ZI=(e,t,n)=>Va(e,t,n).length,Xp=(e,t)=>Ct.existsSync(Pt.join(e,t));function WI(e){try{return JSON.parse(Ct.readFileSync(Pt.join(e,"manifest.json"),"utf-8"))}catch{return null}}function XI(e){try{let t=JSON.parse(Ct.readFileSync(Pt.join(e,"validation.json"),"utf-8"));return{ok:!!t.ok,errors:t.errors?.length??0,warnings:t.warnings?.length??0}}catch{return null}}function qp(e,t,n){return{pass:e,unit:t,phase:e,attempts:[],...Rt({failure_type:"unknown",failure_code:"legacy_unclassified"},{retryable:e==="pass2",message:n})}}function eA(e,t,n){try{let o=JSON.parse(Ct.readFileSync(Pt.join(e,t,`${n}.error.json`),"utf-8")),i=Hr(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"?qp(t,n,o.error):qp(t,n,"Error sidecar has an unsupported schema.")}catch{return qp(t,n,"Error sidecar is unreadable.")}}function tA(e,t,n=new Set){return Va(e,t,".error.json").map(o=>o.replace(/\.error\.json$/,"")).filter(o=>!n.has(o)).map(o=>eA(e,t,o))}function nA(e,t,n){let o=Hr(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 Zp(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 oA(e){try{let t=JSON.parse(Ct.readFileSync(Pt.join(e,"body.json"),"utf-8"));return Array.isArray(t.episodes)?t.episodes.length:0}catch{return 0}}function iA(e){try{let t=JSON.parse(Ct.readFileSync(Pt.join(e,"script.json"),"utf-8"));return t.version===4&&Array.isArray(t.episodes)?t.episodes.length:null}catch{return null}}function rA(e,t,n){try{let o;return n==="comic"?o=JSON.parse(Ct.readFileSync(Pt.join(e,"checkpoint.json"),"utf-8")).context:o=JSON.parse(Ct.readFileSync(Pt.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 sA(e,t){let n=t.chunks??0,o={total:n,done:Va(e,"pass2",".json").filter(a=>/^chunk_\d+\.json$/.test(a)).length,failed:ZI(e,"pass2",".error.json")},i=oA(e),r=Va(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:Xp(e,"body.json")},{name:"serial",done:i>0&&r>=i,unit:s},{name:"govern",done:Xp(e,"script.json")}],units:o}}function aA(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&&iA(e)===o}],units:c,parsed:s}}function qr(e){let t=Pt.resolve(e),n=WI(t);if(!n)return{workspace:t,exists:!1,kind:null,state:"empty",phase:"none",passes:[],units:null,script:!1,validation:null,failure_summary:Zp([]),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"?rA(t,i,o):0,s=o!=="text"&&r<i,c=o==="video"?n.skips??[]:[],a=new Set(c.map(_=>`ep_${String(_.episode).padStart(3,"0")}`)),d=o!=="text"&&r<i?nA(n,r,a):[],p=o!=="text"?aA(t,n,c,r,d.length):null,{passes:l,units:f}=o==="text"?sA(t,n):p,u=o==="text"?tA(t,"pass2"):d;if(s){let _=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:Zp(u),errors:u,updated:n.updated??null,timings:Th(t),completed:r,remaining:i-r,complete:!1,next_episode:r+1,parsed:p?.parsed??r,skipped:_.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 h=Xp(t,"script.json"),m=XI(t);m&&!m.ok&&u.push({pass:"finalize",unit:"script",phase:"validation",attempts:[],...Rt({failure_type:"validation",failure_code:"script_validation_failed"},{retryable:!1,message:`Script validation failed with ${m.errors} error(s).`})});let g,w=l.length>0&&l.every(_=>_.done);(o==="text"||w)&&h&&m?.ok?g="ready":u.length>0||m&&!m.ok?g="failed":g="incomplete";let y=l.find(_=>!_.done),x=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(_=>_.episode<=f.done).length,skipped_episodes:c.map(_=>_.episode),has_skips:c.length>0,skips:c.map(_=>({episode:_.episode,skipped_at:_.skipped_at,reason:_.reason,failure_type:_.failure.failure_type,failure_code:_.failure.failure_code}))}:{};return{workspace:t,exists:!0,kind:o,state:g,phase:x,passes:l,units:f,script:h,validation:m,failure_summary:Zp(u),errors:u,updated:n.updated??null,timings:Th(t),...S}}function cA(e){let t=`${e.done}/${e.total}`;return e.failed>0?`${t} (${e.failed} failed)`:t}function dA(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?cA(i.unit):i.done?"\u2713":"-"}`).join(" "),o=[t,n];if(e.timings&&o.push(pA(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 Wp(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 pA(e){let t=[`elapsed ${Wp(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(`~${Wp(n.avgWindowMs)}/window`),n.etaMs!=null&&!e.done&&t.push(`eta ~${Wp(n.etaMs)}`)),t.join(" \xB7 ")}function Vh(e){let t=qI(e.workspace_path||"workspace"),n=qr(t);return[{text:dA(n).join(`
278
+ `),data:{status:n}},J]}import*as $a from"node:path";function bn(e,t,n,o){return new E(e,{exitCode:k,errorCode:t,hint:n,data:{actual:o}})}function lA(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw bn("--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 uA(e,t,n){let o=new lt(e);if(!o.has("manifest.json"))throw bn("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 bn("Only video ingest episodes can be skipped.","INGEST_SKIP_WRONG_PIPELINE","Use skip only with a video ingest workspace.",[e]);let r=Fp(o);if(!r)throw bn("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 bn("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=Hp(o);Na(c.episodes,r.episodes);let a=o.has("context.json")?o.readJson("context.json"):Ao();if(c.episodes.find(w=>w.episode===t)){let w=Yp(o,r);a=Fr(o,a,c.episodes);let y=o.has("v4_identity_map.json")?o.readJson("v4_identity_map.json"):So();return Ca(o,w.episodes,a,Pa(w.source.path),y,c.episodes),!1}let p=a.lastEpisode+1;if(t!==p)throw bn("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 bn("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 bn("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=Hr(o.readJson(`${l}.error.json`));if(!f||f.unit.episode!==t)throw bn("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},h=Yp(o,r),m=[...c.episodes,u];o.writeJson("manifest.json",{...h,updated:u.skipped_at,current_error:void 0,skips:m}),bh(o,{schema_version:1,episodes:m}),a=Fr(o,a,m);let g=o.has("v4_identity_map.json")?o.readJson("v4_identity_map.json"):So();return Ca(o,h.episodes,a,Pa(h.source.path),g,[...c.episodes,u]),!0}async function $h(e){let t=$a.resolve(typeof e.workspace_path=="string"?e.workspace_path:"workspace"),n=lA(e.episode),o=typeof e.reason=="string"?e.reason.trim():"";if(!o)throw bn("--reason is required.","INGEST_SKIP_REASON_REQUIRED","Record why this episode cannot be parsed.",["--reason <text>"]);let i=await bo(t,()=>uA(t,n,o)),r=qr(t),s=Hp(new lt(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:$a.join(t,"script.json")}},J]}import*as Ga from"node:fs";import*as di from"node:path";import{spawnSync as fA}from"node:child_process";function Da(e,t,n,o){return new E(e,{exitCode:k,errorCode:t,hint:n,data:{actual:o}})}function mA(e){let t=va(Sn(e)),n=ka(t);if(n)throw Da("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=di.resolve(o.path),r=Ga.statSync(i),s=r.size,c=Math.trunc(r.mtimeMs),a=fA("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:he(JSON.stringify({absolutePath:i,sizeBytes:s,mtimeMs:c})),size_bytes:s,mtime_ms:c,duration_ms:p}})}async function gA(e){let t=di.resolve(e.scriptPath),n=di.resolve(e.sourcePath),o=di.resolve(e.workspacePath),i=_i(JSON.parse(Ga.readFileSync(t,"utf-8"))),r=mA(n);if(r.length!==i.episodes.length)throw Da("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=Ra(r),c=ba([],i,Ao(),r,s),a=await bo(o,async()=>{let p=new lt(o);return p.ensure(),Ma(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:di.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 Dh(e){let t=Ae(e),n=typeof e.source_path=="string"?e.source_path.trim():"",o=typeof e.workspace_path=="string"?e.workspace_path.trim():"";if(!n)throw Da("--source-path is required.","EVIDENCE_SOURCE_REQUIRED","Pass the linked source-video file or folder.",["--source-path <path>"]);if(!o)throw Da("--workspace-path is required.","EVIDENCE_WORKSPACE_REQUIRED","Pass the project workspace directory.",["--workspace-path <path>"]);let i=await gA({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}},J]}import*as Lo from"node:fs";import*as Ja from"node:path";var At=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Yn=e=>Array.isArray(e),Ke=e=>typeof e=="string"?e:"",hA={interior:"\u5185",exterior:"\u5916"},yA={day:"\u65E5",night:"\u591C"},wA=e=>{let t=e.match(/(\d+)/);return t?Number(t[1]):0},xA=e=>{let t=e.match(/(\d+)/);return t?Number(t[1]):0};function el(e,t,n){let o=new Map;if(Yn(e))for(let i of e)At(i)&&typeof i[t]=="string"&&o.set(i[t],Ke(i[n]));return o}function _A(e,t){let n=new Map;if(Yn(e))for(let o of e){if(!At(o)||typeof o[t]!="string")continue;let i=new Map;for(let r of Yn(o.states)?o.states:[])At(r)&&typeof r.state_id=="string"&&i.set(r.state_id,Ke(r.state_name));n.set(o[t],i)}return n}function EA(e,t){return At(e)?typeof e.actor_id=="string"?t.get(e.actor_id)??e.actor_id:typeof e.kind=="string"?`${e.kind}${e.label?`:${Ke(e.label)}`:""}`:"":""}function SA(e){let t=el(e.actors,"actor_id","actor_name"),n=el(e.locations,"location_id","location_name"),o=el(e.props,"prop_id","prop_name"),i=_A(e.actors,"actor_id"),r=(Yn(e.episodes)?e.episodes:[]).filter(At).map(c=>({episode:wA(Ke(c.episode_id)),synopsis:Ke(c.synopsis),scenes:(Yn(c.scenes)?c.scenes:[]).filter(At).map(a=>{let d=At(a.location)?n.get(Ke(a.location.location_id))??Ke(a.location.location_id):"",p=[],l={};for(let h of Yn(a.actors)?a.actors:[]){if(!At(h)||typeof h.actor_id!="string")continue;let m=t.get(h.actor_id)??h.actor_id;if(p.includes(m)||p.push(m),typeof h.state_id=="string"){let w=(i.get(h.actor_id)?.get(h.state_id)??"")||(h.state_id!=="default"?h.state_id:"");w&&(l[m]=w)}}let f=[];for(let h of Yn(a.props)?a.props:[])if(At(h)&&typeof h.prop_id=="string"){let m=o.get(h.prop_id)??h.prop_id;f.includes(m)||f.push(m)}let u=At(a.environment)?a.environment:{};return{scene_num:xA(Ke(a.scene_id)),location_name:d,environment:{space:hA[Ke(u.space)]??Ke(u.space),time:yA[Ke(u.time)]??Ke(u.time)},actor_names:p,actor_states:l,prop_names:f,actions:(Yn(a.actions)?a.actions:[]).filter(At).map(h=>({type:Ke(h.type),content:Ke(h.content),speaker:EA(h.speaker,t),emotion:typeof h.emotion=="string"?h.emotion:void 0,extend:At(h.extend)&&typeof h.extend.timestamp=="string"?{timestamp:h.extend.timestamp}:void 0}))}})})),s=(Yn(e.actors)?e.actors:[]).filter(At).map(c=>({asset_name:Ke(c.actor_name),description:Ke(c.description),extend:{}}));return{title:Ke(e.title),actors:s,episodes:r}}function Gh(e){if(!At(e))throw new Error("review renderer expects a script object");let t=SA(e),n=JSON.stringify(t),o=Ke(t.title);return`<!DOCTYPE html>
277
279
  <html lang="zh">
278
280
  <head>
279
281
  <meta charset="utf-8">
@@ -594,10 +596,10 @@ tabScript.addEventListener('click',()=>switchTab('script'));
594
596
  tabAssets.addEventListener('click',()=>switchTab('assets'));
595
597
  </script>
596
598
  </body>
597
- </html>`}import*as ah from"node:http";import*as yo from"node:fs";import*as hn from"node:path";import{spawn as GI}from"node:child_process";var JI=e=>e==null?"":String(e);function BI(e){let t=r=>{try{let s=yo.statSync(hn.join(e,r));return{rel:r,size:s.size,mtime:s.mtimeMs}}catch{return null}},n=(r,s)=>{let c=[];try{c=yo.readdirSync(hn.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(".md").filter(r=>!r.rel.endsWith(".context.md")),\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 KI(e){let t="";try{t=yo.readFileSync(hn.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 jI(e){try{return JSON.parse(yo.readFileSync(hn.join(e,"usage.json"),"utf-8"))}catch{return null}}function zI(e,t){let n=hn.resolve(e,t);if(n!==e&&!n.startsWith(e+hn.sep))return{ok:!1};try{return{ok:!0,text:yo.readFileSync(n,"utf-8")}}catch{return{ok:!1}}}function Tr(e,t,n,o){e.writeHead(t,{"Content-Type":n,"Cache-Control":"no-store"}),e.end(o)}async function ch(e){let t=hn.resolve(JI(e.workspace_path||"workspace")),n=Number(e.port)||0,o=ah.createServer((s,c)=>{let a=new URL(s.url??"/","http://localhost");if(a.pathname==="/")return Tr(c,200,"text/html; charset=utf-8",HI);if(a.pathname==="/api/state"){let d=Cr(t);return Tr(c,200,"application/json",JSON.stringify({root:t,status:d,groups:BI(t),timing:KI(t),usage:jI(t)}))}if(a.pathname==="/api/file"){let d=a.searchParams.get("path")??"",p=zI(t,d);return p.ok?Tr(c,200,"text/plain; charset=utf-8",p.text):Tr(c,404,"text/plain","not found")}Tr(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}
599
+ </html>`}import*as Jh from"node:http";import*as Mo from"node:fs";import*as On from"node:path";import{spawn as IA}from"node:child_process";var AA=e=>e==null?"":String(e);function kA(e){let t=r=>{try{let s=Mo.statSync(On.join(e,r));return{rel:r,size:s.size,mtime:s.mtimeMs}}catch{return null}},n=(r,s)=>{let c=[];try{c=Mo.readdirSync(On.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(".md").filter(r=>!r.rel.endsWith(".context.md")),\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 bA(e){let t="";try{t=Mo.readFileSync(On.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 OA(e){try{return JSON.parse(Mo.readFileSync(On.join(e,"usage.json"),"utf-8"))}catch{return null}}function vA(e,t){let n=On.resolve(e,t);if(n!==e&&!n.startsWith(e+On.sep))return{ok:!1};try{return{ok:!0,text:Mo.readFileSync(n,"utf-8")}}catch{return{ok:!1}}}function Zr(e,t,n,o){e.writeHead(t,{"Content-Type":n,"Cache-Control":"no-store"}),e.end(o)}async function Bh(e){let t=On.resolve(AA(e.workspace_path||"workspace")),n=Number(e.port)||0,o=Jh.createServer((s,c)=>{let a=new URL(s.url??"/","http://localhost");if(a.pathname==="/")return Zr(c,200,"text/html; charset=utf-8",RA);if(a.pathname==="/api/state"){let d=qr(t);return Zr(c,200,"application/json",JSON.stringify({root:t,status:d,groups:kA(t),timing:bA(t),usage:OA(t)}))}if(a.pathname==="/api/file"){let d=a.searchParams.get("path")??"",p=vA(t,d);return p.ok?Zr(c,200,"text/plain; charset=utf-8",p.text):Zr(c,404,"text/plain","not found")}Zr(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}
598
600
  Workspace: ${t}
599
601
  Press Ctrl-C to stop.
600
- `),process.platform==="darwin"&&process.stderr.isTTY)try{GI("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 HI=`<!doctype html><html lang="zh"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
602
+ `),process.platform==="darwin"&&process.stderr.isTTY)try{IA("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}},J]}var RA=`<!doctype html><html lang="zh"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
601
603
  <title>scriptctl ingest \u76D1\u542C</title>
602
604
  <style>
603
605
  :root{--bg:#f6f7f9;--panel:#ffffff;--panel2:#f0f2f5;--line:#e3e6ea;--fg:#1f2430;--dim:#6b7280;--acc:#2563eb;--ok:#16a34a;--warn:#d97706;--err:#dc2626}
@@ -795,7 +797,7 @@ function poll(){
795
797
  }).catch(function(){$('#tick').textContent='\u25CF \u79BB\u7EBF'});
796
798
  }
797
799
  poll();setInterval(poll,1500);setInterval(renderTiming,1000);
798
- </script></body></html>`;function dh(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=na.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>
800
+ </script></body></html>`;function Kh(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=Zo.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>
799
801
  <html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
800
802
  <title>\u6F2B\u753B\u5267\u672C\u5BA1\u9605</title>
801
803
  <style>
@@ -944,40 +946,39 @@ if(model.episodes.length){
944
946
  const action=actions.find(action=>action.id===requested.get('action'));
945
947
  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);}
946
948
  }
947
- </script></html>`}import*as Ct from"node:fs";import*as Gi from"node:path";import{spawn as QI}from"node:child_process";var ph=1200;function FI(e,t){return new Promise((n,o)=>{let i=QI("pdftoppm",["-cropbox","-scale-to-x",String(ph),"-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:b,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:b,errorCode:"VIEW_PDF_RENDER_FAILED",data:{actual:[e]}}))})})}async function lh(e,t){let n=`review-pages/cropbox-w${ph}-q92/${e.sha256}`,o=Gi.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=>Ct.existsSync(Gi.join(o,s)))){let s=`${o}.part`;Ct.rmSync(s,{recursive:!0,force:!0}),Ct.mkdirSync(s,{recursive:!0}),process.stderr.write(`\u6E32\u67D3\u6F2B\u753B\u539F\u9875 \xB7 ${e.title} \xB7 ${e.page_count} \u9875
948
- `),await FI(e.path,Gi.join(s,"page"));for(let c of r)if(!Ct.existsSync(Gi.join(s,c))||Ct.statSync(Gi.join(s,c)).size===0)throw new x(`PDF renderer did not produce ${c}.`,{exitCode:b,errorCode:"VIEW_PDF_RENDER_FAILED"});Ct.rmSync(o,{recursive:!0,force:!0}),Ct.renameSync(s,o)}return r.map(s=>`${n}/${s}`)}var YI=e=>e==null?"":String(e),qI=e=>String(e).padStart(3,"0");function ZI(e){if(!e.has("manifest.json"))return;let t=e.readJson("manifest.json");if(!Array.isArray(t.episodes))return;let n=e.path("src");wo.mkdirSync(n,{recursive:!0});for(let o of t.episodes){if(typeof o.episode!="number"||typeof o.path!="string")continue;let i=Sa.join(n,`ep_${qI(o.episode)}.mp4`);try{wo.rmSync(i,{force:!0}),wo.symlinkSync(o.path,i)}catch{}}}async function uh(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:b,errorCode:"VIEW_WATCH_SANDBOX",hint:"Use `scriptctl ingest status` for progress in the sandbox; run `view --watch` on your local machine."});return ch(e)}let t=YI(e.workspace_path||"workspace"),n=new st(Sa.resolve(t));if(!n.has("script.json"))throw new x("workspace has no script.json to render.",{exitCode:b,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=si(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=na.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 x(`Unknown comic source document: ${p}`,{exitCode:b,errorCode:"VIEW_COMIC_SOURCE_MISSING"});let f=n.path(`src/${l.document_id}.pdf`);wo.rmSync(f,{force:!0}),wo.symlinkSync(l.path,f);let u=await lh(l,n.root);d.push({id:l.document_id,title:l.title,pdf:`src/${l.document_id}.pdf`,images:u})}i=dh(c,d)}else ZI(n),i=sh(n.readJson("script.json"));n.writeText("review.html",i);let r=n.path("review.html");return[{text:r,data:{output:r}},B]}import*as qo from"node:path";import WI from"fast-json-patch";var{compare:fh}=WI;var mh="/api/anime/workbench/v2/script/project-groups",XI="/api/anime/workbench/projectGroup/updateProjectGroupInfo",eA=5e3,gh=8*1024*1024;function tA(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 hh(e){return encodeURIComponent(String(e))}function nA(e,t,n){if(t===404&&n.includes("/imports"))return new pe("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 pe(r,{status:t,code:i.code??null,payload:i})}return new pe(e||`HTTP ${t}`,{status:t,payload:e})}function yh(e,t){let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(!(n<=gh))throw new pe(`script ${e} body too large: ${n} bytes (limit ${gh})`)}async function wh(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 m=await fetch(`${e}${i}`,{method:o,headers:c,body:s,signal:a.signal});p=m.status,l=await m.text()}catch(m){if(m instanceof Error&&m.name==="AbortError")throw new pe("Gateway request timed out");let h=m instanceof Error?m.message:String(m);throw new pe(`Gateway request failed: ${h}`)}finally{clearTimeout(d)}if(p>=400)throw nA(l,p,i);let f=null;if(l)try{f=JSON.parse(l)}catch{throw new pe("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 m=String(u.msg??u.message??"script-output API failed");if(r.allowMissing&&typeof m=="string"&&m.includes("\u5267\u672C\u4E0D\u5B58\u5728"))return null;throw new pe(m,{status:p,code:g,payload:u})}return"data"in u?u.data:u}var Lp=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 pe("projectGroupNo missing; pass --project-group-no or set SANDBOX_PROJECT_GROUP_NO",{configMissing:"project"});let o=tA(process.env.AWB_BASE_URL||"");if(!o)throw new pe("gateway URL missing; set AWB_BASE_URL",{configMissing:"gateway"});let i=(process.env.LINGJING_AWB_ACCESS_KEY||"").trim();if(!i)throw new pe("access key missing; set LINGJING_AWB_ACCESS_KEY",{configMissing:"access"});return new e({gatewayBase:o,projectGroupNo:n,accessKey:i})}get projectPrefix(){return`${mh}/${hh(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:fh(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 yh("root",n),await this.request("PUT",this.projectPrefix,{body:n})}async patchScript(t){let n=fh(t.old,t.edited),o={requestId:t.requestId,baseRevision:t.baseRevision,source:t.source??"ctl",patch:n};return yh("patch",o),await this.request("PATCH",this.projectPrefix,{body:o})}async saveValidationResult(t){return await this.request("POST",`${mh}/${hh(this.projectGroupNo)}/validation-result`,{body:{revision:t.revision,validationStatus:t.validationStatus,validationSummary:t.validationSummary,issues:t.issues}})}async updateEpisodeCount(t){await wh(this.gatewayBase,this.accessKey,Math.min(this.timeoutMs,eA),"POST",XI,{body:{projectGroupNo:this.projectGroupNo,episodeCount:t}})}async request(t,n,o={}){return wh(this.gatewayBase,this.accessKey,this.timeoutMs,t,n,o)}};function Np(e){return Lp.fromEnv(e)}var Vr=class{workspace;script;version;baseline;baselineHash;scriptPath;client;projectGroupNo;revision;constructor(t){this.workspace=t.workspace,this.script=t.script,this.version=Ao(t.script),this.baseline=structuredClone(t.script),this.baselineHash=$e(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 Eo(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?me:b,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 $r(e){let t=v(e.workspace_path||"workspace"),n=Se(e);if(!xo(n))throw new x("Local script file not found.",{exitCode:b,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=Hi(n)}catch(i){throw new x("script JSON invalid.",{exitCode:b,errorCode:"SCRIPT_JSON_INVALID",hint:"Fix the local script JSON syntax before editing.",data:{expected:["valid JSON"],actual:[`${n}: ${i.message}`]}})}if(!ee(o))throw new x("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 Vr({workspace:t,scriptPath:n,script:o})}function Dr(e,t={}){let n=Up(e.script);return e.remote&&(n.script_path=e.artifactLabel),n}function oA(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=te(e.episodes),c=0,a=0;for(let d of s)for(let p of te(d.scenes))c+=1,a+=te(p.actions).length;return{passed:n,has_blocking:!n,issues:r,stats:{actors:te(e.actors).length,locations:te(e.locations).length,props:te(e.props).length,episodes:s.length,scenes:c,actions:a}}}function Up(e){return oA(e,tr(e))}function iA(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 rA(e){let t=v(e||"info");return t==="blocking"||t==="error"?"error":t==="warning"?"warning":"info"}function sA(e){let t=te(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(!ee(r))continue;let s={...r};for(let c of["severity","code","path","summary","repair_hint"])delete s[c];i.push({severity:rA(r.severity),code:v(r.code||"SCRIPT_VALIDATION_ISSUE"),path:iA(r),summary:v(r.summary),repairHint:r.repair_hint,payload:s})}return[n,o,i]}async function Pp(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]=sA(t);try{await e.client.saveValidationResult({revision:o,validationStatus:i,validationSummary:r,issues:s})}catch(c){throw c instanceof pe?Eo("SCRIPT API BLOCKED: Validation sync failed",c):c}}async function Cp(e,t,n){if(e.scriptPath===null)throw new Error("local script session missing script path");return Rt(e.scriptPath,e.baselineHash),je(e.scriptPath,e.script),[null,!1]}async function Eh(e,t=Ln){let n=await $r(e),o=t.createExecutor(v(e.llm_config).trim()||void 0),i=await Xd(n.script,o);n.scriptPath&&Rt(n.scriptPath,n.baselineHash);let r=n.scriptPath?qo.dirname(n.scriptPath):qo.resolve(n.workspace),s=qo.resolve(v(e.output).trim()||qo.join(r,"asset-audit.json"));je(s,i);let c=i.issues.length>0,a=i.issues.map(ep);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(`
949
- `),data:{op:"script.audit-assets",changed:!1,issues:i.issues,output:s,asset_audit:i,config_source:o.configSource,llm_routes:o.usage()}},c?Dn:B]}function _h(e=""){return{version:4,title:e,worldview:"",style:"",actors:[],locations:[],props:[],episodes:[]}}function _o(e){let t=ee(e.location)?e.location:null;return{actors:In(e.actors)?e.actors:[],props:In(e.props)?e.props:[],locations:t&&String(t.location_id??"").trim()?[t]:[]}}function Rh(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(`
950
- `),data:{op:"script.create",changed:!0,validation:t,script_path:e.artifactLabel,...e.remote?{revision:e.revision,idempotent:n}:{}}}}async function Mh(e){let t=v(e.workspace_path||"workspace"),n=!!e.force,o=v(e.title).trim(),i=_h(o),r=Se(e);if(xo(r)&&!n)throw new x("A script already exists at the target.",{exitCode:b,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]}});je(r,i);let s=new Vr({workspace:t,scriptPath:r,script:i}),c=Dr(s),a=!!c.passed;return[Rh(s,c,null),a?B:Dn]}import*as Bi from"node:fs";import*as Wo from"node:path";function _A(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 Zo(e){return ee(e)&&Object.values(e).every(t=>typeof t=="string")}function xA(e){return ee(e)&&Object.values(e).every(Zo)}function SA(e){return ee(e)&&e.version===3&&Zo(e.actor)&&Zo(e.location)&&Zo(e.prop)&&xA(e.state)&&Zo(e.episode)&&Zo(e.scene)&&Zo(e.action)}function IA(e){if(e!==void 0){if(SA(e.identityMap))return e.identityMap;throw new x("Migration manifest contains an invalid v3-to-v4 identity map.",{exitCode:b,errorCode:"MIGRATE_MANIFEST_INVALID"})}}function Lh(e,t){let n=bt(e),o=Oi(n,IA(t),{action:_A(n)});return{script:o.script,artifact:{sourceVersion:3,targetVersion:4,identityMap:o.identityMap}}}var AA=[{sourceVersion:3,targetVersion:4,migrate:Lh}];function kA(e){return ee(e)&&jn(e.source_version)&&jn(e.target_version)&&e.source_version<e.target_version&&"identity_map"in e}function Nh(e){if(!Array.isArray(e))throw new x("Migration manifest steps must be an array.",{exitCode:b,errorCode:"MIGRATE_MANIFEST_INVALID"});return e.map(t=>{if(!kA(t))throw new x("Migration manifest contains an invalid step artifact.",{exitCode:b,errorCode:"MIGRATE_MANIFEST_INVALID"});return{sourceVersion:t.source_version,targetVersion:t.target_version,identityMap:t.identity_map}})}function bA(e,t){return AA.find(n=>n.sourceVersion===e&&n.targetVersion<=t)}function OA(e,t){return e.find(n=>n.sourceVersion===t.sourceVersion&&n.targetVersion===t.targetVersion)}function Uh(e,t,n=[]){let o=Ao(e);if(t<o)throw new x("A migration target must be newer than the source script.",{exitCode:b,errorCode:"MIGRATE_TARGET_OLDER",data:{expected:[String(o)],actual:[String(t)]}});let i=ss(e),r=o,s=[];for(;r<t;){let c=bA(r,t);if(c===void 0)throw new x(`No migration path exists from Script v${r} to Script v${t}.`,{exitCode:b,errorCode:"MIGRATE_PATH_UNSUPPORTED",data:{actual:[String(r),String(t)]}});let a=c.migrate(i,OA(n,c));i=a.script,r=c.targetVersion,s.push(a.artifact)}return{sourceVersion:o,targetVersion:t,script:i,steps:s}}function Gr(e,t){let n=e[t];return typeof n=="string"?n.trim():""}function vA(e,t){let n=Gr(e,t);return/^\d+$/.test(n)?Number(n):null}function RA(e){let t=vA(e,"to");if(jn(t))return t;throw new x("A supported migration target version is required.",{exitCode:J,errorCode:"MIGRATE_TARGET_INVALID",hint:"Pass --to <version> with a supported Script version.",data:{expected:rc.map(String),actual:[Gr(e,"to")||"<empty>"]}})}function MA(e){let t=Wo.extname(e);return`${t.length>0?e.slice(0,-t.length):e}.migration.json`}function LA(e,t,n){let o=[e,t,n].map(i=>Wo.resolve(i));if(o[0]===o[1])throw new x("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 x("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 Ph(e,t){if(!t&&Bi.existsSync(e))throw new x("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 NA(e){let t;try{t=Bi.readFileSync(e,"utf8")}catch(n){throw new x("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 x("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 UA(e,t){if(!t||!Bi.existsSync(e))return;let n;try{n=JSON.parse(Bi.readFileSync(e,"utf8"))}catch(o){throw new x("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(!ee(n)||n.version!==1||!jn(n.source_version)||!jn(n.target_version)||typeof n.source_path!="string"||typeof n.source_sha256!="string")throw new x("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:Nh(n.steps)}}async function Ch(e){let t=Gr(e,"script_path"),n=Gr(e,"output");if(!t||!n)throw new x("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=Wo.resolve(t),i=Wo.resolve(n),r=Wo.resolve(Gr(e,"manifest")||MA(i)),s=RA(e),c=!!e.force;return LA(o,i,r),ns(i,async()=>{Ph(i,c),Ph(r,c);let a=NA(o),d=Ao(a.value);if(s<=d)throw new x("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=tr(a.value),l=UA(r,c),f=Uh(a.value,s,l?.steps),u=tr(f.script),g={version:1,source_version:f.sourceVersion,target_version:f.targetVersion,source_path:o,source_sha256:Ie(a.raw),steps:f.steps};je(r,{...g,steps:g.steps.map(w=>({source_version:w.sourceVersion,target_version:w.targetVersion,identity_map:w.identityMap}))}),je(i,f.script);let m={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(`
949
+ </script></html>`}var MA=e=>e==null?"":String(e),LA=e=>String(e).padStart(3,"0");function NA(e){if(!e.has("manifest.json"))return;let t=e.readJson("manifest.json");if(!Array.isArray(t.episodes))return;let n=e.path("src");Lo.mkdirSync(n,{recursive:!0});for(let o of t.episodes){if(typeof o.episode!="number"||typeof o.path!="string")continue;let i=Ja.join(n,`ep_${LA(o.episode)}.mp4`);try{Lo.rmSync(i,{force:!0}),Lo.symlinkSync(o.path,i)}catch{}}}async function jh(e){if(e.watch){if((process.env.SANDBOX_PROJECT_GROUP_NO??"").trim())throw new E("`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 Bh(e)}let t=MA(e.workspace_path||"workspace"),n=new lt(Ja.resolve(t));if(!n.has("script.json"))throw new E("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=Zo.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(h=>h.document_id===p);if(!l)throw new E(`Unknown comic source document: ${p}`,{exitCode:k,errorCode:"VIEW_COMIC_SOURCE_MISSING"});let f=n.path(`src/${l.document_id}.pdf`);Lo.rmSync(f,{force:!0}),Lo.symlinkSync(l.path,f);let u=await Fs(l,n.root);d.push({id:l.document_id,title:l.title,pdf:`src/${l.document_id}.pdf`,images:u})}i=Kh(c,d)}else NA(n),i=Gh(n.readJson("script.json"));n.writeText("review.html",i);let r=n.path("review.html");return[{text:r,data:{output:r}},J]}import*as pi from"node:path";import UA from"fast-json-patch";var{compare:zh}=UA;var Hh="/api/anime/workbench/v2/script/project-groups",CA="/api/anime/workbench/projectGroup/updateProjectGroupInfo",PA=5e3,Qh=8*1024*1024;function TA(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 Fh(e){return encodeURIComponent(String(e))}function VA(e,t,n){if(t===404&&n.includes("/imports"))return new pe("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 pe(r,{status:t,code:i.code??null,payload:i})}return new pe(e||`HTTP ${t}`,{status:t,payload:e})}function Yh(e,t){let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(!(n<=Qh))throw new pe(`script ${e} body too large: ${n} bytes (limit ${Qh})`)}async function qh(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 m=await fetch(`${e}${i}`,{method:o,headers:c,body:s,signal:a.signal});p=m.status,l=await m.text()}catch(m){if(m instanceof Error&&m.name==="AbortError")throw new pe("Gateway request timed out");let g=m instanceof Error?m.message:String(m);throw new pe(`Gateway request failed: ${g}`)}finally{clearTimeout(d)}if(p>=400)throw VA(l,p,i);let f=null;if(l)try{f=JSON.parse(l)}catch{throw new pe("Gateway response is not valid JSON",{status:p,payload:l})}if(f===null)return null;if(typeof f!="object")return f;let u=f,h=u.code;if(h!=null&&String(h)!=="200"){let m=String(u.msg??u.message??"script-output API failed");if(r.allowMissing&&typeof m=="string"&&m.includes("\u5267\u672C\u4E0D\u5B58\u5728"))return null;throw new pe(m,{status:p,code:h,payload:u})}return"data"in u?u.data:u}var tl=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 pe("projectGroupNo missing; pass --project-group-no or set SANDBOX_PROJECT_GROUP_NO",{configMissing:"project"});let o=TA(process.env.AWB_BASE_URL||"");if(!o)throw new pe("gateway URL missing; set AWB_BASE_URL",{configMissing:"gateway"});let i=(process.env.LINGJING_AWB_ACCESS_KEY||"").trim();if(!i)throw new pe("access key missing; set LINGJING_AWB_ACCESS_KEY",{configMissing:"access"});return new e({gatewayBase:o,projectGroupNo:n,accessKey:i})}get projectPrefix(){return`${Hh}/${Fh(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:zh(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 Yh("root",n),await this.request("PUT",this.projectPrefix,{body:n})}async patchScript(t){let n=zh(t.old,t.edited),o={requestId:t.requestId,baseRevision:t.baseRevision,source:t.source??"ctl",patch:n};return Yh("patch",o),await this.request("PATCH",this.projectPrefix,{body:o})}async saveValidationResult(t){return await this.request("POST",`${Hh}/${Fh(this.projectGroupNo)}/validation-result`,{body:{revision:t.revision,validationStatus:t.validationStatus,validationSummary:t.validationSummary,issues:t.issues}})}async updateEpisodeCount(t){await qh(this.gatewayBase,this.accessKey,Math.min(this.timeoutMs,PA),"POST",CA,{body:{projectGroupNo:this.projectGroupNo,episodeCount:t}})}async request(t,n,o={}){return qh(this.gatewayBase,this.accessKey,this.timeoutMs,t,n,o)}};function nl(e){return tl.fromEnv(e)}var Wr=class{workspace;script;version;baseline;baselineHash;scriptPath;client;projectGroupNo;revision;constructor(t){this.workspace=t.workspace,this.script=t.script,this.version=Vo(t.script),this.baseline=structuredClone(t.script),this.baselineHash=De(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 No(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 E(r,{exitCode:t.status!==null&&t.status>=500?me: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 Xr(e){let t=v(e.workspace_path||"workspace"),n=Ae(e);if(!Co(n))throw new E("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=rr(n)}catch(i){throw new E("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(!ee(o))throw new E("script root invalid.",{exitCode:G,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 Wr({workspace:t,scriptPath:n,script:o})}function es(e,t={}){let n=ol(e.script);return e.remote&&(n.script_path=e.artifactLabel),n}function $A(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=te(e.episodes),c=0,a=0;for(let d of s)for(let p of te(d.scenes))c+=1,a+=te(p.actions).length;return{passed:n,has_blocking:!n,issues:r,stats:{actors:te(e.actors).length,locations:te(e.locations).length,props:te(e.props).length,episodes:s.length,scenes:c,actions:a}}}function ol(e){return $A(e,mr(e))}function DA(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 GA(e){let t=v(e||"info");return t==="blocking"||t==="error"?"error":t==="warning"?"warning":"info"}function JA(e){let t=te(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(!ee(r))continue;let s={...r};for(let c of["severity","code","path","summary","repair_hint"])delete s[c];i.push({severity:GA(r.severity),code:v(r.code||"SCRIPT_VALIDATION_ISSUE"),path:DA(r),summary:v(r.summary),repairHint:r.repair_hint,payload:s})}return[n,o,i]}async function il(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]=JA(t);try{await e.client.saveValidationResult({revision:o,validationStatus:i,validationSummary:r,issues:s})}catch(c){throw c instanceof pe?No("SCRIPT API BLOCKED: Validation sync failed",c):c}}async function rl(e,t,n){if(e.scriptPath===null)throw new Error("local script session missing script path");return Tt(e.scriptPath,e.baselineHash),ze(e.scriptPath,e.script),[null,!1]}async function Zh(e,t=zn){let n=await Xr(e),o=t.createExecutor(v(e.llm_config).trim()||void 0),i=await Op(n.script,o);n.scriptPath&&Tt(n.scriptPath,n.baselineHash);let r=n.scriptPath?pi.dirname(n.scriptPath):pi.resolve(n.workspace),s=pi.resolve(v(e.output).trim()||pi.join(r,"asset-audit.json"));ze(s,i);let c=i.issues.length>0,a=i.issues.map(vp);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(`
950
+ `),data:{op:"script.audit-assets",changed:!1,issues:i.issues,output:s,asset_audit:i,config_source:o.configSource,llm_routes:o.usage()}},c?Wn:J]}function Wh(e=""){return{version:4,title:e,worldview:"",style:"",actors:[],locations:[],props:[],episodes:[]}}function Uo(e){let t=ee(e.location)?e.location:null;return{actors:Cn(e.actors)?e.actors:[],props:Cn(e.props)?e.props:[],locations:t&&String(t.location_id??"").trim()?[t]:[]}}function ay(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(`
951
+ `),data:{op:"script.create",changed:!0,validation:t,script_path:e.artifactLabel,...e.remote?{revision:e.revision,idempotent:n}:{}}}}async function cy(e){let t=v(e.workspace_path||"workspace"),n=!!e.force,o=v(e.title).trim(),i=Wh(o),r=Ae(e);if(Co(r)&&!n)throw new E("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]}});ze(r,i);let s=new Wr({workspace:t,scriptPath:r,script:i}),c=es(s),a=!!c.passed;return[ay(s,c,null),a?J:Wn]}import*as tr from"node:fs";import*as ui from"node:path";function tk(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 li(e){return ee(e)&&Object.values(e).every(t=>typeof t=="string")}function nk(e){return ee(e)&&Object.values(e).every(li)}function ok(e){return ee(e)&&e.version===3&&li(e.actor)&&li(e.location)&&li(e.prop)&&nk(e.state)&&li(e.episode)&&li(e.scene)&&li(e.action)}function ik(e){if(e!==void 0){if(ok(e.identityMap))return e.identityMap;throw new E("Migration manifest contains an invalid v3-to-v4 identity map.",{exitCode:k,errorCode:"MIGRATE_MANIFEST_INVALID"})}}function dy(e,t){let n=Nt(e),o=Bi(n,ik(t),{action:tk(n)});return{script:o.script,artifact:{sourceVersion:3,targetVersion:4,identityMap:o.identityMap}}}var rk=[{sourceVersion:3,targetVersion:4,migrate:dy}];function sk(e){return ee(e)&&oo(e.source_version)&&oo(e.target_version)&&e.source_version<e.target_version&&"identity_map"in e}function py(e){if(!Array.isArray(e))throw new E("Migration manifest steps must be an array.",{exitCode:k,errorCode:"MIGRATE_MANIFEST_INVALID"});return e.map(t=>{if(!sk(t))throw new E("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 ak(e,t){return rk.find(n=>n.sourceVersion===e&&n.targetVersion<=t)}function ck(e,t){return e.find(n=>n.sourceVersion===t.sourceVersion&&n.targetVersion===t.targetVersion)}function ly(e,t,n=[]){let o=Vo(e);if(t<o)throw new E("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=Es(e),r=o,s=[];for(;r<t;){let c=ak(r,t);if(c===void 0)throw new E(`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,ck(n,c));i=a.script,r=c.targetVersion,s.push(a.artifact)}return{sourceVersion:o,targetVersion:t,script:i,steps:s}}function ts(e,t){let n=e[t];return typeof n=="string"?n.trim():""}function dk(e,t){let n=ts(e,t);return/^\d+$/.test(n)?Number(n):null}function pk(e){let t=dk(e,"to");if(oo(t))return t;throw new E("A supported migration target version is required.",{exitCode:G,errorCode:"MIGRATE_TARGET_INVALID",hint:"Pass --to <version> with a supported Script version.",data:{expected:Ac.map(String),actual:[ts(e,"to")||"<empty>"]}})}function lk(e){let t=ui.extname(e);return`${t.length>0?e.slice(0,-t.length):e}.migration.json`}function uk(e,t,n){let o=[e,t,n].map(i=>ui.resolve(i));if(o[0]===o[1])throw new E("The migration destination must differ from the source.",{exitCode:G,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 E("The migration manifest needs its own file path.",{exitCode:G,errorCode:"MIGRATE_MANIFEST_PATH",hint:"Choose a --manifest path separate from the source and output files.",data:{actual:[n]}})}function uy(e,t){if(!t&&tr.existsSync(e))throw new E("Migration destination already exists.",{exitCode:G,errorCode:"MIGRATE_OUTPUT_EXISTS",hint:"Choose a new path, or pass --force to replace the migration artifact.",data:{actual:[e]}})}function fk(e){let t;try{t=tr.readFileSync(e,"utf8")}catch(n){throw new E("Cannot read the source script.",{exitCode:G,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 E("The source script is not valid JSON.",{exitCode:G,errorCode:"MIGRATE_SOURCE_JSON_INVALID",hint:"Repair the JSON syntax, then rerun migrate.",data:{actual:[n instanceof Error?n.message:String(n)]}})}}function mk(e,t){if(!t||!tr.existsSync(e))return;let n;try{n=JSON.parse(tr.readFileSync(e,"utf8"))}catch(o){throw new E("Cannot reuse the existing migration manifest.",{exitCode:G,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(!ee(n)||n.version!==1||!oo(n.source_version)||!oo(n.target_version)||typeof n.source_path!="string"||typeof n.source_sha256!="string")throw new E("Cannot reuse the existing migration manifest.",{exitCode:G,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:py(n.steps)}}async function fy(e){let t=ts(e,"script_path"),n=ts(e,"output");if(!t||!n)throw new E("Migration paths are required.",{exitCode:G,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=ui.resolve(t),i=ui.resolve(n),r=ui.resolve(ts(e,"manifest")||lk(i)),s=pk(e),c=!!e.force;return uk(o,i,r),ys(i,async()=>{uy(i,c),uy(r,c);let a=fk(o),d=Vo(a.value);if(s<=d)throw new E("The migration target must be newer than the source script.",{exitCode:G,errorCode:"MIGRATE_TARGET_NOT_NEWER",data:{expected:[`>${d}`],actual:[String(s)]}});let p=mr(a.value),l=mk(r,c),f=ly(a.value,s,l?.steps),u=mr(f.script),h={version:1,source_version:f.sourceVersion,target_version:f.targetVersion,source_path:o,source_sha256:he(a.raw),steps:f.steps};ze(r,{...h,steps:h.steps.map(w=>({source_version:w.sourceVersion,target_version:w.targetVersion,identity_map:w.identityMap}))}),ze(i,f.script);let m={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(`
951
952
  `):[`Script v${f.targetVersion}: ${i}`,`Migration manifest: ${r}`,`validation: ${u.errors.length} errors; repair before production use`].join(`
952
- `),data:m},u.ok?B:Dn]})}import*as Ki from"node:path";import*as Vh from"node:path";function Th(e,t){let n=Ie(t);return Vh.join(e,`${n}.json`)}function Jr(e){return{read(t){let n=Th(e,t);return xo(n)?Hi(n):null},write(t){Ta(Th(e,t.key),t)}}}function Kp(){return{read(){return null},write(){}}}function jp(e){if(Array.isArray(e))return`[${e.map(t=>jp(t)).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${jp(t[n])}`).join(",")}}`}return JSON.stringify(e)}function zp(e){return Ie(jp(e))}function Hp(e,t,n){return{key:e,signature:t,value:n,createdAt:new Date().toISOString()}}function PA(e,t){return[e.trim(),t.trim()].filter(Boolean).join(`
953
-
954
- `)}function Dh(e,t){return{system:PA(e.instruction,e.format),user:e.input?e.input({parcel:t}):String(t)}}function CA(e,t,n){if(e.kind==="llm"){if(!n.executor)throw new Error("loom llm task requires run({ executor })");let o=Dh(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 Aa(e){return{kind:"root",children:e}}function qp(e,t,n){return{kind:"scope",scope:e,data:n,children:t}}function Br(e){return{kind:"parcel",data:e}}function jr(e){return{kind:"llm",...e}}var Qp=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 JA(this.input,this.steps,t)}};function ka(e){return new Qp(e)}async function TA(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 VA(e,t){let n=t.partition(e);return Aa(n.map(o=>{let i=t.chunk(o).map(r=>Br(r));return qp(t.scope,i,o)}))}function Fp(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(...Fp(r,s))}return o}function Kr(e,t){return e?.(t),t}async function $A(e,t){return Kr(e.validate,await e.run({parcel:t}))}async function DA(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 $h(e,t,n){return Kr(e.validate,e.parse({text:n.text,parcel:t,raw:n.raw}))}function Gh(e,t,n){if(e.kind==="parcel"){let i=t[n.index];return n.index+=1,Br(i)}let o=e.children.map(i=>Gh(i,t,n));return e.kind==="root"?Aa(o):qp(e.scope,o,e.data)}function GA(e){return e.children.every(t=>t.kind==="parcel")}async function Jh(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 Jh(y,t,n,o,[...i,`${y.kind}:${w}`]))}let s=e.kind==="root"?Aa(r):qp(e.scope,r,e.data),c=t==="root"&&s.kind==="root",a=s.kind==="scope"&&s.scope===t;if(!c&&!a||!GA(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("/")}:${zp({items:d,scopeData:p,version:f,salt:o.checkpointSalt})}`,g=zp({step:"reduce",scope:t,version:f,items:d,scopeData:p,salt:o.checkpointSalt}),m=await Yp(o.checkpoint,u,g);if(m.hit)return o.report.reused+=1,Br(Kr(n.validate,m.value));let h=Kr(n.validate,await n.run(d,{scope:p,scopeName:l}));return o.report.ran+=1,await o.checkpoint.write(Hp(u,g,h)),Br(h)}async function Yp(e,t,n){let o=await e.read(t);return o&&o.signature===n?{hit:!0,value:o.value}:{hit:!1}}async function JA(e,t,n){let o={executor:n.executor,signal:n.signal,checkpointSalt:n.checkpointSalt,checkpoint:n.checkpoint??Kp(),concurrency:n.concurrency??4,report:{reused:0,ran:0}},i=null,r=e;for(let c of t){if(c.kind==="split"){i=VA(r,c.spec),r=i;continue}if(i||(i=Aa([Br(r)])),c.kind==="extract"){let a=Fp(i),d=await TA(a,o.concurrency,async p=>{let l=CA(c.task,p.parcel,o),f=zp(l.payload),u=`extract:${p.path.join("/")}:${f}`;if(c.task.kind==="llm"){let h=await Yp(o.checkpoint,u,f);if(h.hit)return o.report.reused+=1,o.executor?.recordReuse(c.task.taskId),$h(c.task,p.parcel,h.value);let w=l.request??Dh(c.task,p.parcel),y=await DA(c.task,w,o),E=$h(c.task,p.parcel,y);return o.report.ran+=1,await o.checkpoint.write(Hp(u,f,y)),E}let g=await Yp(o.checkpoint,u,f);if(g.hit)return o.report.reused+=1,Kr(c.task.validate,g.value);let m=await $A(c.task,p.parcel);return o.report.ran+=1,await o.checkpoint.write(Hp(u,f,m)),m});i=Gh(i,d,{index:0}),r=i;continue}i=await Jh(i,c.scope,c.task,o,[]),r=i}if(!i)return{value:r,report:o.report};let s=Fp(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 jh={episodeInputMaxChars:6e3,episodeChunkTargetChars:4800,arcEpisodeCount:10,finalMaxInputChars:12e3},BA="\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",KA=["\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(`
955
- `),jA="\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",zA=["\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(`
956
- `),HA="\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",QA=["\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(`
957
- `),FA="\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",YA=["\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(`
958
- `);function qA(e,t,n){let o=v(t.episode_id).trim()||`ep_${String(n+1).padStart(3,"0")}`,i=uk(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 te(t.scenes)){s.push(pk(e,a));for(let d of te(a.actions)){let p=lk(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(`
959
- `).trim()}}function ZA(e,t=jh){let n=e.text.split(/\r?\n/),o=n.flatMap(c=>ak(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:Ie(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(`
953
+ `),data:m},u.ok?J:Wn]})}import*as nr from"node:path";import*as gy from"node:path";function my(e,t){let n=he(t);return gy.join(e,`${n}.json`)}function ns(e){return{read(t){let n=my(e,t);return Co(n)?rr(n):null},write(t){tc(my(e,t.key),t)}}}function fl(){return{read(){return null},write(){}}}function ml(e){if(Array.isArray(e))return`[${e.map(t=>ml(t)).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${ml(t[n])}`).join(",")}}`}return JSON.stringify(e)}function gl(e){return he(ml(e))}function hl(e,t,n){return{key:e,signature:t,value:n,createdAt:new Date().toISOString()}}function gk(e,t){return[e.trim(),t.trim()].filter(Boolean).join(`
954
+
955
+ `)}function yy(e,t){return{system:gk(e.instruction,e.format),user:e.input?e.input({parcel:t}):String(t)}}function hk(e,t,n){if(e.kind==="llm"){if(!n.executor)throw new Error("loom llm task requires run({ executor })");let o=yy(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 Ka(e){return{kind:"root",children:e}}function _l(e,t,n){return{kind:"scope",scope:e,data:n,children:t}}function os(e){return{kind:"parcel",data:e}}function rs(e){return{kind:"llm",...e}}var yl=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 Sk(this.input,this.steps,t)}};function ja(e){return new yl(e)}async function yk(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 wk(e,t){let n=t.partition(e);return Ka(n.map(o=>{let i=t.chunk(o).map(r=>os(r));return _l(t.scope,i,o)}))}function wl(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(...wl(r,s))}return o}function is(e,t){return e?.(t),t}async function xk(e,t){return is(e.validate,await e.run({parcel:t}))}async function _k(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 hy(e,t,n){return is(e.validate,e.parse({text:n.text,parcel:t,raw:n.raw}))}function wy(e,t,n){if(e.kind==="parcel"){let i=t[n.index];return n.index+=1,os(i)}let o=e.children.map(i=>wy(i,t,n));return e.kind==="root"?Ka(o):_l(e.scope,o,e.data)}function Ek(e){return e.children.every(t=>t.kind==="parcel")}async function xy(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 xy(y,t,n,o,[...i,`${y.kind}:${w}`]))}let s=e.kind==="root"?Ka(r):_l(e.scope,r,e.data),c=t==="root"&&s.kind==="root",a=s.kind==="scope"&&s.scope===t;if(!c&&!a||!Ek(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})}`,h=gl({step:"reduce",scope:t,version:f,items:d,scopeData:p,salt:o.checkpointSalt}),m=await xl(o.checkpoint,u,h);if(m.hit)return o.report.reused+=1,os(is(n.validate,m.value));let g=is(n.validate,await n.run(d,{scope:p,scopeName:l}));return o.report.ran+=1,await o.checkpoint.write(hl(u,h,g)),os(g)}async function xl(e,t,n){let o=await e.read(t);return o&&o.signature===n?{hit:!0,value:o.value}:{hit:!1}}async function Sk(e,t,n){let o={executor:n.executor,signal:n.signal,checkpointSalt:n.checkpointSalt,checkpoint:n.checkpoint??fl(),concurrency:n.concurrency??4,report:{reused:0,ran:0}},i=null,r=e;for(let c of t){if(c.kind==="split"){i=wk(r,c.spec),r=i;continue}if(i||(i=Ka([os(r)])),c.kind==="extract"){let a=wl(i),d=await yk(a,o.concurrency,async p=>{let l=hk(c.task,p.parcel,o),f=gl(l.payload),u=`extract:${p.path.join("/")}:${f}`;if(c.task.kind==="llm"){let g=await xl(o.checkpoint,u,f);if(g.hit)return o.report.reused+=1,o.executor?.recordReuse(c.task.taskId),hy(c.task,p.parcel,g.value);let w=l.request??yy(c.task,p.parcel),y=await _k(c.task,w,o),x=hy(c.task,p.parcel,y);return o.report.ran+=1,await o.checkpoint.write(hl(u,f,y)),x}let h=await xl(o.checkpoint,u,f);if(h.hit)return o.report.reused+=1,is(c.task.validate,h.value);let m=await xk(c.task,p.parcel);return o.report.ran+=1,await o.checkpoint.write(hl(u,f,m)),m});i=wy(i,d,{index:0}),r=i;continue}i=await xy(i,c.scope,c.task,o,[]),r=i}if(!i)return{value:r,report:o.report};let s=wl(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 Sy={episodeInputMaxChars:6e3,episodeChunkTargetChars:4800,arcEpisodeCount:10,finalMaxInputChars:12e3},Ik="\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",Ak=["\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(`
956
+ `),kk="\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",bk=["\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(`
957
+ `),Ok="\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",vk=["\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(`
958
+ `),Rk="\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",Mk=["\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(`
959
+ `);function Lk(e,t,n){let o=v(t.episode_id).trim()||`ep_${String(n+1).padStart(3,"0")}`,i=Qk(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 te(t.scenes)){s.push(zk(e,a));for(let d of te(a.actions)){let p=Hk(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(`
960
+ `).trim()}}function Nk(e,t=Sy){let n=e.text.split(/\r?\n/),o=n.flatMap(c=>Bk(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:he(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(`
960
961
  `).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(`
961
- `).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:Ie(c)}))}function WA(e,t){let n=Oa(e);return{episodeIndex:t.episodeIndex,episodeId:t.episodeId,episodeNo:t.episodeNo,title:t.title,part:t.part,partCount:t.partCount,synopsis:Vn(n,"\u7247\u6BB5\u6897\u6982"),events:ji(n.get("\u5173\u952E\u4E8B\u4EF6")??""),characterChanges:mk(n.get("\u4EBA\u7269\u53D8\u5316")??""),hook:(n.get("\u7ED3\u5C3E\u94A9\u5B50")??"").trim()}}function XA(e,t){let n=xk(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(`
962
- `),oneLine:Ik(o.map(i=>i.synopsis)),events:Xp(o.flatMap(i=>i.events))}}function ek(e,t){let n=Oa(e);return{episodeIndex:t.episodeIndex,episodeId:t.episodeId,episodeNo:t.episodeNo,title:t.title,synopsis:Vn(n,"\u5206\u96C6\u6897\u6982"),oneLine:Vn(n,"\u5355\u53E5\u6897\u6982"),events:ji(n.get("\u5173\u952E\u4E8B\u4EF6")??"")}}function tk(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:wk(i)})}return n}function nk(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:Ek(i)})}return n}function ok(e,t){let n=Oa(e);return{index:t.index,startEpisodeNo:t.startEpisodeNo,endEpisodeNo:t.endEpisodeNo,synopsis:Vn(n,"\u9636\u6BB5\u6897\u6982"),turns:ji(n.get("\u5173\u952E\u8F6C\u6298")??""),openQuestions:ji(n.get("\u672A\u89E3\u51B3\u60AC\u5FF5")??"")}}function ik(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(`
963
- `),turns:Xp(t.flatMap(i=>i.turns)),openQuestions:Xp(t.flatMap(i=>i.openQuestions))}}function Zp(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(`
964
- `)}function rk(e){let t=Oa(e);return{synopsis:Vn(t,"\u5168\u6587\u6897\u6982"),theme:Vn(t,"\u4E3B\u9898"),logline:Vn(t,"\u4E00\u53E5\u8BDD"),style:Vn(t,"\u98CE\u683C"),mainCharacters:gk(Vn(t,"\u4E3B\u8981\u4EBA\u7269"))}}async function sk(e){let t=e.config??jh,n=te(e.script.episodes);if(n.length===0)throw new x("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)=>qA(e.script,u,g)),i=e.overwrite?o:o.filter(u=>!u.existingSynopsis),r=i.length===0?[]:await ka(e.script).split({scope:"episode",partition:()=>i,chunk:u=>ZA(u,t)}).extract(jr({taskId:"synopsis.chunk",instruction:BA,format:KA,input:({parcel:u})=>hk(u),parse:({text:u,parcel:g})=>WA(u,g)})).reduce("episode",XA).extract(jr({taskId:"synopsis.episode",instruction:jA,format:zA,input:({parcel:u})=>yk(u),parse:({text:u,parcel:g})=>ek(u,g)})).reduce("root",u=>[...u].sort((g,m)=>g.episodeNo-m.episodeNo)).run({concurrency:e.concurrency,checkpoint:Jr(Ki.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:Ak(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:me,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||bk(e.script),l=p?await ck({episodes:a,executor:e.executor,checkpointDir:Ki.join(e.checkpointDir,"arc"),checkpointSalt:e.checkpointSalt,concurrency:e.concurrency,config:t}):{value:[],report:{reused:0,ran:0}},f=p?await dk({episodes:a,arcs:l.value,executor:e.executor,checkpointDir:Ki.join(e.checkpointDir,"final"),checkpointSalt:e.checkpointSalt,config:t}):{value:Ok(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 zh(e,t=Ln){let n=kk(e.concurrency,rl,"--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: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 $r(e),a=t.createExecutor(v(e.llm_config).trim()||void 0),d=v(e.checkpoint).trim()||Ki.join(cl(s),"loom","synopsis-generate"),p=await sk({script:c.script,executor:a,checkpointDir:d,concurrency:n,overwrite:o}),l=new Set,f=te(c.script.episodes);for(let A of p.episodeBriefs){let k=f[A.episodeIndex];k&&(o||!v(k.synopsis).trim())&&v(k.synopsis)!==A.synopsis&&(k.synopsis=A.synopsis,l.add(A.episodeId))}let u=!1;if(u=ba(c.script,"synopsis",p.overview.synopsis,o)||u,u=ba(c.script,"theme",p.overview.theme,o)||u,u=ba(c.script,"logline",p.overview.logline,o)||u,u=ba(c.script,"style",p.overview.style,o)||u,o||te(c.script.main_characters).length===0){let A=p.overview.mainCharacters.map(k=>({name:k.name,role:k.role}));JSON.stringify(c.script.main_characters??[])!==JSON.stringify(A)&&(c.script.main_characters=A,u=!0)}let g=l.size>0||u,m=Dr(c),h=!!m.passed,w=[`${p.episodeBriefs.length} episodes; ${l.size} synopses ${i?"written":"would change"}; overview ${p.overviewGenerated?"generated":"reused"}; validation ${h?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,E;i&&g&&([y,E]=await Cp(c,e,"synopsis.generate"),await Pp(c,m,y),c.remote&&w.push(`revision ${y}; idempotent ${String(E).toLowerCase()}`));let I=Rc(te(m.issues));return i||w.push("Run again with --apply to write the generated synopsis fields."),[{text:[...w,...I].join(`
965
- `),data:{op:i?"synopsis.generate":"synopsis.generate.dry-run",changed:i&&g,revision:y,idempotent:E,validation:m,issues:I,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 ak(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 ck(e){let t=tk(e.episodes,e.config.arcEpisodeCount),n=1,o={reused:0,ran:0};for(;;){let i=await ka(t).split({scope:"arc",partition:c=>c,chunk:c=>[c]}).extract(jr({taskId:"synopsis.arc",instruction:HA,format:QA,input:({parcel:c})=>_k(c),parse:({text:c,parcel:a})=>ok(c,a)})).reduce("arc",c=>Sk(c,"arc")).reduce("root",c=>[...c].sort((a,d)=>a.startEpisodeNo-d.startEpisodeNo)).run({concurrency:e.concurrency,checkpoint:Jr(Ki.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(Zp(e.episodes,r).length<=e.config.finalMaxInputChars||r.length<=1)return{value:r,report:o};t=nk(r,e.config.arcEpisodeCount),n+=1}}async function dk(e){let t=e.arcs;for(;Zp(e.episodes,t).length>e.config.finalMaxInputChars&&t.length>1;)t=[ik(t)];let n=await ka({episodes:e.episodes,arcs:t}).extract(jr({taskId:"synopsis.script-overview",instruction:FA,format:YA,input:({parcel:o})=>Zp(o.episodes,o.arcs),parse:({text:o})=>rk(o)})).run({concurrency:1,checkpoint:Jr(e.checkpointDir),checkpointSalt:e.checkpointSalt,executor:e.executor});return{value:n.value,report:n.report}}function pk(e,t){let n=ee(t.environment)?t.environment:{},o=v(n.space).trim(),i=v(n.time).trim(),r=_o(t),s=te(r.locations).map(p=>Wp(e,"locations","location_id","location_name",v(p.location_id))).filter(p=>p),c=te(r.actors).map(p=>Wp(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 lk(e,t){let n=v(t.type).trim();if(n==="dialogue"){let i=Bh(e,t),r=v(t.content).trim();return r?`[\u5BF9\u767D] ${i?`${i}\uFF1A`:""}${r}`:""}if(n==="inner_thought"){let i=Bh(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 Bh(e,t){let n=t.speaker;if(!ee(n))return"";let o=v(n.actor_id).trim();if(o)return Wp(e,"actors","actor_id","actor_name",o)||o;let i=v(n.kind).trim();return i?v(n.label).trim()||i:""}function Wp(e,t,n,o,i){let r=te(e[t]).find(s=>v(s[n])===i);return r?v(r[o]).trim():""}function uk(e,t){let n=/^ep_(\d+)$/.exec(e);return n?Number(n[1]):t+1}function Oa(e){let t=new Map,n=null,o=[],i=()=>{n&&t.set(n,o.join(`
966
- `).trim()),o=[]};for(let r of e.split(/\r?\n/)){let s=fk(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 Kh=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 fk(e){let t=e.trim(),n=/^#{1,6}\s+(.+?)\s*$/.exec(t);if(n){let r=n[1].trim();return Kh.has(r)?{name:r,inline:""}:null}let o=t.search(/[::]/),i=(o>=0?t.slice(0,o):t).trim();return Kh.has(i)?{name:i,inline:o>=0?t.slice(o+1).trim():""}:null}function Vn(e,t){let n=(e.get(t)??"").trim();if(!n)throw new Error(`synopsis output missing section: ${t}`);return n}function ji(e){return e.split(/\r?\n/).map(t=>t.trim()).map(t=>t.replace(/^[-*]\s*/,"").trim()).filter(t=>t.length>0)}function mk(e){return ji(e).map(t=>{let[n,...o]=t.split("|");return{name:v(n).trim(),change:o.join("|").trim()}}).filter(t=>t.name&&t.change)}function gk(e){return ji(e).map(t=>{let[n,...o]=t.split("|");return{name:v(n).trim(),role:o.join("|").trim()}}).filter(t=>t.name&&t.role)}function hk(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(`
967
- `)}function yk(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(`
968
- `)}function wk(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(`
969
- `).trim()}function Ek(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(`
970
- `).trim()}function _k(e){return[`\u5F53\u524D\u9636\u6BB5\uFF1A\u7B2C${e.startEpisodeNo}-${e.endEpisodeNo}\u96C6`,"","\u5206\u96C6\u6897\u6982\uFF1A",e.text].join(`
971
- `)}function xk(e,t){if(e===null)throw new Error(`${t} scope missing`);return e}function Sk(e,t){let n=e[0];if(!n||e.length!==1)throw new Error(`${t} reduce requires exactly one item`);return n}function Ik(e){return e.map(t=>t.trim()).find(t=>t.length>0)??""}function Xp(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 Ak(e){let t=e.replace(/\s+/g," ").trim();return t.length>50?t.slice(0,50):t}function kk(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:J,errorCode:"NUMERIC_OPTION_INVALID",hint:`Pass ${n} ${t}.`,data:{expected:[`${n}: positive integer`],actual:[v(e)]}});return Math.floor(o)}function ba(e,t,n,o){return!o&&v(e[t]).trim()||v(e[t])===n?!1:(e[t]=n,!0)}function bk(e){return!v(e.synopsis).trim()||!v(e.theme).trim()||!v(e.logline).trim()||!v(e.style).trim()||te(e.main_characters).length===0}function Ok(e){return{synopsis:v(e.synopsis).trim(),theme:v(e.theme).trim(),logline:v(e.logline).trim(),style:v(e.style).trim(),mainCharacters:te(e.main_characters).map(t=>({name:v(t.name).trim(),role:v(t.role).trim()})).filter(t=>t.name&&t.role)}}import*as zr from"node:fs";var Qh=3;function el(e){return v(e.project_group_no||process.env.SANDBOX_PROJECT_GROUP_NO).trim()}function tl(e){try{return Np(e)}catch(t){throw t instanceof pe?Eo("SCRIPT API BLOCKED: gateway not configured",t):t}}function Fh(e,t){let n=el(e);if(n&&n!==t.projectGroupNo)throw Hh(t,`configured projectGroupNo=${n}`);let o=tl(t.projectGroupNo);if(o.gatewayBase!==t.apiBaseUrl)throw Hh(t,`configured apiBaseUrl=${o.gatewayBase}`);return o}function Hh(e,t){return new x("The configured remote does not match this working copy.",{exitCode:b,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 nl(e){let t;try{t=JSON.parse(zr.readFileSync(e,"utf-8"))}catch(n){throw new x("The local script is missing or invalid JSON.",{exitCode:b,errorCode:"SCRIPT_JSON_INVALID",hint:"Fix the local script JSON before continuing.",data:{actual:[e,n instanceof Error?n.message:String(n)]}})}if(!ee(t))throw new x("The script root must be a JSON object.",{exitCode:b,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 Yh(e){return String(e.code)==="9002"||e.message.includes("\u7248\u672C\u51B2\u7A81")}function va(e){let t=e.status!==null&&e.status>=200&&e.status<300&&e.code===null;return e.status===null||e.status>=500||t}function qh(e){let t=Number(e.revision);if(!Number.isInteger(t)||t<0)throw new x("The gateway returned an invalid snapshot revision.",{exitCode:me,errorCode:"PUBLISH_OUTCOME_UNKNOWN",hint:"Inspect the remote script before retrying.",data:{actual:[JSON.stringify(e)]}});return t}function Zh(e,t){return new x("The publish outcome could not be confirmed after retrying.",{exitCode:me,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 vk(e,t,n,o,i,r){let s=[];for(let c=1;c<=Qh;c+=1){let a;try{a=await e.getSnapshot()}catch(p){if(p instanceof pe&&va(p)){s.push(`snapshot attempt ${c}: ${p.message}`);continue}throw p instanceof pe?Eo("PUBLISH BLOCKED: snapshot query failed",p):p}if(a===null||!ee(a.script))throw new x("The managed working copy no longer has a remote script.",{exitCode:b,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=qh(a);if($e(a.script)===o&&a.validationStatus==="valid")return{revision:d,patchedFromRevision:d,attempts:c,recovered:d!==i.baseRevision};Rt(t,o);try{let p=await e.publishPatch({baseRevision:d,old:a.script,edited:n,validation:r}),l=ee(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 pe&&(Yh(p)||va(p))){s.push(`patch attempt ${c}: ${p.message}`);continue}throw p instanceof pe?Eo("PUBLISH BLOCKED: patch failed",p):p}}throw Zh(i.baseRevision,s)}async function Rk(e,t,n,o,i){let r=[];for(let s=1;s<=Qh;s+=1){let c;try{c=await e.getSnapshot()}catch(a){if(a instanceof pe&&va(a)){r.push(`snapshot attempt ${s}: ${a.message}`);continue}throw a instanceof pe?Eo("PUBLISH BLOCKED: snapshot query failed",a):a}if(c!==null){let a=qh(c);if(ee(c.script)&&$e(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:b,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}`]}})}Rt(t,o);try{let a=await e.publishPatch({baseRevision:0,old:{},edited:n,validation:i}),d=ee(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 pe&&(Yh(a)||va(a))){r.push(`patch attempt ${s}: ${a.message}`);continue}throw a instanceof pe?Eo("PUBLISH BLOCKED: patch failed",a):a}}throw Zh(0,r)}async function Wh(e){let t=Se(e),n=!!e.discard_local,o=er(t),i=is(t),r=zr.existsSync(t),s=Wi(t);if(r&&i===null&&!n)throw new x("The target is an unmanaged local script.",{exitCode:b,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&&$e(nl(t))!==i.baseContentHash)throw new x("The working copy has unpublished local changes.",{exitCode:b,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?Fh(e,i):tl(el(e)||null),a;try{a=await c.getSnapshot()}catch(l){throw l instanceof pe?Eo("CHECKOUT BLOCKED: snapshot query failed",l):l}if(a===null||!ee(a.script))throw new x("No remote script_v2 snapshot exists for this project.",{exitCode:b,errorCode:"REMOTE_SCRIPT_NOT_FOUND",hint:"Use the ingest/create workflow and publish the first script instead of checkout.",data:{actual:[`projectGroupNo=${c.projectGroupNo}`]}});Xi(t,s);let d=$e(a.script);return je(t,a.script),rs(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 Xh(e){let t=Se(e),n=zr.existsSync(t),o=is(t),i=n&&o!==null?$e(nl(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 ey(e){let t=Se(e),n=nl(t),o=$e(n),i=is(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=Up(n);if(!r.passed)throw new x("The local script does not pass its declared Script version validation.",{exitCode:b,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=ss(n).episodes.length,c={status:"valid",summary:{passed:!0,hasBlocking:!1,stats:r.stats??{},issueCount:0}};if(i!==null){let p=Fh(e,i),l=await vk(p,t,n,o,i,c);return rs(t,{schemaVersion:1,projectGroupNo:p.projectGroupNo,apiBaseUrl:p.gatewayBase,baseRevision:l.revision,baseContentHash:o}),await Kc(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=tl(el(e)||null),d=await Rk(a,t,n,o,c);return rs(t,{schemaVersion:1,projectGroupNo:a.projectGroupNo,apiBaseUrl:a.gatewayBase,baseRevision:d.revision,baseContentHash:o}),await Kc(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 ty(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",`
962
+ `).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:he(c)}))}function Uk(e,t){let n=Ha(e);return{episodeIndex:t.episodeIndex,episodeId:t.episodeId,episodeNo:t.episodeNo,title:t.title,part:t.part,partCount:t.partCount,synopsis:qn(n,"\u7247\u6BB5\u6897\u6982"),events:or(n.get("\u5173\u952E\u4E8B\u4EF6")??""),characterChanges:Yk(n.get("\u4EBA\u7269\u53D8\u5316")??""),hook:(n.get("\u7ED3\u5C3E\u94A9\u5B50")??"").trim()}}function Ck(e,t){let n=nb(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(`
963
+ `),oneLine:ib(o.map(i=>i.synopsis)),events:Il(o.flatMap(i=>i.events))}}function Pk(e,t){let n=Ha(e);return{episodeIndex:t.episodeIndex,episodeId:t.episodeId,episodeNo:t.episodeNo,title:t.title,synopsis:qn(n,"\u5206\u96C6\u6897\u6982"),oneLine:qn(n,"\u5355\u53E5\u6897\u6982"),events:or(n.get("\u5173\u952E\u4E8B\u4EF6")??"")}}function Tk(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:Xk(i)})}return n}function Vk(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:eb(i)})}return n}function $k(e,t){let n=Ha(e);return{index:t.index,startEpisodeNo:t.startEpisodeNo,endEpisodeNo:t.endEpisodeNo,synopsis:qn(n,"\u9636\u6BB5\u6897\u6982"),turns:or(n.get("\u5173\u952E\u8F6C\u6298")??""),openQuestions:or(n.get("\u672A\u89E3\u51B3\u60AC\u5FF5")??"")}}function Dk(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(`
964
+ `),turns:Il(t.flatMap(i=>i.turns)),openQuestions:Il(t.flatMap(i=>i.openQuestions))}}function El(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(`
965
+ `)}function Gk(e){let t=Ha(e);return{synopsis:qn(t,"\u5168\u6587\u6897\u6982"),theme:qn(t,"\u4E3B\u9898"),logline:qn(t,"\u4E00\u53E5\u8BDD"),style:qn(t,"\u98CE\u683C"),mainCharacters:qk(qn(t,"\u4E3B\u8981\u4EBA\u7269"))}}async function Jk(e){let t=e.config??Sy,n=te(e.script.episodes);if(n.length===0)throw new E("No episodes found in script.",{exitCode:G,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,h)=>Lk(e.script,u,h)),i=e.overwrite?o:o.filter(u=>!u.existingSynopsis),r=i.length===0?[]:await ja(e.script).split({scope:"episode",partition:()=>i,chunk:u=>Nk(u,t)}).extract(rs({taskId:"synopsis.chunk",instruction:Ik,format:Ak,input:({parcel:u})=>Zk(u),parse:({text:u,parcel:h})=>Uk(u,h)})).reduce("episode",Ck).extract(rs({taskId:"synopsis.episode",instruction:kk,format:bk,input:({parcel:u})=>Wk(u),parse:({text:u,parcel:h})=>Pk(u,h)})).reduce("root",u=>[...u].sort((h,m)=>h.episodeNo-m.episodeNo)).run({concurrency:e.concurrency,checkpoint:ns(nr.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:rb(u.existingSynopsis),events:[]}),d=a.filter(u=>!u.synopsis.trim()).map(u=>u.episodeId);if(d.length>0)throw new E("Some episode synopses are still missing.",{exitCode:me,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||ab(e.script),l=p?await Kk({episodes:a,executor:e.executor,checkpointDir:nr.join(e.checkpointDir,"arc"),checkpointSalt:e.checkpointSalt,concurrency:e.concurrency,config:t}):{value:[],report:{reused:0,ran:0}},f=p?await jk({episodes:a,arcs:l.value,executor:e.executor,checkpointDir:nr.join(e.checkpointDir,"final"),checkpointSalt:e.checkpointSalt,config:t}):{value:cb(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 Iy(e,t=zn){let n=sb(e.concurrency,Rl,"--concurrency"),o=!!e.overwrite,i=!!e.apply,r=!!e.dry_run;if(i&&r)throw new E("--apply and --dry-run are mutually exclusive.",{exitCode:G,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 Xr(e),a=t.createExecutor(v(e.llm_config).trim()||void 0),d=v(e.checkpoint).trim()||nr.join(Nl(s),"loom","synopsis-generate"),p=await Jk({script:c.script,executor:a,checkpointDir:d,concurrency:n,overwrite:o}),l=new Set,f=te(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=za(c.script,"synopsis",p.overview.synopsis,o)||u,u=za(c.script,"theme",p.overview.theme,o)||u,u=za(c.script,"logline",p.overview.logline,o)||u,u=za(c.script,"style",p.overview.style,o)||u,o||te(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 h=l.size>0||u,m=es(c),g=!!m.passed,w=[`${p.episodeBriefs.length} episodes; ${l.size} synopses ${i?"written":"would change"}; overview ${p.overviewGenerated?"generated":"reused"}; validation ${g?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,x;i&&h&&([y,x]=await rl(c,e,"synopsis.generate"),await il(c,m,y),c.remote&&w.push(`revision ${y}; idempotent ${String(x).toLowerCase()}`));let S=Fc(te(m.issues));return i||w.push("Run again with --apply to write the generated synopsis fields."),[{text:[...w,...S].join(`
966
+ `),data:{op:i?"synopsis.generate":"synopsis.generate.dry-run",changed:i&&h,revision:y,idempotent:x,validation:m,issues:S,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()}},J]}function Bk(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 Kk(e){let t=Tk(e.episodes,e.config.arcEpisodeCount),n=1,o={reused:0,ran:0};for(;;){let i=await ja(t).split({scope:"arc",partition:c=>c,chunk:c=>[c]}).extract(rs({taskId:"synopsis.arc",instruction:Ok,format:vk,input:({parcel:c})=>tb(c),parse:({text:c,parcel:a})=>$k(c,a)})).reduce("arc",c=>ob(c,"arc")).reduce("root",c=>[...c].sort((a,d)=>a.startEpisodeNo-d.startEpisodeNo)).run({concurrency:e.concurrency,checkpoint:ns(nr.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(El(e.episodes,r).length<=e.config.finalMaxInputChars||r.length<=1)return{value:r,report:o};t=Vk(r,e.config.arcEpisodeCount),n+=1}}async function jk(e){let t=e.arcs;for(;El(e.episodes,t).length>e.config.finalMaxInputChars&&t.length>1;)t=[Dk(t)];let n=await ja({episodes:e.episodes,arcs:t}).extract(rs({taskId:"synopsis.script-overview",instruction:Rk,format:Mk,input:({parcel:o})=>El(o.episodes,o.arcs),parse:({text:o})=>Gk(o)})).run({concurrency:1,checkpoint:ns(e.checkpointDir),checkpointSalt:e.checkpointSalt,executor:e.executor});return{value:n.value,report:n.report}}function zk(e,t){let n=ee(t.environment)?t.environment:{},o=v(n.space).trim(),i=v(n.time).trim(),r=Uo(t),s=te(r.locations).map(p=>Sl(e,"locations","location_id","location_name",v(p.location_id))).filter(p=>p),c=te(r.actors).map(p=>Sl(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 Hk(e,t){let n=v(t.type).trim();if(n==="dialogue"){let i=_y(e,t),r=v(t.content).trim();return r?`[\u5BF9\u767D] ${i?`${i}\uFF1A`:""}${r}`:""}if(n==="inner_thought"){let i=_y(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 _y(e,t){let n=t.speaker;if(!ee(n))return"";let o=v(n.actor_id).trim();if(o)return Sl(e,"actors","actor_id","actor_name",o)||o;let i=v(n.kind).trim();return i?v(n.label).trim()||i:""}function Sl(e,t,n,o,i){let r=te(e[t]).find(s=>v(s[n])===i);return r?v(r[o]).trim():""}function Qk(e,t){let n=/^ep_(\d+)$/.exec(e);return n?Number(n[1]):t+1}function Ha(e){let t=new Map,n=null,o=[],i=()=>{n&&t.set(n,o.join(`
967
+ `).trim()),o=[]};for(let r of e.split(/\r?\n/)){let s=Fk(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 Ey=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 Fk(e){let t=e.trim(),n=/^#{1,6}\s+(.+?)\s*$/.exec(t);if(n){let r=n[1].trim();return Ey.has(r)?{name:r,inline:""}:null}let o=t.search(/[::]/),i=(o>=0?t.slice(0,o):t).trim();return Ey.has(i)?{name:i,inline:o>=0?t.slice(o+1).trim():""}:null}function qn(e,t){let n=(e.get(t)??"").trim();if(!n)throw new Error(`synopsis output missing section: ${t}`);return n}function or(e){return e.split(/\r?\n/).map(t=>t.trim()).map(t=>t.replace(/^[-*]\s*/,"").trim()).filter(t=>t.length>0)}function Yk(e){return or(e).map(t=>{let[n,...o]=t.split("|");return{name:v(n).trim(),change:o.join("|").trim()}}).filter(t=>t.name&&t.change)}function qk(e){return or(e).map(t=>{let[n,...o]=t.split("|");return{name:v(n).trim(),role:o.join("|").trim()}}).filter(t=>t.name&&t.role)}function Zk(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(`
968
+ `)}function Wk(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(`
969
+ `)}function Xk(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(`
970
+ `).trim()}function eb(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(`
971
+ `).trim()}function tb(e){return[`\u5F53\u524D\u9636\u6BB5\uFF1A\u7B2C${e.startEpisodeNo}-${e.endEpisodeNo}\u96C6`,"","\u5206\u96C6\u6897\u6982\uFF1A",e.text].join(`
972
+ `)}function nb(e,t){if(e===null)throw new Error(`${t} scope missing`);return e}function ob(e,t){let n=e[0];if(!n||e.length!==1)throw new Error(`${t} reduce requires exactly one item`);return n}function ib(e){return e.map(t=>t.trim()).find(t=>t.length>0)??""}function Il(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 rb(e){let t=e.replace(/\s+/g," ").trim();return t.length>50?t.slice(0,50):t}function sb(e,t,n){if(e==null||e==="")return t;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new E(`${n} must be a positive integer.`,{exitCode:G,errorCode:"NUMERIC_OPTION_INVALID",hint:`Pass ${n} ${t}.`,data:{expected:[`${n}: positive integer`],actual:[v(e)]}});return Math.floor(o)}function za(e,t,n,o){return!o&&v(e[t]).trim()||v(e[t])===n?!1:(e[t]=n,!0)}function ab(e){return!v(e.synopsis).trim()||!v(e.theme).trim()||!v(e.logline).trim()||!v(e.style).trim()||te(e.main_characters).length===0}function cb(e){return{synopsis:v(e.synopsis).trim(),theme:v(e.theme).trim(),logline:v(e.logline).trim(),style:v(e.style).trim(),mainCharacters:te(e.main_characters).map(t=>({name:v(t.name).trim(),role:v(t.role).trim()})).filter(t=>t.name&&t.role)}}import*as ss from"node:fs";var ky=3;function Al(e){return v(e.project_group_no||process.env.SANDBOX_PROJECT_GROUP_NO).trim()}function kl(e){try{return nl(e)}catch(t){throw t instanceof pe?No("SCRIPT API BLOCKED: gateway not configured",t):t}}function by(e,t){let n=Al(e);if(n&&n!==t.projectGroupNo)throw Ay(t,`configured projectGroupNo=${n}`);let o=kl(t.projectGroupNo);if(o.gatewayBase!==t.apiBaseUrl)throw Ay(t,`configured apiBaseUrl=${o.gatewayBase}`);return o}function Ay(e,t){return new E("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 bl(e){let t;try{t=JSON.parse(ss.readFileSync(e,"utf-8"))}catch(n){throw new E("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(!ee(t))throw new E("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 Oy(e){return String(e.code)==="9002"||e.message.includes("\u7248\u672C\u51B2\u7A81")}function Qa(e){let t=e.status!==null&&e.status>=200&&e.status<300&&e.code===null;return e.status===null||e.status>=500||t}function vy(e){let t=Number(e.revision);if(!Number.isInteger(t)||t<0)throw new E("The gateway returned an invalid snapshot revision.",{exitCode:me,errorCode:"PUBLISH_OUTCOME_UNKNOWN",hint:"Inspect the remote script before retrying.",data:{actual:[JSON.stringify(e)]}});return t}function Ry(e,t){return new E("The publish outcome could not be confirmed after retrying.",{exitCode:me,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 db(e,t,n,o,i,r){let s=[];for(let c=1;c<=ky;c+=1){let a;try{a=await e.getSnapshot()}catch(p){if(p instanceof pe&&Qa(p)){s.push(`snapshot attempt ${c}: ${p.message}`);continue}throw p instanceof pe?No("PUBLISH BLOCKED: snapshot query failed",p):p}if(a===null||!ee(a.script))throw new E("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=vy(a);if(De(a.script)===o&&a.validationStatus==="valid")return{revision:d,patchedFromRevision:d,attempts:c,recovered:d!==i.baseRevision};Tt(t,o);try{let p=await e.publishPatch({baseRevision:d,old:a.script,edited:n,validation:r}),l=ee(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 pe&&(Oy(p)||Qa(p))){s.push(`patch attempt ${c}: ${p.message}`);continue}throw p instanceof pe?No("PUBLISH BLOCKED: patch failed",p):p}}throw Ry(i.baseRevision,s)}async function pb(e,t,n,o,i){let r=[];for(let s=1;s<=ky;s+=1){let c;try{c=await e.getSnapshot()}catch(a){if(a instanceof pe&&Qa(a)){r.push(`snapshot attempt ${s}: ${a.message}`);continue}throw a instanceof pe?No("PUBLISH BLOCKED: snapshot query failed",a):a}if(c!==null){let a=vy(c);if(ee(c.script)&&De(c.script)===o&&c.validationStatus==="valid")return{revision:a,patchedFromRevision:0,attempts:s,recovered:!0};throw new E("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}`]}})}Tt(t,o);try{let a=await e.publishPatch({baseRevision:0,old:{},edited:n,validation:i}),d=ee(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 pe&&(Oy(a)||Qa(a))){r.push(`patch attempt ${s}: ${a.message}`);continue}throw a instanceof pe?No("PUBLISH BLOCKED: patch failed",a):a}}throw Ry(0,r)}async function My(e){let t=Ae(e),n=!!e.discard_local,o=fr(t),i=xs(t),r=ss.existsSync(t),s=lr(t);if(r&&i===null&&!n)throw new E("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&&De(bl(t))!==i.baseContentHash)throw new E("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?by(e,i):kl(Al(e)||null),a;try{a=await c.getSnapshot()}catch(l){throw l instanceof pe?No("CHECKOUT BLOCKED: snapshot query failed",l):l}if(a===null||!ee(a.script))throw new E("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}`]}});ur(t,s);let d=De(a.script);return ze(t,a.script),_s(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)}},J]}function Ly(e){let t=Ae(e),n=ss.existsSync(t),o=xs(t),i=n&&o!==null?De(bl(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}}},J]}async function Ny(e){let t=Ae(e),n=bl(t),o=De(n),i=xs(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}},J];let r=ol(n);if(!r.passed)throw new E("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=Es(n).episodes.length,c={status:"valid",summary:{passed:!0,hasBlocking:!1,stats:r.stats??{},issueCount:0}};if(i!==null){let p=by(e,i),l=await db(p,t,n,o,i,c);return _s(t,{schemaVersion:1,projectGroupNo:p.projectGroupNo,apiBaseUrl:p.gatewayBase,baseRevision:l.revision,baseContentHash:o}),await cd(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}},J]}let a=kl(Al(e)||null),d=await pb(a,t,n,o,c);return _s(t,{schemaVersion:1,projectGroupNo:a.projectGroupNo,apiBaseUrl:a.gatewayBase,baseRevision:d.revision,baseContentHash:o}),await cd(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}},J]}function Uy(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",`
972
973
  Example:
973
974
  scriptctl migrate -p ./old-script.json -o ./script-v4.json --to 4
974
- `).action(q(Ch,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-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",`
975
+ `).action(q(fy,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-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",`
975
976
  Example:
976
977
  scriptctl ingest --source-path ./draft.md --workspace-path ./workspace
977
- `).action(q(r=>th(r,n),t));o.command("status").description("Show ingest workspace progress").option("-w, --workspace-path <path>","Workspace directory").action(q(oh,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",`
978
+ `).action(q(r=>Ph(r,n),t));o.command("status").description("Show ingest workspace progress").option("-w, --workspace-path <path>","Workspace directory").action(q(Vh,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",`
978
979
  Example:
979
980
  scriptctl ingest skip -w ./workspace --episode 7 --reason "provider policy block"
980
- `).action(q(ih,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",`
981
+ `).action(q($h,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",`
981
982
  Example:
982
983
  scriptctl evidence -p ./script.json -s /Volumes/NAS/videos -w ./workspace --force
983
- `).action(q(rh,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(q(uh,t)),Pc(e.command("checkout")).description("Download a remote script into a managed local copy").option("--discard-local","Replace an existing dirty local copy").action(q(Wh,t)),ae(e.command("status"),"read").description("Show local working-copy state").action(q(Xh,t)),Pc(e.command("publish")).description("Validate and publish the local working copy").action(q(ey,t)),ae(e.command("create")).description("Create an empty script").option("--title <title>","Script title").option("--force","Replace an existing script file").action(q(Mh,t)),ae(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(q(r=>Eh(r,n),t));let i=e.command("synopsis").description("Generate synopsis fields with an LLM").action(()=>i.outputHelp());ae(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(q(r=>zh(r,n),t))}function Nk(e,t=Ln){let n=new Mk("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(ui(),"-v, --version","Show the scriptctl version");return ty(n,e,t),Rf(n,e),_u(n,e),Wu(n,e),Fu(n,e),n}function Ra(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 oy(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=Ra(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 Uk(e,t){return t==="--"?!0:t.startsWith("--")?Ra(e,t)!==void 0:oy(e,t).recognized}function ny(e,t,n){return n===void 0||n==="--"?!1:t.required?!Uk(e,n):t.optional&&!n.startsWith("-")}function Pk(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=Ra(n,i);s&&!i.includes("=")&&ny(n,s,t[o+1])&&(o+=1);continue}if(i.startsWith("-")){let s=oy(n,i);if(s.recognized&&s.json)return!0;s.recognized&&s.valueOption&&!s.hasAttachedValue&&ny(n,s.valueOption,t[o+1])&&(o+=1);continue}let r=n.commands.find(s=>s.name()===i);r&&(n=r)}return!1}function Ck(e,t){let n=e;for(let r=0;r<t.length;r+=1){let s=t[r];if(s.startsWith("-")){let a=Ra(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 Tk(e){return e.message.replace(/^error:\s*/i,"").replace(/\.$/,"")}async function TB(e=null,t=Ln){bu();let n=e??process.argv.slice(2),o={jsonMode:!1,exitCode:B},i=Nk(o,t);if(o.jsonMode=Pk(i,n),n.length===0)return i.outputHelp(),B;try{return await i.parseAsync(n,{from:"user"}),o.exitCode}catch(r){if(r instanceof Lk)return r.code==="commander.help"||r.code==="commander.helpDisplayed"||r.code==="commander.version"?B:dr(new x(Tk(r),{exitCode:J,errorCode:"USAGE_ERROR",hint:`Run '${Ck(i,n)}'.`}),o.jsonMode);if(r instanceof x)return dr(r,o.jsonMode);if(r instanceof C)return dr(new x(tn(r.failure),{exitCode:70,errorCode:"RUNTIME_ERROR"}),o.jsonMode);let s=r instanceof Error?r.message:String(r);return dr(new x(s,{exitCode:70,errorCode:"RUNTIME_ERROR"}),o.jsonMode)}}export{Nk as a,TB as b};
984
+ `).action(q(Dh,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(q(jh,t)),Xc(e.command("checkout")).description("Download a remote script into a managed local copy").option("--discard-local","Replace an existing dirty local copy").action(q(My,t)),ce(e.command("status"),"read").description("Show local working-copy state").action(q(Ly,t)),Xc(e.command("publish")).description("Validate and publish the local working copy").action(q(Ny,t)),ce(e.command("create")).description("Create an empty script").option("--title <title>","Script title").option("--force","Replace an existing script file").action(q(cy,t)),ce(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(q(r=>Zh(r,n),t));let i=e.command("synopsis").description("Generate synopsis fields with an LLM").action(()=>i.outputHelp());ce(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(q(r=>Iy(r,n),t))}function fb(e,t=zn){let n=new lb("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(bi(),"-v, --version","Show the scriptctl version");return Uy(n,e,t),Om(n,e),ju(n,e),km(n,e),xf(n,e),n}function Fa(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 Py(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=Fa(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 mb(e,t){return t==="--"?!0:t.startsWith("--")?Fa(e,t)!==void 0:Py(e,t).recognized}function Cy(e,t,n){return n===void 0||n==="--"?!1:t.required?!mb(e,n):t.optional&&!n.startsWith("-")}function gb(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=Fa(n,i);s&&!i.includes("=")&&Cy(n,s,t[o+1])&&(o+=1);continue}if(i.startsWith("-")){let s=Py(n,i);if(s.recognized&&s.json)return!0;s.recognized&&s.valueOption&&!s.hasAttachedValue&&Cy(n,s.valueOption,t[o+1])&&(o+=1);continue}let r=n.commands.find(s=>s.name()===i);r&&(n=r)}return!1}function hb(e,t){let n=e;for(let r=0;r<t.length;r+=1){let s=t[r];if(s.startsWith("-")){let a=Fa(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 yb(e){return e.message.replace(/^error:\s*/i,"").replace(/\.$/,"")}async function qK(e=null,t=zn){qu();let n=e??process.argv.slice(2),o={jsonMode:!1,exitCode:J},i=fb(o,t);if(o.jsonMode=gb(i,n),n.length===0)return i.outputHelp(),J;try{return await i.parseAsync(n,{from:"user"}),o.exitCode}catch(r){if(r instanceof ub)return r.code==="commander.help"||r.code==="commander.helpDisplayed"||r.code==="commander.version"?J:Sr(new E(yb(r),{exitCode:G,errorCode:"USAGE_ERROR",hint:`Run '${hb(i,n)}'.`}),o.jsonMode);if(r instanceof E)return Sr(r,o.jsonMode);if(r instanceof P)return Sr(new E(ln(r.failure),{exitCode:70,errorCode:"RUNTIME_ERROR"}),o.jsonMode);let s=r instanceof Error?r.message:String(r);return Sr(new E(s,{exitCode:70,errorCode:"RUNTIME_ERROR"}),o.jsonMode)}}export{fb as a,qK as b};