@cjhyy/code-shell-web 0.9.17 → 0.9.19

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.
@@ -19,6 +19,8 @@ export interface PendingApproval {
19
19
  options?: string[];
20
20
  /** When true, the user must pick an option (no free text). */
21
21
  optionsOnly?: boolean;
22
+ /** A nonblocking question remains answerable after the run ends. */
23
+ asynchronous?: boolean;
22
24
  /** True for path-scoped tools (Read/Edit/Write/…) → show file/dir scope. */
23
25
  pathScoped: boolean;
24
26
  }
@@ -72,6 +72,7 @@ export function useRemoteApp(options = {}) {
72
72
  const [approvals, setApprovals] = useState([]);
73
73
  const approvalsRef = useRef(approvals);
74
74
  approvalsRef.current = approvals;
75
+ const submittingAsyncApprovalsRef = useRef(new Set());
75
76
  // The SELECTED project (one-true-source for "what am I looking at"), distinct
76
77
  // from activeSessionCwd which is derived from the bound session. Drives session
77
78
  // list filtering AND ccRoom.listSessions.
@@ -219,6 +220,7 @@ export function useRemoteApp(options = {}) {
219
220
  setLoading((prev) => (prev[key] === value ? prev : { ...prev, [key]: value }));
220
221
  }, []);
221
222
  const clearApproval = useCallback((requestId) => {
223
+ submittingAsyncApprovalsRef.current.delete(requestId);
222
224
  approvalsRef.current = removeResolvedApproval(approvalsRef.current, requestId);
223
225
  setApprovals((prev) => removeResolvedApproval(prev, requestId));
224
226
  }, []);
@@ -240,8 +242,10 @@ export function useRemoteApp(options = {}) {
240
242
  const type = event?.type;
241
243
  return type === "turn_complete" || type === "error";
242
244
  })) {
243
- approvalsRef.current = [];
244
- setApprovals([]);
245
+ // Asynchronous questions outlive the current run. Only a resolution
246
+ // notification (or a new worker epoch) makes their answer stale.
247
+ approvalsRef.current = approvalsRef.current.filter((approval) => approval.asynchronous);
248
+ setApprovals((prev) => prev.filter((approval) => approval.asynchronous));
245
249
  }
246
250
  }, []);
247
251
  const appendSessionEvents = useCallback((sessionId, events) => {
@@ -558,6 +562,9 @@ export function useRemoteApp(options = {}) {
558
562
  setNotice(event.message || t("mobile.notice.roomError"));
559
563
  break;
560
564
  case "error":
565
+ if (event.approvalId) {
566
+ submittingAsyncApprovalsRef.current.delete(event.approvalId);
567
+ }
561
568
  if (event.clientMessageId) {
562
569
  settleMessageAck(event.clientMessageId, new Error(event.message));
563
570
  }
@@ -773,6 +780,7 @@ export function useRemoteApp(options = {}) {
773
780
  risk,
774
781
  options: askOptions?.options,
775
782
  optionsOnly: askOptions?.optionsOnly,
783
+ asynchronous: rq.toolName === "__ask_user__" && rq.args?.asynchronous === true,
776
784
  pathScoped: PATH_SCOPED.has(rq.toolName ?? ""),
777
785
  });
778
786
  }
@@ -811,18 +819,9 @@ export function useRemoteApp(options = {}) {
811
819
  return;
812
820
  }
813
821
  dispatchChat({ kind: "raw", raw });
814
- // A turn ending (or erroring) resolves any pending approval for this
815
- // session — clear stale cards so a request the user already handled (or
816
- // that the desktop answered) doesn't linger ("点了还存在").
817
- const ev = params.event?.type;
818
- if (ev === "turn_complete" || ev === "error") {
819
- // We only ever hold bound-session approvals, so the turn ending clears
820
- // them all (the request can no longer be answered).
821
- approvalsRef.current = [];
822
- setApprovals([]);
823
- }
822
+ clearApprovalsIfTerminal([params.event]);
824
823
  }
