@kmugalkhod/lightcode 0.18.4 → 0.18.5
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/assets/web/{index-kj8t3m63.js → index-89rgdkry.js} +1 -1
- package/assets/web/index.html +1 -1
- package/cli.js +17 -8
- package/package.json +1 -1
- package/server.js +17 -8
|
@@ -96,7 +96,7 @@ Error message: ${OR(J)}`,cause:J});this[HR]=!0,this.value=U,this.context=Y}stati
|
|
|
96
96
|
|
|
97
97
|
`)},flush($){$.enqueue(`data: [DONE]
|
|
98
98
|
|
|
99
|
-
`)}})}};var xX=W.record(W.string(),e8.optional()),Jr=dU(()=>e6(W.union([W.strictObject({type:W.literal("text-start"),id:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("text-delta"),id:W.string(),delta:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("text-end"),id:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("error"),errorText:W.string()}),W.strictObject({type:W.literal("tool-input-start"),toolCallId:W.string(),toolName:W.string(),providerExecuted:W.boolean().optional(),providerMetadata:D$.optional(),toolMetadata:xX.optional(),dynamic:W.boolean().optional(),title:W.string().optional()}),W.strictObject({type:W.literal("tool-input-delta"),toolCallId:W.string(),inputTextDelta:W.string()}),W.strictObject({type:W.literal("tool-input-available"),toolCallId:W.string(),toolName:W.string(),input:W.unknown(),providerExecuted:W.boolean().optional(),providerMetadata:D$.optional(),toolMetadata:xX.optional(),dynamic:W.boolean().optional(),title:W.string().optional()}),W.strictObject({type:W.literal("tool-input-error"),toolCallId:W.string(),toolName:W.string(),input:W.unknown(),providerExecuted:W.boolean().optional(),providerMetadata:D$.optional(),toolMetadata:xX.optional(),dynamic:W.boolean().optional(),errorText:W.string(),title:W.string().optional()}),W.strictObject({type:W.literal("tool-approval-request"),approvalId:W.string(),toolCallId:W.string()}),W.strictObject({type:W.literal("tool-output-available"),toolCallId:W.string(),output:W.unknown(),providerExecuted:W.boolean().optional(),providerMetadata:D$.optional(),toolMetadata:xX.optional(),dynamic:W.boolean().optional(),preliminary:W.boolean().optional()}),W.strictObject({type:W.literal("tool-output-error"),toolCallId:W.string(),errorText:W.string(),providerExecuted:W.boolean().optional(),providerMetadata:D$.optional(),toolMetadata:xX.optional(),dynamic:W.boolean().optional()}),W.strictObject({type:W.literal("tool-output-denied"),toolCallId:W.string()}),W.strictObject({type:W.literal("reasoning-start"),id:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("reasoning-delta"),id:W.string(),delta:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("reasoning-end"),id:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("source-url"),sourceId:W.string(),url:W.string(),title:W.string().optional(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("source-document"),sourceId:W.string(),mediaType:W.string(),title:W.string(),filename:W.string().optional(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("file"),url:W.string(),mediaType:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.custom(($)=>typeof $==="string"&&$.startsWith("data-"),{message:'Type must start with "data-"'}),id:W.string().optional(),data:W.unknown(),transient:W.boolean().optional()}),W.strictObject({type:W.literal("start-step")}),W.strictObject({type:W.literal("finish-step")}),W.strictObject({type:W.literal("start"),messageId:W.string().optional(),messageMetadata:W.unknown().optional()}),W.strictObject({type:W.literal("finish"),finishReason:W.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:W.unknown().optional()}),W.strictObject({type:W.literal("abort"),reason:W.string().optional()}),W.strictObject({type:W.literal("message-metadata"),messageMetadata:W.unknown()})])));function Xr($){return $.type.startsWith("tool-")}function VT($){return $.type==="dynamic-tool"}function l4($){return Xr($)||VT($)}function Yr($){return $.type.split("-").slice(1).join("-")}function QJ($){return VT($)?$.toolName:Yr($)}var a5$=_1({prefix:"aitxt",size:24});var c1=W.record(W.string(),e8.optional()),wr=dU(()=>e6(W.array(W.object({id:W.string(),role:W.enum(["system","user","assistant"]),metadata:W.unknown().optional(),parts:W.array(W.union([W.object({type:W.literal("text"),text:W.string(),state:W.enum(["streaming","done"]).optional(),providerMetadata:D$.optional()}),W.object({type:W.literal("reasoning"),text:W.string(),state:W.enum(["streaming","done"]).optional(),providerMetadata:D$.optional()}),W.object({type:W.literal("source-url"),sourceId:W.string(),url:W.string(),title:W.string().optional(),providerMetadata:D$.optional()}),W.object({type:W.literal("source-document"),sourceId:W.string(),mediaType:W.string(),title:W.string(),filename:W.string().optional(),providerMetadata:D$.optional()}),W.object({type:W.literal("file"),mediaType:W.string(),filename:W.string().optional(),url:W.string(),providerMetadata:D$.optional()}),W.object({type:W.literal("step-start")}),W.object({type:W.string().startsWith("data-"),id:W.string().optional(),data:W.unknown()}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("input-streaming"),input:W.unknown().optional(),providerExecuted:W.boolean().optional(),callProviderMetadata:D$.optional(),output:W.never().optional(),errorText:W.never().optional(),approval:W.never().optional()}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("input-available"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.never().optional()}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("approval-requested"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.never().optional(),reason:W.never().optional()})}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("approval-responded"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.boolean(),reason:W.string().optional()})}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("output-available"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.unknown(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),resultProviderMetadata:D$.optional(),preliminary:W.boolean().optional(),approval:W.object({id:W.string(),approved:W.literal(!0),reason:W.string().optional()}).optional()}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("output-error"),input:W.unknown().optional(),rawInput:W.unknown().optional(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.string(),callProviderMetadata:D$.optional(),resultProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.literal(!0),reason:W.string().optional()}).optional()}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("output-denied"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.literal(!1),reason:W.string().optional()})}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("input-streaming"),providerExecuted:W.boolean().optional(),callProviderMetadata:D$.optional(),input:W.unknown().optional(),output:W.never().optional(),errorText:W.never().optional(),approval:W.never().optional()}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("input-available"),providerExecuted:W.boolean().optional(),input:W.unknown(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.never().optional()}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("approval-requested"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.never().optional(),reason:W.never().optional()})}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("approval-responded"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.boolean(),reason:W.string().optional()})}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("output-available"),providerExecuted:W.boolean().optional(),input:W.unknown(),output:W.unknown(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),resultProviderMetadata:D$.optional(),preliminary:W.boolean().optional(),approval:W.object({id:W.string(),approved:W.literal(!0),reason:W.string().optional()}).optional()}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("output-error"),providerExecuted:W.boolean().optional(),input:W.unknown().optional(),rawInput:W.unknown().optional(),output:W.never().optional(),errorText:W.string(),callProviderMetadata:D$.optional(),resultProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.literal(!0),reason:W.string().optional()}).optional()}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("output-denied"),providerExecuted:W.boolean().optional(),input:W.unknown(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.literal(!1),reason:W.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));async function OT({messages:$,metadataSchema:U,dataSchemas:J,tools:Y}){try{if($==null)return{success:!1,error:new Fc({parameter:"messages",value:$,message:"messages parameter must be provided"})};let X=await _6({value:$,schema:wr});if(U)for(let[w,G]of X.entries())await _6({value:G.metadata,schema:U,context:{field:`messages[${w}].metadata`,entityId:G.id}});if(J||Y)for(let[w,G]of X.entries())for(let[Q,H]of G.parts.entries()){if(J&&H.type.startsWith("data-")){let z=H,D=z.type.slice(5),q=J[D];if(!q)return{success:!1,error:new $U({value:z.data,cause:`No data schema found for data part ${D}`,context:{field:`messages[${w}].parts[${Q}].data`,entityName:D,entityId:z.id}})};await _6({value:z.data,schema:q,context:{field:`messages[${w}].parts[${Q}].data`,entityName:D,entityId:z.id}})}if(Y&&H.type.startsWith("tool-")){let z=H,D=z.type.slice(5),q=Y[D];if(!q&&(z.state==="output-available"||z.state==="output-error"||z.state==="output-denied"))continue;if(!q)return{success:!1,error:new $U({value:z.input,cause:`No tool schema found for tool part ${D}`,context:{field:`messages[${w}].parts[${Q}].input`,entityName:D,entityId:z.toolCallId}})};if(z.state==="input-available"||z.state==="output-available"||z.state==="output-error"&&z.input!==void 0)await _6({value:z.input,schema:q.inputSchema,context:{field:`messages[${w}].parts[${Q}].input`,entityName:D,entityId:z.toolCallId}});if(z.state==="output-available"&&q.outputSchema)await _6({value:z.output,schema:q.outputSchema,context:{field:`messages[${w}].parts[${Q}].output`,entityName:D,entityId:z.toolCallId}})}}return{success:!0,data:X}}catch(X){return{success:!1,error:X}}}var U9$=_1({prefix:"aiobj",size:24});function NT($){return({url:U,abortSignal:J})=>hd({url:U,maxBytes:$==null?void 0:$.maxBytes,abortSignal:J})}var X9$=_1({prefix:"aiobj",size:24});var Y9$=NT();var Gr="AI_NoSuchProviderError",Qr=`vercel.ai.error.${Gr}`,Wr=Symbol.for(Qr),Hr;Hr=Wr;var w9$=NT();var zr=class{constructor({api:$="/api/chat",credentials:U,headers:J,body:Y,fetch:X,prepareSendMessagesRequest:w,prepareReconnectToStreamRequest:G}){this.api=$,this.credentials=U,this.headers=J,this.body=Y,this.fetch=X,this.prepareSendMessagesRequest=w,this.prepareReconnectToStreamRequest=G}async sendMessages({abortSignal:$,...U}){var J,Y,X,w,G;let Q=await p0(this.body),H=await p0(this.headers),z=await p0(this.credentials),D={...P1(H),...P1(U.headers)},q=await((J=this.prepareSendMessagesRequest)==null?void 0:J.call(this,{api:this.api,id:U.chatId,messages:U.messages,body:{...Q,...U.body},headers:D,credentials:z,requestMetadata:U.metadata,trigger:U.trigger,messageId:U.messageId})),L=(Y=q==null?void 0:q.api)!=null?Y:this.api,B=(q==null?void 0:q.headers)!==void 0?P1(q.headers):D,O=(q==null?void 0:q.body)!==void 0?q.body:{...Q,...U.body,id:U.chatId,messages:U.messages,trigger:U.trigger,messageId:U.messageId},A=(X=q==null?void 0:q.credentials)!=null?X:z,V=await((w=this.fetch)!=null?w:globalThis.fetch)(L,{method:"POST",headers:{"Content-Type":"application/json",...B},body:JSON.stringify(O),credentials:A,signal:$});if(!V.ok)throw Error((G=await V.text())!=null?G:"Failed to fetch the chat response.");if(!V.body)throw Error("The response body is empty.");return this.processResponseStream(V.body)}async reconnectToStream($){var U,J,Y,X,w;let G=await p0(this.body),Q=await p0(this.headers),H=await p0(this.credentials),z={...P1(Q),...P1($.headers)},D=await((U=this.prepareReconnectToStreamRequest)==null?void 0:U.call(this,{api:this.api,id:$.chatId,body:{...G,...$.body},headers:z,credentials:H,requestMetadata:$.metadata})),q=(J=D==null?void 0:D.api)!=null?J:`${this.api}/${$.chatId}/stream`,L=(D==null?void 0:D.headers)!==void 0?P1(D.headers):z,B=(Y=D==null?void 0:D.credentials)!=null?Y:H,A=await((X=this.fetch)!=null?X:globalThis.fetch)(q,{method:"GET",headers:L,credentials:B});if(A.status===204)return null;if(!A.ok)throw Error((w=await A.text())!=null?w:"Failed to fetch the chat response.");if(!A.body)throw Error("The response body is empty.");return this.processResponseStream(A.body)}},AT=class extends zr{constructor($={}){super($)}processResponseStream($){return xG({stream:$,schema:Jr}).pipeThrough(new TransformStream({async transform(U,J){if(!U.success)throw U.error;J.enqueue(U.value)}}))}};function FT({messages:$}){let U=$[$.length-1];if(!U)return!1;if(U.role!=="assistant")return!1;let J=U.parts.reduce((X,w,G)=>{return w.type==="step-start"?G:X},-1),Y=U.parts.slice(J+1).filter(l4);return Y.filter((X)=>X.state==="approval-responded").length>0&&Y.every((X)=>X.state==="output-available"||X.state==="output-error"||X.state==="approval-responded")}function bT({messages:$}){let U=$[$.length-1];if(!U)return!1;if(U.role!=="assistant")return!1;let J=U.parts.reduce((X,w,G)=>{return w.type==="step-start"?G:X},-1),Y=U.parts.slice(J+1).filter(l4).filter((X)=>!X.providerExecuted);return Y.length>0&&Y.every((X)=>X.state==="output-available"||X.state==="output-error")}var e=M0(f0(),1);var O6=12000,aU=6000,$5=200,kX=200;var QV=200,WV=80;var Dr=["agent","list_files","glob_search","read_file","grep","git_status","git_diff","git_log","git_show","tool_search","skill","list_mcp_resources","read_mcp_resource","call_mcp_tool","request_user_input","todo_write","write_file","edit_file","bash","web_fetch","web_search"],p4=W.enum(Dr),qr=["build","plan"],c4=W.enum(qr),HV="build";var Br=["read-only","workspace-write","danger-full-access"],d1=W.enum(Br),Lr=W.enum(["allow","ask","deny"]),yX=W.object({allow:W.array(W.string().min(1).max(2000)).optional(),deny:W.array(W.string().min(1).max(2000)).optional(),ask:W.array(W.string().min(1).max(2000)).optional(),deniedTools:W.array(W.string().min(1).max(120)).optional()}),ZT=W.object({outcome:Lr,toolName:W.string().min(1).max(120),activeMode:d1,requiredMode:d1,reason:W.string().min(1).max(2000).optional()}),MT={"read-only":0,"workspace-write":1,"danger-full-access":2};function U5($){return $.trim().replaceAll("-","_").toLowerCase()}function _r($,U){return MT[$]>=MT[U]}function Kr($){return{allow:$?.allow??[],deny:$?.deny??[],ask:$?.ask??[],deniedTools:$?.deniedTools??[]}}function Vr($,U){let J=!1;for(let Y=0;Y<$.length;Y+=1){let X=$[Y];if(X==="\\"){J=!J;continue}if(X===U&&!J)return Y;J=!1}return-1}function Or($,U){for(let J=$.length-1;J>=0;J-=1){if($[J]!==U)continue;let Y=0;for(let X=J-1;X>=0;X-=1){if($[X]!=="\\")break;Y+=1}if(Y%2===0)return J}return-1}function Nr($){return $.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function Ar($){let U=Nr($.trim());if(!U||U==="*")return{kind:"any"};if(U.endsWith(":*"))return{kind:"prefix",value:U.slice(0,-2)};return{kind:"exact",value:U}}function Fr($){let U=$.trim(),J=Vr(U,"("),Y=Or(U,")");if(J>0&&Y===U.length-1&&J<Y){let X=U.slice(0,J).trim(),w=U.slice(J+1,Y);if(X)return{raw:U,toolName:U5(X),matcher:Ar(w)}}return{raw:U,toolName:U5(U),matcher:{kind:"any"}}}function br($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Mr($){if(br($))for(let U of["command","path","query","pattern","filePath","file_path","url"]){let J=Reflect.get($,U);if(typeof J==="string"&&J.trim())return J.trim()}if(typeof $==="string"&&$.trim())return $.trim();return""}function Zr($,U,J){if($.toolName!==U5(U))return!1;if($.matcher.kind==="any")return!0;let Y=Mr(J);if($.matcher.kind==="exact")return Y===$.matcher.value;return Y.startsWith($.matcher.value)}function zV($,U,J){return $.map(Fr).find((Y)=>Zr(Y,U,J))}class DV{activeMode;toolRequirements;allowedTools;rules;approved;constructor({activeMode:$,toolRequirements:U,allowedTools:J,rules:Y,approved:X=!1}){this.activeMode=$,this.toolRequirements=U,this.allowedTools=J&&J.length>0?new Set(J.map(U5)):null,this.rules=Kr(Y),this.approved=X}requiredModeFor($){return this.toolRequirements[U5($)]??"danger-full-access"}decide($,U){let J=U5($),Y=this.requiredModeFor($),X={toolName:$,activeMode:this.activeMode,requiredMode:Y};if(this.allowedTools&&!this.allowedTools.has(J))return{...X,outcome:"deny",reason:`Tool "${$}" is not enabled for this session.`};if(this.rules.deniedTools.map(U5).includes(J))return{...X,outcome:"deny",reason:`Tool "${$}" is denied by policy.`};let w=zV(this.rules.deny,$,U);if(w)return{...X,outcome:"deny",reason:`Tool "${$}" is denied by rule "${w.raw}".`};let G=zV(this.rules.ask,$,U);if(G&&!this.approved)return{...X,outcome:"ask",reason:`Tool "${$}" requires approval by rule "${G.raw}".`};if(zV(this.rules.allow,$,U)||_r(this.activeMode,Y))return{...X,outcome:"allow"};if(this.activeMode==="workspace-write"&&Y==="danger-full-access"){if(this.approved)return{...X,outcome:"allow"};return{...X,outcome:"ask",reason:`Tool "${$}" requires approval to escalate from ${this.activeMode} to ${Y}.`}}if(J==="web_search"&&this.activeMode==="read-only"&&Y==="danger-full-access"){if(this.approved)return{...X,outcome:"allow"};return{...X,outcome:"ask",reason:'Tool "web_search" requires approval for network access.'}}return{...X,outcome:"deny",reason:`Tool "${$}" requires ${Y} permission; current mode is ${this.activeMode}.`}}}var jr=W.enum(["disabled","read-only","workspace-write"]),Ir=W.enum(["inherit","disabled"]),WJ=W.object({enabled:W.boolean().optional().default(!1),mode:jr.optional().default("disabled"),network:Ir.optional().default("inherit")}),A9$=WJ.extend({supported:W.boolean(),isolation:W.literal("process-guards"),unsupportedReason:W.string().optional()});var Rr=new Set(["cat","dir","findstr","get-childitem","get-content","grep","ls","pwd","rg","select-string","type"]),Tr=new Set(["bun","bunx","npm","npx","pnpm","yarn"]),Sr=new Set(["curl","ftp","iwr","invoke-restmethod","invoke-webrequest","nc","netcat","scp","sftp","ssh","telnet","wget"]),Er=new Set(["del","erase","rd","rm","rmdir","remove-item"]),Pr=new Set(["kill","pkill","start-process","stop-process","taskkill"]),gr=new Set(["mkdir","new-item","touch"]),Cr=new Set(["diff","log","show","status"]);function c0($,U,J){return{permissionMode:d1.parse($),reason:U,baseCommand:J}}function vr($){return $.trim().replace(/\.(?:cmd|exe|bat|ps1)$/i,"").toLowerCase()}function xr($){let U=[],J="",Y=null;for(let X=0;X<$.length;X+=1){let w=$[X];if((w==='"'||w==="'")&&Y===null){Y=w;continue}if(w===Y){Y=null;continue}if(/\s/.test(w)&&Y===null){if(J)U.push(J),J="";continue}J+=w}if(J)U.push(J);return U}function kr($){let U=null;for(let J=0;J<$.length;J+=1){let Y=$[J],X=$[J+1];if((Y==='"'||Y==="'")&&U===null){U=Y;continue}if(Y===U){U=null;continue}if(U!==null)continue;if(Y===">"||Y==="<"||Y==="|"||Y===";"||Y==="`"||Y==="&")return!0;if(Y==="$"&&X==="(")return!0}return!1}function qV($){return $.some((U)=>{if(!U||U.startsWith("-"))return!1;if(/^[a-z]:[\\/]/i.test(U)||U.startsWith("/")||U.startsWith("~"))return!0;return U.split(/[\\/]+/).includes("..")})}function yr($,U){let J=$[1]?.toLowerCase();if(!J)return c0("read-only","git with no subcommand only prints help.",U);if(!Cr.has(J))return c0("danger-full-access",`git ${J} may mutate repository state or run hooks.`,U);if($.some((Y)=>Y.startsWith("--output")))return c0("danger-full-access","git diff/show output options can write files.",U);if(qV($.slice(2)))return c0("danger-full-access","git read command references a path outside the workspace.",U);return c0("read-only",`git ${J} is treated as read-only.`,U)}function hr($,U){if($[1]==="run"&&$[2]==="typecheck")return c0("read-only","bun run typecheck is treated as read-only.",U);if(["add","install","link","remove","unlink","update","upgrade"].includes($[1]??""))return c0("danger-full-access",`bun ${$[1]} can change dependencies or run lifecycle scripts.`,U);return c0("danger-full-access","bun commands other than the known typecheck script can run arbitrary package scripts.",U)}function fr($,U){if(U==="bun")return hr($,U);return c0("danger-full-access",`${U} can install packages, run scripts, or access the network.`,U)}function jT($){let U=$.trim();if(!U)return c0("danger-full-access","Empty shell commands are not executable.");if(kr(U))return c0("danger-full-access","Shell control operators, redirects, pipes, or substitutions require full approval.");let J=xr(U),Y=vr(J[0]??"");if(!Y)return c0("danger-full-access","Unable to identify the shell command.");if(Sr.has(Y))return c0("danger-full-access",`${Y} can access the network or remote systems.`,Y);if(Er.has(Y))return c0("danger-full-access",`${Y} can delete files or directories.`,Y);if(Pr.has(Y))return c0("danger-full-access",`${Y} can control processes outside the workspace.`,Y);if(Tr.has(Y))return fr(J,Y);if(Y==="git")return yr(J,Y);if(Rr.has(Y)){if(qV(J.slice(1)))return c0("danger-full-access",`${Y} references an absolute, home, or parent path.`,Y);return c0("read-only",`${Y} is treated as a read-only command.`,Y)}if(gr.has(Y)){if(qV(J.slice(1)))return c0("danger-full-access",`${Y} references an absolute, home, or parent path.`,Y);return c0("workspace-write",`${Y} is treated as a workspace-local write command.`,Y)}return c0("danger-full-access",`Unknown shell command "${Y}" requires full approval.`,Y)}var ur=W.enum(["heuristic","llm"]),mG=W.object({sessionId:W.string().min(1),summary:W.string().min(1),anchorMessageId:W.string().min(1),coveredMessageCount:W.number().int().positive(),estimatedTokens:W.number().int().nonnegative(),tier:ur,model:W.string().nullable(),createdAt:W.string().min(1),updatedAt:W.string().min(1)});var IT=W.enum(["auto","provider","brave","tavily","disabled"]),hX=W.enum(["approved","denied"]),R9$=W.object({backend:IT.optional(),maxResults:W.number().int().min(1).max(25).optional(),maxUsesPerTurn:W.number().int().min(1).max(30).optional(),maxCharactersPerResult:W.number().int().min(1).max(1e5).optional(),timeoutMs:W.number().int().min(1000).max(120000).optional()}).strict(),T9$=W.object({backend:IT,maxResults:W.number().int().min(1).max(25),maxUsesPerTurn:W.number().int().min(1).max(30),maxCharactersPerResult:W.number().int().min(1).max(1e5),timeoutMs:W.number().int().min(1000).max(120000)});var mr=W.enum(["openrouter","anthropic","brave","tavily","disabled","unavailable"]),ir=W.enum(["provider","local","none"]),lr=W.object({maxResults:W.number().int().positive(),maxTotalResults:W.number().int().positive(),maxUsesPerTurn:W.number().int().positive(),maxCharactersPerResult:W.number().int().positive(),timeoutMs:W.number().int().positive()}),S9$=W.object({available:W.boolean(),backend:mr,execution:ir,limits:lr,reason:W.string().nullable()});var N6=W.string().uuid(),fX=W.union([N6,W.literal("latest")]),f9$=W.object({id:fX}),u9$=W.object({id:N6}),m9$=W.object({cwd:W.string().min(1).max(4096).optional(),mode:c4.optional(),permissionMode:d1.optional(),title:W.string().min(1).max(120).optional()}),i9$=W.object({id:N6}),l9$=W.object({title:W.string().min(1).max(120).optional(),permissionMode:d1.optional()}),p9$=W.object({id:N6,copiedMessages:W.number().int().nonnegative()}),iG=W.object({id:N6,title:W.string().nullable(),cwd:W.string().nullable(),mode:c4,permissionMode:d1.nullable(),model:W.string().nullable(),revision:W.number().int().nonnegative(),createdAt:W.string().min(1),updatedAt:W.string().min(1)}),pr=iG.extend({messageCount:W.number().int().nonnegative(),latestUserPromptPreview:W.string().nullable()}),c9$=W.object({sessions:W.array(pr)}),d9$=W.object({session:iG.optional(),messages:W.array(W.json()),contextState:mG.nullable().optional()}),cr=W.object({tokens:W.number().nonnegative(),basis:W.enum(["usage_calibrated","heuristic"])}),dr=W.object({systemTokens:W.number().int().nonnegative(),toolTokens:W.number().int().nonnegative(),messageTokens:W.number().int().nonnegative(),mediaTokens:W.number().int().nonnegative(),inputTokens:W.number().int().nonnegative(),inputBudgetTokens:W.number().int().nonnegative(),messageBudgetTokens:W.number().int().nonnegative(),reservedOutputTokens:W.number().int().nonnegative(),contextWindow:W.number().int().positive(),remainingTokens:W.number().int().nonnegative(),compactedTokens:W.number().int().nonnegative()}),r9$=W.object({contextState:mG.nullable(),estimate:cr,contextWindow:W.number().int().positive(),breakdown:dr,withinBudget:W.boolean()}),n9$=W.object({contextState:mG,usedFallback:W.boolean()}),o9$=W.object({session:iG,messages:W.array(W.json())}),a9$=W.object({id:N6,deleted:W.boolean(),deletedMessages:W.number().int().nonnegative()}),t9$=W.object({clientTurnId:W.string().min(1).max(320),expectedRevision:W.number().int().nonnegative(),messageId:W.string().min(1).max(320),role:W.enum(["user","assistant"]),parts:W.array(W.json()).min(1),metadata:W.json().optional(),trigger:W.string().min(1).max(80).optional(),mode:c4.optional(),permissionMode:d1.optional(),providerWebSearchDecision:hX.optional(),allowedTools:W.array(p4).optional(),permissionRules:yX.optional(),sandbox:WJ.optional()}).strict(),RT=W.enum(["pending","running","completed","failed","cancelled"]),s9$=W.object({id:fX,runId:W.string().uuid()}),e9$=W.object({after:W.coerce.number().int().min(-1).default(-1)}),rr=W.object({cursor:W.number().int().nonnegative(),kind:W.string().min(1).max(80),payload:W.json(),createdAt:W.string().min(1)}),$J$=W.object({runId:W.string().uuid(),status:RT,events:W.array(rr),nextCursor:W.number().int().min(-1)}),UJ$=W.object({runId:W.string().uuid(),status:RT,aborted:W.boolean()}),JJ$=W.object({turnKey:W.string().min(1),restoredFiles:W.array(W.string()),messageCount:W.number().int().nonnegative(),revision:W.number().int().nonnegative()}),XJ$=W.object({exportedAt:W.string().min(1),session:iG,messages:W.array(W.json())});var nr="plan",or=["explore"],BV=W.enum(or),TT="explore";var ST=2000;var ar=["pending","running","completed","failed","blocked_on_approval","blocked_on_provider","cancelled"],LV=W.enum(ar),tr=W.json(),sr=W.object({parentSessionId:N6,prompt:W.string().min(1).max(50000),mode:c4.default(nr),model:W.string().min(1).max(200).nullable().optional(),allowedTools:W.array(p4).default([])}),er=sr.extend({id:W.string().uuid(),status:LV,model:W.string().nullable(),output:tr.nullable(),error:W.string().nullable(),startedAt:W.string().min(1).nullable(),finishedAt:W.string().min(1).nullable(),createdAt:W.string().min(1),updatedAt:W.string().min(1)}),WJ$=W.object({tasks:W.array(er)});var ET=`Spawn a read-only subagent that explores the codebase in a fresh context and returns only a final summary (max ~${ST} tokens). Use it for broad searches or multi-file questions where you need conclusions, not raw file contents. It cannot see this conversation or modify files, so make the prompt self-contained: the question, relevant paths/symbols, and what the report must contain.`,PT=W.object({description:W.string().min(1).max(100),prompt:W.string().min(1).max(50000),profile:BV.optional().default(TT),model:W.string().min(1).max(200).optional()}),gT=W.object({description:W.string().min(1).max(100).describe("Short 3-5 word label for the task"),prompt:W.string().min(1).describe("Self-contained task for the subagent"),profile:BV.optional(),model:W.string().optional().describe("Optional model id override; defaults to the session model")}),CT=W.object({taskId:W.string().nullable(),status:LV,summary:W.string(),truncated:W.boolean()});var $n=W.number().finite().refine(($)=>Number.isInteger($),{error:"Expected an integer value."});function j0($,U,J){return $n.refine((Y)=>Y>=$&&Y<=U,{error:`${J} must be between ${$} and ${U}.`})}var R0=W.string().min(1).max(4096),uX=j0(1,1e6,"Line number");var vT="Run a shell command from workspace root with a timeout. Bound noisy output at the source (head/tail/grep/wc) — output is truncated head+tail. Commands may require approval.",xT=W.object({command:W.string().min(1).max(4000),timeoutMs:j0(1000,120000,"timeoutMs").optional().default(30000),maxOutputChars:j0(200,O6,"maxOutputChars").optional().default(aU)}),kT=W.object({command:W.string().min(1).max(4000)}),yT=W.object({command:W.string(),cwd:W.string(),stdout:W.string(),stderr:W.string(),exitCode:W.number().int(),truncated:W.boolean()});var hT="Edit a file via search and replace; copy the search text as shown by read_file (whitespace and line endings are matched tolerantly). It must match exactly one "+"place — add surrounding context to disambiguate, or set replaceAll: true.",_V=W.object({path:R0,search:W.string().min(1),replace:W.string(),replaceAll:W.boolean().optional().default(!1)}),fT=_V,uT=W.object({path:W.string(),replacements:W.number().int().nonnegative(),bytesWritten:W.number().int().nonnegative(),diff:W.string().optional()});var mT="Search project files for text or regex matches and return file path plus line information.",iT=W.object({query:W.string().min(1).max(1000),path:R0.optional().default("."),isRegex:W.boolean().optional().default(!1),caseSensitive:W.boolean().optional().default(!1),maxResults:j0(1,kX,"maxResults").optional().default(50)}),lT=W.object({query:W.string().min(1).max(1000),path:R0,isRegex:W.boolean().optional(),caseSensitive:W.boolean().optional()}),pT=W.object({query:W.string(),path:W.string(),matches:W.array(W.object({path:W.string(),lineNumber:W.number().int().min(1),column:W.number().int().min(1),line:W.string()})),totalMatches:W.number().int().nonnegative(),truncated:W.boolean()});var cT="Find workspace files by glob pattern. Use this when you know a filename shape, extension, or path pattern.",dT=W.object({pattern:W.string().min(1).max(1000),path:R0.optional().default("."),includeHidden:W.boolean().optional().default(!1),includeDirectories:W.boolean().optional().default(!1),maxResults:j0(1,$5,"maxResults").optional().default(100)}),rT=W.object({pattern:W.string().min(1).max(1000),path:R0.optional(),includeHidden:W.boolean().optional()}),nT=W.object({pattern:W.string(),path:W.string(),matches:W.array(W.object({path:W.string(),type:W.enum(["file","directory","symlink","other"]),size:W.number().int().nonnegative().nullable()})),totalMatches:W.number().int().nonnegative(),truncated:W.boolean()});var oT="Return structured git status for the workspace without running an arbitrary shell command.",aT="Return a bounded git diff for workspace changes. Use this to inspect edits before summarizing.",tT="Return recent git commits as structured metadata.",sT="Show a commit or revision with bounded patch output.",eT=W.object({maxEntries:j0(1,$5,"maxEntries").optional().default(100)}),$S=W.object({}),US=W.object({path:R0.optional(),staged:W.boolean().optional().default(!1),statOnly:W.boolean().optional().default(!1),maxChars:j0(200,O6,"maxChars").optional().default(aU)}),JS=W.object({path:R0.optional(),staged:W.boolean().optional(),statOnly:W.boolean().optional()}),KV=W.object({path:R0.optional(),maxCommits:j0(1,50,"maxCommits").optional().default(10)}),XS=KV,YS=W.object({revision:W.string().min(1).max(240),path:R0.optional(),maxChars:j0(200,O6,"maxChars").optional().default(aU)}),wS=W.object({revision:W.string().min(1).max(240),path:R0.optional()}),lG=W.object({code:W.string(),message:W.string(),exitCode:W.number().int().nullable(),stdout:W.string(),stderr:W.string()}),GS=W.object({ok:W.boolean(),cwd:W.string(),branch:W.string().nullable(),upstream:W.string().nullable(),ahead:W.number().int().nonnegative(),behind:W.number().int().nonnegative(),entries:W.array(W.object({path:W.string(),indexStatus:W.string(),workingTreeStatus:W.string(),originalPath:W.string().nullable()})),totalEntries:W.number().int().nonnegative(),truncated:W.boolean(),error:lG.nullable()}),QS=W.object({ok:W.boolean(),cwd:W.string(),path:W.string().nullable(),staged:W.boolean(),statOnly:W.boolean(),diff:W.string(),truncated:W.boolean(),error:lG.nullable()}),WS=W.object({ok:W.boolean(),cwd:W.string(),path:W.string().nullable(),commits:W.array(W.object({hash:W.string(),shortHash:W.string(),authorName:W.string(),authorEmail:W.string(),date:W.string(),subject:W.string()})),totalCommits:W.number().int().nonnegative(),truncated:W.boolean(),error:lG.nullable()}),HS=W.object({ok:W.boolean(),cwd:W.string(),revision:W.string(),path:W.string().nullable(),content:W.string(),truncated:W.boolean(),error:lG.nullable()});var zS="List files and directories within the working directory. Use this before reading or editing unfamiliar locations.",DS=W.object({path:R0.optional().default("."),recursive:W.boolean().optional().default(!1),includeHidden:W.boolean().optional().default(!1),maxEntries:j0(1,$5,"maxEntries").optional().default(100)}),qS=W.object({path:R0,recursive:W.boolean().optional(),includeHidden:W.boolean().optional()}),BS=W.object({path:W.string(),entries:W.array(W.object({path:W.string(),type:W.enum(["file","directory","symlink","other"]),size:W.number().int().nonnegative().nullable()})),totalEntries:W.number().int().nonnegative(),truncated:W.boolean()});var Un=W.object({transport:W.literal("stdio").default("stdio"),command:W.string().min(1).max(4096),args:W.array(W.string().max(4096)).optional().default([]),cwd:W.string().min(1).max(4096).optional(),env:W.record(W.string(),W.string()).optional().default({}),enabled:W.boolean().optional().default(!0)}),fJ$=W.object({servers:W.record(W.string().min(1).max(120),Un).optional().default({})}),Jn=W.enum(["stopped","running","degraded"]),LS=W.object({name:W.string().min(1),transport:W.literal("stdio"),enabled:W.boolean(),state:Jn,command:W.string().min(1),pid:W.number().int().positive().nullable(),error:W.string().nullable()}),_S=W.object({server:W.string().min(1),uri:W.string().min(1),name:W.string().nullable(),description:W.string().nullable(),mimeType:W.string().nullable()});var KS="List resources exposed by configured MCP servers. Servers must be configured and permission-gated.",VS="Read a resource from a configured MCP server by server name and resource URI.",OS="Call a configured MCP server tool. This is gated as danger-full-access unless explicitly allowed.",NS=W.object({server:W.string().min(1).max(120).optional()}),AS=W.object({server:W.string().min(1).max(120).optional()}),FS=W.object({servers:W.array(LS),resources:W.array(_S)}),VV=W.object({server:W.string().min(1).max(120),uri:W.string().min(1).max(4096)}),bS=VV,MS=W.object({server:W.string(),uri:W.string(),content:W.string(),mimeType:W.string().nullable()}),ZS=W.object({server:W.string().min(1).max(120),toolName:W.string().min(1).max(240),arguments:W.record(W.string(),W.unknown()).optional().default({})}),jS=W.object({server:W.string().min(1).max(120),toolName:W.string().min(1).max(240)}),IS=W.object({server:W.string(),toolName:W.string(),result:W.unknown()});var RS="Read file content from the working directory. Prefer a startLine/endLine range over whole files — large files are truncated head+tail.",TS=W.object({path:R0,startLine:uX.optional(),endLine:uX.optional(),maxChars:j0(1,O6,"maxChars").optional()}).superRefine(($,U)=>{if($.startLine!==void 0&&$.endLine!==void 0&&$.endLine<$.startLine)U.addIssue({code:W.ZodIssueCode.custom,message:"endLine must be greater than or equal to startLine.",path:["endLine"]})}),SS=W.object({path:R0,startLine:uX.optional(),endLine:uX.optional()}),ES=W.object({path:W.string(),startLine:W.number().int().min(1),endLine:W.number().int().min(1),content:W.string(),totalLines:W.number().int().nonnegative(),truncated:W.boolean()});var Xn=W.object({label:W.string().min(1).max(120),description:W.string().min(1).max(240).optional()}),PS="Ask the user a focused question while planning. Use this to collect missing requirements or confirm tradeoffs before finalizing a plan.",pG=W.object({question:W.string().min(1).max(2000),header:W.string().min(1).max(80).optional(),options:W.array(Xn).min(1).max(8).optional(),allowCustomResponse:W.boolean().optional().default(!0),placeholder:W.string().min(1).max(200).optional()}),gS=W.object({question:W.string().min(1).max(2000)}),HJ=W.object({answer:W.string().min(1).max(4000),selectedOption:W.string().min(1).max(120).optional(),source:W.enum(["option","custom"])});var CS="Load an installed skill by name before following its instructions. Use resource to read a supporting file relative to that skill's directory.",OV=W.object({name:W.string().min(1).max(160),resource:W.string().min(1).max(1024).optional()}),vS=OV,xS=W.object({name:W.string().min(1),description:W.string().nullable(),path:W.string().min(1),source:W.enum(["project","user"])}),kS=W.object({skill:xS,content:W.string()}),tJ$=W.object({skills:W.array(xS)});var yS="Persist the current session task list. Use this to track multi-step coding work and update task status as progress changes.",hS=W.enum(["pending","in_progress","completed","canceled"]),Yn=W.enum(["low","medium","high"]),fS=W.object({id:W.string().min(1).max(120).optional(),content:W.string().min(1).max(QV),status:hS,priority:Yn.optional().default("medium"),notes:W.string().max(1000).optional(),activeForm:W.string().min(1).max(WV).optional()}),wn=W.object({content:W.string().min(1).max(QV),status:hS,activeForm:W.string().min(1).max(WV).optional().describe('Present-tense label shown while in_progress, e.g. "Adding tests".')}),uS=W.object({todos:W.array(fS).max(50)}),mS=W.object({todos:W.array(wn).max(20)}),iS=W.object({sessionId:W.string(),path:W.string(),todos:W.array(fS),summary:W.object({total:W.number().int().nonnegative(),pending:W.number().int().nonnegative(),inProgress:W.number().int().nonnegative(),completed:W.number().int().nonnegative(),canceled:W.number().int().nonnegative()}),warnings:W.array(W.string()).optional()});var lS="Search available coding-agent tools by name, capability, or permission requirement.",pS=W.object({query:W.string().min(1).max(200),maxResults:j0(1,kX,"maxResults").optional().default(10)}),cS=W.object({query:W.string().min(1).max(200)}),dS=W.object({query:W.string(),results:W.array(W.object({name:p4,description:W.string(),permissionMode:d1,activeModes:W.array(c4),score:W.number()})),totalResults:W.number().int().nonnegative(),truncated:W.boolean()});var rS="Fetch a URL and return normalized, bounded text with source metadata. Keep maxChars modest and request more only if the answer wasn't in the returned text. Requires network permission.",nS=W.object({url:W.string().url().max(4096),maxChars:j0(200,O6,"maxChars").optional().default(aU),timeoutMs:j0(1000,30000,"timeoutMs").optional().default(1e4)}),oS=W.object({url:W.string().url().max(4096)}),Gn=W.object({code:W.string(),message:W.string()}),aS=W.object({ok:W.boolean(),url:W.string(),finalUrl:W.string().nullable(),status:W.number().int().nullable(),statusText:W.string().nullable(),contentType:W.string().nullable(),title:W.string().nullable(),text:W.string(),truncated:W.boolean(),fetchedAt:W.string(),error:Gn.nullable()});var tS="Search the live web through the configured provider-native or local search backend and return citable sources.",Qn=W.enum(["auto","brave","tavily"]),sS=W.object({query:W.string().min(1).max(500),provider:Qn.optional().default("auto"),maxResults:j0(1,25,"maxResults").optional().default(3)}),eS=W.object({query:W.string().min(1).max(500)}),Wn=W.object({code:W.string(),message:W.string()}),$E=W.object({ok:W.boolean(),query:W.string(),provider:W.string(),results:W.array(W.object({title:W.string(),url:W.string(),snippet:W.string(),source:W.string().nullable()})),totalResults:W.number().int().nonnegative(),error:Wn.nullable()});var UE="Write complete file content to a path in the working directory. Use for creating or overwriting files.",JE=W.object({path:R0,content:W.string(),overwrite:W.boolean().optional().default(!0)}),XE=W.object({path:R0,content:W.string()}),YE=W.object({path:W.string(),created:W.boolean(),bytesWritten:W.number().int().nonnegative(),diff:W.string().optional()});var zJ=["build"],Hn=["plan"],r1=["build","plan"],cG={agent:{description:ET,inputSchema:PT,providerInputSchema:gT,outputSchema:CT,modes:r1,permissionSubject:"agent",permissionMode:"read-only",execution:"server",availability:"model",activation:"core",outputPolicy:"artifact-if-large"},list_files:{description:zS,inputSchema:DS,providerInputSchema:qS,outputSchema:BS,modes:r1,permissionSubject:"list_files",permissionMode:"read-only",execution:"server",availability:"always",activation:"core",outputPolicy:"artifact-if-large"},glob_search:{description:cT,inputSchema:dT,providerInputSchema:rT,outputSchema:nT,modes:r1,permissionSubject:"glob_search",permissionMode:"read-only",execution:"server",availability:"always",activation:"core",outputPolicy:"artifact-if-large"},read_file:{description:RS,inputSchema:TS,providerInputSchema:SS,outputSchema:ES,modes:r1,permissionSubject:"read_file",permissionMode:"read-only",execution:"server",availability:"always",activation:"core",outputPolicy:"artifact-if-large"},grep:{description:mT,inputSchema:iT,providerInputSchema:lT,outputSchema:pT,modes:r1,permissionSubject:"grep",permissionMode:"read-only",execution:"server",availability:"always",activation:"core",outputPolicy:"artifact-if-large"},git_status:{description:oT,inputSchema:eT,providerInputSchema:$S,outputSchema:GS,modes:r1,permissionSubject:"git_status",permissionMode:"read-only",execution:"server",availability:"git-workspace",activation:"specialized",outputPolicy:"artifact-if-large"},git_diff:{description:aT,inputSchema:US,providerInputSchema:JS,outputSchema:QS,modes:r1,permissionSubject:"git_diff",permissionMode:"read-only",execution:"server",availability:"git-workspace",activation:"specialized",outputPolicy:"artifact-if-large"},git_log:{description:tT,inputSchema:KV,providerInputSchema:XS,outputSchema:WS,modes:r1,permissionSubject:"git_log",permissionMode:"read-only",execution:"server",availability:"git-workspace",activation:"specialized",outputPolicy:"artifact-if-large"},git_show:{description:sT,inputSchema:YS,providerInputSchema:wS,outputSchema:HS,modes:r1,permissionSubject:"git_show",permissionMode:"read-only",execution:"server",availability:"git-workspace",activation:"specialized",outputPolicy:"artifact-if-large"},tool_search:{description:lS,inputSchema:pS,providerInputSchema:cS,outputSchema:dS,modes:r1,permissionSubject:"tool_search",permissionMode:"read-only",execution:"server",availability:"always",activation:"core",outputPolicy:"inline"},skill:{description:CS,inputSchema:OV,providerInputSchema:vS,outputSchema:kS,modes:r1,permissionSubject:"skill",permissionMode:"read-only",execution:"server",availability:"skills",activation:"core",outputPolicy:"artifact-if-large"},list_mcp_resources:{description:KS,inputSchema:NS,providerInputSchema:AS,outputSchema:FS,modes:r1,permissionSubject:"list_mcp_resources",permissionMode:"read-only",execution:"server",availability:"mcp",activation:"specialized",outputPolicy:"artifact-if-large"},read_mcp_resource:{description:VS,inputSchema:VV,providerInputSchema:bS,outputSchema:MS,modes:r1,permissionSubject:"read_mcp_resource",permissionMode:"read-only",execution:"server",availability:"mcp",activation:"specialized",outputPolicy:"artifact-if-large"},call_mcp_tool:{description:OS,inputSchema:ZS,providerInputSchema:jS,outputSchema:IS,modes:zJ,permissionSubject:"call_mcp_tool",permissionMode:"danger-full-access",execution:"server",availability:"mcp",activation:"specialized",outputPolicy:"artifact-if-large"},request_user_input:{description:PS,inputSchema:pG,providerInputSchema:gS,outputSchema:HJ,modes:Hn,permissionSubject:"request_user_input",permissionMode:"read-only",execution:"client",availability:"always",activation:"core",outputPolicy:"inline"},todo_write:{description:yS,inputSchema:uS,providerInputSchema:mS,outputSchema:iS,modes:zJ,permissionSubject:"todo_write",permissionMode:"workspace-write",execution:"server",availability:"always",activation:"core",outputPolicy:"inline"},write_file:{description:UE,inputSchema:JE,providerInputSchema:XE,outputSchema:YE,modes:zJ,permissionSubject:"write_file",permissionMode:"workspace-write",execution:"server",availability:"always",activation:"core",outputPolicy:"inline"},edit_file:{description:hT,inputSchema:_V,providerInputSchema:fT,outputSchema:uT,modes:zJ,permissionSubject:"edit_file",permissionMode:"workspace-write",execution:"server",availability:"always",activation:"core",outputPolicy:"inline"},bash:{description:vT,inputSchema:xT,providerInputSchema:kT,outputSchema:yT,modes:zJ,permissionSubject:"bash",permissionMode:"danger-full-access",execution:"server",availability:"always",activation:"core",outputPolicy:"artifact-if-large"},web_fetch:{description:rS,inputSchema:nS,providerInputSchema:oS,outputSchema:aS,modes:zJ,permissionSubject:"web_fetch",permissionMode:"danger-full-access",execution:"server",availability:"web",activation:"specialized",outputPolicy:"artifact-if-large"},web_search:{description:tS,inputSchema:sS,providerInputSchema:eS,outputSchema:$E,modes:r1,permissionSubject:"web_search",permissionMode:"danger-full-access",execution:"server-or-provider",availability:"web",activation:"specialized",outputPolicy:"artifact-if-large"}};function mX($){return Object.fromEntries(Object.entries(cG).map(([U,J])=>[U,J[$]]))}var zn=mX("description"),iX=mX("inputSchema"),Dn=mX("providerInputSchema"),qn=mX("outputSchema"),dG=mX("permissionMode");var d7$=W.object({messages:W.array(W.json()),cwd:W.string().min(1).max(4096),mode:c4.optional(),permissionMode:d1.optional(),providerWebSearchDecision:hX.optional(),allowedTools:W.array(p4).optional(),permissionRules:yX.optional(),sandbox:WJ.optional()}),Bn=new Set(Object.keys(cG).filter(($)=>cG[$].execution!=="client"));function wE($){return Bn.has($)}var r7$=W.object({cwd:W.string().min(1).max(4096),sessionId:W.string().min(1).max(200).optional(),mode:c4.optional(),permissionMode:d1.optional(),providerWebSearchDecision:hX.optional(),allowedTools:W.array(p4).optional(),permissionRules:yX.optional(),sandbox:WJ.optional(),environmentContext:W.string().optional(),maxOutputTokens:W.number().int().min(1).optional(),contextWindow:W.number().int().positive().optional(),preserveRecentTokens:W.number().int().nonnegative().optional(),originalInputTokens:W.number().int().nonnegative().optional(),assemblyAbortSignal:W.custom().optional(),turnKey:W.string().min(1).max(200).optional()});function Ln($){return $==="plan"?"read-only":"workspace-write"}function _n({mode:$,permissionMode:U}){if($==="plan")return"read-only";return U??Ln($)}function Kn({mode:$,permissionMode:U,allowedTools:J,permissionRules:Y,approved:X,toolRequirements:w=dG}){return new DV({activeMode:_n({mode:$,permissionMode:U}),toolRequirements:w,allowedTools:J,rules:Y,approved:X})}function Vn($,U){if(!$||typeof $!=="object")return null;let J=Reflect.get($,U);return typeof J==="string"&&J.trim().length>0?J.trim():null}function On($,U){if($!=="bash")return{permissionMode:dG[$]};let J=Vn(U,"command")??"",Y=jT(J);return{permissionMode:Y.permissionMode,reason:Y.reason}}function NV({toolName:$,input:U,mode:J,permissionMode:Y,allowedTools:X,permissionRules:w,approved:G}){let Q=On($,U),H={...dG,[$]:Q.permissionMode},z=Kn({mode:J,permissionMode:Y,allowedTools:X,permissionRules:w,approved:G,toolRequirements:H}).decide($,U);if($==="bash"&&Q.reason)return{...z,reason:z.reason&&z.reason!==Q.reason?`${z.reason} ${Q.reason}`:Q.reason};return z}var Nn=new Set(["auth","billing","rate_limit","invalid_request","context_overflow","provider_unavailable","network","aborted","unknown"]);function rG($){if(!$||!$.startsWith("LIGHTCODE_ERROR:"))return null;try{let U=JSON.parse($.slice(16));if(typeof U!=="object"||U===null||typeof U.message!=="string"||typeof U.retryable!=="boolean"||typeof U.kind!=="string"||!Nn.has(U.kind))return null;return{kind:U.kind,statusCode:typeof U.statusCode==="number"?U.statusCode:void 0,retryable:U.retryable,message:U.message,contextLimitTokens:typeof U.contextLimitTokens==="number"?U.contextLimitTokens:void 0}}catch{return null}}var An={auth:"Authentication error",billing:"Billing or quota error",rate_limit:"Rate limited",invalid_request:"Provider rejected the request",context_overflow:"Context window exceeded",provider_unavailable:"Provider unavailable",network:"Connection error",aborted:"Request aborted",unknown:"Provider error"};function GE($){let U=$.statusCode?` (HTTP ${$.statusCode})`:"";return`${An[$.kind]}${U}: ${$.message}`}var Fn=["tool_approval","user_prompt"],QE=W.enum(Fn),bn=["pending","approved","denied","answered","superseded"],AV=W.enum(bn),nG=W.string().min(1).max(240),WE=W.object({toolName:p4,input:W.json(),summary:W.string().min(1).max(4000),permissionDecision:ZT,cwd:W.string().min(1).max(4096)}),oG=pG,UX$=W.union([WE,oG]),Mn=W.object({id:W.string().min(1),sessionId:N6,toolCallId:nG,kind:QE,status:AV,payload:W.json(),response:W.json().nullable(),resolvedAt:W.string().min(1).nullable(),createdAt:W.string().min(1),updatedAt:W.string().min(1)}),FV=W.discriminatedUnion("kind",[W.object({kind:W.literal("tool_approval"),toolCallId:nG,payload:WE}),W.object({kind:W.literal("user_prompt"),toolCallId:nG,payload:oG})]),JX$=AV.exclude(["pending"]),XX$=W.union([W.object({status:W.literal("answered"),response:HJ}),W.object({status:W.enum(["approved","denied","superseded"]),response:W.json().optional()})]),YX$=W.object({status:AV.optional(),kind:QE.optional()}),wX$=W.object({id:fX}),GX$=W.object({id:fX,toolCallId:nG}),QX$=W.object({interactions:W.array(Mn)}),WX$=W.object({total:W.number().int().nonnegative(),toolApprovals:W.number().int().nonnegative(),userPrompts:W.number().int().nonnegative(),stale:W.number().int().nonnegative(),recoverable:W.number().int().nonnegative()});function bV($,U=140){let J;if(typeof $==="string")J=$;else try{J=JSON.stringify($)}catch{J=String($)}let Y=J.replace(/\s+/g," ").trim();if(Y.length<=U)return Y;return`${Y.slice(0,U-3)}...`}var J5=Symbol("no-change");function Zn($,U){if($===void 0||$===null)return J5;switch(U){case"number":{if(typeof $==="string"){let J=$.trim();if(J!==""&&Number.isFinite(Number(J)))return Number(J)}return J5}case"boolean":{if(typeof $==="string"){let J=$.trim().toLowerCase();if(J==="true"||J==="1"||J==="yes")return!0;if(J==="false"||J==="0"||J==="no")return!1}if($===1)return!0;if($===0)return!1;return J5}case"string":{if(typeof $==="number"||typeof $==="boolean")return String($);return J5}case"object":case"array":{if(typeof $==="string")try{let J=JSON.parse($),Y=Array.isArray(J);if(U==="array"?Y:J!==null&&typeof J==="object"&&!Y)return J}catch{}return J5}default:return J5}}function jn($,U,J){if(U.length===0||$===null||typeof $!=="object")return!1;let Y=$;for(let G=0;G<U.length-1;G+=1){let Q=Y[U[G]];if(Q===null||typeof Q!=="object")return!1;Y=Q}let X=U[U.length-1],w=Zn(Y[X],J);if(w===J5)return!1;return Y[X]=w,!0}function HE($,U){if($===null||typeof $!=="object")return null;let J;try{J=structuredClone($)}catch{J=$}for(let X=0;X<4;X+=1){let w=U.safeParse(J);if(w.success)return w.data;let G=!1;for(let Q of w.error.issues){if(Q.code!=="invalid_type")continue;let H=Q.expected;if(typeof H!=="string")continue;if(jn(J,Q.path,H))G=!0}if(!G)break}let Y=U.safeParse(J);return Y.success?Y.data:null}function MV($,U){let J=iX[$],Y=J.safeParse(U);if(Y.success)return Y.data;let X=HE(U,J);if(X!==null)return X;return J.parse(U)}var In=W.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]),Rn=W.object({usage:W.object({inputTokens:W.number().nonnegative().optional(),outputTokens:W.number().nonnegative().optional(),totalTokens:W.number().nonnegative().optional(),cachedInputTokens:W.number().nonnegative().optional()}),modelId:W.string().optional(),finishReason:In.optional(),context:W.object({inputTokens:W.number().nonnegative(),contextWindow:W.number().positive(),compactedMessages:W.number().nonnegative().optional(),systemTokens:W.number().nonnegative().optional(),toolTokens:W.number().nonnegative().optional(),messageTokens:W.number().nonnegative().optional(),mediaTokens:W.number().nonnegative().optional(),remainingTokens:W.number().nonnegative().optional(),compactedTokens:W.number().nonnegative().optional()}).optional()}).loose();function zE($){if($.role!=="assistant"||$.metadata===void 0)return null;let U=Rn.safeParse($.metadata);return U.success?U.data:null}var aG={enabled:!0,maxAutoContinues:50},Tn="Your previous response was cut off by the output token limit. Continue exactly where you left off. Do not repeat completed work.",Sn="You stopped before completing the task. Review your todo list and continue working until every item is complete. Call tools through the function-calling interface, never as XML or plain text.",En=/(?::|\b(?:let me|i'll now|i will now|next,? i(?:'ll| will)|now i(?:'ll| will)|going to|proceeding to|let's)\s*[\w,' ]*)$/i,Pn=3,gn=200;function DE($){return $.parts.map((U)=>U.type==="text"?U.text:"").join("")}function Cn($){for(let U=$.length-1;U>=0;U--)if($[U].role==="assistant")return $[U];return null}function vn($){return $.some((U)=>U.status==="pending"||U.status==="in_progress")}function xn($){let U=$.trim();if(!U)return!1;return En.test(U)}function kn($){let U=DE($).trim().slice(0,gn),J=$.parts.filter((Y)=>Y.type.startsWith("tool-")).map((Y)=>{let X=Y;return`${X.type}:${JSON.stringify(X.input??null)}`}).join("|");return`${U}::${J}`}function yn($,U=Pn){let J=[];for(let w=$.length-1;w>=0&&J.length<U;w--)if($[w].role==="assistant")J.push(kn($[w]));if(J.length<U)return!1;let[Y,...X]=J;if(!Y.trim()||Y==="::")return!1;return X.every((w)=>w===Y)}function qE({lastActivityAt:$,now:U,stallTimeoutMs:J}){return J>0&&U-$>=J}function BE({messages:$,todos:U,autoContinuesThisTurn:J,limits:Y=aG}){if(!Y.enabled)return{kind:"none"};let X=Cn($);if(!X)return{kind:"none"};let w=zE(X),G=w?.finishReason,Q=w?.toolIntent,H=G==="length"?"continue-length":G==="stop"&&(Q==="unparsed"||vn(U)||xn(DE(X)))?"nudge-stop":null;if(!H)return{kind:"none"};if(J>=Y.maxAutoContinues)return{kind:"none",guardTripped:"max-continues"};if(yn($))return{kind:"none",guardTripped:"doom-loop"};return H==="continue-length"?{kind:"continue-length",prompt:Tn}:{kind:"nudge-stop",prompt:Sn}}async function ZV($){if(typeof $==="function")return Promise.resolve($());return Promise.resolve($)}var hn="Connection interrupted. Please retry or regenerate your last message.",LE="Proceed with implementation in Build mode. Continue without additional plan questions.",fn=50,un=/^\/?(retry|regenerate)$/i,mn="provider_web_search_approval_required",tU="lightcode-provider-web-search-approval",ln=/^: lightcode-cursor=(\d+)\r?$/;function _E($,U){let J=`${$.carry}${U}`.split(`
|
|
99
|
+
`)}})}};var xX=W.record(W.string(),e8.optional()),Jr=dU(()=>e6(W.union([W.strictObject({type:W.literal("text-start"),id:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("text-delta"),id:W.string(),delta:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("text-end"),id:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("error"),errorText:W.string()}),W.strictObject({type:W.literal("tool-input-start"),toolCallId:W.string(),toolName:W.string(),providerExecuted:W.boolean().optional(),providerMetadata:D$.optional(),toolMetadata:xX.optional(),dynamic:W.boolean().optional(),title:W.string().optional()}),W.strictObject({type:W.literal("tool-input-delta"),toolCallId:W.string(),inputTextDelta:W.string()}),W.strictObject({type:W.literal("tool-input-available"),toolCallId:W.string(),toolName:W.string(),input:W.unknown(),providerExecuted:W.boolean().optional(),providerMetadata:D$.optional(),toolMetadata:xX.optional(),dynamic:W.boolean().optional(),title:W.string().optional()}),W.strictObject({type:W.literal("tool-input-error"),toolCallId:W.string(),toolName:W.string(),input:W.unknown(),providerExecuted:W.boolean().optional(),providerMetadata:D$.optional(),toolMetadata:xX.optional(),dynamic:W.boolean().optional(),errorText:W.string(),title:W.string().optional()}),W.strictObject({type:W.literal("tool-approval-request"),approvalId:W.string(),toolCallId:W.string()}),W.strictObject({type:W.literal("tool-output-available"),toolCallId:W.string(),output:W.unknown(),providerExecuted:W.boolean().optional(),providerMetadata:D$.optional(),toolMetadata:xX.optional(),dynamic:W.boolean().optional(),preliminary:W.boolean().optional()}),W.strictObject({type:W.literal("tool-output-error"),toolCallId:W.string(),errorText:W.string(),providerExecuted:W.boolean().optional(),providerMetadata:D$.optional(),toolMetadata:xX.optional(),dynamic:W.boolean().optional()}),W.strictObject({type:W.literal("tool-output-denied"),toolCallId:W.string()}),W.strictObject({type:W.literal("reasoning-start"),id:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("reasoning-delta"),id:W.string(),delta:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("reasoning-end"),id:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("source-url"),sourceId:W.string(),url:W.string(),title:W.string().optional(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("source-document"),sourceId:W.string(),mediaType:W.string(),title:W.string(),filename:W.string().optional(),providerMetadata:D$.optional()}),W.strictObject({type:W.literal("file"),url:W.string(),mediaType:W.string(),providerMetadata:D$.optional()}),W.strictObject({type:W.custom(($)=>typeof $==="string"&&$.startsWith("data-"),{message:'Type must start with "data-"'}),id:W.string().optional(),data:W.unknown(),transient:W.boolean().optional()}),W.strictObject({type:W.literal("start-step")}),W.strictObject({type:W.literal("finish-step")}),W.strictObject({type:W.literal("start"),messageId:W.string().optional(),messageMetadata:W.unknown().optional()}),W.strictObject({type:W.literal("finish"),finishReason:W.enum(["stop","length","content-filter","tool-calls","error","other"]).optional(),messageMetadata:W.unknown().optional()}),W.strictObject({type:W.literal("abort"),reason:W.string().optional()}),W.strictObject({type:W.literal("message-metadata"),messageMetadata:W.unknown()})])));function Xr($){return $.type.startsWith("tool-")}function VT($){return $.type==="dynamic-tool"}function l4($){return Xr($)||VT($)}function Yr($){return $.type.split("-").slice(1).join("-")}function QJ($){return VT($)?$.toolName:Yr($)}var a5$=_1({prefix:"aitxt",size:24});var c1=W.record(W.string(),e8.optional()),wr=dU(()=>e6(W.array(W.object({id:W.string(),role:W.enum(["system","user","assistant"]),metadata:W.unknown().optional(),parts:W.array(W.union([W.object({type:W.literal("text"),text:W.string(),state:W.enum(["streaming","done"]).optional(),providerMetadata:D$.optional()}),W.object({type:W.literal("reasoning"),text:W.string(),state:W.enum(["streaming","done"]).optional(),providerMetadata:D$.optional()}),W.object({type:W.literal("source-url"),sourceId:W.string(),url:W.string(),title:W.string().optional(),providerMetadata:D$.optional()}),W.object({type:W.literal("source-document"),sourceId:W.string(),mediaType:W.string(),title:W.string(),filename:W.string().optional(),providerMetadata:D$.optional()}),W.object({type:W.literal("file"),mediaType:W.string(),filename:W.string().optional(),url:W.string(),providerMetadata:D$.optional()}),W.object({type:W.literal("step-start")}),W.object({type:W.string().startsWith("data-"),id:W.string().optional(),data:W.unknown()}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("input-streaming"),input:W.unknown().optional(),providerExecuted:W.boolean().optional(),callProviderMetadata:D$.optional(),output:W.never().optional(),errorText:W.never().optional(),approval:W.never().optional()}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("input-available"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.never().optional()}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("approval-requested"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.never().optional(),reason:W.never().optional()})}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("approval-responded"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.boolean(),reason:W.string().optional()})}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("output-available"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.unknown(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),resultProviderMetadata:D$.optional(),preliminary:W.boolean().optional(),approval:W.object({id:W.string(),approved:W.literal(!0),reason:W.string().optional()}).optional()}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("output-error"),input:W.unknown().optional(),rawInput:W.unknown().optional(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.string(),callProviderMetadata:D$.optional(),resultProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.literal(!0),reason:W.string().optional()}).optional()}),W.object({type:W.literal("dynamic-tool"),toolName:W.string(),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("output-denied"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.literal(!1),reason:W.string().optional()})}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("input-streaming"),providerExecuted:W.boolean().optional(),callProviderMetadata:D$.optional(),input:W.unknown().optional(),output:W.never().optional(),errorText:W.never().optional(),approval:W.never().optional()}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("input-available"),providerExecuted:W.boolean().optional(),input:W.unknown(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.never().optional()}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("approval-requested"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.never().optional(),reason:W.never().optional()})}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("approval-responded"),input:W.unknown(),providerExecuted:W.boolean().optional(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.boolean(),reason:W.string().optional()})}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("output-available"),providerExecuted:W.boolean().optional(),input:W.unknown(),output:W.unknown(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),resultProviderMetadata:D$.optional(),preliminary:W.boolean().optional(),approval:W.object({id:W.string(),approved:W.literal(!0),reason:W.string().optional()}).optional()}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("output-error"),providerExecuted:W.boolean().optional(),input:W.unknown().optional(),rawInput:W.unknown().optional(),output:W.never().optional(),errorText:W.string(),callProviderMetadata:D$.optional(),resultProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.literal(!0),reason:W.string().optional()}).optional()}),W.object({type:W.string().startsWith("tool-"),toolCallId:W.string(),toolMetadata:c1.optional(),state:W.literal("output-denied"),providerExecuted:W.boolean().optional(),input:W.unknown(),output:W.never().optional(),errorText:W.never().optional(),callProviderMetadata:D$.optional(),approval:W.object({id:W.string(),approved:W.literal(!1),reason:W.string().optional()})})])).nonempty("Message must contain at least one part")})).nonempty("Messages array must not be empty")));async function OT({messages:$,metadataSchema:U,dataSchemas:J,tools:Y}){try{if($==null)return{success:!1,error:new Fc({parameter:"messages",value:$,message:"messages parameter must be provided"})};let X=await _6({value:$,schema:wr});if(U)for(let[w,G]of X.entries())await _6({value:G.metadata,schema:U,context:{field:`messages[${w}].metadata`,entityId:G.id}});if(J||Y)for(let[w,G]of X.entries())for(let[Q,H]of G.parts.entries()){if(J&&H.type.startsWith("data-")){let z=H,D=z.type.slice(5),q=J[D];if(!q)return{success:!1,error:new $U({value:z.data,cause:`No data schema found for data part ${D}`,context:{field:`messages[${w}].parts[${Q}].data`,entityName:D,entityId:z.id}})};await _6({value:z.data,schema:q,context:{field:`messages[${w}].parts[${Q}].data`,entityName:D,entityId:z.id}})}if(Y&&H.type.startsWith("tool-")){let z=H,D=z.type.slice(5),q=Y[D];if(!q&&(z.state==="output-available"||z.state==="output-error"||z.state==="output-denied"))continue;if(!q)return{success:!1,error:new $U({value:z.input,cause:`No tool schema found for tool part ${D}`,context:{field:`messages[${w}].parts[${Q}].input`,entityName:D,entityId:z.toolCallId}})};if(z.state==="input-available"||z.state==="output-available"||z.state==="output-error"&&z.input!==void 0)await _6({value:z.input,schema:q.inputSchema,context:{field:`messages[${w}].parts[${Q}].input`,entityName:D,entityId:z.toolCallId}});if(z.state==="output-available"&&q.outputSchema)await _6({value:z.output,schema:q.outputSchema,context:{field:`messages[${w}].parts[${Q}].output`,entityName:D,entityId:z.toolCallId}})}}return{success:!0,data:X}}catch(X){return{success:!1,error:X}}}var U9$=_1({prefix:"aiobj",size:24});function NT($){return({url:U,abortSignal:J})=>hd({url:U,maxBytes:$==null?void 0:$.maxBytes,abortSignal:J})}var X9$=_1({prefix:"aiobj",size:24});var Y9$=NT();var Gr="AI_NoSuchProviderError",Qr=`vercel.ai.error.${Gr}`,Wr=Symbol.for(Qr),Hr;Hr=Wr;var w9$=NT();var zr=class{constructor({api:$="/api/chat",credentials:U,headers:J,body:Y,fetch:X,prepareSendMessagesRequest:w,prepareReconnectToStreamRequest:G}){this.api=$,this.credentials=U,this.headers=J,this.body=Y,this.fetch=X,this.prepareSendMessagesRequest=w,this.prepareReconnectToStreamRequest=G}async sendMessages({abortSignal:$,...U}){var J,Y,X,w,G;let Q=await p0(this.body),H=await p0(this.headers),z=await p0(this.credentials),D={...P1(H),...P1(U.headers)},q=await((J=this.prepareSendMessagesRequest)==null?void 0:J.call(this,{api:this.api,id:U.chatId,messages:U.messages,body:{...Q,...U.body},headers:D,credentials:z,requestMetadata:U.metadata,trigger:U.trigger,messageId:U.messageId})),L=(Y=q==null?void 0:q.api)!=null?Y:this.api,B=(q==null?void 0:q.headers)!==void 0?P1(q.headers):D,O=(q==null?void 0:q.body)!==void 0?q.body:{...Q,...U.body,id:U.chatId,messages:U.messages,trigger:U.trigger,messageId:U.messageId},A=(X=q==null?void 0:q.credentials)!=null?X:z,V=await((w=this.fetch)!=null?w:globalThis.fetch)(L,{method:"POST",headers:{"Content-Type":"application/json",...B},body:JSON.stringify(O),credentials:A,signal:$});if(!V.ok)throw Error((G=await V.text())!=null?G:"Failed to fetch the chat response.");if(!V.body)throw Error("The response body is empty.");return this.processResponseStream(V.body)}async reconnectToStream($){var U,J,Y,X,w;let G=await p0(this.body),Q=await p0(this.headers),H=await p0(this.credentials),z={...P1(Q),...P1($.headers)},D=await((U=this.prepareReconnectToStreamRequest)==null?void 0:U.call(this,{api:this.api,id:$.chatId,body:{...G,...$.body},headers:z,credentials:H,requestMetadata:$.metadata})),q=(J=D==null?void 0:D.api)!=null?J:`${this.api}/${$.chatId}/stream`,L=(D==null?void 0:D.headers)!==void 0?P1(D.headers):z,B=(Y=D==null?void 0:D.credentials)!=null?Y:H,A=await((X=this.fetch)!=null?X:globalThis.fetch)(q,{method:"GET",headers:L,credentials:B});if(A.status===204)return null;if(!A.ok)throw Error((w=await A.text())!=null?w:"Failed to fetch the chat response.");if(!A.body)throw Error("The response body is empty.");return this.processResponseStream(A.body)}},AT=class extends zr{constructor($={}){super($)}processResponseStream($){return xG({stream:$,schema:Jr}).pipeThrough(new TransformStream({async transform(U,J){if(!U.success)throw U.error;J.enqueue(U.value)}}))}};function FT({messages:$}){let U=$[$.length-1];if(!U)return!1;if(U.role!=="assistant")return!1;let J=U.parts.reduce((X,w,G)=>{return w.type==="step-start"?G:X},-1),Y=U.parts.slice(J+1).filter(l4);return Y.filter((X)=>X.state==="approval-responded").length>0&&Y.every((X)=>X.state==="output-available"||X.state==="output-error"||X.state==="approval-responded")}function bT({messages:$}){let U=$[$.length-1];if(!U)return!1;if(U.role!=="assistant")return!1;let J=U.parts.reduce((X,w,G)=>{return w.type==="step-start"?G:X},-1),Y=U.parts.slice(J+1).filter(l4).filter((X)=>!X.providerExecuted);return Y.length>0&&Y.every((X)=>X.state==="output-available"||X.state==="output-error")}var e=M0(f0(),1);var O6=12000,aU=6000,$5=200,kX=200;var QV=200,WV=80;var Dr=["agent","list_files","glob_search","read_file","grep","git_status","git_diff","git_log","git_show","tool_search","skill","list_mcp_resources","read_mcp_resource","call_mcp_tool","request_user_input","todo_write","write_file","edit_file","bash","web_fetch","web_search"],p4=W.enum(Dr),qr=["build","plan"],c4=W.enum(qr),HV="build";var Br=["read-only","workspace-write","danger-full-access"],d1=W.enum(Br),Lr=W.enum(["allow","ask","deny"]),yX=W.object({allow:W.array(W.string().min(1).max(2000)).optional(),deny:W.array(W.string().min(1).max(2000)).optional(),ask:W.array(W.string().min(1).max(2000)).optional(),deniedTools:W.array(W.string().min(1).max(120)).optional()}),ZT=W.object({outcome:Lr,toolName:W.string().min(1).max(120),activeMode:d1,requiredMode:d1,reason:W.string().min(1).max(2000).optional()}),MT={"read-only":0,"workspace-write":1,"danger-full-access":2};function U5($){return $.trim().replaceAll("-","_").toLowerCase()}function _r($,U){return MT[$]>=MT[U]}function Kr($){return{allow:$?.allow??[],deny:$?.deny??[],ask:$?.ask??[],deniedTools:$?.deniedTools??[]}}function Vr($,U){let J=!1;for(let Y=0;Y<$.length;Y+=1){let X=$[Y];if(X==="\\"){J=!J;continue}if(X===U&&!J)return Y;J=!1}return-1}function Or($,U){for(let J=$.length-1;J>=0;J-=1){if($[J]!==U)continue;let Y=0;for(let X=J-1;X>=0;X-=1){if($[X]!=="\\")break;Y+=1}if(Y%2===0)return J}return-1}function Nr($){return $.replaceAll("\\(","(").replaceAll("\\)",")").replaceAll("\\\\","\\")}function Ar($){let U=Nr($.trim());if(!U||U==="*")return{kind:"any"};if(U.endsWith(":*"))return{kind:"prefix",value:U.slice(0,-2)};return{kind:"exact",value:U}}function Fr($){let U=$.trim(),J=Vr(U,"("),Y=Or(U,")");if(J>0&&Y===U.length-1&&J<Y){let X=U.slice(0,J).trim(),w=U.slice(J+1,Y);if(X)return{raw:U,toolName:U5(X),matcher:Ar(w)}}return{raw:U,toolName:U5(U),matcher:{kind:"any"}}}function br($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Mr($){if(br($))for(let U of["command","path","query","pattern","filePath","file_path","url"]){let J=Reflect.get($,U);if(typeof J==="string"&&J.trim())return J.trim()}if(typeof $==="string"&&$.trim())return $.trim();return""}function Zr($,U,J){if($.toolName!==U5(U))return!1;if($.matcher.kind==="any")return!0;let Y=Mr(J);if($.matcher.kind==="exact")return Y===$.matcher.value;return Y.startsWith($.matcher.value)}function zV($,U,J){return $.map(Fr).find((Y)=>Zr(Y,U,J))}class DV{activeMode;toolRequirements;allowedTools;rules;approved;constructor({activeMode:$,toolRequirements:U,allowedTools:J,rules:Y,approved:X=!1}){this.activeMode=$,this.toolRequirements=U,this.allowedTools=J&&J.length>0?new Set(J.map(U5)):null,this.rules=Kr(Y),this.approved=X}requiredModeFor($){return this.toolRequirements[U5($)]??"danger-full-access"}decide($,U){let J=U5($),Y=this.requiredModeFor($),X={toolName:$,activeMode:this.activeMode,requiredMode:Y};if(this.allowedTools&&!this.allowedTools.has(J))return{...X,outcome:"deny",reason:`Tool "${$}" is not enabled for this session.`};if(this.rules.deniedTools.map(U5).includes(J))return{...X,outcome:"deny",reason:`Tool "${$}" is denied by policy.`};let w=zV(this.rules.deny,$,U);if(w)return{...X,outcome:"deny",reason:`Tool "${$}" is denied by rule "${w.raw}".`};let G=zV(this.rules.ask,$,U);if(G&&!this.approved)return{...X,outcome:"ask",reason:`Tool "${$}" requires approval by rule "${G.raw}".`};if(zV(this.rules.allow,$,U)||_r(this.activeMode,Y))return{...X,outcome:"allow"};if(this.activeMode==="workspace-write"&&Y==="danger-full-access"){if(this.approved)return{...X,outcome:"allow"};return{...X,outcome:"ask",reason:`Tool "${$}" requires approval to escalate from ${this.activeMode} to ${Y}.`}}if(J==="web_search"&&this.activeMode==="read-only"&&Y==="danger-full-access"){if(this.approved)return{...X,outcome:"allow"};return{...X,outcome:"ask",reason:'Tool "web_search" requires approval for network access.'}}return{...X,outcome:"deny",reason:`Tool "${$}" requires ${Y} permission; current mode is ${this.activeMode}.`}}}var jr=W.enum(["disabled","read-only","workspace-write"]),Ir=W.enum(["inherit","disabled"]),WJ=W.object({enabled:W.boolean().optional().default(!1),mode:jr.optional().default("disabled"),network:Ir.optional().default("inherit")}),A9$=WJ.extend({supported:W.boolean(),isolation:W.literal("process-guards"),unsupportedReason:W.string().optional()});var Rr=new Set(["cat","dir","findstr","get-childitem","get-content","grep","ls","pwd","rg","select-string","type"]),Tr=new Set(["bun","bunx","npm","npx","pnpm","yarn"]),Sr=new Set(["curl","ftp","iwr","invoke-restmethod","invoke-webrequest","nc","netcat","scp","sftp","ssh","telnet","wget"]),Er=new Set(["del","erase","rd","rm","rmdir","remove-item"]),Pr=new Set(["kill","pkill","start-process","stop-process","taskkill"]),gr=new Set(["mkdir","new-item","touch"]),Cr=new Set(["diff","log","show","status"]);function c0($,U,J){return{permissionMode:d1.parse($),reason:U,baseCommand:J}}function vr($){return $.trim().replace(/\.(?:cmd|exe|bat|ps1)$/i,"").toLowerCase()}function xr($){let U=[],J="",Y=null;for(let X=0;X<$.length;X+=1){let w=$[X];if((w==='"'||w==="'")&&Y===null){Y=w;continue}if(w===Y){Y=null;continue}if(/\s/.test(w)&&Y===null){if(J)U.push(J),J="";continue}J+=w}if(J)U.push(J);return U}function kr($){let U=null;for(let J=0;J<$.length;J+=1){let Y=$[J],X=$[J+1];if((Y==='"'||Y==="'")&&U===null){U=Y;continue}if(Y===U){U=null;continue}if(U!==null)continue;if(Y===">"||Y==="<"||Y==="|"||Y===";"||Y==="`"||Y==="&")return!0;if(Y==="$"&&X==="(")return!0}return!1}function qV($){return $.some((U)=>{if(!U||U.startsWith("-"))return!1;if(/^[a-z]:[\\/]/i.test(U)||U.startsWith("/")||U.startsWith("~"))return!0;return U.split(/[\\/]+/).includes("..")})}function yr($,U){let J=$[1]?.toLowerCase();if(!J)return c0("read-only","git with no subcommand only prints help.",U);if(!Cr.has(J))return c0("danger-full-access",`git ${J} may mutate repository state or run hooks.`,U);if($.some((Y)=>Y.startsWith("--output")))return c0("danger-full-access","git diff/show output options can write files.",U);if(qV($.slice(2)))return c0("danger-full-access","git read command references a path outside the workspace.",U);return c0("read-only",`git ${J} is treated as read-only.`,U)}function hr($,U){if($[1]==="run"&&$[2]==="typecheck")return c0("read-only","bun run typecheck is treated as read-only.",U);if(["add","install","link","remove","unlink","update","upgrade"].includes($[1]??""))return c0("danger-full-access",`bun ${$[1]} can change dependencies or run lifecycle scripts.`,U);return c0("danger-full-access","bun commands other than the known typecheck script can run arbitrary package scripts.",U)}function fr($,U){if(U==="bun")return hr($,U);return c0("danger-full-access",`${U} can install packages, run scripts, or access the network.`,U)}function jT($){let U=$.trim();if(!U)return c0("danger-full-access","Empty shell commands are not executable.");if(kr(U))return c0("danger-full-access","Shell control operators, redirects, pipes, or substitutions require full approval.");let J=xr(U),Y=vr(J[0]??"");if(!Y)return c0("danger-full-access","Unable to identify the shell command.");if(Sr.has(Y))return c0("danger-full-access",`${Y} can access the network or remote systems.`,Y);if(Er.has(Y))return c0("danger-full-access",`${Y} can delete files or directories.`,Y);if(Pr.has(Y))return c0("danger-full-access",`${Y} can control processes outside the workspace.`,Y);if(Tr.has(Y))return fr(J,Y);if(Y==="git")return yr(J,Y);if(Rr.has(Y)){if(qV(J.slice(1)))return c0("danger-full-access",`${Y} references an absolute, home, or parent path.`,Y);return c0("read-only",`${Y} is treated as a read-only command.`,Y)}if(gr.has(Y)){if(qV(J.slice(1)))return c0("danger-full-access",`${Y} references an absolute, home, or parent path.`,Y);return c0("workspace-write",`${Y} is treated as a workspace-local write command.`,Y)}return c0("danger-full-access",`Unknown shell command "${Y}" requires full approval.`,Y)}var ur=W.enum(["heuristic","llm"]),mG=W.object({sessionId:W.string().min(1),summary:W.string().min(1),anchorMessageId:W.string().min(1),coveredMessageCount:W.number().int().positive(),estimatedTokens:W.number().int().nonnegative(),tier:ur,model:W.string().nullable(),createdAt:W.string().min(1),updatedAt:W.string().min(1)});var IT=W.enum(["auto","provider","brave","tavily","disabled"]),hX=W.enum(["approved","denied"]),R9$=W.object({backend:IT.optional(),maxResults:W.number().int().min(1).max(25).optional(),maxUsesPerTurn:W.number().int().min(1).max(30).optional(),maxCharactersPerResult:W.number().int().min(1).max(1e5).optional(),timeoutMs:W.number().int().min(1000).max(120000).optional()}).strict(),T9$=W.object({backend:IT,maxResults:W.number().int().min(1).max(25),maxUsesPerTurn:W.number().int().min(1).max(30),maxCharactersPerResult:W.number().int().min(1).max(1e5),timeoutMs:W.number().int().min(1000).max(120000)});var mr=W.enum(["openrouter","anthropic","brave","tavily","disabled","unavailable"]),ir=W.enum(["provider","local","none"]),lr=W.object({maxResults:W.number().int().positive(),maxTotalResults:W.number().int().positive(),maxUsesPerTurn:W.number().int().positive(),maxCharactersPerResult:W.number().int().positive(),timeoutMs:W.number().int().positive()}),S9$=W.object({available:W.boolean(),backend:mr,execution:ir,limits:lr,reason:W.string().nullable()});var N6=W.string().uuid(),fX=W.union([N6,W.literal("latest")]),f9$=W.object({id:fX}),u9$=W.object({id:N6}),m9$=W.object({cwd:W.string().min(1).max(4096).optional(),mode:c4.optional(),permissionMode:d1.optional(),title:W.string().min(1).max(120).optional()}),i9$=W.object({id:N6}),l9$=W.object({title:W.string().min(1).max(120).optional(),permissionMode:d1.optional()}),p9$=W.object({id:N6,copiedMessages:W.number().int().nonnegative()}),iG=W.object({id:N6,title:W.string().nullable(),cwd:W.string().nullable(),mode:c4,permissionMode:d1.nullable(),model:W.string().nullable(),revision:W.number().int().nonnegative(),createdAt:W.string().min(1),updatedAt:W.string().min(1)}),pr=iG.extend({messageCount:W.number().int().nonnegative(),latestUserPromptPreview:W.string().nullable()}),c9$=W.object({sessions:W.array(pr)}),d9$=W.object({session:iG.optional(),messages:W.array(W.json()),contextState:mG.nullable().optional()}),cr=W.object({tokens:W.number().nonnegative(),basis:W.enum(["usage_calibrated","heuristic"])}),dr=W.object({systemTokens:W.number().int().nonnegative(),toolTokens:W.number().int().nonnegative(),messageTokens:W.number().int().nonnegative(),mediaTokens:W.number().int().nonnegative(),inputTokens:W.number().int().nonnegative(),inputBudgetTokens:W.number().int().nonnegative(),messageBudgetTokens:W.number().int().nonnegative(),reservedOutputTokens:W.number().int().nonnegative(),contextWindow:W.number().int().positive(),remainingTokens:W.number().int().nonnegative(),compactedTokens:W.number().int().nonnegative()}),r9$=W.object({contextState:mG.nullable(),estimate:cr,contextWindow:W.number().int().positive(),breakdown:dr,withinBudget:W.boolean()}),n9$=W.object({contextState:mG,usedFallback:W.boolean()}),o9$=W.object({session:iG,messages:W.array(W.json())}),a9$=W.object({id:N6,deleted:W.boolean(),deletedMessages:W.number().int().nonnegative()}),t9$=W.object({clientTurnId:W.string().min(1).max(320),expectedRevision:W.number().int().nonnegative(),messageId:W.string().min(1).max(320),role:W.enum(["user","assistant"]),parts:W.array(W.json()).min(1),metadata:W.json().optional(),trigger:W.string().min(1).max(80).optional(),mode:c4.optional(),permissionMode:d1.optional(),providerWebSearchDecision:hX.optional(),allowedTools:W.array(p4).optional(),permissionRules:yX.optional(),sandbox:WJ.optional()}).strict(),RT=W.enum(["pending","running","completed","failed","cancelled"]),s9$=W.object({id:fX,runId:W.string().uuid()}),e9$=W.object({after:W.coerce.number().int().min(-1).default(-1)}),rr=W.object({cursor:W.number().int().nonnegative(),kind:W.string().min(1).max(80),payload:W.json(),createdAt:W.string().min(1)}),$J$=W.object({runId:W.string().uuid(),status:RT,events:W.array(rr),nextCursor:W.number().int().min(-1)}),UJ$=W.object({runId:W.string().uuid(),status:RT,aborted:W.boolean()}),JJ$=W.object({turnKey:W.string().min(1),restoredFiles:W.array(W.string()),messageCount:W.number().int().nonnegative(),revision:W.number().int().nonnegative()}),XJ$=W.object({exportedAt:W.string().min(1),session:iG,messages:W.array(W.json())});var nr="plan",or=["explore"],BV=W.enum(or),TT="explore";var ST=2000;var ar=["pending","running","completed","failed","blocked_on_approval","blocked_on_provider","cancelled"],LV=W.enum(ar),tr=W.json(),sr=W.object({parentSessionId:N6,prompt:W.string().min(1).max(50000),mode:c4.default(nr),model:W.string().min(1).max(200).nullable().optional(),allowedTools:W.array(p4).default([])}),er=sr.extend({id:W.string().uuid(),status:LV,model:W.string().nullable(),output:tr.nullable(),error:W.string().nullable(),startedAt:W.string().min(1).nullable(),finishedAt:W.string().min(1).nullable(),createdAt:W.string().min(1),updatedAt:W.string().min(1)}),WJ$=W.object({tasks:W.array(er)});var ET=`Spawn a read-only subagent that explores the codebase in a fresh context and returns only a final summary (max ~${ST} tokens). Use it for broad searches or multi-file questions where you need conclusions, not raw file contents. It cannot see this conversation or modify files, so make the prompt self-contained: the question, relevant paths/symbols, and what the report must contain.`,PT=W.object({description:W.string().min(1).max(100),prompt:W.string().min(1).max(50000),profile:BV.optional().default(TT),model:W.string().min(1).max(200).optional()}),gT=W.object({description:W.string().min(1).max(100).describe("Short 3-5 word label for the task"),prompt:W.string().min(1).describe("Self-contained task for the subagent"),profile:BV.optional(),model:W.string().optional().describe("Optional model id override; defaults to the session model")}),CT=W.object({taskId:W.string().nullable(),status:LV,summary:W.string(),truncated:W.boolean()});var $n=W.number().finite().refine(($)=>Number.isInteger($),{error:"Expected an integer value."});function j0($,U,J){return $n.refine((Y)=>Y>=$&&Y<=U,{error:`${J} must be between ${$} and ${U}.`})}var R0=W.string().min(1).max(4096),uX=j0(1,1e6,"Line number");var vT="Run a shell command from workspace root with a timeout. Bound noisy output at the source (head/tail/grep/wc) — output is truncated head+tail. Commands may require approval.",xT=W.object({command:W.string().min(1).max(4000),timeoutMs:j0(1000,120000,"timeoutMs").optional().default(30000),maxOutputChars:j0(200,O6,"maxOutputChars").optional().default(aU)}),kT=W.object({command:W.string().min(1).max(4000)}),yT=W.object({command:W.string(),cwd:W.string(),stdout:W.string(),stderr:W.string(),exitCode:W.number().int(),truncated:W.boolean()});var hT="Edit a file via search and replace; copy the search text as shown by read_file (whitespace and line endings are matched tolerantly). It must match exactly one "+"place — add surrounding context to disambiguate, or set replaceAll: true.",_V=W.object({path:R0,search:W.string().min(1),replace:W.string(),replaceAll:W.boolean().optional().default(!1)}),fT=_V,uT=W.object({path:W.string(),replacements:W.number().int().nonnegative(),bytesWritten:W.number().int().nonnegative(),diff:W.string().optional()});var mT="Search project files for text or regex matches and return file path plus line information.",iT=W.object({query:W.string().min(1).max(1000),path:R0.optional().default("."),isRegex:W.boolean().optional().default(!1),caseSensitive:W.boolean().optional().default(!1),maxResults:j0(1,kX,"maxResults").optional().default(50)}),lT=W.object({query:W.string().min(1).max(1000),path:R0,isRegex:W.boolean().optional(),caseSensitive:W.boolean().optional()}),pT=W.object({query:W.string(),path:W.string(),matches:W.array(W.object({path:W.string(),lineNumber:W.number().int().min(1),column:W.number().int().min(1),line:W.string()})),totalMatches:W.number().int().nonnegative(),truncated:W.boolean()});var cT="Find workspace files by glob pattern. Use this when you know a filename shape, extension, or path pattern.",dT=W.object({pattern:W.string().min(1).max(1000),path:R0.optional().default("."),includeHidden:W.boolean().optional().default(!1),includeDirectories:W.boolean().optional().default(!1),maxResults:j0(1,$5,"maxResults").optional().default(100)}),rT=W.object({pattern:W.string().min(1).max(1000),path:R0.optional(),includeHidden:W.boolean().optional()}),nT=W.object({pattern:W.string(),path:W.string(),matches:W.array(W.object({path:W.string(),type:W.enum(["file","directory","symlink","other"]),size:W.number().int().nonnegative().nullable()})),totalMatches:W.number().int().nonnegative(),truncated:W.boolean()});var oT="Return structured git status for the workspace without running an arbitrary shell command.",aT="Return a bounded git diff for workspace changes. Use this to inspect edits before summarizing.",tT="Return recent git commits as structured metadata.",sT="Show a commit or revision with bounded patch output.",eT=W.object({maxEntries:j0(1,$5,"maxEntries").optional().default(100)}),$S=W.object({}),US=W.object({path:R0.optional(),staged:W.boolean().optional().default(!1),statOnly:W.boolean().optional().default(!1),maxChars:j0(200,O6,"maxChars").optional().default(aU)}),JS=W.object({path:R0.optional(),staged:W.boolean().optional(),statOnly:W.boolean().optional()}),KV=W.object({path:R0.optional(),maxCommits:j0(1,50,"maxCommits").optional().default(10)}),XS=KV,YS=W.object({revision:W.string().min(1).max(240),path:R0.optional(),maxChars:j0(200,O6,"maxChars").optional().default(aU)}),wS=W.object({revision:W.string().min(1).max(240),path:R0.optional()}),lG=W.object({code:W.string(),message:W.string(),exitCode:W.number().int().nullable(),stdout:W.string(),stderr:W.string()}),GS=W.object({ok:W.boolean(),cwd:W.string(),branch:W.string().nullable(),upstream:W.string().nullable(),ahead:W.number().int().nonnegative(),behind:W.number().int().nonnegative(),entries:W.array(W.object({path:W.string(),indexStatus:W.string(),workingTreeStatus:W.string(),originalPath:W.string().nullable()})),totalEntries:W.number().int().nonnegative(),truncated:W.boolean(),error:lG.nullable()}),QS=W.object({ok:W.boolean(),cwd:W.string(),path:W.string().nullable(),staged:W.boolean(),statOnly:W.boolean(),diff:W.string(),truncated:W.boolean(),error:lG.nullable()}),WS=W.object({ok:W.boolean(),cwd:W.string(),path:W.string().nullable(),commits:W.array(W.object({hash:W.string(),shortHash:W.string(),authorName:W.string(),authorEmail:W.string(),date:W.string(),subject:W.string()})),totalCommits:W.number().int().nonnegative(),truncated:W.boolean(),error:lG.nullable()}),HS=W.object({ok:W.boolean(),cwd:W.string(),revision:W.string(),path:W.string().nullable(),content:W.string(),truncated:W.boolean(),error:lG.nullable()});var zS="List files and directories within the working directory. Use this before reading or editing unfamiliar locations.",DS=W.object({path:R0.optional().default("."),recursive:W.boolean().optional().default(!1),includeHidden:W.boolean().optional().default(!1),maxEntries:j0(1,$5,"maxEntries").optional().default(100)}),qS=W.object({path:R0,recursive:W.boolean().optional(),includeHidden:W.boolean().optional()}),BS=W.object({path:W.string(),entries:W.array(W.object({path:W.string(),type:W.enum(["file","directory","symlink","other"]),size:W.number().int().nonnegative().nullable()})),totalEntries:W.number().int().nonnegative(),truncated:W.boolean()});var Un=W.object({transport:W.literal("stdio").default("stdio"),command:W.string().min(1).max(4096),args:W.array(W.string().max(4096)).optional().default([]),cwd:W.string().min(1).max(4096).optional(),env:W.record(W.string(),W.string()).optional().default({}),enabled:W.boolean().optional().default(!0)}),fJ$=W.object({servers:W.record(W.string().min(1).max(120),Un).optional().default({})}),Jn=W.enum(["stopped","running","degraded"]),LS=W.object({name:W.string().min(1),transport:W.literal("stdio"),enabled:W.boolean(),state:Jn,command:W.string().min(1),pid:W.number().int().positive().nullable(),error:W.string().nullable()}),_S=W.object({server:W.string().min(1),uri:W.string().min(1),name:W.string().nullable(),description:W.string().nullable(),mimeType:W.string().nullable()});var KS="List resources exposed by configured MCP servers. Servers must be configured and permission-gated.",VS="Read a resource from a configured MCP server by server name and resource URI.",OS="Call a configured MCP server tool. This is gated as danger-full-access unless explicitly allowed.",NS=W.object({server:W.string().min(1).max(120).optional()}),AS=W.object({server:W.string().min(1).max(120).optional()}),FS=W.object({servers:W.array(LS),resources:W.array(_S)}),VV=W.object({server:W.string().min(1).max(120),uri:W.string().min(1).max(4096)}),bS=VV,MS=W.object({server:W.string(),uri:W.string(),content:W.string(),mimeType:W.string().nullable()}),ZS=W.object({server:W.string().min(1).max(120),toolName:W.string().min(1).max(240),arguments:W.record(W.string(),W.unknown()).optional().default({})}),jS=W.object({server:W.string().min(1).max(120),toolName:W.string().min(1).max(240)}),IS=W.object({server:W.string(),toolName:W.string(),result:W.unknown()});var RS="Read file content from the working directory. Each call returns about 6,000 characters (roughly 150 lines); longer content is truncated head+tail. Small files: read them whole. Long files: find the spot with grep first, then read a startLine/endLine range of about 100-150 lines around it.",TS=W.object({path:R0,startLine:uX.optional(),endLine:uX.optional(),maxChars:j0(1,O6,"maxChars").optional()}).superRefine(($,U)=>{if($.startLine!==void 0&&$.endLine!==void 0&&$.endLine<$.startLine)U.addIssue({code:W.ZodIssueCode.custom,message:"endLine must be greater than or equal to startLine.",path:["endLine"]})}),SS=W.object({path:R0,startLine:uX.optional(),endLine:uX.optional()}),ES=W.object({path:W.string(),startLine:W.number().int().min(1),endLine:W.number().int().min(1),content:W.string(),totalLines:W.number().int().nonnegative(),truncated:W.boolean()});var Xn=W.object({label:W.string().min(1).max(120),description:W.string().min(1).max(240).optional()}),PS="Ask the user a focused question while planning. Use this to collect missing requirements or confirm tradeoffs before finalizing a plan.",pG=W.object({question:W.string().min(1).max(2000),header:W.string().min(1).max(80).optional(),options:W.array(Xn).min(1).max(8).optional(),allowCustomResponse:W.boolean().optional().default(!0),placeholder:W.string().min(1).max(200).optional()}),gS=W.object({question:W.string().min(1).max(2000)}),HJ=W.object({answer:W.string().min(1).max(4000),selectedOption:W.string().min(1).max(120).optional(),source:W.enum(["option","custom"])});var CS="Load an installed skill by name before following its instructions. Use resource to read a supporting file relative to that skill's directory.",OV=W.object({name:W.string().min(1).max(160),resource:W.string().min(1).max(1024).optional()}),vS=OV,xS=W.object({name:W.string().min(1),description:W.string().nullable(),path:W.string().min(1),source:W.enum(["project","user"])}),kS=W.object({skill:xS,content:W.string()}),tJ$=W.object({skills:W.array(xS)});var yS="Persist the current session task list. Use this to track multi-step coding work and update task status as progress changes.",hS=W.enum(["pending","in_progress","completed","canceled"]),Yn=W.enum(["low","medium","high"]),fS=W.object({id:W.string().min(1).max(120).optional(),content:W.string().min(1).max(QV),status:hS,priority:Yn.optional().default("medium"),notes:W.string().max(1000).optional(),activeForm:W.string().min(1).max(WV).optional()}),wn=W.object({content:W.string().min(1).max(QV),status:hS,activeForm:W.string().min(1).max(WV).optional().describe('Present-tense label shown while in_progress, e.g. "Adding tests".')}),uS=W.object({todos:W.array(fS).max(50)}),mS=W.object({todos:W.array(wn).max(20)}),iS=W.object({sessionId:W.string(),path:W.string(),todos:W.array(fS),summary:W.object({total:W.number().int().nonnegative(),pending:W.number().int().nonnegative(),inProgress:W.number().int().nonnegative(),completed:W.number().int().nonnegative(),canceled:W.number().int().nonnegative()}),warnings:W.array(W.string()).optional()});var lS="Search available coding-agent tools by name, capability, or permission requirement.",pS=W.object({query:W.string().min(1).max(200),maxResults:j0(1,kX,"maxResults").optional().default(10)}),cS=W.object({query:W.string().min(1).max(200)}),dS=W.object({query:W.string(),results:W.array(W.object({name:p4,description:W.string(),permissionMode:d1,activeModes:W.array(c4),score:W.number()})),totalResults:W.number().int().nonnegative(),truncated:W.boolean()});var rS="Fetch a URL and return normalized, bounded text with source metadata. Keep maxChars modest and request more only if the answer wasn't in the returned text. Requires network permission.",nS=W.object({url:W.string().url().max(4096),maxChars:j0(200,O6,"maxChars").optional().default(aU),timeoutMs:j0(1000,30000,"timeoutMs").optional().default(1e4)}),oS=W.object({url:W.string().url().max(4096)}),Gn=W.object({code:W.string(),message:W.string()}),aS=W.object({ok:W.boolean(),url:W.string(),finalUrl:W.string().nullable(),status:W.number().int().nullable(),statusText:W.string().nullable(),contentType:W.string().nullable(),title:W.string().nullable(),text:W.string(),truncated:W.boolean(),fetchedAt:W.string(),error:Gn.nullable()});var tS="Search the live web through the configured provider-native or local search backend and return citable sources.",Qn=W.enum(["auto","brave","tavily"]),sS=W.object({query:W.string().min(1).max(500),provider:Qn.optional().default("auto"),maxResults:j0(1,25,"maxResults").optional().default(3)}),eS=W.object({query:W.string().min(1).max(500)}),Wn=W.object({code:W.string(),message:W.string()}),$E=W.object({ok:W.boolean(),query:W.string(),provider:W.string(),results:W.array(W.object({title:W.string(),url:W.string(),snippet:W.string(),source:W.string().nullable()})),totalResults:W.number().int().nonnegative(),error:Wn.nullable()});var UE="Write complete file content to a path in the working directory. Use for creating or overwriting files.",JE=W.object({path:R0,content:W.string(),overwrite:W.boolean().optional().default(!0)}),XE=W.object({path:R0,content:W.string()}),YE=W.object({path:W.string(),created:W.boolean(),bytesWritten:W.number().int().nonnegative(),diff:W.string().optional()});var zJ=["build"],Hn=["plan"],r1=["build","plan"],cG={agent:{description:ET,inputSchema:PT,providerInputSchema:gT,outputSchema:CT,modes:r1,permissionSubject:"agent",permissionMode:"read-only",execution:"server",availability:"model",activation:"core",outputPolicy:"artifact-if-large"},list_files:{description:zS,inputSchema:DS,providerInputSchema:qS,outputSchema:BS,modes:r1,permissionSubject:"list_files",permissionMode:"read-only",execution:"server",availability:"always",activation:"core",outputPolicy:"artifact-if-large"},glob_search:{description:cT,inputSchema:dT,providerInputSchema:rT,outputSchema:nT,modes:r1,permissionSubject:"glob_search",permissionMode:"read-only",execution:"server",availability:"always",activation:"core",outputPolicy:"artifact-if-large"},read_file:{description:RS,inputSchema:TS,providerInputSchema:SS,outputSchema:ES,modes:r1,permissionSubject:"read_file",permissionMode:"read-only",execution:"server",availability:"always",activation:"core",outputPolicy:"artifact-if-large"},grep:{description:mT,inputSchema:iT,providerInputSchema:lT,outputSchema:pT,modes:r1,permissionSubject:"grep",permissionMode:"read-only",execution:"server",availability:"always",activation:"core",outputPolicy:"artifact-if-large"},git_status:{description:oT,inputSchema:eT,providerInputSchema:$S,outputSchema:GS,modes:r1,permissionSubject:"git_status",permissionMode:"read-only",execution:"server",availability:"git-workspace",activation:"specialized",outputPolicy:"artifact-if-large"},git_diff:{description:aT,inputSchema:US,providerInputSchema:JS,outputSchema:QS,modes:r1,permissionSubject:"git_diff",permissionMode:"read-only",execution:"server",availability:"git-workspace",activation:"specialized",outputPolicy:"artifact-if-large"},git_log:{description:tT,inputSchema:KV,providerInputSchema:XS,outputSchema:WS,modes:r1,permissionSubject:"git_log",permissionMode:"read-only",execution:"server",availability:"git-workspace",activation:"specialized",outputPolicy:"artifact-if-large"},git_show:{description:sT,inputSchema:YS,providerInputSchema:wS,outputSchema:HS,modes:r1,permissionSubject:"git_show",permissionMode:"read-only",execution:"server",availability:"git-workspace",activation:"specialized",outputPolicy:"artifact-if-large"},tool_search:{description:lS,inputSchema:pS,providerInputSchema:cS,outputSchema:dS,modes:r1,permissionSubject:"tool_search",permissionMode:"read-only",execution:"server",availability:"always",activation:"core",outputPolicy:"inline"},skill:{description:CS,inputSchema:OV,providerInputSchema:vS,outputSchema:kS,modes:r1,permissionSubject:"skill",permissionMode:"read-only",execution:"server",availability:"skills",activation:"core",outputPolicy:"artifact-if-large"},list_mcp_resources:{description:KS,inputSchema:NS,providerInputSchema:AS,outputSchema:FS,modes:r1,permissionSubject:"list_mcp_resources",permissionMode:"read-only",execution:"server",availability:"mcp",activation:"specialized",outputPolicy:"artifact-if-large"},read_mcp_resource:{description:VS,inputSchema:VV,providerInputSchema:bS,outputSchema:MS,modes:r1,permissionSubject:"read_mcp_resource",permissionMode:"read-only",execution:"server",availability:"mcp",activation:"specialized",outputPolicy:"artifact-if-large"},call_mcp_tool:{description:OS,inputSchema:ZS,providerInputSchema:jS,outputSchema:IS,modes:zJ,permissionSubject:"call_mcp_tool",permissionMode:"danger-full-access",execution:"server",availability:"mcp",activation:"specialized",outputPolicy:"artifact-if-large"},request_user_input:{description:PS,inputSchema:pG,providerInputSchema:gS,outputSchema:HJ,modes:Hn,permissionSubject:"request_user_input",permissionMode:"read-only",execution:"client",availability:"always",activation:"core",outputPolicy:"inline"},todo_write:{description:yS,inputSchema:uS,providerInputSchema:mS,outputSchema:iS,modes:zJ,permissionSubject:"todo_write",permissionMode:"workspace-write",execution:"server",availability:"always",activation:"core",outputPolicy:"inline"},write_file:{description:UE,inputSchema:JE,providerInputSchema:XE,outputSchema:YE,modes:zJ,permissionSubject:"write_file",permissionMode:"workspace-write",execution:"server",availability:"always",activation:"core",outputPolicy:"inline"},edit_file:{description:hT,inputSchema:_V,providerInputSchema:fT,outputSchema:uT,modes:zJ,permissionSubject:"edit_file",permissionMode:"workspace-write",execution:"server",availability:"always",activation:"core",outputPolicy:"inline"},bash:{description:vT,inputSchema:xT,providerInputSchema:kT,outputSchema:yT,modes:zJ,permissionSubject:"bash",permissionMode:"danger-full-access",execution:"server",availability:"always",activation:"core",outputPolicy:"artifact-if-large"},web_fetch:{description:rS,inputSchema:nS,providerInputSchema:oS,outputSchema:aS,modes:zJ,permissionSubject:"web_fetch",permissionMode:"danger-full-access",execution:"server",availability:"web",activation:"specialized",outputPolicy:"artifact-if-large"},web_search:{description:tS,inputSchema:sS,providerInputSchema:eS,outputSchema:$E,modes:r1,permissionSubject:"web_search",permissionMode:"danger-full-access",execution:"server-or-provider",availability:"web",activation:"specialized",outputPolicy:"artifact-if-large"}};function mX($){return Object.fromEntries(Object.entries(cG).map(([U,J])=>[U,J[$]]))}var zn=mX("description"),iX=mX("inputSchema"),Dn=mX("providerInputSchema"),qn=mX("outputSchema"),dG=mX("permissionMode");var d7$=W.object({messages:W.array(W.json()),cwd:W.string().min(1).max(4096),mode:c4.optional(),permissionMode:d1.optional(),providerWebSearchDecision:hX.optional(),allowedTools:W.array(p4).optional(),permissionRules:yX.optional(),sandbox:WJ.optional()}),Bn=new Set(Object.keys(cG).filter(($)=>cG[$].execution!=="client"));function wE($){return Bn.has($)}var r7$=W.object({cwd:W.string().min(1).max(4096),sessionId:W.string().min(1).max(200).optional(),mode:c4.optional(),permissionMode:d1.optional(),providerWebSearchDecision:hX.optional(),allowedTools:W.array(p4).optional(),permissionRules:yX.optional(),sandbox:WJ.optional(),environmentContext:W.string().optional(),maxOutputTokens:W.number().int().min(1).optional(),contextWindow:W.number().int().positive().optional(),preserveRecentTokens:W.number().int().nonnegative().optional(),originalInputTokens:W.number().int().nonnegative().optional(),assemblyAbortSignal:W.custom().optional(),turnKey:W.string().min(1).max(200).optional()});function Ln($){return $==="plan"?"read-only":"workspace-write"}function _n({mode:$,permissionMode:U}){if($==="plan")return"read-only";return U??Ln($)}function Kn({mode:$,permissionMode:U,allowedTools:J,permissionRules:Y,approved:X,toolRequirements:w=dG}){return new DV({activeMode:_n({mode:$,permissionMode:U}),toolRequirements:w,allowedTools:J,rules:Y,approved:X})}function Vn($,U){if(!$||typeof $!=="object")return null;let J=Reflect.get($,U);return typeof J==="string"&&J.trim().length>0?J.trim():null}function On($,U){if($!=="bash")return{permissionMode:dG[$]};let J=Vn(U,"command")??"",Y=jT(J);return{permissionMode:Y.permissionMode,reason:Y.reason}}function NV({toolName:$,input:U,mode:J,permissionMode:Y,allowedTools:X,permissionRules:w,approved:G}){let Q=On($,U),H={...dG,[$]:Q.permissionMode},z=Kn({mode:J,permissionMode:Y,allowedTools:X,permissionRules:w,approved:G,toolRequirements:H}).decide($,U);if($==="bash"&&Q.reason)return{...z,reason:z.reason&&z.reason!==Q.reason?`${z.reason} ${Q.reason}`:Q.reason};return z}var Nn=new Set(["auth","billing","rate_limit","invalid_request","context_overflow","provider_unavailable","network","aborted","unknown"]);function rG($){if(!$||!$.startsWith("LIGHTCODE_ERROR:"))return null;try{let U=JSON.parse($.slice(16));if(typeof U!=="object"||U===null||typeof U.message!=="string"||typeof U.retryable!=="boolean"||typeof U.kind!=="string"||!Nn.has(U.kind))return null;return{kind:U.kind,statusCode:typeof U.statusCode==="number"?U.statusCode:void 0,retryable:U.retryable,message:U.message,contextLimitTokens:typeof U.contextLimitTokens==="number"?U.contextLimitTokens:void 0}}catch{return null}}var An={auth:"Authentication error",billing:"Billing or quota error",rate_limit:"Rate limited",invalid_request:"Provider rejected the request",context_overflow:"Context window exceeded",provider_unavailable:"Provider unavailable",network:"Connection error",aborted:"Request aborted",unknown:"Provider error"};function GE($){let U=$.statusCode?` (HTTP ${$.statusCode})`:"";return`${An[$.kind]}${U}: ${$.message}`}var Fn=["tool_approval","user_prompt"],QE=W.enum(Fn),bn=["pending","approved","denied","answered","superseded"],AV=W.enum(bn),nG=W.string().min(1).max(240),WE=W.object({toolName:p4,input:W.json(),summary:W.string().min(1).max(4000),permissionDecision:ZT,cwd:W.string().min(1).max(4096)}),oG=pG,UX$=W.union([WE,oG]),Mn=W.object({id:W.string().min(1),sessionId:N6,toolCallId:nG,kind:QE,status:AV,payload:W.json(),response:W.json().nullable(),resolvedAt:W.string().min(1).nullable(),createdAt:W.string().min(1),updatedAt:W.string().min(1)}),FV=W.discriminatedUnion("kind",[W.object({kind:W.literal("tool_approval"),toolCallId:nG,payload:WE}),W.object({kind:W.literal("user_prompt"),toolCallId:nG,payload:oG})]),JX$=AV.exclude(["pending"]),XX$=W.union([W.object({status:W.literal("answered"),response:HJ}),W.object({status:W.enum(["approved","denied","superseded"]),response:W.json().optional()})]),YX$=W.object({status:AV.optional(),kind:QE.optional()}),wX$=W.object({id:fX}),GX$=W.object({id:fX,toolCallId:nG}),QX$=W.object({interactions:W.array(Mn)}),WX$=W.object({total:W.number().int().nonnegative(),toolApprovals:W.number().int().nonnegative(),userPrompts:W.number().int().nonnegative(),stale:W.number().int().nonnegative(),recoverable:W.number().int().nonnegative()});function bV($,U=140){let J;if(typeof $==="string")J=$;else try{J=JSON.stringify($)}catch{J=String($)}let Y=J.replace(/\s+/g," ").trim();if(Y.length<=U)return Y;return`${Y.slice(0,U-3)}...`}var J5=Symbol("no-change");function Zn($,U){if($===void 0||$===null)return J5;switch(U){case"number":{if(typeof $==="string"){let J=$.trim();if(J!==""&&Number.isFinite(Number(J)))return Number(J)}return J5}case"boolean":{if(typeof $==="string"){let J=$.trim().toLowerCase();if(J==="true"||J==="1"||J==="yes")return!0;if(J==="false"||J==="0"||J==="no")return!1}if($===1)return!0;if($===0)return!1;return J5}case"string":{if(typeof $==="number"||typeof $==="boolean")return String($);return J5}case"object":case"array":{if(typeof $==="string")try{let J=JSON.parse($),Y=Array.isArray(J);if(U==="array"?Y:J!==null&&typeof J==="object"&&!Y)return J}catch{}return J5}default:return J5}}function jn($,U,J){if(U.length===0||$===null||typeof $!=="object")return!1;let Y=$;for(let G=0;G<U.length-1;G+=1){let Q=Y[U[G]];if(Q===null||typeof Q!=="object")return!1;Y=Q}let X=U[U.length-1],w=Zn(Y[X],J);if(w===J5)return!1;return Y[X]=w,!0}function HE($,U){if($===null||typeof $!=="object")return null;let J;try{J=structuredClone($)}catch{J=$}for(let X=0;X<4;X+=1){let w=U.safeParse(J);if(w.success)return w.data;let G=!1;for(let Q of w.error.issues){if(Q.code!=="invalid_type")continue;let H=Q.expected;if(typeof H!=="string")continue;if(jn(J,Q.path,H))G=!0}if(!G)break}let Y=U.safeParse(J);return Y.success?Y.data:null}function MV($,U){let J=iX[$],Y=J.safeParse(U);if(Y.success)return Y.data;let X=HE(U,J);if(X!==null)return X;return J.parse(U)}var In=W.enum(["stop","length","content-filter","tool-calls","error","other","unknown"]),Rn=W.object({usage:W.object({inputTokens:W.number().nonnegative().optional(),outputTokens:W.number().nonnegative().optional(),totalTokens:W.number().nonnegative().optional(),cachedInputTokens:W.number().nonnegative().optional()}),modelId:W.string().optional(),finishReason:In.optional(),context:W.object({inputTokens:W.number().nonnegative(),contextWindow:W.number().positive(),compactedMessages:W.number().nonnegative().optional(),systemTokens:W.number().nonnegative().optional(),toolTokens:W.number().nonnegative().optional(),messageTokens:W.number().nonnegative().optional(),mediaTokens:W.number().nonnegative().optional(),remainingTokens:W.number().nonnegative().optional(),compactedTokens:W.number().nonnegative().optional()}).optional()}).loose();function zE($){if($.role!=="assistant"||$.metadata===void 0)return null;let U=Rn.safeParse($.metadata);return U.success?U.data:null}var aG={enabled:!0,maxAutoContinues:50},Tn="Your previous response was cut off by the output token limit. Continue exactly where you left off. Do not repeat completed work.",Sn="You stopped before completing the task. Review your todo list and continue working until every item is complete. Call tools through the function-calling interface, never as XML or plain text.",En=/(?::|\b(?:let me|i'll now|i will now|next,? i(?:'ll| will)|now i(?:'ll| will)|going to|proceeding to|let's)\s*[\w,' ]*)$/i,Pn=3,gn=200;function DE($){return $.parts.map((U)=>U.type==="text"?U.text:"").join("")}function Cn($){for(let U=$.length-1;U>=0;U--)if($[U].role==="assistant")return $[U];return null}function vn($){return $.some((U)=>U.status==="pending"||U.status==="in_progress")}function xn($){let U=$.trim();if(!U)return!1;return En.test(U)}function kn($){let U=DE($).trim().slice(0,gn),J=$.parts.filter((Y)=>Y.type.startsWith("tool-")).map((Y)=>{let X=Y;return`${X.type}:${JSON.stringify(X.input??null)}`}).join("|");return`${U}::${J}`}function yn($,U=Pn){let J=[];for(let w=$.length-1;w>=0&&J.length<U;w--)if($[w].role==="assistant")J.push(kn($[w]));if(J.length<U)return!1;let[Y,...X]=J;if(!Y.trim()||Y==="::")return!1;return X.every((w)=>w===Y)}function qE({lastActivityAt:$,now:U,stallTimeoutMs:J}){return J>0&&U-$>=J}function BE({messages:$,todos:U,autoContinuesThisTurn:J,limits:Y=aG}){if(!Y.enabled)return{kind:"none"};let X=Cn($);if(!X)return{kind:"none"};let w=zE(X),G=w?.finishReason,Q=w?.toolIntent,H=G==="length"?"continue-length":G==="stop"&&(Q==="unparsed"||vn(U)||xn(DE(X)))?"nudge-stop":null;if(!H)return{kind:"none"};if(J>=Y.maxAutoContinues)return{kind:"none",guardTripped:"max-continues"};if(yn($))return{kind:"none",guardTripped:"doom-loop"};return H==="continue-length"?{kind:"continue-length",prompt:Tn}:{kind:"nudge-stop",prompt:Sn}}async function ZV($){if(typeof $==="function")return Promise.resolve($());return Promise.resolve($)}var hn="Connection interrupted. Please retry or regenerate your last message.",LE="Proceed with implementation in Build mode. Continue without additional plan questions.",fn=50,un=/^\/?(retry|regenerate)$/i,mn="provider_web_search_approval_required",tU="lightcode-provider-web-search-approval",ln=/^: lightcode-cursor=(\d+)\r?$/;function _E($,U){let J=`${$.carry}${U}`.split(`
|
|
100
100
|
`),Y=J.pop()??"",X=$.cursor;for(let w of J){let G=ln.exec(w);if(!G)continue;let Q=Number(G[1]);if(Number.isSafeInteger(Q)&&Q>X)X=Q}return{carry:Y.slice(-128),cursor:X}}function pn($){return Boolean($.body&&$.status!==204&&$.status!==205&&$.status!==304)}function cn({chatApi:$,runId:U,after:J}){let Y=/^[a-z][a-z\d+.-]*:\/\//i.test($),X=new URL($,"http://lightcode.local");return X.pathname=X.pathname.replace(/\/turns\/?$/,U?`/runs/${encodeURIComponent(U)}/stream`:"/runs/stream"),X.search="",X.searchParams.set("after",String(Math.max(-1,Math.floor(J)))),Y?X.toString():`${X.pathname}${X.search}`}var dn=new Set(Object.keys(iX)),rn=1000,nn=8000,on=6,an=180000;function tn({attempt:$,kind:U,elapsedMs:J,maxErrorRetries:Y}){let X=U==="rate_limit"?Math.min(on,Y):Y;if($>X)return{retry:!1,delayMs:0};let w=Math.min(rn*2**($-1),nn);if(J+w>an)return{retry:!1,delayMs:0};return{retry:!0,delayMs:w}}function jV($,U){if($ instanceof Error)return $.message;return U}function KE($){return dn.has($)}function sn($){return $==="request_user_input"}function DJ($,U){if(!$||typeof $!=="object")return null;let J=Reflect.get($,U);return typeof J==="string"&&J.trim().length>0?J.trim():null}function en($,U){let J=DJ(U,"path")??DJ(U,"command")??DJ(U,"query")??DJ(U,"pattern")??DJ(U,"revision")??DJ(U,"url");if(J)return`${$} ${bV(J)}`.trim();return`${$} ${bV(U)}`.trim()}function $o($,U){return $==="todo_write"&&typeof U==="object"&&U!==null&&Array.isArray(Reflect.get(U,"todos"))}var NE=/(failed to fetch|networkerror|socket|connection|aborted|terminated|timed?\s?out|timeout|econnreset)/i,Uo=/(rate.?limit|too many requests|\b429\b|overloaded|quota)/i;function Jo($){let U=rG($);if(U)return GE(U);if(NE.test($))return hn;return $}function tG($){let U=rG($);if(U)return U.retryable;return NE.test($)||Uo.test($)}function Xo($){return un.test($.trim())}function Yo($){let U=JSON.stringify($),J=2166136261;for(let Y=0;Y<U.length;Y+=1)J^=U.charCodeAt(Y),J=Math.imul(J,16777619);return(J>>>0).toString(16).padStart(8,"0")}function wo($){if(($.type==="text"||$.type==="reasoning")&&Reflect.get($,"state")==="streaming")return!0;return l4($)&&$.state==="input-streaming"}function VE($){let U=$;while(U.length>0){let J=U.length-1,Y=U[J];if(Y.role!=="assistant")break;let X=Y.parts.filter((G)=>!wo(G));if(X.length===Y.parts.length)break;if(X.length===0){U=U.slice(0,J);continue}let w=U.slice();w[J]={...Y,parts:X},U=w;break}return U}function Go($){return $.some((U)=>U.parts.some((J)=>{if(!l4(J))return!1;return!["output-available","output-error","output-denied"].includes(J.state)}))}var Qo=new Set(["output-available","output-error","output-denied"]);function Wo($){let U=0;for(let J of $)for(let Y of J.parts)if((Y.type==="text"||Y.type==="reasoning")&&Reflect.get(Y,"state")!=="streaming")U+=1;else if(l4(Y)&&Qo.has(Y.state))U+=1;return U}function Ho({messages:$,pendingApprovals:U,pendingUserPrompts:J}){let Y=new Set(U.map((w)=>w.toolCallId)),X=new Set(J.map((w)=>w.toolCallId));return $.some((w)=>w.parts.some((G)=>{if(!l4(G))return!1;if(G.state==="input-streaming"||G.state==="approval-responded")return!0;if(G.state!=="input-available")return!1;return!Y.has(G.toolCallId)&&!X.has(G.toolCallId)}))}function zo($){let U=$.trim();if(!U)return null;let J=U.match(/^\/?(approve|deny)(?:\s+(all|\d+))?$/i);if(J){let X=J[1].toLowerCase()==="approve"?"approve":"deny",w=J[2]?.toLowerCase(),G=w==="all"?"all":w?Math.max(0,Number(w)-1):0;return{action:X,target:G}}return null}async function OE($){let U=[];for(let J of $){let Y=await OT({messages:[J]});if(!Y.success||Y.data.length===0)continue;U.push(Y.data[0])}return U}function Do($){if($.kind!=="user_prompt"||$.status!=="pending")return null;let U=oG.safeParse($.payload);if(!U.success)return null;return{toolCallId:$.toolCallId,header:U.data.header,question:U.data.question,options:U.data.options??[],allowCustomResponse:U.data.allowCustomResponse,placeholder:U.data.placeholder}}function AE({chatApi:$,initialPrompt:U="",isSessionIdValid:J,loadPersistedMessages:Y,loadPersistedInteractions:X,upsertInteraction:w,resolveInteraction:G,sessionId:Q,skipHistoryLoad:H=!1,cwd:z,loadTodos:D,fetch:q,headers:L,mode:B=HV,permissionMode:O,allowedTools:A,permissionRules:I,sandbox:V,autoContinue:K}){let _=e.useRef(null),F=e.useRef(0),R=e.useRef(`turn-${Date.now()}-0`),b=e.useRef(B),E=e.useRef(z),C=e.useRef(O),x=e.useRef(A),Z=e.useRef(I),W$=e.useRef(V),Q$=e.useRef(q),t=e.useRef(L),i=e.useRef(0),$$=e.useRef(null),X$=e.useRef(-1),B$=e.useRef(null),P$=e.useRef(null),k$=e.useRef(async()=>{return}),M=e.useRef(void 0),p$=e.useRef(null),L0=e.useRef(Y),j=e.useRef(X),[t$,Q0]=e.useState(null),[p,r]=e.useState(null),[q$,r0]=e.useState(!0),[T0,n0]=e.useState(!0),[o0,u$]=e.useState(!1),[J0,w1]=e.useState([]),[I0,e0]=e.useState([]),[L4,_4]=e.useState([]),[a4,G1]=e.useState(null),K4={enabled:K?.enabled??aG.enabled,maxAutoContinues:K?.maxAutoContinues??aG.maxAutoContinues},W0=K?.maxErrorRetries??5,YU=(K?.stallTimeoutSeconds??180)*1000,C4=e.useRef(K4);C4.current=K4;let v=e.useRef(W0);v.current=W0;let a=W0+3,V$=e.useRef(a);V$.current=a;let I$=e.useRef(YU);I$.current=YU;let y$=e.useRef(Date.now()),_0=e.useRef(!1),a0=e.useRef(0),K0=e.useRef(0),P=e.useRef(null),y=e.useRef(null),u=e.useRef(null),L$=e.useRef(0),R$=e.useRef(0),$1=e.useRef(!1),M6=e.useRef([]),V5=e.useCallback(()=>{if(F.current+=1,R.current=`turn-${Date.now()}-${F.current}`,a0.current=0,K0.current=0,y.current=null,L$.current=0,R$.current=0,$1.current=!1,u.current=null,M.current=void 0,p$.current=null,w1((m)=>m.filter((G$)=>G$.approvalId!==tU)),P.current)clearTimeout(P.current),P.current=null;G1(null)},[]),D8=e.useCallback((m)=>{let G$=Wo(m);if(G$>L$.current)return L$.current=G$,R$.current=0,!0;if(R$.current+=1,R$.current>V$.current)return $1.current=!0,!1;return!0},[]);b.current=B,E.current=z,C.current=O,x.current=A,Z.current=I,W$.current=V,Q$.current=q,t.current=L,L0.current=Y,j.current=X;let q8=e.useCallback(()=>{let m=P$.current;if(m)return m;u$(!0);let G$=k$.current().finally(()=>{if(P$.current===G$)P$.current=null;u$(!1)});return P$.current=G$,G$},[]),B8=e.useMemo(()=>{return new AT({api:$,fetch:async(G$,b$)=>{let O$=b$?.method?.toUpperCase()??"GET";if(O$==="POST")$$.current=null,X$.current=-1;let N$=await(Q$.current??globalThis.fetch)(G$,b$),h0=N$.headers.get("x-lightcode-revision");if(h0){let s4=Number(h0);if(Number.isInteger(s4)&&s4>=0)i.current=s4}let wU=N$.headers.get("x-lightcode-run-id");if(wU){if(wU!==$$.current)X$.current=-1;$$.current=wU}else if(O$==="GET"&&N$.status===204)$$.current=null,X$.current=-1;if(N$.status===428)try{let s4=await N$.clone().json();if(typeof s4==="object"&&s4!==null&&Reflect.get(s4,"code")===mn){let _2={query:"Allow provider-native web search for this turn",provider:"auto",maxResults:3},RN={toolCallId:tU,approvalId:tU,toolName:"web_search",input:_2,summary:"Use provider-native web search during this turn.",permissionDecision:NV({toolName:"web_search",input:_2,mode:b.current??HV,permissionMode:C.current,allowedTools:x.current,permissionRules:Z.current}),cwd:E.current};p$.current=RN,w1((_v)=>[RN,..._v.filter((Kv)=>Kv.approvalId!==tU)])}}catch{}if(y$.current=Date.now(),!pn(N$))return N$;let Z6=N$.body;if(!Z6)return N$;let IN=new TextDecoder,Z5={carry:"",cursor:X$.current},Lv=Z6.pipeThrough(new TransformStream({transform(s4,_2){y$.current=Date.now(),Z5=_E(Z5,IN.decode(s4,{stream:!0})),X$.current=Z5.cursor,_2.enqueue(s4)},flush(){Z5=_E(Z5,IN.decode()),X$.current=Z5.cursor}}));return new Response(Lv,{status:N$.status,statusText:N$.statusText,headers:N$.headers})},headers:async()=>await ZV(t.current)??{},body:()=>({mode:b.current,permissionMode:C.current,allowedTools:x.current,permissionRules:Z.current,sandbox:W$.current}),prepareSendMessagesRequest:async({messages:G$,body:b$,trigger:O$})=>{await P$.current;let N$=G$.at(-1);if(!N$||N$.role!=="user"&&N$.role!=="assistant")throw Error("No admissible turn message is available to send.");let h0=i.current;return{body:{...b$,clientTurnId:`${N$.id}:${h0}:${Yo({parts:N$.parts,metadata:N$.metadata,trigger:O$})}`,expectedRevision:h0,messageId:N$.id,role:N$.role,parts:N$.parts,metadata:N$.metadata,trigger:O$,providerWebSearchDecision:M.current}}},prepareReconnectToStreamRequest:()=>({api:cn({chatApi:$,runId:$$.current,after:X$.current})})})},[$]),C1=e.useCallback(async(m)=>{if(!w)return;try{await w(m)}catch(G$){console.warn("Failed to checkpoint chat interaction.",G$)}},[w]),t4=e.useCallback(async(m,G$)=>{if(!G)return;try{await G(m,G$)}catch(b$){console.warn("Failed to resolve chat interaction.",b$)}},[G]),O5=e.useCallback((m)=>{if(!m)return;Promise.resolve(m).catch((G$)=>{r(jV(G$,"Failed to deliver the tool response to the model. Retry or resend your message."))})},[]),{messages:Q1,setMessages:bN,sendMessage:t1,addToolOutput:N5,addToolApprovalResponse:B2,clearError:A5,error:W1,resumeStream:F5,status:s1,stop:L2}=GT({id:Q,transport:B8,experimental_throttle:fn,sendAutomaticallyWhen:(m)=>bT(m)||FT(m),onFinish:({isAbort:m,isDisconnect:G$})=>{if(m||G$)return;q8()},onToolCall:async({toolCall:m})=>{if(m.dynamic||!KE(m.toolName))return;if(wE(m.toolName))return;let G$=m.toolName;if(!sn(G$))return;let b$;try{b$=MV("request_user_input",m.input)}catch(N$){O5(N5({tool:G$,toolCallId:m.toolCallId,state:"output-error",errorText:jV(N$,"Invalid tool input payload.")}));return}if(B!=="plan"){O5(N5({tool:"request_user_input",toolCallId:m.toolCallId,output:{answer:LE,source:"custom"}}));return}let O$={toolCallId:m.toolCallId,header:b$.header,question:b$.question,options:b$.options??[],allowCustomResponse:b$.allowCustomResponse,placeholder:b$.placeholder};C1(FV.parse({kind:"user_prompt",toolCallId:m.toolCallId,payload:b$})),e0((N$)=>{if(N$.some((h0)=>h0.toolCallId===m.toolCallId))return N$;return[...N$,O$]})}}),b5=e.useRef(bN);b5.current=bN;let M5=e.useCallback(async()=>{if(A5(),r(null),await F5(),!$$.current)await q8();else if(P$.current)await P$.current},[A5,F5,q8]),MN=e.useRef(new Set);e.useEffect(()=>{let m=[];for(let O$ of Q1){if(O$.role!=="assistant")continue;for(let N$ of O$.parts){if(!l4(N$)||N$.state!=="approval-requested")continue;let h0=QJ(N$);if(!KE(h0))continue;let wU=N$.approval?.id;if(!wU)continue;let Z6;try{Z6=MV(h0,N$.input)}catch{continue}m.push({toolCallId:N$.toolCallId,approvalId:wU,toolName:h0,input:Z6,summary:en(h0,Z6),permissionDecision:NV({toolName:h0,input:Z6,mode:B,permissionMode:O,allowedTools:A,permissionRules:I}),cwd:z})}}let G$=p$.current,b$=G$?[G$,...m]:m;w1((O$)=>{if(O$.length===b$.length&&O$.every((N$,h0)=>N$.toolCallId===b$[h0].toolCallId))return O$;return b$});for(let O$ of m){if(MN.current.has(O$.toolCallId))continue;MN.current.add(O$.toolCallId),C1(FV.parse({kind:"tool_approval",toolCallId:O$.toolCallId,payload:{toolName:O$.toolName,input:O$.input,summary:O$.summary,permissionDecision:O$.permissionDecision,cwd:z}}))}},[A,C1,z,Q1,B,O,I]),e.useEffect(()=>{for(let m=Q1.length-1;m>=0;m-=1){let G$=Q1[m];if(G$.role!=="assistant")continue;for(let b$=G$.parts.length-1;b$>=0;b$-=1){let O$=G$.parts[b$];if(!l4(O$)||O$.state!=="output-available"||QJ(O$)!=="todo_write")continue;let N$=O$.output;if($o("todo_write",N$))_4(N$.todos);return}}},[Q1]);let cQ=e.useCallback((m,G$)=>{if(J0.length===0){r("No pending tool approvals.");return}if(!Number.isInteger(G$)||G$<0||G$>=J0.length){r(`Invalid approval index. Use 1-${J0.length}.`);return}let b$=J0[G$];if(w1((O$)=>O$.filter((N$)=>N$.toolCallId!==b$.toolCallId)),r(null),b$.approvalId===tU){p$.current=null,M.current=m==="approve"?"approved":"denied",A5(),t1();return}B2({id:b$.approvalId,approved:m==="approve",...m==="deny"?{reason:"Tool execution denied by user."}:{}}),t4(b$.toolCallId,{status:m==="approve"?"approved":"denied",response:m==="deny"?{errorText:"Tool execution denied by user."}:void 0})},[B2,A5,t4,J0,t1]),dQ=e.useCallback((m)=>{if(J0.length===0){r("No pending tool approvals.");return}let G$=[...J0];w1([]),r(null);let b$=G$.find((O$)=>O$.approvalId===tU);if(b$)p$.current=null,M.current=m==="approve"?"approved":"denied";for(let O$ of G$){if(O$.approvalId===tU)continue;B2({id:O$.approvalId,approved:m==="approve",...m==="deny"?{reason:"Tool execution denied by user."}:{}}),t4(O$.toolCallId,{status:m==="approve"?"approved":"denied",response:m==="deny"?{errorText:"Tool execution denied by user."}:void 0})}if(b$)A5(),t1()},[B2,A5,t4,J0,t1]),Gv=e.useCallback(({toolCallId:m,...G$})=>{if(!I0.find((N$)=>N$.toolCallId===m)){r("No matching user prompt is pending.");return}let O$=HJ.safeParse(G$);if(!O$.success){r("Invalid user prompt response.");return}r(null),e0((N$)=>N$.filter((h0)=>h0.toolCallId!==m)),O5((async()=>{await N5({tool:"request_user_input",toolCallId:m,output:O$.data}),await t4(m,{status:"answered",response:O$.data})})())},[N5,t4,I0,O5]),rQ=Boolean(W1?.message&&tG(W1.message)),nQ=e.useCallback(async()=>{if(!W1?.message||!tG(W1.message)){r("No recoverable response is waiting to retry.");return}if(J0.length>0||I0.length>0){r("Resolve pending tool approvals or user prompts before retrying.");return}await M5()},[W1?.message,J0.length,I0.length,M5]);e.useEffect(()=>{if(s1==="ready"&&!W1)K0.current=0,y.current=null},[W1,s1]),e.useEffect(()=>{if(s1==="streaming"||s1==="submitted")y$.current=Date.now()},[Q1,s1]),e.useEffect(()=>{M6.current=Q1},[Q1]),e.useEffect(()=>{if(s1!=="streaming"&&s1!=="submitted")return;let m=setInterval(()=>{if(!qE({lastActivityAt:y$.current,now:Date.now(),stallTimeoutMs:I$.current}))return;if($1.current||_0.current||K0.current>=v.current)return;if(!D8(M6.current)){G1({attempt:K0.current,kind:"none",guardTripped:"no-progress"});return}_0.current=!0,K0.current+=1,G1({attempt:K0.current,kind:"retry-error",retryReason:"stall"}),(async()=>{try{await L2(),await M5()}finally{_0.current=!1}})()},15000);return()=>clearInterval(m)},[D8,M5,s1,L2]),e.useEffect(()=>{if(s1!=="ready"||W1)return;if($1.current||q$||T0||o0||P$.current!==null||J0.length>0||I0.length>0||Go(Q1))return;let m=Q1[Q1.length-1];if(!m||m.role!=="assistant")return;if(u.current===m.id)return;u.current=m.id;let G$=BE({messages:Q1,todos:L4,autoContinuesThisTurn:a0.current,limits:C4.current});if(G$.guardTripped){G1({attempt:a0.current,kind:"none",guardTripped:G$.guardTripped});return}if(G$.kind==="none"||!G$.prompt){G1(null);return}a0.current+=1,G1({attempt:a0.current,kind:G$.kind}),t1({text:G$.prompt,metadata:{autoContinue:!0}})},[W1,o0,q$,T0,Q1,J0.length,I0.length,t1,s1,L4]),e.useEffect(()=>{if(!W1?.message||!tG(W1.message))return;if($1.current||J0.length>0||I0.length>0||P.current||_0.current)return;let m=rG(W1.message)?.kind??"network";if(y.current===null)y.current=Date.now();let G$=K0.current+1,b$=tn({attempt:G$,kind:m,elapsedMs:Date.now()-y.current,maxErrorRetries:v.current});if(!b$.retry)return;let O$=b$.delayMs;return G1({attempt:G$,kind:"retry-error",retryReason:m,retryAtMs:Date.now()+O$}),P.current=setTimeout(()=>{if(P.current=null,!D8(M6.current)){G1({attempt:K0.current,kind:"none",guardTripped:"no-progress"});return}K0.current=G$,G1({attempt:G$,kind:"retry-error",retryReason:m}),M5()},O$),()=>{if(P.current)clearTimeout(P.current),P.current=null}},[W1?.message,J0.length,I0.length,D8,M5]);let Qv=e.useCallback((m,G$,b$=[])=>{if(rQ&&Xo(m)){nQ();return}if(J0.length>0){let O$=zo(m);if(O$){if(O$.target==="all")dQ(O$.action);else cQ(O$.action,O$.target);return}r("Tool approval pending. Use approve/deny with optional index or all, e.g. 'approve 1' or 'approve all'.");return}if(I0.length>0){r("A user prompt is waiting for response. Please answer it in the inline prompt.");return}if(r(null),V5(),b$.length>0)t1({parts:[...G$??[],...b$,{type:"text",text:m}]});else t1({text:m,files:G$})},[V5,J0.length,I0.length,rQ,nQ,dQ,cQ,t1]),Wv=e.useCallback((m)=>{let G$=m.trim();if(!G$)return;r(null),V5(),t1({text:G$})},[V5,t1]),ZN=e.useCallback(async()=>{let m=await L0.current();i.current=m.session?.revision??0;let G$=await OE(m.messages);b5.current(VE(G$)),w1([]),e0([]),Q0(null),r(null),$$.current=null,X$.current=-1},[]);k$.current=ZN,e.useEffect(()=>{let m=!1;i.current=0,$$.current=null,X$.current=-1,B$.current=null,M.current=void 0,p$.current=null,_.current=null,Q0(null),r(null),w1([]),e0([]),r0(!0),n0(!0);async function G$(){if(!J){b5.current([]),Q0("Invalid session route."),r0(!1);return}if(H){b5.current([]),r0(!1);return}try{let[b$,O$]=await Promise.all([L0.current(),j.current?j.current():Promise.resolve({interactions:[]})]);i.current=b$.session?.revision??0;let N$=await OE(b$.messages),h0=O$.interactions.map(Do).filter((Z6)=>Z6!==null);if(m)return;let wU=h0.length===0?VE(N$):N$;b5.current(wU),e0(h0)}catch(b$){if(m)return;b5.current([]),w1([]),e0([]),Q0(jV(b$,"Unable to load persisted chat history."))}finally{if(!m)r0(!1)}}return G$(),()=>{m=!0}},[J,Q,H]),e.useEffect(()=>{if(q$)return;if(!J||t$){n0(!1);return}if(B$.current===Q)return;B$.current=Q;let m=!1;return n0(!0),F5().finally(()=>{if(!m)n0(!1)}),()=>{m=!0}},[t$,q$,J,F5,Q]),e.useEffect(()=>{if(B==="plan"||I0.length===0)return;for(let m of I0)O5((async()=>{let G$={answer:LE,source:"custom"};await N5({tool:"request_user_input",toolCallId:m.toolCallId,output:G$}),await t4(m.toolCallId,{status:"answered",response:G$})})());e0([]),r(null)},[N5,t4,B,I0,O5]),e.useEffect(()=>{let m=!0;async function G$(){if(!D){if(m)_4([]);return}try{let b$=await D({sessionId:Q,cwd:z});if(m)_4([...b$])}catch{if(m)_4([])}}return G$(),()=>{m=!1}},[z,D,Q]),e.useEffect(()=>{if(!J)return;if(q$||T0||o0)return;if(!U||_.current===U.trim())return;if(Q1.length>0)return;_.current=U.trim(),t1({text:U.trim()})},[U,o0,q$,T0,J,Q1.length,t1]);let Hv=Ho({messages:Q1,pendingApprovals:J0,pendingUserPrompts:I0}),jN=s1==="submitted"||s1==="streaming"||Hv,zv=q$||T0||o0||jN,Dv=Boolean(W1?.message&&tG(W1.message)&&K0.current<v.current),qv=J0.some((m)=>m.approvalId===tU),Bv=t$??p??(W1?.message&&!Dv&&!qv?Jo(W1.message):null);return{abortActiveRun:e.useCallback(async()=>{if(P.current)clearTimeout(P.current),P.current=null;let m=$$.current;if(m){let G$=$.replace(/\/turns(?:\?.*)?$/,`/runs/${encodeURIComponent(m)}/abort`);try{let b$=await ZV(t.current);await(Q$.current??globalThis.fetch)(G$,{method:"POST",...b$?{headers:b$}:{}})}catch{}}await L2();try{if(m)await F5();await q8()}catch{}},[$,F5,L2,q8]),autoContinueState:a4,errorMessage:Bv,isHistoryLoading:q$,isLoading:zv,isStreaming:jN,messages:Q1,pendingApprovals:J0,pendingUserPrompts:I0,canRetryRecoverableResponse:rQ,refreshPersistedMessages:ZN,todos:L4,retryRecoverableResponse:nQ,resolveAllToolApprovals:dQ,resolveToolApproval:cQ,sessionId:Q,status:s1,respondToUserPrompt:Gv,sendDirectMessage:Wv,submitInput:Qv,isSessionIdValid:J}}var D0=M0(f0(),1);var sU=[{id:"copy",command:"/copy",label:"Copy",description:"Copy the last reply, its code blocks, or the conversation",category:"conversation",availability:"session",argumentHint:"[last|code|all]",aliases:["/cp"],searchTerms:["clipboard","reply","code","transcript"]},{id:"export",command:"/export",label:"Export session",description:"Download the current chat session as Markdown",category:"conversation",availability:"session",argumentHint:null,aliases:["/save"],searchTerms:["download","markdown","transcript"]},{id:"compact",command:"/compact",label:"Compact context",description:"Summarize older messages to free context window space",category:"conversation",availability:"session",argumentHint:null,aliases:["/summarize"],searchTerms:["context","tokens","shorten"]},{id:"context",command:"/context",label:"Inspect context",description:"Show the provider request budget and compaction savings",category:"conversation",availability:"session",argumentHint:null,aliases:["/ctx"],searchTerms:["tokens","budget","prompt","usage"]},{id:"abort",command:"/abort",label:"Abort active run",description:"Stop the current response and active tool work",category:"conversation",availability:"session",argumentHint:null,aliases:["/cancel","/stop"],searchTerms:["interrupt","run","stream"]},{id:"undo",command:"/undo",label:"Undo last turn",description:"Rewind the latest turn and its file edits",category:"conversation",availability:"session",argumentHint:null,aliases:["/rewind"],searchTerms:["restore","history","files"]},{id:"redo",command:"/redo",label:"Redo last turn",description:"Replay the most recently undone turn and file edits",category:"conversation",availability:"session",argumentHint:null,aliases:["/replay"],searchTerms:["restore","history","files"]},{id:"skills",command:"/skills",label:"List skills",description:"Show skills available to the agent in this workspace",category:"conversation",availability:"session",argumentHint:null,aliases:["/skill"],searchTerms:["agents","instructions","extensions"]},{id:"permission",command:"/permission",label:"Permission mode",description:"Change the permission level used for the next turn",category:"configuration",availability:"always",argumentHint:"[read-only|workspace-write|danger-full-access]",aliases:["/perm"],searchTerms:["approval","access","sandbox","mode"]},{id:"home",command:"/home",label:"Home",description:"Start a new session in the current workspace",category:"navigation",availability:"always",argumentHint:null,aliases:["/new"],searchTerms:["start","workspace","project"]},{id:"status",command:"/status",label:"Status",description:"Show server, model, database, session, and tool status",category:"diagnostics",availability:"always",argumentHint:null,aliases:[],searchTerms:["health","server","database","tools"]},{id:"doctor",command:"/doctor",label:"Doctor",description:"Run operational health checks",category:"diagnostics",availability:"always",argumentHint:null,aliases:["/health"],searchTerms:["diagnose","checks","troubleshoot"]},{id:"permissions",command:"/permissions",label:"Permissions",description:"Inspect permission rules, allowed tools, and sandbox guards",category:"diagnostics",availability:"always",argumentHint:null,aliases:["/permission-info"],searchTerms:["rules","access","sandbox","tools"]},{id:"sessions",command:"/sessions",label:"Sessions",description:"Browse saved conversations",category:"navigation",availability:"always",argumentHint:null,aliases:["/chats"],searchTerms:["history","conversations","saved"]},{id:"tools",command:"/tools",label:"Tools",description:"List available tools and their permission requirements",category:"diagnostics",availability:"always",argumentHint:null,aliases:[],searchTerms:["schemas","capabilities","permissions"]},{id:"config",command:"/config",label:"Config",description:"Show effective configuration without secrets",category:"configuration",availability:"always",argumentHint:null,aliases:["/settings"],searchTerms:["configuration","preferences","effective"]},{id:"connect",command:"/connect",label:"Provider setup",description:"Check connection and show trusted terminal setup instructions",category:"configuration",availability:"always",argumentHint:null,aliases:["/provider"],searchTerms:["setup","credential","api key","authentication"]},{id:"model",command:"/model",label:"Switch model",description:"Inspect models or switch by exact model ID",category:"configuration",availability:"always",argumentHint:"[model-id]",aliases:["/models","/switch-model"],searchTerms:["select","provider","catalog"]},{id:"model-info",command:"/model-info",label:"Model info",description:"Show the provider, model, base URL, and credential hints",category:"diagnostics",availability:"always",argumentHint:null,aliases:["/current-model"],searchTerms:["provider","base url","credential","api key"]},{id:"latest",command:"/latest",label:"Resume latest",description:"Open the most recently updated saved session",category:"navigation",availability:"always",argumentHint:null,aliases:["/resume"],searchTerms:["recent","session","continue"]},{id:"help",command:"/help",label:"Command help",description:"List commands or explain one command",category:"navigation",availability:"always",argumentHint:"[command]",aliases:["/commands"],searchTerms:["shortcuts","usage","documentation"]}];function FE($){let U=$.trim().toLowerCase();return U.startsWith("/")?U:`/${U}`}function qo($){return[$.command,...$.aliases]}function sG($){let U=FE($);return sU.find((J)=>qo(J).some((Y)=>Y===U))??null}function IV($,U){return $.availability==="always"||U}function bE($){return $.argumentHint?`${$.command} ${$.argumentHint}`:$.command}function Bo($,U){let J=$.command.slice(1),Y=$.aliases.map((Q)=>Q.slice(1)),X=$.label.toLowerCase(),w=X.split(/\s+/),G=$.searchTerms.map((Q)=>Q.toLowerCase());if(J===U)return 0;if(J.startsWith(U))return 1;if(Y.some((Q)=>Q===U))return 2;if(Y.some((Q)=>Q.startsWith(U)))return 3;if(w.some((Q)=>Q.startsWith(U)))return 4;if(G.some((Q)=>Q.startsWith(U)))return 5;if(X.includes(U))return 6;return null}function Lo($){let U=$.trim().toLowerCase().replace(/^\//,""),J=U.search(/\s/);if(J===-1)return{query:U,hasArgumentBoundary:!1};return{query:U.slice(0,J),hasArgumentBoundary:!0}}function RV($="",U={}){let{hasSession:J=!0,includeUnavailable:Y=!1,limit:X=sU.length}=U,{query:w,hasArgumentBoundary:G}=Lo($),Q=Number.isFinite(X)?Math.max(0,Math.floor(X)):sU.length,H=sU.filter((z)=>Y||IV(z,J));if(!w)return H.slice(0,Q);if(G){let z=sG(w);return z&&(Y||IV(z,J))?[z].slice(0,Q):[]}return H.map((z,D)=>({command:z,index:D,score:Bo(z,w)})).filter((z)=>z.score!==null).sort((z,D)=>z.score-D.score||z.index-D.index).slice(0,Q).map(({command:z})=>z)}function ME($,U={}){let J=$.trim();if(!J.startsWith("/"))return{kind:"plain-text",input:$};let Y=/^\/([^\s]+)(?:\s+([\s\S]*))?$/.exec(J);if(!Y)return{kind:"incomplete",input:$};let X=FE(Y[1]??""),w=(Y[2]??"").trim(),G=sG(X),Q=U.hasSession??!0;if(G)return{kind:"command",input:$,command:G,invokedAs:X,args:w,available:IV(G,Q)};return{kind:"unknown",input:$,invokedAs:X,args:w,suggestions:RV(X,{hasSession:Q,limit:5})}}function b0($,U,J="info"){return{title:$,detail:U,tone:J}}function B4($,U){return b0($,U,"error")}function d4($){if($<1000)return String($);return`${($/1000).toFixed($>=1e4?0:1)}k`}function jE($){return $.parts.filter((U)=>U.type==="text").map((U)=>U.text).join(`
|
|
101
101
|
`).trim()}function ZE($){for(let U=$.length-1;U>=0;U-=1){let J=$[U];if(J?.role!=="assistant")continue;let Y=jE(J);if(Y)return Y}return null}function _o($){return Array.from($.matchAll(/```[^\n]*\n([\s\S]*?)```/g),(U)=>(U[1]??"").replace(/\n$/,"")).filter(Boolean)}function Ko($){return $.filter((U)=>U.role==="user"||U.role==="assistant").map((U)=>{let J=jE(U);if(!J)return null;return`## ${U.role==="user"?"You":"Lightcode"}
|
|
102
102
|
|
package/assets/web/index.html
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
<meta name="theme-color" content="#0B0B0C" />
|
|
8
8
|
<title>Lightcode</title>
|
|
9
9
|
|
|
10
|
-
<link rel="stylesheet" crossorigin href="./index-5dh9c5av.css"><script type="module" crossorigin src="./index-
|
|
10
|
+
<link rel="stylesheet" crossorigin href="./index-5dh9c5av.css"><script type="module" crossorigin src="./index-89rgdkry.js"></script></head>
|
|
11
11
|
<body>
|
|
12
12
|
<!--
|
|
13
13
|
THESIS: One local coding workspace shared with the CLI; this surface rejects dashboard-card clutter and keeps the project conversation central.
|
package/cli.js
CHANGED
|
@@ -124,7 +124,7 @@ var init_logger = __esm(() => {
|
|
|
124
124
|
});
|
|
125
125
|
|
|
126
126
|
// packages/shared/src/version.ts
|
|
127
|
-
var lightcodeVersion = "0.18.
|
|
127
|
+
var lightcodeVersion = "0.18.5";
|
|
128
128
|
|
|
129
129
|
// packages/shared/src/index.ts
|
|
130
130
|
var productName = "Lightcode";
|
|
@@ -2485,7 +2485,7 @@ var init_schema8 = __esm(() => {
|
|
|
2485
2485
|
|
|
2486
2486
|
// packages/ai/src/read-file/schema.ts
|
|
2487
2487
|
import { z as z18 } from "zod";
|
|
2488
|
-
var readFileDescription = "Read file content from the working directory.
|
|
2488
|
+
var readFileDescription = "Read file content from the working directory. Each call returns about 6,000 characters (roughly 150 lines); longer content is truncated head+tail. Small files: read them whole. Long files: find the spot with grep first, then read a startLine/endLine range of about 100-150 lines around it.", readFileInputSchema, readFileProviderInputSchema, readFileOutputSchema;
|
|
2489
2489
|
var init_schema9 = __esm(() => {
|
|
2490
2490
|
init_base_schemas();
|
|
2491
2491
|
readFileInputSchema = z18.object({
|
|
@@ -3608,7 +3608,7 @@ ${environmentContext.trim()}` : "");
|
|
|
3608
3608
|
var cwdPromptPlaceholder = "{cwd}", defaultCodingAgentSystemPrompt, toolCallingDisciplineAddendum;
|
|
3609
3609
|
var init_coding_agent_prompt = __esm(() => {
|
|
3610
3610
|
init_coding_agent_modes();
|
|
3611
|
-
defaultCodingAgentSystemPrompt = "You are a coding agent working inside the user's project at this working directory: {cwd}. " + 'You can already see the project \u2014 proactively read it. When the user asks you to review, explain, or work on "my code"/"this", inspect the working directory yourself with list_files, glob_search, grep, and read_file; NEVER ask the user to paste or share code that lives in this directory \u2014 open it. ' + "Use tools for filesystem and codebase tasks instead of guessing, and only interact with files under the working directory. " + "Prefer dedicated tools \u2014 glob_search for paths, grep for text search, structured git tools for repository inspection \u2014 and bash only when those are not enough. " + "Check the available skill descriptions for every task. When a skill is explicitly named or clearly matches the task, load it with the skill tool before acting and follow its instructions within the user's scope and tool permissions. Skill files may be installed outside the workspace; use the skill tool to read their relative supporting resources. Never claim to have used a skill you have not loaded. " + `Inspect context before risky operations. Progress notes: before a major tool action you may emit ONE short note (one sentence, ~15 words) saying what you are about to do. After a tool returns, mention a finding only if it changes your plan, and state it as fact grounded in what the tool actually returned \u2014 cite the file/line/symbol. NEVER claim you found, changed, or fixed something before a tool result confirms it. Skip notes for routine reads, and do not restate the todo list in prose.
|
|
3611
|
+
defaultCodingAgentSystemPrompt = "You are a coding agent working inside the user's project at this working directory: {cwd}. " + 'You can already see the project \u2014 proactively read it. When the user asks you to review, explain, or work on "my code"/"this", inspect the working directory yourself with list_files, glob_search, grep, and read_file; NEVER ask the user to paste or share code that lives in this directory \u2014 open it. ' + "Use tools for filesystem and codebase tasks instead of guessing, and only interact with files under the working directory. " + "Prefer dedicated tools \u2014 glob_search for paths, grep for text search, structured git tools for repository inspection \u2014 and bash only when those are not enough. " + "Gather context efficiently \u2014 every tool round trip costs the user seconds. Locate before you read: use grep or glob_search to find the relevant files and line numbers, then read those regions in generous ranges (about 100-150 lines) instead of many small slices or re-reading the same file. When several reads or searches do not depend on each other, request them together in one step. Skip generated output (dist/, build/, minified bundles, node_modules) unless the task is about it. Stop exploring once you have enough evidence to act or answer. " + "Check the available skill descriptions for every task. When a skill is explicitly named or clearly matches the task, load it with the skill tool before acting and follow its instructions within the user's scope and tool permissions. Skill files may be installed outside the workspace; use the skill tool to read their relative supporting resources. Never claim to have used a skill you have not loaded. " + `Inspect context before risky operations. Progress notes: before a major tool action you may emit ONE short note (one sentence, ~15 words) saying what you are about to do. After a tool returns, mention a finding only if it changes your plan, and state it as fact grounded in what the tool actually returned \u2014 cite the file/line/symbol. NEVER claim you found, changed, or fixed something before a tool result confirms it. Skip notes for routine reads, and do not restate the todo list in prose.
|
|
3612
3612
|
|
|
3613
3613
|
` + `Task list discipline \u2014 use the todo_write tool to keep a visible, evolving checklist:
|
|
3614
3614
|
` + `- Create the list FIRST. For any task with roughly three or more distinct steps, or any multi-file or multi-stage work, call todo_write as your very first action \u2014 before reading or editing \u2014 with every step listed and all of them set to pending.
|
|
@@ -3623,7 +3623,7 @@ var init_coding_agent_prompt = __esm(() => {
|
|
|
3623
3623
|
` + `When the task is complete, end with a short summary (a few lines) grounded in the todos you actually completed and the real file diffs \u2014 name the files you edited, do not list steps you did not verify, and do not repeat the todo card verbatim. If anything is incomplete or you are blocked, say so plainly.
|
|
3624
3624
|
|
|
3625
3625
|
` + "Long-running processes (dev servers, watchers): never run them as plain foreground bash \u2014 the bash tool enforces a timeout and will kill them. Start them detached with output redirected to a log " + '(Windows: start /B cmd /c "npm run dev > dev.log 2>&1"; Unix: nohup npm run dev > dev.log 2>&1 &), then read the log to confirm startup and the actual port (do not assume the default). ' + "Never kill processes or free ports you did not open yourself.";
|
|
3626
|
-
toolCallingDisciplineAddendum = "Invoke tools only through the function-calling interface. " + "Never write tool calls as XML or plain text such as <tool_call>, <function_call>, <invoke>, or bare JSON in your message. " + "Tool arguments must be valid JSON matching the tool's schema. " + "
|
|
3626
|
+
toolCallingDisciplineAddendum = "Invoke tools only through the function-calling interface. " + "Never write tool calls as XML or plain text such as <tool_call>, <function_call>, <invoke>, or bare JSON in your message. " + "Tool arguments must be valid JSON matching the tool's schema. " + "You may request several independent tool calls in one response; wait for their results before making calls that depend on them.";
|
|
3627
3627
|
});
|
|
3628
3628
|
|
|
3629
3629
|
// packages/ai/src/common/coerce-tool-input.ts
|
|
@@ -7688,12 +7688,19 @@ async function artifactizeLargeToolOutputs(messages, options = {}) {
|
|
|
7688
7688
|
if (previewCharacters < MIN_TOOL_OUTPUT_ARTIFACT_PREVIEW_CHARACTERS) {
|
|
7689
7689
|
throw new RangeError(`Tool-output artifact previews must allow at least ${MIN_TOOL_OUTPUT_ARTIFACT_PREVIEW_CHARACTERS} characters.`);
|
|
7690
7690
|
}
|
|
7691
|
+
const currentTurnThreshold = Math.max(0, Math.floor(options.currentTurnThresholdCharacters ?? thresholdCharacters));
|
|
7692
|
+
let currentTurnStart = 0;
|
|
7693
|
+
messages.forEach((message, index) => {
|
|
7694
|
+
if (message.role === "user")
|
|
7695
|
+
currentTurnStart = index + 1;
|
|
7696
|
+
});
|
|
7691
7697
|
const uniqueArtifacts = new Map;
|
|
7692
7698
|
let artifactizedOutputs = 0;
|
|
7693
7699
|
let savedCharacters = 0;
|
|
7694
7700
|
const providerMessages = [];
|
|
7695
|
-
for (const message of messages) {
|
|
7701
|
+
for (const [index, message] of messages.entries()) {
|
|
7696
7702
|
options.signal?.throwIfAborted();
|
|
7703
|
+
const limit = index >= currentTurnStart ? currentTurnThreshold : thresholdCharacters;
|
|
7697
7704
|
if (!Array.isArray(message.content)) {
|
|
7698
7705
|
providerMessages.push(message);
|
|
7699
7706
|
continue;
|
|
@@ -7707,7 +7714,7 @@ async function artifactizeLargeToolOutputs(messages, options = {}) {
|
|
|
7707
7714
|
}
|
|
7708
7715
|
const output = part.output;
|
|
7709
7716
|
const serialized = serializeToolResultOutput(output);
|
|
7710
|
-
if (serialized.length <=
|
|
7717
|
+
if (serialized.length <= limit) {
|
|
7711
7718
|
providerContent.push(part);
|
|
7712
7719
|
continue;
|
|
7713
7720
|
}
|
|
@@ -7791,7 +7798,7 @@ async function toolOutputArtifactExists(handleOrDigest, dataDir = getLightcodeDa
|
|
|
7791
7798
|
throw error;
|
|
7792
7799
|
}
|
|
7793
7800
|
}
|
|
7794
|
-
var TOOL_OUTPUT_ARTIFACT_HANDLE_PREFIX = "lightcode-artifact://tool-output/sha256/", DEFAULT_TOOL_OUTPUT_ARTIFACT_THRESHOLD_CHARACTERS, DEFAULT_TOOL_OUTPUT_ARTIFACT_PREVIEW_CHARACTERS = 2400, MIN_TOOL_OUTPUT_ARTIFACT_PREVIEW_CHARACTERS = 512, SHA256_PATTERN, ARTIFACT_PREVIEW_MARKER = "[Lightcode tool-output artifact]";
|
|
7801
|
+
var TOOL_OUTPUT_ARTIFACT_HANDLE_PREFIX = "lightcode-artifact://tool-output/sha256/", DEFAULT_TOOL_OUTPUT_ARTIFACT_THRESHOLD_CHARACTERS, DEFAULT_CURRENT_TURN_TOOL_OUTPUT_THRESHOLD_CHARACTERS = 16000, DEFAULT_TOOL_OUTPUT_ARTIFACT_PREVIEW_CHARACTERS = 2400, MIN_TOOL_OUTPUT_ARTIFACT_PREVIEW_CHARACTERS = 512, SHA256_PATTERN, ARTIFACT_PREVIEW_MARKER = "[Lightcode tool-output artifact]";
|
|
7795
7802
|
var init_tool_output_artifacts = __esm(() => {
|
|
7796
7803
|
init_src();
|
|
7797
7804
|
DEFAULT_TOOL_OUTPUT_ARTIFACT_THRESHOLD_CHARACTERS = DEFAULT_TOOL_TEXT_OUTPUT_CHARS;
|
|
@@ -9210,7 +9217,8 @@ function createCodingAgent({
|
|
|
9210
9217
|
originalInputTokens: context.originalInputTokens
|
|
9211
9218
|
});
|
|
9212
9219
|
const artifactized = await artifactizeLargeToolOutputs(messages, {
|
|
9213
|
-
signal: context.assemblyAbortSignal
|
|
9220
|
+
signal: context.assemblyAbortSignal,
|
|
9221
|
+
currentTurnThresholdCharacters: DEFAULT_CURRENT_TURN_TOOL_OUTPUT_THRESHOLD_CHARACTERS
|
|
9214
9222
|
});
|
|
9215
9223
|
const assembled = assembler.assembleModelMessages(artifactized.messages, {
|
|
9216
9224
|
preserveRecentTokens: context.preserveRecentTokens
|
|
@@ -16805,6 +16813,7 @@ __export(exports_runtime, {
|
|
|
16805
16813
|
DEFAULT_PRUNE_QUANTIZE_USER_TURNS: () => DEFAULT_PRUNE_QUANTIZE_USER_TURNS,
|
|
16806
16814
|
DEFAULT_PRUNE_MIN_OUTPUT_CHARS: () => DEFAULT_PRUNE_MIN_OUTPUT_CHARS,
|
|
16807
16815
|
DEFAULT_INPUT_BUDGET_SAFETY_FRACTION: () => DEFAULT_INPUT_BUDGET_SAFETY_FRACTION,
|
|
16816
|
+
DEFAULT_CURRENT_TURN_TOOL_OUTPUT_THRESHOLD_CHARACTERS: () => DEFAULT_CURRENT_TURN_TOOL_OUTPUT_THRESHOLD_CHARACTERS,
|
|
16808
16817
|
DEFAULT_CONTEXT_WINDOW_TOKENS: () => DEFAULT_CONTEXT_WINDOW_TOKENS,
|
|
16809
16818
|
CheckpointConflictError: () => CheckpointConflictError,
|
|
16810
16819
|
ANTHROPIC_TOOL_OPTIONAL_PARAMETER_BUDGET: () => ANTHROPIC_TOOL_OPTIONAL_PARAMETER_BUDGET
|
package/package.json
CHANGED
package/server.js
CHANGED
|
@@ -2002,7 +2002,7 @@ var init_schema8 = __esm(() => {
|
|
|
2002
2002
|
|
|
2003
2003
|
// packages/ai/src/read-file/schema.ts
|
|
2004
2004
|
import { z as z19 } from "zod";
|
|
2005
|
-
var readFileDescription = "Read file content from the working directory.
|
|
2005
|
+
var readFileDescription = "Read file content from the working directory. Each call returns about 6,000 characters (roughly 150 lines); longer content is truncated head+tail. Small files: read them whole. Long files: find the spot with grep first, then read a startLine/endLine range of about 100-150 lines around it.", readFileInputSchema, readFileProviderInputSchema, readFileOutputSchema;
|
|
2006
2006
|
var init_schema9 = __esm(() => {
|
|
2007
2007
|
init_base_schemas();
|
|
2008
2008
|
readFileInputSchema = z19.object({
|
|
@@ -3068,7 +3068,7 @@ ${environmentContext.trim()}` : "");
|
|
|
3068
3068
|
var cwdPromptPlaceholder = "{cwd}", defaultCodingAgentSystemPrompt, toolCallingDisciplineAddendum;
|
|
3069
3069
|
var init_coding_agent_prompt = __esm(() => {
|
|
3070
3070
|
init_coding_agent_modes();
|
|
3071
|
-
defaultCodingAgentSystemPrompt = "You are a coding agent working inside the user's project at this working directory: {cwd}. " + 'You can already see the project \u2014 proactively read it. When the user asks you to review, explain, or work on "my code"/"this", inspect the working directory yourself with list_files, glob_search, grep, and read_file; NEVER ask the user to paste or share code that lives in this directory \u2014 open it. ' + "Use tools for filesystem and codebase tasks instead of guessing, and only interact with files under the working directory. " + "Prefer dedicated tools \u2014 glob_search for paths, grep for text search, structured git tools for repository inspection \u2014 and bash only when those are not enough. " + "Check the available skill descriptions for every task. When a skill is explicitly named or clearly matches the task, load it with the skill tool before acting and follow its instructions within the user's scope and tool permissions. Skill files may be installed outside the workspace; use the skill tool to read their relative supporting resources. Never claim to have used a skill you have not loaded. " + `Inspect context before risky operations. Progress notes: before a major tool action you may emit ONE short note (one sentence, ~15 words) saying what you are about to do. After a tool returns, mention a finding only if it changes your plan, and state it as fact grounded in what the tool actually returned \u2014 cite the file/line/symbol. NEVER claim you found, changed, or fixed something before a tool result confirms it. Skip notes for routine reads, and do not restate the todo list in prose.
|
|
3071
|
+
defaultCodingAgentSystemPrompt = "You are a coding agent working inside the user's project at this working directory: {cwd}. " + 'You can already see the project \u2014 proactively read it. When the user asks you to review, explain, or work on "my code"/"this", inspect the working directory yourself with list_files, glob_search, grep, and read_file; NEVER ask the user to paste or share code that lives in this directory \u2014 open it. ' + "Use tools for filesystem and codebase tasks instead of guessing, and only interact with files under the working directory. " + "Prefer dedicated tools \u2014 glob_search for paths, grep for text search, structured git tools for repository inspection \u2014 and bash only when those are not enough. " + "Gather context efficiently \u2014 every tool round trip costs the user seconds. Locate before you read: use grep or glob_search to find the relevant files and line numbers, then read those regions in generous ranges (about 100-150 lines) instead of many small slices or re-reading the same file. When several reads or searches do not depend on each other, request them together in one step. Skip generated output (dist/, build/, minified bundles, node_modules) unless the task is about it. Stop exploring once you have enough evidence to act or answer. " + "Check the available skill descriptions for every task. When a skill is explicitly named or clearly matches the task, load it with the skill tool before acting and follow its instructions within the user's scope and tool permissions. Skill files may be installed outside the workspace; use the skill tool to read their relative supporting resources. Never claim to have used a skill you have not loaded. " + `Inspect context before risky operations. Progress notes: before a major tool action you may emit ONE short note (one sentence, ~15 words) saying what you are about to do. After a tool returns, mention a finding only if it changes your plan, and state it as fact grounded in what the tool actually returned \u2014 cite the file/line/symbol. NEVER claim you found, changed, or fixed something before a tool result confirms it. Skip notes for routine reads, and do not restate the todo list in prose.
|
|
3072
3072
|
|
|
3073
3073
|
` + `Task list discipline \u2014 use the todo_write tool to keep a visible, evolving checklist:
|
|
3074
3074
|
` + `- Create the list FIRST. For any task with roughly three or more distinct steps, or any multi-file or multi-stage work, call todo_write as your very first action \u2014 before reading or editing \u2014 with every step listed and all of them set to pending.
|
|
@@ -3083,7 +3083,7 @@ var init_coding_agent_prompt = __esm(() => {
|
|
|
3083
3083
|
` + `When the task is complete, end with a short summary (a few lines) grounded in the todos you actually completed and the real file diffs \u2014 name the files you edited, do not list steps you did not verify, and do not repeat the todo card verbatim. If anything is incomplete or you are blocked, say so plainly.
|
|
3084
3084
|
|
|
3085
3085
|
` + "Long-running processes (dev servers, watchers): never run them as plain foreground bash \u2014 the bash tool enforces a timeout and will kill them. Start them detached with output redirected to a log " + '(Windows: start /B cmd /c "npm run dev > dev.log 2>&1"; Unix: nohup npm run dev > dev.log 2>&1 &), then read the log to confirm startup and the actual port (do not assume the default). ' + "Never kill processes or free ports you did not open yourself.";
|
|
3086
|
-
toolCallingDisciplineAddendum = "Invoke tools only through the function-calling interface. " + "Never write tool calls as XML or plain text such as <tool_call>, <function_call>, <invoke>, or bare JSON in your message. " + "Tool arguments must be valid JSON matching the tool's schema. " + "
|
|
3086
|
+
toolCallingDisciplineAddendum = "Invoke tools only through the function-calling interface. " + "Never write tool calls as XML or plain text such as <tool_call>, <function_call>, <invoke>, or bare JSON in your message. " + "Tool arguments must be valid JSON matching the tool's schema. " + "You may request several independent tool calls in one response; wait for their results before making calls that depend on them.";
|
|
3087
3087
|
});
|
|
3088
3088
|
|
|
3089
3089
|
// packages/ai/src/common/coerce-tool-input.ts
|
|
@@ -7080,12 +7080,19 @@ async function artifactizeLargeToolOutputs(messages, options = {}) {
|
|
|
7080
7080
|
if (previewCharacters < MIN_TOOL_OUTPUT_ARTIFACT_PREVIEW_CHARACTERS) {
|
|
7081
7081
|
throw new RangeError(`Tool-output artifact previews must allow at least ${MIN_TOOL_OUTPUT_ARTIFACT_PREVIEW_CHARACTERS} characters.`);
|
|
7082
7082
|
}
|
|
7083
|
+
const currentTurnThreshold = Math.max(0, Math.floor(options.currentTurnThresholdCharacters ?? thresholdCharacters));
|
|
7084
|
+
let currentTurnStart = 0;
|
|
7085
|
+
messages.forEach((message, index) => {
|
|
7086
|
+
if (message.role === "user")
|
|
7087
|
+
currentTurnStart = index + 1;
|
|
7088
|
+
});
|
|
7083
7089
|
const uniqueArtifacts = new Map;
|
|
7084
7090
|
let artifactizedOutputs = 0;
|
|
7085
7091
|
let savedCharacters = 0;
|
|
7086
7092
|
const providerMessages = [];
|
|
7087
|
-
for (const message of messages) {
|
|
7093
|
+
for (const [index, message] of messages.entries()) {
|
|
7088
7094
|
options.signal?.throwIfAborted();
|
|
7095
|
+
const limit = index >= currentTurnStart ? currentTurnThreshold : thresholdCharacters;
|
|
7089
7096
|
if (!Array.isArray(message.content)) {
|
|
7090
7097
|
providerMessages.push(message);
|
|
7091
7098
|
continue;
|
|
@@ -7099,7 +7106,7 @@ async function artifactizeLargeToolOutputs(messages, options = {}) {
|
|
|
7099
7106
|
}
|
|
7100
7107
|
const output = part.output;
|
|
7101
7108
|
const serialized = serializeToolResultOutput(output);
|
|
7102
|
-
if (serialized.length <=
|
|
7109
|
+
if (serialized.length <= limit) {
|
|
7103
7110
|
providerContent.push(part);
|
|
7104
7111
|
continue;
|
|
7105
7112
|
}
|
|
@@ -7131,7 +7138,7 @@ async function artifactizeLargeToolOutputs(messages, options = {}) {
|
|
|
7131
7138
|
savedCharacters
|
|
7132
7139
|
};
|
|
7133
7140
|
}
|
|
7134
|
-
var TOOL_OUTPUT_ARTIFACT_HANDLE_PREFIX = "lightcode-artifact://tool-output/sha256/", DEFAULT_TOOL_OUTPUT_ARTIFACT_THRESHOLD_CHARACTERS, DEFAULT_TOOL_OUTPUT_ARTIFACT_PREVIEW_CHARACTERS = 2400, MIN_TOOL_OUTPUT_ARTIFACT_PREVIEW_CHARACTERS = 512, SHA256_PATTERN, ARTIFACT_PREVIEW_MARKER = "[Lightcode tool-output artifact]";
|
|
7141
|
+
var TOOL_OUTPUT_ARTIFACT_HANDLE_PREFIX = "lightcode-artifact://tool-output/sha256/", DEFAULT_TOOL_OUTPUT_ARTIFACT_THRESHOLD_CHARACTERS, DEFAULT_CURRENT_TURN_TOOL_OUTPUT_THRESHOLD_CHARACTERS = 16000, DEFAULT_TOOL_OUTPUT_ARTIFACT_PREVIEW_CHARACTERS = 2400, MIN_TOOL_OUTPUT_ARTIFACT_PREVIEW_CHARACTERS = 512, SHA256_PATTERN, ARTIFACT_PREVIEW_MARKER = "[Lightcode tool-output artifact]";
|
|
7135
7142
|
var init_tool_output_artifacts = __esm(() => {
|
|
7136
7143
|
init_src();
|
|
7137
7144
|
DEFAULT_TOOL_OUTPUT_ARTIFACT_THRESHOLD_CHARACTERS = DEFAULT_TOOL_TEXT_OUTPUT_CHARS;
|
|
@@ -8617,7 +8624,8 @@ function createCodingAgent({
|
|
|
8617
8624
|
originalInputTokens: context.originalInputTokens
|
|
8618
8625
|
});
|
|
8619
8626
|
const artifactized = await artifactizeLargeToolOutputs(messages, {
|
|
8620
|
-
signal: context.assemblyAbortSignal
|
|
8627
|
+
signal: context.assemblyAbortSignal,
|
|
8628
|
+
currentTurnThresholdCharacters: DEFAULT_CURRENT_TURN_TOOL_OUTPUT_THRESHOLD_CHARACTERS
|
|
8621
8629
|
});
|
|
8622
8630
|
const assembled = assembler.assembleModelMessages(artifactized.messages, {
|
|
8623
8631
|
preserveRecentTokens: context.preserveRecentTokens
|
|
@@ -14621,7 +14629,8 @@ async function runSubagentToolTask(input, context2, deps) {
|
|
|
14621
14629
|
abortSignal: context2.abortSignal,
|
|
14622
14630
|
prepareStep: async ({ messages }) => {
|
|
14623
14631
|
const artifactized = await artifactizeLargeToolOutputs(messages, {
|
|
14624
|
-
signal: context2.abortSignal
|
|
14632
|
+
signal: context2.abortSignal,
|
|
14633
|
+
currentTurnThresholdCharacters: DEFAULT_CURRENT_TURN_TOOL_OUTPUT_THRESHOLD_CHARACTERS
|
|
14625
14634
|
});
|
|
14626
14635
|
const turn = assembler.assembleModelMessages(artifactized.messages, {
|
|
14627
14636
|
preserveRecentTokens
|