@zaly/agent 0.1.1 → 0.3.0

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 (57) hide show
  1. package/dist/{agent-BRENvuvx.mjs → agent-GXRF7DUP.mjs} +102 -33
  2. package/dist/agent-GXRF7DUP.mjs.map +1 -0
  3. package/dist/{bash-DSy03sAj.mjs → bash-CB_VXpyd.mjs} +2 -2
  4. package/dist/{bash-DSy03sAj.mjs.map → bash-CB_VXpyd.mjs.map} +1 -1
  5. package/dist/{compactions-HFjEgrv3.mjs → compactions-92bMlcxJ.mjs} +25 -15
  6. package/dist/compactions-92bMlcxJ.mjs.map +1 -0
  7. package/dist/{edit-DT672zIy.mjs → edit-gkb6MCW-.mjs} +2 -2
  8. package/dist/{edit-DT672zIy.mjs.map → edit-gkb6MCW-.mjs.map} +1 -1
  9. package/dist/{fetch-BrtIqrid.mjs → fetch-D_GzL2yy.mjs} +4 -4
  10. package/dist/{fetch-BrtIqrid.mjs.map → fetch-D_GzL2yy.mjs.map} +1 -1
  11. package/dist/{find-B-vvdlHu.mjs → find-DlrYUTXT.mjs} +2 -2
  12. package/dist/{find-B-vvdlHu.mjs.map → find-DlrYUTXT.mjs.map} +1 -1
  13. package/dist/{grep-rvZ5S319.mjs → grep-BI8Rou2q.mjs} +2 -2
  14. package/dist/{grep-rvZ5S319.mjs.map → grep-BI8Rou2q.mjs.map} +1 -1
  15. package/dist/{html-VrAsoGBK.mjs → html-B-Lr-9W6.mjs} +9457 -4826
  16. package/dist/html-B-Lr-9W6.mjs.map +1 -0
  17. package/dist/{index-node-esm-BwaOzhXB.mjs → index-node-esm-75XSYyIw.mjs} +16 -13
  18. package/dist/index-node-esm-75XSYyIw.mjs.map +1 -0
  19. package/dist/index.d.mts +21 -6
  20. package/dist/index.d.mts.map +1 -1
  21. package/dist/index.mjs +2 -2
  22. package/dist/{manager-1zEE5WiA.mjs → manager-CEociHy_.mjs} +2 -2
  23. package/dist/{manager-1zEE5WiA.mjs.map → manager-CEociHy_.mjs.map} +1 -1
  24. package/dist/{masker-DEgR_ntk.mjs → masker-DWuL2Fjs.mjs} +16 -5
  25. package/dist/{masker-DEgR_ntk.mjs.map → masker-DWuL2Fjs.mjs.map} +1 -1
  26. package/dist/{read-C5keKntU.mjs → read-DLtNq4XJ.mjs} +2 -2
  27. package/dist/{read-C5keKntU.mjs.map → read-DLtNq4XJ.mjs.map} +1 -1
  28. package/dist/{registry-CntkeXlo.mjs → registry-7mJQhyBA.mjs} +3 -3
  29. package/dist/{registry-CntkeXlo.mjs.map → registry-7mJQhyBA.mjs.map} +1 -1
  30. package/dist/{rolldown-runtime-DYf_mQCB.mjs → rolldown-runtime-BVN1G_yT.mjs} +4 -4
  31. package/dist/{session-C8zqqbPE.mjs → session-C5ra-Hi1.mjs} +80 -45
  32. package/dist/session-C5ra-Hi1.mjs.map +1 -0
  33. package/dist/{session-Cq52cam5.d.mts → session-WtXqtAaq.d.mts} +19 -10
  34. package/dist/session-WtXqtAaq.d.mts.map +1 -0
  35. package/dist/session.d.mts +1 -1
  36. package/dist/session.mjs +1 -1
  37. package/dist/{src-C04Qk9KE.mjs → src-Di-H3Oya.mjs} +71 -41
  38. package/dist/src-Di-H3Oya.mjs.map +1 -0
  39. package/dist/{subagent-BbcxLzgC.mjs → subagent-BOK4GFd4.mjs} +3 -3
  40. package/dist/{subagent-BbcxLzgC.mjs.map → subagent-BOK4GFd4.mjs.map} +1 -1
  41. package/dist/{tasks-Dgsiuh0Q.mjs → tasks-BUFqFoh6.mjs} +2 -2
  42. package/dist/{tasks-Dgsiuh0Q.mjs.map → tasks-BUFqFoh6.mjs.map} +1 -1
  43. package/dist/{tasks-D76WXWr2.mjs → tasks-CkDWJk_3.mjs} +4 -4
  44. package/dist/tasks-CkDWJk_3.mjs.map +1 -0
  45. package/dist/{tools-DmoUYORG.mjs → tools-Ca7VsMg3.mjs} +2 -2
  46. package/dist/{tools-DmoUYORG.mjs.map → tools-Ca7VsMg3.mjs.map} +1 -1
  47. package/dist/{write-BRQFfWAn.mjs → write-y93TC5ng.mjs} +2 -2
  48. package/dist/{write-BRQFfWAn.mjs.map → write-y93TC5ng.mjs.map} +1 -1
  49. package/package.json +11 -11
  50. package/dist/agent-BRENvuvx.mjs.map +0 -1
  51. package/dist/compactions-HFjEgrv3.mjs.map +0 -1
  52. package/dist/html-VrAsoGBK.mjs.map +0 -1
  53. package/dist/index-node-esm-BwaOzhXB.mjs.map +0 -1
  54. package/dist/session-C8zqqbPE.mjs.map +0 -1
  55. package/dist/session-Cq52cam5.d.mts.map +0 -1
  56. package/dist/src-C04Qk9KE.mjs.map +0 -1
  57. package/dist/tasks-D76WXWr2.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"tools-DmoUYORG.mjs","names":["shellParse"],"sources":["../../../node_modules/.bun/shell-quote@1.12.0/node_modules/shell-quote/quote.js","../../../node_modules/.bun/shell-quote@1.12.0/node_modules/shell-quote/parse.js","../../../node_modules/.bun/shell-quote@1.12.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\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\tvar sawComment = false;\n\treturn xs.map(function (s) {\n\t\tif (sawComment && typeof s === 'string' && LINE_TERMINATORS.test(s)) {\n\t\t\tthrow new TypeError('a token after a `comment` must not contain line terminators');\n\t\t}\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\tif (s.pattern === '') {\n\t\t\t\t\treturn /** @type {const} */ ('\\'\\'');\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\tsawComment = true;\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 ((/'/).test(s) && (/!/).test(s)) {\n\t\t\treturn \"'\" + s.replace(/'/g, \"'\\\"'\\\"'\") + \"'\";\n\t\t}\n\t\tif ((/[\"\\s\\\\]/).test(s) && !(/'/).test(s)) {\n\t\t\treturn \"'\" + s + \"'\";\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// '<(' and '>(' are process substitution operators and\n// can be parsed the same as control operator\nvar CONTROL = /** @type {const} */ ('(?:') + /** @type {const} */ ([\n\t'\\\\|\\\\|',\n\t'\\\\&(?:\\\\&|>>?)', // `&&`, `&>`, and `&>>`\n\t';;\\\\&?', // `;;` and `;;&`\n\t'[;|]\\\\&', // `;&` and `|&`\n\t'\\\\<\\\\(',\n\t'\\\\<\\\\<\\\\<',\n\t'\\\\<\\\\<-',\n\t'\\\\<\\\\<(?!\\\\()', // `<<(` stays `<` and `<(`, as zsh reads it; other shells reject it\n\t'>>',\n\t'>[&|(]', // `>&`, `>|`, and `>(`\n\t'<[&>]', // `<&` and `<>`\n\t'[&;()|<>]'\n]).join(/** @type {const} */ ('|')) + /** @type {const} */ (')');\nvar controlRE = new RegExp('^' + CONTROL + '$');\nvar META = /** @type {const} */ ('|&;()<> \\\\t');\nvar SINGLE_QUOTE = /** @type {const} */ ('\\'([^\\']*?)\\'');\n// bash ANSI-C quoting, `$'...'`: a backslash escapes the next character, including `'`\nvar ANSI_C_BODY = '(?:\\\\\\\\[\\\\s\\\\S]|[^\\\\\\\\\\'])*?';\nvar ANSI_C_QUOTE = '\\\\$\\'' + ANSI_C_BODY + '\\'';\nvar ansiCAt = new RegExp('\\\\$\\'' + ANSI_C_BODY + '(?:(\\')|\\\\\\\\?$)', 'g');\nvar ANSI_C_LETTERS = 'abeEfnrtv';\nvar ANSI_C_CHARS = '\\x07\\b\\x1B\\x1B\\f\\n\\r\\t\\v';\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\nvar ansiCEscape = /\\\\([0-7]{1,3}|x[\\dA-Fa-f]{1,2}|u[\\dA-Fa-f]{1,4}|U[\\dA-Fa-f]{1,8}|c(?:\\\\\\\\|[\\s\\S])|[abeEfnrtv\\\\'\"?])/g;\n\n/**\n * @param {string} m\n * @param {string} escape\n */\nfunction expandAnsiCEscape(m, escape) {\n\tvar kind = escape.charAt(0);\n\tif (kind === 'c') {\n\t\tvar ctrl = escape.charAt(1);\n\t\treturn ctrl === '?' ? '\\x7F' : String.fromCharCode(ctrl.charCodeAt(0) & 0x1F);\n\t}\n\tif (kind === 'x' || kind === 'u' || kind === 'U') {\n\t\tvar cp = parseInt(escape.slice(1), 16);\n\t\tif (cp > 0x10FFFF) {\n\t\t\treturn m;\n\t\t}\n\t\treturn String.fromCharCode.apply(null, cp > 0xFFFF ? [0xD7C0 + (cp >> 10), 0xDC00 + (cp & 0x3FF)] : [cp]);\n\t}\n\tif (kind >= '0' && kind <= '7') {\n\t\treturn String.fromCharCode(parseInt(escape, 8) & 0xFF);\n\t}\n\tvar letter = ANSI_C_LETTERS.indexOf(escape);\n\treturn letter < 0 ? escape : ANSI_C_CHARS.charAt(letter);\n}\n\n/** @param {string} body */\nfunction expandAnsiC(body) {\n\treturn body.replace(ansiCEscape, expandAnsiCEscape).split('\\0')[0]; // like bash, a NUL ends the string\n}\n\n/**\n * @param {string} s\n * @param {number} i\n */\nfunction closesAnsiC(s, i) {\n\tansiCAt.lastIndex = i;\n\treturn !!(/** @type {RegExpExecArray} */ (ansiCAt.exec(s)))[1];\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 + '[\\'\"$\\\\' + BS + META + ']|\\\\$\\\\$|\\\\$(?!' + ANSI_C_QUOTE.slice(2) + ')|[^\\\\s\\'\"$' + META + '])+';\n\tvar DOUBLE_QUOTE = '\"(?:\\\\' + BS + '[\\\\s\\\\S]|[^\"\\\\' + BS + '])*\"';\n\n\tvar chunker = new RegExp([\n\t\t'(' + CONTROL + ')', // control chars\n\t\t'(' + ANSI_C_QUOTE + '|' + 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} 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 && s.charAt(i + 1) === SQ && closesAnsiC(s, i)) {\n\t\t\t\tflushRun();\n\t\t\t\tsawQuote = true;\n\t\t\t\tout += expandAnsiC(s.slice(i + 2, ansiCAt.lastIndex - 1));\n\t\t\t\ti = ansiCAt.lastIndex - 1;\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"],"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;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD;CACA,IAAI,mBAAmB;CACvB,IAAI,qBAAqB;;CAGzB,OAAO,UAAU,SAAS,MAAM,IAAI;EACnC,IAAI,aAAa;EACjB,OAAO,GAAG,IAAI,SAAU,GAAG;GAC1B,IAAI,cAAc,OAAO,MAAM,YAAY,iBAAiB,KAAK,CAAC,GACjE,MAAM,IAAI,UAAU,6DAA6D;GAElF,IAAI,MAAM,IACT,OAA6B;GAE9B,IAAI,KAAK,OAAO,MAAM,UAAU;IAC/B,IAA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AAY;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
