@zaly/agent 0.2.0 → 0.3.1
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-DlhEEMPU.mjs → agent-GXRF7DUP.mjs} +7 -11
- package/dist/agent-GXRF7DUP.mjs.map +1 -0
- package/dist/{bash-DSy03sAj.mjs → bash-CB_VXpyd.mjs} +2 -2
- package/dist/{bash-DSy03sAj.mjs.map → bash-CB_VXpyd.mjs.map} +1 -1
- package/dist/{compactions-BpvQk4CG.mjs → compactions-92bMlcxJ.mjs} +3 -3
- package/dist/{compactions-BpvQk4CG.mjs.map → compactions-92bMlcxJ.mjs.map} +1 -1
- package/dist/{edit-DT672zIy.mjs → edit-gkb6MCW-.mjs} +2 -2
- package/dist/{edit-DT672zIy.mjs.map → edit-gkb6MCW-.mjs.map} +1 -1
- package/dist/{fetch-BrtIqrid.mjs → fetch-D_GzL2yy.mjs} +4 -4
- package/dist/{fetch-BrtIqrid.mjs.map → fetch-D_GzL2yy.mjs.map} +1 -1
- package/dist/{find-B-vvdlHu.mjs → find-DlrYUTXT.mjs} +2 -2
- package/dist/{find-B-vvdlHu.mjs.map → find-DlrYUTXT.mjs.map} +1 -1
- package/dist/{grep-rvZ5S319.mjs → grep-BI8Rou2q.mjs} +2 -2
- package/dist/{grep-rvZ5S319.mjs.map → grep-BI8Rou2q.mjs.map} +1 -1
- package/dist/{html-VrAsoGBK.mjs → html-B-Lr-9W6.mjs} +9457 -4826
- package/dist/html-B-Lr-9W6.mjs.map +1 -0
- package/dist/{index-node-esm-BwaOzhXB.mjs → index-node-esm-75XSYyIw.mjs} +16 -13
- package/dist/index-node-esm-75XSYyIw.mjs.map +1 -0
- package/dist/index.d.mts +11 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{manager-1zEE5WiA.mjs → manager-CEociHy_.mjs} +2 -2
- package/dist/{manager-1zEE5WiA.mjs.map → manager-CEociHy_.mjs.map} +1 -1
- package/dist/{masker-B97uwYXG.mjs → masker-DWuL2Fjs.mjs} +16 -5
- package/dist/{masker-B97uwYXG.mjs.map → masker-DWuL2Fjs.mjs.map} +1 -1
- package/dist/{read-C5keKntU.mjs → read-DLtNq4XJ.mjs} +2 -2
- package/dist/{read-C5keKntU.mjs.map → read-DLtNq4XJ.mjs.map} +1 -1
- package/dist/{registry-CntkeXlo.mjs → registry-7mJQhyBA.mjs} +3 -3
- package/dist/{registry-CntkeXlo.mjs.map → registry-7mJQhyBA.mjs.map} +1 -1
- package/dist/{rolldown-runtime-DYf_mQCB.mjs → rolldown-runtime-BVN1G_yT.mjs} +4 -4
- package/dist/{session-CUE48QWX.mjs → session-C5ra-Hi1.mjs} +2 -2
- package/dist/{session-CUE48QWX.mjs.map → session-C5ra-Hi1.mjs.map} +1 -1
- package/dist/{session-DY9mF9Vb.d.mts → session-WtXqtAaq.d.mts} +2 -2
- package/dist/{session-DY9mF9Vb.d.mts.map → session-WtXqtAaq.d.mts.map} +1 -1
- package/dist/session.d.mts +1 -1
- package/dist/session.mjs +1 -1
- package/dist/{src-DJoqT9yP.mjs → src-Di-H3Oya.mjs} +71 -41
- package/dist/src-Di-H3Oya.mjs.map +1 -0
- package/dist/{subagent-D-TYaX38.mjs → subagent-BOK4GFd4.mjs} +3 -3
- package/dist/{subagent-D-TYaX38.mjs.map → subagent-BOK4GFd4.mjs.map} +1 -1
- package/dist/{tasks-Dgsiuh0Q.mjs → tasks-BUFqFoh6.mjs} +2 -2
- package/dist/{tasks-Dgsiuh0Q.mjs.map → tasks-BUFqFoh6.mjs.map} +1 -1
- package/dist/{tasks-D76WXWr2.mjs → tasks-CkDWJk_3.mjs} +4 -4
- package/dist/tasks-CkDWJk_3.mjs.map +1 -0
- package/dist/{tools-DmoUYORG.mjs → tools-Ca7VsMg3.mjs} +2 -2
- package/dist/{tools-DmoUYORG.mjs.map → tools-Ca7VsMg3.mjs.map} +1 -1
- package/dist/{write-BRQFfWAn.mjs → write-y93TC5ng.mjs} +2 -2
- package/dist/{write-BRQFfWAn.mjs.map → write-y93TC5ng.mjs.map} +1 -1
- package/package.json +11 -11
- package/dist/agent-DlhEEMPU.mjs.map +0 -1
- package/dist/html-VrAsoGBK.mjs.map +0 -1
- package/dist/index-node-esm-BwaOzhXB.mjs.map +0 -1
- package/dist/src-DJoqT9yP.mjs.map +0 -1
- package/dist/tasks-D76WXWr2.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-node-esm-BwaOzhXB.mjs","names":["error"],"sources":["../../../node_modules/.bun/jsonpath-plus@11.2.1/node_modules/jsonpath-plus/dist/index-node-esm.js"],"sourcesContent":["import vm from 'node: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 unicorn/no-top-level-side-effects -- Temporary? */\n/* eslint-disable no-bitwise -- Convenient */\n\n/**\n * @import {EvaluatedResult, UnknownResult} from './jsonpath.js';\n */\n\n/**\n * @typedef {any} AssignmentExpression\n */\n\n/**\n * @typedef {any} Substitution\n */\n\n/**\n * @typedef {any} AnyParameter\n */\n\n/**\n * @typedef {Record<string, Substitution>} Substitutions\n */\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__']);\n\n// Every function-constructor variant, along with the invocation helpers which\n// could otherwise reach them indirectly, e.g., `Function.call(0, 'code')()`,\n// plus whichever BLOCKED_PROTO_PROPERTIES names resolve to an own method on\n// Object.prototype (e.g. `__defineGetter__`) - an own-property access on a\n// shared prototype (`@.prototype.__defineGetter__`) bypasses the\n// inherited-only name check below, so those methods need blocking by value.\n/** @type {WeakSet<object>} */\nconst BLOCKED_FUNCTIONS = new WeakSet([Function,\n// eslint-disable-next-line no-empty-function -- Only need the constructor\nfunction* () {}.constructor,\n// eslint-disable-next-line no-empty-function -- Only need the constructor\nasync function () {}.constructor,\n// eslint-disable-next-line no-empty-function -- Only need the constructor\nasync function* () {}.constructor, Function.prototype.call, Function.prototype.apply, Function.prototype.bind, Reflect.apply, Reflect.construct, ...[...BLOCKED_PROTO_PROPERTIES].map(name => Reflect.get(Object.prototype, name)).filter(value => typeof value === 'function')]);\n\n/**\n * @param {UnknownResult} value\n * @returns {boolean}\n */\nconst isBlockedFunction = value => {\n return typeof value === 'function' && BLOCKED_FUNCTIONS.has(value);\n};\n\n/**\n * Guarded `obj[prop]`, applying the same restrictions as a MemberExpression.\n * @param {UnknownResult} obj\n * @param {string} prop\n * @returns {UnknownResult}\n */\nconst getSafeProperty = (obj, prop) => {\n if (obj === undefined || obj === null) {\n throw new TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);\n }\n if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {\n throw new TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);\n }\n const result = /** @type {Record<string, UnknownResult>} */obj[prop];\n if (isBlockedFunction(result)) {\n throw new TypeError('Function constructor is disabled');\n }\n return result;\n};\n\n/**\n * @typedef {Record<\n * string,\n * (a: AnyParameter, b: AnyParameter) => UnknownResult\n * >} OperatorTable\n */\n\n// eslint-disable-next-line @stylistic/max-len -- Long\nconst BINOPS = Object.assign(Object.create(null), /** @type {OperatorTable} */{\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 // 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 '**': (a, b) => a ** b()\n});\n\n/**\n * @typedef {{\n * [key: string]: (a: AnyParameter) => UnknownResult\n * }} UnaryOperatorTable\n */\n\n// eslint-disable-next-line @stylistic/max-len -- Long\nconst UNOPS = Object.assign(Object.create(null), /** @type {UnaryOperatorTable} */{\n '-': a => -(/** @type {EvaluatedResult} */a),\n '!': a => !a,\n '~': a => ~(/** @type {EvaluatedResult} */a),\n // eslint-disable-next-line no-implicit-coercion -- API\n '+': a => +(/** @type {EvaluatedResult} */a),\n typeof: a => typeof a,\n void: () => undefined\n});\nconst SafeEval = {\n /**\n * @param {jsep.Expression} ast\n * @param {Substitutions} subs\n * @returns {UnknownResult}\n */\n evalAst(ast, subs) {\n switch (ast.type) {\n case 'BinaryExpression':\n case 'LogicalExpression':\n return SafeEval.evalBinaryExpression(/** @type {jsep.BinaryExpression} */ast, subs);\n case 'Compound':\n return SafeEval.evalCompound(/** @type {jsep.Compound} */ast, subs);\n case 'ConditionalExpression':\n return SafeEval.evalConditionalExpression(/** @type {jsep.ConditionalExpression} */ast, subs);\n case 'Identifier':\n return SafeEval.evalIdentifier(/** @type {jsep.Identifier} */ast, subs);\n case 'Literal':\n return SafeEval.evalLiteral(/** @type {jsep.Literal} */ast);\n case 'MemberExpression':\n return SafeEval.evalMemberExpression(/** @type {jsep.MemberExpression} */ast, subs);\n case 'UnaryExpression':\n return SafeEval.evalUnaryExpression(/** @type {jsep.UnaryExpression} */ast, subs);\n case 'ArrayExpression':\n return SafeEval.evalArrayExpression(/** @type {jsep.ArrayExpression} */ast, subs);\n case 'CallExpression':\n return SafeEval.evalCallExpression(/** @type {jsep.CallExpression} */ast, subs);\n case 'AssignmentExpression':\n return SafeEval.evalAssignmentExpression(/** @type {AssignmentExpression} */ast, subs);\n default:\n throw new SyntaxError('Unexpected expression', {\n cause: ast\n });\n }\n },\n /**\n * @param {jsep.BinaryExpression} ast\n * @param {Substitutions} subs\n * @returns {UnknownResult}\n */\n evalBinaryExpression(ast, subs) {\n /* c8 ignore next 3 -- Defensive guard for malformed ASTs */\n if (!Object.hasOwn(BINOPS, ast.operator)) {\n throw new SyntaxError(`Unknown binary operator: ${ast.operator}`);\n }\n const result = BINOPS[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));\n return result;\n },\n /**\n * @param {jsep.Compound} ast\n * @param {Substitutions} subs\n * @returns {UnknownResult}\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(/** @type {jsep.Identifier} */\n ast.body[i].name) && Object.hasOwn(ast.body, i + 1) && ast.body[i + 1].type === 'AssignmentExpression') {\n // var x=2; is detected as\n // [{Identifier var}, {AssignmentExpression x=2}]\n i += 1;\n }\n const expr = ast.body[i];\n last = SafeEval.evalAst(expr, subs);\n }\n return last;\n },\n /**\n * @param {jsep.ConditionalExpression} ast\n * @param {Substitutions} subs\n * @returns {UnknownResult}\n */\n evalConditionalExpression(ast, subs) {\n return SafeEval.evalAst(ast.test, subs) ? SafeEval.evalAst(ast.consequent, subs) : SafeEval.evalAst(ast.alternate, subs);\n },\n /**\n * @param {jsep.Identifier} ast\n * @param {Substitutions} subs\n * @returns {UnknownResult}\n */\n evalIdentifier(ast, subs) {\n if (Object.hasOwn(subs, ast.name)) {\n return subs[ast.name];\n }\n throw new ReferenceError(`${ast.name} is not defined`);\n },\n /**\n * @param {jsep.Literal} ast\n * @returns {UnknownResult}\n */\n evalLiteral(ast) {\n return ast.value;\n },\n /**\n * @param {jsep.MemberExpression} ast\n * @param {Substitutions} subs\n * @returns {UnknownResult}\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, subs) // `object[property]`\n : ast.property.name // `object.property` property is Identifier\n );\n const obj = SafeEval.evalAst(ast.object, subs);\n const result = getSafeProperty(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 /**\n * @param {jsep.UnaryExpression} ast\n * @param {Substitutions} subs\n * @returns {UnknownResult}\n */\n evalUnaryExpression(ast, subs) {\n /* c8 ignore next 3 -- Defensive guard for malformed ASTs */\n if (!Object.hasOwn(UNOPS, ast.operator)) {\n throw new SyntaxError(`Unknown unary operator: ${ast.operator}`);\n }\n const operand = SafeEval.evalAst(ast.argument, subs);\n return UNOPS[ast.operator](operand);\n },\n /**\n * @param {jsep.ArrayExpression} ast\n * @param {Substitutions} subs\n * @returns {UnknownResult}\n */\n evalArrayExpression(ast, subs) {\n return ast.elements.map(el => SafeEval.evalAst(/** @type {jsep.Expression} */\n el, subs));\n },\n /**\n * @param {jsep.CallExpression} ast\n * @param {Substitutions} subs\n * @returns {UnknownResult}\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 if (isBlockedFunction(func) || args.some(arg => isBlockedFunction(arg))) {\n throw new Error('Function constructor is disabled');\n }\n return (/** @type {(...args: AnyParameter[]) => UnknownResult} */\n func)(...args);\n },\n /**\n * @param {AssignmentExpression} ast\n * @param {Substitutions} subs\n * @returns {UnknownResult}\n */\n evalAssignmentExpression(ast, subs) {\n if (ast.left.type !== 'Identifier') {\n throw new SyntaxError('Invalid left-hand side in assignment');\n }\n const id = /** @type {jsep.Identifier} */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 = /** @type {unknown} */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(/** @type {jsep.Expression} */this.ast, keyMap);\n }\n}\n\n/**\n * @param {unknown} val\n */\nconst toStringTag = val => {\n return Object.prototype.toString.call(val).slice(8, -1);\n};\n\n/* eslint-disable camelcase -- Convenient for escaping */\n/* eslint-disable class-methods-use-this -- Consistent monkey-patching */\n/* eslint-disable unicorn/prefer-private-class-fields -- Allow\n monkey-patching */\nconst scriptCache = new Map();\nconst pathCache = new Map();\n\n/**\n * @typedef {any} AnyInput\n */\n\n/**\n * @typedef {((...args: any[]) => any)} SandboxCallback\n */\n\n/**\n * @typedef {any|SandboxCallback} SandboxPropertyValue\n */\n\n/**\n * @typedef {(string|number)[]} ExpressionArray\n */\n\n/**\n * @typedef {\"scalar\"|\"boolean\"|\"string\"|\"undefined\"\n * |\"function\"|\"integer\"|\"number\"|\"nonFinite\"|\"object\"\n * |\"array\"|\"other\"|\"null\"|\"symbol\"|\"Promise\"|\"BigInt\"\n * |\"jsonReference\"} ValueType\n */\n\n/**\n * @typedef {unknown} ParentValue\n */\n\n/**\n * @typedef {unknown} UnknownResult\n */\n\n/**\n * @typedef {string|number|null} ParentProperty\n */\n\n/**\n * @typedef {ReturnObject|string|number|boolean|null|unknown[]\n * |Record<string, unknown>} PreferredOutput\n */\n\n/**\n * Copies array and then pushes item into it.\n * @param {ExpressionArray} arr Array to copy and into which to push\n * @param {string|number} item Array item to add (to end)\n * @returns {ExpressionArray} 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 {string|number} item Array item to add (to beginning)\n * @param {ExpressionArray} arr Array to copy and into which to unshift\n * @returns {ExpressionArray} 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 * @typedef {object} ReturnObject\n * @property {ExpressionArray|string} path\n * @property {unknown} value\n * @property {ParentValue} parent\n * @property {ParentProperty} parentProperty\n * @property {boolean} [isParentSelector]\n * @property {boolean} [hasArrExpr]\n * @property {ExpressionArray} [expr]\n * @property {string} [pointer]\n */\n\n/**\n * @callback JSONPathCallback\n * @param {any} preferredOutput Using `any` type instead of `PreferredOutput` so\n * that user can supply flexible type\n * @param {\"value\"|\"property\"} type\n * @param {ReturnObject} fullRetObj\n * @returns {void}\n */\n\n/**\n * @callback OtherTypeCallback\n * @param {unknown} val\n * @param {ExpressionArray} path\n * @param {ParentValue} parent\n * @param {string|number|null} parentPropName\n * @param {string} arg\n * @returns {boolean|null}\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 {new (expr: string) => {\n * runInNewContext: (context: object) => EvaluatedResult\n * }} ScriptConstructor\n */\n\n/**\n * @typedef {ScriptConstructor} EvalClass\n */\n\n/**\n * @typedef {\"value\"|\"path\"|\"pointer\"|\"parent\"|\"parentProperty\"\n * |\"all\"} ResultType\n */\n\n/**\n * @typedef {EvalCallback|EvalClass|'safe'|'native'|boolean} EvalValue\n */\n\n/**\n * @typedef {string|string[]} PathType\n */\n\n/**\n * @typedef {{Script: ScriptConstructor}} SafeScriptType\n */\n\n/**\n * @typedef {{Script: ScriptConstructor}} ScriptType\n */\n\n/**\n * @typedef {{\n * _$_path?: string,\n * _$_parentProperty?: ParentProperty,\n * _$_parent?: ParentValue,\n * _$_property?: string|number,\n * _$_root?: AnyInput,\n * _$_v?: unknown,\n * [key: string]: SandboxPropertyValue\n * }} SandboxType\n */\n\n/**\n * @typedef {object} JSONPathOptions\n * @property {AnyInput} [json]\n * @property {PathType} [path]\n * @property {ResultType} [resultType=\"value\"]\n * @property {boolean} [flatten=false]\n * @property {boolean} [wrap=true]\n * @property {SandboxType} [sandbox={}]\n * @property {EvalValue} [eval='safe']\n * @property {any|null} [parent=null]\n * @property {ParentProperty} [parentProperty=null]\n * @property {JSONPathCallback} [callback]\n * @property {OtherTypeCallback} [otherTypeCallback] Defaults to\n * function which throws on encountering `@other`\n * @property {Record<string, OtherTypeCallback>} [customTypes] Map of\n * custom type operator names to their evaluation callbacks\n * @property {boolean} [autostart=true]\n * @property {boolean} [ignoreEvalErrors=false]\n */\n\n/**\n * @overload\n * @param {string} opts JSON path to evaluate\n * @param {AnyInput} [expr] JSON object to evaluate against\n * @param {JSONPathCallback} [obj] Passed 3 arguments: 1) desired\n * payload per `resultType`, 2) `\"value\"|\"property\"`, 3) Full returned\n * object with all payloads\n * @param {OtherTypeCallback} [callback] If `@other()` is at the\n * end of one's query, this will be invoked with the value of the item,\n * its path, its parent, and its parent's property name, and it should\n * return a boolean indicating whether the supplied value belongs to the\n * \"other\" type or not (or it may handle transformations and return\n * `false`).\n * @param {undefined} [otherTypeCallback]\n * @returns {unknown} The string form always has `autostart` implicitly\n * `true`, so the result is the evaluated value, not a `JSONPathClass`\n */\n/**\n * @overload\n * @param {JSONPathOptions & {autostart: false}} opts An options object\n * with `autostart` explicitly set to `false` defers evaluation and\n * returns the `JSONPathClass` instance instead\n * @returns {JSONPathClass}\n */\n/**\n * @overload\n * @param {JSONPathOptions} opts If a string, will be treated as\n * `expr`\n * @returns {unknown}\n */\n/**\n * @param {JSONPathOptions|string} opts If a string, will be treated as `expr`\n * @param {string|AnyInput} [expr] JSON path to evaluate\n * @param {AnyInput|JSONPathCallback} [obj] JSON object to evaluate against\n * @param {JSONPathCallback|OtherTypeCallback} [callback] Passed 3\n * arguments: 1) desired payload per `resultType`,\n * 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 * @throws {Error}\n * @returns {unknown|JSONPathClass}\n */\nfunction JSONPath(opts, expr, obj, callback, otherTypeCallback) {\n try {\n if (opts && typeof opts === 'object') {\n return new JSONPathClass(opts);\n }\n return new JSONPathClass(opts, expr, /** @type {JSONPathCallback|undefined} */obj, /** @type {OtherTypeCallback|undefined} */callback, /** @type {undefined} */otherTypeCallback);\n } catch (e) {\n if (new.target) {\n throw e;\n }\n if (e && typeof e === 'object' && 'value' in e) {\n return /** @type {{value: UnknownResult}} */e.value;\n }\n throw e;\n }\n}\n\n/**\n *\n */\nclass JSONPathClass {\n /**\n * @overload\n * @param {string} opts JSON path to evaluate\n * @param {AnyInput} [expr] JSON object to evaluate against\n * @param {JSONPathCallback} [obj] Passed 3 arguments: 1) desired\n * payload per `resultType`, 2) `\"value\"|\"property\"`, 3) Full returned\n * object with all payloads\n * @param {OtherTypeCallback} [callback] If `@other()` is at the\n * end of one's query, this will be invoked with the value of the item,\n * its path, its parent, and its parent's property name, and it should\n * return a boolean indicating whether the supplied value belongs to the\n * \"other\" type or not (or it may handle transformations and return\n * `false`).\n * @param {undefined} [otherTypeCallback]\n */\n /**\n * @overload\n * @param {JSONPathOptions} opts If a string, will be treated as\n * `expr`\n */\n /**\n * @param {null|string|JSONPathOptions} opts If a string, will be treated as\n * `expr`\n * @param {string|AnyInput} [expr] JSON path to evaluate\n * @param {AnyInput|JSONPathCallback} [obj] JSON object to evaluate against\n * @param {JSONPathCallback|OtherTypeCallback} [callback] Passed 3\n * arguments: 1) desired payload per `resultType`,\n * 2) `\"value\"|\"property\"`, 3) Full returned\n * object with all payloads\n * @param {OtherTypeCallback} [otherTypeCallback] If `@other()` is at the\n * end of one's query, this will be invoked with the value of the item,\n * its path, its parent, and its parent's property name, and it should\n * return a boolean indicating whether the supplied value belongs to the\n * \"other\" type or not (or it may handle transformations and return\n * `false`).\n */\n constructor(opts, expr, obj, callback, otherTypeCallback) {\n if (typeof opts === 'string') {\n otherTypeCallback = /** @type {OtherTypeCallback} */\n callback;\n callback = /** @type {JSONPathCallback} */\n obj;\n obj = expr;\n expr = opts;\n opts = null;\n }\n const optObj = opts && typeof opts === 'object';\n opts ||= /** @type {JSONPathOptions} */{};\n /** @type {ResultType|undefined} */\n this.currResultType = undefined;\n\n /** @type {EvalValue|undefined} */\n this.currEval = undefined;\n\n /** @type {OtherTypeCallback|undefined} */\n this.currOtherTypeCallback = undefined;\n\n /** @type {Record<string, OtherTypeCallback>|undefined} */\n this.currCustomTypes = undefined;\n\n /** @type {SandboxType|undefined} */\n this.currSandbox = undefined;\n this._hasParentSelector = false;\n this.json = opts.json || obj;\n this.path = opts.path || expr;\n this.resultType = opts.resultType || 'value';\n this.flatten = Object.hasOwn(opts, 'flatten') && opts.flatten;\n this.wrap = !Object.hasOwn(opts, 'wrap') || opts.wrap;\n this.sandbox = opts.sandbox || {};\n this.eval = opts.eval === undefined ? 'safe' : opts.eval;\n this.ignoreEvalErrors = typeof opts.ignoreEvalErrors !== 'undefined' && opts.ignoreEvalErrors;\n this.parent = Object.hasOwn(opts, 'parent') ? opts.parent : null;\n this.parentProperty = Object.hasOwn(opts, 'parentProperty') ? opts.parentProperty : null;\n this.callback = opts.callback || (/** @type {JSONPathCallback} */\n 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 this.customTypes = opts.customTypes || {};\n if (opts.autostart === false) {\n return;\n }\n const args = /** @type {JSONPathOptions} */{\n path: optObj ? opts.path : expr\n };\n if (!optObj && obj !== undefined) {\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 const err = /** @type {Error & {value: UnknownResult}} */\n new Error('JSONPath should not be called with \"new\" (it ' + 'prevents return of (unwrapped) scalar values)');\n err.value = ret;\n throw err;\n }\n\n // @ts-expect-error - Constructor returns evaluate result for legacy API\n // eslint-disable-next-line @stylistic/max-len -- Long\n // eslint-disable-next-line consistent-return, no-constructor-return -- Legacy API\n return ret;\n }\n\n // PUBLIC METHODS\n\n /**\n * @overload\n * @param {JSONPathOptions} [expr]\n * @returns {ReturnObject|ReturnObject[]|undefined|unknown}\n */\n\n /**\n * @overload\n * @param {PathType|undefined} [expr]\n * @param {AnyInput} [json]\n * @param {JSONPathCallback|null} [callback]\n * @param {OtherTypeCallback} [otherTypeCallback]\n * @returns {ReturnObject|ReturnObject[]|undefined|unknown}\n */\n\n /**\n * @param {PathType|JSONPathOptions|undefined} [expr]\n * @param {AnyInput} [json]\n * @param {JSONPathCallback|null} [callback]\n * @param {OtherTypeCallback} [otherTypeCallback]\n * @returns {ReturnObject|ReturnObject[]|undefined|unknown}\n */\n evaluate(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 ||= this.callback;\n this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;\n this.currCustomTypes = this.customTypes;\n if (expr && typeof expr === 'object' && !Array.isArray(expr)) {\n const exprObj = expr;\n if (!exprObj.path && exprObj.path !== '') {\n throw new TypeError('You must supply a \"path\" property when providing an ' + 'object argument to JSONPath.evaluate().');\n }\n if (!Object.hasOwn(exprObj, 'json')) {\n throw new TypeError('You must supply a \"json\" property when providing an ' + 'object argument to JSONPath.evaluate().');\n }\n ({\n json\n } = exprObj);\n flatten = Object.hasOwn(exprObj, 'flatten') ? exprObj.flatten : flatten;\n this.currResultType = Object.hasOwn(exprObj, 'resultType') ? exprObj.resultType : this.currResultType;\n this.currSandbox = Object.hasOwn(exprObj, 'sandbox') ? exprObj.sandbox : this.currSandbox;\n wrap = Object.hasOwn(exprObj, 'wrap') ? exprObj.wrap : wrap;\n this.currEval = Object.hasOwn(exprObj, 'eval') ? exprObj.eval : this.currEval;\n callback = Object.hasOwn(exprObj, 'callback') ? exprObj.callback : callback;\n this.currOtherTypeCallback = Object.hasOwn(exprObj, 'otherTypeCallback') ? exprObj.otherTypeCallback : this.currOtherTypeCallback;\n this.currCustomTypes = Object.hasOwn(exprObj, 'customTypes') ? exprObj.customTypes : this.currCustomTypes;\n currParent = Object.hasOwn(exprObj, 'parent') ? exprObj.parent : currParent;\n currParentProperty = Object.hasOwn(exprObj, 'parentProperty') ? exprObj.parentProperty : currParentProperty;\n expr = exprObj.path;\n } else {\n json ||= this.json;\n expr ||= this.path;\n }\n currParent ||= null;\n currParentProperty ||= null;\n if (Array.isArray(expr)) {\n expr = JSONPath.toPathString(expr);\n }\n if (!json || !expr && expr !== '') {\n return undefined;\n }\n const exprList = JSONPath.toPathArray(/** @type {string} */\n expr);\n if (exprList[0] === '$' && exprList.length > 1) {\n exprList.shift();\n }\n this._hasParentSelector = false;\n const traceResult = this._trace(exprList, json, ['$'], currParent, currParentProperty, callback ?? undefined, undefined);\n\n // eslint-disable-next-line @stylistic/max-len -- Long\n /* c8 ignore next 2 -- Unreachable: _trace returns array when hasArrExpr set */\n const result = (Array.isArray(traceResult) ? traceResult : [traceResult]).filter(ea => {\n return ea && !ea.isParentSelector;\n });\n if (!result.length) {\n // eslint-disable-next-line @stylistic/max-len -- Long\n /* c8 ignore next -- Unreachable: valid queries always produce results */\n return wrap ? [] : undefined;\n }\n if (!wrap && result.length === 1 && !result[0].hasArrExpr) {\n const preferredOutput = this._getPreferredOutput(result[0]);\n return preferredOutput;\n }\n const reduced = 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 }, /** @type {UnknownResult[]} */\n []);\n return reduced;\n }\n\n // PRIVATE METHODS\n\n /**\n * @param {ReturnObject} ea\n * @returns {PreferredOutput}\n */\n _getPreferredOutput(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(/** @type {string[]} */path);\n ea.path = typeof ea.path === 'string' ? ea.path : JSONPath.toPathString(/** @type {string[]} */ea.path);\n return ea;\n }\n case 'value':\n case 'parent':\n case 'parentProperty':\n return /** @type {PreferredOutput} */ea[resultType];\n case 'path':\n if (typeof ea.path === 'string') {\n return ea.path;\n }\n return JSONPath.toPathString(/** @type {string[]} */ea.path);\n case 'pointer':\n {\n const pathArray = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);\n return JSONPath.toPointer(/** @type {string[]} */pathArray);\n }\n default:\n throw new TypeError('Unknown result type');\n }\n }\n\n /**\n * @param {ReturnObject} fullRetObj\n * @param {JSONPathCallback|undefined} callback\n * @param {\"value\"|\"property\"} type\n * @returns {void}\n */\n _handleCallback(fullRetObj, callback, type) {\n // Early return if no callback provided (defensive\n // check for internal calls)\n if (!callback) {\n return;\n }\n const preferredOutput = this._getPreferredOutput(fullRetObj);\n if (Array.isArray(fullRetObj.path)) {\n fullRetObj.path = JSONPath.toPathString(/** @type {string[]} */fullRetObj.path);\n }\n callback(preferredOutput, type, fullRetObj);\n }\n\n /**\n *\n * @param {ExpressionArray} expr\n * @param {unknown} val\n * @param {ExpressionArray} path\n * @param {ParentValue} parent\n * @param {ParentProperty} parentPropName\n * @param {JSONPathCallback|undefined} callback\n * @param {boolean|undefined} hasArrExpr\n * @param {boolean} [literalPriority]\n * @returns {ReturnObject|ReturnObject[]}\n */\n _trace(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 = /** @type {string} */expr[0],\n x = expr.slice(1);\n\n // We need to gather the return value of recursive trace calls in order\n // to do the parent sel computation.\n /** @type {ReturnObject[]} */\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 (val && (typeof loc !== 'string' || literalPriority) && Object.hasOwn(val, /** @type {PropertyKey} */loc)) {\n // simple case--directly follow property\n const valObj = /** @type {Record<string, unknown>} */val;\n addRet(this._trace(x, valObj[(/** @type {string} */loc)], push(path, loc), val, /** @type {string|number} */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 const valObj = /** @type {Record<string, unknown>} */val;\n addRet(this._trace(x, valObj[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 const valObj = /** @type {Record<string, unknown>} */val;\n if (typeof valObj[m] === 'object') {\n // Keep going with recursive descent on val's\n // object children\n addRet(this._trace(expr.slice(), valObj[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\n // callback here\n this._hasParentSelector = true;\n return /** @type {ReturnObject} */{\n path: path.slice(0, -1),\n expr: x,\n isParentSelector: true,\n value: undefined,\n parent: undefined,\n parentProperty: null\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*)$/v.test(loc)) {\n // [start:end:step] Python slice syntax\n const sliceResult = this._slice(loc, x, val, path, parent, parentPropName, callback);\n if (sliceResult) {\n addRet(sliceResult);\n }\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(/^\\?\\((.*?)\\)$/v, '$1');\n // check for a nested filter expression\n\n const nested = /@.?([^?]*)[\\['](\\??\\(.*?\\))(?!.\\)\\])[\\]']/gv.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 valObj2 = /** @type {Record<string, unknown>} */\n val;\n // guard against nested[1] resolving to `constructor`\n const nvalue = /** @type {ValueType} */nested[1] ? getSafeProperty(/** @type {Record<string, unknown>} */\n valObj2[m], nested[1]) : valObj2[m];\n const filterResults = this._trace(npath, nvalue, path, parent, parentPropName, callback, true);\n // eslint-disable-next-line @stylistic/max-len -- Long\n /* c8 ignore next 3 -- Unreachable: _trace always returns array for nested filters */\n const filterArray = Array.isArray(filterResults) ? filterResults : [filterResults];\n if (filterArray.length > 0) {\n addRet(this._trace(x, valObj2[m], push(path, m), val, m, callback, true));\n }\n });\n } else {\n const valObj3 = /** @type {Record<string, unknown>} */val;\n this._walk(val, m => {\n if (this._eval(safeLoc, valObj3[m], m, path, parent, parentPropName)) {\n addRet(this._trace(x, valObj3[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 const evalResult = this._eval(/** @type {string} */loc, val, /** @type {string|number} */path.at(-1), path.slice(0, -1), parent, parentPropName);\n const exprToUse = /** @type {string|number} */\n evalResult !== undefined ? evalResult : '';\n addRet(this._trace(unshift(exprToUse, x), val, path, parent, parentPropName, callback, hasArrExpr));\n } else if (loc[0] === '@') {\n // value type: @boolean(), etc.\n // eslint-disable-next-line no-useless-assignment -- ESLint bug\n let addType = false;\n const parenthIndex = loc.indexOf('(');\n const valueType = /** @type {ValueType|string} */loc.slice(1, parenthIndex);\n const lastParenth = loc.lastIndexOf(')');\n const argRaw = loc.slice(parenthIndex + 1, lastParenth);\n const arg = argRaw ? JSON.parse(argRaw) : undefined;\n switch (valueType) {\n case 'scalar':\n addType = !val || !['object', 'function'].includes(typeof val);\n break;\n case 'boolean':\n case 'string':\n case 'undefined':\n case 'function':\n addType = typeof val === valueType;\n break;\n case 'integer':\n addType = Number.isFinite(val) && !(/** @type {number} */val % 1);\n break;\n case 'number':\n addType = Number.isFinite(val);\n break;\n case 'nonFinite':\n addType = typeof val === 'number' && !Number.isFinite(val);\n break;\n case 'object':\n addType = Boolean(val) && typeof val === valueType;\n break;\n case 'array':\n addType = Array.isArray(val);\n break;\n case 'other':\n addType = /** @type {OtherTypeCallback} */this.currOtherTypeCallback(val, path, parent, parentPropName, arg) || false;\n break;\n case 'null':\n addType = val === null;\n break;\n case 'symbol':\n addType = typeof val === 'symbol';\n break;\n case 'BigInt':\n addType = typeof val === 'bigint';\n break;\n case 'Promise':\n addType = toStringTag(val) === 'Promise';\n break;\n case 'jsonReference':\n addType = Boolean(val) && typeof val === 'object' && Object.hasOwn(/** @type {object} */val, '$ref');\n break;\n default:\n if (this.currCustomTypes && Object.hasOwn(this.currCustomTypes, valueType)) {\n addType = this.currCustomTypes[valueType](val, path, parent, parentPropName, arg) || false;\n } else {\n throw new TypeError('Unknown value type ' + valueType);\n }\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 (val && loc[0] === '`' && Object.hasOwn(val, loc.slice(1))) {\n const locProp = loc.slice(1);\n const valObj = /** @type {Record<string, unknown>} */val;\n addRet(this._trace(x, valObj[locProp], push(path, locProp), val, locProp, callback, hasArrExpr, true));\n } else if (loc[0] === \"'\" || loc[0] === '\"') {\n // ['name1','name2',...]\n // Quoted members are literal property names\n for (const [, single, double] of loc.matchAll(/'((?:\\\\.|[^'\\\\])*)'|\"((?:\\\\.|[^\"\\\\])*)\"/gv)) {\n const prop = (single ?? double).replaceAll(/\\\\(['\"\\\\])/gv, '$1');\n if (!val || !Object.hasOwn(val, prop)) {\n continue;\n }\n const valObj = /** @type {Record<string, unknown>} */val;\n addRet(this._trace(x, valObj[prop], push(path, prop), val, prop, callback, true));\n }\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 const valObj = /** @type {Record<string, unknown>} */val;\n addRet(this._trace(x, valObj[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\n // the 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 continue;\n }\n const exprToUse = /** @type {ExpressionArray} */\n rett.expr;\n const pathToUse = /** @type {ExpressionArray} */\n rett.path;\n const tmp = this._trace(exprToUse, val, pathToUse, 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 t++;\n ret.splice(t, 0, tmp[tt]);\n }\n } else {\n ret[t] = tmp;\n }\n }\n }\n return ret;\n }\n\n /**\n * @param {unknown} val\n * @param {(prop: string|number) => void} f\n * @returns {void}\n */\n _walk(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 }\n\n /**\n * @param {string} loc\n * @param {ExpressionArray} expr\n * @param {unknown} val\n * @param {ExpressionArray} path\n * @param {ParentValue} parent\n * @param {ParentProperty} parentPropName\n * @param {JSONPathCallback|undefined} callback\n * @returns {ReturnObject[]|undefined}\n */\n _slice(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(parts[2]) || 1;\n let start = parts[0] && Number(parts[0]) || 0,\n end = parts[1] ? Number(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 /** @type {ReturnObject[]} */\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,\n // nor `~`, 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 // eslint-disable-next-line @stylistic/max-len -- Long\n /* c8 ignore next -- Unreachable: _trace returns array when expr non-empty */\n const tmpArray = Array.isArray(tmp) ? tmp : [tmp];\n tmpArray.forEach(t => {\n ret.push(t);\n });\n }\n return ret;\n }\n\n /**\n * @param {string} code\n * @param {unknown} _v\n * @param {string|number} _vname\n * @param {ExpressionArray} path\n * @param {ParentValue} parent\n * @param {ParentProperty} parentPropName\n * @returns {UnknownResult}\n */\n _eval(code, _v, _vname, path, parent, parentPropName) {\n if (this.currSandbox) {\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 }\n const containsPath = code.includes('@path');\n if (containsPath) {\n // eslint-disable-next-line @stylistic/max-len -- Long\n /* c8 ignore next -- Unreachable: currSandbox set in evaluate() before _eval */\n const currSandbox = this.currSandbox ?? {};\n currSandbox._$_path = JSONPath.toPathString(/** @type {string[]} */path.concat([_vname]));\n }\n const scriptCacheKey = this.currEval + 'Script:' + code;\n if (!scriptCache.has(scriptCacheKey)) {\n let script = code.replaceAll('@parentProperty', '_$_parentProperty').replaceAll('@parent', '_$_parent').replaceAll('@property', '_$_property').replaceAll('@root', '_$_root')\n // Replace a bare `@` (not followed by an identifier\n // character) while leaving quoted string literals and\n // regex literals (a `/` where an operand is expected,\n // as opposed to division) intact\n .replaceAll(/('(?:\\\\.|[^'\\\\])*'|\"(?:\\\\.|[^\"\\\\])*\"|(?<=(?:^|[\\(,=:\\[!\\|?\\{\\};+\\-*%<>~^]|&)\\s*)\\/(?:\\\\.|\\[(?:\\\\.|[^\\]\\\\])*\\]|[^\\/\\\\\\[])+\\/[dgimsuvy]*)|@(?![\\w$])/gv, (_, literal) => literal ?? '_$_v');\n if (containsPath) {\n script = script.replaceAll('@path', '_$_path');\n }\n const evalType = /** @type {string|boolean|undefined} */\n this.currEval;\n if (['safe', true, undefined].includes(evalType)) {\n // eslint-disable-next-line @stylistic/max-len -- Long\n /* eslint-disable unicorn/no-undeclared-class-members -- Prototype members */\n scriptCache.set(scriptCacheKey, new (\n /**\n * @type {JSONPathClass & {\n * safeVm: SafeScriptType,\n * vm: ScriptType\n * }}\n */ /** @type {unknown} */\n this).safeVm.Script(script));\n // eslint-disable-next-line @stylistic/max-len -- Long\n /* eslint-enable unicorn/no-undeclared-class-members -- End prototype member scope */\n } else if (this.currEval === 'native') {\n // eslint-disable-next-line @stylistic/max-len -- Long\n /* eslint-disable unicorn/no-undeclared-class-members -- Prototype members */\n scriptCache.set(scriptCacheKey, new (\n /**\n * @type {JSONPathClass & {\n * safeVm: SafeScriptType,\n * vm: ScriptType\n * }}\n */ /** @type {unknown} */\n this).vm.Script(script));\n // eslint-disable-next-line @stylistic/max-len -- Long\n /* eslint-enable unicorn/no-undeclared-class-members -- End prototype member scope */\n } else if (typeof this.currEval === 'function' && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, 'runInNewContext')) {\n const CurrEval = this.currEval;\n // eslint-disable-next-line @stylistic/max-len -- Long\n // @ts-expect-error - Type checked above to have proper constructor\n scriptCache.set(scriptCacheKey, new CurrEval(script));\n } else if (typeof this.currEval === 'function') {\n // Type narrowing: at this point currEval is a function\n // but not a constructor\n const evalFunc = /** @type {EvalCallback} */this.currEval;\n scriptCache.set(scriptCacheKey, {\n runInNewContext: (/** @type {ContextItem} */context) => evalFunc(script, context)\n });\n } else {\n throw new TypeError(`Unknown \"eval\" property \"${this.currEval}\"`);\n }\n }\n try {\n /**\n * @typedef {{\n * runInNewContext: (\n * ctx: SandboxType|undefined\n * ) => EvaluatedResult\n * }} RunInNewContext\n */\n\n return /** @type {RunInNewContext} */scriptCache.get(scriptCacheKey).runInNewContext(this.currSandbox);\n } catch (e) {\n if (this.ignoreEvalErrors) {\n return false;\n }\n const error = /** @type {Error} */e;\n throw new Error('jsonPath: ' + error.message + ': ' + code, {\n cause: e\n });\n }\n }\n}\n\n/** @type {{safeVm: SafeScriptType}} */\n(/** @type {unknown} */JSONPathClass.prototype).safeVm = {\n Script: SafeScript\n};\nJSONPath.prototype = JSONPathClass.prototype;\n\n// PUBLIC CLASS PROPERTIES AND METHODS\n\n/**\n * Clears cached parsed paths and compiled scripts.\n * @returns {void}\n */\nJSONPath.clearCache = function () {\n pathCache.clear();\n scriptCache.clear();\n};\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 (!/^(~|\\^|@.*?\\(\\))$/v.test(x[i])) {\n p += /^[0-9*]+$/v.test(x[i]) ? '[' + x[i] + ']' : \"['\" + String(x[i]).replaceAll(/['\\\\]/gv, String.raw`\\$&`) + \"']\";\n }\n }\n return p;\n};\n\n/**\n * @param {string[]} pointer JSON Path array\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 (!/^(~|\\^|@.*?\\(\\))$/v.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 if (pathCache.has(expr)) {\n return /** @type {string[]} */pathCache.get(expr).concat();\n }\n /** @type {string[]} */\n const subx = [];\n const normalized = expr\n // Properties\n .replaceAll(/@[\\w$\\-]+\\([^\\)]*\\)/gv, ';$&;')\n // Parenthetical evaluations (filtering and otherwise), directly\n // within brackets or single quotes\n .replaceAll(/[\\['](\\??\\(.*?\\))[\\]'](?!.\\])/gv, function ($0, $1) {\n return '[#' + (\n // eslint-disable-next-line @stylistic/max-len -- Long\n // eslint-disable-next-line unicorn/no-return-array-push -- Optimization\n subx.push($1) - 1) + ']';\n })\n // Unions of quoted property names (e.g., `['x','y']`) and quoted\n // names with commas or backslash escapes, kept intact (with\n // quotes) so their members survive tokenization\n .replaceAll(/\\[\\s*((?:'(?:\\\\.|[^'\\\\])*'|\"(?:\\\\.|[^\"\\\\])*\")(?:\\s*,\\s*(?:'(?:\\\\.|[^'\\\\])*'|\"(?:\\\\.|[^\"\\\\])*\"))*)\\s*\\]/gv, function ($0, $1) {\n if (!/[,\\\\]/v.test($1)) {\n return $0;\n }\n // eslint-disable-next-line @stylistic/max-len -- Long\n // eslint-disable-next-line unicorn/no-return-array-push -- Optimization\n return '[#' + (subx.push($1) - 1) + ']';\n })\n // Escape periods and tildes within properties\n .replaceAll(/\\[['\"]([^'\\]]*)['\"]\\]/gv, function ($0, prop) {\n return \"['\" + prop.replaceAll('.', '%@%').replaceAll('~', '%%@@%%') + \"']\";\n })\n // Properties operator\n .replaceAll('~', ';~;')\n // Split by property boundaries\n .replaceAll(/['\"]?\\.['\"]?(?![^\\[]*\\])|\\[['\"]?/gv, ';')\n // Reinsert periods within properties\n .replaceAll('%@%', '.')\n // Reinsert tildes within properties\n .replaceAll('%%@@%%', '~')\n // Parent\n .replaceAll(/(?:;)?(\\^+)(?:;)?/gv, function ($0, ups) {\n return ';' + ups.split('').join(';') + ';';\n })\n // Descendents\n .replaceAll(/;;;|;;/gv, ';..;')\n // Remove trailing\n .replaceAll(/;$|'?\\]|'$/gv, '');\n const exprList = normalized.split(';').map(function (exp) {\n const match = exp.match(/#(\\d+)/v);\n return !match || !match[1] ? exp : subx[Number(match[1])];\n });\n pathCache.set(expr, exprList);\n return /** @type {string[]} */pathCache.get(expr).concat();\n};\n\n/**\n * @typedef {import('./jsonpath.js').AnyInput} AnyInput\n */\n/**\n * @typedef {import('./jsonpath.js').SandboxCallback} SandboxCallback\n */\n/**\n * @typedef {import('./jsonpath.js').SandboxPropertyValue} SandboxPropertyValue\n */\n/**\n * @typedef {import('./jsonpath.js').ExpressionArray} ExpressionArray\n */\n/**\n * @typedef {import('./jsonpath.js').ValueType} ValueType\n */\n/**\n * @typedef {import('./jsonpath.js').ParentValue} ParentValue\n */\n/**\n * @typedef {import('./jsonpath.js').UnknownResult} UnknownResult\n */\n/**\n * @typedef {import('./jsonpath.js').ParentProperty} ParentProperty\n */\n/**\n * @typedef {import('./jsonpath.js').PreferredOutput} PreferredOutput\n */\n/**\n * @typedef {import('./jsonpath.js').ReturnObject} ReturnObject\n */\n/**\n * @typedef {import('./jsonpath.js').JSONPathCallback} JSONPathCallback\n */\n/**\n * @typedef {import('./jsonpath.js').OtherTypeCallback} OtherTypeCallback\n */\n/**\n * @typedef {import('./jsonpath.js').ContextItem} ContextItem\n */\n/**\n * @typedef {import('./jsonpath.js').EvaluatedResult} EvaluatedResult\n */\n/**\n * @typedef {import('./jsonpath.js').EvalCallback} EvalCallback\n */\n/**\n * @typedef {import('./jsonpath.js').EvalClass} EvalClass\n */\n/**\n * @typedef {import('./jsonpath.js').ResultType} ResultType\n */\n/**\n * @typedef {import('./jsonpath.js').EvalValue} EvalValue\n */\n/**\n * @typedef {import('./jsonpath.js').PathType} PathType\n */\n/**\n * @typedef {import('./jsonpath.js').SafeScriptType} SafeScriptType\n */\n/**\n * @typedef {import('./jsonpath.js').ScriptType} ScriptType\n */\n/**\n * @typedef {import('./jsonpath.js').SandboxType} SandboxType\n */\n/**\n * @typedef {import('./jsonpath.js').JSONPathOptions} JSONPathOptions\n */\n\n// Node's vm module shape is wider than ScriptType, but is compatible for\n// the properties actually used (Script) -- kept Node-specific here so\n// `node:vm` types don't leak into the shared/browser declarations.\n/** @type {{vm: ScriptType}} */\n(/** @type {unknown} */JSONPathClass.prototype).vm = /** @type {ScriptType} */\n/** @type {unknown} */vm;\n\nexport { JSONPath, JSONPathClass };\n"],"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;GAC5B,IAAI,UACF,KAAK,KAAK,CAAC,QAAQ,YAAY,OAAO,CAAC,QAAQ;EAEnD,GAAG,IAAI;CAEX;;;;;;;;;;CAWA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I,KAAK;EACpD,OAAO,MAAM,IAAI,MAAM,EAAE,CAAC,CAAC,KAAK,GAAG,IAAI;CACzC,CAAC,CAAC,CAED,WAAW,YAAY,MAAM,CAAC,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,OAAO,MAAM,EAAE;CACzD,CAAC;CACD,UAAU,IAAI,MAAM,QAAQ;CAC5B,OAA8B,UAAU,IAAI,IAAI,CAAC,CAAC,OAAO;AAC3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4EA,cAAqC,UAAW,KAC1B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-DJoqT9yP.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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":["import type {\n ContentPart,\n Message,\n MetaPart,\n TextPart,\n Tool,\n ToolCallPart,\n ToolContext,\n ToolResult,\n ToolResultPart,\n Streamable as TStreamable,\n} from \"@zaly/ai\"\n\nimport { AiError, isStreamable, runTool, stringifyContent, toErrorResult } from \"@zaly/ai\"\nimport { Emitter, safeStringify } from \"@zaly/shared\"\nimport { uuidv7 } from \"./utils/uuid.ts\"\n\nconst DEFAULT_GRACE_MS = 10_000\n\n/** Status of a task. `pending` = queued behind a dependency, not yet\n * started. `running` = work in progress (a Streamable is being polled).\n * `done` = result captured, no longer mutating. */\nexport type TaskStatus = \"pending\" | \"running\" | \"done\"\n\n/** Public projection of a registered task. Status-discriminated so the\n * fields visible at any moment are exactly the ones that make sense\n * for that lifecycle stage:\n *\n * - `running`: `elapsedMs` since start; `hasNewOutput` when the\n * streamable signals that `task_poll` would yield bytes.\n * - `pending`: queued behind another task (`waitingFor`); `elapsedMs`\n * counts time-since-registration.\n * - `done`: settled. Carries `durationMs` and the captured `result`.\n *\n * This is the only public task type — the registry exposes it via\n * `running()` / `finished()` / `get()`, events carry it (`task-done`\n * is narrowed to `status: \"done\"` so listeners get `result` typed\n * without checks), and `task_list` JSON-stringifies it directly. */\nexport type TaskInfo = {\n id: string\n type: string\n desc: string\n} & (\n | { status: \"running\"; elapsedMs: number; hasNewOutput?: boolean }\n | { status: \"pending\"; waitingFor: string; elapsedMs: number }\n | { status: \"done\"; durationMs: number; result: ToolResult }\n)\n\n/** A `TaskInfo` known to be in the `done` state. `task-done` event\n * payloads use this so listeners get `result` and `durationMs` typed\n * without manual narrowing. */\nexport type DoneTaskInfo = Extract<TaskInfo, { status: \"done\" }>\n\n/** Events emitted by a `Tasks` instance. `task-done` only fires for\n * completions that happen *outside* an in-flight `run()` round —\n * round-internal completions are folded into the `run()` return value\n * instead. `heartbeat` fires periodically (when `heartbeatMs` is set\n * and at least one task is active), giving the agent a hook to keep\n * the model engaged on long-running work. */\nexport type TasksEvents = {\n \"task-added\": { task: TaskInfo }\n \"task-removed\": { task: TaskInfo }\n \"task-done\": { task: DoneTaskInfo }\n heartbeat: { running: readonly TaskInfo[] }\n}\n\n/** Augment ToolMeta so tools and consumers can read freshness/state info\n * off `ToolResultPart.meta.task`. The registry stamps this on every\n * result it produces so the model can correlate placeholders to their\n * eventual completion. */\nexport interface TaskMeta {\n task?: {\n id: string\n status: TaskStatus\n type: string\n desc: string\n dependsOn?: string\n durationMs?: number\n }\n}\n\n/** Internal storage record. Not exposed — `toTaskInfo` projects it to\n * `TaskInfo` for any caller that crosses the boundary (events,\n * registry methods, the `task_*` tools). Carries everything the\n * registry needs to drive lifecycle transitions, plus the raw\n * timestamps `TaskInfo` derives elapsed/duration from. */\ninterface InternalTask {\n id: string\n type: string\n desc: string\n status: TaskStatus\n /** Wallclock at registration. */\n startedAt: number\n /** Wallclock at completion; set once status is `done`. */\n finishedAt?: number\n /** Captured result when status is `done`. */\n result?: ToolResult\n /** When set, this task is queued behind another and won't start until\n * the named task transitions to `done`. */\n waitingFor?: string\n /** Streamable returned by the tool, if any — held so we can `abort()`\n * on cancellation and call `poll()` for partial snapshots. */\n streamable?: TStreamable\n /** Resolves when the task transitions to `done`. Used by the round\n * race in `run()`. */\n donePromise: Promise<void>\n resolveDone: () => void\n /** When set, the task belongs to an in-flight `run()` round — its\n * completion does *not* fire `task-done` (the round folds it into the\n * returned parts instead). Cleared once the round ends. */\n ownerRound?: symbol\n /** Stashed call so a pending task can be restarted once its\n * dependency completes. */\n pending?: { tool: Tool; call: ToolCallPart; ctx: ToolContext }\n}\n\n/**\n * Tool registry + execution machinery + long-running task bookkeeping.\n * One Tasks instance per Agent. Owns the tool list (the agent delegates\n * `agent.tools` to it) and runs every assistant tool batch through\n * `run()`, which:\n *\n * - validates each call's params,\n * - dispatches to the named tool (sync results land immediately),\n * - races `Streamable` returns against a grace window,\n * - chains `parallel: false` calls behind their predecessors,\n * - returns `ToolResultPart[]` 1:1 with the assistant's calls,\n * surfacing partial results / placeholders for anything still running\n * when the grace expires.\n *\n * Completions during a round are folded into the returned parts and do\n * NOT fire `task-done`. Completions afterward fire normally — the agent\n * listens and injects a system message into the next step.\n */\nexport class Tasks extends Emitter<TasksEvents> {\n readonly #map = new Map<string, InternalTask>()\n graceMs = DEFAULT_GRACE_MS\n\n #tools: (() => Promise<readonly Tool[]>) | Tool[] = []\n\n /** Heartbeat interval in ms. When set, fires `heartbeat` events while\n * at least one task is pending or running. Self-managing: starts on\n * the first active task, stops when the last one finishes. Set to\n * `undefined` to disable. */\n #heartbeatMs?: number\n #heartbeatTimer?: ReturnType<typeof setInterval>\n\n get heartbeatMs(): number | undefined {\n return this.#heartbeatMs\n }\n set heartbeatMs(value: number | undefined) {\n this.#heartbeatMs = value\n this.#syncHeartbeat()\n }\n\n // ── Public registry surface ─────────────────────────────────────────\n\n /** Snapshot of every active task (pending or running). */\n running(): readonly TaskInfo[] {\n return [...this.#map.values()].filter((t) => t.status !== \"done\").map((t) => toTaskInfo(t))\n }\n\n /** Snapshot of every task that has completed. Drops are by `remove()`\n * or implicit retention; this list grows unless the caller prunes. */\n finished(): readonly DoneTaskInfo[] {\n return [...this.#map.values()]\n .filter((t): t is InternalTask & { status: \"done\" } => t.status === \"done\")\n .map((t) => toTaskInfo(t) as DoneTaskInfo)\n }\n\n /** Look up a task by id. Useful for `task_stop` / `task_poll`. */\n get(id: string): TaskInfo | undefined {\n const t = this.#map.get(id)\n return t ? toTaskInfo(t) : undefined\n }\n\n /** Snapshot of every task in the registry — running, pending, and done. */\n info(): readonly TaskInfo[] {\n return [...this.#map.values()].map(toTaskInfo)\n }\n\n async tools(): Promise<readonly Tool[]> {\n return typeof this.#tools === \"function\" ? this.#tools() : this.#tools\n }\n\n set $tools(tools: (() => Promise<readonly Tool[]>) | Tool[]) {\n this.#tools = tools\n }\n\n /** Non-consuming check: does the underlying streamable have output\n * the model hasn't seen since the last `poll()`? Returns false for\n * tasks without a streamable, completed tasks, or streamables that\n * don't implement the optional `hasNew` hook (no signal to give).\n * Used by heartbeats to flag tasks worth polling. */\n hasNewOutput(id: string): boolean {\n const t = this.#map.get(id)\n if (t?.status !== \"running\" || !t.streamable) return false\n return t.streamable.hasNew?.() ?? false\n }\n\n /** Poll a task's streamable for incremental output without changing\n * its lifecycle state. Advances the streamable's cursor — the next\n * call returns only what arrived since *this* one. Returns the same\n * `ToolResult` shape the original tool produces (parts + meta).\n * Errors when the task is unknown, already done, or has no streamable\n * (the latter is the case for plain-Promise tools — there's no\n * partial state to read). */\n pollOutput(id: string): ToolResult & { running: boolean } {\n const t = this.#map.get(id)\n if (!t) {\n throw new AiError({\n code: \"NOT_FOUND\",\n data: { id },\n message: `no task with id \"${id}\"`,\n })\n }\n if (t.status === \"done\") {\n throw new AiError({\n code: \"TASK_DONE\",\n data: { id },\n message: `task \"${id}\" has already completed; its result was injected as a system message`,\n })\n }\n if (!t.streamable) {\n throw new AiError({\n code: \"NOT_STREAMABLE\",\n data: { id },\n message:\n `task \"${id}\" has no incremental output — it's a plain-Promise tool ` +\n `whose result is delivered all-at-once when complete`,\n })\n }\n return t.streamable.poll()\n }\n\n /** Drop a task from the registry — does not abort. Caller is\n * responsible for `abort()`-ing if the task is still running. */\n remove(id: string): boolean {\n const task = this.#map.get(id)\n if (!task) return false\n this.#map.delete(id)\n void this.emit(\"task-removed\", { task: toTaskInfo(task) })\n return true\n }\n\n /** Mark a task done with a final result. Fires `task-done` UNLESS the\n * task is currently owned by an in-flight `run()` round — in that\n * case the round folds the completion into its returned parts and\n * the event is suppressed. Starts any pending dependents. */\n done(id: string, result: ToolResult): void {\n const task = this.#map.get(id)\n if (!task || task.status === \"done\") return\n task.status = \"done\"\n task.result = result\n task.finishedAt = Date.now()\n task.resolveDone()\n if (!task.ownerRound) {\n void this.emit(\"task-done\", { task: toTaskInfo(task) as DoneTaskInfo })\n }\n this.#startReadyDependents(id, result)\n this.#syncHeartbeat()\n }\n\n /** Abort a running task. Calls the streamable's `abort()` if present;\n * pending tasks transition straight to `done` with a cancelled\n * result. Idempotent. */\n abort(id: string, reason = \"aborted by request\"): void {\n const task = this.#map.get(id)\n if (!task || task.status === \"done\") return\n if (task.streamable) task.streamable.abort()\n if (task.status === \"pending\") {\n this.done(id, toErrorResult(new AiError({ code: \"TASK_ABORTED\", message: reason })))\n }\n // Running tasks: the streamable will eventually settle and call done()\n // via its watcher. We could force a synchronous \"done\" here, but\n // letting the streamable's natural completion path run keeps the\n // final snapshot accurate (output that arrived before abort lands).\n }\n\n /** Abort every active task. Used on agent dispose. Awaits each\n * task's `donePromise` so the registry is fully drained before\n * resolving — so callers can rely on no pending I/O after `dispose`. */\n async killAll(): Promise<void> {\n const active = [...this.#map.values()].filter((t) => t.status !== \"done\")\n for (const t of active) {\n if (t.streamable) t.streamable.abort()\n if (t.status === \"pending\") {\n this.done(\n t.id,\n toErrorResult(new AiError({ code: \"TASK_ABORTED\", message: \"agent disposed\" }))\n )\n }\n }\n await Promise.all(active.map((t) => t.donePromise.catch(() => undefined)))\n this.#syncHeartbeat()\n }\n\n /** Start or stop the heartbeat timer based on whether any task is\n * active and whether `heartbeatMs` is configured. Idempotent — called\n * after every state transition (`add` / `done` / `killAll`). The\n * timer is `unref`'d so it never holds the process open. */\n #syncHeartbeat(): void {\n const hasActive = [...this.#map.values()].some((t) => t.status !== \"done\")\n const want = hasActive && this.#heartbeatMs !== undefined\n if (want && !this.#heartbeatTimer) {\n this.#heartbeatTimer = setInterval(() => {\n void this.emit(\"heartbeat\", { running: this.info().filter((t) => t.status !== \"done\") })\n }, this.#heartbeatMs)\n this.#heartbeatTimer.unref()\n } else if (!want && this.#heartbeatTimer) {\n clearInterval(this.#heartbeatTimer)\n this.#heartbeatTimer = undefined\n }\n }\n\n // ── Batch execution ─────────────────────────────────────────────────\n\n /**\n * Execute a batch of assistant tool calls. Returns ToolResultPart[]\n * mapped 1:1 with `calls`. Sync completions land in the result array\n * immediately; long-running ones return a placeholder and the eventual\n * completion fires `task-done` post-round (the agent injects a system\n * message in response).\n *\n * The `messages` snapshot is what tools see on `ctx.messages` — pass\n * the conversation up to (and including) the assistant message that\n * produced these calls, so freshness checks can scan back through\n * prior tool results.\n */\n async run(\n calls: readonly ToolCallPart[],\n ctx: ToolContext,\n opts: { onResult?: (call: ToolCallPart, result: ToolResultPart, idx: number) => void } = {}\n ): Promise<ToolResultPart[]> {\n const round = Symbol(\"round\")\n const tasks: InternalTask[] = []\n let chainHead: string | undefined\n\n const tools = await this.tools()\n\n for (const call of calls) {\n const tool = tools.find((t) => t.name === call.name)\n if (!tool) {\n tasks.push(this.#startSyncResult(call, unknownToolResult(call.name), round))\n continue\n }\n\n const parallel = tool.parallel ?? false\n\n if (chainHead && !parallel) {\n // Queue behind the chain head — won't start until that finishes.\n tasks.push(\n this.#registerPending({ call, ctxBase: ctx, round, tool, waitingFor: chainHead })\n )\n chainHead = tasks[tasks.length - 1].id\n continue\n }\n\n if (this.#needsPreflight(tool, ctx)) {\n // Preflight is intentionally sequential: permission prompts should\n // appear one at a time and should not register/background a task while\n // waiting for the user's answer.\n // oxlint-disable-next-line no-await-in-loop\n const preflight = await this.#preflight(tool, call, ctx)\n if (preflight) {\n tasks.push(this.#startSyncResult(call, preflight, round))\n continue\n }\n }\n\n const task = this.#start({ call, ctxBase: ctx, round, tool })\n tasks.push(task)\n // If this call promoted to a long-running task and `parallel: false`,\n // subsequent serial calls chain behind it.\n if (task.status === \"running\" && !parallel) chainHead = task.id\n }\n\n const parts: ToolResultPart[] = []\n\n const resultPart = (idx: number): ToolResultPart => {\n if (parts[idx]) return parts[idx]\n const task = tasks[idx]\n if (task.status !== \"done\") task.ownerRound = undefined\n const call = calls[idx]\n const part = this.#buildPart(call, task)\n parts[idx] = part\n return part\n }\n\n let onResult = opts.onResult\n\n // Race: every task done, OR grace expires, OR ctx.signal aborts.\n const allDone = Promise.all(\n tasks.map(async (t, ti) => {\n await t.donePromise\n onResult?.(calls[ti], resultPart(ti), ti)\n })\n )\n const grace = sleep(this.graceMs)\n const aborted = ctx.signal\n ? new Promise<void>((resolve) => {\n if (ctx.signal!.aborted) resolve()\n else ctx.signal!.addEventListener(\"abort\", () => resolve(), { once: true })\n })\n : new Promise<void>(() => undefined) // never resolves\n await Promise.race([allDone, grace, aborted])\n onResult = undefined\n\n // Release ownership on still-active tasks BEFORE building the result\n // array, so the post-round listener sees them as free-floating if\n // they happen to settle in the same tick.\n return tasks.map((_, i) => resultPart(i))\n }\n\n // ── Internals ──────────────────────────────────────────────────────\n\n /** Build a \"done\" task synchronously from a precomputed result.\n * Used for unknown-tool errors and validation failures. */\n #startSyncResult(call: ToolCallPart, result: ToolResult, round: symbol): InternalTask {\n // oxlint-disable-next-line sort-keys -- semantic field order\n const task = this.#allocate({ id: uuidv7(), type: call.name, desc: call.name, round })\n task.status = \"done\"\n task.result = result\n task.finishedAt = task.startedAt\n task.resolveDone()\n return task\n }\n\n /** Allocate an internal task record, register it, and emit `task-added`. */\n #allocate(opts: {\n id: string\n type: string\n desc: string\n waitingFor?: string\n round: symbol\n }): InternalTask {\n let resolveDone!: () => void\n const donePromise = new Promise<void>((r) => {\n resolveDone = r\n })\n const task: InternalTask = {\n desc: opts.desc,\n donePromise,\n id: opts.id,\n ownerRound: opts.round,\n resolveDone,\n startedAt: Date.now(),\n status: \"pending\",\n type: opts.type,\n waitingFor: opts.waitingFor,\n }\n this.#map.set(task.id, task)\n void this.emit(\"task-added\", { task: toTaskInfo(task) })\n this.#syncHeartbeat()\n return task\n }\n\n /** Register a pending task (chained behind `dependsOn`). Does not\n * invoke the tool — that happens once the dependency completes. */\n #registerPending(opts: {\n call: ToolCallPart\n tool: Tool\n ctxBase: ToolContext\n waitingFor: string\n round: symbol\n }): InternalTask {\n // oxlint-disable-next-line sort-keys -- semantic field order\n const task = this.#allocate({\n id: uuidv7(),\n type: opts.tool.name,\n desc: descOfCall(opts.call),\n waitingFor: opts.waitingFor,\n round: opts.round,\n })\n task.pending = { call: opts.call, ctx: opts.ctxBase, tool: opts.tool }\n return task\n }\n\n /** Start a tool call. Allocates a task record, validates params,\n * invokes `tool.call`, detects `Streamable`, and wires completion\n * back to `done()`. Returns the task in its post-launch state\n * (`done` for sync failures or already-resolved sync calls,\n * `running` for everything else). */\n #start(opts: {\n call: ToolCallPart\n tool: Tool\n ctxBase: ToolContext\n round: symbol\n }): InternalTask {\n // oxlint-disable-next-line sort-keys -- semantic field order\n const task = this.#allocate({\n id: uuidv7(),\n type: opts.tool.name,\n desc: descOfCall(opts.call),\n round: opts.round,\n })\n this.#dispatch(task, opts.tool, opts.call, opts.ctxBase)\n return task\n }\n\n #needsPreflight(tool: Tool, ctx: ToolContext): boolean {\n return ctx.need !== undefined || tool.preflight !== undefined\n }\n\n /** Run schema validation and semantic/tool permission checks before a\n * public task is allocated. Returns a formatted tool error when the\n * call should short-circuit, otherwise undefined. */\n async #preflight(\n tool: Tool,\n call: ToolCallPart,\n ctxBase: ToolContext\n ): Promise<ToolResult | undefined> {\n const ctx: ToolContext = { ...ctxBase, tasks: this }\n let params: unknown\n try {\n params = await tool.validator.validateParams(call.params)\n await ctx.need?.(\"tool\", tool.name)\n await tool.preflight?.(params, ctx)\n } catch (error) {\n return toErrorResult(error)\n }\n }\n\n /** Validate / call / wire up completion for an existing task record.\n * Used both for fresh tasks (`#start`) and pending-becoming-ready\n * (`#startReadyDependents`). The task's id and registry entry are\n * reused so identifiers stay stable across the pending → running\n * transition.\n *\n * Delegates the validate/call/error machinery to `runTool` (in\n * streaming mode) so there's one source of truth. The task's status\n * is flipped to `running` synchronously — the round loop reads it\n * right after `#start` returns to decide chain heads, and we want\n * that read to see the post-launch state, not the allocation default.\n * Async resolution either keeps it `running` (streamable returned)\n * or transitions to `done` (sync result or error). */\n #dispatch(task: InternalTask, tool: Tool, call: ToolCallPart, ctxBase: ToolContext): void {\n const ctx: ToolContext = { ...ctxBase, tasks: this }\n task.status = \"running\"\n\n const dispatchPromise = runTool(tool, call.params, ctx, { preflight: false, streaming: true })\n\n void dispatchPromise.then(\n (settled) => {\n if (isStreamable(settled)) {\n // Long-running — hold the streamable for partial snapshots /\n // abort, wire its completion back through done().\n task.streamable = settled\n settled.done.then(\n () => {\n const snap = settled.poll()\n this.done(task.id, {\n content: snap.content,\n error: snap.error,\n isError: snap.isError,\n meta: snap.meta,\n })\n },\n // `done` shouldn't reject by contract; treat as internal bug.\n (error: unknown) => this.done(task.id, toErrorResult(error))\n )\n return\n }\n // Sync path: validation error, sync return, or thrown error —\n // runTool has already formatted everything into a ToolResult.\n this.done(task.id, settled)\n },\n // The permission gate threw (or AiError leaked from runTool).\n // Either way, format and settle the task.\n (error: unknown) => this.done(task.id, toErrorResult(error))\n )\n }\n\n /** Walk pending tasks; start any whose `dependsOn` just completed.\n * If the dependency failed, propagate cancellation: dependents land\n * in `done` with an `UPSTREAM_FAILED` result. */\n #startReadyDependents(completedId: string, completedResult: ToolResult): void {\n for (const t of this.#map.values()) {\n if (t.status !== \"pending\" || t.waitingFor !== completedId) continue\n if (completedResult.isError) {\n // Skip dependent — its predecessor failed.\n this.done(\n t.id,\n toErrorResult(\n new AiError({\n code: \"UPSTREAM_FAILED\",\n data: { dependsOn: completedId },\n message: `skipped: upstream task ${completedId} failed`,\n })\n )\n )\n continue\n }\n void this.#startPending(t)\n }\n }\n\n async #startPending(task: InternalTask): Promise<void> {\n const pending = task.pending\n if (!pending) return\n if (!this.#needsPreflight(pending.tool, pending.ctx)) {\n task.pending = undefined\n task.waitingFor = undefined\n task.ownerRound = undefined\n this.#dispatch(task, pending.tool, pending.call, pending.ctx)\n return\n }\n\n const preflight = await this.#preflight(pending.tool, pending.call, pending.ctx)\n if (preflight) {\n this.done(task.id, preflight)\n return\n }\n\n // Restart as a regular task. The round that originally registered\n // this task has already returned its placeholder, so whatever happens\n // now flows through normal `task-done`.\n task.pending = undefined\n task.waitingFor = undefined\n task.ownerRound = undefined\n this.#dispatch(task, pending.tool, pending.call, pending.ctx)\n }\n\n /** Build a `ToolResultPart` for a task at round-end. Done tasks pass\n * through their captured result; still-running tasks get a snapshot\n * from the streamable (if any) plus a placeholder note for the model. */\n #buildPart(call: ToolCallPart, task: InternalTask): ToolResultPart {\n if (task.status === \"done\" && task.result) {\n return {\n content: task.result.content,\n error: task.result.error,\n id: call.id,\n isError: task.result.isError,\n meta: stampTaskMeta(task.result.meta, task),\n name: call.name,\n type: \"tool-result\",\n }\n }\n\n // Pending: never started, will run when its dependency completes.\n // Placeholder uses the standard TaskInfo shape so it's parseable\n // the same way as task_list / heartbeat entries.\n if (task.status === \"pending\") {\n return {\n content: [{ data: toTaskInfo(task), tag: \"task\", type: \"meta\" }],\n id: call.id,\n isError: false,\n meta: stampTaskMeta(undefined, task),\n name: call.name,\n type: \"tool-result\",\n }\n }\n\n // Running: capture whatever the streamable has so far (partial output)\n // and append a `<task>` MetaPart with an explicit \"still running\"\n // hint. Without the hint, models tend to treat partial output as a\n // final answer and respond prematurely; with it they see the state\n // structurally and know the final result will arrive as a later\n // system message. Tagged `<task>` for symmetry with the pending /\n // task_list / heartbeat / task-done entries — same shape everywhere\n // a task surfaces.\n const snap = task.streamable?.poll()\n const baseContent = partialContentFrom(snap)\n const trailer: MetaPart = {\n content:\n \"Task is still running. Partial output above. The final result \" +\n \"will arrive as a system message when the task completes; you \" +\n \"do not need to poll. Continue with other work or wait.\",\n data: {\n ...toTaskInfo(task),\n },\n tag: \"task\",\n type: \"meta\",\n }\n const parts: ContentPart[] = []\n if (typeof baseContent === \"string\") {\n if (baseContent !== \"\") parts.push({ text: baseContent, type: \"text\" })\n } else {\n parts.push(...baseContent)\n }\n parts.push(trailer)\n return {\n content: parts,\n id: call.id,\n isError: false,\n meta: stampTaskMeta(snap?.meta, task),\n name: call.name,\n type: \"tool-result\",\n }\n }\n}\n\n/** Stamp `meta.task` with the current task state. Preserves any\n * tool-attached `meta` fields. Used both on done results (so the\n * model can correlate completion to the original call) and on\n * partial / pending placeholders. */\nfunction stampTaskMeta(\n base: ToolResult[\"meta\"] | undefined,\n task: InternalTask\n): ToolResult[\"meta\"] & TaskMeta {\n return {\n ...base,\n task: {\n dependsOn: task.waitingFor,\n desc: task.desc,\n durationMs: task.finishedAt ? task.finishedAt - task.startedAt : undefined,\n id: task.id,\n status: task.status,\n type: task.type,\n },\n }\n}\n\n/** Build the \"running\" placeholder content from a streamable snapshot.\n * Empty string when there's nothing yet to show; copies the parts\n * array so downstream mutation of the result message can't reach back\n * into the streamable's accumulator. */\nfunction partialContentFrom(\n snap: { content: ToolResult[\"content\"] } | undefined\n): ToolResultPart[\"content\"] {\n if (!snap) return \"\"\n if (typeof snap.content === \"string\") return snap.content\n return [...snap.content]\n}\n\n/** Best-effort human-readable label for a tool call. Reads a\n * `description` field from params if the tool defined one (bash does);\n * otherwise falls back to the tool name. Kept short so log lines stay\n * scannable. */\nfunction descOfCall(call: ToolCallPart): string {\n const params = call.params as { description?: unknown } | null | undefined\n if (params && typeof params === \"object\" && typeof params.description === \"string\") {\n return params.description\n }\n return call.name\n}\n\n/** Synthesize the tool-result payload returned when the model calls a\n * tool that wasn't registered for this turn. Same shape the previous\n * `unknownToolResult` helper produced; inlined here to keep `tasks.ts`\n * self-contained. */\nfunction unknownToolResult(name: string): ToolResult {\n const err = new AiError({\n code: \"UNKNOWN_TOOL\",\n message: `no tool named \"${name}\" is registered for this turn`,\n })\n return toErrorResult(err)\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => {\n const t = setTimeout(r, ms)\n t.unref()\n })\n}\n\n/** Render an array of `TaskInfo` as a `<tasks>` MetaPart for the model\n * (heartbeat pulses and `task_list`). Each task lands as one line of\n * JSON. The `result` field on done tasks is stripped — listing should\n * give an inventory, not historical output (the result was already\n * injected as a system message at task-done time, and re-shipping it\n * on every heartbeat / list call would be a token bomb). */\nexport function taskInfoPart(info: readonly TaskInfo[]): MetaPart {\n if (info.length === 0) return { data: \"no active tasks\", tag: \"tasks\", type: \"meta\" }\n const data = info.map((t) => safeStringify(t, omitResult)).join(\"\\n\")\n return { data, tag: \"tasks\", type: \"meta\" }\n}\n\n/** JSON.stringify replacer that drops the `result` field. Used by\n * `taskInfoPart` to keep listing payloads bounded. */\nfunction omitResult(key: string, value: unknown): unknown {\n return key === \"result\" ? undefined : value\n}\n\nfunction toTaskInfo(task: InternalTask): TaskInfo {\n const { id, status, type, desc } = task\n const ms = (task.finishedAt ?? Date.now()) - task.startedAt\n if (status === \"running\") {\n return { desc, elapsedMs: ms, hasNewOutput: task.streamable?.hasNew?.(), id, status, type }\n }\n if (status === \"pending\") {\n return { desc, elapsedMs: ms, id, status, type, waitingFor: task.waitingFor ?? \"\" }\n }\n // status === \"done\" — `result` is set by `done()` before status flips,\n // so the `?? toErrorResult(...)` is just a defensive fallback for\n // a malformed record (shouldn't happen in practice).\n return {\n desc,\n durationMs: ms,\n id,\n result:\n task.result ??\n toErrorResult(\n new AiError({\n code: \"INTERNAL\",\n message: `task \"${task.id}\" completed without a result`,\n })\n ),\n status,\n type,\n }\n}\n\n/** Format a finished task as the parts of a system inject. Layout:\n *\n * <task>{id, type, desc, status: \"done\", durationMs}</task>\n * {result body}\n *\n * The header is the standard `TaskInfo`-shaped JSON so consumers\n * (model, TUI) can parse it the same way they parse `task_list` and\n * heartbeat output — same shape everywhere a task surfaces.\n *\n * The body comes straight from `result.content`. For errors, that\n * already includes the `<error>{code, message, ...}</error>` MetaPart\n * + the formatted `❌ CODE: message` block (baked in by\n * `toErrorResult`), so this function doesn't need to special-case\n * errors — the structured tag and human body ride along with the\n * result content for any tool failure, anywhere.\n *\n * System messages can't carry attachments, so any image/pdf/etc. in\n * the result degrades to a `[image]` placeholder via\n * `stringifyContent` — best-effort, model still sees *something* was\n * there. */\nfunction formatTaskCompletion(task: DoneTaskInfo): (TextPart | MetaPart)[] {\n const { result, ...header } = task\n const parts: (TextPart | MetaPart)[] = [{ data: header, tag: \"task\", type: \"meta\" }]\n const bodyText = stringifyContent(result.content)\n if (bodyText !== \"\") parts.push({ text: bodyText, type: \"text\" })\n return parts\n}\n\n/** Build an `inject`-ready system message for a finished task. */\nexport function taskCompletionMessage(task: DoneTaskInfo): Message<\"system\"> {\n return {\n content: formatTaskCompletion(task),\n meta: { kind: \"task\", taskId: task.id },\n role: \"system\",\n }\n}\n"],"mappings":";;;;AAiBA,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;AAqHzB,IAAa,QAAb,cAA2B,QAAqB;CAC9C,uBAAgB,IAAI,IAA0B;CAC9C,UAAU;CAEV,SAAoD,CAAC;;;;;CAMrD;CACA;CAEA,IAAI,cAAkC;EACpC,OAAO,KAAK;CACd;CACA,IAAI,YAAY,OAA2B;EACzC,KAAK,eAAe;EACpB,KAAK,eAAe;CACtB;;CAKA,UAA+B;EAC7B,OAAO,CAAC,GAAG,KAAK,KAAK,OAAO,CAAC,CAAC,CAAC,QAAQ,MAAM,EAAE,WAAW,MAAM,CAAC,CAAC,KAAK,MAAM,WAAW,CAAC,CAAC;CAC5F;;;CAIA,WAAoC;EAClC,OAAO,CAAC,GAAG,KAAK,KAAK,OAAO,CAAC,CAAC,CAC3B,QAAQ,MAA8C,EAAE,WAAW,MAAM,CAAC,CAC1E,KAAK,MAAM,WAAW,CAAC,CAAiB;CAC7C;;CAGA,IAAI,IAAkC;EACpC,MAAM,IAAI,KAAK,KAAK,IAAI,EAAE;EAC1B,OAAO,IAAI,WAAW,CAAC,IAAI,KAAA;CAC7B;;CAGA,OAA4B;EAC1B,OAAO,CAAC,GAAG,KAAK,KAAK,OAAO,CAAC,CAAC,CAAC,IAAI,UAAU;CAC/C;CAEA,MAAM,QAAkC;EACtC,OAAO,OAAO,KAAK,WAAW,aAAa,KAAK,OAAO,IAAI,KAAK;CAClE;CAEA,IAAI,OAAO,OAAkD;EAC3D,KAAK,SAAS;CAChB;;;;;;CAOA,aAAa,IAAqB;EAChC,MAAM,IAAI,KAAK,KAAK,IAAI,EAAE;EAC1B,IAAI,GAAG,WAAW,aAAa,CAAC,EAAE,YAAY,OAAO;EACrD,OAAO,EAAE,WAAW,SAAS,KAAK;CACpC;;;;;;;;CASA,WAAW,IAA+C;EACxD,MAAM,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