agent-yes 1.303.1 → 1.304.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 +54 -0
- package/default.config.yaml +5 -5
- package/dist/{JsonlStore-BpYZZTap.js → JsonlStore-CB_0sfdT.js} +5 -4
- package/dist/{SUPPORTED_CLIS-Dq9Lq9WJ.js → SUPPORTED_CLIS-C_1IiOj3.js} +2 -2
- package/dist/SUPPORTED_CLIS-Do3GHAY1.js +12 -0
- package/dist/{agentShare-suB6yPgO.js → agentShare-BvpEm-Fr.js} +10 -9
- package/dist/{askCli-BU3CNCLU.js → askCli-KmMf-3wA.js} +6 -6
- package/dist/{browser-BmxN1Ur9.js → browser-BAFPmEvN.js} +2 -2
- package/dist/{callback-Ctj3_Wxp.js → callback-BiSUhjw7.js} +6 -6
- package/dist/callback-SqLD2mMX.js +17 -0
- package/dist/{callbackCore-DSJWhqAe.js → callbackCore-BZ_10zyc.js} +1 -1
- package/dist/{callbackCore-BesbQ6-Z.js → callbackCore-Deve5pv3.js} +1 -1
- package/dist/{channels-j5nWuzlQ.js → channels-Y36S0ccW.js} +2 -2
- package/dist/cli.js +118 -13
- package/dist/{cmdDsh-2LP0grim.js → cmdDsh-DZ8bLsH7.js} +1 -1
- package/dist/cmdKill-CzSBfWmx.js +116 -0
- package/dist/{cmdPs-wc1j85fi.js → cmdPs-DBt23Qz0.js} +11 -10
- package/dist/{cwdConflictWarn-skQSMwEh.js → cwdConflictWarn-y-epQyOj.js} +21 -5
- package/dist/{cwdPassthroughHint-BUbWMoz0.js → cwdPassthroughHint-CzWh0hrw.js} +1 -1
- package/dist/{expose-Dawq1LxC.js → expose-Bhsn5yUz.js} +2 -2
- package/dist/forceKill-BDqxx4uQ.js +44 -0
- package/dist/{forkNested-CavHyWzA.js → forkNested-3heLs5XC.js} +45 -5
- package/dist/{globalPidIndex-CRB5KtyL.js → globalPidIndex-BsjlId-h.js} +6 -5
- package/dist/{globalPidIndex-BftWlg2V.js → globalPidIndex-uoz8Esqz.js} +2 -2
- package/dist/{hist-Cs0KFSUW.js → hist-DY16wm7g.js} +1 -1
- package/dist/{identity-DA7YI9km.js → identity-C0MxfwI2.js} +1 -1
- package/dist/{identity-Bk-aG_xl.js → identity-Ckav3-Up.js} +1 -1
- package/dist/index.js +7 -7
- package/dist/{initMsg-CcTqFtsp.js → initMsg-BEVDWYnv.js} +1 -1
- package/dist/{initMsg-D9KJnfgC.js → initMsg-GPU52N-j.js} +1 -1
- package/dist/liagent/box-BSIrRRc_.js +2320 -0
- package/dist/liagent/box-DloywR57.d.ts +409 -0
- package/dist/liagent/box.d.ts +3 -0
- package/dist/liagent/box.js +3 -0
- package/dist/liagent/cli.d.ts +1 -0
- package/dist/liagent/cli.js +908 -0
- package/dist/liagent/client.d.ts +28 -0
- package/dist/liagent/client.js +240 -0
- package/dist/liagent/echo-BvzPSI0x.js +86 -0
- package/dist/liagent/echo-W2RcMEny.d.ts +38 -0
- package/dist/liagent/hub.d.ts +405 -0
- package/dist/liagent/hub.js +1831 -0
- package/dist/liagent/index.d.ts +14 -0
- package/dist/liagent/index.js +10 -0
- package/dist/liagent/liagent.js +339 -0
- package/dist/liagent/mic-audio-C3Shud_F.js +754 -0
- package/dist/liagent/mic-audio-DMCWtEI-.d.ts +317 -0
- package/dist/liagent/mic-button-CtZHFBSG.js +651 -0
- package/dist/liagent/mic-button-Y0ioPetQ.d.ts +248 -0
- package/dist/liagent/mic.d.ts +3 -0
- package/dist/liagent/mic.js +4 -0
- package/dist/liagent/progress-CJs08bXb.js +473 -0
- package/dist/liagent/progress-CfE-meHr.d.ts +205 -0
- package/dist/liagent/progress.d.ts +2 -0
- package/dist/liagent/progress.js +3 -0
- package/dist/liagent/protocol.d.ts +324 -0
- package/dist/liagent/protocol.js +504 -0
- package/dist/liagent/speech-rate-DXeJjRTc.js +42 -0
- package/dist/liagent/state-tree-BZCmAknI.js +353 -0
- package/dist/liagent/tree-BrR7NwMf.js +710 -0
- package/dist/liagent/tree-HB9RhX_H.d.ts +295 -0
- package/dist/liagent/tree.d.ts +2 -0
- package/dist/liagent/tree.js +4 -0
- package/dist/liagent/ui-strings-B03le3fh.d.ts +27 -0
- package/dist/liagent/ui-strings-CJIwW5Gf.js +794 -0
- package/dist/liagent/ui.d.ts +394 -0
- package/dist/liagent/ui.js +5 -0
- package/dist/liagent/voice-D7yeS9VM.js +802 -0
- package/dist/liagent/voice-Qo7SCgi8.d.ts +308 -0
- package/dist/liagent/voice.d.ts +3 -0
- package/dist/liagent/voice.js +4 -0
- package/dist/{notifyDaemon-C7GlfJ1E.js → notifyDaemon-DkUB7GV2.js} +10 -9
- package/dist/{openBrowser-1cIo4dJL.js → openBrowser-CQAOIrD6.js} +1 -1
- package/dist/oxmgrService-DlYHmqyI.js +37 -0
- package/dist/oxmgrService-o9L3I6FX.js +3 -0
- package/dist/{parentLink-DoEWVGld.js → parentLink-BcAYcO9L.js} +2 -2
- package/dist/{parentLink-B58V1RVd.js → parentLink-MBUD3oY2.js} +2 -2
- package/dist/{parentPingLoop-C73bbmCE.js → parentPingLoop-DDO592Wh.js} +5 -5
- package/dist/{pidStore-433kvh9D.js → pidStore-C50VPk3E.js} +3 -3
- package/dist/pidStore-COkPjpW8.js +6 -0
- package/dist/{procStats-BvmrBrOs.js → procStats-DwTxj3rs.js} +1 -1
- package/dist/{remotes-MfdV9M8u.js → remotes-BqLoB5GR.js} +2 -2
- package/dist/{remotes-DevcBeLl.js → remotes-BsMGvAay.js} +3 -3
- package/dist/{roomReplyAlias-DFqg_6IU.js → roomReplyAlias-B-v76TA8.js} +3 -3
- package/dist/roomReplyAlias-BzWUBkQy.js +6 -0
- package/dist/{rustBinary-7VK7oLlW.js → rustBinary-BrJ2p8wy.js} +2 -2
- package/dist/{rustBinary-BV4LxMMn.js → rustBinary-vpfpWj1q.js} +2 -2
- package/dist/{schedule-Dp0qkNO1.js → schedule-Bzjhl6-h.js} +15 -44
- package/dist/schedulesCli-CLqieyQZ.js +784 -0
- package/dist/senderAncestry-CVHeKk1Y.js +173 -0
- package/dist/senderAncestry-KhAUPCQs.js +3 -0
- package/dist/{serve-BpOIIOVc.js → serve-XwFYE0cE.js} +67 -69
- package/dist/{serveRust-CbBrcUrg.js → serveRust-BfWkeL6T.js} +31 -4
- package/dist/{setup-DdIBk6Iv.js → setup-D4-s2VZw.js} +5 -5
- package/dist/{share-w5oRbvlj.js → share-CbFetL5H.js} +1 -1
- package/dist/{share-DrS3LYqf.js → share-_TPYAGWC.js} +1 -1
- package/dist/{shareCmd-DDENkBW2.js → shareCmd-DUBsVI3e.js} +10 -10
- package/dist/spawnGate-Dfj9V76w.js +5 -0
- package/dist/{spawnGate-lr3tvA6U.js → spawnGate-Dj_WaS29.js} +3 -3
- package/dist/{subcommands-DxgvDmZX.js → subcommands-B7YZJL8n.js} +471 -307
- package/dist/subcommands-BZPxFgkT.js +15 -0
- package/dist/{systemPathLink-SjUzgSiq.js → systemPathLink-Y3iC7bYV.js} +1 -1
- package/dist/{terminal-C2h7tpe0.js → terminal-13cGj3h6.js} +2 -2
- package/dist/terminal.js +1 -1
- package/dist/{todoAutomation-TTp_Qz9G.js → todoAutomation-CKlrxuZv.js} +2 -2
- package/dist/{todoCli-BWm5nZE0.js → todoCli-CU9vSJSJ.js} +6 -6
- package/dist/{todoIdentity-BvXZKWJI.js → todoIdentity-CzS1e7VL.js} +2 -2
- package/dist/{todoStore-C9RTz0Vs.js → todoStore-msRCEUi1.js} +2 -2
- package/dist/{tray-BeRSozJz.js → tray-CLktEN3G.js} +1 -1
- package/dist/{trayApp-QQjqhDv1.js → trayApp-5_OlvQcz.js} +2 -2
- package/dist/trayApp-DkAPo0m6.js +5 -0
- package/dist/{ts-6LF7f4fx.js → ts-njuddXQz.js} +126 -57
- package/dist/{versionChecker-Bc62HNf6.js → versionChecker-BJycAanp.js} +2 -2
- package/dist/{webrtcLink-va_gAR77.js → webrtcLink-DcvacEci.js} +1 -1
- package/dist/{webrtcLink-SsInrVHU.js → webrtcLink-WxS1nTIs.js} +1 -1
- package/dist/{webrtcRemote-BlGyNZDC.js → webrtcRemote-C3xQyf3u.js} +2 -2
- package/dist/{widget-Crb5zeHL.js → widget-DmRwOlco.js} +3 -3
- package/dist/widgets.js +1 -1
- package/dist/{workspaceConfig-BLWB5Wu9.js → workspaceConfig-DBgsu81B.js} +1 -1
- package/dist/{ws-DIbwNz8Z.js → ws-ByO6JO6m.js} +3 -3
- package/dist/{ws-BRhPG1Vy.js → ws-D0-Jg88z.js} +9 -8
- package/lab/ui/index.html +1 -1
- package/lab/ui/lab/posts/2026-08-11-slack-term-safe-writes.md +1 -1
- package/package.json +73 -8
- package/ts/JsonlStore.ts +10 -3
- package/ts/cli-idle.bun.spec.ts +1 -1
- package/ts/cli-idle.spec.ts +1 -1
- package/ts/cli.ts +35 -0
- package/ts/cmdKill.bun.spec.ts +155 -0
- package/ts/cmdKill.spec.ts +155 -0
- package/ts/cmdKill.ts +183 -0
- package/ts/composerGuard.edges.spec.ts +91 -0
- package/ts/composerGuard.spec.ts +53 -6
- package/ts/composerGuard.ts +42 -13
- package/ts/conptyModeFilter.spec.ts +30 -0
- package/ts/conptyModeFilter.ts +53 -0
- package/ts/copyLiagent.ts +42 -0
- package/ts/cwdConflictWarn.io.spec.ts +50 -0
- package/ts/cwdConflictWarn.spec.ts +34 -1
- package/ts/cwdConflictWarn.ts +43 -5
- package/ts/cwdGuard.spec.ts +110 -0
- package/ts/cwdGuard.ts +118 -0
- package/ts/forceKill.ts +52 -0
- package/ts/forkNested.bun.spec.ts +41 -0
- package/ts/forkNested.spec.ts +41 -0
- package/ts/forkNested.ts +48 -1
- package/ts/globalPidIndex.edges.spec.ts +125 -0
- package/ts/globalPidIndex.ts +6 -2
- package/ts/index.ts +13 -1
- package/ts/interruptSend.bun.spec.ts +99 -0
- package/ts/interruptSend.spec.ts +99 -0
- package/ts/interruptSend.ts +51 -0
- package/ts/lockRegistry.spec.ts +49 -0
- package/ts/lsRenderCache.spec.ts +58 -0
- package/ts/needsInput.edges.spec.ts +23 -0
- package/ts/parseCliArgs.ts +7 -0
- package/ts/pushGatePlan.spec.ts +147 -0
- package/ts/roomReplyAlias.io.spec.ts +81 -0
- package/ts/schedule.ts +5 -1
- package/ts/schedules.bun.spec.ts +397 -0
- package/ts/schedules.spec.ts +397 -0
- package/ts/schedules.ts +517 -0
- package/ts/schedulesCli.ts +386 -0
- package/ts/sendControl.bun.spec.ts +12 -0
- package/ts/senderAncestry.ts +1 -3
- package/ts/serve.ts +22 -33
- package/ts/serveRust.spec.ts +29 -2
- package/ts/serveRust.ts +27 -2
- package/ts/sizeNego.bun.spec.ts +9 -2
- package/ts/sizeNego.spec.ts +9 -2
- package/ts/sizeNego.ts +10 -5
- package/ts/subcommands.spec.ts +348 -9
- package/ts/subcommands.ts +513 -93
- package/ts/suggestAgents.spec.ts +33 -0
- package/ts/terminal/browser.ts +1 -1
- package/ts/todoParse.spec.ts +22 -1
- package/ts/todoParse.ts +19 -0
- package/dist/SUPPORTED_CLIS-ByO5twge.js +0 -12
- package/dist/callback-D7qfh_7p.js +0 -16
- package/dist/pidStore-BRlKRHXY.js +0 -6
- package/dist/roomReplyAlias-DuEkSSDI.js +0 -6
- package/dist/spawnGate-DeQBTX-o.js +0 -5
- package/dist/subcommands-DmiswRy4.js +0 -14
- package/dist/trayApp-C4TAvRvU.js +0 -5
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
var po=16384,go=4000,fo=300,ho=120000,mo=3600000,yo=28800000,bo=2592000000,He=4000,xo=200,kt=12000,wt=1500,vo=300000,ko=(e)=>typeof e==="string"&&/^[A-Za-z0-9_-]{6,64}$/.test(e),St=300,wo=3;function Et(e,t){if(e.id!==t.id||(e.thread??"owner")!==t.thread)return e;return{...e,text:t.text,raw:t.raw,edited:t.edited}}function Tt(e,t,n){return!e.trim()||e===t?n:null}function At(e,t){return t!==null&&e===t&&!!e.trim()?"stt":void 0}var H=(e,t)=>typeof e==="string"?e.slice(0,t):void 0;function Mt(e){if(typeof e!=="string"||e.length>18432)return null;try{let t=JSON.parse(e);return t&&typeof t==="object"&&!Array.isArray(t)?t:null}catch{return null}}function Ve(e){if(typeof e!=="string")return;let t=e.trim();return t&&t.length<=4000?t:void 0}function So(e){let t=Mt(e);if(t?.type==="say"){let r=Ve(t.text);if(!r)return{ok:!1,error:`say needs text of 1–${4000} chars`};let s=H(t.to,320)?.trim(),i;if(s?.startsWith("/")||typeof t.node==="string"){if(i=K(typeof t.node==="string"?t.node:s),!i)return{ok:!1,error:`not a node path: ${String(t.node??s)}`};if(s?.startsWith("/"))s=void 0;if(i===P)i=void 0}let o=t.taskPath===void 0?void 0:K(t.taskPath);if(t.taskPath!==void 0&&!o)return{ok:!1,error:`not a node path: ${String(t.taskPath)}`};let a=Br(t.agentId),l={type:"say",text:r};if(s)l.to=s;if(i)l.node=i;if(o&&o!==P)l.taskPath=o;if(a)l.agentId=a;return{ok:!0,value:l}}if(t?.type==="edit"){let r=H(t.id,64)?.trim();if(!r)return{ok:!1,error:"edit needs the id of the message to polish"};let s=Ve(t.text);if(!s)return{ok:!1,error:`edit needs text of 1–${4000} chars`};return{ok:!0,value:{type:"edit",id:r,text:s}}}if(t?.type==="grant"||t?.type==="ungrant"){let r=K(t.from),s=K(t.to);if(!r||!s)return{ok:!1,error:`${t.type} needs node paths "from" and "to"`};if(t.type==="ungrant")return{ok:!0,value:{type:"ungrant",from:r,to:s}};let i=typeof t.ms==="number"&&t.ms>0?Math.min(t.ms,2592000000):void 0;return{ok:!0,value:i?{type:"grant",from:r,to:s,ms:i}:{type:"grant",from:r,to:s}}}if(t?.type==="busy"){let r=H(t.to,320),s={type:"busy"};if(r)s.to=r;if(t.on===!1)s.on=!1;return{ok:!0,value:s}}if(!t||t.type!=="eval")return{ok:!1,error:'expected {"type":"say","text":"…"}, {"type":"eval","code":"…"}, {"type":"edit","id","text"} or {"type":"grant","from","to"}'};if(typeof t.code!=="string"||!t.code.trim())return{ok:!1,error:"empty code"};if(t.code.length>16384)return{ok:!1,error:"code over 16384 chars"};let n=H(t.target,300);return{ok:!0,value:n?{type:"eval",code:t.code,target:n}:{type:"eval",code:t.code}}}function Eo(e){let t=Mt(e);if(!t)return null;if(t.type==="allow"){let n=H(t.pair,64);if(!n)return null;let r={type:"allow",pair:n};if(t.pages==="all")r.pages="all";else if(Array.isArray(t.pages))r.pages=t.pages.filter((s)=>typeof s==="string"&&s.length>0&&s.length<=64).slice(0,64);if(t.scope==="chat")r.scope="chat";return r}if(t.type==="page"){let n=typeof t.label==="string"?t.label.slice(0,300):void 0;return n?{type:"page",label:n}:null}if(t.type==="end-page"){let n=H(t.id,64);return n?{type:"end-page",id:n}:null}if(t.type==="deny"||t.type==="revoke"){let n=H(t.pair,64);return n?{type:t.type,pair:n}:null}if(t.type==="chat"){let n=H(t.id,64),r=Ve(t.text);if(!n||!r)return null;let s=K(t.to),i={type:"chat",id:n,text:r};if(s&&s!==P)i.to=s;if(t.source==="stt")i.source="stt";return i}if(t.type==="result"){let n=H(t.id,64),r=H(t.to,64);if(!n||!r)return null;return{type:"result",id:n,to:r,ok:t.ok===!0,value:H(t.value,4064),error:H(t.error,1000),stack:H(t.stack,2000),ms:typeof t.ms==="number"?t.ms:void 0}}return null}function te(e,t=200){return e.length>t?e.slice(e.length-t):e}function me(e){if(/[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e))return"ja-JP";if(/\p{Script=Hangul}/u.test(e))return"ko-KR";if(/\p{Script=Han}/u.test(e))return"zh-CN";return"en-US"}function _t(e,t){let n=(l)=>l.replace(/_/g,"-").toLowerCase(),r=n(t),s=r.split("-")[0],i=e.filter((l)=>n(l.lang)===r),o=e.filter((l)=>n(l.lang).split("-")[0]===s),a=i.length?i:o;return a.find((l)=>l.default)??a[0]}function To(e,t=300){return(e??"").replace(/[\u0000-\u001f\u007f]+/g," ").trim().slice(0,t)}function Ao(e){return Array.from(e.slice(0,2),(t)=>t.toString(16).padStart(2,"0")).join("")}function Mo(e,t){if(!t)return!0;return e.toLowerCase().includes(t.toLowerCase())}function Ct(e,t=4000){let n=new WeakSet,r;try{r=JSON.stringify(e,(s,i)=>{if(typeof i==="bigint")return`${i}n`;if(typeof i==="function")return`[function ${i.name||"anonymous"}]`;if(typeof i==="symbol")return i.toString();if(i===void 0)return"[undefined]";if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(typeof i==="object"&&i!==null){let o=i;if(typeof o.nodeType==="number")return typeof o.outerHTML==="string"?o.outerHTML.slice(0,500):`[node ${String(o.nodeName)}]`;if(n.has(i))return"[circular]";if(n.add(i),i instanceof Map)return{"[Map]":[...i.entries()]};if(i instanceof Set)return{"[Set]":[...i.values()]}}return i})}catch(s){r=`[unserialisable: ${s instanceof Error?s.message:String(s)}]`}return r??="[undefined]",r.length>t?`${r.slice(0,t)}…[${r.length-t} more]`:r}function Lt(e){try{return Function(`return (async () => (
|
|
2
|
+
${e}
|
|
3
|
+
))();`)}catch(t){if(!(t instanceof SyntaxError))throw t;return Function(`return (async () => {
|
|
4
|
+
${e}
|
|
5
|
+
})();`)}}var vt=80,Hr=40,P="/",Ur=/^[A-Za-z0-9._~-]+$/;function K(e){if(typeof e!=="string")return;let t=e.trim();if(!t||t.length>vt*2)return;let n=t.split(/\s*[/›]\s*/).filter(Boolean);if(n.some((s)=>!Ur.test(s)||s==="."||s===".."))return;let r=`/${n.join("/")}`;return r.length<=vt?r:void 0}function Br(e){if(typeof e!=="string")return;let t=e.trim().slice(0,Hr).trim();return/^[\w.@:+ -]+$/.test(t)?t:void 0}function ee(e,t){return t===P||e===t||e.startsWith(`${t}/`)}function Wr(e,t){let n=e.split("/").filter(Boolean),r=t.split("/").filter(Boolean),s=[];for(let i=0;i<Math.min(n.length,r.length)&&n[i]===r[i];i++)s.push(n[i]??"");return`/${s.join("/")}`}function z(e){let t=e.split("/").filter(Boolean);return t.length?`/${t.join(" › ")}`:P}function _o(e,t){let n=e??P,r=t??P;if(n===r)return"direct";return ee(r,n)?"observed":null}function Co(e,t,n=[],r=Date.now()){if(ee(t,e))return{ok:!0,via:"subtree"};if(ee(e,t))return{ok:!0,via:"upward"};if(n.some((s)=>s.until>r&&ee(e,s.from)&&ee(t,s.to)))return{ok:!0,via:"grant"};return{ok:!1,error:`out of scope: needs a grant from ${Wr(e,t)}`}}var Kr=/^@(\/?(?:[A-Za-z0-9._~-]+(?:(?:\/|\s*›\s*)[A-Za-z0-9._~-]+)*)?\/?)(?:\s+([\s\S]*))?$/;function X(e){if(!e.startsWith("@/"))return null;let t=Kr.exec(e);if(!t)return null;let n=K(t[1]||P);if(!n)return null;if(t[2]===void 0||t[2].startsWith("›"))return{to:n,text:"",complete:!1};return{to:n,text:t[2].trim(),complete:!0}}function Pt(e,t){let n=e.replace(/^@/,"").replace(/\s*›\s*/g,"/").trim().toLowerCase();return[...new Set(t)].filter((r)=>r!==P&&r.toLowerCase().startsWith(n||"/")).sort((r,s)=>r.length-s.length||r.localeCompare(s)).slice(0,8)}function zr(e){let t=2166136261,n=`node:${e}`;for(let r=0;r<n.length;r++)t^=n.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0)%360}function Ue(e){let t=e.from==="agent"&&e.taskPath&&e.taskPath!==P?e.taskPath:"",n=e.to&&e.to!==P?e.to:"";if(!t&&!n)return null;let r=t?n?`${z(t)} → ${z(n)}`:z(t):`→ ${z(n)}`,s=t||n;return{node:s,subtitle:r,border:`oklch(0.7 0.09 ${zr(s)})`}}var ne=3000;var Gr=/[。..!?!?]$/;function Nt(e,t){if(e.key!=="Enter"||e.shiftKey)return!1;return!(e.isComposing||t||e.keyCode===229)}function Rt(e,t){if(e!=="insertLineBreak"&&e!=="insertParagraph")return!1;return!(t.composing||t.isComposing||t.shiftEnter)}function It(e,t,n){if(n)return"idle";if(e.length-t>10&&Gr.test(e.trim()))return"send";return e.trim()?"arm":"idle"}var Yr=/^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul} -〿-]/u,jr=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul} -〿-]$/u;function Ot(e,t){let n=(t??"").trim();if(!n)return"";if(!e||/\s$/.test(e)||jr.test(e)||Yr.test(n))return n;return` ${n}`}var No="owner";var Xr=/^(\s*)[-*+]\s+(.*)$/,qr=/^##\s+(.*)$/,$t=/^(?:→|->)\s*(.*)$/,Ft=/^≈([A-Za-z]{2,3}(?:-[A-Za-z0-9]+)?)?\s+(.*)$/,Zr=/^\[([ xX~!])\]\s*/,Be=/\(!\)/g,We=/\(any order\)/gi,Jr=/\(done\s+(\d{4}-\d{2}-\d{2}(?:[T ][\d:]+)?)\)/i,Qr=/(?:^|\s)@([A-Za-z0-9][\w.-]*)(?:#(\S*))?$/,es=/^[A-Za-z0-9_-]{1,40}$/,ts={" ":"open","~":"doing","!":"blocked",x:"done",X:"done"};function re(e,t={}){let n=(t.host??"https://github.com").replace(/\/$/,""),r=[],s=new Set,i=(a)=>{if(s.has(a.url))return;s.add(a.url),r.push(a)},o=/(https?:\/\/[^\s)>\]]+)|(?<![\w/#])([A-Za-z0-9][\w.-]*\/[\w.-]+)#(\d+)\b|(?<![\w/&#])#(\d+)\b/g;for(let a of e.matchAll(o))if(a[1]){let l=a[1].replace(/[.,;:]+$/,"");i({text:l,url:l})}else if(a[2])i({text:`${a[2]}#${a[3]}`,url:`${n}/${a[2]}/pull/${a[3]}`});else if(a[4]&&t.repo)i({text:`#${a[4]}`,url:`${n}/${t.repo}/pull/${a[4]}`});return r}var Dt=(e)=>e.replaceAll("\t"," ").length;function ns(e,t){if(e==="owner")return{type:"human",name:e};return t&&es.test(t)?{type:"agent",name:e,id:t}:{type:"agent",name:e}}function Vt(e,t){let n=e.trim(),r,s=Zr.exec(n);if(s)r=ts[s[1]],n=n.slice(s[0].length);let i=Be.test(n);if(Be.lastIndex=0,i)n=n.replace(Be," ");let o=We.test(n);if(We.lastIndex=0,o)n=n.replace(We," ");let a=Jr.exec(n);if(a)n=n.replace(a[0]," ");n=n.replace(/\s+/g," ").trim();let l=Qr.exec(n);if(l)n=n.slice(0,l.index).trim();let c={title:n,links:re(n,t),children:[]};if(r)c.status=r,c.done=r==="done";if(i)c.needsOwner=!0;if(o)c.unordered=!0;if(a)c.doneAt=a[1].replace(" ","T");if(l)c.assignee=ns(l[1],l[2]);return c}function rs(e){let t={};for(let n of e.split(/\s*[·|]\s*/)){let r=/^(done|doing|next)\s*[::]\s*(.+)$/i.exec(n.trim());if(r)t[r[1].toLowerCase()]=r[2].trim()}return t}function Ht(e,t,n){let r=rs(n);if(!Object.keys(r).length)return;e.summaries??={};let s=(t??"zh").toLowerCase();e.summaries[s]={...e.summaries[s],...r}}function Wt(e,t){for(let n of e){if(!n.assignee&&t)n.assignee=t;Wt(n.children,n.assignee)}}function ze(e,t={}){let n={title:"",links:[],children:[]},r=[],s=null,i=null,o=e.replace(/\r\n?/g,`
|
|
6
|
+
`).replace(/<!--[\s\S]*?(?:-->|$)/g,"");for(let a of o.split(`
|
|
7
|
+
`)){if(!a.trim())continue;let l=qr.exec(a);if(l){s=Vt(l[1],t),n.children.push(s),r=[],i={indent:-1,node:s};continue}if(/^#\s/.test(a)){s=null,r=[],i=null;continue}let c=Xr.exec(a);if(c&&!$t.test(c[2])&&!Ft.test(c[2])){let y=Dt(c[1]),b=Vt(c[2],t);while(r.length&&r[r.length-1].indent>=y)r.pop();(r.length?r[r.length-1].node:s??n).children.push(b),r.push({indent:y,node:b}),i={indent:y,node:b};continue}let u=Dt(/^\s*/.exec(a)[0]),p=a.trim().replace(/^[-*+]\s+/,""),d=Ft.exec(p);if(d&&!i&&!n.children.length){Ht(n,d[1],d[2]);continue}let g=$t.exec(p),f=!!i&&(i.indent<0||u>i.indent);if(!f&&(!s||g))continue;let m=f?i.node:s;if(d)Ht(m,d[1],d[2]);else if(g){let y=g[1].trim();if(!y)continue;m.action=m.action?`${m.action}
|
|
8
|
+
${y}`:y;for(let b of re(y,t))if(!m.links.some((S)=>S.url===b.url))m.links.push(b)}else m.note=m.note?`${m.note} ${p}`:p}return Wt(n.children,n.assignee),n}function Ro(e,t={}){return ze(e,t).children}function q(e){let t=0,n=0;for(let r of e.children){if(r.done===!1){if(t++,r.needsOwner)n++}let s=q(r);t+=s.open,n+=s.needsOwner}return{open:t,needsOwner:n}}function Ge(e){let t=[];for(let n of e){let r=Ge(n.children);if(n.needsOwner&&n.done!==!0||r.length)t.push({...n,children:r})}return t}var ss={doing:0,open:1,blocked:2,done:3},Ut=(e)=>e.status?ss[e.status]:1;function is(e){let t=[],n=(r,s)=>{let i=r.unordered?r.children.map((a,l)=>[a,l]).sort((a,l)=>Ut(a[0])-Ut(l[0])||a[1]-l[1]).map(([a])=>a):r.children,o=[...s,r];for(let a of i){if(a.status){let l=o.map((c)=>c.title).filter(Boolean);t.push({node:a,path:l,title:a.title,assignee:a.assignee,chain:o})}n(a,o)}};return n(e,[]),t}function os(e){let t=(e??"").toLowerCase();return[...new Set([t,t.split("-")[0]??"","zh","en"].filter(Boolean))]}function as(e,t,n){let r=e[0].chain;for(let s of e){let i=0;while(i<r.length&&i<s.chain.length&&r[i]===s.chain[i])i++;r=r.slice(0,i)}for(let s=r.length-1;s>=0;s--){let i=r[s].summaries;if(!i)continue;for(let o of n)if(i[o]?.[t])return i[o][t]}return}function Bt(e){let t={node:e.node,path:e.path,title:e.title};if(e.assignee)t.assignee=e.assignee;return t}function Ke(e,t,n,r){let s={...Bt(t),count:e.length,items:e.map(Bt)};if(e.length>1){let i=as(e,n,r);if(i)s.summary=i}return s}function se(e,t={}){let n=Array.isArray(e)?{title:"",links:[],children:e}:e;for(let u of t.scope??[]){let p=n.children.find((d)=>d.title===u);if(!p)return{};n=p}let r=os(t.locale),s=is(n),i={},o=s.filter((u)=>u.node.status==="done");if(o.length){let u=o.filter((d)=>d.node.doneAt),p=u.length?u.reduce((d,g)=>g.node.doneAt>=d.node.doneAt?g:d):o[o.length-1];i.done=Ke(o,p,"done",r)}let l=[...s.filter((u)=>u.node.needsOwner&&u.node.status!=="done"),...s.filter((u)=>u.node.status==="doing"&&!u.node.needsOwner)];if(l.length)i.doing=Ke(l,l[0],"doing",r);let c=s.filter((u)=>u.node.status==="open"&&!u.node.needsOwner);if(c.length){let u=i.doing&&!i.doing.node.needsOwner?s.indexOf(l[0]):-1,p=c.find((d)=>s.indexOf(d)>u)??c[0];i.next=Ke(c,p,"next",r)}return i}var ie=(e)=>e.join(" › ");var ls=["doing","blocked","waiting","waiting-owner","review","done"],cs=["task","decision","approval","feedback","person","group"],us=["agent","human"];var ds=200,ps=20;var gs="/@owner";var fs=(e)=>e.startsWith(`${gs}/`);var Kt=(e)=>e.startsWith("/");var Ye=(e)=>{if(!e||typeof e!=="object")return!1;let t=e,n=t.assignee;return typeof t.id==="string"&&!!n&&typeof n.name==="string"&&us.includes(n.type)&&typeof t.task==="string"&&ls.includes(t.status)&&cs.includes(t.kind)&&typeof t.at==="number"};function zt(e){let t;try{t=typeof e==="string"?JSON.parse(e):null}catch{return null}if(!t||typeof t!=="object")return null;let n=t;if(n.type==="snapshot"&&Array.isArray(n.entries))return{type:"snapshot",entries:n.entries.filter(Ye),log:(Array.isArray(n.log)?n.log:[]).filter(Ye)};if(n.type==="progress"&&Ye(n))return n;return null}function Gt(e,t){if(t.type==="snapshot")return{rows:[...t.entries].sort((l,c)=>c.at-l.at),log:t.log};let{type:n,note:r,...s}=t,o=[...e.rows.find((l)=>l.id===t.id)?.notes??[]];if(r)o.push({at:t.at,by:t.by,text:r});return{rows:[{...s,...o.length?{notes:o.slice(-ps)}:{}},...e.rows.filter((l)=>l.id!==t.id)].sort((l,c)=>c.at-l.at),log:[...e.log,t].slice(-ds)}}var Yt=(e)=>e.status!=="done";var jt=(e,t=new Set)=>Yt(e)&&(e.kind==="decision"||e.kind==="approval"||e.status==="waiting-owner"||!!e.needs?.trim()||t.has(e.id));function Xt(e){let t=new Set;for(let n of e)if(fs(n.id)&&Yt(n)&&n.ref)t.add(n.ref);return t}var hs={doing:"doing",review:"doing",blocked:"blocked",waiting:"open","waiting-owner":"open",done:"done"},je=(e)=>e.toLowerCase().replace(/[^a-z0-9@/_]+/g,"-").replace(/^-+|-+$/g,""),qt=(e)=>e.replace(/^\//,""),ms=(e,t)=>{let n=e.trim().split(/\s+/)[0]??"";return qt(je(n))===t||qt(je(e))===t};function ys(e){return[e.pct!=null?`${e.pct}%`:"",e.eta?`ETA ${e.eta}`:"",e.needs?`needs: ${e.needs}`:"",e.notes?.at(-1)?.text??""].filter(Boolean).join(" · ")}function bs(e,t,n,r){if(e.status=hs[t.status],e.done=t.status==="done",n)e.needsOwner=!0;else delete e.needsOwner;if(e.assignee={type:t.assignee.type,name:t.assignee.name},t.action)e.action=t.action;let s=ys(t);if(s)e.note=e.note?`${s}
|
|
9
|
+
${e.note}`:s;let i=[...t.pr?re(`#${t.pr}`,r):[],...t.link?[{text:t.link,url:t.link}]:[],...t.action?re(t.action,r):[]];for(let o of i)if(!e.links.some((a)=>a.url===o.url))e.links.push(o)}var Zt=(e)=>({...e,links:[...e.links],children:e.children.map(Zt)});function Xe(e,t,n={}){let{liveTitle:r="Live",...s}=n,i=Zt(e),o=new Map(t.map((p)=>[p.id,p])),a=Xt(t),l=(p,d,g)=>{let f=d;return p.forEach((m,y)=>{let b=f.children.find((S)=>ms(S.title,m));if(!b)b={title:g(y),links:[],children:[]},f.children.push(b);f=b}),f},c=(p,d)=>{let g=o.get(`/${p.slice(0,d+1).join("/")}`);if(g&&g.kind!=="person"&&g.kind!=="group")return g.task;return d===0&&!p[0].startsWith("@")?`/${p[0]}`:p[d]},u=[...t].sort((p,d)=>p.id.split("/").length-d.id.split("/").length);for(let p of u){if(p.kind==="group"||p.kind==="person")continue;let d;if(Kt(p.id)){let g=p.id.slice(1).split("/");d=l(g,i,(f)=>c(g,f))}else{let g=l([je(r)],i,()=>r);d=g.children.find((f)=>f.title===p.task)??l([p.id],g,()=>p.task)}bs(d,p,jt(p,a),s)}return i}var xs=60000,vs=10;function ks(e,t){let n=new URL(e,t??globalThis.location?.href);if(n.protocol==="https:")n.protocol="wss:";if(n.protocol==="http:")n.protocol="ws:";return n.toString()}var ws=(e)=>{if(typeof window>"u"||typeof document>"u")return()=>{};let t=()=>document.visibilityState==="visible"&&e();return window.addEventListener("online",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("online",e),document.removeEventListener("visibilitychange",t)}};function ye(e){let t=e.socket??((o)=>new WebSocket(o)),n=e.setTimeout??((o,a)=>setTimeout(o,a)),r=e.clearTimeout??((o)=>clearTimeout(o)),s=e.onWake??ws,i=new Set;return{resolve(o,a){let l=i.values().next().value;if(!l)return!1;try{return l.send?.(JSON.stringify(a?{type:"resolve",id:o,note:a}:{type:"resolve",id:o})),!0}catch{return!1}},subscribe(o){let a={rows:[],log:[]},l=!1,c=null,u,p=0,d=!1,g=()=>{if(u!==void 0)r(u);if(u=void 0,d||c)return;let m=t(ks(e.url));c=m,m.onopen=()=>{p=0,i.add(m)},m.onmessage=(b)=>{let S=zt(b.data);if(!S||d)return;a=Gt(a,S),l=!0,o(a,!0)};let y=()=>{if(i.delete(m),c!==m)return;if(c=null,l&&!d)l=!1,o(a,!1);if(d||++p>vs)return;u=n(g,Math.min(xs,1000*2**(p-1)))};m.onclose=y,m.onerror=()=>{y(),m.close()}},f=s(()=>{if(c)return;p=0,g()});return g(),()=>{if(d=!0,u!==void 0)r(u);if(f(),c)i.delete(c);c?.close()}}}}var ve={tree:"Tree",back:"Back to the chat",needsMe:"Needs me",needsYou:"needs you",openCount:"{n} open",needsYouCount:"{n} need you",copy:"Copy",copied:"Copied",loading:"Loading…",failed:"Could not load the tree",empty:"The tree is empty.",nothingNeedsYou:"Nothing waits on you.",you:"you",lastDone:"Last done",nowDoing:"In progress",upNext:"Up next",live:"Live"},en=(e,t)=>typeof e==="string"?ze(e,t):Array.isArray(e)?{title:"",links:[],children:e}:e;async function tn(e,t={}){let n;if(typeof e==="string"){let r=await fetch(e,{credentials:"same-origin",cache:"no-store"});if(!r.ok)throw Error(`HTTP ${r.status}`);n=await r.text()}else n=await e();return en(n,t)}function oe(e,t,n,r){let s=!0;if(typeof e==="object"){let i=e.subscribe((o,a)=>s&&n(en(o,t),!!a?.live),(o)=>s&&r(o));return()=>{s=!1,i()}}return tn(e,t).then((i)=>s&&n(i,!1),(i)=>s&&r(i)),()=>{s=!1}}function nn(e){let{base:t,progress:n,...r}=e,s=typeof n==="string"?ye({url:n}):("subscribe"in n)?n:ye(n);return{subscribe(i,o){let a=null,l=[],c=!1,u=()=>a&&i(Xe(a,l,r),{live:c}),p=oe(t,r,(g)=>{a=g,u()},(g)=>o?.(g)),d=s.subscribe((g,f)=>{l=g.rows,c=f,u()});return()=>{p(),d()}}}}var be="oklch(0.58 0.21 33)",G={open:"oklch(0.62 0.03 260)",doing:"oklch(0.6 0.16 250)",blocked:"oklch(0.7 0.16 70)",done:"oklch(0.62 0.15 150)"},Ss="oklch(0.58 0.15 255)",Es={open:"☐",doing:"◧",blocked:"⊘",done:"☑"},Ts="liagent:tree-needs-me",Jt=`
|
|
10
|
+
:host { display: block; font: 12px/1.35 system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
11
|
+
color: var(--liagent-fg, CanvasText); --bg: var(--liagent-bg, Canvas);
|
|
12
|
+
text-shadow: 0 0 3px var(--bg), 0 0 6px var(--bg); pointer-events: none; }
|
|
13
|
+
* { box-sizing: border-box; }
|
|
14
|
+
ul { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
|
|
15
|
+
ul ul { padding-inline-start: 12px; }
|
|
16
|
+
button { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; position: relative; }
|
|
17
|
+
/* Small controls: a 40px invisible hit area. */
|
|
18
|
+
button.hit::after { content: ""; position: absolute; inset: -10px; }
|
|
19
|
+
.head, .line, .act, .note { pointer-events: auto; }
|
|
20
|
+
.head { display: flex; align-items: center; gap: 8px; font-weight: 600; }
|
|
21
|
+
.head .grow { flex: 1; display: flex; align-items: center; gap: 6px; }
|
|
22
|
+
.dot { width: 6px; height: 6px; border-radius: 50%; background: ${G.done}; }
|
|
23
|
+
.needs { font-size: 10px; font-weight: 600; color: ${be}; opacity: .7; }
|
|
24
|
+
.needs[aria-pressed="true"] { opacity: 1; text-decoration: underline; }
|
|
25
|
+
.line { display: flex; gap: 4px; align-items: flex-start; }
|
|
26
|
+
.line.branch { cursor: pointer; user-select: none; }
|
|
27
|
+
.chev { width: 10px; flex: none; display: inline-block; transition: transform .15s; }
|
|
28
|
+
.chev.open { transform: rotate(90deg); }
|
|
29
|
+
.text { flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
|
30
|
+
.heading > .line .text { font-weight: 600; }
|
|
31
|
+
.done > .line .text { opacity: .6; }
|
|
32
|
+
.mark { font-weight: 700; margin-inline-end: 4px; }
|
|
33
|
+
.marked > .line .text { opacity: 1; font-weight: 500; }
|
|
34
|
+
.badge { font-size: 10px; font-weight: 600; color: ${be}; margin-inline-start: 6px; white-space: nowrap; }
|
|
35
|
+
.who, .count { font-size: 10px; opacity: .6; margin-inline-start: 6px; white-space: nowrap; }
|
|
36
|
+
a { color: ${Ss}; }
|
|
37
|
+
.note { padding-inline-start: 14px; opacity: .6; white-space: pre-line; }
|
|
38
|
+
.act { padding-inline-start: 14px; }
|
|
39
|
+
.act code { font: 11px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: pre-wrap; word-break: break-all; opacity: .8; }
|
|
40
|
+
.act button { margin-inline-start: 4px; opacity: .6; }
|
|
41
|
+
.status { opacity: .6; margin: 0; }
|
|
42
|
+
`,As=typeof HTMLElement>"u"?class{}:HTMLElement,A=(e,t,n)=>{let r=document.createElement(e);if(t)r.className=t;if(n!==void 0)r.textContent=n;return r},rn=(e,t)=>[...e,t].join("\x00"),Qt=(e,t)=>e.replace("{n}",String(t)),qe=(e,t)=>e?`@${e.type==="human"?t.you:e.name}`:"";function Ms(e){let t=[],n=e.title;for(let r of e.links){let s=n.indexOf(r.text);if(s<0)continue;t.push(document.createTextNode(n.slice(0,s)));let i=A("a",void 0,r.text);i.href=r.url,i.target="_blank",i.rel="noreferrer",i.addEventListener("click",(o)=>o.stopPropagation()),t.push(i),n=n.slice(s+r.text.length)}return t.push(document.createTextNode(n)),t}function _s(e,t){let n=new Map,r=(s,i)=>s&&n.set(rn(s.path,s.title),i);return r(e.done,{glyph:"✓",color:G.done,label:t.lastDone}),r(e.next,{glyph:"›",color:G.open,label:t.upNext}),r(e.doing,{glyph:"▶",color:e.doing?.node.needsOwner?be:G.doing,label:t.nowDoing}),n}class xe extends As{static observedAttributes=["src","progress"];onBack;repo;locale;strings={};storageKey=Ts;_source;_progress;_root=null;live=!1;error="";stop;collapsed=new Set;shadow;set source(e){this._source=e,this.reload()}get source(){return this._source}set progress(e){this._progress=e||void 0,this.reload()}get progress(){return this._progress}set root(e){this._root=e,this.render()}get root(){return this._root}attributeChangedCallback(e,t,n){if(e==="progress")this.progress=n??void 0;else if(n)this.source=n}reload(){if(this.stop?.(),this.stop=void 0,!this._source||!this.isConnected)return;let e=this._progress?nn({base:this._source,progress:this._progress,repo:this.repo}):this._source;this.stop=oe(e,{repo:this.repo},(t,n)=>{this._root=t,this.live=n,this.error="",this.render()},(t)=>{this.error=t instanceof Error?t.message:String(t),this.render()})}connectedCallback(){if(!this.shadow){this.shadow=this.attachShadow({mode:"open"});try{let e=new CSSStyleSheet;e.replaceSync(Jt),this.shadow.adoptedStyleSheets=[e]}catch{let e=A("style");e.textContent=Jt,this.shadow.append(e)}}this.reload(),this.render()}disconnectedCallback(){this.stop?.(),this.stop=void 0}get t(){return{...ve,...this.strings}}get needsMe(){try{return localStorage.getItem(this.storageKey)==="1"}catch{return!1}}render(){let e=this.shadow;if(!e)return;let t=this.t;e.replaceChildren(...Array.from(e.querySelectorAll("style")));let n=A("div","head");if(this.onBack){let c=A("button","hit","‹");c.type="button",c.setAttribute("aria-label",t.back),c.addEventListener("click",()=>this.onBack?.()),n.append(c)}let r=A("span","grow",t.tree);if(this.live){let c=A("span","dot");c.title=t.live,c.setAttribute("role","img"),c.setAttribute("aria-label",t.live),r.append(c)}let s=this._root,i=s?q(s).needsOwner:0,o=A("button","needs hit",`⚑ ${t.needsMe}${i?` · ${i}`:""}`);if(o.type="button",o.setAttribute("aria-pressed",String(this.needsMe)),o.addEventListener("click",()=>{try{localStorage.setItem(this.storageKey,this.needsMe?"0":"1")}catch{}this.render()}),n.append(r,o),e.append(n),this.error||!s){e.append(A("p","status",this.error?`${t.failed} (${this.error})`:t.loading));return}let a=this.needsMe?Ge(s.children):s.children;if(!a.length){e.append(A("p","status",this.needsMe?t.nothingNeedsYou:t.empty));return}let l=_s(se(s,{locale:this.locale}),t);e.append(this.list(a,"",[],0,l,void 0))}list(e,t,n,r,s,i){let o=this.t,a=A("ul");return e.forEach((l,c)=>{let u=t?`${t}.${c}`:String(c),p=l.children.length>0,d=p&&this.collapsed.has(u),g=s.get(rn(n,l.title)),f=A("li");if(f.dataset.status=l.status??"",r===0&&!l.status&&p)f.classList.add("heading");if(l.status==="done")f.classList.add("done");if(g)f.classList.add("marked");let m=A("div",`line${p?" branch":""}`);if(m.append(A("span",`chev${d||!p?"":" open"}`,p?"›":"")),l.status){let b=A("span",void 0,Es[l.status]);b.style.color=G[l.status],b.setAttribute("aria-label",l.status),m.append(b)}let y=A("span","text");if(g){let b=A("span","mark",g.glyph);b.style.color=g.color,b.title=g.label,y.append(b)}if(y.append(...Ms(l)),l.needsOwner&&l.status!=="done")y.append(A("span","badge",`⚑ ${o.needsYou}`));else if(l.assignee&&l.assignee!==i)y.append(A("span","who",qe(l.assignee,o)));if(d){let b=q(l);if(b.open)y.append(A("span","count",Qt(o.openCount,b.open)));if(b.needsOwner)y.append(A("span","badge",`⚑ ${Qt(o.needsYouCount,b.needsOwner)}`))}if(m.append(y),p){m.setAttribute("role","button"),m.tabIndex=0,m.setAttribute("aria-expanded",String(!d));let b=()=>{if(!this.collapsed.delete(u))this.collapsed.add(u);this.render()};m.addEventListener("click",b),m.addEventListener("keydown",(S)=>{if(S.key!=="Enter"&&S.key!==" ")return;S.preventDefault(),b()})}if(f.append(m),l.note)f.append(A("p","note",l.note));for(let b of l.action?.split(`
|
|
43
|
+
`)??[]){let S=A("div","act");S.append(A("code",void 0,b));let x=A("button","hit","⧉");x.type="button",x.setAttribute("aria-label",`${o.copy}: ${b}`),x.addEventListener("click",()=>{navigator.clipboard?.writeText(b).then(()=>{x.textContent="✓",x.setAttribute("aria-label",o.copied),setTimeout(()=>x.textContent="⧉",1500)},()=>{})}),S.append(x),f.append(S)}if(p&&!d)f.append(this.list(l.children,u,l.title?[...n,l.title]:n,r+1,s,l.assignee));a.append(f)}),a}}function Cs(e,t={}){let n={...ve,...t.strings},r=se(e,{locale:t.locale}),s=A("div","liagent-frontier"),i=[["done","✓",G.done,n.lastDone],["doing","▶",r.doing?.node.needsOwner?be:G.doing,n.nowDoing],["next","›",G.open,n.upNext]];for(let[o,a,l,c]of i){let u=r[o];if(!u)continue;let p=u.count>1&&!!u.summary,d=A(p?"button":"div");d.dataset.frontier=o,d.title=p?c:ie([...u.path,u.title]),d.style.cssText="display:flex;gap:4px;align-items:center;width:100%;font:inherit;color:inherit;background:none;border:0;padding:0;text-align:start;pointer-events:auto";let g=A("span",void 0,a);g.style.color=l,g.style.fontWeight="700",g.setAttribute("aria-label",c);let f=A("span",void 0,p?u.summary:[...u.path.slice(-1),u.title].join(" › "));if(f.style.cssText="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap",d.append(g,f),p)d.append(A("span",void 0,`〔${u.count}〕`));else if(u.assignee)d.append(A("span",void 0,qe(u.assignee,n)));if(s.append(d),p){let m=A("ul");m.hidden=!0,m.style.cssText="list-style:none;margin:0;padding:0 0 0 16px";for(let y of u.items){let b=A("li",void 0,`${y.title}${y.assignee?` ${qe(y.assignee,n)}`:""}`);b.title=ie(y.path),m.append(b)}d.setAttribute("aria-expanded","false"),d.addEventListener("click",()=>{m.hidden=!m.hidden,d.setAttribute("aria-expanded",String(!m.hidden))}),s.append(m)}}return s}function Ls(e="liagent-state-tree"){if(typeof customElements<"u"&&!customElements.get(e))customElements.define(e,xe);return xe}function Ps(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function ke(e){if(typeof e==="string")return e?[e]:[];if(Array.isArray(e))return e.filter((t)=>typeof t==="string"&&!!t);return[]}function Ze(e){let t=(e??"").trim();if(!t)return"?";let n=Intl.Segmenter;return((n?new n(void 0,{granularity:"grapheme"}).segment(t)[Symbol.iterator]().next().value?.segment??t[0]:Array.from(t)[0]??t)??t).toLocaleUpperCase()}function ln(e,t,n){let r=n*Math.PI/180,s=t*Math.cos(r),i=t*Math.sin(r),o=(e+0.3963377774*s+0.2158037573*i)**3,a=(e-0.1055613458*s-0.0638541728*i)**3,l=(e-0.0894841775*s-1.291485548*i)**3,c=(g)=>Math.min(1,Math.max(0,g)),u=c(4.0767416621*o-3.3077115913*a+0.2309699292*l),p=c(-1.2684380046*o+2.6097574011*a-0.3413193965*l),d=c(-0.0041960863*o-0.7034186147*a+1.707614701*l);return 0.2126*u+0.7152*p+0.0722*d}var sn=(e,t)=>(Math.max(e,t)+0.05)/(Math.min(e,t)+0.05),on=0.7,an=0.12,Ns=[{css:"oklch(0.2 0 0)",y:ln(0.2,0,0)},{css:"oklch(1 0 0)",y:1}];function Je(e){let t=parseInt(Ps(`avatar:${e}`),36)%360,n=ln(on,an,t),r=Ns.reduce((s,i)=>sn(i.y,n)>sn(s.y,n)?i:s);return{bg:`oklch(${on} ${an} ${t})`,fg:r.css,hue:t}}function cn(e,t){if(e.from==="agent"){let a=e.agentId||e.label||"agent",l=t.agentAvatar,c=typeof l==="string"||Array.isArray(l);return{srcs:c?ke(l):[],...l&&!c?{node:l}:{},name:a,initialFrom:a,seed:`agent:${a}`,mine:!1}}let n=e.from===(t.friend?"friend":"owner"),r=t.avatarFor?.(e)??void 0,s={...n?t.user:void 0,...e.sender,...r},i=[...ke(r?.avatar),...n?ke(t.user?.avatar):[],...ke(e.sender?.avatar)],o=s.name||(e.from==="friend"?"friend":"owner");return{srcs:[...new Set(i)],name:n?"you":o,initialFrom:o,seed:s.id||e.thread||e.from,mine:n}}function we(e,t){let n=e>=0?t.max:-(t.min??-t.max),r=Math.abs(e),s=n*t.cell,i=r<=s?t.unit*(r/t.cell-t.snap*Math.sin(2*Math.PI*r/t.cell)/(2*Math.PI)):Math.min(t.stop,n*t.unit+(r-s)*t.stretch);return Math.sign(e)*i}function un(e,t,n){let r=t;while(r<n.max&&e>r+0.5+n.hysteresis)r++;while(r>n.min&&e<r-0.5-n.hysteresis)r--;return r}function gn(e,t,n){let r={roots:[],parent:new Map,children:new Map},s=(i,o,a)=>{let l=n(i,o,a);return r.parent.set(l,o),r.children.set(l,t(i).map((c,u)=>s(c,l,u))),l};return r.roots=e.map((i,o)=>s(i,null,o)),r}function fn(e,t){let n=e.children.get(t)??[];return n.length?1+Math.max(...n.map((r)=>fn(e,r))):0}var Rs=3;function Te(e,t){return Math.min(Rs,fn(e,t))}var Qe=(e)=>({focusId:e.roots[0]??null,expanded:{},detent:0});function hn(e,t){let n=[];for(let r=e.parent.get(t)??null;r!==null;r=e.parent.get(r)??null)n.push(r);return n}var Z=(e,t)=>hn(e,t).at(-1)??t;function le(e,t,n){let r=hn(e,n);if(!r.length)return!0;if(!le(e,t,r[0]))return!1;return r.some((s,i)=>(t.expanded[s]??0)>=i+1)}function Se(e,t,n){let r={};for(let[s,i]of Object.entries(t))if(i>0&&(n===null||Z(e,s)===n))r[s]=i;for(let s=!0;s;){s=!1;for(let i of Object.keys(r))if(!le(e,{expanded:r},i))delete r[i],s=!0}return r}function Is(e,t){let n=t.focusId;if(n===null)return{s:t,limit:"max"};let r=t.expanded[n]??0;if(r>=Te(e,n))return{s:t,limit:"max"};let s=Se(e,{...t.expanded,[n]:r+1},Z(e,n));return{s:{...t,expanded:s}}}function Os(e,t){let n=t.focusId;if(n===null)return{s:t,limit:"min"};let r=t.expanded[n]??0;if(r>0){let a={...t.expanded,[n]:r-1};return{s:{...t,expanded:Se(e,a,Z(e,n))}}}let s=e.parent.get(n)??null;if(s===null)return{s:t,limit:"min"};let i=t.expanded[s]??1,o={...t.expanded,[s]:Math.max(0,i-1)};return{s:{...t,focusId:s,expanded:Se(e,o,Z(e,s))}}}function dn(e,t,n){let r={s:t};for(let s=0;s<Math.abs(n);s++){let i=n>0?Is(e,r.s):Os(e,r.s);if(i.limit)return{s:r.s,limit:i.limit};r=i}return r}function Y(e,t,n){let r=n?{...t,atLimit:n}:t.atLimit?{...t,atLimit:void 0}:t;if(r.focusId===e.focusId&&r.detent===e.detent&&r.atLimit===e.atLimit&&r.base===e.base&&$s(r.expanded,e.expanded))return e;return r}var $s=(e,t)=>{let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every((r)=>e[r]===t[r])},Fs=(e,t)=>{let n=e.parent.get(t)??null;return n===null?e.roots:e.children.get(n)??[]};function Ae(e,t,n){switch(n.type){case"dragStart":return{...t,base:t.base??{...t,base:void 0},detent:0,atLimit:void 0};case"dragMove":{let r=t.base??t,s=dn(e,r,n.cells);return Y(t,{...s.s,base:r,detent:n.cells},s.limit)}case"dragEnd":{if(!t.base)return t;return{...t,base:void 0,detent:0,atLimit:void 0}}case"dragCancel":return t.base?{...t.base,base:void 0,detent:0,atLimit:void 0}:t;case"tapChip":{if(!e.parent.has(n.id))return t;let r=Z(e,n.id),s=t.expanded[n.id]??0,i=s===0&&Te(e,n.id)>0?1:s,o=Se(e,{...t.expanded,[n.id]:i},r);return Y(t,{...t,focusId:n.id,expanded:o,base:void 0,detent:0})}case"collapseAll":{let r=t.focusId===null?null:Z(e,t.focusId);return Y(t,{focusId:r,expanded:{},detent:0})}case"key":{let r=t.focusId;if(r===null)return t;let s=Fs(e,r),i=s.indexOf(r),o=(a)=>{let l=dn(e,t,a);return Y(t,l.s,l.limit)};switch(n.key){case"ArrowRight":return i<s.length-1?Y(t,{...t,focusId:s[i+1]}):o(1);case"ArrowLeft":return i>0?Y(t,{...t,focusId:s[i-1]}):o(-1);case"Enter":return o(1);case"Escape":return o(-1);case"ArrowDown":{let a=(e.children.get(r)??[])[0];return a&&(t.expanded[r]??0)>0?Y(t,{...t,focusId:a}):t}case"ArrowUp":{let a=e.parent.get(r)??null;return a===null?t:Y(t,{...t,focusId:a})}default:return t}}}}var ae=40,Ee=6,Ds=0.1,Vs=0.6,pn=0.3;function mn(e,t){return un(e/ae,t,{min:-Ee,max:Ee,hysteresis:Ds})}function yn(e,t){let n={cell:ae,unit:ae,max:Ee,snap:Vs,stretch:pn,stop:Ee*ae};if(t===void 0)return we(e,n);let r=t*ae,s=e-r;if(Math.sign(s)!==Math.sign(t||e)||s===0)return we(e,n);return we(r,n)+s*pn}function et(e){let t=new Map;return{ix:gn(e?.children??[],(r)=>r.children,(r,s,i)=>{let o=s===null?String(i):`${s}.${i}`;return t.set(o,r),o}),byId:t}}function xn(e){let t=Object.keys(e.expanded);return t.length?t[0].split(".")[0]:null}function Hs(e,t){let n=xn(t),r=[],s=(i,o)=>{for(let a of e.children.get(i)??[]){if(!le(e,t,a))continue;r.push({id:a,level:o}),s(a,o+1)}};if(n!==null)s(n,0);return r}var Us={open:"○",doing:"◐",blocked:"!",done:"✓"},Bs={open:"oklch(0.62 0.03 260)",doing:"oklch(0.6 0.16 250)",blocked:"oklch(0.7 0.16 70)",done:"oklch(0.62 0.15 150)"},Ws="oklch(0.58 0.21 33)",vn=`
|
|
44
|
+
.chips { min-width: 0; max-width: 100%; display: flex; flex-direction: column; gap: 2px; line-height: 1.35; }
|
|
45
|
+
.chiprow { pointer-events: auto; display: flex; column-gap: 12px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; white-space: nowrap; scrollbar-width: none; }
|
|
46
|
+
.chiprow::-webkit-scrollbar { display: none; }
|
|
47
|
+
.chips button { all: unset; cursor: pointer; pointer-events: auto; text-align: start; }
|
|
48
|
+
.chiprow > button { flex: none; min-height: 24px; }
|
|
49
|
+
.chiprow > button[data-open] { font-weight: 600; }
|
|
50
|
+
.chips button[data-focus] .lbl { text-decoration: underline; text-decoration-thickness: 2px; text-underline-offset: 3px; }
|
|
51
|
+
.chiplines { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
|
|
52
|
+
.chiplines .note { margin: 0; padding-inline-start: 12px; font-size: 10px; opacity: .6; }
|
|
53
|
+
.chips .g { display: inline-block; margin-inline-end: 2px; }
|
|
54
|
+
.chips .done { opacity: .6; }
|
|
55
|
+
.chips .need { margin-inline-start: 2px; font-weight: 700; color: ${Ws}; }
|
|
56
|
+
.chips .cnt { margin-inline-start: 2px; opacity: .6; font-variant-numeric: tabular-nums; }
|
|
57
|
+
.chips .tw { margin-inline-end: 2px; opacity: .6; }
|
|
58
|
+
.chips .status { margin: 0; opacity: .6; }
|
|
59
|
+
`,D=(e,t,n)=>{let r=document.createElement(e);if(t)r.className=t;if(n!==void 0)r.textContent=n;return r};function bn(e,t,n){let r=D("span","lbl");if(e.status){let i=D("span",`g${e.status==="doing"?" blink":""}`,Us[e.status]);i.setAttribute("aria-hidden","true"),i.style.color=Bs[e.status],r.append(i)}if(r.append(D("span",e.status==="done"?"done":void 0,e.title||"—")),e.needsOwner&&e.status!=="done"){let i=D("span","need","(!)");i.setAttribute("aria-label",n),r.append(i)}let s=t?q(e).open:0;if(s>0)r.append(D("span","cnt",`〔${s}〕`));return r}function kn(e){if(e.status||!e.root||!e.ix.roots.length){let a=D("p","status",e.status??e.empty);return a.dataset.testid="tree-chips-status",a}let t=(a,l)=>{a.addEventListener("pointerdown",(c)=>c.preventDefault()),a.addEventListener("click",()=>e.onNav({type:"tapChip",id:l}))},n=xn(e.nav),r=e.nav.focusId,s=D("div","chips");s.dataset.testid="tree-chips";let i=D("div","chiprow");i.setAttribute("role","tablist"),i.setAttribute("aria-label",e.label);for(let a of e.ix.roots){let l=e.byId.get(a),c=D("button");if(c.setAttribute("type","button"),c.setAttribute("role","tab"),c.setAttribute("aria-selected",String(a===n)),c.dataset.id=a,a===r)c.dataset.focus="";if(a===n)c.dataset.open="";c.append(bn(l,a!==n,e.needsYou)),t(c,a),i.append(c)}s.append(i);let o=Hs(e.ix,e.nav);if(o.length){let a=D("ul","chiplines");for(let{id:l,level:c}of o){let u=e.byId.get(l),p=e.ix.children.get(l)??[],d=p.length>0&&!p.some((m)=>le(e.ix,e.nav,m)),g=D("li");g.dataset.id=l,g.dataset.level=String(c),g.style.paddingInlineStart=`${c*0.75}rem`;let f=D("button");if(f.setAttribute("type","button"),l===r)f.dataset.focus="";if(p.length){let m=D("span","tw",d?"▸":"▾");m.setAttribute("aria-hidden","true"),f.append(m)}if(f.append(bn(u,d,e.needsYou)),t(f,l),g.append(f),u.note&&!d&&c<1)g.append(D("p","note",u.note));a.append(g)}s.append(a)}return s}var wn=1e4,Sn=6,Ks=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function zs(e){let t=0,n=0;for(let r of e.trim())if(Ks.test(r))t++;else n++;return t/6+n/15}function En(e){return Math.max(2500,Math.round(zs(e)*1000*2))}function Gs(e){let t=e.now??(()=>Date.now()),n=e.setTimer??((c,u)=>setTimeout(c,u)),r=e.clearTimer??((c)=>clearTimeout(c)),s=e.ms,i=t(),o=null,a=!1,l=()=>{i=t(),o=n(()=>{o=null,a=!0,e.onDone()},s)};return l(),{pause(){if(o===null||a)return;r(o),o=null,s=Math.max(0,s-(t()-i))},resume(){if(o!==null||a)return;l()},cancel(){if(o!==null)r(o);o=null,a=!0},remaining:()=>o===null?s:Math.max(0,s-(t()-i))}}var Ys=600000;function Tn(){let e=new Map,t=new Map,n=0,r=!1;return{see(s,i){let o=s.filter((l)=>!e.has(l.id));for(let l of o)e.set(l.id,i),t.set(l.id,++n);let a=!r;if(s.length)r=!0;if(e.size>2*s.length+100){let l=new Set(s.map((c)=>c.id));for(let c of e.keys())if(!l.has(c))e.delete(c),t.delete(c)}return{fresh:o,history:a}},at:(s)=>e.get(s),seqOf:(s)=>t.get(s),seq:()=>n}}function An(e,t,n){return e.filter((r)=>r.from==="agent"&&(t(r.id)??0)>n).length}function Mn(e,t,n){let r=e.at(-1);if(!r)return null;let s=n(r.id);return s!==void 0&&t-s<=Ys?r:null}function _n(e){let t=e.setTimer??((u,p)=>setTimeout(u,p)),n=e.clearTimer??((u)=>clearTimeout(u)),r="dwell",s=!1,i=null,o=(u)=>{r=u,e.onPhase(u)},a=()=>{o("fade"),i=t(()=>{i=null,o("gone")},e.fadeMs??1e4)},l=Gs({ms:e.ms,onDone:()=>e.reducedMotion?o("gone"):a(),now:e.now,setTimer:t,clearTimer:n}),c={pause(){if(s)return;if(s=!0,r==="dwell")l.pause();else if(r==="fade")n(i),i=null,o("held")},resume(){if(!s)return;if(s=!1,r==="dwell")l.resume();else if(r==="held")a()},cancel(){if(l.cancel(),i!==null)n(i);i=null},phase:()=>r};if(e.paused)c.pause();return c}function js(e,t,n){let r=(e+t)/2;return r<n/3?"left":r>2*n/3?"right":"center"}function Cn(e){let t=e.gutter??8,n=js(e.barLeft,e.barRight,e.vw),r=n==="left"?e.barLeft:n==="right"?e.barRight-e.boxWidth:(e.barLeft+e.barRight)/2-e.boxWidth/2,s=(e.insetLeft??0)+t,i=e.vw-(e.insetRight??0)-t-e.boxWidth;return{side:n,left:Math.round(i<s?s:Math.min(i,Math.max(s,r)))}}var Ln=[{key:"done",mark:"✓",label:"Last done"},{key:"doing",mark:"▶",label:"In progress"},{key:"next",mark:"›",label:"Next"}],Xs=6,qs=64,Pn=500;function Nn(e){if(!e||e.type!=="agent"||!e.id)return null;let t=e.id.trim();if(!t||t.length>qs||/[.:/\\]/.test(t))return null;return t}var Rn=(e)=>e.slice(-Xs),In=(e)=>e&&e>1?`〔${e}〕`:"";function On(e){let t=(o)=>o&&{text:o.count>1&&o.summary?o.summary:o.title,count:o.count,...o.assignee?{assignee:o.assignee}:{},...o.count>1?{items:o.items.map((a)=>({title:a.title,path:ie(a.path),...a.assignee?{assignee:a.assignee}:{}}))}:{}},n={},r=t(e.done),s=t(e.doing),i=t(e.next);if(r)n.done=r;if(s)n.doing=s;if(i)n.next=i;return r||s||i?n:void 0}var Me=[1,1.25,1.5,2];var $n=()=>{try{return globalThis.localStorage??null}catch{return null}};function _e(e=$n()){let t=null;try{t=e?.getItem("liagent:speech-rate")??null}catch{}let n=Number(t);return t!==null&&Me.includes(n)?n:1.5}function Fn(e,t=$n()){if(!Me.includes(e))return;try{t?.setItem("liagent:speech-rate",String(e))}catch{}}function Dn(e){let t=e.setTimer??((s,i)=>setTimeout(s,i)),n=e.clearTimer??((s)=>clearTimeout(s)),r=null;return{tap(){if(r!==null)return n(r),r=null,e.onDouble();r=t(()=>{r=null,e.onSingle()},e.delayMs??280)},cancel(){if(r!==null)n(r);r=null}}}var Zs=400;function tt(e=Date.now){let t=null;return{down(){t=null},dragEnded(){t=e()},wasDrag(){let n=t!==null&&e()-t<Zs;return t=null,n}}}var Js=8;function Vn(e=Js){let t=null,n=null;return{down(r,s){t={x:r,y:s},n=null},move(r,s){if(!t)return null;let i=r-t.x,o=s-t.y;if(!n){if(Math.hypot(i,o)<e)return null;n=Math.abs(o)>Math.abs(i)?"y":"x"}return{axis:n,dx:i,dy:o}},up(){let r=n;return t=null,n=null,r},axis:()=>n}}function Hn(e){let t=e.setTimer??((o,a)=>setTimeout(o,a)),n=e.clearTimer??((o)=>clearTimeout(o)),r=null,s=!1,i=()=>{if(r!==null)n(r);r=null};return{down(){i(),s=!1,r=t(()=>{r=null,s=!0,e.onLong()},e.ms??500)},up(){return i(),s},cancel:i}}var Qs={stateTree:"State tree",closeTree:"Close the state tree",noTreeSource:"No tree source",lastDone:"Last done",nowDoing:"In progress",upNext:"Next",needsYou:"needs you",items:"items",polished:"Polished"},ei={stateTree:"状态树",closeTree:"关闭状态树",noTreeSource:"没有状态树来源",lastDone:"最近完成",nowDoing:"进行中",upNext:"下一步",needsYou:"等你处理",items:"项",polished:"已润色"},ti={tree:"状态树",back:"返回聊天",needsMe:"待我处理",needsYou:"等你处理",openCount:"{n} 项未完成",needsYouCount:"{n} 项等你",copy:"复制",copied:"已复制",loading:"加载中…",failed:"无法加载状态树",empty:"状态树是空的。",nothingNeedsYou:"没有等你处理的事。",you:"你",lastDone:"最近完成",nowDoing:"进行中",upNext:"下一步",live:"实时数据"};function Un(e=globalThis.document?.documentElement.lang){return/^zh\b/i.test(e??"")}var Bn=(e)=>Un(e)?ei:Qs,Wn=(e)=>Un(e)?ti:{};function Kn(e){let[t="",...n]=e.split(" "),r=n.join(" "),s=/iPhone/.test(r)?"iPhone":/iPad/.test(r)?"iPad":/Android/.test(r)?"Android":/Macintosh|Mac OS/.test(r)?"Mac":/Windows/.test(r)?"Windows":/Linux|X11/.test(r)?"Linux":r.split(" ").find((o)=>o!=="pwa")??"",i=/(^| )pwa( |$)/.test(r)?" app":"";return s?`${t} · ${s}${i}`:t}var ni=typeof HTMLElement>"u"?class{}:HTMLElement,Ce=()=>typeof speechSynthesis>"u"?null:speechSynthesis,zn=!1;function Gn(){let e=Ce();if(zn||!e)return;zn=!0,e.speak(new SpeechSynthesisUtterance(""))}function ri(){let e=Ce();if(e&&(e.speaking||e.pending))e.cancel()}var si=()=>typeof matchMedia<"u"&&matchMedia("(prefers-reduced-motion: reduce)").matches;function nt(){let e=document.createElement("div");e.style.cssText="position:fixed;visibility:hidden;pointer-events:none;padding:env(safe-area-inset-top) env(safe-area-inset-right) 0 env(safe-area-inset-left)",document.body.append(e);let t=getComputedStyle(e),n={top:Number.parseFloat(t.paddingTop)||0,left:Number.parseFloat(t.paddingLeft)||0,right:Number.parseFloat(t.paddingRight)||0};return e.remove(),n}var ce=(e)=>String(e).padStart(2,"0");function Yn(e,t=new Date){let n=new Date(e),r=(i)=>`${i.getFullYear()}-${ce(i.getMonth()+1)}-${ce(i.getDate())}`,s=`${ce(n.getHours())}:${ce(n.getMinutes())}`;return r(n)===r(t)?`${s}:${ce(n.getSeconds())}`:`${r(n)} ${s}`}var ii="drag: move · tap: minimize · double-tap: menu",oi="Tap: minimize or restore · double-tap: menu · drag: move the chat",rt="Tap: show or hide the state tree · drag right: open the focused node deeper · drag left: fold it · arrow keys: move",qn=128,ue={lock:'<svg viewBox="0 0 16 16" width="10" height="10" aria-hidden="true"><path fill="currentColor" d="M5 7V5a3 3 0 0 1 6 0v2h1v7H4V7zm1.5 0h3V5a1.5 1.5 0 0 0-3 0z"/></svg>',sparkle:'<svg viewBox="0 0 256 256" width="1em" height="1em" aria-hidden="true"><path fill="currentColor" d="M104,40Q112,136,200,144Q112,152,104,248Q96,152,8,144Q96,136,104,40ZM200,8Q204,48,244,52Q204,56,200,96Q196,56,156,52Q196,48,200,8Z"/></svg>',speaker:'<svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true"><path fill="currentColor" d="M2 6h3l4-3v10l-4-3H2z"/><path d="M11 5.5a3.5 3.5 0 0 1 0 5M12.5 3.5a6 6 0 0 1 0 9" stroke="currentColor" fill="none" stroke-width="1.3"/></svg>',mark:'<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 3h10a4 4 0 0 1 4 4v7a4 4 0 0 1-4 4h-7l-5 3v-3.6A4 4 0 0 1 3 14V7a4 4 0 0 1 4-4Z"/><path d="M10.5 6.5v8"/><path d="M15.5 5.6l.55 1.35 1.35.55-1.35.55-.55 1.35-.55-1.35-1.35-.55 1.35-.55Z" fill="oklch(0.72 0.17 150)" stroke="oklch(0.72 0.17 150)" stroke-width="1"/></svg>',tree:'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="10" width="7" height="4.5" rx="1.5"/><rect x="14" y="16.5" width="7" height="4.5" rx="1.5"/><path d="M6.5 8v10.75H14M6.5 12.25H14"/></svg>'},jn=`
|
|
60
|
+
:host {
|
|
61
|
+
all: initial;
|
|
62
|
+
position: fixed;
|
|
63
|
+
right: 0.5rem;
|
|
64
|
+
bottom: calc(0.5rem + env(safe-area-inset-bottom));
|
|
65
|
+
z-index: var(--liagent-z, 40);
|
|
66
|
+
/* Click-through: only the bar, the menu, the pairing line and opted-in rows take pointer events. */
|
|
67
|
+
pointer-events: none;
|
|
68
|
+
font: 12px/1.35 system-ui, -apple-system, "Segoe UI", sans-serif;
|
|
69
|
+
color: var(--liagent-fg, CanvasText);
|
|
70
|
+
--bg: var(--liagent-bg, Canvas);
|
|
71
|
+
--glass: color-mix(in oklch, var(--bg) 55%, transparent);
|
|
72
|
+
--line: color-mix(in oklch, currentColor 25%, transparent);
|
|
73
|
+
--muted: color-mix(in oklch, currentColor 55%, transparent);
|
|
74
|
+
/* Lines straight over the page (floating, frontier): a stronger halo, never a fill. */
|
|
75
|
+
--halo: 0 0 1px var(--bg), 0 0 2px var(--bg), 0 0 4px var(--bg), 0 0 8px var(--bg);
|
|
76
|
+
}
|
|
77
|
+
* { box-sizing: border-box; }
|
|
78
|
+
button { font: inherit; color: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
|
|
79
|
+
.halo { text-shadow: 0 0 3px var(--bg), 0 0 6px var(--bg); }
|
|
80
|
+
.box {
|
|
81
|
+
width: var(--liagent-width, min(20rem, calc(100vw - 1rem)));
|
|
82
|
+
display: flex; flex-direction: column; pointer-events: none;
|
|
83
|
+
opacity: .6; transition: opacity .15s;
|
|
84
|
+
}
|
|
85
|
+
.box:focus-within, .box:active, .box.on { opacity: 1; }
|
|
86
|
+
/* The one scroller: the tree (when open) on top, the log below. Compact at rest. */
|
|
87
|
+
.column {
|
|
88
|
+
max-height: 4.4rem; min-height: 3rem; overflow-y: auto; padding: 6px 8px;
|
|
89
|
+
scrollbar-width: none; transition: max-height .15s ease-out;
|
|
90
|
+
}
|
|
91
|
+
.column::-webkit-scrollbar { display: none; }
|
|
92
|
+
.column.wide { max-height: 30vh; }
|
|
93
|
+
.column.fade { -webkit-mask-image: linear-gradient(to bottom, transparent, black .9rem); mask-image: linear-gradient(to bottom, transparent, black .9rem); }
|
|
94
|
+
.column.wide.fade { -webkit-mask-image: linear-gradient(to bottom, transparent, black 2.5rem); mask-image: linear-gradient(to bottom, transparent, black 2.5rem); }
|
|
95
|
+
.treepanel { pointer-events: none; display: flex; flex-direction: row-reverse; align-items: flex-start; min-width: 0; max-width: 100%; padding-bottom: 4px; animation: appear .18s ease-out; }
|
|
96
|
+
@keyframes appear { from { opacity: 0; } }
|
|
97
|
+
.treepanel .tbody { flex: 1; min-width: 0; }
|
|
98
|
+
.treepanel .x { pointer-events: auto; flex: none; position: relative; padding: 0 6px; font-size: 10px; color: var(--muted); }
|
|
99
|
+
.ftree .tbody { max-height: 4.4rem; overflow-y: auto; scrollbar-width: none; }
|
|
100
|
+
.ftree .tbody.wide { max-height: 30vh; }
|
|
101
|
+
.ftree .tbody.fade { -webkit-mask-image: linear-gradient(to bottom, transparent, black .9rem); mask-image: linear-gradient(to bottom, transparent, black .9rem); }
|
|
102
|
+
.blink { animation: blink 1.6s ease-in-out infinite; }
|
|
103
|
+
@keyframes blink { 50% { opacity: .35; } }
|
|
104
|
+
.log { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; }
|
|
105
|
+
.log li { display: flex; align-items: flex-start; gap: 6px; }
|
|
106
|
+
.text { flex: 1; min-width: 0; white-space: pre-wrap; overflow-wrap: anywhere; padding-top: 1px; }
|
|
107
|
+
.log .hint { opacity: .6; display: block; }
|
|
108
|
+
.polished { all: unset; pointer-events: auto; cursor: pointer; margin-inline-start: 4px; font-size: .85em; opacity: .55; vertical-align: baseline; }
|
|
109
|
+
.polished[aria-pressed="true"] { opacity: .9; }
|
|
110
|
+
.raw { opacity: .65; }
|
|
111
|
+
.log li.node { border-inline-start: 2px solid var(--node); padding-inline-start: 4px; }
|
|
112
|
+
.log .sub { display: block; font-size: 10px; line-height: 1.2; opacity: .65; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
113
|
+
/* Fixed size whatever loads, so a late picture shifts nothing. */
|
|
114
|
+
.av {
|
|
115
|
+
--s: var(--liagent-avatar, 18px);
|
|
116
|
+
flex: none; width: var(--s); height: var(--s); border-radius: 50%; overflow: hidden;
|
|
117
|
+
display: inline-flex; align-items: center; justify-content: center;
|
|
118
|
+
font-weight: 600; font-size: calc(var(--s) * 0.55); line-height: 1; text-shadow: none; user-select: none;
|
|
119
|
+
}
|
|
120
|
+
img.av { display: block; object-fit: cover; }
|
|
121
|
+
.av > * { max-width: 100%; max-height: 100%; }
|
|
122
|
+
.sr { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
|
|
123
|
+
.warn { padding: 4px 8px 0; font-size: 10px; color: oklch(0.6 0.17 45); }
|
|
124
|
+
.asks { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; padding: 0 0 4px; }
|
|
125
|
+
.asks:empty { display: none; }
|
|
126
|
+
.ask {
|
|
127
|
+
pointer-events: auto; display: inline-flex; align-items: center; gap: 4px;
|
|
128
|
+
border-radius: 999px; padding: 2px 2px 2px 6px; font-size: 10px; color: oklch(1 0 0);
|
|
129
|
+
background: oklch(0.45 0.12 30); text-shadow: none;
|
|
130
|
+
}
|
|
131
|
+
.ask b { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: .08em; }
|
|
132
|
+
.ask button { border-radius: 999px; padding: 0 6px; }
|
|
133
|
+
.ask .y { background: oklch(0.55 0.15 145); }
|
|
134
|
+
.ask .c { background: oklch(0.5 0.1 230); }
|
|
135
|
+
.ask .n { background: oklch(0.4 0.02 260); }
|
|
136
|
+
.ask .tag { opacity: .85; }
|
|
137
|
+
.askwrap { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; pointer-events: auto; }
|
|
138
|
+
.pagelist {
|
|
139
|
+
display: flex; flex-direction: column; gap: 1px; padding: 3px 8px; border-radius: 8px; font-size: 11px;
|
|
140
|
+
border: 1px solid var(--line); background: var(--glass); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
|
|
141
|
+
}
|
|
142
|
+
.pagelist label { display: flex; align-items: center; gap: 4px; cursor: pointer; }
|
|
143
|
+
.pagelist input { margin: 0; }
|
|
144
|
+
/* The bar's row: two grid columns, the bar's and a spacer's, trading 1fr ⇄ 0fr. */
|
|
145
|
+
.rowbox { position: relative; display: grid; grid-template-columns: 1fr 0fr; transition: grid-template-columns .18s ease-out; }
|
|
146
|
+
.min .rowbox { grid-template-columns: 0fr 1fr; }
|
|
147
|
+
.bar {
|
|
148
|
+
pointer-events: auto; position: relative; display: flex; align-items: flex-end;
|
|
149
|
+
padding: 2px; border-radius: 1.125rem; border: 1px solid var(--line); background: var(--glass);
|
|
150
|
+
backdrop-filter: blur(12px) saturate(1.5); -webkit-backdrop-filter: blur(12px) saturate(1.5);
|
|
151
|
+
touch-action: none; text-shadow: none;
|
|
152
|
+
}
|
|
153
|
+
.min .bar { padding: 1px; }
|
|
154
|
+
/* 40px targets: the hit area reaches 40px whatever the drawn size. */
|
|
155
|
+
.tap { position: relative; flex: none; width: 40px; height: 32px; display: inline-flex; align-items: center; justify-content: center; border-radius: 999px; }
|
|
156
|
+
.tap::before { content: ""; position: absolute; left: 50%; top: 50%; width: max(100%, 40px); height: max(100%, 40px); transform: translate(-50%, -50%); }
|
|
157
|
+
.mark, .treebtn { touch-action: none; cursor: grab; }
|
|
158
|
+
.treebtn { cursor: pointer; }
|
|
159
|
+
.mark .dot { position: absolute; top: 4px; inset-inline-end: 6px; width: 6px; height: 6px; border-radius: 50%; }
|
|
160
|
+
.evals {
|
|
161
|
+
position: absolute; top: 0; inset-inline-end: 2px; min-width: 14px; height: 14px; padding: 0 2px; border-radius: 999px;
|
|
162
|
+
display: inline-flex; align-items: center; justify-content: center; font-size: 8px; line-height: 1; color: oklch(1 0 0);
|
|
163
|
+
background: oklch(0.55 0.15 30); font-variant-numeric: tabular-nums;
|
|
164
|
+
}
|
|
165
|
+
.evals.ran { animation: pulse 1s ease-in-out infinite; }
|
|
166
|
+
@keyframes pulse { 50% { opacity: .4; } }
|
|
167
|
+
.thint { pointer-events: none; position: absolute; inset-inline-start: 0; bottom: 100%; margin-bottom: 8px; white-space: nowrap; font-size: 10px; text-shadow: var(--halo); }
|
|
168
|
+
.slot { position: relative; display: flex; flex: 1; width: 0; min-width: 0; transition: opacity .18s ease-out; }
|
|
169
|
+
.min .slot { opacity: 0; max-height: 2rem; overflow: hidden; }
|
|
170
|
+
textarea {
|
|
171
|
+
pointer-events: auto; display: block; flex: 1; min-width: 0; resize: none; margin: 0; align-self: flex-end;
|
|
172
|
+
font: 16px/1.35 inherit; font-family: inherit; color: inherit; height: 2.125rem; min-height: 2.125rem; max-height: ${qn}px;
|
|
173
|
+
padding: 4px 8px; border: 1px solid transparent; background: transparent; outline: none;
|
|
174
|
+
overflow-y: auto; overscroll-behavior: contain; touch-action: pan-y;
|
|
175
|
+
}
|
|
176
|
+
textarea.pe { padding-inline-end: 24px; }
|
|
177
|
+
textarea::placeholder { color: color-mix(in oklch, currentColor 45%, transparent); }
|
|
178
|
+
.mirror {
|
|
179
|
+
pointer-events: none; position: absolute; inset: 0; overflow: hidden; white-space: pre-wrap; overflow-wrap: anywhere;
|
|
180
|
+
border: 1px solid transparent; padding: 4px 8px; font: 16px/1.35 inherit; font-family: inherit;
|
|
181
|
+
}
|
|
182
|
+
.mirror .ghost { visibility: hidden; }
|
|
183
|
+
.mirror .partial { color: var(--muted); }
|
|
184
|
+
.notice { margin: 0; flex: 1; min-width: 0; padding: 8px; opacity: .8; }
|
|
185
|
+
.spin {
|
|
186
|
+
pointer-events: none; position: absolute; inset-inline-end: 6px; top: 50%; margin-top: -6px;
|
|
187
|
+
width: 12px; height: 12px; border-radius: 50%;
|
|
188
|
+
border: 2px solid var(--line); border-top-color: var(--liagent-agent, oklch(0.55 0.14 150));
|
|
189
|
+
animation: rot .8s linear infinite;
|
|
190
|
+
}
|
|
191
|
+
@keyframes rot { to { transform: rotate(360deg); } }
|
|
192
|
+
.mic { pointer-events: auto; flex: none; display: flex; align-items: center; min-height: 32px; }
|
|
193
|
+
.unread {
|
|
194
|
+
pointer-events: none; position: absolute; top: -6px; inset-inline-end: -6px; border-radius: 999px; padding: 0 4px;
|
|
195
|
+
font-size: 10px; line-height: 16px; color: oklch(1 0 0); background: oklch(0.55 0.2 260);
|
|
196
|
+
}
|
|
197
|
+
.drain {
|
|
198
|
+
position: absolute; inset: 0 12px auto 12px; height: 2px; background: oklch(0.55 0.2 260 / .6);
|
|
199
|
+
transform-origin: left; animation: drain var(--drain-ms) linear both; pointer-events: none;
|
|
200
|
+
}
|
|
201
|
+
@keyframes drain { to { transform: scaleX(0); } }
|
|
202
|
+
.aim { position: absolute; inset-inline-start: 84px; bottom: 100%; margin-bottom: 4px; max-width: calc(100% - 6rem); display: flex; flex-direction: column; align-items: flex-start; gap: 4px; pointer-events: none; }
|
|
203
|
+
.aim > * { pointer-events: auto; }
|
|
204
|
+
.target { display: inline-flex; align-items: center; gap: 4px; max-width: 100%; border: 1px solid var(--node, var(--line)); border-radius: 999px; padding: 0 6px; font-size: 10px; line-height: 16px; background: var(--glass); }
|
|
205
|
+
.target.preview { opacity: .7; }
|
|
206
|
+
.target button { all: unset; cursor: pointer; line-height: 1; }
|
|
207
|
+
.nodes { list-style: none; margin: 0; padding: 2px 0; max-width: 100%; border: 1px solid var(--line); border-radius: 8px; font-size: 11px; background: var(--glass); backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); }
|
|
208
|
+
.nodes button { all: unset; display: block; cursor: pointer; padding: 1px 8px; }
|
|
209
|
+
/* Minimized: the tree, the floating lines and the frontier, on the bar's side. */
|
|
210
|
+
.floatbox {
|
|
211
|
+
pointer-events: none; position: absolute; bottom: 100%; margin-bottom: 4px; left: 0;
|
|
212
|
+
width: max-content; max-width: min(20rem, calc(100vw - 16px));
|
|
213
|
+
display: flex; flex-direction: column; gap: 4px; align-items: flex-start;
|
|
214
|
+
}
|
|
215
|
+
.floatbox[data-side="center"] { align-items: center; text-align: center; }
|
|
216
|
+
.floatbox[data-side="right"] { align-items: flex-end; text-align: right; }
|
|
217
|
+
.floats, .frontier { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 2px; align-items: inherit; max-width: 100%; }
|
|
218
|
+
.floats:empty, .frontier:empty, .ftree:empty { display: none; }
|
|
219
|
+
.float {
|
|
220
|
+
pointer-events: auto; max-width: 100%; padding: 2px 0; white-space: pre-wrap; overflow-wrap: anywhere;
|
|
221
|
+
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; line-clamp: 3; overflow: hidden;
|
|
222
|
+
text-shadow: var(--halo); opacity: 1; transition: none;
|
|
223
|
+
}
|
|
224
|
+
.float.fading { opacity: 0; transition: opacity ${wn}ms ease-out; }
|
|
225
|
+
.float .who { margin-inline-end: 4px; font-weight: 500; }
|
|
226
|
+
.frontier > li { pointer-events: auto; max-width: 100%; min-width: 0; text-shadow: var(--halo); }
|
|
227
|
+
.frontier .fl { display: flex; min-width: 0; align-items: center; }
|
|
228
|
+
.frontier .fb { display: flex; min-width: 0; align-items: center; gap: 4px; padding: 2px 4px 2px 0; text-align: start; }
|
|
229
|
+
.frontier .fb[aria-expanded] { cursor: pointer; }
|
|
230
|
+
.frontier .fb:not([aria-expanded]) { cursor: default; }
|
|
231
|
+
.frontier .m { width: 12px; flex: none; text-align: center; opacity: .7; }
|
|
232
|
+
.frontier .t { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
233
|
+
.frontier .n { flex: none; opacity: .7; }
|
|
234
|
+
.frontier .fav {
|
|
235
|
+
display: inline-flex; width: 16px; height: 16px; flex: none; align-items: center; justify-content: center;
|
|
236
|
+
border-radius: 50%; font-size: 9px; line-height: 1; font-weight: 600; text-shadow: none;
|
|
237
|
+
}
|
|
238
|
+
.frontier .id { position: relative; margin-inline-start: auto; flex: none; padding: 0 8px 0 6px; user-select: none; -webkit-user-select: none; font: 10px ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--muted); }
|
|
239
|
+
.frontier .full {
|
|
240
|
+
position: absolute; inset-inline-end: 0; bottom: 100%; margin-bottom: 4px; white-space: nowrap; padding: 2px 6px; border-radius: 6px;
|
|
241
|
+
border: 1px solid var(--line); background: color-mix(in oklch, var(--bg) 85%, transparent); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
|
|
242
|
+
}
|
|
243
|
+
.frontier .items { list-style: none; margin: 0; padding: 0 8px 4px; max-height: 9.75rem; overflow-y: auto; overscroll-behavior: contain; }
|
|
244
|
+
.frontier .items li { display: flex; min-width: 0; align-items: center; gap: 4px; padding: 1px 0; }
|
|
245
|
+
.frontier .items .p { margin-inline-start: 4px; font-size: 10px; color: var(--muted); }
|
|
246
|
+
.menu {
|
|
247
|
+
pointer-events: auto; position: absolute; bottom: 100%; left: 0; margin-bottom: 4px; min-width: 12rem; max-height: 60vh; overflow-y: auto;
|
|
248
|
+
display: flex; flex-direction: column; padding: 4px 0; border-radius: 8px; text-shadow: none;
|
|
249
|
+
border: 1px solid var(--line); background: var(--glass); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
|
|
250
|
+
}
|
|
251
|
+
.menu > * { padding: 5px 12px; text-align: start; display: flex; align-items: center; gap: 8px; }
|
|
252
|
+
.menu .status { opacity: .65; }
|
|
253
|
+
.menu .rate { gap: 4px; padding-top: 2px; padding-bottom: 2px; }
|
|
254
|
+
.menu .rate span { opacity: .65; margin-inline-end: 4px; }
|
|
255
|
+
.menu .rate button { min-width: 40px; min-height: 28px; border-radius: 4px; font-variant-numeric: tabular-nums; opacity: .7; }
|
|
256
|
+
.menu .rate button[aria-checked="true"] { opacity: 1; font-weight: 600; text-decoration: underline; text-underline-offset: 2px; }
|
|
257
|
+
.menu .sess, .menu .pg { opacity: .75; }
|
|
258
|
+
.menu .sess span, .menu .pg span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
259
|
+
.menu .sess button, .menu .pg button { text-decoration: underline; padding: 0; }
|
|
260
|
+
.menu .head { opacity: .5; font-size: 10px; padding-bottom: 0; }
|
|
261
|
+
.menu [aria-checked="false"] svg { opacity: .45; }
|
|
262
|
+
${vn}
|
|
263
|
+
@media (prefers-reduced-motion: reduce) {
|
|
264
|
+
.rowbox, .slot, .column, .box, .float.fading { transition: none; }
|
|
265
|
+
.blink, .treepanel, .evals.ran { animation: none; }
|
|
266
|
+
}
|
|
267
|
+
[hidden] { display: none !important; }
|
|
268
|
+
`;class Le extends ni{static get observedAttributes(){return["mic-active"]}onSend;onAnswer;onEnd;onEndPage;avatarFor;voice;_messages=[];_live=!1;_listeners=0;_sessions=[];_pending=null;_evalRan=!1;_busy=!1;busyTimer;lastReplyAt=0;_pages=[];_self="";picked=new Map;confirmEnd="";_friend=!1;_notice="";_warning="";_defaultOpen=!0;_placeholder="";_treeSource;treeRepo;treeStrings={};_strings={};_agentAvatar=null;_user={};_nodes=[];_target=P;rawIds=new Set;root;open=!0;panel="none";offline=!1;pos={x:0,y:0};_draft="";pure=null;_partial="";_micActive=!1;typing=!1;holding=!1;settledLen=0;composing=!1;shiftEnter=!1;timer;els={};markDrag=tt();taps=Dn({onSingle:()=>{this.setPanel("none"),this.setOpen(!this.open)},onDouble:()=>this.setPanel(this.panel==="menu"?"none":"menu")});atEnd=!0;arrivals=Tn();readSeq=0;wasOpen=!0;floats=new Map;floatHover=!1;frontierOpen=null;place={side:"left",left:0};ro;treeStop;treeRoot=null;treeError="";navIx=et(null);nav=Qe(this.navIx.ix);treeAxis=Vn();treeDragged=tt();treePress={cells:0,limitAt:null};userScrollAt=0;get messages(){return this._messages}set messages(e){this._messages=te(Array.isArray(e)?e:[]),this.messagesChanged()}push(e){if(!e||typeof e.text!=="string"||typeof e.id!=="string")return;if(this._messages.some((t)=>t.id===e.id))return;if(this._messages=te([...this._messages,e]),this.messagesChanged(e.from!=="agent"),e.from!=="agent")return;this.lastReplyAt=Date.now(),this.busy=!1,this.speak(e.text,e.id)}edit(e){if(!e||typeof e.id!=="string"||typeof e.text!=="string")return;this._messages=this._messages.map((t)=>Et(t,e)),this.renderLog(),this.renderFloatTexts()}beat(e=Date.now()){if(e-this.lastReplyAt<wt)return;this.busy=!0,this.busyTimer=setTimeout(()=>this.busy=!1,kt)}set live(e){this._live=!!e,this.renderStatus()}get live(){return this._live}set nodes(e){this._nodes=Array.isArray(e)?e.filter((t)=>typeof t==="string"):[],this.renderAim()}get target(){return this._target}setTarget(e){this._target=K(e)??P,this.renderAim(),this.renderPlaceholder()}set listeners(e){this._listeners=Number(e)||0,this.renderStatus()}set sessions(e){this._sessions=Array.isArray(e)?e:[],this.renderEvals(),this.renderMenu()}set pending(e){this._pending=e??null,this.renderAsks()}set evalRan(e){this._evalRan=!!e,this.renderEvals()}set busy(e){clearTimeout(this.busyTimer),this._busy=!!e,this.renderBusy()}get busy(){return this._busy}set pages(e){this._pages=Array.isArray(e)?e:[],this.renderAsks(),this.renderMenu()}set self(e){this._self=e??"",this.renderAsks(),this.renderMenu()}set friend(e){this._friend=!!e,this.renderAsks()}set notice(e){this._notice=e??"",this.renderInput()}set warning(e){this._warning=e??"",this.renderInput()}set defaultOpen(e){this._defaultOpen=!!e}set treeSource(e){this._treeSource=e,this.loadTree(),this.renderMenu()}get treeSource(){return this._treeSource}setTree(e){this.setPanel(e?"tree":this.panel==="tree"?"none":this.panel)}set strings(e){this._strings=e??{},this.renderAll()}set agentAvatar(e){if(Xn(this._agentAvatar,e??null))return;this._agentAvatar=e??null,this.renderLog()}get agentAvatar(){return this._agentAvatar}set userAvatar(e){this.setUser("avatar",e??void 0)}set userName(e){this.setUser("name",e??void 0)}set userId(e){this.setUser("id",e??void 0)}setUser(e,t){if(Xn(this._user[e],t))return;this._user={...this._user,[e]:t},this.renderLog()}set placeholder(e){this._placeholder=e,this.renderPlaceholder()}get draft(){return this._draft}setDraft(e,t){let n=String(e??"").slice(0,He);this.pure=t?.source==="stt"?Tt(this._draft,this.pure,n):null,this._draft=n,this.settledLen=n.length,this.offline=!1;let r=this.els.input;if(r)r.value=n,this.fitInput(),r.setSelectionRange?.(n.length,n.length),r.scrollTop=r.scrollHeight;this.renderPartial(),this.renderStatus(),this.renderAim(),this.arm()}setPartial(e){this._partial=e??"",this.renderPartial(),this.renderPlaceholder(),this.arm()}get micActive(){return this._micActive}set micActive(e){if(typeof this.toggleAttribute==="function")this.toggleAttribute("mic-active",!!e);else this.applyMic(!!e)}attributeChangedCallback(e){if(e==="mic-active")this.applyMic(this.hasAttribute("mic-active"))}applyMic(e){if(e===this._micActive)return;this._micActive=e,this.renderLayout(),this.arm()}key(e){return`${this.getAttribute("storage-key")||"liagent"}:${e}`}read(e){try{return localStorage.getItem(this.key(e))}catch{return null}}write(e,t){try{localStorage.setItem(this.key(e),t)}catch{}}rateStore={getItem:()=>this.read("speech-rate"),setItem:(e,t)=>this.write("speech-rate",t)};get speaking(){return this.read("speak")!=="0"}get speechRate(){return _e(this.rateStore)}speak(e,t){if(!this.speaking&&!this._micActive)return;if(this.voice)return this.voice.speak(e,t);let n=Ce();if(!n)return;let r=new SpeechSynthesisUtterance(e);r.lang=me(e),r.rate=this.speechRate;let s=_t(n.getVoices(),r.lang);if(s)r.voice=s;n.speak(r)}stopSpeech(e){if(this.voice)this.voice.stop(e);else ri()}connectedCallback(){if(document.addEventListener("pointerdown",this.outside,!0),document.addEventListener("keydown",this.escape,!0),addEventListener("resize",this.relayout),addEventListener("orientationchange",this.relayout),globalThis.visualViewport?.addEventListener("resize",this.relayout),this.root){this.loadTree();return}if(this.hasAttribute("collapsed"))this._defaultOpen=!1;let e=this.getAttribute("placeholder");if(e)this._placeholder=e;let t=this.getAttribute("agent-avatar");if(t&&!this._agentAvatar)this._agentAvatar=t;let n=this.getAttribute("user-avatar");if(n&&!this._user.avatar)this._user.avatar=n;let r=this.getAttribute("user-name");if(r&&!this._user.name)this._user.name=r;this._micActive=this.hasAttribute("mic-active");let s=this.read("open");this.open=s===null?this._defaultOpen:s==="1",this.wasOpen=this.open;try{let i=JSON.parse(this.read("pos")??"null");if(i&&Number.isFinite(i.x)&&Number.isFinite(i.y))this.pos=i}catch{}Ce()?.getVoices(),this.root=this.attachShadow({mode:"open"}),this.build(),this.messagesChanged(),this.renderAll(),this.loadTree()}disconnectedCallback(){clearTimeout(this.timer),this.taps.cancel(),this.treeStop?.(),this.treeStop=void 0,document.removeEventListener("pointerdown",this.outside,!0),document.removeEventListener("keydown",this.escape,!0),removeEventListener("resize",this.relayout),removeEventListener("orientationchange",this.relayout),globalThis.visualViewport?.removeEventListener("resize",this.relayout)}outside=(e)=>{if(this.panel!=="menu")return;let t=e.composedPath();if(t.includes(this.els.menu)||t.includes(this.els.mark))return;this.setPanel("none")};escape=(e)=>{if(e.key!=="Escape"||this.panel==="none")return;e.stopPropagation(),this.setPanel("none")};relayout=()=>{this.fit(),this.placeFloat()};get ui(){return{...Bn(),...this._strings}}get treeText(){return{...ve,...Wn(),...this.treeStrings}}build(){let e=this.root,t="";try{let f=new CSSStyleSheet;f.replaceSync(jn),e.adoptedStyleSheets=[f]}catch{t=`<style>${jn}</style>`}e.innerHTML=`${t}
|
|
269
|
+
<section class="box halo" id="box" aria-label="Chat with the agent">
|
|
270
|
+
<div class="column" id="column">
|
|
271
|
+
<ol class="log" id="log"></ol>
|
|
272
|
+
</div>
|
|
273
|
+
<div class="warn" id="warn" role="alert" hidden></div>
|
|
274
|
+
<div class="asks" id="asks" aria-label="Agent connections"></div>
|
|
275
|
+
<div class="rowbox" id="rowbox">
|
|
276
|
+
<div class="aim" id="aim" hidden></div>
|
|
277
|
+
<div class="bar" id="bar">
|
|
278
|
+
<button type="button" class="tap mark" id="mark" title="${oi}">${ue.mark}<span class="dot" id="dot"></span></button>
|
|
279
|
+
<button type="button" class="tap treebtn" id="treebtn" aria-expanded="false" title="${rt}">${ue.tree}<span class="evals" id="evals" aria-hidden="true" hidden></span><span class="thint" id="thint" role="status" hidden></span></button>
|
|
280
|
+
<div class="slot" id="slot">
|
|
281
|
+
<div class="mirror" id="mirror" aria-hidden="true" hidden><span class="ghost" id="ghost"></span><span class="partial" id="partial"></span></div>
|
|
282
|
+
<textarea id="input" rows="1" maxlength="${He}" aria-label="Message the agent"></textarea>
|
|
283
|
+
<p class="notice" id="notice" role="status" hidden></p>
|
|
284
|
+
<span class="spin" id="spin" role="status" hidden></span>
|
|
285
|
+
</div>
|
|
286
|
+
<div class="mic" id="mic" hidden><slot name="mic" id="micslot"></slot></div>
|
|
287
|
+
<span class="unread" id="unread" hidden></span>
|
|
288
|
+
</div>
|
|
289
|
+
<span aria-hidden="true"></span>
|
|
290
|
+
<div class="floatbox" id="floatbox" hidden>
|
|
291
|
+
<div class="ftree" id="ftree"></div>
|
|
292
|
+
<ol class="floats" id="floats" aria-live="polite"></ol>
|
|
293
|
+
<ul class="frontier" id="frontier"></ul>
|
|
294
|
+
</div>
|
|
295
|
+
<div class="menu" id="menu" role="menu" hidden></div>
|
|
296
|
+
</div>
|
|
297
|
+
</section>`;for(let f of e.querySelectorAll("[id]"))this.els[f.id]=f;let{box:n,bar:r,mark:s,treebtn:i,column:o,floats:a,rowbox:l}=this.els,c=this.els.input,u=this.els.micslot,p=document.createElement("div");p.className="treepanel",p.id="tree",p.setAttribute("role","region");let d=document.createElement("button");d.type="button",d.className="x tap",d.textContent="✕",d.addEventListener("mousedown",(f)=>f.preventDefault()),d.addEventListener("click",()=>this.setPanel("none"));let g=document.createElement("div");g.className="tbody",g.addEventListener("scroll",()=>this.treeFade()),p.append(d,g),this.els.tree=p,this.els.tbody=g,this.els.tclose=d,n.addEventListener("pointerdown",Gn),n.addEventListener("keydown",Gn),this.dragHandle(s,()=>!0),s.addEventListener("pointerdown",()=>this.setHolding(!0));for(let f of["pointerup","pointercancel"])s.addEventListener(f,()=>this.setHolding(!1));if(s.addEventListener("click",()=>!this.markDrag.wasDrag()&&this.taps.tap()),this.dragHandle(r,(f)=>f.target===r),this.treeGestures(i),o.addEventListener("scroll",()=>this.onColumnScroll()),o.addEventListener("wheel",()=>this.userScrollAt=Date.now(),{passive:!0}),o.addEventListener("touchmove",()=>this.userScrollAt=Date.now(),{passive:!0}),o.addEventListener("transitionend",(f)=>{if(f.target!==o)return;if(!this.wide())this.toEnd();this.onColumnScroll()}),l.addEventListener("transitionend",(f)=>{if(f.target!==l)return;this.fitInput(),this.placeFloat()}),a.addEventListener("pointerenter",()=>this.holdFloats(!0)),a.addEventListener("pointerleave",()=>this.holdFloats(!1)),a.addEventListener("pointercancel",()=>this.holdFloats(!1)),a.addEventListener("touchstart",()=>this.holdFloats(!0),{passive:!0}),a.addEventListener("touchend",()=>this.holdFloats(!1),{passive:!0}),u.addEventListener("slotchange",()=>{this.els.mic.hidden=!u.assignedElements().length}),this.els.mic.hidden=!u.assignedElements().length,typeof ResizeObserver<"u"){let f=c.clientWidth;this.ro=new ResizeObserver((m)=>{for(let y of m)if(y.target===c){if(c.clientWidth===f)continue;f=c.clientWidth,this.fitInput()}else this.placeFloat()}),this.ro.observe(c),this.ro.observe(this.els.floatbox)}c.addEventListener("input",()=>{this._draft=c.value,this.offline=!1,this.stopSpeech("typing"),this.fitInput(),this.renderPartial(),this.arm(),this.renderStatus(),this.renderAim()}),c.addEventListener("scroll",()=>this.els.mirror.scrollTop=c.scrollTop),c.addEventListener("focus",()=>{this.typing=!0,this.renderLayout()}),c.addEventListener("blur",()=>{this.typing=!1,this.renderLayout()}),c.addEventListener("compositionstart",()=>{this.composing=!0,this.disarm()}),c.addEventListener("compositionend",()=>{this.composing=!1,this.arm()}),c.addEventListener("beforeinput",(f)=>{let m=f;if(Rt(m.inputType,{composing:this.composing,isComposing:m.isComposing,shiftEnter:this.shiftEnter})){f.preventDefault();let y=this.completions()[0];if(y)return this.pick(y);this.submit()}}),c.addEventListener("keydown",(f)=>{this.shiftEnter=f.key==="Enter"&&f.shiftKey;let m=this.completions()[0];if((f.key==="Tab"||f.key==="Enter")&&!f.shiftKey&&m)return f.preventDefault(),this.pick(m);if(f.key==="Backspace"&&!this._draft&&this._target!==P)return this.setTarget(P);if(!Nt(f,this.composing))return;f.preventDefault(),this.submit()}),this.swipeScrollsLog(c)}swipeScrollsLog(e){let t=0,n=!1;e.addEventListener("touchstart",(r)=>{t=r.touches[0].clientY,n=!1},{passive:!0}),e.addEventListener("touchmove",(r)=>{if(e.value.length>0)return;let s=r.touches[0].clientY;if(!n&&Math.abs(s-t)<6)return;if(n=!0,this.els.column.scrollTop-=s-t,this.userScrollAt=Date.now(),t=s,r.cancelable)r.preventDefault()},{passive:!1})}dragHandle(e,t){let n=null;e.addEventListener("pointerdown",(s)=>{if(!t(s))return;n={px:s.clientX,py:s.clientY,x:this.pos.x,y:this.pos.y,moved:!1},this.markDrag.down(),e.setPointerCapture?.(s.pointerId)}),e.addEventListener("pointermove",(s)=>{if(!n)return;let i=s.clientX-n.px,o=s.clientY-n.py;if(!n.moved&&Math.hypot(i,o)<5)return;n.moved=!0;let a=this.els.bar.getBoundingClientRect(),l=a.left-(this.pos.x-n.x),c=a.top-(this.pos.y-n.y),u=nt().top;this.pos={x:n.x+Math.max(-l,Math.min(innerWidth-a.width-l,i)),y:n.y+Math.max(u-c,Math.min(innerHeight-a.height-c,o))},this.style.transform=`translate(${this.pos.x}px, ${this.pos.y}px)`});let r=()=>{let s=n?.moved;if(n=null,this.setHolding(!1),!s)return;this.markDrag.dragEnded(),this.write("pos",JSON.stringify(this.pos)),this.placeFloat()};e.addEventListener("pointerup",r),e.addEventListener("pointercancel",()=>{n=null,this.setHolding(!1)})}setHolding(e){if(this.holding===e)return;this.holding=e,this.renderPlaceholder()}fit(){let e=this.els.bar?.getBoundingClientRect(),t=this.els.box?.getBoundingClientRect();if(!e||!t||!e.width)return;let n=this.open?t:e,r=nt().top,s=n.left<0?-n.left:n.right>innerWidth?innerWidth-n.right:0,i=e.top<r?r-e.top:e.bottom>innerHeight?innerHeight-e.bottom:0;if(!s&&!i)return;this.pos={x:this.pos.x+s,y:this.pos.y+i},this.style.transform=`translate(${this.pos.x}px, ${this.pos.y}px)`,this.write("pos",JSON.stringify(this.pos))}treeGestures(e){e.addEventListener("mousedown",(t)=>t.preventDefault()),e.addEventListener("pointerdown",(t)=>{this.treeAxis.down(t.clientX,t.clientY),this.treeDragged.down(),this.treePress={cells:0,limitAt:null},e.setPointerCapture?.(t.pointerId)}),e.addEventListener("pointermove",(t)=>{let n=this.treeAxis.axis(),r=this.treeAxis.move(t.clientX,t.clientY);if(!r||r.axis!=="x"||!this._treeSource)return;if(!n){if(this.panel!=="tree")this.setPanel("tree");this.nav=Ae(this.navIx.ix,this.nav,{type:"dragStart"})}let s=this.treePress;s.cells=mn(r.dx,s.cells);let i=Ae(this.navIx.ix,this.nav,{type:"dragMove",cells:s.cells});s.limitAt=i.atLimit?s.limitAt??s.cells-Math.sign(s.cells):null,this.setNav(i),this.showTreeHint(r.dx,s.limitAt)}),e.addEventListener("pointerup",()=>{let t=this.treeAxis.up();if(!t)return;if(this.treeDragged.dragEnded(),t==="x")this.navTo({type:"dragEnd"});this.els.thint.hidden=!0}),e.addEventListener("pointercancel",()=>{if(this.treeAxis.up()==="x")this.navTo({type:"dragCancel"});this.els.thint.hidden=!0}),e.addEventListener("click",()=>{if(this.treeDragged.wasDrag())return;this.setPanel(this.panel==="tree"?"none":"tree")}),e.addEventListener("keydown",(t)=>{if(this.panel!=="tree"||!t.key.startsWith("Arrow"))return;t.preventDefault(),this.navTo({type:"key",key:t.key})})}showTreeHint(e,t){let n=this.els.thint,r=this.nav.focusId,s=r===null?void 0:this.navIx.byId.get(r),i=r===null?0:this.nav.expanded[r]??0,o=r===null?0:Te(this.navIx.ix,r);n.textContent=s?`${s.title} · ${i}/${o}`:"—",n.style.transform=`translateX(${Math.round(yn(e,t??void 0)*0.25)}px)`,n.hidden=!1}loadTree(){this.treeStop?.(),this.treeStop=void 0;let e=this._treeSource;if(!e){this.treeRoot=null,this.treeError="",this.setRoot(null);return}if(!this.isConnected||!this.root)return;this.treeStop=oe(e,{repo:this.treeRepo},(t)=>{this.treeError="",this.setRoot(t)},(t)=>{this.treeError=t instanceof Error?t.message:String(t),this.renderTree()})}setRoot(e){this.treeRoot=e,this.navIx=et(e);let t=this.nav.focusId;if(t===null||!this.navIx.ix.parent.has(t))this.nav=Qe(this.navIx.ix);this.renderTree(),this.renderFrontier()}setNav(e){if(e===this.nav)return;this.nav=e,this.renderTree()}navTo(e){let t=this.open?this.els.column:this.els.tbody,n=()=>this.els.tbody.querySelectorAll("[data-id]"),r=new Map;for(let c of n())r.set(c.dataset.id,c.getBoundingClientRect().top);let s=(c)=>Object.values(c).reduce((u,p)=>u+p,0),i=this.nav,o=Ae(this.navIx.ix,i,e);this.setNav(o);let a=o.focusId;if(a===null)return;let l=[...n()].find((c)=>c.dataset.id===a);if(!l)return;if(s(o.expanded)>s(i.expanded)){if(Date.now()-this.userScrollAt<600)return;let u=[...n()].filter((f)=>f.dataset.id.startsWith(`${a}.`)).at(-1)??l,p=l.getBoundingClientRect().top,d=u.getBoundingClientRect().bottom,g=t.getBoundingClientRect();if(d>g.bottom)t.scrollTop+=Math.min(d-g.bottom,p-g.top);else if(p<g.top)t.scrollTop-=g.top-p}else{let c=r.get(a);if(c!==void 0)t.scrollTop+=l.getBoundingClientRect().top-c}}renderTree(){if(!this.root)return;let e=this.els.tbody,t=this.treeText;e.replaceChildren(this._treeSource?kn({root:this.treeRoot,nav:this.nav,ix:this.navIx.ix,byId:this.navIx.byId,onNav:(n)=>this.navTo(n),status:this.treeError?`${t.failed} (${this.treeError})`:this.treeRoot?void 0:t.loading,empty:t.empty,label:this.ui.stateTree,needsYou:this.ui.needsYou}):Object.assign(document.createElement("p"),{className:"chips status",textContent:this.ui.noTreeSource})),this.treeFade()}treeFade(){let e=this.els.tbody;if(e)e.classList.toggle("fade",e.scrollHeight>e.clientHeight+1||e.scrollTop>0)}disarm(){clearTimeout(this.timer),this.els.bar?.querySelector(".drain")?.remove()}arm(){if(this.disarm(),X(this._draft)?.complete===!1)return;let e=It(this._draft,this.settledLen,this.composing);if(!this.composing)this.settledLen=this._draft.length;if(e==="send")return void this.submit();if(e==="idle"||this._micActive||this._partial)return;let t=document.createElement("div");t.className="drain",t.setAttribute("aria-hidden","true"),t.style.setProperty("--drain-ms",`${ne}ms`),this.els.bar.prepend(t),this.timer=setTimeout(()=>this.submit(),ne)}submit(){this.disarm();let e=this._draft.trim(),t=X(e);if(t){if(!t.complete)return!1;if(this.setTarget(t.to),e=t.text,!e)return this.clearDraft(),!1}if(!e)return!1;let n=this._target===P?void 0:this._target,r=At(this._draft,this.pure);if(!this.onSend?.(e,n,r?{source:r}:void 0))return this.offline=!0,this.renderStatus(),!1;return this.offline=!1,this.clearDraft(),!0}clearDraft(){this._draft="",this.pure=null,this.settledLen=0;let e=this.els.input;if(e)e.value="";this.fitInput(),this.renderPartial(),this.renderStatus(),this.renderAim()}fitInput(){let e=this.els.input;if(!e)return;if(e.style.height="",!e.value||e.clientWidth<40)return;e.style.height="auto";let t=e.offsetHeight-e.clientHeight;e.style.height=`${Math.min(e.scrollHeight+t,qn)}px`}completions(){let e=/^@\/\S*(?:\s*›\s*\S*)*$/.test(this._draft)?X(this._draft):null;return e&&!e.complete?Pt(this._draft,this._nodes):[]}pick(e){this.setTarget(e),this.clearDraft(),this.els.input.focus()}renderPlaceholder(){let e=this.els.input;if(!e)return;e.placeholder=this.holding?ii:this._partial?"":this._target!==P?`Message ${z(this._target)}…`:this._placeholder||(this._live&&!this._listeners?"Agent offline — your message waits for it…":"Message the agent…")}renderPartial(){let e=this.els.mirror;if(!e)return;let t=Ot(this._draft,this._partial);e.hidden=!t,this.els.ghost.textContent=t?this._draft:"",this.els.partial.textContent=t,e.scrollTop=this.els.input.scrollTop}renderAim(){let e=this.els.aim;if(!e)return;e.replaceChildren();let t=this.completions(),n=X(this._draft)?.complete?X(this._draft):null,r=n?n.to:this._target;if(t.length){let s=document.createElement("ul");s.className="nodes",s.setAttribute("role","listbox"),s.setAttribute("aria-label","Nodes to address");for(let i of t){let o=document.createElement("li");o.setAttribute("role","option");let a=document.createElement("button");a.type="button",a.textContent=z(i),a.addEventListener("pointerdown",(l)=>l.preventDefault()),a.addEventListener("click",()=>this.pick(i)),o.append(a),s.append(o)}e.append(s)}if(r!==P){let s=document.createElement("span");s.className=n?"target preview":"target",s.dataset.node=r;let i=Ue({from:"owner",to:r})?.border;if(i)s.style.setProperty("--node",i);let o=document.createElement("span");if(o.textContent=`→ ${z(r)}`,s.append(o),!n){let a=document.createElement("button");a.type="button",a.textContent="×",a.setAttribute("aria-label","Send to the main thread instead"),a.addEventListener("pointerdown",(l)=>l.preventDefault()),a.addEventListener("click",()=>this.setTarget(P)),s.append(a)}e.append(s)}e.hidden=!this.open||!e.childElementCount}setOpen(e){if(e)this.atEnd=!0;this.open=e,this.write("open",e?"1":"0"),this.messagesChanged(),this.renderAll(),requestAnimationFrame?.(()=>this.fit())}setPanel(e){if(e===this.panel)return;let t=e==="tree"&&this.panel!=="tree";if(this.panel=e,t)this.loadTree();if(this.renderLayout(),this.renderMenu(),t&&this.open)this.els.column.scrollTop=0;requestAnimationFrame?.(()=>this.fit())}wide(){return this.typing||this._micActive||this.panel==="tree"}status(){if(this._notice)return"chat unavailable";if(this.offline)return"not connected — your draft is kept";if(!this._live)return"reconnecting…";return this._listeners?`agent listening (${this._listeners})`:"agent offline · messages wait until it is back"}renderAll(){if(!this.root)return;this.style.transform=`translate(${this.pos.x}px, ${this.pos.y}px)`,this.renderLayout(),this.renderAsks(),this.renderEvals(),this.renderBusy(),this.renderLog(),this.renderInput(),this.renderAim(),this.renderPlaceholder(),this.renderPartial(),this.renderTree(),this.renderFrontier(),this.renderStatus(),this.renderMenu()}renderLayout(){if(!this.root)return;let{box:e,column:t,slot:n,mark:r,treebtn:s,tree:i,tclose:o,ftree:a}=this.els,l=this.ui;if(e.classList.toggle("min",!this.open),e.classList.toggle("on",this._micActive||this.panel!=="none"),t.hidden=!this.open,n.toggleAttribute("inert",!this.open),this.open)n.removeAttribute("aria-hidden");else n.setAttribute("aria-hidden","true");if(r.setAttribute("aria-expanded",String(this.open)),s.setAttribute("aria-expanded",String(this.panel==="tree")),s.setAttribute("aria-label",l.stateTree),i.setAttribute("aria-label",l.stateTree),o.setAttribute("aria-label",l.closeTree),this.panel==="tree"){let u=this.open?t:a;if(i.parentElement!==u)u.prepend(i)}else i.remove();let c=this.wide();if(t.classList.toggle("wide",c),this.els.tbody.classList.toggle("wide",c),this.renderAim(),this.renderFrontier(),this.onColumnScroll(),this.treeFade(),!c&&this.panel!=="tree")this.toEnd();this.placeFloat()}renderStatus(){if(!this.root)return;let e=this._live&&this._listeners?"oklch(0.68 0.16 150)":this._live?"oklch(0.75 0.13 75)":"oklch(0.62 0.02 70)";this.els.dot.style.background=e;let t=this.status();this.els.bar.title=t;let n=this.open?0:An(this._messages,(s)=>this.arrivals.seqOf(s),this.readSeq),r=this.els.unread;if(r.hidden=n===0,r.textContent=String(n),this.els.mark.setAttribute("aria-label",this.open?"Minimize chat":`Restore chat${n?`, ${n} new`:""}`),this.renderPlaceholder(),this.panel==="menu")this.renderMenu()}renderEvals(){if(!this.root)return;let e=this._sessions.filter((r)=>r.scope!=="chat"),t=this.els.evals;t.hidden=!e.length,t.textContent=String(e.length),t.classList.toggle("ran",this._evalRan);let n=this._friend?"preview":"eval";this.els.treebtn.title=e.length?`${rt}
|
|
298
|
+
${e.map((r)=>`${n}: ${r.label} · ${r.code}`).join(`
|
|
299
|
+
`)}`:rt}renderBusy(){if(!this.root)return;let e=this.els.spin;e.hidden=!this._busy,e.title="the agent is working",e.setAttribute("aria-label","the agent is working"),this.els.input.classList.toggle("pe",this._busy)}renderAsks(){if(!this.root)return;let e=this.els.asks;e.replaceChildren();let t=this._pending;if(t)e.append(this.renderAsk(t))}renderAsk(e){let t=document.createElement("span");t.className="ask",t.setAttribute("role","alertdialog");let n=this._friend?"to run code on the chosen pages, for 1 hour":e.scope==="eval"?"to run code on the chosen pages and chat, for 8 hours":e.scope==="chat"?"to chat with you, for 30 days":"to run code on your pages, or to chat",r=`${e.label} asks ${n}. Allow only if the agent shows the same code: ${e.code}.`;t.setAttribute("aria-label",r),t.title=r,t.innerHTML=ue.lock;let s=document.createElement("b");if(s.textContent=e.code,t.append(s),e.scope){let d=document.createElement("span");d.className="tag",d.textContent=this._friend?"code · 1h":e.scope==="eval"?"code · 8h":"chat · 30d",t.append(d)}if(!this.picked.has(e.pair))this.picked.set(e.pair,new Set(this._self?[this._self]:[]));let i=this.picked.get(e.pair),o=()=>{let d=this.picked.get(e.pair);if(d==="all")return"all";return d&&d.size?[...d]:void 0},a=(d,g,f,m)=>{let y=document.createElement("button");y.type="button",y.className=d,y.textContent=g,y.title=f,y.setAttribute("aria-label",f),y.addEventListener("click",m),t.append(y)};if(e.scope||this._friend)a("y","Allow","Allow on the ticked pages",()=>this.onAnswer?.("allow",e,{pages:o()}));else a("y","8h","Allow code and chat for 8 hours",()=>this.onAnswer?.("allow",e,{pages:o()})),a("c","chat","Chat only, for 30 days",()=>this.onAnswer?.("allow",e,{pages:o(),scope:"chat"}));if(a("n","✕","Deny",()=>this.onAnswer?.("deny",e,{})),this._pages.length<2||e.scope==="chat"&&!this._friend)return t;let l=document.createElement("div");l.className="askwrap";let c=document.createElement("div");c.className="pagelist";let u=(d,g,f)=>{let m=document.createElement("label"),y=document.createElement("input");y.type="checkbox",y.checked=g,y.addEventListener("change",()=>f(y.checked)),m.append(y,document.createTextNode(d)),c.append(m)},p=i==="all";for(let d of this._pages)u(`${Kn(d.label)}${d.id===this._self?" (this page)":""}`,p||i.has(d.id),(g)=>{let f=this.picked.get(e.pair),m=f==="all"?new Set(this._pages.map((y)=>y.id)):new Set(f);if(g)m.add(d.id);else m.delete(d.id);this.picked.set(e.pair,m),this.renderAsks()});return u("all pages, and pages opened later",p,(d)=>{this.picked.set(e.pair,d?"all":new Set(this._self?[this._self]:[])),this.renderAsks()}),l.append(t,c),l}lineBody(e,t){if(!e.edited||e.raw===void 0)return[document.createTextNode(e.text)];let n=this.rawIds.has(e.id),r=document.createElement("span");if(n)r.className="raw";r.textContent=n?e.raw:e.text;let s=document.createElement("button");return s.type="button",s.className="polished",s.title=this.ui.polished,s.setAttribute("aria-label",this.ui.polished),s.setAttribute("aria-pressed",String(n)),s.innerHTML=ue.sparkle,s.addEventListener("click",(i)=>{if(i.stopPropagation(),!this.rawIds.delete(e.id))this.rawIds.add(e.id);t()}),[r,s]}renderLog(){if(!this.root)return;let e=this.els.log;if(e.replaceChildren(),this._messages.length===0){let t=document.createElement("li");t.className="hint",t.textContent=`Type here; it is sent ${ne/1000} s after you stop.`,e.append(t)}for(let t of this._messages){let n=document.createElement("li");n.dataset.from=t.from;let r=cn(t,{friend:this._friend,user:this._user,agentAvatar:this._agentAvatar,avatarFor:this.avatarFor}),s=Ue(t);n.title=s?`${Yn(t.at)} · ${r.name} · ${s.subtitle}`:Yn(t.at);let i=document.createElement("span");if(i.className="text",s){n.classList.add("node"),n.dataset.node=s.node,n.style.setProperty("--node",s.border);let a=document.createElement("span");a.className="sub",a.setAttribute("aria-hidden","true"),a.textContent=s.subtitle,i.append(a)}let o=document.createElement("span");o.className="sr",o.textContent=s?`${r.name} (${s.subtitle}): `:`${r.name}: `,i.append(o,...this.lineBody(t,()=>{this.renderLog(),this.renderFloatTexts()})),n.append(Jn(r.srcs,r.node,r.name,Ze(r.initialFrom),r.seed),i),e.append(n)}if(this.open&&this.atEnd)this.toEnd();this.onColumnScroll(),this.renderStatus()}toEnd(){let e=this.els.column;if(!e||!this.open)return;e.scrollTop=e.scrollHeight,this.atEnd=!0}onColumnScroll(){let e=this.els.column;if(!e)return;e.classList.toggle("fade",e.scrollHeight>e.clientHeight+1||e.scrollTop>0),this.atEnd=e.scrollHeight-e.scrollTop-e.clientHeight<4}messagesChanged(e=!1){let t=Date.now(),{fresh:n,history:r}=this.arrivals.see(this._messages,t);if(this.open||r)this.readSeq=this.arrivals.seq();let s=this.wasOpen&&!this.open;if(this.wasOpen=this.open,e)this.atEnd=!0;if(this.renderLog(),!this.root)return;if(this.open)return this.clearFloats();if(s){this.clearFloats(),this.frontierOpen=null;let i=Mn(this._messages,t,this.arrivals.at);if(i)this.addFloat(i);return}if(r)return;for(let i of n)this.addFloat(i)}clearFloats(){for(let e of this.floats.values())e.life.cancel();this.floats.clear(),this.els.floats?.replaceChildren()}addFloat(e){let t=this.floats.get(e.id);if(t)t.life.cancel(),t.li.remove(),this.floats.delete(e.id);let n=document.createElement("li");n.className="float",n.dataset.from=e.from;let r={m:e,li:n,life:_n({ms:En(e.text),reducedMotion:si(),paused:this.floatHover,onPhase:(s)=>{if(s==="gone")this.dropFloat(e.id);else n.classList.toggle("fading",s==="fade")}})};this.floats.set(e.id,r),this.fillFloat(r.li,e),this.els.floats.append(n);while(this.floats.size>Sn)this.dropFloat(this.floats.keys().next().value);this.placeFloat()}dropFloat(e){let t=this.floats.get(e);if(!t)return;t.life.cancel(),t.li.remove(),this.floats.delete(e),this.placeFloat()}fillFloat(e,t){let n=this._messages.find((s)=>s.id===t.id)??t,r=document.createElement("span");r.className="who",r.style.color=n.from!=="agent"?"oklch(0.55 0.13 250)":"oklch(0.55 0.14 150)",r.textContent=`${n.from!=="agent"?"you":n.label||"agent"}:`,e.replaceChildren(r,...this.lineBody(n,()=>this.renderFloatTexts()))}renderFloatTexts(){for(let e of this.floats.values())this.fillFloat(e.li,e.m)}holdFloats(e){if(this.floatHover===e)return;this.floatHover=e;for(let t of this.floats.values())(e?t.life.pause:t.life.resume)()}renderFrontier(){if(!this.root)return;let e=this.els.frontier;if(e.replaceChildren(),this.open||!this.treeRoot)return this.placeFloat();let t=globalThis.document?.documentElement.lang||void 0,n=On(se(this.treeRoot,{locale:t})),r=this.ui;for(let s of Ln){let i=n?.[s.key];if(!i?.text)continue;let o=i.items??[],a=o.length>0,l=a&&this.frontierOpen===s.key,c=s.key==="doing"?Nn(i.assignee):null,u=In(i.count),p=document.createElement("li");if(p.dataset.status=s.key,l)p.dataset.expanded="";let d=document.createElement("div");d.className="fl";let g=document.createElement("button");g.type="button",g.className="fb";let f=s.key==="done"?r.lastDone:s.key==="doing"?r.nowDoing:r.upNext;if(g.setAttribute("aria-label",`${f}: ${i.text}${u?`, ${i.count} ${r.items}`:""}`),a)g.setAttribute("aria-expanded",String(l));g.addEventListener("mousedown",(b)=>b.preventDefault()),g.addEventListener("click",()=>{if(!a)return;this.frontierOpen=l?null:s.key,this.renderFrontier()});let m=document.createElement("span");if(m.className=`m${s.key==="doing"?" blink":""}`,m.setAttribute("aria-hidden","true"),m.textContent=s.mark,g.append(m),s.key==="doing"&&i.assignee){let b=Zn(i.assignee);b.classList.add("blink"),g.append(b)}let y=document.createElement("span");if(y.className="t",y.textContent=i.text,g.append(y),u){let b=document.createElement("span");b.className="n",b.textContent=u,g.append(b)}if(d.append(g),c)d.append(ai(c));if(p.append(d),l)p.append(li(o));e.append(p)}this.placeFloat()}placeFloat(){let e=this.els.floatbox;if(!e)return;let t=!this.open&&this.panel!=="menu"&&(this.floats.size>0||this.els.frontier.childElementCount>0||this.panel==="tree");if(e.hidden=!t,!t)return;let n=this.els.bar.getBoundingClientRect(),r=this.els.rowbox.getBoundingClientRect(),s=nt(),i=Cn({barLeft:n.left,barRight:n.right,boxWidth:e.getBoundingClientRect().width,vw:document.documentElement.clientWidth||innerWidth,insetLeft:s.left,insetRight:s.right}),o={side:i.side,left:i.left-r.left};if(o.side===this.place.side&&o.left===this.place.left&&e.dataset.side)return;this.place=o,e.dataset.side=o.side,e.style.left=`${o.left}px`}renderInput(){if(!this.root)return;let e=this.els.warn;e.hidden=!this._warning||!this.open,e.textContent=this._warning;let t=this.els.notice;t.hidden=!this._notice,t.textContent=this._notice,this.els.input.hidden=!!this._notice,this.renderStatus()}renderMenu(){if(!this.root)return;let e=this.els.menu;if(e.hidden=this.panel!=="menu",e.hidden)return;e.replaceChildren();let t=document.createElement("span");t.className="status",t.setAttribute("aria-live","polite"),t.textContent=this.status();let n=document.createElement("button");n.type="button",n.setAttribute("role","menuitemcheckbox");let r=this.speaking||this._micActive;n.setAttribute("aria-checked",String(r)),n.innerHTML=ue.speaker,n.append(this._micActive?"Replies read aloud (mic on)":r?"Replies read aloud":"Replies silent"),n.addEventListener("click",()=>{if(this._micActive)return;let c=!this.speaking;if(this.write("speak",c?"1":"0"),!c)this.stopSpeech("off");this.renderMenu()});let s=document.createElement("div");s.className="rate",s.setAttribute("role","radiogroup"),s.setAttribute("aria-label","Reading speed");let i=document.createElement("span");i.textContent="Speed",s.append(i);let o=this.speechRate;for(let c of Me){let u=document.createElement("button");u.type="button",u.setAttribute("role","radio"),u.setAttribute("aria-checked",String(c===o)),u.dataset.rate=String(c),u.textContent=`${c}×`,u.addEventListener("click",()=>{Fn(c,this.rateStore),this.renderMenu()}),s.append(u)}if(e.append(t,n,s),this._treeSource){let c=document.createElement("button");c.type="button",c.setAttribute("role","menuitem"),c.textContent=`☰ ${this.treeText.tree}`,c.addEventListener("click",()=>this.setPanel("tree")),e.append(c)}let a=document.createElement("button");a.type="button",a.setAttribute("role","menuitem"),a.textContent=this.open?"– Minimize":"+ Restore",a.addEventListener("click",()=>{this.setPanel("none"),this.setOpen(!this.open)}),e.append(a);for(let c of this._sessions){let u=document.createElement("div");u.className="sess";let p=document.createElement("span"),d=c.pages===void 0||c.pages==="all"?"all pages":`${c.pages.length} page${c.pages.length===1?"":"s"}`;p.textContent=`${c.scope==="chat"?"chat":this._friend?"preview":"eval"}: ${c.label} · ${c.code} · ${d}`;let g=document.createElement("button");g.type="button",g.textContent="End",g.addEventListener("click",()=>{this.setPanel("none"),this.onEnd?.(c)}),u.append(p,g),e.append(u)}if(this._pages.length<2)return;let l=document.createElement("span");l.className="head",l.textContent="Your open pages",e.append(l);for(let c of this._pages){let u=document.createElement("div");u.className="pg";let p=document.createElement("span"),d=c.id===this._self;p.textContent=`${Kn(c.label)}${d?" (this page)":""}`,p.title=c.label;let g=document.createElement("button");g.type="button",g.textContent=d&&this.confirmEnd===c.id?"End this page?":"End",g.addEventListener("click",()=>{if(d&&this.confirmEnd!==c.id)return this.confirmEnd=c.id,this.renderMenu();this.confirmEnd="",this.onEndPage?.(c.id)}),u.append(p,g),e.append(u)}}}function Xn(e,t){if(e===t)return!0;return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>n===t[r])}function Zn(e){let t=document.createElement("span");t.className="fav",t.setAttribute("role","img"),t.setAttribute("aria-label",`${e.type==="agent"?"Agent":"Person"}: ${e.name}`),t.title=e.name;let{bg:n,fg:r}=Je(`${e.type}:${e.name}`);return t.style.background=n,t.style.color=r,t.textContent=Ze(e.name),t}function ai(e){let t=document.createElement("span");t.className="id",t.title=`agent id: ${e}`,t.setAttribute("aria-label",`agent id ${e}`),t.textContent=Rn(e);let n,r=document.createElement("span");r.className="full",r.setAttribute("role","tooltip"),r.textContent=e;let s=Hn({ms:Pn,onLong:()=>{clearTimeout(n),t.append(r)}});return t.addEventListener("pointerdown",(i)=>i.pointerType!=="mouse"&&s.down()),t.addEventListener("pointerup",()=>{if(s.up())n=setTimeout(()=>r.remove(),2000)}),t.addEventListener("pointerleave",()=>s.cancel()),t.addEventListener("pointercancel",()=>s.cancel()),t.addEventListener("contextmenu",(i)=>i.preventDefault()),t}function li(e){let t=document.createElement("ul");t.className="items";for(let n of e){let r=document.createElement("li");if(n.assignee)r.append(Zn(n.assignee));let s=document.createElement("span");if(s.className="t",s.textContent=n.title,n.path){let i=document.createElement("span");i.className="p",i.textContent=n.path,s.append(i)}r.append(s),t.append(r)}return t}function Jn(e,t,n,r,s,i=0){let o;if(i<e.length){let a=document.createElement("img");a.alt=n,a.referrerPolicy="no-referrer",a.loading="lazy",a.decoding="async",a.draggable=!1,a.addEventListener("error",()=>a.replaceWith(Jn(e,t,n,r,s,i+1)),{once:!0}),a.src=e[i],o=a}else if(o=document.createElement("span"),o.setAttribute("role","img"),o.setAttribute("aria-label",n),t)o.append(t.cloneNode(!0));else{let{bg:a,fg:l}=Je(s);o.style.background=a,o.style.color=l,o.textContent=r}return o.className="av",o.title=n,o.setAttribute("aria-hidden","true"),o}function ci(e="liagent-chat"){if(typeof customElements<"u"&&!customElements.get(e))customElements.define(e,Le);return Le}var ui=30000,di=4000,Qn="liagent:page",pi=()=>{try{return sessionStorage.getItem(Qn)??""}catch{return""}},gi=(e)=>{try{if(e)sessionStorage.setItem(Qn,e)}catch{}};function fi(e,t){let n=new URL(e,location.href);if(n.protocol==="http:")n.protocol="ws:";if(n.protocol==="https:")n.protocol="wss:";n.searchParams.set("label",t);let r=pi();if(r)n.searchParams.set("page",r);return n.toString()}function hi(e,t){let n=null,r,s,i,o=()=>{if(typeof t.label==="function")return t.label();if(t.label)return t.label;let x=matchMedia?.("(display-mode: standalone)").matches?"pwa ":"";return`${location.pathname} ${x}${navigator.userAgent}`},a="",l=!1,c=new WeakSet,u=()=>!l&&document.visibilityState==="visible"&&(t.wanted?.()??!0),p=(x,h)=>{if(!x||x.readyState!==WebSocket.OPEN)return!1;try{return x.send(JSON.stringify(h)),!0}catch{return!1}},d=async(x,h,k,w)=>{clearTimeout(s),e.evalRan=!0,s=setTimeout(()=>e.evalRan=!1,di);let T=performance.now(),C;try{let U=await Lt(w)();C={ok:!0,ms:Math.round(performance.now()-T),value:Ct(U)}}catch(U){let W=U instanceof Error?U:Error(String(U));C={ok:!1,error:`${W.name}: ${W.message}`.slice(0,1000),stack:(W.stack??"").slice(0,2000)}}t.onEval?.({id:h,...C}),p(x,{type:"result",id:h,to:k,...C})},g=()=>{e.live=!1,e.pending=null,e.sessions=[],e.pages=[],e.busy=!1},f=()=>{if(n)return;let x=a=o(),h=new WebSocket(fi(t.url,x));n=h,h.onopen=()=>{c.add(h),e.live=!0},h.onmessage=(k)=>{let w;try{w=JSON.parse(String(k.data))}catch{return}switch(w.type){case"friend-status":e.friend=!0,e.notice=w.status==="blocked"?"Chat is not available for this account.":"";return;case"rate-limited":{let T=Math.max(1,Math.ceil(Number(w.retryIn)/60000)||1);e.warning=`Too many messages: that one was not sent. Try again in ${T} min.`;return}case"state":{let T=w;e.pending=T.pending??null,e.sessions=Array.isArray(T.sessions)?T.sessions:[],e.listeners=T.listeners??e.sessions.length,e.nodes=Array.isArray(T.nodes)?T.nodes:[],e.pages=Array.isArray(T.pages)?T.pages:[];let C=typeof T.self==="string"?T.self:"";e.self=C,gi(C);return}case"busy":e.beat();return;case"history":if(Array.isArray(w.messages))e.messages=te(w.messages);return;case"chat":{let T=w.message;if(!T||typeof T!=="object")return;if(e.push(T),T.from!=="agent")e.warning="";return}case"edited":e.edit(w);return;case"eval":if(!t.evalCode)return;if(typeof w.id!=="string"||typeof w.to!=="string")return;if(typeof w.code!=="string")return;d(h,w.id,w.to,w.code);return}},h.onclose=(k)=>{if(n!==h)return;if(n=null,g(),c.has(h)&&k.code<4000&&u())f()}},m=()=>{clearTimeout(r);let x=n;n=null,g(),x?.close()},y=()=>{if(clearTimeout(r),u())f();else if(l||!(t.wanted?.()??!0))m();else if(n)r=setTimeout(m,ui)};e.onSend=(x,h,k)=>p(n,{type:"chat",id:crypto.randomUUID().slice(0,12),text:x,...h?{to:h}:{},...k?.source?{source:k.source}:{}}),e.onAnswer=(x,h,k)=>void p(n,x==="deny"?{type:x,pair:h.pair}:{type:x,pair:h.pair,...k.pages?{pages:k.pages}:{},...k.scope?{scope:k.scope}:{}}),e.onEnd=(x)=>void p(n,{type:"revoke",pair:x.pair}),e.onEndPage=(x)=>void p(n,{type:"end-page",id:x});let b=()=>{clearTimeout(i),i=setTimeout(()=>{let x=o();if(x===a)return;if(p(n,{type:"page",label:x}))a=x},St)},S=[];if(t.trackPages!==!1){for(let x of["pushState","replaceState"]){let h=history[x];history[x]=function(...k){let w=h.apply(this,k);return b(),w},S.push(()=>history[x]=h)}addEventListener("popstate",b),S.push(()=>removeEventListener("popstate",b))}return document.addEventListener("visibilitychange",y),y(),{update:y,close(){l=!0,document.removeEventListener("visibilitychange",y),clearTimeout(s),clearTimeout(i);for(let x of S)x();m()}}}var st=16000;function it(e,t,n=!1){if(e==="capturing")return"capturing";if(n&&e==="listening")return"speaking";if(t>0)return"transcribing";if(e==="off")return"idle";return e}class J extends Error{status;constructor(e,t){super(t);this.status=e;this.name="SttError"}}var tr=(e)=>e?.name;function mi(e){let t=tr(e);return t==="NotAllowedError"||t==="SecurityError"||t==="NotFoundError"}var Pe={denied:"Microphone permission denied",noMic:"No microphone found",signIn:"Sign in to use the mic",tooMuch:"Too much speech for now; try again in a minute",failed:"Transcription failed ({status})",other:"Mic: {message}"};function nr(e,t=Pe){let n={...Pe,...t},r=tr(e);if(r==="NotAllowedError"||r==="SecurityError")return n.denied;if(r==="NotFoundError")return n.noMic;if(e instanceof J){if(e.status===401)return n.signIn;if(e.status===429)return n.tooMuch;return n.failed.replace("{status}",String(e.status))}return n.other.replace("{message}",String(e?.message??e).slice(0,100))}class rr{next=0;head=0;done=new Map;partials=new Map;add(){return this.next++}resolve(e,t){if(e<this.head)return;this.done.set(e,t),this.partials.delete(e)}partial(e,t){if(e>=this.head&&!this.done.has(e))this.partials.set(e,t)}getPartial(e){return this.partials.get(e)??""}take(){let e="";while(this.done.has(this.head)){let t=this.done.get(this.head);if(this.done.delete(this.head++),t)e=de(e,t)}return e}pending(){return this.next-this.head}interim(){let e="",t=!1;for(let n=this.head;n<this.next;n++){let r=this.done.has(n)?this.done.get(n)??"":this.partials.get(n)||"…";if(r==="…"&&t)continue;t=r==="…",e=de(e,r)}return e}}var Ne=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}。、!?]/u;function de(e,t){let n=t.trim();if(!n)return e;if(!e||/\s$/.test(e))return e+n;return Ne.test(e.at(-1)??"")&&Ne.test(n[0]??"")?e+n:`${e} ${n}`}var yi=/[。..!?!?]$/;var bi=/(?:吗|嗎|呢|么|麼|吧|か|かな|かしら|の|でしょう|ですか|ますか|니까|나요|까요)$/u,xi=/^(?:what|why|how|when|where|who|whom|whose|which|can|could|do|does|did|is|are|was|were|will|would|should|shall|may|might|have|has|had)\b/i,vi=/[\p{P}\s]+$/u;function ki(e){let t=e.trim();if(!t||/[\p{P}~]$/u.test(t))return t;let n=t.replace(vi,"");if(Ne.test(t))return t+(bi.test(n)?"?":"。");return t+(xi.test(n)?"?":".")}var wi=/[\p{L}\p{N}]/u;function sr(e,t){let n=ki(t);if(!n)return{draft:e,send:!1};let r=de(e,n);return{draft:r,send:wi.test(n)&&yi.test(r.trim())}}function er(e){let t=Ne.test(e),n=t?[...e.replace(/\s+/g,"")]:e.split(/\s+/).filter(Boolean),r=n.map((s)=>s.toLowerCase().replace(/[\p{P}\p{S}]/gu,""));return{raw:n,key:r,cjk:t}}function Si(e,t){let n=er(e.trim()),r=er(t.trim());for(let s=Math.min(n.key.length,r.key.length);s>0;s--){let i=n.key.slice(-s);if(i.join("")&&i.every((o,a)=>o===r.key[a]))return de(e.trim(),r.raw.slice(s).join(r.cjk?"":" "))}return de(e.trim(),t)}function ot(e,t,n){if(t===n)return e;let r=Math.max(1,Math.round(e.length*n/t)),s=new Float32Array(r),i=t/n,o=e.length-1;for(let a=0;a<r;a++){let l=a*i,c=Math.floor(l),u=e[Math.min(c,o)]??0,p=e[Math.min(c+1,o)]??0;s[a]=u+(p-u)*(l-c)}return s}function Re(e,t=16000){let n=new ArrayBuffer(44+e.length*2),r=new DataView(n),s=(i,o)=>{for(let a=0;a<o.length;a++)r.setUint8(i+a,o.charCodeAt(a))};s(0,"RIFF"),r.setUint32(4,36+e.length*2,!0),s(8,"WAVE"),s(12,"fmt "),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),s(36,"data"),r.setUint32(40,e.length*2,!0);for(let i=0;i<e.length;i++){let o=Math.max(-1,Math.min(1,e[i]??0));r.setInt16(44+i*2,o<0?o*32768:o*32767,!0)}return new Uint8Array(n)}function Ei(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t/(e.length||1))}function ir(e){let t=new Float32Array(e.reduce((r,s)=>r+s.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function or(e){let t=e.on??0.02,n=e.off??0.01,r=(e.hangMs??700)*e.rate/1000,s=(e.minMs??250)*e.rate/1000,i=0,o=0,a=!1,l=[],c=[],u=()=>{let p=ir(c);return a=!1,c=[],o=0,i=0,p.length<s?"misfire":p};return{push(p){let d=Ei(p);if(!a){if(l=[...l.slice(-1),p],i=d>t?i+1:0,i<2)return null;return a=!0,c=l,l=[],"start"}return c.push(p),o=d<n?o+p.length:0,o>=r?u():null},flush(){return a?u():null}}}function ar(e){let t=e.setTimer??((E,_)=>setTimeout(E,_)),n=e.clearTimer??((E)=>clearTimeout(E)),r=new rr,s="off",i=null,o,a=0,l=[],c=0,u=0,p=null,d=!1,g=e.partials!==!1,f=!1,m=!1,y=Promise.resolve(),b=(E)=>Math.round(E/16000*1000),S=(E)=>E*16000/1000,x=(E)=>{s=E,e.onState(E)},h=()=>e.onPending(r.pending(),r.interim()),k=()=>{let E=r.take();if(E)e.onText(E);h()},w=()=>{l=[],c=0,u=0},T=()=>{if(p===null)return;r.resolve(p,null),p=null,k()},C=(E)=>{if(e.onError?.(E),E instanceof J&&E.status===401)j()},U=()=>{let E=p??(p=r.add()),_=Math.min(c,u+S(1500)),N=ir(l).subarray(c-_);u=0,d=!0,h(),e.upload(Re(N),{seq:E,durationMs:b(_),partial:!0}).then((R)=>r.partial(E,Si(r.getPartial(E),R)),(R)=>{if(R instanceof J&&R.status===429)g=!1;if(R instanceof J&&R.status===401)C(R)}).finally(()=>{d=!1,h()})},W=(E)=>({onSpeechStart(){if(E!==a||f)return;m=!1,x("capturing"),w(),n(o),o=t(()=>void i?.flush(),30000)},onFrame(_,N){if(E!==a||s!=="capturing")return;if(N!==void 0)e.onProb?.(N);if(l.push(_),c+=_.length,u+=_.length,g&&!d&&c>=S(3000)&&u>=S(2500))U()},onMisfire(){if(E!==a||f)return;if(n(o),w(),T(),s==="capturing")x("listening")},onSpeechEnd(_){if(f||m)return;n(o);let N=E===a;if(N&&s==="capturing")x("listening");let R=N&&p!==null?p:r.add();if(N)p=null,w();h(),e.upload(Re(_),{seq:R,durationMs:b(_.length),partial:!1}).then((B)=>r.resolve(R,B),(B)=>{r.resolve(R,null),C(B)}).finally(k)}}),Q=async()=>{let E=++a;g=e.partials!==!1,x("loading");let _;try{_=await e.load(W(E))}catch(N){if(!e.fallback||mi(N)){if(E===a)x("off");e.onError?.(N);return}try{_=await e.fallback(W(E))}catch(R){if(E===a)x("off");e.onError?.(R);return}}if(E!==a)return void _.destroy();if(i=_,!f)await _.start();x("listening")};async function j(){if(s==="off")return;a++,n(o);let E=i;i=null;let _=p;if(p=null,w(),x("off"),E)await E.flush(),await E.destroy();if(_!==null)p=_,T()}function he(E){if(f===E)return;if(f=E,E){if(m=!0,n(o),w(),T(),s==="capturing")x("listening")}let _=i;if(_)y=y.then(()=>E?_.pause():_.start()).catch(()=>{})}return{toggle:()=>s==="off"?Q():j(),hold:he,held:()=>f,off:j,state:()=>s}}function Ti(e,t){if(!t)return e;let n=e.indexOf("#"),r=n<0?e:e.slice(0,n),s=n<0?"":e.slice(n);return`${r}${r.includes("?")?"&":"?"}lang=${encodeURIComponent(t)}${s}`}async function at(e,t,n=fetch){let r=typeof t==="string"?{url:t}:t,s=await n(Ti(r.url,r.lang),{method:"POST",body:e,headers:{"content-type":r.type??"audio/wav",...r.headers},credentials:r.credentials??"same-origin"}),i=await s.json().catch(()=>({}));if(!s.ok)throw new J(s.status,i.error??`stt ${s.status}`);return{...i,text:typeof i.text==="string"?i.text:""}}var Ai=0.08,Mi=80;function lr(e,t=e.currentTime){let n=t+Mi/1000,r=e.createGain();r.gain.setValueAtTime(0.0001,t),r.gain.linearRampToValueAtTime(Ai,t+0.005),r.gain.exponentialRampToValueAtTime(0.0001,n),r.connect(e.destination);let s=[[880,t],[1320,t+0.03]];for(let[i,o]of s){let a=e.createOscillator();a.type="sine",a.frequency.setValueAtTime(i,o),a.connect(r),a.start(o),a.stop(n)}return n}var pe="__liagentMic",ur=1,lt="liagent:mic",_i=(e)=>!!e&&e.getTracks().length>0&&e.getTracks().every((t)=>t.readyState==="live");function cr(e,t){let n=e.storageKey??lt,r=t?.stream??null,s={state:"off",pending:0,interim:"",error:null,resume:!1,speaking:!1},i,o=null,a=null,l=new Set,c=null,u=[],p=0,d=(h)=>{s={...s,...h};for(let k of l)k(s)},g={on:()=>{try{e.storage?.set(n,"1")}catch{}},clear:()=>{try{e.storage?.remove(n)}catch{}},get:()=>{try{return e.storage?.get(n)==="1"}catch{return!1}}},f=async()=>{if(r&&_i(r))return r;return p++,r=await e.getStream(i),r},m=()=>{for(let h of r?.getTracks()??[])h.stop();r=null},y=e.fallback,b="off",S=ar({load:async(h)=>e.load(h,await f(),i),fallback:y?async(h)=>y(h,await f(),i):void 0,upload:async(h,k)=>{let w=await e.upload(h,k,i),T=w&&o?.echoCheck?o.echoCheck(w,k.durationMs):void 0;if(!k.partial)e.onUtterance?.({...k,wav:h,text:w,echo:T},i);if(T?.drop){if(!k.partial)o?.echoDropped?.();return""}return w},onState:(h)=>{let k=b;if(b=h,d({state:h,...h!=="off"?{resume:!1}:{}}),o){if(o.setMic(h!=="off"),h==="capturing")o.userSpeech();else if(k==="capturing")o.userIdle()}e.onState?.(h,k)},onText:(h)=>c?c.onText(h):void u.push(h),onPending:(h,k)=>{d({pending:h,interim:k}),c?.onPending(h,k)},onError:(h)=>d({error:h}),onProb:(h)=>o?.userFrame?.(h)}),x={v:ur,view:()=>s,stream:()=>r,gumCalls:()=>p,subscribe(h){return l.add(h),h(s),()=>void l.delete(h)},attach(h){c=h;let k=u;u=[];for(let w of k)h.onText(w);return h.onPending(s.pending,s.interim),()=>{if(c===h)c=null}},configure(h){i=h},config:()=>i,setVoice(h){if(h===o)return;if(a?.(),a=null,o=h,!h){S.hold(!1),d({speaking:!1});return}let k=(w)=>{if(S.hold(w.hold),w.speaking!==s.speaking)d({speaking:w.speaking})};if(k(h.state()),a=h.subscribe(k),S.state()!=="off")h.setMic(!0)},voice:()=>o,async toggle(){if(d({error:null}),S.state()==="off")g.on(),await S.toggle();else await x.off()},async off(){g.clear(),d({resume:!1}),await S.off(),m()},hold:(h)=>S.hold(h),async retire(){a?.(),a=null,o=null,l.clear(),c=null;let h=r;return r=null,await S.off(),h},async autoResume(){if(!g.get())return;let h=(C)=>{d({resumed:C,...C.path==="tap"?{resume:!0}:{}}),e.onResume?.(C)},k=(C)=>h({path:"tap",reason:C}),w="unknown";try{w=await e.permission?.()??"unknown"}catch{}if(w!=="granted"&&w!=="unknown")return k(`permission ${w}`);let T=!0;try{T=await e.resumeAudio?.()??!0}catch{T=!1}if(!T)return k("audio context suspended");if(await S.toggle(),S.state()==="off"){let C=s.error;return k(C?.name||C?.message||"capture did not start")}h({path:"auto",ok:!0,permission:w})}};if(t?.on)S.toggle();return x}function ct(e){let t=globalThis,n=t[pe];if(n&&n.v===ur)return n;if(n){let s=(n.view?.().state??"off")!=="off",i=n.stream?.()??null;n.retire?.();let o=cr(e,{stream:i,on:s});return t[pe]=o,o}let r=cr(e);return t[pe]=r,queueMicrotask(()=>void r.autoResume()),r}var Ci={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1},Li={echoCancellation:!0,noiseSuppression:!0,channelCount:1},Pi=(e=!0)=>e?{...Ci}:{...Li},dr=null;function Ni(e){try{let t=e.getAudioTracks()[0]?.getSettings?.()??{},{echoCancellation:n,noiseSuppression:r,autoGainControl:s,sampleRate:i,channelCount:o}=t;dr={echoCancellation:n,noiseSuppression:r,autoGainControl:s,sampleRate:i,channelCount:o}}catch{dr=null}}var ut="__liagentAudio";function Ie(){let e=globalThis,t=e[ut];if(t)return t;let n=globalThis.AudioContext??globalThis.webkitAudioContext;return n?e[ut]=new n:null}var ge=()=>globalThis[ut]??null,fr=()=>typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia&&!!(globalThis.AudioContext??globalThis.webkitAudioContext);async function hr(e=!0){let t=await navigator.mediaDevices.getUserMedia({audio:Pi(e)});return Ni(t),t}var pr=(e)=>new Promise((t,n)=>{if(document.querySelector(`script[src="${CSS.escape(e)}"]`))return t();let r=document.createElement("script");r.src=e,r.async=!0,r.onload=()=>t(),r.onerror=()=>{r.remove(),n(Error(`could not load ${e}`))},document.head.append(r)}),gr=(e)=>e.endsWith("/")?e:`${e}/`;function dt(e,t){let n=gr(e),r=gr(t);return{baseAssetPath:n,onnxWASMBasePath:r,load:async()=>{await pr(`${r}ort.wasm.min.js`),await pr(`${n}bundle.min.js`);let s=globalThis.vad;if(!s?.MicVAD)throw Error("vad-web did not load");return s}}}var Ri=(e)=>typeof e==="function"?{load:e}:e;async function mr(e,t,n){let r=Ri(n),s=await r.load(),i="MicVAD"in s?s:s.default;if(!i?.MicVAD)throw Error("vad-web: no MicVAD");let o=await i.MicVAD.new({...r.baseAssetPath?{baseAssetPath:r.baseAssetPath}:{},...r.onnxWASMBasePath?{onnxWASMBasePath:r.onnxWASMBasePath}:{},model:r.model??"v5",submitUserSpeechOnPause:!0,startOnLoad:!1,...r.options,getStream:async()=>t,pauseStream:async()=>{},resumeStream:async()=>t,onSpeechStart:e.onSpeechStart,onSpeechEnd:e.onSpeechEnd,onVADMisfire:e.onMisfire,onFrameProcessed:(a,l)=>e.onFrame?.(l,a?.isSpeech)});return{start:()=>o.start(),pause:()=>o.pause(),flush:async()=>{await o.pause(),await o.start()},destroy:()=>o.destroy()}}async function yr(e,t){let n=Ie();if(!n)throw Error("no Web Audio");let r=n.createMediaStreamSource(t),s=n.createScriptProcessor(2048,1,1),i=or({rate:n.sampleRate}),o=!1,a=(l)=>{if(l==="start")e.onSpeechStart();else if(l==="misfire")e.onMisfire();else if(l)e.onSpeechEnd(ot(l,n.sampleRate,st))};return s.onaudioprocess=(l)=>{if(!o)return;let c=new Float32Array(l.inputBuffer.getChannelData(0)),u=i.push(c);if(u==="start")a(u);if(e.onFrame?.(ot(c,n.sampleRate,st)),u!=="start")a(u)},r.connect(s),s.connect(n.destination),{start:()=>(o=!0,n.resume()),pause:()=>{o=!1,a(i.flush())},flush:()=>a(i.flush()),destroy:()=>{o=!1,s.disconnect(),r.disconnect()}}}var br=(e)=>!!e&&typeof e.setDraft==="function"&&typeof e.setPartial==="function"&&typeof e.submit==="function";function Sr(e,t){let n=sr(e.draft??"",t);if(n.draft===e.draft)return!1;return e.setDraft(n.draft,{source:"stt"}),n.send&&e.submit()!==!1}var Er={...Pe,dictate:"Dictate: listen and type what you say",resume:"Tap to resume listening",speaking:"Agent speaking; tap to interrupt and talk",recording:"Recording; tap to stop listening",listening:"Listening; tap to stop",rec:"REC",noStt:"No STT endpoint: set stt-url"};function xr(e,t,n=Er){if(e.state==="off")return e.resume?n.resume:n.dictate;if(t==="speaking")return n.speaking;return e.state==="capturing"?n.recording:n.listening}class pt extends Error{constructor(){super("no STT endpoint");this.name="NoStt"}}function Ii(e){let t=()=>globalThis.sessionStorage;return{getStream:(n)=>hr(n?.aec??!0),load:(n,r,s)=>s?.vad?mr(n,r,s.vad):Promise.reject(Error("no VAD source")),fallback:(n,r)=>yr(n,r),upload:async(n,r,s)=>{if(!s?.stt)throw new pt;let i=await s.stt(n,r);return typeof i==="string"?i:i.text??""},onState:(n)=>{let s=globalThis[pe]?.view().speaking??!1;if(n==="off"&&!s)ge()?.suspend().catch(()=>{})},onUtterance:(n,r)=>r?.onUtterance?.(n),storage:{get:(n)=>t().getItem(n),set:(n,r)=>t().setItem(n,r),remove:(n)=>t().removeItem(n)},storageKey:e,permission:async()=>(await navigator.permissions?.query({name:"microphone"}))?.state??"unknown",resumeAudio:async()=>{let n=Ie();if(!n)return!1;if(n.state==="running")return!0;return await Promise.race([n.resume().catch(()=>{}),new Promise((r)=>setTimeout(r,800))]),n.state==="running"}}}var vr={regular:"M128,176a48.05,48.05,0,0,0,48-48V64a48,48,0,0,0-96,0v64A48.05,48.05,0,0,0,128,176ZM96,64a32,32,0,0,1,64,0v64a32,32,0,0,1-64,0Zm40,143.6V240a8,8,0,0,1-16,0V207.6A80.11,80.11,0,0,1,48,128a8,8,0,0,1,16,0,64,64,0,0,0,128,0,8,8,0,0,1,16,0A80.11,80.11,0,0,1,136,207.6Z",fill:"M80,128V64a48,48,0,0,1,96,0v64a48,48,0,0,1-96,0Zm128,0a8,8,0,0,0-16,0,64,64,0,0,1-128,0,8,8,0,0,0-16,0,80.11,80.11,0,0,0,72,79.6V240a8,8,0,0,0,16,0V207.6A80.11,80.11,0,0,0,208,128Z"},kr=`
|
|
300
|
+
:host {
|
|
301
|
+
position: relative; display: inline-flex; flex-shrink: 0;
|
|
302
|
+
color: var(--liagent-fg, CanvasText);
|
|
303
|
+
--rec: var(--liagent-mic-rec, oklch(0.6 0.22 25));
|
|
304
|
+
--talk: var(--liagent-mic-talk, oklch(0.62 0.14 250));
|
|
305
|
+
}
|
|
306
|
+
:host([hidden]) { display: none; }
|
|
307
|
+
button {
|
|
308
|
+
all: unset; box-sizing: border-box; position: relative; cursor: pointer;
|
|
309
|
+
display: flex; flex-direction: column; align-items: center; justify-content: center;
|
|
310
|
+
width: 40px; height: 32px; border-radius: 999px; font-size: 16px; line-height: 1;
|
|
311
|
+
color: color-mix(in oklch, currentColor 55%, transparent); touch-action: none;
|
|
312
|
+
-webkit-tap-highlight-color: transparent;
|
|
313
|
+
}
|
|
314
|
+
button::after { content: ""; position: absolute; inset: -4px 0; }
|
|
315
|
+
button::before {
|
|
316
|
+
content: ""; position: absolute; inset: 2px 6px; border-radius: 999px; pointer-events: none;
|
|
317
|
+
}
|
|
318
|
+
button:focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }
|
|
319
|
+
button[data-state="loading"] { opacity: 0.5; }
|
|
320
|
+
button[data-state="listening"], button[data-state="capturing"] { color: var(--rec); }
|
|
321
|
+
button[data-state="listening"]::before { box-shadow: 0 0 0 2px color-mix(in oklch, var(--rec) 35%, transparent); }
|
|
322
|
+
button[data-state="capturing"]::before { box-shadow: 0 0 0 2px var(--rec); animation: pulse 1.2s ease-in-out infinite; }
|
|
323
|
+
button[data-status="speaking"] { color: var(--talk); }
|
|
324
|
+
button[data-status="speaking"]::before { box-shadow: 0 0 0 2px var(--talk); animation: pulse 2.4s ease-in-out infinite; }
|
|
325
|
+
button[data-resume]::before { border: 2px dashed var(--rec); }
|
|
326
|
+
svg { width: 1em; height: 1em; fill: currentColor; }
|
|
327
|
+
.rec { font-size: 8px; font-weight: 700; color: var(--rec); }
|
|
328
|
+
.rec[hidden] { display: none; }
|
|
329
|
+
.note {
|
|
330
|
+
position: absolute; inset-inline-end: 0; bottom: 100%; margin-bottom: 8px;
|
|
331
|
+
white-space: nowrap; font-size: 10px; pointer-events: none; color: oklch(0.6 0.17 45);
|
|
332
|
+
}
|
|
333
|
+
.note:empty { display: none; }
|
|
334
|
+
@keyframes pulse { 50% { opacity: 0.35; } }
|
|
335
|
+
@media (prefers-reduced-motion: reduce) { button::before { animation: none !important; } }
|
|
336
|
+
`,Oi=typeof HTMLElement>"u"?class{}:HTMLElement,wr="http://www.w3.org/2000/svg";class Oe extends Oi{static observedAttributes=["stt-url","lang","vad-src","ort-src","aec"];stt;sttHeaders;sttCredentials;vad;strings={};_box=null;_voice;_session;shadow;btn;path;recEl;noteEl;off=[];last={};lastResume;get sttUrl(){return this.getAttribute("stt-url")??""}set sttUrl(e){if(e)this.setAttribute("stt-url",e);else this.removeAttribute("stt-url")}get lang(){return this.getAttribute("lang")??""}set lang(e){if(e)this.setAttribute("lang",e);else this.removeAttribute("lang")}get storageKey(){return this.getAttribute("storage-key")||lt}set storageKey(e){this.setAttribute("storage-key",e)}get aec(){let e=this.getAttribute("aec");if(e===null)try{return globalThis.localStorage?.getItem("liagent:voice-aec")!=="0"}catch{return!0}return e!=="off"&&e!=="false"&&e!=="0"}set aec(e){this.setAttribute("aec",e?"on":"off")}get tick(){return this.hasAttribute("tick")}set tick(e){this.toggleAttribute("tick",e)}get box(){if(this._box)return this._box;let e=this.closest?.("liagent-chat");if(br(e))return e;let t=this.getRootNode?.()?.host;return br(t)?t:null}set box(e){this._box=e,this.syncActive(!0)}get voice(){return this._session?.voice()??this._voice??null}set voice(e){this._voice=e,this._session?.setVoice(e)}get session(){return this._session}get t(){return{...Er,...this.strings}}config(){let e=this.sttUrl,t=this.getAttribute("vad-src"),n=this.getAttribute("ort-src");return{stt:this.stt??(e?(r)=>at(r,{url:e,lang:this.lang||void 0,headers:this.sttHeaders,credentials:this.sttCredentials}):void 0),vad:this.vad??(t&&n?dt(t,n):void 0),aec:this.aec,onUtterance:(r)=>this.fire("mic-utterance",r)}}attributeChangedCallback(){this._session?.configure(this.config())}connectedCallback(){if(!fr()){this.hidden=!0;return}this.build();let e=this._session=ct(Ii(this.storageKey));if(e.configure(this.config()),this._voice!==void 0)e.setVoice(this._voice);this.off.push(e.subscribe((r)=>this.render(r)),e.attach({onText:(r)=>this.onText(r),onPending:(r,s)=>this.box?.setPartial(r>0&&s?s:null)}));let t=(r)=>{if(r.key==="Escape"&&e.view().state!=="off")e.off()};document.addEventListener("keydown",t),this.off.push(()=>document.removeEventListener("keydown",t));let n=this.box;if(n&&typeof n.addEventListener==="function"){let r=()=>{if(e.view().state!=="off")e.voice()?.resume?.()};n.addEventListener("focusout",r),this.off.push(()=>n.removeEventListener("focusout",r))}}disconnectedCallback(){for(let e of this.off.splice(0))e()}toggle(){let e=this._session;if(!e)return;if(e.view().state==="off")Ie()?.resume().catch(()=>{}),e.voice()?.unlock?.();e.toggle()}fire(e,t,n=!1){return this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0,cancelable:n}))}onText(e){if(!this.fire("mic-text",{text:e},!0))return;let t=this.box;if(!t||!Sr(t,e))return;this.fire("mic-sent",{text:e}),this._session?.voice()?.resume?.(),this.playTick()}playTick(){let e=ge();if(!this.tick||!e||e.state==="closed"||this._session?.view().speaking)return;e.resume().then(()=>lr(e),()=>{})}syncActive(e=!1){let t=(this._session?.view().state??"off")!=="off";if(!e&&t===this.last.active)return;this.last.active=t;let n=this.box;if(n)n.micActive=t}build(){if(this.shadow)return;let e=this.shadow=this.attachShadow({mode:"open"});try{let o=new CSSStyleSheet;o.replaceSync(kr),e.adoptedStyleSheets=[o]}catch{let o=document.createElement("style");o.textContent=kr,e.append(o)}let t=this.noteEl=document.createElement("span");t.className="note",t.setAttribute("role","alert"),t.setAttribute("part","note");let n=this.btn=document.createElement("button");n.type="button",n.setAttribute("part","button");let r=document.createElementNS(wr,"svg");r.setAttribute("viewBox","0 0 256 256"),r.setAttribute("aria-hidden","true");let s=this.path=document.createElementNS(wr,"path");r.append(s);let i=this.recEl=document.createElement("span");i.className="rec",i.setAttribute("aria-hidden","true"),n.append(r,i),n.addEventListener("pointerdown",(o)=>o.preventDefault()),n.addEventListener("click",()=>{let o=this._session;if(!o)return;let a=o.view();if(it(a.state,a.pending,a.speaking)==="speaking"&&o.voice()?.interrupt)return o.voice()?.interrupt?.("tap");this.toggle()}),e.append(t,n)}render(e){let t=this.btn;if(!t||!this.path||!this.recEl||!this.noteEl)return;let n=this.t,r=it(e.state,e.pending,e.speaking);t.dataset.state=e.state,t.dataset.status=r,t.toggleAttribute("data-resume",e.resume&&e.state==="off"),t.setAttribute("aria-pressed",String(e.state!=="off")),t.setAttribute("aria-label",xr(e,r,n)),t.title=xr(e,r,n),this.path.setAttribute("d",e.state==="off"?vr.regular:vr.fill),this.recEl.textContent=n.rec,this.recEl.hidden=e.state!=="capturing";let s=e.error?e.error instanceof pt?n.noStt:nr(e.error,n):"";if(this.noteEl.textContent=s,e.error&&e.error!==this.last.error)this.fire("mic-error",{error:e.error,note:s});if(this.last.error=e.error,e.state!==this.last.state||r!==this.last.status)this.last.state=e.state,this.last.status=r,this.fire("mic-state",{state:e.state,status:r});if(e.resumed&&e.resumed!==this.lastResume)this.lastResume=e.resumed,this.fire("mic-resume",e.resumed);this.syncActive()}}function $i(e="liagent-mic"){if(typeof customElements<"u"&&!customElements.get(e))customElements.define(e,Oe);return Oe}var Mr=1e4;var Fi=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function Tr(e){return e.normalize("NFKC").toLowerCase().replace(/[\p{P}\p{S}\s]/gu,"")}function Ar(e,t){let n=new Map,r=[...e];if(r.length&&r.length<t)n.set(e,1);for(let s=0;s+t<=r.length;s++){let i=r.slice(s,s+t).join("");n.set(i,(n.get(i)??0)+1)}return n}function Di(e,t){let n=0,r=0,s=0;for(let i of e.values())n+=i;for(let i of t.values())r+=i;for(let[i,o]of e)s+=Math.min(o,t.get(i)??0);return n+r?2*s/(n+r):0}function _r(e,t){let n=Tr(e),r={score:0,against:null,drop:!1};if(!n||!t.length)return r;let s=Fi.test(n)?2:3,i=[...n].length<4,o=[...t];for(let c=0;c+1<t.length;c++)o.push(`${t[c]} ${t[c+1]}`);let a=Ar(n,s),l=r;for(let c of o){let u=Tr(c);if(!u)continue;let p;if(u===n||!i&&u.includes(n))p=1;else if(i)p=0;else p=Di(a,Ar(u,s));if(p>l.score)l={score:p,against:c,drop:!1}}return{...l,score:Math.round(l.score*1000)/1000,drop:l.score>=0.6}}var Vi="liagent:voice-out",Hi="liagent:voice-aec",Ui=0.3,$e=()=>{},Bi=64,Lr=(e)=>{try{return globalThis.localStorage?.getItem(e)??null}catch{return null}},ht=()=>Lr(Vi)==="cloud"?"cloud":"speech",Pr=()=>Lr(Hi)!=="0";function Wi(e){if(typeof e==="function")return e;return(t,n)=>`${e}${e.includes("?")?"&":"?"}lang=${encodeURIComponent(n.split(/[-_]/)[0]??n)}&text=${encodeURIComponent(t)}`}function Cr(e,t,n={}){let r=n.langs?new Set(n.langs):null;if(r&&!r.has(t.toLowerCase().split(/[-_]/)[0]??""))return"lang";if(!e.trim())return"empty";if(n.maxText!==void 0&&e.length>n.maxText)return"long";return null}function Ki(e){let t=e.toUrl??((g)=>URL.createObjectURL(g)),n=e.revoke??((g)=>URL.revokeObjectURL(g)),r=()=>({langs:e.langs,maxText:e.maxText}),s=new Map,i=null,o=null,a=!1,l=0,c=()=>{if(!i)i=e.element(),i.preload="auto";if(!a){let g=e.ctx();if(g){a=!0;try{let f=g.createGain();g.createMediaElementSource(i).connect(f),f.connect(g.destination),o=f}catch{o=null}}}return i},u=(g,f)=>{let m=`${f}
|
|
337
|
+
${g}`,y=s.get(m);if(y)return y;let b=e.url(),S=b?e.fetch(b(g,f)).then(async(x)=>{let h=x.headers.get("X-Voice");if(!x.ok)throw Error(`http ${x.status}${h?` ${h}`:""}`);return t(await x.blob())}):Promise.reject(Error("no tts url"));if(s.set(m,S),S.catch(()=>s.delete(m)),s.size>Bi){let x=s.entries().next().value;if(x)s.delete(x[0]),x[1].then(n,$e)}return S},p=(g,f)=>{let m=e.ctx();if(o&&m){let y=m.currentTime;o.gain.cancelScheduledValues(y),o.gain.setValueAtTime(o.gain.value,y),o.gain.linearRampToValueAtTime(g,y+f/1000)}else if(i)i.volume=g},d=(g)=>{let f=e.ctx();if(o&&f)o.gain.cancelScheduledValues(f.currentTime),o.gain.setValueAtTime(g,f.currentTime);else if(i)i.volume=g};return{unlock(){let g=c();if(!g.paused)return;g.src=zi(),g.play().then(()=>g.pause(),$e)},gain:()=>o,prepare(g,f){if(!Cr(g,f,r()))u(g,f).catch($e)},play(g,f){let m=++l,y=()=>m===l,b=(h)=>void Promise.resolve().then(()=>y()&&f.onfail?.(h)),S={route:"audio",stop(){if(!y())return{};l++;let h=i;if(!h)return{at:g.at};return h.pause(),{at:Math.max(0,h.currentTime-Ui)}},volume:(h,k)=>y()&&p(h,k)},x=Cr(g.text,g.lang,r());if(x)return b(x),S;return u(g.text,g.lang).then((h)=>{if(!y())return;let k=c();e.ctx()?.resume?.().catch($e),d(g.volume),k.onended=()=>y()&&f.onend(),k.onerror=()=>y()&&f.onerror(),k.onloadedmetadata=()=>{if(!y())return;k.onloadedmetadata=null,k.currentTime=g.at;let w=g.rate??1;k.defaultPlaybackRate=w,k.playbackRate=w,k.preservesPitch=!0,k.webkitPreservesPitch=!0,k.play().catch((T)=>{if(y())f.onfail?.(`play ${T?.name??"error"}`)})},k.src=h,k.load()},(h)=>y()&&f.onfail?.(String(h?.message??h))),S}}}var gt="",zi=()=>{if(gt)return gt;let e="";for(let t of Re(new Float32Array(80),8000))e+=String.fromCharCode(t);return gt=`data:audio/wav;base64,${btoa(e)}`},ft="__liagentCloudOut";function fe(e,t){let n=globalThis,r=n[ft];if(!r){if(typeof Audio>"u"||typeof fetch>"u")return null;let s={url:null,lim:t??{},out:null};s.out=Ki({url:()=>s.url,fetch:(i)=>fetch(i,{credentials:"same-origin"}),element:()=>new Audio,ctx:()=>ge(),get langs(){return s.lim.langs},get maxText(){return s.lim.maxText}}),r=n[ft]=s}if(e!==void 0)r.url=e?Wi(e):null;if(t)r.lim=t;return r.out}var mt=()=>!!globalThis[ft]?.url;var Gi=400,Nr=1500,Yi=0.25,ji=80,Xi=200,qi=1500,Zi=0.7,Ji=200,Qi="liagent:speak",Rr="__liagentVoice",$r=1,eo=200,Ir="。.!?",Or=".!?",to=`」』)】〕〉》"'”’)]`;function no(e){let t=[],n="",r=()=>{let s=n.trim();if(s)t.push(s);n=""};for(let s=0;s<e.length;s++){let i=e[s]??"";if(i===`
|
|
338
|
+
`||i==="\r"){r();continue}n+=i;let o=Ir.includes(i);if(!o&&!Or.includes(i))continue;while(s+1<e.length&&(Ir+Or+to).includes(e[s+1]??`
|
|
339
|
+
`))n+=e[++s];if(o||s+1>=e.length||/\s/.test(e[s+1]??""))r()}return r(),t}var ro=/[、,,;;::]/;function so(e,t=Ji){let n=[],r=e.trim();while(r.length>t){let s=r.slice(0,t),i=-1;for(let o=s.length-1;o>t/3;o--)if(ro.test(s[o]??"")){i=o+1;break}if(i<0){let o=s.lastIndexOf(" ");i=o>t/3?o+1:t}n.push(r.slice(0,i).trim()),r=r.slice(i).trim()}if(r)n.push(r);return n}function io(e,t=Zi){if(!e.length)return!0;return e.reduce((n,r)=>n+r,0)/e.length>=t}function bt(e){let t=(e.voiceURI??"").toLowerCase();if(t.includes("eloquence")||t.includes("speech.synthesis.voice."))return 0;if(t.includes("premium"))return 4;if(t.includes("enhanced"))return 3;if(t.includes("siri"))return 3;return 2}function Fr(e,t){let n=(u)=>u.replace(/_/g,"-").toLowerCase(),r=n(t),s=r.split("-")[0],i=e.filter((u)=>n(u.lang)===r),o=e.filter((u)=>n(u.lang).split("-")[0]===s),a=i.length?i:o,l=Math.max(-1,...a.map(bt)),c=a.filter((u)=>bt(u)===l);return c.find((u)=>u.default)??c[0]}var oo=["speech","tap","typing"];function Dr(e){let t=e.setTimer??((v,M)=>setTimeout(v,M)),n=e.clearTimer??((v)=>clearTimeout(v)),r=e.now??(()=>Date.now()),s=()=>e.cloud?.()??null,i=()=>e.mode?.()==="cloud"&&s()?"cloud":"speech",o=()=>e.aec?.()??!0,a=e.log??(()=>{}),l=!1,c=!1,u=[],p=new Set,d=null,g,f,m=0,y=1,b=null,S=[],x=[],h=new Set,k=()=>({mic:l,speaking:c,hold:c&&!o(),ducked:!!b,queued:u.length,paused:p.size>0}),w=()=>{let v=k();for(let M of h)M(v)},T=()=>e.enabled()&&(e.here?.()??!0),C=()=>!!e.synth()||i()==="cloud",U=()=>{if(d&&d.said.end===void 0)d.said.end=r()},W=(v,M,L)=>{let F=e.synth();if(!F)return null;let V=v.from,O=e.utter(v.text.slice(V),v.lang);if(y!==1)O.volume=y;return O.rate=e.rate?.()??1,O.onboundary=(I)=>{if(L!==m||!d)return;if(I.name&&I.name!=="word")return;d.mark=V+Math.max(0,I.charIndex|0)},O.onend=()=>M.onend(),O.onerror=()=>M.onerror(),F.speak(O),{route:"speech",stop:()=>(F.cancel(),{}),volume:()=>{}}},Q=()=>{if(d||p.size||!C())return;let v=u[0];if(!v)return;let M=m,L=()=>{if(M!==m)return;if(U(),d=null,u.shift(),Q(),!d)n(g),g=t(()=>{if(M!==m||d)return;c=!1,w()},Gi);w()},F={lang:v.lang,chars:v.text.length},V={onend:L,onerror:L,onfail:(Vr)=>{if(M!==m||!d)return;a({ev:"voice-out",out:"cloud",route:"speech",fallback:Vr,...F});let xt=W(v,V,M);if(!xt)return L();d.p=xt}},O={text:v.text,start:r()},I=i()==="cloud"?s():null;d={p:null,mark:v.from,said:O};let Fe=I?I.play({text:v.text,lang:v.lang,at:v.at,volume:y,rate:e.rate?.()??1},V):W(v,V,M);if(!Fe){d=null;return}if(d.p=Fe,S.push(O),S.length>50)S.shift();a({ev:"voice-out",out:I?"cloud":"speech",route:Fe.route,...F,volume:y,at:v.at||void 0,from:v.from||void 0});let De=u[1];if(I&&De)I.prepare?.(De.text,De.lang);n(g),c=!0},j=(v)=>{if(m++,n(g),d){U();let M=d.p.stop(),L=u[0];if(v&&L)if(d.p.route==="audio")L.at=M.at??L.at;else L.from=d.mark,L.at=0;d=null}c=!1},he=(v,M)=>{y=v,d?.p.volume(v,M)},E=(v)=>{if(!b)return;n(b.timer),b=null,he(1,v)},_=()=>{let v=b;if(!v)return;n(v.timer),v.timer=t(()=>{if(b!==v)return;let M=v.probs;v.probs=[];let L=M.length?M.reduce((F,V)=>F+V,0)/M.length:void 0;if(!io(M))return a({ev:"voice-duck-hold",prob:L}),_();a({ev:"voice-barge-in",prob:L}),B.interrupt("speech")},qi)},N=()=>{if(n(f),!p.size)return;p.clear(),Q(),w()},R=()=>{j(!1),E(0),n(f),u.length=0,p.clear(),w()},B={v:$r,state:k,subscribe(v){return h.add(v),()=>void h.delete(v)},setLog(v){a=v},log:(v)=>a(v),mode:i,aec:o,shouldSpeak:()=>l||T(),readAloud:()=>l||e.enabled(),setMic(v){if(l===v)return;if(l=v,!v&&!T())return R();w()},reply(v){if(!C()||!B.shouldSpeak())return!1;let M=me(v),L=no(v).flatMap((O)=>so(O)).map((O)=>({text:O,lang:M,from:0,at:0})),F=L[0];if(!F)return!1;let V=i()==="cloud"?s():null;if(V&&!u.length)V.prepare?.(F.text,M);return u.push(...L),Q(),w(),!0},speak(v,M){if(M){if(x.includes(M))return;if(x.push(M),x.length>eo)x.shift()}B.reply(v)},stop(v){if(v&&oo.includes(v))return B.interrupt(v);R()},unlock(){e.unlock?.()},userSpeech(){if(d&&o()){if(!b)b={timer:void 0,probs:[]},he(Yi,ji),a({ev:"voice-duck",route:d.p.route}),w();_();return}B.interrupt("speech")},userFrame(v){b?.probs.push(v)},interrupt(v){if(!u.length&&!d){if(E(0),c)j(!1),w();return}if(j(!0),E(0),p.add(v),n(f),v==="tap")f=t(N,Nr);w()},userIdle(){if(b){E(Xi),w();return}if(!p.has("speech")&&!p.has("tap"))return;n(f),f=t(N,Nr)},resume:N,echoCheck(v,M=0){let L=r(),F=L-M,V=S.filter((I)=>(I.end??L)>=F-Mr).map((I)=>I.text),O=S.some((I)=>I.start<=L&&(I.end??L)>=F);return{..._r(v,V),during:O}},echoDropped(){if(p.size===1&&p.has("speech"))N()}};return B}var ao=()=>typeof speechSynthesis>"u"?null:speechSynthesis,lo=(e=Qi)=>{try{return globalThis.localStorage?.getItem(e)!=="0"}catch{return!0}};function co(){return typeof document<"u"&&document.visibilityState==="visible"}var yt=new Set;function uo(e){let t=globalThis,n=t[Rr];if(n&&n.v===$r&&n.configure){if(e)n.configure(e);return n}let r={...e};if(r.tts!==void 0)fe(r.tts,r.ttsLimits);let s=Dr({synth:ao,enabled:()=>(r.enabled??lo)(),here:()=>(r.here??co)(),cloud:()=>mt()?fe():null,mode:()=>(r.mode??ht)(),aec:()=>(r.aec??Pr)(),rate:()=>(r.rate??_e)(),unlock:()=>{if((r.mode??ht)()==="cloud"&&mt())fe()?.unlock()},log:r.log,utter:(o,a)=>{let l=new SpeechSynthesisUtterance(o);l.lang=a;let c=Fr(speechSynthesis.getVoices(),a);if(c)l.voice=c;return yt.add(l),l.addEventListener("end",()=>yt.delete(l)),l.addEventListener("error",()=>yt.delete(l)),l}}),i=Object.assign(s,{configure(o){if(r={...r,...o},o.tts!==void 0||o.ttsLimits)fe(r.tts??null,r.ttsLimits);if(o.log)s.setLog(o.log)}});return t[Rr]=i,i}export{mo as APPROVAL_MS,wt as BUSY_AFTER_REPLY_MS,kt as BUSY_MS,xo as CHAT_HISTORY,bo as CHAT_MS,Le as ChatBox,ne as DEBOUNCE_MS,yo as EVAL_GRANT_MS,Hr as MAX_AGENT_ID,He as MAX_CHAT,po as MAX_CODE,wo as MAX_EDITS,fo as MAX_LABEL,vt as MAX_NODE_PATH,go as MAX_RESULT,Oe as MicElement,No as OWNER_NAME,vo as PAGES_GONE_MS,St as PAGE_DEBOUNCE_MS,ho as PENDING_MS,P as ROOT_NODE,xe as StateTreeElement,Br as agentIdOf,Et as applyEdit,ns as assigneeOf,Ve as chatText,To as cleanLabel,Wr as commonAncestor,Lt as compile,Pt as completeNode,hi as connectHub,q as countOpen,Dr as createVoice,ie as crumbs,ci as defineChatBox,$i as defineMic,Ls as defineStateTree,Sr as dictate,Tt as dictatedDraft,At as draftSource,Ge as filterNeedsOwner,re as findLinks,se as frontier,Cs as frontierLines,ko as isPageId,ee as isWithin,Ue as lineNode,nn as liveTreeSource,tn as loadTree,os as localeChain,Mo as matchesTarget,Co as mayAddress,ct as micSession,zr as nodeHue,K as nodePath,Xe as overlayProgress,X as parseAddress,So as parseControllerMessage,Eo as parsePageMessage,Ro as parseTree,ze as parseTreeDoc,z as pathLabel,me as pickLang,Fr as pickNaturalVoice,_t as pickVoice,at as postStt,ye as progressFeed,_o as routeTo,Ao as shortCode,Ct as summarize,te as trimHistory,dt as vadFromScripts,uo as voice,bt as voiceQuality,oe as watchTree};
|