@zaly/agent 0.0.5 → 0.0.9

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.
Files changed (51) hide show
  1. package/dist/{agent-BaD2kax9.mjs → agent-B7cQOuMZ.mjs} +2 -2
  2. package/dist/agent-B7cQOuMZ.mjs.map +1 -0
  3. package/dist/{agent-EkPynZRJ.mjs → agent-D3wVIibN.mjs} +4 -3
  4. package/dist/agent-D3wVIibN.mjs.map +1 -0
  5. package/dist/{compactions-3AjPqjeZ.mjs → compactions-B8VdZJoU.mjs} +2 -2
  6. package/dist/{compactions-3AjPqjeZ.mjs.map → compactions-B8VdZJoU.mjs.map} +1 -1
  7. package/dist/{edit-Qxl4w1C2.mjs → edit-D4yaBK1K.mjs} +9 -17
  8. package/dist/edit-D4yaBK1K.mjs.map +1 -0
  9. package/dist/{fetch-DknuSrSX.mjs → fetch-VKhSWdEh.mjs} +2 -2
  10. package/dist/{fetch-DknuSrSX.mjs.map → fetch-VKhSWdEh.mjs.map} +1 -1
  11. package/dist/{find-Bah9SKWX.mjs → find-CimUGn-L.mjs} +6 -20
  12. package/dist/find-CimUGn-L.mjs.map +1 -0
  13. package/dist/{grep-B4GF0svc.mjs → grep-6O3mjSvV.mjs} +10 -78
  14. package/dist/grep-6O3mjSvV.mjs.map +1 -0
  15. package/dist/index-node-esm-CJsN8G51.mjs +2116 -0
  16. package/dist/index-node-esm-CJsN8G51.mjs.map +1 -0
  17. package/dist/index.d.mts +25 -37
  18. package/dist/index.d.mts.map +1 -1
  19. package/dist/index.mjs +3 -953
  20. package/dist/{manager-f-WjFTMX.mjs → manager-BqlbCGYV.mjs} +12 -2
  21. package/dist/{manager-f-WjFTMX.mjs.map → manager-BqlbCGYV.mjs.map} +1 -1
  22. package/dist/{masker-Bv9KjkDF.mjs → masker-DRFztUwc.mjs} +2 -2
  23. package/dist/{masker-Bv9KjkDF.mjs.map → masker-DRFztUwc.mjs.map} +1 -1
  24. package/dist/{read-Djsx2NZl.mjs → read-CSL_8nAk.mjs} +47 -63
  25. package/dist/read-CSL_8nAk.mjs.map +1 -0
  26. package/dist/{registry-BVf0aZEA.mjs → registry-L9GDccS0.mjs} +89 -43
  27. package/dist/registry-L9GDccS0.mjs.map +1 -0
  28. package/dist/{session-Bv8JiT8P.mjs → session-BSvUrr12.mjs} +2 -2
  29. package/dist/{session-Bv8JiT8P.mjs.map → session-BSvUrr12.mjs.map} +1 -1
  30. package/dist/session.mjs +1 -1
  31. package/dist/src-fK6DL2bg.mjs +953 -0
  32. package/dist/src-fK6DL2bg.mjs.map +1 -0
  33. package/dist/{subagent-CX7Zjcws.mjs → subagent-C8XCEecM.mjs} +2 -2
  34. package/dist/{subagent-CX7Zjcws.mjs.map → subagent-C8XCEecM.mjs.map} +1 -1
  35. package/dist/{tools-Bl-YI890.mjs → tools-wvkkuXWH.mjs} +76 -20
  36. package/dist/tools-wvkkuXWH.mjs.map +1 -0
  37. package/dist/{write-D3L-92vj.mjs → write-DwGiDNeG.mjs} +3 -11
  38. package/dist/write-DwGiDNeG.mjs.map +1 -0
  39. package/package.json +12 -12
  40. package/dist/agent-BaD2kax9.mjs.map +0 -1
  41. package/dist/agent-EkPynZRJ.mjs.map +0 -1
  42. package/dist/edit-Qxl4w1C2.mjs.map +0 -1
  43. package/dist/find-Bah9SKWX.mjs.map +0 -1
  44. package/dist/grep-B4GF0svc.mjs.map +0 -1
  45. package/dist/index-node-esm-D6YQRKEz.mjs +0 -1537
  46. package/dist/index-node-esm-D6YQRKEz.mjs.map +0 -1
  47. package/dist/index.mjs.map +0 -1
  48. package/dist/read-Djsx2NZl.mjs.map +0 -1
  49. package/dist/registry-BVf0aZEA.mjs.map +0 -1
  50. package/dist/tools-Bl-YI890.mjs.map +0 -1
  51. package/dist/write-D3L-92vj.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"registry-BVf0aZEA.mjs","names":["resolveRule","ignore","ignore"],"sources":["../src/permissions/handlers/bash.ts","../../../node_modules/.bun/ignore@7.0.8/node_modules/ignore/index.js","../src/permissions/handlers/files.ts","../src/permissions/handlers/tool.ts","../src/permissions/handlers/registry.ts"],"sourcesContent":["import type { Segment } from \"../../utils/bash/parser.ts\"\nimport type { CheckResult, PermissionHandler, Rule, Suggestion, Verdict } from \"../types.ts\"\n\nimport { parseBash } from \"../../utils/bash/parser.ts\"\nimport { TOOLS } from \"../../utils/bash/tools.ts\"\n\n/**\n * Handler for `Rule<\"bash\">` — evaluates a bash command line against\n * pattern rules, then delegates each segment's inferred and explicit\n * file paths to the file handler via `ctx.validate(\"read\"|\"write\", …)`.\n *\n * Composition keeps file-rule logic in one place: the bash handler\n * doesn't know about workspaces, sensitive files, or path-pattern\n * matching — it just asks the registered handler for those scopes.\n *\n * Sources of file paths per segment:\n * - `seg.reads` / `seg.writes` — explicit `<` / `>` / `>>` redirects\n * extracted by the parser.\n * - `TOOLS[cmd].reads/writes(args)` — inferred from built-in tool\n * specs (e.g. `cat foo.txt` reads `foo.txt`, `tee out` writes `out`).\n *\n * Suggestions and reasons from inner `validate` calls bubble up so the\n * prompt UI can offer \"allow `Bash(cat:*)`\" alongside \"add ~/Documents\n * as workspace\" in a single ask.\n */\nexport const bashHandler: PermissionHandler<\"bash\"> = {\n validate(input, ctx): CheckResult {\n const parsed = parseBash(input)\n if (!parsed.ok) {\n return {\n ask: `Allow this bash command? (${parsed.reason})`,\n reason: parsed.reason,\n verdict: \"ask\",\n }\n }\n\n let verdict: Verdict = \"allow\"\n let reason: string | undefined\n const suggestions: Suggestion[] = []\n\n for (const seg of parsed.segments) {\n // Bash rule match for the command itself. Resolve this before the\n // conservative safety checks so explicit allow-all presets like yolo can\n // mean exactly that instead of degrading to an unimplemented ask prompt.\n const cmdVerdict = resolveRules(ctx.rules, seg) ?? \"ask\"\n if (seg.hasCommandSubst && cmdVerdict !== \"allow\") {\n return {\n ask: `Allow command substitution in \\`${seg.cmd}\\`?`,\n reason: \"command substitution not allowed\",\n verdict: \"ask\",\n }\n }\n const spec = TOOLS[seg.cmd]\n if (spec?.unsafe?.(seg.args) && cmdVerdict !== \"allow\") {\n return {\n ask: `Allow invocation of \\`${seg.cmd}\\`? (unsafe)`,\n reason: `${seg.cmd}: invocation mode not safely modelled`,\n verdict: \"ask\",\n }\n }\n\n let segVerdict: Verdict = cmdVerdict\n let segReason: string | undefined =\n cmdVerdict === \"allow\" ? undefined : `segment \"${seg.cmd}\" → ${cmdVerdict}`\n if (cmdVerdict === \"ask\") {\n suggestions.push({\n kind: \"rule\",\n pattern: seg.args.length > 0 ? `${seg.cmd}:*` : seg.cmd,\n scope: \"bash\",\n })\n }\n\n // Delegate file paths to the file handler. Reads first, then\n // writes; both contribute to this segment's verdict via combine.\n const reads = [...(spec?.reads?.(seg.args) ?? []), ...seg.reads]\n const writes = [...(spec?.writes?.(seg.args) ?? []), ...seg.writes.map((w) => w.path)]\n\n for (const path of reads) {\n if (seg.dyn?.has(path)) {\n segVerdict = combine(segVerdict, \"ask\")\n segReason ??= `${seg.cmd}: read ${path}: dynamic path`\n suggestions.push({\n kind: \"rule\",\n pattern: `${seg.cmd}:*`,\n scope: \"bash\",\n })\n continue\n }\n const r = ctx.validate(\"read\", path)\n segVerdict = combine(segVerdict, r.verdict)\n if (r.verdict !== \"allow\") {\n segReason ??= `${seg.cmd}: read ${path}: ${r.reason}`\n if (r.suggestions) suggestions.push(...r.suggestions)\n }\n if (segVerdict === \"deny\") break\n }\n if (segVerdict !== \"deny\") {\n for (const path of writes) {\n if (seg.dyn?.has(path)) {\n segVerdict = combine(segVerdict, \"ask\")\n segReason ??= `${seg.cmd}: write ${path}: dynamic path`\n suggestions.push({\n kind: \"rule\",\n pattern: `${seg.cmd}:*`,\n scope: \"bash\",\n })\n continue\n }\n const w = ctx.validate(\"write\", path)\n segVerdict = combine(segVerdict, w.verdict)\n if (w.verdict !== \"allow\") {\n segReason ??= `${seg.cmd}: write ${path}: ${w.reason}`\n if (w.suggestions) suggestions.push(...w.suggestions)\n }\n if (segVerdict === \"deny\") break\n }\n }\n\n verdict = combine(verdict, segVerdict)\n if (verdict !== \"allow\" && reason === undefined) reason = segReason\n if (verdict === \"deny\") break\n }\n\n return verdict === \"allow\"\n ? { verdict: \"allow\" }\n : {\n ask: `Allow this bash command?`,\n reason: reason ?? \"no rule matched\",\n suggestions: suggestions.length > 0 ? suggestions : undefined,\n verdict,\n }\n },\n}\n\n// ── Pattern matching ─────────────────────────────────────────────────────\n\n/** A command-pattern rule.\n *\n * Pattern syntax:\n * \"cmd\" → cmd alone, no args\n * \"cmd:*\" → cmd with any args (trailing wildcard)\n * \"cmd a\" → cmd with arg \"a\", no other args\n * \"cmd a:*\" → cmd with arg \"a\" plus any others\n * \"cmd a b\" → cmd with exact args [a, b]\n * \"cmd --flag*\" → cmd with arg starting with \"--flag\" (per-arg prefix)\n * \"bun test:node:*\" → cmd \"bun\", arg \"test:node\", any others\n *\n * Whitespace separates the cmd from its args, and args from each\n * other. The `:` character is only meaningful as the trailing `:*`\n * wildcard suffix — anywhere else (including inside an arg like\n * `test:node`) it's a literal character. */\n\ninterface ParsedPattern {\n cmd: string\n /** Arg-position match tokens. Each may end with `*` for prefix match. */\n parts: string[]\n /** Set when the pattern ends with `:*`, allowing arbitrary further args. */\n trailingWildcard: boolean\n}\n\n/** Combine two verdicts: deny dominates, ask beats allow. */\nfunction combine(a: Verdict, b: Verdict): Verdict {\n if (a === \"deny\" || b === \"deny\") return \"deny\"\n if (a === \"ask\" || b === \"ask\") return \"ask\"\n return \"allow\"\n}\n\nconst patternCache = new Map<string, ParsedPattern>()\n\nfunction parsePattern(pattern: string): ParsedPattern {\n const cached = patternCache.get(pattern)\n if (cached) return cached\n\n let body = pattern.trim()\n let trailingWildcard = false\n if (body.endsWith(\":*\")) {\n trailingWildcard = true\n body = body.slice(0, -2)\n }\n\n const tokens = body.split(/\\s+/).filter((s) => s.length > 0)\n const cmd = tokens[0] ?? \"\"\n const result: ParsedPattern = {\n cmd,\n parts: tokens.slice(1),\n trailingWildcard,\n }\n patternCache.set(pattern, result)\n return result\n}\n\nfunction matchPart(part: string, value: string): boolean {\n if (part.endsWith(\"*\")) {\n return value.startsWith(part.slice(0, -1))\n }\n return part === value\n}\n\n/** Test whether a parsed segment matches a rule pattern. */\nexport function matchRule(rule: Rule, seg: Segment): boolean {\n const p = parsePattern(rule.pattern)\n // Bare `*` (e.g. from a `Bash` rule with no parens) matches any command.\n if (p.cmd === \"*\" && p.parts.length === 0) return true\n if (p.cmd !== seg.cmd) return false\n if (seg.args.length < p.parts.length) return false\n for (let i = 0; i < p.parts.length; i++) {\n if (!matchPart(p.parts[i], seg.args[i])) return false\n }\n if (p.trailingWildcard) return true\n return seg.args.length === p.parts.length\n}\n\n/** First-match-wins resolution. Returns `undefined` if no rule matches. */\nfunction resolveRules(rules: readonly Rule[], seg: Segment): Verdict | undefined {\n for (const r of rules) {\n if (matchRule(r, seg)) return r.policy\n }\n return undefined\n}\n","// A simple implementation of make-array\nfunction makeArray (subject) {\n return Array.isArray(subject)\n ? subject\n : [subject]\n}\n\nconst UNDEFINED = undefined\nconst EMPTY = ''\nconst SPACE = ' '\nconst ESCAPE = '\\\\'\n\n// The characters that carry a meaning of their own inside a regular\n// expression, so a literal one has to be escaped before it is emitted.\nconst REGEX_LITERAL_SPECIAL = /[.*+?()[\\]{}^$|\\\\/]/\n// A line of only spaces is blank -- the trailing-space trimming empties it --\n// but a line holding a tab is a pattern for a tab-named path, since git\n// never trims a tab.\nconst REGEX_TEST_BLANK_LINE = /^ +$/\nconst REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\\\]|^)\\\\$/\nconst REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\\\!/\nconst REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\\\#/\nconst REGEX_SPLITALL_CRLF = /\\r?\\n/g\n\n// Invalid:\n// - /foo,\n// - ./foo,\n// - ../foo,\n// - .\n// - ..\n// Valid:\n// - .foo\nconst DOUBLE_SLASH = '//'\nconst SLASH_CODE = 47\nconst DOT_CODE = 46\n\n\nconst SLASH = '/'\n\n// Do not use ternary expression here, since \"istanbul ignore next\" is buggy\nlet TMP_KEY_IGNORE = 'node-ignore'\n/* istanbul ignore else */\nif (typeof Symbol !== 'undefined') {\n TMP_KEY_IGNORE = Symbol.for('node-ignore')\n}\nconst KEY_IGNORE = TMP_KEY_IGNORE\n\nconst define = (object, key, value) => {\n Object.defineProperty(object, key, {value})\n return value\n}\n\nconst RETURN_FALSE = () => false\n\n// See fixtures #59\nconst cleanRangeBackSlash = slashes => {\n const {length} = slashes\n return slashes.slice(0, length - length % 2)\n}\n\n// > The range notation, e.g. [a-zA-Z],\n// > can be used to match one of the characters in a range.\n//\n// gitignore(5) defers to fnmatch(3) for this, and git implements it in\n// `wildmatch.c`. A bracket expression has a sub-grammar of its own, which\n// is neither the surrounding pattern grammar nor the JavaScript one:\n//\n// - a `]` right after `[` or `[!` is a literal member, not the terminator\n// - `[:alpha:]` names one of twelve POSIX classes\n// - `\\` escapes the next member, `]` included\n// - `*`, `?` and `.` are plain literal members\n// - an unterminated expression makes the whole pattern match nothing\n//\n// which means the expression can not be located -- let alone translated -- by\n// a regular expression. It is scanned out of the pattern before the\n// replacers below run, and put back once they are done, so that neither the\n// metacharacter escaper nor the `?` / `*` replacers ever see its body.\n\n// git classifies with its own ASCII-only ctype macros (`wildmatch.c`), never\n// with the C library ones, so these must not be mapped onto `\\d` / `\\w` /\n// `\\s`, which are wider. `/` is left out of every expansion, because a\n// bracket expression never matches a path separator.\nconst POSIX_CLASSES = {\n alnum: '0-9A-Za-z',\n alpha: 'A-Za-z',\n blank: ' \\\\t',\n cntrl: '\\\\x00-\\\\x1f\\\\x7f',\n digit: '0-9',\n graph: '!-.0-~',\n lower: 'a-z',\n print: ' -.0-~',\n punct: '!-.:-@\\\\[-`{-~',\n // git's `sane-ctype.h` classifies \\v and \\f as control, not space,\n // unlike C's `isspace`\n space: ' \\\\t\\\\n\\\\r',\n upper: 'A-Z',\n xdigit: '0-9A-Fa-f'\n}\n\nconst CLASS_MEMBERS_TO_ESCAPE = '\\\\]^-['\n\nconst escapeMember = char => CLASS_MEMBERS_TO_ESCAPE.indexOf(char) < 0\n ? char\n : ESCAPE + char\n\n// > if (matched == negated || ((flags & WM_PATHNAME) && text_ch == '/'))\n// > return WM_ABORT_TO_STARSTAR; (git, `wildmatch.c`)\n// A bracket expression never matches a path separator, whatever its members\n// say, so a negated class gets `/` as one more excluded character, while a\n// plain one -- where a literal member or a range could still let `/` in --\n// is guarded with a lookahead, `/` being impossible to subtract from a\n// JavaScript character class.\nconst NON_SLASH = '(?!\\\\/)'\n\nconst classSource = (negated, body) => {\n if (negated) {\n return `[^\\\\/${body}]`\n }\n\n const source = `[${body}]`\n\n return new RegExp(source).test('/')\n ? NON_SLASH + source\n : source\n}\n\n// Scan the bracket expression that starts at `pattern[start] === '['`,\n// mirroring the member loop of git's `wildmatch.c`.\n// @returns {{end: number, source: string} | null} `null` if the expression is\n// never terminated, which makes the whole pattern match nothing.\nconst scanBracket = (pattern, start) => {\n const {length} = pattern\n let index = start + 1\n let negated = EMPTY\n\n const lead = pattern[index]\n if (lead === '!' || lead === '^') {\n negated = '^'\n index ++\n }\n\n let body = EMPTY\n\n // The member a `-` could start a range from, or EMPTY when the previous\n // member can not open one (start of the body, or a range / POSIX class\n // that has just closed)\n let prev = EMPTY\n\n // git scans the members with a do-while, so the first one is consumed\n // unconditionally. That is the whole reason a leading `]` is a member\n // and not the terminator.\n for (;;) {\n const char = pattern[index]\n\n if (char === UNDEFINED) {\n return null\n }\n\n if (char === ESCAPE) {\n const escaped = pattern[index + 1]\n if (escaped === UNDEFINED) {\n return null\n }\n body += escapeMember(escaped)\n prev = escaped\n index ++\n } else if (\n char === '-'\n && prev\n && index + 1 < length\n && pattern[index + 1] !== ']'\n ) {\n index ++\n let to = pattern[index]\n if (to === ESCAPE) {\n // A pattern can not end on a lone backslash -- `checkPattern` has\n // already thrown it away -- so there is an upper bound to read.\n to = pattern[index += 1]\n }\n // An out-of-order range matches nothing in git but is a syntax error in\n // JavaScript, so it is dropped. Its lower bound stays: git tests it\n // as a plain member before it ever looks at the `-`, so `[c-a]` does\n // match `c`.\n if (prev <= to) {\n body += `-${escapeMember(to)}`\n }\n prev = EMPTY\n } else if (char === '[' && pattern[index + 1] === ':') {\n const nameStart = index + 2\n let end = nameStart\n while (end < length && pattern[end] !== ']') {\n end ++\n }\n\n if (end === length) {\n return null\n }\n\n if (end > nameStart && pattern[end - 1] === ':') {\n const expanded = POSIX_CLASSES[pattern.slice(nameStart, end - 1)]\n\n // An unknown class name makes the whole pattern match nothing\n if (expanded === UNDEFINED) {\n return null\n }\n\n body += expanded\n prev = EMPTY\n index = end\n } else {\n // No `:]` to close it, so the `[` is a plain member and scanning\n // resumes right after it.\n body += escapeMember('[')\n prev = '['\n index = nameStart - 2\n }\n } else {\n body += escapeMember(char)\n prev = char\n }\n\n index ++\n\n if (pattern[index] === ']') {\n return {\n end: index,\n source: classSource(negated, body)\n }\n }\n }\n}\n\n// An empty JavaScript class can never match, which is how a pattern that git\n// gives up on (`WM_ABORT_ALL`) is expressed here.\nconst NEVER_MATCH = '[]'\n\n// A NUL can appear in neither a `.gitignore` line nor a path, which makes it\n// the one safe placeholder character. A literal one in the pattern is\n// held aside all the same, so a collision is impossible by construction.\nconst PLACEHOLDER = '\\u0000'\nconst REGEX_RESTORE_PLACEHOLDER = new RegExp(\n `${PLACEHOLDER}(\\\\d+)${PLACEHOLDER}`, 'g'\n)\n\n// The one wildcard the chain does not expand for itself is a trailing `*`. How\n// it expands depends on the mode (`regex` vs `checkRegex`), so `_make` is\n// left to do it, and until then the pending wildcard travels as this marker.\n// That is what keeps it apart from a user-escaped literal `\\*`: the unescape\n// steps collapse the escaped one to the exact `\\*` a wildcard would leave\n// behind, so by the time `_make` runs the two are otherwise the same string\n// and a literal star gets wrongly rewritten into a wildcard. This marker is a\n// private-use character no compiled pattern carries, and it never survives\n// into a `RegExp` -- `_make` always turns it back into a real wildcard first.\nconst TRAILING_WILDCARD = '\\uE000'\n\n// Replace every bracket expression with a placeholder the replacers below\n// leave alone, and translate it separately.\nconst extractBrackets = pattern => {\n const sources = []\n const hold = source =>\n `${PLACEHOLDER}${sources.push(source) - 1}${PLACEHOLDER}`\n\n const {length} = pattern\n let out = EMPTY\n let index = 0\n\n while (index < length) {\n const char = pattern[index]\n\n if (char === ESCAPE) {\n // > Put a backslash (\"\\\") in front of ... a character to make it literal.\n // (gitignore(5) -> fnmatch(3))\n // A backslash quotes the next character, whatever it is, so `\\d` is a\n // literal `d`, not the regex digit class, and `\\?` is a literal `?`,\n // not a wildcard. Held aside as its literal here, the escape never\n // reaches the replacers below, which would otherwise let `\\d`, `\\b`,\n // `\\1`, `\\/` keep their regular-expression meaning, and would turn a\n // `\\?` into `[^\\/]`.\n //\n // Four escapes are left for the chain, each with dedicated handling it\n // would be wrong to bypass: `\\*` (a literal star, told apart from a\n // wildcard by `TRAILING_WILDCARD` and the wildcard replacers), `\\[`\n // (a literal bracket, the one `[` the bracket replacer still expects),\n // `\\ ` (a quoted trailing space), and `\\\\` (a literal backslash). A\n // lone trailing backslash never reaches here -- `checkPattern` throws\n // it out first.\n const escaped = pattern[index + 1]\n\n if (\n escaped === '*'\n || escaped === '['\n || escaped === SPACE\n || escaped === ESCAPE\n ) {\n out += pattern.slice(index, index + 2)\n } else {\n out += hold(\n REGEX_LITERAL_SPECIAL.test(escaped)\n ? ESCAPE + escaped\n : escaped\n )\n }\n\n index += 2\n } else if (char === PLACEHOLDER) {\n // Hold a literal placeholder character aside as well, so that pattern\n // text can never be mistaken for a placeholder we emitted.\n out += hold(`[${PLACEHOLDER}]`)\n index ++\n } else if (char === '[') {\n const scanned = scanBracket(pattern, index)\n\n if (scanned === null) {\n // git gives up on the whole pattern (`WM_ABORT_ALL`), so whatever\n // follows can not make it match either.\n out += hold(NEVER_MATCH)\n index = length\n } else {\n out += hold(scanned.source)\n index = scanned.end + 1\n }\n } else {\n out += char\n index ++\n }\n }\n\n return {\n source: out,\n sources\n }\n}\n\n// A step of the chain below is normally a `[matcher, replacer]` pair handed\n// to `String.replace`. `DIRECT` marks the ones that are plain string work\n// instead, and take `(source, pattern)`.\n//\n// Anchoring the two ends is exactly that -- a test of one character and a\n// concatenation -- and putting it through the regular expression engine\n// cost a third of this chain for nothing: 167ns where 10ns does the same\n// job. The two are still steps in the same list, in the same places,\n// because their position in the order is part of what they mean.\nconst DIRECT = null\n\n// A separator at the beginning or in the middle of a pattern, as opposed to\n// one at the very end.\nconst REGEX_INNER_SLASH = /\\/(?!$)/\n\n// > If the pattern ends with a slash,\n// > it is removed for the purpose of the following description,\n// > but it would only find a match with a directory.\n// > In other words, foo/ will match a directory foo and paths underneath it,\n// > but will not match a regular file or a symbolic link foo\n// > (this is consistent with the way how pathspec works in general in Git).\n// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'\n// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call\n// you could use option `mark: true` with `glob`\n\n// '`foo/`' should not continue with the '`..`'\n// The chain that turns one gitignore pattern into a regular expression\n// source, in order. A step is either\n//\n// [matcher, replacer] handed to `String.replace`\n// [matcher, replacer, required] the same, but skipped outright unless\n// `required` appears in the string, which\n// the matcher cannot match without\n// [DIRECT, transform] plain string work, taking (source, pattern)\n//\n// The `required` character is only ever a shortcut: finding it does not mean\n// the matcher will match, and not finding it means it cannot. It is there\n// because scanning for one character costs a fraction of running a matcher\n// that then finds nothing -- for the wildcard step, whose `[^\\\\]+`\n// backtracks its way through the whole string before giving up, 11ns\n// against 400ns.\nconst REPLACERS = [\n\n [\n // Remove BOM\n // TODO:\n // Other similar zero-width characters?\n /^\\uFEFF/,\n () => EMPTY,\n '\\uFEFF'\n ],\n\n [\n // A trailing line terminator, left on when a whole file's contents are\n // added as one pattern rather than split into lines. git never sees one\n // -- it reads a `.gitignore` line by line -- so it is not part of the\n // pattern and is dropped here, apart from the trailing-space trimming,\n // which follows git in touching spaces and nothing else.\n /[\\r\\n]+$/,\n () => EMPTY\n ],\n\n // > Trailing spaces are ignored unless they are quoted with backslash (\"\\\")\n [\n // Only spaces, never tabs or other whitespace: git trims a trailing run\n // of `' '` and nothing else (dir.c, `trim_trailing_spaces`, a single\n // `case ' '`), so a pattern ending in a tab keeps it as a literal.\n // (a\\ ) -> (a )\n // (a ) -> (a)\n // (a ) -> (a)\n // (a \\ ) -> (a )\n /((?:\\\\\\\\)*?)(\\\\? +)$/,\n (_, m1, m2) => m1 + (\n m2.indexOf('\\\\') === 0\n ? SPACE\n : EMPTY\n )\n ],\n\n // Replace (\\ ) with ' '\n // Only a space: an escaped tab or other whitespace is already a literal by\n // the time it reaches here, and a bare tab must be left as one, not turned\n // into a space.\n // (\\ ) -> ' '\n // (\\\\ ) -> '\\\\ '\n // (\\\\\\ ) -> '\\\\ '\n [\n /(\\\\+?) /g,\n (_, m1) => {\n const {length} = m1\n return m1.slice(0, length - length % 2) + SPACE\n }\n ],\n\n // Escape metacharacters\n // which is written down by users but means special for regular expressions.\n\n // > There are 12 characters with special meanings:\n // > - the backslash \\,\n // > - the caret ^,\n // > - the dollar sign $,\n // > - the period or dot .,\n // > - the vertical bar or pipe symbol |,\n // > - the question mark ?,\n // > - the asterisk or star *,\n // > - the plus sign +,\n // > - the opening parenthesis (,\n // > - the closing parenthesis ),\n // > - and the opening square bracket [,\n // > - the opening curly brace {,\n // > These special characters are often called \"metacharacters\".\n [\n /[\\\\$.|*+(){^]/g,\n match => `\\\\${match}`\n ],\n\n [\n // > a question mark (?) matches a single character\n /(?!\\\\)\\?/g,\n () => '[^/]',\n '?'\n ],\n\n // leading slash\n [\n\n // > A leading slash matches the beginning of the pathname.\n // > For example, \"/*.c\" matches \"cat-file.c\" but not \"mozilla-sha1/sha1.c\".\n // A leading slash matches the beginning of the pathname\n /^\\//,\n () => '^',\n SLASH\n ],\n\n // replace special metacharacter slash after the leading slash\n [\n /\\//g,\n () => '\\\\/',\n SLASH\n ],\n\n [\n // > A leading \"**\" followed by a slash means match in all directories.\n // > For example, \"**/foo\" matches file or directory \"foo\" anywhere,\n // > the same as pattern \"foo\".\n // > \"**/foo/bar\" matches file or directory \"bar\" anywhere that is directly\n // > under directory \"foo\".\n // Notice that the '*'s have been replaced as '\\\\*'\n /^\\^*(?:\\\\\\*\\\\\\*\\\\\\/)+/,\n\n // '**/foo' <-> 'foo'\n () => '^(?:.*\\\\/)?',\n '*'\n ],\n\n // starting\n [\n // there will be no leading '/'\n // (which has been replaced by section \"leading slash\")\n // If starts with '**', adding a '^' to the regular expression also works\n DIRECT,\n (source, pattern) => {\n // Nothing to anchor to, or already anchored\n if (!source || source[0] === '^') {\n return source\n }\n\n // If has a slash `/` at the beginning or middle\n const anchor = !REGEX_INNER_SLASH.test(pattern)\n // > Prior to 2.22.1\n // > If the pattern does not contain a slash /,\n // > Git treats it as a shell glob pattern\n // Actually, if there is only a trailing slash,\n // git also treats it as a shell glob pattern\n\n // After 2.22.1 (compatible but clearer)\n // > If there is a separator at the beginning or middle (or both)\n // > of the pattern, then the pattern is relative to the directory\n // > level of the particular .gitignore file itself.\n // > Otherwise the pattern may also match at any level below\n // > the .gitignore level.\n ? '(?:^|\\\\/)'\n\n // > Otherwise, Git treats the pattern as a shell glob suitable for\n // > consumption by fnmatch(3)\n : '^'\n\n return anchor + source\n }\n ],\n\n // two globstars\n [\n // Use lookahead assertions so that we could match more than one `'/**'`\n /\\\\\\/\\\\\\*\\\\\\*(?=\\\\\\/|$)/g,\n\n // Zero, one or several directories\n // should not use '*', or it will be replaced by the next replacer\n\n // Check if it is not the last `'/**'`\n (_, index, str) => index + 6 < str.length\n\n // case: /**/ at the end of the pattern, i.e. a trailing `'/**/'`\n // > A trailing `\"/**/\"` (a trailing `\"/**\"` restricted to directories)\n // > matches everything inside, but it should not match the current\n // > folder itself, so it requires at least one directory segment.\n // 'a/**/' matches 'a/b/', 'a/x/y/' but not 'a/'\n ? str.slice(index + 6) === '\\\\/'\n ? '(?:\\\\/[^\\\\/]+)+'\n\n // case: /**/\n // > A slash followed by two consecutive asterisks then a slash matches\n // > zero or more directories.\n // > For example, \"a/**/b\" matches \"a/b\", \"a/x/b\", \"a/x/y/b\" and so on.\n // '/**/'\n : '(?:\\\\/[^\\\\/]+)*'\n\n // case: /**\n // > A trailing `\"/**\"` matches everything inside.\n\n // #21: everything inside but it should not include the current folder\n : '\\\\/.+',\n '*'\n ],\n\n // normal intermediate wildcards\n [\n // Never replace escaped '*'\n // ignore rule '\\*' will match the path '*'\n\n // 'abc.*/' -> go\n // 'abc.*' -> skip this rule,\n // coz trailing single wildcard will be handed by [trailing wildcard]\n /(^|[^\\\\]+)(\\\\\\*)+(?=.+)/g,\n\n // '*.js' matches '.js'\n // '*.js' doesn't match 'abc'\n (_, p1, p2) => {\n // 1.\n // > An asterisk \"*\" matches anything except a slash.\n // 2.\n // > Other consecutive asterisks are considered regular asterisks\n // > and will match according to the previous rules.\n const unescaped = p2.replace(/\\\\\\*/g, '[^\\\\/]*')\n return p1 + unescaped\n },\n '*'\n ],\n\n // trailing wildcard, held apart from a literal star\n [\n // The step above leaves a trailing `*` alone, so a single `\\*` is all that\n // can be left at the end here. Whether it is a wildcard or a literal\n // turns on the backslashes the user put in front of it: the escaper has\n // since doubled every one, so what stands here is those `2N` doubled\n // backslashes and then the star's own escape. An even number of the\n // original `N` leaves the star unescaped -- a wildcard -- and an odd\n // number escapes it -- a literal. This runs while the two are still\n // distinct, before the unescape steps below collapse the literal onto\n // the very `\\*` a wildcard leaves behind.\n /(^|[^\\\\])((?:\\\\\\\\)*)\\\\\\*$/,\n\n (match, p1, p2) =>\n // `p2` holds the doubled user backslashes; half of them is `N`.\n (p2.length / 2) % 2 === 0\n // A real wildcard: carry it to `_make` as the marker, so the unescape\n // steps and the trailing-wildcard rewrite can never mistake it for a\n // literal `\\*` (nor the reverse).\n ? p1 + p2 + TRAILING_WILDCARD\n // A literal star: leave it exactly as it stands for the unescape steps.\n : match,\n '*'\n ],\n\n [\n // unescape, revert step 3 except for back slash\n // For example, if a user escape a '\\\\*',\n // after step 3, the result will be '\\\\\\\\\\\\*'\n /\\\\\\\\\\\\(?=[$.|*+(){^])/g,\n () => ESCAPE,\n ESCAPE + ESCAPE\n ],\n\n [\n // '\\\\\\\\' -> '\\\\'\n /\\\\\\\\/g,\n () => ESCAPE,\n ESCAPE + ESCAPE\n ],\n\n [\n // Every real bracket expression -- POSIX classes included -- has already\n // been held aside by `extractBrackets`, so the only `[` left in the\n // pattern is an escaped, literal one.\n\n // `\\` is escaped by step 3\n /\\\\\\[([^\\]/]*?)(\\\\*)($|\\])/g,\n\n // '\\\\[bar]' -> '\\\\\\\\[bar\\\\]'\n (match, range, endEscape, close) =>\n `\\\\[${range}${cleanRangeBackSlash(endEscape)}${close}`,\n '['\n ],\n\n // ending\n [\n // 'js' will not match 'js.'\n // 'ab' will not match 'abc'\n DIRECT,\n\n // WTF!\n // https://git-scm.com/docs/gitignore\n // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)\n // which re-fixes #24, #38\n\n // > If there is a separator at the end of the pattern then the pattern\n // > will only match directories, otherwise the pattern can match both\n // > files and directories.\n\n // 'js*' will not match 'a.js'\n // 'js/' will not match 'a.js'\n // 'js' will match 'a.js' and 'a.js/'\n source => {\n const last = source[source.length - 1]\n\n // The pattern is empty, or ends in the pending trailing wildcard the next\n // step owns. A trailing `*` that is not the marker is a literal star,\n // which anchors like any other final character.\n if (!last || last === TRAILING_WILDCARD) {\n return source\n }\n\n return last === SLASH\n // foo/ will not match 'foo'\n ? `${source}$`\n // foo matches 'foo' and 'foo/'\n : `${source}(?=$|\\\\/$)`\n }\n ]\n]\n\nconst REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\\\\/)?\\uE000$/\nconst MODE_IGNORE = 'regex'\nconst MODE_CHECK_IGNORE = 'checkRegex'\nconst UNDERSCORE = '_'\n\nconst TRAILING_WILD_CARD_REPLACERS = {\n [MODE_IGNORE] (_, p1) {\n const prefix = p1\n // '\\^':\n // '/*' does not match EMPTY\n // '/*' does not match everything\n\n // '\\\\\\/':\n // 'abc/*' does not match 'abc/'\n ? `${p1}[^/]+`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n },\n\n [MODE_CHECK_IGNORE] (_, p1) {\n // When doing `git check-ignore`\n const prefix = p1\n // '\\\\\\/':\n // 'abc/*' DOES match 'abc/' !\n ? `${p1}[^/]*`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n }\n}\n\nconst WILDCARD = '[^\\\\/]*'\n\n// Where a run of non-slash wildcards is split by single fixed characters --\n// `[^/]*x[^/]*y...` -- the engine has many equivalent ways to lay the\n// input across the wildcards, and on input that does not match it works\n// through all of them, so the time grows with the number of wildcards\n// rather than the length of the path. Every wildcard but the last in such a\n// run can be pinned to stop at the character that follows it, which leaves\n// one way to lay out the input and no rewinding, without changing which\n// paths match: the fixed characters still bound the count, and the last\n// wildcard still absorbs the rest.\n//\n// The source is read one token at a time -- a wildcard, a single-character\n// piece (a literal, an escape, a class), or a parenthesised group or anchor\n// that ends the run -- so only a genuine wildcard is touched.\nconst pinWildcards = source => {\n if (source.indexOf(WILDCARD) < 0) {\n return source\n }\n\n const tokens = []\n const {length} = source\n let index = 0\n\n while (index < length) {\n const char = source[index]\n\n if (source.startsWith(WILDCARD, index)) {\n tokens.push({wildcard: true})\n index += WILDCARD.length\n } else if (char === '[') {\n let end = index + 1\n\n if (source[end] === '^') {\n end ++\n }\n\n if (source[end] === ']') {\n end ++\n }\n\n while (end < length && source[end] !== ']') {\n end += source[end] === ESCAPE\n ? 2\n : 1\n }\n\n end ++\n tokens.push({single: source.slice(index, end)})\n index = end\n } else if (char === ESCAPE) {\n tokens.push({single: source.slice(index, index + 2)})\n index += 2\n } else if (char === '(') {\n let depth = 0\n let end = index\n\n do {\n if (source[end] === ESCAPE) {\n end ++\n } else if (source[end] === '(') {\n depth ++\n } else if (source[end] === ')') {\n depth --\n }\n\n end ++\n } while (end < length && depth > 0)\n\n if ('*+?'.indexOf(source[end]) >= 0) {\n end ++\n }\n\n tokens.push({boundary: source.slice(index, end)})\n index = end\n } else if (char === '^' || char === '$') {\n tokens.push({boundary: char})\n index ++\n } else {\n tokens.push({single: char})\n index ++\n }\n }\n\n let out = EMPTY\n let run = []\n\n const flush = () => {\n let lastWildcard\n\n run.forEach((token, at) => {\n if (token.wildcard) {\n lastWildcard = at\n }\n })\n\n run.forEach((token, at) => {\n if (!token.wildcard) {\n out += token.single\n return\n }\n\n // A wildcard that is not the last in the run is always immediately\n // followed by the single character that separates it from the next\n // one, because a run never holds two wildcards in a row, so it can be\n // pinned to stop there. The last wildcard stays as it is and takes up\n // the rest.\n out += at === lastWildcard\n ? WILDCARD\n : `(?:(?!${run[at + 1].single})[^\\\\/])*`\n })\n\n run = []\n }\n\n tokens.forEach(token => {\n if (token.boundary === undefined) {\n run.push(token)\n return\n }\n\n flush()\n out += token.boundary\n })\n\n flush()\n\n return out\n}\n\n// @param {pattern}\nconst makeRegexPrefix = pattern => {\n const {source, sources} = extractBrackets(pattern)\n\n const replaced = REPLACERS.reduce(\n // A pass whose matcher finds nothing hands back the very string it was\n // given, so asking first costs a search and saves a rewrite. Ten of the\n // fifteen passes never fire for a typical .gitignore line, and between\n // them they were 45% of this chain.\n (prev, [matcher, replacer, required]) => {\n if (matcher === DIRECT) {\n return replacer(prev, pattern)\n }\n\n if (required !== UNDEFINED && prev.indexOf(required) < 0) {\n return prev\n }\n\n // A pass whose matcher finds nothing hands back the very string it was\n // given, so asking first costs a search and saves a rewrite.\n return matcher.test(prev)\n ? prev.replace(matcher, replacer.bind(pattern))\n : prev\n },\n source\n )\n\n // Most patterns hold no bracket expression at all, and then there is\n // nothing to put back.\n return sources.length\n ? replaced.replace(\n REGEX_RESTORE_PLACEHOLDER,\n (match, index) => sources[index]\n )\n : replaced\n}\n\n// A trailing slash does not stop a pattern being basename-only: it restricts\n// the match to a directory, it does not let the pattern reach across one.\n// Everything else a pattern can hold -- a wildcard, a character class, an\n// escape -- stays inside a single path segment too, so a pattern with no\n// separator in it can only ever describe the last one.\nconst matchesBasename = body => {\n const index = body.indexOf(SLASH)\n\n return index < 0 || index === body.length - 1\n}\n\n// The last segment of a path, keeping a trailing slash, because a pattern that\n// ends in one matches only a directory.\n// 'a/b/c.js' -> 'c.js'; 'a/b/' -> 'b/'; 'c.js' -> 'c.js' (no copy made)\nconst basenameOf = path => {\n const end = path.length - 1\n\n const index = path.lastIndexOf(\n SLASH,\n path[end] === SLASH\n ? end - 1\n : end\n )\n\n return index < 0\n ? path\n : path.slice(index + 1)\n}\n\n// The parent directory of a path, with its trailing separator, or EMPTY when\n// the path has none.\n// 'a/b/c' -> 'a/b/'; 'a/b/' -> 'a/'; 'a' -> EMPTY; 'a/' -> EMPTY\n//\n// A path holding an empty segment has to be taken apart, because its\n// ancestors are not prefixes of it: the parent of 'a//b' is 'a/', not\n// 'a//', and the parent of '/a/' is nothing at all. Both shapes reach here\n// -- 'a//b' is accepted outright, and `checkIgnore` does not put the path\n// it is given through the relative-path check.\n//\n// Every other path is a prefix of itself, and cutting one costs a fraction of\n// splitting it into an array and joining that back at every level: 73ns\n// against 207ns.\nconst parentOf = path => {\n if (\n path.charCodeAt(0) === SLASH_CODE\n || path.indexOf(DOUBLE_SLASH) >= 0\n ) {\n const slices = path.split(SLASH).filter(Boolean)\n\n slices.pop()\n\n return slices.length\n ? slices.join(SLASH) + SLASH\n : EMPTY\n }\n\n const end = path.length - 1\n\n // Look back from before a trailing separator, since that one belongs to the\n // path itself.\n //\n // A negative place to start would be a trap here: `lastIndexOf` clamps one\n // to 0 and searches there rather than reporting no match, so '/' would\n // come back as its own parent and the walk would never end. It cannot\n // happen -- that is the only path short enough to produce one, and the\n // test above has already sent it the other way.\n const cut = path.lastIndexOf(\n SLASH,\n path.charCodeAt(end) === SLASH_CODE\n ? end - 1\n : end\n )\n\n return cut < 0\n ? EMPTY\n : path.slice(0, cut + 1)\n}\n\nconst isString = subject => typeof subject === 'string'\n\n// > A blank line matches no files, so it can serve as a separator for readability.\nconst checkPattern = pattern => pattern\n && isString(pattern)\n && !REGEX_TEST_BLANK_LINE.test(pattern)\n && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)\n\n // > A line starting with # serves as a comment.\n && pattern.indexOf('#') !== 0\n\nconst splitPattern = pattern => pattern\n.split(REGEX_SPLITALL_CRLF)\n.filter(Boolean)\n\nclass IgnoreRule {\n constructor (\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n prefix\n ) {\n this.pattern = pattern\n this.mark = mark\n this.negative = negative\n\n define(this, 'body', body)\n define(this, 'ignoreCase', ignoreCase)\n define(this, 'regexPrefix', prefix)\n }\n\n // Worked out on first use and kept behind an own property, the way `regex`\n // caches itself in `_regex`. Deciding it in the constructor instead would\n // add a fourth `defineProperty` to every rule ever built, which cost 4% of\n // every compile -- including the compiles of rules that are never matched\n // against anything.\n get _basenameOnly () {\n return define(this, '_basenameOnly', matchesBasename(this.body))\n }\n\n get regex () {\n const key = UNDERSCORE + MODE_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_IGNORE, key)\n }\n\n get checkRegex () {\n const key = UNDERSCORE + MODE_CHECK_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_CHECK_IGNORE, key)\n }\n\n _make (mode, key) {\n const str = pinWildcards(this.regexPrefix.replace(\n REGEX_REPLACE_TRAILING_WILDCARD,\n\n // It does not need to bind pattern\n TRAILING_WILD_CARD_REPLACERS[mode]\n ))\n\n const regex = this.ignoreCase\n ? new RegExp(str, 'i')\n : new RegExp(str)\n\n return define(this, key, regex)\n }\n}\n\nconst createRule = ({\n pattern,\n mark\n}, ignoreCase) => {\n let negative = false\n let body = pattern\n\n // > An optional prefix \"!\" which negates the pattern;\n if (body.indexOf('!') === 0) {\n negative = true\n body = body.substr(1)\n }\n\n body = body\n // > Put a backslash (\"\\\") in front of the first \"!\" for patterns that\n // > begin with a literal \"!\", for example, `\"\\!important!.txt\"`.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')\n // > Put a backslash (\"\\\") in front of the first hash for patterns that\n // > begin with a hash.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')\n\n const regexPrefix = makeRegexPrefix(body)\n\n return new IgnoreRule(\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n regexPrefix\n )\n}\n\nclass RuleManager {\n constructor (ignoreCase) {\n this._ignoreCase = ignoreCase\n this._rules = []\n\n // How many of the rules git would tag `EXC_FLAG_NODIR`.\n //\n // The scan uses it to decide, once for the whole set, whether handing\n // those rules the basename is worth what it costs the others. The\n // shortcut saves a full-path scan on every rule it applies to and costs\n // a check on every rule it does not, so a set where almost nothing is\n // basename-only comes out behind -- a 955 pattern set with 44 of them\n // measured 19% slower with the shortcut always on.\n //\n // Deciding this by measurement rather than by meaning is safe: a\n // basename-only pattern gives the very same answer against the whole\n // path, it just takes longer to say so. The choice can only change how\n // fast the scan runs, never what it returns.\n this._basenameCount = 0\n }\n\n _add (pattern) {\n // #32\n if (pattern && pattern[KEY_IGNORE]) {\n this._rules = this._rules.concat(pattern._rules._rules)\n this._basenameCount += pattern._rules._basenameCount\n this._added = true\n return\n }\n\n if (isString(pattern)) {\n pattern = {\n pattern\n }\n }\n\n if (checkPattern(pattern.pattern)) {\n const rule = createRule(pattern, this._ignoreCase)\n this._added = true\n this._rules.push(rule)\n\n // Deliberately not `rule._basenameOnly`: reading that would materialise\n // the rule's own copy, and the whole point of leaving it lazy is that\n // a rule which is compiled and never matched never pays for it.\n if (matchesBasename(rule.body)) {\n this._basenameCount ++\n }\n }\n }\n\n // @param {Array<string> | string | Ignore} pattern\n add (pattern) {\n this._added = false\n\n makeArray(\n isString(pattern)\n ? splitPattern(pattern)\n : pattern\n ).forEach(this._add, this)\n\n return this._added\n }\n\n // Test one single path without recursively checking parent directories\n //\n // - checkUnignored `boolean` whether should check if the path is unignored,\n // setting `checkUnignored` to `false` could reduce additional\n // path matching.\n // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`\n\n // @returns {TestResult} true if a file is ignored\n test (path, checkUnignored, mode) {\n let ignored = false\n let unignored = false\n let matchedRule\n\n // Most of a .gitignore is patterns with no slash in them, and running\n // those against the whole path makes the regular expression engine walk\n // every directory name on the way to the only segment that could match.\n // Handing them the basename instead is what git does, and it is where\n // the time in a directory walk goes: the rule scan was two thirds of it.\n const rules = this._rules\n const {length} = rules\n\n const shortcut = this._basenameCount * 2 >= length\n\n const basename = shortcut\n ? basenameOf(path)\n : path\n\n // A plain loop rather than `forEach`, so that `path`, `basename` and\n // `shortcut` are locals. As a callback they became closure variables,\n // and reaching for one of those once per rule cost 10% of a scan over a\n // large rule set -- more than the shortcut they were there to serve.\n for (let index = 0; index < length; index ++) {\n const rule = rules[index]\n const {negative} = rule\n\n // | ignored : unignored\n // -------- | ---------------------------------------\n // negative | 0:0 | 0:1 | 1:0 | 1:1\n // -------- | ------- | ------- | ------- | --------\n // 0 | TEST | TEST | SKIP | X\n // 1 | TESTIF | SKIP | TEST | X\n\n // - SKIP: always skip\n // - TEST: always test\n // - TESTIF: only test if checkUnignored\n // - X: that never happen\n const skip = unignored === negative && ignored !== unignored\n || negative && !ignored && !unignored && !checkUnignored\n\n if (!skip && rule[mode].test(\n shortcut && rule._basenameOnly\n ? basename\n : path\n )) {\n ignored = !negative\n unignored = negative\n\n matchedRule = negative\n ? UNDEFINED\n : rule\n }\n }\n\n const ret = {\n ignored,\n unignored\n }\n\n if (matchedRule) {\n ret.rule = matchedRule\n }\n\n return ret\n }\n}\n\nconst throwError = (message, Ctor) => {\n throw new Ctor(message)\n}\n\nconst checkPath = (path, originalPath, doThrow) => {\n if (!isString(path)) {\n return doThrow(\n `path must be a string, but got \\`${originalPath}\\``,\n TypeError\n )\n }\n\n // We don't know if we should ignore EMPTY, so throw\n if (!path) {\n return doThrow(`path must not be empty`, TypeError)\n }\n\n // Check if it is a relative path\n if (checkPath.isNotRelative(path)) {\n const r = '`path.relative()`d'\n return doThrow(\n `path should be a ${r} string, but got \"${originalPath}\"`,\n RangeError\n )\n }\n\n return true\n}\n\n// > pathname should be a `path.relative()`d one\n//\n// The same thing `REGEX_TEST_INVALID_PATH` says, spelled out: a path is not\n// relative if it begins with a separator, or with `./` or `../`, or is\n// nothing but `.` or `..`. Every match is decided by the first three\n// characters, and this runs on every path handed to the library -- where it\n// was 55% of a cached lookup, more than the cache lookup itself.\nconst isNotRelative = path => {\n const first = path.charCodeAt(0)\n\n if (first === SLASH_CODE) {\n return true\n }\n\n if (first !== DOT_CODE) {\n return false\n }\n\n // '.'\n if (path.length === 1) {\n return true\n }\n\n const second = path.charCodeAt(1)\n\n // './'\n if (second === SLASH_CODE) {\n return true\n }\n\n if (second !== DOT_CODE) {\n return false\n }\n\n // '..' or '../'\n return path.length === 2 || path.charCodeAt(2) === SLASH_CODE\n}\n\ncheckPath.isNotRelative = isNotRelative\n\n// On windows, the following function will be replaced\n/* istanbul ignore next */\ncheckPath.convert = p => p\n\n\nclass Ignore {\n constructor ({\n ignorecase = true,\n ignoreCase = ignorecase,\n allowRelativePaths = false\n } = {}) {\n define(this, KEY_IGNORE, true)\n\n this._rules = new RuleManager(ignoreCase)\n this._strictPathCheck = !allowRelativePaths\n this._initCache()\n }\n\n _initCache () {\n // A cache for the result of `.ignores()`\n this._ignoreCache = Object.create(null)\n\n // A cache for the result of `.test()`\n this._testCache = Object.create(null)\n }\n\n add (pattern) {\n if (this._rules.add(pattern)) {\n // Some rules have just added to the ignore,\n // making the behavior changed,\n // so we need to re-initialize the result cache\n this._initCache()\n }\n\n return this\n }\n\n // legacy\n addPattern (pattern) {\n return this.add(pattern)\n }\n\n // @returns {TestResult}\n _test (originalPath, cache, checkUnignored) {\n const path = originalPath\n // Supports nullable path\n && checkPath.convert(originalPath)\n\n checkPath(\n path,\n originalPath,\n this._strictPathCheck\n ? throwError\n : RETURN_FALSE\n )\n\n return this._t(path, cache, checkUnignored)\n }\n\n checkIgnore (path) {\n // If the path doest not end with a slash, `.ignores()` is much equivalent\n // to `git check-ignore`\n if (path.charCodeAt(path.length - 1) !== SLASH_CODE) {\n return this.test(path)\n }\n\n const parentPath = parentOf(path)\n\n if (parentPath) {\n const parent = this._t(parentPath, this._testCache, true)\n\n if (parent.ignored) {\n return parent\n }\n }\n\n return this._rules.test(path, false, MODE_CHECK_IGNORE)\n }\n\n _t (\n // The path to be tested\n path,\n\n // The cache for the result of a certain checking\n cache,\n\n // Whether should check if the path is unignored\n checkUnignored\n ) {\n if (path in cache) {\n return cache[path]\n }\n\n const parentPath = parentOf(path)\n\n // If the path contains a parent directory, check the parent first\n const parent = parentPath\n ? this._t(parentPath, cache, checkUnignored)\n : UNDEFINED\n\n return cache[path] = parent && parent.ignored\n // > It is not possible to re-include a file if a parent directory of\n // > that file is excluded.\n ? parent\n : this._rules.test(path, checkUnignored, MODE_IGNORE)\n }\n\n ignores (path) {\n return this._test(path, this._ignoreCache, false).ignored\n }\n\n createFilter () {\n return path => !this.ignores(path)\n }\n\n filter (paths) {\n return makeArray(paths).filter(this.createFilter())\n }\n\n // @returns {TestResult}\n test (path) {\n return this._test(path, this._testCache, true)\n }\n}\n\nconst factory = options => new Ignore(options)\n\nconst isPathValid = path =>\n checkPath(path && checkPath.convert(path), path, RETURN_FALSE)\n\n/* istanbul ignore next */\nconst setupWindows = () => {\n /* eslint no-control-regex: \"off\" */\n const makePosix = str => /^\\\\\\\\\\?\\\\/.test(str)\n || /[\"<>|\\u0000-\\u001F]+/u.test(str)\n ? str\n : str.replace(/\\\\/g, '/')\n\n checkPath.convert = makePosix\n\n // 'C:\\\\foo' <- 'C:\\\\foo' has been converted to 'C:/'\n // 'd:\\\\foo'\n const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\\//i\n checkPath.isNotRelative = path =>\n REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path)\n || isNotRelative(path)\n}\n\n\n// Windows\n// --------------------------------------------------------------\n/* istanbul ignore next */\nif (\n // Detect `process` so that it can run in browsers.\n typeof process !== 'undefined'\n && process.platform === 'win32'\n) {\n setupWindows()\n}\n\n// COMMONJS_EXPORTS ////////////////////////////////////////////////////////////\n\nmodule.exports = factory\n\n// Although it is an anti-pattern,\n// it is still widely misused by a lot of libraries in github\n// Ref: https://github.com/search?q=ignore.default%28%29&type=code\nfactory.default = factory\n\nmodule.exports.isPathValid = isPathValid\n\n// For testing purposes\ndefine(module.exports, Symbol.for('setupWindows'), setupWindows)\n","import type { CheckResult, PermissionHandler, Rule } from \"../types.ts\"\n\nimport { normPath, prettyPath } from \"@zaly/shared\"\nimport ignore from \"ignore\"\nimport { dirname, isAbsolute, relative } from \"pathe\"\n\n/**\n * Handler for `Rule<\"read\" | \"write\">` — one impl serves both scopes\n * because they share the same matcher and the same workspace state.\n *\n * Algorithm:\n * 1. Normalize candidate to an absolute path.\n * 2. Sensitive-file check (env, ssh keys, credentials) → deny.\n * 3. Find the longest-prefix workspace containing the path. None →\n * ask, with a `kind: \"workspace\"` suggestion for the containing\n * directory.\n * 4. Inside a workspace: resolve the first matching rule against the\n * workspace-relative path. Earlier rules win.\n * 5. Default when no rule matches but the path is inside a workspace:\n * `allow` for reads (workspace = trust signal), `ask` for writes\n * (mutating ops escalate by default; users add `Write(...)` rules\n * to whitelist).\n *\n * Pattern grammar (per Claude-Code conventions):\n * //abs/path absolute filesystem path\n * ~/path path under home directory\n * /path or path workspace-relative (passed through to gitignore)\n */\nexport const fileHandler: PermissionHandler<\"read\" | \"write\"> = {\n validate(input, ctx): CheckResult {\n const abs = normPath(ctx.cwd, input)\n\n if (isSensitiveFile(abs)) {\n return { reason: `${abs}: sensitive file`, verdict: \"deny\" }\n }\n\n const ws = longestWorkspace(abs, ctx.workspaces)\n const inWorkspace = ws !== undefined\n\n // Inside-workspace + path === root: the workspace itself (e.g. `find .`\n // resolved to cwd). Workspace containment alone is enough to allow.\n if (inWorkspace && abs === ws) return { verdict: \"allow\" }\n\n // Outside any workspace, fall through to rule matching with `/` as\n // synthetic root. Lets blanket rules like `read(*)` (yolo preset)\n // override the default \"ask outside workspace\" verdict, while\n // narrower presets keep the safer default.\n const base = ws ?? \"/\"\n const rel = relative(base, abs)\n\n const verb = ctx.scope === \"read\" ? \"reading\" : \"writing\"\n\n const rule = resolveRule(base, rel, ctx.rules)\n if (rule?.policy === \"deny\") return { reason: `${abs}: denied by rule`, verdict: \"deny\" }\n if (rule?.policy === \"ask\") {\n return {\n ask: `Allow ${verb} ${prettyPath(abs)}?`,\n reason: `${abs}: rule requires confirmation`,\n suggestions: [{ kind: \"rule\", pattern: `/${rel}`, scope: ctx.scope }],\n verdict: \"ask\",\n }\n }\n if (rule?.policy === \"allow\") return { verdict: \"allow\" }\n\n // No rule matched. Defaults differ by location:\n // - Inside a workspace: reads ride on workspace trust → allow;\n // writes escalate → ask.\n // - Outside any workspace: always ask, and surface a\n // workspace-add suggestion so the user can promote the parent\n // dir without composing a rule by hand.\n if (!inWorkspace) {\n const parent = dirname(abs)\n return {\n ask: `Allow ${verb} ${prettyPath(abs)}? (not in any workspace)`,\n reason: `${abs}: outside any workspace`,\n suggestions: [\n { description: `add ${parent} as workspace`, kind: \"workspace\", path: parent },\n ],\n verdict: \"ask\",\n }\n }\n if (ctx.scope === \"read\") return { verdict: \"allow\" }\n return {\n ask: `Allow ${verb} ${prettyPath(abs)}?`,\n reason: `${abs}: write requires confirmation`,\n suggestions: [{ kind: \"rule\", pattern: `/${rel}`, scope: \"write\" }],\n verdict: \"ask\",\n }\n },\n}\n\n/** True if `path` looks like a credentials/keys file we shouldn't\n * expose to the model by default. Conservative — false positives are\n * fine here, and users can override via `allow` rules. */\nexport function isSensitiveFile(path: string): boolean {\n return SENSITIVE_PATTERNS.some((re) => re.test(path))\n}\n\n/** Common locations for credentials, keys, and other sensitive data.\n * Matched against the path string directly — covers both absolute and\n * relative inputs. Add to this list as new gotchas surface. */\nconst SENSITIVE_PATTERNS: RegExp[] = [\n /(?:^|\\/)\\.env(?:\\.|$)/, // .env, .env.local, .env.production, ...\n /(?:^|\\/)\\.git\\/(?!hooks\\/)/, // .git/* but not hooks (commonly inspected)\n /(?:^|\\/)\\.ssh\\//, // ssh keys + config\n /(?:^|\\/)\\.aws\\/credentials/,\n /(?:^|\\/)\\.netrc$/,\n /(?:^|\\/)id_(?:rsa|dsa|ed25519|ecdsa)(?:\\.pub)?$/,\n /(?:^|\\/)\\.npmrc$/, // can hold auth tokens\n /(?:^|\\/)\\.pypirc$/,\n /(?:^|\\/)secrets?\\//,\n /(?:^|\\/)credentials?(?:\\.|\\/)/,\n]\n\n/** Longest-prefix match against the workspace list — returns the\n * containing workspace's absolute path, or undefined if none contain\n * the candidate. Workspaces arrive pre-normalized from the manager. */\nfunction longestWorkspace(abs: string, workspaces: readonly string[]): string | undefined {\n let best: string | undefined\n for (const root of workspaces) {\n if (abs === root || abs.startsWith(root.endsWith(\"/\") ? root : `${root}/`)) {\n if (best === undefined || root.length > best.length) best = root\n }\n }\n return best\n}\n\n/** Resolve the first matching rule.\n * Patterns get normalized (`//abs`, `~/`, `/rel`, `rel`) into\n * workspace-rooted gitignore syntax; patterns that resolve outside the\n * candidate's workspace are dropped (they don't apply here). */\nfunction resolveRule(\n workspace: string,\n rel: string,\n rules: readonly Rule<\"read\" | \"write\">[]\n): Rule<\"read\" | \"write\"> | undefined {\n if (rel === \"\") return undefined\n for (const rule of rules) {\n const norm = normalizePattern(rule.pattern, workspace)\n if (norm === undefined) continue\n try {\n if (ignore().add(norm).ignores(rel)) return rule\n } catch {\n // Skip invalid rels.\n }\n }\n}\n\nfunction normalizePattern(pattern: string, workspace: string): string | undefined {\n if (pattern.startsWith(\"//\")) {\n return relativizeToWorkspace(pattern.slice(1), workspace)\n }\n if (pattern.startsWith(\"~/\")) {\n return relativizeToWorkspace(normPath(pattern), workspace)\n }\n // /pattern or pattern → already workspace-relative gitignore syntax.\n return pattern\n}\n\nfunction relativizeToWorkspace(absPattern: string, workspace: string): string | undefined {\n const rel = relative(workspace, absPattern)\n if (rel === \"\" || rel.startsWith(\"..\") || isAbsolute(rel)) return undefined\n return `/${rel}`\n}\n","import type { CheckResult, PermissionHandler, Rule } from \"../types.ts\"\n\nimport ignore from \"ignore\"\n\n/**\n * Generic tool-scope handler.\n *\n * Used by `Tasks` to gate every tool dispatch on the tool name, and\n * available to tools themselves for richer checks (e.g. fetch passing\n * `fetch:example.com` so users can ask-for-domain).\n *\n * Pattern grammar is gitignore-style — reuses the `ignore` package so\n * the syntax matches `read` / `write` patterns. Common shapes:\n *\n * \"tool\" → bare scope; matches every input (default-allow)\n * \"tool(bash)\" → exact match for `\"bash\"`\n * \"tool(fetch:*)\" → glob match `\"fetch:...\"`\n * \"tool(task_*)\" → glob match `\"task_...\"`\n *\n * Resolution is first-match-wins. Default verdict when no rule matches is\n * `allow` — an unconfigured `tool` scope should not surprise users by\n * gating ordinary tool calls.\n */\nexport const toolHandler: PermissionHandler<\"tool\"> = {\n validate(input, ctx): CheckResult {\n const rule = resolveRule(input, ctx.rules)\n if (rule?.policy === \"deny\") {\n return { reason: `tool ${input}: denied by rule`, verdict: \"deny\" }\n }\n if (rule?.policy === \"ask\") {\n return {\n ask: `Allow tool ${input}?`,\n reason: `tool ${input}: rule requires confirmation`,\n suggestions: [{ kind: \"rule\", pattern: input, scope: \"tool\" }],\n verdict: \"ask\",\n }\n }\n return { verdict: \"allow\" }\n },\n}\n\nfunction resolveRule(input: string, rules: readonly Rule<\"tool\">[]): Rule<\"tool\"> | undefined {\n for (const rule of rules) {\n if (ignore().add(rule.pattern).ignores(input)) return rule\n }\n}\n","import type { PermissionHandler } from \"../types.ts\"\n\nimport { createRegistry } from \"@zaly/shared/registry\"\nimport { bashHandler } from \"./bash.ts\"\nimport { fileHandler } from \"./files.ts\"\nimport { toolHandler } from \"./tool.ts\"\n\nexport type HandlerLoader = () => PermissionHandler<string>\n\nconst builtin = {\n bash: () => bashHandler,\n read: () => fileHandler,\n tool: () => toolHandler,\n write: () => fileHandler,\n} as const satisfies Record<string, HandlerLoader>\n\n/** Open registry of permission scopes — declaration-merge to add your\n * own. The keys give `ctx.need(\"…\", input)` typed autocomplete and\n * catch typos at compile time. The value carries the *input* type for\n * that scope (almost always `string` — files take paths, bash takes\n * commands, the generic `tool` scope takes the tool name).\n *\n * Built-ins:\n * - `bash` → command string\n * - `read` → absolute path\n * - `write` → absolute path\n * - `tool` → tool name (or richer `name:arg` shape per tool)\n *\n * Add your own scope:\n *\n * ```ts\n * declare module \"@zaly/agent\" {\n * interface PermissionScopes {\n * fetch: string // expects a domain (or \"*\" for any)\n * }\n * }\n * ```\n *\n * Then `ctx.need(\"fetch\", domain)` is typed end-to-end. You still need\n * to register a runtime handler via `handlerRegistry.register(\"fetch\", …)`\n * — this interface is only the type-side declaration.\n */\nexport interface PermissionScopes {\n bash: string\n read: string\n tool: string\n write: string\n}\n\nexport type BuiltinScope = keyof typeof builtin\nexport type PermissionScope = keyof PermissionScopes\nexport type AnyScope = PermissionScope | (string & {})\n\nexport const handlerRegistry = createRegistry<HandlerLoader>(\"scope\").from(builtin)\n"],"x_google_ignoreList":[1],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,cAAyC,EACpD,SAAS,OAAO,KAAkB;CAChC,MAAM,SAAS,UAAU,KAAK;CAC9B,IAAI,CAAC,OAAO,IACV,OAAO;EACL,KAAK,6BAA6B,OAAO,OAAO;EAChD,QAAQ,OAAO;EACf,SAAS;CACX;CAGF,IAAI,UAAmB;CACvB,IAAI;CACJ,MAAM,cAA4B,CAAC;CAEnC,KAAK,MAAM,OAAO,OAAO,UAAU;EAIjC,MAAM,aAAa,aAAa,IAAI,OAAO,GAAG,KAAK;EACnD,IAAI,IAAI,mBAAmB,eAAe,SACxC,OAAO;GACL,KAAK,mCAAmC,IAAI,IAAI;GAChD,QAAQ;GACR,SAAS;EACX;EAEF,MAAM,OAAO,MAAM,IAAI;EACvB,IAAI,MAAM,SAAS,IA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AAS,OAAO,KAAkB;CAChC,MAAM,OAAO,YAAY,OAAO,IAAI,KAAK;CACzC,IAAI,MAAM,WAAW,QACnB,OAAO;EAAE,QAAQ,QAAQ,MAAM;EAAmB,SAAS;CAAO;CAEpE,IAAI,MAAM,WAAW,OACnB,OAAO;EACL,KAAK,cAAc,MAAM;EACzB,QAAQ,QAAQ,MAAM;EACtB,aAAa,CAAC;GAAE,MAAM;GAAQ,SAAS;GAAO,OAAO;EAAO,CAAC;EAC7D,SAAS;CACX;CAEF,OAAO,EAAE,SAAS,QAAQ;AAC5B,EACF;AAEA,SAAS,YAAY,OAAe,OAA0D;CAC5F,KAAK,MAAM,QAAQ,OACjB,KAAA,GAAIC,cAAAA,QAAAA,CAAO,CAAC,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC,QAAQ,KAAK,GAAG,OAAO;AAE1D;ACQA,MAAa,kBAAkB,eAA8B,OAAO,CAAC,CAAC,KAAK;CA3CzE,YAAY;CACZ,YAAY;CACZ,YAAY;CACZ,aAAa;AAwC4D,CAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"tools-Bl-YI890.mjs","names":["shellParse"],"sources":["../../../node_modules/.bun/shell-quote@1.10.0/node_modules/shell-quote/quote.js","../../../node_modules/.bun/shell-quote@1.10.0/node_modules/shell-quote/parse.js","../../../node_modules/.bun/shell-quote@1.10.0/node_modules/shell-quote/index.js","../src/utils/bash/parser.ts","../src/utils/bash/tools.ts"],"sourcesContent":["'use strict';\n\n/** @import { ControlOperator } from './parse' */\n\n/** @type {ControlOperator['op'][]} */\nvar OPS = /** @type {const} */ ([\n\t'||',\n\t'&&',\n\t';;',\n\t'|&',\n\t'<(',\n\t'<<<',\n\t'>>',\n\t'>&',\n\t'<&',\n\t'&',\n\t';',\n\t'(',\n\t')',\n\t'|',\n\t'<',\n\t'>'\n]);\nvar LINE_TERMINATORS = /[\\n\\r\\u2028\\u2029]/;\nvar GLOB_SHELL_SPECIAL = /[\\s#!\"$&'():;<=>@\\\\^`|]/g;\n\n/** @type {typeof import('./quote')} */\nmodule.exports = function quote(xs) {\n\treturn xs.map(function (s) {\n\t\tif (s === '') {\n\t\t\treturn /** @type {const} */ ('\\'\\'');\n\t\t}\n\t\tif (s && typeof s === 'object') {\n\t\t\tif ('op' in s && s.op === 'glob') {\n\t\t\t\tif (typeof s.pattern !== 'string') {\n\t\t\t\t\tthrow new TypeError('glob token requires a string `pattern`');\n\t\t\t\t}\n\t\t\t\tif (LINE_TERMINATORS.test(s.pattern)) {\n\t\t\t\t\tthrow new TypeError('glob `pattern` must not contain line terminators');\n\t\t\t\t}\n\t\t\t\treturn s.pattern.replace(GLOB_SHELL_SPECIAL, '\\\\$&');\n\t\t\t}\n\t\t\tif ('op' in s && typeof s.op === 'string') {\n\t\t\t\tif (OPS.indexOf(s.op) < 0) {\n\t\t\t\t\tthrow new TypeError('invalid `op` value: ' + JSON.stringify(s.op));\n\t\t\t\t}\n\t\t\t\treturn s.op.replace(/[\\s\\S]/g, '\\\\$&');\n\t\t\t}\n\t\t\tif ('comment' in s && typeof s.comment === 'string') {\n\t\t\t\tif (LINE_TERMINATORS.test(s.comment)) {\n\t\t\t\t\tthrow new TypeError('`comment` must not contain line terminators');\n\t\t\t\t}\n\t\t\t\treturn '#' + s.comment;\n\t\t\t}\n\t\t\tthrow new TypeError('unrecognized object token shape');\n\t\t}\n\t\tif ((/[\"\\s\\\\]/).test(s) && !(/'/).test(s)) {\n\t\t\treturn \"'\" + s.replace(/(['])/g, '\\\\$1') + \"'\";\n\t\t}\n\t\tif ((/[\"'\\s]/).test(s)) {\n\t\t\treturn '\"' + s.replace(/([\"\\\\$`!])/g, '\\\\$1') + '\"';\n\t\t}\n\t\treturn String(s).replace(/([A-Za-z]:)?([#!\"$&'()*,:;<=>?@[\\\\\\]^`{|}~])/g, '$1\\\\$2');\n\t}).join(' ');\n};\n","'use strict';\n\n/**\n * @import {\n * \tControlOperator,\n * \tEnv,\n * \tGlobPattern,\n * \tParseEntry,\n * } from './parse' */\n\n// '<(' is process substitution operator and\n// can be parsed the same as control operator\nvar CONTROL = /** @type {const} */ ('(?:') + /** @type {const} */ ([\n\t'\\\\|\\\\|',\n\t'\\\\&\\\\&',\n\t';;',\n\t'\\\\|\\\\&',\n\t'\\\\<\\\\(',\n\t'\\\\<\\\\<\\\\<',\n\t'>>',\n\t'>\\\\&',\n\t'<\\\\&',\n\t'[&;()|<>]'\n]).join(/** @type {const} */ ('|')) + /** @type {const} */ (')');\nvar controlRE = new RegExp('^' + CONTROL + '$');\nvar META = /** @type {const} */ ('|&;()<> \\\\t');\nvar SINGLE_QUOTE = /** @type {const} */ ('\\'([^\\']*?)\\'');\nvar DOUBLE_QUOTE = /** @type {const} */ ('\"((\\\\\\\\\"|[^\"])*?)\"');\nvar hash = /^#$/;\n\nvar SQ = /** @type {const} */ (\"'\");\nvar DQ = /** @type {const} */ ('\"');\nvar DS = /** @type {const} */ ('$');\n\nvar TOKEN = '';\nvar mult = /** @type {const} */ (0x100000000); // Math.pow(16, 8);\nfor (var i = 0; i < 4; i++) {\n\tTOKEN += (mult * Math.random()).toString(16);\n}\nvar startsWithToken = new RegExp('^' + TOKEN);\n\n/**\n * @param {string} s\n * @param {RegExp} r\n */\nfunction matchAll(s, r) {\n\tvar origIndex = r.lastIndex;\n\n\tvar matches = [];\n\tvar matchObj;\n\n\twhile ((matchObj = r.exec(s))) {\n\t\tmatches[matches.length] = matchObj;\n\t\tif (r.lastIndex === matchObj.index) {\n\t\t\tr.lastIndex += 1;\n\t\t}\n\t}\n\n\tr.lastIndex = origIndex;\n\n\treturn matches;\n}\n\n/**\n * @param {Env} env\n * @param {string} pre\n * @param {string} key\n */\nfunction getVar(env, pre, key) {\n\tvar r = typeof env === 'function' ? env(key) : env[key];\n\tif (typeof r === 'undefined' && key != '') {\n\t\tr = '';\n\t} else if (typeof r === 'undefined') {\n\t\tr = '$';\n\t}\n\n\tif (typeof r === 'object') {\n\t\treturn pre + TOKEN + JSON.stringify(r) + TOKEN;\n\t}\n\treturn pre + r;\n}\n\n/**\n * @param {string} string\n * @param {Env} [env]\n * @param {{ escape?: string, splitUnquoted?: boolean | string }} [opts]\n * @returns {ParseEntry[]}\n */\nfunction parseInternal(string, env, opts) {\n\tif (!opts) {\n\t\topts = {};\n\t}\n\tvar BS = opts.escape || '\\\\';\n\tvar ifs = opts.splitUnquoted === true ? ' \\t\\n' : (typeof opts.splitUnquoted === 'string' ? opts.splitUnquoted : '');\n\tvar BAREWORD = '(\\\\' + BS + '[\\'\"' + META + ']|[^\\\\s\\'\"' + META + '])+';\n\n\tvar chunker = new RegExp([\n\t\t'(' + CONTROL + ')', // control chars\n\t\t'(' + BAREWORD + '|' + DOUBLE_QUOTE + '|' + SINGLE_QUOTE + ')+'\n\t].join('|'), 'g');\n\n\tvar matches = matchAll(string, chunker);\n\n\tif (matches.length === 0) {\n\t\treturn [];\n\t}\n\tif (!env) {\n\t\tenv = {};\n\t}\n\n\tvar commented = false;\n\n\treturn matches.map(function (match) {\n\t\tvar s = match[0];\n\t\tif (!s || commented) {\n\t\t\treturn void undefined;\n\t\t}\n\t\tif (controlRE.test(s)) {\n\t\t\treturn /** @type {ControlOperator} */ ({ op: s });\n\t\t}\n\n\t\t// Hand-written scanner/parser for Bash quoting rules:\n\t\t//\n\t\t// 1. inside single quotes, all characters are printed literally.\n\t\t// 2. inside double quotes, all characters are printed literally\n\t\t// except variables prefixed by '$' and backslashes followed by\n\t\t// either a double quote or another backslash.\n\t\t// 3. outside of any quotes, backslashes are treated as escape\n\t\t// characters and not printed (unless they are themselves escaped)\n\t\t// 4. quote context can switch mid-token if there is no whitespace\n\t\t// between the two quote contexts (e.g. all'one'\"token\" parses as\n\t\t// \"allonetoken\")\n\t\t/** @type {string | boolean} */\n\t\tvar quote = false;\n\t\tvar esc = false;\n\t\tvar out = '';\n\t\t/** @type {string[]} */\n\t\tvar words = [];\n\t\tvar sawQuote = false;\n\t\t/** @type {number | null} */\n\t\tvar pendingNw = null;\n\t\tvar isGlob = false;\n\t\t/** @type {number} */\n\t\tvar i;\n\n\t\tfunction parseEnvVar() {\n\t\t\ti += 1;\n\t\t\t/** @type {number | RegExpMatchArray | null} */\n\t\t\tvar varend;\n\t\t\t/** @type {string} */\n\t\t\tvar varname;\n\t\t\tvar char = s.charAt(i);\n\n\t\t\tif (char === '{') {\n\t\t\t\ti += 1;\n\t\t\t\tif (s.charAt(i) === '}') {\n\t\t\t\t\tthrow new Error('Bad substitution: ' + s.slice(i - 2, i + 1));\n\t\t\t\t}\n\t\t\t\t// match braces by depth so a nested `${` keeps its inner `}` from ending the outer substitution\n\t\t\t\tvar depth = 1;\n\t\t\t\tvarend = i;\n\t\t\t\twhile (depth > 0 && varend < s.length) {\n\t\t\t\t\tif (s.charAt(varend) === '{' && s.charAt(varend - 1) === '$') {\n\t\t\t\t\t\tdepth += 1;\n\t\t\t\t\t} else if (s.charAt(varend) === '}') {\n\t\t\t\t\t\tdepth -= 1;\n\t\t\t\t\t}\n\t\t\t\t\tvarend += 1;\n\t\t\t\t}\n\t\t\t\tif (depth !== 0) {\n\t\t\t\t\tthrow new Error('Bad substitution: ' + s.slice(i));\n\t\t\t\t}\n\t\t\t\tvarend -= 1;\n\t\t\t\tvarname = s.slice(i, varend);\n\t\t\t\ti = varend;\n\t\t\t} else if ((/[*@#?$!_-]/).test(char)) {\n\t\t\t\tvarname = char;\n\t\t\t\ti += 1;\n\t\t\t} else {\n\t\t\t\tvar slicedFromI = s.slice(i);\n\t\t\t\tvarend = slicedFromI.match(/[^\\w\\d_]/);\n\t\t\t\tif (!varend) {\n\t\t\t\t\tvarname = slicedFromI;\n\t\t\t\t\ti = s.length;\n\t\t\t\t} else {\n\t\t\t\t\tvarname = slicedFromI.slice(0, varend.index);\n\t\t\t\t\ti += /** @type {number} */ (varend.index) - 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn getVar(/** @type {NonNullable<typeof env>} */ (env), '', varname);\n\t\t}\n\n\t\tfunction flushRun() {\n\t\t\tif (pendingNw === null) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (pendingNw === 0) {\n\t\t\t\tif (out !== '') {\n\t\t\t\t\twords[words.length] = out;\n\t\t\t\t\tout = '';\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\twords[words.length] = out;\n\t\t\t\tout = '';\n\t\t\t\tfor (var fe = 1; fe < pendingNw; fe += 1) {\n\t\t\t\t\twords[words.length] = '';\n\t\t\t\t}\n\t\t\t}\n\t\t\tpendingNw = null;\n\t\t}\n\n\t\tfor (i = 0; i < s.length; i++) {\n\t\t\tvar c = s.charAt(i);\n\t\t\tif (ifs && c !== DS) {\n\t\t\t\tflushRun();\n\t\t\t}\n\t\t\tisGlob = isGlob || (!quote && (c === '*' || c === '?'));\n\t\t\tif (esc) {\n\t\t\t\tout += c;\n\t\t\t\tesc = false;\n\t\t\t} else if (quote) {\n\t\t\t\tif (c === quote) {\n\t\t\t\t\tquote = false;\n\t\t\t\t} else if (quote == SQ) {\n\t\t\t\t\tout += c;\n\t\t\t\t} else { // Double quote\n\t\t\t\t\tif (c === BS) {\n\t\t\t\t\t\ti += 1;\n\t\t\t\t\t\tc = s.charAt(i);\n\t\t\t\t\t\tif (c === DQ || c === BS || c === DS) {\n\t\t\t\t\t\t\tout += c;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tout += BS + c;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (c === DS) {\n\t\t\t\t\t\tout += parseEnvVar();\n\t\t\t\t\t} else {\n\t\t\t\t\t\tout += c;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (c === DQ || c === SQ) {\n\t\t\t\tquote = c;\n\t\t\t\tsawQuote = true;\n\t\t\t} else if (controlRE.test(c)) {\n\t\t\t\treturn /** @type {ControlOperator} */ ({ op: s });\n\t\t\t} else if (hash.test(c)) {\n\t\t\t\tcommented = true;\n\t\t\t\tvar commentObj = { comment: string.slice(match.index + i + 1) };\n\t\t\t\tif (out.length) {\n\t\t\t\t\treturn /** @type {const} */ ([out, commentObj]);\n\t\t\t\t}\n\t\t\t\treturn /** @type {const} */ ([commentObj]);\n\t\t\t} else if (c === BS) {\n\t\t\t\tesc = true;\n\t\t\t} else if (c === DS) {\n\t\t\t\tvar value = parseEnvVar();\n\t\t\t\tif (!ifs) {\n\t\t\t\t\tout += value;\n\t\t\t\t} else {\n\t\t\t\t\tfor (var vi = 0; vi < value.length; vi += 1) {\n\t\t\t\t\t\tvar vc = value.charAt(vi);\n\t\t\t\t\t\tif (ifs.indexOf(vc) < 0) {\n\t\t\t\t\t\t\tflushRun();\n\t\t\t\t\t\t\tout += vc;\n\t\t\t\t\t\t} else if (pendingNw === null) {\n\t\t\t\t\t\t\tpendingNw = vc === ' ' || vc === '\\t' || vc === '\\n' ? 0 : 1;\n\t\t\t\t\t\t} else if (vc !== ' ' && vc !== '\\t' && vc !== '\\n') {\n\t\t\t\t\t\t\tpendingNw += 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tout += c;\n\t\t\t}\n\t\t}\n\n\t\tif (isGlob) {\n\t\t\treturn /** @type {GlobPattern} */ ({ op: 'glob', pattern: out });\n\t\t}\n\n\t\tif (ifs) {\n\t\t\tif (pendingNw !== null && pendingNw > 0) {\n\t\t\t\twords[words.length] = out;\n\t\t\t\tout = '';\n\t\t\t\tfor (var te = 1; te < pendingNw; te += 1) {\n\t\t\t\t\twords[words.length] = '';\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (out !== '' || (sawQuote && words.length === 0)) {\n\t\t\t\twords[words.length] = out;\n\t\t\t}\n\t\t\treturn words;\n\t\t}\n\n\t\treturn out;\n\t}).reduce(function (prev, arg) { // finalize parsed arguments\n\t\tif (typeof arg === 'undefined') {\n\t\t\treturn prev;\n\t\t}\n\t\t/** @type {ParseEntry[]} */ ([]).concat(arg).forEach(function (entry) {\n\t\t\tprev[prev.length] = entry;\n\t\t});\n\t\treturn prev;\n\t}, /** @type {ParseEntry[]} */ ([]));\n}\n\n/** @type {typeof import('./parse')} */\nmodule.exports = function parse(s, env, opts) {\n\tvar mapped = parseInternal(s, env, opts);\n\tif (typeof env !== 'function') {\n\t\treturn mapped;\n\t}\n\treturn mapped.reduce(function (acc, s) {\n\t\tif (typeof s === 'object') {\n\t\t\tacc[acc.length] = s;\n\t\t\treturn acc;\n\t\t}\n\t\tvar xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g'));\n\t\tif (xs.length === 1) {\n\t\t\tacc[acc.length] = xs[0];\n\t\t\treturn acc;\n\t\t}\n\t\txs.filter(Boolean).forEach(function (x) {\n\t\t\tacc[acc.length] = startsWithToken.test(x)\n\t\t\t\t? JSON.parse(x.split(TOKEN)[1])\n\t\t\t\t: x;\n\t\t});\n\t\treturn acc;\n\t}, /** @type {ParseEntry[]} */ ([]));\n};\n","'use strict';\n\nexports.quote = require('./quote');\nexports.parse = require('./parse');\n","import { safeStringify } from \"@zaly/shared\"\nimport { parse as shellParse } from \"shell-quote\"\n\n/** A shell command broken down into its structural parts. One bash\n * input may parse to multiple segments (joined by `|`, `&&`, `||`, `;`).\n * Each segment is evaluated independently by the policy. */\nexport interface Segment {\n cmd: string\n args: string[]\n dyn?: Set<string>\n /** File paths the segment reads from (`< file` redirects). Built-in\n * tools may add inferred reads in the policy layer. */\n reads: string[]\n /** File paths the segment writes to (`> file` / `>> file`). */\n writes: { path: string; mode: \"trunc\" | \"append\" }[]\n /** True if the input contains command substitution (`$()` or backticks)\n * or any other dynamic-evaluation construct. Forces ask. */\n hasCommandSubst: boolean\n}\n\nexport type ParseResult = { ok: true; segments: Segment[] } | { ok: false; reason: string }\n\n/** Targets a redirect can write to without filesystem implications.\n * Anything else is treated as a file write and goes through fileWrite\n * policy. */\nconst SAFE_REDIRECT_TARGETS = new Set([\"/dev/null\", \"/dev/stderr\", \"/dev/stdout\"])\n\n/** A redirect target like `&1`, `&2`, `&-` — duplicates an existing fd,\n * no filesystem effect. */\nfunction isFdRedirect(target: string): boolean {\n return /^&(?:\\d+|-)$/.test(target)\n}\n\ntype Op = { op: string }\ntype Glob = { op: \"glob\"; pattern: string }\ntype Comment = { comment: string }\ntype Token = string | Op | Glob | Comment\n\nconst COMMAND_SEPS = new Set([\"|\", \"&&\", \"||\", \";\"])\nconst REDIRECT_OPS = new Set([\">\", \">>\", \"<\", \">&\", \"<&\"])\nconst DYN_SENTINEL = \"\\u{E000}\"\n\n/** Parse a bash command line. Returns segments with a flag for\n * unsupported constructs that force \"ask\" downstream. Heredocs,\n * subshells, command substitution, and backticks all surface as\n * `hasCommandSubst: true` (the umbrella \"we can't reason about this\"\n * signal) rather than parse failures, so the policy can still decide. */\nexport function parseBash(input: string): ParseResult {\n // Heredocs derail shell-quote (the body bleeds into surrounding tokens),\n // so we bail to ok:false here. checkBash maps that to ask.\n if (/<<-?\\s*['\"]?\\w+/.test(input)) {\n return { ok: false, reason: \"heredoc not supported\" }\n }\n // Backticks command-substitute in bash unless inside single quotes\n // (single quotes preserve everything literally; double quotes don't\n // suppress substitution). Flag only the unquoted form so embedded\n // template literals in `bun -e '... ${x} `tpl` ...'` don't trip us.\n const hasBackticks = hasUnquotedBacktick(input)\n\n let rawTokens: Token[]\n try {\n rawTokens = shellParse(input, (e) =>\n e === \"\" ? undefined : `${DYN_SENTINEL}\\${${e}}`\n ) as Token[]\n } catch (error) {\n return { ok: false, reason: `tokenize: ${(error as Error).message}` }\n }\n\n // Inline plain `(subshell)` contents as separate segments; strip\n // `$(...)` regions and flag as command substitution. Backticks\n // already detected via the pre-scan above.\n const flat = flattenParens(rawTokens)\n const hasCommandSubst = hasBackticks || flat.hasCommandSubst\n\n const segmentTokens: Token[][] = [[]]\n for (const t of flat.tokens) {\n if (typeof t === \"object\" && \"comment\" in t) continue\n\n if (typeof t === \"object\" && \"op\" in t && COMMAND_SEPS.has(t.op)) {\n if (segmentTokens.at(-1)!.length > 0) segmentTokens.push([])\n continue\n }\n\n segmentTokens.at(-1)!.push(t)\n }\n\n if (segmentTokens.at(-1)!.length === 0) segmentTokens.pop()\n\n const segments: Segment[] = []\n for (const segToks of segmentTokens) {\n const seg = parseSegment(segToks)\n if (!seg.ok) return seg\n if (seg.segment) segments.push({ ...seg.segment, hasCommandSubst })\n }\n\n if (segments.length === 0) {\n return { ok: false, reason: \"empty input\" }\n }\n return { ok: true, segments }\n}\n\nfunction parseSegment(\n tokens: Token[]\n):\n | { ok: true; segment: Omit<Segment, \"hasCommandSubst\"> | undefined }\n | { ok: false; reason: string } {\n let args: string[] = []\n let reads: string[] = []\n let writes: { path: string; mode: \"trunc\" | \"append\" }[] = []\n const dyn = new Set<string>()\n\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i]\n\n if (typeof t === \"string\") {\n // FD prefix on a redirect (`2>&1`, `2>file`, `1<&-`) — shell-quote\n // splits the leading digit off as its own token. Don't treat it\n // as a regular arg; the redirect handler below picks up the op.\n if (/^\\d+$/.test(t)) {\n const next = tokens[i + 1]\n if (typeof next === \"object\" && \"op\" in next && REDIRECT_OPS.has(next.op)) {\n continue\n }\n }\n args.push(t)\n continue\n }\n\n if (\"comment\" in t) continue\n\n if (\"pattern\" in t) {\n // Pass globs through as their pattern — policy layer decides.\n args.push(t.pattern)\n dyn.add(t.pattern)\n continue\n }\n\n if (!(\"op\" in t)) {\n return { ok: false, reason: `unsupported token: ${safeStringify(t)}` }\n }\n\n if (REDIRECT_OPS.has(t.op)) {\n const next = tokens[i + 1]\n if (typeof next !== \"string\") {\n return { ok: false, reason: `redirect target missing after ${t.op}` }\n }\n i++ // consume target\n\n if (t.op === \">\" || t.op === \">>\") {\n // Skip safe targets (/dev/null etc.) and fd redirects entirely.\n if (SAFE_REDIRECT_TARGETS.has(next) || isFdRedirect(next)) continue\n writes.push({ mode: t.op === \">>\" ? \"append\" : \"trunc\", path: next })\n } else if (t.op === \"<\") {\n if (SAFE_REDIRECT_TARGETS.has(next) || isFdRedirect(next)) continue\n reads.push(next)\n }\n // `>&` / `<&` are fd-duplicating (`2>&1`-style) — no fs impact.\n continue\n }\n\n return { ok: false, reason: `unsupported op: ${t.op}` }\n }\n\n const dynPath = (p: string) => {\n if (!p.includes(DYN_SENTINEL)) return p\n p = p.replaceAll(DYN_SENTINEL, \"\")\n dyn.add(p)\n return p\n }\n\n args = args.map((a) => dynPath(a))\n writes = writes.map((w) => ({ ...w, path: dynPath(w.path) }))\n reads = reads.map(dynPath)\n\n // Strip leading wrapper commands (`time`, `nohup`, `nice`, …) so the\n // policy sees the real command being run. `time bun test` evaluates\n // as `bun test`; a bare `time` (or `time (subshell)` after flatten)\n // leaves nothing and signals the caller to drop the segment.\n const unwrapped = unwrapWrappers(args)\n if (unwrapped.length === 0) {\n return { ok: true, segment: undefined }\n }\n\n return {\n ok: true,\n segment: {\n args: unwrapped.slice(1),\n cmd: unwrapped[0],\n dyn,\n reads,\n writes,\n },\n }\n}\n\ninterface WrapperSpec {\n /** Flags that consume the next arg as their value. */\n valueFlags?: Set<string>\n}\n\n/** Commands that wrap another command — they're transparent for\n * permission purposes, since the security-relevant action is whatever\n * they run. `sudo` is intentionally absent: it changes the effective\n * user and must always be flagged. */\nconst WRAPPERS: Partial<Record<string, WrapperSpec>> = {\n command: {}, // bash builtin, bypasses aliases\n ionice: { valueFlags: new Set([\"-c\", \"-n\", \"-p\", \"-P\", \"-u\"]) },\n nice: { valueFlags: new Set([\"-n\", \"--adjustment\"]) },\n nohup: {},\n time: {}, // bash reserved word, also GNU /usr/bin/time\n}\n\n/** Detect backticks outside single-quoted regions. Single quotes in\n * bash can't be escaped from within, so the toggle is a simple state\n * flip on every `'`. Double quotes do not suppress backtick\n * substitution and are ignored here. */\nfunction hasUnquotedBacktick(input: string): boolean {\n let inSingle = false\n for (const c of input) {\n if (c === \"'\") {\n inSingle = !inSingle\n continue\n }\n if (c === \"`\" && !inSingle) return true\n }\n return false\n}\n\n/** Strip leading wrapper-command prefixes from an arg list. Repeats\n * while the head is a wrapper (so `time nice -n 5 cmd` → `cmd`).\n * Wrapper-flags (and their values, where applicable) are consumed\n * along with the wrapper itself. */\nfunction unwrapWrappers(args: string[]): string[] {\n let current = args\n while (current.length > 0) {\n const spec = WRAPPERS[current[0]]\n if (!spec) break\n const valueFlags = spec.valueFlags ?? new Set()\n let i = 1\n while (i < current.length && current[i].startsWith(\"-\")) {\n const flag = current[i]\n i++\n if (valueFlags.has(flag) && i < current.length) i++ // consume flag value\n }\n current = current.slice(i)\n }\n return current\n}\n\n/** Walk a token list and resolve paren constructs:\n * - Plain `(subshell)` → tokens inlined with `;` boundaries on each\n * side, so the contents become independent segments evaluated by\n * the same policy. The subshell's own scope (cwd changes etc.) is\n * irrelevant to permissions — each command is checked individually.\n * - `$(...)` (command substitution) → stripped entirely, with the\n * `hasCommandSubst` flag raised. The dynamic value can't be\n * statically reasoned about. Detected by the leading `$` token\n * that shell-quote emits before the `(`.\n *\n * Recurses into subshell contents to handle nesting and to catch\n * `$(...)` constructs nested inside subshells. */\nfunction flattenParens(tokens: Token[]): { tokens: Token[]; hasCommandSubst: boolean } {\n const out: Token[] = []\n let hasCommandSubst = false\n let i = 0\n while (i < tokens.length) {\n const t = tokens[i]\n if (typeof t === \"object\" && \"op\" in t && t.op === \"(\") {\n const isSubst = out.at(-1) === \"$\"\n if (isSubst) out.pop()\n\n // Find matching `)`, accounting for nesting.\n let depth = 1\n let j = i + 1\n while (j < tokens.length && depth > 0) {\n const tj = tokens[j]\n if (typeof tj === \"object\" && \"op\" in tj) {\n if (tj.op === \"(\") depth++\n else if (tj.op === \")\") depth--\n }\n if (depth > 0) j++\n }\n const inner = tokens.slice(i + 1, j)\n\n if (isSubst) {\n hasCommandSubst = true\n // Drop the entire $(...) — its value is dynamic.\n } else {\n const sub = flattenParens(inner)\n if (sub.hasCommandSubst) hasCommandSubst = true\n // Surround with separators so subshell contents form their own\n // segments regardless of what's adjacent in the outer chain.\n out.push({ op: \";\" }, ...sub.tokens, { op: \";\" })\n }\n i = j + 1\n continue\n }\n\n if (typeof t === \"object\" && \"op\" in t && t.op === \")\") {\n // Stray closing paren (unbalanced input). Skip — the parser's\n // overall result will likely fail downstream on a malformed segment.\n i++\n continue\n }\n\n out.push(t)\n i++\n }\n return { hasCommandSubst, tokens: out }\n}\n","/**\n * Built-in tool registry — per-command knowledge of which args are\n * input files, output files, and which invocation modes are too\n * complex to safely model.\n *\n * The policy engine consults this registry alongside explicit redirect\n * info from the parser to determine per-command file I/O for the\n * fileRead/fileWrite policy hooks.\n */\nexport interface ToolSpec {\n /** File paths the command will read from, derived from args. */\n reads?: (args: string[]) => string[]\n /** File paths the command will write to. */\n writes?: (args: string[]) => string[]\n /** Returns true if the args invoke a mode the parser can't safely\n * reason about (e.g. `sed -e 'w out'`, `find -exec`). Forces ask. */\n unsafe?: (args: string[]) => boolean\n}\n\n/** All bare positional args (no leading dash). Default for many\n * read-only utilities. */\nfunction positionals(args: string[]): string[] {\n return args.filter((a) => !a.startsWith(\"-\") && a !== \"\")\n}\n\n/** All positionals after the first one (e.g. `grep PATTERN file...`). */\nfunction positionalsAfterFirst(args: string[]): string[] {\n const out: string[] = []\n let seenFirst = false\n for (const a of args) {\n if (a.startsWith(\"-\") || a === \"\") continue\n if (!seenFirst) {\n seenFirst = true\n continue\n }\n out.push(a)\n }\n return out\n}\n\n// ── sed ──────────────────────────────────────────────────────────────────\n\n/** Flags whose value is the *next* arg, not part of the script. */\nconst SED_VALUE_FLAGS = new Set([\"-e\", \"--expression\", \"-f\", \"--file\"])\n\n/** Walk sed args, returning [scripts, positionalsAfterScript]. The\n * \"script\" is everything passed via `-e` plus the first bare arg\n * (the implicit script when no `-e` is given). Positionals after\n * that are input files. */\nfunction sedSplit(args: string[]): { scripts: string[]; files: string[] } {\n const scripts: string[] = []\n const files: string[] = []\n let needsImplicitScript = !args.some(\n (a) => a === \"-e\" || a === \"--expression\" || a === \"-f\" || a === \"--file\"\n )\n\n for (let i = 0; i < args.length; i++) {\n const a = args[i]\n if (a.startsWith(\"-\")) {\n if (SED_VALUE_FLAGS.has(a) && i + 1 < args.length) {\n if (a === \"-e\" || a === \"--expression\") scripts.push(args[i + 1])\n i++ // consume value\n }\n continue\n }\n if (needsImplicitScript) {\n scripts.push(a)\n needsImplicitScript = false\n continue\n }\n files.push(a)\n }\n return { files, scripts }\n}\n\nconst SED_INPLACE = new Set([\"-i\", \"--in-place\"])\n\nfunction sedReads(args: string[]): string[] {\n return sedSplit(args).files\n}\n\nfunction sedWrites(args: string[]): string[] {\n // `-i` rewrites positional input files; also supports `-i.bak` form.\n const inPlace = args.some((a) => SED_INPLACE.has(a) || a.startsWith(\"-i.\"))\n return inPlace ? sedSplit(args).files : []\n}\n\nfunction sedUnsafe(args: string[]): boolean {\n // `w` / `W` write commands and `r` / `R` read commands inside the\n // script can do file I/O the parser can't see. Bail to ask.\n for (const script of sedSplit(args).scripts) {\n if (/(?:^|;|\\n)\\s*[wWrR]\\s+\\S/.test(script)) return true\n }\n return false\n}\n\n// ── awk ──────────────────────────────────────────────────────────────────\n\nfunction awkReads(args: string[]): string[] {\n // awk usage: `awk [opts] 'script' [files...]` or `awk [opts] -f file [files...]`\n // Files come after the script. Skip flags + their values.\n let sawScript = false\n let usingFFlag = false\n const files: string[] = []\n for (let i = 0; i < args.length; i++) {\n const a = args[i]\n if (a === \"-f\" || a === \"--file\") {\n if (i + 1 < args.length) files.push(args[i + 1]) // script file is read too\n i++\n sawScript = true\n usingFFlag = true\n continue\n }\n if (a.startsWith(\"-\")) {\n // Some awk flags take a value (-v, -F)\n if (a === \"-v\" || a === \"-F\") i++\n continue\n }\n if (!sawScript) {\n sawScript = true\n continue\n }\n files.push(a)\n }\n return usingFFlag ? files : files\n}\n\nfunction awkUnsafe(args: string[]): boolean {\n // awk's `print > file` and `printf > file` inside a script write to\n // files. Detecting reliably without parsing the script is hard, so\n // bail to ask if the script (or any -e value) contains a `>` operator.\n // Conservative — false positives are fine for \"ask\".\n let sawScript = false\n for (let i = 0; i < args.length; i++) {\n const a = args[i]\n if (a === \"-f\" || a === \"--file\" || a === \"-v\" || a === \"-F\") {\n i++\n continue\n }\n if (a.startsWith(\"-\")) continue\n if (!sawScript) {\n sawScript = true\n if (/[>|]/.test(a)) return true\n }\n }\n return false\n}\n\n// ── find ─────────────────────────────────────────────────────────────────\n\nfunction findReads(args: string[]): string[] {\n // First positional (or `.`) is the path. Multiple paths possible\n // before the first `-action` flag.\n const out: string[] = []\n for (const a of args) {\n if (a.startsWith(\"-\")) break\n out.push(a)\n }\n return out.length > 0 ? out : [\".\"]\n}\n\nfunction findUnsafe(args: string[]): boolean {\n // `-delete`, `-exec`, `-execdir`, `-ok`, `-okdir` all do work we\n // can't trace.\n return args.some(\n (a) => a === \"-delete\" || a === \"-exec\" || a === \"-execdir\" || a === \"-ok\" || a === \"-okdir\"\n )\n}\n\n// ── dynamic execution ────────────────────────────────────────────────────\n//\n// These commands run arbitrary code passed as arguments or sourced from\n// files. We can't reason about their effects from the parser; force ask.\n\nconst dynamicExec = (): boolean => true\n\n// ── registry ─────────────────────────────────────────────────────────────\n\nexport const TOOLS: Partial<Record<string, ToolSpec>> = {\n \".\": { unsafe: dynamicExec }, // sh: source alias\n awk: { reads: awkReads, unsafe: awkUnsafe },\n basename: {},\n cat: { reads: positionals },\n cd: {},\n cut: { reads: positionals },\n diff: { reads: positionals },\n dirname: {},\n echo: {},\n eval: { unsafe: dynamicExec }, // runs its argument as shell input\n exec: { unsafe: dynamicExec }, // replaces the shell process\n file: { reads: positionals },\n find: { reads: findReads, unsafe: findUnsafe },\n grep: { reads: positionalsAfterFirst },\n head: { reads: positionals },\n hexdump: { reads: positionals },\n less: { reads: positionals },\n ls: { reads: positionals },\n more: { reads: positionals },\n od: { reads: positionals },\n printf: {},\n pwd: {},\n readlink: { reads: positionals },\n realpath: { reads: positionals },\n rg: { reads: positionalsAfterFirst },\n sed: { reads: sedReads, unsafe: sedUnsafe, writes: sedWrites },\n sort: { reads: positionals },\n source: { unsafe: dynamicExec }, // bash: runs the file in current shell\n stat: { reads: positionals },\n tail: { reads: positionals },\n tree: { reads: positionals },\n uniq: { reads: positionals },\n wc: { reads: positionals },\n xxd: { reads: positionals },\n}\n"],"x_google_ignoreList":[0,1,2],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAKA,IAAI,MAA4B;EAC/B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD;CACA,IAAI,mBAAmB;CACvB,IAAI,qBAAqB;;CAGzB,OAAO,UAAU,SAAS,MAAM,IAAI;EACnC,OAAO,GAAG,IAAI,SAAU,GAAG;GAC1B,IAAI,MAAM,IACT,OAA6B;GAE9B,IAAI,KAAK,OAAO,MAAM,UAAU;IAC/B,IAAI,QAAQ,KAAK,EAAE,OAAO,QAAQ;KACjC,IAAI,OAAO,EAAE,YAAY,UACxB,MAAM,IAAI,UAAU,wCAAwC;KAE7D,IAAI,iBAAiB,KAAK,EAAE,OAAO,GAClC,MAAM,IAAI,UAAU,kDAAkD;KAEvE,OAAO,EAAE,QAAQ,QAAQ,oBAAoB,MAAM;IACpD;IACA,IAAI,QAAQ,KAAK,OAAO,EAAE,OAAO,UAAU;KAC1C,IAAI,IAAI,QAAQ,EAAE,EAAE,IAAI,GACvB,MAAM,IAAI,UAAU,yBAAyB,KAAK,UAAU,EAAE,EAAE,CAAC;KAElE,OAAO,EAAE,GAAG,QAAQ,WAAW,MAAM;IACtC;IACA,IAAI,aAAa,KAAK,OAAO,EAAE,YAAY,UAAU;KACpD,IAAI,iBAAiB,KAAK,EAAE,OAAO,GAClC,MAAM,IAAI,UAAU,6CAA6C;KAElE,OAAO,MAAM,EAAE;IAChB;IACA,MAAM,IAAI,UAAU,iCAAiC;GACtD;GACA,IAAK,UAAW,KAAK,CAAC,KAAK,CAAE,IAAK,KAAK,CAAC,GACvC,OAAO,MAAM,EAAE,QAAQ,UAAU,MAAM,IAAI;GAE5C,IAAK,SAAU,KAAK,CAAC,GACpB,OAAO,OAAM,EAAE,QAAQ,eAAe,M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OAAO;EAAW,QAAQ;CAAW;CAC7C,MAAM,EAAE,OAAO,sBAAsB;CACrC,MAAM,EAAE,OAAO,YAAY;CAC3B,SAAS,EAAE,OAAO,YAAY;CAC9B,MAAM,EAAE,OAAO,YAAY;CAC3B,IAAI,EAAE,OAAO,YAAY;CACzB,MAAM,EAAE,OAAO,YAAY;CAC3B,IAAI,EAAE,OAAO,YAAY;CACzB,QAAQ,CAAC;CACT,KAAK,CAAC;CACN,UAAU,EAAE,OAAO,YAAY;CAC/B,UAAU,EAAE,OAAO,YAAY;CAC/B,IAAI,EAAE,OAAO,sBAAsB;CACnC,KAAK;EAAE,OAAO;EAAU,QAAQ;EAAW,QAAQ;CAAU;CAC7D,MAAM,EAAE,OAAO,YAAY;CAC3B,QAAQ,EAAE,QAAQ,YAAY;CAC9B,MAAM,EAAE,OAAO,YAAY;CAC3B,MAAM,EAAE,OAAO,YAAY;CAC3B,MAAM,EAAE,OAAO,YAAY;CAC3B,MAAM,EAAE,OAAO,YAAY;CAC3B,IAAI,EAAE,OAAO,YAAY;CACzB,KAAK,EAAE,OAAO,YAAY;AAC5B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"write-D3L-92vj.mjs","names":[],"sources":["../src/tools/write.ts"],"sourcesContent":["import type { ToolContext } from \"@zaly/ai\"\nimport type { FileMeta } from \"./read.ts\"\n\nimport { AiError, defineTool } from \"@zaly/ai\"\nimport { normPath, safeReadFile, safeStat } from \"@zaly/shared\"\nimport { detectEol, normalizeEol } from \"@zaly/shared/text\"\nimport { mkdir, stat, writeFile } from \"node:fs/promises\"\nimport { dirname } from \"pathe\"\nimport { Type } from \"typebox\"\nimport { assertFresh } from \"./read.ts\"\n\nexport type WriteTool = typeof writeTool\n\nexport type WriteToolMeta = FileMeta & {\n /** File content before the write. Undefined for new files. The\n * post-write content is recoverable from the original call's\n * `params.content`, so we don't redundantly stash it on meta. */\n original?: string\n}\n\n/**\n * Write a file to disk. Overwrites if the file exists; creates parent\n * directories as needed.\n *\n * Content is written *verbatim* in everything but line endings. The\n * model always emits LF; this tool detects the existing file's\n * line-ending style (or the platform default for new files via\n * `detectEol`) and re-applies it on write so a CRLF file stays CRLF\n * after an LF-from-the-model overwrite. No trailing-newline injection,\n * no whitespace stripping.\n *\n * Freshness: when the target file already exists, the model must have\n * read it in this session and the on-disk mtime must be unchanged\n * since that read. Otherwise the tool refuses with `FILE_NOT_FRESH` —\n * \"read this file before overwriting it.\" New files (path doesn't\n * exist) bypass this check; nothing to be fresh against.\n *\n * Returns a small acknowledgement (`{ ok, bytes, lines }`) rather than\n * echoing the content back — the model already has it. `bytes` reflects\n * the on-disk byte count, including any extra bytes from CRLF expansion.\n */\n// oxlint-disable-next-line sort-keys -- semantic field order: name, desc, params, call\nexport const writeTool = defineTool({\n name: \"write\",\n desc:\n \"Write content to a file. Overwrites existing files (must be read first); \" +\n \"creates parent directories as needed. Returns the byte count and line \" +\n \"count of the written file.\",\n // oxlint-disable-next-line sort-keys -- semantic param order\n params: Type.Object({\n path: Type.String({ description: \"Path to the file. Absolute or cwd-relative.\" }),\n content: Type.String({ description: \"File contents to write, verbatim.\" }),\n }),\n\n async preflight(args, ctx: ToolContext<WriteToolMeta>) {\n const path = normPath(ctx.cwd, args.path)\n await ctx.need?.(\"write\", path)\n },\n\n async call(\n args,\n ctx: ToolContext<WriteToolMeta>\n ): Promise<{ ok: true; path: string; bytes: number; lines: number }> {\n const path = normPath(ctx.cwd, args.path)\n\n // Existing file → freshness required. New file → no requirement.\n if (safeStat(path)?.isFile()) assertFresh(path, ctx)\n\n let text: string\n let original: string | undefined\n try {\n original = await safeReadFile(path)\n const eol = detectEol({ path, text: original })\n text = normalizeEol(args.content, { eol })\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, text, \"utf8\")\n } catch (error) {\n throw new AiError({\n cause: error,\n code: \"WRITE_FAILED\",\n message: `failed to write ${path}: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n\n // Record post-write so the model can re-edit without an immediate\n // re-read. Captures the new mtime.\n const fstat = await stat(path)\n ctx.meta = { full: true, kind: \"write\", mtime: fstat.mtimeMs, original, path }\n\n const bytes = Buffer.byteLength(text, \"utf8\")\n const lines = countLines(text)\n return { bytes, lines, ok: true, path }\n },\n})\n\n/** Count lines the way an editor would — non-empty trailing line counts;\n * trailing newline doesn't add a phantom blank line. */\nfunction countLines(content: string): number {\n if (content === \"\") return 0\n let n = 1\n for (const c of content) if (c === \"\\n\") n++\n // A trailing newline means the count is one too high (no real line follows).\n if (content.endsWith(\"\\n\")) n--\n return n\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAa,YAAY,WAAW;CAClC,MAAM;CACN,MACE;CAIF,QAAQ,KAAK,OAAO;EAClB,MAAM,KAAK,OAAO,EAAE,aAAa,8CAA8C,CAAC;EAChF,SAAS,KAAK,OAAO,EAAE,aAAa,oCAAoC,CAAC;CAC3E,CAAC;CAED,MAAM,UAAU,MAAM,KAAiC;EACrD,MAAM,OAAO,SAAS,IAAI,KAAK,KAAK,IAAI;EACxC,MAAM,IAAI,OAAO,SAAS,IAAI;CAChC;CAEA,MAAM,KACJ,MACA,KACmE;EACnE,MAAM,OAAO,SAAS,IAAI,KAAK,KAAK,IAAI;EAGxC,IAAI,SAAS,IAAI,CAAC,EAAE,OAAO,GAAG,YAAY,MAAM,GAAG;EAEnD,IAAI;EACJ,IAAI;EACJ,IAAI;GACF,WAAW,MAAM,aAAa,IAAI;GAClC,MAAM,MAAM,UAAU;IAAE;IAAM,MAAM;GAAS,CAAC;GAC9C,OAAO,aAAa,KAAK,SAAS,EAAE,IAAI,CAAC;GACzC,MAAM,MAAM,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;GAC9C,MAAM,UAAU,MAAM,MAAM,MAAM;EACpC,SAAS,OAAO;GACd,MAAM,IAAI,QAAQ;IAChB,OAAO;IACP,MAAM;IACN,SAAS,mBAAmB,KAAK,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAA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