@maincode-ai/matilda-code 0.22.3-nightly.20261110.cb1234773 → 0.22.4
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/chunks/{agent-7LLN72GU.js → agent-MOVDRLTH.js} +1 -1
- package/chunks/{agent-headless-APBRBFN3.js → agent-headless-OIL2DH2J.js} +1 -1
- package/chunks/{chunk-HK3QQSM7.js → chunk-5372BQ2X.js} +3 -3
- package/chunks/{chunk-JZMGEGR6.js → chunk-5MS3VZDH.js} +1 -1
- package/chunks/{chunk-NO6BFSGG.js → chunk-EC2IF7DG.js} +1 -1
- package/chunks/{chunk-N3AQRPV5.js → chunk-J6YVJMKL.js} +31 -31
- package/chunks/{chunk-BEP4F3GO.js → chunk-LPPYEBZM.js} +475 -474
- package/chunks/{chunk-GDRS4OWI.js → chunk-LQ3VS2EV.js} +51 -46
- package/chunks/{chunk-TVNM3PQ7.js → chunk-MUYVUUSO.js} +1 -1
- package/chunks/chunk-RR3LDVGW.js +8 -0
- package/chunks/{chunk-DERMLVT6.js → chunk-RT2VU2QV.js} +1 -1
- package/chunks/{computer-use-RIDTFLYZ.js → computer-use-MBKJPMWZ.js} +4 -4
- package/chunks/{cron-create-T5QOBRRU.js → cron-create-K6DCVCY3.js} +1 -1
- package/chunks/{cron-delete-JXDOHSJF.js → cron-delete-XNCDKPVV.js} +1 -1
- package/chunks/{cron-list-ZQ76A2FW.js → cron-list-3IPROBTC.js} +1 -1
- package/chunks/{edit-LDTYXEVU.js → edit-72ASKQO7.js} +17 -17
- package/chunks/{enter-worktree-FOFQXTPW.js → enter-worktree-YYH4RD3G.js} +1 -1
- package/chunks/{enterPlanMode-2GHHILQY.js → enterPlanMode-SKK26RKS.js} +1 -1
- package/chunks/{exit-worktree-OK7AD7DC.js → exit-worktree-5K5Y2UR4.js} +1 -1
- package/chunks/{exitPlanMode-EANVOWTX.js → exitPlanMode-XDH6WKKD.js} +1 -1
- package/chunks/{glob-VZD7TOML.js → glob-3PF3E5R2.js} +1 -1
- package/chunks/{goal-tools-REBEAKVP.js → goal-tools-4SWS6CGW.js} +1 -1
- package/chunks/{grep-JPEHWEM3.js → grep-RQLOBTPU.js} +3 -3
- package/chunks/monitor-ZS5E3EAX.js +33 -0
- package/chunks/notebook-edit-JMRHVFA4.js +17 -0
- package/chunks/{openaiContentGenerator-QLDLWN4P.js → openaiContentGenerator-PRVYEJIU.js} +5 -5
- package/chunks/{read-file-4M76GCWT.js → read-file-GWUQN2ZM.js} +1 -1
- package/chunks/{ripGrep-LF2E2V6N.js → ripGrep-CWJYHBK6.js} +1 -1
- package/chunks/{scheduler-G4LEIBL4.js → scheduler-LPJ66QW3.js} +1 -1
- package/chunks/{shell-NUMSSUOV.js → shell-AXB4E537.js} +1 -1
- package/chunks/{skill-IVESDHGG.js → skill-7PMKFRET.js} +1 -1
- package/chunks/{symbol-search-BLJAKP7C.js → symbol-search-NHVD4D3O.js} +1 -1
- package/chunks/{team-create-QQD472XN.js → team-create-3S7UXATW.js} +1 -1
- package/chunks/{tool-search-LGTQYGTC.js → tool-search-ECQHNTSM.js} +1 -1
- package/chunks/{web-fetch-5X37JMDH.js → web-fetch-2BMJPIBC.js} +1 -1
- package/chunks/{web-search-62YZTP3D.js → web-search-CHJGDUDM.js} +1 -1
- package/chunks/{workflow-OT4I6TMY.js → workflow-H5E25IZN.js} +2 -2
- package/chunks/write-file-UPXM654K.js +15 -0
- package/cli.js +419 -419
- package/package.json +2 -2
- package/chunks/chunk-VBZS7ARJ.js +0 -8
- package/chunks/monitor-5WDGSYNZ.js +0 -33
- package/chunks/notebook-edit-W42S562V.js +0 -17
- package/chunks/write-file-GMIHG7AP.js +0 -15
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{Ka as l,La as u,c as d,ra as h,sa as s}from"./chunk-LPPYEBZM.js";import{l as p}from"./chunk-M5ABGGE7.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();import g from"node:path";function O(e,n){let o=e.getChannel?.()==="desktop";if((h()??e.getApprovalMode())!=="bogan"||!(o||e.getCommandSandbox()))return null;let t=g.resolve(n),i=e.getCommandSandbox()?s(e)?.unresolved?.[0]:void 0;if(i)return{message:`Refusing a write in BOGAN mode: ${t}. Git could not say where hooks run from in ${i}, so the sandbox lets nothing write until it can. Ask the user to check that git works there, or to turn the sandbox off.`,type:"permission_denied"};if(e.getCommandSandbox()&&(u(t)||k(e,t)))return{message:`Refusing a write to a protected path in BOGAN mode: ${t}. What it holds runs later with no prompt, or configures Matilda: git's hooks and config, hook managers, editor and dev container settings, shell startup files, and Matilda's own settings, rules, commands, agents, skills and hooks. Ask the user to make this change, to switch to a mode where they approve it, or to turn the sandbox off.`,type:"permission_denied"};let m=e.getProjectRoot?.()??e.getTargetDir();if(p(t,m))return null;let r=e.getWorkspaceContext?.();if(!r||(typeof r.isPathWithinWorkspaceFresh=="function"?r.isPathWithinWorkspaceFresh(t):r.isPathWithinWorkspace(t)))return null;let f=r.getDirectories?.()??[e.getTargetDir()],c=o?"Approve the folder from Matilda Desktop, then retry the write.":"Add the folder with --include-directories or /directory add. For intentional external writes, turn the sandbox off (security.sandbox.enabled) or use a non-BOGAN approval mode.";return{message:`Refusing out-of-workspace write in BOGAN mode: ${t}. Workspace root(s): ${f.join(", ")}. This blocks path typos (e.g. writing under $HOME when the project is elsewhere). `+c,type:"path_not_in_workspace"}}function k(e,n){let o=s(e);if(!o)return!1;let t=l(n);return t!==void 0&&d(o,t)}export{O as a};
|
|
4
|
+
/**
|
|
5
|
+
* @license
|
|
6
|
+
* Copyright 2025 Matilda Team
|
|
7
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
8
|
+
*/
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as Pn}from"./chunk-
|
|
3
|
+
import{a as Pn}from"./chunk-5MS3VZDH.js";import{b as An}from"./chunk-V6UPUMP3.js";import{P as St,R as vn,Wa as Ct,Xa as In,Ya as ze,Za as kt,a as mn,ab as Qe,eb as Ze,gb as xn,ha as En,hb as wn,ia as Sn,kb as et,r as hn,ua as Cn,va as kn,w as yn}from"./chunk-J6YVJMKL.js";import{Na as vt,Tb as Et,mb as Rn,qa as Rt}from"./chunk-LQ3VS2EV.js";import{a as _n}from"./chunk-QKAKC34Q.js";import{g as me}from"./chunk-3EQIOCSJ.js";import{e as Ue,ea as H,f as Ye,pa as Tn,qa as Gn,ra as ce,ua as bn}from"./chunk-4SDFTVQW.js";import{b as h}from"./chunk-GZPNIYVZ.js";h();import{AsyncLocalStorage as On}from"node:async_hooks";var Le=new On,Fe=new On;function is(e,t,n){return e?Le.run(e,()=>n?Fe.run(r=>n.billSpend(e.goalId,r),t):t()):t()}h();function Nn(e){return`The Goal spent its autonomous token budget (${e.toLocaleString("en-US")} tokens). Resume the Goal to authorize another budget window, or clear it.`}function De(e){return e.tokenBudget!==void 0&&e.tokensUsed>=e.tokenBudget}function Bn(e){return`The Goal ran its Goal-turn budget (${e.toLocaleString("en-US")} ${e===1?"turn":"turns"}). Resume the Goal to authorize another window of turns, or clear it.`}function tt(e){return e.turnBudget!==void 0&&e.turnCount>=e.turnBudget}function dr(e){let t=e/6e4;if(t>=1){let r=Math.round(t);return`${r.toLocaleString("en-US")} ${r===1?"minute":"minutes"}`}let n=Math.max(1,Math.round(e/1e3));return`${n.toLocaleString("en-US")} ${n===1?"second":"seconds"}`}function Un(e){return`The Goal ran its active-time budget (${dr(e)}). Resume the Goal to authorize another window of time, or clear it.`}function nt(e,t){return e.activeTimeBudgetMs!==void 0&&t>=e.activeTimeBudgetMs}function It(e){return e==="token_budget"||e==="turn_budget"||e==="time_budget"}var us=`<system-reminder>
|
|
4
4
|
The Goal is paused. Do not continue its objective unless the user resumes it. Treat this message as ordinary conversation.
|
|
5
5
|
</system-reminder>`;function Ln(){return{v:2,goal:null,activity:"idle"}}function ds(e){return e.goal!==null&&(e.goal.status==="active"||e.activity==="running")}function Fn(e){return e.status==="blocked"&&e.blockerKind!=="authority"&&e.blockerKind!=="external"&&e.blockerKind!=="infeasible"}var Dn="The objective cannot be satisfied as written; edit or replace the Goal with an objective the evidence allows before resuming it.";function jn(e){return e.trim()?[...e].length>8e3?"Goal proposal reason exceeds 8000 characters":new TextEncoder().encode(e).byteLength>16e3?"Goal proposal reason exceeds 16000 UTF-8 bytes":null:"Goal proposal reason must not be empty"}var Mn=500;var ls="Interrupted by the user. Run /goal resume to continue.",cs="Paused with /goal pause.",fs="Paused while this computer slept. Run /goal resume to continue.",ps="The session token limit was exceeded before the model request. Start a new session or increase sessionTokenLimit in settings.json before resuming the Goal.",gs="The headless run finished before the Goal did. Resume the Goal in a later run.",Vn="The conversation was rewound past where this Goal was set. Resume the Goal to work on it from here.",$n="Three Goal turns in a row recorded nothing to judge and no proposal. Resume the Goal to try again, or edit its objective into one the model can act on and then resume it.";function ot(e){let t=[...e];return t.length<=Mn?e:`${t.slice(0,Mn-1).join("")}\u2026`}function lr(e){let t=e.trim();return ot(t?`The Goal turn could not finish: ${t}. Run /goal resume to continue.`:"The Goal turn could not finish. Run /goal resume to continue.")}function ms(e){return{reason:lr(e),failed:!0}}function Hn(e){let t=e.trim();return ot(t?`The Goal verifier could not judge the turn: ${t}. Run /goal resume to continue.`:"The Goal verifier could not judge the turn. Run /goal resume to continue.")}function Kn(e){return ot(`Two turns in a row ended with the same conditions unmet (${e.join(", ")}). Resume the Goal to try again, or edit its objective first.`)}function hs(e){let t=e.trim();return ot(t?`The headless run stopped at its ${t} budget. Resume the Goal in a later run.`:"The headless run stopped at a budget. Resume the Goal in a later run.")}h();var Gs=e=>{let t=e/1073741824;return e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${t.toFixed(2)} GB`},cr={"<":"\\u003c",">":"\\u003e","&":"\\u0026"},Wn=e=>e.replace(/[<>&]/g,t=>cr[t]);h();import{randomUUID as F}from"node:crypto";h();h();var fr=new Set(["execution_denied","tool_not_registered","invalid_tool_params"]);function xt(e){return e?.status==="error"&&e.errorType!==void 0&&fr.has(e.errorType)}function wt(e,t,n){let{goalContext:r}=e;if(!r)return;let i=bn(e.name).toLowerCase();return i===ce.GET_GOAL||i===ce.UPDATE_GOAL||i===ce.TOOL_SEARCH&&gr(t)?{goalContext:{...r},provenance:"goal_runtime"}:(i===ce.AGENT||i===ce.WORKFLOW)&&!xt(n)?{goalContext:{...r},provenance:"execution_output"}:{goalContext:{...r}}}function pr(e){let t=(e??[]).flatMap(n=>{let r=n.functionResponse?.response?.output;return typeof r=="string"?[r]:[]});return t.length>0?t.join(`
|
|
6
6
|
`):void 0}function gr(e){let n=pr(e)?.match(/^<functions>\n([\s\S]+)\n<\/functions>$/)?.[1];if(!n)return!1;let r=new Set([ce.GET_GOAL,ce.UPDATE_GOAL]);return n.split(`
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{
|
|
3
|
+
import{Fb as D}from"./chunk-LPPYEBZM.js";import{d as C,m as f,o as P}from"./chunk-5372BQ2X.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-EC2IF7DG.js";import"./chunk-R373GBK6.js";import"./chunk-VNSW4TSX.js";import"./chunk-EEPSTT7K.js";import"./chunk-RT2VU2QV.js";import"./chunk-5MS3VZDH.js";import"./chunk-JVQHQDDE.js";import"./chunk-QXSBPCBA.js";import"./chunk-WAZCC4SE.js";import"./chunk-V6UPUMP3.js";import"./chunk-5B2QERWR.js";import"./chunk-MUYVUUSO.js";import"./chunk-7ZODGQO6.js";import"./chunk-GT6MSEK4.js";import"./chunk-J6YVJMKL.js";import"./chunk-LBQNFSZ2.js";import{a as g}from"./chunk-LQ3VS2EV.js";import"./chunk-B7BF33U4.js";import"./chunk-M5ABGGE7.js";import"./chunk-QKAKC34Q.js";import"./chunk-T6MRYRLI.js";import"./chunk-3EQIOCSJ.js";import"./chunk-XPVKH5TC.js";import"./chunk-J6NYCXUR.js";import"./chunk-UM6CLO7D.js";import"./chunk-YUCEPXGG.js";import{ka as k,la as T}from"./chunk-4SDFTVQW.js";import"./chunk-HEJO7OBH.js";import{b as d}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";d();d();d();import{homedir as F}from"node:os";d();import{join as y}from"node:path";import{homedir as w}from"node:os";var _="0.5.2";function M(t=process.platform,e=process.arch,i=_){let r=i;if(t==="darwin")return{extractDir:`cua-driver-rs-${r}-${e==="arm64"?"darwin-arm64":"darwin-x86_64"}`,binaryRelPath:"CuaDriver.app/Contents/MacOS/cua-driver",hasApp:!0};if(t==="linux"){if(e!=="x64")throw new Error(`Computer Use: unsupported Linux arch '${e}' (only x64).`);return{extractDir:".",binaryRelPath:"cua-driver",hasApp:!1}}if(t==="win32")return{extractDir:`cua-driver-rs-${r}-${e==="arm64"?"windows-arm64":"windows-x86_64"}`,binaryRelPath:"cua-driver.exe",hasApp:!1};throw new Error(`Computer Use: unsupported platform '${t}'.`)}var j="MATILDA_COMPUTER_USE_MAX_IMAGE_DIMENSION";function R(t){if(t===void 0||typeof t=="string"&&t.trim()==="")return;let e=typeof t=="number"?t:Number(t);if(!(!Number.isInteger(e)||e<0))return e}function O(t,e=process.env){let i=R(e[j]);return i!==void 0?i:R(t)}function W(t=w()){return y(t,".matilda","computer-use")}function q(t=w(),e=_){return y(W(t),`cua-driver-rs-${e}`)}function l(t=w(),e=process.platform,i=process.arch,r=_){let o=M(e,i,r);return y(q(t,r),o.extractDir,o.binaryRelPath)}var u=class t{static singleton;binary;onProgress;maxImageDimension;client;startPromise;constructor(e){this.binary=e.binary,this.onProgress=e.onProgress??(()=>{}),this.maxImageDimension=e.maxImageDimension}setMaxImageDimension(e){this.maxImageDimension=e}static shared(){return t.singleton||(t.singleton=new t({binary:l(F())})),t.singleton}static setSharedForTest(e){t.singleton=e}isStarted(){return this.client!==void 0}async start(e){if(!this.client)return this.startPromise?this.startPromise:(this.startPromise=this.doStart(e).finally(()=>{this.startPromise=void 0}),this.startPromise)}async doStart(e){let i=e??this.onProgress;i("Starting Computer Use driver...");let r=new C({command:this.binary,args:["mcp"],env:P(f())}),o=new D({name:"matilda-code-computer-use",version:"1.0.0"},{capabilities:{}});await o.connect(r),this.client=o,await this.applyRuntimeConfig(o,i)}async applyRuntimeConfig(e,i){if(this.maxImageDimension!==void 0)try{await e.callTool({name:"set_config",arguments:{max_image_dimension:this.maxImageDimension}})}catch(r){let o=r instanceof Error?r.message:String(r);i(`Computer Use: could not apply max_image_dimension=${this.maxImageDimension} (${o}); using driver default.`)}}async listTools(){if(!this.client)throw new Error("ComputerUseClient not started");return this.client.listTools()}async callTool(e,i){if(!this.client)throw new Error("ComputerUseClient not started");try{return await this.client.callTool({name:e,arguments:i})}catch(r){if(!A(r))throw r;let o=r;for(let s=0;s<3;s++){if(await this.stop(),await this.start(),!this.client)throw new Error("ComputerUseClient reconnect failed");try{return await this.client.callTool({name:e,arguments:i})}catch(n){if(!A(n))throw n;o=n,await new Promise(p=>setTimeout(p,1e3))}}throw o}}async stop(){let e=this.client;if(this.client=void 0,e)try{await e.close()}catch{}}};function A(t){let e=t instanceof Error?t.message:String(t);return/connection closed|not connected|connection refused|daemon transport error|os error 61/i.test(e)}d();var b=["bring_to_front","check_for_update","check_permissions","click","double_click","drag","end_session","get_accessibility_tree","get_agent_cursor_state","get_config","get_cursor_position","get_recording_state","get_screen_size","get_window_state","hotkey","kill_app","launch_app","list_apps","list_windows","move_cursor","page","press_key","replay_trajectory","right_click","scroll","set_agent_cursor_enabled","set_agent_cursor_motion","set_agent_cursor_style","set_config","set_value","start_recording","start_session","stop_recording","type_text","zoom"],m={bring_to_front:{description:'Activate a window so subsequent input tools with `dispatch:"foreground"` land on it without a per-call SetForegroundWindow flash. **Windows-only:** on macOS this tool returns an error pointing to the platform-native `NSRunningApplication.activate` (which the macOS input tools don\'t need because CGEvent.postToPid reaches backgrounded windows). On Linux this tool also stubs out; use `wmctrl -a` or `xdotool windowactivate` if you need explicit activation.',parameterSchema:{additionalProperties:!1,properties:{pid:{type:"integer"},window_id:{type:"integer"}},required:["pid"],type:"object"}},check_for_update:{description:"Check whether a newer cua-driver-rs release is available on GitHub. Returns the current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only \u2014 never installs. Mirror of `cua-driver check-update --json`.",parameterSchema:{additionalProperties:!1,properties:{},type:"object"}},check_permissions:{description:"Report TCC permission status for Accessibility and Screen Recording. By default also raises the system permission dialogs for any missing grants \u2014 Apple's request APIs are no-ops when the grant is already active, so this is safe to call repeatedly. Pass {\"prompt\": false} for a purely read-only status check.\n\nReturns: `accessibility` + `screen_recording` (booleans from the TCC preflight APIs), `screen_recording_capturable` (a live ScreenCaptureKit probe \u2014 if it disagrees with `screen_recording`, the preflight grant belongs to a different process), and `source` (which TCC identity the booleans reflect: the CuaDriver daemon vs the launching terminal/IDE). macOS attributes grants to the responsible process, so a standalone call from a terminal reports the terminal's grants, not the driver's.",parameterSchema:{additionalProperties:!1,properties:{prompt:{description:"Raise the system permission prompts for missing grants. Default true.",type:"boolean"}},type:"object"}},click:{description:`Left-click against a target pid. **Prefer \`element_index\` over pixel coordinates** \u2014 element_index works on backgrounded / minimized / hidden / off-Space windows, surfaces a stable handle that survives rebuilds, and tells you what you're clicking via the cached element's role + label. Reach for \`x, y\` only when the target is a canvas / video / WebGL / custom-drawn surface that doesn't appear in the AX tree.
|
|
4
4
|
|
|
5
5
|
Two addressing modes:
|
|
6
6
|
|
|
@@ -87,13 +87,13 @@ All parameters are optional; omit any you do not want to change.`,parameterSchem
|
|
|
87
87
|
|
|
88
88
|
- **All other elements**: writes AXValue directly (sliders, steppers, date pickers, native text fields that expose settable AXValue).
|
|
89
89
|
|
|
90
|
-
For free-form text entry into web inputs, prefer \`type_text_chars\` which synthesises key events \u2014 AXValue writes are ignored by WebKit.`,parameterSchema:{additionalProperties:!1,properties:{element_index:{type:"integer"},pid:{type:"integer"},session:{description:"Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.",type:"string"},value:{description:"New value. AX will coerce to the element's native type.",type:"string"},window_id:{description:"CGWindowID for the window whose get_window_state produced the element_index.",type:"integer"}},required:["pid","window_id","element_index","value"],type:"object"}},start_recording:{description:"Start trajectory recording. Every subsequent action-tool invocation (click, right_click, scroll, type_text, press_key, hotkey, set_value) writes a turn folder under `output_dir`:\n\n- `app_state.json` \u2014 post-action AX/UIA snapshot for the target pid.\n- `screenshot.png` \u2014 post-action per-window screenshot of the target's frontmost on-screen window.\n- `action.json` \u2014 tool name, full input arguments, result summary, pid, click point (when applicable), ISO-8601 timestamp.\n- `click.png` \u2014 for click-family actions only, `screenshot.png` with a red dot drawn at the click point.\n\nTurn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.\n\n**Video is off by default.** Pass `record_video: true` to also capture the main display to `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of the session. The recording is torn down automatically when the MCP client disconnects.\n\n**macOS uses native ScreenCaptureKit** (in-process SCStream + SCRecordingOutput) so video inherits Cua Driver's own Screen Recording grant \u2014 no extra TCC prompt, no ffmpeg subprocess. Requires macOS 15.0+.\n\n**Windows + Linux use an ffmpeg subprocess** (`gdigrab` / `x11grab` + libx264). Requires ffmpeg on PATH (winget install Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or fails on startup the per-turn capture (screenshots + action.json) still runs and the session's `last_error` field carries the diagnostic.\n\nState persists for the life of the daemon / MCP session; a restart resets to disabled with no on-disk state. Call `stop_recording` to disable + finalize the mp4.",parameterSchema:{additionalProperties:!1,properties:{output_dir:{description:"Absolute or ~-rooted directory where turn folders and (when enabled) the video file are written.",type:"string"},record_video:{description:"Capture the main display to <output_dir>/recording.mp4. Default: false. Set to true to also capture the main display to recording.mp4 (otherwise only the per-turn screenshots + JSON are recorded). On macOS this uses native ScreenCaptureKit (no extra TCC prompt, macOS 15.0+); on Windows + Linux it requires ffmpeg on PATH.",type:"boolean"}},required:["output_dir"],type:"object"}},start_session:{description:"Declare a session \u2014 a named, color-coded identity for THIS agent run. Pass a stable `session` id; the agent cursor, per-session config, and recording all key on it, and it follows the run across any apps/windows. The cursor's color is derived from the id, so distinct runs are visually distinct. A cursor is shown only for a declared session \u2014 call this (or pass `session` on your first action) to opt in. Idempotent: re-calling with the same id just refreshes its idle-TTL. End it with `end_session` (or let the idle-TTL reclaim it). Concurrent runs/subagents each pass their own `session` to get their own cursor.",parameterSchema:{additionalProperties:!0,properties:{session:{description:'Stable session id for this run (e.g. "research-run-1").',type:"string"}},required:["session"],type:"object"}},stop_recording:{description:"Stop trajectory recording. Disables further per-turn capture and, when video was enabled, gracefully terminates the ffmpeg subprocess so the mp4's moov atom is finalized (the file is playable). Calling stop on an already-stopped session is a no-op. The response carries `last_video_path` pointing at the finalized mp4 (when video was on).\n\nA manual `stop_recording` is **unconditional** \u2014 it stops whatever recording is active regardless of which session started it. Ownership-scoped teardown (so one MCP client disconnecting can't stop a recording a later client started) is handled by the daemon's `session_end` lifecycle signal, not by this tool.",parameterSchema:{additionalProperties:!1,properties:{},type:"object"}},type_text:{description:"Insert text into the target pid via `AXSetAttribute(kAXSelectedText)`. Works for standard Cocoa text fields and text views. No keystrokes are synthesized \u2014 special keys (Return / Escape / arrows) go through `press_key` / `hotkey`. For Chromium / Electron inputs that don't implement `kAXSelectedText`, the tool falls back to CGEvent character synthesis automatically.\n\nOptional `element_index` + `window_id` (from the last `get_window_state` snapshot) directs the write to a specific field. Without `element_index`, the write goes to the pid's currently focused element.",parameterSchema:{additionalProperties:!1,properties:{delay_ms:{description:"Milliseconds between characters in the CGEvent fallback path. Default 30. Ignored when the AX path succeeds.",maximum:200,minimum:0,type:"integer"},element_index:{description:"Element index from last get_window_state. Directs the write to a specific field. Requires window_id.",type:"integer"},pid:{description:"Target process ID.",type:"integer"},session:{description:"Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.",type:"string"},text:{description:"Text to insert at the target's cursor.",type:"string"},window_id:{description:"CGWindowID. Required when element_index is used.",type:"integer"}},required:["pid","text"],type:"object"}},zoom:{description:"Capture a cropped JPEG of a window region (x1,y1)\u2013(x2,y2) in screenshot pixel coordinates, with 20% padding added on each side. The output image is at most 500 px wide.\n\nAfter a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space.",parameterSchema:{additionalProperties:!1,properties:{pid:{description:"Target pid \u2014 required for from_zoom click/type translation.",type:"integer"},window_id:{description:"CGWindowID from list_windows.",type:"integer"},x1:{description:"Left edge of region in screenshot pixels.",type:"number"},x2:{description:"Right edge of region in screenshot pixels.",type:"number"},y1:{description:"Top edge of region in screenshot pixels.",type:"number"},y2:{description:"Bottom edge of region in screenshot pixels.",type:"number"}},required:["window_id","x1","y1","x2","y2"],type:"object"}}};d();import{execFile as L,spawnSync as v}from"node:child_process";import{promisify as z}from"node:util";import{rmSync as X,statSync as G}from"node:fs";import{homedir as x}from"node:os";import{join as $}from"node:path";var B=z(L),H="Computer Use isn't available in this release: its driver doesn't come with Matilda Code yet.";function V(t){try{let e=JSON.parse(t);return typeof e.accessibility!="boolean"?"unknown":e.accessibility?e.screen_recording?"ok":"screenRecording":"accessibility"}catch{return"unknown"}}var K=()=>$(x(),"Library","Caches","cua-driver","cua-driver.sock");function E(){try{v("pkill",["-f","CuaDriver.app/Contents/MacOS/cua-driver serve"],{stdio:"ignore"})}catch{}try{X(K(),{force:!0})}catch{}}async function J(){try{let{stdout:t}=await B(l(x()),["permissions","status","--json"],{timeout:1e4,env:g()});return V(t)}catch{return"unknown"}}function Y(){E();try{v("open",["-n","-g","-a","CuaDriver","--args","serve","--no-permissions-gate"],{stdio:"ignore"})}catch{}return{kill:E}}function Z(t){let e=t==="accessibility"?"Privacy_Accessibility":"Privacy_ScreenCapture";try{v("open",[`x-apple.systempreferences:com.apple.preference.security?${e}`],{stdio:"ignore"})}catch{}}function Q(){return{platform:process.platform,driverInstalled:()=>ee(l(x())),startStatusDaemon:Y,probePermissions:J,openPermissionPane:Z}}function ee(t){try{return G(t).isFile()}catch{return!1}}async function I(t,e,i){let r={...Q(),...i},o=r.pollIntervalMs??5e3,s=r.pollTimeoutMs??10*6e4;if(!t.isStarted()){if(!r.driverInstalled())throw new Error(H);r.platform==="darwin"&&await te(r,e,o,s),await t.start(e.updateOutput)}}async function te(t,e,i,r){let o=t.startStatusDaemon(),s=!1,n=!1;try{let p=Date.now();for(;;){if(e.signal.aborted)throw new Error("Computer Use bootstrap aborted.");if(Date.now()-p>r)throw new Error(`Computer Use permission grant timed out after ${Math.round(r/1e3)}s. Re-invoke the tool to retry.`);await re(i);let a=await t.probePermissions();if(a==="ok")return;if(a==="unknown"){o.kill(),o=t.startStatusDaemon();let c=Math.round((Date.now()-p)/1e3);e.updateOutput?.(`Bringing up Computer Use permissions check\u2026 (${c}s)`);continue}if(a==="accessibility"){if(!s)s=!0,t.openPermissionPane("accessibility"),e.updateOutput?.("Step 1/2 \u2014 In the System Settings window that opened (Privacy & Security \u2192 Accessibility), turn ON CuaDriver. This continues automatically.");else{let c=Math.round((Date.now()-p)/1e3);e.updateOutput?.(`Waiting for Accessibility\u2026 (${c}s) \u2014 enable CuaDriver in System Settings.`)}continue}if(!n)n=!0,t.openPermissionPane("screenRecording"),e.updateOutput?.("Step 2/2 \u2014 Accessibility granted. Now in System Settings (Privacy & Security \u2192 Screen & System Audio Recording), turn ON CuaDriver. macOS will ask to restart CuaDriver \u2014 allow it; that is expected. This continues automatically.");else{let c=Math.round((Date.now()-p)/1e3);e.updateOutput?.(`Waiting for Screen Recording\u2026 (${c}s) \u2014 enable CuaDriver in System Settings.`)}}}finally{o.kill()}}var re=t=>new Promise(e=>setTimeout(e,t));var N=new Set(["kill_app","launch_app","start_recording","set_config","replay_trajectory"]),ie=new Set(["execute_javascript","enable_javascript_apple_events"]);for(let t of N)if(!(t in m))throw new Error(`HIGH_RISK_TOOLS contains unknown tool: ${t}`);function oe(t,e){return N.has(t)?!0:t==="page"&&ie.has(e.action)}var S=class extends C{constructor(i,r,o){super(r);this.upstreamName=i;this.config=o}getDescription(){return f(this.params)}async getDefaultPermission(){return"ask"}async getConfirmationDetails(i){let r=[`computer_use__${this.upstreamName}`],o=async()=>{};if(oe(this.upstreamName,this.params))return{type:"mcp",title:`Allow high-risk Computer Use (${this.upstreamName})`,serverName:"cua-driver",toolName:this.upstreamName,toolDisplayName:`computer_use__${this.upstreamName}`,permissionRules:r,onConfirm:o};let s=f(this.params),n=`Tool: computer_use__${this.upstreamName}
|
|
90
|
+
For free-form text entry into web inputs, prefer \`type_text_chars\` which synthesises key events \u2014 AXValue writes are ignored by WebKit.`,parameterSchema:{additionalProperties:!1,properties:{element_index:{type:"integer"},pid:{type:"integer"},session:{description:"Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.",type:"string"},value:{description:"New value. AX will coerce to the element's native type.",type:"string"},window_id:{description:"CGWindowID for the window whose get_window_state produced the element_index.",type:"integer"}},required:["pid","window_id","element_index","value"],type:"object"}},start_recording:{description:"Start trajectory recording. Every subsequent action-tool invocation (click, right_click, scroll, type_text, press_key, hotkey, set_value) writes a turn folder under `output_dir`:\n\n- `app_state.json` \u2014 post-action AX/UIA snapshot for the target pid.\n- `screenshot.png` \u2014 post-action per-window screenshot of the target's frontmost on-screen window.\n- `action.json` \u2014 tool name, full input arguments, result summary, pid, click point (when applicable), ISO-8601 timestamp.\n- `click.png` \u2014 for click-family actions only, `screenshot.png` with a red dot drawn at the click point.\n\nTurn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.\n\n**Video is off by default.** Pass `record_video: true` to also capture the main display to `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of the session. The recording is torn down automatically when the MCP client disconnects.\n\n**macOS uses native ScreenCaptureKit** (in-process SCStream + SCRecordingOutput) so video inherits Cua Driver's own Screen Recording grant \u2014 no extra TCC prompt, no ffmpeg subprocess. Requires macOS 15.0+.\n\n**Windows + Linux use an ffmpeg subprocess** (`gdigrab` / `x11grab` + libx264). Requires ffmpeg on PATH (winget install Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or fails on startup the per-turn capture (screenshots + action.json) still runs and the session's `last_error` field carries the diagnostic.\n\nState persists for the life of the daemon / MCP session; a restart resets to disabled with no on-disk state. Call `stop_recording` to disable + finalize the mp4.",parameterSchema:{additionalProperties:!1,properties:{output_dir:{description:"Absolute or ~-rooted directory where turn folders and (when enabled) the video file are written.",type:"string"},record_video:{description:"Capture the main display to <output_dir>/recording.mp4. Default: false. Set to true to also capture the main display to recording.mp4 (otherwise only the per-turn screenshots + JSON are recorded). On macOS this uses native ScreenCaptureKit (no extra TCC prompt, macOS 15.0+); on Windows + Linux it requires ffmpeg on PATH.",type:"boolean"}},required:["output_dir"],type:"object"}},start_session:{description:"Declare a session \u2014 a named, color-coded identity for THIS agent run. Pass a stable `session` id; the agent cursor, per-session config, and recording all key on it, and it follows the run across any apps/windows. The cursor's color is derived from the id, so distinct runs are visually distinct. A cursor is shown only for a declared session \u2014 call this (or pass `session` on your first action) to opt in. Idempotent: re-calling with the same id just refreshes its idle-TTL. End it with `end_session` (or let the idle-TTL reclaim it). Concurrent runs/subagents each pass their own `session` to get their own cursor.",parameterSchema:{additionalProperties:!0,properties:{session:{description:'Stable session id for this run (e.g. "research-run-1").',type:"string"}},required:["session"],type:"object"}},stop_recording:{description:"Stop trajectory recording. Disables further per-turn capture and, when video was enabled, gracefully terminates the ffmpeg subprocess so the mp4's moov atom is finalized (the file is playable). Calling stop on an already-stopped session is a no-op. The response carries `last_video_path` pointing at the finalized mp4 (when video was on).\n\nA manual `stop_recording` is **unconditional** \u2014 it stops whatever recording is active regardless of which session started it. Ownership-scoped teardown (so one MCP client disconnecting can't stop a recording a later client started) is handled by the daemon's `session_end` lifecycle signal, not by this tool.",parameterSchema:{additionalProperties:!1,properties:{},type:"object"}},type_text:{description:"Insert text into the target pid via `AXSetAttribute(kAXSelectedText)`. Works for standard Cocoa text fields and text views. No keystrokes are synthesized \u2014 special keys (Return / Escape / arrows) go through `press_key` / `hotkey`. For Chromium / Electron inputs that don't implement `kAXSelectedText`, the tool falls back to CGEvent character synthesis automatically.\n\nOptional `element_index` + `window_id` (from the last `get_window_state` snapshot) directs the write to a specific field. Without `element_index`, the write goes to the pid's currently focused element.",parameterSchema:{additionalProperties:!1,properties:{delay_ms:{description:"Milliseconds between characters in the CGEvent fallback path. Default 30. Ignored when the AX path succeeds.",maximum:200,minimum:0,type:"integer"},element_index:{description:"Element index from last get_window_state. Directs the write to a specific field. Requires window_id.",type:"integer"},pid:{description:"Target process ID.",type:"integer"},session:{description:"Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.",type:"string"},text:{description:"Text to insert at the target's cursor.",type:"string"},window_id:{description:"CGWindowID. Required when element_index is used.",type:"integer"}},required:["pid","text"],type:"object"}},zoom:{description:"Capture a cropped JPEG of a window region (x1,y1)\u2013(x2,y2) in screenshot pixel coordinates, with 20% padding added on each side. The output image is at most 500 px wide.\n\nAfter a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space.",parameterSchema:{additionalProperties:!1,properties:{pid:{description:"Target pid \u2014 required for from_zoom click/type translation.",type:"integer"},window_id:{description:"CGWindowID from list_windows.",type:"integer"},x1:{description:"Left edge of region in screenshot pixels.",type:"number"},x2:{description:"Right edge of region in screenshot pixels.",type:"number"},y1:{description:"Top edge of region in screenshot pixels.",type:"number"},y2:{description:"Bottom edge of region in screenshot pixels.",type:"number"}},required:["window_id","x1","y1","x2","y2"],type:"object"}}};d();import{execFile as L,spawnSync as v}from"node:child_process";import{promisify as z}from"node:util";import{rmSync as X,statSync as G}from"node:fs";import{homedir as x}from"node:os";import{join as $}from"node:path";var B=z(L),H="Computer Use isn't available in this release: its driver doesn't come with Matilda Code yet.";function V(t){try{let e=JSON.parse(t);return typeof e.accessibility!="boolean"?"unknown":e.accessibility?e.screen_recording?"ok":"screenRecording":"accessibility"}catch{return"unknown"}}var K=()=>$(x(),"Library","Caches","cua-driver","cua-driver.sock");function E(){try{v("pkill",["-f","CuaDriver.app/Contents/MacOS/cua-driver serve"],{stdio:"ignore"})}catch{}try{X(K(),{force:!0})}catch{}}async function J(){try{let{stdout:t}=await B(l(x()),["permissions","status","--json"],{timeout:1e4,env:f()});return V(t)}catch{return"unknown"}}function Y(){E();try{v("open",["-n","-g","-a","CuaDriver","--args","serve","--no-permissions-gate"],{stdio:"ignore"})}catch{}return{kill:E}}function Z(t){let e=t==="accessibility"?"Privacy_Accessibility":"Privacy_ScreenCapture";try{v("open",[`x-apple.systempreferences:com.apple.preference.security?${e}`],{stdio:"ignore"})}catch{}}function Q(){return{platform:process.platform,driverInstalled:()=>ee(l(x())),startStatusDaemon:Y,probePermissions:J,openPermissionPane:Z}}function ee(t){try{return G(t).isFile()}catch{return!1}}async function I(t,e,i){let r={...Q(),...i},o=r.pollIntervalMs??5e3,s=r.pollTimeoutMs??10*6e4;if(!t.isStarted()){if(!r.driverInstalled())throw new Error(H);r.platform==="darwin"&&await te(r,e,o,s),await t.start(e.updateOutput)}}async function te(t,e,i,r){let o=t.startStatusDaemon(),s=!1,n=!1;try{let p=Date.now();for(;;){if(e.signal.aborted)throw new Error("Computer Use bootstrap aborted.");if(Date.now()-p>r)throw new Error(`Computer Use permission grant timed out after ${Math.round(r/1e3)}s. Re-invoke the tool to retry.`);await re(i);let a=await t.probePermissions();if(a==="ok")return;if(a==="unknown"){o.kill(),o=t.startStatusDaemon();let c=Math.round((Date.now()-p)/1e3);e.updateOutput?.(`Bringing up Computer Use permissions check\u2026 (${c}s)`);continue}if(a==="accessibility"){if(!s)s=!0,t.openPermissionPane("accessibility"),e.updateOutput?.("Step 1/2 \u2014 In the System Settings window that opened (Privacy & Security \u2192 Accessibility), turn ON CuaDriver. This continues automatically.");else{let c=Math.round((Date.now()-p)/1e3);e.updateOutput?.(`Waiting for Accessibility\u2026 (${c}s) \u2014 enable CuaDriver in System Settings.`)}continue}if(!n)n=!0,t.openPermissionPane("screenRecording"),e.updateOutput?.("Step 2/2 \u2014 Accessibility granted. Now in System Settings (Privacy & Security \u2192 Screen & System Audio Recording), turn ON CuaDriver. macOS will ask to restart CuaDriver \u2014 allow it; that is expected. This continues automatically.");else{let c=Math.round((Date.now()-p)/1e3);e.updateOutput?.(`Waiting for Screen Recording\u2026 (${c}s) \u2014 enable CuaDriver in System Settings.`)}}}finally{o.kill()}}var re=t=>new Promise(e=>setTimeout(e,t));var N=new Set(["kill_app","launch_app","start_recording","set_config","replay_trajectory"]),ie=new Set(["execute_javascript","enable_javascript_apple_events"]);for(let t of N)if(!(t in m))throw new Error(`HIGH_RISK_TOOLS contains unknown tool: ${t}`);function oe(t,e){return N.has(t)?!0:t==="page"&&ie.has(e.action)}var S=class extends k{constructor(i,r,o){super(r);this.upstreamName=i;this.config=o}getDescription(){return g(this.params)}async getDefaultPermission(){return"ask"}async getConfirmationDetails(i){let r=[`computer_use__${this.upstreamName}`],o=async()=>{};if(oe(this.upstreamName,this.params))return{type:"mcp",title:`Allow high-risk Computer Use (${this.upstreamName})`,serverName:"cua-driver",toolName:this.upstreamName,toolDisplayName:`computer_use__${this.upstreamName}`,permissionRules:r,onConfirm:o};let s=g(this.params),n=`Tool: computer_use__${this.upstreamName}
|
|
91
91
|
|
|
92
92
|
Args: ${s}
|
|
93
93
|
|
|
94
|
-
This will act on your desktop via the Computer Use binary.`;return{type:"info",title:`Allow Computer Use (${this.upstreamName})`,prompt:n,permissionRules:r,onConfirm:o}}async execute(i,r){let o=u.shared();o.setMaxImageDimension(O(this.config?.getComputerUseMaxImageDimension())),await I(o,{signal:i,updateOutput:r});let s;try{s=await o.callTool(this.upstreamName,this.params)}catch(a){let c=a instanceof Error?a.message:String(a);return{llmContent:`Computer Use tool '${this.upstreamName}' failed: ${c}`,returnDisplay:`Error: ${c}`,error:{message:c}}}let n=ne(s.content,this.upstreamName,s.structuredContent),p=se(s.content);if(s.isError){let a=p||`Tool '${this.upstreamName}' returned isError=true`;return{llmContent:n||a,returnDisplay:a,error:{message:a}}}return{llmContent:n,returnDisplay:p}}},h=class extends
|
|
94
|
+
This will act on your desktop via the Computer Use binary.`;return{type:"info",title:`Allow Computer Use (${this.upstreamName})`,prompt:n,permissionRules:r,onConfirm:o}}async execute(i,r){let o=u.shared();o.setMaxImageDimension(O(this.config?.getComputerUseMaxImageDimension())),await I(o,{signal:i,updateOutput:r});let s;try{s=await o.callTool(this.upstreamName,this.params)}catch(a){let c=a instanceof Error?a.message:String(a);return{llmContent:`Computer Use tool '${this.upstreamName}' failed: ${c}`,returnDisplay:`Error: ${c}`,error:{message:c}}}let n=ne(s.content,this.upstreamName,s.structuredContent),p=se(s.content);if(s.isError){let a=p||`Tool '${this.upstreamName}' returned isError=true`;return{llmContent:n||a,returnDisplay:a,error:{message:a}}}return{llmContent:n,returnDisplay:p}}},h=class extends T{constructor(i,r,o){let s=`computer_use__${i}`;super(s,s,r.description,"other",r.parameterSchema,!0,!0,!0,!1,"computer use desktop click type screenshot mouse keyboard scroll drag automation gui app native");this.upstreamName=i;this.config=o}validateToolParams(i){let r=U(i,this.parameterSchema);return super.validateToolParams(r)}build(i){let r=U(i,this.parameterSchema);return super.build(r)}createInvocation(i){return new S(this.upstreamName,i,this.config)}};function U(t,e){let i=e.properties;if(!i)return t;let r={...t};for(let[o,s]of Object.entries(r)){let n=i[o]?.type;if((n==="integer"||n==="number")&&typeof s=="string"){let p=s.trim();if(/^-?\d+(\.\d+)?$/.test(p)){let a=n==="integer"?parseInt(p,10):parseFloat(p);Number.isFinite(a)&&(r[o]=a)}}else n==="string"&&typeof s=="number"&&(r[o]=String(s))}return r}function ne(t,e,i){let r=[];for(let n of t)n.type==="text"&&n.text?r.push({text:n.text}):(n.type==="image"||n.type==="audio")&&n.mimeType&&n.data&&(r.push({text:`[Tool '${e}' provided the following ${n.type} data with mime-type: ${n.mimeType}]`}),r.push({inlineData:{mimeType:n.mimeType,data:n.data}}));let o=ae(i);return o&&r.push({text:`Structured result: ${o}`}),r.some(n=>n.inlineData!==void 0)?r:r.map(n=>n.text??"").filter(Boolean).join(`
|
|
95
95
|
`)}function se(t){return t.map(e=>e.type==="text"?e.text??"":"").filter(Boolean).join(`
|
|
96
|
-
`)}function ae(t){if(!t||typeof t!="object")return;let e={};for(let[i,r]of Object.entries(t))i!=="tree_markdown"&&(e[i]=r);if(Object.keys(e).length!==0)return
|
|
96
|
+
`)}function ae(t){if(!t||typeof t!="object")return;let e={};for(let[i,r]of Object.entries(t))i!=="tree_markdown"&&(e[i]=r);if(Object.keys(e).length!==0)return g(e)}async function ze(t,e){for(let i of b){let r=m[i],o=`computer_use__${i}`;await t(o,async()=>new h(i,r,e))}}export{m as COMPUTER_USE_SCHEMAS,b as COMPUTER_USE_TOOL_NAMES,u as ComputerUseClient,h as ComputerUseTool,ze as registerComputerUseTools};
|
|
97
97
|
/**
|
|
98
98
|
* @license
|
|
99
99
|
* Copyright 2025 Matilda Team
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as p,c as f}from"./chunk-TXMXCR7D.js";import{a as y}from"./chunk-YULUB745.js";import{a as s}from"./chunk-
|
|
3
|
+
import{a as p,c as f}from"./chunk-TXMXCR7D.js";import{a as y}from"./chunk-YULUB745.js";import{a as s}from"./chunk-EC2IF7DG.js";import"./chunk-GT6MSEK4.js";import"./chunk-J6NYCXUR.js";import{ka as c,la as d,ra as n,sa as h}from"./chunk-4SDFTVQW.js";import"./chunk-HEJO7OBH.js";import{b as m}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";m();var a=class extends c{constructor(e,t){super(t);this.config=e}getDescription(){return`${this.params.cron}: ${this.params.prompt}`}async getDefaultPermission(){return"ask"}async execute(){let e=this.config.getCronScheduler(),t=this.params.recurring!==!1,i=this.params.durable===!0;try{p(this.params.cron),f(this.params.cron,new Date);let r=i?await e.createDurable(this.params.cron,this.params.prompt,t):e.create(this.params.cron,this.params.prompt,t),o=y(r.cronExpr),w=`Scheduled ${r.id} (${o})${i?" [durable]":""}`,u=i?`Persisted to ${s}`:"Session-only (not written to disk, dies when Matilda exits)";return{llmContent:t?`Scheduled recurring job ${r.id} (${r.cronExpr}). ${u}. Auto-expires after 7 days. Use ${n.CRON_DELETE} to cancel sooner.`:`Scheduled one-shot task ${r.id} (${r.cronExpr}). ${u}. It will fire once then auto-delete.`,returnDisplay:w}}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error creating cron job: ${o}`,returnDisplay:o,error:{message:o}}}}},g=class l extends d{constructor(e){super(l.Name,h.CRON_CREATE,`Schedule a prompt to be enqueued at a future time. Use for both recurring schedules and one-shot reminders.
|
|
4
4
|
|
|
5
5
|
Uses standard 5-field cron in the user's local timezone: minute hour day-of-month month day-of-week. "0 9 * * *" means 9am local \u2014 no timezone conversion needed.
|
|
6
6
|
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as d,f as u}from"./chunk-
|
|
3
|
+
import{a as d,f as u}from"./chunk-EC2IF7DG.js";import"./chunk-GT6MSEK4.js";import"./chunk-J6NYCXUR.js";import{e as n,ka as l,la as c,ra as m,sa as p}from"./chunk-4SDFTVQW.js";import"./chunk-HEJO7OBH.js";import{b as i}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";i();var s=class extends l{constructor(r,o){super(o);this.config=r}getDescription(){return this.params.id}async execute(){let r=this.config.getCronScheduler(),o;try{o=await r.delete(this.params.id),o||(o=await u(this.config.getProjectRoot(),[this.params.id])>0)}catch(e){let t=`Failed to cancel job ${this.params.id}: ${n(e)}`;return{llmContent:t,returnDisplay:t,error:{message:t}}}if(o){let e=`Cancelled job ${this.params.id}.`,t=`Cancelled ${this.params.id}`;return{llmContent:e,returnDisplay:t}}else{let e=`Job ${this.params.id} not found.`;return{llmContent:e,returnDisplay:e,error:{message:e}}}}},f=class a extends c{constructor(r){super(a.Name,p.CRON_DELETE,`Cancel a cron job previously scheduled with CronCreate. Removes it from the in-memory session store or from ${d} (durable jobs).`,"other",{type:"object",properties:{id:{type:"string",description:"Job ID returned by CronCreate."}},required:["id"],additionalProperties:!1},!0,!1,!0,!1,"cron delete cancel remove");this.config=r}static Name=m.CRON_DELETE;createInvocation(r){return new s(this.config,r)}};export{f as CronDeleteTool};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as m}from"./chunk-YULUB745.js";import{a as d,c as g}from"./chunk-
|
|
3
|
+
import{a as m}from"./chunk-YULUB745.js";import{a as d,c as g}from"./chunk-EC2IF7DG.js";import"./chunk-GT6MSEK4.js";import"./chunk-J6NYCXUR.js";import{ka as l,la as c,ra as p,sa as u}from"./chunk-4SDFTVQW.js";import"./chunk-HEJO7OBH.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var s=class extends l{constructor(e,t){super(t);this.config=e}getDescription(){return""}async execute(){let e=this.config.getCronScheduler(),t;try{t=await g(this.config.getProjectRoot())}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error listing cron jobs: ${o}`,returnDisplay:o,error:{message:o}}}let n=[...t.map(r=>({id:r.id,cron:r.cron,prompt:r.prompt,recurring:r.recurring,durable:!0})),...e.list().filter(r=>!r.durable).map(r=>({id:r.id,cron:r.cronExpr,prompt:r.prompt,recurring:r.recurring,durable:!1}))];if(n.length===0){let r="No active cron jobs.";return{llmContent:r,returnDisplay:r}}let y=n.map(r=>{let o=r.recurring?"recurring":"one-shot",h=r.durable?"durable":"session-only";return`${r.id} \u2014 ${r.cron} (${o}) [${h}]: ${r.prompt}`}).join(`
|
|
4
4
|
`),T=n.map(r=>`${r.id} ${m(r.cron)} [${r.durable?"durable":"session-only"}]`).join(`
|
|
5
5
|
`);return{llmContent:y,returnDisplay:T}}},f=class i extends c{constructor(e){super(i.Name,u.CRON_LIST,`List all cron jobs scheduled via CronCreate, both session-only and durable (${d}).`,"other",{type:"object",properties:{},additionalProperties:!1},!0,!1,!0,!1,"cron list scheduled jobs");this.config=e}static Name=p.CRON_LIST;createInvocation(e){return new s(this.config,e)}};export{f as CronListTool};
|
|
@@ -1,41 +1,41 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as T}from"./chunk-
|
|
3
|
+
import{a as T}from"./chunk-RR3LDVGW.js";import{aa as Q,cb as L,db as Y,nb as M,ob as S,q as R,sb as K,tb as J,ub as Z,vb as ee}from"./chunk-LPPYEBZM.js";import"./chunk-5372BQ2X.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-EC2IF7DG.js";import"./chunk-R373GBK6.js";import"./chunk-VNSW4TSX.js";import"./chunk-EEPSTT7K.js";import"./chunk-RT2VU2QV.js";import"./chunk-5MS3VZDH.js";import"./chunk-JVQHQDDE.js";import"./chunk-QXSBPCBA.js";import"./chunk-WAZCC4SE.js";import"./chunk-V6UPUMP3.js";import"./chunk-5B2QERWR.js";import"./chunk-MUYVUUSO.js";import"./chunk-7ZODGQO6.js";import"./chunk-GT6MSEK4.js";import"./chunk-J6YVJMKL.js";import"./chunk-LBQNFSZ2.js";import{C as A,H,Rb as V,db as D,xa as z,z as j}from"./chunk-LQ3VS2EV.js";import"./chunk-B7BF33U4.js";import{l as B,m as X,n as q}from"./chunk-M5ABGGE7.js";import"./chunk-QKAKC34Q.js";import"./chunk-T6MRYRLI.js";import"./chunk-3EQIOCSJ.js";import{a as G}from"./chunk-XPVKH5TC.js";import"./chunk-J6NYCXUR.js";import"./chunk-UM6CLO7D.js";import"./chunk-YUCEPXGG.js";import{D as y,E as N,G as $,c as x,ea as k,la as U,ra as P,sa as W}from"./chunk-4SDFTVQW.js";import"./chunk-HEJO7OBH.js";import{b}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";b();import*as _ from"node:fs";import*as p from"node:path";b();var le={"\u2010":"-","\u2011":"-","\u2012":"-","\u2013":"-","\u2014":"-","\u2015":"-","\u2212":"-","\u2018":"'","\u2019":"'","\u201A":"'","\u201B":"'","\u201C":'"',"\u201D":'"',"\u201E":'"',"\u201F":'"',"\xA0":" ","\u2002":" ","\u2003":" ","\u2004":" ","\u2005":" ","\u2006":" ","\u2007":" ","\u2008":" ","\u2009":" ","\u200A":" ","\u202F":" ","\u205F":" ","\u3000":" "},me=new RegExp(`[${Object.keys(le).join("")}]`,"g");function w(n){return n.replace(me,t=>le[t])}var _e=[n=>n,n=>n.trimEnd()];function we(n){return w(n).trimEnd()}function te(n,t,i){if(t.length===0)return 0;if(t.length>n.length)return null;e:for(let e=0;e<=n.length-t.length;e++){for(let r=0;r<t.length;r++)if(i(n[e+r])!==i(t[r]))continue e;return e}return null}function Ee(n){let t=n.split(`
|
|
4
4
|
`),i=new Array(t.length+1),e=0;for(let r=0;r<t.length;r++)i[r]=e,e+=t[r].length,r<t.length-1&&(e+=1);return i[t.length]=n.length,{lines:t,offsets:i}}function ne(n,t,i,e,r,o){if(r===0)return o?`
|
|
5
|
-
`:"";let l=t[e]??0,s=e+r-1,f=(t[s]??0)+(i[s]?.length??0);if(o){let
|
|
6
|
-
`)&&(f=n.length)}return n.slice(l,f)}function ye(n,t){let{lines:i,offsets:e}=
|
|
5
|
+
`:"";let l=t[e]??0,s=e+r-1,f=(t[s]??0)+(i[s]?.length??0);if(o){let d=t[e+r];d!==void 0?f=d:n.endsWith(`
|
|
6
|
+
`)&&(f=n.length)}return n.slice(l,f)}function ye(n,t){let{lines:i,offsets:e}=Ee(n),r=t.split(`
|
|
7
7
|
`),o=t.endsWith(`
|
|
8
|
-
`);if(r.length===0)return null;let l=c=>{for(let f of _e){let
|
|
8
|
+
`);if(r.length===0)return null;let l=c=>{for(let f of _e){let d=te(i,c,f);if(d!==null)return d}return te(i,c,we)},s=l(r);if(s!==null)return{slice:ne(n,e,i,s,r.length-(o?1:0),o),removedTrailingFinalEmptyLine:!1};if(r.at(-1)===""){let c=r.slice(0,-1);if(c.length===0)return null;if(s=l(c),s!==null)return{slice:ne(n,e,i,s,c.length,!1),removedTrailingFinalEmptyLine:!0}}return null}function Te(n,t){if(t==="")return null;let i=n.indexOf(t);if(i!==-1)return{slice:n.slice(i,i+t.length),removedTrailingFinalEmptyLine:!1};let e=w(n),r=w(t),o=e.indexOf(r);return o!==-1?{slice:n.slice(o,o+t.length),removedTrailingFinalEmptyLine:!1}:ye(n,t)}function Ce(n){return n.endsWith(`\r
|
|
9
9
|
`)?n.slice(0,-2):n.endsWith(`
|
|
10
10
|
`)||n.endsWith("\r")?n.slice(0,-1):n}function be(n,t){return t?Ce(n):n}function ae(n,t,i){if(n===null||t==="")return{oldString:t,newString:i};let e=Te(n,t);return e!==null?{oldString:e.slice,newString:be(i,e.removedTrailingFinalEmptyLine)}:{oldString:t,newString:i}}function ce(n,t,i){if(n===null||t===""||i!==""||t.endsWith(`
|
|
11
11
|
`))return t;let e=`${t}
|
|
12
|
-
`;return n.includes(e)?e:t}function fe(n,t){if(t==="")return 0;let i=0,e=n.indexOf(t);for(;e!==-1;)i++,e=n.indexOf(t,e+t.length);return i}var xe=12,ie=300,Se=2e6,
|
|
13
|
-
`);return Ie(n,i,t)??
|
|
14
|
-
`)}function oe(n,t){let i=0;for(let e=0;e<t;e++)n.charCodeAt(e)!==32&&i++;return i}function
|
|
15
|
-
`).map(i),r=e.length;if(r>n.length||r*n.length>
|
|
16
|
-
`)}function
|
|
12
|
+
`;return n.includes(e)?e:t}function fe(n,t){if(t==="")return 0;let i=0,e=n.indexOf(t);for(;e!==-1;)i++,e=n.indexOf(t,e+t.length);return i}var xe=12,ie=300,Se=2e6,Fe=4e6;function ge(n,t){if(n.length>Se||t.trim()==="")return;let i=n.split(`
|
|
13
|
+
`);return Ie(n,i,t)??Pe(i,t)}function re(n){return w(n).replace(/\s+/g," ").trim()}function Ie(n,t,i){let e=re(i),r=re(n),o=r.indexOf(e);if(e===""||o===-1)return;let[l,s]=Ne(n,[oe(r,o),oe(r,o+e.length-1)]);return[`The text is in the file, but with different whitespace (indentation, tabs or spaces, or line breaks), at lines ${l+1}-${s+1}:`,...de(t,l,s),"Copy the whitespace exactly as shown (\u2192 is a tab, \xB7 is a leading or trailing space)."].join(`
|
|
14
|
+
`)}function oe(n,t){let i=0;for(let e=0;e<t;e++)n.charCodeAt(e)!==32&&i++;return i}function Ne(n,t){let i=[],e=0,r=0;for(let o=0;o<n.length&&i.length<t.length;o++){let l=n.charCodeAt(o);if(l===10&&e++,!(l<128?l===32||l>=9&&l<=13:/\s/.test(n[o]))){for(;i.length<t.length&&t[i.length]===r;)i.push(e);r++}}return i}function Pe(n,t){let i=g=>w(g).trim(),e=t.trim().split(`
|
|
15
|
+
`).map(i),r=e.length;if(r>n.length||r*n.length>Fe)return;let o=new Map,l=e.map(g=>g===""?-1:(o.has(g)||o.set(g,o.size),o.get(g))),s=new Set(e.map(g=>g.length)),c=n.map(g=>{let h=g.trim();return s.has(h.length)?o.get(w(h))??-2:-2}),f=-1,d=0;for(let g=0;g+r<=c.length;g++){let h=0;for(let a=0;a<r;a++)c[g+a]===l[a]&&h++;h>d&&(d=h,f=g)}if(f===-1||d*2<r)return;let m=f+r-1;return[`The closest match is at lines ${f+1}-${m+1}, where ${d} of ${r} lines agree once leading and trailing whitespace is ignored:`,...de(n,Math.max(0,f-1),Math.min(n.length-1,m+1)),"Copy the text exactly as shown (\u2192 is a tab, \xB7 is a leading or trailing space)."].join(`
|
|
16
|
+
`)}function de(n,t,i){let e=Math.min(i,t+xe-1),r=[];for(let o=t;o<=e;o++)r.push(`${String(o+1).padStart(6)}|${Ae(n[o])}`);return e<i&&r.push(` \u2026| ${i-e} more lines`),r}function Ae(n){let t=n.length>ie,i=t?n.slice(0,ie):n,e=c=>c===" "||c===" ",r=0;for(;e(i[r]);)r++;let o=i.length;for(;!t&&o>r&&e(i[o-1]);)o--;let l=c=>c.replace(/\t/g,"\u2192").replace(/ /g,"\xB7"),s=l(i.slice(0,r))+i.slice(r,o).replace(/\t/g,"\u2192")+l(i.slice(o));return t?`${s}\u2026[${n.length-i.length} more characters not shown]`:s}var se=4,De=1e3;function ue(n,t){let i=t.split(`
|
|
17
17
|
`),e=i.length;if(n===null)return{startLine:1,endLine:e,totalLines:e,content:t};if(n===t||!t)return null;let r=n.split(`
|
|
18
|
-
`),o=0,l=Math.min(r.length,i.length);for(;o<l&&r[o]===i[o];)o++;let s=r.length-1,c=i.length-1;for(;s>=o&&c>=o&&r[s]===i[c];)s--,c--;let f=o+1,
|
|
19
|
-
`)}}var he=k("EDIT_PRIOR_READ");function pe(n,t,i,e){return e?i:n===null?t===""?i:"":t===""&&!e?n:G(n,t,i)}var Re=["filePath","filepath","path","file","filename"],Le=["oldString","oldText","old_text","previous_string","previousString"],Me=["newString","newText","new_text","content"];function
|
|
20
|
-
`),r=!0}catch(a){if(!x(a)||a.code!=="ENOENT")throw a;r=!1}if(r&&!this.config.getFileReadCacheDisabled()){let a=await S(this.config.getFileReadCache(),t.file_path,"editing",{expectExisting:!0});if(!a.ok)return he.warn("post-read TOCTOU rejection",{path:t.file_path,reason:a.type}),{currentContent:null,newContent:"",occurrences:0,error:{display:a.displayMessage,raw:a.rawMessage,type:a.type},isNewFile:!1,encoding:"utf-8",bom:!1,lineEnding:"lf"}}if(t.full_file_replace)o=!r,r&&e!==null?(c=1,s=e,l=t.new_string):r||(s="",l=t.new_string);else{let a=ae(e,s,l);if(s=a.oldString,l=a.newString,s===""&&!r)o=!0;else if(!r)f={display:"File not found. Cannot apply edit. Use an empty old_string to create a new file.",raw:`File not found: ${t.file_path}`,type:"file_not_found"};else if(e!==null)if(s=ce(e,s,l),c=fe(e,s),t.old_string==="")f={display:"Failed to edit. Attempted to create a file that already exists.",raw:`File already exists, cannot create: ${t.file_path}`,type:"attempt_to_create_existing_file"};else if(c===0){let
|
|
21
|
-
`).length,
|
|
18
|
+
`),o=0,l=Math.min(r.length,i.length);for(;o<l&&r[o]===i[o];)o++;let s=r.length-1,c=i.length-1;for(;s>=o&&c>=o&&r[s]===i[c];)s--,c--;let f=o+1,d=c+1;if(d-f>De)return null;let m=Math.max(1,f-se),g=Math.min(e,d+se),h=i.slice(m-1,g);return{startLine:m,endLine:g,totalLines:e,content:h.join(`
|
|
19
|
+
`)}}var he=k("EDIT_PRIOR_READ");function pe(n,t,i,e){return e?i:n===null?t===""?i:"":t===""&&!e?n:G(n,t,i)}var Re=["filePath","filepath","path","file","filename"],Le=["oldString","oldText","old_text","previous_string","previousString"],Me=["newString","newText","new_text","content"];function ve(n){if(!(typeof n.file_path=="string"&&n.file_path.trim()))for(let t of Re){let i=n[t];if(typeof i=="string"&&i.trim()){n.file_path=i,delete n[t];break}}if(n.old_string===void 0||n.old_string===null){for(let t of Le)if(n[t]!==void 0&&n[t]!==null){n.old_string=n[t],delete n[t];break}}if(n.new_string===void 0||n.new_string===null){for(let t of Me)if(n[t]!==void 0&&n[t]!==null){n.new_string=n[t],delete n[t];break}}(n.old_string===void 0||n.old_string===null)&&typeof n.new_string=="string"&&typeof n.file_path=="string"&&n.file_path.trim()&&(n.old_string="",n.full_file_replace=!0)}var v=class{constructor(t,i){this.config=t;this.params=i}toolLocations(){return[{path:this.params.file_path}]}async calculateEdit(t){let i=t.replace_all??!1,e=null,r=await A(t.file_path),o=!1,l=t.new_string,s=t.old_string,c=0,f,d=!1,m="utf-8",g="lf";if(!this.config.getFileReadCacheDisabled()){let a=await S(this.config.getFileReadCache(),t.file_path,"editing");if(!a.ok)return{currentContent:null,newContent:"",occurrences:0,error:{display:a.displayMessage,raw:a.rawMessage,type:a.type},isNewFile:!1,encoding:"utf-8",bom:!1,lineEnding:"lf"}}if(r)try{let a=await this.config.getFileSystemService().readTextFile({path:t.file_path});a._meta?.bom!==void 0?d=a._meta.bom:d=a.content.length>0&&a.content.codePointAt(0)===65279,m=a._meta?.encoding||"utf-8",g=Z(a.content),e=a.content.replace(/\r\n/g,`
|
|
20
|
+
`),r=!0}catch(a){if(!x(a)||a.code!=="ENOENT")throw a;r=!1}if(r&&!this.config.getFileReadCacheDisabled()){let a=await S(this.config.getFileReadCache(),t.file_path,"editing",{expectExisting:!0});if(!a.ok)return he.warn("post-read TOCTOU rejection",{path:t.file_path,reason:a.type}),{currentContent:null,newContent:"",occurrences:0,error:{display:a.displayMessage,raw:a.rawMessage,type:a.type},isNewFile:!1,encoding:"utf-8",bom:!1,lineEnding:"lf"}}if(t.full_file_replace)o=!r,r&&e!==null?(c=1,s=e,l=t.new_string):r||(s="",l=t.new_string);else{let a=ae(e,s,l);if(s=a.oldString,l=a.newString,s===""&&!r)o=!0;else if(!r)f={display:"File not found. Cannot apply edit. Use an empty old_string to create a new file.",raw:`File not found: ${t.file_path}`,type:"file_not_found"};else if(e!==null)if(s=ce(e,s,l),c=fe(e,s),t.old_string==="")f={display:"Failed to edit. Attempted to create a file that already exists.",raw:`File already exists, cannot create: ${t.file_path}`,type:"attempt_to_create_existing_file"};else if(c===0){let F=ge(e,s);f={display:"Failed to edit, could not find the string to replace.",raw:`Failed to edit, 0 occurrences found for old_string in ${t.file_path}. No edits made. ${F??`The exact text in old_string was not found. Ensure you're not escaping content incorrectly and check whitespace, indentation, and context. Use ${D.Name} tool to verify.`}`,type:"edit_no_occurrence_found"}}else!i&&c>1?f={display:"Failed to edit because the text matches multiple locations. Provide more context or set replace_all to true.",raw:`Failed to edit. Found ${c} occurrences for old_string in ${t.file_path} but replace_all was not enabled.`,type:"edit_expected_occurrence_mismatch"}:s===l&&(f={display:"No changes to apply. The old_string and new_string are identical.",raw:`No changes to apply. The old_string and new_string are identical in file: ${t.file_path}`,type:"edit_no_change"});else f={display:"Failed to read content of file.",raw:`Failed to read content of existing file: ${t.file_path}`,type:"read_content_failure"}}let h=f?e??"":t.full_file_replace?t.new_string:pe(e,s,l,o);return!f&&r&&e===h&&(f={display:"No changes to apply. The new content is identical to the current content.",raw:`No changes to apply. The new content is identical to the current content in file: ${t.file_path}`,type:"edit_no_change"}),{currentContent:e,newContent:h,occurrences:c,error:f,isNewFile:o,bom:d,encoding:m,lineEnding:g}}async getDefaultPermission(){let t=this.config.getProjectRoot();return B(p.resolve(this.params.file_path),t)?"allow":"ask"}async getConfirmationDetails(t){let i=T(this.config,this.params.file_path);if(i)throw new M(i.message,i.type);let e;try{e=await this.calculateEdit(this.params)}catch(s){if(t.aborted)throw s;let c=s instanceof Error?s.message:String(s);throw new Error(`Error preparing edit: ${c}`)}if(e.error)throw new M(e.error.raw,e.error.type);let r=p.basename(this.params.file_path),o=R(r,e.currentContent??"",e.newContent,"Current","Proposed",L);return{type:"edit",title:`Confirm Edit: ${y(N(this.params.file_path,this.config.getTargetDir()))}`,fileName:r,filePath:this.params.file_path,fileDiff:o,originalContent:e.currentContent,newContent:e.newContent,onConfirm:async s=>{s==="proceed_always"&&this.config.setApprovalMode("auto-edit")}}}getDescription(){let t=N(this.params.file_path,this.config.getTargetDir());return this.params.old_string===""?`Create ${y(t)}`:this.params.old_string===this.params.new_string?`No file changes to ${y(t)}`:y(t)}async execute(t){let i=T(this.config,this.params.file_path);if(i)return{llmContent:i.message,returnDisplay:i.message,error:i};let e;try{e=await this.calculateEdit(this.params)}catch(r){if(t.aborted)throw r;let o=r instanceof Error?r.message:String(r);return{llmContent:`Error preparing edit: ${o}`,returnDisplay:`Error preparing edit: ${o}`,error:{message:o,type:"edit_preparation_failure"}}}if(e.error)return{llmContent:e.error.raw,returnDisplay:`Error: ${e.error.display}`,error:{message:e.error.raw,type:e.error.type}};try{try{await this.config.getFileHistoryService().trackEdit(this.params.file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){let u=await S(this.config.getFileReadCache(),this.params.file_path,"editing",{expectExisting:!e.isNewFile});if(!u.ok)return he.warn("pre-write TOCTOU rejection",{path:this.params.file_path,reason:u.type}),{llmContent:u.rawMessage,returnDisplay:`Error: ${u.displayMessage}`,error:{message:u.rawMessage,type:u.type}}}let r=T(this.config,this.params.file_path);if(r)return{llmContent:r.message,returnDisplay:r.message,error:r};this.ensureParentDirectoriesExist(this.params.file_path);let o=T(this.config,this.params.file_path);if(o)return{llmContent:o.message,returnDisplay:o.message,error:o};let l=q(this.params.file_path,this.config.getProjectRoot(),e.newContent);if(e.isNewFile){let u=this.config.getDefaultFileEncoding(),I=!1;u===K.UTF8_BOM?I=!0:u===void 0&&(I=J(this.params.file_path)),await this.config.getFileSystemService().writeTextFile({path:this.params.file_path,content:l,_meta:{bom:I}})}else await this.config.getFileSystemService().writeTextFile({path:this.params.file_path,content:l,_meta:{bom:e.bom,encoding:e.encoding,lineEnding:e.lineEnding}});this.params.modified_by_user||Q.getInstance().recordEdit(this.params.file_path,e.currentContent,e.newContent);try{let u=_.statSync(this.params.file_path);this.config.getFileReadCache().recordWrite(this.params.file_path,u)}catch{}let s=p.basename(this.params.file_path),c=this.params.ai_proposed_content||e.newContent,f=Y(s,e.currentContent??"",c,e.newContent),m={fileDiff:R(s,e.currentContent??"",e.newContent,"Current","Proposed",L),fileName:s,originalContent:e.currentContent,newContent:e.newContent,diffStat:f},g=j(this.params.file_path),h=H(this.params.file_path),a=p.extname(this.params.file_path),F=e.isNewFile?"create":"update";z(this.config,new V(O.Name,F,e.newContent.split(`
|
|
21
|
+
`).length,g,a,h));let C=[e.isNewFile?`Created new file: ${this.params.file_path} with provided content.`:`The file: ${this.params.file_path} has been updated.`];l!==e.newContent&&C.push(X);let E=ue(e.currentContent,e.newContent);if(E){let u=`Showing lines ${E.startLine}-${E.endLine} of ${E.totalLines} from the edited file:
|
|
22
22
|
|
|
23
23
|
---
|
|
24
24
|
|
|
25
|
-
${
|
|
25
|
+
${E.content}`;C.push(u)}try{let u=await ee(this.config,this.params.file_path);u&&C.push(`
|
|
26
26
|
|
|
27
|
-
${u}`)}catch{}return{llmContent:C.join(" "),returnDisplay:m}}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error executing edit: ${o}`,returnDisplay:`Error writing file: ${o}`,error:{message:o,type:"file_write_failure"}}}}ensureParentDirectoriesExist(t){let i=p.dirname(t);_.existsSync(i)||_.mkdirSync(i,{recursive:!0})}},
|
|
27
|
+
${u}`)}catch{}return{llmContent:C.join(" "),returnDisplay:m}}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error executing edit: ${o}`,returnDisplay:`Error writing file: ${o}`,error:{message:o,type:"file_write_failure"}}}}ensureParentDirectoriesExist(t){let i=p.dirname(t);_.existsSync(i)||_.mkdirSync(i,{recursive:!0})}},O=class n extends U{constructor(i){super(n.Name,W.EDIT,`Replaces text within a file. By default, replaces a single occurrence. Set \`replace_all\` to true when you intend to modify every instance of \`old_string\`. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${D.Name} tool to examine the file's current content before attempting a text replacement.
|
|
28
28
|
|
|
29
29
|
The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.
|
|
30
30
|
|
|
31
31
|
Expectation for required parameters:
|
|
32
32
|
1. \`file_path\` MUST be an absolute path; otherwise an error will be thrown.
|
|
33
|
-
2. \`old_string\` MUST be the exact literal text to replace (including all whitespace, indentation, newlines, and surrounding code etc.). For a full-file rewrite prefer \`${
|
|
33
|
+
2. \`old_string\` MUST be the exact literal text to replace (including all whitespace, indentation, newlines, and surrounding code etc.). For a full-file rewrite prefer \`${P.WRITE_FILE}\`; if you omit \`old_string\` and only pass \`new_string\`, the tool overwrites the entire file.
|
|
34
34
|
3. \`new_string\` MUST be the exact literal text to replace \`old_string\` with (also including all whitespace, indentation, newlines, and surrounding code etc.). Ensure the resulting code is correct and idiomatic.
|
|
35
35
|
4. NEVER escape \`old_string\` or \`new_string\`, that would break the exact literal text requirement.
|
|
36
36
|
**Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the single instance to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations, or does not match exactly, the tool will fail.
|
|
37
37
|
**Multiple replacements:** Set \`replace_all\` to true when you want to replace every occurrence that matches \`old_string\`.
|
|
38
|
-
**New files:** Pass an empty \`old_string\` to create a file that does not exist yet.`,"edit",{properties:{file_path:{description:"The absolute path to the file to modify. Must start with '/'.",type:"string"},old_string:{description:"The exact literal text to replace, preferably unescaped. For single replacements (default), include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string is not the exact literal text (i.e. you escaped it) or does not match exactly, the tool will fail. Omit only when intentionally overwriting the entire file with new_string (prefer write_file for that). Empty string creates a new file when the path does not exist.",type:"string"},new_string:{description:"The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic.",type:"string"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)."}},required:["file_path","old_string","new_string"],type:"object"});this.config=i}static Name=
|
|
38
|
+
**New files:** Pass an empty \`old_string\` to create a file that does not exist yet.`,"edit",{properties:{file_path:{description:"The absolute path to the file to modify. Must start with '/'.",type:"string"},old_string:{description:"The exact literal text to replace, preferably unescaped. For single replacements (default), include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string is not the exact literal text (i.e. you escaped it) or does not match exactly, the tool will fail. Omit only when intentionally overwriting the entire file with new_string (prefer write_file for that). Empty string creates a new file when the path does not exist.",type:"string"},new_string:{description:"The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic.",type:"string"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)."}},required:["file_path","old_string","new_string"],type:"object"});this.config=i}static Name=P.EDIT;validateToolParams(i){return ve(i),super.validateToolParams(i)}validateToolParamValues(i){return i.file_path=$(i.file_path.trim()),i.file_path?p.isAbsolute(i.file_path)?typeof i.new_string!="string"?"The 'new_string' parameter must be a string.":null:`File path must be absolute: ${i.file_path}`:"The 'file_path' parameter must be non-empty."}createInvocation(i){return new v(this.config,i)}toAutoClassifierInput(i){let e=i.old_string??"",r=i.new_string??"";return{file_path:i.file_path,old_string_preview:e.slice(0,300),new_string_preview:r.slice(0,300),old_string_truncated:e.length>300,new_string_truncated:r.length>300,lines_changed:(r.match(/\n/g)?.length??0)-(e.match(/\n/g)?.length??0)}}getModifyContext(i){return{getFilePath:e=>e.file_path,getCurrentContent:async e=>{if(await A(e.file_path))try{let{content:o}=await this.config.getFileSystemService().readTextFile({path:e.file_path});return o}catch(o){if(!x(o)||o.code!=="ENOENT")throw o;return""}else return""},getProposedContent:async e=>{if(e.full_file_replace)return e.new_string;if(_.existsSync(e.file_path))try{let{content:r}=await this.config.getFileSystemService().readTextFile({path:e.file_path});return pe(r,e.old_string,e.new_string,e.old_string===""&&r==="")}catch(r){if(!x(r)||r.code!=="ENOENT")throw r;return""}else return""},createUpdatedParams:(e,r,o)=>({...o,ai_proposed_content:e,old_string:e,new_string:r,modified_by_user:!0})}}};export{O as EditTool,pe as applyReplacement,ve as normalizeEditToolParams};
|
|
39
39
|
/**
|
|
40
40
|
* @license
|
|
41
41
|
* Copyright 2025 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{
|
|
3
|
+
import{Rb as W,Ub as s,bd as T}from"./chunk-LPPYEBZM.js";import"./chunk-5372BQ2X.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-EC2IF7DG.js";import"./chunk-R373GBK6.js";import"./chunk-VNSW4TSX.js";import"./chunk-EEPSTT7K.js";import"./chunk-RT2VU2QV.js";import"./chunk-5MS3VZDH.js";import"./chunk-JVQHQDDE.js";import"./chunk-QXSBPCBA.js";import"./chunk-WAZCC4SE.js";import"./chunk-V6UPUMP3.js";import"./chunk-5B2QERWR.js";import"./chunk-MUYVUUSO.js";import"./chunk-7ZODGQO6.js";import"./chunk-GT6MSEK4.js";import"./chunk-J6YVJMKL.js";import"./chunk-LBQNFSZ2.js";import"./chunk-LQ3VS2EV.js";import"./chunk-B7BF33U4.js";import"./chunk-M5ABGGE7.js";import"./chunk-QKAKC34Q.js";import"./chunk-T6MRYRLI.js";import"./chunk-3EQIOCSJ.js";import"./chunk-XPVKH5TC.js";import"./chunk-J6NYCXUR.js";import"./chunk-UM6CLO7D.js";import"./chunk-YUCEPXGG.js";import{ea as b,ka as $,la as E,ra as m,sa as R}from"./chunk-4SDFTVQW.js";import"./chunk-HEJO7OBH.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();var o=b("ENTER_WORKTREE"),P=`Creates an isolated git worktree at \`<projectRoot>/.matilda/worktrees/<slug>\` and returns its absolute path so subsequent file edits, shell commands, and other tools can operate inside it.
|
|
4
4
|
|
|
5
5
|
## When to Use
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{
|
|
3
|
+
import{Ac as r}from"./chunk-LPPYEBZM.js";import"./chunk-5372BQ2X.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-EC2IF7DG.js";import"./chunk-R373GBK6.js";import"./chunk-VNSW4TSX.js";import"./chunk-EEPSTT7K.js";import"./chunk-RT2VU2QV.js";import"./chunk-5MS3VZDH.js";import"./chunk-JVQHQDDE.js";import"./chunk-QXSBPCBA.js";import"./chunk-WAZCC4SE.js";import"./chunk-V6UPUMP3.js";import"./chunk-5B2QERWR.js";import"./chunk-MUYVUUSO.js";import"./chunk-7ZODGQO6.js";import"./chunk-GT6MSEK4.js";import"./chunk-J6YVJMKL.js";import"./chunk-LBQNFSZ2.js";import"./chunk-LQ3VS2EV.js";import"./chunk-B7BF33U4.js";import"./chunk-M5ABGGE7.js";import"./chunk-QKAKC34Q.js";import"./chunk-T6MRYRLI.js";import"./chunk-3EQIOCSJ.js";import"./chunk-XPVKH5TC.js";import"./chunk-J6NYCXUR.js";import"./chunk-UM6CLO7D.js";import"./chunk-YUCEPXGG.js";import{ea as p,ka as m,la as u,ra as d,sa as c}from"./chunk-4SDFTVQW.js";import"./chunk-HEJO7OBH.js";import{b as l}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";l();var y=p("ENTER_PLAN_MODE"),g=`Use this tool to lower into plan mode before doing uncertain or complex work. Entering plan mode is a privilege reduction, so it does not require user confirmation.
|
|
4
4
|
|
|
5
5
|
## When to Use This Tool
|
|
6
6
|
Use this tool when the task is not yet clear enough to safely execute, for example when it requires multi-file changes, design choices, investigation before a plan can be summarized, or when requirements are ambiguous. While investigating, if complexity rises or you find yourself repeatedly needing to ask the user, enter plan mode and consolidate a plan.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{
|
|
3
|
+
import{Qb as k,Sb as W,Ub as l,ad as C,cd as x}from"./chunk-LPPYEBZM.js";import"./chunk-5372BQ2X.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-EC2IF7DG.js";import"./chunk-R373GBK6.js";import"./chunk-VNSW4TSX.js";import"./chunk-EEPSTT7K.js";import"./chunk-RT2VU2QV.js";import"./chunk-5MS3VZDH.js";import"./chunk-JVQHQDDE.js";import"./chunk-QXSBPCBA.js";import"./chunk-WAZCC4SE.js";import"./chunk-V6UPUMP3.js";import"./chunk-5B2QERWR.js";import"./chunk-MUYVUUSO.js";import"./chunk-7ZODGQO6.js";import"./chunk-GT6MSEK4.js";import"./chunk-J6YVJMKL.js";import"./chunk-LBQNFSZ2.js";import"./chunk-LQ3VS2EV.js";import"./chunk-B7BF33U4.js";import"./chunk-M5ABGGE7.js";import"./chunk-QKAKC34Q.js";import"./chunk-T6MRYRLI.js";import"./chunk-3EQIOCSJ.js";import"./chunk-XPVKH5TC.js";import"./chunk-J6NYCXUR.js";import"./chunk-UM6CLO7D.js";import"./chunk-YUCEPXGG.js";import{c as $,ea as b,ka as E,la as R,ra as c,sa as T}from"./chunk-4SDFTVQW.js";import"./chunk-HEJO7OBH.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();import*as S from"node:fs/promises";var h=b("EXIT_WORKTREE"),O=`Exits a worktree previously created by ${c.ENTER_WORKTREE}.
|
|
4
4
|
|
|
5
5
|
## Behavior
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as G}from"./chunk-ILBTI4K5.js";import{
|
|
3
|
+
import{a as G}from"./chunk-ILBTI4K5.js";import{$c as O,Ac as A,Mb as N,bc as F}from"./chunk-LPPYEBZM.js";import"./chunk-5372BQ2X.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-EC2IF7DG.js";import"./chunk-R373GBK6.js";import"./chunk-VNSW4TSX.js";import"./chunk-EEPSTT7K.js";import"./chunk-RT2VU2QV.js";import"./chunk-5MS3VZDH.js";import"./chunk-JVQHQDDE.js";import"./chunk-QXSBPCBA.js";import"./chunk-WAZCC4SE.js";import"./chunk-V6UPUMP3.js";import"./chunk-5B2QERWR.js";import"./chunk-MUYVUUSO.js";import"./chunk-7ZODGQO6.js";import"./chunk-GT6MSEK4.js";import{m as M}from"./chunk-J6YVJMKL.js";import"./chunk-LBQNFSZ2.js";import"./chunk-LQ3VS2EV.js";import"./chunk-B7BF33U4.js";import"./chunk-M5ABGGE7.js";import"./chunk-QKAKC34Q.js";import"./chunk-T6MRYRLI.js";import"./chunk-3EQIOCSJ.js";import"./chunk-XPVKH5TC.js";import"./chunk-J6NYCXUR.js";import"./chunk-UM6CLO7D.js";import"./chunk-YUCEPXGG.js";import{ea as y,ka as $,la as C,ra as w,sa as D}from"./chunk-4SDFTVQW.js";import"./chunk-HEJO7OBH.js";import{b as v}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";v();v();v();var T=y("GATE_REVIEW_AGENTS");function te(e){return`You are a Plan Design Reviewer for the Plan Approval Gate. Review the plan across three dimensions:
|
|
4
4
|
|
|
5
5
|
1. **Request Fit** \u2014 Does the plan fulfill every part of the user's original request and respect all explicit constraints? Does it do anything the user explicitly asked NOT to do?
|
|
6
6
|
2. **System Fit** \u2014 Does the plan align with the codebase structure, file paths, function names, permission model, and integration boundaries found during investigation?
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{
|
|
3
|
+
import{pb as _,qb as j}from"./chunk-LPPYEBZM.js";import"./chunk-5372BQ2X.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-EC2IF7DG.js";import"./chunk-R373GBK6.js";import"./chunk-VNSW4TSX.js";import"./chunk-EEPSTT7K.js";import"./chunk-RT2VU2QV.js";import"./chunk-5MS3VZDH.js";import"./chunk-JVQHQDDE.js";import"./chunk-QXSBPCBA.js";import"./chunk-WAZCC4SE.js";import"./chunk-V6UPUMP3.js";import{a as D}from"./chunk-5B2QERWR.js";import"./chunk-MUYVUUSO.js";import"./chunk-7ZODGQO6.js";import"./chunk-GT6MSEK4.js";import"./chunk-J6YVJMKL.js";import"./chunk-LBQNFSZ2.js";import"./chunk-LQ3VS2EV.js";import"./chunk-B7BF33U4.js";import{b as k}from"./chunk-M5ABGGE7.js";import"./chunk-QKAKC34Q.js";import"./chunk-T6MRYRLI.js";import"./chunk-3EQIOCSJ.js";import"./chunk-XPVKH5TC.js";import"./chunk-J6NYCXUR.js";import"./chunk-UM6CLO7D.js";import"./chunk-YUCEPXGG.js";import{G as $,J as O,N as v,e as x,ea as R,ka as M,la as C,ra as N,sa as A}from"./chunk-4SDFTVQW.js";import"./chunk-HEJO7OBH.js";import{b as L}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";L();import z from"node:fs";import T from"node:path";var V=R("GLOB"),Y=100,B=2e4,W=15e3,q=500;function K(u,g,t){let e=[...u];return e.sort((r,s)=>{let c=r.mtimeMs??0,a=s.mtimeMs??0,o=g-c<t,l=g-a<t;return o&&l?a-c:o?-1:l?1:r.fullpath().localeCompare(s.fullpath())}),e}var S=class extends M{constructor(t,e){super(e);this.config=t;this.fileService=t.getFileService()}fileService;getDescription(){let t=`'${this.params.pattern}'`;return this.params.path&&(t+=` in path '${this.params.path}'`),t}async getDefaultPermission(){if(!this.params.path)return"allow";let t=this.config.getWorkspaceContext(),e=T.resolve(this.config.getTargetDir(),this.params.path);return t.isPathWithinWorkspace(e)||O(k(),e)?"allow":"ask"}async globInDirectory(t,e,r){let s=e,c=T.join(t,s);z.existsSync(c)&&(s=_(s));let a=j(s,{cwd:t,withFileTypes:!0,nodir:!0,stat:!0,nocase:!0,dot:!0,ignore:this.config.getFileExclusions().getGlobExcludes(),follow:!1,signal:r}),o=[],l=Date.now(),p=null;for await(let n of a){if(o.push(n),o.length>=B){p="count";break}if(Date.now()-l>W){p="time";break}o.length%q===0&&await new Promise(b=>setImmediate(b))}p&&a.destroy?.();let d=this.config.getTargetDir(),P=o.map(n=>T.relative(d,n.fullpath())),{filteredPaths:m}=this.fileService.filterFilesWithReport(P,this.getFileFilteringOptions()),h=n=>process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n,f=new Set(m.map(n=>h(T.resolve(d,n))));return{entries:o.filter(n=>f.has(h(n.fullpath()))),limited:p}}async execute(t){try{let e=[],r;if(this.params.path){let i=v(this.config,this.params.path,{allowExternalPaths:!0});e.push(i),r=`within ${i}`}else{let i=this.config.getWorkspaceContext().getDirectories();e.push(...i),r=i.length>1?`across ${i.length} workspace directories`:"in the workspace directory"}let s=this.params.pattern,c=[],a=new Set,o=null;for(let i of e){let{entries:F,limited:E}=await this.globInDirectory(i,s,t);E&&(o=E);for(let G of F){let I=G.fullpath();a.has(I)||(a.add(I),c.push(G))}}let l=c,p=o==="time"?`
|
|
4
4
|
|
|
5
5
|
[Search stopped after ${W/1e3}s before scanning the whole tree. Results may be incomplete \u2014 narrow the search by passing a more specific 'path' or pattern.]`:o==="count"?`
|
|
6
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{I as b,n as h,pa as w,qa as f}from"./chunk-
|
|
3
|
+
import{I as b,n as h,pa as w,qa as f}from"./chunk-RT2VU2QV.js";import"./chunk-5MS3VZDH.js";import"./chunk-V6UPUMP3.js";import"./chunk-J6YVJMKL.js";import"./chunk-LBQNFSZ2.js";import"./chunk-LQ3VS2EV.js";import"./chunk-B7BF33U4.js";import"./chunk-M5ABGGE7.js";import"./chunk-QKAKC34Q.js";import"./chunk-3EQIOCSJ.js";import"./chunk-XPVKH5TC.js";import"./chunk-J6NYCXUR.js";import"./chunk-UM6CLO7D.js";import"./chunk-YUCEPXGG.js";import{ka as c,la as d,ra as m,sa as p}from"./chunk-4SDFTVQW.js";import"./chunk-HEJO7OBH.js";import{b as P}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";P();function l(o,a){return typeof o!="object"||o===null||!a.some(e=>e in o)?o:Object.fromEntries(Object.entries(o).filter(([e])=>!a.includes(e)))}var G=class extends c{constructor(e,t,r,i){super(e);this.runtime=t;this.permit=r;this.lastGoal=i}getDescription(){return"Read the current goal"}async execute(e){if(!this.runtime||!this.permit)return E(this.lastGoal);let t=await S(this.runtime,this.permit,e);e.throwIfAborted();let r=y(this.runtime,this.permit);if(t.goalId!==this.permit.goalId||t.revision!==this.permit.revision)throw u();let i=C(t,r);return{llmContent:JSON.stringify(i),returnDisplay:`Active goal \xB7 revision ${t.revision}`}}},k=class o extends d{constructor(e){super(o.Name,p.GET_GOAL,`Read the current Goal: its objective, status, budget figures, and any verifier feedback. Read-only; never changes Goal state.
|
|
4
4
|
|
|
5
5
|
Outside a Goal turn it returns "active": false with "lastGoal", a summary of the session's most recent Goal. Use the result silently; do not mention the retrieval to the user.`,"read",{type:"object",properties:{},additionalProperties:!1},!0,!1,!1);this.config=e}static Name=m.GET_GOAL;build(e){return super.build(l(e,["view"]))}validateToolParams(e){return super.validateToolParams(l(e,["view"]))}createInvocation(e){let t=h.getStore(),r=t?structuredClone(t):void 0,i=r?this.config.getGoalRuntime():void 0;return new G(e,i,r,r?void 0:this.lastGoal())}lastGoal(){let e;try{e=this.config.getGoalRuntime()}catch{return}if(typeof e?.getSnapshot!="function")return;let t=e.getSnapshot().goal;if(t)return{goalId:t.goalId,revision:t.revision,status:t.status,turnCount:t.turnCount,activeTimeMs:t.activeTimeMs,tokensUsed:t.tokensUsed,...t.tokenBudget===void 0?{}:{tokenBudget:t.tokenBudget},...t.turnBudget===void 0?{}:{turnBudget:t.turnBudget},...t.activeTimeBudgetMs===void 0?{}:{activeTimeBudgetMs:t.activeTimeBudgetMs},...t.lastReason===void 0?{}:{lastReason:t.lastReason}}}};function E(o){return o?{llmContent:JSON.stringify({active:!1,lastGoal:o}),returnDisplay:`No Goal turn is permitted \xB7 last Goal ${o.status} after ${o.turnCount} ${o.turnCount===1?"turn":"turns"}`}:{llmContent:JSON.stringify({active:!1}),returnDisplay:"No active Goal is available for this turn."}}var v=class extends c{constructor(e,t,r){super(e);this.runtime=t;this.permit=r}getDescription(){return`Propose that the Goal is ${this.params.status} for this permitted turn`}async execute(e){if(!this.runtime||!this.permit)throw new Error("No active Goal is available for this turn");let t=this.permit,r=await S(this.runtime,t,e);if(e.throwIfAborted(),y(this.runtime,t),r.goalId!==this.permit.goalId||r.revision!==this.permit.revision)throw u();let i={status:this.params.status,reason:this.params.reason.trim(),...this.params.blockerKind?{blockerKind:this.params.blockerKind}:{}};e.throwIfAborted();let n=F(this.runtime,this.permit,i),T=y(this.runtime,this.permit),x={proposalRecorded:n.recorded,readyForVerification:n.readyForVerification,goalLifecycleChanged:!1,nextAction:n.readyForVerification?"End this turn without user-facing text. Do not claim the Goal is complete or blocked. The Goal status card will report the independent verification result.":"Continue this turn without claiming the Goal is complete or blocked. A repeated-blocker audit requires the same blocker mode and exact same reason text across three consecutive Goal turns, each of which must show the blocker in its own tool results."},s;return n.recorded?n.readyForVerification&&T.goal?.status==="active"?s="Proposal queued for independent verification at the turn boundary; no terminal lifecycle change was committed.":T.goal?.status==="paused"?s="Proposal recorded while the Goal is paused; no terminal lifecycle change was committed.":s="Proposal recorded for blocker audit; it is not yet ready for independent verification and no terminal lifecycle change was committed.":s="A Goal proposal is already recorded for this turn; no terminal lifecycle change was committed.",{llmContent:JSON.stringify(x),returnDisplay:s}}},R=class o extends d{constructor(e){super(o.Name,p.UPDATE_GOAL,`Propose that the current Goal is complete or blocked; an independent verifier decides and this tool never changes the Goal's status.
|
|
6
6
|
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{
|
|
3
|
+
import{Uc as tt,Vc as et,Wc as rt,Xc as st,Yc as it,a as J,oa as k,qb as Z}from"./chunk-LPPYEBZM.js";import{m as V}from"./chunk-5372BQ2X.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-EC2IF7DG.js";import"./chunk-R373GBK6.js";import"./chunk-VNSW4TSX.js";import"./chunk-EEPSTT7K.js";import"./chunk-RT2VU2QV.js";import"./chunk-5MS3VZDH.js";import"./chunk-JVQHQDDE.js";import"./chunk-QXSBPCBA.js";import"./chunk-WAZCC4SE.js";import"./chunk-V6UPUMP3.js";import"./chunk-5B2QERWR.js";import"./chunk-MUYVUUSO.js";import"./chunk-7ZODGQO6.js";import"./chunk-GT6MSEK4.js";import"./chunk-J6YVJMKL.js";import"./chunk-LBQNFSZ2.js";import"./chunk-LQ3VS2EV.js";import"./chunk-B7BF33U4.js";import{b as Q}from"./chunk-M5ABGGE7.js";import"./chunk-QKAKC34Q.js";import"./chunk-T6MRYRLI.js";import"./chunk-3EQIOCSJ.js";import"./chunk-XPVKH5TC.js";import"./chunk-J6NYCXUR.js";import"./chunk-UM6CLO7D.js";import"./chunk-YUCEPXGG.js";import{G as _,J as H,M as U,N,c as j,e as w,ea as q,ka as z,la as K,ra as X,sa as Y}from"./chunk-4SDFTVQW.js";import"./chunk-HEJO7OBH.js";import{b as W}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";W();import nt from"node:fs/promises";import E from"node:path";import{EOL as ct}from"node:os";import{spawn as ot}from"node:child_process";var L=q("GREP"),D=class extends z{constructor(s,i){super(i);this.config=s;this.fileExclusions=s.getFileExclusions()}fileExclusions;async getDefaultPermission(){if(!this.params.path)return"allow";let s=this.config.getWorkspaceContext(),i=E.resolve(this.config.getTargetDir(),this.params.path);return s.isPathWithinWorkspace(i)||H(Q(),i)||U(this.config,i)?"allow":"ask"}async execute(s){try{let i=[],o;if(this.params.path){let t=N(this.config,this.params.path,{allowFiles:!0,allowExternalPaths:!0});i.push(t),o=`in path "${this.params.path}"`}else{let t=this.config.getWorkspaceContext().getDirectories();i.push(...t),o=t.length>1?`across ${t.length} workspace directories`:"in the workspace directory"}let a=[];for(let t of i){let e=await this.performGrepSearch({pattern:this.params.pattern,path:t,glob:this.params.glob,signal:s});if(i.length>1)for(let n of e)E.isAbsolute(n.filePath)||(n.filePath=E.resolve(t,n.filePath));a.push(...e)}if(i.length>1){let t=new Set;a=a.filter(e=>{let n=`${e.filePath}:${e.lineNumber}`;return t.has(n)?!1:(t.add(n),!0)})}let c=this.params.glob?` (filter: "${this.params.glob}")`:"";if(a.length===0)return{llmContent:`No matches found for pattern "${this.params.pattern}" ${o}${c}.`,returnDisplay:"No matches found"};let p=this.config.getTruncateToolOutputThreshold(),u=Math.min(this.config.getTruncateToolOutputLines(),this.params.limit??Number.POSITIVE_INFINITY),x=!1,h=a;a.length>u&&(h=a.slice(0,u),x=!0);let $=a.length,v=$===1?"match":"matches",G=`Found ${$} ${v} for pattern "${this.params.pattern}" ${o}${c}:
|
|
4
4
|
---
|
|
5
5
|
`,T=h.reduce((t,e)=>{let n=e.filePath;return t[n]||(t[n]=[]),t[n].push(e),t[n].sort((y,F)=>y.lineNumber-F.lineNumber),t},{}),P="",M=[],C=!1,f=(t,e)=>Number.isFinite(p)&&P.length+t.length>p?(P+=t.slice(0,Math.max(p-P.length,0)),P+="...",e&&M.push(e),C=!0,!1):(P+=t,e&&M.push(e),!0);for(let t in T){if(!f(`File: ${t}
|
|
6
6
|
`))break;let e=!1;for(let n of T[t]){let y=n.line.length>rt?n.range??it(n.line,this.params.pattern):void 0,F=st(n.line,y?.[0]??0,y?.[1]??0).trim();if(!f(`L${n.lineNumber}: ${F}
|
|
7
7
|
`,n)){e=!0;break}}if(e||!f(`---
|
|
8
8
|
`))break}let m=P.split(`
|
|
9
|
-
`).filter(t=>t.trim()&&!t.startsWith("File:")&&!t.startsWith("---")).length,l=G+P;if(x||C){let t=$-m;l+=` [${t} ${t===1?"line":"lines"} truncated] ...`}let r=`Found ${$} ${v}`;(x||C)&&(r+=" (truncated)");let d=Array.from(new Set(M.map(t=>t.absoluteFilePath).filter(t=>t!=="")));return await tt(this.config,d),{llmContent:l.trim(),returnDisplay:r,resultFilePaths:d}}catch(i){L.error(`Error during GrepLogic execution: ${i}`);let o=w(i);return{llmContent:`Error during grep search operation: ${o}`,returnDisplay:`Error: ${o}`,error:{message:o,type:"grep_execution_error"}}}}parseGrepOutput(s,i){let o=[];if(!s)return o;let a=s.split(ct);for(let c of a){if(!c.trim())continue;let p=c.indexOf(":");if(p===-1)continue;let u=c.indexOf(":",p+1);if(u===-1)continue;let x=c.substring(0,p),h=c.substring(p+1,u),$=c.substring(u+1),v=parseInt(h,10);if(!isNaN(v)){let G=E.resolve(i,x),T=E.relative(i,G);o.push({filePath:T||E.basename(G),absoluteFilePath:G,lineNumber:v,line:$.replace(/\r$/,"")})}}return o}getDescription(){let s=`'${this.params.pattern}' in path '${this.params.path||"./"}'`;return this.params.glob&&(s+=` (filter: '${this.params.glob}')`),s}async performGrepSearch(s){let{pattern:i,path:o,glob:a}=s,c="none",p=await nt.stat(o).then(h=>h.isFile()).catch(()=>!1),u=p?E.dirname(o):o,x=p?E.basename(o):".";try{if(!p&&
|
|
9
|
+
`).filter(t=>t.trim()&&!t.startsWith("File:")&&!t.startsWith("---")).length,l=G+P;if(x||C){let t=$-m;l+=` [${t} ${t===1?"line":"lines"} truncated] ...`}let r=`Found ${$} ${v}`;(x||C)&&(r+=" (truncated)");let d=Array.from(new Set(M.map(t=>t.absoluteFilePath).filter(t=>t!=="")));return await tt(this.config,d),{llmContent:l.trim(),returnDisplay:r,resultFilePaths:d}}catch(i){L.error(`Error during GrepLogic execution: ${i}`);let o=w(i);return{llmContent:`Error during grep search operation: ${o}`,returnDisplay:`Error: ${o}`,error:{message:o,type:"grep_execution_error"}}}}parseGrepOutput(s,i){let o=[];if(!s)return o;let a=s.split(ct);for(let c of a){if(!c.trim())continue;let p=c.indexOf(":");if(p===-1)continue;let u=c.indexOf(":",p+1);if(u===-1)continue;let x=c.substring(0,p),h=c.substring(p+1,u),$=c.substring(u+1),v=parseInt(h,10);if(!isNaN(v)){let G=E.resolve(i,x),T=E.relative(i,G);o.push({filePath:T||E.basename(G),absoluteFilePath:G,lineNumber:v,line:$.replace(/\r$/,"")})}}return o}getDescription(){let s=`'${this.params.pattern}' in path '${this.params.path||"./"}'`;return this.params.glob&&(s+=` (filter: '${this.params.glob}')`),s}async performGrepSearch(s){let{pattern:i,path:o,glob:a}=s,c="none",p=await nt.stat(o).then(h=>h.isFile()).catch(()=>!1),u=p?E.dirname(o):o,x=p?E.basename(o):".";try{if(!p&&J(u)&&k("git").available){c="git grep";let f=["grep","--untracked","-n","-E","--ignore-case","-e",i];a&&f.push("--",a);try{let g=await new Promise((m,l)=>{let r=ot("git",f,{cwd:u,windowsHide:!0,env:V()}),d=[],t=[];r.stdout.on("data",e=>d.push(e)),r.stderr.on("data",e=>t.push(e)),r.on("error",e=>l(new Error(`Failed to start git grep: ${e.message}`))),r.on("close",e=>{let n=Buffer.concat(d).toString("utf8"),y=Buffer.concat(t).toString("utf8");e===0?m(n):e===1?m(""):l(new Error(`git grep exited with code ${e}: ${y}`))})});return this.parseGrepOutput(g,u)}catch(g){L.debug(`GrepLogic: git grep failed: ${w(g)}. Falling back...`)}}let{available:v}=k("grep");if(v){c="system grep";let f=["-r","-n","-H","-E"];this.fileExclusions.getGlobExcludes().map(l=>{let r=l;return r.startsWith("**/")&&(r=r.substring(3)),r.endsWith("/**")?r=r.slice(0,-3):r.endsWith("/")&&(r=r.slice(0,-1)),r&&!r.includes("/")&&!r.includes("*")?r:null}).filter(l=>!!l).forEach(l=>f.push(`--exclude-dir=${l}`)),a&&!p&&f.push(`--include=${a}`),f.push("-e",i,"--",x);try{let l=await new Promise((r,d)=>{let t=ot("grep",f,{cwd:u,windowsHide:!0}),e=[],n=[],y=b=>e.push(b),F=b=>{let S=b.toString();!S.includes("Permission denied")&&!/grep:.*: Is a directory/i.test(S)&&n.push(b)},A=b=>{I(),d(new Error(`Failed to start system grep: ${b.message}`))},B=b=>{let S=Buffer.concat(e).toString("utf8"),O=Buffer.concat(n).toString("utf8").trim();I(),b===0?r(S):b===1?r(""):O?d(new Error(`System grep exited with code ${b}: ${O}`)):r("")},I=()=>{t.stdout.removeListener("data",y),t.stderr.removeListener("data",F),t.removeListener("error",A),t.removeListener("close",B),t.connected&&t.disconnect()};t.stdout.on("data",y),t.stderr.on("data",F),t.on("error",A),t.on("close",B)});return this.parseGrepOutput(l,u)}catch(l){L.debug(`GrepLogic: System grep failed: ${w(l)}. Falling back...`)}}L.debug("GrepLogic: Falling back to JavaScript grep implementation."),c="javascript fallback";let G=a||"**/*",T=this.fileExclusions.getGlobExcludes(),P=p?[o]:Z(G,{cwd:u,dot:!0,ignore:T,absolute:!0,nodir:!0,signal:s.signal}),M=new RegExp(i,"i"),C=[];for await(let f of P){let g=f;try{(await nt.readFile(g,"utf8")).split(/\r?\n/).forEach((r,d)=>{let t=M.exec(r);t&&C.push({filePath:E.relative(u,g)||E.basename(g),absoluteFilePath:g,lineNumber:d+1,line:r,range:[t.index,t.index+t[0].length]})})}catch(m){(!j(m)||m.code!=="ENOENT")&&L.debug(`GrepLogic: Could not read/process ${g}: ${w(m)}`)}}return C}catch(h){throw L.error(`GrepLogic: Error in performGrepSearch (Strategy: ${c}): ${w(h)}`),h}}},at=class R extends K{constructor(s){super(R.Name,Y.GREP,`A powerful search tool for finding patterns in files
|
|
10
10
|
|
|
11
11
|
Usage:
|
|
12
12
|
- ALWAYS use Grep for search tasks. NEVER invoke \`grep\` or \`rg\` as a Bash command. The Grep tool has been optimized for correct permissions and access.
|
|
@@ -14,7 +14,7 @@ import{Nc as tt,Oc as et,Pc as rt,Qc as st,Rc as it,g as Q,ka as k,mb as Z}from"
|
|
|
14
14
|
- Filter files with glob parameter (e.g., "*.js", "**/*.tsx")
|
|
15
15
|
- Case-insensitive by default
|
|
16
16
|
- Use Agent tool for open-ended searches requiring multiple rounds
|
|
17
|
-
`,"search",{properties:{pattern:{type:"string",description:"JavaScript regular expression (not PCRE). Case-insensitive by default \u2014 do not use (?i)."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}")'},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},limit:{type:"number",description:"Limit output to first N matching lines. Optional - shows all matches if not specified."}},required:["pattern"],type:"object"});this.config=s}static Name=
|
|
17
|
+
`,"search",{properties:{pattern:{type:"string",description:"JavaScript regular expression (not PCRE). Case-insensitive by default \u2014 do not use (?i)."},glob:{type:"string",description:'Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}")'},path:{type:"string",description:"File or directory to search in. Defaults to current working directory."},limit:{type:"number",description:"Limit output to first N matching lines. Optional - shows all matches if not specified."}},required:["pattern"],type:"object"});this.config=s}static Name=X.GREP;get maxOutputChars(){return 2e4}validateToolParamValues(s){s.pattern=et(s.pattern);try{new RegExp(s.pattern)}catch(i){return`Invalid regular expression pattern: ${s.pattern}. Error: ${w(i)}`}if(s.path){s.path=_(s.path.trim());try{N(this.config,s.path,{allowFiles:!0,allowExternalPaths:!0})}catch(i){return w(i)}}return null}createInvocation(s){return new D(this.config,s)}};export{at as GrepTool};
|
|
18
18
|
/**
|
|
19
19
|
* @license
|
|
20
20
|
* Copyright 2025 Google LLC
|