+ {"version":3,"file":"tools-Ca7VsMg3.mjs","names":["shellParse"],"sources":["../../../node_modules/.bun/shell-quote@1.12.0/node_modules/shell-quote/quote.js","../../../node_modules/.bun/shell-quote@1.12.0/node_modules/shell-quote/parse.js","../../../node_modules/.bun/shell-quote@1.12.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\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\tvar sawComment = false;\n\treturn xs.map(function (s) {\n\t\tif (sawComment && typeof s === 'string' && LINE_TERMINATORS.test(s)) {\n\t\t\tthrow new TypeError('a token after a `comment` must not contain line terminators');\n\t\t}\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\tif (s.pattern === '') {\n\t\t\t\t\treturn /** @type {const} */ ('\\'\\'');\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\tsawComment = true;\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 ((/'/).test(s) && (/!/).test(s)) {\n\t\t\treturn \"'\" + s.replace(/'/g, \"'\\\"'\\\"'\") + \"'\";\n\t\t}\n\t\tif ((/[\"\\s\\\\]/).test(s) && !(/'/).test(s)) {\n\t\t\treturn \"'\" + s + \"'\";\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// '<(' and '>(' are process substitution operators and\n// can be parsed the same as control operator\nvar CONTROL = /** @type {const} */ ('(?:') + /** @type {const} */ ([\n\t'\\\\|\\\\|',\n\t'\\\\&(?:\\\\&|>>?)', // `&&`, `&>`, and `&>>`\n\t';;\\\\&?', // `;;` and `;;&`\n\t'[;|]\\\\&', // `;&` and `|&`\n\t'\\\\<\\\\(',\n\t'\\\\<\\\\<\\\\<',\n\t'\\\\<\\\\<-',\n\t'\\\\<\\\\<(?!\\\\()', // `<<(` stays `<` and `<(`, as zsh reads it; other shells reject it\n\t'>>',\n\t'>[&|(]', // `>&`, `>|`, and `>(`\n\t'<[&>]', // `<&` and `<>`\n\t'[&;()|<>]'\n]).join(/** @type {const} */ ('|')) + /** @type {const} */ (')');\nvar controlRE = new RegExp('^' + CONTROL + '$');\nvar META = /** @type {const} */ ('|&;()<> \\\\t');\nvar SINGLE_QUOTE = /** @type {const} */ ('\\'([^\\']*?)\\'');\n// bash ANSI-C quoting, `$'...'`: a backslash escapes the next character, including `'`\nvar ANSI_C_BODY = '(?:\\\\\\\\[\\\\s\\\\S]|[^\\\\\\\\\\'])*?';\nvar ANSI_C_QUOTE = '\\\\$\\'' + ANSI_C_BODY + '\\'';\nvar ansiCAt = new RegExp('\\\\$\\'' + ANSI_C_BODY + '(?:(\\')|\\\\\\\\?$)', 'g');\nvar ANSI_C_LETTERS = 'abeEfnrtv';\nvar ANSI_C_CHARS = '\\x07\\b\\x1B\\x1B\\f\\n\\r\\t\\v';\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\nvar ansiCEscape = /\\\\([0-7]{1,3}|x[\\dA-Fa-f]{1,2}|u[\\dA-Fa-f]{1,4}|U[\\dA-Fa-f]{1,8}|c(?:\\\\\\\\|[\\s\\S])|[abeEfnrtv\\\\'\"?])/g;\n\n/**\n * @param {string} m\n * @param {string} escape\n */\nfunction expandAnsiCEscape(m, escape) {\n\tvar kind = escape.charAt(0);\n\tif (kind === 'c') {\n\t\tvar ctrl = escape.charAt(1);\n\t\treturn ctrl === '?' ? '\\x7F' : String.fromCharCode(ctrl.charCodeAt(0) & 0x1F);\n\t}\n\tif (kind === 'x' || kind === 'u' || kind === 'U') {\n\t\tvar cp = parseInt(escape.slice(1), 16);\n\t\tif (cp > 0x10FFFF) {\n\t\t\treturn m;\n\t\t}\n\t\treturn String.fromCharCode.apply(null, cp > 0xFFFF ? [0xD7C0 + (cp >> 10), 0xDC00 + (cp & 0x3FF)] : [cp]);\n\t}\n\tif (kind >= '0' && kind <= '7') {\n\t\treturn String.fromCharCode(parseInt(escape, 8) & 0xFF);\n\t}\n\tvar letter = ANSI_C_LETTERS.indexOf(escape);\n\treturn letter < 0 ? escape : ANSI_C_CHARS.charAt(letter);\n}\n\n/** @param {string} body */\nfunction expandAnsiC(body) {\n\treturn body.replace(ansiCEscape, expandAnsiCEscape).split('\\0')[0]; // like bash, a NUL ends the string\n}\n\n/**\n * @param {string} s\n * @param {number} i\n */\nfunction closesAnsiC(s, i) {\n\tansiCAt.lastIndex = i;\n\treturn !!(/** @type {RegExpExecArray} */ (ansiCAt.exec(s)))[1];\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 + '[\\'\"$\\\\' + BS + META + ']|\\\\$\\\\$|\\\\$(?!' + ANSI_C_QUOTE.slice(2) + ')|[^\\\\s\\'\"$' + META + '])+';\n\tvar DOUBLE_QUOTE = '\"(?:\\\\' + BS + '[\\\\s\\\\S]|[^\"\\\\' + BS + '])*\"';\n\n\tvar chunker = new RegExp([\n\t\t'(' + CONTROL + ')', // control chars\n\t\t'(' + ANSI_C_QUOTE + '|' + 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} 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 && s.charAt(i + 1) === SQ && closesAnsiC(s, i)) {\n\t\t\t\tflushRun();\n\t\t\t\tsawQuote = true;\n\t\t\t\tout += expandAnsiC(s.slice(i + 2, ansiCAt.lastIndex - 1));\n\t\t\t\ti = ansiCAt.lastIndex - 1;\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"],"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;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD;CACA,IAAI,mBAAmB;CACvB,IAAI,qBAAqB;;CAGzB,OAAO,UAAU,SAAS,MAAM,IAAI;EACnC,IAAI,aAAa;EACjB,OAAO,GAAG,IAAI,SAAU,GAAG;GAC1B,IAAI,cAAc,OAAO,MAAM,YAAY,iBAAiB,KAAK,CAAC,GACjE,MAAM,IAAI,UAAU,6DAA6D;GAElF,IAAI,MAAM,IACT,OAA6B;GAE9B,IAAI,KAAK,OAAO,MAAM,UAAU;IAC/B,IAAI,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Y;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,6 +1,6 @@
1
+ import { AiError, defineTool } from "@zaly/ai";
1
2
  import { normPath, safeReadFile } from "@zaly/shared";
2
3
  import { dirname } from "pathe";
3
- import { AiError, defineTool } from "@zaly/ai";
4
4
  import { mkdir, stat, writeFile } from "node:fs/promises";
5
5
  import { Type } from "typebox";
6
6
  import { detectEol, normalizeEol } from "@zaly/shared/text";
@@ -77,4 +77,4 @@ function countLines(content) {
77
77
  }
78
78
  export { writeTool };
79
79
 
80
- //# sourceMappingURL=write-BRQFfWAn.mjs.map
80
+ //# sourceMappingURL=write-y93TC5ng.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"write-BRQFfWAn.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 } 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\"\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 * 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; \" +\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 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 the new mtime for unchanged-read detection and mark the\n // full-file replacement for context masking.\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":";;;;;;;;;;;;;;;;;;;;;;AAmCA,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;EAExC,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,OAAO,KAAK;GAC5F,CAAC;EACH;EAKA,IAAI,OAAO;GAAE,MAAM;GAAM,MAAM;GAAS,QAAO,MAD3B,KAAK,IAAI,EAAA,CACwB;GAAS;GAAU;EAAK;EAI7E,OAAO;GAAE,OAFK,OAAO,WAAW,MAAM,MAEzB;GAAG,OADF,WAAW,IACL;GAAG,IAAI;GAAM;EAAK;CACxC;AACF,CAAC;;;AAID,SAAS,WAAW,SAAyB;CAC3C,IAAI,YAAY,IAAI,OAAO;CAC3B,IAAI,IAAI;CACR,KAAK,MAAM,KAAK,SAAS,IAAI,MAAM,MAAM;CAEzC,IAAI,QAAQ,SAAS,IAAI,GAAG;CAC5B,OAAO;AACT"}
1
+ {"version":3,"file":"write-y93TC5ng.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 } 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\"\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 * 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; \" +\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 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 the new mtime for unchanged-read detection and mark the\n // full-file replacement for context masking.\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":";;;;;;;;;;;;;;;;;;;;;;AAmCA,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;EAExC,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,OAAO,KAAK;GAC5F,CAAC;EACH;EAKA,IAAI,OAAO;GAAE,MAAM;GAAM,MAAM;GAAS,QAAO,MAD3B,KAAK,IAAI,EAAA,CACwB;GAAS;GAAU;EAAK;EAI7E,OAAO;GAAE,OAFK,OAAO,WAAW,MAAM,MAEzB;GAAG,OADF,WAAW,IACL;GAAG,IAAI;GAAM;EAAK;CACxC;AACF,CAAC;;;AAID,SAAS,WAAW,SAAyB;CAC3C,IAAI,YAAY,IAAI,OAAO;CAC3B,IAAI,IAAI;CACR,KAAK,MAAM,KAAK,SAAS,IAAI,MAAM,MAAM;CAEzC,IAAI,QAAQ,SAAS,IAAI,GAAG;CAC5B,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaly/agent",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Agent runtime, sessions, tools, permissions, compaction, and tasks for zaly.",
5
5
  "keywords": [
6
6
  "agent",
@@ -33,8 +33,8 @@
33
33
  "access": "public"
34
34
  },
35
35
  "dependencies": {
36
- "@zaly/ai": "0.1.1",
37
- "@zaly/shared": "0.1.1",
36
+ "@zaly/ai": "0.3.0",
37
+ "@zaly/shared": "0.3.0",
38
38
  "pathe": "^2.0.3"
39
39
  },
40
40
  "devDependencies": {
@@ -43,26 +43,26 @@
43
43
  "@types/shell-quote": "^1.7.5",
44
44
  "@types/turndown": "^5.0.6",
45
45
  "ignore": "^7.0.14",
46
- "jsonpath-plus": "^11.2.1",
47
- "linkedom": "^0.18.14",
46
+ "jsonpath-plus": "^11.3.0",
47
+ "linkedom": "^0.18.15",
48
48
  "shell-quote": "^1.12.0",
49
- "turndown": "^7.2.4"
49
+ "turndown": "^7.2.5"
50
50
  },
51
51
  "peerDependencies": {
52
- "typebox": "^1.4.3"
52
+ "typebox": "^1.4.5"
53
53
  },
54
54
  "engines": {
55
55
  "bun": ">=1.2",
56
56
  "node": ">=22.18.0"
57
57
  },
58
58
  "inlinedDependencies": {
59
- "@acemir/cssom": "0.9.32",
60
59
  "@joplin/turndown-plugin-gfm": "1.0.68",
61
60
  "@mixmark-io/domino": "2.2.0",
62
61
  "@mozilla/readability": "0.6.0",
63
62
  "boolbase": "2.0.0",
64
63
  "css-select": "7.0.0",
65
64
  "css-what": "8.0.0",
65
+ "cssomnom": "0.1.11",
66
66
  "dom-serializer": [
67
67
  "2.0.0",
68
68
  "3.1.1"
@@ -86,11 +86,11 @@
86
86
  ],
87
87
  "htmlparser2": "10.1.0",
88
88
  "ignore": "7.0.14",
89
- "jsonpath-plus": "11.2.1",
90
- "linkedom": "0.18.14",
89
+ "jsonpath-plus": "11.3.0",
90
+ "linkedom": "0.18.15",
91
91
  "nth-check": "3.0.1",
92
92
  "shell-quote": "1.12.0",
93
- "turndown": "7.2.4",
93
+ "turndown": "7.2.5",
94
94
  "uhyphen": "0.2.0"
95
95
  },
96
96
  "scripts": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"agent-BRENvuvx.mjs","names":[],"sources":["../src/utils/usage.ts","../src/stop.ts","../src/agent.ts"],"sourcesContent":["import type { Message, TokenCount, Usage } from \"@zaly/ai\"\n\n/** Sum two Usages. Optional fields are only present in the result\n * when at least one input had them set, so callers can tell \"no\n * reasoning happened this turn\" apart from \"0 reasoning tokens.\" */\nexport function addUsage(a: Usage, b: Usage): Usage {\n const out: Usage = {\n input: a.input + b.input,\n output: a.output + b.output,\n }\n if (a.cacheRead !== undefined || b.cacheRead !== undefined) {\n out.cacheRead = (a.cacheRead ?? 0) + (b.cacheRead ?? 0)\n }\n if (a.cacheWrite !== undefined || b.cacheWrite !== undefined) {\n out.cacheWrite = (a.cacheWrite ?? 0) + (b.cacheWrite ?? 0)\n }\n if (a.reasoning !== undefined || b.reasoning !== undefined) {\n out.reasoning = (a.reasoning ?? 0) + (b.reasoning ?? 0)\n }\n if (a.cost || b.cost) out.cost = addUsage(a.cost ?? empty(), b.cost ?? empty())\n return out\n}\n\nexport class TokenUsage implements Usage {\n #last: Usage = empty()\n #total: Usage = empty()\n\n constructor(messages?: readonly Message[]) {\n for (const m of messages ?? [])\n if (m.role === \"assistant\" && m.meta?.usage) this.add(m.meta.usage)\n }\n\n get cost(): Usage {\n return this.total.cost ?? empty()\n }\n\n get input(): number {\n return this.last.input\n }\n\n get output(): number {\n return this.last.output\n }\n\n get cacheRead(): number {\n return this.last.cacheRead ?? 0\n }\n\n get cacheWrite(): number {\n return this.last.cacheWrite ?? 0\n }\n\n get reasoning(): number {\n return this.last.reasoning ?? 0\n }\n\n add(count: Usage): void {\n this.#last = count\n this.#total = addUsage(this.#total, count)\n }\n\n resetLast(): void {\n this.#last = empty()\n }\n\n get last(): Usage {\n return this.#last\n }\n\n get total(): Usage {\n return this.#total\n }\n\n get contextSize(): number {\n return (\n this.last.input + this.last.output + (this.last.cacheRead ?? 0) + (this.last.cacheWrite ?? 0)\n )\n }\n}\n\nfunction empty(): TokenCount {\n return { input: 0, output: 0 }\n}\n","import type { TokenCount, ToolCallPart } from \"@zaly/ai\"\nimport type { Emitter, Envelope } from \"@zaly/shared\"\nimport type { AgentEvents, AgentStopKind } from \"./events.ts\"\n\nimport { safeStringify } from \"@zaly/shared\"\nimport { addUsage } from \"./utils/usage.ts\"\n\n/** Caps + heuristics that can end a run early. Wired into the\n * `AgentSession` loop via a single `detect()` call after each step. */\nexport interface StopOptions {\n /** Hard ceiling on provider round-trips per `run()`. Default: 50. */\n maxSteps?: number\n /** Cumulative token cap across the whole `run()`\n * (`totalUsage.input + totalUsage.output`). */\n tokenBudget?: number\n /** Bail after this many consecutive failing tool calls. A successful\n * tool result resets the streak. */\n maxToolErrors?: number\n\n // ── Loop detection ──────────────────────────────────────────────────\n // Two cheap heuristics over the running tool-call history. Hash is\n // `name + JSON.stringify(params)`; property order matters (rare false\n // negative if the model alternates key order on the same logical call,\n // accepted in exchange for a much cheaper hash). Set either limit to\n // `Infinity` to disable that arm.\n\n /** Same `(name, params)` appearing N times in a row → loop. Catches\n * the most common failure mode: re-calling `read_file` with the same\n * path expecting different output. Default 3. */\n loopConsecutive?: number\n /** Bounded window for duplicate detection. Default 10. */\n loopWindow?: number\n /** Within the window, this many duplicates of one call → loop.\n * Catches alternation patterns (`A B A B …`) the consecutive arm\n * alone won't see. Default 4. */\n loopWindowRepeats?: number\n}\n\n/**\n * Subscribes to an `AgentEvent` stream, accumulates the bookkeeping\n * the loop needs to make stop-or-continue decisions, and exposes a\n * single `detect()` to consult after each step.\n *\n * Lives outside `AgentSession` so concerns separate cleanly:\n * - the session owns conversation, queues, status, and loop control;\n * - the policy owns counters and the rules that act on them.\n *\n * Wire it up via `attach(session)` (returns an unsubscribe), or feed\n * events manually with `handle(event)` for custom drivers.\n */\nexport class StopPolicy {\n readonly #opts: StopOptions\n\n #steps = 0\n #consecutiveErrors = 0\n #calls: ToolCallPart[] = []\n #usage: TokenCount = { input: 0, output: 0 }\n #totalUsage: TokenCount = { input: 0, output: 0 }\n\n constructor(opts: StopOptions = {}) {\n this.#opts = opts\n }\n\n // ── Read ──────────────────────────────────────────────────────────────\n\n /** Token usage from the most recent step's response. */\n get usage(): TokenCount {\n return this.#usage\n }\n /** Cumulative token usage across every step in the current run. */\n get totalUsage(): TokenCount {\n return this.#totalUsage\n }\n get steps(): number {\n return this.#steps\n }\n get consecutiveErrors(): number {\n return this.#consecutiveErrors\n }\n /** Tool-call history fed to the loop detector. Read-only. */\n get calls(): readonly ToolCallPart[] {\n return this.#calls\n }\n\n // ── Wiring ────────────────────────────────────────────────────────────\n\n /** Subscribe to an emitter. To detach later, register the listener\n * yourself and pass the same fn to `emitter.off(fn)`:\n *\n * const handler = (e) => policy.handle(e)\n * emitter.all(handler)\n * // later:\n * emitter.off(handler) */\n attach(emitter: Emitter<AgentEvents>): void {\n emitter.onAny((event) => this.handle(event))\n }\n\n /** Feed a single event into the policy. Public so custom drivers\n * can drive it without going through `attach`. */\n handle(event: Envelope<AgentEvents>): void {\n switch (event.type) {\n case \"step-end\": {\n this.#steps++\n break\n }\n case \"tool-call\": {\n this.#calls.push(event.call)\n break\n }\n case \"tool-result\": {\n this.#consecutiveErrors = event.result.isError ? this.#consecutiveErrors + 1 : 0\n break\n }\n case \"stream-event\": {\n if (event.event.type === \"finish\") {\n this.#usage = event.event.usage\n this.#totalUsage = addUsage(this.#totalUsage, event.event.usage)\n }\n break\n }\n // status / stop — no policy state to update.\n }\n }\n\n /** Reset per-run counters. Token totals (`usage` / `totalUsage`)\n * persist unless `keepUsage: false` is passed — billing-style\n * displays usually want them sticky across resets. */\n reset(opts: { keepUsage?: boolean } = {}): void {\n this.#steps = 0\n this.#consecutiveErrors = 0\n this.#calls = []\n if (opts.keepUsage === false) {\n this.#usage = { input: 0, output: 0 }\n this.#totalUsage = { input: 0, output: 0 }\n }\n }\n\n /** Decide whether the loop should stop. Returns the stop reason or\n * `undefined` to continue. Order matters — `loop-detected` wins\n * over `max-tool-errors` if both fire, since a model in a tight\n * loop is the more pressing thing to surface. */\n detect(): AgentStopKind | undefined {\n if (this.#opts.maxSteps !== undefined && this.#steps >= this.#opts.maxSteps) {\n return \"max-steps\"\n }\n if (this.#detectLoop()) {\n return \"loop-detected\"\n }\n if (\n this.#opts.maxToolErrors !== undefined &&\n this.#consecutiveErrors >= this.#opts.maxToolErrors\n ) {\n return \"max-tool-errors\"\n }\n if (\n this.#opts.tokenBudget !== undefined &&\n this.#totalUsage.input + this.#totalUsage.output > this.#opts.tokenBudget\n ) {\n return \"token-budget\"\n }\n return undefined\n }\n\n // ── Loop detection internals ─────────────────────────────────────────\n\n #detectLoop(): boolean {\n const calls = this.#calls\n if (calls.length === 0) return false\n\n const consecutive = this.#opts.loopConsecutive ?? 3\n if (Number.isFinite(consecutive) && calls.length >= consecutive) {\n const last = hashCall(calls[calls.length - 1])\n let run = 1\n for (let i = calls.length - 2; i >= 0 && run < consecutive; i--) {\n if (hashCall(calls[i]) === last) run++\n else break\n }\n if (run >= consecutive) return true\n }\n\n const window = this.#opts.loopWindow ?? 10\n const windowRepeats = this.#opts.loopWindowRepeats ?? 4\n if (Number.isFinite(windowRepeats) && calls.length >= windowRepeats) {\n const slice = calls.slice(Math.max(0, calls.length - window))\n const counts = new Map<string, number>()\n for (const call of slice) {\n const h = hashCall(call)\n const next = (counts.get(h) ?? 0) + 1\n if (next >= windowRepeats) return true\n counts.set(h, next)\n }\n }\n\n return false\n }\n}\n\nfunction hashCall(call: ToolCallPart): string {\n return `${call.name}\\0${safeStringify(call.params)}`\n}\n","// oxlint-disable no-await-in-loop\nimport type {\n AssistantMessage,\n Content,\n Context,\n Message,\n MetaOf,\n MetaPart,\n Model,\n ModelStreamOptions,\n ParamsOf,\n TokenCount,\n Tool,\n ToolCallPart,\n ToolContext,\n ToolResult,\n} from \"@zaly/ai\"\nimport type { CompactionOptions } from \"./compaction/compactions.ts\"\nimport type { AgentContext } from \"./ctx.ts\"\nimport type { AgentEvents, AgentStatus, AgentStop, AgentStopKind } from \"./events.ts\"\nimport type { Session } from \"./session/session.ts\"\nimport type { AgentOptions, ContextPressure, SendMode, StepResult, TurnResult } from \"./types.ts\"\n\nimport { AiError, isContextOverflow, runTool } from \"@zaly/ai\"\nimport { Emitter, toValue, toError } from \"@zaly/shared\"\nimport { StopPolicy } from \"./stop.ts\"\nimport { Tasks, taskCompletionMessage, taskInfoPart } from \"./tasks.ts\"\nimport { TokenUsage } from \"./utils/usage.ts\"\nimport { uuidv7 } from \"./utils/uuid.ts\"\n\nconst PRESSURE_LEVELS = [0.75, 0.85, 0.95] as const\n\n/**\n * Long-lived agent — drives the multi-turn loop, owns the run-time\n * status / queues, and delegates conversation state to a `Session`.\n *\n * Typical interactive use:\n *\n * ```ts\n * const agent = await Agent.load({ model, tools })\n * agent.session.on(\"node\", (e) => render(e))\n * agent.send({ role: \"user\", content: \"hi\" }) // auto-runs\n * // …user types again later…\n * agent.send({ role: \"user\", content: \"follow-up\" }) // queues if running\n * ```\n *\n * Headless / one-shot use is just a thin wrapper on top — see\n * `runAgent` in the test helpers.\n */\nexport class Agent extends Emitter<AgentEvents> {\n readonly #opts: AgentOptions\n readonly #ctx: AgentContext\n readonly #stopPolicy: StopPolicy\n readonly #tasks: Tasks\n /** Nesting depth — see `AgentOptions.depth`. Read-only; subagents pass\n * `parent.depth + 1` when constructing their child. */\n readonly depth: number\n /** Cap on `depth` — see `AgentOptions.maxDepth`. */\n readonly maxDepth: number\n #started = false\n\n #parent?: Agent\n\n #injectQueue: Message[] = []\n #appendQueue: Message[][] = []\n #notifyQueue: MetaPart[] = []\n\n #status: AgentStatus = \"idle\"\n #abortController?: AbortController\n #pauseRequested?: string\n #running?: Promise<AgentStopKind>\n #usage: TokenUsage\n\n /** Pending future-injects scheduled via `scheduleWakeup`. Cleared\n * whenever the loop becomes active for any reason — the scheduled\n * inject was a fallback \"wake me up at time T if nothing else does,\"\n * and once something else has, the timer is moot. Hints from cancelled\n * wakeups carry over as a system message so the intent doesn't\n * evaporate. */\n readonly #wakeups = new Map<string, { timer: ReturnType<typeof setTimeout>; hint?: string }>()\n\n #lastStop?: AgentStop\n\n /** Synchronous, low-level constructor. Prefer `Agent.load(opts)` —\n * it runs the same construction *plus* any async setup (resolving\n * `session: SessionOptions` to a built `Session`, skills discovery,\n * future warm-ups). The constructor is `protected` so test doubles /\n * subclasses can still call `super(init)` directly; they're\n * responsible for providing a pre-built `Session` on `init.session`. */\n public constructor(ctx: AgentContext) {\n super()\n const opts = ctx.opts\n this.#ctx = ctx\n this.#opts = ctx.opts\n this.depth = opts.depth ?? 0\n this.maxDepth = opts.maxDepth ?? 2\n\n // Note: session.update() + initial messages are committed\n // asynchronously from `Agent.load`, NOT here. Constructors can't\n // be async; deferring those writes until after construction also\n // gives consumers a window to subscribe to session events before\n // the first node fires.\n\n this.#tasks = new Tasks()\n this.#tasks.$tools = async () => this.tools\n this.#tasks.heartbeatMs = opts.heartbeatMs\n this.#tasks.onEmitError = (error) => opts.logger?.child(\"tasks\").error(error)\n // Post-round task completions inject a system message into the next\n // step, surfacing the result to the model. Round-internal completions\n // are folded into the round's returned parts and don't fire here.\n this.#tasks.on(\"task-done\", ({ task }) => {\n this.send(taskCompletionMessage(task))\n })\n // Heartbeats keep the agent loop alive while long-running tasks are\n // in flight. Each pulse injects a small system note listing what's\n // still going. Tasks with incremental output ready to read get a\n // `*new*` marker so the model knows to call `task_poll` if it cares.\n this.#tasks.on(\"heartbeat\", ({ running }) => {\n this.send({\n content: [{ content: [taskInfoPart(running)], tag: \"heartbeat\", type: \"meta\" }],\n role: \"system\",\n })\n })\n\n this.#stopPolicy = new StopPolicy(opts.stop)\n this.#stopPolicy.attach(this)\n this.onEmitError = (error) => opts.logger?.child(\"events\").error(error)\n this.#ctx.attach(this)\n\n // Seed usage\n this.#usage = new TokenUsage(this.messages)\n this.#ctx.on(\"session\", () => this.reset())\n }\n\n async reset(): Promise<void> {\n this.stop({ abort: true, reason: \"reset\" })\n await this.waitIdle()\n await this.#tasks.killAll()\n this.#cancelAllWakeups()\n this.#usage = new TokenUsage(this.messages)\n this.#stopPolicy.reset({ keepUsage: false })\n this.#injectQueue = []\n this.#appendQueue = []\n this.#notifyQueue = []\n this.#wakeups.clear()\n this.#stop(\"natural\")\n }\n\n /** Spawn a child agent that inherits this agent's runtime defaults —\n * cwd, model, permissions, full effective tool list (user tools +\n * the loaded skill tool), `depth + 1`, and `maxDepth`. Pass\n * `overrides` to specialize: typical ones are `prompt` (the child\n * has its own role), `session` (the child writes to its own JSONL),\n * and `tools` (curated subset).\n *\n * Used by the `subagent` tool for delegation; equally useful for\n * ad-hoc parallel-agent patterns (multiple children working on\n * pieces of a task in parallel).\n *\n * Depth cap: when the child would be at `maxDepth`, the `subagent`\n * tool is filtered out of its inherited tool list so recursion\n * bottoms out cleanly. The model just doesn't see the tool — no\n * error path. */\n async child(overrides: Partial<AgentOptions> = {}): Promise<Agent> {\n const childDepth = overrides.depth ?? this.depth + 1\n // Inherit the *effective* step tool list (includes the loaded\n // `skill` tool). The child opts out of its own skill scan since\n // the catalog is shared.\n\n let tools = [...this.tools].filter((t) => t.name !== \"skill\")\n if (childDepth >= this.maxDepth) tools = tools.filter((t) => t.name !== \"subagent\")\n const { createAgent } = await import(\"./ctx.ts\")\n\n const ret = await createAgent({\n cwd: this.cwd,\n depth: childDepth,\n mask: this.#opts.mask,\n maxDepth: this.maxDepth,\n model: this.model,\n // Inherit the parent's `notify` setting so test roots that\n // disable the notifier (`notify: false`) propagate that to\n // children — otherwise spawning a child would silently re-enable\n // session-started / time / etc. injections that the harness\n // explicitly opted out of.\n notify: this.#opts.notify,\n permissions: await this.ctx.permissions(),\n skills: this.#ctx.skills, // shared catalog; child doesn't reload\n // Propagate the swarm so the child + every grandchild address\n // each other through the same registry. Override-able via\n // `overrides.swarm` if a caller wants the child outside the\n // tree (rare).\n swarm: await this.#ctx.swarm(),\n tools,\n ...overrides,\n })\n ret.#parent = this\n // Children are spawned ready — subagent dispatch typically calls\n // `.send()` immediately after, and inspecting `child.tools` /\n // `child.prompt` before sending should just work.\n await ret.start()\n return ret\n }\n\n // ── Read ──────────────────────────────────────────────────────────────\n\n /** Active conversation — delegates to the underlying `Session`. */\n get messages(): readonly Message[] {\n return this.session.messages\n }\n\n get status(): AgentStatus {\n return this.#status\n }\n\n get cwd(): string {\n return this.#ctx.cwd\n }\n\n get model(): Model | undefined {\n return this.#ctx.model\n }\n\n get session(): Session {\n return this.#ctx.session\n }\n\n get signal(): AbortSignal | undefined {\n return this.#abortController?.signal\n }\n\n /** Token usage from the most recent step's response. Drives\n * `contextSize` and any \"this turn used N tokens\" UI. */\n get usage(): TokenUsage {\n return this.#usage\n }\n\n /** Cumulative token usage across every step in the current run.\n * Useful for billing-style displays. */\n get totalUsage(): TokenCount {\n return this.#usage.total\n }\n /** Logical size of the current conversation in tokens — what the\n * next request will send as input. Equals the last step's\n * `input + output` (since the model's reply becomes part of the\n * next prompt). Returns 0 before any step has run. */\n get contextSize(): number {\n return this.#usage.contextSize\n }\n\n get pressure(): ContextPressure {\n const used = this.contextSize\n const limit = this.model?.spec.contextSize ?? 0\n const ratio = limit > 0 ? used / limit : 0\n const level = PRESSURE_LEVELS.findLast((t) => ratio >= t) ?? 0\n return { level, limit, ratio, used }\n }\n\n get lastStop(): AgentStop | undefined {\n return this.#lastStop\n }\n\n get steps(): number {\n return this.#stopPolicy.steps\n }\n\n get parent(): Agent | undefined {\n return this.#parent\n }\n\n get tools() {\n return this.#ctx.tools\n }\n\n get prompt() {\n return this.#ctx.prompt\n }\n\n get ctx(): AgentContext {\n return this.#ctx\n }\n\n /** Long-running task registry — exposed for the TUI / introspection\n * tools (`task_list`, etc.). Mutating directly is a foot-gun;\n * prefer the agent's higher-level surface. */\n get tasks(): Tasks {\n return this.#tasks\n }\n\n // ── Input ────────────────────────────────────────────────────────────\n\n #enqueue(message: Message | Message[], opts: { mode?: SendMode } = {}): void {\n const messages = Array.isArray(message) ? message : [message]\n if (!messages.length) return\n for (const m of messages) m.id ??= uuidv7()\n if (opts.mode === \"append\") this.#appendQueue.push(messages)\n else this.#injectQueue.push(...messages)\n void this.emit(\"pending\", { messages })\n }\n\n /** Queue messages and start/resume the loop when idle or paused.\n * `inject` (default) delivers before the next model step without\n * interrupting an active response or tool batch. `append` waits until\n * the current turn finishes naturally and no injections remain.\n * Injections batch in queue order; appends run one send() submission\n * at a time, keeping each submission's messages together.\n * With `run: false`, only enqueue; omit messages to start/resume\n * processing already queued work. */\n send(message?: Message | Message[], opts: { mode?: SendMode; run?: boolean } = {}): void {\n this.#enqueue(message ?? [], opts)\n if (opts.run === false) return\n if (this.#status === \"idle\" || this.#status === \"paused\") void this.run()\n }\n\n async useTool<T extends Tool = Tool>(\n name: T[\"name\"],\n params: ParamsOf<T>,\n msg: string,\n opts: { hidden?: boolean } = {}\n ): Promise<{\n call: ToolCallPart<T[\"name\"], ParamsOf<T>>\n result: ToolResult<MetaOf<T>>\n messages: [Message<\"system\">, Message<\"assistant\">, Message<\"tool\">]\n }> {\n const tool = this.tools.find((t) => t.name === name) as T | undefined\n if (!tool) throw new Error(`cannot inject tool use: no tool named \"${name}\"`)\n\n const id = uuidv7()\n const call: ToolCallPart = { id, name, params, type: \"tool-call\" }\n const result = await runTool(tool, params, await this.#toolContext(), { preflight: false })\n const messages: [Message<\"system\">, Message<\"assistant\">, Message<\"tool\">] = [\n {\n content: [\n {\n content: msg,\n data: { tool: name },\n tag: \"user-tool-use\",\n type: \"meta\",\n },\n ],\n role: \"system\",\n },\n {\n content: [call],\n role: \"assistant\",\n },\n {\n content: [\n {\n content: result.content,\n error: result.error,\n id,\n isError: result.isError,\n meta: result.meta,\n name,\n type: \"tool-result\",\n },\n ],\n role: \"tool\",\n },\n ]\n\n if (opts.hidden) for (const m of messages) m.hidden = true\n\n return { call, messages, result: result as ToolResult<MetaOf<T>> }\n }\n\n notify(type: string, data: Content | Record<string, unknown>): void {\n const meta: MetaPart =\n typeof data === \"string\" || Array.isArray(data)\n ? { content: data, tag: type, type: \"meta\" }\n : { data, tag: type, type: \"meta\" }\n this.#notifyQueue.push(meta)\n }\n\n /** Schedule a one-shot wake-up at `delayMs` from now. The agent will\n * receive a system message at that time IF nothing else has woken\n * the loop in the meantime — task-done injects, heartbeats, and user\n * messages all auto-cancel pending wakeups (their job was to ensure\n * the agent gets a turn; if it's already getting one, the timer is\n * redundant).\n *\n * Cancelled wakeups don't silently disappear — their `hint`s, if any,\n * are folded into a system message that lands in the next step\n * alongside whatever woke the loop. The model sees the hints with a\n * `status=\"cancelled\"` marker so it knows the timer didn't fire.\n *\n * Returns the wakeup id (mostly for telemetry / TUI display — the\n * model can't usefully cancel it later, since by the time it has a\n * turn to call cancel, the wakeup has either fired or been cancelled\n * for it). */\n scheduleWakeup(opts: { delayMs: number; hint?: string }): string {\n const id = uuidv7()\n const timer = setTimeout(() => {\n this.#wakeups.delete(id)\n this.send({\n content: [{ data: { hint: opts.hint, id }, tag: \"wakeup\", type: \"meta\" }],\n role: \"system\",\n })\n }, opts.delayMs)\n timer.unref()\n this.#wakeups.set(id, { hint: opts.hint, timer })\n return id\n }\n\n /** Cancel all pending wakeups, surfacing their hints as a single\n * system message so the model can see what was queued. Called from\n * `#setStatus` whenever the agent transitions to `streaming` — that's\n * the unambiguous \"loop is active\" signal. */\n #cancelAllWakeups(): void {\n if (this.#wakeups.size === 0) return\n const carried: { id: string; hint: string }[] = []\n for (const [id, { hint, timer }] of this.#wakeups) {\n clearTimeout(timer)\n if (hint) carried.push({ hint, id })\n }\n this.#wakeups.clear()\n if (carried.length > 0) {\n const parts: MetaPart[] = carried.map((c) => ({\n data: { hint: c.hint, id: c.id, status: \"cancelled\" as const },\n tag: \"wakeup\",\n type: \"meta\",\n }))\n this.#injectQueue.push({ content: parts, role: \"system\" })\n }\n }\n\n // ── Loop control ─────────────────────────────────────────────────────\n\n /** Drive steps until the agent goes idle (no queued messages and\n * the model stopped naturally) or hits a non-recoverable stop.\n * Doubles as a resume from `paused` — drains queued messages and\n * picks the loop back up. If a run is already in flight, returns\n * the existing promise. */\n run(): Promise<AgentStopKind> {\n if (this.#running) return this.#running\n this.#pauseRequested = undefined\n this.#abortController = undefined\n this.#running = this.#loop()\n .catch((error) => {\n this.#opts.logger?.child(\"run\").error(error)\n return this.#stop(\n error instanceof Error && error.name === \"AbortError\" ? \"aborted\" : \"error\",\n error\n )\n })\n .finally(() => {\n this.#abortController = undefined\n this.#running = undefined\n })\n return this.#running\n }\n\n async #collect() {\n this.#abortController = new AbortController()\n const context = {\n cacheKey: this.ctx.session.id,\n messages: [...this.ctx.messages],\n prompt: this.prompt,\n sessionId: this.ctx.session.id,\n tools: this.tools,\n } satisfies Context\n await this.emitSerial(\"context\", context)\n const model = this.model\n if (!model) throw new Error(\"model must be loaded to collect\")\n return model.stream(context, this.#streamOpts())\n }\n\n #shouldAutoCompact(): boolean {\n const opts = toValue(this.#opts.compaction)\n const auto = opts?.enabled ?? true\n if (!auto) return false\n const threshold = opts?.threshold ?? 0.95\n return this.pressure.ratio >= threshold\n }\n\n #streamOpts(): ModelStreamOptions {\n const base = this.#opts.request ?? {}\n return {\n ...base,\n onEvent: (event) => {\n void this.emit(\"stream-event\", { event })\n try {\n void this.#opts.onEvent?.(event)\n } catch (error) {\n this.#opts.logger?.child(\"stream\").error(error)\n }\n },\n onUpdate: this.#opts.onUpdate,\n reasoning: { ...base.reasoning, effort: this.#ctx.reasoning },\n signal: this.#abortController?.signal,\n }\n }\n\n /** Run exactly one step. Useful for tests and custom drivers\n * that want to interleave logic between steps. */\n async step(): Promise<StepResult> {\n if (this.#shouldAutoCompact()) await this.compact()\n // Drain the notify queue into the inject queue as a single system message\n if (this.#notifyQueue.length > 0) {\n this.#injectQueue.push({\n content: this.#notifyQueue.splice(0),\n role: \"system\",\n })\n }\n\n // Drain injections from send(), notifications, wakeups, and hooks.\n // Sequential await preserves queue order in the session.\n for (const m of this.#injectQueue.splice(0)) await this.session.add(m)\n\n this.#setStatus(\"streaming\")\n\n let collected: AssistantMessage\n\n try {\n collected = await this.#collect()\n } catch (error) {\n const err = toError(error)\n const overflow = isContextOverflow({ message: err.message })\n if (overflow) this.#opts.logger?.warn(\"Context overflow detected:\", err)\n return {\n error: err,\n finishReason: overflow ? \"length\" : \"error\",\n kind: overflow ? \"context-overflow\" : \"error\",\n usage: { input: 0, output: 0 },\n }\n }\n\n this.#usage.add(collected.meta.usage)\n\n const result: Omit<StepResult, \"kind\"> = {\n finishReason: collected.meta.finishReason,\n message: collected,\n usage: collected.meta.usage,\n }\n\n // Silent-overflow check BEFORE committing the message — gives the\n // session a chance to drop it and retry on a compacted history.\n if (\n this.#opts.contextLimit !== undefined &&\n isContextOverflow({\n contextLimit: this.#opts.contextLimit,\n // Total prompt size = uncached input + cached reads + cached\n // writes. `usage.input` is uncached-only; the cache fields are\n // separate billing tiers that still occupy the context window.\n usageInput:\n result.usage.input + (result.usage.cacheRead ?? 0) + (result.usage.cacheWrite ?? 0),\n })\n )\n return { kind: \"context-overflow\", ...result }\n\n const calls = await this.#parseToolCalls(collected)\n await this.session.add(collected)\n\n if (calls.length === 0) return { kind: \"natural\", ...result }\n\n return {\n kind: \"tool-calls\",\n toolMessage: await this.#runTools(calls),\n ...result,\n }\n }\n\n async #parseToolCalls(message: Message): Promise<ToolCallPart[]> {\n if (typeof message.content === \"string\") return []\n const calls = message.content.filter((p): p is ToolCallPart => p.type === \"tool-call\")\n for (const call of calls) {\n const tool = this.tools.find((t) => t.name === call.name)\n if (!tool) continue\n try {\n call.params = (await tool.validator.cleanParams(call.params)) ?? call.params\n } catch {}\n }\n return calls\n }\n\n async compact(): Promise<void> {\n const prev = this.#status\n const pressure = this.pressure\n this.#setStatus(\"compacting\")\n this.#usage.resetLast()\n try {\n const { Compaction } = await import(\"./compaction/compactions.ts\")\n const opts: Partial<CompactionOptions> = {\n ...toValue(this.#opts.compaction),\n signal: this.#abortController?.signal,\n }\n const compactor = new Compaction(this, opts)\n await compactor.compact(pressure)\n } finally {\n this.#setStatus(prev)\n }\n }\n\n async #runTools(calls: ToolCallPart[]) {\n this.#setStatus(\"running-tools\")\n void this.emit(\"tool-calls\", { calls })\n for (const call of calls) void this.emit(\"tool-call\", { call })\n\n const emitted = new Set<string>()\n // The whole batch — including streamable promotion, parallel chains,\n // grace timing, and ownerRound suppression — lives in Tasks.run().\n // What lands back here is a 1:1 array of result parts ready to commit.\n // The skill tool (when active) is passed via `extraTools` so dispatch\n // can resolve `name: \"skill\"` calls without polluting `tasks.tools`.\n const resultParts = await this.#tasks.run(calls, await this.#toolContext(), {\n onResult: (call, result) => {\n emitted.add(call.id)\n void this.emit(\"tool-result\", { call, result })\n },\n })\n\n for (let i = 0; i < calls.length; i++) {\n const call = calls[i]\n const part = resultParts[i]\n if (emitted.has(call.id)) continue\n void this.emit(\"tool-result\", {\n call,\n result: {\n content: part.content,\n error: part.error,\n isError: part.isError ?? false,\n meta: part.meta,\n },\n })\n }\n const message: Message<\"tool\"> = { content: resultParts, role: \"tool\" }\n await this.session.add(message)\n return message\n }\n\n /** Resolve when the agent is in a quiescent state — `idle` or\n * `paused`. If a run is currently in flight (or was just kicked off\n * synchronously by `send` / `inject` / a wakeup), waits for it to\n * settle before returning the final status. If no run is in flight,\n * resolves immediately with the current status.\n *\n * Use this in REPL-style drivers to await the loop without racing\n * with internally-triggered runs (the wakeup timer, heartbeat, or\n * task-completion injects all spawn `void this.run()` independently\n * of caller-driven `await agent.run()`). The `#running` promise is\n * set synchronously inside `run()` before any await point, so this\n * catches every kicked-off cycle including the one `send` just fired.\n *\n * Errors from the loop are swallowed — callers read `agent.lastError`\n * / `agent.lastStopReason` for diagnostics. The point of `waitIdle`\n * is just to know \"the loop is no longer driving.\" */\n async waitIdle(timeout?: number): Promise<AgentStatus> {\n if (!this.#running) return this.#status\n const wait = [this.#running.catch(() => undefined)]\n if (timeout !== undefined) wait.push(new Promise((resolve) => setTimeout(resolve, timeout)))\n await Promise.race(wait)\n return this.#status\n }\n\n /** Stop the loop with a custom reason.\n * When `abort: true` (the default), also trigger the abort signal so any\n * in-flight stream or tool calls can react to the stop.\n * When `abort: false`, the agent still stops immediately, but any active\n * stream or tool calls are left to run to completion */\n stop(opts: { abort?: boolean; reason?: string } = {}): void {\n this.#pauseRequested ??= opts.reason ?? \"stop\"\n if (opts.abort ?? true) this.#abortController?.abort(opts.reason)\n }\n\n async start() {\n if (this.#started) return\n this.#started = true\n await this.emit(\"start\")\n }\n\n get started() {\n return this.#started\n }\n\n // ── Internals ────────────────────────────────────────────────────────\n\n async #turn(): Promise<TurnResult> {\n for (let step = 1; ; step++) {\n if (this.#abortController?.signal.aborted)\n return { kind: \"aborted\", reason: this.#abortController.signal.reason }\n if (this.#pauseRequested !== undefined)\n return { kind: \"paused\", reason: this.#pauseRequested }\n\n void this.emit(\"step-start\", { step })\n const outcome = await this.step()\n void this.emit(\"step-end\", { outcome: outcome.kind, step })\n\n if (outcome.kind === \"error\") {\n return {\n kind: outcome.error?.name === \"AbortError\" ? \"aborted\" : \"error\",\n reason: outcome.error,\n }\n }\n\n if (outcome.kind === \"natural\") {\n return { kind: \"natural\" }\n }\n\n if (outcome.kind === \"context-overflow\") {\n // Auto-compaction also gates the overflow recovery path. With\n // `auto: false`, overflow stops cleanly instead of attempting\n // a recovery the user explicitly opted out of.\n if (toValue(this.#opts.compaction)?.enabled === false) return { kind: \"context-overflow\" }\n // Compactor mutates the conversation; the rejected message is\n // not committed — next step retries on the compacted state.\n this.#opts.logger\n ?.child(\"compaction\")\n .warn(\n `context overflow detected (size ${this.contextSize}, limit ${this.pressure.limit}); running compaction`\n )\n await this.compact()\n continue\n }\n\n // outcome.kind === \"tool-calls\" — consult the policy.\n const stop = this.#stopPolicy.detect()\n if (stop) return { kind: stop }\n }\n }\n\n async #loop(): Promise<AgentStopKind> {\n if (!this.#started) await this.start()\n // Reset per-run counters (steps, consecutive errors, call history).\n // Token totals stay sticky across resets — they're billing-style\n // displays, not per-turn caps.\n this.#stopPolicy.reset()\n for (let turn = 1; ; turn++) {\n // Start one append submission only after pending injections have settled.\n if (this.#injectQueue.length === 0)\n for (const m of this.#appendQueue.shift() ?? []) await this.session.add(m)\n\n void this.emit(\"turn-start\", { turn })\n const result = await this.#turn()\n const reason = result.reason ? toError(result.reason).message : undefined\n void this.emit(\"turn-end\", { outcome: result.kind, reason, turn })\n\n // If the model stopped naturally but there are still queued messages,\n // keep the loop alive to process them.\n if (\n result.kind === \"natural\" &&\n (this.#injectQueue.length > 0 || this.#appendQueue.length > 0)\n )\n continue\n\n return this.#stop(result.kind, result.reason)\n }\n }\n\n #stop(kind: AgentStopKind, reason?: unknown): AgentStopKind {\n this.#lastStop = {\n error: reason instanceof Error ? reason : undefined,\n kind,\n reason: reason === undefined ? undefined : toError(reason).message,\n }\n this.#setStatus(kind === \"natural\" ? \"idle\" : \"paused\")\n void this.emit(\"stop\", {\n status: this.#status,\n usage: this.usage,\n ...this.#lastStop,\n })\n return kind\n }\n\n /** Build the per-step `ToolContext` handed to each tool. The session\n * cwd, an abort signal scoped to the in-flight stream, and the\n * long-running spawn registry are all surfaced here. */\n async #toolContext(): Promise<ToolContext> {\n const masker = await this.#ctx.masker()\n return {\n agent: this,\n bash: this.#opts.bash,\n cwd: this.cwd,\n isMasked: (msgId: string, partIdx?: number) => masker?.isMasked(msgId, partIdx) ?? false,\n messages: this.session.messages,\n need: (scope, input) => this.#need(scope, input),\n perms: await this.ctx.permissions(),\n sessionDir: this.session.dir,\n signal: this.#abortController?.signal,\n swarm: () => this.#ctx.swarm(),\n tasks: this.#tasks,\n }\n }\n\n /** Implementation of `ctx.need(scope, input)`. Resolves on `allow`,\n * throws a `PERMISSION_DENIED` `AiError` on `deny`, and escalates\n * `ask` to `AgentOptions.allow` (treating it as `deny` when no\n * callback is configured). */\n async #need(scope: string, input: string): Promise<void> {\n const perms = await this.ctx.permissions()\n const r = perms.validate(scope, input)\n if (r.verdict === \"allow\") return\n if (r.verdict === \"ask\" && this.#opts.allow) {\n const ok = await this.#opts.allow({\n ask: r.ask,\n input,\n reason: r.reason,\n scope,\n suggestions: r.suggestions,\n })\n if (ok) return\n }\n throw new AiError({\n code: \"PERMISSION_DENIED\",\n data: { input, scope, suggestions: r.suggestions, verdict: r.verdict },\n message: r.reason,\n // `ask` verdicts that the user denied this turn are retryable —\n // they may add a rule later. Hard `deny` is not.\n retryable: r.verdict === \"ask\",\n })\n }\n\n /** Tear down session-scoped resources. Called on agent disposal — the\n * agent doesn't auto-dispose today, so callers (TUI on quit, headless\n * runner on completion) should invoke this explicitly. */\n async dispose(): Promise<void> {\n this.clearListeners()\n this.#cancelAllWakeups()\n await this.#tasks.killAll()\n }\n\n #setStatus(status: AgentStatus): void {\n const prev = this.#status\n if (prev === status) return\n // Cancel wakeups only when an EXTERNAL wake-up brings the loop back\n // to active (idle/paused → streaming). Mid-turn transitions\n // (running-tools → streaming) are the same turn continuing — a\n // wakeup the model just scheduled mid-tool-call would otherwise be\n // killed before it ever fires. The \"external wake-up\" cases that\n // *should* cancel: a `task-done` inject, a heartbeat, a user\n // message — all route through `inject` → `send` → `run` from the\n // idle/paused state, hitting this branch correctly.\n if (status === \"streaming\" && (prev === \"idle\" || prev === \"paused\")) {\n this.#cancelAllWakeups()\n }\n this.#status = status\n void this.emit(\"status\", { status })\n }\n}\n"],"mappings":";;;;;;;;AAKA,SAAgB,SAAS,GAAU,GAAiB;CAClD,MAAM,MAAa;EACjB,OAAO,EAAE,QAAQ,EAAE;EACnB,QAAQ,EAAE,SAAS,EAAE;CACvB;CACA,IAAI,EAAE,cAAc,KAAA,KAAa,EAAE,cAAc,KAAA,GAC/C,IAAI,aAAa,EAAE,aAAa,MAAM,EAAE,aAAa;CAEvD,IAAI,EAAE,eAAe,KAAA,KAAa,EAAE,eAAe,KAAA,GACjD,IAAI,cAAc,EAAE,cAAc,MAAM,EAAE,cAAc;CAE1D,IAAI,EAAE,cAAc,KAAA,KAAa,EAAE,cAAc,KAAA,GAC/C,IAAI,aAAa,EAAE,aAAa,MAAM,EAAE,aAAa;CAEvD,IAAI,EAAE,QAAQ,EAAE,MAAM,IAAI,OAAO,SAAS,EAAE,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,CAAC;CAC9E,OAAO;AACT;AAEA,IAAa,aAAb,MAAyC;CACvC,QAAe,MAAM;CACrB,SAAgB,MAAM;CAEtB,YAAY,UAA+B;EACzC,KAAK,MAAM,KAAK,YAAY,CAAC,GAC3B,IAAI,EAAE,SAAS,eAAe,EAAE,MAAM,OAAO,KAAK,IAAI,EAAE,KAAK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;GAAQ;GACrE,SAAS,EAAE;GAGX,WAAW,EAAE,YAAY;EAC3B,CAAC;CACH;;;;CAKA,MAAM,UAAyB;EAC7B,KAAK,eAAe;EACpB,KAAK,kBAAkB;EACvB,MAAM,KAAK,OAAO,QAAQ;CAC5B;CAEA,WAAW,QAA2B;EACpC,MAAM,OAAO,KAAK;EAClB,IAAI,SAAS,QAAQ;EASrB,IAAI,WAAW,gBAAgB,SAAS,UAAU,SAAS,WACzD,KAAK,kBAAkB;EAEzB,KAAK,UAAU;EACf,KAAU,KAAK,UAAU,EAAE,OAAO,CAAC;CACrC;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"compactions-HFjEgrv3.mjs","names":[],"sources":["../src/compaction/prompt.ts","../src/compaction/compactions.ts"],"sourcesContent":["/* Prompts for generating a checkpoint and framing it for the resumed agent. */\n\nexport const SYSTEM_PROMPT = `Summarize the supplied conversation into a structured context checkpoint for your future self to resume the work. Do not continue the conversation or answer questions in it.\n\nUse this format, omitting empty sections:\n\n## Goal\nWhat the user is trying to accomplish and what they have authorized.\n\n## Constraints & Preferences\nImportant requirements, boundaries, and user corrections.\n\n## Progress\nCompleted work, work in progress, and blockers. Include outstanding tasks or tool results needed to resume.\n\n## Key Decisions\nWhat was chosen or rejected, with brief rationale.\n\n## Next Steps\nWhat remains to be done, in order. Do not invent work if the task is complete.\n\n## Critical Context\nEssential data, references, and artifact paths, with a brief explanation of why they matter.\n\nBe concise and readable. Preserve exact paths, identifiers, commands, and errors when needed to continue accurately. Distinguish verified results from proposals and uncertainty; do not infer missing tool results.\n\nSummarize user intent rather than listing every message. File and command usage tables are included separately: do not reproduce their inventories or infer outcomes from them. Mention only files and commands whose significance needs explaining.\n\nConsolidate previous summaries with newer evidence, removing repetition and superseded state while retaining relevant constraints and decisions.`\n\nexport const SUMMARY_PROMPT = `Create the context checkpoint summary now, using the format above. Output only the summary.`\n\nexport const PREVIOUS_SUMMARY_PROMPT = `Incorporate this prior summary into the new checkpoint, retaining relevant context and updating superseded state from the conversation.`\n\n/** Shown to the resumed agent, not the summarizer. */\nexport const SUMMARY_HEADER = `The older conversation has been compacted into the summary below. Recent messages follow verbatim and may supersede it. Use both to continue where the conversation left off without repeating completed work.\n\nFile and command usage tables cover the full conversation and are navigation aids, not evidence of results. If necessary information is missing, consult the referenced artifacts or ask rather than guess.`\n","import type { Message, ReasoningEffort } from \"@zaly/ai\"\nimport type { Agent } from \"../agent.ts\"\nimport type { ContextPressure } from \"../types.ts\"\nimport type { ToolStatOptions } from \"./utils.ts\"\n\nimport { toXml } from \"@zaly/ai\"\nimport { SUMMARY_HEADER, SUMMARY_PROMPT, SYSTEM_PROMPT } from \"./prompt.ts\"\nimport {\n extractBashUsage,\n extractConversation,\n extractFileUsage,\n formatBashUsage,\n formatFileUsage,\n messageTail,\n} from \"./utils.ts\"\n\nexport type CompactionOptions = {\n enabled: boolean\n threshold?: number\n /** Existing messages up to this many tokens will be preserved in the context */\n keepTokens: number\n maxToolResultLen: number\n summaryTokens: number\n bash: ToolStatOptions\n files: ToolStatOptions\n signal?: AbortSignal\n reasoning?: ReasoningEffort\n trigger?: \"manual\" | \"auto\"\n}\n\nconst defaults: CompactionOptions = {\n bash: { limit: 50, minCount: 2, minScore: 0.5, sort: \"score\" },\n enabled: true,\n files: { limit: 50, minCount: 1, minScore: 0.5, sort: \"score\" },\n keepTokens: 20_000,\n maxToolResultLen: 2000,\n reasoning: \"low\",\n summaryTokens: 10_000,\n threshold: 0.95,\n}\n\nexport class Compaction {\n #opts: CompactionOptions\n #agent: Agent\n\n constructor(agent: Agent, opts: Partial<CompactionOptions> = {}) {\n this.#agent = agent\n this.#opts = { ...defaults, ...opts }\n }\n\n async compact(pressure: ContextPressure): Promise<void> {\n const { session } = this.#agent\n\n const masker = await this.#agent.ctx.masker()\n\n const messages = masker ? await masker.mask(session.messages, pressure) : session.messages\n\n const now = performance.now()\n\n const tail = messageTail(messages, { keepTokens: this.#opts.keepTokens })\n const older = tail.length > 0 ? messages.slice(0, -tail.length) : messages\n\n if (older.length === 0) return\n\n const conversation = extractConversation(\n // Conversation summary is based on the older messages, not the tail — the tail is what we keep\n older,\n { maxToolResultLen: this.#opts.maxToolResultLen }\n )\n\n const bashUsage = formatBashUsage(extractBashUsage(messages, this.#opts.bash))\n const fileUsage = formatFileUsage(extractFileUsage(messages, this.#opts.files))\n\n const request: Message<\"user\"> = {\n content: [\n { text: conversation, type: \"text\" },\n { text: fileUsage, type: \"text\" },\n { text: bashUsage, type: \"text\" },\n { text: SUMMARY_PROMPT, type: \"text\" },\n ],\n role: \"user\",\n }\n\n const summary = await this.#summarize(request)\n // The bash + file usage tables are deterministic, ground-truth signals\n // — pricier to ask the model to reproduce than to copy verbatim. Carry\n // them through to the resumed agent so it has the same working-set\n // visibility the summarizer had, without paying for output tokens.\n const summaryMessage: Message<\"system\"> = {\n content: [\n { text: SUMMARY_HEADER, type: \"text\" },\n { text: toXml(summary, \"compaction-summary\", { indent: false }), type: \"text\" },\n { text: fileUsage, type: \"text\" },\n { text: bashUsage, type: \"text\" },\n ],\n meta: { kind: \"compaction-summary\" },\n role: \"system\",\n }\n await session.compact({\n durationMs: Math.round(performance.now() - now),\n preTokens: this.#agent.contextSize,\n summary: summaryMessage,\n tail: tail.length,\n trigger: this.#opts.trigger,\n })\n masker?.reset()\n }\n\n async #summarize(message: Message<\"user\">): Promise<string> {\n const model = this.#agent.model\n if (!model) throw new Error(\"model must be loaded to compact\")\n const m = await model.stream(\n {\n messages: [message],\n prompt: [SYSTEM_PROMPT],\n sessionId: this.#agent.session.id,\n },\n {\n caching: false,\n maxTokens: this.#opts.summaryTokens,\n reasoning: this.#opts.reasoning ? { effort: this.#opts.reasoning } : undefined,\n signal: this.#opts.signal,\n }\n )\n if (typeof m.content === \"string\") return m.content\n const parts = m.content.filter((p) => p.type === \"text\").map((p) => p.text)\n return parts.join(\"\\n\")\n }\n}\n"],"mappings":";;;AAEA,MAAa,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA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