@kingsoftcloud/agentkit-harness-node 0.0.32 → 0.0.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/engine-view.html +1 -1
- package/dist/studio-tool-catalog.json +1 -1
- package/package.json +2 -2
- package/src/native/command-shell.mjs +16 -0
- package/src/native/engine-runtime.mjs +13 -8
- package/src/native/engine-server.mjs +3 -0
- package/src/native/engine-service.mjs +2 -2
- package/src/native/local-background.mjs +2 -2
- package/src/native/local-command-tools.mjs +23 -9
- package/src/native/workspace-search-worker.mjs +121 -0
- package/src/native/workspace-search.mjs +37 -0
- package/src/native/workspace-tools.mjs +8 -85
package/dist/engine-view.html
CHANGED
|
@@ -722,5 +722,5 @@ button.harness-tool-summary { border: 0; background: none; color: inherit; font:
|
|
|
722
722
|
.harness-activity-children { border-left: 1px solid var(--harness-border); margin: 8px 0 8px 7px; padding-left: 16px; display: flex; flex-direction: column; gap: 8px; }
|
|
723
723
|
`;var Ma=8,Oo=24,Ao=1;function za({clientHeight:e,scrollHeight:t,scrollTop:n},r){let i=Math.max(0,t-e),o={showTop:i>Ao&&n>Ao,showBottom:i>Ao&&n<i-Ao};return r?.showTop===o.showTop&&r?.showBottom===o.showBottom?r:o}function vy({showTop:e,showBottom:t}){if(!e&&!t)return;let n=e?`transparent 0px, black ${Oo}px`:`black 0px, black ${Oo}px`,r=t?`black calc(100% - ${Oo}px), transparent 100%`:`black calc(100% - ${Oo}px), black 100%`,i=`linear-gradient(to bottom, ${n}, ${r})`;return{WebkitMaskImage:i,maskImage:i,WebkitMaskRepeat:"no-repeat",maskRepeat:"no-repeat",WebkitMaskSize:"100% 100%",maskSize:"100% 100%"}}function wy(e){if(!e)return;let t="linear-gradient(to right, transparent 0, black 16px, black calc(100% - 16px), transparent 100%)";return{WebkitMaskImage:t,maskImage:t,WebkitMaskRepeat:"no-repeat",maskRepeat:"no-repeat",WebkitMaskSize:"100% 100%",maskSize:"100% 100%"}}function kp(e){let{createElement:t,useState:n,useCallback:r,useRef:i,useEffect:o,useMemo:l,Fragment:a}=e;function s(c){let{state:y,className:w,workspaceRoot:v,labels:x,locale:S,showPlanDock:z,theme:C="system",renderText:T,initiallyExpandedThoughts:H,initiallyExpandedTools:V,autoFollow:q,styleSheet:Q,onJumpLatest:$,onOpenFile:A,onCopy:B,onOpenTerminal:N,onRetrieveFullDiff:b,onInspectTool:ke,onOpenSubagent:Ae,loadImage:K}=c||{},[W,me]=n(()=>new Map((H||[]).map(J=>[J,!0]))),[_t,Tp]=n(()=>new Map((V||[]).map(J=>[J,!0]))),[Lp,Rp]=n(()=>new Map),[Fo,Aa]=n(!0),[Do,Mp]=n(!1),Et=i(null),Fa=i(new Set),Da=i(new Map);o(()=>{if(typeof window!="object"||typeof window.matchMedia!="function")return;let J=window.matchMedia("(prefers-reduced-motion: reduce)"),ce=()=>Mp(!!J.matches);return ce(),typeof J.addEventListener=="function"?(J.addEventListener("change",ce),()=>J.removeEventListener("change",ce)):(J.addListener(ce),()=>J.removeListener(ce))},[]),o(()=>{if(!q)return;let J=Et.current;if(!J||typeof J.addEventListener!="function")return;let ce=()=>{let ge=J.scrollHeight-J.scrollTop-J.clientHeight<Ma;Aa(ge)};return J.addEventListener("scroll",ce,{passive:!0}),()=>J.removeEventListener("scroll",ce)},[q]),o(()=>{q&&Fo&&Et.current&&(Et.current.scrollTop=Et.current.scrollHeight)},[y,Fo,q]),o(()=>{let J=Hr(y),ce=new Map(W),ge=!1;for(let ot of J){if(ot.kind!=="thought")continue;let Xr=Da.current.get(ot.id)??!1,de=!!ot.streaming;Xr&&!de&&!Fa.current.has(ot.id)&&ce.get(ot.id)!==!1&&(ce.set(ot.id,!1),ge=!0),Da.current.set(ot.id,de)}ge&&me(ce)},[y,W]);let zp=r(J=>{let ce=J.target;if(!ce||!ce.closest)return;let ge=ce.closest("[data-action]");if(ge){let de=ge.getAttribute("data-action");if(de==="jump-latest"){$?$():Et.current&&(Et.current.scrollTop=Et.current.scrollHeight,Aa(!0));return}if(de==="open-file"&&A){A({path:ge.getAttribute("data-path")||"",kind:ge.getAttribute("data-kind")||"file",callId:ge.getAttribute("data-call-id")||void 0});return}if(de==="copy"&&B){B(ge.getAttribute("data-copy-text")||"");return}if(de==="open-terminal"&&N){N({callId:ge.getAttribute("data-call-id")||"",cwd:ge.getAttribute("data-cwd")||void 0});return}if(de==="retrieve-diff"&&b){b({callId:ge.getAttribute("data-call-id")||"",path:ge.getAttribute("data-path")||""});return}if(de==="open-subagent"&&Ae){let It=ge.getAttribute("data-call-id"),Kt=y.items.find(Yn=>Yn.callId===It)?.child;Kt&&Ae({callId:It,...Kt});return}if(de==="inspect-tool"&&ke){ke({callId:ge.getAttribute("data-call-id")||""});return}}let ot=ce.closest('summary[data-testid="work-history-toggle"]');if(ot){J.preventDefault();let de=ot.parentElement,It=de.getAttribute("data-item-id");Rp(Kt=>new Map(Kt).set(It,!de.open));return}let Xr=ce.closest('summary[data-testid="thought-toggle"], summary[data-testid="tool-toggle"]');if(Xr){let de=Xr.parentElement,It=de.getAttribute("data-item-id"),Kt=de.getAttribute("data-call-id");J.preventDefault(),It?(Fa.current.add(It),me(Yn=>{let Xn=new Map(Yn);return Xn.set(It,!de.open),Xn})):Kt&&Tp(Yn=>{let Xn=new Map(Yn);return Xn.set(Kt,!de.open),Xn})}},[y,$,A,B,N,b,ke,Ae]),Pp={ref:Et,onClick:zp,className:w?`harness-timeline-shell ${w}`:"harness-timeline-shell","data-reduced-motion":Do?"true":"false","data-theme":C},ja=l(()=>({onOpenFile:A,onCopy:B,onOpenTerminal:N,onRetrieveFullDiff:b,onInspectTool:ke,onOpenSubagent:Ae,loadImage:K}),[A,B,N,b,ke,Ae,K]),$a=l(()=>new WeakMap,[_t,x,S,v,!!A,!!B,!!N,!!b,!!ke,!!Ae]),Op=l(()=>new WeakMap,[$a,Do]),Ap=yp(y,{thoughtOpen:W,toolOpen:_t,historyOpen:Lp,labels:x,locale:S,showPlanDock:z,workspaceRoot:v,following:Fo,rootProps:Pp,toolViewCache:$a,...ja}),Wa=u(Ap,T,ja,e,Do,Op);return Q===null?Wa:t(a,null,t("style",{"data-harness-ui":!0},Q===void 0?wp:Q),Wa)}function u(c,y,w,v,x,S){if(c==null||c===!1)return null;if(typeof c!="object")return c;let{createElement:z}=v,C=c.props?.["data-testid"],T=c.props||{};if(C==="model-retry-countdown")return z(f,{key:T["data-retry-at"],retryAt:T["data-retry-at"],zh:T["data-retry-language"]==="zh",React:v});if(C==="user-image")return z(g,{key:T["data-item-id"],image:T.image,loadImage:w.loadImage,id:T["data-item-id"]});if(C==="tool-block"&&S?.has(c))return S.get(c);if(C==="execute-command")return z(m,{key:T["data-call-id"],type:c.type,props:T,renderChildren:(c.children||[]).map($=>u($,y,w,v,x,S))});if(C==="thought-body")return z(k,{key:T["data-item-id"],streaming:T["data-streaming"]==="true",axis:"vertical",mask:"vertical",reducedMotion:x,renderChildren:(c.children||[]).map($=>u($,y,w,v,x,S)),type:c.type,props:c.props});if(C==="bash-output-preview-full"||C==="bash-result-output")return z(k,{key:T["data-call-id"]||C,streaming:T["data-streaming"]==="true",axis:"vertical",freezeWhileReading:!0,mask:"vertical",renderChildren:(c.children||[]).map($=>u($,y,w,v,x,S)),type:c.type,props:c.props});if(C==="thought-preview")return z(E,{key:T["data-item-id"]||C,reducedMotion:x,renderChildren:(c.children||[]).map($=>u($,y,w,v,x,S)),type:c.type,props:c.props});let H=C==="text-block"&&T["data-role"]!=="user",V=c.children?.[0]?.children?.[0],q=H&&y?[y(String(V??""),{streaming:T["data-streaming"]==="true"})]:(c.children||[]).map($=>u($,y,w,v,x,S)),Q=z(c.type,{key:T["data-item-id"]??T["data-call-id"],...T},...q);return C==="tool-block"&&S?.set(c,Q),Q}function f({retryAt:c,zh:y,React:w}){let v=()=>Math.max(0,Math.ceil((c-Date.now())/1e3)),[x,S]=w.useState(v);return w.useEffect(()=>{let z,C=()=>{let T=v();S(T),T>0&&(z=setTimeout(C,Math.max(1,c-Date.now()-(T-1)*1e3)))};return C(),()=>clearTimeout(z)},[c]),w.createElement("span",{"data-testid":"model-retry-countdown","aria-hidden":"true"},x?y?`${x} \u79D2\u540E`:`in ${x}s`:y?"\u5373\u5C06\u91CD\u8BD5":"Retry due")}function g({image:c,loadImage:y,id:w}){let{attachment:v,previewUrl:x}=c,[S,z]=n(()=>So(x??y?.peek?.(v))),[C,T]=n(!1),[H,V]=n(0),[q,Q]=n(!1),$=i(null),A=JSON.stringify(v??x);o(()=>{let N=!0;return T(!1),z(So(x??(v&&y?.peek?.(v)))),v&&y?Promise.resolve().then(()=>y(v)).then(b=>{if(N){let ke=So(b);z(ke),T(!ke)}}).catch(()=>{N&&T(!0)}):x||T(!0),()=>{N=!1}},[A,y,H]),o(()=>{q?$.current?.showModal?.():$.current?.close?.()},[q]);let B=v?.name||c.name||"\u56FE\u7247";return t("span",{className:"harness-user-image","data-testid":"user-image","data-item-id":w},S?t("button",{type:"button",className:"harness-image-preview","aria-label":`\u67E5\u770B\u56FE\u7247\uFF1A${B}`,onClick:()=>Q(!0)},t("img",{src:S,alt:B,onError:()=>{z(null),T(!0)}})):t("button",{type:"button",disabled:!C,onClick:()=>V(N=>N+1)},C?`${B} \xB7 \u70B9\u51FB\u91CD\u65B0\u52A0\u8F7D`:`${B} \xB7 \u52A0\u8F7D\u4E2D\u2026`),q?t("dialog",{ref:$,className:"harness-image-dialog","aria-label":`\u56FE\u7247\u9884\u89C8\uFF1A${B}`,onClose:()=>Q(!1)},t("button",{type:"button",onClick:()=>Q(!1)},"\u5173\u95ED"),t("img",{src:S,alt:B})):null)}function m({renderChildren:c,type:y,props:w}){let v=i(null),[x,S]=n(!1),[z,C]=n(!1);return o(()=>{let T=v.current;if(!T||x)return;let H=()=>C(T.scrollHeight>T.clientHeight+1);if(H(),typeof ResizeObserver>"u")return;let V=new ResizeObserver(H);return V.observe(T),()=>V.disconnect()},[c,x]),e.createElement(y,w,e.createElement("div",{ref:v,className:"harness-command-viewport","data-expanded":String(x),tabIndex:x?0:void 0},c[0]),z||x?e.createElement("button",{type:"button",className:"harness-command-toggle","aria-expanded":x,onClick:()=>{v.current&&(v.current.scrollTop=0),S(T=>!T)}},w[x?"data-collapse-label":"data-expand-label"]):null,...c.slice(1))}function k({streaming:c,axis:y,mask:w,freezeWhileReading:v=!1,reducedMotion:x,renderChildren:S,type:z,props:C}){let T=i(null),H=i(!0),V=i(0),q=i(c),[Q,$]=n(null),[A,B]=n({showTop:!1,showBottom:!1}),N=v?Q===null:H.current,b=Q??S;o(()=>{let K=T.current;K&&(c&&(q.current=!0),(v?q.current:c)&&N&&(y==="vertical"?K.scrollTop=K.scrollHeight:K.scrollLeft=K.scrollWidth,V.current=K.scrollTop),w==="vertical"&&B(W=>za({clientHeight:K.clientHeight,scrollHeight:K.scrollHeight,scrollTop:K.scrollTop},W)))}),o(()=>{let K=T.current;if(!K||w!=="vertical"||typeof ResizeObserver>"u")return;let W=()=>{B(_t=>za({clientHeight:K.clientHeight,scrollHeight:K.scrollHeight,scrollTop:K.scrollTop},_t))};W();let me=new ResizeObserver(W);return me.observe(K),()=>me.disconnect()},[w]);let ke=K=>{let W=K.currentTarget,me=y==="vertical"?W.scrollHeight-W.scrollTop-W.clientHeight<=Ma:W.scrollWidth-W.scrollLeft-W.clientWidth<=Ma;v&&q.current&&N&&W.scrollTop<V.current&&!me?$(b):v&&!N&&me?$(null):!v&&H.current&&W.scrollTop<V.current&&!me?H.current=!1:!v&&!H.current&&me&&(H.current=!0),V.current=W.scrollTop,w==="vertical"&&B(_t=>za({clientHeight:W.clientHeight,scrollHeight:W.scrollHeight,scrollTop:W.scrollTop},_t))};o(()=>{c&&(H.current=!0)},[c]);let Ae={ref:T,onScroll:ke,"data-following":N?"true":"false"};if(w==="vertical"){let K=A.showTop&&A.showBottom?"both":A.showTop?"top":A.showBottom?"bottom":"none";Ae["data-reasoning-scroll-mask"]=K;let W=vy(A);W&&(Ae.style={...C.style||{},...W})}return e.createElement(z,{...C,...Ae},...b)}function E({reducedMotion:c,renderChildren:y,type:w,props:v}){let x={key:v["data-line-key"],text:v["data-line-text"]},[S,z]=n(()=>({current:x,previous:null,animate:!1})),C=i(null);o(()=>(C.current=Ef(x,A=>z(B=>A.refresh?{...B,current:A.current}:A)),()=>{C.current.dispose(),C.current=null}),[]),o(()=>{C.current?.update(x,!c)},[x.key,x.text,c]);let T=i(null),[H,V]=n(!1);o(()=>{let A=T.current;if(!A)return;A.scrollLeft=A.scrollWidth;let B=A.scrollWidth>A.clientWidth+1;if(V(ke=>ke===B?ke:B),typeof ResizeObserver>"u")return;let N=()=>{A.scrollLeft=A.scrollWidth,V(A.scrollWidth>A.clientWidth+1)},b=new ResizeObserver(N);return b.observe(A),()=>b.disconnect()});let q=H?"both":"none",Q=wy(H),$={ref:T,"data-reasoning-streaming-mask":q};return Q&&($.style={...v.style||{},...Q}),e.createElement(w,{...v,...$},e.createElement("span",{className:"harness-summary-roll","data-animated":String(S.animate)},S.animate&&S.previous?e.createElement("span",{key:"out:"+S.previous.key,className:"harness-summary-out","aria-hidden":!0},S.previous.text):null,e.createElement("span",{key:S.current.key,className:S.animate?"harness-summary-in":""},S.current.text)))}function I({path:c,seq:y,resolve:w,zh:v,application:x=!1}){let[S,z]=n(null),[C,T]=n(!1),[H,V]=n(!1),q=i(null);if(o(()=>{let N=new AbortController;return q.current=N,w({path:c,seq:y,application:x},N.signal).then(b=>{N.signal.aborted||z(b)}).catch(()=>{}),()=>N.abort()},[c,y,w,x]),!S?.href)return null;let Q=x?v?"\u8FD0\u884C\u4E2D\u7684\u5E94\u7528":"Running application":c.split("/").at(-1),$=v?`\u6253\u5F00 ${Q}`:`Open ${Q}`,A=async()=>{let N=q.current.signal;V(!1),T(!0);try{await S.openInSidebar(N)}catch{N.aborted||V(!0)}finally{N.aborted||T(!1)}},B=(N,b)=>t("a",{href:S.href,target:"_blank",rel:"noopener noreferrer","aria-label":b},N);return t("div",{className:"harness-delivery","data-testid":"web-delivery"},t("span",{className:"harness-delivery-icon"},t("svg",{viewBox:"0 0 24 24",width:20,height:20,fill:"none",stroke:"currentColor",strokeWidth:1.5,"aria-hidden":!0},t("circle",{cx:12,cy:12,r:9}),t("ellipse",{cx:12,cy:12,rx:4,ry:9}),t("path",{d:"M3 12h18"}))),t("span",{className:"harness-delivery-name"},t("strong",{title:c},Q),t("small",null,x?c:v?"\u7F51\u7AD9 \xB7 HTML":"Website \xB7 HTML")),S.openInSidebar?t("div",{className:"harness-delivery-actions"},t("button",{type:"button",disabled:C,onClick:A,"aria-label":$},C?v?"\u6B63\u5728\u6253\u5F00\u2026":"Opening\u2026":v?"\u6253\u5F00":"Open"),t("details",{className:"harness-delivery-menu"},t("summary",{"aria-label":v?"\u66F4\u591A\u6253\u5F00\u65B9\u5F0F":"More ways to open"},t("svg",{width:14,height:14,viewBox:"0 0 24 24","aria-hidden":!0,fill:"none",stroke:"currentColor"},t("path",{d:"m6 9 6 6 6-6",strokeWidth:2}))),B(v?"\u5728\u65B0\u6807\u7B7E\u9875\u6253\u5F00":"Open in a new tab")),H?t("span",{role:"status"},v?"\u65E0\u6CD5\u6253\u5F00\u4FA7\u680F\u9884\u89C8":"Could not open the sidebar preview"):null):B(v?"\u6253\u5F00":"Open",$))}function O({seq:c,load:y,openFile:w,resolveWebDelivery:v,deliveries:x,zh:S}){let[z,C]=n(null);o(()=>{let N=new AbortController;if(!(!y||c===void 0))return y(c,N.signal).then(b=>{N.signal.aborted||C(b)}).catch(()=>{}),()=>N.abort()},[c,y]);let{files:T=[],screenshots:H=[],truncated:V,application:q}=z??{},Q=N=>Number.isSafeInteger(N.added)&&N.added>=0&&Number.isSafeInteger(N.removed)&&N.removed>=0,$=(N,b)=>t("span",{className:"harness-delivery-delta"},t("span",null,`+${N}`),t("span",null,`\u2212${b}`)),A=T.length&&!V&&T.every(Q)?$(T.reduce((N,b)=>N+b.added,0),T.reduce((N,b)=>N+b.removed,0)):null,B=S?`${T.length}${V?"+":""} \u4E2A\u6587\u4EF6\u5DF2\u66F4\u6539`:`${T.length}${V?"+":""} ${T.length===1?"file":"files"} changed`;return t(e.Fragment,null,...v?[...q?[{path:q.path,seq:c,application:!0}]:[],...(x??[]).filter(N=>N.path!==q?.path)].map(N=>t(I,{key:N.path,...N,resolve:v,zh:S})):[],T.length?t("details",{className:"harness-delivery-changes","data-testid":"delivery-changes"},t("summary",null,B,A),t("ul",null,...T.map(N=>t("li",{key:N.path},N.deleted||!w?t("span",null,N.path):t("button",{type:"button",onClick:()=>w({path:N.path,kind:"file"})},N.path),Q(N)?$(N.added,N.removed):null)))):null,...H.map(({path:N,href:b})=>t("a",{key:N,className:"harness-delivery-image","data-testid":"delivery-screenshot",href:b,target:"_blank",rel:"noopener noreferrer"},t("img",{src:b,alt:N.split("/").at(-1),loading:"lazy"}))))}function p({state:c,reply:y,onCopy:w,onBranch:v,assistantActions:x,containerProps:S,deliveries:z,resolveWebDelivery:C,deliverySeq:T,loadDeliveryEvidence:H,locale:V="zh-CN",...q}){let[Q,$]=n(null),A=c.items.find(W=>W.id===c.finalAnswerId),B=async()=>{try{let W=A.sourceMessageId?c.items.filter(me=>me.kind==="text"&&me.sourceMessageId===A.sourceMessageId).map(me=>me.text).join(`
|
|
724
724
|
|
|
725
|
-
`):A.text;await(w?w(W):navigator.clipboard.writeText(W)),$("copied")}catch{$("failed")}},N=V.startsWith("zh"),b=Q==="copied"?N?"\u5DF2\u590D\u5236":"Copied":N?"\u590D\u5236\u56DE\u590D":"Copy reply",ke=N?"\u4ECE\u8FD9\u91CC\u65B0\u5EFA\u5206\u652F":"Branch from here",Ae=(W,me,_t)=>t("button",{type:"button",title:W,"aria-label":W,onClick:me},t("svg",{viewBox:"0 0 24 24",width:16,height:16,fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},t("path",{d:_t}))),K=y?.time??c.taskEndedAt;return t("article",{...S,className:"harness-turn","data-testid":"harness-turn"},t(s,{state:c,onCopy:w,locale:V,...q}),c.taskState==="failed"&&c.taskError?t("details",{className:"harness-turn-error"},t("summary",null,N?"\u672C\u8F6E\u672A\u5B8C\u6210\uFF0C\u67E5\u770B\u539F\u56E0":"This turn did not complete. View reason"),t("p",null,c.taskError)):c.taskState==="paused"&&c.taskReason==="provider_unavailable"&&c.taskMessage?t("p",{className:"harness-turn-model-pause",role:"status"},c.taskMessage):null,A?.kind==="text"&&!A.streaming&&(C||H)?t(O,{key:T,seq:T,load:H,deliveries:z,openFile:q.onOpenFile,resolveWebDelivery:C,zh:N}):null,A?.kind==="text"&&!A.streaming?t("div",{className:"harness-reply-actions",role:"group","aria-label":N?"\u56DE\u590D\u64CD\u4F5C":"Reply actions"},Ae(b,B,Q==="copied"?"m5 12 4 4L19 6":"M8 8h11v12H8zM5 16H4V4h11v1"),x,y?.branchable&&v?Ae(ke,()=>v(y.seq),"M5 19 19 5m-6 0h6v6M5 10v9h9"):null,typeof K=="number"&&Number.isFinite(K)?t("time",{dateTime:new Date(K).toISOString()},new Intl.DateTimeFormat(V,{hour:"2-digit",minute:"2-digit",hour12:!1}).format(K)):null,Q==="failed"?t("span",{role:"status"},N?"\u65E0\u6CD5\u590D\u5236":"Unable to copy"):null):null)}function d({state:c,loading:y,error:w,omittedRows:v=0,omittedChars:x=0,labels:S={},...z}){return e.createElement("section",{className:"harness-subagent-pane","data-testid":"subagent-pane","aria-readonly":!0},w?e.createElement("p",{role:"alert"},w):y?e.createElement("p",{role:"status"},S.childSyncing||"Syncing"):null,v||x?e.createElement("p",{className:"harness-subagent-window-notice"},S.childOmitted||"Earlier rows or long fields are omitted in this observation window."):null,c?e.createElement(s,{state:c,labels:S,...z}):null)}return{HarnessTimeline:s,HarnessTurn:p,SubagentPane:d}}function qn(){return{protocolVersion:1,taskId:null,taskTitle:null,runId:null,taskState:R.Idle,taskReason:null,taskMessage:null,taskOutcome:null,taskSummary:null,taskError:null,taskStartedAt:null,taskEndedAt:null,finalAnswerId:null,verificationRequired:null,modelRequestActive:!1,modelRequestRetry:!1,modelRetryAttempt:void 0,modelRequestPurpose:null,modelWait:null,modelThinkingId:null,contextMarkers:[],subagents:new Map,items:[],seen:new Set,pendingThinking:new Set,plan:null,planSummary:null,lastSeq:null}}function ky(e,t){e||(e=qn());let n;try{n=Mf(t)}catch{return e}if(e.seen.has(n.id))return e;let r=Ly(e);return r.seen=new Set(e.seen),r.seen.add(n.id),r.items=e.items.slice(),r.pendingThinking=new Set(e.pendingThinking),n.seq!=null&&(r.lastSeq==null||n.seq>r.lastSeq)&&(r.lastSeq=n.seq),xy(r,n),r}function Sp(e,t){let n=e||qn();for(let r of Array.isArray(t)?t:[])n=ky(n,r);return n}function xy(e,t){switch(t.type){case M.TaskStarted:return Sy(e,t);case M.TaskState:return xp(e,t);case M.TaskFinished:return _y(e,t);case M.ModelWait:e.taskState===R.Running&&(e.modelWait={retryAt:t.retryAt,httpStatus:t.httpStatus,attempt:t.attempt,purpose:t.purpose});return;case M.ModelRequest:e.modelRetryAttempt=t.active&&t.retry?e.modelWait?.attempt:void 0,t.active&&(e.modelWait=null),t.active&&e.taskState===R.Paused&&["provider_unavailable","delivery_no_progress","delivery_repair_budget_exhausted"].includes(e.taskReason)&&xp(e,{state:R.Running,reason:null,message:null}),(!t.active||e.modelThinkingId!==t.itemId)&&Pa(e),e.modelRequestActive=t.active,e.modelRequestRetry=t.active&&t.retry===!0,e.modelRequestPurpose=t.active?t.purpose??null:null,e.modelThinkingId=t.active?t.itemId:null;return;case M.TextPreview:{if(!e.modelRequestActive||!t.responseId||t.responseId!==e.modelThinkingId||!t.itemId||!t.text)return;let n=Yr(e,t.itemId);if(n>=0&&!e.items[n].preview)return;Gr(e,t);let r={kind:"text",id:t.itemId,text:t.text,responseId:t.responseId,streaming:!0,preview:!0,receivedChars:t.receivedChars};n>=0?e.items[n]=r:e.items.push(r);return}case M.TextDelta:return Ey(e,t);case M.TextDone:return Iy(e,t);case M.ThinkingStart:return Cy(e,t);case M.ThinkingDelta:return Ny(e,t);case M.ThinkingDone:return _p(e,t);case M.SubagentBound:{if(!t.callId)return;e.subagents=new Map(e.subagents??[]),e.subagents.set(t.callId,t.child);let n=Ep(e,t.callId);n>=0&&(hn(e,n).child=t.child);return}case M.ToolPreview:{if(!t.previewId)return;Gr(e,t);let n=e.items.findIndex(i=>i.kind==="tool-preview"&&i.id===t.previewId),r={kind:"tool-preview",id:t.previewId,name:t.name,input:t.input,receivedChars:t.receivedChars,streaming:!0,...t.responseId?{responseId:t.responseId}:{}};n>=0?e.items[n]=r:e.items.push(r);return}case M.ToolScheduled:return Kn(e,t,j.Scheduled);case M.ToolStarted:return Kn(e,t,j.Running);case M.ToolState:return Kn(e,t,t.status,t);case M.ToolProgress:return Kn(e,t,j.Running,t);case M.ToolResult:return Kn(e,t,j.Completed,t);case M.ToolError:return Kn(e,t,j.Failed,t);case M.ContextMarker:{let n=[...e.contextMarkers??[]],r=n.findIndex(i=>i.id===t.marker.id);r<0?n.push(t.marker):n[r]=t.marker,e.contextMarkers=n;return}case M.PlanUpdated:return Ty(e,t);default:return e}}function Sy(e,t){if(e.taskId=t.taskId||e.taskId,e.taskTitle=t.title||e.taskTitle,e.runId=t.runId||e.runId,la(e.taskState,R.Running)||e.taskState===R.Idle)e.taskState=R.Running;else return;e.taskOutcome=null,e.taskSummary=null,e.taskError=null,e.taskReason=null,e.taskMessage=null,t.startedAt!==void 0&&(e.taskStartedAt=t.startedAt),e.taskEndedAt=null,e.finalAnswerId=null}function Pa(e){e.modelThinkingId&&(_p(e,{itemId:e.modelThinkingId}),e.items=e.items.filter(t=>!(t.kind==="tool-preview"||t.preview===!0)||t.responseId!==e.modelThinkingId))}function xp(e,t){la(e.taskState,t.state)&&(e.taskState=t.state,t.state!==R.Running&&(Pa(e),e.modelWait=null,e.modelRequestActive=!1,e.modelRequestRetry=!1,e.modelRetryAttempt=void 0,e.modelRequestPurpose=null,e.modelThinkingId=null),e.taskReason=t.reason,e.taskMessage=t.message,(t.state===R.Running||t.state===R.Recovered)&&(e.taskOutcome=null,e.taskError=null))}function _y(e,t){Pa(e),e.modelWait=null,e.modelRequestActive=!1,e.modelRequestRetry=!1,e.modelRetryAttempt=void 0,e.modelRequestPurpose=null,e.modelThinkingId=null,e.verificationRequired=t.verificationRequired,e.taskOutcome=t.outcome,e.taskSummary=t.summary,e.taskError=t.error||null,e.taskReason=t.reason||null,e.taskEndedAt=t.endedAt??null,e.finalAnswerId=["completed","unverified"].includes(t.outcome)&&!t.error&&t.executionState!=="interrupted"?t.finalAnswerId??null:null,t.outcome===it.Completed?e.taskState=R.Completed:t.outcome===it.Cancelled?e.taskState=R.Cancelled:t.outcome===it.Failed?e.taskState=R.Failed:t.outcome===it.Blocked?e.taskState=R.Blocked:t.outcome===it.Unverified&&(e.taskState=R.Unverified),t.executionState===R.Interrupted&&(e.taskState=R.Interrupted);for(let n=0;n<e.items.length;n+=1){let r=e.items[n],i=r.streaming,o=r.kind==="tool"&&(r.status===j.Scheduled||r.status===j.Running);(i||o)&&(e.items[n]={...r,streaming:!1,...o?{status:j.Interrupted}:{}})}e.pendingThinking=new Set}function Ey(e,t){if(!t.itemId)return;t.delta&&Gr(e,t);let n=Yr(e,t.itemId);if(n>=0){let r=hn(e,n);r.text=(r.text||"")+t.delta,r.streaming=!0,t.responseId&&(r.responseId=t.responseId);return}e.items.push({kind:"text",id:t.itemId,text:t.delta,streaming:!0,...t.responseId?{responseId:t.responseId}:{}})}function Iy(e,t){t.text&&Gr(e,t);let n=Yr(e,t.itemId);if(n>=0&&e.items[n].kind==="text"){let r=hn(e,n);t.text!==void 0&&(r.text=t.text),r.streaming=!1,t.sourceMessageId&&(r.sourceMessageId=t.sourceMessageId),t.responseId&&(r.responseId=t.responseId),t.role==="user"&&t.images&&(r.images=t.images)}else t.itemId&&(t.text||t.images?.length)&&e.items.push({kind:"text",id:t.itemId,text:t.text??"",role:t.role??"assistant",streaming:!1,...t.images?.length?{images:t.images}:{},...t.responseId?{responseId:t.responseId}:{},...t.sourceMessageId?{sourceMessageId:t.sourceMessageId}:{}})}function Cy(e,t){t.itemId&&e.pendingThinking.add(t.itemId)}function Ny(e,t){if(!t.itemId||!t.delta&&e.pendingThinking.has(t.itemId))return;let n=Yr(e,t.itemId);if(n>=0){let r=hn(e,n);r.text=(r.text||"")+t.delta,r.streaming=!0,t.responseId&&(r.responseId=t.responseId);return}t.delta&&(e.pendingThinking.delete(t.itemId),e.items.push({kind:"thought",id:t.itemId,text:t.delta,streaming:!0,provider:!0,...t.responseId?{responseId:t.responseId}:{}}))}function _p(e,t){e.pendingThinking.delete(t.itemId);let n=Yr(e,t.itemId);if(n>=0&&e.items[n].kind==="thought"){let r=hn(e,n);t.text!==void 0&&(r.text=t.text),r.streaming=!1,t.sourceMessageId&&(r.sourceMessageId=t.sourceMessageId),t.responseId&&(r.responseId=t.responseId),t.duration!=null&&(r.duration=t.duration)}else t.itemId&&t.text&&e.items.push({kind:"thought",id:t.itemId,text:t.text,streaming:!1,provider:!0,...t.responseId?{responseId:t.responseId}:{},...t.sourceMessageId?{sourceMessageId:t.sourceMessageId}:{},...t.duration!=null?{duration:t.duration}:{}})}function Kn(e,t,n,r){if(!t.callId)return;n===j.Scheduled&&Gr(e,t);let i=Ep(e,t.callId);if(i>=0){let l=hn(e,i);if([j.Completed,j.Failed,j.NotDispatched].includes(l.status)&&![j.Completed,j.Failed,j.NotDispatched].includes(n)){t.type===M.ToolScheduled&&(l.name=t.name||l.name,l.input=t.input,t.responseId&&(l.responseId=t.responseId));return}t.type===M.ToolScheduled&&(l.name=t.name||l.name,l.input=t.input,t.responseId&&(l.responseId=t.responseId)),e.subagents?.has(t.callId)&&(l.child=e.subagents.get(t.callId)),r&&t.type===M.ToolProgress&&(l.progress=r.progress||r.message||null,r.display&&r.display.kind&&(l.display=r.display)),r&&t.type===M.ToolResult&&(l.result=r.result,l.display=r.display),r&&t.type===M.ToolError&&(l.error=r.error),t.type===M.ToolState&&(l.progress=t.message),l.status=n;return}let o={kind:"tool",callId:t.callId,...t.responseId?{responseId:t.responseId}:{},...e.subagents?.has(t.callId)?{child:e.subagents.get(t.callId)}:{},name:t.name||"tool",input:t.input||{},status:n};r&&t.type===M.ToolResult&&(o.result=r.result,o.display=r.display),r&&t.type===M.ToolError&&(o.error=r.error),r&&t.type===M.ToolProgress&&(o.progress=r.progress||r.message||null,r.display&&r.display.kind&&(o.display=r.display)),e.items.push(o)}function Gr(e,t){if(t.responseId)for(let n=0;n<e.items.length;n++){let r=e.items[n];r.kind==="thought"&&r.streaming&&r.responseId===t.responseId&&(hn(e,n).streaming=!1)}}function Ty(e,t){e.plan=t.items.length?t.items:null;let n=t.items.filter(l=>l.status==="completed").length,r=Number.isSafeInteger(t.totalCount)&&t.totalCount>=t.items.length?t.totalCount:t.items.length,i=r-t.items.length,o=Number.isSafeInteger(t.completedCount)&&t.completedCount>=n&&t.completedCount<=n+i?t.completedCount:n;e.planSummary={totalCount:r,completedCount:o,omittedItems:i}}function Yr(e,t){for(let n=0;n<e.items.length;n+=1)if(e.items[n].id===t)return n;return-1}function Ep(e,t){for(let n=0;n<e.items.length;n+=1){let r=e.items[n];if(r.kind==="tool"&&r.callId===t)return n}return-1}function hn(e,t){let n={...e.items[t]};return e.items[t]=n,n}function Ly(e){return Object.assign({},e,{items:e.items,seen:e.seen,pendingThinking:e.pendingThinking,plan:e.plan})}var Ry="agentkit.engine-event/v1",Oa="agentkit.engine-view/v1",My="submit_final_output",zy=new Set(["completed","unverified","blocked","failed","cancelled"]),Be=e=>typeof e=="string"&&e.trim().length>0,Py=e=>e==null?{}:typeof e=="object"?e:{value:e};function Oy(e){let t=se(e.title)?.family,{ok:n,path:r,diff_additions:i,diff_deletions:o}=e.result??{};if(!(!["edit","write"].includes(t)||n!==!0||!Be(r)||![i,o].every(l=>Number.isSafeInteger(l)&&l>=0)))return{kind:"file_edit",files:[{path:r,changeStat:{added:i,removed:o},operationKind:t==="write"?"write":"edit"}]}}function Ay(e){return e.title==="failed"||e.status==="failed"?"failed":["canceled","cancelled"].includes(e.title)||["canceled","cancelled"].includes(e.status)?"cancelled":e.status==="verified"?"completed":zy.has(e.status)?e.status:e.title==="completed"?"completed":"unverified"}function Fy(e,t){let n=e?.error_type??e?.code??e?.error_code,r=e?.error_message??e?.message;if(!Be(n))return{message:Be(r)?r:`\u5DE5\u5177 ${t??""} \u672A\u6210\u529F`.trim()};let i=n==="command_policy_blocked"&&e?.executed===!1?e.finding?.detail:void 0;return{code:n,...Be(i)?{message:i}:Be(r)?{message:r}:{},...Number.isSafeInteger(e.failed_edit_index)&&e.failed_edit_index>=0?{failed_edit_index:e.failed_edit_index}:{}}}function Dy(e,{runId:t="run",time:n,startedAt:r=n}={}){if(!e||e.schema!==Ry||!Number.isSafeInteger(e.seq))return[];let i=Eo,o=a=>`${t}:${e.seq}:${a}`,l=typeof e.requestId=="string"&&/^[a-f0-9]{64}$/.test(e.requestId)?`${t}:thought:${e.requestId}`:o("thought");switch(e.kind){case"run.started":return[{v:i,id:o("start"),type:"task.started",taskId:t,runId:t,startedAt:r}];case"todo.initialized":case"todo.updated":return Object.hasOwn(e,"plan")?[{v:i,id:o("todo"),type:"plan.updated",items:e.plan?.items??[],completedCount:e.plan?.completedCount,totalCount:e.plan?.totalCount}]:[];case"effect.prepared":case"effect.settled":return e.category==="model"&&e.title==="request"?[{v:i,id:o("model-request"),type:"model.request",active:e.kind==="effect.prepared",retry:e.kind==="effect.prepared"&&e.retry===!0,...e.purpose==="compaction"?{purpose:"compaction"}:{},itemId:l}]:[];case"model.completed":{let a=[];if(Be(e.thinking)&&a.push({v:i,id:o("thought-done"),type:"thinking.done",itemId:l,text:e.thinking}),Be(e.detail)&&(e.title==="initial_plan"||Array.isArray(e.calls)&&e.calls.length)){let s=`${t}:note:${e.seq}`;a.push({v:i,id:o("note"),type:"text.delta",itemId:s,delta:e.detail},{v:i,id:o("note-done"),type:"text.done",itemId:s})}for(let s of Array.isArray(e.calls)?e.calls:[])!Be(s?.callId)||!Be(s?.name)||s.name===My||a.push({v:i,id:o(`call:${s.callId}`),type:"tool.scheduled",callId:s.callId,name:s.name,input:Py(s.arguments)},{v:i,id:o(`run:${s.callId}`),type:"tool.started",callId:s.callId});return a}case"model.stream_interrupted":return Be(e.thinking)?[{v:i,id:o("thought-done"),type:"thinking.done",itemId:l,text:e.thinking}]:[];case"tool.completed":{if(!Be(e.callId))return[];if(e.status==="uncertain")return[{v:i,id:o("uncertain"),type:"tool.state",callId:e.callId,status:"uncertain"}];let a=e.status==="ok"?Oy(e):void 0;if(e.status!=="ok")return[{v:i,id:o("error"),type:"tool.error",callId:e.callId,error:Fy(e.result,e.title)}];let s=[{v:i,id:o("result"),type:"tool.result",callId:e.callId,result:e.result??null,...a?{display:a}:{}}];return e.title==="TodoWrite"&&Array.isArray(e.result?.todos)&&s.push({v:i,id:o("todo-receipt"),type:"plan.updated",items:e.result.todos.map((u,f)=>({...u,id:`todo:${f}`}))}),s}case"model.retry_scheduled":return Number.isSafeInteger(e.retryAt)&&e.retryAt>0?[{v:i,id:o("model-wait"),type:"model.wait",retryAt:e.retryAt,httpStatus:e.httpStatus,attempt:e.attempt,purpose:e.purpose}]:[];case"model.retry_exhausted":return[{v:i,id:o("paused"),type:"task.state",state:"paused",reason:"provider_unavailable",message:e.modelError}];case"run.paused":return[{v:i,id:o("paused"),type:"task.state",state:"paused",reason:e.reason,message:e.modelError}];case"run.terminal":{let a=[],s=`${t}:final`;return Be(e.detail)&&a.push({v:i,id:o("final"),type:"text.delta",itemId:s,delta:e.detail},{v:i,id:o("final-done"),type:"text.done",itemId:s}),e.title==="paused"?[...a,{v:i,id:o("paused"),type:"task.state",state:"paused",reason:e.reason??null}]:e.title==="interrupted"?[{v:i,id:o("finished"),type:"task.finished",outcome:"unverified",executionState:"interrupted",endedAt:n,reason:e.reason}]:[...a,{v:i,id:o("finished"),type:"task.finished",outcome:Ay(e),endedAt:n,...a.length?{finalAnswerId:s}:{},...e.reason?{reason:e.reason}:{},...Be(e.modelError)?{error:e.modelError}:{}}]}default:return[]}}function Ip(e,t){return(Array.isArray(e)?e:[]).flatMap(n=>Dy(n,t))}var jy="0.0.32",{HarnessTurn:$y}=kp(Gn.default),Cp=e=>{try{window.parent.postMessage({contract:Oa,...e},"*")}catch{}};function Wy(){let[e,t]=Gn.default.useState({runId:"run",state:qn(),theme:"system"});return Gn.default.useEffect(()=>{let n=o=>{if(o.source!==window.parent)return;let l=o.data;!l||l.contract!==Oa||(l.type==="theme"&&["light","dark","system"].includes(l.theme)?(document.documentElement.style.colorScheme=l.theme==="system"?"light dark":l.theme,t(a=>({...a,theme:l.theme}))):l.type==="reset"?t(a=>({...a,runId:String(l.runId||"run"),state:qn()})):l.type==="events"&&Array.isArray(l.events)&&t(a=>{let s=String(l.runId||a.runId),u=s===a.runId?a.state:qn();return{...a,runId:s,state:Sp(u,Ip(l.events,{runId:s}))}}))};window.addEventListener("message",n),Cp({type:"ready",version:jy});let r=document.getElementById("root"),i=new ResizeObserver(()=>Cp({type:"height",height:Math.ceil(r.getBoundingClientRect().height)}));return i.observe(r),()=>{window.removeEventListener("message",n),i.disconnect()}},[]),Gn.default.createElement($y,{state:e.state,theme:e.theme,autoFollow:!1,styleSheet:null})}(0,Np.createRoot)(document.getElementById("root")).render(Gn.default.createElement(Wy));})();
|
|
725
|
+
`):A.text;await(w?w(W):navigator.clipboard.writeText(W)),$("copied")}catch{$("failed")}},N=V.startsWith("zh"),b=Q==="copied"?N?"\u5DF2\u590D\u5236":"Copied":N?"\u590D\u5236\u56DE\u590D":"Copy reply",ke=N?"\u4ECE\u8FD9\u91CC\u65B0\u5EFA\u5206\u652F":"Branch from here",Ae=(W,me,_t)=>t("button",{type:"button",title:W,"aria-label":W,onClick:me},t("svg",{viewBox:"0 0 24 24",width:16,height:16,fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0},t("path",{d:_t}))),K=y?.time??c.taskEndedAt;return t("article",{...S,className:"harness-turn","data-testid":"harness-turn"},t(s,{state:c,onCopy:w,locale:V,...q}),c.taskState==="failed"&&c.taskError?t("details",{className:"harness-turn-error"},t("summary",null,N?"\u672C\u8F6E\u672A\u5B8C\u6210\uFF0C\u67E5\u770B\u539F\u56E0":"This turn did not complete. View reason"),t("p",null,c.taskError)):c.taskState==="paused"&&c.taskReason==="provider_unavailable"&&c.taskMessage?t("p",{className:"harness-turn-model-pause",role:"status"},c.taskMessage):null,A?.kind==="text"&&!A.streaming&&(C||H)?t(O,{key:T,seq:T,load:H,deliveries:z,openFile:q.onOpenFile,resolveWebDelivery:C,zh:N}):null,A?.kind==="text"&&!A.streaming?t("div",{className:"harness-reply-actions",role:"group","aria-label":N?"\u56DE\u590D\u64CD\u4F5C":"Reply actions"},Ae(b,B,Q==="copied"?"m5 12 4 4L19 6":"M8 8h11v12H8zM5 16H4V4h11v1"),x,y?.branchable&&v?Ae(ke,()=>v(y.seq),"M5 19 19 5m-6 0h6v6M5 10v9h9"):null,typeof K=="number"&&Number.isFinite(K)?t("time",{dateTime:new Date(K).toISOString()},new Intl.DateTimeFormat(V,{hour:"2-digit",minute:"2-digit",hour12:!1}).format(K)):null,Q==="failed"?t("span",{role:"status"},N?"\u65E0\u6CD5\u590D\u5236":"Unable to copy"):null):null)}function d({state:c,loading:y,error:w,omittedRows:v=0,omittedChars:x=0,labels:S={},...z}){return e.createElement("section",{className:"harness-subagent-pane","data-testid":"subagent-pane","aria-readonly":!0},w?e.createElement("p",{role:"alert"},w):y?e.createElement("p",{role:"status"},S.childSyncing||"Syncing"):null,v||x?e.createElement("p",{className:"harness-subagent-window-notice"},S.childOmitted||"Earlier rows or long fields are omitted in this observation window."):null,c?e.createElement(s,{state:c,labels:S,...z}):null)}return{HarnessTimeline:s,HarnessTurn:p,SubagentPane:d}}function qn(){return{protocolVersion:1,taskId:null,taskTitle:null,runId:null,taskState:R.Idle,taskReason:null,taskMessage:null,taskOutcome:null,taskSummary:null,taskError:null,taskStartedAt:null,taskEndedAt:null,finalAnswerId:null,verificationRequired:null,modelRequestActive:!1,modelRequestRetry:!1,modelRetryAttempt:void 0,modelRequestPurpose:null,modelWait:null,modelThinkingId:null,contextMarkers:[],subagents:new Map,items:[],seen:new Set,pendingThinking:new Set,plan:null,planSummary:null,lastSeq:null}}function ky(e,t){e||(e=qn());let n;try{n=Mf(t)}catch{return e}if(e.seen.has(n.id))return e;let r=Ly(e);return r.seen=new Set(e.seen),r.seen.add(n.id),r.items=e.items.slice(),r.pendingThinking=new Set(e.pendingThinking),n.seq!=null&&(r.lastSeq==null||n.seq>r.lastSeq)&&(r.lastSeq=n.seq),xy(r,n),r}function Sp(e,t){let n=e||qn();for(let r of Array.isArray(t)?t:[])n=ky(n,r);return n}function xy(e,t){switch(t.type){case M.TaskStarted:return Sy(e,t);case M.TaskState:return xp(e,t);case M.TaskFinished:return _y(e,t);case M.ModelWait:e.taskState===R.Running&&(e.modelWait={retryAt:t.retryAt,httpStatus:t.httpStatus,attempt:t.attempt,purpose:t.purpose});return;case M.ModelRequest:e.modelRetryAttempt=t.active&&t.retry?e.modelWait?.attempt:void 0,t.active&&(e.modelWait=null),t.active&&e.taskState===R.Paused&&["provider_unavailable","delivery_no_progress","delivery_repair_budget_exhausted"].includes(e.taskReason)&&xp(e,{state:R.Running,reason:null,message:null}),(!t.active||e.modelThinkingId!==t.itemId)&&Pa(e),e.modelRequestActive=t.active,e.modelRequestRetry=t.active&&t.retry===!0,e.modelRequestPurpose=t.active?t.purpose??null:null,e.modelThinkingId=t.active?t.itemId:null;return;case M.TextPreview:{if(!e.modelRequestActive||!t.responseId||t.responseId!==e.modelThinkingId||!t.itemId||!t.text)return;let n=Yr(e,t.itemId);if(n>=0&&!e.items[n].preview)return;Gr(e,t);let r={kind:"text",id:t.itemId,text:t.text,responseId:t.responseId,streaming:!0,preview:!0,receivedChars:t.receivedChars};n>=0?e.items[n]=r:e.items.push(r);return}case M.TextDelta:return Ey(e,t);case M.TextDone:return Iy(e,t);case M.ThinkingStart:return Cy(e,t);case M.ThinkingDelta:return Ny(e,t);case M.ThinkingDone:return _p(e,t);case M.SubagentBound:{if(!t.callId)return;e.subagents=new Map(e.subagents??[]),e.subagents.set(t.callId,t.child);let n=Ep(e,t.callId);n>=0&&(hn(e,n).child=t.child);return}case M.ToolPreview:{if(!t.previewId)return;Gr(e,t);let n=e.items.findIndex(i=>i.kind==="tool-preview"&&i.id===t.previewId),r={kind:"tool-preview",id:t.previewId,name:t.name,input:t.input,receivedChars:t.receivedChars,streaming:!0,...t.responseId?{responseId:t.responseId}:{}};n>=0?e.items[n]=r:e.items.push(r);return}case M.ToolScheduled:return Kn(e,t,j.Scheduled);case M.ToolStarted:return Kn(e,t,j.Running);case M.ToolState:return Kn(e,t,t.status,t);case M.ToolProgress:return Kn(e,t,j.Running,t);case M.ToolResult:return Kn(e,t,j.Completed,t);case M.ToolError:return Kn(e,t,j.Failed,t);case M.ContextMarker:{let n=[...e.contextMarkers??[]],r=n.findIndex(i=>i.id===t.marker.id);r<0?n.push(t.marker):n[r]=t.marker,e.contextMarkers=n;return}case M.PlanUpdated:return Ty(e,t);default:return e}}function Sy(e,t){if(e.taskId=t.taskId||e.taskId,e.taskTitle=t.title||e.taskTitle,e.runId=t.runId||e.runId,la(e.taskState,R.Running)||e.taskState===R.Idle)e.taskState=R.Running;else return;e.taskOutcome=null,e.taskSummary=null,e.taskError=null,e.taskReason=null,e.taskMessage=null,t.startedAt!==void 0&&(e.taskStartedAt=t.startedAt),e.taskEndedAt=null,e.finalAnswerId=null}function Pa(e){e.modelThinkingId&&(_p(e,{itemId:e.modelThinkingId}),e.items=e.items.filter(t=>!(t.kind==="tool-preview"||t.preview===!0)||t.responseId!==e.modelThinkingId))}function xp(e,t){la(e.taskState,t.state)&&(e.taskState=t.state,t.state!==R.Running&&(Pa(e),e.modelWait=null,e.modelRequestActive=!1,e.modelRequestRetry=!1,e.modelRetryAttempt=void 0,e.modelRequestPurpose=null,e.modelThinkingId=null),e.taskReason=t.reason,e.taskMessage=t.message,(t.state===R.Running||t.state===R.Recovered)&&(e.taskOutcome=null,e.taskError=null))}function _y(e,t){Pa(e),e.modelWait=null,e.modelRequestActive=!1,e.modelRequestRetry=!1,e.modelRetryAttempt=void 0,e.modelRequestPurpose=null,e.modelThinkingId=null,e.verificationRequired=t.verificationRequired,e.taskOutcome=t.outcome,e.taskSummary=t.summary,e.taskError=t.error||null,e.taskReason=t.reason||null,e.taskEndedAt=t.endedAt??null,e.finalAnswerId=["completed","unverified"].includes(t.outcome)&&!t.error&&t.executionState!=="interrupted"?t.finalAnswerId??null:null,t.outcome===it.Completed?e.taskState=R.Completed:t.outcome===it.Cancelled?e.taskState=R.Cancelled:t.outcome===it.Failed?e.taskState=R.Failed:t.outcome===it.Blocked?e.taskState=R.Blocked:t.outcome===it.Unverified&&(e.taskState=R.Unverified),t.executionState===R.Interrupted&&(e.taskState=R.Interrupted);for(let n=0;n<e.items.length;n+=1){let r=e.items[n],i=r.streaming,o=r.kind==="tool"&&(r.status===j.Scheduled||r.status===j.Running);(i||o)&&(e.items[n]={...r,streaming:!1,...o?{status:j.Interrupted}:{}})}e.pendingThinking=new Set}function Ey(e,t){if(!t.itemId)return;t.delta&&Gr(e,t);let n=Yr(e,t.itemId);if(n>=0){let r=hn(e,n);r.text=(r.text||"")+t.delta,r.streaming=!0,t.responseId&&(r.responseId=t.responseId);return}e.items.push({kind:"text",id:t.itemId,text:t.delta,streaming:!0,...t.responseId?{responseId:t.responseId}:{}})}function Iy(e,t){t.text&&Gr(e,t);let n=Yr(e,t.itemId);if(n>=0&&e.items[n].kind==="text"){let r=hn(e,n);t.text!==void 0&&(r.text=t.text),r.streaming=!1,t.sourceMessageId&&(r.sourceMessageId=t.sourceMessageId),t.responseId&&(r.responseId=t.responseId),t.role==="user"&&t.images&&(r.images=t.images)}else t.itemId&&(t.text||t.images?.length)&&e.items.push({kind:"text",id:t.itemId,text:t.text??"",role:t.role??"assistant",streaming:!1,...t.images?.length?{images:t.images}:{},...t.responseId?{responseId:t.responseId}:{},...t.sourceMessageId?{sourceMessageId:t.sourceMessageId}:{}})}function Cy(e,t){t.itemId&&e.pendingThinking.add(t.itemId)}function Ny(e,t){if(!t.itemId||!t.delta&&e.pendingThinking.has(t.itemId))return;let n=Yr(e,t.itemId);if(n>=0){let r=hn(e,n);r.text=(r.text||"")+t.delta,r.streaming=!0,t.responseId&&(r.responseId=t.responseId);return}t.delta&&(e.pendingThinking.delete(t.itemId),e.items.push({kind:"thought",id:t.itemId,text:t.delta,streaming:!0,provider:!0,...t.responseId?{responseId:t.responseId}:{}}))}function _p(e,t){e.pendingThinking.delete(t.itemId);let n=Yr(e,t.itemId);if(n>=0&&e.items[n].kind==="thought"){let r=hn(e,n);t.text!==void 0&&(r.text=t.text),r.streaming=!1,t.sourceMessageId&&(r.sourceMessageId=t.sourceMessageId),t.responseId&&(r.responseId=t.responseId),t.duration!=null&&(r.duration=t.duration)}else t.itemId&&t.text&&e.items.push({kind:"thought",id:t.itemId,text:t.text,streaming:!1,provider:!0,...t.responseId?{responseId:t.responseId}:{},...t.sourceMessageId?{sourceMessageId:t.sourceMessageId}:{},...t.duration!=null?{duration:t.duration}:{}})}function Kn(e,t,n,r){if(!t.callId)return;n===j.Scheduled&&Gr(e,t);let i=Ep(e,t.callId);if(i>=0){let l=hn(e,i);if([j.Completed,j.Failed,j.NotDispatched].includes(l.status)&&![j.Completed,j.Failed,j.NotDispatched].includes(n)){t.type===M.ToolScheduled&&(l.name=t.name||l.name,l.input=t.input,t.responseId&&(l.responseId=t.responseId));return}t.type===M.ToolScheduled&&(l.name=t.name||l.name,l.input=t.input,t.responseId&&(l.responseId=t.responseId)),e.subagents?.has(t.callId)&&(l.child=e.subagents.get(t.callId)),r&&t.type===M.ToolProgress&&(l.progress=r.progress||r.message||null,r.display&&r.display.kind&&(l.display=r.display)),r&&t.type===M.ToolResult&&(l.result=r.result,l.display=r.display),r&&t.type===M.ToolError&&(l.error=r.error),t.type===M.ToolState&&(l.progress=t.message),l.status=n;return}let o={kind:"tool",callId:t.callId,...t.responseId?{responseId:t.responseId}:{},...e.subagents?.has(t.callId)?{child:e.subagents.get(t.callId)}:{},name:t.name||"tool",input:t.input||{},status:n};r&&t.type===M.ToolResult&&(o.result=r.result,o.display=r.display),r&&t.type===M.ToolError&&(o.error=r.error),r&&t.type===M.ToolProgress&&(o.progress=r.progress||r.message||null,r.display&&r.display.kind&&(o.display=r.display)),e.items.push(o)}function Gr(e,t){if(t.responseId)for(let n=0;n<e.items.length;n++){let r=e.items[n];r.kind==="thought"&&r.streaming&&r.responseId===t.responseId&&(hn(e,n).streaming=!1)}}function Ty(e,t){e.plan=t.items.length?t.items:null;let n=t.items.filter(l=>l.status==="completed").length,r=Number.isSafeInteger(t.totalCount)&&t.totalCount>=t.items.length?t.totalCount:t.items.length,i=r-t.items.length,o=Number.isSafeInteger(t.completedCount)&&t.completedCount>=n&&t.completedCount<=n+i?t.completedCount:n;e.planSummary={totalCount:r,completedCount:o,omittedItems:i}}function Yr(e,t){for(let n=0;n<e.items.length;n+=1)if(e.items[n].id===t)return n;return-1}function Ep(e,t){for(let n=0;n<e.items.length;n+=1){let r=e.items[n];if(r.kind==="tool"&&r.callId===t)return n}return-1}function hn(e,t){let n={...e.items[t]};return e.items[t]=n,n}function Ly(e){return Object.assign({},e,{items:e.items,seen:e.seen,pendingThinking:e.pendingThinking,plan:e.plan})}var Ry="agentkit.engine-event/v1",Oa="agentkit.engine-view/v1",My="submit_final_output",zy=new Set(["completed","unverified","blocked","failed","cancelled"]),Be=e=>typeof e=="string"&&e.trim().length>0,Py=e=>e==null?{}:typeof e=="object"?e:{value:e};function Oy(e){let t=se(e.title)?.family,{ok:n,path:r,diff_additions:i,diff_deletions:o}=e.result??{};if(!(!["edit","write"].includes(t)||n!==!0||!Be(r)||![i,o].every(l=>Number.isSafeInteger(l)&&l>=0)))return{kind:"file_edit",files:[{path:r,changeStat:{added:i,removed:o},operationKind:t==="write"?"write":"edit"}]}}function Ay(e){return e.title==="failed"||e.status==="failed"?"failed":["canceled","cancelled"].includes(e.title)||["canceled","cancelled"].includes(e.status)?"cancelled":e.status==="verified"?"completed":zy.has(e.status)?e.status:e.title==="completed"?"completed":"unverified"}function Fy(e,t){let n=e?.error_type??e?.code??e?.error_code,r=e?.error_message??e?.message;if(!Be(n))return{message:Be(r)?r:`\u5DE5\u5177 ${t??""} \u672A\u6210\u529F`.trim()};let i=n==="command_policy_blocked"&&e?.executed===!1?e.finding?.detail:void 0;return{code:n,...Be(i)?{message:i}:Be(r)?{message:r}:{},...Number.isSafeInteger(e.failed_edit_index)&&e.failed_edit_index>=0?{failed_edit_index:e.failed_edit_index}:{}}}function Dy(e,{runId:t="run",time:n,startedAt:r=n}={}){if(!e||e.schema!==Ry||!Number.isSafeInteger(e.seq))return[];let i=Eo,o=a=>`${t}:${e.seq}:${a}`,l=typeof e.requestId=="string"&&/^[a-f0-9]{64}$/.test(e.requestId)?`${t}:thought:${e.requestId}`:o("thought");switch(e.kind){case"run.started":return[{v:i,id:o("start"),type:"task.started",taskId:t,runId:t,startedAt:r}];case"todo.initialized":case"todo.updated":return Object.hasOwn(e,"plan")?[{v:i,id:o("todo"),type:"plan.updated",items:e.plan?.items??[],completedCount:e.plan?.completedCount,totalCount:e.plan?.totalCount}]:[];case"effect.prepared":case"effect.settled":return e.category==="model"&&e.title==="request"?[{v:i,id:o("model-request"),type:"model.request",active:e.kind==="effect.prepared",retry:e.kind==="effect.prepared"&&e.retry===!0,...e.purpose==="compaction"?{purpose:"compaction"}:{},itemId:l}]:[];case"model.completed":{let a=[];if(Be(e.thinking)&&a.push({v:i,id:o("thought-done"),type:"thinking.done",itemId:l,text:e.thinking}),Be(e.detail)&&(e.title==="initial_plan"||Array.isArray(e.calls)&&e.calls.length)){let s=`${t}:note:${e.seq}`;a.push({v:i,id:o("note"),type:"text.delta",itemId:s,delta:e.detail},{v:i,id:o("note-done"),type:"text.done",itemId:s})}for(let s of Array.isArray(e.calls)?e.calls:[])!Be(s?.callId)||!Be(s?.name)||s.name===My||a.push({v:i,id:o(`call:${s.callId}`),type:"tool.scheduled",callId:s.callId,name:s.name,input:Py(s.arguments)},{v:i,id:o(`run:${s.callId}`),type:"tool.started",callId:s.callId});return a}case"model.stream_interrupted":return Be(e.thinking)?[{v:i,id:o("thought-done"),type:"thinking.done",itemId:l,text:e.thinking}]:[];case"tool.completed":{if(!Be(e.callId))return[];if(e.status==="uncertain")return[{v:i,id:o("uncertain"),type:"tool.state",callId:e.callId,status:"uncertain"}];let a=e.status==="ok"?Oy(e):void 0;if(e.status!=="ok")return[{v:i,id:o("error"),type:"tool.error",callId:e.callId,error:Fy(e.result,e.title)}];let s=[{v:i,id:o("result"),type:"tool.result",callId:e.callId,result:e.result??null,...a?{display:a}:{}}];return e.title==="TodoWrite"&&Array.isArray(e.result?.todos)&&s.push({v:i,id:o("todo-receipt"),type:"plan.updated",items:e.result.todos.map((u,f)=>({...u,id:`todo:${f}`}))}),s}case"model.retry_scheduled":return Number.isSafeInteger(e.retryAt)&&e.retryAt>0?[{v:i,id:o("model-wait"),type:"model.wait",retryAt:e.retryAt,httpStatus:e.httpStatus,attempt:e.attempt,purpose:e.purpose}]:[];case"model.retry_exhausted":return[{v:i,id:o("paused"),type:"task.state",state:"paused",reason:"provider_unavailable",message:e.modelError}];case"run.paused":return[{v:i,id:o("paused"),type:"task.state",state:"paused",reason:e.reason,message:e.modelError}];case"run.terminal":{let a=[],s=`${t}:final`;return Be(e.detail)&&a.push({v:i,id:o("final"),type:"text.delta",itemId:s,delta:e.detail},{v:i,id:o("final-done"),type:"text.done",itemId:s}),e.title==="paused"?[...a,{v:i,id:o("paused"),type:"task.state",state:"paused",reason:e.reason??null}]:e.title==="interrupted"?[{v:i,id:o("finished"),type:"task.finished",outcome:"unverified",executionState:"interrupted",endedAt:n,reason:e.reason}]:[...a,{v:i,id:o("finished"),type:"task.finished",outcome:Ay(e),endedAt:n,...a.length?{finalAnswerId:s}:{},...e.reason?{reason:e.reason}:{},...Be(e.modelError)?{error:e.modelError}:{}}]}default:return[]}}function Ip(e,t){return(Array.isArray(e)?e:[]).flatMap(n=>Dy(n,t))}var jy="0.0.34",{HarnessTurn:$y}=kp(Gn.default),Cp=e=>{try{window.parent.postMessage({contract:Oa,...e},"*")}catch{}};function Wy(){let[e,t]=Gn.default.useState({runId:"run",state:qn(),theme:"system"});return Gn.default.useEffect(()=>{let n=o=>{if(o.source!==window.parent)return;let l=o.data;!l||l.contract!==Oa||(l.type==="theme"&&["light","dark","system"].includes(l.theme)?(document.documentElement.style.colorScheme=l.theme==="system"?"light dark":l.theme,t(a=>({...a,theme:l.theme}))):l.type==="reset"?t(a=>({...a,runId:String(l.runId||"run"),state:qn()})):l.type==="events"&&Array.isArray(l.events)&&t(a=>{let s=String(l.runId||a.runId),u=s===a.runId?a.state:qn();return{...a,runId:s,state:Sp(u,Ip(l.events,{runId:s}))}}))};window.addEventListener("message",n),Cp({type:"ready",version:jy});let r=document.getElementById("root"),i=new ResizeObserver(()=>Cp({type:"height",height:Math.ceil(r.getBoundingClientRect().height)}));return i.observe(r),()=>{window.removeEventListener("message",n),i.disconnect()}},[]),Gn.default.createElement($y,{state:e.state,theme:e.theme,autoFollow:!1,styleSheet:null})}(0,Np.createRoot)(document.getElementById("root")).render(Gn.default.createElement(Wy));})();
|
|
726
726
|
</script></body></html>
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kingsoftcloud/agentkit-harness-node",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.34",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Standalone Native Harness Node adapters: a durable SQLite run store, a one-request model HTTP port, and a minimal versioned JSON-RPC 2.0 over NDJSON process entry. Reuses the shared Native adapter implementations and externalizes @kingsoftcloud/agentkit-harness-core; depends on no Studio/DSH code at runtime.",
|
|
@@ -155,7 +155,7 @@
|
|
|
155
155
|
"src/package-integrity.mjs"
|
|
156
156
|
],
|
|
157
157
|
"dependencies": {
|
|
158
|
-
"@kingsoftcloud/agentkit-harness-core": "0.0.
|
|
158
|
+
"@kingsoftcloud/agentkit-harness-core": "0.0.34",
|
|
159
159
|
"@astral-sh/ruff-wasm-nodejs": "0.16.8",
|
|
160
160
|
"parse5": "7.3.0",
|
|
161
161
|
"playwright-core": "1.58.2",
|
|
@@ -2,6 +2,21 @@ import { isAbsolute, relative, resolve, sep } from 'node:path';
|
|
|
2
2
|
|
|
3
3
|
export const LOCAL_COMMAND_SHELL = 'bash-execution/v1';
|
|
4
4
|
export const ISOLATED_COMMAND_SHELL = 'bubblewrap-workspace/v1';
|
|
5
|
+
export const DESKTOP_WORKSPACE_SHELL = 'seatbelt-workspace/v1';
|
|
6
|
+
|
|
7
|
+
function workspaceSeatbelt(workspaceRoot, cwd) {
|
|
8
|
+
if (process.platform !== 'darwin' || !workspaceRoot || !cwd || !isAbsolute(workspaceRoot)
|
|
9
|
+
|| !isAbsolute(cwd) || resolve(workspaceRoot) !== workspaceRoot || workspaceRoot === '/')
|
|
10
|
+
throw Error('desktop_command_workspace_invalid');
|
|
11
|
+
const within = relative(workspaceRoot, cwd);
|
|
12
|
+
if (within === '..' || within.startsWith('..' + sep) || isAbsolute(within))
|
|
13
|
+
throw Error('isolated_command_cwd_outside_workspace');
|
|
14
|
+
// File effects follow DSH's workspace-write mode. Use canonical workspace
|
|
15
|
+
// paths and a literal SBPL parameter rather than interpolating the directory.
|
|
16
|
+
return ['/usr/bin/sandbox-exec', '-D', 'WORKSPACE=' + workspaceRoot, '-p',
|
|
17
|
+
'(version 1) (allow default) (deny file-write*) '
|
|
18
|
+
+ '(allow file-write* (subpath (param "WORKSPACE")) (literal "/dev/null") (subpath "/private/tmp"))'];
|
|
19
|
+
}
|
|
5
20
|
|
|
6
21
|
/** A missing policy belongs to a persisted legacy request. Never reinterpret
|
|
7
22
|
* it under a new shell during supervision/recovery. No PATH-based fallback.
|
|
@@ -9,6 +24,7 @@ export const ISOLATED_COMMAND_SHELL = 'bubblewrap-workspace/v1';
|
|
|
9
24
|
export function shellCommandArgv(command, policy = null, { workspaceRoot, cwd } = {}) {
|
|
10
25
|
if (policy === null) return ['/bin/sh', '-c', command];
|
|
11
26
|
if (policy === LOCAL_COMMAND_SHELL) return ['/bin/bash', '-c', command];
|
|
27
|
+
if (policy === DESKTOP_WORKSPACE_SHELL) return [...workspaceSeatbelt(workspaceRoot, cwd), '/bin/bash', '-c', command];
|
|
12
28
|
if (policy !== ISOLATED_COMMAND_SHELL) throw Error('unsupported_command_shell');
|
|
13
29
|
if (process.platform !== 'linux' || typeof workspaceRoot !== 'string' || typeof cwd !== 'string'
|
|
14
30
|
|| !isAbsolute(workspaceRoot) || !isAbsolute(cwd) || resolve(workspaceRoot) !== workspaceRoot
|
|
@@ -63,7 +63,7 @@ const approvalDenialMessages = {
|
|
|
63
63
|
approval_cancelled: 'This approval was cancelled. The action did not run. Do not request it again unless the user asks to continue.',
|
|
64
64
|
};
|
|
65
65
|
|
|
66
|
-
function durableDecision(record, request, explainDenial = false, workspaceWriteSafe = false) {
|
|
66
|
+
function durableDecision(record, request, explainDenial = false, workspaceWriteSafe = false, sandboxEscalation = false) {
|
|
67
67
|
const { call, operationKey } = request;
|
|
68
68
|
const interactionId = `engine-permission-${digest({ runId: request.runId, call, definition: request.definition })}`;
|
|
69
69
|
// Walk backward only within the lifetime of this call. A reused provider
|
|
@@ -86,7 +86,8 @@ function durableDecision(record, request, explainDenial = false, workspaceWriteS
|
|
|
86
86
|
}
|
|
87
87
|
return { status: 'approval_required', approvalPolicy: DURABLE_APPROVAL, interactionId,
|
|
88
88
|
content: { contract: ENGINE_APPROVAL_CONTRACT, code: 'approval_required', argumentDigest: digest(call.arguments),
|
|
89
|
-
subject: engineApprovalSubject(call), ...(workspaceWriteSafe ? { workspaceWriteSafe } : {})
|
|
89
|
+
subject: engineApprovalSubject(call), ...(workspaceWriteSafe ? { workspaceWriteSafe } : {}),
|
|
90
|
+
...(sandboxEscalation ? { sandboxEscalation } : {}) } };
|
|
90
91
|
}
|
|
91
92
|
|
|
92
93
|
function admitExecutionPolicy(policy, legacyMaxModelCalls) {
|
|
@@ -109,9 +110,11 @@ export function admitEngineModel(model) {
|
|
|
109
110
|
&& (model.requestOutputTokens == null || Number.isSafeInteger(model.requestOutputTokens) && model.requestOutputTokens > 0)
|
|
110
111
|
&& (model.images === undefined || typeof model.images === 'boolean')
|
|
111
112
|
&& (model.compatibilityRule === undefined || isProviderCompatibilityRule(model.compatibilityRule))
|
|
113
|
+
&& (model.reasoningEffort === undefined || ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'].includes(model.reasoningEffort))
|
|
112
114
|
&& typeof model.apiKey === 'function', 'engine_model_invalid');
|
|
113
115
|
const contextWindow = model.contextWindow ?? 128000;
|
|
114
116
|
return { protocol: model.protocol ?? 'openai-chat', modelName: model.name, baseUrl: model.baseUrl, parameters: {},
|
|
117
|
+
...(model.reasoningEffort === undefined ? {} : { reasoningEffort: model.reasoningEffort }),
|
|
115
118
|
...(model.compatibilityRule === undefined ? {} : { compatibilityRule: model.compatibilityRule }),
|
|
116
119
|
input: model.images ? ['text', 'image'] : ['text'], contextWindow,
|
|
117
120
|
maxOutputTokens: presetRequestOutputTokens({ configured: model.requestOutputTokens ?? null,
|
|
@@ -200,7 +203,7 @@ export function admitHostTools(tools, reserved, durableApprovals = false, hostRe
|
|
|
200
203
|
contextRole: 'none', observationRole: 'none', progressObservation: false, contextRetention: 'normal',
|
|
201
204
|
recoveryPolicy: readOnly ? 'safe-read/v1' : tool.receiptObservation ? 'receipt-observation/v1' : 'manual',
|
|
202
205
|
...(tool.effectProtocol ? { hostEffectProtocol: tool.effectProtocol,
|
|
203
|
-
...(durableApprovals ? { approvalPolicy: DURABLE_APPROVAL } : {}) } : {}),
|
|
206
|
+
...(durableApprovals && !(tool.name === 'web_search' && tool.readOnly === true) ? { approvalPolicy: DURABLE_APPROVAL } : {}) } : {}),
|
|
204
207
|
...(tool.deferred ? { discovery: { deferred: true } } : {}) };
|
|
205
208
|
});
|
|
206
209
|
}
|
|
@@ -222,9 +225,9 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
222
225
|
const roles = nativeChildRoles({ subAgents });
|
|
223
226
|
const supportsImages = description.input.includes('image');
|
|
224
227
|
const store = runStore ?? new SqliteRunStore(join(stateDir, 'runs.sqlite'));
|
|
225
|
-
const decide = async (request, explainDenial = false, workspaceWriteSafe = false) => {
|
|
228
|
+
const decide = async (request, explainDenial = false, workspaceWriteSafe = false, sandboxEscalation = false) => {
|
|
226
229
|
if (request.definition?.approvalPolicy === DURABLE_APPROVAL)
|
|
227
|
-
return durableDecision(store.load(request.scope, request.runId), request, explainDenial, workspaceWriteSafe);
|
|
230
|
+
return durableDecision(store.load(request.scope, request.runId), request, explainDenial, workspaceWriteSafe, sandboxEscalation);
|
|
228
231
|
return await authorize(request) === 'allow' ? 'allow' : 'deny';
|
|
229
232
|
};
|
|
230
233
|
const artifacts = await createNativeArtifactStore({ directory: join(stateDir, 'artifacts'), scope });
|
|
@@ -236,7 +239,8 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
236
239
|
const commands = windows ? null : createNativeLocalCommandTools({ workspaceRoot: root, stateRoot: join(stateDir, 'commands'), sessionId,
|
|
237
240
|
settings: local.settings, sourceEnv: local.environment, outputPolicy: local.outputPolicy, environmentPolicy: local.environmentPolicy,
|
|
238
241
|
shellPolicy: commandSandbox,
|
|
239
|
-
artifacts, authorize: (request, info) => decide(request, true,
|
|
242
|
+
artifacts, authorize: (request, info) => request.definition.readOnly && !request.definition.approvalPolicy ? 'allow' : decide(request, true,
|
|
243
|
+
!info?.escalation && (info?.readOnlyCommand || info?.sandboxedCommand), info?.escalation),
|
|
240
244
|
classifyApproval: true, captureWorkspace: request => workspace.capture(request),
|
|
241
245
|
resolveOwnedCommand: createOwnedCommandResolver({ scope, store }) });
|
|
242
246
|
const search = engineWebConfig(sourceEnv);
|
|
@@ -327,6 +331,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
327
331
|
const profile = { profileId: 'engine', profileVersion: digest(description), providerFamily: description.protocol,
|
|
328
332
|
compatibilityDigest: digest(description), supportsImages, discoveredToolExposure: 'direct-after-search/v1', streamTimeoutPolicy: 'idle/v1',
|
|
329
333
|
...(chatUsage ? { chatUsagePolicy: chatUsage } : {}), maxRetries: 2, maxProviderRetries: 3, ...context.profile,
|
|
334
|
+
...(description.reasoningEffort === undefined ? {} : { reasoningEffort: description.reasoningEffort }),
|
|
330
335
|
maxOutputTokens: description.maxOutputTokens, contextWindow: description.contextWindow,
|
|
331
336
|
requestTimeoutMs: description.requestTimeoutMs, providerReplayMode: 'reasoning_content',
|
|
332
337
|
providerCompatibilityPolicy: admitProviderCompatibilityPolicy(providerRule, {
|
|
@@ -421,7 +426,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
421
426
|
invariant(!policy || internal.every(name => !policy.rules.has(name) || policy.rules.get(name) === 'inherit'),
|
|
422
427
|
'engine_tool_policy_internal_control_unsupported');
|
|
423
428
|
const hosted = restrictEngineTools(admitHostTools(hostTools, reserved, durableApprovals, typeof callHostReceipt === 'function'), policy, DURABLE_APPROVAL);
|
|
424
|
-
const builtins = restrictEngineTools(durableApprovals ? bound.map(tool => route.get(tool.name) === workspace
|
|
429
|
+
const builtins = restrictEngineTools(durableApprovals ? bound.map(tool => tool.readOnly && (route.get(tool.name) === workspace || route.get(tool.name) === commands)
|
|
425
430
|
? tool : { ...tool, approvalPolicy: DURABLE_APPROVAL }) : bound, policy, DURABLE_APPROVAL);
|
|
426
431
|
const childControls = durableApprovals ? restrictEngineTools(childDefinitions, policy, DURABLE_APPROVAL) : [];
|
|
427
432
|
const searchable = builtins.some(tool => tool.discovery) || hosted.some(tool => tool.discovery);
|
|
@@ -523,7 +528,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
523
528
|
&& receipt.status === 'committed')?.result.results?.find(result => result.interactionId === pending.hostInteractionId)?.content
|
|
524
529
|
: null;
|
|
525
530
|
return { interactionId: pending.interactionId, callId: pending.callId, tool: call.name,
|
|
526
|
-
...(tools.some(tool => tool.name === call.name && (tool.hostApprovalRequired
|
|
531
|
+
...(commandApproval?.sandboxEscalation === true || tools.some(tool => tool.name === call.name && (tool.hostApprovalRequired
|
|
527
532
|
|| tool.hostEffectProtocol === ENGINE_HOST_EFFECT)) ? { requiresUserApproval: true } : {}),
|
|
528
533
|
...(snapshot.childApproval ? { childRunId: snapshot.childApproval.childRunId } : {}),
|
|
529
534
|
...(!snapshot.childApproval && (commandApproval?.workspaceWriteSafe === true || route.get(call.name) === workspace
|
|
@@ -654,10 +654,13 @@ export function engineStartupFromArgs(argv, env) {
|
|
|
654
654
|
subAgents,
|
|
655
655
|
sessionId: values.session ?? 'engine-session', approval, approvalTimeoutMs: number('AGENTKIT_ENGINE_APPROVAL_TIMEOUT_MS') ?? 600000,
|
|
656
656
|
scope: { tenantId: values.tenant ?? 'local', workspaceId: 'local', userId: values.user ?? 'local-user', agentId: values.agent ?? 'engine' },
|
|
657
|
+
...(env.AGENTKIT_ENGINE_DESKTOP_WORKSPACE_SANDBOX === '1' && process.platform === 'darwin'
|
|
658
|
+
? { commandSandbox: 'seatbelt-workspace/v1' } : {}),
|
|
657
659
|
model: { protocol: env.AGENTKIT_ENGINE_MODEL_PROTOCOL ?? 'openai-chat', name: need(env.AGENTKIT_ENGINE_MODEL_NAME, 'AGENTKIT_ENGINE_MODEL_NAME'),
|
|
658
660
|
compatibilityRule: env.AGENTKIT_ENGINE_MODEL_COMPAT_RULE ?? env.KSADK_MODEL_COMPAT_RULE,
|
|
659
661
|
baseUrl: need(env.AGENTKIT_ENGINE_MODEL_BASE_URL, 'AGENTKIT_ENGINE_MODEL_BASE_URL'),
|
|
660
662
|
apiKeyEnv: env.AGENTKIT_ENGINE_MODEL_API_KEY_ENV ?? 'AGENTKIT_ENGINE_MODEL_API_KEY',
|
|
663
|
+
reasoningEffort: env.AGENTKIT_ENGINE_MODEL_REASONING_EFFORT,
|
|
661
664
|
contextWindow: number('AGENTKIT_ENGINE_MODEL_CONTEXT_WINDOW'), maxOutputTokens: number('AGENTKIT_ENGINE_MODEL_MAX_OUTPUT_TOKENS'),
|
|
662
665
|
requestOutputTokens: number('AGENTKIT_ENGINE_MODEL_REQUEST_OUTPUT_TOKENS'), images: env.AGENTKIT_ENGINE_MODEL_IMAGES === '1' } };
|
|
663
666
|
}
|
|
@@ -20,7 +20,7 @@ import { ENGINE_HOST_EFFECT } from './engine-host-effects.mjs';
|
|
|
20
20
|
import { ENGINE_VERIFICATION } from './engine-verification.mjs';
|
|
21
21
|
import { createEngineManagedService, MANAGED_NATIVE_KERNEL_CONTRACT, MANAGED_NATIVE_KERNEL_PATH } from './engine-managed-service.mjs';
|
|
22
22
|
import { isAgentKernelPlatformPath } from './native-managed-kernel-http.mjs';
|
|
23
|
-
import { ISOLATED_COMMAND_SHELL, shellCommandArgv } from './command-shell.mjs';
|
|
23
|
+
import { DESKTOP_WORKSPACE_SHELL, ISOLATED_COMMAND_SHELL, shellCommandArgv } from './command-shell.mjs';
|
|
24
24
|
|
|
25
25
|
export const ENGINE_SERVICE_CONTRACT = 'agentkit.engine-service/v1';
|
|
26
26
|
// Bound the authenticated frame separately from the current-turn media budget.
|
|
@@ -193,7 +193,7 @@ export function createEngineService({ startup, token, env = process.env, fetchIm
|
|
|
193
193
|
throw new Error('engine_service_workspace_state_overlap');
|
|
194
194
|
if (process.platform === 'win32') privateDirectory(stateDir);
|
|
195
195
|
if (startup.commandSandbox !== undefined) {
|
|
196
|
-
if (startup.commandSandbox
|
|
196
|
+
if (![ISOLATED_COMMAND_SHELL, DESKTOP_WORKSPACE_SHELL].includes(startup.commandSandbox)) throw new Error('engine_service_sandbox_invalid');
|
|
197
197
|
const [command, ...args] = shellCommandArgv(':', startup.commandSandbox, { workspaceRoot: workspace, cwd: workspace });
|
|
198
198
|
const probe = spawnSync(command, args, { cwd: workspace, env: { PATH: '/bin:/usr/bin' }, timeout: 5000, stdio: 'ignore' });
|
|
199
199
|
if (probe.status !== 0) throw new Error('engine_service_sandbox_unavailable');
|
|
@@ -8,7 +8,7 @@ import { dirname, join, resolve, sep } from 'node:path';
|
|
|
8
8
|
import { fileURLToPath } from 'node:url';
|
|
9
9
|
import { localControlSettings, resolveLocalProcessLauncher } from './local-process.mjs';
|
|
10
10
|
import { localEnvironmentPolicy, localOutputPolicy } from './local-output-policy.mjs';
|
|
11
|
-
import { ISOLATED_COMMAND_SHELL, shellCommandArgv } from './command-shell.mjs';
|
|
11
|
+
import { DESKTOP_WORKSPACE_SHELL, ISOLATED_COMMAND_SHELL, shellCommandArgv } from './command-shell.mjs';
|
|
12
12
|
import { LOCAL_BACKGROUND_CONTRACT, START_GRACE_MS, TERMINAL, LocalCommandError,
|
|
13
13
|
check, createPrivate, delay, digest, failCommandStart, fsyncPrivate, lockUntil, openPrivate, privateDirectory, privateFile,
|
|
14
14
|
readAll, readRecord, readWindow, syncDirectory, tryLock, validId, writeRecord } from './local-command-state.mjs';
|
|
@@ -47,7 +47,7 @@ export function commandRequest({ command, cwd, env, timeoutMs, settings = {}, ou
|
|
|
47
47
|
if (outPolicy) request.outputPolicy = outPolicy;
|
|
48
48
|
if (envPolicy) request.environmentPolicy = envPolicy;
|
|
49
49
|
shellCommandArgv(command, shellPolicy, { workspaceRoot, cwd: request.cwd });
|
|
50
|
-
if (shellPolicy
|
|
50
|
+
if ([ISOLATED_COMMAND_SHELL, DESKTOP_WORKSPACE_SHELL].includes(shellPolicy)) request.workspaceRoot = workspaceRoot;
|
|
51
51
|
if (shellPolicy) request.shellPolicy = shellPolicy;
|
|
52
52
|
check(Buffer.byteLength(JSON.stringify(request)) <= 1024 * 1024, 'background_command_request_too_large');
|
|
53
53
|
return request;
|
|
@@ -11,7 +11,7 @@ import { checkGovernedCommand, LOCAL_COMMAND_POLICY, GOVERNED_COMMAND_POLICY } f
|
|
|
11
11
|
import { checkPlanCommand, PLAN_COMMAND_POLICY } from './command-plan.mjs';
|
|
12
12
|
import { commandFailureEvidence, commandExceptionCause } from './local-command-evidence.mjs';
|
|
13
13
|
import { captureCommandWorkspace, commandWorkspaceChange } from './command-workspace-observation.mjs';
|
|
14
|
-
import { ISOLATED_COMMAND_SHELL, LOCAL_COMMAND_SHELL, shellCommandArgv } from './command-shell.mjs';
|
|
14
|
+
import { DESKTOP_WORKSPACE_SHELL, ISOLATED_COMMAND_SHELL, LOCAL_COMMAND_SHELL, shellCommandArgv } from './command-shell.mjs';
|
|
15
15
|
|
|
16
16
|
export const LOCAL_COMMAND_TOOLS_CONTRACT = 'agentkit.local-command-tools/v1';
|
|
17
17
|
export const LOCAL_COMMAND_PROGRESS_CONTRACT = 'agentkit.local-command-progress/v1';
|
|
@@ -26,13 +26,17 @@ const base = (name, properties, required, mutating, timeoutMs) => ({ name,
|
|
|
26
26
|
readOnly: !mutating, concurrentSafe: !mutating, permissions: mutating ? [name === 'stop_command' ? 'sandbox:cancel' : 'sandbox:execute'] : [],
|
|
27
27
|
timeoutMs, contextRole: 'none', observationRole: 'none', progressObservation: false, contextRetention: 'normal',
|
|
28
28
|
...(!mutating ? { recoveryPolicy: 'safe-read/v1' } : {}) });
|
|
29
|
-
export function localCommandToolDefinitions(settings = {}) {
|
|
29
|
+
export function localCommandToolDefinitions(settings = {}, desktopSandbox = false) {
|
|
30
30
|
const limits = localControlSettings(settings);
|
|
31
31
|
return [
|
|
32
32
|
base('sandbox_status', {}, [], false, 10000),
|
|
33
33
|
{ ...base('run_command', { command: { type: 'string', minLength: 1 }, cwd: { anyOf: [{ type: 'string' }, { type: 'null' }] },
|
|
34
34
|
timeout: schemas.nullableSeconds, env: { anyOf: [{ type: 'object', additionalProperties: { type: 'string' } }, { type: 'null' }] },
|
|
35
|
-
background: { type: 'boolean' }, background_timeout: schemas.nullableSeconds
|
|
35
|
+
background: { type: 'boolean' }, background_timeout: schemas.nullableSeconds,
|
|
36
|
+
...(desktopSandbox ? { sandbox_permissions: { type: 'string', enum: ['danger-full-access'],
|
|
37
|
+
description: 'Request one-time user approval to run outside workspace confinement if required by the task.' } } : {}),
|
|
38
|
+
}, ['command'], true, limits.wallSeconds * 1000 + 15000),
|
|
39
|
+
...(desktopSandbox ? { description: 'Run a governed Bash command under the workspace file sandbox. Use sandbox_permissions only when the command needs wider file access. Background commands return an owned task_id.' } : {}),
|
|
36
40
|
backgroundCommandPolicy: 'owned-command-launch/v1', workspaceChangePolicy: 'observed-command/v1' },
|
|
37
41
|
base('read_command_output', { task_id: { type: 'string', pattern: '^[a-f0-9]{64}$' }, stdout_cursor: schemas.cursor,
|
|
38
42
|
stderr_cursor: schemas.cursor, max_bytes: { type: 'integer', minimum: 4, maximum: 65536 },
|
|
@@ -70,7 +74,8 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
|
|
|
70
74
|
const outPolicy = localOutputPolicy(outputPolicy);
|
|
71
75
|
const envPolicy = localEnvironmentPolicy(environmentPolicy);
|
|
72
76
|
if (outPolicy) durableForeground = true;
|
|
73
|
-
const
|
|
77
|
+
const desktopSandbox = shellPolicy === DESKTOP_WORKSPACE_SHELL;
|
|
78
|
+
const root = realpathSync(workspaceRoot), policy = localControlSettings(settings), definitions = localCommandToolDefinitions(policy, desktopSandbox);
|
|
74
79
|
shellCommandArgv(':', shellPolicy, { workspaceRoot: root, cwd: root });
|
|
75
80
|
// Under persisted-stream/v1 the automatic foreground receipt uses a bounded
|
|
76
81
|
// window matching previewBytes (clamped to the 4..65536 UTF-8 cursor range).
|
|
@@ -163,6 +168,12 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
|
|
|
163
168
|
if (rejection) return { status: 'error', content: rejection };
|
|
164
169
|
const args = structuredClone(request.call.arguments);
|
|
165
170
|
let command, cwd, readOnlyCommand = false;
|
|
171
|
+
const escalation = desktopSandbox && args.sandbox_permissions === 'danger-full-access';
|
|
172
|
+
// A standing authorization in a legacy run does not grant a one-time
|
|
173
|
+
// escape from the requested desktop sandbox.
|
|
174
|
+
if (escalation && request.definition.approvalPolicy !== 'durable-preflight/v1')
|
|
175
|
+
return errorResult('sandbox_escalation_requires_approval', { executed: false });
|
|
176
|
+
const executionShell = escalation ? LOCAL_COMMAND_SHELL : shellPolicy;
|
|
166
177
|
if (request.call.name === 'run_command') {
|
|
167
178
|
command = args.command.trim();
|
|
168
179
|
if (!command) return errorResult('command_required');
|
|
@@ -178,14 +189,17 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
|
|
|
178
189
|
readOnlyCommand = await checkPlanCommand(command, { cwd, workspaceRoot: root, signal: request.signal });
|
|
179
190
|
}
|
|
180
191
|
guard();
|
|
181
|
-
const
|
|
192
|
+
const sandboxedCommand = desktopSandbox && !escalation && request.call.name === 'run_command'
|
|
193
|
+
&& !args.env && !args.background && !request.definition.hostApprovalRequired;
|
|
194
|
+
const decision = await authorize(request, { readOnlyCommand, sandboxedCommand, escalation }); guard();
|
|
182
195
|
if (decision !== 'allow') return decision?.status === 'approval_required' && typeof decision.interactionId === 'string'
|
|
183
196
|
? decision : errorResult('policy_denied');
|
|
184
197
|
if (request.call.name === 'sandbox_status') return { status: 'ok', content: { ok: true, backend: 'local_process', enabled: true,
|
|
185
|
-
isolated: shellPolicy === ISOLATED_COMMAND_SHELL, sandbox_id: `local_process:${sessionId}`, timeout_seconds: policy.wallSeconds,
|
|
198
|
+
isolated: desktopSandbox || shellPolicy === ISOLATED_COMMAND_SHELL, sandbox_id: `local_process:${sessionId}`, timeout_seconds: policy.wallSeconds,
|
|
186
199
|
boundary: shellPolicy === ISOLATED_COMMAND_SHELL
|
|
187
200
|
? 'Only the workspace and temporary files are writable. The command has no Host process or network access.'
|
|
188
|
-
: '
|
|
201
|
+
: desktopSandbox ? 'Only workspace and temporary files are writable under the desktop file sandbox.'
|
|
202
|
+
: 'Shares Host filesystem, allowlisted environment and network. Not an OS security sandbox.',
|
|
189
203
|
shell: '/bin/bash', shell_policy: shellPolicy,
|
|
190
204
|
contracts: [LOCAL_COMMAND_TOOLS_CONTRACT, LOCAL_PROCESS_CONTRACT, LOCAL_COMMAND_POLICY, GOVERNED_COMMAND_POLICY] } };
|
|
191
205
|
if (request.call.name === 'read_command_output' || request.call.name === 'stop_command') {
|
|
@@ -217,7 +231,7 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
|
|
|
217
231
|
dispatched = true;
|
|
218
232
|
const operationKey = request.operationKey, expectedTaskId = store.commandId(operationKey);
|
|
219
233
|
known = { content: { backend: 'sandbox/local_process', task_id: expectedTaskId } };
|
|
220
|
-
const handle = await store.start({ operationKey, command, cwd, env, settings: policy, shellPolicy, workspaceRoot: root,
|
|
234
|
+
const handle = await store.start({ operationKey, command, cwd, env, settings: policy, shellPolicy: executionShell, workspaceRoot: root,
|
|
221
235
|
outputPolicy: outPolicy, environmentPolicy: envPolicy,
|
|
222
236
|
timeoutMs: deadline(args.background ? args.background_timeout : args.timeout), assertCurrent: guard });
|
|
223
237
|
if (!args.background) {
|
|
@@ -270,7 +284,7 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
|
|
|
270
284
|
? { backgroundCommandFinished: true } : {}) };
|
|
271
285
|
} else {
|
|
272
286
|
dispatched = true;
|
|
273
|
-
const result = await runBoundedProcess({ argv: shellCommandArgv(command,
|
|
287
|
+
const result = await runBoundedProcess({ argv: shellCommandArgv(command, executionShell, { workspaceRoot: root, cwd }), cwd, env, settings: policy, signal: request.signal,
|
|
274
288
|
timeoutMs: deadline(args.timeout), onOutput: progress });
|
|
275
289
|
const incomplete = result.controls.status === 'failed' || !!result.cleanupError;
|
|
276
290
|
const resourceReason = result.exitCode === -osConstants.signals.SIGXCPU ? 'cpu_time'
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { lstat, open, readdir, realpath } from 'node:fs/promises';
|
|
3
|
+
import { basename, join } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { publicErrorMessage } from '@kingsoftcloud/agentkit-harness-core/error-presentation';
|
|
6
|
+
import { splitlines } from './workspace-editing.mjs';
|
|
7
|
+
import { escapeRegex, fnmatch, isInside, workspaceRelative } from './workspace-paths.mjs';
|
|
8
|
+
|
|
9
|
+
const skippedDirectories = new Set(['.git', 'node_modules', '.venv', 'venv', '__pycache__']);
|
|
10
|
+
const maxFileBytes = 1024 * 1024;
|
|
11
|
+
const timedOut = Symbol('timed out');
|
|
12
|
+
|
|
13
|
+
async function readText(file, root, signal) {
|
|
14
|
+
if (!isInside(await realpath(file), root) || signal.aborted) return;
|
|
15
|
+
const fd = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
16
|
+
try {
|
|
17
|
+
if (signal.aborted) return;
|
|
18
|
+
const info = await fd.stat();
|
|
19
|
+
if (!info.isFile() || info.size > maxFileBytes || signal.aborted) return;
|
|
20
|
+
const buffer = Buffer.allocUnsafe(info.size + 1);
|
|
21
|
+
let offset = 0;
|
|
22
|
+
while (offset < buffer.length && !signal.aborted) {
|
|
23
|
+
const { bytesRead } = await fd.read(buffer, offset, buffer.length - offset, offset);
|
|
24
|
+
if (bytesRead === 0) return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(buffer.subarray(0, offset));
|
|
25
|
+
offset += bytesRead;
|
|
26
|
+
}
|
|
27
|
+
} finally {
|
|
28
|
+
await fd.close();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export async function searchWorkspace({ args, root, base }, { read = readText, fileTimeoutMs = 1000 } = {}) {
|
|
33
|
+
const { query, path, glob } = args;
|
|
34
|
+
let pattern;
|
|
35
|
+
try {
|
|
36
|
+
pattern = new RegExp(args.is_regex ? query.trim() : escapeRegex(query.trim()), args.case_sensitive ? '' : 'i');
|
|
37
|
+
} catch (error) {
|
|
38
|
+
return { ok: false, error_code: 'invalid_search_pattern', error_message: publicErrorMessage(error) };
|
|
39
|
+
}
|
|
40
|
+
const limit = Math.max(1, Math.min(Number(args.max_results) || 100, 5000));
|
|
41
|
+
const context = Math.max(0, Math.min(Number(args.context_lines) || 0, 20));
|
|
42
|
+
const results = [];
|
|
43
|
+
const deadline = performance.now() + 27_000;
|
|
44
|
+
let skippedSlow = 0;
|
|
45
|
+
let stalledIo = 0;
|
|
46
|
+
let truncated = false;
|
|
47
|
+
|
|
48
|
+
async function bounded(action) {
|
|
49
|
+
const controller = new AbortController();
|
|
50
|
+
let timer;
|
|
51
|
+
const result = action(controller.signal).catch(() => undefined).finally(() => {
|
|
52
|
+
if (controller.signal.aborted) stalledIo--;
|
|
53
|
+
});
|
|
54
|
+
const timeout = new Promise(resolve => {
|
|
55
|
+
timer = setTimeout(() => {
|
|
56
|
+
skippedSlow++;
|
|
57
|
+
stalledIo++;
|
|
58
|
+
controller.abort();
|
|
59
|
+
resolve(timedOut);
|
|
60
|
+
}, fileTimeoutMs);
|
|
61
|
+
});
|
|
62
|
+
try {
|
|
63
|
+
return await Promise.race([result, timeout]);
|
|
64
|
+
} finally {
|
|
65
|
+
clearTimeout(timer);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function inspect(file) {
|
|
70
|
+
const path = workspaceRelative(root, file);
|
|
71
|
+
if (glob && !fnmatch(path, glob) && !fnmatch(basename(file), glob)) return false;
|
|
72
|
+
const text = await bounded(signal => read(file, root, signal));
|
|
73
|
+
if (typeof text !== 'string') return false;
|
|
74
|
+
const lines = splitlines(text);
|
|
75
|
+
for (let i = 0; i < lines.length; i++) {
|
|
76
|
+
const line = lines[i];
|
|
77
|
+
if (!pattern.test(line)) continue;
|
|
78
|
+
if (results.length >= limit) return true;
|
|
79
|
+
results.push({ path, line: i + 1, text: line, snippet: line,
|
|
80
|
+
context_before: lines.slice(Math.max(0, i - context), i),
|
|
81
|
+
context_after: lines.slice(i + 1, i + 1 + context) });
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const info = await bounded(() => lstat(base));
|
|
87
|
+
if (!info) return { ok: false, error_code: 'workspace_path_not_found', error_message: `workspace path not found: ${path}` };
|
|
88
|
+
if (info === timedOut) return { ok: false, error_code: 'workspace_search_timeout', error_message: 'workspace search path did not respond' };
|
|
89
|
+
// Stop before slow operations can fill the separate process's default
|
|
90
|
+
// four-thread I/O pool. The parent reaps outstanding reads when we return.
|
|
91
|
+
const budgetUsed = () => stalledIo >= 3 || performance.now() >= deadline;
|
|
92
|
+
if (info.isFile()) truncated = await inspect(base);
|
|
93
|
+
else if (info.isDirectory()) {
|
|
94
|
+
const dirs = [base];
|
|
95
|
+
search: while (dirs.length) {
|
|
96
|
+
if (budgetUsed()) { truncated = true; break; }
|
|
97
|
+
const dir = dirs.pop();
|
|
98
|
+
const entries = await bounded(async signal => {
|
|
99
|
+
if (await realpath(dir) !== dir || signal.aborted) return;
|
|
100
|
+
return readdir(dir, { withFileTypes: true });
|
|
101
|
+
});
|
|
102
|
+
if (!Array.isArray(entries)) continue;
|
|
103
|
+
for (const entry of entries) {
|
|
104
|
+
if (budgetUsed()) { truncated = true; break search; }
|
|
105
|
+
const name = entry.name;
|
|
106
|
+
const child = join(dir, name);
|
|
107
|
+
if (entry.isDirectory() && !skippedDirectories.has(name.toLowerCase())) dirs.push(child);
|
|
108
|
+
else if (entry.isFile() && await inspect(child)) { truncated = true; break search; }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return { ok: true, query, searched_path: path, results, match_count: results.length,
|
|
113
|
+
truncated: truncated || skippedSlow > 0, context_lines: context, search_backend: 'node',
|
|
114
|
+
...(skippedSlow > 0 ? { skipped_slow_paths: skippedSlow } : {}) };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (process.send && process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
|
|
118
|
+
process.once('message', input => {
|
|
119
|
+
void searchWorkspace(input).then(result => process.send(result), () => process.exit(1));
|
|
120
|
+
});
|
|
121
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { fork } from 'node:child_process';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
|
|
4
|
+
const worker = fileURLToPath(new URL('./workspace-search-worker.mjs', import.meta.url));
|
|
5
|
+
const failed = (code, message) => ({ ok: false, error_code: code, error_message: message });
|
|
6
|
+
|
|
7
|
+
export function runWorkspaceSearch(input, signal) {
|
|
8
|
+
const canceled = () => failed('canceled', 'workspace search canceled');
|
|
9
|
+
if (signal?.aborted) return Promise.resolve(canceled());
|
|
10
|
+
// Keep filesystem stalls and expensive regex evaluation off the Harness
|
|
11
|
+
// event loop. A stuck filesystem read can outlive termination of a worker
|
|
12
|
+
// thread, so this process has its own I/O pool and can be detached on timeout.
|
|
13
|
+
const child = fork(worker, { execArgv: [], stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
|
|
14
|
+
env: { SystemRoot: process.env.SystemRoot }, windowsHide: true });
|
|
15
|
+
return new Promise(resolve => {
|
|
16
|
+
let settled = false;
|
|
17
|
+
const finish = value => {
|
|
18
|
+
if (settled) return;
|
|
19
|
+
settled = true;
|
|
20
|
+
clearTimeout(timer);
|
|
21
|
+
signal?.removeEventListener('abort', abort);
|
|
22
|
+
child.kill('SIGKILL');
|
|
23
|
+
child.channel?.unref();
|
|
24
|
+
child.unref();
|
|
25
|
+
resolve(value);
|
|
26
|
+
};
|
|
27
|
+
const abort = () => finish(canceled());
|
|
28
|
+
const unavailable = () => finish(failed('workspace_search_failed', 'workspace search worker stopped; retry with a narrower path'));
|
|
29
|
+
const timer = setTimeout(() => finish(failed('workspace_search_timeout', 'workspace search timed out; retry with a narrower path')), 30_000);
|
|
30
|
+
child.once('message', finish);
|
|
31
|
+
child.once('error', unavailable);
|
|
32
|
+
child.once('exit', unavailable);
|
|
33
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
34
|
+
if (signal?.aborted) abort();
|
|
35
|
+
else child.send(input, error => { if (error) unavailable(); });
|
|
36
|
+
});
|
|
37
|
+
}
|
|
@@ -19,7 +19,7 @@ import { publicErrorMessage, publicErrorCode, publicFailureContent } from '@king
|
|
|
19
19
|
import { createHash } from 'node:crypto';
|
|
20
20
|
import {
|
|
21
21
|
chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readdirSync,
|
|
22
|
-
|
|
22
|
+
readlinkSync, readSync, realpathSync, rmdirSync, statSync,
|
|
23
23
|
unlinkSync,
|
|
24
24
|
} from 'node:fs';
|
|
25
25
|
import { basename, join } from 'node:path';
|
|
@@ -30,13 +30,14 @@ import { prepareWorkspaceEdits } from './workspace-edit-match.mjs';
|
|
|
30
30
|
import { prepareWorkspacePatch } from './workspace-patch.mjs';
|
|
31
31
|
import { workspaceChangeDisplay } from './workspace-display.mjs';
|
|
32
32
|
import { readBoundedWorkspaceImage } from './workspace-image.mjs';
|
|
33
|
+
import { runWorkspaceSearch } from './workspace-search.mjs';
|
|
33
34
|
import { createWorkspaceCheckpointJournal, captureCheckpointFile, checkpointStatesEqual, WORKSPACE_CHECKPOINT_POLICY, CONVERSATION_WORKSPACE_CONTROL } from './workspace-checkpoints.mjs';
|
|
34
35
|
import { parseStructuredPatch } from '@kingsoftcloud/agentkit-harness-core/patch-parser';
|
|
35
36
|
import { canonical } from '@kingsoftcloud/agentkit-harness-core';
|
|
36
37
|
import { captureWorkspaceSubject } from './workspace-subject-observer.mjs';
|
|
37
38
|
|
|
38
39
|
import {
|
|
39
|
-
WorkspacePathError,
|
|
40
|
+
WorkspacePathError, fnmatch, publishWorkspaceBytes, sha256,
|
|
40
41
|
TWO_MB, resolveWorkspacePath, workspaceRelative,
|
|
41
42
|
} from './workspace-paths.mjs';
|
|
42
43
|
import {
|
|
@@ -349,7 +350,7 @@ export function createNativeWorkspaceTools({
|
|
|
349
350
|
ok: false,
|
|
350
351
|
error_message: 'start_line must be <= end_line',
|
|
351
352
|
path: rel,
|
|
352
|
-
requested_range: { start, end: args.end_line },
|
|
353
|
+
requested_range: { start, end: args.end_line ?? null },
|
|
353
354
|
total_lines: totalLines,
|
|
354
355
|
suggested_action: `Re-read the current file with read_workspace_file(path='${rel}', start_line=${Math.max(1, Math.min(start, totalLines))}) before editing.`,
|
|
355
356
|
};
|
|
@@ -886,87 +887,9 @@ export function createNativeWorkspaceTools({
|
|
|
886
887
|
|
|
887
888
|
function searchWorkspaceFiles(args, ctx) {
|
|
888
889
|
const query = String(args.query ?? '');
|
|
890
|
+
if (!query.trim()) return { ok: false, error_message: 'query is required' };
|
|
889
891
|
const path = String(args.path ?? '.');
|
|
890
|
-
|
|
891
|
-
const glob = args.glob ?? null;
|
|
892
|
-
const caseSensitive = Boolean(args.case_sensitive);
|
|
893
|
-
const contextLines = Number(args.context_lines ?? 0);
|
|
894
|
-
const maxResults = Number(args.max_results ?? 100);
|
|
895
|
-
const needle = query.trim();
|
|
896
|
-
if (!needle) return { ok: false, error_message: 'query is required' };
|
|
897
|
-
const base = resolvePath(path);
|
|
898
|
-
if (!existsSync(base)) return { ok: false, error_code: 'workspace_path_not_found', error_message: `workspace path not found: ${path}` };
|
|
899
|
-
const candidates = [];
|
|
900
|
-
if (lstatSync(base, { bigint: true }).isFile()) {
|
|
901
|
-
candidates.push(base);
|
|
902
|
-
} else {
|
|
903
|
-
// Real files beneath the base subtree; symlinked directories are not
|
|
904
|
-
// followed so the search cannot escape the workspace root.
|
|
905
|
-
const stack = [base];
|
|
906
|
-
while (stack.length) {
|
|
907
|
-
const cur = stack.pop();
|
|
908
|
-
let dirents;
|
|
909
|
-
try { dirents = readdirSync(cur, { withFileTypes: true }); } catch { continue; }
|
|
910
|
-
for (const d of dirents) {
|
|
911
|
-
const abs = join(cur, d.name);
|
|
912
|
-
if (d.isFile()) candidates.push(abs);
|
|
913
|
-
else if (d.isDirectory() && !d.isSymbolicLink()) stack.push(abs);
|
|
914
|
-
}
|
|
915
|
-
}
|
|
916
|
-
}
|
|
917
|
-
let filtered = candidates;
|
|
918
|
-
if (glob) {
|
|
919
|
-
filtered = candidates.filter((c) => {
|
|
920
|
-
const rel = relativeOf(c);
|
|
921
|
-
return fnmatch(rel, glob) || fnmatch(basename(c), glob);
|
|
922
|
-
});
|
|
923
|
-
}
|
|
924
|
-
let pattern;
|
|
925
|
-
try {
|
|
926
|
-
pattern = new RegExp(isRegex ? needle : escapeRegex(needle), caseSensitive ? '' : 'i');
|
|
927
|
-
} catch (e) {
|
|
928
|
-
return { ok: false, error_code: 'invalid_search_pattern', error_message: publicErrorMessage(e) };
|
|
929
|
-
}
|
|
930
|
-
const limit = Math.max(1, Math.min(maxResults || 100, 5000));
|
|
931
|
-
const contextLimit = Math.max(0, Math.min(contextLines || 0, 20));
|
|
932
|
-
const results = [];
|
|
933
|
-
let truncated = false;
|
|
934
|
-
outer:
|
|
935
|
-
for (const item of filtered) {
|
|
936
|
-
if (ctx?.signal?.aborted) return { ok: false, error_code: 'canceled', error_message: 'workspace search canceled' };
|
|
937
|
-
let size;
|
|
938
|
-
try { size = Number(lstatSync(item, { bigint: true }).size); } catch { continue; }
|
|
939
|
-
if (size > 1024 * 1024) continue;
|
|
940
|
-
let payload;
|
|
941
|
-
try { payload = readFileSync(item); } catch { continue; }
|
|
942
|
-
let text;
|
|
943
|
-
try { text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(payload); }
|
|
944
|
-
catch { continue; }
|
|
945
|
-
const lines = splitlines(text);
|
|
946
|
-
for (let i = 0; i < lines.length; i++) {
|
|
947
|
-
const line = lines[i];
|
|
948
|
-
if (!pattern.test(line)) continue;
|
|
949
|
-
if (results.length >= limit) { truncated = true; break outer; }
|
|
950
|
-
results.push({
|
|
951
|
-
path: relativeOf(item),
|
|
952
|
-
line: i + 1,
|
|
953
|
-
text: line,
|
|
954
|
-
snippet: line,
|
|
955
|
-
context_before: lines.slice(Math.max(0, i - contextLimit), i),
|
|
956
|
-
context_after: lines.slice(i + 1, i + 1 + contextLimit),
|
|
957
|
-
});
|
|
958
|
-
}
|
|
959
|
-
}
|
|
960
|
-
return {
|
|
961
|
-
ok: true,
|
|
962
|
-
query,
|
|
963
|
-
searched_path: path,
|
|
964
|
-
results,
|
|
965
|
-
match_count: results.length,
|
|
966
|
-
truncated,
|
|
967
|
-
context_lines: contextLimit,
|
|
968
|
-
search_backend: 'node',
|
|
969
|
-
};
|
|
892
|
+
return runWorkspaceSearch({ args: { ...args, query, path }, root: pinnedRootReal, base: resolvePath(path) }, ctx?.signal);
|
|
970
893
|
}
|
|
971
894
|
|
|
972
895
|
function deleteWorkspaceFile(args) {
|
|
@@ -1208,14 +1131,14 @@ export function createNativeWorkspaceTools({
|
|
|
1208
1131
|
return { status: 'error', content: { ok: false, error_type: publicErrorCode(e, 'internal_error'), error_message: publicErrorMessage(e) } };
|
|
1209
1132
|
} finally { activeMutations = previousMutations; activeGuard = previousGuard; activeCheckpoint = previousCheckpoint; activeDisplayChanges = previousDisplayChanges;
|
|
1210
1133
|
activePublications = previousPublications; activeReads = previousReads; release?.(); }
|
|
1211
|
-
// The only
|
|
1134
|
+
// The read-only syntax and search implementations can run asynchronously.
|
|
1212
1135
|
// Restore mutation tracking before any await so concurrent writers cannot
|
|
1213
1136
|
// attribute their publications to this invocation.
|
|
1214
1137
|
if (result && typeof result.then === 'function') {
|
|
1215
1138
|
try { result = await result; }
|
|
1216
1139
|
catch (error) {
|
|
1217
1140
|
if (signal?.aborted) return canceled();
|
|
1218
|
-
return { status: 'error', content: { ok: false, error_type: publicErrorCode(error, 'python_syntax_unavailable'),
|
|
1141
|
+
return { status: 'error', content: { ok: false, error_type: publicErrorCode(error, name === 'search_workspace_files' ? 'workspace_search_failed' : 'python_syntax_unavailable'),
|
|
1219
1142
|
error_message: publicErrorMessage(error) } };
|
|
1220
1143
|
}
|
|
1221
1144
|
}
|