825
- }, [addApproval, clearApproval, sessionCwdById]);
824
+ }, [addApproval, clearApproval, clearApprovalsIfTerminal, sessionCwdById]);
826
825
  const requestActiveResync = useCallback(() => {
827
826
  const roomId = activeRoomIdRef.current;
828
827
  if (roomId) {
@@ -877,6 +876,7 @@ export function useRemoteApp(options = {}) {
877
876
  useEffect(() => {
878
877
  if (socket.status === "online")
879
878
  return;
879
+ submittingAsyncApprovalsRef.current.clear();
880
880
  const error = new Error("Remote connection was lost");
881
881
  for (const waiter of uploadWaitersRef.current.values()) {
882
882
  clearTimeout(waiter.timer);
@@ -1115,7 +1115,9 @@ export function useRemoteApp(options = {}) {
1115
1115
  // card unmounts). Sending again would violate the approve-once invariant.
1116
1116
  if (!a)
1117
1117
  return;
1118
- socket.send({
1118
+ if (a.asynchronous && submittingAsyncApprovalsRef.current.has(requestId))
1119
+ return;
1120
+ const sent = socket.send({
1119
1121
  type: "approval.respond",
1120
1122
  approvalId: requestId,
1121
1123
  decision,
@@ -1125,6 +1127,14 @@ export function useRemoteApp(options = {}) {
1125
1127
  scope: opts?.scope,
1126
1128
  pathScope: opts?.pathScope,
1127
1129
  });
1130
+ if (!sent)
1131
+ return;
1132
+ if (a.asynchronous) {
1133
+ // Keep the card until the worker accepts this late answer. A rejected
1134
+ // delivery unlocks it for retry without losing the user's question.
1135
+ submittingAsyncApprovalsRef.current.add(requestId);
1136
+ return;
1137
+ }
1128
1138
  // Update the ref synchronously too so a second tap in the same tick (before
1129
1139
  // the async setApprovals commits) sees it gone and no-ops above.
1130
1140
  approvalsRef.current = approvalsRef.current.filter((p) => p.requestId !== requestId);
@@ -53,6 +53,7 @@ function runStateForReason(reason) {
53
53
  case "prompt_too_long":
54
54
  case "model_error":
55
55
  case "image_error":
56
+ case "replay_incomplete":
56
57
  return "error";
57
58
  // "completed", "max_turns", "goal_budget_exhausted", "stop_hook_prevented",
58
59
  // "hook_stopped", and any future/unknown terminal reason: a normal stop.
@@ -45,6 +45,6 @@ description: 描述这个 Skill 适合处理什么任务
45
45
  `))+1))}const o="#".repeat(f),m=r.enter("headingAtx"),g=r.enter("phrasing");d.move(o+" ");let p=r.containerPhrasing(n,{before:"# ",after:`
46
46
  `,...d.current()});return/^[\t ]/.test(p)&&(p=ta(p.charCodeAt(0))+p.slice(1)),p=p?o+" "+p:o,r.options.closeAtx&&(p+=" "+o),g(),m(),p}Ay.peek=Mw;function Ay(n){return n.value||""}function Mw(){return"<"}zy.peek=Lw;function zy(n,i,r,s){const f=yf(r),d=f==='"'?"Quote":"Apostrophe",o=r.enter("image");let m=r.enter("label");const g=r.createTracker(s);let p=g.move("![");return p+=g.move(r.safe(n.alt,{before:p,after:"]",...g.current()})),p+=g.move("]("),m(),!n.url&&n.title||/[\0- \u007F]/.test(n.url)?(m=r.enter("destinationLiteral"),p+=g.move("<"),p+=g.move(r.safe(n.url,{before:p,after:">",...g.current()})),p+=g.move(">")):(m=r.enter("destinationRaw"),p+=g.move(r.safe(n.url,{before:p,after:n.title?" ":")",...g.current()}))),m(),n.title&&(m=r.enter(`title${d}`),p+=g.move(" "+f),p+=g.move(r.safe(n.title,{before:p,after:f,...g.current()})),p+=g.move(f),m()),p+=g.move(")"),o(),p}function Lw(){return"!"}Ry.peek=Uw;function Ry(n,i,r,s){const f=n.referenceType,d=r.enter("imageReference");let o=r.enter("label");const m=r.createTracker(s);let g=m.move("![");const p=r.safe(n.alt,{before:g,after:"]",...m.current()});g+=m.move(p+"]["),o();const b=r.stack;r.stack=[],o=r.enter("reference");const y=r.safe(r.associationId(n),{before:g,after:"]",...m.current()});return o(),r.stack=b,d(),f==="full"||!p||p!==y?g+=m.move(y+"]"):f==="shortcut"?g=g.slice(0,-1):g+=m.move("]"),g}function Uw(){return"!"}_y.peek=Bw;function _y(n,i,r){let s=n.value||"",f="`",d=-1;for(;new RegExp("(^|[^`])"+f+"([^`]|$)").test(s);)f+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++d<r.unsafe.length;){const o=r.unsafe[d],m=r.compilePattern(o);let g;if(o.atBreak)for(;g=m.exec(s);){let p=g.index;s.charCodeAt(p)===10&&s.charCodeAt(p-1)===13&&p--,s=s.slice(0,p)+" "+s.slice(g.index+1)}}return f+s+f}function Bw(){return"`"}function Dy(n,i){const r=uf(n);return!!(!i.options.resourceLink&&n.url&&!n.title&&n.children&&n.children.length===1&&n.children[0].type==="text"&&(r===n.url||"mailto:"+r===n.url)&&/^[a-z][a-z+.-]+:/i.test(n.url)&&!/[\0- <>\u007F]/.test(n.url))}Oy.peek=qw;function Oy(n,i,r,s){const f=yf(r),d=f==='"'?"Quote":"Apostrophe",o=r.createTracker(s);let m,g;if(Dy(n,r)){const b=r.stack;r.stack=[],m=r.enter("autolink");let y=o.move("<");return y+=o.move(r.containerPhrasing(n,{before:y,after:">",...o.current()})),y+=o.move(">"),m(),r.stack=b,y}m=r.enter("link"),g=r.enter("label");let p=o.move("[");return p+=o.move(r.containerPhrasing(n,{before:p,after:"](",...o.current()})),p+=o.move("]("),g(),!n.url&&n.title||/[\0- \u007F]/.test(n.url)?(g=r.enter("destinationLiteral"),p+=o.move("<"),p+=o.move(r.safe(n.url,{before:p,after:">",...o.current()})),p+=o.move(">")):(g=r.enter("destinationRaw"),p+=o.move(r.safe(n.url,{before:p,after:n.title?" ":")",...o.current()}))),g(),n.title&&(g=r.enter(`title${d}`),p+=o.move(" "+f),p+=o.move(r.safe(n.title,{before:p,after:f,...o.current()})),p+=o.move(f),g()),p+=o.move(")"),m(),p}function qw(n,i,r){return Dy(n,r)?"<":"["}My.peek=Hw;function My(n,i,r,s){const f=n.referenceType,d=r.enter("linkReference");let o=r.enter("label");const m=r.createTracker(s);let g=m.move("[");const p=r.containerPhrasing(n,{before:g,after:"]",...m.current()});g+=m.move(p+"]["),o();const b=r.stack;r.stack=[],o=r.enter("reference");const y=r.safe(r.associationId(n),{before:g,after:"]",...m.current()});return o(),r.stack=b,d(),f==="full"||!p||p!==y?g+=m.move(y+"]"):f==="shortcut"?g=g.slice(0,-1):g+=m.move("]"),g}function Hw(){return"["}function bf(n){const i=n.options.bullet||"*";if(i!=="*"&&i!=="+"&&i!=="-")throw new Error("Cannot serialize items with `"+i+"` for `options.bullet`, expected `*`, `+`, or `-`");return i}function Iw(n){const i=bf(n),r=n.options.bulletOther;if(!r)return i==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===i)throw new Error("Expected `bullet` (`"+i+"`) and `bulletOther` (`"+r+"`) to be different");return r}function Yw(n){const i=n.options.bulletOrdered||".";if(i!=="."&&i!==")")throw new Error("Cannot serialize items with `"+i+"` for `options.bulletOrdered`, expected `.` or `)`");return i}function Ly(n){const i=n.options.rule||"*";if(i!=="*"&&i!=="-"&&i!=="_")throw new Error("Cannot serialize rules with `"+i+"` for `options.rule`, expected `*`, `-`, or `_`");return i}function Gw(n,i,r,s){const f=r.enter("list"),d=r.bulletCurrent;let o=n.ordered?Yw(r):bf(r);const m=n.ordered?o==="."?")":".":Iw(r);let g=i&&r.bulletLastUsed?o===r.bulletLastUsed:!1;if(!n.ordered){const b=n.children?n.children[0]:void 0;if((o==="*"||o==="-")&&b&&(!b.children||!b.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(g=!0),Ly(r)===o&&b){let y=-1;for(;++y<n.children.length;){const v=n.children[y];if(v&&v.type==="listItem"&&v.children&&v.children[0]&&v.children[0].type==="thematicBreak"){g=!0;break}}}}g&&(o=m),r.bulletCurrent=o;const p=r.containerFlow(n,s);return r.bulletLastUsed=o,r.bulletCurrent=d,f(),p}function Vw(n){const i=n.options.listItemIndent||"one";if(i!=="tab"&&i!=="one"&&i!=="mixed")throw new Error("Cannot serialize items with `"+i+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return i}function Qw(n,i,r,s){const f=Vw(r);let d=r.bulletCurrent||bf(r);i&&i.type==="list"&&i.ordered&&(d=(typeof i.start=="number"&&i.start>-1?i.start:1)+(r.options.incrementListMarker===!1?0:i.children.indexOf(n))+d);let o=d.length+1;(f==="tab"||f==="mixed"&&(i&&i.type==="list"&&i.spread||n.spread))&&(o=Math.ceil(o/4)*4);const m=r.createTracker(s);m.move(d+" ".repeat(o-d.length)),m.shift(o);const g=r.enter("listItem"),p=r.indentLines(r.containerFlow(n,m.current()),b);return g(),p;function b(y,v,S){return v?(S?"":" ".repeat(o))+y:(S?d:d+" ".repeat(o-d.length))+y}}function Xw(n,i,r,s){const f=r.enter("paragraph"),d=r.enter("phrasing"),o=r.containerPhrasing(n,s);return d(),f(),o}const Zw=Ys(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Kw(n,i,r,s){return(n.children.some(function(o){return Zw(o)})?r.containerPhrasing:r.containerFlow).call(r,n,s)}function Fw(n){const i=n.options.strong||"*";if(i!=="*"&&i!=="_")throw new Error("Cannot serialize strong with `"+i+"` for `options.strong`, expected `*`, or `_`");return i}Uy.peek=$w;function Uy(n,i,r,s){const f=Fw(r),d=r.enter("strong"),o=r.createTracker(s),m=o.move(f+f);let g=o.move(r.containerPhrasing(n,{after:f,before:m,...o.current()}));const p=g.charCodeAt(0),b=Ds(s.before.charCodeAt(s.before.length-1),p,f);b.inside&&(g=ta(p)+g.slice(1));const y=g.charCodeAt(g.length-1),v=Ds(s.after.charCodeAt(0),y,f);v.inside&&(g=g.slice(0,-1)+ta(y));const S=o.move(f+f);return d(),r.attentionEncodeSurroundingInfo={after:v.outside,before:b.outside},m+g+S}function $w(n,i,r){return r.options.strong||"*"}function Jw(n,i,r,s){return r.safe(n.value,s)}function Pw(n){const i=n.options.ruleRepetition||3;if(i<3)throw new Error("Cannot serialize rules with repetition `"+i+"` for `options.ruleRepetition`, expected `3` or more");return i}function Ww(n,i,r){const s=(Ly(r)+(r.options.ruleSpaces?" ":"")).repeat(Pw(r));return r.options.ruleSpaces?s.slice(0,-1):s}const By={blockquote:jw,break:Sg,code:Tw,definition:zw,emphasis:Ty,hardBreak:Sg,heading:Ow,html:Ay,image:zy,imageReference:Ry,inlineCode:_y,link:Oy,linkReference:My,list:Gw,listItem:Qw,paragraph:Xw,root:Kw,strong:Uy,text:Jw,thematicBreak:Ww};function eC(){return{enter:{table:tC,tableData:jg,tableHeader:jg,tableRow:lC},exit:{codeText:iC,table:nC,tableData:zc,tableHeader:zc,tableRow:zc}}}function tC(n){const i=n._align;this.enter({type:"table",align:i.map(function(r){return r==="none"?null:r}),children:[]},n),this.data.inTable=!0}function nC(n){this.exit(n),this.data.inTable=void 0}function lC(n){this.enter({type:"tableRow",children:[]},n)}function zc(n){this.exit(n)}function jg(n){this.enter({type:"tableCell",children:[]},n)}function iC(n){let i=this.resume();this.data.inTable&&(i=i.replace(/\\([\\|])/g,rC));const r=this.stack[this.stack.length-1];r.type,r.value=i,this.exit(n)}function rC(n,i){return i==="|"?i:n}function aC(n){const i=n||{},r=i.tableCellPadding,s=i.tablePipeAlign,f=i.stringLength,d=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
47
47
  `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:v,table:o,tableCell:g,tableRow:m}};function o(S,N,D,z){return p(b(S,D,z),S.align)}function m(S,N,D,z){const _=y(S,D,z),M=p([_]);return M.slice(0,M.indexOf(`
48
- `))}function g(S,N,D,z){const _=D.enter("tableCell"),M=D.enter("phrasing"),H=D.containerPhrasing(S,{...z,before:d,after:d});return M(),_(),H}function p(S,N){return vw(S,{align:N,alignDelimiters:s,padding:r,stringLength:f})}function b(S,N,D){const z=S.children;let _=-1;const M=[],H=N.enter("table");for(;++_<z.length;)M[_]=y(z[_],N,D);return H(),M}function y(S,N,D){const z=S.children;let _=-1;const M=[],H=N.enter("tableRow");for(;++_<z.length;)M[_]=g(z[_],S,N,D);return H(),M}function v(S,N,D){let z=By.inlineCode(S,N,D);return D.stack.includes("tableCell")&&(z=z.replace(/\|/g,"\\$&")),z}}function sC(){return{exit:{taskListCheckValueChecked:kg,taskListCheckValueUnchecked:kg,paragraph:oC}}}function uC(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:cC}}}function kg(n){const i=this.stack[this.stack.length-2];i.type,i.checked=n.type==="taskListCheckValueChecked"}function oC(n){const i=this.stack[this.stack.length-2];if(i&&i.type==="listItem"&&typeof i.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const s=r.children[0];if(s&&s.type==="text"){const f=i.children;let d=-1,o;for(;++d<f.length;){const m=f[d];if(m.type==="paragraph"){o=m;break}}o===r&&(s.value=s.value.slice(1),s.value.length===0?r.children.shift():r.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,r.position.start=Object.assign({},s.position.start)))}}this.exit(n)}function cC(n,i,r,s){const f=n.children[0],d=typeof n.checked=="boolean"&&f&&f.type==="paragraph",o="["+(n.checked?"x":" ")+"] ",m=r.createTracker(s);d&&m.move(o);let g=By.listItem(n,i,r,{...s,...m.current()});return d&&(g=g.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,p)),g;function p(b){return b+o}}function fC(){return[Gk(),cw(),pw(),eC(),sC()]}function dC(n){return{extensions:[Vk(),fw(n),mw(),aC(n),uC()]}}const hC={tokenize:xC,partial:!0},qy={tokenize:vC,partial:!0},Hy={tokenize:SC,partial:!0},Iy={tokenize:jC,partial:!0},pC={tokenize:kC,partial:!0},Yy={name:"wwwAutolink",tokenize:yC,previous:Vy},Gy={name:"protocolAutolink",tokenize:bC,previous:Qy},ul={name:"emailAutolink",tokenize:gC,previous:Xy},Yn={};function mC(){return{text:Yn}}let ti=48;for(;ti<123;)Yn[ti]=ul,ti++,ti===58?ti=65:ti===91&&(ti=97);Yn[43]=ul;Yn[45]=ul;Yn[46]=ul;Yn[95]=ul;Yn[72]=[ul,Gy];Yn[104]=[ul,Gy];Yn[87]=[ul,Yy];Yn[119]=[ul,Yy];function gC(n,i,r){const s=this;let f,d;return o;function o(y){return!Vc(y)||!Xy.call(s,s.previous)||xf(s.events)?r(y):(n.enter("literalAutolink"),n.enter("literalAutolinkEmail"),m(y))}function m(y){return Vc(y)?(n.consume(y),m):y===64?(n.consume(y),g):r(y)}function g(y){return y===46?n.check(pC,b,p)(y):y===45||y===95||Jt(y)?(d=!0,n.consume(y),g):b(y)}function p(y){return n.consume(y),f=!0,g}function b(y){return d&&f&&en(s.previous)?(n.exit("literalAutolinkEmail"),n.exit("literalAutolink"),i(y)):r(y)}}function yC(n,i,r){const s=this;return f;function f(o){return o!==87&&o!==119||!Vy.call(s,s.previous)||xf(s.events)?r(o):(n.enter("literalAutolink"),n.enter("literalAutolinkWww"),n.check(hC,n.attempt(qy,n.attempt(Hy,d),r),r)(o))}function d(o){return n.exit("literalAutolinkWww"),n.exit("literalAutolink"),i(o)}}function bC(n,i,r){const s=this;let f="",d=!1;return o;function o(y){return(y===72||y===104)&&Qy.call(s,s.previous)&&!xf(s.events)?(n.enter("literalAutolink"),n.enter("literalAutolinkHttp"),f+=String.fromCodePoint(y),n.consume(y),m):r(y)}function m(y){if(en(y)&&f.length<5)return f+=String.fromCodePoint(y),n.consume(y),m;if(y===58){const v=f.toLowerCase();if(v==="http"||v==="https")return n.consume(y),g}return r(y)}function g(y){return y===47?(n.consume(y),d?p:(d=!0,g)):r(y)}function p(y){return y===null||zs(y)||xt(y)||li(y)||qs(y)?r(y):n.attempt(qy,n.attempt(Hy,b),r)(y)}function b(y){return n.exit("literalAutolinkHttp"),n.exit("literalAutolink"),i(y)}}function xC(n,i,r){let s=0;return f;function f(o){return(o===87||o===119)&&s<3?(s++,n.consume(o),f):o===46&&s===3?(n.consume(o),d):r(o)}function d(o){return o===null?r(o):i(o)}}function vC(n,i,r){let s,f,d;return o;function o(p){return p===46||p===95?n.check(Iy,g,m)(p):p===null||xt(p)||li(p)||p!==45&&qs(p)?g(p):(d=!0,n.consume(p),o)}function m(p){return p===95?s=!0:(f=s,s=void 0),n.consume(p),o}function g(p){return f||s||!d?r(p):i(p)}}function SC(n,i){let r=0,s=0;return f;function f(o){return o===40?(r++,n.consume(o),f):o===41&&s<r?d(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?n.check(Iy,i,d)(o):o===null||xt(o)||li(o)?i(o):(n.consume(o),f)}function d(o){return o===41&&s++,n.consume(o),f}}function jC(n,i,r){return s;function s(m){return m===33||m===34||m===39||m===41||m===42||m===44||m===46||m===58||m===59||m===63||m===95||m===126?(n.consume(m),s):m===38?(n.consume(m),d):m===93?(n.consume(m),f):m===60||m===null||xt(m)||li(m)?i(m):r(m)}function f(m){return m===null||m===40||m===91||xt(m)||li(m)?i(m):s(m)}function d(m){return en(m)?o(m):r(m)}function o(m){return m===59?(n.consume(m),s):en(m)?(n.consume(m),o):r(m)}}function kC(n,i,r){return s;function s(d){return n.consume(d),f}function f(d){return Jt(d)?r(d):i(d)}}function Vy(n){return n===null||n===40||n===42||n===95||n===91||n===93||n===126||xt(n)}function Qy(n){return!en(n)}function Xy(n){return!(n===47||Vc(n))}function Vc(n){return n===43||n===45||n===46||n===95||Jt(n)}function xf(n){let i=n.length,r=!1;for(;i--;){const s=n[i][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){r=!0;break}if(s._gfmAutolinkLiteralWalkedInto){r=!1;break}}return n.length>0&&!r&&(n[n.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const wC={tokenize:_C,partial:!0};function CC(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:AC,continuation:{tokenize:zC},exit:RC}},text:{91:{name:"gfmFootnoteCall",tokenize:TC},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:EC,resolveTo:NC}}}}function EC(n,i,r){const s=this;let f=s.events.length;const d=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o;for(;f--;){const g=s.events[f][1];if(g.type==="labelImage"){o=g;break}if(g.type==="gfmFootnoteCall"||g.type==="labelLink"||g.type==="label"||g.type==="image"||g.type==="link")break}return m;function m(g){if(!o||!o._balanced)return r(g);const p=Mn(s.sliceSerialize({start:o.end,end:s.now()}));return p.codePointAt(0)!==94||!d.includes(p.slice(1))?r(g):(n.enter("gfmFootnoteCallLabelMarker"),n.consume(g),n.exit("gfmFootnoteCallLabelMarker"),i(g))}}function NC(n,i){let r=n.length;for(;r--;)if(n[r][1].type==="labelImage"&&n[r][0]==="enter"){n[r][1];break}n[r+1][1].type="data",n[r+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},n[r+3][1].start),end:Object.assign({},n[n.length-1][1].end)},f={type:"gfmFootnoteCallMarker",start:Object.assign({},n[r+3][1].end),end:Object.assign({},n[r+3][1].end)};f.end.column++,f.end.offset++,f.end._bufferIndex++;const d={type:"gfmFootnoteCallString",start:Object.assign({},f.end),end:Object.assign({},n[n.length-1][1].start)},o={type:"chunkString",contentType:"string",start:Object.assign({},d.start),end:Object.assign({},d.end)},m=[n[r+1],n[r+2],["enter",s,i],n[r+3],n[r+4],["enter",f,i],["exit",f,i],["enter",d,i],["enter",o,i],["exit",o,i],["exit",d,i],n[n.length-2],n[n.length-1],["exit",s,i]];return n.splice(r,n.length-r+1,...m),n}function TC(n,i,r){const s=this,f=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let d=0,o;return m;function m(y){return n.enter("gfmFootnoteCall"),n.enter("gfmFootnoteCallLabelMarker"),n.consume(y),n.exit("gfmFootnoteCallLabelMarker"),g}function g(y){return y!==94?r(y):(n.enter("gfmFootnoteCallMarker"),n.consume(y),n.exit("gfmFootnoteCallMarker"),n.enter("gfmFootnoteCallString"),n.enter("chunkString").contentType="string",p)}function p(y){if(d>999||y===93&&!o||y===null||y===91||xt(y))return r(y);if(y===93){n.exit("chunkString");const v=n.exit("gfmFootnoteCallString");return f.includes(Mn(s.sliceSerialize(v)))?(n.enter("gfmFootnoteCallLabelMarker"),n.consume(y),n.exit("gfmFootnoteCallLabelMarker"),n.exit("gfmFootnoteCall"),i):r(y)}return xt(y)||(o=!0),d++,n.consume(y),y===92?b:p}function b(y){return y===91||y===92||y===93?(n.consume(y),d++,p):p(y)}}function AC(n,i,r){const s=this,f=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let d,o=0,m;return g;function g(N){return n.enter("gfmFootnoteDefinition")._container=!0,n.enter("gfmFootnoteDefinitionLabel"),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(N),n.exit("gfmFootnoteDefinitionLabelMarker"),p}function p(N){return N===94?(n.enter("gfmFootnoteDefinitionMarker"),n.consume(N),n.exit("gfmFootnoteDefinitionMarker"),n.enter("gfmFootnoteDefinitionLabelString"),n.enter("chunkString").contentType="string",b):r(N)}function b(N){if(o>999||N===93&&!m||N===null||N===91||xt(N))return r(N);if(N===93){n.exit("chunkString");const D=n.exit("gfmFootnoteDefinitionLabelString");return d=Mn(s.sliceSerialize(D)),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(N),n.exit("gfmFootnoteDefinitionLabelMarker"),n.exit("gfmFootnoteDefinitionLabel"),v}return xt(N)||(m=!0),o++,n.consume(N),N===92?y:b}function y(N){return N===91||N===92||N===93?(n.consume(N),o++,b):b(N)}function v(N){return N===58?(n.enter("definitionMarker"),n.consume(N),n.exit("definitionMarker"),f.includes(d)||f.push(d),tt(n,S,"gfmFootnoteDefinitionWhitespace")):r(N)}function S(N){return i(N)}}function zC(n,i,r){return n.check(ra,i,n.attempt(wC,i,r))}function RC(n){n.exit("gfmFootnoteDefinition")}function _C(n,i,r){const s=this;return tt(n,f,"gfmFootnoteDefinitionIndent",5);function f(d){const o=s.events[s.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?i(d):r(d)}}function DC(n){let r=(n||{}).singleTilde;const s={name:"strikethrough",tokenize:d,resolveAll:f};return r==null&&(r=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function f(o,m){let g=-1;for(;++g<o.length;)if(o[g][0]==="enter"&&o[g][1].type==="strikethroughSequenceTemporary"&&o[g][1]._close){let p=g;for(;p--;)if(o[p][0]==="exit"&&o[p][1].type==="strikethroughSequenceTemporary"&&o[p][1]._open&&o[g][1].end.offset-o[g][1].start.offset===o[p][1].end.offset-o[p][1].start.offset){o[g][1].type="strikethroughSequence",o[p][1].type="strikethroughSequence";const b={type:"strikethrough",start:Object.assign({},o[p][1].start),end:Object.assign({},o[g][1].end)},y={type:"strikethroughText",start:Object.assign({},o[p][1].end),end:Object.assign({},o[g][1].start)},v=[["enter",b,m],["enter",o[p][1],m],["exit",o[p][1],m],["enter",y,m]],S=m.parser.constructs.insideSpan.null;S&&xn(v,v.length,0,Hs(S,o.slice(p+1,g),m)),xn(v,v.length,0,[["exit",y,m],["enter",o[g][1],m],["exit",o[g][1],m],["exit",b,m]]),xn(o,p-1,g-p+3,v),g=p+v.length-2;break}}for(g=-1;++g<o.length;)o[g][1].type==="strikethroughSequenceTemporary"&&(o[g][1].type="data");return o}function d(o,m,g){const p=this.previous,b=this.events;let y=0;return v;function v(N){return p===126&&b[b.length-1][1].type!=="characterEscape"?g(N):(o.enter("strikethroughSequenceTemporary"),S(N))}function S(N){const D=Fi(p);if(N===126)return y>1?g(N):(o.consume(N),y++,S);if(y<2&&!r)return g(N);const z=o.exit("strikethroughSequenceTemporary"),_=Fi(N);return z._open=!_||_===2&&!!D,z._close=!D||D===2&&!!_,m(N)}}}class OC{constructor(){this.map=[]}add(i,r,s){MC(this,i,r,s)}consume(i){if(this.map.sort(function(d,o){return d[0]-o[0]}),this.map.length===0)return;let r=this.map.length;const s=[];for(;r>0;)r-=1,s.push(i.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),i.length=this.map[r][0];s.push(i.slice()),i.length=0;let f=s.pop();for(;f;){for(const d of f)i.push(d);f=s.pop()}this.map.length=0}}function MC(n,i,r,s){let f=0;if(!(r===0&&s.length===0)){for(;f<n.map.length;){if(n.map[f][0]===i){n.map[f][1]+=r,n.map[f][2].push(...s);return}f+=1}n.map.push([i,r,s])}}function LC(n,i){let r=!1;const s=[];for(;i<n.length;){const f=n[i];if(r){if(f[0]==="enter")f[1].type==="tableContent"&&s.push(n[i+1][1].type==="tableDelimiterMarker"?"left":"none");else if(f[1].type==="tableContent"){if(n[i-1][1].type==="tableDelimiterMarker"){const d=s.length-1;s[d]=s[d]==="left"?"center":"right"}}else if(f[1].type==="tableDelimiterRow")break}else f[0]==="enter"&&f[1].type==="tableDelimiterRow"&&(r=!0);i+=1}return s}function UC(){return{flow:{null:{name:"table",tokenize:BC,resolveAll:qC}}}}function BC(n,i,r){const s=this;let f=0,d=0,o;return m;function m(A){let G=s.events.length-1;for(;G>-1;){const ae=s.events[G][1].type;if(ae==="lineEnding"||ae==="linePrefix")G--;else break}const V=G>-1?s.events[G][1].type:null,se=V==="tableHead"||V==="tableRow"?R:g;return se===R&&s.parser.lazy[s.now().line]?r(A):se(A)}function g(A){return n.enter("tableHead"),n.enter("tableRow"),p(A)}function p(A){return A===124||(o=!0,d+=1),b(A)}function b(A){return A===null?r(A):Me(A)?d>1?(d=0,s.interrupt=!0,n.exit("tableRow"),n.enter("lineEnding"),n.consume(A),n.exit("lineEnding"),S):r(A):Ze(A)?tt(n,b,"whitespace")(A):(d+=1,o&&(o=!1,f+=1),A===124?(n.enter("tableCellDivider"),n.consume(A),n.exit("tableCellDivider"),o=!0,b):(n.enter("data"),y(A)))}function y(A){return A===null||A===124||xt(A)?(n.exit("data"),b(A)):(n.consume(A),A===92?v:y)}function v(A){return A===92||A===124?(n.consume(A),y):y(A)}function S(A){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(A):(n.enter("tableDelimiterRow"),o=!1,Ze(A)?tt(n,N,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):N(A))}function N(A){return A===45||A===58?z(A):A===124?(o=!0,n.enter("tableCellDivider"),n.consume(A),n.exit("tableCellDivider"),D):ce(A)}function D(A){return Ze(A)?tt(n,z,"whitespace")(A):z(A)}function z(A){return A===58?(d+=1,o=!0,n.enter("tableDelimiterMarker"),n.consume(A),n.exit("tableDelimiterMarker"),_):A===45?(d+=1,_(A)):A===null||Me(A)?oe(A):ce(A)}function _(A){return A===45?(n.enter("tableDelimiterFiller"),M(A)):ce(A)}function M(A){return A===45?(n.consume(A),M):A===58?(o=!0,n.exit("tableDelimiterFiller"),n.enter("tableDelimiterMarker"),n.consume(A),n.exit("tableDelimiterMarker"),H):(n.exit("tableDelimiterFiller"),H(A))}function H(A){return Ze(A)?tt(n,oe,"whitespace")(A):oe(A)}function oe(A){return A===124?N(A):A===null||Me(A)?!o||f!==d?ce(A):(n.exit("tableDelimiterRow"),n.exit("tableHead"),i(A)):ce(A)}function ce(A){return r(A)}function R(A){return n.enter("tableRow"),W(A)}function W(A){return A===124?(n.enter("tableCellDivider"),n.consume(A),n.exit("tableCellDivider"),W):A===null||Me(A)?(n.exit("tableRow"),i(A)):Ze(A)?tt(n,W,"whitespace")(A):(n.enter("data"),ie(A))}function ie(A){return A===null||A===124||xt(A)?(n.exit("data"),W(A)):(n.consume(A),A===92?F:ie)}function F(A){return A===92||A===124?(n.consume(A),ie):ie(A)}}function qC(n,i){let r=-1,s=!0,f=0,d=[0,0,0,0],o=[0,0,0,0],m=!1,g=0,p,b,y;const v=new OC;for(;++r<n.length;){const S=n[r],N=S[1];S[0]==="enter"?N.type==="tableHead"?(m=!1,g!==0&&(wg(v,i,g,p,b),b=void 0,g=0),p={type:"table",start:Object.assign({},N.start),end:Object.assign({},N.end)},v.add(r,0,[["enter",p,i]])):N.type==="tableRow"||N.type==="tableDelimiterRow"?(s=!0,y=void 0,d=[0,0,0,0],o=[0,r+1,0,0],m&&(m=!1,b={type:"tableBody",start:Object.assign({},N.start),end:Object.assign({},N.end)},v.add(r,0,[["enter",b,i]])),f=N.type==="tableDelimiterRow"?2:b?3:1):f&&(N.type==="data"||N.type==="tableDelimiterMarker"||N.type==="tableDelimiterFiller")?(s=!1,o[2]===0&&(d[1]!==0&&(o[0]=o[1],y=Cs(v,i,d,f,void 0,y),d=[0,0,0,0]),o[2]=r)):N.type==="tableCellDivider"&&(s?s=!1:(d[1]!==0&&(o[0]=o[1],y=Cs(v,i,d,f,void 0,y)),d=o,o=[d[1],r,0,0])):N.type==="tableHead"?(m=!0,g=r):N.type==="tableRow"||N.type==="tableDelimiterRow"?(g=r,d[1]!==0?(o[0]=o[1],y=Cs(v,i,d,f,r,y)):o[1]!==0&&(y=Cs(v,i,o,f,r,y)),f=0):f&&(N.type==="data"||N.type==="tableDelimiterMarker"||N.type==="tableDelimiterFiller")&&(o[3]=r)}for(g!==0&&wg(v,i,g,p,b),v.consume(i.events),r=-1;++r<i.events.length;){const S=i.events[r];S[0]==="enter"&&S[1].type==="table"&&(S[1]._align=LC(i.events,r))}return n}function Cs(n,i,r,s,f,d){const o=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",m="tableContent";r[0]!==0&&(d.end=Object.assign({},Ki(i.events,r[0])),n.add(r[0],0,[["exit",d,i]]));const g=Ki(i.events,r[1]);if(d={type:o,start:Object.assign({},g),end:Object.assign({},g)},n.add(r[1],0,[["enter",d,i]]),r[2]!==0){const p=Ki(i.events,r[2]),b=Ki(i.events,r[3]),y={type:m,start:Object.assign({},p),end:Object.assign({},b)};if(n.add(r[2],0,[["enter",y,i]]),s!==2){const v=i.events[r[2]],S=i.events[r[3]];if(v[1].end=Object.assign({},S[1].end),v[1].type="chunkText",v[1].contentType="text",r[3]>r[2]+1){const N=r[2]+1,D=r[3]-r[2]-1;n.add(N,D,[])}}n.add(r[3]+1,0,[["exit",y,i]])}return f!==void 0&&(d.end=Object.assign({},Ki(i.events,f)),n.add(f,0,[["exit",d,i]]),d=void 0),d}function wg(n,i,r,s,f){const d=[],o=Ki(i.events,r);f&&(f.end=Object.assign({},o),d.push(["exit",f,i])),s.end=Object.assign({},o),d.push(["exit",s,i]),n.add(r+1,0,d)}function Ki(n,i){const r=n[i],s=r[0]==="enter"?"start":"end";return r[1][s]}const HC={name:"tasklistCheck",tokenize:YC};function IC(){return{text:{91:HC}}}function YC(n,i,r){const s=this;return f;function f(g){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?r(g):(n.enter("taskListCheck"),n.enter("taskListCheckMarker"),n.consume(g),n.exit("taskListCheckMarker"),d)}function d(g){return xt(g)?(n.enter("taskListCheckValueUnchecked"),n.consume(g),n.exit("taskListCheckValueUnchecked"),o):g===88||g===120?(n.enter("taskListCheckValueChecked"),n.consume(g),n.exit("taskListCheckValueChecked"),o):r(g)}function o(g){return g===93?(n.enter("taskListCheckMarker"),n.consume(g),n.exit("taskListCheckMarker"),n.exit("taskListCheck"),m):r(g)}function m(g){return Me(g)?i(g):Ze(g)?n.check({tokenize:GC},i,r)(g):r(g)}}function GC(n,i,r){return tt(n,s,"whitespace");function s(f){return f===null?r(f):i(f)}}function VC(n){return ly([mC(),CC(),DC(n),UC(),IC()])}const QC={};function XC(n){const i=this,r=n||QC,s=i.data(),f=s.micromarkExtensions||(s.micromarkExtensions=[]),d=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),o=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);f.push(VC(r)),d.push(fC()),o.push(dC(r))}function Qc(n){const i=n.trim();if(!(!i||/[\u0000-\u0020\u007f]/.test(i)))try{const r=new URL(i);if(r.protocol==="https:"||r.protocol==="http:"||r.protocol==="mailto:")return i}catch{}}function Xc(n){return!!n&&!/[\u0000-\u001f\u007f]/.test(n)&&!/^[a-z][a-z\d+.-]*:/i.test(n)&&!n.startsWith("//")}function Cg(n){if(!Xc(n))return;const i=n.split(/[?#]/,1)[0];if(i)try{const r=decodeURIComponent(i);return Xc(r)?r:void 0}catch{return}}async function ZC(n){if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(n);return}const i=document.activeElement,r=document.createElement("textarea");r.value=n,r.setAttribute("aria-label","复制内容"),r.style.cssText="position:fixed;left:-10000px;top:0",document.body.append(r);try{if(r.select(),!document.execCommand("copy"))throw new Error("复制不可用")}finally{r.remove(),i instanceof HTMLElement&&i.focus({preventScroll:!0})}}function Vs({text:n,label:i="复制"}){const[r,s]=w.useState("idle"),f=w.useRef(!0),d=w.useRef(void 0);w.useEffect(()=>(f.current=!0,()=>{f.current=!1,clearTimeout(d.current)}),[]);const o=async()=>{clearTimeout(d.current);try{await ZC(n),f.current&&s("copied")}catch{f.current&&s("error")}f.current&&(d.current=setTimeout(()=>s("idle"),2500))};return u.jsx("button",{className:"message-copy",onClick:()=>{o()},"aria-label":i,title:i,children:r==="copied"?"已复制":r==="error"?"复制失败":i})}function Zc(n){return typeof n=="string"||typeof n=="number"?String(n):Array.isArray(n)?n.map(Zc).join(""):w.isValidElement(n)?Zc(n.props.children):""}function KC({children:n}){const i=w.Children.toArray(n).find(d=>w.isValidElement(d)),s=(w.isValidElement(i)?i.props.className??"":"").match(/(?:^|\s)language-([\w+-]+)/)?.[1]??"代码",f=Zc(n).replace(/\n$/,"");return u.jsxs("div",{className:"message-code-block",children:[u.jsxs("div",{className:"message-code-heading",children:[u.jsx("span",{children:s}),u.jsx(Vs,{text:f,label:"复制代码"})]}),u.jsx("pre",{tabIndex:0,children:n})]})}function FC(n){return{a:({href:i,children:r,title:s})=>{const f=Qc(i??"");if(f)return u.jsx("a",{href:f,title:s,target:"_blank",rel:"noopener noreferrer",referrerPolicy:"no-referrer",children:r});const d=i?Cg(i):void 0;return d?u.jsxs("span",{className:"message-file-reference",title:d,children:[n?u.jsx("button",{className:"message-file-open",onClick:()=>n(d),children:r}):r,u.jsx(Vs,{text:d,label:"复制路径"})]}):u.jsx("span",{children:r})},img:({src:i,alt:r})=>{const s=Qc(typeof i=="string"?i:""),f=typeof i=="string"?Cg(i):void 0;return s?u.jsxs("a",{className:"message-image-reference",href:s,target:"_blank",rel:"noopener noreferrer",referrerPolicy:"no-referrer",children:[r||"图片",u.jsx("span",{children:"打开图片 ↗"})]}):f&&n?u.jsxs("button",{className:"message-image-reference",title:f,onClick:()=>n(f),children:[r||"图片",u.jsx("span",{children:"查看图片"})]}):u.jsxs("span",{className:"message-image-reference",children:[r||"图片",u.jsx("span",{children:"图片路径不可直接访问"})]})},pre:({children:i})=>u.jsx(KC,{children:i}),table:({children:i})=>u.jsx("div",{className:"message-table-scroll",role:"region","aria-label":"表格",tabIndex:0,children:u.jsx("table",{children:i})})}}const $C=w.memo(function({text:i,reasoning:r="",streaming:s=!1,onOpenFile:f}){const d=w.useMemo(()=>FC(f),[f]);return u.jsxs("div",{className:"message-content",children:[r?u.jsxs("details",{className:"message-reasoning",children:[u.jsx("summary",{children:s&&!i?"思考中…":"思考过程"}),u.jsx("pre",{children:r})]}):null,s?u.jsxs("div",{className:"message-streaming",children:[i||(r?"":"正在思考…"),u.jsx("span",{className:"cursor","aria-hidden":"true",children:"▍"})]}):i?u.jsx(Dk,{remarkPlugins:[XC],skipHtml:!0,urlTransform:o=>Qc(o)??(Xc(o)?o:""),components:d,children:i}):null,!s&&i?u.jsx("div",{className:"message-actions",children:u.jsx(Vs,{text:i,label:"复制回复"})}):null]})});function JC(n){const i=n.args??{},r=n.summary||[i.description,i.command,i.file_path,i.path,i.query,i.url].find(s=>typeof s=="string"&&s.trim());return typeof r=="string"?r.replace(/\s+/g," ").slice(0,180):""}const PC=w.memo(function({item:i,running:r}){const s=JC(i),f=i.done?i.error?"失败":"已完成":r?"执行中":"未完成";return u.jsxs("details",{className:`message-tool-card${i.error?" message-tool-error":""}`,children:[u.jsxs("summary",{children:[u.jsx("span",{className:"message-tool-indicator","aria-hidden":"true",children:i.done?i.error?"!":"✓":"·"}),u.jsx("span",{className:"message-tool-name",children:i.name}),u.jsx("span",{className:"message-tool-summary",children:s}),u.jsx("span",{className:"message-tool-status",children:f})]}),i.args&&Object.keys(i.args).length?u.jsxs("div",{className:"message-tool-section",children:[u.jsx("strong",{children:"参数"}),u.jsx("pre",{tabIndex:0,children:JSON.stringify(i.args,null,2)})]}):null,u.jsxs("div",{className:"message-tool-section",children:[u.jsxs("div",{className:"message-tool-result-heading",children:[u.jsx("strong",{children:"结果"}),i.result?u.jsx(Vs,{text:i.result,label:"复制结果"}):null]}),u.jsx("pre",{tabIndex:0,children:i.result??(i.done?"工具没有返回文本内容。":r?"等待工具返回结果…":"这次工具调用没有保存结果。")})]})]})});function WC(n){return{running:"运行中",completed:"已完成",error:"失败",recorded:"历史记录"}[n]??n}function Eg(n){return n.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"")}function As(){return{items:[],run:"idle",seq:0,liveByAgent:{}}}function Kr(n){return n.agentId??""}function Es(n,i,r=!1){const s=i.goalId;if(n.goalId!==s&&!(r&&n.goalId===void 0&&s!==void 0))return!0;const f=i.revision;return n.goalRevision!==void 0&&(f===void 0||f<n.goalRevision)}function eE(n){switch(n){case"aborted_streaming":case"aborted_tools":return"idle";case"prompt_too_long":case"model_error":case"image_error":return"error";default:return"completed"}}function tE(n){if(!n||typeof n!="object")return null;const i=n;if(i.method==="agent/streamEvent"&&i.params&&typeof i.params=="object"){const r=i.params;if(r.event&&typeof r.event=="object")return{event:r.event,sessionId:typeof r.sessionId=="string"?r.sessionId:void 0}}return typeof i.type=="string"?{event:i}:null}function Os(n,i){const r=tE(i);if(!r)return n;const{event:s,sessionId:f}=r,d=s.type;let o=n;f&&f!==o.sessionId&&(o={...o,sessionId:f});const m=g=>{const p=o.seq+1;return[`${g}-${p}`,{...o,seq:p}]};switch(d){case"stream_request_start":{const g=Kr(s),[p,b]=m("a"),y={kind:"assistant",id:p,text:"",reasoning:"",done:!1,agentId:s.agentId,...typeof s.messageId=="string"?{messageId:s.messageId}:{}};return{...b,items:[...b.items,y],liveByAgent:{...b.liveByAgent,[g]:p},run:"running"}}case"text_delta":{const g=s.text??"",p=Kr(s),b=o.liveByAgent[p];if(b&&o.items.find(D=>D.id===b&&D.kind==="assistant"))return{...o,run:"running",items:o.items.map(D=>D.id===b&&D.kind==="assistant"?{...D,text:D.text+g}:D)};const[v,S]=m("a"),N={kind:"assistant",id:v,text:g,reasoning:"",done:!1,agentId:s.agentId};return{...S,items:[...S.items,N],liveByAgent:{...S.liveByAgent,[p]:v},run:"running"}}case"thinking_delta":{const g=s.text??"",p=Kr(s),b=o.liveByAgent[p];if(b&&o.items.some(N=>N.id===b&&N.kind==="assistant"))return{...o,run:"running",items:o.items.map(N=>N.id===b&&N.kind==="assistant"?{...N,reasoning:N.reasoning+g}:N)};const[y,v]=m("a"),S={kind:"assistant",id:y,text:"",reasoning:g,done:!1,agentId:s.agentId};return{...v,items:[...v.items,S],liveByAgent:{...v.liveByAgent,[p]:y},run:"running"}}case"tool_use_start":{const g=s.toolCall;if(!g||o.items.some(v=>v.kind==="tool"&&v.id===g.id))return o;const p=o.orphanResults?.[g.id],b={kind:"tool",id:g.id,name:g.toolName,args:g.args,summary:g.summary,done:!!p,result:p?.result,error:p?.error,agentId:s.agentId};let y=o.orphanResults;if(p){const{[g.id]:v,...S}=o.orphanResults;y=Object.keys(S).length>0?S:void 0}return{...o,run:"running",items:[...o.items,b],orphanResults:y}}case"tool_use_args_delta":{const g=s.toolCallId,p=s.args;return!g||!p?o:{...o,items:o.items.map(b=>b.kind==="tool"&&b.id===g?{...b,args:{...b.args??{},...p}}:b)}}case"tool_result":{const g=s.result;return g?o.items.some(b=>b.kind==="tool"&&b.id===g.id)?{...o,items:o.items.map(b=>b.kind==="tool"&&b.id===g.id?{...b,done:!0,result:Eg(g.result??g.error??""),error:!!(g.isError||g.error)}:b)}:{...o,orphanResults:{...o.orphanResults??{},[g.id]:{result:g.result??g.error??"",error:!!(g.isError||g.error)}}}:o}case"room_tool_result":{const g=s.summary??"",p=Eg(g),b=!!s.isError;let y=-1;for(let N=o.items.length-1;N>=0;N--)if(o.items[N].kind==="tool"&&!o.items[N].done){y=N;break}if(y===-1)return o;const v=o.items.slice(),S=v[y];return v[y]={...S,done:!0,result:p,summary:p||S.summary,error:b},{...o,items:v}}case"tool_summary":{const g=s.summary??"",p=Array.isArray(s.toolCallIds)?s.toolCallIds.filter(D=>typeof D=="string"):[],y=p.length>0?p[p.length-1]:void 0,v=s.agentId;if(y){let D=!1;const z=o.items.map(_=>_.kind!=="tool"||_.id!==y||_.agentId!==v?_:(D=!0,{..._,summary:g}));return D?{...o,items:z}:o}if(v){let D=-1;for(let _=o.items.length-1;_>=0;_--){const M=o.items[_];if(M.kind==="tool"&&M.agentId===v){D=_;break}}if(D===-1)return o;const z=o.items.slice();return z[D]={...z[D],summary:g},{...o,items:z}}let S=-1;for(let D=o.items.length-1;D>=0;D--){const z=o.items[D];if(z.kind==="tool"&&z.agentId===void 0){S=D;break}}if(S===-1)return o;const N=o.items.slice();return N[S]={...N[S],summary:g},{...o,items:N}}case"tombstone":{if(typeof s.messageId!="string")return o;const g=new Set(o.items.filter(p=>p.kind==="assistant"&&p.messageId===s.messageId||p.kind==="tool"&&p.id===s.messageId).map(p=>p.id));return g.size?{...o,items:o.items.filter(p=>!g.has(p.id)),liveByAgent:Object.fromEntries(Object.entries(o.liveByAgent).filter(([,p])=>!g.has(p)))}:o}case"assistant_message":{const g=Kr(s);if(!(g in o.liveByAgent))return o;const{[g]:p,...b}=o.liveByAgent,y=o.items.map(v=>v.kind==="assistant"&&!v.done&&(v.agentId??"")===g?{...v,done:!0}:v);return{...o,liveByAgent:b,items:y}}case"turn_complete":{const g=s.reason??"completed",p=Kr(s),{[p]:b,...y}=o.liveByAgent,v=o.items.map(S=>S.kind==="assistant"&&!S.done&&(S.agentId??"")===p?{...S,done:!0}:S);return s.agentId?{...o,liveByAgent:y,items:v}:{...o,liveByAgent:y,items:v,run:eE(g)}}case"goal_set":{const g=s.objective??"",p=!!s.paused;return o.goal&&o.goalId===s.goalId&&Es(o,s)?o:{...o,goal:g?`◎ ${g}${p?" (已暂停)":""}`:"◎ 目标",goalId:s.goalId,goalPaused:p,goalRevision:s.revision}}case"goal_updated":{if(o.goal&&Es(o,s,!0))return o;const g=s.goalId,p=s.objective??"",b=!!s.paused;return{...o,goal:p?`◎ ${p}${b?" (已暂停)":""}`:o.goal,goalId:g??o.goalId,goalPaused:b,goalRevision:s.revision??o.goalRevision}}case"goal_cleared":return o.goal&&Es(o,s)?o:{...o,goal:void 0,goalId:void 0,goalPaused:void 0,goalRevision:void 0};case"goal_progress":{if(o.goal&&Es(o,s))return o;const g=s.status??"";if(g==="met"||g==="exhausted")return{...o,goal:void 0,goalId:void 0,goalPaused:void 0,goalRevision:void 0};const p=s.round,b=p?`目标 · 第 ${p} 轮 (${g})`:`目标 (${g})`;return{...o,goal:b,goalRevision:s.revision??o.goalRevision}}case"task_update":{const g=s.agentId;if(!g)return o;const p=s.tasks??[],b=p.filter(N=>N.status==="completed").length,y=`任务 ${b}/${p.length}`,v=o.items.findIndex(N=>N.kind==="subagent"&&N.agentId===g),S={kind:"subagent",id:`sub-${g}`,agentId:g,label:y,status:p.length>0&&b===p.length?"completed":"running"};if(v>=0){const N=o.items.slice();return N[v]=S,{...o,items:N}}return{...o,items:[...o.items,S]}}case"agent_start":{const g=s.agentId;if(!g)return o;const p={kind:"subagent",id:`sub-${g}`,agentId:g,label:s.name||s.description||"子代理",status:s.status==="recorded"?"recorded":"running"};return o.items.some(b=>b.kind==="subagent"&&b.agentId===g)?o:{...o,items:[...o.items,p]}}case"agent_end":{const g=s.agentId;return{...o,items:o.items.map(p=>p.kind==="subagent"&&p.agentId===g?{...p,status:s.error?"error":"completed"}:p)}}case"error":{const[g,p]=m("err");return{...p,run:"error",liveByAgent:{},items:[...p.items,{kind:"system_error",id:g,text:s.error||"运行出错"}]}}case"session_title":return{...o,title:s.title};case"session_user_message":case"user_message":{const g=typeof s.clientMessageId=="string"?s.clientMessageId:void 0,p=Array.isArray(s.attachments)?s.attachments.map(v=>v).filter(v=>!!v&&typeof v.name=="string"&&typeof v.size=="number"&&Number.isFinite(v.size)&&v.size>=0).map(v=>({name:v.name,size:v.size,...typeof v.mime=="string"?{mime:v.mime}:{},...typeof v.path=="string"?{path:v.path}:{}})):void 0;if(g&&o.items.some(v=>v.kind==="user"&&v.clientMessageId===g))return p?.length?{...o,items:o.items.map(v=>v.kind==="user"&&v.clientMessageId===g?{...v,attachments:p.map((S,N)=>{const D=v.attachments?.[N];return D?.name===S.name?{...D,...S}:S})}:v)}:o;const[b,y]=m("u");return{...y,items:[...y.items,{kind:"user",id:b,text:s.text??"",...p?.length?{attachments:p}:{},...g?{clientMessageId:g}:{}}]}}case"assistant_text":{const[g,p]=m("a");return{...p,run:"running",items:[...p.items,{kind:"assistant",id:g,text:s.text??"",reasoning:"",done:!0,agentId:s.agentId}]}}default:return o}}function nE(n,i,r,s){const f=`u-${n.seq+1}`;return{...n,seq:n.seq+1,items:[...n.items,{kind:"user",id:f,text:i,...r?.length?{attachments:r}:{},...s?{clientMessageId:s}:{}}]}}function On(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function yt(n){return typeof n=="string"?n:""}function Ms(n){return Array.isArray(n)?n.map(On).filter(i=>i!==void 0):[]}function Kc(n){return typeof n=="string"?n:Ms(n).filter(i=>i.type==="text").map(i=>yt(i.text)).join("")}function Ns(n){return n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Rc(n){const i=n.replace(/\\/g,"/").split("/").filter(Boolean).pop()||"附件";return n.includes(".code-shell/attachments/")?i.replace(/^[a-f0-9]{16}-/,""):i}function Ng(n){const i=typeof n=="number"?n:Number(n);return Number.isSafeInteger(i)&&i>=0?i:0}function lE(n){const i=[],r=[];let s=Kc(n.content);s=s.replace(/<attached-file\s+path="([^"]*)">\s*([\s\S]*?)<\/attached-file>/g,(o,m,g)=>{if(!/^absolutePath:\s*.+$/m.test(g)||!/^origin:\s*.+$/m.test(g))return o;const p=g.match(/^mime:\s*(.+)$/m)?.[1]?.trim();return i.push({name:Rc(Ns(m)),path:Ns(m),size:Ng(g.match(/^size:\s*(\d+)\s*$/m)?.[1]),...p?{mime:p}:{}}),""}),s=s.replace(/<attached-directory\s+path="([^"]*)"[^>]*>[\s\S]*?<\/attached-directory>/g,(o,m)=>(i.push({name:`${Rc(Ns(m))}/`,path:Ns(m),size:0}),"")),s=s.replace(/<attached-image-paths>\s*([\s\S]*?)<\/attached-image-paths>\s*(?:\(上面附带的图片在工作区的真实路径[^\n]*\))?/g,(o,m)=>(r.push(...m.split(`
48
+ `))}function g(S,N,D,z){const _=D.enter("tableCell"),M=D.enter("phrasing"),H=D.containerPhrasing(S,{...z,before:d,after:d});return M(),_(),H}function p(S,N){return vw(S,{align:N,alignDelimiters:s,padding:r,stringLength:f})}function b(S,N,D){const z=S.children;let _=-1;const M=[],H=N.enter("table");for(;++_<z.length;)M[_]=y(z[_],N,D);return H(),M}function y(S,N,D){const z=S.children;let _=-1;const M=[],H=N.enter("tableRow");for(;++_<z.length;)M[_]=g(z[_],S,N,D);return H(),M}function v(S,N,D){let z=By.inlineCode(S,N,D);return D.stack.includes("tableCell")&&(z=z.replace(/\|/g,"\\$&")),z}}function sC(){return{exit:{taskListCheckValueChecked:kg,taskListCheckValueUnchecked:kg,paragraph:oC}}}function uC(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:cC}}}function kg(n){const i=this.stack[this.stack.length-2];i.type,i.checked=n.type==="taskListCheckValueChecked"}function oC(n){const i=this.stack[this.stack.length-2];if(i&&i.type==="listItem"&&typeof i.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const s=r.children[0];if(s&&s.type==="text"){const f=i.children;let d=-1,o;for(;++d<f.length;){const m=f[d];if(m.type==="paragraph"){o=m;break}}o===r&&(s.value=s.value.slice(1),s.value.length===0?r.children.shift():r.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,r.position.start=Object.assign({},s.position.start)))}}this.exit(n)}function cC(n,i,r,s){const f=n.children[0],d=typeof n.checked=="boolean"&&f&&f.type==="paragraph",o="["+(n.checked?"x":" ")+"] ",m=r.createTracker(s);d&&m.move(o);let g=By.listItem(n,i,r,{...s,...m.current()});return d&&(g=g.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,p)),g;function p(b){return b+o}}function fC(){return[Gk(),cw(),pw(),eC(),sC()]}function dC(n){return{extensions:[Vk(),fw(n),mw(),aC(n),uC()]}}const hC={tokenize:xC,partial:!0},qy={tokenize:vC,partial:!0},Hy={tokenize:SC,partial:!0},Iy={tokenize:jC,partial:!0},pC={tokenize:kC,partial:!0},Yy={name:"wwwAutolink",tokenize:yC,previous:Vy},Gy={name:"protocolAutolink",tokenize:bC,previous:Qy},ul={name:"emailAutolink",tokenize:gC,previous:Xy},Yn={};function mC(){return{text:Yn}}let ti=48;for(;ti<123;)Yn[ti]=ul,ti++,ti===58?ti=65:ti===91&&(ti=97);Yn[43]=ul;Yn[45]=ul;Yn[46]=ul;Yn[95]=ul;Yn[72]=[ul,Gy];Yn[104]=[ul,Gy];Yn[87]=[ul,Yy];Yn[119]=[ul,Yy];function gC(n,i,r){const s=this;let f,d;return o;function o(y){return!Vc(y)||!Xy.call(s,s.previous)||xf(s.events)?r(y):(n.enter("literalAutolink"),n.enter("literalAutolinkEmail"),m(y))}function m(y){return Vc(y)?(n.consume(y),m):y===64?(n.consume(y),g):r(y)}function g(y){return y===46?n.check(pC,b,p)(y):y===45||y===95||Jt(y)?(d=!0,n.consume(y),g):b(y)}function p(y){return n.consume(y),f=!0,g}function b(y){return d&&f&&en(s.previous)?(n.exit("literalAutolinkEmail"),n.exit("literalAutolink"),i(y)):r(y)}}function yC(n,i,r){const s=this;return f;function f(o){return o!==87&&o!==119||!Vy.call(s,s.previous)||xf(s.events)?r(o):(n.enter("literalAutolink"),n.enter("literalAutolinkWww"),n.check(hC,n.attempt(qy,n.attempt(Hy,d),r),r)(o))}function d(o){return n.exit("literalAutolinkWww"),n.exit("literalAutolink"),i(o)}}function bC(n,i,r){const s=this;let f="",d=!1;return o;function o(y){return(y===72||y===104)&&Qy.call(s,s.previous)&&!xf(s.events)?(n.enter("literalAutolink"),n.enter("literalAutolinkHttp"),f+=String.fromCodePoint(y),n.consume(y),m):r(y)}function m(y){if(en(y)&&f.length<5)return f+=String.fromCodePoint(y),n.consume(y),m;if(y===58){const v=f.toLowerCase();if(v==="http"||v==="https")return n.consume(y),g}return r(y)}function g(y){return y===47?(n.consume(y),d?p:(d=!0,g)):r(y)}function p(y){return y===null||zs(y)||xt(y)||li(y)||qs(y)?r(y):n.attempt(qy,n.attempt(Hy,b),r)(y)}function b(y){return n.exit("literalAutolinkHttp"),n.exit("literalAutolink"),i(y)}}function xC(n,i,r){let s=0;return f;function f(o){return(o===87||o===119)&&s<3?(s++,n.consume(o),f):o===46&&s===3?(n.consume(o),d):r(o)}function d(o){return o===null?r(o):i(o)}}function vC(n,i,r){let s,f,d;return o;function o(p){return p===46||p===95?n.check(Iy,g,m)(p):p===null||xt(p)||li(p)||p!==45&&qs(p)?g(p):(d=!0,n.consume(p),o)}function m(p){return p===95?s=!0:(f=s,s=void 0),n.consume(p),o}function g(p){return f||s||!d?r(p):i(p)}}function SC(n,i){let r=0,s=0;return f;function f(o){return o===40?(r++,n.consume(o),f):o===41&&s<r?d(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?n.check(Iy,i,d)(o):o===null||xt(o)||li(o)?i(o):(n.consume(o),f)}function d(o){return o===41&&s++,n.consume(o),f}}function jC(n,i,r){return s;function s(m){return m===33||m===34||m===39||m===41||m===42||m===44||m===46||m===58||m===59||m===63||m===95||m===126?(n.consume(m),s):m===38?(n.consume(m),d):m===93?(n.consume(m),f):m===60||m===null||xt(m)||li(m)?i(m):r(m)}function f(m){return m===null||m===40||m===91||xt(m)||li(m)?i(m):s(m)}function d(m){return en(m)?o(m):r(m)}function o(m){return m===59?(n.consume(m),s):en(m)?(n.consume(m),o):r(m)}}function kC(n,i,r){return s;function s(d){return n.consume(d),f}function f(d){return Jt(d)?r(d):i(d)}}function Vy(n){return n===null||n===40||n===42||n===95||n===91||n===93||n===126||xt(n)}function Qy(n){return!en(n)}function Xy(n){return!(n===47||Vc(n))}function Vc(n){return n===43||n===45||n===46||n===95||Jt(n)}function xf(n){let i=n.length,r=!1;for(;i--;){const s=n[i][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){r=!0;break}if(s._gfmAutolinkLiteralWalkedInto){r=!1;break}}return n.length>0&&!r&&(n[n.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const wC={tokenize:_C,partial:!0};function CC(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:AC,continuation:{tokenize:zC},exit:RC}},text:{91:{name:"gfmFootnoteCall",tokenize:TC},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:EC,resolveTo:NC}}}}function EC(n,i,r){const s=this;let f=s.events.length;const d=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let o;for(;f--;){const g=s.events[f][1];if(g.type==="labelImage"){o=g;break}if(g.type==="gfmFootnoteCall"||g.type==="labelLink"||g.type==="label"||g.type==="image"||g.type==="link")break}return m;function m(g){if(!o||!o._balanced)return r(g);const p=Mn(s.sliceSerialize({start:o.end,end:s.now()}));return p.codePointAt(0)!==94||!d.includes(p.slice(1))?r(g):(n.enter("gfmFootnoteCallLabelMarker"),n.consume(g),n.exit("gfmFootnoteCallLabelMarker"),i(g))}}function NC(n,i){let r=n.length;for(;r--;)if(n[r][1].type==="labelImage"&&n[r][0]==="enter"){n[r][1];break}n[r+1][1].type="data",n[r+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},n[r+3][1].start),end:Object.assign({},n[n.length-1][1].end)},f={type:"gfmFootnoteCallMarker",start:Object.assign({},n[r+3][1].end),end:Object.assign({},n[r+3][1].end)};f.end.column++,f.end.offset++,f.end._bufferIndex++;const d={type:"gfmFootnoteCallString",start:Object.assign({},f.end),end:Object.assign({},n[n.length-1][1].start)},o={type:"chunkString",contentType:"string",start:Object.assign({},d.start),end:Object.assign({},d.end)},m=[n[r+1],n[r+2],["enter",s,i],n[r+3],n[r+4],["enter",f,i],["exit",f,i],["enter",d,i],["enter",o,i],["exit",o,i],["exit",d,i],n[n.length-2],n[n.length-1],["exit",s,i]];return n.splice(r,n.length-r+1,...m),n}function TC(n,i,r){const s=this,f=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let d=0,o;return m;function m(y){return n.enter("gfmFootnoteCall"),n.enter("gfmFootnoteCallLabelMarker"),n.consume(y),n.exit("gfmFootnoteCallLabelMarker"),g}function g(y){return y!==94?r(y):(n.enter("gfmFootnoteCallMarker"),n.consume(y),n.exit("gfmFootnoteCallMarker"),n.enter("gfmFootnoteCallString"),n.enter("chunkString").contentType="string",p)}function p(y){if(d>999||y===93&&!o||y===null||y===91||xt(y))return r(y);if(y===93){n.exit("chunkString");const v=n.exit("gfmFootnoteCallString");return f.includes(Mn(s.sliceSerialize(v)))?(n.enter("gfmFootnoteCallLabelMarker"),n.consume(y),n.exit("gfmFootnoteCallLabelMarker"),n.exit("gfmFootnoteCall"),i):r(y)}return xt(y)||(o=!0),d++,n.consume(y),y===92?b:p}function b(y){return y===91||y===92||y===93?(n.consume(y),d++,p):p(y)}}function AC(n,i,r){const s=this,f=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let d,o=0,m;return g;function g(N){return n.enter("gfmFootnoteDefinition")._container=!0,n.enter("gfmFootnoteDefinitionLabel"),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(N),n.exit("gfmFootnoteDefinitionLabelMarker"),p}function p(N){return N===94?(n.enter("gfmFootnoteDefinitionMarker"),n.consume(N),n.exit("gfmFootnoteDefinitionMarker"),n.enter("gfmFootnoteDefinitionLabelString"),n.enter("chunkString").contentType="string",b):r(N)}function b(N){if(o>999||N===93&&!m||N===null||N===91||xt(N))return r(N);if(N===93){n.exit("chunkString");const D=n.exit("gfmFootnoteDefinitionLabelString");return d=Mn(s.sliceSerialize(D)),n.enter("gfmFootnoteDefinitionLabelMarker"),n.consume(N),n.exit("gfmFootnoteDefinitionLabelMarker"),n.exit("gfmFootnoteDefinitionLabel"),v}return xt(N)||(m=!0),o++,n.consume(N),N===92?y:b}function y(N){return N===91||N===92||N===93?(n.consume(N),o++,b):b(N)}function v(N){return N===58?(n.enter("definitionMarker"),n.consume(N),n.exit("definitionMarker"),f.includes(d)||f.push(d),tt(n,S,"gfmFootnoteDefinitionWhitespace")):r(N)}function S(N){return i(N)}}function zC(n,i,r){return n.check(ra,i,n.attempt(wC,i,r))}function RC(n){n.exit("gfmFootnoteDefinition")}function _C(n,i,r){const s=this;return tt(n,f,"gfmFootnoteDefinitionIndent",5);function f(d){const o=s.events[s.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?i(d):r(d)}}function DC(n){let r=(n||{}).singleTilde;const s={name:"strikethrough",tokenize:d,resolveAll:f};return r==null&&(r=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function f(o,m){let g=-1;for(;++g<o.length;)if(o[g][0]==="enter"&&o[g][1].type==="strikethroughSequenceTemporary"&&o[g][1]._close){let p=g;for(;p--;)if(o[p][0]==="exit"&&o[p][1].type==="strikethroughSequenceTemporary"&&o[p][1]._open&&o[g][1].end.offset-o[g][1].start.offset===o[p][1].end.offset-o[p][1].start.offset){o[g][1].type="strikethroughSequence",o[p][1].type="strikethroughSequence";const b={type:"strikethrough",start:Object.assign({},o[p][1].start),end:Object.assign({},o[g][1].end)},y={type:"strikethroughText",start:Object.assign({},o[p][1].end),end:Object.assign({},o[g][1].start)},v=[["enter",b,m],["enter",o[p][1],m],["exit",o[p][1],m],["enter",y,m]],S=m.parser.constructs.insideSpan.null;S&&xn(v,v.length,0,Hs(S,o.slice(p+1,g),m)),xn(v,v.length,0,[["exit",y,m],["enter",o[g][1],m],["exit",o[g][1],m],["exit",b,m]]),xn(o,p-1,g-p+3,v),g=p+v.length-2;break}}for(g=-1;++g<o.length;)o[g][1].type==="strikethroughSequenceTemporary"&&(o[g][1].type="data");return o}function d(o,m,g){const p=this.previous,b=this.events;let y=0;return v;function v(N){return p===126&&b[b.length-1][1].type!=="characterEscape"?g(N):(o.enter("strikethroughSequenceTemporary"),S(N))}function S(N){const D=Fi(p);if(N===126)return y>1?g(N):(o.consume(N),y++,S);if(y<2&&!r)return g(N);const z=o.exit("strikethroughSequenceTemporary"),_=Fi(N);return z._open=!_||_===2&&!!D,z._close=!D||D===2&&!!_,m(N)}}}class OC{constructor(){this.map=[]}add(i,r,s){MC(this,i,r,s)}consume(i){if(this.map.sort(function(d,o){return d[0]-o[0]}),this.map.length===0)return;let r=this.map.length;const s=[];for(;r>0;)r-=1,s.push(i.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),i.length=this.map[r][0];s.push(i.slice()),i.length=0;let f=s.pop();for(;f;){for(const d of f)i.push(d);f=s.pop()}this.map.length=0}}function MC(n,i,r,s){let f=0;if(!(r===0&&s.length===0)){for(;f<n.map.length;){if(n.map[f][0]===i){n.map[f][1]+=r,n.map[f][2].push(...s);return}f+=1}n.map.push([i,r,s])}}function LC(n,i){let r=!1;const s=[];for(;i<n.length;){const f=n[i];if(r){if(f[0]==="enter")f[1].type==="tableContent"&&s.push(n[i+1][1].type==="tableDelimiterMarker"?"left":"none");else if(f[1].type==="tableContent"){if(n[i-1][1].type==="tableDelimiterMarker"){const d=s.length-1;s[d]=s[d]==="left"?"center":"right"}}else if(f[1].type==="tableDelimiterRow")break}else f[0]==="enter"&&f[1].type==="tableDelimiterRow"&&(r=!0);i+=1}return s}function UC(){return{flow:{null:{name:"table",tokenize:BC,resolveAll:qC}}}}function BC(n,i,r){const s=this;let f=0,d=0,o;return m;function m(A){let G=s.events.length-1;for(;G>-1;){const ae=s.events[G][1].type;if(ae==="lineEnding"||ae==="linePrefix")G--;else break}const V=G>-1?s.events[G][1].type:null,se=V==="tableHead"||V==="tableRow"?R:g;return se===R&&s.parser.lazy[s.now().line]?r(A):se(A)}function g(A){return n.enter("tableHead"),n.enter("tableRow"),p(A)}function p(A){return A===124||(o=!0,d+=1),b(A)}function b(A){return A===null?r(A):Me(A)?d>1?(d=0,s.interrupt=!0,n.exit("tableRow"),n.enter("lineEnding"),n.consume(A),n.exit("lineEnding"),S):r(A):Ze(A)?tt(n,b,"whitespace")(A):(d+=1,o&&(o=!1,f+=1),A===124?(n.enter("tableCellDivider"),n.consume(A),n.exit("tableCellDivider"),o=!0,b):(n.enter("data"),y(A)))}function y(A){return A===null||A===124||xt(A)?(n.exit("data"),b(A)):(n.consume(A),A===92?v:y)}function v(A){return A===92||A===124?(n.consume(A),y):y(A)}function S(A){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(A):(n.enter("tableDelimiterRow"),o=!1,Ze(A)?tt(n,N,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):N(A))}function N(A){return A===45||A===58?z(A):A===124?(o=!0,n.enter("tableCellDivider"),n.consume(A),n.exit("tableCellDivider"),D):ce(A)}function D(A){return Ze(A)?tt(n,z,"whitespace")(A):z(A)}function z(A){return A===58?(d+=1,o=!0,n.enter("tableDelimiterMarker"),n.consume(A),n.exit("tableDelimiterMarker"),_):A===45?(d+=1,_(A)):A===null||Me(A)?oe(A):ce(A)}function _(A){return A===45?(n.enter("tableDelimiterFiller"),M(A)):ce(A)}function M(A){return A===45?(n.consume(A),M):A===58?(o=!0,n.exit("tableDelimiterFiller"),n.enter("tableDelimiterMarker"),n.consume(A),n.exit("tableDelimiterMarker"),H):(n.exit("tableDelimiterFiller"),H(A))}function H(A){return Ze(A)?tt(n,oe,"whitespace")(A):oe(A)}function oe(A){return A===124?N(A):A===null||Me(A)?!o||f!==d?ce(A):(n.exit("tableDelimiterRow"),n.exit("tableHead"),i(A)):ce(A)}function ce(A){return r(A)}function R(A){return n.enter("tableRow"),W(A)}function W(A){return A===124?(n.enter("tableCellDivider"),n.consume(A),n.exit("tableCellDivider"),W):A===null||Me(A)?(n.exit("tableRow"),i(A)):Ze(A)?tt(n,W,"whitespace")(A):(n.enter("data"),ie(A))}function ie(A){return A===null||A===124||xt(A)?(n.exit("data"),W(A)):(n.consume(A),A===92?F:ie)}function F(A){return A===92||A===124?(n.consume(A),ie):ie(A)}}function qC(n,i){let r=-1,s=!0,f=0,d=[0,0,0,0],o=[0,0,0,0],m=!1,g=0,p,b,y;const v=new OC;for(;++r<n.length;){const S=n[r],N=S[1];S[0]==="enter"?N.type==="tableHead"?(m=!1,g!==0&&(wg(v,i,g,p,b),b=void 0,g=0),p={type:"table",start:Object.assign({},N.start),end:Object.assign({},N.end)},v.add(r,0,[["enter",p,i]])):N.type==="tableRow"||N.type==="tableDelimiterRow"?(s=!0,y=void 0,d=[0,0,0,0],o=[0,r+1,0,0],m&&(m=!1,b={type:"tableBody",start:Object.assign({},N.start),end:Object.assign({},N.end)},v.add(r,0,[["enter",b,i]])),f=N.type==="tableDelimiterRow"?2:b?3:1):f&&(N.type==="data"||N.type==="tableDelimiterMarker"||N.type==="tableDelimiterFiller")?(s=!1,o[2]===0&&(d[1]!==0&&(o[0]=o[1],y=Cs(v,i,d,f,void 0,y),d=[0,0,0,0]),o[2]=r)):N.type==="tableCellDivider"&&(s?s=!1:(d[1]!==0&&(o[0]=o[1],y=Cs(v,i,d,f,void 0,y)),d=o,o=[d[1],r,0,0])):N.type==="tableHead"?(m=!0,g=r):N.type==="tableRow"||N.type==="tableDelimiterRow"?(g=r,d[1]!==0?(o[0]=o[1],y=Cs(v,i,d,f,r,y)):o[1]!==0&&(y=Cs(v,i,o,f,r,y)),f=0):f&&(N.type==="data"||N.type==="tableDelimiterMarker"||N.type==="tableDelimiterFiller")&&(o[3]=r)}for(g!==0&&wg(v,i,g,p,b),v.consume(i.events),r=-1;++r<i.events.length;){const S=i.events[r];S[0]==="enter"&&S[1].type==="table"&&(S[1]._align=LC(i.events,r))}return n}function Cs(n,i,r,s,f,d){const o=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",m="tableContent";r[0]!==0&&(d.end=Object.assign({},Ki(i.events,r[0])),n.add(r[0],0,[["exit",d,i]]));const g=Ki(i.events,r[1]);if(d={type:o,start:Object.assign({},g),end:Object.assign({},g)},n.add(r[1],0,[["enter",d,i]]),r[2]!==0){const p=Ki(i.events,r[2]),b=Ki(i.events,r[3]),y={type:m,start:Object.assign({},p),end:Object.assign({},b)};if(n.add(r[2],0,[["enter",y,i]]),s!==2){const v=i.events[r[2]],S=i.events[r[3]];if(v[1].end=Object.assign({},S[1].end),v[1].type="chunkText",v[1].contentType="text",r[3]>r[2]+1){const N=r[2]+1,D=r[3]-r[2]-1;n.add(N,D,[])}}n.add(r[3]+1,0,[["exit",y,i]])}return f!==void 0&&(d.end=Object.assign({},Ki(i.events,f)),n.add(f,0,[["exit",d,i]]),d=void 0),d}function wg(n,i,r,s,f){const d=[],o=Ki(i.events,r);f&&(f.end=Object.assign({},o),d.push(["exit",f,i])),s.end=Object.assign({},o),d.push(["exit",s,i]),n.add(r+1,0,d)}function Ki(n,i){const r=n[i],s=r[0]==="enter"?"start":"end";return r[1][s]}const HC={name:"tasklistCheck",tokenize:YC};function IC(){return{text:{91:HC}}}function YC(n,i,r){const s=this;return f;function f(g){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?r(g):(n.enter("taskListCheck"),n.enter("taskListCheckMarker"),n.consume(g),n.exit("taskListCheckMarker"),d)}function d(g){return xt(g)?(n.enter("taskListCheckValueUnchecked"),n.consume(g),n.exit("taskListCheckValueUnchecked"),o):g===88||g===120?(n.enter("taskListCheckValueChecked"),n.consume(g),n.exit("taskListCheckValueChecked"),o):r(g)}function o(g){return g===93?(n.enter("taskListCheckMarker"),n.consume(g),n.exit("taskListCheckMarker"),n.exit("taskListCheck"),m):r(g)}function m(g){return Me(g)?i(g):Ze(g)?n.check({tokenize:GC},i,r)(g):r(g)}}function GC(n,i,r){return tt(n,s,"whitespace");function s(f){return f===null?r(f):i(f)}}function VC(n){return ly([mC(),CC(),DC(n),UC(),IC()])}const QC={};function XC(n){const i=this,r=n||QC,s=i.data(),f=s.micromarkExtensions||(s.micromarkExtensions=[]),d=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),o=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);f.push(VC(r)),d.push(fC()),o.push(dC(r))}function Qc(n){const i=n.trim();if(!(!i||/[\u0000-\u0020\u007f]/.test(i)))try{const r=new URL(i);if(r.protocol==="https:"||r.protocol==="http:"||r.protocol==="mailto:")return i}catch{}}function Xc(n){return!!n&&!/[\u0000-\u001f\u007f]/.test(n)&&!/^[a-z][a-z\d+.-]*:/i.test(n)&&!n.startsWith("//")}function Cg(n){if(!Xc(n))return;const i=n.split(/[?#]/,1)[0];if(i)try{const r=decodeURIComponent(i);return Xc(r)?r:void 0}catch{return}}async function ZC(n){if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(n);return}const i=document.activeElement,r=document.createElement("textarea");r.value=n,r.setAttribute("aria-label","复制内容"),r.style.cssText="position:fixed;left:-10000px;top:0",document.body.append(r);try{if(r.select(),!document.execCommand("copy"))throw new Error("复制不可用")}finally{r.remove(),i instanceof HTMLElement&&i.focus({preventScroll:!0})}}function Vs({text:n,label:i="复制"}){const[r,s]=w.useState("idle"),f=w.useRef(!0),d=w.useRef(void 0);w.useEffect(()=>(f.current=!0,()=>{f.current=!1,clearTimeout(d.current)}),[]);const o=async()=>{clearTimeout(d.current);try{await ZC(n),f.current&&s("copied")}catch{f.current&&s("error")}f.current&&(d.current=setTimeout(()=>s("idle"),2500))};return u.jsx("button",{className:"message-copy",onClick:()=>{o()},"aria-label":i,title:i,children:r==="copied"?"已复制":r==="error"?"复制失败":i})}function Zc(n){return typeof n=="string"||typeof n=="number"?String(n):Array.isArray(n)?n.map(Zc).join(""):w.isValidElement(n)?Zc(n.props.children):""}function KC({children:n}){const i=w.Children.toArray(n).find(d=>w.isValidElement(d)),s=(w.isValidElement(i)?i.props.className??"":"").match(/(?:^|\s)language-([\w+-]+)/)?.[1]??"代码",f=Zc(n).replace(/\n$/,"");return u.jsxs("div",{className:"message-code-block",children:[u.jsxs("div",{className:"message-code-heading",children:[u.jsx("span",{children:s}),u.jsx(Vs,{text:f,label:"复制代码"})]}),u.jsx("pre",{tabIndex:0,children:n})]})}function FC(n){return{a:({href:i,children:r,title:s})=>{const f=Qc(i??"");if(f)return u.jsx("a",{href:f,title:s,target:"_blank",rel:"noopener noreferrer",referrerPolicy:"no-referrer",children:r});const d=i?Cg(i):void 0;return d?u.jsxs("span",{className:"message-file-reference",title:d,children:[n?u.jsx("button",{className:"message-file-open",onClick:()=>n(d),children:r}):r,u.jsx(Vs,{text:d,label:"复制路径"})]}):u.jsx("span",{children:r})},img:({src:i,alt:r})=>{const s=Qc(typeof i=="string"?i:""),f=typeof i=="string"?Cg(i):void 0;return s?u.jsxs("a",{className:"message-image-reference",href:s,target:"_blank",rel:"noopener noreferrer",referrerPolicy:"no-referrer",children:[r||"图片",u.jsx("span",{children:"打开图片 ↗"})]}):f&&n?u.jsxs("button",{className:"message-image-reference",title:f,onClick:()=>n(f),children:[r||"图片",u.jsx("span",{children:"查看图片"})]}):u.jsxs("span",{className:"message-image-reference",children:[r||"图片",u.jsx("span",{children:"图片路径不可直接访问"})]})},pre:({children:i})=>u.jsx(KC,{children:i}),table:({children:i})=>u.jsx("div",{className:"message-table-scroll",role:"region","aria-label":"表格",tabIndex:0,children:u.jsx("table",{children:i})})}}const $C=w.memo(function({text:i,reasoning:r="",streaming:s=!1,onOpenFile:f}){const d=w.useMemo(()=>FC(f),[f]);return u.jsxs("div",{className:"message-content",children:[r?u.jsxs("details",{className:"message-reasoning",children:[u.jsx("summary",{children:s&&!i?"思考中…":"思考过程"}),u.jsx("pre",{children:r})]}):null,s?u.jsxs("div",{className:"message-streaming",children:[i||(r?"":"正在思考…"),u.jsx("span",{className:"cursor","aria-hidden":"true",children:"▍"})]}):i?u.jsx(Dk,{remarkPlugins:[XC],skipHtml:!0,urlTransform:o=>Qc(o)??(Xc(o)?o:""),components:d,children:i}):null,!s&&i?u.jsx("div",{className:"message-actions",children:u.jsx(Vs,{text:i,label:"复制回复"})}):null]})});function JC(n){const i=n.args??{},r=n.summary||[i.description,i.command,i.file_path,i.path,i.query,i.url].find(s=>typeof s=="string"&&s.trim());return typeof r=="string"?r.replace(/\s+/g," ").slice(0,180):""}const PC=w.memo(function({item:i,running:r}){const s=JC(i),f=i.done?i.error?"失败":"已完成":r?"执行中":"未完成";return u.jsxs("details",{className:`message-tool-card${i.error?" message-tool-error":""}`,children:[u.jsxs("summary",{children:[u.jsx("span",{className:"message-tool-indicator","aria-hidden":"true",children:i.done?i.error?"!":"✓":"·"}),u.jsx("span",{className:"message-tool-name",children:i.name}),u.jsx("span",{className:"message-tool-summary",children:s}),u.jsx("span",{className:"message-tool-status",children:f})]}),i.args&&Object.keys(i.args).length?u.jsxs("div",{className:"message-tool-section",children:[u.jsx("strong",{children:"参数"}),u.jsx("pre",{tabIndex:0,children:JSON.stringify(i.args,null,2)})]}):null,u.jsxs("div",{className:"message-tool-section",children:[u.jsxs("div",{className:"message-tool-result-heading",children:[u.jsx("strong",{children:"结果"}),i.result?u.jsx(Vs,{text:i.result,label:"复制结果"}):null]}),u.jsx("pre",{tabIndex:0,children:i.result??(i.done?"工具没有返回文本内容。":r?"等待工具返回结果…":"这次工具调用没有保存结果。")})]})]})});function WC(n){return{running:"运行中",completed:"已完成",error:"失败",recorded:"历史记录"}[n]??n}function Eg(n){return n.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"")}function As(){return{items:[],run:"idle",seq:0,liveByAgent:{}}}function Kr(n){return n.agentId??""}function Es(n,i,r=!1){const s=i.goalId;if(n.goalId!==s&&!(r&&n.goalId===void 0&&s!==void 0))return!0;const f=i.revision;return n.goalRevision!==void 0&&(f===void 0||f<n.goalRevision)}function eE(n){switch(n){case"aborted_streaming":case"aborted_tools":return"idle";case"prompt_too_long":case"model_error":case"image_error":case"replay_incomplete":return"error";default:return"completed"}}function tE(n){if(!n||typeof n!="object")return null;const i=n;if(i.method==="agent/streamEvent"&&i.params&&typeof i.params=="object"){const r=i.params;if(r.event&&typeof r.event=="object")return{event:r.event,sessionId:typeof r.sessionId=="string"?r.sessionId:void 0}}return typeof i.type=="string"?{event:i}:null}function Os(n,i){const r=tE(i);if(!r)return n;const{event:s,sessionId:f}=r,d=s.type;let o=n;f&&f!==o.sessionId&&(o={...o,sessionId:f});const m=g=>{const p=o.seq+1;return[`${g}-${p}`,{...o,seq:p}]};switch(d){case"stream_request_start":{const g=Kr(s),[p,b]=m("a"),y={kind:"assistant",id:p,text:"",reasoning:"",done:!1,agentId:s.agentId,...typeof s.messageId=="string"?{messageId:s.messageId}:{}};return{...b,items:[...b.items,y],liveByAgent:{...b.liveByAgent,[g]:p},run:"running"}}case"text_delta":{const g=s.text??"",p=Kr(s),b=o.liveByAgent[p];if(b&&o.items.find(D=>D.id===b&&D.kind==="assistant"))return{...o,run:"running",items:o.items.map(D=>D.id===b&&D.kind==="assistant"?{...D,text:D.text+g}:D)};const[v,S]=m("a"),N={kind:"assistant",id:v,text:g,reasoning:"",done:!1,agentId:s.agentId};return{...S,items:[...S.items,N],liveByAgent:{...S.liveByAgent,[p]:v},run:"running"}}case"thinking_delta":{const g=s.text??"",p=Kr(s),b=o.liveByAgent[p];if(b&&o.items.some(N=>N.id===b&&N.kind==="assistant"))return{...o,run:"running",items:o.items.map(N=>N.id===b&&N.kind==="assistant"?{...N,reasoning:N.reasoning+g}:N)};const[y,v]=m("a"),S={kind:"assistant",id:y,text:"",reasoning:g,done:!1,agentId:s.agentId};return{...v,items:[...v.items,S],liveByAgent:{...v.liveByAgent,[p]:y},run:"running"}}case"tool_use_start":{const g=s.toolCall;if(!g||o.items.some(v=>v.kind==="tool"&&v.id===g.id))return o;const p=o.orphanResults?.[g.id],b={kind:"tool",id:g.id,name:g.toolName,args:g.args,summary:g.summary,done:!!p,result:p?.result,error:p?.error,agentId:s.agentId};let y=o.orphanResults;if(p){const{[g.id]:v,...S}=o.orphanResults;y=Object.keys(S).length>0?S:void 0}return{...o,run:"running",items:[...o.items,b],orphanResults:y}}case"tool_use_args_delta":{const g=s.toolCallId,p=s.args;return!g||!p?o:{...o,items:o.items.map(b=>b.kind==="tool"&&b.id===g?{...b,args:{...b.args??{},...p}}:b)}}case"tool_result":{const g=s.result;return g?o.items.some(b=>b.kind==="tool"&&b.id===g.id)?{...o,items:o.items.map(b=>b.kind==="tool"&&b.id===g.id?{...b,done:!0,result:Eg(g.result??g.error??""),error:!!(g.isError||g.error)}:b)}:{...o,orphanResults:{...o.orphanResults??{},[g.id]:{result:g.result??g.error??"",error:!!(g.isError||g.error)}}}:o}case"room_tool_result":{const g=s.summary??"",p=Eg(g),b=!!s.isError;let y=-1;for(let N=o.items.length-1;N>=0;N--)if(o.items[N].kind==="tool"&&!o.items[N].done){y=N;break}if(y===-1)return o;const v=o.items.slice(),S=v[y];return v[y]={...S,done:!0,result:p,summary:p||S.summary,error:b},{...o,items:v}}case"tool_summary":{const g=s.summary??"",p=Array.isArray(s.toolCallIds)?s.toolCallIds.filter(D=>typeof D=="string"):[],y=p.length>0?p[p.length-1]:void 0,v=s.agentId;if(y){let D=!1;const z=o.items.map(_=>_.kind!=="tool"||_.id!==y||_.agentId!==v?_:(D=!0,{..._,summary:g}));return D?{...o,items:z}:o}if(v){let D=-1;for(let _=o.items.length-1;_>=0;_--){const M=o.items[_];if(M.kind==="tool"&&M.agentId===v){D=_;break}}if(D===-1)return o;const z=o.items.slice();return z[D]={...z[D],summary:g},{...o,items:z}}let S=-1;for(let D=o.items.length-1;D>=0;D--){const z=o.items[D];if(z.kind==="tool"&&z.agentId===void 0){S=D;break}}if(S===-1)return o;const N=o.items.slice();return N[S]={...N[S],summary:g},{...o,items:N}}case"tombstone":{if(typeof s.messageId!="string")return o;const g=new Set(o.items.filter(p=>p.kind==="assistant"&&p.messageId===s.messageId||p.kind==="tool"&&p.id===s.messageId).map(p=>p.id));return g.size?{...o,items:o.items.filter(p=>!g.has(p.id)),liveByAgent:Object.fromEntries(Object.entries(o.liveByAgent).filter(([,p])=>!g.has(p)))}:o}case"assistant_message":{const g=Kr(s);if(!(g in o.liveByAgent))return o;const{[g]:p,...b}=o.liveByAgent,y=o.items.map(v=>v.kind==="assistant"&&!v.done&&(v.agentId??"")===g?{...v,done:!0}:v);return{...o,liveByAgent:b,items:y}}case"turn_complete":{const g=s.reason??"completed",p=Kr(s),{[p]:b,...y}=o.liveByAgent,v=o.items.map(S=>S.kind==="assistant"&&!S.done&&(S.agentId??"")===p?{...S,done:!0}:S);return s.agentId?{...o,liveByAgent:y,items:v}:{...o,liveByAgent:y,items:v,run:eE(g)}}case"goal_set":{const g=s.objective??"",p=!!s.paused;return o.goal&&o.goalId===s.goalId&&Es(o,s)?o:{...o,goal:g?`◎ ${g}${p?" (已暂停)":""}`:"◎ 目标",goalId:s.goalId,goalPaused:p,goalRevision:s.revision}}case"goal_updated":{if(o.goal&&Es(o,s,!0))return o;const g=s.goalId,p=s.objective??"",b=!!s.paused;return{...o,goal:p?`◎ ${p}${b?" (已暂停)":""}`:o.goal,goalId:g??o.goalId,goalPaused:b,goalRevision:s.revision??o.goalRevision}}case"goal_cleared":return o.goal&&Es(o,s)?o:{...o,goal:void 0,goalId:void 0,goalPaused:void 0,goalRevision:void 0};case"goal_progress":{if(o.goal&&Es(o,s))return o;const g=s.status??"";if(g==="met"||g==="exhausted")return{...o,goal:void 0,goalId:void 0,goalPaused:void 0,goalRevision:void 0};const p=s.round,b=p?`目标 · 第 ${p} 轮 (${g})`:`目标 (${g})`;return{...o,goal:b,goalRevision:s.revision??o.goalRevision}}case"task_update":{const g=s.agentId;if(!g)return o;const p=s.tasks??[],b=p.filter(N=>N.status==="completed").length,y=`任务 ${b}/${p.length}`,v=o.items.findIndex(N=>N.kind==="subagent"&&N.agentId===g),S={kind:"subagent",id:`sub-${g}`,agentId:g,label:y,status:p.length>0&&b===p.length?"completed":"running"};if(v>=0){const N=o.items.slice();return N[v]=S,{...o,items:N}}return{...o,items:[...o.items,S]}}case"agent_start":{const g=s.agentId;if(!g)return o;const p={kind:"subagent",id:`sub-${g}`,agentId:g,label:s.name||s.description||"子代理",status:s.status==="recorded"?"recorded":"running"};return o.items.some(b=>b.kind==="subagent"&&b.agentId===g)?o:{...o,items:[...o.items,p]}}case"agent_end":{const g=s.agentId;return{...o,items:o.items.map(p=>p.kind==="subagent"&&p.agentId===g?{...p,status:s.error?"error":"completed"}:p)}}case"error":{const[g,p]=m("err");return{...p,run:"error",liveByAgent:{},items:[...p.items,{kind:"system_error",id:g,text:s.error||"运行出错"}]}}case"session_title":return{...o,title:s.title};case"session_user_message":case"user_message":{const g=typeof s.clientMessageId=="string"?s.clientMessageId:void 0,p=Array.isArray(s.attachments)?s.attachments.map(v=>v).filter(v=>!!v&&typeof v.name=="string"&&typeof v.size=="number"&&Number.isFinite(v.size)&&v.size>=0).map(v=>({name:v.name,size:v.size,...typeof v.mime=="string"?{mime:v.mime}:{},...typeof v.path=="string"?{path:v.path}:{}})):void 0;if(g&&o.items.some(v=>v.kind==="user"&&v.clientMessageId===g))return p?.length?{...o,items:o.items.map(v=>v.kind==="user"&&v.clientMessageId===g?{...v,attachments:p.map((S,N)=>{const D=v.attachments?.[N];return D?.name===S.name?{...D,...S}:S})}:v)}:o;const[b,y]=m("u");return{...y,items:[...y.items,{kind:"user",id:b,text:s.text??"",...p?.length?{attachments:p}:{},...g?{clientMessageId:g}:{}}]}}case"assistant_text":{const[g,p]=m("a");return{...p,run:"running",items:[...p.items,{kind:"assistant",id:g,text:s.text??"",reasoning:"",done:!0,agentId:s.agentId}]}}default:return o}}function nE(n,i,r,s){const f=`u-${n.seq+1}`;return{...n,seq:n.seq+1,items:[...n.items,{kind:"user",id:f,text:i,...r?.length?{attachments:r}:{},...s?{clientMessageId:s}:{}}]}}function On(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function yt(n){return typeof n=="string"?n:""}function Ms(n){return Array.isArray(n)?n.map(On).filter(i=>i!==void 0):[]}function Kc(n){return typeof n=="string"?n:Ms(n).filter(i=>i.type==="text").map(i=>yt(i.text)).join("")}function Ns(n){return n.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Rc(n){const i=n.replace(/\\/g,"/").split("/").filter(Boolean).pop()||"附件";return n.includes(".code-shell/attachments/")?i.replace(/^[a-f0-9]{16}-/,""):i}function Ng(n){const i=typeof n=="number"?n:Number(n);return Number.isSafeInteger(i)&&i>=0?i:0}function lE(n){const i=[],r=[];let s=Kc(n.content);s=s.replace(/<attached-file\s+path="([^"]*)">\s*([\s\S]*?)<\/attached-file>/g,(o,m,g)=>{if(!/^absolutePath:\s*.+$/m.test(g)||!/^origin:\s*.+$/m.test(g))return o;const p=g.match(/^mime:\s*(.+)$/m)?.[1]?.trim();return i.push({name:Rc(Ns(m)),path:Ns(m),size:Ng(g.match(/^size:\s*(\d+)\s*$/m)?.[1]),...p?{mime:p}:{}}),""}),s=s.replace(/<attached-directory\s+path="([^"]*)"[^>]*>[\s\S]*?<\/attached-directory>/g,(o,m)=>(i.push({name:`${Rc(Ns(m))}/`,path:Ns(m),size:0}),"")),s=s.replace(/<attached-image-paths>\s*([\s\S]*?)<\/attached-image-paths>\s*(?:\(上面附带的图片在工作区的真实路径[^\n]*\))?/g,(o,m)=>(r.push(...m.split(`
49
49
  `).map(g=>g.trim()).filter(Boolean)),""));const f=Ms(n.content).filter(o=>o.type==="image");for(let o=0;o<Math.max(f.length,r.length);o++){const m=On(f[o]?.source),g=yt(m?.data).replace(/\s/g,"");i.push({name:r[o]?Rc(r[o]):`图片 ${o+1}`,...r[o]?{path:r[o]}:{},size:g?Math.max(0,Math.floor(g.length*3/4)-(g.match(/=+$/)?.[0].length??0)):0,...typeof m?.media_type=="string"?{mime:m.media_type}:{}})}const d=Array.isArray(n.attachments)?n.attachments.flatMap(o=>{const m=On(o),g=yt(m?.name)||yt(m?.originalName);return g?[{name:g,size:Ng(m?.size),...typeof m?.mime=="string"?{mime:m.mime}:{},...typeof m?.path=="string"?{path:m.path}:{}}]:[]}):[];return{text:typeof n.displayText=="string"?n.displayText:s.trim(),attachments:d.length?d:i}}function Tg(n){return On(n.data)??On(n.message)??n}function iE(n){const i=[],r=new Set,s=new Set,f=new Map;for(const m of n){const g=On(m);if(!g)continue;const p=Tg(g);g.type==="tool_use"&&yt(p.toolCallId)&&f.set(yt(p.toolCallId),{name:yt(p.toolName)||"工具",args:On(p.args)??{}});for(const b of Ms(p.content))b.type==="tool_use"&&yt(b.id)&&f.set(yt(b.id),{name:yt(b.name)||"工具",args:On(b.input)??{}})}const d=(m,g,p,b)=>{m&&(s.has(m)?i.push({type:"tool_use_args_delta",toolCallId:m,args:p,...b?{agentId:b}:{}}):(s.add(m),i.push({type:"tool_use_start",toolCall:{id:m,toolName:g||"工具",args:p},...b?{agentId:b}:{}})))},o=(m,g,p)=>{if(!m)return;const b=f.get(m);s.has(m)||d(m,b?.name||yt(g.toolName)||"工具",b?.args??{},p);const y=typeof g.result=="string"?g.result:Kc(g.content??g.contentBlocks),v=yt(g.error);i.push({type:"tool_result",result:{id:m,result:y||v,...v?{error:v}:{},isError:g.isError===!0||g.is_error===!0||!!v},...p?{agentId:p}:{}})};for(const m of n){const g=On(m);if(!g)continue;const p=yt(g.id);if(p&&r.has(p))continue;p&&r.add(p);const b=Tg(g),y=yt(b.agentId)||void 0;switch(typeof g.type=="string"?g.type:typeof b.role=="string"?"message":""){case"message":{const S=Ms(b.content);if(b.role==="user"){if(b.injected===!0||b.authority==="agent"||b.authority==="system"||b.authority==="policy")break;const N=lE(b);if(N.text.startsWith("<system-reminder>"))break;(N.text||N.attachments.length)&&i.push({type:"user_message",...N,...typeof b.clientMessageId=="string"?{clientMessageId:b.clientMessageId}:{}});for(const D of S)D.type==="tool_result"&&o(yt(D.tool_use_id),D,y)}else if(b.role==="assistant"){const N=Kc(b.content),D=S.filter(z=>z.type==="reasoning").map(z=>yt(z.reasoningContent)||yt(z.text)).join("");if(N||D){const z=y?{agentId:y}:{};i.push({type:"stream_request_start",...z}),D&&i.push({type:"thinking_delta",text:D,...z}),N&&i.push({type:"text_delta",text:N,...z}),i.push({type:"assistant_message",...z})}for(const z of S)z.type==="tool_use"&&d(yt(z.id),yt(z.name),On(z.input)??{},y)}else b.role==="tool"&&o(yt(b.tool_call_id),b,y);break}case"tool_use":d(yt(b.toolCallId),yt(b.toolName),On(b.args)??{},y);break;case"tool_result":o(yt(b.toolCallId),b,y);break;case"subagent":y&&i.push({type:"agent_start",agentId:y,name:yt(b.name),description:yt(b.description),status:"recorded"});break;case"error":yt(b.error)&&i.push({type:"error",error:b.error});break;case"turn_stopped":i.push({type:"turn_complete",reason:"aborted_tools"});break;case"session_meta":yt(b.sessionId)&&i.push({type:"session_started",sessionId:b.sessionId});break}}return i}function rE(n){let i=As();for(const r of iE(n))i=Os(i,r);return{...i,run:i.run==="error"?"error":"idle",liveByAgent:{}}}function aE(n){const i=new URLSearchParams(n).get("session");return i&&/^[a-zA-Z0-9_-]{1,128}$/.test(i)?i:null}function Zy(n,i){return!i||!n.hubEpoch||n.hubSequence===void 0?!0:n.hubEpoch===i.epoch&&n.hubSequence>i.sequence}function Ag(n,i=[]){let r=rE(n.transcript);for(const f of n.liveStream?.events??[])r=Os(r,f.event);n.running?r={...r,run:"running"}:n.running===!1&&(r.run==="running"||r.run==="waiting")&&(r={...r,run:"idle"});let s=n.streamCursor;for(const f of i)Zy(f,s)&&(r=Os(r,f.event),f.hubEpoch&&f.hubSequence!==void 0&&(s={epoch:f.hubEpoch,sequence:f.hubSequence}));return{chat:r,cursor:s,truncated:n.liveStream?.truncated??!1}}function Ky(n,i){if(n?.title)return n.title;const r=n?.items.find(s=>s.kind==="user");if(r&&r.kind==="user"&&r.text.trim()){const s=r.text.trim().split(`
50
50
  `)[0];return s.length>32?`${s.slice(0,32)}…`:s}return r?.kind==="user"&&r.attachments?.length?`附件:${r.attachments[0].name}`:i.slice(0,8)}function sE(n,i){if(i.workspaceKey!==n.workspaceKey||i.sessionId!==n.activeId)throw new Error("当前工作区或对话已经变化,请重新打开面板后发送。");if(n.connection!=="open"||n.loading)throw new Error("工作台尚未连接,请连接后重新发送面板任务。");if(n.readOnly)throw new Error("当前对话为只读,无法发送面板任务。");if(n.running||n.chat.run==="running"||n.chat.run==="waiting"||n.approvals.some(r=>!r.sessionId||r.sessionId===i.sessionId))throw new Error("当前对话仍在处理任务,请完成后再发送面板任务。");if(n.uncertain||n.uploading||n.uploadBusy)throw new Error("当前消息或附件仍在发送,请等待结果后重试。");if(n.draft.length>0||n.files.length>0)throw new Error("当前对话还有草稿或附件,请先处理它们,再发送面板任务。");if(!i.prompt.trim()||i.prompt.length>2e4)throw new Error("面板任务内容无效。");if(n.setDraft(i.prompt),!n.send())throw n.setDraft(""),new Error("当前对话暂时无法接收任务,请稍后重新发送。");return{accepted:!0}}function uE({controller:n,onBackToProjects:i,projectName:r}){const{connection:s,sessions:f,activeId:d,chat:o,draft:m,files:g,uploading:p,workerNote:b,replayNote:y,error:v,workspaceCwd:S,workspaceName:N,configuration:D,configurationVersion:z,sessionsVersion:_,localDrafts:M,running:H,title:oe,approvalCount:ce,onAuthLost:R,refreshSessions:W,refreshConfiguration:ie,session:F}=n,A=n.workspaceApi,G=n.host==="desktop"?"桌面":"服务端",[V,se]=w.useState(!1),ae=w.useRef(null),P=w.useRef(null),[E,U]=w.useState("chat"),[te,he]=w.useState(),[k,T]=w.useState(),[K,C]=w.useState(0),[re,ve]=w.useState(!1),[Q,pe]=w.useState(null),[je,Y]=w.useState("overview"),[xe,J]=w.useState(()=>window.matchMedia("(max-width: 760px)").matches),[ye,Ae]=w.useState(()=>!window.matchMedia("(max-width: 760px)").matches),we=w.useRef(null),Ye=w.useRef(null),nt=w.useRef(!1),jt=w.useRef(null),Yt=w.useRef(null),at=w.useRef(!0);w.useEffect(()=>{he(void 0),U(q=>q==="panel"?"panels":q)},[n.workspaceKey]),w.useEffect(()=>{xe&&!ye&&nt.current&&!V&&Ye.current?.focus(),nt.current=ye},[xe,ye,V]),w.useEffect(()=>{const q=window.matchMedia("(max-width: 760px)"),ze=()=>{J(q.matches),Ae(!q.matches)};return q.addEventListener("change",ze),()=>q.removeEventListener("change",ze)},[]),w.useEffect(()=>{if(!xe||!ye)return;const q=we.current;q?.querySelector("button")?.focus();const ze=St=>{if(!document.querySelector("dialog[open]")){if(St.key==="Escape"&&!St.isComposing)St.preventDefault(),Ae(!1),Ye.current?.focus();else if(St.key==="Tab"){const de=Array.from(q?.querySelectorAll('button:not(:disabled), select:not(:disabled), input:not(:disabled), textarea:not(:disabled), a[href], summary, [tabindex]:not([tabindex="-1"])')??[]).filter(_e=>_e.getClientRects().length>0),Re=de?.[0],Je=de?.[de.length-1];St.shiftKey&&document.activeElement===Re?(St.preventDefault(),Je?.focus()):!St.shiftKey&&document.activeElement===Je&&(St.preventDefault(),Re?.focus())}}};return document.addEventListener("keydown",ze),()=>document.removeEventListener("keydown",ze)},[xe,ye]),w.useLayoutEffect(()=>{const q=Yt.current;!q||E!=="chat"||(q.style.height="auto",q.style.height=`${Math.min(180,Math.max(64,q.scrollHeight))}px`)},[m,E]),w.useLayoutEffect(()=>{const q=jt.current;q&&at.current&&E==="chat"&&(q.scrollTop=q.scrollHeight)},[o.items,n.approvals.length,E]);const mt=()=>{xe&&(Ae(!1),Ye.current?.focus())},ut=q=>{if(E==="settings"&&je===q){mt();return}ot(()=>{Y(q),U("settings"),mt()})},ot=q=>{re?pe(()=>q):q()},Gt=q=>ot(()=>{T(q),C(ze=>ze+1),U("files"),mt()}),vt=w.useRef(Gt);vt.current=Gt;const qt=w.useCallback(q=>vt.current(q),[]);w.useEffect(()=>{if(!re&&!n.uploadBusy&&!n.hasUnsent)return;const q=ze=>{ze.preventDefault(),ze.returnValue=""};return window.addEventListener("beforeunload",q),()=>window.removeEventListener("beforeunload",q)},[re,n.uploadBusy,n.hasUnsent]);const ne=q=>ot(()=>{U("chat"),mt(),at.current=!0,q()}),me=q=>ne(()=>{n.selectSession(q)}),Te=()=>ne(n.newSession),ge=()=>{at.current=!0,n.send()},ke=n.stop,Ce=n.approvals.filter(q=>!q.sessionId||q.sessionId===d),B=n.approvals.filter(q=>q.sessionId&&q.sessionId!==d),Se=o.items.length===0&&Ce.length===0,Ke=D?.connections.find(q=>q.id===D.defaults.text),lt=s==="open"?"已连接":s==="connecting"?"连接中":"正在重连",Be=E==="chat"?oe:E==="files"?"工作区文件":E==="history"?"历史对话":E==="links"?"Link":E==="panels"||E==="panel"?te&&E==="panel"?te.panel.title["zh-CN"]||te.panel.title.default:"面板":je==="skills"?"Skills":"设置";return u.jsxs("div",{className:`shell${ye?" sidebar-open":""}`,children:[xe&&ye?u.jsx("div",{className:"sidebar-backdrop",onClick:()=>{Ae(!1),Ye.current?.focus()},"aria-hidden":"true"}):null,u.jsxs("aside",{id:"workbench-sidebar",ref:we,className:"rail",hidden:!ye,role:xe?"dialog":void 0,"aria-modal":xe&&ye?!0:void 0,"aria-label":"工作台导航",children:[u.jsxs("div",{className:"rail-head",children:[u.jsx("span",{className:"brand-mark",children:u.jsx(Et,{name:"brand"})}),u.jsx("strong",{children:"CodeShell"}),u.jsx("span",{className:"hub-badge",children:n.host==="desktop"?"Desktop":A?"Hub":"Web"}),u.jsx("button",{className:"icon-button sidebar-close","aria-label":"收起侧栏",onClick:()=>{Ae(!1),Ye.current?.focus()},children:u.jsx(Et,{name:"sidebar"})})]}),u.jsxs("nav",{className:"workbench-nav","aria-label":"主要功能",children:[i?u.jsxs("button",{className:"nav-button",title:r,onClick:()=>{re||n.hasUnsent||n.uploadBusy?pe(()=>i):i()},children:[u.jsx(Et,{name:"folder"}),u.jsx("span",{children:"返回项目列表"})]}):null,u.jsxs("button",{className:"nav-button new-chat-button",onClick:Te,children:[u.jsx(Et,{name:"plus"}),u.jsx("span",{children:"新对话"})]}),u.jsxs("button",{className:`nav-button${E==="chat"?" active":""}`,onClick:()=>{ot(()=>{U("chat"),mt()})},"aria-current":E==="chat"?"page":void 0,children:[u.jsx(Et,{name:"chat"}),u.jsx("span",{children:"对话"})]}),A?u.jsxs(u.Fragment,{children:[u.jsxs("button",{className:`nav-button${E==="history"?" active":""}`,onClick:()=>ot(()=>{U("history"),mt()}),"aria-current":E==="history"?"page":void 0,children:[u.jsx(Et,{name:"history"}),u.jsx("span",{children:"历史对话"})]}),u.jsxs("button",{className:`nav-button${E==="files"?" active":""}`,onClick:()=>Gt(),"aria-current":E==="files"?"page":void 0,children:[u.jsx(Et,{name:"folder"}),u.jsx("span",{children:"文件"})]}),u.jsxs("button",{className:`nav-button${E==="settings"&&je==="skills"?" active":""}`,onClick:()=>ut("skills"),"aria-current":E==="settings"&&je==="skills"?"page":void 0,children:[u.jsx(Et,{name:"skills"}),u.jsx("span",{children:"Skills"})]}),u.jsxs("button",{className:`nav-button${E==="panels"||E==="panel"?" active":""}`,onClick:()=>ot(()=>{U("panels"),mt()}),"aria-current":E==="panels"||E==="panel"?"page":void 0,children:[u.jsx(Et,{name:"panels"}),u.jsx("span",{children:"面板"})]}),u.jsxs("button",{className:`nav-button${E==="links"?" active":""}`,onClick:()=>ot(()=>{U("links"),mt()}),"aria-current":E==="links"?"page":void 0,children:[u.jsx(Et,{name:"links"}),u.jsx("span",{children:"Link"})]}),u.jsxs("button",{className:`nav-button${E==="settings"&&je!=="skills"?" active":""}`,onClick:()=>ut("overview"),"aria-current":E==="settings"&&je!=="skills"?"page":void 0,children:[u.jsx(Et,{name:"settings"}),u.jsx("span",{children:"设置"})]})]}):null]}),u.jsx("div",{className:"rail-section-label",children:"工作区"}),A?u.jsxs("button",{className:"workspace-button",title:S??void 0,onClick:()=>Gt(),children:[u.jsx(Et,{name:"folder"}),u.jsx("span",{children:r??N}),u.jsx(Et,{name:"chevron"})]}):u.jsxs("div",{className:"workspace-button",title:S??void 0,children:[u.jsx(Et,{name:"folder"}),u.jsx("span",{children:r??N})]}),u.jsxs("div",{className:"rail-section-label history-label",children:[u.jsx("span",{children:"最近对话"}),u.jsx("span",{children:f.length})]}),n.renderSidebar?.({guard:ot,conversation:ne}),u.jsxs("ul",{className:"sessions","aria-label":"最近对话",children:[M.map(({sessionId:q,draft:ze})=>u.jsx("li",{children:u.jsxs("button",{className:q===d&&E==="chat"?"session active":"session",onClick:()=>{me(q)},children:[u.jsx("span",{className:"session-title",children:ze.text.trim()||`附件:${ze.files[0]?.name??"新对话"}`}),u.jsx("span",{className:"session-meta",children:"草稿"})]})},`draft-${q}`)),f.map(q=>u.jsx("li",{children:u.jsxs("button",{className:q.sessionId===d&&E==="chat"?"session active":"session",onClick:()=>{me(q.sessionId)},"aria-current":q.sessionId===d&&E==="chat"?"page":void 0,children:[u.jsx("span",{className:"session-title",children:q.sessionId===d?q.customTitle||o.title||q.title||Ky(o,q.sessionId):q.title||q.preview?.trim()||q.sessionId.slice(0,8)}),u.jsxs("span",{className:"session-meta",children:[n.unreadSessionIds?.has(q.sessionId)&&q.sessionId!==d?u.jsxs("span",{className:"session-unread","aria-label":"有新消息",children:["●"," "]}):null,ce(q.sessionId)?`${ce(q.sessionId)} 项待审批`:q.running?"进行中":cE(q.status),n.showTurnCounts!==!1?u.jsxs("span",{children:[" · ",q.turnCount," 轮"]}):null]})]})},q.sessionId)),f.length===0&&M.length===0?u.jsx("li",{className:"empty",children:"开始对话后,记录会保存在这里。"}):null]}),u.jsxs("div",{className:"rail-footer",children:[u.jsxs("div",{className:"host-label",children:[u.jsx("span",{className:`dot ${s}`}),u.jsxs("span",{children:[G,lt]})]}),n.host==="hub"?u.jsxs("button",{className:"account-button",onClick:()=>{mt(),se(!0)},children:[u.jsx("span",{className:"account-avatar",children:(F?.username||"C").slice(0,1).toUpperCase()}),u.jsxs("span",{className:"account-copy",children:[u.jsx("strong",{children:F?.username||"账号"}),u.jsx("span",{children:"设备与退出"})]}),u.jsx(Et,{name:"chevron"})]}):null,n.logout?u.jsxs("button",{className:"account-button",onClick:n.logout,children:[u.jsx("span",{className:"account-avatar",children:(n.accountName||"D").slice(0,1)}),u.jsxs("span",{className:"account-copy",children:[u.jsx("strong",{children:n.accountName||"已配对设备"}),u.jsx("span",{children:"退出此设备"})]})]}):null]})]}),u.jsxs("main",{className:"workbench-main",inert:xe&&ye?!0:void 0,children:[u.jsxs("header",{className:"workbench-topbar",children:[u.jsx("button",{ref:Ye,className:"icon-button","aria-label":ye?"收起侧栏":"展开侧栏","aria-expanded":ye,"aria-controls":"workbench-sidebar",onClick:()=>Ae(q=>!q),children:u.jsx(Et,{name:"sidebar"})}),u.jsx("span",{className:"topbar-title",title:Be,children:Be}),u.jsxs("span",{className:"connection-pill",title:`任务在${G}工作区执行`,children:[u.jsx("span",{className:`dot ${s}`}),u.jsx("span",{children:G})]})]}),b?u.jsx("div",{className:"banner",children:b}):null,y?u.jsx("div",{className:"banner",children:y}):null,v?u.jsxs("div",{className:"banner form-error",role:"alert",children:[v,u.jsx("button",{className:"ghost","aria-label":"关闭错误提示",onClick:n.clearError,children:"×"})]}):null,B.length?u.jsxs("div",{className:"banner",children:["其他会话有待处理审批。",B.map(q=>u.jsxs("button",{className:"ghost",onClick:()=>{me(q.sessionId)},children:["打开 ",q.sessionId.slice(0,8)]},q.id))]}):null,s!=="open"?u.jsxs("div",{className:"banner",children:["连接",s==="connecting"?"中…":"已断开,重连中…"]}):null,E!=="chat"&&Ce.length>0?u.jsxs("div",{className:"banner",children:["当前对话需要你的确认。",u.jsx("button",{className:"ghost",onClick:()=>ot(()=>U("chat")),children:"返回对话"})]}):null,u.jsxs("section",{className:`chat${Se?" chat-empty":""}`,hidden:E!=="chat","aria-label":"对话",children:[u.jsx("div",{className:"messages",ref:jt,onScroll:q=>{const ze=q.currentTarget;at.current=ze.scrollHeight-ze.scrollTop-ze.clientHeight<100},children:u.jsxs("div",{className:"transcript",children:[n.chatControls,n.loading?u.jsx("div",{className:"banner",role:"status",children:"正在恢复会话记录…"}):null,o.goal?u.jsxs("div",{className:"banner goal",children:[u.jsx("span",{children:o.goal}),n.goalActions]}):null,o.items.map(q=>{switch(q.kind){case"user":return u.jsxs("div",{className:"msg user",children:[q.text,q.attachments?.map((ze,St)=>A&&ze.path?u.jsxs("button",{className:"attachment attachment-open",onClick:()=>Gt(ze.path),children:["📎 ",ze.name]},St):u.jsxs("span",{className:"attachment",children:["📎 ",ze.name]},St))]},q.id);case"assistant":return q.done&&!q.text&&!q.reasoning?null:u.jsx("div",{className:"msg assistant",children:u.jsx($C,{text:q.text,reasoning:q.reasoning,streaming:!q.done,onOpenFile:A?qt:void 0})},q.id);case"tool":return u.jsx("div",{className:`msg tool${q.error?" tool-error":""}`,children:u.jsx(PC,{item:q,running:H})},q.id);case"subagent":return u.jsxs("div",{className:"msg info",children:["↳ ",q.label," · ",WC(q.status)]},q.id);case"system_error":return u.jsx("div",{className:"msg error",children:q.text},q.id);default:return null}}),n.approvalContent,Se?u.jsxs("div",{className:"empty-chat",children:[u.jsx("span",{className:"welcome-mark",children:u.jsx(Et,{name:"brand"})}),u.jsx("h1",{children:"今天想完成什么?"}),u.jsx("p",{children:"从一个问题或想法开始,让 CodeShell 帮你一步步完成。"}),u.jsxs("span",{className:"welcome-workspace",children:[u.jsx(Et,{name:"folder"}),r??N]})]}):null]})}),n.readOnlyNote?u.jsx("div",{className:"banner",children:n.readOnlyNote}):null,u.jsxs("div",{className:"composer-wrap",children:[u.jsxs("footer",{className:"composer",children:[g.length||p&&n.host==="hub"?u.jsxs("div",{className:"attachments","aria-live":"polite",children:[g.map(q=>u.jsxs("span",{className:"attachment",children:[u.jsx(Et,{name:"attachment"}),q.name,u.jsx("button",{className:"ghost","aria-label":`移除 ${q.name}`,onClick:()=>{n.removeFile(q.id)},children:"×"})]},q.id)),p&&n.host==="hub"?u.jsx("span",{children:"正在上传…"}):null]}):null,u.jsx("textarea",{ref:Yt,"aria-label":"任务内容",value:m,disabled:n.readOnly,rows:2,placeholder:"描述你的任务,或提出一个问题…",onChange:q=>{n.setDraft(q.target.value)},onKeyDown:q=>{q.key==="Enter"&&!q.shiftKey&&!q.nativeEvent.isComposing&&(q.preventDefault(),ge())}}),u.jsxs("div",{className:"composer-toolbar",children:[A?u.jsxs(u.Fragment,{children:[u.jsx("input",{hidden:!0,multiple:!0,type:"file",accept:n.attachmentAccept,ref:ae,onChange:q=>{const ze=q.currentTarget;Promise.resolve(n.addFiles(ze.files)).finally(()=>{ze.value=""})}}),u.jsx("button",{className:"icon-button attach-button","aria-label":"添加附件",title:"添加附件",disabled:n.uploadBusy||s!=="open"||n.readOnly,onClick:()=>ae.current?.click(),children:u.jsx(Et,{name:"plus"})}),n.cameraAttachments?u.jsxs(u.Fragment,{children:[u.jsx("input",{hidden:!0,type:"file",accept:"image/*",capture:"environment",ref:P,onChange:q=>{const ze=q.currentTarget;Promise.resolve(n.addFiles(ze.files)).finally(()=>{ze.value=""})}}),u.jsx("button",{className:"icon-button attach-button","aria-label":"拍照",title:"拍照",disabled:n.uploadBusy||s!=="open"||n.readOnly,onClick:()=>P.current?.click(),children:u.jsx(Et,{name:"camera"})})]}):null,u.jsxs("button",{className:"model-button",title:"打开模型设置",onClick:()=>ut("models"),children:[u.jsx("span",{children:Ke?.model||"配置模型"}),u.jsx(Et,{name:"chevron"})]})]}):null,u.jsx("span",{className:"composer-run-status",role:"status",children:n.uncertain?"正在核对消息…":p?n.host==="desktop"?"正在发送…":"正在上传附件…":Ce.length?"等待你的确认":H?"正在处理…":""}),H?u.jsx("button",{className:"stop composer-submit","aria-label":"停止",title:"停止",onClick:ke,disabled:s!=="open",children:u.jsx(Et,{name:"stop"})}):u.jsx("button",{className:"send composer-submit","aria-label":"发送",title:"发送",onClick:ge,disabled:s!=="open"||p||n.uncertain||n.readOnly||!m.trim()&&!g.length,children:u.jsx(Et,{name:"send"})})]})]}),u.jsxs("div",{className:"composer-caption",children:[u.jsxs("span",{children:["任务在",G,"工作区执行"]}),u.jsx("span",{children:"Enter 发送 · Shift + Enter 换行"})]})]})]}),E==="settings"&&A?u.jsx(l0,{host:n.host==="desktop"?"desktop":"hub",section:je,onSectionChange:ut,onAuthLost:R,onConfigurationChange:()=>{ie()},configurationVersion:z,onDirtyChange:ve},`${n.workspaceKey}:settings`):null,E==="files"&&A?u.jsx(c0,{initialPath:k,openVersion:K,onAuthLost:R},`${n.workspaceKey}:files`):null,E==="history"&&A?u.jsx(f0,{onAuthLost:R,onOpen:q=>{me(q)},onChanged:()=>{W()},version:_,onDirtyChange:ve},`${n.workspaceKey}:history`):null,E==="links"&&A?u.jsx(h0,{onAuthLost:R,onDirtyChange:ve,hostLabel:G,configurationVersion:z},`${n.workspaceKey}:links`):null,E==="panels"&&A?u.jsx(m0,{onAuthLost:R,onDirtyChange:ve,onChanged:()=>{ie()},hostLabel:G,configurationVersion:z,onOpen:q=>ot(()=>{he({panel:q,workspaceKey:n.workspaceKey}),U("panel"),mt()})},`${n.workspaceKey}:panels`):null,E==="panel"&&A&&te?.workspaceKey===n.workspaceKey?u.jsx(S0,{panel:te.panel,sessionId:d,busy:H||p||n.uncertain,onAuthLost:R,onDirtyChange:ve,onClose:()=>ot(()=>U("panels")),onSubmitPrompt:async q=>sE(n,{...q,workspaceKey:te.workspaceKey})},`${n.workspaceKey}:panel:${te.panel.id}:${d}`):null]}),Q?u.jsx(oE,{onStay:()=>pe(null),onLeave:()=>{const q=Q;pe(null),ve(!1),q()}}):null,V&&n.host==="hub"?u.jsx(wv,{session:F,onClose:()=>se(!1),onAuthLost:R}):null]})}function oE({onStay:n,onLeave:i}){const r=w.useRef(null);return w.useEffect(()=>{const s=document.activeElement;return r.current?.showModal(),()=>{r.current?.close(),s?.focus()}},[]),u.jsxs("dialog",{className:"navigation-prompt",ref:r,"aria-labelledby":"navigation-prompt-title",onCancel:s=>{s.preventDefault(),n()},children:[u.jsx("h2",{id:"navigation-prompt-title",children:"还有未保存的修改"}),u.jsx("p",{children:"离开会丢弃未提交的修改;切换项目还会清除未发送的草稿和附件。已经提交的操作可能仍会完成,请等待结果后再离开。"}),u.jsxs("div",{className:"library-actions",children:[u.jsx("button",{className:"library-button primary",onClick:n,autoFocus:!0,children:"留在此页"}),u.jsx("button",{className:"library-button",onClick:i,children:"放弃修改并离开"})]})]})}function cE(n){switch(n){case"running":return"进行中";case"waiting":case"waiting_approval":return"等待确认";case"completed":return"已完成";case"cancelled":case"canceled":return"已停止";case"failed":case"error":return"发生错误";case"idle":return"可继续";default:return"对话"}}function Et({name:n}){const i={panels:u.jsxs(u.Fragment,{children:[u.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),u.jsx("path",{d:"M15 3v18M15 10h6"})]}),camera:u.jsxs(u.Fragment,{children:[u.jsx("path",{d:"M3 7h4l2-3h6l2 3h4v13H3Z"}),u.jsx("circle",{cx:"12",cy:"13",r:"4"})]}),links:u.jsxs(u.Fragment,{children:[u.jsx("path",{d:"M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2"}),u.jsx("path",{d:"M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2"})]}),brand:u.jsx(u.Fragment,{children:u.jsx("path",{d:"m5 7 5 5-5 5M13 17h6"})}),sidebar:u.jsxs(u.Fragment,{children:[u.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),u.jsx("path",{d:"M9 4v16"})]}),plus:u.jsx("path",{d:"M12 5v14M5 12h14"}),chat:u.jsx("path",{d:"M21 11.5a8.4 8.4 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.4 8.4 0 0 1-3.8-.9L3 21l1.9-5.7a8.4 8.4 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.4 8.4 0 0 1 3.8-.9h.5a8.5 8.5 0 0 1 8 8v.5Z"}),history:u.jsxs(u.Fragment,{children:[u.jsx("path",{d:"M3 12a9 9 0 1 0 3-6.7L3 8"}),u.jsx("path",{d:"M3 3v5h5M12 7v5l3 2"})]}),skills:u.jsx(u.Fragment,{children:u.jsx("path",{d:"m12 3 2.7 5.5L21 9.4l-4.5 4.4 1.1 6.2L12 17.1 6.4 20l1.1-6.2L3 9.4l6.3-.9L12 3Z"})}),settings:u.jsxs(u.Fragment,{children:[u.jsx("path",{d:"m9 3-.7 3-2.6 1-2.6 2 1.4 3-1.4 3 2.6 2 2.6 1 .7 3h6l.7-3 2.6-1 2.6-2-1.4-3 1.4-3-2.6-2-2.6-1L15 3H9Z"}),u.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),folder:u.jsx("path",{d:"M3 7V5a1 1 0 0 1 1-1h5l2 3h9a1 1 0 0 1 1 1v11a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V7Z"}),chevron:u.jsx("path",{d:"m9 5 7 7-7 7"}),attachment:u.jsx("path",{d:"m21 11-8 8a6 6 0 0 1-8.5-8.5l9-9A4 4 0 0 1 19 7l-9 9a2 2 0 0 1-2.8-2.8l8-8"}),send:u.jsx("path",{d:"M12 19V5m-6 6 6-6 6 6"}),stop:u.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2",fill:"currentColor",stroke:"none"})};return u.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:i[n]})}class Ll extends Error{constructor(i,r,s){super(i),this.kind=r,this.code=s,this.name="ProtocolRequestError"}kind;code}const fE=3e4,zg=800,dE=15e3;class hE{constructor(i){this.url=i}url;ws=null;nextId=1;pending=new Map;notificationHandlers=new Set;stateHandlers=new Set;reconnectDelay=zg;closedByUser=!1;reconnectTimer;authHandlers=new Set;connect(){this.ws||(clearTimeout(this.reconnectTimer),this.closedByUser=!1,this.openSocket())}openSocket(){if(this.closedByUser)return;this.reconnectTimer=void 0,this.emitState("connecting");const i=new WebSocket(this.url);this.ws=i,i.onopen=()=>{this.ws!==i||this.closedByUser||(this.reconnectDelay=zg,this.emitState("open"))},i.onmessage=r=>{if(this.ws!==i||this.closedByUser)return;let s;try{if(s=JSON.parse(String(r.data)),!s||typeof s!="object"||Array.isArray(s))return}catch{return}if(s.id!==void 0&&s.method===void 0){const f=this.pending.get(String(s.id));if(!f)return;this.pending.delete(String(s.id)),clearTimeout(f.timer),s.error?f.reject(new Ll(s.error.message??"request failed","response",s.error.code)):f.resolve(s.result);return}if(s.method)for(const f of this.notificationHandlers)f(s.method,s.params??{})},i.onclose=r=>{if(this.ws===i){if(this.ws=null,this.emitState("closed"),this.failAllPending(new Ll("connection closed","transport")),r.code===4401||r.code===4403){this.closedByUser=!0;for(const s of this.authHandlers)s()}this.closedByUser||(this.reconnectTimer=setTimeout(()=>this.openSocket(),this.reconnectDelay),this.reconnectDelay=Math.min(this.reconnectDelay*2,dE))}},i.onerror=()=>{}}close(){this.closedByUser=!0,clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0;const i=this.ws;this.ws=null,i?.close(),this.failAllPending(new Ll("connection closed","transport"))}onNotification(i){return this.notificationHandlers.add(i),()=>this.notificationHandlers.delete(i)}onStateChange(i){return this.stateHandlers.add(i),()=>this.stateHandlers.delete(i)}onAuthLost(i){return this.authHandlers.add(i),()=>this.authHandlers.delete(i)}request(i,r,s=fE){const f=this.ws;if(!f||f.readyState!==WebSocket.OPEN)return Promise.reject(new Ll("not connected","not-sent"));const d=`web-${this.nextId++}`;return new Promise((o,m)=>{const g=s>0?setTimeout(()=>{this.pending.delete(d),m(new Ll(`request timed out: ${i}`,"timeout"))},s):void 0;this.pending.set(d,{resolve:o,reject:m,timer:g});try{f.send(JSON.stringify({jsonrpc:"2.0",id:d,method:i,params:r}))}catch(p){clearTimeout(g),this.pending.delete(d),m(new Ll(p instanceof Error?p.message:"send failed","not-sent"))}})}run(i){return this.request("agent/run",i,0)}listSessions(){return this.request("agent/query",{type:"sessions"})}sessionDetail(i){return this.request("agent/query",{type:"session_detail",sessionId:i})}approve(i,r,s){return this.request("agent/approve",{sessionId:i.sessionId??"",...i.connectionId?{connectionId:i.connectionId}:{},...i.generation!==void 0?{generation:i.generation}:{},requestId:i.requestId,decision:r?{approved:!0,...s?{answer:s}:{}}:{approved:!1}})}cancel(i){return this.request("agent/cancel",{sessionId:i})}emitState(i){for(const r of this.stateHandlers)r(i)}failAllPending(i){for(const[,r]of this.pending)clearTimeout(r.timer),r.reject(i);this.pending.clear()}}function pE(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}${Rt("/ws")}`}function mE(n,i){const{method:r,params:s}=i;if(r==="serve/approvalSnapshot"){if(!Array.isArray(s.approvals))return n;const d={};for(const o of s.approvals)o?.requestId&&o.request&&(d[o.requestId]={payload:o});return d}if(r==="agent/approvalRequest"){const d=s;return!d.requestId||!d.request?n:{...n,[d.requestId]:{...n[d.requestId],payload:d}}}const f=s.requestId;if(typeof f!="string"||!n[f])return n;if(r==="agent/approvalResolved"){const d={...n};return delete d[f],d}return r==="serve/approvalLease"?{...n,[f]:{...n[f],lease:s}}:n}class gE{drafts=new Map;get(i){return this.drafts.get(i)??{text:"",files:[],revision:0}}update(i,r){const s={...r,revision:this.get(i).revision+1};return this.drafts.set(i,s),s}setText(i,r){return this.update(i,{...this.get(i),text:r})}addFile(i,r){const s=this.get(i);return this.update(i,{...s,files:[...s.files,r]})}removeFile(i,r){const s=this.get(i);return this.update(i,{...s,files:s.files.filter(f=>f.id!==r)})}take(i){const r=this.get(i),s=this.update(i,{text:"",files:[]});return{sessionId:i,draft:r,clearedRevision:s.revision}}restore(i){const r=this.get(i.sessionId);return r.revision!==i.clearedRevision||r.text||r.files.length?!1:(this.update(i.sessionId,i.draft),!0)}unsent(){return[...this.drafts].flatMap(([i,r])=>r.text.trim()||r.files.length?[{sessionId:i,draft:r}]:[])}}const yE="codeshell.uiLanguage";function bE(){try{const n=globalThis.localStorage?.getItem(yE);if(n==="zh"||n==="en")return n}catch{}return"zh"}const xE={zh:{mobile:{app:{extendGoal:"延长目标",clearGoal:"清除目标",loadingCcSession:"正在加载 CC 会话…",loadingSession:"正在加载会话…",conversationFallback:"对话",desktopSession:"桌面会话",newSession:"新会话",openSessionsAria:"打开会话",leaveSessionAria:"退出会话",deviceFallback:"设备",logoutAria:"退出登录",permission:"权限",ccRoomObserving:"此会话当前为只读查看;请在桌面端明确接管后再发送消息。"},approval:{risk:{low:"低风险",medium:"中风险",high:"高风险"},readSourceSummary:"读取数据源 {source} / {scope} / {resource}",question:"问题",customPlaceholder:"或输入自定义回答…",sendCustom:"发送自定义回答",rememberScope:"记住范围",scope:{once:"仅本次",session:"本会话",project:"本项目"},pathScopeLabel:"路径范围",pathScope:{file:"此文件",dir:"此目录",tool:"此工具"},allow:"允许",reject:"拒绝"},cc:{title:"CC 会话",subtitle:"外部 {label} 会话",selectProjectFirst:"先选择一个项目。",probingCli:"正在检测 {label} CLI…",cliMissing:"未检测到 {label} CLI(需在桌面端机器的 PATH 中)。",loadingSessions:"正在加载 cc 会话…",empty:"该项目下没有 {label} 会话。",messageCount:"{count} 条"},sidePane:{localTab:"会话",ccTab:"CC 会话"},composer:{disconnected:"未连接",placeholder:"发消息…",stop:"停止",send:"发送",chooseImages:"从相册选择图片",takePhoto:"拍照",removeImage:"移除图片",uploading:"上传中…",tooManyImages:"每条消息最多发送 4 张图片",unsupportedImage:"不支持此图片格式",sendFailed:"图片发送失败,请重试"},connection:{connectingTitle:"正在连接…",connectingBody:"与 CodeShell 建立通道",authenticatingTitle:"认证中…",authenticatingBody:"正在校验设备身份",unpairedTitle:"未配对",unpairedBody:"请在 CodeShell 桌面端打开「设置 → 远程」,扫码或打开配对链接。",offlineTitle:"连接断开",offlineBody:"正在自动重连…"},format:{noProject:"无项目",justNow:"刚刚",minutesAgo:"{n} 分钟前",hoursAgo:"{n} 小时前",daysAgo:"{n} 天前",monthsAgo:"{n} 个月前",yearsAgo:"{n} 年前"},notice:{roomMissing:"会话不存在或未就绪",roomError:"会话错误",sessionRecoveryIncomplete:"当前回复的开头尚未恢复,请重新打开会话以读取已保存的内容。",sessionRecoveryHistoryOnly:"已恢复保存的聊天记录。当前回复的实时部分暂时无法接续,请稍后重新打开会话。",goalExtendFailed:"延长目标失败",ccRoomOpenFailed:"cc 会话无法打开",ccRoomObserving:"此 CC 会话当前为只读查看,消息未发送",attachmentSendFailed:"图片发送失败:{error}"},permissionMode:{default:"默认",acceptEdits:"自动改",bypassPermissions:"全放行",defaultDesc:"每个工具调用都要你确认",acceptEditsDesc:"自动放行文件编辑,其余仍确认",bypassDesc:"跳过所有权限确认(危险)",title:"选择权限模式",confirmBypass:"全放行模式会跳过所有权限确认。确定吗?"},sessionList:{title:"会话",takeoverCount:"{count} 个可接管",refreshAria:"刷新会话",new:"新建",createHint:"新会话默认使用当前目录",currentProject:"当前项目 · {name}",noProjectConversation:"无项目对话",desktopCwd:"当前桌面目录",unboundRepo:"不绑定 repo",followsDesktopCwd:"跟随桌面当前 cwd",otherProjects:"其他项目",loading:"正在加载会话…",empty:"还没有会话。点「新建」开一个,或在桌面端开始。",automation:"自动",noProjectPath:"无项目路径",unreadAria:"有新内容",primaryRoot:"主目录",secondaryRoot:"次目录"},status:{conn:{connecting:"连接中…",authenticating:"认证中…",unpaired:"未配对",online:"在线",offline:"已断开"},run:{idle:"空闲",running:"运行中",waiting:"待审批",completed:"已完成",error:"出错"}},storage:{browserDevice:"{platform} 浏览器"},stream:{showReasoning:"显示思考",hideReasoning:"隐藏思考",subagent:"子代理",loading:"正在加载…",generating:"正在生成回复",emptyHint:"发个任务试试,或在侧栏打开一个 Claude Code 会话。"},tool:{running:"运行中",failed:"失败",completed:"完成",fallbackName:"操作",truncated:"… (已截断)"}}},en:{mobile:{app:{extendGoal:"Extend goal",clearGoal:"Clear goal",loadingCcSession:"Loading CC session…",loadingSession:"Loading conversation…",conversationFallback:"Conversation",desktopSession:"Desktop session",newSession:"New session",openSessionsAria:"Open sessions",leaveSessionAria:"Leave session",deviceFallback:"Device",logoutAria:"Log out",permission:"Permission",ccRoomObserving:"This session is read-only. Take it over explicitly on desktop before sending messages."},approval:{risk:{low:"Low risk",medium:"Medium risk",high:"High risk"},readSourceSummary:"Read data source {source} / {scope} / {resource}",question:"Question",customPlaceholder:"Or enter a custom answer…",sendCustom:"Send custom answer",rememberScope:"Remember scope",scope:{once:"Once",session:"This session",project:"This project"},pathScopeLabel:"Path scope",pathScope:{file:"This file",dir:"This directory",tool:"This tool"},allow:"Allow",reject:"Deny"},cc:{title:"CC sessions",subtitle:"External {label} sessions",selectProjectFirst:"Select a project first.",probingCli:"Checking {label} CLI…",cliMissing:"{label} CLI was not found (it must be in PATH on the desktop machine).",loadingSessions:"Loading cc sessions…",empty:"No {label} sessions in this project.",messageCount:"{count} messages"},sidePane:{localTab:"Sessions",ccTab:"CC"},composer:{disconnected:"Disconnected",placeholder:"Message…",stop:"Stop",send:"Send",chooseImages:"Choose images",takePhoto:"Take photo",removeImage:"Remove image",uploading:"Uploading…",tooManyImages:"Up to 4 images can be sent per message",unsupportedImage:"This image format is not supported",sendFailed:"Could not send images; try again"},connection:{connectingTitle:"Connecting…",connectingBody:"Opening a channel to CodeShell",authenticatingTitle:"Authenticating…",authenticatingBody:"Verifying this device",unpairedTitle:"Not paired",unpairedBody:"Open Settings → Remote in CodeShell desktop, then scan the QR code or open the pairing link.",offlineTitle:"Disconnected",offlineBody:"Reconnecting automatically…"},format:{noProject:"No project",justNow:"Just now",minutesAgo:"{n} min ago",hoursAgo:"{n} hr ago",daysAgo:"{n} days ago",monthsAgo:"{n} mo ago",yearsAgo:"{n} yr ago"},notice:{roomMissing:"Session does not exist or is not ready",roomError:"Session error",sessionRecoveryIncomplete:"The beginning of this reply could not be restored. Reopen the conversation to read its saved content.",sessionRecoveryHistoryOnly:"Saved chat history has been restored. Reopen the conversation later to see the rest of this reply.",goalExtendFailed:"Failed to extend goal",ccRoomOpenFailed:"Could not open cc session",ccRoomObserving:"This CC session is read-only; the message was not sent",attachmentSendFailed:"Could not send images: {error}"},permissionMode:{default:"Default",acceptEdits:"Auto-edit",bypassPermissions:"Allow all",defaultDesc:"Confirm every tool call",acceptEditsDesc:"Allow file edits automatically; confirm everything else",bypassDesc:"Skip all permission confirmations (dangerous)",title:"Choose permission mode",confirmBypass:"Allow all mode skips every permission confirmation. Continue?"},sessionList:{title:"Sessions",takeoverCount:"{count} available",refreshAria:"Refresh sessions",new:"New",createHint:"New sessions default to the current directory",currentProject:"Current project · {name}",noProjectConversation:"No-project conversation",desktopCwd:"Current desktop directory",unboundRepo:"Do not bind a repo",followsDesktopCwd:"Follow desktop current cwd",otherProjects:"Other projects",loading:"Loading sessions…",empty:"No sessions yet. Tap “New” to start one, or start from desktop.",automation:"Automation",noProjectPath:"No project path",unreadAria:"New content",primaryRoot:"Primary",secondaryRoot:"Secondary"},status:{conn:{connecting:"Connecting…",authenticating:"Authenticating…",unpaired:"Not paired",online:"Online",offline:"Disconnected"},run:{idle:"Idle",running:"Running",waiting:"Awaiting approval",completed:"Completed",error:"Error"}},storage:{browserDevice:"{platform} browser"},stream:{showReasoning:"Show reasoning",hideReasoning:"Hide reasoning",subagent:"Subagent",loading:"Loading…",generating:"Generating response",emptyHint:"Send a task, or open a Claude Code session from the sidebar."},tool:{running:"Running",failed:"Failed",completed:"Completed",fallbackName:"Operation",truncated:"… (truncated)"}}}},Rg=xE;function _g(n,i){let r=n;for(const s of i.split(".")){if(r==null||typeof r!="object")return;r=r[s]}return typeof r=="string"?r:void 0}function vE(n,i){return i?n.replace(/\{(\w+)\}/g,(r,s)=>s in i?String(i[s]):r):n}function SE(n,i,r){const s=_g(Rg[n],i)??_g(Rg.zh,i)??i;return vE(s,r)}function jE(n,i){return SE(bE(),n,i)}const kE=["command","file_path","path","url","pattern","query"];function wE(n,i,r){let s="";const f=n?.source,d=n?.scope,o=n?.resource;if(r==="ReadSource"&&typeof f=="string"&&f.length>0&&typeof d=="string"&&d.length>0&&typeof o=="string"&&o.length>0)s=jE("mobile.approval.readSourceSummary",{source:f,scope:d,resource:o});else for(const g of kE){const p=n?.[g];if(typeof p=="string"&&p.length>0){s=p;break}}s||(s=JSON.stringify(n??{}));let m;return i==="low"||i==="medium"||i==="high"?m=i:i===void 0||i===""?m="medium":m="high",{summary:s,risk:m}}function CE({payload:n,onDecide:i,busy:r,connected:s}){const[f,d]=w.useState(""),o=n.request.toolName==="__ask_user__",{summary:m,risk:g}=wE(n.request.args,n.request.riskLevel,n.request.toolName);return u.jsxs("div",{className:"approval",children:[u.jsxs("div",{className:"approval-title",children:[o?"Agent 提问":`工具审批:${n.request.toolName}`,o?null:u.jsxs("em",{children:[" · ",g]})]}),n.request.description?u.jsx("div",{className:"approval-desc",children:n.request.description}):null,o?null:u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"approval-summary",children:m}),u.jsxs("details",{className:"approval-raw",children:[u.jsx("summary",{children:"原始参数"}),u.jsx("pre",{className:"approval-args",children:JSON.stringify(n.request.args,null,2)})]})]}),o?u.jsx("textarea",{className:"approval-answer",value:f,placeholder:"输入回答…",onChange:p=>d(p.target.value)}):null,r?u.jsx("span",{className:"muted",role:"status",children:"设备正在处理此审批…"}):null,u.jsxs("div",{className:"approval-actions",children:[u.jsx("button",{className:"send",disabled:r||!s||o&&!f.trim(),onClick:()=>i(n,!0,o?f:void 0),children:o?"回答":"允许"}),u.jsx("button",{className:"stop",disabled:r||!s,onClick:()=>i(n,!1),children:"拒绝"})]})]})}function Dg(){return la()}const EE=()=>{},NE=async()=>{};function TE({session:n,hub:i=!1,onAuthLost:r=EE,onCheckAuth:s=NE}){const f=w.useRef(null),[d,o]=w.useState("connecting"),[m,g]=w.useState([]),p=w.useRef([]),[b,y]=w.useState(()=>aE(window.location.search)??Dg()),[v,S]=w.useState(As()),[N,D]=w.useReducer(mE,{}),[z,_]=w.useState({}),[M,H]=w.useState(""),[oe,ce]=w.useState([]),R=w.useRef(new gE),[W,ie]=w.useState(0),[F,A]=w.useState(null),G=F===b,[V,se]=w.useState(null),[ae,P]=w.useState(null),[E,U]=w.useState(""),[te,he]=w.useState(Date.now()),[k,T]=w.useState(0),[K,C]=w.useState(null),[re,ve]=w.useState(0),Q=w.useRef(0),pe=w.useRef(b),je=w.useRef(null),Y=w.useRef(new Map),xe=w.useRef(new Map),J=w.useRef(new Set),ye=w.useRef(new Set),Ae=w.useRef(new Set),we=w.useRef(!1),Ye=w.useRef(null),nt=w.useRef(null),jt=w.useCallback(de=>{if(ie(Je=>Je+1),pe.current!==de)return;const Re=R.current.get(de);H(Re.text),ce(Re.files)},[]);w.useEffect(()=>{const de=new URL(window.location.href);de.searchParams.set("session",b),window.history.replaceState(window.history.state,"",de)},[b]);const Yt=w.useCallback((de,Re)=>{const Je=R.current.restore(de.draft);jt(de.draft.sessionId),pe.current===de.draft.sessionId&&(S(_e=>({..._e,run:"error",items:_e.items.filter(Ue=>Ue.kind!=="user"||Ue.clientMessageId!==de.clientMessageId)})),Je&&U(`${Re?`${Re} `:"消息未送达。"}内容和附件已恢复,可以重试。`))},[jt]),at=w.useCallback(de=>{we.current&&(de instanceof We&&de.status===401?r():U(de instanceof Error?de.message:"操作失败,请重试。"))},[r]),mt=w.useCallback(async()=>{if(!i||!we.current)return;const de=++Q.current;try{const Re=await Hg();we.current&&de===Q.current&&C(Re)}catch(Re){we.current&&Re instanceof We&&Re.status===401&&r()}},[i,r]),ut=w.useCallback(async()=>{const de=f.current;if(de)try{const Re=i?(await Dc()).sessions:(await de.listSessions()).data;if(f.current===de&&we.current){const Je=[...Re].sort((_e,Ue)=>(Ue.lastActiveAt??Ue.startedAt)-(_e.lastActiveAt??_e.startedAt));p.current=Je,g(Je)}}catch(Re){at(Re)}},[at,i]),ot=w.useCallback(async()=>{const de=f.current;if(de)for(const[Re,Je]of xe.current)try{const _e=await de.sessionDetail(Re);if(!we.current||de!==f.current||xe.current.get(Re)!==Je)continue;Ag(_e.data).chat.items.some(Oe=>Oe.kind==="user"&&Oe.clientMessageId===Je.clientMessageId)?xe.current.delete(Re):_e.data.running||(xe.current.delete(Re),Yt(Je))}catch(_e){if(!we.current||de!==f.current||xe.current.get(Re)!==Je)continue;_e instanceof Ll&&_e.kind==="response"&&_e.code===-32001&&_e.message===`Session not found: ${Re}`&&(xe.current.delete(Re),Yt(Je))}},[Yt]),Gt=w.useCallback(async de=>{const Re=f.current;if(!Re)return;const Je={sessionId:de,events:[]};nt.current=Je;try{const _e=await Re.sessionDetail(de);if(!we.current||nt.current!==Je||pe.current!==de)return;const Ue=Je.running??_e.data.running;Ue?ye.current.add(de):Ue===!1&&ye.current.delete(de);const et=Ag(_e.data,Je.events),Oe=et.chat;je.current=et.cursor??null,P(et.truncated?"这次运行的实时记录较长,已恢复已保存的内容;结束后重新打开可查看完整记录。":null),Ue||J.current.has(de)?Oe.run="running":Ue===!1&&(Oe.run==="running"||Oe.run==="waiting")&&(Oe.run="idle"),S(Oe)}catch(_e){pe.current===de&&at(_e)}finally{nt.current===Je&&(nt.current=null)}},[at]);w.useEffect(()=>{we.current=!0;const de=new hE(pE());f.current=de;const Re=de.onAuthLost(r),Je=de.onStateChange(Ue=>{o(Ue),Ue==="open"?(se(null),U(""),ut().then(()=>{const et=pe.current;we.current&&f.current===de&&(p.current.some(Oe=>Oe.sessionId===et)||ye.current.has(et)||J.current.has(et)||xe.current.has(et))&&Gt(et)}),mt(),ot()):Ue==="closed"&&(i&&s(),S(et=>({...et,run:"idle"})))}),_e=de.onNotification((Ue,et)=>{if(Ue==="serve/sessionsChanged"){ut(),T(Oe=>Oe+1);return}if(Ue==="agent/runAccepted"&&typeof et.sessionId=="string"){const Oe=Y.current.get(et.sessionId);Oe&&(Oe.accepted=!0);return}if(Ue==="serve/configurationChanged"){mt(),ve(Oe=>Oe+1);return}if(Ue==="agent/streamEvent"){const Oe=et,{sessionId:_t,event:Ft}=Oe,ol=Y.current.get(_t);if(ol&&["stream_request_start","text_delta","thinking_delta","tool_use_start"].includes(String(Ft.type))&&(ol.accepted=!0),_t===pe.current){if(nt.current?.sessionId===_t&&nt.current.events.push(Oe),!Zy(Oe,je.current))return;Oe.hubEpoch&&Oe.hubSequence!==void 0&&(je.current={epoch:Oe.hubEpoch,sequence:Oe.hubSequence}),S(Qs=>Os(Qs,Ft))}Ft.type==="stream_request_start"&&se(null),Ft.type==="turn_complete"&&ut();return}if(Ue==="serve/sessionStatus"){T(Ft=>Ft+1);const{sessionId:Oe,running:_t}=et;if(typeof Oe!="string"||typeof _t!="boolean")return;nt.current?.sessionId===Oe&&(nt.current.running=_t),_t?ye.current.add(Oe):ye.current.delete(Oe),!_t&&xe.current.has(Oe)&&ot(),Oe===pe.current&&S(Ft=>_t?{...Ft,run:"running"}:Ft.run==="running"||Ft.run==="waiting"?{...Ft,run:"idle"}:Ft),ut();return}if(Ue==="agent/approvalRequest"||Ue==="agent/approvalResolved"||Ue==="serve/approvalSnapshot"||Ue==="serve/approvalLease"){D({method:Ue,params:et});return}if(Ue==="serve/workerExit"){ye.current.clear();const Oe=et.clean;se(Oe?"服务进程已退出,发送消息会自动重启":"服务进程异常退出,发送消息会自动重启"),S(_t=>({..._t,run:"idle"}))}});return de.connect(),()=>{we.current=!1,Ye.current?.abort(),Je(),_e(),Re(),de.close(),f.current=null}},[ut,Gt,mt,ot,r,s,i]);const vt=Object.values(N).some(de=>de.lease?.holderId&&(de.lease.expiresAt??0)>te);w.useEffect(()=>{if(!vt)return;he(Date.now());const de=setInterval(()=>he(Date.now()),1e3);return()=>clearInterval(de)},[vt]);const qt=async de=>{pe.current=de,je.current=null,y(de),jt(de),S(As()),U(""),P(null),!(!m.some(Re=>Re.sessionId===de)&&!ye.current.has(de)&&R.current.unsent().some(Re=>Re.sessionId===de))&&await Gt(de)},ne=()=>{const de=Dg();pe.current=de,je.current=null,nt.current=null,y(de),jt(de),S(As()),U(""),P(null)},me=()=>{const de=R.current.get(pe.current),Re=de.text.trim(),Je=f.current;if(!Re&&!de.files.length||!Je||d!=="open"||G)return!1;const _e=pe.current;if(J.current.has(_e)||ye.current.has(_e)||v.run==="running"||v.run==="waiting"||Object.values(N).some(Oe=>Oe.payload.sessionId===_e)||xe.current.has(_e))return!1;pe.current=_e,y(_e),J.current.add(_e);const Ue={clientMessageId:la(),draft:R.current.take(_e),accepted:!1};Y.current.set(_e,Ue);const et=Ue.draft.draft.files;return jt(_e),U(""),S(Oe=>({...nE(Oe,Re,et.map(_t=>({name:_t.name,mime:_t.mimeType,size:_t.size})),Ue.clientMessageId),run:"running"})),Je.run({sessionId:_e,task:Re,clientMessageId:Ue.clientMessageId,displayText:Re,...et.length?{uploadIds:et.map(Oe=>Oe.id)}:{}}).catch(Oe=>{we.current&&(at(Oe),Oe instanceof Ll&&(Oe.kind==="transport"||Oe.kind==="timeout")?(xe.current.set(_e,Ue),U("连接中断,重新连接后会核对这条消息是否已经送达。")):Ue.accepted||Yt(Ue,Oe instanceof Error?Oe.message==="upload not found or expired"?"附件已失效,请移除后重新上传。":Oe.message:void 0),pe.current===_e&&S(_t=>({..._t,run:"error"})))}).finally(()=>{J.current.delete(_e),Y.current.get(_e)===Ue&&Y.current.delete(_e),we.current&&pe.current===_e&&!ye.current.has(_e)&&S(Oe=>Oe.run==="running"?{...Oe,run:"idle"}:Oe)}),!0},Te=(de,Re,Je)=>{const _e=f.current;!_e||d!=="open"||Ae.current.has(de.requestId)||(Ae.current.add(de.requestId),_(Ue=>({...Ue,[de.requestId]:!0})),U(""),_e.approve({...de,sessionId:de.sessionId??pe.current??""},Re,Je).then(()=>D({method:"agent/approvalResolved",params:{requestId:de.requestId}})).catch(at).finally(()=>{Ae.current.delete(de.requestId),_(Ue=>{const et={...Ue};return delete et[de.requestId],et})}))},ge=()=>{b&&f.current?.cancel(b).catch(at)},ke=async de=>{if(!de?.length||Ye.current)return;const Re=new AbortController,Je=Ug();Ye.current=Re,A(pe.current),U("");const _e=pe.current;try{for(const Ue of Array.from(de)){if(!we.current||Re.signal.aborted)break;const et=await kv(Ue,{signal:Re.signal,scope:Je});we.current&&!Re.signal.aborted&&(R.current.addFile(_e,et),jt(_e))}}catch(Ue){at(Ue)}finally{Ye.current===Re&&(Ye.current=null),we.current&&A(null)}},Ce=Object.values(N).filter(de=>!de.payload.sessionId||de.payload.sessionId===b),B=de=>Object.values(N).filter(Re=>Re.payload.sessionId===de).length,Se=v.run==="running"||v.run==="waiting"||Ce.length>0,Ke=w.useMemo(()=>R.current.unsent().filter(de=>!m.some(Re=>Re.sessionId===de.sessionId)),[W,m]),lt=K?.workspace.path??m.find(de=>de.sessionId===b)?.cwd??m[0]?.cwd??null,Be=lt?.split(/[\\/]/).filter(Boolean).pop()??"服务端工作区",q=v.items.length===0&&Ce.length===0,ze=m.find(de=>de.sessionId===b),St=q?"新对话":ze?.customTitle||v.title||ze?.title||ze?.preview?.trim()||Ky(v,b??"新对话");return{host:i?"hub":"legacy",workspaceApi:i,connection:d,session:n,activeId:b,chat:v,sessions:m,workspaceCwd:lt,workspaceName:Be,title:St,workspaceKey:lt??"hub",configuration:K,configurationVersion:re,sessionsVersion:k,draft:M,files:oe,uploading:G,uploadBusy:F!==null,hasUnsent:R.current.unsent().length>0,localDrafts:Ke,uncertain:xe.current.has(b),running:Se,approvals:Object.values(N).map(de=>({id:de.payload.requestId,sessionId:de.payload.sessionId})),approvalCount:B,approvalContent:Ce.map(de=>u.jsx(CE,{payload:de.payload,onDecide:Te,busy:!!z[de.payload.requestId]||!!(de.lease?.holderId&&(de.lease.expiresAt??0)>te),connected:d==="open"},de.payload.requestId)),workerNote:V,replayNote:ae,error:E,clearError:()=>U(""),setDraft:de=>{R.current.setText(pe.current,de),jt(pe.current)},removeFile:de=>{R.current.removeFile(pe.current,de),jt(pe.current)},selectSession:qt,newSession:ne,send:me,stop:ge,addFiles:ke,refreshSessions:ut,refreshConfiguration:mt,onAuthLost:r}}function Og({onBackToProjects:n,projectName:i,...r}){return u.jsx(uE,{controller:TE(r),onBackToProjects:n,projectName:i})}function Fy(n){if(!n||typeof n!="object")return!1;const i=n;return Wr(i.id)&&typeof i.name=="string"&&i.name.length>0&&["stopped","starting","running","stopping","error"].includes(i.status)&&Number.isSafeInteger(i.generation)&&i.generation>=0&&Number.isSafeInteger(i.createdAt)&&i.createdAt>=0&&(i.error===void 0||typeof i.error=="string")}function AE(n){const i=n;if(!i||i.runtime!=="docker"||typeof i.available!="boolean"||!Array.isArray(i.projects)||!i.projects.every(Fy)||new Set(i.projects.map(r=>r.id)).size!==i.projects.length||i.error!==void 0&&typeof i.error!="string")throw new Error("服务端返回了无效的项目列表,请重试。");return i}function Mg(){return new URL(window.location.href).searchParams.get("project")}function Fr(n,i=!1){const r=new URL(window.location.href);n?r.searchParams.set("project",n):r.searchParams.delete("project"),i||r.searchParams.delete("session"),window.history.replaceState(window.history.state,"",r)}const zE={stopped:"已停止",starting:"正在启动",running:"运行中",stopping:"正在停止",error:"启动失败"};function RE({children:n,onAuthLost:i}){const[r,s]=w.useState(null),[f,d]=w.useState(!1),[o,m]=w.useState(null),[g,p]=w.useState(""),[b,y]=w.useState(!0),[v,S]=w.useState(null),[N,D]=w.useState(""),[z,_]=w.useState(null),M=w.useRef(null),H=w.useRef(Mg()),oe=w.useRef(o),ce=w.useRef(r),R=w.useRef(0),W=w.useRef(0),ie=w.useRef(null),F=w.useRef(i),A=w.useRef(!1);F.current=i,oe.current=o,ce.current=r;const G=w.useCallback(E=>{if(E.status!=="running")return;const U=Mg()===E.id;vs(),xs(E.id),Fr(E.id,U),H.current=null,oe.current=E,m(E),p("")},[]),V=w.useCallback(()=>{H.current=null,oe.current=null,m(null),xs(null),vs(),Fr(null)},[]),se=w.useCallback(async E=>{if(A.current)return;const U=++W.current,te=R.current;try{const he=AE(await Ve("/api/v1/projects",{signal:E}));if(E?.aborted||U!==W.current||te!==R.current)return;s(he),ce.current=he,y(!1),p("");const k=oe.current;if(k){const K=he.projects.find(C=>C.id===k.id);(!K||K.status!=="running"||K.generation!==k.generation)&&(V(),p("项目运行状态已经变化,请重新打开项目。未发送的内容不会带入其他项目。"));return}if(!H.current)return;const T=he.projects.find(K=>K.id===H.current);T?T.status==="running"&&he.available&&G(T):(H.current=null,Fr(null),p("链接中的项目不存在或当前账号无权访问,请选择一个项目。"))}catch(he){if(E?.aborted||U!==W.current||te!==R.current)return;y(!1),he instanceof We&&he.status===404&&!ce.current?(xs(null),vs(),A.current=!0,d(!0)):he instanceof We&&he.status===401?F.current():p(he instanceof Error?he.message:"无法读取项目,请重试。")}},[V,G]);w.useEffect(()=>{R.current++;const E=new AbortController;se(E.signal);const U=()=>{se(E.signal)},te=()=>{document.visibilityState==="visible"&&U()};return window.addEventListener("focus",U),document.addEventListener("visibilitychange",te),()=>{R.current++,E.abort(),ie.current?.abort(),window.removeEventListener("focus",U),document.removeEventListener("visibilitychange",te),xs(null),vs()}},[se]);const ae=r?.projects.some(E=>E.status==="starting"||E.status==="stopping");w.useEffect(()=>{if(f||!r)return;const E=new AbortController,U=setInterval(()=>{se(E.signal)},ae?2e3:1e4);return()=>{clearInterval(U),E.abort()}},[f,!!r,ae,se]),w.useEffect(()=>{if(!z)return;const E=document.activeElement,U=M.current;return U?.showModal?.(),()=>{U?.close?.(),E?.focus()}},[z]);const P=async(E,U)=>{if(ie.current||E==="create"&&!N.trim())return;const te=new AbortController;ie.current=te,S(U?.id??"create"),p(""),W.current++;try{const he=await Ve(E==="create"?"/api/v1/projects":`/api/v1/projects/${U.id}/${E}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E==="create"?{name:N.trim()}:{}),signal:te.signal});if(te.signal.aborted)return;if(!Fy(he.project)||U&&U.id!==he.project.id)throw new Error("服务端返回了无效的项目状态,请刷新列表。");const k=he.project;s(T=>T&&{...T,projects:T.projects.some(K=>K.id===k.id)?T.projects.map(K=>K.id===k.id?k:K):[...T.projects,k]}),E==="create"&&D(""),E==="start"&&(H.current=k.id,Fr(k.id),k.status==="running"&&G(k)),E==="stop"&&(H.current===k.id&&(H.current=null,Fr(null)),_(null)),await se(te.signal)}catch(he){if(te.signal.aborted)return;he instanceof We&&he.status===401?F.current():p(he instanceof Error?he.message:"项目操作失败,请重试。")}finally{ie.current===te&&(ie.current=null),te.signal.aborted||S(null)}};return f?u.jsx(w.Fragment,{children:n(null)},"single-project"):o?u.jsxs(w.Fragment,{children:[g?u.jsxs("div",{className:"project-connection-note",role:"status",children:["项目状态暂时无法刷新,当前工作台会保留。",g]}):null,n(o,V)]},`${o.id}:${o.generation}`):u.jsxs("main",{className:"projects-page",children:[u.jsxs("header",{className:"projects-header",children:[u.jsxs("div",{className:"auth-brand",children:["CodeShell ",u.jsx("span",{children:"Hub"})]}),u.jsx("h1",{children:"你的项目"}),u.jsx("p",{children:"每个项目有独立的运行环境、文件、会话和配置。启动后进入同一个工作台。"})]}),b?u.jsx("p",{role:"status",children:"正在读取项目…"}):null,g?u.jsxs("div",{className:"form-error",role:"alert",children:[g,u.jsx("button",{className:"library-button",onClick:()=>{se()},children:"刷新项目"})]}):null,r?u.jsxs(u.Fragment,{children:[r.available?null:u.jsxs("p",{className:"form-error",role:"alert",children:["项目运行环境暂不可用。",r.error||"请检查服务端 Docker 是否已启动。"]}),u.jsxs("form",{className:"project-create",onSubmit:E=>{E.preventDefault(),P("create")},children:[u.jsxs("label",{children:["新项目名称",u.jsx("input",{value:N,maxLength:80,required:!0,placeholder:"例如:个人网站",onChange:E=>D(E.target.value)})]}),u.jsx("button",{className:"library-button primary",disabled:!!v||!N.trim(),type:"submit",children:v==="create"?"正在创建…":"创建项目"})]}),u.jsxs("section",{className:"projects-grid","aria-label":"项目列表",children:[r.projects.length===0?u.jsx("p",{className:"project-empty",children:"创建第一个项目,开始配置模型、添加技能和使用面板。"}):null,r.projects.map(E=>u.jsxs("article",{className:"project-card",children:[u.jsxs("div",{className:"project-card-heading",children:[u.jsx("h2",{children:E.name}),u.jsx("span",{className:`project-status ${E.status}`,children:zE[E.status]})]}),u.jsxs("p",{className:"project-date",children:["创建于 ",new Date(E.createdAt).toLocaleDateString()]}),E.error?u.jsx("p",{className:"form-error",role:"alert",children:E.error}):null,u.jsxs("div",{className:"library-actions",children:[u.jsx("button",{className:"library-button primary",disabled:!!v||!r.available||E.status==="starting"||E.status==="stopping",onClick:()=>E.status==="running"?G(E):void P("start",E),children:v===E.id||E.status==="starting"||E.status==="stopping"?"正在处理…":E.status==="running"?"打开项目":"启动并打开"}),E.status==="running"?u.jsx("button",{className:"library-button",disabled:!!v,onClick:()=>_(E),children:"停止项目"}):null]})]},E.id))]})]}):null,z?u.jsxs("dialog",{className:"project-stop-confirm",ref:M,role:"alertdialog","aria-modal":"true","aria-labelledby":"project-stop-title",onCancel:E=>{E.preventDefault(),v||_(null)},children:[u.jsxs("h2",{id:"project-stop-title",children:["停止 ",z.name,"?"]}),u.jsx("p",{children:"正在运行的任务和面板进程会中断。项目文件和配置保留,可稍后重新启动。"}),u.jsxs("div",{className:"library-actions",children:[u.jsx("button",{className:"library-button primary",disabled:!!v,onClick:()=>_(null),children:"继续运行"}),u.jsx("button",{className:"library-button",disabled:!!v,onClick:()=>{P("stop",z)},children:"确认停止"})]})]}):null]})}function _E({setupToken:n}){const[i,r]=w.useState("checking"),[s,f]=w.useState(),[d,o]=w.useState(""),[m,g]=w.useState(""),[p,b]=w.useState(""),[y,v]=w.useState(n),[S,N]=w.useState(""),[D,z]=w.useState(!1),_=w.useRef(!1),M=w.useRef(0),H=w.useRef(i);H.current=i;const oe=w.useCallback(ie=>{_.current&&(f(ie?.session),r(ie===null?"legacy":ie.initialized?ie.authenticated?"authenticated":"login":"setup"),N(""),ie?.initialized&&v(""))},[]),ce=w.useCallback(async()=>{const ie=++M.current;try{const F=await Sv();ie===M.current&&oe(F)}catch(F){if(!_.current||ie!==M.current||H.current==="authenticated"||H.current==="legacy")return;r("error"),N(F instanceof Error?F.message:"无法连接服务端")}},[oe]);w.useEffect(()=>{_.current=!0,ce();const ie=()=>{ce()},F=()=>{document.visibilityState==="visible"&&ce()};return window.addEventListener("focus",ie),document.addEventListener("visibilitychange",F),()=>{_.current=!1,window.removeEventListener("focus",ie),document.removeEventListener("visibilitychange",F)}},[ce]);const R=w.useCallback(()=>{M.current++,f(void 0),r("login"),g(""),N("登录已过期或此设备已被撤销,请重新登录。")},[]),W=async ie=>{if(ie.preventDefault(),!D){M.current++,z(!0),N("");try{const F=await qg(`/api/v1/auth/${i==="setup"?"setup":"login"}`,{username:d.trim(),password:m,deviceName:p.trim()||void 0,...i==="setup"?{token:y.trim()}:{}});if(!F.authenticated)throw new Error("登录失败,请重试。");M.current++,g(""),v(""),oe({initialized:!0,authenticated:!0,session:F.session})}catch(F){N(F instanceof Error?F.message:"登录失败,请重试。"),F instanceof We&&F.status===409&&ce()}finally{z(!1)}}};return i==="authenticated"?u.jsx(RE,{onAuthLost:R,children:(ie,F)=>u.jsx(Og,{session:s,hub:!0,onAuthLost:R,onCheckAuth:ce,projectName:ie?.name,onBackToProjects:F})}):i==="legacy"?u.jsx(Og,{session:s,hub:!1,onAuthLost:R,onCheckAuth:ce}):u.jsx("main",{className:"auth-page",children:u.jsxs("section",{className:"auth-card",children:[u.jsxs("div",{className:"auth-brand",children:["CodeShell ",u.jsx("span",{children:"Hub"})]}),i==="checking"?u.jsx("p",{role:"status",children:"正在连接你的工作空间…"}):null,i==="error"?u.jsxs(u.Fragment,{children:[u.jsx("p",{className:"form-error",role:"alert",children:S}),u.jsx("button",{className:"send",onClick:()=>{ce()},children:"重试连接"})]}):null,i==="setup"||i==="login"?u.jsxs("form",{onSubmit:ie=>{W(ie)},children:[u.jsx("h1",{children:i==="setup"?"创建管理员账号":"登录工作空间"}),u.jsx("p",{children:i==="setup"?"首次启动需要服务端提供的初始化令牌。创建后,可在其他设备使用此账号登录。":"连接服务端,继续你的会话与任务。"}),i==="setup"?u.jsxs("label",{children:["初始化令牌",u.jsx("input",{type:"password",autoComplete:"off",required:!0,value:y,onChange:ie=>v(ie.target.value)})]}):null,u.jsxs("label",{children:["用户名",u.jsx("input",{autoComplete:"username",required:!0,maxLength:64,value:d,onChange:ie=>o(ie.target.value)})]}),u.jsxs("label",{children:["密码",u.jsx("input",{type:"password",autoComplete:i==="setup"?"new-password":"current-password",required:!0,maxLength:256,minLength:i==="setup"?12:void 0,value:m,onChange:ie=>g(ie.target.value)})]}),i==="setup"?u.jsx("small",{children:"密码至少 12 个字符。"}):null,u.jsxs("label",{children:["设备名称 ",u.jsx("span",{children:"(可选)"}),u.jsx("input",{autoComplete:"off",maxLength:100,placeholder:"例如:我的笔记本",value:p,onChange:ie=>b(ie.target.value)})]}),S?u.jsx("p",{className:"form-error",role:"alert",children:S}):null,u.jsx("button",{className:"send",type:"submit",disabled:D,children:D?"正在连接…":i==="setup"?"创建并进入":"登录"})]}):null]})})}function DE(n="/"){"serviceWorker"in navigator&&window.isSecureContext&&navigator.serviceWorker.register(`${n}sw.js`).catch(()=>{})}const OE=jv(window.location,window.history);yv.createRoot(document.getElementById("root")).render(u.jsx(w.StrictMode,{children:u.jsx(_E,{setupToken:OE})}));DE("/");
@@ -7,7 +7,7 @@
7
7
  <link rel="manifest" href="/manifest.webmanifest" />
8
8
  <link rel="icon" type="image/svg+xml" href="/icon.svg" />
9
9
  <title>CodeShell Hub</title>
10
- <script type="module" crossorigin src="/assets/index-JhGBckTz.js"></script>
10
+ <script type="module" crossorigin src="/assets/index-Bshhn7qV.js"></script>
11
11
  <link rel="stylesheet" crossorigin href="/assets/index-Dz4kCU3p.css">
12
12
  </head>
13
13
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cjhyy/code-shell-web",
3
- "version": "0.9.17",
3
+ "version": "0.9.19",
4
4
  "description": "CodeShell web client logic layer — remote-app state (chatReducer + server-event fold), reconnecting WebSocket hook, pairing/device-credential/risk helpers, and the mobile i18n namespace. Browser-only (no Electron, no Node); seed of the standalone browser client.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,8 +24,8 @@
24
24
  "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true});require('node:fs').rmSync('dist-app',{recursive:true,force:true})\""
25
25
  },
26
26
  "dependencies": {
27
- "@cjhyy/code-shell-core": "0.9.17",
28
- "@cjhyy/code-shell-link": "0.9.17"
27
+ "@cjhyy/code-shell-core": "0.9.19",
28
+ "@cjhyy/code-shell-link": "0.9.19"
29
29
  },
30
30
  "peerDependencies": {
31
31
  "react": "19.2.6"