@zaly/agent 0.0.5 → 0.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-BaD2kax9.mjs → agent-B7cQOuMZ.mjs} +2 -2
- package/dist/agent-B7cQOuMZ.mjs.map +1 -0
- package/dist/{agent-EkPynZRJ.mjs → agent-D3wVIibN.mjs} +4 -3
- package/dist/agent-D3wVIibN.mjs.map +1 -0
- package/dist/{compactions-3AjPqjeZ.mjs → compactions-B8VdZJoU.mjs} +2 -2
- package/dist/{compactions-3AjPqjeZ.mjs.map → compactions-B8VdZJoU.mjs.map} +1 -1
- package/dist/{edit-Qxl4w1C2.mjs → edit-D4yaBK1K.mjs} +9 -17
- package/dist/edit-D4yaBK1K.mjs.map +1 -0
- package/dist/{fetch-DknuSrSX.mjs → fetch-VKhSWdEh.mjs} +2 -2
- package/dist/{fetch-DknuSrSX.mjs.map → fetch-VKhSWdEh.mjs.map} +1 -1
- package/dist/{find-Bah9SKWX.mjs → find-CimUGn-L.mjs} +6 -20
- package/dist/find-CimUGn-L.mjs.map +1 -0
- package/dist/{grep-B4GF0svc.mjs → grep-6O3mjSvV.mjs} +10 -78
- package/dist/grep-6O3mjSvV.mjs.map +1 -0
- package/dist/index-node-esm-CJsN8G51.mjs +2116 -0
- package/dist/index-node-esm-CJsN8G51.mjs.map +1 -0
- package/dist/index.d.mts +25 -37
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3 -953
- package/dist/{manager-f-WjFTMX.mjs → manager-BqlbCGYV.mjs} +12 -2
- package/dist/{manager-f-WjFTMX.mjs.map → manager-BqlbCGYV.mjs.map} +1 -1
- package/dist/{masker-Bv9KjkDF.mjs → masker-DRFztUwc.mjs} +2 -2
- package/dist/{masker-Bv9KjkDF.mjs.map → masker-DRFztUwc.mjs.map} +1 -1
- package/dist/{read-Djsx2NZl.mjs → read-CSL_8nAk.mjs} +47 -63
- package/dist/read-CSL_8nAk.mjs.map +1 -0
- package/dist/{registry-BVf0aZEA.mjs → registry-L9GDccS0.mjs} +89 -43
- package/dist/registry-L9GDccS0.mjs.map +1 -0
- package/dist/{session-Bv8JiT8P.mjs → session-BSvUrr12.mjs} +2 -2
- package/dist/{session-Bv8JiT8P.mjs.map → session-BSvUrr12.mjs.map} +1 -1
- package/dist/session.mjs +1 -1
- package/dist/src-fK6DL2bg.mjs +953 -0
- package/dist/src-fK6DL2bg.mjs.map +1 -0
- package/dist/{subagent-CX7Zjcws.mjs → subagent-C8XCEecM.mjs} +2 -2
- package/dist/{subagent-CX7Zjcws.mjs.map → subagent-C8XCEecM.mjs.map} +1 -1
- package/dist/{tools-Bl-YI890.mjs → tools-wvkkuXWH.mjs} +76 -20
- package/dist/tools-wvkkuXWH.mjs.map +1 -0
- package/dist/{write-D3L-92vj.mjs → write-DwGiDNeG.mjs} +3 -11
- package/dist/write-DwGiDNeG.mjs.map +1 -0
- package/package.json +12 -12
- package/dist/agent-BaD2kax9.mjs.map +0 -1
- package/dist/agent-EkPynZRJ.mjs.map +0 -1
- package/dist/edit-Qxl4w1C2.mjs.map +0 -1
- package/dist/find-Bah9SKWX.mjs.map +0 -1
- package/dist/grep-B4GF0svc.mjs.map +0 -1
- package/dist/index-node-esm-D6YQRKEz.mjs +0 -1537
- package/dist/index-node-esm-D6YQRKEz.mjs.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/read-Djsx2NZl.mjs.map +0 -1
- package/dist/registry-BVf0aZEA.mjs.map +0 -1
- package/dist/tools-Bl-YI890.mjs.map +0 -1
- package/dist/write-D3L-92vj.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-node-esm-D6YQRKEz.mjs","names":[],"sources":["../../../node_modules/.bun/jsonpath-plus@10.4.0/node_modules/jsonpath-plus/dist/index-node-esm.js"],"sourcesContent":["import vm from 'vm';\n\n/**\n * @implements {IHooks}\n */\nclass Hooks {\n /**\n * @callback HookCallback\n * @this {*|Jsep} this\n * @param {Jsep} env\n * @returns: void\n */\n /**\n * Adds the given callback to the list of callbacks for the given hook.\n *\n * The callback will be invoked when the hook it is registered for is run.\n *\n * One callback function can be registered to multiple hooks and the same hook multiple times.\n *\n * @param {string|object} name The name of the hook, or an object of callbacks keyed by name\n * @param {HookCallback|boolean} callback The callback function which is given environment variables.\n * @param {?boolean} [first=false] Will add the hook to the top of the list (defaults to the bottom)\n * @public\n */\n add(name, callback, first) {\n if (typeof arguments[0] != 'string') {\n // Multiple hook callbacks, keyed by name\n for (let name in arguments[0]) {\n this.add(name, arguments[0][name], arguments[1]);\n }\n } else {\n (Array.isArray(name) ? name : [name]).forEach(function (name) {\n this[name] = this[name] || [];\n if (callback) {\n this[name][first ? 'unshift' : 'push'](callback);\n }\n }, this);\n }\n }\n\n /**\n * Runs a hook invoking all registered callbacks with the given environment variables.\n *\n * Callbacks will be invoked synchronously and in the order in which they were registered.\n *\n * @param {string} name The name of the hook.\n * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.\n * @public\n */\n run(name, env) {\n this[name] = this[name] || [];\n this[name].forEach(function (callback) {\n callback.call(env && env.context ? env.context : env, env);\n });\n }\n}\n\n/**\n * @implements {IPlugins}\n */\nclass Plugins {\n constructor(jsep) {\n this.jsep = jsep;\n this.registered = {};\n }\n\n /**\n * @callback PluginSetup\n * @this {Jsep} jsep\n * @returns: void\n */\n /**\n * Adds the given plugin(s) to the registry\n *\n * @param {object} plugins\n * @param {string} plugins.name The name of the plugin\n * @param {PluginSetup} plugins.init The init function\n * @public\n */\n register(...plugins) {\n plugins.forEach(plugin => {\n if (typeof plugin !== 'object' || !plugin.name || !plugin.init) {\n throw new Error('Invalid JSEP plugin format');\n }\n if (this.registered[plugin.name]) {\n // already registered. Ignore.\n return;\n }\n plugin.init(this.jsep);\n this.registered[plugin.name] = plugin;\n });\n }\n}\n\n// JavaScript Expression Parser (JSEP) 1.4.0\n\nclass Jsep {\n /**\n * @returns {string}\n */\n static get version() {\n // To be filled in by the template\n return '1.4.0';\n }\n\n /**\n * @returns {string}\n */\n static toString() {\n return 'JavaScript Expression Parser (JSEP) v' + Jsep.version;\n }\n // ==================== CONFIG ================================\n /**\n * @method addUnaryOp\n * @param {string} op_name The name of the unary op to add\n * @returns {Jsep}\n */\n static addUnaryOp(op_name) {\n Jsep.max_unop_len = Math.max(op_name.length, Jsep.max_unop_len);\n Jsep.unary_ops[op_name] = 1;\n return Jsep;\n }\n\n /**\n * @method jsep.addBinaryOp\n * @param {string} op_name The name of the binary op to add\n * @param {number} precedence The precedence of the binary op (can be a float). Higher number = higher precedence\n * @param {boolean} [isRightAssociative=false] whether operator is right-associative\n * @returns {Jsep}\n */\n static addBinaryOp(op_name, precedence, isRightAssociative) {\n Jsep.max_binop_len = Math.max(op_name.length, Jsep.max_binop_len);\n Jsep.binary_ops[op_name] = precedence;\n if (isRightAssociative) {\n Jsep.right_associative.add(op_name);\n } else {\n Jsep.right_associative.delete(op_name);\n }\n return Jsep;\n }\n\n /**\n * @method addIdentifierChar\n * @param {string} char The additional character to treat as a valid part of an identifier\n * @returns {Jsep}\n */\n static addIdentifierChar(char) {\n Jsep.additional_identifier_chars.add(char);\n return Jsep;\n }\n\n /**\n * @method addLiteral\n * @param {string} literal_name The name of the literal to add\n * @param {*} literal_value The value of the literal\n * @returns {Jsep}\n */\n static addLiteral(literal_name, literal_value) {\n Jsep.literals[literal_name] = literal_value;\n return Jsep;\n }\n\n /**\n * @method removeUnaryOp\n * @param {string} op_name The name of the unary op to remove\n * @returns {Jsep}\n */\n static removeUnaryOp(op_name) {\n delete Jsep.unary_ops[op_name];\n if (op_name.length === Jsep.max_unop_len) {\n Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);\n }\n return Jsep;\n }\n\n /**\n * @method removeAllUnaryOps\n * @returns {Jsep}\n */\n static removeAllUnaryOps() {\n Jsep.unary_ops = {};\n Jsep.max_unop_len = 0;\n return Jsep;\n }\n\n /**\n * @method removeIdentifierChar\n * @param {string} char The additional character to stop treating as a valid part of an identifier\n * @returns {Jsep}\n */\n static removeIdentifierChar(char) {\n Jsep.additional_identifier_chars.delete(char);\n return Jsep;\n }\n\n /**\n * @method removeBinaryOp\n * @param {string} op_name The name of the binary op to remove\n * @returns {Jsep}\n */\n static removeBinaryOp(op_name) {\n delete Jsep.binary_ops[op_name];\n if (op_name.length === Jsep.max_binop_len) {\n Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);\n }\n Jsep.right_associative.delete(op_name);\n return Jsep;\n }\n\n /**\n * @method removeAllBinaryOps\n * @returns {Jsep}\n */\n static removeAllBinaryOps() {\n Jsep.binary_ops = {};\n Jsep.max_binop_len = 0;\n return Jsep;\n }\n\n /**\n * @method removeLiteral\n * @param {string} literal_name The name of the literal to remove\n * @returns {Jsep}\n */\n static removeLiteral(literal_name) {\n delete Jsep.literals[literal_name];\n return Jsep;\n }\n\n /**\n * @method removeAllLiterals\n * @returns {Jsep}\n */\n static removeAllLiterals() {\n Jsep.literals = {};\n return Jsep;\n }\n // ==================== END CONFIG ============================\n\n /**\n * @returns {string}\n */\n get char() {\n return this.expr.charAt(this.index);\n }\n\n /**\n * @returns {number}\n */\n get code() {\n return this.expr.charCodeAt(this.index);\n }\n /**\n * @param {string} expr a string with the passed in express\n * @returns Jsep\n */\n constructor(expr) {\n // `index` stores the character number we are currently at\n // All of the gobbles below will modify `index` as we move along\n this.expr = expr;\n this.index = 0;\n }\n\n /**\n * static top-level parser\n * @returns {jsep.Expression}\n */\n static parse(expr) {\n return new Jsep(expr).parse();\n }\n\n /**\n * Get the longest key length of any object\n * @param {object} obj\n * @returns {number}\n */\n static getMaxKeyLen(obj) {\n return Math.max(0, ...Object.keys(obj).map(k => k.length));\n }\n\n /**\n * `ch` is a character code in the next three functions\n * @param {number} ch\n * @returns {boolean}\n */\n static isDecimalDigit(ch) {\n return ch >= 48 && ch <= 57; // 0...9\n }\n\n /**\n * Returns the precedence of a binary operator or `0` if it isn't a binary operator. Can be float.\n * @param {string} op_val\n * @returns {number}\n */\n static binaryPrecedence(op_val) {\n return Jsep.binary_ops[op_val] || 0;\n }\n\n /**\n * Looks for start of identifier\n * @param {number} ch\n * @returns {boolean}\n */\n static isIdentifierStart(ch) {\n return ch >= 65 && ch <= 90 ||\n // A...Z\n ch >= 97 && ch <= 122 ||\n // a...z\n ch >= 128 && !Jsep.binary_ops[String.fromCharCode(ch)] ||\n // any non-ASCII that is not an operator\n Jsep.additional_identifier_chars.has(String.fromCharCode(ch)); // additional characters\n }\n\n /**\n * @param {number} ch\n * @returns {boolean}\n */\n static isIdentifierPart(ch) {\n return Jsep.isIdentifierStart(ch) || Jsep.isDecimalDigit(ch);\n }\n\n /**\n * throw error at index of the expression\n * @param {string} message\n * @throws\n */\n throwError(message) {\n const error = new Error(message + ' at character ' + this.index);\n error.index = this.index;\n error.description = message;\n throw error;\n }\n\n /**\n * Run a given hook\n * @param {string} name\n * @param {jsep.Expression|false} [node]\n * @returns {?jsep.Expression}\n */\n runHook(name, node) {\n if (Jsep.hooks[name]) {\n const env = {\n context: this,\n node\n };\n Jsep.hooks.run(name, env);\n return env.node;\n }\n return node;\n }\n\n /**\n * Runs a given hook until one returns a node\n * @param {string} name\n * @returns {?jsep.Expression}\n */\n searchHook(name) {\n if (Jsep.hooks[name]) {\n const env = {\n context: this\n };\n Jsep.hooks[name].find(function (callback) {\n callback.call(env.context, env);\n return env.node;\n });\n return env.node;\n }\n }\n\n /**\n * Push `index` up to the next non-space character\n */\n gobbleSpaces() {\n let ch = this.code;\n // Whitespace\n while (ch === Jsep.SPACE_CODE || ch === Jsep.TAB_CODE || ch === Jsep.LF_CODE || ch === Jsep.CR_CODE) {\n ch = this.expr.charCodeAt(++this.index);\n }\n this.runHook('gobble-spaces');\n }\n\n /**\n * Top-level method to parse all expressions and returns compound or single node\n * @returns {jsep.Expression}\n */\n parse() {\n this.runHook('before-all');\n const nodes = this.gobbleExpressions();\n\n // If there's only one expression just try returning the expression\n const node = nodes.length === 1 ? nodes[0] : {\n type: Jsep.COMPOUND,\n body: nodes\n };\n return this.runHook('after-all', node);\n }\n\n /**\n * top-level parser (but can be reused within as well)\n * @param {number} [untilICode]\n * @returns {jsep.Expression[]}\n */\n gobbleExpressions(untilICode) {\n let nodes = [],\n ch_i,\n node;\n while (this.index < this.expr.length) {\n ch_i = this.code;\n\n // Expressions can be separated by semicolons, commas, or just inferred without any\n // separators\n if (ch_i === Jsep.SEMCOL_CODE || ch_i === Jsep.COMMA_CODE) {\n this.index++; // ignore separators\n } else {\n // Try to gobble each expression individually\n if (node = this.gobbleExpression()) {\n nodes.push(node);\n // If we weren't able to find a binary expression and are out of room, then\n // the expression passed in probably has too much\n } else if (this.index < this.expr.length) {\n if (ch_i === untilICode) {\n break;\n }\n this.throwError('Unexpected \"' + this.char + '\"');\n }\n }\n }\n return nodes;\n }\n\n /**\n * The main parsing function.\n * @returns {?jsep.Expression}\n */\n gobbleExpression() {\n const node = this.searchHook('gobble-expression') || this.gobbleBinaryExpression();\n this.gobbleSpaces();\n return this.runHook('after-expression', node);\n }\n\n /**\n * Search for the operation portion of the string (e.g. `+`, `===`)\n * Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)\n * and move down from 3 to 2 to 1 character until a matching binary operation is found\n * then, return that binary operation\n * @returns {string|boolean}\n */\n gobbleBinaryOp() {\n this.gobbleSpaces();\n let to_check = this.expr.substr(this.index, Jsep.max_binop_len);\n let tc_len = to_check.length;\n while (tc_len > 0) {\n // Don't accept a binary op when it is an identifier.\n // Binary ops that start with a identifier-valid character must be followed\n // by a non identifier-part valid character\n if (Jsep.binary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {\n this.index += tc_len;\n return to_check;\n }\n to_check = to_check.substr(0, --tc_len);\n }\n return false;\n }\n\n /**\n * This function is responsible for gobbling an individual expression,\n * e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`\n * @returns {?jsep.BinaryExpression}\n */\n gobbleBinaryExpression() {\n let node, biop, prec, stack, biop_info, left, right, i, cur_biop;\n\n // First, try to get the leftmost thing\n // Then, check to see if there's a binary operator operating on that leftmost thing\n // Don't gobbleBinaryOp without a left-hand-side\n left = this.gobbleToken();\n if (!left) {\n return left;\n }\n biop = this.gobbleBinaryOp();\n\n // If there wasn't a binary operator, just return the leftmost node\n if (!biop) {\n return left;\n }\n\n // Otherwise, we need to start a stack to properly place the binary operations in their\n // precedence structure\n biop_info = {\n value: biop,\n prec: Jsep.binaryPrecedence(biop),\n right_a: Jsep.right_associative.has(biop)\n };\n right = this.gobbleToken();\n if (!right) {\n this.throwError(\"Expected expression after \" + biop);\n }\n stack = [left, biop_info, right];\n\n // Properly deal with precedence using [recursive descent](http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm)\n while (biop = this.gobbleBinaryOp()) {\n prec = Jsep.binaryPrecedence(biop);\n if (prec === 0) {\n this.index -= biop.length;\n break;\n }\n biop_info = {\n value: biop,\n prec,\n right_a: Jsep.right_associative.has(biop)\n };\n cur_biop = biop;\n\n // Reduce: make a binary expression from the three topmost entries.\n const comparePrev = prev => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;\n while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {\n right = stack.pop();\n biop = stack.pop().value;\n left = stack.pop();\n node = {\n type: Jsep.BINARY_EXP,\n operator: biop,\n left,\n right\n };\n stack.push(node);\n }\n node = this.gobbleToken();\n if (!node) {\n this.throwError(\"Expected expression after \" + cur_biop);\n }\n stack.push(biop_info, node);\n }\n i = stack.length - 1;\n node = stack[i];\n while (i > 1) {\n node = {\n type: Jsep.BINARY_EXP,\n operator: stack[i - 1].value,\n left: stack[i - 2],\n right: node\n };\n i -= 2;\n }\n return node;\n }\n\n /**\n * An individual part of a binary expression:\n * e.g. `foo.bar(baz)`, `1`, `\"abc\"`, `(a % 2)` (because it's in parenthesis)\n * @returns {boolean|jsep.Expression}\n */\n gobbleToken() {\n let ch, to_check, tc_len, node;\n this.gobbleSpaces();\n node = this.searchHook('gobble-token');\n if (node) {\n return this.runHook('after-token', node);\n }\n ch = this.code;\n if (Jsep.isDecimalDigit(ch) || ch === Jsep.PERIOD_CODE) {\n // Char code 46 is a dot `.` which can start off a numeric literal\n return this.gobbleNumericLiteral();\n }\n if (ch === Jsep.SQUOTE_CODE || ch === Jsep.DQUOTE_CODE) {\n // Single or double quotes\n node = this.gobbleStringLiteral();\n } else if (ch === Jsep.OBRACK_CODE) {\n node = this.gobbleArray();\n } else {\n to_check = this.expr.substr(this.index, Jsep.max_unop_len);\n tc_len = to_check.length;\n while (tc_len > 0) {\n // Don't accept an unary op when it is an identifier.\n // Unary ops that start with a identifier-valid character must be followed\n // by a non identifier-part valid character\n if (Jsep.unary_ops.hasOwnProperty(to_check) && (!Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {\n this.index += tc_len;\n const argument = this.gobbleToken();\n if (!argument) {\n this.throwError('missing unaryOp argument');\n }\n return this.runHook('after-token', {\n type: Jsep.UNARY_EXP,\n operator: to_check,\n argument,\n prefix: true\n });\n }\n to_check = to_check.substr(0, --tc_len);\n }\n if (Jsep.isIdentifierStart(ch)) {\n node = this.gobbleIdentifier();\n if (Jsep.literals.hasOwnProperty(node.name)) {\n node = {\n type: Jsep.LITERAL,\n value: Jsep.literals[node.name],\n raw: node.name\n };\n } else if (node.name === Jsep.this_str) {\n node = {\n type: Jsep.THIS_EXP\n };\n }\n } else if (ch === Jsep.OPAREN_CODE) {\n // open parenthesis\n node = this.gobbleGroup();\n }\n }\n if (!node) {\n return this.runHook('after-token', false);\n }\n node = this.gobbleTokenProperty(node);\n return this.runHook('after-token', node);\n }\n\n /**\n * Gobble properties of of identifiers/strings/arrays/groups.\n * e.g. `foo`, `bar.baz`, `foo['bar'].baz`\n * It also gobbles function calls:\n * e.g. `Math.acos(obj.angle)`\n * @param {jsep.Expression} node\n * @returns {jsep.Expression}\n */\n gobbleTokenProperty(node) {\n this.gobbleSpaces();\n let ch = this.code;\n while (ch === Jsep.PERIOD_CODE || ch === Jsep.OBRACK_CODE || ch === Jsep.OPAREN_CODE || ch === Jsep.QUMARK_CODE) {\n let optional;\n if (ch === Jsep.QUMARK_CODE) {\n if (this.expr.charCodeAt(this.index + 1) !== Jsep.PERIOD_CODE) {\n break;\n }\n optional = true;\n this.index += 2;\n this.gobbleSpaces();\n ch = this.code;\n }\n this.index++;\n if (ch === Jsep.OBRACK_CODE) {\n node = {\n type: Jsep.MEMBER_EXP,\n computed: true,\n object: node,\n property: this.gobbleExpression()\n };\n if (!node.property) {\n this.throwError('Unexpected \"' + this.char + '\"');\n }\n this.gobbleSpaces();\n ch = this.code;\n if (ch !== Jsep.CBRACK_CODE) {\n this.throwError('Unclosed [');\n }\n this.index++;\n } else if (ch === Jsep.OPAREN_CODE) {\n // A function call is being made; gobble all the arguments\n node = {\n type: Jsep.CALL_EXP,\n 'arguments': this.gobbleArguments(Jsep.CPAREN_CODE),\n callee: node\n };\n } else if (ch === Jsep.PERIOD_CODE || optional) {\n if (optional) {\n this.index--;\n }\n this.gobbleSpaces();\n node = {\n type: Jsep.MEMBER_EXP,\n computed: false,\n object: node,\n property: this.gobbleIdentifier()\n };\n }\n if (optional) {\n node.optional = true;\n } // else leave undefined for compatibility with esprima\n\n this.gobbleSpaces();\n ch = this.code;\n }\n return node;\n }\n\n /**\n * Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to\n * keep track of everything in the numeric literal and then calling `parseFloat` on that string\n * @returns {jsep.Literal}\n */\n gobbleNumericLiteral() {\n let number = '',\n ch,\n chCode;\n while (Jsep.isDecimalDigit(this.code)) {\n number += this.expr.charAt(this.index++);\n }\n if (this.code === Jsep.PERIOD_CODE) {\n // can start with a decimal marker\n number += this.expr.charAt(this.index++);\n while (Jsep.isDecimalDigit(this.code)) {\n number += this.expr.charAt(this.index++);\n }\n }\n ch = this.char;\n if (ch === 'e' || ch === 'E') {\n // exponent marker\n number += this.expr.charAt(this.index++);\n ch = this.char;\n if (ch === '+' || ch === '-') {\n // exponent sign\n number += this.expr.charAt(this.index++);\n }\n while (Jsep.isDecimalDigit(this.code)) {\n // exponent itself\n number += this.expr.charAt(this.index++);\n }\n if (!Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {\n this.throwError('Expected exponent (' + number + this.char + ')');\n }\n }\n chCode = this.code;\n\n // Check to make sure this isn't a variable name that start with a number (123abc)\n if (Jsep.isIdentifierStart(chCode)) {\n this.throwError('Variable names cannot start with a number (' + number + this.char + ')');\n } else if (chCode === Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === Jsep.PERIOD_CODE) {\n this.throwError('Unexpected period');\n }\n return {\n type: Jsep.LITERAL,\n value: parseFloat(number),\n raw: number\n };\n }\n\n /**\n * Parses a string literal, staring with single or double quotes with basic support for escape codes\n * e.g. `\"hello world\"`, `'this is\\nJSEP'`\n * @returns {jsep.Literal}\n */\n gobbleStringLiteral() {\n let str = '';\n const startIndex = this.index;\n const quote = this.expr.charAt(this.index++);\n let closed = false;\n while (this.index < this.expr.length) {\n let ch = this.expr.charAt(this.index++);\n if (ch === quote) {\n closed = true;\n break;\n } else if (ch === '\\\\') {\n // Check for all of the common escape codes\n ch = this.expr.charAt(this.index++);\n switch (ch) {\n case 'n':\n str += '\\n';\n break;\n case 'r':\n str += '\\r';\n break;\n case 't':\n str += '\\t';\n break;\n case 'b':\n str += '\\b';\n break;\n case 'f':\n str += '\\f';\n break;\n case 'v':\n str += '\\x0B';\n break;\n default:\n str += ch;\n }\n } else {\n str += ch;\n }\n }\n if (!closed) {\n this.throwError('Unclosed quote after \"' + str + '\"');\n }\n return {\n type: Jsep.LITERAL,\n value: str,\n raw: this.expr.substring(startIndex, this.index)\n };\n }\n\n /**\n * Gobbles only identifiers\n * e.g.: `foo`, `_value`, `$x1`\n * Also, this function checks if that identifier is a literal:\n * (e.g. `true`, `false`, `null`) or `this`\n * @returns {jsep.Identifier}\n */\n gobbleIdentifier() {\n let ch = this.code,\n start = this.index;\n if (Jsep.isIdentifierStart(ch)) {\n this.index++;\n } else {\n this.throwError('Unexpected ' + this.char);\n }\n while (this.index < this.expr.length) {\n ch = this.code;\n if (Jsep.isIdentifierPart(ch)) {\n this.index++;\n } else {\n break;\n }\n }\n return {\n type: Jsep.IDENTIFIER,\n name: this.expr.slice(start, this.index)\n };\n }\n\n /**\n * Gobbles a list of arguments within the context of a function call\n * or array literal. This function also assumes that the opening character\n * `(` or `[` has already been gobbled, and gobbles expressions and commas\n * until the terminator character `)` or `]` is encountered.\n * e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`\n * @param {number} termination\n * @returns {jsep.Expression[]}\n */\n gobbleArguments(termination) {\n const args = [];\n let closed = false;\n let separator_count = 0;\n while (this.index < this.expr.length) {\n this.gobbleSpaces();\n let ch_i = this.code;\n if (ch_i === termination) {\n // done parsing\n closed = true;\n this.index++;\n if (termination === Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {\n this.throwError('Unexpected token ' + String.fromCharCode(termination));\n }\n break;\n } else if (ch_i === Jsep.COMMA_CODE) {\n // between expressions\n this.index++;\n separator_count++;\n if (separator_count !== args.length) {\n // missing argument\n if (termination === Jsep.CPAREN_CODE) {\n this.throwError('Unexpected token ,');\n } else if (termination === Jsep.CBRACK_CODE) {\n for (let arg = args.length; arg < separator_count; arg++) {\n args.push(null);\n }\n }\n }\n } else if (args.length !== separator_count && separator_count !== 0) {\n // NOTE: `&& separator_count !== 0` allows for either all commas, or all spaces as arguments\n this.throwError('Expected comma');\n } else {\n const node = this.gobbleExpression();\n if (!node || node.type === Jsep.COMPOUND) {\n this.throwError('Expected comma');\n }\n args.push(node);\n }\n }\n if (!closed) {\n this.throwError('Expected ' + String.fromCharCode(termination));\n }\n return args;\n }\n\n /**\n * Responsible for parsing a group of things within parentheses `()`\n * that have no identifier in front (so not a function call)\n * This function assumes that it needs to gobble the opening parenthesis\n * and then tries to gobble everything within that parenthesis, assuming\n * that the next thing it should see is the close parenthesis. If not,\n * then the expression probably doesn't have a `)`\n * @returns {boolean|jsep.Expression}\n */\n gobbleGroup() {\n this.index++;\n let nodes = this.gobbleExpressions(Jsep.CPAREN_CODE);\n if (this.code === Jsep.CPAREN_CODE) {\n this.index++;\n if (nodes.length === 1) {\n return nodes[0];\n } else if (!nodes.length) {\n return false;\n } else {\n return {\n type: Jsep.SEQUENCE_EXP,\n expressions: nodes\n };\n }\n } else {\n this.throwError('Unclosed (');\n }\n }\n\n /**\n * Responsible for parsing Array literals `[1, 2, 3]`\n * This function assumes that it needs to gobble the opening bracket\n * and then tries to gobble the expressions as arguments.\n * @returns {jsep.ArrayExpression}\n */\n gobbleArray() {\n this.index++;\n return {\n type: Jsep.ARRAY_EXP,\n elements: this.gobbleArguments(Jsep.CBRACK_CODE)\n };\n }\n}\n\n// Static fields:\nconst hooks = new Hooks();\nObject.assign(Jsep, {\n hooks,\n plugins: new Plugins(Jsep),\n // Node Types\n // ----------\n // This is the full set of types that any JSEP node can be.\n // Store them here to save space when minified\n COMPOUND: 'Compound',\n SEQUENCE_EXP: 'SequenceExpression',\n IDENTIFIER: 'Identifier',\n MEMBER_EXP: 'MemberExpression',\n LITERAL: 'Literal',\n THIS_EXP: 'ThisExpression',\n CALL_EXP: 'CallExpression',\n UNARY_EXP: 'UnaryExpression',\n BINARY_EXP: 'BinaryExpression',\n ARRAY_EXP: 'ArrayExpression',\n TAB_CODE: 9,\n LF_CODE: 10,\n CR_CODE: 13,\n SPACE_CODE: 32,\n PERIOD_CODE: 46,\n // '.'\n COMMA_CODE: 44,\n // ','\n SQUOTE_CODE: 39,\n // single quote\n DQUOTE_CODE: 34,\n // double quotes\n OPAREN_CODE: 40,\n // (\n CPAREN_CODE: 41,\n // )\n OBRACK_CODE: 91,\n // [\n CBRACK_CODE: 93,\n // ]\n QUMARK_CODE: 63,\n // ?\n SEMCOL_CODE: 59,\n // ;\n COLON_CODE: 58,\n // :\n\n // Operations\n // ----------\n // Use a quickly-accessible map to store all of the unary operators\n // Values are set to `1` (it really doesn't matter)\n unary_ops: {\n '-': 1,\n '!': 1,\n '~': 1,\n '+': 1\n },\n // Also use a map for the binary operations but set their values to their\n // binary precedence for quick reference (higher number = higher precedence)\n // see [Order of operations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)\n binary_ops: {\n '||': 1,\n '??': 1,\n '&&': 2,\n '|': 3,\n '^': 4,\n '&': 5,\n '==': 6,\n '!=': 6,\n '===': 6,\n '!==': 6,\n '<': 7,\n '>': 7,\n '<=': 7,\n '>=': 7,\n '<<': 8,\n '>>': 8,\n '>>>': 8,\n '+': 9,\n '-': 9,\n '*': 10,\n '/': 10,\n '%': 10,\n '**': 11\n },\n // sets specific binary_ops as right-associative\n right_associative: new Set(['**']),\n // Additional valid identifier chars, apart from a-z, A-Z and 0-9 (except on the starting char)\n additional_identifier_chars: new Set(['$', '_']),\n // Literals\n // ----------\n // Store the values to return for the various literals we may encounter\n literals: {\n 'true': true,\n 'false': false,\n 'null': null\n },\n // Except for `this`, which is special. This could be changed to something like `'self'` as well\n this_str: 'this'\n});\nJsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);\nJsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);\n\n// Backward Compatibility:\nconst jsep = expr => new Jsep(expr).parse();\nconst stdClassProps = Object.getOwnPropertyNames(class Test {});\nObject.getOwnPropertyNames(Jsep).filter(prop => !stdClassProps.includes(prop) && jsep[prop] === undefined).forEach(m => {\n jsep[m] = Jsep[m];\n});\njsep.Jsep = Jsep; // allows for const { Jsep } = require('jsep');\n\nconst CONDITIONAL_EXP = 'ConditionalExpression';\nvar ternary = {\n name: 'ternary',\n init(jsep) {\n // Ternary expression: test ? consequent : alternate\n jsep.hooks.add('after-expression', function gobbleTernary(env) {\n if (env.node && this.code === jsep.QUMARK_CODE) {\n this.index++;\n const test = env.node;\n const consequent = this.gobbleExpression();\n if (!consequent) {\n this.throwError('Expected expression');\n }\n this.gobbleSpaces();\n if (this.code === jsep.COLON_CODE) {\n this.index++;\n const alternate = this.gobbleExpression();\n if (!alternate) {\n this.throwError('Expected expression');\n }\n env.node = {\n type: CONDITIONAL_EXP,\n test,\n consequent,\n alternate\n };\n\n // check for operators of higher priority than ternary (i.e. assignment)\n // jsep sets || at 1, and assignment at 0.9, and conditional should be between them\n if (test.operator && jsep.binary_ops[test.operator] <= 0.9) {\n let newTest = test;\n while (newTest.right.operator && jsep.binary_ops[newTest.right.operator] <= 0.9) {\n newTest = newTest.right;\n }\n env.node.test = newTest.right;\n newTest.right = env.node;\n env.node = test;\n }\n } else {\n this.throwError('Expected :');\n }\n }\n });\n }\n};\n\n// Add default plugins:\n\njsep.plugins.register(ternary);\n\nconst FSLASH_CODE = 47; // '/'\nconst BSLASH_CODE = 92; // '\\\\'\n\nvar index = {\n name: 'regex',\n init(jsep) {\n // Regex literal: /abc123/ig\n jsep.hooks.add('gobble-token', function gobbleRegexLiteral(env) {\n if (this.code === FSLASH_CODE) {\n const patternIndex = ++this.index;\n let inCharSet = false;\n while (this.index < this.expr.length) {\n if (this.code === FSLASH_CODE && !inCharSet) {\n const pattern = this.expr.slice(patternIndex, this.index);\n let flags = '';\n while (++this.index < this.expr.length) {\n const code = this.code;\n if (code >= 97 && code <= 122 // a...z\n || code >= 65 && code <= 90 // A...Z\n || code >= 48 && code <= 57) {\n // 0-9\n flags += this.char;\n } else {\n break;\n }\n }\n let value;\n try {\n value = new RegExp(pattern, flags);\n } catch (e) {\n this.throwError(e.message);\n }\n env.node = {\n type: jsep.LITERAL,\n value,\n raw: this.expr.slice(patternIndex - 1, this.index)\n };\n\n // allow . [] and () after regex: /regex/.test(a)\n env.node = this.gobbleTokenProperty(env.node);\n return env.node;\n }\n if (this.code === jsep.OBRACK_CODE) {\n inCharSet = true;\n } else if (inCharSet && this.code === jsep.CBRACK_CODE) {\n inCharSet = false;\n }\n this.index += this.code === BSLASH_CODE ? 2 : 1;\n }\n this.throwError('Unclosed Regex');\n }\n });\n }\n};\n\nconst PLUS_CODE = 43; // +\nconst MINUS_CODE = 45; // -\n\nconst plugin = {\n name: 'assignment',\n assignmentOperators: new Set(['=', '*=', '**=', '/=', '%=', '+=', '-=', '<<=', '>>=', '>>>=', '&=', '^=', '|=', '||=', '&&=', '??=']),\n updateOperators: [PLUS_CODE, MINUS_CODE],\n assignmentPrecedence: 0.9,\n init(jsep) {\n const updateNodeTypes = [jsep.IDENTIFIER, jsep.MEMBER_EXP];\n plugin.assignmentOperators.forEach(op => jsep.addBinaryOp(op, plugin.assignmentPrecedence, true));\n jsep.hooks.add('gobble-token', function gobbleUpdatePrefix(env) {\n const code = this.code;\n if (plugin.updateOperators.some(c => c === code && c === this.expr.charCodeAt(this.index + 1))) {\n this.index += 2;\n env.node = {\n type: 'UpdateExpression',\n operator: code === PLUS_CODE ? '++' : '--',\n argument: this.gobbleTokenProperty(this.gobbleIdentifier()),\n prefix: true\n };\n if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {\n this.throwError(`Unexpected ${env.node.operator}`);\n }\n }\n });\n jsep.hooks.add('after-token', function gobbleUpdatePostfix(env) {\n if (env.node) {\n const code = this.code;\n if (plugin.updateOperators.some(c => c === code && c === this.expr.charCodeAt(this.index + 1))) {\n if (!updateNodeTypes.includes(env.node.type)) {\n this.throwError(`Unexpected ${env.node.operator}`);\n }\n this.index += 2;\n env.node = {\n type: 'UpdateExpression',\n operator: code === PLUS_CODE ? '++' : '--',\n argument: env.node,\n prefix: false\n };\n }\n }\n });\n jsep.hooks.add('after-expression', function gobbleAssignment(env) {\n if (env.node) {\n // Note: Binaries can be chained in a single expression to respect\n // operator precedence (i.e. a = b = 1 + 2 + 3)\n // Update all binary assignment nodes in the tree\n updateBinariesToAssignments(env.node);\n }\n });\n function updateBinariesToAssignments(node) {\n if (plugin.assignmentOperators.has(node.operator)) {\n node.type = 'AssignmentExpression';\n updateBinariesToAssignments(node.left);\n updateBinariesToAssignments(node.right);\n } else if (!node.operator) {\n Object.values(node).forEach(val => {\n if (val && typeof val === 'object') {\n updateBinariesToAssignments(val);\n }\n });\n }\n }\n }\n};\n\n/* eslint-disable no-bitwise -- Convenient */\n\n// register plugins\njsep.plugins.register(index, plugin);\njsep.addUnaryOp('typeof');\njsep.addUnaryOp('void');\njsep.addLiteral('null', null);\njsep.addLiteral('undefined', undefined);\nconst BLOCKED_PROTO_PROPERTIES = new Set(['constructor', '__proto__', '__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__']);\nconst SafeEval = {\n /**\n * @param {jsep.Expression} ast\n * @param {Record<string, any>} subs\n */\n evalAst(ast, subs) {\n switch (ast.type) {\n case 'BinaryExpression':\n case 'LogicalExpression':\n return SafeEval.evalBinaryExpression(ast, subs);\n case 'Compound':\n return SafeEval.evalCompound(ast, subs);\n case 'ConditionalExpression':\n return SafeEval.evalConditionalExpression(ast, subs);\n case 'Identifier':\n return SafeEval.evalIdentifier(ast, subs);\n case 'Literal':\n return SafeEval.evalLiteral(ast, subs);\n case 'MemberExpression':\n return SafeEval.evalMemberExpression(ast, subs);\n case 'UnaryExpression':\n return SafeEval.evalUnaryExpression(ast, subs);\n case 'ArrayExpression':\n return SafeEval.evalArrayExpression(ast, subs);\n case 'CallExpression':\n return SafeEval.evalCallExpression(ast, subs);\n case 'AssignmentExpression':\n return SafeEval.evalAssignmentExpression(ast, subs);\n default:\n throw SyntaxError('Unexpected expression', ast);\n }\n },\n evalBinaryExpression(ast, subs) {\n const result = {\n '||': (a, b) => a || b(),\n '&&': (a, b) => a && b(),\n '|': (a, b) => a | b(),\n '^': (a, b) => a ^ b(),\n '&': (a, b) => a & b(),\n // eslint-disable-next-line eqeqeq -- API\n '==': (a, b) => a == b(),\n // eslint-disable-next-line eqeqeq -- API\n '!=': (a, b) => a != b(),\n '===': (a, b) => a === b(),\n '!==': (a, b) => a !== b(),\n '<': (a, b) => a < b(),\n '>': (a, b) => a > b(),\n '<=': (a, b) => a <= b(),\n '>=': (a, b) => a >= b(),\n '<<': (a, b) => a << b(),\n '>>': (a, b) => a >> b(),\n '>>>': (a, b) => a >>> b(),\n '+': (a, b) => a + b(),\n '-': (a, b) => a - b(),\n '*': (a, b) => a * b(),\n '/': (a, b) => a / b(),\n '%': (a, b) => a % b()\n }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));\n return result;\n },\n evalCompound(ast, subs) {\n let last;\n for (let i = 0; i < ast.body.length; i++) {\n if (ast.body[i].type === 'Identifier' && ['var', 'let', 'const'].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === 'AssignmentExpression') {\n // var x=2; is detected as\n // [{Identifier var}, {AssignmentExpression x=2}]\n // eslint-disable-next-line @stylistic/max-len -- Long\n // eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient\n i += 1;\n }\n const expr = ast.body[i];\n last = SafeEval.evalAst(expr, subs);\n }\n return last;\n },\n evalConditionalExpression(ast, subs) {\n if (SafeEval.evalAst(ast.test, subs)) {\n return SafeEval.evalAst(ast.consequent, subs);\n }\n return SafeEval.evalAst(ast.alternate, subs);\n },\n evalIdentifier(ast, subs) {\n if (Object.hasOwn(subs, ast.name)) {\n return subs[ast.name];\n }\n throw ReferenceError(`${ast.name} is not defined`);\n },\n evalLiteral(ast) {\n return ast.value;\n },\n evalMemberExpression(ast, subs) {\n const prop = String(\n // NOTE: `String(value)` throws error when\n // value has overwritten the toString method to return non-string\n // i.e. `value = {toString: () => []}`\n ast.computed ? SafeEval.evalAst(ast.property) // `object[property]`\n : ast.property.name // `object.property` property is Identifier\n );\n const obj = SafeEval.evalAst(ast.object, subs);\n if (obj === undefined || obj === null) {\n throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);\n }\n if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {\n throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);\n }\n const result = obj[prop];\n if (typeof result === 'function') {\n return result.bind(obj); // arrow functions aren't affected by bind.\n }\n return result;\n },\n evalUnaryExpression(ast, subs) {\n const result = {\n '-': a => -SafeEval.evalAst(a, subs),\n '!': a => !SafeEval.evalAst(a, subs),\n '~': a => ~SafeEval.evalAst(a, subs),\n // eslint-disable-next-line no-implicit-coercion -- API\n '+': a => +SafeEval.evalAst(a, subs),\n typeof: a => typeof SafeEval.evalAst(a, subs),\n // eslint-disable-next-line no-void, sonarjs/void-use -- feature\n void: a => void SafeEval.evalAst(a, subs)\n }[ast.operator](ast.argument);\n return result;\n },\n evalArrayExpression(ast, subs) {\n return ast.elements.map(el => SafeEval.evalAst(el, subs));\n },\n evalCallExpression(ast, subs) {\n const args = ast.arguments.map(arg => SafeEval.evalAst(arg, subs));\n const func = SafeEval.evalAst(ast.callee, subs);\n /* c8 ignore start */\n if (func === Function) {\n // unreachable since BLOCKED_PROTO_PROPERTIES includes 'constructor'\n throw new Error('Function constructor is disabled');\n }\n /* c8 ignore end */\n return func(...args);\n },\n evalAssignmentExpression(ast, subs) {\n if (ast.left.type !== 'Identifier') {\n throw SyntaxError('Invalid left-hand side in assignment');\n }\n const id = ast.left.name;\n const value = SafeEval.evalAst(ast.right, subs);\n subs[id] = value;\n return subs[id];\n }\n};\n\n/**\n * A replacement for NodeJS' VM.Script which is also {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP | Content Security Policy} friendly.\n */\nclass SafeScript {\n /**\n * @param {string} expr Expression to evaluate\n */\n constructor(expr) {\n this.code = expr;\n this.ast = jsep(this.code);\n }\n\n /**\n * @param {object} context Object whose items will be added\n * to evaluation\n * @returns {EvaluatedResult} Result of evaluated code\n */\n runInNewContext(context) {\n // `Object.create(null)` creates a prototypeless object\n const keyMap = Object.assign(Object.create(null), context);\n return SafeEval.evalAst(this.ast, keyMap);\n }\n}\n\n/* eslint-disable camelcase -- Convenient for escaping */\n\n\n/**\n * @typedef {null|boolean|number|string|object|GenericArray} JSONObject\n */\n\n/**\n * @typedef {any} AnyItem\n */\n\n/**\n * @typedef {any} AnyResult\n */\n\n/**\n * Copies array and then pushes item into it.\n * @param {GenericArray} arr Array to copy and into which to push\n * @param {AnyItem} item Array item to add (to end)\n * @returns {GenericArray} Copy of the original array\n */\nfunction push(arr, item) {\n arr = arr.slice();\n arr.push(item);\n return arr;\n}\n/**\n * Copies array and then unshifts item into it.\n * @param {AnyItem} item Array item to add (to beginning)\n * @param {GenericArray} arr Array to copy and into which to unshift\n * @returns {GenericArray} Copy of the original array\n */\nfunction unshift(item, arr) {\n arr = arr.slice();\n arr.unshift(item);\n return arr;\n}\n\n/**\n * Caught when JSONPath is used without `new` but rethrown if with `new`\n * @extends Error\n */\nclass NewError extends Error {\n /**\n * @param {AnyResult} value The evaluated scalar value\n */\n constructor(value) {\n super('JSONPath should not be called with \"new\" (it prevents return ' + 'of (unwrapped) scalar values)');\n this.avoidNew = true;\n this.value = value;\n this.name = 'NewError';\n }\n}\n\n/**\n* @typedef {object} ReturnObject\n* @property {string} path\n* @property {JSONObject} value\n* @property {object|GenericArray} parent\n* @property {string} parentProperty\n*/\n\n/**\n* @callback JSONPathCallback\n* @param {string|object} preferredOutput\n* @param {\"value\"|\"property\"} type\n* @param {ReturnObject} fullRetObj\n* @returns {void}\n*/\n\n/**\n* @callback OtherTypeCallback\n* @param {JSONObject} val\n* @param {string} path\n* @param {object|GenericArray} parent\n* @param {string} parentPropName\n* @returns {boolean}\n*/\n\n/**\n * @typedef {any} ContextItem\n */\n\n/**\n * @typedef {any} EvaluatedResult\n */\n\n/**\n* @callback EvalCallback\n* @param {string} code\n* @param {ContextItem} context\n* @returns {EvaluatedResult}\n*/\n\n/**\n * @typedef {typeof SafeScript} EvalClass\n */\n\n/**\n * @typedef {object} JSONPathOptions\n * @property {JSON} json\n * @property {string|string[]} path\n * @property {\"value\"|\"path\"|\"pointer\"|\"parent\"|\"parentProperty\"|\n * \"all\"} [resultType=\"value\"]\n * @property {boolean} [flatten=false]\n * @property {boolean} [wrap=true]\n * @property {object} [sandbox={}]\n * @property {EvalCallback|EvalClass|'safe'|'native'|\n * boolean} [eval = 'safe']\n * @property {object|GenericArray|null} [parent=null]\n * @property {string|null} [parentProperty=null]\n * @property {JSONPathCallback} [callback]\n * @property {OtherTypeCallback} [otherTypeCallback] Defaults to\n * function which throws on encountering `@other`\n * @property {boolean} [autostart=true]\n */\n\n/**\n * @param {string|JSONPathOptions} opts If a string, will be treated as `expr`\n * @param {string} [expr] JSON path to evaluate\n * @param {JSON} [obj] JSON object to evaluate against\n * @param {JSONPathCallback} [callback] Passed 3 arguments: 1) desired payload\n * per `resultType`, 2) `\"value\"|\"property\"`, 3) Full returned object with\n * all payloads\n * @param {OtherTypeCallback} [otherTypeCallback] If `@other()` is at the end\n * of one's query, this will be invoked with the value of the item, its\n * path, its parent, and its parent's property name, and it should return\n * a boolean indicating whether the supplied value belongs to the \"other\"\n * type or not (or it may handle transformations and return `false`).\n * @returns {JSONPath}\n * @class\n */\nfunction JSONPath(opts, expr, obj, callback, otherTypeCallback) {\n // eslint-disable-next-line no-restricted-syntax -- Allow for pseudo-class\n if (!(this instanceof JSONPath)) {\n try {\n return new JSONPath(opts, expr, obj, callback, otherTypeCallback);\n } catch (e) {\n if (!e.avoidNew) {\n throw e;\n }\n return e.value;\n }\n }\n if (typeof opts === 'string') {\n otherTypeCallback = callback;\n callback = obj;\n obj = expr;\n expr = opts;\n opts = null;\n }\n const optObj = opts && typeof opts === 'object';\n opts = opts || {};\n this.json = opts.json || obj;\n this.path = opts.path || expr;\n this.resultType = opts.resultType || 'value';\n this.flatten = opts.flatten || false;\n this.wrap = Object.hasOwn(opts, 'wrap') ? opts.wrap : true;\n this.sandbox = opts.sandbox || {};\n this.eval = opts.eval === undefined ? 'safe' : opts.eval;\n this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === 'undefined' ? false : opts.ignoreEvalErrors;\n this.parent = opts.parent || null;\n this.parentProperty = opts.parentProperty || null;\n this.callback = opts.callback || callback || null;\n this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function () {\n throw new TypeError('You must supply an otherTypeCallback callback option ' + 'with the @other() operator.');\n };\n if (opts.autostart !== false) {\n const args = {\n path: optObj ? opts.path : expr\n };\n if (!optObj) {\n args.json = obj;\n } else if ('json' in opts) {\n args.json = opts.json;\n }\n const ret = this.evaluate(args);\n if (!ret || typeof ret !== 'object') {\n throw new NewError(ret);\n }\n return ret;\n }\n}\n\n// PUBLIC METHODS\nJSONPath.prototype.evaluate = function (expr, json, callback, otherTypeCallback) {\n let currParent = this.parent,\n currParentProperty = this.parentProperty;\n let {\n flatten,\n wrap\n } = this;\n this.currResultType = this.resultType;\n this.currEval = this.eval;\n this.currSandbox = this.sandbox;\n callback = callback || this.callback;\n this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;\n json = json || this.json;\n expr = expr || this.path;\n if (expr && typeof expr === 'object' && !Array.isArray(expr)) {\n if (!expr.path && expr.path !== '') {\n throw new TypeError('You must supply a \"path\" property when providing an object ' + 'argument to JSONPath.evaluate().');\n }\n if (!Object.hasOwn(expr, 'json')) {\n throw new TypeError('You must supply a \"json\" property when providing an object ' + 'argument to JSONPath.evaluate().');\n }\n ({\n json\n } = expr);\n flatten = Object.hasOwn(expr, 'flatten') ? expr.flatten : flatten;\n this.currResultType = Object.hasOwn(expr, 'resultType') ? expr.resultType : this.currResultType;\n this.currSandbox = Object.hasOwn(expr, 'sandbox') ? expr.sandbox : this.currSandbox;\n wrap = Object.hasOwn(expr, 'wrap') ? expr.wrap : wrap;\n this.currEval = Object.hasOwn(expr, 'eval') ? expr.eval : this.currEval;\n callback = Object.hasOwn(expr, 'callback') ? expr.callback : callback;\n this.currOtherTypeCallback = Object.hasOwn(expr, 'otherTypeCallback') ? expr.otherTypeCallback : this.currOtherTypeCallback;\n currParent = Object.hasOwn(expr, 'parent') ? expr.parent : currParent;\n currParentProperty = Object.hasOwn(expr, 'parentProperty') ? expr.parentProperty : currParentProperty;\n expr = expr.path;\n }\n currParent = currParent || null;\n currParentProperty = currParentProperty || null;\n if (Array.isArray(expr)) {\n expr = JSONPath.toPathString(expr);\n }\n if (!expr && expr !== '' || !json) {\n return undefined;\n }\n const exprList = JSONPath.toPathArray(expr);\n if (exprList[0] === '$' && exprList.length > 1) {\n exprList.shift();\n }\n this._hasParentSelector = null;\n const result = this._trace(exprList, json, ['$'], currParent, currParentProperty, callback).filter(function (ea) {\n return ea && !ea.isParentSelector;\n });\n if (!result.length) {\n return wrap ? [] : undefined;\n }\n if (!wrap && result.length === 1 && !result[0].hasArrExpr) {\n return this._getPreferredOutput(result[0]);\n }\n return result.reduce((rslt, ea) => {\n const valOrPath = this._getPreferredOutput(ea);\n if (flatten && Array.isArray(valOrPath)) {\n rslt = rslt.concat(valOrPath);\n } else {\n rslt.push(valOrPath);\n }\n return rslt;\n }, []);\n};\n\n// PRIVATE METHODS\n\nJSONPath.prototype._getPreferredOutput = function (ea) {\n const resultType = this.currResultType;\n switch (resultType) {\n case 'all':\n {\n const path = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);\n ea.pointer = JSONPath.toPointer(path);\n ea.path = typeof ea.path === 'string' ? ea.path : JSONPath.toPathString(ea.path);\n return ea;\n }\n case 'value':\n case 'parent':\n case 'parentProperty':\n return ea[resultType];\n case 'path':\n return JSONPath.toPathString(ea[resultType]);\n case 'pointer':\n return JSONPath.toPointer(ea.path);\n default:\n throw new TypeError('Unknown result type');\n }\n};\nJSONPath.prototype._handleCallback = function (fullRetObj, callback, type) {\n if (callback) {\n const preferredOutput = this._getPreferredOutput(fullRetObj);\n fullRetObj.path = typeof fullRetObj.path === 'string' ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);\n // eslint-disable-next-line n/callback-return -- No need to return\n callback(preferredOutput, type, fullRetObj);\n }\n};\n\n/**\n *\n * @param {string} expr\n * @param {JSONObject} val\n * @param {string} path\n * @param {object|GenericArray} parent\n * @param {string} parentPropName\n * @param {JSONPathCallback} callback\n * @param {boolean} hasArrExpr\n * @param {boolean} literalPriority\n * @returns {ReturnObject|ReturnObject[]}\n */\nJSONPath.prototype._trace = function (expr, val, path, parent, parentPropName, callback, hasArrExpr, literalPriority) {\n // No expr to follow? return path and value as the result of\n // this trace branch\n let retObj;\n if (!expr.length) {\n retObj = {\n path,\n value: val,\n parent,\n parentProperty: parentPropName,\n hasArrExpr\n };\n this._handleCallback(retObj, callback, 'value');\n return retObj;\n }\n const loc = expr[0],\n x = expr.slice(1);\n\n // We need to gather the return value of recursive trace calls in order to\n // do the parent sel computation.\n const ret = [];\n /**\n *\n * @param {ReturnObject|ReturnObject[]} elems\n * @returns {void}\n */\n function addRet(elems) {\n if (Array.isArray(elems)) {\n // This was causing excessive stack size in Node (with or\n // without Babel) against our performance test:\n // `ret.push(...elems);`\n elems.forEach(t => {\n ret.push(t);\n });\n } else {\n ret.push(elems);\n }\n }\n if ((typeof loc !== 'string' || literalPriority) && val && Object.hasOwn(val, loc)) {\n // simple case--directly follow property\n addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, hasArrExpr));\n // eslint-disable-next-line unicorn/prefer-switch -- Part of larger `if`\n } else if (loc === '*') {\n // all child properties\n this._walk(val, m => {\n addRet(this._trace(x, val[m], push(path, m), val, m, callback, true, true));\n });\n } else if (loc === '..') {\n // all descendent parent properties\n // Check remaining expression with val's immediate children\n addRet(this._trace(x, val, path, parent, parentPropName, callback, hasArrExpr));\n this._walk(val, m => {\n // We don't join m and x here because we only want parents,\n // not scalar values\n if (typeof val[m] === 'object') {\n // Keep going with recursive descent on val's\n // object children\n addRet(this._trace(expr.slice(), val[m], push(path, m), val, m, callback, true));\n }\n });\n // The parent sel computation is handled in the frame above using the\n // ancestor object of val\n } else if (loc === '^') {\n // This is not a final endpoint, so we do not invoke the callback here\n this._hasParentSelector = true;\n return {\n path: path.slice(0, -1),\n expr: x,\n isParentSelector: true\n };\n } else if (loc === '~') {\n // property name\n retObj = {\n path: push(path, loc),\n value: parentPropName,\n parent,\n parentProperty: null\n };\n this._handleCallback(retObj, callback, 'property');\n return retObj;\n } else if (loc === '$') {\n // root only\n addRet(this._trace(x, val, path, null, null, callback, hasArrExpr));\n } else if (/^(-?\\d*):(-?\\d*):?(\\d*)$/u.test(loc)) {\n // [start:end:step] Python slice syntax\n addRet(this._slice(loc, x, val, path, parent, parentPropName, callback));\n } else if (loc.indexOf('?(') === 0) {\n // [?(expr)] (filtering)\n if (this.currEval === false) {\n throw new Error('Eval [?(expr)] prevented in JSONPath expression.');\n }\n const safeLoc = loc.replace(/^\\?\\((.*?)\\)$/u, '$1');\n // check for a nested filter expression\n const nested = /@.?([^?]*)[['](\\??\\(.*?\\))(?!.\\)\\])[\\]']/gu.exec(safeLoc);\n if (nested) {\n // find if there are matches in the nested expression\n // add them to the result set if there is at least one match\n this._walk(val, m => {\n const npath = [nested[2]];\n const nvalue = nested[1] ? val[m][nested[1]] : val[m];\n const filterResults = this._trace(npath, nvalue, path, parent, parentPropName, callback, true);\n if (filterResults.length > 0) {\n addRet(this._trace(x, val[m], push(path, m), val, m, callback, true));\n }\n });\n } else {\n this._walk(val, m => {\n if (this._eval(safeLoc, val[m], m, path, parent, parentPropName)) {\n addRet(this._trace(x, val[m], push(path, m), val, m, callback, true));\n }\n });\n }\n } else if (loc[0] === '(') {\n // [(expr)] (dynamic property/index)\n if (this.currEval === false) {\n throw new Error('Eval [(expr)] prevented in JSONPath expression.');\n }\n // As this will resolve to a property name (but we don't know it\n // yet), property and parent information is relative to the\n // parent of the property to which this expression will resolve\n addRet(this._trace(unshift(this._eval(loc, val, path.at(-1), path.slice(0, -1), parent, parentPropName), x), val, path, parent, parentPropName, callback, hasArrExpr));\n } else if (loc[0] === '@') {\n // value type: @boolean(), etc.\n let addType = false;\n const valueType = loc.slice(1, -2);\n switch (valueType) {\n case 'scalar':\n if (!val || !['object', 'function'].includes(typeof val)) {\n addType = true;\n }\n break;\n case 'boolean':\n case 'string':\n case 'undefined':\n case 'function':\n if (typeof val === valueType) {\n addType = true;\n }\n break;\n case 'integer':\n if (Number.isFinite(val) && !(val % 1)) {\n addType = true;\n }\n break;\n case 'number':\n if (Number.isFinite(val)) {\n addType = true;\n }\n break;\n case 'nonFinite':\n if (typeof val === 'number' && !Number.isFinite(val)) {\n addType = true;\n }\n break;\n case 'object':\n if (val && typeof val === valueType) {\n addType = true;\n }\n break;\n case 'array':\n if (Array.isArray(val)) {\n addType = true;\n }\n break;\n case 'other':\n addType = this.currOtherTypeCallback(val, path, parent, parentPropName);\n break;\n case 'null':\n if (val === null) {\n addType = true;\n }\n break;\n /* c8 ignore next 2 */\n default:\n throw new TypeError('Unknown value type ' + valueType);\n }\n if (addType) {\n retObj = {\n path,\n value: val,\n parent,\n parentProperty: parentPropName\n };\n this._handleCallback(retObj, callback, 'value');\n return retObj;\n }\n // `-escaped property\n } else if (loc[0] === '`' && val && Object.hasOwn(val, loc.slice(1))) {\n const locProp = loc.slice(1);\n addRet(this._trace(x, val[locProp], push(path, locProp), val, locProp, callback, hasArrExpr, true));\n } else if (loc.includes(',')) {\n // [name1,name2,...]\n const parts = loc.split(',');\n for (const part of parts) {\n addRet(this._trace(unshift(part, x), val, path, parent, parentPropName, callback, true));\n }\n // simple case--directly follow property\n } else if (!literalPriority && val && Object.hasOwn(val, loc)) {\n addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, hasArrExpr, true));\n }\n\n // We check the resulting values for parent selections. For parent\n // selections we discard the value object and continue the trace with the\n // current val object\n if (this._hasParentSelector) {\n for (let t = 0; t < ret.length; t++) {\n const rett = ret[t];\n if (rett && rett.isParentSelector) {\n const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);\n if (Array.isArray(tmp)) {\n ret[t] = tmp[0];\n const tl = tmp.length;\n for (let tt = 1; tt < tl; tt++) {\n // eslint-disable-next-line @stylistic/max-len -- Long\n // eslint-disable-next-line sonarjs/updated-loop-counter -- Convenient\n t++;\n ret.splice(t, 0, tmp[tt]);\n }\n } else {\n ret[t] = tmp;\n }\n }\n }\n }\n return ret;\n};\nJSONPath.prototype._walk = function (val, f) {\n if (Array.isArray(val)) {\n const n = val.length;\n for (let i = 0; i < n; i++) {\n f(i);\n }\n } else if (val && typeof val === 'object') {\n Object.keys(val).forEach(m => {\n f(m);\n });\n }\n};\nJSONPath.prototype._slice = function (loc, expr, val, path, parent, parentPropName, callback) {\n if (!Array.isArray(val)) {\n return undefined;\n }\n const len = val.length,\n parts = loc.split(':'),\n step = parts[2] && Number.parseInt(parts[2]) || 1;\n let start = parts[0] && Number.parseInt(parts[0]) || 0,\n end = parts[1] && Number.parseInt(parts[1]) || len;\n start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);\n end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);\n const ret = [];\n for (let i = start; i < end; i += step) {\n const tmp = this._trace(unshift(i, expr), val, path, parent, parentPropName, callback, true);\n // Should only be possible to be an array here since first part of\n // ``unshift(i, expr)` passed in above would not be empty, nor `~`,\n // nor begin with `@` (as could return objects)\n // This was causing excessive stack size in Node (with or\n // without Babel) against our performance test: `ret.push(...tmp);`\n tmp.forEach(t => {\n ret.push(t);\n });\n }\n return ret;\n};\nJSONPath.prototype._eval = function (code, _v, _vname, path, parent, parentPropName) {\n this.currSandbox._$_parentProperty = parentPropName;\n this.currSandbox._$_parent = parent;\n this.currSandbox._$_property = _vname;\n this.currSandbox._$_root = this.json;\n this.currSandbox._$_v = _v;\n const containsPath = code.includes('@path');\n if (containsPath) {\n this.currSandbox._$_path = JSONPath.toPathString(path.concat([_vname]));\n }\n const scriptCacheKey = this.currEval + 'Script:' + code;\n if (!JSONPath.cache[scriptCacheKey]) {\n let script = code.replaceAll('@parentProperty', '_$_parentProperty').replaceAll('@parent', '_$_parent').replaceAll('@property', '_$_property').replaceAll('@root', '_$_root').replaceAll(/@([.\\s)[])/gu, '_$_v$1');\n if (containsPath) {\n script = script.replaceAll('@path', '_$_path');\n }\n if (this.currEval === 'safe' || this.currEval === true || this.currEval === undefined) {\n JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);\n } else if (this.currEval === 'native') {\n JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);\n } else if (typeof this.currEval === 'function' && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, 'runInNewContext')) {\n const CurrEval = this.currEval;\n JSONPath.cache[scriptCacheKey] = new CurrEval(script);\n } else if (typeof this.currEval === 'function') {\n JSONPath.cache[scriptCacheKey] = {\n runInNewContext: context => this.currEval(script, context)\n };\n } else {\n throw new TypeError(`Unknown \"eval\" property \"${this.currEval}\"`);\n }\n }\n try {\n return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);\n } catch (e) {\n if (this.ignoreEvalErrors) {\n return false;\n }\n throw new Error('jsonPath: ' + e.message + ': ' + code);\n }\n};\n\n// PUBLIC CLASS PROPERTIES AND METHODS\n\n// Could store the cache object itself\nJSONPath.cache = {};\n\n/**\n * @param {string[]} pathArr Array to convert\n * @returns {string} The path string\n */\nJSONPath.toPathString = function (pathArr) {\n const x = pathArr,\n n = x.length;\n let p = '$';\n for (let i = 1; i < n; i++) {\n if (!/^(~|\\^|@.*?\\(\\))$/u.test(x[i])) {\n p += /^[0-9*]+$/u.test(x[i]) ? '[' + x[i] + ']' : \"['\" + x[i] + \"']\";\n }\n }\n return p;\n};\n\n/**\n * @param {string} pointer JSON Path\n * @returns {string} JSON Pointer\n */\nJSONPath.toPointer = function (pointer) {\n const x = pointer,\n n = x.length;\n let p = '';\n for (let i = 1; i < n; i++) {\n if (!/^(~|\\^|@.*?\\(\\))$/u.test(x[i])) {\n p += '/' + x[i].toString().replaceAll('~', '~0').replaceAll('/', '~1');\n }\n }\n return p;\n};\n\n/**\n * @param {string} expr Expression to convert\n * @returns {string[]}\n */\nJSONPath.toPathArray = function (expr) {\n const {\n cache\n } = JSONPath;\n if (cache[expr]) {\n return cache[expr].concat();\n }\n const subx = [];\n const normalized = expr\n // Properties\n .replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\\(\\)/gu, ';$&;')\n // Parenthetical evaluations (filtering and otherwise), directly\n // within brackets or single quotes\n .replaceAll(/[['](\\??\\(.*?\\))[\\]'](?!.\\])/gu, function ($0, $1) {\n return '[#' + (subx.push($1) - 1) + ']';\n })\n // Escape periods and tildes within properties\n .replaceAll(/\\[['\"]([^'\\]]*)['\"]\\]/gu, function ($0, prop) {\n return \"['\" + prop.replaceAll('.', '%@%').replaceAll('~', '%%@@%%') + \"']\";\n })\n // Properties operator\n .replaceAll('~', ';~;')\n // Split by property boundaries\n .replaceAll(/['\"]?\\.['\"]?(?![^[]*\\])|\\[['\"]?/gu, ';')\n // Reinsert periods within properties\n .replaceAll('%@%', '.')\n // Reinsert tildes within properties\n .replaceAll('%%@@%%', '~')\n // Parent\n .replaceAll(/(?:;)?(\\^+)(?:;)?/gu, function ($0, ups) {\n return ';' + ups.split('').join(';') + ';';\n })\n // Descendents\n .replaceAll(/;;;|;;/gu, ';..;')\n // Remove trailing\n .replaceAll(/;$|'?\\]|'$/gu, '');\n const exprList = normalized.split(';').map(function (exp) {\n const match = exp.match(/#(\\d+)/u);\n return !match || !match[1] ? exp : subx[match[1]];\n });\n cache[expr] = exprList;\n return cache[expr].concat();\n};\nJSONPath.prototype.safeVm = {\n Script: SafeScript\n};\n\nJSONPath.prototype.vm = vm;\n\nexport { JSONPath };\n"],"x_google_ignoreList":[0],"mappings":";;;;;AAKA,IAAM,QAAN,MAAY;;;;;;;;;;;;;;;;;;;CAmBV,IAAI,MAAM,UAAU,OAAO;EACzB,IAAI,OAAO,UAAU,MAAM,UAEzB,KAAK,IAAI,QAAQ,UAAU,IACzB,KAAK,IAAI,MAAM,UAAU,EAAE,CAAC,OAAO,UAAU,EAAE;OAGjD,CAAC,MAAM,QAAQ,IAAI,IAAI,OAAO,CAAC,IAAI,EAAA,CAAG,QAAQ,SAAU,MAAM;GAC5D,KAAK,QAAQ,KAAK,SAAS,CAAC;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,CAE9B,WAAW,gBAAgB,EACF,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,SAAU,KAAK;EACxD,MAAM,QAAQ,IAAI,MAAM,SAAS;EACjC,OAAO,CAAC,SAAS,CAAC,MAAM,KAAK,MAAM,KAAK,MAAM;CAChD,CACqB;CACrB,OAAO,MAAM,KAAK,CAAC,OAAO;AAC5B;AACA,SAAS,UAAU,SAAS,EAC1B,QAAQ,WACV;AAEA,SAAS,UAAU,KAAK"}
|
package/dist/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["builtin"],"sources":["../src/ctx.ts","../src/prompt/registry.ts","../src/tools/registry.ts","../src/commands.ts","../src/skills.ts","../src/compaction/utils.ts","../src/context/tokens.ts"],"sourcesContent":["import type { Model, ReasoningEffort, Tool } from \"@zaly/ai\"\nimport type { Agent } from \"./agent.ts\"\nimport type { AgentStatus } from \"./events.ts\"\nimport type { Masker } from \"./masker.ts\"\nimport type { Notifier, NotifyOptions } from \"./notify.ts\"\nimport type { PermissionManager, PermissionOptions } from \"./permissions/manager.ts\"\nimport type { Session } from \"./session/session.ts\"\nimport type { Skills } from \"./skills.ts\"\nimport type { Swarm } from \"./swarm.ts\"\nimport type { AgentOptions } from \"./types.ts\"\n\nimport { Emitter, isInstance, normPath } from \"@zaly/shared\"\nimport { LazyCache } from \"@zaly/shared/cache\"\n\ntype AgentContextOptions = Omit<AgentOptions, \"session\"> & { session: Session }\n\ntype Slots = {\n notifier: Notifier\n masker: Masker\n permissions: PermissionManager\n swarm: Swarm\n}\n\nexport type AgentContextEvents = {\n model: { model?: Model; prev?: Model }\n reasoning: { effort: ReasoningEffort; prev?: ReasoningEffort }\n session: { session: Session; prev?: Session }\n cwd: { cwd: string; prev?: string }\n skills: { skills?: Skills }\n}\n\nexport class AgentContext extends Emitter<AgentContextEvents> {\n #agent?: Agent\n #opts: AgentOptions\n #model?: Model\n #session: Session\n #reasoning: ReasoningEffort\n #cwd: string\n #cache = new LazyCache<Slots>()\n #tools: Tool[]\n #skills?: Skills\n #prompt: string[]\n\n constructor(opts: AgentContextOptions) {\n super()\n this.#opts = opts\n this.#cwd = normPath(opts.cwd)\n this.#reasoning = opts.request?.reasoning?.effort ?? \"medium\"\n this.#session = opts.session\n this.#model = opts.model\n this.#skills = opts.skills\n this.#prompt = opts.prompt ?? []\n\n this.#tools = opts.tools ?? []\n this.onEmitError = (error) => this.#opts.logger?.child(\"context\").error(error)\n\n this.on(\"model\", async ({ model }) => {\n if (!this.#session.started) return\n if (model) await this.session.update({ modelId: model.id })\n })\n .on(\"reasoning\", async ({ effort }) => {\n if (!this.#session.started) return\n await this.session.update({ reasoning: effort })\n })\n .on(\"cwd\", ({ cwd }) => {\n if (!this.#session.started) return\n this.#cache.forget(\"permissions\") // reset permissions to force reload with new cwd\n void this.session.update({ cwd })\n })\n }\n\n private async start() {\n const [_masker, notifier] = await Promise.all([this.masker(), this.notifier()])\n\n if (!this.model) throw new Error(\"model is required to start agent session\")\n\n if (notifier) notifier.attach(this.agent)\n\n await this.session.start({\n cwd: this.cwd,\n modelId: this.model.id,\n reasoning: this.reasoning,\n })\n // oxlint-disable-next-line no-await-in-loop\n for (const m of this.#opts.messages ?? []) await this.session.add(m)\n }\n\n attach(agent: Agent) {\n if (this.#agent === agent) return\n if (this.#agent) throw new Error(\"agent already attached to context\")\n if (agent.started) throw new Error(\"cannot attach agent that has already started\")\n this.#agent = agent\n agent.once(\"start\", () => this.start())\n }\n\n get messages() {\n return this.session.messages\n }\n\n get status(): AgentStatus | undefined {\n return this.#agent?.status\n }\n\n get opts() {\n return this.#opts\n }\n\n get cwd() {\n return this.#cwd\n }\n\n set cwd(c: string) {\n if (c === this.#cwd) return\n const prev = this.#cwd\n this.#cwd = normPath(c)\n void this.emit(\"cwd\", { cwd: this.#cwd, prev })\n }\n\n get signal() {\n return this.#agent?.signal\n }\n\n get agent() {\n if (!this.#agent) throw new Error(\"agent not attached to context\")\n return this.#agent\n }\n\n get reasoning() {\n return this.#reasoning\n }\n\n set reasoning(r: ReasoningEffort) {\n if (r === this.#reasoning) return\n const prev = this.#reasoning\n this.#reasoning = r\n void this.emit(\"reasoning\", { effort: r, prev })\n }\n\n get session(): Session {\n return this.#session\n }\n\n async useSession(s: Session): Promise<void> {\n const prev = this.#session\n this.#session = s\n const modelId = s.settings.modelId\n if (modelId && modelId !== this.model?.id) {\n if (this.#opts.loadModel) {\n this.model = await this.#opts.loadModel(modelId)\n } else {\n const { loadModel } = await import(\"@zaly/ai\")\n this.model = await loadModel(modelId)\n }\n }\n this.cwd = s.settings.cwd ?? this.cwd\n this.reasoning = s.settings.reasoning ?? this.reasoning\n await this.emit(\"session\", { prev, session: s })\n if (this.#agent?.started)\n await s.start({\n cwd: this.cwd,\n modelId: this.model?.id,\n reasoning: this.reasoning,\n })\n }\n\n get model() {\n return this.#model\n }\n\n set model(m: Model | undefined) {\n if (m === this.#model) return\n const prev = this.#model\n this.#model = m\n void this.emit(\"model\", { model: m, prev })\n }\n\n set tools(tools: Tool[]) {\n this.#tools = tools\n }\n\n get tools(): Tool[] {\n return [...this.#tools, ...(this.skills?.tool ? [this.skills.tool] : [])]\n }\n\n get prompt(): string[] {\n return this.#prompt\n }\n\n set prompt(p: string[]) {\n this.#prompt = p\n }\n\n async swarm() {\n return this.#cache.need(\n \"swarm\",\n async () => {\n const { Swarm } = await import(\"./swarm.ts\")\n return new Swarm()\n },\n this.#opts.swarm\n )\n }\n\n set skills(s: Skills | undefined) {\n if (s === this.#skills) return\n this.#skills = s\n void this.emit(\"skills\", { skills: s })\n }\n\n get skills(): Skills | undefined {\n return this.#skills\n }\n\n private async notifier(): Promise<Notifier | undefined> {\n return this.#cache.want(\n \"notifier\",\n async (opts?: NotifyOptions) => {\n const { Notifier } = await import(\"./notify.ts\")\n return new Notifier(opts)\n },\n this.#opts.notify\n )\n }\n\n async masker(): Promise<Masker | undefined> {\n return this.#cache.want(\n \"masker\",\n async (opts?: AgentOptions[\"mask\"]) => {\n const { Masker } = await import(\"./masker.ts\")\n return new Masker(this.agent, opts)\n },\n this.#opts.mask\n )\n }\n\n async permissions(): Promise<PermissionManager> {\n return this.#cache.need(\n \"permissions\",\n async (opts?: PermissionOptions) => {\n const { PermissionManager } = await import(\"./permissions/manager.ts\")\n return new PermissionManager({ ...opts, cwd: this.cwd })\n },\n this.#opts.permissions\n )\n }\n}\n\nasync function loadSession(spec?: AgentOptions[\"session\"]): Promise<Session> {\n if (isInstance<Session>(spec)) return spec\n else {\n const { Session } = await import(\"./session/session.ts\")\n return await Session.load({ ...spec })\n }\n}\n\nexport async function createAgentContext(opts: AgentOptions): Promise<AgentContext> {\n const session = await loadSession(opts.session)\n return new AgentContext({ ...opts, session })\n}\n\nexport async function createAgent(opts: AgentOptions): Promise<Agent> {\n const [{ Agent }, ctx] = await Promise.all([import(\"./agent.ts\"), createAgentContext(opts)])\n return new Agent(ctx)\n}\n","import type { Model } from \"@zaly/ai\"\n\nimport { BaseCollection } from \"@zaly/shared/collection\"\nimport { createRegistry } from \"@zaly/shared/registry\"\n\nexport interface PromptCtx {\n model: Model\n cwd: string\n}\n\nexport type PromptLoader = (ctx: PromptCtx) => Promise<string>\nexport type Prompt<T extends string | PromptLoader = string | PromptLoader> = {\n name: string\n text: T\n}\nexport type { PromptCollection }\n\nconst builtin = {\n \"AGENTS.md\": (ctx) => import(\"./markdown.ts\").then((m) => m.agentsMdPrompt(ctx)),\n \"MEMORY.md\": (ctx) => import(\"./markdown.ts\").then((m) => m.memoryMdPrompt(ctx)),\n agent: () => import(\"./agent.ts\").then((m) => m.agentPrompt),\n env: (ctx) => import(\"./env.ts\").then((m) => m.prompt(ctx)),\n model: (ctx) => import(\"./model.ts\").then((m) => m.prompt(ctx)),\n} as const satisfies Record<string, PromptLoader>\n\nexport type BuiltinPrompt = keyof typeof builtin\nexport type AnyPrompt = BuiltinPrompt | (string & {})\n\nexport const promptRegistry = createRegistry<PromptLoader>(\"prompt\").from(builtin)\n\nclass PromptCollection extends BaseCollection<AnyPrompt[], Prompt[], Prompt> {\n list(): Prompt[] {\n const ret = new Map<string, Prompt>()\n for (const k of promptRegistry.keys())\n ret.set(k, {\n name: k,\n text: (ctx) => promptRegistry.load(k, ctx),\n })\n for (const r of this.registered) ret.set(r.name, r)\n return [...ret.values()]\n }\n\n async render(ctx: PromptCtx & { prompts?: string[] }): Promise<Prompt<string>[]> {\n const all = new Map(this.list().map((p) => [p.name, p]))\n const ret = await Promise.all(\n (ctx.prompts ?? this.active).map(async (p) => {\n const def = all.get(p)\n if (!def) throw new Error(`Unknown prompt: ${p}`)\n return {\n name: def.name,\n text: typeof def.text === \"string\" ? def.text : await def.text(ctx),\n }\n })\n )\n return ret.map((p) => ({ name: p.name, text: p.text.trim() })).filter((p) => p.text.length > 0)\n }\n}\n\nexport async function promptCollection(): Promise<PromptCollection> {\n return new PromptCollection([\"agent\", \"env\", \"model\", \"AGENTS.md\", \"MEMORY.md\"])\n}\n","import type { Model, Tool } from \"@zaly/ai\"\nimport type { AnyKey } from \"@zaly/shared/registry\"\n\nimport { BaseCollection } from \"@zaly/shared/collection\"\nimport { createRegistry } from \"@zaly/shared/registry\"\n\n/** Per-load context handed to every tool factory. Lets factories\n * customise the tool — typically schema descriptions — based on the\n * agent's model and working directory. Tools that don't care about\n * init just ignore the arg. */\nexport interface ToolInit {\n model: Model\n cwd: string\n}\n\nexport type { ToolCollection }\nexport type ToolLoader = () => Promise<Tool>\nexport type BuiltinTool = keyof typeof builtin\nexport type AnyTool = AnyKey<BuiltinTool>\n\n// PERF: `import(\"./x\")` makes TS load the full module type.\n// The `as string` erases the dynamic import type while emitting the same JS.\nconst builtin = {\n agent_send: () => import(\"./swarm.ts\" as string).then((m) => m.agentSendTool as Tool),\n agent_spawn: () => import(\"./swarm.ts\" as string).then((m) => m.agentSpawnTool as Tool),\n bash: () => import(\"./bash.ts\" as string).then((m) => m.bashTool as Tool),\n edit: () => import(\"./edit.ts\" as string).then((m) => m.editTool as Tool),\n fetch: () => import(\"./fetch.ts\" as string).then((m) => m.fetchTool as Tool),\n find: () => import(\"./find.ts\" as string).then((m) => m.findTool as Tool),\n grep: () => import(\"./grep.ts\" as string).then((m) => m.grepTool as Tool),\n read: () => import(\"./read.ts\" as string).then((m) => m.readTool as Tool),\n search: () => import(\"./search.ts\" as string).then((m) => m.searchTool as Tool),\n subagent: () => import(\"./subagent.ts\" as string).then((m) => m.subagentTool as Tool),\n task_list: () => import(\"./tasks.ts\" as string).then((m) => m.taskListTool as Tool),\n task_poll: () => import(\"./tasks.ts\" as string).then((m) => m.taskPollTool as Tool),\n task_stop: () => import(\"./tasks.ts\" as string).then((m) => m.taskStopTool as Tool),\n wakeup: () => import(\"./wakeup.ts\" as string).then((m) => m.wakeupTool as Tool),\n write: () => import(\"./write.ts\" as string).then((m) => m.writeTool as Tool),\n} as const satisfies Record<string, ToolLoader>\n\nexport const toolRegistry = createRegistry<ToolLoader>(\"tool\").from(builtin)\n\nclass ToolCollection extends BaseCollection<AnyTool[], AnyTool[], Tool> {\n list(): AnyTool[] {\n const ret = new Set(toolRegistry.keys())\n for (const r of this.registered) ret.add(r.name)\n return [...ret]\n }\n\n async load(tools?: AnyTool[]): Promise<Tool[]> {\n const load = async (t: string) =>\n this.registered.findLast((r) => r.name === t) ?? toolRegistry.load(t)\n return await Promise.all((tools ?? this.active).map((t) => load(t)))\n }\n}\n\nexport async function toolCollection(): Promise<ToolCollection> {\n return new ToolCollection([])\n}\n","// oxlint-disable no-await-in-loop\nimport type { ArgsOpts, ArgsResult } from \"@zaly/shared/args\"\nimport type { Logger } from \"@zaly/shared/logger\"\n\nimport { normPath, prettyPath, safeReadFile, toError } from \"@zaly/shared\"\nimport { basename } from \"pathe\"\n\nexport type Command = {\n name: string\n body: string\n path: string\n description?: string\n args: ArgsOpts\n}\n\nexport interface CommandsOptions {\n /** cmd.md paths, sorted from highest to lowest precedence. */\n paths?: string[]\n logger?: Logger\n /** Bash execution of commands:\n * - `true`: Use the system default bash shell.\n * - `false`: Disable bash execution.\n * - `string[]`: Use a custom bash shell with the provided arguments. */\n bash?: boolean | string[]\n /** When `false`, template expressions are disabled and only simple variable interpolation is allowed. */\n expr?: boolean\n}\n\ntype Token =\n | { type: \"text\"; value: string }\n | { type: \"block\"; value: string; lang?: string; body: string }\n | { type: \"script\"; value: string }\n\nconst BASH_RE = /^!`(.*)`$/\n\nexport class Commands {\n #opts: CommandsOptions\n readonly catalog = new Map<string, Command>()\n #logger?: Logger\n\n constructor(opts: CommandsOptions = {}) {\n this.#opts = opts\n this.#logger = opts.logger\n }\n\n async load(): Promise<this> {\n const paths = this.#opts.paths ?? []\n await Promise.all(paths.map(async (path) => await this.add(path)))\n return this\n }\n\n async add(path: string): Promise<void> {\n path = normPath(path)\n const name = basename(path, \".md\")\n const { parseFrontmatter } = await import(\"@zaly/shared/yaml\")\n try {\n const content = await safeReadFile(path)\n if (!content) throw new Error(`Failed to read command file at ${path}`)\n\n const { fm, body } = await parseFrontmatter(content)\n\n const args: ArgsOpts = {}\n const fmArgs = (fm.args ?? {}) as Record<string, Partial<ArgsOpts[string]>>\n\n for (const [o, opt] of Object.entries(fmArgs)) {\n // Set default values for boolean\n if (opt.type === \"boolean\") opt.default ??= false\n // Make string options required if no default is provided\n else if (opt.type === \"string\") opt.required ??= opt.default === undefined\n else {\n this.#logger?.warn(\n `Unsupported argument type for \\`--${o}\\` in command **${name}** at \\`${prettyPath(path)}\\`\\nOnly \\`string\\` and \\`boolean\\` are supported. Skipping this argument.`\n )\n continue\n }\n args[o] = opt as ArgsOpts[string]\n }\n\n const cmd: Command = {\n ...fm,\n args,\n body,\n name,\n path,\n }\n if (this.catalog.has(name)) return\n this.catalog.set(name, cmd)\n } catch (error) {\n this.#logger?.error(`Error loading **command** from ${path}: ${(error as Error).message}`)\n }\n }\n\n get(name: string): Command | undefined {\n return this.catalog.get(name)\n }\n\n async format(input: string | ArgsResult, cmd: Command): Promise<string> {\n let args: ArgsResult\n if (typeof input === \"string\") {\n const { argsParse } = await import(\"@zaly/shared/args\")\n args = await argsParse(input, cmd.args)\n } else args = input\n\n const { createTemplate } = await import(\"@zaly/shared/template\")\n const tpl = createTemplate(cmd.body, {\n expr: this.#opts.expr,\n format: (value) => {\n if (value === args._) return args._.join(\" \")\n },\n name: cmd.name,\n })\n\n const vars = {\n ...args,\n args: args._,\n raw: args.$,\n }\n\n const rendered = tpl(vars)\n if (this.#opts.bash === false) return rendered\n const bash = Array.isArray(this.#opts.bash) ? this.#opts.bash : [\"bash\"]\n\n const lines = rendered.split(\"\\n\")\n\n const ret: string[] = []\n for (const token of this.#tokenize(lines, cmd)) {\n let text: string | undefined\n if (token.type === \"script\") text = await exec(token.value, { bash })\n else if (token.type === \"block\" && /^bash\\s*!$/.test(token.lang ?? \"\"))\n text = await exec(token.body, { bash })\n ret.push(text ?? token.value)\n }\n\n return ret.join(\"\\n\")\n }\n\n *#tokenize(lines: string[], cmd: Command): Generator<Token> {\n let block: string[] = []\n let marker: RegExp | undefined = undefined\n let lang: string | undefined = undefined\n for (const line of lines) {\n const m = line.match(/^\\s*(`{3,}|~{3,})(.*)$/)\n const script = line.match(BASH_RE)\n if (marker && line.match(marker)) {\n block.push(line)\n yield {\n body: block.slice(1, -1).join(\"\\n\"),\n lang,\n type: \"block\",\n value: block.join(\"\\n\"),\n }\n marker = undefined // end of code block\n } else if (!marker && m) {\n marker = new RegExp(`^\\\\s*${m[1]}\\\\s*$`) // start of code block\n lang = m[2].trim() || undefined\n block = [line]\n } else if (marker) block.push(line)\n else if (script) yield { type: \"script\", value: script[1] }\n else yield { type: \"text\", value: line }\n }\n if (marker) throw new Error(`Unclosed code block in command **${cmd.name}**`)\n }\n}\n\nasync function exec(script: string, opts: { bash?: string[] } = {}): Promise<string | undefined> {\n if (!script.trim()) return\n const { spawnCmd } = await import(\"@zaly/shared/process\")\n let result: string\n try {\n const r = await spawnCmd(script, { bash: opts.bash ?? true, throw: true })\n result = r?.trim() ?? \"\"\n } catch (error) {\n result = toError(error).message.trim()\n }\n const md: string[] = []\n if (script.includes(\"\\n\")) {\n md.push(\"```bash\")\n md.push(script)\n md.push(\"```\")\n md.push(\"\")\n md.push(\"```shellsession\")\n md.push(result)\n md.push(\"```\")\n } else {\n md.push(\"```shellsession\")\n md.push(`$ ${script}`)\n md.push(result)\n md.push(\"```\")\n }\n md.push(\"\")\n return md.join(\"\\n\")\n}\n","import type { MetaPart, TextPart, Tool, ToolContext } from \"@zaly/ai\"\nimport type { Agent } from \"./agent.ts\"\n\nimport { AiError, defineTool, extractToolResults } from \"@zaly/ai\"\nimport { safeStatAsync } from \"@zaly/shared\"\nimport { glob } from \"@zaly/shared/glob\"\nimport { readFile } from \"node:fs/promises\"\nimport { isDeepStrictEqual } from \"node:util\"\nimport { dirname } from \"pathe\"\nimport { Type } from \"typebox\"\n\nexport type SkillMeta = {\n name: string\n mtime: number\n desc: string\n path: string\n unchanged?: boolean\n}\n\nexport type SkillTool = Tool<{ name: string }, unknown, SkillMeta>\n\n/**\n * Agent Skills support — discovery, catalog, and the activation tool.\n *\n * Locations scanned (subdirectories containing `SKILL.md`):\n * - `${cwd}/.agent/skills/` — project\n * - `${homedir()}/.agent/skills/` — user (cross-project)\n *\n * Project shadows user on name collision.\n *\n * Progressive disclosure (per the Agent Skills spec):\n * - Catalog (name + description) lives in the tool's schema /\n * description. The model sees this from the start.\n * - Body of the SKILL.md is loaded only when the tool is invoked.\n * - References (files under the skill's directory) are *enumerated*\n * at activation, not read — the model reads them via the `read`\n * tool when its instructions call for it.\n *\n * Lifecycle:\n * - Construct with `new Skills({ cwd })` — no I/O yet.\n * - Call `await skills.load()` to populate the catalog. Idempotent;\n * re-call to pick up newly installed skills (`/reload-plugins`).\n * - `skills.tool` returns the current activation tool, or undefined\n * when the catalog is empty. Lazily built; invalidated on reload.\n */\n\nexport interface SkillEntry {\n name: string\n desc: string\n mtime: number\n body: string\n /** Absolute path to the SKILL.md file. */\n path: string\n /** Absolute path to the skill's base directory (parent of SKILL.md).\n * Used as the workspace anchor for permissions and as the root for\n * resolving references. */\n dir: string\n}\n\nexport interface SkillsOptions {\n /** SKILL.md paths, sorted from highest to lowest precedence. */\n paths?: string[]\n}\n\nexport class Skills {\n readonly catalog = new Map<string, SkillEntry>()\n #tool?: Tool\n #opts: SkillsOptions\n\n protected constructor(opts: SkillsOptions = {}) {\n this.#opts = opts\n }\n\n static async load(opts?: SkillsOptions): Promise<Skills> {\n return new Skills(opts).reload()\n }\n\n /** (Re)scan project + user `.agent/skills/` directories. Wipes the\n * current catalog and the cached tool, then repopulates. Safe to\n * call mid-session — agent uses `this.tool` per-step so the next\n * request after reload picks up the change. */\n async reload(): Promise<this> {\n this.catalog.clear()\n this.#tool = undefined\n const paths = this.#opts.paths ?? []\n // Load all skills in parallel, but add them to the catalog in order so\n // that the first one wins on name collision.\n const skills = await Promise.all(paths.map(async (path) => await this.#load(path)))\n for (const skill of skills)\n if (skill && !this.catalog.has(skill.name)) this.catalog.set(skill.name, skill)\n return this\n }\n\n async #load(path: string): Promise<SkillEntry | undefined> {\n if (!path.endsWith(\"SKILL.md\")) return\n const dir = dirname(path)\n try {\n const { meta, mtime, body } = await readSkill(path)\n if (!meta.name || !meta.description || this.catalog.has(meta.name)) return\n return {\n body,\n desc: meta.description,\n dir,\n mtime,\n name: meta.name,\n path,\n }\n } catch {}\n }\n\n async #update(entry: SkillEntry): Promise<SkillEntry> {\n const updated = (await this.#load(entry.path)) ?? entry\n if (isDeepStrictEqual(updated, entry)) return entry\n this.catalog.set(entry.name, updated)\n this.#tool = undefined\n return updated\n }\n\n /** Skill base directories — pass each to `agent.permissions.addWorkspace`\n * so the model can read bundled `references/` files without tripping\n * permission asks. */\n get dirs(): readonly string[] {\n return [...this.catalog.values()].map((s) => s.dir)\n }\n\n /** The activation tool. Returns `undefined` when the catalog is empty\n * (the agent then omits skills entirely from the model's tool list,\n * per the spec). Lazily built on first access; invalidated by\n * `load()`. */\n get tool(): Tool | undefined {\n if (this.catalog.size === 0) return undefined\n return (this.#tool ??= this.#buildTool())\n }\n\n #buildTool(): SkillTool {\n const names = [...this.catalog.keys()]\n // oxlint-disable-next-line sort-keys -- semantic field order: name, desc, params, call\n return defineTool({\n name: \"skill\",\n desc: this.#buildCatalogDesc(),\n parallel: true,\n params: Type.Object({\n name: Type.Union(\n names.map((n) => Type.Literal(n)),\n {\n description:\n \"Name of the skill to activate. The full SKILL.md \" +\n \"instructions are loaded as the tool result; bundled \" +\n \"files in the skill's directory are listed but not read \" +\n \"— fetch them via the `read` tool when the skill's \" +\n \"instructions require them.\",\n }\n ),\n }),\n call: (args, ctx: ToolContext<SkillMeta>) => this.#call(args.name as string, ctx),\n })\n }\n\n async #call(requested: string, ctx: ToolContext<SkillMeta>): Promise<(MetaPart | TextPart)[]> {\n let skill = this.catalog.get(requested)\n if (!skill) {\n const available = [...this.catalog.keys()]\n throw new AiError({\n code: \"UNKNOWN_SKILL\",\n data: { available, name: requested },\n message: `no skill named \"${requested}\". Available: ${available.join(\", \")}`,\n })\n }\n\n // Refresh the skill entry so we have an up-to-date mtime for staleness checks in `isActivated`.\n skill = await this.#update(skill)\n\n ctx.meta = { desc: skill.desc, mtime: skill.mtime, name: skill.name, path: skill.path }\n const activated = await this.isActivated(skill, ctx)\n if (activated) {\n // Already activated and fresh — no need to reload or update the tool result.\n ctx.meta.unchanged = true\n return [\n {\n content: `skill \"${skill.name}\" unchanged since last read: ${skill.path}`,\n tag: \"unchanged\",\n type: \"meta\",\n },\n ]\n }\n\n const references = await listReferences(skill.dir)\n return [\n {\n data: { dir: skill.dir, name: skill.name, references },\n tag: \"skill\",\n type: \"meta\",\n },\n { text: skill.body, type: \"text\" },\n ]\n }\n\n async isActivated(skill: SkillEntry, ctx: ToolContext<SkillMeta>): Promise<boolean> {\n const messages = ctx.messages ?? []\n for (const { m, $p, p } of extractToolResults<SkillMeta, \"skill\">(messages, [\"skill\"])) {\n const id = m.id\n if (!id || !p.meta || ctx.isMasked?.(id, $p)) continue\n if (p.meta.unchanged) continue\n if (p.meta.name === skill.name) return p.meta.mtime === skill.mtime\n }\n return false\n }\n\n async activate(name: string, agent: Agent) {\n const ret = await agent.useTool<SkillTool>(\n \"skill\",\n { name },\n `Skill \"${name}\" was activated by the user.`\n )\n if (ret.result.meta?.unchanged) return\n return ret\n }\n\n #buildCatalogDesc(): string {\n const header =\n \"Activate one of the available skills below. The skill's full \" +\n \"SKILL.md instructions are loaded as the tool result; the model \" +\n \"should follow them directly. Bundled files are listed in the \" +\n \"result but not eagerly read — fetch the ones the skill's \" +\n \"instructions reference via the `read` tool.\"\n const lines = [...this.catalog.values()].map((s) => `- ${s.name}: ${s.desc}`)\n return `${header}\\n\\nAvailable skills:\\n${lines.join(\"\\n\")}`\n }\n}\n\n// ── Discovery ──────────────────────────────────────────────────────────\n\nasync function readSkill(\n path: string\n): Promise<{ meta: { name?: string; description?: string }; body: string; mtime: number }> {\n const s = await safeStatAsync(path)\n if (!s?.isFile()) throw new Error(`Skill file not found at ${path}`)\n const raw = await readFile(path, \"utf8\")\n const { parseFrontmatter } = await import(\"@zaly/shared/yaml\")\n const { fm, body } = await parseFrontmatter(raw)\n return { body, meta: fm, mtime: s.mtimeMs }\n}\n\nasync function listReferences(dir: string): Promise<string[]> {\n const out: string[] = []\n for await (const rel of glob(\"**\", { cwd: dir, depth: 4, type: \"file\" })) {\n if (rel === \"SKILL.md\" || rel.endsWith(\"/SKILL.md\")) continue\n out.push(rel)\n if (out.length >= 200) break\n }\n return out.toSorted()\n}\n","import type { AnyPart, Message } from \"@zaly/ai\"\nimport type { BashTool } from \"../tools/bash.ts\"\nimport type { EditToolMeta } from \"../tools/edit.ts\"\nimport type { ReadToolMeta } from \"../tools/read.ts\"\nimport type { WriteToolMeta } from \"../tools/write.ts\"\n\nimport {\n attachmentToMeta,\n ContentTransform,\n errorToMeta,\n extractToolCalls,\n extractToolResults,\n metaToText,\n safeParseToolParams,\n sanitizeText,\n stringifyContent,\n toXml,\n} from \"@zaly/ai\"\nimport { safeStringify, formatDuration } from \"@zaly/shared\"\nimport { parseBash } from \"../utils/bash/parser.ts\"\nimport { TOOLS } from \"../utils/bash/tools.ts\"\n\nexport type ToolStat = {\n count: number\n score: number\n /** Turns ago at the most recent occurrence (0 = current/last turn).\n * Use with `lastTs` to give the agent both an \"in-experience\" recency\n * signal and a wall-clock staleness signal. */\n lastTurn: number\n /** Wall-clock ms timestamp of the most recent occurrence. `0` if no\n * occurrence carried a timestamp. */\n lastTs: number\n}\n\n/** Per-file activity tally produced by `extractFiles`. Each entry is a\n * path that the agent touched, with per-kind counts and a frecency\n * `score` that downweights older touches and weights writes/edits\n * more than reads. Sort the top-N by `score` to surface the active\n * working set; `reads` / `writes` / `edits` give the per-kind detail\n * for display. */\nexport type FileUsage = ToolStat & {\n path: string\n reads: number\n writes: number\n edits: number\n}\n\n/** Per-command activity tally produced by `extractBashCommands`. `count`\n * is raw invocations; `score` is the same number but exp-decay-weighted\n * by turn distance from the end of the conversation, so recently-used\n * commands rank above old hot ones. */\nexport type BashUsage = ToolStat & {\n command: string\n}\n\n// ── Frecency tuning ───────────────────────────────────────────────────\n// Half-life measured in user turns, not wall time — what matters for\n// compaction context is what's been hot in the agent's *recent\n// experience*, regardless of how long the user spent between turns.\n// 60 turns is a middle ground: actively-iterated work stays at the top\n// while recurring workflow patterns (git stash, test-runner flags) still\n// clear the minScore filter instead of getting buried under one-shot\n// noise from earlier in the session.\nconst HALF_LIFE_TURN = 60\nconst LAMBDA = Math.LN2 / HALF_LIFE_TURN\n// Per-kind weights — writes are the strongest intent signal (full-file\n// authorship), edits the iteration signal, reads the informational one.\nconst KIND_WEIGHTS = { edit: 2, read: 1, write: 3 } as const\n\nexport type ToolStatOptions = {\n minCount?: number\n minScore?: number\n limit?: number\n sort?: \"score\" | \"count\" | \"key\"\n}\n\nconst sorters = {\n count: (a: [string, ToolStat], b: [string, ToolStat]) => b[1].count - a[1].count,\n key: (a: [string, ToolStat], b: [string, ToolStat]) => a[0].localeCompare(b[0]),\n score: (a: [string, ToolStat], b: [string, ToolStat]) => b[1].score - a[1].score,\n} as const satisfies Record<string, (a: [string, ToolStat], b: [string, ToolStat]) => number>\n\nfunction turnInfo(messages: readonly Message[]) {\n const weights: number[] = []\n const turns: number[] = []\n let turn = 0\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i]\n if (m.role === \"assistant\") turn++\n weights[i] = Math.exp(-LAMBDA * turn)\n turns[i] = turn\n }\n return { turns, weights }\n}\n\nfunction toolStats<T extends ToolStat = ToolStat>(\n map: Map<string, T>,\n opts: ToolStatOptions = {}\n): T[] {\n const limit = opts.limit ?? 50\n const sorter = sorters[opts.sort ?? \"score\"]\n const sorted = [...map.entries()].toSorted(sorter).map(([, stat]) => stat)\n return sorted\n .filter((stat) => stat.count >= (opts.minCount ?? 1))\n .filter((stat) => stat.score >= (opts.minScore ?? 0))\n .slice(0, limit)\n}\n\n/** Walk assistant tool-calls for `read` / `write` / `edit` and tally\n * per-path activity with frecency-weighted scoring. Returns the top-N\n * by score. Each entry carries the per-kind breakdown so the\n * summarizer can describe the *kind* of activity (\"heavily edited\",\n * \"read once, then written\", \"iteratively refined\").\n *\n * Paths are canonicalized via the cwd recorded on each call's session\n * node — relative paths are resolved against the cwd that was active\n * when the call ran, and `~` is expanded. Calls under different cwds\n * that target the same file thus collapse into one bucket. */\nexport function extractFileUsage(\n messages: readonly Message[],\n opts: ToolStatOptions = {}\n): FileUsage[] {\n opts = { minScore: 0.5, ...opts }\n const map = new Map<string, FileUsage>()\n const { turns, weights } = turnInfo(messages)\n\n for (const { m, p, $m: idx } of extractToolResults<EditToolMeta | ReadToolMeta | WriteToolMeta>(\n messages,\n [\"read\", \"write\", \"edit\"]\n )) {\n const path = p.meta?.path\n if (!path) continue\n const entry = map.get(path) ?? {\n count: 0,\n edits: 0,\n lastTs: 0,\n lastTurn: Infinity,\n path,\n reads: 0,\n score: 0,\n writes: 0,\n }\n if (p.name === \"read\") entry.reads++\n else if (p.name === \"write\") entry.writes++\n else entry.edits++\n entry.count++\n entry.score += weights[idx] * KIND_WEIGHTS[p.name as keyof typeof KIND_WEIGHTS]\n if (turns[idx] < entry.lastTurn) entry.lastTurn = turns[idx]\n if (m.ts && m.ts > entry.lastTs) entry.lastTs = m.ts\n map.set(path, entry)\n }\n return toolStats(map, opts)\n}\n\n/** Walk assistant tool-calls for `bash`, parse each command line, and\n * tally per-command frecency. Plumbing commands (cat, head, grep, awk,\n * sed, …) are filtered out — they dominate raw counts but carry no\n * operational signal a summarizer would describe. Returns the top-N\n * by frecency `score`. */\nexport function extractBashUsage(\n messages: readonly Message[],\n opts: ToolStatOptions = {}\n): BashUsage[] {\n opts = { minCount: 2, minScore: 0.5, ...opts } // bash commands are noisier, so default to minCount=2\n const { turns, weights } = turnInfo(messages)\n const map = new Map<string, BashUsage>()\n for (const { m, p, $m: idx } of extractToolCalls(messages, [\"bash\"])) {\n const params = safeParseToolParams<BashTool>(p.params)\n const cmd = params?.command\n if (!cmd) continue\n const result = parseBash(cmd)\n if (!result.ok) continue\n const w = weights[idx] ?? 0\n const t = turns[idx] ?? Infinity\n for (const seg of result.segments) {\n if (TOOLS[seg.cmd]) continue\n const key = `${seg.cmd} ${seg.args.join(\" \")}`\n if (key.includes(\"\\n\")) continue\n const entry = map.get(key) ?? {\n command: key,\n count: 0,\n lastTs: 0,\n lastTurn: Infinity,\n score: 0,\n }\n entry.count++\n entry.score += w\n if (t < entry.lastTurn) entry.lastTurn = t\n if (m.ts && m.ts > entry.lastTs) entry.lastTs = m.ts\n map.set(key, entry)\n }\n }\n return toolStats(map, opts)\n}\n\n// ── Transcript ────────────────────────────────────────────────────────\n\nfunction truncate(text: string, len: number): string {\n return text.length <= len ? text : `${text.slice(0, len)}…`\n}\n\n/** Flatten a list of messages into a single tagged transcript. */\nexport function extractConversation(\n messages: readonly Message[],\n opts: { maxToolResultLen?: number } = {}\n): string {\n const transform = ContentTransform.create<AnyPart>()\n .drop(\"reasoning\")\n .map(\"tool-call\", (part) => ({\n content: [\n {\n text: `${part.name}(${safeStringify(part.params)})`,\n type: \"text\" as const,\n },\n ],\n tag: \"tool-call\",\n type: \"meta\",\n }))\n .map(\"tool-result\", (part) => {\n const text = truncate(stringifyContent(part.content), opts.maxToolResultLen ?? 2000)\n return {\n content: text === \"\" ? undefined : [{ text, type: \"text\" as const }],\n data: { tool: part.name, ...(part.isError ? { error: true } : {}) },\n tag: \"tool-result\",\n type: \"meta\" as const,\n }\n })\n .pipe(attachmentToMeta(\"image\", \"pdf\", \"audio\", \"video\"))\n .pipe(errorToMeta())\n .pipe(metaToText())\n .pipe(sanitizeText())\n\n const blocks: string[] = []\n let role: string | undefined = undefined\n for (const m of messages) {\n const parts =\n typeof m.content === \"string\" ? [{ text: m.content, type: \"text\" as const }] : m.content\n const transformed = transform.runSync(parts)\n const text = stringifyContent(transformed).trim()\n if (!text) continue\n let currentRole = m.role.charAt(0).toUpperCase() + m.role.slice(1) // capitalize\n currentRole = currentRole === \"Tool\" ? \"Assistant\" : currentRole // re-label \"Tool\" as \"Assistant\" for summarization purposes\n blocks.push(role === currentRole ? text : `\\n[${currentRole}]: ${text}`)\n role = currentRole\n }\n const text = blocks.join(\"\\n\").replace(/^\\s+$/gm, \"\").trim()\n return toXml(text, \"conversation\", { indent: false })\n}\n\n// ── Tail selection ────────────────────────────────────────────────────\n\nexport function messageTail(\n messages: readonly Message[],\n opts: { keepTokens?: number }\n): Message[] {\n const maxTokens = opts.keepTokens ?? 20_000\n messages = messages.toReversed()\n const tail: Message[] = []\n const queue: Message[] = []\n\n let used = 0\n let last: number | undefined = undefined\n\n for (const m of messages) {\n queue.unshift(m)\n const usage = m.role === \"assistant\" ? m.meta?.usage : undefined\n if (!usage) continue\n const current = usage.input + usage.output + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0)\n // clamp for masker and similar events that might shrink the context size\n const delta = Math.max(0, (last ?? current) - current)\n if (used + delta > maxTokens) break\n used += delta\n last = current\n tail.unshift(...queue.splice(0))\n }\n return tail\n}\n\n// -- Formatting helpers -────────────────────────────────────────────────────────\n\nconst lastCol = (lastTurn: number, lastTs: number): string => {\n const turn = lastTurn === Infinity ? \"?\" : `${lastTurn}t`\n const wall = lastTs > 0 ? formatDuration(lastTs) : \"?\"\n return `${turn} / ${wall}`\n}\n\nexport function formatBashUsage(commands: BashUsage[]): string {\n if (commands.length === 0) return \"(no bash commands found)\"\n const lines: string[] = []\n lines.push(\"=== Top bash commands (sorted by frecency) ===\")\n lines.push(` ${\"score\".padStart(7)} ${\"count\".padStart(5)} ${\"last\".padEnd(14)} command`)\n for (const c of commands) {\n lines.push(\n ` ${c.score.toFixed(2).padStart(7)} ${String(c.count).padStart(5)} ${lastCol(c.lastTurn, c.lastTs).padEnd(14)} ${c.command}`\n )\n }\n const text = lines.join(\"\\n\")\n return toXml(text, \"bash-commands\", { indent: false })\n}\n\nexport function formatFileUsage(files: FileUsage[]): string {\n if (files.length === 0) return \"(no file ops found)\"\n const lines: string[] = []\n lines.push(\"=== Top files touched (sorted by frecency) ===\")\n lines.push(\n ` ${\"score\".padStart(7)} ${\"total\".padStart(5)} r/w/e ${\"last\".padEnd(14)} path`\n )\n for (const f of files) {\n const rwe = `${f.reads}/${f.writes}/${f.edits}`.padEnd(12)\n lines.push(\n ` ${f.score.toFixed(2).padStart(7)} ${String(f.count).padStart(5)} ${rwe} ${lastCol(f.lastTurn, f.lastTs).padEnd(14)} ${f.path}`\n )\n }\n const text = lines.join(\"\\n\")\n return toXml(text, \"files\", { indent: false })\n}\n","import type { AnyContent, AnyPart, AnyType, Attachment, Message, Tool } from \"@zaly/ai\"\nimport type { Prompt } from \"../prompt/registry.ts\"\n\nimport { stringifyContent } from \"@zaly/ai\"\n\nexport type TokenCount = {\n type: AnyType | Message[\"role\"] | \"prompt\" | \"tool-schema\" | \"system-prompt\"\n kind?: string\n tokens: number\n children?: TokenCount[]\n}\n\nexport type TokenStats = {\n key: string\n tokens: number\n count: number\n children?: Map<string, TokenStats>\n}\n\n// ── token estimation ───────────────────────────────────────────────────\n\nconst CHARS_PER_TOKEN = 4\n\nconst ATTACHMENT_TOKENS: Record<Attachment[\"type\"], number> = {\n audio: 3000,\n image: 1500,\n pdf: 8000,\n video: 5000,\n}\n\nfunction fromText(text: string): number {\n return Math.ceil(text.length / CHARS_PER_TOKEN)\n}\n\nfunction sumTokens(stats: TokenCount[]): number {\n return stats.reduce((sum, s) => sum + s.tokens, 0)\n}\n\nexport function estimatePart(p: AnyPart): TokenCount {\n switch (p.type) {\n case \"reasoning\":\n case \"text\": {\n return { tokens: fromText(p.text), type: p.type }\n }\n case \"tool-call\": {\n return {\n kind: p.name,\n tokens: fromText(p.name) + fromText(JSON.stringify(p.params ?? {})),\n type: p.type,\n }\n }\n case \"tool-result\": {\n const children = estimateContent(p.content)\n return {\n children,\n kind: p.name,\n tokens: fromText(p.name) + sumTokens(children),\n type: p.type,\n }\n }\n case \"image\":\n case \"pdf\":\n case \"audio\":\n case \"video\": {\n return { tokens: ATTACHMENT_TOKENS[p.type], type: p.type }\n }\n case \"meta\": {\n const children = p.content ? estimateContent(p.content) : undefined\n return {\n children,\n kind: p.tag,\n tokens: fromText(stringifyContent(p)),\n type: p.type,\n }\n }\n case \"error\": {\n return { tokens: fromText(stringifyContent(p)), type: p.type }\n }\n default: {\n // @ts-expect-error: exhaustive check\n throw new Error(`Unknown part type: ${p.type}`)\n }\n }\n}\n\nfunction estimateContent(content: AnyContent): TokenCount[] {\n if (typeof content === \"string\") return [{ tokens: fromText(content), type: \"text\" }]\n let tokens = 0\n const children: TokenCount[] = []\n for (const p of content) {\n const partStats = estimatePart(p)\n tokens += partStats.tokens\n children.push(partStats)\n }\n return children\n}\n\nfunction estimateMessage(m: Message): TokenCount {\n const type = m.role\n const children = estimateContent(m.content)\n const kind = m.role === \"system\" ? m.meta?.kind : undefined\n return {\n children,\n kind,\n tokens: sumTokens(children),\n type,\n }\n}\n\nfunction estimatePrompt(prompt: (string | Prompt<string>)[], tools?: Tool[]): TokenCount {\n const children: TokenCount[] = prompt.map((p) => ({\n kind: typeof p === \"string\" ? undefined : p.name,\n tokens: fromText(typeof p === \"string\" ? p : p.text),\n type: \"prompt\" as const,\n }))\n children.push(\n ...(tools?.map((t) => ({\n kind: t.name,\n tokens: fromText(t.name) + fromText(JSON.stringify(t.params ?? {})),\n type: \"tool-schema\" as const,\n })) ?? [])\n )\n return {\n children,\n tokens: sumTokens(children),\n type: \"system-prompt\" as const,\n }\n}\n\nfunction addCount(stat: TokenCount, parent: TokenStats, expand?: (c: TokenCount) => boolean): void {\n const keys = stat.kind ? [stat.type, stat.kind] : [stat.type]\n let child: TokenStats | undefined\n\n for (const key of keys) {\n parent.children ??= new Map()\n child = parent.children.get(key)\n if (!child) {\n child = { children: new Map(), count: 0, key, tokens: 0 }\n parent.children.set(key, child)\n }\n child.tokens += stat.tokens\n child.count++\n parent = child\n }\n\n if (stat.children && child && (!expand || expand(stat))) {\n for (const c of stat.children) addCount(c, child, expand)\n }\n}\n\nexport function tokenStats(\n msgs: readonly Message[],\n opts: {\n prompt?: (string | Prompt<string>)[]\n tools?: Tool[]\n expand?: (c: TokenCount) => boolean\n } = {}\n): TokenStats {\n const root: TokenStats = { children: new Map(), count: 0, key: \"TOTAL\", tokens: 0 }\n const counts: TokenCount[] = []\n if (opts.prompt) counts.push(estimatePrompt(opts.prompt, opts.tools))\n counts.push(...msgs.map(estimateMessage))\n for (const stats of counts) {\n root.tokens += stats.tokens\n root.count++\n addCount(stats, root, opts.expand)\n }\n return root\n}\n\n// ── stats ──────────────────────────────────────────────────────────────\n\nfunction fmtStats(s: TokenStats, indent = 0): string {\n const header = \" \".repeat(indent) + s.key\n return `${header.padEnd(28)} ${fmt(s.count).padStart(6)}x ${fmt(s.tokens).padStart(14)}`\n}\n\nexport function formatTokenStats(s: TokenStats, indent = 0): string {\n const ret: string[] = []\n const children = s.children\n ? [...s.children.values()].toSorted((a, b) => b.tokens - a.tokens)\n : []\n for (const c of children) {\n ret.push(fmtStats(c, indent))\n if (c.children?.size) ret.push(formatTokenStats(c, indent + 1))\n if (indent === 0) ret.push(\"─\".repeat(51))\n }\n if (indent === 0) {\n ret.unshift(\"─\".repeat(51))\n ret.push(fmtStats(s, indent))\n ret.push(\"─\".repeat(51))\n }\n return ret.join(\"\\n\")\n}\n\nfunction fmt(n: number): string {\n return n.toLocaleString(\"en-US\").replace(/,/g, \"_\")\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+BA,IAAa,eAAb,cAAkC,QAA4B;CAC5D;CACA;CACA;CACA;CACA;CACA;CACA,SAAS,IAAI,UAAiB;CAC9B;CACA;CACA;CAEA,YAAY,MAA2B;EACrC,MAAM;EACN,KAAK,QAAQ;EACb,KAAK,OAAO,SAAS,KAAK,GAAG;EAC7B,KAAK,aAAa,KAAK,SAAS,WAAW,UAAU;EACrD,KAAK,WAAW,KAAK;EACrB,KAAK,SAAS,KAAK;EACnB,KAAK,UAAU,KAAK;EACpB,KAAK,UAAU,KAAK,UAAU,CAAC;EAE/B,KAAK,SAAS,KAAK,SAAS,CAAC;EAC7B,KAAK,eAAe,UAAU,KAAK,MAAM,QAAQ,MAAM,SAAS,CAAC,CAAC,MAAM,KAAK;EAE7E,KAAK,GAAG,SAAS,OAAO,EAAE,YAAY;GACpC,IAAI,CAAC,KAAK,SAAS,SAAS;GAC5B,IAAI,OAAO,MAAM,KAAK,QAAQ,OAAO,EAAE,SAAS,MAAM,GAAG,CAAC;EAC5D,CAAC,CAAC,CACC,GAAG,aAAa,OAAO,EAAE,aAAa;GACrC,IAAI,CAAC,KAAK,SAAS,SAAS;GAC5B,MAAM,KAAK,QAAQ,OAAO,EAAE,WAAW,OAAO,CAAC;EACjD,CAAC,CAAC,CACD,GAAG,QAAQ,EAAE,UAAU;GACtB,IAAI,CAAC,KAAK,SAAS,SAAS;GAC5B,KAAK,OAAO,OAAO,aAAa;GAChC,KAAU,QAAQ,OAAO,EAAE,IAAI,CAAC;EAClC,CAAC;CACL;CAEA,MAAc,QAAQ;EACpB,MAAM,CAAC,SAAS,YAAY,MAA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AIA,SAAS,SAAS,GAAe,SAAS,GAAW;CAEnD,OAAO,IADQ,KAAK,OAAO,MAAM,IAAI,EAAE,IAAA,CACtB,OAAO,EAAE,EAAE,GAAG,IAAI,EAAE,KAAK,CAAC,CAAC,SAAS,CAAC,EAAE,IAAI,IAAI,EAAE,MAAM,CAAC,CAAC,SAAS,EAAE;AACvF;AAEA,SAAgB,iBAAiB,GAAe,SAAS,GAAW;CAClE,MAAM,MAAgB,CAAC;CACvB,MAAM,WAAW,EAAE,WACf,CAAC,GAAG,EAAE,SAAS,OAAO,CAAC,CAAC,CAAC,UAAU,GAAG,MAAM,EAAE,SAAS,EAAE,MAAM,IAC/D,CAAC;CACL,KAAK,MAAM,KAAK,UAAU;EACxB,IAAI,KAAK,SAAS,GAAG,MAAM,CAAC;EAC5B,IAAI,EAAE,UAAU,MAAM,IAAI,KAAK,iBAAiB,GAAG,SAAS,CAAC,CAAC;EAC9D,IAAI,WAAW,GAAG,IAAI,KAAK,IAAI,OAAO,EAAE,CAAC;CAC3C;CACA,IAAI,WAAW,GAAG;EAChB,IAAI,QAAQ,IAAI,OAAO,EAAE,CAAC;EAC1B,IAAI,KAAK,SAAS,GAAG,MAAM,CAAC;EAC5B,IAAI,KAAK,IAAI,OAAO,EAAE,CAAC;CACzB;CACA,OAAO,IAAI,KAAK,IAAI;AACtB;AAEA,SAAS,IAAI,GAAmB;CAC9B,OAAO,EAAE,eAAe,OAAO,CAAC,CAAC,QAAQ,MAAM,GAAG;AACpD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"read-Djsx2NZl.mjs","names":[],"sources":["../src/tools/read.ts"],"sourcesContent":["import type { Content, ToolContext } from \"@zaly/ai\"\n\nimport { AiError, defineTool, extractToolResults, toAttachment } from \"@zaly/ai\"\nimport { normPath, safeStat } from \"@zaly/shared\"\nimport { fileDetect } from \"@zaly/shared/detect\"\nimport { normalizeEol } from \"@zaly/shared/text\"\nimport { stat } from \"node:fs/promises\"\nimport { Type } from \"typebox\"\n\n/**\n * Read a file from disk.\n *\n * Output shape:\n * - Text files → numbered lines, `cat -n` style (6-char padded number,\n * tab, content). Line numbers reflect the absolute line in the file\n * even when reading a slice via `offset`/`limit`.\n * - Image files (png, jpeg, webp, gif, avif, …) → `ImagePart` attachment.\n * The model sees the image natively if its modality supports it.\n * - Other binary files → `BINARY_FILE` error with a hint.\n *\n * Path resolution: relative paths resolve against the agent's session\n * cwd via `process.cwd()` for now. When the permission system gates this\n * via a tool-side hook, the cwd from `PermissionContext` will be used\n * instead so resolution stays consistent across the loop.\n */\nconst DEFAULT_LIMIT = 2000\nconst MAX_LINE_LENGTH = 2000\n\nexport type ReadTool = typeof readTool\n\nexport type FileMeta = {\n path: string\n mtime: number\n kind: \"read\" | \"write\" | \"edit\"\n /** True when the result reflects the whole-file content — set by\n * un-sliced `read` and by `write` (which always replaces the\n * full file). Used by the masker to know whether this result\n * subsumes earlier reads of the same path. `edit` never sets it\n * because the result is patch-relative. */\n full?: boolean\n unchanged?: boolean\n}\n\nfunction isFileMeta(meta: unknown): meta is FileMeta {\n const m = meta as Partial<Record<string, unknown>> | undefined | null\n return (\n m !== undefined &&\n m !== null &&\n typeof m === \"object\" &&\n typeof m.path === \"string\" &&\n typeof m.mtime === \"number\" &&\n (m.kind === \"read\" || m.kind === \"write\" || m.kind === \"edit\")\n )\n}\n\nexport type ReadToolMeta = FileMeta & {\n offset: number\n limit: number\n}\n\n/** Build the `read` tool with model-aware schema description. The\n * attachment-shape blurb is included only when the loaded model\n * actually accepts the relevant modality — text-only models see a\n * description that promises only text output, so they don't reach\n * for the tool expecting images they can't process. */\n// oxlint-disable-next-line sort-keys -- semantic field order: name, desc, params, call\nexport const readTool = defineTool({\n name: \"read\",\n desc: `Read a file. Text files return numbered lines (\\`cat -n\\` style). Image & PDF files are sent as attachments. Use \\`offset\\`/\\`limit\\` to slice large files.`,\n parallel: true,\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 offset: Type.Optional(\n Type.Integer({\n default: 1,\n description:\n \"1-based line number to start at. Negative values count from \" +\n \"the end: -50 starts 50 lines before EOF (so `offset: -50` \" +\n \"with the default limit returns the last 50 lines, like \" +\n \"`tail -n 50`). `offset: -50, limit: 20` reads 20 lines \" +\n \"starting 50 from the end.\",\n })\n ),\n limit: Type.Optional(\n Type.Integer({\n default: DEFAULT_LIMIT,\n description: \"Maximum number of lines to return.\",\n minimum: 1,\n })\n ),\n }),\n\n async preflight(args, ctx: ToolContext<ReadToolMeta>) {\n const path = normPath(ctx.cwd, args.path)\n await ctx.need?.(\"read\", path)\n },\n\n async call(args, ctx: ToolContext<ReadToolMeta>): Promise<Content> {\n const path = normPath(ctx.cwd, args.path)\n\n const fileStat = await stat(path).catch((error: unknown) => {\n throw new AiError({\n cause: error,\n code: \"NOT_FOUND\",\n message: `cannot read ${path}: file not found`,\n })\n })\n if (!fileStat.isFile()) {\n throw new AiError({ code: \"NOT_A_FILE\", message: `${path} is not a regular file` })\n }\n\n if (isUnchanged(path, ctx)) {\n // Fresh! We've seen this file's current bytes, so we can skip\n // returning the content again.\n ctx.meta = {\n full: false,\n kind: \"read\",\n limit: 0,\n mtime: fileStat.mtimeMs,\n offset: 0,\n path,\n unchanged: true,\n }\n return [\n { content: `file unchanged since last read: ${path}`, tag: \"unchanged\", type: \"meta\" },\n ]\n }\n\n const file = await fileDetect(path)\n if (!file) {\n throw new AiError({\n code: \"READ_ERROR\",\n message: `${path}: could not read file`,\n })\n }\n\n // Threshold-based binary check — files with sporadic control bytes\n // (logs with ANSI styling, source with form feeds) still read as\n // text; only when binary content dominates the sample do we bail.\n if (file.type === \"binary\") {\n throw new AiError({\n code: \"BINARY_FILE\",\n data: { bytes: file.data.length, path },\n message: `${path}: binary file (${file.data.length} bytes); not displayable as text`,\n })\n }\n\n const att = await toAttachment(file)\n if (att) return [att]\n\n if (file.type !== \"text\") {\n throw new AiError({\n code: \"UNSUPPORTED_FILE\",\n data: { path, type: file.type },\n message: `${path}: unsupported file type ${file.type}`,\n })\n }\n\n const text = new TextDecoder().decode(file.data)\n const slice = formatTextSlice(text, {\n limit: args.limit ?? DEFAULT_LIMIT,\n offset: args.offset ?? 1,\n })\n\n // Record the read so the freshness tracker knows we've seen this\n // file's current bytes. write/edit consult this before mutating;\n // the masker uses `full` to know whether this read subsumes\n // earlier reads of the same path.\n ctx.meta = {\n full: slice.full,\n kind: \"read\",\n limit: slice.limit,\n mtime: fileStat.mtimeMs,\n offset: slice.offset,\n path,\n }\n\n return slice.content\n },\n})\n\nexport function assertFresh(path: string, ctx: ToolContext) {\n const err = checkFresh(path, ctx)\n if (err !== true) throw err\n}\n\nexport function isUnchanged(path: string, ctx: ToolContext) {\n return checkFresh(path, ctx, { full: true }) === true\n}\n\nexport function checkFresh(\n path: string,\n ctx: ToolContext,\n opts: { full?: boolean } = {}\n): AiError | true {\n path = normPath(ctx.cwd, path)\n const mtime = safeStat(path)?.mtimeMs\n if (mtime === undefined)\n return new AiError({ code: \"NOT_FOUND\", message: `${path}: file not found` })\n const messages = ctx.messages ?? []\n let ret: AiError = freshnessError(path, \"NOT_READ\")\n\n for (const { m, $p, p } of extractToolResults<FileMeta>(messages)) {\n const id = m.id\n if (!id || !isFileMeta(p.meta) || ctx.isMasked?.(id, $p)) continue\n if (opts.full && !p.meta.full) continue\n if (p.meta.mtime === mtime) return true // Fresh! The file's mtime matches what we saw at read time.\n ret = freshnessError(path, \"STALE\")\n }\n return ret\n}\n\n/** Build the canonical \"you need to read this first\" error. Used by\n * `write` (existing files only) and `edit` (always). The `code` is\n * stable so the model can branch on it; the message tells the model\n * what to do next; `data.reason` distinguishes never-read vs\n * changed-since-read for downstream renderers. */\nexport function freshnessError(path: string, reason: \"NOT_READ\" | \"STALE\"): AiError {\n return new AiError({\n code: \"FILE_NOT_FRESH\",\n data: { path, reason },\n message:\n reason === \"NOT_READ\"\n ? `${path}: read this file before mutating it.`\n : `${path}: file changed since last read. Re-read before mutating.`,\n })\n}\n\n/** Format a slice of file content as numbered lines plus, when the\n * slice doesn't cover the whole file, a `<slice>` MetaPart with\n * \"showing X-Y of Z\" info is included, Full reads return a plain\n * string for the cleanest model surface. */\nfunction formatTextSlice(\n content: string,\n { offset, limit }: { offset: number; limit: number }\n): { content: Content; full?: boolean; offset: number; limit: number } {\n // Normalize line endings to LF for display. The model always sees LF;\n // edit/write detect the file's actual style and re-apply it on disk.\n content = normalizeEol(content)\n const lines = content.split(\"\\n\")\n // `split` on a final newline produces a trailing empty string — drop\n // it so a 3-line file with trailing LF reads as 3 lines, not 4.\n if (lines.at(-1) === \"\") lines.pop()\n\n // Negative offset = \"from the end\" — Python-slice / `tail -n` semantic.\n // `-1000` on a 30-line file clamps to 0 (read whole file) rather than\n // erroring; `0` is treated as `1` (head, off-by-one tolerance).\n let start = offset < 0 ? Math.max(0, lines.length + offset) : Math.max(0, offset - 1)\n // Overshoot clamps to `lines.length` so the slice loop emits nothing.\n // The agent gets an empty text + a `<slice>` meta that reports the\n // real file size, then can re-issue with a sensible offset.\n if (start >= lines.length) start = lines.length\n const end = Math.min(lines.length, start + limit)\n\n const out: string[] = []\n for (let i = start; i < end; i++) {\n const lineNo = (i + 1).toString().padStart(6, \" \")\n let line = lines[i]\n if (line.length > MAX_LINE_LENGTH) {\n line = `${line.slice(0, MAX_LINE_LENGTH)}… [line truncated, ${line.length} chars]`\n }\n out.push(`${lineNo}\\t${line}`)\n }\n\n const text = out.join(\"\\n\")\n const full = start === 0 && end === lines.length\n if (full) return { content: text, full, limit: lines.length, offset: 1 }\n\n // Empty slice (overshot offset): tell the agent the offset they asked\n // for and the real file size, rather than emitting a nonsensical\n // \"showing 6-5 of 5\"-style range.\n const sliceMsg =\n start === end\n ? `offset ${offset} past end of file (${lines.length} lines)`\n : `showing ${start + 1}-${end} of ${lines.length}`\n\n return {\n content: [\n { content: sliceMsg, tag: \"slice\", type: \"meta\" },\n { text, type: \"text\" },\n ],\n full,\n limit: end - start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