@lingjingai/scriptctl 0.75.0 → 0.77.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/changes/0.76.0.md +18 -0
- package/changes/0.77.0.md +13 -0
- package/dist/bin.js +1 -1
- package/dist/{chunk-7AXMHZL5.js → chunk-NKSTP54U.js} +197 -190
- package/dist/cli.js +1 -1
- package/dist/review-agent.js +348 -344
- package/package.json +3 -1
- package/scripts/review-view.html +836 -0
- package/scripts/review-view.mjs +662 -0
- package/skills/scriptctl/SKILL.md +2 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{Command as
|
|
2
|
-
`)}list(t,n="*"){if(!Ce.existsSync(t))return[];let o=
|
|
1
|
+
import{Command as AR,CommanderError as kR}from"commander";import*as fd from"node:crypto";import*as Fi from"node:fs";import*as jr from"node:path";import*as Ce from"node:fs";import*as Pt from"node:path";var sa=class{workspace;constructor(t){this.workspace=t}get sourceText(){return Pt.join(this.workspace,"source.txt")}get directDir(){return Pt.join(this.workspace,"draft","scriptctl","direct")}get directScript(){return Pt.join(this.directDir,"script.initial.json")}get validation(){return Pt.join(this.directDir,"validation.json")}get runState(){return Pt.join(this.directDir,"run_state.json")}get episodeResultsDir(){return Pt.join(this.directDir,"episode_results")}get batchResultsDir(){return Pt.join(this.directDir,"batch_results")}outputScript(t){return Pt.join(t,"script.json")}};function NE(e){let t="";for(let n of e)n==="*"?t+="[^/]*":n==="?"?t+="[^/]":".+^$()[]{}|\\".includes(n)?t+="\\"+n:t+=n;return new RegExp("^"+t+"$")}var ud=class{exists(t){return Ce.existsSync(t)}readText(t){return Ce.readFileSync(t,"utf-8")}writeText(t,n){Ce.mkdirSync(Pt.dirname(t),{recursive:!0}),Ce.writeFileSync(t,n,"utf-8")}readJson(t){return JSON.parse(Ce.readFileSync(t,"utf-8"))}writeJson(t,n){this.writeText(t,JSON.stringify(n,null,2)+`
|
|
2
|
+
`)}list(t,n="*"){if(!Ce.existsSync(t))return[];let o=NE(n),i=Ce.readdirSync(t),r=[];for(let s of i)o.test(s)&&r.push(Pt.join(t,s));return r.sort(),r}delete(t){Ce.existsSync(t)&&Ce.unlinkSync(t)}deleteTree(t){Ce.existsSync(t)&&Ce.rmSync(t,{recursive:!0,force:!0})}copyToPath(t,n){Ce.mkdirSync(Pt.dirname(n),{recursive:!0}),Ce.copyFileSync(t,n)}},aa=new ud;var V=0,B=64,k=66,q=70,Eo=78,Sf=30;var UR=jr.join("draft","scriptctl","direct"),LE=jr.join("workspace","script.json");var If=["\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"],Af=new Set(["actor","location","prop"]);var PR=`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 gR,CommanderError as hR}from"commander";import*as pd 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`+
|
|
82
|
+
worldview: <\u4E16\u754C\u89C2\uFF0C\u53D6\u8FD9\u4E9B\u679A\u4E3E\u4E4B\u4E00\uFF1A`+If.join(" / ")+`>
|
|
83
83
|
style: <\u98CE\u683C\uFF0C\u81EA\u7531\u6587\u672C\uFF0C\u5982 \u90FD\u5E02\u751C\u5BA0 / \u60AC\u7591\u590D\u4EC7>
|
|
84
84
|
title: <\u5267\u540D>
|
|
85
85
|
\u4E3B\u89D2: <\u4E3B\u89D2\u540D1>, <\u4E3B\u89D2\u540D2> \u2190 \u5217\u5728\u8FD9\u91CC\u7684\u8BBE\u4E3A role_type=\u4E3B\u89D2\uFF0C\u5176\u4F59\u89D2\u8272=\u914D\u89D2
|
|
@@ -119,30 +119,30 @@ Rules:
|
|
|
119
119
|
- \u7FA4\u4F53\u8BCD\uFF08\u4F17\u4EBA / \u7FA4\u4F17 / \u56F4\u89C2\u8005 / \u8DEF\u4EBA\u4EEC\uFF09\u4E0D\u8FDB \u4EBA\u7269.md\uFF0C\u767B\u5230 \u53D1\u58F0\u6E90.md \u7528 group \u6216\u5199\u52A8\u4F5C\u65C1\u767D\u3002
|
|
120
120
|
- \u52A8\u4F5C / \u5BF9\u767D\u6B63\u6587\u9010\u5B57\u4FDD\u7559\uFF0C\u4E0D\u8981\u8F6C\u8FF0 / \u7FFB\u8BD1 / \u6982\u62EC / \u52A0\u6CE8\u91CA\uFF1B\u52A8\u4F5C\u79CD\u7C7B\u53EA\u6709 act/dlg/think\u3002
|
|
121
121
|
- \u6BCF\u4E2A\u51FA\u73B0\u5728\u6B63\u6587\u91CC\u7684\u89D2\u8272\uFF0C\u90FD\u8981\u5728 \u4EBA\u7269.md \u7ED9\u51FA\u975E\u7A7A\u63CF\u8FF0\uFF08\u5426\u5219\u6821\u9A8C\u62A5\u9519\uFF09\u3002
|
|
122
|
-
`,S=class extends Error{exitCode;errorCode;hint;data;constructor(t,n){super(t),this.name="CliError",this.exitCode=n.exitCode,this.errorCode=n.errorCode,this.hint=n.hint,this.data=n.data??{}}};function RE(e){return new ia(e)}function Sf(e){return RE(e).directDir}function he(e){let t=e.script_path??e.scriptPath;return Kr.resolve(typeof t=="string"&&t.length>0?t:OE)}function jr(e){return ra.readJson(e)}function ld(e,t){ra.writeJson(e,t)}function ri(e){return ra.exists(e)}function _e(e){return pd.createHash("sha256").update(e,"utf-8").digest("hex")}function ud(e){let t=pd.createHash("sha256"),n=Qi.openSync(e,"r");try{let o=Buffer.alloc(1048576);for(;;){let i=Qi.readSync(n,o,0,o.length,null);if(i<=0)break;t.update(o.subarray(0,i))}}finally{Qi.closeSync(n)}return t.digest("hex")}var Ct={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 Tt(e,t){return typeof e=="string"&&t.some(n=>n===e)}function If(e,t){switch(e){case"policy":return Tt(t,Ct.policy)?{failure_type:e,failure_code:t}:null;case"network":return Tt(t,Ct.network)?{failure_type:e,failure_code:t}:null;case"timeout":return Tt(t,Ct.timeout)?{failure_type:e,failure_code:t}:null;case"rate_limit":return Tt(t,Ct.rate_limit)?{failure_type:e,failure_code:t}:null;case"authentication":return Tt(t,Ct.authentication)?{failure_type:e,failure_code:t}:null;case"authorization":return Tt(t,Ct.authorization)?{failure_type:e,failure_code:t}:null;case"provider":return Tt(t,Ct.provider)?{failure_type:e,failure_code:t}:null;case"media":return Tt(t,Ct.media)?{failure_type:e,failure_code:t}:null;case"response":return Tt(t,Ct.response)?{failure_type:e,failure_code:t}:null;case"pipeline":return Tt(t,Ct.pipeline)?{failure_type:e,failure_code:t}:null;case"validation":return Tt(t,Ct.validation)?{failure_type:e,failure_code:t}:null;case"cancelled":return Tt(t,Ct.cancelled)?{failure_type:e,failure_code:t}:null;case"unknown":return Tt(t,Ct.unknown)?{failure_type:e,failure_code:t}:null;default:return null}}function Vt(e,t){return{...e,...t}}function Fi(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 Hr(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 Af(e,t){if(e.length===0)return Vt({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)?Fi(n):{failure_type:"provider",failure_code:"attempts_exhausted"};return Vt(i,{retryable:e.some(r=>r.retryable),message:t})}function An(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 Df from"node:crypto";import*as Gf from"node:fs";import*as Bf from"node:path";import*as Lf from"node:crypto";var Kn=["action","dialogue","inner_thought","transition"],tn=new Set(Kn),jn=["system","broadcast","offscreen","group"],si=new Set(jn),Hn=["featured","background"],$t=new Set(Hn),Yi=["\u4E3B\u89D2","\u914D\u89D2"],_o=new Set(Yi),sa=["day","night","dawn","dusk"],fd=new Set(sa);function Qr(e){return typeof e=="string"&&fd.has(e)}var md=["interior","exterior"],kf=new Set(md);function mt(e){return e.normalize("NFKC").toLowerCase()}function bf(e){return JSON.stringify([e.code,e.path,e.message])}function gd(e){let t=new Map;for(let n of e){let o=bf(n);t.set(o,(t.get(o)??0)+1)}return t}function hd(e,t){if(e.ok||t.errors.length>=e.errors.length)return!1;let n=gd(e.errors),o=gd(t.errors);for(let[i,r]of o)if(r>(n.get(i)??0))return!1;return!0}function yd(e,t){let n=gd(e),o=[];for(let i of t){let r=bf(i),s=n.get(r)??0;s>0?n.set(r,s-1):o.push(i)}return o}import{customAlphabet as ME}from"nanoid";var qi="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",wd=6,Zi={episode:"ep",scene:"scn",action:"ac",actor:"act",location:"loc",prop:"prp",state:"st"},NE=ME(qi,wd),LE=`[${qi}]`,vf=Object.fromEntries(Object.entries(Zi).map(([e,t])=>[e,new RegExp(`^${t}${LE}{${wd}}$`)]));function $(e,t){return typeof t=="string"&&vf[e].test(t)}var xd="ID_SPACE_EXHAUSTED";function Fr(e,t=new Set,n=NE){let o=Zi[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:xd})}var it=class extends Error{input;constructor(t,n){super(n),this.input=t,this.name="TimestampParseError"}},UE=/^(\d+):(\d{2})(?:\.(\d{1,3}))?$/,PE=/^(\d+):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/;function Of(e){return e?Number(e.padEnd(3,"0")):0}function Rf(e,t){if(!Number.isSafeInteger(t))throw new it(e,"Timestamp exceeds the supported numeric range.");return t}function Mf(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 So(e){let t=e.trim();if(!t)throw new it(e,"Timestamp must not be empty.");let n=t.match(PE);if(n){let c=Number(n[1]),d=Number(n[2]),p=Number(n[3]),l=n[4];if(d>59)throw new it(e,"Hour-form timestamps require minutes between 00 and 59.");if(p>59)throw new it(e,"Timestamp seconds must be between 00 and 59.");let f=Rf(e,((c*60+d)*60+p)*1e3+Of(l));return{canonical:Mf(f,l),milliseconds:f,fractionDigits:l?.length??0}}let o=t.match(UE);if(!o)throw new it(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 it(e,"Timestamp seconds must be between 00 and 59.");let a=Rf(e,(i*60+r)*1e3+Of(s));return{canonical:Mf(a,s),milliseconds:a,fractionDigits:s?.length??0}}function CE(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 TE(e,t){let n=e.milliseconds-t.milliseconds;return e.fractionDigits===0||t.fractionDigits===0?n>=1e3:n>0}function aa(e,t,n){let o=null;e.forEach((i,r)=>{let s=CE(i);if(s===void 0)return;let a=`${t}[${r}].extend.timestamp`;if(typeof s!="string"){n("timestamp_invalid",a,"timestamp must be a string in M:SS, MM:SS, or H:MM:SS form");return}let c;try{c=So(s)}catch(d){if(!(d instanceof it))throw d;n("timestamp_invalid",a,d.message);return}o!==null&&TE(o.timestamp,c)&&n("timestamp_out_of_order",a,`timestamp ${c.canonical} is earlier than Action ${o.actionIndex+1} timestamp ${o.timestamp.canonical}; equal timestamps and sub-second differences against a whole-second mark are allowed`),o={actionIndex:r,timestamp:c}})}var _t=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>Array.isArray(e),ke=e=>typeof e=="string",VE=["state_changes","actor_id","speakers","lines"];function St(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(!_t(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"])ke(e[u])||o("field",`$.${u}`,`${u} must be a string`);let r=new Map,s=new Map,a=new Map,c=(u,h,m,g,w)=>{if(!Qn(u)){o("field",w,`${w} must be an array`);return}u.forEach((y,E)=>{let _=`${w}[${E}]`;if(!_t(y)){o("asset",_,"asset must be an object");return}let x=y[m];if(!ke(x)){o("asset_id",`${_}.${m}`,`${m} required`);return}if(s.has(x)&&o("dup_id",`${_}.${m}`,`duplicate id ${x}`),s.set(x,h),!ke(y[g]))o("asset_name",`${_}.${g}`,`${g} required`);else if(h==="actor"){let v=mt(y[g]),I=a.get(v);I!==void 0?o("dup_actor_name",`${_}.${g}`,`actor name ${y[g]} already belongs to ${I}`):a.set(v,x)}(!ke(y.importance)||!Hn.includes(y.importance))&&o("importance",`${_}.importance`,`importance must be one of ${Hn.join("|")}`),ke(y.description)||o("asset_desc",`${_}.description`,"description must be a string");let A=new Set,b=new Set,U=0;!Qn(y.states)||y.states.length===0?o("states",`${_}.states`,"states must be a non-empty array"):y.states.forEach((v,I)=>{let R=`${_}.states[${I}]`;if(!_t(v)||!ke(v.state_id)){o("state_id",R,"state_id required");return}A.has(v.state_id)&&o("dup_state",R,`duplicate state_id ${v.state_id}`),A.add(v.state_id),v.state_id==="default"&&U++,ke(v.state_name)?(b.has(v.state_name)&&o("dup_state_name",`${R}.state_name`,`duplicate state_name ${v.state_name}`),b.add(v.state_name)):o("state_name",`${R}.state_name`,"state_name required")}),Qn(y.states)&&U!==1&&o("default_state",`${_}.states`,`exactly one 'default' state required, found ${U}`),r.set(x,A)})};c(e.actors,"actor","actor_id","actor_name","$.actors"),c(e.locations,"location","location_id","location_name","$.locations"),c(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&&(!ke(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(!Qn(u)){o("field",g,`${g} must be an array`);return}u.forEach((w,y)=>{if(!_t(w)||!ke(w[m])){o("ref",`${g}[${y}]`,`${m} required`);return}d(w[m],w.state_id,h,`${g}[${y}]`)})},l=(u,h,m,g)=>{if(!_t(u)){o("action",h,"action must be an object");return}for(let y of VE)y in u&&o("legacy_field",`${h}.${y}`,`v3 forbids action.${y}`);let w=u.type;if((!ke(w)||!Kn.includes(w))&&o("action_type",`${h}.type`,`invalid action type ${String(w)}`),ke(u.content)||o("content",`${h}.content`,"content must be a plain-text string"),w==="dialogue"||w==="inner_thought"){let y=u.speaker;if(!_t(y))o("speaker",`${h}.speaker`,"dialogue/inner_thought needs a speaker");else if("kind"in y)(!ke(y.kind)||!jn.includes(y.kind))&&o("speaker_kind",`${h}.speaker.kind`,"invalid non-actor speaker kind");else if(ke(y.actor_id)){if(d(y.actor_id,y.state_id,"actor",`${h}.speaker`),!m.has(y.actor_id)){let E=r.get(y.actor_id),_=ke(y.state_id)&&E?.has(y.state_id)?y.state_id:E?.has("default")?"default":E?.values().next().value,x=g&&_?`scriptctl scene-ref ${g} actor:${y.actor_id} --state ${_} -p "$SCRIPT"`:void 0;o("actor_not_in_scene",`${h}.speaker.actor_id`,`actor ${y.actor_id} is not referenced by this scene`,x)}}else o("speaker",`${h}.speaker`,"speaker needs actor_id or kind")}},f=e.episodes;return Qn(f)?f.forEach((u,h)=>{let m=`$.episodes[${h}]`;if(!_t(u)||!ke(u.episode_id)){o("episode_id",m,"episode_id required");return}if(!Qn(u.scenes)){o("scenes",`${m}.scenes`,"scenes must be an array");return}u.scenes.forEach((g,w)=>{let y=`${m}.scenes[${w}]`;if(!_t(g)){o("scene",y,"scene must be an object");return}"context"in g&&o("legacy_field",`${y}.context`,"v3 forbids scene.context"),ke(g.scene_id)||o("scene_id",y,"scene_id required");let E=g.environment;E===void 0||_t(E)&&(!ke(E.time)||E.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!_t(E)||E.space!==void 0&&!ke(E.space)||!ke(E.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):Qr(E.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk"),(g.environment===void 0||_t(g.environment)&&(!ke(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 _=g.location;if(_!==null&&(!_t(_)||!ke(_.location_id)?o("location",`${y}.location`,"location must be null or {location_id}"):d(_.location_id,_.state_id,"location",`${y}.location`)),p(g.actors,"actor","actor_id",`${y}.actors`),p(g.props,"prop","prop_id",`${y}.props`),Qn(g.props)){let A=new Set;g.props.forEach((b,U)=>{!_t(b)||!ke(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 x=new Set(Qn(g.actors)?g.actors.filter(A=>_t(A)).map(A=>A.actor_id).filter(A=>ke(A)):[]);if(!Qn(g.actions))o("actions",`${y}.actions`,"actions must be an array");else{let A=ke(g.scene_id)?`${u.episode_id}/${g.scene_id}`:void 0;g.actions.forEach((b,U)=>l(b,`${y}.actions[${U}]`,x,A)),aa(g.actions,`${y}.actions`,o)}})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}var rt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),le=e=>typeof e=="string",kn=e=>Array.isArray(e);function Ed(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Ed):rt(e)&&Object.values(e).every(Ed)}function Wi(e,t,n){e!==void 0&&(!rt(e)||!Object.values(e).every(Ed))&&n("extend",t,"extend must be an object containing JSON values")}function $E(e){for(let t=1;t<e.length;t++)if(e[t-1]>e[t])return!1;return!0}function Te(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(!rt(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"])le(e[u])||o("field",`$.${u}`,`${u} must be a string`);for(let u of["worldview_raw","synopsis","logline","theme"])e[u]!==void 0&&!le(e[u])&&o("field",`$.${u}`,`${u} must be a string`);e.main_characters!==void 0&&(!kn(e.main_characters)||!e.main_characters.every(u=>rt(u)&&le(u.name)&&le(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,a=new Set,c=(u,h,m,g,w)=>{if(!kn(u)){o("field",w,`${w} must be an array`);return}let y=new Set;u.forEach((E,_)=>{let x=`${w}[${_}]`;if(!rt(E)){o("asset",x,"asset must be an object");return}let A=E[m];if(!$(h,A)){o("asset_id",`${x}.${m}`,`${m} must be ${h} ID`);return}if(y.has(A)&&o("dup_id",`${x}.${m}`,`duplicate ${m} ${A}`),y.add(A),r.set(A,h),!le(E[g])||E[g].trim()==="")o("asset_name",`${x}.${g}`,`${g} must be a non-empty string`);else if(h==="actor"){let I=E[g].trim().toLocaleLowerCase();a.has(I)&&o("dup_actor_name",`${x}.${g}`,`duplicate actor name ${E[g]}`),a.add(I)}if((!le(E.importance)||!Hn.includes(E.importance))&&o("importance",`${x}.importance`,`importance must be ${Hn.join("|")}`),h==="actor"&&E.role_type!==void 0&&(!le(E.role_type)||!Yi.includes(E.role_type))&&o("role_type",`${x}.role_type`,`role_type must be ${Yi.join("|")}`),le(E.description)||o("asset_desc",`${x}.description`,"description must be a string"),E.aliases!==void 0&&(!kn(E.aliases)||!E.aliases.every(le)))o("aliases",`${x}.aliases`,"aliases must be an array of strings");else if(kn(E.aliases)&&E.aliases.every(le)){let I=new Set,R=le(E[g])?E[g]:"";E.aliases.forEach((C,N)=>{C===""&&o("alias_empty",`${x}.aliases[${N}]`,"alias must not be empty"),C===R&&o("alias_equals_name",`${x}.aliases[${N}]`,"alias must differ from the asset name"),I.has(C)&&o("dup_alias",`${x}.aliases[${N}]`,`duplicate alias ${C}`),I.add(C)})}Wi(E.extend,`${x}.extend`,o);let b=new Set,U=new Set,v=0;!kn(E.states)||E.states.length===0?o("states",`${x}.states`,"states must be a non-empty array"):E.states.forEach((I,R)=>{let C=`${x}.states[${R}]`;if(!rt(I)){o("state",C,"state must be an object");return}let N=I.state_id;if(N!=="default"&&!$("state",N)){o("state_id",`${C}.state_id`,"state_id must be default or st plus six Base58 characters");return}b.has(N)&&o("dup_state",`${C}.state_id`,`duplicate state_id ${N}`),b.add(N),N==="default"&&v++,!le(I.state_name)||I.state_name.trim()===""?o("state_name",`${C}.state_name`,"state_name must be a non-empty string"):(U.has(I.state_name)&&o("dup_state_name",`${C}.state_name`,`duplicate state_name ${I.state_name}`),U.add(I.state_name)),le(I.description)||o("state_description",`${C}.description`,"description must be a string"),Wi(I.extend,`${C}.extend`,o)}),v!==1&&o("default_state",`${x}.states`,`exactly one default state required, found ${v}`),s.set(A,b)})};c(e.actors,"actor","actor_id","actor_name","$.actors"),c(e.locations,"location","location_id","location_name","$.locations"),c(e.props,"prop","prop_id","prop_name","$.props");let d=(u,h,m)=>{if(!kn(h)||h.length===0||!h.every(le))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,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}`)}),$E(g)||o("state_ids_order",m,"state_ids must be sorted lexically"),g},p=new Set,l=new Set,f=new Set;return kn(e.episodes)?e.episodes.forEach((u,h)=>{let m=`$.episodes[${h}]`;if(!rt(u)){o("episode",m,"episode must be an object");return}$("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&&!le(u[g])&&o("field",`${m}.${g}`,`${g} must be a string`);if(Wi(u.extend,`${m}.extend`,o),!kn(u.scenes)){o("scenes",`${m}.scenes`,"scenes must be an array");return}u.scenes.forEach((g,w)=>{let y=`${m}.scenes[${w}]`;if(!rt(g)){o("scene",y,"scene must be an object");return}$("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||rt(g.environment)&&(!le(g.environment.time)||g.environment.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!rt(g.environment)||g.environment.space!==void 0&&!le(g.environment.space)||!le(g.environment.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):Qr(g.environment.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk"),(g.environment===void 0||rt(g.environment)&&(!le(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&&(!rt(g.location)||!$("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 E=new Map,_=(x,A,b,U)=>{if(!kn(x)){o("field",U,`${U} must be an array`);return}let v=new Set;x.forEach((I,R)=>{let C=`${U}[${R}]`;if(!rt(I)||!$(A,I[b])){o("ref",C,`${b} must be a typed v4 ID`);return}let N=I[b];"state_id"in I&&o("v3_field",`${C}.state_id`,"Script v4 scene references use state_ids"),v.has(N)&&o("dup_asset_ref",`${C}.${b}`,`duplicate ${A} ref ${N}`),v.add(N),r.get(N)!==A&&o("asset_ref",`${C}.${b}`,`${A} ${N} not found`);let M=d(N,I.state_ids,`${C}.state_ids`);A==="actor"&&E.set(N,new Set(M))})};if(_(g.actors,"actor","actor_id",`${y}.actors`),_(g.props,"prop","prop_id",`${y}.props`),!kn(g.actions)){o("actions",`${y}.actions`,"actions must be an array");return}g.actions.forEach((x,A)=>{let b=`${y}.actions[${A}]`;if(!rt(x)){o("action",b,"action must be an object");return}if($("action",x.action_id)?(f.has(x.action_id)&&o("dup_action_id",`${b}.action_id`,`duplicate action_id ${x.action_id}`),f.add(x.action_id)):o("action_id",`${b}.action_id`,"action_id must be ac plus six Base58 characters"),(!le(x.type)||!Kn.includes(x.type))&&o("action_type",`${b}.type`,`invalid action type ${String(x.type)}`),le(x.content)||o("content",`${b}.content`,"content must be a string"),"emotion"in x&&o("v3_field",`${b}.emotion`,"Script v4 does not allow emotion"),Wi(x.extend,`${b}.extend`,o),x.type==="dialogue"||x.type==="inner_thought")if(x.parenthetical!==void 0&&!le(x.parenthetical)&&o("parenthetical",`${b}.parenthetical`,"parenthetical must be a string"),!rt(x.speaker))o("speaker",`${b}.speaker`,"dialogue/inner_thought requires a speaker");else if(le(x.speaker.actor_id)){("kind"in x.speaker||"label"in x.speaker)&&o("speaker_shape",`${b}.speaker`,"actor speaker cannot contain non-actor speaker fields");let v=x.speaker.actor_id;(!$("actor",v)||r.get(v)!=="actor")&&o("speaker_actor",`${b}.speaker.actor_id`,`actor ${v} not found`);let I=E.get(v),R=s.get(v),C=le(x.speaker.state_id)&&R?.has(x.speaker.state_id)?x.speaker.state_id:void 0,N=R?.has("default")?"default":R?.values().next().value,M=C?[C]:N?[N]:[],K=$("scene",g.scene_id)&&$("actor",v)&&M.length>0?`scriptctl scene-ref ${g.scene_id} ${v} ${M.map(X=>`--state ${X}`).join(" ")} -p "$SCRIPT"`:void 0;if(I||o("actor_not_in_scene",`${b}.speaker.actor_id`,`actor ${v} is not referenced by this scene`,K),x.speaker.state_id!==void 0&&(!le(x.speaker.state_id)||!I?.has(x.speaker.state_id))){let X=C?[...new Set([...I??[],C])].sort():[],Ke=$("scene",g.scene_id)&&$("actor",v)&&X.length>0?`scriptctl scene-ref ${g.scene_id} ${v} ${X.map(se=>`--state ${se}`).join(" ")} -p "$SCRIPT"`:K;o("speaker_state",`${b}.speaker.state_id`,`speaker state ${String(x.speaker.state_id)} is not in this scene's actor state_ids`,Ke)}}else le(x.speaker.kind)?(("actor_id"in x.speaker||"state_id"in x.speaker)&&o("speaker_shape",`${b}.speaker`,"non-actor speaker cannot contain actor speaker fields"),jn.includes(x.speaker.kind)||o("speaker_kind",`${b}.speaker.kind`,"invalid non-actor speaker kind"),x.speaker.label!==void 0&&!le(x.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 x&&o("parenthetical_type",`${b}.parenthetical`,"parenthetical only belongs to speaking actions"),"speaker"in x&&o("speaker_type",`${b}.speaker`,"speaker only belongs to speaking actions");if(x.transition_prompt!==void 0){let v=x.transition_prompt;!rt(v)||!le(v.target)||!le(v.process)||v.process===""||!le(v.contrast)||v.contrast===""?o("transition_prompt",`${b}.transition_prompt`,"transition_prompt requires non-empty target/process/contrast"):r.has(v.target)||o("transition_target",`${b}.transition_prompt.target`,`asset ${v.target} not found`)}}),aa(g.actions,`${y}.actions`,o)})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}function ai(e,t=new Set,n){try{return n?Fr(e,t,n):Fr(e,t)}catch(o){throw o?.code!==xd?o:new S(`Could not generate an unused ${e} ID.`,{exitCode:k,errorCode:"ID_SPACE_RETRY_EXHAUSTED",hint:"Retry the command. If this persists, inspect the configured ID generator."})}}function be(e,t=[]){throw new S(e,{exitCode:k,errorCode:"CREATIVE_DRAFT_INVALID",hint:"Use the readable creative draft schema; do not include Script IDs or .scriptctl syntax.",data:{actual:t.map(String)}})}function Fn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Z(e,t=""){return String(e??"").replace(/\s+/gu," ").trim()||t}function DE(e,t){let n=Number(e);return(!Number.isSafeInteger(n)||n<1)&&be(`${t} must be a positive integer.`,[e]),n}function GE(e){return e===void 0?{}:(Fn(e)||be("Action extensions must be an object."),structuredClone(e))}function BE(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 Io(e,t,n){for(let o=0;o<128;o+=1){let i=Lf.createHash("sha256").update(`${e}:${t}:${o}`).digest(),r="";for(let a=0;a<6;a+=1)r+=qi[i[a]%qi.length];let s=`${Zi[e]}${r}`;if(!n.has(s))return n.add(s),s}be(`Could not allocate a stable ${e} ID.`)}function JE(e){let t=Z(e).match(/^(\d+):([0-5]\d)(?:\.(\d{1,3}))?$/u);return t?(Number(t[1])*60+Number(t[2]))*1e3+Number((t[3]??"").padEnd(3,"0")):null}function zE(e){return`${Math.floor(e/6e4)}:${String(Math.floor(e%6e4/1e3)).padStart(2,"0")}.${String(e%1e3).padStart(3,"0")}`}function KE(e){let t=Number(e.extend?.duration_ms??e.extend?.rewrite_duration_ms);return Number.isFinite(t)&&t>0?Math.round(t):1200}function jE(e){let t=0;for(let n of e.scenes.flatMap(o=>o.actions))t=(JE(n.extend?.timestamp)??t)+KE(n);return t}function Uf(e){return e===void 0?[]:((!Array.isArray(e)||!e.every(Fn))&&be("Asset variants must be an array of readable objects."),e)}function HE(e,t){let n=e.assets;if(n===void 0)return[];Fn(n)||be("assets must be an object.");let o=n[t];return o===void 0?[]:((!Array.isArray(o)||!o.every(Fn))&&be(`assets.${t} must be an array.`),o)}function QE(e,t){return e==="actors"?t.actor_name:e==="locations"?t.location_name:t.prop_name}function FE(e,t){return e[t]}function YE(e,t){return[QE(e,t),...t.aliases??[]].map(mt)}function Pf(e,t,n){let o=mt(n);return HE(e,t).find(i=>[i.name,...Array.isArray(i.aliases)?i.aliases:[]].map(r=>mt(Z(r))).includes(o))??null}function Cf(e,t){if(!e)return null;let n=mt(t);return Uf(e.variants).find(o=>{let i=mt(Z(o.name));return i===n||["default","\u9ED8\u8BA4"].includes(n)&&["default","\u9ED8\u8BA4"].includes(i)})??null}function Tf(e,t,n){let o=Cf(e,n),i=Z(o?.description);return(!o||!i)&&be(`${t}/${n} is a new variant and requires a readable assets declaration with a self-contained description.`),o}function qE(e,t){let n=Z(t?.name);return n&&!["default","\u9ED8\u8BA4"].includes(mt(n))?n:e==="actors"?"\u57FA\u7840\u9020\u578B":e==="locations"?"\u5E38\u89C4\u5E03\u7F6E":"\u57FA\u7840\u5916\u89C2"}function ZE(e,t,n,o,i,r){let s=Pf(t,n,o);s||be(`${o} is not an existing ${n} asset and has no readable declaration.`);let a=Z(s.name,o),c=Uf(s.variants),d=Cf(s,"\u9ED8\u8BA4")??c[0]??null;n==="actors"&&!Z(s.description)&&be(`${a} requires an identity description separate from its appearance variants.`),n==="actors"&&!Z(d?.description)&&be(`${a} requires its first variant to provide a self-contained base appearance description.`);let p=[{state_id:"default",state_name:qE(n,d),description:Z(d?.description,Z(s.description,`${a}\u7684\u57FA\u7840\u53C2\u8003\u5916\u89C2\u3002`))}];for(let u of c){let h=Z(u.name);if(u===d||!h||["default","\u9ED8\u8BA4"].includes(mt(h)))continue;let m=Io("state",`${n}:${a}:${h}`,i);p.push({state_id:m,state_name:h,description:Z(Tf(s,a,h).description)}),r.states.push(`${a}/${h}`)}let l={aliases:Array.isArray(s.aliases)?[...new Set(s.aliases.map(u=>Z(u)).filter(u=>u&&u!==a))]:[],importance:s.importance==="background"?"background":"featured",description:Z(s.description,`${a}\u7684\u57FA\u7840\u8BBE\u5B9A\u3002`),states:p};if(n==="actors"){let u={...l,actor_id:Io("actor",a,i),actor_name:a,...s.roleType==="\u4E3B\u89D2"||s.roleType==="\u914D\u89D2"?{role_type:s.roleType}:{}};return e.actors.push(u),r.actors.push(a),u}if(n==="locations"){let u={...l,location_id:Io("location",a,i),location_name:a};return e.locations.push(u),r.locations.push(a),u}let f={...l,prop_id:Io("prop",a,i),prop_name:a};return e.props.push(f),r.props.push(a),f}function da(e,t,n,o,i,r){let s=Z(o);s||be(`${n} reference requires a readable name.`);let a=mt(s);return FE(e,n).find(d=>YE(n,d).includes(a))??ZE(e,t,n,s,i,r)}function Yr(e,t,n,o,i,r){let s=Z(t,"\u9ED8\u8BA4"),a=mt(s),c=e.states.find(u=>mt(u.state_name)===a||u.state_id==="default"&&["default","\u9ED8\u8BA4"].includes(a));if(c)return c.state_id;let d="actor_name"in e?e.actor_name:"location_name"in e?e.location_name:e.prop_name,p=Pf(n,o,d),l=Tf(p,d,s),f={state_id:Io("state",`${d}:${s}`,i),state_name:s,description:Z(l.description)};return e.states.push(f),r.states.push(`${d}/${s}`),f.state_id}function Nf(e,t){return e===void 0?[]:((!Array.isArray(e)||!e.every(Fn))&&be(`${t} must be an array of readable references.`),e)}function ca(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 WE(e,t){return!!(e&&e.location?.location_id&&t.location?.location_id&&e.location.location_id===t.location.location_id&&Z(e.environment?.space)===Z(t.environment?.space)&&Z(e.environment?.time)===Z(t.environment?.time))}function XE(e,t,n,o,i,r,s,a){(!Array.isArray(e)||e.length===0||!e.every(Fn))&&be("scene.actions must contain at least one readable Action.");let c=structuredClone(o),d=r;return{actions:e.map((l,f)=>{let u=Z(l.type,"action");["action","transition","dialogue","inner_thought"].includes(u)||be(`Action ${f+1} has an unsupported type.`,[u]);let h=Z(l.content);h||be(`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=GE(l.extensions);g.timestamp=zE(d),g.duration_ms=m,g.rewrite_duration_ms!==void 0&&(g.rewrite_duration_ms=m);let w={action_id:Io("action",`${i}:${f+1}:${h}`,s),type:u,content:h,extend:g};if(d+=m,u==="action"||u==="transition")return w;let y=Z(l.speaker);y||be(`Action ${f+1} requires a speaker.`);let E=y.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");new RegExp(`^${E}\\s*[:\uFF1A]`,"iu").test(h)&&be(`Action ${f+1} repeats the speaker name in dialogue content.`),/^(?:“[^”]+”|「[^」]+」|『[^』]+』|"[^"]+")$/u.test(h)&&be(`Action ${f+1} wraps dialogue content in quotation marks.`);let _=mt(y);if(["\u65C1\u767D","narrator"].includes(_))return{...w,speaker:{kind:"broadcast",label:"\u65C1\u767D"},...Z(l.parenthetical)?{parenthetical:Z(l.parenthetical)}:{}};if(["\u753B\u5916\u97F3","offscreen"].includes(_))return{...w,speaker:{kind:"offscreen",label:"\u753B\u5916\u97F3"},...Z(l.parenthetical)?{parenthetical:Z(l.parenthetical)}:{}};let x=da(t,n,"actors",y,s,a),A=Z(l.speakerVariant),b=c.find(v=>v.actor_id===x.actor_id),U;if(A)U=Yr(x,A,n,"actors",s,a),b?b.state_ids=[...new Set([...b.state_ids,U])].sort():c.push({actor_id:x.actor_id,state_ids:[U]});else if(!b){let v=Yr(x,"\u9ED8\u8BA4",n,"actors",s,a);c.push({actor_id:x.actor_id,state_ids:[v]})}return{...w,speaker:{actor_id:x.actor_id,...U?{state_id:U}:{}},...Z(l.parenthetical)?{parenthetical:Z(l.parenthetical)}:{}}}),actorRefs:c}}function Vf(e,t){(!Fn(t)||t.version!==1)&&be("Creative draft version must be 1."),(!Fn(t.episode)||!Fn(t.scene))&&be("Creative draft requires episode and scene objects.");let n=structuredClone(t),o=n.episode,i=n.scene,r=structuredClone(e),s=BE(r),a={actors:[],locations:[],props:[],states:[]},c=DE(o.number,"episode.number");c>r.episodes.length+1&&be("Episodes must be composed in order.",[c]);let d=r.episodes[c-1];d?(Z(d.title)||(d.title=Z(o.title,`\u7B2C ${c} \u96C6`)),Z(d.synopsis)||(d.synopsis=Z(o.synopsis,`\u7B2C ${c} \u96C6\u5267\u60C5\u3002`))):(d={episode_id:Io("episode",`episode:${c}`,s),title:Z(o.title,`\u7B2C ${c} \u96C6`),synopsis:Z(o.synopsis,`\u7B2C ${c} \u96C6\u5267\u60C5\u3002`),scenes:[]},r.episodes.push(d));let p=da(r,n,"locations",i.location,s,a),l=Yr(p,i.locationVariant,n,"locations",s,a),f=Nf(i.actors,"scene.actors").map(I=>{let R=da(r,n,"actors",I.name,s,a);return{actor_id:R.actor_id,state_ids:[Yr(R,I.variant,n,"actors",s,a)]}}),u=ca([],f,I=>I.actor_id),h=Nf(i.props,"scene.props").map(I=>{let R=da(r,n,"props",I.name,s,a);return{prop_id:R.prop_id,state_ids:[Yr(R,I.variant,n,"props",s,a)]}}),m=ca([],h,I=>I.prop_id),g=d.scenes.at(-1),w={scene_id:Io("scene",`episode:${c}:scene:${d.scenes.length+1}:${Z(i.title)}`,s),environment:{space:Z(i.space,"interior"),time:Z(i.time,"day")},location:{location_id:p.location_id,state_ids:[l]},actors:u,props:m,actions:[],extend:{scene_title:Z(i.title,`\u7B2C ${d.scenes.length+1} \u573A`)}},y=Z(i.boundary,"auto");["auto","new","continue"].includes(y)||be("scene.boundary must be auto, new, or continue.");let E=WE(g,w);y==="continue"&&!E&&be("scene.boundary=continue requires the same location, space, and time as the previous scene.");let _=y!=="new"&&E,x=_&&g?g:w,A=_?d.scenes.length:d.scenes.length+1,b=ca(x.actors,w.actors,I=>I.actor_id),U=XE(i.actions,r,n,b,x.scene_id,jE(d),s,a);x.actors=U.actorRefs,x.props=ca(x.props,w.props,I=>I.prop_id),x.location&&w.location&&(x.location.state_ids=[...new Set([...x.location.state_ids,...w.location.state_ids])].sort()),x.actions.push(...U.actions),_||d.scenes.push(x);let v=Te(r);return v.ok||be("Composed screenplay does not pass Script v4 validation.",v.errors.slice(0,12).map(I=>`${I.path}: ${I.message}`)),{script:r,validation:v,episodeNumber:c,sceneNumber:A,sceneId:x.scene_id,actionIds:U.actions.map(I=>I.action_id),joinedPreviousScene:_,created:a}}function qe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bn(e,t){return e[t]===void 0||typeof e[t]=="string"}function _d(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(_d):qe(e)&&Object.values(e).every(_d)}function Xi(e){return e.extend===void 0||qe(e.extend)&&Object.values(e.extend).every(_d)}function Sd(e){return e==="default"||$("state",e)}function e_(e){return qe(e)&&Sd(e.state_id)&&typeof e.state_name=="string"&&typeof e.description=="string"&&Xi(e)}function Id(e){return typeof e.importance=="string"&&$t.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(e_)&&Xi(e)}function t_(e){return qe(e)&&$("actor",e.actor_id)&&typeof e.actor_name=="string"&&(e.role_type===void 0||typeof e.role_type=="string"&&_o.has(e.role_type))&&Id(e)}function n_(e){return qe(e)&&$("location",e.location_id)&&typeof e.location_name=="string"&&Id(e)}function o_(e){return qe(e)&&$("prop",e.prop_id)&&typeof e.prop_name=="string"&&Id(e)}function Ad(e){return Array.isArray(e)&&e.every(Sd)}function i_(e){return qe(e)&&$("actor",e.actor_id)&&Ad(e.state_ids)}function r_(e){return qe(e)&&$("location",e.location_id)&&Ad(e.state_ids)}function s_(e){return qe(e)&&$("prop",e.prop_id)&&Ad(e.state_ids)}function a_(e){return $("actor",e.actor_id)&&(e.state_id===void 0||Sd(e.state_id))}function c_(e){return typeof e.kind=="string"&&si.has(e.kind)&&bn(e,"label")}function d_(e){return!(!qe(e)||!$("action",e.action_id)||typeof e.type!="string"||!tn.has(e.type)||typeof e.content!="string"||!bn(e,"parenthetical")||!Xi(e)||(e.type==="dialogue"||e.type==="inner_thought")&&(!qe(e.speaker)||!a_(e.speaker)&&!c_(e.speaker))||e.transition_prompt!==void 0&&(!qe(e.transition_prompt)||!$("actor",e.transition_prompt.target)&&!$("location",e.transition_prompt.target)&&!$("prop",e.transition_prompt.target)||typeof e.transition_prompt.process!="string"||typeof e.transition_prompt.contrast!="string"))}function p_(e){return!(!qe(e)||!$("scene",e.scene_id)||!Array.isArray(e.actors)||!e.actors.every(i_)||!Array.isArray(e.props)||!e.props.every(s_)||!Array.isArray(e.actions)||!e.actions.every(d_)||!Xi(e)||e.location!==null&&!r_(e.location)||e.environment!==void 0&&(!qe(e.environment)||!bn(e.environment,"space")||!bn(e.environment,"time")))}function l_(e){return qe(e)&&$("episode",e.episode_id)&&bn(e,"title")&&bn(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(p_)&&Xi(e)}function u_(e){return qe(e)&&e.version===4&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&bn(e,"worldview_raw")&&bn(e,"synopsis")&&bn(e,"logline")&&bn(e,"theme")&&(e.main_characters===void 0||Array.isArray(e.main_characters)&&e.main_characters.every(t=>qe(t)&&typeof t.name=="string"&&typeof t.role=="string"))&&Array.isArray(e.actors)&&e.actors.every(t_)&&Array.isArray(e.locations)&&e.locations.every(n_)&&Array.isArray(e.props)&&e.props.every(o_)&&Array.isArray(e.episodes)&&e.episodes.every(l_)&&Xi(e)}function er(e){let t=Te(e);if(t.ok)return e;throw new S("The local file is not a valid Script v4 document.",{exitCode:k,errorCode:"SCRIPT_V4_INVALID",hint:"Run `scriptctl validate --script-path <path>` and repair the reported v4 fields.",data:{expected:["A valid Script v4 document"],actual:t.errors.slice(0,20).map(n=>`${n.path}: ${n.message}`)}})}function vn(e){if(u_(e))return e;throw new S("The local file is not a structurally readable Script v4 document.",{exitCode:k,errorCode:"SCRIPT_V4_SHAPE_INVALID",hint:"Repair the local Script v4 structure, then rerun the command.",data:{expected:["Script v4 with typed assets, episodes, scenes, references, and actions"],actual:[Array.isArray(e)?"array":typeof e]}})}import*as qr from"node:crypto";import*as Ge from"node:fs";import*as Dt from"node:path";import f_ from"proper-lockfile";function bd(e){if(Array.isArray(e))return e.map(bd);if(e!==null&&typeof e=="object"){let t=e,n={};for(let o of Object.keys(t).sort())n[o]=bd(t[o]);return n}return e}function je(e){let t=JSON.stringify(bd(e));return`sha256:${qr.createHash("sha256").update(t).digest("hex")}`}function Zr(e){return Ge.existsSync(e)?`sha256:${qr.createHash("sha256").update(Ge.readFileSync(e)).digest("hex")}`:null}function Wr(e,t){let n=Zr(e);if(n!==t)throw new S("The local script changed while the command was running.",{exitCode:k,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and retry the command.",data:{actual:[`loadedFingerprint=${t??"<missing>"}`,`currentFingerprint=${n??"<missing>"}`,e]}})}function Xr(e){let t=Dt.resolve(e),n=Dt.join(Dt.dirname(t),".scriptctl"),o=Dt.basename(t);return{scriptPath:t,stateDir:n,metadataPath:Dt.join(n,`${o}.working-copy.json`),lockPath:Dt.join(n,o)}}async function pa(e,t){let n=Xr(e);Ge.mkdirSync(n.stateDir,{recursive:!0});let o=null;try{o=await f_.lock(n.lockPath,{realpath:!1,stale:12e4,update:1e4,retries:{retries:260,factor:1,minTimeout:500,maxTimeout:500}})}catch(i){throw new S("Timed out waiting for the script file lock.",{exitCode:q,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){la(e,`${JSON.stringify(t,null,2)}
|
|
123
|
-
`)}function
|
|
124
|
-
`),data:{op:"compose",applied:f,source_path:o.path,source_digest:d,script_path:i,baseline:a,plan_digest:l,episode_number:c.episodeNumber,scene_number:c.sceneNumber,scene_id:c.sceneId,action_ids:c.actionIds,joined_previous_scene:c.joinedPreviousScene,created:c.created,validation:c.validation}},V]}import*as
|
|
122
|
+
`,S=class extends Error{exitCode;errorCode;hint;data;constructor(t,n){super(t),this.name="CliError",this.exitCode=n.exitCode,this.errorCode=n.errorCode,this.hint=n.hint,this.data=n.data??{}}};function UE(e){return new sa(e)}function kf(e){return UE(e).directDir}function he(e){let t=e.script_path??e.scriptPath;return jr.resolve(typeof t=="string"&&t.length>0?t:LE)}function Hr(e){return aa.readJson(e)}function md(e,t){aa.writeJson(e,t)}function si(e){return aa.exists(e)}function _e(e){return fd.createHash("sha256").update(e,"utf-8").digest("hex")}function gd(e){let t=fd.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 Ct={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 Tt(e,t){return typeof e=="string"&&t.some(n=>n===e)}function bf(e,t){switch(e){case"policy":return Tt(t,Ct.policy)?{failure_type:e,failure_code:t}:null;case"network":return Tt(t,Ct.network)?{failure_type:e,failure_code:t}:null;case"timeout":return Tt(t,Ct.timeout)?{failure_type:e,failure_code:t}:null;case"rate_limit":return Tt(t,Ct.rate_limit)?{failure_type:e,failure_code:t}:null;case"authentication":return Tt(t,Ct.authentication)?{failure_type:e,failure_code:t}:null;case"authorization":return Tt(t,Ct.authorization)?{failure_type:e,failure_code:t}:null;case"provider":return Tt(t,Ct.provider)?{failure_type:e,failure_code:t}:null;case"media":return Tt(t,Ct.media)?{failure_type:e,failure_code:t}:null;case"response":return Tt(t,Ct.response)?{failure_type:e,failure_code:t}:null;case"pipeline":return Tt(t,Ct.pipeline)?{failure_type:e,failure_code:t}:null;case"validation":return Tt(t,Ct.validation)?{failure_type:e,failure_code:t}:null;case"cancelled":return Tt(t,Ct.cancelled)?{failure_type:e,failure_code:t}:null;case"unknown":return Tt(t,Ct.unknown)?{failure_type:e,failure_code:t}:null;default:return null}}function Vt(e,t){return{...e,...t}}function Yi(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 Qr(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 vf(e,t){if(e.length===0)return Vt({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)?Yi(n):{failure_type:"provider",failure_code:"attempts_exhausted"};return Vt(i,{retryable:e.some(r=>r.retryable),message:t})}function An(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 Jf from"node:crypto";import*as zf from"node:fs";import*as Kf from"node:path";import*as Cf from"node:crypto";var Kn=["action","dialogue","inner_thought","transition"],tn=new Set(Kn),jn=["system","broadcast","offscreen","group"],ai=new Set(jn),Hn=["featured","background"],$t=new Set(Hn),qi=["\u4E3B\u89D2","\u914D\u89D2"],_o=new Set(qi),ca=["day","night","dawn","dusk"],hd=new Set(ca);function Fr(e){return typeof e=="string"&&hd.has(e)}var yd=["interior","exterior"],Of=new Set(yd);function mt(e){return e.normalize("NFKC").toLowerCase()}function Rf(e){return JSON.stringify([e.code,e.path,e.message])}function wd(e){let t=new Map;for(let n of e){let o=Rf(n);t.set(o,(t.get(o)??0)+1)}return t}function xd(e,t){if(e.ok||t.errors.length>=e.errors.length)return!1;let n=wd(e.errors),o=wd(t.errors);for(let[i,r]of o)if(r>(n.get(i)??0))return!1;return!0}function Ed(e,t){let n=wd(e),o=[];for(let i of t){let r=Rf(i),s=n.get(r)??0;s>0?n.set(r,s-1):o.push(i)}return o}import{customAlphabet as PE}from"nanoid";var Wi="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",_d=6,Zi={episode:"ep",scene:"scn",action:"ac",actor:"act",location:"loc",prop:"prp",state:"st"},CE=PE(Wi,_d),TE=`[${Wi}]`,Mf=Object.fromEntries(Object.entries(Zi).map(([e,t])=>[e,new RegExp(`^${t}${TE}{${_d}}$`)]));function $(e,t){return typeof t=="string"&&Mf[e].test(t)}var Sd="ID_SPACE_EXHAUSTED";function Yr(e,t=new Set,n=CE){let o=Zi[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:Sd})}var it=class extends Error{input;constructor(t,n){super(n),this.input=t,this.name="TimestampParseError"}},VE=/^(\d+):(\d{2})(?:\.(\d{1,3}))?$/,$E=/^(\d+):(\d{2}):(\d{2})(?:\.(\d{1,3}))?$/;function Nf(e){return e?Number(e.padEnd(3,"0")):0}function Lf(e,t){if(!Number.isSafeInteger(t))throw new it(e,"Timestamp exceeds the supported numeric range.");return t}function Uf(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 So(e){let t=e.trim();if(!t)throw new it(e,"Timestamp must not be empty.");let n=t.match($E);if(n){let c=Number(n[1]),d=Number(n[2]),p=Number(n[3]),l=n[4];if(d>59)throw new it(e,"Hour-form timestamps require minutes between 00 and 59.");if(p>59)throw new it(e,"Timestamp seconds must be between 00 and 59.");let f=Lf(e,((c*60+d)*60+p)*1e3+Nf(l));return{canonical:Uf(f,l),milliseconds:f,fractionDigits:l?.length??0}}let o=t.match(VE);if(!o)throw new it(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 it(e,"Timestamp seconds must be between 00 and 59.");let a=Lf(e,(i*60+r)*1e3+Nf(s));return{canonical:Uf(a,s),milliseconds:a,fractionDigits:s?.length??0}}function DE(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 GE(e,t){let n=e.milliseconds-t.milliseconds;return e.fractionDigits===0||t.fractionDigits===0?n>=1e3:n>0}function da(e,t,n){let o=null;e.forEach((i,r)=>{let s=DE(i);if(s===void 0)return;let a=`${t}[${r}].extend.timestamp`;if(typeof s!="string"){n("timestamp_invalid",a,"timestamp must be a string in M:SS, MM:SS, or H:MM:SS form");return}let c;try{c=So(s)}catch(d){if(!(d instanceof it))throw d;n("timestamp_invalid",a,d.message);return}o!==null&&GE(o.timestamp,c)&&n("timestamp_out_of_order",a,`timestamp ${c.canonical} is earlier than Action ${o.actionIndex+1} timestamp ${o.timestamp.canonical}; equal timestamps and sub-second differences against a whole-second mark are allowed`),o={actionIndex:r,timestamp:c}})}var _t=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qn=e=>Array.isArray(e),ke=e=>typeof e=="string",BE=["state_changes","actor_id","speakers","lines"];function St(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(!_t(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"])ke(e[u])||o("field",`$.${u}`,`${u} must be a string`);let r=new Map,s=new Map,a=new Map,c=(u,h,m,g,w)=>{if(!Qn(u)){o("field",w,`${w} must be an array`);return}u.forEach((y,E)=>{let _=`${w}[${E}]`;if(!_t(y)){o("asset",_,"asset must be an object");return}let x=y[m];if(!ke(x)){o("asset_id",`${_}.${m}`,`${m} required`);return}if(s.has(x)&&o("dup_id",`${_}.${m}`,`duplicate id ${x}`),s.set(x,h),!ke(y[g]))o("asset_name",`${_}.${g}`,`${g} required`);else if(h==="actor"){let v=mt(y[g]),I=a.get(v);I!==void 0?o("dup_actor_name",`${_}.${g}`,`actor name ${y[g]} already belongs to ${I}`):a.set(v,x)}(!ke(y.importance)||!Hn.includes(y.importance))&&o("importance",`${_}.importance`,`importance must be one of ${Hn.join("|")}`),ke(y.description)||o("asset_desc",`${_}.description`,"description must be a string");let A=new Set,b=new Set,U=0;!Qn(y.states)||y.states.length===0?o("states",`${_}.states`,"states must be a non-empty array"):y.states.forEach((v,I)=>{let R=`${_}.states[${I}]`;if(!_t(v)||!ke(v.state_id)){o("state_id",R,"state_id required");return}A.has(v.state_id)&&o("dup_state",R,`duplicate state_id ${v.state_id}`),A.add(v.state_id),v.state_id==="default"&&U++,ke(v.state_name)?(b.has(v.state_name)&&o("dup_state_name",`${R}.state_name`,`duplicate state_name ${v.state_name}`),b.add(v.state_name)):o("state_name",`${R}.state_name`,"state_name required")}),Qn(y.states)&&U!==1&&o("default_state",`${_}.states`,`exactly one 'default' state required, found ${U}`),r.set(x,A)})};c(e.actors,"actor","actor_id","actor_name","$.actors"),c(e.locations,"location","location_id","location_name","$.locations"),c(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&&(!ke(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(!Qn(u)){o("field",g,`${g} must be an array`);return}u.forEach((w,y)=>{if(!_t(w)||!ke(w[m])){o("ref",`${g}[${y}]`,`${m} required`);return}d(w[m],w.state_id,h,`${g}[${y}]`)})},l=(u,h,m,g)=>{if(!_t(u)){o("action",h,"action must be an object");return}for(let y of BE)y in u&&o("legacy_field",`${h}.${y}`,`v3 forbids action.${y}`);let w=u.type;if((!ke(w)||!Kn.includes(w))&&o("action_type",`${h}.type`,`invalid action type ${String(w)}`),ke(u.content)||o("content",`${h}.content`,"content must be a plain-text string"),w==="dialogue"||w==="inner_thought"){let y=u.speaker;if(!_t(y))o("speaker",`${h}.speaker`,"dialogue/inner_thought needs a speaker");else if("kind"in y)(!ke(y.kind)||!jn.includes(y.kind))&&o("speaker_kind",`${h}.speaker.kind`,"invalid non-actor speaker kind");else if(ke(y.actor_id)){if(d(y.actor_id,y.state_id,"actor",`${h}.speaker`),!m.has(y.actor_id)){let E=r.get(y.actor_id),_=ke(y.state_id)&&E?.has(y.state_id)?y.state_id:E?.has("default")?"default":E?.values().next().value,x=g&&_?`scriptctl scene-ref ${g} actor:${y.actor_id} --state ${_} -p "$SCRIPT"`:void 0;o("actor_not_in_scene",`${h}.speaker.actor_id`,`actor ${y.actor_id} is not referenced by this scene`,x)}}else o("speaker",`${h}.speaker`,"speaker needs actor_id or kind")}},f=e.episodes;return Qn(f)?f.forEach((u,h)=>{let m=`$.episodes[${h}]`;if(!_t(u)||!ke(u.episode_id)){o("episode_id",m,"episode_id required");return}if(!Qn(u.scenes)){o("scenes",`${m}.scenes`,"scenes must be an array");return}u.scenes.forEach((g,w)=>{let y=`${m}.scenes[${w}]`;if(!_t(g)){o("scene",y,"scene must be an object");return}"context"in g&&o("legacy_field",`${y}.context`,"v3 forbids scene.context"),ke(g.scene_id)||o("scene_id",y,"scene_id required");let E=g.environment;E===void 0||_t(E)&&(!ke(E.time)||E.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!_t(E)||E.space!==void 0&&!ke(E.space)||!ke(E.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):Fr(E.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk"),(g.environment===void 0||_t(g.environment)&&(!ke(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 _=g.location;if(_!==null&&(!_t(_)||!ke(_.location_id)?o("location",`${y}.location`,"location must be null or {location_id}"):d(_.location_id,_.state_id,"location",`${y}.location`)),p(g.actors,"actor","actor_id",`${y}.actors`),p(g.props,"prop","prop_id",`${y}.props`),Qn(g.props)){let A=new Set;g.props.forEach((b,U)=>{!_t(b)||!ke(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 x=new Set(Qn(g.actors)?g.actors.filter(A=>_t(A)).map(A=>A.actor_id).filter(A=>ke(A)):[]);if(!Qn(g.actions))o("actions",`${y}.actions`,"actions must be an array");else{let A=ke(g.scene_id)?`${u.episode_id}/${g.scene_id}`:void 0;g.actions.forEach((b,U)=>l(b,`${y}.actions[${U}]`,x,A)),da(g.actions,`${y}.actions`,o)}})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}var rt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),le=e=>typeof e=="string",kn=e=>Array.isArray(e);function Id(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Id):rt(e)&&Object.values(e).every(Id)}function Xi(e,t,n){e!==void 0&&(!rt(e)||!Object.values(e).every(Id))&&n("extend",t,"extend must be an object containing JSON values")}function JE(e){for(let t=1;t<e.length;t++)if(e[t-1]>e[t])return!1;return!0}function Te(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(!rt(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"])le(e[u])||o("field",`$.${u}`,`${u} must be a string`);for(let u of["worldview_raw","synopsis","logline","theme"])e[u]!==void 0&&!le(e[u])&&o("field",`$.${u}`,`${u} must be a string`);e.main_characters!==void 0&&(!kn(e.main_characters)||!e.main_characters.every(u=>rt(u)&&le(u.name)&&le(u.role)))&&o("main_characters","$.main_characters","main_characters must contain {name, role} string records"),Xi(e.extend,"$.extend",o);let r=new Map,s=new Map,a=new Set,c=(u,h,m,g,w)=>{if(!kn(u)){o("field",w,`${w} must be an array`);return}let y=new Set;u.forEach((E,_)=>{let x=`${w}[${_}]`;if(!rt(E)){o("asset",x,"asset must be an object");return}let A=E[m];if(!$(h,A)){o("asset_id",`${x}.${m}`,`${m} must be ${h} ID`);return}if(y.has(A)&&o("dup_id",`${x}.${m}`,`duplicate ${m} ${A}`),y.add(A),r.set(A,h),!le(E[g])||E[g].trim()==="")o("asset_name",`${x}.${g}`,`${g} must be a non-empty string`);else if(h==="actor"){let I=E[g].trim().toLocaleLowerCase();a.has(I)&&o("dup_actor_name",`${x}.${g}`,`duplicate actor name ${E[g]}`),a.add(I)}if((!le(E.importance)||!Hn.includes(E.importance))&&o("importance",`${x}.importance`,`importance must be ${Hn.join("|")}`),h==="actor"&&E.role_type!==void 0&&(!le(E.role_type)||!qi.includes(E.role_type))&&o("role_type",`${x}.role_type`,`role_type must be ${qi.join("|")}`),le(E.description)||o("asset_desc",`${x}.description`,"description must be a string"),E.aliases!==void 0&&(!kn(E.aliases)||!E.aliases.every(le)))o("aliases",`${x}.aliases`,"aliases must be an array of strings");else if(kn(E.aliases)&&E.aliases.every(le)){let I=new Set,R=le(E[g])?E[g]:"";E.aliases.forEach((C,N)=>{C===""&&o("alias_empty",`${x}.aliases[${N}]`,"alias must not be empty"),C===R&&o("alias_equals_name",`${x}.aliases[${N}]`,"alias must differ from the asset name"),I.has(C)&&o("dup_alias",`${x}.aliases[${N}]`,`duplicate alias ${C}`),I.add(C)})}Xi(E.extend,`${x}.extend`,o);let b=new Set,U=new Set,v=0;!kn(E.states)||E.states.length===0?o("states",`${x}.states`,"states must be a non-empty array"):E.states.forEach((I,R)=>{let C=`${x}.states[${R}]`;if(!rt(I)){o("state",C,"state must be an object");return}let N=I.state_id;if(N!=="default"&&!$("state",N)){o("state_id",`${C}.state_id`,"state_id must be default or st plus six Base58 characters");return}b.has(N)&&o("dup_state",`${C}.state_id`,`duplicate state_id ${N}`),b.add(N),N==="default"&&v++,!le(I.state_name)||I.state_name.trim()===""?o("state_name",`${C}.state_name`,"state_name must be a non-empty string"):(U.has(I.state_name)&&o("dup_state_name",`${C}.state_name`,`duplicate state_name ${I.state_name}`),U.add(I.state_name)),le(I.description)||o("state_description",`${C}.description`,"description must be a string"),Xi(I.extend,`${C}.extend`,o)}),v!==1&&o("default_state",`${x}.states`,`exactly one default state required, found ${v}`),s.set(A,b)})};c(e.actors,"actor","actor_id","actor_name","$.actors"),c(e.locations,"location","location_id","location_name","$.locations"),c(e.props,"prop","prop_id","prop_name","$.props");let d=(u,h,m)=>{if(!kn(h)||h.length===0||!h.every(le))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,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}`)}),JE(g)||o("state_ids_order",m,"state_ids must be sorted lexically"),g},p=new Set,l=new Set,f=new Set;return kn(e.episodes)?e.episodes.forEach((u,h)=>{let m=`$.episodes[${h}]`;if(!rt(u)){o("episode",m,"episode must be an object");return}$("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&&!le(u[g])&&o("field",`${m}.${g}`,`${g} must be a string`);if(Xi(u.extend,`${m}.extend`,o),!kn(u.scenes)){o("scenes",`${m}.scenes`,"scenes must be an array");return}u.scenes.forEach((g,w)=>{let y=`${m}.scenes[${w}]`;if(!rt(g)){o("scene",y,"scene must be an object");return}$("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"),Xi(g.extend,`${y}.extend`,o),g.environment===void 0||rt(g.environment)&&(!le(g.environment.time)||g.environment.time.trim()==="")?i("scene_time_missing",`${y}.environment.time`,"scene time is required for production review"):!rt(g.environment)||g.environment.space!==void 0&&!le(g.environment.space)||!le(g.environment.time)?o("environment",`${y}.environment`,"environment must contain optional string space and a time string"):Fr(g.environment.time)||o("scene_time",`${y}.environment.time`,"scene time must be day|night|dawn|dusk"),(g.environment===void 0||rt(g.environment)&&(!le(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&&(!rt(g.location)||!$("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 E=new Map,_=(x,A,b,U)=>{if(!kn(x)){o("field",U,`${U} must be an array`);return}let v=new Set;x.forEach((I,R)=>{let C=`${U}[${R}]`;if(!rt(I)||!$(A,I[b])){o("ref",C,`${b} must be a typed v4 ID`);return}let N=I[b];"state_id"in I&&o("v3_field",`${C}.state_id`,"Script v4 scene references use state_ids"),v.has(N)&&o("dup_asset_ref",`${C}.${b}`,`duplicate ${A} ref ${N}`),v.add(N),r.get(N)!==A&&o("asset_ref",`${C}.${b}`,`${A} ${N} not found`);let M=d(N,I.state_ids,`${C}.state_ids`);A==="actor"&&E.set(N,new Set(M))})};if(_(g.actors,"actor","actor_id",`${y}.actors`),_(g.props,"prop","prop_id",`${y}.props`),!kn(g.actions)){o("actions",`${y}.actions`,"actions must be an array");return}g.actions.forEach((x,A)=>{let b=`${y}.actions[${A}]`;if(!rt(x)){o("action",b,"action must be an object");return}if($("action",x.action_id)?(f.has(x.action_id)&&o("dup_action_id",`${b}.action_id`,`duplicate action_id ${x.action_id}`),f.add(x.action_id)):o("action_id",`${b}.action_id`,"action_id must be ac plus six Base58 characters"),(!le(x.type)||!Kn.includes(x.type))&&o("action_type",`${b}.type`,`invalid action type ${String(x.type)}`),le(x.content)||o("content",`${b}.content`,"content must be a string"),"emotion"in x&&o("v3_field",`${b}.emotion`,"Script v4 does not allow emotion"),Xi(x.extend,`${b}.extend`,o),x.type==="dialogue"||x.type==="inner_thought")if(x.parenthetical!==void 0&&!le(x.parenthetical)&&o("parenthetical",`${b}.parenthetical`,"parenthetical must be a string"),!rt(x.speaker))o("speaker",`${b}.speaker`,"dialogue/inner_thought requires a speaker");else if(le(x.speaker.actor_id)){("kind"in x.speaker||"label"in x.speaker)&&o("speaker_shape",`${b}.speaker`,"actor speaker cannot contain non-actor speaker fields");let v=x.speaker.actor_id;(!$("actor",v)||r.get(v)!=="actor")&&o("speaker_actor",`${b}.speaker.actor_id`,`actor ${v} not found`);let I=E.get(v),R=s.get(v),C=le(x.speaker.state_id)&&R?.has(x.speaker.state_id)?x.speaker.state_id:void 0,N=R?.has("default")?"default":R?.values().next().value,M=C?[C]:N?[N]:[],K=$("scene",g.scene_id)&&$("actor",v)&&M.length>0?`scriptctl scene-ref ${g.scene_id} ${v} ${M.map(X=>`--state ${X}`).join(" ")} -p "$SCRIPT"`:void 0;if(I||o("actor_not_in_scene",`${b}.speaker.actor_id`,`actor ${v} is not referenced by this scene`,K),x.speaker.state_id!==void 0&&(!le(x.speaker.state_id)||!I?.has(x.speaker.state_id))){let X=C?[...new Set([...I??[],C])].sort():[],Ke=$("scene",g.scene_id)&&$("actor",v)&&X.length>0?`scriptctl scene-ref ${g.scene_id} ${v} ${X.map(se=>`--state ${se}`).join(" ")} -p "$SCRIPT"`:K;o("speaker_state",`${b}.speaker.state_id`,`speaker state ${String(x.speaker.state_id)} is not in this scene's actor state_ids`,Ke)}}else le(x.speaker.kind)?(("actor_id"in x.speaker||"state_id"in x.speaker)&&o("speaker_shape",`${b}.speaker`,"non-actor speaker cannot contain actor speaker fields"),jn.includes(x.speaker.kind)||o("speaker_kind",`${b}.speaker.kind`,"invalid non-actor speaker kind"),x.speaker.label!==void 0&&!le(x.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 x&&o("parenthetical_type",`${b}.parenthetical`,"parenthetical only belongs to speaking actions"),"speaker"in x&&o("speaker_type",`${b}.speaker`,"speaker only belongs to speaking actions");if(x.transition_prompt!==void 0){let v=x.transition_prompt;!rt(v)||!le(v.target)||!le(v.process)||v.process===""||!le(v.contrast)||v.contrast===""?o("transition_prompt",`${b}.transition_prompt`,"transition_prompt requires non-empty target/process/contrast"):r.has(v.target)||o("transition_target",`${b}.transition_prompt.target`,`asset ${v.target} not found`)}}),da(g.actions,`${y}.actions`,o)})}):o("episodes","$.episodes","episodes must be an array"),{ok:t.length===0,errors:t,warnings:n}}function ci(e,t=new Set,n){try{return n?Yr(e,t,n):Yr(e,t)}catch(o){throw o?.code!==Sd?o:new S(`Could not generate an unused ${e} ID.`,{exitCode:k,errorCode:"ID_SPACE_RETRY_EXHAUSTED",hint:"Retry the command. If this persists, inspect the configured ID generator."})}}function be(e,t=[]){throw new S(e,{exitCode:k,errorCode:"CREATIVE_DRAFT_INVALID",hint:"Use the readable creative draft schema; do not include Script IDs or .scriptctl syntax.",data:{actual:t.map(String)}})}function Fn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function W(e,t=""){return String(e??"").replace(/\s+/gu," ").trim()||t}function zE(e,t){let n=Number(e);return(!Number.isSafeInteger(n)||n<1)&&be(`${t} must be a positive integer.`,[e]),n}function KE(e){return e===void 0?{}:(Fn(e)||be("Action extensions must be an object."),structuredClone(e))}function jE(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 Io(e,t,n){for(let o=0;o<128;o+=1){let i=Cf.createHash("sha256").update(`${e}:${t}:${o}`).digest(),r="";for(let a=0;a<6;a+=1)r+=Wi[i[a]%Wi.length];let s=`${Zi[e]}${r}`;if(!n.has(s))return n.add(s),s}be(`Could not allocate a stable ${e} ID.`)}function HE(e){let t=W(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 QE(e){return`${Math.floor(e/6e4)}:${String(Math.floor(e%6e4/1e3)).padStart(2,"0")}.${String(e%1e3).padStart(3,"0")}`}function FE(e){let t=Number(e.extend?.duration_ms??e.extend?.rewrite_duration_ms);return Number.isFinite(t)&&t>0?Math.round(t):1200}function YE(e){let t=0;for(let n of e.scenes.flatMap(o=>o.actions))t=(HE(n.extend?.timestamp)??t)+FE(n);return t}function Tf(e){return e===void 0?[]:((!Array.isArray(e)||!e.every(Fn))&&be("Asset variants must be an array of readable objects."),e)}function qE(e,t){let n=e.assets;if(n===void 0)return[];Fn(n)||be("assets must be an object.");let o=n[t];return o===void 0?[]:((!Array.isArray(o)||!o.every(Fn))&&be(`assets.${t} must be an array.`),o)}function WE(e,t){return e==="actors"?t.actor_name:e==="locations"?t.location_name:t.prop_name}function ZE(e,t){return e[t]}function XE(e,t){return[WE(e,t),...t.aliases??[]].map(mt)}function Vf(e,t,n){let o=mt(n);return qE(e,t).find(i=>[i.name,...Array.isArray(i.aliases)?i.aliases:[]].map(r=>mt(W(r))).includes(o))??null}function $f(e,t){if(!e)return null;let n=mt(t);return Tf(e.variants).find(o=>{let i=mt(W(o.name));return i===n||["default","\u9ED8\u8BA4"].includes(n)&&["default","\u9ED8\u8BA4"].includes(i)})??null}function Df(e,t,n){let o=$f(e,n),i=W(o?.description);return(!o||!i)&&be(`${t}/${n} is a new variant and requires a readable assets declaration with a self-contained description.`),o}function e_(e,t){let n=W(t?.name);return n&&!["default","\u9ED8\u8BA4"].includes(mt(n))?n:e==="actors"?"\u57FA\u7840\u9020\u578B":e==="locations"?"\u5E38\u89C4\u5E03\u7F6E":"\u57FA\u7840\u5916\u89C2"}function t_(e,t,n,o,i,r){let s=Vf(t,n,o);s||be(`${o} is not an existing ${n} asset and has no readable declaration.`);let a=W(s.name,o),c=Tf(s.variants),d=$f(s,"\u9ED8\u8BA4")??c[0]??null;n==="actors"&&!W(s.description)&&be(`${a} requires an identity description separate from its appearance variants.`),n==="actors"&&!W(d?.description)&&be(`${a} requires its first variant to provide a self-contained base appearance description.`);let p=[{state_id:"default",state_name:e_(n,d),description:W(d?.description,W(s.description,`${a}\u7684\u57FA\u7840\u53C2\u8003\u5916\u89C2\u3002`))}];for(let u of c){let h=W(u.name);if(u===d||!h||["default","\u9ED8\u8BA4"].includes(mt(h)))continue;let m=Io("state",`${n}:${a}:${h}`,i);p.push({state_id:m,state_name:h,description:W(Df(s,a,h).description)}),r.states.push(`${a}/${h}`)}let l={aliases:Array.isArray(s.aliases)?[...new Set(s.aliases.map(u=>W(u)).filter(u=>u&&u!==a))]:[],importance:s.importance==="background"?"background":"featured",description:W(s.description,`${a}\u7684\u57FA\u7840\u8BBE\u5B9A\u3002`),states:p};if(n==="actors"){let u={...l,actor_id:Io("actor",a,i),actor_name:a,...s.roleType==="\u4E3B\u89D2"||s.roleType==="\u914D\u89D2"?{role_type:s.roleType}:{}};return e.actors.push(u),r.actors.push(a),u}if(n==="locations"){let u={...l,location_id:Io("location",a,i),location_name:a};return e.locations.push(u),r.locations.push(a),u}let f={...l,prop_id:Io("prop",a,i),prop_name:a};return e.props.push(f),r.props.push(a),f}function la(e,t,n,o,i,r){let s=W(o);s||be(`${n} reference requires a readable name.`);let a=mt(s);return ZE(e,n).find(d=>XE(n,d).includes(a))??t_(e,t,n,s,i,r)}function qr(e,t,n,o,i,r){let s=W(t,"\u9ED8\u8BA4"),a=mt(s),c=e.states.find(u=>mt(u.state_name)===a||u.state_id==="default"&&["default","\u9ED8\u8BA4"].includes(a));if(c)return c.state_id;let d="actor_name"in e?e.actor_name:"location_name"in e?e.location_name:e.prop_name,p=Vf(n,o,d),l=Df(p,d,s),f={state_id:Io("state",`${d}:${s}`,i),state_name:s,description:W(l.description)};return e.states.push(f),r.states.push(`${d}/${s}`),f.state_id}function Pf(e,t){return e===void 0?[]:((!Array.isArray(e)||!e.every(Fn))&&be(`${t} must be an array of readable references.`),e)}function pa(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 n_(e,t){return!!(e&&e.location?.location_id&&t.location?.location_id&&e.location.location_id===t.location.location_id&&W(e.environment?.space)===W(t.environment?.space)&&W(e.environment?.time)===W(t.environment?.time))}function o_(e,t,n,o,i,r,s,a){(!Array.isArray(e)||e.length===0||!e.every(Fn))&&be("scene.actions must contain at least one readable Action.");let c=structuredClone(o),d=r;return{actions:e.map((l,f)=>{let u=W(l.type,"action");["action","transition","dialogue","inner_thought"].includes(u)||be(`Action ${f+1} has an unsupported type.`,[u]);let h=W(l.content);h||be(`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=KE(l.extensions);g.timestamp=QE(d),g.duration_ms=m,g.rewrite_duration_ms!==void 0&&(g.rewrite_duration_ms=m);let w={action_id:Io("action",`${i}:${f+1}:${h}`,s),type:u,content:h,extend:g};if(d+=m,u==="action"||u==="transition")return w;let y=W(l.speaker);y||be(`Action ${f+1} requires a speaker.`);let E=y.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&");new RegExp(`^${E}\\s*[:\uFF1A]`,"iu").test(h)&&be(`Action ${f+1} repeats the speaker name in dialogue content.`),/^(?:“[^”]+”|「[^」]+」|『[^』]+』|"[^"]+")$/u.test(h)&&be(`Action ${f+1} wraps dialogue content in quotation marks.`);let _=mt(y);if(["\u65C1\u767D","narrator"].includes(_))return{...w,speaker:{kind:"broadcast",label:"\u65C1\u767D"},...W(l.parenthetical)?{parenthetical:W(l.parenthetical)}:{}};if(["\u753B\u5916\u97F3","offscreen"].includes(_))return{...w,speaker:{kind:"offscreen",label:"\u753B\u5916\u97F3"},...W(l.parenthetical)?{parenthetical:W(l.parenthetical)}:{}};let x=la(t,n,"actors",y,s,a),A=W(l.speakerVariant),b=c.find(v=>v.actor_id===x.actor_id),U;if(A)U=qr(x,A,n,"actors",s,a),b?b.state_ids=[...new Set([...b.state_ids,U])].sort():c.push({actor_id:x.actor_id,state_ids:[U]});else if(!b){let v=qr(x,"\u9ED8\u8BA4",n,"actors",s,a);c.push({actor_id:x.actor_id,state_ids:[v]})}return{...w,speaker:{actor_id:x.actor_id,...U?{state_id:U}:{}},...W(l.parenthetical)?{parenthetical:W(l.parenthetical)}:{}}}),actorRefs:c}}function Gf(e,t){(!Fn(t)||t.version!==1)&&be("Creative draft version must be 1."),(!Fn(t.episode)||!Fn(t.scene))&&be("Creative draft requires episode and scene objects.");let n=structuredClone(t),o=n.episode,i=n.scene,r=structuredClone(e),s=jE(r),a={actors:[],locations:[],props:[],states:[]},c=zE(o.number,"episode.number");c>r.episodes.length+1&&be("Episodes must be composed in order.",[c]);let d=r.episodes[c-1];d?(W(d.title)||(d.title=W(o.title,`\u7B2C ${c} \u96C6`)),W(d.synopsis)||(d.synopsis=W(o.synopsis,`\u7B2C ${c} \u96C6\u5267\u60C5\u3002`))):(d={episode_id:Io("episode",`episode:${c}`,s),title:W(o.title,`\u7B2C ${c} \u96C6`),synopsis:W(o.synopsis,`\u7B2C ${c} \u96C6\u5267\u60C5\u3002`),scenes:[]},r.episodes.push(d));let p=la(r,n,"locations",i.location,s,a),l=qr(p,i.locationVariant,n,"locations",s,a),f=Pf(i.actors,"scene.actors").map(I=>{let R=la(r,n,"actors",I.name,s,a);return{actor_id:R.actor_id,state_ids:[qr(R,I.variant,n,"actors",s,a)]}}),u=pa([],f,I=>I.actor_id),h=Pf(i.props,"scene.props").map(I=>{let R=la(r,n,"props",I.name,s,a);return{prop_id:R.prop_id,state_ids:[qr(R,I.variant,n,"props",s,a)]}}),m=pa([],h,I=>I.prop_id),g=d.scenes.at(-1),w={scene_id:Io("scene",`episode:${c}:scene:${d.scenes.length+1}:${W(i.title)}`,s),environment:{space:W(i.space,"interior"),time:W(i.time,"day")},location:{location_id:p.location_id,state_ids:[l]},actors:u,props:m,actions:[],extend:{scene_title:W(i.title,`\u7B2C ${d.scenes.length+1} \u573A`)}},y=W(i.boundary,"auto");["auto","new","continue"].includes(y)||be("scene.boundary must be auto, new, or continue.");let E=n_(g,w);y==="continue"&&!E&&be("scene.boundary=continue requires the same location, space, and time as the previous scene.");let _=y!=="new"&&E,x=_&&g?g:w,A=_?d.scenes.length:d.scenes.length+1,b=pa(x.actors,w.actors,I=>I.actor_id),U=o_(i.actions,r,n,b,x.scene_id,YE(d),s,a);x.actors=U.actorRefs,x.props=pa(x.props,w.props,I=>I.prop_id),x.location&&w.location&&(x.location.state_ids=[...new Set([...x.location.state_ids,...w.location.state_ids])].sort()),x.actions.push(...U.actions),_||d.scenes.push(x);let v=Te(r);return v.ok||be("Composed screenplay does not pass Script v4 validation.",v.errors.slice(0,12).map(I=>`${I.path}: ${I.message}`)),{script:r,validation:v,episodeNumber:c,sceneNumber:A,sceneId:x.scene_id,actionIds:U.actions.map(I=>I.action_id),joinedPreviousScene:_,created:a}}function qe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bn(e,t){return e[t]===void 0||typeof e[t]=="string"}function Ad(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Ad):qe(e)&&Object.values(e).every(Ad)}function er(e){return e.extend===void 0||qe(e.extend)&&Object.values(e.extend).every(Ad)}function kd(e){return e==="default"||$("state",e)}function i_(e){return qe(e)&&kd(e.state_id)&&typeof e.state_name=="string"&&typeof e.description=="string"&&er(e)}function bd(e){return typeof e.importance=="string"&&$t.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(i_)&&er(e)}function r_(e){return qe(e)&&$("actor",e.actor_id)&&typeof e.actor_name=="string"&&(e.role_type===void 0||typeof e.role_type=="string"&&_o.has(e.role_type))&&bd(e)}function s_(e){return qe(e)&&$("location",e.location_id)&&typeof e.location_name=="string"&&bd(e)}function a_(e){return qe(e)&&$("prop",e.prop_id)&&typeof e.prop_name=="string"&&bd(e)}function vd(e){return Array.isArray(e)&&e.every(kd)}function c_(e){return qe(e)&&$("actor",e.actor_id)&&vd(e.state_ids)}function d_(e){return qe(e)&&$("location",e.location_id)&&vd(e.state_ids)}function p_(e){return qe(e)&&$("prop",e.prop_id)&&vd(e.state_ids)}function l_(e){return $("actor",e.actor_id)&&(e.state_id===void 0||kd(e.state_id))}function u_(e){return typeof e.kind=="string"&&ai.has(e.kind)&&bn(e,"label")}function f_(e){return!(!qe(e)||!$("action",e.action_id)||typeof e.type!="string"||!tn.has(e.type)||typeof e.content!="string"||!bn(e,"parenthetical")||!er(e)||(e.type==="dialogue"||e.type==="inner_thought")&&(!qe(e.speaker)||!l_(e.speaker)&&!u_(e.speaker))||e.transition_prompt!==void 0&&(!qe(e.transition_prompt)||!$("actor",e.transition_prompt.target)&&!$("location",e.transition_prompt.target)&&!$("prop",e.transition_prompt.target)||typeof e.transition_prompt.process!="string"||typeof e.transition_prompt.contrast!="string"))}function m_(e){return!(!qe(e)||!$("scene",e.scene_id)||!Array.isArray(e.actors)||!e.actors.every(c_)||!Array.isArray(e.props)||!e.props.every(p_)||!Array.isArray(e.actions)||!e.actions.every(f_)||!er(e)||e.location!==null&&!d_(e.location)||e.environment!==void 0&&(!qe(e.environment)||!bn(e.environment,"space")||!bn(e.environment,"time")))}function g_(e){return qe(e)&&$("episode",e.episode_id)&&bn(e,"title")&&bn(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(m_)&&er(e)}function h_(e){return qe(e)&&e.version===4&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&bn(e,"worldview_raw")&&bn(e,"synopsis")&&bn(e,"logline")&&bn(e,"theme")&&(e.main_characters===void 0||Array.isArray(e.main_characters)&&e.main_characters.every(t=>qe(t)&&typeof t.name=="string"&&typeof t.role=="string"))&&Array.isArray(e.actors)&&e.actors.every(r_)&&Array.isArray(e.locations)&&e.locations.every(s_)&&Array.isArray(e.props)&&e.props.every(a_)&&Array.isArray(e.episodes)&&e.episodes.every(g_)&&er(e)}function tr(e){let t=Te(e);if(t.ok)return e;throw new S("The local file is not a valid Script v4 document.",{exitCode:k,errorCode:"SCRIPT_V4_INVALID",hint:"Run `scriptctl validate --script-path <path>` and repair the reported v4 fields.",data:{expected:["A valid Script v4 document"],actual:t.errors.slice(0,20).map(n=>`${n.path}: ${n.message}`)}})}function vn(e){if(h_(e))return e;throw new S("The local file is not a structurally readable Script v4 document.",{exitCode:k,errorCode:"SCRIPT_V4_SHAPE_INVALID",hint:"Repair the local Script v4 structure, then rerun the command.",data:{expected:["Script v4 with typed assets, episodes, scenes, references, and actions"],actual:[Array.isArray(e)?"array":typeof e]}})}import*as Wr from"node:crypto";import*as Ge from"node:fs";import*as Dt from"node:path";import y_ from"proper-lockfile";function Rd(e){if(Array.isArray(e))return e.map(Rd);if(e!==null&&typeof e=="object"){let t=e,n={};for(let o of Object.keys(t).sort())n[o]=Rd(t[o]);return n}return e}function je(e){let t=JSON.stringify(Rd(e));return`sha256:${Wr.createHash("sha256").update(t).digest("hex")}`}function Zr(e){return Ge.existsSync(e)?`sha256:${Wr.createHash("sha256").update(Ge.readFileSync(e)).digest("hex")}`:null}function Xr(e,t){let n=Zr(e);if(n!==t)throw new S("The local script changed while the command was running.",{exitCode:k,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and retry the command.",data:{actual:[`loadedFingerprint=${t??"<missing>"}`,`currentFingerprint=${n??"<missing>"}`,e]}})}function es(e){let t=Dt.resolve(e),n=Dt.join(Dt.dirname(t),".scriptctl"),o=Dt.basename(t);return{scriptPath:t,stateDir:n,metadataPath:Dt.join(n,`${o}.working-copy.json`),lockPath:Dt.join(n,o)}}async function ua(e,t){let n=es(e);Ge.mkdirSync(n.stateDir,{recursive:!0});let o=null;try{o=await y_.lock(n.lockPath,{realpath:!1,stale:12e4,update:1e4,retries:{retries:260,factor:1,minTimeout:500,maxTimeout:500}})}catch(i){throw new S("Timed out waiting for the script file lock.",{exitCode:q,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 We(e,t){fa(e,`${JSON.stringify(t,null,2)}
|
|
123
|
+
`)}function fa(e,t){let n=Dt.dirname(e);Ge.mkdirSync(n,{recursive:!0});let o=Dt.join(n,`.${Dt.basename(e)}.${process.pid}.${Wr.randomUUID()}.tmp`),i=Ge.openSync(o,"wx");try{Ge.writeFileSync(i,t,"utf-8"),Ge.fsyncSync(i)}finally{Ge.closeSync(i)}Ge.renameSync(o,e)}function ma(e){let t=es(e).metadataPath;if(!Ge.existsSync(t))return null;let n;try{n=JSON.parse(Ge.readFileSync(t,"utf-8"))}catch(i){throw Od(t,i instanceof Error?i.message:String(i))}if(n===null||typeof n!="object"||Array.isArray(n))throw Od(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 Od(t,"required fields are missing or invalid");return{schemaVersion:1,projectGroupNo:o.projectGroupNo,apiBaseUrl:o.apiBaseUrl,baseRevision:Number(o.baseRevision),baseContentHash:o.baseContentHash}}function ga(e,t){We(es(e).metadataPath,t)}function Od(e,t){return new S("Working copy metadata is invalid.",{exitCode:k,errorCode:"WORKING_COPY_METADATA_INVALID",hint:"Run `scriptctl checkout --discard-local` to recreate the working copy metadata.",data:{expected:["valid scriptctl working-copy metadata"],actual:[e,t]}})}function Kt(e,t){let n;try{n=JSON.parse(Ge.readFileSync(e,"utf-8"))}catch(i){throw new S("The local script changed while the command was running.",{exitCode:k,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and re-apply the operation.",data:{actual:[e,i instanceof Error?i.message:String(i)]}})}let o=je(n);if(o!==t)throw new S("The local script changed while the command was running.",{exitCode:k,errorCode:"LOCAL_SCRIPT_CHANGED",hint:"Read the latest local script and re-apply the operation.",data:{actual:[`loadedHash=${t}`,`currentHash=${o}`,e]}})}function O(e){return e==null?"":String(e)}function ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Yn(e){return Array.isArray(e)}function ce(e){return Array.isArray(e)?e:[]}function Md(e,t=[]){throw new S(e,{exitCode:B,errorCode:"CREATIVE_DRAFT_USAGE_INVALID",hint:"Run `scriptctl authoring compose <draft.json> --script-path <script.json>` and apply the returned plan digest.",data:{actual:t}})}function Bf(e,t){let n=Kf.resolve(e),o;try{o=zf.readFileSync(n)}catch{throw new S(`${t} does not exist.`,{exitCode:k,errorCode:"CREATIVE_DRAFT_SOURCE_UNAVAILABLE",data:{actual:[n]}})}try{return{path:n,bytes:o,value:JSON.parse(o.toString("utf-8"))}}catch(i){throw new S(`${t} is not valid JSON.`,{exitCode:k,errorCode:"CREATIVE_DRAFT_JSON_INVALID",data:{actual:[n,i instanceof Error?i.message:String(i)]}})}}function jf(e){let t=Array.isArray(e._args)?e._args:[],n=typeof t[0]=="string"?t[0]:"";(!n||n==="-")&&Md("Creative draft input must be a named JSON file.",[n||"<missing>"]);let o=Bf(n,"The creative draft"),i=he(e),r=Bf(i,"The target Script v4 file"),s=vn(r.value),a=je(s),c=Gf(s,o.value),d=`sha256:${Jf.createHash("sha256").update(o.bytes).digest("hex")}`,p={version:1,op:"compose",sourceDigest:d,baseline:a,proposed:je(c.script),episodeNumber:c.episodeNumber,sceneNumber:c.sceneNumber,sceneId:c.sceneId,actionIds:c.actionIds,joinedPreviousScene:c.joinedPreviousScene,created:c.created},l=`sha256:${_e(JSON.stringify(p))}`,f=e.apply===!0,u=O(e.plan).trim();if(f&&!u&&Md("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!f&&u&&Md("--plan is only valid together with --apply.",[`plan=${u}`]),f&&u!==l)throw new S("The supplied plan does not match the current draft or script baseline.",{exitCode:k,errorCode:"CREATIVE_DRAFT_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[l],actual:[u]}});return f&&(Kt(i,a),We(i,c.script)),[{text:[`${f?"Applied":"Planned"} readable scene draft as episode ${c.episodeNumber}, scene ${c.sceneNumber}${c.joinedPreviousScene?" (joined previous scene)":""}`,`plan: ${l}`].join(`
|
|
124
|
+
`),data:{op:"compose",applied:f,source_path:o.path,source_digest:d,script_path:i,baseline:a,plan_digest:l,episode_number:c.episodeNumber,scene_number:c.sceneNumber,scene_id:c.sceneId,action_ids:c.actionIds,joined_previous_scene:c.joinedPreviousScene,created:c.created,validation:c.validation}},V]}import*as tm from"node:fs";import*as nm from"node:path";var nn={line:1,column:1};function w_(e){let t=[];for(let n of e.actors){let o=structuredClone(n);o.states=[],t.push({declarationKind:"actor",value:o,source:nn});for(let i of n.states)t.push(Nd("actor",n.actor_id,i))}for(let n of e.locations){let o=structuredClone(n);o.states=[],t.push({declarationKind:"location",value:o,source:nn});for(let i of n.states)t.push(Nd("location",n.location_id,i))}for(let n of e.props){let o=structuredClone(n);o.states=[],t.push({declarationKind:"prop",value:o,source:nn});for(let i of n.states)t.push(Nd("prop",n.prop_id,i))}return t}function Nd(e,t,n){return{declarationKind:"state",ownerKind:e,ownerId:t,value:structuredClone(n),source:nn}}function Hf(e){let t={kind:"script",title:e.title,worldview:e.worldview,style:e.style,episodes:structuredClone(e.episodes),source:nn};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:w_(e),targets:[t],targetKind:"script"}}function nr(e,t){return{version:1,declarations:[],targets:t,targetKind:e}}function x_(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function E_(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function me(e,t,n){let o=[e,...t].map(x_).join("|"),i=E_(n);return`[${o}]${i.length>0?` ${i}`:""}`}function Ud(e){if(Array.isArray(e))return e.map(Ud);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=Ud(e[n]);return t}return e}function qn(e){return e===void 0?[]:[me("extensions",[],""),...Object.keys(e).sort().map(t=>me("extend",[t],JSON.stringify(Ud(e[t]))))]}function __(e){return"actor_id"in e?e.state_id===void 0?e.actor_id:`${e.actor_id}/${e.state_id}`:e.label===void 0?e.kind:`${e.kind}:${e.label}`}function Qf(e){let t=qn(e.extend);if(e.transition_prompt!==void 0&&t.push(me("prompt",[e.transition_prompt.target,e.transition_prompt.process,e.transition_prompt.contrast],"")),e.type==="dialogue"||e.type==="inner_thought"){let o=e.type==="dialogue"?"dlg":"think",i=[__(e.speaker)];return e.emotion!==void 0&&i.push(e.emotion),t.push(me(o,i,e.content)),t}let n=e.type==="action"?"act":"trans";return t.push(me(n,e.emotion===void 0?[]:[e.emotion],e.content)),t}function Pd(e,t){let n=[...qn(e.extend),`<scene ${t}>`];if(e.environment!==void 0&&(e.environment.time!==void 0?n.push(me("environment",[e.environment.space??"",e.environment.time],"")):e.environment.space!==void 0?n.push(me("environment",[e.environment.space],"")):n.push(me("environment",[],""))),e.location===null)n.push(me("location",[],""));else{let o=[e.location.location_id];e.location.state_id!==void 0&&o.push(e.location.state_id),n.push(me("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(me("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(me("prop",i,""))}n.push("","<body>");for(let o of e.actions)n.push(...Qf(o));return n.push("</body>","","</scene>"),n}function Ld(e){let t=[...qn(e.extend),`<episode id=${e.episode_id}>`];return e.title!==void 0&&t.push(me("title",[],e.title)),e.synopsis!==void 0&&t.push(me("synopsis",[],e.synopsis)),(e.title!==void 0||e.synopsis!==void 0)&&e.scenes.length>0&&t.push(""),e.scenes.forEach((n,o)=>{t.push(...Pd(n,`id=${n.scene_id}`)),o<e.scenes.length-1&&t.push("")}),t.push("</episode>"),t}function S_(e){if(e.declarationKind==="state")return I_(e.ownerKind,e.ownerId,e.value);let t=e.value,n=qn(t.extend);t.aliases!==void 0&&n.push(me("aliases",[],""));for(let o of t.aliases??[])n.push(me("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(me("actor",i,o.description))}else if(e.declarationKind==="location"){let o=e.value;n.push(me("location",[o.location_id,o.location_name,o.importance],o.description))}else{let o=e.value;n.push(me("prop",[o.prop_id,o.prop_name,o.importance],o.description))}return n}function I_(e,t,n){return[...qn(n.extend),me("state",[`${e}:${t}`,n.state_id,n.state_name],n.description)]}function A_(e){switch(e.kind){case"script":{let t=[...qn(e.extend),"<script>"];if(t.push(me("title",[],e.title)),t.push(me("worldview",[],e.worldview)),e.worldviewRaw!==void 0&&t.push(me("worldview-raw",[],e.worldviewRaw)),t.push(me("style",[],e.style)),e.synopsis!==void 0&&t.push(me("synopsis",[],e.synopsis)),e.logline!==void 0&&t.push(me("logline",[],e.logline)),e.theme!==void 0&&t.push(me("theme",[],e.theme)),e.mainCharacters!==void 0){t.push(me("main-characters",[],""));for(let n of e.mainCharacters)t.push(me("main-character",[n.name,n.role],""))}return e.episodes.length>0&&t.push(""),e.episodes.forEach((n,o)=>{t.push(...Ld(n)),o<e.episodes.length-1&&t.push("")}),t.push("</script>"),t}case"episode":return Ld(e.value);case"episode-span":{let t=[...qn(e.extend),`<episode-span from=${e.from} through=${e.through}>`];return e.episodes.forEach((n,o)=>{t.push(...Ld(n)),o<e.episodes.length-1&&t.push("")}),t.push("</episode-span>"),t}case"scene":return Pd(e.value,`id=${e.value.scene_id} parent=${e.parent}`);case"scene-span":{let t=[...qn(e.extend),`<scene-span parent=${e.parent} from=${e.from} through=${e.through}>`];return e.scenes.forEach((n,o)=>{t.push(...Pd(n,`id=${n.scene_id}`)),o<e.scenes.length-1&&t.push("")}),t.push("</scene-span>"),t}case"action-span":{let t=[...qn(e.extend),`<action-span parent=${e.parent} from=${e.from} through=${e.through}>`,"<body>"];for(let n of e.actions)t.push(...Qf(n));return t.push("</body>","</action-span>"),t}}}function Ff(e){let t=["<authoring version=1>",""];if(e.declarations.length>0){t.push("<create>");for(let n of e.declarations)t.push(...S_(n));t.push("</create>","")}return e.targets.forEach((n,o)=>{t.push(...A_(n)),o<e.targets.length-1&&t.push("")}),t.push("","</authoring>"),`${t.join(`
|
|
125
125
|
`)}
|
|
126
|
-
`}function We(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function It(e,t){return e[t]===void 0||typeof e[t]=="string"}function Ld(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Ld):We(e)&&Object.values(e).every(Ld)}function Ao(e){return e.extend===void 0||We(e.extend)&&Object.values(e.extend).every(Ld)}function Ud(e){return We(e)&&typeof e.state_id=="string"&&typeof e.state_name=="string"&&typeof e.description=="string"&&Ao(e)}function __(e){return We(e)&&typeof e.actor_id=="string"&&typeof e.actor_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&$t.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(Ud)&&Ao(e)}function S_(e){return We(e)&&typeof e.location_id=="string"&&typeof e.location_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&$t.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(Ud)&&Ao(e)}function I_(e){return We(e)&&typeof e.prop_id=="string"&&typeof e.prop_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&$t.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(Ud)&&Ao(e)}function A_(e){if(!We(e)||typeof e.type!="string"||!tn.has(e.type)||typeof e.content!="string"||!It(e,"emotion"))return!1;if(e.speaker!==void 0){if(!We(e.speaker))return!1;if(typeof e.speaker.actor_id=="string"){if(!It(e.speaker,"state_id"))return!1}else if(typeof e.speaker.kind=="string"){if(!si.has(e.speaker.kind)||!It(e.speaker,"label"))return!1}else return!1}return e.transition_prompt!==void 0&&(!We(e.transition_prompt)||typeof e.transition_prompt.target!="string"||typeof e.transition_prompt.process!="string"||typeof e.transition_prompt.contrast!="string")?!1:Ao(e)}function k_(e){return!We(e)||typeof e.scene_id!="string"||!Array.isArray(e.actors)||!Array.isArray(e.props)||!Array.isArray(e.actions)||!e.actions.every(A_)||!e.actors.every(t=>We(t)&&typeof t.actor_id=="string"&&It(t,"state_id"))||!e.props.every(t=>We(t)&&typeof t.prop_id=="string"&&It(t,"state_id"))||e.location!==null&&(!We(e.location)||typeof e.location.location_id!="string"||!It(e.location,"state_id"))||e.environment!==void 0&&(!We(e.environment)||!It(e.environment,"space")||!It(e.environment,"time"))?!1:Ao(e)}function b_(e){return We(e)&&typeof e.episode_id=="string"&&It(e,"title")&&It(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(k_)&&Ao(e)}function v_(e){return We(e)&&e.version===3&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&It(e,"worldview_raw")&&It(e,"synopsis")&&It(e,"logline")&&It(e,"theme")&&(e.main_characters===void 0||Array.isArray(e.main_characters)&&e.main_characters.every(t=>We(t)&&typeof t.name=="string"&&typeof t.role=="string"))&&Array.isArray(e.actors)&&e.actors.every(__)&&Array.isArray(e.locations)&&e.locations.every(S_)&&Array.isArray(e.props)&&e.props.every(I_)&&Array.isArray(e.episodes)&&e.episodes.every(b_)&&Ao(e)}function Gt(e){if(v_(e))return e;throw new S("The local file is not a structurally readable Script v3 document.",{exitCode:k,errorCode:"SCRIPT_V3_SHAPE_INVALID",hint:"Repair the local Script v3 structure, then rerun authoring.",data:{expected:["Script v3 with typed assets, episodes, scenes, and actions"],actual:[Array.isArray(e)?"array":typeof e]}})}var Pd=[3,4],O_={3:{version:3,require:Gt,requireStructurallyReadable:Gt,validate:St},4:{version:4,require:er,requireStructurallyReadable:vn,validate:Te}};function ko(e){return typeof e=="number"&&Pd.some(t=>t===e)}function ci(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new S("script.json must be an object with an explicit version.",{exitCode:k,errorCode:"SCRIPT_VERSION_MISSING",data:{expected:["version: 3 or version: 4"],actual:[Array.isArray(e)?"array":typeof e]}});let t=e.version;if(ko(t))return t;throw new S("script.json must declare version 3 or version 4.",{exitCode:k,errorCode:t===void 0?"SCRIPT_VERSION_MISSING":"SCRIPT_VERSION_UNSUPPORTED",hint:"Use an explicit supported script version; scriptctl does not infer a version from document shape.",data:{expected:["version: 3 or version: 4"],actual:[String(t)]}})}function Cd(e){return O_[ci(e)]}function ma(e){return Cd(e).require(e)}function ga(e){return Cd(e).requireStructurallyReadable(e)}function es(e){return Cd(e).validate(e)}function ha(e){throw new S("Use a bare typed v4 ID or asset/state address.",{exitCode:B,errorCode:"V4_ADDRESS_INVALID",data:{expected:["ep\u2026 | scn\u2026 | ac\u2026 | act\u2026 | loc\u2026 | prp\u2026 | asset_id/state_id"],actual:[e||"<empty>"]}})}function ts(e){let t=typeof e=="string"?e.trim():"",n=t.indexOf("/");if(n>=0){n!==t.lastIndexOf("/")&&ha(t);let o=t.slice(0,n),i=t.slice(n+1);return i!=="default"&&!$("state",i)&&ha(t),$("actor",o)?{kind:"state",assetKind:"actor",assetId:o,stateId:i}:$("location",o)?{kind:"state",assetKind:"location",assetId:o,stateId:i}:$("prop",o)?{kind:"state",assetKind:"prop",assetId:o,stateId:i}:ha(t)}return $("episode",t)?{kind:"episode",id:t}:$("scene",t)?{kind:"scene",id:t}:$("action",t)?{kind:"action",id:t}:$("actor",t)?{kind:"asset",assetKind:"actor",id:t}:$("location",t)?{kind:"asset",assetKind:"location",id:t}:$("prop",t)?{kind:"asset",assetKind:"prop",id:t}:ha(t)}function di(e){return e.episodes.map((t,n)=>({episode:t,episodeIndex:n}))}function Zn(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 pi(e){let t=[],n=0,o=0;return e.episodes.forEach((i,r)=>{i.scenes.forEach((s,a)=>{s.actions.forEach((c,d)=>{t.push({episode:i,episodeIndex:r,scene:s,sceneIndex:a,globalSceneIndex:n,action:c,actionIndex:d,globalActionIndex:o}),o++}),n++})}),t}function On(e,t){return di(e).find(n=>n.episode.episode_id===t)??null}function Wn(e,t){return Zn(e).find(n=>n.scene.scene_id===t)??null}function bo(e,t){throw new S(t,{exitCode:B,errorCode:"ORDINAL_ANCHOR_INVALID",data:{expected:["@ep:N | @ep:N/scn:N | @ep:N/scn:N/ac:N | @scn:N | @scn:N/ac:N | @ac:N"],actual:[e]}})}function Rn(e,t){return/^[1-9]\d*$/.test(e)||bo(t,"Ordinal positions are 1-based positive integers."),Number(e)}function ya(e,t){let n=/^@ep:(\d+)$/.exec(t);if(n){let o=di(e)[Rn(n[1],t)-1];return o||bo(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=di(e)[Rn(n[1],t)-1],i=o?.episode.scenes[Rn(n[2],t)-1];return(!o||!i)&&bo(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=di(e)[Rn(n[1],t)-1],i=o?.episode.scenes[Rn(n[2],t)-1],r=i?.actions[Rn(n[3],t)-1];return(!o||!i||!r)&&bo(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=Zn(e)[Rn(n[1],t)-1];return o||bo(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=Zn(e)[Rn(n[1],t)-1],i=o?.scene.actions[Rn(n[2],t)-1];return(!o||!i)&&bo(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=pi(e)[Rn(n[1],t)-1];return o||bo(t,"Global action ordinal is outside the current script."),{kind:"action",id:o.action.action_id}}return bo(t,"Ordinal anchor syntax is not supported.")}function nr(e,t){throw new S(e,{exitCode:B,errorCode:"V4_SELECTOR_INVALID",data:{expected:["typed v4 ID or same-kind inclusive range; comma joins regions"],actual:[t]}})}function Hf(e,t){return e.kind==="episode"||e.kind==="scene"||e.kind==="action"?e.kind:nr("Asset and state addresses are not narrative range anchors.",t)}function Qf(e){return e.kind==="state"?`${e.assetId}/${e.stateId}`:e.id}function Ff(e,t,n){return t.startsWith("@")?(n||nr("Ordinal anchors are query-only.",t),ya(e,t)):ts(t)}function R_(e,t,n,o){let i=e.indexOf(t),r=e.indexOf(n);(i<0||r<0)&&nr("Range endpoint does not exist in the current script.",o);let s=Math.min(i,r),a=Math.max(i,r);return e.slice(s,a+1)}function wa(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=di(e),r=Zn(e),s=pi(e),a=i.map(g=>g.episode.episode_id),c=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(E=>f.add(E.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||nr("Selector contains an empty region.",o);let y=w.split("..");y.length>2&&nr("Selector region has too many range delimiters.",w);let E=Ff(e,y[0].trim(),n.allowOrdinals),_=Ff(e,(y[1]??y[0]).trim(),n.allowOrdinals),x=Hf(E,w);Hf(_,w)!==x&&nr("Range endpoints must have the same kind.",w);let A=Qf(E),b=Qf(_),v=R_(x==="episode"?a:x==="scene"?c:d,A,b,w);x==="episode"?v.forEach(u):x==="scene"?v.forEach(h):v.forEach(m)}return{isEmpty:!1,isWholeScript:!1,matchesEpisode:g=>p.has(g),matchesScene:g=>l.has(g),matchesAction:g=>f.has(g)}}function vo(e,t){throw new S(e,{exitCode:B,errorCode:"AUTHORING_SELECTOR_INVALID",data:{actual:t}})}function M_(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function N_(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function de(e,t,n=""){let o=[e,...t].map(M_).join("|"),i=N_(n);return`[${o}]${i?` ${i}`:""}`}function $d(e){if(Array.isArray(e))return e.map($d);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=$d(e[n]);return t}return e}function Oo(e){return e===void 0?[]:[de("extensions",[]),...Object.keys(e).sort().map(t=>de("extend",[t],JSON.stringify($d(e[t]))))]}function L_(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 Yf(e){let t=Oo(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 n=[e.action_id,L_(e.speaker)];"parenthetical"in e&&n.push(e.parenthetical??""),t.push(de(e.type==="dialogue"?"dlg":"think",n,e.content))}else t.push(de(e.type==="action"?"act":"trans",[e.action_id],e.content));return t}function Dd(e,t){let n=[...Oo(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(de("environment",o))}n.push(e.location===null?de("location",[]):de("location",[e.location.location_id,...e.location.state_ids]));for(let o of e.actors)n.push(de("cast",[o.actor_id,...o.state_ids]));for(let o of e.props)n.push(de("prop",[o.prop_id,...o.state_ids]));return n.push("","<body>"),e.actions.forEach(o=>n.push(...Yf(o))),n.push("</body>","","</scene>"),n}function Gd(e){let t=[...Oo(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.scenes.forEach((n,o)=>{(o>0||e.title!==void 0||e.synopsis!==void 0)&&t.push(""),t.push(...Dd(n,`id=${n.scene_id}`))}),t.push("</episode>"),t}function Td(e,t){return[...Oo(t.extend),de("state",[e,t.state_id,t.state_name],t.description)]}function U_(e){let t=["<create>"];for(let n of e.actors){t.push(...Oo(n.extend)),n.aliases!==void 0&&(t.push(de("aliases",[])),n.aliases.forEach(i=>t.push(de("alias",[],i))));let o=[n.actor_id,n.actor_name,n.importance];n.role_type!==void 0&&o.push(n.role_type),t.push(de("actor",o,n.description)),n.states.forEach(i=>t.push(...Td(n.actor_id,i)))}for(let n of e.locations)t.push(...Oo(n.extend)),n.aliases!==void 0&&(t.push(de("aliases",[])),n.aliases.forEach(o=>t.push(de("alias",[],o)))),t.push(de("location",[n.location_id,n.location_name,n.importance],n.description)),n.states.forEach(o=>t.push(...Td(n.location_id,o)));for(let n of e.props)t.push(...Oo(n.extend)),n.aliases!==void 0&&(t.push(de("aliases",[])),n.aliases.forEach(o=>t.push(de("alias",[],o)))),t.push(de("prop",[n.prop_id,n.prop_name,n.importance],n.description)),n.states.forEach(o=>t.push(...Td(n.prop_id,o)));return t.push("</create>"),t}function P_(e){let t=[...Oo(e.extend),"<script>"];return t.push(de("title",[],e.title),de("worldview",[],e.worldview)),e.worldview_raw!==void 0&&t.push(de("worldview-raw",[],e.worldview_raw)),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.main_characters!==void 0&&(t.push(de("main-characters",[])),e.main_characters.forEach(n=>t.push(de("main-character",[n.name,n.role])))),e.episodes.forEach(n=>t.push("",...Gd(n))),t.push("</script>"),t}function C_(e){return e.trim()||vo("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]?vo("Selector region is invalid.",[t]):{left:n[0],right:n[1]??n[0]}})}function Vd(e,t,n,o,i){let r=-1;return C_(i).map(s=>{let a=f=>{if(!f.startsWith("@"))return f;let u=ya(e,f);return u.kind!==t?vo("Selector endpoint kind does not match the export kind.",[f,t]):u.id},c=o.indexOf(a(s.left)),d=o.indexOf(a(s.right));(c<0||d<0)&&vo("Selector endpoint was not found.",[s.left,s.right]);let p=Math.min(c,d),l=Math.max(c,d);return p<=r&&vo("Selector regions must follow current document order without overlap.",[`${s.left}..${s.right}`]),r=l,n.slice(p,l+1)})}function qf(e,t,n){let o=["<authoring version=1>",""],i=0;if(t==="script")o.push(...U_(e),"",...P_(e)),i=1;else if(t==="episodes"){let r=wa(e,n,{allowOrdinals:!0}),s=e.episodes.filter(a=>r.matchesEpisode(a.episode_id));s.forEach((a,c)=>{c>0&&o.push(""),o.push(...Gd(a))}),i=s.length}else if(t==="episode-spans"){let r=Vd(e,"episode",e.episodes,e.episodes.map(s=>s.episode_id),n);for(let[s,a]of r.entries())s>0&&o.push(""),o.push(`<episode-span range=${a[0].episode_id}..${a.at(-1).episode_id}>`),a.forEach(c=>o.push(...Gd(c))),o.push("</episode-span>"),i++}else if(t==="scenes"){let r=wa(e,n,{allowOrdinals:!0}),s=Zn(e).filter(a=>r.matchesScene(a.scene.scene_id));s.forEach((a,c)=>{c>0&&o.push(""),o.push(...Dd(a.scene,`id=${a.scene.scene_id} parent=${a.episode.episode_id}`))}),i=s.length}else if(t==="scene-spans"){let r=Zn(e),s=Vd(e,"scene",r,r.map(a=>a.scene.scene_id),n);for(let[a,c]of s.entries()){let d=c[0].episode.episode_id;c.every(p=>p.episode.episode_id===d)||vo("A scene span must remain inside one episode.",[c[0].scene.scene_id,c.at(-1).scene.scene_id]),a>0&&o.push(""),o.push(`<scene-span parent=${d} range=${c[0].scene.scene_id}..${c.at(-1).scene.scene_id}>`),c.forEach(p=>o.push(...Dd(p.scene,`id=${p.scene.scene_id}`))),o.push("</scene-span>"),i++}}else{let r=pi(e),s=Vd(e,"action",r,r.map(a=>a.action.action_id),n);for(let[a,c]of s.entries()){let d=c[0].scene.scene_id;c.every(p=>p.scene.scene_id===d)||vo("An action span must remain inside one scene.",[c[0].action.action_id,c.at(-1).action.action_id]),a>0&&o.push(""),o.push(`<action-span parent=${d} range=${c[0].action.action_id}..${c.at(-1).action.action_id}>`,"<body>"),c.forEach(p=>o.push(...Yf(p.action))),o.push("</body>","</action-span>"),i++}}return i===0&&vo("Selector did not match any authoring targets.",[n||"<empty>"]),o.push("","</authoring>"),{content:`${o.join(`
|
|
126
|
+
`}function Ze(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function It(e,t){return e[t]===void 0||typeof e[t]=="string"}function Cd(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Cd):Ze(e)&&Object.values(e).every(Cd)}function Ao(e){return e.extend===void 0||Ze(e.extend)&&Object.values(e.extend).every(Cd)}function Td(e){return Ze(e)&&typeof e.state_id=="string"&&typeof e.state_name=="string"&&typeof e.description=="string"&&Ao(e)}function k_(e){return Ze(e)&&typeof e.actor_id=="string"&&typeof e.actor_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&$t.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(Td)&&Ao(e)}function b_(e){return Ze(e)&&typeof e.location_id=="string"&&typeof e.location_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&$t.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(Td)&&Ao(e)}function v_(e){return Ze(e)&&typeof e.prop_id=="string"&&typeof e.prop_name=="string"&&typeof e.description=="string"&&typeof e.importance=="string"&&$t.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(Td)&&Ao(e)}function O_(e){if(!Ze(e)||typeof e.type!="string"||!tn.has(e.type)||typeof e.content!="string"||!It(e,"emotion"))return!1;if(e.speaker!==void 0){if(!Ze(e.speaker))return!1;if(typeof e.speaker.actor_id=="string"){if(!It(e.speaker,"state_id"))return!1}else if(typeof e.speaker.kind=="string"){if(!ai.has(e.speaker.kind)||!It(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:Ao(e)}function R_(e){return!Ze(e)||typeof e.scene_id!="string"||!Array.isArray(e.actors)||!Array.isArray(e.props)||!Array.isArray(e.actions)||!e.actions.every(O_)||!e.actors.every(t=>Ze(t)&&typeof t.actor_id=="string"&&It(t,"state_id"))||!e.props.every(t=>Ze(t)&&typeof t.prop_id=="string"&&It(t,"state_id"))||e.location!==null&&(!Ze(e.location)||typeof e.location.location_id!="string"||!It(e.location,"state_id"))||e.environment!==void 0&&(!Ze(e.environment)||!It(e.environment,"space")||!It(e.environment,"time"))?!1:Ao(e)}function M_(e){return Ze(e)&&typeof e.episode_id=="string"&&It(e,"title")&&It(e,"synopsis")&&Array.isArray(e.scenes)&&e.scenes.every(R_)&&Ao(e)}function N_(e){return Ze(e)&&e.version===3&&typeof e.title=="string"&&typeof e.worldview=="string"&&typeof e.style=="string"&&It(e,"worldview_raw")&&It(e,"synopsis")&&It(e,"logline")&&It(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(k_)&&Array.isArray(e.locations)&&e.locations.every(b_)&&Array.isArray(e.props)&&e.props.every(v_)&&Array.isArray(e.episodes)&&e.episodes.every(M_)&&Ao(e)}function Gt(e){if(N_(e))return e;throw new S("The local file is not a structurally readable Script v3 document.",{exitCode:k,errorCode:"SCRIPT_V3_SHAPE_INVALID",hint:"Repair the local Script v3 structure, then rerun authoring.",data:{expected:["Script v3 with typed assets, episodes, scenes, and actions"],actual:[Array.isArray(e)?"array":typeof e]}})}var Vd=[3,4],L_={3:{version:3,require:Gt,requireStructurallyReadable:Gt,validate:St},4:{version:4,require:tr,requireStructurallyReadable:vn,validate:Te}};function ko(e){return typeof e=="number"&&Vd.some(t=>t===e)}function di(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new S("script.json must be an object with an explicit version.",{exitCode:k,errorCode:"SCRIPT_VERSION_MISSING",data:{expected:["version: 3 or version: 4"],actual:[Array.isArray(e)?"array":typeof e]}});let t=e.version;if(ko(t))return t;throw new S("script.json must declare version 3 or version 4.",{exitCode:k,errorCode:t===void 0?"SCRIPT_VERSION_MISSING":"SCRIPT_VERSION_UNSUPPORTED",hint:"Use an explicit supported script version; scriptctl does not infer a version from document shape.",data:{expected:["version: 3 or version: 4"],actual:[String(t)]}})}function $d(e){return L_[di(e)]}function ha(e){return $d(e).require(e)}function ya(e){return $d(e).requireStructurallyReadable(e)}function ts(e){return $d(e).validate(e)}function wa(e){throw new S("Use a bare typed v4 ID or asset/state address.",{exitCode:B,errorCode:"V4_ADDRESS_INVALID",data:{expected:["ep\u2026 | scn\u2026 | ac\u2026 | act\u2026 | loc\u2026 | prp\u2026 | asset_id/state_id"],actual:[e||"<empty>"]}})}function ns(e){let t=typeof e=="string"?e.trim():"",n=t.indexOf("/");if(n>=0){n!==t.lastIndexOf("/")&&wa(t);let o=t.slice(0,n),i=t.slice(n+1);return i!=="default"&&!$("state",i)&&wa(t),$("actor",o)?{kind:"state",assetKind:"actor",assetId:o,stateId:i}:$("location",o)?{kind:"state",assetKind:"location",assetId:o,stateId:i}:$("prop",o)?{kind:"state",assetKind:"prop",assetId:o,stateId:i}:wa(t)}return $("episode",t)?{kind:"episode",id:t}:$("scene",t)?{kind:"scene",id:t}:$("action",t)?{kind:"action",id:t}:$("actor",t)?{kind:"asset",assetKind:"actor",id:t}:$("location",t)?{kind:"asset",assetKind:"location",id:t}:$("prop",t)?{kind:"asset",assetKind:"prop",id:t}:wa(t)}function pi(e){return e.episodes.map((t,n)=>({episode:t,episodeIndex:n}))}function Wn(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 li(e){let t=[],n=0,o=0;return e.episodes.forEach((i,r)=>{i.scenes.forEach((s,a)=>{s.actions.forEach((c,d)=>{t.push({episode:i,episodeIndex:r,scene:s,sceneIndex:a,globalSceneIndex:n,action:c,actionIndex:d,globalActionIndex:o}),o++}),n++})}),t}function On(e,t){return pi(e).find(n=>n.episode.episode_id===t)??null}function Zn(e,t){return Wn(e).find(n=>n.scene.scene_id===t)??null}function bo(e,t){throw new S(t,{exitCode:B,errorCode:"ORDINAL_ANCHOR_INVALID",data:{expected:["@ep:N | @ep:N/scn:N | @ep:N/scn:N/ac:N | @scn:N | @scn:N/ac:N | @ac:N"],actual:[e]}})}function Rn(e,t){return/^[1-9]\d*$/.test(e)||bo(t,"Ordinal positions are 1-based positive integers."),Number(e)}function xa(e,t){let n=/^@ep:(\d+)$/.exec(t);if(n){let o=pi(e)[Rn(n[1],t)-1];return o||bo(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=pi(e)[Rn(n[1],t)-1],i=o?.episode.scenes[Rn(n[2],t)-1];return(!o||!i)&&bo(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=pi(e)[Rn(n[1],t)-1],i=o?.episode.scenes[Rn(n[2],t)-1],r=i?.actions[Rn(n[3],t)-1];return(!o||!i||!r)&&bo(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=Wn(e)[Rn(n[1],t)-1];return o||bo(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=Wn(e)[Rn(n[1],t)-1],i=o?.scene.actions[Rn(n[2],t)-1];return(!o||!i)&&bo(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=li(e)[Rn(n[1],t)-1];return o||bo(t,"Global action ordinal is outside the current script."),{kind:"action",id:o.action.action_id}}return bo(t,"Ordinal anchor syntax is not supported.")}function or(e,t){throw new S(e,{exitCode:B,errorCode:"V4_SELECTOR_INVALID",data:{expected:["typed v4 ID or same-kind inclusive range; comma joins regions"],actual:[t]}})}function Yf(e,t){return e.kind==="episode"||e.kind==="scene"||e.kind==="action"?e.kind:or("Asset and state addresses are not narrative range anchors.",t)}function qf(e){return e.kind==="state"?`${e.assetId}/${e.stateId}`:e.id}function Wf(e,t,n){return t.startsWith("@")?(n||or("Ordinal anchors are query-only.",t),xa(e,t)):ns(t)}function U_(e,t,n,o){let i=e.indexOf(t),r=e.indexOf(n);(i<0||r<0)&&or("Range endpoint does not exist in the current script.",o);let s=Math.min(i,r),a=Math.max(i,r);return e.slice(s,a+1)}function Ea(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=pi(e),r=Wn(e),s=li(e),a=i.map(g=>g.episode.episode_id),c=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(E=>f.add(E.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||or("Selector contains an empty region.",o);let y=w.split("..");y.length>2&&or("Selector region has too many range delimiters.",w);let E=Wf(e,y[0].trim(),n.allowOrdinals),_=Wf(e,(y[1]??y[0]).trim(),n.allowOrdinals),x=Yf(E,w);Yf(_,w)!==x&&or("Range endpoints must have the same kind.",w);let A=qf(E),b=qf(_),v=U_(x==="episode"?a:x==="scene"?c:d,A,b,w);x==="episode"?v.forEach(u):x==="scene"?v.forEach(h):v.forEach(m)}return{isEmpty:!1,isWholeScript:!1,matchesEpisode:g=>p.has(g),matchesScene:g=>l.has(g),matchesAction:g=>f.has(g)}}function vo(e,t){throw new S(e,{exitCode:B,errorCode:"AUTHORING_SELECTOR_INVALID",data:{actual:t}})}function P_(e){return e.replace(/\\/g,"\\\\").replace(/\|/g,"\\|").replace(/\]/g,"\\]").replace(/\n/g,"\\n")}function C_(e){return e.replace(/\\/g,"\\\\").replace(/\n/g,"\\n")}function de(e,t,n=""){let o=[e,...t].map(P_).join("|"),i=C_(n);return`[${o}]${i?` ${i}`:""}`}function Bd(e){if(Array.isArray(e))return e.map(Bd);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=Bd(e[n]);return t}return e}function Oo(e){return e===void 0?[]:[de("extensions",[]),...Object.keys(e).sort().map(t=>de("extend",[t],JSON.stringify(Bd(e[t]))))]}function T_(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 Zf(e){let t=Oo(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 n=[e.action_id,T_(e.speaker)];"parenthetical"in e&&n.push(e.parenthetical??""),t.push(de(e.type==="dialogue"?"dlg":"think",n,e.content))}else t.push(de(e.type==="action"?"act":"trans",[e.action_id],e.content));return t}function Jd(e,t){let n=[...Oo(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(de("environment",o))}n.push(e.location===null?de("location",[]):de("location",[e.location.location_id,...e.location.state_ids]));for(let o of e.actors)n.push(de("cast",[o.actor_id,...o.state_ids]));for(let o of e.props)n.push(de("prop",[o.prop_id,...o.state_ids]));return n.push("","<body>"),e.actions.forEach(o=>n.push(...Zf(o))),n.push("</body>","","</scene>"),n}function zd(e){let t=[...Oo(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.scenes.forEach((n,o)=>{(o>0||e.title!==void 0||e.synopsis!==void 0)&&t.push(""),t.push(...Jd(n,`id=${n.scene_id}`))}),t.push("</episode>"),t}function Dd(e,t){return[...Oo(t.extend),de("state",[e,t.state_id,t.state_name],t.description)]}function V_(e){let t=["<create>"];for(let n of e.actors){t.push(...Oo(n.extend)),n.aliases!==void 0&&(t.push(de("aliases",[])),n.aliases.forEach(i=>t.push(de("alias",[],i))));let o=[n.actor_id,n.actor_name,n.importance];n.role_type!==void 0&&o.push(n.role_type),t.push(de("actor",o,n.description)),n.states.forEach(i=>t.push(...Dd(n.actor_id,i)))}for(let n of e.locations)t.push(...Oo(n.extend)),n.aliases!==void 0&&(t.push(de("aliases",[])),n.aliases.forEach(o=>t.push(de("alias",[],o)))),t.push(de("location",[n.location_id,n.location_name,n.importance],n.description)),n.states.forEach(o=>t.push(...Dd(n.location_id,o)));for(let n of e.props)t.push(...Oo(n.extend)),n.aliases!==void 0&&(t.push(de("aliases",[])),n.aliases.forEach(o=>t.push(de("alias",[],o)))),t.push(de("prop",[n.prop_id,n.prop_name,n.importance],n.description)),n.states.forEach(o=>t.push(...Dd(n.prop_id,o)));return t.push("</create>"),t}function $_(e){let t=[...Oo(e.extend),"<script>"];return t.push(de("title",[],e.title),de("worldview",[],e.worldview)),e.worldview_raw!==void 0&&t.push(de("worldview-raw",[],e.worldview_raw)),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.main_characters!==void 0&&(t.push(de("main-characters",[])),e.main_characters.forEach(n=>t.push(de("main-character",[n.name,n.role])))),e.episodes.forEach(n=>t.push("",...zd(n))),t.push("</script>"),t}function D_(e){return e.trim()||vo("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]?vo("Selector region is invalid.",[t]):{left:n[0],right:n[1]??n[0]}})}function Gd(e,t,n,o,i){let r=-1;return D_(i).map(s=>{let a=f=>{if(!f.startsWith("@"))return f;let u=xa(e,f);return u.kind!==t?vo("Selector endpoint kind does not match the export kind.",[f,t]):u.id},c=o.indexOf(a(s.left)),d=o.indexOf(a(s.right));(c<0||d<0)&&vo("Selector endpoint was not found.",[s.left,s.right]);let p=Math.min(c,d),l=Math.max(c,d);return p<=r&&vo("Selector regions must follow current document order without overlap.",[`${s.left}..${s.right}`]),r=l,n.slice(p,l+1)})}function Xf(e,t,n){let o=["<authoring version=1>",""],i=0;if(t==="script")o.push(...V_(e),"",...$_(e)),i=1;else if(t==="episodes"){let r=Ea(e,n,{allowOrdinals:!0}),s=e.episodes.filter(a=>r.matchesEpisode(a.episode_id));s.forEach((a,c)=>{c>0&&o.push(""),o.push(...zd(a))}),i=s.length}else if(t==="episode-spans"){let r=Gd(e,"episode",e.episodes,e.episodes.map(s=>s.episode_id),n);for(let[s,a]of r.entries())s>0&&o.push(""),o.push(`<episode-span range=${a[0].episode_id}..${a.at(-1).episode_id}>`),a.forEach(c=>o.push(...zd(c))),o.push("</episode-span>"),i++}else if(t==="scenes"){let r=Ea(e,n,{allowOrdinals:!0}),s=Wn(e).filter(a=>r.matchesScene(a.scene.scene_id));s.forEach((a,c)=>{c>0&&o.push(""),o.push(...Jd(a.scene,`id=${a.scene.scene_id} parent=${a.episode.episode_id}`))}),i=s.length}else if(t==="scene-spans"){let r=Wn(e),s=Gd(e,"scene",r,r.map(a=>a.scene.scene_id),n);for(let[a,c]of s.entries()){let d=c[0].episode.episode_id;c.every(p=>p.episode.episode_id===d)||vo("A scene span must remain inside one episode.",[c[0].scene.scene_id,c.at(-1).scene.scene_id]),a>0&&o.push(""),o.push(`<scene-span parent=${d} range=${c[0].scene.scene_id}..${c.at(-1).scene.scene_id}>`),c.forEach(p=>o.push(...Jd(p.scene,`id=${p.scene.scene_id}`))),o.push("</scene-span>"),i++}}else{let r=li(e),s=Gd(e,"action",r,r.map(a=>a.action.action_id),n);for(let[a,c]of s.entries()){let d=c[0].scene.scene_id;c.every(p=>p.scene.scene_id===d)||vo("An action span must remain inside one scene.",[c[0].action.action_id,c.at(-1).action.action_id]),a>0&&o.push(""),o.push(`<action-span parent=${d} range=${c[0].action.action_id}..${c.at(-1).action.action_id}>`,"<body>"),c.forEach(p=>o.push(...Zf(p.action))),o.push("</body>","</action-span>"),i++}}return i===0&&vo("Selector did not match any authoring targets.",[n||"<empty>"]),o.push("","</authoring>"),{content:`${o.join(`
|
|
127
127
|
`)}
|
|
128
|
-
`,targetCount:i}}function ue(e,t,n,o,i=k){throw new S(t,{exitCode:i,errorCode:e,hint:o,data:{actual:n}})}function T_(e){let t=he(e),n;try{n=JSON.parse(Wf.readFileSync(t,"utf-8"))}catch(o){ue("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 ga(n)}function ns(e){return e||ue("AUTHORING_SELECTOR_REQUIRED","This export kind requires --in.",["<missing>"],"Pass one or more comma-separated point or from..through regions.",B),e.split(",").map(t=>{let n=t.trim();n||ue("AUTHORING_SELECTOR_INVALID","Selector contains an empty region.",[e],"Remove empty comma-separated regions.",B);let o=n.indexOf("..");if(o<0)return{from:n,through:n};n.indexOf("..",o+2)>=0&&ue("AUTHORING_SELECTOR_INVALID","Selector region has more than one range delimiter.",[n],"Use point or from..through.",B);let i=n.slice(0,o),r=n.slice(o+2);return(!i||!r)&&ue("AUTHORING_SELECTOR_INVALID","Selector range endpoint is empty.",[n],"Provide both endpoints.",B),{from:i,through:r}})}function xa(e,t,n){if(t.from==="*"&&t.through==="*")return e.length===0&&ue("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)&&ue("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)&&ue("AUTHORING_SELECTOR_NOT_FOUND",`${n} selector endpoint was not found.`,[t.from,t.through],"Use IDs from the current local script."),o>i&&ue("AUTHORING_SELECTOR_REVERSED",`${n} selector is reversed in current document order.`,[t.from,t.through],"Put the earlier document endpoint first."),[o,i]}function em(e,t){let n=new Set;for(let o of e){let i=t(o);n.has(i)&&ue("AUTHORING_SELECTOR_OVERLAP","Selector regions overlap or repeat a target.",[i],"Use non-overlapping regions."),n.add(i)}return e}function os(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 a=0;a<r&&(s=(i[a]??0)-(o[a]??0),s===0);a+=1);s<=0&&ue("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 V_(e,t){let n=[],o=e.episodes.map(r=>r.episode_id);for(let r of ns(t)){let[s,a]=xa(o,r,"episode");n.push(...e.episodes.slice(s,a+1))}em(n,r=>r.episode_id),os(n.map(r=>[o.indexOf(r.episode_id)]),"Episode");let i=n.map(r=>({kind:"episode",value:structuredClone(r),source:nn}));return tr("episode",i)}function $_(e,t){let n=e.episodes.map(s=>s.episode_id),o=[],i=new Set,r=[];for(let s of ns(t)){let[a,c]=xa(n,s,"episode");for(let d=a;d<=c;d+=1)i.has(d)&&ue("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[a],through:n[c],episodes:structuredClone(e.episodes.slice(a,c+1)),source:nn}),r.push([a])}return os(r,"Episode span"),tr("episode-span",o)}function D_(e){return e.episodes.flatMap(t=>t.scenes.map(n=>({episodeId:t.episode_id,scene:n})))}function Bd(e){return`${e.episodeId}/${e.scene.scene_id}`}function G_(e,t){let n=D_(e),o=n.map(Bd),i=[];for(let s of ns(t)){let[a,c]=xa(o,s,"scene");i.push(...n.slice(a,c+1))}em(i,Bd),os(i.map(s=>[o.indexOf(Bd(s))]),"Scene");let r=i.map(s=>({kind:"scene",parent:s.episodeId,value:structuredClone(s.scene),source:nn}));return tr("scene",r)}function Jd(e){let t=/^([^/#]+)\/([^/#]+)$/.exec(e);return t||ue("AUTHORING_SELECTOR_INVALID","Scene selector endpoint must be ep/scn.",[e],"Use ep_ID/scn_ID."),{episodeId:t[1],sceneId:t[2]}}function B_(e,t){let n=[],o=new Set,i=[];for(let r of ns(t)){(r.from==="*"||r.through==="*")&&ue("AUTHORING_SELECTOR_INVALID","A scene span wildcard has no single parent.",["*"],"Use one explicit region per episode.");let s=Jd(r.from),a=Jd(r.through);s.episodeId!==a.episodeId&&ue("AUTHORING_SELECTOR_CROSS_PARENT","A scene span must remain inside one episode.",[r.from,r.through],"Split it into one region per episode.");let c=e.episodes.filter(u=>u.episode_id===s.episodeId);c.length===0&&ue("AUTHORING_SELECTOR_NOT_FOUND","Scene span parent episode was not found.",[s.episodeId],"Use an existing episode ID."),c.length>1&&ue("AUTHORING_SELECTOR_AMBIGUOUS","Scene span parent episode is not unique.",[s.episodeId],"Repair duplicate stable IDs before exporting.");let d=c[0],p=d.scenes.map(u=>u.scene_id),[l,f]=xa(p,{from:s.sceneId,through:a.sceneId},"scene");for(let u=l;u<=f;u+=1){let h=`${d.episode_id}/${p[u]}`;o.has(h)&&ue("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:nn}),i.push([e.episodes.indexOf(d),l])}return os(i,"Scene span"),tr("scene-span",n)}function Zf(e){let t=/^([^/#]+\/[^/#]+)#(\d+)$/.exec(e);t||ue("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)||ue("AUTHORING_SELECTOR_INVALID","Action index is outside the safe integer range.",[e],"Use a zero-based safe integer index."),{parent:t[1],index:n}}function J_(e,t){let n=[],o=new Set,i=[];for(let r of ns(t)){(r.from==="*"||r.through==="*")&&ue("AUTHORING_SELECTOR_INVALID","An action span wildcard has no single parent.",["*"],"Use one explicit region per scene.");let s=Zf(r.from),a=Zf(r.through);s.parent!==a.parent&&ue("AUTHORING_SELECTOR_CROSS_PARENT","An action span must remain inside one scene.",[r.from,r.through],"Split it into one region per scene.");let c=Jd(s.parent),d=e.episodes.filter(u=>u.episode_id===c.episodeId);d.length===0&&ue("AUTHORING_SELECTOR_NOT_FOUND","Action span parent episode was not found.",[c.episodeId],"Use an existing episode ID."),d.length>1&&ue("AUTHORING_SELECTOR_AMBIGUOUS","Action span parent episode is not unique.",[c.episodeId],"Repair duplicate stable IDs before exporting.");let p=d[0],l=p.scenes.filter(u=>u.scene_id===c.sceneId);l.length===0&&ue("AUTHORING_SELECTOR_NOT_FOUND","Action span parent scene was not found.",[s.parent],"Use an existing scene address."),l.length>1&&ue("AUTHORING_SELECTOR_AMBIGUOUS","Action span parent scene is not unique.",[s.parent],"Repair duplicate stable IDs before exporting.");let f=l[0];s.index>a.index&&ue("AUTHORING_SELECTOR_REVERSED","Action span is reversed.",[r.from,r.through],"Put the lower current action index first."),a.index>=f.actions.length&&ue("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<=a.index;u+=1){let h=`${s.parent}#${u}`;o.has(h)&&ue("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:a.index,actions:structuredClone(f.actions.slice(s.index,a.index+1)),source:nn}),i.push([e.episodes.indexOf(p),p.scenes.indexOf(f),s.index])}return os(i,"Action span"),tr("action-span",n)}function tm(e,t){let n=O(t.output).trim();n||ue("AUTHORING_OUTPUT_REQUIRED","Export requires --output.",["<missing>"],"Pass a destination .scriptctl file.",B);let o=T_(t),i=O(t.in).trim(),r=Xf.resolve(n);if(o.version===4){let p=qf(vn(o),e,i);return la(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}},V]}let s=Gt(o),a;e==="script"?a=zf(s):e==="episodes"?a=V_(s,i):e==="episode-spans"?a=$_(s,i):e==="scenes"?a=G_(s,i):e==="scene-spans"?a=B_(s,i):a=J_(s,i);let c=jf(a);return la(r,c),[{text:`Exported ${a.targets.length} ${e} target(s) to ${r}`,data:{op:`export.${e}`,output:r,target_kind:a.targetKind,target_count:a.targets.length,bytes:Buffer.byteLength(c),script_version:3}},V]}import*as ap from"node:crypto";import*as as from"node:fs";import*as Om from"node:path";function F(e,t,n,o,i=k){throw new S(t,{exitCode:i,errorCode:e,hint:o[0],data:{actual:n}})}function fe(e){return`line ${e.line}, column ${e.column}`}function Ea(e){if(Array.isArray(e))return e.map(Ea);if(e!==null&&typeof e=="object"){let t={};for(let[n,o]of Object.entries(e).sort(([i],[r])=>i.localeCompare(r)))t[n]=Ea(o);return t}return e}function Ro(e,t){return JSON.stringify(Ea(e))===JSON.stringify(Ea(t))}function is(e,t){return"actor_id"in t?t.actor_id:"location_id"in t?t.location_id:t.prop_id}function z_(e,t){return"actor_name"in t?t.actor_name:"location_name"in t?t.location_name:t.prop_name}function K_(e,t){return t==="actor"?e.actors:t==="location"?e.locations:e.props}function j_(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 cm(e,t,n){return K_(e,t).find(o=>is(t,o)===n)}function H_(e,t){for(let n of["actor","location","prop"]){let o=cm(e,n,t);if(o!==void 0)return{kind:n,value:o}}}function Q_(e){let t=[],n=[],o={actor:0,location:1,prop:2},i=-1,r,s=!1,a=new Set;for(let c of e){if(c.declarationKind!=="state"){s&&F("AUTHORING_DECLARATION_ORDER","Asset declarations must precede standalone state declarations.",[fe(c.source)],["Move standalone states to the end of <create>."]);let p=c.declarationKind;o[p]<i&&F("AUTHORING_DECLARATION_ORDER","Asset declaration groups are out of canonical order.",[fe(c.source),p],["Order asset declarations as actor, location, then prop."]),i=o[p];let l=structuredClone(c.value);l.states=[];let f={kind:p,value:l,source:c.source},u=`${p}:${is(p,l)}`;a.has(u)&&F("AUTHORING_DECLARATION_DUPLICATE","Asset declaration is duplicated.",[fe(c.source),u],["Keep one declaration per asset."]),a.add(u),t.push(f),r=f;continue}let d=`${c.ownerKind}:${c.ownerId}`;if(r!==void 0&&r.kind===c.ownerKind&&is(r.kind,r.value)===c.ownerId){r.value.states.push(structuredClone(c.value));continue}s=!0,r=void 0,n.push({kind:c.ownerKind,ownerId:c.ownerId,value:structuredClone(c.value),source:c.source})}for(let c of t){let d=is(c.kind,c.value);(c.value.states.length===0||c.value.states[0].state_id!=="default")&&F("AUTHORING_DEFAULT_STATE_REQUIRED","Every declared asset must be immediately followed by its states, beginning with default.",[fe(c.source),`${c.kind}:${d}`],[`Add [state|${c.kind}:${d}|default|...] directly after the asset declaration.`]),c.value.states.filter(l=>l.state_id==="default").length!==1&&F("AUTHORING_DEFAULT_STATE_DUPLICATE","Every declared asset must contain exactly one default state.",[fe(c.source),`${c.kind}:${d}`],["Keep exactly one default state."]);let p=c.value.aliases??[];(new Set(p).size!==p.length||p.includes(z_(c.kind,c.value)))&&F("AUTHORING_ALIAS_INVALID","Asset aliases must be unique and must differ from the canonical name.",[fe(c.source),`${c.kind}:${d}`],["Remove duplicate aliases and the canonical name from aliases."])}return{assets:t,states:n}}function F_(){return{createdAssets:[],existingAssets:[],createdStates:[],existingStates:[]}}function dm(e,t){let n=Q_(t),o=F_();for(let i of n.assets){let r=is(i.kind,i.value),s=`${i.kind}:${r}`,a=H_(e,r);if(a!==void 0){if(a.kind===i.kind&&Ro(a.value,i.value)){o.existingAssets.push(s),o.existingStates.push(...i.value.states.map(c=>`${s}/${c.state_id}`));continue}F("AUTHORING_ASSET_CONFLICT","Create-only asset declaration conflicts with an existing asset.",[fe(i.source),`${i.kind}:${r}`],["Use the existing identical definition or change it with an explicit mutation verb."])}j_(e,i),o.createdAssets.push(s),o.createdStates.push(...i.value.states.map(c=>`${s}/${c.state_id}`))}for(let i of n.states){let r=cm(e,i.kind,i.ownerId);r===void 0&&F("AUTHORING_STATE_OWNER_NOT_FOUND","Standalone state owner does not exist.",[fe(i.source),`${i.kind}:${i.ownerId}`],["Declare the asset before its states or use an existing asset ID."]);let s=r.states.find(c=>c.state_id===i.value.state_id);s!==void 0&&!Ro(s,i.value)&&F("AUTHORING_STATE_CONFLICT","Create-only state declaration conflicts with an existing state on the same asset.",[fe(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 a=`${i.kind}:${i.ownerId}/${i.value.state_id}`;s===void 0?(r.states.push(i.value),o.createdStates.push(a)):o.existingStates.push(a)}return o}function nm(e){return{episodes:0,scenes:e===void 0?0:1,actions:e?.actions.length??0}}function om(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 _a(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 im(e){return{episodes:0,scenes:e.length,actions:e.reduce((t,n)=>t+n.actions.length,0)}}function rs(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 zd(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&&F("AUTHORING_SCENE_REF_UNMATERIALIZED","Every scene asset reference in an authored block must bind a state.",[fe(t),...n],["Add the concrete state ID to every location, cast, and prop record."])}function Kd(e,t){for(let n of e.scenes)zd(n,t)}function li(e,t){return e.episodes.findIndex(n=>n.episode_id===t)}function Sa(e,t){return e.scenes.findIndex(n=>n.scene_id===t)}function pm(e,t,n){let o=li(e,t);o<0&&F("AUTHORING_EPISODE_NOT_FOUND","Episode target does not exist.",[t],["Inspect episodes and use an existing parent."]);let i=Sa(e.episodes[o],n);return i<0&&F("AUTHORING_SCENE_NOT_FOUND","Scene target does not exist.",[`${t}/${n}`],["Inspect scenes and use an existing target."]),[o,i]}function Y_(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 ss(e,t){for(let n=1;n<e.length;n+=1)Y_(e[n-1].coord,e[n].coord)>=0&&F("AUTHORING_TARGET_ORDER",t,[fe(e[n].source)],["List replace targets in current document order without duplicates."],B)}function q_(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>{let a=li(e,s.value.episode_id);return a<0&&F("AUTHORING_EPISODE_NOT_FOUND","Episode replace target does not exist.",[fe(s.source),s.value.episode_id],["Use --create for a new episode or choose an existing ID."]),{coord:[a],source:s.source}});ss(r,"Episode replace targets are not in document order.")}for(let r of n){Kd(r.value,r.source);let s=li(e,r.value.episode_id),a=s<0?void 0:e.episodes[s];o==="create"?a!==void 0?Ro(a,r.value)||F("AUTHORING_CREATE_CONFLICT","Episode create target already exists with different content.",[fe(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:om(a),after:om(r.value),...rs(a?.scenes.map(c=>c.scene_id)??[],r.value.scenes.map(c=>c.scene_id)),untouchedSiblings:Math.max(0,e.episodes.length-(a===void 0?0:1))})}return i}function Z_(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>({coord:pm(e,s.parent,s.value.scene_id),source:s.source}));ss(r,"Scene replace targets are not in document order.")}for(let r of n){zd(r.value,r.source);let s=li(e,r.parent);s<0&&F("AUTHORING_EPISODE_NOT_FOUND","Scene parent episode does not exist.",[fe(r.source),r.parent],["Use an existing episode parent."]);let a=e.episodes[s],c=t.episodes[s],d=Sa(a,r.value.scene_id),p=d<0?void 0:a.scenes[d];o==="create"?p!==void 0?Ro(p,r.value)||F("AUTHORING_CREATE_CONFLICT","Scene create target already exists with different content.",[fe(r.source),`${r.parent}/${r.value.scene_id}`],["Use --replace or make the create block identical for a no-op retry."]):c.scenes.push(structuredClone(r.value)):(d<0&&F("AUTHORING_SCENE_NOT_FOUND","Scene replace target does not exist.",[fe(r.source),`${r.parent}/${r.value.scene_id}`],["Use --create for a new scene or choose an existing scene."]),c.scenes[d]=structuredClone(r.value)),i.push({kind:"scene",address:`${r.parent}/${r.value.scene_id}`,before:nm(p),after:nm(r.value),...rs(p===void 0?[]:[p.scene_id],[r.value.scene_id]),untouchedSiblings:Math.max(0,a.scenes.length-(p===void 0?0:1))})}return i}function W_(e,t,n){let o=n.map(r=>{let s=li(e,r.from),a=li(e,r.through);(s<0||a<0)&&F("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Episode-span endpoint does not exist.",[fe(r.source),`${r.from}..${r.through}`],["Use existing episode IDs as span endpoints."]),s>a&&F("AUTHORING_SPAN_REVERSED","Episode-span endpoints are reversed in current document order.",[fe(r.source),`${r.from}..${r.through}`],["Swap from and through."]),r.episodes.length===0&&F("AUTHORING_EMPTY_SPAN","Episode-span replacement cannot be empty.",[fe(r.source)],["Include at least one complete episode."]);for(let c of r.episodes)Kd(c,r.source);return{target:r,from:s,through:a}});ss(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&&F("AUTHORING_SPAN_OVERLAP","Episode spans overlap.",[fe(o[r].target.source)],["Use disjoint episode spans."]);let i=o.map(({target:r,from:s,through:a})=>{let c=e.episodes.slice(s,a+1);return{kind:"episode-span",address:`${r.from}..${r.through}`,before:_a(c),after:_a(r.episodes),...rs(c.map(d=>d.episode_id),r.episodes.map(d=>d.episode_id)),untouchedSiblings:e.episodes.length-c.length}});for(let{target:r,from:s,through:a}of[...o].reverse())t.episodes.splice(s,a-s+1,...structuredClone(r.episodes));return i}function X_(e,t,n){let o=n.map(s=>{let a=li(e,s.parent);a<0&&F("AUTHORING_EPISODE_NOT_FOUND","Scene-span parent does not exist.",[fe(s.source),s.parent],["Use an existing parent episode."]);let c=e.episodes[a],d=Sa(c,s.from),p=Sa(c,s.through);(d<0||p<0)&&F("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Scene-span endpoint does not exist in its parent.",[fe(s.source),`${s.parent}:${s.from}..${s.through}`],["Use scene IDs from the same existing episode."]),d>p&&F("AUTHORING_SPAN_REVERSED","Scene-span endpoints are reversed in current document order.",[fe(s.source),`${s.from}..${s.through}`],["Swap from and through."]),s.scenes.length===0&&F("AUTHORING_EMPTY_SPAN","Scene-span replacement cannot be empty.",[fe(s.source)],["Include at least one complete scene."]);for(let l of s.scenes)zd(l,s.source);return{target:s,epIndex:a,from:d,through:p}});ss(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 a=o[s-1],c=o[s];c.epIndex===a.epIndex&&c.from<=a.through&&F("AUTHORING_SPAN_OVERLAP","Scene spans overlap.",[fe(c.target.source)],["Use disjoint scene spans."])}let i=o.map(({target:s,epIndex:a,from:c,through:d})=>{let p=e.episodes[a].scenes.slice(c,d+1);return{kind:"scene-span",address:`${s.parent}/${s.from}..${s.parent}/${s.through}`,before:im(p),after:im(s.scenes),...rs(p.map(l=>l.scene_id),s.scenes.map(l=>l.scene_id)),untouchedSiblings:e.episodes[a].scenes.length-p.length}}),r=new Map;for(let s of o)r.set(s.epIndex,[...r.get(s.epIndex)??[],s]);for(let[s,a]of r)for(let{target:c,from:d,through:p}of[...a].reverse())t.episodes[s].scenes.splice(d,p-d+1,...structuredClone(c.scenes));return i}function e5(e,t,n){let o=n.map(s=>{let a=s.parent.indexOf("/");(a<1||a===s.parent.length-1)&&F("AUTHORING_SCENE_ADDRESS_INVALID","Action-span parent is not a complete scene address.",[fe(s.source),s.parent],["Use parent=ep_ID/scn_ID."]);let c=s.parent.slice(0,a),d=s.parent.slice(a+1),[p,l]=pm(e,c,d),f=e.episodes[p].scenes[l];return s.from>s.through&&F("AUTHORING_SPAN_REVERSED","Action-span endpoints are reversed.",[fe(s.source),`${s.from}..${s.through}`],["Swap from and through."]),s.through>=f.actions.length&&F("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Action-span endpoint is outside the current scene body.",[fe(s.source),`${s.from}..${s.through}`,`actions=${f.actions.length}`],["Use zero-based endpoints within the current body."]),s.actions.length===0&&F("AUTHORING_EMPTY_SPAN","Action-span replacement cannot be empty.",[fe(s.source)],["Include at least one action."]),{target:s,epIndex:p,scIndex:l,scene:f,from:s.from,through:s.through}});ss(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 a=o[s-1],c=o[s];c.epIndex===a.epIndex&&c.scIndex===a.scIndex&&c.from<=a.through&&F("AUTHORING_SPAN_OVERLAP","Action spans overlap.",[fe(c.target.source)],["Use disjoint action spans."])}let i=o.map(({target:s,scene:a,from:c,through:d})=>({kind:"action-span",address:`${s.parent}#${c}..${s.parent}#${d}`,before:{episodes:0,scenes:0,actions:d-c+1},after:{episodes:0,scenes:0,actions:s.actions.length},retainedIds:[],createdIds:[],removedIds:[],untouchedSiblings:a.actions.length-(d-c+1)})),r=new Map;for(let s of o){let a=`${s.epIndex}/${s.scIndex}`;r.set(a,[...r.get(a)??[],s])}for(let s of r.values())for(let{target:a,epIndex:c,scIndex:d,from:p,through:l}of[...s].reverse())t.episodes[c].scenes[d].actions.splice(p,l-p+1,...structuredClone(a.actions));return i}function lm(e){let t=new Set,n=new Set;for(let o of e.episodes){t.has(o.episode_id)&&F("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)&&F("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 t5(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 a=`${n[0]}.scenes[${r[2]}]`;i=e.replace(a,`$.episodes[${o.episode_id}].scenes[${s.scene_id}]`)}}return i}function rm(e,t){return`${e.code}\0${t5(e.path,t)}\0${e.message}`}function n5(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 o5(e,t,n){let o=[],i=new Map(e?.episodes.map(c=>[c.episode_id,c])??[]),r=new Map;for(let c of e?.episodes??[])for(let d of c.scenes)r.set(d.scene_id,d);let s=new Map(t.episodes.map(c=>[c.episode_id,c])),a=new Map;for(let c of t.episodes)for(let d of c.scenes)a.set(d.scene_id,{episodeId:c.episode_id,scene:d});for(let c of n.fullEpisodeIds){let d=s.get(c);if(d===void 0||d.scenes.length>0)continue;let p=(i.get(c)?.scenes.length??0)>0;o.push({code:p?"authoring_episode_cleared":"authoring_empty_episode",path:`$.episodes[${c}]`,message:p?`authoring replaced episode ${c} with an empty scene list`:`authored episode ${c} has no scenes`})}for(let c of n.fullSceneIds){let d=a.get(c);if(d===void 0)continue;let p=`$.episodes[${d.episodeId}].scenes[${c}]`;if(d.scene.actions.length===0){let l=(r.get(c)?.actions.length??0)>0;o.push({code:l?"authoring_scene_cleared":"authoring_empty_scene",path:p,message:l?`authoring replaced scene ${c} with an empty body`:`authored scene ${c} 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 c of n.actionSpans)c.actions.forEach((d,p)=>{d.content.trim()===""&&o.push({code:"authoring_empty_action_content",path:`${c.parent}#replacement[${p}]`,message:"authored action-span replacement contains an action with empty content"})});return o}function sm(e,t,n){let o=St(t),i=n5(n),r=()=>({...o,warnings:[...o.warnings,...o5(e,t,i)]});if(o.ok||e!==null&&Ro(e,t))return r();let s=new Set(e===null?[]:St(e).errors.map(c=>rm(c,e))),a=o.errors.filter(c=>{if(!s.has(rm(c,t)))return!0;let d=/^\$\.episodes\[(\d+)]/.exec(c.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(c.path),f=l===null?void 0:p.scenes[Number(l[1])];return f!==void 0&&i.sceneIds.has(f.scene_id)});return a.length>0&&F("AUTHORING_VALIDATION_FAILED","The proposed script has blocking validation errors.",a.map(c=>`${c.path}: ${c.code} ${c.message}`),["Repair the authoring source and rerun the plan."]),r()}function am(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 i5(e){let t=e.targets[0];t?.kind!=="script"&&F("AUTHORING_TARGET_MODE","Script create requires exactly one script target.",[],["Use a single <script> block."],B);for(let i of t.episodes)Kd(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=dm(n,e.declarations);return lm(n),{script:n,declarations:o}}function um(e,t,n){if(t.targetKind==="script"){n!=="create"&&F("AUTHORING_TARGET_MODE","Script targets support create only.",[n],["Use --create."],B);let c=i5(t),d=c.script;e!==null&&!Ro(e,d)&&F("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?c.declarations:{createdAssets:[],existingAssets:[...c.declarations.existingAssets,...c.declarations.createdAssets],createdStates:[],existingStates:[...c.declarations.existingStates,...c.declarations.createdStates]},l=sm(e,d,t.targets);return{script:d,changed:e===null||!Ro(e,d),declarations:p,targets:[{kind:"script",address:"global",before:e===null?{episodes:0,scenes:0,actions:0}:_a(e.episodes),after:_a(d.episodes),...rs(e?.episodes.map(f=>f.episode_id)??[],d.episodes.map(f=>f.episode_id)),untouchedSiblings:0}],retainedOrphanAssets:am(d),validation:l}}e===null&&F("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"&&F("AUTHORING_TARGET_MODE",`${t.targetKind} supports replace only.`,[n],["Use --replace."],B);let o=structuredClone(e),i=structuredClone(e),r=dm(i,t.declarations),s;switch(t.targetKind){case"episode":{let c=t.targets.flatMap(d=>d.kind==="episode"?[d]:[]);c.length!==t.targets.length&&F("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=q_(o,i,c,n);break}case"scene":{let c=t.targets.flatMap(d=>d.kind==="scene"?[d]:[]);c.length!==t.targets.length&&F("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=Z_(o,i,c,n);break}case"episode-span":{let c=t.targets.flatMap(d=>d.kind==="episode-span"?[d]:[]);c.length!==t.targets.length&&F("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=W_(o,i,c);break}case"scene-span":{let c=t.targets.flatMap(d=>d.kind==="scene-span"?[d]:[]);c.length!==t.targets.length&&F("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=X_(o,i,c);break}case"action-span":{let c=t.targets.flatMap(d=>d.kind==="action-span"?[d]:[]);c.length!==t.targets.length&&F("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=e5(o,i,c);break}default:F("AUTHORING_TARGET_MODE","Unsupported authoring target.",[t.targetKind],["Use a supported homogeneous target kind."])}lm(i);let a=sm(e,i,t.targets);return{script:i,changed:!Ro(e,i),declarations:r,targets:s,retainedOrphanAssets:am(i),validation:a}}function D(e,t,n,o){return new S(e,{exitCode:k,errorCode:"AUTHORING_SOURCE_INVALID",hint:o,data:{actual:[`line ${t.line}, column ${t.column}: ${n}`]}})}function jd(e,t,n){let o="";for(let i=0;i<e.length;i+=1){let r=e[i];if(r!=="\\"){o+=r;continue}let s=e[i+1];if(s===void 0)throw D("Trailing escape is invalid.",{line:t.line,column:t.column+i},e,"Escape a supported character or remove the trailing backslash.");if(s==="\\"||s==="n"||n&&(s==="|"||s==="]")){o+=s==="n"?`
|
|
129
|
-
`:s,i+=1;continue}throw D("Unknown escape sequence.",{line:t.line,column:t.column+i},`\\${s}`,n?"Use only \\|, \\], \\\\, or \\n in a header.":"Use only \\\\ or \\n in record content.")}return o}function
|
|
128
|
+
`,targetCount:i}}function ue(e,t,n,o,i=k){throw new S(t,{exitCode:i,errorCode:e,hint:o,data:{actual:n}})}function G_(e){let t=he(e),n;try{n=JSON.parse(tm.readFileSync(t,"utf-8"))}catch(o){ue("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 ya(n)}function os(e){return e||ue("AUTHORING_SELECTOR_REQUIRED","This export kind requires --in.",["<missing>"],"Pass one or more comma-separated point or from..through regions.",B),e.split(",").map(t=>{let n=t.trim();n||ue("AUTHORING_SELECTOR_INVALID","Selector contains an empty region.",[e],"Remove empty comma-separated regions.",B);let o=n.indexOf("..");if(o<0)return{from:n,through:n};n.indexOf("..",o+2)>=0&&ue("AUTHORING_SELECTOR_INVALID","Selector region has more than one range delimiter.",[n],"Use point or from..through.",B);let i=n.slice(0,o),r=n.slice(o+2);return(!i||!r)&&ue("AUTHORING_SELECTOR_INVALID","Selector range endpoint is empty.",[n],"Provide both endpoints.",B),{from:i,through:r}})}function _a(e,t,n){if(t.from==="*"&&t.through==="*")return e.length===0&&ue("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)&&ue("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)&&ue("AUTHORING_SELECTOR_NOT_FOUND",`${n} selector endpoint was not found.`,[t.from,t.through],"Use IDs from the current local script."),o>i&&ue("AUTHORING_SELECTOR_REVERSED",`${n} selector is reversed in current document order.`,[t.from,t.through],"Put the earlier document endpoint first."),[o,i]}function om(e,t){let n=new Set;for(let o of e){let i=t(o);n.has(i)&&ue("AUTHORING_SELECTOR_OVERLAP","Selector regions overlap or repeat a target.",[i],"Use non-overlapping regions."),n.add(i)}return e}function is(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 a=0;a<r&&(s=(i[a]??0)-(o[a]??0),s===0);a+=1);s<=0&&ue("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 B_(e,t){let n=[],o=e.episodes.map(r=>r.episode_id);for(let r of os(t)){let[s,a]=_a(o,r,"episode");n.push(...e.episodes.slice(s,a+1))}om(n,r=>r.episode_id),is(n.map(r=>[o.indexOf(r.episode_id)]),"Episode");let i=n.map(r=>({kind:"episode",value:structuredClone(r),source:nn}));return nr("episode",i)}function J_(e,t){let n=e.episodes.map(s=>s.episode_id),o=[],i=new Set,r=[];for(let s of os(t)){let[a,c]=_a(n,s,"episode");for(let d=a;d<=c;d+=1)i.has(d)&&ue("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[a],through:n[c],episodes:structuredClone(e.episodes.slice(a,c+1)),source:nn}),r.push([a])}return is(r,"Episode span"),nr("episode-span",o)}function z_(e){return e.episodes.flatMap(t=>t.scenes.map(n=>({episodeId:t.episode_id,scene:n})))}function Kd(e){return`${e.episodeId}/${e.scene.scene_id}`}function K_(e,t){let n=z_(e),o=n.map(Kd),i=[];for(let s of os(t)){let[a,c]=_a(o,s,"scene");i.push(...n.slice(a,c+1))}om(i,Kd),is(i.map(s=>[o.indexOf(Kd(s))]),"Scene");let r=i.map(s=>({kind:"scene",parent:s.episodeId,value:structuredClone(s.scene),source:nn}));return nr("scene",r)}function jd(e){let t=/^([^/#]+)\/([^/#]+)$/.exec(e);return t||ue("AUTHORING_SELECTOR_INVALID","Scene selector endpoint must be ep/scn.",[e],"Use ep_ID/scn_ID."),{episodeId:t[1],sceneId:t[2]}}function j_(e,t){let n=[],o=new Set,i=[];for(let r of os(t)){(r.from==="*"||r.through==="*")&&ue("AUTHORING_SELECTOR_INVALID","A scene span wildcard has no single parent.",["*"],"Use one explicit region per episode.");let s=jd(r.from),a=jd(r.through);s.episodeId!==a.episodeId&&ue("AUTHORING_SELECTOR_CROSS_PARENT","A scene span must remain inside one episode.",[r.from,r.through],"Split it into one region per episode.");let c=e.episodes.filter(u=>u.episode_id===s.episodeId);c.length===0&&ue("AUTHORING_SELECTOR_NOT_FOUND","Scene span parent episode was not found.",[s.episodeId],"Use an existing episode ID."),c.length>1&&ue("AUTHORING_SELECTOR_AMBIGUOUS","Scene span parent episode is not unique.",[s.episodeId],"Repair duplicate stable IDs before exporting.");let d=c[0],p=d.scenes.map(u=>u.scene_id),[l,f]=_a(p,{from:s.sceneId,through:a.sceneId},"scene");for(let u=l;u<=f;u+=1){let h=`${d.episode_id}/${p[u]}`;o.has(h)&&ue("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:nn}),i.push([e.episodes.indexOf(d),l])}return is(i,"Scene span"),nr("scene-span",n)}function em(e){let t=/^([^/#]+\/[^/#]+)#(\d+)$/.exec(e);t||ue("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)||ue("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 H_(e,t){let n=[],o=new Set,i=[];for(let r of os(t)){(r.from==="*"||r.through==="*")&&ue("AUTHORING_SELECTOR_INVALID","An action span wildcard has no single parent.",["*"],"Use one explicit region per scene.");let s=em(r.from),a=em(r.through);s.parent!==a.parent&&ue("AUTHORING_SELECTOR_CROSS_PARENT","An action span must remain inside one scene.",[r.from,r.through],"Split it into one region per scene.");let c=jd(s.parent),d=e.episodes.filter(u=>u.episode_id===c.episodeId);d.length===0&&ue("AUTHORING_SELECTOR_NOT_FOUND","Action span parent episode was not found.",[c.episodeId],"Use an existing episode ID."),d.length>1&&ue("AUTHORING_SELECTOR_AMBIGUOUS","Action span parent episode is not unique.",[c.episodeId],"Repair duplicate stable IDs before exporting.");let p=d[0],l=p.scenes.filter(u=>u.scene_id===c.sceneId);l.length===0&&ue("AUTHORING_SELECTOR_NOT_FOUND","Action span parent scene was not found.",[s.parent],"Use an existing scene address."),l.length>1&&ue("AUTHORING_SELECTOR_AMBIGUOUS","Action span parent scene is not unique.",[s.parent],"Repair duplicate stable IDs before exporting.");let f=l[0];s.index>a.index&&ue("AUTHORING_SELECTOR_REVERSED","Action span is reversed.",[r.from,r.through],"Put the lower current action index first."),a.index>=f.actions.length&&ue("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<=a.index;u+=1){let h=`${s.parent}#${u}`;o.has(h)&&ue("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:a.index,actions:structuredClone(f.actions.slice(s.index,a.index+1)),source:nn}),i.push([e.episodes.indexOf(p),p.scenes.indexOf(f),s.index])}return is(i,"Action span"),nr("action-span",n)}function im(e,t){let n=O(t.output).trim();n||ue("AUTHORING_OUTPUT_REQUIRED","Export requires --output.",["<missing>"],"Pass a destination .scriptctl file.",B);let o=G_(t),i=O(t.in).trim(),r=nm.resolve(n);if(o.version===4){let p=Xf(vn(o),e,i);return fa(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}},V]}let s=Gt(o),a;e==="script"?a=Hf(s):e==="episodes"?a=B_(s,i):e==="episode-spans"?a=J_(s,i):e==="scenes"?a=K_(s,i):e==="scene-spans"?a=j_(s,i):a=H_(s,i);let c=Ff(a);return fa(r,c),[{text:`Exported ${a.targets.length} ${e} target(s) to ${r}`,data:{op:`export.${e}`,output:r,target_kind:a.targetKind,target_count:a.targets.length,bytes:Buffer.byteLength(c),script_version:3}},V]}import*as pp from"node:crypto";import*as cs from"node:fs";import*as Nm from"node:path";function F(e,t,n,o,i=k){throw new S(t,{exitCode:i,errorCode:e,hint:o[0],data:{actual:n}})}function fe(e){return`line ${e.line}, column ${e.column}`}function Sa(e){if(Array.isArray(e))return e.map(Sa);if(e!==null&&typeof e=="object"){let t={};for(let[n,o]of Object.entries(e).sort(([i],[r])=>i.localeCompare(r)))t[n]=Sa(o);return t}return e}function Ro(e,t){return JSON.stringify(Sa(e))===JSON.stringify(Sa(t))}function rs(e,t){return"actor_id"in t?t.actor_id:"location_id"in t?t.location_id:t.prop_id}function Q_(e,t){return"actor_name"in t?t.actor_name:"location_name"in t?t.location_name:t.prop_name}function F_(e,t){return t==="actor"?e.actors:t==="location"?e.locations:e.props}function Y_(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 lm(e,t,n){return F_(e,t).find(o=>rs(t,o)===n)}function q_(e,t){for(let n of["actor","location","prop"]){let o=lm(e,n,t);if(o!==void 0)return{kind:n,value:o}}}function W_(e){let t=[],n=[],o={actor:0,location:1,prop:2},i=-1,r,s=!1,a=new Set;for(let c of e){if(c.declarationKind!=="state"){s&&F("AUTHORING_DECLARATION_ORDER","Asset declarations must precede standalone state declarations.",[fe(c.source)],["Move standalone states to the end of <create>."]);let p=c.declarationKind;o[p]<i&&F("AUTHORING_DECLARATION_ORDER","Asset declaration groups are out of canonical order.",[fe(c.source),p],["Order asset declarations as actor, location, then prop."]),i=o[p];let l=structuredClone(c.value);l.states=[];let f={kind:p,value:l,source:c.source},u=`${p}:${rs(p,l)}`;a.has(u)&&F("AUTHORING_DECLARATION_DUPLICATE","Asset declaration is duplicated.",[fe(c.source),u],["Keep one declaration per asset."]),a.add(u),t.push(f),r=f;continue}let d=`${c.ownerKind}:${c.ownerId}`;if(r!==void 0&&r.kind===c.ownerKind&&rs(r.kind,r.value)===c.ownerId){r.value.states.push(structuredClone(c.value));continue}s=!0,r=void 0,n.push({kind:c.ownerKind,ownerId:c.ownerId,value:structuredClone(c.value),source:c.source})}for(let c of t){let d=rs(c.kind,c.value);(c.value.states.length===0||c.value.states[0].state_id!=="default")&&F("AUTHORING_DEFAULT_STATE_REQUIRED","Every declared asset must be immediately followed by its states, beginning with default.",[fe(c.source),`${c.kind}:${d}`],[`Add [state|${c.kind}:${d}|default|...] directly after the asset declaration.`]),c.value.states.filter(l=>l.state_id==="default").length!==1&&F("AUTHORING_DEFAULT_STATE_DUPLICATE","Every declared asset must contain exactly one default state.",[fe(c.source),`${c.kind}:${d}`],["Keep exactly one default state."]);let p=c.value.aliases??[];(new Set(p).size!==p.length||p.includes(Q_(c.kind,c.value)))&&F("AUTHORING_ALIAS_INVALID","Asset aliases must be unique and must differ from the canonical name.",[fe(c.source),`${c.kind}:${d}`],["Remove duplicate aliases and the canonical name from aliases."])}return{assets:t,states:n}}function Z_(){return{createdAssets:[],existingAssets:[],createdStates:[],existingStates:[]}}function um(e,t){let n=W_(t),o=Z_();for(let i of n.assets){let r=rs(i.kind,i.value),s=`${i.kind}:${r}`,a=q_(e,r);if(a!==void 0){if(a.kind===i.kind&&Ro(a.value,i.value)){o.existingAssets.push(s),o.existingStates.push(...i.value.states.map(c=>`${s}/${c.state_id}`));continue}F("AUTHORING_ASSET_CONFLICT","Create-only asset declaration conflicts with an existing asset.",[fe(i.source),`${i.kind}:${r}`],["Use the existing identical definition or change it with an explicit mutation verb."])}Y_(e,i),o.createdAssets.push(s),o.createdStates.push(...i.value.states.map(c=>`${s}/${c.state_id}`))}for(let i of n.states){let r=lm(e,i.kind,i.ownerId);r===void 0&&F("AUTHORING_STATE_OWNER_NOT_FOUND","Standalone state owner does not exist.",[fe(i.source),`${i.kind}:${i.ownerId}`],["Declare the asset before its states or use an existing asset ID."]);let s=r.states.find(c=>c.state_id===i.value.state_id);s!==void 0&&!Ro(s,i.value)&&F("AUTHORING_STATE_CONFLICT","Create-only state declaration conflicts with an existing state on the same asset.",[fe(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 a=`${i.kind}:${i.ownerId}/${i.value.state_id}`;s===void 0?(r.states.push(i.value),o.createdStates.push(a)):o.existingStates.push(a)}return o}function rm(e){return{episodes:0,scenes:e===void 0?0:1,actions:e?.actions.length??0}}function sm(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 Ia(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 am(e){return{episodes:0,scenes:e.length,actions:e.reduce((t,n)=>t+n.actions.length,0)}}function ss(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 Hd(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&&F("AUTHORING_SCENE_REF_UNMATERIALIZED","Every scene asset reference in an authored block must bind a state.",[fe(t),...n],["Add the concrete state ID to every location, cast, and prop record."])}function Qd(e,t){for(let n of e.scenes)Hd(n,t)}function ui(e,t){return e.episodes.findIndex(n=>n.episode_id===t)}function Aa(e,t){return e.scenes.findIndex(n=>n.scene_id===t)}function fm(e,t,n){let o=ui(e,t);o<0&&F("AUTHORING_EPISODE_NOT_FOUND","Episode target does not exist.",[t],["Inspect episodes and use an existing parent."]);let i=Aa(e.episodes[o],n);return i<0&&F("AUTHORING_SCENE_NOT_FOUND","Scene target does not exist.",[`${t}/${n}`],["Inspect scenes and use an existing target."]),[o,i]}function X_(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 as(e,t){for(let n=1;n<e.length;n+=1)X_(e[n-1].coord,e[n].coord)>=0&&F("AUTHORING_TARGET_ORDER",t,[fe(e[n].source)],["List replace targets in current document order without duplicates."],B)}function e5(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>{let a=ui(e,s.value.episode_id);return a<0&&F("AUTHORING_EPISODE_NOT_FOUND","Episode replace target does not exist.",[fe(s.source),s.value.episode_id],["Use --create for a new episode or choose an existing ID."]),{coord:[a],source:s.source}});as(r,"Episode replace targets are not in document order.")}for(let r of n){Qd(r.value,r.source);let s=ui(e,r.value.episode_id),a=s<0?void 0:e.episodes[s];o==="create"?a!==void 0?Ro(a,r.value)||F("AUTHORING_CREATE_CONFLICT","Episode create target already exists with different content.",[fe(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:sm(a),after:sm(r.value),...ss(a?.scenes.map(c=>c.scene_id)??[],r.value.scenes.map(c=>c.scene_id)),untouchedSiblings:Math.max(0,e.episodes.length-(a===void 0?0:1))})}return i}function t5(e,t,n,o){let i=[];if(o==="replace"){let r=n.map(s=>({coord:fm(e,s.parent,s.value.scene_id),source:s.source}));as(r,"Scene replace targets are not in document order.")}for(let r of n){Hd(r.value,r.source);let s=ui(e,r.parent);s<0&&F("AUTHORING_EPISODE_NOT_FOUND","Scene parent episode does not exist.",[fe(r.source),r.parent],["Use an existing episode parent."]);let a=e.episodes[s],c=t.episodes[s],d=Aa(a,r.value.scene_id),p=d<0?void 0:a.scenes[d];o==="create"?p!==void 0?Ro(p,r.value)||F("AUTHORING_CREATE_CONFLICT","Scene create target already exists with different content.",[fe(r.source),`${r.parent}/${r.value.scene_id}`],["Use --replace or make the create block identical for a no-op retry."]):c.scenes.push(structuredClone(r.value)):(d<0&&F("AUTHORING_SCENE_NOT_FOUND","Scene replace target does not exist.",[fe(r.source),`${r.parent}/${r.value.scene_id}`],["Use --create for a new scene or choose an existing scene."]),c.scenes[d]=structuredClone(r.value)),i.push({kind:"scene",address:`${r.parent}/${r.value.scene_id}`,before:rm(p),after:rm(r.value),...ss(p===void 0?[]:[p.scene_id],[r.value.scene_id]),untouchedSiblings:Math.max(0,a.scenes.length-(p===void 0?0:1))})}return i}function n5(e,t,n){let o=n.map(r=>{let s=ui(e,r.from),a=ui(e,r.through);(s<0||a<0)&&F("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Episode-span endpoint does not exist.",[fe(r.source),`${r.from}..${r.through}`],["Use existing episode IDs as span endpoints."]),s>a&&F("AUTHORING_SPAN_REVERSED","Episode-span endpoints are reversed in current document order.",[fe(r.source),`${r.from}..${r.through}`],["Swap from and through."]),r.episodes.length===0&&F("AUTHORING_EMPTY_SPAN","Episode-span replacement cannot be empty.",[fe(r.source)],["Include at least one complete episode."]);for(let c of r.episodes)Qd(c,r.source);return{target:r,from:s,through:a}});as(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&&F("AUTHORING_SPAN_OVERLAP","Episode spans overlap.",[fe(o[r].target.source)],["Use disjoint episode spans."]);let i=o.map(({target:r,from:s,through:a})=>{let c=e.episodes.slice(s,a+1);return{kind:"episode-span",address:`${r.from}..${r.through}`,before:Ia(c),after:Ia(r.episodes),...ss(c.map(d=>d.episode_id),r.episodes.map(d=>d.episode_id)),untouchedSiblings:e.episodes.length-c.length}});for(let{target:r,from:s,through:a}of[...o].reverse())t.episodes.splice(s,a-s+1,...structuredClone(r.episodes));return i}function o5(e,t,n){let o=n.map(s=>{let a=ui(e,s.parent);a<0&&F("AUTHORING_EPISODE_NOT_FOUND","Scene-span parent does not exist.",[fe(s.source),s.parent],["Use an existing parent episode."]);let c=e.episodes[a],d=Aa(c,s.from),p=Aa(c,s.through);(d<0||p<0)&&F("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Scene-span endpoint does not exist in its parent.",[fe(s.source),`${s.parent}:${s.from}..${s.through}`],["Use scene IDs from the same existing episode."]),d>p&&F("AUTHORING_SPAN_REVERSED","Scene-span endpoints are reversed in current document order.",[fe(s.source),`${s.from}..${s.through}`],["Swap from and through."]),s.scenes.length===0&&F("AUTHORING_EMPTY_SPAN","Scene-span replacement cannot be empty.",[fe(s.source)],["Include at least one complete scene."]);for(let l of s.scenes)Hd(l,s.source);return{target:s,epIndex:a,from:d,through:p}});as(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 a=o[s-1],c=o[s];c.epIndex===a.epIndex&&c.from<=a.through&&F("AUTHORING_SPAN_OVERLAP","Scene spans overlap.",[fe(c.target.source)],["Use disjoint scene spans."])}let i=o.map(({target:s,epIndex:a,from:c,through:d})=>{let p=e.episodes[a].scenes.slice(c,d+1);return{kind:"scene-span",address:`${s.parent}/${s.from}..${s.parent}/${s.through}`,before:am(p),after:am(s.scenes),...ss(p.map(l=>l.scene_id),s.scenes.map(l=>l.scene_id)),untouchedSiblings:e.episodes[a].scenes.length-p.length}}),r=new Map;for(let s of o)r.set(s.epIndex,[...r.get(s.epIndex)??[],s]);for(let[s,a]of r)for(let{target:c,from:d,through:p}of[...a].reverse())t.episodes[s].scenes.splice(d,p-d+1,...structuredClone(c.scenes));return i}function i5(e,t,n){let o=n.map(s=>{let a=s.parent.indexOf("/");(a<1||a===s.parent.length-1)&&F("AUTHORING_SCENE_ADDRESS_INVALID","Action-span parent is not a complete scene address.",[fe(s.source),s.parent],["Use parent=ep_ID/scn_ID."]);let c=s.parent.slice(0,a),d=s.parent.slice(a+1),[p,l]=fm(e,c,d),f=e.episodes[p].scenes[l];return s.from>s.through&&F("AUTHORING_SPAN_REVERSED","Action-span endpoints are reversed.",[fe(s.source),`${s.from}..${s.through}`],["Swap from and through."]),s.through>=f.actions.length&&F("AUTHORING_SPAN_ENDPOINT_NOT_FOUND","Action-span endpoint is outside the current scene body.",[fe(s.source),`${s.from}..${s.through}`,`actions=${f.actions.length}`],["Use zero-based endpoints within the current body."]),s.actions.length===0&&F("AUTHORING_EMPTY_SPAN","Action-span replacement cannot be empty.",[fe(s.source)],["Include at least one action."]),{target:s,epIndex:p,scIndex:l,scene:f,from:s.from,through:s.through}});as(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 a=o[s-1],c=o[s];c.epIndex===a.epIndex&&c.scIndex===a.scIndex&&c.from<=a.through&&F("AUTHORING_SPAN_OVERLAP","Action spans overlap.",[fe(c.target.source)],["Use disjoint action spans."])}let i=o.map(({target:s,scene:a,from:c,through:d})=>({kind:"action-span",address:`${s.parent}#${c}..${s.parent}#${d}`,before:{episodes:0,scenes:0,actions:d-c+1},after:{episodes:0,scenes:0,actions:s.actions.length},retainedIds:[],createdIds:[],removedIds:[],untouchedSiblings:a.actions.length-(d-c+1)})),r=new Map;for(let s of o){let a=`${s.epIndex}/${s.scIndex}`;r.set(a,[...r.get(a)??[],s])}for(let s of r.values())for(let{target:a,epIndex:c,scIndex:d,from:p,through:l}of[...s].reverse())t.episodes[c].scenes[d].actions.splice(p,l-p+1,...structuredClone(a.actions));return i}function mm(e){let t=new Set,n=new Set;for(let o of e.episodes){t.has(o.episode_id)&&F("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)&&F("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 r5(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 a=`${n[0]}.scenes[${r[2]}]`;i=e.replace(a,`$.episodes[${o.episode_id}].scenes[${s.scene_id}]`)}}return i}function cm(e,t){return`${e.code}\0${r5(e.path,t)}\0${e.message}`}function s5(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 a5(e,t,n){let o=[],i=new Map(e?.episodes.map(c=>[c.episode_id,c])??[]),r=new Map;for(let c of e?.episodes??[])for(let d of c.scenes)r.set(d.scene_id,d);let s=new Map(t.episodes.map(c=>[c.episode_id,c])),a=new Map;for(let c of t.episodes)for(let d of c.scenes)a.set(d.scene_id,{episodeId:c.episode_id,scene:d});for(let c of n.fullEpisodeIds){let d=s.get(c);if(d===void 0||d.scenes.length>0)continue;let p=(i.get(c)?.scenes.length??0)>0;o.push({code:p?"authoring_episode_cleared":"authoring_empty_episode",path:`$.episodes[${c}]`,message:p?`authoring replaced episode ${c} with an empty scene list`:`authored episode ${c} has no scenes`})}for(let c of n.fullSceneIds){let d=a.get(c);if(d===void 0)continue;let p=`$.episodes[${d.episodeId}].scenes[${c}]`;if(d.scene.actions.length===0){let l=(r.get(c)?.actions.length??0)>0;o.push({code:l?"authoring_scene_cleared":"authoring_empty_scene",path:p,message:l?`authoring replaced scene ${c} with an empty body`:`authored scene ${c} 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 c of n.actionSpans)c.actions.forEach((d,p)=>{d.content.trim()===""&&o.push({code:"authoring_empty_action_content",path:`${c.parent}#replacement[${p}]`,message:"authored action-span replacement contains an action with empty content"})});return o}function dm(e,t,n){let o=St(t),i=s5(n),r=()=>({...o,warnings:[...o.warnings,...a5(e,t,i)]});if(o.ok||e!==null&&Ro(e,t))return r();let s=new Set(e===null?[]:St(e).errors.map(c=>cm(c,e))),a=o.errors.filter(c=>{if(!s.has(cm(c,t)))return!0;let d=/^\$\.episodes\[(\d+)]/.exec(c.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(c.path),f=l===null?void 0:p.scenes[Number(l[1])];return f!==void 0&&i.sceneIds.has(f.scene_id)});return a.length>0&&F("AUTHORING_VALIDATION_FAILED","The proposed script has blocking validation errors.",a.map(c=>`${c.path}: ${c.code} ${c.message}`),["Repair the authoring source and rerun the plan."]),r()}function pm(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 c5(e){let t=e.targets[0];t?.kind!=="script"&&F("AUTHORING_TARGET_MODE","Script create requires exactly one script target.",[],["Use a single <script> block."],B);for(let i of t.episodes)Qd(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=um(n,e.declarations);return mm(n),{script:n,declarations:o}}function gm(e,t,n){if(t.targetKind==="script"){n!=="create"&&F("AUTHORING_TARGET_MODE","Script targets support create only.",[n],["Use --create."],B);let c=c5(t),d=c.script;e!==null&&!Ro(e,d)&&F("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?c.declarations:{createdAssets:[],existingAssets:[...c.declarations.existingAssets,...c.declarations.createdAssets],createdStates:[],existingStates:[...c.declarations.existingStates,...c.declarations.createdStates]},l=dm(e,d,t.targets);return{script:d,changed:e===null||!Ro(e,d),declarations:p,targets:[{kind:"script",address:"global",before:e===null?{episodes:0,scenes:0,actions:0}:Ia(e.episodes),after:Ia(d.episodes),...ss(e?.episodes.map(f=>f.episode_id)??[],d.episodes.map(f=>f.episode_id)),untouchedSiblings:0}],retainedOrphanAssets:pm(d),validation:l}}e===null&&F("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"&&F("AUTHORING_TARGET_MODE",`${t.targetKind} supports replace only.`,[n],["Use --replace."],B);let o=structuredClone(e),i=structuredClone(e),r=um(i,t.declarations),s;switch(t.targetKind){case"episode":{let c=t.targets.flatMap(d=>d.kind==="episode"?[d]:[]);c.length!==t.targets.length&&F("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=e5(o,i,c,n);break}case"scene":{let c=t.targets.flatMap(d=>d.kind==="scene"?[d]:[]);c.length!==t.targets.length&&F("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=t5(o,i,c,n);break}case"episode-span":{let c=t.targets.flatMap(d=>d.kind==="episode-span"?[d]:[]);c.length!==t.targets.length&&F("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=n5(o,i,c);break}case"scene-span":{let c=t.targets.flatMap(d=>d.kind==="scene-span"?[d]:[]);c.length!==t.targets.length&&F("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=o5(o,i,c);break}case"action-span":{let c=t.targets.flatMap(d=>d.kind==="action-span"?[d]:[]);c.length!==t.targets.length&&F("AUTHORING_TARGET_MODE","Authoring targets are not homogeneous.",[],["Keep one target kind per file."],B),s=i5(o,i,c);break}default:F("AUTHORING_TARGET_MODE","Unsupported authoring target.",[t.targetKind],["Use a supported homogeneous target kind."])}mm(i);let a=dm(e,i,t.targets);return{script:i,changed:!Ro(e,i),declarations:r,targets:s,retainedOrphanAssets:pm(i),validation:a}}function D(e,t,n,o){return new S(e,{exitCode:k,errorCode:"AUTHORING_SOURCE_INVALID",hint:o,data:{actual:[`line ${t.line}, column ${t.column}: ${n}`]}})}function Fd(e,t,n){let o="";for(let i=0;i<e.length;i+=1){let r=e[i];if(r!=="\\"){o+=r;continue}let s=e[i+1];if(s===void 0)throw D("Trailing escape is invalid.",{line:t.line,column:t.column+i},e,"Escape a supported character or remove the trailing backslash.");if(s==="\\"||s==="n"||n&&(s==="|"||s==="]")){o+=s==="n"?`
|
|
129
|
+
`:s,i+=1;continue}throw D("Unknown escape sequence.",{line:t.line,column:t.column+i},`\\${s}`,n?"Use only \\|, \\], \\\\, or \\n in a header.":"Use only \\\\ or \\n in record content.")}return o}function ir(e,t){let n={line:t,column:Math.max(1,e.indexOf("[")+1)},o=e.trimStart();if(!o.startsWith("["))throw D("Expected a bracket record.",n,e,"Start the semantic line with a known [type] record.");let i=-1,r=!1;for(let 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 D("Bracket record is not closed.",n,e,"Add the closing ].");let s=o.slice(1,i),a=[],c="";r=!1;for(let h=0;h<s.length;h+=1){let m=s[h];r?(c+=`\\${m}`,r=!1):m==="\\"?r=!0:m==="|"?(a.push(c),c=""):c+=m}r&&(c+="\\"),a.push(c);let[d,...p]=a,l=Fd(d??"",n,!0);if(!l)throw D("Record type is empty.",n,e,"Use a known record type.");let f=o.slice(i+1),u=f.startsWith(" ")?f.slice(1):f;return{type:l,slots:p.map(h=>Fd(h,n,!0)),content:Fd(u,{line:t,column:i+2},!1),source:n}}function At(){return{extend:{},extendPresent:!1,aliases:[],aliasesPresent:!1,phase:"extend"}}function Xn(e){return e.extendPresent||e.aliasesPresent||e.prompt!==void 0}function kt(e){return e.extendPresent?e.extend:void 0}function Yd(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(Yd):typeof e!="object"?!1:Object.values(e).every(Yd)}function qd(e){if(Array.isArray(e))return e.map(qd);if(e!==null&&typeof e=="object"){let t={};for(let n of Object.keys(e).sort())t[n]=qd(e[n]);return t}return e}function hm(e){return e==="featured"||e==="background"}function d5(e){return e==="\u4E3B\u89D2"||e==="\u914D\u89D2"}function p5(e){return e==="system"||e==="broadcast"||e==="offscreen"||e==="group"}function l5(e){return e==="actor"||e==="location"||e==="prop"}function ym(e,t,n,o){if(!/^\d+$/.test(e))throw D(`${n} must be an integer.`,t,e||"<empty>",`Use ${o?"a non-negative":"a positive"} integer.`);let i=Number(e);if(!Number.isSafeInteger(i)||(o?i<0:i<1))throw D(`${n} is out of range.`,t,e,`Use ${o?"a non-negative":"a positive"} safe integer.`);return i}function u5(e,t){let n=e.trim();if(!n.startsWith("<"))return null;let o={line:t,column:e.indexOf("<")+1},i=/^<\/([a-z-]+)>$/.exec(n);if(i)return{name:i[1],closing:!0,attrs:new Map,source:o};let r=/^<([a-z-]+)(?: ([^>]+))?>$/.exec(n);if(!r)throw D("Block tag syntax is invalid.",o,e,"Use <name key=value> or </name> on its own line.");let s=new Map,a=r[2]??"";if(a)for(let c of a.split(" ")){if(!c)throw D("Block attributes must use one space separators.",o,e,"Use canonical key=value attributes separated by one space.");let d=/^([a-z]+)=([A-Za-z0-9_./#:-]+)$/.exec(c);if(!d)throw D("Block attribute syntax is invalid.",o,c,"Use unquoted canonical key=value attributes.");if(s.has(d[1]))throw D("Block attribute is duplicated.",o,d[1],"Keep exactly one value for each attribute.");s.set(d[1],d[2])}return{name:r[1],closing:!1,attrs:s,source:o}}function Mn(e,t,n=[]){let o=new Set([...t,...n]),i=[...e.attrs.keys()].filter(s=>!o.has(s)),r=t.filter(s=>!e.attrs.has(s));if(i.length>0||r.length>0)throw D(`Attributes for <${e.name}> are invalid.`,e.source,`missing=${r.join(",")||"-"} unknown=${i.join(",")||"-"}`,`Use ${[...t,...n].map(s=>`${s}=...`).join(" ")}.`)}function f5(e,t){if(!e)throw D("Speaker is required.",t,"<empty>","Use act_ID[/state_ID] or system|broadcast|offscreen|group[:label].");let n=e.indexOf("/"),o=n>=0?e.slice(0,n):e;if(/^act_[A-Za-z0-9_-]+$/.test(o)){if(n<0)return{actor_id:o};let s=e.slice(n+1);if(!s||s.includes("/"))throw D("Actor speaker state is invalid.",t,e,"Use act_ID/state_ID.");return{actor_id:o,state_id:s}}let i=e.indexOf(":"),r=i>=0?e.slice(0,i):e;if(!ai.has(r)||!p5(r))throw D("Speaker kind is invalid.",t,e,"Use an actor ID or system, broadcast, offscreen, or group.");return i<0?{kind:r}:{kind:r,label:e.slice(i+1)}}function m5(e,t){let o={act:"action",dlg:"dialogue",think:"inner_thought",trans:"transition"}[e.type];if(o===void 0||!tn.has(o))throw D("Body record type is invalid.",e.source,e.type,"Use [act], [dlg], [think], or [trans].");let i={type:o,content:e.content};if(o==="dialogue"||o==="inner_thought"){if(e.slots.length<1||e.slots.length>2)throw D("Speaker record slots are invalid.",e.source,e.slots.join("|"),`Use [${e.type}|speaker|emotion?].`);i.speaker=f5(e.slots[0],e.source),e.slots.length===2&&(i.emotion=e.slots[1])}else{if(e.slots.length>1)throw D("Body record slots are invalid.",e.source,e.slots.join("|"),`Use [${e.type}|emotion?].`);e.slots.length===1&&(i.emotion=e.slots[0])}let r=kt(t);if(r!==void 0&&(i.extend=r),t.aliasesPresent)throw D("Alias cannot modify an action.",t.source??e.source,t.aliases.join(","),"Use [alias] only before an asset declaration.");return t.prompt!==void 0&&(i.transition_prompt=t.prompt),i}var Wd=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(Mn(t,["version"]),t.attrs.get("version")!=="1")throw D("Authoring version is unsupported.",t.source,t.attrs.get("version")??"<missing>","Use <authoring version=1>.");let n=[],o=[],i=!1,r=At();for(;;){if(this.skipBlank(),this.peekClose("authoring")){Xn(r)&&this.throwDangling(r),this.takeClose("authoring");break}let c=this.peekSemantic();if(c===null)throw this.eofError("authoring");if(c.record?.type==="extensions"||c.record?.type==="extend"){r=this.addModifier(r,this.takeRecord());continue}if(c.tag?.name==="create"&&!c.tag.closing){if(i)throw D("<create> must precede every target.",c.tag.source,"<create>","Move the single <create> block before the targets.");Xn(r)&&this.throwUnsupportedModifiers(r,"create"),n.push(...this.parseCreate()),i=!0;continue}i=!0,o.push(this.parseTarget(r)),r=At()}if(this.skipBlank(),this.index<this.lines.length){let c={line:this.index+1,column:1};throw D("Content exists after </authoring>.",c,this.lines[this.index],"Remove content outside the root block.")}if(o.length===0)throw D("Authoring file has no target.",t.source,"<authoring>","Add one or more homogeneous target blocks.");let s=o[0].kind,a=o.find(c=>c.kind!==s);if(a!==void 0)throw D("Authoring targets are not homogeneous.",a.source,a.kind,`Keep only ${s} targets in this file.`);if(s==="script"&&o.length!==1)throw D("A script authoring file has exactly one target.",o[1].source,"second <script>","Keep one <script> target.");return{version:1,declarations:n,targets:o,targetKind:s}}parseCreate(){let t=this.takeOpen("create");Mn(t,[]);let n=[],o=At();for(;;){if(this.skipBlank(),this.peekClose("create"))return Xn(o)&&this.throwDangling(o),this.takeClose("create"),n;let i=this.takeRecord();if(i.type==="extensions"||i.type==="extend"||i.type==="aliases"||i.type==="alias"||i.type==="prompt"){o=this.addModifier(o,i);continue}if(i.type==="actor"){if(i.slots.length<3||i.slots.length>4)throw D("Actor declaration slots are invalid.",i.source,i.slots.join("|"),"Use [actor|id|name|importance|role?] description.");let[r,s,a,c]=i.slots;if(!r||!s||!a||!$t.has(a)||!fm(a))throw D("Actor declaration is invalid.",i.source,i.slots.join("|"),"Provide id, name, and featured|background importance.");if(c!==void 0&&(!_o.has(c)||!r5(c)))throw D("Actor role is invalid.",i.source,c,"Use \u4E3B\u89D2 or \u914D\u89D2, or omit the slot.");let d={actor_id:r,actor_name:s,importance:a,description:i.content,states:[]};c!==void 0&&(d.role_type=c),o.aliasesPresent&&(d.aliases=[...o.aliases]);let p=kt(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=At();continue}if(i.type==="location"||i.type==="prop"){if(i.slots.length!==3)throw D(`${i.type} declaration slots are invalid.`,i.source,i.slots.join("|"),`Use [${i.type}|id|name|importance] description.`);let[r,s,a]=i.slots;if(!r||!s||!a||!$t.has(a)||!fm(a))throw D(`${i.type} declaration is invalid.`,i.source,i.slots.join("|"),"Provide id, name, and featured|background importance.");o.prompt!==void 0&&this.throwUnsupportedModifiers(o,i.type);let c=kt(o);if(i.type==="location"){let d={location_id:r,location_name:s,importance:a,description:i.content,states:[]};o.aliasesPresent&&(d.aliases=[...o.aliases]),c!==void 0&&(d.extend=c),n.push({declarationKind:"location",value:d,source:i.source})}else{let d={prop_id:r,prop_name:s,importance:a,description:i.content,states:[]};o.aliasesPresent&&(d.aliases=[...o.aliases]),c!==void 0&&(d.extend=c),n.push({declarationKind:"prop",value:d,source:i.source})}o=At();continue}if(i.type==="state"){if(i.slots.length!==3)throw D("State declaration slots are invalid.",i.source,i.slots.join("|"),"Use [state|kind:asset_id|state_id|state_name] description.");(o.aliasesPresent||o.prompt!==void 0)&&this.throwUnsupportedModifiers(o,"state");let[r,s,a]=i.slots,c=/^(actor|location|prop):(.+)$/.exec(r??""),d=c?.[1]??"";if(!c||!a5(d)||!s||!a)throw D("State declaration is invalid.",i.source,i.slots.join("|"),"Use a typed owner and non-empty state ID/name.");let p={state_id:s,state_name:a,description:i.content},l=kt(o);l!==void 0&&(p.extend=l),n.push({declarationKind:"state",ownerKind:d,ownerId:c[2],value:p,source:i.source}),o=At();continue}throw D("Record is not allowed in <create>.",i.source,i.type,"Use actor, location, prop, state, or a supported prefix modifier.")}}parseTarget(t){let n=this.peekTag();if(n===null||n.closing){let o=n?.source??{line:this.index+1,column:1};throw D("Expected a target block.",o,this.lines[this.index]??"<eof>","Add a supported target block.")}switch((t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,n.name),n.name){case"script":return this.parseScript(t);case"episode":return{kind:"episode",value:this.parseEpisode(t),source:n.source,...kt(t)?{extend:kt(t)}:{}};case"episode-span":return this.parseEpisodeSpan(t);case"scene":return Mn(n,["id","parent"]),{kind:"scene",parent:n.attrs.get("parent"),value:this.parseScene(t,!0),source:n.source,...kt(t)?{extend:kt(t)}:{}};case"scene-span":return this.parseSceneSpan(t);case"action-span":return this.parseActionSpan(t);default:throw D("Unknown target block.",n.source,n.name,"Use script, episode, episode-span, scene, scene-span, or action-span.")}}parseScript(t){let n=this.takeOpen("script");Mn(n,[]);let o=["title","worldview","worldview-raw","style","synopsis","logline","theme","main-characters","main-character"],i=new Map,r=[],s=[],a=-1,c=!1,d=At();for(;;){if(this.skipBlank(),this.peekClose("script")){Xn(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}Xn(d)&&this.throwUnsupportedModifiers(d,m.type);let g=o.indexOf(m.type),w=m.type==="main-character";if(c||g<0||g<a||!w&&i.has(m.type))throw D("Metadata record in <script> is invalid or out of order.",m.source,m.type,`Use ${o.join(", ")} in canonical order before episode blocks.`);if(a=g,m.type==="main-characters"){if(m.slots.length!==0||m.content!=="")throw D("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 D("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 D("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 D("Unexpected member in <script>.",m,this.lines[this.index]??"<eof>","Use metadata records followed by <episode> blocks.")}c=!0,s.push(this.parseEpisode(d)),d=At()}let p=this.requiredMetadata(i,"title",n.source),l=this.requiredMetadata(i,"worldview",n.source),f=this.requiredMetadata(i,"style",n.source),u=kt(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");Mn(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=kt(t);return r!==void 0&&(i.extend=r),i}parseScene(t,n){let o=this.takeOpen("scene");Mn(o,n?["id","parent"]:["id"]),(t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,"scene");let i,r,s=[],a=[],c="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(c==="body")throw D("Scene has more than one body.",f.tag.source,"<body>","Keep exactly one <body>.");c="body",d=this.parseBody();continue}if(f?.record===void 0){let h=f?.tag?.source??{line:this.index+1,column:1};throw D("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 D("Scene prefix modifier must directly precede <scene>.",u.source,u.type,"Move the modifier before the <scene> opening tag.");if(u.type==="environment"){if(c!=="environment"||i!==void 0||u.slots.length>2)throw D("Environment record is out of order or invalid.",u.source,u.slots.join("|"),"Place at most one [environment|space?|time?] first.");i={},u.slots.length>=1&&u.slots[0]!==""&&(i.space=u.slots[0]),u.slots.length>=2&&u.slots[1]!==""&&(i.time=u.slots[1]);continue}if(u.type==="location"){if(c==="cast"||c==="prop"||c==="body"||r!==void 0||u.slots.length>2)throw D("Location record is out of order or invalid.",u.source,u.slots.join("|"),"Place exactly one [location|id?|state?] before cast.");c="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||c==="prop"||c==="body"||u.slots.length<1||u.slots.length>2||!u.slots[0])throw D("Cast record is out of order or invalid.",u.source,u.slots.join("|"),"Place [cast|actor_id|state_id?] after location and before props.");c="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||c==="body"||u.slots.length<1||u.slots.length>2||!u.slots[0])throw D("Prop record is out of order or invalid.",u.source,u.slots.join("|"),"Place [prop|prop_id|state_id?] after cast and before body.");c="prop",a.push(u.slots.length===2?{prop_id:u.slots[0],state_id:u.slots[1]}:{prop_id:u.slots[0]});continue}throw D("Record is not allowed in a scene header.",u.source,u.type,"Use environment, location, cast, prop, or body records.")}if(r===void 0)throw D("Scene location record is missing.",o.source,`<scene id=${o.attrs.get("id")}>`,"Add [location] or [location|loc_ID|state_ID].");if(d===void 0)throw D("Scene body is missing.",o.source,`<scene id=${o.attrs.get("id")}>`,"Add one <body> block.");let p={scene_id:o.attrs.get("id"),location:r,actors:s,props:a,actions:d};i!==void 0&&(p.environment=i);let l=kt(t);return l!==void 0&&(p.extend=l),p}parseBody(){let t=this.takeOpen("body");Mn(t,[]);let n=[],o=At();for(;;){if(this.skipBlank(),this.peekClose("body"))return Xn(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(p5(i,o)),o=At()}}parseEpisodeSpan(t){let n=this.takeOpen("episode-span");Mn(n,["from","through"]);let o=this.parseOnlyChildren("episode-span","episode",r=>this.parseEpisode(r)),i=kt(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");Mn(n,["parent","from","through"]);let o=this.parseOnlyChildren("scene-span","scene",r=>this.parseScene(r,!1)),i=kt(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");Mn(n,["parent","from","through"]),this.skipBlank();let o=this.parseBody();this.skipBlank(),this.takeClose("action-span");let i=kt(t);return{kind:"action-span",parent:n.attrs.get("parent"),from:mm(n.attrs.get("from"),n.source,"action-span from",!0),through:mm(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=[],a=-1,c=!1,d=At();for(;;){if(this.skipBlank(),this.peekClose(t))return Xn(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}Xn(d)&&this.throwUnsupportedModifiers(d,f.type);let u=n.indexOf(f.type);if(c||u<0||u<a||r.has(f.type)||f.slots.length!==0)throw D(`Metadata record in <${t}> is invalid or out of order.`,f.source,f.type,`Use each of ${n.join(", ")} at most once in canonical order before child blocks.`);a=u,r.set(f.type,f.content);continue}let l=p?.tag;if(l===void 0||l.closing||l.name!==o){let f=l?.source??{line:this.index+1,column:1};throw D(`Unexpected member in <${t}>.`,f,this.lines[this.index]??"<eof>",`Use metadata records followed by <${o}> blocks.`)}c=!0,s.push(i(d)),d=At()}}parseOnlyChildren(t,n,o){let i=[],r=At();for(;;){if(this.skipBlank(),this.peekClose(t))return Xn(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 a=s?.tag?.source??s?.record?.source??{line:this.index+1,column:1};throw D(`Only <${n}> children are allowed in <${t}>.`,a,this.lines[this.index]??"<eof>",`Add complete <${n}> blocks.`)}i.push(o(r)),r=At()}}addModifier(t,n){let o={extend:{...t.extend},extendPresent:t.extendPresent,aliases:[...t.aliases],aliasesPresent:t.aliasesPresent,phase:t.phase,...t.prompt!==void 0?{prompt:t.prompt}:{},source:t.source??n.source};if(n.type==="extensions"){if(o.phase!=="extend"||o.extendPresent||n.slots.length!==0||n.content!=="")throw D("Extensions marker is invalid or out of order.",n.source,n.content||"<empty>","Use one [extensions] marker before extension records.");return o.extendPresent=!0,o}if(n.type==="extend"){if(o.phase!=="extend"||n.slots.length!==1||!n.slots[0])throw D("Extend modifier is invalid or out of order.",n.source,n.slots.join("|"),"Place unique [extend|key] records first.");let i=n.slots[0];if(Object.hasOwn(o.extend,i))throw D("Extend key is duplicated.",n.source,i,"Keep one value for each extension key.");let r;try{r=JSON.parse(n.content)}catch{throw D("Extension value is not valid JSON.",n.source,n.content,"Use one canonical JSON value.")}if(!Hd(r))throw D("Extension value is not JSON-compatible.",n.source,n.content,"Use string, number, boolean, null, array, or object.");return o.extendPresent=!0,o.extend[i]=Qd(r),o}if(n.type==="aliases"){if(o.phase!=="extend"||o.aliasesPresent||n.slots.length!==0||n.content!=="")throw D("Aliases marker is invalid or out of order.",n.source,n.content||"<empty>","Use one [aliases] marker after extensions and before alias records.");return o.phase="alias",o.aliasesPresent=!0,o}if(n.type==="alias"){if(o.phase==="prompt"||n.slots.length!==0||!n.content)throw D("Alias modifier is invalid or out of order.",n.source,n.content||"<empty>","Place non-empty [alias] records after extensions and before prompt.");if(o.phase="alias",o.aliasesPresent=!0,o.aliases.includes(n.content))throw D("Alias is duplicated.",n.source,n.content,"Keep each alias once.");return o.aliases.push(n.content),o}if(n.type==="prompt"){if(o.prompt!==void 0||n.slots.length!==3||n.slots.some(i=>!i))throw D("Prompt modifier is invalid.",n.source,n.slots.join("|"),"Use one [prompt|target|process|contrast] after extensions and aliases.");if(!/^(?:actor:act_|location:loc_|prop:prp_)[A-Za-z0-9_-]+$/.test(n.slots[0]))throw D("Prompt target is invalid.",n.source,n.slots[0],"Use actor:act_ID, location:loc_ID, or prop:prp_ID.");return o.phase="prompt",o.prompt={target:n.slots[0],process:n.slots[1],contrast:n.slots[2]},o}throw D("Unknown prefix modifier.",n.source,n.type,"Use extend, alias, or prompt.")}requiredMetadata(t,n,o){let i=t.get(n);if(i===void 0)throw D(`Script ${n} record is missing.`,o,"<script>",`Add [${n}] in canonical metadata order.`);return i}peekSemantic(){if(this.skipBlank(),this.index>=this.lines.length)return null;let t=this.lines[this.index],n=c5(t,this.index+1);if(n!==null)return{tag:n};if(t.trimStart().startsWith("["))return{record:or(t,this.index+1)};let o={line:this.index+1,column:Math.max(1,t.search(/\S/)+1)};throw D("Semantic line is neither a tag nor a bracket record.",o,t,"Use only known tags, bracket records, or blank lines.")}peekTag(){return this.peekSemantic()?.tag??null}takeRecord(){let t=this.peekSemantic();if(t?.record===void 0){let n=t?.tag?.source??{line:this.index+1,column:1};throw D("Expected a bracket record.",n,this.lines[this.index]??"<eof>","Use the record required at this position.")}return this.index+=1,t.record}takeOpen(t){let n=this.peekTag();if(n===null||n.closing||n.name!==t){let o=n?.source??{line:this.index+1,column:1};throw D(`Expected <${t}>.`,o,this.lines[this.index]??"<eof>",`Open <${t}> here.`)}return this.index+=1,n}takeClose(t){let n=this.peekTag();if(n===null||!n.closing||n.name!==t){let o=n?.source??{line:this.index+1,column:1};throw D(`Expected </${t}>.`,o,this.lines[this.index]??"<eof>",`Close the current <${t}> block.`)}return this.index+=1,n}peekClose(t){let n=this.peekTag();return n!==null&&n.closing&&n.name===t}skipBlank(){for(;this.index<this.lines.length&&this.lines[this.index].trim()==="";)this.index+=1}eofError(t){return D(`Unexpected end of file inside <${t}>.`,{line:this.lines.length,column:1},"<eof>",`Add </${t}>.`)}throwDangling(t){throw D("Prefix modifier has no following node.",t.source??{line:this.index+1,column:1},"dangling modifier","Move it directly before a supported node.")}throwUnsupportedModifiers(t,n){throw D("Prefix modifier does not apply to this node.",t.source??{line:this.index+1,column:1},n,"Remove the unsupported modifier or move it before a supported node.")}};function gm(e){return new Fd(e).parse()}function L(e,t,n){throw new S(e,{exitCode:k,errorCode:"AUTHORING_SOURCE_INVALID",data:{actual:[`line ${t}: ${n}`]}})}function Wd(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]??"",a=s===""?[]:s.split(" ");a.some(c=>c==="")&&L("Tag attributes need one-space separators.",t,n);for(let c of a){let d=/^([a-z]+)=([A-Za-z0-9_./#:-]+)$/.exec(c);(!d||r.has(d[1]))&&L("Tag attributes are invalid.",t,c),r.set(d[1],d[2])}return{name:i[1],closing:!1,attrs:r,line:t}}function Be(e,t,n=[]){let o=new Set([...t,...n]),i=[...e.attrs.keys()].filter(s=>!o.has(s)),r=t.filter(s=>!e.attrs.has(s));(i.length>0||r.length>0)&&L("Tag attributes do not match the canonical grammar.",e.line,[...r.map(s=>`missing:${s}`),...i.map(s=>`unknown:${s}`)].join(","))}var Xd=class{lines;index=0;constructor(t){this.lines=t.split(/\r?\n/).map((n,o)=>({raw:n.replace(/^\s+/,""),line:o+1})).filter(n=>n.raw.trim()!=="")}peek(){let t=this.lines[this.index];return t||L("Unexpected end of authoring file.",this.lines.at(-1)?.line??1,"<eof>"),t}take(){let t=this.peek();return this.index++,t}tag(t,n){let o=this.take(),i=Wd(o.raw,o.line);return(!i||i.name!==t||i.closing!==n)&&L(`Expected ${n?"</":"<"}${t}>.`,o.line,o.raw),i}record(){let t=this.take();return or(t.raw,t.line)}nextTag(){let t=this.peek();return Wd(t.raw,t.line)}nextRecord(){let t=this.peek();return t.raw.startsWith("[")?or(t.raw,t.line):null}};function ep(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(ep):typeof e=="object"&&Object.values(e).every(ep)}function ui(e){let t={},n=e.nextRecord();if(n?.type==="extensions"){e.record();let o={},i=null;for(;(n=e.nextRecord())?.type==="extend";){let r=e.record();(r.slots.length!==1||Object.hasOwn(o,r.slots[0]))&&L("extend record is invalid or duplicated.",r.source.line,r.type);let s=r.slots[0];i!==null&&i>=s&&L("extend keys must use ascending canonical order.",r.source.line,s);let a;try{a=JSON.parse(r.content)}catch{L("extend content must be JSON.",r.source.line,r.content)}ep(a)||L("extend value must be JSON-compatible.",r.source.line,r.content),o[s]=a,i=s}t.extend=o}if(n=e.nextRecord(),n?.type==="aliases"){e.record();let o=[];for(;(n=e.nextRecord())?.type==="alias";){let i=e.record();i.slots.length!==0&&L("alias takes no slots.",i.source.line,i.type),i.content===""&&L("alias must not be empty.",i.source.line,i.type),o.includes(i.content)&&L("alias must not be duplicated.",i.source.line,i.content),o.push(i.content)}t.aliases=o}if(n=e.nextRecord(),n?.type==="prompt"){let o=e.record();(o.slots.length!==3||o.slots.some(r=>r===""))&&L("prompt requires non-empty target, process, and contrast.",o.source.line,o.type);let i=o.slots[0];!$("actor",i)&&!$("location",i)&&!$("prop",i)&&L("prompt target must be an asset ID.",o.source.line,i),t.prompt={target:i,process:o.slots[1],contrast:o.slots[2]}}return t}function Yd(e,t){return e!=="featured"&&e!=="background"&&L("Importance is invalid.",t,e),e}function l5(e,t){if(e!==void 0)return e!=="\u4E3B\u89D2"&&e!=="\u914D\u89D2"&&L("Role type is invalid.",t,e),e}function op(e,t){return e==="default"||$("state",e)?e:L("State ID is invalid.",t,e)}function u5(e){let t=e.tag("create",!1);Be(t,[]);let n=[],o=new Map,i=null,r=0,s=c=>{if(i===null)return;let d=o.get(i);(!d||d.states.length===0||d.states[0].state_id!=="default")&&L("A new asset must be followed immediately by its default state.",c,i),i=null};for(;e.nextTag()?.name!=="create"||e.nextTag()?.closing!==!0;){let c=ui(e),d=e.record();if(d.type==="actor"){r>0&&L("Create declarations are not in canonical order.",d.source.line,d.type),s(d.source.line),c.prompt!==void 0&&L("prompt cannot modify an asset.",d.source.line,d.type),(d.slots.length<3||d.slots.length>4||!$("actor",d.slots[0]))&&L("actor declaration is invalid.",d.source.line,d.type);let p=l5(d.slots[3],d.source.line),l={actor_id:d.slots[0],actor_name:d.slots[1],importance:Yd(d.slots[2],d.source.line),description:d.content,states:[],...p===void 0?{}:{role_type:p},...c.aliases===void 0?{}:{aliases:c.aliases},...c.extend===void 0?{}:{extend:c.extend}};l.aliases?.includes(l.actor_name)&&L("An alias must differ from the asset name.",d.source.line,l.actor_name),n.push({kind:"actor",value:l}),o.set(l.actor_id,l),i=l.actor_id}else if(d.type==="location"||d.type==="prop"){let p=d.type==="location"?1:2;p<r&&L("Create declarations are not in canonical order.",d.source.line,d.type),r=p,s(d.source.line),c.prompt!==void 0&&L("prompt cannot modify an asset.",d.source.line,d.type);let l=d.type;if((d.slots.length!==3||(l==="location"?!$("location",d.slots[0]):!$("prop",d.slots[0])))&&L(`${l} declaration is invalid.`,d.source.line,d.type),l==="location"){let f=d.slots[0];$("location",f)||L("location ID is invalid.",d.source.line,f);let u={location_id:f,location_name:d.slots[1],importance:Yd(d.slots[2],d.source.line),description:d.content,states:[],...c.aliases===void 0?{}:{aliases:c.aliases},...c.extend===void 0?{}:{extend:c.extend}};u.aliases?.includes(u.location_name)&&L("An alias must differ from the asset name.",d.source.line,u.location_name),n.push({kind:l,value:u}),o.set(u.location_id,u),i=u.location_id}else{let f=d.slots[0];$("prop",f)||L("prop ID is invalid.",d.source.line,f);let u={prop_id:f,prop_name:d.slots[1],importance:Yd(d.slots[2],d.source.line),description:d.content,states:[],...c.aliases===void 0?{}:{aliases:c.aliases},...c.extend===void 0?{}:{extend:c.extend}};u.aliases?.includes(u.prop_name)&&L("An alias must differ from the asset name.",d.source.line,u.prop_name),n.push({kind:l,value:u}),o.set(u.prop_id,u),i=u.prop_id}}else if(d.type==="state"){(d.slots.length!==3||c.aliases!==void 0||c.prompt!==void 0)&&L("state declaration is invalid.",d.source.line,d.type);let p=d.slots[0],l=o.get(p);l&&i!==p&&L("States for a new asset must immediately follow that asset.",d.source.line,p),l||(s(d.source.line),r=3);let f={state_id:op(d.slots[1],d.source.line),state_name:d.slots[2],description:d.content,...c.extend===void 0?{}:{extend:c.extend}};l?(l.states.length===0&&f.state_id!=="default"&&L("The first state of a new asset must be default.",d.source.line,f.state_id),l.states.push(f)):n.push({kind:"state",ownerId:p,value:f})}else s(d.source.line),L("Unknown create declaration.",d.source.line,d.type)}s(e.peek().line);let a=e.tag("create",!0);return Be(a,[]),n}function f5(e,t){let n=e.indexOf("/"),o=n<0?e:e.slice(0,n);if($("actor",o))return n<0?{actor_id:o}:{actor_id:o,state_id:op(e.slice(n+1),t)};let i=e.indexOf(":"),r=i<0?e:e.slice(0,i);return["system","broadcast","offscreen","group"].includes(r)?i<0?{kind:r}:{kind:r,label:e.slice(i+1)}:L("Speaker is invalid.",t,e)}function hm(e){let t=ui(e);t.aliases!==void 0&&L("aliases cannot modify an Action.",e.peek().line,"aliases");let n=e.record();return n.type==="act"||n.type==="trans"?((n.slots.length!==1||!$("action",n.slots[0]))&&L("Narrative Action record is invalid.",n.source.line,n.type),{action_id:n.slots[0],type:n.type==="act"?"action":"transition",content:n.content,...t.extend===void 0?{}:{extend:t.extend},...t.prompt===void 0?{}:{transition_prompt:t.prompt}}):n.type!=="dlg"&&n.type!=="think"?L("Unknown Action record.",n.source.line,n.type):((n.slots.length!==2&&n.slots.length!==3||!$("action",n.slots[0]))&&L("Speaking Action record is invalid.",n.source.line,n.type),{action_id:n.slots[0],type:n.type==="dlg"?"dialogue":"inner_thought",speaker:f5(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 qd(e,t){e.length===0&&L("Scene reference needs at least one state.",t,"<empty>");let n=e.map(o=>op(o,t));return new Set(n).size!==n.length&&L("Scene reference repeats a state.",t,n.join(",")),n.sort()}function tp(e,t,n,o){Be(t,n===void 0?["id","parent"]:["id"]);let i=t.attrs.get("id")??"";$("scene",i)||L("Scene ID is invalid.",t.line,i);let r=t.attrs.get("parent")??n;r!==void 0&&!$("episode",r)&&L("Scene parent must be an Episode ID.",t.line,r);let s,a,c=[],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&&L("Scene records are not in canonical order.",m.source.line,m.type),f=g,m.type==="environment"?(s!==void 0&&L("Scene environment is duplicated.",m.source.line,m.type),m.slots.length>2&&L("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"?(a!==void 0&&L("Scene location is duplicated.",m.source.line,m.type),m.slots.length===0?a=null:($("location",m.slots[0])||L("Location ref ID is invalid.",m.source.line,m.slots[0]),a={location_id:m.slots[0],state_ids:qd(m.slots.slice(1),m.source.line)})):m.type==="cast"?($("actor",m.slots[0])||L("Cast ref ID is invalid.",m.source.line,m.slots[0]??""),p.has(m.slots[0])&&L("Scene repeats an actor reference.",m.source.line,m.slots[0]),p.add(m.slots[0]),c.push({actor_id:m.slots[0],state_ids:qd(m.slots.slice(1),m.source.line)})):m.type==="prop"?($("prop",m.slots[0])||L("Prop ref ID is invalid.",m.source.line,m.slots[0]??""),l.has(m.slots[0])&&L("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:qd(m.slots.slice(1),m.source.line)})):L("Unknown scene header record.",m.source.line,m.type)}a===void 0&&L("Scene must declare location or [location].",e.peek().line,i);let u=e.tag("body",!1);Be(u,[]);let h=[];for(;e.nextTag()?.name!=="body"||e.nextTag()?.closing!==!0;)h.push(hm(e));return Be(e.tag("body",!0),[]),Be(e.tag("scene",!0),[]),{...r===void 0?{}:{parent:r},value:{scene_id:i,...s===void 0?{}:{environment:s},location:a,actors:c,props:d,actions:h,...o===void 0?{}:{extend:o}}}}function np(e,t,n){Be(t,["id"]);let o=t.attrs.get("id")??"";$("episode",o)||L("Episode ID is invalid.",t.line,o);let i,r,s=[],a=0;for(;e.nextTag()?.name!=="episode"||e.nextTag()?.closing!==!0;){let c=ui(e);(c.aliases!==void 0||c.prompt!==void 0)&&L("Invalid episode child modifier.",e.peek().line,"modifier");let d=e.nextTag();if(d?.name==="scene"&&!d.closing){a=2,e.take(),s.push(tp(e,d,o,c.extend).value);continue}c.extend!==void 0&&L("extend must precede a scene here.",e.peek().line,"extend");let p=e.record(),l=p.type==="title"?0:p.type==="synopsis"?1:-1;l<a&&L("Episode records are not in canonical order.",p.source.line,p.type),a=l,p.type==="title"?(i!==void 0&&L("Episode title is duplicated.",p.source.line,p.type),p.slots.length!==0&&L("Episode title takes no slots.",p.source.line,p.type),i=p.content):p.type==="synopsis"?(r!==void 0&&L("Episode synopsis is duplicated.",p.source.line,p.type),p.slots.length!==0&&L("Episode synopsis takes no slots.",p.source.line,p.type),r=p.content):L("Unknown episode record.",p.source.line,p.type)}return Be(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 Zd(e,t){let n=e.attrs.get("range")??"",o=n.split("..");return(o.length!==2||!o[0]||!o[1]||!$(t,o[0])||!$(t,o[1]))&&L(`Span range must contain two ${t} IDs.`,e.line,n),[o[0],o[1]]}function m5(e,t,n){Be(t,[]);let o,i,r,s,a,c,d,p,l=[],f=0;for(;e.nextTag()?.name!=="script"||e.nextTag()?.closing!==!0;){let u=ui(e);(u.aliases!==void 0||u.prompt!==void 0)&&L("Invalid script child modifier.",e.peek().line,"modifier");let h=e.nextTag();if(h?.name==="episode"&&!h.closing){f=8,e.take(),l.push(np(e,h,u.extend));continue}u.extend!==void 0&&L("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&&L("Script records are not in canonical order.",m.source.line,m.type),f=g,m.type!=="main-character"&&m.slots.length!==0&&L("Script metadata record takes no slots.",m.source.line,m.type),m.type==="title"?(o!==void 0&&L("Script title is duplicated.",m.source.line,m.type),o=m.content):m.type==="worldview"?(i!==void 0&&L("Script worldview is duplicated.",m.source.line,m.type),i=m.content):m.type==="worldview-raw"?(r!==void 0&&L("Script worldview-raw is duplicated.",m.source.line,m.type),r=m.content):m.type==="style"?(s!==void 0&&L("Script style is duplicated.",m.source.line,m.type),s=m.content):m.type==="synopsis"?(a!==void 0&&L("Script synopsis is duplicated.",m.source.line,m.type),a=m.content):m.type==="logline"?(c!==void 0&&L("Script logline is duplicated.",m.source.line,m.type),c=m.content):m.type==="theme"?(d!==void 0&&L("Script theme is duplicated.",m.source.line,m.type),d=m.content):m.type==="main-characters"?(p!==void 0&&L("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]}):L("Unknown script record.",m.source.line,m.type)}return Be(e.tag("script",!0),[]),(o===void 0||i===void 0||s===void 0)&&L("Script target needs title, worldview, and style.",e.peek().line,"script"),{kind:"script",value:{title:o,worldview:i,style:s,episodes:l,...r===void 0?{}:{worldview_raw:r},...a===void 0?{}:{synopsis:a},...c===void 0?{}:{logline:c},...d===void 0?{}:{theme:d},...p===void 0?{}:{main_characters:p},...n===void 0?{}:{extend:n}}}}function ym(e){let t=new Xd(e),n=t.tag("authoring",!1);Be(n,["version"]),n.attrs.get("version")!=="1"&&L("authoring version must be 1.",1,n.attrs.get("version")??"<missing>");let o=t.nextTag()?.name==="create"?u5(t):[],i=[];for(;t.nextTag()?.name!=="authoring"||t.nextTag()?.closing!==!0;){let s=ui(t);(s.aliases!==void 0||s.prompt!==void 0)&&L("Invalid target modifier.",t.peek().line,"modifier");let a=t.take(),c=Wd(a.raw,a.line);if((!c||c.closing)&&L("Expected an authoring target.",a.line,a.raw),c.name==="script")i.push(m5(t,c,s.extend));else if(c.name==="episode")i.push({kind:"episode",value:np(t,c,s.extend)});else if(c.name==="scene"){let d=tp(t,c,void 0,s.extend);d.parent||L("Top-level scene needs parent.",a.line,a.raw),i.push({kind:"scene",parent:d.parent,value:d.value})}else if(c.name==="episode-span"){s.extend!==void 0&&L("A span cannot carry node extensions.",a.line,a.raw),Be(c,["range"]);let[d,p]=Zd(c,"episode"),l=[];for(;t.nextTag()?.name!=="episode-span"||t.nextTag()?.closing!==!0;){let f=ui(t);(f.aliases!==void 0||f.prompt!==void 0)&&L("Invalid episode child modifier.",t.peek().line,"modifier");let u=t.tag("episode",!1);l.push(np(t,u,f.extend))}Be(t.tag("episode-span",!0),[]),i.push({kind:"episode-span",from:d,through:p,values:l})}else if(c.name==="scene-span"){s.extend!==void 0&&L("A span cannot carry node extensions.",a.line,a.raw),Be(c,["parent","range"]);let[d,p]=Zd(c,"scene"),l=c.attrs.get("parent")??L("scene-span needs parent.",a.line,a.raw);$("episode",l)||L("scene-span parent must be an Episode ID.",a.line,l);let f=[];for(;t.nextTag()?.name!=="scene-span"||t.nextTag()?.closing!==!0;){let u=ui(t);(u.aliases!==void 0||u.prompt!==void 0)&&L("Invalid scene child modifier.",t.peek().line,"modifier");let h=t.tag("scene",!1);f.push(tp(t,h,l,u.extend).value)}Be(t.tag("scene-span",!0),[]),i.push({kind:"scene-span",parent:l,from:d,through:p,values:f})}else if(c.name==="action-span"){s.extend!==void 0&&L("A span cannot carry node extensions.",a.line,a.raw),Be(c,["parent","range"]);let[d,p]=Zd(c,"action"),l=c.attrs.get("parent")??L("action-span needs parent.",a.line,a.raw);$("scene",l)||L("action-span parent must be a Scene ID.",a.line,l),Be(t.tag("body",!1),[]);let f=[];for(;t.nextTag()?.name!=="body"||t.nextTag()?.closing!==!0;)f.push(hm(t));Be(t.tag("body",!0),[]),Be(t.tag("action-span",!0),[]),i.push({kind:"action-span",parent:l,from:d,through:p,values:f})}else L("Unknown authoring target.",a.line,c.name)}Be(t.tag("authoring",!0),[]),(t.index!==t.lines.length||i.length===0)&&L("Authoring file has trailing content or no targets.",t.peek().line,"<root>");let r=i[0].kind;return i.every(s=>s.kind===r)||L("All targets must have the same kind.",1,r),{declarations:o,targets:i,targetKind:r}}function Nn(e){if(Array.isArray(e))return e.map(t=>Nn(t));if(ie(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Nn(e[n]);return t}return e}function ip(e){if(e.length===0)return[];let t={};for(let i of e){let r=O(i.severity);t[r]=(t[r]??0)+1}let n=Object.entries(t).sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>`${i}: ${r}`),o=e[0];return[n.join("; "),`first: ${o.code} - ${o.summary}`,...o.repair_hint?[`repair: ${o.repair_hint}`]:[]]}function wm(e,t){if(!(t.ok||e!==null&&hd(Te(e),t)))throw new S("The proposed document is not a valid or strictly improved Script v4.",{exitCode:k,errorCode:"AUTHORING_VALIDATION_FAILED",data:{actual:t.errors.slice(0,20).map(n=>`${n.path}: ${n.message}`)}})}function Ve(e,t){throw new S(e,{exitCode:k,errorCode:"AUTHORING_APPLY_INVALID",data:{actual:t}})}function sp(e){return{ids:e.map(t=>t.action_id),counts:{episodes:0,scenes:0,actions:e.length}}}function ir(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 Mo(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 g5(e){return e.kind==="script"?Mo(e.value.episodes):e.kind==="episode"?Mo([e.value]):e.kind==="episode-span"?Mo(e.values):e.kind==="scene"?ir([e.value]):e.kind==="scene-span"?ir(e.values):sp(e.values)}function h5(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 rp(e,t){return JSON.stringify(Nn(e))===JSON.stringify(Nn(t))}function xm(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=[],a=[],c=d=>{(o.has(d)?a:s).push(d)};for(let d of t){if(d.kind==="state"){n.has(d.ownerId)&&r.push(d.ownerId),c(`${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=>{c(`${p}/${l.state_id}`)})}return{createdAssets:i,existingAssets:[...new Set(r)],createdStates:s,existingStates:a}}function Em(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 _m(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 Sm(e,t){let n=e===null?[]:_m(e),o=_m(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 y5(e,t){for(let n of t)if(n.kind==="actor")e.actors.some(o=>o.actor_id===n.value.actor_id)&&Ve("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)&&Ve("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)&&Ve("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||Ve("State declaration owner was not found.",[n.ownerId]),o.states.some(i=>i.state_id===n.value.state_id)&&Ve("State declaration cannot redefine an existing state.",[`${n.ownerId}/${n.value.state_id}`]),o.states.push(structuredClone(n.value))}}function on(e,t,n){let o=e.indexOf(t),i=e.indexOf(n);return(o<0||i<0)&&Ve("Span endpoint was not found.",[t,n]),[Math.min(o,i),Math.max(o,i)]}function w5(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"?on(o,t.value.episode_id,t.value.episode_id):on(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"?on(o,t.value.scene_id,t.value.scene_id):on(o,t.from,t.through)}let n=e.episodes.flatMap(o=>o.scenes.flatMap(i=>i.actions.map(r=>r.action_id)));return on(n,t.from,t.through)}function x5(e,t){let n=-1;for(let o of t){let[i,r]=w5(e,o);i<=n&&Ve("Replace targets must follow current document order without overlap.",[bm(o)]),n=r}}function bm(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 Im(e,t){if(t.kind==="script")return{...Mo(e.episodes),siblings:0};if(t.kind==="episode"){let r=On(e,t.value.episode_id);return{...Mo(r?[r.episode]:[]),siblings:Math.max(0,e.episodes.length-(r?1:0))}}if(t.kind==="episode-span"){let[r,s]=on(e.episodes.map(a=>a.episode_id),t.from,t.through);return{...Mo(e.episodes.slice(r,s+1)),siblings:e.episodes.length-(s-r+1)}}if(t.kind==="scene"){let r=Wn(e,t.value.scene_id),s=On(e,t.parent)?.episode;return{...ir(r?[r.scene]:[]),siblings:r?Math.max(0,r.episode.scenes.length-1):s?.scenes.length??0}}if(t.kind==="scene-span"){let r=On(e,t.parent)?.episode;if(!r)return{...ir([]),siblings:0};let[s,a]=on(r.scenes.map(c=>c.scene_id),t.from,t.through);return{...ir(r.scenes.slice(s,a+1)),siblings:r.scenes.length-(a-s+1)}}let n=Wn(e,t.parent)?.scene;if(!n)return{...sp([]),siblings:0};let[o,i]=on(n.actions.map(r=>r.action_id),t.from,t.through);return{...sp(n.actions.slice(o,i+1)),siblings:n.actions.length-(i-o+1)}}function Am(e,t){let n=g5(e),o=new Set(t.ids),i=new Set(n.ids);return{kind:e.kind,address:bm(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 E5(e,t){if(t.kind==="script"&&Ve("An existing Script v4 is not replaced through a script root.",["script"]),t.kind==="episode"){let n=On(e,t.value.episode_id);n||Ve("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]=on(e.episodes.map(i=>i.episode_id),t.from,t.through);t.values.length===0&&Ve("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=Wn(e,t.value.scene_id);(!n||n.episode.episode_id!==t.parent)&&Ve("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=On(e,t.parent)?.episode;n||Ve("Scene span parent was not found.",[t.parent]);let[o,i]=on(n.scenes.map(r=>r.scene_id),t.from,t.through);t.values.length===0&&Ve("Scene span replacement cannot be empty.",[t.from,t.through]),n.scenes.splice(o,i-o+1,...structuredClone(t.values))}else{let n=Wn(e,t.parent)?.scene;n||Ve("Action span parent was not found.",[t.parent]);let[o,i]=on(n.actions.map(r=>r.action_id),t.from,t.through);t.values.length===0&&Ve("Action span replacement cannot be empty.",[t.from,t.through]),n.actions.splice(o,i-o+1,...structuredClone(t.values))}}function _5(e,t){if(t.kind==="episode")e.episodes.push(structuredClone(t.value));else if(t.kind==="scene"){let n=On(e,t.parent)?.episode;n||Ve("Scene create parent was not found.",[t.parent]),n.scenes.push(structuredClone(t.value))}else Ve("This target kind does not support create against an existing script.",[t.kind])}function km(e){if(e.targets.length!==1||e.targets[0].kind!=="script")return Ve("Script create requires exactly one script target.",[e.targetKind]);if(e.declarations.some(n=>n.kind==="state"))return Ve("Standalone state declarations need an existing owner.",["state"]);let t=e.targets[0];return{version:4,...structuredClone(t.value),...h5(e.declarations)}}function vm(e,t,n){let o;if(e===null)n!=="create"&&Ve("A missing target requires one script create target.",[n,t.targetKind]),o=km(t);else if(n==="create"&&t.targetKind==="script")o=km(t),rp(o,e)||Ve("Script create retry differs from the existing script.",["script"]);else{o=structuredClone(e),n==="replace"&&x5(e,t.targets),y5(o,t.declarations);let r=t.targets.map(c=>Im(e,c));if(n==="replace")for(let c of[...t.targets].reverse())E5(o,c);else for(let c of t.targets)_5(o,c);let s=t.targets.map((c,d)=>Am(c,r[d])),a=Te(o);return wm(e,a),{script:o,changed:!rp(e,o),validation:a,targets:s,declarations:xm(e,t.declarations),retainedOrphanAssets:Em(o),identity:Sm(e,o)}}let i=Te(o);return wm(e,i),{script:o,changed:e===null||!rp(e,o),validation:i,declarations:xm(e,t.declarations),retainedOrphanAssets:Em(o),identity:Sm(e,o),targets:t.targets.map(r=>{let s=e===null?{...Mo([]),siblings:0}:Im(e,r);return Am(r,s)})}}function fi(e,t){throw new S(e,{exitCode:B,errorCode:"AUTHORING_USAGE_INVALID",hint:"Choose exactly one mode and pass a regular authoring source file.",data:{expected:["scriptctl authoring write <file> (--create|--replace) [--apply --plan <digest>]"],actual:t}})}function S5(e){(!e||e==="-")&&fi("Authoring input must be a named file.",[e||"<missing>"]);let t=Om.resolve(e),n;try{n=as.statSync(t)}catch{throw new S("The authoring source file does not exist.",{exitCode:k,errorCode:"AUTHORING_SOURCE_UNAVAILABLE",hint:"Write the complete authoring draft to a file, then rerun the command.",data:{actual:[t]}})}n.isFile()||fi("Authoring input must be a regular file.",[t]);let o=as.readFileSync(t);return{absolutePath:t,bytes:o,text:o.toString("utf-8")}}function I5(e){let t=Zr(e);if(t===null)return{script:null,baseline:"missing",fingerprint:t};let n;try{n=JSON.parse(as.readFileSync(e,"utf-8"))}catch(i){throw new S("The local script is not valid JSON.",{exitCode:k,errorCode:"SCRIPT_JSON_INVALID",hint:"Repair the local JSON file, then rerun authoring.",data:{actual:[e,i instanceof Error?i.message:String(i)]}})}let o=ga(n);return{script:o,baseline:je(o),fingerprint:t}}function A5(e){let t=e.create===!0,n=e.replace===!0;return t===n&&fi("Choose exactly one authoring mode.",[`create=${t}`,`replace=${n}`]),t?"create":"replace"}function Rm(e){return`sha256:${_e(JSON.stringify(e))}`}function k5(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 b5(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 v5(e,t,n,o,i){let r=ym(t.text),s=i.script===null?null:vn(i.script),a=vm(s,r,n),c=`sha256:${ap.createHash("sha256").update(t.bytes).digest("hex")}`,d={version:1,sourceDigest:c,mode:n,targetKind:r.targetKind,targets:a.targets.map(g=>g.address),baseline:i.baseline,plan:{targets:a.targets,declarations:a.declarations,retainedOrphanAssets:a.retainedOrphanAssets,identity:a.identity,validation:a.validation}},p=Rm(d),l=e.apply===!0,f=O(e.plan).trim();if(l&&!f&&fi("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!l&&f&&fi("--plan is only valid together with --apply.",[`plan=${f}`]),l&&f!==p)throw new S("The supplied plan does not match the current source, mode, targets, or script baseline.",{exitCode:k,errorCode:"AUTHORING_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[p],actual:[f]}});l&&a.changed&&(i.script===null?Wr(o,i.fingerprint):Kt(o,i.baseline),Ze(o,a.script));let u=a.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(a.declarations.createdAssets)}`,`existing_assets=${JSON.stringify(a.declarations.existingAssets)}`,`created_states=${JSON.stringify(a.declarations.createdStates)}`,`existing_states=${JSON.stringify(a.declarations.existingStates)}`,`retained_orphan_assets=${JSON.stringify(a.retainedOrphanAssets)}`,`created_ids=${JSON.stringify(a.identity.createdIds)}`,`removed_ids=${JSON.stringify(a.identity.removedIds)}`,`retained_ids=${JSON.stringify(a.identity.retainedIds)}`),[{text:[`${l?"Applied":"Planned"} ${a.targets.length} ${r.targetKind} target(s); validation ${a.validation.ok?"passed":"needs repair"}`,`plan: ${p}`,...u].join(`
|
|
132
|
-
`),data:{op:"write",changed:a.changed,source_path:t.absolutePath,source_digest:c,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:a.targets,declarations:a.declarations,retained_orphan_assets:a.retainedOrphanAssets,identity:a.identity,validation:a.validation,applied:l,script_version:4}},V]}function
|
|
133
|
-
`),data:{op:"write",changed:c.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:a.targetKind,targets:c.targets,declarations:c.declarations,counts:h,validation:c.validation,retained_orphan_assets:c.retainedOrphanAssets,applied:f,script_version:3}},V]}function
|
|
131
|
+
`)}parse(){this.skipBlank();let t=this.takeOpen("authoring");if(Mn(t,["version"]),t.attrs.get("version")!=="1")throw D("Authoring version is unsupported.",t.source,t.attrs.get("version")??"<missing>","Use <authoring version=1>.");let n=[],o=[],i=!1,r=At();for(;;){if(this.skipBlank(),this.peekClose("authoring")){Xn(r)&&this.throwDangling(r),this.takeClose("authoring");break}let c=this.peekSemantic();if(c===null)throw this.eofError("authoring");if(c.record?.type==="extensions"||c.record?.type==="extend"){r=this.addModifier(r,this.takeRecord());continue}if(c.tag?.name==="create"&&!c.tag.closing){if(i)throw D("<create> must precede every target.",c.tag.source,"<create>","Move the single <create> block before the targets.");Xn(r)&&this.throwUnsupportedModifiers(r,"create"),n.push(...this.parseCreate()),i=!0;continue}i=!0,o.push(this.parseTarget(r)),r=At()}if(this.skipBlank(),this.index<this.lines.length){let c={line:this.index+1,column:1};throw D("Content exists after </authoring>.",c,this.lines[this.index],"Remove content outside the root block.")}if(o.length===0)throw D("Authoring file has no target.",t.source,"<authoring>","Add one or more homogeneous target blocks.");let s=o[0].kind,a=o.find(c=>c.kind!==s);if(a!==void 0)throw D("Authoring targets are not homogeneous.",a.source,a.kind,`Keep only ${s} targets in this file.`);if(s==="script"&&o.length!==1)throw D("A script authoring file has exactly one target.",o[1].source,"second <script>","Keep one <script> target.");return{version:1,declarations:n,targets:o,targetKind:s}}parseCreate(){let t=this.takeOpen("create");Mn(t,[]);let n=[],o=At();for(;;){if(this.skipBlank(),this.peekClose("create"))return Xn(o)&&this.throwDangling(o),this.takeClose("create"),n;let i=this.takeRecord();if(i.type==="extensions"||i.type==="extend"||i.type==="aliases"||i.type==="alias"||i.type==="prompt"){o=this.addModifier(o,i);continue}if(i.type==="actor"){if(i.slots.length<3||i.slots.length>4)throw D("Actor declaration slots are invalid.",i.source,i.slots.join("|"),"Use [actor|id|name|importance|role?] description.");let[r,s,a,c]=i.slots;if(!r||!s||!a||!$t.has(a)||!hm(a))throw D("Actor declaration is invalid.",i.source,i.slots.join("|"),"Provide id, name, and featured|background importance.");if(c!==void 0&&(!_o.has(c)||!d5(c)))throw D("Actor role is invalid.",i.source,c,"Use \u4E3B\u89D2 or \u914D\u89D2, or omit the slot.");let d={actor_id:r,actor_name:s,importance:a,description:i.content,states:[]};c!==void 0&&(d.role_type=c),o.aliasesPresent&&(d.aliases=[...o.aliases]);let p=kt(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=At();continue}if(i.type==="location"||i.type==="prop"){if(i.slots.length!==3)throw D(`${i.type} declaration slots are invalid.`,i.source,i.slots.join("|"),`Use [${i.type}|id|name|importance] description.`);let[r,s,a]=i.slots;if(!r||!s||!a||!$t.has(a)||!hm(a))throw D(`${i.type} declaration is invalid.`,i.source,i.slots.join("|"),"Provide id, name, and featured|background importance.");o.prompt!==void 0&&this.throwUnsupportedModifiers(o,i.type);let c=kt(o);if(i.type==="location"){let d={location_id:r,location_name:s,importance:a,description:i.content,states:[]};o.aliasesPresent&&(d.aliases=[...o.aliases]),c!==void 0&&(d.extend=c),n.push({declarationKind:"location",value:d,source:i.source})}else{let d={prop_id:r,prop_name:s,importance:a,description:i.content,states:[]};o.aliasesPresent&&(d.aliases=[...o.aliases]),c!==void 0&&(d.extend=c),n.push({declarationKind:"prop",value:d,source:i.source})}o=At();continue}if(i.type==="state"){if(i.slots.length!==3)throw D("State declaration slots are invalid.",i.source,i.slots.join("|"),"Use [state|kind:asset_id|state_id|state_name] description.");(o.aliasesPresent||o.prompt!==void 0)&&this.throwUnsupportedModifiers(o,"state");let[r,s,a]=i.slots,c=/^(actor|location|prop):(.+)$/.exec(r??""),d=c?.[1]??"";if(!c||!l5(d)||!s||!a)throw D("State declaration is invalid.",i.source,i.slots.join("|"),"Use a typed owner and non-empty state ID/name.");let p={state_id:s,state_name:a,description:i.content},l=kt(o);l!==void 0&&(p.extend=l),n.push({declarationKind:"state",ownerKind:d,ownerId:c[2],value:p,source:i.source}),o=At();continue}throw D("Record is not allowed in <create>.",i.source,i.type,"Use actor, location, prop, state, or a supported prefix modifier.")}}parseTarget(t){let n=this.peekTag();if(n===null||n.closing){let o=n?.source??{line:this.index+1,column:1};throw D("Expected a target block.",o,this.lines[this.index]??"<eof>","Add a supported target block.")}switch((t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,n.name),n.name){case"script":return this.parseScript(t);case"episode":return{kind:"episode",value:this.parseEpisode(t),source:n.source,...kt(t)?{extend:kt(t)}:{}};case"episode-span":return this.parseEpisodeSpan(t);case"scene":return Mn(n,["id","parent"]),{kind:"scene",parent:n.attrs.get("parent"),value:this.parseScene(t,!0),source:n.source,...kt(t)?{extend:kt(t)}:{}};case"scene-span":return this.parseSceneSpan(t);case"action-span":return this.parseActionSpan(t);default:throw D("Unknown target block.",n.source,n.name,"Use script, episode, episode-span, scene, scene-span, or action-span.")}}parseScript(t){let n=this.takeOpen("script");Mn(n,[]);let o=["title","worldview","worldview-raw","style","synopsis","logline","theme","main-characters","main-character"],i=new Map,r=[],s=[],a=-1,c=!1,d=At();for(;;){if(this.skipBlank(),this.peekClose("script")){Xn(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}Xn(d)&&this.throwUnsupportedModifiers(d,m.type);let g=o.indexOf(m.type),w=m.type==="main-character";if(c||g<0||g<a||!w&&i.has(m.type))throw D("Metadata record in <script> is invalid or out of order.",m.source,m.type,`Use ${o.join(", ")} in canonical order before episode blocks.`);if(a=g,m.type==="main-characters"){if(m.slots.length!==0||m.content!=="")throw D("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 D("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 D("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 D("Unexpected member in <script>.",m,this.lines[this.index]??"<eof>","Use metadata records followed by <episode> blocks.")}c=!0,s.push(this.parseEpisode(d)),d=At()}let p=this.requiredMetadata(i,"title",n.source),l=this.requiredMetadata(i,"worldview",n.source),f=this.requiredMetadata(i,"style",n.source),u=kt(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");Mn(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=kt(t);return r!==void 0&&(i.extend=r),i}parseScene(t,n){let o=this.takeOpen("scene");Mn(o,n?["id","parent"]:["id"]),(t.aliasesPresent||t.prompt!==void 0)&&this.throwUnsupportedModifiers(t,"scene");let i,r,s=[],a=[],c="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(c==="body")throw D("Scene has more than one body.",f.tag.source,"<body>","Keep exactly one <body>.");c="body",d=this.parseBody();continue}if(f?.record===void 0){let h=f?.tag?.source??{line:this.index+1,column:1};throw D("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 D("Scene prefix modifier must directly precede <scene>.",u.source,u.type,"Move the modifier before the <scene> opening tag.");if(u.type==="environment"){if(c!=="environment"||i!==void 0||u.slots.length>2)throw D("Environment record is out of order or invalid.",u.source,u.slots.join("|"),"Place at most one [environment|space?|time?] first.");i={},u.slots.length>=1&&u.slots[0]!==""&&(i.space=u.slots[0]),u.slots.length>=2&&u.slots[1]!==""&&(i.time=u.slots[1]);continue}if(u.type==="location"){if(c==="cast"||c==="prop"||c==="body"||r!==void 0||u.slots.length>2)throw D("Location record is out of order or invalid.",u.source,u.slots.join("|"),"Place exactly one [location|id?|state?] before cast.");c="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||c==="prop"||c==="body"||u.slots.length<1||u.slots.length>2||!u.slots[0])throw D("Cast record is out of order or invalid.",u.source,u.slots.join("|"),"Place [cast|actor_id|state_id?] after location and before props.");c="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||c==="body"||u.slots.length<1||u.slots.length>2||!u.slots[0])throw D("Prop record is out of order or invalid.",u.source,u.slots.join("|"),"Place [prop|prop_id|state_id?] after cast and before body.");c="prop",a.push(u.slots.length===2?{prop_id:u.slots[0],state_id:u.slots[1]}:{prop_id:u.slots[0]});continue}throw D("Record is not allowed in a scene header.",u.source,u.type,"Use environment, location, cast, prop, or body records.")}if(r===void 0)throw D("Scene location record is missing.",o.source,`<scene id=${o.attrs.get("id")}>`,"Add [location] or [location|loc_ID|state_ID].");if(d===void 0)throw D("Scene body is missing.",o.source,`<scene id=${o.attrs.get("id")}>`,"Add one <body> block.");let p={scene_id:o.attrs.get("id"),location:r,actors:s,props:a,actions:d};i!==void 0&&(p.environment=i);let l=kt(t);return l!==void 0&&(p.extend=l),p}parseBody(){let t=this.takeOpen("body");Mn(t,[]);let n=[],o=At();for(;;){if(this.skipBlank(),this.peekClose("body"))return Xn(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(m5(i,o)),o=At()}}parseEpisodeSpan(t){let n=this.takeOpen("episode-span");Mn(n,["from","through"]);let o=this.parseOnlyChildren("episode-span","episode",r=>this.parseEpisode(r)),i=kt(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");Mn(n,["parent","from","through"]);let o=this.parseOnlyChildren("scene-span","scene",r=>this.parseScene(r,!1)),i=kt(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");Mn(n,["parent","from","through"]),this.skipBlank();let o=this.parseBody();this.skipBlank(),this.takeClose("action-span");let i=kt(t);return{kind:"action-span",parent:n.attrs.get("parent"),from:ym(n.attrs.get("from"),n.source,"action-span from",!0),through:ym(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=[],a=-1,c=!1,d=At();for(;;){if(this.skipBlank(),this.peekClose(t))return Xn(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}Xn(d)&&this.throwUnsupportedModifiers(d,f.type);let u=n.indexOf(f.type);if(c||u<0||u<a||r.has(f.type)||f.slots.length!==0)throw D(`Metadata record in <${t}> is invalid or out of order.`,f.source,f.type,`Use each of ${n.join(", ")} at most once in canonical order before child blocks.`);a=u,r.set(f.type,f.content);continue}let l=p?.tag;if(l===void 0||l.closing||l.name!==o){let f=l?.source??{line:this.index+1,column:1};throw D(`Unexpected member in <${t}>.`,f,this.lines[this.index]??"<eof>",`Use metadata records followed by <${o}> blocks.`)}c=!0,s.push(i(d)),d=At()}}parseOnlyChildren(t,n,o){let i=[],r=At();for(;;){if(this.skipBlank(),this.peekClose(t))return Xn(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 a=s?.tag?.source??s?.record?.source??{line:this.index+1,column:1};throw D(`Only <${n}> children are allowed in <${t}>.`,a,this.lines[this.index]??"<eof>",`Add complete <${n}> blocks.`)}i.push(o(r)),r=At()}}addModifier(t,n){let o={extend:{...t.extend},extendPresent:t.extendPresent,aliases:[...t.aliases],aliasesPresent:t.aliasesPresent,phase:t.phase,...t.prompt!==void 0?{prompt:t.prompt}:{},source:t.source??n.source};if(n.type==="extensions"){if(o.phase!=="extend"||o.extendPresent||n.slots.length!==0||n.content!=="")throw D("Extensions marker is invalid or out of order.",n.source,n.content||"<empty>","Use one [extensions] marker before extension records.");return o.extendPresent=!0,o}if(n.type==="extend"){if(o.phase!=="extend"||n.slots.length!==1||!n.slots[0])throw D("Extend modifier is invalid or out of order.",n.source,n.slots.join("|"),"Place unique [extend|key] records first.");let i=n.slots[0];if(Object.hasOwn(o.extend,i))throw D("Extend key is duplicated.",n.source,i,"Keep one value for each extension key.");let r;try{r=JSON.parse(n.content)}catch{throw D("Extension value is not valid JSON.",n.source,n.content,"Use one canonical JSON value.")}if(!Yd(r))throw D("Extension value is not JSON-compatible.",n.source,n.content,"Use string, number, boolean, null, array, or object.");return o.extendPresent=!0,o.extend[i]=qd(r),o}if(n.type==="aliases"){if(o.phase!=="extend"||o.aliasesPresent||n.slots.length!==0||n.content!=="")throw D("Aliases marker is invalid or out of order.",n.source,n.content||"<empty>","Use one [aliases] marker after extensions and before alias records.");return o.phase="alias",o.aliasesPresent=!0,o}if(n.type==="alias"){if(o.phase==="prompt"||n.slots.length!==0||!n.content)throw D("Alias modifier is invalid or out of order.",n.source,n.content||"<empty>","Place non-empty [alias] records after extensions and before prompt.");if(o.phase="alias",o.aliasesPresent=!0,o.aliases.includes(n.content))throw D("Alias is duplicated.",n.source,n.content,"Keep each alias once.");return o.aliases.push(n.content),o}if(n.type==="prompt"){if(o.prompt!==void 0||n.slots.length!==3||n.slots.some(i=>!i))throw D("Prompt modifier is invalid.",n.source,n.slots.join("|"),"Use one [prompt|target|process|contrast] after extensions and aliases.");if(!/^(?:actor:act_|location:loc_|prop:prp_)[A-Za-z0-9_-]+$/.test(n.slots[0]))throw D("Prompt target is invalid.",n.source,n.slots[0],"Use actor:act_ID, location:loc_ID, or prop:prp_ID.");return o.phase="prompt",o.prompt={target:n.slots[0],process:n.slots[1],contrast:n.slots[2]},o}throw D("Unknown prefix modifier.",n.source,n.type,"Use extend, alias, or prompt.")}requiredMetadata(t,n,o){let i=t.get(n);if(i===void 0)throw D(`Script ${n} record is missing.`,o,"<script>",`Add [${n}] in canonical metadata order.`);return i}peekSemantic(){if(this.skipBlank(),this.index>=this.lines.length)return null;let t=this.lines[this.index],n=u5(t,this.index+1);if(n!==null)return{tag:n};if(t.trimStart().startsWith("["))return{record:ir(t,this.index+1)};let o={line:this.index+1,column:Math.max(1,t.search(/\S/)+1)};throw D("Semantic line is neither a tag nor a bracket record.",o,t,"Use only known tags, bracket records, or blank lines.")}peekTag(){return this.peekSemantic()?.tag??null}takeRecord(){let t=this.peekSemantic();if(t?.record===void 0){let n=t?.tag?.source??{line:this.index+1,column:1};throw D("Expected a bracket record.",n,this.lines[this.index]??"<eof>","Use the record required at this position.")}return this.index+=1,t.record}takeOpen(t){let n=this.peekTag();if(n===null||n.closing||n.name!==t){let o=n?.source??{line:this.index+1,column:1};throw D(`Expected <${t}>.`,o,this.lines[this.index]??"<eof>",`Open <${t}> here.`)}return this.index+=1,n}takeClose(t){let n=this.peekTag();if(n===null||!n.closing||n.name!==t){let o=n?.source??{line:this.index+1,column:1};throw D(`Expected </${t}>.`,o,this.lines[this.index]??"<eof>",`Close the current <${t}> block.`)}return this.index+=1,n}peekClose(t){let n=this.peekTag();return n!==null&&n.closing&&n.name===t}skipBlank(){for(;this.index<this.lines.length&&this.lines[this.index].trim()==="";)this.index+=1}eofError(t){return D(`Unexpected end of file inside <${t}>.`,{line:this.lines.length,column:1},"<eof>",`Add </${t}>.`)}throwDangling(t){throw D("Prefix modifier has no following node.",t.source??{line:this.index+1,column:1},"dangling modifier","Move it directly before a supported node.")}throwUnsupportedModifiers(t,n){throw D("Prefix modifier does not apply to this node.",t.source??{line:this.index+1,column:1},n,"Remove the unsupported modifier or move it before a supported node.")}};function wm(e){return new Wd(e).parse()}function L(e,t,n){throw new S(e,{exitCode:k,errorCode:"AUTHORING_SOURCE_INVALID",data:{actual:[`line ${t}: ${n}`]}})}function tp(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]??"",a=s===""?[]:s.split(" ");a.some(c=>c==="")&&L("Tag attributes need one-space separators.",t,n);for(let c of a){let d=/^([a-z]+)=([A-Za-z0-9_./#:-]+)$/.exec(c);(!d||r.has(d[1]))&&L("Tag attributes are invalid.",t,c),r.set(d[1],d[2])}return{name:i[1],closing:!1,attrs:r,line:t}}function Be(e,t,n=[]){let o=new Set([...t,...n]),i=[...e.attrs.keys()].filter(s=>!o.has(s)),r=t.filter(s=>!e.attrs.has(s));(i.length>0||r.length>0)&&L("Tag attributes do not match the canonical grammar.",e.line,[...r.map(s=>`missing:${s}`),...i.map(s=>`unknown:${s}`)].join(","))}var np=class{lines;index=0;constructor(t){this.lines=t.split(/\r?\n/).map((n,o)=>({raw:n.replace(/^\s+/,""),line:o+1})).filter(n=>n.raw.trim()!=="")}peek(){let t=this.lines[this.index];return t||L("Unexpected end of authoring file.",this.lines.at(-1)?.line??1,"<eof>"),t}take(){let t=this.peek();return this.index++,t}tag(t,n){let o=this.take(),i=tp(o.raw,o.line);return(!i||i.name!==t||i.closing!==n)&&L(`Expected ${n?"</":"<"}${t}>.`,o.line,o.raw),i}record(){let t=this.take();return ir(t.raw,t.line)}nextTag(){let t=this.peek();return tp(t.raw,t.line)}nextRecord(){let t=this.peek();return t.raw.startsWith("[")?ir(t.raw,t.line):null}};function op(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"?!0:Array.isArray(e)?e.every(op):typeof e=="object"&&Object.values(e).every(op)}function fi(e){let t={},n=e.nextRecord();if(n?.type==="extensions"){e.record();let o={},i=null;for(;(n=e.nextRecord())?.type==="extend";){let r=e.record();(r.slots.length!==1||Object.hasOwn(o,r.slots[0]))&&L("extend record is invalid or duplicated.",r.source.line,r.type);let s=r.slots[0];i!==null&&i>=s&&L("extend keys must use ascending canonical order.",r.source.line,s);let a;try{a=JSON.parse(r.content)}catch{L("extend content must be JSON.",r.source.line,r.content)}op(a)||L("extend value must be JSON-compatible.",r.source.line,r.content),o[s]=a,i=s}t.extend=o}if(n=e.nextRecord(),n?.type==="aliases"){e.record();let o=[];for(;(n=e.nextRecord())?.type==="alias";){let i=e.record();i.slots.length!==0&&L("alias takes no slots.",i.source.line,i.type),i.content===""&&L("alias must not be empty.",i.source.line,i.type),o.includes(i.content)&&L("alias must not be duplicated.",i.source.line,i.content),o.push(i.content)}t.aliases=o}if(n=e.nextRecord(),n?.type==="prompt"){let o=e.record();(o.slots.length!==3||o.slots.some(r=>r===""))&&L("prompt requires non-empty target, process, and contrast.",o.source.line,o.type);let i=o.slots[0];!$("actor",i)&&!$("location",i)&&!$("prop",i)&&L("prompt target must be an asset ID.",o.source.line,i),t.prompt={target:i,process:o.slots[1],contrast:o.slots[2]}}return t}function Zd(e,t){return e!=="featured"&&e!=="background"&&L("Importance is invalid.",t,e),e}function g5(e,t){if(e!==void 0)return e!=="\u4E3B\u89D2"&&e!=="\u914D\u89D2"&&L("Role type is invalid.",t,e),e}function sp(e,t){return e==="default"||$("state",e)?e:L("State ID is invalid.",t,e)}function h5(e){let t=e.tag("create",!1);Be(t,[]);let n=[],o=new Map,i=null,r=0,s=c=>{if(i===null)return;let d=o.get(i);(!d||d.states.length===0||d.states[0].state_id!=="default")&&L("A new asset must be followed immediately by its default state.",c,i),i=null};for(;e.nextTag()?.name!=="create"||e.nextTag()?.closing!==!0;){let c=fi(e),d=e.record();if(d.type==="actor"){r>0&&L("Create declarations are not in canonical order.",d.source.line,d.type),s(d.source.line),c.prompt!==void 0&&L("prompt cannot modify an asset.",d.source.line,d.type),(d.slots.length<3||d.slots.length>4||!$("actor",d.slots[0]))&&L("actor declaration is invalid.",d.source.line,d.type);let p=g5(d.slots[3],d.source.line),l={actor_id:d.slots[0],actor_name:d.slots[1],importance:Zd(d.slots[2],d.source.line),description:d.content,states:[],...p===void 0?{}:{role_type:p},...c.aliases===void 0?{}:{aliases:c.aliases},...c.extend===void 0?{}:{extend:c.extend}};l.aliases?.includes(l.actor_name)&&L("An alias must differ from the asset name.",d.source.line,l.actor_name),n.push({kind:"actor",value:l}),o.set(l.actor_id,l),i=l.actor_id}else if(d.type==="location"||d.type==="prop"){let p=d.type==="location"?1:2;p<r&&L("Create declarations are not in canonical order.",d.source.line,d.type),r=p,s(d.source.line),c.prompt!==void 0&&L("prompt cannot modify an asset.",d.source.line,d.type);let l=d.type;if((d.slots.length!==3||(l==="location"?!$("location",d.slots[0]):!$("prop",d.slots[0])))&&L(`${l} declaration is invalid.`,d.source.line,d.type),l==="location"){let f=d.slots[0];$("location",f)||L("location ID is invalid.",d.source.line,f);let u={location_id:f,location_name:d.slots[1],importance:Zd(d.slots[2],d.source.line),description:d.content,states:[],...c.aliases===void 0?{}:{aliases:c.aliases},...c.extend===void 0?{}:{extend:c.extend}};u.aliases?.includes(u.location_name)&&L("An alias must differ from the asset name.",d.source.line,u.location_name),n.push({kind:l,value:u}),o.set(u.location_id,u),i=u.location_id}else{let f=d.slots[0];$("prop",f)||L("prop ID is invalid.",d.source.line,f);let u={prop_id:f,prop_name:d.slots[1],importance:Zd(d.slots[2],d.source.line),description:d.content,states:[],...c.aliases===void 0?{}:{aliases:c.aliases},...c.extend===void 0?{}:{extend:c.extend}};u.aliases?.includes(u.prop_name)&&L("An alias must differ from the asset name.",d.source.line,u.prop_name),n.push({kind:l,value:u}),o.set(u.prop_id,u),i=u.prop_id}}else if(d.type==="state"){(d.slots.length!==3||c.aliases!==void 0||c.prompt!==void 0)&&L("state declaration is invalid.",d.source.line,d.type);let p=d.slots[0],l=o.get(p);l&&i!==p&&L("States for a new asset must immediately follow that asset.",d.source.line,p),l||(s(d.source.line),r=3);let f={state_id:sp(d.slots[1],d.source.line),state_name:d.slots[2],description:d.content,...c.extend===void 0?{}:{extend:c.extend}};l?(l.states.length===0&&f.state_id!=="default"&&L("The first state of a new asset must be default.",d.source.line,f.state_id),l.states.push(f)):n.push({kind:"state",ownerId:p,value:f})}else s(d.source.line),L("Unknown create declaration.",d.source.line,d.type)}s(e.peek().line);let a=e.tag("create",!0);return Be(a,[]),n}function y5(e,t){let n=e.indexOf("/"),o=n<0?e:e.slice(0,n);if($("actor",o))return n<0?{actor_id:o}:{actor_id:o,state_id:sp(e.slice(n+1),t)};let i=e.indexOf(":"),r=i<0?e:e.slice(0,i);return["system","broadcast","offscreen","group"].includes(r)?i<0?{kind:r}:{kind:r,label:e.slice(i+1)}:L("Speaker is invalid.",t,e)}function xm(e){let t=fi(e);t.aliases!==void 0&&L("aliases cannot modify an Action.",e.peek().line,"aliases");let n=e.record();return n.type==="act"||n.type==="trans"?((n.slots.length!==1||!$("action",n.slots[0]))&&L("Narrative Action record is invalid.",n.source.line,n.type),{action_id:n.slots[0],type:n.type==="act"?"action":"transition",content:n.content,...t.extend===void 0?{}:{extend:t.extend},...t.prompt===void 0?{}:{transition_prompt:t.prompt}}):n.type!=="dlg"&&n.type!=="think"?L("Unknown Action record.",n.source.line,n.type):((n.slots.length!==2&&n.slots.length!==3||!$("action",n.slots[0]))&&L("Speaking Action record is invalid.",n.source.line,n.type),{action_id:n.slots[0],type:n.type==="dlg"?"dialogue":"inner_thought",speaker:y5(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 Xd(e,t){e.length===0&&L("Scene reference needs at least one state.",t,"<empty>");let n=e.map(o=>sp(o,t));return new Set(n).size!==n.length&&L("Scene reference repeats a state.",t,n.join(",")),n.sort()}function ip(e,t,n,o){Be(t,n===void 0?["id","parent"]:["id"]);let i=t.attrs.get("id")??"";$("scene",i)||L("Scene ID is invalid.",t.line,i);let r=t.attrs.get("parent")??n;r!==void 0&&!$("episode",r)&&L("Scene parent must be an Episode ID.",t.line,r);let s,a,c=[],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&&L("Scene records are not in canonical order.",m.source.line,m.type),f=g,m.type==="environment"?(s!==void 0&&L("Scene environment is duplicated.",m.source.line,m.type),m.slots.length>2&&L("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"?(a!==void 0&&L("Scene location is duplicated.",m.source.line,m.type),m.slots.length===0?a=null:($("location",m.slots[0])||L("Location ref ID is invalid.",m.source.line,m.slots[0]),a={location_id:m.slots[0],state_ids:Xd(m.slots.slice(1),m.source.line)})):m.type==="cast"?($("actor",m.slots[0])||L("Cast ref ID is invalid.",m.source.line,m.slots[0]??""),p.has(m.slots[0])&&L("Scene repeats an actor reference.",m.source.line,m.slots[0]),p.add(m.slots[0]),c.push({actor_id:m.slots[0],state_ids:Xd(m.slots.slice(1),m.source.line)})):m.type==="prop"?($("prop",m.slots[0])||L("Prop ref ID is invalid.",m.source.line,m.slots[0]??""),l.has(m.slots[0])&&L("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:Xd(m.slots.slice(1),m.source.line)})):L("Unknown scene header record.",m.source.line,m.type)}a===void 0&&L("Scene must declare location or [location].",e.peek().line,i);let u=e.tag("body",!1);Be(u,[]);let h=[];for(;e.nextTag()?.name!=="body"||e.nextTag()?.closing!==!0;)h.push(xm(e));return Be(e.tag("body",!0),[]),Be(e.tag("scene",!0),[]),{...r===void 0?{}:{parent:r},value:{scene_id:i,...s===void 0?{}:{environment:s},location:a,actors:c,props:d,actions:h,...o===void 0?{}:{extend:o}}}}function rp(e,t,n){Be(t,["id"]);let o=t.attrs.get("id")??"";$("episode",o)||L("Episode ID is invalid.",t.line,o);let i,r,s=[],a=0;for(;e.nextTag()?.name!=="episode"||e.nextTag()?.closing!==!0;){let c=fi(e);(c.aliases!==void 0||c.prompt!==void 0)&&L("Invalid episode child modifier.",e.peek().line,"modifier");let d=e.nextTag();if(d?.name==="scene"&&!d.closing){a=2,e.take(),s.push(ip(e,d,o,c.extend).value);continue}c.extend!==void 0&&L("extend must precede a scene here.",e.peek().line,"extend");let p=e.record(),l=p.type==="title"?0:p.type==="synopsis"?1:-1;l<a&&L("Episode records are not in canonical order.",p.source.line,p.type),a=l,p.type==="title"?(i!==void 0&&L("Episode title is duplicated.",p.source.line,p.type),p.slots.length!==0&&L("Episode title takes no slots.",p.source.line,p.type),i=p.content):p.type==="synopsis"?(r!==void 0&&L("Episode synopsis is duplicated.",p.source.line,p.type),p.slots.length!==0&&L("Episode synopsis takes no slots.",p.source.line,p.type),r=p.content):L("Unknown episode record.",p.source.line,p.type)}return Be(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 ep(e,t){let n=e.attrs.get("range")??"",o=n.split("..");return(o.length!==2||!o[0]||!o[1]||!$(t,o[0])||!$(t,o[1]))&&L(`Span range must contain two ${t} IDs.`,e.line,n),[o[0],o[1]]}function w5(e,t,n){Be(t,[]);let o,i,r,s,a,c,d,p,l=[],f=0;for(;e.nextTag()?.name!=="script"||e.nextTag()?.closing!==!0;){let u=fi(e);(u.aliases!==void 0||u.prompt!==void 0)&&L("Invalid script child modifier.",e.peek().line,"modifier");let h=e.nextTag();if(h?.name==="episode"&&!h.closing){f=8,e.take(),l.push(rp(e,h,u.extend));continue}u.extend!==void 0&&L("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&&L("Script records are not in canonical order.",m.source.line,m.type),f=g,m.type!=="main-character"&&m.slots.length!==0&&L("Script metadata record takes no slots.",m.source.line,m.type),m.type==="title"?(o!==void 0&&L("Script title is duplicated.",m.source.line,m.type),o=m.content):m.type==="worldview"?(i!==void 0&&L("Script worldview is duplicated.",m.source.line,m.type),i=m.content):m.type==="worldview-raw"?(r!==void 0&&L("Script worldview-raw is duplicated.",m.source.line,m.type),r=m.content):m.type==="style"?(s!==void 0&&L("Script style is duplicated.",m.source.line,m.type),s=m.content):m.type==="synopsis"?(a!==void 0&&L("Script synopsis is duplicated.",m.source.line,m.type),a=m.content):m.type==="logline"?(c!==void 0&&L("Script logline is duplicated.",m.source.line,m.type),c=m.content):m.type==="theme"?(d!==void 0&&L("Script theme is duplicated.",m.source.line,m.type),d=m.content):m.type==="main-characters"?(p!==void 0&&L("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]}):L("Unknown script record.",m.source.line,m.type)}return Be(e.tag("script",!0),[]),(o===void 0||i===void 0||s===void 0)&&L("Script target needs title, worldview, and style.",e.peek().line,"script"),{kind:"script",value:{title:o,worldview:i,style:s,episodes:l,...r===void 0?{}:{worldview_raw:r},...a===void 0?{}:{synopsis:a},...c===void 0?{}:{logline:c},...d===void 0?{}:{theme:d},...p===void 0?{}:{main_characters:p},...n===void 0?{}:{extend:n}}}}function Em(e){let t=new np(e),n=t.tag("authoring",!1);Be(n,["version"]),n.attrs.get("version")!=="1"&&L("authoring version must be 1.",1,n.attrs.get("version")??"<missing>");let o=t.nextTag()?.name==="create"?h5(t):[],i=[];for(;t.nextTag()?.name!=="authoring"||t.nextTag()?.closing!==!0;){let s=fi(t);(s.aliases!==void 0||s.prompt!==void 0)&&L("Invalid target modifier.",t.peek().line,"modifier");let a=t.take(),c=tp(a.raw,a.line);if((!c||c.closing)&&L("Expected an authoring target.",a.line,a.raw),c.name==="script")i.push(w5(t,c,s.extend));else if(c.name==="episode")i.push({kind:"episode",value:rp(t,c,s.extend)});else if(c.name==="scene"){let d=ip(t,c,void 0,s.extend);d.parent||L("Top-level scene needs parent.",a.line,a.raw),i.push({kind:"scene",parent:d.parent,value:d.value})}else if(c.name==="episode-span"){s.extend!==void 0&&L("A span cannot carry node extensions.",a.line,a.raw),Be(c,["range"]);let[d,p]=ep(c,"episode"),l=[];for(;t.nextTag()?.name!=="episode-span"||t.nextTag()?.closing!==!0;){let f=fi(t);(f.aliases!==void 0||f.prompt!==void 0)&&L("Invalid episode child modifier.",t.peek().line,"modifier");let u=t.tag("episode",!1);l.push(rp(t,u,f.extend))}Be(t.tag("episode-span",!0),[]),i.push({kind:"episode-span",from:d,through:p,values:l})}else if(c.name==="scene-span"){s.extend!==void 0&&L("A span cannot carry node extensions.",a.line,a.raw),Be(c,["parent","range"]);let[d,p]=ep(c,"scene"),l=c.attrs.get("parent")??L("scene-span needs parent.",a.line,a.raw);$("episode",l)||L("scene-span parent must be an Episode ID.",a.line,l);let f=[];for(;t.nextTag()?.name!=="scene-span"||t.nextTag()?.closing!==!0;){let u=fi(t);(u.aliases!==void 0||u.prompt!==void 0)&&L("Invalid scene child modifier.",t.peek().line,"modifier");let h=t.tag("scene",!1);f.push(ip(t,h,l,u.extend).value)}Be(t.tag("scene-span",!0),[]),i.push({kind:"scene-span",parent:l,from:d,through:p,values:f})}else if(c.name==="action-span"){s.extend!==void 0&&L("A span cannot carry node extensions.",a.line,a.raw),Be(c,["parent","range"]);let[d,p]=ep(c,"action"),l=c.attrs.get("parent")??L("action-span needs parent.",a.line,a.raw);$("scene",l)||L("action-span parent must be a Scene ID.",a.line,l),Be(t.tag("body",!1),[]);let f=[];for(;t.nextTag()?.name!=="body"||t.nextTag()?.closing!==!0;)f.push(xm(t));Be(t.tag("body",!0),[]),Be(t.tag("action-span",!0),[]),i.push({kind:"action-span",parent:l,from:d,through:p,values:f})}else L("Unknown authoring target.",a.line,c.name)}Be(t.tag("authoring",!0),[]),(t.index!==t.lines.length||i.length===0)&&L("Authoring file has trailing content or no targets.",t.peek().line,"<root>");let r=i[0].kind;return i.every(s=>s.kind===r)||L("All targets must have the same kind.",1,r),{declarations:o,targets:i,targetKind:r}}function Nn(e){if(Array.isArray(e))return e.map(t=>Nn(t));if(ie(e)){let t={};for(let n of Object.keys(e).sort())t[n]=Nn(e[n]);return t}return e}function ap(e){if(e.length===0)return[];let t={};for(let i of e){let r=O(i.severity);t[r]=(t[r]??0)+1}let n=Object.entries(t).sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>`${i}: ${r}`),o=e[0];return[n.join("; "),`first: ${o.code} - ${o.summary}`,...o.repair_hint?[`repair: ${o.repair_hint}`]:[]]}function _m(e,t){if(!(t.ok||e!==null&&xd(Te(e),t)))throw new S("The proposed document is not a valid or strictly improved Script v4.",{exitCode:k,errorCode:"AUTHORING_VALIDATION_FAILED",data:{actual:t.errors.slice(0,20).map(n=>`${n.path}: ${n.message}`)}})}function Ve(e,t){throw new S(e,{exitCode:k,errorCode:"AUTHORING_APPLY_INVALID",data:{actual:t}})}function dp(e){return{ids:e.map(t=>t.action_id),counts:{episodes:0,scenes:0,actions:e.length}}}function rr(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 Mo(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 x5(e){return e.kind==="script"?Mo(e.value.episodes):e.kind==="episode"?Mo([e.value]):e.kind==="episode-span"?Mo(e.values):e.kind==="scene"?rr([e.value]):e.kind==="scene-span"?rr(e.values):dp(e.values)}function E5(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 cp(e,t){return JSON.stringify(Nn(e))===JSON.stringify(Nn(t))}function Sm(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=[],a=[],c=d=>{(o.has(d)?a:s).push(d)};for(let d of t){if(d.kind==="state"){n.has(d.ownerId)&&r.push(d.ownerId),c(`${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=>{c(`${p}/${l.state_id}`)})}return{createdAssets:i,existingAssets:[...new Set(r)],createdStates:s,existingStates:a}}function Im(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 Am(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 km(e,t){let n=e===null?[]:Am(e),o=Am(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 _5(e,t){for(let n of t)if(n.kind==="actor")e.actors.some(o=>o.actor_id===n.value.actor_id)&&Ve("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)&&Ve("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)&&Ve("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||Ve("State declaration owner was not found.",[n.ownerId]),o.states.some(i=>i.state_id===n.value.state_id)&&Ve("State declaration cannot redefine an existing state.",[`${n.ownerId}/${n.value.state_id}`]),o.states.push(structuredClone(n.value))}}function on(e,t,n){let o=e.indexOf(t),i=e.indexOf(n);return(o<0||i<0)&&Ve("Span endpoint was not found.",[t,n]),[Math.min(o,i),Math.max(o,i)]}function S5(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"?on(o,t.value.episode_id,t.value.episode_id):on(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"?on(o,t.value.scene_id,t.value.scene_id):on(o,t.from,t.through)}let n=e.episodes.flatMap(o=>o.scenes.flatMap(i=>i.actions.map(r=>r.action_id)));return on(n,t.from,t.through)}function I5(e,t){let n=-1;for(let o of t){let[i,r]=S5(e,o);i<=n&&Ve("Replace targets must follow current document order without overlap.",[Rm(o)]),n=r}}function Rm(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 bm(e,t){if(t.kind==="script")return{...Mo(e.episodes),siblings:0};if(t.kind==="episode"){let r=On(e,t.value.episode_id);return{...Mo(r?[r.episode]:[]),siblings:Math.max(0,e.episodes.length-(r?1:0))}}if(t.kind==="episode-span"){let[r,s]=on(e.episodes.map(a=>a.episode_id),t.from,t.through);return{...Mo(e.episodes.slice(r,s+1)),siblings:e.episodes.length-(s-r+1)}}if(t.kind==="scene"){let r=Zn(e,t.value.scene_id),s=On(e,t.parent)?.episode;return{...rr(r?[r.scene]:[]),siblings:r?Math.max(0,r.episode.scenes.length-1):s?.scenes.length??0}}if(t.kind==="scene-span"){let r=On(e,t.parent)?.episode;if(!r)return{...rr([]),siblings:0};let[s,a]=on(r.scenes.map(c=>c.scene_id),t.from,t.through);return{...rr(r.scenes.slice(s,a+1)),siblings:r.scenes.length-(a-s+1)}}let n=Zn(e,t.parent)?.scene;if(!n)return{...dp([]),siblings:0};let[o,i]=on(n.actions.map(r=>r.action_id),t.from,t.through);return{...dp(n.actions.slice(o,i+1)),siblings:n.actions.length-(i-o+1)}}function vm(e,t){let n=x5(e),o=new Set(t.ids),i=new Set(n.ids);return{kind:e.kind,address:Rm(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 A5(e,t){if(t.kind==="script"&&Ve("An existing Script v4 is not replaced through a script root.",["script"]),t.kind==="episode"){let n=On(e,t.value.episode_id);n||Ve("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]=on(e.episodes.map(i=>i.episode_id),t.from,t.through);t.values.length===0&&Ve("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=Zn(e,t.value.scene_id);(!n||n.episode.episode_id!==t.parent)&&Ve("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=On(e,t.parent)?.episode;n||Ve("Scene span parent was not found.",[t.parent]);let[o,i]=on(n.scenes.map(r=>r.scene_id),t.from,t.through);t.values.length===0&&Ve("Scene span replacement cannot be empty.",[t.from,t.through]),n.scenes.splice(o,i-o+1,...structuredClone(t.values))}else{let n=Zn(e,t.parent)?.scene;n||Ve("Action span parent was not found.",[t.parent]);let[o,i]=on(n.actions.map(r=>r.action_id),t.from,t.through);t.values.length===0&&Ve("Action span replacement cannot be empty.",[t.from,t.through]),n.actions.splice(o,i-o+1,...structuredClone(t.values))}}function k5(e,t){if(t.kind==="episode")e.episodes.push(structuredClone(t.value));else if(t.kind==="scene"){let n=On(e,t.parent)?.episode;n||Ve("Scene create parent was not found.",[t.parent]),n.scenes.push(structuredClone(t.value))}else Ve("This target kind does not support create against an existing script.",[t.kind])}function Om(e){if(e.targets.length!==1||e.targets[0].kind!=="script")return Ve("Script create requires exactly one script target.",[e.targetKind]);if(e.declarations.some(n=>n.kind==="state"))return Ve("Standalone state declarations need an existing owner.",["state"]);let t=e.targets[0];return{version:4,...structuredClone(t.value),...E5(e.declarations)}}function Mm(e,t,n){let o;if(e===null)n!=="create"&&Ve("A missing target requires one script create target.",[n,t.targetKind]),o=Om(t);else if(n==="create"&&t.targetKind==="script")o=Om(t),cp(o,e)||Ve("Script create retry differs from the existing script.",["script"]);else{o=structuredClone(e),n==="replace"&&I5(e,t.targets),_5(o,t.declarations);let r=t.targets.map(c=>bm(e,c));if(n==="replace")for(let c of[...t.targets].reverse())A5(o,c);else for(let c of t.targets)k5(o,c);let s=t.targets.map((c,d)=>vm(c,r[d])),a=Te(o);return _m(e,a),{script:o,changed:!cp(e,o),validation:a,targets:s,declarations:Sm(e,t.declarations),retainedOrphanAssets:Im(o),identity:km(e,o)}}let i=Te(o);return _m(e,i),{script:o,changed:e===null||!cp(e,o),validation:i,declarations:Sm(e,t.declarations),retainedOrphanAssets:Im(o),identity:km(e,o),targets:t.targets.map(r=>{let s=e===null?{...Mo([]),siblings:0}:bm(e,r);return vm(r,s)})}}function mi(e,t){throw new S(e,{exitCode:B,errorCode:"AUTHORING_USAGE_INVALID",hint:"Choose exactly one mode and pass a regular authoring source file.",data:{expected:["scriptctl authoring write <file> (--create|--replace) [--apply --plan <digest>]"],actual:t}})}function b5(e){(!e||e==="-")&&mi("Authoring input must be a named file.",[e||"<missing>"]);let t=Nm.resolve(e),n;try{n=cs.statSync(t)}catch{throw new S("The authoring source file does not exist.",{exitCode:k,errorCode:"AUTHORING_SOURCE_UNAVAILABLE",hint:"Write the complete authoring draft to a file, then rerun the command.",data:{actual:[t]}})}n.isFile()||mi("Authoring input must be a regular file.",[t]);let o=cs.readFileSync(t);return{absolutePath:t,bytes:o,text:o.toString("utf-8")}}function v5(e){let t=Zr(e);if(t===null)return{script:null,baseline:"missing",fingerprint:t};let n;try{n=JSON.parse(cs.readFileSync(e,"utf-8"))}catch(i){throw new S("The local script is not valid JSON.",{exitCode:k,errorCode:"SCRIPT_JSON_INVALID",hint:"Repair the local JSON file, then rerun authoring.",data:{actual:[e,i instanceof Error?i.message:String(i)]}})}let o=ya(n);return{script:o,baseline:je(o),fingerprint:t}}function O5(e){let t=e.create===!0,n=e.replace===!0;return t===n&&mi("Choose exactly one authoring mode.",[`create=${t}`,`replace=${n}`]),t?"create":"replace"}function Lm(e){return`sha256:${_e(JSON.stringify(e))}`}function R5(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 M5(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 N5(e,t,n,o,i){let r=Em(t.text),s=i.script===null?null:vn(i.script),a=Mm(s,r,n),c=`sha256:${pp.createHash("sha256").update(t.bytes).digest("hex")}`,d={version:1,sourceDigest:c,mode:n,targetKind:r.targetKind,targets:a.targets.map(g=>g.address),baseline:i.baseline,plan:{targets:a.targets,declarations:a.declarations,retainedOrphanAssets:a.retainedOrphanAssets,identity:a.identity,validation:a.validation}},p=Lm(d),l=e.apply===!0,f=O(e.plan).trim();if(l&&!f&&mi("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!l&&f&&mi("--plan is only valid together with --apply.",[`plan=${f}`]),l&&f!==p)throw new S("The supplied plan does not match the current source, mode, targets, or script baseline.",{exitCode:k,errorCode:"AUTHORING_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[p],actual:[f]}});l&&a.changed&&(i.script===null?Xr(o,i.fingerprint):Kt(o,i.baseline),We(o,a.script));let u=a.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(a.declarations.createdAssets)}`,`existing_assets=${JSON.stringify(a.declarations.existingAssets)}`,`created_states=${JSON.stringify(a.declarations.createdStates)}`,`existing_states=${JSON.stringify(a.declarations.existingStates)}`,`retained_orphan_assets=${JSON.stringify(a.retainedOrphanAssets)}`,`created_ids=${JSON.stringify(a.identity.createdIds)}`,`removed_ids=${JSON.stringify(a.identity.removedIds)}`,`retained_ids=${JSON.stringify(a.identity.retainedIds)}`),[{text:[`${l?"Applied":"Planned"} ${a.targets.length} ${r.targetKind} target(s); validation ${a.validation.ok?"passed":"needs repair"}`,`plan: ${p}`,...u].join(`
|
|
132
|
+
`),data:{op:"write",changed:a.changed,source_path:t.absolutePath,source_digest:c,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:a.targets,declarations:a.declarations,retained_orphan_assets:a.retainedOrphanAssets,identity:a.identity,validation:a.validation,applied:l,script_version:4}},V]}function Um(e){let t=Array.isArray(e._args)?e._args:[],n=typeof t[0]=="string"?t[0]:"",o=b5(n),i=O5(e),r=he(e),s=v5(r);if(s.script===null||s.script.version===4)return N5(e,o,i,r,s);let a=wm(o.text),c=gm(Gt(s.script),a,i),d=`sha256:${pp.createHash("sha256").update(o.bytes).digest("hex")}`,p={version:1,sourceDigest:d,mode:i,targetKind:a.targetKind,targets:c.targets.map(w=>w.address),baseline:s.baseline,plan:{targets:c.targets,declarations:c.declarations,retainedOrphanAssets:c.retainedOrphanAssets,validation:c.validation}},l=Lm(p),f=e.apply===!0,u=O(e.plan).trim();if(f&&!u&&mi("--apply requires the exact digest returned by the current plan.",["plan=<missing>"]),!f&&u&&mi("--plan is only valid together with --apply.",[`plan=${u}`]),f&&u!==l)throw new S("The supplied plan does not match the current source, mode, targets, or script baseline.",{exitCode:k,errorCode:"AUTHORING_PLAN_MISMATCH",hint:"Review the newly computed plan, then apply its exact digest.",data:{expected:[l],actual:[u]}});f&&c.changed&&(s.script===null?Xr(r,s.fingerprint):Kt(r,s.baseline),We(r,c.script));let h=R5(c);return[{text:[`${f?"Applied":"Planned"} ${c.targets.length} ${a.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}`,...M5(c)].join(`
|
|
133
|
+
`),data:{op:"write",changed:c.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:a.targetKind,targets:c.targets,declarations:c.declarations,counts:h,validation:c.validation,retained_orphan_assets:c.retainedOrphanAssets,applied:f,script_version:3}},V]}function Cm(e){return Array.isArray(e.rows)}function L5(e){return e.endsWith(`
|
|
134
134
|
`)?e:`${e}
|
|
135
|
-
`}function
|
|
136
|
-
`)}function
|
|
135
|
+
`}function Pm(e){return Array.isArray(e)?e.map(t=>String(t).replace(/[\r\n]+/g," ")):[]}function U5(e){return e==null?"":(typeof e=="string"?e:JSON.stringify(e)).replace(/\t/g," ").replace(/\r?\n/g," ")}function P5(e){if(!Cm(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=>U5(n[o])).join(" "))].join(`
|
|
136
|
+
`)}function Tm(e,t,n,o){if(!(e.text===""&&Object.keys(e.data).length===0)){if(o==="addr"&&Cm(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
138
|
`);return}}if(n){let i={ok:t===V,exit_code:t,...e.data};i.ok=t===V,i.exit_code=t,process.stdout.write(JSON.stringify(i,null,2)+`
|
|
139
|
-
`)}else process.stdout.write(
|
|
140
|
-
`)}else{let n=
|
|
139
|
+
`)}else process.stdout.write(L5(P5(e.data)??e.text))}}function ds(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=Pm(e.data.actual),o=Pm(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
|
|
142
|
+
`)}return e.exitCode}var lp=new WeakMap;function C5(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function T5(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[C5(t),n]))}function V5(e){let t=[],n=e;for(;n;)t.unshift(n),n=n.parent;return Object.assign({},...t.map(o=>o.opts()))}function j(e,t){return async(...n)=>{let o=n[n.length-1],i=n.slice(0,-2).filter(d=>d!==void 0),r=T5(V5(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),[a,c]=lp.get(o)==="write"?await ua(he(r),s):await s();Tm(a,c,t.jsonMode,t.format),t.exitCode=c}}function Le(e,t){return e.registeredArguments.forEach((n,o)=>{n.description=t[o]??""}),e}function te(e,t="write"){return lp.set(e,t),e.option("-p, --script-path <path>","Script JSON file (default: ./workspace/script.json)")}function up(e){return lp.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 Vm(e,t){let n=e.command("authoring").description("Structured screenplay compilation and atomic application transactions"),o=te(n.command("write <file>")).description("Plan or apply a complete structured authoring document").option("--create","Create the selected target").option("--replace","Replace the selected target").option("--apply","Apply the exact plan").option("--plan <digest>","Exact plan digest to apply").action(j(Um,t));Le(o,["Structured .scriptctl file"]);let i=te(n.command("compose <file>")).description("Compile a readable scene JSON draft with generated identities and timing").option("--apply","Apply the exact plan").option("--plan <digest>","Exact plan digest to apply").action(j(jf,t));Le(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 a of s){let c=te(r.command(a),"read").description(`Export structured ${a}`).requiredOption("-o, --output <file>","Destination .scriptctl file");a!=="script"&&c.requiredOption("-i, --in <selector>","Formal ID or @ep:N selector / inclusive range"),c.action(j(d=>im(a,d),t))}}import*as ba from"node:fs";import*as wp from"node:path";import*as gp from"node:fs";import*as sr from"node:path";import{fileURLToPath as $5}from"node:url";var mp="@lingjingai/scriptctl",fp="";function ps(){if(fp)return fp;let e=sr.dirname($5(import.meta.url));for(;;){try{let n=gp.readFileSync(sr.join(e,"package.json"),"utf-8");if(JSON.parse(n).name===mp)return fp=e,e}catch{}let t=sr.dirname(e);if(t===e)throw new Error(`${mp} package root not found`);e=t}}function ar(){let e=gp.readFileSync(sr.join(ps(),"package.json"),"utf-8"),t=JSON.parse(e).version;if(typeof t!="string")throw new Error(`${mp} package.json has no string version`);return t}var $m=/^\d+\.\d+\.\d+$/,D5="unreleased";function Dm(){return wp.join(ps(),"changes")}function G5(){return ar()}function ls(e){if(!$m.test(e))throw new S("Version must use x.y.z.",{exitCode:B,errorCode:"CHANGELOG_VERSION_INVALID",hint:"Pass a released version such as `scriptctl changelog 0.25.10`.",data:{expected:["x.y.z"],actual:[e||"<empty>"]}});let[t,n,o]=e.split(".").map(i=>Number(i));return[t,n,o]}function yp(e,t){let n=ls(e),o=ls(t);for(let i=0;i<3;i++)if(n[i]!==o[i])return n[i]-o[i];return 0}function B5(){let e=Dm();return ba.readdirSync(e).filter(t=>t.endsWith(".md")).map(t=>t.slice(0,-3)).filter(t=>$m.test(t)).sort(yp)}function ka(e){return ba.readFileSync(wp.join(Dm(),`${e}.md`),"utf-8").trimEnd()}function hp(e,t){return new S(`No changelog entry exists for ${e}.`,{exitCode:k,errorCode:"CHANGELOG_VERSION_NOT_FOUND",hint:t.length>0?`Available versions: ${t.join(", ")}`:"Add changes/<version>.md first.",data:{expected:["existing changelog version"],actual:[e]}})}function J5(e,t){return new S(`No released changelog entries found after ${e} through ${t}.`,{exitCode:k,errorCode:"CHANGELOG_RANGE_EMPTY",hint:"Choose a wider range or run `scriptctl changelog <version>` for a known release.",data:{expected:["a version range containing released changelog entries"],actual:[`--from ${e}`,`--to ${t}`]}})}function z5(e){return e.map(ka).join(`
|
|
143
143
|
|
|
144
|
-
`)}function Vm(e){let t=e._args??[],n=t[0]?.trim()??"",o=String(e.from??"").trim(),i=String(e.to??"").trim(),r=!!e.unreleased;if(t.length>1)throw new S("changelog accepts at most one version argument.",{exitCode:B,errorCode:"CHANGELOG_TOO_MANY_ARGS",hint:"Pass a single version, or use --from/--to for a range.",data:{expected:["scriptctl changelog [version] [--from X] [--to Y] [--unreleased]"],actual:[t.join(" ")]}});if(r&&(n||o||i))throw new S("--unreleased cannot combine with version, --from, or --to.",{exitCode:B,errorCode:"CHANGELOG_SELECTOR_CONFLICT",hint:"Run `scriptctl changelog --unreleased` by itself.",data:{expected:["either --unreleased, a version, or a --from/--to range"],actual:["--unreleased with another selector"]}});if(n&&(o||i))throw new S("A version argument cannot combine with --from or --to.",{exitCode:B,errorCode:"CHANGELOG_SELECTOR_CONFLICT",hint:"Run `scriptctl changelog 0.25.10` or `scriptctl changelog --from 0.25.8 --to 0.25.10`.",data:{expected:["either a version argument, or --from/--to"],actual:[n,o?`--from ${o}`:"",i?`--to ${i}`:""].filter(Boolean)}});if(r){let d=Ia(C5);return[{text:d,data:{content:d,versions:[],unreleased:!0}},V]}let s=V5(),a=T5();if(n){if(ds(n),!s.includes(n))throw mp(n,s);let d=Ia(n);return[{text:d,data:{content:d,versions:[n],unreleased:!1}},V]}if(o||i){if(!o)throw new S("--from is required for range queries.",{exitCode:B,errorCode:"CHANGELOG_FROM_MISSING",hint:"Run `scriptctl changelog --from 0.25.8 --to 0.25.10`.",data:{expected:["--from <x.y.z>"],actual:[i?`--to ${i}`:"<missing>"]}});ds(o);let d=i||a;if(ds(d),!s.includes(d))throw mp(d,s);let p=s.filter(f=>gp(f,o)>0&&gp(f,d)<=0);if(p.length===0)throw $5(o,d);let l=D5(p);return[{text:l,data:{content:l,versions:p,from:o,to:d,unreleased:!1}},V]}if(!s.includes(a))throw mp(a,s);let c=Ia(a);return[{text:c,data:{content:c,versions:[a],unreleased:!1}},V]}import*as jt from"node:fs";import*as wi from"node:path";import{createRequire as BS}from"node:module";import*as eo from"node:fs";import*as No from"node:path";import*as Dm from"node:os";import{fileURLToPath as G5}from"node:url";function $m(e){return e.startsWith("~")?No.join(Dm.homedir(),e.slice(1)):e}function B5(e){let t=eo.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 yp(){let e=[],t=(process.env.SCRIPTCTL_ENV_FILE??"").trim();t&&e.push($m(t));let n=(process.env.SCRIPTCTL_SKILL_DIR??"").trim();n&&e.push(No.join($m(n),".env"));let o;try{o=G5(import.meta.url)}catch{o=process.cwd()}let i=No.resolve(o),r=new Set;for(;;){let s=No.dirname(i);if(s===i||r.has(s))break;r.add(s),e.push(No.join(s,".env")),i=s}return e}function Gm(){let e=process.env.SCRIPTCTL_NO_DOTENV;if(e==="1"||e==="true"||e==="True")return;let t=new Set;for(let n of yp()){let o;try{o=eo.existsSync(n)?eo.realpathSync(n):n}catch{o=n}t.has(o)||!eo.existsSync(n)||!eo.statSync(n).isFile()||(t.add(o),B5(n))}}var ge=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 wp(e,t){if(e.updateEpisodeCount)try{await e.updateEpisodeCount(t)}catch{}}function Bm(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 us from"node:fs";import*as Km from"node:os";import*as ps from"node:path";import{parseDocument as J5}from"yaml";function ae(e,t,n){return{id:e,mode:t,version:"1",maxOutputTokens:n,defaultProfile:"default"}}var Ln={"direct.episode-titles":ae("direct.episode-titles","tool",4096),"direct.batch-extract":ae("direct.batch-extract","text",16e3),"direct.episode-synopsis":ae("direct.episode-synopsis","tool",2048),"direct.synopsis-reduction":ae("direct.synopsis-reduction","tool",4096),"direct.script-synopsis":ae("direct.script-synopsis","tool",2048),"direct.asset-grouping":ae("direct.asset-grouping","text",8e3),"direct.asset-curation":ae("direct.asset-curation","text",2e4),"direct.asset-curation-audit":ae("direct.asset-curation-audit","text",2e4),"direct.location-canonicalization":ae("direct.location-canonicalization","text",2e4),"direct.state-curation":ae("direct.state-curation","text",2e4),"direct.state-binding":ae("direct.state-binding","tool",16e3),"metadata.global":ae("metadata.global","text",16e3),"metadata.descriptions":ae("metadata.descriptions","text",16e3),"synopsis.chunk":ae("synopsis.chunk","text",4096),"synopsis.episode":ae("synopsis.episode","text",4096),"synopsis.arc":ae("synopsis.arc","text",16e3),"synopsis.script-overview":ae("synopsis.script-overview","text",16e3),"ingest.body-start":ae("ingest.body-start","text",16e3),"ingest.arc-summary":ae("ingest.arc-summary","text",4096),"ingest.text-normalize":ae("ingest.text-normalize","text",32e3),"ingest.episode-assets":ae("ingest.episode-assets","tool",32e3),"ingest.name-fix":ae("ingest.name-fix","tool",16e3),"ingest.mention-resolve":ae("ingest.mention-resolve","text",8e3),"ingest.asset-extract":ae("ingest.asset-extract","text",8e3),"ingest.asset-curate":ae("ingest.asset-curate","text",32e3),"ingest.asset-recall":ae("ingest.asset-recall","text",65536),"ingest.asset-refine":ae("ingest.asset-refine","text",32e3),"ingest.state-reconcile":ae("ingest.state-reconcile","text",32e3),"ingest.asset-audit":ae("ingest.asset-audit","tool",32e3),"ingest.speaker-audit":ae("ingest.speaker-audit","tool",16e3),"ingest.comic-serial":{id:"ingest.comic-serial",mode:"document",version:"1",defaultProfile:"default"},"ingest.video-serial":ae("ingest.video-serial","video",65536),"soundtrack.analyze":ae("soundtrack.analyze","video",32e3)},Jm=new Set(["soundtrack.analyze"]),zm=Object.keys(Ln).filter(xp);function xp(e){return Object.hasOwn(Ln,e)}var z5=new Set(["protocol","baseUrl","apiKey","timeoutMs","maxAttempts","videoResponseSchemaField","videoUploadMode","documentResponseSchemaField","documentUploadMode"]),K5=new Set(["provider","model","thinking","reasoning","temperature","fallbacks"]),j5=new Set(["env"]),H5=new Set(["budgetTokens"]);function Me(e,t=[]){return new S(e,{exitCode:k,errorCode:"LLM_CONFIG_INVALID",hint:"Fix the selected LLM configuration or environment and rerun `scriptctl doctor`.",data:{expected:["valid scriptctl LLM YAML configuration"],actual:t}})}function Ap(e,t){let n;try{n=new URL(e)}catch{throw Me(`${t} must be an absolute URL.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Me(`${t} must use http or https.`);return n.toString().replace(/\/$/,"")}function kp(e,t="provider base URL"){return Ap(e,t)}function Q5(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lo(e,t){if(!Q5(e))throw Me(`${t} must be a mapping.`,[`${t}: ${typeof e}`]);return e}function Uo(e,t){if(typeof e!="string"||!e.trim())throw Me(`${t} must be a non-empty string.`);return e.trim()}function Ip(e,t,n,o){if(!Number.isInteger(e)||typeof e!="number"||e<n||o!==void 0&&e>o)throw Me(`${t} must be an integer in ${o===void 0?`[${n}, +\u221E)`:`[${n}, ${o}]`}.`);return e}function ls(e,t,n){let o=Object.keys(e).filter(i=>!t.has(i));if(o.length>0)throw Me(`${n} contains unknown fields.`,o)}function F5(e,t){let n=Lo(t,`providers.${e}`);ls(n,z5,`providers.${e}`);let o=Uo(n.protocol,`providers.${e}.protocol`);if(o!=="anthropic"&&o!=="openai-compatible"&&o!=="google-gemini"&&o!=="google-vertex")throw Me(`providers.${e}.protocol is unsupported.`,[o]);let i=n.baseUrl===void 0&&o!=="openai-compatible"?null:Ap(Uo(n.baseUrl,`providers.${e}.baseUrl`),`providers.${e}.baseUrl`),r="";if(o!=="google-vertex"||n.apiKey!==void 0){let a=Lo(n.apiKey,`providers.${e}.apiKey`);if(ls(a,j5,`providers.${e}.apiKey`),r=Uo(a.env,`providers.${e}.apiKey.env`),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw Me(`providers.${e}.apiKey.env must be an environment variable name.`)}let s={protocol:o,baseUrl:i,apiKeyEnv:r,timeoutMs:Ip(n.timeoutMs,`providers.${e}.timeoutMs`,1),maxAttempts:Ip(n.maxAttempts,`providers.${e}.maxAttempts`,1,6)};for(let a of["videoResponseSchemaField","documentResponseSchemaField"]){let c=n[a];if(c!==void 0){if(o!=="google-gemini"&&o!=="google-vertex")throw Me(`providers.${e}.${a} requires a Gemini ${a.startsWith("video")?"video":"document"} provider.`);if(c!=="responseJsonSchema"&&c!=="responseSchema")throw Me(`providers.${e}.${a} must be responseJsonSchema or responseSchema.`);s[a]=c}}for(let a of["videoUploadMode","documentUploadMode"]){let c=n[a];if(c!==void 0){if(o!=="google-gemini"&&o!=="google-vertex")throw Me(`providers.${e}.${a} requires a Gemini ${a.startsWith("video")?"video":"document"} provider.`);if(c!=="file-api"&&c!=="base64")throw Me(`providers.${e}.${a} must be file-api or base64.`);s[a]=c}}return s}function Y5(e,t,n){let o=Lo(t,`models.${e}`);ls(o,K5,`models.${e}`);let i=Uo(o.provider,`models.${e}.provider`),r=n[i];if(!r)throw Me(`models.${e} references an unknown provider.`,[i]);let s={provider:i,model:Uo(o.model,`models.${e}.model`)};if(o.reasoning!==void 0&&(s.reasoning=Uo(o.reasoning,`models.${e}.reasoning`)),o.fallbacks!==void 0){let a=o.fallbacks;if(!Array.isArray(a))throw Me(`models.${e}.fallbacks must be a list of model profiles.`);s.fallbacks=a.map((c,d)=>Uo(c,`models.${e}.fallbacks[${d}]`))}if(o.temperature!==void 0){let a=o.temperature;if(typeof a!="number"||!Number.isFinite(a)||a<0)throw Me(`models.${e}.temperature must be a number \u2265 0.`);s.temperature=a}if(o.thinking!==void 0){if(r.protocol!=="anthropic")throw Me(`models.${e}.thinking is only valid for anthropic providers.`);let a=Lo(o.thinking,`models.${e}.thinking`);ls(a,H5,`models.${e}.thinking`),s.thinkingBudgetTokens=Ip(a.budgetTokens,`models.${e}.thinking.budgetTokens`,1024)}return s}function q5(e,t){let n=Lo(e,"config");if(ls(n,new Set(["version","providers","models","tasks"]),"config"),n.version!==1)throw Me("config.version must be 1.");let o=Lo(n.providers,"providers"),i={};for(let[c,d]of Object.entries(o))i[c]=F5(c,d);let r=Lo(n.models,"models"),s={};for(let[c,d]of Object.entries(r))s[c]=Y5(c,d,i);if(!s.default)throw Me("models.default is required.");for(let[c,d]of Object.entries(s))for(let p of d.fallbacks??[])if(!s[p]||p===c)throw Me(`models.${c}.fallbacks references an unknown or the same profile.`,[p]);let a={};if(n.tasks!==void 0){let c=Lo(n.tasks,"tasks");for(let[d,p]of Object.entries(c)){if(!xp(d))throw Me("tasks contains an unknown task id.",[d]);let l=Uo(p,`tasks.${d}`);if(!s[l])throw Me(`tasks.${d} references an unknown model profile.`,[l]);a[d]=l}}return{version:1,providers:i,models:s,tasks:a,source:"file",sourcePath:t}}var no={protocol:"google-gemini",baseUrl:"https://grsai.dakka.com.cn",apiKeyEnv:"GRSAI_API_KEY",timeoutMs:6e5,maxAttempts:3,videoResponseSchemaField:"responseSchema",videoUploadMode:"base64"},mi={protocol:"google-gemini",baseUrl:"https://api.nnyyai.com",apiKeyEnv:"NNYYAI_API_KEY",timeoutMs:6e5,maxAttempts:3,videoResponseSchemaField:"responseSchema",videoUploadMode:"base64",documentResponseSchemaField:"responseSchema",documentUploadMode:"base64"},bp="gemini-3.8-flash-anci",Ep={protocol:"google-gemini",baseUrl:"http://15.204.107.123:3000",apiKeyEnv:"MSUICODE_VERTEX_API_KEY",timeoutMs:6e5,maxAttempts:3,videoResponseSchemaField:"responseSchema",videoUploadMode:"base64"},_p=["review-msuicode-gcp","review-msuicode-t3","review-tuzi","review-doubao-lite","review-doubao"],to={version:1,providers:{gw:{protocol:"openai-compatible",baseUrl:null,apiKeyEnv:"PROJECT_LITELLM_GATEWAY_API_KEY",timeoutMs:3e5,maxAttempts:3},"gw-anthropic":{protocol:"anthropic",baseUrl:null,apiKeyEnv:"PROJECT_LITELLM_GATEWAY_API_KEY",timeoutMs:3e5,maxAttempts:3},"google-gemini":{protocol:"google-vertex",baseUrl:null,apiKeyEnv:"",timeoutMs:6e5,maxAttempts:3},nnyyai:mi,"nnyyai-ci":{...mi,apiKeyEnv:"NNYYAI_CI_API_KEY"},"msuicode-vertex":{...Ep},"msuicode-gcp":{...Ep,apiKeyEnv:"MSUICODE_GCP_API_KEY"},"msuicode-t3":{...Ep,apiKeyEnv:"MSUICODE_T3_API_KEY"},grsai:no,tuzi:{protocol:"google-gemini",baseUrl:"https://api.tu-zi.com",apiKeyEnv:"TUZI_API_KEY",timeoutMs:6e5,maxAttempts:3},"ark-lite":{protocol:"openai-compatible",baseUrl:"https://ark.cn-beijing.volces.com/api/v3",apiKeyEnv:"ARK_API_KEY",timeoutMs:3e5,maxAttempts:3},ark:{protocol:"openai-compatible",baseUrl:"https://ark.ap-southeast.bytepluses.com/api/v3",apiKeyEnv:"DOUBAO_TURBO_API_KEY",timeoutMs:3e5,maxAttempts:3}},models:{default:{provider:"gw",model:"deepseek-v4-flash-packy",temperature:0},synopsis:{provider:"gw",model:"deepseek-v4.1-flash-huoshan",temperature:0},"ingest-low":{provider:"gw",model:"deepseek-v4-flash-packy",temperature:0},"ingest-normalize":{provider:"gw",model:"claude-sonnet-4-6-aihubmix",temperature:0},"ingest-video":{provider:"nnyyai-ci",model:bp},"ingest-comic":{provider:"nnyyai",model:"gemini-3.8-flash"},"review-text":{provider:"msuicode-vertex",model:"gemini-3.8-flash",temperature:0,fallbacks:_p},"review-comic":{provider:"msuicode-vertex",model:"gemini-3.8-flash",temperature:0,fallbacks:_p},"review-agent":{provider:"msuicode-vertex",model:"gemini-3.8-flash",temperature:0,fallbacks:_p},"review-msuicode-gcp":{provider:"msuicode-gcp",model:"gemini-3.8-flash"},"review-msuicode-t3":{provider:"msuicode-t3",model:"gemini-3.8-flash"},"review-nnyyai":{provider:"nnyyai",model:"gemini-3.8-flash"},"review-tuzi":{provider:"tuzi",model:"gemini-3.8-flash"},"review-doubao-lite":{provider:"ark-lite",model:"ep-20261029164743-gt8dh"},"review-doubao":{provider:"ark",model:"ep-20261028172514-tlxzc"},"review-media":{provider:"nnyyai",model:"gemini-3.8-flash"},"review-grok-4.7":{provider:"gw",model:"grok-4.7-packy"},"review-grok-4.6":{provider:"gw",model:"grok-4.6-packy"},"review-grok-4.5":{provider:"gw",model:"grok-4.5-packy"},"review-grsai-3.8":{provider:"grsai",model:"gemini-3.8-flash"},"review-grsai-3.7":{provider:"grsai",model:"gemini-3.7-flash"},"review-grsai-3.6":{provider:"grsai",model:"gemini-3.6-flash"},reskin:{provider:"google-gemini",model:"gemini-3.8-flash"},"reskin-claude":{provider:"gw-anthropic",model:"claude-opus-5-5-nnyy-offical"}},tasks:{"synopsis.chunk":"synopsis","synopsis.episode":"synopsis","synopsis.arc":"synopsis","synopsis.script-overview":"synopsis","ingest.body-start":"ingest-low","ingest.arc-summary":"ingest-low","ingest.text-normalize":"ingest-low","ingest.mention-resolve":"ingest-low","ingest.asset-recall":"ingest-low","ingest.asset-audit":"ingest-normalize","ingest.episode-assets":"ingest-normalize","ingest.name-fix":"ingest-normalize","ingest.video-serial":"ingest-video","ingest.comic-serial":"ingest-comic","soundtrack.analyze":"ingest-video"},source:"builtin",sourcePath:null};function Z5(){let e=(process.env.PROJECT_LITELLM_GATEWAY_BASE_URL??"").trim(),t=e?Ap(e,"PROJECT_LITELLM_GATEWAY_BASE_URL"):null;return{...to,providers:{...to.providers,gw:{...to.providers.gw,baseUrl:t},"gw-anthropic":{...to.providers["gw-anthropic"],baseUrl:t?t.replace(/\/v1\/?$/,""):null},"google-gemini":{...to.providers["google-gemini"]},nnyyai:{...to.providers.nnyyai},"nnyyai-ci":{...to.providers["nnyyai-ci"]},grsai:{...no}},models:{...to.models},tasks:{...to.tasks}}}function W5(){let e=(process.env.XDG_CONFIG_HOME??"").trim();return e?ps.join(e,"scriptctl","llm.yaml"):ps.join(Km.homedir(),".config","scriptctl","llm.yaml")}function Sp(e){if(!us.existsSync(e))throw Me("LLM configuration file does not exist.",[e]);let t=J5(us.readFileSync(e,"utf-8"),{uniqueKeys:!0});if(t.errors.length>0)throw Me("LLM configuration YAML is invalid.",t.errors.map(o=>o.message));let n=t.toJS();return q5(n,ps.resolve(e))}function Po(e){let t=(e??"").trim();if(t)return Sp(t);let n=(process.env.SCRIPTCTL_LLM_CONFIG??"").trim();if(n)return Sp(n);let o=W5();return us.existsSync(o)?Sp(o):Z5()}import*as rg from"node:crypto";import*as Cp from"node:fs";import tS,{APIConnectionError as nS,APIConnectionTimeoutError as oS,APIError as iS,APIUserAbortError as rS}from"@anthropic-ai/sdk";var vp=1e8;function X5(e){switch(e){case"auth":return{failure_type:"authentication",failure_code:"authentication_failed"};case"permission_denied":return{failure_type:"authorization",failure_code:"permission_denied"};case"endpoint":return{failure_type:"provider",failure_code:"resource_not_found"};case"network":return{failure_type:"network",failure_code:"network_failed"};case"timeout":return{failure_type:"timeout",failure_code:"request_timeout"};case"rate_limited":return{failure_type:"rate_limit",failure_code:"rate_limited"};case"request_failed":return{failure_type:"provider",failure_code:"request_rejected"};case"truncated":return{failure_type:"response",failure_code:"output_truncated"};case"content_filtered":return{failure_type:"policy",failure_code:"content_blocked"};case"empty_response":return{failure_type:"response",failure_code:"empty_response"};case"invalid_response":return{failure_type:"response",failure_code:"malformed_response"};case"cancelled":return{failure_type:"cancelled",failure_code:"cancelled"}}}var T=class extends Error{code;retryable;details;failure;modelFailures;attempts;usage;constructor(t,n,o={}){super(n),this.name="LlmTransportError",this.code=t,this.retryable=o.retryable??!1,this.details=o.details??[],this.attempts=o.attempts??1,this.usage=o.usage??{},this.failure=Vt(o.classification??X5(t),{retryable:this.retryable,message:n,...o.context,...this.details.length>0?{details:this.details}:{}}),this.modelFailures=o.modelFailures??[]}};function eS(e){return new Promise(t=>setTimeout(t,e))}function rn(e={},t={}){let n=a=>e[a]===void 0&&t[a]===void 0?void 0:(e[a]??0)+(t[a]??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 sn(e,t){let n={};for(let o=1;o<=e;o+=1)try{return{value:await t(),attempts:o,failedUsage:n}}catch(i){if(i instanceof T&&(n=rn(n,i.usage),i.attempts=o,i.usage=n),!(i instanceof T)||!i.retryable||o===e)throw i;await eS(Math.min(3e4,1e3*2**(o-1)))}throw new Error("unreachable retry state")}function jm(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 Hm(e){if(e instanceof T)return e;if(e instanceof rS)return new T("request_failed","Anthropic request was aborted.");if(e instanceof oS)return new T("timeout","Anthropic request timed out.",{retryable:!0});if(e instanceof nS)return new T("request_failed","Anthropic connection failed.",{retryable:!0,details:[e.message.slice(0,500)]});if(e instanceof iS){let n=e.status??0,o=n===408||n===429||n>=500,i=n===401||n===403?"auth":n===429?"rate_limited":"request_failed";return new T(i,"Anthropic request failed.",{retryable:o,details:[`status: ${n}`,e.message.slice(0,500)]})}let t=e instanceof Error?e.message:String(e);return new T("request_failed","Anthropic request failed.",{details:[t.slice(0,500)]})}var ka=class{constructor(t,n,o){this.provider=t;this.model=n;let i={apiKey:o};t.baseUrl&&(i.baseURL=t.baseUrl),this.client=new tS({...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 sn(this.provider.maxAttempts,async()=>{try{let o=await this.client.messages.create(this.params(t),{timeout:this.provider.timeoutMs,signal:t.signal}),i=jm(o);if(o.stop_reason==="max_tokens")throw new T("truncated","Provider output was truncated.",{usage:i});if(o.stop_reason==="refusal")throw new T("content_filtered","Provider filtered the response.",{usage:i});let r=o.content.filter(s=>s.type==="text").map(s=>s.text).join(`
|
|
145
|
-
`).trim();if(!r)throw new T("empty_response","Provider returned an empty text response.",{usage:i});return{text:r,finishReason:o.stop_reason??"",usage:i,raw:o}}catch(o){throw Hm(o)}});return{...n.value,attempts:n.attempts,usage:rn(n.failedUsage,n.value.usage)}}async generateTool(t){let n=await sn(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=jm(i);if(i.stop_reason==="max_tokens")throw new T("truncated","Provider tool output was truncated.",{usage:r});if(i.stop_reason==="refusal")throw new T("content_filtered","Provider filtered the response.",{usage:r});let s=i.content.find(a=>a.type==="tool_use"&&a.name===t.tool.name);if(!s||s.type!=="tool_use")throw new T("invalid_response","Provider did not return the required tool call.",{usage:r});return{input:s.input,finishReason:i.stop_reason??"",usage:r,raw:i}}catch(o){throw Hm(o)}});return{...n.value,attempts:n.attempts,usage:rn(n.failedUsage,n.value.usage)}}};import*as Np from"node:fs";import*as Lp from"node:path";import{File as lS}from"node:buffer";import{Agent as uS,fetch as va,FormData as fS}from"undici";function sS(e){return typeof e=="object"&&e!==null}function Op(e){let t=[],n=new Set,o=e;for(;sS(o)&&!n.has(o);)n.add(o),t.push(o),o=o.cause;return t}function ba(e){for(let t of Op(e)){if(typeof t.status=="number")return t.status;if(typeof t.statusCode=="number")return t.statusCode}return null}function aS(e){for(let t of Op(e))if(typeof t.code=="string")return t.code}function cS(e){for(let t of Op(e))if(typeof t.name=="string")return t.name}function dS(e){let t=cS(e);return t==="AbortError"||t==="TimeoutError"||t==="RequestTimeoutError"||t==="APIConnectionTimeoutError"}function pS(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 gi(e,t,n,o,i={}){if(t?.aborted)return new T("cancelled",n,{details:[o],classification:{failure_type:"cancelled",failure_code:"cancelled"},context:i});let r=aS(e),s=dS(e)?{failure_type:"timeout",failure_code:"request_timeout"}:pS(r),a=s.failure_type==="timeout"?"timeout":"network";return new T(a,n,{retryable:!0,details:[o],classification:s,context:{...i,...r?{system_code:r}:{}}})}function hi(e,t,n,o={}){let i,r,s=!1;return e===401?(i="auth",r={failure_type:"authentication",failure_code:"authentication_failed"}):e===403?(i="permission_denied",r={failure_type:"authorization",failure_code:"permission_denied"}):e===404?(i="endpoint",r={failure_type:"provider",failure_code:"resource_not_found"}):e===408?(i="timeout",r={failure_type:"timeout",failure_code:"request_timeout"},s=!0):e===413&&o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"media_too_large"}):e===415&&o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"unsupported_media"}):e===429?(i="rate_limited",r={failure_type:"rate_limit",failure_code:"rate_limited"},s=!0):e>=500?(i="request_failed",r={failure_type:"provider",failure_code:"provider_unavailable"},s=!0):o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"media_upload_failed"}):(i="request_failed",r={failure_type:"provider",failure_code:"request_rejected"}),new T(i,t,{retryable:s,details:[`status: ${e}`,n],classification:r,context:{...o,http_status:e}})}var mS=2e3;function gS(e){return new Promise(t=>setTimeout(t,e))}function Rp(e,t,n,o){if(e instanceof T)return e;let i=e instanceof Error?e.message:String(e),r=ba(e),s={provider:"doubao",model:o,operation:n};return r!==null?hi(r,`Doubao ${n} failed.`,i.slice(0,500),s):gi(e,t,`Doubao ${n} failed.`,i.slice(0,500),s)}function hS(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 yS(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 Oa=class{constructor(t,n,o,i,r,s){this.model=t;this.timeoutMs=n;this.maxAttempts=o;this.client=s??wS(i,r,n)}model;timeoutMs;maxAttempts;client;async run(t){let{value:n}=await sn(this.maxAttempts,async()=>{try{return await this.client.uploadFile({filePath:t.localPath,mimeType:t.localMime,fps:t.fps})}catch(i){throw Rp(i,t.signal,"upload",this.model)}});if(!n.id)throw new T("invalid_response","Doubao upload returned no file id.");let o=await this.pollActive(n.id,t.signal);try{return await this.generateOnce(o,t)}finally{await this.client.deleteFile({id:o}).catch(()=>{})}}async pollActive(t,n){let o=Date.now()+this.timeoutMs,i="processing";for(;i==="processing"||i==="";){if(n?.aborted)throw new T("cancelled","Doubao upload aborted.",{context:{provider:"doubao",model:this.model,operation:"file_poll"}});if(Date.now()>=o)throw new T("timeout","Doubao file processing timed out.",{retryable:!0,classification:{failure_type:"timeout",failure_code:"media_processing_timeout"},context:{provider:"doubao",model:this.model,operation:"file_poll"}});await gS(mS);let r;try{r=await this.client.getFile({id:t})}catch(s){throw Rp(s,n,"file_poll",this.model)}i=(r.status??"").toLowerCase()}if(i==="failed"||i==="error")throw new T("invalid_response","Doubao file processing failed.",{classification:{failure_type:"media",failure_code:"media_processing_failed"},context:{provider:"doubao",model:this.model,operation:"file_poll"}});return t}async generateOnce(t,n){let o={model:this.model,input:[{role:"user",content:[{type:"input_video",file_id:t},{type:"input_text",text:n.user}]}]};return n.system?.trim()&&(o.instructions=n.system),n.responseJsonSchema&&(o.text={format:{type:"json_schema",name:"video_serial",schema:n.responseJsonSchema}}),this.generateResponse(o,n.signal,!!n.responseJsonSchema,n.acceptsText)}async generateText(t){let n=this.textParams(t);return t.responseFormat&&(n.text={format:{type:t.responseFormat}}),this.generateResponse(n,t.signal,!!t.responseFormat)}async generateDocument(t,n){let o=t.media.kind==="base64"?t.media.data:n?Np.readFileSync(n).toString("base64"):void 0;if(!o)throw new T("invalid_response","Doubao PDF recovery requires the original document bytes.");let i={model:this.model,input:[{role:"user",content:[{type:"input_file",filename:n?Lp.basename(n):"document.pdf",file_data:`data:application/pdf;base64,${o}`},{type:"input_text",text:t.user}]}]};return t.system?.trim()&&(i.instructions=t.system),t.responseJsonSchema&&(i.text={format:{type:"json_schema",name:"document",schema:t.responseJsonSchema}}),this.generateResponse(i,t.signal,!!t.responseJsonSchema)}async generateTool(t){let n=this.textParams(t);n.text={format:{type:"json_schema",name:t.tool.name,description:t.tool.description,schema:t.tool.inputSchema}};let o=await this.generateResponse(n,t.signal,!0);return{input:JSON.parse(o.text),finishReason:o.finishReason,attempts:o.attempts,usage:o.usage,raw:o.raw}}textParams(t){return{model:this.model,instructions:t.system,input:[{role:"user",content:[{type:"input_text",text:t.user}]}]}}async generateResponse(t,n,o,i){let{value:r,attempts:s,failedUsage:a}=await sn(this.maxAttempts,async()=>{let c;try{c=await this.client.createResponse(t,n)}catch(f){throw Rp(f,n,"generate",this.model)}let d=(c.status??"").toLowerCase(),p=hS(c.usage);if(d==="incomplete"){let f=c.incomplete_details?.reason??"unknown";throw f==="max_output_tokens"||f==="length"?new T("truncated","Doubao output was truncated.",{usage:p}):new T("content_filtered",`Doubao response incomplete (reason=${f}).`,{usage:p})}let l=yS(c);if(!l)throw new T("empty_response","Doubao returned an empty response.",{retryable:!0,usage:p});if(i&&!i(l))throw new T("invalid_response","Doubao response does not match the requested output format.",{retryable:!0,usage:p,context:{provider:"doubao",model:this.model,operation:"generate"}});if(o)try{JSON.parse(l)}catch{throw new T("invalid_response","Doubao returned malformed JSON for a structured response.",{retryable:!0,usage:p,context:{provider:"doubao",model:this.model,operation:"generate"}})}return{text:l,usage:p,raw:c}});return{text:r.text,finishReason:"STOP",attempts:s,usage:rn(a,r.usage),raw:r.raw}}},Mp=class extends Error{constructor(n,o){super(o);this.status=n;this.name="HttpError"}status};function wS(e,t,n){let o=t.replace(/\/$/,""),i={Authorization:`Bearer ${e}`},r=new uS({headersTimeout:n,bodyTimeout:n});function s(c){let d=AbortSignal.timeout(n);return c?AbortSignal.any([c,d]):d}async function a(c){let d=await c.text().catch(()=>"");throw new Mp(c.status,d.slice(0,500))}return{async uploadFile({filePath:c,mimeType:d,fps:p}){let l=new fS,f=Np.readFileSync(c);l.append("file",new lS([f],Lp.basename(c),{type:d})),l.append("purpose","user_data"),l.append("preprocess_configs[video][fps]",String(p));let u=await va(`${o}/files`,{method:"POST",headers:i,body:l,signal:s(),dispatcher:r});return u.ok||await a(u),await u.json()},async getFile({id:c}){let d=await va(`${o}/files/${c}`,{headers:i,signal:s(),dispatcher:r});return d.ok||await a(d),await d.json()},async createResponse(c,d){let p=await va(`${o}/responses`,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify(c),signal:s(d),dispatcher:r});return p.ok||await a(p),await p.json()},async deleteFile({id:c}){let d=await va(`${o}/files/${c}`,{method:"DELETE",headers:i,signal:s(),dispatcher:r});d.ok||await a(d)}}}import{GoogleAuth as xS}from"google-auth-library";function Ra(){let e=(process.env.VERTEX_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT)?.trim();if(!e)throw new Error("VERTEX_PROJECT_ID or GOOGLE_CLOUD_PROJECT is required for official Vertex AI");return e}var Qm=new xS({scopes:["https://www.googleapis.com/auth/cloud-platform"]});function fs(){return process.env.VERTEX_LOCATION||process.env.GOOGLE_CLOUD_LOCATION||"global"}function Fm(){let e=fs();return`https://${e==="global"?"aiplatform":`${e}-aiplatform`}.googleapis.com`}import*as Xm from"node:fs";import{createRequire as vS}from"node:module";import*as Ma from"node:fs";import*as ES from"node:http";import*as _S from"node:https";import{HttpsProxyAgent as SS}from"https-proxy-agent";var qm="https://generativelanguage.googleapis.com";function IS(e,t){let n=new URL(e??qm);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/upload/v1beta/files`,n.searchParams.set("key",t),n}function AS(e,t){let n=new URL(t??qm),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 ar(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 kS(e){return e?new SS(e):void 0}function Ym(e,t,n,o){return new Promise((i,r)=>{let a=(e.protocol==="http:"?ES:_S).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}`},c=>{let d="";c.on("data",p=>d+=p),c.on("end",()=>i({status:c.statusCode??0,headers:c.headers,body:d}))});if(a.on("error",r),o){if(o.aborted){a.destroy(new Error("aborted"));return}o.addEventListener("abort",()=>a.destroy(new Error("aborted")),{once:!0})}n&&typeof n.pipe=="function"?n.pipe(a):(n&&a.write(n),a.end())})}function bS(e,t){let n=e[t];return Array.isArray(n)?n[0]??"":n??""}async function Zm(e){let t=Ma.statSync(e.filePath).size,o={agent:kS(e.proxyUrl??""),timeout:e.timeoutMs},i=IS(e.baseUrl,e.apiKey),r=l=>ar(l,e.apiKey),s;try{s=await Ym(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 gi(l,e.signal,"Gemini upload start failed.",f,{operation:"upload"})}let a=bS(s.headers,"x-goog-upload-url");if(s.status<200||s.status>=300)throw hi(s.status,"Gemini upload start failed.",r(s.body).slice(0,300),{operation:"upload"});if(!a)throw new T("invalid_response","Gemini upload start returned no upload URL.",{details:[r(s.body).slice(0,300)],context:{operation:"upload",http_status:s.status}});let c=AS(a,e.baseUrl),d;try{d=await Ym(c,{...o,method:"POST",headers:{"Content-Length":String(t),"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"}},Ma.createReadStream(e.filePath),e.signal)}catch(l){let f=r(l instanceof Error?l.message:String(l));throw gi(l,e.signal,"Gemini upload transfer failed.",f,{operation:"upload"})}if(d.status<200||d.status>=300)throw hi(d.status,"Gemini upload transfer failed.",r(d.body).slice(0,300),{operation:"upload"});let p;try{p=JSON.parse(d.body)}catch{throw new T("invalid_response","Gemini upload returned invalid JSON.",{details:[r(d.body).slice(0,300)]})}if(!p.file)throw new T("invalid_response","Gemini upload returned no file.",{details:[r(d.body).slice(0,300)]});return p.file}var OS=new Set(["SAFETY","PROHIBITED_CONTENT","RECITATION","BLOCKLIST","SPII","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION"]),RS=new Set(["LANGUAGE","OTHER","MALFORMED_FUNCTION_CALL","IMAGE_OTHER","NO_IMAGE","UNEXPECTED_TOOL_CALL","TOO_MANY_TOOL_CALLS","MISSING_THOUGHT_SIGNATURE","MALFORMED_RESPONSE"]);function Up(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 Wm(e){if(e?.length)return e.map(t=>({category:t.category??"UNSPECIFIED",probability:t.probability??"UNSPECIFIED",blocked:t.blocked??!1}))}function MS(e){if(typeof e!="object"||e===null)return{};let t=e,n=s=>typeof s=="number"?s:void 0,o=n(t.candidatesTokenCount),i=n(t.thoughtsTokenCount),r=n(t.cachedContentTokenCount);return{inputTokens:n(t.promptTokenCount),outputTokens:o===void 0&&i===void 0?void 0:(o??0)+(i??0),...r!==void 0?{cachedInputTokens:r}:{}}}function NS(e){return/-c\d+$/.test(e)}function LS(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 US=2e3;function PS(e){return new Promise(t=>setTimeout(t,e))}function Pp(e,t,n,o,i,r){if(e instanceof T)return new T(e.code,ar(e.message,o),{retryable:e.retryable,details:e.details.map(d=>ar(d,o)),attempts:e.attempts,usage:e.usage,classification:Fi(e.failure),context:{...Hr(e.failure),provider:i,model:r,operation:n},modelFailures:e.modelFailures});let s=ar(e instanceof Error?e.message:String(e),o),a=ba(e),c={provider:i,model:r,operation:n};return a!==null?hi(a,`Gemini ${n} failed.`,s.slice(0,500),c):gi(e,t,`Gemini ${n} failed.`,s.slice(0,500),c)}var cr=class{constructor(t,n,o,i){this.provider=t;this.model=n;this.apiKey=o;this.client=i??TS(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:Xm.readFileSync(t,"base64"),mimeType:n}:{kind:"file-api",file:await this.uploadFile(t,n,i)}}async uploadFile(t,n,o){let{value:i}=await sn(this.provider.maxAttempts,async()=>{try{return await this.client.files.upload({file:t,config:{mimeType:n}})}catch(s){throw Pp(s,o,"upload",this.apiKey,this.model.provider,this.model.model)}}),r=await this.pollActive(i,o);if(!r.name||!r.uri)throw new T("invalid_response","Gemini upload returned no file reference.",{context:{provider:this.model.provider,model:this.model.model,operation:"upload"}});return{name:r.name,uri:r.uri,mimeType:r.mimeType??n}}async pollActive(t,n){let o=t,i=Date.now()+this.provider.timeoutMs;for(;(o.state??"").toUpperCase()==="PROCESSING";){if(n?.aborted)throw new T("cancelled","Gemini upload aborted.",{context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});if(Date.now()>=i)throw new T("timeout","Gemini file processing timed out.",{retryable:!0,classification:{failure_type:"timeout",failure_code:"media_processing_timeout"},context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});if(await PS(US),!o.name)throw new T("invalid_response","Gemini upload returned no file name to poll.",{context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});try{o=await this.client.files.get({name:o.name})}catch(r){throw Pp(r,n,"file_poll",this.apiKey,this.model.provider,this.model.model)}}if((o.state??"").toUpperCase()==="FAILED")throw new T("invalid_response","Gemini file processing failed.",{details:[ar(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=n?.fps===void 0?void 0:{fps:n.fps},i=!!t.responseJsonSchema&&NS(this.model.model),r={mediaResolution:"MEDIA_RESOLUTION_HIGH",...t.temperature===void 0?{}:{temperature:t.temperature},...t.seed===void 0?{}:{seed:t.seed}},s=[t.system?.trim(),i?`\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 Gm(e){let t=e._args??[],n=t[0]?.trim()??"",o=String(e.from??"").trim(),i=String(e.to??"").trim(),r=!!e.unreleased;if(t.length>1)throw new S("changelog accepts at most one version argument.",{exitCode:B,errorCode:"CHANGELOG_TOO_MANY_ARGS",hint:"Pass a single version, or use --from/--to for a range.",data:{expected:["scriptctl changelog [version] [--from X] [--to Y] [--unreleased]"],actual:[t.join(" ")]}});if(r&&(n||o||i))throw new S("--unreleased cannot combine with version, --from, or --to.",{exitCode:B,errorCode:"CHANGELOG_SELECTOR_CONFLICT",hint:"Run `scriptctl changelog --unreleased` by itself.",data:{expected:["either --unreleased, a version, or a --from/--to range"],actual:["--unreleased with another selector"]}});if(n&&(o||i))throw new S("A version argument cannot combine with --from or --to.",{exitCode:B,errorCode:"CHANGELOG_SELECTOR_CONFLICT",hint:"Run `scriptctl changelog 0.25.10` or `scriptctl changelog --from 0.25.8 --to 0.25.10`.",data:{expected:["either a version argument, or --from/--to"],actual:[n,o?`--from ${o}`:"",i?`--to ${i}`:""].filter(Boolean)}});if(r){let d=ka(D5);return[{text:d,data:{content:d,versions:[],unreleased:!0}},V]}let s=B5(),a=G5();if(n){if(ls(n),!s.includes(n))throw hp(n,s);let d=ka(n);return[{text:d,data:{content:d,versions:[n],unreleased:!1}},V]}if(o||i){if(!o)throw new S("--from is required for range queries.",{exitCode:B,errorCode:"CHANGELOG_FROM_MISSING",hint:"Run `scriptctl changelog --from 0.25.8 --to 0.25.10`.",data:{expected:["--from <x.y.z>"],actual:[i?`--to ${i}`:"<missing>"]}});ls(o);let d=i||a;if(ls(d),!s.includes(d))throw hp(d,s);let p=s.filter(f=>yp(f,o)>0&&yp(f,d)<=0);if(p.length===0)throw J5(o,d);let l=z5(p);return[{text:l,data:{content:l,versions:p,from:o,to:d,unreleased:!1}},V]}if(!s.includes(a))throw hp(a,s);let c=ka(a);return[{text:c,data:{content:c,versions:[a],unreleased:!1}},V]}import*as jt from"node:fs";import*as xi from"node:path";import{createRequire as jS}from"node:module";import*as eo from"node:fs";import*as No from"node:path";import*as Jm from"node:os";import{fileURLToPath as K5}from"node:url";function Bm(e){return e.startsWith("~")?No.join(Jm.homedir(),e.slice(1)):e}function j5(e){let t=eo.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 xp(){let e=[],t=(process.env.SCRIPTCTL_ENV_FILE??"").trim();t&&e.push(Bm(t));let n=(process.env.SCRIPTCTL_SKILL_DIR??"").trim();n&&e.push(No.join(Bm(n),".env"));let o;try{o=K5(import.meta.url)}catch{o=process.cwd()}let i=No.resolve(o),r=new Set;for(;;){let s=No.dirname(i);if(s===i||r.has(s))break;r.add(s),e.push(No.join(s,".env")),i=s}return e}function zm(){let e=process.env.SCRIPTCTL_NO_DOTENV;if(e==="1"||e==="true"||e==="True")return;let t=new Set;for(let n of xp()){let o;try{o=eo.existsSync(n)?eo.realpathSync(n):n}catch{o=n}t.has(o)||!eo.existsSync(n)||!eo.statSync(n).isFile()||(t.add(o),j5(n))}}var ge=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 Ep(e,t){if(e.updateEpisodeCount)try{await e.updateEpisodeCount(t)}catch{}}function Km(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 ms from"node:fs";import*as Qm from"node:os";import*as us from"node:path";import{parseDocument as H5}from"yaml";function ae(e,t,n){return{id:e,mode:t,version:"1",maxOutputTokens:n,defaultProfile:"default"}}var Ln={"direct.episode-titles":ae("direct.episode-titles","tool",4096),"direct.batch-extract":ae("direct.batch-extract","text",16e3),"direct.episode-synopsis":ae("direct.episode-synopsis","tool",2048),"direct.synopsis-reduction":ae("direct.synopsis-reduction","tool",4096),"direct.script-synopsis":ae("direct.script-synopsis","tool",2048),"direct.asset-grouping":ae("direct.asset-grouping","text",8e3),"direct.asset-curation":ae("direct.asset-curation","text",2e4),"direct.asset-curation-audit":ae("direct.asset-curation-audit","text",2e4),"direct.location-canonicalization":ae("direct.location-canonicalization","text",2e4),"direct.state-curation":ae("direct.state-curation","text",2e4),"direct.state-binding":ae("direct.state-binding","tool",16e3),"metadata.global":ae("metadata.global","text",16e3),"metadata.descriptions":ae("metadata.descriptions","text",16e3),"synopsis.chunk":ae("synopsis.chunk","text",4096),"synopsis.episode":ae("synopsis.episode","text",4096),"synopsis.arc":ae("synopsis.arc","text",16e3),"synopsis.script-overview":ae("synopsis.script-overview","text",16e3),"ingest.body-start":ae("ingest.body-start","text",16e3),"ingest.arc-summary":ae("ingest.arc-summary","text",4096),"ingest.text-normalize":ae("ingest.text-normalize","text",32e3),"ingest.episode-assets":ae("ingest.episode-assets","tool",32e3),"ingest.name-fix":ae("ingest.name-fix","tool",16e3),"ingest.mention-resolve":ae("ingest.mention-resolve","text",8e3),"ingest.asset-extract":ae("ingest.asset-extract","text",8e3),"ingest.asset-curate":ae("ingest.asset-curate","text",32e3),"ingest.asset-recall":ae("ingest.asset-recall","text",65536),"ingest.asset-refine":ae("ingest.asset-refine","text",32e3),"ingest.state-reconcile":ae("ingest.state-reconcile","text",32e3),"ingest.asset-audit":ae("ingest.asset-audit","tool",32e3),"ingest.speaker-audit":ae("ingest.speaker-audit","tool",16e3),"ingest.comic-serial":{id:"ingest.comic-serial",mode:"document",version:"1",defaultProfile:"default"},"ingest.video-serial":ae("ingest.video-serial","video",65536),"soundtrack.analyze":ae("soundtrack.analyze","video",32e3)},jm=new Set(["soundtrack.analyze"]),Hm=Object.keys(Ln).filter(_p);function _p(e){return Object.hasOwn(Ln,e)}var Q5=new Set(["protocol","baseUrl","apiKey","timeoutMs","maxAttempts","videoResponseSchemaField","videoUploadMode","documentResponseSchemaField","documentUploadMode"]),F5=new Set(["provider","model","thinking","reasoning","temperature","fallbacks"]),Y5=new Set(["env"]),q5=new Set(["budgetTokens"]);function Me(e,t=[]){return new S(e,{exitCode:k,errorCode:"LLM_CONFIG_INVALID",hint:"Fix the selected LLM configuration or environment and rerun `scriptctl doctor`.",data:{expected:["valid scriptctl LLM YAML configuration"],actual:t}})}function bp(e,t){let n;try{n=new URL(e)}catch{throw Me(`${t} must be an absolute URL.`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw Me(`${t} must use http or https.`);return n.toString().replace(/\/$/,"")}function vp(e,t="provider base URL"){return bp(e,t)}function W5(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Uo(e,t){if(!W5(e))throw Me(`${t} must be a mapping.`,[`${t}: ${typeof e}`]);return e}function Po(e,t){if(typeof e!="string"||!e.trim())throw Me(`${t} must be a non-empty string.`);return e.trim()}function kp(e,t,n,o){if(!Number.isInteger(e)||typeof e!="number"||e<n||o!==void 0&&e>o)throw Me(`${t} must be an integer in ${o===void 0?`[${n}, +\u221E)`:`[${n}, ${o}]`}.`);return e}function fs(e,t,n){let o=Object.keys(e).filter(i=>!t.has(i));if(o.length>0)throw Me(`${n} contains unknown fields.`,o)}function Z5(e,t){let n=Uo(t,`providers.${e}`);fs(n,Q5,`providers.${e}`);let o=Po(n.protocol,`providers.${e}.protocol`);if(o!=="anthropic"&&o!=="openai-compatible"&&o!=="google-gemini"&&o!=="google-vertex")throw Me(`providers.${e}.protocol is unsupported.`,[o]);let i=n.baseUrl===void 0&&o!=="openai-compatible"?null:bp(Po(n.baseUrl,`providers.${e}.baseUrl`),`providers.${e}.baseUrl`),r="";if(o!=="google-vertex"||n.apiKey!==void 0){let a=Uo(n.apiKey,`providers.${e}.apiKey`);if(fs(a,Y5,`providers.${e}.apiKey`),r=Po(a.env,`providers.${e}.apiKey.env`),!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw Me(`providers.${e}.apiKey.env must be an environment variable name.`)}let s={protocol:o,baseUrl:i,apiKeyEnv:r,timeoutMs:kp(n.timeoutMs,`providers.${e}.timeoutMs`,1),maxAttempts:kp(n.maxAttempts,`providers.${e}.maxAttempts`,1,6)};for(let a of["videoResponseSchemaField","documentResponseSchemaField"]){let c=n[a];if(c!==void 0){if(o!=="google-gemini"&&o!=="google-vertex")throw Me(`providers.${e}.${a} requires a Gemini ${a.startsWith("video")?"video":"document"} provider.`);if(c!=="responseJsonSchema"&&c!=="responseSchema")throw Me(`providers.${e}.${a} must be responseJsonSchema or responseSchema.`);s[a]=c}}for(let a of["videoUploadMode","documentUploadMode"]){let c=n[a];if(c!==void 0){if(o!=="google-gemini"&&o!=="google-vertex")throw Me(`providers.${e}.${a} requires a Gemini ${a.startsWith("video")?"video":"document"} provider.`);if(c!=="file-api"&&c!=="base64")throw Me(`providers.${e}.${a} must be file-api or base64.`);s[a]=c}}return s}function X5(e,t,n){let o=Uo(t,`models.${e}`);fs(o,F5,`models.${e}`);let i=Po(o.provider,`models.${e}.provider`),r=n[i];if(!r)throw Me(`models.${e} references an unknown provider.`,[i]);let s={provider:i,model:Po(o.model,`models.${e}.model`)};if(o.reasoning!==void 0&&(s.reasoning=Po(o.reasoning,`models.${e}.reasoning`)),o.fallbacks!==void 0){let a=o.fallbacks;if(!Array.isArray(a))throw Me(`models.${e}.fallbacks must be a list of model profiles.`);s.fallbacks=a.map((c,d)=>Po(c,`models.${e}.fallbacks[${d}]`))}if(o.temperature!==void 0){let a=o.temperature;if(typeof a!="number"||!Number.isFinite(a)||a<0)throw Me(`models.${e}.temperature must be a number \u2265 0.`);s.temperature=a}if(o.thinking!==void 0){if(r.protocol!=="anthropic")throw Me(`models.${e}.thinking is only valid for anthropic providers.`);let a=Uo(o.thinking,`models.${e}.thinking`);fs(a,q5,`models.${e}.thinking`),s.thinkingBudgetTokens=kp(a.budgetTokens,`models.${e}.thinking.budgetTokens`,1024)}return s}function eS(e,t){let n=Uo(e,"config");if(fs(n,new Set(["version","providers","models","tasks"]),"config"),n.version!==1)throw Me("config.version must be 1.");let o=Uo(n.providers,"providers"),i={};for(let[c,d]of Object.entries(o))i[c]=Z5(c,d);let r=Uo(n.models,"models"),s={};for(let[c,d]of Object.entries(r))s[c]=X5(c,d,i);if(!s.default)throw Me("models.default is required.");for(let[c,d]of Object.entries(s))for(let p of d.fallbacks??[])if(!s[p]||p===c)throw Me(`models.${c}.fallbacks references an unknown or the same profile.`,[p]);let a={};if(n.tasks!==void 0){let c=Uo(n.tasks,"tasks");for(let[d,p]of Object.entries(c)){if(!_p(d))throw Me("tasks contains an unknown task id.",[d]);let l=Po(p,`tasks.${d}`);if(!s[l])throw Me(`tasks.${d} references an unknown model profile.`,[l]);a[d]=l}}return{version:1,providers:i,models:s,tasks:a,source:"file",sourcePath:t}}var no={protocol:"google-gemini",baseUrl:"https://grsai.dakka.com.cn",apiKeyEnv:"GRSAI_API_KEY",timeoutMs:6e5,maxAttempts:3,videoResponseSchemaField:"responseSchema",videoUploadMode:"base64"},gi={protocol:"google-gemini",baseUrl:"https://api.nnyyai.com",apiKeyEnv:"NNYYAI_API_KEY",timeoutMs:6e5,maxAttempts:3,videoResponseSchemaField:"responseSchema",videoUploadMode:"base64",documentResponseSchemaField:"responseSchema",documentUploadMode:"base64"},Op="gemini-3.8-flash-anci",Sp={protocol:"google-gemini",baseUrl:"http://15.204.107.123:3000",apiKeyEnv:"MSUICODE_VERTEX_API_KEY",timeoutMs:6e5,maxAttempts:3,videoResponseSchemaField:"responseSchema",videoUploadMode:"base64"},Lo="medium",Ip=["review-msuicode-gcp","review-msuicode-t3","review-tuzi","review-doubao-lite","review-doubao"],to={version:1,providers:{gw:{protocol:"openai-compatible",baseUrl:null,apiKeyEnv:"PROJECT_LITELLM_GATEWAY_API_KEY",timeoutMs:3e5,maxAttempts:3},"gw-anthropic":{protocol:"anthropic",baseUrl:null,apiKeyEnv:"PROJECT_LITELLM_GATEWAY_API_KEY",timeoutMs:3e5,maxAttempts:3},"google-gemini":{protocol:"google-vertex",baseUrl:null,apiKeyEnv:"",timeoutMs:6e5,maxAttempts:3},nnyyai:gi,"nnyyai-ci":{...gi,apiKeyEnv:"NNYYAI_CI_API_KEY"},"msuicode-vertex":{...Sp},"msuicode-gcp":{...Sp,apiKeyEnv:"MSUICODE_GCP_API_KEY"},"msuicode-t3":{...Sp,apiKeyEnv:"MSUICODE_T3_API_KEY"},grsai:no,tuzi:{protocol:"google-gemini",baseUrl:"https://api.tu-zi.com",apiKeyEnv:"TUZI_API_KEY",timeoutMs:6e5,maxAttempts:3},"ark-lite":{protocol:"openai-compatible",baseUrl:"https://ark.cn-beijing.volces.com/api/v3",apiKeyEnv:"ARK_API_KEY",timeoutMs:3e5,maxAttempts:3},ark:{protocol:"openai-compatible",baseUrl:"https://ark.ap-southeast.bytepluses.com/api/v3",apiKeyEnv:"DOUBAO_TURBO_API_KEY",timeoutMs:3e5,maxAttempts:3}},models:{default:{provider:"gw",model:"deepseek-v4-flash-packy",temperature:0},synopsis:{provider:"gw",model:"deepseek-v4.1-flash-huoshan",temperature:0},"ingest-low":{provider:"gw",model:"deepseek-v4-flash-packy",temperature:0},"ingest-normalize":{provider:"gw",model:"claude-sonnet-4-6-aihubmix",temperature:0},"ingest-video":{provider:"nnyyai-ci",model:Op},"ingest-comic":{provider:"nnyyai",model:"gemini-3.8-flash"},"review-text":{provider:"msuicode-vertex",model:"gemini-3.8-flash",temperature:0,reasoning:Lo,fallbacks:Ip},"review-comic":{provider:"msuicode-vertex",model:"gemini-3.8-flash",temperature:0,reasoning:Lo,fallbacks:Ip},"review-agent":{provider:"msuicode-vertex",model:"gemini-3.8-flash",temperature:0,reasoning:Lo,fallbacks:Ip},"review-msuicode-gcp":{provider:"msuicode-gcp",model:"gemini-3.8-flash",reasoning:Lo},"review-msuicode-t3":{provider:"msuicode-t3",model:"gemini-3.8-flash",reasoning:Lo},"review-nnyyai":{provider:"nnyyai",model:"gemini-3.8-flash",reasoning:Lo},"review-tuzi":{provider:"tuzi",model:"gemini-3.8-flash",reasoning:Lo},"review-doubao-lite":{provider:"ark-lite",model:"ep-20261029164743-gt8dh"},"review-doubao":{provider:"ark",model:"ep-20261028172514-tlxzc"},"review-media":{provider:"nnyyai",model:"gemini-3.8-flash",reasoning:Lo},"review-grok-4.7":{provider:"gw",model:"grok-4.7-packy"},"review-grok-4.6":{provider:"gw",model:"grok-4.6-packy"},"review-grok-4.5":{provider:"gw",model:"grok-4.5-packy"},"review-grsai-3.8":{provider:"grsai",model:"gemini-3.8-flash"},"review-grsai-3.7":{provider:"grsai",model:"gemini-3.7-flash"},"review-grsai-3.6":{provider:"grsai",model:"gemini-3.6-flash"},reskin:{provider:"google-gemini",model:"gemini-3.8-flash"},"reskin-claude":{provider:"gw-anthropic",model:"claude-opus-5-5-nnyy-offical"}},tasks:{"synopsis.chunk":"synopsis","synopsis.episode":"synopsis","synopsis.arc":"synopsis","synopsis.script-overview":"synopsis","ingest.body-start":"ingest-low","ingest.arc-summary":"ingest-low","ingest.text-normalize":"ingest-low","ingest.mention-resolve":"ingest-low","ingest.asset-recall":"ingest-low","ingest.asset-audit":"ingest-normalize","ingest.episode-assets":"ingest-normalize","ingest.name-fix":"ingest-normalize","ingest.video-serial":"ingest-video","ingest.comic-serial":"ingest-comic","soundtrack.analyze":"ingest-video"},source:"builtin",sourcePath:null};function tS(){let e=(process.env.PROJECT_LITELLM_GATEWAY_BASE_URL??"").trim(),t=e?bp(e,"PROJECT_LITELLM_GATEWAY_BASE_URL"):null;return{...to,providers:{...to.providers,gw:{...to.providers.gw,baseUrl:t},"gw-anthropic":{...to.providers["gw-anthropic"],baseUrl:t?t.replace(/\/v1\/?$/,""):null},"google-gemini":{...to.providers["google-gemini"]},nnyyai:{...to.providers.nnyyai},"nnyyai-ci":{...to.providers["nnyyai-ci"]},grsai:{...no}},models:{...to.models},tasks:{...to.tasks}}}function nS(){let e=(process.env.XDG_CONFIG_HOME??"").trim();return e?us.join(e,"scriptctl","llm.yaml"):us.join(Qm.homedir(),".config","scriptctl","llm.yaml")}function Ap(e){if(!ms.existsSync(e))throw Me("LLM configuration file does not exist.",[e]);let t=H5(ms.readFileSync(e,"utf-8"),{uniqueKeys:!0});if(t.errors.length>0)throw Me("LLM configuration YAML is invalid.",t.errors.map(o=>o.message));let n=t.toJS();return eS(n,us.resolve(e))}function Co(e){let t=(e??"").trim();if(t)return Ap(t);let n=(process.env.SCRIPTCTL_LLM_CONFIG??"").trim();if(n)return Ap(n);let o=nS();return ms.existsSync(o)?Ap(o):tS()}import*as cg from"node:crypto";import*as Vp from"node:fs";import rS,{APIConnectionError as sS,APIConnectionTimeoutError as aS,APIError as cS,APIUserAbortError as dS}from"@anthropic-ai/sdk";var Rp=1e8;function oS(e){switch(e){case"auth":return{failure_type:"authentication",failure_code:"authentication_failed"};case"permission_denied":return{failure_type:"authorization",failure_code:"permission_denied"};case"endpoint":return{failure_type:"provider",failure_code:"resource_not_found"};case"network":return{failure_type:"network",failure_code:"network_failed"};case"timeout":return{failure_type:"timeout",failure_code:"request_timeout"};case"rate_limited":return{failure_type:"rate_limit",failure_code:"rate_limited"};case"request_failed":return{failure_type:"provider",failure_code:"request_rejected"};case"truncated":return{failure_type:"response",failure_code:"output_truncated"};case"content_filtered":return{failure_type:"policy",failure_code:"content_blocked"};case"empty_response":return{failure_type:"response",failure_code:"empty_response"};case"invalid_response":return{failure_type:"response",failure_code:"malformed_response"};case"cancelled":return{failure_type:"cancelled",failure_code:"cancelled"}}}var T=class extends Error{code;retryable;details;failure;modelFailures;attempts;usage;constructor(t,n,o={}){super(n),this.name="LlmTransportError",this.code=t,this.retryable=o.retryable??!1,this.details=o.details??[],this.attempts=o.attempts??1,this.usage=o.usage??{},this.failure=Vt(o.classification??oS(t),{retryable:this.retryable,message:n,...o.context,...this.details.length>0?{details:this.details}:{}}),this.modelFailures=o.modelFailures??[]}};function iS(e){return new Promise(t=>setTimeout(t,e))}function rn(e={},t={}){let n=a=>e[a]===void 0&&t[a]===void 0?void 0:(e[a]??0)+(t[a]??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 sn(e,t){let n={};for(let o=1;o<=e;o+=1)try{return{value:await t(),attempts:o,failedUsage:n}}catch(i){if(i instanceof T&&(n=rn(n,i.usage),i.attempts=o,i.usage=n),!(i instanceof T)||!i.retryable||o===e)throw i;await iS(Math.min(3e4,1e3*2**(o-1)))}throw new Error("unreachable retry state")}function Fm(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 Ym(e){if(e instanceof T)return e;if(e instanceof dS)return new T("request_failed","Anthropic request was aborted.");if(e instanceof aS)return new T("timeout","Anthropic request timed out.",{retryable:!0});if(e instanceof sS)return new T("request_failed","Anthropic connection failed.",{retryable:!0,details:[e.message.slice(0,500)]});if(e instanceof cS){let n=e.status??0,o=n===408||n===429||n>=500,i=n===401||n===403?"auth":n===429?"rate_limited":"request_failed";return new T(i,"Anthropic request failed.",{retryable:o,details:[`status: ${n}`,e.message.slice(0,500)]})}let t=e instanceof Error?e.message:String(e);return new T("request_failed","Anthropic request failed.",{details:[t.slice(0,500)]})}var va=class{constructor(t,n,o){this.provider=t;this.model=n;let i={apiKey:o};t.baseUrl&&(i.baseURL=t.baseUrl),this.client=new rS({...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 sn(this.provider.maxAttempts,async()=>{try{let o=await this.client.messages.create(this.params(t),{timeout:this.provider.timeoutMs,signal:t.signal}),i=Fm(o);if(o.stop_reason==="max_tokens")throw new T("truncated","Provider output was truncated.",{usage:i});if(o.stop_reason==="refusal")throw new T("content_filtered","Provider filtered the response.",{usage:i});let r=o.content.filter(s=>s.type==="text").map(s=>s.text).join(`
|
|
145
|
+
`).trim();if(!r)throw new T("empty_response","Provider returned an empty text response.",{usage:i});return{text:r,finishReason:o.stop_reason??"",usage:i,raw:o}}catch(o){throw Ym(o)}});return{...n.value,attempts:n.attempts,usage:rn(n.failedUsage,n.value.usage)}}async generateTool(t){let n=await sn(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=Fm(i);if(i.stop_reason==="max_tokens")throw new T("truncated","Provider tool output was truncated.",{usage:r});if(i.stop_reason==="refusal")throw new T("content_filtered","Provider filtered the response.",{usage:r});let s=i.content.find(a=>a.type==="tool_use"&&a.name===t.tool.name);if(!s||s.type!=="tool_use")throw new T("invalid_response","Provider did not return the required tool call.",{usage:r});return{input:s.input,finishReason:i.stop_reason??"",usage:r,raw:i}}catch(o){throw Ym(o)}});return{...n.value,attempts:n.attempts,usage:rn(n.failedUsage,n.value.usage)}}};import*as Up from"node:fs";import*as Pp from"node:path";import{File as gS}from"node:buffer";import{Agent as hS,fetch as Ra,FormData as yS}from"undici";function pS(e){return typeof e=="object"&&e!==null}function Mp(e){let t=[],n=new Set,o=e;for(;pS(o)&&!n.has(o);)n.add(o),t.push(o),o=o.cause;return t}function Oa(e){for(let t of Mp(e)){if(typeof t.status=="number")return t.status;if(typeof t.statusCode=="number")return t.statusCode}return null}function lS(e){for(let t of Mp(e))if(typeof t.code=="string")return t.code}function uS(e){for(let t of Mp(e))if(typeof t.name=="string")return t.name}function fS(e){let t=uS(e);return t==="AbortError"||t==="TimeoutError"||t==="RequestTimeoutError"||t==="APIConnectionTimeoutError"}function mS(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 hi(e,t,n,o,i={}){if(t?.aborted)return new T("cancelled",n,{details:[o],classification:{failure_type:"cancelled",failure_code:"cancelled"},context:i});let r=lS(e),s=fS(e)?{failure_type:"timeout",failure_code:"request_timeout"}:mS(r),a=s.failure_type==="timeout"?"timeout":"network";return new T(a,n,{retryable:!0,details:[o],classification:s,context:{...i,...r?{system_code:r}:{}}})}function yi(e,t,n,o={}){let i,r,s=!1;return e===401?(i="auth",r={failure_type:"authentication",failure_code:"authentication_failed"}):e===403?(i="permission_denied",r={failure_type:"authorization",failure_code:"permission_denied"}):e===404?(i="endpoint",r={failure_type:"provider",failure_code:"resource_not_found"}):e===408?(i="timeout",r={failure_type:"timeout",failure_code:"request_timeout"},s=!0):e===413&&o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"media_too_large"}):e===415&&o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"unsupported_media"}):e===429?(i="rate_limited",r={failure_type:"rate_limit",failure_code:"rate_limited"},s=!0):e>=500?(i="request_failed",r={failure_type:"provider",failure_code:"provider_unavailable"},s=!0):o.operation==="upload"?(i="request_failed",r={failure_type:"media",failure_code:"media_upload_failed"}):(i="request_failed",r={failure_type:"provider",failure_code:"request_rejected"}),new T(i,t,{retryable:s,details:[`status: ${e}`,n],classification:r,context:{...o,http_status:e}})}var wS=2e3;function xS(e){return new Promise(t=>setTimeout(t,e))}function Np(e,t,n,o){if(e instanceof T)return e;let i=e instanceof Error?e.message:String(e),r=Oa(e),s={provider:"doubao",model:o,operation:n};return r!==null?yi(r,`Doubao ${n} failed.`,i.slice(0,500),s):hi(e,t,`Doubao ${n} failed.`,i.slice(0,500),s)}function ES(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 _S(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 Ma=class{constructor(t,n,o,i,r,s){this.model=t;this.timeoutMs=n;this.maxAttempts=o;this.client=s??SS(i,r,n)}model;timeoutMs;maxAttempts;client;async run(t){let{value:n}=await sn(this.maxAttempts,async()=>{try{return await this.client.uploadFile({filePath:t.localPath,mimeType:t.localMime,fps:t.fps})}catch(i){throw Np(i,t.signal,"upload",this.model)}});if(!n.id)throw new T("invalid_response","Doubao upload returned no file id.");let o=await this.pollActive(n.id,t.signal);try{return await this.generateOnce(o,t)}finally{await this.client.deleteFile({id:o}).catch(()=>{})}}async pollActive(t,n){let o=Date.now()+this.timeoutMs,i="processing";for(;i==="processing"||i==="";){if(n?.aborted)throw new T("cancelled","Doubao upload aborted.",{context:{provider:"doubao",model:this.model,operation:"file_poll"}});if(Date.now()>=o)throw new T("timeout","Doubao file processing timed out.",{retryable:!0,classification:{failure_type:"timeout",failure_code:"media_processing_timeout"},context:{provider:"doubao",model:this.model,operation:"file_poll"}});await xS(wS);let r;try{r=await this.client.getFile({id:t})}catch(s){throw Np(s,n,"file_poll",this.model)}i=(r.status??"").toLowerCase()}if(i==="failed"||i==="error")throw new T("invalid_response","Doubao file processing failed.",{classification:{failure_type:"media",failure_code:"media_processing_failed"},context:{provider:"doubao",model:this.model,operation:"file_poll"}});return t}async generateOnce(t,n){let o={model:this.model,input:[{role:"user",content:[{type:"input_video",file_id:t},{type:"input_text",text:n.user}]}]};return n.system?.trim()&&(o.instructions=n.system),n.responseJsonSchema&&(o.text={format:{type:"json_schema",name:"video_serial",schema:n.responseJsonSchema}}),this.generateResponse(o,n.signal,!!n.responseJsonSchema,n.acceptsText)}async generateText(t){let n=this.textParams(t);return t.responseFormat&&(n.text={format:{type:t.responseFormat}}),this.generateResponse(n,t.signal,!!t.responseFormat)}async generateDocument(t,n){let o=t.media.kind==="base64"?t.media.data:n?Up.readFileSync(n).toString("base64"):void 0;if(!o)throw new T("invalid_response","Doubao PDF recovery requires the original document bytes.");let i={model:this.model,input:[{role:"user",content:[{type:"input_file",filename:n?Pp.basename(n):"document.pdf",file_data:`data:application/pdf;base64,${o}`},{type:"input_text",text:t.user}]}]};return t.system?.trim()&&(i.instructions=t.system),t.responseJsonSchema&&(i.text={format:{type:"json_schema",name:"document",schema:t.responseJsonSchema}}),this.generateResponse(i,t.signal,!!t.responseJsonSchema)}async generateTool(t){let n=this.textParams(t);n.text={format:{type:"json_schema",name:t.tool.name,description:t.tool.description,schema:t.tool.inputSchema}};let o=await this.generateResponse(n,t.signal,!0);return{input:JSON.parse(o.text),finishReason:o.finishReason,attempts:o.attempts,usage:o.usage,raw:o.raw}}textParams(t){return{model:this.model,instructions:t.system,input:[{role:"user",content:[{type:"input_text",text:t.user}]}]}}async generateResponse(t,n,o,i){let{value:r,attempts:s,failedUsage:a}=await sn(this.maxAttempts,async()=>{let c;try{c=await this.client.createResponse(t,n)}catch(f){throw Np(f,n,"generate",this.model)}let d=(c.status??"").toLowerCase(),p=ES(c.usage);if(d==="incomplete"){let f=c.incomplete_details?.reason??"unknown";throw f==="max_output_tokens"||f==="length"?new T("truncated","Doubao output was truncated.",{usage:p}):new T("content_filtered",`Doubao response incomplete (reason=${f}).`,{usage:p})}let l=_S(c);if(!l)throw new T("empty_response","Doubao returned an empty response.",{retryable:!0,usage:p});if(i&&!i(l))throw new T("invalid_response","Doubao response does not match the requested output format.",{retryable:!0,usage:p,context:{provider:"doubao",model:this.model,operation:"generate"}});if(o)try{JSON.parse(l)}catch{throw new T("invalid_response","Doubao returned malformed JSON for a structured response.",{retryable:!0,usage:p,context:{provider:"doubao",model:this.model,operation:"generate"}})}return{text:l,usage:p,raw:c}});return{text:r.text,finishReason:"STOP",attempts:s,usage:rn(a,r.usage),raw:r.raw}}},Lp=class extends Error{constructor(n,o){super(o);this.status=n;this.name="HttpError"}status};function SS(e,t,n){let o=t.replace(/\/$/,""),i={Authorization:`Bearer ${e}`},r=new hS({headersTimeout:n,bodyTimeout:n});function s(c){let d=AbortSignal.timeout(n);return c?AbortSignal.any([c,d]):d}async function a(c){let d=await c.text().catch(()=>"");throw new Lp(c.status,d.slice(0,500))}return{async uploadFile({filePath:c,mimeType:d,fps:p}){let l=new yS,f=Up.readFileSync(c);l.append("file",new gS([f],Pp.basename(c),{type:d})),l.append("purpose","user_data"),l.append("preprocess_configs[video][fps]",String(p));let u=await Ra(`${o}/files`,{method:"POST",headers:i,body:l,signal:s(),dispatcher:r});return u.ok||await a(u),await u.json()},async getFile({id:c}){let d=await Ra(`${o}/files/${c}`,{headers:i,signal:s(),dispatcher:r});return d.ok||await a(d),await d.json()},async createResponse(c,d){let p=await Ra(`${o}/responses`,{method:"POST",headers:{...i,"Content-Type":"application/json"},body:JSON.stringify(c),signal:s(d),dispatcher:r});return p.ok||await a(p),await p.json()},async deleteFile({id:c}){let d=await Ra(`${o}/files/${c}`,{method:"DELETE",headers:i,signal:s(),dispatcher:r});d.ok||await a(d)}}}import{GoogleAuth as IS}from"google-auth-library";function Na(){let e=(process.env.VERTEX_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT)?.trim();if(!e)throw new Error("VERTEX_PROJECT_ID or GOOGLE_CLOUD_PROJECT is required for official Vertex AI");return e}var qm=new IS({scopes:["https://www.googleapis.com/auth/cloud-platform"]});function gs(){return process.env.VERTEX_LOCATION||process.env.GOOGLE_CLOUD_LOCATION||"global"}function Wm(){let e=gs();return`https://${e==="global"?"aiplatform":`${e}-aiplatform`}.googleapis.com`}import*as ng from"node:fs";import{createRequire as NS}from"node:module";import*as La from"node:fs";import*as AS from"node:http";import*as kS from"node:https";import{HttpsProxyAgent as bS}from"https-proxy-agent";var Xm="https://generativelanguage.googleapis.com";function vS(e,t){let n=new URL(e??Xm);return n.pathname=`${n.pathname.replace(/\/+$/,"")}/upload/v1beta/files`,n.searchParams.set("key",t),n}function OS(e,t){let n=new URL(t??Xm),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 cr(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 RS(e){return e?new bS(e):void 0}function Zm(e,t,n,o){return new Promise((i,r)=>{let a=(e.protocol==="http:"?AS:kS).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}`},c=>{let d="";c.on("data",p=>d+=p),c.on("end",()=>i({status:c.statusCode??0,headers:c.headers,body:d}))});if(a.on("error",r),o){if(o.aborted){a.destroy(new Error("aborted"));return}o.addEventListener("abort",()=>a.destroy(new Error("aborted")),{once:!0})}n&&typeof n.pipe=="function"?n.pipe(a):(n&&a.write(n),a.end())})}function MS(e,t){let n=e[t];return Array.isArray(n)?n[0]??"":n??""}async function eg(e){let t=La.statSync(e.filePath).size,o={agent:RS(e.proxyUrl??""),timeout:e.timeoutMs},i=vS(e.baseUrl,e.apiKey),r=l=>cr(l,e.apiKey),s;try{s=await Zm(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 hi(l,e.signal,"Gemini upload start failed.",f,{operation:"upload"})}let a=MS(s.headers,"x-goog-upload-url");if(s.status<200||s.status>=300)throw yi(s.status,"Gemini upload start failed.",r(s.body).slice(0,300),{operation:"upload"});if(!a)throw new T("invalid_response","Gemini upload start returned no upload URL.",{details:[r(s.body).slice(0,300)],context:{operation:"upload",http_status:s.status}});let c=OS(a,e.baseUrl),d;try{d=await Zm(c,{...o,method:"POST",headers:{"Content-Length":String(t),"X-Goog-Upload-Offset":"0","X-Goog-Upload-Command":"upload, finalize"}},La.createReadStream(e.filePath),e.signal)}catch(l){let f=r(l instanceof Error?l.message:String(l));throw hi(l,e.signal,"Gemini upload transfer failed.",f,{operation:"upload"})}if(d.status<200||d.status>=300)throw yi(d.status,"Gemini upload transfer failed.",r(d.body).slice(0,300),{operation:"upload"});let p;try{p=JSON.parse(d.body)}catch{throw new T("invalid_response","Gemini upload returned invalid JSON.",{details:[r(d.body).slice(0,300)]})}if(!p.file)throw new T("invalid_response","Gemini upload returned no file.",{details:[r(d.body).slice(0,300)]});return p.file}var LS=new Set(["SAFETY","PROHIBITED_CONTENT","RECITATION","BLOCKLIST","SPII","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION"]),US=new Set(["LANGUAGE","OTHER","MALFORMED_FUNCTION_CALL","IMAGE_OTHER","NO_IMAGE","UNEXPECTED_TOOL_CALL","TOO_MANY_TOOL_CALLS","MISSING_THOUGHT_SIGNATURE","MALFORMED_RESPONSE"]);function Cp(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 tg(e){if(e?.length)return e.map(t=>({category:t.category??"UNSPECIFIED",probability:t.probability??"UNSPECIFIED",blocked:t.blocked??!1}))}function PS(e){if(typeof e!="object"||e===null)return{};let t=e,n=s=>typeof s=="number"?s:void 0,o=n(t.candidatesTokenCount),i=n(t.thoughtsTokenCount),r=n(t.cachedContentTokenCount);return{inputTokens:n(t.promptTokenCount),outputTokens:o===void 0&&i===void 0?void 0:(o??0)+(i??0),...r!==void 0?{cachedInputTokens:r}:{}}}function CS(e){return/-c\d+$/.test(e)}function TS(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 VS=2e3;function $S(e){return new Promise(t=>setTimeout(t,e))}function Tp(e,t,n,o,i,r){if(e instanceof T)return new T(e.code,cr(e.message,o),{retryable:e.retryable,details:e.details.map(d=>cr(d,o)),attempts:e.attempts,usage:e.usage,classification:Yi(e.failure),context:{...Qr(e.failure),provider:i,model:r,operation:n},modelFailures:e.modelFailures});let s=cr(e instanceof Error?e.message:String(e),o),a=Oa(e),c={provider:i,model:r,operation:n};return a!==null?yi(a,`Gemini ${n} failed.`,s.slice(0,500),c):hi(e,t,`Gemini ${n} failed.`,s.slice(0,500),c)}var dr=class{constructor(t,n,o,i){this.provider=t;this.model=n;this.apiKey=o;this.client=i??GS(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:ng.readFileSync(t,"base64"),mimeType:n}:{kind:"file-api",file:await this.uploadFile(t,n,i)}}async uploadFile(t,n,o){let{value:i}=await sn(this.provider.maxAttempts,async()=>{try{return await this.client.files.upload({file:t,config:{mimeType:n}})}catch(s){throw Tp(s,o,"upload",this.apiKey,this.model.provider,this.model.model)}}),r=await this.pollActive(i,o);if(!r.name||!r.uri)throw new T("invalid_response","Gemini upload returned no file reference.",{context:{provider:this.model.provider,model:this.model.model,operation:"upload"}});return{name:r.name,uri:r.uri,mimeType:r.mimeType??n}}async pollActive(t,n){let o=t,i=Date.now()+this.provider.timeoutMs;for(;(o.state??"").toUpperCase()==="PROCESSING";){if(n?.aborted)throw new T("cancelled","Gemini upload aborted.",{context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});if(Date.now()>=i)throw new T("timeout","Gemini file processing timed out.",{retryable:!0,classification:{failure_type:"timeout",failure_code:"media_processing_timeout"},context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});if(await $S(VS),!o.name)throw new T("invalid_response","Gemini upload returned no file name to poll.",{context:{provider:this.model.provider,model:this.model.model,operation:"file_poll"}});try{o=await this.client.files.get({name:o.name})}catch(r){throw Tp(r,n,"file_poll",this.apiKey,this.model.provider,this.model.model)}}if((o.state??"").toUpperCase()==="FAILED")throw new T("invalid_response","Gemini file processing failed.",{details:[cr(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=n?.fps===void 0?void 0:{fps:n.fps},i=!!t.responseJsonSchema&&CS(this.model.model),r={mediaResolution:"MEDIA_RESOLUTION_HIGH",...t.temperature===void 0?{}:{temperature:t.temperature},...t.seed===void 0?{}:{seed:t.seed}},s=[t.system?.trim(),i?`\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,134 +150,141 @@ ${JSON.stringify(t.responseJsonSchema,null,2)}
|
|
|
150
150
|
|
|
151
151
|
`);if(s&&(r.systemInstruction=s),t.responseJsonSchema&&!i){r.responseMimeType="application/json";let l=n?this.provider.videoResponseSchemaField:this.provider.documentResponseSchemaField;r[l??"responseJsonSchema"]=t.responseJsonSchema}let a={model:this.model.model,contents:[{role:"user",parts:[t.media.kind==="file-api"?{fileData:{fileUri:t.media.file.uri,mimeType:t.media.file.mimeType},...o?{videoMetadata:o}:{}}:{inlineData:{data:t.media.data,mimeType:t.media.mimeType},...o?{videoMetadata:o}:{}},{text:i?`${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:r},{value:c,attempts:d,failedUsage:p}=await sn(this.provider.maxAttempts,async()=>{let l;try{if(this.client.models.generateContentStream){let y="",E={},_=await this.client.models.generateContentStream(a);for await(let x of _)x.text&&(y+=x.text),E={...E,...x,usageMetadata:x.usageMetadata??E.usageMetadata,promptFeedback:x.promptFeedback??E.promptFeedback,candidates:x.candidates??E.candidates};l={...E,text:y}}else l=await this.client.models.generateContent(a)}catch(y){throw
|
|
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:r},{value:c,attempts:d,failedUsage:p}=await sn(this.provider.maxAttempts,async()=>{let l;try{if(this.client.models.generateContentStream){let y="",E={},_=await this.client.models.generateContentStream(a);for await(let x of _)x.text&&(y+=x.text),E={...E,...x,usageMetadata:x.usageMetadata??E.usageMetadata,promptFeedback:x.promptFeedback??E.promptFeedback,candidates:x.candidates??E.candidates};l={...E,text:y}}else l=await this.client.models.generateContent(a)}catch(y){throw Tp(y,t.signal,"generate",this.apiKey,this.model.provider,this.model.model)}let f=l.candidates?.[0],u=f?.finishReason??"",h=l.promptFeedback?.blockReason??"",m=PS(l.usageMetadata),g={provider:this.model.provider,model:this.model.model,operation:"generate"};if(u==="MAX_TOKENS")throw new T("truncated","Gemini output was truncated.",{usage:m,context:g});if(h)throw new T("content_filtered",`Gemini blocked the prompt (blockReason=${h}).`,{usage:m,classification:{failure_type:"policy",failure_code:"content_blocked"},context:{...g,provider_source:"prompt",provider_reason:Cp(h),...Cp(h)==="UNKNOWN"?{provider_reason_raw:h}:{},safety_ratings:tg(l.promptFeedback?.safetyRatings)}});if(LS.has(u))throw new T("content_filtered",`Gemini filtered the response (finishReason=${u}).`,{usage:m,classification:{failure_type:"policy",failure_code:"content_blocked"},context:{...g,provider_source:"candidate",provider_reason:Cp(u),finish_message:f?.finishMessage,safety_ratings:tg(f?.safetyRatings)}});let w=(l.text??"").trim();if(!w)throw US.has(u)?new T("invalid_response",`Gemini returned no usable response (finishReason=${u}).`,{usage:m,context:{...g,provider_reason_raw:u,finish_message:f?.finishMessage}}):new T("empty_response",`Gemini returned an empty response (finishReason=${u||"none"}).`,{retryable:!0,usage:m,context:g});if(t.acceptsText&&!t.acceptsText(w))throw new T("invalid_response","Gemini response does not match the requested output format.",{retryable:!0,usage:m,context:{...g,provider_reason_raw:w.slice(0,200)}});if(!u)throw new T("invalid_response","Gemini stream ended before the response finished.",{retryable:!0,usage:m,context:{...g,provider_reason_raw:"missing_finish_reason"}});if(t.responseJsonSchema)try{let y=i?TS(w):w;return JSON.parse(y),{text:y,finishReason:u,usage:m,raw:l}}catch{throw new T("invalid_response","Gemini returned malformed JSON for a structured media response.",{retryable:!0,usage:m,context:g})}return{text:w,finishReason:u,usage:m,raw:l}});return{text:c.text,finishReason:c.finishReason,attempts:d,usage:rn(p,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){}}},DS=NS(import.meta.url);function GS(e,t,n,o){let{GoogleGenAI:i}=DS("@google/genai"),r=new i({...o?{vertexai:!0,project:Na(),location:gs(),...e?{googleAuthOptions:{apiKey:e}}:{}}:{vertexai:!1,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:a=>
|
|
157
|
-
`).trim():""}function og(e){try{return JSON.parse(e)}catch{throw new T("invalid_response","Provider returned invalid JSON.",{details:[e.slice(0,500)]})}}var La=class{constructor(t,n,o){this.provider=t;this.model=n;this.apiKey=o;if(!t.baseUrl&&t.protocol!=="google-vertex")throw new T("endpoint","OpenAI-compatible provider endpoint (baseUrl) is not set \u2014 the built-in gateway reads PROJECT_LITELLM_GATEWAY_BASE_URL.");this.url=t.protocol==="google-vertex"?`${Fm()}/v1/projects/${Ra()}/locations/${fs()}/endpoints/openapi/chat/completions`:t.protocol==="google-gemini"?`${t.baseUrl.trim().replace(/\/+$/,"")}/v1beta/openai/chat/completions`:VS(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 sn(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:{...this.provider.protocol==="google-vertex"&&this.apiKey?{"x-goog-api-key":this.apiKey}:{authorization:`Bearer ${this.provider.protocol==="google-vertex"?await Qm.getAccessToken():this.apiKey}`},"content-type":"application/json"},body:JSON.stringify(t),signal:r})}catch(c){let d=c instanceof Error?c.message:String(c),p=r.aborted&&!n?.aborted;throw new T(p?"timeout":"request_failed",p?`OpenAI-compatible request timed out reaching ${this.host}.`:`OpenAI-compatible request could not reach ${this.host}: ${d}`,{retryable:!n?.aborted,details:[d.slice(0,500)]})}let a=await s.text();if(!s.ok){let c=s.status===408||s.status===429||s.status>=500,d=s.status===401||s.status===403?"auth":s.status===429?"rate_limited":"request_failed";throw new T(d,`OpenAI-compatible request to ${this.host} failed (status ${s.status}).`,{retryable:c,details:[`status: ${s.status}`,a.slice(0,500)]})}return og(a)});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=rn(i,eg(n,this.provider.protocol==="google-vertex"||this.provider.protocol==="google-gemini"));try{let s=tg(n),a=ng(s);if(a==="length")throw new T("truncated","Provider output was truncated.");if(a==="content_filter"||a.startsWith("content_filter:"))throw new T("content_filtered",`Provider filtered the response (${a}).`);let c=$S(s);if(!c)throw new T("empty_response","Provider returned an empty text response.");return{text:c,finishReason:a,attempts:o,usage:r,raw:n}}catch(s){throw s instanceof T&&(s.attempts=o,s.usage=r),s}}async generateTool(t){let{payload:n,attempts:o,failedUsage:i}=await this.post({...this.baseBody(t),tools:[{type:"function",function:{name:t.tool.name,description:t.tool.description,parameters:t.tool.inputSchema}}],tool_choice:{type:"function",function:{name:t.tool.name}},parallel_tool_calls:!1},t.signal),r=rn(i,eg(n,this.provider.protocol==="google-vertex"||this.provider.protocol==="google-gemini"));try{let s=tg(n),a=ng(s);if(a==="length")throw new T("truncated","Provider tool output was truncated.");if(a==="content_filter"||a.startsWith("content_filter:"))throw new T("content_filtered",`Provider filtered the response (${a}).`);let c=ig(s)?.tool_calls;if(!Array.isArray(c))throw new T("invalid_response","Provider did not return a tool call.");for(let d of c){if(!oo(d)||!oo(d.function))continue;let p=d.function;if(!(p.name!==t.tool.name||typeof p.arguments!="string"))return{input:og(p.arguments),finishReason:a,attempts:o,usage:r,raw:n}}throw new T("invalid_response","Provider did not return the required tool call.")}catch(s){throw s instanceof T&&(s.attempts=o,s.usage=r),s}}};var DS={lite:{model:"ep-20261029164743-gt8dh",modelEnv:"DOUBAO_LITE_MODEL",baseUrl:"https://ark.cn-beijing.volces.com/api/v3",apiKeyEnv:"ARK_API_KEY",timeoutMs:6e5,maxAttempts:3},turbo:{model:"ep-20261028172514-tlxzc",modelEnv:"DOUBAO_TURBO_MODEL",baseUrl:"https://ark.ap-southeast.bytepluses.com/api/v3",apiKeyEnv:"DOUBAO_TURBO_API_KEY",timeoutMs:6e5,maxAttempts:3}},Tp=["gemini-3.8-flash","gemini-3.7-flash","gemini-3.6-flash"];function Vp(e){return e?.trim().replace(/\/+$/,"")??"anthropic-sdk-default"}function gs(e,t,n){let o=Ln[e],i=JSON.stringify({task:e,taskVersion:o.version,protocol:t.protocol,baseUrl:Vp(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 rg.createHash("sha256").update(i).digest("hex")}function Je(e,t,n){return new S(e,{exitCode:k,errorCode:"LLM_CONFIG_INVALID",hint:"Fix the selected LLM configuration and run `scriptctl doctor`.",data:{expected:t,actual:n}})}function dr(e){return new S("The selected LLM provider credential is not configured.",{exitCode:q,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 yi(e,t){return Vt(Fi(e.failure),{...Hr(e.failure),provider:t.provider,model:t.model,retryable:e.failure.retryable,message:e.message})}function Ua(e,t){if(t.length===1)return e;let n=Af(t,"All configured model routes failed.");return new T(e.code,n.message,{retryable:n.retryable,classification:Fi(n),context:Hr(n),modelFailures:t,details:t.map(An)})}function GS(e){return["google-gemini","google-vertex"].includes(e.protocol)||/(^|\/)gemini-/i.test(e.model)}function Pa(e){let t=e.info.model.slice(0,e.info.model.lastIndexOf("/")+1);return[...new Set([e.info.model,...Tp.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:gs(e.info.task,e.providerConfig,i)}}})}function Co(e,t){return!t?.aborted&&e instanceof T&&e.code!=="cancelled"}var hs=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=Ln[t];if(o.mode==="video"&&this.options.videoProvider?.provider==="doubao"){let l=this.resolveDoubao(t,!0);return this.resolvedRoutes.set(t,l),l}let i=this.options.profile??this.config.tasks[t]??o.defaultProfile,r=this.config.models[i];if(!r)throw Je("The task route references a missing model profile.",[i],[`task: ${t}`]);let s=this.config.providers[r.provider];if(!s)throw Je("The model profile references a missing provider.",[r.provider],[`profile: ${i}`]);if(s.protocol==="openai-compatible"&&!s.baseUrl)throw Je("OpenAI-compatible providers require an explicit endpoint \u2014 set the provider's baseUrl, or PROJECT_LITELLM_GATEWAY_BASE_URL for the built-in gateway.",["provider.baseUrl"],[`provider: ${r.provider}`]);if(r.thinkingBudgetTokens!==void 0&&o.mode==="tool")throw Je("Anthropic thinking cannot be combined with a forced tool call.",["a text task or a profile without thinking"],[`task: ${t}`,`profile: ${i}`]);if(o.mode!=="document"&&r.thinkingBudgetTokens!==void 0&&r.thinkingBudgetTokens>=o.maxOutputTokens)throw Je("The thinking token budget must be smaller than the task output budget.",[`thinking budget < ${o.maxOutputTokens}`],[`task: ${t}`,`thinking budget: ${r.thinkingBudgetTokens}`]);let a=o.mode==="video"?this.options.videoProvider:void 0,c=a?.baseUrl?{...s,protocol:"google-gemini",baseUrl:kp(a.baseUrl,"--provider-base-url")}:s,d=a?.model?{...r,model:a.model.trim()}:r;if(a?.model!==void 0&&!d.model)throw Je("The video provider model cannot be empty.",["non-empty --provider-model"],["model: empty"]);let p={info:{task:t,profile:i,provider:r.provider,protocol:c.protocol,baseUrl:c.baseUrl,model:d.model,fingerprint:gs(t,c,d),...o.mode==="video"&&c.videoUploadMode?{videoUploadMode:c.videoUploadMode}:{}},providerConfig:c,modelConfig:d};return this.resolvedRoutes.set(t,p),p}route(t){return this.resolve(t).info}routes(){return zm.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,a=0,c){this.usageLog.push({...t,sequence:this.usageLog.length+1,status:n,attempts:a,startedAt:o,endedAt:i,durationMs:r,inputTokens:s.inputTokens??0,outputTokens:s.outputTokens??0,cachedInputTokens:s.cachedInputTokens??0,cacheCreationTokens:s.cacheCreationTokens??0,...c?{errorCode:c}:{}})}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(),a=r instanceof T?r:null;throw this.recordEvent(t,"failed",i,new Date(s).toISOString(),s-o,a?.usage??{},a?.attempts??1,a?.code),r}}resolveDoubao(t,n,o="turbo"){let i=DS[o],r=n?this.options.videoProvider:void 0,s=n?(r?.model??process.env.DOUBAO_TURBO_MODEL??"").trim():(process.env[i.modelEnv]??"").trim()||i.model;if(!s)throw Je("Doubao requires --provider-model or DOUBAO_TURBO_MODEL.",["--provider-model <id> or DOUBAO_TURBO_MODEL"],["model: empty"]);let a={protocol:"openai-compatible",baseUrl:r?.baseUrl?kp(r.baseUrl,"--provider-base-url"):i.baseUrl,apiKeyEnv:i.apiKeyEnv,timeoutMs:i.timeoutMs,maxAttempts:i.maxAttempts},c={provider:"doubao",model:s};return{info:{task:t,profile:n?"doubao":o==="lite"?"doubao-lite-fallback":"doubao-fallback",provider:"doubao",protocol:a.protocol,baseUrl:a.baseUrl,model:s,fingerprint:gs(t,a,c)},providerConfig:a,modelConfig:c}}doubaoRoutes(t){return Jm.has(t)?[]:[this.resolveDoubao(t,!1,"lite"),this.resolveDoubao(t,!1,"turbo")].filter(n=>(process.env[n.providerConfig.apiKeyEnv]??"").trim())}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 dr(t.info.provider);let r=t.providerConfig.protocol==="anthropic"?new ka(t.providerConfig,t.modelConfig,i):new La(t.providerConfig,t.modelConfig,i);return this.adapters.set(n,r),r}videoAdapter(t){if(!["google-gemini","google-vertex"].includes(t.providerConfig.protocol))throw Je("Video tasks require a google-gemini provider.",["provider.protocol: google-gemini"],[`provider: ${t.info.provider}`,`protocol: ${t.providerConfig.protocol}`]);let n=t.info.model,o=`${t.info.provider} ${t.providerConfig.baseUrl??"official"} ${n}`,i=this.videoAdapters.get(o);if(i)return i;let r=this.videoCredential(t);if(!r&&t.providerConfig.protocol!=="google-vertex")throw dr(t.info.provider);let s=new Na(t.providerConfig,t.modelConfig,r);return this.videoAdapters.set(o,s),s}videoCredential(t){let n=this.resolve(t.info.task).info,o=t.info.provider===n.provider&&t.info.baseUrl===n.baseUrl?this.options.videoProvider?.apiKey:void 0,i=o?.kind==="literal"?o.value.trim():o?.kind==="env"?(process.env[o.name]??"").trim():(process.env[t.providerConfig.apiKeyEnv]??"").trim();if(!i&&(o||t.providerConfig.protocol!=="google-vertex"))throw dr(t.info.provider);return i}primaryVideoRoutes(t){if(t.info.provider!=="nnyyai-ci"||t.info.model!==bp||Vp(t.info.baseUrl)!==mi.baseUrl)return Pa(t);if(!(process.env[mi.apiKeyEnv]??"").trim())return[t];let n={provider:"nnyyai",model:Tp[0]},o={providerConfig:mi,modelConfig:n,info:{...t.info,profile:"nnyyai-fallback",provider:"nnyyai",model:n.model,fingerprint:gs(t.info.task,mi,n),videoUploadMode:"base64"}};return[t,...Pa(o)]}grsaiVideoRoutes(t){return!(process.env[no.apiKeyEnv]??"").trim()||Vp(t.providerConfig.baseUrl)===no.baseUrl?[]:Tp.map(n=>{let o={provider:"grsai",model:n};return{providerConfig:no,modelConfig:o,info:{task:t.info.task,profile:"grsai-fallback",provider:"grsai",protocol:no.protocol,baseUrl:no.baseUrl,model:n,videoUploadMode:"base64",fingerprint:gs(t.info.task,no,o)}}})}fallbackVideoMedia(t){if(t.media.kind==="base64")return t.media;let n=t.media.kind==="local-fallback"?t.media.path:t.localPath;if(!n)throw Je("Video channel fallback requires the local video.",["localPath"],["localPath: missing"]);let o=t.localMime??(t.media.kind==="file-api"?t.media.file.mimeType:t.media.mimeType);return{kind:"base64",data:Cp.readFileSync(n,"base64"),mimeType:o}}documentPort(t){if(Ln[t].mode!=="document")throw Je("The task does not support document generation.",["document task"],[t]);let n=this.resolve(t);if(n.providerConfig.protocol!=="google-gemini"&&n.providerConfig.protocol!=="google-vertex")throw Je("PDF tasks require a Gemini provider.",["google-gemini or google-vertex"],[n.providerConfig.protocol]);let o=(process.env[n.providerConfig.apiKeyEnv]??"").trim();if(!o&&n.providerConfig.protocol!=="google-vertex")throw dr(n.info.provider);let i=new ms(n.providerConfig,n.modelConfig,o),r=new WeakMap;return{prepare:async(s,a)=>{let c;try{c=await i.prepare(s,a)}catch(d){if(!Co(d,a))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 (${An(d.failure)})
|
|
158
|
-
`),c={kind:"base64",data:
|
|
156
|
+
`),{files:{upload:a=>eg({apiKey:e,filePath:a.file,mimeType:a.config?.mimeType??"video/mp4",timeoutMs:t,proxyUrl:s,baseUrl:n}),get:a=>r.files.get(a),delete:a=>r.files.delete(a)},models:{generateContent:a=>r.models.generateContent(a),generateContentStream:a=>r.models.generateContentStream(a)}}}var hs=class{constructor(t,n,o,i){this.provider=t;this.transport=new dr(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 Ua=class extends dr{generate(t){let n=t.media;if(n.kind==="local-fallback"||n.kind==="local")throw new T("invalid_response","A local fallback video cannot be sent to Gemini.");let o=n.kind==="file-api"?n.file.mimeType:n.mimeType;return this.generateMedia({...t,media:n},o.startsWith("audio/")?{}:{fps:t.fps})}};function og(e,t){if(!oo(e)||!oo(e.usage))return{};let n=e.usage,o=c=>{let d=typeof c=="number"?c:0;return Number.isFinite(d)?d:0},i=oo(n.prompt_tokens_details)?n.prompt_tokens_details:{},r=o(n.prompt_tokens),s=o(i.cached_tokens)||o(n.cache_read_input_tokens),a=o(i.cache_creation_tokens)||o(n.cache_creation_input_tokens);return{inputTokens:t?r:r+s+a,outputTokens:o(n.completion_tokens),cachedInputTokens:s,cacheCreationTokens:a}}function oo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function BS(e){let t=e.trim().replace(/\/+$/,"");return t.endsWith("/chat/completions")?t:t.endsWith("/v1")?`${t}/chat/completions`:`${t}/v1/chat/completions`}function ig(e){return!oo(e)||!Array.isArray(e.choices)?null:e.choices.find(oo)??null}function rg(e){return e&&typeof e.finish_reason=="string"?e.finish_reason:""}function ag(e){return e&&oo(e.message)?e.message:null}function JS(e){let t=ag(e)?.content;return typeof t=="string"?t.trim():Array.isArray(t)?t.flatMap(n=>oo(n)&&typeof n.text=="string"?[n.text]:[]).join(`
|
|
157
|
+
`).trim():""}function sg(e){try{return JSON.parse(e)}catch{throw new T("invalid_response","Provider returned invalid JSON.",{details:[e.slice(0,500)]})}}var Pa=class{constructor(t,n,o){this.provider=t;this.model=n;this.apiKey=o;if(!t.baseUrl&&t.protocol!=="google-vertex")throw new T("endpoint","OpenAI-compatible provider endpoint (baseUrl) is not set \u2014 the built-in gateway reads PROJECT_LITELLM_GATEWAY_BASE_URL.");this.url=t.protocol==="google-vertex"?`${Wm()}/v1/projects/${Na()}/locations/${gs()}/endpoints/openapi/chat/completions`:t.protocol==="google-gemini"?`${t.baseUrl.trim().replace(/\/+$/,"")}/v1beta/openai/chat/completions`:BS(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 sn(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:{...this.provider.protocol==="google-vertex"&&this.apiKey?{"x-goog-api-key":this.apiKey}:{authorization:`Bearer ${this.provider.protocol==="google-vertex"?await qm.getAccessToken():this.apiKey}`},"content-type":"application/json"},body:JSON.stringify(t),signal:r})}catch(c){let d=c instanceof Error?c.message:String(c),p=r.aborted&&!n?.aborted;throw new T(p?"timeout":"request_failed",p?`OpenAI-compatible request timed out reaching ${this.host}.`:`OpenAI-compatible request could not reach ${this.host}: ${d}`,{retryable:!n?.aborted,details:[d.slice(0,500)]})}let a=await s.text();if(!s.ok){let c=s.status===408||s.status===429||s.status>=500,d=s.status===401||s.status===403?"auth":s.status===429?"rate_limited":"request_failed";throw new T(d,`OpenAI-compatible request to ${this.host} failed (status ${s.status}).`,{retryable:c,details:[`status: ${s.status}`,a.slice(0,500)]})}return sg(a)});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=rn(i,og(n,this.provider.protocol==="google-vertex"||this.provider.protocol==="google-gemini"));try{let s=ig(n),a=rg(s);if(a==="length")throw new T("truncated","Provider output was truncated.");if(a==="content_filter"||a.startsWith("content_filter:"))throw new T("content_filtered",`Provider filtered the response (${a}).`);let c=JS(s);if(!c)throw new T("empty_response","Provider returned an empty text response.");return{text:c,finishReason:a,attempts:o,usage:r,raw:n}}catch(s){throw s instanceof T&&(s.attempts=o,s.usage=r),s}}async generateTool(t){let{payload:n,attempts:o,failedUsage:i}=await this.post({...this.baseBody(t),tools:[{type:"function",function:{name:t.tool.name,description:t.tool.description,parameters:t.tool.inputSchema}}],tool_choice:{type:"function",function:{name:t.tool.name}},parallel_tool_calls:!1},t.signal),r=rn(i,og(n,this.provider.protocol==="google-vertex"||this.provider.protocol==="google-gemini"));try{let s=ig(n),a=rg(s);if(a==="length")throw new T("truncated","Provider tool output was truncated.");if(a==="content_filter"||a.startsWith("content_filter:"))throw new T("content_filtered",`Provider filtered the response (${a}).`);let c=ag(s)?.tool_calls;if(!Array.isArray(c))throw new T("invalid_response","Provider did not return a tool call.");for(let d of c){if(!oo(d)||!oo(d.function))continue;let p=d.function;if(!(p.name!==t.tool.name||typeof p.arguments!="string"))return{input:sg(p.arguments),finishReason:a,attempts:o,usage:r,raw:n}}throw new T("invalid_response","Provider did not return the required tool call.")}catch(s){throw s instanceof T&&(s.attempts=o,s.usage=r),s}}};var zS={lite:{model:"ep-20261029164743-gt8dh",modelEnv:"DOUBAO_LITE_MODEL",baseUrl:"https://ark.cn-beijing.volces.com/api/v3",apiKeyEnv:"ARK_API_KEY",timeoutMs:6e5,maxAttempts:3},turbo:{model:"ep-20261028172514-tlxzc",modelEnv:"DOUBAO_TURBO_MODEL",baseUrl:"https://ark.ap-southeast.bytepluses.com/api/v3",apiKeyEnv:"DOUBAO_TURBO_API_KEY",timeoutMs:6e5,maxAttempts:3}},$p=["gemini-3.8-flash","gemini-3.7-flash","gemini-3.6-flash"];function Dp(e){return e?.trim().replace(/\/+$/,"")??"anthropic-sdk-default"}function ys(e,t,n){let o=Ln[e],i=JSON.stringify({task:e,taskVersion:o.version,protocol:t.protocol,baseUrl:Dp(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 cg.createHash("sha256").update(i).digest("hex")}function Je(e,t,n){return new S(e,{exitCode:k,errorCode:"LLM_CONFIG_INVALID",hint:"Fix the selected LLM configuration and run `scriptctl doctor`.",data:{expected:t,actual:n}})}function pr(e){return new S("The selected LLM provider credential is not configured.",{exitCode:q,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 wi(e,t){return Vt(Yi(e.failure),{...Qr(e.failure),provider:t.provider,model:t.model,retryable:e.failure.retryable,message:e.message})}function Ca(e,t){if(t.length===1)return e;let n=vf(t,"All configured model routes failed.");return new T(e.code,n.message,{retryable:n.retryable,classification:Yi(n),context:Qr(n),modelFailures:t,details:t.map(An)})}function KS(e){return["google-gemini","google-vertex"].includes(e.protocol)||/(^|\/)gemini-/i.test(e.model)}function Ta(e){let t=e.info.model.slice(0,e.info.model.lastIndexOf("/")+1);return[...new Set([e.info.model,...$p.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:ys(e.info.task,e.providerConfig,i)}}})}function To(e,t){return!t?.aborted&&e instanceof T&&e.code!=="cancelled"}var ws=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=Ln[t];if(o.mode==="video"&&this.options.videoProvider?.provider==="doubao"){let l=this.resolveDoubao(t,!0);return this.resolvedRoutes.set(t,l),l}let i=this.options.profile??this.config.tasks[t]??o.defaultProfile,r=this.config.models[i];if(!r)throw Je("The task route references a missing model profile.",[i],[`task: ${t}`]);let s=this.config.providers[r.provider];if(!s)throw Je("The model profile references a missing provider.",[r.provider],[`profile: ${i}`]);if(s.protocol==="openai-compatible"&&!s.baseUrl)throw Je("OpenAI-compatible providers require an explicit endpoint \u2014 set the provider's baseUrl, or PROJECT_LITELLM_GATEWAY_BASE_URL for the built-in gateway.",["provider.baseUrl"],[`provider: ${r.provider}`]);if(r.thinkingBudgetTokens!==void 0&&o.mode==="tool")throw Je("Anthropic thinking cannot be combined with a forced tool call.",["a text task or a profile without thinking"],[`task: ${t}`,`profile: ${i}`]);if(o.mode!=="document"&&r.thinkingBudgetTokens!==void 0&&r.thinkingBudgetTokens>=o.maxOutputTokens)throw Je("The thinking token budget must be smaller than the task output budget.",[`thinking budget < ${o.maxOutputTokens}`],[`task: ${t}`,`thinking budget: ${r.thinkingBudgetTokens}`]);let a=o.mode==="video"?this.options.videoProvider:void 0,c=a?.baseUrl?{...s,protocol:"google-gemini",baseUrl:vp(a.baseUrl,"--provider-base-url")}:s,d=a?.model?{...r,model:a.model.trim()}:r;if(a?.model!==void 0&&!d.model)throw Je("The video provider model cannot be empty.",["non-empty --provider-model"],["model: empty"]);let p={info:{task:t,profile:i,provider:r.provider,protocol:c.protocol,baseUrl:c.baseUrl,model:d.model,fingerprint:ys(t,c,d),...o.mode==="video"&&c.videoUploadMode?{videoUploadMode:c.videoUploadMode}:{}},providerConfig:c,modelConfig:d};return this.resolvedRoutes.set(t,p),p}route(t){return this.resolve(t).info}routes(){return Hm.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,a=0,c){this.usageLog.push({...t,sequence:this.usageLog.length+1,status:n,attempts:a,startedAt:o,endedAt:i,durationMs:r,inputTokens:s.inputTokens??0,outputTokens:s.outputTokens??0,cachedInputTokens:s.cachedInputTokens??0,cacheCreationTokens:s.cacheCreationTokens??0,...c?{errorCode:c}:{}})}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(),a=r instanceof T?r:null;throw this.recordEvent(t,"failed",i,new Date(s).toISOString(),s-o,a?.usage??{},a?.attempts??1,a?.code),r}}resolveDoubao(t,n,o="turbo"){let i=zS[o],r=n?this.options.videoProvider:void 0,s=n?(r?.model??process.env.DOUBAO_TURBO_MODEL??"").trim():(process.env[i.modelEnv]??"").trim()||i.model;if(!s)throw Je("Doubao requires --provider-model or DOUBAO_TURBO_MODEL.",["--provider-model <id> or DOUBAO_TURBO_MODEL"],["model: empty"]);let a={protocol:"openai-compatible",baseUrl:r?.baseUrl?vp(r.baseUrl,"--provider-base-url"):i.baseUrl,apiKeyEnv:i.apiKeyEnv,timeoutMs:i.timeoutMs,maxAttempts:i.maxAttempts},c={provider:"doubao",model:s};return{info:{task:t,profile:n?"doubao":o==="lite"?"doubao-lite-fallback":"doubao-fallback",provider:"doubao",protocol:a.protocol,baseUrl:a.baseUrl,model:s,fingerprint:ys(t,a,c)},providerConfig:a,modelConfig:c}}doubaoRoutes(t){return jm.has(t)?[]:[this.resolveDoubao(t,!1,"lite"),this.resolveDoubao(t,!1,"turbo")].filter(n=>(process.env[n.providerConfig.apiKeyEnv]??"").trim())}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 pr(t.info.provider);let r=t.providerConfig.protocol==="anthropic"?new va(t.providerConfig,t.modelConfig,i):new Pa(t.providerConfig,t.modelConfig,i);return this.adapters.set(n,r),r}videoAdapter(t){if(!["google-gemini","google-vertex"].includes(t.providerConfig.protocol))throw Je("Video tasks require a google-gemini provider.",["provider.protocol: google-gemini"],[`provider: ${t.info.provider}`,`protocol: ${t.providerConfig.protocol}`]);let n=t.info.model,o=`${t.info.provider} ${t.providerConfig.baseUrl??"official"} ${n}`,i=this.videoAdapters.get(o);if(i)return i;let r=this.videoCredential(t);if(!r&&t.providerConfig.protocol!=="google-vertex")throw pr(t.info.provider);let s=new Ua(t.providerConfig,t.modelConfig,r);return this.videoAdapters.set(o,s),s}videoCredential(t){let n=this.resolve(t.info.task).info,o=t.info.provider===n.provider&&t.info.baseUrl===n.baseUrl?this.options.videoProvider?.apiKey:void 0,i=o?.kind==="literal"?o.value.trim():o?.kind==="env"?(process.env[o.name]??"").trim():(process.env[t.providerConfig.apiKeyEnv]??"").trim();if(!i&&(o||t.providerConfig.protocol!=="google-vertex"))throw pr(t.info.provider);return i}primaryVideoRoutes(t){if(t.info.provider!=="nnyyai-ci"||t.info.model!==Op||Dp(t.info.baseUrl)!==gi.baseUrl)return Ta(t);if(!(process.env[gi.apiKeyEnv]??"").trim())return[t];let n={provider:"nnyyai",model:$p[0]},o={providerConfig:gi,modelConfig:n,info:{...t.info,profile:"nnyyai-fallback",provider:"nnyyai",model:n.model,fingerprint:ys(t.info.task,gi,n),videoUploadMode:"base64"}};return[t,...Ta(o)]}grsaiVideoRoutes(t){return!(process.env[no.apiKeyEnv]??"").trim()||Dp(t.providerConfig.baseUrl)===no.baseUrl?[]:$p.map(n=>{let o={provider:"grsai",model:n};return{providerConfig:no,modelConfig:o,info:{task:t.info.task,profile:"grsai-fallback",provider:"grsai",protocol:no.protocol,baseUrl:no.baseUrl,model:n,videoUploadMode:"base64",fingerprint:ys(t.info.task,no,o)}}})}fallbackVideoMedia(t){if(t.media.kind==="base64")return t.media;let n=t.media.kind==="local-fallback"?t.media.path:t.localPath;if(!n)throw Je("Video channel fallback requires the local video.",["localPath"],["localPath: missing"]);let o=t.localMime??(t.media.kind==="file-api"?t.media.file.mimeType:t.media.mimeType);return{kind:"base64",data:Vp.readFileSync(n,"base64"),mimeType:o}}documentPort(t){if(Ln[t].mode!=="document")throw Je("The task does not support document generation.",["document task"],[t]);let n=this.resolve(t);if(n.providerConfig.protocol!=="google-gemini"&&n.providerConfig.protocol!=="google-vertex")throw Je("PDF tasks require a Gemini provider.",["google-gemini or google-vertex"],[n.providerConfig.protocol]);let o=(process.env[n.providerConfig.apiKeyEnv]??"").trim();if(!o&&n.providerConfig.protocol!=="google-vertex")throw pr(n.info.provider);let i=new hs(n.providerConfig,n.modelConfig,o),r=new WeakMap;return{prepare:async(s,a)=>{let c;try{c=await i.prepare(s,a)}catch(d){if(!To(d,a))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 (${An(d.failure)})
|
|
158
|
+
`),c={kind:"base64",data:Vp.readFileSync(s).toString("base64"),mimeType:"application/pdf"}}return r.set(c,s),c},generate:async s=>{let a=Ta(n),c=[];for(let[d,p]of a.entries()){s.signal?.throwIfAborted();let l=d===0?i:new hs(p.providerConfig,p.modelConfig,o);try{return await this.tracked(p.info,()=>l.generate(s))}catch(f){if(!To(f,s.signal))throw f;let u=wi(f,p.info);c.push(u);let h=a[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} (${An(u)})
|
|
159
159
|
`);continue}let m=f;for(let g of this.doubaoRoutes(t)){s.signal?.throwIfAborted();let w=this.arkAdapter(g);if(w){process.stderr.write(`\u21AA\uFE0F \u6587\u6863\u8BF7\u6C42\u5207\u6362\u5230\u8C46\u5305 ${g.info.model}
|
|
160
|
-
`);try{return await this.tracked(g.info,()=>w.generateDocument(s,r.get(s.media)))}catch(y){if(!
|
|
161
|
-
`);continue}if(!this.doubaoRoutes(t).some(h=>this.doubaoAdapter(h))||!r.localPath&&r.media.kind!=="local-fallback")throw
|
|
162
|
-
`);try{return await this.tracked(c.info,()=>d.run({localPath:i,localMime:r,user:n.user,fps:n.fps,maxOutputTokens:s.maxOutputTokens,...n.system?{system:n.system}:{},...n.responseJsonSchema?{responseJsonSchema:n.responseJsonSchema}:{},...n.acceptsText?{acceptsText:n.acceptsText}:{},...n.signal?{signal:n.signal}:{}}))}catch(p){if(!
|
|
160
|
+
`);try{return await this.tracked(g.info,()=>w.generateDocument(s,r.get(s.media)))}catch(y){if(!To(y,s.signal))throw y;c.push(wi(y,g.info)),m=y}}}throw Ca(m,c)}}throw new Error("Document model routes cannot be empty.")},release:async(s,a)=>{r.delete(s),await i.release(s,a)}}}videoPort(t){let n=Ln[t];if(n.mode!=="video")throw Je("The task does not support video generation.",["video task"],[`task: ${t}`]);let o=this.resolve(t);if(this.options.videoProvider?.provider==="doubao"){let r=this.doubaoAdapter(o);if(!r)throw pr("doubao");return{prepare:async(s,a,c,d)=>{if(c!=="file-api")throw Je("Doubao requires file-api upload mode.",["file-api"],[c]);return d?.throwIfAborted(),{kind:"local",path:s,mimeType:a}},generate:s=>{if(s.media.kind!=="local")throw Je("Doubao requires locally prepared video.",["local media"],[s.media.kind]);s.signal?.throwIfAborted();let{path:a,mimeType:c}=s.media;return this.tracked(o.info,()=>r.run({localPath:a,localMime:c,user:s.user,fps:s.fps,maxOutputTokens:n.maxOutputTokens,...s.system?{system:s.system}:{},...s.responseJsonSchema?{responseJsonSchema:s.responseJsonSchema}:{},...s.acceptsText?{acceptsText:s.acceptsText}:{},...s.signal?{signal:s.signal}:{}}))},release:async()=>{}}}if(!["google-gemini","google-vertex"].includes(o.providerConfig.protocol))throw Je("Video tasks require a google-gemini provider.",["provider.protocol: google-gemini"],[`provider: ${o.info.provider}`,`protocol: ${o.providerConfig.protocol}`]);let i=this.videoAdapter(o);return{prepare:async(r,s,a,c)=>{let d=Date.now();try{return await i.prepare(r,s,a,c)}catch(p){if(!To(p,c)||!this.primaryVideoRoutes(o).some(l=>l.providerConfig!==o.providerConfig)&&!this.grsaiVideoRoutes(o).length&&!this.doubaoRoutes(t).some(l=>this.doubaoAdapter(l)))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:wi(p,o.info)}}},release:(r,s)=>r.kind==="local-fallback"?Promise.resolve():i.release(r,s),generate:async r=>{r.signal?.throwIfAborted();let s=[...this.primaryVideoRoutes(o).filter(d=>r.media.kind!=="local-fallback"||d.providerConfig!==o.providerConfig),...this.grsaiVideoRoutes(o)],a=r.media.kind==="local-fallback"?[r.media.primaryFailure]:[],c;for(let[d,p]of s.entries()){r.signal?.throwIfAborted();try{let l=p.providerConfig===o.providerConfig?r.media:c??=this.fallbackVideoMedia(r);return await this.tracked(p.info,()=>this.videoAdapter(p).generate({...r,media:l,maxOutputTokens:n.maxOutputTokens}))}catch(l){if(!To(l,r.signal))throw l;let f=wi(l,p.info);a.push(f);let u=s[d+1];if(u){process.stderr.write(`\u21AA\uFE0F ${p.info.provider}/${p.info.model} \u8BF7\u6C42\u5931\u8D25\uFF0C\u5207\u6362\u5230 ${u.info.provider}/${u.info.model} (${An(f)})
|
|
161
|
+
`);continue}if(!this.doubaoRoutes(t).some(h=>this.doubaoAdapter(h))||!r.localPath&&r.media.kind!=="local-fallback")throw Ca(l,a);return this.generateDoubaoVideo(t,r,a)}}return this.generateDoubaoVideo(t,r,a)}}}async generateDoubaoVideo(t,n,o){let i=n.media.kind==="local-fallback"?n.media.path:n.localPath;if(!i)throw Je("Doubao video fallback requires the local video.",["localPath"],["localPath: missing"]);let r=n.localMime??(n.media.kind==="file-api"?n.media.file.mimeType:n.media.mimeType),s=Ln[t];if(s.mode!=="video")throw Je("Expected a video task.",["video task"],[t]);let a;for(let c of this.doubaoRoutes(t)){n.signal?.throwIfAborted();let d=this.doubaoAdapter(c);if(d){process.stderr.write(`\u21AA\uFE0F \u89C6\u9891\u8BF7\u6C42\u5207\u6362\u5230\u8C46\u5305 ${c.info.model}
|
|
162
|
+
`);try{return await this.tracked(c.info,()=>d.run({localPath:i,localMime:r,user:n.user,fps:n.fps,maxOutputTokens:s.maxOutputTokens,...n.system?{system:n.system}:{},...n.responseJsonSchema?{responseJsonSchema:n.responseJsonSchema}:{},...n.acceptsText?{acceptsText:n.acceptsText}:{},...n.signal?{signal:n.signal}:{}}))}catch(p){if(!To(p,n.signal))throw p;o.push(wi(p,c.info)),a=p}}}throw a?Ca(a,o):pr("doubao")}doubaoAdapter(t){return this.arkAdapter(t)}doubaoTextAdapter(t){return this.arkAdapter(t)}arkAdapter(t){let n=this.videoCredential(t);if(!n)return null;let{model:o}=t.info,{baseUrl:i,timeoutMs:r,maxAttempts:s}=t.providerConfig,a=`doubao ${i} ${o}`,c=this.doubaoAdapters.get(a);if(c)return c;let d=new Ma(o,r,s,n,i);return this.doubaoAdapters.set(a,d),d}async withTextFallback(t,n,o){let i=this.resolve(t),r=KS(i.info),s=r?Ta(i):[i],a=[];for(let[c,d]of s.entries()){n?.throwIfAborted();let p=this.adapter(d);try{return await this.tracked(d.info,()=>o(p))}catch(l){if(!To(l,n)||!r&&l.code!=="content_filtered")throw l;let f=wi(l,d.info);a.push(f);let u=s[c+1];if(u){process.stderr.write(`\u21AA\uFE0F ${d.info.model} \u8BF7\u6C42\u5931\u8D25\uFF0C\u5207\u6362\u5230 ${u.info.model} (${An(f)})
|
|
163
163
|
`);continue}let h=l;for(let m of this.doubaoRoutes(t)){n?.throwIfAborted();let g=this.doubaoTextAdapter(m);if(g){process.stderr.write(`\u21AA\uFE0F \u6587\u672C\u8BF7\u6C42\u5207\u6362\u5230\u8C46\u5305 ${m.info.model}
|
|
164
|
-
`);try{return await this.tracked(m.info,()=>o(g))}catch(w){if(!
|
|
165
|
-
`),data:{checks:C}},V]}import{spawn as
|
|
166
|
-
`),data:{op:"update",changed:!1,update:c}},V];let d=await t(
|
|
167
|
-
`)
|
|
168
|
-
# ${a}`:i}function
|
|
169
|
-
`)}var
|
|
164
|
+
`);try{return await this.tracked(m.info,()=>o(g))}catch(w){if(!To(w,n))throw w;a.push(wi(w,m.info)),h=w}}}throw Ca(h,a)}}throw new Error("Text model routes cannot be empty.")}async generateText(t,n){let o=Ln[t];if(o.mode!=="text")throw Je("The task does not support text generation.",["text task"],[`task: ${t}`]);return this.withTextFallback(t,n.signal,i=>i.generateText({...n,maxOutputTokens:o.maxOutputTokens}))}async generateTool(t,n){let o=Ln[t];if(o.mode!=="tool")throw Je("The task does not support tool generation.",["tool task"],[`task: ${t}`]);return this.withTextFallback(t,n.signal,i=>i.generateTool({...n,maxOutputTokens:o.maxOutputTokens}))}};function dg(e,t){return new ws(Co(e),t)}var HS=jS(import.meta.url);function Va(e){try{return HS.resolve(e),!0}catch{return!1}}function QS(e){let t=!1;try{jt.statSync(e).isDirectory()&&(jt.accessSync(e,jt.constants.W_OK),t=!0)}catch{t=!1}let n=!1;try{n=jt.statSync(xi.join(e,"script.json")).isFile()}catch{n=!1}return{writable:t,hasScript:n}}function FS(){return xi.join(xi.dirname(xi.resolve("workspace")),"output")}function pg(e={}){let t=xp(),n=[],o=new Set;for(let M of t)try{if(!jt.existsSync(M)||!jt.statSync(M).isFile())continue;let K=jt.realpathSync(M);if(o.has(K))continue;o.add(K),n.push(M)}catch{}let i=typeof e.llm_config=="string"?e.llm_config.trim():"",r=Co(i||void 0),a=new ws(r).routes(),c=Object.entries(r.providers).map(([M,K])=>({alias:M,configured:!!(process.env[K.apiKeyEnv]??"").trim(),env:K.apiKeyEnv})),d=Object.entries(r.providers).filter(([,M])=>M.protocol==="openai-compatible").map(([M,K])=>{let X="not set";if(K.baseUrl)try{X=new URL(K.baseUrl).host}catch{X=K.baseUrl}return{alias:M,host:X}}),{mode:p}=Km(),l=(process.env.SCRIPTCTL_OUTPUT_DIR??"").trim()||FS(),f=p==="local"?QS(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":Va("@anthropic-ai/sdk"),"@google/genai":Va("@google/genai"),jszip:Va("jszip"),"fast-xml-parser":Va("fast-xml-parser")},w=Object.entries(g).filter(([,M])=>!M).map(([M])=>M),y=process.versions.node,E=`env_file: ${n[0]??"missing"}`,_=M=>M?"configured":"not configured",A=[`node: ${y}`,"storage: local-filesystem",E,`llm config: ${r.source}`,`llm routes: ${a.length}`,...c.map(M=>`llm provider ${M.alias}: ${_(M.configured)}`),...d.map(M=>`llm provider ${M.alias} endpoint: ${M.host}`)];p===null?A.push("output target: not configured"):p==="local"&&f?(A.push(`output writable: ${_(f.writable)}`),A.push(`output snapshot: ${f.hasScript?"present":"absent"}`)):(A.push(`gateway endpoint: ${_(u)}`),A.push(`gateway access credential: ${_(h)}`),A.push(`gateway project identifier: ${_(m)}`));for(let[M,K]of Object.entries(g))A.push(`dependency ${M}: ${K?"ok":"missing"}`);let b=[];w.length>0&&b.push("Install missing CLI dependencies (see above)."),c.some(M=>!M.configured)&&b.push("Configure every credential referenced by the selected LLM configuration."),d.some(M=>M.host==="not set")&&b.push("An openai-compatible provider has no endpoint \u2014 set PROJECT_LITELLM_GATEWAY_BASE_URL (built-in gateway) or the provider's baseUrl."),p===null?b.push("Configure an output target before running `publish` / script CRUD."):p==="local"?f&&!f.writable&&b.push("Output target is not writable; check directory permissions."):(!u||!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,v]=y.split(".").map(M=>parseInt(M,10)),I=(U??0)>20||(U??0)===20&&(v??0)>=0,R=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}},C={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:c.map(M=>({alias:M.alias,ok:M.configured,credential_env:M.env,...d.find(K=>K.alias===M.alias)?{endpoint:d.find(K=>K.alias===M.alias).host}:{}})),profiles:Object.keys(r.models),routes:a.map(M=>({task:M.task,profile:M.profile,provider:M.provider,protocol:M.protocol,model:M.model}))},output:R,dependencies:g};return[{text:[...A,...b].join(`
|
|
165
|
+
`),data:{checks:C}},V]}import{spawn as YS}from"node:child_process";var $a="@lingjingai/scriptctl",qS=`${$a}@latest`,Gp="npm";function WS(){return ar()}function ZS(e){let t=/^(\d+)\.(\d+)\.\d+/.exec(e);return t?`${$a}@~${t[1]}.${t[2]}.0`:null}function XS(e){return["install","-g",e]}function eI(e,t){return[e,...t].join(" ")}function tI(e,t){return e.split(/\r?\n/).map(o=>o.trim()).filter(o=>o.length>0).slice(-t)}function nI(e,t){return new Promise(n=>{let o=YS(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,a)=>{n({exitCode:s,signal:a,stdout:i.join(""),stderr:r.join("")})})})}async function lg(e,t=nI,n=WS){let o=!!e.patch,i=n(),r=o?ZS(i):qS;if(!r)throw new S(`Cannot compute a patch update range from version ${i}.`,{exitCode:q,errorCode:"UPDATE_VERSION_INVALID",hint:"Run `scriptctl update` without --patch to install the latest version.",data:{version:i}});let s=[...XS(r)],a=eI(Gp,s),c={package:$a,package_spec:r,command:Gp,args:s,command_line:a};if(e.dry_run)return[{text:[`package: ${$a}`,`command: ${a}`,"dry-run: no update performed"].join(`
|
|
166
|
+
`),data:{op:"update",changed:!1,update:c}},V];let d=await t(Gp,s);if(d.error)throw new S(`Failed to start npm: ${d.error.message}`,{exitCode:q,errorCode:"UPDATE_SPAWN_FAILED",hint:`Run '${a}' after fixing the npm installation.`,data:{update:c,cause:d.error.message}});if(d.exitCode!==V){let f=[`exit: ${d.exitCode===null?`signal ${d.signal??"unknown"}`:String(d.exitCode)}`,...tI(d.stderr,5).map(u=>`stderr: ${u}`)];throw new S("npm could not update scriptctl.",{exitCode:q,errorCode:"UPDATE_COMMAND_FAILED",hint:`Run '${a}' after resolving the npm error.`,data:{update:c,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}},V]}function ug(e,t){e.command("doctor").description("Check configuration and runtime dependencies").option("--llm-config <path>","LLM configuration file").action(j(pg,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(j(lg,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(j(Gm,t));Le(n,["Release version"])}import{Option as PA}from"commander";import*as ki from"node:fs";import*as nc from"node:path";import{fileURLToPath as uA,pathToFileURL as fA}from"node:url";import*as dt from"node:fs";import*as ct from"node:path";import{createHash as oh}from"node:crypto";import{z as at}from"zod";import*as $o from"node:fs";var fg=null,oI=0;function Q(e,t){fg&&fg.push({fn:e,note:t,ms:Math.round((performance.now()-oI)*100)/100})}var iI=[["actor","actors","actor"],["location","locations","location"],["prop","props","prop"]];function Vo(e){return Array.isArray(e)?e:[]}function ve(e){return typeof e=="string"?e:""}function io(e,t,n,o){if(t){if(e.has(t)&&e.get(t)!==n){o.add(t);return}e.set(t,n)}}function Jp(e){return Do(JSON.parse($o.readFileSync(e,"utf8")),e)}function Do(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[c,d,p]of iI)for(let l of Vo(e[d])){let f={id:ve(l[`${p}_id`]),kind:c,name:ve(l[`${p}_name`]),aliases:Vo(l.aliases).map(ve).filter(Boolean),importance:ve(l.importance),desc:ve(l.description),states:Vo(l.states).map(u=>({id:ve(u.state_id),name:ve(u.state_name),desc:ve(u.description)})),raw:l,label:""};o.assets.push(f),o.byId.set(f.id,f)}let i=new Map;for(let c of o.assets)for(let d of[c.name,...c.aliases])i.set(d,(i.get(d)??0)+1);for(let c of o.assets)c.label=[c.name,...c.aliases].filter(d=>i.get(d)===1).sort((d,p)=>d.length-p.length)[0]??c.name;let r=new Set,s=0,a=0;Vo(e.episodes).forEach((c,d)=>{let p={anchor:String(d+1),id:ve(c.episode_id),no:d+1,title:ve(c.title)||void 0,synopsis:ve(c.synopsis)||void 0,scenes:[],raw:c};Vo(c.scenes).forEach((l,f)=>{s++;let u={anchor:n===4?ve(l.scene_id):`${d+1}-${f+1}`,id:ve(l.scene_id),no:f+1,gno:s,env:l.environment??{},location:Bp(l.location,"location_id"),actors:Vo(l.actors).map(h=>Bp(h,"actor_id")).filter(Boolean),props:Vo(l.props).map(h=>Bp(h,"prop_id")).filter(Boolean),actions:[],raw:l,ep:p};Vo(l.actions).forEach((h,m)=>{a++;let g={anchor:n===4?ve(h.action_id):`${d+1}-${f+1}-${m+1}`,no:m+1,gno:a,type:ve(h.type)||"action",content:ve(h.content),speaker:rI(h.speaker),paren:typeof h.parenthetical=="string"?h.parenthetical:typeof h.emotion=="string"?h.emotion:void 0,ts:ve(h.extend?.timestamp)||void 0,raw:h,scene:u};u.actions.push(g),io(o.actions,g.anchor,g,r),io(o.actions,`${d+1}-${f+1}-${m+1}`,g,r),n===3&&io(o.actions,`${p.id}/${u.id}#${m}`,g,r)}),p.scenes.push(u),io(o.scenes,u.anchor,u,r),io(o.scenes,`${d+1}-${f+1}`,u,r),io(o.scenes,`${p.id}/${u.id}`,u,r),io(o.scenes,u.id,u,r)}),o.episodes.push(p),io(o.eps,String(d+1),p,r),io(o.eps,p.id,p,r)});for(let c of r)o.actions.delete(c),o.scenes.delete(c),o.eps.delete(c);return Q(t?"model.load":"model.parse",`v${n} \xB7 ${o.episodes.length} ep \xB7 ${o.scenes.size} scene keys \xB7 ${o.actions.size} action keys \xB7 ${o.assets.length} assets \xB7 ${r.size} ambiguous keys dropped`),o}function Bp(e,t){if(!e||typeof e!="object")return null;let n=ve(e[t]);if(!n)return null;let o=Array.isArray(e.state_ids)?e.state_ids.map(ve):e.state_id?[ve(e.state_id)]:[];return{id:n,states:o,raw:e}}function rI(e){if(!(!e||typeof e!="object")){if(e.actor_id)return{id:ve(e.actor_id),state:ve(e.state_id)||void 0};if(e.kind)return{kind:ve(e.kind),label:ve(e.label)||void 0}}}function $e(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)??sI(e,p);if(f){let u=f.states.filter(h=>h.id===l||h.name===l);if(u.length===1)return Q("resolve",`"${n}" -> state ${f.id}/${u[0].id} "${u[0].name}"`),{t:"state",asset:f,state:u[0]};throw u.length>1?new Error(`${f.name} has ${u.length} states named "${l}"; address it by state id`):new Error(`${f.name} has no state "${l}" (has: ${f.states.map(h=>`${h.id}(${h.name})`).join(", ")})`)}}let i=e.actions.get(n);if(i)return Q("resolve",`"${n}" -> action map hit -> ${i.anchor}`),{t:"action",action:i};let r=e.scenes.get(n);if(r)return Q("resolve",`"${n}" -> scene map hit -> ${r.anchor}`),{t:"scene",scene:r};let s=e.eps.get(n);if(s)return Q("resolve",`"${n}" -> episode map hit -> ${s.id}`),{t:"ep",ep:s};let a=e.byId.get(n);if(a)return Q("resolve",`"${n}" -> asset id hit -> ${a.name}`),{t:"asset",asset:a};let c=e.assets.filter(p=>p.name===n||p.aliases.includes(n));if(c.length===1)return Q("resolve",`"${n}" -> exact name/alias -> ${c[0].id} ${c[0].name}`),{t:"asset",asset:c[0]};if(c.length>1)throw new Error(`Ambiguous name "${n}": ${c.map(p=>`${p.id}(${p.name})`).join(", ")}`);let d=e.assets.filter(p=>p.name.includes(n)||p.aliases.some(l=>l.includes(n)));if(d.length===1)return Q("resolve",`"${n}" -> substring name match -> ${d[0].id} ${d[0].name}`),{t:"asset",asset:d[0]};throw new Error(`Unknown address "${n}". Use an ordinal (3 / 3-2 / 3-2-5), a canonical ID, or an asset name.`+(d.length?` Did you mean: ${d.slice(0,5).map(p=>p.name).join(", ")}?`:""))}function sI(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 Ei(e,t){return e.byId.get(t)?.label||t}function _i(e,t,n){return e.byId.get(t)?.states.find(i=>i.id===n)?.name||n}function Un(e){return e.episodes.flatMap(t=>t.scenes.flatMap(n=>n.actions))}var aI={ep:"episode",scn:"scene",ac:"action",act:"actor",loc:"location",prp:"prop",st:"state"};function Go(e,t){let n=Yr(aI[e],t);return t.add(n),Q("newId",`${n} (collision-checked against ${t.size-1} live ids)`),n}function Oe(e){if(Object.assign(e,Do(e.raw,e.path)),!e.path){Q("save","skipped: document is not bound to a file");return}mg(e,e.path)}function mg(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}`;$o.writeFileSync(n,JSON.stringify(e.raw,null,2)+`
|
|
167
|
+
`),$o.renameSync(n,t),Q("commit",`${$o.statSync(t).size} bytes -> ${t} (tmp + atomic rename)`)}var gg={system:"\u65C1\u767D",broadcast:"\u5E7F\u64AD",offscreen:"\u753B\u5916",group:"\u7FA4\u58F0"},cI="\u5FC3\u58F0",hg=/^((?:\d+:)?\d+:\d{2}(?:\.\d{1,3})?)\s/,dI=/(^|[//,,、])\s*心声\s*(?=$|[//,,、])/g;function xs(e){let t=e.split("/").map(r=>r.trim()).filter(Boolean).join("/"),n=t.replace(dI,""),o=n!==t,i=o?n.replace(/^[\s//,,、]+/,"").trim():t;return{thought:o,...i?{paren:i}:{}}}function lr(e){let t=e.match(/^([^()()::,。!?;]+?)\s*(?:[((](.*?)[))])?\s*[::]\s*([\s\S]*)$/);return t?{label:t[1].trim(),...t[2]===void 0?{}:{note:t[2]},content:t[3].trim()}:null}function ur(e,t){let n=e.assets.filter(r=>r.kind==="actor"),o=n.filter(r=>r.name===t||r.aliases.includes(t));if(o.length)return o.length===1?o[0]:void 0;let i=n.filter(r=>r.name.split(/[\s·]+/).includes(t));return i.length===1?i[0]:void 0}function yg(e){let t=new Set(Object.values(gg));for(let n of e.assets){t.add(n.name);for(let o of n.aliases)t.add(o)}return n=>t.has(n)||!!ur(e,n)}function Es(e,t,n=yg(e)){if(n(t))return{base:t};for(let o=t.lastIndexOf("\xB7");o>0;o=t.lastIndexOf("\xB7",o-1)){let i=t.slice(0,o);if(n(i))return{base:i,qualifier:t.slice(o+1)}}return null}function Da(e){let t=yg(e);return n=>!!Es(e,n,t)}function wg(e,t){let n=lr(e);return/^(→|\\|##)/.test(e)||hg.test(e)||n&&t(n.label)?`\\${e}`:e}function pI(e,t){if(t.kind)return gg[t.kind]??t.kind;let n=Ei(e,t.id);return t.state?`${n}\xB7${_i(e,t.id,t.state)}`:n}function _s(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 c=t.speaker?pI(e,t.speaker):"?",d=[t.type==="inner_thought"?cI:"",t.paren??""].filter(Boolean);return`${t.speaker?.kind&&t.speaker.label?`${c}\xB7${t.speaker.label}`:c}${d.length?`(${d.join("/")})`:""}\uFF1A${t.content}`}return o.plain?t.content:wg(t.content,Da(e))})(),a=`${i}${i?" ":""}`;return`${o.timestamps?r+a:a+r}${s}`.replace(/\n/g,"\\n")}function zp(e,t){let n=Ei(e,t.id);return t.states.length===1&&t.states[0]==="default"?n:`${n}(${t.states.map(o=>_i(e,t.id,o)).join("+")})`}function fr(e,t){let n=[t.env?.space,t.env?.time].filter(Boolean).join("/").toUpperCase(),o=t.location?zp(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(c=>zp(e,c)).join(", "),s=t.props.map(c=>zp(e,c)).join(", "),a=[r&&`cast: ${r}`,s&&`props: ${s}`].filter(Boolean).join(" ");return a?`${i}
|
|
168
|
+
# ${a}`:i}function Kp(e,t,n={}){let o=n.plain?0:Math.max(0,...t.actions.map(i=>i.anchor.length));return Q("formatScene",`${t.anchor}: ${t.actions.length} actions, gutter=${o}`),[fr(e,t),...t.actions.map(i=>_s(e,i,o,n))].join(`
|
|
169
|
+
`)}var lI=/^([A-Za-z][A-Za-z0-9_]*|\d+(?:-\d+){0,2})\s\s+/;function xg(e,t){let n=e.trimEnd();if(!n.trim())return null;let o,i=n.match(lI);i&&(o=i[1],n=n.slice(i[0].length));let r,s=n.match(hg);if(s&&(r=s[1],n=n.slice(s[0].length)),n.startsWith("\\"))return{anchor:o,ts:r,type:"action",content:n.slice(1).replace(/\\n/g,`
|
|
170
170
|
`).trim()};if(n=n.replace(/\\n/g,`
|
|
171
|
-
`),n.startsWith("\u2192"))return{anchor:o,ts:r,type:"transition",content:n.slice(1).trim()};let a=
|
|
172
|
-
`)}})}}function
|
|
171
|
+
`),n.startsWith("\u2192"))return{anchor:o,ts:r,type:"transition",content:n.slice(1).trim()};let a=lr(n);if(a&&t(a.label)){let{thought:c,paren:d}=xs(a.note??"");return{anchor:o,ts:r,type:c?"inner_thought":"dialogue",speakerName:a.label,paren:d,content:a.content}}return{anchor:o,ts:r,type:"action",content:n.trim()}}var uI=/^(scn[1-9A-HJ-NP-Za-km-z]{6}|scn_\d+)$/,fI=/^[A-Z.\/]+$/,mI=/^\d+\s+actions?$/,gI={EXT:"exterior",EXTERIOR:"exterior",INT:"interior",INTERIOR:"interior"};function Eg(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 jp(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)||mI.test(i))){if(uI.test(i)){n.anchor=i;continue}if(fI.test(i)&&i!=="\u2014"){let[r,s]=i.split("/");r&&(n.env.space=gI[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*([^]*)$/),a=c=>(c??"").split(",").map(d=>d.trim()).filter(Boolean);n.cast=a(r?.[1]),n.props=a(s?.[1])}return n}function _g(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 mr(e,t){throw Object.assign(new Error(e),t)}function Qp(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 Hp(e){try{return So(e.timestamp??"")}catch(t){if(!(t instanceof it))throw t;return mr(`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 Sg(e,t){return mr("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 Fp(e,t){t.length===0&&mr("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&&mr("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&&mr("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||mr(`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 a=Hp(r),c=r,d=a,p="";for(let h of o){if(!h.timestamp)continue;let m=Hp(h);m.milliseconds<d.milliseconds&&Sg(c,h),c=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=Hp(m);if(g.milliseconds<d.milliseconds&&Sg(c,m),g.milliseconds!==d.milliseconds){f=m,u=g;break}}return Q("span",`${r.episodeId} ${a.canonical}..${u?.canonical??"(open)"} over ${o.length} action(s)`),{episode_id:r.episodeId,ep_no:r.episodeNo,start_timestamp:a.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 Yp=["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 qp(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 Wp(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=$e(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 a=s.asset,c=s.t==="state"?s.state.id:null,d=[...new Set([a.id,a.name,...a.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===a.id&&(c===null||m.states.includes(c)));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===a.id&&(c===null||m.speaker.state===c)&&p.push({kind:"speaker",scene:u,action:m,matched:[a.id]}),c===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:a.id,state_id:c,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(E=>E.anchor.length));return{kind:f,address:h?.anchor??u.anchor,scene_address:u.anchor,episode:u.ep.no,matched:m,text:[fr(e,u),...w.map(E=>(E===h?"> ":" ")+_s(e,E,y))].join(`
|
|
172
|
+
`)}})}}function Zp(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
173
|
${t.text}`),e.next_offset===null?"end":`Continue: --offset ${e.next_offset}`].join(`
|
|
174
174
|
|
|
175
|
-
`)}var
|
|
176
|
-
`)}}}function
|
|
177
|
-
`)}function
|
|
178
|
-
`):[o,...t.scenes.map(i=>
|
|
179
|
-
|
|
180
|
-
`)}function
|
|
181
|
-
`)}function
|
|
182
|
-
`)}function
|
|
183
|
-
`)}function
|
|
184
|
-
deleted: ${t.dropped.map(n=>`${n.anchor} ${
|
|
185
|
-
`)}`:"")}function
|
|
186
|
-
`));if(d){let y=
|
|
175
|
+
`)}var bg={\u65C1\u767D:"system",\u5E7F\u64AD:"broadcast",\u753B\u5916:"offscreen",\u7FA4\u58F0:"group"};function Ba(e,t="",n={}){let o=$e(e,t);switch(Q("read",`dispatch on node kind "${o.t}"`),o.t){case"script":return yI(e);case"ep":return wI(e,o.ep,n);case"scene":return Kp(e,o.scene,n);case"asset":return xI(e,o.asset);case"state":return EI(e,o.asset,o.state);case"action":{let i=n.context??3,r=o.action.scene.actions,s=r.indexOf(o.action),a=r.slice(Math.max(0,s-i),s+i+1),c=n.plain?0:Math.max(...a.map(l=>l.anchor.length)),d=o.action.raw.transition_prompt,p=Object.entries(o.action.raw.extend??{}).filter(([l])=>l!=="timestamp");return[fr(e,o.action.scene),...a.map(l=>(l===o.action?"> ":" ")+_s(e,l,c,n)),d?`transition: ${Ei(e,d.target)} | ${d.process} | ${d.contrast}`:"",p.length?`extend: ${p.map(([l,f])=>`${l}=${JSON.stringify(f)}`).join(", ")}`:""].filter(Boolean).join(`
|
|
176
|
+
`)}}}function hI(e){return e.actions.reduce((t,n)=>t+n.content.length,0)}function yI(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((a,c)=>a+c.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}: ${Ss(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(a=>a.kind===r);if(s.length){i.push("",`${r}s (${s.length})`);for(let a of s.slice(0,40)){let c=a.aliases.length?` ~${a.aliases.join(",")}`:"",d=a.importance?` [${a.importance}]`:"";i.push(` ${a.id} ${a.name}${d} ${a.states.length}st${c}`)}s.length>40&&i.push(` \u2026 ${s.length-40} more`)}}i.push("","episodes");for(let r of e.episodes){let s=r.scenes.reduce((a,c)=>a+hI(c),0);i.push(` ${r.no} ${r.id} ${r.scenes.length} scenes ${s} chars${r.title?` ${r.title}`:""}`+(r.synopsis?` ${Ss(r.synopsis,120)}`:""))}return i.join(`
|
|
177
|
+
`)}function wI(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=>fr(e,i))].join(`
|
|
178
|
+
`):[o,...t.scenes.map(i=>Kp(e,i,n))].join(`
|
|
179
|
+
|
|
180
|
+
`)}function xI(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} ${Ss(s.desc,160)}`);let i=[],r=new Map;for(let s of e.episodes)for(let a of s.scenes){let c=[a.location,...a.actors,...a.props].find(d=>d&&d.id===t.id);if(c){i.push(a);for(let d of c.states)r.set(d,(r.get(d)??0)+1)}}if(i.length){let s=[...new Set(i.map(c=>c.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(([c,d])=>`${_i(e,t.id,c)}\xD7${d}`).join(", ")}`);let a=t.states.filter(c=>!r.has(c.id));a.length&&o.push(`unused states: ${a.map(c=>`${c.id}(${c.name})`).join(", ")}`)}else o.push("appears: never referenced");return o.join(`
|
|
181
|
+
`)}function EI(e,t,n){let o=[];for(let r of e.episodes)for(let s of r.scenes)[s.location,...s.actors,...s.props].find(c=>c&&c.id===t.id)?.states.includes(n.id)&&o.push(s);let i=Un(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 Ss(e,t){return e.length>t?e.slice(0,t)+"\u2026":e}function el(e,t){let n=Un(e);if(Q("find",`pool = all actions (${n.length})`),t.in!==void 0){let o=typeof t.in=="string"?[t.in]:t.in,i=new Set(o.flatMap(r=>{let s=$e(e,r);if(s.t==="ep")return s.ep.scenes.flatMap(a=>a.actions);if(s.t==="scene")return s.scene.actions;if(s.t==="action")return[s.action];throw new Error(`--in must address an episode, scene or action (got ${s.t})`)}));n=n.filter(r=>i.has(r)),Q("find",`--in ${o.join(", ")} narrows pool to ${n.length}`)}if(t.type&&(n=n.filter(o=>o.type===t.type),Q("find",`--type ${t.type} -> ${n.length}`)),t.speaker){let o=$e(e,t.speaker);if(o.t!=="asset")throw new Error("--speaker must name an actor");n=n.filter(i=>i.speaker?.id===o.asset.id),Q("find",`--speaker ${t.speaker} -> ${o.asset.id} -> ${n.length}`)}return n}function vg(e,t,n={}){let o=el(e,n),i=t?new RegExp(t,"u"):null,r=o.filter(f=>!i||i.test(f.content));Q("find",`regex /${t}/ -> ${r.length} hits`);let s=n.limit??40,a=n.window??16,c=r.slice(0,s),d=Math.max(0,...c.map(f=>f.anchor.length)),p=`${r.length} hit${r.length===1?"":"s"}`+(t?` for /${t}/`:"")+(r.length>c.length?` (showing ${c.length})`:""),l=c.map(f=>{let u=`${f.scene.ep.no}-${f.scene.no}-${f.no}`,h=u===f.anchor?"":u.padEnd(8)+" ",m=f.speaker?.id?Ei(e,f.speaker.id)+"\uFF1A":"",g=n.full||!i?f.content:_I(f.content,i,a);return`${f.anchor.padEnd(d)} ${h}${m}${g}`});return[p,...l].join(`
|
|
183
|
+
`)}function _I(e,t,n){let o=e.match(t);if(!o||o.index===void 0)return Ss(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 tl(e,t){return Fp(Qp(e),qp(e,el(e,{in:t})))}function Og(e,t){let n=tl(e,t);return Yp.map(o=>`${o}=${n[o]}`).join(" ")}var SI=["content","paren","speaker","ts","type","transition"],II=["name","desc","importance","aliases","role"],AI=["name","desc"],kI=["title","synopsis"],bI=["space","time"],vI=["title","worldview","style","synopsis","logline","theme","main"];function Is(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 Rg(e,t,n){let o=$e(e,t);if(o.t==="asset")return RI(e,t,o.asset,n);if(o.t==="state")return MI(e,t,o.asset,o.state,n);if(o.t==="script")return Ig(e,t||"script","script",o.doc.raw,n,vI);if(o.t==="ep")return Ig(e,t,"episode",o.ep.raw,n,kI);if(o.t==="scene")return OI(e,t,o.scene,n);let i=o.action,r=i.raw,s=Is(i.anchor,"action",n,SI),a=gt(e);Q("edit",`${i.anchor}: ${s.join(", ")}`),n.type!==void 0&&(r.type=Si("type",n.type,tn,Kn));let c=n.content!==void 0&&Lg.has(r.type)?nl(e,n.content):null,d=n.paren===void 0?c?.note:n.paren,p=n.speaker===void 0?c?.label:n.speaker;if(n.content!==void 0&&(r.content=c?.content??n.content),d!==void 0){let l=d===null?null:xs(d);l?.thought&&n.type===void 0&&r.type==="dialogue"&&(r.type="inner_thought"),Ga(e,r,l?.thought?l.paren??null:d)}if(p===null||p===""?delete r.speaker:p!==void 0&&(r.speaker=ol(e,p)),n.ts!==void 0&&Ug(r,n.ts),n.transition!==void 0)if(n.transition===null)delete r.transition_prompt;else{let[l,f,u]=n.transition.split("|").map(m=>m.trim());if(!l||!f||!u)throw new Error(`transition takes "target|process|contrast" (got "${n.transition}")`);let h=$e(e,l);if(h.t!=="asset")throw new Error(`transition target must be an asset (got ${l})`);r.transition_prompt={target:h.asset.id,process:f,contrast:u}}return Oe(e),`${i.anchor} ${s.join("+")} ${Ja(r)}`+ze(e,a)}function Ig(e,t,n,o,i,r){let s=Is(t,n,i,r),a=gt(e);for(let c of s)if(c==="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(c==="aliases"||c==="role")throw new Error(`${t} is ${n}; it has no ${c}`);o[c]=i[c]}return Q("edit",`${n} ${t}: ${s.join(", ")}`),Oe(e),`${t} ${s.join("+")}`+ze(e,a)}function OI(e,t,n,o){let i=Is(t,"scene",o,bI),r=gt(e),s={...n.raw.environment??{}};return o.space!==void 0&&(s.space=Si("space",o.space,Of,yd)),o.time!==void 0&&(s.time=Si("time",o.time,hd,ca)),n.raw.environment=s,Q("edit",`scene ${n.anchor}: ${i.join(", ")}`),Oe(e),`${n.anchor} ${i.join("+")} ${[s.space,s.time].filter(Boolean).join("/")}`+ze(e,r)}function RI(e,t,n,o){let i=Is(t,"asset",o,II),r=gt(e);if(o.name!==void 0){let s=e.assets.find(a=>a!==n&&(a.name===o.name||a.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=Dg(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=Si("role",o.role,_o,qi):delete n.raw.role_type}return o.aliases!==void 0&&(o.aliases.length?n.raw.aliases=o.aliases:delete n.raw.aliases),Q("edit",`asset ${n.id}: ${i.join(", ")}`),Oe(e),`${n.id} ${i.join("+")} ${o.name??n.name}`+ze(e,r)}function MI(e,t,n,o,i){let r=Is(t,"state",i,AI),s=gt(e),a=n.raw.states.find(c=>c.state_id===o.id);if(i.name!==void 0){if(n.states.some(c=>c.id!==o.id&&c.name===i.name))throw new Error(`${n.name} already has a state named "${i.name}"`);a.state_name=i.name}return i.desc!==void 0&&(a.description=i.desc),Q("edit",`state ${n.id}/${o.id}: ${r.join(", ")}`),Oe(e),`${n.id}/${o.id} ${r.join("+")} ${i.name??o.name}`+ze(e,s)}function Mg(e,t,n,o,i,r,s,a){let c=$e(e,t);if(c.t!=="action")throw new Error(`${t} is a ${c.t}; insert needs a sibling action`);let d=c.action,p=gt(e),l={type:Si("type",o,tn,Kn),content:i};if(e.version===4&&(l.action_id=Go("ac",new Set(e.actions.keys()))),Lg.has(o)){let h=nl(e,i),m=r||h?.label,g=s??h?.note;if(h&&(l.content=h.content),!m)throw new Error(`a ${o} needs a speaker`);if(l.speaker=ol(e,m),g!==void 0){let w=xs(g);w.thought&&(l.type="inner_thought"),Ga(e,l,w.thought?w.paren??null:g)}}else if(r||s)throw new Error(`a ${o} takes neither speaker nor paren`);a!==void 0&&(l.extend=a);let f=d.scene.raw.actions,u=f.indexOf(d.raw)+(n==="before"?0:1);return f.splice(u,0,l),Q("insert",`${l.action_id??`${d.scene.anchor}#${u}`} ${n} ${d.anchor}`),Oe(e),`${l.action_id??`${d.scene.anchor}#${u}`} ${n} ${d.anchor} ${Ja(l)}`+ze(e,p)}function Ng(e,t,n,o="after"){let i=$e(e,t);if(i.t!=="action")throw new Error(`${t} is a ${i.t}; move targets one action`);let r=$e(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=gt(e),a=i.action.scene.raw.actions;a.splice(a.indexOf(i.action.raw),1);let c=r.action.scene.raw.actions;return c.splice(c.indexOf(r.action.raw)+(o==="before"?0:1),0,i.action.raw),Q("move",`${i.action.scene.anchor} -> ${r.action.scene.anchor}, identity ${i.action.anchor} preserved`),Oe(e),`${i.action.anchor} ${o} ${r.action.anchor} (${i.action.scene.anchor} -> ${r.action.scene.anchor})`+ze(e,s)}var Lg=new Set(["dialogue","inner_thought"]);function nl(e,t){let n=lr(t);if(!n)return null;let o=Es(e,n.label)?.base;return o&&(bg[o]||ur(e,o))?n:null}function Ga(e,t,n){let o=e.version===4?"parenthetical":"emotion";n===null?delete t[o]:t[o]=n}function Ug(e,t){if(t===null){e.extend&&delete e.extend.timestamp;return}let n;try{n=So(t).canonical}catch(o){throw o instanceof it?new Error(`${o.message} (got ${JSON.stringify(t)})`):o}e.extend={...e.extend??{},timestamp:n}}function ol(e,t){let n=Es(e,t),[o,i]=n?[n.base,n.qualifier]:NI(t,"\xB7"),r=bg[o];if(r)return i?{kind:r,label:i}:{kind:r};let s=ur(e,o),a=s?{t:"asset",asset:s}:$e(e,o);if(a.t!=="asset"||a.asset.kind!=="actor")throw new Error(`Not an actor: ${t}`);let c={actor_id:a.asset.id};if(i){let d=a.asset.states.find(p=>p.name===i||p.id===i);if(!d)throw new Error(`Unknown state "${i}" on ${a.asset.name}`);c.state_id=d.id}return c}function NI(e,t){let n=e.indexOf(t);return n<0?[e,void 0]:[e.slice(0,n),e.slice(n+t.length)]}function Ja(e){return Ss(String(e.content??""),40)}function Pg(e,t,n,o={}){let i=Do(structuredClone(e.raw)),r=LI(i,t,n,o);return e.raw=i.raw,Oe(e),r}function LI(e,t,n,o){if(t==="+"||Number(t)===e.episodes.length+1){let r={scenes:[]};return e.version===4&&(r.episode_id=Go("ep",new Set(e.eps.keys()))),e.raw.episodes.push(r),Q("write",`appending episode ${e.episodes.length+1}`),Ag(e,r,e.episodes.length+1,n,o,!0)}let i=$e(e,t);if(i.t==="scene")return UI(e,i.scene,n,o);if(i.t==="ep")return Ag(e,i.ep.raw,i.ep.no,n,o,!1);throw new Error(`write targets a scene or an episode (got ${i.t})`)}function UI(e,t,n,o){let i=gt(e),r=Tg(e,t.raw,t,n,new Set(e.actions.keys()),o);return Oe(e),Cg(t.anchor,r)+ze(e,i)}function Cg(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} ${Ja(n.raw)}`).join(`
|
|
185
|
+
`)}`:"")}function Tg(e,t,n,o,i,r,s,a){let c=Da(e),{head:d,meta:p,body:l}=Eg(o.split(`
|
|
186
|
+
`));if(d){let y=jp(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?Xp(e,y.location,"location"):null,t.actors=y.cast.map(E=>Xp(e,E,"actor")),t.props=y.props.map(E=>Xp(e,E,"prop"))}let f=s??new Map((n?.actions??[]).map(y=>[y.anchor,y])),u=a??new Set,h=new Set,m=[],g=0,w=n?n.anchor:"this new scene";for(let y of l){let E=xg(y,c);if(!E)continue;let _=E.anchor?f.get(E.anchor):void 0;if(E.anchor&&!_)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(_&&u.has(_.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 x=_?_.raw:{};!_&&e.version===4&&(x.action_id=Go("ac",i)),x.type=Si("type",E.type,tn,Kn),x.content=E.content,E.type==="dialogue"||E.type==="inner_thought"?(x.speaker=ol(e,E.speakerName),Ga(e,x,E.paren??null)):(delete x.speaker,Ga(e,x,null)),Ug(x,E.ts??null),_?(h.add(_.anchor),u.add(_.anchor)):g++,m.push(x)}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 Ag(e,t,n,o,i,r){let s=gt(e),a=r?[]:e.episodes[n-1].scenes,c=new Map;for(let _ of a)c.set(_.anchor,_),c.set(_.id,_);let d=[];for(let _ of o.split(`
|
|
187
187
|
`))_.startsWith("##")?d.push(_):d.length&&(d[d.length-1]+=`
|
|
188
|
-
`+_);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 _ of a)for(let x of _.actions)f.set(x.anchor,x);let u=new Set,h=new Set,m=[],g=[],w=0;for(let _ of d){let x=
|
|
189
|
-
`)[0]),A=x.anchor?c.get(x.anchor):void 0;if(x.anchor&&!A)throw new Error(`Scene ${x.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=
|
|
188
|
+
`+_);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 _ of a)for(let x of _.actions)f.set(x.anchor,x);let u=new Set,h=new Set,m=[],g=[],w=0;for(let _ of d){let x=jp(_.split(`
|
|
189
|
+
`)[0]),A=x.anchor?c.get(x.anchor):void 0;if(x.anchor&&!A)throw new Error(`Scene ${x.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=Go("scn",l):b.scene_id=`scn_${String(a.length+w+1).padStart(3,"0")}`,w++);let U=Tg(e,b,A??null,_,p,i,f,u);m.push(b),g.push(Cg(A?A.anchor:`new ${b.scene_id}`,U))}let y=[...f.values()].filter(_=>!u.has(_.anchor));if(y.length&&!i.allowDelete)throw new Error(`This would delete ${y.length} action(s) from episode ${n}: `+y.slice(0,6).map(_=>`${_.anchor}(${_.scene.anchor})`).join(", ")+(y.length>6?" \u2026":"")+" \u2014 keep their lines, or pass --allow-delete if that is the intent");let E=a.filter(_=>!h.has(_.anchor));if(E.length&&!i.allowDelete)throw new Error(`This would delete ${E.length} whole scene(s) from episode ${n}: `+E.map(_=>`${_.anchor}(${_.actions.length} actions)`).join(", ")+" \u2014 include their `##` headers to keep them, or pass --allow-delete if that is the intent");return Q("write",`episode ${n}: ${d.length} scene blocks, ${w} new, ${E.length} deleted`),t.scenes=m,Oe(e),`EP${n}: ${m.length} scenes (${m.length-w} kept, ${w} new, ${E.length} deleted, ${y.length} actions deleted)
|
|
190
190
|
`+g.map(_=>" "+_.replace(/\n/g,`
|
|
191
191
|
`)).join(`
|
|
192
192
|
`)+(E.length?`
|
|
193
|
-
deleted scenes: ${E.map(_=>_.anchor).join(", ")}`:"")+ze(e,s)}function
|
|
193
|
+
deleted scenes: ${E.map(_=>_.anchor).join(", ")}`:"")+ze(e,s)}function Xp(e,t,n){let{name:o,states:i}=_g(t),r=$e(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}),a=[...new Set(s)].sort(),c=`${n}_id`;return e.version===4?{[c]:r.asset.id,state_ids:a}:{[c]:r.asset.id,state_id:a[0]}}function Vg(e,t,n,o,i=!1){let r=$e(e,t);if(r.t!=="scene")throw new Error(`${t} is a ${r.t}; ref targets one scene`);let s=r.scene,a=$e(e,n);if(a.t!=="asset")throw new Error(`${n} is a ${a.t}; ref takes an actor, location or prop`);let c=a.asset,d=c.kind==="actor"?"actors":c.kind==="prop"?"props":"location",p=gt(e);if(i){if(c.kind==="location"){if(s.location?.id!==c.id)throw new Error(`${s.anchor}'s location is ${s.location?Ei(e,s.location.id):"empty"}, not ${c.name}`);s.raw.location=null}else{let m=s.raw[d],g=m.findIndex(w=>w[`${c.kind}_id`]===c.id);if(g<0)throw new Error(`${s.anchor} does not reference ${c.name}`);m.splice(g,1)}return Q("ref",`${s.anchor} -= ${c.id}`),Oe(e),`${s.anchor} removed ${c.name}`+ze(e,p)}if(!o.length)throw new Error(`ref needs at least one state for ${c.name} (has: ${c.states.map(m=>m.name).join(", ")}) \u2014 nothing is implied, not even default`);let l=[...new Set(o.map(m=>{let g=c.states.filter(w=>w.name===m||w.id===m);if(!g.length)throw new Error(`${c.name} has no state "${m}" (has: ${c.states.map(w=>w.name).join(", ")})`);if(g.length>1)throw new Error(`${c.name} has ${g.length} states named "${m}"; use the state id`);return g[0].id}))].sort(),f=`${c.kind}_id`,u=e.version===4?{[f]:c.id,state_ids:l}:{[f]:c.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(c.kind==="location")h=s.location?s.location.id===c.id?"restated":"replaced":"set",s.raw.location=u;else{let m=s.raw[d],g=m.findIndex(w=>w[f]===c.id);g<0?(m.push(u),h="added"):(m[g]=u,h="restated")}return Q("ref",`${s.anchor} ${h} ${c.id} = [${l.join(", ")}]`),Oe(e),`${s.anchor} ${h} ${c.name}(${l.map(m=>_i(e,c.id,m)).join("+")})`+ze(e,p)}function $g(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=gt(e),s=el(e,o),a=s.filter(p=>(i.lastIndex=0,i.test(p.content)));if(Q("replace",`/${t}/ matched ${a.length} of ${s.length} actions in scope`),!a.length)return`0 hits for /${t}/ \u2014 nothing to do`;let c=Math.max(...a.map(p=>p.anchor.length)),d=a.map(p=>{let l=p.content.replace(i,n);return`${p.anchor.padEnd(c)} ${p.scene.ep.no}-${p.scene.no}-${p.no}
|
|
194
194
|
${" ".repeat(c)} - ${p.content}
|
|
195
195
|
${" ".repeat(c)} + ${l}`});if(!o.apply)return`${a.length} action(s) would change (dry run \u2014 pass apply to write)
|
|
196
196
|
`+d.join(`
|
|
197
197
|
`);for(let p of a)i.lastIndex=0,p.raw.content=p.content.replace(i,n);return Oe(e),Q("replace",`wrote ${a.length} actions`),`${a.length} action(s) changed`+ze(e,r)+`
|
|
198
198
|
`+d.join(`
|
|
199
|
-
`)}function
|
|
200
|
-
`)}function
|
|
201
|
-
`):"No issues."}function
|
|
202
|
-
fix: ${n.repair_hint}`:""))}function gt(e){return
|
|
199
|
+
`)}function Si(e,t,n,o){if(!n.has(t))throw new Error(`${e} must be one of ${o.join(" | ")} (got "${t}")`);return t}function Dg(e){return Si("importance",e,$t,Hn)}function gr(e){let t=e.version===4?Te(e.raw):St(e.raw);return{...t,warnings:[...t.warnings,...TI(e)]}}function PI(e){let t=e.assets.filter(o=>o.kind==="actor").flatMap(o=>[...new Set([o.name,...o.aliases,...o.name.split(/[\s·]+/).filter(r=>ur(e,r)===o)])].flatMap(r=>o.states.map(s=>`${r}\xB7${s.name}`))).sort((o,i)=>i.length-o.length);if(!t.length)return()=>{};let n=new RegExp(t.map(o=>o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"));return o=>o.match(n)?.[0]}function CI(e){let t=PI(e),n=[];return e.episodes.forEach((o,i)=>o.scenes.forEach((r,s)=>r.actions.forEach((a,c)=>{if(a.type!=="action")return;let d=`$.episodes[${i}].scenes[${s}].actions[${c}].content`,p=lr(a.content);p&&(p.note!==void 0||nl(e,a.content))&&n.push({code:"action_speech_shape",action:a,path:d,found:p.label});let l=t(a.content);l&&n.push({code:"action_look_label",action:a,path:d,found:l})}))),n}function TI(e){return CI(e).map(({code:t,path:n,found:o})=>t==="action_speech_shape"?{code:t,path:n,message:`action text is written as a speech by "${o}"`,repair_hint:"set type and speaker, and keep only the spoken words in content"}:{code:t,path:n,message:`action text holds the speaker label "${o}"`,repair_hint:"name the character only; a look change belongs to the scene's references"})}function Gg(e){let t=gr(e);return[`${e.episodes.length} episodes / ${e.scenes.size?[...new Set(e.episodes.flatMap(o=>o.scenes))].length:0} scenes / ${Un(e).length} actions \u2014 ${t.ok?"ok":`${t.errors.length} error(s)`}`+(t.warnings.length?`, ${t.warnings.length} warning(s)`:""),...rl([...t.errors.map(o=>["error",o]),...t.warnings.map(o=>["warning",o])])].join(`
|
|
200
|
+
`)}function il(e,t={}){let n=gr(e),o=[...n.errors.map(i=>["error",i]),...n.warnings.map(i=>["warning",i])];return t.severity&&(o=o.filter(([i])=>i===t.severity)),t.code&&(o=o.filter(([,i])=>i.code===t.code)),Q("issues",`${o.length} matching issue(s)`),o.length?rl(o).join(`
|
|
201
|
+
`):"No issues."}function rl(e){return e.map(([t,n])=>`${t} ${n.code} ${n.path} ${n.message}`+(n.repair_hint?`
|
|
202
|
+
fix: ${n.repair_hint}`:""))}function gt(e){return gr(e)}function ze(e,t){let n=gr(e),o=[...Ed(t.errors,n.errors).map(i=>["error",i]),...Ed(t.warnings,n.warnings).map(i=>["warning",i])];return o.length?(Q("check",`${o.length} issue(s) introduced by this edit`),`
|
|
203
203
|
introduced ${o.length} issue(s):
|
|
204
|
-
`+
|
|
205
|
-
`)):""}var
|
|
204
|
+
`+rl(o).join(`
|
|
205
|
+
`)):""}var sl={actor:"actors",location:"locations",prop:"props"},VI={actor:"actors",location:"location",prop:"props"},kg={actor:"act",location:"loc",prop:"prp"};function Bg(e,t,n,o,i="featured",r=[]){if(!n.trim())throw new Error("asset needs a name");let s=gt(e),a=e.assets.find(l=>l.name===n||l.aliases.includes(n));if(a)throw new Error(`"${n}" already names ${a.kind} ${a.id}; read it instead`);let c=sl[t],d=e.version===4?Go(kg[t],new Set(e.assets.map(l=>l.id))):`${kg[t]}_${String(e.raw[c].length+1).padStart(3,"0")}`,p={[`${t}_id`]:d,[`${t}_name`]:n,importance:Dg(i),description:o,states:[{state_id:"default",state_name:n,description:o}]};return r.length&&(p.aliases=r),e.raw[c].push(p),Q("asset",`${t} ${d} "${n}" + default state`),Oe(e),`${d} ${n} ${t} states: default`+ze(e,s)}function Jg(e,t,n,o){let i=$e(e,t);if(i.t!=="asset")throw new Error(`${t} is a ${i.t}; state targets an asset`);let r=gt(e);if(i.asset.states.some(a=>a.name===n))throw new Error(`${i.asset.name} already has a state named "${n}"`);let s=e.version===4?Go("st",new Set(i.asset.states.map(a=>a.id))):`st_${String(i.asset.states.length).padStart(3,"0")}`;return i.asset.raw.states.push({state_id:s,state_name:n,description:o}),Q("state",`${i.asset.id} + ${s} "${n}"`),Oe(e),`${i.asset.id}/${s} ${n} (${i.asset.name} now has ${i.asset.states.length+1} states)`+ze(e,r)}function $I(e,t){let n=$e(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 zg(e,t,n,o,i=!1){let{raw:r,label:s}=$I(e,t),a=r.extend??{};if(!n){let c=Object.keys(a);return c.length?`${s} extend:
|
|
206
206
|
`+c.map(d=>` ${d} = ${JSON.stringify(a[d])}`).join(`
|
|
207
|
-
`):`${s} has no extend data`}if(i){if(!(n in a))throw new Error(`${s} has no extend key "${n}"`);return delete a[n],Object.keys(a).length?r.extend=a:delete r.extend,Q("ext",`${s} -= ${n}`),Oe(e),`${s} removed extend.${n}`}if(o===void 0){if(!(n in a))throw new Error(`${s} has no extend key "${n}"`);return`${s} extend.${n} = ${JSON.stringify(a[n])}`}return r.extend={...a,[n]:o},Q("ext",`${s} extend.${n} = ${o}`),Oe(e),`${s} extend.${n} = ${JSON.stringify(o)}`}function
|
|
208
|
-
stripped ${o.length} scene reference(s) and ${i.length} speaker(s)`:"")}function
|
|
209
|
-
${d?"rewired":"cleared"} ${i.length} scene binding(s) and ${r.length} speaker(s)${d?` to ${
|
|
210
|
-
moved ${f.length} scene reference(s), ${u.length} speaker(s), ${[...p].filter(([m,g])=>m!==g).length} state mapping(s)`+ze(e,r)}import{z as Bt}from"zod";var
|
|
211
|
-
`),await
|
|
207
|
+
`):`${s} has no extend data`}if(i){if(!(n in a))throw new Error(`${s} has no extend key "${n}"`);return delete a[n],Object.keys(a).length?r.extend=a:delete r.extend,Q("ext",`${s} -= ${n}`),Oe(e),`${s} removed extend.${n}`}if(o===void 0){if(!(n in a))throw new Error(`${s} has no extend key "${n}"`);return`${s} extend.${n} = ${JSON.stringify(a[n])}`}return r.extend={...a,[n]:o},Q("ext",`${s} extend.${n} = ${o}`),Oe(e),`${s} extend.${n} = ${JSON.stringify(o)}`}function Kg(e,t,n={}){let o=$e(e,t),i=gt(e);if(o.t==="action"){let r=o.action.scene.raw.actions;return r.splice(r.indexOf(o.action.raw),1),Q("del",`action ${o.action.anchor} from ${o.action.scene.anchor}`),Oe(e),`deleted ${o.action.anchor} ${Ja(o.action.raw)}`+ze(e,i)}if(o.t==="scene"){if(o.scene.actions.length&&!n.force)throw new Error(`${o.scene.anchor} still holds ${o.scene.actions.length} action(s) \u2014 pass --force to delete the scene and everything in it`);let r=o.scene.ep.raw.scenes;return r.splice(r.indexOf(o.scene.raw),1),Q("del",`scene ${o.scene.anchor} (${o.scene.actions.length} actions)`),Oe(e),`deleted scene ${o.scene.anchor} with ${o.scene.actions.length} action(s)`+ze(e,i)}if(o.t==="ep"){let r=o.ep.scenes.reduce((a,c)=>a+c.actions.length,0);if(o.ep.scenes.length&&!n.force)throw new Error(`episode ${o.ep.no} still holds ${o.ep.scenes.length} scene(s) / ${r} action(s) \u2014 pass --force to delete the episode and everything in it`);let s=e.raw.episodes;return s.splice(s.indexOf(o.ep.raw),1),Q("del",`episode ${o.ep.no}`),Oe(e),`deleted episode ${o.ep.no} (${o.ep.id}) with ${o.ep.scenes.length} scene(s) / ${r} action(s)`}if(o.t==="asset")return DI(e,o.asset,n)+ze(e,i);if(o.t==="state")return GI(e,o.asset,o.state,n)+ze(e,i);throw new Error(`del takes an action, scene, episode, asset or state (got ${o.t})`)}function jg(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:Un(e).filter(o=>o.speaker?.id===t)}}function DI(e,t,n){let{scenes:o,speakers:i}=jg(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 al(e,t.id,n.replacement);for(let c of o){c.raw.location?.[`${t.kind}_id`]===t.id&&(c.raw.location=null);for(let d of["actors","props"]){let p=c.raw[d];if(!p)continue;let l=p.findIndex(f=>f[`${t.kind}_id`]===t.id);l>=0&&p.splice(l,1)}}for(let c of i)delete c.raw.speaker;let s=sl[t.kind],a=e.raw[s];return a.splice(a.indexOf(t.raw),1),Q("del",`asset ${t.id}, stripped ${o.length} scene refs + ${i.length} speakers`),Oe(e),`deleted ${t.kind} ${t.id} ${t.name}`+(r?`
|
|
208
|
+
stripped ${o.length} scene reference(s) and ${i.length} speaker(s)`:"")}function GI(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=Un(e).filter(d=>d.speaker?.id===t.id&&d.speaker.state===n.id),s=i.length+r.length,a="";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;a=`
|
|
209
|
+
${d?"rewired":"cleared"} ${i.length} scene binding(s) and ${r.length} speaker(s)${d?` to ${_i(e,t.id,d)}`:""}`}let c=t.raw.states;return c.splice(c.findIndex(d=>d.state_id===n.id),1),Q("del",`state ${t.id}/${n.id}`),Oe(e),`deleted state ${t.id}/${n.id} ${n.name}`+a}function al(e,t,n){let o=$e(e,t),i=$e(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=gt(e),s=o.asset,a=i.asset,c=`${s.kind}_id`,d=new Set(a.states.map(m=>m.id)),p=new Map;for(let m of s.states){let g=a.states.find(y=>y.name===m.name);if(g){p.set(m.id,g.id);continue}if(m.id==="default"){p.set(m.id,"default");continue}let w=e.version===4?Go("st",d):`st_${String(a.states.length+p.size).padStart(3,"0")}`;a.raw.states.push({state_id:w,state_name:m.name,description:m.desc}),p.set(m.id,w)}let l=VI[s.kind],{scenes:f,speakers:u}=jg(e,s.id);for(let m of f){let g=m.raw[l],w=l==="location"?g?[g]:[]:g??[];for(let y of w)y[c]===s.id&&(y[c]=a.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(l!=="location"&&Array.isArray(g)){let y=[];for(let E of g){let _=y.find(x=>x[c]===E[c]);if(!_){y.push(E);continue}e.version===4&&(_.state_ids=[...new Set([..._.state_ids,...E.state_ids])].sort())}m.raw[l]=y}}for(let m of u)m.raw.speaker.actor_id=a.id,m.raw.speaker.state_id&&(m.raw.speaker.state_id=p.get(m.raw.speaker.state_id)??"default");let h=e.raw[sl[s.kind]];return h.splice(h.indexOf(s.raw),1),Q("merge",`${s.id} -> ${a.id}: ${f.length} scenes, ${u.length} speakers`),Oe(e),`merged ${s.id} ${s.name} into ${a.id} ${a.name}
|
|
210
|
+
moved ${f.length} scene reference(s), ${u.length} speaker(s), ${[...p].filter(([m,g])=>m!==g).length} state mapping(s)`+ze(e,r)}import{z as Bt}from"zod";var BI=Bt.string().min(1),JI=Bt.array(Bt.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"),za=Bt.number().min(0).max(1e3),Ka=Bt.object({page:Bt.number().int().min(1),kind:Bt.enum(["panel","bubble","text"]),box:Bt.object({top:za,left:za,bottom:za,right:za}).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")}),ja=Bt.array(Ka).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 As(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:a}=o.box;(s<=i||a<=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 Hg=Bt.object({kind:Bt.literal("comic"),document_id:BI,pages:JI,regions:ja.optional()}),Ii=Bt.object({scriptctl:Bt.object({source:Hg})});import{z as J}from"zod";var st=J.string().min(1),Bo=J.array(st),Qg=J.object({name:st,description:st.describe("\u8BE5\u9636\u6BB5\u72EC\u7ACB\u5B8C\u6574\u7684\u53EF\u89C1\u5916\u8C8C\uFF0C\u5305\u62EC\u8DE8\u9636\u6BB5\u76F8\u540C\u7279\u5F81\uFF1B\u53D1\u58F0\u7279\u5F81\u4EC5\u91C7\u7528\u6F2B\u753B\u6587\u5B57\u660E\u786E\u8BF4\u660E\u7684\u4E8B\u5B9E")}),dl=J.string().length(0),pl=J.object({apparent_gender:J.string(),apparent_age:J.string(),face_shape:J.string(),brows_eyes:J.string(),nose:J.string(),mouth:J.string(),skin_features:J.string(),hair:J.string(),build:J.string(),persistent_marks:Bo,voice:dl.describe("\u6F2B\u753B\u6CA1\u6709\u539F\u58F0\u97F3\u8F68\uFF0C\u586B\u7A7A\u4E32")}).describe("\u753B\u50CF\u5B57\u7B26\u4E32\u586B\u7A7A\u4E32\u3001persistent_marks \u586B\u7A7A\u6570\u7EC4\uFF1B\u5168\u90E8\u5916\u8C8C\u4E0E\u8EAB\u4F53\u6807\u8BB0\u5199\u5165\u5404\u9636\u6BB5\u5B8C\u6574 state"),zI=J.object({name:st,kind:J.enum(["actor","location","prop"]),status:J.enum(["canonical","provisional"]),importance:J.enum(["featured","background"]),recognition_anchors:Bo.describe("\u586B\u7A7A\u6570\u7EC4\uFF1B\u4EBA\u7269\u8BC6\u522B\u7279\u5F81\u4FDD\u5B58\u5728\u5BF9\u5E94 state"),identity_profile:pl,appearance:J.string(),role:J.string().describe("\u4EBA\u7269\u53EA\u5199\u5DF2\u786E\u8BA4\u7684\u8EAB\u4EFD\u79F0\u8C13\u4E0E\u5173\u7CFB\uFF1B\u5730\u70B9/\u9053\u5177\u5199\u7528\u9014"),states:J.array(Qg),aliases:Bo}),KI=J.object({new_entities:J.array(zI),enrich:J.array(J.object({name:st,add_recognition_anchors:Bo.describe("\u586B\u7A7A\u6570\u7EC4"),identity_profile_patch:pl,identity_revision:J.object({profile:pl,recognition_anchors:Bo}).describe("\u65E2\u6709\u753B\u50CF\u6216\u951A\u70B9\u975E\u7A7A\u65F6\u63D0\u4F9B\u5168\u7A7A profile \u548C\u7A7A recognition_anchors\uFF1B\u6709\u8BC1\u636E\u7684\u4E8B\u5B9E\u8865\u5165\u9002\u7528 state\uFF0Crole \u5B8C\u6574\u7ED9\u51FA\u8EAB\u4EFD\u5173\u7CFB\uFF0C\u663E\u5F0F\u7A7A\u4E32\u6E05\u9664\u65E7 role").optional(),appearance:J.string(),role:J.string().describe("\u4EBA\u7269\u5DF2\u786E\u8BA4\u7684\u8EAB\u4EFD\u79F0\u8C13\u4E0E\u5173\u7CFB\uFF1B\u5730\u70B9/\u9053\u5177\u5199\u7528\u9014\u3002\u63D0\u4F9B identity_revision \u65F6\u586B\u5199\u5B8C\u6574\u8EAB\u4EFD\u5173\u7CFB\uFF0C\u7A7A\u4E32\u6E05\u9664\u65E7 role\uFF1B\u666E\u901A\u589E\u91CF\u65E0\u66F4\u65B0\u586B\u7A7A\u4E32"),add_aliases:Bo,add_states:J.array(Qg)})),canonicalize:J.array(J.object({from_name:st,canonical_name:st,evidence:st.describe("\u672C\u8BDD PDF \u9875\u7801\u548C\u76F4\u63A5\u51FA\u73B0\u7684\u59D3\u540D\u539F\u6587")}))}),Fg=J.array(J.number().int().min(1)).min(1).describe("1-based PDF \u7269\u7406\u9875\u7801\uFF1B\u8DE8\u9875\u753B\u683C\u6216\u540C\u4E00\u6C14\u6CE1\u586B\u5199\u76F8\u5173\u7684\u5168\u90E8\u9875\u7801\uFF1B\u540C\u4E00\u4E2A\u8DE8\u9875\u6C14\u6CE1\u5408\u4E3A\u4E00\u6761\u5B8C\u6574\u5BF9\u767D\uFF0C\u6309\u5347\u5E8F\u6392\u5217"),Yg="\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",qg="\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",Wg=J.object({type:J.enum(["dialogue","inner_thought"]),content:st,pages:Fg,regions:ja,speaker:st.describe(Yg),parenthetical:J.string()}),jI=J.discriminatedUnion("type",[J.object({type:J.enum(["action","transition"]),content:st,pages:Fg,regions:ja}),Wg]),Zg=J.object({space:J.union([J.enum(["interior","exterior"]),dl]),time:J.union([J.enum(["day","night","dawn","dusk"]),dl]),location:J.string().describe("\u672C\u573A\u5730\u70B9\u7684\u89C4\u8303\u540D\uFF0C\u5FC5\u987B\u5DF2\u5728\u5DF2\u77E5\u8BBE\u5B9A\u6216\u672C\u6B21 registry_delta \u767B\u8BB0\uFF1B\u7A7A\u95F4\u65E0\u6CD5\u786E\u8BA4\u586B\u7A7A\u4E32"),characters:J.array(J.object({name:st,states:Bo})),props:Bo,actions:J.array(jI).min(1).describe(qg)}),Ha=J.object({registry_delta:KI,synopsis:st,scenes:J.array(Zg).min(1),open_threads:J.object({opened:J.array(J.object({text:st})),closed:J.array(J.object({ref:st}))}),ignored_pages:J.array(J.object({page:J.number().int().min(1),reason:st.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")}))}),Xg=Ha.extend({scenes:J.array(Zg.extend({actions:J.array(Wg.extend({type:J.enum(["action","transition","dialogue","inner_thought"]),speaker:J.string().describe(`${Yg}\uFF1Baction/transition \u586B\u7A7A\u4E32`)})).min(1).describe(qg)})).min(1)});import*as Ne from"node:fs";import*as bt from"node:path";import{spawn as HI}from"node:child_process";import{createHash as QI}from"node:crypto";import{PDFDocument as eh}from"pdf-lib";var ll=1200;function th(e,t){return new Promise((n,o)=>{let i=HI("pdftoppm",["-cropbox","-scale-to-x",String(ll),"-scale-to-y","-1","-jpeg","-jpegopt","quality=92",e,t],{stdio:["ignore","ignore","pipe"]}),r="";i.stderr.on("data",s=>{r+=String(s)}),i.on("error",s=>o(new S(`Cannot render comic pages: ${s.message}`,{exitCode:k,errorCode:"VIEW_PDF_RENDER_FAILED",hint:"Install Poppler (pdftoppm), then rerun scriptctl view."}))),i.on("close",s=>{s===0?n():o(new S(`PDF page rendering failed: ${r.trim()}`,{exitCode:k,errorCode:"VIEW_PDF_RENDER_FAILED",data:{actual:[e]}}))})})}async function Qa(e,t){let n=`review-pages/cropbox-w${ll}-q92/${e.sha256}`,o=bt.join(t,n),i=String(e.page_count).length,r=Array.from({length:e.page_count},(s,a)=>`page-${String(a+1).padStart(i,"0")}.jpg`);if(!r.every(s=>Ne.existsSync(bt.join(o,s)))){let s=`${o}.part`;Ne.rmSync(s,{recursive:!0,force:!0}),Ne.mkdirSync(s,{recursive:!0}),process.stderr.write(`\u6E32\u67D3\u6F2B\u753B\u539F\u9875 \xB7 ${e.title} \xB7 ${e.page_count} \u9875
|
|
211
|
+
`),await th(e.path,bt.join(s,"page"));for(let a of r)if(!Ne.existsSync(bt.join(s,a))||Ne.statSync(bt.join(s,a)).size===0)throw new S(`PDF renderer did not produce ${a}.`,{exitCode:k,errorCode:"VIEW_PDF_RENDER_FAILED"});Ne.rmSync(o,{recursive:!0,force:!0}),Ne.renameSync(s,o)}return r.map(s=>`${n}/${s}`)}async function nh(e,t,n){Ka.parse(t);let o=As([t.page],[t]);if(t.page>e.page_count||o.length)throw new Error(`Invalid comic region: ${o.join("; ")}`);let i=QI("sha256").update(JSON.stringify(t)).digest("hex"),r=`review-pages/cropbox-w${ll}-q92/${e.sha256}/regions/${i}.jpg`,s=bt.join(n,r);if(Ne.existsSync(s)&&Ne.statSync(s).size>0)return r;let a=await eh.load(Ne.readFileSync(e.path)),c=await eh.create(),[d]=await c.copyPages(a,[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,E=m/1e3,_=l===90?[y,g,E,w]:l===180?[1-w,y,1-g,E]:l===270?[1-E,1-w,1-y,1-g]:[g,1-E,w,1-y];d.setCropBox(p.x+_[0]*p.width,p.y+_[1]*p.height,(_[2]-_[0])*p.width,(_[3]-_[1])*p.height),c.addPage(d),Ne.mkdirSync(bt.dirname(s),{recursive:!0});let x=Ne.mkdtempSync(bt.join(bt.dirname(s),".region-"));try{let A=bt.join(x,"crop.pdf");Ne.writeFileSync(A,await c.save()),await th(A,bt.join(x,"page")),Ne.renameSync(bt.join(x,"page-1.jpg"),s)}finally{Ne.rmSync(x,{recursive:!0,force:!0})}return r}var FI=at.object({episode:at.number().int().positive(),document_id:at.string().min(1),source_number:at.number().nullable(),title:at.string(),path:at.string(),sha256:at.string(),page_count:at.number().int().positive(),size_bytes:at.number()}),YI=at.object({source:at.object({kind:at.enum(["comic-file","comic-directory"])}),episodes:at.array(FI)});function an(e){throw new S(e,{exitCode:k,errorCode:"REVIEW_COMIC_SOURCE_INVALID",hint:"Pass -s to the comic ingest workspace, or to its original PDF files with manifest.json beside script.json. Keep the original source PDFs unchanged."})}function qI(e){let t=ct.join(e,"manifest.json");if(!dt.existsSync(t))return!1;let n=at.object({source:at.object({kind:at.string()}).optional()}).parse(JSON.parse(dt.readFileSync(t,"utf8")));return n.source?.kind==="comic-file"||n.source?.kind==="comic-directory"}async function ih(e,t,n){let o=dt.statSync(e).isDirectory()&&qI(e)?ct.resolve(e):ct.dirname(ct.resolve(t)),i=ct.join(o,"manifest.json");dt.existsSync(i)||an("Comic review needs the ingest manifest to verify source identity.");let r=YI.safeParse(JSON.parse(dt.readFileSync(i,"utf8")));r.success||an(`Invalid comic manifest: ${r.error.message}`);let s=r.data,a=Do(JSON.parse(dt.readFileSync(t,"utf8")));a.version!==4&&an("Comic source review requires the ingested Script v4.");let c=a.episodes.filter(w=>!n?.length||n.includes(w.no));c.length||an("No selected episodes exist in this script.");let d=ct.resolve(e)===o?void 0:dt.statSync(e).isFile()?[ct.resolve(e)]:dt.readdirSync(e).filter(w=>/\.pdf$/i.test(w)).map(w=>ct.resolve(e,w)),p=new Map;for(let w of d??[])p.set(oh("sha256").update(dt.readFileSync(w)).digest("hex"),w);let l=new Map,f=[];for(let w of c){let y=new Set(w.scenes.flatMap(E=>E.actions.flatMap(_=>{let x=Ii.safeParse(_.raw.extend);return x.success?[x.data.scriptctl.source.document_id]:[]})));y.size||an(`Episode ${w.no} has no comic document identity; cannot safely match an original PDF.`);for(let E of y){let _=s.episodes.find(U=>U.document_id===E);_||an(`Unknown comic document: ${E}`),f.some(U=>U.document_id===E&&U.episode!==w.no)&&an(`Comic document ${E} is bound to multiple script episodes.`);let x=d?p.get(_.sha256):ct.resolve(o,_.path);(!x||!dt.existsSync(x))&&an(`Original PDF missing or changed: ${_.title}`),oh("sha256").update(dt.readFileSync(x)).digest("hex")!==_.sha256&&an(`Original PDF content changed: ${_.title}`);let b={..._,path:x};l.set(E,b),f.push({document_id:E,episode:w.no,title:_.title,page_count:_.page_count})}}let u=new Map,h=ct.dirname(ct.resolve(t));function m(w){let y=l.get(w);return y||an(`Comic document not available: ${w}`)}function g(w,y){return{path:w,label:y,data:dt.readFileSync(w).toString("base64")}}return{documents:f,async page(w,y){let E=m(w);(!Number.isInteger(y)||y<1||y>E.page_count)&&an(`Invalid page ${y} in ${w}.`);let _=u.get(w);_||(_=Qa(E,h),u.set(w,_));let x=await _;return g(ct.join(h,x[y-1]),`${w} \u7B2C ${y} \u9875\u6982\u89C8\uFF1B\u6587\u5B57\u4E0D\u6E05\u65F6\u7528 region \u653E\u5927`)},async region(w,y){let E=await nh(m(w),y,h);return g(ct.join(h,E),`${w} \u7B2C ${y.page} \u9875 ${JSON.stringify(y.box)}`)}}}import*as Pn from"node:fs";import*as ks from"node:path";import{z as gl}from"zod";import*as yr from"node:fs";import*as hr from"node:path";var fl=[".txt",".md",".docx"],ml={".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"},Ai=class extends Error{constructor(n){super(`Unsupported input: ${n}`);this.received=n}received};function ul(e){return hr.extname(e).toLowerCase()}function rh(e){return Object.hasOwn(ml,e)}function Ht(e){if(yr.statSync(e).isDirectory()){let o=yr.readdirSync(e).filter(r=>!r.startsWith(".")&&ul(r)===".pdf"&&yr.statSync(hr.join(e,r)).isFile()).sort().map(r=>hr.join(e,r)),i=yr.readdirSync(e).filter(r=>!r.startsWith(".")).filter(r=>rh(ul(r))).sort().map(r=>hr.join(e,r));if(o.length&&i.length)throw new Ai("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 Ai(`directory has no supported video or PDF files: ${e}`);return{kind:"video-directory",path:e,files:i}}let n=ul(e);if(n===".pdf")return{kind:"comic-file",path:e,ext:n};if(fl.includes(n))return{kind:"text",path:e,ext:n};if(rh(n))return{kind:"video-file",path:e,ext:n};throw new Ai(`file extension ${n||"(none)"} is not supported by ingest (txt/md/docx/video/pdf only)`)}var sh=/\.(mp4|mov|mkv|m4v|webm|avi|mpeg|mpg|flv|wmv)$/i;function ah(e,t=!1){if(t)return"video";if(!e)return"script";if(!Pn.existsSync(e))throw new S("Review source not found.",{exitCode:k,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass an existing original source or ingest workspace, or omit -s for script-only review."});if(Pn.statSync(e).isFile()){if(/\.pdf$/i.test(e))return"comic";if(fl.some(n=>ks.extname(e).toLowerCase()===n))return"text";if(sh.test(e))return"video"}else{let n=Pn.readdirSync(e).filter(s=>!s.startsWith(".")&&Pn.statSync(ks.join(e,s)).isFile()),o=n.some(s=>/\.pdf$/i.test(s)),i=n.some(s=>sh.test(s));if(o&&i)throw new S("Review source mixes PDF and video files.",{exitCode:k,errorCode:"REVIEW_SOURCE_AMBIGUOUS",hint:"Use a source directory containing only one media kind."});if(i)return"video";if(o)return"comic";let r=ks.join(e,"manifest.json");if(Pn.existsSync(r)){let s=gl.object({source:gl.object({kind:gl.string()})}).parse(JSON.parse(Pn.readFileSync(r,"utf8")));if(s.source.kind==="text")return"text";if(["comic-file","comic-directory"].includes(s.source.kind))return"comic"}}throw new S("Unsupported review source.",{exitCode:k,errorCode:"REVIEW_SOURCE_UNSUPPORTED",hint:"Use a text/comic ingest workspace, original txt/md/docx/PDF, a video file or a directory of videos."})}import*as ao from"node:fs";import*as Yt from"node:path";import{z as Xe}from"zod";import{z as ro}from"zod";var WI=ro.object({start_line:ro.number().int().positive(),end_line:ro.number().int().positive()}),hl=ro.object({kind:ro.literal("text"),document_id:ro.string().min(1),ranges:ro.array(WI).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")}),$P=ro.object({scriptctl:ro.object({source:hl})});function Fa(e){return`text-${e}`}import*as gh from"node:fs";import*as ch from"node:fs";import dh from"jszip";import{XMLParser as eA}from"fast-xml-parser";function ph(e){return e==null?"":String(e)}function Qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ue(e){return Array.isArray(e)}function lh(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(`
|
|
212
212
|
${s}`);continue}let a=i.length>1?i[1]??"":"";a||(a=n),n=a;let c=[];s&&c.push(`${s}.`);let d=i.slice(2).filter(p=>p);a&&d.length>0?c.push(`${a}\uFF0C${d.join(" ")}`):a?c.push(a):c.push(...d),t.push(c.join(" "))}return t.join(`
|
|
213
|
-
`)}function
|
|
214
|
-
`):Ue(s)&&n(s)}}}return n(e),t.join("").trim()}function
|
|
213
|
+
`)}function wr(e,t){let n=e[":@"];return Qt(n)?ph(n[t]).trim():""}function Ya(e,t){for(let[n,o]of Object.entries(e))if(so(n)===t&&Ue(o))return o;return null}function qa(e){let t=[],n=o=>{if(Ue(o)){for(let i of o)if(Qt(i))for(let[r,s]of Object.entries(i))r==="#text"&&s!==null&&s!==void 0?t.push(ph(s)):r!==":@"&&Ue(s)&&n(s)}};return n(e),t.join("")}function Wa(e){let t=uh.parse(e);if(!Ue(t))throw new Error("xlsx xml part has an unexpected shape");return t}function Jo(e,t){let n=[],o=i=>{let r=Ue(i)?i.filter(Qt):Qt(i)?[i]:[];for(let s of r)for(let[a,c]of Object.entries(s))so(a)===t&&Ue(c)&&n.push(s),Ue(c)&&o(c)};return o(e),n}function tA(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 nA(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 Za(e,t){let n=e.file(t);return n?n.async("string"):null}async function oA(e){let t=await Za(e,"xl/sharedStrings.xml");if(!t)return[];let n=Wa(t),o=[];for(let i of Jo(n,"si"))o.push(qa(Ya(i,"si")??[]));return o}async function iA(e){let t=await Za(e,"xl/workbook.xml"),n=await Za(e,"xl/_rels/workbook.xml.rels");if(!t||!n)throw new Error("xlsx missing workbook metadata");let o=new Map;for(let r of Jo(Wa(n),"Relationship")){let s=wr(r,"@_Id"),a=wr(r,"@_Target");s&&a&&o.set(s,nA("xl",a))}let i=[];for(let r of Jo(Wa(t),"sheet")){let s=wr(r,"@_name"),a=wr(r,"@_r:id"),c=o.get(a);s&&c&&i.push({name:s,path:c})}if(i.length===0)throw new Error("xlsx workbook contains no readable sheets");return i}function rA(e,t){let n=wr(e,"@_t");if(n==="inlineStr"){let s=Jo(e,"is")[0],a=s?Ya(s,"is"):null;return a?qa(a).trim():""}let o=Jo(e,"v")[0],i=o?Ya(o,"v"):null,r=i?qa(i).trim():"";if(!r&&n==="str"){let s=Jo(e,"is")[0],a=s?Ya(s,"is"):null;return a?qa(a).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 sA(e){let t=await dh.loadAsync(e),[n,o]=await Promise.all([oA(t),iA(t)]),i=[];for(let r of o){let s=await Za(t,r.path);if(!s)throw new Error(`xlsx missing worksheet part: ${r.path}`);let a=[];for(let c of Jo(Wa(s),"row")){let d=[];for(let p of Jo(c,"c")){let l=wr(p,"@_r"),f=l?tA(l):null,u=rA(p,n),h=f??d.length;for(;d.length<h;)d.push("");d[h]=u.trim()}d.some(p=>p)&&a.push(d)}i.push({name:r.name,rows:a})}return i}var uh=new eA({ignoreAttributes:!1,attributeNamePrefix:"@_",preserveOrder:!0,trimValues:!1,textNodeName:"#text"});function so(e){let t=e.indexOf(":");return t>=0?e.slice(t+1):e}function yl(e){let t=[];function n(o){if(Ue(o)){for(let i of o)if(Qt(i))for(let[r,s]of Object.entries(i)){if(r===":@"||r==="#text"&&typeof s=="string")continue;let a=so(r);if(a==="t"){if(Ue(s)){for(let c of s)if(Qt(c)){let d=c["#text"];typeof d=="string"&&t.push(d)}}}else a==="tab"?t.push(" "):a==="br"||a==="cr"?t.push(`
|
|
214
|
+
`):Ue(s)&&n(s)}}}return n(e),t.join("").trim()}function aA(e){let t=[];for(let n of e)if(Qt(n))for(let[o,i]of Object.entries(n)){if(so(o)!=="tr")continue;let r=[];if(Ue(i)){for(let s of i)if(Qt(s)){for(let[a,c]of Object.entries(s))if(so(a)==="tc"&&Ue(c)){let d=[],p=l=>{if(Ue(l)){for(let f of l)if(Qt(f))for(let[u,h]of Object.entries(f))if(so(u)==="p"&&Ue(h)){let m=yl(h);m&&d.push(m)}else Ue(h)&&p(h)}};p(c),r.push(d.join(" ").trim())}}}r.some(s=>s)&&t.push(r)}return lh(t)}async function cA(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"),a=await sA(s);for(let c of a)c.rows.length>0&&t.push([`Embedded Sheet ${o}: ${c.name}`,lh(c.rows)])}return t}async function fh(e){let t;try{t=await dh.loadAsync(ch.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=uh.parse(o),r=null,s=d=>{if(Ue(d)){for(let p of d)if(Qt(p))for(let[l,f]of Object.entries(p)){if(so(l)==="body"&&Ue(f)){r=f;return}Ue(f)&&s(f)}}};s(i);let a=[];if(r===null){let d=p=>{if(Ue(p)){for(let l of p)if(Qt(l))for(let[f,u]of Object.entries(l))if(so(f)==="p"&&Ue(u)){let h=yl(u);h&&a.push(h)}else Ue(u)&&d(u)}};d(i)}else for(let d of r)if(Qt(d))for(let[p,l]of Object.entries(d)){if(p.startsWith("@_")||p===":@"||p==="#text"||!Ue(l))continue;let f=so(p);if(f==="p"){let u=yl(l);u&&a.push(u)}else if(f==="tbl"){let u=aA(l);u&&a.push(u)}}let c=await cA(t);for(let[d,p]of c)a.push(`
|
|
215
215
|
## ${d}
|
|
216
216
|
`),a.push(p);return[a.join(`
|
|
217
217
|
|
|
218
|
-
`),c.length>0]}var
|
|
219
|
-
`)}function
|
|
220
|
-
`),{line:p}=Xe.object({line:Xe.number().int().nonnegative()}).parse(r("pass1/body_start.json"));p>=d.length&&Ft("Text body start is outside the source snapshot.");let l=
|
|
221
|
-
media: ${d.provider}/${d.model}`:""}`:"the review agent bundle is present but exports no reviewScript",data:{ready:w,review_kind:r,provider:a.provider,model:a.model,...d?{media_provider:d.provider,media_model:d.model}:{},llm_config:t.sourcePath??"builtin"}},w?V:q]}let l=he(e);if(!
|
|
222
|
-
`);try{let m={scriptPath:l,...
|
|
223
|
-
`).flatMap(w=>{let y;try{y=JSON.parse(w)}catch{return[]}return y&&(y.type==="episode"||y.type==="global")?[y]:[]})),...a,maxSteps:pt(e,"max_steps",300),episodeTimeoutMs:pt(e,"episode_timeout_ms",9e5),onEvent:h};if(r==="comic"){let g=await
|
|
224
|
-
|
|
225
|
-
|
|
218
|
+
`),c.length>0]}var wl=class extends Error{};function mh(e){return e.replace(/^/,"").replace(/\r\n?/g,`
|
|
219
|
+
`)}function dA(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{throw new wl("source is not valid UTF-8")}}async function Xa(e,t){if(t===".docx"){let[n]=await fh(e);return mh(n)}return mh(dA(gh.readFileSync(e)))}import{z as ec}from"zod";function xl(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 El(e,t,n){return{kind:"text",document_id:t,ranges:[xl(e,n)]}}function hh(e,t,n){for(let o of e.episodes)for(let i of o.scenes)for(let r of i.actions){let s=ec.object({scriptctl:ec.record(ec.string(),ec.json()).optional()}).parse(r.extend??{});r.extend={...r.extend,scriptctl:{...s.scriptctl,source:El(r.identity_key,t,n)}}}}var pA=Xe.object({source:Xe.object({kind:Xe.literal("text"),sha256:Xe.string().length(64),path:Xe.string()})}),lA=Xe.object({version:Xe.literal(3),episode:Xe.record(Xe.string(),Xe.string()),action:Xe.record(Xe.string(),Xe.string())});function Ft(e){throw new S(e,{exitCode:k,errorCode:"REVIEW_TEXT_SOURCE_INVALID",hint:"Pass -s to the text ingest workspace, or its original txt/md/docx with the ingest workspace beside script.json. Keep pass1/source.txt, body_start.json and v4_identity_map.json."})}async function yh(e,t,n){let o=ao.statSync(e).isDirectory(),i=o?Yt.resolve(e):Yt.dirname(Yt.resolve(t)),r=y=>{let E=Yt.join(i,y);return ao.existsSync(E)||Ft(`Text ingest artifact missing: ${E}`),JSON.parse(ao.readFileSync(E,"utf8"))},s=pA.parse(r("manifest.json")),a=Yt.join(i,"pass1/source.txt");ao.existsSync(a)||Ft("Text review requires the normalized original source snapshot.");let c=ao.readFileSync(a,"utf8");if(_e(c)!==s.source.sha256&&Ft("The original text snapshot has changed since ingest."),!o){let y=await Xa(e,Yt.extname(e).toLowerCase());_e(y)!==s.source.sha256&&Ft("The supplied text does not match this ingest source.")}let d=c.split(`
|
|
220
|
+
`),{line:p}=Xe.object({line:Xe.number().int().nonnegative()}).parse(r("pass1/body_start.json"));p>=d.length&&Ft("Text body start is outside the source snapshot.");let l=lA.parse(r("v4_identity_map.json")),f=Do(JSON.parse(ao.readFileSync(t,"utf8")));f.version!==4&&Ft("Text source review requires the ingested Script v4.");let u=Fa(s.source.sha256),h=Object.entries(l.episode).map(([y,E])=>({id:E,...xl(y,p)})).sort((y,E)=>y.start_line-E.start_line);h.some(y=>y.end_line>d.length)&&Ft("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 E=h.filter(A=>A.id===y.id);E.length!==1&&Ft(`Episode ${y.no} has no unambiguous text source identity.`);let _=E[0],x=h[h.indexOf(_)+1];return{episode:y.no,start_line:h.indexOf(_)===0?p+1:_.start_line,end_line:x?x.end_line:d.length}});m.length||Ft("No selected episodes exist in this script.");let g=new Map,w=new Map(Object.entries(l.action).map(([y,E])=>[E,El(y,u,p)]));for(let y of Un(f)){if(!m.some(x=>x.episode===y.scene.ep.no))continue;let E=Xe.object({scriptctl:Xe.object({source:hl.optional()}).optional()}).safeParse(y.raw.extend??{});E.success||Ft(`Invalid text source metadata on ${y.anchor}.`);let _=E.data.scriptctl?.source??w.get(y.anchor);_&&(_.document_id!==u&&Ft(`Action ${y.anchor} belongs to a different text document.`),_.ranges.some(x=>x.start_line>x.end_line||x.end_line>d.length)&&Ft(`Invalid source lines on ${y.anchor}.`),g.set(y.anchor,_))}return{document_id:u,title:Yt.basename(s.source.path),path:a,lines:d,episodes:m,references:g}}var xh="review-agent",mA=["minimal","low","medium","high"];function tc(e,t){let n=t||xh,o=e.models[n];if(!o)throw new S(`LLM profile "${n}" is not defined.`,{exitCode:k,errorCode:"REVIEW_PROFILE_UNKNOWN",hint:`Define it under models, or pick one of: ${Object.keys(e.models).join(", ")}.`,data:{expected:["a defined models entry"],actual:[n]}});let i=e.providers[o.provider];if(!i)throw new S(`Provider "${o.provider}" is not defined.`,{exitCode:k,errorCode:"REVIEW_PROVIDER_UNKNOWN",hint:`Available providers: ${Object.keys(e.providers).join(", ")}.`,data:{expected:["a defined providers entry"],actual:[o.provider]}});let r=(process.env[i.apiKeyEnv]??"").trim();if(!r&&i.protocol!=="google-vertex")throw new S(`${i.apiKeyEnv} is not set.`,{exitCode:k,errorCode:"REVIEW_API_KEY_MISSING",hint:`Export ${i.apiKeyEnv} for provider ${o.provider}.`,data:{expected:[i.apiKeyEnv],actual:["<empty>"]}});let s=i.protocol.startsWith("google")&&mA.includes(o.reasoning??"")?o.reasoning:void 0;return{provider:o.provider,model:o.model,baseUrl:i.baseUrl,apiKey:r,maxAttempts:i.maxAttempts,protocol:i.protocol,responseSchemaField:i.videoResponseSchemaField,...s?{thinking:s}:{}}}function wh(e){let{baseUrl:t,...n}=e;return{...n,...t?{baseUrl:t}:{}}}function _l(e,t,n=!1){let o=wh(tc(e,t));if(n||process.env.SCRIPTCTL_REVIEW_SINGLE_MODEL==="1")return{...o,singleModel:!0};let i=(e.models[t]?.fallbacks??[]).flatMap(r=>{let s=e.models[r],a=s&&e.providers[s.provider];return a&&a.protocol!=="google-vertex"&&!process.env[a.apiKeyEnv]?.trim()?[]:[wh(tc(e,r))]});return{...o,fallbacks:i}}async function cn(){let e=nc.dirname(uA(import.meta.url)),t=nc.join(e,"review-agent.js"),n=ki.existsSync(t)?fA(t).href:"@lingjingai/review-agent";try{return await import(n)}catch(o){throw new S("The review agent is not installed.",{exitCode:q,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 bs(e){let t=e.trim();if(!t)return;let n=t.split(",").map(o=>Number(o.trim()));if(n.some(o=>!Number.isInteger(o)||o<1))throw new S("--episodes takes a comma-separated list of 1-based episode numbers.",{exitCode:k,errorCode:"REVIEW_EPISODES_INVALID",hint:"For example: --episodes 1,2,5",data:{expected:["1-based episode numbers"],actual:[t]}});return n}function pt(e,t,n){let o=e[t];if(o===void 0)return n;let i=Number(o);if(!Number.isFinite(i)||i<=0)throw new S(`--${t.replace(/_/g,"-")} must be a positive number.`,{exitCode:k,errorCode:"REVIEW_OPTION_INVALID",hint:`Pass a positive number for --${t.replace(/_/g,"-")}.`,data:{expected:["a positive number"],actual:[String(o)]}});return i}async function Eh(e){let t=Co(O(e.llm_config).trim()||void 0),n=O(e.model).trim(),o=O(e.source_path).trim(),i=(Array.isArray(e.video)?e.video:[]).map(m=>m.trim()).filter(m=>m.length>0),r=ah(o,i.length>0),a=_l(t,n||(r==="comic"?"review-comic":r==="text"?"review-text":xh),e.fallback===!1),c=O(e.media_model).trim(),d=r==="video"?c?_l(t,c,e.fallback===!1):t.source==="builtin"&&!n?_l(t,"review-media",e.fallback===!1):a:void 0,p=O(e.assets).split(",").map(m=>m.trim()).filter(Boolean);if(p.length&&(r!=="video"||e.converge_only!==!0||e.converge===!1))throw new S("--assets \u7528\u4E8E\u89C6\u9891\u8D44\u4EA7\u5B9A\u70B9\u590D\u6838\uFF0C\u8BF7\u540C\u65F6\u63D0\u4F9B --converge-only \u4E0E\u89C6\u9891\u6765\u6E90\u3002",{exitCode:k,errorCode:"REVIEW_OPTION_INVALID",hint:"\u7528 --assets actXXXXXX --converge-only\uFF1B--episodes \u53EF\u9650\u5B9A\u4EBA\u7269\u9636\u6BB5\u590D\u6838\u96C6\u6570\u3002",data:{expected:["video review with --converge-only"],actual:[r]}});if(e.check){let m=await cn(),w=typeof{script:m.reviewPlainScript,text:m.reviewTextScript,comic:m.reviewComicScript,video:m.reviewVideoScript}[r]=="function";return[{text:w?`ready: ${a.provider}/${a.model}${d?`
|
|
221
|
+
media: ${d.provider}/${d.model}`:""}`:"the review agent bundle is present but exports no reviewScript",data:{ready:w,review_kind:r,provider:a.provider,model:a.model,...d?{media_provider:d.provider,media_model:d.model}:{},llm_config:t.sourcePath??"builtin"}},w?V:q]}let l=he(e);if(!ki.existsSync(l))throw new S("Local script file not found.",{exitCode:k,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[l]}});let f=i.filter(m=>!ki.existsSync(m));if(f.length>0)throw new S("A --video path does not exist.",{exitCode:k,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass --video once per episode, in episode order.",data:{expected:["existing video files"],actual:f.slice(0,5)}});if(o&&!ki.existsSync(o))throw new S("Review source not found.",{exitCode:k,errorCode:"REVIEW_SOURCE_NOT_FOUND",hint:"Pass an existing source or ingest workspace, or omit -s for script-only review.",data:{expected:["existing source or ingest workspace"],actual:[o]}});let u=await cn(),h=m=>process.stdout.write(JSON.stringify(m)+`
|
|
222
|
+
`);try{let m={scriptPath:l,...bs(O(e.episodes))?{episodes:bs(O(e.episodes))}:{},concurrency:pt(e,"concurrency",5),converge:e.converge!==!1,convergeOnly:e.converge_only===!0,resumeUnits:(Array.isArray(e.resume_log)?e.resume_log:[]).flatMap(g=>ki.readFileSync(g,"utf8").split(`
|
|
223
|
+
`).flatMap(w=>{let y;try{y=JSON.parse(w)}catch{return[]}return y&&(y.type==="episode"||y.type==="global")?[y]:[]})),...a,maxSteps:pt(e,"max_steps",300),episodeTimeoutMs:pt(e,"episode_timeout_ms",9e5),onEvent:h};if(r==="comic"){let g=await ih(o,l,m.converge?void 0:m.episodes);await u.reviewComicScript({...m,comic:g})}else if(r==="text"){let g=await yh(o,l,m.converge?void 0:m.episodes);await u.reviewTextScript({...m,text:g})}else r==="video"?await u.reviewVideoScript({...m,source:o,videos:i,mediaConfig:d,...p.length?{convergenceAssets:p}:{},strategy:e.review_strategy==="batch"?"batch":"legacy",mediaModel:d.model,...e.media_budget===void 0?{}:{mediaBudget:pt(e,"media_budget",1)}}):await u.reviewPlainScript(m)}catch(m){throw m instanceof S?m:new S("Review failed.",{exitCode:q,errorCode:"REVIEW_FAILED",hint:r==="video"?"Read the error details and NDJSON episode reports before retrying.":`Read the error details and episode reports${r==="script"?"":` in .review/${r}/`} before retrying.`,data:{expected:["a completed review run"],actual:[m instanceof Error?m.message:String(m)]}})}return[{text:"",data:{}},V]}import*as oc from"node:path";import{pathToFileURL as gA}from"node:url";var Sl=e=>e==null?"":String(e),hA=5180,yA=new Set(["127.0.0.1","localhost","::1"]);function wA(e){let t=Sl(e).trim(),n=t===""?hA:Number(t);if(!Number.isInteger(n)||n<0||n>65535)throw new S("--port takes a port number.",{exitCode:k,errorCode:"REVIEW_VIEW_PORT_INVALID",hint:"Pass a number from 1 to 65535, or 0 for any free port.",data:{actual:[t]}});return n}function xA(e,t,n){return new Promise((o,i)=>{e.once("error",r=>{r.code==="EADDRINUSE"?i(new S(`Port ${t} is already in use on ${n}.`,{exitCode:k,errorCode:"REVIEW_VIEW_PORT_BUSY",hint:"Pass another --port, or stop what is using this one."})):r.code==="EADDRNOTAVAIL"||r.code==="ENOTFOUND"?i(new S(`This machine has no address ${n}.`,{exitCode:k,errorCode:"REVIEW_VIEW_HOST_INVALID",hint:"Pass an address of this machine, such as its LAN or Tailscale address."})):i(r)}),e.listen(t,n,()=>o(e.address().port))})}async function _h(e){if((process.env.SANDBOX_PROJECT_GROUP_NO??"").trim())throw new S("`review-view` runs a web server; it is unavailable in the sandbox.",{exitCode:k,errorCode:"REVIEW_VIEW_SANDBOX",hint:"Run it on a machine with a browser, against a copy of the workspace."});let t=(e._args??[]).flat().map(Sl).filter(Boolean),n=t.length?t:["."],o=Sl(e.host).trim()||"127.0.0.1",i=wA(e.port),r=yA.has(o),s=gA(oc.join(ps(),"scripts","review-view.mjs")).href,{createReviewViewServer:a}=await import(s),{server:c,workspaces:d}=a({paths:n,allowOpen:r});if(d.length===0)throw new S("No review runs found here.",{exitCode:k,errorCode:"REVIEW_VIEW_EMPTY",hint:"Pass a workspace that `scriptctl review` ran in, or a folder holding several.",data:{actual:n.map(h=>oc.resolve(h))}});let p=await xA(c,i,o),l=`http://${o.includes(":")?`[${o}]`:o}:${p}/`,f=r?"\u53EA\u6709\u8FD9\u53F0\u7535\u8111\u80FD\u6253\u5F00\u3002\u8981\u5728\u522B\u7684\u7535\u8111\u4E0A\u770B\uFF0C\u52A0 --host <\u8FD9\u53F0\u673A\u5668\u7684\u5C40\u57DF\u7F51\u6216 Tailscale \u5730\u5740>\u3002":"\u6CA1\u6709\u767B\u5F55\u4FDD\u62A4\uFF0C\u80FD\u8FDE\u5230\u8FD9\u4E2A\u5730\u5740\u7684\u4EBA\u90FD\u80FD\u6253\u5F00\u3002";process.stderr.write(`\u5BA1\u6838\u94FE\u8DEF\uFF1A${l}
|
|
224
|
+
${d.length} \u6B21\u8FD0\u884C\uFF0C${f}
|
|
225
|
+
\u6309 Ctrl-C \u505C\u6B62\u3002
|
|
226
|
+
`);let u=()=>{c.close(),c.closeAllConnections()};return process.once("SIGINT",u),process.once("SIGTERM",u),[{text:l,data:{url:l,workspaces:d.map(h=>h.path)}},V]}import*as Cn from"node:fs";import*as ye from"node:fs";import*as Se from"node:path";import{createHash as EA}from"node:crypto";var vs=["analyze","direction","plan","write","review"],_A={analyze:"reskin",direction:"reskin-claude",plan:"reskin-claude",write:"reskin",review:"reskin-claude"},SA={"claude-opus-5-5":{input:4,cached_input:.2,output:20}};function Il(e,t){let n=Se.join(e,t);return{root:n,source:Se.join(n,"0_input","script.json"),analysis:Se.join(n,"1_src","\u62C6\u89E3.json"),direction:Se.join(n,"2_new","\u6362\u58F3\u65B9\u5411.json"),brief:Se.join(n,"2_new","\u6362\u58F3\u65B9\u5411.md"),plan:Se.join(n,"2_new","\u6362\u58F3\u65B9\u6848.json"),script:Se.join(n,"4_output","script.json"),log:o=>Se.join(n,"logs",`${o}.ndjson`),status:Se.join(n,"status.json")}}function ic(e,t){ye.mkdirSync(Se.dirname(e),{recursive:!0}),ye.writeFileSync(`${e}.tmp`,JSON.stringify(t,null,2)+`
|
|
227
|
+
`),ye.renameSync(`${e}.tmp`,e)}function Al(e){return ye.existsSync(e)?JSON.parse(ye.readFileSync(e,"utf8")):null}function IA(e,t){let n=Object.keys(e).filter(o=>t.startsWith(o)).sort((o,i)=>i.length-o.length)[0];return n?e[n]:null}function Sh(e,t){let n=0,o=[];for(let[i,r]of Object.entries(e)){let s=IA(t,i);if(!s){o.push(i);continue}n+=((r.input-r.cached_input)*s.input+r.cached_input*s.cached_input+r.output*s.output)/1e6}return{usd:n,unpriced:o}}function AA(e,t){for(let n of t){let o=e[n.model]??={calls:0,input:0,cached_input:0,output:0};o.calls+=1,o.input+=n.input_tokens,o.cached_input+=n.cached_input_tokens,o.output+=n.output_tokens}}var kA=new Set(["unit-done","episode","global","direction-done"]),bA=["\u6210\u7ACB","\u8981\u6539\u505A\u6CD5","\u7275\u5F3A","\u6491\u4E0D\u4F4F"];function vA(e){if(!e)return"\u672A\u5BA1\u8BFB";let t=[...e.stages,...e.points];return bA.map(n=>[n,t.filter(o=>o.grade===n).length]).filter(([,n])=>n).map(([n,o])=>`${n} ${o}`).join(" \xB7 ")}function Ih(e){return e?[...e.stages.filter(t=>t.grade!=="\u6210\u7ACB").map(t=>`${t.stage}\uFF08${t.grade}\uFF09\uFF1A${t.note}`),...e.points.filter(t=>t.grade!=="\u6210\u7ACB").map(t=>`${t.point}\uFF08${t.grade}\uFF09\uFF1A${t.note}`)]:[]}function OA(e,t){return EA("sha256").update(JSON.stringify([ye.readFileSync(e,"utf8"),t.notes??"",t.custom??"",t.market??"",t.rating??"",t.avoid??[]])).digest("hex")}function RA(e,t,n){let o=n.market?.trim();return[`# ${e.title}`,`\u76EE\u6807\u5E02\u573A\uFF1A${o||"\u540C\u539F\u5267"}`,o&&n.language?.trim()?`\u53F0\u8BCD\u8BED\u8A00\uFF1A${n.language.trim()}`:"",`\u5C3A\u5EA6\uFF1A${n.rating?.trim()||"\u540C\u539F\u5267"}`,`\u6362\u58F3\uFF1A${e.shell}`,`\u6362\u6CD5\uFF1A${e.approach}`,e.keeps?`\u6CBF\u7528\u539F\u5267\uFF1A${e.keeps}`:"",e.changes?`\u5FC5\u987B\u6539\u52A8\uFF1A${e.changes}`:"",e.risks?`\u98CE\u9669\uFF1A${e.risks}`:"",Ih(e.review).length?`\u72EC\u7ACB\u5BA1\u8BFB\u6307\u51FA\u7684\u627F\u63A5\u95EE\u9898\uFF0C\u65B9\u6848\u91CC\u8981\u89E3\u51B3\uFF1A
|
|
228
|
+
${Ih(e.review).map(i=>`- ${i}`).join(`
|
|
226
229
|
`)}`:"",e.research?`\u65B0\u58F3\u5728\u5F53\u5730\u7684\u73B0\u5B9E\uFF08\u8054\u7F51\u8C03\u7814\uFF0C\u5177\u4F53\u505A\u6CD5\u4F9D\u636E\u5B83\u8BBE\u8BA1\uFF09\uFF1A
|
|
227
230
|
${e.research.text}`:"",t.research?`\u76EE\u6807\u5E02\u573A\u7684\u5F53\u5730\u73B0\u5B9E\uFF08\u8054\u7F51\u8C03\u7814\uFF09\uFF1A
|
|
228
231
|
${t.research.text}`:"",t.verdict&&t.reason?`\u65B9\u5411\u5224\u65AD\uFF08${t.verdict}\uFF09\uFF1A${t.reason}`:"",n.notes?.trim()?`\u7528\u6237\u8981\u6C42\uFF1A${n.notes.trim()}`:""].filter(Boolean).join(`
|
|
229
232
|
|
|
230
233
|
`)+`
|
|
231
|
-
`}function
|
|
232
|
-
`),
|
|
233
|
-
`)[0].replace(/\|/g,"\uFF0F");return t.length>160?`${t.slice(0,160)}\u2026`:t}function
|
|
234
|
-
`))}var
|
|
235
|
-
`);async function
|
|
236
|
-
`),[{text:"",data:{}},s.type==="paths-done"&&s.state==="completed"?V:q]}catch(s){throw
|
|
237
|
-
`),[{text:"",data:{}},f.type==="direction-done"&&f.state==="completed"?V:q]}catch(f){throw wr(f,"RESKIN_DIRECTION_FAILED")}}async function Oh(e){if(e.check)return xr(e,"buildReskinPlan");let{config:t}=dn(e),n=et(he(e),"source script"),o=et(O(e.analysis).trim(),"analysis"),i=et(O(e.direction).trim(),"direction"),r=O(e.output).trim(),s=O(e.until).trim();if(!r)throw new S("Plan output path missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass -o <\u6362\u58F3\u65B9\u6848.json>.",data:{expected:["plan output path"],actual:["<empty>"]}});if(s&&!Sl.includes(s))throw new S("Unknown plan layer.",{exitCode:k,errorCode:"RESKIN_LAYER_UNKNOWN",hint:`Pass --until ${Sl.join("|")}.`,data:{expected:[...Sl],actual:[s]}});let a=await cn();try{let c=await a.buildReskinPlan({...t,sourcePath:n,analysisPath:o,directionPath:i,planPath:r,...s?{until:s}:{},force:e.force===!0,...e.unit_timeout_ms!==void 0?{unitTimeoutMs:pt(e,"unit_timeout_ms",18e5)}:{},onEvent:ki}),d=c.type==="plan-done"&&c.state!=="failed";return[{text:"",data:{}},d?V:q]}catch(c){throw wr(c,"RESKIN_PLAN_FAILED")}}async function Rh(e){let t=O(e.review_model).trim()?dn({...e,model:e.review_model}).config:void 0;if(e.check)return xr(e,"writeReskinScript");let{config:n}=dn(e),o=he(e),i=et(O(e.source).trim(),"source script"),r=et(O(e.analysis).trim(),"analysis"),s=et(O(e.plan).trim(),"plan"),a=As(O(e.episodes)),c=await cn();try{let d=await c.writeReskinScript({...n,sourcePath:i,analysisPath:r,planPath:s,scriptPath:o,...a?{episodes:a}:{},force:e.force===!0,concurrency:pt(e,"concurrency",6),...t?{reviewModel:t}:{},episodeTimeoutMs:pt(e,"episode_timeout_ms",48e4),onEvent:ki});return[{text:"",data:{}},d.type==="done"&&d.failed.length===0?V:q]}catch(d){throw wr(d,"RESKIN_WRITE_FAILED")}}async function Mh(e){if(e.check)return xr(e,"reviewReskinScript");let{config:t}=dn(e),n=et(he(e),"reskinned script"),o=et(O(e.source).trim(),"source script"),i=et(O(e.analysis).trim(),"analysis"),r=et(O(e.plan).trim(),"plan"),s=As(O(e.episodes)),a=await cn();try{let c=await a.reviewReskinScript({...t,scriptPath:n,sourcePath:o,analysisPath:i,planPath:r,...s?{episodes:s}:{},concurrency:pt(e,"concurrency",10),converge:e.converge!==!1,convergeOnly:e.converge_only===!0,maxSteps:pt(e,"max_steps",300),episodeTimeoutMs:pt(e,"episode_timeout_ms",9e5),onEvent:ki});return[{text:"",data:{}},c.some(d=>(d.type==="episode"||d.type==="global")&&d.state==="failed")?q:V]}catch(c){throw wr(c,"RESKIN_REVIEW_FAILED")}}async function Nh(e){let t=e._args??[],n=et(O(t[0]).trim(),"batch manifest"),o=O(e.output).trim();if(!o)throw new S("Batch output folder missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass -o <folder>; each drama gets its own project folder inside it.",data:{expected:["batch output folder"],actual:["<empty>"]}});let i=O(e.until).trim();if(i&&!ks.includes(i))throw new S("Unknown batch step.",{exitCode:k,errorCode:"RESKIN_LAYER_UNKNOWN",hint:`Pass --until ${ks.join("|")}.`,data:{expected:[...ks],actual:[i]}});let r;try{r=_h(n)}catch(l){throw new S("Batch manifest is invalid.",{exitCode:k,errorCode:"RESKIN_BATCH_INVALID",hint:"Fix the manifest and run again.",data:{expected:["{ dramas: [{ source, ... }] }"],actual:[l instanceof Error?l.message:String(l)]}})}let s=O(e.pick).trim();s&&(r.pick=s==="recommended"?"recommended":pt(e,"pick",1));let a=new Map([...Object.values(r.models),...r.search?[r.search]:[],...r.ideas??[]].map(l=>[l,dn({...e,model:l}).config])),c=await cn();Cn.mkdirSync(o,{recursive:!0});let p=(await Sh(r,c,{outputDir:o,until:i||void 0,concurrency:pt(e,"concurrency",2),attempts:pt(e,"attempts",3),config:l=>a.get(l),onEvent:ki})).filter(l=>l.state==="failed").length;return[{text:"",data:{}},p?q:V]}function Lh(e,t){te(e.command("review"),"write").description("\u6D3E\u53D1 agent \u5BA1\u6838\u5267\u672C\uFF1A\u7ED9 -s \u5BF9\u7167\u6587\u672C\u3001\u6F2B\u753B\u6216\u89C6\u9891\u539F\u7A3F\uFF0C\u4E0D\u7ED9\u5219\u68C0\u67E5\u5267\u672C\u5185\u90E8\u4E00\u81F4\u6027").option("-s, --source-path <path>","\u6587\u672C/\u6F2B\u753B ingest \u5DE5\u4F5C\u533A\u3001\u539F txt/md/docx/PDF \u6216\u89C6\u9891\u6587\u4EF6/\u76EE\u5F55").option("--video <path>","\u7B2C N \u96C6\u7684\u89C6\u9891\uFF1B\u6309\u96C6\u987A\u5E8F\u91CD\u590D\u4F20\uFF0C\u8986\u76D6 -s \u7684\u76EE\u5F55\u6392\u5E8F",(i,r)=>[...r,i],[]).addOption(new kA("--review-strategy <strategy>","\u89C6\u9891\u5BA1\u6838\u6267\u884C\u65B9\u5F0F\uFF1Abatch \u53EF\u9009\u8054\u5408\u5BA1\u6838\uFF08\u9700\u4EBA\u5DE5\u590D\u6838\u8BC1\u636E\u51B2\u7A81\uFF09\uFF1Blegacy \u9010\u9879\u4FEE\u6B63").choices(["batch","legacy"]).default("legacy")).option("--episodes <list>","\u53EA\u5BA1\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u5267\uFF09").option("--concurrency <n>","\u9010\u96C6\u5BA1\u6838\u548C\u5168\u5267\u8D44\u4EA7\u6838\u5BF9\u7684\u5E76\u53D1\u6570",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u8D85\u65F6\uFF08\u9ED8\u8BA4 15 \u5206\u949F\uFF09\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>","\u5A92\u4F53\u9884\u7B97\uFF1A\u9010\u96C6\u9ED8\u8BA4 1 \u6B21\uFF1B\u6307\u5B9A\u4EBA\u7269\u6DF1\u5BA1\u9ED8\u8BA4\u8986\u76D6\u5168\u90E8\u76F8\u5173\u96C6\uFF0C\u663E\u5F0F\u503C\u9650\u5236\u672C\u6B21\u8986\u76D6\u96C6\u6570",Number).option("--converge-only","\u53EA\u6267\u884C\u5168\u5267\u6536\u655B\uFF0C\u4E0D\u91CD\u65B0\u5BA1\u6838\u5404\u96C6").option("--assets <list>","\u89C6\u9891\u5B9A\u70B9\u590D\u6838\u7684\u8D44\u4EA7 ID\uFF0C\u9017\u53F7\u5206\u9694\uFF1B\u4E0E --converge-only \u540C\u7528\uFF0C\u53EF\u7528 --episodes \u9650\u5B9A\u4EBA\u7269\u9636\u6BB5\u8303\u56F4").option("--resume-log <path>","\u4ECE\u5F53\u524D\u5267\u672C\u7684\u65E2\u6709\u5BA1\u6838\u65E5\u5FD7\u7EED\u8DD1\uFF0C\u4FDD\u7559\u5DF2\u5B8C\u6210\u5355\u5143\uFF1B\u591A\u4EFD\u65E5\u5FD7\u6309\u65F6\u95F4\u5148\u540E\u91CD\u590D\u4F20\u5165",(i,r=[])=>[...r,i]).option("--no-converge","\u8DF3\u8FC7\u5168\u5267\u6536\u655B\u9636\u6BB5").option("--model <profile>","\u8986\u76D6 LLM profile\uFF08\u89C6\u9891/\u7EAF\u5267\u672C\u9ED8\u8BA4 review-agent\uFF0C\u6587\u672C review-text\uFF0C\u6F2B\u753B review-comic\uFF09").option("--media-model <profile>","\u89C6\u9891\u53D6\u8BC1\u4F7F\u7528\u7684 LLM profile\uFF08\u5168\u96C6\u5B9A\u4F4D\u3001\u9759\u5E27\u4E0E\u97F3\u8F68\u6838\u5BF9\uFF09").option("--no-fallback","\u53EA\u7528\u6240\u9009\u6A21\u578B\uFF0C\u5931\u8D25\u65F6\u4E0D\u6362\u7528\u5176\u4ED6\u6A21\u578B").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(j(yh,t));let n=e.command("reskin").description("\u6362\u58F3\u4EFF\u5199\uFF1A\u62C6\u89E3\u539F\u5267\uFF0C\u63D0\u51FA\u65B0\u58F3\u65B9\u5411\uFF0C\u9010\u5C42\u5B9A\u6362\u58F3\u65B9\u6848\uFF08\u6574\u4F53\u65B9\u6848 \u2192 \u4E8B\u4EF6 \u2192 \u8282\u62CD\uFF09\uFF0C\u6309\u7ED3\u6784\u8868\u9010\u96C6\u5199\u65B0\u5267\uFF0C\u518D\u505A\u6362\u58F3\u5BA1\u6838"),o=i=>i.option("--model <profile>","\u8986\u76D6 LLM profile\uFF08\u9ED8\u8BA4 reskin\uFF09").option("--no-fallback","\u53EA\u7528\u6240\u9009\u6A21\u578B\uFF0C\u5931\u8D25\u65F6\u4E0D\u6362\u7528\u5176\u4ED6\u6A21\u578B\uFF08\u9ED8\u8BA4\u6309\u914D\u7F6E\u7684\u964D\u7EA7\u987A\u5E8F\u6362\u7528\uFF09").option("--llm-config <path>","LLM configuration file").option("--check","\u53EA\u68C0\u67E5\u6A21\u578B\u4E0E agent \u662F\u5426\u5C31\u7EEA");o(te(n.command("analyze"),"read").description("\u62C6\u89E3\u539F\u5267\uFF1A\u5148\u901A\u8BFB\u5168\u5267\u5212\u5206\u9636\u6BB5\u4E0E\u4E8B\u4EF6\uFF0C\u518D\u6309\u9636\u6BB5\u5E76\u884C\u5199\u4E8B\u4EF6\u4E8B\u5B9E\u3001\u6309\u96C6\u5E76\u884C\u5207\u8282\u62CD\uFF0C\u540C\u65F6\u5F52\u7EB3\u5168\u5267\u753B\u50CF\uFF08\u539F\u5267\u5730\u533A\u4E0E\u53F0\u8BCD\u8BED\u8A00\u3001\u6362\u58F3\u9002\u5408\u5EA6\uFF09\u3002-p \u4E3A\u539F\u5267\u5267\u672C\uFF1B\u5DF2\u5B8C\u6210\u7684\u5355\u5143\u4FDD\u5B58\u5728\u8F93\u51FA\u6587\u4EF6\u65C1\u7684 .cache/analyze.json\uFF0C\u518D\u6B21\u8FD0\u884C\u4ECE\u65AD\u70B9\u7EE7\u7EED").option("-o, --output <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--force","\u5FFD\u7565\u5DF2\u4FDD\u5B58\u7684\u8FDB\u5EA6\u91CD\u65B0\u62C6\u89E3").option("--concurrency <n>","\u5E76\u884C\u7684\u5355\u5143\u6570",Number).option("--unit-timeout-ms <ms>","\u5355\u4E2A\u5355\u5143\u7684\u8D85\u65F6",Number)).action(j(kh,t)),o(n.command("paths").description("\u9009\u9898\u5224\u65AD\uFF1A\u8BFB\u539F\u5267\u62C6\u89E3\u7684\u753B\u50CF\u4E0E\u5927\u7EB2\uFF0C\u9010\u4E2A\u5019\u9009\u5E02\u573A\u5217\u51FA\u8D70\u5F97\u901A\u7684\u6539\u7F16\u8DEF\u5F84\uFF08\u540C\u5E02\u573A\u6362\u8F7D\u4F53\u3001\u8DE8\u5E02\u573A\u672C\u5730\u5316\u3001\u8DE8\u5E02\u573A\u6362\u58F3\u3001\u6362\u4E16\u754C\u89C2\uFF09\uFF0C\u7ED9\u51FA\u5EFA\u8BAE\u505A\u51E0\u4E2A\u7248\u672C").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--markets <list>","\u5019\u9009\u5E02\u573A\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u5FC5\u586B\uFF09\uFF0C\u5982 \u4E2D\u56FD,\u5370\u5C3C,\u7F8E\u56FD").option("--notes <text>","\u7528\u6237\u8981\u6C42\u4E0E\u4E1A\u52A1\u4F18\u5148").option("-o, --output <path>","\u628A\u7ED3\u679C\u53E6\u5B58\u4E3A JSON")).action(j(bh,t)),o(te(n.command("direction"),"read").description("\u4E3A\u4E00\u4E2A\u76EE\u6807\u5E02\u573A\u627E\u65B0\u58F3\uFF1A\u5148\u8054\u7F51\u8C03\u7814\u5F53\u5730\u73B0\u5B9E\uFF08\u7ED9\u51FA --search-model \u65F6\uFF09\uFF0C\u518D\u7531\u5404\u53D1\u6563\u6A21\u578B\u5206\u522B\u5217\u60F3\u6CD5\u3001\u53BB\u91CD\u7559\u4E0B\u81F3\u591A 10 \u4E2A\uFF0C\u9010\u4E2A\u8C03\u7814\u65B0\u58F3\u5728\u5F53\u5730\u7684\u73B0\u5B9E\u5E76\u5C55\u5F00\uFF0C\u7531\u72EC\u7ACB\u5BA1\u8BFB\u9010\u4E2A\u9636\u6BB5\u548C\u9AD8\u8BC6\u522B\u573A\u9762\u7ED9\u51FA\u627F\u63A5\u7A0B\u5EA6\uFF08\u6210\u7ACB\u3001\u8981\u6539\u505A\u6CD5\u3001\u7275\u5F3A\u3001\u6491\u4E0D\u4F4F\uFF09\uFF0C\u6709\u4E00\u5904\u6491\u4E0D\u4F4F\u7684\u5019\u9009\u820D\u5F03\uFF0C\u5176\u4F59\u6392\u5E8F\u5E76\u63A8\u8350\uFF1B\u7ED9\u51FA --custom \u65F6\u5224\u65AD\u7528\u6237\u6307\u5B9A\u7684\u65B9\u5411\u5E76\u6309\u5B83\u8BBE\u8BA1\u3001\u5BA1\u8BFB\u4E00\u4E2A\u5019\u9009\u3002-p \u4E3A\u539F\u5267\u5267\u672C").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--notes <text>","\u7528\u6237\u7684\u6362\u58F3\u8981\u6C42").option("--custom <text>","\u7528\u6237\u6307\u5B9A\u7684\u6362\u58F3\u65B9\u5411").option("--market <text>","\u65B0\u5267\u9762\u5411\u7684\u76EE\u6807\u5E02\u573A\uFF0C\u9ED8\u8BA4\u540C\u539F\u5267").option("--rating <text>","\u5C3A\u5EA6\u8981\u6C42\uFF0C\u9ED8\u8BA4\u540C\u539F\u5267").option("--avoid <shell>","\u8FD9\u90E8\u539F\u5267\u5DF2\u505A\u8FC7\u7684\u7248\u672C\u7684\u58F3\uFF0C\u53EF\u91CD\u590D\u7ED9\u51FA\uFF1B\u65B0\u60F3\u6CD5\u4E0E\u5B83\u4EEC\u660E\u663E\u4E0D\u540C",(i,r=[])=>[...r,i]).option("--used <path>",'\u8FD9\u4E2A\u76EE\u6807\u5E02\u573A\u5DF2\u505A\u6210\u4EFF\u5199\u5267\u7684\u58F3\uFF08JSON \u6587\u4EF6\uFF0C[{ "drama": \u5267\u540D, "shell": \u65E7\u58F3 \u2192 \u65B0\u58F3 }]\uFF09\uFF1B\u5BA1\u8BFB\u6807\u51FA\u4E0E\u5B83\u4EEC\u76F8\u8FD1\u7684\u5019\u9009').option("--evidence <path>","\u76EE\u6807\u5E02\u573A\u540C\u7C7B\u5267\u6570\u636E\uFF08\u6587\u672C\u6587\u4EF6\uFF09\uFF1A\u4EE3\u8868\u5267\u548C\u5B83\u4EEC\u8BB2\u4EC0\u4E48\uFF0C\u7528\u6765\u542F\u53D1\u60F3\u6CD5\u548C\u5224\u65AD\u89C2\u4F17\u719F\u6089\u7A0B\u5EA6").option("--search-model <profile>","\u8054\u7F51\u641C\u7D22\u7528\u7684 LLM profile\uFF1A\u5B83\u548C\u5B83\u7684 fallbacks \u91CC\u7684 Gemini \u6E20\u9053\u8F6E\u6D41\u5F00\u641C\uFF0C\u8C03\u7814\u5F53\u5730\u73B0\u5B9E\uFF1B\u4E0D\u7ED9\u5219\u4E0D\u8C03\u7814").option("--idea-model <profile>","\u53D1\u6563\u60F3\u6CD5\u7684 LLM profile\uFF0C\u53EF\u91CD\u590D\u7ED9\u51FA\uFF1B\u51E0\u4E2A\u6A21\u578B\u5206\u522B\u5217\u60F3\u6CD5\u540E\u53BB\u91CD\uFF08\u9ED8\u8BA4\u7528 --model\uFF09",(i,r=[])=>[...r,i]).option("-o, --output <path>","\u628A\u7ED3\u679C\u53E6\u5B58\u4E3A JSON")).action(j(vh,t)),o(te(n.command("plan"),"read").description("\u9010\u5C42\u751F\u6210\u6362\u58F3\u65B9\u6848\uFF1A\u6574\u4F53\u65B9\u6848\uFF08\u542B\u9636\u6BB5\u8D70\u5411\uFF09\u2192 \u5404\u9636\u6BB5\u4E8B\u4EF6 \u2192 \u5404\u9636\u6BB5\u8282\u62CD \u2192 \u65B9\u6848\u6838\u9A8C \u2192 \u6545\u4E8B\u65F6\u95F4\u7EBF \u2192 \u4EBA\u7269\u9020\u578B\uFF0C\u4E0B\u5C42\u53EF\u56DE\u6539\u4E0A\u5C42\u5E76\u590D\u67E5\u53D7\u5F71\u54CD\u7684\u90E8\u5206\u3002-p \u4E3A\u539F\u5267\u5267\u672C\uFF1B\u5DF2\u6709\u65B9\u6848\u65F6\u4ECE\u672A\u5B8C\u6210\u7684\u90E8\u5206\u7EE7\u7EED").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--direction <path>","\u9009\u5B9A\u7684\u6362\u58F3\u65B9\u5411\u8BF4\u660E\uFF08\u5FC5\u586B\uFF09").option("-o, --output <path>","\u6362\u58F3\u65B9\u6848 JSON\uFF08\u5FC5\u586B\uFF09").option("--until <layer>","\u505A\u5230\u8FD9\u4E00\u5C42\u540E\u6682\u505C\uFF1Aoverall | events | beats").option("--force","\u5FFD\u7565\u5DF2\u6709\u65B9\u6848\u91CD\u65B0\u751F\u6210").option("--unit-timeout-ms <ms>","\u5355\u4E2A\u5355\u5143\u7684\u8D85\u65F6",Number)).action(j(Oh,t)),o(te(n.command("write"),"write").description("\u6309\u6362\u58F3\u65B9\u6848\u7684\u7ED3\u6784\u8868\u5199\u65B0\u5267\uFF1A\u9636\u6BB5\u5185\u6309\u96C6\u5E8F\u5199\uFF0C\u9636\u6BB5\u4E4B\u95F4\u5E76\u884C\uFF1B\u53EF\u9010\u96C6\u5BA1\u6838\u5E76\u4F20\u9012\u8D26\u672C\u3002-p \u4E3A\u65B0\u5267\u5267\u672C\uFF0C\u4E0D\u5B58\u5728\u6216\u6362\u540D\u6362\u5916\u89C2\u53D8\u5316\u65F6\u4ECE\u539F\u5267\u590D\u5236\uFF1B\u6BCF\u6761\u6B63\u6587\u8BB0\u4E0B\u6240\u5C5E\u7684\u65B0\u8282\u62CD\uFF0C\u4E0D\u5199\u65F6\u95F4\u6233").option("--source <path>","\u539F\u5267\u5267\u672C\uFF08\u5FC5\u586B\uFF09").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--plan <path>","\u5DF2\u5B8C\u6210\u7684\u6362\u58F3\u65B9\u6848 JSON\uFF08\u5FC5\u586B\uFF09").option("--episodes <list>","\u53EA\u5199\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u5267\u672A\u5B8C\u6210\u7684\u96C6\uFF09").option("--force","\u6240\u9009\u7684\u96C6\u5DF2\u5199\u8FC7\u4E5F\u91CD\u5199").option("--review-model <profile>","\u9010\u96C6\u5199\u5B8C\u5373\u7528\u6B64 profile \u5BA1\u6838\uFF0C\u8D26\u672C\u4F20\u7ED9\u4E0B\u4E00\u96C6").option("--concurrency <n>","\u540C\u65F6\u8FD0\u884C\u7684\u9636\u6BB5\u94FE\u6570\uFF08\u9ED8\u8BA4 6\uFF09",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u5199\u4F5C\u8BF7\u6C42\u8D85\u65F6\uFF08\u9ED8\u8BA4 8 \u5206\u949F\uFF09\uFF1B\u9010\u96C6\u5BA1\u6838\u6309\u5BA1\u6838\u7684\u5355\u96C6\u8D85\u65F6\uFF0815 \u5206\u949F\uFF09",Number)).action(j(Rh,t)),o(te(n.command("review"),"write").description("\u6362\u58F3\u5BA1\u6838\uFF1A\u6309\u96C6\u5E8F\u901A\u8BFB\uFF0C\u9010\u96C6\u5BA1\u6362\u5F97\u662F\u5426\u5408\u7406\u3001\u662F\u5426\u770B\u5F97\u61C2\u4E0E\u901A\u987A\u3001\u524D\u540E\u662F\u5426\u8FDE\u8D2F\u3001\u9020\u578B\u4E0E\u573A\u666F\u5F15\u7528\u662F\u5426\u51C6\u786E\uFF0C\u5904\u7406\u7A0B\u5E8F\u68C0\u67E5\u7ED3\u679C\uFF0C\u518D\u505A\u5168\u5267\u6536\u5C3E\u3002-p \u4E3A\u65B0\u5267\u5267\u672C\uFF1B\u4E8B\u4EF6\u683C\u5F0F\u4E0E review \u76F8\u540C").option("--source <path>","\u539F\u5267\u5267\u672C\uFF08\u5FC5\u586B\uFF09").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--plan <path>","\u6362\u58F3\u65B9\u6848 JSON\uFF08\u5FC5\u586B\uFF09").option("--episodes <list>","\u53EA\u5BA1\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u90E8\uFF09").option("--concurrency <n>","\u540C\u65F6\u8FDB\u884C\u7684\u9636\u6BB5\u94FE\u6570\uFF08\u9ED8\u8BA4 10\uFF09",Number).option("--max-steps <n>","\u6BCF\u96C6\u6700\u591A\u51E0\u6B65\u5DE5\u5177\u8C03\u7528",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u8D85\u65F6\uFF08\u9ED8\u8BA4 15 \u5206\u949F\uFF09",Number).option("--converge-only","\u53EA\u6267\u884C\u9636\u6BB5\u9996\u96C6\u63A5\u7F1D\u590D\u6838\u4E0E\u5168\u5267\u6536\u5C3E").option("--no-converge","\u8DF3\u8FC7\u5168\u5267\u6536\u5C3E")).action(j(Mh,t)),n.command("batch").argument("<manifest>","\u6279\u91CF\u6E05\u5355 JSON\uFF1A{ dramas: [{ id, source, market, language, rating, notes, custom, pick, avoid }], models, prices, pick }").description("\u65E0\u4EBA\u503C\u5B88\u6279\u91CF\u6362\u58F3\uFF1A\u6BCF\u90E8\u5267\u5728 -o \u4E0B\u6709\u81EA\u5DF1\u7684\u9879\u76EE\u76EE\u5F55\uFF0C\u4F9D\u6B21\u62C6\u89E3 \u2192 \u65B9\u5411 \u2192 \u65B9\u6848 \u2192 \u5199\u4F5C \u2192 \u5BA1\u6838\uFF0C\u6BCF\u6B65\u4ECE\u5DF2\u4FDD\u5B58\u7684\u8FDB\u5EA6\u7EE7\u7EED\u3002\u62C6\u89E3\u8BC4\u51FA\u7684\u9002\u5408\u5EA6\u4F4E\u4E8E 3 \u4E14\u6CA1\u5199 pick \u65F6\u505C\u5728\u62C6\u89E3\u540E\uFF0C\u6307\u5B9A\u65B9\u5411\u4E0D\u53EF\u884C\u6216\u9700\u8981\u4EBA\u5DE5\u9009\u65B9\u5411\u65F6\u505C\u5728\u65B9\u5411\u6B65\uFF1B\u8865\u4E0A pick \u540E\u518D\u8FD0\u884C\u5373\u4ECE\u65B9\u5411\u7EE7\u7EED\u3002\u8FDB\u5EA6\u4E0E\u62A5\u544A\u5199\u5728 -o \u4E0B\u7684 batch-report.json / batch-report.md").option("-o, --output <dir>","\u6279\u91CF\u8F93\u51FA\u76EE\u5F55\uFF08\u5FC5\u586B\uFF09").option("--concurrency <n>","\u540C\u65F6\u8FDB\u884C\u7684\u5267\u6570\uFF08\u9ED8\u8BA4 2\uFF09",Number).option("--attempts <n>","\u6BCF\u6B65\u6700\u591A\u8FD0\u884C\u51E0\u6B21\uFF0C\u6BCF\u6B21\u4ECE\u4E0A\u6B21\u8FDB\u5EA6\u7EE7\u7EED\uFF08\u9ED8\u8BA4 3\uFF09",Number).option("--pick <n|recommended>","\u6CA1\u5199 pick \u7684\u5267\u7528\u8FD9\u4E2A\u5019\u9009\uFF1B\u4E0D\u7ED9\u65F6\u505C\u4E0B\u7B49\u4EBA\u5DE5\u9009\u62E9").option("--until <step>","\u505A\u5230\u8FD9\u4E00\u6B65\u540E\u505C\u4E0B\uFF1Aanalyze | direction | plan | write | review").option("--no-fallback","\u53EA\u7528\u6240\u9009\u6A21\u578B\uFF0C\u5931\u8D25\u65F6\u4E0D\u6362\u7528\u5176\u4ED6\u6A21\u578B\uFF08\u9ED8\u8BA4\u6309\u914D\u7F6E\u7684\u964D\u7EA7\u987A\u5E8F\u6362\u7528\uFF09").option("--llm-config <path>","LLM configuration file").action(j(Nh,t))}import*as Uh from"node:fs";var Jo="\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 He(e){let t=he(e);if(!Uh.existsSync(t))throw new S("Local script file not found.",{exitCode:k,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[t]}});return Gp(t)}function we(e,t){let n=e[t];return typeof n=="string"?n:void 0}function bi(e,t){let n=e[t];if(n==null||n==="")return;let o=Number(n);if(!Number.isFinite(o))throw new S(`--${t} must be a number.`,{exitCode:k,errorCode:"OPTION_NOT_NUMBER",data:{actual:[String(n)]}});return o}function xe(e,t=0){return(e._args??[])[t]??""}function Il(e){return Array.isArray(e)?e.map(String):typeof e=="string"?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function lt(e,t,n=()=>({})){try{let o=e();return[{text:o,data:{op:t,changed:!1,text:o,...n()}},V]}catch(o){throw o instanceof S?o:new S(o instanceof Error?o.message:String(o),{exitCode:k,errorCode:o?.code??"SCRIPT_TOOL_FAILED"})}}function Ph(e,t){let n=te(e.command("read [addr]"),"read").description(`\u8BFB\u4EFB\u610F\u8282\u70B9\uFF1B\u4E0D\u7ED9\u5730\u5740\u8FD4\u56DE\u5267\u672C\u5361\u3002${Jo}`).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(j(y=>{let E=He(y);return lt(()=>Da(E,xe(y),{...y.outline?{depth:"outline"}:{},...y.plain?{plain:!0}:{},...bi(y,"context")!==void 0?{context:bi(y,"context")}:{}}),"read",()=>xe(y)?{}:{document:E.raw})},t));Le(n,[Jo]);let o=te(e.command("scan <episode>"),"read").description("\u4E00\u6B21\u8FD4\u56DE\u67D0\u96C6\u7684\u5B8C\u6574\u4E0A\u4E0B\u6587\uFF1A\u573A\u7ED3\u6784 + \u5168\u90E8\u6B63\u6587 + \u5F53\u524D\u6821\u9A8C\u95EE\u9898").action(j(y=>lt(()=>{let E=He(y),_=xe(y);return[`## \u573A\u7ED3\u6784
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
`)},"scan"),t));Le(o,["\u96C6\u53F7\uFF0C\u4ECE 1 \u5F00\u59CB"]);let i=te(e.command("find [query]"),"read").description("\u6309\u6B63\u6587\u6B63\u5219 / \u8BF4\u8BDD\u4EBA / \u7C7B\u578B\u5B9A\u4F4D action\uFF0C\u8FD4\u56DE\u951A\u70B9 + \u547D\u4E2D\u7A97\u53E3").option("-i, --in <addr>",`\u9650\u5236\u8303\u56F4\uFF0C${Jo}`).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(j(y=>lt(()=>Ag(He(y),xe(y),{...we(y,"in")?{in:we(y,"in")}:{},...we(y,"speaker")?{speaker:we(y,"speaker")}:{},...we(y,"type")?{type:we(y,"type")}:{},...bi(y,"limit")!==void 0?{limit:bi(y,"limit")}:{},...y.full?{full:!0}:{}}),"find"),t));Le(i,["\u6B63\u5219\uFF1B\u53EA\u6309 speaker/type \u8FC7\u6EE4\u65F6\u53EF\u7701\u7565"]);let r=te(e.command("refs <addr>"),"read").description("\u53EA\u8BFB\u5B9A\u4F4D\u8D44\u4EA7/\u9020\u578B\u7684\u573A\u666F\u7ED1\u5B9A\u3001\u8BF4\u8BDD\u5F15\u7528\u548C\u6B63\u6587\u63D0\u53CA\uFF0C\u8FD4\u56DE\u53EF read \u7684\u5730\u5740\u53CA\u4E0A\u4E0B\u6587").option("--offset <n>","\u4ECE\u7B2C\u51E0\u6761\u5F15\u7528\u7EE7\u7EED\uFF08\u4ECE 0 \u5F00\u59CB\uFF09").option("--limit <n>","\u672C\u6279\u5F15\u7528\u6570\uFF08\u9ED8\u8BA4 20\uFF09").option("--context <n>","\u6B63\u6587\u547D\u4E2D\u524D\u540E\u5404\u51E0\u6761 action\uFF08\u9ED8\u8BA4 3\uFF09").action(j(y=>{let E=Yp(He(y),xe(y),{offset:bi(y,"offset"),limit:bi(y,"limit"),context:bi(y,"context")});return[{text:qp(E),data:{op:"refs",changed:!1,...E}},V]},t));Le(r,["\u4EBA\u7269/\u573A\u666F/\u9053\u5177 ID \u6216\u540D\u79F0\uFF0C\u6216 <\u8D44\u4EA7>/<\u9020\u578B>\uFF1B\u6B63\u6587\u63D0\u53CA\u4E0D\u7B49\u4E8E\u5B9E\u9645\u51FA\u573A"]);let s=te(e.command("span <range>"),"read").description("\u628A\u4E00\u6BB5 action \u6362\u7B97\u6210\u96C6\u5185\u89C6\u9891\u65F6\u95F4\u7A97\u53E3\uFF08\u534A\u5F00\u533A\u95F4\uFF09").action(j(y=>{let E=He(y);return lt(()=>kg(E,xe(y)),"span",()=>({rows:[Xp(E,xe(y))]}))},t));Le(s,[`${Jo}\uFF0C\u6216 \`\u8D77ID..\u6B62ID\``]),te(e.command("validate"),"read").description("\u8DD1\u6574\u672C\u6821\u9A8C").action(j(y=>{let E=He(y),_=mr(E);return[{text:Vg(E),data:{op:"script.validate",changed:!1,passed:_.ok,script_path:E.path,stats:{actors:E.assets.filter(x=>x.kind==="actor").length,locations:E.assets.filter(x=>x.kind==="location").length,props:E.assets.filter(x=>x.kind==="prop").length,episodes:E.episodes.length,scenes:E.episodes.reduce((x,A)=>x+A.scenes.length,0),actions:Un(E).length},issues:[..._.errors.map(x=>({...x,severity:"error"})),..._.warnings.map(x=>({...x,severity:"warning"}))]}},_.ok?V:Eo]},t)),te(e.command("issues"),"read").description("\u5217\u5F53\u524D\u6821\u9A8C\u95EE\u9898").option("--severity <severity>","error | warning").option("--code <code>","\u6309 issue code \u8FC7\u6EE4").action(j(y=>lt(()=>nl(He(y),{...we(y,"severity")?{severity:we(y,"severity")}:{},...we(y,"code")?{code:we(y,"code")}:{}}),"issues"),t));let a=te(e.command("edit <addr>"),"write").description(`\u6539\u4E00\u4E2A\u8282\u70B9\u7684\u5B57\u6BB5\uFF1B\u5730\u5740\u51B3\u5B9A\u54EA\u4E9B\u5B57\u6BB5\u5408\u6CD5\u3002${Jo}`).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(j(y=>{let E={};for(let _ of["content","speaker","type","name","desc","importance","role","space","time","title","synopsis","logline","theme","worldview","style","main"]){let x=we(y,_);x!==void 0&&(E[_]=x)}for(let _ of["paren","ts","transition"])if(y[_]===!1)E[_]=null;else{let x=we(y,_);x!==void 0&&(E[_]=x)}return y.alias!==void 0&&(E.aliases=Il(y.alias)),lt(()=>bg(He(y),xe(y),E),"edit")},t));Le(a,[Jo]);let c=te(e.command("insert <addr> <content>"),"write").description("\u5728\u67D0\u6761 action \u524D/\u540E\u63D2\u5165\u4E00\u6761\u65B0 action").requiredOption("-t, --type <type>","action | dialogue | inner_thought | transition").option("--before","\u63D2\u5230\u76EE\u6807\u4E4B\u524D\uFF08\u9ED8\u8BA4\u4E4B\u540E\uFF09").option("-a, --speaker <name>","dialogue / inner_thought \u5FC5\u586B").option("--paren <text>","\u8868\u6F14\u63D0\u793A").action(j(y=>lt(()=>vg(He(y),xe(y),y.before?"before":"after",we(y,"type"),xe(y,1),we(y,"speaker"),we(y,"paren")),"insert"),t));Le(c,["\u76F8\u90BB action \u7684\u5730\u5740","\u65B0 action \u7684\u6B63\u6587"]);let d=te(e.command("move <addr> <to>"),"write").description("\u628A\u4E00\u6761 action \u632A\u5230\u53E6\u4E00\u6761\u65C1\u8FB9\uFF1B\u8DE8\u573A\u4E5F\u4FDD\u6301 action_id").option("--before","\u632A\u5230\u76EE\u6807\u4E4B\u524D\uFF08\u9ED8\u8BA4\u4E4B\u540E\uFF09").action(j(y=>lt(()=>Og(He(y),xe(y),xe(y,1),y.before?"before":"after"),"move"),t));Le(d,["\u8981\u632A\u7684 action","\u76EE\u6807\u90BB\u5C45 action"]);let p=te(e.command("write <addr>"),"write").description("\u7528 read \u8F93\u51FA\u7684\u540C\u4E00\u4EFD\u6B63\u6587\u683C\u5F0F\u56DE\u5199\u6574\u573A / \u6574\u96C6 / \u65B0\u96C6\uFF08`+`\uFF09").option("-f, --file <path>","\u6B63\u6587\u6587\u4EF6\uFF1B\u7701\u7565\u5219\u8BFB stdin").option("--allow-delete","\u5141\u8BB8\u5220\u9664\u6587\u672C\u91CC\u6D88\u5931\u7684\u573A / action").action(j(async y=>{let E=await import("node:fs"),_=we(y,"file"),x=_?E.readFileSync(_,"utf8"):E.readFileSync(0,"utf8");return lt(()=>Ng(He(y),xe(y),x,{allowDelete:!!y.allow_delete}),"write")},t));Le(p,["\u573A / \u96C6\u5730\u5740\uFF0C\u6216 `+` \u8FFD\u52A0\u65B0\u96C6"]);let l=te(e.command("replace <pattern> <to>"),"write").description("\u6279\u91CF\u66FF\u6362\u6B63\u6587\uFF1B\u9ED8\u8BA4\u53EA\u9884\u89C8\uFF0C--apply \u624D\u843D\u76D8\u3002\u8FC7\u6EE4\u53C2\u6570\u4E0E find \u76F8\u540C").option("-i, --in <addr>","\u9650\u5236\u8303\u56F4").option("-a, --speaker <name>","\u9650\u5B9A\u8BF4\u8BDD\u4EBA").option("-t, --type <type>","\u9650\u5B9A action \u7C7B\u578B").option("--apply","\u771F\u7684\u5199\u5165").action(j(y=>lt(()=>Cg(He(y),xe(y),xe(y,1),{...we(y,"in")?{in:we(y,"in")}:{},...we(y,"speaker")?{speaker:we(y,"speaker")}:{},...we(y,"type")?{type:we(y,"type")}:{},...y.apply?{apply:!0}:{}}),"replace"),t));Le(l,["\u6B63\u5219","\u66FF\u6362\u6210\u4EC0\u4E48"]);let f=te(e.command("ref <scene> <asset>"),"write").description("\u6539\u4E00\u4E2A\u573A\u5BF9\u67D0\u8D44\u4EA7\u7684\u5F15\u7528\uFF1B--state \u662F\u5B8C\u6574\u72B6\u6001\u96C6\u5408\u800C\u975E\u8FFD\u52A0").option("--state <list>","\u5B8C\u6574\u72B6\u6001\u96C6\u5408\uFF08\u540D\u5B57\u6216 ID\uFF09\uFF0C\u9017\u53F7\u5206\u9694\u6216\u91CD\u590D\u7ED9\u51FA",bA,[]).option("--remove","\u5220\u9664\u6574\u6761\u5F15\u7528").action(j(y=>lt(()=>Pg(He(y),xe(y),xe(y,1),Il(y.state).flatMap(E=>E.split(",")).map(E=>E.trim()).filter(Boolean),!!y.remove),"ref"),t));Le(f,["\u573A\u5730\u5740","\u4EBA\u7269 / \u5730\u70B9 / \u9053\u5177\u7684\u540D\u5B57\u6216 ID"]);let u=te(e.command("asset <kind> <name>"),"write").description("\u767B\u8BB0\u4E00\u4E2A\u65B0\u7684 actor / location / prop").requiredOption("--desc <text>","\u63CF\u8FF0").option("--importance <tier>","featured | background","featured").option("--alias <list>","\u522B\u540D\uFF0C\u9017\u53F7\u5206\u9694").action(j(y=>lt(()=>$g(He(y),xe(y),xe(y,1),we(y,"desc")??"",we(y,"importance")??"featured",Il(y.alias)),"asset"),t));Le(u,["actor | location | prop","\u540D\u5B57"]);let h=te(e.command("state <asset> <name>"),"write").description("\u7ED9\u5DF2\u6709\u8D44\u4EA7\u52A0\u4E00\u4E2A\u72B6\u6001\uFF08\u9020\u578B\u6863\u4F4D\uFF09").requiredOption("--desc <text>","\u63CF\u8FF0").action(j(y=>lt(()=>Dg(He(y),xe(y),xe(y,1),we(y,"desc")??""),"state"),t));Le(h,["\u8D44\u4EA7\u540D\u6216 ID","\u72B6\u6001\u540D"]);let m=te(e.command("del <addr>"),"write").description("\u5220\u9664 action / \u573A / \u96C6 / \u8D44\u4EA7 / \u72B6\u6001").option("--replacement <state>","\u5220\u72B6\u6001\u65F6\u628A\u5F15\u7528\u6539\u5199\u5230\u8FD9\u4E2A\u72B6\u6001").option("--force","\u5BB9\u5668\u975E\u7A7A\u65F6\u4ECD\u7136\u5220\u9664").action(j(y=>lt(()=>Bg(He(y),xe(y),{...we(y,"replacement")?{replacement:we(y,"replacement")}:{},...y.force?{force:!0}:{}}),"del"),t));Le(m,[Jo]);let g=te(e.command("merge <src> <dst>"),"write").description("\u628A\u4E00\u4E2A\u8D44\u4EA7\u5E76\u5165\u53E6\u4E00\u4E2A\uFF1A\u5168\u90E8\u573A\u666F\u5F15\u7528\u4E0E speaker \u6539\u5199\u8FC7\u53BB").action(j(y=>lt(()=>rl(He(y),xe(y),xe(y,1)),"merge"),t));Le(g,["\u88AB\u5E76\u5165\u7684\u8D44\u4EA7","\u4FDD\u7559\u7684\u8D44\u4EA7"]);let w=te(e.command("ext <addr> [key] [value]"),"write").description("\u8BFB\u6216\u5199\u4EFB\u610F\u8282\u70B9\u7684 extend \u6570\u636E").option("--remove","\u5220\u9664\u8BE5 key").action(j(y=>lt(()=>Gg(He(y),xe(y),xe(y,1)||void 0,xe(y,2)||void 0,!!y.remove),"ext"),t));Le(w,[Jo,"extend key","\u503C"])}function bA(e,t){return[...t,e]}import*as jw from"node:path";var pn={createExecutor:sg};import*as Zl from"node:fs";import*as br from"node:path";var Tn=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();var bs=e=>String(e).padStart(3,"0"),Al=e=>e.normalize("NFC").replace(/\s+/g," ").trim();function Ch(e,t={}){let n=[],o=[],i=null,r=null,s=0,a=0,c=new Map,d=(l,f)=>{let u=`text:${l}:${f.chunk}:${f.line_start}:${f.line_end}`,h=(c.get(u)??0)+1;return c.set(u,h),`${u}:${h}`},p=(l,f)=>{let u=l.actors.find(h=>Al(h.name)===Al(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_${bs(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_${bs(s)}`,scenes:[]},n.push(i)),a++,r={identity_key:d("scene",l.source),scene_id:`scn_${bs(a)}`,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 vs=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=Al(t),i=this.byNorm.get(o);return i||(i={provisional_id:`${this.prefix}_${bs(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=Tn(n),i=t.states.find(s=>Tn(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 vA(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 nc(e){let t=0,n=()=>`st_${bs(++t)}`,o=new vs("act","actor",n),i=new vs("loc","location",n),r=new vs("prp","prop",n),s={episode:{},scene:{},action:{}},a={episode:new Set,scene:new Set,action:new Set},c=(u,h,m)=>{if(!m||a[u].has(m))throw new Error(`Duplicate or missing ${u} source identity: ${m}`);a[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)=>(c("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}`;c("scene",w,m.identity_key);let y={episode:h,scene:g},E=m.location?d(i,m.location,y,"location_id"):null,_=m.actors.map(b=>d(o,b,y,"actor_id")),x=m.props.map(b=>d(r,b,y,"prop_id")),A=m.actions.map((b,U)=>{c("action",`${w}#${U}`,b.identity_key);let v={type:b.type,content:b.content};if(b.speaker)if("name"in b.speaker){let I=o.ensure(b.speaker.name,y),R={actor_id:I.provisional_id};b.speaker.state!==void 0&&(R.state_id=o.stateId(I,b.speaker.state)),v.speaker=R}else v.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?v.emotion=b.parenthetical:b.emotion!==void 0&&(v.emotion=b.emotion)),b.extend!==void 0&&(v.extend=b.extend),v});return{scene_id:m.scene_id,...m.environment?{environment:m.environment}:{},location:E,actors:_,props:x,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:vA(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 Th(e,t={}){let n=t.maxChars??500,o=e.split(`
|
|
234
|
+
`}function kh(e){let t=JSON.parse(ye.readFileSync(e,"utf8")),n=Array.isArray(t)?{dramas:t}:t;if(!Array.isArray(n.dramas)||!n.dramas.length)throw new Error("\u6E05\u5355\u91CC\u6CA1\u6709 dramas\u3002");let o=Se.dirname(Se.resolve(e)),i=new Set;return{dramas:n.dramas.map((s,a)=>{if(!s.source?.trim())throw new Error(`\u7B2C ${a+1} \u90E8\u5267\u6CA1\u6709 source\u3002`);let c=Se.resolve(o,s.source.trim()),d=(s.id?.trim()||Se.basename(Se.dirname(c))).replace(/[\\/]/g,"-");if(i.has(d))throw new Error(`\u5267\u7684 id \u91CD\u590D\uFF1A${d}\uFF1B\u7ED9\u6BCF\u90E8\u5267\u5199\u4E0D\u540C\u7684 id\u3002`);if(i.add(d),s.pick!==void 0&&s.pick!=="recommended"&&!(Number.isInteger(s.pick)&&Number(s.pick)>=1))throw new Error(`${d} \u7684 pick \u5199\u5019\u9009\u5E8F\u53F7\uFF08\u4ECE 1 \u5F00\u59CB\uFF09\u6216 recommended\u3002`);return{...s,id:d,source:c}}),models:{..._A,...n.models??{}},prices:{...SA,...n.prices??{}},...n.pick!==void 0?{pick:n.pick}:{},...n.search?{search:n.search}:{},...n.ideas?.length?{ideas:n.ideas}:{}}}async function MA(e,t,n){let o=[...e];await Promise.all(Array.from({length:Math.max(1,Math.min(t,o.length))},async()=>{for(let i=o.shift();i!==void 0;i=o.shift())await n(i)}))}var co=class extends Error{constructor(n,o){super(o);this.state=n}state};async function bh(e,t,n){let o=n.now??Date.now,i=new Map,r=()=>LA(n.outputDir,e,[...i.values()]);async function s(a){let c=Il(n.outputDir,a.id),d={...Al(c.status)??{id:a.id,steps:{}},state:"running",reason:"",step:null,updated_at:""};i.set(a.id,d);let p=()=>{d.updated_at=new Date(o()).toISOString(),ic(c.status,d),r()},l=v=>n.onEvent?.({drama:a.id,...v});if(!ye.existsSync(c.source)){if(!ye.existsSync(a.source))throw new co("failed",`\u539F\u5267\u5267\u672C\u4E0D\u5B58\u5728\uFF1A${a.source}`);ye.mkdirSync(Se.dirname(c.source),{recursive:!0}),ye.copyFileSync(a.source,c.source)}async function f(v,I){let R=d.steps[v]??{state:"running",runs:0,wall_ms:0,usage:{}};R.state="running",d.steps[v]=R,d.step=v,p(),l({type:"step-started",step:v}),ye.mkdirSync(Se.dirname(c.log(v)),{recursive:!0});let C=M=>{ye.appendFileSync(c.log(v),JSON.stringify(M)+`
|
|
235
|
+
`),kA.has(String(M.type))&&Array.isArray(M.usage)&&AA(R.usage,M.usage)},N=null;for(let M=1;M<=n.attempts;M+=1){let K=o();R.runs+=1;try{N=await I(C)}catch(X){N=X instanceof Error?X.message:String(X)}if(R.wall_ms+=o()-K,p(),!N)break}if(R.state=N?"failed":"completed",N?R.error=N:delete R.error,p(),l({type:"step-done",step:v,state:R.state,error:N}),N)throw new co("failed",`${v}\uFF1A${N}`)}let u=v=>d.steps[v]?.state==="completed",h=v=>n.until===v;if((!u("analyze")||!ye.existsSync(c.analysis))&&await f("analyze",async v=>{let I=await t.analyzeReskinSource({...n.config(e.models.analyze),sourcePath:c.source,outputPath:c.analysis,onEvent:v});return I.state==="completed"?null:I.error||"\u62C6\u89E3\u672A\u5B8C\u6210"}),h("analyze"))return;let m=OA(c.analysis,a),g=Al(c.direction);(g?.key!==m||g.result.state!=="completed")&&(g=null,await f("direction",async v=>{let I=await t.proposeReskinDirections({...n.config(e.models.direction),sourcePath:c.source,analysisPath:c.analysis,...e.search?{search:n.config(e.search)}:{},...e.ideas?.length?{ideaModels:e.ideas.map(R=>n.config(R))}:{},notes:a.notes??"",custom:a.custom??"",market:a.market??"",rating:a.rating??"",avoid:a.avoid??[],onEvent:v});return I.type!=="direction-done"||I.state!=="completed"?I.type==="direction-done"&&I.error||"\u65B9\u5411\u672A\u5B8C\u6210":(g={key:m,result:I},ic(c.direction,g),null)}));let w=g.result,y=!!a.custom?.trim(),E=y?1:a.pick??e.pick,_=E==="recommended"?w.recommended:E??null;if(d.direction={mode:y?"custom":"candidates",verdict:w.verdict,verdict_reason:w.reason,candidates:w.candidates.map(({title:v,shell:I,review:R})=>({title:v,shell:I,carry:vA(R)})),recommended:w.recommended,recommendation:w.recommendation,picked:_},d.step="direction",w.verdict==="\u4E0D\u53EF\u884C")throw new co("stopped",`\u6307\u5B9A\u7684\u65B9\u5411\u4E0D\u53EF\u884C\uFF1A${w.reason}`);if(!w.candidates.length)throw new co("stopped",`\u8FD9\u4E00\u8F6E\u7684\u65B9\u5411\u90FD\u6709\u6491\u4E0D\u4F4F\u7684\u5730\u65B9\uFF1A${(w.dropped??[]).map(v=>`${v.title}\uFF08${v.breaks.join("\uFF1B")}\uFF09`).join("\uFF1B")}\u3002\u6362\u4E2A\u8981\u6C42\u6216\u5199 custom \u518D\u8FD0\u884C`);if(_===null)throw new co("stopped",`\u5F85\u4EBA\u5DE5\u9009\u62E9\u65B9\u5411\uFF1A\u5728\u6E05\u5355\u91CC\u7ED9\u8FD9\u90E8\u5267\u5199 pick\uFF081\u2013${w.candidates.length}\uFF0C\u63A8\u8350 ${w.recommended}\uFF09\u540E\u518D\u8FD0\u884C`);let x=w.candidates[_-1];if(!x)throw new co("stopped",`pick ${_} \u8D85\u51FA\u5019\u9009\u8303\u56F4\uFF08\u5171 ${w.candidates.length} \u4E2A\uFF09`);let A=RA(x,w,a),b=ye.existsSync(c.brief)?ye.readFileSync(c.brief,"utf8"):null;if(b!==A){let v=Se.dirname(c.script);b!==null&&ye.existsSync(v)&&ye.renameSync(v,`${v}.${new Date(o()).toISOString().replace(/[:.]/g,"-")}`);for(let I of["plan","write","review"])delete d.steps[I];delete d.review,ye.mkdirSync(Se.dirname(c.brief),{recursive:!0}),ye.writeFileSync(c.brief,A)}if(p(),h("direction")||(u("plan")||await f("plan",async v=>{let I=await t.buildReskinPlan({...n.config(e.models.plan),sourcePath:c.source,analysisPath:c.analysis,directionPath:c.brief,planPath:c.plan,onEvent:v});return I.state==="completed"?null:I.error||"\u65B9\u6848\u672A\u5B8C\u6210"}),h("plan"))||(u("write")||await f("write",async v=>{let I=await t.writeReskinScript({...n.config(e.models.write),reviewModel:n.config(e.models.review),sourcePath:c.source,analysisPath:c.analysis,planPath:c.plan,scriptPath:c.script,concurrency:Math.max(1,Math.floor(6/n.concurrency)),episodeTimeoutMs:48e4,onEvent:v});return I.type==="done"&&!I.failed?.length?null:`\u8FD9\u4E9B\u96C6\u6CA1\u6709\u5199\u6210\uFF1A${(I.failed??[]).join("\u3001")}`}),h("write")))return;let U=d.review??={converged:!1};u("review")||await f("review",async v=>{U.converged=!1;let I=!1,R=0,C=N=>{v(N),N.type==="global"&&R++,(N.type==="global"||N.type==="episode")&&N.state==="failed"&&(I=!0),N.type==="done"&&(U.converged=R>0&&!I)};return await t.reviewReskinScript({...n.config(e.models.review),scriptPath:c.script,sourcePath:c.source,analysisPath:c.analysis,planPath:c.plan,convergeOnly:!0,concurrency:5,maxSteps:300,episodeTimeoutMs:8*6e4,onEvent:C}),U.converged?null:"\u5168\u5267\u6536\u5C3E\u6CA1\u6709\u5B8C\u6210"})}for(let a of e.dramas){let c=Al(Il(n.outputDir,a.id).status);i.set(a.id,{...c??{id:a.id,steps:{},step:null,reason:"",updated_at:""},state:"pending"})}return r(),await MA(e.dramas,n.concurrency,async a=>{try{await s(a);let d=i.get(a.id);d.state=n.until&&n.until!=="review"?"stopped":"completed",d.reason=d.state==="stopped"?`\u6309 --until \u505C\u5728 ${n.until}`:""}catch(d){let p=i.get(a.id)??{id:a.id,steps:{},step:null,reason:"",state:"failed",updated_at:""};i.set(a.id,p),p.state=d instanceof co?d.state:"failed",p.reason=d instanceof Error?d.message:String(d)}let c=i.get(a.id);c.updated_at=new Date(o()).toISOString(),ic(Il(n.outputDir,a.id).status,c),r(),n.onEvent?.({type:"drama-done",drama:a.id,state:c.state,step:c.step,reason:c.reason})}),e.dramas.map(a=>i.get(a.id))}function NA(e){let t=e.split(`
|
|
236
|
+
`)[0].replace(/\|/g,"\uFF0F");return t.length>160?`${t.slice(0,160)}\u2026`:t}function Ah(e){return`${Math.round(e/6e4)} \u5206\u949F`}function LA(e,t,n){let o=n.map(s=>{let a=Object.fromEntries(vs.filter(p=>s.steps[p]).map(p=>{let l=s.steps[p];return[p,{state:l.state,runs:l.runs,wall_ms:l.wall_ms,...Sh(l.usage,t.prices),usage:l.usage}]})),c={};for(let p of Object.values(s.steps))for(let[l,f]of Object.entries(p.usage)){let u=c[l]??={calls:0,input:0,cached_input:0,output:0};u.calls+=f.calls,u.input+=f.input,u.cached_input+=f.cached_input,u.output+=f.output}let d=Object.values(s.steps).reduce((p,l)=>p+l.wall_ms,0);return{id:s.id,state:s.state,step:s.step,reason:s.reason,wall_ms:d,...Sh(c,t.prices),usage:c,steps:a,direction:s.direction??null}});ic(Se.join(e,"batch-report.json"),{updated_at:new Date().toISOString(),dramas:o});let i={pending:"\u7B49\u5F85",running:"\u8FDB\u884C\u4E2D",completed:"\u5B8C\u6210",stopped:"\u505C\u4E0B",failed:"\u5931\u8D25"},r=["# \u6362\u58F3\u6279\u91CF\u8FD0\u884C","","| \u5267 | \u72B6\u6001 | \u6B65\u9AA4 | \u7528\u65F6 | \u8D39\u7528\uFF08\u7F8E\u5143\uFF09 | \u8BF4\u660E |","| --- | --- | --- | --- | --- | --- |",...o.map(s=>`| ${s.id} | ${i[s.state]} | ${s.step??""} | ${Ah(s.wall_ms)} | ${s.usd.toFixed(2)}${s.unpriced.length?`\uFF08\u672A\u8BA1\u4EF7\uFF1A${s.unpriced.join("\u3001")}\uFF09`:""} | ${NA(s.reason)} |`),"",...o.flatMap(s=>[`## ${s.id}`,"","| \u6B65\u9AA4 | \u72B6\u6001 | \u8FD0\u884C\u6B21\u6570 | \u7528\u65F6 | \u8F93\u5165 tok | \u7F13\u5B58\u547D\u4E2D | \u8F93\u51FA tok | \u8D39\u7528 |","| --- | --- | --- | --- | --- | --- | --- | --- |",...Object.entries(s.steps).map(([a,c])=>{let d=Object.values(c.usage).reduce((p,l)=>({input:p.input+l.input,cached:p.cached+l.cached_input,output:p.output+l.output}),{input:0,cached:0,output:0});return`| ${a} | ${c.state} | ${c.runs} | ${Ah(c.wall_ms)} | ${(d.input/1e6).toFixed(2)}M | ${d.input?Math.round(d.cached/d.input*100):0}% | ${(d.output/1e6).toFixed(2)}M | ${c.usd.toFixed(2)} |`}),...s.direction?["",s.direction.verdict?`\u6307\u5B9A\u65B9\u5411\u5224\u65AD\uFF1A${s.direction.verdict}\uFF1B${s.direction.verdict_reason}`:"",...s.direction.candidates.map((a,c)=>`${c+1}. ${a.title}\uFF1A${a.shell}\uFF08\u627F\u63A5 ${a.carry}\uFF09${c+1===s.direction.recommended&&s.direction.mode==="candidates"?" \u2190 \u63A8\u8350":""}${c+1===s.direction.picked?" \u2190 \u9009\u5B9A":""}`)].filter(Boolean):[],""])];ye.writeFileSync(Se.join(e,"batch-report.md"),r.join(`
|
|
237
|
+
`))}var vh="reskin",UA=["minimal","low","medium","high"],kl=["overall","events","beats"];function et(e,t){if(!e||!Cn.existsSync(e))throw new S(`${t} not found.`,{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:`Pass an existing ${t}.`,data:{expected:[`existing ${t}`],actual:[e||"<empty>"]}});return e}function Oh(e,t){let n=tc(e,t),o=e.providers[e.models[t].provider]?.protocol,i=e.models[t].reasoning,r=o?.startsWith("google")&&UA.includes(i??"")?i:void 0;return{profile:n,config:{provider:e.models[t].provider,apiKey:n.apiKey,model:n.model,maxAttempts:n.maxAttempts,...n.baseUrl?{baseUrl:n.baseUrl}:{},...o?{protocol:o}:{},...r?{thinking:r}:{}}}}function dn(e){let t=Co(O(e.llm_config).trim()||void 0),n=O(e.model).trim()||(t.models[vh]?vh:"review-agent"),{profile:o,config:i}=Oh(t,n),r=(t.models[n].fallbacks??[]).flatMap(s=>{try{return[Oh(t,s).config]}catch{return[]}});return{llm:t,name:n,profile:o,config:{...i,singleModel:e.fallback===!1,...r.length?{fallbacks:r}:{}}}}function xr(e,t){return e instanceof S?e:new S("Reskin failed.",{exitCode:q,errorCode:t,hint:"Read the NDJSON events and the saved plan or script before retrying; completed work is kept.",data:{expected:["a completed reskin run"],actual:[e instanceof Error?e.message:String(e)]}})}var bi=e=>process.stdout.write(JSON.stringify(e)+`
|
|
238
|
+
`);async function Er(e,t){let{llm:n,name:o,profile:i}=dn(e),s=typeof(await cn())[t]=="function";return[{text:s?`ready: ${o} ${i.provider}/${i.model}`:"the agent bundle exports no reskin commands",data:{ready:s,profile:o,provider:i.provider,model:i.model,llm_config:n.sourcePath??"builtin"}},s?V:q]}async function Rh(e){if(e.check)return Er(e,"analyzeReskinSource");let{config:t}=dn(e),n=et(he(e),"source script"),o=O(e.output).trim();if(!o)throw new S("Analysis output path missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass -o <\u62C6\u89E3.json>.",data:{expected:["analysis output path"],actual:["<empty>"]}});let i=await cn();try{let r=await i.analyzeReskinSource({...t,sourcePath:n,outputPath:o,force:e.force===!0,...e.concurrency!==void 0?{concurrency:pt(e,"concurrency",5)}:{},...e.unit_timeout_ms!==void 0?{unitTimeoutMs:pt(e,"unit_timeout_ms",6e5)}:{},onEvent:bi});return[{text:"",data:{}},r.type==="analyze-done"&&r.state==="completed"?V:q]}catch(r){throw xr(r,"RESKIN_ANALYZE_FAILED")}}async function Mh(e){if(e.check)return Er(e,"assessReskinPaths");let{config:t}=dn(e),n=et(O(e.analysis).trim(),"analysis"),o=O(e.markets).split(/[,,]/).map(s=>s.trim()).filter(Boolean);if(!o.length)throw new S("Candidate markets missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass --markets, e.g. --markets \u4E2D\u56FD,\u5370\u5C3C,\u7F8E\u56FD.",data:{expected:["comma-separated markets"],actual:["<empty>"]}});let i=O(e.output).trim(),r=await cn();try{let s=await r.assessReskinPaths({...t,analysisPath:n,markets:o,notes:O(e.notes),onEvent:bi});return i&&s.type==="paths-done"&&s.state==="completed"&&Cn.writeFileSync(i,JSON.stringify(s,null,2)+`
|
|
239
|
+
`),[{text:"",data:{}},s.type==="paths-done"&&s.state==="completed"?V:q]}catch(s){throw xr(s,"RESKIN_PATHS_FAILED")}}async function Nh(e){if(e.check)return Er(e,"proposeReskinDirections");let{config:t}=dn(e),n=et(he(e),"source script"),o=et(O(e.analysis).trim(),"analysis"),i=O(e.output).trim(),r=O(e.evidence).trim(),s=r?Cn.readFileSync(et(r,"evidence"),"utf8"):void 0,a=O(e.used).trim(),c=a?JSON.parse(Cn.readFileSync(et(a,"used"),"utf8")):void 0,d=O(e.search_model).trim()?dn({...e,model:e.search_model}).config:void 0,p=(Array.isArray(e.idea_model)?e.idea_model:[]).map(f=>String(f).trim()).filter(Boolean).map(f=>dn({...e,model:f}).config),l=await cn();try{let f=await l.proposeReskinDirections({...t,sourcePath:n,analysisPath:o,notes:O(e.notes),custom:O(e.custom),market:O(e.market).trim(),rating:O(e.rating).trim(),avoid:(Array.isArray(e.avoid)?e.avoid:[]).map(u=>String(u).trim()).filter(Boolean),...c?{used:c}:{},...d?{search:d}:{},...p.length?{ideaModels:p}:{},evidence:s,onEvent:bi});return i&&f.type==="direction-done"&&f.state==="completed"&&Cn.writeFileSync(i,JSON.stringify(f,null,2)+`
|
|
240
|
+
`),[{text:"",data:{}},f.type==="direction-done"&&f.state==="completed"?V:q]}catch(f){throw xr(f,"RESKIN_DIRECTION_FAILED")}}async function Lh(e){if(e.check)return Er(e,"buildReskinPlan");let{config:t}=dn(e),n=et(he(e),"source script"),o=et(O(e.analysis).trim(),"analysis"),i=et(O(e.direction).trim(),"direction"),r=O(e.output).trim(),s=O(e.until).trim();if(!r)throw new S("Plan output path missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass -o <\u6362\u58F3\u65B9\u6848.json>.",data:{expected:["plan output path"],actual:["<empty>"]}});if(s&&!kl.includes(s))throw new S("Unknown plan layer.",{exitCode:k,errorCode:"RESKIN_LAYER_UNKNOWN",hint:`Pass --until ${kl.join("|")}.`,data:{expected:[...kl],actual:[s]}});let a=await cn();try{let c=await a.buildReskinPlan({...t,sourcePath:n,analysisPath:o,directionPath:i,planPath:r,...s?{until:s}:{},force:e.force===!0,...e.unit_timeout_ms!==void 0?{unitTimeoutMs:pt(e,"unit_timeout_ms",18e5)}:{},onEvent:bi}),d=c.type==="plan-done"&&c.state!=="failed";return[{text:"",data:{}},d?V:q]}catch(c){throw xr(c,"RESKIN_PLAN_FAILED")}}async function Uh(e){let t=O(e.review_model).trim()?dn({...e,model:e.review_model}).config:void 0;if(e.check)return Er(e,"writeReskinScript");let{config:n}=dn(e),o=he(e),i=et(O(e.source).trim(),"source script"),r=et(O(e.analysis).trim(),"analysis"),s=et(O(e.plan).trim(),"plan"),a=bs(O(e.episodes)),c=await cn();try{let d=await c.writeReskinScript({...n,sourcePath:i,analysisPath:r,planPath:s,scriptPath:o,...a?{episodes:a}:{},force:e.force===!0,concurrency:pt(e,"concurrency",6),...t?{reviewModel:t}:{},episodeTimeoutMs:pt(e,"episode_timeout_ms",48e4),onEvent:bi});return[{text:"",data:{}},d.type==="done"&&d.failed.length===0?V:q]}catch(d){throw xr(d,"RESKIN_WRITE_FAILED")}}async function Ph(e){if(e.check)return Er(e,"reviewReskinScript");let{config:t}=dn(e),n=et(he(e),"reskinned script"),o=et(O(e.source).trim(),"source script"),i=et(O(e.analysis).trim(),"analysis"),r=et(O(e.plan).trim(),"plan"),s=bs(O(e.episodes)),a=await cn();try{let c=await a.reviewReskinScript({...t,scriptPath:n,sourcePath:o,analysisPath:i,planPath:r,...s?{episodes:s}:{},concurrency:pt(e,"concurrency",10),converge:e.converge!==!1,convergeOnly:e.converge_only===!0,maxSteps:pt(e,"max_steps",300),episodeTimeoutMs:pt(e,"episode_timeout_ms",9e5),onEvent:bi});return[{text:"",data:{}},c.some(d=>(d.type==="episode"||d.type==="global")&&d.state==="failed")?q:V]}catch(c){throw xr(c,"RESKIN_REVIEW_FAILED")}}async function Ch(e){let t=e._args??[],n=et(O(t[0]).trim(),"batch manifest"),o=O(e.output).trim();if(!o)throw new S("Batch output folder missing.",{exitCode:k,errorCode:"RESKIN_INPUT_NOT_FOUND",hint:"Pass -o <folder>; each drama gets its own project folder inside it.",data:{expected:["batch output folder"],actual:["<empty>"]}});let i=O(e.until).trim();if(i&&!vs.includes(i))throw new S("Unknown batch step.",{exitCode:k,errorCode:"RESKIN_LAYER_UNKNOWN",hint:`Pass --until ${vs.join("|")}.`,data:{expected:[...vs],actual:[i]}});let r;try{r=kh(n)}catch(l){throw new S("Batch manifest is invalid.",{exitCode:k,errorCode:"RESKIN_BATCH_INVALID",hint:"Fix the manifest and run again.",data:{expected:["{ dramas: [{ source, ... }] }"],actual:[l instanceof Error?l.message:String(l)]}})}let s=O(e.pick).trim();s&&(r.pick=s==="recommended"?"recommended":pt(e,"pick",1));let a=new Map([...Object.values(r.models),...r.search?[r.search]:[],...r.ideas??[]].map(l=>[l,dn({...e,model:l}).config])),c=await cn();Cn.mkdirSync(o,{recursive:!0});let p=(await bh(r,c,{outputDir:o,until:i||void 0,concurrency:pt(e,"concurrency",2),attempts:pt(e,"attempts",3),config:l=>a.get(l),onEvent:bi})).filter(l=>l.state==="failed").length;return[{text:"",data:{}},p?q:V]}function Th(e,t){e.command("review-view").description("Serve the step-by-step path of review runs: each unit, model round, tool call and failure").argument("[paths...]","A workspace, or a folder to search for them (default: the current folder)").option("--host <address>","Address to listen on; pass a LAN or Tailscale address to watch from another machine","127.0.0.1").option("--port <n>","HTTP server port; 0 picks a free one","5180").addHelpText("after",`
|
|
241
|
+
Example:
|
|
242
|
+
scriptctl review-view ./workspace
|
|
243
|
+
scriptctl review-view ~/Workspaces/scratch --port 5181
|
|
244
|
+
`).action(j(_h,t)),te(e.command("review"),"write").description("\u6D3E\u53D1 agent \u5BA1\u6838\u5267\u672C\uFF1A\u7ED9 -s \u5BF9\u7167\u6587\u672C\u3001\u6F2B\u753B\u6216\u89C6\u9891\u539F\u7A3F\uFF0C\u4E0D\u7ED9\u5219\u68C0\u67E5\u5267\u672C\u5185\u90E8\u4E00\u81F4\u6027").option("-s, --source-path <path>","\u6587\u672C/\u6F2B\u753B ingest \u5DE5\u4F5C\u533A\u3001\u539F txt/md/docx/PDF \u6216\u89C6\u9891\u6587\u4EF6/\u76EE\u5F55").option("--video <path>","\u7B2C N \u96C6\u7684\u89C6\u9891\uFF1B\u6309\u96C6\u987A\u5E8F\u91CD\u590D\u4F20\uFF0C\u8986\u76D6 -s \u7684\u76EE\u5F55\u6392\u5E8F",(i,r)=>[...r,i],[]).addOption(new PA("--review-strategy <strategy>","\u89C6\u9891\u5BA1\u6838\u6267\u884C\u65B9\u5F0F\uFF1Abatch \u53EF\u9009\u8054\u5408\u5BA1\u6838\uFF08\u9700\u4EBA\u5DE5\u590D\u6838\u8BC1\u636E\u51B2\u7A81\uFF09\uFF1Blegacy \u9010\u9879\u4FEE\u6B63").choices(["batch","legacy"]).default("legacy")).option("--episodes <list>","\u53EA\u5BA1\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u5267\uFF09").option("--concurrency <n>","\u9010\u96C6\u5BA1\u6838\u548C\u5168\u5267\u8D44\u4EA7\u6838\u5BF9\u7684\u5E76\u53D1\u6570",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u8D85\u65F6\uFF08\u9ED8\u8BA4 15 \u5206\u949F\uFF09\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>","\u5A92\u4F53\u9884\u7B97\uFF1A\u9010\u96C6\u9ED8\u8BA4 1 \u6B21\uFF1B\u6307\u5B9A\u4EBA\u7269\u6DF1\u5BA1\u9ED8\u8BA4\u8986\u76D6\u5168\u90E8\u76F8\u5173\u96C6\uFF0C\u663E\u5F0F\u503C\u9650\u5236\u672C\u6B21\u8986\u76D6\u96C6\u6570",Number).option("--converge-only","\u53EA\u6267\u884C\u5168\u5267\u6536\u655B\uFF0C\u4E0D\u91CD\u65B0\u5BA1\u6838\u5404\u96C6").option("--assets <list>","\u89C6\u9891\u5B9A\u70B9\u590D\u6838\u7684\u8D44\u4EA7 ID\uFF0C\u9017\u53F7\u5206\u9694\uFF1B\u4E0E --converge-only \u540C\u7528\uFF0C\u53EF\u7528 --episodes \u9650\u5B9A\u4EBA\u7269\u9636\u6BB5\u8303\u56F4").option("--resume-log <path>","\u4ECE\u5F53\u524D\u5267\u672C\u7684\u65E2\u6709\u5BA1\u6838\u65E5\u5FD7\u7EED\u8DD1\uFF0C\u4FDD\u7559\u5DF2\u5B8C\u6210\u5355\u5143\uFF1B\u591A\u4EFD\u65E5\u5FD7\u6309\u65F6\u95F4\u5148\u540E\u91CD\u590D\u4F20\u5165",(i,r=[])=>[...r,i]).option("--no-converge","\u8DF3\u8FC7\u5168\u5267\u6536\u655B\u9636\u6BB5").option("--model <profile>","\u8986\u76D6 LLM profile\uFF08\u89C6\u9891/\u7EAF\u5267\u672C\u9ED8\u8BA4 review-agent\uFF0C\u6587\u672C review-text\uFF0C\u6F2B\u753B review-comic\uFF09").option("--media-model <profile>","\u89C6\u9891\u53D6\u8BC1\u4F7F\u7528\u7684 LLM profile\uFF08\u5168\u96C6\u5B9A\u4F4D\u3001\u9759\u5E27\u4E0E\u97F3\u8F68\u6838\u5BF9\uFF09").option("--no-fallback","\u53EA\u7528\u6240\u9009\u6A21\u578B\uFF0C\u5931\u8D25\u65F6\u4E0D\u6362\u7528\u5176\u4ED6\u6A21\u578B").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(j(Eh,t));let n=e.command("reskin").description("\u6362\u58F3\u4EFF\u5199\uFF1A\u62C6\u89E3\u539F\u5267\uFF0C\u63D0\u51FA\u65B0\u58F3\u65B9\u5411\uFF0C\u9010\u5C42\u5B9A\u6362\u58F3\u65B9\u6848\uFF08\u6574\u4F53\u65B9\u6848 \u2192 \u4E8B\u4EF6 \u2192 \u8282\u62CD\uFF09\uFF0C\u6309\u7ED3\u6784\u8868\u9010\u96C6\u5199\u65B0\u5267\uFF0C\u518D\u505A\u6362\u58F3\u5BA1\u6838"),o=i=>i.option("--model <profile>","\u8986\u76D6 LLM profile\uFF08\u9ED8\u8BA4 reskin\uFF09").option("--no-fallback","\u53EA\u7528\u6240\u9009\u6A21\u578B\uFF0C\u5931\u8D25\u65F6\u4E0D\u6362\u7528\u5176\u4ED6\u6A21\u578B\uFF08\u9ED8\u8BA4\u6309\u914D\u7F6E\u7684\u964D\u7EA7\u987A\u5E8F\u6362\u7528\uFF09").option("--llm-config <path>","LLM configuration file").option("--check","\u53EA\u68C0\u67E5\u6A21\u578B\u4E0E agent \u662F\u5426\u5C31\u7EEA");o(te(n.command("analyze"),"read").description("\u62C6\u89E3\u539F\u5267\uFF1A\u5148\u901A\u8BFB\u5168\u5267\u5212\u5206\u9636\u6BB5\u4E0E\u4E8B\u4EF6\uFF0C\u518D\u6309\u9636\u6BB5\u5E76\u884C\u5199\u4E8B\u4EF6\u4E8B\u5B9E\u3001\u6309\u96C6\u5E76\u884C\u5207\u8282\u62CD\uFF0C\u540C\u65F6\u5F52\u7EB3\u5168\u5267\u753B\u50CF\uFF08\u539F\u5267\u5730\u533A\u4E0E\u53F0\u8BCD\u8BED\u8A00\u3001\u6362\u58F3\u9002\u5408\u5EA6\uFF09\u3002-p \u4E3A\u539F\u5267\u5267\u672C\uFF1B\u5DF2\u5B8C\u6210\u7684\u5355\u5143\u4FDD\u5B58\u5728\u8F93\u51FA\u6587\u4EF6\u65C1\u7684 .cache/analyze.json\uFF0C\u518D\u6B21\u8FD0\u884C\u4ECE\u65AD\u70B9\u7EE7\u7EED").option("-o, --output <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--force","\u5FFD\u7565\u5DF2\u4FDD\u5B58\u7684\u8FDB\u5EA6\u91CD\u65B0\u62C6\u89E3").option("--concurrency <n>","\u5E76\u884C\u7684\u5355\u5143\u6570",Number).option("--unit-timeout-ms <ms>","\u5355\u4E2A\u5355\u5143\u7684\u8D85\u65F6",Number)).action(j(Rh,t)),o(n.command("paths").description("\u9009\u9898\u5224\u65AD\uFF1A\u8BFB\u539F\u5267\u62C6\u89E3\u7684\u753B\u50CF\u4E0E\u5927\u7EB2\uFF0C\u9010\u4E2A\u5019\u9009\u5E02\u573A\u5217\u51FA\u8D70\u5F97\u901A\u7684\u6539\u7F16\u8DEF\u5F84\uFF08\u540C\u5E02\u573A\u6362\u8F7D\u4F53\u3001\u8DE8\u5E02\u573A\u672C\u5730\u5316\u3001\u8DE8\u5E02\u573A\u6362\u58F3\u3001\u6362\u4E16\u754C\u89C2\uFF09\uFF0C\u7ED9\u51FA\u5EFA\u8BAE\u505A\u51E0\u4E2A\u7248\u672C").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--markets <list>","\u5019\u9009\u5E02\u573A\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u5FC5\u586B\uFF09\uFF0C\u5982 \u4E2D\u56FD,\u5370\u5C3C,\u7F8E\u56FD").option("--notes <text>","\u7528\u6237\u8981\u6C42\u4E0E\u4E1A\u52A1\u4F18\u5148").option("-o, --output <path>","\u628A\u7ED3\u679C\u53E6\u5B58\u4E3A JSON")).action(j(Mh,t)),o(te(n.command("direction"),"read").description("\u4E3A\u4E00\u4E2A\u76EE\u6807\u5E02\u573A\u627E\u65B0\u58F3\uFF1A\u5148\u8054\u7F51\u8C03\u7814\u5F53\u5730\u73B0\u5B9E\uFF08\u7ED9\u51FA --search-model \u65F6\uFF09\uFF0C\u518D\u7531\u5404\u53D1\u6563\u6A21\u578B\u5206\u522B\u5217\u60F3\u6CD5\u3001\u53BB\u91CD\u7559\u4E0B\u81F3\u591A 10 \u4E2A\uFF0C\u9010\u4E2A\u8C03\u7814\u65B0\u58F3\u5728\u5F53\u5730\u7684\u73B0\u5B9E\u5E76\u5C55\u5F00\uFF0C\u7531\u72EC\u7ACB\u5BA1\u8BFB\u9010\u4E2A\u9636\u6BB5\u548C\u9AD8\u8BC6\u522B\u573A\u9762\u7ED9\u51FA\u627F\u63A5\u7A0B\u5EA6\uFF08\u6210\u7ACB\u3001\u8981\u6539\u505A\u6CD5\u3001\u7275\u5F3A\u3001\u6491\u4E0D\u4F4F\uFF09\uFF0C\u6709\u4E00\u5904\u6491\u4E0D\u4F4F\u7684\u5019\u9009\u820D\u5F03\uFF0C\u5176\u4F59\u6392\u5E8F\u5E76\u63A8\u8350\uFF1B\u7ED9\u51FA --custom \u65F6\u5224\u65AD\u7528\u6237\u6307\u5B9A\u7684\u65B9\u5411\u5E76\u6309\u5B83\u8BBE\u8BA1\u3001\u5BA1\u8BFB\u4E00\u4E2A\u5019\u9009\u3002-p \u4E3A\u539F\u5267\u5267\u672C").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--notes <text>","\u7528\u6237\u7684\u6362\u58F3\u8981\u6C42").option("--custom <text>","\u7528\u6237\u6307\u5B9A\u7684\u6362\u58F3\u65B9\u5411").option("--market <text>","\u65B0\u5267\u9762\u5411\u7684\u76EE\u6807\u5E02\u573A\uFF0C\u9ED8\u8BA4\u540C\u539F\u5267").option("--rating <text>","\u5C3A\u5EA6\u8981\u6C42\uFF0C\u9ED8\u8BA4\u540C\u539F\u5267").option("--avoid <shell>","\u8FD9\u90E8\u539F\u5267\u5DF2\u505A\u8FC7\u7684\u7248\u672C\u7684\u58F3\uFF0C\u53EF\u91CD\u590D\u7ED9\u51FA\uFF1B\u65B0\u60F3\u6CD5\u4E0E\u5B83\u4EEC\u660E\u663E\u4E0D\u540C",(i,r=[])=>[...r,i]).option("--used <path>",'\u8FD9\u4E2A\u76EE\u6807\u5E02\u573A\u5DF2\u505A\u6210\u4EFF\u5199\u5267\u7684\u58F3\uFF08JSON \u6587\u4EF6\uFF0C[{ "drama": \u5267\u540D, "shell": \u65E7\u58F3 \u2192 \u65B0\u58F3 }]\uFF09\uFF1B\u5BA1\u8BFB\u6807\u51FA\u4E0E\u5B83\u4EEC\u76F8\u8FD1\u7684\u5019\u9009').option("--evidence <path>","\u76EE\u6807\u5E02\u573A\u540C\u7C7B\u5267\u6570\u636E\uFF08\u6587\u672C\u6587\u4EF6\uFF09\uFF1A\u4EE3\u8868\u5267\u548C\u5B83\u4EEC\u8BB2\u4EC0\u4E48\uFF0C\u7528\u6765\u542F\u53D1\u60F3\u6CD5\u548C\u5224\u65AD\u89C2\u4F17\u719F\u6089\u7A0B\u5EA6").option("--search-model <profile>","\u8054\u7F51\u641C\u7D22\u7528\u7684 LLM profile\uFF1A\u5B83\u548C\u5B83\u7684 fallbacks \u91CC\u7684 Gemini \u6E20\u9053\u8F6E\u6D41\u5F00\u641C\uFF0C\u8C03\u7814\u5F53\u5730\u73B0\u5B9E\uFF1B\u4E0D\u7ED9\u5219\u4E0D\u8C03\u7814").option("--idea-model <profile>","\u53D1\u6563\u60F3\u6CD5\u7684 LLM profile\uFF0C\u53EF\u91CD\u590D\u7ED9\u51FA\uFF1B\u51E0\u4E2A\u6A21\u578B\u5206\u522B\u5217\u60F3\u6CD5\u540E\u53BB\u91CD\uFF08\u9ED8\u8BA4\u7528 --model\uFF09",(i,r=[])=>[...r,i]).option("-o, --output <path>","\u628A\u7ED3\u679C\u53E6\u5B58\u4E3A JSON")).action(j(Nh,t)),o(te(n.command("plan"),"read").description("\u9010\u5C42\u751F\u6210\u6362\u58F3\u65B9\u6848\uFF1A\u6574\u4F53\u65B9\u6848\uFF08\u542B\u9636\u6BB5\u8D70\u5411\uFF09\u2192 \u5404\u9636\u6BB5\u4E8B\u4EF6 \u2192 \u5404\u9636\u6BB5\u8282\u62CD \u2192 \u65B9\u6848\u6838\u9A8C \u2192 \u6545\u4E8B\u65F6\u95F4\u7EBF \u2192 \u4EBA\u7269\u9020\u578B\uFF0C\u4E0B\u5C42\u53EF\u56DE\u6539\u4E0A\u5C42\u5E76\u590D\u67E5\u53D7\u5F71\u54CD\u7684\u90E8\u5206\u3002-p \u4E3A\u539F\u5267\u5267\u672C\uFF1B\u5DF2\u6709\u65B9\u6848\u65F6\u4ECE\u672A\u5B8C\u6210\u7684\u90E8\u5206\u7EE7\u7EED").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--direction <path>","\u9009\u5B9A\u7684\u6362\u58F3\u65B9\u5411\u8BF4\u660E\uFF08\u5FC5\u586B\uFF09").option("-o, --output <path>","\u6362\u58F3\u65B9\u6848 JSON\uFF08\u5FC5\u586B\uFF09").option("--until <layer>","\u505A\u5230\u8FD9\u4E00\u5C42\u540E\u6682\u505C\uFF1Aoverall | events | beats").option("--force","\u5FFD\u7565\u5DF2\u6709\u65B9\u6848\u91CD\u65B0\u751F\u6210").option("--unit-timeout-ms <ms>","\u5355\u4E2A\u5355\u5143\u7684\u8D85\u65F6",Number)).action(j(Lh,t)),o(te(n.command("write"),"write").description("\u6309\u6362\u58F3\u65B9\u6848\u7684\u7ED3\u6784\u8868\u5199\u65B0\u5267\uFF1A\u9636\u6BB5\u5185\u6309\u96C6\u5E8F\u5199\uFF0C\u9636\u6BB5\u4E4B\u95F4\u5E76\u884C\uFF1B\u53EF\u9010\u96C6\u5BA1\u6838\u5E76\u4F20\u9012\u8D26\u672C\u3002-p \u4E3A\u65B0\u5267\u5267\u672C\uFF0C\u4E0D\u5B58\u5728\u6216\u6362\u540D\u6362\u5916\u89C2\u53D8\u5316\u65F6\u4ECE\u539F\u5267\u590D\u5236\uFF1B\u6BCF\u6761\u6B63\u6587\u8BB0\u4E0B\u6240\u5C5E\u7684\u65B0\u8282\u62CD\uFF0C\u4E0D\u5199\u65F6\u95F4\u6233").option("--source <path>","\u539F\u5267\u5267\u672C\uFF08\u5FC5\u586B\uFF09").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--plan <path>","\u5DF2\u5B8C\u6210\u7684\u6362\u58F3\u65B9\u6848 JSON\uFF08\u5FC5\u586B\uFF09").option("--episodes <list>","\u53EA\u5199\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u5267\u672A\u5B8C\u6210\u7684\u96C6\uFF09").option("--force","\u6240\u9009\u7684\u96C6\u5DF2\u5199\u8FC7\u4E5F\u91CD\u5199").option("--review-model <profile>","\u9010\u96C6\u5199\u5B8C\u5373\u7528\u6B64 profile \u5BA1\u6838\uFF0C\u8D26\u672C\u4F20\u7ED9\u4E0B\u4E00\u96C6").option("--concurrency <n>","\u540C\u65F6\u8FD0\u884C\u7684\u9636\u6BB5\u94FE\u6570\uFF08\u9ED8\u8BA4 6\uFF09",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u5199\u4F5C\u8BF7\u6C42\u8D85\u65F6\uFF08\u9ED8\u8BA4 8 \u5206\u949F\uFF09\uFF1B\u9010\u96C6\u5BA1\u6838\u6309\u5BA1\u6838\u7684\u5355\u96C6\u8D85\u65F6\uFF0815 \u5206\u949F\uFF09",Number)).action(j(Uh,t)),o(te(n.command("review"),"write").description("\u6362\u58F3\u5BA1\u6838\uFF1A\u6309\u96C6\u5E8F\u901A\u8BFB\uFF0C\u9010\u96C6\u5BA1\u6362\u5F97\u662F\u5426\u5408\u7406\u3001\u662F\u5426\u770B\u5F97\u61C2\u4E0E\u901A\u987A\u3001\u524D\u540E\u662F\u5426\u8FDE\u8D2F\u3001\u9020\u578B\u4E0E\u573A\u666F\u5F15\u7528\u662F\u5426\u51C6\u786E\uFF0C\u5904\u7406\u7A0B\u5E8F\u68C0\u67E5\u7ED3\u679C\uFF0C\u518D\u505A\u5168\u5267\u6536\u5C3E\u3002-p \u4E3A\u65B0\u5267\u5267\u672C\uFF1B\u4E8B\u4EF6\u683C\u5F0F\u4E0E review \u76F8\u540C").option("--source <path>","\u539F\u5267\u5267\u672C\uFF08\u5FC5\u586B\uFF09").option("--analysis <path>","\u539F\u5267\u62C6\u89E3 JSON\uFF08\u5FC5\u586B\uFF09").option("--plan <path>","\u6362\u58F3\u65B9\u6848 JSON\uFF08\u5FC5\u586B\uFF09").option("--episodes <list>","\u53EA\u5BA1\u8FD9\u4E9B\u96C6\uFF0C\u9017\u53F7\u5206\u9694\uFF08\u9ED8\u8BA4\u5168\u90E8\uFF09").option("--concurrency <n>","\u540C\u65F6\u8FDB\u884C\u7684\u9636\u6BB5\u94FE\u6570\uFF08\u9ED8\u8BA4 10\uFF09",Number).option("--max-steps <n>","\u6BCF\u96C6\u6700\u591A\u51E0\u6B65\u5DE5\u5177\u8C03\u7528",Number).option("--episode-timeout-ms <ms>","\u5355\u96C6\u8D85\u65F6\uFF08\u9ED8\u8BA4 15 \u5206\u949F\uFF09",Number).option("--converge-only","\u53EA\u6267\u884C\u9636\u6BB5\u9996\u96C6\u63A5\u7F1D\u590D\u6838\u4E0E\u5168\u5267\u6536\u5C3E").option("--no-converge","\u8DF3\u8FC7\u5168\u5267\u6536\u5C3E")).action(j(Ph,t)),n.command("batch").argument("<manifest>","\u6279\u91CF\u6E05\u5355 JSON\uFF1A{ dramas: [{ id, source, market, language, rating, notes, custom, pick, avoid }], models, prices, pick }").description("\u65E0\u4EBA\u503C\u5B88\u6279\u91CF\u6362\u58F3\uFF1A\u6BCF\u90E8\u5267\u5728 -o \u4E0B\u6709\u81EA\u5DF1\u7684\u9879\u76EE\u76EE\u5F55\uFF0C\u4F9D\u6B21\u62C6\u89E3 \u2192 \u65B9\u5411 \u2192 \u65B9\u6848 \u2192 \u5199\u4F5C \u2192 \u5BA1\u6838\uFF0C\u6BCF\u6B65\u4ECE\u5DF2\u4FDD\u5B58\u7684\u8FDB\u5EA6\u7EE7\u7EED\u3002\u62C6\u89E3\u8BC4\u51FA\u7684\u9002\u5408\u5EA6\u4F4E\u4E8E 3 \u4E14\u6CA1\u5199 pick \u65F6\u505C\u5728\u62C6\u89E3\u540E\uFF0C\u6307\u5B9A\u65B9\u5411\u4E0D\u53EF\u884C\u6216\u9700\u8981\u4EBA\u5DE5\u9009\u65B9\u5411\u65F6\u505C\u5728\u65B9\u5411\u6B65\uFF1B\u8865\u4E0A pick \u540E\u518D\u8FD0\u884C\u5373\u4ECE\u65B9\u5411\u7EE7\u7EED\u3002\u8FDB\u5EA6\u4E0E\u62A5\u544A\u5199\u5728 -o \u4E0B\u7684 batch-report.json / batch-report.md").option("-o, --output <dir>","\u6279\u91CF\u8F93\u51FA\u76EE\u5F55\uFF08\u5FC5\u586B\uFF09").option("--concurrency <n>","\u540C\u65F6\u8FDB\u884C\u7684\u5267\u6570\uFF08\u9ED8\u8BA4 2\uFF09",Number).option("--attempts <n>","\u6BCF\u6B65\u6700\u591A\u8FD0\u884C\u51E0\u6B21\uFF0C\u6BCF\u6B21\u4ECE\u4E0A\u6B21\u8FDB\u5EA6\u7EE7\u7EED\uFF08\u9ED8\u8BA4 3\uFF09",Number).option("--pick <n|recommended>","\u6CA1\u5199 pick \u7684\u5267\u7528\u8FD9\u4E2A\u5019\u9009\uFF1B\u4E0D\u7ED9\u65F6\u505C\u4E0B\u7B49\u4EBA\u5DE5\u9009\u62E9").option("--until <step>","\u505A\u5230\u8FD9\u4E00\u6B65\u540E\u505C\u4E0B\uFF1Aanalyze | direction | plan | write | review").option("--no-fallback","\u53EA\u7528\u6240\u9009\u6A21\u578B\uFF0C\u5931\u8D25\u65F6\u4E0D\u6362\u7528\u5176\u4ED6\u6A21\u578B\uFF08\u9ED8\u8BA4\u6309\u914D\u7F6E\u7684\u964D\u7EA7\u987A\u5E8F\u6362\u7528\uFF09").option("--llm-config <path>","LLM configuration file").action(j(Ch,t))}import*as Vh from"node:fs";var zo="\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 He(e){let t=he(e);if(!Vh.existsSync(t))throw new S("Local script file not found.",{exitCode:k,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[t]}});return Jp(t)}function we(e,t){let n=e[t];return typeof n=="string"?n:void 0}function vi(e,t){let n=e[t];if(n==null||n==="")return;let o=Number(n);if(!Number.isFinite(o))throw new S(`--${t} must be a number.`,{exitCode:k,errorCode:"OPTION_NOT_NUMBER",data:{actual:[String(n)]}});return o}function xe(e,t=0){return(e._args??[])[t]??""}function bl(e){return Array.isArray(e)?e.map(String):typeof e=="string"?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function lt(e,t,n=()=>({})){try{let o=e();return[{text:o,data:{op:t,changed:!1,text:o,...n()}},V]}catch(o){throw o instanceof S?o:new S(o instanceof Error?o.message:String(o),{exitCode:k,errorCode:o?.code??"SCRIPT_TOOL_FAILED"})}}function $h(e,t){let n=te(e.command("read [addr]"),"read").description(`\u8BFB\u4EFB\u610F\u8282\u70B9\uFF1B\u4E0D\u7ED9\u5730\u5740\u8FD4\u56DE\u5267\u672C\u5361\u3002${zo}`).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(j(y=>{let E=He(y);return lt(()=>Ba(E,xe(y),{...y.outline?{depth:"outline"}:{},...y.plain?{plain:!0}:{},...vi(y,"context")!==void 0?{context:vi(y,"context")}:{}}),"read",()=>xe(y)?{}:{document:E.raw})},t));Le(n,[zo]);let o=te(e.command("scan <episode>"),"read").description("\u4E00\u6B21\u8FD4\u56DE\u67D0\u96C6\u7684\u5B8C\u6574\u4E0A\u4E0B\u6587\uFF1A\u573A\u7ED3\u6784 + \u5168\u90E8\u6B63\u6587 + \u5F53\u524D\u6821\u9A8C\u95EE\u9898").action(j(y=>lt(()=>{let E=He(y),_=xe(y);return[`## \u573A\u7ED3\u6784
|
|
245
|
+
${Ba(E,_,{depth:"outline"})}`,`## \u6B63\u6587
|
|
246
|
+
${Ba(E,_)}`,`## \u5F53\u524D\u6821\u9A8C\u95EE\u9898
|
|
247
|
+
${il(E,{})}`].join(`
|
|
248
|
+
|
|
249
|
+
`)},"scan"),t));Le(o,["\u96C6\u53F7\uFF0C\u4ECE 1 \u5F00\u59CB"]);let i=te(e.command("find [query]"),"read").description("\u6309\u6B63\u6587\u6B63\u5219 / \u8BF4\u8BDD\u4EBA / \u7C7B\u578B\u5B9A\u4F4D action\uFF0C\u8FD4\u56DE\u951A\u70B9 + \u547D\u4E2D\u7A97\u53E3").option("-i, --in <addr>",`\u9650\u5236\u8303\u56F4\uFF0C${zo}`).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(j(y=>lt(()=>vg(He(y),xe(y),{...we(y,"in")?{in:we(y,"in")}:{},...we(y,"speaker")?{speaker:we(y,"speaker")}:{},...we(y,"type")?{type:we(y,"type")}:{},...vi(y,"limit")!==void 0?{limit:vi(y,"limit")}:{},...y.full?{full:!0}:{}}),"find"),t));Le(i,["\u6B63\u5219\uFF1B\u53EA\u6309 speaker/type \u8FC7\u6EE4\u65F6\u53EF\u7701\u7565"]);let r=te(e.command("refs <addr>"),"read").description("\u53EA\u8BFB\u5B9A\u4F4D\u8D44\u4EA7/\u9020\u578B\u7684\u573A\u666F\u7ED1\u5B9A\u3001\u8BF4\u8BDD\u5F15\u7528\u548C\u6B63\u6587\u63D0\u53CA\uFF0C\u8FD4\u56DE\u53EF read \u7684\u5730\u5740\u53CA\u4E0A\u4E0B\u6587").option("--offset <n>","\u4ECE\u7B2C\u51E0\u6761\u5F15\u7528\u7EE7\u7EED\uFF08\u4ECE 0 \u5F00\u59CB\uFF09").option("--limit <n>","\u672C\u6279\u5F15\u7528\u6570\uFF08\u9ED8\u8BA4 20\uFF09").option("--context <n>","\u6B63\u6587\u547D\u4E2D\u524D\u540E\u5404\u51E0\u6761 action\uFF08\u9ED8\u8BA4 3\uFF09").action(j(y=>{let E=Wp(He(y),xe(y),{offset:vi(y,"offset"),limit:vi(y,"limit"),context:vi(y,"context")});return[{text:Zp(E),data:{op:"refs",changed:!1,...E}},V]},t));Le(r,["\u4EBA\u7269/\u573A\u666F/\u9053\u5177 ID \u6216\u540D\u79F0\uFF0C\u6216 <\u8D44\u4EA7>/<\u9020\u578B>\uFF1B\u6B63\u6587\u63D0\u53CA\u4E0D\u7B49\u4E8E\u5B9E\u9645\u51FA\u573A"]);let s=te(e.command("span <range>"),"read").description("\u628A\u4E00\u6BB5 action \u6362\u7B97\u6210\u96C6\u5185\u89C6\u9891\u65F6\u95F4\u7A97\u53E3\uFF08\u534A\u5F00\u533A\u95F4\uFF09").action(j(y=>{let E=He(y);return lt(()=>Og(E,xe(y)),"span",()=>({rows:[tl(E,xe(y))]}))},t));Le(s,[`${zo}\uFF0C\u6216 \`\u8D77ID..\u6B62ID\``]),te(e.command("validate"),"read").description("\u8DD1\u6574\u672C\u6821\u9A8C").action(j(y=>{let E=He(y),_=gr(E);return[{text:Gg(E),data:{op:"script.validate",changed:!1,passed:_.ok,script_path:E.path,stats:{actors:E.assets.filter(x=>x.kind==="actor").length,locations:E.assets.filter(x=>x.kind==="location").length,props:E.assets.filter(x=>x.kind==="prop").length,episodes:E.episodes.length,scenes:E.episodes.reduce((x,A)=>x+A.scenes.length,0),actions:Un(E).length},issues:[..._.errors.map(x=>({...x,severity:"error"})),..._.warnings.map(x=>({...x,severity:"warning"}))]}},_.ok?V:Eo]},t)),te(e.command("issues"),"read").description("\u5217\u5F53\u524D\u6821\u9A8C\u95EE\u9898").option("--severity <severity>","error | warning").option("--code <code>","\u6309 issue code \u8FC7\u6EE4").action(j(y=>lt(()=>il(He(y),{...we(y,"severity")?{severity:we(y,"severity")}:{},...we(y,"code")?{code:we(y,"code")}:{}}),"issues"),t));let a=te(e.command("edit <addr>"),"write").description(`\u6539\u4E00\u4E2A\u8282\u70B9\u7684\u5B57\u6BB5\uFF1B\u5730\u5740\u51B3\u5B9A\u54EA\u4E9B\u5B57\u6BB5\u5408\u6CD5\u3002${zo}`).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(j(y=>{let E={};for(let _ of["content","speaker","type","name","desc","importance","role","space","time","title","synopsis","logline","theme","worldview","style","main"]){let x=we(y,_);x!==void 0&&(E[_]=x)}for(let _ of["paren","ts","transition"])if(y[_]===!1)E[_]=null;else{let x=we(y,_);x!==void 0&&(E[_]=x)}return y.alias!==void 0&&(E.aliases=bl(y.alias)),lt(()=>Rg(He(y),xe(y),E),"edit")},t));Le(a,[zo]);let c=te(e.command("insert <addr> <content>"),"write").description("\u5728\u67D0\u6761 action \u524D/\u540E\u63D2\u5165\u4E00\u6761\u65B0 action").requiredOption("-t, --type <type>","action | dialogue | inner_thought | transition").option("--before","\u63D2\u5230\u76EE\u6807\u4E4B\u524D\uFF08\u9ED8\u8BA4\u4E4B\u540E\uFF09").option("-a, --speaker <name>","dialogue / inner_thought \u5FC5\u586B").option("--paren <text>","\u8868\u6F14\u63D0\u793A").action(j(y=>lt(()=>Mg(He(y),xe(y),y.before?"before":"after",we(y,"type"),xe(y,1),we(y,"speaker"),we(y,"paren")),"insert"),t));Le(c,["\u76F8\u90BB action \u7684\u5730\u5740","\u65B0 action \u7684\u6B63\u6587"]);let d=te(e.command("move <addr> <to>"),"write").description("\u628A\u4E00\u6761 action \u632A\u5230\u53E6\u4E00\u6761\u65C1\u8FB9\uFF1B\u8DE8\u573A\u4E5F\u4FDD\u6301 action_id").option("--before","\u632A\u5230\u76EE\u6807\u4E4B\u524D\uFF08\u9ED8\u8BA4\u4E4B\u540E\uFF09").action(j(y=>lt(()=>Ng(He(y),xe(y),xe(y,1),y.before?"before":"after"),"move"),t));Le(d,["\u8981\u632A\u7684 action","\u76EE\u6807\u90BB\u5C45 action"]);let p=te(e.command("write <addr>"),"write").description("\u7528 read \u8F93\u51FA\u7684\u540C\u4E00\u4EFD\u6B63\u6587\u683C\u5F0F\u56DE\u5199\u6574\u573A / \u6574\u96C6 / \u65B0\u96C6\uFF08`+`\uFF09").option("-f, --file <path>","\u6B63\u6587\u6587\u4EF6\uFF1B\u7701\u7565\u5219\u8BFB stdin").option("--allow-delete","\u5141\u8BB8\u5220\u9664\u6587\u672C\u91CC\u6D88\u5931\u7684\u573A / action").action(j(async y=>{let E=await import("node:fs"),_=we(y,"file"),x=_?E.readFileSync(_,"utf8"):E.readFileSync(0,"utf8");return lt(()=>Pg(He(y),xe(y),x,{allowDelete:!!y.allow_delete}),"write")},t));Le(p,["\u573A / \u96C6\u5730\u5740\uFF0C\u6216 `+` \u8FFD\u52A0\u65B0\u96C6"]);let l=te(e.command("replace <pattern> <to>"),"write").description("\u6279\u91CF\u66FF\u6362\u6B63\u6587\uFF1B\u9ED8\u8BA4\u53EA\u9884\u89C8\uFF0C--apply \u624D\u843D\u76D8\u3002\u8FC7\u6EE4\u53C2\u6570\u4E0E find \u76F8\u540C").option("-i, --in <addr>","\u9650\u5236\u8303\u56F4").option("-a, --speaker <name>","\u9650\u5B9A\u8BF4\u8BDD\u4EBA").option("-t, --type <type>","\u9650\u5B9A action \u7C7B\u578B").option("--apply","\u771F\u7684\u5199\u5165").action(j(y=>lt(()=>$g(He(y),xe(y),xe(y,1),{...we(y,"in")?{in:we(y,"in")}:{},...we(y,"speaker")?{speaker:we(y,"speaker")}:{},...we(y,"type")?{type:we(y,"type")}:{},...y.apply?{apply:!0}:{}}),"replace"),t));Le(l,["\u6B63\u5219","\u66FF\u6362\u6210\u4EC0\u4E48"]);let f=te(e.command("ref <scene> <asset>"),"write").description("\u6539\u4E00\u4E2A\u573A\u5BF9\u67D0\u8D44\u4EA7\u7684\u5F15\u7528\uFF1B--state \u662F\u5B8C\u6574\u72B6\u6001\u96C6\u5408\u800C\u975E\u8FFD\u52A0").option("--state <list>","\u5B8C\u6574\u72B6\u6001\u96C6\u5408\uFF08\u540D\u5B57\u6216 ID\uFF09\uFF0C\u9017\u53F7\u5206\u9694\u6216\u91CD\u590D\u7ED9\u51FA",CA,[]).option("--remove","\u5220\u9664\u6574\u6761\u5F15\u7528").action(j(y=>lt(()=>Vg(He(y),xe(y),xe(y,1),bl(y.state).flatMap(E=>E.split(",")).map(E=>E.trim()).filter(Boolean),!!y.remove),"ref"),t));Le(f,["\u573A\u5730\u5740","\u4EBA\u7269 / \u5730\u70B9 / \u9053\u5177\u7684\u540D\u5B57\u6216 ID"]);let u=te(e.command("asset <kind> <name>"),"write").description("\u767B\u8BB0\u4E00\u4E2A\u65B0\u7684 actor / location / prop").requiredOption("--desc <text>","\u63CF\u8FF0").option("--importance <tier>","featured | background","featured").option("--alias <list>","\u522B\u540D\uFF0C\u9017\u53F7\u5206\u9694").action(j(y=>lt(()=>Bg(He(y),xe(y),xe(y,1),we(y,"desc")??"",we(y,"importance")??"featured",bl(y.alias)),"asset"),t));Le(u,["actor | location | prop","\u540D\u5B57"]);let h=te(e.command("state <asset> <name>"),"write").description("\u7ED9\u5DF2\u6709\u8D44\u4EA7\u52A0\u4E00\u4E2A\u72B6\u6001\uFF08\u9020\u578B\u6863\u4F4D\uFF09").requiredOption("--desc <text>","\u63CF\u8FF0").action(j(y=>lt(()=>Jg(He(y),xe(y),xe(y,1),we(y,"desc")??""),"state"),t));Le(h,["\u8D44\u4EA7\u540D\u6216 ID","\u72B6\u6001\u540D"]);let m=te(e.command("del <addr>"),"write").description("\u5220\u9664 action / \u573A / \u96C6 / \u8D44\u4EA7 / \u72B6\u6001").option("--replacement <state>","\u5220\u72B6\u6001\u65F6\u628A\u5F15\u7528\u6539\u5199\u5230\u8FD9\u4E2A\u72B6\u6001").option("--force","\u5BB9\u5668\u975E\u7A7A\u65F6\u4ECD\u7136\u5220\u9664").action(j(y=>lt(()=>Kg(He(y),xe(y),{...we(y,"replacement")?{replacement:we(y,"replacement")}:{},...y.force?{force:!0}:{}}),"del"),t));Le(m,[zo]);let g=te(e.command("merge <src> <dst>"),"write").description("\u628A\u4E00\u4E2A\u8D44\u4EA7\u5E76\u5165\u53E6\u4E00\u4E2A\uFF1A\u5168\u90E8\u573A\u666F\u5F15\u7528\u4E0E speaker \u6539\u5199\u8FC7\u53BB").action(j(y=>lt(()=>al(He(y),xe(y),xe(y,1)),"merge"),t));Le(g,["\u88AB\u5E76\u5165\u7684\u8D44\u4EA7","\u4FDD\u7559\u7684\u8D44\u4EA7"]);let w=te(e.command("ext <addr> [key] [value]"),"write").description("\u8BFB\u6216\u5199\u4EFB\u610F\u8282\u70B9\u7684 extend \u6570\u636E").option("--remove","\u5220\u9664\u8BE5 key").action(j(y=>lt(()=>zg(He(y),xe(y),xe(y,1)||void 0,xe(y,2)||void 0,!!y.remove),"ext"),t));Le(w,[zo,"extend key","\u503C"])}function CA(e,t){return[...t,e]}import*as Yw from"node:path";var pn={createExecutor:dg};import*as eu from"node:fs";import*as vr from"node:path";var Tn=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();var Os=e=>String(e).padStart(3,"0"),vl=e=>e.normalize("NFC").replace(/\s+/g," ").trim();function Dh(e,t={}){let n=[],o=[],i=null,r=null,s=0,a=0,c=new Map,d=(l,f)=>{let u=`text:${l}:${f.chunk}:${f.line_start}:${f.line_end}`,h=(c.get(u)??0)+1;return c.set(u,h),`${u}:${h}`},p=(l,f)=>{let u=l.actors.find(h=>vl(h.name)===vl(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_${Os(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_${Os(s)}`,scenes:[]},n.push(i)),a++,r={identity_key:d("scene",l.source),scene_id:`scn_${Os(a)}`,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 Rs=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=vl(t),i=this.byNorm.get(o);return i||(i={provisional_id:`${this.prefix}_${Os(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=Tn(n),i=t.states.find(s=>Tn(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 TA(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 rc(e){let t=0,n=()=>`st_${Os(++t)}`,o=new Rs("act","actor",n),i=new Rs("loc","location",n),r=new Rs("prp","prop",n),s={episode:{},scene:{},action:{}},a={episode:new Set,scene:new Set,action:new Set},c=(u,h,m)=>{if(!m||a[u].has(m))throw new Error(`Duplicate or missing ${u} source identity: ${m}`);a[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)=>(c("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}`;c("scene",w,m.identity_key);let y={episode:h,scene:g},E=m.location?d(i,m.location,y,"location_id"):null,_=m.actors.map(b=>d(o,b,y,"actor_id")),x=m.props.map(b=>d(r,b,y,"prop_id")),A=m.actions.map((b,U)=>{c("action",`${w}#${U}`,b.identity_key);let v={type:b.type,content:b.content};if(b.speaker)if("name"in b.speaker){let I=o.ensure(b.speaker.name,y),R={actor_id:I.provisional_id};b.speaker.state!==void 0&&(R.state_id=o.stateId(I,b.speaker.state)),v.speaker=R}else v.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?v.emotion=b.parenthetical:b.emotion!==void 0&&(v.emotion=b.emotion)),b.extend!==void 0&&(v.extend=b.extend),v});return{scene_id:m.scene_id,...m.environment?{environment:m.environment}:{},location:E,actors:_,props:x,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:TA(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 Gh(e,t={}){let n=t.maxChars??500,o=e.split(`
|
|
243
250
|
`),i=[],r=0,s=0,a=c=>{let d=o.slice(r,c).join(`
|
|
244
|
-
`);return d.trim()===""?!1:(i.push({index:i.length,core_line_start:r,core_line_end:c,text:d}),r=c,s=0,!0)};for(let c=0;c<o.length;c++){let d=o[c],l=s+(c===r?0:1)+d.length;d.trim()!==""&&c>r&&l>n&&a(c)?s=d.length:s=l}return a(o.length),i}var
|
|
245
|
-
`);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 Ee("invalid JSON",i+1+t)}if(!
|
|
246
|
-
`)}var
|
|
247
|
-
`)}function
|
|
248
|
-
`);function
|
|
249
|
-
`)}function
|
|
250
|
-
`);i=Os(r)}catch(r){throw r instanceof Ee?sc(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)]):sc(n(19)+t[n(73)]+n(69),[n(2)]);return i}function Ll(){let e=["lsdOVAZLNlRVVjP7iMTPBMqIoIj0CMfUC2L0Aw9UiIWIy29UDgvUDci6iUw/OowUNUI9RoAnOUAiKoEUGos9K+s4REAwH+EAHoI9RowCUUAwH+wTLYj944cc5BI46kEb5Qc85BYp6k+n5lMF6kAb57+76k+r77Ym5l6l5AAcigbgteftsejbq0TGiokgKIbG6zEQ5zUEyooaGwbcqunlifrpifbsrvnftLrGiokgKIbG5zUE5yIW546W5A6EyooaGG","BgvUz3rO","CMvJB3jKCZOGma","icdOKAhOR63LIQJKVzWGyfvTihbYyxrVigrLig9MzxjLBMrHCYbJywKGzgeGBwvZysbLihnLigvZCgfSAgeGCgvSBYbJAmoJBY5GiokgKIbHy3rPB24Uy29UDgvUDd1G5lIa55Uy5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5l6B5lIT5PAh57Yw5yMN5Asn5Qc455Qe5Qch5yEg56I/77YAzgLHBg9NDwuG5zkmigLUBMvYx3rOB3vNAhqG55QeignVBNrLBNqG6ycq5A2x5l+D55wz5RQq5PAh5PYS5A6E6zMf6k+T6kIa5lIo5As55P2c6k+T6kIa77Ym57UD5lIn57+76k+r77YB6zMK5Q2K5lUL5Asw77Ymywn0Aw9U44cbDhjHBNnPDgLVBUoaGw5VDgxJGifLBw90Aw9Uios7PEwpIUwCUUAzR+EAHoMaMUEuQowCSoEcUEApJ+I/SoMdVEs9V+EuQoIhQUEeTUoaGEwhHUEHRUEAHoEUGos9K+s4REAwH+oaGUs6UUEjQEwNK+wqJEwCQcbZCgvHA2vYlM5HBwxJGifZy2vUzs5Hy3rVCNpJGifHy3rPB24G5zkm5zco57UT6lwe5lQN55M76k6W5lIT6yo95B+f6Ag75Rk/55sO5RQq5PAh5PYS55Qe5y6F5AEl5OU85yAz77Ym5lIn57+76k+r44cb5lIn6z+Z6k+r44cb5lIn5Ps55OIq5lIT5PAh5zcn77YB5zob54Mm5zkm5RkH5PYj6ycA6kgm6k+r5zcn55Qe5yw25lUw5lIt5zcn5l+D55wz5y6F5PAh44cc5lIn5B6x5OQk5Pw05y+L5Asw6k+T5yQO5l2C5OIw546V5Akd5O+p6l+W5y6F5Qc355wz5zYOigfJDgLVBIdKUk3JGii","icdLKiZKUidLJ6xNLlhLPjRKURRLKiZML7BOR7tML7BVViZKUlRMR4/KUkROR7tOR53KURRLKitLHPNKUidMNAhNM7JPGRSGzgLHBg9NDwxVViXJB250zw50ioEBUowqJooaGG","6l2S5O2I6kEe5yIz77YA","44cq5B6f6kEe6iYd5yYw55Qe5y6F5PAh54Mh5Q6144cr"];return Ll=function(){return e},Ll()}async function Fh(e,t,n){let o=Y,i=await e[o(41)](o(71),{system:HA,user:QA(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 sc(o(19)+t[o(73)]+o(50),[i[o(53)][o(7)](0,500)])}return{raw:i[o(53)],records:Ul(r,t)}}var Cl=fn,YA=Cl(1);function qA(e){let t=Cl,n=e[t(5)](/起点\s*[::]\s*(\d+)/);return n?{found:!0,line:Math[t(3)](Number(n[1]))}:{found:!1,line:null}}function Pl(){let e=["Dgv4Da","5l2G5PIV55+T5yMN5yMN5PYS55Qe44cm5Q2J5PAh6lw354k55A6A5l2n5zMO44cn44cc5lIa5lU95PAh5lU25BI45BI45zYO55YF5Q2J55Qe5yMN5PYS5Q2J5PAh5lMl5yMn77Ym5y6l552a5lIa5AsN5Q61kIRPNz7MRApMLOCQkUEAHoETUEwKH+ADKoAwMEoaGUs9OoIMGEwiPoAwRE+8MIOQ55YF5Q2J55Qe5yMN5PYS5Q2J5PAhkIRMMk/KUi3MMk/LNkJMIjhNU5NKVAdNMOtOV5NMRRxLUkBOOyZLJ7FNMOtMLOFMNkZPH4ZLVidLP4VVViZLPOlMNPZMMk/VViZMIQxLKyRLROpNMOtOTBFLP4VOOyZLJ7FJGiikcUoaKoATO+AwH+MvV+s7Gos5IoAGT+oaKEMaKowCUUEAHowjP+ACRo+8MUs7PEoaJoESRe7PM4BJGi3KUlRPM4BLPltVViZKUiVPNAlNTkFOT5/JGiZLNlPylvKGioAxPs/LHOuG5zYW54k544cn6l+z56En5BIM5zY65QYH57Yw5y+355Qe5zY65PMV5As077Ym5yAn5B6a5lIl5PIV44cm5lI76kAb5lQ654MP77YAl+s6UUEjQE+8MUoaJEwsJos4GoADOEADOEs7PsdILRmG5BYa5As055Qe5yQO5l2C44cb5lUL5y+k5BIM6k+06k+D5lQ655Qe5y+W6k+n44cc6l+z5OMn5PIV5Q2J5PAh44cccGRJGjdLIy3OQidPLB/KU4dKUyJMOlFVViZNU53KUi3NRPFMRApMLOFJGjhVVjOklsdPOBNNM67LN7RMNkZKV6hMGA8GlYdNRzBLIjlLPkFNURiGlYdPOP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L44cm6kgm5y+3pfrbqJ7LHOxLRRNJGi3NU5NLH7RJGilLIktMLQ3NNj/MRApNMOtLIAFMNkZMRApMLOFMMk/LKkBLNkJOV5NMRRxPH4ZLVidLP4VVViZMJiNMOlZLVi/LJ6RLM57KUidOOyZJGiikcG"];return Pl=function(){return e},Pl()}async function Yh(e,t,n){let o=Cl,i=await e[o(4)](o(2),{system:YA,user:o(6)+t,...n?{signal:n}:{}});return qA(i[o(0)])}function fn(e,t){e=e-0;let n=Pl(),o=n[e];if(fn.sLepLJ===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};fn.TPTWLA=i,fn.iYuNay={},fn.sLepLJ=!0}let r=n[0];fn.inDmHY!==r&&(fn.iYuNay={},fn.inDmHY=r);let s=fn.iYuNay[e];return s===void 0?(o=fn.TPTWLA(o),fn.iYuNay[e]=o):o=s,o}var qh=50,ZA=10;async function Zh(e,t,n){let o=t.split(`
|
|
251
|
-
`),i=
|
|
252
|
-
`),c=await Yh(e,a,n);if(c.found&&c.line!==null)return{line:Math.min(Math.max(c.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 ac(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(a){o[s]={index:s,ok:!1,error:a}}}});return await Promise.all(r),o}var Wt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mn=e=>Array.isArray(e);function Tl(e){let t=new Map;if(!mn(e))return t;for(let n of e){if(!Wt(n))continue;let o=n.actor_id??n.location_id??n.prop_id;typeof o=="string"&&t.set(o,n)}return t}function WA(e){let t=[],n=(o,i)=>{!Wt(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 mn(e.episodes)?e.episodes:[])if(!(!Wt(o)||!mn(o.scenes))){for(let i of o.scenes)if(Wt(i)){n(i.location,"location_id");for(let r of mn(i.actors)?i.actors:[])n(r,"actor_id");for(let r of mn(i.props)?i.props:[])n(r,"prop_id");for(let r of mn(i.actions)?i.actions:[])Wt(r)&&n(r.speaker,"actor_id")}}return t}function XA(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 cc(e){if(!Wt(e))throw new Error("govern expects a script object");let t=JSON.parse(JSON.stringify(e));for(let p of mn(t.episodes)?t.episodes:[])if(!(!Wt(p)||!mn(p.scenes)))for(let l of p.scenes){if(!Wt(l))continue;let f=mn(l.actors)?l.actors.filter(Wt):[],u=new Set(f.map(h=>h.actor_id).filter(h=>typeof h=="string"));for(let h of mn(l.actions)?l.actions:[])!Wt(h)||!Wt(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=Tl(t.actors),o=Tl(t.locations),i=Tl(t.props),r=new Map([...n,...o,...i]),s=WA(t),a=new Map;for(let p of s){if(p.explicit===void 0)continue;a.has(p.assetId)||a.set(p.assetId,new Map);let l=a.get(p.assetId);l.set(p.explicit,(l.get(p.explicit)??0)+1)}let c=new Map;for(let[p,l]of r){let f=(mn(l.states)?l.states:[]).filter(Wt),u=new Map,h=XA(f,a.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,c.set(p,u)}let d=new Map;for(let p of s){let l=c.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 Wh=gn;function gn(e,t){e=e-0;let n=Vl(),o=n[e];if(gn.vcGzia===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};gn.alaGPc=i,gn.IPZchV={},gn.vcGzia=!0}let r=n[0];gn.cEXTRr!==r&&(gn.IPZchV={},gn.cEXTRr=r);let s=gn.IPZchV[e];return s===void 0?(o=gn.alaGPc(o),gn.IPZchV[e]=o):o=s,o}var ek=Wh(6);async function Xh(e,t,n,o){let i=Wh;return(await e[i(4)](i(2),{system:ek,user:i(0)+t+i(3)+n,...o?{signal:o}:{}}))[i(5)][i(1)]()}function Vl(){let e=["5OQk5lIl6z2Iia","DhjPBq","Aw5Nzxn0lMfYyY1ZDw1Tyxj5","ioEAHoMaKoADOEwjP+AdHEA1K+E8QEAiKos4GoAUTEEVH+EROoAIL+AMGIGYmddIGjmZmJaG5A2xloI/NUI0R+AiKoAUTsZKUi3OPOhPGjdPM4BNVzFLIjCPoGOk","z2vUzxjHDgvuzxH0","Dgv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ues"],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"]}}}}}},$l={type:"array",items:{type:"object",required:["asset_id","state_id"],additionalProperties:!1,properties:{asset_id:{type:"string"},state_id:{type:["string","null"]}}}},IT={type:"object",required:["scenes"],additionalProperties:!1,properties:{scenes:{type:"array",items:{type:"object",required:["scene_id"],additionalProperties:!1,properties:{scene_id:{type:"string"},actors:{...$l,items:{type:"object",required:["actor_id","state_id"],additionalProperties:!1,properties:{actor_id:{type:"string"},state_id:{type:["string","null"]}}}},locations:{...$l,items:{type:"object",required:["location_id","state_id"],additionalProperties:!1,properties:{location_id:{type:"string"},state_id:{type:["string","null"]}}}},props:{...$l,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"]}}}}}}}}},iy={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"}}},ry={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:iy}}},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"}}},tk={type:"string",enum:["actor","location","prop"]},sy={type:"string",description:"\u72B6\u6001\u540D\u7B80\u6D01\u6982\u62EC\u53EF\u533A\u5206\u7684\u9636\u6BB5\u5916\u89C2\uFF1B\u5F15\u7528\u65F6\u9010\u5B57\u4F7F\u7528\u767B\u8BB0\u540D\uFF0C\u8BE6\u7EC6\u5916\u89C2\u5199\u5728 description"},ey={type:"string",minLength:5,pattern:"^[0-9]{2}:[0-5][0-9](\\.[0-9]{1,3})?$",description:"\u5FC5\u586B\u3002\u672C\u955C\u5934\u6216\u58F0\u97F3\u771F\u6B63\u5F00\u59CB\u7684\u539F\u7247\u65F6\u95F4\uFF0C\u4F7F\u7528 MM:SS\uFF0C\u53EF\u4FDD\u7559\u539F\u7247\u4F9D\u636E\u652F\u6301\u7684 1\u20133 \u4F4D\u5C0F\u6570\uFF0C\u5982 00:03.240\u3002\u53EA\u6709\u6574\u79D2\u4F9D\u636E\u65F6\u5199\u6574\u79D2\uFF0C\u4E0D\u8865\u9020\u5C0F\u6570\u3002SS \u4E3A 00\u201359\uFF0C\u6574\u5206\u949F\u5199\u4E0B\u4E00\u5206\u949F\u7684 :00"},ty={type:"object",required:["name","description"],additionalProperties:!1,properties:{name:sy,description:{type:"string",description:"\u8BE5\u8D44\u4EA7\u6B64\u9636\u6BB5\u53EF\u590D\u73B0\u7684\u5916\u89C2\uFF0C\u975E\u7A7A\u3002\u4EBA\u7269\u8BB0\u5F55\u8138\u5F62\u3001\u4F53\u6001\u3001\u80A4\u51B5\u3001\u5E74\u9F84\u5916\u89C2\u3001\u5986\u53D1\u3001\u53EF\u8FA8\u58F0\u7EBF\u4E0E\u6301\u7EED\u670D\u88C5\u6574\u4F53\u9020\u578B\uFF0C\u5199\u660E\u53EF\u89C1\u989C\u8272\u3001\u6750\u8D28\u8868\u73B0\u3001\u7248\u578B\u3001\u53E0\u7A7F\u548C\u6301\u7EED\u635F\u4F24\uFF1B\u540C\u8863\u670D\u4E0B\u5B9E\u9645\u4E0D\u540C\u7684\u8138\u5F62\u4F53\u6001\u5206\u522B\u5EFA\u72B6\u6001\u3002\u72EC\u7ACB\u53D6\u653E\u3001\u6301\u6709\u6216\u7A7F\u6234\u64CD\u4F5C\u5BF9\u8C61\u7684\u5B8C\u6574\u5916\u89C2\u5F52 prop\uFF0C\u6301\u6709\u3001\u4F69\u6234\u3001\u6458\u4E0B\u3001\u6570\u91CF\u4E0E\u4F4D\u7F6E\u5173\u7CFB\u5F52 Action\uFF0C\u4EBA\u7269 state \u4E0E\u9053\u5177\u5171\u540C\u590D\u73B0\u573A\u666F\u3002\u906E\u6321\u6216\u672A\u786E\u8BA4\u90E8\u4F4D\u4FDD\u7559\u672A\u77E5\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\uFF1B\u52A8\u4F5C\u3001\u59FF\u6001\u3001\u60C5\u7EEA\u548C\u5267\u60C5\u8BC4\u4EF7\u5F52\u6B63\u6587"}}},ny={type:"object",description:"\u753B\u50CF\u5B57\u6BB5\u586B\u7A7A\u5B57\u7B26\u4E32\uFF0Cpersistent_marks \u586B\u7A7A\u6570\u7EC4\uFF1B\u5168\u90E8\u5916\u8C8C\u3001\u8EAB\u4F53\u6807\u8BB0\u4E0E\u53EF\u8FA8\u58F0\u7EBF\u5199\u5165\u5404\u9636\u6BB5\u5B8C\u6574 state\u3002",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"},apparent_age:{type:"string"},face_shape:{type:"string"},brows_eyes:{type:"string"},nose:{type:"string"},mouth:{type:"string"},skin_features:{type:"string"},hair:{type:"string"},build:{type:"string"},persistent_marks:{type:"array",items:{type:"string"}},voice:{type:"string"}}},ay={type:"object",required:["synopsis","scenes","registry_delta","open_threads"],additionalProperties:!1,properties:{synopsis:{type:"string",description:"\u672C\u96C6\u5267\u60C5\u6897\u6982\uFF0C\u6309\u53D1\u751F\u987A\u5E8F\uFF0C200-300 \u5B57\u7EAF\u6587\u672C"},scenes:{type:"array",minItems:1,description:"\u672C\u96C6\u6240\u6709\u573A\u666F\u5355\u5143\uFF0C\u6309\u65F6\u95F4\u987A\u5E8F\u6392\u5217\u3002\u573A\u5185\u5C3D\u91CF\u5FE0\u5B9E\u8FD8\u539F\u539F\u7247\u5206\u955C\uFF1A\u6BCF\u6B21\u5207\u955C\u3001\u8FDE\u7EED\u955C\u5934\u5185\u7684\u6444\u5F71\u53D8\u5316\u3001\u53EF\u89C1\u8868\u6F14\u548C\u58F0\u97F3\u4E8B\u4EF6\u6309\u5B9E\u9645\u65F6\u95F4\u4EA4\u9519\u4FDD\u7559\uFF0C\u91CD\u590D\u955C\u5934\u4E5F\u4E0D\u53BB\u91CD\uFF1B\u5730\u70B9\u3001\u660E\u663E\u65F6\u6BB5\u6216\u53D9\u4E8B\u7EBF\u53D8\u5316\u65F6\u62C6\u573A\uFF0C\u666E\u901A\u5207\u955C\u4E0D\u5355\u72EC\u62C6 scene\uFF1B\u540C\u4E00\u8FDE\u7EED\u573A\u5185\u7684\u4EBA\u7269\u9020\u578B\u53D8\u5316\u4FDD\u7559\u5728\u540C\u4E00\u573A\uFF1B\u8DE8\u5730\u70B9\u8499\u592A\u5947\u62C6\u6210\u591A\u4E2A\u77ED\u573A",items:{type:"object",required:["space","time","timeRange","location","characters","props","shots","voices"],additionalProperties:!1,properties:{space:{type:"string",description:"\u5185\u666F\u586B\u300C\u5185\u300D/\u5916\u666F\u586B\u300C\u5916\u300D\uFF1B\u4E0D\u786E\u5B9A\u586B\u7A7A\u4E32"},time:{type:"string",enum:["\u65E5","\u591C","\u6668","\u660F"],description:"\u672C\u573A\u5FC5\u987B\u9009\u62E9\u4E00\u4E2A\u65F6\u6BB5\uFF1A\u767D\u5929/\u65E5\u95F4\u586B\u300C\u65E5\u300D\uFF0C\u591C\u665A/\u591C\u95F4\u586B\u300C\u591C\u300D\uFF0C\u6E05\u6668/\u9ECE\u660E\u586B\u300C\u6668\u300D\uFF0C\u9EC4\u660F/\u508D\u665A\u586B\u300C\u660F\u300D\u3002\u7ED3\u5408\u7167\u660E\u3001\u4F5C\u606F\u3001\u5929\u7A7A\u548C\u5267\u60C5\u4E0A\u4E0B\u6587\u5224\u65AD\uFF0C\u4E0D\u5F97\u7559\u7A7A"},timeRange:{type:"string",description:"\u672C\u573A\u8D77\u6B62\u65F6\u95F4 MM:SS-MM:SS\uFF0C\u53EF\u4FDD\u7559\u539F\u7247\u4F9D\u636E\u652F\u6301\u7684 1\u20133 \u4F4D\u5C0F\u6570\uFF1BSS \u4E3A 00\u201359\uFF0C\u6574\u5206\u949F\u5199\u4E0B\u4E00\u5206\u949F\u7684 :00"},location:{type:"string",description:"\u672C\u573A\u552F\u4E00\u7A33\u5B9A\u4E3B\u7A7A\u95F4\u5730\u70B9\u540D\uFF0C\u6CBF\u7528\u89C4\u8303\u540D\uFF1B\u5BA2\u5385/\u5367\u5BA4/\u536B\u751F\u95F4/\u5927\u5385/\u5E7F\u573A/\u821E\u53F0/\u540E\u53F0\u5206\u522B\u5EFA\u5730\u70B9\uFF0C\u76F8\u5173\u7A7A\u95F4\u7528\u300E\u8C6A\u5B85\xB7\u5BA2\u5385\u300F\u5F0F\u547D\u540D"},characters:{type:"array",description:"\u672C\u573A\u5728\u573A\u7684\u5177\u4F53\u5355\u4EBA\u89D2\u8272\uFF08\u7FA4\u4F17\u4E0D\u5217\uFF09\u3002\u540C\u4E00\u89D2\u8272\u53EA\u80FD\u51FA\u73B0\u4E00\u6B21\uFF1B\u5176 states \u586B\u672C\u573A\u51FA\u73B0\u8FC7\u7684\u5168\u90E8\u7A33\u5B9A\u9020\u578B/\u72B6\u6001\u96C6\u5408",items:{type:"object",required:["name","states"],additionalProperties:!1,properties:{name:{type:"string",description:"\u89D2\u8272\u89C4\u8303\u540D"},states:{type:"array",items:sy,description:"\u672C\u573A\u8BE5\u89D2\u8272\u51FA\u73B0\u8FC7\u7684\u5168\u90E8\u5916\u8C8C\u9636\u6BB5\u4E0E\u9020\u578B\u72B6\u6001\u540D\u96C6\u5408\uFF0C\u9010\u5B57\u5F15\u7528\u5DF2\u6709\u767B\u8BB0\u540D\u6216\u672C\u6B21\u65B0\u5EFA\u540D\u3002\u9636\u6BB5\u548C\u9020\u578B\u5747\u76F8\u540C\u624D\u6CBF\u7528\u5DF2\u6709\u540D\uFF1B\u65E0\u6CD5\u786E\u8BA4\u72B6\u6001\u65F6\u586B\u7A7A\u6570\u7EC4\u3002\u540C\u4E00\u89D2\u8272\u4E00\u6761\u8BB0\u5F55\uFF0C\u56DE\u5FC6\u53CA\u573A\u5185\u53D8\u5316\u5305\u542B\u5B9E\u9645\u51FA\u73B0\u7684\u5404\u9636\u6BB5\u72B6\u6001"}}}},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:ey,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:ey,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","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:tk,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"]},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:"\u4EBA\u7269\u53EA\u5199\u8EAB\u4EFD\u79F0\u8C13\u4E0E\u4EBA\u7269\u5173\u7CFB\uFF0C\u5730\u70B9/\u9053\u5177\u5199\u7528\u9014\uFF1B\u5916\u8C8C\u5F52state\uFF0C\u884C\u4E3A\u548C\u5267\u60C5\u8BC4\u4EF7\u5F52\u6B63\u6587\uFF0C\u975E\u7A7A"},states:{type:"array",items:ty,description:"\u672C\u96C6\u8BE5\u5B9E\u4F53\u51FA\u73B0\u7684\u9636\u6BB5\u72B6\u6001\u3002\u9996\u6B21\u4EBA\u7269\u767B\u8BB0\u4E5F\u4FDD\u5B58\u5F53\u524D\u5B8C\u6574\u5916\u8C8C\u3001\u53EF\u8FA8\u58F0\u7EBF\u4E0E\u670D\u9970\uFF1B\u6BCF\u9879\u7ED9\u51FA\u53EF\u533A\u5206\u7684\u9636\u6BB5\u72B6\u6001\u540D\u53CA\u6765\u6E90\u652F\u6301\u7684\u8BE6\u7EC6\u63CF\u8FF0"},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:"\u586B\u7A7A\u6570\u7EC4\uFF1B\u4EBA\u7269\u8BC6\u522B\u6240\u9700\u7684\u53EF\u89C1\u7279\u5F81\u4E0E\u58F0\u7EBF\u4FDD\u5B58\u5728\u5BF9\u5E94 state"},identity_profile_patch:ny,identity_revision:{type:"object",description:"\u65E2\u6709\u753B\u50CF\u6216\u951A\u70B9\u975E\u7A7A\u65F6\u63D0\u4F9B\uFF1Aprofile \u4E2D\u5B57\u7B26\u4E32\u5168\u90E8\u4E3A\u7A7A\u3001persistent_marks \u548C recognition_anchors \u5747\u4E3A\u7A7A\u6570\u7EC4\uFF0C\u6574\u4F53\u6E05\u7A7A\u65E7\u753B\u50CF\u4E0E\u951A\u70B9\uFF1B\u6709\u8BC1\u636E\u7684\u4E8B\u5B9E\u8865\u5165\u9002\u7528\u7684 add_states\uFF0Crole \u5B8C\u6574\u7ED9\u51FA\u8EAB\u4EFD\u5173\u7CFB\uFF0C\u663E\u5F0F\u7A7A\u4E32\u8868\u793A\u6E05\u9664\u65E7 role\u3002\u65E0\u9700\u6E05\u7406\u65F6\u7701\u7565\u3002",required:["profile","recognition_anchors"],additionalProperties:!1,properties:{profile:ny,recognition_anchors:{type:"array",items:{type:"string"}}}},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:"\u4EBA\u7269\u5DF2\u786E\u8BA4\u7684\u8EAB\u4EFD\u79F0\u8C13\u4E0E\u5173\u7CFB\uFF1B\u5730\u70B9/\u9053\u5177\u5199\u7528\u9014\u3002\u63D0\u4F9B identity_revision \u65F6\u586B\u5199\u5B8C\u6574\u8EAB\u4EFD\u5173\u7CFB\uFF0C\u7A7A\u4E32\u6E05\u9664\u65E7 role\uFF1B\u666E\u901A\u589E\u91CF\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:ty,description:"\u672C\u96C6\u65B0\u72B6\u6001\uFF0C\u4EE5\u53CA\u6709\u8BC1\u636E\u8865\u5168\u7684\u65E7\u72B6\u6001\u3002\u6BCF\u9879\u72EC\u7ACB\u5199\u5168\u8BE5\u9636\u6BB5\u5916\u8C8C\u3001\u58F0\u7EBF\u4E0E\u51C6\u786E\u670D\u9970\uFF0C\u5305\u62EC\u8DE8\u9636\u6BB5\u76F8\u540C\u7279\u5F81\u3002\u65E2\u6709\u9636\u6BB5\u9010\u5B57\u6CBF\u7528\u5176 name\uFF1B\u4EC5\u90E8\u5206\u5F15\u7528\u5F97\u5230\u65B0\u8BC1\u636E\u65F6\uFF0C\u65B0\u5EFA\u72B6\u6001\u5E76\u7ED1\u5B9A\u5DF2\u786E\u8BA4\u573A\u666F\uFF0C\u5176\u4F59\u8303\u56F4\u4FDD\u7559\u5F85\u6838"}}}},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"}}}}}}}},cy={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:iy}}}}};var H=hn;function hn(e,t){e=e-0;let n=Dl(),o=n[e];if(hn.AowUYu===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};hn.vGSHGD=i,hn.ykrKeL={},hn.AowUYu=!0}let r=n[0];hn.qbkWqr!==r&&(hn.ykrKeL={},hn.qbkWqr=r);let s=hn.ykrKeL[e];return s===void 0?(o=hn.vGSHGD(o),hn.ykrKeL[e]=o):o=s,o}var nk=[H(37),H(84),H(100),H(83),H(39),"",H(71),H(55),H(1),H(47),H(10),H(70),H(56),H(46),H(92),H(2),H(61),H(24),H(82),H(51),H(79),H(88),H(58),H(30),H(65),H(73),H(27),H(59),H(86)][H(33)](`
|
|
253
|
-
`);function
|
|
254
|
-
`)}async function
|
|
255
|
-
`);else n+='\\"';continue}n+=r}return n}function ak(e,t){let n=H,o=r=>JSON[n(101)](r),i;try{i=o(e)}catch(r){let s=sk(e);if(s===e)throw new De(t+n(89)+(r instanceof Error?r[n(20)]:String(r)));try{i=o(s)}catch(a){throw new De(t+n(26)+(a instanceof Error?a[n(20)]:String(a)))}}if(!Array[n(13)](i))if(n(6)===n(54))_0x291b73=_0x1aa471(_0x238c2b);else throw new De(t+n(91)+typeof i);return i}function Ri(e,t){let n=H;if(e==null)return[];if(Array[n(13)](e))return e;if(typeof e===n(9)){let o=e[n(50)]();return o?ak(o,t):[]}throw new De(t+n(19)+typeof e)}var ck=/[((]([^))]*)[))]?/;function Dl(){let e=["u2vYAwfSrgvSDgftAgfWzuvYCM9Y","icdcTYbHBgLHC2vZid0G6l+z5Q616yEm6k+L5A6E5l2t55QekIRMIydMNiNLHBBKU5BLJ6VMS5uQkU+8JoMaKos4QUwnLEwiL++8IoE6R+wqJE+8JowiQ+w4PUoaJU+8Iow/G++8IEoaJ+oaJU+8MUoaJ+oaJU+8JoMTGUIVREoaJ+I/MEEXU+wVUEEzVs/MG4xNU6RMOiFORRdVViNVVjRLIkVLKi3JGihOR5hLKi3JGihLIy3KUjBLKi3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oaGIOQ5y+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/KVjRNHACGBwvYz2vZicSGywXPyxnLCYdMIORMRApMLOFVViJLR7NNMB3OR7tOR53KURRJGihML4hNMB3MLOFMNkZVViNPH4ZNMOtOV5NKUPVLHPN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ZMMzOV6kkR5Q+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 Dl=function(){return e},Dl()}function Gl(e){let t=H,n=po(e),o=ck[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 Mi=e=>Gl(po(e))[H(32)];function dk(e){let t=H;if(Ni(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 De(t(53)+(i instanceof Error?i[t(20)]:String(i)))}if(!Ni(o)){if(t(3)===t(3))throw new De(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 Ls(e){let t=H,n=Jh(),o=dk(e);if(!o)return n;for(let i of Ri(o[t(25)],t(25))){if(!Ni(i))continue;let r=po(i[t(52)]),{name:s,aliases:a}=Gl(po(i[t(32)]));if(!ik[t(62)](r)||!s)continue;let c=dc(i[t(15)],t(81)+s+t(93)),d=rk(i[t(75)],t(81)+s+t(43)),p=[...a];for(let f of Ri(i[t(16)],t(68))){let{name:u,aliases:h}=Gl(po(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:c,aliases:l,defaultLook:d})}for(let i of Ri(o[t(57)],t(57))){if(!Ni(i))continue;let r=Mi(i[t(11)]),s=Mi(i[t(80)]);r&&s&&r!==s&&n[t(57)][t(76)]({from:r,into:s})}for(let i of Ri(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(!Ni(i))continue;let r=Mi(i[t(17)]),s=Mi(i[t(32)]);if(!r||!s)continue;let a=[s,...Ri(i[t(16)],t(94))[t(63)](Mi)[t(18)](Boolean)];n[t(42)][t(76)]({entity:r,names:a,description:dc(i[t(15)],t(7)+r+"."+s+t(93))})}}for(let i of Ri(o[t(85)],t(85))){if(!Ni(i))continue;let r=po(i[t(87)]),s=Mi(i[t(17)]),a=Mi(i[t(103)]);r&&s&&a&&n[t(85)][t(76)]({scene:r,entity:s,look:a})}return n[t(96)]=Ri(o[t(96)],t(96))[t(63)](po)[t(18)](Boolean),n[t(97)]=po(o[t(97)]),n}var nt=yn,pk=[nt(1),nt(29),nt(18),nt(32),nt(0),nt(7),nt(15),nt(8),nt(3)][nt(21)](`
|
|
256
|
-
`);function
|
|
251
|
+
`);return d.trim()===""?!1:(i.push({index:i.length,core_line_start:r,core_line_end:c,text:d}),r=c,s=0,!0)};for(let c=0;c<o.length;c++){let d=o[c],l=s+(c===r?0:1)+d.length;d.trim()!==""&&c>r&&l>n&&a(c)?s=d.length:s=l}return a(o.length),i}var Bh=["episode","scene","action","dialogue","inner_thought","transition","note"];var VA={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 Ko(e){if(typeof e!="string")return;let t=e.normalize("NFC").replace(/\s+/g,"").trim().toLocaleLowerCase();return VA[t]}var Ee=class extends Error{constructor(n,o){super(`line ${o}: ${n}`);this.line=o}line};function Sr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ln(e,t,n){for(let o of Object.keys(e))if(!t.includes(o))throw new Ee(`unknown field '${o}'`,n)}function $A(e,t){if(!Sr(e))throw new Ee("missing source",t);ln(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 Ee("source needs integer chunk/line_start/line_end",t);if(o>=i)throw new Ee("source line_start must be < line_end",t);return{chunk:n,line_start:o,line_end:i}}function _r(e,t,n){let o=e[t];if(typeof o!="string"||o==="")throw new Ee(`'${t}' must be a non-empty string`,n);return o}function jo(e,t,n){if(!(t in e)||e[t]===void 0)return;let o=e[t];if(typeof o!="string"||o==="")throw new Ee(`'${t}' must be a non-empty string`,n);return o}function Jh(e,t,n){if(!Array.isArray(e))throw new Ee(`'${t}' must be an array`,n);return e.map(o=>{if(!Sr(o))throw new Ee(`'${t}' entries must be objects`,n);ln(o,["name","state"],n);let i={name:_r(o,"name",n)},r=jo(o,"state",n);return r!==void 0&&(i.state=r),i})}function DA(e,t){if(!Sr(e))throw new Ee("dialogue/inner_thought needs a speaker",t);if("kind"in e){ln(e,["kind","label"],t);let r=e.kind;if(typeof r!="string"||!jn.includes(r))throw new Ee(`speaker.kind must be one of ${jn.join("|")}`,t);let s={kind:r},a=jo(e,"label",t);return a!==void 0&&(s.label=a),s}ln(e,["name","state"],t);let n=_r(e,"name",t);if(!/[\p{L}\p{N}]/u.test(n))throw new Ee("speaker.name must contain a letter or number",t);let o={name:n},i=jo(e,"state",t);return i!==void 0&&(o.state=i),o}function GA(e,t){let n=e.kind;if(typeof n!="string"||!Bh.includes(n))throw new Ee(`unknown or missing kind '${String(n)}'`,t);let o=$A(e.source,t);switch(n){case"episode":{ln(e,["kind","episode","title","source"],t);let i=e.episode;if(typeof i!="number"||!Number.isInteger(i))throw new Ee("episode must be an integer",t);let r={kind:n,episode:i,source:o},s=jo(e,"title",t);return s!==void 0&&(r.title=s),r}case"scene":{ln(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 Ee("scene must be an integer",t);i.scene=e.scene}if("environment"in e&&e.environment!==void 0){if(!Sr(e.environment))throw new Ee("environment must be an object",t);ln(e.environment,["space","time"],t);let r={},s=jo(e.environment,"space",t);s!==void 0&&(r.space=s);let a=jo(e.environment,"time",t);if(a!==void 0){let c=Ko(a);if(!c)throw new Ee("environment.time must be day|night|dawn|dusk or a recognized Chinese equivalent",t);r.time=c}i.environment=r}if("location"in e&&e.location!==void 0){if(!Sr(e.location))throw new Ee("location must be an object",t);ln(e.location,["name","state"],t);let r={name:_r(e.location,"name",t)},s=jo(e.location,"state",t);s!==void 0&&(r.state=s),i.location=r}return"actors"in e&&e.actors!==void 0&&(i.actors=Jh(e.actors,"actors",t)),"props"in e&&e.props!==void 0&&(i.props=Jh(e.props,"props",t)),i}case"action":case"transition":{ln(e,["kind","content","source"],t);let i=_r(e,"content",t);return{kind:n,content:i,source:o}}case"dialogue":case"inner_thought":{ln(e,["kind","speaker","content","emotion","source"],t);let i=_r(e,"content",t),r=DA(e.speaker,t),s={kind:n,speaker:r,content:i,source:o},a=jo(e,"emotion",t);return a!==void 0&&(s.emotion=a),s}case"note":{ln(e,["kind","content","category","source"],t);let i=_r(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 Ee("note.category must be author_note|format_note|unclassified",t);r.category=s}return r}default:throw new Ee(`unhandled kind '${n}'`,t)}}function Ms(e,t=0){let n=[],o=e.split(`
|
|
252
|
+
`);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 Ee("invalid JSON",i+1+t)}if(!Sr(s))throw new Ee("record must be a JSON object",i+1+t);n.push(GA(s,i+1+t))}return n}var oe=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),Oi=e=>{let t=/[((]/.exec(e);return!t||t.index===0?e:e.slice(0,t.index).trim()},BA=e=>e.startEp===e.endEp?`\u7B2C${e.startEp}\u96C6`:`\u7B2C${e.startEp}\u96C6\u2013\u7B2C${e.endEp}\u96C6`,Rl=e=>e.startEp===e.endEp?`\u7B2C${e.startEp}\u96C6`:`\u7B2C${e.startEp}\u96C6\u2013\u7B2C${e.endEp}\u96C6`,Hh=()=>({newEntities:[],merges:[],looks:[],lookChanges:[],subEvents:[],summary:""}),Qh=()=>({entities:[],lookChanges:{},recent:[],synopsis:[]}),Ml={recentEpisodes:6,synopsisChars:3500,arcFold:10},JA=1e4;function Fh(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 Yh(e,t=JA){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 zA={actor:"\u4EBA\u7269",location:"\u573A\u666F",prop:"\u9053\u5177"};function qt(e,t){let n=oe(t);return e.entities.find(o=>oe(o.canonical)===n||o.aliases.some(i=>oe(i)===n))}var zh=(e,t)=>{oe(t)!==oe(e.canonical)&&!e.aliases.some(n=>oe(n)===oe(t))&&e.aliases.push(t)},KA=["\u5E74\u8F7B","\u5E74\u8001","\u5E74\u5E7C","\u5E74\u5C11","\u4E2D\u5E74","\u9752\u5E74","\u5C11\u5E74","\u8001\u5E74","\u5E7C\u5E74","\u8001","\u5C0F","\u5927","\u5C11","\u5E7C"];function jA(e,t){let n=oe(e),o=oe(t);if(n===o||!n.includes(o))return!1;let i=n.replace(o,"").trim();return i.length>0&&!KA.some(r=>i===r||i.startsWith(r))}function HA(e){let t=e.filter(n=>e.some(o=>o!==n&&jA(n,o)));return t.length?t.reduce((n,o)=>o.length>n.length?o:n):e[0]}var Kh=["\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"],QA=["\u4F17\u4EBA","\u7FA4\u4F17","\u6C11\u4F17","\u89C2\u4F17","\u4EBA\u7FA4","\u4EBA\u4EEC","\u5927\u5BB6","\u767E\u59D3","\u5B98\u5175"],FA=/^(?:一群|一众|全体|所有|几名|数名|多名|[0-9零一二两三四五六七八九十百千]+名?)/;function ut(e){let t=oe(e).replace(/[0-9零一二两三四五六七八九十百千]+名?$/,"").trim();return t?t.endsWith("\u4EEC")||Kh.includes(t)||QA.some(n=>t.endsWith(n))?!0:FA.test(t)&&Kh.some(n=>t.endsWith(n)):!1}function Ho(e,t){let n=Oi(t);return qt(e,n)?.canonical??n}function YA(e,t){let n=oe(t);return e.looks.find(o=>oe(o.name)===n||o.aliases.some(i=>oe(i)===n))?.name??t}var qA=["\u5E38\u6001","\u65E5\u5E38","\u5E73\u65F6","\u57FA\u7840","\u666E\u901A"];function Nl(e){if(e.looks.length!==0)return(e.looks.find(t=>qA.some(n=>t.name.includes(n)))??e.looks[0]).name}function Ol(e,t,n,o){let i=oe(Oi(n));if(i)return e.entities.find(r=>r.kind===t&&r!==o&&(oe(r.canonical)===i||r.aliases.some(s=>oe(s)===i)))}function jh(e){let t=[e.canonical,...e.aliases],n=HA(t);oe(n)!==oe(e.canonical)&&(e.canonical=n,e.aliases=t.filter(o=>oe(o)!==oe(n)))}function Ns(e,t,n,o=n){for(let r of t.newEntities){let s=Oi(r.name);if(!s)continue;let a=Ol(e,r.kind,s);if(!a){let d=[];for(let p of r.aliases){let l=Oi(p);l&&oe(l)!==oe(s)&&!Ol(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=Oi(d);p&&!Ol(e,r.kind,p,a)&&zh(a,p)}!a.description&&r.description&&(a.description=r.description);let c=a.looks.find(d=>oe(d.name)===oe(r.defaultLook.name));c?c.description=r.defaultLook.description:a.looks.unshift({name:r.defaultLook.name,aliases:[],description:r.defaultLook.description}),jh(a)}for(let{from:r,into:s}of t.merges){let a=Oi(s);if(!a)continue;let c=qt(e,a);if(!c)continue;let d=Oi(r);!d||oe(d)===oe(c.canonical)||qt(e,d)||(zh(c,d),jh(c))}for(let{entity:r,names:s,description:a}of t.looks){let c=qt(e,r);if(!c)continue;let d=s.map(f=>f.trim()).filter(Boolean);if(!d.length)continue;let p=d[0],l=c.looks.find(f=>oe(f.name)===oe(p)||d.some(u=>f.aliases.some(h=>oe(h)===oe(u))));if(l){a&&(l.description=a);for(let f of d)oe(f)!==oe(l.name)&&!l.aliases.some(u=>oe(u)===oe(f))&&l.aliases.push(f)}else c.looks.push({name:p,aliases:d.slice(1),description:a})}for(let r of t.lookChanges){let s=r.scene.trim(),a=Ho(e,r.entity),c=r.look.trim();if(!s||!a||!c)continue;let d=qt(e,a),p=d?YA(d,c):c;(e.lookChanges[s]??=[]).push({entity:a,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=qt(e,r);s&&(s.lastSeen=o)}return e.recent.push({startEp:n,endEp:o,summary:t.summary,subEvents:t.subEvents}),e}var WA=e=>e.summary.length+e.subEvents.reduce((t,n)=>t+n.length,0);function qh(e,t=Ml){for(;e.recent.length>t.recentEpisodes||e.recent.length>1&&e.recent.reduce((n,o)=>n+WA(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 Ll(e,t=Ml){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 Wh(e,t,n=Ml){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 ZA=6;function sc(e,t){let n=i=>t===void 0||i.lastSeen>=t-ZA,o=["# \u8BBE\u5B9A"];for(let i of["actor","location","prop"]){let r=e.entities.filter(s=>s.kind===i);if(r.length){o.push(`## ${zA[i]}`);for(let s of r){let a=[...s.aliases.length?[`\u522B\u540D ${s.aliases.join("\u3001")}`]:[],...s.currentLook?[`\u5F53\u524D\u9020\u578B ${s.currentLook}`]:[]];if(o.push(`- ${s.canonical}\uFF5C${a.join("\uFF5C")}`),!!n(s)){s.description&&o.push(` \u7B80\u4ECB\uFF1A${s.description}`);for(let c of s.looks){let d=c.aliases.length?`${c.name}(=${c.aliases.join("=")})`:c.name;o.push(` \u9020\u578B ${d}${c.description?`\uFF1A${c.description}`:""}`)}}}}}if(e.synopsis.length){o.push("","# \u524D\u60C5");for(let i of e.synopsis)o.push(`- ${Rl(i)}\uFF1A${i.line}`)}if(e.recent.length){o.push("","# \u6700\u8FD1");for(let i of e.recent){o.push(`## ${BA(i)}`),i.summary.trim()&&o.push(`\u6897\u6982\uFF1A${i.summary.trim()}`);for(let r of i.subEvents)o.push(`- ${r}`)}}return o.join(`
|
|
253
|
+
`)}var XA=/(?:^|[,。!?;:、\s“”"'((])(他们|她们|它们|其中一人|另一个人|前者|后者|对方|有人|两人|他|她|它)(?!人)/;function Ir(e){let t=[],n=(o,i,r)=>{t.push({code:o,path:i,message:r})};return e.actors.forEach((o,i)=>{ut(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 a=`$.episodes[${i}].scenes[${s}]`;r.location===null&&n("production_location_missing",`${a}.location`,"production scene needs one stable location"),r.actions.forEach((c,d)=>{let p=`${a}.actions[${d}]`;if(c.type==="action"){let l=XA.exec(c.content);l&&n("production_action_pronoun",`${p}.content`,`action uses ambiguous reference ${l[1]}`)}})})}),t}var tt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ht=e=>Array.isArray(e),ac=e=>String(e).padStart(3,"0"),Ul=[{key:"actors",idField:"actor_id",prefix:"act"},{key:"locations",idField:"location_id",prefix:"loc"},{key:"props",idField:"prop_id",prefix:"prp"}];function cc(e){if(!tt(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=(c,d)=>{typeof d=="string"&&!i[c].has(d)&&(i[c].add(d),o[c].push(d))};for(let c of ht(t.episodes)?t.episodes:[])if(!(!tt(c)||!ht(c.scenes))){for(let d of c.scenes)if(tt(d)){tt(d.location)&&r("locations",d.location.location_id);for(let p of ht(d.actors)?d.actors:[])tt(p)&&r("actors",p.actor_id);for(let p of ht(d.props)?d.props:[])tt(p)&&r("props",p.prop_id);for(let p of ht(d.actions)?d.actions:[])tt(p)&&tt(p.speaker)&&r("actors",p.speaker.actor_id)}}for(let{key:c,idField:d}of Ul)for(let p of ht(t[c])?t[c]:[])tt(p)&&r(c,p[d]);for(let{key:c,prefix:d}of Ul)o[c].forEach((p,l)=>{n[c][p]=`${d}_${ac(l+1)}`});for(let{key:c,idField:d}of Ul){let p=(ht(t[c])?t[c]:[]).filter(tt),l=n[c],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 ht(u.states)?u.states:[]){if(!tt(w)||typeof w.state_id!="string"||w.state_id==="default")continue;let y=`st_${ac(++g)}`;n.states[w.state_id]=y,w.state_id=y}f.set(m,u)}t[c]=[...f.entries()].sort((u,h)=>u[0]<h[0]?-1:1).map(u=>u[1])}let s=0;(ht(t.episodes)?t.episodes:[]).forEach((c,d)=>{if(tt(c)){if(typeof c.episode_id=="string"){let p=`ep_${ac(d+1)}`;n.episodes[c.episode_id]=p,c.episode_id=p}for(let p of ht(c.scenes)?c.scenes:[])if(tt(p)&&typeof p.scene_id=="string"){let l=`scn_${ac(++s)}`;n.scenes[p.scene_id]=l,p.scene_id=l}}});let a=(c,d,p)=>{!tt(c)||typeof c[d]!="string"||(c[d]=n[p][c[d]]??c[d],typeof c.state_id=="string"&&n.states[c.state_id]&&(c.state_id=n.states[c.state_id]))};for(let c of ht(t.episodes)?t.episodes:[])if(!(!tt(c)||!ht(c.scenes))){for(let d of c.scenes)if(tt(d)){a(d.location,"location_id","locations");for(let p of ht(d.actors)?d.actors:[])a(p,"actor_id","actors");for(let p of ht(d.props)?d.props:[])a(p,"prop_id","props");for(let p of ht(d.actions)?d.actions:[])tt(p)&&a(p.speaker,"actor_id","actors")}}return{script:t,idMap:n}}import{createHash as ek}from"node:crypto";function Ls(e){let t=O(e).trim();if(!t.includes(":"))throw new S("Target invalid.",{exitCode:B,errorCode:"TARGET_INVALID",hint:"Use a concrete asset target.",data:{expected:["target: actor:<id>, location:<id>, or prop:<id>"],actual:[t||"<empty>"]}});let n=t.indexOf(":"),o=t.slice(0,n).trim(),i=t.slice(n+1).trim();if(!Af.has(o)||!i)throw new S("Target invalid.",{exitCode:B,errorCode:"TARGET_INVALID",hint:"Use actor, location, or prop with a non-empty id.",data:{expected:["target: actor:<id>, location:<id>, or prop:<id>"],actual:[t]}});return[o,i]}function Qo(){return{version:3,actor:{},location:{},prop:{},state:{},episode:{},scene:{},action:{}}}function Wt(e,t){let n=e.get(t);if(n===void 0)throw new Error(`Missing mapped ID for ${t}`);return n}function Ar(e,t=Qo(),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,R,C,N)=>{let M=C[R];if(M!==void 0){if(!$(I,M))throw new Error(`Invalid persisted ${I} ID for ${R}: ${M}`);if(N.has(M))throw new Error(`Duplicate persisted ${I} ID: ${M}`);return N.add(M),M}let K=ci(I,N);return N.add(K),C[R]=K,K},a=(I,R)=>n[I]?.[R]??R;for(let I of e.actors){let R=s("actor",a("actor",I.actor_id),o.actor,r.actor);i.actor.set(I.actor_id,R)}for(let I of e.locations){let R=s("location",a("location",I.location_id),o.location,r.location);i.location.set(I.location_id,R)}for(let I of e.props){let R=s("prop",a("prop",I.prop_id),o.prop,r.prop);i.prop.set(I.prop_id,R)}let c=new Map,d=(I,R,C)=>{let N=new Map,M=new Set,K=a(I,R),X=o.state[K]??{};o.state[K]=X;let Ke=C.map(se=>{let z;if(se.state_id==="default")z="default";else{let Nt=n.state?.[R]?.[se.state_id]??se.state_id,P=X[Nt];if(P!==void 0){if(!$("state",P))throw new Error(`Invalid persisted state ID for ${R}/${se.state_id}: ${P}`);if(M.has(P))throw new Error(`Duplicate persisted state ID on ${R}: ${P}`);z=P}else z=ci("state",M),X[Nt]=z}return M.add(z),N.set(se.state_id,z),{...se,state_id:z}});return c.set(R,N),Ke},p=(I,R)=>R===void 0?void 0:Wt(c.get(I)??new Map,R),l=e.actors.map(I=>({...I,actor_id:Wt(i.actor,I.actor_id),states:d("actor",I.actor_id,I.states)})),f=e.locations.map(I=>({...I,location_id:Wt(i.location,I.location_id),states:d("location",I.location_id,I.states)})),u=e.props.map(I=>({...I,prop_id:Wt(i.prop,I.prop_id),states:d("prop",I.prop_id,I.states)})),h=I=>{if("actor_id"in I){let R=p(I.actor_id,I.state_id);return{actor_id:Wt(i.actor,I.actor_id),...R===void 0?{}:{state_id:R}}}return I.label===void 0?{kind:I.kind}:{kind:I.kind,label:I.label}},m=I=>{if(I.includes(":")){let[C,N]=Ls(I);return Wt(C==="actor"?i.actor:C==="location"?i.location:i.prop,N)}let R=i.actor.get(I)??i.location.get(I)??i.prop.get(I);if(R===void 0)throw new Error(`Missing transition target mapping for ${I}`);return R},g=(I,R)=>{let C=s("action",R,o.action,r.action),N=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:C,type:I.type,content:I.content,speaker:h(I.speaker),...I.emotion===void 0?{}:{parenthetical:I.emotion},...N,...I.extend===void 0?{}:{extend:I.extend}}}return{action_id:C,type:I.type,content:I.content,...N,...I.extend===void 0?{}:{extend:I.extend}}},w=(I,R)=>[p(I,R??"default")??"default"],y=(I,R)=>{let C=new Map;for(let N of I){let M=Wt(i.actor,N.actor_id),K=C.get(M)??new Set;w(N.actor_id,N.state_id).forEach(X=>K.add(X)),C.set(M,K)}for(let N of R){if(N.speaker===void 0||!("actor_id"in N.speaker))continue;let M=N.speaker.actor_id,K=Wt(i.actor,M),X=C.get(K)??new Set;w(M,N.speaker.state_id).forEach(Ke=>X.add(Ke)),C.set(K,X)}return[...C].map(([N,M])=>({actor_id:N,state_ids:[...M].sort()}))},E=I=>{let R=new Map;for(let C of I){let N=Wt(i.prop,C.prop_id),M=R.get(N)??new Set;w(C.prop_id,C.state_id).forEach(K=>M.add(K)),R.set(N,M)}return[...R].map(([C,N])=>({prop_id:C,state_ids:[...N].sort()}))},_=new Set,x=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 R=n.episode?.[I.episode_id]??I.episode_id;_.add(R);let C=s("episode",R,o.episode,r.episode);return{...I,episode_id:C,scenes:I.scenes.map(N=>{let M=`${I.episode_id}/${N.scene_id}`,K=n.scene?.[M]??M;x.add(K);let X=s("scene",K,o.scene,r.scene),Ke=new Map;return{...N,scene_id:X,location:N.location===null?null:{location_id:Wt(i.location,N.location.location_id),state_ids:w(N.location.location_id,N.location.state_id)},actors:y(N.actors,N.actions),props:E(N.props),actions:N.actions.map((se,z)=>{let Nt=`${M}#${z}`,P=JSON.stringify(Nn(se)),pe=(Ke.get(P)??0)+1;Ke.set(P,pe);let Ae=ek("sha256").update(P).digest("hex"),Lt=n.action?.[Nt]??`${K}:action:${Ae}:${pe}`;return A.add(Lt),g(se,Lt)})}})}})},U=(I,R)=>{for(let C of Object.keys(I))R.has(C)||delete I[C]};U(o.actor,new Set(e.actors.map(I=>a("actor",I.actor_id)))),U(o.location,new Set(e.locations.map(I=>a("location",I.location_id)))),U(o.prop,new Set(e.props.map(I=>a("prop",I.prop_id)))),U(o.episode,_),U(o.scene,x),U(o.action,A);let v=[...e.actors.map(I=>({id:a("actor",I.actor_id),oldId:I.actor_id,states:I.states})),...e.locations.map(I=>({id:a("location",I.location_id),oldId:I.location_id,states:I.states})),...e.props.map(I=>({id:a("prop",I.prop_id),oldId:I.prop_id,states:I.states}))];U(o.state,new Set(v.map(I=>I.id)));for(let I of v)U(o.state[I.id]??{},new Set(I.states.map(R=>n.state?.[I.oldId]?.[R.state_id]??R.state_id)));return{script:b,identityMap:o}}import*as Pe from"node:fs";import*as Ri from"node:path";function Vn(e,t){let n=Ri.dirname(e);Pe.mkdirSync(n,{recursive:!0});let o=Ri.join(n,`.${Ri.basename(e)}.${process.pid}.tmp`),i=Pe.openSync(o,"w");try{Pe.writeFileSync(i,t),Pe.fsyncSync(i)}finally{Pe.closeSync(i)}Pe.renameSync(o,e)}function Pl(e,t){Vn(e,JSON.stringify(t,null,2)+`
|
|
254
|
+
`)}function Us(e){return JSON.parse(Pe.readFileSync(e,"utf-8"))}var yt=class{constructor(t){this.root=t}root;abs(t){return Ri.join(this.root,t)}ensure(){Pe.mkdirSync(this.root,{recursive:!0})}passDir(t){let n=this.abs(t);return Pe.mkdirSync(n,{recursive:!0}),n}readText(t){return Pe.readFileSync(this.abs(t),"utf-8")}writeText(t,n){Vn(this.abs(t),n)}writeJson(t,n){Pl(this.abs(t),n)}readJson(t){return Us(this.abs(t))}has(t){return Pe.existsSync(this.abs(t))}path(t){return this.abs(t)}clearError(t){let n=this.abs(t);Pe.existsSync(n)&&Pe.rmSync(n)}};function un(e,t){e=e-0;let n=Cl(),o=n[e];if(un.wCYmoh===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};un.ccSjUe=i,un.dKlJjl={},un.wCYmoh=!0}let r=n[0];un.sBhMJx!==r&&(un.dKlJjl={},un.sBhMJx=r);let s=un.dKlJjl[e];return s===void 0?(o=un.ccSjUe(o),un.dKlJjl[e]=o):o=s,o}var Y=un,tk=[Y(40),Y(37),Y(24),Y(75),Y(5),Y(21),"",Y(65),Y(13),Y(34),Y(62),"",Y(70),Y(35),Y(42),Y(27),Y(39),Y(43),Y(0),Y(68),Y(55),"",Y(77),Y(18),Y(58),Y(10),Y(11),Y(51),Y(59),Y(66),Y(8),Y(3),Y(76),"",Y(15),Y(4),Y(9),Y(6),Y(20),Y(14),Y(45),Y(48),Y(38),Y(54)][Y(74)](`
|
|
255
|
+
`);function nk(e){let t=Y,n=e[t(73)]===0?t(47):t(23);return[t(78),n,t(49),"",e[t(53)]][t(74)](`
|
|
256
|
+
`)}function dc(e,t){let n=Y;return new S(e,{exitCode:q,errorCode:n(12),hint:n(44),data:{actual:t}})}function ok(e){let t=Y;return typeof e!==t(29)||e===null||Array[t(46)](e)?!1:Object[t(61)](e)[t(1)]===1&&t(33)in e&&Array[t(46)](e[t(33)])}function Tl(e,t){let n=Y;if(!ok(e))throw dc(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 a=n;if(typeof s!==a(29)||s===null||Array[a(46)](s)||Object[a(26)](s,a(56))){if(a(72)!==a(30))throw new Ee(a(57),1);if(typeof _0x5a19bf!==a(29)||_0x5b66f6===null||_0x10f05d[a(46)](_0x23b052)||_0x733702[a(26)](_0x1cb121,a(56)))throw new _0x3dba95(a(57),1);return _0x5020a9[a(32)]({..._0x80cb75,source:_0x442727})}return JSON[a(32)]({...s,source:o})})[n(74)](`
|
|
257
|
+
`);i=Ms(r)}catch(r){throw r instanceof Ee?dc(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)]):dc(n(19)+t[n(73)]+n(69),[n(2)]);return i}function Cl(){let e=["lsdOVAZLNlRVVjP7iMTPBMqIoIj0CMfUC2L0Aw9UiIWIy29UDgvUDci6iUw/OowUNUI9RoAnOUAiKoEUGos9K+s4REAwH+EAHoI9RowCUUAwH+wTLYj944cc5BI46kEb5Qc85BYp6k+n5lMF6kAb57+76k+r77Ym5l6l5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HBg9NDwxVViXJB250zw50ioEBUowqJooaGG","6l2S5O2I6kEe5yIz77YA","44cq5B6f6kEe6iYd5yYw55Qe5y6F5PAh54Mh5Q6144cr"];return Cl=function(){return e},Cl()}async function Zh(e,t,n){let o=Y,i=await e[o(41)](o(71),{system:tk,user:nk(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 dc(o(19)+t[o(73)]+o(50),[i[o(53)][o(7)](0,500)])}return{raw:i[o(53)],records:Tl(r,t)}}var $l=fn,ik=$l(1);function rk(e){let t=$l,n=e[t(5)](/起点\s*[::]\s*(\d+)/);return n?{found:!0,line:Math[t(3)](Number(n[1]))}:{found:!1,line:null}}function Vl(){let e=["Dgv4Da","5l2G5PIV55+T5yMN5yMN5PYS55Qe44cm5Q2J5PAh6lw354k55A6A5l2n5zMO44cn44cc5lIa5lU95PAh5lU25BI45BI45zYO55YF5Q2J55Qe5yMN5PYS5Q2J5PAh5lMl5yMn77Ym5y6l552a5lIa5AsN5Q61kIRPNz7MRApMLOCQkUEAHoETUEwKH+ADKoAwMEoaGUs9OoIMGEwiPoAwRE+8MIOQ55YF5Q2J55Qe5yMN5PYS5Q2J5PAhkIRMMk/KUi3MMk/LNkJMIjhNU5NKVAdNMOtOV5NMRRxLUkBOOyZLJ7FNMOtMLOFMNkZPH4ZLVidLP4VVViZLPOlMNPZMMk/VViZMIQxLKyRLROpNMOtOTBFLP4VOOyZLJ7FJGiikcUoaKoATO+AwH+MvV+s7Gos5IoAGT+oaKEMaKowCUUEAHowjP+ACRo+8MUs7PEoaJoESRe7PM4BJGi3KUlRPM4BLPltVViZKUiVPNAlNTkFOT5/JGiZLNlPylvKGioAxPs/LHOuG5zYW54k544cn6l+z56En5BIM5zY65QYH57Yw5y+355Qe5zY65PMV5As077Ym5yAn5B6a5lIl5PIV44cm5lI76kAb5lQ654MP77YAl+s6UU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LJ7C+yo+8Ios+I+wMGIbG6lw354k5oIaXndbG77YjcI0G5PYS56Qx5y+J5ywO5PIV5yMn6kIaic8G6l+y5RkH5yIW5Q2J5PAh77YAyoI1T+EcUtOG5PEGya","Aw5Nzxn0lMjVzhKTC3rHCNq","Dhj1BMm","z2vUzxjHDgvuzxH0","Bwf0y2G","5lIl6z2I5PIV5RQq5PAh5lU255Qe5lIa5Q6177Ym5Q+p6kgm5lUL44cm6kgm5y+3pfrbqJ7LHOxLRRNJGi3NU5NLH7RJGilLIktMLQ3NNj/MRApNMOtLIAFMNkZMRApMLOFMMk/LKkBLNkJOV5NMRRxPH4ZLVidLP4VVViZMJiNMOlZLVi/LJ6RLM57KUidOOyZJGiikcG"];return Vl=function(){return e},Vl()}async function Xh(e,t,n){let o=$l,i=await e[o(4)](o(2),{system:ik,user:o(6)+t,...n?{signal:n}:{}});return rk(i[o(0)])}function fn(e,t){e=e-0;let n=Vl(),o=n[e];if(fn.sLepLJ===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};fn.TPTWLA=i,fn.iYuNay={},fn.sLepLJ=!0}let r=n[0];fn.inDmHY!==r&&(fn.iYuNay={},fn.inDmHY=r);let s=fn.iYuNay[e];return s===void 0?(o=fn.TPTWLA(o),fn.iYuNay[e]=o):o=s,o}var ey=50,sk=10;async function ty(e,t,n){let o=t.split(`
|
|
258
|
+
`),i=ey-sk;try{for(let r=0;r<o.length;r+=i){let s=Math.min(r+ey,o.length),a=o.slice(r,s).map((d,p)=>`${r+p+1} ${d}`).join(`
|
|
259
|
+
`),c=await Xh(e,a,n);if(c.found&&c.line!==null)return{line:Math.min(Math.max(c.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 pc(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(a){o[s]={index:s,ok:!1,error:a}}}});return await Promise.all(r),o}var Zt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),mn=e=>Array.isArray(e);function Dl(e){let t=new Map;if(!mn(e))return t;for(let n of e){if(!Zt(n))continue;let o=n.actor_id??n.location_id??n.prop_id;typeof o=="string"&&t.set(o,n)}return t}function ak(e){let t=[],n=(o,i)=>{!Zt(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 mn(e.episodes)?e.episodes:[])if(!(!Zt(o)||!mn(o.scenes))){for(let i of o.scenes)if(Zt(i)){n(i.location,"location_id");for(let r of mn(i.actors)?i.actors:[])n(r,"actor_id");for(let r of mn(i.props)?i.props:[])n(r,"prop_id");for(let r of mn(i.actions)?i.actions:[])Zt(r)&&n(r.speaker,"actor_id")}}return t}function ck(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 lc(e){if(!Zt(e))throw new Error("govern expects a script object");let t=JSON.parse(JSON.stringify(e));for(let p of mn(t.episodes)?t.episodes:[])if(!(!Zt(p)||!mn(p.scenes)))for(let l of p.scenes){if(!Zt(l))continue;let f=mn(l.actors)?l.actors.filter(Zt):[],u=new Set(f.map(h=>h.actor_id).filter(h=>typeof h=="string"));for(let h of mn(l.actions)?l.actions:[])!Zt(h)||!Zt(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=Dl(t.actors),o=Dl(t.locations),i=Dl(t.props),r=new Map([...n,...o,...i]),s=ak(t),a=new Map;for(let p of s){if(p.explicit===void 0)continue;a.has(p.assetId)||a.set(p.assetId,new Map);let l=a.get(p.assetId);l.set(p.explicit,(l.get(p.explicit)??0)+1)}let c=new Map;for(let[p,l]of r){let f=(mn(l.states)?l.states:[]).filter(Zt),u=new Map,h=ck(f,a.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,c.set(p,u)}let d=new Map;for(let p of s){let l=c.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 ny=gn;function gn(e,t){e=e-0;let n=Gl(),o=n[e];if(gn.vcGzia===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};gn.alaGPc=i,gn.IPZchV={},gn.vcGzia=!0}let r=n[0];gn.cEXTRr!==r&&(gn.IPZchV={},gn.cEXTRr=r);let s=gn.IPZchV[e];return s===void 0?(o=gn.alaGPc(o),gn.IPZchV[e]=o):o=s,o}var dk=ny(6);async function oy(e,t,n,o){let i=ny;return(await e[i(4)](i(2),{system:dk,user:i(0)+t+i(3)+n,...o?{signal:o}:{}}))[i(5)][i(1)]()}function Gl(){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 Gl=function(){return e},Gl()}var ay={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"]}}}}}},Bl={type:"array",items:{type:"object",required:["asset_id","state_id"],additionalProperties:!1,properties:{asset_id:{type:"string"},state_id:{type:["string","null"]}}}},VT={type:"object",required:["scenes"],additionalProperties:!1,properties:{scenes:{type:"array",items:{type:"object",required:["scene_id"],additionalProperties:!1,properties:{scene_id:{type:"string"},actors:{...Bl,items:{type:"object",required:["actor_id","state_id"],additionalProperties:!1,properties:{actor_id:{type:"string"},state_id:{type:["string","null"]}}}},locations:{...Bl,items:{type:"object",required:["location_id","state_id"],additionalProperties:!1,properties:{location_id:{type:"string"},state_id:{type:["string","null"]}}}},props:{...Bl,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"]}}}}}}}}},cy={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"}}},dy={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:cy}}},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"}}},pk={type:"string",enum:["actor","location","prop"]},py={type:"string",description:"\u72B6\u6001\u540D\u7B80\u6D01\u6982\u62EC\u53EF\u533A\u5206\u7684\u9636\u6BB5\u5916\u89C2\uFF1B\u5F15\u7528\u65F6\u9010\u5B57\u4F7F\u7528\u767B\u8BB0\u540D\uFF0C\u8BE6\u7EC6\u5916\u89C2\u5199\u5728 description"},iy={type:"string",minLength:5,pattern:"^[0-9]{2}:[0-5][0-9](\\.[0-9]{1,3})?$",description:"\u5FC5\u586B\u3002\u672C\u955C\u5934\u6216\u58F0\u97F3\u771F\u6B63\u5F00\u59CB\u7684\u539F\u7247\u65F6\u95F4\uFF0C\u4F7F\u7528 MM:SS\uFF0C\u53EF\u4FDD\u7559\u539F\u7247\u4F9D\u636E\u652F\u6301\u7684 1\u20133 \u4F4D\u5C0F\u6570\uFF0C\u5982 00:03.240\u3002\u53EA\u6709\u6574\u79D2\u4F9D\u636E\u65F6\u5199\u6574\u79D2\uFF0C\u4E0D\u8865\u9020\u5C0F\u6570\u3002SS \u4E3A 00\u201359\uFF0C\u6574\u5206\u949F\u5199\u4E0B\u4E00\u5206\u949F\u7684 :00"},ry={type:"object",required:["name","description"],additionalProperties:!1,properties:{name:py,description:{type:"string",description:"\u8BE5\u8D44\u4EA7\u6B64\u9636\u6BB5\u53EF\u590D\u73B0\u7684\u5916\u89C2\uFF0C\u975E\u7A7A\u3002\u4EBA\u7269\u8BB0\u5F55\u8138\u5F62\u3001\u4F53\u6001\u3001\u80A4\u51B5\u3001\u5E74\u9F84\u5916\u89C2\u3001\u5986\u53D1\u3001\u53EF\u8FA8\u58F0\u7EBF\u4E0E\u6301\u7EED\u670D\u88C5\u6574\u4F53\u9020\u578B\uFF0C\u5199\u660E\u53EF\u89C1\u989C\u8272\u3001\u6750\u8D28\u8868\u73B0\u3001\u7248\u578B\u3001\u53E0\u7A7F\u548C\u6301\u7EED\u635F\u4F24\uFF1B\u540C\u8863\u670D\u4E0B\u5B9E\u9645\u4E0D\u540C\u7684\u8138\u5F62\u4F53\u6001\u5206\u522B\u5EFA\u72B6\u6001\u3002\u72EC\u7ACB\u53D6\u653E\u3001\u6301\u6709\u6216\u7A7F\u6234\u64CD\u4F5C\u5BF9\u8C61\u7684\u5B8C\u6574\u5916\u89C2\u5F52 prop\uFF0C\u6301\u6709\u3001\u4F69\u6234\u3001\u6458\u4E0B\u3001\u6570\u91CF\u4E0E\u4F4D\u7F6E\u5173\u7CFB\u5F52 Action\uFF0C\u4EBA\u7269 state \u4E0E\u9053\u5177\u5171\u540C\u590D\u73B0\u573A\u666F\u3002\u906E\u6321\u6216\u672A\u786E\u8BA4\u90E8\u4F4D\u4FDD\u7559\u672A\u77E5\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\uFF1B\u52A8\u4F5C\u3001\u59FF\u6001\u3001\u60C5\u7EEA\u548C\u5267\u60C5\u8BC4\u4EF7\u5F52\u6B63\u6587"}}},sy={type:"object",description:"\u753B\u50CF\u5B57\u6BB5\u586B\u7A7A\u5B57\u7B26\u4E32\uFF0Cpersistent_marks \u586B\u7A7A\u6570\u7EC4\uFF1B\u5168\u90E8\u5916\u8C8C\u3001\u8EAB\u4F53\u6807\u8BB0\u4E0E\u53EF\u8FA8\u58F0\u7EBF\u5199\u5165\u5404\u9636\u6BB5\u5B8C\u6574 state\u3002",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"},apparent_age:{type:"string"},face_shape:{type:"string"},brows_eyes:{type:"string"},nose:{type:"string"},mouth:{type:"string"},skin_features:{type:"string"},hair:{type:"string"},build:{type:"string"},persistent_marks:{type:"array",items:{type:"string"}},voice:{type:"string"}}},ly={type:"object",required:["synopsis","scenes","registry_delta","open_threads"],additionalProperties:!1,properties:{synopsis:{type:"string",description:"\u672C\u96C6\u5267\u60C5\u6897\u6982\uFF0C\u6309\u53D1\u751F\u987A\u5E8F\uFF0C200-300 \u5B57\u7EAF\u6587\u672C"},scenes:{type:"array",minItems:1,description:"\u672C\u96C6\u6240\u6709\u573A\u666F\u5355\u5143\uFF0C\u6309\u65F6\u95F4\u987A\u5E8F\u6392\u5217\u3002\u573A\u5185\u5C3D\u91CF\u5FE0\u5B9E\u8FD8\u539F\u539F\u7247\u5206\u955C\uFF1A\u6BCF\u6B21\u5207\u955C\u3001\u8FDE\u7EED\u955C\u5934\u5185\u7684\u6444\u5F71\u53D8\u5316\u3001\u53EF\u89C1\u8868\u6F14\u548C\u58F0\u97F3\u4E8B\u4EF6\u6309\u5B9E\u9645\u65F6\u95F4\u4EA4\u9519\u4FDD\u7559\uFF0C\u91CD\u590D\u955C\u5934\u4E5F\u4E0D\u53BB\u91CD\uFF1B\u5730\u70B9\u3001\u660E\u663E\u65F6\u6BB5\u6216\u53D9\u4E8B\u7EBF\u53D8\u5316\u65F6\u62C6\u573A\uFF0C\u666E\u901A\u5207\u955C\u4E0D\u5355\u72EC\u62C6 scene\uFF1B\u540C\u4E00\u8FDE\u7EED\u573A\u5185\u7684\u4EBA\u7269\u9020\u578B\u53D8\u5316\u4FDD\u7559\u5728\u540C\u4E00\u573A\uFF1B\u8DE8\u5730\u70B9\u8499\u592A\u5947\u62C6\u6210\u591A\u4E2A\u77ED\u573A",items:{type:"object",required:["space","time","timeRange","location","characters","props","shots","voices"],additionalProperties:!1,properties:{space:{type:"string",description:"\u5185\u666F\u586B\u300C\u5185\u300D/\u5916\u666F\u586B\u300C\u5916\u300D\uFF1B\u4E0D\u786E\u5B9A\u586B\u7A7A\u4E32"},time:{type:"string",enum:["\u65E5","\u591C","\u6668","\u660F"],description:"\u672C\u573A\u5FC5\u987B\u9009\u62E9\u4E00\u4E2A\u65F6\u6BB5\uFF1A\u767D\u5929/\u65E5\u95F4\u586B\u300C\u65E5\u300D\uFF0C\u591C\u665A/\u591C\u95F4\u586B\u300C\u591C\u300D\uFF0C\u6E05\u6668/\u9ECE\u660E\u586B\u300C\u6668\u300D\uFF0C\u9EC4\u660F/\u508D\u665A\u586B\u300C\u660F\u300D\u3002\u7ED3\u5408\u7167\u660E\u3001\u4F5C\u606F\u3001\u5929\u7A7A\u548C\u5267\u60C5\u4E0A\u4E0B\u6587\u5224\u65AD\uFF0C\u4E0D\u5F97\u7559\u7A7A"},timeRange:{type:"string",description:"\u672C\u573A\u8D77\u6B62\u65F6\u95F4 MM:SS-MM:SS\uFF0C\u53EF\u4FDD\u7559\u539F\u7247\u4F9D\u636E\u652F\u6301\u7684 1\u20133 \u4F4D\u5C0F\u6570\uFF1BSS \u4E3A 00\u201359\uFF0C\u6574\u5206\u949F\u5199\u4E0B\u4E00\u5206\u949F\u7684 :00"},location:{type:"string",description:"\u672C\u573A\u552F\u4E00\u7A33\u5B9A\u4E3B\u7A7A\u95F4\u5730\u70B9\u540D\uFF0C\u6CBF\u7528\u89C4\u8303\u540D\uFF1B\u5BA2\u5385/\u5367\u5BA4/\u536B\u751F\u95F4/\u5927\u5385/\u5E7F\u573A/\u821E\u53F0/\u540E\u53F0\u5206\u522B\u5EFA\u5730\u70B9\uFF0C\u76F8\u5173\u7A7A\u95F4\u7528\u300E\u8C6A\u5B85\xB7\u5BA2\u5385\u300F\u5F0F\u547D\u540D"},characters:{type:"array",description:"\u672C\u573A\u5728\u573A\u7684\u5177\u4F53\u5355\u4EBA\u89D2\u8272\uFF08\u7FA4\u4F17\u4E0D\u5217\uFF09\u3002\u540C\u4E00\u89D2\u8272\u53EA\u80FD\u51FA\u73B0\u4E00\u6B21\uFF1B\u5176 states \u586B\u672C\u573A\u51FA\u73B0\u8FC7\u7684\u5168\u90E8\u7A33\u5B9A\u9020\u578B/\u72B6\u6001\u96C6\u5408",items:{type:"object",required:["name","states"],additionalProperties:!1,properties:{name:{type:"string",description:"\u89D2\u8272\u89C4\u8303\u540D"},states:{type:"array",items:py,description:"\u672C\u573A\u8BE5\u89D2\u8272\u51FA\u73B0\u8FC7\u7684\u5168\u90E8\u5916\u8C8C\u9636\u6BB5\u4E0E\u9020\u578B\u72B6\u6001\u540D\u96C6\u5408\uFF0C\u9010\u5B57\u5F15\u7528\u5DF2\u6709\u767B\u8BB0\u540D\u6216\u672C\u6B21\u65B0\u5EFA\u540D\u3002\u9636\u6BB5\u548C\u9020\u578B\u5747\u76F8\u540C\u624D\u6CBF\u7528\u5DF2\u6709\u540D\uFF1B\u65E0\u6CD5\u786E\u8BA4\u72B6\u6001\u65F6\u586B\u7A7A\u6570\u7EC4\u3002\u540C\u4E00\u89D2\u8272\u4E00\u6761\u8BB0\u5F55\uFF0C\u56DE\u5FC6\u53CA\u573A\u5185\u53D8\u5316\u5305\u542B\u5B9E\u9645\u51FA\u73B0\u7684\u5404\u9636\u6BB5\u72B6\u6001"}}}},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:iy,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:iy,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","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:pk,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"]},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:"\u4EBA\u7269\u53EA\u5199\u8EAB\u4EFD\u79F0\u8C13\u4E0E\u4EBA\u7269\u5173\u7CFB\uFF0C\u5730\u70B9/\u9053\u5177\u5199\u7528\u9014\uFF1B\u5916\u8C8C\u5F52state\uFF0C\u884C\u4E3A\u548C\u5267\u60C5\u8BC4\u4EF7\u5F52\u6B63\u6587\uFF0C\u975E\u7A7A"},states:{type:"array",items:ry,description:"\u672C\u96C6\u8BE5\u5B9E\u4F53\u51FA\u73B0\u7684\u9636\u6BB5\u72B6\u6001\u3002\u9996\u6B21\u4EBA\u7269\u767B\u8BB0\u4E5F\u4FDD\u5B58\u5F53\u524D\u5B8C\u6574\u5916\u8C8C\u3001\u53EF\u8FA8\u58F0\u7EBF\u4E0E\u670D\u9970\uFF1B\u6BCF\u9879\u7ED9\u51FA\u53EF\u533A\u5206\u7684\u9636\u6BB5\u72B6\u6001\u540D\u53CA\u6765\u6E90\u652F\u6301\u7684\u8BE6\u7EC6\u63CF\u8FF0"},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:"\u586B\u7A7A\u6570\u7EC4\uFF1B\u4EBA\u7269\u8BC6\u522B\u6240\u9700\u7684\u53EF\u89C1\u7279\u5F81\u4E0E\u58F0\u7EBF\u4FDD\u5B58\u5728\u5BF9\u5E94 state"},identity_profile_patch:sy,identity_revision:{type:"object",description:"\u65E2\u6709\u753B\u50CF\u6216\u951A\u70B9\u975E\u7A7A\u65F6\u63D0\u4F9B\uFF1Aprofile \u4E2D\u5B57\u7B26\u4E32\u5168\u90E8\u4E3A\u7A7A\u3001persistent_marks \u548C recognition_anchors \u5747\u4E3A\u7A7A\u6570\u7EC4\uFF0C\u6574\u4F53\u6E05\u7A7A\u65E7\u753B\u50CF\u4E0E\u951A\u70B9\uFF1B\u6709\u8BC1\u636E\u7684\u4E8B\u5B9E\u8865\u5165\u9002\u7528\u7684 add_states\uFF0Crole \u5B8C\u6574\u7ED9\u51FA\u8EAB\u4EFD\u5173\u7CFB\uFF0C\u663E\u5F0F\u7A7A\u4E32\u8868\u793A\u6E05\u9664\u65E7 role\u3002\u65E0\u9700\u6E05\u7406\u65F6\u7701\u7565\u3002",required:["profile","recognition_anchors"],additionalProperties:!1,properties:{profile:sy,recognition_anchors:{type:"array",items:{type:"string"}}}},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:"\u4EBA\u7269\u5DF2\u786E\u8BA4\u7684\u8EAB\u4EFD\u79F0\u8C13\u4E0E\u5173\u7CFB\uFF1B\u5730\u70B9/\u9053\u5177\u5199\u7528\u9014\u3002\u63D0\u4F9B identity_revision \u65F6\u586B\u5199\u5B8C\u6574\u8EAB\u4EFD\u5173\u7CFB\uFF0C\u7A7A\u4E32\u6E05\u9664\u65E7 role\uFF1B\u666E\u901A\u589E\u91CF\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:ry,description:"\u672C\u96C6\u65B0\u72B6\u6001\uFF0C\u4EE5\u53CA\u6709\u8BC1\u636E\u8865\u5168\u7684\u65E7\u72B6\u6001\u3002\u6BCF\u9879\u72EC\u7ACB\u5199\u5168\u8BE5\u9636\u6BB5\u5916\u8C8C\u3001\u58F0\u7EBF\u4E0E\u51C6\u786E\u670D\u9970\uFF0C\u5305\u62EC\u8DE8\u9636\u6BB5\u76F8\u540C\u7279\u5F81\u3002\u65E2\u6709\u9636\u6BB5\u9010\u5B57\u6CBF\u7528\u5176 name\uFF1B\u4EC5\u90E8\u5206\u5F15\u7528\u5F97\u5230\u65B0\u8BC1\u636E\u65F6\uFF0C\u65B0\u5EFA\u72B6\u6001\u5E76\u7ED1\u5B9A\u5DF2\u786E\u8BA4\u573A\u666F\uFF0C\u5176\u4F59\u8303\u56F4\u4FDD\u7559\u5F85\u6838"}}}},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"}}}}}}}},uy={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:cy}}}}};var H=hn;function hn(e,t){e=e-0;let n=Jl(),o=n[e];if(hn.AowUYu===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};hn.vGSHGD=i,hn.ykrKeL={},hn.AowUYu=!0}let r=n[0];hn.qbkWqr!==r&&(hn.ykrKeL={},hn.qbkWqr=r);let s=hn.ykrKeL[e];return s===void 0?(o=hn.vGSHGD(o),hn.ykrKeL[e]=o):o=s,o}var lk=[H(37),H(84),H(100),H(83),H(39),"",H(71),H(55),H(1),H(47),H(10),H(70),H(56),H(46),H(92),H(2),H(61),H(24),H(82),H(51),H(79),H(88),H(58),H(30),H(65),H(73),H(27),H(59),H(86)][H(33)](`
|
|
260
|
+
`);function uk(e,t){let n=H;return[n(4),e[n(50)]()||n(5),"",n(66),t[n(50)]()][n(33)](`
|
|
261
|
+
`)}async function fy(e,t,n,o){let i=H,r=await e[i(45)](i(69),{system:lk,user:uk(t,n),tool:{name:i(44),description:i(22),inputSchema:dy},...o?{signal:o}:{}});return{delta:Ps(r[i(49)]),raw:JSON[i(38)](r[i(49)])}}var fk=new Set([H(60),H(40),H(99)]),Li=e=>typeof e===H(78)&&e!==null&&!Array[H(13)](e),po=e=>typeof e===H(9)?e[H(50)]():"";function uc(e,t){let n=H,o=po(e);if(!o)throw new De(t+n(36));return o}function mk(e,t){let n=H;if(!Li(e))throw new De(t+n(31));let o=uc(e[n(32)],t+n(90));if(o!=="\u5E38\u6001")throw new De(t+n(29));return{name:o,description:uc(e[n(15)],t+n(93))}}var De=class extends Error{[H(12)]=H(34);constructor(t){let n=H;super(t),this[n(32)]=n(0)}};function gk(e){let t=H,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 a=s<e[t(28)]?e[s]:"";if(a===""||a===","||a==="}"||a==="]"||a===":")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)](`
|
|
262
|
+
`);else n+='\\"';continue}n+=r}return n}function hk(e,t){let n=H,o=r=>JSON[n(101)](r),i;try{i=o(e)}catch(r){let s=gk(e);if(s===e)throw new De(t+n(89)+(r instanceof Error?r[n(20)]:String(r)));try{i=o(s)}catch(a){throw new De(t+n(26)+(a instanceof Error?a[n(20)]:String(a)))}}if(!Array[n(13)](i))if(n(6)===n(54))_0x291b73=_0x1aa471(_0x238c2b);else throw new De(t+n(91)+typeof i);return i}function Mi(e,t){let n=H;if(e==null)return[];if(Array[n(13)](e))return e;if(typeof e===n(9)){let o=e[n(50)]();return o?hk(o,t):[]}throw new De(t+n(19)+typeof e)}var yk=/[((]([^))]*)[))]?/;function Jl(){let e=["u2vYAwfSrgvSDgftAgfWzuvYCM9Y","icdcTYbHBgLHC2vZid0G6l+z5Q616yEm6k+L5A6E5l2t55QekIRMIydMNiNLHBBKU5BLJ6VMS5uQkU+8JoMaKos4QUwnLEwiL++8IoE6R+wqJE+8JowiQ+w4PUoaJU+8Iow/G++8IEoaJ+oaJU+8MUoaJ+oaJU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NU63LIQJKVzZVViZLPOlLIy3MLOFJGi7LSi/PQQJJGi/MNkZMRRxNGRNLKi3JGi7MNBdLHyVcT+IoSEw+T+oaJ++8IEoaGIOQ5y+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/KVjRNHACGBwvYz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YC2u","C3bSAxq","Bg9VAW"];return Jl=function(){return e},Jl()}function zl(e){let t=H,n=po(e),o=yk[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 Ni=e=>zl(po(e))[H(32)];function wk(e){let t=H;if(Li(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 De(t(53)+(i instanceof Error?i[t(20)]:String(i)))}if(!Li(o)){if(t(3)===t(3))throw new De(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 Ps(e){let t=H,n=Hh(),o=wk(e);if(!o)return n;for(let i of Mi(o[t(25)],t(25))){if(!Li(i))continue;let r=po(i[t(52)]),{name:s,aliases:a}=zl(po(i[t(32)]));if(!fk[t(62)](r)||!s)continue;let c=uc(i[t(15)],t(81)+s+t(93)),d=mk(i[t(75)],t(81)+s+t(43)),p=[...a];for(let f of Mi(i[t(16)],t(68))){let{name:u,aliases:h}=zl(po(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:c,aliases:l,defaultLook:d})}for(let i of Mi(o[t(57)],t(57))){if(!Li(i))continue;let r=Ni(i[t(11)]),s=Ni(i[t(80)]);r&&s&&r!==s&&n[t(57)][t(76)]({from:r,into:s})}for(let i of Mi(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(!Li(i))continue;let r=Ni(i[t(17)]),s=Ni(i[t(32)]);if(!r||!s)continue;let a=[s,...Mi(i[t(16)],t(94))[t(63)](Ni)[t(18)](Boolean)];n[t(42)][t(76)]({entity:r,names:a,description:uc(i[t(15)],t(7)+r+"."+s+t(93))})}}for(let i of Mi(o[t(85)],t(85))){if(!Li(i))continue;let r=po(i[t(87)]),s=Ni(i[t(17)]),a=Ni(i[t(103)]);r&&s&&a&&n[t(85)][t(76)]({scene:r,entity:s,look:a})}return n[t(96)]=Mi(o[t(96)],t(96))[t(63)](po)[t(18)](Boolean),n[t(97)]=po(o[t(97)]),n}var nt=yn,xk=[nt(1),nt(29),nt(18),nt(32),nt(0),nt(7),nt(15),nt(8),nt(3)][nt(21)](`
|
|
263
|
+
`);function Ek(e,t){let n=nt;return[n(13),e[n(27)]()||n(19),"",n(4),t[n(14)](o=>"- "+o)[n(21)](`
|
|
257
264
|
`)][n(21)](`
|
|
258
|
-
`)}async function
|
|
265
|
+
`)}async function my(e,t,n,o){let i=nt,r=await e[i(24)](i(26),{system:xk,user:Ek(t,n),tool:{name:i(11),description:i(12),inputSchema:uy},...o?{signal:o}:{}});return{delta:jl(r[i(5)],n),raw:JSON[i(30)](r[i(5)])}}var fc=e=>e[nt(23)](nt(6))[nt(31)](/\s+/g," ")[nt(27)]();function jl(e,t=[]){let n=nt,o=Ps(e),i=new Set;for(let s of o[n(22)])i[n(9)](fc(s[n(33)]));for(let s of o[n(25)]){i[n(9)](fc(s[n(10)]));for(let a of s[n(28)])i[n(9)](fc(a))}let r=t[n(20)](s=>!i[n(2)](fc(s)));if(r[n(17)])throw new De(n(16)+r[n(21)]("\u3001"));return o}function yn(e,t){e=e-0;let n=Kl(),o=n[e];if(yn.brkHeO===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};yn.xoIkcy=i,yn.GcFqUp={},yn.brkHeO=!0}let r=n[0];yn.pyAYZq!==r&&(yn.GcFqUp={},yn.pyAYZq=r);let s=yn.GcFqUp[e];return s===void 0?(o=yn.xoIkcy(o),yn.GcFqUp[e]=o):o=s,o}function Kl(){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+55BQu5yIW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n55+T5zcn77Yj4OAsioAuVUI/MYbGBwvYz2vZyo+8MNTMCM9ToIdOV5NKUkRLKi3LRzCSigLUDg86iow3SUEzU+IUSowUNUs9K+EAHcbJyw5VBMLJywX944cc","77Yi56M677Yj","zMLSDgvY","AM9PBG","BwvYz2vZ","BM9YBwfSAxPL","z2vUzxjHDgvuB29S","BMv3rw50AxrPzxm","Aw5Nzxn0lM5HBwuTzML4","DhjPBq","ywXPyxnLCW","5A+5kIRMR4/KUidKUkOQkUw+HEw9KUs4GowqJEwTL++8JowiPoAwREwUG+AyR+s4JEAyRYbYzwDPC3rLCIdPH4ZMN5dKUkRLT7lNMBVORRdLRP7KVzpNMOtLJ6BKUidNP43LJ6VMS5xVVjO","C3rYAw5NAwz5","CMvWBgfJzq","icdcTYaQkUs4JEAyRYOQ77Yi5A6d56gU5A6E5PIVihjLz2LZDgvYioMhJos7JUAYOEEzU+IUSoI/H+EAHos4Gos4QUAwSowUNUs9K++8IEkgKIdMLl7OV5SGyg5LD0vUDgL0AwvZyo+8MNTRAw5KlcbUyw1LkoE6RYbJyw5VBMLJywWPlcbKzxnJCMLWDgLVBIJKUidLJ6xOR53OUQVKU70PlcbHBgLHC2vZlcbKzwzHDwX0tg9VAZP7BMfTztON5BI45OcbjYWGzgvZy3jPChrPB2465y+V6kEb5Asw6kEcFx3JGii","zNjVBq"];return Kl=function(){return e},Kl()}var vt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ot=e=>Array.isArray(e),_k=5,Ui=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),gy=e=>{try{return JSON.parse(e)}catch{return null}},Sk=new Set(["timeout","rate_limited","request_failed","endpoint","empty_response","invalid_response","truncated","serial_delta_shape"]),Ey=e=>!!e&&typeof e=="object"&&"code"in e&&Sk.has(String(e.code)),_y=e=>new Promise(t=>setTimeout(t,e)),kr=(e,t)=>e===t?`episode ${e}`:`episodes ${e}-${t}`;async function hy(e,t,n,o,i,r){for(let s=1;;s++)try{return await fy(e,o,i,r)}catch(a){if(Ey(a)&&s<3&&!r?.aborted){await _y(3e3*s);continue}throw new S(`serial govern failed at ${kr(t,n)}.`,{exitCode:k,errorCode:"INGEST_SERIAL_FAILED",hint:a instanceof De?`Model returned a malformed serial delta (${a.message}). Rerun \`scriptctl ingest\` (optionally --force) to retry ${kr(t,n)}.`:`Rerun \`scriptctl ingest\` to resume from ${kr(t,n)} (earlier windows are cached).`,data:{actual:[a instanceof Error?a.message:String(a)]}})}}function Sy(e,t){let n=t.merges.map(o=>o.into).filter(o=>!qt(e,o));if(n.length)throw new De(`name-fix merge target is not registered: ${[...new Set(n)].join("\u3001")}`)}async function yy(e,t,n,o,i,r,s){for(let a=1;;a++)try{let c=await my(e,o,i,s);return Sy(r,c.delta),c}catch(c){if(Ey(c)&&a<3&&!s?.aborted){await _y(3e3*a);continue}throw new S(`serial name repair failed at ${kr(t,n)}.`,{exitCode:k,errorCode:"INGEST_SERIAL_NAME_FIX_FAILED",hint:c instanceof De?`Model returned an incomplete name repair (${c.message}). Rerun \`scriptctl ingest\` to retry ${kr(t,n)}.`:`Rerun \`scriptctl ingest\` to resume from ${kr(t,n)} (earlier windows are cached).`,data:{actual:[c instanceof Error?c.message:String(c)]}})}}async function Iy(e,t){let n=Qh(),o=e.episodes??[],i=0,r=o.map(bk),s=Yh(r.map(Fh),t.windowTokens);for(let c=0;c<s.length;c++){let[d,p]=s[c],l=sc(n,p),f=r.slice(d-1,p).join(`
|
|
259
266
|
|
|
260
267
|
`),u=t.sourceRef?`# \u539F\u6587\u8BBE\u5B9A\uFF08\u53C2\u8003\uFF0C\u6765\u81EA\u539F\u7A3F\u5F00\u5934\uFF09
|
|
261
268
|
${t.sourceRef}
|
|
262
269
|
|
|
263
|
-
${l}`:l,h=Date.now(),m=t.force?void 0:t.checkpoint?.readUpdate(d,p),g,w=!1;if(m!==void 0){let E=
|
|
264
|
-
`);b=await
|
|
265
|
-
`)}function wk(e,t){let n=JSON.parse(JSON.stringify(e)),o=new Map;for(let a of n.episodes)for(let c of a.scenes){let d=g=>!!qt(t,g),p=c.location?jo(t,c.location.name):null,l=my(c.actors.map(g=>jo(t,g.name)).filter(g=>!ut(g)&&d(g))),f=my(c.props.map(g=>jo(t,g.name)).filter(d)),u=[];for(let g of c.actions)if(g.speaker&&"name"in g.speaker){let w=jo(t,g.speaker.name);ut(w)?g.speaker={kind:"group",label:w}:(g.speaker.name=w,d(w)&&u.push(w))}for(let g of u)l.some(w=>Li(w)===Li(g))||l.push(g);let h=new Map;for(let g of t.lookChanges[c.scene_id]??[]){let w=jo(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}))??[gy(t,g,o)];c.location=p&&d(p)?gy(t,p,o):null,c.actors=l.flatMap(m),c.props=f.flatMap(m)}let i=nc(n),r=i.script;_k(r,t),Sk(r);let s=cc(r);return Ek(s),Ik(s),{doc:s,identityKeys:i.identityKeys}}var xk="\u5E38\u6001";function my(e){let t=new Set;return e.filter(n=>{let o=Li(n);return!n||t.has(o)?!1:(t.add(o),!0)})}function gy(e,t,n){let o=qt(e,t),i=n.get(t)??(o?Ol(o):void 0)??xk;return{name:t,state:i}}function Ek(e){for(let t of["actors","locations","props"])for(let n of Ot(e[t])?e[t]:[])if(vt(n))for(let o of Ot(n.states)?n.states:[])vt(o)&&o.state_id==="default"&&o.state_name==="default"&&(o.state_name="\u5E38\u6001")}function _k(e,t){for(let[n,o]of[["actors","actor_name"],["locations","location_name"],["props","prop_name"]])for(let i of Ot(e[n])?e[n]:[]){if(!vt(i))continue;let r=qt(t,String(i[o])),s=Ot(i.states)?i.states:[];if(r){r.description&&(i.description=r.description),r.aliases.length&&(i.aliases=[...new Set([...Ot(i.aliases)?i.aliases:[],...r.aliases])]);let a=Ol(r),c=a?r.looks.find(d=>Li(d.name)===Li(a))?.description??"":"";for(let d of s){if(!vt(d))continue;if(d.state_id==="default"){c&&(d.description=c);continue}let p=r.looks.find(l=>Li(l.name)===Li(String(d.state_name)));p?.description&&(d.description=p.description)}}}}function Sk(e){let t=new Map,n=new Map,o=new Map,i=0,r=a=>{typeof a=="string"&&(t.has(a)||t.set(a,i),n.set(a,i),o.set(a,(o.get(a)??0)+1))};for(let a of Ot(e.episodes)?e.episodes:[])if(!(!vt(a)||!Ot(a.scenes)))for(let c of a.scenes){if(!vt(c))continue;let p=[...Ot(c.actors)?c.actors:[],...Ot(c.props)?c.props:[],...vt(c.location)?[c.location]:[]].filter(vt).map(l=>l.actor_id??l.prop_id??l.location_id);for(let l of p)r(l);for(let l of Ot(c.actions)?c.actions:[])vt(l)&&vt(l.speaker)&&typeof l.speaker.actor_id=="string"&&r(l.speaker.actor_id),i++}let s=a=>(o.get(a)??0)>=2&&n.get(a)-t.get(a)>=uk;for(let[a,c]of[["actors","actor_id"],["props","prop_id"]])for(let d of Ot(e[a])?e[a]:[])vt(d)&&(d.importance=s(String(d[c]))?"featured":"background");for(let a of Ot(e.locations)?e.locations:[])vt(a)&&(a.importance="featured")}function Ik(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 Ot(e[n])?e[n]:[]){if(!vt(i))continue;let r=String(i[o]??""),s=Ot(i.states)?i.states:[];if(!t(i.description))throw new S(`Ingested asset "${r}" is missing its identity description.`,{exitCode:k,errorCode:"ASSET_DESCRIPTION_MISSING",hint:"Rerun `scriptctl ingest --force` so the serial asset window can regenerate this entity."});for(let a of s){if(!vt(a)||t(a.description))continue;let c=String(a.state_name??"");throw new S(`Ingested asset "${r}" has no visual description for look "${c}".`,{exitCode:k,errorCode:a.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 $n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lo=e=>Array.isArray(e)?e:[],ot=e=>typeof e=="string"?e.trim():"";function zl(e){return e.normalize("NFKC").toLowerCase().replace(/[\p{White_Space}\p{P}\p{S}]+/gu,"")}var Ak={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"}},Ey=(e,t,n=8)=>{!t||e.includes(t)||e.length>=n||e.push(t)};function _y(e){let t=$n(e)?e:{},n={actor:[],location:[],prop:[]},o=new Map;for(let a of["actor","location","prop"]){let c=Ak[a];for(let d of lo(t[c.list])){if(!$n(d))continue;let p=ot(d[c.id]),l=ot(d[c.name]);if(!p)continue;let f=[...new Set(lo(d.aliases).map(ot).filter(Boolean))],u=new Map,h=[];for(let g of lo(d.states)){if(!$n(g))continue;let w=ot(g.state_id);if(!w)continue;let y=ot(g.state_name),E={address:`${p}/${w}`,state_id:w,state_name:y,description:ot(g.description),format_key:zl(y),reference_count:0,episode_count:0,scene_count:0,references:[],frequency_flag:null,episodeIds:new Set,sceneIds:new Set};h.push(E),u.set(w,E)}let m={kind:a,id:p,name:l,aliases:f,description:ot(d.description),importance:ot(d.importance),format_key:zl(l),alias_format_keys:f.map(zl),reference_count:0,episode_count:0,scene_count:0,references:[],states:h,episodeIds:new Set,sceneIds:new Set,stateById:u};n[a].push(m),o.set(p,m)}}let i=a=>{let c=lo(a.state_ids).map(ot).filter(Boolean);if(c.length>0)return[...new Set(c)];let d=ot(a.state_id);return d?[d]:[]},r=(a,c,d,p,l,f)=>{let u=o.get(c);if(!u||u.kind!==a)return;u.reference_count+=1,u.episodeIds.add(p),u.sceneIds.add(`${p}/${l}`),Ey(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}`),Ey(g.references,f))}};for(let a of lo(t.episodes)){if(!$n(a))continue;let c=ot(a.episode_id)||"<episode>";for(let d of lo(a.scenes)){if(!$n(d))continue;let p=ot(d.scene_id)||"<scene>",l=`${c}/${p}`;$n(d.location)&&r("location",ot(d.location.location_id),i(d.location),c,p,`${l}.location`);for(let f of lo(d.actors))$n(f)&&r("actor",ot(f.actor_id),i(f),c,p,`${l}.actors`);for(let f of lo(d.props))$n(f)&&r("prop",ot(f.prop_id),i(f),c,p,`${l}.props`);lo(d.actions).forEach((f,u)=>{if(!$n(f)||!$n(f.speaker))return;let h=ot(f.speaker.actor_id);h&&r("actor",h,i(f.speaker),c,p,`${l}#${u+1}.speaker`)})}}let s=a=>{a.episode_count=a.episodeIds.size,a.scene_count=a.sceneIds.size;for(let c of a.states)c.episode_count=c.episodeIds.size,c.scene_count=c.sceneIds.size,c.frequency_flag=c.state_id==="default"?null:c.scene_count===0?"unused":c.scene_count===1?"singleton":null;return{kind:a.kind,id:a.id,name:a.name,aliases:a.aliases,description:a.description,importance:a.importance,format_key:a.format_key,alias_format_keys:a.alias_format_keys,reference_count:a.reference_count,episode_count:a.episode_count,scene_count:a.scene_count,references:a.references,states:a.states.map(c=>({address:c.address,state_id:c.state_id,state_name:c.state_name,description:c.description,format_key:c.format_key,reference_count:c.reference_count,episode_count:c.episode_count,scene_count:c.scene_count,references:c.references,frequency_flag:c.frequency_flag}))}};return{title:ot(t.title),actors:n.actor.map(s),locations:n.location.map(s),props:n.prop.map(s)}}var G=xn,Iy=["id",G(38),G(13),G(90),G(40),G(34),G(6),G(82),G(35),G(62)];function Hl(){let e=["yxnZzxrFAwrZ","DgL0Bgv8","5l6l5AAc44co5P6x5PYj57kU44cp5zkm44co5P6xioACIEEYRUoaJ+wpQUAyR+AGVow8J+s4JEwqJo+8Jos9HUs4JEIdVEwpQUAmIEwqJEENSoEBUos8Vow6PUwqIow5TUoaGUw/HEMHU+E7VowqIos6UUEjQEwfS+EZU+oaGEwjP+AdHEI6Q+s7VEoaGEwKLUIYJoApJ+I/SooaGEIHJos4UUI9QoI/UEoaGEwVUEEzVEw9KUwXNUoaGEwhUUEoSos9JEE9RUwsJoI3QoMBHUI/NUE7REAaP+w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GihPGzpLHBFLIiBLJlRVViXoioAyR+IVPEwiHUwmUUI1Hos6P+AvSow5TUwgS+wUMUwfTUs4RsbbioIHJoEAHoI1Hos6P+EXU+wEI+oaGG","CMv2Awv3","5Qoa5P+L5zcm5lIa5lIQ54MP55cg5zYW54k55OIw5zcm5lIa5lU25yw35l2t6ygt5yw35PIV5zcM5zUG5zcn56EW44cb5yMn5zco57Ya44cb5B2s5BgE5O+p6l+W44cb566a56EW44cb566a57Mb5l2t44cb6l2S5B2v5BEU5BYc5OIw6kEc5A+F6kEs5BQM5lIn5zcm6icm6yEn5Asn55M76k6W44cc5yY65yIg5zcm5lIa5zYW54k555Qe5lIn5zcm5zcn56EW5lIo5zcm5lIa5BU6562r5lIT55Qe5lIn5zcm54US56Ul56M66zE077Ym5lMF5yY65yIg5zcm5lIa5lU25yw35l2t6ygt5yw35lIo5zcm57g75l2g5A6E6zMf5lIn5zcm55Qe5AsA5lU26ygt5yw344cc","yxnZzxqGyxvKAxqGCMvZCg9UC2uGBxvZDcbIzsbHiePtt04GB2jQzwn0","CMvJB21Tzw5KyxrPB24","AgLNAa","zw1PDf9HC3nLDf9HDwrPDa","Bg93","ywn0Aw9U","C3rHDgvFAwrZ","zMLSDgvY","qvntrvrFqvvesvrFu05bufnit1rFvJe","zM9YBwf0x2TLEsdLJ6RMIPJLJ6dNQBRNMB3JGihMOiFNGRNJGihLPkFLSi/LHPNJGihLHAJLJyROP5lNRyNMOlZLVi/LT67LVilVViZMMk/LJ6ZLM57OR4hMJA7OGiZKUi3MMk/LKiZKUidLRP7KVzpNMOtMNidNU4JNU5pORRRJGii","AxnbCNjHEq","zxbPC29Kzxm","zgvZy3jPChrPB24","CMvWBgfJzq","BwvKAxvT","BMfTzq","u19dt0Xvtu5tFa","CMvMCW","5l2G5Q2J5zYO5A+55lIa6yoO5BEY57Up5A6m5OIq6kEJ5P6q55Qe5A6m5Pw05yMN5PYS6l+B6kgm5ywO5Bga6lwe5lQN5lIa6iE05OcN5A6H6k6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Mb5l2t77YB5ywO5zcn44cb566a56EW44cb5PI156EW44cb56EW6lct44cb6igm5l2n44cb5PEN5zcn44cb5yYw5zcn44cb6k+r5zcn44cb6z+Z6k+r77YB5yIg6k+n5BEU5BYc44cb6l275B6U6zsz5yIR5A2x44cb6l2S5B2v6k+V5BEU77YB5zcn56EW6zMe5BIM6lQR5lU944cb5Oof57UQ44cb5A+555M95OIw54Q25Ocb6k+05PIo77YB5yMn5PYF6lQR5lU95PYQ5PIo44cb5zco5PYF5y+i5lUL55YF5zcn6yEn5PAW55M76k6W44cc","5zYO5zcm5lIa5lIQ5lQ654MP44cb5zYW54k55OIw6ygt5yw35yAf6yoO77Ym5Qoa5P+L5PIV5zcM5zUG5O+p6l+W5PA55BYp44cb6AkC6iMY57ks5BQM44cb5O6Q6l6E6k+M55wL5OIw6kEc5A+F6kEs5BQM5lIn5zcm77Ym5OQk5zcm5lIa5lIQ56IZ5A6A6kEg6kEj54Q25Ocb5OUg5OIq5AsA5lIQihn0yxrL44cc6yEn54k55ywZ5RoO5zcm5lMjl+I/KEs5IEEkTUAaGEoaGEwqJos4GowLL+ACJEIJHEIIQ+MhJEAwSowrVEwqJEoaGEs7HEwfIEE6V+AiLUwXGoMdQoE7HUIkGUMaOoAiKoEAHow3RUw8GU+8Jos7PEwpIUEkTUAaGEwqJEA3T+wfPEAdHEE7QUoaGEwkQos9NoAiLUwCUUAzR+IVToAyJUoaGG","BwvYz2u","zhvWBgLJyxrLx3n0yxrL","BMfTzxm","vw9trNG","6l+u5zUE5ywO5yMN6lwe5lQN5lIa6iE05OcN5A6H6k6H5y+r546W","Aw1WB3j0yw5Jzq","5lQm44cb6kEg6kEj54Q25Ocb5lIa6iE05OcN","5lIj44cb5l2o6Akr5lIo5BYc5BI454Q25Ocb","DhjPBq"];return Hl=function(){return e},Hl()}var Ay=[G(5),G(38),G(40),G(34),G(6),G(11),G(82),G(35),G(62)],kk=[G(41),G(20),G(14)+Iy[G(45)](G(68))+G(61),G(77)+Ay[G(45)](G(68))+G(79),G(58),G(32),"",G(75),G(83),G(2),"",G(91),G(84),G(53),"",G(92),G(56),"",G(60),G(22),G(74),"",G(7),G(52),G(9),G(8),G(67),G(43)][G(45)](`
|
|
266
|
-
`),
|
|
267
|
-
`)}function xn(e,t){e=e-0;let n=
|
|
270
|
+
${l}`:l,h=Date.now(),m=t.force?void 0:t.checkpoint?.readUpdate(d,p),g,w=!1;if(m!==void 0){let E=gy(m);try{if(E==null)throw new De("checkpoint top-level JSON is unparseable");g=Ps(E),w=!0,i++,t.executor.recordReuse("ingest.episode-assets")}catch(_){if(!(_ instanceof De))throw _;let x=await hy(t.executor,d,p,u,f,t.signal);g=x.delta,t.checkpoint?.writeStep(d,p,l,x.raw)}}else{let E=await hy(t.executor,d,p,u,f,t.signal);g=E.delta,t.checkpoint?.writeStep(d,p,l,E.raw)}Ns(n,g,d,p);let y=Ik(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 _=gy(E);try{if(_==null)throw new De("name-fix checkpoint top-level JSON is unparseable");let x=jl(_,y);Sy(n,x),Ns(n,x,d,p),i++,t.executor.recordReuse("ingest.name-fix")}catch(x){if(!(x instanceof De))throw x;let A=await yy(t.executor,d,p,sc(n,p),y,n,t.signal);t.checkpoint?.writeNameFix?.(d,p,A.raw),Ns(n,A.delta,d,p)}}else{let _=await yy(t.executor,d,p,sc(n,p),y,n,t.signal);t.checkpoint?.writeNameFix?.(d,p,_.raw),Ns(n,_.delta,d,p)}}qh(n);for(let E=Ll(n);E;E=Ll(n)){let _=E[0].startEp,x=E[E.length-1].endEp,A=t.force?void 0:t.checkpoint?.readArc?.(_,x),b;if(A!==void 0)b=A,i++,t.executor.recordReuse("ingest.arc-summary");else{let U=E.map(v=>`${Rl(v)}\uFF1A${v.line}`).join(`
|
|
271
|
+
`);b=await oy(t.executor,`\u7B2C${_}\u96C6\u2013\u7B2C${x}\u96C6`,U,t.signal),t.checkpoint?.writeArc?.(_,x,b)}Wh(n,b)}t.onWindow?.({startEp:d,endEp:p,ms:Date.now()-h,cached:w,index:c,total:s.length,totalEpisodes:o.length})}return{...vk(e,n),episodes:o.length,reused:i}}function Ik(e,t){let n=new Set,o=i=>{if(!i)return;let r=Ho(t,i);ut(r)||qt(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 Ak={interior:"\u5185",exterior:"\u5916"},kk={day:"\u65E5",night:"\u591C"};function bk(e){let t=[`# ${e.episode_id}${e.title?` ${e.title}`:""}`];for(let n of e.scenes){t.push(`## ${n.scene_id}`);let o=[Ak[n.environment?.space??""],kk[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(`
|
|
272
|
+
`)}function vk(e,t){let n=JSON.parse(JSON.stringify(e)),o=new Map;for(let a of n.episodes)for(let c of a.scenes){let d=g=>!!qt(t,g),p=c.location?Ho(t,c.location.name):null,l=wy(c.actors.map(g=>Ho(t,g.name)).filter(g=>!ut(g)&&d(g))),f=wy(c.props.map(g=>Ho(t,g.name)).filter(d)),u=[];for(let g of c.actions)if(g.speaker&&"name"in g.speaker){let w=Ho(t,g.speaker.name);ut(w)?g.speaker={kind:"group",label:w}:(g.speaker.name=w,d(w)&&u.push(w))}for(let g of u)l.some(w=>Ui(w)===Ui(g))||l.push(g);let h=new Map;for(let g of t.lookChanges[c.scene_id]??[]){let w=Ho(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}))??[xy(t,g,o)];c.location=p&&d(p)?xy(t,p,o):null,c.actors=l.flatMap(m),c.props=f.flatMap(m)}let i=rc(n),r=i.script;Mk(r,t),Nk(r);let s=lc(r);return Rk(s),Lk(s),{doc:s,identityKeys:i.identityKeys}}var Ok="\u5E38\u6001";function wy(e){let t=new Set;return e.filter(n=>{let o=Ui(n);return!n||t.has(o)?!1:(t.add(o),!0)})}function xy(e,t,n){let o=qt(e,t),i=n.get(t)??(o?Nl(o):void 0)??Ok;return{name:t,state:i}}function Rk(e){for(let t of["actors","locations","props"])for(let n of Ot(e[t])?e[t]:[])if(vt(n))for(let o of Ot(n.states)?n.states:[])vt(o)&&o.state_id==="default"&&o.state_name==="default"&&(o.state_name="\u5E38\u6001")}function Mk(e,t){for(let[n,o]of[["actors","actor_name"],["locations","location_name"],["props","prop_name"]])for(let i of Ot(e[n])?e[n]:[]){if(!vt(i))continue;let r=qt(t,String(i[o])),s=Ot(i.states)?i.states:[];if(r){r.description&&(i.description=r.description),r.aliases.length&&(i.aliases=[...new Set([...Ot(i.aliases)?i.aliases:[],...r.aliases])]);let a=Nl(r),c=a?r.looks.find(d=>Ui(d.name)===Ui(a))?.description??"":"";for(let d of s){if(!vt(d))continue;if(d.state_id==="default"){c&&(d.description=c);continue}let p=r.looks.find(l=>Ui(l.name)===Ui(String(d.state_name)));p?.description&&(d.description=p.description)}}}}function Nk(e){let t=new Map,n=new Map,o=new Map,i=0,r=a=>{typeof a=="string"&&(t.has(a)||t.set(a,i),n.set(a,i),o.set(a,(o.get(a)??0)+1))};for(let a of Ot(e.episodes)?e.episodes:[])if(!(!vt(a)||!Ot(a.scenes)))for(let c of a.scenes){if(!vt(c))continue;let p=[...Ot(c.actors)?c.actors:[],...Ot(c.props)?c.props:[],...vt(c.location)?[c.location]:[]].filter(vt).map(l=>l.actor_id??l.prop_id??l.location_id);for(let l of p)r(l);for(let l of Ot(c.actions)?c.actions:[])vt(l)&&vt(l.speaker)&&typeof l.speaker.actor_id=="string"&&r(l.speaker.actor_id),i++}let s=a=>(o.get(a)??0)>=2&&n.get(a)-t.get(a)>=_k;for(let[a,c]of[["actors","actor_id"],["props","prop_id"]])for(let d of Ot(e[a])?e[a]:[])vt(d)&&(d.importance=s(String(d[c]))?"featured":"background");for(let a of Ot(e.locations)?e.locations:[])vt(a)&&(a.importance="featured")}function Lk(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 Ot(e[n])?e[n]:[]){if(!vt(i))continue;let r=String(i[o]??""),s=Ot(i.states)?i.states:[];if(!t(i.description))throw new S(`Ingested asset "${r}" is missing its identity description.`,{exitCode:k,errorCode:"ASSET_DESCRIPTION_MISSING",hint:"Rerun `scriptctl ingest --force` so the serial asset window can regenerate this entity."});for(let a of s){if(!vt(a)||t(a.description))continue;let c=String(a.state_name??"");throw new S(`Ingested asset "${r}" has no visual description for look "${c}".`,{exitCode:k,errorCode:a.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 $n=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),lo=e=>Array.isArray(e)?e:[],ot=e=>typeof e=="string"?e.trim():"";function Hl(e){return e.normalize("NFKC").toLowerCase().replace(/[\p{White_Space}\p{P}\p{S}]+/gu,"")}var Uk={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"}},Ay=(e,t,n=8)=>{!t||e.includes(t)||e.length>=n||e.push(t)};function ky(e){let t=$n(e)?e:{},n={actor:[],location:[],prop:[]},o=new Map;for(let a of["actor","location","prop"]){let c=Uk[a];for(let d of lo(t[c.list])){if(!$n(d))continue;let p=ot(d[c.id]),l=ot(d[c.name]);if(!p)continue;let f=[...new Set(lo(d.aliases).map(ot).filter(Boolean))],u=new Map,h=[];for(let g of lo(d.states)){if(!$n(g))continue;let w=ot(g.state_id);if(!w)continue;let y=ot(g.state_name),E={address:`${p}/${w}`,state_id:w,state_name:y,description:ot(g.description),format_key:Hl(y),reference_count:0,episode_count:0,scene_count:0,references:[],frequency_flag:null,episodeIds:new Set,sceneIds:new Set};h.push(E),u.set(w,E)}let m={kind:a,id:p,name:l,aliases:f,description:ot(d.description),importance:ot(d.importance),format_key:Hl(l),alias_format_keys:f.map(Hl),reference_count:0,episode_count:0,scene_count:0,references:[],states:h,episodeIds:new Set,sceneIds:new Set,stateById:u};n[a].push(m),o.set(p,m)}}let i=a=>{let c=lo(a.state_ids).map(ot).filter(Boolean);if(c.length>0)return[...new Set(c)];let d=ot(a.state_id);return d?[d]:[]},r=(a,c,d,p,l,f)=>{let u=o.get(c);if(!u||u.kind!==a)return;u.reference_count+=1,u.episodeIds.add(p),u.sceneIds.add(`${p}/${l}`),Ay(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}`),Ay(g.references,f))}};for(let a of lo(t.episodes)){if(!$n(a))continue;let c=ot(a.episode_id)||"<episode>";for(let d of lo(a.scenes)){if(!$n(d))continue;let p=ot(d.scene_id)||"<scene>",l=`${c}/${p}`;$n(d.location)&&r("location",ot(d.location.location_id),i(d.location),c,p,`${l}.location`);for(let f of lo(d.actors))$n(f)&&r("actor",ot(f.actor_id),i(f),c,p,`${l}.actors`);for(let f of lo(d.props))$n(f)&&r("prop",ot(f.prop_id),i(f),c,p,`${l}.props`);lo(d.actions).forEach((f,u)=>{if(!$n(f)||!$n(f.speaker))return;let h=ot(f.speaker.actor_id);h&&r("actor",h,i(f.speaker),c,p,`${l}#${u+1}.speaker`)})}}let s=a=>{a.episode_count=a.episodeIds.size,a.scene_count=a.sceneIds.size;for(let c of a.states)c.episode_count=c.episodeIds.size,c.scene_count=c.sceneIds.size,c.frequency_flag=c.state_id==="default"?null:c.scene_count===0?"unused":c.scene_count===1?"singleton":null;return{kind:a.kind,id:a.id,name:a.name,aliases:a.aliases,description:a.description,importance:a.importance,format_key:a.format_key,alias_format_keys:a.alias_format_keys,reference_count:a.reference_count,episode_count:a.episode_count,scene_count:a.scene_count,references:a.references,states:a.states.map(c=>({address:c.address,state_id:c.state_id,state_name:c.state_name,description:c.description,format_key:c.format_key,reference_count:c.reference_count,episode_count:c.episode_count,scene_count:c.scene_count,references:c.references,frequency_flag:c.frequency_flag}))}};return{title:ot(t.title),actors:n.actor.map(s),locations:n.location.map(s),props:n.prop.map(s)}}var G=xn,vy=["id",G(38),G(13),G(90),G(40),G(34),G(6),G(82),G(35),G(62)];function Yl(){let e=["yxnZzxrFAwrZ","DgL0Bgv8","5l6l5AAc44co5P6x5PYj57kU44cp5zkm44co5P6xioACIEEYRUoaJ+wpQUAyR+AGVow8J+s4JEwqJo+8Jos9HUs4JEIdVEwpQUAmIEwqJEENSoEBUos8Vow6PUwqIow5TUoaGUw/HEMHU+E7VowqIos6UUEjQEwfS+EZU+oaGEwjP+AdHEI6Q+s7VEoaGEwKLUIYJoApJ+I/SooaGEIHJos4UUI9QoI/UEoaGEwVUEEzVEw9KUwXNUoaGEwhUUEoSos9JEE9RUwsJoI3QoMBHUI/NUE7REAaP+wiPoAwREoaGUwNK+wqJEEBUos8VooaGEI6Q+s7VEEBUoI/KEAiLUE7J+w4UowqJoAHHUEAHos4JEwqJos6UUEjQEE7NEs4JEIdVE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EI+oaGG","CMv2Awv3","5Qoa5P+L5zcm5lIa5lIQ54MP55cg5zYW54k55OIw5zcm5lIa5lU25yw35l2t6ygt5yw35PIV5zcM5zUG5zcn56EW44cb5yMn5zco57Ya44cb5B2s5BgE5O+p6l+W44cb566a56EW44cb566a57Mb5l2t44cb6l2S5B2v5BEU5BYc5OIw6kEc5A+F6kEs5BQM5lIn5zcm6icm6yEn5Asn55M76k6W44cc5yY65yIg5zcm5lIa5zYW54k555Qe5lIn5zcm5zcn56EW5lIo5zcm5lIa5BU6562r5lIT55Qe5lIn5zcm54US56Ul56M66zE077Ym5lMF5yY65yIg5zcm5lIa5lU25yw35l2t6ygt5yw35lIo5zcm57g75l2g5A6E6zMf5lIn5zcm55Qe5AsA5lU26ygt5yw344cc","yxnZzxqGyxvKAxqGCMvZCg9UC2uGBxvZDcbIzsbHiePtt04GB2jQzwn0","CMvJB21Tzw5KyxrPB24","AgLNAa","zw1PDf9HC3nLDf9HDwrPDa","Bg93","ywn0Aw9U","C3rHDgvFAwrZ","zMLSDgvY","qvntrvrFqvvesvrFu05bufnit1rFvJe","zM9YBwf0x2TLEsdLJ6RMIPJLJ6dNQBRNMB3JGihMOiFNGRNJGihLPkFLSi/LHPNJGihLHAJLJyROP5lNRyNMOlZLVi/LT67LVilVViZMMk/LJ6ZLM57OR4hMJA7OGiZKUi3MMk/LKiZKUidLRP7KVzpNMOtMNidNU4JNU5pORRRJGii","AxnbCNjHEq","zxbPC29Kzxm","zgvZy3jPChrPB24","CMvWBgfJzq","BwvKAxvT","BMfTzq","u19dt0Xvtu5tFa","CMvMCW","5l2G5Q2J5zYO5A+55lIa6yoO5BEY57Up5A6m5OIq6kEJ5P6q55Qe5A6m5Pw05yMN5PYS6l+B6kgm5ywO5Bga6lwe5lQN5lIa6iE05OcN5A6H6k6H44cc55UU5Qch5PIV5y+r546W5zcm5lIa5A6E5l2t6kkR6yEn5Asn5BU65QgJ44cb5zcm5lIa56IZ5A6A6kEg6kEj54Q25Ocb6k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z6k+r77YB5yIg6k+n5BEU5BYc44cb6l275B6U6zsz5yIR5A2x44cb6l2S5B2v6k+V5BEU77YB5zcn56EW6zMe5BIM6lQR5lU944cb5Oof57UQ44cb5A+555M95OIw54Q25Ocb6k+05PIo77YB5yMn5PYF6lQR5lU95PYQ5PIo44cb5zco5PYF5y+i5lUL55YF5zcn6yEn5PAW55M76k6W44cc","5zYO5zcm5lIa5lIQ5lQ654MP44cb5zYW54k55OIw6ygt5yw35yAf6yoO77Ym5Qoa5P+L5PIV5zcM5zUG5O+p6l+W5PA55BYp44cb6AkC6iMY57ks5BQM44cb5O6Q6l6E6k+M55wL5OIw6kEc5A+F6kEs5BQM5lIn5zcm77Ym5OQk5zcm5lIa5lIQ56IZ5A6A6kEg6kEj54Q25Ocb5OUg5OIq5AsA5lIQihn0yxrL44cc6yEn54k55ywZ5RoO5zcm5lMjl+I/KEs5IEEkTUAaGEoaGEwqJos4GowLL+ACJEIJHEIIQ+MhJEAwSowrVEwqJEoaGEs7HEwfIEE6V+AiLUwXGoMdQoE7HUIkGUMaOoAiKoEAHow3RUw8GU+8Jos7PEwpIUEkTUAaGEwqJEA3T+wfPEAdHEE7QUoaGEwkQos9NoAiLUwCUUAzR+IVToAyJUoaGG","BwvYz2u","zhvWBgLJyxrLx3n0yxrL","BMfTzxm","vw9trNG","6l+u5zUE5ywO5yMN6lwe5lQN5lIa6iE05OcN5A6H6k6H5y+r546W","Aw1WB3j0yw5Jzq","5lQm44cb6kEg6kEj54Q25Ocb5lIa6iE05OcN","5lIj44cb5l2o6Akr5lIo5BYc5BI454Q25Ocb","DhjPBq"];return Yl=function(){return e},Yl()}var Oy=[G(5),G(38),G(40),G(34),G(6),G(11),G(82),G(35),G(62)],Pk=[G(41),G(20),G(14)+vy[G(45)](G(68))+G(61),G(77)+Oy[G(45)](G(68))+G(79),G(58),G(32),"",G(75),G(83),G(2),"",G(91),G(84),G(53),"",G(92),G(56),"",G(60),G(22),G(74),"",G(7),G(52),G(9),G(8),G(67),G(43)][G(45)](`
|
|
273
|
+
`),Ck=new Set([G(80),G(55),G(10),G(86),G(57),G(70),G(65)]),Tk=new Set([G(85),G(78),G(21)]),Vk=new Set([G(25),G(37),G(27)]);function wn(e){let t=G,n=e[t(93)]();return n?n[t(36)](/\\/g,"\\\\")[t(36)](/\r\n?|\n/g,"\\n")[t(36)](/\|/g,"\\|")[t(36)](/;/g,"\\;"):"-"}function Ql(e){let t=G;return e[t(18)]>0?e[t(69)](wn)[t(45)](";"):"-"}function $k(e){let t=G,n=[t(31),t(1)+wn(e[t(42)]),t(46)+vy[t(45)]("|"),t(39)+Oy[t(45)]("|")],o=(i,r)=>{let s=t;n[s(71)]("["+i+":"+r[s(18)]+"]");for(let a 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 c of _0xef23b5[s(17)])_0x5593cc[s(71)](["S",_0x265c62(c[s(5)]),_0x1ae902(c[s(49)]),_0xabc48e(c[s(19)]),_0x4a1d6b(c[s(3)]),_0x514694(c[s(64)]),c[s(15)]??"-",_0x5aa3d6(c[s(82)]),_0x32748e(c[s(35)]),_0x3d8f50(c[s(4)])][s(45)]("|"))}else{n[s(71)](["A",wn(a.id),wn(a[s(38)]),Ql(a[s(13)]),wn(a[s(90)]),String(a[s(19)]),String(a[s(3)]),String(a[s(64)]),wn(a[s(82)]),wn(a[s(35)]),Ql(a[s(4)])][s(45)]("|"));for(let c of a[s(17)])n[s(71)](["S",wn(c[s(5)]),wn(c[s(49)]),String(c[s(19)]),String(c[s(3)]),String(c[s(64)]),c[s(15)]??"-",wn(c[s(82)]),wn(c[s(35)]),Ql(c[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)](`
|
|
274
|
+
`)}function xn(e,t){e=e-0;let n=Yl(),o=n[e];if(xn.qyTtRy===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};xn.uxwRFZ=i,xn.OXUPnC={},xn.qyTtRy=!0}let r=n[0];xn.TDHWfX!==r&&(xn.OXUPnC={},xn.TDHWfX=r);let s=xn.OXUPnC[e];return s===void 0?(o=xn.uxwRFZ(o),xn.OXUPnC[e]=o):o=s,o}var by=e=>typeof e===G(48)&&e!==null&&!Array[G(33)](e),Ry=e=>Array[G(33)](e)?e:[],Pi=e=>typeof e===G(63)?e[G(93)]():"",Fl=e=>[...new Set(Ry(e)[G(69)](Pi)[G(30)](Boolean))];function Dk(e,t){let n=G;if(!by(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)](a=>a[n(5)]))),r=[];for(let s of Ry(e[n(73)])){if(!by(s))continue;let a=Pi(s[n(50)]),c=Pi(s[n(28)]),d=Pi(s[n(76)]);if(!Ck[n(44)](a)||!Tk[n(44)](c)||!Vk[n(44)](d))continue;let p=Fl(s[n(0)])[n(30)](h=>o[n(44)](h)),l=Fl(s[n(29)])[n(30)](h=>i[n(44)](h));if(p[n(18)]===0&&l[n(18)]===0)continue;let f=Pi(s[n(51)]),u=f&&(o[n(44)](f)||i[n(44)](f))?f:null;r[n(71)]({type:a,asset_ids:p,state_ids:l,names:Fl(s[n(87)]),evidence:Pi(s[n(16)]),recommendation:Pi(s[n(24)]),suggested_survivor:u,action:c,confidence:d})}return r}async function My(e,t,n){let o=G,i=await e[o(12)](o(66),{system:Pk,user:$k(t),tool:{name:o(26),description:o(89),inputSchema:ay},...n?{signal:n}:{}});return Dk(i[o(72)],t)}var Ny="1",Gk=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;let n=e;return n.audit_version===Ny&&n.script_hash===t&&n.summary!==null&&typeof n.summary=="object"&&Array.isArray(n.issues)};function Bk(e,t){return{audit_version:Ny,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 ql(e,t,n){let o=je(e),i=ky(e),r=await My(t,i,n);return Bk(o,r)}async function Jk(e){let t=je(e.script);if(!e.force&&e.exists())try{let o=e.read();if(Gk(o,t))return e.executor.recordReuse("ingest.asset-audit"),{report:o,reused:!0}}catch{}let n=await ql(e.script,e.executor,e.signal);return e.write(n),{report:n,reused:!1}}async function Ly(e,t,n,o={}){return Jk({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 zk={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 Wl(e){let t=[...e.asset_ids,...e.state_ids].join(", ")||"<unknown>",n=e.evidence||e.recommendation||"review the referenced assets";return`${zk[e.type]} [${t}]: ${n}`}function Uy(e){return e.issues.map(t=>({code:`asset_audit_${t.type}`,path:"$",message:`${Wl(t)}; action=${t.action}; confidence=${t.confidence}`}))}var br=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 Py(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),a=s.length?s.reduce((p,l)=>p+l.ms,0)/s.length:null,c=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:c,totalEpisodes:e.serial.totalEpisodes,avgWindowMs:a!=null?Math.round(a):null,etaMs:a!=null?Math.round(a*d):null}}return{elapsedMs:n,done:e.endedMs!==null,phases:o,serial:i}}import*as Ty from"node:crypto";function Xl(){return{calls:0,succeeded:0,failed:0,reused:0,attempts:0,durationMs:0,inputTokens:0,outputTokens:0,cachedInputTokens:0,cacheCreationTokens:0,totalTokens:0}}function Kk(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 mc(e){let t=Xl();for(let n of e)Kk(t,n);return t}var Ts=e=>`${e.provider}\0${e.protocol}\0${e.model}`;function Vy(e){let t=new Map;for(let n of e){let o=Ts(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:mc(n.records)})).sort((n,o)=>Ts(n).localeCompare(Ts(o)))}function Zl(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:mc(o),byModel:Vy(o)})).sort((n,o)=>n.task.localeCompare(o.task))}function Cy(e){return Vy(e).map(t=>{let n=e.filter(o=>Ts(o)===Ts(t));return{...t,byTask:Zl(n).map(({task:o,totals:i})=>({task:o,totals:i}))}})}function jk(e){let t=e.updatedAt,n=new Map;for(let a of e.episodes)n.set(a.episode,a.runs);let o=new Map,i=new Map;for(let[a,c]of n){o.set(a,[]);for(let d of c)for(let p of d.recordIds){let l=i.get(p)??new Set;l.add(a),i.set(p,l)}}for(let a of e.records)for(let c of i.get(a.id)??[])o.get(c).push(a);let r=[...n.entries()].map(([a,c])=>{let d=o.get(a);return{episode:a,totals:mc(d),byTask:Zl(d),byModel:Cy(d),durationMs:c.reduce((p,l)=>p+l.durationMs,0),runs:c}}).sort((a,c)=>a.episode-c.episode),s=mc(e.records);return{...e,updatedAt:t,totals:s,byTask:Zl(e.records),byModel:Cy(e.records),episodes:r,timing:{totalDurationMs:e.runs.reduce((a,c)=>a+c.durationMs,0),modelDurationMs:s.durationMs,episodeDurationMs:r.reduce((a,c)=>a+c.durationMs,0)}}}function Hk(e){return{version:2,createdAt:e,updatedAt:e,totals:Xl(),byTask:[],byModel:[],episodes:[],runs:[],records:[],timing:{totalDurationMs:0,modelDurationMs:0,episodeDurationMs:0}}}function Cs(e){return new Date(e).toISOString()}var Fo=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=Cs(this.startedAtMs);if(this.report=t.has("usage.json")?t.readJson("usage.json"):Hk(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=Ty.randomUUID();startedAtMs;cursor;report;flush(t){this.write(this.append(t))}recordReusedEpisodes(t,n){if(n.length!==0){for(let o of n){this.executor.recordReuse(t);let i=this.now();this.append({scope:{kind:"episode",episode:o},status:"reused",startedAtMs:i,endedAtMs:i})}this.write(this.now())}}append(t){let n=t.endedAtMs??this.now(),o=t.startedAtMs??n,i=this.executor.usageEvents(),s=i.slice(this.cursor).map(a=>this.toRecord(a,t.scope));if(this.cursor=i.length,this.report.records.push(...s),t.scope.kind==="episode"){let a=t.scope.episode,c=this.report.episodes.find(p=>p.episode===a),d=c?.runs??[];d.push({runId:this.runId,status:t.status??"succeeded",startedAt:Cs(o),endedAt:Cs(n),durationMs:Math.max(0,n-o),stages:t.stages??{},recordIds:s.map(p=>p.id)}),c||this.report.episodes.push({episode:a,totals:Xl(),byTask:[],byModel:[],durationMs:0,runs:d})}return n}finish(t){let n=this.now();this.executor.usageEvents().length>this.cursor&&this.flush({scope:{kind:"run"},status:t==="succeeded"?"succeeded":"failed",endedAtMs:n});let o=this.report.runs.find(i=>i.id===this.runId);o&&(o.status=t,o.endedAt=Cs(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=Cs(t),this.report=jk(this.report),this.store.writeJson("usage.json",this.report)}};var tu="12",gc=e=>String(e).padStart(3,"0"),$y=e=>e.map(t=>JSON.stringify(t)).join(`
|
|
268
275
|
`)+`
|
|
269
|
-
`;function
|
|
276
|
+
`;function Qk(e,t,n){if(e.has("manifest.json")){let o=e.readJson("manifest.json");if(o.source?.sha256&&o.source.sha256!==t)throw new S("This workspace was built from a different source. --force cannot switch sources.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Choose a fresh --workspace-path for the new source.",data:{actual:["workspace source differs from --source-path"]}});if(!n&&o.pipeline_version&&o.pipeline_version!==tu)throw new S("This workspace was created by an older text-ingest pipeline.",{exitCode:k,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Rerun `scriptctl ingest --force` with the same source to rebuild its checkpoints.",data:{actual:[`workspace pipeline ${o.pipeline_version}; current ${tu}`]}})}if(n){for(let o of["pass1","pass2","pass3","pass5","serial"])eu.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"])eu.rmSync(e.path(o),{force:!0})}}async function Dy(e){let t=Ht(e.sourcePath);if(t.kind!=="text")throw new S("runTextIngest received a non-text source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=await Xa(t.path,t.ext),o=_e(n),i=new yt(e.workspacePath);i.ensure(),Qk(i,o,e.force??!1);let r=new br(c=>i.writeJson("timings.json",c)),s=new Fo(i,e.executor),a="failed";try{let c=Date.now(),d=0;if(!e.force&&i.has("pass1/body_start.json"))d=i.readJson("pass1/body_start.json").line??0,e.executor.recordReuse("ingest.body-start");else{let P=await ty(e.executor,n,e.signal);d=P.line,i.writeJson("pass1/body_start.json",P)}let p=n.split(`
|
|
270
277
|
`),l=d>0?p.slice(d).join(`
|
|
271
278
|
`):n,f=d>0?p.slice(0,d).join(`
|
|
272
|
-
`).trim().slice(0,6e3):"",u=Th(l);i.writeText("pass1/source.txt",n),i.writeJson("pass1/chunks.json",u.map(P=>({index:P.index,core_line_start:P.core_line_start,core_line_end:P.core_line_end}))),i.writeJson("manifest.json",{version:1,pipeline_version:Wl,updated:new Date().toISOString(),source:{path:br.resolve(t.path),sha256:o,kind:"text",ext:t.ext},chunks:u.length}),s.flush({scope:{kind:"phase",phase:"prepare"},status:"succeeded",startedAtMs:c});let h=0;r.phaseStart("normalize");let m=await ac(u,e.concurrency??30,async P=>{let pe=`pass2/chunk_${uc(P.index)}.json`,Ae=`pass2/chunk_${uc(P.index)}.error.json`;if(i.has(pe)&&!e.force){let Hi=Ul(i.readJson(pe),P);return i.clearError(Ae),h++,e.executor.recordReuse("ingest.text-normalize"),Hi}let{raw:Lt,records:zn}=await Fh(e.executor,P,e.signal);return i.writeText(pe,Lt),i.writeText(`pass2/chunk_${uc(P.index)}.jsonl`,Py(zn)),i.clearError(Ae),zn}),g=m.filter(P=>!P.ok);for(let P of g){let pe=P.error instanceof Error?P.error.message:String(P.error);i.writeJson(`pass2/chunk_${uc(P.index)}.error.json`,{chunk:P.index,error:pe})}if(s.flush({scope:{kind:"phase",phase:"normalize"},status:g.length?"failed":"succeeded"}),g.length>0)throw new S(`${g.length}/${u.length} chunk(s) failed normalization.`,{exitCode:k,errorCode:"INGEST_NORMALIZE_INCOMPLETE",hint:"Inspect pass2/chunk_NNN.error.json and rerun `scriptctl ingest` to resume.",data:{actual:g.map(P=>`chunk ${P.index}`)}});r.phaseEnd("normalize");let w,y,E;if(!e.force&&i.has("body.json"))w=i.readJson("body.json"),y=i.has("pass3/script.jsonl")?Os(i.readText("pass3/script.jsonl")).length:0,E=i.has("notes.json")?i.readJson("notes.json").length:0,h++;else{let P=[];for(let zn of m)zn.ok&&P.push(...zn.value);i.writeText("pass3/script.jsonl",Py(P));let pe=Os(i.readText("pass3/script.jsonl")),Ae=Dk(t.path),Lt=Ch(pe,{title:Ae});i.writeJson("notes.json",Lt.notes),w=Lt.script,i.writeJson("body.json",w),y=P.length,E=Lt.notes.length}fh(w,Ha(o),d);let _=P=>String(P).padStart(3,"0"),x=(P,pe)=>`serial/win_${_(P)}_${_(pe)}.json`,A={readUpdate:(P,pe)=>i.has(x(P,pe))?i.readText(x(P,pe)):void 0,writeStep:(P,pe,Ae,Lt)=>{i.writeText(`serial/context_${_(P)}.md`,Ae),i.writeText(x(P,pe),Lt)},readArc:(P,pe)=>{let Ae=`serial/arc_${_(P)}_${_(pe)}.md`;return i.has(Ae)?i.readText(Ae):void 0},writeArc:(P,pe,Ae)=>{i.writeText(`serial/arc_${_(P)}_${_(pe)}.md`,Ae)},readNameFix:(P,pe)=>{let Ae=`serial/fix_${_(P)}_${_(pe)}.json`;return i.has(Ae)?i.readText(Ae):void 0},writeNameFix:(P,pe,Ae)=>i.writeText(`serial/fix_${_(P)}_${_(pe)}.json`,Ae)};r.phaseStart("serial");let b=await xy(w,{executor:e.executor,checkpoint:A,force:e.force??!1,...f?{sourceRef:f}:{},onWindow:P=>{P.index===0&&r.serialStart(P.total,P.totalEpisodes),r.windowDone(P.startEp,P.endEp,P.ms,P.cached);let pe=P.startEp===P.endEp?{kind:"episode",episode:P.startEp}:{kind:"episode-range",startEpisode:P.startEp,endEpisode:P.endEp},Ae=Date.now();s.flush({scope:pe,status:P.cached?"reused":"succeeded",startedAtMs:Ae-P.ms,endedAtMs:Ae})},...e.signal?{signal:e.signal}:{}}),U=b.doc;h+=b.reused,r.phaseEnd("serial"),r.phaseStart("govern");let{script:v,idMap:I}=rc(U);i.writeJson("id_map.json",I);let R=St(v);if(!R.ok)throw i.writeJson("validation.json",R),new S("Intermediate script failed validation before v4 identity assignment.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:R.errors.slice(0,5).map(P=>`${P.path}: ${P.message}`)}});let C=!e.force&&i.has("v4_identity_map.json")?i.readJson("v4_identity_map.json"):void 0,N=Ir(Gt(U),C,b.identityKeys),M=N.script,K=Te(M),X=[],Ke=Date.now(),se="failed";try{if(K.ok){let P=await Oy(i,M,e.executor,{force:e.force??!1,...e.signal?{signal:e.signal}:{}});X=Ry(P.report)}se="succeeded"}finally{s.flush({scope:{kind:"phase",phase:"asset-audit"},status:se,startedAtMs:Ke})}let z={...K,warnings:[...K.warnings,...Sr(M),...X]};if(i.writeJson("pass5/script.json",M),i.writeJson("v4_identity_map.json",N.identityMap),i.writeJson("validation.json",z),!z.ok)throw new S("Final script.json failed v4 validation.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:z.errors.slice(0,5).map(P=>`${P.path}: ${P.message}`)}});i.writeJson("script.json",M),r.phaseEnd("govern"),r.finish();let Nt=M;return a="succeeded",{workspacePath:i.root,chunks:u.length,reused:h,records:y,notes:E,assets:{actors:Nt.actors?.length??0,locations:Nt.locations?.length??0,props:Nt.props?.length??0},scriptPath:i.path("script.json"),validation:{ok:z.ok,errors:z.errors.length,warnings:z.warnings.length}}}finally{s.finish(a)}}function Dk(e){return br.basename(e,br.extname(e))}import*as mo from"node:fs";import*as Ci from"node:path";import{createHash as db}from"node:crypto";var Gk=()=>({apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:[],voice:""});function Fo(){return{lastEpisode:0,registry:[],digests:[],openThreads:[]}}var Ie=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),mc=(e,t)=>e.length>t?`${e.slice(0,t)}\u2026`:e;function Bk(e,t){let n=Ie(t);return e.find(o=>Ie(o.name)===n||Ie(o.identitySeed)===n||o.aliases.some(i=>Ie(i)===n))}var Jk=3,zk=12e3;function Pi(e,t){let n=(t??"").trim();n&&!e.includes(n)&&e.push(n)}var Kk=["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","voice"];function fc(e,t,n){if(!t)return e;let o=e?{...e,persistent_marks:[...e.persistent_marks]}:Gk();for(let i of Kk){let r=t[i]?.trim()??"";r&&(n||!o[i])&&(o[i]=r)}for(let i of t.persistent_marks??[])Pi(o.persistent_marks,i);return o}function eu(e,t,n){let o=t.name.trim();if(!o)return;let i=t.description.trim(),r=e.find(s=>Tn(s.name)===Tn(o));if(!r){e.push({name:o,description:i});return}i&&(n||!r.description)&&(r.description=i)}function Xl(e,t,n,o=!1){let i=(s,a)=>{let c=(a??"").trim();return c&&(o||!s)?c:s};for(let s of t.add_recognition_anchors??[])Pi(e.recognitionAnchors,s);e.identityProfile=fc(e.identityProfile,t.identity_profile_patch,o),t.identity_revision&&(e.identityProfile={...t.identity_revision.profile,persistent_marks:[...t.identity_revision.profile.persistent_marks]},e.recognitionAnchors=[...t.identity_revision.recognition_anchors]);let r=i(e.appearance,t.appearance);r&&(e.appearance=r),e.role=t.identity_revision&&t.role!==void 0?t.role.trim():i(e.role,t.role)??e.role;for(let s of t.add_aliases??[])Pi(e.aliases,s);for(let s of t.add_states??[])eu(e.states,s,o);e.lastEpisode=n}function Cs(e,t,n){let o=r=>Bk(e.registry,r);for(let r of t.registry_delta.new_entities){let s=r.name.trim();if(!s||r.kind==="actor"&&ut(s))continue;let a=o(s);if(a){Xl(a,{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 c=[];for(let p of r.states??[])eu(c,p,!1);let d=[];for(let p of r.aliases??[])Pi(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:fc(void 0,r.identity_profile,!0)}:{},...r.appearance?{appearance:r.appearance.trim()}:{},role:(r.role??"").trim(),aliases:d,states:c,firstEpisode:n,lastEpisode:n})}for(let r of t.registry_delta.enrich){if(r.identity_revision)continue;let s=o(r.name);s&&Xl(s,r,n,!0)}for(let r of t.registry_delta.canonicalize){let s=o(r.from_name),a=r.canonical_name.trim();if(!s||!a||Ie(a)===Ie(s.name))continue;let c=o(a);if(c&&c!==s){let d=s.firstEpisode<c.firstEpisode?s:c,p=d===s?c:s,l=d.states.map(h=>({...h})),f=new Set([...s.aliases,...c.aliases,s.identitySeed,c.identitySeed,s.name,c.name,r.from_name].map(h=>h.trim()).filter(Boolean));d.name=a,d.status="canonical",d.importance=s.importance==="featured"||c.importance==="featured"?"featured":"background",d.recognitionAnchors=[];for(let h of[...s.recognitionAnchors,...c.recognitionAnchors])Pi(d.recognitionAnchors,h);let u=fc(void 0,s.identityProfile,!0);d.identityProfile=fc(u,c.identityProfile,!0),(c.appearance||s.appearance)&&(d.appearance=c.appearance||s.appearance),d.role=c.role||s.role,d.states=[];for(let h of[...l,...p.states])eu(d.states,h,!1);d.aliases=[...f].filter(h=>Ie(h)!==Ie(a)),d.firstEpisode=Math.min(s.firstEpisode,c.firstEpisode),d.lastEpisode=Math.max(s.lastEpisode,c.lastEpisode,n),e.registry.splice(e.registry.indexOf(p),1);continue}Pi(s.aliases,s.name),Pi(s.aliases,r.from_name),s.name=a,s.status="canonical",s.aliases=s.aliases.filter(d=>Ie(d)!==Ie(a)),s.lastEpisode=n}for(let r of t.registry_delta.enrich){if(!r.identity_revision)continue;let s=o(r.name);s&&Xl(s,r,n,!0)}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(a=>a.id!==s&&a.text!==s))}return e.digests.push({episode:n,synopsis:(t.synopsis??"").trim()}),e.lastEpisode=n,e}function $y(e,t){return e.digests.push({episode:t,synopsis:"",outcome:"skipped"}),e.lastEpisode=t,e}function jk(e,t){let n=[],o=e.status==="provisional"?"\xB7\u5F85\u5B9A \u26A0":`\xB7${e.importance}`;n.push(`### ${e.name} ${o}`),e.role&&n.push(`- \u8EAB\u4EFD\u5173\u7CFB\u8BB0\u5F55\uFF08\u5F85\u6838\uFF09: ${mc(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}`)}if(e.aliases.length&&n.push(`- \u66FE\u7528\u79F0\u547C: ${e.aliases.join("\u3001")}`),e.states.length){n.push("- \u5DF2\u767B\u8BB0\u9636\u6BB5\uFF08\u540D\u79F0\u9010\u5B57\u7528\u4E8E\u5F15\u7528\uFF0C\u63CF\u8FF0\u6309\u9002\u7528\u9636\u6BB5\u6838\u5BF9\uFF09\uFF1A");for(let r of e.states)n.push(` - ${r.name}\uFF1A${r.description||"\u63CF\u8FF0\u5F85\u8865"}`)}return 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 Ty(e,t){let n=mc(e.appearance||e.role||"",t?30:60),o=e.states.map(i=>i.description?`${i.name}\uFF08${mc(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 Vy(e,t,n){let o=[];o.push(`# \u5148\u524D\u767B\u8BB0\uFF08\u89E3\u6790\u7B2C ${e.lastEpisode+1} \u96C6\u65F6\u6838\u5BF9\u672C\u8868\uFF09`,""),o.push("\u4F9D\u636E\u6765\u6E90\u4FDD\u6301\u4EBA\u7269\u8EAB\u4EFD\u8FDE\u7EED\u3002\u4EBA\u7269 role \u91CD\u5199\u4E3A\u5DF2\u786E\u8BA4\u7684\u8EAB\u4EFD\u79F0\u8C13\u4E0E\u5173\u7CFB\uFF1B\u5176\u4E2D\u6DF7\u5165\u7684\u5916\u8C8C\u6309\u9002\u7528\u9636\u6BB5\u5F52\u5165 state\u3002\u5168\u90E8\u5916\u8C8C\u4E0E\u58F0\u7EBF\u7531\u5404 state \u72EC\u7ACB\u627F\u8F7D\uFF0C\u65E2\u6709\u753B\u50CF\u4E0E\u8BC6\u522B\u951A\u70B9\u4F5C\u4E3A\u5F85\u6838\u89C2\u5BDF\uFF0C\u4F9D\u636E\u5404\u9636\u6BB5\u8BC1\u636E\u8865\u5168\u76F8\u5E94 state\uFF0C\u5E76\u4EE5\u5168\u7A7A identity_revision \u6E05\u7A7A\u753B\u50CF\u4E0E\u951A\u70B9\u3002","");let i=e.registry.filter(c=>c.kind==="actor"),r=e.registry.filter(c=>c.kind==="location"),s=e.registry.filter(c=>c.kind==="prop");if(i.length){o.push("## \u4EBA\u7269","");for(let c of i)o.push(...jk(c,n),"")}if(r.length||s.length){o.push("## \u573A\u666F / \u9053\u5177","");for(let c of r)o.push(Ty(c,n));for(let c of s)o.push(Ty(c,n));o.push("")}let a=e.digests.filter(c=>c.episode>e.lastEpisode-t);if(a.length){o.push("## \u5267\u60C5\u8FDB\u5C55","");for(let c of[...a].sort((d,p)=>d.episode-p.episode))o.push(c.outcome==="skipped"?`\u7B2C${c.episode}\u96C6\u5DF2\u4EBA\u5DE5\u8DF3\u8FC7\uFF0C\u5267\u60C5\u672A\u77E5\u3002`:`\u7B2C${c.episode}\u96C6\uFF1A${n?mc(c.synopsis,40):c.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 c of e.openThreads)o.push(`- [${c.id}] ${c.text}`);o.push("")}return o.join(`
|
|
273
|
-
`)}function gc(e){for(let t=Jk;t>=1;t--){let n=Vy(e,t,!1);if(n.length<=zk)return n}return Vy(e,1,!0)}function Yo(e){let t=new Map;for(let n of e)for(let o of[n.identitySeed,...n.aliases])Ie(o)!==Ie(n.name)&&t.set(o,n.name);return t}function Hk(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 Dy(e,t){let n=new Map,o=new Map,i=(s,a)=>{let c=Ie(s),d=a.trim();!d||Ie(d)===c||(o.has(c)||o.set(c,new Set),o.get(c).add(d))};for(let s of t){n.set(Ie(s.name),s.importance);for(let a of s.aliases)n.set(Ie(a),s.importance);n.set(Ie(s.identitySeed),s.importance);for(let a of new Set([s.identitySeed,...s.aliases]))i(s.name,a)}let r=(s,a)=>{for(let c of s??[]){let d=String(c[a]??""),p=[d,...c.aliases??[]],l;for(let h of p)if(l=t.find(m=>Ie(m.name)===Ie(h)||Ie(m.identitySeed)===Ie(h)||m.aliases.some(g=>Ie(g)===Ie(h))),l)break;c.importance=l?.importance??n.get(Ie(d))??"featured";let f=o.get(Ie(d));if(f?.size&&(c.aliases=[...new Set([...c.aliases??[],...f])]),!l)continue;let u=l.kind==="actor"?Hk(l):[l.appearance,l.role].map(h=>(h?.trim()??"").replace(/[。;]+$/,"")).filter(Boolean).join("\uFF1B");u&&(c.description=`${u}\u3002`);for(let h of c.states??[]){let m=l.states.find(g=>Tn(g.name)===Tn(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 Gy(e,t,n){let o=Yo(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)}:ut(d)?{kind:"group",label:d}:{name:i(d)}},s=0,a={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 E=y.speaker.name;u.some(_=>_.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:zo(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}})}))},c=new Set(t.registry.map(d=>`${d.kind}:${d.name}`));for(let d of a.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=>!c.has(u));if(f.length)throw new S(`Comic scene references assets absent from the registry: ${f.join(", ")}`,{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"The episode must register every referenced character, location and key prop.",data:{actual:f}})}return a}var vr=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();function Qk(e,t,n){let o=Yo(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&&vr(g.name)===vr(f))??l,m=`${l.kind}:${vr(f)}`;r.has(m)||r.set(m,`${n}:${h.kind}:${h.firstEpisode}:${vr(h.identitySeed)}`)}let s={},a={},c={},d={},p={actor:s,location:a,prop:c};for(let l of e){let f=l.names[0]??l.provisional_id,u=r.get(`${l.kind}:${vr(f)}`)??`${n}:${l.kind}:source:${vr(f)}`;p[l.kind][l.provisional_id]=u,d[l.provisional_id]=Object.fromEntries(l.states.map(h=>[h.id,`${u}:state:${Tn(h.name)}`]))}return{actor:s,location:a,prop:c,state:d}}function hc(e,t,n,o){let{script:i,assets:r,identityKeys:s}=nc(e);Dy(i,t.registry);let a=cc(i),{script:c,idMap:d}=rc(a),p=St(c);if(!p.ok)return{initial:i,final:c,idMap:d,validation:p,identityMap:o,scriptV4:null};let l=Ir(Gt(a),o,{...Qk(r,t.registry,n),...s}),f=l.script,u=Te(f);return{initial:i,final:f,scriptV4:f,idMap:d,identityMap:l.identityMap,validation:{...u,warnings:[...u.warnings,...Sr(f)]}}}import*as By from"node:fs";import*as uo from"node:path";import{createHash as Fk}from"node:crypto";import{PDFDocument as Yk}from"pdf-lib";import*as yc from"node:path";function Or(e){let t=yc.basename(e,yc.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 qk(e){let t=e.kind==="comic-file"?[e.path]:e.files,n=t.map(i=>({path:i,sourceNumber:Or(i)})),o=n.flatMap(i=>i.sourceNumber===null?[]:[i.sourceNumber]);if(o.length>0&&o.length!==t.length||new Set(o).size!==o.length)throw new S("Comic chapter ordering is ambiguous.",{exitCode:k,errorCode:"INGEST_COMIC_DISCOVERY",hint:"Give every PDF a unique chapter number, or use unnumbered filenames that sort in reading order.",data:{actual:t.map(i=>uo.basename(i))}});return n.sort((i,r)=>i.sourceNumber!==null&&r.sourceNumber!==null?i.sourceNumber-r.sourceNumber:uo.basename(i.path).localeCompare(uo.basename(r.path),"zh-Hans",{numeric:!0}))}async function Jy(e){let t=[];for(let[n,o]of qk(e).entries()){let i=By.readFileSync(o.path),s=(await Yk.load(i,{updateMetadata:!1})).getPageCount();if(!s)throw new S("PDF is outside the document provider limits.",{exitCode:k,errorCode:"INGEST_COMIC_SIZE",hint:"Provide a PDF containing at least one readable page.",data:{actual:[`${o.path}: ${s} pages, ${i.length} bytes`]}});t.push({episode:n+1,document_id:`chapter-${String(n+1).padStart(3,"0")}`,source_number:o.sourceNumber,title:uo.basename(o.path,uo.extname(o.path)),path:uo.resolve(o.path),sha256:Fk("sha256").update(i).digest("hex"),page_count:s,size_bytes:i.length})}return t}function zy(e,t){let n=e.find((o,i)=>{let r=t[i];return!r||o.sha256!==r.sha256||o.source_number!==r.source_number||o.title!==r.title});if(n)throw new S("The comic source prefix changed.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Restore the original chapters or use a fresh workspace. Only tail chapters may be appended.",data:{actual:[n.title]}})}import{PDFDocument as Zk,StandardFonts as Wk,rgb as Xk,pushGraphicsState as eb,popGraphicsState as tb,concatTransformationMatrix as wc}from"pdf-lib";async function Ky(e){let t=await Zk.load(e),n=await t.embedFont(Wk.Helvetica),o=Xk(0,.45,.85);for(let i of t.getPages()){let r=i.getCropBox(),s=(i.getRotation().angle%360+360)%360,a=s===90||s===270,c=a?r.height:r.width,d=a?r.width:r.height;switch(i.pushOperators(eb()),s){case 90:i.pushOperators(wc(0,1,-1,0,r.x+r.width,r.y));break;case 180:i.pushOperators(wc(-1,0,0,-1,r.x+r.width,r.y+r.height));break;case 270:i.pushOperators(wc(0,-1,1,0,r.x,r.y+r.height));break;default:i.pushOperators(wc(1,0,0,1,r.x,r.y))}let p=c/70;for(let l=0;l<=1e3;l+=50){let f=d*(1-l/1e3);i.drawLine({start:{x:0,y:f},end:{x:c,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,c-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=c*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(tb())}return t.save()}import*as jy from"node:fs";import*as Hy from"node:path";import nb from"proper-lockfile";async function qo(e,t){let n=Hy.resolve(e);jy.mkdirSync(n,{recursive:!0});let o=null;try{o=await nb.lock(n,{realpath:!1,stale:12e4,update:1e4,retries:0})}catch(i){throw new S("The ingest workspace is busy.",{exitCode:q,errorCode:"INGEST_WORKSPACE_BUSY",hint:"Wait for the other ingest or skip command to finish, then retry.",data:{actual:[n,i instanceof Error?i.message:String(i)]}})}try{return await t()}finally{await o()}}import*as fo from"node:fs";import*as nu from"node:path";import{PDFDocument as tu}from"pdf-lib";import{z as Rr}from"zod";var Qy=Rr.object({starts:Rr.array(Rr.object({page:Rr.number().int().min(1),title:Rr.string().min(1)}))}),ob="\u9605\u8BFB\u6F2B\u753B PDF \u5E76\u8BC6\u522B\u5B9E\u9645\u8BDD/\u7AE0\u8282\u8FB9\u754C\u3002\u53EA\u8F93\u51FA\u672C\u6BB5\u5185\u786E\u5B9E\u5F00\u59CB\u7684\u65B0\u8BDD\u7684\u8D77\u59CB\u7269\u7406\u9875\u7801\u548C\u539F\u7A3F\u6807\u9898\u3002\u4F9D\u636E\u8BDD\u53F7\u3001\u7AE0\u8282\u6249\u9875\u3001\u6807\u9898\u53CA\u53D9\u4E8B\u8FDE\u7EED\u6027\u7EFC\u5408\u5224\u65AD\uFF1B\u573A\u666F\u5207\u6362\u3001\u56DE\u5FC6\u3001\u6362\u9875\u548C\u5E7F\u544A\u4E0D\u662F\u65B0\u8BDD\u3002\u8F93\u5165\u53EF\u80FD\u4ECE\u4E00\u8BDD\u4E2D\u95F4\u5F00\u59CB\uFF0C\u5EF6\u7EED\u524D\u6BB5\u7684\u5185\u5BB9\u4E0D\u7B97\u65B0\u8BDD\u3002\u7B2C\u4E00\u6BB5\u4ECE\u539F\u6587\u6863\u7B2C\u4E00\u9875\u5F00\u59CB\u65F6\uFF0C\u4E3A\u7B2C\u4E00\u8BDD\u5EFA\u7ACB\u8D77\u70B9\uFF0C\u5C01\u9762\u548C\u76EE\u5F55\u968F\u9996\u8BDD\u4FDD\u7559\u3002\u591A\u8BDD\u5408\u96C6\u9010\u9879\u5217\u51FA\u5404\u8BDD\uFF1B\u5355\u8BDD\u6587\u4EF6\u53EA\u6709\u4E00\u4E2A\u8D77\u70B9\u3002page \u4F7F\u7528\u672C\u6B21\u8F93\u5165 PDF \u4ECE 1 \u5F00\u59CB\u7684\u7269\u7406\u9875\u7801\u3002\u6807\u9898\u4FDD\u7559\u539F\u8BDD\u53F7\u548C\u53EF\u8BFB\u8BDD\u540D\uFF1B\u65E0\u6CD5\u786E\u8BA4\u8BDD\u53F7\u65F6\u4F7F\u7528\u7B80\u77ED\u5185\u5BB9\u6807\u9898\u3002";async function Fy(e,t,n,o){let i=[];for(let r of e){let s=`sources/${r.sha256}.chapters.json`,a,c=await tu.load(fo.readFileSync(r.path));if(t.has(s))a=t.readJson(s);else{a=[];for(let d=0;d<r.page_count;){let p=Math.min(40,r.page_count-d),l;for(;;){let h=await tu.create();for(let m of await h.copyPages(c,Array.from({length:p},(g,w)=>d+w)))h.addPage(m);if(l=await h.save(),l.length<=4e7||p===1)break;p=Math.ceil(p/2)}let f=t.path(`sources/${r.sha256}.scan.pdf`);fo.mkdirSync(nu.dirname(f),{recursive:!0}),Vn(f,Buffer.from(l)),process.stderr.write(`\u8BC6\u522B\u6F2B\u753B\u7AE0\u8282 \xB7 ${r.title} \xB7 \u539F\u7A3F ${d+1}\u2013${d+p} / ${r.page_count} \u9875
|
|
274
|
-
`);let u=await n.prepare(f,o);try{let h=await n.generate({media:u,system:ob,user:`\u539F\u6587\u4EF6\uFF1A${r.title}\uFF0C\u5171 ${r.page_count} \u9875\u3002\u672C\u6BB5\u4E3A\u539F\u7A3F\u7B2C ${d+1}\u2013${d+p} \u9875\u3002\u5DF2\u8BC6\u522B\u8D77\u70B9\uFF1A${JSON.stringify(a)}\u3002`,responseJsonSchema:Rr.toJSONSchema(Qy,{target:"openapi-3.0"}),signal:o}),m=Qy.parse(JSON.parse(h.text));a.push(...m.starts.filter(g=>g.page<=p).map(g=>({...g,page:d+g.page})))}finally{await n.release(u,o)}d+=p}a=[...new Map(a.sort((d,p)=>d.page-p.page).map(d=>[d.page,d])).values()],a.length?a[0].page=1:a.push({page:1,title:r.title}),t.writeJson(s,a)}for(let[d,p]of a.entries()){let l=(a[d+1]?.page??r.page_count+1)-1,f=i.length+1,u=a.length===1?r.path:t.path(`sources/${r.sha256}.${p.page}-${l}.pdf`);if(!fo.existsSync(u)){let h=await tu.create();for(let m of await h.copyPages(c,Array.from({length:l-p.page+1},(g,w)=>p.page-1+w)))h.addPage(m);fo.mkdirSync(nu.dirname(u),{recursive:!0}),Vn(u,Buffer.from(await h.save()))}i.push({...r,episode:f,document_id:`chapter-${String(f).padStart(3,"0")}`,title:a.length===1?r.title:p.title,path:u,page_count:l-p.page+1,size_bytes:fo.statSync(u).size,original_path:r.path,original_page_count:r.page_count,start_page:p.page,end_page:l})}}return i}import{z as Yy}from"zod";var xc=En,ib=xc(7);function iu(e,t){let n=xc,o=Ka[n(1)](JSON[n(12)](e)),i=c=>{let d=n;throw new S(d(14)+c[d(21)]("; "),{exitCode:k,errorCode:d(44),hint:d(23),data:{actual:c}})};if(!o[n(17)])return i(o[n(37)][n(18)][n(15)](0,8)[n(38)](c=>c[n(10)][n(21)](".")+": "+c[n(9)]));let r=o[n(41)],s=new Set;for(let c of r[n(43)])for(let d of c[n(20)]){if(d[n(28)][n(42)]((l,f)=>l>t||f>0&&l<=d[n(28)][f-1]))return i([n(24)+d[n(28)][n(21)](", ")+n(25)+t+n(34)]);let p=Ss(d[n(28)],d[n(29)]);if(p[n(30)])return i(p);for(let l of d[n(28)])s[n(40)](l)}for(let c of r[n(6)]){if(c[n(36)]>t||s[n(13)](c[n(36)]))return i([n(27)+c[n(36)]]);s[n(40)](c[n(36)])}let a=Array[n(33)]({length:t},(c,d)=>d+1)[n(19)](c=>!s[n(13)](c));return a[n(30)]?i([n(31)+a[n(21)](", ")]):r}async function qy(e,t,n,o,i,r,s){let a=xc,c=await e[a(2)]({media:t,system:ib,user:a(3)+n+a(22)+o+a(0)+i,responseJsonSchema:Yy[a(5)](qg,{target:a(35)}),signal:s});return r(c[a(26)]),iu(c[a(26)],o)}function ou(){let e=["ioMHTE+8JoIVT+wUJoAvToMyHEIVU+w5TUAmIEMHUUw6J+MaKoAGVoI9RowgMEwfQoMdQowjP+AdHEoaGGOk","C2fMzvbHCNnL","z2vUzxjHDgu","5B2t5yMn6k+D77YA","5Qc55O2U5y6F5RYR55s75zkm5BEY6l2S5B2v5Q2J5PAh5Pw055cg5A6m5Pw06lwe5lQN55M76k6W44cc6l+u5zUEihjLz2LZDhj5x2rLBhrHiowVUEIXOE+8Jos/NEEvMEATO+EHRUEzU+IUSo+8JoIHPEM9KoATO+AwH+wUNUMzHEw8LEEuQoEAHos6UUEjQEoaGEwCSoEcUEwsJowfS+MuRUMbK+wfT++8JoINHoImG+wqJEs4JUw8LEEuQoMaKowTL+s4GoIhTooaGUs+NEAnRUwoN+EOV+ApJ+I/SowpR+INGEwKLUINGU+8M+wqJos4GoI6Q+s7VEEuQowiQ+wqJEwsJcbJyw5VBMLJywXPEMuG5B2s5BM244cc5l+D55wz5BEY6l2S5B2v5Q2J5PAh55Qe5ywO6yoO5yAf5A6544cc","Dg9ku09ou2nOzw1H","AwDUB3jLzf9WywDLCW","5l2G5PIV5RYR55s76l2S5yMN5PYS55Qe5lIY6kgm6kEJ5P6q5zMO44cc6l6t5ywL5PIV5A6m5Pw05lIa6k+DifberIdLKOZLIy3PNAlLKitOR53NTk/NP6/NMOtLT7lNN6xORR7LRPRJGilOVPpLH7RKUidKUkRNRkBLKiGGC2nOzw1HioEAHcbku09oiowVUEIXOE+8JowqJoAxTUwmHEwqQ+ACRoIVNEMaKoAGVowjP+ACRooaGEI1Hos6P+wINU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ROZMIjdLIy3KU47NRkZKUidPOBxLIldMNkVPOBxPGjdPOBxMOlJLR7NVVjRMR4/POBxLIAFMG4xPG73LT7lOVAZLHPNVViZMIydMNiNLJ6/OVQJORQtLJ7dOR43LKOZNLlVPNAlMLOFLRzFPG73LT7lLH7RNJRdVViZLHOxLRRNPOBRLUO/MRApNOA7VVjVKU4xMLBtPOBxNQBRNMB3JGihLSihPNAlJGihLIlBKVzZKV6hMGA/LJ6/KU6xLIjFLHAuGAwDUB3jLzf9WywDLCYdLUBBLHPNLJP/LM6dJGilKUi3OPOhLNkGGywn0Aw9UCYdKUi4GAwDUB3jLzf9WywDLCYdLKiZML7BNMBVORRdLKiZKUidPOBxJGijZEw5VChnPCYdLJ6RMPOlMI6ZMNkZOR53VViZKUi3OG73KU6pMM7/MRApMLOFJGii","CMvNAxn0CNLFzgvSDge","BwvZC2fNzq","Cgf0Aa","C2HHCgu","CgfYC2u","AgfZ","q29TAwmGzxbPC29KzsbMywLSzwqGDhjHBNnJCMLWDcb2ywXPzgf0Aw9UoIa","C2XPy2u","cUMCGoIMGEINO+wgS++8MG","C3vJy2vZCW","AxnZDwvZ","zMLSDgvY","ywn0Aw9UCW","AM9PBG","44cc5PYSifberIdLHBeG","sw5ZCgvJDcbLCc8QlNjLC3bVBNnLlMPZB24Gyw5KihjLCNvUigLUz2vZDcb3AxrOihrOzsbZyw1LihnVDxjJzsbHBMqGD29YA3nWywnLlG","sw52ywXPzcbVCIb1BM9YzgvYzwqGC291CMnLihbHz2vZoIa","oYbKB2n1BwvUDcbOyxmG","Dgv4Da","sw52ywXPzcbVCIbKDxbSAwnHDguGAwDUB3jLzcbWywDLoIa","CgfNzxm","CMvNAw9UCW","BgvUz3rO","ugfNzxmGywjZzw50igzYB20GDhjHBNnJCMLWDdOG","cUw3SUACIEI9Row9LE+8MG","zNjVBq","ihbHz2vZlG","B3bLBMfWAs0ZlJa","CgfNzq","zxjYB3i","BwfW","C3rYAw5NAwz5","ywrK","zgf0yq","C29Tzq","C2nLBMvZ","su5hrvnux0nptuLdx1nfuKLbtf9gquLmruq"];return ou=function(){return e},ou()}async function Zy(e,t,n,o,i,r){let s=xc,a=Ka[s(11)][s(8)],c=await e[s(2)]({media:t,signal:r,system:s(4),user:o+s(16)+i+s(32)+JSON[s(39)](n),responseJsonSchema:Yy[s(5)](a,{target:s(35)})});return a[s(12)](JSON[s(12)](c[s(26)]))}function En(e,t){e=e-0;let n=ou(),o=n[e];if(En.pkbepj===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};En.AcwwSN=i,En.wSoQuY={},En.pkbepj=!0}let r=n[0];En.aUTMuq!==r&&(En.wSoQuY={},En.aUTMuq=r);let s=En.wSoQuY[e];return s===void 0?(o=En.AcwwSN(o),En.wSoQuY[e]=o):o=s,o}function Ec(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function rb(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 sb(e){if(e instanceof T)return{failure:e.failure,attempts:e.modelFailures};if(e instanceof S){let t=e.errorCode==="INGEST_VALIDATION_FAILED"||e.errorCode==="INGEST_VIDEO_SERIAL_FAILED"||e.errorCode==="INGEST_COMIC_SERIAL_FAILED";return{failure:Vt(rb(e),{retryable:t,message:e.message}),attempts:[]}}return{failure:Vt({failure_type:"unknown",failure_code:"unknown"},{retryable:!1,message:e instanceof Error?e.message:String(e)}),attempts:[]}}function _c(e,t,n){let o=sb(e);return{schema_version:1,unit:{kind:"episode",episode:t},phase:n,occurred_at:new Date().toISOString(),...o}}function Xy(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 Wy(e,t){return typeof e=="string"&&t.some(n=>n===e)}function Mr(e){return typeof e=="string"?e:void 0}function ab(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!Ec(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 cb(e){let t=e.provider_source,n=e.provider_reason;return{provider:Mr(e.provider),model:Mr(e.model),operation:Mr(e.operation),http_status:typeof e.http_status=="number"?e.http_status:void 0,system_code:Mr(e.system_code),provider_source:Wy(t,["prompt","candidate"])?t:void 0,provider_reason:Wy(n,["SAFETY","PROHIBITED_CONTENT","BLOCKLIST","SPII","RECITATION","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION","OTHER","UNSPECIFIED","UNKNOWN"])?n:void 0,provider_reason_raw:Mr(e.provider_reason_raw),finish_message:Mr(e.finish_message),safety_ratings:ab(e.safety_ratings),details:Array.isArray(e.details)&&e.details.every(i=>typeof i=="string")?e.details:void 0}}function Ts(e){if(!Ec(e))return null;let t=If(e.failure_type,e.failure_code);return!t||typeof e.retryable!="boolean"||typeof e.message!="string"?null:Vt(t,{...cb(e),retryable:e.retryable,message:e.message})}function Vs(e){if(!Ec(e)||e.schema_version!==1)return null;let t=e.unit;if(!Ec(t)||t.kind!=="episode"||typeof t.episode!="number"||typeof e.phase!="string"||typeof e.occurred_at!="string")return null;let n=Ts(e.failure);if(!n||!Array.isArray(e.attempts))return null;let o=[];for(let i of e.attempts){let r=Ts(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 ew="comic-1",Sc=e=>String(e).padStart(3,"0"),tw=["script.initial.json","id_map.json","validation.json","context.json","v4_identity_map.json","script.json"];function Ic(e,t,n){let o=hc(Gy(e,t.context,n),t.context,"comic",t.identityMap);if(!o.scriptV4||!o.validation.ok)throw new S("Comic script failed validation.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect the current episode response and rerun ingest with the same source and workspace.",data:{actual:o.validation.errors.slice(0,8).map(i=>`${i.path}: ${i.message}`)}});for(let[i,r]of o.scriptV4.episodes.entries())r.synopsis=e[i].output.synopsis;return{...o,scriptV4:o.scriptV4}}function ru(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 pb(e){let t=Ht(e.sourcePath);if(t.kind!=="comic-file"&&t.kind!=="comic-directory")throw new S("Expected PDF comic source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=new yt(Ci.resolve(e.workspacePath));n.ensure();let o=n.has("manifest.json")?n.readJson("manifest.json"):null;if(o&&o.pipeline_version!==ew)throw new S("This workspace belongs to another ingest pipeline.",{exitCode:k,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Choose a fresh workspace."});if(!o&&n.has("script.json"))throw new S("Workspace already contains an unmanaged script.json.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Choose a fresh workspace."});let i=await Jy(t),r=o&&!o.episodes.some(w=>w.original_path)?i:await Fy(i,n,e.executor.documentPort("ingest.comic-serial"),e.signal);o&&zy(o.episodes,r);let s={version:1,pipeline_version:ew,updated:new Date().toISOString(),source:{kind:t.kind,path:Ci.resolve(t.path),sha256:db("sha256").update(r.map(w=>w.sha256).join(`
|
|
275
|
-
`)).digest("hex")},episodes:r,...o?.current_error?{current_error:o.current_error}:{}};if(e.force){for(let w of o?.episodes??[])for(let y of["json","response.json","context.md","error.json","input.pdf"])mo.rmSync(n.path(`ep/ep_${
|
|
279
|
+
`).trim().slice(0,6e3):"",u=Gh(l);i.writeText("pass1/source.txt",n),i.writeJson("pass1/chunks.json",u.map(P=>({index:P.index,core_line_start:P.core_line_start,core_line_end:P.core_line_end}))),i.writeJson("manifest.json",{version:1,pipeline_version:tu,updated:new Date().toISOString(),source:{path:vr.resolve(t.path),sha256:o,kind:"text",ext:t.ext},chunks:u.length}),s.flush({scope:{kind:"phase",phase:"prepare"},status:"succeeded",startedAtMs:c});let h=0;r.phaseStart("normalize");let m=await pc(u,e.concurrency??30,async P=>{let pe=`pass2/chunk_${gc(P.index)}.json`,Ae=`pass2/chunk_${gc(P.index)}.error.json`;if(i.has(pe)&&!e.force){let Qi=Tl(i.readJson(pe),P);return i.clearError(Ae),h++,e.executor.recordReuse("ingest.text-normalize"),Qi}let{raw:Lt,records:zn}=await Zh(e.executor,P,e.signal);return i.writeText(pe,Lt),i.writeText(`pass2/chunk_${gc(P.index)}.jsonl`,$y(zn)),i.clearError(Ae),zn}),g=m.filter(P=>!P.ok);for(let P of g){let pe=P.error instanceof Error?P.error.message:String(P.error);i.writeJson(`pass2/chunk_${gc(P.index)}.error.json`,{chunk:P.index,error:pe})}if(s.flush({scope:{kind:"phase",phase:"normalize"},status:g.length?"failed":"succeeded"}),g.length>0)throw new S(`${g.length}/${u.length} chunk(s) failed normalization.`,{exitCode:k,errorCode:"INGEST_NORMALIZE_INCOMPLETE",hint:"Inspect pass2/chunk_NNN.error.json and rerun `scriptctl ingest` to resume.",data:{actual:g.map(P=>`chunk ${P.index}`)}});r.phaseEnd("normalize");let w,y,E;if(!e.force&&i.has("body.json"))w=i.readJson("body.json"),y=i.has("pass3/script.jsonl")?Ms(i.readText("pass3/script.jsonl")).length:0,E=i.has("notes.json")?i.readJson("notes.json").length:0,h++;else{let P=[];for(let zn of m)zn.ok&&P.push(...zn.value);i.writeText("pass3/script.jsonl",$y(P));let pe=Ms(i.readText("pass3/script.jsonl")),Ae=Fk(t.path),Lt=Dh(pe,{title:Ae});i.writeJson("notes.json",Lt.notes),w=Lt.script,i.writeJson("body.json",w),y=P.length,E=Lt.notes.length}hh(w,Fa(o),d);let _=P=>String(P).padStart(3,"0"),x=(P,pe)=>`serial/win_${_(P)}_${_(pe)}.json`,A={readUpdate:(P,pe)=>i.has(x(P,pe))?i.readText(x(P,pe)):void 0,writeStep:(P,pe,Ae,Lt)=>{i.writeText(`serial/context_${_(P)}.md`,Ae),i.writeText(x(P,pe),Lt)},readArc:(P,pe)=>{let Ae=`serial/arc_${_(P)}_${_(pe)}.md`;return i.has(Ae)?i.readText(Ae):void 0},writeArc:(P,pe,Ae)=>{i.writeText(`serial/arc_${_(P)}_${_(pe)}.md`,Ae)},readNameFix:(P,pe)=>{let Ae=`serial/fix_${_(P)}_${_(pe)}.json`;return i.has(Ae)?i.readText(Ae):void 0},writeNameFix:(P,pe,Ae)=>i.writeText(`serial/fix_${_(P)}_${_(pe)}.json`,Ae)};r.phaseStart("serial");let b=await Iy(w,{executor:e.executor,checkpoint:A,force:e.force??!1,...f?{sourceRef:f}:{},onWindow:P=>{P.index===0&&r.serialStart(P.total,P.totalEpisodes),r.windowDone(P.startEp,P.endEp,P.ms,P.cached);let pe=P.startEp===P.endEp?{kind:"episode",episode:P.startEp}:{kind:"episode-range",startEpisode:P.startEp,endEpisode:P.endEp},Ae=Date.now();s.flush({scope:pe,status:P.cached?"reused":"succeeded",startedAtMs:Ae-P.ms,endedAtMs:Ae})},...e.signal?{signal:e.signal}:{}}),U=b.doc;h+=b.reused,r.phaseEnd("serial"),r.phaseStart("govern");let{script:v,idMap:I}=cc(U);i.writeJson("id_map.json",I);let R=St(v);if(!R.ok)throw i.writeJson("validation.json",R),new S("Intermediate script failed validation before v4 identity assignment.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:R.errors.slice(0,5).map(P=>`${P.path}: ${P.message}`)}});let C=!e.force&&i.has("v4_identity_map.json")?i.readJson("v4_identity_map.json"):void 0,N=Ar(Gt(U),C,b.identityKeys),M=N.script,K=Te(M),X=[],Ke=Date.now(),se="failed";try{if(K.ok){let P=await Ly(i,M,e.executor,{force:e.force??!1,...e.signal?{signal:e.signal}:{}});X=Uy(P.report)}se="succeeded"}finally{s.flush({scope:{kind:"phase",phase:"asset-audit"},status:se,startedAtMs:Ke})}let z={...K,warnings:[...K.warnings,...Ir(M),...X]};if(i.writeJson("pass5/script.json",M),i.writeJson("v4_identity_map.json",N.identityMap),i.writeJson("validation.json",z),!z.ok)throw new S("Final script.json failed v4 validation.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:z.errors.slice(0,5).map(P=>`${P.path}: ${P.message}`)}});i.writeJson("script.json",M),r.phaseEnd("govern"),r.finish();let Nt=M;return a="succeeded",{workspacePath:i.root,chunks:u.length,reused:h,records:y,notes:E,assets:{actors:Nt.actors?.length??0,locations:Nt.locations?.length??0,props:Nt.props?.length??0},scriptPath:i.path("script.json"),validation:{ok:z.ok,errors:z.errors.length,warnings:z.warnings.length}}}finally{s.finish(a)}}function Fk(e){return vr.basename(e,vr.extname(e))}import*as mo from"node:fs";import*as Ti from"node:path";import{createHash as wb}from"node:crypto";var Yk=()=>({apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:[],voice:""});function Yo(){return{lastEpisode:0,registry:[],digests:[],openThreads:[]}}var Ie=e=>e.normalize("NFC").replace(/\s+/g," ").trim(),yc=(e,t)=>e.length>t?`${e.slice(0,t)}\u2026`:e;function qk(e,t){let n=Ie(t);return e.find(o=>Ie(o.name)===n||Ie(o.identitySeed)===n||o.aliases.some(i=>Ie(i)===n))}var Wk=3,Zk=12e3;function Ci(e,t){let n=(t??"").trim();n&&!e.includes(n)&&e.push(n)}var Xk=["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","voice"];function hc(e,t,n){if(!t)return e;let o=e?{...e,persistent_marks:[...e.persistent_marks]}:Yk();for(let i of Xk){let r=t[i]?.trim()??"";r&&(n||!o[i])&&(o[i]=r)}for(let i of t.persistent_marks??[])Ci(o.persistent_marks,i);return o}function ou(e,t,n){let o=t.name.trim();if(!o)return;let i=t.description.trim(),r=e.find(s=>Tn(s.name)===Tn(o));if(!r){e.push({name:o,description:i});return}i&&(n||!r.description)&&(r.description=i)}function nu(e,t,n,o=!1){let i=(s,a)=>{let c=(a??"").trim();return c&&(o||!s)?c:s};for(let s of t.add_recognition_anchors??[])Ci(e.recognitionAnchors,s);e.identityProfile=hc(e.identityProfile,t.identity_profile_patch,o),t.identity_revision&&(e.identityProfile={...t.identity_revision.profile,persistent_marks:[...t.identity_revision.profile.persistent_marks]},e.recognitionAnchors=[...t.identity_revision.recognition_anchors]);let r=i(e.appearance,t.appearance);r&&(e.appearance=r),e.role=t.identity_revision&&t.role!==void 0?t.role.trim():i(e.role,t.role)??e.role;for(let s of t.add_aliases??[])Ci(e.aliases,s);for(let s of t.add_states??[])ou(e.states,s,o);e.lastEpisode=n}function Vs(e,t,n){let o=r=>qk(e.registry,r);for(let r of t.registry_delta.new_entities){let s=r.name.trim();if(!s||r.kind==="actor"&&ut(s))continue;let a=o(s);if(a){nu(a,{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 c=[];for(let p of r.states??[])ou(c,p,!1);let d=[];for(let p of r.aliases??[])Ci(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:hc(void 0,r.identity_profile,!0)}:{},...r.appearance?{appearance:r.appearance.trim()}:{},role:(r.role??"").trim(),aliases:d,states:c,firstEpisode:n,lastEpisode:n})}for(let r of t.registry_delta.enrich){if(r.identity_revision)continue;let s=o(r.name);s&&nu(s,r,n,!0)}for(let r of t.registry_delta.canonicalize){let s=o(r.from_name),a=r.canonical_name.trim();if(!s||!a||Ie(a)===Ie(s.name))continue;let c=o(a);if(c&&c!==s){let d=s.firstEpisode<c.firstEpisode?s:c,p=d===s?c:s,l=d.states.map(h=>({...h})),f=new Set([...s.aliases,...c.aliases,s.identitySeed,c.identitySeed,s.name,c.name,r.from_name].map(h=>h.trim()).filter(Boolean));d.name=a,d.status="canonical",d.importance=s.importance==="featured"||c.importance==="featured"?"featured":"background",d.recognitionAnchors=[];for(let h of[...s.recognitionAnchors,...c.recognitionAnchors])Ci(d.recognitionAnchors,h);let u=hc(void 0,s.identityProfile,!0);d.identityProfile=hc(u,c.identityProfile,!0),(c.appearance||s.appearance)&&(d.appearance=c.appearance||s.appearance),d.role=c.role||s.role,d.states=[];for(let h of[...l,...p.states])ou(d.states,h,!1);d.aliases=[...f].filter(h=>Ie(h)!==Ie(a)),d.firstEpisode=Math.min(s.firstEpisode,c.firstEpisode),d.lastEpisode=Math.max(s.lastEpisode,c.lastEpisode,n),e.registry.splice(e.registry.indexOf(p),1);continue}Ci(s.aliases,s.name),Ci(s.aliases,r.from_name),s.name=a,s.status="canonical",s.aliases=s.aliases.filter(d=>Ie(d)!==Ie(a)),s.lastEpisode=n}for(let r of t.registry_delta.enrich){if(!r.identity_revision)continue;let s=o(r.name);s&&nu(s,r,n,!0)}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(a=>a.id!==s&&a.text!==s))}return e.digests.push({episode:n,synopsis:(t.synopsis??"").trim()}),e.lastEpisode=n,e}function Jy(e,t){return e.digests.push({episode:t,synopsis:"",outcome:"skipped"}),e.lastEpisode=t,e}function eb(e,t){let n=[],o=e.status==="provisional"?"\xB7\u5F85\u5B9A \u26A0":`\xB7${e.importance}`;n.push(`### ${e.name} ${o}`),e.role&&n.push(`- \u8EAB\u4EFD\u5173\u7CFB\u8BB0\u5F55\uFF08\u5F85\u6838\uFF09: ${yc(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}`)}if(e.aliases.length&&n.push(`- \u66FE\u7528\u79F0\u547C: ${e.aliases.join("\u3001")}`),e.states.length){n.push("- \u5DF2\u767B\u8BB0\u9636\u6BB5\uFF08\u540D\u79F0\u9010\u5B57\u7528\u4E8E\u5F15\u7528\uFF0C\u63CF\u8FF0\u6309\u9002\u7528\u9636\u6BB5\u6838\u5BF9\uFF09\uFF1A");for(let r of e.states)n.push(` - ${r.name}\uFF1A${r.description||"\u63CF\u8FF0\u5F85\u8865"}`)}return 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 Gy(e,t){let n=yc(e.appearance||e.role||"",t?30:60),o=e.states.map(i=>i.description?`${i.name}\uFF08${yc(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 By(e,t,n){let o=[];o.push(`# \u5148\u524D\u767B\u8BB0\uFF08\u89E3\u6790\u7B2C ${e.lastEpisode+1} \u96C6\u65F6\u6838\u5BF9\u672C\u8868\uFF09`,""),o.push("\u4F9D\u636E\u6765\u6E90\u4FDD\u6301\u4EBA\u7269\u8EAB\u4EFD\u8FDE\u7EED\u3002\u4EBA\u7269 role \u91CD\u5199\u4E3A\u5DF2\u786E\u8BA4\u7684\u8EAB\u4EFD\u79F0\u8C13\u4E0E\u5173\u7CFB\uFF1B\u5176\u4E2D\u6DF7\u5165\u7684\u5916\u8C8C\u6309\u9002\u7528\u9636\u6BB5\u5F52\u5165 state\u3002\u5168\u90E8\u5916\u8C8C\u4E0E\u58F0\u7EBF\u7531\u5404 state \u72EC\u7ACB\u627F\u8F7D\uFF0C\u65E2\u6709\u753B\u50CF\u4E0E\u8BC6\u522B\u951A\u70B9\u4F5C\u4E3A\u5F85\u6838\u89C2\u5BDF\uFF0C\u4F9D\u636E\u5404\u9636\u6BB5\u8BC1\u636E\u8865\u5168\u76F8\u5E94 state\uFF0C\u5E76\u4EE5\u5168\u7A7A identity_revision \u6E05\u7A7A\u753B\u50CF\u4E0E\u951A\u70B9\u3002","");let i=e.registry.filter(c=>c.kind==="actor"),r=e.registry.filter(c=>c.kind==="location"),s=e.registry.filter(c=>c.kind==="prop");if(i.length){o.push("## \u4EBA\u7269","");for(let c of i)o.push(...eb(c,n),"")}if(r.length||s.length){o.push("## \u573A\u666F / \u9053\u5177","");for(let c of r)o.push(Gy(c,n));for(let c of s)o.push(Gy(c,n));o.push("")}let a=e.digests.filter(c=>c.episode>e.lastEpisode-t);if(a.length){o.push("## \u5267\u60C5\u8FDB\u5C55","");for(let c of[...a].sort((d,p)=>d.episode-p.episode))o.push(c.outcome==="skipped"?`\u7B2C${c.episode}\u96C6\u5DF2\u4EBA\u5DE5\u8DF3\u8FC7\uFF0C\u5267\u60C5\u672A\u77E5\u3002`:`\u7B2C${c.episode}\u96C6\uFF1A${n?yc(c.synopsis,40):c.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 c of e.openThreads)o.push(`- [${c.id}] ${c.text}`);o.push("")}return o.join(`
|
|
280
|
+
`)}function wc(e){for(let t=Wk;t>=1;t--){let n=By(e,t,!1);if(n.length<=Zk)return n}return By(e,1,!0)}function qo(e){let t=new Map;for(let n of e)for(let o of[n.identitySeed,...n.aliases])Ie(o)!==Ie(n.name)&&t.set(o,n.name);return t}function tb(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 zy(e,t){let n=new Map,o=new Map,i=(s,a)=>{let c=Ie(s),d=a.trim();!d||Ie(d)===c||(o.has(c)||o.set(c,new Set),o.get(c).add(d))};for(let s of t){n.set(Ie(s.name),s.importance);for(let a of s.aliases)n.set(Ie(a),s.importance);n.set(Ie(s.identitySeed),s.importance);for(let a of new Set([s.identitySeed,...s.aliases]))i(s.name,a)}let r=(s,a)=>{for(let c of s??[]){let d=String(c[a]??""),p=[d,...c.aliases??[]],l;for(let h of p)if(l=t.find(m=>Ie(m.name)===Ie(h)||Ie(m.identitySeed)===Ie(h)||m.aliases.some(g=>Ie(g)===Ie(h))),l)break;c.importance=l?.importance??n.get(Ie(d))??"featured";let f=o.get(Ie(d));if(f?.size&&(c.aliases=[...new Set([...c.aliases??[],...f])]),!l)continue;let u=l.kind==="actor"?tb(l):[l.appearance,l.role].map(h=>(h?.trim()??"").replace(/[。;]+$/,"")).filter(Boolean).join("\uFF1B");u&&(c.description=`${u}\u3002`);for(let h of c.states??[]){let m=l.states.find(g=>Tn(g.name)===Tn(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 Ky(e,t,n){let o=qo(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)}:ut(d)?{kind:"group",label:d}:{name:i(d)}},s=0,a={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 E=y.speaker.name;u.some(_=>_.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:Ko(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}})}))},c=new Set(t.registry.map(d=>`${d.kind}:${d.name}`));for(let d of a.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=>!c.has(u));if(f.length)throw new S(`Comic scene references assets absent from the registry: ${f.join(", ")}`,{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"The episode must register every referenced character, location and key prop.",data:{actual:f}})}return a}var Or=e=>e.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();function nb(e,t,n){let o=qo(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&&Or(g.name)===Or(f))??l,m=`${l.kind}:${Or(f)}`;r.has(m)||r.set(m,`${n}:${h.kind}:${h.firstEpisode}:${Or(h.identitySeed)}`)}let s={},a={},c={},d={},p={actor:s,location:a,prop:c};for(let l of e){let f=l.names[0]??l.provisional_id,u=r.get(`${l.kind}:${Or(f)}`)??`${n}:${l.kind}:source:${Or(f)}`;p[l.kind][l.provisional_id]=u,d[l.provisional_id]=Object.fromEntries(l.states.map(h=>[h.id,`${u}:state:${Tn(h.name)}`]))}return{actor:s,location:a,prop:c,state:d}}function xc(e,t,n,o){let{script:i,assets:r,identityKeys:s}=rc(e);zy(i,t.registry);let a=lc(i),{script:c,idMap:d}=cc(a),p=St(c);if(!p.ok)return{initial:i,final:c,idMap:d,validation:p,identityMap:o,scriptV4:null};let l=Ar(Gt(a),o,{...nb(r,t.registry,n),...s}),f=l.script,u=Te(f);return{initial:i,final:f,scriptV4:f,idMap:d,identityMap:l.identityMap,validation:{...u,warnings:[...u.warnings,...Ir(f)]}}}import*as jy from"node:fs";import*as uo from"node:path";import{createHash as ob}from"node:crypto";import{PDFDocument as ib}from"pdf-lib";import*as Ec from"node:path";function Rr(e){let t=Ec.basename(e,Ec.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 rb(e){let t=e.kind==="comic-file"?[e.path]:e.files,n=t.map(i=>({path:i,sourceNumber:Rr(i)})),o=n.flatMap(i=>i.sourceNumber===null?[]:[i.sourceNumber]);if(o.length>0&&o.length!==t.length||new Set(o).size!==o.length)throw new S("Comic chapter ordering is ambiguous.",{exitCode:k,errorCode:"INGEST_COMIC_DISCOVERY",hint:"Give every PDF a unique chapter number, or use unnumbered filenames that sort in reading order.",data:{actual:t.map(i=>uo.basename(i))}});return n.sort((i,r)=>i.sourceNumber!==null&&r.sourceNumber!==null?i.sourceNumber-r.sourceNumber:uo.basename(i.path).localeCompare(uo.basename(r.path),"zh-Hans",{numeric:!0}))}async function Hy(e){let t=[];for(let[n,o]of rb(e).entries()){let i=jy.readFileSync(o.path),s=(await ib.load(i,{updateMetadata:!1})).getPageCount();if(!s)throw new S("PDF is outside the document provider limits.",{exitCode:k,errorCode:"INGEST_COMIC_SIZE",hint:"Provide a PDF containing at least one readable page.",data:{actual:[`${o.path}: ${s} pages, ${i.length} bytes`]}});t.push({episode:n+1,document_id:`chapter-${String(n+1).padStart(3,"0")}`,source_number:o.sourceNumber,title:uo.basename(o.path,uo.extname(o.path)),path:uo.resolve(o.path),sha256:ob("sha256").update(i).digest("hex"),page_count:s,size_bytes:i.length})}return t}function Qy(e,t){let n=e.find((o,i)=>{let r=t[i];return!r||o.sha256!==r.sha256||o.source_number!==r.source_number||o.title!==r.title});if(n)throw new S("The comic source prefix changed.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Restore the original chapters or use a fresh workspace. Only tail chapters may be appended.",data:{actual:[n.title]}})}import{PDFDocument as sb,StandardFonts as ab,rgb as cb,pushGraphicsState as db,popGraphicsState as pb,concatTransformationMatrix as _c}from"pdf-lib";async function Fy(e){let t=await sb.load(e),n=await t.embedFont(ab.Helvetica),o=cb(0,.45,.85);for(let i of t.getPages()){let r=i.getCropBox(),s=(i.getRotation().angle%360+360)%360,a=s===90||s===270,c=a?r.height:r.width,d=a?r.width:r.height;switch(i.pushOperators(db()),s){case 90:i.pushOperators(_c(0,1,-1,0,r.x+r.width,r.y));break;case 180:i.pushOperators(_c(-1,0,0,-1,r.x+r.width,r.y+r.height));break;case 270:i.pushOperators(_c(0,-1,1,0,r.x,r.y+r.height));break;default:i.pushOperators(_c(1,0,0,1,r.x,r.y))}let p=c/70;for(let l=0;l<=1e3;l+=50){let f=d*(1-l/1e3);i.drawLine({start:{x:0,y:f},end:{x:c,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,c-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=c*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(pb())}return t.save()}import*as Yy from"node:fs";import*as qy from"node:path";import lb from"proper-lockfile";async function Wo(e,t){let n=qy.resolve(e);Yy.mkdirSync(n,{recursive:!0});let o=null;try{o=await lb.lock(n,{realpath:!1,stale:12e4,update:1e4,retries:0})}catch(i){throw new S("The ingest workspace is busy.",{exitCode:q,errorCode:"INGEST_WORKSPACE_BUSY",hint:"Wait for the other ingest or skip command to finish, then retry.",data:{actual:[n,i instanceof Error?i.message:String(i)]}})}try{return await t()}finally{await o()}}import*as fo from"node:fs";import*as ru from"node:path";import{PDFDocument as iu}from"pdf-lib";import{z as Mr}from"zod";var Wy=Mr.object({starts:Mr.array(Mr.object({page:Mr.number().int().min(1),title:Mr.string().min(1)}))}),ub="\u9605\u8BFB\u6F2B\u753B PDF \u5E76\u8BC6\u522B\u5B9E\u9645\u8BDD/\u7AE0\u8282\u8FB9\u754C\u3002\u53EA\u8F93\u51FA\u672C\u6BB5\u5185\u786E\u5B9E\u5F00\u59CB\u7684\u65B0\u8BDD\u7684\u8D77\u59CB\u7269\u7406\u9875\u7801\u548C\u539F\u7A3F\u6807\u9898\u3002\u4F9D\u636E\u8BDD\u53F7\u3001\u7AE0\u8282\u6249\u9875\u3001\u6807\u9898\u53CA\u53D9\u4E8B\u8FDE\u7EED\u6027\u7EFC\u5408\u5224\u65AD\uFF1B\u573A\u666F\u5207\u6362\u3001\u56DE\u5FC6\u3001\u6362\u9875\u548C\u5E7F\u544A\u4E0D\u662F\u65B0\u8BDD\u3002\u8F93\u5165\u53EF\u80FD\u4ECE\u4E00\u8BDD\u4E2D\u95F4\u5F00\u59CB\uFF0C\u5EF6\u7EED\u524D\u6BB5\u7684\u5185\u5BB9\u4E0D\u7B97\u65B0\u8BDD\u3002\u7B2C\u4E00\u6BB5\u4ECE\u539F\u6587\u6863\u7B2C\u4E00\u9875\u5F00\u59CB\u65F6\uFF0C\u4E3A\u7B2C\u4E00\u8BDD\u5EFA\u7ACB\u8D77\u70B9\uFF0C\u5C01\u9762\u548C\u76EE\u5F55\u968F\u9996\u8BDD\u4FDD\u7559\u3002\u591A\u8BDD\u5408\u96C6\u9010\u9879\u5217\u51FA\u5404\u8BDD\uFF1B\u5355\u8BDD\u6587\u4EF6\u53EA\u6709\u4E00\u4E2A\u8D77\u70B9\u3002page \u4F7F\u7528\u672C\u6B21\u8F93\u5165 PDF \u4ECE 1 \u5F00\u59CB\u7684\u7269\u7406\u9875\u7801\u3002\u6807\u9898\u4FDD\u7559\u539F\u8BDD\u53F7\u548C\u53EF\u8BFB\u8BDD\u540D\uFF1B\u65E0\u6CD5\u786E\u8BA4\u8BDD\u53F7\u65F6\u4F7F\u7528\u7B80\u77ED\u5185\u5BB9\u6807\u9898\u3002";async function Zy(e,t,n,o){let i=[];for(let r of e){let s=`sources/${r.sha256}.chapters.json`,a,c=await iu.load(fo.readFileSync(r.path));if(t.has(s))a=t.readJson(s);else{a=[];for(let d=0;d<r.page_count;){let p=Math.min(40,r.page_count-d),l;for(;;){let h=await iu.create();for(let m of await h.copyPages(c,Array.from({length:p},(g,w)=>d+w)))h.addPage(m);if(l=await h.save(),l.length<=4e7||p===1)break;p=Math.ceil(p/2)}let f=t.path(`sources/${r.sha256}.scan.pdf`);fo.mkdirSync(ru.dirname(f),{recursive:!0}),Vn(f,Buffer.from(l)),process.stderr.write(`\u8BC6\u522B\u6F2B\u753B\u7AE0\u8282 \xB7 ${r.title} \xB7 \u539F\u7A3F ${d+1}\u2013${d+p} / ${r.page_count} \u9875
|
|
281
|
+
`);let u=await n.prepare(f,o);try{let h=await n.generate({media:u,system:ub,user:`\u539F\u6587\u4EF6\uFF1A${r.title}\uFF0C\u5171 ${r.page_count} \u9875\u3002\u672C\u6BB5\u4E3A\u539F\u7A3F\u7B2C ${d+1}\u2013${d+p} \u9875\u3002\u5DF2\u8BC6\u522B\u8D77\u70B9\uFF1A${JSON.stringify(a)}\u3002`,responseJsonSchema:Mr.toJSONSchema(Wy,{target:"openapi-3.0"}),signal:o}),m=Wy.parse(JSON.parse(h.text));a.push(...m.starts.filter(g=>g.page<=p).map(g=>({...g,page:d+g.page})))}finally{await n.release(u,o)}d+=p}a=[...new Map(a.sort((d,p)=>d.page-p.page).map(d=>[d.page,d])).values()],a.length?a[0].page=1:a.push({page:1,title:r.title}),t.writeJson(s,a)}for(let[d,p]of a.entries()){let l=(a[d+1]?.page??r.page_count+1)-1,f=i.length+1,u=a.length===1?r.path:t.path(`sources/${r.sha256}.${p.page}-${l}.pdf`);if(!fo.existsSync(u)){let h=await iu.create();for(let m of await h.copyPages(c,Array.from({length:l-p.page+1},(g,w)=>p.page-1+w)))h.addPage(m);fo.mkdirSync(ru.dirname(u),{recursive:!0}),Vn(u,Buffer.from(await h.save()))}i.push({...r,episode:f,document_id:`chapter-${String(f).padStart(3,"0")}`,title:a.length===1?r.title:p.title,path:u,page_count:l-p.page+1,size_bytes:fo.statSync(u).size,original_path:r.path,original_page_count:r.page_count,start_page:p.page,end_page:l})}}return i}import{z as Xy}from"zod";var Sc=En,fb=Sc(7);function au(e,t){let n=Sc,o=Ha[n(1)](JSON[n(12)](e)),i=c=>{let d=n;throw new S(d(14)+c[d(21)]("; "),{exitCode:k,errorCode:d(44),hint:d(23),data:{actual:c}})};if(!o[n(17)])return i(o[n(37)][n(18)][n(15)](0,8)[n(38)](c=>c[n(10)][n(21)](".")+": "+c[n(9)]));let r=o[n(41)],s=new Set;for(let c of r[n(43)])for(let d of c[n(20)]){if(d[n(28)][n(42)]((l,f)=>l>t||f>0&&l<=d[n(28)][f-1]))return i([n(24)+d[n(28)][n(21)](", ")+n(25)+t+n(34)]);let p=As(d[n(28)],d[n(29)]);if(p[n(30)])return i(p);for(let l of d[n(28)])s[n(40)](l)}for(let c of r[n(6)]){if(c[n(36)]>t||s[n(13)](c[n(36)]))return i([n(27)+c[n(36)]]);s[n(40)](c[n(36)])}let a=Array[n(33)]({length:t},(c,d)=>d+1)[n(19)](c=>!s[n(13)](c));return a[n(30)]?i([n(31)+a[n(21)](", ")]):r}async function ew(e,t,n,o,i,r,s){let a=Sc,c=await e[a(2)]({media:t,system:fb,user:a(3)+n+a(22)+o+a(0)+i,responseJsonSchema:Xy[a(5)](Xg,{target:a(35)}),signal:s});return r(c[a(26)]),au(c[a(26)],o)}function su(){let e=["ioMHTE+8JoIVT+wUJoAvToMyHEIVU+w5TUAmIEMHUUw6J+MaKoAGVoI9RowgMEwfQoMdQowjP+AdHEoaGGOk","C2fMzvbHCNnL","z2vUzxjHDgu","5B2t5yMn6k+D77YA","5Qc55O2U5y6F5RYR55s75zkm5BEY6l2S5B2v5Q2J5PAh5Pw055cg5A6m5Pw06lwe5lQN55M76k6W44cc6l+u5zUEihjLz2LZDhj5x2rLBhrHiowVUEIXOE+8Jos/NEEvMEATO+EHRUEzU+IUSo+8JoIHPEM9KoATO+AwH+wUNUMzHEw8LEEuQoEAHos6UUEjQEoaGEwCSoEcUEwsJowfS+MuRUMbK+wfT++8JoINHoImG+wqJEs4JUw8LEEuQoMaKowTL+s4GoIhTooaGUs+NEAnRUwoN+EOV+ApJ+I/SowpR+INGEwKLUINGU+8M+wqJos4GoI6Q+s7VEEu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3bVBNnLlMPZB24Gyw5KihjLCNvUigLUz2vZDcb3AxrOihrOzsbZyw1LihnVDxjJzsbHBMqGD29YA3nWywnLlG","sw52ywXPzcbVCIb1BM9YzgvYzwqGC291CMnLihbHz2vZoIa","oYbKB2n1BwvUDcbOyxmG","Dgv4Da","sw52ywXPzcbVCIbKDxbSAwnHDguGAwDUB3jLzcbWywDLoIa","CgfNzxm","CMvNAw9UCW","BgvUz3rO","ugfNzxmGywjZzw50igzYB20GDhjHBNnJCMLWDdOG","cUw3SUACIEI9Row9LE+8MG","zNjVBq","ihbHz2vZlG","B3bLBMfWAs0ZlJa","CgfNzq","zxjYB3i","BwfW","C3rYAw5NAwz5","ywrK","zgf0yq","C29Tzq","C2nLBMvZ","su5hrvnux0nptuLdx1nfuKLbtf9gquLmruq"];return su=function(){return e},su()}async function tw(e,t,n,o,i,r){let s=Sc,a=Ha[s(11)][s(8)],c=await e[s(2)]({media:t,signal:r,system:s(4),user:o+s(16)+i+s(32)+JSON[s(39)](n),responseJsonSchema:Xy[s(5)](a,{target:s(35)})});return a[s(12)](JSON[s(12)](c[s(26)]))}function En(e,t){e=e-0;let n=su(),o=n[e];if(En.pkbepj===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};En.AcwwSN=i,En.wSoQuY={},En.pkbepj=!0}let r=n[0];En.aUTMuq!==r&&(En.wSoQuY={},En.aUTMuq=r);let s=En.wSoQuY[e];return s===void 0?(o=En.AcwwSN(o),En.wSoQuY[e]=o):o=s,o}function Ic(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function mb(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 gb(e){if(e instanceof T)return{failure:e.failure,attempts:e.modelFailures};if(e instanceof S){let t=e.errorCode==="INGEST_VALIDATION_FAILED"||e.errorCode==="INGEST_VIDEO_SERIAL_FAILED"||e.errorCode==="INGEST_COMIC_SERIAL_FAILED";return{failure:Vt(mb(e),{retryable:t,message:e.message}),attempts:[]}}return{failure:Vt({failure_type:"unknown",failure_code:"unknown"},{retryable:!1,message:e instanceof Error?e.message:String(e)}),attempts:[]}}function Ac(e,t,n){let o=gb(e);return{schema_version:1,unit:{kind:"episode",episode:t},phase:n,occurred_at:new Date().toISOString(),...o}}function ow(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 nw(e,t){return typeof e=="string"&&t.some(n=>n===e)}function Nr(e){return typeof e=="string"?e:void 0}function hb(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!Ic(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 yb(e){let t=e.provider_source,n=e.provider_reason;return{provider:Nr(e.provider),model:Nr(e.model),operation:Nr(e.operation),http_status:typeof e.http_status=="number"?e.http_status:void 0,system_code:Nr(e.system_code),provider_source:nw(t,["prompt","candidate"])?t:void 0,provider_reason:nw(n,["SAFETY","PROHIBITED_CONTENT","BLOCKLIST","SPII","RECITATION","IMAGE_SAFETY","IMAGE_PROHIBITED_CONTENT","IMAGE_RECITATION","ESCALATION","OTHER","UNSPECIFIED","UNKNOWN"])?n:void 0,provider_reason_raw:Nr(e.provider_reason_raw),finish_message:Nr(e.finish_message),safety_ratings:hb(e.safety_ratings),details:Array.isArray(e.details)&&e.details.every(i=>typeof i=="string")?e.details:void 0}}function $s(e){if(!Ic(e))return null;let t=bf(e.failure_type,e.failure_code);return!t||typeof e.retryable!="boolean"||typeof e.message!="string"?null:Vt(t,{...yb(e),retryable:e.retryable,message:e.message})}function Ds(e){if(!Ic(e)||e.schema_version!==1)return null;let t=e.unit;if(!Ic(t)||t.kind!=="episode"||typeof t.episode!="number"||typeof e.phase!="string"||typeof e.occurred_at!="string")return null;let n=$s(e.failure);if(!n||!Array.isArray(e.attempts))return null;let o=[];for(let i of e.attempts){let r=$s(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 iw="comic-1",kc=e=>String(e).padStart(3,"0"),rw=["script.initial.json","id_map.json","validation.json","context.json","v4_identity_map.json","script.json"];function bc(e,t,n){let o=xc(Ky(e,t.context,n),t.context,"comic",t.identityMap);if(!o.scriptV4||!o.validation.ok)throw new S("Comic script failed validation.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect the current episode response and rerun ingest with the same source and workspace.",data:{actual:o.validation.errors.slice(0,8).map(i=>`${i.path}: ${i.message}`)}});for(let[i,r]of o.scriptV4.episodes.entries())r.synopsis=e[i].output.synopsis;return{...o,scriptV4:o.scriptV4}}function cu(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 xb(e){let t=Ht(e.sourcePath);if(t.kind!=="comic-file"&&t.kind!=="comic-directory")throw new S("Expected PDF comic source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=new yt(Ti.resolve(e.workspacePath));n.ensure();let o=n.has("manifest.json")?n.readJson("manifest.json"):null;if(o&&o.pipeline_version!==iw)throw new S("This workspace belongs to another ingest pipeline.",{exitCode:k,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Choose a fresh workspace."});if(!o&&n.has("script.json"))throw new S("Workspace already contains an unmanaged script.json.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Choose a fresh workspace."});let i=await Hy(t),r=o&&!o.episodes.some(w=>w.original_path)?i:await Zy(i,n,e.executor.documentPort("ingest.comic-serial"),e.signal);o&&Qy(o.episodes,r);let s={version:1,pipeline_version:iw,updated:new Date().toISOString(),source:{kind:t.kind,path:Ti.resolve(t.path),sha256:wb("sha256").update(r.map(w=>w.sha256).join(`
|
|
282
|
+
`)).digest("hex")},episodes:r,...o?.current_error?{current_error:o.current_error}:{}};if(e.force){for(let w of o?.episodes??[])for(let y of["json","response.json","context.md","error.json","input.pdf"])mo.rmSync(n.path(`ep/ep_${kc(w.episode)}.${y}`),{force:!0});for(let w of["checkpoint.json","timings.json",...rw])mo.rmSync(n.path(w),{force:!0});delete s.current_error}n.writeJson("manifest.json",s);let a=n.has("checkpoint.json")?n.readJson("checkpoint.json"):{context:Yo(),identityMap:Qo()},c=r.slice(0,a.context.lastEpisode).map(w=>n.readJson(`ep/ep_${kc(w.episode)}.json`)),d=mo.realpathSync(t.path),p=Ti.basename(d,t.kind==="comic-file"?Ti.extname(d):""),l=new Fo(n,e.executor),f=new br(w=>n.writeJson("timings.json",w));f.phaseStart("serial"),f.serialStart(r.length,r.length);let u="failed",h=0,m=c.length,g;try{if(c.length>0){cu(n,bc(c,a,p),a.context);for(let E of c)n.clearError(`ep/ep_${kc(E.episode)}.error.json`);s.current_error&&s.current_error.unit.episode<=a.context.lastEpisode&&(delete s.current_error,s.updated=new Date().toISOString(),n.writeJson("manifest.json",s))}else for(let E of rw)mo.rmSync(n.path(E),{force:!0});for(let E of r){if(e.signal?.throwIfAborted(),E.episode<=a.context.lastEpisode){e.executor.recordReuse("ingest.comic-serial");let v=Date.now();l.flush({scope:{kind:"episode",episode:E.episode},status:"reused",startedAtMs:v,endedAtMs:v}),f.windowDone(E.episode,E.episode,0,!0);continue}if(e.step&&h>=1)break;let _=Date.now(),x=`ep/ep_${kc(E.episode)}`,A=s.current_error?.unit.episode===E.episode?s.current_error.failure.message:void 0,b=wc(a.context)+(A?`
|
|
276
283
|
|
|
277
284
|
\u672C\u8BDD\u4E0A\u4E00\u6B21\u8F93\u51FA\u5C1A\u672A\u88AB\u63A5\u53D7\uFF0C\u5931\u8D25\u539F\u56E0\uFF1A${A}\u3002\u8BF7\u6839\u636E\u539F PDF \u8FD4\u56DE\u4FEE\u6B63\u540E\u7684\u5B8C\u6574\u672C\u8BDD\uFF1B\u5C24\u5176\u9010\u9879\u6838\u5BF9\u6BCF\u4E2A\u5730\u70B9\u3001\u4EBA\u7269\u548C\u5173\u952E\u9053\u5177\u5F15\u7528\u662F\u5426\u5DF2\u7ECF\u767B\u8BB0\u3002`:"");n.writeText(`${x}.context.md`,b),process.stderr.write(`\u6F2B\u753B ${E.episode}/${r.length} \xB7 ${E.title} \xB7 ${E.page_count} \u9875
|
|
278
|
-
`);let U="upload";try{g??=e.executor.documentPort("ingest.comic-serial");let v=n.path(`${x}.input.pdf`);Vn(v,Buffer.from(await
|
|
279
|
-
`);let z=await g.prepare(v,e.signal);try{R.output.registry_delta=await
|
|
280
|
-
`)}catch(v){let I=_c(v,E.episode,U);throw n.writeJson(`${x}.error.json`,I),n.writeJson("manifest.json",{...s,updated:I.occurred_at,current_error:I}),l.flush({scope:{kind:"episode",episode:E.episode},status:"failed",startedAtMs:_,endedAtMs:Date.now()}),v}}let w=Ic(c,a,p);ru(n,w,a.context);let y=c.length===r.length;return u="succeeded",{workspace:n.root,script_path:n.path("script.json"),kind:"comic",episodes:r.length,processed:h,reused:m,completed:c.length,remaining:r.length-c.length,complete:y,next_episode:y?null:c.length+1,assets:{actors:w.scriptV4.actors.length,locations:w.scriptV4.locations.length,props:w.scriptV4.props.length}}}finally{f.phaseEnd("serial"),f.finish(),l.finish(u)}}async function nw(e){return qo(e.workspacePath,()=>pb(e))}import*as Rt from"node:fs";import*as Xt from"node:path";function lb(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 ow(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=lb(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 Ac(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 Nr(e){let t=typeof e=="string"?e.trim():"",n=t.match(/^(?:(\d+):)?(\d+):(\d{2})(\.\d{1,3})?$/);if(!n)return t;let o=Number(n[1]??0),i=Number(n[2]),r=Number(n[3]);if(![o,i,r].every(Number.isSafeInteger))return t;let s=o*3600+i*60+r,a=Math.floor(s/3600),c=Math.floor(s%3600/60),d=s%60;return(a>0?`${a}:${String(c).padStart(2,"0")}:${String(d).padStart(2,"0")}`:`${String(c).padStart(2,"0")}:${String(d).padStart(2,"0")}`)+(n[4]??"")}function Lr(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 iw=e=>String(e).padStart(3,"0"),ub={\u5185:"interior",\u5916:"exterior"},fb={act:"action",dlg:"dialogue",think:"inner_thought"},su={broadcast:"broadcast",system:"system",group:"group",offscreen:"offscreen",prop:"offscreen",location:"offscreen"};function mb(e){let t=e.match(/^(\w+):(.+)$/);if(t&&su[t[1]]){let n=t[2].trim();return n?{kind:su[t[1]],label:n}:{kind:su[t[1]]}}return ut(e)?{kind:"group",label:e.trim()}:{name:e}}function rw(e,t){let n=0,o=e.map((i,r)=>{let s=`video:episode:${i.episode}`,a=new Map;return{identity_key:s,episode_id:`ep_${iw(r+1)}`,scenes:i.scenes.map(c=>{let d=c.timeRange?.trim()?`time:${c.timeRange.trim()}`:`index:${c.index}`,p=(a.get(d)??0)+1;a.set(d,p);let l=`${s}:scene:${d}:${p}`,f={},u=ub[(c.environment.space??"").trim()],h=zo(c.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 c.characters)A.name&&!ut(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=c.anchors.map(A=>{let b=Nr(A.ts),U=b?`time:${b}`:`content:${JSON.stringify([A.kind,A.speaker??"",A.content])}`,v=(w.get(U)??0)+1;w.set(U,v);let I={identity_key:`${l}:action:${U}:${v}`,type:fb[A.kind]??"action",content:A.content};if((A.kind==="dlg"||A.kind==="think")&&A.speaker){let C=mb(A.speaker);I.speaker=C,"name"in C&&g(C.name)}A.parenthetical&&(I.parenthetical=A.parenthetical);let R=Nr(A.ts);return R&&(I.extend={timestamp:R}),I}),E=(c.location??"").trim(),_=[],x=new Set;for(let A of c.props??[]){if(!A)continue;let b=A.normalize("NFC").replace(/\s+/g," ").trim();!b||x.has(b)||(x.add(b),_.push({name:A}))}return{identity_key:l,scene_id:`scn_${iw(++n)}`,...f.space||f.time?{environment:f}:{},location:E?{name:E}:null,actors:m,props:_,actions:y}})}});return{title:t,episodes:o}}var gb=60,hb=6,yb=[-1e3,0,1e3],dw=/(?:身穿|穿着|服装|造型|衣|裙|袍|衫|夹克|制服|西装|盔甲|装甲|防弹服|套装|裤|靴)/u,au=/(?:全身|半身|上半身|四分之三身|躯干|胸前|腰部)/u,cu=/(?:站(?:在|立)|坐(?:在|下|起)|跪(?:在|下|倒)?|蹲(?:在|下)?|走(?:在|出|向)|行走|迈步|奔跑|跳起|跃起|转身|抬头|转头)/u,sw=/(?:特写|近景|脸|面容|五官|正脸|侧脸|侧前脸|双眼|眼眶|眉头|嘴角)/u,pw=/(?:背对|背影|远处|极远|模糊|运动模糊|脸被遮|面部遮挡|只露出|纯道具|空镜)/u,lw=/(?:双脚|脚部|膝盖|伤口|手部特写)/u,uw=/(?:画外音|旁白|未入镜|镜外|电话音|广播|\bO\.?S\.?\b)/iu;function Zo(e){return e.normalize("NFC").replace(/\s+/g," ").trim()}function fw(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 mw(e){let t=e.trim().match(/^(\d+):(\d{2})$/);return t?Number(t[1])*1e3+Number(t[2])*10:null}function gw(e,t="clock"){return t==="legacy_centiseconds"?mw(e):fw(e)}function du(e,t){return e===null?!1:t===void 0||e<=t}function wb(e,t){if(t===void 0)return"clock";let n=e.scenes.flatMap(r=>r.actions.map(hw)).filter(Boolean),o=n.filter(r=>du(fw(r),t)).length;return n.filter(r=>du(mw(r),t)).length>o?"legacy_centiseconds":"clock"}function aw(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 hw(e){let t=e.extend?.timestamp;return typeof t=="string"?t.trim():""}function xb(e,t){let n=new Set([e.actor_name,...e.aliases??[]].map(Zo).filter(Boolean));for(let[o,i]of t)Zo(i)===Zo(e.actor_name)&&n.add(Zo(o));return[...n].sort((o,i)=>i.length-o.length)}function yw(e,t){let n=t.map(o=>e.indexOf(o)).filter(o=>o>=0);return n.length>0?Math.min(...n):-1}function ww(e,t,n){return t.filter(o=>yw(e,n.get(o.actor_id)??[])>=0).length}function Eb({action:e,actor:t,actorCount:n,allActors:o,surfaces:i,surfacesByActor:r,stateName:s}){let a=e.type==="action"||e.type==="transition",c=Zo(a?e.content:"parenthetical"in e?e.parenthetical??"":""),d=yw(c,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&&!uw.test(c),h=n===1&&(a&&c.length>0||u&&c.length>0&&(cu.test(c)||sw.test(c)));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=Zo(s);return y&&y!=="default"&&y!=="\u9ED8\u8BA4"&&c.includes(y)&&(g+=35),dw.test(c)&&(g+=30),au.test(c)?(g+=25,w+=15):cu.test(c)&&(g+=15,w+=5),sw.test(c)&&(w+=30,au.test(c)||(g-=20)),pw.test(c)&&(g-=70,w-=70),lw.test(c)&&(g-=40),ww(c,o,r)>=2&&(g-=15,w-=15),{stateScore:g,identityScore:w,selection:m}}function _b(e,t,n){let o=e.type==="action"||e.type==="transition",i="parenthetical"in e?Zo(e.parenthetical??""):"";if(!o&&uw.test(i))return null;let r=Zo(o?e.content:i),s=o?0:-40;return s-=ww(r,t,n)*20,dw.test(r)&&(s+=10),au.test(r)?s+=10:cu.test(r)&&(s+=5),pw.test(r)&&(s-=20),lw.test(r)&&(s-=10),{stateScore:s,identityScore:Number.NEGATIVE_INFINITY,selection:"scene_fallback"}}function $s(e,t,n){let o=(n.get(`${e.episode}:${e.milliseconds}`)?.size??0)>1;return e[t]-(o?35:0)}function xw(e,t,n,o,i){let r=new Map;for(let c of e){let d=`${c.episode}:${c.milliseconds}`,p=r.get(d);(!p||$s(c,t,n)>$s(p,t,n))&&r.set(d,c)}let s=[...r.values()].sort((c,d)=>$s(d,t,n)-$s(c,t,n)||c.episode-d.episode||c.milliseconds-d.milliseconds).filter(c=>i===null||$s(c,t,n)>=i),a=[];for(let c of s)if(!a.some(p=>p.episode===c.episode&&p.sceneId===c.sceneId&&Math.abs(p.milliseconds-c.milliseconds)<3e3)&&(a.push(c),a.length>=o))break;return a}function Sb(e,t,n){return xw(e,t,n,1,null)[0]??null}function cw(e){return e.replace(/[^0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function kc(e,t,n,o,i){let r=new Map(o.map(g=>[g.episode,g])),s=Yo(n.registry),a=new Map(t.actors.map(g=>[g.actor_id,g])),c=new Map(t.actors.map(g=>[g.actor_id,xb(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,E=r.get(y);if(!E)continue;let _=wb(w,E.duration_ms);for(let x=0;x<w.scenes.length;x+=1){let A=w.scenes[x],b=A.actors.map(U=>a.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 v=a.get(U.actor_id);if(!v)continue;let I=c.get(v.actor_id)??[v.actor_name],R=[],C=U.state_ids.length===1?U.state_ids[0]:null,N=C?v.states.find(M=>M.state_id===C):null;for(let M of A.actions){let K=hw(M),X=gw(K,_);if(!du(X,E.duration_ms))continue;let Ke=Eb({action:M,actor:v,actorCount:b.length,allActors:b,surfaces:I,surfacesByActor:c,stateName:N?.state_name??"default"}),se=Ke??(N?_b(M,b,c):null);if(!se)continue;let z={actorId:v.actor_id,episode:y,episodeId:w.episode_id,sceneId:A.scene_id,timestamp:aw(X),milliseconds:X,durationMs:E.duration_ms,stateScore:se.stateScore,identityScore:se.identityScore,selection:se.selection,sourcePath:E.path,sourceSha256:E.sha256};if(R.push(z),Ke){let Nt=`${y}:${X}`,P=f.get(Nt)??new Set;P.add(v.actor_id),f.set(Nt,P)}}if(R.length>0){let M=p.get(v.actor_id)??[];if(M.push(...R),p.set(v.actor_id,M),N){let K=`${v.actor_id}:${N.state_id}`,X=l.get(K)??[];X.push(...R),l.set(K,X)}}}}}let u=(g,w)=>{let y=a.get(g),E=a.get(w),_=y?.importance==="background"?1:0,x=E?.importance==="background"?1:0;return _-x||(d.get(w)??0)-(d.get(g)??0)||(y?.actor_name??g).localeCompare(E?.actor_name??w,"zh-CN")},h=[...l.entries()].flatMap(([g,w])=>{let[y,E]=g.split(":"),_=y?a.get(y):void 0,x=_?.states.find(v=>v.state_id===E),A=Sb(w,"stateScore",f);if(!_||!x||!A)return[];let b=`state:${_.actor_id}:${x.state_id}`,U=yb.map(v=>{let I=A.durationMs===void 0?Number.POSITIVE_INFINITY:Math.max(0,A.durationMs-50),R=Math.min(I,Math.max(0,A.milliseconds+v)),C=aw(R);return{evidence_id:`${b}:${A.episode}:${C}`,episode:A.episode,episode_id:A.episodeId,scene_id:A.sceneId,timestamp:C,offset_ms:v,selection:A.selection,source_sha256:A.sourceSha256,source_path:A.sourcePath,frame_path:`evidence/frames/${_.actor_id}/${x.state_id}/ep_${String(A.episode).padStart(3,"0")}_${cw(C)}.jpg`,frame_status:"pending"}}).filter((v,I,R)=>R.findIndex(C=>C.timestamp===v.timestamp)===I);return[{evidence_id:b,asset_kind:"actor",actor_id:_.actor_id,actor_name:_.actor_name,state_id:x.state_id,state_name:x.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=a.get(g),E=xw(w,"identityScore",f,hb,gb);if(!y||E.length===0)return[];let _=`identity:${y.actor_id}`;return[{evidence_id:_,asset_kind:"actor",actor_id:y.actor_id,actor_name:y.actor_name,samples:E.map(x=>({evidence_id:`${_}:${x.episode}:${x.timestamp}`,episode:x.episode,episode_id:x.episodeId,scene_id:x.sceneId,timestamp:x.timestamp,offset_ms:0,selection:x.selection,source_sha256:x.sourceSha256,source_path:x.sourcePath,frame_path:`evidence/frames/${y.actor_id}/identity/ep_${String(x.episode).padStart(3,"0")}_${cw(x.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 Ew(e){return gw(e)}function _w(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(a=>({kind:a.kind,...a.speaker?{speaker:a.speaker}:{},...a.parenthetical?{parenthetical:a.parenthetical}:{},...a.ts?{ts:a.ts}:{},content:a.content??""}));return{index:i+1,environment:r,...o.timeRange?{timeRange:o.timeRange}:{},...o.location?{location:o.location}:{},characters:(o.characters??[]).filter(a=>a.name).map(a=>({name:a.name,states:[...a.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 bc from"node:path";function Iw(e){return bc.extname(e).toLowerCase()}function Ib(e){return ul[Iw(e)]??"application/octet-stream"}function Sw(e,t){return new S(e,{exitCode:k,errorCode:"INGEST_VIDEO_DISCOVERY",hint:"Name every episode file with a number, or none of them, and rerun `scriptctl ingest`.",data:{actual:t}})}function pu(e,t){return{episode:t,path:e,ext:Iw(e),mime:Ib(e)}}function Ur(e){if(e.kind!=="video-file"&&e.kind!=="video-directory")throw new S("Expected video source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});if(e.kind==="video-file")return[pu(e.path,1)];let t=e.files,n=t.map(Or),o=n.filter(r=>r!==null);if(o.length===0)return t.map((r,s)=>pu(r,s+1));if(o.length!==t.length){let r=t.filter((s,a)=>n[a]===null).map(s=>bc.basename(s));throw Sw("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 Sw("Two episode files resolve to the same number.",[`duplicate episode: ${r}`]);i.add(r)}return t.map((r,s)=>pu(r,n[s])).sort((r,s)=>r.episode-s.episode)}import*as Aw from"node:fs";import*as kw from"node:path";function bw(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=kw.resolve(r.path),a=Aw.statSync(s),c=a.size,d=Math.trunc(a.mtimeMs),p=o.get(r.episode),l=p&&p.size_bytes===c&&p.mtime_ms===d,f=p&&p.size_bytes===void 0&&p.mtime_ms===void 0&&p.path===s&&Number.isFinite(i)&&a.mtimeMs<=i,u=p&&p.ext===r.ext&&p.mime===r.mime&&(l||f)?p.sha256:ud(s);return{episode:r.episode,path:s,ext:r.ext,mime:r.mime,sha256:u,size_bytes:c,mtime_ms:d}})}function vc(e){return _e(JSON.stringify(e.map(t=>({episode:t.episode,ext:t.ext,mime:t.mime,sha256:t.sha256}))))}import{spawn as Ab}from"node:child_process";import*as wt from"node:fs";import*as vw from"node:path";var kb=20*1024*1024,bb="scale='if(gt(a,1),min(1280,iw),-2)':'if(gt(a,1),-2,min(1280,ih))'";function vb(e,t){return["-y","-loglevel","error","-i",e,"-vf",bb,"-c:v","libx264","-preset","medium","-crf","27","-pix_fmt","yuv420p","-c:a","aac","-b:a","96k","-movflags","+faststart","-f","mp4",t]}function Ob(e,t,n){return new Promise((o,i)=>{if(n?.aborted){i(new Error("aborted"));return}let r=Ab("ffmpeg",vb(e,t),{stdio:["ignore","ignore","pipe"]}),s="";r.stderr?.on("data",c=>{s+=String(c)});let a=()=>{r.kill("SIGKILL")};n?.addEventListener("abort",a,{once:!0}),r.on("error",c=>{n?.removeEventListener("abort",a),i(c)}),r.on("close",c=>{n?.removeEventListener("abort",a),c===0?o():i(new Error(`ffmpeg exited ${c}: ${s.trim().slice(0,300)}`))})})}async function Ow(e,t,n,o){if(wt.existsSync(t)&&(wt.statSync(t).size??0)>0)return{path:t,mime:"video/mp4",transcoded:!0};let i=0;try{i=wt.statSync(e).size}catch{}if(i>0&&i<=kb)return{path:e,mime:n,transcoded:!1,note:`already ${(i/1024/1024).toFixed(1)}MB (\u226420MB)`};let r=`${t}.part`;try{if(wt.mkdirSync(vw.dirname(t),{recursive:!0}),wt.rmSync(r,{force:!0}),await Ob(e,r,o),!wt.existsSync(r)||wt.statSync(r).size===0)throw new Error("ffmpeg produced no output");return wt.renameSync(r,t),{path:t,mime:"video/mp4",transcoded:!0}}catch(s){try{wt.rmSync(r,{force:!0}),wt.rmSync(t,{force:!0})}catch{}if(o?.aborted)throw s instanceof Error?s:new Error(String(s));let a=s instanceof Error?s.message:String(s);return{path:e,mime:n,transcoded:!1,note:`transcode failed, uploading original (${a})`}}}import{spawn as Rb}from"node:child_process";import*as Qe from"node:fs";import*as Rw from"node:path";var Mb="scale='if(gt(a,1),min(960,iw),-2)':'if(gt(a,1),-2,min(960,ih))'",Nb=4;function Lb(e){let t=Ew(e);return t===null?null:(t/1e3).toFixed(3)}var Ub=async(e,t,n,o)=>{if(o?.aborted)throw new Error("aborted");let i=Lb(t);if(i===null)return{ok:!1,error:"invalid timestamp"};try{if(!Qe.existsSync(e)||Qe.statSync(e).size===0)return{ok:!1,error:"source video is unavailable or empty"}}catch{return{ok:!1,error:"source video is unavailable"}}Qe.mkdirSync(Rw.dirname(n),{recursive:!0});let r=`${n}.part`;return Qe.rmSync(r,{force:!0}),new Promise((s,a)=>{let c=Rb("ffmpeg",["-y","-loglevel","error","-ss",i,"-i",e,"-frames:v","1","-vf",Mb,"-q:v","3","-f","image2",r],{stdio:["ignore","ignore","pipe"]});c.stderr?.resume();let d=()=>{c.kill("SIGKILL")};o?.addEventListener("abort",d,{once:!0}),c.on("error",()=>{o?.removeEventListener("abort",d),Qe.rmSync(r,{force:!0}),o?.aborted?a(new Error("aborted")):s({ok:!1,error:"frame extractor unavailable"})}),c.on("close",p=>{if(o?.removeEventListener("abort",d),o?.aborted){Qe.rmSync(r,{force:!0}),a(new Error("aborted"));return}if(p===0&&Qe.existsSync(r)&&Qe.statSync(r).size>0){Qe.renameSync(r,n),s({ok:!0});return}Qe.rmSync(r,{force:!0}),s({ok:!1,error:`frame extraction failed (exit ${p??"unknown"})`})})})};function Pb(e){let{source_path:t,...n}=e;return n}async function Oc(e,t,n,o=Ub,i={}){let r=i.reuseExistingFrames!==!1,s=[...t.items.flatMap(h=>h.samples),...(t.identities??[]).flatMap(h=>h.samples)],a=new Map,c=0,d=async()=>{for(;;){let h=c;if(c+=1,h>=s.length)return;if(n?.aborted)throw new Error("aborted");let m=s[h],g=e.path(m.frame_path),w;r&&Qe.existsSync(g)&&Qe.statSync(g).size>0?w={ok:!0}:(Qe.rmSync(g,{force:!0}),w=await o(m.source_path,m.timestamp,g,n)),a.set(m,Pb({...m,frame_status:w.ok?"ready":"unavailable",...w.error?{error:w.error}:{}}))}};await Promise.all(Array.from({length:Math.min(Nb,s.length)},()=>d()));let p=h=>h.map(m=>a.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 Cb=new Set(["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","voice"]),lu=()=>({apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:[],voice:""}),Pr=(e,t)=>{let n=e.split("|"),o=n.slice(0,t-1).map(r=>r.trim()),i=n.slice(t-1).join("|").trim();for(;o.length<t-1;)o.push("");return[...o,i]};function uu(e){let t=[],n=[],o=[],i=[],r=[],s=[],a=[],c="",d,p,l=!1,f=0;for(let u of e.split(/\r?\n/)){let h=u.replace(/|/g,"|").trim().replace(/^[-*]\s+/,"");if(!h||h.startsWith("```"))continue;f++;let g=d&&!p&&/^\d{2}:\d{2}\|[^|]*\|/.test(h)&&h.split("|").length===3?["","shot",h]:/^([a-z_]+):?\s*(.*)$/.exec(h),w=g?.[1]??"",y=g?.[2]??"",E=_=>p[_];if(w==="synopsis"){c=y;continue}if(w==="scene"){let[_,x,A,b]=Pr(y,4);d={space:_,time:x,timeRange:A,location:b,characters:[],props:[],shots:[],voices:[]},t.push(d),p=void 0;continue}if(d&&!p){if(w==="char"){let[_,...x]=y.split("|").map(A=>A.trim());_&&d.characters.push({name:_,states:x.filter(Boolean)});continue}if(w==="props"){d.props.push(...y.split("|").map(_=>_.trim()).filter(Boolean));continue}if(w==="shot"){let[_,x,A]=Pr(y,3);d.shots.push({ts:_,camera:x,visual:A});continue}if(w==="dlg"||w==="think"){let[_,x,A,b]=Pr(y,4);d.voices.push({kind:w,speaker:x,parenthetical:A,ts:_,content:b});continue}}if(w==="new"){let[_,x,A,b]=Pr(y,4);p={name:x,kind:_,status:A,importance:b,recognition_anchors:[],identity_profile:lu(),appearance:"",role:"",states:[],aliases:[]},l=!1,n.push(p);continue}if(w==="enrich"){p={name:y.trim(),add_recognition_anchors:[],identity_profile_patch:lu(),appearance:"",add_aliases:[],add_states:[]},l=!0,o.push(p);continue}if(w==="rename"){let[_,x,A]=Pr(y,3);i.push({from_name:_,canonical_name:x,evidence:A}),p=void 0;continue}if(w==="open"){r.push({text:y.trim()}),p=void 0;continue}if(w==="close"){s.push({ref:y.trim()}),p=void 0;continue}if(p){if(l&&w==="identity_revision"){p.identity_revision={profile:lu(),recognition_anchors:[]};continue}let _=p.identity_revision,x=_?.profile??p[l?"identity_profile_patch":"identity_profile"];if(Cb.has(w)){x[w]=y.trim();continue}let A=y.split("|").map(b=>b.trim()).filter(Boolean);if(w==="mark"){x.persistent_marks.push(...A);continue}if(w==="anchor"||w==="anchors"){(_?_.recognition_anchors:E(l?"add_recognition_anchors":"recognition_anchors")).push(...A);continue}if(w==="alias"){E(l?"add_aliases":"aliases").push(...A);continue}if(w==="role"||w==="appearance"){p[w]=y.trim();continue}if(w==="state"){let[b,U]=Pr(y,2);E(l?"add_states":"states").push({name:b,description:U});continue}}a.push(h)}return{value:{synopsis:c,scenes:t,registry_delta:{new_entities:n,enrich:o,canonicalize:i},open_threads:{opened:r,closed:s}},recognized:f-a.length,unknown:a}}var Mw=e=>uu(e).recognized>0,Nw=`\u3010\u8F93\u51FA\u683C\u5F0F\uFF1A\u884C\u5F0F DSL\u3011\u53EA\u8F93\u51FA\u4E0B\u5217\u683C\u5F0F\u7684\u7EAF\u6587\u672C\uFF0C\u4E0D\u8981 JSON\u3001Markdown \u4EE3\u7801\u5757\u3001\u6807\u9898\u6216\u4EFB\u4F55\u89E3\u91CA\u3002\u4E00\u884C\u4E00\u6761\u8BB0\u5F55\uFF1A\u884C\u9996\u662F\u5C0F\u5199\u6807\u7B7E\uFF0C\u6807\u7B7E\u540E\u4E00\u4E2A\u7A7A\u683C\uFF0C\u5B57\u6BB5\u4E4B\u95F4\u7528\u534A\u89D2 | \u5206\u9694\uFF1B\u6700\u540E\u4E00\u4E2A\u5B57\u6BB5\u53EF\u4EE5\u5305\u542B\u4EFB\u610F\u6587\u5B57\u3002\u4EFB\u4F55\u503C\u5185\u90FD\u4E0D\u6362\u884C\u3001\u4E0D\u5199 |\u3002\u53EF\u9009\u5B57\u6BB5\u4E3A\u7A7A\u65F6\u4FDD\u7559\u5206\u9694\u7B26\u3002\u89C4\u5219\u6B63\u6587\u91CC\u7684\u5B57\u6BB5\u540D\u4E0E\u672C\u683C\u5F0F\u5BF9\u5E94\uFF1Ascenes=scene \u5757\uFF0Cshots=shot \u884C\uFF0Cvoices=dlg/think \u884C\uFF0Cregistry_delta.new_entities=new \u5757\uFF0Cenrich=enrich \u5757\uFF0Ccanonicalize=rename \u884C\uFF0Copen_threads=open/close \u884C\uFF0Cidentity_revision=\u6E05\u7A7A\u753B\u50CF\u4E0E\u951A\u70B9\u884C\u3002
|
|
285
|
+
`);let U="upload";try{g??=e.executor.documentPort("ingest.comic-serial");let v=n.path(`${x}.input.pdf`);Vn(v,Buffer.from(await Fy(mo.readFileSync(E.path))));let I=await g.prepare(v,e.signal),R;try{U="generate";let se=A&&n.has(`${x}.response.json`)&&s.current_error?.phase==="validation"?au(mo.readFileSync(n.path(`${x}.response.json`),"utf8"),E.page_count):await ew(g,I,E.title,E.page_count,b,z=>n.writeText(`${x}.response.json`,z),e.signal);R={episode:E.episode,document_id:E.document_id,title:E.title,output:se}}finally{await g.release(I,e.signal)}U="validation";let C=Vs(structuredClone(a.context),R.output,E.episode),N=[...c,R],M;try{M=bc(N,{context:C,identityMap:a.identityMap},p)}catch(se){if(!(se instanceof S)||se.errorCode!=="INGEST_VALIDATION_FAILED")throw se;process.stderr.write(`\u6B63\u5728\u6839\u636E\u539F\u7A3F\u8865\u5168\u4EBA\u7269\u3001\u5730\u70B9\u548C\u9053\u5177\u767B\u8BB0\uFF0C\u4FDD\u7559\u5DF2\u8F6C\u5F55\u6B63\u6587\u2026
|
|
286
|
+
`);let z=await g.prepare(v,e.signal);try{R.output.registry_delta=await tw(g,z,R.output,b,se.message,e.signal),n.writeJson(`${x}.response.json`,R.output)}finally{await g.release(z,e.signal)}C=Vs(structuredClone(a.context),R.output,E.episode),M=bc(N,{context:C,identityMap:a.identityMap},p)}let K={context:C,identityMap:M.identityMap};U="checkpoint",n.writeJson(`${x}.json`,R),n.writeJson("checkpoint.json",K),a=K,c.push(R),U="publish",cu(n,M,a.context),n.clearError(`${x}.error.json`),delete s.current_error,s.updated=new Date().toISOString(),n.writeJson("manifest.json",s),h++;let X=Date.now();f.windowDone(E.episode,E.episode,X-_,!1),l.flush({scope:{kind:"episode",episode:E.episode},status:"succeeded",startedAtMs:_,endedAtMs:X});let Ke=R.output.scenes.reduce((se,z)=>se+z.actions.length,0);process.stderr.write(` \u5DF2\u4FDD\u5B58\uFF1A${R.output.scenes.length} \u573A / ${Ke} \u6761\u6B63\u6587
|
|
287
|
+
`)}catch(v){let I=Ac(v,E.episode,U);throw n.writeJson(`${x}.error.json`,I),n.writeJson("manifest.json",{...s,updated:I.occurred_at,current_error:I}),l.flush({scope:{kind:"episode",episode:E.episode},status:"failed",startedAtMs:_,endedAtMs:Date.now()}),v}}let w=bc(c,a,p);cu(n,w,a.context);let y=c.length===r.length;return u="succeeded",{workspace:n.root,script_path:n.path("script.json"),kind:"comic",episodes:r.length,processed:h,reused:m,completed:c.length,remaining:r.length-c.length,complete:y,next_episode:y?null:c.length+1,assets:{actors:w.scriptV4.actors.length,locations:w.scriptV4.locations.length,props:w.scriptV4.props.length}}}finally{f.phaseEnd("serial"),f.finish(),l.finish(u)}}async function sw(e){return Wo(e.workspacePath,()=>xb(e))}import*as Rt from"node:fs";import*as Xt from"node:path";function Eb(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 aw(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=Eb(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 vc(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 Lr(e){let t=typeof e=="string"?e.trim():"",n=t.match(/^(?:(\d+):)?(\d+):(\d{2})(\.\d{1,3})?$/);if(!n)return t;let o=Number(n[1]??0),i=Number(n[2]),r=Number(n[3]);if(![o,i,r].every(Number.isSafeInteger))return t;let s=o*3600+i*60+r,a=Math.floor(s/3600),c=Math.floor(s%3600/60),d=s%60;return(a>0?`${a}:${String(c).padStart(2,"0")}:${String(d).padStart(2,"0")}`:`${String(c).padStart(2,"0")}:${String(d).padStart(2,"0")}`)+(n[4]??"")}function Ur(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 cw=e=>String(e).padStart(3,"0"),_b={\u5185:"interior",\u5916:"exterior"},Sb={act:"action",dlg:"dialogue",think:"inner_thought"},du={broadcast:"broadcast",system:"system",group:"group",offscreen:"offscreen",prop:"offscreen",location:"offscreen"};function Ib(e){let t=e.match(/^(\w+):(.+)$/);if(t&&du[t[1]]){let n=t[2].trim();return n?{kind:du[t[1]],label:n}:{kind:du[t[1]]}}return ut(e)?{kind:"group",label:e.trim()}:{name:e}}function dw(e,t){let n=0,o=e.map((i,r)=>{let s=`video:episode:${i.episode}`,a=new Map;return{identity_key:s,episode_id:`ep_${cw(r+1)}`,scenes:i.scenes.map(c=>{let d=c.timeRange?.trim()?`time:${c.timeRange.trim()}`:`index:${c.index}`,p=(a.get(d)??0)+1;a.set(d,p);let l=`${s}:scene:${d}:${p}`,f={},u=_b[(c.environment.space??"").trim()],h=Ko(c.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 c.characters)A.name&&!ut(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=c.anchors.map(A=>{let b=Lr(A.ts),U=b?`time:${b}`:`content:${JSON.stringify([A.kind,A.speaker??"",A.content])}`,v=(w.get(U)??0)+1;w.set(U,v);let I={identity_key:`${l}:action:${U}:${v}`,type:Sb[A.kind]??"action",content:A.content};if((A.kind==="dlg"||A.kind==="think")&&A.speaker){let C=Ib(A.speaker);I.speaker=C,"name"in C&&g(C.name)}A.parenthetical&&(I.parenthetical=A.parenthetical);let R=Lr(A.ts);return R&&(I.extend={timestamp:R}),I}),E=(c.location??"").trim(),_=[],x=new Set;for(let A of c.props??[]){if(!A)continue;let b=A.normalize("NFC").replace(/\s+/g," ").trim();!b||x.has(b)||(x.add(b),_.push({name:A}))}return{identity_key:l,scene_id:`scn_${cw(++n)}`,...f.space||f.time?{environment:f}:{},location:E?{name:E}:null,actors:m,props:_,actions:y}})}});return{title:t,episodes:o}}var Ab=60,kb=6,bb=[-1e3,0,1e3],fw=/(?:身穿|穿着|服装|造型|衣|裙|袍|衫|夹克|制服|西装|盔甲|装甲|防弹服|套装|裤|靴)/u,pu=/(?:全身|半身|上半身|四分之三身|躯干|胸前|腰部)/u,lu=/(?:站(?:在|立)|坐(?:在|下|起)|跪(?:在|下|倒)?|蹲(?:在|下)?|走(?:在|出|向)|行走|迈步|奔跑|跳起|跃起|转身|抬头|转头)/u,pw=/(?:特写|近景|脸|面容|五官|正脸|侧脸|侧前脸|双眼|眼眶|眉头|嘴角)/u,mw=/(?:背对|背影|远处|极远|模糊|运动模糊|脸被遮|面部遮挡|只露出|纯道具|空镜)/u,gw=/(?:双脚|脚部|膝盖|伤口|手部特写)/u,hw=/(?:画外音|旁白|未入镜|镜外|电话音|广播|\bO\.?S\.?\b)/iu;function Zo(e){return e.normalize("NFC").replace(/\s+/g," ").trim()}function yw(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 ww(e){let t=e.trim().match(/^(\d+):(\d{2})$/);return t?Number(t[1])*1e3+Number(t[2])*10:null}function xw(e,t="clock"){return t==="legacy_centiseconds"?ww(e):yw(e)}function uu(e,t){return e===null?!1:t===void 0||e<=t}function vb(e,t){if(t===void 0)return"clock";let n=e.scenes.flatMap(r=>r.actions.map(Ew)).filter(Boolean),o=n.filter(r=>uu(yw(r),t)).length;return n.filter(r=>uu(ww(r),t)).length>o?"legacy_centiseconds":"clock"}function lw(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 Ew(e){let t=e.extend?.timestamp;return typeof t=="string"?t.trim():""}function Ob(e,t){let n=new Set([e.actor_name,...e.aliases??[]].map(Zo).filter(Boolean));for(let[o,i]of t)Zo(i)===Zo(e.actor_name)&&n.add(Zo(o));return[...n].sort((o,i)=>i.length-o.length)}function _w(e,t){let n=t.map(o=>e.indexOf(o)).filter(o=>o>=0);return n.length>0?Math.min(...n):-1}function Sw(e,t,n){return t.filter(o=>_w(e,n.get(o.actor_id)??[])>=0).length}function Rb({action:e,actor:t,actorCount:n,allActors:o,surfaces:i,surfacesByActor:r,stateName:s}){let a=e.type==="action"||e.type==="transition",c=Zo(a?e.content:"parenthetical"in e?e.parenthetical??"":""),d=_w(c,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&&!hw.test(c),h=n===1&&(a&&c.length>0||u&&c.length>0&&(lu.test(c)||pw.test(c)));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=Zo(s);return y&&y!=="default"&&y!=="\u9ED8\u8BA4"&&c.includes(y)&&(g+=35),fw.test(c)&&(g+=30),pu.test(c)?(g+=25,w+=15):lu.test(c)&&(g+=15,w+=5),pw.test(c)&&(w+=30,pu.test(c)||(g-=20)),mw.test(c)&&(g-=70,w-=70),gw.test(c)&&(g-=40),Sw(c,o,r)>=2&&(g-=15,w-=15),{stateScore:g,identityScore:w,selection:m}}function Mb(e,t,n){let o=e.type==="action"||e.type==="transition",i="parenthetical"in e?Zo(e.parenthetical??""):"";if(!o&&hw.test(i))return null;let r=Zo(o?e.content:i),s=o?0:-40;return s-=Sw(r,t,n)*20,fw.test(r)&&(s+=10),pu.test(r)?s+=10:lu.test(r)&&(s+=5),mw.test(r)&&(s-=20),gw.test(r)&&(s-=10),{stateScore:s,identityScore:Number.NEGATIVE_INFINITY,selection:"scene_fallback"}}function Gs(e,t,n){let o=(n.get(`${e.episode}:${e.milliseconds}`)?.size??0)>1;return e[t]-(o?35:0)}function Iw(e,t,n,o,i){let r=new Map;for(let c of e){let d=`${c.episode}:${c.milliseconds}`,p=r.get(d);(!p||Gs(c,t,n)>Gs(p,t,n))&&r.set(d,c)}let s=[...r.values()].sort((c,d)=>Gs(d,t,n)-Gs(c,t,n)||c.episode-d.episode||c.milliseconds-d.milliseconds).filter(c=>i===null||Gs(c,t,n)>=i),a=[];for(let c of s)if(!a.some(p=>p.episode===c.episode&&p.sceneId===c.sceneId&&Math.abs(p.milliseconds-c.milliseconds)<3e3)&&(a.push(c),a.length>=o))break;return a}function Nb(e,t,n){return Iw(e,t,n,1,null)[0]??null}function uw(e){return e.replace(/[^0-9]+/g,"-").replace(/^-|-$/g,"")||"unknown"}function Oc(e,t,n,o,i){let r=new Map(o.map(g=>[g.episode,g])),s=qo(n.registry),a=new Map(t.actors.map(g=>[g.actor_id,g])),c=new Map(t.actors.map(g=>[g.actor_id,Ob(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,E=r.get(y);if(!E)continue;let _=vb(w,E.duration_ms);for(let x=0;x<w.scenes.length;x+=1){let A=w.scenes[x],b=A.actors.map(U=>a.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 v=a.get(U.actor_id);if(!v)continue;let I=c.get(v.actor_id)??[v.actor_name],R=[],C=U.state_ids.length===1?U.state_ids[0]:null,N=C?v.states.find(M=>M.state_id===C):null;for(let M of A.actions){let K=Ew(M),X=xw(K,_);if(!uu(X,E.duration_ms))continue;let Ke=Rb({action:M,actor:v,actorCount:b.length,allActors:b,surfaces:I,surfacesByActor:c,stateName:N?.state_name??"default"}),se=Ke??(N?Mb(M,b,c):null);if(!se)continue;let z={actorId:v.actor_id,episode:y,episodeId:w.episode_id,sceneId:A.scene_id,timestamp:lw(X),milliseconds:X,durationMs:E.duration_ms,stateScore:se.stateScore,identityScore:se.identityScore,selection:se.selection,sourcePath:E.path,sourceSha256:E.sha256};if(R.push(z),Ke){let Nt=`${y}:${X}`,P=f.get(Nt)??new Set;P.add(v.actor_id),f.set(Nt,P)}}if(R.length>0){let M=p.get(v.actor_id)??[];if(M.push(...R),p.set(v.actor_id,M),N){let K=`${v.actor_id}:${N.state_id}`,X=l.get(K)??[];X.push(...R),l.set(K,X)}}}}}let u=(g,w)=>{let y=a.get(g),E=a.get(w),_=y?.importance==="background"?1:0,x=E?.importance==="background"?1:0;return _-x||(d.get(w)??0)-(d.get(g)??0)||(y?.actor_name??g).localeCompare(E?.actor_name??w,"zh-CN")},h=[...l.entries()].flatMap(([g,w])=>{let[y,E]=g.split(":"),_=y?a.get(y):void 0,x=_?.states.find(v=>v.state_id===E),A=Nb(w,"stateScore",f);if(!_||!x||!A)return[];let b=`state:${_.actor_id}:${x.state_id}`,U=bb.map(v=>{let I=A.durationMs===void 0?Number.POSITIVE_INFINITY:Math.max(0,A.durationMs-50),R=Math.min(I,Math.max(0,A.milliseconds+v)),C=lw(R);return{evidence_id:`${b}:${A.episode}:${C}`,episode:A.episode,episode_id:A.episodeId,scene_id:A.sceneId,timestamp:C,offset_ms:v,selection:A.selection,source_sha256:A.sourceSha256,source_path:A.sourcePath,frame_path:`evidence/frames/${_.actor_id}/${x.state_id}/ep_${String(A.episode).padStart(3,"0")}_${uw(C)}.jpg`,frame_status:"pending"}}).filter((v,I,R)=>R.findIndex(C=>C.timestamp===v.timestamp)===I);return[{evidence_id:b,asset_kind:"actor",actor_id:_.actor_id,actor_name:_.actor_name,state_id:x.state_id,state_name:x.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=a.get(g),E=Iw(w,"identityScore",f,kb,Ab);if(!y||E.length===0)return[];let _=`identity:${y.actor_id}`;return[{evidence_id:_,asset_kind:"actor",actor_id:y.actor_id,actor_name:y.actor_name,samples:E.map(x=>({evidence_id:`${_}:${x.episode}:${x.timestamp}`,episode:x.episode,episode_id:x.episodeId,scene_id:x.sceneId,timestamp:x.timestamp,offset_ms:0,selection:x.selection,source_sha256:x.sourceSha256,source_path:x.sourcePath,frame_path:`evidence/frames/${y.actor_id}/identity/ep_${String(x.episode).padStart(3,"0")}_${uw(x.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 Aw(e){return xw(e)}function kw(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(a=>({kind:a.kind,...a.speaker?{speaker:a.speaker}:{},...a.parenthetical?{parenthetical:a.parenthetical}:{},...a.ts?{ts:a.ts}:{},content:a.content??""}));return{index:i+1,environment:r,...o.timeRange?{timeRange:o.timeRange}:{},...o.location?{location:o.location}:{},characters:(o.characters??[]).filter(a=>a.name).map(a=>({name:a.name,states:[...a.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 Rc from"node:path";function vw(e){return Rc.extname(e).toLowerCase()}function Lb(e){return ml[vw(e)]??"application/octet-stream"}function bw(e,t){return new S(e,{exitCode:k,errorCode:"INGEST_VIDEO_DISCOVERY",hint:"Name every episode file with a number, or none of them, and rerun `scriptctl ingest`.",data:{actual:t}})}function fu(e,t){return{episode:t,path:e,ext:vw(e),mime:Lb(e)}}function Pr(e){if(e.kind!=="video-file"&&e.kind!=="video-directory")throw new S("Expected video source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});if(e.kind==="video-file")return[fu(e.path,1)];let t=e.files,n=t.map(Rr),o=n.filter(r=>r!==null);if(o.length===0)return t.map((r,s)=>fu(r,s+1));if(o.length!==t.length){let r=t.filter((s,a)=>n[a]===null).map(s=>Rc.basename(s));throw bw("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 bw("Two episode files resolve to the same number.",[`duplicate episode: ${r}`]);i.add(r)}return t.map((r,s)=>fu(r,n[s])).sort((r,s)=>r.episode-s.episode)}import*as Ow from"node:fs";import*as Rw from"node:path";function Mw(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=Rw.resolve(r.path),a=Ow.statSync(s),c=a.size,d=Math.trunc(a.mtimeMs),p=o.get(r.episode),l=p&&p.size_bytes===c&&p.mtime_ms===d,f=p&&p.size_bytes===void 0&&p.mtime_ms===void 0&&p.path===s&&Number.isFinite(i)&&a.mtimeMs<=i,u=p&&p.ext===r.ext&&p.mime===r.mime&&(l||f)?p.sha256:gd(s);return{episode:r.episode,path:s,ext:r.ext,mime:r.mime,sha256:u,size_bytes:c,mtime_ms:d}})}function Mc(e){return _e(JSON.stringify(e.map(t=>({episode:t.episode,ext:t.ext,mime:t.mime,sha256:t.sha256}))))}import{spawn as Ub}from"node:child_process";import*as wt from"node:fs";import*as Nw from"node:path";var Pb=20*1024*1024,Cb="scale='if(gt(a,1),min(1280,iw),-2)':'if(gt(a,1),-2,min(1280,ih))'";function Tb(e,t){return["-y","-loglevel","error","-i",e,"-vf",Cb,"-c:v","libx264","-preset","medium","-crf","27","-pix_fmt","yuv420p","-c:a","aac","-b:a","96k","-movflags","+faststart","-f","mp4",t]}function Vb(e,t,n){return new Promise((o,i)=>{if(n?.aborted){i(new Error("aborted"));return}let r=Ub("ffmpeg",Tb(e,t),{stdio:["ignore","ignore","pipe"]}),s="";r.stderr?.on("data",c=>{s+=String(c)});let a=()=>{r.kill("SIGKILL")};n?.addEventListener("abort",a,{once:!0}),r.on("error",c=>{n?.removeEventListener("abort",a),i(c)}),r.on("close",c=>{n?.removeEventListener("abort",a),c===0?o():i(new Error(`ffmpeg exited ${c}: ${s.trim().slice(0,300)}`))})})}async function Lw(e,t,n,o){if(wt.existsSync(t)&&(wt.statSync(t).size??0)>0)return{path:t,mime:"video/mp4",transcoded:!0};let i=0;try{i=wt.statSync(e).size}catch{}if(i>0&&i<=Pb)return{path:e,mime:n,transcoded:!1,note:`already ${(i/1024/1024).toFixed(1)}MB (\u226420MB)`};let r=`${t}.part`;try{if(wt.mkdirSync(Nw.dirname(t),{recursive:!0}),wt.rmSync(r,{force:!0}),await Vb(e,r,o),!wt.existsSync(r)||wt.statSync(r).size===0)throw new Error("ffmpeg produced no output");return wt.renameSync(r,t),{path:t,mime:"video/mp4",transcoded:!0}}catch(s){try{wt.rmSync(r,{force:!0}),wt.rmSync(t,{force:!0})}catch{}if(o?.aborted)throw s instanceof Error?s:new Error(String(s));let a=s instanceof Error?s.message:String(s);return{path:e,mime:n,transcoded:!1,note:`transcode failed, uploading original (${a})`}}}import{spawn as $b}from"node:child_process";import*as Qe from"node:fs";import*as Uw from"node:path";var Db="scale='if(gt(a,1),min(960,iw),-2)':'if(gt(a,1),-2,min(960,ih))'",Gb=4;function Bb(e){let t=Aw(e);return t===null?null:(t/1e3).toFixed(3)}var Jb=async(e,t,n,o)=>{if(o?.aborted)throw new Error("aborted");let i=Bb(t);if(i===null)return{ok:!1,error:"invalid timestamp"};try{if(!Qe.existsSync(e)||Qe.statSync(e).size===0)return{ok:!1,error:"source video is unavailable or empty"}}catch{return{ok:!1,error:"source video is unavailable"}}Qe.mkdirSync(Uw.dirname(n),{recursive:!0});let r=`${n}.part`;return Qe.rmSync(r,{force:!0}),new Promise((s,a)=>{let c=$b("ffmpeg",["-y","-loglevel","error","-ss",i,"-i",e,"-frames:v","1","-vf",Db,"-q:v","3","-f","image2",r],{stdio:["ignore","ignore","pipe"]});c.stderr?.resume();let d=()=>{c.kill("SIGKILL")};o?.addEventListener("abort",d,{once:!0}),c.on("error",()=>{o?.removeEventListener("abort",d),Qe.rmSync(r,{force:!0}),o?.aborted?a(new Error("aborted")):s({ok:!1,error:"frame extractor unavailable"})}),c.on("close",p=>{if(o?.removeEventListener("abort",d),o?.aborted){Qe.rmSync(r,{force:!0}),a(new Error("aborted"));return}if(p===0&&Qe.existsSync(r)&&Qe.statSync(r).size>0){Qe.renameSync(r,n),s({ok:!0});return}Qe.rmSync(r,{force:!0}),s({ok:!1,error:`frame extraction failed (exit ${p??"unknown"})`})})})};function zb(e){let{source_path:t,...n}=e;return n}async function Nc(e,t,n,o=Jb,i={}){let r=i.reuseExistingFrames!==!1,s=[...t.items.flatMap(h=>h.samples),...(t.identities??[]).flatMap(h=>h.samples)],a=new Map,c=0,d=async()=>{for(;;){let h=c;if(c+=1,h>=s.length)return;if(n?.aborted)throw new Error("aborted");let m=s[h],g=e.path(m.frame_path),w;r&&Qe.existsSync(g)&&Qe.statSync(g).size>0?w={ok:!0}:(Qe.rmSync(g,{force:!0}),w=await o(m.source_path,m.timestamp,g,n)),a.set(m,zb({...m,frame_status:w.ok?"ready":"unavailable",...w.error?{error:w.error}:{}}))}};await Promise.all(Array.from({length:Math.min(Gb,s.length)},()=>d()));let p=h=>h.map(m=>a.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 Kb=new Set(["apparent_gender","apparent_age","face_shape","brows_eyes","nose","mouth","skin_features","hair","build","voice"]),mu=()=>({apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:[],voice:""}),Cr=(e,t)=>{let n=e.split("|"),o=n.slice(0,t-1).map(r=>r.trim()),i=n.slice(t-1).join("|").trim();for(;o.length<t-1;)o.push("");return[...o,i]};function gu(e){let t=[],n=[],o=[],i=[],r=[],s=[],a=[],c="",d,p,l=!1,f=0;for(let u of e.split(/\r?\n/)){let h=u.replace(/|/g,"|").trim().replace(/^[-*]\s+/,"");if(!h||h.startsWith("```"))continue;f++;let g=d&&!p&&/^\d{2}:\d{2}\|[^|]*\|/.test(h)&&h.split("|").length===3?["","shot",h]:/^([a-z_]+):?\s*(.*)$/.exec(h),w=g?.[1]??"",y=g?.[2]??"",E=_=>p[_];if(w==="synopsis"){c=y;continue}if(w==="scene"){let[_,x,A,b]=Cr(y,4);d={space:_,time:x,timeRange:A,location:b,characters:[],props:[],shots:[],voices:[]},t.push(d),p=void 0;continue}if(d&&!p){if(w==="char"){let[_,...x]=y.split("|").map(A=>A.trim());_&&d.characters.push({name:_,states:x.filter(Boolean)});continue}if(w==="props"){d.props.push(...y.split("|").map(_=>_.trim()).filter(Boolean));continue}if(w==="shot"){let[_,x,A]=Cr(y,3);d.shots.push({ts:_,camera:x,visual:A});continue}if(w==="dlg"||w==="think"){let[_,x,A,b]=Cr(y,4);d.voices.push({kind:w,speaker:x,parenthetical:A,ts:_,content:b});continue}}if(w==="new"){let[_,x,A,b]=Cr(y,4);p={name:x,kind:_,status:A,importance:b,recognition_anchors:[],identity_profile:mu(),appearance:"",role:"",states:[],aliases:[]},l=!1,n.push(p);continue}if(w==="enrich"){p={name:y.trim(),add_recognition_anchors:[],identity_profile_patch:mu(),appearance:"",add_aliases:[],add_states:[]},l=!0,o.push(p);continue}if(w==="rename"){let[_,x,A]=Cr(y,3);i.push({from_name:_,canonical_name:x,evidence:A}),p=void 0;continue}if(w==="open"){r.push({text:y.trim()}),p=void 0;continue}if(w==="close"){s.push({ref:y.trim()}),p=void 0;continue}if(p){if(l&&w==="identity_revision"){p.identity_revision={profile:mu(),recognition_anchors:[]};continue}let _=p.identity_revision,x=_?.profile??p[l?"identity_profile_patch":"identity_profile"];if(Kb.has(w)){x[w]=y.trim();continue}let A=y.split("|").map(b=>b.trim()).filter(Boolean);if(w==="mark"){x.persistent_marks.push(...A);continue}if(w==="anchor"||w==="anchors"){(_?_.recognition_anchors:E(l?"add_recognition_anchors":"recognition_anchors")).push(...A);continue}if(w==="alias"){E(l?"add_aliases":"aliases").push(...A);continue}if(w==="role"||w==="appearance"){p[w]=y.trim();continue}if(w==="state"){let[b,U]=Cr(y,2);E(l?"add_states":"states").push({name:b,description:U});continue}}a.push(h)}return{value:{synopsis:c,scenes:t,registry_delta:{new_entities:n,enrich:o,canonicalize:i},open_threads:{opened:r,closed:s}},recognized:f-a.length,unknown:a}}var Pw=e=>gu(e).recognized>0,Cw=`\u3010\u8F93\u51FA\u683C\u5F0F\uFF1A\u884C\u5F0F DSL\u3011\u53EA\u8F93\u51FA\u4E0B\u5217\u683C\u5F0F\u7684\u7EAF\u6587\u672C\uFF0C\u4E0D\u8981 JSON\u3001Markdown \u4EE3\u7801\u5757\u3001\u6807\u9898\u6216\u4EFB\u4F55\u89E3\u91CA\u3002\u4E00\u884C\u4E00\u6761\u8BB0\u5F55\uFF1A\u884C\u9996\u662F\u5C0F\u5199\u6807\u7B7E\uFF0C\u6807\u7B7E\u540E\u4E00\u4E2A\u7A7A\u683C\uFF0C\u5B57\u6BB5\u4E4B\u95F4\u7528\u534A\u89D2 | \u5206\u9694\uFF1B\u6700\u540E\u4E00\u4E2A\u5B57\u6BB5\u53EF\u4EE5\u5305\u542B\u4EFB\u610F\u6587\u5B57\u3002\u4EFB\u4F55\u503C\u5185\u90FD\u4E0D\u6362\u884C\u3001\u4E0D\u5199 |\u3002\u53EF\u9009\u5B57\u6BB5\u4E3A\u7A7A\u65F6\u4FDD\u7559\u5206\u9694\u7B26\u3002\u89C4\u5219\u6B63\u6587\u91CC\u7684\u5B57\u6BB5\u540D\u4E0E\u672C\u683C\u5F0F\u5BF9\u5E94\uFF1Ascenes=scene \u5757\uFF0Cshots=shot \u884C\uFF0Cvoices=dlg/think \u884C\uFF0Cregistry_delta.new_entities=new \u5757\uFF0Cenrich=enrich \u5757\uFF0Ccanonicalize=rename \u884C\uFF0Copen_threads=open/close \u884C\uFF0Cidentity_revision=\u6E05\u7A7A\u753B\u50CF\u4E0E\u951A\u70B9\u884C\u3002
|
|
281
288
|
\u6309\u4EE5\u4E0B\u987A\u5E8F\u8F93\u51FA\uFF1A
|
|
282
289
|
synopsis \u672C\u96C6\u5267\u60C5\u6897\u6982\uFF0C\u6309\u53D1\u751F\u987A\u5E8F\uFF0C200-300 \u5B57\u7EAF\u6587\u672C
|
|
283
290
|
\u8D44\u4EA7\u767B\u8BB0\uFF1A\u5148\u5199\u6240\u9700\u7684 new / enrich / rename \u5757\u3002\u65E7\u5224\u65AD\u7684\u9636\u6BB5\u4FEE\u8BA2\u5C5E\u4E8E\u672C\u6B21\u589E\u91CF\uFF1B\u6CA1\u6709\u65B0\u8BC1\u636E\u4E14\u65E0\u9700\u4FEE\u8BA2\u7684\u5B9E\u4F53\u7701\u7565\u3002
|
|
@@ -314,25 +321,25 @@ shot 00:00|\u5168\u666F\uFF0C\u5E73\u89C6\uFF0C\u56FA\u5B9A|\u6797\u665A\u5750\u
|
|
|
314
321
|
shot 00:03|\u8FD1\u666F\uFF0C\u6797\u665A\u6B63\u9762\uFF0C\u7F13\u63A8|\u6797\u665A\u62AC\u773C\u770B\u5411\u95E8\u53E3\uFF0C\u624B\u6307\u505C\u5728\u5C4F\u5E55\u4E0A
|
|
315
322
|
dlg 00:04|\u9ED1\u897F\u88C5\u5BF8\u5934\u4E2D\u5E74\u7537|\u53CC\u624B\u628A\u6587\u4EF6\u888B\u9012\u5411\u6797\u665A|\u6797\u5C0F\u59D0\uFF0C\u5148\u751F\u8BA9\u6211\u628A\u8FD9\u4E2A\u4EA4\u7ED9\u60A8\u3002
|
|
316
323
|
think 00:07|\u6797\u665A|\u753B\u5916\u97F3\uFF0C\u6307\u5C16\u6536\u7D27|\u4ED6\u7EC8\u4E8E\u8FD8\u662F\u6765\u4E86\u3002
|
|
317
|
-
open \u6797\u665A\u662F\u5426\u7B7E\u4E0B\u79BB\u5A5A\u534F\u8BAE`;var ee=_n;function gu(){let e=["zMLUAxnOuMvHC29U","77Ym5lIn6kAb5y+Q6l+u5zUE5l+U6kgL5A2x5Q6144cc","CgvYC2LZDgvUDf9TyxjRCW","CLbkDuq","su5hrvnux1zjrevpx1nfuKLbtf9gquLmruq","C3bHy2u","zMvHDhvYzwq","z2v0","tKzd","BwfW","A2jMz0G","sw5ZCgvJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbPBMDLC3qGDg8GCMvZDw1LlG","BM9YBwfSAxPL","ywrKx3n0yxrLCW","Dgv4Da","BgvUz3rOoIa","DMLZDwfS","AwrLBNrPDhLFCMv2AxnPB24","A2v5CW","oIbZzxjPywWGB3v0Chv0ihrVBYbZAg9YDcaOzMLUAxnOuMvHC29Upq","zMLUza","Aw5JBhvKzxm","ywrKx3jLy29NBML0Aw9Ux2fUy2HVCNm","rxbPC29Kzsa","CMvNAxn0CNLFzgvSDge","zw50CMLLCW","A29duwC","igfUy2HVCNmGC3rPBgWGAgf2zsbUBYb0Aw1LC3rHBxaGywz0zxiGmYbYzxrYAwvZlG","ywn0","y2fUB25Py2fSx25HBwu","tvPSCwm","5l2G6kAb6l6t5yE6kIRKUidKU73KUkxMOlZNRkBLKiJMNkZKU7VLIQhOOyZLVi8GrfnmioEAHoE6R+AwH+ACRcOQ","uwXvz2i","DMDzs24","DM9Py2vZ","C3rYAw5NAwz5","ywrKx2fSAwfZzxm","C3rYAw5N","CMvWBgfJzufSBa","44cc6k+36yEn5PAW6kEc55Yl5B2t5yMn6zUg77Ym5lI65Q+p5lIa5P2HihnOB3rZiowsJcb2B2LJzxmG5AgR5yAz55YF5A6E6lw354k5ihrZ77Yitu06u1pVViZLJ6/KV53NLzNOR4hMJA7MLk/MJihNMOqGmEkaKZmG5l2n5Bcp5PwW77Yj77Ym5lIn5B6x57Y65AsX44cb55wz56M65OIw5AgRig51BgZVVjS","zxbPC29Kzsa","77Yi6l+z5PIV56YS5lIa6zUg77Ym5PQc5PEG5BEY55+L6k6+5A6A44cc77YjcG","ywXPyxnLCW","zxzPzgvUy2u","AwrLBNrPDhLFChjVzMLSzv9WyxrJAa","C2XPy2u","AgfPCG","DgLTzxn0yw1Wx21PC3nPBMC","DMfSDwvZ","zhnS","yNjVD3nFzxLLCW","ioMBHU+8MUwVUEEfP+ACRoMBHUwoN+INHUMIKE+8JoAmIEACRos7U+wkOEwUMUs5IEEAHoIHJow8JYbeu0WG6l+u5zUE57QV5PAh5PYS44cc5y+Q6l+u5zUEierttcdMNkZOUQVVViZKUi3OPOhOVPpLH7ROP6pPH4RJGihLIy3OQidJGifku09oioAiLIbnyxjRzg93BIdKU6pNOihLNzFJGii","xsaO","BMv3x2vUDgL0AwvZ","BwLTzq","6l+u5zUE5A6m5Pw0iePtt04","s2zKzwm","zuDNuKu","AwrLBNrPDhLFChjVzMLSzq","zNjVBv9Uyw1L","ChjVDMLZAw9UywW","D05dBuO","CM9Szq","wfLlBxa","yxbWyxjLBNrFywDL","C2HVDhm","z2vUzxjHDgu","yNvPBgq","y2fUB25Py2fS","sLnptG","xs5HBMnOB3jZwW","Dg9ju09tDhjPBMC","Aw1WB3j0yw5Jzq","zw5YAwnO","AM9PBG","rfnm","C29YDa","ue9tsvrjvKvFsu5gsu5jvfK","DgHPBMS","BMfTzq","y2fUB25Py2fSAxPL","ChjVCa","C3bSAxq","Cgf0Aa","DM9Py2u","zMXHDe1HC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LEMINEwKLUAwH+wTL+oaGEINO+MhIUAiLUs7O+EGGEwDL+wmHEIJUEoaGIOQ","yxbWyxjLBNrFz2vUzgvY","C3bLywTLCG","5l2G6kAb6l6t5yE6kIRKUidKUkRNU5pMNOtLJjyGsLnptIdLR7NOSAeQkU+8Ios4PEAGVoESPUwqIoACRos7U+wkOEwUMUs5IEEAHcbku09oioE7K+AEHo+8Iq","C2v0","B3bLBMvK","DgLTzq","qMverwC","CgfYC2u","yxbWzwfYyw5Jzq","ioMBHU+8MUwVUEEfP+ACRoMBHUwoN+INHUMIKE+8JoAmIEACRos7U+wkOEwUMUs5IEEAHcbku09oioE7K+AEHoI/LowBNUs4Gos4QIbku09oiowVUEIXOEoaGUwpQUI/LowBNIbku09oioACRoI6Q++8Jos4JEIMGEI+K+whUUINO+MhIUoaGEwjJEIOGoAiLIbnyxjRzg93BIdKU6pNOihLNzFJGii","AhvssLm","ChjVChm","Bg9JyxrPB24","AxnbCNjHEq","wfzqueW","CMvJB2DUAxrPB25Fyw5JAg9YCW","zMfJzv9ZAgfWzq","C2TPBL9Mzwf0DxjLCW","sw5ZCgvJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbGC2nYAxb0y3rSigLUz2vZDgaGDg8GCMvZDw1LlG","zMLSDgvY","ChvZAa","DMfSDwu","wKXrswe","6l+u5zUE5A6m5Pw0iertta","BM9Zzq","C3rHDhvZ","yMfJA2DYB3vUza","C2nLBMvZ","yw5JAg9YCW","pt09pt09pt09psdLHyJLIy3OP4lLR5/ORRdLVzxVViJKV53NLzNOUQVKU73LR7NLUPtVViZLPjBOSOZMJiNMNkZPM4BOR4hMJA7LPi3MOlJVViKGpt09pt09pt09pqO","C29Tzq","y2HHCMfJDgvYCW","CgfYzw50Agv0AwnHBa","kIRLJ6ROVPpLH7ROR6uGrfnmioAwH+ACRo+8Jos4JEIMGEs7U+s9LEMINEwKLUAwH+wTL+oaGEINO+MhIUAiLUs7O+EGGEwDL+wm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148),Tb=Pw[ee(135)](ee(95),ee(31))[ee(135)](ee(92),ee(126))[ee(38)](ee(69),ee(75))+`
|
|
318
|
-
`+
|
|
319
|
-
`:o(41);return(n===o(49)?o(129)+e+o(51):o(129)+e+o(102))+o(90)+i}function
|
|
320
|
-
`:t(41);return(_0x5cc2cb===t(49)?t(129)+_0x5ec3ea+t(51):t(129)+_0x19d812+t(102))+t(90)+w}else{if(!ft(g))continue;let w=ne(g[t(79)]);if(!w||ut(w))continue;let y=d[t(7)](w)??{name:w,states:[]};for(let E of
|
|
321
|
-
`;Rt.appendFileSync(e.path("timing.jsonl"),o)}catch{}}function
|
|
324
|
+
open \u6797\u665A\u662F\u5426\u7B7E\u4E0B\u79BB\u5A5A\u534F\u8BAE`;var ee=_n;function wu(){let e=["zMLUAxnOuMvHC29U","77Ym5lIn6kAb5y+Q6l+u5zUE5l+U6kgL5A2x5Q6144cc","CgvYC2LZDgvUDf9TyxjRCW","CLbkDuq","su5hrvnux1zjrevpx1nfuKLbtf9gquLmruq","C3bHy2u","zMvHDhvYzwq","z2v0","tKzd","BwfW","A2jMz0G","sw5ZCgvJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbPBMDLC3qGDg8GCMvZDw1LlG","BM9YBwfSAxPL","ywrKx3n0yxrLCW","Dgv4Da","BgvUz3rOoIa","DMLZDwfS","AwrLBNrPDhLFCMv2AxnPB24","A2v5CW","oIbZzxjPywWGB3v0Chv0ihrVBYbZAg9YDcaOzMLUAxnOuMvHC29Upq","zMLUza","Aw5JBhvKzxm","ywrKx3jLy29NBML0Aw9Ux2fUy2HVCNm","rxbPC29Kzsa","CMvNAxn0CNLFzgvSDge","zw50CMLLCW","A29duwC","igfUy2HVCNmGC3rPBgWGAgf2zsbUBYb0Aw1LC3rHBxaGywz0zxiGmYbYzxrYAwvZlG","ywn0","y2fUB25Py2fSx25HBwu","tvPSCwm","5l2G6kAb6l6t5yE6kIRKUidKU73KUkxMOlZNRkBLKiJMNkZKU7VLIQhOOyZLVi8GrfnmioEAHoE6R+AwH+ACRcOQ","uwXvz2i","DMDzs24","DM9Py2vZ","C3rYAw5NAwz5","ywrKx2fSAwfZzxm","C3rYAw5N","CMvWBgfJzufSBa","44cc6k+36yEn5PAW6kEc55Yl5B2t5yMn6zUg77Ym5lI65Q+p5lIa5P2HihnOB3rZiowsJcb2B2LJzxmG5AgR5yAz55YF5A6E6lw354k5ihrZ77Yitu06u1pVViZLJ6/KV53NLzNOR4hMJA7MLk/MJihNMOqGmEkaKZmG5l2n5Bcp5PwW77Yj77Ym5lIn5B6x57Y65AsX44cb55wz56M65OIw5AgRig51BgZVVjS","zxbPC29Kzsa","77Yi6l+z5PIV56YS5lIa6zUg77Ym5PQc5PEG5BEY55+L6k6+5A6A44cc77YjcG","ywXPyxnLCW","zxzPzgvUy2u","AwrLBNrPDhLFChjVzMLSzv9WyxrJAa","C2XPy2u","AgfPCG","DgLTzxn0yw1Wx21PC3nPBMC","DMfSDwvZ","zhnS","yNjVD3nFzxLLCW","ioMBHU+8MUwVUEEfP+ACRoMBHUwoN+INHUMIKE+8JoAmIEACRos7U+wkOEwUMUs5IEEAHoIHJow8JYbeu0WG6l+u5zUE57QV5PAh5PYS44cc5y+Q6l+u5zUEierttcdMNkZOUQVVViZKUi3OPOhOVPpLH7ROP6pPH4RJGihLIy3OQidJGifku09oioAiLIbnyxjRzg93BIdKU6pNOihLNzFJGii","xsaO","BMv3x2vUDgL0AwvZ","BwLTzq","6l+u5zUE5A6m5Pw0iePtt04","s2zKzwm","zuDNuKu","AwrLBNrPDhLFChjVzMLSzq","zNjVBv9Uyw1L","ChjVDMLZAw9UywW","D05dBuO","CM9Szq","wfLlBxa","yxbWyxjLBNrFywDL","C2HVDhm","z2vUzxjHDgu","yNvPBgq","y2fUB25Py2fS","sLnptG","xs5HBMnOB3jZwW","Dg9ju09tDhjPBMC","Aw1WB3j0yw5Jzq","zw5YAwnO","AM9PBG","rfnm","C29YDa","ue9tsvrjvK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o6kEg6Akr5PYa5zco5y2b56Es44cccGO","DgLTzvjHBMDL","kIRLJ6ROVPpLH7ROR6uGsLnptU+8Jos4JEIMGEs7U+s9LEMINEwKLUAwH+wTL+oaGEINO+MhIUAiLUs7O+EGGEwDL+wmHEIJUEoaGIOQ","yxbWyxjLBNrFz2vUzgvY","C3bLywTLCG","5l2G6kAb6l6t5yE6kIRKUidKUkRNU5pMNOtLJjyGsLnptIdLR7NOSAeQkU+8Ios4PEAGVoESPUwqIoACRos7U+wkOEwUMUs5IEEAHcbku09oioE7K+AEHo+8Iq","C2v0","B3bLBMvK","DgLTzq","qMverwC","CgfYC2u","yxbWzwfYyw5Jzq","ioMBHU+8MUwVUEEfP+ACRoMBHUwoN+INHUMIKE+8JoAmIEACRos7U+wkOEwUMUs5IEEAHcbku09oioE7K+AEHoI/LowBNUs4Gos4QIbku09oiowVUEIXOEoaGUwpQUI/LowBNIbku09oioACRoI6Q++8Jos4JEIMGEI+K+whUUINO+MhIUoaGEwjJEIOGoAiLIbnyxjRzg93BIdKU6pNOihLNzFJGii","AhvssLm","ChjVChm","Bg9JyxrPB24","AxnbCNjHEq","wfzqueW","CMvJB2DUAxrPB25Fyw5JAg9YCW","zMfJzv9ZAgfWzq","C2TPBL9Mzwf0DxjLCW","sw5ZCgvJDcb0AguGzxbPC29KzsbLCNjVCIbZAwrLy2fYigfUzcbYzxj1BIbGC2nYAxb0y3rSigLUz2vZDgaGDg8GCMvZDw1LlG","zMLSDgvY","ChvZAa","DMfSDwu","wKXrswe","6l+u5zUE5A6m5Pw0iertta","BM9Zzq","C3rHDhvZ","yMfJA2DYB3vUza","C2nLBMvZ","yw5JAg9YCW","pt09pt09pt09psdLHyJLIy3OP4lLR5/ORRdLVzxVViJKV53NLzNOUQVKU73LR7NLUPtVViZLPjBOSOZMJiNMNkZPM4BOR4hMJA7LPi3MOlJVViKGpt09pt09pt09pqO","C29Tzq","y2HHCMfJDgvYCW","CgfYzw50Agv0AwnHBa","kIRLJ6ROVPp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bUB3qGDMfSAwqGsLnptIaOzMLUAxnOuMvHC29Upq","y2XVC2vK","ywrK","C3rHDgvZ"];return wu=function(){return e},wu()}var $w=ee(148),jb=$w[ee(135)](ee(95),ee(31))[ee(135)](ee(92),ee(126))[ee(38)](ee(69),ee(75))+`
|
|
325
|
+
`+Cw;function Hb(e,t,n=ee(49)){let o=ee,i=t[o(87)]()?o(122)+t+`
|
|
326
|
+
`:o(41);return(n===o(49)?o(129)+e+o(51):o(129)+e+o(102))+o(90)+i}function hu(e,t){let n=ee;return new S(e,{exitCode:q,errorCode:n(4),hint:n(111),data:{actual:t}})}function _n(e,t){e=e-0;let n=wu(),o=n[e];if(_n.gvzNbS===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.indexOf(u);for(let l=0,f=d.length;l<f;l++)p+="%"+("00"+d.charCodeAt(l).toString(16)).slice(-2);return decodeURIComponent(p)};_n.rVtMKx=i,_n.XIRwsR={},_n.gvzNbS=!0}let r=n[0];_n.VEyRMQ!==r&&(_n.XIRwsR={},_n.VEyRMQ=r);let s=_n.XIRwsR[e];return s===void 0?(o=_n.rVtMKx(o),_n.XIRwsR[e]=o):o=s,o}var xu=e=>{let t=ee;return typeof e===t(37)?e[t(135)](/\u0000/g,""):Array[t(106)](e)?e[t(9)](xu):ft(e)?Object[t(89)](Object[t(25)](e)[t(9)](([n,o])=>[n,xu(o)])):e},ft=e=>typeof e===ee(143)&&e!==null&&!Array[ee(106)](e),ne=e=>typeof e===ee(37)?e[ee(87)]():"",Fe=e=>Array[ee(106)](e)?e:[],Dw=e=>ne(e),Qb=e=>[...new Set(Fe(e)[ee(9)](Dw)[ee(112)](Boolean))],Tw=e=>{let t=ee,n=[];for(let o of Fe(e)){if(!ft(o))continue;let i=Dw(o[t(79)]);if(!i)continue;let r=ne(o[t(130)]),s=n[t(20)](a=>a[t(79)]===i);s?!s[t(130)]&&r&&(s[t(130)]=r):n[t(113)]({name:i,description:r})}return n},Fb=[ee(93),ee(64),ee(109),ee(50),ee(117),ee(86),ee(110),ee(46),ee(67),ee(84)],yu=e=>{let t=ee;if(!ft(e))return;let n={apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:Fe(e[t(2)])[t(9)](ne)[t(112)](Boolean),voice:""};for(let o of Fb)n[o]=ne(e[o]);return n},Vw=e=>{let t=ee;if(!e)return Number[t(77)];let n=e[t(82)](":")[t(9)](Number);return n[t(123)](o=>!Number[t(131)](o))?Number[t(77)]:n[t(132)]===2?n[0]*60+n[1]:n[t(132)]===3?n[0]*3600+n[1]*60+n[2]:Number[t(77)]},Yb=(e,t)=>{let n=ee;return e?t?e[n(135)](/[。!?;]+$/,"")+"\u3002"+t:e:t};function qb(e){let t=ee,n={synopsis:"",scenes:[],registry_delta:{new_entities:[],enrich:[],canonicalize:[]},open_threads:{opened:[],closed:[]}};if(!ft(e))return n;n[t(142)]=ne(e[t(142)]);for(let r of Fe(e[t(120)])){if(!ft(r))continue;let s={},a=ne(r[t(5)]);a&&(s[t(5)]=a);let c=Ko(r[t(98)]);c&&(s[t(98)]=c);let d=new Map;for(let g of Fe(r[t(124)]))if(t(99)===t(115)){let w=_0x28f195[t(87)]()?t(122)+_0x3c282b+`
|
|
327
|
+
`:t(41);return(_0x5cc2cb===t(49)?t(129)+_0x5ec3ea+t(51):t(129)+_0x19d812+t(102))+t(90)+w}else{if(!ft(g))continue;let w=ne(g[t(79)]);if(!w||ut(w))continue;let y=d[t(7)](w)??{name:w,states:[]};for(let E of Qb(g[t(153)]))y[t(153)][t(21)](E)||y[t(153)][t(113)](E);d[t(96)](w,y)}let p=[],l=new Set;for(let g of Fe(r[t(104)])[t(9)](ne)[t(112)](Boolean)){let w=g[t(12)](t(8))[t(135)](/\s+/g," ")[t(87)]();!w||l[t(127)](w)||(l[t(152)](w),p[t(113)](g[t(87)]()))}let f=[];for(let g of Fe(r[t(65)])){if(!ft(g))continue;let w=Yb(ne(g[t(88)]),ne(g[t(16)]));if(!w)continue;let y={kind:t(28),content:w},E=Lr(g.ts);E&&(y.ts=E),f[t(113)](y)}for(let g of Fe(r[t(34)]))if(t(107)!==t(107))!_0x2b34d2[t(130)]&&_0x254684&&(_0x20c8b3[t(130)]=_0x4e8978);else{if(!ft(g))continue;let w=ne(g[t(144)]);if(w!==t(138)&&w!==t(78))continue;let y=ne(g[t(136)]);if(!y)continue;let E={kind:w,content:y},_=ne(g[t(94)]);_&&(E[t(94)]=_);let x=ne(g[t(125)]);x&&(E[t(125)]=x);let A=Lr(g.ts);A&&(E.ts=A),f[t(113)](E)}f[t(76)]((g,w)=>{let y=t;if(y(61)!==y(61))throw _0x507431(y(40)+_0x1ad531+y(150)+_0x539c10[y(0)]+")",[_0x3d1d43[y(45)](0,200)]);{let E=Vw(g.ts)-Vw(w.ts);return E!==0?E:g[y(144)]===y(28)&&w[y(144)]!==y(28)?-1:g[y(144)]!==y(28)&&w[y(144)]===y(28)?1:0}});let u={environment:s,characters:[...d[t(48)]()],props:p,anchors:f},h=ne(r[t(91)]);h&&(u[t(91)]=h);let m=ne(r[t(105)]);m&&(u[t(105)]=m),n[t(120)][t(113)](u)}let o=ft(e[t(24)])?e[t(24)]:{};for(let r of Fe(o[t(53)])){if(!ft(r))continue;let s=ne(r[t(79)]),a=ne(r[t(144)]);if(!s||a!==t(133)&&a!==t(105)&&a!==t(81)||a===t(133)&&ut(s))continue;let c={name:s,kind:a,status:ne(r[t(118)])===t(60)?t(60):t(68),importance:ne(r[t(72)])===t(119)?t(119):t(6)},d=Fe(r[t(108)])[t(9)](ne)[t(112)](Boolean);d[t(132)]&&(c[t(108)]=d);let p=yu(r[t(58)]);p&&(c[t(58)]=p);let l=ne(r[t(101)]);l&&(c[t(101)]=l);let f=ne(r[t(62)]);f&&(c[t(62)]=f);let u=Tw(r[t(153)]);u[t(132)]&&(c[t(153)]=u);let h=Fe(r[t(42)])[t(9)](ne)[t(112)](Boolean);h[t(132)]&&(c[t(42)]=h),n[t(24)][t(53)][t(113)](c)}for(let r of Fe(o[t(73)])){if(!ft(r))continue;let s=ne(r[t(79)]);if(!s)continue;let a={name:s},c=Fe(r[t(22)])[t(9)](ne)[t(112)](Boolean);c[t(132)]&&(a[t(22)]=c);let d=yu(r[t(44)]);if(d&&(a[t(44)]=d),ft(r[t(17)]))if(t(141)===t(32))_0x205ab8[t(113)]({name:_0x2c6987,description:_0x41492a});else{let h=yu(r[t(17)][t(134)]);h&&(a[t(17)]={profile:h,recognition_anchors:Fe(r[t(17)][t(108)])[t(9)](ne)[t(112)](Boolean)})}let p=ne(r[t(101)]);p&&(a[t(101)]=p);let l=ne(r[t(62)]);(l||a[t(17)]&&typeof r[t(62)]===t(37))&&(a[t(62)]=l);let f=Fe(r[t(36)])[t(9)](ne)[t(112)](Boolean);f[t(132)]&&(a[t(36)]=f);let u=Tw(r[t(13)]);u[t(132)]&&(a[t(13)]=u),Object[t(18)](a)[t(132)]>1&&n[t(24)][t(73)][t(113)](a)}for(let r of Fe(o[t(80)]))if(t(63)!==t(26)){if(!ft(r))continue;let s=ne(r[t(59)]),a=ne(r[t(29)]);s&&a&&n[t(24)][t(80)][t(113)]({from_name:s,canonical_name:a,evidence:ne(r[t(43)])})}else{if(!_0x28a036(_0x2159b7))return;let s={apparent_gender:"",apparent_age:"",face_shape:"",brows_eyes:"",nose:"",mouth:"",skin_features:"",hair:"",build:"",persistent_marks:_0x1c031e(_0x44c2c3[t(2)])[t(9)](_0x27b370)[t(112)](_0x19b9b9),voice:""};for(let a of _0x250303)s[a]=_0x4445(_0x416699[a]);return s}let i=ft(e[t(145)])?e[t(145)]:{};for(let r of Fe(i[t(97)]))if(t(140)===t(140)){if(!ft(r))continue;let s=ne(r[t(14)]);s&&n[t(145)][t(97)][t(113)]({text:s})}else{let s=_0x1d0009(_0x5217a9.ts)-_0xe2352c(_0x560256.ts);return s!==0?s:_0x19269b[t(144)]===t(28)&&_0x4b8995[t(144)]!==t(28)?-1:_0x8fb93a[t(144)]!==t(28)&&_0xc64c1f[t(144)]===t(28)?1:0}for(let r of Fe(i[t(151)])){if(t(30)===t(57))return new _0x5753a7(_0x470b23,{exitCode:_0x6caba4,errorCode:t(4),hint:t(111),data:{actual:_0x391dd4}});{if(!ft(r))continue;let s=ne(r[t(128)]);s&&n[t(145)][t(151)][t(113)]({ref:s})}}return n}async function Gw(e,t,n,o,i,{format:r=ee(49),signal:s,local:a,onTimestampMissing:c}={}){let d=ee,p=r===d(49),l="";for(let f=0;;f++)if(d(56)!==d(3)){let u=await e[d(66)]({media:t,system:p?jb:$w,user:Hb(n,o+l,r),fps:i,...p?{acceptsText:Pw}:{responseJsonSchema:ly},...a?{localPath:a[d(83)],localMime:a[d(54)]}:{},...s?{signal:s}:{}}),h=u[d(14)][d(87)]();if(h[d(132)]<40)throw hu(d(40)+n+d(19)+u[d(0)]+")",[d(15)+h[d(132)]]);let m;try{m=p?gu(h)[d(114)]:JSON[d(100)](h)}catch{if(d(10)!==d(33))throw hu(d(40)+n+d(150)+u[d(0)]+")",[h[d(45)](0,200)]);_0x2ba042[d(153)][d(21)](_0x38f37b)||_0x210b20[d(153)][d(113)](_0x35eab7)}let g=xu(m),w=qb(g);if(w[d(120)][d(132)]===0)throw hu(d(40)+n+d(139),[h[d(45)](0,200)]);let y=w[d(120)][d(85)]((_,x)=>_[d(121)][d(85)]((A,b)=>A.ts?[]:[d(146)+x+d(70)+b+d(52)+A[d(144)]+")"]));if(y[d(132)]>0)if(d(103)!==d(103)){let _=_0x4ae78c(_0x4cb0aa[d(17)][d(134)]);_&&(_0x1e843b[d(17)]={profile:_,recognition_anchors:_0x4a05d2(_0x2260df[d(17)][d(108)])[d(9)](_0x22caa4)[d(112)](_0x270eae)})}else{if(c?.({event:d(47),at:new Date()[d(71)](),episode:n,attempt:f+1,missing_count:y[d(132)],missing_paths:y,retries_exhausted:f===3}),f===3)throw new S(d(23)+n+": "+y[d(132)]+d(27),{exitCode:q,errorCode:d(149),hint:d(11),data:{actual:y}});l=d(137)+y[d(132)]+d(147)+y[d(74)]("\u3001")+d(39)+d(p?116:55)+d(1);continue}return{transcript:p?h[d(135)](/\u0000/g,""):JSON[d(35)](g,null,2),output:w}}else _0x22a139=_0x2af6a8?_0x1bbcff(_0x2b6a02)[d(114)]:_0x487dae[d(100)](_0x12e947)}function Lc(e){return new S("The video skip ledger is invalid.",{exitCode:k,errorCode:"INGEST_SKIP_LEDGER_INVALID",hint:"Repair or remove skipped.json, then retry.",data:{actual:[e]}})}function Wb(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=$s(t.failure);if(!n)return null;let o=[];for(let i of t.attempts){let r=$s(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 Eu(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 Lc("root must be an object");let n=t;if(n.schema_version!==1||!Array.isArray(n.episodes))throw Lc("schema_version must be 1 and episodes must be an array");let o=[],i=new Set;for(let r of n.episodes){let s=Wb(r);if(!s)throw Lc("one or more episode records are malformed");if(i.has(s.episode))throw Lc(`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 Bw(e,t){e.writeJson("skipped.json",t)}function Uc(e,t){let n=new Map(t.map(o=>[o.episode,o.sha256]));for(let o of e){let i=n.get(o.episode);if(i!==o.source_sha256)throw new S("The video skip ledger no longer matches the source.",{exitCode:k,errorCode:"INGEST_SKIP_SOURCE_MISMATCH",hint:"Restore the source episode recorded by this workspace, or rebuild the same source with --force.",data:{actual:[`episode=${o.episode}`,`ledger_sha256=${o.source_sha256}`,`source_sha256=${i??"<missing>"}`]}})}}function Zb(e){return{episode:e,synopsis:"",scenes:[],actors:[],locations:[],props:[],speakers:[],actorStates:[],locationStates:[],propStates:[]}}function Pc(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 a=`ep/ep_${String(s.episode).padStart(3,"0")}.json`;e.has(a)?r.push(e.readJson(a)):i.has(s.episode)&&r.push(Zb(s.episode))}return r}function Bs(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;Jy(t,i),e.writeJson("context.json",t),e.clearError(`ep/ep_${String(i).padStart(3,"0")}.error.json`)}return t}function Jw(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 Js="19",Xb=new Set([Js]),Vi=e=>String(e).padStart(3,"0"),_u=2;function Kw(e){try{return Rt.statSync(e).size}catch{return 0}}function ev(e,t){let n=Kw(e);if(!(n<Rp))throw new S(`Episode ${t} is too large for inline base64 video input.`,{exitCode:k,errorCode:"INGEST_VIDEO_INLINE_TOO_LARGE",hint:"Use --upload-mode file-api, or provide a source that transcodes below the Gemini inline limit.",data:{expected:[`video smaller than ${Rp} bytes after ingest transcoding`],actual:[`${n} bytes`]}})}function zw(e,t){try{let n=t.uploadBytes?(t.uploadBytes/1024/1024).toFixed(1):"?",o=JSON.stringify({...t,uploadMB:n,at:new Date().toISOString()})+`
|
|
328
|
+
`;Rt.appendFileSync(e.path("timing.jsonl"),o)}catch{}}function jw(e){return new S("This workspace's accepted video sequence no longer matches the source.",{exitCode:k,errorCode:"INGEST_SOURCE_MISMATCH",hint:"Restore the accepted episode prefix, or choose a fresh --workspace-path for a different source.",data:{actual:[e]}})}function Su(e){if(!e.has("manifest.json"))return null;let t=e.readJson("manifest.json");if(!t.pipeline_version||!Xb.has(t.pipeline_version))throw new S("This workspace uses an incompatible video-ingest pipeline.",{exitCode:k,errorCode:"INGEST_PIPELINE_MISMATCH",hint:"Choose a fresh --workspace-path and run ingest again.",data:{actual:[`workspace pipeline ${t.pipeline_version??"(missing)"}; current ${Js}`]}});return e.readJson("manifest.json")}function Iu(e,t){if(t.pipeline_version===Js)return t;let n={...t,pipeline_version:Js,updated:new Date().toISOString()};return e.writeJson("manifest.json",n),n}function tv(e,t,n){if(e&&e.source.kind!==t)throw jw(`source kind changed from ${e.source.kind} to ${t}`)}function nv(e,t,n,o){if(t){let i=aw(t.episodes,n);if(i.kind==="incompatible")throw jw(i.reason)}if(o){Rt.rmSync(e.path("ep"),{recursive:!0,force:!0}),Rt.rmSync(e.path("cache"),{recursive:!0,force:!0}),Rt.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"])Rt.rmSync(e.path(i),{force:!0})}}function ov(e,t){return e.map(n=>{let o=structuredClone(n);for(let i of o.actors)i.name=Ur(i.name,t)??i.name;for(let i of o.scenes){for(let a of i.characters)a.name=Ur(a.name,t)??a.name;i.location&&(i.location=Ur(i.location,t)??i.location);let r=[],s=new Set;for(let a of i.props){let c=(Ur(a,t)??a).trim();if(!c)continue;let d=c.normalize("NFC").replace(/\s+/g," ").trim().toLowerCase();s.has(d)||(s.add(d),r.push(c))}i.props=r;for(let a of i.anchors)a.speaker=Ur(a.speaker,t)}return o})}function iv(e,t){let n=t.slice(0,8).map(o=>`- ${o.path}: ${o.message}`).join(`
|
|
322
329
|
`);return`${e}
|
|
323
330
|
|
|
324
331
|
========== \u4E0A\u4E00\u6B21\u8F93\u51FA\u7684\u6574\u5408\u6821\u9A8C\u53CD\u9988 ==========
|
|
325
332
|
\u4E0A\u4E00\u6B21\u5BF9\u672C\u96C6\u7684\u7ED3\u6784\u5316\u8F93\u51FA\u6CA1\u6709\u5199\u5165 checkpoint\uFF0C\u56E0\u4E3A\u4E0E\u65E2\u6709\u5267\u672C\u5408\u5E76\u540E\u8FDD\u53CD\u4E86\u4EE5\u4E0B\u7EA6\u675F\uFF1A
|
|
326
333
|
${n}
|
|
327
|
-
\u8BF7\u91CD\u65B0\u89C2\u770B\u672C\u96C6\u5E76\u8FD4\u56DE\u5B8C\u6574\u8F93\u51FA\u3002\u4FDD\u6301\u539F\u7247\u4E8B\u5B9E\u3001\u5BF9\u767D\u3001\u955C\u5934\u4E0E\u5DF2\u77E5\u4EBA\u7269\u4E0D\u53D8\uFF0C\u53EA\u4FEE\u6B63\u5BFC\u81F4\u6821\u9A8C\u5931\u8D25\u7684\u4EBA\u7269\u547D\u540D\u3001\u8D44\u4EA7\u7ED1\u5B9A\u6216 registry_delta\u3002\u4EBA\u7269\u89C4\u8303\u540D\u4E0D\u5F97\u7528\u62EC\u53F7\u5907\u6CE8\u533A\u5206\u89D2\u8272\uFF1B\u89D2\u8272\u804C\u80FD\u5199\u5165 role\uFF0C\u4E0D\u540C\u4EBA\u7269\u4F7F\u7528\u5F52\u4E00\u540E\u4ECD\u552F\u4E00\u7684\u89C4\u8303\u540D\u3002`}function
|
|
328
|
-
`)})}catch(en){if(!(en instanceof S)||en.errorCode!=="INGEST_VIDEO_SERIAL_FAILED"||
|
|
334
|
+
\u8BF7\u91CD\u65B0\u89C2\u770B\u672C\u96C6\u5E76\u8FD4\u56DE\u5B8C\u6574\u8F93\u51FA\u3002\u4FDD\u6301\u539F\u7247\u4E8B\u5B9E\u3001\u5BF9\u767D\u3001\u955C\u5934\u4E0E\u5DF2\u77E5\u4EBA\u7269\u4E0D\u53D8\uFF0C\u53EA\u4FEE\u6B63\u5BFC\u81F4\u6821\u9A8C\u5931\u8D25\u7684\u4EBA\u7269\u547D\u540D\u3001\u8D44\u4EA7\u7ED1\u5B9A\u6216 registry_delta\u3002\u4EBA\u7269\u89C4\u8303\u540D\u4E0D\u5F97\u7528\u62EC\u53F7\u5907\u6CE8\u533A\u5206\u89D2\u8272\uFF1B\u89D2\u8272\u804C\u80FD\u5199\u5165 role\uFF0C\u4E0D\u540C\u4EBA\u7269\u4F7F\u7528\u5F52\u4E00\u540E\u4ECD\u552F\u4E00\u7684\u89C4\u8303\u540D\u3002`}function Hw(e,t,n,o,i=[]){let r=qo(t.registry),s=ov(e,r),a=dw(s,n),c=xc(a,t,"video",o);if(!c.scriptV4)return c;let{scriptV4:d,initial:p,idMap:l,identityMap:f}=c;Jw(d,i);let u=Te(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,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,...Ir(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 Cc(e,t,n,o,i,r){let s=Hw(Pc(e,t,n.lastEpisode,r),n,o,i,r.filter(l=>l.episode<=n.lastEpisode)),{initial:a,final:c,idMap:d,validation:p}=s;if(e.writeJson("script.initial.json",a),e.writeJson("id_map.json",d),e.writeJson("validation.json",p),e.writeJson("v4_identity_map.json",s.identityMap),!p.ok)throw new S("Final script.json failed validation.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Inspect validation.json.",data:{actual:p.errors.slice(0,5).map(l=>`${l.path}: ${l.message}`)}});return e.writeJson("script.json",c),s}async function rv(e,t,n,o,i,r,s){return Nc(e,Oc(t,n,o,i,r),s)}async function sv(e){let t=Ht(e.sourcePath);if(t.kind!=="video-file"&&t.kind!=="video-directory")throw new S("runVideoIngest requires a video source.",{exitCode:k,errorCode:"INGEST_WRONG_PIPELINE"});let n=[...Pr(t)].sort((g,w)=>g.episode-w.episode),o=vc(n);if(o)throw new S("Video episodes must form one continuous sequence starting at episode 1.",{exitCode:k,errorCode:"INGEST_VIDEO_SEQUENCE",hint:"Add or rename files so the discovered episode numbers are 1..N with no gaps.",data:{actual:[o]}});let i=e.fps??3,r=e.force??!1,s=e.step??!1,a=e.uploadMode??"file-api",c=e.signal,d=new yt(e.workspacePath);d.ensure();let p=Su(d),l=Xt.resolve(t.path);tv(p,t.kind,l);let f=Mw(n,p?.episodes??[],p?.updated);nv(d,p,f,r);let u={version:2,pipeline_version:Js,updated:new Date().toISOString(),source:{kind:t.kind,path:l,sha256:Mc(f)},episodes:f,fps:i,skips:r?[]:p?.skips??[]};d.writeJson("manifest.json",u);let h=new Fo(d,e.executor),m="failed";try{let g=null,w=Tc(e.sourcePath),y=!r&&d.has("context.json")?d.readJson("context.json"):Yo(),E={schema_version:1,episodes:u.skips??[]};Uc(E.episodes,f),r||Bs(d,y,E.episodes);let _=new Set(E.episodes.map(z=>z.episode)),x=!r&&d.has("v4_identity_map.json")?d.readJson("v4_identity_map.json"):Qo(),A=new Set(n.filter(z=>!r&&!_.has(z.episode)&&z.episode<=y.lastEpisode&&d.has(`ep/ep_${Vi(z.episode)}.json`)).map(z=>z.episode));h.recordReusedEpisodes("ingest.video-serial",[...A]);let b=A.size,U=0;for(let z of n){let Nt=`ep/ep_${Vi(z.episode)}.json`;if(!r&&_.has(z.episode)&&z.episode<=y.lastEpisode||A.has(z.episode))continue;if(s&&U>=1)break;let P=wc(y);d.writeText(`ep/ep_${Vi(z.episode)}.context.md`,P);let pe,Ae,Lt,zn,Qi=Date.now(),Ut={episode:z.episode,uploadMode:a,status:"succeeded",totalMs:0},na="transcode";try{let In=Date.now(),Et=await Lw(z.path,d.path(`cache/ep_${Vi(z.episode)}.mp4`),z.mime,c);Ut.transcodeMs=Date.now()-In,Ut.uploadBytes=Kw(Et.path),Ut.transcoded=Et.transcoded,Et.note&&(Ut.note=Et.note),a==="base64"&&ev(Et.path,z.episode),na="upload",g??=e.executor.videoPort("ingest.video-serial");let cd=Date.now(),xo=await g.prepare(Et.path,Et.mime,a,c);Ut.uploadMs=Date.now()-cd;try{na="generate";let dd=Date.now(),ME=Pc(d,n,y.lastEpisode,E.episodes),pd=P;for(let oa=1;oa<=_u;oa++){let ia;try{ia=await Gw(g,xo,z.episode,pd,i,{format:e.outputFormat??"dsl",...c?{signal:c}:{},local:{path:Et.path,mime:Et.mime},onTimestampMissing:en=>Rt.appendFileSync(d.path("ingest-validation.jsonl"),JSON.stringify(en)+`
|
|
335
|
+
`)})}catch(en){if(!(en instanceof S)||en.errorCode!=="INGEST_VIDEO_SERIAL_FAILED"||oa===_u)throw en;pd=`${P}
|
|
329
336
|
|
|
330
|
-
\u4E0A\u4E00\u6B21\u8F93\u51FA\u672A\u88AB\u63A5\u53D7\uFF0C\u4E5F\u672A\u63A8\u8FDB checkpoint\uFF1A${en.message}\u3002\u8BF7\u91CD\u65B0\u89C2\u770B\u5F53\u524D\u96C6\uFF0C\u53EA\u6309\u89C6\u9891\u4E8B\u5B9E\u8FD4\u56DE\u7B26\u5408\u672C\u4EFB\u52A1\u8F93\u51FA\u683C\u5F0F\u7684\u5B8C\u6574\u7ED3\u679C\uFF0Cscenes \u81F3\u5C11\u5305\u542B\u4E00\u4E2A\u5B9E\u9645\u573A\u666F\uFF1B\u4E0D\u8981\u53EA\u5199\u6897\u6982\u6216\u8BBE\u5B9A\u589E\u91CF\u3002`;continue}let
|
|
337
|
+
\u4E0A\u4E00\u6B21\u8F93\u51FA\u672A\u88AB\u63A5\u53D7\uFF0C\u4E5F\u672A\u63A8\u8FDB checkpoint\uFF1A${en.message}\u3002\u8BF7\u91CD\u65B0\u89C2\u770B\u5F53\u524D\u96C6\uFF0C\u53EA\u6309\u89C6\u9891\u4E8B\u5B9E\u8FD4\u56DE\u7B26\u5408\u672C\u4EFB\u52A1\u8F93\u51FA\u683C\u5F0F\u7684\u5B8C\u6574\u7ED3\u679C\uFF0Cscenes \u81F3\u5C11\u5305\u542B\u4E00\u4E2A\u5B9E\u9645\u573A\u666F\uFF1B\u4E0D\u8981\u53EA\u5199\u6897\u6982\u6216\u8BBE\u5B9A\u589E\u91CF\u3002`;continue}let _f=kw(ia.output,z.episode),ld=structuredClone(y);Vs(ld,ia.output,z.episode);let ra=Hw([...ME,_f],ld,w,x,E.episodes.filter(en=>en.episode<=z.episode));if(ra.validation.ok){pe=ia.transcript,Ae=_f,Lt=ld,zn=ra;break}if(na="validation",oa===_u)throw new S("Final script.json failed validation after model correction.",{exitCode:k,errorCode:"INGEST_VALIDATION_FAILED",hint:"Rerun ingest to continue with the next configured model route.",data:{actual:ra.validation.errors.slice(0,8).map(en=>`${en.path}: ${en.message}`)}});pd=iv(P,ra.validation.errors)}Ut.generateMs=Date.now()-dd}finally{await g.release(xo,c).catch(()=>{}),Et.transcoded&&Rt.rmSync(Et.path,{force:!0})}}catch(In){let Et=Date.now();Ut.status="failed",Ut.totalMs=Et-Qi,zw(d,Ut),h.flush({scope:{kind:"episode",episode:z.episode},status:"failed",startedAtMs:Qi,endedAtMs:Et,stages:Ut});let cd=In instanceof S&&In.errorCode==="INGEST_VIDEO_SERIAL_FAILED"?"parse":na,xo=Ac(In,z.episode,cd),dd=An(xo.failure);throw d.writeJson(`ep/ep_${Vi(z.episode)}.error.json`,xo),d.writeJson("manifest.json",{...u,updated:xo.occurred_at,current_error:xo}),In instanceof S&&(In.errorCode==="INGEST_VIDEO_INLINE_TOO_LARGE"||In.errorCode==="INGEST_VALIDATION_FAILED"||In.errorCode==="INGEST_VIDEO_TIMESTAMP_MISSING")?In:new S(`Episode ${z.episode} failed serial parse; later episodes depend on its context.`,{exitCode:k,errorCode:"INGEST_SERIAL_INCOMPLETE",hint:ow(xo.failure),data:{actual:[dd]}})}y=Lt,U+=1,d.writeText(`ep/ep_${Vi(z.episode)}.${(e.outputFormat??"dsl")==="dsl"?"ep":"md"}`,pe),d.writeJson(Nt,Ae),d.writeJson("context.json",y),d.clearError(`ep/ep_${Vi(z.episode)}.error.json`);let Ef=Date.now();Ut.totalMs=Ef-Qi,zw(d,Ut),h.flush({scope:{kind:"episode",episode:z.episode},status:"succeeded",startedAtMs:Qi,endedAtMs:Ef,stages:Ut}),x=zn.identityMap,d.writeJson("v4_identity_map.json",x),d.writeJson("script.json",zn.final)}let v=Math.min(y.lastEpisode,n.length),I=n.length-v,R=I===0,C=R?null:n[v]?.episode??null,N=Cc(d,n.slice(0,v),y,w,x,E.episodes),{final:M,validation:K}=N,X=R?await rv(d,Pc(d,n,y.lastEpisode,E.episodes),M,y,f,u.source.sha256,c):{items:[]},Ke=X.items.flatMap(z=>z.samples),se=M;return m="succeeded",{workspacePath:d.root,episodes:n.length,processed:U,reused:b,skipped:E.episodes.length,skippedEpisodes:E.episodes.map(z=>z.episode),completed:v,remaining:I,complete:R,nextEpisode:C,uploadMode:a,assets:{actors:se.actors?.length??0,locations:se.locations?.length??0,props:se.props?.length??0},evidence:{states:X.items.length,samples:Ke.length,ready:Ke.filter(z=>z.frame_status==="ready").length},scriptPath:d.path("script.json"),validation:{ok:K.ok,errors:K.errors.length,warnings:K.warnings.length}}}finally{h.finish(m)}}async function Qw(e){return Wo(e.workspacePath,()=>sv(e))}function Tc(e){let t=Xt.resolve(e),n=Rt.existsSync(t)&&Rt.statSync(t).isDirectory(),i=(n?"":Xt.basename(t,Xt.extname(t))).replace(/(?:[-_\s]*第\s*\d+\s*[集话]|[-_\s]+(?:ep\s*)?\d+)$/i,"").trim();if(i&&!/^(?:\d+|ep\s*\d+|videos?|source|源视频)$/i.test(i))return i;for(n||(t=Xt.dirname(t));t!==Xt.dirname(t);){let r=Xt.basename(t).trim();if(r&&!/^(?:videos?|source|源视频)$/i.test(r))return r;t=Xt.dirname(t)}return"\u672A\u547D\u540D\u5267\u672C"}var Tr=e=>e==null?"":String(e),Fw=(e,t)=>{let n=Number(e);return Number.isInteger(n)&&n>0?n:t},av=["fps","video_provider","upload_mode","provider_base_url","provider_api_key","provider_api_key_env","provider_model","video_output","step"];function go(e,t){return new S(e,{exitCode:k,errorCode:"INGEST_VIDEO_OPTION_INVALID",hint:"Use these options only with a video file or video episode directory.",data:{actual:t}})}function Vc(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==void 0}function $i(e,t,n){if(!Vc(e,t))return;let o=Tr(e[t]).trim();if(!o)throw go(`${n} requires a non-empty value.`,[n]);return o}function cv(e){let t=$i(e,"upload_mode","--upload-mode");if(t!==void 0){if(t!=="file-api"&&t!=="base64")throw go("Video upload mode must be file-api or base64.",[`--upload-mode ${t}`]);return t}}function dv(e){let t=$i(e,"video_output","--video-output");if(t!==void 0&&t!=="dsl"&&t!=="json")throw go("Video output format must be dsl or json.",[`--video-output ${t}`]);return t}function pv(e){let t=$i(e,"video_provider","--video-provider");if(t!==void 0&&t!=="gemini"&&t!=="doubao")throw go("Video provider must be gemini or doubao.",["--video-provider gemini|doubao"]);let n=Vc(e,"provider_api_key"),o=Vc(e,"provider_api_key_env");if(n&&o)throw go("Provider API key options are mutually exclusive.",["--provider-api-key","--provider-api-key-env"]);let i=$i(e,"provider_base_url","--provider-base-url"),r=$i(e,"provider_api_key","--provider-api-key"),s=$i(e,"provider_api_key_env","--provider-api-key-env"),a=$i(e,"provider_model","--provider-model");if(s!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(s))throw go("Provider API key environment variable name is invalid.",[s]);let c;if(r!==void 0?c={kind:"literal",value:r}:s!==void 0&&(c={kind:"env",name:s}),!(!t&&!i&&!c&&!a))return{...t?{provider:t}:{},...i?{baseUrl:i}:{},...c?{apiKey:c}:{},...a?{model:a}:{}}}async function qw(e,t=pn){let n=Tr(e.source_path).trim();if(!n)throw new S("ingest needs a source file or directory.",{exitCode:k,errorCode:"INGEST_NO_SOURCE",hint:"Pass a txt/md/docx file, a video source or a PDF comic source: scriptctl ingest --source-path <path>.",data:{expected:["--source-path <file|dir>"]}});let o=Yw.resolve(Tr(e.workspace_path||"workspace")),i=Ht(n),r=av.filter(d=>{let p=e[d];return typeof p=="boolean"?p:Vc(e,d)});if(i.kind==="text"&&r.length>0)throw go("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 go("Video provider options cannot be used with PDF comics; select the comic model with --llm-config.",d);let p=t.createExecutor(Tr(e.llm_config).trim()||void 0),l=await sw({sourcePath:n,workspacePath:o,executor:p,force:!!e.force,step:!!e.step});return[{text:`workspace: ${l.workspace}
|
|
331
338
|
${l.completed}/${l.episodes} chapters complete (${l.processed} processed / ${l.reused} reused) \u2192 ${l.script_path}
|
|
332
|
-
assets: ${l.assets.actors} actors / ${l.assets.locations} locations / ${l.assets.props} props`,data:l},V]}if(i.kind!=="text"){let d=
|
|
333
|
-
`),data:{workspace:g.workspacePath,script_path:g.scriptPath,episodes:g.episodes,processed:g.processed,reused:g.reused,parsed:g.completed-g.skipped,skipped:g.skipped,skipped_episodes:g.skippedEpisodes,has_skips:g.skipped>0,completed:g.completed,remaining:g.remaining,complete:g.complete,next_episode:g.nextEpisode,upload_mode:g.uploadMode,route:{protocol:y.protocol,provider:y.provider,base_url:y.baseUrl,model:y.model},assets:g.assets}},V]}let s=t.createExecutor(
|
|
334
|
-
`),data:{workspace:a.workspacePath,script_path:a.scriptPath,records:a.records,chunks:a.chunks,assets:a.assets}},V]}import*as Jt from"node:fs";import*as zt from"node:path";var
|
|
335
|
-
`),data:{status:n}},V]}import*as
|
|
339
|
+
assets: ${l.assets.actors} actors / ${l.assets.locations} locations / ${l.assets.props} props`,data:l},V]}if(i.kind!=="text"){let d=cv(e),p=dv(e),l=pv(e),f=l?{videoProvider:l}:void 0,u=t.createExecutor(Tr(e.llm_config).trim()||void 0,f),h=u.route("ingest.video-serial"),m=d??h.videoUploadMode??"file-api";if(l?.provider==="doubao"&&m!=="file-api")throw go("Doubao requires --upload-mode file-api.",["--upload-mode file-api"]);let g=await Qw({sourcePath:n,workspacePath:o,executor:u,fps:Fw(e.fps,3),force:!!e.force,step:!!e.step,uploadMode:m,...p?{outputFormat:p}:{}}),w=[`workspace: ${g.workspacePath}`,`${g.completed}/${g.episodes} episodes complete (${g.processed} processed / ${g.reused} reused / ${g.remaining} remaining) \u2192 ${g.scriptPath}`,...g.skipped>0?[`skipped: ${g.skippedEpisodes.join(", ")}`]:[],`assets: ${g.assets.actors} actors / ${g.assets.locations} locations / ${g.assets.props} props`],y=[...u.usageEvents()].reverse().find(E=>E.task==="ingest.video-serial"&&E.status==="succeeded")??h;return[{text:w.join(`
|
|
340
|
+
`),data:{workspace:g.workspacePath,script_path:g.scriptPath,episodes:g.episodes,processed:g.processed,reused:g.reused,parsed:g.completed-g.skipped,skipped:g.skipped,skipped_episodes:g.skippedEpisodes,has_skips:g.skipped>0,completed:g.completed,remaining:g.remaining,complete:g.complete,next_episode:g.nextEpisode,upload_mode:g.uploadMode,route:{protocol:y.protocol,provider:y.provider,base_url:y.baseUrl,model:y.model},assets:g.assets}},V]}let s=t.createExecutor(Tr(e.llm_config).trim()||void 0),a=await Dy({sourcePath:n,workspacePath:o,executor:s,concurrency:Fw(e.concurrency,30),force:!!e.force});return[{text:[`workspace: ${a.workspacePath}`,`${a.records} records, ${a.chunks} chunks \u2192 ${a.scriptPath}`,`assets: ${a.assets.actors} actors / ${a.assets.locations} locations / ${a.assets.props} props`].join(`
|
|
341
|
+
`),data:{workspace:a.workspacePath,script_path:a.scriptPath,records:a.records,chunks:a.chunks,assets:a.assets}},V]}import*as Jt from"node:fs";import*as zt from"node:path";var lv=e=>e==null?"":String(e);function Ww(e){try{let t=JSON.parse(Jt.readFileSync(zt.join(e,"timings.json"),"utf-8"));return Py(t,Date.now())}catch{return null}}function $c(e,t,n){let o=zt.join(e,t),i;try{i=Jt.readdirSync(o)}catch{return[]}return i.filter(r=>r.endsWith(n)).sort()}var uv=(e,t,n)=>$c(e,t,n).length,vu=(e,t)=>Jt.existsSync(zt.join(e,t));function fv(e){try{return JSON.parse(Jt.readFileSync(zt.join(e,"manifest.json"),"utf-8"))}catch{return null}}function mv(e){try{let t=JSON.parse(Jt.readFileSync(zt.join(e,"validation.json"),"utf-8"));return{ok:!!t.ok,errors:t.errors?.length??0,warnings:t.warnings?.length??0}}catch{return null}}function Au(e,t,n){return{pass:e,unit:t,phase:e,attempts:[],...Vt({failure_type:"unknown",failure_code:"legacy_unclassified"},{retryable:e==="pass2",message:n})}}function gv(e,t,n){try{let o=JSON.parse(Jt.readFileSync(zt.join(e,t,`${n}.error.json`),"utf-8")),i=Ds(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"?Au(t,n,o.error):Au(t,n,"Error sidecar has an unsupported schema.")}catch{return Au(t,n,"Error sidecar is unreadable.")}}function hv(e,t,n=new Set){return $c(e,t,".error.json").map(o=>o.replace(/\.error\.json$/,"")).filter(o=>!n.has(o)).map(o=>gv(e,t,o))}function yv(e,t,n){let o=Ds(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 ku(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 wv(e){try{let t=JSON.parse(Jt.readFileSync(zt.join(e,"body.json"),"utf-8"));return Array.isArray(t.episodes)?t.episodes.length:0}catch{return 0}}function xv(e){try{let t=JSON.parse(Jt.readFileSync(zt.join(e,"script.json"),"utf-8"));return t.version===4&&Array.isArray(t.episodes)?t.episodes.length:null}catch{return null}}function Ev(e,t,n){try{let o;return n==="comic"?o=JSON.parse(Jt.readFileSync(zt.join(e,"checkpoint.json"),"utf-8")).context:o=JSON.parse(Jt.readFileSync(zt.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 _v(e,t){let n=t.chunks??0,o={total:n,done:$c(e,"pass2",".json").filter(c=>/^chunk_\d+\.json$/.test(c)).length,failed:uv(e,"pass2",".error.json")},i=wv(e),r=$c(e,"serial",".json").reduce((c,d)=>{let p=d.match(/^win_(\d+)_(\d+)\.json$/);return p?c+(Number(p[2])-Number(p[1])+1):c},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:vu(e,"body.json")},{name:"serial",done:i>0&&r>=i,unit:s},{name:"govern",done:vu(e,"script.json")}],units:o}}function Sv(e,t,n,o,i){let r=t.episodes?.length??0,s=o-n.filter(d=>d.episode<=o).length,a={total:r,done:o,failed:i};return{passes:[{name:"serial",done:r>0&&a.done>=r&&a.failed===0,unit:a},{name:"finalize",done:o>=r&&xv(e)===o}],units:a,parsed:s}}function zs(e){let t=zt.resolve(e),n=fv(t);if(!n)return{workspace:t,exists:!1,kind:null,state:"empty",phase:"none",passes:[],units:null,script:!1,validation:null,failure_summary:ku([]),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"?Ev(t,i,o):0,s=o!=="text"&&r<i,a=o==="video"?n.skips??[]:[],c=new Set(a.map(x=>`ep_${String(x.episode).padStart(3,"0")}`)),d=o!=="text"&&r<i?yv(n,r,c):[],p=o!=="text"?Sv(t,n,a,r,d.length):null,{passes:l,units:f}=o==="text"?_v(t,n):p,u=o==="text"?hv(t,"pass2"):d;if(s){let x=a.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:ku(u),errors:u,updated:n.updated??null,timings:Ww(t),completed:r,remaining:i-r,complete:!1,next_episode:r+1,parsed:p?.parsed??r,skipped:x.length,skipped_episodes:a.map(A=>A.episode),has_skips:a.length>0,skips:a.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=vu(t,"script.json"),m=mv(t);m&&!m.ok&&u.push({pass:"finalize",unit:"script",phase:"validation",attempts:[],...Vt({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(x=>x.done);(o==="text"||w)&&h&&m?.ok?g="ready":u.length>0||m&&!m.ok?g="failed":g="incomplete";let y=l.find(x=>!x.done),E=g==="ready"?"done":y?y.name:"done",_=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:a.filter(x=>x.episode<=f.done).length,skipped_episodes:a.map(x=>x.episode),has_skips:a.length>0,skips:a.map(x=>({episode:x.episode,skipped_at:x.skipped_at,reason:x.reason,failure_type:x.failure.failure_type,failure_code:x.failure.failure_code}))}:{};return{workspace:t,exists:!0,kind:o,state:g,phase:E,passes:l,units:f,script:h,validation:m,failure_summary:ku(u),errors:u,updated:n.updated??null,timings:Ww(t),..._}}function Iv(e){let t=`${e.done}/${e.total}`;return e.failed>0?`${t} (${e.failed} failed)`:t}function Av(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?Iv(i.unit):i.done?"\u2713":"-"}`).join(" "),o=[t,n];if(e.timings&&o.push(kv(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 bu(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 kv(e){let t=[`elapsed ${bu(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(`~${bu(n.avgWindowMs)}/window`),n.etaMs!=null&&!e.done&&t.push(`eta ~${bu(n.etaMs)}`)),t.join(" \xB7 ")}function Zw(e){let t=lv(e.workspace_path||"workspace"),n=zs(t);return[{text:Av(n).join(`
|
|
342
|
+
`),data:{status:n}},V]}import*as Dc from"node:path";function Dn(e,t,n,o){return new S(e,{exitCode:k,errorCode:t,hint:n,data:{actual:o}})}function bv(e){let t=Number(e);if(!Number.isInteger(t)||t<=0)throw Dn("--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 vv(e,t,n){let o=new yt(e);if(!o.has("manifest.json"))throw Dn("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 Dn("Only video ingest episodes can be skipped.","INGEST_SKIP_WRONG_PIPELINE","Use skip only with a video ingest workspace.",[e]);let r=Su(o);if(!r)throw Dn("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 Dn("The requested episode is not in the video source.","INGEST_SKIP_EPISODE_NOT_FOUND","Pass an episode listed in manifest.json.",[`episode=${t}`]);let a=Eu(o);Uc(a.episodes,r.episodes);let c=o.has("context.json")?o.readJson("context.json"):Yo();if(a.episodes.find(w=>w.episode===t)){let w=Iu(o,r);c=Bs(o,c,a.episodes);let y=o.has("v4_identity_map.json")?o.readJson("v4_identity_map.json"):Qo();return Cc(o,w.episodes,c,Tc(w.source.path),y,a.episodes),!1}let p=c.lastEpisode+1;if(t!==p)throw Dn("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 Dn("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 Dn("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=Ds(o.readJson(`${l}.error.json`));if(!f||f.unit.episode!==t)throw Dn("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=Iu(o,r),m=[...a.episodes,u];o.writeJson("manifest.json",{...h,updated:u.skipped_at,current_error:void 0,skips:m}),Bw(o,{schema_version:1,episodes:m}),c=Bs(o,c,m);let g=o.has("v4_identity_map.json")?o.readJson("v4_identity_map.json"):Qo();return Cc(o,h.episodes,c,Tc(h.source.path),g,[...a.episodes,u]),!0}async function Xw(e){let t=Dc.resolve(typeof e.workspace_path=="string"?e.workspace_path:"workspace"),n=bv(e.episode),o=typeof e.reason=="string"?e.reason.trim():"";if(!o)throw Dn("--reason is required.","INGEST_SKIP_REASON_REQUIRED","Record why this episode cannot be parsed.",["--reason <text>"]);let i=await Wo(t,()=>vv(t,n,o)),r=zs(t),s=Eu(new yt(t)).episodes.map(a=>a.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:Dc.join(t,"script.json")}},V]}import*as Bc from"node:fs";import*as Di from"node:path";import{spawnSync as Ov}from"node:child_process";function Gc(e,t,n,o){return new S(e,{exitCode:k,errorCode:t,hint:n,data:{actual:o}})}function Rv(e){let t=Pr(Ht(e)),n=vc(t);if(n)throw Gc("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=Bc.statSync(i),s=r.size,a=Math.trunc(r.mtimeMs),c=Ov("ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",i],{encoding:"utf-8"}),d=Number(c.stdout.trim()),p=c.status===0&&Number.isFinite(d)&&d>0?Math.round(d*1e3):void 0;return{episode:o.episode,path:i,ext:o.ext,mime:o.mime,sha256:_e(JSON.stringify({absolutePath:i,sizeBytes:s,mtimeMs:a})),size_bytes:s,mtime_ms:a,duration_ms:p}})}async function Mv(e){let t=Di.resolve(e.scriptPath),n=Di.resolve(e.sourcePath),o=Di.resolve(e.workspacePath),i=tr(JSON.parse(Bc.readFileSync(t,"utf-8"))),r=Rv(n);if(r.length!==i.episodes.length)throw Gc("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=Mc(r),a=Oc([],i,Yo(),r,s),c=await Wo(o,async()=>{let p=new yt(o);return p.ensure(),Nc(p,a,e.signal,e.extractor,{reuseExistingFrames:e.force!==!0})}),d=[...c.items.flatMap(p=>p.samples),...(c.identities??[]).flatMap(p=>p.samples)];return{output:Di.join(o,"evidence","state-evidence.json"),states:c.items.length,identities:c.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 ex(e){let t=he(e),n=typeof e.source_path=="string"?e.source_path.trim():"",o=typeof e.workspace_path=="string"?e.workspace_path.trim():"";if(!n)throw Gc("--source-path is required.","EVIDENCE_SOURCE_REQUIRED","Pass the linked source-video file or folder.",["--source-path <path>"]);if(!o)throw Gc("--workspace-path is required.","EVIDENCE_WORKSPACE_REQUIRED","Pass the project workspace directory.",["--workspace-path <path>"]);let i=await Mv({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}},V]}import*as ei from"node:fs";import*as Jc from"node:path";var Mt=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ho=e=>Array.isArray(e),Ye=e=>typeof e=="string"?e:"",Nv={interior:"\u5185",exterior:"\u5916"},Lv={day:"\u65E5",night:"\u591C"},Uv=e=>{let t=e.match(/(\d+)/);return t?Number(t[1]):0},Pv=e=>{let t=e.match(/(\d+)/);return t?Number(t[1]):0};function Ou(e,t,n){let o=new Map;if(ho(e))for(let i of e)Mt(i)&&typeof i[t]=="string"&&o.set(i[t],Ye(i[n]));return o}function Cv(e,t){let n=new Map;if(ho(e))for(let o of e){if(!Mt(o)||typeof o[t]!="string")continue;let i=new Map;for(let r of ho(o.states)?o.states:[])Mt(r)&&typeof r.state_id=="string"&&i.set(r.state_id,Ye(r.state_name));n.set(o[t],i)}return n}function Tv(e,t){return Mt(e)?typeof e.actor_id=="string"?t.get(e.actor_id)??e.actor_id:typeof e.kind=="string"?`${e.kind}${e.label?`:${Ye(e.label)}`:""}`:"":""}function Vv(e){let t=Ou(e.actors,"actor_id","actor_name"),n=Ou(e.locations,"location_id","location_name"),o=Ou(e.props,"prop_id","prop_name"),i=Cv(e.actors,"actor_id"),r=(ho(e.episodes)?e.episodes:[]).filter(Mt).map(a=>({episode:Uv(Ye(a.episode_id)),synopsis:Ye(a.synopsis),scenes:(ho(a.scenes)?a.scenes:[]).filter(Mt).map(c=>{let d=Mt(c.location)?n.get(Ye(c.location.location_id))??Ye(c.location.location_id):"",p=[],l={};for(let h of ho(c.actors)?c.actors:[]){if(!Mt(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 ho(c.props)?c.props:[])if(Mt(h)&&typeof h.prop_id=="string"){let m=o.get(h.prop_id)??h.prop_id;f.includes(m)||f.push(m)}let u=Mt(c.environment)?c.environment:{};return{scene_num:Pv(Ye(c.scene_id)),location_name:d,environment:{space:Nv[Ye(u.space)]??Ye(u.space),time:Lv[Ye(u.time)]??Ye(u.time)},actor_names:p,actor_states:l,prop_names:f,actions:(ho(c.actions)?c.actions:[]).filter(Mt).map(h=>({type:Ye(h.type),content:Ye(h.content),speaker:Tv(h.speaker,t),emotion:typeof h.emotion=="string"?h.emotion:void 0,extend:Mt(h.extend)&&typeof h.extend.timestamp=="string"?{timestamp:h.extend.timestamp}:void 0}))}})})),s=(ho(e.actors)?e.actors:[]).filter(Mt).map(a=>({asset_name:Ye(a.actor_name),description:Ye(a.description),extend:{}}));return{title:Ye(e.title),actors:s,episodes:r}}function tx(e){if(!Mt(e))throw new Error("review renderer expects a script object");let t=Vv(e),n=JSON.stringify(t),o=Ye(t.title);return`<!DOCTYPE html>
|
|
336
343
|
<html lang="zh">
|
|
337
344
|
<head>
|
|
338
345
|
<meta charset="utf-8">
|
|
@@ -653,10 +660,10 @@ tabScript.addEventListener('click',()=>switchTab('script'));
|
|
|
653
660
|
tabAssets.addEventListener('click',()=>switchTab('assets'));
|
|
654
661
|
</script>
|
|
655
662
|
</body>
|
|
656
|
-
</html>`}import*as
|
|
663
|
+
</html>`}import*as nx from"node:http";import*as Xo from"node:fs";import*as Gn from"node:path";import{spawn as $v}from"node:child_process";var Dv=e=>e==null?"":String(e);function Gv(e){let t=r=>{try{let s=Xo.statSync(Gn.join(e,r));return{rel:r,size:s.size,mtime:s.mtimeMs}}catch{return null}},n=(r,s)=>{let a=[];try{a=Xo.readdirSync(Gn.join(e,r))}catch{return[]}return a.filter(s).sort().map(c=>t(`${r}/${c}`)).filter(c=>!!c)},o=r=>r.filter(s=>!!s),i=r=>n("ep",s=>s.endsWith(r)&&!s.endsWith(".error.json"));return{\u7ED3\u679C:o([t("script.json"),t("validation.json"),t("asset-audit.json"),t("usage.json"),t("review.html"),t("timings.json")]),\u4E0A\u4E0B\u6587:n("serial",r=>r.startsWith("context_")&&r.endsWith(".md")),\u6BCF\u7A97\u66F4\u65B0:n("serial",r=>r.startsWith("win_")&&r.endsWith(".json")),\u7BC7\u7AE0\u6897\u6982:n("serial",r=>r.startsWith("arc_")&&r.endsWith(".md")),\u524D\u6BB5:n("pass2",r=>/^chunk_\d+\.json$/.test(r)),\u8F6C\u5F55:[...i(".ep"),...i(".md").filter(r=>!r.rel.endsWith(".context.md"))].sort((r,s)=>r.rel.localeCompare(s.rel)),\u9001\u6A21\u4E0A\u4E0B\u6587:i(".context.md"),\u89E3\u6790:i(".json"),\u82B1\u540D\u518C:o([t("context.json")]),\u8BA1\u65F6:o([t("timing.jsonl")]),\u4E2D\u95F4\u4EA7\u7269:o([t("script.initial.json"),t("provisional_assets.json"),t("notes.json"),t("id_map.json"),t("manifest.json")])}}function Bv(e){let t="";try{t=Xo.readFileSync(Gn.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 a={episode:s.episode};typeof s.transcodeMs=="number"&&(a.transcodeMs=s.transcodeMs,o+=s.transcodeMs),typeof s.uploadMs=="number"&&(a.uploadMs=s.uploadMs,o+=s.uploadMs),typeof s.generateMs=="number"&&(a.generateMs=s.generateMs,o+=s.generateMs),typeof s.uploadMB=="string"&&(a.uploadMB=s.uploadMB),typeof s.transcoded=="boolean"&&(a.transcoded=s.transcoded),n.push(a)}catch{}}return{episodes:n,totalMs:o}}function Jv(e){try{return JSON.parse(Xo.readFileSync(Gn.join(e,"usage.json"),"utf-8"))}catch{return null}}function zv(e,t){let n=Gn.resolve(e,t);if(n!==e&&!n.startsWith(e+Gn.sep))return{ok:!1};try{return{ok:!0,text:Xo.readFileSync(n,"utf-8")}}catch{return{ok:!1}}}function Ks(e,t,n,o){e.writeHead(t,{"Content-Type":n,"Cache-Control":"no-store"}),e.end(o)}async function ox(e){let t=Gn.resolve(Dv(e.workspace_path||"workspace")),n=Number(e.port)||0,o=nx.createServer((s,a)=>{let c=new URL(s.url??"/","http://localhost");if(c.pathname==="/")return Ks(a,200,"text/html; charset=utf-8",Kv);if(c.pathname==="/api/state"){let d=zs(t);return Ks(a,200,"application/json",JSON.stringify({root:t,status:d,groups:Gv(t),timing:Bv(t),usage:Jv(t)}))}if(c.pathname==="/api/file"){let d=c.searchParams.get("path")??"",p=zv(t,d);return p.ok?Ks(a,200,"text/plain; charset=utf-8",p.text):Ks(a,404,"text/plain","not found")}Ks(a,404,"text/plain","not found")}),r=`http://127.0.0.1:${await new Promise((s,a)=>{o.once("error",a),o.listen(n,"127.0.0.1",()=>s(o.address().port))})}/`;if(process.stderr.write(`Ingest monitor: ${r}
|
|
657
664
|
Workspace: ${t}
|
|
658
665
|
Press Ctrl-C to stop.
|
|
659
|
-
`),process.platform==="darwin"&&process.stderr.isTTY)try{
|
|
666
|
+
`),process.platform==="darwin"&&process.stderr.isTTY)try{$v("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}},V]}var Kv=`<!doctype html><html lang="zh"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
660
667
|
<title>scriptctl ingest \u76D1\u542C</title>
|
|
661
668
|
<style>
|
|
662
669
|
:root{--bg:#f6f7f9;--panel:#ffffff;--panel2:#f0f2f5;--line:#e3e6ea;--fg:#1f2430;--dim:#6b7280;--acc:#2563eb;--ok:#16a34a;--warn:#d97706;--err:#dc2626}
|
|
@@ -854,7 +861,7 @@ function poll(){
|
|
|
854
861
|
}).catch(function(){$('#tick').textContent='\u25CF \u79BB\u7EBF'});
|
|
855
862
|
}
|
|
856
863
|
poll();setInterval(poll,1500);setInterval(renderTiming,1000);
|
|
857
|
-
</script></body></html>`;function
|
|
864
|
+
</script></body></html>`;function ix(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,a)=>({title:s.title??`\u7B2C ${a+1} \u8BDD`,synopsis:s.synopsis??"",scenes:s.scenes.map((c,d)=>({title:`${d+1} \xB7 ${c.location?o.get(c.location.location_id):"\u672A\u660E\u786E\u5730\u70B9"}`,actions:c.actions.map(p=>{let l=Ii.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>
|
|
858
865
|
<html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
859
866
|
<title>\u6F2B\u753B\u5267\u672C\u5BA1\u9605</title>
|
|
860
867
|
<style>
|
|
@@ -1003,31 +1010,31 @@ if(model.episodes.length){
|
|
|
1003
1010
|
const action=actions.find(action=>action.id===requested.get('action'));
|
|
1004
1011
|
if(action?.source){const page=Number(requested.get('page'));selectAction(action,action.source.pages.includes(page)?page:action.source.pages[0],true,requested.has('region')?Number(requested.get('region')):undefined);}
|
|
1005
1012
|
}
|
|
1006
|
-
</script></html>`}var Tv=e=>e==null?"":String(e),Vv=e=>String(e).padStart(3,"0");function $v(e){if(!e.has("manifest.json"))return;let t=e.readJson("manifest.json");if(!Array.isArray(t.episodes))return;let n=e.path("src");Xo.mkdirSync(n,{recursive:!0});for(let o of t.episodes){if(typeof o.episode!="number"||typeof o.path!="string")continue;let i=Dc.join(n,`ep_${Vv(o.episode)}.mp4`);try{Xo.rmSync(i,{force:!0}),Xo.symlinkSync(o.path,i)}catch{}}}async function tx(e){if(e.watch){if((process.env.SANDBOX_PROJECT_GROUP_NO??"").trim())throw new S("`view --watch` runs a local web server and opens a browser; it is local-only and unavailable in the sandbox.",{exitCode:k,errorCode:"VIEW_WATCH_SANDBOX",hint:"Use `scriptctl ingest status` for progress in the sandbox; run `view --watch` on your local machine."});return Xw(e)}let t=Tv(e.workspace_path||"workspace"),n=new yt(Dc.resolve(t));if(!n.has("script.json"))throw new S("workspace has no script.json to render.",{exitCode:k,errorCode:"VIEW_NO_SCRIPT",hint:"Run `scriptctl ingest --source-path <src> --workspace-path <dir>` first.",data:{actual:[n.path("script.json")]}});let o=n.has("manifest.json")?n.readJson("manifest.json"):null,i;if(o?.source?.kind==="comic-file"||o?.source?.kind==="comic-directory"){let s=n.readJson("manifest.json"),a=er(n.readJson("script.json")),c=new Set;for(let p of a.episodes)for(let l of p.scenes)for(let f of l.actions){let u=Si.safeParse(f.extend);u.success&&c.add(u.data.scriptctl.source.document_id)}let d=[];n.passDir("src");for(let p of c){let l=s.episodes.find(h=>h.document_id===p);if(!l)throw new S(`Unknown comic source document: ${p}`,{exitCode:k,errorCode:"VIEW_COMIC_SOURCE_MISSING"});let f=n.path(`src/${l.document_id}.pdf`);Xo.rmSync(f,{force:!0}),Xo.symlinkSync(l.path,f);let u=await ja(l,n.root);d.push({id:l.document_id,title:l.title,pdf:`src/${l.document_id}.pdf`,images:u})}i=ex(a,d)}else $v(n),i=Zw(n.readJson("script.json"));n.writeText("review.html",i);let r=n.path("review.html");return[{text:r,data:{output:r}},V]}import*as Di from"node:path";import Dv from"fast-json-patch";var{compare:nx}=Dv;var ox="/api/anime/workbench/v2/script/project-groups",Gv="/api/anime/workbench/projectGroup/updateProjectGroupInfo",Bv=5e3,ix=8*1024*1024;function Jv(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 rx(e){return encodeURIComponent(String(e))}function zv(e,t,n){if(t===404&&n.includes("/imports"))return new ge("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 ge(r,{status:t,code:i.code??null,payload:i})}return new ge(e||`HTTP ${t}`,{status:t,payload:e})}function sx(e,t){let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(!(n<=ix))throw new ge(`script ${e} body too large: ${n} bytes (limit ${ix})`)}async function ax(e,t,n,o,i,r={}){let s=r.body===void 0?void 0:JSON.stringify(r.body),a={Accept:"application/json","X-Access-Key":t};s!==void 0&&(a["Content-Type"]="application/json; charset=utf-8");let c=new AbortController,d=setTimeout(()=>c.abort(),n),p,l;try{let m=await fetch(`${e}${i}`,{method:o,headers:a,body:s,signal:c.signal});p=m.status,l=await m.text()}catch(m){if(m instanceof Error&&m.name==="AbortError")throw new ge("Gateway request timed out");let g=m instanceof Error?m.message:String(m);throw new ge(`Gateway request failed: ${g}`)}finally{clearTimeout(d)}if(p>=400)throw zv(l,p,i);let f=null;if(l)try{f=JSON.parse(l)}catch{throw new ge("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 ge(m,{status:p,code:h,payload:u})}return"data"in u?u.data:u}var bu=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 ge("projectGroupNo missing; pass --project-group-no or set SANDBOX_PROJECT_GROUP_NO",{configMissing:"project"});let o=Jv(process.env.AWB_BASE_URL||"");if(!o)throw new ge("gateway URL missing; set AWB_BASE_URL",{configMissing:"gateway"});let i=(process.env.LINGJING_AWB_ACCESS_KEY||"").trim();if(!i)throw new ge("access key missing; set LINGJING_AWB_ACCESS_KEY",{configMissing:"access"});return new e({gatewayBase:o,projectGroupNo:n,accessKey:i})}get projectPrefix(){return`${ox}/${rx(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:nx(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 sx("root",n),await this.request("PUT",this.projectPrefix,{body:n})}async patchScript(t){let n=nx(t.old,t.edited),o={requestId:t.requestId,baseRevision:t.baseRevision,source:t.source??"ctl",patch:n};return sx("patch",o),await this.request("PATCH",this.projectPrefix,{body:o})}async saveValidationResult(t){return await this.request("POST",`${ox}/${rx(this.projectGroupNo)}/validation-result`,{body:{revision:t.revision,validationStatus:t.validationStatus,validationSummary:t.validationSummary,issues:t.issues}})}async updateEpisodeCount(t){await ax(this.gatewayBase,this.accessKey,Math.min(this.timeoutMs,Bv),"POST",Gv,{body:{projectGroupNo:this.projectGroupNo,episodeCount:t}})}async request(t,n,o={}){return ax(this.gatewayBase,this.accessKey,this.timeoutMs,t,n,o)}};function vu(e){return bu.fromEnv(e)}var zs=class{workspace;script;version;baseline;baselineHash;scriptPath;client;projectGroupNo;revision;constructor(t){this.workspace=t.workspace,this.script=t.script,this.version=ci(t.script),this.baseline=structuredClone(t.script),this.baselineHash=je(t.script),this.scriptPath=t.scriptPath??null,this.client=t.client??null,this.projectGroupNo=t.projectGroupNo??null,this.revision=t.revision??null}get remote(){return this.client!==null}get artifactLabel(){return this.remote?`script-output/${this.projectGroupNo}@revision/${this.revision??0}`:this.scriptPath??""}};function ei(e,t){let n=t.message||"script-output API failed",o=String(t.code)==="9002"||n.includes("\u7248\u672C\u51B2\u7A81"),i=n.includes("\u5267\u672C\u4E0D\u5B58\u5728"),r=o?"Script has been updated by another revision; keep local work and merge before retrying.":i?"Script not found on the gateway.":"Gateway request failed.";return new S(r,{exitCode:t.status!==null&&t.status>=500?q: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 Ks(e){let t=O(e.workspace_path||"workspace"),n=he(e);if(!ri(n))throw new S("Local script file not found.",{exitCode:k,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[n]}});let o;try{o=jr(n)}catch(i){throw new S("script JSON invalid.",{exitCode:k,errorCode:"SCRIPT_JSON_INVALID",hint:"Fix the local script JSON syntax before editing.",data:{expected:["valid JSON"],actual:[`${n}: ${i.message}`]}})}if(!ie(o))throw new S("script root invalid.",{exitCode:B,errorCode:"SCRIPT_ROOT_INVALID",hint:"Use a valid script document object.",data:{expected:["script root object"],actual:[Array.isArray(o)?"array":typeof o]}});return new zs({workspace:t,scriptPath:n,script:o})}function js(e,t={}){let n=Ou(e.script);return e.remote&&(n.script_path=e.artifactLabel),n}function Kv(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=ce(e.episodes),a=0,c=0;for(let d of s)for(let p of ce(d.scenes))a+=1,c+=ce(p.actions).length;return{passed:n,has_blocking:!n,issues:r,stats:{actors:ce(e.actors).length,locations:ce(e.locations).length,props:ce(e.props).length,episodes:s.length,scenes:a,actions:c}}}function Ou(e){return Kv(e,es(e))}function jv(e){if(e.path)return O(e.path);let t=[];return e.episode!==null&&e.episode!==void 0&&t.push(O(e.episode)),e.scene!==null&&e.scene!==void 0&&t.push(O(e.scene)),e.action_index!==null&&e.action_index!==void 0&&t.push(`action[${e.action_index}]`),t.length>0?t.join("/"):null}function Hv(e){let t=O(e||"info");return t==="blocking"||t==="error"?"error":t==="warning"?"warning":"info"}function Qv(e){let t=ce(e.issues),n=e.passed?"valid":"invalid",o={passed:!!e.passed,hasBlocking:!!e.has_blocking,stats:e.stats??{},issueCount:t.length},i=[];for(let r of t){if(!ie(r))continue;let s={...r};for(let a of["severity","code","path","summary","repair_hint"])delete s[a];i.push({severity:Hv(r.severity),code:O(r.code||"SCRIPT_VALIDATION_ISSUE"),path:jv(r),summary:O(r.summary),repairHint:r.repair_hint,payload:s})}return[n,o,i]}async function Ru(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]=Qv(t);try{await e.client.saveValidationResult({revision:o,validationStatus:i,validationSummary:r,issues:s})}catch(a){throw a instanceof ge?ei("SCRIPT API BLOCKED: Validation sync failed",a):a}}async function Mu(e,t,n){if(e.scriptPath===null)throw new Error("local script session missing script path");return Kt(e.scriptPath,e.baselineHash),Ze(e.scriptPath,e.script),[null,!1]}async function cx(e,t=pn){let n=await Ks(e),o=t.createExecutor(O(e.llm_config).trim()||void 0),i=await Ql(n.script,o);n.scriptPath&&Kt(n.scriptPath,n.baselineHash);let r=n.scriptPath?Di.dirname(n.scriptPath):Di.resolve(n.workspace),s=Di.resolve(O(e.output).trim()||Di.join(r,"asset-audit.json"));Ze(s,i);let a=i.issues.length>0,c=i.issues.map(Fl);return[{text:[`${i.summary.issues} issues; confidence high=${i.summary.high} medium=${i.summary.medium} low=${i.summary.low}`,...c,`output: ${s}`,...a?["Inspect each finding, repair confirmed duplicates, then rerun `scriptctl audit-assets` and `scriptctl validate`."]:[]].join(`
|
|
1007
|
-
`),data:{op:"script.audit-assets",changed:!1,issues:i.issues,output:s,asset_audit:i,config_source:o.configSource,llm_routes:o.usage()}},a?Eo:V]}function
|
|
1008
|
-
`),data:{op:"script.create",changed:!0,validation:t,script_path:e.artifactLabel,...e.remote?{revision:e.revision,idempotent:n}:{}}}}async function
|
|
1013
|
+
</script></html>`}var jv=e=>e==null?"":String(e),Hv=e=>String(e).padStart(3,"0");function Qv(e){if(!e.has("manifest.json"))return;let t=e.readJson("manifest.json");if(!Array.isArray(t.episodes))return;let n=e.path("src");ei.mkdirSync(n,{recursive:!0});for(let o of t.episodes){if(typeof o.episode!="number"||typeof o.path!="string")continue;let i=Jc.join(n,`ep_${Hv(o.episode)}.mp4`);try{ei.rmSync(i,{force:!0}),ei.symlinkSync(o.path,i)}catch{}}}async function rx(e){if(e.watch){if((process.env.SANDBOX_PROJECT_GROUP_NO??"").trim())throw new S("`view --watch` runs a local web server and opens a browser; it is local-only and unavailable in the sandbox.",{exitCode:k,errorCode:"VIEW_WATCH_SANDBOX",hint:"Use `scriptctl ingest status` for progress in the sandbox; run `view --watch` on your local machine."});return ox(e)}let t=jv(e.workspace_path||"workspace"),n=new yt(Jc.resolve(t));if(!n.has("script.json"))throw new S("workspace has no script.json to render.",{exitCode:k,errorCode:"VIEW_NO_SCRIPT",hint:"Run `scriptctl ingest --source-path <src> --workspace-path <dir>` first.",data:{actual:[n.path("script.json")]}});let o=n.has("manifest.json")?n.readJson("manifest.json"):null,i;if(o?.source?.kind==="comic-file"||o?.source?.kind==="comic-directory"){let s=n.readJson("manifest.json"),a=tr(n.readJson("script.json")),c=new Set;for(let p of a.episodes)for(let l of p.scenes)for(let f of l.actions){let u=Ii.safeParse(f.extend);u.success&&c.add(u.data.scriptctl.source.document_id)}let d=[];n.passDir("src");for(let p of c){let l=s.episodes.find(h=>h.document_id===p);if(!l)throw new S(`Unknown comic source document: ${p}`,{exitCode:k,errorCode:"VIEW_COMIC_SOURCE_MISSING"});let f=n.path(`src/${l.document_id}.pdf`);ei.rmSync(f,{force:!0}),ei.symlinkSync(l.path,f);let u=await Qa(l,n.root);d.push({id:l.document_id,title:l.title,pdf:`src/${l.document_id}.pdf`,images:u})}i=ix(a,d)}else Qv(n),i=tx(n.readJson("script.json"));n.writeText("review.html",i);let r=n.path("review.html");return[{text:r,data:{output:r}},V]}import*as Gi from"node:path";import Fv from"fast-json-patch";var{compare:sx}=Fv;var ax="/api/anime/workbench/v2/script/project-groups",Yv="/api/anime/workbench/projectGroup/updateProjectGroupInfo",qv=5e3,cx=8*1024*1024;function Wv(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 dx(e){return encodeURIComponent(String(e))}function Zv(e,t,n){if(t===404&&n.includes("/imports"))return new ge("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 ge(r,{status:t,code:i.code??null,payload:i})}return new ge(e||`HTTP ${t}`,{status:t,payload:e})}function px(e,t){let n=Buffer.byteLength(JSON.stringify(t),"utf8");if(!(n<=cx))throw new ge(`script ${e} body too large: ${n} bytes (limit ${cx})`)}async function lx(e,t,n,o,i,r={}){let s=r.body===void 0?void 0:JSON.stringify(r.body),a={Accept:"application/json","X-Access-Key":t};s!==void 0&&(a["Content-Type"]="application/json; charset=utf-8");let c=new AbortController,d=setTimeout(()=>c.abort(),n),p,l;try{let m=await fetch(`${e}${i}`,{method:o,headers:a,body:s,signal:c.signal});p=m.status,l=await m.text()}catch(m){if(m instanceof Error&&m.name==="AbortError")throw new ge("Gateway request timed out");let g=m instanceof Error?m.message:String(m);throw new ge(`Gateway request failed: ${g}`)}finally{clearTimeout(d)}if(p>=400)throw Zv(l,p,i);let f=null;if(l)try{f=JSON.parse(l)}catch{throw new ge("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 ge(m,{status:p,code:h,payload:u})}return"data"in u?u.data:u}var Ru=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 ge("projectGroupNo missing; pass --project-group-no or set SANDBOX_PROJECT_GROUP_NO",{configMissing:"project"});let o=Wv(process.env.AWB_BASE_URL||"");if(!o)throw new ge("gateway URL missing; set AWB_BASE_URL",{configMissing:"gateway"});let i=(process.env.LINGJING_AWB_ACCESS_KEY||"").trim();if(!i)throw new ge("access key missing; set LINGJING_AWB_ACCESS_KEY",{configMissing:"access"});return new e({gatewayBase:o,projectGroupNo:n,accessKey:i})}get projectPrefix(){return`${ax}/${dx(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:sx(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 px("root",n),await this.request("PUT",this.projectPrefix,{body:n})}async patchScript(t){let n=sx(t.old,t.edited),o={requestId:t.requestId,baseRevision:t.baseRevision,source:t.source??"ctl",patch:n};return px("patch",o),await this.request("PATCH",this.projectPrefix,{body:o})}async saveValidationResult(t){return await this.request("POST",`${ax}/${dx(this.projectGroupNo)}/validation-result`,{body:{revision:t.revision,validationStatus:t.validationStatus,validationSummary:t.validationSummary,issues:t.issues}})}async updateEpisodeCount(t){await lx(this.gatewayBase,this.accessKey,Math.min(this.timeoutMs,qv),"POST",Yv,{body:{projectGroupNo:this.projectGroupNo,episodeCount:t}})}async request(t,n,o={}){return lx(this.gatewayBase,this.accessKey,this.timeoutMs,t,n,o)}};function Mu(e){return Ru.fromEnv(e)}var js=class{workspace;script;version;baseline;baselineHash;scriptPath;client;projectGroupNo;revision;constructor(t){this.workspace=t.workspace,this.script=t.script,this.version=di(t.script),this.baseline=structuredClone(t.script),this.baselineHash=je(t.script),this.scriptPath=t.scriptPath??null,this.client=t.client??null,this.projectGroupNo=t.projectGroupNo??null,this.revision=t.revision??null}get remote(){return this.client!==null}get artifactLabel(){return this.remote?`script-output/${this.projectGroupNo}@revision/${this.revision??0}`:this.scriptPath??""}};function ti(e,t){let n=t.message||"script-output API failed",o=String(t.code)==="9002"||n.includes("\u7248\u672C\u51B2\u7A81"),i=n.includes("\u5267\u672C\u4E0D\u5B58\u5728"),r=o?"Script has been updated by another revision; keep local work and merge before retrying.":i?"Script not found on the gateway.":"Gateway request failed.";return new S(r,{exitCode:t.status!==null&&t.status>=500?q: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 Hs(e){let t=O(e.workspace_path||"workspace"),n=he(e);if(!si(n))throw new S("Local script file not found.",{exitCode:k,errorCode:"SCRIPT_NOT_FOUND",hint:"Run `scriptctl checkout`, `scriptctl create`, or pass --script-path to an existing script.",data:{expected:["existing local script JSON"],actual:[n]}});let o;try{o=Hr(n)}catch(i){throw new S("script JSON invalid.",{exitCode:k,errorCode:"SCRIPT_JSON_INVALID",hint:"Fix the local script JSON syntax before editing.",data:{expected:["valid JSON"],actual:[`${n}: ${i.message}`]}})}if(!ie(o))throw new S("script root invalid.",{exitCode:B,errorCode:"SCRIPT_ROOT_INVALID",hint:"Use a valid script document object.",data:{expected:["script root object"],actual:[Array.isArray(o)?"array":typeof o]}});return new js({workspace:t,scriptPath:n,script:o})}function Qs(e,t={}){let n=Nu(e.script);return e.remote&&(n.script_path=e.artifactLabel),n}function Xv(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=ce(e.episodes),a=0,c=0;for(let d of s)for(let p of ce(d.scenes))a+=1,c+=ce(p.actions).length;return{passed:n,has_blocking:!n,issues:r,stats:{actors:ce(e.actors).length,locations:ce(e.locations).length,props:ce(e.props).length,episodes:s.length,scenes:a,actions:c}}}function Nu(e){return Xv(e,ts(e))}function e0(e){if(e.path)return O(e.path);let t=[];return e.episode!==null&&e.episode!==void 0&&t.push(O(e.episode)),e.scene!==null&&e.scene!==void 0&&t.push(O(e.scene)),e.action_index!==null&&e.action_index!==void 0&&t.push(`action[${e.action_index}]`),t.length>0?t.join("/"):null}function t0(e){let t=O(e||"info");return t==="blocking"||t==="error"?"error":t==="warning"?"warning":"info"}function n0(e){let t=ce(e.issues),n=e.passed?"valid":"invalid",o={passed:!!e.passed,hasBlocking:!!e.has_blocking,stats:e.stats??{},issueCount:t.length},i=[];for(let r of t){if(!ie(r))continue;let s={...r};for(let a of["severity","code","path","summary","repair_hint"])delete s[a];i.push({severity:t0(r.severity),code:O(r.code||"SCRIPT_VALIDATION_ISSUE"),path:e0(r),summary:O(r.summary),repairHint:r.repair_hint,payload:s})}return[n,o,i]}async function Lu(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]=n0(t);try{await e.client.saveValidationResult({revision:o,validationStatus:i,validationSummary:r,issues:s})}catch(a){throw a instanceof ge?ti("SCRIPT API BLOCKED: Validation sync failed",a):a}}async function Uu(e,t,n){if(e.scriptPath===null)throw new Error("local script session missing script path");return Kt(e.scriptPath,e.baselineHash),We(e.scriptPath,e.script),[null,!1]}async function ux(e,t=pn){let n=await Hs(e),o=t.createExecutor(O(e.llm_config).trim()||void 0),i=await ql(n.script,o);n.scriptPath&&Kt(n.scriptPath,n.baselineHash);let r=n.scriptPath?Gi.dirname(n.scriptPath):Gi.resolve(n.workspace),s=Gi.resolve(O(e.output).trim()||Gi.join(r,"asset-audit.json"));We(s,i);let a=i.issues.length>0,c=i.issues.map(Wl);return[{text:[`${i.summary.issues} issues; confidence high=${i.summary.high} medium=${i.summary.medium} low=${i.summary.low}`,...c,`output: ${s}`,...a?["Inspect each finding, repair confirmed duplicates, then rerun `scriptctl audit-assets` and `scriptctl validate`."]:[]].join(`
|
|
1014
|
+
`),data:{op:"script.audit-assets",changed:!1,issues:i.issues,output:s,asset_audit:i,config_source:o.configSource,llm_routes:o.usage()}},a?Eo:V]}function fx(e=""){return{version:4,title:e,worldview:"",style:"",actors:[],locations:[],props:[],episodes:[]}}function ni(e){let t=ie(e.location)?e.location:null;return{actors:Yn(e.actors)?e.actors:[],props:Yn(e.props)?e.props:[],locations:t&&String(t.location_id??"").trim()?[t]:[]}}function Sx(e,t,n){let o=!!t.passed,i=[`created: blank script (Script v${e.version})`,`validation: ${o?"passed":"needs repair"}`];return e.remote&&(i.push(`revision: ${e.revision}`),n!==null&&i.push(`idempotent: ${String(n).toLowerCase()}`)),{text:i.join(`
|
|
1015
|
+
`),data:{op:"script.create",changed:!0,validation:t,script_path:e.artifactLabel,...e.remote?{revision:e.revision,idempotent:n}:{}}}}async function Ix(e){let t=O(e.workspace_path||"workspace"),n=!!e.force,o=O(e.title).trim(),i=fx(o),r=he(e);if(si(r)&&!n)throw new S("A script already exists at the target.",{exitCode:k,errorCode:"SCRIPT_EXISTS",hint:"Edit the existing script with the atomic verbs, or pass --force to overwrite with a blank scaffold.",data:{expected:["a non-existent target, or --force to overwrite"],actual:[r]}});We(r,i);let s=new js({workspace:t,scriptPath:r,script:i}),a=Qs(s),c=!!a.passed;return[Sx(s,a,null),c?V:Eo]}import*as $r from"node:fs";import*as Ji from"node:path";function h0(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 a=`${i}#${s}`;t[a]=a})}return t}function Bi(e){return ie(e)&&Object.values(e).every(t=>typeof t=="string")}function y0(e){return ie(e)&&Object.values(e).every(Bi)}function w0(e){return ie(e)&&e.version===3&&Bi(e.actor)&&Bi(e.location)&&Bi(e.prop)&&y0(e.state)&&Bi(e.episode)&&Bi(e.scene)&&Bi(e.action)}function x0(e){if(e!==void 0){if(w0(e.identityMap))return e.identityMap;throw new S("Migration manifest contains an invalid v3-to-v4 identity map.",{exitCode:k,errorCode:"MIGRATE_MANIFEST_INVALID"})}}function Ax(e,t){let n=Gt(e),o=Ar(n,x0(t),{action:h0(n)});return{script:o.script,artifact:{sourceVersion:3,targetVersion:4,identityMap:o.identityMap}}}var E0=[{sourceVersion:3,targetVersion:4,migrate:Ax}];function _0(e){return ie(e)&&ko(e.source_version)&&ko(e.target_version)&&e.source_version<e.target_version&&"identity_map"in e}function kx(e){if(!Array.isArray(e))throw new S("Migration manifest steps must be an array.",{exitCode:k,errorCode:"MIGRATE_MANIFEST_INVALID"});return e.map(t=>{if(!_0(t))throw new S("Migration manifest contains an invalid step artifact.",{exitCode:k,errorCode:"MIGRATE_MANIFEST_INVALID"});return{sourceVersion:t.source_version,targetVersion:t.target_version,identityMap:t.identity_map}})}function S0(e,t){return E0.find(n=>n.sourceVersion===e&&n.targetVersion<=t)}function I0(e,t){return e.find(n=>n.sourceVersion===t.sourceVersion&&n.targetVersion===t.targetVersion)}function bx(e,t,n=[]){let o=di(e);if(t<o)throw new S("A migration target must be newer than the source script.",{exitCode:k,errorCode:"MIGRATE_TARGET_OLDER",data:{expected:[String(o)],actual:[String(t)]}});let i=ha(e),r=o,s=[];for(;r<t;){let a=S0(r,t);if(a===void 0)throw new S(`No migration path exists from Script v${r} to Script v${t}.`,{exitCode:k,errorCode:"MIGRATE_PATH_UNSUPPORTED",data:{actual:[String(r),String(t)]}});let c=a.migrate(i,I0(n,a));i=c.script,r=a.targetVersion,s.push(c.artifact)}return{sourceVersion:o,targetVersion:t,script:i,steps:s}}function Fs(e,t){let n=e[t];return typeof n=="string"?n.trim():""}function A0(e,t){let n=Fs(e,t);return/^\d+$/.test(n)?Number(n):null}function k0(e){let t=A0(e,"to");if(ko(t))return t;throw new S("A supported migration target version is required.",{exitCode:B,errorCode:"MIGRATE_TARGET_INVALID",hint:"Pass --to <version> with a supported Script version.",data:{expected:Vd.map(String),actual:[Fs(e,"to")||"<empty>"]}})}function b0(e){let t=Ji.extname(e);return`${t.length>0?e.slice(0,-t.length):e}.migration.json`}function v0(e,t,n){let o=[e,t,n].map(i=>Ji.resolve(i));if(o[0]===o[1])throw new S("The migration destination must differ from the source.",{exitCode:B,errorCode:"MIGRATE_SAME_PATH",hint:"Choose a separate --output path. The source file stays unchanged.",data:{actual:[e]}});if(o[0]===o[2]||o[1]===o[2])throw new S("The migration manifest needs its own file path.",{exitCode:B,errorCode:"MIGRATE_MANIFEST_PATH",hint:"Choose a --manifest path separate from the source and output files.",data:{actual:[n]}})}function vx(e,t){if(!t&&$r.existsSync(e))throw new S("Migration destination already exists.",{exitCode:B,errorCode:"MIGRATE_OUTPUT_EXISTS",hint:"Choose a new path, or pass --force to replace the migration artifact.",data:{actual:[e]}})}function O0(e){let t;try{t=$r.readFileSync(e,"utf8")}catch(n){throw new S("Cannot read the source script.",{exitCode:B,errorCode:"MIGRATE_SOURCE_READ_FAILED",hint:"Pass an existing JSON file with --script-path.",data:{actual:[e,n instanceof Error?n.message:String(n)]}})}try{return{raw:t,value:JSON.parse(t)}}catch(n){throw new S("The source script is not valid JSON.",{exitCode:B,errorCode:"MIGRATE_SOURCE_JSON_INVALID",hint:"Repair the JSON syntax, then rerun migrate.",data:{actual:[n instanceof Error?n.message:String(n)]}})}}function R0(e,t){if(!t||!$r.existsSync(e))return;let n;try{n=JSON.parse($r.readFileSync(e,"utf8"))}catch(o){throw new S("Cannot reuse the existing migration manifest.",{exitCode:B,errorCode:"MIGRATE_MANIFEST_INVALID",hint:"Restore the migration manifest, or choose a new --manifest path.",data:{actual:[e,o instanceof Error?o.message:String(o)]}})}if(!ie(n)||n.version!==1||!ko(n.source_version)||!ko(n.target_version)||typeof n.source_path!="string"||typeof n.source_sha256!="string")throw new S("Cannot reuse the existing migration manifest.",{exitCode:B,errorCode:"MIGRATE_MANIFEST_INVALID",hint:"Restore the migration manifest, or choose a new --manifest path.",data:{actual:[e]}});return{version:1,source_version:n.source_version,target_version:n.target_version,source_path:n.source_path,source_sha256:n.source_sha256,steps:kx(n.steps)}}async function Ox(e){let t=Fs(e,"script_path"),n=Fs(e,"output");if(!t||!n)throw new S("Migration paths are required.",{exitCode:B,errorCode:"MIGRATE_PATH_MISSING",hint:"Pass --script-path <source.json> and --output <target.json>.",data:{expected:["--script-path <source.json>","--output <target.json>"]}});let o=Ji.resolve(t),i=Ji.resolve(n),r=Ji.resolve(Fs(e,"manifest")||b0(i)),s=k0(e),a=!!e.force;return v0(o,i,r),ua(i,async()=>{vx(i,a),vx(r,a);let c=O0(o),d=di(c.value);if(s<=d)throw new S("The migration target must be newer than the source script.",{exitCode:B,errorCode:"MIGRATE_TARGET_NOT_NEWER",data:{expected:[`>${d}`],actual:[String(s)]}});let p=ts(c.value),l=R0(r,a),f=bx(c.value,s,l?.steps),u=ts(f.script),h={version:1,source_version:f.sourceVersion,target_version:f.targetVersion,source_path:o,source_sha256:_e(c.raw),steps:f.steps};We(r,{...h,steps:h.steps.map(w=>({source_version:w.sourceVersion,target_version:w.targetVersion,identity_map:w.identityMap}))}),We(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(`
|
|
1009
1016
|
`):[`Script v${f.targetVersion}: ${i}`,`Migration manifest: ${r}`,`validation: ${u.errors.length} errors; repair before production use`].join(`
|
|
1010
|
-
`),data:m},u.ok?V:Eo]})}import*as
|
|
1011
|
-
|
|
1012
|
-
`)}function
|
|
1013
|
-
`),
|
|
1014
|
-
`),
|
|
1015
|
-
`),
|
|
1016
|
-
`);function
|
|
1017
|
-
`).trim()}}function
|
|
1017
|
+
`),data:m},u.ok?V:Eo]})}import*as Dr from"node:path";import*as Mx from"node:path";function Rx(e,t){let n=_e(t);return Mx.join(e,`${n}.json`)}function Ys(e){return{read(t){let n=Rx(e,t);return si(n)?Hr(n):null},write(t){md(Rx(e,t.key),t)}}}function Bu(){return{read(){return null},write(){}}}function Ju(e){if(Array.isArray(e))return`[${e.map(t=>Ju(t)).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Ju(t[n])}`).join(",")}}`}return JSON.stringify(e)}function zu(e){return _e(Ju(e))}function Ku(e,t,n){return{key:e,signature:t,value:n,createdAt:new Date().toISOString()}}function M0(e,t){return[e.trim(),t.trim()].filter(Boolean).join(`
|
|
1018
|
+
|
|
1019
|
+
`)}function Lx(e,t){return{system:M0(e.instruction,e.format),user:e.input?e.input({parcel:t}):String(t)}}function N0(e,t,n){if(e.kind==="llm"){if(!n.executor)throw new Error("loom llm task requires run({ executor })");let o=Lx(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 Kc(e){return{kind:"root",children:e}}function Fu(e,t,n){return{kind:"scope",scope:e,data:n,children:t}}function qs(e){return{kind:"parcel",data:e}}function Zs(e){return{kind:"llm",...e}}var ju=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 V0(this.input,this.steps,t)}};function jc(e){return new ju(e)}async function L0(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 U0(e,t){let n=t.partition(e);return Kc(n.map(o=>{let i=t.chunk(o).map(r=>qs(r));return Fu(t.scope,i,o)}))}function Hu(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(...Hu(r,s))}return o}function Ws(e,t){return e?.(t),t}async function P0(e,t){return Ws(e.validate,await e.run({parcel:t}))}async function C0(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 Nx(e,t,n){return Ws(e.validate,e.parse({text:n.text,parcel:t,raw:n.raw}))}function Ux(e,t,n){if(e.kind==="parcel"){let i=t[n.index];return n.index+=1,qs(i)}let o=e.children.map(i=>Ux(i,t,n));return e.kind==="root"?Kc(o):Fu(e.scope,o,e.data)}function T0(e){return e.children.every(t=>t.kind==="parcel")}async function Px(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 Px(y,t,n,o,[...i,`${y.kind}:${w}`]))}let s=e.kind==="root"?Kc(r):Fu(e.scope,r,e.data),a=t==="root"&&s.kind==="root",c=s.kind==="scope"&&s.scope===t;if(!a&&!c||!T0(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("/")}:${zu({items:d,scopeData:p,version:f,salt:o.checkpointSalt})}`,h=zu({step:"reduce",scope:t,version:f,items:d,scopeData:p,salt:o.checkpointSalt}),m=await Qu(o.checkpoint,u,h);if(m.hit)return o.report.reused+=1,qs(Ws(n.validate,m.value));let g=Ws(n.validate,await n.run(d,{scope:p,scopeName:l}));return o.report.ran+=1,await o.checkpoint.write(Ku(u,h,g)),qs(g)}async function Qu(e,t,n){let o=await e.read(t);return o&&o.signature===n?{hit:!0,value:o.value}:{hit:!1}}async function V0(e,t,n){let o={executor:n.executor,signal:n.signal,checkpointSalt:n.checkpointSalt,checkpoint:n.checkpoint??Bu(),concurrency:n.concurrency??4,report:{reused:0,ran:0}},i=null,r=e;for(let a of t){if(a.kind==="split"){i=U0(r,a.spec),r=i;continue}if(i||(i=Kc([qs(r)])),a.kind==="extract"){let c=Hu(i),d=await L0(c,o.concurrency,async p=>{let l=N0(a.task,p.parcel,o),f=zu(l.payload),u=`extract:${p.path.join("/")}:${f}`;if(a.task.kind==="llm"){let g=await Qu(o.checkpoint,u,f);if(g.hit)return o.report.reused+=1,o.executor?.recordReuse(a.task.taskId),Nx(a.task,p.parcel,g.value);let w=l.request??Lx(a.task,p.parcel),y=await C0(a.task,w,o),E=Nx(a.task,p.parcel,y);return o.report.ran+=1,await o.checkpoint.write(Ku(u,f,y)),E}let h=await Qu(o.checkpoint,u,f);if(h.hit)return o.report.reused+=1,Ws(a.task.validate,h.value);let m=await P0(a.task,p.parcel);return o.report.ran+=1,await o.checkpoint.write(Ku(u,f,m)),m});i=Ux(i,d,{index:0}),r=i;continue}i=await Px(i,a.scope,a.task,o,[]),r=i}if(!i)return{value:r,report:o.report};let s=Hu(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 $x={episodeInputMaxChars:6e3,episodeChunkTargetChars:4800,arcEpisodeCount:10,finalMaxInputChars:12e3},$0="\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",D0=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u7247\u6BB5\u6897\u6982","<\u5982\u679C\u5F53\u524D\u96C6\u53EA\u6709\u4E00\u4E2A\u7247\u6BB5\uFF0C\u5199 200-300 \u5B57\uFF1B\u5982\u679C\u5F53\u524D\u96C6\u88AB\u5207\u6210\u591A\u4E2A\u7247\u6BB5\uFF0C\u5199 80-150 \u5B57\u3002\u6309\u53D1\u751F\u987A\u5E8F\u6982\u62EC\uFF0C\u53EA\u5199\u5F53\u524D\u7247\u6BB5\u3002>","","## \u5173\u952E\u4E8B\u4EF6","- <\u4E8B\u4EF61>","- <\u4E8B\u4EF62>","","## \u4EBA\u7269\u53D8\u5316","- <\u4EBA\u7269\u540D> | <\u53D8\u5316>","","## \u7ED3\u5C3E\u94A9\u5B50","<\u6709\u5219\u5199\u4E00\u53E5\uFF1B\u6CA1\u6709\u5219\u7559\u7A7A>"].join(`
|
|
1020
|
+
`),G0="\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",B0=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u5206\u96C6\u6897\u6982","<200-300 \u5B57\uFF0C\u6309\u5267\u60C5\u53D1\u751F\u987A\u5E8F\u5199\u6210\u8FDE\u8D2F\u6BB5\u843D\u3002>","","## \u5355\u53E5\u6897\u6982","<30-50 \u5B57\uFF0C\u6982\u62EC\u672C\u96C6\u4E3B\u7EBF\u3002>","","## \u5173\u952E\u4E8B\u4EF6","- <\u4E8B\u4EF61>","- <\u4E8B\u4EF62>"].join(`
|
|
1021
|
+
`),J0="\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",z0=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u9636\u6BB5\u6897\u6982","<400-600 \u5B57\uFF0C\u6982\u62EC\u8FD9\u4E00\u9636\u6BB5\u7684\u4E3B\u7EBF\u63A8\u8FDB\u3002>","","## \u5173\u952E\u8F6C\u6298","- <\u8F6C\u62981>","- <\u8F6C\u62982>","","## \u672A\u89E3\u51B3\u60AC\u5FF5","- <\u60AC\u5FF51>"].join(`
|
|
1022
|
+
`),K0="\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",j0=["\u8F93\u51FA\u683C\u5F0F\uFF1A\u4E00\u4E2A\u7EAF\u6587\u672C\u7ED3\u6784\u5316\u6587\u6863\u3002\u4E0D\u8981\u5305\u88F9\u4EE3\u7801\u5757\uFF0C\u4E0D\u8981\u5728\u6587\u6863\u524D\u540E\u6DFB\u52A0\u89E3\u91CA\u3002","","## \u5168\u6587\u6897\u6982","<800-1200 \u5B57\uFF0C\u8986\u76D6\u5168\u5267\u4E3B\u7EBF\u3001\u5173\u952E\u5173\u7CFB\u3001\u4E3B\u8981\u51B2\u7A81\u548C\u7ED3\u5C40\u8D70\u5411\u3002>","","## \u4E3B\u9898","<\u4E00\u53E5\u8BDD\u6216\u4E00\u4E2A\u77ED\u8BED>","","## \u4E00\u53E5\u8BDD","<\u4E00\u53E5\u5B8C\u6574 logline>","","## \u98CE\u683C","<\u7C7B\u578B / \u6C14\u8D28 / \u53D9\u4E8B\u98CE\u683C>","","## \u4E3B\u8981\u4EBA\u7269","- <\u540D\u5B57> | <\u89D2\u8272\u5B9A\u4F4D>"].join(`
|
|
1023
|
+
`);function H0(e,t,n){let o=O(t.episode_id).trim()||`ep_${String(n+1).padStart(3,"0")}`,i=cO(o,n),r=O(t.title).trim(),s=[],a=O(e.title).trim();a&&s.push(`\u5267\u540D\uFF1A${a}`),s.push(`\u96C6\u6570\uFF1A\u7B2C${i}\u96C6`),r&&s.push(`\u6807\u9898\uFF1A${r}`),s.push("");for(let c of ce(t.scenes)){s.push(sO(e,c));for(let d of ce(c.actions)){let p=aO(e,d);p&&s.push(p)}s.push("")}return{episodeIndex:n,episodeId:o,episodeNo:i,title:r,existingSynopsis:O(t.synopsis).trim(),text:s.join(`
|
|
1024
|
+
`).trim()}}function Q0(e,t=$x){let n=e.text.split(/\r?\n/),o=n.flatMap(a=>oO(a,t.episodeChunkTargetChars));if(e.text.length<=t.episodeInputMaxChars&&o.length===n.length)return[{episodeIndex:e.episodeIndex,episodeId:e.episodeId,episodeNo:e.episodeNo,title:e.title,part:1,partCount:1,text:e.text,sourceHash:_e(e.text)}];let i=[],r=[],s=0;for(let a of o){let c=a.length+(r.length>0?1:0);r.length>0&&s+c>t.episodeChunkTargetChars&&(i.push(r.join(`
|
|
1018
1025
|
`).trim()),r=[],s=0);let d=a.length+(r.length>0?1:0);r.push(a),s+=d}return r.length>0&&i.push(r.join(`
|
|
1019
|
-
`).trim()),i.map((a,c)=>({episodeIndex:e.episodeIndex,episodeId:e.episodeId,episodeNo:e.episodeNo,title:e.title,part:c+1,partCount:i.length,text:a,sourceHash:_e(a)}))}function
|
|
1020
|
-
`),oneLine:
|
|
1021
|
-
`),turns:
|
|
1022
|
-
`)}function
|
|
1023
|
-
`),data:{op:i?"synopsis.generate":"synopsis.generate.dry-run",changed:i&&m,revision:E,idempotent:_,validation:g,issues:x,script_path:a.artifactLabel,episode_synopses:l.episodeBriefs.map(b=>({episode_id:b.episodeId,title:b.title,synopsis:b.synopsis,one_line:b.oneLine})),config_source:d.configSource,llm_routes:d.usage()}},V]}function
|
|
1024
|
-
`).trim()),o=[]};for(let r of e.split(/\r?\n/)){let s=
|
|
1025
|
-
`)}function
|
|
1026
|
-
`)}function
|
|
1027
|
-
`).trim()}function
|
|
1028
|
-
`).trim()}function
|
|
1029
|
-
`)}function dO(e,t){if(e===null)throw new Error(`${t} scope missing`);return e}function pO(e,t){let n=e[0];if(!n||e.length!==1)throw new Error(`${t} reduce requires exactly one item`);return n}function lO(e){return e.map(t=>t.trim()).find(t=>t.length>0)??""}function Fu(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 uO(e){let t=e.replace(/\s+/g," ").trim();return t.length>50?t.slice(0,50):t}function fO(e,t,n){if(e==null||e==="")return t;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new S(`${n} must be a positive integer.`,{exitCode:B,errorCode:"NUMERIC_OPTION_INVALID",hint:`Pass ${n} ${t}.`,data:{expected:[`${n}: positive integer`],actual:[O(e)]}});return Math.floor(o)}function zc(e,t,n,o){return!o&&O(e[t]).trim()||O(e[t])===n?!1:(e[t]=n,!0)}function mO(e){return!O(e.synopsis).trim()||!O(e.theme).trim()||!O(e.logline).trim()||!O(e.style).trim()||ce(e.main_characters).length===0}function gO(e){return{synopsis:O(e.synopsis).trim(),theme:O(e.theme).trim(),logline:O(e.logline).trim(),style:O(e.style).trim(),mainCharacters:ce(e.main_characters).map(t=>({name:O(t.name).trim(),role:O(t.role).trim()})).filter(t=>t.name&&t.role)}}import*as ii from"node:fs";import*as Jn from"node:path";var jc=["\u7D27\u5F20","\u60AC\u7591","\u6050\u60E7","\u6124\u6012","\u9707\u60CA","\u60B2\u4F24","\u538B\u6291","\u6E29\u60C5","\u751C\u871C","\u6B22\u5FEB","\u71C3\u723D","\u641E\u7B11","\u5E73\u9759"],qu=["\u52A8\u4F5C","\u73AF\u5883","\u7269\u4EF6","\u5F3A\u8C03","\u8F6C\u573A","\u63D0\u793A\u97F3"],Vx=["\u6162","\u4E2D","\u5FEB","\u65E0\u660E\u663E\u8282\u62CD"],$x=["\u5E73\u7A33","\u6E10\u5F3A","\u6E10\u5F31","\u8D77\u4F0F","\u7A81\u8D77","\u9AA4\u505C"];var Hc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xt=e=>typeof e=="string"?e.trim():"",Ji=e=>Math.round(e*10)/10,hO=(e,t,n)=>Math.min(n,Math.max(t,e));function Dx(e,t,n,o){let i=typeof e=="number"?e:Number.NaN;return Number.isFinite(i)?hO(i,t,n):o}function Gr(e){if(typeof e=="number")return Number.isFinite(e)&&e>=0?e:null;if(typeof e!="string")return null;let t=e.trim().match(/^(?:(?:(\d+):)?(\d+):)?(\d+(?:\.\d+)?)$/);return t?Number(t[1]??0)*3600+Number(t[2]??0)*60+Number(t[3]):null}function Re(e){let t=Math.round(e*10),n=Math.floor(t/600),o=(t-n*600)/10;return`${String(n).padStart(2,"0")}:${o.toFixed(1).padStart(4,"0")}`}function Zu(e){return{on_screen:xt(e.on_screen),why:xt(e.why),improve:xt(e.improve)}}function Gx(e){let t=xt(e.audio_emotion);return{source:e.source==="video"?"video":"audio",audio_emotion:jc.includes(t)?t:null}}function Bx(e,t,n){let o=xt(e);return jc.includes(o)?o:(n.push(`${t}: emotion "${o}" is outside the list, kept as \u5176\u4ED6`),"\u5176\u4ED6")}function Jx(e,t,n,o){let i=Gr(e.start),r=Gr(e.end);return i===null?(o.push(`${t}: unreadable start "${String(e.start)}", dropped`),null):i>=n?(o.push(`${t}: start ${i} is past the ${n}s video, dropped`),null):(r!==null&&r>n+1&&o.push(`${t}: end ${r} clamped to the ${n}s video`),{start:Ji(i),end:Ji(Math.min(r??i,n))})}function zx(e,t){let n=[e];for(let o of t)n=n.flatMap(i=>o.end<=i.start||o.start>=i.end?[i]:[...o.start>i.start?[{...i,end:o.start}]:[],...o.end<i.end?[{...i,start:o.end}]:[]]);return n.filter(o=>o.end-o.start>=.3)}function yO(e,t,n,o){let i=[];e.forEach((a,c)=>{let d=`bgm[${c}]`;if(!Hc(a)){o.push(`${d}: not an object, dropped`);return}let p=Jx(a,d,t,o);if(p){if(p.end-p.start<.3){o.push(`${d}: ${p.start}-${p.end} is too short for a music cue, dropped`);return}i.push({id:"",...p,emotion:Bx(a.emotion,d,o),emotion_note:xt(a.emotion_note),intensity:Math.round(Dx(a.intensity,1,5,3)),music:xt(a.music),instruments:Array.isArray(a.instruments)?a.instruments.map(xt).filter(Boolean):[],tempo:xt(a.tempo),dynamics:xt(a.dynamics),...Zu(a),...Gx(a)})}});let r=i.flatMap(a=>{let c=zx(a,n);return(c.length!==1||c[0].start!==a.start||c[0].end!==a.end)&&o.push(`bgm ${Re(a.start)}-${Re(a.end)} crosses measured silence, cut to what can be heard`),c});r.sort((a,c)=>a.start-c.start||a.end-c.end);let s=[];for(let a of r){let c=s[s.length-1];c&&a.start<c.end&&(o.push(`bgm overlap at ${Re(a.start)}: earlier cue ended there`),c.end=a.start,c.end-c.start<.3&&s.pop()),s.push(a)}return s.map((a,c)=>({...a,id:`bgm_${String(c+1).padStart(2,"0")}`}))}function wO(e,t,n,o){let i=[];return e.forEach((r,s)=>{let a=`sfx[${s}]`;if(!Hc(r)){o.push(`${a}: not an object, dropped`);return}let c=Jx(r,a,t,o);if(!c)return;let d=xt(r.label);if(!d){o.push(`${a}: no label, dropped`);return}if(n.some(l=>c.start>=l.start&&c.start<l.end)){o.push(`${a}: "${d}" at ${Re(c.start)} falls in measured silence, dropped`);return}let p=xt(r.category);i.push({id:"",start:c.start,end:Math.max(c.start,c.end),label:d,category:qu.includes(p)?p:"\u5176\u4ED6",emotion:Bx(r.emotion,a,o),intensity:Math.round(Dx(r.intensity,1,5,3)),...Zu(r),...Gx(r)})}),i.sort((r,s)=>r.start-s.start||r.end-s.end),i.map((r,s)=>({...r,id:`sfx_${String(s+1).padStart(2,"0")}`}))}function xO(e,t){let n=[],o=0;for(let i of[...e,{start:t,end:t}])i.start-o>=.5&&n.push({start:Ji(o),end:Ji(i.start)}),o=Math.max(o,i.end);return n}function Tx(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return[...t].map(([n,o])=>({key:n,count:o})).sort((n,o)=>o.count-n.count)}function EO(e,t,n){let o=new Map,i=0;for(let s of e){let a=s.end-s.start;i+=a,o.set(s.emotion,(o.get(s.emotion)??0)+a)}let r=s=>n>0?Math.round(s/n*1e3)/1e3:0;return{bgm_seconds:Ji(i),no_bgm_seconds:Ji(Math.max(0,n-i)),bgm_coverage:r(i),bgm_by_emotion:[...o].map(([s,a])=>({emotion:s,seconds:Ji(a),share:r(a)})).sort((s,a)=>a.seconds-s.seconds),sfx_by_emotion:Tx(t.map(s=>s.emotion)).map(({key:s,count:a})=>({emotion:s,count:a})),sfx_by_category:Tx(t.map(s=>s.category)).map(({key:s,count:a})=>({category:s,count:a}))}}function Wu(e){return Hc(e)&&Array.isArray(e.bgm)&&Array.isArray(e.sfx)}function Qc(e,t,n=[]){let o=[],i=yO(e.bgm,t,n,o),r=wO(e.sfx,t,n,o);return{summary:xt(e.summary),advice:xt(e.advice),bgm:i,sfx:r,gaps:xO(i,t),distribution:EO(i,r,t),warnings:o}}function Kx(e){return Wu(e)}function Yu(e){return Array.isArray(e)?e.filter(Hc):[]}function _O(e,t){if(t.length===0)return[{start:e.start,end:e.end,entry:null}];let n=c=>c!==null&&c>e.start&&c<e.end,o=t.map(c=>({entry:c,at:Gr(c.start)})).sort((c,d)=>(c.at??0)-(d.at??0)),[i,...r]=o,s=r.filter(c=>n(c.at)),a=[e.start,...s.map(c=>c.at)];return[i,...s].map((c,d)=>({start:a[d],end:a[d+1]??e.end,entry:c.entry}))}function jx(e,t,n,o=[]){let i=[...e.warnings],r=(f,u)=>{let h=Yu(f).filter(m=>xt(m.id)===u);return h.length===0&&i.push(`${u}: the video pass left no notes`),h},s=(f,u)=>({...f,emotion:u?.emotion??f.emotion,...u?.emotion_note===void 0?{}:{emotion_note:u.emotion_note},...Zu(u??{}),audio_emotion:f.emotion,source:"audio"}),a=e.bgm.flatMap(f=>_O(f,r(t.bgm,f.id)).map(({start:u,end:h,entry:m})=>({...s(f,m),start:u,end:h}))),c=e.sfx.map(f=>s(f,r(t.sfx,f.id)[0]??null)),d=Yu(t.extra_bgm).flatMap(f=>{let u=Gr(f.start),h=Gr(f.end);return u===null||h===null?[]:zx({...f,start:u,end:h,source:"video"},e.bgm)}),p=Yu(t.extra_sfx).flatMap(f=>{let u=Gr(f.start);return u===null||e.sfx.some(h=>Math.abs(h.start-u)<=1)?[]:[{...f,source:"video"}]}),l=Qc({summary:t.summary,advice:t.advice,bgm:[...a,...d],sfx:[...c,...p]},n,o);return{...l,warnings:[...i,...l.warnings]}}var Hx=e=>Math.max(-90,10*Math.log10(e+1e-12)),Zs=e=>Math.round(e*10)/10;function Fx(e,t=16e3){let n=Math.round(t*.05),o=Math.floor(e.length/n),i=new Float64Array(o);for(let d=0;d<o;d+=1){let p=0;for(let l=d*n;l<(d+1)*n;l+=1)p+=e[l]*e[l];i[d]=p/n}let r=Math.round(.25/.05),s=Math.round(2/.05/2),a=[],c=[];for(let d=0;d<o;d+=r){let p=0,l=Math.min(o,d+r);for(let h=d;h<l;h+=1)p+=i[h];a.push(Zs(Hx(p/(l-d))));let f=d+Math.floor(r/2),u=Array.from(i.subarray(Math.max(0,f-s),Math.min(o,f+s))).sort((h,m)=>h-m);c.push(Zs(Hx(u[Math.floor(u.length*.1)]??0)))}return{step_seconds:.25,level_db:a,bed_db:c}}function Yx(e){let t=[],n=null;return e.level_db.forEach((o,i)=>{let r=o<-60;r&&n===null&&(n=i);let s=i===e.level_db.length-1;if(n!==null&&(!r||s)){let a=r?i+1:i;(a-n)*e.step_seconds>=1&&t.push({start:Zs(n*e.step_seconds),end:Zs(a*e.step_seconds)}),n=null}}),t}function Qx(e,t){let n=Math.floor(t.start/e.step_seconds),o=Math.max(n+1,Math.ceil(t.end/e.step_seconds)),i=e.bed_db.slice(n,o);return i.length===0?-90:Zs(i.reduce((r,s)=>r+s,0)/i.length)}function SO(e){return e.length===0?null:[...e].sort((t,n)=>t-n)[Math.floor(e.length/2)]}function Xu(e,t,n){let o=e.map(s=>{let a=Qx(n,s);return{id:s.id,bed_db:a,silent_bed:a<-55}}),i=SO(o.map(s=>s.bed_db)),r=t.filter(s=>s.end-s.start>=2).map(s=>{let a=Qx(n,s);return{...s,bed_db:a,loud_bed:i!==null&&a>=i-6}});return{bgm:o,gaps:r}}import{spawn as IO}from"node:child_process";import*as Fc from"node:fs";import*as Zx from"node:path";var AO="scale='if(gt(a,1),min(640,iw),-2)':'if(gt(a,1),-2,min(640,ih))'";function ef(e,t,n){return new Promise((o,i)=>{let r=IO(e,t,{stdio:["ignore","pipe","pipe"],...n?{signal:n}:{}}),s=[],a="";r.stdout.on("data",c=>s.push(c)),r.stderr.on("data",c=>{a+=String(c)}),r.on("error",c=>{if(c.code!=="ENOENT"){i(c);return}i(new S(`${e} was not found on PATH.`,{exitCode:k,errorCode:"SOUNDTRACK_FFMPEG_MISSING",hint:"Install ffmpeg (it provides ffprobe too) and make sure both are on PATH.",data:{expected:[`${e} on PATH`]}}))}),r.on("close",c=>{if(c===0){o(Buffer.concat(s));return}i(new S(`${e} exited with code ${c}.`,{exitCode:q,errorCode:"SOUNDTRACK_MEDIA_FAILED",data:{actual:[a.trim().slice(0,300)]}}))})})}async function qx(e,t,n,o){Fc.mkdirSync(Zx.dirname(t),{recursive:!0});let i=`${t}.part`;await ef("ffmpeg",["-y","-v","error","-i",e,...n,"-c:a","aac","-b:a","128k","-movflags","+faststart","-f","mp4",i],o),Fc.renameSync(i,t)}var Wx={async probe(e,t){let n=await ef("ffprobe",["-v","error","-show_entries","format=duration:stream=codec_type","-of","json",e],t),o=JSON.parse(n.toString("utf-8"));return{durationSeconds:Number(o.format?.duration??0),hasAudio:(o.streams??[]).some(i=>i.codec_type==="audio")}},async decodeMono(e,t,n){let o=await ef("ffmpeg",["-v","error","-i",e,"-vn","-ac","1","-ar",String(t),"-f","f32le","-"],n),i=new Float32Array(Math.floor(o.length/4));for(let r=0;r<i.length;r+=1)i[r]=o.readFloatLE(r*4);return i},async makePreview(e,t,n){await qx(e,t,["-vf",AO,"-c:v","libx264","-preset","veryfast","-crf","30","-pix_fmt","yuv420p"],n)},async extractAudio(e,t,n){await qx(e,t,["-vn"],n)}};var W=Sn;function Sn(e,t){e=e-0;let n=nf(),o=n[e];if(Sn.DupkkL===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.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.nVmIem=i,Sn.NjHzYT={},Sn.DupkkL=!0}let r=n[0];Sn.XuEcNo!==r&&(Sn.NjHzYT={},Sn.XuEcNo=r);let s=Sn.NjHzYT[e];return s===void 0?(o=Sn.nVmIem(o),Sn.NjHzYT[e]=o):o=s,o}var Br={type:W(53),description:W(1)},qc={type:W(53),enum:[...jc]},tE={type:W(16),minimum:1,maximum:5},Xx={type:W(53),description:W(42)},eE={type:W(53),description:W(19)},kO={type:W(53),description:W(57)},bO={type:W(53),description:W(23)},vO={type:W(53),description:W(7)},OO=3,RO=1,MO={temperature:0,seed:1},nE={start:Br,end:Br,emotion:qc,intensity:tE,music:{type:W(53),description:W(37)},instruments:{type:W(24),items:{type:W(53)}},tempo:{type:W(53),enum:[...Vx]},dynamics:{type:W(53),enum:[...$x]}},oE={start:Br,end:Br,label:{type:W(53),description:W(25)},category:{type:W(53),enum:[...qu]},emotion:qc,intensity:tE},Yc={on_screen:kO,why:bO,improve:vO};function ni(e){let t=W;return{type:t(13),additionalProperties:!1,required:Object[t(44)](e),properties:e}}var NO=ni({bgm:{type:W(24),items:ni(nE)},sfx:{type:W(24),items:ni(oE)}}),LO=ni({summary:{type:W(53),description:W(28)},advice:{type:W(53),description:W(46)},bgm:{type:W(24),items:ni({id:Xx,start:Br,end:Br,emotion:qc,emotion_note:eE,...Yc})},sfx:{type:W(24),items:ni({id:Xx,emotion:qc,...Yc})},extra_bgm:{type:W(24),items:ni({...nE,emotion_note:eE,...Yc})},extra_sfx:{type:W(24),items:ni({...oE,...Yc})}}),UO=W(14),PO=W(29);function tf(e){let t=W;return e[t(56)]>e[t(32)]?Re(e[t(32)])+"\u2013"+Re(e[t(56)]):Re(e[t(32)])}function CO(e,t){let n=W;return n(17)+e+n(11)+Re(t)+n(5)}function TO(e,t,n,o){let i=W,r=n[i(27)][i(38)](a=>a.id+" "+tf(a)+" "+a[i(3)]+i(8)+a[i(18)]+"\uFF1A"+a[i(0)]),s=n[i(6)][i(38)](a=>a.id+" "+tf(a)+" "+a[i(3)]+i(8)+a[i(18)]+"\uFF1A"+a[i(49)]+"\uFF08"+a[i(35)]+"\uFF09");return[i(17)+e+i(52)+Re(t)+i(47),"",i(39),...r[i(21)]?r:[i(60)],"",i(41),...s[i(21)]?s:[i(60)],...o[i(21)]?["",i(10),...o[i(38)](tf)]:[]][i(33)](`
|
|
1030
|
-
`)}async function
|
|
1026
|
+
`).trim()),i.map((a,c)=>({episodeIndex:e.episodeIndex,episodeId:e.episodeId,episodeNo:e.episodeNo,title:e.title,part:c+1,partCount:i.length,text:a,sourceHash:_e(a)}))}function F0(e,t){let n=Qc(e);return{episodeIndex:t.episodeIndex,episodeId:t.episodeId,episodeNo:t.episodeNo,title:t.title,part:t.part,partCount:t.partCount,synopsis:yo(n,"\u7247\u6BB5\u6897\u6982"),events:Gr(n.get("\u5173\u952E\u4E8B\u4EF6")??""),characterChanges:lO(n.get("\u4EBA\u7269\u53D8\u5316")??""),hook:(n.get("\u7ED3\u5C3E\u94A9\u5B50")??"").trim()}}function Y0(e,t){let n=wO(t.scope,"episode"),o=[...e].sort((i,r)=>i.part-r.part);return{episodeIndex:n.episodeIndex,episodeId:n.episodeId,episodeNo:n.episodeNo,title:n.title,synopsis:o.map(i=>i.synopsis).filter(i=>i.trim()).join(`
|
|
1027
|
+
`),oneLine:EO(o.map(i=>i.synopsis)),events:Wu(o.flatMap(i=>i.events))}}function q0(e,t){let n=Qc(e);return{episodeIndex:t.episodeIndex,episodeId:t.episodeId,episodeNo:t.episodeNo,title:t.title,synopsis:yo(n,"\u5206\u96C6\u6897\u6982"),oneLine:yo(n,"\u5355\u53E5\u6897\u6982"),events:Gr(n.get("\u5173\u952E\u4E8B\u4EF6")??"")}}function W0(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:gO(i)})}return n}function Z0(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:hO(i)})}return n}function X0(e,t){let n=Qc(e);return{index:t.index,startEpisodeNo:t.startEpisodeNo,endEpisodeNo:t.endEpisodeNo,synopsis:yo(n,"\u9636\u6BB5\u6897\u6982"),turns:Gr(n.get("\u5173\u952E\u8F6C\u6298")??""),openQuestions:Gr(n.get("\u672A\u89E3\u51B3\u60AC\u5FF5")??"")}}function eO(e){let t=[...e].sort((i,r)=>i.startEpisodeNo-r.startEpisodeNo),n=t[0],o=t[t.length-1];if(!n||!o)throw new Error("arc reduce requires at least one item");return{index:n.index,startEpisodeNo:n.startEpisodeNo,endEpisodeNo:o.endEpisodeNo,synopsis:t.map(i=>`\u7B2C${i.startEpisodeNo}-${i.endEpisodeNo}\u96C6\uFF1A${i.synopsis}`).join(`
|
|
1028
|
+
`),turns:Wu(t.flatMap(i=>i.turns)),openQuestions:Wu(t.flatMap(i=>i.openQuestions))}}function Yu(e,t){let n=["\u5206\u96C6\u7D22\u5F15\uFF1A"];for(let o of[...e].sort((i,r)=>i.episodeNo-r.episodeNo))n.push(`\u7B2C${o.episodeNo}\u96C6\uFF1A${o.oneLine||o.synopsis}`);n.push("","\u9636\u6BB5\u6897\u6982\uFF1A");for(let o of[...t].sort((i,r)=>i.startEpisodeNo-r.startEpisodeNo))n.push(`\u7B2C${o.startEpisodeNo}-${o.endEpisodeNo}\u96C6\uFF1A${o.synopsis}`);return n.join(`
|
|
1029
|
+
`)}function tO(e){let t=Qc(e);return{synopsis:yo(t,"\u5168\u6587\u6897\u6982"),theme:yo(t,"\u4E3B\u9898"),logline:yo(t,"\u4E00\u53E5\u8BDD"),style:yo(t,"\u98CE\u683C"),mainCharacters:uO(yo(t,"\u4E3B\u8981\u4EBA\u7269"))}}async function nO(e){let t=e.config??$x,n=ce(e.script.episodes);if(n.length===0)throw new S("No episodes found in script.",{exitCode:B,errorCode:"SCRIPT_EPISODES_MISSING",hint:"Create or parse episodes before generating synopsis.",data:{expected:["script.episodes[] with at least one episode"],actual:["episodes: 0"]}});let o=n.map((u,h)=>H0(e.script,u,h)),i=e.overwrite?o:o.filter(u=>!u.existingSynopsis),r=i.length===0?[]:await jc(e.script).split({scope:"episode",partition:()=>i,chunk:u=>Q0(u,t)}).extract(Zs({taskId:"synopsis.chunk",instruction:$0,format:D0,input:({parcel:u})=>fO(u),parse:({text:u,parcel:h})=>F0(u,h)})).reduce("episode",Y0).extract(Zs({taskId:"synopsis.episode",instruction:G0,format:B0,input:({parcel:u})=>mO(u),parse:({text:u,parcel:h})=>q0(u,h)})).reduce("root",u=>[...u].sort((h,m)=>h.episodeNo-m.episodeNo)).run({concurrency:e.concurrency,checkpoint:Ys(Dr.join(e.checkpointDir,"episode")),checkpointSalt:e.checkpointSalt,executor:e.executor}),s=Array.isArray(r)?r:r.value,a=new Map(s.map(u=>[u.episodeIndex,u])),c=o.map(u=>a.get(u.episodeIndex)??{episodeIndex:u.episodeIndex,episodeId:u.episodeId,episodeNo:u.episodeNo,title:u.title,synopsis:u.existingSynopsis,oneLine:_O(u.existingSynopsis),events:[]}),d=c.filter(u=>!u.synopsis.trim()).map(u=>u.episodeId);if(d.length>0)throw new S("Some episode synopses are still missing.",{exitCode:q,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||IO(e.script),l=p?await iO({episodes:c,executor:e.executor,checkpointDir:Dr.join(e.checkpointDir,"arc"),checkpointSalt:e.checkpointSalt,concurrency:e.concurrency,config:t}):{value:[],report:{reused:0,ran:0}},f=p?await rO({episodes:c,arcs:l.value,executor:e.executor,checkpointDir:Dr.join(e.checkpointDir,"final"),checkpointSalt:e.checkpointSalt,config:t}):{value:AO(e.script),report:{reused:0,ran:0}};return{episodeBriefs:c,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 Dx(e,t=pn){let n=SO(e.concurrency,Sf,"--concurrency"),o=!!e.overwrite,i=!!e.apply,r=!!e.dry_run;if(i&&r)throw new S("--apply and --dry-run are mutually exclusive.",{exitCode:B,errorCode:"SYNOPSIS_GENERATE_FLAG_CONFLICT",hint:"Pick one mode and retry.",data:{expected:["at most one of --apply / --dry-run"],actual:["--apply","--dry-run"]}});let s=O(e.workspace_path||"workspace"),a=await Hs(e),c=O(e.model).trim(),d=t.createExecutor(O(e.llm_config).trim()||void 0,c?{profile:c}:void 0),p=O(e.checkpoint).trim()||Dr.join(kf(s),"loom","synopsis-generate"),l=await nO({script:a.script,executor:d,checkpointDir:p,concurrency:n,overwrite:o}),f=new Set,u=ce(a.script.episodes);for(let b of l.episodeBriefs){let U=u[b.episodeIndex];U&&(o||!O(U.synopsis).trim())&&O(U.synopsis)!==b.synopsis&&(U.synopsis=b.synopsis,f.add(b.episodeId))}let h=!1;if(h=Hc(a.script,"synopsis",l.overview.synopsis,o)||h,h=Hc(a.script,"theme",l.overview.theme,o)||h,h=Hc(a.script,"logline",l.overview.logline,o)||h,h=Hc(a.script,"style",l.overview.style,o)||h,o||ce(a.script.main_characters).length===0){let b=l.overview.mainCharacters.map(U=>({name:U.name,role:U.role}));JSON.stringify(a.script.main_characters??[])!==JSON.stringify(b)&&(a.script.main_characters=b,h=!0)}let m=f.size>0||h,g=Qs(a),w=!!g.passed,y=[`${l.episodeBriefs.length} episodes; ${f.size} synopses ${i?"written":"would change"}; overview ${l.overviewGenerated?"generated":"reused"}; validation ${w?i?"passed":"would pass":i?"needs repair":"would need repair"}${i?"":"; dry-run, no write"}`,`loom: ran=${l.report.ran}, reused=${l.report.reused}`,`llm config: ${d.configSource}; routes: ${d.usage().length}`],E,_;i&&m&&([E,_]=await Uu(a,e,"synopsis.generate"),await Lu(a,g,E),a.remote&&y.push(`revision ${E}; idempotent ${String(_).toLowerCase()}`));let x=ap(ce(g.issues));return i||y.push("Run again with --apply to write the generated synopsis fields."),[{text:[...y,...x].join(`
|
|
1030
|
+
`),data:{op:i?"synopsis.generate":"synopsis.generate.dry-run",changed:i&&m,revision:E,idempotent:_,validation:g,issues:x,script_path:a.artifactLabel,episode_synopses:l.episodeBriefs.map(b=>({episode_id:b.episodeId,title:b.title,synopsis:b.synopsis,one_line:b.oneLine})),config_source:d.configSource,llm_routes:d.usage()}},V]}function oO(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 iO(e){let t=W0(e.episodes,e.config.arcEpisodeCount),n=1,o={reused:0,ran:0};for(;;){let i=await jc(t).split({scope:"arc",partition:a=>a,chunk:a=>[a]}).extract(Zs({taskId:"synopsis.arc",instruction:J0,format:z0,input:({parcel:a})=>yO(a),parse:({text:a,parcel:c})=>X0(a,c)})).reduce("arc",a=>xO(a,"arc")).reduce("root",a=>[...a].sort((c,d)=>c.startEpisodeNo-d.startEpisodeNo)).run({concurrency:e.concurrency,checkpoint:Ys(Dr.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(Yu(e.episodes,r).length<=e.config.finalMaxInputChars||r.length<=1)return{value:r,report:o};t=Z0(r,e.config.arcEpisodeCount),n+=1}}async function rO(e){let t=e.arcs;for(;Yu(e.episodes,t).length>e.config.finalMaxInputChars&&t.length>1;)t=[eO(t)];let n=await jc({episodes:e.episodes,arcs:t}).extract(Zs({taskId:"synopsis.script-overview",instruction:K0,format:j0,input:({parcel:o})=>Yu(o.episodes,o.arcs),parse:({text:o})=>tO(o)})).run({concurrency:1,checkpoint:Ys(e.checkpointDir),checkpointSalt:e.checkpointSalt,executor:e.executor});return{value:n.value,report:n.report}}function sO(e,t){let n=ie(t.environment)?t.environment:{},o=O(n.space).trim(),i=O(n.time).trim(),r=ni(t),s=ce(r.locations).map(p=>qu(e,"locations","location_id","location_name",O(p.location_id))).filter(p=>p),a=ce(r.actors).map(p=>qu(e,"actors","actor_id","actor_name",O(p.actor_id))).filter(p=>p),c=s.join("\u3001")||"-";return`[\u573A\u666F] ${[o,i].filter(p=>p).join(" ")||"-"}\uFF5C${c}\uFF5C\u51FA\u573A\uFF1A${a.join("\u3001")||"-"}`}function aO(e,t){let n=O(t.type).trim();if(n==="dialogue"){let i=Cx(e,t),r=O(t.content).trim();return r?`[\u5BF9\u767D] ${i?`${i}\uFF1A`:""}${r}`:""}if(n==="inner_thought"){let i=Cx(e,t),r=O(t.content).trim();return r?`[\u5FC3\u58F0] ${i?`${i}\uFF1A`:""}${r}`:""}let o=O(t.content).trim();return o?`[\u52A8\u4F5C] ${o}`:""}function Cx(e,t){let n=t.speaker;if(!ie(n))return"";let o=O(n.actor_id).trim();if(o)return qu(e,"actors","actor_id","actor_name",o)||o;let i=O(n.kind).trim();return i?O(n.label).trim()||i:""}function qu(e,t,n,o,i){let r=ce(e[t]).find(s=>O(s[n])===i);return r?O(r[o]).trim():""}function cO(e,t){let n=/^ep_(\d+)$/.exec(e);return n?Number(n[1]):t+1}function Qc(e){let t=new Map,n=null,o=[],i=()=>{n&&t.set(n,o.join(`
|
|
1031
|
+
`).trim()),o=[]};for(let r of e.split(/\r?\n/)){let s=dO(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 Tx=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 dO(e){let t=e.trim(),n=/^#{1,6}\s+(.+?)\s*$/.exec(t);if(n){let r=Vx(n[1].trim());return Tx.has(r)?{name:r,inline:""}:null}let o=t.search(/[::]/),i=Vx((o>=0?t.slice(0,o):t).trim());return Tx.has(i)?{name:i,inline:o>=0?t.slice(o+1).trim():""}:null}var pO={\u95DC\u9375\u4E8B\u4EF6:"\u5173\u952E\u4E8B\u4EF6",\u4EBA\u7269\u8B8A\u5316:"\u4EBA\u7269\u53D8\u5316",\u7D50\u5C3E\u9264\u5B50:"\u7ED3\u5C3E\u94A9\u5B50",\u55AE\u53E5\u6897\u6982:"\u5355\u53E5\u6897\u6982",\u968E\u6BB5\u6897\u6982:"\u9636\u6BB5\u6897\u6982",\u95DC\u9375\u8F49\u6298:"\u5173\u952E\u8F6C\u6298",\u672A\u89E3\u6C7A\u61F8\u5FF5:"\u672A\u89E3\u51B3\u60AC\u5FF5",\u4E3B\u984C:"\u4E3B\u9898",\u4E00\u53E5\u8A71:"\u4E00\u53E5\u8BDD",\u98A8\u683C:"\u98CE\u683C"};function Vx(e){return pO[e]??e}function yo(e,t){let n=(e.get(t)??"").trim();if(!n)throw new Error(`synopsis output missing section: ${t}`);return n}function Gr(e){return e.split(/\r?\n/).map(t=>t.trim()).map(t=>t.replace(/^[-*]\s*/,"").trim()).filter(t=>t.length>0)}function lO(e){return Gr(e).map(t=>{let[n,...o]=t.split("|");return{name:O(n).trim(),change:o.join("|").trim()}}).filter(t=>t.name&&t.change)}function uO(e){return Gr(e).map(t=>{let[n,...o]=t.split("|");return{name:O(n).trim(),role:o.join("|").trim()}}).filter(t=>t.name&&t.role)}function fO(e){return[`\u5F53\u524D\u5206\u96C6\uFF1A\u7B2C${e.episodeNo}\u96C6 ${e.title||""}`.trim(),`\u5F53\u524D\u7247\u6BB5\uFF1A${e.part}/${e.partCount}`,"","\u8FD9\u662F\u5F53\u524D\u4EFB\u52A1\u7684\u539F\u6587\uFF1A",e.text].join(`
|
|
1032
|
+
`)}function mO(e){return[`\u5F53\u524D\u5206\u96C6\uFF1A\u7B2C${e.episodeNo}\u96C6 ${e.title||""}`.trim(),"","\u7247\u6BB5\u6897\u6982\uFF1A",e.synopsis,"","\u7247\u6BB5\u5173\u952E\u4E8B\u4EF6\uFF1A",...e.events.map(t=>`- ${t}`)].join(`
|
|
1033
|
+
`)}function gO(e){let t=[];for(let n of e){if(t.push(`\u7B2C${n.episodeNo}\u96C6 ${n.title||""}`.trim()),t.push(`\u5355\u53E5\uFF1A${n.oneLine}`),t.push(`\u6897\u6982\uFF1A${n.synopsis}`),n.events.length>0){t.push("\u5173\u952E\u4E8B\u4EF6\uFF1A");for(let o of n.events)t.push(`- ${o}`)}t.push("")}return t.join(`
|
|
1034
|
+
`).trim()}function hO(e){let t=[];for(let n of e){if(t.push(`\u7B2C${n.startEpisodeNo}-${n.endEpisodeNo}\u96C6`),t.push(`\u9636\u6BB5\u6897\u6982\uFF1A${n.synopsis}`),n.turns.length>0){t.push("\u5173\u952E\u8F6C\u6298\uFF1A");for(let o of n.turns)t.push(`- ${o}`)}if(n.openQuestions.length>0){t.push("\u672A\u89E3\u51B3\u60AC\u5FF5\uFF1A");for(let o of n.openQuestions)t.push(`- ${o}`)}t.push("")}return t.join(`
|
|
1035
|
+
`).trim()}function yO(e){return[`\u5F53\u524D\u9636\u6BB5\uFF1A\u7B2C${e.startEpisodeNo}-${e.endEpisodeNo}\u96C6`,"","\u5206\u96C6\u6897\u6982\uFF1A",e.text].join(`
|
|
1036
|
+
`)}function wO(e,t){if(e===null)throw new Error(`${t} scope missing`);return e}function xO(e,t){let n=e[0];if(!n||e.length!==1)throw new Error(`${t} reduce requires exactly one item`);return n}function EO(e){return e.map(t=>t.trim()).find(t=>t.length>0)??""}function Wu(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 _O(e){let t=e.replace(/\s+/g," ").trim();return t.length>50?t.slice(0,50):t}function SO(e,t,n){if(e==null||e==="")return t;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new S(`${n} must be a positive integer.`,{exitCode:B,errorCode:"NUMERIC_OPTION_INVALID",hint:`Pass ${n} ${t}.`,data:{expected:[`${n}: positive integer`],actual:[O(e)]}});return Math.floor(o)}function Hc(e,t,n,o){return!o&&O(e[t]).trim()||O(e[t])===n?!1:(e[t]=n,!0)}function IO(e){return!O(e.synopsis).trim()||!O(e.theme).trim()||!O(e.logline).trim()||!O(e.style).trim()||ce(e.main_characters).length===0}function AO(e){return{synopsis:O(e.synopsis).trim(),theme:O(e.theme).trim(),logline:O(e.logline).trim(),style:O(e.style).trim(),mainCharacters:ce(e.main_characters).map(t=>({name:O(t.name).trim(),role:O(t.role).trim()})).filter(t=>t.name&&t.role)}}import*as ri from"node:fs";import*as Jn from"node:path";var Fc=["\u7D27\u5F20","\u60AC\u7591","\u6050\u60E7","\u6124\u6012","\u9707\u60CA","\u60B2\u4F24","\u538B\u6291","\u6E29\u60C5","\u751C\u871C","\u6B22\u5FEB","\u71C3\u723D","\u641E\u7B11","\u5E73\u9759"],Xu=["\u52A8\u4F5C","\u73AF\u5883","\u7269\u4EF6","\u5F3A\u8C03","\u8F6C\u573A","\u63D0\u793A\u97F3"],Bx=["\u6162","\u4E2D","\u5FEB","\u65E0\u660E\u663E\u8282\u62CD"],Jx=["\u5E73\u7A33","\u6E10\u5F3A","\u6E10\u5F31","\u8D77\u4F0F","\u7A81\u8D77","\u9AA4\u505C"];var Yc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),xt=e=>typeof e=="string"?e.trim():"",zi=e=>Math.round(e*10)/10,kO=(e,t,n)=>Math.min(n,Math.max(t,e));function zx(e,t,n,o){let i=typeof e=="number"?e:Number.NaN;return Number.isFinite(i)?kO(i,t,n):o}function Br(e){if(typeof e=="number")return Number.isFinite(e)&&e>=0?e:null;if(typeof e!="string")return null;let t=e.trim().match(/^(?:(?:(\d+):)?(\d+):)?(\d+(?:\.\d+)?)$/);return t?Number(t[1]??0)*3600+Number(t[2]??0)*60+Number(t[3]):null}function Re(e){let t=Math.round(e*10),n=Math.floor(t/600),o=(t-n*600)/10;return`${String(n).padStart(2,"0")}:${o.toFixed(1).padStart(4,"0")}`}function ef(e){return{on_screen:xt(e.on_screen),why:xt(e.why),improve:xt(e.improve)}}function Kx(e){let t=xt(e.audio_emotion);return{source:e.source==="video"?"video":"audio",audio_emotion:Fc.includes(t)?t:null}}function jx(e,t,n){let o=xt(e);return Fc.includes(o)?o:(n.push(`${t}: emotion "${o}" is outside the list, kept as \u5176\u4ED6`),"\u5176\u4ED6")}function Hx(e,t,n,o){let i=Br(e.start),r=Br(e.end);return i===null?(o.push(`${t}: unreadable start "${String(e.start)}", dropped`),null):i>=n?(o.push(`${t}: start ${i} is past the ${n}s video, dropped`),null):(r!==null&&r>n+1&&o.push(`${t}: end ${r} clamped to the ${n}s video`),{start:zi(i),end:zi(Math.min(r??i,n))})}function Qx(e,t){let n=[e];for(let o of t)n=n.flatMap(i=>o.end<=i.start||o.start>=i.end?[i]:[...o.start>i.start?[{...i,end:o.start}]:[],...o.end<i.end?[{...i,start:o.end}]:[]]);return n.filter(o=>o.end-o.start>=.3)}function bO(e,t,n,o){let i=[];e.forEach((a,c)=>{let d=`bgm[${c}]`;if(!Yc(a)){o.push(`${d}: not an object, dropped`);return}let p=Hx(a,d,t,o);if(p){if(p.end-p.start<.3){o.push(`${d}: ${p.start}-${p.end} is too short for a music cue, dropped`);return}i.push({id:"",...p,emotion:jx(a.emotion,d,o),emotion_note:xt(a.emotion_note),intensity:Math.round(zx(a.intensity,1,5,3)),music:xt(a.music),instruments:Array.isArray(a.instruments)?a.instruments.map(xt).filter(Boolean):[],tempo:xt(a.tempo),dynamics:xt(a.dynamics),...ef(a),...Kx(a)})}});let r=i.flatMap(a=>{let c=Qx(a,n);return(c.length!==1||c[0].start!==a.start||c[0].end!==a.end)&&o.push(`bgm ${Re(a.start)}-${Re(a.end)} crosses measured silence, cut to what can be heard`),c});r.sort((a,c)=>a.start-c.start||a.end-c.end);let s=[];for(let a of r){let c=s[s.length-1];c&&a.start<c.end&&(o.push(`bgm overlap at ${Re(a.start)}: earlier cue ended there`),c.end=a.start,c.end-c.start<.3&&s.pop()),s.push(a)}return s.map((a,c)=>({...a,id:`bgm_${String(c+1).padStart(2,"0")}`}))}function vO(e,t,n,o){let i=[];return e.forEach((r,s)=>{let a=`sfx[${s}]`;if(!Yc(r)){o.push(`${a}: not an object, dropped`);return}let c=Hx(r,a,t,o);if(!c)return;let d=xt(r.label);if(!d){o.push(`${a}: no label, dropped`);return}if(n.some(l=>c.start>=l.start&&c.start<l.end)){o.push(`${a}: "${d}" at ${Re(c.start)} falls in measured silence, dropped`);return}let p=xt(r.category);i.push({id:"",start:c.start,end:Math.max(c.start,c.end),label:d,category:Xu.includes(p)?p:"\u5176\u4ED6",emotion:jx(r.emotion,a,o),intensity:Math.round(zx(r.intensity,1,5,3)),...ef(r),...Kx(r)})}),i.sort((r,s)=>r.start-s.start||r.end-s.end),i.map((r,s)=>({...r,id:`sfx_${String(s+1).padStart(2,"0")}`}))}function OO(e,t){let n=[],o=0;for(let i of[...e,{start:t,end:t}])i.start-o>=.5&&n.push({start:zi(o),end:zi(i.start)}),o=Math.max(o,i.end);return n}function Gx(e){let t=new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return[...t].map(([n,o])=>({key:n,count:o})).sort((n,o)=>o.count-n.count)}function RO(e,t,n){let o=new Map,i=0;for(let s of e){let a=s.end-s.start;i+=a,o.set(s.emotion,(o.get(s.emotion)??0)+a)}let r=s=>n>0?Math.round(s/n*1e3)/1e3:0;return{bgm_seconds:zi(i),no_bgm_seconds:zi(Math.max(0,n-i)),bgm_coverage:r(i),bgm_by_emotion:[...o].map(([s,a])=>({emotion:s,seconds:zi(a),share:r(a)})).sort((s,a)=>a.seconds-s.seconds),sfx_by_emotion:Gx(t.map(s=>s.emotion)).map(({key:s,count:a})=>({emotion:s,count:a})),sfx_by_category:Gx(t.map(s=>s.category)).map(({key:s,count:a})=>({category:s,count:a}))}}function tf(e){return Yc(e)&&Array.isArray(e.bgm)&&Array.isArray(e.sfx)}function qc(e,t,n=[]){let o=[],i=bO(e.bgm,t,n,o),r=vO(e.sfx,t,n,o);return{summary:xt(e.summary),advice:xt(e.advice),bgm:i,sfx:r,gaps:OO(i,t),distribution:RO(i,r,t),warnings:o}}function Fx(e){return tf(e)}function Zu(e){return Array.isArray(e)?e.filter(Yc):[]}function MO(e,t){if(t.length===0)return[{start:e.start,end:e.end,entry:null}];let n=c=>c!==null&&c>e.start&&c<e.end,o=t.map(c=>({entry:c,at:Br(c.start)})).sort((c,d)=>(c.at??0)-(d.at??0)),[i,...r]=o,s=r.filter(c=>n(c.at)),a=[e.start,...s.map(c=>c.at)];return[i,...s].map((c,d)=>({start:a[d],end:a[d+1]??e.end,entry:c.entry}))}function Yx(e,t,n,o=[]){let i=[...e.warnings],r=(f,u)=>{let h=Zu(f).filter(m=>xt(m.id)===u);return h.length===0&&i.push(`${u}: the video pass left no notes`),h},s=(f,u)=>({...f,emotion:u?.emotion??f.emotion,...u?.emotion_note===void 0?{}:{emotion_note:u.emotion_note},...ef(u??{}),audio_emotion:f.emotion,source:"audio"}),a=e.bgm.flatMap(f=>MO(f,r(t.bgm,f.id)).map(({start:u,end:h,entry:m})=>({...s(f,m),start:u,end:h}))),c=e.sfx.map(f=>s(f,r(t.sfx,f.id)[0]??null)),d=Zu(t.extra_bgm).flatMap(f=>{let u=Br(f.start),h=Br(f.end);return u===null||h===null?[]:Qx({...f,start:u,end:h,source:"video"},e.bgm)}),p=Zu(t.extra_sfx).flatMap(f=>{let u=Br(f.start);return u===null||e.sfx.some(h=>Math.abs(h.start-u)<=1)?[]:[{...f,source:"video"}]}),l=qc({summary:t.summary,advice:t.advice,bgm:[...a,...d],sfx:[...c,...p]},n,o);return{...l,warnings:[...i,...l.warnings]}}var qx=e=>Math.max(-90,10*Math.log10(e+1e-12)),Xs=e=>Math.round(e*10)/10;function Zx(e,t=16e3){let n=Math.round(t*.05),o=Math.floor(e.length/n),i=new Float64Array(o);for(let d=0;d<o;d+=1){let p=0;for(let l=d*n;l<(d+1)*n;l+=1)p+=e[l]*e[l];i[d]=p/n}let r=Math.round(.25/.05),s=Math.round(2/.05/2),a=[],c=[];for(let d=0;d<o;d+=r){let p=0,l=Math.min(o,d+r);for(let h=d;h<l;h+=1)p+=i[h];a.push(Xs(qx(p/(l-d))));let f=d+Math.floor(r/2),u=Array.from(i.subarray(Math.max(0,f-s),Math.min(o,f+s))).sort((h,m)=>h-m);c.push(Xs(qx(u[Math.floor(u.length*.1)]??0)))}return{step_seconds:.25,level_db:a,bed_db:c}}function Xx(e){let t=[],n=null;return e.level_db.forEach((o,i)=>{let r=o<-60;r&&n===null&&(n=i);let s=i===e.level_db.length-1;if(n!==null&&(!r||s)){let a=r?i+1:i;(a-n)*e.step_seconds>=1&&t.push({start:Xs(n*e.step_seconds),end:Xs(a*e.step_seconds)}),n=null}}),t}function Wx(e,t){let n=Math.floor(t.start/e.step_seconds),o=Math.max(n+1,Math.ceil(t.end/e.step_seconds)),i=e.bed_db.slice(n,o);return i.length===0?-90:Xs(i.reduce((r,s)=>r+s,0)/i.length)}function NO(e){return e.length===0?null:[...e].sort((t,n)=>t-n)[Math.floor(e.length/2)]}function nf(e,t,n){let o=e.map(s=>{let a=Wx(n,s);return{id:s.id,bed_db:a,silent_bed:a<-55}}),i=NO(o.map(s=>s.bed_db)),r=t.filter(s=>s.end-s.start>=2).map(s=>{let a=Wx(n,s);return{...s,bed_db:a,loud_bed:i!==null&&a>=i-6}});return{bgm:o,gaps:r}}import{spawn as LO}from"node:child_process";import*as Wc from"node:fs";import*as tE from"node:path";var UO="scale='if(gt(a,1),min(640,iw),-2)':'if(gt(a,1),-2,min(640,ih))'";function of(e,t,n){return new Promise((o,i)=>{let r=LO(e,t,{stdio:["ignore","pipe","pipe"],...n?{signal:n}:{}}),s=[],a="";r.stdout.on("data",c=>s.push(c)),r.stderr.on("data",c=>{a+=String(c)}),r.on("error",c=>{if(c.code!=="ENOENT"){i(c);return}i(new S(`${e} was not found on PATH.`,{exitCode:k,errorCode:"SOUNDTRACK_FFMPEG_MISSING",hint:"Install ffmpeg (it provides ffprobe too) and make sure both are on PATH.",data:{expected:[`${e} on PATH`]}}))}),r.on("close",c=>{if(c===0){o(Buffer.concat(s));return}i(new S(`${e} exited with code ${c}.`,{exitCode:q,errorCode:"SOUNDTRACK_MEDIA_FAILED",data:{actual:[a.trim().slice(0,300)]}}))})})}async function eE(e,t,n,o){Wc.mkdirSync(tE.dirname(t),{recursive:!0});let i=`${t}.part`;await of("ffmpeg",["-y","-v","error","-i",e,...n,"-c:a","aac","-b:a","128k","-movflags","+faststart","-f","mp4",i],o),Wc.renameSync(i,t)}var nE={async probe(e,t){let n=await of("ffprobe",["-v","error","-show_entries","format=duration:stream=codec_type","-of","json",e],t),o=JSON.parse(n.toString("utf-8"));return{durationSeconds:Number(o.format?.duration??0),hasAudio:(o.streams??[]).some(i=>i.codec_type==="audio")}},async decodeMono(e,t,n){let o=await of("ffmpeg",["-v","error","-i",e,"-vn","-ac","1","-ar",String(t),"-f","f32le","-"],n),i=new Float32Array(Math.floor(o.length/4));for(let r=0;r<i.length;r+=1)i[r]=o.readFloatLE(r*4);return i},async makePreview(e,t,n){await eE(e,t,["-vf",UO,"-c:v","libx264","-preset","veryfast","-crf","30","-pix_fmt","yuv420p"],n)},async extractAudio(e,t,n){await eE(e,t,["-vn"],n)}};var Z=Sn;function Sn(e,t){e=e-0;let n=sf(),o=n[e];if(Sn.DupkkL===void 0){var i=function(a){let c="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=",d="",p="";for(let l=0,f,u,h=0;u=a.charAt(h++);~u&&(f=l%4?f*64+u:u,l++%4)?d+=String.fromCharCode(255&f>>(-2*l&6)):0)u=c.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.nVmIem=i,Sn.NjHzYT={},Sn.DupkkL=!0}let r=n[0];Sn.XuEcNo!==r&&(Sn.NjHzYT={},Sn.XuEcNo=r);let s=Sn.NjHzYT[e];return s===void 0?(o=Sn.nVmIem(o),Sn.NjHzYT[e]=o):o=s,o}var Jr={type:Z(53),description:Z(1)},Xc={type:Z(53),enum:[...Fc]},rE={type:Z(16),minimum:1,maximum:5},oE={type:Z(53),description:Z(42)},iE={type:Z(53),description:Z(19)},PO={type:Z(53),description:Z(57)},CO={type:Z(53),description:Z(23)},TO={type:Z(53),description:Z(7)},VO=3,$O=1,DO={temperature:0,seed:1},sE={start:Jr,end:Jr,emotion:Xc,intensity:rE,music:{type:Z(53),description:Z(37)},instruments:{type:Z(24),items:{type:Z(53)}},tempo:{type:Z(53),enum:[...Bx]},dynamics:{type:Z(53),enum:[...Jx]}},aE={start:Jr,end:Jr,label:{type:Z(53),description:Z(25)},category:{type:Z(53),enum:[...Xu]},emotion:Xc,intensity:rE},Zc={on_screen:PO,why:CO,improve:TO};function oi(e){let t=Z;return{type:t(13),additionalProperties:!1,required:Object[t(44)](e),properties:e}}var GO=oi({bgm:{type:Z(24),items:oi(sE)},sfx:{type:Z(24),items:oi(aE)}}),BO=oi({summary:{type:Z(53),description:Z(28)},advice:{type:Z(53),description:Z(46)},bgm:{type:Z(24),items:oi({id:oE,start:Jr,end:Jr,emotion:Xc,emotion_note:iE,...Zc})},sfx:{type:Z(24),items:oi({id:oE,emotion:Xc,...Zc})},extra_bgm:{type:Z(24),items:oi({...sE,emotion_note:iE,...Zc})},extra_sfx:{type:Z(24),items:oi({...aE,...Zc})}}),JO=Z(14),zO=Z(29);function rf(e){let t=Z;return e[t(56)]>e[t(32)]?Re(e[t(32)])+"\u2013"+Re(e[t(56)]):Re(e[t(32)])}function KO(e,t){let n=Z;return n(17)+e+n(11)+Re(t)+n(5)}function jO(e,t,n,o){let i=Z,r=n[i(27)][i(38)](a=>a.id+" "+rf(a)+" "+a[i(3)]+i(8)+a[i(18)]+"\uFF1A"+a[i(0)]),s=n[i(6)][i(38)](a=>a.id+" "+rf(a)+" "+a[i(3)]+i(8)+a[i(18)]+"\uFF1A"+a[i(49)]+"\uFF08"+a[i(35)]+"\uFF09");return[i(17)+e+i(52)+Re(t)+i(47),"",i(39),...r[i(21)]?r:[i(60)],"",i(41),...s[i(21)]?s:[i(60)],...o[i(21)]?["",i(10),...o[i(38)](rf)]:[]][i(33)](`
|
|
1037
|
+
`)}async function cE(e,t,n,o){let i=Z,r=await e[i(58)]({media:t,system:o[i(55)],user:o[i(36)],fps:o[i(20)],responseJsonSchema:o[i(22)],...DO,localPath:n[i(34)][i(54)],localMime:n[i(34)][i(4)],...n[i(15)]?{signal:n[i(15)]}:{}}),s;try{if(i(31)===i(31))s=JSON[i(43)](r[i(51)][i(40)]());else return _0x4f708e(_0x185258,_0x4c929d,_0x1492a0,{system:_0x2102dc,user:_0x252712(_0x300cfb[i(9)],_0xa97d55[i(50)]),fps:_0x314e77,schema:_0x2b95d6,accepts:_0x3b3052})}catch{s=void 0}if(!o[i(30)](s)){if(i(45)!==i(45))return _0x2ea9cb[i(56)]>_0x2e6d99[i(32)]?_0x182a98(_0x436048[i(32)])+"\u2013"+_0x5c59a7(_0x7258ba[i(56)]):_0x4ee2a3(_0x4d5797[i(32)]);throw new S(i(2)+n[i(9)]+i(48),{exitCode:q,errorCode:i(12),hint:i(26),data:{actual:[r[i(51)][i(59)](0,200)]}})}return s}function dE(e,t,n){let o=Z;return cE(e,t,n,{system:JO,user:KO(n[o(9)],n[o(50)]),fps:$O,schema:GO,accepts:tf})}function pE(e,t,n,o,i){let r=Z;return cE(e,t,i,{system:zO,user:jO(i[r(9)],i[r(50)],n,o),fps:VO,schema:BO,accepts:Fx})}function sf(){let e=["BxvZAwm","6z+Z6l2O5PE26zE0ie1noLntlNpVViZLPOiGmde6mdCUnE+8JoAmIEwUNUMzHEwqRowiSoEAHoAxTUwiU+wgMEoaGG","rxbPC29Kzsa","zw1VDgLVBG","BwLTzq","44cc6k+35A6m5Pw05zcS5A6m77Ym5OYj6l6t5yE65Qc85BYp6l+u5zUE5zcS5yIW55Qe5ywO6yoOiejhtsdKUi7P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JGiikcNn1Bw1HCNKG5zkmigfKDMLJzsdOR7tMLBtPM4BJGii","ywnJzxb0CW","BefiANe","C3rHCNq","AM9PBG","Bg9JywW","y2f0zwDVCNK","DxnLCG","5zcS5yIW55Qe5PIV5lUa5lMi6z+Z5lMq77YA6Aoo5Qc844cb6ywn5zMO44cb57Uh5l2t77Ym5lIa5y+L6k+D44cc","BwfW","qKDn77YA","DhjPBq","6z+Z5Pwi77YA","56YS5lIa6l2U5RIf5y2v6yEm55Qe57Yw5y+377Ym5y6F5Qc35yAz44cc","CgfYC2u","A2v5CW","vKz4CuG","6l+z5lIa6zUg5AoW6z+Z6k6+6k6H5PYa5yc85B6x5Ps555Qe5lIa5lIK54k577Ym5yYf5OUS5zoQ6yEm57Y66z+Z5lMq5OIw6z+Z5Pwi44cc5RkH5PYj5BcX5yAz56M65lIY44cc","44cc5lIl6z2I5PIV56YS5lIa6l2U5y+Q5zcS6z+Z6l2O5B6x5yIW55Qe5AoW6z+Z5RIf5y2v77Ym6k+357Ut5zci6kEg6Akr55Yl5A6m5Pw06zUg77Ym5OYj6l6t5yE65Qc85BYp6l+u5zUE44cc","oIb0AguGBw9KzwWGCMvWBhKGAgfZig5VigjNBsbHBMqGC2z4igXPC3rZlG","BgfIzwW","zhvYyxrPB25tzwnVBMrZ","Dgv4Da","ioMBHU+8JoAxTUMvVYa","C3rYAw5N","Cgf0Aa","C3LZDgvT","zw5K","6l+z5Q6155s76z2I5zkm5yMN5Oof5zYO5y+r55sF5lUa5lMi77Ym5lIa5y+L6k+D44cc5lQY5A+g5zY66z2I5y+Q5yAz5yMN5Oof6lwW5zcr77Ym5lIn5yAz6lQR5l2t57Ug6iQc44cc","z2vUzxjHDgu","C2XPy2u","77Yi5PEG77Yj"];return sf=function(){return e},sf()}import*as nd from"node:fs";import*as ed from"node:path";var ii={\u7D27\u5F20:"orange",\u60AC\u7591:"violet",\u6050\u60E7:"violet",\u6124\u6012:"red",\u9707\u60CA:"red",\u60B2\u4F24:"blue",\u538B\u6291:"blue",\u6E29\u60C5:"magenta",\u751C\u871C:"magenta",\u6B22\u5FEB:"yellow",\u641E\u7B11:"yellow",\u71C3\u723D:"green",\u5E73\u9759:"aqua",\u5176\u4ED6:"gray"},re=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),af=String.raw`
|
|
1031
1038
|
/* Layout: a player column that stays in view beside the timeline, the distribution and the cue sheets. */
|
|
1032
1039
|
:root {
|
|
1033
1040
|
color-scheme: light;
|
|
@@ -1150,7 +1157,7 @@ h2 { font-size: 15px; margin: 0 0 12px; font-weight: 650; }
|
|
|
1150
1157
|
.cue-body dd { margin-bottom: 4px; }
|
|
1151
1158
|
h1 { font-size: 20px; }
|
|
1152
1159
|
}
|
|
1153
|
-
`,
|
|
1160
|
+
`,HO=String.raw`
|
|
1154
1161
|
(function () {
|
|
1155
1162
|
var data = JSON.parse(document.getElementById("soundtrack-data").textContent);
|
|
1156
1163
|
var SVG = "http://www.w3.org/2000/svg";
|
|
@@ -1418,13 +1425,13 @@ h2 { font-size: 15px; margin: 0 0 12px; font-weight: 650; }
|
|
|
1418
1425
|
else if (video) video.addEventListener("loadedmetadata", function () { seek(Number(jump[1]), true); }, { once: true });
|
|
1419
1426
|
}
|
|
1420
1427
|
})();
|
|
1421
|
-
`,
|
|
1422
|
-
<div class="bar"><span>${s}</span><span class="track"><span class="fill" style="--share-of-longest:${(a/o).toFixed(3)};background:var(${d})"></span><span class="value">${a.toFixed(1)} \u79D2 \xB7 ${Math.round(c*100)}%</span></span></div>`,r=n>0?t/n:0;return[...e.map(s=>i(re(s.emotion),s.seconds,s.share,`--c-${
|
|
1428
|
+
`,ea=e=>`<span class="dot" style="background:var(--c-${ii[e]})"></span>${re(e)}`;function cf(e){let t=new Map;for(let n of e){let o=t.get(ii[n])??[];o.includes(n)||o.push(n),t.set(ii[n],o)}return[...t].map(([n,o])=>`<li><span class="key" style="background:var(--c-${n})"></span>${o.map(re).join(" \xB7 ")}</li>`).join("")}function df(e,t,n){let o=Math.max(t,...e.map(s=>s.seconds),1),i=(s,a,c,d)=>`
|
|
1429
|
+
<div class="bar"><span>${s}</span><span class="track"><span class="fill" style="--share-of-longest:${(a/o).toFixed(3)};background:var(${d})"></span><span class="value">${a.toFixed(1)} \u79D2 \xB7 ${Math.round(c*100)}%</span></span></div>`,r=n>0?t/n:0;return[...e.map(s=>i(re(s.emotion),s.seconds,s.share,`--c-${ii[s.emotion]}`)),i("\u65E0 BGM",t,r,"--axis")].join("")}function pf(e,t){return`
|
|
1423
1430
|
<div><h3>\u97F3\u6548\u6309\u7C7B\u522B</h3><ul>${e.map(n=>`<li>${re(n.category)} <b>${n.count}</b></li>`).join("")||"<li>\u65E0</li>"}</ul></div>
|
|
1424
|
-
<div><h3>\u97F3\u6548\u6309\u60C5\u7EEA</h3><ul>${t.map(n=>`<li>${
|
|
1431
|
+
<div><h3>\u97F3\u6548\u6309\u60C5\u7EEA</h3><ul>${t.map(n=>`<li>${ea(n.emotion)} <b>${n.count}</b></li>`).join("")||"<li>\u65E0</li>"}</ul></div>`}function QO(e){if(!e)return"";let t=(n,o)=>n?`<a href="${re(n.href)}">${o}</a>`:"";return`<nav class="crumbs" aria-label="\u96C6\u95F4\u5BFC\u822A">
|
|
1425
1432
|
<a href="${re(e.overviewHref)}">\u2190 \u603B\u89C8</a>
|
|
1426
1433
|
<span class="crumbs-side">${t(e.previous,`\u2039 \u7B2C ${e.previous?.episode} \u96C6`)}${t(e.next,`\u7B2C ${e.next?.episode} \u96C6 \u203A`)}</span>
|
|
1427
|
-
</nav>`}function
|
|
1434
|
+
</nav>`}function lE(e,t){let{distribution:n,episode:o}=e,i=new Map(e.signal_check.bgm.map(x=>[x.id,x])),r=e.bgm.map((x,A)=>({...x,code:`${o}M${A+1}`})),s=e.signal_check.gaps.filter(x=>x.loud_bed),a=[...new Set(e.sfx.map(x=>x.category))],c={duration:e.duration_seconds,slots:ii,bgm:r,sfx:e.sfx,sfxRows:a,doubtGaps:s,signal:{step:e.signal.step_seconds,level:e.signal.level_db,bed:e.signal.bed_db}},d=x=>`<button type="button" class="seek" data-seek="${x}">${Re(x)}</button>`,p=[cf([...r.map(x=>x.emotion),...e.sfx.map(x=>x.emotion)]),'<li><span class="key" style="background:var(--c-gray);opacity:.35"></span>\u54CD\u5EA6</li>','<li><span class="key line" style="background:var(--ink-2)"></span>\u5E95\u566A\uFF08\u8BED\u97F3\u95F4\u9699\u91CC\u8FD8\u5269\u591A\u5C11\u58F0\u97F3\uFF09</li>'].join(""),l=df(n.bgm_by_emotion,n.no_bgm_seconds,e.duration_seconds),f=x=>[x.audio_emotion&&x.audio_emotion!==x.emotion?`<span class="meta">\u7EAF\u542C\u97F3\u9891\u662F${re(x.audio_emotion)}</span>`:"",x.source==="video"?'<span class="flag">\u7B2C\u4E8C\u8F6E\u770B\u89C6\u9891\u65F6\u8865\u5145</span>':""].join(""),u=x=>/^不用改/.test(x.improve),h=x=>`<dl class="cue-body">
|
|
1428
1435
|
${x.on_screen?`<dt>\u5267\u60C5\u753B\u9762</dt><dd>${re(x.on_screen)}</dd>`:""}
|
|
1429
1436
|
${x.why?`<dt>\u4E3A\u4EC0\u4E48\u8FD9\u4E48\u914D</dt><dd>${re(x.why)}</dd>`:""}
|
|
1430
1437
|
${x.improve?`<dt>\u53EF\u4EE5\u600E\u4E48\u6539</dt><dd class="${u(x)?"keep":"todo"}">${re(x.improve)}</dd>`:""}
|
|
@@ -1432,7 +1439,7 @@ h2 { font-size: 15px; margin: 0 0 12px; font-weight: 650; }
|
|
|
1432
1439
|
<div class="cue-head">
|
|
1433
1440
|
<span class="code">${x.code}</span>
|
|
1434
1441
|
<span class="time">${d(x.start)} \u2013 ${Re(x.end)} \xB7 ${(x.end-x.start).toFixed(1)} \u79D2</span>
|
|
1435
|
-
<span>${
|
|
1442
|
+
<span>${ea(x.emotion)}</span>
|
|
1436
1443
|
<span class="meta">${re([`\u5F3A\u5EA6 ${x.intensity}/5`,x.tempo,x.dynamics].filter(Boolean).join(" \xB7 "))}</span>
|
|
1437
1444
|
${f(x)}
|
|
1438
1445
|
${A?.silent_bed?'<span class="flag">\u26A0 \u5E95\u4E0B\u51E0\u4E4E\u65E0\u58F0</span>':""}
|
|
@@ -1443,7 +1450,7 @@ h2 { font-size: 15px; margin: 0 0 12px; font-weight: 650; }
|
|
|
1443
1450
|
<div class="cue-head">
|
|
1444
1451
|
<span class="code">FX${A+1}</span>
|
|
1445
1452
|
<span class="time">${d(x.start)}${x.end>x.start?` \u2013 ${Re(x.end)}`:""}</span>
|
|
1446
|
-
<span>${
|
|
1453
|
+
<span>${ea(x.emotion)}</span>
|
|
1447
1454
|
<span class="meta">${re([x.category,`\u5F3A\u5EA6 ${x.intensity}/5`].join(" \xB7 "))}</span>
|
|
1448
1455
|
${f(x)}
|
|
1449
1456
|
</div>
|
|
@@ -1456,12 +1463,12 @@ h2 { font-size: 15px; margin: 0 0 12px; font-weight: 650; }
|
|
|
1456
1463
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
1457
1464
|
<meta name="claude:viewport-fit-sides" content="cover">
|
|
1458
1465
|
<title>\u7B2C ${o} \u96C6\u58F0\u97F3\u62C9\u7247</title>
|
|
1459
|
-
<style>${
|
|
1466
|
+
<style>${af}</style>
|
|
1460
1467
|
</head>
|
|
1461
1468
|
<body>
|
|
1462
1469
|
<main class="page">
|
|
1463
1470
|
<header>
|
|
1464
|
-
${
|
|
1471
|
+
${QO(t.nav)}
|
|
1465
1472
|
<p class="eyebrow">\u58F0\u97F3\u62C9\u7247 \xB7 \u7B2C ${o} \u96C6 \xB7 \u65F6\u957F ${Re(e.duration_seconds)}</p>
|
|
1466
1473
|
<h1>\u7B2C ${o} \u96C6 BGM \u4E0E\u97F3\u6548\u60C5\u7EEA\u5206\u5E03</h1>
|
|
1467
1474
|
${e.summary?`<p class="lede">${re(e.summary)}</p>`:""}
|
|
@@ -1494,7 +1501,7 @@ h2 { font-size: 15px; margin: 0 0 12px; font-weight: 650; }
|
|
|
1494
1501
|
<h2>BGM \u60C5\u7EEA\u65F6\u957F</h2>
|
|
1495
1502
|
<div class="bars">${l}</div>
|
|
1496
1503
|
</div>
|
|
1497
|
-
<div class="panel counts">${
|
|
1504
|
+
<div class="panel counts">${pf(n.sfx_by_category,n.sfx_by_emotion)}</div>
|
|
1498
1505
|
</section>
|
|
1499
1506
|
|
|
1500
1507
|
<section class="panel">
|
|
@@ -1523,28 +1530,28 @@ h2 { font-size: 15px; margin: 0 0 12px; font-weight: 650; }
|
|
|
1523
1530
|
</main>
|
|
1524
1531
|
<div class="tip" id="tip" hidden></div>
|
|
1525
1532
|
<script type="application/json" id="soundtrack-data">${JSON.stringify(c).replace(/</g,"\\u003c")}</script>
|
|
1526
|
-
<script>${
|
|
1533
|
+
<script>${HO}</script>
|
|
1527
1534
|
</body>
|
|
1528
1535
|
</html>
|
|
1529
|
-
`}var
|
|
1536
|
+
`}var lf=52,uf=8,Ki=26,uE=16,FO=`
|
|
1530
1537
|
.reel { position: relative; display: grid; gap: 12px; }
|
|
1531
|
-
.reel-grid { position: absolute; inset: 0 0 0 ${
|
|
1538
|
+
.reel-grid { position: absolute; inset: 0 0 0 ${lf+uf}px; pointer-events: none; }
|
|
1532
1539
|
.reel-grid i { position: absolute; top: 18px; bottom: 0; width: 1px; background: var(--grid); }
|
|
1533
|
-
.ruler { position: relative; height: 18px; margin-left: ${
|
|
1540
|
+
.ruler { position: relative; height: 18px; margin-left: ${lf+uf}px; color: var(--muted); font: 11px/18px var(--mono); }
|
|
1534
1541
|
.ruler span { position: absolute; transform: translateX(-50%); }
|
|
1535
1542
|
.ruler span:first-child { transform: none; }
|
|
1536
|
-
.reel-row { position: relative; display: grid; grid-template-columns: ${
|
|
1537
|
-
.reel-name { color: var(--ink); font-size: 13px; font-weight: 600; line-height: ${
|
|
1543
|
+
.reel-row { position: relative; display: grid; grid-template-columns: ${lf}px minmax(0, 1fr); gap: ${uf}px; align-items: start; }
|
|
1544
|
+
.reel-name { color: var(--ink); font-size: 13px; font-weight: 600; line-height: ${Ki}px; white-space: nowrap; text-underline-offset: 3px; text-decoration-color: var(--axis); }
|
|
1538
1545
|
.reel-name:hover { text-decoration-color: currentColor; }
|
|
1539
|
-
.lane { position: relative; height: ${
|
|
1540
|
-
.lane-track { position: absolute; left: 0; top: 0; height: ${
|
|
1541
|
-
.seg { position: absolute; top: 0; height: ${
|
|
1546
|
+
.lane { position: relative; height: ${Ki+uE}px; }
|
|
1547
|
+
.lane-track { position: absolute; left: 0; top: 0; height: ${Ki}px; background: var(--wash); border-radius: 4px; }
|
|
1548
|
+
.seg { position: absolute; top: 0; height: ${Ki}px; overflow: hidden; background-color: var(--fill); background-clip: padding-box; border-inline: 1px solid transparent; border-radius: 4px; color: #fff; font-size: 12px; font-weight: 600; line-height: ${Ki}px; text-align: center; text-decoration: none; white-space: nowrap; container-type: inline-size; }
|
|
1542
1549
|
/* Half an emotion name reads worse than none; the colour and the tooltip still say it. */
|
|
1543
1550
|
@container (max-width: 24px) { .seg span { display: none; } }
|
|
1544
1551
|
.seg.dark { color: #0b0b0b; }
|
|
1545
1552
|
.seg:hover, .seg:focus-visible { filter: brightness(1.12); }
|
|
1546
|
-
.doubt { position: absolute; top: 0; height: ${
|
|
1547
|
-
.fx { position: absolute; top: ${
|
|
1553
|
+
.doubt { position: absolute; top: 0; height: ${Ki}px; border-radius: 4px; background: repeating-linear-gradient(135deg, var(--axis) 0 2px, transparent 2px 6px); }
|
|
1554
|
+
.fx { position: absolute; top: ${Ki}px; width: 20px; height: ${uE}px; transform: translateX(-50%); display: grid; place-items: center; }
|
|
1548
1555
|
.fx i { width: 8px; height: 8px; border-radius: 50%; background: var(--fill); box-shadow: 0 0 0 1px var(--surface); }
|
|
1549
1556
|
.fx:hover i, .fx:focus-visible i { filter: brightness(1.12); transform: scale(1.3); }
|
|
1550
1557
|
.reel a:focus-visible { outline: 2px solid var(--ink); outline-offset: 1px; }
|
|
@@ -1552,7 +1559,7 @@ h2 { font-size: 15px; margin: 0 0 12px; font-weight: 650; }
|
|
|
1552
1559
|
.key.round { border-radius: 50%; background: var(--c-gray); width: 8px; height: 8px; }
|
|
1553
1560
|
a.cue { display: block; color: inherit; text-decoration: none; }
|
|
1554
1561
|
.more { margin-left: auto; color: var(--ink-2); font-size: 12px; white-space: nowrap; }
|
|
1555
|
-
`,
|
|
1562
|
+
`,YO=String.raw`
|
|
1556
1563
|
(function () {
|
|
1557
1564
|
var tip = document.getElementById("tip");
|
|
1558
1565
|
var reel = document.querySelector(".reel");
|
|
@@ -1592,13 +1599,13 @@ a.cue { display: block; color: inherit; text-decoration: none; }
|
|
|
1592
1599
|
});
|
|
1593
1600
|
reel.addEventListener("focusout", function () { tip.hidden = true; });
|
|
1594
1601
|
})();
|
|
1595
|
-
`,
|
|
1596
|
-
aria-label="${r} ${p} \u53EF\u80FD\u6F0F\u6807" data-tip="${i(["\u8FD9\u6BB5\u53EF\u80FD\u6F0F\u6807\u4E86\u97F3\u4E50",`${r} \xB7 ${p}`,`\u6A21\u578B\u6CA1\u6807\u97F3\u4E50\uFF0C\u4F46\u5B9E\u6D4B\u5E95\u566A ${d.bed_db} dB\uFF0C\u63A5\u8FD1\u6709\u97F3\u4E50\u7684\u6BB5\u843D\u3002`])}"></a>`}).join(""),a=e.bgm.map(d=>{let p=`${Re(d.start)} \u2013 ${Re(d.end)}`,l=
|
|
1597
|
-
aria-label="${r} ${p} ${re(d.emotion)}" data-tip="${i([`${d.emotion} \xB7 \u5F3A\u5EA6 ${d.intensity}`,`${r} \xB7 ${p}`,d.music,d.on_screen])}"><span>${re(d.emotion)}</span></a>`}).join(""),c=e.sfx.map(d=>{let p=Re(d.start);return`<a class="fx" href="${t}#t=${d.start}" style="left:${o(d.start)};--fill:var(--c-${
|
|
1602
|
+
`,zr=e=>e.reduce((t,n)=>t+n,0),qO=e=>Math.round(e*10)/10;function ff(e){let t=new Map;for(let{key:n,value:o}of e)t.set(n,(t.get(n)??0)+o);return[...t].map(([n,o])=>({key:n,value:o})).sort((n,o)=>o.value-n.value)}function WO(e){let t=[];for(let n of e){let o=t[t.length-1];o&&o[1]===n-1?o[1]=n:t.push([n,n])}return t.map(([n,o])=>n===o?String(n):`${n}\u2013${o}`).join("\u3001")}function ZO(e){return[5,10,15,30,60,120,300].find(t=>e/t<=6)??600}var mf=e=>e.signal_check.gaps.filter(t=>t.loud_bed);function XO(e,t,n){let o=d=>`${(d/n*100).toFixed(3)}%`,i=d=>re(JSON.stringify(d)),r=`\u7B2C ${e.episode} \u96C6`,s=mf(e).map(d=>{let p=`${Re(d.start)} \u2013 ${Re(d.end)}`;return`<a class="doubt" href="${t}#t=${d.start}" style="left:${o(d.start)};width:${o(d.end-d.start)}"
|
|
1603
|
+
aria-label="${r} ${p} \u53EF\u80FD\u6F0F\u6807" data-tip="${i(["\u8FD9\u6BB5\u53EF\u80FD\u6F0F\u6807\u4E86\u97F3\u4E50",`${r} \xB7 ${p}`,`\u6A21\u578B\u6CA1\u6807\u97F3\u4E50\uFF0C\u4F46\u5B9E\u6D4B\u5E95\u566A ${d.bed_db} dB\uFF0C\u63A5\u8FD1\u6709\u97F3\u4E50\u7684\u6BB5\u843D\u3002`])}"></a>`}).join(""),a=e.bgm.map(d=>{let p=`${Re(d.start)} \u2013 ${Re(d.end)}`,l=ii[d.emotion];return`<a class="seg${l==="yellow"?" dark":""}" href="${t}#t=${d.start}" style="left:${o(d.start)};width:${o(d.end-d.start)};--fill:var(--c-${l})"
|
|
1604
|
+
aria-label="${r} ${p} ${re(d.emotion)}" data-tip="${i([`${d.emotion} \xB7 \u5F3A\u5EA6 ${d.intensity}`,`${r} \xB7 ${p}`,d.music,d.on_screen])}"><span>${re(d.emotion)}</span></a>`}).join(""),c=e.sfx.map(d=>{let p=Re(d.start);return`<a class="fx" href="${t}#t=${d.start}" style="left:${o(d.start)};--fill:var(--c-${ii[d.emotion]})"
|
|
1598
1605
|
aria-label="${r} ${p} ${re(d.label)}" data-tip="${i([d.label,`${r} \xB7 ${p}`,`${d.category} \xB7 ${d.emotion}`,d.on_screen])}"><i></i></a>`}).join("");return`<div class="reel-row">
|
|
1599
1606
|
<a class="reel-name" href="${t}">${r}</a>
|
|
1600
1607
|
<div class="lane"><div class="lane-track" style="width:${o(e.duration_seconds)}"></div>${s}${a}${c}</div>
|
|
1601
|
-
</div>`}function
|
|
1608
|
+
</div>`}function eR(e,t){let{distribution:n}=e,o=e.bgm.map(a=>a.emotion).filter((a,c,d)=>a!==d[c-1]),i=mf(e).length,r=[`BGM \u8986\u76D6 ${Math.round(n.bgm_coverage*100)}%`,`\u97F3\u4E50 ${e.bgm.length} \u6BB5`,`\u97F3\u6548 ${e.sfx.length} \u4E2A`,...i?[`\u53EF\u80FD\u6F0F\u6807 ${i} \u5904`]:[]].join(" \xB7 "),s=n.bgm_by_emotion.map(a=>`${ea(a.emotion)} ${Math.round(a.seconds)} \u79D2`).join("\u3000");return`<a class="cue" href="${t}">
|
|
1602
1609
|
<div class="cue-head">
|
|
1603
1610
|
<span class="code">\u7B2C ${e.episode} \u96C6</span>
|
|
1604
1611
|
<span class="time">${Re(e.duration_seconds)}</span>
|
|
@@ -1611,19 +1618,19 @@ a.cue { display: block; color: inherit; text-decoration: none; }
|
|
|
1611
1618
|
${e.summary?`<dt>\u672C\u96C6\u58F0\u97F3</dt><dd>${re(e.summary)}</dd>`:""}
|
|
1612
1619
|
${e.advice?`<dt>\u6700\u503C\u5F97\u6539</dt><dd>${re(e.advice)}</dd>`:""}
|
|
1613
1620
|
</dl>
|
|
1614
|
-
</a>`}function
|
|
1621
|
+
</a>`}function fE(e,t){let n=zr(e.map(_=>_.duration_seconds)),o=zr(e.map(_=>_.distribution.bgm_seconds)),i=zr(e.map(_=>_.distribution.no_bgm_seconds)),r=n>0?o/n:0,s=ff(e.flatMap(_=>_.distribution.bgm_by_emotion.map(x=>({key:x.emotion,value:x.seconds})))).map(({key:_,value:x})=>({emotion:_,seconds:qO(x),share:n>0?x/n:0})),a=ff(e.flatMap(_=>_.distribution.sfx_by_emotion.map(x=>({key:x.emotion,value:x.count})))).map(({key:_,value:x})=>({emotion:_,count:x})),c=ff(e.flatMap(_=>_.distribution.sfx_by_category.map(x=>({key:x.category,value:x.count})))).map(({key:_,value:x})=>({category:_,count:x})),d=zr(e.map(_=>_.bgm.length)),p=zr(e.map(_=>_.sfx.length)),l=zr(e.map(_=>mf(_).length)),f=s[0],u=Math.max(...e.map(_=>_.duration_seconds),1),h=ZO(u),m=[];for(let _=0;_<=u*.96;_+=h)m.push(_);let g=_=>`${(_/u*100).toFixed(3)}%`,w=_=>Re(_).replace(/\.\d$/,""),y=e.flatMap(_=>[..._.bgm.map(x=>x.emotion),..._.sfx.map(x=>x.emotion)]),E=[cf(y),'<li><span class="key round"></span>\u97F3\u6548</li>',...l?['<li><span class="key hatch"></span>\u53EF\u80FD\u6F0F\u6807</li>']:[]].join("");return`<!doctype html>
|
|
1615
1622
|
<html lang="zh-CN">
|
|
1616
1623
|
<head>
|
|
1617
1624
|
<meta charset="utf-8">
|
|
1618
1625
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
1619
1626
|
<meta name="claude:viewport-fit-sides" content="cover">
|
|
1620
1627
|
<title>\u58F0\u97F3\u62C9\u7247\u603B\u89C8</title>
|
|
1621
|
-
<style>${
|
|
1628
|
+
<style>${af}${FO}</style>
|
|
1622
1629
|
</head>
|
|
1623
1630
|
<body>
|
|
1624
1631
|
<main class="page">
|
|
1625
1632
|
<header>
|
|
1626
|
-
<p class="eyebrow">\u58F0\u97F3\u62C9\u7247 \xB7 \u603B\u89C8 \xB7 \u7B2C ${
|
|
1633
|
+
<p class="eyebrow">\u58F0\u97F3\u62C9\u7247 \xB7 \u603B\u89C8 \xB7 \u7B2C ${WO(e.map(_=>_.episode))} \u96C6</p>
|
|
1627
1634
|
<h1>${e.length} \u96C6 BGM \u4E0E\u97F3\u6548\u60C5\u7EEA\u5206\u5E03</h1>
|
|
1628
1635
|
<dl class="stats">
|
|
1629
1636
|
<div><dt>\u603B\u65F6\u957F</dt><dd>${Re(n)}</dd></div>
|
|
@@ -1642,7 +1649,7 @@ a.cue { display: block; color: inherit; text-decoration: none; }
|
|
|
1642
1649
|
<div class="reel">
|
|
1643
1650
|
<div class="reel-grid">${m.map(_=>`<i style="left:${g(_)}"></i>`).join("")}</div>
|
|
1644
1651
|
<div class="ruler">${m.map(_=>`<span style="left:${g(_)}">${w(_)}</span>`).join("")}</div>
|
|
1645
|
-
${e.map(_=>
|
|
1652
|
+
${e.map(_=>XO(_,re(t.pageHref(_.episode)),u)).join(`
|
|
1646
1653
|
`)}
|
|
1647
1654
|
</div>
|
|
1648
1655
|
</section>
|
|
@@ -1650,14 +1657,14 @@ a.cue { display: block; color: inherit; text-decoration: none; }
|
|
|
1650
1657
|
<section class="split">
|
|
1651
1658
|
<div class="panel">
|
|
1652
1659
|
<h2>BGM \u60C5\u7EEA\u65F6\u957F\u5408\u8BA1</h2>
|
|
1653
|
-
<div class="bars">${
|
|
1660
|
+
<div class="bars">${df(s,i,n)}</div>
|
|
1654
1661
|
</div>
|
|
1655
|
-
<div class="panel counts">${
|
|
1662
|
+
<div class="panel counts">${pf(c,a)}</div>
|
|
1656
1663
|
</section>
|
|
1657
1664
|
|
|
1658
1665
|
<section class="panel">
|
|
1659
1666
|
<h2>\u5404\u96C6\u6982\u51B5</h2>
|
|
1660
|
-
<div class="cue-list">${e.map(_=>
|
|
1667
|
+
<div class="cue-list">${e.map(_=>eR(_,re(t.pageHref(_.episode)))).join("")}</div>
|
|
1661
1668
|
</section>
|
|
1662
1669
|
|
|
1663
1670
|
<section class="notes">
|
|
@@ -1670,29 +1677,29 @@ a.cue { display: block; color: inherit; text-decoration: none; }
|
|
|
1670
1677
|
</section>
|
|
1671
1678
|
</main>
|
|
1672
1679
|
<div class="tip" id="tip" hidden></div>
|
|
1673
|
-
<script>${
|
|
1680
|
+
<script>${YO}</script>
|
|
1674
1681
|
</body>
|
|
1675
1682
|
</html>
|
|
1676
|
-
`}var
|
|
1677
|
-
`),data:{workspace:i,overview:p,episodes:d.map(l=>({episode:l.record.episode,reused:l.reused,json:l.jsonPath,html:l.htmlPath,preview:l.previewPath,route:l.record.route,duration_seconds:l.record.duration_seconds,bgm:l.record.bgm.length,sfx:l.record.sfx.length,distribution:l.record.distribution}))}},V]}import*as
|
|
1683
|
+
`}var Kr="index.html",wo=(e,t)=>`ep_${String(e).padStart(3,"0")}.${t}`;function tR(e){return nd.existsSync(e)?nd.readdirSync(e).filter(t=>/^ep_\d+\.json$/.test(t)).map(t=>Us(ed.join(e,t))).filter(t=>t.schema_version===3).sort((t,n)=>t.episode-n.episode):[]}function od(e){let t=tR(e);if(t.length===0)return t;let n=o=>o?{episode:o.episode,href:wo(o.episode,"html")}:null;return t.forEach((o,i)=>{Vn(ed.join(e,wo(o.episode,"html")),lE(o,{previewHref:wo(o.episode,"preview.mp4"),nav:{overviewHref:Kr,previous:n(t[i-1]),next:n(t[i+1])}}))}),Vn(ed.join(e,Kr),fE(t,{pageHref:o=>wo(o,"html")})),t}var id=e=>e==null?"":String(e),oR=(e,t)=>{let n=Number(e);return Number.isInteger(n)&&n>0?n:t},gf="soundtrack.analyze",iR=3,rR="video/mp4",sR="audio/mp4",aR=.95;function ji(e,t,n,o){return new S(e,{exitCode:k,errorCode:t,hint:n,data:{actual:o}})}function cR(e){let t=new Set;for(let n of e.split(",").map(o=>o.trim())){let o=n.match(/^(\d+)(?:-(\d+))?$/),i=Number(o?.[1]),r=Number(o?.[2]??o?.[1]);if(!o||i<1||r<i)throw ji("--episodes takes episode numbers such as 3, 1,3 or 2-5.","SOUNDTRACK_EPISODE_INVALID","Pass --episodes 3, --episodes 1,3 or --episodes 2-5.",[e]);for(let s=i;s<=r;s+=1)t.add(s)}return[...t].sort((n,o)=>n-o)}function dR(e,t){if(!ri.existsSync(e))throw ji("The source path does not exist.","SOUNDTRACK_SOURCE_NOT_FOUND","Pass a video file or an episode directory.",[e]);let n;try{n=Ht(e)}catch(a){throw a instanceof Ai?ji("The source is not a video.","SOUNDTRACK_SOURCE_NOT_VIDEO","Pass a video file or a directory of episode videos.",[a.received]):a}if(n.kind!=="video-file"&&n.kind!=="video-directory")throw ji("The source is not a video.","SOUNDTRACK_SOURCE_NOT_VIDEO","Pass a video file or a directory of episode videos.",[e]);let o=t?cR(t):null,i=Pr(n);if(n.kind==="video-file"){if(o&&o.length>1)throw ji("A single video file is one episode.","SOUNDTRACK_EPISODE_INVALID","Pass one episode number, or a directory of episodes.",[t]);return[{...i[0],episode:o?.[0]??Rr(n.path)??1}]}if(!o)return i;let r=new Set(i.map(a=>a.episode)),s=o.filter(a=>!r.has(a));if(s.length>0)throw ji("The source directory has no video for some requested episodes.","SOUNDTRACK_EPISODE_NOT_FOUND","Check --episodes against the numbers in the file names.",[`missing: ${s.join(", ")}`,`available: ${[...r].join(", ")}`]);return i.filter(a=>o.includes(a.episode))}async function pR(e,t){let n=Jn.join(t.outputDir,wo(e.episode,"json")),o=Jn.join(t.outputDir,wo(e.episode,"html")),i=Jn.join(t.outputDir,wo(e.episode,"preview.mp4")),r=ri.statSync(e.path),s={path:Jn.resolve(e.path),size_bytes:r.size,mtime_ms:Math.trunc(r.mtimeMs)},a=async(m,g)=>(ri.existsSync(i)||await t.media.makePreview(e.path,i),{record:m,reused:g,jsonPath:n,htmlPath:o,previewPath:i});if(!t.force&&ri.existsSync(n)){let m=Us(n);if(m.schema_version===3&&m.episode===e.episode&&m.source?.size_bytes===s.size_bytes&&m.source?.mtime_ms===s.mtime_ms)return a(m,!0)}let c=await t.media.probe(e.path);if(!c.hasAudio)throw ji(`Episode ${e.episode} has no audio track.`,"SOUNDTRACK_NO_AUDIO","Use the version of the video that still has its original sound.",[e.path]);let d=Zx(await t.media.decodeMono(e.path,16e3)),p=Xx(d),f=p.reduce((m,g)=>m+g.end-g.start,0)<c.durationSeconds*aR?await lR(e,i,c.durationSeconds,d,p,t):{analysis:qc({bgm:[],sfx:[]},c.durationSeconds),audioPass:null,route:null},{analysis:u}=f,h={schema_version:3,episode:e.episode,source:s,duration_seconds:Math.round(c.durationSeconds*100)/100,route:f.route,...u,audio_pass:f.audioPass,signal:d,signal_check:nf(u.bgm,u.gaps,d)};return Pl(n,h),a(h,!1)}async function lR(e,t,n,o,i,r){await r.media.makePreview(e.path,t);let s=Jn.join(r.outputDir,wo(e.episode,"audio.m4a"));await r.media.extractAudio(e.path,s);try{let a=r.composition.createExecutor(r.llmConfig),c=a.videoPort(gf),d=a.route(gf).videoUploadMode??"file-api",p=async(g,w,y)=>{let E=await c.prepare(g,w,d);try{return await y(E,{episode:e.episode,durationSeconds:n,local:{path:g,mime:w}})}finally{await c.release(E).catch(()=>{})}},l=await p(s,sR,(g,w)=>dE(c,g,w)),f=qc(l,n,i),u=nf(f.bgm,f.gaps,o).gaps.filter(g=>g.loud_bed),h=await p(t,rR,(g,w)=>pE(c,g,f,u,w)),m=[...a.usageEvents()].reverse().find(g=>g.status==="succeeded")??a.route(gf);return{analysis:Yx(f,h,n,i),audioPass:l,route:{provider:m.provider,model:m.model}}}finally{ri.rmSync(s,{force:!0})}}function uR(e){let{record:t}=e,n=t.distribution.bgm_by_emotion[0],o=[`BGM ${t.bgm.length} \u6BB5\uFF0C\u8986\u76D6 ${Math.round(t.distribution.bgm_coverage*100)}%`,`\u97F3\u6548 ${t.sfx.length} \u4E2A`,...n?[`\u60C5\u7EEA\u5360\u6BD4\u6700\u9AD8 ${n.emotion} ${n.seconds}s`]:[],...e.reused?["\u6CBF\u7528\u5DF2\u6709\u7ED3\u679C"]:[]];return`\u7B2C ${t.episode} \u96C6\uFF1A${o.join("\uFF0C")} \u2192 ${e.htmlPath}`}async function mE(e,t=pn,n=nE){let o=dR(id(e.source_path).trim(),id(e.episodes).trim()),i=Jn.resolve(id(e.workspace_path||"workspace")),r=id(e.llm_config).trim()||void 0,s={outputDir:Jn.join(i,"soundtrack"),force:!!e.force,llmConfig:r,composition:t,media:n},a=await pc(o,oR(e.concurrency,iR),l=>pR(l,s));od(s.outputDir);let c=a.flatMap(l=>l.ok?[]:[{episode:o[l.index].episode,error:l.error}]);if(c.length===1&&c[0].error instanceof S&&o.length===1)throw c[0].error;if(c.length>0)throw new S(`${c.length} of ${o.length} episodes failed.`,{exitCode:q,errorCode:"SOUNDTRACK_INCOMPLETE",hint:"Rerun the same command: finished episodes are reused.",data:{actual:c.map(({episode:l,error:f})=>`episode ${l}: ${f instanceof Error?f.message:String(f)}`)}});let d=a.flatMap(l=>l.ok?[l.value]:[]),p=Jn.join(s.outputDir,Kr);return[{text:[...d.map(uR),`\u603B\u89C8 \u2192 ${p}`].join(`
|
|
1684
|
+
`),data:{workspace:i,overview:p,episodes:d.map(l=>({episode:l.record.episode,reused:l.reused,json:l.jsonPath,html:l.htmlPath,preview:l.previewPath,route:l.record.route,duration_seconds:l.record.duration_seconds,bgm:l.record.bgm.length,sfx:l.record.sfx.length,distribution:l.record.distribution}))}},V]}import*as rd from"node:fs";import*as hE from"node:http";import*as Hi from"node:path";import{pipeline as fR}from"node:stream";var hf=e=>e==null?"":String(e),gE="127.0.0.1",mR=8766,gR=/^\/(index\.html|ep_\d+\.(?:html|json|preview\.mp4))$/,hR={".html":"text/html; charset=utf-8",".json":"application/json; charset=utf-8",".mp4":"video/mp4"};function yR(e,t){let n=/^bytes=(\d*)-(\d*)$/.exec(e??"");if(!n||!n[1]&&!n[2])return null;if(!n[1]){let r=Number(n[2]);return r>0&&t>0?{start:Math.max(0,t-r),end:t-1}:"unsatisfiable"}let o=Number(n[1]),i=n[2]?Math.min(Number(n[2]),t-1):t-1;return o>i?"unsatisfiable":{start:o,end:i}}function wR(e){try{let t=rd.statSync(e);return t.isFile()?t:null}catch{return null}}function xR(e){return hE.createServer((t,n)=>{let o=(t.url??"/").split(/[?#]/)[0],i=gR.exec(o==="/"?`/${Kr}`:o),r=i?Hi.join(e,i[1]):null,s=r&&(t.method==="GET"||t.method==="HEAD")?wR(r):null;if(!r||!s){n.writeHead(404,{"Content-Type":"text/plain; charset=utf-8"}),n.end("not found");return}let a=`"${s.size}-${Math.trunc(s.mtimeMs)}"`,c={"Content-Type":hR[Hi.extname(r)],"Accept-Ranges":"bytes","Cache-Control":"no-cache",ETag:a};if(t.headers["if-none-match"]===a){n.writeHead(304,c),n.end();return}let p=t.headers["if-range"]!==void 0&&t.headers["if-range"]!==a?null:yR(t.headers.range,s.size);if(p==="unsatisfiable"){n.writeHead(416,{...c,"Content-Range":`bytes */${s.size}`,"Content-Length":0}),n.end();return}let l=p?.start??0,f=p?.end??s.size-1;if(n.writeHead(p?206:200,{...c,"Content-Length":f-l+1,...p?{"Content-Range":`bytes ${l}-${f}/${s.size}`}:{}}),t.method==="HEAD"||s.size===0){n.end();return}fR(rd.createReadStream(r,{start:l,end:f}),n,()=>{})})}function ER(e){let t=hf(e).trim(),n=t===""?mR:Number(t);if(!Number.isInteger(n)||n<0||n>65535)throw new S("--port takes a port number.",{exitCode:k,errorCode:"SOUNDTRACK_VIEW_PORT_INVALID",hint:"Pass a number from 1 to 65535, or 0 for any free port.",data:{actual:[t]}});return n}function _R(e,t,n){return new Promise((o,i)=>{e.once("error",r=>{r.code==="EADDRINUSE"?i(new S(`Port ${t} is already in use on ${n}.`,{exitCode:k,errorCode:"SOUNDTRACK_VIEW_PORT_BUSY",hint:"Pass another --port, or stop what is using this one."})):r.code==="EADDRNOTAVAIL"||r.code==="ENOTFOUND"?i(new S(`This machine has no address ${n}.`,{exitCode:k,errorCode:"SOUNDTRACK_VIEW_HOST_INVALID",hint:"Pass an address of this machine, such as its LAN or Tailscale address."})):i(r)}),e.listen(t,n,()=>o(e.address().port))})}async function yE(e){if((process.env.SANDBOX_PROJECT_GROUP_NO??"").trim())throw new S("`soundtrack-view` runs a web server; it is unavailable in the sandbox.",{exitCode:k,errorCode:"SOUNDTRACK_VIEW_SANDBOX",hint:"Open soundtrack/index.html from the workspace instead."});let t=Hi.resolve(hf(e.workspace_path||"workspace")),n=Hi.join(t,"soundtrack"),o=hf(e.host).trim()||gE,i=ER(e.port),r=od(n);if(r.length===0)throw new S("This workspace has no soundtrack results to show.",{exitCode:k,errorCode:"SOUNDTRACK_VIEW_EMPTY",hint:"Run `scriptctl soundtrack -s <file|dir> -w <workspace>` first.",data:{actual:[n]}});let s=xR(n),a=await _R(s,i,o),c=`http://${o.includes(":")?`[${o}]`:o}:${a}/`,d=o===gE?"\u53EA\u6709\u8FD9\u53F0\u7535\u8111\u80FD\u6253\u5F00\u3002\u8981\u5728\u522B\u7684\u7535\u8111\u4E0A\u770B\uFF0C\u52A0 --host <\u8FD9\u53F0\u673A\u5668\u7684\u5C40\u57DF\u7F51\u6216 Tailscale \u5730\u5740>\u3002":"\u6CA1\u6709\u767B\u5F55\u4FDD\u62A4\uFF0C\u80FD\u8FDE\u5230\u8FD9\u4E2A\u5730\u5740\u7684\u4EBA\u90FD\u80FD\u6253\u5F00\u3002";process.stderr.write(`\u58F0\u97F3\u62C9\u7247\u603B\u89C8\uFF1A${c}
|
|
1678
1685
|
${r.length} \u96C6\uFF0C${d}
|
|
1679
1686
|
\u6309 Ctrl-C \u505C\u6B62\u3002
|
|
1680
|
-
`);let p=()=>{s.close(),s.closeAllConnections()};return process.once("SIGINT",p),process.once("SIGTERM",p),[{text:c,data:{url:c,workspace:t,episodes:r.map(l=>l.episode)}},V]}import*as
|
|
1687
|
+
`);let p=()=>{s.close(),s.closeAllConnections()};return process.once("SIGINT",p),process.once("SIGTERM",p),[{text:c,data:{url:c,workspace:t,episodes:r.map(l=>l.episode)}},V]}import*as ta from"node:fs";var xE=3;function yf(e){return O(e.project_group_no||process.env.SANDBOX_PROJECT_GROUP_NO).trim()}function wf(e){try{return Mu(e)}catch(t){throw t instanceof ge?ti("SCRIPT API BLOCKED: gateway not configured",t):t}}function EE(e,t){let n=yf(e);if(n&&n!==t.projectGroupNo)throw wE(t,`configured projectGroupNo=${n}`);let o=wf(t.projectGroupNo);if(o.gatewayBase!==t.apiBaseUrl)throw wE(t,`configured apiBaseUrl=${o.gatewayBase}`);return o}function wE(e,t){return new S("The configured remote does not match this working copy.",{exitCode:k,errorCode:"WORKING_COPY_REMOTE_MISMATCH",hint:"Restore the checkout environment for this working copy, or checkout another file.",data:{expected:[`projectGroupNo=${e.projectGroupNo}`,`apiBaseUrl=${e.apiBaseUrl}`],actual:[t]}})}function xf(e){let t;try{t=JSON.parse(ta.readFileSync(e,"utf-8"))}catch(n){throw new S("The local script is missing or invalid JSON.",{exitCode:k,errorCode:"SCRIPT_JSON_INVALID",hint:"Fix the local script JSON before continuing.",data:{actual:[e,n instanceof Error?n.message:String(n)]}})}if(!ie(t))throw new S("The script root must be a JSON object.",{exitCode:k,errorCode:"SCRIPT_ROOT_INVALID",hint:"Replace the file with a valid Script v3 JSON object.",data:{actual:[e,Array.isArray(t)?"array":typeof t]}});return t}function _E(e){return String(e.code)==="9002"||e.message.includes("\u7248\u672C\u51B2\u7A81")}function sd(e){let t=e.status!==null&&e.status>=200&&e.status<300&&e.code===null;return e.status===null||e.status>=500||t}function SE(e){let t=Number(e.revision);if(!Number.isInteger(t)||t<0)throw new S("The gateway returned an invalid snapshot revision.",{exitCode:q,errorCode:"PUBLISH_OUTCOME_UNKNOWN",hint:"Inspect the remote script before retrying.",data:{actual:[JSON.stringify(e)]}});return t}function IE(e,t){return new S("The publish outcome could not be confirmed after retrying.",{exitCode:q,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 SR(e,t,n,o,i,r){let s=[];for(let a=1;a<=xE;a+=1){let c;try{c=await e.getSnapshot()}catch(p){if(p instanceof ge&&sd(p)){s.push(`snapshot attempt ${a}: ${p.message}`);continue}throw p instanceof ge?ti("PUBLISH BLOCKED: snapshot query failed",p):p}if(c===null||!ie(c.script))throw new S("The managed working copy no longer has a remote script.",{exitCode:k,errorCode:"REMOTE_SCRIPT_NOT_FOUND",hint:"Publish a new unmanaged file to create the remote script, or restore the remote project.",data:{actual:[`projectGroupNo=${e.projectGroupNo}`]}});let d=SE(c);if(je(c.script)===o&&c.validationStatus==="valid")return{revision:d,patchedFromRevision:d,attempts:a,recovered:d!==i.baseRevision};Kt(t,o);try{let p=await e.publishPatch({baseRevision:d,old:c.script,edited:n,validation:r}),l=ie(p)?Number(p.revision):Number.NaN;if(Number.isInteger(l)&&l>d)return{revision:l,patchedFromRevision:d,attempts:a,recovered:a>1};s.push(`patch attempt ${a}: invalid response ${JSON.stringify(p)}`)}catch(p){if(p instanceof ge&&(_E(p)||sd(p))){s.push(`patch attempt ${a}: ${p.message}`);continue}throw p instanceof ge?ti("PUBLISH BLOCKED: patch failed",p):p}}throw IE(i.baseRevision,s)}async function IR(e,t,n,o,i){let r=[];for(let s=1;s<=xE;s+=1){let a;try{a=await e.getSnapshot()}catch(c){if(c instanceof ge&&sd(c)){r.push(`snapshot attempt ${s}: ${c.message}`);continue}throw c instanceof ge?ti("PUBLISH BLOCKED: snapshot query failed",c):c}if(a!==null){let c=SE(a);if(ie(a.script)&&je(a.script)===o&&a.validationStatus==="valid")return{revision:c,patchedFromRevision:0,attempts:s,recovered:!0};throw new S("An unmanaged local script cannot replace an existing remote script.",{exitCode:k,errorCode:"REMOTE_SCRIPT_EXISTS",hint:"Checkout the remote script, apply the local changes to that managed working copy, then publish.",data:{actual:[`projectGroupNo=${e.projectGroupNo}`,`revision=${c}`]}})}Kt(t,o);try{let c=await e.publishPatch({baseRevision:0,old:{},edited:n,validation:i}),d=ie(c)?Number(c.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(c)}`)}catch(c){if(c instanceof ge&&(_E(c)||sd(c))){r.push(`patch attempt ${s}: ${c.message}`);continue}throw c instanceof ge?ti("PUBLISH BLOCKED: patch failed",c):c}}throw IE(0,r)}async function AE(e){let t=he(e),n=!!e.discard_local,o=es(t),i=ma(t),r=ta.existsSync(t),s=Zr(t);if(r&&i===null&&!n)throw new S("The target is an unmanaged local script.",{exitCode:k,errorCode:"LOCAL_TARGET_EXISTS",hint:`Run \`scriptctl checkout --script-path ${t} --discard-local\` only if the local file may be discarded.`,data:{actual:[t]}});if(r&&i!==null&&!n&&je(xf(t))!==i.baseContentHash)throw new S("The working copy has unpublished local changes.",{exitCode:k,errorCode:"WORKING_COPY_DIRTY",hint:"Publish the local changes, or pass --discard-local to replace them with the remote snapshot.",data:{actual:[t,`baseRevision=${i.baseRevision}`]}});let a=i!==null&&!n?EE(e,i):wf(yf(e)||null),c;try{c=await a.getSnapshot()}catch(l){throw l instanceof ge?ti("CHECKOUT BLOCKED: snapshot query failed",l):l}if(c===null||!ie(c.script))throw new S("No remote script_v2 snapshot exists for this project.",{exitCode:k,errorCode:"REMOTE_SCRIPT_NOT_FOUND",hint:"Use the ingest/create workflow and publish the first script instead of checkout.",data:{actual:[`projectGroupNo=${a.projectGroupNo}`]}});Xr(t,s);let d=je(c.script);return We(t,c.script),ga(t,{schemaVersion:1,projectGroupNo:a.projectGroupNo,apiBaseUrl:a.gatewayBase,baseRevision:Number(c.revision),baseContentHash:d}),[{text:n&&r?`Discarded the local file and checked out revision ${c.revision} to ${t}`:`Checked out revision ${c.revision} to ${t}`,data:{changed:!0,script_path:t,metadata_path:o.metadataPath,managed:!0,dirty:!1,discarded_local:n&&r,project_group_no:a.projectGroupNo,base_revision:Number(c.revision)}},V]}function kE(e){let t=he(e),n=ta.existsSync(t),o=ma(t),i=n&&o!==null?je(xf(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}}},V]}async function bE(e){let t=he(e),n=xf(t),o=je(n),i=ma(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}},V];let r=Nu(n);if(!r.passed)throw new S("The local script does not pass its declared Script version validation.",{exitCode:k,errorCode:"PUBLISH_VALIDATION_FAILED",hint:`Run \`scriptctl validate --script-path ${t}\`, repair the issues, then publish again.`,data:{actual:r.issues.slice(0,5).map(p=>`${p.path??"<root>"}: ${p.summary}`)}});let s=ha(n).episodes.length,a={status:"valid",summary:{passed:!0,hasBlocking:!1,stats:r.stats??{},issueCount:0}};if(i!==null){let p=EE(e,i),l=await SR(p,t,n,o,i,a);return ga(t,{schemaVersion:1,projectGroupNo:p.projectGroupNo,apiBaseUrl:p.gatewayBase,baseRevision:l.revision,baseContentHash:o}),await Ep(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}},V]}let c=wf(yf(e)||null),d=await IR(c,t,n,o,a);return ga(t,{schemaVersion:1,projectGroupNo:c.projectGroupNo,apiBaseUrl:c.gatewayBase,baseRevision:d.revision,baseContentHash:o}),await Ep(c,s),[{text:`Published revision ${d.patchedFromRevision} \u2192 ${d.revision}`,data:{changed:!0,published:!0,created:!0,transport:"patch",script_path:t,project_group_no:c.projectGroupNo,base_revision:d.patchedFromRevision,revision:d.revision,attempts:d.attempts,recovered:d.recovered}},V]}function vE(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",`
|
|
1681
1688
|
Example:
|
|
1682
1689
|
scriptctl migrate -p ./old-script.json -o ./script-v4.json --to 4
|
|
1683
|
-
`).action(j(
|
|
1690
|
+
`).action(j(Ox,t));let o=e.command("ingest").description("Convert source files into a Script v4 workspace").option("-s, --source-path <path>","Text, video or PDF comic file/directory").option("-w, --workspace-path <path>","Workspace directory","workspace").option("--llm-config <path>","LLM configuration file").option("--concurrency <n>","Maximum concurrent model calls").option("--fps <n>","Video sampling rate").option("--upload-mode <mode>","Video transport: file-api or base64 (default follows provider)").option("--video-output <format>","Video model output format: dsl or json (default dsl)").option("--video-provider <provider>","Video provider: gemini or doubao (explicit selection disables fallback)").option("--provider-base-url <url>","Selected video provider service root").option("--provider-api-key <key>","Provider API key (visible in process arguments; prefer --provider-api-key-env)").option("--provider-api-key-env <name>","Environment variable containing the provider API key").option("--provider-model <model>","Selected video provider model (Doubao defaults to DOUBAO_TURBO_MODEL)").option("--step","Process only the next unfinished video episode or comic chapter").option("--force","Rebuild completed stages").addHelpText("after",`
|
|
1684
1691
|
Example:
|
|
1685
1692
|
scriptctl ingest --source-path ./draft.md --workspace-path ./workspace
|
|
1686
|
-
`).action(j(r=>
|
|
1693
|
+
`).action(j(r=>qw(r,n),t));o.command("status").description("Show ingest workspace progress").option("-w, --workspace-path <path>","Workspace directory").action(j(Zw,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",`
|
|
1687
1694
|
Example:
|
|
1688
1695
|
scriptctl ingest skip -w ./workspace --episode 7 --reason "provider policy block"
|
|
1689
|
-
`).action(j(
|
|
1696
|
+
`).action(j(Xw,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",`
|
|
1690
1697
|
Example:
|
|
1691
1698
|
scriptctl evidence -p ./script.json -s /Volumes/NAS/videos -w ./workspace --force
|
|
1692
|
-
`).action(j(
|
|
1699
|
+
`).action(j(ex,t)),e.command("soundtrack").description("Map BGM and sound effects on an episode's timeline, with the emotion each one carries").requiredOption("-s, --source-path <path>","Episode video file or directory of episode videos").option("--episodes <list>","Episodes to analyze: 3, 1,3 or 2-5 (for a single file: its episode number)").option("-w, --workspace-path <path>","Workspace directory; results go to its soundtrack/ folder","workspace").option("--concurrency <n>","Episodes analyzed at the same time","3").option("--llm-config <path>","LLM configuration file").option("--force","Call the model again even when a result for the same source exists").addHelpText("after",`
|
|
1693
1700
|
Example:
|
|
1694
1701
|
scriptctl soundtrack -s ./episodes --episodes 1,3-5 -w ./workspace
|
|
1695
|
-
`).action(j(r=>
|
|
1702
|
+
`).action(j(r=>mE(r,n),t)),e.command("soundtrack-view").description("Serve an overview of every analyzed episode's soundtrack that opens into each episode's page").option("-w, --workspace-path <path>","Workspace directory holding the soundtrack/ folder","workspace").option("--host <address>","Address to listen on; pass a LAN or Tailscale address to watch from another machine","127.0.0.1").option("--port <n>","HTTP server port; 0 picks a free one","8766").addHelpText("after",`
|
|
1696
1703
|
Example:
|
|
1697
1704
|
scriptctl soundtrack-view -w ./workspace --host 192.168.1.20
|
|
1698
|
-
`).action(j(
|
|
1705
|
+
`).action(j(yE,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(j(rx,t)),up(e.command("checkout")).description("Download a remote script into a managed local copy").option("--discard-local","Replace an existing dirty local copy").action(j(AE,t)),te(e.command("status"),"read").description("Show local working-copy state").action(j(kE,t)),up(e.command("publish")).description("Validate and publish the local working copy").action(j(bE,t)),te(e.command("create")).description("Create an empty script").option("--title <title>","Script title").option("--force","Replace an existing script file").action(j(Ix,t)),te(e.command("audit-assets"),"read").description("Audit asset consistency with an LLM").option("--llm-config <path>","LLM configuration file").option("-o, --output <path>","Audit JSON output file").action(j(r=>ux(r,n),t));let i=e.command("synopsis").description("Generate synopsis fields with an LLM").action(()=>i.outputHelp());te(i.command("generate")).description("Generate synopsis fields with an LLM").option("--model <profile>","Use this LLM profile for all synopsis stages").option("--llm-config <path>","LLM configuration file").option("--concurrency <n>","Maximum concurrent model calls","30").option("--checkpoint <dir>","Checkpoint directory").option("--overwrite","Regenerate existing synopsis fields").option("--apply","Write generated fields").option("-n, --dry-run","Generate a preview without writing").action(j(r=>Dx(r,n),t))}function bR(e,t=pn){let n=new AR("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(ar(),"-v, --version","Show the scriptctl version");return vE(n,e,t),$h(n,e),Vm(n,e),Th(n,e),ug(n,e),n}function ad(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 RE(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=ad(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 vR(e,t){return t==="--"?!0:t.startsWith("--")?ad(e,t)!==void 0:RE(e,t).recognized}function OE(e,t,n){return n===void 0||n==="--"?!1:t.required?!vR(e,n):t.optional&&!n.startsWith("-")}function OR(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=ad(n,i);s&&!i.includes("=")&&OE(n,s,t[o+1])&&(o+=1);continue}if(i.startsWith("-")){let s=RE(n,i);if(s.recognized&&s.json)return!0;s.recognized&&s.valueOption&&!s.hasAttachedValue&&OE(n,s.valueOption,t[o+1])&&(o+=1);continue}let r=n.commands.find(s=>s.name()===i);r&&(n=r)}return!1}function RR(e,t){let n=e;for(let r=0;r<t.length;r+=1){let s=t[r];if(s.startsWith("-")){let c=ad(n,s);c&&!s.includes("=")&&(c.required||c.optional)&&(r+=1);continue}let a=n.commands.find(c=>c.name()===s);if(!a)break;n=a}let o=[],i=n;for(;i&&i.parent;)o.unshift(i.name()),i=i.parent;return["scriptctl",...o,"--help"].join(" ")}function MR(e){return e.message.replace(/^error:\s*/i,"").replace(/\.$/,"")}async function x3(e=null,t=pn){zm();let n=e??process.argv.slice(2),o={jsonMode:!1,exitCode:V},i=bR(o,t);if(o.jsonMode=OR(i,n),n.length===0)return i.outputHelp(),V;try{return await i.parseAsync(n,{from:"user"}),o.exitCode}catch(r){if(r instanceof kR)return r.code==="commander.help"||r.code==="commander.helpDisplayed"||r.code==="commander.version"?V:ds(new S(MR(r),{exitCode:B,errorCode:"USAGE_ERROR",hint:`Run '${RR(i,n)}'.`}),o.jsonMode);if(r instanceof S)return ds(r,o.jsonMode);if(r instanceof T)return ds(new S(An(r.failure),{exitCode:70,errorCode:"RUNTIME_ERROR"}),o.jsonMode);let s=r instanceof Error?r.message:String(r);return ds(new S(s,{exitCode:70,errorCode:"RUNTIME_ERROR"}),o.jsonMode)}}export{bR as a,x3 as b};
|