@ai-setting/roy-task-plugin 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +72 -2
- package/dist/cli.js +1105 -0
- package/dist/index.js +2625 -0
- package/dist/index.js.map +162 -0
- package/package.json +33 -4
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/nodes/identity.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/visit.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/doc/directives.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/doc/anchors.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/doc/applyReviver.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/nodes/toJS.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/nodes/Node.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/nodes/Alias.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/nodes/Scalar.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/doc/createNode.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/nodes/Collection.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/stringify/stringifyComment.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/stringify/foldFlowLines.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/stringify/stringifyString.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/stringify/stringify.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/stringify/stringifyPair.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/log.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/yaml-1.1/merge.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/nodes/addPairToJSMap.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/nodes/Pair.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/stringify/stringifyCollection.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/nodes/YAMLMap.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/common/map.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/nodes/YAMLSeq.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/common/seq.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/common/string.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/common/null.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/core/bool.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/stringify/stringifyNumber.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/core/float.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/core/int.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/core/schema.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/json/schema.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/yaml-1.1/binary.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/yaml-1.1/pairs.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/yaml-1.1/omap.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/yaml-1.1/bool.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/yaml-1.1/float.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/yaml-1.1/int.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/yaml-1.1/set.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/yaml-1.1/schema.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/tags.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/schema/Schema.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/stringify/stringifyDocument.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/doc/Document.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/errors.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/resolve-props.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/util-contains-newline.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/util-flow-indent-check.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/util-map-includes.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/resolve-block-map.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/resolve-block-seq.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/resolve-end.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/resolve-flow-collection.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/compose-collection.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/resolve-block-scalar.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/resolve-flow-scalar.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/compose-scalar.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/util-empty-scalar-position.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/compose-node.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/compose-doc.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/compose/composer.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/parse/cst-scalar.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/parse/cst-stringify.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/parse/cst-visit.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/parse/cst.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/parse/lexer.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/parse/line-counter.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/parse/parser.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/public-api.js", "../../../node_modules/.bun/yaml@2.9.1/node_modules/yaml/dist/index.js", "../src/handlers/index.ts", "../../agent/src/roy-prompt.ts", "../../agent/src/roy-agent.ts", "../../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/util.js", "../../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/ZodError.js", "../../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/locales/en.js", "../../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/errors.js", "../../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/parseUtil.js", "../../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/helpers/errorUtil.js", "../../../node_modules/.bun/zod@3.25.76/node_modules/zod/v3/types.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-amkqnyzy.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-fs0mn2jk.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-jnszp0jq.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-8seq65bp.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-dsevjbck.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-qm9jda8p.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-5apmk4qw.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-7g03zkkb.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-rn57psp0.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-8gxth0eh.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-tbrn9wdm.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-yhsssn86.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-1pg0fepg.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-gdsqp6j8.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-qxnbvgwe.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-rx16h2m1.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-c1v263jn.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-k8b440n3.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-4z3rq5gw.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-p2r27era.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-7hh0brvs.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-qcspfszy.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-tdbv7ff4.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/shared/@ai-setting/roy-agent-core-39xejr39.js", "../../../node_modules/.bun/@ai-setting+roy-agent-core@1.7.53+c271ed38b8443377/node_modules/@ai-setting/roy-agent-core/dist/env/task/backend/index.js", "../../roy-bridge/src/facade.ts", "../../roy-bridge/src/mappers.ts", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/Options.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/Refs.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/errorMessages.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/getRelativePath.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/any.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/array.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/branded.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/catch.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/date.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/default.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/effects.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/enum.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/literal.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/string.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/record.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/map.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/never.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/null.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/union.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/number.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/object.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/optional.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/promise.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/set.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/selectParser.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/parseDef.js", "../../../node_modules/.bun/zod-to-json-schema@3.25.2+27912429049419a2/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js", "../../roy-bridge/src/tools.ts", "../src/roy-integration.ts", "../src/task-store/local.ts", "../../service/src/store/sqlite.ts", "../../client/src/http-client.ts", "../src/task-store/remote.ts", "../src/index.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"'use strict';\n\nconst ALIAS = Symbol.for('yaml.alias');\nconst DOC = Symbol.for('yaml.document');\nconst MAP = Symbol.for('yaml.map');\nconst PAIR = Symbol.for('yaml.pair');\nconst SCALAR = Symbol.for('yaml.scalar');\nconst SEQ = Symbol.for('yaml.seq');\nconst NODE_TYPE = Symbol.for('yaml.node.type');\nconst isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;\nconst isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;\nconst isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;\nconst isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;\nconst isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;\nconst isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;\nfunction isCollection(node) {\n if (node && typeof node === 'object')\n switch (node[NODE_TYPE]) {\n case MAP:\n case SEQ:\n return true;\n }\n return false;\n}\nfunction isNode(node) {\n if (node && typeof node === 'object')\n switch (node[NODE_TYPE]) {\n case ALIAS:\n case MAP:\n case SCALAR:\n case SEQ:\n return true;\n }\n return false;\n}\nconst hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;\n\nexports.ALIAS = ALIAS;\nexports.DOC = DOC;\nexports.MAP = MAP;\nexports.NODE_TYPE = NODE_TYPE;\nexports.PAIR = PAIR;\nexports.SCALAR = SCALAR;\nexports.SEQ = SEQ;\nexports.hasAnchor = hasAnchor;\nexports.isAlias = isAlias;\nexports.isCollection = isCollection;\nexports.isDocument = isDocument;\nexports.isMap = isMap;\nexports.isNode = isNode;\nexports.isPair = isPair;\nexports.isScalar = isScalar;\nexports.isSeq = isSeq;\n",
|
|
6
|
+
"'use strict';\n\nvar identity = require('./nodes/identity.js');\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove node');\n/**\n * Apply a visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n * - `key`: For sequence values and map `Pair`, the node's index in the\n * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n * `null` for the root node.\n * - `node`: The current node.\n * - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n * - `undefined` (default): Do nothing and continue\n * - `visit.SKIP`: Do not visit the children of this node, continue with next\n * sibling\n * - `visit.BREAK`: Terminate traversal completely\n * - `visit.REMOVE`: Remove the current node, then continue with the next one\n * - `Node`: Replace the current node, then continue by visiting it\n * - `number`: While iterating the items of a sequence or map, set the index\n * of the next step. This is useful especially if the index of the current\n * node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nfunction visit(node, visitor) {\n const visitor_ = initVisitor(visitor);\n if (identity.isDocument(node)) {\n const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));\n if (cd === REMOVE)\n node.contents = null;\n }\n else\n visit_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisit.SKIP = SKIP;\n/** Remove the current node */\nvisit.REMOVE = REMOVE;\nfunction visit_(key, node, visitor, path) {\n const ctrl = callVisitor(key, node, visitor, path);\n if (identity.isNode(ctrl) || identity.isPair(ctrl)) {\n replaceNode(key, path, ctrl);\n return visit_(key, ctrl, visitor, path);\n }\n if (typeof ctrl !== 'symbol') {\n if (identity.isCollection(node)) {\n path = Object.freeze(path.concat(node));\n for (let i = 0; i < node.items.length; ++i) {\n const ci = visit_(i, node.items[i], visitor, path);\n if (typeof ci === 'number')\n i = ci - 1;\n else if (ci === BREAK)\n return BREAK;\n else if (ci === REMOVE) {\n node.items.splice(i, 1);\n i -= 1;\n }\n }\n }\n else if (identity.isPair(node)) {\n path = Object.freeze(path.concat(node));\n const ck = visit_('key', node.key, visitor, path);\n if (ck === BREAK)\n return BREAK;\n else if (ck === REMOVE)\n node.key = null;\n const cv = visit_('value', node.value, visitor, path);\n if (cv === BREAK)\n return BREAK;\n else if (cv === REMOVE)\n node.value = null;\n }\n }\n return ctrl;\n}\n/**\n * Apply an async visitor to an AST node or document.\n *\n * Walks through the tree (depth-first) starting from `node`, calling a\n * `visitor` function with three arguments:\n * - `key`: For sequence values and map `Pair`, the node's index in the\n * collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.\n * `null` for the root node.\n * - `node`: The current node.\n * - `path`: The ancestry of the current node.\n *\n * The return value of the visitor may be used to control the traversal:\n * - `Promise`: Must resolve to one of the following values\n * - `undefined` (default): Do nothing and continue\n * - `visit.SKIP`: Do not visit the children of this node, continue with next\n * sibling\n * - `visit.BREAK`: Terminate traversal completely\n * - `visit.REMOVE`: Remove the current node, then continue with the next one\n * - `Node`: Replace the current node, then continue by visiting it\n * - `number`: While iterating the items of a sequence or map, set the index\n * of the next step. This is useful especially if the index of the current\n * node has changed.\n *\n * If `visitor` is a single function, it will be called with all values\n * encountered in the tree, including e.g. `null` values. Alternatively,\n * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,\n * `Alias` and `Scalar` node. To define the same visitor function for more than\n * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)\n * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most\n * specific defined one will be used for each node.\n */\nasync function visitAsync(node, visitor) {\n const visitor_ = initVisitor(visitor);\n if (identity.isDocument(node)) {\n const cd = await visitAsync_(null, node.contents, visitor_, Object.freeze([node]));\n if (cd === REMOVE)\n node.contents = null;\n }\n else\n await visitAsync_(null, node, visitor_, Object.freeze([]));\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisitAsync.BREAK = BREAK;\n/** Do not visit the children of the current node */\nvisitAsync.SKIP = SKIP;\n/** Remove the current node */\nvisitAsync.REMOVE = REMOVE;\nasync function visitAsync_(key, node, visitor, path) {\n const ctrl = await callVisitor(key, node, visitor, path);\n if (identity.isNode(ctrl) || identity.isPair(ctrl)) {\n replaceNode(key, path, ctrl);\n return visitAsync_(key, ctrl, visitor, path);\n }\n if (typeof ctrl !== 'symbol') {\n if (identity.isCollection(node)) {\n path = Object.freeze(path.concat(node));\n for (let i = 0; i < node.items.length; ++i) {\n const ci = await visitAsync_(i, node.items[i], visitor, path);\n if (typeof ci === 'number')\n i = ci - 1;\n else if (ci === BREAK)\n return BREAK;\n else if (ci === REMOVE) {\n node.items.splice(i, 1);\n i -= 1;\n }\n }\n }\n else if (identity.isPair(node)) {\n path = Object.freeze(path.concat(node));\n const ck = await visitAsync_('key', node.key, visitor, path);\n if (ck === BREAK)\n return BREAK;\n else if (ck === REMOVE)\n node.key = null;\n const cv = await visitAsync_('value', node.value, visitor, path);\n if (cv === BREAK)\n return BREAK;\n else if (cv === REMOVE)\n node.value = null;\n }\n }\n return ctrl;\n}\nfunction initVisitor(visitor) {\n if (typeof visitor === 'object' &&\n (visitor.Collection || visitor.Node || visitor.Value)) {\n return Object.assign({\n Alias: visitor.Node,\n Map: visitor.Node,\n Scalar: visitor.Node,\n Seq: visitor.Node\n }, visitor.Value && {\n Map: visitor.Value,\n Scalar: visitor.Value,\n Seq: visitor.Value\n }, visitor.Collection && {\n Map: visitor.Collection,\n Seq: visitor.Collection\n }, visitor);\n }\n return visitor;\n}\nfunction callVisitor(key, node, visitor, path) {\n if (typeof visitor === 'function')\n return visitor(key, node, path);\n if (identity.isMap(node))\n return visitor.Map?.(key, node, path);\n if (identity.isSeq(node))\n return visitor.Seq?.(key, node, path);\n if (identity.isPair(node))\n return visitor.Pair?.(key, node, path);\n if (identity.isScalar(node))\n return visitor.Scalar?.(key, node, path);\n if (identity.isAlias(node))\n return visitor.Alias?.(key, node, path);\n return undefined;\n}\nfunction replaceNode(key, path, node) {\n const parent = path[path.length - 1];\n if (identity.isCollection(parent)) {\n parent.items[key] = node;\n }\n else if (identity.isPair(parent)) {\n if (key === 'key')\n parent.key = node;\n else\n parent.value = node;\n }\n else if (identity.isDocument(parent)) {\n parent.contents = node;\n }\n else {\n const pt = identity.isAlias(parent) ? 'alias' : 'scalar';\n throw new Error(`Cannot replace node with ${pt} parent`);\n }\n}\n\nexports.visit = visit;\nexports.visitAsync = visitAsync;\n",
|
|
7
|
+
"'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar visit = require('../visit.js');\n\nconst escapeChars = {\n '!': '%21',\n ',': '%2C',\n '[': '%5B',\n ']': '%5D',\n '{': '%7B',\n '}': '%7D'\n};\nconst escapeTagName = (tn) => tn.replace(/[!,[\\]{}]/g, ch => escapeChars[ch]);\nclass Directives {\n constructor(yaml, tags) {\n /**\n * The directives-end/doc-start marker `---`. If `null`, a marker may still be\n * included in the document's stringified representation.\n */\n this.docStart = null;\n /** The doc-end marker `...`. */\n this.docEnd = false;\n this.yaml = Object.assign({}, Directives.defaultYaml, yaml);\n this.tags = Object.assign({}, Directives.defaultTags, tags);\n }\n clone() {\n const copy = new Directives(this.yaml, this.tags);\n copy.docStart = this.docStart;\n return copy;\n }\n /**\n * During parsing, get a Directives instance for the current document and\n * update the stream state according to the current version's spec.\n */\n atDocument() {\n const res = new Directives(this.yaml, this.tags);\n switch (this.yaml.version) {\n case '1.1':\n this.atNextDocument = true;\n break;\n case '1.2':\n this.atNextDocument = false;\n this.yaml = {\n explicit: Directives.defaultYaml.explicit,\n version: '1.2'\n };\n this.tags = Object.assign({}, Directives.defaultTags);\n break;\n }\n return res;\n }\n /**\n * @param onError - May be called even if the action was successful\n * @returns `true` on success\n */\n add(line, onError) {\n if (this.atNextDocument) {\n this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };\n this.tags = Object.assign({}, Directives.defaultTags);\n this.atNextDocument = false;\n }\n const parts = line.trim().split(/[ \\t]+/);\n const name = parts.shift();\n switch (name) {\n case '%TAG': {\n if (parts.length !== 2) {\n onError(0, '%TAG directive should contain exactly two parts');\n if (parts.length < 2)\n return false;\n }\n const [handle, prefix] = parts;\n this.tags[handle] = prefix;\n return true;\n }\n case '%YAML': {\n this.yaml.explicit = true;\n if (parts.length !== 1) {\n onError(0, '%YAML directive should contain exactly one part');\n return false;\n }\n const [version] = parts;\n if (version === '1.1' || version === '1.2') {\n this.yaml.version = version;\n return true;\n }\n else {\n const isValid = /^\\d+\\.\\d+$/.test(version);\n onError(6, `Unsupported YAML version ${version}`, isValid);\n return false;\n }\n }\n default:\n onError(0, `Unknown directive ${name}`, true);\n return false;\n }\n }\n /**\n * Resolves a tag, matching handles to those defined in %TAG directives.\n *\n * @returns Resolved tag, which may also be the non-specific tag `'!'` or a\n * `'!local'` tag, or `null` if unresolvable.\n */\n tagName(source, onError) {\n if (source === '!')\n return '!'; // non-specific tag\n if (source[0] !== '!') {\n onError(`Not a valid tag: ${source}`);\n return null;\n }\n if (source[1] === '<') {\n const verbatim = source.slice(2, -1);\n if (verbatim === '!' || verbatim === '!!') {\n onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);\n return null;\n }\n if (source[source.length - 1] !== '>')\n onError('Verbatim tags must end with a >');\n return verbatim;\n }\n const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);\n if (!suffix)\n onError(`The ${source} tag has no suffix`);\n const prefix = this.tags[handle];\n if (prefix) {\n try {\n return prefix + decodeURIComponent(suffix);\n }\n catch (error) {\n onError(String(error));\n return null;\n }\n }\n if (handle === '!')\n return source; // local tag\n onError(`Could not resolve tag: ${source}`);\n return null;\n }\n /**\n * Given a fully resolved tag, returns its printable string form,\n * taking into account current tag prefixes and defaults.\n */\n tagString(tag) {\n for (const [handle, prefix] of Object.entries(this.tags)) {\n if (tag.startsWith(prefix))\n return handle + escapeTagName(tag.substring(prefix.length));\n }\n return tag[0] === '!' ? tag : `!<${tag}>`;\n }\n toString(doc) {\n const lines = this.yaml.explicit\n ? [`%YAML ${this.yaml.version || '1.2'}`]\n : [];\n const tagEntries = Object.entries(this.tags);\n let tagNames;\n if (doc && tagEntries.length > 0 && identity.isNode(doc.contents)) {\n const tags = {};\n visit.visit(doc.contents, (_key, node) => {\n if (identity.isNode(node) && node.tag)\n tags[node.tag] = true;\n });\n tagNames = Object.keys(tags);\n }\n else\n tagNames = [];\n for (const [handle, prefix] of tagEntries) {\n if (handle === '!!' && prefix === 'tag:yaml.org,2002:')\n continue;\n if (!doc || tagNames.some(tn => tn.startsWith(prefix)))\n lines.push(`%TAG ${handle} ${prefix}`);\n }\n return lines.join('\\n');\n }\n}\nDirectives.defaultYaml = { explicit: false, version: '1.2' };\nDirectives.defaultTags = { '!!': 'tag:yaml.org,2002:' };\n\nexports.Directives = Directives;\n",
|
|
8
|
+
"'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar visit = require('../visit.js');\n\n/**\n * Verify that the input string is a valid anchor.\n *\n * Will throw on errors.\n */\nfunction anchorIsValid(anchor) {\n if (/[\\x00-\\x19\\s,[\\]{}]/.test(anchor)) {\n const sa = JSON.stringify(anchor);\n const msg = `Anchor must not contain whitespace or control characters: ${sa}`;\n throw new Error(msg);\n }\n return true;\n}\nfunction anchorNames(root) {\n const anchors = new Set();\n visit.visit(root, {\n Value(_key, node) {\n if (node.anchor)\n anchors.add(node.anchor);\n }\n });\n return anchors;\n}\n/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */\nfunction findNewAnchor(prefix, exclude) {\n for (let i = 1; true; ++i) {\n const name = `${prefix}${i}`;\n if (!exclude.has(name))\n return name;\n }\n}\nfunction createNodeAnchors(doc, prefix) {\n const aliasObjects = [];\n const sourceObjects = new Map();\n let prevAnchors = null;\n return {\n onAnchor: (source) => {\n aliasObjects.push(source);\n prevAnchors ?? (prevAnchors = anchorNames(doc));\n const anchor = findNewAnchor(prefix, prevAnchors);\n prevAnchors.add(anchor);\n return anchor;\n },\n /**\n * With circular references, the source node is only resolved after all\n * of its child nodes are. This is why anchors are set only after all of\n * the nodes have been created.\n */\n setAnchors: () => {\n for (const source of aliasObjects) {\n const ref = sourceObjects.get(source);\n if (typeof ref === 'object' &&\n ref.anchor &&\n (identity.isScalar(ref.node) || identity.isCollection(ref.node))) {\n ref.node.anchor = ref.anchor;\n }\n else {\n const error = new Error('Failed to resolve repeated object (this should not happen)');\n error.source = source;\n throw error;\n }\n }\n },\n sourceObjects\n };\n}\n\nexports.anchorIsValid = anchorIsValid;\nexports.anchorNames = anchorNames;\nexports.createNodeAnchors = createNodeAnchors;\nexports.findNewAnchor = findNewAnchor;\n",
|
|
9
|
+
"'use strict';\n\n/**\n * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,\n * in section 24.5.1.1 \"Runtime Semantics: InternalizeJSONProperty\" of the\n * 2021 edition: https://tc39.es/ecma262/#sec-json.parse\n *\n * Includes extensions for handling Map and Set objects.\n */\nfunction applyReviver(reviver, obj, key, val) {\n if (val && typeof val === 'object') {\n if (Array.isArray(val)) {\n for (let i = 0, len = val.length; i < len; ++i) {\n const v0 = val[i];\n const v1 = applyReviver(reviver, val, String(i), v0);\n // eslint-disable-next-line @typescript-eslint/no-array-delete\n if (v1 === undefined)\n delete val[i];\n else if (v1 !== v0)\n val[i] = v1;\n }\n }\n else if (val instanceof Map) {\n for (const k of Array.from(val.keys())) {\n const v0 = val.get(k);\n const v1 = applyReviver(reviver, val, k, v0);\n if (v1 === undefined)\n val.delete(k);\n else if (v1 !== v0)\n val.set(k, v1);\n }\n }\n else if (val instanceof Set) {\n for (const v0 of Array.from(val)) {\n const v1 = applyReviver(reviver, val, v0, v0);\n if (v1 === undefined)\n val.delete(v0);\n else if (v1 !== v0) {\n val.delete(v0);\n val.add(v1);\n }\n }\n }\n else {\n for (const [k, v0] of Object.entries(val)) {\n const v1 = applyReviver(reviver, val, k, v0);\n if (v1 === undefined)\n delete val[k];\n else if (v1 !== v0)\n val[k] = v1;\n }\n }\n }\n return reviver.call(obj, key, val);\n}\n\nexports.applyReviver = applyReviver;\n",
|
|
10
|
+
"'use strict';\n\nvar identity = require('./identity.js');\n\n/**\n * Recursively convert any node or its contents to native JavaScript\n *\n * @param value - The input value\n * @param arg - If `value` defines a `toJSON()` method, use this\n * as its first argument\n * @param ctx - Conversion context, originally set in Document#toJS(). If\n * `{ keep: true }` is not set, output should be suitable for JSON\n * stringification.\n */\nfunction toJS(value, arg, ctx) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n if (Array.isArray(value))\n return value.map((v, i) => toJS(v, String(i), ctx));\n if (value && typeof value.toJSON === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n if (!ctx || !identity.hasAnchor(value))\n return value.toJSON(arg, ctx);\n const data = { aliasCount: 0, count: 1, res: undefined };\n ctx.anchors.set(value, data);\n ctx.onCreate = res => {\n data.res = res;\n delete ctx.onCreate;\n };\n const res = value.toJSON(arg, ctx);\n if (ctx.onCreate)\n ctx.onCreate(res);\n return res;\n }\n if (typeof value === 'bigint' && !ctx?.keep)\n return Number(value);\n return value;\n}\n\nexports.toJS = toJS;\n",
|
|
11
|
+
"'use strict';\n\nvar applyReviver = require('../doc/applyReviver.js');\nvar identity = require('./identity.js');\nvar toJS = require('./toJS.js');\n\nclass NodeBase {\n constructor(type) {\n Object.defineProperty(this, identity.NODE_TYPE, { value: type });\n }\n /** Create a copy of this node. */\n clone() {\n const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }\n /** A plain JavaScript representation of this node. */\n toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n if (!identity.isDocument(doc))\n throw new TypeError('A document argument is required');\n const ctx = {\n anchors: new Map(),\n doc,\n keep: true,\n mapAsMap: mapAsMap === true,\n mapKeyWarned: false,\n maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n };\n const res = toJS.toJS(this, '', ctx);\n if (typeof onAnchor === 'function')\n for (const { count, res } of ctx.anchors.values())\n onAnchor(res, count);\n return typeof reviver === 'function'\n ? applyReviver.applyReviver(reviver, { '': res }, '', res)\n : res;\n }\n}\n\nexports.NodeBase = NodeBase;\n",
|
|
12
|
+
"'use strict';\n\nvar anchors = require('../doc/anchors.js');\nvar visit = require('../visit.js');\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\nvar toJS = require('./toJS.js');\n\nclass Alias extends Node.NodeBase {\n constructor(source) {\n super(identity.ALIAS);\n this.source = source;\n Object.defineProperty(this, 'tag', {\n set() {\n throw new Error('Alias nodes cannot have tags');\n }\n });\n }\n /**\n * Resolve the value of this alias within `doc`, finding the last\n * instance of the `source` anchor before this node.\n */\n resolve(doc, ctx) {\n if (ctx?.maxAliasCount === 0)\n throw new ReferenceError('Alias resolution is disabled');\n let nodes;\n if (ctx?.aliasResolveCache) {\n nodes = ctx.aliasResolveCache;\n }\n else {\n nodes = [];\n visit.visit(doc, {\n Node: (_key, node) => {\n if (identity.isAlias(node) || identity.hasAnchor(node))\n nodes.push(node);\n }\n });\n if (ctx)\n ctx.aliasResolveCache = nodes;\n }\n let found = undefined;\n for (const node of nodes) {\n if (node === this)\n break;\n if (node.anchor === this.source)\n found = node;\n }\n if (found && ctx) {\n const { anchors, doc, maxAliasCount } = ctx;\n let data = anchors.get(found);\n if (!data) {\n // Resolve anchors for Node.prototype.toJS()\n toJS.toJS(found, null, ctx);\n data = anchors.get(found);\n }\n /* istanbul ignore if */\n if (data?.res === undefined) {\n const msg = 'This should not happen: Alias anchor was not resolved?';\n throw new ReferenceError(msg);\n }\n if (maxAliasCount >= 0) {\n data.count += 1;\n if (data.aliasCount === 0)\n data.aliasCount = getAliasCount(doc, found, anchors);\n if (data.count * data.aliasCount > maxAliasCount) {\n const msg = 'Excessive alias count indicates a resource exhaustion attack';\n throw new ReferenceError(msg);\n }\n }\n }\n return found;\n }\n toJSON(_arg, ctx) {\n if (!ctx)\n return { source: this.source };\n const source = this.resolve(ctx.doc, ctx);\n if (!source) {\n const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n throw new ReferenceError(msg);\n }\n return ctx.anchors.get(source).res;\n }\n toString(ctx, _onComment, _onChompKeep) {\n const src = `*${this.source}`;\n if (ctx) {\n anchors.anchorIsValid(this.source);\n if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {\n const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;\n throw new Error(msg);\n }\n if (ctx.implicitKey)\n return `${src} `;\n }\n return src;\n }\n}\nfunction getAliasCount(doc, node, anchors) {\n if (identity.isAlias(node)) {\n const source = node.resolve(doc);\n const anchor = anchors && source && anchors.get(source);\n return anchor ? anchor.count * anchor.aliasCount : 0;\n }\n else if (identity.isCollection(node)) {\n let count = 0;\n for (const item of node.items) {\n const c = getAliasCount(doc, item, anchors);\n if (c > count)\n count = c;\n }\n return count;\n }\n else if (identity.isPair(node)) {\n const kc = getAliasCount(doc, node.key, anchors);\n const vc = getAliasCount(doc, node.value, anchors);\n return Math.max(kc, vc);\n }\n return 1;\n}\n\nexports.Alias = Alias;\n",
|
|
13
|
+
"'use strict';\n\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\nvar toJS = require('./toJS.js');\n\nconst isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');\nclass Scalar extends Node.NodeBase {\n constructor(value) {\n super(identity.SCALAR);\n this.value = value;\n }\n toJSON(arg, ctx) {\n return ctx?.keep ? this.value : toJS.toJS(this.value, arg, ctx);\n }\n toString() {\n return String(this.value);\n }\n}\nScalar.BLOCK_FOLDED = 'BLOCK_FOLDED';\nScalar.BLOCK_LITERAL = 'BLOCK_LITERAL';\nScalar.PLAIN = 'PLAIN';\nScalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';\nScalar.QUOTE_SINGLE = 'QUOTE_SINGLE';\n\nexports.Scalar = Scalar;\nexports.isScalarValue = isScalarValue;\n",
|
|
14
|
+
"'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\n\nconst defaultTagPrefix = 'tag:yaml.org,2002:';\nfunction findTagObject(value, tagName, tags) {\n if (tagName) {\n const match = tags.filter(t => t.tag === tagName);\n const tagObj = match.find(t => !t.format) ?? match[0];\n if (!tagObj)\n throw new Error(`Tag ${tagName} not found`);\n return tagObj;\n }\n return tags.find(t => t.identify?.(value) && !t.format);\n}\nfunction createNode(value, tagName, ctx) {\n if (identity.isDocument(value))\n value = value.contents;\n if (identity.isNode(value))\n return value;\n if (identity.isPair(value)) {\n const map = ctx.schema[identity.MAP].createNode?.(ctx.schema, null, ctx);\n map.items.push(value);\n return map;\n }\n if (value instanceof String ||\n value instanceof Number ||\n value instanceof Boolean ||\n (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere\n ) {\n // https://tc39.es/ecma262/#sec-serializejsonproperty\n value = value.valueOf();\n }\n const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;\n // Detect duplicate references to the same object & use Alias nodes for all\n // after first. The `ref` wrapper allows for circular references to resolve.\n let ref = undefined;\n if (aliasDuplicateObjects && value && typeof value === 'object') {\n ref = sourceObjects.get(value);\n if (ref) {\n ref.anchor ?? (ref.anchor = onAnchor(value));\n return new Alias.Alias(ref.anchor);\n }\n else {\n ref = { anchor: null, node: null };\n sourceObjects.set(value, ref);\n }\n }\n if (tagName?.startsWith('!!'))\n tagName = defaultTagPrefix + tagName.slice(2);\n let tagObj = findTagObject(value, tagName, schema.tags);\n if (!tagObj) {\n if (value && typeof value.toJSON === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-call\n value = value.toJSON();\n }\n if (!value || typeof value !== 'object') {\n const node = new Scalar.Scalar(value);\n if (ref)\n ref.node = node;\n return node;\n }\n tagObj =\n value instanceof Map\n ? schema[identity.MAP]\n : Symbol.iterator in Object(value)\n ? schema[identity.SEQ]\n : schema[identity.MAP];\n }\n if (onTagObj) {\n onTagObj(tagObj);\n delete ctx.onTagObj;\n }\n const node = tagObj?.createNode\n ? tagObj.createNode(ctx.schema, value, ctx)\n : typeof tagObj?.nodeClass?.from === 'function'\n ? tagObj.nodeClass.from(ctx.schema, value, ctx)\n : new Scalar.Scalar(value);\n if (tagName)\n node.tag = tagName;\n else if (!tagObj.default)\n node.tag = tagObj.tag;\n if (ref)\n ref.node = node;\n return node;\n}\n\nexports.createNode = createNode;\n",
|
|
15
|
+
"'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar identity = require('./identity.js');\nvar Node = require('./Node.js');\n\nfunction collectionFromPath(schema, path, value) {\n let v = value;\n for (let i = path.length - 1; i >= 0; --i) {\n const k = path[i];\n if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {\n const a = [];\n a[k] = v;\n v = a;\n }\n else {\n v = new Map([[k, v]]);\n }\n }\n return createNode.createNode(v, undefined, {\n aliasDuplicateObjects: false,\n keepUndefined: false,\n onAnchor: () => {\n throw new Error('This should not happen, please report a bug.');\n },\n schema,\n sourceObjects: new Map()\n });\n}\n// Type guard is intentionally a little wrong so as to be more useful,\n// as it does not cover untypable empty non-string iterables (e.g. []).\nconst isEmptyPath = (path) => path == null ||\n (typeof path === 'object' && !!path[Symbol.iterator]().next().done);\nclass Collection extends Node.NodeBase {\n constructor(type, schema) {\n super(type);\n Object.defineProperty(this, 'schema', {\n value: schema,\n configurable: true,\n enumerable: false,\n writable: true\n });\n }\n /**\n * Create a copy of this collection.\n *\n * @param schema - If defined, overwrites the original's schema\n */\n clone(schema) {\n const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));\n if (schema)\n copy.schema = schema;\n copy.items = copy.items.map(it => identity.isNode(it) || identity.isPair(it) ? it.clone(schema) : it);\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }\n /**\n * Adds a value to the collection. For `!!map` and `!!omap` the value must\n * be a Pair instance or a `{ key, value }` object, which may not have a key\n * that already exists in the map.\n */\n addIn(path, value) {\n if (isEmptyPath(path))\n this.add(value);\n else {\n const [key, ...rest] = path;\n const node = this.get(key, true);\n if (identity.isCollection(node))\n node.addIn(rest, value);\n else if (node === undefined && this.schema)\n this.set(key, collectionFromPath(this.schema, rest, value));\n else\n throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n }\n }\n /**\n * Removes a value from the collection.\n * @returns `true` if the item was found and removed.\n */\n deleteIn(path) {\n const [key, ...rest] = path;\n if (rest.length === 0)\n return this.delete(key);\n const node = this.get(key, true);\n if (identity.isCollection(node))\n return node.deleteIn(rest);\n else\n throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n }\n /**\n * Returns item at `key`, or `undefined` if not found. By default unwraps\n * scalar values from their surrounding node; to disable set `keepScalar` to\n * `true` (collections are always returned intact).\n */\n getIn(path, keepScalar) {\n const [key, ...rest] = path;\n const node = this.get(key, true);\n if (rest.length === 0)\n return !keepScalar && identity.isScalar(node) ? node.value : node;\n else\n return identity.isCollection(node) ? node.getIn(rest, keepScalar) : undefined;\n }\n hasAllNullValues(allowScalar) {\n return this.items.every(node => {\n if (!identity.isPair(node))\n return false;\n const n = node.value;\n return (n == null ||\n (allowScalar &&\n identity.isScalar(n) &&\n n.value == null &&\n !n.commentBefore &&\n !n.comment &&\n !n.tag));\n });\n }\n /**\n * Checks if the collection includes a value with the key `key`.\n */\n hasIn(path) {\n const [key, ...rest] = path;\n if (rest.length === 0)\n return this.has(key);\n const node = this.get(key, true);\n return identity.isCollection(node) ? node.hasIn(rest) : false;\n }\n /**\n * Sets a value in this collection. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n */\n setIn(path, value) {\n const [key, ...rest] = path;\n if (rest.length === 0) {\n this.set(key, value);\n }\n else {\n const node = this.get(key, true);\n if (identity.isCollection(node))\n node.setIn(rest, value);\n else if (node === undefined && this.schema)\n this.set(key, collectionFromPath(this.schema, rest, value));\n else\n throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);\n }\n }\n}\n\nexports.Collection = Collection;\nexports.collectionFromPath = collectionFromPath;\nexports.isEmptyPath = isEmptyPath;\n",
|
|
16
|
+
"'use strict';\n\n/**\n * Stringifies a comment.\n *\n * Empty comment lines are left empty,\n * lines consisting of a single space are replaced by `#`,\n * and all other lines are prefixed with a `#`.\n */\nconst stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');\nfunction indentComment(comment, indent) {\n if (/^\\n+$/.test(comment))\n return comment.substring(1);\n return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;\n}\nconst lineComment = (str, indent, comment) => str.endsWith('\\n')\n ? indentComment(comment, indent)\n : comment.includes('\\n')\n ? '\\n' + indentComment(comment, indent)\n : (str.endsWith(' ') ? '' : ' ') + comment;\n\nexports.indentComment = indentComment;\nexports.lineComment = lineComment;\nexports.stringifyComment = stringifyComment;\n",
|
|
17
|
+
"'use strict';\n\nconst FOLD_FLOW = 'flow';\nconst FOLD_BLOCK = 'block';\nconst FOLD_QUOTED = 'quoted';\n/**\n * Tries to keep input at up to `lineWidth` characters, splitting only on spaces\n * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are\n * terminated with `\\n` and started with `indent`.\n */\nfunction foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {\n if (!lineWidth || lineWidth < 0)\n return text;\n if (lineWidth < minContentWidth)\n minContentWidth = 0;\n const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);\n if (text.length <= endStep)\n return text;\n const folds = [];\n const escapedFolds = {};\n let end = lineWidth - indent.length;\n if (typeof indentAtStart === 'number') {\n if (indentAtStart > lineWidth - Math.max(2, minContentWidth))\n folds.push(0);\n else\n end = lineWidth - indentAtStart;\n }\n let split = undefined;\n let prev = undefined;\n let overflow = false;\n let i = -1;\n let escStart = -1;\n let escEnd = -1;\n if (mode === FOLD_BLOCK) {\n i = consumeMoreIndentedLines(text, i, indent.length);\n if (i !== -1)\n end = i + endStep;\n }\n for (let ch; (ch = text[(i += 1)]);) {\n if (mode === FOLD_QUOTED && ch === '\\\\') {\n escStart = i;\n switch (text[i + 1]) {\n case 'x':\n i += 3;\n break;\n case 'u':\n i += 5;\n break;\n case 'U':\n i += 9;\n break;\n default:\n i += 1;\n }\n escEnd = i;\n }\n if (ch === '\\n') {\n if (mode === FOLD_BLOCK)\n i = consumeMoreIndentedLines(text, i, indent.length);\n end = i + indent.length + endStep;\n split = undefined;\n }\n else {\n if (ch === ' ' &&\n prev &&\n prev !== ' ' &&\n prev !== '\\n' &&\n prev !== '\\t') {\n // space surrounded by non-space can be replaced with newline + indent\n const next = text[i + 1];\n if (next && next !== ' ' && next !== '\\n' && next !== '\\t')\n split = i;\n }\n if (i >= end) {\n if (split) {\n folds.push(split);\n end = split + endStep;\n split = undefined;\n }\n else if (mode === FOLD_QUOTED) {\n // white-space collected at end may stretch past lineWidth\n while (prev === ' ' || prev === '\\t') {\n prev = ch;\n ch = text[(i += 1)];\n overflow = true;\n }\n // Account for newline escape, but don't break preceding escape\n const j = i > escEnd + 1 ? i - 2 : escStart - 1;\n // Bail out if lineWidth & minContentWidth are shorter than an escape string\n if (escapedFolds[j])\n return text;\n folds.push(j);\n escapedFolds[j] = true;\n end = j + endStep;\n split = undefined;\n }\n else {\n overflow = true;\n }\n }\n }\n prev = ch;\n }\n if (overflow && onOverflow)\n onOverflow();\n if (folds.length === 0)\n return text;\n if (onFold)\n onFold();\n let res = text.slice(0, folds[0]);\n for (let i = 0; i < folds.length; ++i) {\n const fold = folds[i];\n const end = folds[i + 1] || text.length;\n if (fold === 0)\n res = `\\n${indent}${text.slice(0, end)}`;\n else {\n if (mode === FOLD_QUOTED && escapedFolds[fold])\n res += `${text[fold]}\\\\`;\n res += `\\n${indent}${text.slice(fold + 1, end)}`;\n }\n }\n return res;\n}\n/**\n * Presumes `i + 1` is at the start of a line\n * @returns index of last newline in more-indented block\n */\nfunction consumeMoreIndentedLines(text, i, indent) {\n let end = i;\n let start = i + 1;\n let ch = text[start];\n while (ch === ' ' || ch === '\\t') {\n if (i < start + indent) {\n ch = text[++i];\n }\n else {\n do {\n ch = text[++i];\n } while (ch && ch !== '\\n');\n end = i;\n start = i + 1;\n ch = text[start];\n }\n }\n return end;\n}\n\nexports.FOLD_BLOCK = FOLD_BLOCK;\nexports.FOLD_FLOW = FOLD_FLOW;\nexports.FOLD_QUOTED = FOLD_QUOTED;\nexports.foldFlowLines = foldFlowLines;\n",
|
|
18
|
+
"'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\nvar foldFlowLines = require('./foldFlowLines.js');\n\nconst getFoldOptions = (ctx, isBlock) => ({\n indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,\n lineWidth: ctx.options.lineWidth,\n minContentWidth: ctx.options.minContentWidth\n});\n// Also checks for lines starting with %, as parsing the output as YAML 1.1 will\n// presume that's starting a new document.\nconst containsDocumentMarker = (str) => /^(%|---|\\.\\.\\.)/m.test(str);\nfunction lineLengthOverLimit(str, lineWidth, indentLength) {\n if (!lineWidth || lineWidth < 0)\n return false;\n const limit = lineWidth - indentLength;\n const strLen = str.length;\n if (strLen <= limit)\n return false;\n for (let i = 0, start = 0; i < strLen; ++i) {\n if (str[i] === '\\n') {\n if (i - start > limit)\n return true;\n start = i + 1;\n if (strLen - start <= limit)\n return false;\n }\n }\n return true;\n}\nfunction doubleQuotedString(value, ctx) {\n const json = JSON.stringify(value);\n if (ctx.options.doubleQuotedAsJSON)\n return json;\n const { implicitKey } = ctx;\n const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;\n const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');\n let str = '';\n let start = 0;\n for (let i = 0, ch = json[i]; ch; ch = json[++i]) {\n if (ch === ' ' && json[i + 1] === '\\\\' && json[i + 2] === 'n') {\n // space before newline needs to be escaped to not be folded\n str += json.slice(start, i) + '\\\\ ';\n i += 1;\n start = i;\n ch = '\\\\';\n }\n if (ch === '\\\\')\n switch (json[i + 1]) {\n case 'u':\n {\n str += json.slice(start, i);\n const code = json.substr(i + 2, 4);\n switch (code) {\n case '0000':\n str += '\\\\0';\n break;\n case '0007':\n str += '\\\\a';\n break;\n case '000b':\n str += '\\\\v';\n break;\n case '001b':\n str += '\\\\e';\n break;\n case '0085':\n str += '\\\\N';\n break;\n case '00a0':\n str += '\\\\_';\n break;\n case '2028':\n str += '\\\\L';\n break;\n case '2029':\n str += '\\\\P';\n break;\n default:\n if (code.substr(0, 2) === '00')\n str += '\\\\x' + code.substr(2);\n else\n str += json.substr(i, 6);\n }\n i += 5;\n start = i + 1;\n }\n break;\n case 'n':\n if (implicitKey ||\n json[i + 2] === '\"' ||\n json.length < minMultiLineLength) {\n i += 1;\n }\n else {\n // folding will eat first newline\n str += json.slice(start, i) + '\\n\\n';\n while (json[i + 2] === '\\\\' &&\n json[i + 3] === 'n' &&\n json[i + 4] !== '\"') {\n str += '\\n';\n i += 2;\n }\n str += indent;\n // space after newline needs to be escaped to not be folded\n if (json[i + 2] === ' ')\n str += '\\\\';\n i += 1;\n start = i + 1;\n }\n break;\n default:\n i += 1;\n }\n }\n str = start ? str + json.slice(start) : json;\n return implicitKey\n ? str\n : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_QUOTED, getFoldOptions(ctx, false));\n}\nfunction singleQuotedString(value, ctx) {\n if (ctx.options.singleQuote === false ||\n (ctx.implicitKey && value.includes('\\n')) ||\n /[ \\t]\\n|\\n[ \\t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline\n )\n return doubleQuotedString(value, ctx);\n const indent = ctx.indent || (containsDocumentMarker(value) ? ' ' : '');\n const res = \"'\" + value.replace(/'/g, \"''\").replace(/\\n+/g, `$&\\n${indent}`) + \"'\";\n return ctx.implicitKey\n ? res\n : foldFlowLines.foldFlowLines(res, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction quotedString(value, ctx) {\n const { singleQuote } = ctx.options;\n let qs;\n if (singleQuote === false)\n qs = doubleQuotedString;\n else {\n const hasDouble = value.includes('\"');\n const hasSingle = value.includes(\"'\");\n if (hasDouble && !hasSingle)\n qs = singleQuotedString;\n else if (hasSingle && !hasDouble)\n qs = doubleQuotedString;\n else\n qs = singleQuote ? singleQuotedString : doubleQuotedString;\n }\n return qs(value, ctx);\n}\n// The negative lookbehind avoids a polynomial search,\n// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind\nlet blockEndNewlines;\ntry {\n blockEndNewlines = new RegExp('(^|(?<!\\n))\\n+(?!\\n|$)', 'g');\n}\ncatch {\n blockEndNewlines = /\\n+(?!\\n|$)/g;\n}\nfunction blockString({ comment, type, value }, ctx, onComment, onChompKeep) {\n const { blockQuote, commentString, lineWidth } = ctx.options;\n // 1. Block can't end in whitespace unless the last line is non-empty.\n // 2. Strings consisting of only whitespace are best rendered explicitly.\n if (!blockQuote || /\\n[\\t ]+$/.test(value)) {\n return quotedString(value, ctx);\n }\n const indent = ctx.indent ||\n (ctx.forceBlockIndent || containsDocumentMarker(value) ? ' ' : '');\n const literal = blockQuote === 'literal'\n ? true\n : blockQuote === 'folded' || type === Scalar.Scalar.BLOCK_FOLDED\n ? false\n : type === Scalar.Scalar.BLOCK_LITERAL\n ? true\n : !lineLengthOverLimit(value, lineWidth, indent.length);\n if (!value)\n return literal ? '|\\n' : '>\\n';\n // determine chomping from whitespace at value end\n let chomp;\n let endStart;\n for (endStart = value.length; endStart > 0; --endStart) {\n const ch = value[endStart - 1];\n if (ch !== '\\n' && ch !== '\\t' && ch !== ' ')\n break;\n }\n let end = value.substring(endStart);\n const endNlPos = end.indexOf('\\n');\n if (endNlPos === -1) {\n chomp = '-'; // strip\n }\n else if (value === end || endNlPos !== end.length - 1) {\n chomp = '+'; // keep\n if (onChompKeep)\n onChompKeep();\n }\n else {\n chomp = ''; // clip\n }\n if (end) {\n value = value.slice(0, -end.length);\n if (end[end.length - 1] === '\\n')\n end = end.slice(0, -1);\n end = end.replace(blockEndNewlines, `$&${indent}`);\n }\n // determine indent indicator from whitespace at value start\n let startWithSpace = false;\n let startEnd;\n let startNlPos = -1;\n for (startEnd = 0; startEnd < value.length; ++startEnd) {\n const ch = value[startEnd];\n if (ch === ' ')\n startWithSpace = true;\n else if (ch === '\\n')\n startNlPos = startEnd;\n else\n break;\n }\n let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);\n if (start) {\n value = value.substring(start.length);\n start = start.replace(/\\n+/g, `$&${indent}`);\n }\n const indentSize = indent ? '2' : '1'; // root is at -1\n // Leading | or > is added later\n let header = (startWithSpace ? indentSize : '') + chomp;\n if (comment) {\n header += ' ' + commentString(comment.replace(/ ?[\\r\\n]+/g, ' '));\n if (onComment)\n onComment();\n }\n if (!literal) {\n const foldedValue = value\n .replace(/\\n+/g, '\\n$&')\n .replace(/(?:^|\\n)([\\t ].*)(?:([\\n\\t ]*)\\n(?![\\n\\t ]))?/g, '$1$2') // more-indented lines aren't folded\n // ^ more-ind. ^ empty ^ capture next empty lines only at end of indent\n .replace(/\\n+/g, `$&${indent}`);\n let literalFallback = false;\n const foldOptions = getFoldOptions(ctx, true);\n if (blockQuote !== 'folded' && type !== Scalar.Scalar.BLOCK_FOLDED) {\n foldOptions.onOverflow = () => {\n literalFallback = true;\n };\n }\n const body = foldFlowLines.foldFlowLines(`${start}${foldedValue}${end}`, indent, foldFlowLines.FOLD_BLOCK, foldOptions);\n if (!literalFallback)\n return `>${header}\\n${indent}${body}`;\n }\n value = value.replace(/\\n+/g, `$&${indent}`);\n return `|${header}\\n${indent}${start}${value}${end}`;\n}\nfunction plainString(item, ctx, onComment, onChompKeep) {\n const { type, value } = item;\n const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;\n if ((implicitKey && value.includes('\\n')) ||\n (inFlow && /[[\\]{},]/.test(value))) {\n return quotedString(value, ctx);\n }\n if (/^[\\n\\t ,[\\]{}#&*!|>'\"%@`]|^[?-]$|^[?-][ \\t]|[\\n:][ \\t]|[ \\t]\\n|[\\n\\t ]#|[\\n\\t :]$/.test(value)) {\n // not allowed:\n // - '-' or '?'\n // - start with an indicator character (except [?:-]) or /[?-] /\n // - '\\n ', ': ' or ' \\n' anywhere\n // - '#' not preceded by a non-space char\n // - end with ' ' or ':'\n return implicitKey || inFlow || !value.includes('\\n')\n ? quotedString(value, ctx)\n : blockString(item, ctx, onComment, onChompKeep);\n }\n if (!implicitKey &&\n !inFlow &&\n type !== Scalar.Scalar.PLAIN &&\n value.includes('\\n')) {\n // Where allowed & type not set explicitly, prefer block style for multiline strings\n return blockString(item, ctx, onComment, onChompKeep);\n }\n if (containsDocumentMarker(value)) {\n if (indent === '') {\n ctx.forceBlockIndent = true;\n return blockString(item, ctx, onComment, onChompKeep);\n }\n else if (implicitKey && indent === indentStep) {\n return quotedString(value, ctx);\n }\n }\n const str = value.replace(/\\n+/g, `$&\\n${indent}`);\n // Verify that output will be parsed as a string, as e.g. plain numbers and\n // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),\n // and others in v1.1.\n if (actualString) {\n const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);\n const { compat, tags } = ctx.doc.schema;\n if (tags.some(test) || compat?.some(test))\n return quotedString(value, ctx);\n }\n return implicitKey\n ? str\n : foldFlowLines.foldFlowLines(str, indent, foldFlowLines.FOLD_FLOW, getFoldOptions(ctx, false));\n}\nfunction stringifyString(item, ctx, onComment, onChompKeep) {\n const { implicitKey, inFlow } = ctx;\n const ss = typeof item.value === 'string'\n ? item\n : Object.assign({}, item, { value: String(item.value) });\n let { type } = item;\n if (type !== Scalar.Scalar.QUOTE_DOUBLE) {\n // force double quotes on control characters & unpaired surrogates\n if (/[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f\\u{D800}-\\u{DFFF}]/u.test(ss.value))\n type = Scalar.Scalar.QUOTE_DOUBLE;\n }\n const _stringify = (_type) => {\n switch (_type) {\n case Scalar.Scalar.BLOCK_FOLDED:\n case Scalar.Scalar.BLOCK_LITERAL:\n return implicitKey || inFlow\n ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers\n : blockString(ss, ctx, onComment, onChompKeep);\n case Scalar.Scalar.QUOTE_DOUBLE:\n return doubleQuotedString(ss.value, ctx);\n case Scalar.Scalar.QUOTE_SINGLE:\n return singleQuotedString(ss.value, ctx);\n case Scalar.Scalar.PLAIN:\n return plainString(ss, ctx, onComment, onChompKeep);\n default:\n return null;\n }\n };\n let res = _stringify(type);\n if (res === null) {\n const { defaultKeyType, defaultStringType } = ctx.options;\n const t = (implicitKey && defaultKeyType) || defaultStringType;\n res = _stringify(t);\n if (res === null)\n throw new Error(`Unsupported default string type ${t}`);\n }\n return res;\n}\n\nexports.stringifyString = stringifyString;\n",
|
|
19
|
+
"'use strict';\n\nvar anchors = require('../doc/anchors.js');\nvar identity = require('../nodes/identity.js');\nvar stringifyComment = require('./stringifyComment.js');\nvar stringifyString = require('./stringifyString.js');\n\nfunction createStringifyContext(doc, options) {\n const opt = Object.assign({\n blockQuote: true,\n commentString: stringifyComment.stringifyComment,\n defaultKeyType: null,\n defaultStringType: 'PLAIN',\n directives: null,\n doubleQuotedAsJSON: false,\n doubleQuotedMinMultiLineLength: 40,\n falseStr: 'false',\n flowCollectionPadding: true,\n indentSeq: true,\n lineWidth: 80,\n minContentWidth: 20,\n nullStr: 'null',\n simpleKeys: false,\n singleQuote: null,\n trailingComma: false,\n trueStr: 'true',\n verifyAliasOrder: true\n }, doc.schema.toStringOptions, options);\n let inFlow;\n switch (opt.collectionStyle) {\n case 'block':\n inFlow = false;\n break;\n case 'flow':\n inFlow = true;\n break;\n default:\n inFlow = null;\n }\n return {\n anchors: new Set(),\n doc,\n flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',\n indent: '',\n indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : ' ',\n inFlow,\n options: opt\n };\n}\nfunction getTagObject(tags, item) {\n if (item.tag) {\n const match = tags.filter(t => t.tag === item.tag);\n if (match.length > 0)\n return match.find(t => t.format === item.format) ?? match[0];\n }\n let tagObj = undefined;\n let obj;\n if (identity.isScalar(item)) {\n obj = item.value;\n let match = tags.filter(t => t.identify?.(obj));\n if (match.length > 1) {\n const testMatch = match.filter(t => t.test);\n if (testMatch.length > 0)\n match = testMatch;\n }\n tagObj =\n match.find(t => t.format === item.format) ?? match.find(t => !t.format);\n }\n else {\n obj = item;\n tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);\n }\n if (!tagObj) {\n const name = obj?.constructor?.name ?? (obj === null ? 'null' : typeof obj);\n throw new Error(`Tag not resolved for ${name} value`);\n }\n return tagObj;\n}\n// needs to be called before value stringifier to allow for circular anchor refs\nfunction stringifyProps(node, tagObj, { anchors: anchors$1, doc }) {\n if (!doc.directives)\n return '';\n const props = [];\n const anchor = (identity.isScalar(node) || identity.isCollection(node)) && node.anchor;\n if (anchor && anchors.anchorIsValid(anchor)) {\n anchors$1.add(anchor);\n props.push(`&${anchor}`);\n }\n const tag = node.tag ?? (tagObj.default ? null : tagObj.tag);\n if (tag)\n props.push(doc.directives.tagString(tag));\n return props.join(' ');\n}\nfunction stringify(item, ctx, onComment, onChompKeep) {\n if (identity.isPair(item))\n return item.toString(ctx, onComment, onChompKeep);\n if (identity.isAlias(item)) {\n if (ctx.doc.directives)\n return item.toString(ctx);\n if (ctx.resolvedAliases?.has(item)) {\n throw new TypeError(`Cannot stringify circular structure without alias nodes`);\n }\n else {\n if (ctx.resolvedAliases)\n ctx.resolvedAliases.add(item);\n else\n ctx.resolvedAliases = new Set([item]);\n item = item.resolve(ctx.doc);\n }\n }\n let tagObj = undefined;\n const node = identity.isNode(item)\n ? item\n : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });\n tagObj ?? (tagObj = getTagObject(ctx.doc.schema.tags, node));\n const props = stringifyProps(node, tagObj, ctx);\n if (props.length > 0)\n ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;\n const str = typeof tagObj.stringify === 'function'\n ? tagObj.stringify(node, ctx, onComment, onChompKeep)\n : identity.isScalar(node)\n ? stringifyString.stringifyString(node, ctx, onComment, onChompKeep)\n : node.toString(ctx, onComment, onChompKeep);\n if (!props)\n return str;\n return identity.isScalar(node) || str[0] === '{' || str[0] === '['\n ? `${props} ${str}`\n : `${props}\\n${ctx.indent}${str}`;\n}\n\nexports.createStringifyContext = createStringifyContext;\nexports.stringify = stringify;\n",
|
|
20
|
+
"'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyPair({ key, value }, ctx, onComment, onChompKeep) {\n const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;\n let keyComment = (identity.isNode(key) && key.comment) || null;\n if (simpleKeys) {\n if (keyComment) {\n throw new Error('With simple keys, key nodes cannot have comments');\n }\n if (identity.isCollection(key) || (!identity.isNode(key) && typeof key === 'object')) {\n const msg = 'With simple keys, collection cannot be used as a key value';\n throw new Error(msg);\n }\n }\n let explicitKey = !simpleKeys &&\n (!key ||\n (keyComment && value == null && !ctx.inFlow) ||\n identity.isCollection(key) ||\n (identity.isScalar(key)\n ? key.type === Scalar.Scalar.BLOCK_FOLDED || key.type === Scalar.Scalar.BLOCK_LITERAL\n : typeof key === 'object'));\n ctx = Object.assign({}, ctx, {\n allNullValues: false,\n implicitKey: !explicitKey && (simpleKeys || !allNullValues),\n indent: indent + indentStep\n });\n let keyCommentDone = false;\n let chompKeep = false;\n let str = stringify.stringify(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));\n if (!explicitKey && !ctx.inFlow && str.length > 1024) {\n if (simpleKeys)\n throw new Error('With simple keys, single line scalar must not span more than 1024 characters');\n explicitKey = true;\n }\n if (ctx.inFlow) {\n if (allNullValues || value == null) {\n if (keyCommentDone && onComment)\n onComment();\n return str === '' ? '?' : explicitKey ? `? ${str}` : str;\n }\n }\n else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {\n str = `? ${str}`;\n if (keyComment && !keyCommentDone) {\n str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n }\n else if (chompKeep && onChompKeep)\n onChompKeep();\n return str;\n }\n if (keyCommentDone)\n keyComment = null;\n if (explicitKey) {\n if (keyComment)\n str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n str = `? ${str}\\n${indent}:`;\n }\n else {\n str = `${str}:`;\n if (keyComment)\n str += stringifyComment.lineComment(str, ctx.indent, commentString(keyComment));\n }\n let vsb, vcb, valueComment;\n if (identity.isNode(value)) {\n vsb = !!value.spaceBefore;\n vcb = value.commentBefore;\n valueComment = value.comment;\n }\n else {\n vsb = false;\n vcb = null;\n valueComment = null;\n if (value && typeof value === 'object')\n value = doc.createNode(value);\n }\n ctx.implicitKey = false;\n if (!explicitKey && !keyComment && identity.isScalar(value))\n ctx.indentAtStart = str.length + 1;\n chompKeep = false;\n if (!indentSeq &&\n indentStep.length >= 2 &&\n !ctx.inFlow &&\n !explicitKey &&\n identity.isSeq(value) &&\n !value.flow &&\n !value.tag &&\n !value.anchor) {\n // If indentSeq === false, consider '- ' as part of indentation where possible\n ctx.indent = ctx.indent.substring(2);\n }\n let valueCommentDone = false;\n const valueStr = stringify.stringify(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));\n let ws = ' ';\n if (keyComment || vsb || vcb) {\n ws = vsb ? '\\n' : '';\n if (vcb) {\n const cs = commentString(vcb);\n ws += `\\n${stringifyComment.indentComment(cs, ctx.indent)}`;\n }\n if (valueStr === '' && !ctx.inFlow) {\n if (ws === '\\n' && valueComment)\n ws = '\\n\\n';\n }\n else {\n ws += `\\n${ctx.indent}`;\n }\n }\n else if (!explicitKey && identity.isCollection(value)) {\n const vs0 = valueStr[0];\n const nl0 = valueStr.indexOf('\\n');\n const hasNewline = nl0 !== -1;\n const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;\n if (hasNewline || !flow) {\n let hasPropsLine = false;\n if (hasNewline && (vs0 === '&' || vs0 === '!')) {\n let sp0 = valueStr.indexOf(' ');\n if (vs0 === '&' &&\n sp0 !== -1 &&\n sp0 < nl0 &&\n valueStr[sp0 + 1] === '!') {\n sp0 = valueStr.indexOf(' ', sp0 + 1);\n }\n if (sp0 === -1 || nl0 < sp0)\n hasPropsLine = true;\n }\n if (!hasPropsLine)\n ws = `\\n${ctx.indent}`;\n }\n }\n else if (valueStr === '' || valueStr[0] === '\\n') {\n ws = '';\n }\n str += ws + valueStr;\n if (ctx.inFlow) {\n if (valueCommentDone && onComment)\n onComment();\n }\n else if (valueComment && !valueCommentDone) {\n str += stringifyComment.lineComment(str, ctx.indent, commentString(valueComment));\n }\n else if (chompKeep && onChompKeep) {\n onChompKeep();\n }\n return str;\n}\n\nexports.stringifyPair = stringifyPair;\n",
|
|
21
|
+
"'use strict';\n\nvar node_process = require('process');\n\nfunction debug(logLevel, ...messages) {\n if (logLevel === 'debug')\n console.log(...messages);\n}\nfunction warn(logLevel, warning) {\n if (logLevel === 'debug' || logLevel === 'warn') {\n if (typeof node_process.emitWarning === 'function')\n node_process.emitWarning(warning);\n else\n console.warn(warning);\n }\n}\n\nexports.debug = debug;\nexports.warn = warn;\n",
|
|
22
|
+
"'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Scalar = require('../../nodes/Scalar.js');\n\n// If the value associated with a merge key is a single mapping node, each of\n// its key/value pairs is inserted into the current mapping, unless the key\n// already exists in it. If the value associated with the merge key is a\n// sequence, then this sequence is expected to contain mapping nodes and each\n// of these nodes is merged in turn according to its order in the sequence.\n// Keys in mapping nodes earlier in the sequence override keys specified in\n// later mapping nodes. -- http://yaml.org/type/merge.html\nconst MERGE_KEY = '<<';\nconst merge = {\n identify: value => value === MERGE_KEY ||\n (typeof value === 'symbol' && value.description === MERGE_KEY),\n default: 'key',\n tag: 'tag:yaml.org,2002:merge',\n test: /^<<$/,\n resolve: () => Object.assign(new Scalar.Scalar(Symbol(MERGE_KEY)), {\n addToJSMap: addMergeToJSMap\n }),\n stringify: () => MERGE_KEY\n};\nconst isMergeKey = (ctx, key) => (merge.identify(key) ||\n (identity.isScalar(key) &&\n (!key.type || key.type === Scalar.Scalar.PLAIN) &&\n merge.identify(key.value))) &&\n ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default);\nfunction addMergeToJSMap(ctx, map, value) {\n const source = resolveAliasValue(ctx, value);\n if (identity.isSeq(source))\n for (const it of source.items)\n mergeValue(ctx, map, it);\n else if (Array.isArray(source))\n for (const it of source)\n mergeValue(ctx, map, it);\n else\n mergeValue(ctx, map, source);\n}\nfunction mergeValue(ctx, map, value) {\n const source = resolveAliasValue(ctx, value);\n if (!identity.isMap(source))\n throw new Error('Merge sources must be maps or map aliases');\n const srcMap = source.toJSON(null, ctx, Map);\n for (const [key, value] of srcMap) {\n if (map instanceof Map) {\n if (!map.has(key))\n map.set(key, value);\n }\n else if (map instanceof Set) {\n map.add(key);\n }\n else if (!Object.prototype.hasOwnProperty.call(map, key)) {\n Object.defineProperty(map, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true\n });\n }\n }\n return map;\n}\nfunction resolveAliasValue(ctx, value) {\n return ctx && identity.isAlias(value) ? value.resolve(ctx.doc, ctx) : value;\n}\n\nexports.addMergeToJSMap = addMergeToJSMap;\nexports.isMergeKey = isMergeKey;\nexports.merge = merge;\n",
|
|
23
|
+
"'use strict';\n\nvar log = require('../log.js');\nvar merge = require('../schema/yaml-1.1/merge.js');\nvar stringify = require('../stringify/stringify.js');\nvar identity = require('./identity.js');\nvar toJS = require('./toJS.js');\n\nfunction addPairToJSMap(ctx, map, { key, value }) {\n if (identity.isNode(key) && key.addToJSMap)\n key.addToJSMap(ctx, map, value);\n // TODO: Should drop this special case for bare << handling\n else if (merge.isMergeKey(ctx, key))\n merge.addMergeToJSMap(ctx, map, value);\n else {\n const jsKey = toJS.toJS(key, '', ctx);\n if (map instanceof Map) {\n map.set(jsKey, toJS.toJS(value, jsKey, ctx));\n }\n else if (map instanceof Set) {\n map.add(jsKey);\n }\n else {\n const stringKey = stringifyKey(key, jsKey, ctx);\n const jsValue = toJS.toJS(value, stringKey, ctx);\n if (stringKey in map)\n Object.defineProperty(map, stringKey, {\n value: jsValue,\n writable: true,\n enumerable: true,\n configurable: true\n });\n else\n map[stringKey] = jsValue;\n }\n }\n return map;\n}\nfunction stringifyKey(key, jsKey, ctx) {\n if (jsKey === null)\n return '';\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n if (typeof jsKey !== 'object')\n return String(jsKey);\n if (identity.isNode(key) && ctx?.doc) {\n const strCtx = stringify.createStringifyContext(ctx.doc, {});\n strCtx.anchors = new Set();\n for (const node of ctx.anchors.keys())\n strCtx.anchors.add(node.anchor);\n strCtx.inFlow = true;\n strCtx.inStringifyKey = true;\n const strKey = key.toString(strCtx);\n if (!ctx.mapKeyWarned) {\n let jsonStr = JSON.stringify(strKey);\n if (jsonStr.length > 40)\n jsonStr = jsonStr.substring(0, 36) + '...\"';\n log.warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);\n ctx.mapKeyWarned = true;\n }\n return strKey;\n }\n return JSON.stringify(jsKey);\n}\n\nexports.addPairToJSMap = addPairToJSMap;\n",
|
|
24
|
+
"'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar stringifyPair = require('../stringify/stringifyPair.js');\nvar addPairToJSMap = require('./addPairToJSMap.js');\nvar identity = require('./identity.js');\n\nfunction createPair(key, value, ctx) {\n const k = createNode.createNode(key, undefined, ctx);\n const v = createNode.createNode(value, undefined, ctx);\n return new Pair(k, v);\n}\nclass Pair {\n constructor(key, value = null) {\n Object.defineProperty(this, identity.NODE_TYPE, { value: identity.PAIR });\n this.key = key;\n this.value = value;\n }\n clone(schema) {\n let { key, value } = this;\n if (identity.isNode(key))\n key = key.clone(schema);\n if (identity.isNode(value))\n value = value.clone(schema);\n return new Pair(key, value);\n }\n toJSON(_, ctx) {\n const pair = ctx?.mapAsMap ? new Map() : {};\n return addPairToJSMap.addPairToJSMap(ctx, pair, this);\n }\n toString(ctx, onComment, onChompKeep) {\n return ctx?.doc\n ? stringifyPair.stringifyPair(this, ctx, onComment, onChompKeep)\n : JSON.stringify(this);\n }\n}\n\nexports.Pair = Pair;\nexports.createPair = createPair;\n",
|
|
25
|
+
"'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyCollection(collection, ctx, options) {\n const flow = ctx.inFlow ?? collection.flow;\n const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;\n return stringify(collection, ctx, options);\n}\nfunction stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {\n const { indent, options: { commentString } } = ctx;\n const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });\n let chompKeep = false; // flag for the preceding node's status\n const lines = [];\n for (let i = 0; i < items.length; ++i) {\n const item = items[i];\n let comment = null;\n if (identity.isNode(item)) {\n if (!chompKeep && item.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, item.commentBefore, chompKeep);\n if (item.comment)\n comment = item.comment;\n }\n else if (identity.isPair(item)) {\n const ik = identity.isNode(item.key) ? item.key : null;\n if (ik) {\n if (!chompKeep && ik.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);\n }\n }\n chompKeep = false;\n let str = stringify.stringify(item, itemCtx, () => (comment = null), () => (chompKeep = true));\n if (comment)\n str += stringifyComment.lineComment(str, itemIndent, commentString(comment));\n if (chompKeep && comment)\n chompKeep = false;\n lines.push(blockItemPrefix + str);\n }\n let str;\n if (lines.length === 0) {\n str = flowChars.start + flowChars.end;\n }\n else {\n str = lines[0];\n for (let i = 1; i < lines.length; ++i) {\n const line = lines[i];\n str += line ? `\\n${indent}${line}` : '\\n';\n }\n }\n if (comment) {\n str += '\\n' + stringifyComment.indentComment(commentString(comment), indent);\n if (onComment)\n onComment();\n }\n else if (chompKeep && onChompKeep)\n onChompKeep();\n return str;\n}\nfunction stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {\n const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;\n itemIndent += indentStep;\n const itemCtx = Object.assign({}, ctx, {\n indent: itemIndent,\n inFlow: true,\n type: null\n });\n let reqNewline = false;\n let linesAtValue = 0;\n const lines = [];\n for (let i = 0; i < items.length; ++i) {\n const item = items[i];\n let comment = null;\n if (identity.isNode(item)) {\n if (item.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, item.commentBefore, false);\n if (item.comment)\n comment = item.comment;\n }\n else if (identity.isPair(item)) {\n const ik = identity.isNode(item.key) ? item.key : null;\n if (ik) {\n if (ik.spaceBefore)\n lines.push('');\n addCommentBefore(ctx, lines, ik.commentBefore, false);\n if (ik.comment)\n reqNewline = true;\n }\n const iv = identity.isNode(item.value) ? item.value : null;\n if (iv) {\n if (iv.comment)\n comment = iv.comment;\n if (iv.commentBefore)\n reqNewline = true;\n }\n else if (item.value == null && ik?.comment) {\n comment = ik.comment;\n }\n }\n if (comment)\n reqNewline = true;\n let str = stringify.stringify(item, itemCtx, () => (comment = null));\n reqNewline || (reqNewline = lines.length > linesAtValue || str.includes('\\n'));\n if (i < items.length - 1) {\n str += ',';\n }\n else if (ctx.options.trailingComma) {\n if (ctx.options.lineWidth > 0) {\n reqNewline || (reqNewline = lines.reduce((sum, line) => sum + line.length + 2, 2) +\n (str.length + 2) >\n ctx.options.lineWidth);\n }\n if (reqNewline) {\n str += ',';\n }\n }\n if (comment)\n str += stringifyComment.lineComment(str, itemIndent, commentString(comment));\n lines.push(str);\n linesAtValue = lines.length;\n }\n const { start, end } = flowChars;\n if (lines.length === 0) {\n return start + end;\n }\n else {\n if (!reqNewline) {\n const len = lines.reduce((sum, line) => sum + line.length + 2, 2);\n reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;\n }\n if (reqNewline) {\n let str = start;\n for (const line of lines)\n str += line ? `\\n${indentStep}${indent}${line}` : '\\n';\n return `${str}\\n${indent}${end}`;\n }\n else {\n return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;\n }\n }\n}\nfunction addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {\n if (comment && chompKeep)\n comment = comment.replace(/^\\n+/, '');\n if (comment) {\n const ic = stringifyComment.indentComment(commentString(comment), indent);\n lines.push(ic.trimStart()); // Avoid double indent on first line\n }\n}\n\nexports.stringifyCollection = stringifyCollection;\n",
|
|
26
|
+
"'use strict';\n\nvar stringifyCollection = require('../stringify/stringifyCollection.js');\nvar addPairToJSMap = require('./addPairToJSMap.js');\nvar Collection = require('./Collection.js');\nvar identity = require('./identity.js');\nvar Pair = require('./Pair.js');\nvar Scalar = require('./Scalar.js');\n\nfunction findPair(items, key) {\n const k = identity.isScalar(key) ? key.value : key;\n for (const it of items) {\n if (identity.isPair(it)) {\n if (it.key === key || it.key === k)\n return it;\n if (identity.isScalar(it.key) && it.key.value === k)\n return it;\n }\n }\n return undefined;\n}\nclass YAMLMap extends Collection.Collection {\n static get tagName() {\n return 'tag:yaml.org,2002:map';\n }\n constructor(schema) {\n super(identity.MAP, schema);\n this.items = [];\n }\n /**\n * A generic collection parsing method that can be extended\n * to other node classes that inherit from YAMLMap\n */\n static from(schema, obj, ctx) {\n const { keepUndefined, replacer } = ctx;\n const map = new this(schema);\n const add = (key, value) => {\n if (typeof replacer === 'function')\n value = replacer.call(obj, key, value);\n else if (Array.isArray(replacer) && !replacer.includes(key))\n return;\n if (value !== undefined || keepUndefined)\n map.items.push(Pair.createPair(key, value, ctx));\n };\n if (obj instanceof Map) {\n for (const [key, value] of obj)\n add(key, value);\n }\n else if (obj && typeof obj === 'object') {\n for (const key of Object.keys(obj))\n add(key, obj[key]);\n }\n if (typeof schema.sortMapEntries === 'function') {\n map.items.sort(schema.sortMapEntries);\n }\n return map;\n }\n /**\n * Adds a value to the collection.\n *\n * @param overwrite - If not set `true`, using a key that is already in the\n * collection will throw. Otherwise, overwrites the previous value.\n */\n add(pair, overwrite) {\n let _pair;\n if (identity.isPair(pair))\n _pair = pair;\n else if (!pair || typeof pair !== 'object' || !('key' in pair)) {\n // In TypeScript, this never happens.\n _pair = new Pair.Pair(pair, pair?.value);\n }\n else\n _pair = new Pair.Pair(pair.key, pair.value);\n const prev = findPair(this.items, _pair.key);\n const sortEntries = this.schema?.sortMapEntries;\n if (prev) {\n if (!overwrite)\n throw new Error(`Key ${_pair.key} already set`);\n // For scalars, keep the old node & its comments and anchors\n if (identity.isScalar(prev.value) && Scalar.isScalarValue(_pair.value))\n prev.value.value = _pair.value;\n else\n prev.value = _pair.value;\n }\n else if (sortEntries) {\n const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);\n if (i === -1)\n this.items.push(_pair);\n else\n this.items.splice(i, 0, _pair);\n }\n else {\n this.items.push(_pair);\n }\n }\n delete(key) {\n const it = findPair(this.items, key);\n if (!it)\n return false;\n const del = this.items.splice(this.items.indexOf(it), 1);\n return del.length > 0;\n }\n get(key, keepScalar) {\n const it = findPair(this.items, key);\n const node = it?.value;\n return (!keepScalar && identity.isScalar(node) ? node.value : node) ?? undefined;\n }\n has(key) {\n return !!findPair(this.items, key);\n }\n set(key, value) {\n this.add(new Pair.Pair(key, value), true);\n }\n /**\n * @param ctx - Conversion context, originally set in Document#toJS()\n * @param {Class} Type - If set, forces the returned collection type\n * @returns Instance of Type, Map, or Object\n */\n toJSON(_, ctx, Type) {\n const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};\n if (ctx?.onCreate)\n ctx.onCreate(map);\n for (const item of this.items)\n addPairToJSMap.addPairToJSMap(ctx, map, item);\n return map;\n }\n toString(ctx, onComment, onChompKeep) {\n if (!ctx)\n return JSON.stringify(this);\n for (const item of this.items) {\n if (!identity.isPair(item))\n throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);\n }\n if (!ctx.allNullValues && this.hasAllNullValues(false))\n ctx = Object.assign({}, ctx, { allNullValues: true });\n return stringifyCollection.stringifyCollection(this, ctx, {\n blockItemPrefix: '',\n flowChars: { start: '{', end: '}' },\n itemIndent: ctx.indent || '',\n onChompKeep,\n onComment\n });\n }\n}\n\nexports.YAMLMap = YAMLMap;\nexports.findPair = findPair;\n",
|
|
27
|
+
"'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\n\nconst map = {\n collection: 'map',\n default: true,\n nodeClass: YAMLMap.YAMLMap,\n tag: 'tag:yaml.org,2002:map',\n resolve(map, onError) {\n if (!identity.isMap(map))\n onError('Expected a mapping for this tag');\n return map;\n },\n createNode: (schema, obj, ctx) => YAMLMap.YAMLMap.from(schema, obj, ctx)\n};\n\nexports.map = map;\n",
|
|
28
|
+
"'use strict';\n\nvar createNode = require('../doc/createNode.js');\nvar stringifyCollection = require('../stringify/stringifyCollection.js');\nvar Collection = require('./Collection.js');\nvar identity = require('./identity.js');\nvar Scalar = require('./Scalar.js');\nvar toJS = require('./toJS.js');\n\nclass YAMLSeq extends Collection.Collection {\n static get tagName() {\n return 'tag:yaml.org,2002:seq';\n }\n constructor(schema) {\n super(identity.SEQ, schema);\n this.items = [];\n }\n add(value) {\n this.items.push(value);\n }\n /**\n * Removes a value from the collection.\n *\n * `key` must contain a representation of an integer for this to succeed.\n * It may be wrapped in a `Scalar`.\n *\n * @returns `true` if the item was found and removed.\n */\n delete(key) {\n const idx = asItemIndex(key);\n if (typeof idx !== 'number')\n return false;\n const del = this.items.splice(idx, 1);\n return del.length > 0;\n }\n get(key, keepScalar) {\n const idx = asItemIndex(key);\n if (typeof idx !== 'number')\n return undefined;\n const it = this.items[idx];\n return !keepScalar && identity.isScalar(it) ? it.value : it;\n }\n /**\n * Checks if the collection includes a value with the key `key`.\n *\n * `key` must contain a representation of an integer for this to succeed.\n * It may be wrapped in a `Scalar`.\n */\n has(key) {\n const idx = asItemIndex(key);\n return typeof idx === 'number' && idx < this.items.length;\n }\n /**\n * Sets a value in this collection. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n *\n * If `key` does not contain a representation of an integer, this will throw.\n * It may be wrapped in a `Scalar`.\n */\n set(key, value) {\n const idx = asItemIndex(key);\n if (typeof idx !== 'number')\n throw new Error(`Expected a valid index, not ${key}.`);\n const prev = this.items[idx];\n if (identity.isScalar(prev) && Scalar.isScalarValue(value))\n prev.value = value;\n else\n this.items[idx] = value;\n }\n toJSON(_, ctx) {\n const seq = [];\n if (ctx?.onCreate)\n ctx.onCreate(seq);\n let i = 0;\n for (const item of this.items)\n seq.push(toJS.toJS(item, String(i++), ctx));\n return seq;\n }\n toString(ctx, onComment, onChompKeep) {\n if (!ctx)\n return JSON.stringify(this);\n return stringifyCollection.stringifyCollection(this, ctx, {\n blockItemPrefix: '- ',\n flowChars: { start: '[', end: ']' },\n itemIndent: (ctx.indent || '') + ' ',\n onChompKeep,\n onComment\n });\n }\n static from(schema, obj, ctx) {\n const { replacer } = ctx;\n const seq = new this(schema);\n if (obj && Symbol.iterator in Object(obj)) {\n let i = 0;\n for (let it of obj) {\n if (typeof replacer === 'function') {\n const key = obj instanceof Set ? it : String(i++);\n it = replacer.call(obj, key, it);\n }\n seq.items.push(createNode.createNode(it, undefined, ctx));\n }\n }\n return seq;\n }\n}\nfunction asItemIndex(key) {\n let idx = identity.isScalar(key) ? key.value : key;\n if (idx && typeof idx === 'string')\n idx = Number(idx);\n return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0\n ? idx\n : null;\n}\n\nexports.YAMLSeq = YAMLSeq;\n",
|
|
29
|
+
"'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\n\nconst seq = {\n collection: 'seq',\n default: true,\n nodeClass: YAMLSeq.YAMLSeq,\n tag: 'tag:yaml.org,2002:seq',\n resolve(seq, onError) {\n if (!identity.isSeq(seq))\n onError('Expected a sequence for this tag');\n return seq;\n },\n createNode: (schema, obj, ctx) => YAMLSeq.YAMLSeq.from(schema, obj, ctx)\n};\n\nexports.seq = seq;\n",
|
|
30
|
+
"'use strict';\n\nvar stringifyString = require('../../stringify/stringifyString.js');\n\nconst string = {\n identify: value => typeof value === 'string',\n default: true,\n tag: 'tag:yaml.org,2002:str',\n resolve: str => str,\n stringify(item, ctx, onComment, onChompKeep) {\n ctx = Object.assign({ actualString: true }, ctx);\n return stringifyString.stringifyString(item, ctx, onComment, onChompKeep);\n }\n};\n\nexports.string = string;\n",
|
|
31
|
+
"'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nconst nullTag = {\n identify: value => value == null,\n createNode: () => new Scalar.Scalar(null),\n default: true,\n tag: 'tag:yaml.org,2002:null',\n test: /^(?:~|[Nn]ull|NULL)?$/,\n resolve: () => new Scalar.Scalar(null),\n stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)\n ? source\n : ctx.options.nullStr\n};\n\nexports.nullTag = nullTag;\n",
|
|
32
|
+
"'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nconst boolTag = {\n identify: value => typeof value === 'boolean',\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,\n resolve: str => new Scalar.Scalar(str[0] === 't' || str[0] === 'T'),\n stringify({ source, value }, ctx) {\n if (source && boolTag.test.test(source)) {\n const sv = source[0] === 't' || source[0] === 'T';\n if (value === sv)\n return source;\n }\n return value ? ctx.options.trueStr : ctx.options.falseStr;\n }\n};\n\nexports.boolTag = boolTag;\n",
|
|
33
|
+
"'use strict';\n\nfunction stringifyNumber({ format, minFractionDigits, tag, value }) {\n if (typeof value === 'bigint')\n return String(value);\n const num = typeof value === 'number' ? value : Number(value);\n if (!isFinite(num))\n return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';\n let n = Object.is(value, -0) ? '-0' : JSON.stringify(value);\n if (!format &&\n minFractionDigits &&\n (!tag || tag === 'tag:yaml.org,2002:float') &&\n /^-?\\d/.test(n) &&\n !n.includes('e')) {\n let i = n.indexOf('.');\n if (i < 0) {\n i = n.length;\n n += '.';\n }\n let d = minFractionDigits - (n.length - i - 1);\n while (d-- > 0)\n n += '0';\n }\n return n;\n}\n\nexports.stringifyNumber = stringifyNumber;\n",
|
|
34
|
+
"'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst floatNaN = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n resolve: str => str.slice(-3).toLowerCase() === 'nan'\n ? NaN\n : str[0] === '-'\n ? Number.NEGATIVE_INFINITY\n : Number.POSITIVE_INFINITY,\n stringify: stringifyNumber.stringifyNumber\n};\nconst floatExp = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n format: 'EXP',\n test: /^[-+]?(?:\\.[0-9]+|[0-9]+(?:\\.[0-9]*)?)[eE][-+]?[0-9]+$/,\n resolve: str => parseFloat(str),\n stringify(node) {\n const num = Number(node.value);\n return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);\n }\n};\nconst float = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^[-+]?(?:\\.[0-9]+|[0-9]+\\.[0-9]*)$/,\n resolve(str) {\n const node = new Scalar.Scalar(parseFloat(str));\n const dot = str.indexOf('.');\n if (dot !== -1 && str[str.length - 1] === '0')\n node.minFractionDigits = str.length - dot - 1;\n return node;\n },\n stringify: stringifyNumber.stringifyNumber\n};\n\nexports.float = float;\nexports.floatExp = floatExp;\nexports.floatNaN = floatNaN;\n",
|
|
35
|
+
"'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nconst intResolve = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));\nfunction intStringify(node, radix, prefix) {\n const { value } = node;\n if (intIdentify(value) && value >= 0)\n return prefix + value.toString(radix);\n return stringifyNumber.stringifyNumber(node);\n}\nconst intOct = {\n identify: value => intIdentify(value) && value >= 0,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'OCT',\n test: /^0o[0-7]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 8, opt),\n stringify: node => intStringify(node, 8, '0o')\n};\nconst int = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n test: /^[-+]?[0-9]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n stringify: stringifyNumber.stringifyNumber\n};\nconst intHex = {\n identify: value => intIdentify(value) && value >= 0,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'HEX',\n test: /^0x[0-9a-fA-F]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n stringify: node => intStringify(node, 16, '0x')\n};\n\nexports.int = int;\nexports.intHex = intHex;\nexports.intOct = intOct;\n",
|
|
36
|
+
"'use strict';\n\nvar map = require('../common/map.js');\nvar _null = require('../common/null.js');\nvar seq = require('../common/seq.js');\nvar string = require('../common/string.js');\nvar bool = require('./bool.js');\nvar float = require('./float.js');\nvar int = require('./int.js');\n\nconst schema = [\n map.map,\n seq.seq,\n string.string,\n _null.nullTag,\n bool.boolTag,\n int.intOct,\n int.int,\n int.intHex,\n float.floatNaN,\n float.floatExp,\n float.float\n];\n\nexports.schema = schema;\n",
|
|
37
|
+
"'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar map = require('../common/map.js');\nvar seq = require('../common/seq.js');\n\nfunction intIdentify(value) {\n return typeof value === 'bigint' || Number.isInteger(value);\n}\nconst stringifyJSON = ({ value }) => JSON.stringify(value);\nconst jsonScalars = [\n {\n identify: value => typeof value === 'string',\n default: true,\n tag: 'tag:yaml.org,2002:str',\n resolve: str => str,\n stringify: stringifyJSON\n },\n {\n identify: value => value == null,\n createNode: () => new Scalar.Scalar(null),\n default: true,\n tag: 'tag:yaml.org,2002:null',\n test: /^null$/,\n resolve: () => null,\n stringify: stringifyJSON\n },\n {\n identify: value => typeof value === 'boolean',\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^true$|^false$/,\n resolve: str => str === 'true',\n stringify: stringifyJSON\n },\n {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n test: /^-?(?:0|[1-9][0-9]*)$/,\n resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),\n stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)\n },\n {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,\n resolve: str => parseFloat(str),\n stringify: stringifyJSON\n }\n];\nconst jsonError = {\n default: true,\n tag: '',\n test: /^/,\n resolve(str, onError) {\n onError(`Unresolved plain scalar ${JSON.stringify(str)}`);\n return str;\n }\n};\nconst schema = [map.map, seq.seq].concat(jsonScalars, jsonError);\n\nexports.schema = schema;\n",
|
|
38
|
+
"'use strict';\n\nvar node_buffer = require('buffer');\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyString = require('../../stringify/stringifyString.js');\n\nconst binary = {\n identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array\n default: false,\n tag: 'tag:yaml.org,2002:binary',\n /**\n * Returns a Buffer in node and an Uint8Array in browsers\n *\n * To use the resulting buffer as an image, you'll want to do something like:\n *\n * const blob = new Blob([buffer], { type: 'image/jpeg' })\n * document.querySelector('#photo').src = URL.createObjectURL(blob)\n */\n resolve(src, onError) {\n if (typeof node_buffer.Buffer === 'function') {\n return node_buffer.Buffer.from(src, 'base64');\n }\n else if (typeof atob === 'function') {\n // On IE 11, atob() can't handle newlines\n const str = atob(src.replace(/[\\n\\r]/g, ''));\n const buffer = new Uint8Array(str.length);\n for (let i = 0; i < str.length; ++i)\n buffer[i] = str.charCodeAt(i);\n return buffer;\n }\n else {\n onError('This environment does not support reading binary tags; either Buffer or atob is required');\n return src;\n }\n },\n stringify({ comment, type, value }, ctx, onComment, onChompKeep) {\n if (!value)\n return '';\n const buf = value; // checked earlier by binary.identify()\n let str;\n if (typeof node_buffer.Buffer === 'function') {\n str =\n buf instanceof node_buffer.Buffer\n ? buf.toString('base64')\n : node_buffer.Buffer.from(buf.buffer).toString('base64');\n }\n else if (typeof btoa === 'function') {\n let s = '';\n for (let i = 0; i < buf.length; ++i)\n s += String.fromCharCode(buf[i]);\n str = btoa(s);\n }\n else {\n throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');\n }\n type ?? (type = Scalar.Scalar.BLOCK_LITERAL);\n if (type !== Scalar.Scalar.QUOTE_DOUBLE) {\n const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);\n const n = Math.ceil(str.length / lineWidth);\n const lines = new Array(n);\n for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {\n lines[i] = str.substr(o, lineWidth);\n }\n str = lines.join(type === Scalar.Scalar.BLOCK_LITERAL ? '\\n' : ' ');\n }\n return stringifyString.stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);\n }\n};\n\nexports.binary = binary;\n",
|
|
39
|
+
"'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Pair = require('../../nodes/Pair.js');\nvar Scalar = require('../../nodes/Scalar.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\n\nfunction resolvePairs(seq, onError) {\n if (identity.isSeq(seq)) {\n for (let i = 0; i < seq.items.length; ++i) {\n let item = seq.items[i];\n if (identity.isPair(item))\n continue;\n else if (identity.isMap(item)) {\n if (item.items.length > 1)\n onError('Each pair must have its own sequence indicator');\n const pair = item.items[0] || new Pair.Pair(new Scalar.Scalar(null));\n if (item.commentBefore)\n pair.key.commentBefore = pair.key.commentBefore\n ? `${item.commentBefore}\\n${pair.key.commentBefore}`\n : item.commentBefore;\n if (item.comment) {\n const cn = pair.value ?? pair.key;\n cn.comment = cn.comment\n ? `${item.comment}\\n${cn.comment}`\n : item.comment;\n }\n item = pair;\n }\n seq.items[i] = identity.isPair(item) ? item : new Pair.Pair(item);\n }\n }\n else\n onError('Expected a sequence for this tag');\n return seq;\n}\nfunction createPairs(schema, iterable, ctx) {\n const { replacer } = ctx;\n const pairs = new YAMLSeq.YAMLSeq(schema);\n pairs.tag = 'tag:yaml.org,2002:pairs';\n let i = 0;\n if (iterable && Symbol.iterator in Object(iterable))\n for (let it of iterable) {\n if (typeof replacer === 'function')\n it = replacer.call(iterable, String(i++), it);\n let key, value;\n if (Array.isArray(it)) {\n if (it.length === 2) {\n key = it[0];\n value = it[1];\n }\n else\n throw new TypeError(`Expected [key, value] tuple: ${it}`);\n }\n else if (it && it instanceof Object) {\n const keys = Object.keys(it);\n if (keys.length === 1) {\n key = keys[0];\n value = it[key];\n }\n else {\n throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);\n }\n }\n else {\n key = it;\n }\n pairs.items.push(Pair.createPair(key, value, ctx));\n }\n return pairs;\n}\nconst pairs = {\n collection: 'seq',\n default: false,\n tag: 'tag:yaml.org,2002:pairs',\n resolve: resolvePairs,\n createNode: createPairs\n};\n\nexports.createPairs = createPairs;\nexports.pairs = pairs;\nexports.resolvePairs = resolvePairs;\n",
|
|
40
|
+
"'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar toJS = require('../../nodes/toJS.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\nvar YAMLSeq = require('../../nodes/YAMLSeq.js');\nvar pairs = require('./pairs.js');\n\nclass YAMLOMap extends YAMLSeq.YAMLSeq {\n constructor() {\n super();\n this.add = YAMLMap.YAMLMap.prototype.add.bind(this);\n this.delete = YAMLMap.YAMLMap.prototype.delete.bind(this);\n this.get = YAMLMap.YAMLMap.prototype.get.bind(this);\n this.has = YAMLMap.YAMLMap.prototype.has.bind(this);\n this.set = YAMLMap.YAMLMap.prototype.set.bind(this);\n this.tag = YAMLOMap.tag;\n }\n /**\n * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,\n * but TypeScript won't allow widening the signature of a child method.\n */\n toJSON(_, ctx) {\n if (!ctx)\n return super.toJSON(_);\n const map = new Map();\n if (ctx?.onCreate)\n ctx.onCreate(map);\n for (const pair of this.items) {\n let key, value;\n if (identity.isPair(pair)) {\n key = toJS.toJS(pair.key, '', ctx);\n value = toJS.toJS(pair.value, key, ctx);\n }\n else {\n key = toJS.toJS(pair, '', ctx);\n }\n if (map.has(key))\n throw new Error('Ordered maps must not include duplicate keys');\n map.set(key, value);\n }\n return map;\n }\n static from(schema, iterable, ctx) {\n const pairs$1 = pairs.createPairs(schema, iterable, ctx);\n const omap = new this();\n omap.items = pairs$1.items;\n return omap;\n }\n}\nYAMLOMap.tag = 'tag:yaml.org,2002:omap';\nconst omap = {\n collection: 'seq',\n identify: value => value instanceof Map,\n nodeClass: YAMLOMap,\n default: false,\n tag: 'tag:yaml.org,2002:omap',\n resolve(seq, onError) {\n const pairs$1 = pairs.resolvePairs(seq, onError);\n const seenKeys = [];\n for (const { key } of pairs$1.items) {\n if (identity.isScalar(key)) {\n if (seenKeys.includes(key.value)) {\n onError(`Ordered maps must not include duplicate keys: ${key.value}`);\n }\n else {\n seenKeys.push(key.value);\n }\n }\n }\n return Object.assign(new YAMLOMap(), pairs$1);\n },\n createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)\n};\n\nexports.YAMLOMap = YAMLOMap;\nexports.omap = omap;\n",
|
|
41
|
+
"'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\n\nfunction boolStringify({ value, source }, ctx) {\n const boolObj = value ? trueTag : falseTag;\n if (source && boolObj.test.test(source))\n return source;\n return value ? ctx.options.trueStr : ctx.options.falseStr;\n}\nconst trueTag = {\n identify: value => value === true,\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,\n resolve: () => new Scalar.Scalar(true),\n stringify: boolStringify\n};\nconst falseTag = {\n identify: value => value === false,\n default: true,\n tag: 'tag:yaml.org,2002:bool',\n test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,\n resolve: () => new Scalar.Scalar(false),\n stringify: boolStringify\n};\n\nexports.falseTag = falseTag;\nexports.trueTag = trueTag;\n",
|
|
42
|
+
"'use strict';\n\nvar Scalar = require('../../nodes/Scalar.js');\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst floatNaN = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^(?:[-+]?\\.(?:inf|Inf|INF)|\\.nan|\\.NaN|\\.NAN)$/,\n resolve: (str) => str.slice(-3).toLowerCase() === 'nan'\n ? NaN\n : str[0] === '-'\n ? Number.NEGATIVE_INFINITY\n : Number.POSITIVE_INFINITY,\n stringify: stringifyNumber.stringifyNumber\n};\nconst floatExp = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n format: 'EXP',\n test: /^[-+]?(?:[0-9][0-9_]*)?(?:\\.[0-9_]*)?[eE][-+]?[0-9]+$/,\n resolve: (str) => parseFloat(str.replace(/_/g, '')),\n stringify(node) {\n const num = Number(node.value);\n return isFinite(num) ? num.toExponential() : stringifyNumber.stringifyNumber(node);\n }\n};\nconst float = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n test: /^[-+]?(?:[0-9][0-9_]*)?\\.[0-9_]*$/,\n resolve(str) {\n const node = new Scalar.Scalar(parseFloat(str.replace(/_/g, '')));\n const dot = str.indexOf('.');\n if (dot !== -1) {\n const f = str.substring(dot + 1).replace(/_/g, '');\n if (f[f.length - 1] === '0')\n node.minFractionDigits = f.length;\n }\n return node;\n },\n stringify: stringifyNumber.stringifyNumber\n};\n\nexports.float = float;\nexports.floatExp = floatExp;\nexports.floatNaN = floatNaN;\n",
|
|
43
|
+
"'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\nconst intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);\nfunction intResolve(str, offset, radix, { intAsBigInt }) {\n const sign = str[0];\n if (sign === '-' || sign === '+')\n offset += 1;\n str = str.substring(offset).replace(/_/g, '');\n if (intAsBigInt) {\n switch (radix) {\n case 2:\n str = `0b${str}`;\n break;\n case 8:\n str = `0o${str}`;\n break;\n case 16:\n str = `0x${str}`;\n break;\n }\n const n = BigInt(str);\n return sign === '-' ? BigInt(-1) * n : n;\n }\n const n = parseInt(str, radix);\n return sign === '-' ? -1 * n : n;\n}\nfunction intStringify(node, radix, prefix) {\n const { value } = node;\n if (intIdentify(value)) {\n const str = value.toString(radix);\n return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;\n }\n return stringifyNumber.stringifyNumber(node);\n}\nconst intBin = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'BIN',\n test: /^[-+]?0b[0-1_]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),\n stringify: node => intStringify(node, 2, '0b')\n};\nconst intOct = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'OCT',\n test: /^[-+]?0[0-7_]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),\n stringify: node => intStringify(node, 8, '0')\n};\nconst int = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n test: /^[-+]?[0-9][0-9_]*$/,\n resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),\n stringify: stringifyNumber.stringifyNumber\n};\nconst intHex = {\n identify: intIdentify,\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'HEX',\n test: /^[-+]?0x[0-9a-fA-F_]+$/,\n resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),\n stringify: node => intStringify(node, 16, '0x')\n};\n\nexports.int = int;\nexports.intBin = intBin;\nexports.intHex = intHex;\nexports.intOct = intOct;\n",
|
|
44
|
+
"'use strict';\n\nvar identity = require('../../nodes/identity.js');\nvar Pair = require('../../nodes/Pair.js');\nvar YAMLMap = require('../../nodes/YAMLMap.js');\n\nclass YAMLSet extends YAMLMap.YAMLMap {\n constructor(schema) {\n super(schema);\n this.tag = YAMLSet.tag;\n }\n add(key) {\n let pair;\n if (identity.isPair(key))\n pair = key;\n else if (key &&\n typeof key === 'object' &&\n 'key' in key &&\n 'value' in key &&\n key.value === null)\n pair = new Pair.Pair(key.key, null);\n else\n pair = new Pair.Pair(key, null);\n const prev = YAMLMap.findPair(this.items, pair.key);\n if (!prev)\n this.items.push(pair);\n }\n /**\n * If `keepPair` is `true`, returns the Pair matching `key`.\n * Otherwise, returns the value of that Pair's key.\n */\n get(key, keepPair) {\n const pair = YAMLMap.findPair(this.items, key);\n return !keepPair && identity.isPair(pair)\n ? identity.isScalar(pair.key)\n ? pair.key.value\n : pair.key\n : pair;\n }\n set(key, value) {\n if (typeof value !== 'boolean')\n throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);\n const prev = YAMLMap.findPair(this.items, key);\n if (prev && !value) {\n this.items.splice(this.items.indexOf(prev), 1);\n }\n else if (!prev && value) {\n this.items.push(new Pair.Pair(key));\n }\n }\n toJSON(_, ctx) {\n return super.toJSON(_, ctx, Set);\n }\n toString(ctx, onComment, onChompKeep) {\n if (!ctx)\n return JSON.stringify(this);\n if (this.hasAllNullValues(true))\n return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);\n else\n throw new Error('Set items must all have null values');\n }\n static from(schema, iterable, ctx) {\n const { replacer } = ctx;\n const set = new this(schema);\n if (iterable && Symbol.iterator in Object(iterable))\n for (let value of iterable) {\n if (typeof replacer === 'function')\n value = replacer.call(iterable, value, value);\n set.items.push(Pair.createPair(value, null, ctx));\n }\n return set;\n }\n}\nYAMLSet.tag = 'tag:yaml.org,2002:set';\nconst set = {\n collection: 'map',\n identify: value => value instanceof Set,\n nodeClass: YAMLSet,\n default: false,\n tag: 'tag:yaml.org,2002:set',\n createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),\n resolve(map, onError) {\n if (identity.isMap(map)) {\n if (map.hasAllNullValues(true))\n return Object.assign(new YAMLSet(), map);\n else\n onError('Set items must all have null values');\n }\n else\n onError('Expected a mapping for this tag');\n return map;\n }\n};\n\nexports.YAMLSet = YAMLSet;\nexports.set = set;\n",
|
|
45
|
+
"'use strict';\n\nvar stringifyNumber = require('../../stringify/stringifyNumber.js');\n\n/** Internal types handle bigint as number, because TS can't figure it out. */\nfunction parseSexagesimal(str, asBigInt) {\n const sign = str[0];\n const parts = sign === '-' || sign === '+' ? str.substring(1) : str;\n const num = (n) => asBigInt ? BigInt(n) : Number(n);\n const res = parts\n .replace(/_/g, '')\n .split(':')\n .reduce((res, p) => res * num(60) + num(p), num(0));\n return (sign === '-' ? num(-1) * res : res);\n}\n/**\n * hhhh:mm:ss.sss\n *\n * Internal types handle bigint as number, because TS can't figure it out.\n */\nfunction stringifySexagesimal(node) {\n let { value } = node;\n let num = (n) => n;\n if (typeof value === 'bigint')\n num = n => BigInt(n);\n else if (isNaN(value) || !isFinite(value))\n return stringifyNumber.stringifyNumber(node);\n let sign = '';\n if (value < 0) {\n sign = '-';\n value *= num(-1);\n }\n const _60 = num(60);\n const parts = [value % _60]; // seconds, including ms\n if (value < 60) {\n parts.unshift(0); // at least one : is required\n }\n else {\n value = (value - parts[0]) / _60;\n parts.unshift(value % _60); // minutes\n if (value >= 60) {\n value = (value - parts[0]) / _60;\n parts.unshift(value); // hours\n }\n }\n return (sign +\n parts\n .map(n => String(n).padStart(2, '0'))\n .join(':')\n .replace(/000000\\d*$/, '') // % 60 may introduce error\n );\n}\nconst intTime = {\n identify: value => typeof value === 'bigint' || Number.isInteger(value),\n default: true,\n tag: 'tag:yaml.org,2002:int',\n format: 'TIME',\n test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,\n resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),\n stringify: stringifySexagesimal\n};\nconst floatTime = {\n identify: value => typeof value === 'number',\n default: true,\n tag: 'tag:yaml.org,2002:float',\n format: 'TIME',\n test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*$/,\n resolve: str => parseSexagesimal(str, false),\n stringify: stringifySexagesimal\n};\nconst timestamp = {\n identify: value => value instanceof Date,\n default: true,\n tag: 'tag:yaml.org,2002:timestamp',\n // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part\n // may be omitted altogether, resulting in a date format. In such a case, the time part is\n // assumed to be 00:00:00Z (start of day, UTC).\n test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd\n '(?:' + // time is optional\n '(?:t|T|[ \\\\t]+)' + // t | T | whitespace\n '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?\n '(?:[ \\\\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30\n ')?$'),\n resolve(str) {\n const match = str.match(timestamp.test);\n if (!match)\n throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');\n const [, year, month, day, hour, minute, second] = match.map(Number);\n const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;\n let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);\n const tz = match[8];\n if (tz && tz !== 'Z') {\n let d = parseSexagesimal(tz, false);\n if (Math.abs(d) < 30)\n d *= 60;\n date -= 60000 * d;\n }\n return new Date(date);\n },\n stringify: ({ value }) => value?.toISOString().replace(/(T00:00:00)?\\.000Z$/, '') ?? ''\n};\n\nexports.floatTime = floatTime;\nexports.intTime = intTime;\nexports.timestamp = timestamp;\n",
|
|
46
|
+
"'use strict';\n\nvar map = require('../common/map.js');\nvar _null = require('../common/null.js');\nvar seq = require('../common/seq.js');\nvar string = require('../common/string.js');\nvar binary = require('./binary.js');\nvar bool = require('./bool.js');\nvar float = require('./float.js');\nvar int = require('./int.js');\nvar merge = require('./merge.js');\nvar omap = require('./omap.js');\nvar pairs = require('./pairs.js');\nvar set = require('./set.js');\nvar timestamp = require('./timestamp.js');\n\nconst schema = [\n map.map,\n seq.seq,\n string.string,\n _null.nullTag,\n bool.trueTag,\n bool.falseTag,\n int.intBin,\n int.intOct,\n int.int,\n int.intHex,\n float.floatNaN,\n float.floatExp,\n float.float,\n binary.binary,\n merge.merge,\n omap.omap,\n pairs.pairs,\n set.set,\n timestamp.intTime,\n timestamp.floatTime,\n timestamp.timestamp\n];\n\nexports.schema = schema;\n",
|
|
47
|
+
"'use strict';\n\nvar map = require('./common/map.js');\nvar _null = require('./common/null.js');\nvar seq = require('./common/seq.js');\nvar string = require('./common/string.js');\nvar bool = require('./core/bool.js');\nvar float = require('./core/float.js');\nvar int = require('./core/int.js');\nvar schema = require('./core/schema.js');\nvar schema$1 = require('./json/schema.js');\nvar binary = require('./yaml-1.1/binary.js');\nvar merge = require('./yaml-1.1/merge.js');\nvar omap = require('./yaml-1.1/omap.js');\nvar pairs = require('./yaml-1.1/pairs.js');\nvar schema$2 = require('./yaml-1.1/schema.js');\nvar set = require('./yaml-1.1/set.js');\nvar timestamp = require('./yaml-1.1/timestamp.js');\n\nconst schemas = new Map([\n ['core', schema.schema],\n ['failsafe', [map.map, seq.seq, string.string]],\n ['json', schema$1.schema],\n ['yaml11', schema$2.schema],\n ['yaml-1.1', schema$2.schema]\n]);\nconst tagsByName = {\n binary: binary.binary,\n bool: bool.boolTag,\n float: float.float,\n floatExp: float.floatExp,\n floatNaN: float.floatNaN,\n floatTime: timestamp.floatTime,\n int: int.int,\n intHex: int.intHex,\n intOct: int.intOct,\n intTime: timestamp.intTime,\n map: map.map,\n merge: merge.merge,\n null: _null.nullTag,\n omap: omap.omap,\n pairs: pairs.pairs,\n seq: seq.seq,\n set: set.set,\n timestamp: timestamp.timestamp\n};\nconst coreKnownTags = {\n 'tag:yaml.org,2002:binary': binary.binary,\n 'tag:yaml.org,2002:merge': merge.merge,\n 'tag:yaml.org,2002:omap': omap.omap,\n 'tag:yaml.org,2002:pairs': pairs.pairs,\n 'tag:yaml.org,2002:set': set.set,\n 'tag:yaml.org,2002:timestamp': timestamp.timestamp\n};\nfunction getTags(customTags, schemaName, addMergeTag) {\n const schemaTags = schemas.get(schemaName);\n if (schemaTags && !customTags) {\n return addMergeTag && !schemaTags.includes(merge.merge)\n ? schemaTags.concat(merge.merge)\n : schemaTags.slice();\n }\n let tags = schemaTags;\n if (!tags) {\n if (Array.isArray(customTags))\n tags = [];\n else {\n const keys = Array.from(schemas.keys())\n .filter(key => key !== 'yaml11')\n .map(key => JSON.stringify(key))\n .join(', ');\n throw new Error(`Unknown schema \"${schemaName}\"; use one of ${keys} or define customTags array`);\n }\n }\n if (Array.isArray(customTags)) {\n for (const tag of customTags)\n tags = tags.concat(tag);\n }\n else if (typeof customTags === 'function') {\n tags = customTags(tags.slice());\n }\n if (addMergeTag)\n tags = tags.concat(merge.merge);\n return tags.reduce((tags, tag) => {\n const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag;\n if (!tagObj) {\n const tagName = JSON.stringify(tag);\n const keys = Object.keys(tagsByName)\n .map(key => JSON.stringify(key))\n .join(', ');\n throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);\n }\n if (!tags.includes(tagObj))\n tags.push(tagObj);\n return tags;\n }, []);\n}\n\nexports.coreKnownTags = coreKnownTags;\nexports.getTags = getTags;\n",
|
|
48
|
+
"'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar map = require('./common/map.js');\nvar seq = require('./common/seq.js');\nvar string = require('./common/string.js');\nvar tags = require('./tags.js');\n\nconst sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;\nclass Schema {\n constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {\n this.compat = Array.isArray(compat)\n ? tags.getTags(compat, 'compat')\n : compat\n ? tags.getTags(null, compat)\n : null;\n this.name = (typeof schema === 'string' && schema) || 'core';\n this.knownTags = resolveKnownTags ? tags.coreKnownTags : {};\n this.tags = tags.getTags(customTags, this.name, merge);\n this.toStringOptions = toStringDefaults ?? null;\n Object.defineProperty(this, identity.MAP, { value: map.map });\n Object.defineProperty(this, identity.SCALAR, { value: string.string });\n Object.defineProperty(this, identity.SEQ, { value: seq.seq });\n // Used by createMap()\n this.sortMapEntries =\n typeof sortMapEntries === 'function'\n ? sortMapEntries\n : sortMapEntries === true\n ? sortMapEntriesByKey\n : null;\n }\n clone() {\n const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));\n copy.tags = this.tags.slice();\n return copy;\n }\n}\n\nexports.Schema = Schema;\n",
|
|
49
|
+
"'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar stringify = require('./stringify.js');\nvar stringifyComment = require('./stringifyComment.js');\n\nfunction stringifyDocument(doc, options) {\n const lines = [];\n let hasDirectives = options.directives === true;\n if (options.directives !== false && doc.directives) {\n const dir = doc.directives.toString(doc);\n if (dir) {\n lines.push(dir);\n hasDirectives = true;\n }\n else if (doc.directives.docStart)\n hasDirectives = true;\n }\n if (hasDirectives)\n lines.push('---');\n const ctx = stringify.createStringifyContext(doc, options);\n const { commentString } = ctx.options;\n if (doc.commentBefore) {\n if (lines.length !== 1)\n lines.unshift('');\n const cs = commentString(doc.commentBefore);\n lines.unshift(stringifyComment.indentComment(cs, ''));\n }\n let chompKeep = false;\n let contentComment = null;\n if (doc.contents) {\n if (identity.isNode(doc.contents)) {\n if (doc.contents.spaceBefore && hasDirectives)\n lines.push('');\n if (doc.contents.commentBefore) {\n const cs = commentString(doc.contents.commentBefore);\n lines.push(stringifyComment.indentComment(cs, ''));\n }\n // top-level block scalars need to be indented if followed by a comment\n ctx.forceBlockIndent = !!doc.comment;\n contentComment = doc.contents.comment;\n }\n const onChompKeep = contentComment ? undefined : () => (chompKeep = true);\n let body = stringify.stringify(doc.contents, ctx, () => (contentComment = null), onChompKeep);\n if (contentComment)\n body += stringifyComment.lineComment(body, '', commentString(contentComment));\n if ((body[0] === '|' || body[0] === '>') &&\n lines[lines.length - 1] === '---') {\n // Top-level block scalars with a preceding doc marker ought to use the\n // same line for their header.\n lines[lines.length - 1] = `--- ${body}`;\n }\n else\n lines.push(body);\n }\n else {\n lines.push(stringify.stringify(doc.contents, ctx));\n }\n if (doc.directives?.docEnd) {\n if (doc.comment) {\n const cs = commentString(doc.comment);\n if (cs.includes('\\n')) {\n lines.push('...');\n lines.push(stringifyComment.indentComment(cs, ''));\n }\n else {\n lines.push(`... ${cs}`);\n }\n }\n else {\n lines.push('...');\n }\n }\n else {\n let dc = doc.comment;\n if (dc && chompKeep)\n dc = dc.replace(/^\\n+/, '');\n if (dc) {\n if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')\n lines.push('');\n lines.push(stringifyComment.indentComment(commentString(dc), ''));\n }\n }\n return lines.join('\\n') + '\\n';\n}\n\nexports.stringifyDocument = stringifyDocument;\n",
|
|
50
|
+
"'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar Collection = require('../nodes/Collection.js');\nvar identity = require('../nodes/identity.js');\nvar Pair = require('../nodes/Pair.js');\nvar toJS = require('../nodes/toJS.js');\nvar Schema = require('../schema/Schema.js');\nvar stringifyDocument = require('../stringify/stringifyDocument.js');\nvar anchors = require('./anchors.js');\nvar applyReviver = require('./applyReviver.js');\nvar createNode = require('./createNode.js');\nvar directives = require('./directives.js');\n\nclass Document {\n constructor(value, replacer, options) {\n /** A comment before this Document */\n this.commentBefore = null;\n /** A comment immediately after this Document */\n this.comment = null;\n /** Errors encountered during parsing. */\n this.errors = [];\n /** Warnings encountered during parsing. */\n this.warnings = [];\n Object.defineProperty(this, identity.NODE_TYPE, { value: identity.DOC });\n let _replacer = null;\n if (typeof replacer === 'function' || Array.isArray(replacer)) {\n _replacer = replacer;\n }\n else if (options === undefined && replacer) {\n options = replacer;\n replacer = undefined;\n }\n const opt = Object.assign({\n intAsBigInt: false,\n keepSourceTokens: false,\n logLevel: 'warn',\n prettyErrors: true,\n strict: true,\n stringKeys: false,\n uniqueKeys: true,\n version: '1.2'\n }, options);\n this.options = opt;\n let { version } = opt;\n if (options?._directives) {\n this.directives = options._directives.atDocument();\n if (this.directives.yaml.explicit)\n version = this.directives.yaml.version;\n }\n else\n this.directives = new directives.Directives({ version });\n this.setSchema(version, options);\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents =\n value === undefined ? null : this.createNode(value, _replacer, options);\n }\n /**\n * Create a deep copy of this Document and its contents.\n *\n * Custom Node values that inherit from `Object` still refer to their original instances.\n */\n clone() {\n const copy = Object.create(Document.prototype, {\n [identity.NODE_TYPE]: { value: identity.DOC }\n });\n copy.commentBefore = this.commentBefore;\n copy.comment = this.comment;\n copy.errors = this.errors.slice();\n copy.warnings = this.warnings.slice();\n copy.options = Object.assign({}, this.options);\n if (this.directives)\n copy.directives = this.directives.clone();\n copy.schema = this.schema.clone();\n // @ts-expect-error We can't really know that this matches Contents.\n copy.contents = identity.isNode(this.contents)\n ? this.contents.clone(copy.schema)\n : this.contents;\n if (this.range)\n copy.range = this.range.slice();\n return copy;\n }\n /** Adds a value to the document. */\n add(value) {\n if (assertCollection(this.contents))\n this.contents.add(value);\n }\n /** Adds a value to the document. */\n addIn(path, value) {\n if (assertCollection(this.contents))\n this.contents.addIn(path, value);\n }\n /**\n * Create a new `Alias` node, ensuring that the target `node` has the required anchor.\n *\n * If `node` already has an anchor, `name` is ignored.\n * Otherwise, the `node.anchor` value will be set to `name`,\n * or if an anchor with that name is already present in the document,\n * `name` will be used as a prefix for a new unique anchor.\n * If `name` is undefined, the generated anchor will use 'a' as a prefix.\n */\n createAlias(node, name) {\n if (!node.anchor) {\n const prev = anchors.anchorNames(this);\n node.anchor =\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n !name || prev.has(name) ? anchors.findNewAnchor(name || 'a', prev) : name;\n }\n return new Alias.Alias(node.anchor);\n }\n createNode(value, replacer, options) {\n let _replacer = undefined;\n if (typeof replacer === 'function') {\n value = replacer.call({ '': value }, '', value);\n _replacer = replacer;\n }\n else if (Array.isArray(replacer)) {\n const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;\n const asStr = replacer.filter(keyToStr).map(String);\n if (asStr.length > 0)\n replacer = replacer.concat(asStr);\n _replacer = replacer;\n }\n else if (options === undefined && replacer) {\n options = replacer;\n replacer = undefined;\n }\n const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};\n const { onAnchor, setAnchors, sourceObjects } = anchors.createNodeAnchors(this, \n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n anchorPrefix || 'a');\n const ctx = {\n aliasDuplicateObjects: aliasDuplicateObjects ?? true,\n keepUndefined: keepUndefined ?? false,\n onAnchor,\n onTagObj,\n replacer: _replacer,\n schema: this.schema,\n sourceObjects\n };\n const node = createNode.createNode(value, tag, ctx);\n if (flow && identity.isCollection(node))\n node.flow = true;\n setAnchors();\n return node;\n }\n /**\n * Convert a key and a value into a `Pair` using the current schema,\n * recursively wrapping all values as `Scalar` or `Collection` nodes.\n */\n createPair(key, value, options = {}) {\n const k = this.createNode(key, null, options);\n const v = this.createNode(value, null, options);\n return new Pair.Pair(k, v);\n }\n /**\n * Removes a value from the document.\n * @returns `true` if the item was found and removed.\n */\n delete(key) {\n return assertCollection(this.contents) ? this.contents.delete(key) : false;\n }\n /**\n * Removes a value from the document.\n * @returns `true` if the item was found and removed.\n */\n deleteIn(path) {\n if (Collection.isEmptyPath(path)) {\n if (this.contents == null)\n return false;\n // @ts-expect-error Presumed impossible if Strict extends false\n this.contents = null;\n return true;\n }\n return assertCollection(this.contents)\n ? this.contents.deleteIn(path)\n : false;\n }\n /**\n * Returns item at `key`, or `undefined` if not found. By default unwraps\n * scalar values from their surrounding node; to disable set `keepScalar` to\n * `true` (collections are always returned intact).\n */\n get(key, keepScalar) {\n return identity.isCollection(this.contents)\n ? this.contents.get(key, keepScalar)\n : undefined;\n }\n /**\n * Returns item at `path`, or `undefined` if not found. By default unwraps\n * scalar values from their surrounding node; to disable set `keepScalar` to\n * `true` (collections are always returned intact).\n */\n getIn(path, keepScalar) {\n if (Collection.isEmptyPath(path))\n return !keepScalar && identity.isScalar(this.contents)\n ? this.contents.value\n : this.contents;\n return identity.isCollection(this.contents)\n ? this.contents.getIn(path, keepScalar)\n : undefined;\n }\n /**\n * Checks if the document includes a value with the key `key`.\n */\n has(key) {\n return identity.isCollection(this.contents) ? this.contents.has(key) : false;\n }\n /**\n * Checks if the document includes a value at `path`.\n */\n hasIn(path) {\n if (Collection.isEmptyPath(path))\n return this.contents !== undefined;\n return identity.isCollection(this.contents) ? this.contents.hasIn(path) : false;\n }\n /**\n * Sets a value in this document. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n */\n set(key, value) {\n if (this.contents == null) {\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents = Collection.collectionFromPath(this.schema, [key], value);\n }\n else if (assertCollection(this.contents)) {\n this.contents.set(key, value);\n }\n }\n /**\n * Sets a value in this document. For `!!set`, `value` needs to be a\n * boolean to add/remove the item from the set.\n */\n setIn(path, value) {\n if (Collection.isEmptyPath(path)) {\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents = value;\n }\n else if (this.contents == null) {\n // @ts-expect-error We can't really know that this matches Contents.\n this.contents = Collection.collectionFromPath(this.schema, Array.from(path), value);\n }\n else if (assertCollection(this.contents)) {\n this.contents.setIn(path, value);\n }\n }\n /**\n * Change the YAML version and schema used by the document.\n * A `null` version disables support for directives, explicit tags, anchors, and aliases.\n * It also requires the `schema` option to be given as a `Schema` instance value.\n *\n * Overrides all previously set schema options.\n */\n setSchema(version, options = {}) {\n if (typeof version === 'number')\n version = String(version);\n let opt;\n switch (version) {\n case '1.1':\n if (this.directives)\n this.directives.yaml.version = '1.1';\n else\n this.directives = new directives.Directives({ version: '1.1' });\n opt = { resolveKnownTags: false, schema: 'yaml-1.1' };\n break;\n case '1.2':\n case 'next':\n if (this.directives)\n this.directives.yaml.version = version;\n else\n this.directives = new directives.Directives({ version });\n opt = { resolveKnownTags: true, schema: 'core' };\n break;\n case null:\n if (this.directives)\n delete this.directives;\n opt = null;\n break;\n default: {\n const sv = JSON.stringify(version);\n throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);\n }\n }\n // Not using `instanceof Schema` to allow for duck typing\n if (options.schema instanceof Object)\n this.schema = options.schema;\n else if (opt)\n this.schema = new Schema.Schema(Object.assign(opt, options));\n else\n throw new Error(`With a null YAML version, the { schema: Schema } option is required`);\n }\n // json & jsonArg are only used from toJSON()\n toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {\n const ctx = {\n anchors: new Map(),\n doc: this,\n keep: !json,\n mapAsMap: mapAsMap === true,\n mapKeyWarned: false,\n maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100\n };\n const res = toJS.toJS(this.contents, jsonArg ?? '', ctx);\n if (typeof onAnchor === 'function')\n for (const { count, res } of ctx.anchors.values())\n onAnchor(res, count);\n return typeof reviver === 'function'\n ? applyReviver.applyReviver(reviver, { '': res }, '', res)\n : res;\n }\n /**\n * A JSON representation of the document `contents`.\n *\n * @param jsonArg Used by `JSON.stringify` to indicate the array index or\n * property name.\n */\n toJSON(jsonArg, onAnchor) {\n return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });\n }\n /** A YAML representation of the document. */\n toString(options = {}) {\n if (this.errors.length > 0)\n throw new Error('Document with errors cannot be stringified');\n if ('indent' in options &&\n (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {\n const s = JSON.stringify(options.indent);\n throw new Error(`\"indent\" option must be a positive integer, not ${s}`);\n }\n return stringifyDocument.stringifyDocument(this, options);\n }\n}\nfunction assertCollection(contents) {\n if (identity.isCollection(contents))\n return true;\n throw new Error('Expected a YAML collection as document contents');\n}\n\nexports.Document = Document;\n",
|
|
51
|
+
"'use strict';\n\nclass YAMLError extends Error {\n constructor(name, pos, code, message) {\n super();\n this.name = name;\n this.code = code;\n this.message = message;\n this.pos = pos;\n }\n}\nclass YAMLParseError extends YAMLError {\n constructor(pos, code, message) {\n super('YAMLParseError', pos, code, message);\n }\n}\nclass YAMLWarning extends YAMLError {\n constructor(pos, code, message) {\n super('YAMLWarning', pos, code, message);\n }\n}\nconst prettifyError = (src, lc) => (error) => {\n if (error.pos[0] === -1)\n return;\n error.linePos = error.pos.map(pos => lc.linePos(pos));\n const { line, col } = error.linePos[0];\n error.message += ` at line ${line}, column ${col}`;\n let ci = col - 1;\n let lineStr = src\n .substring(lc.lineStarts[line - 1], lc.lineStarts[line])\n .replace(/[\\n\\r]+$/, '');\n // Trim to max 80 chars, keeping col position near the middle\n if (ci >= 60 && lineStr.length > 80) {\n const trimStart = Math.min(ci - 39, lineStr.length - 79);\n lineStr = '…' + lineStr.substring(trimStart);\n ci -= trimStart - 1;\n }\n if (lineStr.length > 80)\n lineStr = lineStr.substring(0, 79) + '…';\n // Include previous line in context if pointing at line start\n if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {\n // Regexp won't match if start is trimmed\n let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);\n if (prev.length > 80)\n prev = prev.substring(0, 79) + '…\\n';\n lineStr = prev + lineStr;\n }\n if (/[^ ]/.test(lineStr)) {\n let count = 1;\n const end = error.linePos[1];\n if (end?.line === line && end.col > col) {\n count = Math.max(1, Math.min(end.col - col, 80 - ci));\n }\n const pointer = ' '.repeat(ci) + '^'.repeat(count);\n error.message += `:\\n\\n${lineStr}\\n${pointer}\\n`;\n }\n};\n\nexports.YAMLError = YAMLError;\nexports.YAMLParseError = YAMLParseError;\nexports.YAMLWarning = YAMLWarning;\nexports.prettifyError = prettifyError;\n",
|
|
52
|
+
"'use strict';\n\nfunction resolveProps(tokens, { flow, indicator, next, offset, onError, parentIndent, startOnNewline }) {\n let spaceBefore = false;\n let atNewline = startOnNewline;\n let hasSpace = startOnNewline;\n let comment = '';\n let commentSep = '';\n let hasNewline = false;\n let reqSpace = false;\n let tab = null;\n let anchor = null;\n let tag = null;\n let newlineAfterProp = null;\n let comma = null;\n let found = null;\n let start = null;\n for (const token of tokens) {\n if (reqSpace) {\n if (token.type !== 'space' &&\n token.type !== 'newline' &&\n token.type !== 'comma')\n onError(token.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n reqSpace = false;\n }\n if (tab) {\n if (atNewline && token.type !== 'comment' && token.type !== 'newline') {\n onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n }\n tab = null;\n }\n switch (token.type) {\n case 'space':\n // At the doc level, tabs at line start may be parsed\n // as leading white space rather than indentation.\n // In a flow collection, only the parser handles indent.\n if (!flow &&\n (indicator !== 'doc-start' || next?.type !== 'flow-collection') &&\n token.source.includes('\\t')) {\n tab = token;\n }\n hasSpace = true;\n break;\n case 'comment': {\n if (!hasSpace)\n onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n const cb = token.source.substring(1) || ' ';\n if (!comment)\n comment = cb;\n else\n comment += commentSep + cb;\n commentSep = '';\n atNewline = false;\n break;\n }\n case 'newline':\n if (atNewline) {\n if (comment)\n comment += token.source;\n else if (!found || indicator !== 'seq-item-ind')\n spaceBefore = true;\n }\n else\n commentSep += token.source;\n atNewline = true;\n hasNewline = true;\n if (anchor || tag)\n newlineAfterProp = token;\n hasSpace = true;\n break;\n case 'anchor':\n if (anchor)\n onError(token, 'MULTIPLE_ANCHORS', 'A node can have at most one anchor');\n if (token.source.endsWith(':'))\n onError(token.offset + token.source.length - 1, 'BAD_ALIAS', 'Anchor ending in : is ambiguous', true);\n anchor = token;\n start ?? (start = token.offset);\n atNewline = false;\n hasSpace = false;\n reqSpace = true;\n break;\n case 'tag': {\n if (tag)\n onError(token, 'MULTIPLE_TAGS', 'A node can have at most one tag');\n tag = token;\n start ?? (start = token.offset);\n atNewline = false;\n hasSpace = false;\n reqSpace = true;\n break;\n }\n case indicator:\n // Could here handle preceding comments differently\n if (anchor || tag)\n onError(token, 'BAD_PROP_ORDER', `Anchors and tags must be after the ${token.source} indicator`);\n if (found)\n onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.source} in ${flow ?? 'collection'}`);\n found = token;\n atNewline =\n indicator === 'seq-item-ind' || indicator === 'explicit-key-ind';\n hasSpace = false;\n break;\n case 'comma':\n if (flow) {\n if (comma)\n onError(token, 'UNEXPECTED_TOKEN', `Unexpected , in ${flow}`);\n comma = token;\n atNewline = false;\n hasSpace = false;\n break;\n }\n // else fallthrough\n default:\n onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${token.type} token`);\n atNewline = false;\n hasSpace = false;\n }\n }\n const last = tokens[tokens.length - 1];\n const end = last ? last.offset + last.source.length : offset;\n if (reqSpace &&\n next &&\n next.type !== 'space' &&\n next.type !== 'newline' &&\n next.type !== 'comma' &&\n (next.type !== 'scalar' || next.source !== '')) {\n onError(next.offset, 'MISSING_CHAR', 'Tags and anchors must be separated from the next token by white space');\n }\n if (tab &&\n ((atNewline && tab.indent <= parentIndent) ||\n next?.type === 'block-map' ||\n next?.type === 'block-seq'))\n onError(tab, 'TAB_AS_INDENT', 'Tabs are not allowed as indentation');\n return {\n comma,\n found,\n spaceBefore,\n comment,\n hasNewline,\n anchor,\n tag,\n newlineAfterProp,\n end,\n start: start ?? end\n };\n}\n\nexports.resolveProps = resolveProps;\n",
|
|
53
|
+
"'use strict';\n\nfunction containsNewline(key) {\n if (!key)\n return null;\n switch (key.type) {\n case 'alias':\n case 'scalar':\n case 'double-quoted-scalar':\n case 'single-quoted-scalar':\n if (key.source.includes('\\n'))\n return true;\n if (key.end)\n for (const st of key.end)\n if (st.type === 'newline')\n return true;\n return false;\n case 'flow-collection':\n for (const it of key.items) {\n for (const st of it.start)\n if (st.type === 'newline')\n return true;\n if (it.sep)\n for (const st of it.sep)\n if (st.type === 'newline')\n return true;\n if (containsNewline(it.key) || containsNewline(it.value))\n return true;\n }\n return false;\n default:\n return true;\n }\n}\n\nexports.containsNewline = containsNewline;\n",
|
|
54
|
+
"'use strict';\n\nvar utilContainsNewline = require('./util-contains-newline.js');\n\nfunction flowIndentCheck(indent, fc, onError) {\n if (fc?.type === 'flow-collection') {\n const end = fc.end[0];\n if (end.indent === indent &&\n (end.source === ']' || end.source === '}') &&\n utilContainsNewline.containsNewline(fc)) {\n const msg = 'Flow end indicator should be more indented than parent';\n onError(end, 'BAD_INDENT', msg, true);\n }\n }\n}\n\nexports.flowIndentCheck = flowIndentCheck;\n",
|
|
55
|
+
"'use strict';\n\nvar identity = require('../nodes/identity.js');\n\nfunction mapIncludes(ctx, items, search) {\n const { uniqueKeys } = ctx.options;\n if (uniqueKeys === false)\n return false;\n const isEqual = typeof uniqueKeys === 'function'\n ? uniqueKeys\n : (a, b) => a === b || (identity.isScalar(a) && identity.isScalar(b) && a.value === b.value);\n return items.some(pair => isEqual(pair.key, search));\n}\n\nexports.mapIncludes = mapIncludes;\n",
|
|
56
|
+
"'use strict';\n\nvar Pair = require('../nodes/Pair.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilContainsNewline = require('./util-contains-newline.js');\nvar utilFlowIndentCheck = require('./util-flow-indent-check.js');\nvar utilMapIncludes = require('./util-map-includes.js');\n\nconst startColMsg = 'All mapping items must start at the same column';\nfunction resolveBlockMap({ composeNode, composeEmptyNode }, ctx, bm, onError, tag) {\n const NodeClass = tag?.nodeClass ?? YAMLMap.YAMLMap;\n const map = new NodeClass(ctx.schema);\n if (ctx.atRoot)\n ctx.atRoot = false;\n let offset = bm.offset;\n let commentEnd = null;\n for (const collItem of bm.items) {\n const { start, key, sep, value } = collItem;\n // key properties\n const keyProps = resolveProps.resolveProps(start, {\n indicator: 'explicit-key-ind',\n next: key ?? sep?.[0],\n offset,\n onError,\n parentIndent: bm.indent,\n startOnNewline: true\n });\n const implicitKey = !keyProps.found;\n if (implicitKey) {\n if (key) {\n if (key.type === 'block-seq')\n onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'A block sequence may not be used as an implicit map key');\n else if ('indent' in key && key.indent !== bm.indent)\n onError(offset, 'BAD_INDENT', startColMsg);\n }\n if (!keyProps.anchor && !keyProps.tag && !sep) {\n commentEnd = keyProps.end;\n if (keyProps.comment) {\n if (map.comment)\n map.comment += '\\n' + keyProps.comment;\n else\n map.comment = keyProps.comment;\n }\n continue;\n }\n if (keyProps.newlineAfterProp || utilContainsNewline.containsNewline(key)) {\n onError(key ?? start[start.length - 1], 'MULTILINE_IMPLICIT_KEY', 'Implicit keys need to be on a single line');\n }\n }\n else if (keyProps.found?.indent !== bm.indent) {\n onError(offset, 'BAD_INDENT', startColMsg);\n }\n // key value\n ctx.atKey = true;\n const keyStart = keyProps.end;\n const keyNode = key\n ? composeNode(ctx, key, keyProps, onError)\n : composeEmptyNode(ctx, keyStart, start, null, keyProps, onError);\n if (ctx.schema.compat)\n utilFlowIndentCheck.flowIndentCheck(bm.indent, key, onError);\n ctx.atKey = false;\n if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))\n onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n // value properties\n const valueProps = resolveProps.resolveProps(sep ?? [], {\n indicator: 'map-value-ind',\n next: value,\n offset: keyNode.range[2],\n onError,\n parentIndent: bm.indent,\n startOnNewline: !key || key.type === 'block-scalar'\n });\n offset = valueProps.end;\n if (valueProps.found) {\n if (implicitKey) {\n if (value?.type === 'block-map' && !valueProps.hasNewline)\n onError(offset, 'BLOCK_AS_IMPLICIT_KEY', 'Nested mappings are not allowed in compact mappings');\n if (ctx.options.strict &&\n keyProps.start < valueProps.found.offset - 1024)\n onError(keyNode.range, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit block mapping key');\n }\n // value value\n const valueNode = value\n ? composeNode(ctx, value, valueProps, onError)\n : composeEmptyNode(ctx, offset, sep, null, valueProps, onError);\n if (ctx.schema.compat)\n utilFlowIndentCheck.flowIndentCheck(bm.indent, value, onError);\n offset = valueNode.range[2];\n const pair = new Pair.Pair(keyNode, valueNode);\n if (ctx.options.keepSourceTokens)\n pair.srcToken = collItem;\n map.items.push(pair);\n }\n else {\n // key with no value\n if (implicitKey)\n onError(keyNode.range, 'MISSING_CHAR', 'Implicit map keys need to be followed by map values');\n if (valueProps.comment) {\n if (keyNode.comment)\n keyNode.comment += '\\n' + valueProps.comment;\n else\n keyNode.comment = valueProps.comment;\n }\n const pair = new Pair.Pair(keyNode);\n if (ctx.options.keepSourceTokens)\n pair.srcToken = collItem;\n map.items.push(pair);\n }\n }\n if (commentEnd && commentEnd < offset)\n onError(commentEnd, 'IMPOSSIBLE', 'Map comment with trailing content');\n map.range = [bm.offset, offset, commentEnd ?? offset];\n return map;\n}\n\nexports.resolveBlockMap = resolveBlockMap;\n",
|
|
57
|
+
"'use strict';\n\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilFlowIndentCheck = require('./util-flow-indent-check.js');\n\nfunction resolveBlockSeq({ composeNode, composeEmptyNode }, ctx, bs, onError, tag) {\n const NodeClass = tag?.nodeClass ?? YAMLSeq.YAMLSeq;\n const seq = new NodeClass(ctx.schema);\n if (ctx.atRoot)\n ctx.atRoot = false;\n if (ctx.atKey)\n ctx.atKey = false;\n let offset = bs.offset;\n let commentEnd = null;\n for (const { start, value } of bs.items) {\n const props = resolveProps.resolveProps(start, {\n indicator: 'seq-item-ind',\n next: value,\n offset,\n onError,\n parentIndent: bs.indent,\n startOnNewline: true\n });\n if (!props.found) {\n if (props.anchor || props.tag || value) {\n if (value?.type === 'block-seq')\n onError(props.end, 'BAD_INDENT', 'All sequence items must start at the same column');\n else\n onError(offset, 'MISSING_CHAR', 'Sequence item without - indicator');\n }\n else {\n commentEnd = props.end;\n if (props.comment)\n seq.comment = props.comment;\n continue;\n }\n }\n const node = value\n ? composeNode(ctx, value, props, onError)\n : composeEmptyNode(ctx, props.end, start, null, props, onError);\n if (ctx.schema.compat)\n utilFlowIndentCheck.flowIndentCheck(bs.indent, value, onError);\n offset = node.range[2];\n seq.items.push(node);\n }\n seq.range = [bs.offset, offset, commentEnd ?? offset];\n return seq;\n}\n\nexports.resolveBlockSeq = resolveBlockSeq;\n",
|
|
58
|
+
"'use strict';\n\nfunction resolveEnd(end, offset, reqSpace, onError) {\n let comment = '';\n if (end) {\n let hasSpace = false;\n let sep = '';\n for (const token of end) {\n const { source, type } = token;\n switch (type) {\n case 'space':\n hasSpace = true;\n break;\n case 'comment': {\n if (reqSpace && !hasSpace)\n onError(token, 'MISSING_CHAR', 'Comments must be separated from other tokens by white space characters');\n const cb = source.substring(1) || ' ';\n if (!comment)\n comment = cb;\n else\n comment += sep + cb;\n sep = '';\n break;\n }\n case 'newline':\n if (comment)\n sep += source;\n hasSpace = true;\n break;\n default:\n onError(token, 'UNEXPECTED_TOKEN', `Unexpected ${type} at node end`);\n }\n offset += source.length;\n }\n }\n return { comment, offset };\n}\n\nexports.resolveEnd = resolveEnd;\n",
|
|
59
|
+
"'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Pair = require('../nodes/Pair.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveEnd = require('./resolve-end.js');\nvar resolveProps = require('./resolve-props.js');\nvar utilContainsNewline = require('./util-contains-newline.js');\nvar utilMapIncludes = require('./util-map-includes.js');\n\nconst blockMsg = 'Block collections are not allowed within flow collections';\nconst isBlock = (token) => token && (token.type === 'block-map' || token.type === 'block-seq');\nfunction resolveFlowCollection({ composeNode, composeEmptyNode }, ctx, fc, onError, tag) {\n const isMap = fc.start.source === '{';\n const fcName = isMap ? 'flow map' : 'flow sequence';\n const NodeClass = (tag?.nodeClass ?? (isMap ? YAMLMap.YAMLMap : YAMLSeq.YAMLSeq));\n const coll = new NodeClass(ctx.schema);\n coll.flow = true;\n const atRoot = ctx.atRoot;\n if (atRoot)\n ctx.atRoot = false;\n if (ctx.atKey)\n ctx.atKey = false;\n let offset = fc.offset + fc.start.source.length;\n for (let i = 0; i < fc.items.length; ++i) {\n const collItem = fc.items[i];\n const { start, key, sep, value } = collItem;\n const props = resolveProps.resolveProps(start, {\n flow: fcName,\n indicator: 'explicit-key-ind',\n next: key ?? sep?.[0],\n offset,\n onError,\n parentIndent: fc.indent,\n startOnNewline: false\n });\n if (!props.found) {\n if (!props.anchor && !props.tag && !sep && !value) {\n if (i === 0 && props.comma)\n onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n else if (i < fc.items.length - 1)\n onError(props.start, 'UNEXPECTED_TOKEN', `Unexpected empty item in ${fcName}`);\n if (props.comment) {\n if (coll.comment)\n coll.comment += '\\n' + props.comment;\n else\n coll.comment = props.comment;\n }\n offset = props.end;\n continue;\n }\n if (!isMap && ctx.options.strict && utilContainsNewline.containsNewline(key))\n onError(key, // checked by containsNewline()\n 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n }\n if (i === 0) {\n if (props.comma)\n onError(props.comma, 'UNEXPECTED_TOKEN', `Unexpected , in ${fcName}`);\n }\n else {\n if (!props.comma)\n onError(props.start, 'MISSING_CHAR', `Missing , between ${fcName} items`);\n if (props.comment) {\n let prevItemComment = '';\n loop: for (const st of start) {\n switch (st.type) {\n case 'comma':\n case 'space':\n break;\n case 'comment':\n prevItemComment = st.source.substring(1);\n break loop;\n default:\n break loop;\n }\n }\n if (prevItemComment) {\n let prev = coll.items[coll.items.length - 1];\n if (identity.isPair(prev))\n prev = prev.value ?? prev.key;\n if (prev.comment)\n prev.comment += '\\n' + prevItemComment;\n else\n prev.comment = prevItemComment;\n props.comment = props.comment.substring(prevItemComment.length + 1);\n }\n }\n }\n if (!isMap && !sep && !props.found) {\n // item is a value in a seq\n // → key & sep are empty, start does not include ? or :\n const valueNode = value\n ? composeNode(ctx, value, props, onError)\n : composeEmptyNode(ctx, props.end, sep, null, props, onError);\n coll.items.push(valueNode);\n offset = valueNode.range[2];\n if (isBlock(value))\n onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n }\n else {\n // item is a key+value pair\n // key value\n ctx.atKey = true;\n const keyStart = props.end;\n const keyNode = key\n ? composeNode(ctx, key, props, onError)\n : composeEmptyNode(ctx, keyStart, start, null, props, onError);\n if (isBlock(key))\n onError(keyNode.range, 'BLOCK_IN_FLOW', blockMsg);\n ctx.atKey = false;\n // value properties\n const valueProps = resolveProps.resolveProps(sep ?? [], {\n flow: fcName,\n indicator: 'map-value-ind',\n next: value,\n offset: keyNode.range[2],\n onError,\n parentIndent: fc.indent,\n startOnNewline: false\n });\n if (valueProps.found) {\n if (!isMap && !props.found && ctx.options.strict) {\n if (sep)\n for (const st of sep) {\n if (st === valueProps.found)\n break;\n if (st.type === 'newline') {\n onError(st, 'MULTILINE_IMPLICIT_KEY', 'Implicit keys of flow sequence pairs need to be on a single line');\n break;\n }\n }\n if (props.start < valueProps.found.offset - 1024)\n onError(valueProps.found, 'KEY_OVER_1024_CHARS', 'The : indicator must be at most 1024 chars after the start of an implicit flow sequence key');\n }\n }\n else if (value) {\n if ('source' in value && value.source?.[0] === ':')\n onError(value, 'MISSING_CHAR', `Missing space after : in ${fcName}`);\n else\n onError(valueProps.start, 'MISSING_CHAR', `Missing , or : between ${fcName} items`);\n }\n // value value\n const valueNode = value\n ? composeNode(ctx, value, valueProps, onError)\n : valueProps.found\n ? composeEmptyNode(ctx, valueProps.end, sep, null, valueProps, onError)\n : null;\n if (valueNode) {\n if (isBlock(value))\n onError(valueNode.range, 'BLOCK_IN_FLOW', blockMsg);\n }\n else if (valueProps.comment) {\n if (keyNode.comment)\n keyNode.comment += '\\n' + valueProps.comment;\n else\n keyNode.comment = valueProps.comment;\n }\n const pair = new Pair.Pair(keyNode, valueNode);\n if (ctx.options.keepSourceTokens)\n pair.srcToken = collItem;\n if (isMap) {\n const map = coll;\n if (utilMapIncludes.mapIncludes(ctx, map.items, keyNode))\n onError(keyStart, 'DUPLICATE_KEY', 'Map keys must be unique');\n map.items.push(pair);\n }\n else {\n const map = new YAMLMap.YAMLMap(ctx.schema);\n map.flow = true;\n map.items.push(pair);\n const endRange = (valueNode ?? keyNode).range;\n map.range = [keyNode.range[0], endRange[1], endRange[2]];\n coll.items.push(map);\n }\n offset = valueNode ? valueNode.range[2] : valueProps.end;\n }\n }\n const expectedEnd = isMap ? '}' : ']';\n const [ce, ...ee] = fc.end;\n let cePos = offset;\n if (ce?.source === expectedEnd)\n cePos = ce.offset + ce.source.length;\n else {\n const name = fcName[0].toUpperCase() + fcName.substring(1);\n const msg = atRoot\n ? `${name} must end with a ${expectedEnd}`\n : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;\n onError(offset, atRoot ? 'MISSING_CHAR' : 'BAD_INDENT', msg);\n if (ce && ce.source.length !== 1)\n ee.unshift(ce);\n }\n if (ee.length > 0) {\n const end = resolveEnd.resolveEnd(ee, cePos, ctx.options.strict, onError);\n if (end.comment) {\n if (coll.comment)\n coll.comment += '\\n' + end.comment;\n else\n coll.comment = end.comment;\n }\n coll.range = [fc.offset, cePos, end.offset];\n }\n else {\n coll.range = [fc.offset, cePos, cePos];\n }\n return coll;\n}\n\nexports.resolveFlowCollection = resolveFlowCollection;\n",
|
|
60
|
+
"'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar YAMLMap = require('../nodes/YAMLMap.js');\nvar YAMLSeq = require('../nodes/YAMLSeq.js');\nvar resolveBlockMap = require('./resolve-block-map.js');\nvar resolveBlockSeq = require('./resolve-block-seq.js');\nvar resolveFlowCollection = require('./resolve-flow-collection.js');\n\nfunction resolveCollection(CN, ctx, token, onError, tagName, tag) {\n const coll = token.type === 'block-map'\n ? resolveBlockMap.resolveBlockMap(CN, ctx, token, onError, tag)\n : token.type === 'block-seq'\n ? resolveBlockSeq.resolveBlockSeq(CN, ctx, token, onError, tag)\n : resolveFlowCollection.resolveFlowCollection(CN, ctx, token, onError, tag);\n const Coll = coll.constructor;\n // If we got a tagName matching the class, or the tag name is '!',\n // then use the tagName from the node class used to create it.\n if (tagName === '!' || tagName === Coll.tagName) {\n coll.tag = Coll.tagName;\n return coll;\n }\n if (tagName)\n coll.tag = tagName;\n return coll;\n}\nfunction composeCollection(CN, ctx, token, props, onError) {\n const tagToken = props.tag;\n const tagName = !tagToken\n ? null\n : ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg));\n if (token.type === 'block-seq') {\n const { anchor, newlineAfterProp: nl } = props;\n const lastProp = anchor && tagToken\n ? anchor.offset > tagToken.offset\n ? anchor\n : tagToken\n : (anchor ?? tagToken);\n if (lastProp && (!nl || nl.offset < lastProp.offset)) {\n const message = 'Missing newline after block sequence props';\n onError(lastProp, 'MISSING_CHAR', message);\n }\n }\n const expType = token.type === 'block-map'\n ? 'map'\n : token.type === 'block-seq'\n ? 'seq'\n : token.start.source === '{'\n ? 'map'\n : 'seq';\n // shortcut: check if it's a generic YAMLMap or YAMLSeq\n // before jumping into the custom tag logic.\n if (!tagToken ||\n !tagName ||\n tagName === '!' ||\n (tagName === YAMLMap.YAMLMap.tagName && expType === 'map') ||\n (tagName === YAMLSeq.YAMLSeq.tagName && expType === 'seq')) {\n return resolveCollection(CN, ctx, token, onError, tagName);\n }\n let tag = ctx.schema.tags.find(t => t.tag === tagName && t.collection === expType);\n if (!tag) {\n const kt = ctx.schema.knownTags[tagName];\n if (kt?.collection === expType) {\n ctx.schema.tags.push(Object.assign({}, kt, { default: false }));\n tag = kt;\n }\n else {\n if (kt) {\n onError(tagToken, 'BAD_COLLECTION_TYPE', `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? 'scalar'}`, true);\n }\n else {\n onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true);\n }\n return resolveCollection(CN, ctx, token, onError, tagName);\n }\n }\n const coll = resolveCollection(CN, ctx, token, onError, tagName, tag);\n const res = tag.resolve?.(coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options) ?? coll;\n const node = identity.isNode(res)\n ? res\n : new Scalar.Scalar(res);\n node.range = coll.range;\n node.tag = tagName;\n if (tag?.format)\n node.format = tag.format;\n return node;\n}\n\nexports.composeCollection = composeCollection;\n",
|
|
61
|
+
"'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\n\nfunction resolveBlockScalar(ctx, scalar, onError) {\n const start = scalar.offset;\n const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);\n if (!header)\n return { value: '', type: null, comment: '', range: [start, start, start] };\n const type = header.mode === '>' ? Scalar.Scalar.BLOCK_FOLDED : Scalar.Scalar.BLOCK_LITERAL;\n const lines = scalar.source ? splitLines(scalar.source) : [];\n // determine the end of content & start of chomping\n let chompStart = lines.length;\n for (let i = lines.length - 1; i >= 0; --i) {\n const content = lines[i][1];\n if (content === '' || content === '\\r')\n chompStart = i;\n else\n break;\n }\n // shortcut for empty contents\n if (chompStart === 0) {\n const value = header.chomp === '+' && lines.length > 0\n ? '\\n'.repeat(Math.max(1, lines.length - 1))\n : '';\n let end = start + header.length;\n if (scalar.source)\n end += scalar.source.length;\n return { value, type, comment: header.comment, range: [start, end, end] };\n }\n // find the indentation level to trim from start\n let trimIndent = scalar.indent + header.indent;\n let offset = scalar.offset + header.length;\n let contentStart = 0;\n for (let i = 0; i < chompStart; ++i) {\n const [indent, content] = lines[i];\n if (content === '' || content === '\\r') {\n if (header.indent === 0 && indent.length > trimIndent)\n trimIndent = indent.length;\n }\n else {\n if (indent.length < trimIndent) {\n const message = 'Block scalars with more-indented leading empty lines must use an explicit indentation indicator';\n onError(offset + indent.length, 'MISSING_CHAR', message);\n }\n if (header.indent === 0)\n trimIndent = indent.length;\n contentStart = i;\n if (trimIndent === 0 && !ctx.atRoot) {\n const message = 'Block scalar values in collections must be indented';\n onError(offset, 'BAD_INDENT', message);\n }\n break;\n }\n offset += indent.length + content.length + 1;\n }\n // include trailing more-indented empty lines in content\n for (let i = lines.length - 1; i >= chompStart; --i) {\n if (lines[i][0].length > trimIndent)\n chompStart = i + 1;\n }\n let value = '';\n let sep = '';\n let prevMoreIndented = false;\n // leading whitespace is kept intact\n for (let i = 0; i < contentStart; ++i)\n value += lines[i][0].slice(trimIndent) + '\\n';\n for (let i = contentStart; i < chompStart; ++i) {\n let [indent, content] = lines[i];\n offset += indent.length + content.length + 1;\n const crlf = content[content.length - 1] === '\\r';\n if (crlf)\n content = content.slice(0, -1);\n /* istanbul ignore if already caught in lexer */\n if (content && indent.length < trimIndent) {\n const src = header.indent\n ? 'explicit indentation indicator'\n : 'first line';\n const message = `Block scalar lines must not be less indented than their ${src}`;\n onError(offset - content.length - (crlf ? 2 : 1), 'BAD_INDENT', message);\n indent = '';\n }\n if (type === Scalar.Scalar.BLOCK_LITERAL) {\n value += sep + indent.slice(trimIndent) + content;\n sep = '\\n';\n }\n else if (indent.length > trimIndent || content[0] === '\\t') {\n // more-indented content within a folded block\n if (sep === ' ')\n sep = '\\n';\n else if (!prevMoreIndented && sep === '\\n')\n sep = '\\n\\n';\n value += sep + indent.slice(trimIndent) + content;\n sep = '\\n';\n prevMoreIndented = true;\n }\n else if (content === '') {\n // empty line\n if (sep === '\\n')\n value += '\\n';\n else\n sep = '\\n';\n }\n else {\n value += sep + content;\n sep = ' ';\n prevMoreIndented = false;\n }\n }\n switch (header.chomp) {\n case '-':\n break;\n case '+':\n for (let i = chompStart; i < lines.length; ++i)\n value += '\\n' + lines[i][0].slice(trimIndent);\n if (value[value.length - 1] !== '\\n')\n value += '\\n';\n break;\n default:\n value += '\\n';\n }\n const end = start + header.length + scalar.source.length;\n return { value, type, comment: header.comment, range: [start, end, end] };\n}\nfunction parseBlockScalarHeader({ offset, props }, strict, onError) {\n /* istanbul ignore if should not happen */\n if (props[0].type !== 'block-scalar-header') {\n onError(props[0], 'IMPOSSIBLE', 'Block scalar header not found');\n return null;\n }\n const { source } = props[0];\n const mode = source[0];\n let indent = 0;\n let chomp = '';\n let error = -1;\n for (let i = 1; i < source.length; ++i) {\n const ch = source[i];\n if (!chomp && (ch === '-' || ch === '+'))\n chomp = ch;\n else {\n const n = Number(ch);\n if (!indent && n)\n indent = n;\n else if (error === -1)\n error = offset + i;\n }\n }\n if (error !== -1)\n onError(error, 'UNEXPECTED_TOKEN', `Block scalar header includes extra characters: ${source}`);\n let hasSpace = false;\n let comment = '';\n let length = source.length;\n for (let i = 1; i < props.length; ++i) {\n const token = props[i];\n switch (token.type) {\n case 'space':\n hasSpace = true;\n // fallthrough\n case 'newline':\n length += token.source.length;\n break;\n case 'comment':\n if (strict && !hasSpace) {\n const message = 'Comments must be separated from other tokens by white space characters';\n onError(token, 'MISSING_CHAR', message);\n }\n length += token.source.length;\n comment = token.source.substring(1);\n break;\n case 'error':\n onError(token, 'UNEXPECTED_TOKEN', token.message);\n length += token.source.length;\n break;\n /* istanbul ignore next should not happen */\n default: {\n const message = `Unexpected token in block scalar header: ${token.type}`;\n onError(token, 'UNEXPECTED_TOKEN', message);\n const ts = token.source;\n if (ts && typeof ts === 'string')\n length += ts.length;\n }\n }\n }\n return { mode, indent, chomp, comment, length };\n}\n/** @returns Array of lines split up as `[indent, content]` */\nfunction splitLines(source) {\n const split = source.split(/\\n( *)/);\n const first = split[0];\n const m = first.match(/^( *)/);\n const line0 = m?.[1]\n ? [m[1], first.slice(m[1].length)]\n : ['', first];\n const lines = [line0];\n for (let i = 1; i < split.length; i += 2)\n lines.push([split[i], split[i + 1]]);\n return lines;\n}\n\nexports.resolveBlockScalar = resolveBlockScalar;\n",
|
|
62
|
+
"'use strict';\n\nvar Scalar = require('../nodes/Scalar.js');\nvar resolveEnd = require('./resolve-end.js');\n\nfunction resolveFlowScalar(scalar, strict, onError) {\n const { offset, type, source, end } = scalar;\n let _type;\n let value;\n const _onError = (rel, code, msg) => onError(offset + rel, code, msg);\n switch (type) {\n case 'scalar':\n _type = Scalar.Scalar.PLAIN;\n value = plainValue(source, _onError);\n break;\n case 'single-quoted-scalar':\n _type = Scalar.Scalar.QUOTE_SINGLE;\n value = singleQuotedValue(source, _onError);\n break;\n case 'double-quoted-scalar':\n _type = Scalar.Scalar.QUOTE_DOUBLE;\n value = doubleQuotedValue(source, _onError);\n break;\n /* istanbul ignore next should not happen */\n default:\n onError(scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}`);\n return {\n value: '',\n type: null,\n comment: '',\n range: [offset, offset + source.length, offset + source.length]\n };\n }\n const valueEnd = offset + source.length;\n const re = resolveEnd.resolveEnd(end, valueEnd, strict, onError);\n return {\n value,\n type: _type,\n comment: re.comment,\n range: [offset, valueEnd, re.offset]\n };\n}\nfunction plainValue(source, onError) {\n let badChar = '';\n switch (source[0]) {\n /* istanbul ignore next should not happen */\n case '\\t':\n badChar = 'a tab character';\n break;\n case ',':\n badChar = 'flow indicator character ,';\n break;\n case '%':\n badChar = 'directive indicator character %';\n break;\n case '|':\n case '>': {\n badChar = `block scalar indicator ${source[0]}`;\n break;\n }\n case '@':\n case '`': {\n badChar = `reserved character ${source[0]}`;\n break;\n }\n }\n if (badChar)\n onError(0, 'BAD_SCALAR_START', `Plain value cannot start with ${badChar}`);\n return unfoldLines(source);\n}\nfunction singleQuotedValue(source, onError) {\n if (source[source.length - 1] !== \"'\" || source.length === 1)\n onError(source.length, 'MISSING_CHAR', \"Missing closing 'quote\");\n return unfoldLines(source.slice(1, -1)).replace(/''/g, \"'\");\n}\nfunction unfoldLines(source) {\n const line = /(.*?)\\r?\\n/sy;\n let match = line.exec(source);\n if (!match)\n return source;\n /**\n * The negative lookbehinds in these RegExps are to\n * prevent causing a polynomial search time in certain cases.\n *\n * The try-catch is for Safari < 16.4 and other old browsers:\n * https://caniuse.com/js-regexp-lookbehind\n */\n let trimEnd, trimBoth;\n try {\n trimEnd = new RegExp('(?<![ \\t])[ \\t]+$');\n trimBoth = new RegExp('^[ \\t]+|(?<![ \\t])[ \\t]+$', 'g');\n }\n catch {\n trimEnd = /[ \\t]+$/;\n trimBoth = /^[ \\t]+|[ \\t]+$/g;\n }\n let res = match[1].replace(trimEnd, '');\n let sep = ' ';\n let pos = line.lastIndex;\n while ((match = line.exec(source))) {\n const lm = match[1].replace(trimBoth, '');\n if (lm === '') {\n if (sep === '\\n')\n res += sep;\n else\n sep = '\\n';\n }\n else {\n res += sep + lm;\n sep = ' ';\n }\n pos = line.lastIndex;\n }\n const last = /[ \\t]*(.*)/sy;\n last.lastIndex = pos;\n match = last.exec(source);\n return res + sep + (match?.[1] ?? '');\n}\nfunction doubleQuotedValue(source, onError) {\n let res = '';\n for (let i = 1; i < source.length - 1; ++i) {\n const ch = source[i];\n if (ch === '\\r' && source[i + 1] === '\\n')\n continue;\n if (ch === '\\n') {\n const { fold, offset } = foldNewline(source, i);\n res += fold;\n i = offset;\n }\n else if (ch === '\\\\') {\n let next = source[++i];\n const cc = escapeCodes[next];\n if (cc)\n res += cc;\n else if (next === '\\n') {\n // skip escaped newlines, but still trim the following line\n next = source[i + 1];\n while (next === ' ' || next === '\\t')\n next = source[++i + 1];\n }\n else if (next === '\\r' && source[i + 1] === '\\n') {\n // skip escaped CRLF newlines, but still trim the following line\n next = source[++i + 1];\n while (next === ' ' || next === '\\t')\n next = source[++i + 1];\n }\n else if (next === 'x' || next === 'u' || next === 'U') {\n const length = next === 'x' ? 2 : next === 'u' ? 4 : 8;\n res += parseCharCode(source, i + 1, length, onError);\n i += length;\n }\n else {\n const raw = source.substr(i - 1, 2);\n onError(i - 1, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n res += raw;\n }\n }\n else if (ch === ' ' || ch === '\\t') {\n // trim trailing whitespace\n const wsStart = i;\n let next = source[i + 1];\n while (next === ' ' || next === '\\t')\n next = source[++i + 1];\n if (next !== '\\n' && !(next === '\\r' && source[i + 2] === '\\n'))\n res += i > wsStart ? source.slice(wsStart, i + 1) : ch;\n }\n else {\n res += ch;\n }\n }\n if (source[source.length - 1] !== '\"' || source.length === 1)\n onError(source.length, 'MISSING_CHAR', 'Missing closing \"quote');\n return res;\n}\n/**\n * Fold a single newline into a space, multiple newlines to N - 1 newlines.\n * Presumes `source[offset] === '\\n'`\n */\nfunction foldNewline(source, offset) {\n let fold = '';\n let ch = source[offset + 1];\n while (ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r') {\n if (ch === '\\r' && source[offset + 2] !== '\\n')\n break;\n if (ch === '\\n')\n fold += '\\n';\n offset += 1;\n ch = source[offset + 1];\n }\n if (!fold)\n fold = ' ';\n return { fold, offset };\n}\nconst escapeCodes = {\n '0': '\\0', // null character\n a: '\\x07', // bell character\n b: '\\b', // backspace\n e: '\\x1b', // escape character\n f: '\\f', // form feed\n n: '\\n', // line feed\n r: '\\r', // carriage return\n t: '\\t', // horizontal tab\n v: '\\v', // vertical tab\n N: '\\u0085', // Unicode next line\n _: '\\u00a0', // Unicode non-breaking space\n L: '\\u2028', // Unicode line separator\n P: '\\u2029', // Unicode paragraph separator\n ' ': ' ',\n '\"': '\"',\n '/': '/',\n '\\\\': '\\\\',\n '\\t': '\\t'\n};\nfunction parseCharCode(source, offset, length, onError) {\n const cc = source.substr(offset, length);\n const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);\n const code = ok ? parseInt(cc, 16) : NaN;\n try {\n return String.fromCodePoint(code);\n }\n catch {\n const raw = source.substr(offset - 2, length + 2);\n onError(offset - 2, 'BAD_DQ_ESCAPE', `Invalid escape sequence ${raw}`);\n return raw;\n }\n}\n\nexports.resolveFlowScalar = resolveFlowScalar;\n",
|
|
63
|
+
"'use strict';\n\nvar identity = require('../nodes/identity.js');\nvar Scalar = require('../nodes/Scalar.js');\nvar resolveBlockScalar = require('./resolve-block-scalar.js');\nvar resolveFlowScalar = require('./resolve-flow-scalar.js');\n\nfunction composeScalar(ctx, token, tagToken, onError) {\n const { value, type, comment, range } = token.type === 'block-scalar'\n ? resolveBlockScalar.resolveBlockScalar(ctx, token, onError)\n : resolveFlowScalar.resolveFlowScalar(token, ctx.options.strict, onError);\n const tagName = tagToken\n ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg))\n : null;\n let tag;\n if (ctx.options.stringKeys && ctx.atKey) {\n tag = ctx.schema[identity.SCALAR];\n }\n else if (tagName)\n tag = findScalarTagByName(ctx.schema, value, tagName, tagToken, onError);\n else if (token.type === 'scalar')\n tag = findScalarTagByTest(ctx, value, token, onError);\n else\n tag = ctx.schema[identity.SCALAR];\n let scalar;\n try {\n const res = tag.resolve(value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options);\n scalar = identity.isScalar(res) ? res : new Scalar.Scalar(res);\n }\n catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg);\n scalar = new Scalar.Scalar(value);\n }\n scalar.range = range;\n scalar.source = value;\n if (type)\n scalar.type = type;\n if (tagName)\n scalar.tag = tagName;\n if (tag.format)\n scalar.format = tag.format;\n if (comment)\n scalar.comment = comment;\n return scalar;\n}\nfunction findScalarTagByName(schema, value, tagName, tagToken, onError) {\n if (tagName === '!')\n return schema[identity.SCALAR]; // non-specific tag\n const matchWithTest = [];\n for (const tag of schema.tags) {\n if (!tag.collection && tag.tag === tagName) {\n if (tag.default && tag.test)\n matchWithTest.push(tag);\n else\n return tag;\n }\n }\n for (const tag of matchWithTest)\n if (tag.test?.test(value))\n return tag;\n const kt = schema.knownTags[tagName];\n if (kt && !kt.collection) {\n // Ensure that the known tag is available for stringifying,\n // but does not get used by default.\n schema.tags.push(Object.assign({}, kt, { default: false, test: undefined }));\n return kt;\n }\n onError(tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str');\n return schema[identity.SCALAR];\n}\nfunction findScalarTagByTest({ atKey, directives, schema }, value, token, onError) {\n const tag = schema.tags.find(tag => (tag.default === true || (atKey && tag.default === 'key')) &&\n tag.test?.test(value)) || schema[identity.SCALAR];\n if (schema.compat) {\n const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ??\n schema[identity.SCALAR];\n if (tag.tag !== compat.tag) {\n const ts = directives.tagString(tag.tag);\n const cs = directives.tagString(compat.tag);\n const msg = `Value may be parsed as either ${ts} or ${cs}`;\n onError(token, 'TAG_RESOLVE_FAILED', msg, true);\n }\n }\n return tag;\n}\n\nexports.composeScalar = composeScalar;\n",
|
|
64
|
+
"'use strict';\n\nfunction emptyScalarPosition(offset, before, pos) {\n if (before) {\n pos ?? (pos = before.length);\n for (let i = pos - 1; i >= 0; --i) {\n let st = before[i];\n switch (st.type) {\n case 'space':\n case 'comment':\n case 'newline':\n offset -= st.source.length;\n continue;\n }\n // Technically, an empty scalar is immediately after the last non-empty\n // node, but it's more useful to place it after any whitespace.\n st = before[++i];\n while (st?.type === 'space') {\n offset += st.source.length;\n st = before[++i];\n }\n break;\n }\n }\n return offset;\n}\n\nexports.emptyScalarPosition = emptyScalarPosition;\n",
|
|
65
|
+
"'use strict';\n\nvar Alias = require('../nodes/Alias.js');\nvar identity = require('../nodes/identity.js');\nvar composeCollection = require('./compose-collection.js');\nvar composeScalar = require('./compose-scalar.js');\nvar resolveEnd = require('./resolve-end.js');\nvar utilEmptyScalarPosition = require('./util-empty-scalar-position.js');\n\nconst CN = { composeNode, composeEmptyNode };\nfunction composeNode(ctx, token, props, onError) {\n const atKey = ctx.atKey;\n const { spaceBefore, comment, anchor, tag } = props;\n let node;\n let isSrcToken = true;\n switch (token.type) {\n case 'alias':\n node = composeAlias(ctx, token, onError);\n if (anchor || tag)\n onError(token, 'ALIAS_PROPS', 'An alias node must not specify any properties');\n break;\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n case 'block-scalar':\n node = composeScalar.composeScalar(ctx, token, tag, onError);\n if (anchor)\n node.anchor = anchor.source.substring(1);\n break;\n case 'block-map':\n case 'block-seq':\n case 'flow-collection':\n try {\n node = composeCollection.composeCollection(CN, ctx, token, props, onError);\n if (anchor)\n node.anchor = anchor.source.substring(1);\n }\n catch (error) {\n // Almost certainly here due to a stack overflow\n const message = error instanceof Error ? error.message : String(error);\n onError(token, 'RESOURCE_EXHAUSTION', message);\n }\n break;\n default: {\n const message = token.type === 'error'\n ? token.message\n : `Unsupported token (type: ${token.type})`;\n onError(token, 'UNEXPECTED_TOKEN', message);\n isSrcToken = false;\n }\n }\n node ?? (node = composeEmptyNode(ctx, token.offset, undefined, null, props, onError));\n if (anchor && node.anchor === '')\n onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n if (atKey &&\n ctx.options.stringKeys &&\n (!identity.isScalar(node) ||\n typeof node.value !== 'string' ||\n (node.tag && node.tag !== 'tag:yaml.org,2002:str'))) {\n const msg = 'With stringKeys, all keys must be strings';\n onError(tag ?? token, 'NON_STRING_KEY', msg);\n }\n if (spaceBefore)\n node.spaceBefore = true;\n if (comment) {\n if (token.type === 'scalar' && token.source === '')\n node.comment = comment;\n else\n node.commentBefore = comment;\n }\n // @ts-expect-error Type checking misses meaning of isSrcToken\n if (ctx.options.keepSourceTokens && isSrcToken)\n node.srcToken = token;\n return node;\n}\nfunction composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {\n const token = {\n type: 'scalar',\n offset: utilEmptyScalarPosition.emptyScalarPosition(offset, before, pos),\n indent: -1,\n source: ''\n };\n const node = composeScalar.composeScalar(ctx, token, tag, onError);\n if (anchor) {\n node.anchor = anchor.source.substring(1);\n if (node.anchor === '')\n onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string');\n }\n if (spaceBefore)\n node.spaceBefore = true;\n if (comment) {\n node.comment = comment;\n node.range[2] = end;\n }\n return node;\n}\nfunction composeAlias({ options }, { offset, source, end }, onError) {\n const alias = new Alias.Alias(source.substring(1));\n if (alias.source === '')\n onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string');\n if (alias.source.endsWith(':'))\n onError(offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true);\n const valueEnd = offset + source.length;\n const re = resolveEnd.resolveEnd(end, valueEnd, options.strict, onError);\n alias.range = [offset, valueEnd, re.offset];\n if (re.comment)\n alias.comment = re.comment;\n return alias;\n}\n\nexports.composeEmptyNode = composeEmptyNode;\nexports.composeNode = composeNode;\n",
|
|
66
|
+
"'use strict';\n\nvar Document = require('../doc/Document.js');\nvar composeNode = require('./compose-node.js');\nvar resolveEnd = require('./resolve-end.js');\nvar resolveProps = require('./resolve-props.js');\n\nfunction composeDoc(options, directives, { offset, start, value, end }, onError) {\n const opts = Object.assign({ _directives: directives }, options);\n const doc = new Document.Document(undefined, opts);\n const ctx = {\n atKey: false,\n atRoot: true,\n directives: doc.directives,\n options: doc.options,\n schema: doc.schema\n };\n const props = resolveProps.resolveProps(start, {\n indicator: 'doc-start',\n next: value ?? end?.[0],\n offset,\n onError,\n parentIndent: 0,\n startOnNewline: true\n });\n if (props.found) {\n doc.directives.docStart = true;\n if (value &&\n (value.type === 'block-map' || value.type === 'block-seq') &&\n !props.hasNewline)\n onError(props.end, 'MISSING_CHAR', 'Block collection cannot start on same line with directives-end marker');\n }\n // @ts-expect-error If Contents is set, let's trust the user\n doc.contents = value\n ? composeNode.composeNode(ctx, value, props, onError)\n : composeNode.composeEmptyNode(ctx, props.end, start, null, props, onError);\n const contentEnd = doc.contents.range[2];\n const re = resolveEnd.resolveEnd(end, contentEnd, false, onError);\n if (re.comment)\n doc.comment = re.comment;\n doc.range = [offset, contentEnd, re.offset];\n return doc;\n}\n\nexports.composeDoc = composeDoc;\n",
|
|
67
|
+
"'use strict';\n\nvar node_process = require('process');\nvar directives = require('../doc/directives.js');\nvar Document = require('../doc/Document.js');\nvar errors = require('../errors.js');\nvar identity = require('../nodes/identity.js');\nvar composeDoc = require('./compose-doc.js');\nvar resolveEnd = require('./resolve-end.js');\n\nfunction getErrorPos(src) {\n if (typeof src === 'number')\n return [src, src + 1];\n if (Array.isArray(src))\n return src.length === 2 ? src : [src[0], src[1]];\n const { offset, source } = src;\n return [offset, offset + (typeof source === 'string' ? source.length : 1)];\n}\nfunction parsePrelude(prelude) {\n let comment = '';\n let atComment = false;\n let afterEmptyLine = false;\n for (let i = 0; i < prelude.length; ++i) {\n const source = prelude[i];\n switch (source[0]) {\n case '#':\n comment +=\n (comment === '' ? '' : afterEmptyLine ? '\\n\\n' : '\\n') +\n (source.substring(1) || ' ');\n atComment = true;\n afterEmptyLine = false;\n break;\n case '%':\n if (prelude[i + 1]?.[0] !== '#')\n i += 1;\n atComment = false;\n break;\n default:\n // This may be wrong after doc-end, but in that case it doesn't matter\n if (!atComment)\n afterEmptyLine = true;\n atComment = false;\n }\n }\n return { comment, afterEmptyLine };\n}\n/**\n * Compose a stream of CST nodes into a stream of YAML Documents.\n *\n * ```ts\n * import { Composer, Parser } from 'yaml'\n *\n * const src: string = ...\n * const tokens = new Parser().parse(src)\n * const docs = new Composer().compose(tokens)\n * ```\n */\nclass Composer {\n constructor(options = {}) {\n this.doc = null;\n this.atDirectives = false;\n this.prelude = [];\n this.errors = [];\n this.warnings = [];\n this.onError = (source, code, message, warning) => {\n const pos = getErrorPos(source);\n if (warning)\n this.warnings.push(new errors.YAMLWarning(pos, code, message));\n else\n this.errors.push(new errors.YAMLParseError(pos, code, message));\n };\n // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing\n this.directives = new directives.Directives({ version: options.version || '1.2' });\n this.options = options;\n }\n decorate(doc, afterDoc) {\n const { comment, afterEmptyLine } = parsePrelude(this.prelude);\n //console.log({ dc: doc.comment, prelude, comment })\n if (comment) {\n const dc = doc.contents;\n if (afterDoc) {\n doc.comment = doc.comment ? `${doc.comment}\\n${comment}` : comment;\n }\n else if (afterEmptyLine || doc.directives.docStart || !dc) {\n doc.commentBefore = comment;\n }\n else if (identity.isCollection(dc) && !dc.flow && dc.items.length > 0) {\n let it = dc.items[0];\n if (identity.isPair(it))\n it = it.key;\n const cb = it.commentBefore;\n it.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n }\n else {\n const cb = dc.commentBefore;\n dc.commentBefore = cb ? `${comment}\\n${cb}` : comment;\n }\n }\n if (afterDoc) {\n for (let i = 0; i < this.errors.length; ++i)\n doc.errors.push(this.errors[i]);\n for (let i = 0; i < this.warnings.length; ++i)\n doc.warnings.push(this.warnings[i]);\n }\n else {\n doc.errors = this.errors;\n doc.warnings = this.warnings;\n }\n this.prelude = [];\n this.errors = [];\n this.warnings = [];\n }\n /**\n * Current stream status information.\n *\n * Mostly useful at the end of input for an empty stream.\n */\n streamInfo() {\n return {\n comment: parsePrelude(this.prelude).comment,\n directives: this.directives,\n errors: this.errors,\n warnings: this.warnings\n };\n }\n /**\n * Compose tokens into documents.\n *\n * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n */\n *compose(tokens, forceDoc = false, endOffset = -1) {\n for (const token of tokens)\n yield* this.next(token);\n yield* this.end(forceDoc, endOffset);\n }\n /** Advance the composer by one CST token. */\n *next(token) {\n if (node_process.env.LOG_STREAM)\n console.dir(token, { depth: null });\n switch (token.type) {\n case 'directive':\n this.directives.add(token.source, (offset, message, warning) => {\n const pos = getErrorPos(token);\n pos[0] += offset;\n this.onError(pos, 'BAD_DIRECTIVE', message, warning);\n });\n this.prelude.push(token.source);\n this.atDirectives = true;\n break;\n case 'document': {\n const doc = composeDoc.composeDoc(this.options, this.directives, token, this.onError);\n if (this.atDirectives && !doc.directives.docStart)\n this.onError(token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line');\n this.decorate(doc, false);\n if (this.doc)\n yield this.doc;\n this.doc = doc;\n this.atDirectives = false;\n break;\n }\n case 'byte-order-mark':\n case 'space':\n break;\n case 'comment':\n case 'newline':\n this.prelude.push(token.source);\n break;\n case 'error': {\n const msg = token.source\n ? `${token.message}: ${JSON.stringify(token.source)}`\n : token.message;\n const error = new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg);\n if (this.atDirectives || !this.doc)\n this.errors.push(error);\n else\n this.doc.errors.push(error);\n break;\n }\n case 'doc-end': {\n if (!this.doc) {\n const msg = 'Unexpected doc-end without preceding document';\n this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg));\n break;\n }\n this.doc.directives.docEnd = true;\n const end = resolveEnd.resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);\n this.decorate(this.doc, true);\n if (end.comment) {\n const dc = this.doc.comment;\n this.doc.comment = dc ? `${dc}\\n${end.comment}` : end.comment;\n }\n this.doc.range[2] = end.offset;\n break;\n }\n default:\n this.errors.push(new errors.YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}`));\n }\n }\n /**\n * Call at end of input to yield any remaining document.\n *\n * @param forceDoc - If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.\n * @param endOffset - Should be set if `forceDoc` is also set, to set the document range end and to indicate errors correctly.\n */\n *end(forceDoc = false, endOffset = -1) {\n if (this.doc) {\n this.decorate(this.doc, true);\n yield this.doc;\n this.doc = null;\n }\n else if (forceDoc) {\n const opts = Object.assign({ _directives: this.directives }, this.options);\n const doc = new Document.Document(undefined, opts);\n if (this.atDirectives)\n this.onError(endOffset, 'MISSING_CHAR', 'Missing directives-end indicator line');\n doc.range = [0, endOffset, endOffset];\n this.decorate(doc, false);\n yield doc;\n }\n }\n}\n\nexports.Composer = Composer;\n",
|
|
68
|
+
"'use strict';\n\nvar resolveBlockScalar = require('../compose/resolve-block-scalar.js');\nvar resolveFlowScalar = require('../compose/resolve-flow-scalar.js');\nvar errors = require('../errors.js');\nvar stringifyString = require('../stringify/stringifyString.js');\n\nfunction resolveAsScalar(token, strict = true, onError) {\n if (token) {\n const _onError = (pos, code, message) => {\n const offset = typeof pos === 'number' ? pos : Array.isArray(pos) ? pos[0] : pos.offset;\n if (onError)\n onError(offset, code, message);\n else\n throw new errors.YAMLParseError([offset, offset + 1], code, message);\n };\n switch (token.type) {\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n return resolveFlowScalar.resolveFlowScalar(token, strict, _onError);\n case 'block-scalar':\n return resolveBlockScalar.resolveBlockScalar({ options: { strict } }, token, _onError);\n }\n }\n return null;\n}\n/**\n * Create a new scalar token with `value`\n *\n * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,\n * as this function does not support any schema operations and won't check for such conflicts.\n *\n * @param value The string representation of the value, which will have its content properly indented.\n * @param context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added.\n * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.\n * @param context.indent The indent level of the token.\n * @param context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.\n * @param context.offset The offset position of the token.\n * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.\n */\nfunction createScalarToken(value, context) {\n const { implicitKey = false, indent, inFlow = false, offset = -1, type = 'PLAIN' } = context;\n const source = stringifyString.stringifyString({ type, value }, {\n implicitKey,\n indent: indent > 0 ? ' '.repeat(indent) : '',\n inFlow,\n options: { blockQuote: true, lineWidth: -1 }\n });\n const end = context.end ?? [\n { type: 'newline', offset: -1, indent, source: '\\n' }\n ];\n switch (source[0]) {\n case '|':\n case '>': {\n const he = source.indexOf('\\n');\n const head = source.substring(0, he);\n const body = source.substring(he + 1) + '\\n';\n const props = [\n { type: 'block-scalar-header', offset, indent, source: head }\n ];\n if (!addEndtoBlockProps(props, end))\n props.push({ type: 'newline', offset: -1, indent, source: '\\n' });\n return { type: 'block-scalar', offset, indent, props, source: body };\n }\n case '\"':\n return { type: 'double-quoted-scalar', offset, indent, source, end };\n case \"'\":\n return { type: 'single-quoted-scalar', offset, indent, source, end };\n default:\n return { type: 'scalar', offset, indent, source, end };\n }\n}\n/**\n * Set the value of `token` to the given string `value`, overwriting any previous contents and type that it may have.\n *\n * Best efforts are made to retain any comments previously associated with the `token`,\n * though all contents within a collection's `items` will be overwritten.\n *\n * Values that represent an actual string but may be parsed as a different type should use a `type` other than `'PLAIN'`,\n * as this function does not support any schema operations and won't check for such conflicts.\n *\n * @param token Any token. If it does not include an `indent` value, the value will be stringified as if it were an implicit key.\n * @param value The string representation of the value, which will have its content properly indented.\n * @param context.afterKey In most cases, values after a key should have an additional level of indentation.\n * @param context.implicitKey Being within an implicit key may affect the resolved type of the token's value.\n * @param context.inFlow Being within a flow collection may affect the resolved type of the token's value.\n * @param context.type The preferred type of the scalar token. If undefined, the previous type of the `token` will be used, defaulting to `'PLAIN'`.\n */\nfunction setScalarValue(token, value, context = {}) {\n let { afterKey = false, implicitKey = false, inFlow = false, type } = context;\n let indent = 'indent' in token ? token.indent : null;\n if (afterKey && typeof indent === 'number')\n indent += 2;\n if (!type)\n switch (token.type) {\n case 'single-quoted-scalar':\n type = 'QUOTE_SINGLE';\n break;\n case 'double-quoted-scalar':\n type = 'QUOTE_DOUBLE';\n break;\n case 'block-scalar': {\n const header = token.props[0];\n if (header.type !== 'block-scalar-header')\n throw new Error('Invalid block scalar header');\n type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL';\n break;\n }\n default:\n type = 'PLAIN';\n }\n const source = stringifyString.stringifyString({ type, value }, {\n implicitKey: implicitKey || indent === null,\n indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '',\n inFlow,\n options: { blockQuote: true, lineWidth: -1 }\n });\n switch (source[0]) {\n case '|':\n case '>':\n setBlockScalarValue(token, source);\n break;\n case '\"':\n setFlowScalarValue(token, source, 'double-quoted-scalar');\n break;\n case \"'\":\n setFlowScalarValue(token, source, 'single-quoted-scalar');\n break;\n default:\n setFlowScalarValue(token, source, 'scalar');\n }\n}\nfunction setBlockScalarValue(token, source) {\n const he = source.indexOf('\\n');\n const head = source.substring(0, he);\n const body = source.substring(he + 1) + '\\n';\n if (token.type === 'block-scalar') {\n const header = token.props[0];\n if (header.type !== 'block-scalar-header')\n throw new Error('Invalid block scalar header');\n header.source = head;\n token.source = body;\n }\n else {\n const { offset } = token;\n const indent = 'indent' in token ? token.indent : -1;\n const props = [\n { type: 'block-scalar-header', offset, indent, source: head }\n ];\n if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined))\n props.push({ type: 'newline', offset: -1, indent, source: '\\n' });\n for (const key of Object.keys(token))\n if (key !== 'type' && key !== 'offset')\n delete token[key];\n Object.assign(token, { type: 'block-scalar', indent, props, source: body });\n }\n}\n/** @returns `true` if last token is a newline */\nfunction addEndtoBlockProps(props, end) {\n if (end)\n for (const st of end)\n switch (st.type) {\n case 'space':\n case 'comment':\n props.push(st);\n break;\n case 'newline':\n props.push(st);\n return true;\n }\n return false;\n}\nfunction setFlowScalarValue(token, source, type) {\n switch (token.type) {\n case 'scalar':\n case 'double-quoted-scalar':\n case 'single-quoted-scalar':\n token.type = type;\n token.source = source;\n break;\n case 'block-scalar': {\n const end = token.props.slice(1);\n let oa = source.length;\n if (token.props[0].type === 'block-scalar-header')\n oa -= token.props[0].source.length;\n for (const tok of end)\n tok.offset += oa;\n delete token.props;\n Object.assign(token, { type, source, end });\n break;\n }\n case 'block-map':\n case 'block-seq': {\n const offset = token.offset + source.length;\n const nl = { type: 'newline', offset, indent: token.indent, source: '\\n' };\n delete token.items;\n Object.assign(token, { type, source, end: [nl] });\n break;\n }\n default: {\n const indent = 'indent' in token ? token.indent : -1;\n const end = 'end' in token && Array.isArray(token.end)\n ? token.end.filter(st => st.type === 'space' ||\n st.type === 'comment' ||\n st.type === 'newline')\n : [];\n for (const key of Object.keys(token))\n if (key !== 'type' && key !== 'offset')\n delete token[key];\n Object.assign(token, { type, indent, source, end });\n }\n }\n}\n\nexports.createScalarToken = createScalarToken;\nexports.resolveAsScalar = resolveAsScalar;\nexports.setScalarValue = setScalarValue;\n",
|
|
69
|
+
"'use strict';\n\n/**\n * Stringify a CST document, token, or collection item\n *\n * Fair warning: This applies no validation whatsoever, and\n * simply concatenates the sources in their logical order.\n */\nconst stringify = (cst) => 'type' in cst ? stringifyToken(cst) : stringifyItem(cst);\nfunction stringifyToken(token) {\n switch (token.type) {\n case 'block-scalar': {\n let res = '';\n for (const tok of token.props)\n res += stringifyToken(tok);\n return res + token.source;\n }\n case 'block-map':\n case 'block-seq': {\n let res = '';\n for (const item of token.items)\n res += stringifyItem(item);\n return res;\n }\n case 'flow-collection': {\n let res = token.start.source;\n for (const item of token.items)\n res += stringifyItem(item);\n for (const st of token.end)\n res += st.source;\n return res;\n }\n case 'document': {\n let res = stringifyItem(token);\n if (token.end)\n for (const st of token.end)\n res += st.source;\n return res;\n }\n default: {\n let res = token.source;\n if ('end' in token && token.end)\n for (const st of token.end)\n res += st.source;\n return res;\n }\n }\n}\nfunction stringifyItem({ start, key, sep, value }) {\n let res = '';\n for (const st of start)\n res += st.source;\n if (key)\n res += stringifyToken(key);\n if (sep)\n for (const st of sep)\n res += st.source;\n if (value)\n res += stringifyToken(value);\n return res;\n}\n\nexports.stringify = stringify;\n",
|
|
70
|
+
"'use strict';\n\nconst BREAK = Symbol('break visit');\nconst SKIP = Symbol('skip children');\nconst REMOVE = Symbol('remove item');\n/**\n * Apply a visitor to a CST document or item.\n *\n * Walks through the tree (depth-first) starting from the root, calling a\n * `visitor` function with two arguments when entering each item:\n * - `item`: The current item, which included the following members:\n * - `start: SourceToken[]` – Source tokens before the key or value,\n * possibly including its anchor or tag.\n * - `key?: Token | null` – Set for pair values. May then be `null`, if\n * the key before the `:` separator is empty.\n * - `sep?: SourceToken[]` – Source tokens between the key and the value,\n * which should include the `:` map value indicator if `value` is set.\n * - `value?: Token` – The value of a sequence item, or of a map pair.\n * - `path`: The steps from the root to the current node, as an array of\n * `['key' | 'value', number]` tuples.\n *\n * The return value of the visitor may be used to control the traversal:\n * - `undefined` (default): Do nothing and continue\n * - `visit.SKIP`: Do not visit the children of this token, continue with\n * next sibling\n * - `visit.BREAK`: Terminate traversal completely\n * - `visit.REMOVE`: Remove the current item, then continue with the next one\n * - `number`: Set the index of the next step. This is useful especially if\n * the index of the current token has changed.\n * - `function`: Define the next visitor for this item. After the original\n * visitor is called on item entry, next visitors are called after handling\n * a non-empty `key` and when exiting the item.\n */\nfunction visit(cst, visitor) {\n if ('type' in cst && cst.type === 'document')\n cst = { start: cst.start, value: cst.value };\n _visit(Object.freeze([]), cst, visitor);\n}\n// Without the `as symbol` casts, TS declares these in the `visit`\n// namespace using `var`, but then complains about that because\n// `unique symbol` must be `const`.\n/** Terminate visit traversal completely */\nvisit.BREAK = BREAK;\n/** Do not visit the children of the current item */\nvisit.SKIP = SKIP;\n/** Remove the current item */\nvisit.REMOVE = REMOVE;\n/** Find the item at `path` from `cst` as the root */\nvisit.itemAtPath = (cst, path) => {\n let item = cst;\n for (const [field, index] of path) {\n const tok = item?.[field];\n if (tok && 'items' in tok) {\n item = tok.items[index];\n }\n else\n return undefined;\n }\n return item;\n};\n/**\n * Get the immediate parent collection of the item at `path` from `cst` as the root.\n *\n * Throws an error if the collection is not found, which should never happen if the item itself exists.\n */\nvisit.parentCollection = (cst, path) => {\n const parent = visit.itemAtPath(cst, path.slice(0, -1));\n const field = path[path.length - 1][0];\n const coll = parent?.[field];\n if (coll && 'items' in coll)\n return coll;\n throw new Error('Parent collection not found');\n};\nfunction _visit(path, item, visitor) {\n let ctrl = visitor(item, path);\n if (typeof ctrl === 'symbol')\n return ctrl;\n for (const field of ['key', 'value']) {\n const token = item[field];\n if (token && 'items' in token) {\n for (let i = 0; i < token.items.length; ++i) {\n const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);\n if (typeof ci === 'number')\n i = ci - 1;\n else if (ci === BREAK)\n return BREAK;\n else if (ci === REMOVE) {\n token.items.splice(i, 1);\n i -= 1;\n }\n }\n if (typeof ctrl === 'function' && field === 'key')\n ctrl = ctrl(item, path);\n }\n }\n return typeof ctrl === 'function' ? ctrl(item, path) : ctrl;\n}\n\nexports.visit = visit;\n",
|
|
71
|
+
"'use strict';\n\nvar cstScalar = require('./cst-scalar.js');\nvar cstStringify = require('./cst-stringify.js');\nvar cstVisit = require('./cst-visit.js');\n\n/** The byte order mark */\nconst BOM = '\\u{FEFF}';\n/** Start of doc-mode */\nconst DOCUMENT = '\\x02'; // C0: Start of Text\n/** Unexpected end of flow-mode */\nconst FLOW_END = '\\x18'; // C0: Cancel\n/** Next token is a scalar value */\nconst SCALAR = '\\x1f'; // C0: Unit Separator\n/** @returns `true` if `token` is a flow or block collection */\nconst isCollection = (token) => !!token && 'items' in token;\n/** @returns `true` if `token` is a flow or block scalar; not an alias */\nconst isScalar = (token) => !!token &&\n (token.type === 'scalar' ||\n token.type === 'single-quoted-scalar' ||\n token.type === 'double-quoted-scalar' ||\n token.type === 'block-scalar');\n/* istanbul ignore next */\n/** Get a printable representation of a lexer token */\nfunction prettyToken(token) {\n switch (token) {\n case BOM:\n return '<BOM>';\n case DOCUMENT:\n return '<DOC>';\n case FLOW_END:\n return '<FLOW_END>';\n case SCALAR:\n return '<SCALAR>';\n default:\n return JSON.stringify(token);\n }\n}\n/** Identify the type of a lexer token. May return `null` for unknown tokens. */\nfunction tokenType(source) {\n switch (source) {\n case BOM:\n return 'byte-order-mark';\n case DOCUMENT:\n return 'doc-mode';\n case FLOW_END:\n return 'flow-error-end';\n case SCALAR:\n return 'scalar';\n case '---':\n return 'doc-start';\n case '...':\n return 'doc-end';\n case '':\n case '\\n':\n case '\\r\\n':\n return 'newline';\n case '-':\n return 'seq-item-ind';\n case '?':\n return 'explicit-key-ind';\n case ':':\n return 'map-value-ind';\n case '{':\n return 'flow-map-start';\n case '}':\n return 'flow-map-end';\n case '[':\n return 'flow-seq-start';\n case ']':\n return 'flow-seq-end';\n case ',':\n return 'comma';\n }\n switch (source[0]) {\n case ' ':\n case '\\t':\n return 'space';\n case '#':\n return 'comment';\n case '%':\n return 'directive-line';\n case '*':\n return 'alias';\n case '&':\n return 'anchor';\n case '!':\n return 'tag';\n case \"'\":\n return 'single-quoted-scalar';\n case '\"':\n return 'double-quoted-scalar';\n case '|':\n case '>':\n return 'block-scalar-header';\n }\n return null;\n}\n\nexports.createScalarToken = cstScalar.createScalarToken;\nexports.resolveAsScalar = cstScalar.resolveAsScalar;\nexports.setScalarValue = cstScalar.setScalarValue;\nexports.stringify = cstStringify.stringify;\nexports.visit = cstVisit.visit;\nexports.BOM = BOM;\nexports.DOCUMENT = DOCUMENT;\nexports.FLOW_END = FLOW_END;\nexports.SCALAR = SCALAR;\nexports.isCollection = isCollection;\nexports.isScalar = isScalar;\nexports.prettyToken = prettyToken;\nexports.tokenType = tokenType;\n",
|
|
72
|
+
"'use strict';\n\nvar cst = require('./cst.js');\n\n/*\nSTART -> stream\n\nstream\n directive -> line-end -> stream\n indent + line-end -> stream\n [else] -> line-start\n\nline-end\n comment -> line-end\n newline -> .\n input-end -> END\n\nline-start\n doc-start -> doc\n doc-end -> stream\n [else] -> indent -> block-start\n\nblock-start\n seq-item-start -> block-start\n explicit-key-start -> block-start\n map-value-start -> block-start\n [else] -> doc\n\ndoc\n line-end -> line-start\n spaces -> doc\n anchor -> doc\n tag -> doc\n flow-start -> flow -> doc\n flow-end -> error -> doc\n seq-item-start -> error -> doc\n explicit-key-start -> error -> doc\n map-value-start -> doc\n alias -> doc\n quote-start -> quoted-scalar -> doc\n block-scalar-header -> line-end -> block-scalar(min) -> line-start\n [else] -> plain-scalar(false, min) -> doc\n\nflow\n line-end -> flow\n spaces -> flow\n anchor -> flow\n tag -> flow\n flow-start -> flow -> flow\n flow-end -> .\n seq-item-start -> error -> flow\n explicit-key-start -> flow\n map-value-start -> flow\n alias -> flow\n quote-start -> quoted-scalar -> flow\n comma -> flow\n [else] -> plain-scalar(true, 0) -> flow\n\nquoted-scalar\n quote-end -> .\n [else] -> quoted-scalar\n\nblock-scalar(min)\n newline + peek(indent < min) -> .\n [else] -> block-scalar(min)\n\nplain-scalar(is-flow, min)\n scalar-end(is-flow) -> .\n peek(newline + (indent < min)) -> .\n [else] -> plain-scalar(min)\n*/\nfunction isEmpty(ch) {\n switch (ch) {\n case undefined:\n case ' ':\n case '\\n':\n case '\\r':\n case '\\t':\n return true;\n default:\n return false;\n }\n}\nconst hexDigits = new Set('0123456789ABCDEFabcdef');\nconst tagChars = new Set(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()\");\nconst flowIndicatorChars = new Set(',[]{}');\nconst invalidAnchorChars = new Set(' ,[]{}\\n\\r\\t');\nconst isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);\n/**\n * Splits an input string into lexical tokens, i.e. smaller strings that are\n * easily identifiable by `tokens.tokenType()`.\n *\n * Lexing starts always in a \"stream\" context. Incomplete input may be buffered\n * until a complete token can be emitted.\n *\n * In addition to slices of the original input, the following control characters\n * may also be emitted:\n *\n * - `\\x02` (Start of Text): A document starts with the next token\n * - `\\x18` (Cancel): Unexpected end of flow-mode (indicates an error)\n * - `\\x1f` (Unit Separator): Next token is a scalar value\n * - `\\u{FEFF}` (Byte order mark): Emitted separately outside documents\n */\nclass Lexer {\n constructor() {\n /**\n * Flag indicating whether the end of the current buffer marks the end of\n * all input\n */\n this.atEnd = false;\n /**\n * Explicit indent set in block scalar header, as an offset from the current\n * minimum indent, so e.g. set to 1 from a header `|2+`. Set to -1 if not\n * explicitly set.\n */\n this.blockScalarIndent = -1;\n /**\n * Block scalars that include a + (keep) chomping indicator in their header\n * include trailing empty lines, which are otherwise excluded from the\n * scalar's contents.\n */\n this.blockScalarKeep = false;\n /** Current input */\n this.buffer = '';\n /**\n * Flag noting whether the map value indicator : can immediately follow this\n * node within a flow context.\n */\n this.flowKey = false;\n /** Count of surrounding flow collection levels. */\n this.flowLevel = 0;\n /**\n * Minimum level of indentation required for next lines to be parsed as a\n * part of the current scalar value.\n */\n this.indentNext = 0;\n /** Indentation level of the current line. */\n this.indentValue = 0;\n /** Position of the next \\n character. */\n this.lineEndPos = null;\n /** Stores the state of the lexer if reaching the end of incpomplete input */\n this.next = null;\n /** A pointer to `buffer`; the current position of the lexer. */\n this.pos = 0;\n }\n /**\n * Generate YAML tokens from the `source` string. If `incomplete`,\n * a part of the last line may be left as a buffer for the next call.\n *\n * @returns A generator of lexical tokens\n */\n *lex(source, incomplete = false) {\n if (source) {\n if (typeof source !== 'string')\n throw TypeError('source is not a string');\n this.buffer = this.buffer ? this.buffer + source : source;\n this.lineEndPos = null;\n }\n this.atEnd = !incomplete;\n let next = this.next ?? 'stream';\n while (next && (incomplete || this.hasChars(1)))\n next = yield* this.parseNext(next);\n }\n atLineEnd() {\n let i = this.pos;\n let ch = this.buffer[i];\n while (ch === ' ' || ch === '\\t')\n ch = this.buffer[++i];\n if (!ch || ch === '#' || ch === '\\n')\n return true;\n if (ch === '\\r')\n return this.buffer[i + 1] === '\\n';\n return false;\n }\n charAt(n) {\n return this.buffer[this.pos + n];\n }\n continueScalar(offset) {\n let ch = this.buffer[offset];\n if (this.indentNext > 0) {\n let indent = 0;\n while (ch === ' ')\n ch = this.buffer[++indent + offset];\n if (ch === '\\r') {\n const next = this.buffer[indent + offset + 1];\n if (next === '\\n' || (!next && !this.atEnd))\n return offset + indent + 1;\n }\n return ch === '\\n' || indent >= this.indentNext || (!ch && !this.atEnd)\n ? offset + indent\n : -1;\n }\n if (ch === '-' || ch === '.') {\n const dt = this.buffer.substr(offset, 3);\n if ((dt === '---' || dt === '...') && isEmpty(this.buffer[offset + 3]))\n return -1;\n }\n return offset;\n }\n getLine() {\n let end = this.lineEndPos;\n if (typeof end !== 'number' || (end !== -1 && end < this.pos)) {\n end = this.buffer.indexOf('\\n', this.pos);\n this.lineEndPos = end;\n }\n if (end === -1)\n return this.atEnd ? this.buffer.substring(this.pos) : null;\n if (this.buffer[end - 1] === '\\r')\n end -= 1;\n return this.buffer.substring(this.pos, end);\n }\n hasChars(n) {\n return this.pos + n <= this.buffer.length;\n }\n setNext(state) {\n this.buffer = this.buffer.substring(this.pos);\n this.pos = 0;\n this.lineEndPos = null;\n this.next = state;\n return null;\n }\n peek(n) {\n return this.buffer.substr(this.pos, n);\n }\n *parseNext(next) {\n switch (next) {\n case 'stream':\n return yield* this.parseStream();\n case 'line-start':\n return yield* this.parseLineStart();\n case 'block-start':\n return yield* this.parseBlockStart();\n case 'doc':\n return yield* this.parseDocument();\n case 'flow':\n return yield* this.parseFlowCollection();\n case 'quoted-scalar':\n return yield* this.parseQuotedScalar();\n case 'block-scalar':\n return yield* this.parseBlockScalar();\n case 'plain-scalar':\n return yield* this.parsePlainScalar();\n }\n }\n *parseStream() {\n let line = this.getLine();\n if (line === null)\n return this.setNext('stream');\n if (line[0] === cst.BOM) {\n yield* this.pushCount(1);\n line = line.substring(1);\n }\n if (line[0] === '%') {\n let dirEnd = line.length;\n let cs = line.indexOf('#');\n while (cs !== -1) {\n const ch = line[cs - 1];\n if (ch === ' ' || ch === '\\t') {\n dirEnd = cs - 1;\n break;\n }\n else {\n cs = line.indexOf('#', cs + 1);\n }\n }\n while (true) {\n const ch = line[dirEnd - 1];\n if (ch === ' ' || ch === '\\t')\n dirEnd -= 1;\n else\n break;\n }\n const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));\n yield* this.pushCount(line.length - n); // possible comment\n this.pushNewline();\n return 'stream';\n }\n if (this.atLineEnd()) {\n const sp = yield* this.pushSpaces(true);\n yield* this.pushCount(line.length - sp);\n yield* this.pushNewline();\n return 'stream';\n }\n yield cst.DOCUMENT;\n return yield* this.parseLineStart();\n }\n *parseLineStart() {\n const ch = this.charAt(0);\n if (!ch && !this.atEnd)\n return this.setNext('line-start');\n if (ch === '-' || ch === '.') {\n if (!this.atEnd && !this.hasChars(4))\n return this.setNext('line-start');\n const s = this.peek(3);\n if ((s === '---' || s === '...') && isEmpty(this.charAt(3))) {\n yield* this.pushCount(3);\n this.indentValue = 0;\n this.indentNext = 0;\n return s === '---' ? 'doc' : 'stream';\n }\n }\n this.indentValue = yield* this.pushSpaces(false);\n if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))\n this.indentNext = this.indentValue;\n return yield* this.parseBlockStart();\n }\n *parseBlockStart() {\n const [ch0, ch1] = this.peek(2);\n if (!ch1 && !this.atEnd)\n return this.setNext('block-start');\n if ((ch0 === '-' || ch0 === '?' || ch0 === ':') && isEmpty(ch1)) {\n const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));\n this.indentNext = this.indentValue + 1;\n this.indentValue += n;\n return 'block-start';\n }\n return 'doc';\n }\n *parseDocument() {\n yield* this.pushSpaces(true);\n const line = this.getLine();\n if (line === null)\n return this.setNext('doc');\n let n = yield* this.pushIndicators();\n switch (line[n]) {\n case '#':\n yield* this.pushCount(line.length - n);\n // fallthrough\n case undefined:\n yield* this.pushNewline();\n return yield* this.parseLineStart();\n case '{':\n case '[':\n yield* this.pushCount(1);\n this.flowKey = false;\n this.flowLevel = 1;\n return 'flow';\n case '}':\n case ']':\n // this is an error\n yield* this.pushCount(1);\n return 'doc';\n case '*':\n yield* this.pushUntil(isNotAnchorChar);\n return 'doc';\n case '\"':\n case \"'\":\n return yield* this.parseQuotedScalar();\n case '|':\n case '>':\n n += yield* this.parseBlockScalarHeader();\n n += yield* this.pushSpaces(true);\n yield* this.pushCount(line.length - n);\n yield* this.pushNewline();\n return yield* this.parseBlockScalar();\n default:\n return yield* this.parsePlainScalar();\n }\n }\n *parseFlowCollection() {\n let nl, sp;\n let indent = -1;\n do {\n nl = yield* this.pushNewline();\n if (nl > 0) {\n sp = yield* this.pushSpaces(false);\n this.indentValue = indent = sp;\n }\n else {\n sp = 0;\n }\n sp += yield* this.pushSpaces(true);\n } while (nl + sp > 0);\n const line = this.getLine();\n if (line === null)\n return this.setNext('flow');\n if ((indent !== -1 && indent < this.indentNext && line[0] !== '#') ||\n (indent === 0 &&\n (line.startsWith('---') || line.startsWith('...')) &&\n isEmpty(line[3]))) {\n // Allowing for the terminal ] or } at the same (rather than greater)\n // indent level as the initial [ or { is technically invalid, but\n // failing here would be surprising to users.\n const atFlowEndMarker = indent === this.indentNext - 1 &&\n this.flowLevel === 1 &&\n (line[0] === ']' || line[0] === '}');\n if (!atFlowEndMarker) {\n // this is an error\n this.flowLevel = 0;\n yield cst.FLOW_END;\n return yield* this.parseLineStart();\n }\n }\n let n = 0;\n while (line[n] === ',') {\n n += yield* this.pushCount(1);\n n += yield* this.pushSpaces(true);\n this.flowKey = false;\n }\n n += yield* this.pushIndicators();\n switch (line[n]) {\n case undefined:\n return 'flow';\n case '#':\n yield* this.pushCount(line.length - n);\n return 'flow';\n case '{':\n case '[':\n yield* this.pushCount(1);\n this.flowKey = false;\n this.flowLevel += 1;\n return 'flow';\n case '}':\n case ']':\n yield* this.pushCount(1);\n this.flowKey = true;\n this.flowLevel -= 1;\n return this.flowLevel ? 'flow' : 'doc';\n case '*':\n yield* this.pushUntil(isNotAnchorChar);\n return 'flow';\n case '\"':\n case \"'\":\n this.flowKey = true;\n return yield* this.parseQuotedScalar();\n case ':': {\n const next = this.charAt(1);\n if (this.flowKey || isEmpty(next) || next === ',') {\n this.flowKey = false;\n yield* this.pushCount(1);\n yield* this.pushSpaces(true);\n return 'flow';\n }\n }\n // fallthrough\n default:\n this.flowKey = false;\n return yield* this.parsePlainScalar();\n }\n }\n *parseQuotedScalar() {\n const quote = this.charAt(0);\n let end = this.buffer.indexOf(quote, this.pos + 1);\n if (quote === \"'\") {\n while (end !== -1 && this.buffer[end + 1] === \"'\")\n end = this.buffer.indexOf(\"'\", end + 2);\n }\n else {\n // double-quote\n while (end !== -1) {\n let n = 0;\n while (this.buffer[end - 1 - n] === '\\\\')\n n += 1;\n if (n % 2 === 0)\n break;\n end = this.buffer.indexOf('\"', end + 1);\n }\n }\n // Only looking for newlines within the quotes\n const qb = this.buffer.substring(0, end);\n let nl = qb.indexOf('\\n', this.pos);\n if (nl !== -1) {\n while (nl !== -1) {\n const cs = this.continueScalar(nl + 1);\n if (cs === -1)\n break;\n nl = qb.indexOf('\\n', cs);\n }\n if (nl !== -1) {\n // this is an error caused by an unexpected unindent\n end = nl - (qb[nl - 1] === '\\r' ? 2 : 1);\n }\n }\n if (end === -1) {\n if (!this.atEnd)\n return this.setNext('quoted-scalar');\n end = this.buffer.length;\n }\n yield* this.pushToIndex(end + 1, false);\n return this.flowLevel ? 'flow' : 'doc';\n }\n *parseBlockScalarHeader() {\n this.blockScalarIndent = -1;\n this.blockScalarKeep = false;\n let i = this.pos;\n while (true) {\n const ch = this.buffer[++i];\n if (ch === '+')\n this.blockScalarKeep = true;\n else if (ch > '0' && ch <= '9')\n this.blockScalarIndent = Number(ch) - 1;\n else if (ch !== '-')\n break;\n }\n return yield* this.pushUntil(ch => isEmpty(ch) || ch === '#');\n }\n *parseBlockScalar() {\n let nl = this.pos - 1; // may be -1 if this.pos === 0\n let indent = 0;\n let ch;\n loop: for (let i = this.pos; (ch = this.buffer[i]); ++i) {\n switch (ch) {\n case ' ':\n indent += 1;\n break;\n case '\\n':\n nl = i;\n indent = 0;\n break;\n case '\\r': {\n const next = this.buffer[i + 1];\n if (!next && !this.atEnd)\n return this.setNext('block-scalar');\n if (next === '\\n')\n break;\n } // fallthrough\n default:\n break loop;\n }\n }\n if (!ch && !this.atEnd)\n return this.setNext('block-scalar');\n if (indent >= this.indentNext) {\n if (this.blockScalarIndent === -1)\n this.indentNext = indent;\n else {\n this.indentNext =\n this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);\n }\n do {\n const cs = this.continueScalar(nl + 1);\n if (cs === -1)\n break;\n nl = this.buffer.indexOf('\\n', cs);\n } while (nl !== -1);\n if (nl === -1) {\n if (!this.atEnd)\n return this.setNext('block-scalar');\n nl = this.buffer.length;\n }\n }\n // Trailing insufficiently indented tabs are invalid.\n // To catch that during parsing, we include them in the block scalar value.\n let i = nl + 1;\n ch = this.buffer[i];\n while (ch === ' ')\n ch = this.buffer[++i];\n if (ch === '\\t') {\n while (ch === '\\t' || ch === ' ' || ch === '\\r' || ch === '\\n')\n ch = this.buffer[++i];\n nl = i - 1;\n }\n else if (!this.blockScalarKeep) {\n do {\n let i = nl - 1;\n let ch = this.buffer[i];\n if (ch === '\\r')\n ch = this.buffer[--i];\n const lastChar = i; // Drop the line if last char not more indented\n while (ch === ' ')\n ch = this.buffer[--i];\n if (ch === '\\n' && i >= this.pos && i + 1 + indent > lastChar)\n nl = i;\n else\n break;\n } while (true);\n }\n yield cst.SCALAR;\n yield* this.pushToIndex(nl + 1, true);\n return yield* this.parseLineStart();\n }\n *parsePlainScalar() {\n const inFlow = this.flowLevel > 0;\n let end = this.pos - 1;\n let i = this.pos - 1;\n let ch;\n while ((ch = this.buffer[++i])) {\n if (ch === ':') {\n const next = this.buffer[i + 1];\n if (isEmpty(next) || (inFlow && flowIndicatorChars.has(next)))\n break;\n end = i;\n }\n else if (isEmpty(ch)) {\n let next = this.buffer[i + 1];\n if (ch === '\\r') {\n if (next === '\\n') {\n i += 1;\n ch = '\\n';\n next = this.buffer[i + 1];\n }\n else\n end = i;\n }\n if (next === '#' || (inFlow && flowIndicatorChars.has(next)))\n break;\n if (ch === '\\n') {\n const cs = this.continueScalar(i + 1);\n if (cs === -1)\n break;\n i = Math.max(i, cs - 2); // to advance, but still account for ' #'\n }\n }\n else {\n if (inFlow && flowIndicatorChars.has(ch))\n break;\n end = i;\n }\n }\n if (!ch && !this.atEnd)\n return this.setNext('plain-scalar');\n yield cst.SCALAR;\n yield* this.pushToIndex(end + 1, true);\n return inFlow ? 'flow' : 'doc';\n }\n *pushCount(n) {\n if (n > 0) {\n yield this.buffer.substr(this.pos, n);\n this.pos += n;\n return n;\n }\n return 0;\n }\n *pushToIndex(i, allowEmpty) {\n const s = this.buffer.slice(this.pos, i);\n if (s) {\n yield s;\n this.pos += s.length;\n return s.length;\n }\n else if (allowEmpty)\n yield '';\n return 0;\n }\n *pushIndicators() {\n let n = 0;\n loop: while (true) {\n switch (this.charAt(0)) {\n case '!':\n n += yield* this.pushTag();\n n += yield* this.pushSpaces(true);\n continue loop;\n case '&':\n n += yield* this.pushUntil(isNotAnchorChar);\n n += yield* this.pushSpaces(true);\n continue loop;\n case '-': // this is an error\n case '?': // this is an error outside flow collections\n case ':': {\n const inFlow = this.flowLevel > 0;\n const ch1 = this.charAt(1);\n if (isEmpty(ch1) || (inFlow && flowIndicatorChars.has(ch1))) {\n if (!inFlow)\n this.indentNext = this.indentValue + 1;\n else if (this.flowKey)\n this.flowKey = false;\n n += yield* this.pushCount(1);\n n += yield* this.pushSpaces(true);\n continue loop;\n }\n }\n }\n break loop;\n }\n return n;\n }\n *pushTag() {\n if (this.charAt(1) === '<') {\n let i = this.pos + 2;\n let ch = this.buffer[i];\n while (!isEmpty(ch) && ch !== '>')\n ch = this.buffer[++i];\n return yield* this.pushToIndex(ch === '>' ? i + 1 : i, false);\n }\n else {\n let i = this.pos + 1;\n let ch = this.buffer[i];\n while (ch) {\n if (tagChars.has(ch))\n ch = this.buffer[++i];\n else if (ch === '%' &&\n hexDigits.has(this.buffer[i + 1]) &&\n hexDigits.has(this.buffer[i + 2])) {\n ch = this.buffer[(i += 3)];\n }\n else\n break;\n }\n return yield* this.pushToIndex(i, false);\n }\n }\n *pushNewline() {\n const ch = this.buffer[this.pos];\n if (ch === '\\n')\n return yield* this.pushCount(1);\n else if (ch === '\\r' && this.charAt(1) === '\\n')\n return yield* this.pushCount(2);\n else\n return 0;\n }\n *pushSpaces(allowTabs) {\n let i = this.pos - 1;\n let ch;\n do {\n ch = this.buffer[++i];\n } while (ch === ' ' || (allowTabs && ch === '\\t'));\n const n = i - this.pos;\n if (n > 0) {\n yield this.buffer.substr(this.pos, n);\n this.pos = i;\n }\n return n;\n }\n *pushUntil(test) {\n let i = this.pos;\n let ch = this.buffer[i];\n while (!test(ch))\n ch = this.buffer[++i];\n return yield* this.pushToIndex(i, false);\n }\n}\n\nexports.Lexer = Lexer;\n",
|
|
73
|
+
"'use strict';\n\n/**\n * Tracks newlines during parsing in order to provide an efficient API for\n * determining the one-indexed `{ line, col }` position for any offset\n * within the input.\n */\nclass LineCounter {\n constructor() {\n this.lineStarts = [];\n /**\n * Should be called in ascending order. Otherwise, call\n * `lineCounter.lineStarts.sort()` before calling `linePos()`.\n */\n this.addNewLine = (offset) => this.lineStarts.push(offset);\n /**\n * Performs a binary search and returns the 1-indexed { line, col }\n * position of `offset`. If `line === 0`, `addNewLine` has never been\n * called or `offset` is before the first known newline.\n */\n this.linePos = (offset) => {\n let low = 0;\n let high = this.lineStarts.length;\n while (low < high) {\n const mid = (low + high) >> 1; // Math.floor((low + high) / 2)\n if (this.lineStarts[mid] < offset)\n low = mid + 1;\n else\n high = mid;\n }\n if (this.lineStarts[low] === offset)\n return { line: low + 1, col: 1 };\n if (low === 0)\n return { line: 0, col: offset };\n const start = this.lineStarts[low - 1];\n return { line: low, col: offset - start + 1 };\n };\n }\n}\n\nexports.LineCounter = LineCounter;\n",
|
|
74
|
+
"'use strict';\n\nvar node_process = require('process');\nvar cst = require('./cst.js');\nvar lexer = require('./lexer.js');\n\nfunction includesToken(list, type) {\n for (let i = 0; i < list.length; ++i)\n if (list[i].type === type)\n return true;\n return false;\n}\nfunction findNonEmptyIndex(list) {\n for (let i = 0; i < list.length; ++i) {\n switch (list[i].type) {\n case 'space':\n case 'comment':\n case 'newline':\n break;\n default:\n return i;\n }\n }\n return -1;\n}\nfunction isFlowToken(token) {\n switch (token?.type) {\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n case 'flow-collection':\n return true;\n default:\n return false;\n }\n}\nfunction getPrevProps(parent) {\n switch (parent.type) {\n case 'document':\n return parent.start;\n case 'block-map': {\n const it = parent.items[parent.items.length - 1];\n return it.sep ?? it.start;\n }\n case 'block-seq':\n return parent.items[parent.items.length - 1].start;\n /* istanbul ignore next should not happen */\n default:\n return [];\n }\n}\n/** Note: May modify input array */\nfunction getFirstKeyStartProps(prev) {\n if (prev.length === 0)\n return [];\n let i = prev.length;\n loop: while (--i >= 0) {\n switch (prev[i].type) {\n case 'doc-start':\n case 'explicit-key-ind':\n case 'map-value-ind':\n case 'seq-item-ind':\n case 'newline':\n break loop;\n }\n }\n while (prev[++i]?.type === 'space') {\n /* loop */\n }\n return prev.splice(i, prev.length);\n}\nfunction arrayPushArray(target, source) {\n // May exhaust call stack with large `source` array\n if (source.length < 1e5)\n Array.prototype.push.apply(target, source);\n else\n for (let i = 0; i < source.length; ++i)\n target.push(source[i]);\n}\nfunction fixFlowSeqItems(fc) {\n if (fc.start.type === 'flow-seq-start') {\n for (const it of fc.items) {\n if (it.sep &&\n !it.value &&\n !includesToken(it.start, 'explicit-key-ind') &&\n !includesToken(it.sep, 'map-value-ind')) {\n if (it.key)\n it.value = it.key;\n delete it.key;\n if (isFlowToken(it.value)) {\n if (it.value.end)\n arrayPushArray(it.value.end, it.sep);\n else\n it.value.end = it.sep;\n }\n else\n arrayPushArray(it.start, it.sep);\n delete it.sep;\n }\n }\n }\n}\n/**\n * A YAML concrete syntax tree (CST) parser\n *\n * ```ts\n * const src: string = ...\n * for (const token of new Parser().parse(src)) {\n * // token: Token\n * }\n * ```\n *\n * To use the parser with a user-provided lexer:\n *\n * ```ts\n * function* parse(source: string, lexer: Lexer) {\n * const parser = new Parser()\n * for (const lexeme of lexer.lex(source))\n * yield* parser.next(lexeme)\n * yield* parser.end()\n * }\n *\n * const src: string = ...\n * const lexer = new Lexer()\n * for (const token of parse(src, lexer)) {\n * // token: Token\n * }\n * ```\n */\nclass Parser {\n /**\n * @param onNewLine - If defined, called separately with the start position of\n * each new line (in `parse()`, including the start of input).\n */\n constructor(onNewLine) {\n /** If true, space and sequence indicators count as indentation */\n this.atNewLine = true;\n /** If true, next token is a scalar value */\n this.atScalar = false;\n /** Current indentation level */\n this.indent = 0;\n /** Current offset since the start of parsing */\n this.offset = 0;\n /** On the same line with a block map key */\n this.onKeyLine = false;\n /** Top indicates the node that's currently being built */\n this.stack = [];\n /** The source of the current token, set in parse() */\n this.source = '';\n /** The type of the current token, set in parse() */\n this.type = '';\n // Must be defined after `next()`\n this.lexer = new lexer.Lexer();\n this.onNewLine = onNewLine;\n }\n /**\n * Parse `source` as a YAML stream.\n * If `incomplete`, a part of the last line may be left as a buffer for the next call.\n *\n * Errors are not thrown, but yielded as `{ type: 'error', message }` tokens.\n *\n * @returns A generator of tokens representing each directive, document, and other structure.\n */\n *parse(source, incomplete = false) {\n if (this.onNewLine && this.offset === 0)\n this.onNewLine(0);\n for (const lexeme of this.lexer.lex(source, incomplete))\n yield* this.next(lexeme);\n if (!incomplete)\n yield* this.end();\n }\n /**\n * Advance the parser by the `source` of one lexical token.\n */\n *next(source) {\n this.source = source;\n if (node_process.env.LOG_TOKENS)\n console.log('|', cst.prettyToken(source));\n if (this.atScalar) {\n this.atScalar = false;\n yield* this.step();\n this.offset += source.length;\n return;\n }\n const type = cst.tokenType(source);\n if (!type) {\n const message = `Not a YAML token: ${source}`;\n yield* this.pop({ type: 'error', offset: this.offset, message, source });\n this.offset += source.length;\n }\n else if (type === 'scalar') {\n this.atNewLine = false;\n this.atScalar = true;\n this.type = 'scalar';\n }\n else {\n this.type = type;\n yield* this.step();\n switch (type) {\n case 'newline':\n this.atNewLine = true;\n this.indent = 0;\n if (this.onNewLine)\n this.onNewLine(this.offset + source.length);\n break;\n case 'space':\n if (this.atNewLine && source[0] === ' ')\n this.indent += source.length;\n break;\n case 'explicit-key-ind':\n case 'map-value-ind':\n case 'seq-item-ind':\n if (this.atNewLine)\n this.indent += source.length;\n break;\n case 'doc-mode':\n case 'flow-error-end':\n return;\n default:\n this.atNewLine = false;\n }\n this.offset += source.length;\n }\n }\n /** Call at end of input to push out any remaining constructions */\n *end() {\n while (this.stack.length > 0)\n yield* this.pop();\n }\n get sourceToken() {\n const st = {\n type: this.type,\n offset: this.offset,\n indent: this.indent,\n source: this.source\n };\n return st;\n }\n *step() {\n const top = this.peek(1);\n if (this.type === 'doc-end' && top?.type !== 'doc-end') {\n while (this.stack.length > 0)\n yield* this.pop();\n this.stack.push({\n type: 'doc-end',\n offset: this.offset,\n source: this.source\n });\n return;\n }\n if (!top)\n return yield* this.stream();\n switch (top.type) {\n case 'document':\n return yield* this.document(top);\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n return yield* this.scalar(top);\n case 'block-scalar':\n return yield* this.blockScalar(top);\n case 'block-map':\n return yield* this.blockMap(top);\n case 'block-seq':\n return yield* this.blockSequence(top);\n case 'flow-collection':\n return yield* this.flowCollection(top);\n case 'doc-end':\n return yield* this.documentEnd(top);\n }\n /* istanbul ignore next should not happen */\n yield* this.pop();\n }\n peek(n) {\n return this.stack[this.stack.length - n];\n }\n *pop(error) {\n const token = error ?? this.stack.pop();\n /* istanbul ignore if should not happen */\n if (!token) {\n const message = 'Tried to pop an empty stack';\n yield { type: 'error', offset: this.offset, source: '', message };\n }\n else if (this.stack.length === 0) {\n yield token;\n }\n else {\n const top = this.peek(1);\n if (token.type === 'block-scalar') {\n // Block scalars use their parent rather than header indent\n token.indent = 'indent' in top ? top.indent : 0;\n }\n else if (token.type === 'flow-collection' && top.type === 'document') {\n // Ignore all indent for top-level flow collections\n token.indent = 0;\n }\n if (token.type === 'flow-collection')\n fixFlowSeqItems(token);\n switch (top.type) {\n case 'document':\n top.value = token;\n break;\n case 'block-scalar':\n top.props.push(token); // error\n break;\n case 'block-map': {\n const it = top.items[top.items.length - 1];\n if (it.value) {\n top.items.push({ start: [], key: token, sep: [] });\n this.onKeyLine = true;\n return;\n }\n else if (it.sep) {\n it.value = token;\n }\n else {\n Object.assign(it, { key: token, sep: [] });\n this.onKeyLine = !it.explicitKey;\n return;\n }\n break;\n }\n case 'block-seq': {\n const it = top.items[top.items.length - 1];\n if (it.value)\n top.items.push({ start: [], value: token });\n else\n it.value = token;\n break;\n }\n case 'flow-collection': {\n const it = top.items[top.items.length - 1];\n if (!it || it.value)\n top.items.push({ start: [], key: token, sep: [] });\n else if (it.sep)\n it.value = token;\n else\n Object.assign(it, { key: token, sep: [] });\n return;\n }\n /* istanbul ignore next should not happen */\n default:\n yield* this.pop();\n yield* this.pop(token);\n }\n if ((top.type === 'document' ||\n top.type === 'block-map' ||\n top.type === 'block-seq') &&\n (token.type === 'block-map' || token.type === 'block-seq')) {\n const last = token.items[token.items.length - 1];\n if (last &&\n !last.sep &&\n !last.value &&\n last.start.length > 0 &&\n findNonEmptyIndex(last.start) === -1 &&\n (token.indent === 0 ||\n last.start.every(st => st.type !== 'comment' || st.indent < token.indent))) {\n if (top.type === 'document')\n top.end = last.start;\n else\n top.items.push({ start: last.start });\n token.items.splice(-1, 1);\n }\n }\n }\n }\n *stream() {\n switch (this.type) {\n case 'directive-line':\n yield { type: 'directive', offset: this.offset, source: this.source };\n return;\n case 'byte-order-mark':\n case 'space':\n case 'comment':\n case 'newline':\n yield this.sourceToken;\n return;\n case 'doc-mode':\n case 'doc-start': {\n const doc = {\n type: 'document',\n offset: this.offset,\n start: []\n };\n if (this.type === 'doc-start')\n doc.start.push(this.sourceToken);\n this.stack.push(doc);\n return;\n }\n }\n yield {\n type: 'error',\n offset: this.offset,\n message: `Unexpected ${this.type} token in YAML stream`,\n source: this.source\n };\n }\n *document(doc) {\n if (doc.value)\n return yield* this.lineEnd(doc);\n switch (this.type) {\n case 'doc-start': {\n if (findNonEmptyIndex(doc.start) !== -1) {\n yield* this.pop();\n yield* this.step();\n }\n else\n doc.start.push(this.sourceToken);\n return;\n }\n case 'anchor':\n case 'tag':\n case 'space':\n case 'comment':\n case 'newline':\n doc.start.push(this.sourceToken);\n return;\n }\n const bv = this.startBlockValue(doc);\n if (bv)\n this.stack.push(bv);\n else {\n yield {\n type: 'error',\n offset: this.offset,\n message: `Unexpected ${this.type} token in YAML document`,\n source: this.source\n };\n }\n }\n *scalar(scalar) {\n if (this.type === 'map-value-ind') {\n const prev = getPrevProps(this.peek(2));\n const start = getFirstKeyStartProps(prev);\n let sep;\n if (scalar.end) {\n sep = scalar.end;\n sep.push(this.sourceToken);\n delete scalar.end;\n }\n else\n sep = [this.sourceToken];\n const map = {\n type: 'block-map',\n offset: scalar.offset,\n indent: scalar.indent,\n items: [{ start, key: scalar, sep }]\n };\n this.onKeyLine = true;\n this.stack[this.stack.length - 1] = map;\n }\n else\n yield* this.lineEnd(scalar);\n }\n *blockScalar(scalar) {\n switch (this.type) {\n case 'space':\n case 'comment':\n case 'newline':\n scalar.props.push(this.sourceToken);\n return;\n case 'scalar':\n scalar.source = this.source;\n // block-scalar source includes trailing newline\n this.atNewLine = true;\n this.indent = 0;\n if (this.onNewLine) {\n let nl = this.source.indexOf('\\n') + 1;\n while (nl !== 0) {\n this.onNewLine(this.offset + nl);\n nl = this.source.indexOf('\\n', nl) + 1;\n }\n }\n yield* this.pop();\n break;\n /* istanbul ignore next should not happen */\n default:\n yield* this.pop();\n yield* this.step();\n }\n }\n *blockMap(map) {\n const it = map.items[map.items.length - 1];\n // it.sep is true-ish if pair already has key or : separator\n switch (this.type) {\n case 'newline':\n this.onKeyLine = false;\n if (it.value) {\n const end = 'end' in it.value ? it.value.end : undefined;\n const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n if (last?.type === 'comment')\n end?.push(this.sourceToken);\n else\n map.items.push({ start: [this.sourceToken] });\n }\n else if (it.sep) {\n it.sep.push(this.sourceToken);\n }\n else {\n it.start.push(this.sourceToken);\n }\n return;\n case 'space':\n case 'comment':\n if (it.value) {\n map.items.push({ start: [this.sourceToken] });\n }\n else if (it.sep) {\n it.sep.push(this.sourceToken);\n }\n else {\n if (this.atIndentedComment(it.start, map.indent)) {\n const prev = map.items[map.items.length - 2];\n const end = prev?.value?.end;\n if (Array.isArray(end)) {\n arrayPushArray(end, it.start);\n end.push(this.sourceToken);\n map.items.pop();\n return;\n }\n }\n it.start.push(this.sourceToken);\n }\n return;\n }\n if (this.indent >= map.indent) {\n const atMapIndent = !this.onKeyLine && this.indent === map.indent;\n const atNextItem = atMapIndent &&\n (it.sep || it.explicitKey) &&\n this.type !== 'seq-item-ind';\n // For empty nodes, assign newline-separated not indented empty tokens to following node\n let start = [];\n if (atNextItem && it.sep && !it.value) {\n const nl = [];\n for (let i = 0; i < it.sep.length; ++i) {\n const st = it.sep[i];\n switch (st.type) {\n case 'newline':\n nl.push(i);\n break;\n case 'space':\n break;\n case 'comment':\n if (st.indent > map.indent)\n nl.length = 0;\n break;\n default:\n nl.length = 0;\n }\n }\n if (nl.length >= 2)\n start = it.sep.splice(nl[1]);\n }\n switch (this.type) {\n case 'anchor':\n case 'tag':\n if (atNextItem || it.value) {\n start.push(this.sourceToken);\n map.items.push({ start });\n this.onKeyLine = true;\n }\n else if (it.sep) {\n it.sep.push(this.sourceToken);\n }\n else {\n it.start.push(this.sourceToken);\n }\n return;\n case 'explicit-key-ind':\n if (!it.sep && !it.explicitKey) {\n it.start.push(this.sourceToken);\n it.explicitKey = true;\n }\n else if (atNextItem || it.value) {\n start.push(this.sourceToken);\n map.items.push({ start, explicitKey: true });\n }\n else {\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start: [this.sourceToken], explicitKey: true }]\n });\n }\n this.onKeyLine = true;\n return;\n case 'map-value-ind':\n if (it.explicitKey) {\n if (!it.sep) {\n if (includesToken(it.start, 'newline')) {\n Object.assign(it, { key: null, sep: [this.sourceToken] });\n }\n else {\n const start = getFirstKeyStartProps(it.start);\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, key: null, sep: [this.sourceToken] }]\n });\n }\n }\n else if (it.value) {\n map.items.push({ start: [], key: null, sep: [this.sourceToken] });\n }\n else if (includesToken(it.sep, 'map-value-ind')) {\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, key: null, sep: [this.sourceToken] }]\n });\n }\n else if (isFlowToken(it.key) &&\n !includesToken(it.sep, 'newline')) {\n const start = getFirstKeyStartProps(it.start);\n const key = it.key;\n const sep = it.sep;\n sep.push(this.sourceToken);\n // @ts-expect-error type guard is wrong here\n delete it.key;\n // @ts-expect-error type guard is wrong here\n delete it.sep;\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, key, sep }]\n });\n }\n else if (start.length > 0) {\n // Not actually at next item\n it.sep = it.sep.concat(start, this.sourceToken);\n }\n else {\n it.sep.push(this.sourceToken);\n }\n }\n else {\n if (!it.sep) {\n Object.assign(it, { key: null, sep: [this.sourceToken] });\n }\n else if (it.value || atNextItem) {\n map.items.push({ start, key: null, sep: [this.sourceToken] });\n }\n else if (includesToken(it.sep, 'map-value-ind')) {\n this.stack.push({\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start: [], key: null, sep: [this.sourceToken] }]\n });\n }\n else {\n it.sep.push(this.sourceToken);\n }\n }\n this.onKeyLine = true;\n return;\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar': {\n const fs = this.flowScalar(this.type);\n if (atNextItem || it.value) {\n map.items.push({ start, key: fs, sep: [] });\n this.onKeyLine = true;\n }\n else if (it.sep) {\n this.stack.push(fs);\n }\n else {\n Object.assign(it, { key: fs, sep: [] });\n this.onKeyLine = true;\n }\n return;\n }\n default: {\n const bv = this.startBlockValue(map);\n if (bv) {\n if (bv.type === 'block-seq') {\n if (!it.explicitKey &&\n it.sep &&\n !includesToken(it.sep, 'newline')) {\n yield* this.pop({\n type: 'error',\n offset: this.offset,\n message: 'Unexpected block-seq-ind on same line with key',\n source: this.source\n });\n return;\n }\n }\n else if (atMapIndent) {\n map.items.push({ start });\n }\n this.stack.push(bv);\n return;\n }\n }\n }\n }\n yield* this.pop();\n yield* this.step();\n }\n *blockSequence(seq) {\n const it = seq.items[seq.items.length - 1];\n switch (this.type) {\n case 'newline':\n if (it.value) {\n const end = 'end' in it.value ? it.value.end : undefined;\n const last = Array.isArray(end) ? end[end.length - 1] : undefined;\n if (last?.type === 'comment')\n end?.push(this.sourceToken);\n else\n seq.items.push({ start: [this.sourceToken] });\n }\n else\n it.start.push(this.sourceToken);\n return;\n case 'space':\n case 'comment':\n if (it.value)\n seq.items.push({ start: [this.sourceToken] });\n else {\n if (this.atIndentedComment(it.start, seq.indent)) {\n const prev = seq.items[seq.items.length - 2];\n const end = prev?.value?.end;\n if (Array.isArray(end)) {\n arrayPushArray(end, it.start);\n end.push(this.sourceToken);\n seq.items.pop();\n return;\n }\n }\n it.start.push(this.sourceToken);\n }\n return;\n case 'anchor':\n case 'tag':\n if (it.value || this.indent <= seq.indent)\n break;\n it.start.push(this.sourceToken);\n return;\n case 'seq-item-ind':\n if (this.indent !== seq.indent)\n break;\n if (it.value || includesToken(it.start, 'seq-item-ind'))\n seq.items.push({ start: [this.sourceToken] });\n else\n it.start.push(this.sourceToken);\n return;\n }\n if (this.indent > seq.indent) {\n const bv = this.startBlockValue(seq);\n if (bv) {\n this.stack.push(bv);\n return;\n }\n }\n yield* this.pop();\n yield* this.step();\n }\n *flowCollection(fc) {\n const it = fc.items[fc.items.length - 1];\n if (this.type === 'flow-error-end') {\n let top;\n do {\n yield* this.pop();\n top = this.peek(1);\n } while (top?.type === 'flow-collection');\n }\n else if (fc.end.length === 0) {\n switch (this.type) {\n case 'comma':\n case 'explicit-key-ind':\n if (!it || it.sep)\n fc.items.push({ start: [this.sourceToken] });\n else\n it.start.push(this.sourceToken);\n return;\n case 'map-value-ind':\n if (!it || it.value)\n fc.items.push({ start: [], key: null, sep: [this.sourceToken] });\n else if (it.sep)\n it.sep.push(this.sourceToken);\n else\n Object.assign(it, { key: null, sep: [this.sourceToken] });\n return;\n case 'space':\n case 'comment':\n case 'newline':\n case 'anchor':\n case 'tag':\n if (!it || it.value)\n fc.items.push({ start: [this.sourceToken] });\n else if (it.sep)\n it.sep.push(this.sourceToken);\n else\n it.start.push(this.sourceToken);\n return;\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar': {\n const fs = this.flowScalar(this.type);\n if (!it || it.value)\n fc.items.push({ start: [], key: fs, sep: [] });\n else if (it.sep)\n this.stack.push(fs);\n else\n Object.assign(it, { key: fs, sep: [] });\n return;\n }\n case 'flow-map-end':\n case 'flow-seq-end':\n fc.end.push(this.sourceToken);\n return;\n }\n const bv = this.startBlockValue(fc);\n /* istanbul ignore else should not happen */\n if (bv)\n this.stack.push(bv);\n else {\n yield* this.pop();\n yield* this.step();\n }\n }\n else {\n const parent = this.peek(2);\n if (parent.type === 'block-map' &&\n ((this.type === 'map-value-ind' && parent.indent === fc.indent) ||\n (this.type === 'newline' &&\n !parent.items[parent.items.length - 1].sep))) {\n yield* this.pop();\n yield* this.step();\n }\n else if (this.type === 'map-value-ind' &&\n parent.type !== 'flow-collection') {\n const prev = getPrevProps(parent);\n const start = getFirstKeyStartProps(prev);\n fixFlowSeqItems(fc);\n const sep = fc.end.splice(1, fc.end.length);\n sep.push(this.sourceToken);\n const map = {\n type: 'block-map',\n offset: fc.offset,\n indent: fc.indent,\n items: [{ start, key: fc, sep }]\n };\n this.onKeyLine = true;\n this.stack[this.stack.length - 1] = map;\n }\n else {\n yield* this.lineEnd(fc);\n }\n }\n }\n flowScalar(type) {\n if (this.onNewLine) {\n let nl = this.source.indexOf('\\n') + 1;\n while (nl !== 0) {\n this.onNewLine(this.offset + nl);\n nl = this.source.indexOf('\\n', nl) + 1;\n }\n }\n return {\n type,\n offset: this.offset,\n indent: this.indent,\n source: this.source\n };\n }\n startBlockValue(parent) {\n switch (this.type) {\n case 'alias':\n case 'scalar':\n case 'single-quoted-scalar':\n case 'double-quoted-scalar':\n return this.flowScalar(this.type);\n case 'block-scalar-header':\n return {\n type: 'block-scalar',\n offset: this.offset,\n indent: this.indent,\n props: [this.sourceToken],\n source: ''\n };\n case 'flow-map-start':\n case 'flow-seq-start':\n return {\n type: 'flow-collection',\n offset: this.offset,\n indent: this.indent,\n start: this.sourceToken,\n items: [],\n end: []\n };\n case 'seq-item-ind':\n return {\n type: 'block-seq',\n offset: this.offset,\n indent: this.indent,\n items: [{ start: [this.sourceToken] }]\n };\n case 'explicit-key-ind': {\n this.onKeyLine = true;\n const prev = getPrevProps(parent);\n const start = getFirstKeyStartProps(prev);\n start.push(this.sourceToken);\n return {\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, explicitKey: true }]\n };\n }\n case 'map-value-ind': {\n this.onKeyLine = true;\n const prev = getPrevProps(parent);\n const start = getFirstKeyStartProps(prev);\n return {\n type: 'block-map',\n offset: this.offset,\n indent: this.indent,\n items: [{ start, key: null, sep: [this.sourceToken] }]\n };\n }\n }\n return null;\n }\n atIndentedComment(start, indent) {\n if (this.type !== 'comment')\n return false;\n if (this.indent <= indent)\n return false;\n return start.every(st => st.type === 'newline' || st.type === 'space');\n }\n *documentEnd(docEnd) {\n if (this.type !== 'doc-mode') {\n if (docEnd.end)\n docEnd.end.push(this.sourceToken);\n else\n docEnd.end = [this.sourceToken];\n if (this.type === 'newline')\n yield* this.pop();\n }\n }\n *lineEnd(token) {\n switch (this.type) {\n case 'comma':\n case 'doc-start':\n case 'doc-end':\n case 'flow-seq-end':\n case 'flow-map-end':\n case 'map-value-ind':\n yield* this.pop();\n yield* this.step();\n break;\n case 'newline':\n this.onKeyLine = false;\n // fallthrough\n case 'space':\n case 'comment':\n default:\n // all other values are errors\n if (token.end)\n token.end.push(this.sourceToken);\n else\n token.end = [this.sourceToken];\n if (this.type === 'newline')\n yield* this.pop();\n }\n }\n}\n\nexports.Parser = Parser;\n",
|
|
75
|
+
"'use strict';\n\nvar composer = require('./compose/composer.js');\nvar Document = require('./doc/Document.js');\nvar errors = require('./errors.js');\nvar log = require('./log.js');\nvar identity = require('./nodes/identity.js');\nvar lineCounter = require('./parse/line-counter.js');\nvar parser = require('./parse/parser.js');\n\nfunction parseOptions(options) {\n const prettyErrors = options.prettyErrors !== false;\n const lineCounter$1 = options.lineCounter || (prettyErrors && new lineCounter.LineCounter()) || null;\n return { lineCounter: lineCounter$1, prettyErrors };\n}\n/**\n * Parse the input as a stream of YAML documents.\n *\n * Documents should be separated from each other by `...` or `---` marker lines.\n *\n * @returns If an empty `docs` array is returned, it will be of type\n * EmptyStream and contain additional stream information. In\n * TypeScript, you should use `'empty' in docs` as a type guard for it.\n */\nfunction parseAllDocuments(source, options = {}) {\n const { lineCounter, prettyErrors } = parseOptions(options);\n const parser$1 = new parser.Parser(lineCounter?.addNewLine);\n const composer$1 = new composer.Composer(options);\n const docs = Array.from(composer$1.compose(parser$1.parse(source)));\n if (prettyErrors && lineCounter)\n for (const doc of docs) {\n doc.errors.forEach(errors.prettifyError(source, lineCounter));\n doc.warnings.forEach(errors.prettifyError(source, lineCounter));\n }\n if (docs.length > 0)\n return docs;\n return Object.assign([], { empty: true }, composer$1.streamInfo());\n}\n/** Parse an input string into a single YAML.Document */\nfunction parseDocument(source, options = {}) {\n const { lineCounter, prettyErrors } = parseOptions(options);\n const parser$1 = new parser.Parser(lineCounter?.addNewLine);\n const composer$1 = new composer.Composer(options);\n // `doc` is always set by compose.end(true) at the very latest\n let doc = null;\n for (const _doc of composer$1.compose(parser$1.parse(source), true, source.length)) {\n if (!doc)\n doc = _doc;\n else if (doc.options.logLevel !== 'silent') {\n doc.errors.push(new errors.YAMLParseError(_doc.range.slice(0, 2), 'MULTIPLE_DOCS', 'Source contains multiple documents; please use YAML.parseAllDocuments()'));\n break;\n }\n }\n if (prettyErrors && lineCounter) {\n doc.errors.forEach(errors.prettifyError(source, lineCounter));\n doc.warnings.forEach(errors.prettifyError(source, lineCounter));\n }\n return doc;\n}\nfunction parse(src, reviver, options) {\n let _reviver = undefined;\n if (typeof reviver === 'function') {\n _reviver = reviver;\n }\n else if (options === undefined && reviver && typeof reviver === 'object') {\n options = reviver;\n }\n const doc = parseDocument(src, options);\n if (!doc)\n return null;\n doc.warnings.forEach(warning => log.warn(doc.options.logLevel, warning));\n if (doc.errors.length > 0) {\n if (doc.options.logLevel !== 'silent')\n throw doc.errors[0];\n else\n doc.errors = [];\n }\n return doc.toJS(Object.assign({ reviver: _reviver }, options));\n}\nfunction stringify(value, replacer, options) {\n let _replacer = null;\n if (typeof replacer === 'function' || Array.isArray(replacer)) {\n _replacer = replacer;\n }\n else if (options === undefined && replacer) {\n options = replacer;\n }\n if (typeof options === 'string')\n options = options.length;\n if (typeof options === 'number') {\n const indent = Math.round(options);\n options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };\n }\n if (value === undefined) {\n const { keepUndefined } = options ?? replacer ?? {};\n if (!keepUndefined)\n return undefined;\n }\n if (identity.isDocument(value) && !_replacer)\n return value.toString(options);\n return new Document.Document(value, _replacer, options).toString(options);\n}\n\nexports.parse = parse;\nexports.parseAllDocuments = parseAllDocuments;\nexports.parseDocument = parseDocument;\nexports.stringify = stringify;\n",
|
|
76
|
+
"'use strict';\n\nvar composer = require('./compose/composer.js');\nvar Document = require('./doc/Document.js');\nvar Schema = require('./schema/Schema.js');\nvar errors = require('./errors.js');\nvar Alias = require('./nodes/Alias.js');\nvar identity = require('./nodes/identity.js');\nvar Pair = require('./nodes/Pair.js');\nvar Scalar = require('./nodes/Scalar.js');\nvar YAMLMap = require('./nodes/YAMLMap.js');\nvar YAMLSeq = require('./nodes/YAMLSeq.js');\nvar cst = require('./parse/cst.js');\nvar lexer = require('./parse/lexer.js');\nvar lineCounter = require('./parse/line-counter.js');\nvar parser = require('./parse/parser.js');\nvar publicApi = require('./public-api.js');\nvar visit = require('./visit.js');\n\n\n\nexports.Composer = composer.Composer;\nexports.Document = Document.Document;\nexports.Schema = Schema.Schema;\nexports.YAMLError = errors.YAMLError;\nexports.YAMLParseError = errors.YAMLParseError;\nexports.YAMLWarning = errors.YAMLWarning;\nexports.Alias = Alias.Alias;\nexports.isAlias = identity.isAlias;\nexports.isCollection = identity.isCollection;\nexports.isDocument = identity.isDocument;\nexports.isMap = identity.isMap;\nexports.isNode = identity.isNode;\nexports.isPair = identity.isPair;\nexports.isScalar = identity.isScalar;\nexports.isSeq = identity.isSeq;\nexports.Pair = Pair.Pair;\nexports.Scalar = Scalar.Scalar;\nexports.YAMLMap = YAMLMap.YAMLMap;\nexports.YAMLSeq = YAMLSeq.YAMLSeq;\nexports.CST = cst;\nexports.Lexer = lexer.Lexer;\nexports.LineCounter = lineCounter.LineCounter;\nexports.Parser = parser.Parser;\nexports.parse = publicApi.parse;\nexports.parseAllDocuments = publicApi.parseAllDocuments;\nexports.parseDocument = publicApi.parseDocument;\nexports.stringify = publicApi.stringify;\nexports.visit = visit.visit;\nexports.visitAsync = visit.visitAsync;\n",
|
|
77
|
+
"/**\n * Plugin event handlers — translate OpenCode events to task ops.\n *\n * OpenCode V2 emits ~30+ events (session.* / tool.* / command.* / etc.).\n * For MVP we cover the lifecycle subset that maps cleanly to business tasks.\n *\n * The handlers are pure async functions returning either:\n * - null/undefined (event processed silently)\n * - { task_id: string } (a task was created/affected, useful for tests)\n *\n * They never throw — errors are logged + emitted as `plugin.error` operations.\n */\n\nimport type {\n CreateTaskInput,\n Operation,\n Task,\n TaskStore,\n TaskStatus,\n} from \"@roy-task-plugin/shared\";\n\nexport interface HandlerContext {\n store: TaskStore;\n /** Identifier for the current agent (used as default owner + audit meta). */\n agent: string;\n}\n\nexport interface SessionEvent {\n type: \"session.created\" | \"session.idle\" | \"session.deleted\" | \"session.error\" | \"session.compacted\";\n payload: {\n id: string;\n title?: string;\n [k: string]: unknown;\n };\n}\n\nexport interface ToolEvent {\n type: \"tool.execute.after\";\n payload: {\n sessionID: string;\n tool: string;\n args?: Record<string, unknown>;\n };\n}\n\nexport type AnyEvent = SessionEvent | ToolEvent | { type: string; payload: any };\n\nexport interface Handlers {\n session(e: SessionEvent): Promise<{ task_id: string } | null>;\n tool(e: ToolEvent): Promise<{ task_id: string } | null>;\n /** Catch-all for unrecognised event types. */\n catchAll?(e: AnyEvent): Promise<void>;\n}\n\nconst SESSION_TO_TITLE = (s: SessionEvent) =>\n s.payload.title?.trim() || `session:${s.payload.id}`;\n\nexport function createHandlers(ctx: HandlerContext): Handlers {\n const { store, agent } = ctx;\n\n return {\n async session(e) {\n const sessionId = e.payload.id;\n const existing = await findTaskBySession(store, sessionId);\n\n switch (e.type) {\n case \"session.created\": {\n if (existing) return { task_id: existing.id };\n const title = SESSION_TO_TITLE(e);\n const task = await store.createTask({\n title,\n session_id: sessionId,\n owner: agent,\n priority: 3,\n } as CreateTaskInput);\n return { task_id: task.id };\n }\n case \"session.idle\": {\n if (!existing) return null;\n if (existing.status === \"pending\") {\n const t = await store.updateTask(existing.id, { status: \"in_progress\" });\n return t ? { task_id: t.id } : null;\n }\n return null;\n }\n case \"session.deleted\": {\n if (!existing) return null;\n await store.updateTask(existing.id, { status: \"cancelled\" });\n return { task_id: existing.id };\n }\n case \"session.error\":\n case \"session.compacted\": {\n // log only\n await store.appendOperation({\n task_id: existing?.id ?? null,\n type: `session.${e.type.split(\".\").pop()}`,\n data: { session_id: sessionId, agent },\n });\n return null;\n }\n default:\n return null;\n }\n },\n\n async tool(e) {\n const sessionId = e.payload.sessionID;\n const root = await findTaskBySession(store, sessionId);\n if (!root) {\n // Orphan tool event — log it as a session-level operation\n await store.appendOperation({\n task_id: null,\n type: \"tool.orphan\",\n data: { session_id: sessionId, tool: e.payload.tool },\n });\n // Still create an orphan task so the action is captured\n const t = await store.createTask({\n title: `${e.payload.tool} (orphan)`,\n session_id: null,\n owner: agent,\n priority: 3,\n });\n return { task_id: t.id };\n }\n\n const title = describeToolCall(e);\n // Idempotent child: same session + same tool + same args within 60s → reuse\n const recent = await store.listTasks({\n parent_id: root.id,\n limit: 20,\n });\n const dupe = recent.tasks.find(\n (t) =>\n t.title === title &&\n Date.now() - new Date(t.created_at).getTime() < 60_000,\n );\n if (dupe) return { task_id: dupe.id };\n\n const t = await store.createTask({\n title,\n parent_id: root.id,\n session_id: sessionId,\n owner: agent,\n priority: 3,\n });\n // Immediately mark in_progress (tool action is happening)\n await store.updateTask(t.id, { status: \"in_progress\" });\n return { task_id: t.id };\n },\n\n async catchAll(e) {\n // For events we don't specifically handle, log as a generic operation.\n try {\n await store.appendOperation({\n task_id: null,\n type: e.type,\n data: { payload: e.payload, agent },\n });\n } catch {\n // swallow\n }\n },\n };\n}\n\nasync function findTaskBySession(\n store: TaskStore,\n sessionId: string,\n): Promise<Task | null> {\n const r = await store.listTasks({ session_id: sessionId, limit: 1 });\n return r.tasks[0] ?? null;\n}\n\nfunction describeToolCall(e: ToolEvent): string {\n const tool = e.payload.tool;\n const args = e.payload.args ?? {};\n switch (tool) {\n case \"write\":\n case \"edit\":\n return `${tool} ${(args.filePath as string) ?? \"?\"}`;\n case \"bash\":\n case \"shell\": {\n const cmd = String(args.command ?? args.cmd ?? \"\");\n return `${tool} ${cmd.slice(0, 40)}`;\n }\n case \"read\":\n return `read ${(args.filePath as string) ?? \"?\"}`;\n default:\n return `${tool} ${JSON.stringify(args).slice(0, 40)}`;\n }\n}\n\n// Status narrowing helper used elsewhere\nexport const _STATUS_HINT: TaskStatus = \"pending\";\n// Keep TS happy about unused Operation import — referenced via TaskStore.\nexport type _OpCheck = Operation;",
|
|
78
|
+
"/**\n * The `roy` primary agent — system prompt (Task #4286).\n *\n * Semantics imported from roy-agent's \"roy sub-agent\" line of thought:\n * a task is not bookkeeping that happens *after* the work — the task IS the\n * unit of work. Every non-trivial request must materialise as a tracked task\n * whose lifecycle is visible to the user (task tree, milestone operations,\n * progress, deliverable).\n *\n * The tool names referenced here are the roy-agent tool names (imported\n * verbatim by @roy-task-plugin/roy-bridge), so the prompt and the tool\n * surface cannot drift apart.\n */\n\nexport const ROY_AGENT_DESCRIPTION =\n \"Roy — task-as-first-class-citizen agent. Uses the roy-agent task lifecycle \" +\n \"(task_tree → task_create → task_update → task_operation_create → task_complete) \" +\n \"so every piece of work is tracked in the local task store.\";\n\nexport const ROY_SYSTEM_PROMPT = `# Roy — task-first-class-citizen agent\n\nYou are **Roy**, an agent whose defining rule is simple:\n\n> **Task is a first-class citizen. No task, no work.**\n\nYou are not a chat assistant that occasionally writes notes. You are a worker\nwhose output is a *visible, trackable* stream of tasks. Every non-trivial\nrequest (more than one tool call / more than a couple of minutes of work) MUST\nbecome a tracked task before you start doing it, and MUST be closed out\nexplicitly when you finish.\n\n## The lifecycle (non-negotiable)\n\n### 1. Orient — \\`task_tree(depth=1)\\` (or \\`depth=2\\` for bigger trees)\nBefore creating anything, look at the existing tree. Decide:\n- does this work belong to an existing root (attach via \\`parent_task_id\\`)?\n- or is it genuinely new?\n\nKeep **root tasks ≤ 10**. Prefer attaching to an existing thematic root over\nspawning a new root. Never hardcode ids — read them from \\`task_tree\\`.\n\n### 2. Create — \\`task_create\\`\nCreate the task **before** doing the work. Pass:\n- \\`title\\` (imperative, specific), \\`description\\`, \\`goals_and_expected_deliverables\\`\n- \\`priority\\` (low / medium / high), \\`type\\` (normal / cycle / longterm)\n- \\`project_path\\`, \\`context\\` (JSON string: worktree_path / branch / type …)\n- \\`parent_task_id\\` when the tree said so\n\nThe tool returns a **numeric task id** — that number is your handle for the\nrest of the conversation.\n\n### 3. Track — \\`task_update\\`\nReport progress as you go, not only at the end:\n- \\`status\\`: todo → active → (paused / cancelled) → completed\n- \\`progress\\`: 0–100\n- \\`current_status\\`: one human sentence about where you are right now\n\nIf the scope changes, \\`task_update\\` the description/goals instead of silently\ndoing something else.\n\n### 4. Record milestones — \\`task_operation_create\\`\nThis tool has **two orthogonal dimensions** and you must keep them distinct:\n- **state / milestone dimension** — \\`milestone_type\\` + \\`milestone_title\\` +\n \\`milestone_description\\`: *what* was reached (e.g. \"GREEN: all tests pass\").\n- **process dimension** — \\`process_description\\`: *how* you got there —\n strategy + tool steps, strictly **100–150 characters**.\n Too short = rejected (no value); too long = rejected (use the session log).\n\nRules: do **not** use the process field to restate the milestone, and do not\nuse milestones as a substitute for progress. Milestones mark *state\ntransitions*: RED→GREEN, blocker found, decision made, review passed.\n\n### 5. Close — \\`task_complete\\`\nBefore completing:\n1. \\`task_get(task_id)\\` and re-read goal + delivery.\n2. Verify the goal and delivery actually match what you delivered. If they do\n not, either extend the task (\\`task_update\\`) or say so honestly.\n3. Call \\`task_complete\\` with \\`deliverable_storage_path\\` — a locator for the\n work product: a file path, a git branch/worktree, a doc URL, a commit URL.\n The path is persisted into the task context and as an operation record.\n\n\\`task_complete\\` cannot be used on \\`cycle\\` tasks (they are periodic by\ndesign) — use \\`task_update\\` to reset those.\n\n## Other tools\n\n- \\`task_get(task_id, include_operations)\\` — full detail; use it before\n resuming or completing a task.\n- \\`task_list(...)\\` — flat listing with filters (status / priority / type).\n- \\`task_search(keywords)\\` — find by title / description / goals / tags.\n **Search before creating**, to avoid duplicates.\n\n## Where tasks live\n\nAll tasks and operations are persisted by the roy-task-plugin in the\n**single** project store — locally that is SQLite at\n\\`~/.roy-task-plugin/tasks.db\\` (or the remote service when the plugin is\nconfigured with \\`persistence: \"remote\"\\`). Do not create side databases, do\nnot maintain your own to-do list in files, and do not track work in chat only:\nif it is not in the task store, it is not tracked.\n\n## Style\n\n- Be direct and concrete; the user is reading task titles and milestones.\n- Report the task id and its state whenever you finish a step.\n- If a task is blocked, mark it (\\`task_update(status=\"paused\")\\`) and record a\n \\`problem\\` milestone explaining the blocker instead of going silent.`;\n\nexport const ROY_SYSTEM_PROMPT_MARKER = \"task-first-class-citizen agent\";\n",
|
|
79
|
+
"/**\n * The `roy` OpenCode primary agent — registration (Task #4286).\n *\n * OpenCode's v2 plugin API exposes `ctx.agent.transform(draft)` where the draft\n * has `list/get/default/update/remove`. There is **no `add`**; calling\n * `update(<new id>, mutator)` creates the agent (verified empirically against\n * opencode 2.0.30 — see docs/primary-agent-design.md §3.1).\n *\n * We therefore register `roy` by id instead of mutating a builtin, which keeps\n * the user's own default agent untouched.\n */\n\nimport { ROY_AGENT_DESCRIPTION, ROY_SYSTEM_PROMPT } from \"./roy-prompt.js\";\n\nexport const ROY_AGENT_ID = \"roy\";\n\n/** OpenCode permission rule (schema: `{action, resource, effect}`). */\nexport interface PermissionRuleLike {\n action: string;\n resource: string;\n effect: \"allow\" | \"deny\" | \"ask\";\n}\n\n/**\n * The one permission rule that makes `roy` reliable (Task #4317, fix for #4310).\n *\n * OpenCode's Code-Mode `execute` tool ships a description that says *\"Inside\n * `{code}`, ignore tools shown outside the Code Mode catalog. They are not\n * available in the Code Mode runtime.\"* Because `roy` exposes the 9 `task_*`\n * tools as **direct** (top-level) tools *and* OpenCode also advertises\n * `execute`, the model picks the wrong path ~33% of the time on the first turn\n * (`Unknown tool 'task_tree'`), then self-corrects after seeing the error.\n *\n * Denying `execute` for this agent removes the wrong option entirely: `roy` is a\n * task-first worker whose task tools are direct tools, so the Code-Mode sandbox\n * has no value for it. OpenCode resolves a rule via\n * `rules.findLast(r => Wildcard.match(action, r.action))` and treats\n * `resource:\"*\" + effect:\"deny\"` as \"wholly disabled\" — which is exactly what\n * `codeModeEnabled = !whollyDisabled(\"execute\", rules)` reads.\n *\n * Known limitation (cross-validation 2026-10-17): `ConfigAgentPlugin` pushes the\n * user's top-level config `permissions` onto every agent *after* plugins in the\n * `packages` phase, and `whollyDisabled` uses `findLast`. A user-level wildcard\n * allow for `execute` (e.g. `permissions: [{action:\"*\",resource:\"*\",effect:\"allow\"}]`\n * in opencode.jsonc) would therefore override this deny. Today's config has no\n * `permission` field, so this is not triggered; the committed `agents/roy.md`\n * frontmatter also carries the same deny as a second line of defence (config\n * agent loading re-pushes it last).\n */\nexport const ROY_EXECUTE_DENY_RULE: PermissionRuleLike = {\n action: \"execute\",\n resource: \"*\",\n effect: \"deny\",\n};\n\n/** Minimal structural shapes of OpenCode's AgentDraft / AgentV2Info. */\nexport interface AgentLike {\n id?: string;\n mode?: \"primary\" | \"subagent\" | \"all\";\n description?: string;\n system?: string;\n hidden?: boolean;\n permissions?: PermissionRuleLike[];\n [key: string]: unknown;\n}\n\nexport interface AgentDraftLike {\n list(): readonly AgentLike[];\n get(id: string): AgentLike | undefined;\n default(id: string | undefined): void;\n update(id: string, update: (agent: AgentLike) => void): void;\n remove(id: string): void;\n}\n\nexport interface RoyAgentDescriptor {\n id: string;\n mode: \"primary\";\n description: string;\n system: string;\n /** Agent-level permission rules; carries the Code-Mode `execute` deny. */\n permissions: PermissionRuleLike[];\n}\n\n/** The canonical descriptor for the `roy` agent. */\nexport function buildRoyAgentDescriptor(): RoyAgentDescriptor {\n return {\n id: ROY_AGENT_ID,\n mode: \"primary\",\n description: ROY_AGENT_DESCRIPTION,\n system: ROY_SYSTEM_PROMPT,\n permissions: [{ ...ROY_EXECUTE_DENY_RULE }],\n };\n}\n\n/**\n * Push the agent-level permission rules onto an agent, preserving anything the\n * agent already has and staying idempotent across plugin hot-reloads.\n */\nfunction applyPermissions(agent: AgentLike, rules: PermissionRuleLike[]): void {\n if (!Array.isArray(agent.permissions)) agent.permissions = [];\n for (const rule of rules) {\n const exists = agent.permissions.some(\n (current) =>\n current.action === rule.action &&\n current.resource === rule.resource &&\n current.effect === rule.effect,\n );\n if (!exists) agent.permissions.push({ ...rule });\n }\n}\n\n/**\n * Apply the `roy` agent onto an OpenCode agent draft.\n *\n * Idempotent: re-running (plugin hot-reload) simply rewrites the same fields.\n * Works both when `roy` already exists (our own earlier registration) and when\n * it does not (creates it).\n *\n * @returns the descriptor that was applied\n */\nexport function applyRoyAgent(draft: AgentDraftLike): RoyAgentDescriptor {\n const descriptor = buildRoyAgentDescriptor();\n draft.update(ROY_AGENT_ID, (agent) => {\n agent.mode = descriptor.mode;\n agent.description = descriptor.description;\n agent.system = descriptor.system;\n if (agent.hidden === undefined) agent.hidden = false;\n applyPermissions(agent, descriptor.permissions);\n });\n return descriptor;\n}\n\n/** Markdown artifact (portable alternative to plugin registration). */\nexport function toRoyAgentMarkdown(): string {\n return [\n \"---\",\n `description: ${ROY_AGENT_DESCRIPTION}`,\n \"mode: primary\",\n \"permissions:\",\n ` - action: ${ROY_EXECUTE_DENY_RULE.action}`,\n ` resource: \"${ROY_EXECUTE_DENY_RULE.resource}\"`,\n ` effect: ${ROY_EXECUTE_DENY_RULE.effect}`,\n \"---\",\n \"\",\n ROY_SYSTEM_PROMPT,\n \"\",\n ].join(\"\\n\");\n}\n",
|
|
80
|
+
"export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n",
|
|
81
|
+
"import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n const firstEl = sub.path[0];\n fieldErrors[firstEl] = fieldErrors[firstEl] || [];\n fieldErrors[firstEl].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n",
|
|
82
|
+
"import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"bigint\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nexport default errorMap;\n",
|
|
83
|
+
"import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n overrideErrorMap = map;\n}\nexport function getErrorMap() {\n return overrideErrorMap;\n}\n",
|
|
84
|
+
"import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexport const INVALID = Object.freeze({\n status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n",
|
|
85
|
+
"export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n",
|
|
86
|
+
"import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;\nconst ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n if (!header)\n return false;\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n",
|
|
87
|
+
"// src/env/tool/built-in/query-background-process-tool.ts\nimport { z } from \"zod\";\nvar QueryBackgroundProcessParameters = z.object({\n bgProcessId: z.string().min(1, \"bgProcessId must not be empty\").describe(\"The background process ID returned by delegate_task \" + \"(format: process_<timestamp>_<random>).\")\n});\nfunction backgroundTaskToOutput(task) {\n return {\n alive: task.status === \"pending\" || task.status === \"running\",\n status: task.status,\n createdAt: task.createdAt,\n lastUpdatedAt: task.lastUpdatedAt ?? task.completedAt ?? task.startedAt ?? task.createdAt,\n description: task.description,\n ...task.result !== undefined ? { result: task.result } : {},\n ...task.error !== undefined ? { error: task.error } : {}\n };\n}\nfunction notFoundOutput(bgProcessId) {\n const now = Date.now();\n return {\n alive: false,\n status: \"not_found\",\n createdAt: now,\n lastUpdatedAt: now,\n description: `No background process found with id '${bgProcessId}'.`\n };\n}\nvar queryBackgroundProcessTool = {\n name: \"query_background_process\",\n description: `Query the status of a background process previously launched via delegate_task.\n\n` + `Use this tool when:\n` + ` - You delegated a long-running task but have NOT received any notification after a reasonable wait (5+ minutes), and want to confirm whether the process is still alive.\n` + ` - The user asks about the progress of a delegated task and you need a current snapshot.\n` + ` - You suspect a delegated task got stuck (no progress messages, no completion notification).\n\n` + `DO NOT poll this tool on every turn — it is meant for diagnostic checks at a reasonable cadence (e.g. every few minutes, or when you genuinely suspect the task is stuck).\n\n` + `Returns a JSON object with:\n` + ` - alive: boolean — true if status is 'pending' or 'running'\n` + ` - status: 'pending' | 'running' | 'completed' | 'failed' | 'stopped' | 'timeout' | 'not_found'\n` + ` - createdAt, lastUpdatedAt: timestamps (ms)\n` + ` - description: the task description you passed to delegate_task\n` + ` - result: present when status is 'completed'\n` + ` - error: present when status is 'failed'\n\n` + \"Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-agent, etc.) cannot see it because they do not need to query background tasks they themselves launched.\",\n parameters: QueryBackgroundProcessParameters,\n permission: {\n level: \"safe\",\n requireConfirmation: false\n },\n metadata: {\n category: \"task\",\n tags: [\"background\", \"delegate\", \"query\", \"status\", \"diagnostic\"],\n version: \"1.0.0\",\n allowedAgentTypes: [\"default\"]\n },\n execute: async (args, ctx) => createQueryBackgroundProcessTool(null).execute(args, ctx)\n};\nfunction createQueryBackgroundProcessTool(manager = null) {\n return {\n name: \"query_background_process\",\n description: `Query the status of a background process previously launched via delegate_task.\n\n` + `Use this tool when:\n` + ` - You delegated a long-running task but have NOT received any notification after a reasonable wait (5+ minutes), and want to confirm whether the process is still alive.\n` + ` - The user asks about the progress of a delegated task and you need a current snapshot.\n` + ` - You suspect a delegated task got stuck (no progress messages, no completion notification).\n\n` + `DO NOT poll this tool on every turn — it is meant for diagnostic checks at a reasonable cadence (e.g. every few minutes, or when you genuinely suspect the task is stuck).\n\n` + `Returns a JSON object with:\n` + ` - alive: boolean — true if status is 'pending' or 'running'\n` + ` - status: 'pending' | 'running' | 'completed' | 'failed' | 'stopped' | 'timeout' | 'not_found'\n` + ` - createdAt, lastUpdatedAt: timestamps (ms)\n` + ` - description: the task description you passed to delegate_task\n` + ` - result: present when status is 'completed'\n` + ` - error: present when status is 'failed'\n\n` + \"Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-agent, etc.) cannot see it because they do not need to query background tasks they themselves launched.\",\n parameters: QueryBackgroundProcessParameters,\n permission: {\n level: \"safe\",\n requireConfirmation: false\n },\n metadata: {\n category: \"task\",\n tags: [\"background\", \"delegate\", \"query\", \"status\", \"diagnostic\"],\n version: \"1.0.0\",\n allowedAgentTypes: [\"default\"]\n },\n execute: async (args, ctx) => {\n const startTime = Date.now();\n const params = QueryBackgroundProcessParameters.parse(args);\n const { bgProcessId } = params;\n if (!manager) {\n return {\n success: false,\n output: \"\",\n error: \"query_background_process is not initialized: no BackgroundTaskManager \" + \"has been bound. TaskComponent should call \" + \"createQueryBackgroundProcessTool(manager) and register the tool \" + \"during startup.\",\n metadata: { execution_time_ms: Date.now() - startTime }\n };\n }\n let task;\n try {\n task = manager.getTask(bgProcessId);\n } catch (err) {\n return {\n success: false,\n output: \"\",\n error: `failed to query background task: ${err.message}`,\n metadata: { execution_time_ms: Date.now() - startTime }\n };\n }\n if (task) {\n const currentSessionId = ctx.session_id;\n if (!currentSessionId || task.parentSessionId !== currentSessionId) {\n return {\n success: true,\n output: JSON.stringify(notFoundOutput(bgProcessId), null, 2),\n metadata: {\n execution_time_ms: Date.now() - startTime,\n bgProcessId,\n status: \"not_found\",\n alive: false\n }\n };\n }\n }\n const output = task ? backgroundTaskToOutput(task) : notFoundOutput(bgProcessId);\n return {\n success: true,\n output: JSON.stringify(output, null, 2),\n metadata: {\n execution_time_ms: Date.now() - startTime,\n bgProcessId,\n status: output.status,\n alive: output.alive\n }\n };\n }\n };\n}\n\nexport { queryBackgroundProcessTool, createQueryBackgroundProcessTool };\n",
|
|
88
|
+
"import { createRequire } from \"node:module\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nfunction __accessProp(key) {\n return this[key];\n}\nvar __toCommonJS = (from) => {\n var entry = (__moduleCache ??= new WeakMap).get(from), desc;\n if (entry)\n return entry;\n entry = __defProp({}, \"__esModule\", { value: true });\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (var key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(entry, key))\n __defProp(entry, key, {\n get: __accessProp.bind(from, key),\n enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable\n });\n }\n __moduleCache.set(from, entry);\n return entry;\n};\nvar __moduleCache;\nvar __returnValue = (v) => v;\nfunction __exportSetter(name, newValue) {\n this[name] = __returnValue.bind(null, newValue);\n}\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, {\n get: all[name],\n enumerable: true,\n configurable: true,\n set: __exportSetter.bind(all, name)\n });\n};\nvar __legacyDecorateClassTS = function(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\")\n r = Reflect.decorate(decorators, target, key, desc);\n else\n for (var i = decorators.length - 1;i >= 0; i--)\n if (d = decorators[i])\n r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};\nvar __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);\nvar __require = /* @__PURE__ */ createRequire(import.meta.url);\n\nexport { __toCommonJS, __export, __legacyDecorateClassTS, __esm, __require };\n",
|
|
89
|
+
"import {\n __esm,\n __require\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/log-trace/span-storage.ts\nfunction isSpanStorageDebugEnabled() {\n return process.env.ROY_TRACE_DEBUG_STORAGE === \"1\" || process.env.ROY_TRACE_DEBUG === \"1\";\n}\nfunction safeStringify(obj) {\n const seen = new WeakSet;\n try {\n return JSON.stringify(obj, (_key, value) => {\n if (typeof value === \"function\")\n return \"[Function]\";\n if (value === undefined)\n return \"[undefined]\";\n if (value === null)\n return null;\n if (value instanceof Error) {\n return `${value.name}: ${value.message}`;\n }\n if (typeof value === \"object\") {\n if (\"$typeof\" in value || \"type\" in value && \"props\" in value && \"key\" in value) {\n return \"[ReactElement]\";\n }\n if (seen.has(value))\n return \"[Circular]\";\n seen.add(value);\n }\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n });\n } catch (err) {\n return `[Unserializable: ${err instanceof Error ? err.message : String(err)}]`;\n }\n}\nfunction getDatabaseClass() {\n if (typeof Bun !== \"undefined\") {\n const { Database } = __require(\"bun:sqlite\");\n return Database;\n } else {\n return __require(\"better-sqlite3\");\n }\n}\nfunction createCompatibleDatabase(path) {\n const Database = getDatabaseClass();\n const db = new Database(path);\n if (typeof db.run !== \"function\") {\n db.run = function(sql, ...params) {\n if (params.length > 0) {\n return this.prepare(sql).run(...params);\n } else {\n return this.exec(sql);\n }\n };\n }\n return db;\n}\n\nclass SQLiteSpanStorage {\n db = null;\n dbPath;\n initialized = false;\n constructor(dbPath) {\n if (!dbPath) {\n throw new Error(\"SQLiteSpanStorage requires a valid dbPath parameter\");\n }\n if (dbPath === \":memory:\") {\n throw new Error(\"SQLiteSpanStorage does not support :memory: mode. Use a file path instead.\");\n }\n this.dbPath = dbPath;\n }\n async initialize() {\n if (this.initialized)\n return;\n const fs = __require(\"fs\");\n const path = __require(\"path\");\n const dir = path.dirname(this.dbPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n this.db = createCompatibleDatabase(this.dbPath);\n this.db.run(\"PRAGMA journal_mode=WAL\");\n this.db.run(\"PRAGMA busy_timeout=5000\");\n this.db.run(\"PRAGMA synchronous=NORMAL\");\n this.db.run(`\n CREATE TABLE IF NOT EXISTS span (\n span_id TEXT PRIMARY KEY,\n trace_id TEXT NOT NULL,\n parent_span_id TEXT,\n name TEXT NOT NULL,\n kind TEXT NOT NULL,\n status TEXT NOT NULL,\n start_time INTEGER NOT NULL,\n end_time INTEGER,\n attributes TEXT,\n result TEXT,\n error TEXT,\n time_created INTEGER NOT NULL\n )\n `);\n this.db.run(\"CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)\");\n this.db.run(\"CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)\");\n this.initialized = true;\n }\n save(span) {\n if (!this.db) {\n if (isSpanStorageDebugEnabled()) {\n console.log(`[SpanStorage] save() skipped: db not initialized for span \"${span.name}\" traceId=${span.traceId}`);\n }\n return;\n }\n const stmt = this.db.prepare(`\n INSERT OR REPLACE INTO span \n (span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n const resultValue = span.result !== undefined && span.result !== null ? typeof span.result === \"string\" ? span.result : safeStringify(span.result) : null;\n if (isSpanStorageDebugEnabled()) {\n console.log(`[SpanStorage] Saving to \"${this.dbPath}\": name=\"${span.name}\" traceId=${span.traceId} spanId=${span.spanId} status=${span.status}`);\n }\n try {\n const result = stmt.run(span.spanId, span.traceId, span.parentSpanId || null, span.name, span.kind, span.status, span.startTime, span.endTime || null, safeStringify(span.attributes), resultValue, span.error || null, Date.now());\n if (isSpanStorageDebugEnabled()) {\n console.log(`[SpanStorage] Save result: changes=${result?.changes}, lastInsertRowid=${result?.lastInsertRowid}`);\n }\n } catch (err) {\n console.error(`[SpanStorage] Save ERROR:`, err);\n }\n }\n saveBatch(spans) {\n for (const span of spans) {\n this.save(span);\n }\n }\n findByTraceId(traceId) {\n if (!this.db)\n return [];\n const rows = this.db.prepare(\"SELECT * FROM span WHERE trace_id = ?\").all(traceId);\n return this.buildTree(rows.map(this.rowToSpan));\n }\n findBySpanId(spanId) {\n if (!this.db)\n return;\n const row = this.db.prepare(\"SELECT * FROM span WHERE span_id = ?\").get(spanId);\n return row ? this.rowToSpan(row) : undefined;\n }\n listTraces(limit = 10) {\n if (!this.db)\n return [];\n const rows = this.db.prepare(`\n SELECT trace_id,\n MIN(start_time) as start_time,\n MAX(end_time) as end_time,\n COUNT(*) as span_count,\n SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as error_count,\n (SELECT name FROM span s2\n WHERE s2.trace_id = span.trace_id\n ORDER BY (s2.parent_span_id IS NULL OR s2.parent_span_id = '') DESC,\n s2.start_time ASC\n LIMIT 1) as root_name\n FROM span\n GROUP BY trace_id\n ORDER BY start_time DESC\n LIMIT ?\n `).all(limit);\n return rows.map((row) => {\n const spanCount = Number(row.span_count) || 0;\n const errorCount = Number(row.error_count) || 0;\n const endTime = row.end_time ?? undefined;\n const status = errorCount === 0 ? \"ok\" : errorCount >= spanCount ? \"error\" : \"mixed\";\n return {\n traceId: row.trace_id,\n rootSpanName: row.root_name ?? \"unknown\",\n startTime: row.start_time,\n endTime,\n duration: endTime !== undefined ? endTime - row.start_time : undefined,\n spanCount,\n status\n };\n });\n }\n deleteByTraceId(traceId) {\n if (this.db) {\n this.db.prepare(\"DELETE FROM span WHERE trace_id = ?\").run(traceId);\n }\n }\n close() {\n if (this.db) {\n this.db.close();\n this.db = null;\n }\n }\n rowToSpan(row) {\n return {\n traceId: row.trace_id,\n spanId: row.span_id,\n parentSpanId: row.parent_span_id,\n name: row.name,\n kind: row.kind,\n status: row.status,\n startTime: row.start_time,\n endTime: row.end_time,\n attributes: row.attributes ? JSON.parse(row.attributes) : {},\n result: row.result || undefined,\n error: row.error || undefined\n };\n }\n buildTree(spans) {\n const spanMap = new Map;\n const roots = [];\n for (const span of spans) {\n spanMap.set(span.spanId, { ...span, children: [] });\n }\n for (const span of spanMap.values()) {\n if (span.parentSpanId) {\n const parent = spanMap.get(span.parentSpanId);\n if (parent) {\n parent.children.push(span);\n } else {\n roots.push(span);\n }\n } else {\n roots.push(span);\n }\n }\n return roots;\n }\n}\nvar init_span_storage = () => {};\n\nexport { SQLiteSpanStorage, init_span_storage };\n",
|
|
90
|
+
"import {\n SQLiteSpanStorage,\n init_span_storage\n} from \"./roy-agent-core-jnszp0jq.js\";\nimport {\n __esm,\n __export,\n __require\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/log-trace/opentelemetry/propagation.ts\nfunction padLeft(str, length) {\n return str.padStart(length, \"0\");\n}\nfunction isValidHex(str) {\n return /^[0-9a-f]+$/i.test(str);\n}\nfunction serialize(context) {\n const traceId = padLeft(context.traceId.toLowerCase(), TRACE_ID_LENGTH);\n const spanId = padLeft(context.spanId.toLowerCase(), PARENT_SPAN_ID_LENGTH);\n const parts = [\n TRACE_CONTEXT_VERSION,\n traceId,\n spanId,\n TRACE_FLAGS_SAMPLED\n ];\n return parts.join(\"-\");\n}\nfunction parse(traceparent) {\n if (!traceparent || typeof traceparent !== \"string\") {\n return;\n }\n const trimmed = traceparent.trim();\n const parts = trimmed.split(\"-\");\n if (parts.length !== 4) {\n return;\n }\n const [version, traceId, senderSpanId, flags] = parts;\n if (version !== TRACE_CONTEXT_VERSION) {\n if (version > TRACE_CONTEXT_VERSION) {\n return;\n }\n }\n if (traceId.length !== TRACE_ID_LENGTH || !isValidHex(traceId)) {\n return;\n }\n if (senderSpanId.length !== PARENT_SPAN_ID_LENGTH || !isValidHex(senderSpanId)) {\n return;\n }\n if (flags.length !== FLAGS_LENGTH || !isValidHex(flags)) {\n return;\n }\n return {\n traceId: traceId.toLowerCase(),\n spanId: senderSpanId.toLowerCase()\n };\n}\nvar TRACE_CONTEXT_VERSION = \"00\", TRACE_FLAGS_SAMPLED = \"01\", TRACEPARENT_HEADER = \"TRACEPARENT\", TRACE_ID_LENGTH = 32, PARENT_SPAN_ID_LENGTH = 16, FLAGS_LENGTH = 2, propagation;\nvar init_propagation = __esm(() => {\n propagation = {\n inject(carrier, context) {\n carrier[TRACEPARENT_HEADER] = serialize(context);\n },\n extract(carrier) {\n const traceparent = carrier[TRACEPARENT_HEADER];\n if (!traceparent) {\n return;\n }\n return parse(traceparent);\n },\n getTraceparentHeader() {\n return TRACEPARENT_HEADER;\n }\n };\n});\n\n// src/env/log-trace/types.ts\nvar SpanKind, SpanStatus;\nvar init_types = __esm(() => {\n ((SpanKind2) => {\n SpanKind2[\"CLIENT\"] = \"client\";\n SpanKind2[\"SERVER\"] = \"server\";\n SpanKind2[\"INTERNAL\"] = \"internal\";\n })(SpanKind ||= {});\n ((SpanStatus2) => {\n SpanStatus2[\"OK\"] = \"ok\";\n SpanStatus2[\"ERROR\"] = \"error\";\n })(SpanStatus ||= {});\n});\n\n// src/env/log-trace/logger.ts\nimport { appendFileSync, existsSync, mkdirSync } from \"fs\";\nimport { join } from \"path\";\nfunction simplifyFilePath(fullPath) {\n let path = fullPath.replace(/\\\\/g, \"/\");\n const bunfsMatch = path.match(/\\/\\$bunfs\\/root\\/(.+)$/);\n if (bunfsMatch) {\n const virtualPath = bunfsMatch[1];\n const packagesMatch = virtualPath.match(/(packages\\/[^/]+\\/src\\/[^/]+\\/.+)$/);\n if (packagesMatch) {\n return packagesMatch[1];\n }\n return virtualPath;\n }\n const fileProtocolMatch = path.match(/@roy-agent\\+core@file\\+([^/]+)\\/node_modules\\/@roy-agent\\/core\\/(.+)$/);\n if (fileProtocolMatch) {\n const rootPkg = fileProtocolMatch[1].replace(/\\+/g, \"/\");\n const remaining = fileProtocolMatch[2];\n const prefix = rootPkg;\n const suffix = remaining.startsWith(\"src/\") ? remaining : `src/${remaining}`;\n return `${prefix}/${suffix}`;\n }\n const packagesRootMatch = path.match(/(packages\\/[^/]+\\/src\\/[^/]+\\/.+)$/);\n if (packagesRootMatch) {\n return packagesRootMatch[1];\n }\n const rootMarkers = [\"packages/core/src\", \"packages/core\", \"packages\"];\n for (const marker of rootMarkers) {\n const idx = path.indexOf(marker);\n if (idx !== -1) {\n return path.substring(idx);\n }\n }\n return path;\n}\nfunction getDefaultLogDir() {\n const home = process.env.HOME || process.env.USERPROFILE || \"/tmp\";\n try {\n const xdg = __require(\"xdg-basedir\");\n if (xdg.xdgData) {\n return join(xdg.xdgData, \"roy-agent\", \"logs\");\n }\n } catch {}\n return join(home, \".local\", \"share\", \"roy-agent\", \"logs\");\n}\nfunction isQuietMode() {\n return quietMode;\n}\nfunction setQuietMode(enabled) {\n quietMode = enabled;\n}\nfunction setConfigComponent(component) {\n configComponentInstance = component;\n}\nfunction getLogLevel() {\n if (configComponentInstance) {\n const level = configComponentInstance.get(\"log_trace.logging.level\");\n if (level && [\"debug\", \"info\", \"warn\", \"error\"].includes(level)) {\n return level;\n }\n }\n const envLevel = process.env.LOG_LEVEL;\n if (envLevel && [\"debug\", \"info\", \"warn\", \"error\"].includes(envLevel)) {\n return envLevel;\n }\n return \"info\";\n}\nfunction getCategoryLogLevel(category) {\n if (configComponentInstance) {\n const levels = configComponentInstance.get(\"log_trace.logging.levels\");\n if (levels && typeof levels === \"object\") {\n const categoryLevel = levels[category];\n if (categoryLevel && [\"debug\", \"info\", \"warn\", \"error\"].includes(categoryLevel)) {\n return categoryLevel;\n }\n }\n const directLevel = configComponentInstance.get(`log_trace.logging.levels.${category}`);\n if (directLevel && [\"debug\", \"info\", \"warn\", \"error\"].includes(directLevel)) {\n return directLevel;\n }\n }\n const envKey = `LOG_LEVEL_${category.toUpperCase().replace(/:/g, \"_\")}`;\n const envLevel = process.env[envKey];\n if (envLevel && [\"debug\", \"info\", \"warn\", \"error\"].includes(envLevel)) {\n return envLevel;\n }\n return getLogLevel();\n}\nfunction isAbsolutePath(path) {\n if (path.startsWith(\"/\")) {\n return true;\n }\n if (/^[a-zA-Z]:[/\\\\]/.test(path)) {\n return true;\n }\n return false;\n}\nfunction expandHomeDir(path) {\n if (path.startsWith(\"~\")) {\n const home = process.env.HOME || process.env.USERPROFILE || \"/tmp\";\n return join(home, path.slice(1));\n }\n return path;\n}\nfunction getLogFile() {\n if (configComponentInstance) {\n const file = configComponentInstance.get(\"log-trace.logging.file\");\n if (file) {\n return file;\n }\n }\n return \"app.log\";\n}\nfunction getLogDir() {\n if (configComponentInstance) {\n const dir = configComponentInstance.get(\"log-trace.logging.dir\");\n if (dir) {\n return dir;\n }\n }\n return getDefaultLogDir();\n}\nfunction getMaxOutput() {\n if (configComponentInstance) {\n const maxOutput = configComponentInstance.get(\"log-trace.logging.maxOutput\");\n if (typeof maxOutput === \"number\") {\n return maxOutput;\n }\n }\n return;\n}\nfunction setLogDirOverride(dir) {\n logDirOverride = dir;\n}\nfunction getLogDirOverride() {\n return logDirOverride;\n}\n\nclass Logger {\n prefix;\n constructor(prefix) {\n this.prefix = prefix;\n }\n shouldLog(level) {\n const categoryLevel = getCategoryLogLevel(this.prefix);\n return levelPriority[level] >= levelPriority[categoryLevel];\n }\n ensureLogDirectory(dir) {\n if (!existsSync(dir)) {\n try {\n mkdirSync(dir, { recursive: true });\n } catch (err) {\n console.error(\"[Logger] Failed to create log directory:\", dir, err);\n }\n }\n }\n getCallerLocation() {\n const originalLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = 10;\n const err = new Error;\n Error.captureStackTrace(err, this.formatMessage);\n const stack = err.stack?.split(`\n`) || [];\n Error.stackTraceLimit = originalLimit;\n for (let i = 1;i < stack.length; i++) {\n const line = stack[i];\n if (line.includes(\"at \") && !line.includes(\"logger.ts\") && !line.includes(\"formatMessage\")) {\n const match = line.match(/at\\s+.+\\s+\\((.+):(\\d+):\\d+\\)/) || line.match(/at\\s+(.+):(\\d+):\\d+/);\n if (match) {\n const filePath = match[1];\n const relativePath = this.getRelativePath(filePath);\n return {\n file: relativePath,\n line: parseInt(match[2], 10)\n };\n }\n }\n }\n return null;\n }\n getRelativePath(fullPath) {\n return simplifyFilePath(fullPath);\n }\n formatMessage(level, message, data) {\n const now = new Date;\n const timestamp = now.toLocaleString(\"zh-CN\", {\n timeZone: \"Asia/Shanghai\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false\n }).replace(/\\//g, \"-\") + \".\" + String(now.getMilliseconds()).padStart(3, \"0\");\n const prefix = this.prefix ? `[${this.prefix}]` : \"\";\n let traceIdStr = \"\";\n try {\n const provider = getTracerProvider();\n const tracer = provider.getTracer(\"roy-tracer\");\n const context = tracer.getCurrentContext();\n if (context?.traceId) {\n traceIdStr = `[traceId=${context.traceId}]`;\n }\n } catch {}\n let locationStr = \"\";\n if (data && typeof data === \"object\" && \"callerLocation\" in data) {\n const logData = data;\n locationStr = logData.callerLocation ? ` [${logData.callerLocation}]` : \"\";\n const { callerLocation: _callerLocation, ...rest } = logData;\n data = Object.keys(rest).length > 0 ? rest : undefined;\n } else {\n const location = this.getCallerLocation();\n if (location) {\n locationStr = ` [${location.file}:${location.line}]`;\n }\n }\n let formatted = `${timestamp} [${level.toUpperCase()}]${traceIdStr}${locationStr}${prefix} ${message}`;\n if (data !== undefined) {\n if (typeof data === \"object\") {\n formatted += \" \" + JSON.stringify(data).replace(/\\n/g, \"\");\n } else {\n formatted += \" \" + String(data);\n }\n }\n const maxOutput = getMaxOutput();\n if (maxOutput && maxOutput > 0 && formatted.length > maxOutput) {\n formatted = formatted.substring(0, maxOutput) + \" [TRUNCATED]\";\n }\n return formatted;\n }\n writeToFile(message) {\n try {\n const dir = getLogDir();\n const filename = getLogFile();\n const expandedDir = expandHomeDir(dir);\n const resolvedDir = isAbsolutePath(expandedDir) ? expandedDir : join(process.cwd(), expandedDir);\n this.ensureLogDirectory(resolvedDir);\n const logFile = join(resolvedDir, filename);\n appendFileSync(logFile, message + `\n`, \"utf-8\");\n } catch (err) {\n console.error(\"[Logger] Failed to write to log file:\", err);\n }\n }\n log(level, message, data) {\n if (!this.shouldLog(level))\n return;\n const formatted = this.formatMessage(level, message, data);\n this.writeToFile(formatted);\n if (!isQuietMode()) {\n const consoleMethod = level === \"error\" ? console.error : level === \"warn\" ? console.warn : level === \"info\" ? console.log : console.debug;\n consoleMethod(formatted);\n }\n }\n debug(message, data) {\n this.log(\"debug\", message, data);\n }\n info(message, data) {\n this.log(\"info\", message, data);\n }\n warn(message, data) {\n this.log(\"warn\", message, data);\n }\n error(message, data) {\n this.log(\"error\", message, data);\n }\n}\nfunction createLogger(prefix) {\n if (!loggerCache.has(prefix)) {\n loggerCache.set(prefix, new Logger(prefix));\n }\n return loggerCache.get(prefix);\n}\nfunction getLogLevels() {\n return [\"debug\", \"info\", \"warn\", \"error\"];\n}\nvar configComponentInstance = null, quietMode = false, logDirOverride, levelPriority, loggerCache;\nvar init_logger = __esm(() => {\n init_tracer_provider();\n levelPriority = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3\n };\n loggerCache = new Map;\n});\n\n// src/env/log-trace/opentelemetry/tracer-provider.ts\nvar exports_tracer_provider = {};\n__export(exports_tracer_provider, {\n setTracerProvider: () => setTracerProvider,\n resetTracerProvider: () => resetTracerProvider,\n getTracerProvider: () => getTracerProvider,\n OTelTracerProvider: () => OTelTracerProvider\n});\nfunction getOtelLogger() {\n if (!_otelLogger) {\n _otelLogger = createLogger(\"otel-tracer\");\n }\n return _otelLogger;\n}\nfunction isOtelTraceDebugEnabled() {\n return process.env.ROY_TRACE_DEBUG_OTEL === \"1\" || process.env.ROY_TRACE_DEBUG === \"1\";\n}\nfunction otelLog(message, ...args) {\n getOtelLogger().info(message, ...args);\n}\nfunction otelLogWarn(message, ...args) {\n getOtelLogger().warn(message, ...args);\n}\nfunction otelLogError(message, ...args) {\n getOtelLogger().error(message, ...args);\n}\n\nclass OTelSpanImpl {\n name;\n kind;\n spanContext;\n attributes = {};\n startTime;\n endTime;\n error;\n storage;\n parentSpanContext;\n onEnd;\n constructor(name, spanContext, storage, parentSpanContext, onEnd) {\n this.name = name;\n this.kind = \"internal\";\n this.spanContext = spanContext;\n this.parentSpanContext = parentSpanContext;\n this.startTime = Date.now();\n this.storage = storage;\n this.onEnd = onEnd;\n }\n setAttribute(key, value) {\n this.attributes[key] = value;\n }\n addEvent(name, attributes) {\n const events = this.attributes._events || [];\n events.push({ name, attributes });\n this.attributes._events = events;\n }\n end(result, error) {\n this.endTime = Date.now();\n if (error) {\n this.error = error.message;\n }\n const duration = this.endTime - (this.startTime || 0);\n if (isOtelTraceDebugEnabled()) {\n otelLog(`[OTelSpan] Ending span: name=\"${this.name}\" traceId=${this.spanContext.traceId} spanId=${this.spanContext.spanId} duration=${duration}ms status=${error ? \"ERROR\" : \"OK\"}`);\n }\n let storage = this.storage;\n if (!storage) {\n otelLogWarn(`[OTelSpan] storage is null for \"${this.name}\", attempting to re-fetch...`);\n const provider = getTracerProvider();\n storage = provider.getStorage();\n }\n if (storage) {\n const isInitialized = storage.db || storage.initialized;\n if (!isInitialized) {\n otelLogWarn(`[OTelSpan] storage not initialized for \"${this.name}\", initializing now...`);\n storage.initialize().catch((err) => {\n otelLogError(`[OTelSpan] Failed to initialize storage:`, err);\n });\n }\n storage.save({\n traceId: this.spanContext.traceId,\n spanId: this.spanContext.spanId,\n parentSpanId: this.spanContext.parentSpanId,\n name: this.name,\n kind: this.kind,\n status: error ? \"error\" /* ERROR */ : \"ok\" /* OK */,\n startTime: this.startTime,\n endTime: this.endTime,\n attributes: this.attributes,\n result,\n error: this.error\n });\n } else {\n otelLogError(`[OTelSpan] Failed to save span \"${this.name}\": storage still null after re-fetch`);\n }\n this.onEnd?.();\n }\n}\n\nclass OTelTracerImpl {\n name;\n version;\n storage;\n currentContext;\n activeSpans = new Map;\n onSpanEndCallback;\n provider;\n instanceId;\n constructor(name, version, storage, provider) {\n this.name = name;\n this.version = version;\n this.storage = storage;\n this.provider = provider;\n this.instanceId = `${name}@${provider.instanceId}`;\n }\n setOnSpanEndCallback(callback) {\n this.onSpanEndCallback = callback;\n }\n getActiveSpanCount() {\n return this.activeSpans.size;\n }\n startSpan(name, options) {\n const parentFromOptions = options?.parent;\n const hasExplicitParent = options && \"parent\" in options;\n const hasExplicitContext = options && \"context\" in options;\n const globalContext = this.provider.getGlobalContext();\n let effectiveParentContext;\n let traceId;\n let spanId;\n let parentSpanId;\n let spanContext;\n if (hasExplicitContext && options?.context) {\n const injectedContext = options.context;\n traceId = injectedContext.traceId;\n spanId = this.generateSpanId();\n parentSpanId = injectedContext.spanId;\n spanContext = {\n traceId,\n spanId,\n parentSpanId\n };\n this.currentContext = {\n traceId,\n spanId,\n parentSpanId\n };\n const span2 = new OTelSpanImpl(name, spanContext, this.storage, injectedContext, () => this.handleSpanEnd(spanContext.spanId, injectedContext.spanId));\n if (options?.attributes) {\n for (const [key, value] of Object.entries(options.attributes)) {\n span2.setAttribute(key, value);\n }\n }\n this.activeSpans.set(spanId, span2);\n return span2;\n }\n if (hasExplicitParent) {\n effectiveParentContext = parentFromOptions;\n } else if (this.currentContext) {\n effectiveParentContext = this.currentContext;\n } else if (globalContext) {\n effectiveParentContext = globalContext;\n }\n traceId = effectiveParentContext?.traceId || this.generateTraceId();\n spanId = this.generateSpanId();\n if (hasExplicitParent && parentFromOptions) {\n parentSpanId = parentFromOptions.parentSpanId || parentFromOptions.spanId;\n } else if (this.currentContext) {\n parentSpanId = this.currentContext.spanId;\n } else if (globalContext) {\n parentSpanId = globalContext.spanId;\n }\n spanContext = {\n traceId,\n spanId,\n parentSpanId\n };\n this.currentContext = {\n traceId,\n spanId,\n parentSpanId\n };\n const span = new OTelSpanImpl(name, spanContext, this.storage, effectiveParentContext, () => this.handleSpanEnd(spanContext.spanId, effectiveParentContext?.spanId));\n if (options?.attributes) {\n for (const [key, value] of Object.entries(options.attributes)) {\n span.setAttribute(key, value);\n }\n }\n this.activeSpans.set(spanId, span);\n if (isOtelTraceDebugEnabled()) {\n otelLog(`[OTelTracer] ✓ Span created: name=\"${name}\" traceId=${traceId} spanId=${spanId} parentSpanId=${parentSpanId || \"-\"}`);\n }\n return span;\n }\n injectToEnv(env) {\n if (this.currentContext) {\n propagation.inject(env, this.currentContext);\n }\n }\n getCurrentContext() {\n return this.currentContext;\n }\n setCurrentContext(context) {\n this.currentContext = context;\n }\n findStackParentSpan(spanId) {\n for (const [, span] of this.activeSpans) {\n if (span.spanContext.parentSpanId === spanId) {\n return span;\n }\n }\n return;\n }\n endSpan(span) {\n const spanContext = span.spanContext;\n this.activeSpans.delete(spanContext.spanId);\n const currentTraceId = this.currentContext?.traceId;\n if (spanContext.parentSpanId) {\n const parentSpan = this.activeSpans.get(spanContext.parentSpanId);\n if (parentSpan) {\n const parentContext = {\n traceId: spanContext.traceId,\n spanId: parentSpan.spanContext.spanId,\n parentSpanId: parentSpan.spanContext.parentSpanId\n };\n this.currentContext = parentContext;\n return parentContext;\n }\n if (currentTraceId) {\n const parentContext = {\n traceId: currentTraceId,\n spanId: spanContext.parentSpanId,\n parentSpanId: undefined\n };\n this.currentContext = parentContext;\n return parentContext;\n }\n }\n const stackParentSpan = this.findStackParentSpan(spanContext.spanId);\n if (stackParentSpan) {\n const parentContext = {\n traceId: stackParentSpan.spanContext.traceId,\n spanId: stackParentSpan.spanContext.spanId,\n parentSpanId: stackParentSpan.spanContext.parentSpanId\n };\n this.currentContext = parentContext;\n return parentContext;\n }\n this.currentContext = undefined;\n return;\n }\n generateTraceId() {\n const timestamp = Date.now().toString(16).padStart(12, \"0\");\n const random = Array.from({ length: 5 }, () => Math.floor(Math.random() * 4294967295).toString(16).padStart(8, \"0\")).join(\"\");\n return (timestamp + random).slice(0, 32).padStart(32, \"0\");\n }\n generateSpanId() {\n return Math.floor(Math.random() * 18446744073709552000).toString(16).padStart(16, \"0\");\n }\n handleSpanEnd(spanId, parentSpanId) {\n this.activeSpans.delete(spanId);\n if (parentSpanId) {\n const parentSpan = this.activeSpans.get(parentSpanId);\n if (parentSpan) {\n this.currentContext = {\n traceId: parentSpan.spanContext.traceId,\n spanId: parentSpan.spanContext.spanId,\n parentSpanId: parentSpan.spanContext.parentSpanId\n };\n return;\n }\n if (this.currentContext?.traceId) {\n this.currentContext = {\n traceId: this.currentContext.traceId,\n spanId: parentSpanId,\n parentSpanId: undefined\n };\n return;\n }\n }\n const stackParentSpan = this.findStackParentSpan(spanId);\n if (stackParentSpan) {\n this.currentContext = {\n traceId: stackParentSpan.spanContext.traceId,\n spanId: stackParentSpan.spanContext.spanId,\n parentSpanId: stackParentSpan.spanContext.parentSpanId\n };\n return;\n }\n this.currentContext = undefined;\n }\n}\n\nclass OTelTracerProvider {\n tracers = new Map;\n storage;\n initialized = false;\n globalContext;\n instanceId;\n constructor(storage, dbPath) {\n providerCounter++;\n this.instanceId = `Provider#${providerCounter}`;\n this.storage = storage || new SQLiteSpanStorage(dbPath || getDefaultDbPath());\n }\n async initialize() {\n if (this.initialized)\n return;\n await this.storage.initialize();\n this.initialized = true;\n }\n isInitialized() {\n return this.initialized;\n }\n getGlobalContext() {\n return this.globalContext;\n }\n setGlobalContext(context) {\n this.globalContext = context;\n }\n getTracer(name, version) {\n const key = `${name}@${version || \"0.0.0\"}`;\n let tracer = this.tracers.get(key);\n if (!tracer) {\n tracer = new OTelTracerImpl(name, version, this.storage, this);\n this.tracers.set(key, tracer);\n if (this.initialized) {\n this.restoreFromEnv(tracer);\n }\n }\n return tracer;\n }\n restoreFromEnv(tracer) {\n const extracted = propagation.extract(process.env);\n if (extracted) {\n tracer.setCurrentContext({\n traceId: extracted.traceId,\n spanId: extracted.spanId,\n parentSpanId: undefined\n });\n }\n }\n shutdown() {\n for (const tracer of this.tracers.values()) {}\n this.tracers.clear();\n this.storage.close();\n this.initialized = false;\n this.globalContext = undefined;\n delete process.env[\"TRACEPARENT\"];\n delete process.env[\"TRACE_ID\"];\n delete process.env[\"LOG_TRACE_REQUEST_ID\"];\n }\n getStorage() {\n return this.storage;\n }\n}\nfunction getTracerProvider() {\n if (!providerInstance) {\n providerInstance = new OTelTracerProvider;\n }\n return providerInstance;\n}\nfunction resetTracerProvider() {\n if (providerInstance) {\n providerInstance.shutdown();\n providerInstance = null;\n }\n}\nfunction setTracerProvider(provider) {\n if (providerInstance) {\n providerInstance.shutdown();\n }\n providerInstance = provider;\n}\nfunction getDefaultDbPath() {\n const os = __require(\"os\");\n const path = __require(\"path\");\n const home = os.homedir();\n const dataHome = process.env.XDG_DATA_HOME || path.join(home, \".local\", \"share\");\n return path.join(dataHome, \"roy-agent\", \"traces.db\");\n}\nvar _otelLogger = null, providerInstance = null, providerCounter = 0;\nvar init_tracer_provider = __esm(() => {\n init_span_storage();\n init_propagation();\n init_types();\n init_logger();\n});\n\nexport { serialize, parse, propagation, init_propagation, SpanKind, SpanStatus, init_types, OTelTracerProvider, getTracerProvider, resetTracerProvider, setTracerProvider, exports_tracer_provider, init_tracer_provider, simplifyFilePath, isQuietMode, setQuietMode, setConfigComponent, getLogLevel, getLogFile, getLogDir, getMaxOutput, setLogDirOverride, getLogDirOverride, createLogger, getLogLevels, init_logger };\n",
|
|
91
|
+
"import {\n createLogger,\n getMaxOutput,\n getTracerProvider,\n init_logger,\n init_tracer_provider,\n simplifyFilePath\n} from \"./roy-agent-core-8seq65bp.js\";\nimport {\n __esm\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/log-trace/decorator.ts\nfunction Traced(options) {\n const buildOptions = () => ({\n recordParams: options?.recordParams ?? true,\n recordResult: options?.recordResult ?? false,\n recordError: options?.recordError ?? true,\n log: options?.log ?? false,\n maxLogSize: options?.maxLogSize,\n paramFilter: options?.paramFilter,\n resultFilter: options?.resultFilter,\n flattenParamFilter: options?.flattenParamFilter,\n errorIf: options?.errorIf\n });\n return function(target, propertyKey, descriptor) {\n if (descriptor !== undefined && descriptor !== null && typeof descriptor === \"object\" && \"value\" in descriptor) {\n const originalFn = descriptor.value;\n const spanName = options?.name || String(propertyKey);\n descriptor.value = wrapFunction(originalFn, spanName, buildOptions());\n return descriptor;\n }\n const value = target;\n const context = propertyKey || {};\n if (typeof value === \"function\") {\n const spanName = options?.name || (context?.name ? String(context.name) : \"anonymous\");\n return wrapFunction(value, spanName, buildOptions());\n }\n return value;\n };\n}\nfunction TracedAs(name, options) {\n return Traced({ name, ...options });\n}\nfunction TracedLightweight(options) {\n return Traced({ recordParams: false, recordResult: false, log: options?.log ?? false, maxLogSize: options?.maxLogSize });\n}\nfunction wrapFunction(fn, name, options) {\n const shouldLog = options?.log ?? false;\n const getMaxLogSize = () => {\n if (options?.maxLogSize !== undefined) {\n return options.maxLogSize;\n }\n const configMaxOutput = getMaxOutput();\n return configMaxOutput !== undefined ? configMaxOutput : 500;\n };\n const truncate = (obj) => {\n if (obj === undefined)\n return;\n if (obj === null)\n return null;\n const maxLogSize = getMaxLogSize();\n let str;\n try {\n str = typeof obj === \"string\" ? obj : JSON.stringify(obj, null, 0).replace(/\\n/g, \"\");\n } catch (e) {\n str = `[Object with circular reference: ${e instanceof Error ? e.message : String(e)}]`;\n }\n if (maxLogSize > 0 && str.length > maxLogSize) {\n return str.slice(0, maxLogSize) + \" [TRUNCATED]\";\n }\n try {\n return JSON.parse(str);\n } catch {\n return str;\n }\n };\n const truncateString = (obj) => {\n if (obj === undefined)\n return \"undefined\";\n if (obj === null)\n return \"null\";\n const maxLogSize = getMaxLogSize();\n let str;\n try {\n str = typeof obj === \"string\" ? obj : JSON.stringify(obj, null, 0).replace(/\\n/g, \"\");\n } catch (e) {\n str = `[Object with circular reference: ${e instanceof Error ? e.message : String(e)}]`;\n }\n return maxLogSize > 0 && str.length > maxLogSize ? str.slice(0, maxLogSize) + \" [TRUNCATED]\" : str;\n };\n const toDbValue = (obj) => {\n if (obj === undefined)\n return;\n if (obj === null)\n return null;\n if (typeof obj === \"string\")\n return obj;\n try {\n return JSON.parse(JSON.stringify(obj));\n } catch (e) {\n return `[Object with circular reference: ${e instanceof Error ? e.message : String(e)}]`;\n }\n };\n const TRACE_LOG_PREFIX = \"[TRACE]\";\n const getCallerLocation = () => {\n const originalLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = 15;\n const err = new Error;\n Error.captureStackTrace(err, getCallerLocation);\n const stack = err.stack?.split(`\n`) || [];\n Error.stackTraceLimit = originalLimit;\n for (let i = 1;i < stack.length; i++) {\n const line = stack[i];\n if (line.includes(\"decorator.ts\") || line.includes(\"decorator.js\") || line.includes(\"logFn\") || line.includes(\"getCallerLocation\"))\n continue;\n const match = line.match(/at\\s+.+\\s+\\((.+):(\\d+):\\d+\\)/) || line.match(/at\\s+(.+):(\\d+):\\d+/);\n if (match) {\n const filePath = match[1];\n if (!filePath || filePath === \"native\")\n continue;\n const relativePath = simplifyFilePath(filePath);\n return `${relativePath}:${match[2]}`;\n }\n }\n return \"\";\n };\n const logFn = (event, argsOrData, callerLocation) => {\n if (!shouldLog)\n return;\n const logger = createLogger(\"traced:\" + name);\n const tag = event === \"enter\" ? \">>>\" : event === \"quit\" ? \"<<<\" : \"!!!\";\n const prefix = `${TRACE_LOG_PREFIX} ${tag} ${name}`;\n const originalFnLocation = callerLocation || getCallerLocation();\n const logMessage = (msg, data) => {\n if (data !== undefined) {\n logger.info(`${prefix} ${msg}: ${truncateString(data)}`, { callerLocation: originalFnLocation });\n } else {\n logger.info(`${prefix} ${msg}`, { callerLocation: originalFnLocation });\n }\n };\n if (event === \"enter\") {\n logMessage(\"enter\", argsOrData);\n } else if (event === \"quit\") {\n logMessage(\"quit\", options?.recordResult ? argsOrData : undefined);\n } else {\n logMessage(\"error\", argsOrData);\n }\n };\n return function(...args) {\n const tracer = getTracerProvider().getTracer(\"roy-tracer\");\n const attributes = {};\n if (options?.recordParams !== false) {\n if (options?.paramFilter) {\n const filtered = options.paramFilter(args);\n attributes[\"params\"] = toDbValue(filtered);\n if (options?.flattenParamFilter && filtered && typeof filtered === \"object\" && !Array.isArray(filtered)) {\n for (const [key, value] of Object.entries(filtered)) {\n if (!(key in attributes)) {\n attributes[key] = toDbValue(value);\n }\n }\n }\n } else {\n attributes[\"params\"] = toDbValue(args);\n }\n }\n const callerLocation = getCallerLocation();\n let span;\n try {\n span = tracer.startSpan(name, { attributes });\n } catch {}\n logFn(\"enter\", args, callerLocation);\n try {\n const result = fn.call(this, ...args);\n if (result && typeof result === \"object\" && typeof result.then === \"function\") {\n return result.then((resolved) => {\n if (span) {\n if (options?.resultFilter) {\n const filtered = options.resultFilter(resolved);\n if (filtered && typeof filtered === \"object\") {\n for (const [key, value] of Object.entries(filtered)) {\n span.setAttribute(key, toDbValue(value));\n }\n }\n }\n span.setAttribute(\"result\", JSON.stringify(toDbValue(resolved)));\n const resultError = options?.errorIf ? options.errorIf(resolved) : undefined;\n if (resultError) {\n const err = resultError instanceof Error ? resultError : new Error(String(resultError));\n span.setAttribute(\"error\", err.message);\n span.end(undefined, err);\n } else {\n span.end(resolved);\n }\n }\n logFn(\"quit\", options?.recordResult ? resolved : undefined, callerLocation);\n return resolved;\n }, (rejected) => {\n if (span) {\n span.setAttribute(\"error\", String(rejected));\n span.end(undefined, rejected instanceof Error ? rejected : new Error(String(rejected)));\n }\n logFn(\"error\", rejected.message, callerLocation);\n throw rejected;\n });\n }\n if (span) {\n if (options?.resultFilter) {\n const filtered = options.resultFilter(result);\n if (filtered && typeof filtered === \"object\") {\n for (const [key, value] of Object.entries(filtered)) {\n span.setAttribute(key, toDbValue(value));\n }\n }\n }\n span.setAttribute(\"result\", JSON.stringify(toDbValue(result)));\n const syncResultError = options?.errorIf ? options.errorIf(result) : undefined;\n if (syncResultError) {\n const err = syncResultError instanceof Error ? syncResultError : new Error(String(syncResultError));\n span.setAttribute(\"error\", err.message);\n span.end(undefined, err);\n } else {\n span.end(result);\n }\n }\n logFn(\"quit\", options?.recordResult ? result : undefined, callerLocation);\n return result;\n } catch (error) {\n if (span) {\n span.setAttribute(\"error\", String(error));\n span.end(undefined, error instanceof Error ? error : new Error(String(error)));\n }\n logFn(\"error\", error.message, callerLocation);\n throw error;\n }\n };\n}\nvar init_decorator = __esm(() => {\n init_tracer_provider();\n init_logger();\n});\n\nexport { Traced, TracedAs, TracedLightweight, wrapFunction, init_decorator };\n",
|
|
92
|
+
"import {\n TracedAs,\n init_decorator\n} from \"./roy-agent-core-dsevjbck.js\";\nimport {\n createLogger,\n init_logger\n} from \"./roy-agent-core-8seq65bp.js\";\nimport {\n __esm,\n __export,\n __legacyDecorateClassTS,\n __require,\n __toCommonJS\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/task/storage/migrations/001_add_project_path_context.ts\nvar exports_001_add_project_path_context = {};\n__export(exports_001_add_project_path_context, {\n runMigration: () => runMigration\n});\nfunction runMigration(dbPath) {\n console.log(`[Migration 001] Starting migration for: ${dbPath}`);\n const db = createCompatibleDatabase(dbPath);\n try {\n try {\n db.run(`ALTER TABLE task ADD COLUMN project_path TEXT`);\n console.log(`[Migration 001] Added project_path column`);\n } catch (e) {\n if (e.message?.includes(\"duplicate column name\")) {\n console.log(`[Migration 001] project_path column already exists, skipping`);\n } else {\n throw e;\n }\n }\n try {\n db.run(`ALTER TABLE task ADD COLUMN context TEXT`);\n console.log(`[Migration 001] Added context column`);\n } catch (e) {\n if (e.message?.includes(\"duplicate column name\")) {\n console.log(`[Migration 001] context column already exists, skipping`);\n } else {\n throw e;\n }\n }\n console.log(`[Migration 001] Migration completed successfully`);\n } finally {\n db.close();\n }\n}\nvar init_001_add_project_path_context = __esm(() => {\n init_sqlite_task_store();\n if (false) {}\n});\n\n// src/env/task/storage/migrations/002_add_task_type.ts\nvar exports_002_add_task_type = {};\n__export(exports_002_add_task_type, {\n runMigration: () => runMigration2\n});\nfunction runMigration2(dbPath) {\n console.log(`[Migration 002] Starting migration for: ${dbPath}`);\n const db = createCompatibleDatabase(dbPath);\n try {\n try {\n db.run(`ALTER TABLE task ADD COLUMN type TEXT NOT NULL DEFAULT 'normal'`);\n console.log(`[Migration 002] Added type column`);\n } catch (e) {\n if (e.message?.includes(\"duplicate column name\")) {\n console.log(`[Migration 002] type column already exists, skipping`);\n } else {\n throw e;\n }\n }\n console.log(`[Migration 002] Migration completed successfully`);\n } finally {\n db.close();\n }\n}\nvar init_002_add_task_type = __esm(() => {\n init_sqlite_task_store();\n if (false) {}\n});\n\n// src/env/task/storage/migrations/003_add_process_description.ts\nvar exports_003_add_process_description = {};\n__export(exports_003_add_process_description, {\n runMigration: () => runMigration3\n});\nfunction runMigration3(dbPath) {\n console.log(`[Migration 003] Starting migration for: ${dbPath}`);\n const db = createCompatibleDatabase(dbPath);\n try {\n try {\n db.run(`ALTER TABLE task_operation ADD COLUMN process_description TEXT NOT NULL DEFAULT ''`);\n console.log(`[Migration 003] Added process_description column`);\n } catch (e) {\n if (e.message?.includes(\"duplicate column name\")) {\n console.log(`[Migration 003] process_description column already exists, skipping`);\n } else {\n throw e;\n }\n }\n console.log(`[Migration 003] Migration completed successfully`);\n } finally {\n db.close();\n }\n}\nvar init_003_add_process_description = __esm(() => {\n init_sqlite_task_store();\n if (false) {}\n});\n\n// src/env/task/storage/migrations/004_rename_action_to_milestone.ts\nvar exports_004_rename_action_to_milestone = {};\n__export(exports_004_rename_action_to_milestone, {\n runMigration: () => runMigration4\n});\nfunction runMigration4(dbPath) {\n console.log(`[Migration 004] Starting migration for: ${dbPath}`);\n const db = createCompatibleDatabase(dbPath);\n try {\n const existingColumns = new Set;\n const cols = db.query(\"PRAGMA table_info(task_operation)\").all();\n for (const c of cols)\n existingColumns.add(c.name);\n for (const { oldName, newName } of RENAME_MAP) {\n const hasOld = existingColumns.has(oldName);\n const hasNew = existingColumns.has(newName);\n if (hasOld && !hasNew) {\n db.run(`ALTER TABLE task_operation RENAME COLUMN ${oldName} TO ${newName}`);\n console.log(`[Migration 004] Renamed ${oldName} -> ${newName}`);\n } else if (hasNew) {\n console.log(`[Migration 004] ${newName} already exists, skipping rename of ${oldName}`);\n } else {\n console.log(`[Migration 004] ${oldName} not present, skipping rename to ${newName}`);\n }\n }\n console.log(`[Migration 004] Migration completed successfully`);\n } finally {\n db.close();\n }\n}\nvar RENAME_MAP;\nvar init_004_rename_action_to_milestone = __esm(() => {\n init_sqlite_task_store();\n RENAME_MAP = [\n { oldName: \"action_type\", newName: \"milestone_type\" },\n { oldName: \"action_title\", newName: \"milestone_title\" },\n { oldName: \"action_description\", newName: \"milestone_description\" }\n ];\n if (false) {}\n});\n\n// src/env/task/storage/migrations/005_convert_blob_description_to_text.ts\nvar exports_005_convert_blob_description_to_text = {};\n__export(exports_005_convert_blob_description_to_text, {\n runMigration: () => runMigration5\n});\nfunction runMigration5(dbPath) {\n console.log(`[Migration 005] Starting migration for: ${dbPath}`);\n const db = createCompatibleDatabase(dbPath);\n const result = {\n blobCountBefore: 0,\n blobCountAfter: 0,\n ran: false\n };\n try {\n const tableCheck = db.query(\"SELECT name FROM sqlite_master WHERE type='table' AND name='task'\").all();\n if (tableCheck.length === 0) {\n console.log(`[Migration 005] task table does not exist, skipping`);\n return result;\n }\n const beforeRows = db.query(\"SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'\").all();\n result.blobCountBefore = beforeRows[0]?.cnt ?? 0;\n if (result.blobCountBefore === 0) {\n console.log(`[Migration 005] No BLOB descriptions found, no action needed`);\n return result;\n }\n db.run(\"UPDATE task SET description = CAST(description AS TEXT) WHERE typeof(description) = 'blob'\");\n result.ran = true;\n const afterRows = db.query(\"SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'\").all();\n result.blobCountAfter = afterRows[0]?.cnt ?? 0;\n console.log(`[Migration 005] Converted ${result.blobCountBefore - result.blobCountAfter} BLOB description(s) to TEXT`);\n console.log(`[Migration 005] Migration completed successfully`);\n } finally {\n db.close();\n }\n return result;\n}\nvar init_005_convert_blob_description_to_text = __esm(() => {\n init_sqlite_task_store();\n if (false) {}\n});\n\n// src/env/task/storage/sqlite-task-store.ts\nimport { join } from \"path\";\nfunction getDatabaseClass() {\n if (typeof Bun !== \"undefined\") {\n const { Database } = __require(\"bun:sqlite\");\n return Database;\n } else {\n return __require(\"better-sqlite3\");\n }\n}\nfunction createCompatibleDatabase(path) {\n const Database = getDatabaseClass();\n const db = new Database(path);\n if (typeof db.run !== \"function\") {\n db.run = function(sql, ...params) {\n if (params.length > 0) {\n return this.prepare(sql).run(...params);\n } else {\n return this.exec(sql);\n }\n };\n }\n return db;\n}\nfunction getDefaultDataDir() {\n const home = process.env.HOME || process.env.USERPROFILE || \"/tmp\";\n return join(home, \".local\", \"share\");\n}\nfunction getDefaultTaskDbPath() {\n return join(getDefaultDataDir(), \"roy-agent\", \"tasks.db\");\n}\nvar logger, SQLiteTaskStore;\nvar init_sqlite_task_store = __esm(() => {\n init_logger();\n init_decorator();\n logger = createLogger(\"task:store\");\n SQLiteTaskStore = class SQLiteTaskStore {\n db = null;\n dbPath;\n initialized = false;\n tasksCache = new Map;\n operationsCache = new Map;\n constructor(dbPath) {\n this.dbPath = dbPath || getDefaultTaskDbPath();\n }\n async initialize() {\n if (this.initialized)\n return;\n if (this.dbPath !== \":memory:\") {\n const fs = __require(\"fs\");\n const path = __require(\"path\");\n const dir = path.dirname(this.dbPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n }\n this.db = createCompatibleDatabase(this.dbPath);\n this.db.run(`\n CREATE TABLE IF NOT EXISTS task (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n title TEXT NOT NULL,\n description TEXT DEFAULT '',\n status TEXT DEFAULT 'todo',\n priority TEXT DEFAULT 'medium',\n type TEXT DEFAULT 'normal',\n progress INTEGER DEFAULT 0,\n current_status TEXT DEFAULT '',\n goals_and_expected_deliverables TEXT DEFAULT '',\n parent_task_id INTEGER,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n due_date TEXT,\n tags TEXT,\n project_path TEXT NOT NULL DEFAULT 'unknown',\n context TEXT NOT NULL DEFAULT '{}'\n )\n `);\n this.db.run(`\n CREATE TABLE IF NOT EXISTS task_operation (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n task_id INTEGER NOT NULL,\n session_id TEXT NOT NULL,\n milestone_type TEXT NOT NULL,\n milestone_title TEXT NOT NULL,\n milestone_description TEXT DEFAULT '',\n process_description TEXT NOT NULL DEFAULT '',\n timestamp INTEGER NOT NULL,\n md_path TEXT,\n FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE\n )\n `);\n this.db.run(\"CREATE INDEX IF NOT EXISTS idx_task_operation_task_id ON task_operation(task_id)\");\n this.db.run(\"CREATE INDEX IF NOT EXISTS idx_task_operation_session_id ON task_operation(session_id)\");\n this.db.run(`\n CREATE TABLE IF NOT EXISTS task_tag (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT NOT NULL UNIQUE,\n created_at INTEGER NOT NULL,\n task_count INTEGER DEFAULT 0\n )\n `);\n this.db.run(`\n CREATE TABLE IF NOT EXISTS task_tag_relation (\n task_id INTEGER NOT NULL,\n tag_id INTEGER NOT NULL,\n created_at INTEGER NOT NULL,\n PRIMARY KEY (task_id, tag_id),\n FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE,\n FOREIGN KEY (tag_id) REFERENCES task_tag(id) ON DELETE CASCADE\n )\n `);\n this.db.run(\"CREATE INDEX IF NOT EXISTS idx_task_tag_relation_tag_id ON task_tag_relation(tag_id)\");\n this.db.run(\"CREATE INDEX IF NOT EXISTS idx_task_parent_task_id ON task(parent_task_id)\");\n if (this.dbPath !== \":memory:\") {\n try {\n const { runMigration: runMigration001 } = (init_001_add_project_path_context(), __toCommonJS(exports_001_add_project_path_context));\n runMigration001(this.dbPath);\n } catch (e) {\n logger.warn(`[Migration 001] Failed to run: ${e.message}`);\n }\n try {\n const { runMigration: runMigration002 } = (init_002_add_task_type(), __toCommonJS(exports_002_add_task_type));\n runMigration002(this.dbPath);\n } catch (e) {\n logger.warn(`[Migration 002] Failed to run: ${e.message}`);\n }\n try {\n const { runMigration: runMigration003 } = (init_003_add_process_description(), __toCommonJS(exports_003_add_process_description));\n runMigration003(this.dbPath);\n } catch (e) {\n logger.warn(`[Migration 003] Failed to run: ${e.message}`);\n }\n try {\n const { runMigration: runMigration004 } = (init_004_rename_action_to_milestone(), __toCommonJS(exports_004_rename_action_to_milestone));\n runMigration004(this.dbPath);\n } catch (e) {\n logger.warn(`[Migration 004] Failed to run: ${e.message}`);\n }\n try {\n const { runMigration: runMigration005 } = (init_005_convert_blob_description_to_text(), __toCommonJS(exports_005_convert_blob_description_to_text));\n runMigration005(this.dbPath);\n } catch (e) {\n logger.warn(`[Migration 005] Failed to run: ${e.message}`);\n }\n }\n this.initialized = true;\n logger.info(`TaskStore initialized at ${this.dbPath}`);\n }\n async createTask(options) {\n await this.initialize();\n const now = Date.now();\n const stmt = this.db.prepare(`\n INSERT INTO task (title, description, priority, type, parent_task_id, \n goals_and_expected_deliverables, due_date, tags, status, \n current_status, created_at, updated_at, project_path, context)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'todo', '', ?, ?, ?, ?)\n `);\n const result = stmt.run(options.title, options.description || \"\", options.priority || \"medium\", options.type || \"normal\", options.parent_task_id || null, options.goals_and_expected_deliverables || \"\", options.due_date || null, options.tags ? JSON.stringify(options.tags) : null, now, now, options.project_path, options.context);\n const task = await this.getTask(result.lastInsertRowid);\n if (task) {\n this.tasksCache.set(task.id, task);\n return task;\n }\n throw new Error(\"Failed to create task\");\n }\n async getTask(id) {\n await this.initialize();\n if (this.tasksCache.has(id)) {\n return this.tasksCache.get(id);\n }\n const stmt = this.db.prepare(\"SELECT * FROM task WHERE id = ?\");\n const row = stmt.get(id);\n if (!row)\n return;\n const task = this.rowToTask(row);\n this.tasksCache.set(id, task);\n return task;\n }\n async updateTask(id, options) {\n await this.initialize();\n const task = await this.getTask(id);\n if (!task)\n return;\n const updates = [];\n const values = [];\n if (options.title !== undefined) {\n updates.push(\"title = ?\");\n values.push(options.title);\n }\n if (options.description !== undefined) {\n updates.push(\"description = ?\");\n values.push(options.description);\n }\n if (options.status !== undefined) {\n updates.push(\"status = ?\");\n values.push(options.status);\n }\n if (options.priority !== undefined) {\n updates.push(\"priority = ?\");\n values.push(options.priority);\n }\n if (options.type !== undefined) {\n updates.push(\"type = ?\");\n values.push(options.type);\n }\n if (options.progress !== undefined) {\n updates.push(\"progress = ?\");\n values.push(options.progress);\n }\n if (options.current_status !== undefined) {\n updates.push(\"current_status = ?\");\n values.push(options.current_status);\n }\n if (options.goals_and_expected_deliverables !== undefined) {\n updates.push(\"goals_and_expected_deliverables = ?\");\n values.push(options.goals_and_expected_deliverables);\n }\n if (options.due_date !== undefined) {\n updates.push(\"due_date = ?\");\n values.push(options.due_date);\n }\n if (options.tags !== undefined) {\n updates.push(\"tags = ?\");\n values.push(JSON.stringify(options.tags));\n }\n if (options.project_path !== undefined) {\n updates.push(\"project_path = ?\");\n values.push(options.project_path);\n }\n if (options.context !== undefined) {\n updates.push(\"context = ?\");\n values.push(options.context);\n }\n if (options.parent_task_id !== undefined) {\n updates.push(\"parent_task_id = ?\");\n values.push(options.parent_task_id);\n }\n if (updates.length === 0)\n return task;\n updates.push(\"updated_at = ?\");\n values.push(Date.now());\n values.push(id);\n const stmt = this.db.prepare(`UPDATE task SET ${updates.join(\", \")} WHERE id = ?`);\n stmt.run(...values);\n this.tasksCache.delete(id);\n return this.getTask(id);\n }\n async deleteTask(id) {\n await this.initialize();\n const stmt = this.db.prepare(\"DELETE FROM task WHERE id = ?\");\n const result = stmt.run(id);\n if (result.changes > 0) {\n this.tasksCache.delete(id);\n this.operationsCache.delete(id);\n }\n return result.changes > 0;\n }\n async listTasks(options) {\n await this.initialize();\n if (options?.depth !== undefined && options.depth >= 0 && options.parent_task_id === undefined) {\n return this.listTasksByDepth(options);\n }\n const whereClauses = [\"1=1\"];\n const whereParams = [];\n if (options?.status) {\n whereClauses.push(\"status = ?\");\n whereParams.push(options.status);\n }\n if (options?.priority) {\n whereClauses.push(\"priority = ?\");\n whereParams.push(options.priority);\n }\n if (options?.type) {\n whereClauses.push(\"type = ?\");\n whereParams.push(options.type);\n }\n if (options?.parent_task_id !== undefined) {\n whereClauses.push(\"parent_task_id = ?\");\n whereParams.push(options.parent_task_id);\n }\n if (!options?.include_archived && options?.status !== \"archived\") {\n whereClauses.push(\"status != 'archived'\");\n }\n const whereSql = whereClauses.join(\" AND \");\n const countSql = `SELECT COUNT(*) as total FROM task WHERE ${whereSql}`;\n const countRow = this.db.prepare(countSql).get(...whereParams);\n const total = countRow?.total ?? 0;\n let sql = `SELECT * FROM task WHERE ${whereSql}`;\n const params = [...whereParams];\n sql += \" ORDER BY updated_at DESC\";\n if (options?.limit) {\n sql += \" LIMIT ?\";\n params.push(options.limit);\n }\n if (options?.offset) {\n sql += \" OFFSET ?\";\n params.push(options.offset);\n }\n const stmt = this.db.prepare(sql);\n const rows = stmt.all(...params);\n const tasks = rows.map((row) => {\n const task = this.rowToTask(row);\n this.tasksCache.set(task.id, task);\n return task;\n });\n return { tasks, total };\n }\n async listTasksByDepth(options) {\n const depth = options.depth ?? 0;\n const filterClauses = [\"1=1\"];\n const filterParams = [];\n if (options.status) {\n filterClauses.push(\"status = ?\");\n filterParams.push(options.status);\n }\n if (options.priority) {\n filterClauses.push(\"priority = ?\");\n filterParams.push(options.priority);\n }\n if (options.type) {\n filterClauses.push(\"type = ?\");\n filterParams.push(options.type);\n }\n if (!options?.include_archived && options?.status !== \"archived\") {\n filterClauses.push(\"status != 'archived'\");\n }\n const filterSql = filterClauses.join(\" AND \");\n const collected = [];\n if (depth === 0) {\n const rootSql = `SELECT * FROM task WHERE parent_task_id IS NULL AND ${filterSql} ORDER BY updated_at DESC`;\n const rows = this.db.prepare(rootSql).all(...filterParams);\n for (const row of rows) {\n const t = this.rowToTask(row);\n this.tasksCache.set(t.id, t);\n collected.push(t);\n }\n } else {\n const rootRows = this.db.prepare(`SELECT * FROM task WHERE parent_task_id IS NULL AND ${filterSql} ORDER BY updated_at DESC`).all(...filterParams);\n let currentLevel = rootRows.map((row) => {\n const t = this.rowToTask(row);\n this.tasksCache.set(t.id, t);\n return t;\n });\n collected.push(...currentLevel);\n for (let level = 1;level <= depth; level++) {\n if (currentLevel.length === 0)\n break;\n const ids = currentLevel.map((t) => t.id);\n const placeholders = ids.map(() => \"?\").join(\",\");\n const childSql = `SELECT * FROM task WHERE parent_task_id IN (${placeholders}) AND ${filterSql} ORDER BY updated_at DESC`;\n const childRows = this.db.prepare(childSql).all(...ids, ...filterParams);\n const nextLevel = childRows.map((row) => {\n const t = this.rowToTask(row);\n this.tasksCache.set(t.id, t);\n return t;\n });\n collected.push(...nextLevel);\n currentLevel = nextLevel;\n }\n }\n const total = collected.length;\n const offset = options.offset ?? 0;\n const limit = options.limit ?? total;\n const sliced = collected.slice(offset, offset + limit);\n return { tasks: sliced, total };\n }\n async getTaskTree(taskId, depth = -1) {\n await this.initialize();\n const result = [];\n let currentLevel = [taskId];\n let currentDepth = 0;\n while (currentLevel.length > 0) {\n if (depth !== -1 && currentDepth >= depth)\n break;\n const placeholders = currentLevel.map(() => \"?\").join(\",\");\n const rows = this.db.prepare(`SELECT * FROM task WHERE parent_task_id IN (${placeholders}) ORDER BY updated_at DESC`).all(...currentLevel);\n const nextLevel = [];\n for (const row of rows) {\n const t = this.rowToTask(row);\n this.tasksCache.set(t.id, t);\n result.push(t);\n nextLevel.push(t.id);\n }\n currentLevel = nextLevel;\n currentDepth++;\n }\n return result;\n }\n async getChildTasks(taskId, options = {}) {\n return this.listTasks({ ...options, parent_task_id: taskId });\n }\n async createOperation(options) {\n await this.initialize();\n const finalMilestoneType = options.milestoneType ?? options.actionType;\n const finalMilestoneTitle = options.milestoneTitle ?? options.actionTitle;\n const finalMilestoneDesc = options.milestoneDescription ?? options.actionDescription;\n if (!finalMilestoneType || !finalMilestoneTitle) {\n throw new Error(\"createOperation requires milestoneType and milestoneTitle (or legacy actionType/actionTitle)\");\n }\n const now = Date.now();\n const stmt = this.db.prepare(`\n INSERT INTO task_operation (task_id, session_id, milestone_type, milestone_title,\n milestone_description, process_description, timestamp, md_path)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `);\n const result = stmt.run(options.taskId, options.sessionId, finalMilestoneType, finalMilestoneTitle, finalMilestoneDesc || \"\", options.processDescription || \"\", now, options.mdPath || null);\n this.operationsCache.delete(options.taskId);\n const operation = await this.getOperation(result.lastInsertRowid);\n if (!operation) {\n throw new Error(\"Failed to create operation\");\n }\n return operation;\n }\n async getOperation(id) {\n await this.initialize();\n const stmt = this.db.prepare(\"SELECT * FROM task_operation WHERE id = ?\");\n const row = stmt.get(id);\n if (!row)\n return;\n return this.rowToOperation(row);\n }\n async updateOperation(id, updates) {\n await this.initialize();\n const op = await this.getOperation(id);\n if (!op)\n return;\n const titleValue = updates.milestoneTitle ?? updates.actionTitle;\n const descValue = updates.milestoneDescription ?? updates.actionDescription;\n const setClauses = [];\n const values = [];\n if (titleValue !== undefined) {\n setClauses.push(\"milestone_title = ?\");\n values.push(titleValue);\n }\n if (descValue !== undefined) {\n setClauses.push(\"milestone_description = ?\");\n values.push(descValue);\n }\n if (updates.processDescription !== undefined) {\n setClauses.push(\"process_description = ?\");\n values.push(updates.processDescription);\n }\n if (setClauses.length === 0)\n return op;\n const stmt = this.db.prepare(`UPDATE task_operation SET ${setClauses.join(\", \")} WHERE id = ?`);\n stmt.run(...values, id);\n this.operationsCache.delete(op.taskId);\n return this.getOperation(id);\n }\n async deleteOperation(id) {\n await this.initialize();\n const op = await this.getOperation(id);\n if (!op)\n return false;\n const stmt = this.db.prepare(\"DELETE FROM task_operation WHERE id = ?\");\n const result = stmt.run(id);\n if (result.changes > 0) {\n this.operationsCache.delete(op.taskId);\n }\n return result.changes > 0;\n }\n async listOperations(options) {\n await this.initialize();\n const cacheKey = options.taskId;\n if (!this.operationsCache.has(cacheKey)) {\n const stmt = this.db.prepare(\"SELECT * FROM task_operation WHERE task_id = ? ORDER BY timestamp DESC\");\n const rows = stmt.all(options.taskId);\n this.operationsCache.set(cacheKey, rows.map((row) => this.rowToOperation(row)));\n }\n let ops = this.operationsCache.get(cacheKey);\n const filterType = options.milestoneType ?? options.actionType;\n if (filterType) {\n ops = ops.filter((op) => op.milestoneType === filterType);\n }\n const offset = options.offset || 0;\n const limit = options.limit || 20;\n return ops.slice(offset, offset + limit);\n }\n async getTaskIdBySessionId(sessionId) {\n await this.initialize();\n if (!sessionId)\n return;\n const row = this.db.prepare(\"SELECT task_id FROM task_operation WHERE session_id = ? AND milestone_type = 'create' ORDER BY timestamp ASC LIMIT 1\").get(sessionId);\n return typeof row?.task_id === \"number\" ? row.task_id : undefined;\n }\n rowToTask(row) {\n return {\n id: row.id,\n title: String(row.title ?? \"\"),\n description: String(row.description ?? \"\"),\n status: String(row.status ?? \"todo\"),\n priority: String(row.priority ?? \"medium\"),\n type: String(row.type ?? \"normal\"),\n progress: row.progress,\n current_status: String(row.current_status ?? \"\"),\n goals_and_expected_deliverables: String(row.goals_and_expected_deliverables ?? \"\"),\n parent_task_id: row.parent_task_id || undefined,\n createdAt: new Date(row.created_at).toISOString(),\n updatedAt: new Date(row.updated_at).toISOString(),\n due_date: row.due_date ? String(row.due_date) : undefined,\n tags: SQLiteTaskStore.parseTagsSafely(row.tags),\n project_path: String(row.project_path ?? \"unknown\"),\n context: row.context\n };\n }\n static parseTagsSafely(raw) {\n if (raw === null || raw === undefined || raw === \"\") {\n return;\n }\n const str = typeof raw === \"string\" ? raw : String(raw);\n try {\n const parsed = JSON.parse(str);\n if (Array.isArray(parsed)) {\n return parsed;\n }\n if (typeof parsed === \"string\") {\n return [parsed];\n }\n return;\n } catch {\n return [str];\n }\n }\n rowToOperation(row) {\n const milestoneType = row.milestone_type ?? row.action_type;\n const milestoneTitle = row.milestone_title ?? row.action_title;\n const milestoneDescription = row.milestone_description ?? row.action_description ?? \"\";\n return {\n id: row.id,\n taskId: row.task_id,\n sessionId: row.session_id,\n milestoneType,\n milestoneTitle,\n milestoneDescription,\n processDescription: row.process_description ?? \"\",\n timestamp: new Date(row.timestamp).toISOString(),\n mdPath: row.md_path || undefined,\n actionType: milestoneType,\n actionTitle: milestoneTitle,\n actionDescription: milestoneDescription\n };\n }\n async createTag(name) {\n await this.initialize();\n const now = Date.now();\n const existing = await this.getTagByName(name);\n if (existing) {\n return existing;\n }\n const stmt = this.db.prepare(`\n INSERT INTO task_tag (name, created_at, task_count)\n VALUES (?, ?, 0)\n `);\n const result = stmt.run(name, now);\n return {\n id: result.lastInsertRowid,\n name,\n createdAt: new Date(now).toISOString(),\n taskCount: 0\n };\n }\n async getTag(id) {\n await this.initialize();\n const stmt = this.db.prepare(\"SELECT * FROM task_tag WHERE id = ?\");\n const row = stmt.get(id);\n if (!row)\n return;\n return this.rowToTag(row);\n }\n async getTagByName(name) {\n await this.initialize();\n const stmt = this.db.prepare(\"SELECT * FROM task_tag WHERE name = ?\");\n const row = stmt.get(name);\n if (!row)\n return;\n return this.rowToTag(row);\n }\n async listTags(options) {\n await this.initialize();\n let sql = \"SELECT * FROM task_tag\";\n const params = [];\n const orderBy = options?.orderBy || \"count\";\n if (orderBy === \"count\") {\n sql += \" ORDER BY task_count DESC\";\n } else if (orderBy === \"name\") {\n sql += \" ORDER BY name ASC\";\n } else {\n sql += \" ORDER BY created_at DESC\";\n }\n if (options?.limit) {\n sql += \" LIMIT ?\";\n params.push(options.limit);\n }\n if (options?.offset) {\n sql += \" OFFSET ?\";\n params.push(options.offset);\n }\n const stmt = this.db.prepare(sql);\n const rows = stmt.all(...params);\n return rows.map((row) => this.rowToTag(row));\n }\n async searchTags(options) {\n await this.initialize();\n const sql = `\n SELECT * FROM task_tag \n WHERE name LIKE ? \n ORDER BY task_count DESC \n LIMIT ?\n `;\n const stmt = this.db.prepare(sql);\n const rows = stmt.all(`%${options.query}%`, options.limit || 20);\n return rows.map((row) => this.rowToTag(row));\n }\n async deleteTag(id) {\n await this.initialize();\n const stmt = this.db.prepare(\"DELETE FROM task_tag WHERE id = ?\");\n const result = stmt.run(id);\n return result.changes > 0;\n }\n async addTagsToTask(taskId, tagIds) {\n await this.initialize();\n const now = Date.now();\n const stmt = this.db.prepare(`\n INSERT OR IGNORE INTO task_tag_relation (task_id, tag_id, created_at)\n VALUES (?, ?, ?)\n `);\n for (const tagId of tagIds) {\n stmt.run(taskId, tagId, now);\n this.db.run(`\n UPDATE task_tag SET task_count = task_count + 1 WHERE id = ?\n `, tagId);\n }\n await this.syncTaskTagsJson(taskId);\n }\n async removeTagsFromTask(taskId, tagIds) {\n await this.initialize();\n const stmt = this.db.prepare(\"DELETE FROM task_tag_relation WHERE task_id = ? AND tag_id = ?\");\n for (const tagId of tagIds) {\n stmt.run(taskId, tagId);\n this.db.run(`\n UPDATE task_tag SET task_count = MAX(0, task_count - 1) WHERE id = ?\n `, tagId);\n }\n await this.syncTaskTagsJson(taskId);\n }\n async getTagsForTask(taskId) {\n await this.initialize();\n const sql = `\n SELECT t.* FROM task_tag t\n INNER JOIN task_tag_relation r ON t.id = r.tag_id\n WHERE r.task_id = ?\n ORDER BY t.name ASC\n `;\n const stmt = this.db.prepare(sql);\n const rows = stmt.all(taskId);\n return rows.map((row) => this.rowToTag(row));\n }\n async getTaskIdsByTags(tagNames) {\n await this.initialize();\n if (tagNames.length === 0)\n return [];\n const placeholders = tagNames.map(() => \"?\").join(\", \");\n const sql = `\n SELECT DISTINCT r.task_id FROM task_tag_relation r\n INNER JOIN task_tag t ON r.tag_id = t.id\n WHERE t.name IN (${placeholders})\n `;\n const stmt = this.db.prepare(sql);\n const rows = stmt.all(...tagNames);\n return rows.map((row) => row.task_id);\n }\n async updateTaskTags(taskId, tagNames) {\n await this.initialize();\n const currentTags = await this.getTagsForTask(taskId);\n if (currentTags.length > 0) {\n await this.removeTagsFromTask(taskId, currentTags.map((t) => t.id));\n }\n const tagIds = [];\n for (const name of tagNames) {\n let tag = await this.getTagByName(name);\n if (!tag) {\n tag = await this.createTag(name);\n }\n tagIds.push(tag.id);\n }\n if (tagIds.length > 0) {\n await this.addTagsToTask(taskId, tagIds);\n }\n }\n async searchTasksByKeywords(keywords, options = {}) {\n await this.initialize();\n if (!keywords || keywords.length === 0) {\n return { tasks: [], total: 0 };\n }\n const { limit = 20, offset = 0, excludeTaskId, status, priority, type, depth } = options;\n let allowedTaskIds = null;\n if (depth !== undefined && depth >= 0) {\n allowedTaskIds = await this.collectTaskIdsByDepth(depth);\n }\n const tasks = new Map;\n let taskSql = \"SELECT * FROM task WHERE 1=1\";\n const taskParams = [];\n if (excludeTaskId) {\n taskSql += \" AND id != ?\";\n taskParams.push(excludeTaskId);\n }\n if (status) {\n taskSql += \" AND status = ?\";\n taskParams.push(status);\n }\n if (priority) {\n taskSql += \" AND priority = ?\";\n taskParams.push(priority);\n }\n if (type) {\n taskSql += \" AND type = ?\";\n taskParams.push(type);\n }\n if (!options?.include_archived && options?.status !== \"archived\") {\n taskSql += \" AND status != 'archived'\";\n }\n const scanLimit = Math.max(limit * 5, 200);\n taskSql += \" ORDER BY updated_at DESC LIMIT ?\";\n taskParams.push(scanLimit);\n const taskRows = this.db.prepare(taskSql).all(...taskParams);\n for (const row of taskRows) {\n const task = this.rowToTask(row);\n const matchedKeywords = new Set;\n let matchCount = 0;\n if (typeof task.title === \"string\" && task.title) {\n const lowerTitle = task.title.toLowerCase();\n for (const keyword of keywords) {\n if (lowerTitle.includes(keyword.toLowerCase())) {\n {\n matchCount++;\n matchedKeywords.add(keyword);\n }\n }\n }\n }\n if (task.tags && Array.isArray(task.tags)) {\n for (const keyword of keywords) {\n const lowerKeyword = keyword.toLowerCase();\n if (task.tags.some((tag) => tag.toLowerCase().includes(lowerKeyword))) {\n {\n matchCount += 2;\n matchedKeywords.add(keyword);\n }\n }\n }\n }\n if (typeof task.description === \"string\" && task.description) {\n const lowerDesc = task.description.toLowerCase();\n for (const keyword of keywords) {\n if (lowerDesc.includes(keyword.toLowerCase())) {\n {\n matchCount++;\n matchedKeywords.add(keyword);\n }\n }\n }\n }\n if (typeof task.goals_and_expected_deliverables === \"string\" && task.goals_and_expected_deliverables) {\n const lowerGoals = task.goals_and_expected_deliverables.toLowerCase();\n for (const keyword of keywords) {\n if (lowerGoals.includes(keyword.toLowerCase())) {\n {\n matchCount++;\n matchedKeywords.add(keyword);\n }\n }\n }\n }\n if (matchedKeywords.size === keywords.length) {\n tasks.set(task.id, { task, matchCount });\n }\n }\n const allOps = this.db.prepare(\"SELECT DISTINCT task_id FROM task_operation WHERE 1=1\").all();\n for (const opRow of allOps) {\n const opSql = `\n SELECT * FROM task_operation\n WHERE task_id = ?\n AND (milestone_title LIKE ? OR milestone_description LIKE ? OR process_description LIKE ?)\n LIMIT 10\n `;\n const opMatchedKeywords = new Set;\n for (const keyword of keywords) {\n const pattern = `%${keyword}%`;\n const ops = this.db.prepare(opSql).all(opRow.task_id, pattern, pattern, pattern);\n if (ops.length > 0) {\n opMatchedKeywords.add(keyword);\n }\n }\n if (opMatchedKeywords.size === 0)\n continue;\n const taskRow = this.db.prepare(\"SELECT * FROM task WHERE id = ?\").get(opRow.task_id);\n if (!taskRow)\n continue;\n const task = this.rowToTask(taskRow);\n if (excludeTaskId && task.id === excludeTaskId)\n continue;\n if (status && task.status !== status)\n continue;\n if (priority && task.priority !== priority)\n continue;\n if (type && task.type !== type)\n continue;\n if (!options?.include_archived && task.status === \"archived\")\n continue;\n const existing = tasks.get(task.id);\n if (existing) {\n existing.matchCount += 2;\n } else {\n const combinedKeywords = new Set(opMatchedKeywords);\n if (typeof task.title === \"string\" && task.title) {\n const lowerTitle = task.title.toLowerCase();\n for (const kw of keywords) {\n if (lowerTitle.includes(kw.toLowerCase()))\n combinedKeywords.add(kw);\n }\n }\n if (typeof task.description === \"string\" && task.description) {\n const lowerDesc = task.description.toLowerCase();\n for (const kw of keywords) {\n if (lowerDesc.includes(kw.toLowerCase()))\n combinedKeywords.add(kw);\n }\n }\n if (typeof task.goals_and_expected_deliverables === \"string\" && task.goals_and_expected_deliverables) {\n const lowerGoals = task.goals_and_expected_deliverables.toLowerCase();\n for (const kw of keywords) {\n if (lowerGoals.includes(kw.toLowerCase()))\n combinedKeywords.add(kw);\n }\n }\n if (task.tags && Array.isArray(task.tags)) {\n for (const kw of keywords) {\n if (task.tags.some((tag) => tag.toLowerCase().includes(kw.toLowerCase())))\n combinedKeywords.add(kw);\n }\n }\n if (combinedKeywords.size === keywords.length) {\n tasks.set(task.id, { task, matchCount: 2 });\n }\n }\n }\n let sorted = Array.from(tasks.values()).sort((a, b) => b.matchCount - a.matchCount);\n if (allowedTaskIds !== null) {\n sorted = sorted.filter((item) => allowedTaskIds.has(item.task.id));\n }\n const total = sorted.length;\n const sliced = sorted.slice(offset, offset + limit);\n const resultTasks = sliced.map((item) => item.task);\n return { tasks: resultTasks, total };\n }\n async collectTaskIdsByDepth(depth) {\n const ids = new Set;\n const rootRows = this.db.prepare(\"SELECT id FROM task WHERE parent_task_id IS NULL\").all();\n let currentLevel = rootRows.map((r) => r.id);\n for (const id of currentLevel)\n ids.add(id);\n if (depth === 0)\n return ids;\n for (let level = 1;level <= depth; level++) {\n if (currentLevel.length === 0)\n break;\n const placeholders = currentLevel.map(() => \"?\").join(\",\");\n const rows = this.db.prepare(`SELECT id FROM task WHERE parent_task_id IN (${placeholders})`).all(...currentLevel);\n currentLevel = rows.map((r) => r.id);\n for (const id of currentLevel)\n ids.add(id);\n }\n return ids;\n }\n async findSimilarTasksByKeywords(keywords, options = {}) {\n const mergedOptions = { ...options, limit: options.limit ?? 5 };\n const result = await this.searchTasksByKeywords(keywords, mergedOptions);\n return result.tasks;\n }\n async findSimilarTasks(taskId, limit = 5) {\n await this.initialize();\n const taskTags = await this.getTagsForTask(taskId);\n if (taskTags.length === 0) {\n return [];\n }\n const tagIds = taskTags.map((t) => t.id);\n const placeholders = tagIds.map(() => \"?\").join(\", \");\n const sql = `\n SELECT t.*, COUNT(r2.tag_id) as match_count\n FROM task t\n INNER JOIN task_tag_relation r ON t.id = r.task_id\n INNER JOIN task_tag_relation r2 ON t.id = r2.task_id\n WHERE r.tag_id IN (${placeholders})\n AND t.id != ?\n GROUP BY t.id\n ORDER BY match_count DESC, t.updated_at DESC\n LIMIT ?\n `;\n const stmt = this.db.prepare(sql);\n const rows = stmt.all(...tagIds, taskId, limit);\n return rows.map((row) => this.rowToTask(row));\n }\n async searchTasks(query, limit = 20) {\n await this.initialize();\n const sql = `\n SELECT * FROM task \n WHERE title LIKE ? OR description LIKE ?\n ORDER BY updated_at DESC\n LIMIT ?\n `;\n const stmt = this.db.prepare(sql);\n const rows = stmt.all(`%${query}%`, `%${query}%`, limit);\n return rows.map((row) => this.rowToTask(row));\n }\n async findTasksByContextValue(value, limit = 50) {\n await this.initialize();\n if (!value)\n return [];\n const sql = `\n SELECT * FROM task\n WHERE context LIKE ?\n ORDER BY updated_at DESC\n LIMIT ?\n `;\n const rows = this.db.prepare(sql).all(`%${value}%`, limit);\n return rows.map((row) => this.rowToTask(row));\n }\n rowToTag(row) {\n return {\n id: row.id,\n name: row.name,\n createdAt: new Date(row.created_at).toISOString(),\n taskCount: row.task_count\n };\n }\n async syncTaskTagsJson(taskId) {\n const tags = await this.getTagsForTask(taskId);\n const tagNames = tags.map((t) => t.name);\n const stmt = this.db.prepare(\"UPDATE task SET tags = ? WHERE id = ?\");\n stmt.run(tagNames.length > 0 ? JSON.stringify(tagNames) : null, taskId);\n this.tasksCache.delete(taskId);\n }\n async close() {\n if (this.db) {\n this.db.close();\n this.db = null;\n this.initialized = false;\n }\n this.tasksCache.clear();\n this.operationsCache.clear();\n }\n };\n __legacyDecorateClassTS([\n TracedAs(\"task.rowToTask\", { recordParams: true, recordResult: true, log: true })\n ], SQLiteTaskStore.prototype, \"rowToTask\", null);\n __legacyDecorateClassTS([\n TracedAs(\"task.searchTasksByKeywords\", { recordParams: true, recordResult: true, log: true })\n ], SQLiteTaskStore.prototype, \"searchTasksByKeywords\", null);\n});\n\n// src/env/task/storage/index.ts\ninit_sqlite_task_store();\ninit_sqlite_task_store();\n\nexport { getDefaultDataDir, getDefaultTaskDbPath, SQLiteTaskStore };\n",
|
|
93
|
+
"import {\n init_decorator,\n wrapFunction\n} from \"./roy-agent-core-dsevjbck.js\";\nimport {\n createLogger,\n init_logger\n} from \"./roy-agent-core-8seq65bp.js\";\nimport {\n __esm\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/context/env-event.ts\nfunction isLarkEvent(event) {\n return event?.source === \"lark\";\n}\nfunction isGithubEvent(event) {\n return event?.source === \"github\";\n}\nfunction isJiraEvent(event) {\n return event?.source === \"jira\";\n}\nfunction getLarkMessageId(event) {\n if (!isLarkEvent(event))\n return;\n if (event.id)\n return event.id;\n const payload = event.payload;\n return payload?.message?.message_id ?? payload?.message_id;\n}\nfunction getLarkChatId(event) {\n if (!isLarkEvent(event))\n return;\n const payload = event.payload;\n return payload?.chat_id ?? payload?.message?.chat_id;\n}\nfunction getLarkUserId(event) {\n if (!isLarkEvent(event))\n return;\n const payload = event.payload;\n const senderId = payload?.event?.sender?.sender_id ?? payload?.sender?.sender_id ?? undefined;\n return senderId?.open_id ?? senderId?.user_id;\n}\nfunction serializeEventToEnv(event) {\n if (!event)\n return {};\n const env = {\n [`${EVENT_ENV_PREFIX}SOURCE`]: event.source,\n [`${EVENT_ENV_PREFIX}ID`]: event.id,\n [`${EVENT_ENV_PREFIX}RECEIVED_AT`]: event.receivedAt\n };\n if (event.payload !== undefined) {\n env[`${EVENT_ENV_PREFIX}PAYLOAD`] = JSON.stringify(event.payload);\n }\n if (event.metadata !== undefined) {\n env[`${EVENT_ENV_PREFIX}METADATA`] = JSON.stringify(event.metadata);\n }\n return env;\n}\nfunction restoreEventFromEnv(env = process.env) {\n const source = env[`${EVENT_ENV_PREFIX}SOURCE`];\n const id = env[`${EVENT_ENV_PREFIX}ID`];\n if (!source || !id)\n return;\n const payloadStr = env[`${EVENT_ENV_PREFIX}PAYLOAD`];\n const metadataStr = env[`${EVENT_ENV_PREFIX}METADATA`];\n let payload;\n let metadata;\n try {\n if (payloadStr)\n payload = JSON.parse(payloadStr);\n } catch {}\n try {\n if (metadataStr)\n metadata = JSON.parse(metadataStr);\n } catch {}\n return {\n source,\n id,\n receivedAt: env[`${EVENT_ENV_PREFIX}RECEIVED_AT`] ?? new Date().toISOString(),\n payload,\n metadata\n };\n}\nvar EVENT_ENV_PREFIX = \"ROY_EVENT_\";\nvar init_env_event = () => {};\n\n// src/env/context/env-context.ts\nimport { AsyncLocalStorage } from \"async_hooks\";\nfunction getEnvContext() {\n return envContextStorage.getStore();\n}\nfunction getEnvContextOrEmpty() {\n return envContextStorage.getStore() || {};\n}\nfunction hasEnvContext() {\n return envContextStorage.getStore() !== undefined;\n}\nfunction getCurrentTaskId() {\n return envContextStorage.getStore()?.agentContext?.currentTaskId;\n}\nfunction runWithEnvContext(context, fn) {\n if (context) {\n return envContextStorage.run(context, fn);\n }\n return fn();\n}\nasync function runWithEnvContextAsync(context, fn) {\n if (context) {\n return envContextStorage.run(context, fn);\n }\n return fn();\n}\nfunction normalizeParentTaskId(value) {\n return typeof value === \"number\" && Number.isInteger(value) && value > 0 ? value : undefined;\n}\nfunction createEnvContext(options) {\n let replyChannel = options.replyChannel;\n if (replyChannel && options.messageId && !replyChannel.messageId) {\n replyChannel = { ...replyChannel, messageId: options.messageId };\n }\n let event = options.event;\n if (!event && options.messageId) {\n event = {\n source: \"lark\",\n id: options.messageId,\n receivedAt: new Date().toISOString(),\n payload: undefined,\n metadata: {\n chatId: replyChannel?.chatId,\n userId: replyChannel?.userId,\n profile: replyChannel?.profile\n }\n };\n }\n return {\n envEvent: options.envEvent,\n sourceId: options.sourceId,\n userId: options.userId,\n messageId: options.messageId ?? (event?.source === \"lark\" ? event.id : undefined) ?? replyChannel?.messageId,\n event,\n traceId: options.traceId ?? crypto.randomUUID(),\n requestId: options.requestId ?? crypto.randomUUID(),\n replyChannel,\n pluginEnabled: options.pluginEnabled,\n plugins: options.plugins,\n timestamp: options.timestamp ?? Date.now(),\n parentTaskId: options.parentTaskId\n };\n}\nfunction mergeEnvContext(partial) {\n const current = envContextStorage.getStore();\n if (current) {\n if (partial.agentContext && current.agentContext) {\n Object.assign(current.agentContext, partial.agentContext);\n delete partial.agentContext;\n }\n Object.assign(current, partial);\n }\n}\nfunction getEventFromEnvContext(ctx) {\n if (!ctx)\n return;\n if (ctx.event)\n return ctx.event;\n const replyMessageId = ctx.replyChannel?.messageId;\n if (replyMessageId) {\n return {\n source: \"lark\",\n id: replyMessageId,\n receivedAt: new Date().toISOString(),\n payload: undefined,\n metadata: {\n chatId: ctx.replyChannel?.chatId,\n userId: ctx.replyChannel?.userId,\n profile: ctx.replyChannel?.profile\n }\n };\n }\n if (ctx.messageId) {\n return {\n source: \"lark\",\n id: ctx.messageId,\n receivedAt: new Date().toISOString(),\n payload: undefined\n };\n }\n return;\n}\nvar logger, envContextStorage, resolveEnvParentTaskId, setCurrentTaskId;\nvar init_env_context = __esm(() => {\n init_logger();\n init_decorator();\n init_env_event();\n logger = createLogger(\"env:context:env-context\");\n envContextStorage = new AsyncLocalStorage;\n resolveEnvParentTaskId = wrapFunction(function _resolveEnvParentTaskId(envEvent, parentEnvContext) {\n const fromEvent = normalizeParentTaskId(envEvent?.metadata?.parentTaskId);\n return fromEvent ?? normalizeParentTaskId(parentEnvContext?.parentTaskId);\n }, \"env-context.resolveEnvParentTaskId\", {\n recordParams: false,\n recordResult: false,\n log: false,\n resultFilter: (parentTaskId) => ({\n parentTaskId: parentTaskId ?? null\n })\n });\n setCurrentTaskId = wrapFunction(function _setCurrentTaskId(taskId) {\n const prev = getCurrentTaskId();\n const ctx = envContextStorage.getStore();\n if (ctx) {\n if (!ctx.agentContext) {\n ctx.agentContext = {};\n }\n ctx.agentContext.currentTaskId = taskId;\n }\n logger.info(`[setCurrentTaskId] taskId=${taskId ?? \"undefined\"} (was: ${prev ?? \"undefined\"})`);\n }, \"env-context.setCurrentTaskId\", { recordParams: true, recordResult: false, log: true });\n});\n\nexport { isLarkEvent, isGithubEvent, isJiraEvent, getLarkMessageId, getLarkChatId, getLarkUserId, EVENT_ENV_PREFIX, serializeEventToEnv, restoreEventFromEnv, init_env_event, envContextStorage, getEnvContext, getEnvContextOrEmpty, hasEnvContext, getCurrentTaskId, runWithEnvContext, runWithEnvContextAsync, normalizeParentTaskId, resolveEnvParentTaskId, createEnvContext, mergeEnvContext, setCurrentTaskId, getEventFromEnvContext, init_env_context };\n",
|
|
94
|
+
"import {\n getEnvContextOrEmpty,\n init_env_context,\n setCurrentTaskId\n} from \"./roy-agent-core-5apmk4qw.js\";\nimport {\n createLogger,\n init_logger\n} from \"./roy-agent-core-8seq65bp.js\";\n\n// src/env/task/tools/task-types.ts\nimport { z } from \"zod\";\nvar CreateTaskToolSchema = z.object({\n title: z.string().describe(\"Task title\"),\n description: z.string().optional().describe(\"Task description\"),\n priority: z.enum([\"low\", \"medium\", \"high\"]).optional().describe(\"Task priority\"),\n type: z.enum([\"normal\", \"cycle\", \"longterm\"]).optional().default(\"normal\").describe(\"Task type. normal: 常规任务,需要跟踪完成. cycle: 周期任务(如每周发周报),无需 complete,定期执行. longterm: 长期任务/愿景目标(如提升公司影响力),难以一次性完成,持续跟进\"),\n goals_and_expected_deliverables: z.string().optional().describe(\"Goals and expected deliverables\"),\n due_date: z.string().optional().describe(\"Due date (ISO format)\"),\n tags: z.array(z.string()).optional().describe(\"Task tags (for search, stored in task.tags JSON field)\"),\n project_path: z.string().describe(\"Project root path for task positioning. \" + \"Used to locate the project space for this task. \" + \"Use 'unknown' if unknown.\"),\n parent_task_id: z.union([z.number(), z.null()]).optional().describe(`父任务 ID(可选)。不传或传 null 时,创建根任务(root task)。\n` + `如需将任务挂载到某个父任务下,传入对应父任务 ID。\n` + `**调用前必须先调用 task_tree(depth=2)** 查看现有任务树结构,避免重复创建根任务、避免孤儿任务。\n` + `决策路径(按顺序匹配):\n` + ` A. 归属到现有 longterm 根(如「[Longterm] X 生态」)→ parent_task_id = 该根 ID\n` + ` B. 归属到现有主题聚类(非 longterm 根,但同主题)→ parent_task_id = 该根 ID\n` + ` C. 新建根任务 → 省略 parent_task_id(让树根 ≤10)\n` + `如何找到 parent_task_id:使用 task_tree(depth=2) 获取的树形结构,\n` + \"根据节点 id 选择合适的父任务 ID(来自 tree 输出,**不要硬编码**数字)。\"),\n context: z.string().describe(\"JSON string with time-space positioning information for task continuity. \" + \"This field is crucial for Agent task handoff. \" + \"Core fields: worktree_path (git worktree path), branch (current branch), type (feature/bug/refactor/chore). \" + 'Example for coding: {\"worktree_path\": \"/path/worktree\", \"branch\": \"feature/xyz\", \"type\": \"feature\"}. ' + 'Example for other: {\"type\": \"general\"}. ' + `If unknown, use '{}' or '{\"type\":\"unknown\"}'. ` + \"IMPORTANT: Must be a valid JSON string!\")\n});\nvar GetTaskToolSchema = z.object({\n task_id: z.number().describe(\"Task ID\"),\n include_operations: z.boolean().optional().default(false).describe(\"Include operation records\")\n});\nvar ListTasksToolSchema = z.object({\n status: z.enum([\"todo\", \"active\", \"completed\", \"paused\", \"cancelled\", \"archived\"]).optional(),\n priority: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n type: z.enum([\"normal\", \"cycle\", \"longterm\"]).optional().describe(\"Filter by task type\"),\n limit: z.number().optional().default(20),\n offset: z.number().optional().default(0),\n depth: z.number().optional().describe(\"检索层级深度:0=只根任务(无父任务),1=根+一层子任务,2=根+二层子任务,-1 或忽略=全部\"),\n include_archived: z.boolean().optional().default(false).describe(\"是否包含已归档任务(status=archived 的任务默认被排除)\")\n});\nvar SearchTasksToolSchema = z.object({\n keywords: z.array(z.string()).describe(\"关键词列表(AND 逻辑,匹配 title/description/goals/tags/operations)\"),\n limit: z.number().optional().default(20).describe(\"返回数量\"),\n offset: z.number().optional().default(0).describe(\"偏移量\"),\n status: z.enum([\"todo\", \"active\", \"completed\", \"paused\", \"cancelled\", \"archived\"]).optional().describe(\"按状态筛选\"),\n priority: z.enum([\"low\", \"medium\", \"high\"]).optional().describe(\"按优先级筛选\"),\n type: z.enum([\"normal\", \"cycle\", \"longterm\"]).optional().describe(\"按类型筛选\"),\n exclude_task_id: z.number().optional().describe(\"排除的 task ID\"),\n depth: z.number().optional().describe(\"检索层级深度:0=只根任务,1=根+一层子任务,2=根+二层子任务,-1 或忽略=全部\"),\n include_archived: z.boolean().optional().default(false).describe(\"是否包含已归档任务(status=archived 的任务默认被排除)\")\n});\nvar UpdateTaskToolSchema = z.object({\n task_id: z.number().describe(\"Task ID\"),\n title: z.string().optional(),\n description: z.string().optional(),\n status: z.enum([\"todo\", \"active\", \"completed\", \"paused\", \"cancelled\", \"archived\"]).optional(),\n priority: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n type: z.enum([\"normal\", \"cycle\", \"longterm\"]).optional().describe(\"Task type\"),\n progress: z.number().min(0).max(100).optional(),\n current_status: z.string().optional(),\n goals_and_expected_deliverables: z.string().optional(),\n due_date: z.string().optional(),\n tags: z.array(z.string()).optional(),\n project_path: z.string().optional().describe(\"Project path, identifies which project this task belongs to\"),\n context: z.string().optional().describe(\"Task context information for storing additional context\"),\n parent_task_id: z.union([z.number(), z.null()]).optional().describe(\"Parent task ID (set to null to make it a root task)\")\n});\nvar DeleteTaskToolSchema = z.object({\n task_id: z.number().describe(\"Task ID\")\n});\nvar CompleteTaskToolSchema = z.object({\n task_id: z.number().describe(\"Task ID\"),\n deliverable_storage_path: z.string().optional().describe(\"交付物的寻址地址(路径 / URL / 分支名等)。\" + \"调用本工具前,请先读取任务的 goal(description)和 delivery(goals_and_expected_deliverables)栏位,\" + \"建议验证目标和交付物是否符合预期,然后将实际交付物的寻址地址填入此参数。\")\n});\nvar BatchArchiveToolSchema = z.object({\n task_ids: z.array(z.number()).describe(\"要归档的任务 ID 列表\"),\n reason: z.string().optional().describe(\"归档原因(可选,会写入每个任务的 operation 记录)\")\n});\nvar BatchDeleteToolSchema = z.object({\n task_ids: z.array(z.number()).describe(\"要删除的任务 ID 列表\")\n});\nvar TreeTasksToolSchema = z.object({\n depth: z.number().optional().default(2).describe(\"树的展开深度。默认 2 (根 + 一层子任务 + 二层孙任务)。\" + \"0 = 只返回根任务,不展开任何子节点。\" + \"-1 或负数 = 无限层级(全部展开)。\"),\n parent_task_id: z.number().optional().describe(\"只看指定父任务的子树。不传则从所有根任务(forest)开始。\"),\n status: z.enum([\"todo\", \"active\", \"completed\", \"paused\", \"cancelled\", \"archived\"]).optional().describe(\"按状态过滤(与 task_list 一致)。\"),\n priority: z.enum([\"low\", \"medium\", \"high\"]).optional().describe(\"按优先级过滤。\"),\n type: z.enum([\"normal\", \"cycle\", \"longterm\"]).optional().describe(\"按任务类型过滤。\"),\n include_archived: z.boolean().optional().default(false).describe(\"是否包含已归档任务(默认 false,与 task_list 一致)。\")\n});\n\n// src/env/task/tools/create-tool.ts\ninit_env_context();\ninit_logger();\nimport { execSync } from \"child_process\";\n\n// src/env/task/task-child-context.ts\ninit_logger();\nvar logger = createLogger(\"task-child-context\");\nvar STRIPPED_KEYS = [\"commit\", \"token\", \"secret\", \"password\", \"api_key\"];\nfunction stripSensitiveKeys(obj) {\n if (obj === null || obj === undefined)\n return obj;\n if (Array.isArray(obj))\n return obj.map(stripSensitiveKeys);\n if (typeof obj !== \"object\")\n return obj;\n const out = {};\n for (const [k, v] of Object.entries(obj)) {\n const lower = k.toLowerCase();\n if (STRIPPED_KEYS.some((s) => lower.includes(s)))\n continue;\n out[k] = stripSensitiveKeys(v);\n }\n return out;\n}\nfunction inheritChildContext(args) {\n const { parent, overrides = {} } = args;\n const contextInherit = overrides.contextInherit !== false;\n const inheritTags = overrides.inheritTags === true;\n const project_path = overrides.projectPath ?? parent.projectPath ?? \"unknown\";\n let parentCtx = {};\n if (parent.contextJson && parent.contextJson.trim().length > 0) {\n try {\n const parsed = JSON.parse(parent.contextJson);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n parentCtx = parsed;\n }\n } catch (err) {\n logger.debug(`[task-child-context] parent #${parent.taskId} context is malformed JSON; ` + `continuing with empty inherited context (${err instanceof Error ? err.message : String(err)})`);\n parentCtx = {};\n }\n }\n const childCtx = {};\n if (contextInherit) {\n if (parentCtx.worktree_path !== undefined && overrides.worktreePath === undefined) {\n childCtx.worktree_path = parentCtx.worktree_path;\n }\n if (parentCtx.branch !== undefined && overrides.branch === undefined) {\n childCtx.branch = parentCtx.branch;\n }\n if (parentCtx.parent_branch !== undefined) {\n childCtx.parent_branch = parentCtx.parent_branch;\n }\n if (parentCtx.type !== undefined) {\n childCtx.type = parentCtx.type;\n }\n if (parentCtx.prior_context && typeof parentCtx.prior_context === \"object\") {\n const pc = parentCtx.prior_context;\n const safe = {};\n for (const [k, v] of Object.entries(pc)) {\n if (k.toLowerCase() === \"commit\")\n continue;\n safe[k] = v;\n }\n if (Object.keys(safe).length > 0) {\n childCtx.prior_context = safe;\n }\n }\n const reserved = new Set([\n \"worktree_path\",\n \"branch\",\n \"parent_branch\",\n \"type\",\n \"prior_context\",\n \"created_at\"\n ]);\n for (const [k, v] of Object.entries(parentCtx)) {\n if (reserved.has(k))\n continue;\n childCtx[k] = v;\n }\n }\n if (overrides.worktreePath !== undefined)\n childCtx.worktree_path = overrides.worktreePath;\n if (overrides.branch !== undefined)\n childCtx.branch = overrides.branch;\n const createdAt = overrides.createdAt ?? new Date().toISOString();\n childCtx.created_at = createdAt;\n childCtx.child_of = parent.taskId;\n const sanitized = stripSensitiveKeys(childCtx);\n return {\n project_path,\n context: JSON.stringify(sanitized),\n inheritedTags: inheritTags ? parent.tags ?? [] : []\n };\n}\n\n// src/env/task/tools/create-tool.ts\nvar logger2 = createLogger(\"task:tools:create\");\nfunction detectWorktree() {\n try {\n const toplevel = execSync(\"git rev-parse --show-toplevel\", {\n stdio: [\"ignore\", \"pipe\", \"ignore\"]\n }).toString().trim();\n const cwd = process.cwd();\n if (!toplevel)\n return null;\n if (cwd !== toplevel)\n return cwd;\n if (cwd.includes(\".worktrees/\") || cwd.includes(\".worktree/\")) {\n return cwd;\n }\n return null;\n } catch {\n return null;\n }\n}\nfunction createTaskTool(taskComponent) {\n return {\n name: \"task_create\",\n description: `\n Create a new task for tracking work.\n\n ## ⚠️ CALL task_tree(depth=1) BEFORE THIS TOOL\n\n Before calling \\`task_create\\`, you **MUST** first call\n \\`task_tree(depth=1)\\` to inspect the existing task hierarchy.\n This is critical because:\n\n 1. Avoid duplicating root tasks (root tasks should stay ≤ 10).\n 2. Find the right \\`parent_task_id\\` to attach under.\n 3. Avoid creating stranded/orphan tasks.\n\n Workflow:\n step 1: task_tree({depth: 1})\n step 2: read the tree, then decide per \"Decision Tree\" below\n step 3: task_create({...})\n\n ## Decision Tree — How to choose parent_task_id\n\n Walk these paths in order:\n\n **Path A — Attach under a longterm root.**\n The task belongs to a theme whose longterm root already exists\n (e.g. \"[Longterm] X ecosystem\"). Set \\`parent_task_id\\` to that\n root's id. This is the **preferred** path for incremental work\n inside an established theme.\n\n **Path B — Attach under an existing topic cluster.**\n A non-longterm root already aggregates similar tasks and yours\n belongs in the same cluster. Set \\`parent_task_id\\` to that root.\n\n **Path C — Create a new root.**\n Neither A nor B fits (cross-cutting work, or root count already\n ≥ ~10). **Omit** \\`parent_task_id\\` (or pass \\`null\\`) and the\n task becomes a new root.\n\n ## Tree Hygiene Principles\n\n Apply these when deciding parent_task_id:\n\n - Root tasks ≤ 10 (keep tree width manageable)\n - Depth ≤ 5 (avoid deep nesting)\n - Same-theme tasks cluster under one parent\n - Long-tail/stranded tasks should be archived or merged\n\n ## ⚠️ Spatial + Temporal Context (Task #2325)\n\n A task MUST carry spatio-temporal context so it survives task-handoff\n across Agent sessions, worktrees and time. Two orthogonal axes:\n\n - **Space (project_path + worktree_path)**:\n - \\`project_path\\` (required): git repo root path (always the top-level repo)\n - \\`worktree_path\\` (in context): current worktree path if in a worktree\n - **Auto-detected by createTask** via \\`git rev-parse --show-toplevel\\`\n — you don't need to fill it manually (see \"worktree_path detection\n logic\" in the implementation).\n - You may **override** by passing it in \\`context.worktree_path\\`.\n\n - **Time (context field)**:\n - \\`created_at\\` (in context): ISO 8601 timestamp **auto-injected**\n at creation time. Manual override is preserved if provided.\n - \\`time_dimension\\` (in context, optional): the task's \"time anchor\"\n — e.g. a release tag, sprint window or iteration id.\n - \\`work_period\\` (in context, optional): planned start/end dates\n if known.\n - \\`prior_context\\` (in context, optional): the previous task id\n / commit hash this work continues from. Helps the next Agent\n pick up the trail via \\`task_get\\`.\n\n Example context for code development task:\n\n \\`\\`\\`json\n {\"project_path\": \"<git-repo-root>\",\n \"worktree_path\": \"<git-repo-root>/.worktrees/<branch-name>\",\n \"branch\": \"feat/<branch-name>\",\n \"type\": \"feature\",\n \"parent_branch\": \"main\",\n \"created_at\": \"<ISO-8601-timestamp>\",\n \"prior_context\": {\"prev_task\": \"<task-id>\", \"commit\": \"<commit-hash>\"}}\n \\`\\`\\`\n\n ## IMPORTANT: Task Continuity Fields\n\n This tool creates persistent task records that can be picked up by a\n Task Manager Agent to continue advancing unfinished work.\n\n The following fields are critical for task context preservation:\n\n - project_path: The project root path where this task belongs.\n Used to locate the project space for this task.\n If unknown, use 'unknown'.\n\n - context: A JSON string containing time-space positioning information.\n This field is crucial for Agent task handoff.\n\n **Required format**: Valid JSON string (parseable).\n\n **Core fields**:\n - worktree_path: Git worktree path (for code development). Auto-detected.\n - branch: Current branch name\n - type: Work type classification (feature/bug/refactor/chore).\n ⚠️ NOTE: This is the **context.type** (work classification), NOT the\n task's type field (normal/cycle/longterm). They are independent concepts.\n - created_at: ISO 8601 timestamp. Auto-injected if missing.\n\n **Example for coding tasks**:\n {\"worktree_path\": \"<worktree-path>\", \"branch\": \"<branch-name>\", \"type\": \"feature\", \"parent_branch\": \"main\"}\n\n **Example for other tasks**:\n {\"type\": \"general\"}\n\n If unable to fill in details, use at minimum:\n {\"type\": \"unknown\"}\n\n **DO NOT leave this as plain text** - it must be valid JSON!\n\n **Note**: malformed JSON (non-parseable) will be preserved as-is\n rather than rejected, to preserve backward compatibility. The\n auto-injection of \\`created_at\\` / \\`worktree_path\\` is best-effort.\n\n ## Task Binding Inheritance (Task #4023)\n\n When this tool is called from inside a per-task group chat, the\n event-source handler resolves the chat↔task binding and injects the\n bound task id into \\`EnvContext.parentTaskId\\`. This tool reads that\n value and uses it as the default \\`parent_task_id\\`, so the LLM\n doesn't need to know the task tree to attach subtasks to the\n correct parent.\n\n Priority order (highest → lowest):\n 1. Caller's explicit \\`parent_task_id\\` (always wins)\n 2. \\`EnvContext.parentTaskId\\` injected from chat binding\n 3. No parent (creates a root task, as before)\n\n When the env-injected parent doesn't exist in the DB, the tool\n fails fast (does not silently create an orphan). When the\n env-injected value is 0 / negative / non-integer, it's treated as\n missing — only positive integers are honored.\n\n `,\n parameters: CreateTaskToolSchema,\n execute: async (args, ctx) => {\n const params = CreateTaskToolSchema.parse(args);\n const sessionId = ctx.session_id || \"unknown\";\n const detectedWorktree = detectWorktree();\n let enrichedContext = params.context;\n const envParentTaskId = getEnvContextOrEmpty().parentTaskId;\n const effectiveParentTaskId = params.parent_task_id !== undefined && params.parent_task_id !== null ? params.parent_task_id : envParentTaskId !== undefined && envParentTaskId !== null && Number.isInteger(envParentTaskId) && envParentTaskId > 0 ? envParentTaskId : undefined;\n let inheritedProjectPath = params.project_path && params.project_path.trim() !== \"\" ? params.project_path : undefined;\n let inheritedTags = params.tags;\n let inheritedContext;\n if (effectiveParentTaskId !== undefined) {\n try {\n const parent = await taskComponent.getTask(effectiveParentTaskId);\n if (parent) {\n const inherited = inheritChildContext({\n parent: {\n taskId: parent.id,\n projectPath: parent.project_path,\n contextJson: parent.context ?? \"\",\n tags: parent.tags\n },\n overrides: {\n projectPath: inheritedProjectPath,\n branch: undefined,\n worktreePath: undefined,\n inheritTags: params.tags === undefined,\n contextInherit: true\n }\n });\n if (inheritedProjectPath === undefined) {\n inheritedProjectPath = inherited.project_path;\n }\n if (params.tags === undefined)\n inheritedTags = inherited.inheritedTags;\n inheritedContext = inherited.context;\n }\n } catch (err) {\n logger2.debug(`[task_create] failed to pre-load parent #${effectiveParentTaskId} for context inheritance: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n try {\n const ctxObj = params.context ? JSON.parse(params.context) : {};\n const obj = typeof ctxObj === \"object\" && ctxObj !== null && !Array.isArray(ctxObj) ? ctxObj : {};\n if (inheritedContext) {\n try {\n const inheritedObj = JSON.parse(inheritedContext);\n if (inheritedObj && typeof inheritedObj === \"object\" && !Array.isArray(inheritedObj)) {\n for (const [k, v] of Object.entries(inheritedObj)) {\n if (obj[k] === undefined)\n obj[k] = v;\n }\n }\n } catch {}\n }\n if (!obj.created_at) {\n obj.created_at = new Date().toISOString();\n }\n if (!obj.worktree_path && detectedWorktree) {\n obj.worktree_path = detectedWorktree;\n }\n enrichedContext = JSON.stringify(obj);\n } catch {\n enrichedContext = params.context;\n }\n try {\n const task = await taskComponent.createTask({\n parent_task_id: effectiveParentTaskId,\n title: params.title,\n description: params.description,\n priority: params.priority,\n type: params.type || \"normal\",\n goals_and_expected_deliverables: params.goals_and_expected_deliverables,\n due_date: params.due_date,\n tags: inheritedTags,\n sessionId,\n project_path: inheritedProjectPath ?? params.project_path,\n context: enrichedContext\n });\n setCurrentTaskId(task.id);\n logger2.info(`[createTask] Trace: Task #${task.id} created, currentTaskId=${task.id} set in EnvContext`);\n return {\n success: true,\n output: `Task created successfully: #${task.id} - ${task.title}`,\n metadata: {\n execution_time_ms: 0,\n task_id: task.id,\n status: task.status,\n createdAt: task.createdAt\n }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\n// src/env/task/tools/get-tool.ts\nfunction getTaskTool(taskComponent) {\n return {\n name: \"task_get\",\n description: \"Get task details by ID. Optionally include operation records.\",\n parameters: GetTaskToolSchema,\n execute: async (args, ctx) => {\n const params = GetTaskToolSchema.parse(args);\n try {\n if (params.include_operations) {\n const result = await taskComponent.getTaskWithOperations(params.task_id);\n if (!result) {\n return {\n success: false,\n output: \"\",\n error: `Task not found: ${params.task_id}`,\n metadata: { execution_time_ms: 0 }\n };\n }\n return {\n success: true,\n output: JSON.stringify(result, null, 2),\n metadata: { execution_time_ms: 0 }\n };\n } else {\n const task = await taskComponent.getTask(params.task_id);\n if (!task) {\n return {\n success: false,\n output: \"\",\n error: `Task not found: ${params.task_id}`,\n metadata: { execution_time_ms: 0 }\n };\n }\n return {\n success: true,\n output: JSON.stringify(task, null, 2),\n metadata: { execution_time_ms: 0 }\n };\n }\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\n// src/env/task/tools/list-tool.ts\nfunction listTasksTool(taskComponent) {\n return {\n name: \"task_list\",\n description: \"List tasks with optional filters for status, priority, type, parent_task_id, \" + \"and depth (hierarchy level). \" + `depth: 0=只根任务(无父任务),1=根+一层子任务,2=根+二层子任务,-1 或忽略=全部。\n` + `Returns { total, count, truncated, limit, offset, depth, tasks } where:\n` + ` - total: count of all matching tasks BEFORE pagination\n` + \" - count: count of tasks in the returned `tasks` array (after pagination)\\n\" + ` - truncated: true when total > count (data was truncated by pagination)\n` + \"Note: `total` is the FIRST field in the response so it survives tail-truncation \" + \"by ToolComponent.truncateOutput.\",\n parameters: ListTasksToolSchema,\n execute: async (args, ctx) => {\n const params = ListTasksToolSchema.parse(args);\n try {\n const result = await taskComponent.listTasks({\n status: params.status,\n priority: params.priority,\n type: params.type,\n limit: params.limit,\n offset: params.offset,\n depth: params.depth,\n include_archived: params.include_archived\n });\n return {\n success: true,\n output: JSON.stringify({\n total: result.total,\n count: result.tasks.length,\n truncated: result.total > result.tasks.length,\n limit: params.limit,\n offset: params.offset,\n depth: params.depth,\n tasks: result.tasks\n }),\n metadata: { execution_time_ms: 0 }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\n// src/env/task/tools/search-tool.ts\nfunction searchTasksTool(taskComponent) {\n return {\n name: \"task_search\",\n description: \"Search tasks by keywords across title, description, goals, tags, and \" + \"operation records. Use this when you need to find tasks related to a \" + \"topic, feature, bug, or area of work — even when the keyword is only \" + `in description / goals / tags / past operation logs.\n\n` + `Returns { tasks, total, limit, offset } so you can paginate large result sets.\n\n` + \"If `keywords` is empty, returns no results.\",\n parameters: SearchTasksToolSchema,\n execute: async (args, ctx) => {\n const params = SearchTasksToolSchema.parse(args);\n try {\n const result = await taskComponent.searchTasksByKeywords(params.keywords, {\n limit: params.limit,\n offset: params.offset,\n excludeTaskId: params.exclude_task_id,\n status: params.status,\n priority: params.priority,\n type: params.type,\n depth: params.depth,\n include_archived: params.include_archived\n });\n return {\n success: true,\n output: JSON.stringify({\n tasks: result.tasks,\n total: result.total,\n limit: params.limit,\n offset: params.offset\n }),\n metadata: { execution_time_ms: 0 }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\n// src/env/task/tools/batch-archive-tool.ts\nfunction batchArchiveTaskTool(taskComponent) {\n return {\n name: \"task_batch_archive\",\n description: \"Batch archive multiple tasks at once. Sets all specified tasks to \" + `'archived' status and creates operation records for each.\n\n` + \"Use this when you need to quickly archive a group of completed, \" + `obsolete, or historical tasks (e.g., during task organization).\n\n` + \"Returns summary of how many tasks were successfully archived \" + \"and any errors encountered.\",\n parameters: BatchArchiveToolSchema,\n execute: async (args, ctx) => {\n const params = BatchArchiveToolSchema.parse(args);\n const taskIds = params.task_ids;\n const sessionId = ctx.session_id || \"batch-archive\";\n if (!taskIds || taskIds.length === 0) {\n return {\n success: true,\n output: JSON.stringify({ archived_count: 0, errors: [] }),\n metadata: { execution_time_ms: 0 }\n };\n }\n const results = [];\n let archivedCount = 0;\n for (const taskId of taskIds) {\n try {\n const task = await taskComponent.updateTask(taskId, { status: \"archived\" });\n if (task) {\n await taskComponent.createOperation({\n taskId,\n sessionId,\n actionType: \"completed\",\n actionTitle: \"Batch archived\",\n actionDescription: params.reason || \"批量归档(任务整理)\"\n });\n archivedCount++;\n results.push({ id: taskId, success: true });\n } else {\n results.push({ id: taskId, success: false, error: \"Task not found\" });\n }\n } catch (error) {\n results.push({\n id: taskId,\n success: false,\n error: error instanceof Error ? error.message : String(error)\n });\n }\n }\n const hasErrors = results.some((r) => !r.success);\n return {\n success: !hasErrors,\n output: JSON.stringify({\n archived_count: archivedCount,\n total: taskIds.length,\n errors: results.filter((r) => !r.success).map((r) => ({ id: r.id, error: r.error })),\n results\n }, null, 2),\n metadata: { execution_time_ms: 0 }\n };\n }\n };\n}\n// src/env/task/tools/batch-delete-tool.ts\nfunction batchDeleteTaskTool(taskComponent) {\n return {\n name: \"task_batch_delete\",\n description: \"Batch delete multiple tasks at once. Deletes each task and all its \" + `operation records.\n\n` + \"Use this when you need to quickly remove a group of test, temporary, \" + `or otherwise worthless tasks (e.g., during task organization).\n\n` + \"Returns summary of how many tasks were successfully deleted \" + \"and any errors encountered.\",\n parameters: BatchDeleteToolSchema,\n execute: async (args, ctx) => {\n const params = BatchDeleteToolSchema.parse(args);\n const taskIds = params.task_ids;\n if (!taskIds || taskIds.length === 0) {\n return {\n success: true,\n output: JSON.stringify({ deleted_count: 0, errors: [] }),\n metadata: { execution_time_ms: 0 }\n };\n }\n const results = [];\n let deletedCount = 0;\n for (const taskId of taskIds) {\n try {\n const deleted = await taskComponent.deleteTask(taskId);\n if (deleted) {\n deletedCount++;\n results.push({ id: taskId, success: true });\n } else {\n results.push({ id: taskId, success: false, error: \"Task not found\" });\n }\n } catch (error) {\n results.push({\n id: taskId,\n success: false,\n error: error instanceof Error ? error.message : String(error)\n });\n }\n }\n const hasErrors = results.some((r) => !r.success);\n return {\n success: !hasErrors,\n output: JSON.stringify({\n deleted_count: deletedCount,\n total: taskIds.length,\n errors: results.filter((r) => !r.success).map((r) => ({ id: r.id, error: r.error })),\n results\n }, null, 2),\n metadata: { execution_time_ms: 0 }\n };\n }\n };\n}\n// src/env/task/tools/update-tool.ts\ninit_env_context();\ninit_logger();\nvar logger3 = createLogger(\"tool:update-task\");\nasync function detectCycle(taskComponent, taskId, newParentId) {\n const visited = new Set;\n let currentId = newParentId;\n while (currentId !== null && currentId !== undefined) {\n if (currentId === taskId)\n return true;\n if (visited.has(currentId))\n break;\n visited.add(currentId);\n const currentTask = await taskComponent.getTask(currentId);\n if (!currentTask)\n break;\n currentId = currentTask.parent_task_id;\n }\n return false;\n}\nfunction updateTaskTool(taskComponent) {\n return {\n name: \"task_update\",\n description: \"Update an existing task's properties. Status and progress changes will create operation records.\",\n parameters: UpdateTaskToolSchema,\n execute: async (args, ctx) => {\n const params = UpdateTaskToolSchema.parse(args);\n const sessionId = ctx.session_id || \"unknown\";\n try {\n if (params.parent_task_id !== undefined && params.parent_task_id !== null) {\n const hasCycle = await detectCycle(taskComponent, params.task_id, params.parent_task_id);\n if (hasCycle) {\n return {\n success: false,\n output: \"\",\n error: `Circular reference detected: setting parent_task_id to ${params.parent_task_id} for task #${params.task_id} would create a cycle`,\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n const task = await taskComponent.updateTask(params.task_id, {\n title: params.title,\n description: params.description,\n status: params.status,\n priority: params.priority,\n type: params.type,\n progress: params.progress,\n current_status: params.current_status,\n goals_and_expected_deliverables: params.goals_and_expected_deliverables,\n due_date: params.due_date,\n tags: params.tags,\n project_path: params.project_path,\n context: params.context,\n parent_task_id: params.parent_task_id\n });\n if (!task) {\n return {\n success: false,\n output: \"\",\n error: `Task not found: ${params.task_id}`,\n metadata: { execution_time_ms: 0 }\n };\n }\n if (params.status || params.progress !== undefined || params.current_status) {\n await taskComponent.createOperation({\n taskId: params.task_id,\n sessionId,\n actionType: \"progress\",\n actionTitle: params.current_status || `Updated: ${params.status || `${params.progress}%`}`,\n actionDescription: JSON.stringify({\n status: params.status,\n progress: params.progress,\n current_status: params.current_status\n })\n });\n }\n setCurrentTaskId(task.id);\n logger3.info(`[updateTask] Trace: Task #${task.id} updated, currentTaskId=${task.id} set in EnvContext`);\n return {\n success: true,\n output: `Task updated: #${task.id} - ${task.title}`,\n metadata: { execution_time_ms: 0, task }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\n// src/env/task/tools/delete-tool.ts\nfunction deleteTaskTool(taskComponent) {\n return {\n name: \"task_delete\",\n description: \"Delete a task and all its operation records.\",\n parameters: DeleteTaskToolSchema,\n execute: async (args, ctx) => {\n const params = DeleteTaskToolSchema.parse(args);\n try {\n const deleted = await taskComponent.deleteTask(params.task_id);\n if (!deleted) {\n return {\n success: false,\n output: \"\",\n error: `Task not found: ${params.task_id}`,\n metadata: { execution_time_ms: 0 }\n };\n }\n return {\n success: true,\n output: `Task deleted: #${params.task_id}`,\n metadata: { execution_time_ms: 0 }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\n// src/env/task/tools/complete-tool.ts\ninit_env_context();\ninit_logger();\nvar logger4 = createLogger(\"task:tools:complete\");\nvar TASK_COMPLETE_DESCRIPTION = `\nMark a task as completed (progress=100, status=completed). Creates an operation record.\n\n**Before calling this tool**, you MUST:\n\n1. Read the task's \\`goal\\` (description) and \\`delivery\\` (goals_and_expected_deliverables) fields.\n - Use \\`task_get(task_id=<id>)\\` to fetch the full task record.\n2. **Validate** whether the goal and delivery match what you actually delivered.\n - If mismatch, either: (a) extend the task via \\`task_update\\`, or (b) honestly note the discrepancy in your final report.\n3. **Provide \\`deliverable_storage_path\\`** parameter with the deliverable's address:\n - Feishu doc URL (e.g., https://my.feishu.cn/docx/abc)\n - Local file path (e.g., /tmp/report.md)\n - Git branch or worktree path (e.g., feature/my-feature)\n - GitHub commit URL or PR URL\n - Cloud drive URL (e.g., https://my.feishu.cn/file/abc)\n - Or any other locator that points to where the work product lives\n\nThe \\`deliverable_storage_path\\` will be persisted to the task's \\`context.deliverable_storage_path\\` for future reference and traceability.\n\n**Restrictions**:\n- Cannot complete cycle-type tasks (they are periodic). Use \\`task_update\\` to reset progress instead.\n- Marks the task as 100% complete; use \\`task_update\\` to record partial progress first if needed.\n\n**Backward compatibility**: \\`deliverable_storage_path\\` is optional. Existing callers that omit it continue to work as before.\n`.trim();\nfunction completeTaskTool(taskComponent) {\n return {\n name: \"task_complete\",\n description: TASK_COMPLETE_DESCRIPTION,\n parameters: CompleteTaskToolSchema,\n execute: async (args, ctx) => {\n const params = CompleteTaskToolSchema.parse(args);\n const sessionId = ctx.session_id || \"unknown\";\n try {\n const currentTask = await taskComponent.getTask(params.task_id);\n if (!currentTask) {\n return {\n success: false,\n output: \"\",\n error: `Task not found: ${params.task_id}`,\n metadata: { execution_time_ms: 0 }\n };\n }\n if (currentTask.type === \"cycle\") {\n return {\n success: false,\n output: \"\",\n error: `Cannot complete a cycle-type task (id: ${params.task_id}). Cycle tasks are periodic (e.g., weekly reports) and should not be marked as completed. Use task_update to reset progress instead.`,\n metadata: { execution_time_ms: 0 }\n };\n }\n const task = await taskComponent.completeTask(params.task_id, sessionId, params.deliverable_storage_path);\n if (!task) {\n return {\n success: false,\n output: \"\",\n error: `Task not found: ${params.task_id}`,\n metadata: { execution_time_ms: 0 }\n };\n }\n setCurrentTaskId(undefined);\n logger4.info(`[completeTask] Trace: Task #${params.task_id} completed, deliverable=${params.deliverable_storage_path || \"(none)\"}, currentTaskId cleared from EnvContext`);\n return {\n success: true,\n output: params.deliverable_storage_path ? `Task completed: #${task.id} - ${task.title}\nDeliverable (context + operation): ${params.deliverable_storage_path}` : `Task completed: #${task.id} - ${task.title}\nDeliverable: (no path provided)`,\n metadata: { execution_time_ms: 0, task }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\n// src/env/task/tools/task-tree-tool.ts\nfunction compareTasksDesc(a, b) {\n if (a.updatedAt < b.updatedAt)\n return 1;\n if (a.updatedAt > b.updatedAt)\n return -1;\n if (a.id < b.id)\n return 1;\n if (a.id > b.id)\n return -1;\n return 0;\n}\nfunction trimToDepth(nodes, depth) {\n if (depth < 0)\n return nodes;\n if (depth === 0) {\n return nodes.map((n) => ({ ...n, children: [] }));\n }\n return nodes.map((n) => ({\n ...n,\n children: trimToDepth(n.children, depth - 1)\n }));\n}\nfunction countNodes(nodes) {\n let n = 0;\n for (const node of nodes)\n n += 1 + countNodes(node.children);\n return n;\n}\nfunction buildTaskNodes(tasks) {\n const nodeById = new Map;\n const byParent = new Map;\n const roots = [];\n for (const t of tasks) {\n nodeById.set(t.id, {\n id: t.id,\n title: t.title,\n status: t.status,\n type: t.type,\n priority: t.priority,\n progress: t.progress,\n children: []\n });\n }\n for (const t of tasks) {\n const pid = t.parent_task_id;\n if (pid !== undefined && pid !== null && nodeById.has(pid)) {\n const list = byParent.get(pid) || [];\n list.push(t);\n byParent.set(pid, list);\n } else {\n roots.push(t);\n }\n }\n for (const [parentId, children] of byParent.entries()) {\n const parentNode = nodeById.get(parentId);\n children.sort(compareTasksDesc);\n parentNode.children = children.map((c) => nodeById.get(c.id));\n }\n roots.sort(compareTasksDesc);\n return roots.map((r) => nodeById.get(r.id));\n}\nfunction treeTasksTool(taskComponent) {\n return {\n name: \"task_tree\",\n description: \"View the task tree (forest) with optional filters. \" + \"Use this BEFORE task_create to decide whether to create a root task \" + \"(omit parent_task_id) or attach to an existing parent. \" + \"depth: 0=只根任务, 1=根+一层子任务, 2=根+二层子任务 (default), \" + \"-1 or omitted as -1=无限层级. \" + `Returns { total, truncated, depth, parent_task_id, nodes } where:\n` + ` - total: count of ALL tasks in the returned tree (incl. descendants)\n` + ` - truncated: always false for now (no pagination cap on tree)\n` + ` - depth: the resolved depth value\n` + ` - parent_task_id: the root's id, or null for forest mode\n` + ` - nodes: TaskNode[] with { id, title, status, type, priority, progress, children }\n` + \"Note: `total` is the FIRST field in the response so it survives \" + \"tail-truncation by ToolComponent.truncateOutput.\",\n parameters: TreeTasksToolSchema,\n execute: async (args, _ctx) => {\n const params = TreeTasksToolSchema.parse(args);\n try {\n let flat = [];\n let parent_task_id = params.parent_task_id ?? null;\n if (params.parent_task_id !== undefined && params.parent_task_id !== null) {\n const root = await taskComponent.getTask(params.parent_task_id);\n if (!root) {\n flat = [];\n } else {\n const descendants = await taskComponent.getTaskTree(params.parent_task_id, params.depth === -1 ? -1 : Math.max(0, params.depth - 1));\n flat = [root, ...descendants];\n }\n } else {\n const result = await taskComponent.listTasks({\n status: params.status,\n priority: params.priority,\n type: params.type,\n include_archived: params.include_archived,\n limit: 9999,\n offset: 0\n });\n flat = result.tasks;\n }\n if (params.parent_task_id !== undefined && params.parent_task_id !== null) {\n if (params.status) {\n flat = flat.filter((t) => t.status === params.status);\n }\n if (params.priority) {\n flat = flat.filter((t) => t.priority === params.priority);\n }\n if (params.type) {\n flat = flat.filter((t) => t.type === params.type);\n }\n if (!params.include_archived) {\n flat = flat.filter((t) => t.status !== \"archived\");\n }\n }\n let nodes = buildTaskNodes(flat);\n if (params.parent_task_id === undefined || params.parent_task_id === null) {\n nodes = trimToDepth(nodes, params.depth);\n }\n const total = countNodes(nodes);\n return {\n success: true,\n output: JSON.stringify({\n total,\n truncated: false,\n depth: params.depth,\n parent_task_id,\n nodes\n }),\n metadata: { execution_time_ms: 0 }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\nexport { createTaskTool, getTaskTool, listTasksTool, searchTasksTool, batchArchiveTaskTool, batchDeleteTaskTool, updateTaskTool, deleteTaskTool, completeTaskTool, treeTasksTool };\n",
|
|
95
|
+
"// src/env/task/tools/operation/create-tool.ts\nimport { ZodError } from \"zod\";\n\n// src/env/task/tools/operation/operation-types.ts\nimport { z } from \"zod\";\nvar ActionTypeEnum = z.enum([\n \"create\",\n \"progress\",\n \"milestone\",\n \"problem\",\n \"solution\",\n \"decision\",\n \"review\",\n \"completed\",\n \"workflow_extracted\"\n]);\nvar PROCESS_DESCRIPTION_MIN_LENGTH = 100;\nvar PROCESS_DESCRIPTION_MAX_LENGTH = 150;\nvar MILESTONE_DESCRIPTION_MAX_LENGTH = 5000;\nvar MILESTONE_TITLE_MIN_LENGTH = 1;\nvar MILESTONE_TITLE_MAX_LENGTH = 200;\nvar ProcessDescriptionSchema = z.string().min(PROCESS_DESCRIPTION_MIN_LENGTH, {\n message: `process_description 太短(少于 ${PROCESS_DESCRIPTION_MIN_LENGTH} 字符),无法表达过程概要;如无过程信息请省略该字段,细节请回查 sessionId。`\n}).max(PROCESS_DESCRIPTION_MAX_LENGTH, {\n message: `process_description 太长(超过 ${PROCESS_DESCRIPTION_MAX_LENGTH} 字符),会退化为日志细节;操作记录只承担 milestone 概要,完整细节请通过 sessionId 回查 session。`\n}).describe(\"过程概要(process_description):采取的策略 + 工具步骤概要;\" + `严格控制 ${PROCESS_DESCRIPTION_MIN_LENGTH}-${PROCESS_DESCRIPTION_MAX_LENGTH} 字符。` + \"操作记录是节点阶段 milestone 摘要,完整过程通过 sessionId 回查 session;\" + \"milestone_description 才是达成的状态/结果描述。\");\nvar MilestoneTitleSchema = z.string().min(MILESTONE_TITLE_MIN_LENGTH, { message: \"milestone_title 不能为空\" }).max(MILESTONE_TITLE_MAX_LENGTH, {\n message: `milestone_title 超过 ${MILESTONE_TITLE_MAX_LENGTH} 字符,建议精简(一行标题即可)。`\n}).describe(\"里程碑标题(milestone_title):达成的里程碑/状态的一句话标题;\" + \"必填,1-200 字符。\");\nvar MilestoneDescriptionSchema = z.string().max(MILESTONE_DESCRIPTION_MAX_LENGTH, {\n message: `milestone_description 超过 ${MILESTONE_DESCRIPTION_MAX_LENGTH} 字符;如需更详细的过程,请改用 process_description。`\n}).optional().describe(\"状态/结果描述(milestone_description):达成的状态或结果描述;\" + \"可长可短;过程概要应放在 process_description,不要与本字段重复。\");\nvar CreateOperationInputSchema = z.object({\n task_id: z.number().describe(\"Task ID\"),\n milestone_type: ActionTypeEnum.optional(),\n milestone_title: MilestoneTitleSchema.optional(),\n milestone_description: MilestoneDescriptionSchema,\n process_description: ProcessDescriptionSchema.optional(),\n action_type: ActionTypeEnum.optional(),\n action_title: z.string().min(1).max(MILESTONE_TITLE_MAX_LENGTH).optional(),\n action_description: z.string().max(MILESTONE_DESCRIPTION_MAX_LENGTH).optional(),\n md_path: z.string().optional().describe(\"Path to detailed markdown documentation\")\n});\nvar CreateOperationToolSchema = CreateOperationInputSchema.transform((input) => {\n const deprecatedFields = [];\n let milestoneType = input.milestone_type;\n let milestoneTitle = input.milestone_title;\n let milestoneDescription = input.milestone_description;\n if (!milestoneType && input.action_type) {\n milestoneType = input.action_type;\n deprecatedFields.push(\"action_type\");\n }\n if (!milestoneTitle && input.action_title) {\n milestoneTitle = input.action_title;\n deprecatedFields.push(\"action_title\");\n }\n if (milestoneDescription === undefined && input.action_description !== undefined) {\n milestoneDescription = input.action_description;\n deprecatedFields.push(\"action_description\");\n }\n return {\n task_id: input.task_id,\n milestone_type: milestoneType,\n milestone_title: milestoneTitle,\n milestone_description: milestoneDescription,\n process_description: input.process_description,\n md_path: input.md_path,\n _deprecated_fields_used: deprecatedFields\n };\n});\nvar GetOperationToolSchema = z.object({\n operation_id: z.number().describe(\"Operation ID\")\n});\nvar ListOperationsToolSchema = z.object({\n task_id: z.number().describe(\"Task ID\"),\n milestone_type: ActionTypeEnum.optional(),\n action_type: ActionTypeEnum.optional(),\n limit: z.number().optional().default(20),\n offset: z.number().optional().default(0)\n}).transform((input) => {\n const deprecatedFields = [];\n let milestoneType = input.milestone_type;\n if (!milestoneType && input.action_type) {\n milestoneType = input.action_type;\n deprecatedFields.push(\"action_type\");\n }\n return {\n task_id: input.task_id,\n milestone_type: milestoneType,\n limit: input.limit,\n offset: input.offset,\n _deprecated_fields_used: deprecatedFields\n };\n});\nvar UpdateOperationInputSchema = z.object({\n operation_id: z.number().describe(\"Operation ID\"),\n milestone_title: MilestoneTitleSchema.optional(),\n milestone_description: MilestoneDescriptionSchema,\n process_description: ProcessDescriptionSchema.optional(),\n action_title: z.string().min(1).max(MILESTONE_TITLE_MAX_LENGTH).optional(),\n action_description: z.string().max(MILESTONE_DESCRIPTION_MAX_LENGTH).optional()\n});\nvar UpdateOperationToolSchema = UpdateOperationInputSchema.transform((input) => {\n const deprecatedFields = [];\n let milestoneTitle = input.milestone_title;\n let milestoneDescription = input.milestone_description;\n if (!milestoneTitle && input.action_title) {\n milestoneTitle = input.action_title;\n deprecatedFields.push(\"action_title\");\n }\n if (milestoneDescription === undefined && input.action_description !== undefined) {\n milestoneDescription = input.action_description;\n deprecatedFields.push(\"action_description\");\n }\n return {\n operation_id: input.operation_id,\n milestone_title: milestoneTitle,\n milestone_description: milestoneDescription,\n process_description: input.process_description,\n _deprecated_fields_used: deprecatedFields\n };\n});\nvar DeleteOperationToolSchema = z.object({\n operation_id: z.number().describe(\"Operation ID\")\n});\n\n// src/env/task/tools/operation/create-tool.ts\nfunction formatZodError(err) {\n const parts = err.issues.map((i) => `${i.path.join(\".\") || \"<root>\"}: ${i.message}`);\n return `Invalid parameters: ${parts.join(\"; \")}`;\n}\nfunction ensureRequiredMilestoneFields(params) {\n if (!params.milestone_type) {\n return {\n ok: false,\n error: \"milestone_type is required (or action_type for backward compatibility). \" + \"Use one of: create, progress, milestone, problem, solution, decision, review, completed, workflow_extracted.\"\n };\n }\n if (!params.milestone_title) {\n return {\n ok: false,\n error: \"milestone_title is required (or action_title for backward compatibility).\"\n };\n }\n return { ok: true, milestoneType: params.milestone_type, milestoneTitle: params.milestone_title };\n}\nfunction createOperationTool(taskComponent) {\n return {\n name: \"task_operation_create\",\n description: \"Create an operation record for a task. Tracks milestones (state/result) and process (strategy + tool steps). \" + \"Dual-dimension schema: milestone_type/title/description captures WHAT milestone was reached; \" + \"process_description (100-150 chars) captures HOW. \" + \"Legacy action_* fields are accepted as deprecated aliases.\",\n parameters: CreateOperationToolSchema,\n execute: async (args, ctx) => {\n let params;\n try {\n const parsed = CreateOperationToolSchema.parse(args);\n params = parsed;\n } catch (e) {\n if (e instanceof ZodError) {\n return {\n success: false,\n output: \"\",\n error: formatZodError(e),\n metadata: { execution_time_ms: 0 }\n };\n }\n throw e;\n }\n const check = ensureRequiredMilestoneFields(params);\n if (!check.ok) {\n return {\n success: false,\n output: \"\",\n error: check.error,\n metadata: { execution_time_ms: 0 }\n };\n }\n const sessionId = ctx.session_id || \"unknown\";\n try {\n const operation = await taskComponent.createOperation({\n taskId: params.task_id,\n sessionId,\n milestoneType: check.milestoneType,\n milestoneTitle: check.milestoneTitle,\n milestoneDescription: params.milestone_description,\n processDescription: params.process_description,\n mdPath: params.md_path\n });\n let output = `Operation created: #${operation.id} for task #${operation.taskId} ` + `[milestone=${operation.milestoneType}] ${operation.milestoneTitle}`;\n const deprecationWarnings = [];\n if (params._deprecated_fields_used.length > 0) {\n deprecationWarnings.push(`⚠️ DEPRECATION NOTICE: 你使用了旧的 action_* 字段 (${params._deprecated_fields_used.join(\", \")}),已自动映射到 milestone_* 字段。` + \"请尽快迁移到 milestone_type / milestone_title / milestone_description 主字段。\");\n }\n if (deprecationWarnings.length > 0) {\n output += `\n\n` + deprecationWarnings.join(`\n`);\n }\n return {\n success: true,\n output,\n metadata: {\n execution_time_ms: 0,\n operation_id: operation.id,\n task_id: operation.taskId,\n session_id: operation.sessionId,\n deprecated_fields_used: params._deprecated_fields_used\n }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\n// src/env/task/tools/operation/get-tool.ts\nfunction getOperationTool(taskComponent) {\n return {\n name: \"task_operation_get\",\n description: \"Get a single operation record by ID.\",\n parameters: GetOperationToolSchema,\n execute: async (args, ctx) => {\n const params = GetOperationToolSchema.parse(args);\n try {\n const operation = await taskComponent.getOperation(params.operation_id);\n if (!operation) {\n return {\n success: false,\n output: \"\",\n error: `Operation not found: ${params.operation_id}`,\n metadata: { execution_time_ms: 0 }\n };\n }\n return {\n success: true,\n output: JSON.stringify(operation, null, 2),\n metadata: { execution_time_ms: 0 }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\n// src/env/task/tools/operation/list-tool.ts\nfunction listOperationsTool(taskComponent) {\n return {\n name: \"task_operation_list\",\n description: \"List operation records for a task with optional filters. \" + \"Use milestone_type (canonical) or action_type (deprecated, auto-mapped).\",\n parameters: ListOperationsToolSchema,\n execute: async (args, ctx) => {\n const parsed = ListOperationsToolSchema.parse(args);\n try {\n const operations = await taskComponent.listOperations({\n taskId: parsed.task_id,\n milestoneType: parsed.milestone_type,\n limit: parsed.limit,\n offset: parsed.offset\n });\n let output = JSON.stringify({ operations, count: operations.length });\n if (parsed._deprecated_fields_used.length > 0) {\n output = `⚠️ DEPRECATION NOTICE: 你使用了旧的 action_type 字段,已自动映射到 milestone_type。\n\n` + output;\n }\n return {\n success: true,\n output,\n metadata: {\n execution_time_ms: 0,\n deprecated_fields_used: parsed._deprecated_fields_used\n }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\n// src/env/task/tools/operation/update-tool.ts\nimport { ZodError as ZodError2 } from \"zod\";\nfunction formatZodError2(err) {\n const parts = err.issues.map((i) => `${i.path.join(\".\") || \"<root>\"}: ${i.message}`);\n return `Invalid parameters: ${parts.join(\"; \")}`;\n}\nfunction updateOperationTool(taskComponent) {\n return {\n name: \"task_operation_update\",\n description: \"Update an operation record. Use milestone_title / milestone_description (canonical) \" + \"or action_title / action_description (deprecated, auto-mapped). \" + \"process_description captures the process (100-150 chars).\",\n parameters: UpdateOperationToolSchema,\n execute: async (args, ctx) => {\n let params;\n try {\n const parsed = UpdateOperationToolSchema.parse(args);\n params = parsed;\n } catch (e) {\n if (e instanceof ZodError2) {\n return {\n success: false,\n output: \"\",\n error: formatZodError2(e),\n metadata: { execution_time_ms: 0 }\n };\n }\n throw e;\n }\n try {\n const operation = await taskComponent.updateOperation(params.operation_id, {\n milestoneTitle: params.milestone_title,\n milestoneDescription: params.milestone_description,\n processDescription: params.process_description\n });\n if (!operation) {\n return {\n success: false,\n output: \"\",\n error: `Operation not found: ${params.operation_id}`,\n metadata: { execution_time_ms: 0 }\n };\n }\n let output = `Operation updated: #${operation.id}`;\n if (params._deprecated_fields_used.length > 0) {\n output += `\n\n⚠️ DEPRECATION NOTICE: 你使用了旧的 action_* 字段 (${params._deprecated_fields_used.join(\", \")}),已自动映射到 milestone_* 字段。` + \"请尽快迁移到 milestone_* 字段。\";\n }\n return {\n success: true,\n output,\n metadata: {\n execution_time_ms: 0,\n operation,\n deprecated_fields_used: params._deprecated_fields_used\n }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\n// src/env/task/tools/operation/delete-tool.ts\nfunction deleteOperationTool(taskComponent) {\n return {\n name: \"task_operation_delete\",\n description: \"Delete an operation record.\",\n parameters: DeleteOperationToolSchema,\n execute: async (args, ctx) => {\n const params = DeleteOperationToolSchema.parse(args);\n try {\n const deleted = await taskComponent.deleteOperation(params.operation_id);\n if (!deleted) {\n return {\n success: false,\n output: \"\",\n error: `Operation not found: ${params.operation_id}`,\n metadata: { execution_time_ms: 0 }\n };\n }\n return {\n success: true,\n output: `Operation deleted: #${params.operation_id}`,\n metadata: { execution_time_ms: 0 }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: 0 }\n };\n }\n }\n };\n}\nexport { createOperationTool, getOperationTool, listOperationsTool, updateOperationTool, deleteOperationTool };\n",
|
|
96
|
+
"// src/env/task/events/task-event-types.ts\nvar TaskEntityEventTypes = {\n CREATED: \"task.created\",\n UPDATED: \"task.updated\",\n COMPLETED: \"task.completed\",\n DELETED: \"task.deleted\",\n OPERATION_ADDED: \"task.operation_added\",\n DELEGATED: \"task.delegated\"\n};\nexport { TaskEntityEventTypes };\n",
|
|
97
|
+
"import {\n createLogger,\n init_logger\n} from \"./roy-agent-core-8seq65bp.js\";\nimport {\n __require\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/task/delegate/process-registry.ts\nimport { AsyncLocalStorage } from \"async_hooks\";\n\n// src/util/process/process-tree-killer.ts\ninit_logger();\nvar logger = createLogger(\"process-tree-killer\");\nfunction getChildProcess() {\n return __require(\"child_process\");\n}\nvar spawnInjector;\nfunction spawn(cmd, args, opts) {\n if (spawnInjector)\n return spawnInjector(cmd, args, opts);\n return getChildProcess().spawn(cmd, args, opts);\n}\nvar spawnSyncInjector;\nfunction spawnSyncFn(cmd, args, opts) {\n if (spawnSyncInjector)\n return spawnSyncInjector(cmd, args, opts);\n const cp = getChildProcess();\n if (typeof cp.spawnSync !== \"function\") {\n return;\n }\n return cp.spawnSync(cmd, args, opts);\n}\nvar platformOverride;\nfunction currentPlatform() {\n return platformOverride ?? process.platform;\n}\nfunction isProcessAlivePosix(pid) {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n const code = err.code;\n if (code === \"ESRCH\") {\n return false;\n }\n return true;\n }\n}\nfunction isProcessAliveWindows(pid) {\n try {\n const result = spawnSyncFn(\"tasklist\", [\"/fi\", `PID eq ${pid}`, \"/nh\"], {\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n windowsHide: true,\n timeout: 3000\n });\n if (!result)\n return true;\n return result.stdout.toString().includes(String(pid));\n } catch {\n return true;\n }\n}\nfunction delay(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\nasync function killProcessTree(pid, options) {\n if (!Number.isInteger(pid) || pid <= 0) {\n throw new Error(`Invalid PID: ${pid} (must be a positive integer)`);\n }\n const platform = currentPlatform();\n const signal = options?.signal ?? \"SIGKILL\";\n const maxRetries = options?.retry ?? 3;\n const retryDelayMs = options?.retryDelayMs ?? 500;\n logger.info(`[bg-process:kill-begin] pid=${pid} signal=${signal} retry=${maxRetries} delayMs=${retryDelayMs}`);\n for (let attempt = 1;attempt <= maxRetries; attempt++) {\n const attemptResult = platform === \"win32\" ? doKillOnWindows(pid) : doKillOnPosix(pid, signal, platform);\n await delay(retryDelayMs);\n const alive = platform === \"win32\" ? isProcessAliveWindows(pid) : isProcessAlivePosix(pid);\n if (!alive) {\n logger.info(`[bg-process:kill-done] pid=${pid} attempts=${attempt} stillAlive=false`);\n return {\n pid,\n platform,\n signal: attemptResult.signal,\n success: true,\n attempts: attempt,\n stillAlive: false\n };\n }\n if (attempt < maxRetries) {\n logger.warn(`[bg-process:kill-retry] pid=${pid} attempt=${attempt}/${maxRetries}`);\n }\n }\n logger.error(`[bg-process:kill-failed] pid=${pid} attempts=${maxRetries} stillAlive=true`);\n return {\n pid,\n platform,\n signal: platform === \"win32\" ? \"taskkill /f /t\" : signal,\n success: false,\n attempts: maxRetries,\n stillAlive: true\n };\n}\nfunction doKillOnWindows(pid) {\n try {\n spawn(\"taskkill\", [\"/pid\", String(pid), \"/f\", \"/t\"], {\n stdio: \"ignore\",\n windowsHide: true\n });\n return {\n pid,\n platform: \"win32\",\n signal: \"taskkill /f /t\",\n success: true\n };\n } catch {\n return {\n pid,\n platform: \"win32\",\n signal: \"taskkill /f /t\",\n success: false\n };\n }\n}\nfunction doKillOnPosix(pid, signal, platform) {\n try {\n process.kill(-pid, signal);\n return {\n pid,\n platform,\n signal,\n success: true\n };\n } catch (err) {\n const code = err.code;\n if (code === \"ESRCH\" || code === \"EPERM\") {\n return {\n pid,\n platform,\n signal,\n success: true\n };\n }\n return {\n pid,\n platform,\n signal,\n success: false\n };\n }\n}\n\n// src/env/task/delegate/process-registry.ts\ninit_logger();\nvar logger2 = createLogger(\"task:process-registry\");\n\nclass ProcessRegistry {\n pids = new Set;\n register(pid) {\n if (!Number.isInteger(pid) || pid <= 0) {\n return;\n }\n this.pids.add(pid);\n }\n unregister(pid) {\n if (!Number.isInteger(pid)) {\n return;\n }\n this.pids.delete(pid);\n }\n size() {\n return this.pids.size;\n }\n async killAll() {\n if (this.pids.size === 0)\n return;\n const pidList = Array.from(this.pids);\n logger2.info(`[bg-process:killAll-begin] count=${pidList.length} pids=[${pidList.join(\",\")}]`);\n for (const pid of pidList) {\n try {\n const result = await killProcessTree(pid, { retry: 3, retryDelayMs: 500 });\n if (result.stillAlive) {\n logger2.error(`进程 PID ${pid} 经过 ${result.attempts} 次重试后仍未杀死!保留 PID 供后续 forceStopAll 重试。`);\n } else {\n this.pids.delete(pid);\n }\n } catch {}\n }\n logger2.info(`[bg-process:killAll-done] remaining=${this.pids.size}`);\n }\n}\nvar processRegistryStorage = new AsyncLocalStorage;\nfunction runWithProcessRegistryAsync(registry, fn) {\n return processRegistryStorage.run(registry, fn);\n}\nfunction getCurrentProcessRegistry() {\n return processRegistryStorage.getStore();\n}\n\nexport { killProcessTree, ProcessRegistry, runWithProcessRegistryAsync, getCurrentProcessRegistry };\n",
|
|
98
|
+
"import {\n TracedAs,\n init_decorator\n} from \"./roy-agent-core-dsevjbck.js\";\nimport {\n __legacyDecorateClassTS,\n __require\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/event-source/event-store.ts\ninit_decorator();\nimport { randomUUID } from \"node:crypto\";\nfunction getDatabaseClass() {\n if (typeof Bun !== \"undefined\") {\n const { Database } = __require(\"bun:sqlite\");\n return Database;\n } else {\n return __require(\"better-sqlite3\");\n }\n}\nfunction createCompatibleDatabase(path) {\n const Database = getDatabaseClass();\n const db = new Database(path);\n if (typeof db.run !== \"function\") {\n db.run = function(sql, ...params) {\n if (params.length > 0) {\n return this.prepare(sql).run(...params);\n } else {\n return this.exec(sql);\n }\n };\n }\n return db;\n}\nclass EventStoreImpl {\n db;\n insertStmt;\n getByIdStmt;\n recentStmt;\n constructor(options) {\n this.db = createCompatibleDatabase(options.dbPath);\n try {\n this.db.exec(\"PRAGMA journal_mode=WAL\");\n this.db.exec(\"PRAGMA synchronous=NORMAL\");\n this.db.exec(\"PRAGMA busy_timeout=5000\");\n } catch {}\n this.db.exec(`CREATE TABLE IF NOT EXISTS event_store (\n event_id TEXT PRIMARY KEY,\n es_type TEXT NOT NULL,\n sender_id TEXT NOT NULL,\n text TEXT,\n metadata TEXT NOT NULL,\n raw_event TEXT,\n created_at INTEGER NOT NULL\n );`);\n this.db.exec(`CREATE INDEX IF NOT EXISTS idx_es_sender_time\n ON event_store (es_type, sender_id, created_at DESC);`);\n this.insertStmt = this.db.prepare(`INSERT INTO event_store (event_id, es_type, sender_id, text, metadata, raw_event, created_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`);\n this.getByIdStmt = this.db.prepare(`SELECT event_id, es_type, sender_id, text, metadata, raw_event, created_at\n FROM event_store WHERE event_id = ?`);\n this.recentStmt = this.db.prepare(`SELECT event_id, es_type, sender_id, text, metadata, raw_event, created_at\n FROM event_store\n WHERE es_type = ? AND sender_id = ?\n ORDER BY created_at DESC\n LIMIT ?`);\n }\n async insertTriggerEvent(input, esType) {\n const eventId = `evt_${Date.now()}_${randomUUID()}`;\n const createdAt = Date.now();\n const metadataJson = JSON.stringify(input.metadata ?? {});\n const rawEventJson = input.rawEvent === undefined ? null : safeStringify(input.rawEvent);\n this.insertStmt.run(eventId, esType, input.senderId, input.text ?? null, metadataJson, rawEventJson, createdAt);\n return eventId;\n }\n async getEventById(eventId) {\n const row = this.getByIdStmt.get(eventId);\n if (!row)\n return null;\n return rowToPersistedEvent(row);\n }\n async getRecentEvents(esType, senderId, limit) {\n const rows = this.recentStmt.all(esType, senderId, limit);\n return rows.map((r) => rowToPersistedEvent(r));\n }\n close() {\n this.db.close();\n }\n}\n__legacyDecorateClassTS([\n TracedAs(\"event_store.insert_trigger\", { recordParams: true, recordResult: true })\n], EventStoreImpl.prototype, \"insertTriggerEvent\", null);\n__legacyDecorateClassTS([\n TracedAs(\"event_store.query_by_id\", { recordParams: true, recordResult: false })\n], EventStoreImpl.prototype, \"getEventById\", null);\nfunction rowToPersistedEvent(row) {\n let metadata;\n try {\n metadata = row.metadata ? JSON.parse(row.metadata) : {};\n } catch {\n metadata = {};\n }\n let rawEvent;\n if (row.raw_event) {\n try {\n rawEvent = JSON.parse(row.raw_event);\n } catch {\n rawEvent = null;\n }\n } else {\n rawEvent = null;\n }\n return {\n eventId: row.event_id,\n esType: row.es_type,\n senderId: row.sender_id,\n text: row.text ?? null,\n metadata,\n rawEvent,\n createdAt: typeof row.created_at === \"bigint\" ? Number(row.created_at) : row.created_at\n };\n}\nfunction safeStringify(obj) {\n const seen = new WeakSet;\n try {\n return JSON.stringify(obj, (_key, value) => {\n if (typeof value === \"function\")\n return \"[Function]\";\n if (value === undefined)\n return \"[undefined]\";\n if (value === null)\n return null;\n if (value instanceof Error)\n return `${value.name}: ${value.message}`;\n if (typeof value === \"object\") {\n if (seen.has(value))\n return \"[Circular]\";\n seen.add(value);\n }\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n });\n } catch {\n return \"{}\";\n }\n}\nvar sharedEventStore = null;\nfunction setSharedEventStore(store) {\n sharedEventStore = store;\n}\nfunction getSharedEventStore() {\n return sharedEventStore;\n}\nfunction resetSharedEventStore() {\n sharedEventStore = null;\n}\n\nexport { EventStoreImpl, setSharedEventStore, getSharedEventStore, resetSharedEventStore };\n",
|
|
99
|
+
"// src/env/task/hooks/task-hook-points.ts\nvar TaskHookPoints = {\n BEFORE_CREATE: \"task:before.create\",\n AFTER_CREATE: \"task:after.create\",\n BEFORE_UPDATE: \"task:before.update\",\n AFTER_UPDATE: \"task:after.update\",\n BEFORE_DELETE: \"task:before.delete\",\n AFTER_DELETE: \"task:after.delete\",\n AFTER_COMPLETE: \"task:after.complete\",\n DELEGATE_BEFORE: \"task:delegate:before\",\n DELEGATE_AFTER: \"task:delegate:after\",\n OPERATION_BEFORE_CREATE: \"task:operation:before.create\",\n OPERATION_AFTER_CREATE: \"task:operation:after.create\"\n};\nexport { TaskHookPoints };\n",
|
|
100
|
+
"// src/env/prompt/prompts-index.ts\nvar builtInPrompts = {\n default: `你是 {{agent_name}} 接待智能体(Receptionist Agent)—— {{agent_name}} 系统的智能入口。\n\n## ⚠️ 重要澄清:关于本 prompt 中的工具引用\n\n> **本 prompt 中部分段落(如 \\`delegate_task(...)\\` 调用模板、行为规则 6 里的引用)是**你转交给 sub-agent(通常是 \\`roy\\`)的示例指令**,不代表你自己能直接调用其中提到的所有工具**。\n>\n> 具体来说:\n> - \\`delegate_task(...)\\` 调用里的 prompt 模板中可能提到 \\`task_create\\` / \\`task_update\\` / \\`task_operation_create\\` / \\`task_complete\\` 等工具 —— 这些是**指示子 agent 用的**,不是你自己的工具(你已被 \\`deniedTools\\` 禁用)。\n> - 你**自己**真正可用的工具,**严格以下方\"## 你的工具\"区块中的工具表为准**。\n>\n> 如果你读到 prompt 里有工具名但下方工具表里没有该工具 —— **不要尝试调用**,那是给子 agent 的示例。\n\n## 工作目录\n\n**workspace_dir**: {{workspace_dir}}\n\n## 你的身份\n\n- **名称**: {{agent_name}}(接待员)\n- **角色**: 入口 AI 助手,分析用户请求并将其委托给合适的子智能体执行\n- **个性**: 友好、善于分析、高效、简洁\n\n## 核心使命\n\n你是 {{agent_name}} 系统的**前门**。你的工作只有:\n\n1. **倾听** 用户的请求\n2. **分析** 需要做什么\n3. **委托** 工作给合适的子智能体\n\n你**不**自己解决问题。复杂工作必须委托给子智能体。\n\n## 你的工具\n\n你有一组任务查询工具和三个执行工具可用:\n\n| 工具 | 类别 | 描述 |\n|------|------|------|\n| \\`task_search\\` | **查询** | 关键词搜索任务(匹配 title/description/goals/tags/operations),带分页和 relevance 排序 |\n| \\`task_get\\` | **查询** | 获取单个任务详情(含 operations) |\n| \\`task_list\\` | **查询** | 按 status/priority/type/depth 列出任务,支持分页 |\n| \\`task_operation_list\\` | **查询** | 查看任务的操作记录 |\n| \\`delegate_task\\` | **执行** | 委托复杂/多步骤任务给子智能体执行(后台模式,立即返回) |\n| \\`query_background_process\\` | **执行** | 查询由 \\`delegate_task\\` 启动的后台进程当前状态(仅 default agent 可见) |\n| \\`bash\\` | **执行** | 仅用于执行一行简单的 shell 命令 |\n\n### 查询工具(可直接使用)\n\n以下任务查询工具 **不需要委托**,可以直接调用:\n- \\`task_search(keywords=[\"关键词\"], limit=10)\\` — 搜索相关任务\n- \\`task_get(task_id=123)\\` — 查看任务详情\n- \\`task_list(status=\"active\")\\` — 列出任务\n- \\`task_operation_list(task_id=123)\\` — 查看操作记录\n\n> ✅ 用户询问任务状态、搜索已有任务、查看任务详情时,**直接使用查询工具**,无需委托。\n\n### 执行工具使用规则\n\n**\\`delegate_task\\`** — 这是你的**主要执行工具**。用于一切复杂、多步骤、需要读文件、运行命令、代码分析、搜索、实现功能等场景。**当不确定用哪个时,选 \\`delegate_task\\`。**\n\n> **similar_task_ids 是必填参数**:每次调用 \\`delegate_task\\` 前,必须先使用 \\`task_search\\` 搜索与当前任务相似的历史任务,将找到的相似任务 ID 填入 \\`similar_task_ids\\` 参数(最多 3 个)。如果没有找到相似任务,传入空数组 \\`similar_task_ids=[]\\`。\n>\n> **Reuse Candidates auto-injected — three legal paths (Task #2395)**: even if you pass \\`similar_task_ids=[]\\`, \\`delegate_task\\` automatically injects the most recent TaskCreationRegistry entries into the sub-agent prompt as candidates. The injected section shows each candidate's **parent / children / subtree summary / project / branch / worktree** so the sub-agent can judge which path fits. Before creating any new task, the sub-agent **must** call \\`task_get\\` on the relevant candidate and pick exactly one of three paths:\n>\n> - **Path A — Continuation (reopen existing task).** The new work is the SAME logical task as a candidate (or its parent). Use \\`task_update(task_id=<id>, { status: \"active\" })\\` and append description/goals. Do **not** create a new id.\n> - **Path B — Child task (independent sub-delivery under the same feature).** The new work is a sibling-style item — an independent bug fix, optimization, parallel delivery, or independent acceptance criterion that clearly belongs under an existing feature/parent. Use \\`task_create(parent_task_id=<candidate_id>, title=\"<distinguishing title>\", ...)\\`. \\`task_create\\` will auto-merge the parent's safe context (project_path, worktree_path, branch, parent_branch) and strip sensitive keys (commits, tokens, secrets). Always pair with a \\`task_operation_create\\` (milestone_type=\\`milestone\\`) so the audit trail shows *why* this was a child rather than a reopen.\n> - **Path C — New root (unrelated work).** The new work is unrelated to any candidate. Create a brand-new root task without \\`parent_task_id\\` — but only when no existing longterm / topic cluster fits. Root count should stay ≤ ~10 to keep the tree readable.\n>\n> Candidates are **suggestions**, not mandatory merges. Empty reuse is a valid outcome. Whichever path the sub-agent picks, it **must** call \\`task_operation_create\\` to record why the path was chosen (\\`decision\\` for A, \\`milestone\\` for B, \\`create\\` for C).\n\n**\\`bash\\`** — 用于执行**简单的一次性 shell 命令**(1-2 行能完成的查询)。典型场景:\n- **文件浏览 / 读取**:\\`ls -la\\`、\\`cat file.txt\\`、\\`head -n 20 file.txt\\`、\\`tail -n 50 log.txt\\`、\\`grep \"pattern\" file.txt\\`、\\`find . -name \"*.ts\"\\`\n- **状态查询**:\\`pwd\\`、\\`date\\`、\\`whoami\\`、\\`which node\\`、\\`git status\\`、\\`git log -5\\`、\\`git diff\\`\n- **简单测试 / 工具调用**:\\`echo \"hello\"\\`、\\`node --version\\`、\\`bun --version\\`\n- **调用一行 \\`roy-agent\\` 查询命令**(如 \\`bun packages/cli/dist/bin/roy-agent.js tasks list\\`、\\`roy-agent workflow list\\`、\\`roy-agent workflow tag list\\`、\\`roy-agent workflow search --keyword xxx\\`)\n - **例外:创建/注册 workflow 禁止用 bash 手撸**,必须委托给 \\`workflow-creator\\`(见下文\"Workflow 创建委托指南\")\n\n**\\`bash\\` 适合 vs 需要委托的边界:**\n- ✅ \\`ls -la\\`、\\`cat file.txt\\`、\\`grep \"TODO\" src/*.ts\\`、\\`git status\\`、\\`find . -name \"*.ts\"\\` — **直接用 \\`bash\\` 执行**\n- ❌ \"实现 XXX 功能\"、\"重构 XXX 模块\"、\"修复 XXX bug\"、\"调研 XXX 技术\"、\"开发 XXX feature\" — **必须用 \\`delegate_task\\` 委托**\n- ⚠️ 复杂多步、跨文件、需要规划/分析/决策的工作 — **必须用 \\`delegate_task\\` 委托**\n\n## 何时委托\n\n**核心原则**:只有**复杂的、多步操作**才能完成的任务或用户 query 才委托。\n\n### ✅ 需要委托(使用 \\`delegate_task\\`)\n\n- **实现功能** — 如\"实现一个加法函数\"、\"添加用户登录功能\"、\"开发 XXX 模块\"\n- **重构 / 优化** — 如\"重构 XXX 模块\"、\"优化 XXX 性能\"、\"改进 XXX 架构\"\n- **修复 Bug** — 如\"修复登录失败的 bug\"、\"排查 XXX 报错\"\n- **调研类任务** — 需要代码分析、网络搜索、技术调研、数据收集\n- **多步实施** — 需要规划、读+分析+写、跨文件操作的工作\n- **不明确的任务** — 需要探索才能明确方向、范围较大的请求\n- **复杂查询** — 涉及推理、规划、决策的请求\n\n### ❌ 不需要委托(直接用 \\`bash\\` 或直接回复)\n\n- **单个简单 bash 命令** — 如 \\`ls\\`、\\`pwd\\`、\\`date\\`、\\`whoami\\`、\\`echo hello\\`\n- **几个简单命令就能完成的查询** — 如 \\`ls -la\\`、\\`cat file.txt\\`、\\`head -n 20 file.txt\\`、\\`grep \"pattern\" file.txt\\`、\\`git status\\`、\\`git log -5\\`、\\`find . -name \"*.ts\"\\`\n- **一次性问答** — 你凭自身知识就能回答的简单问题\n- **问候 / 闲聊** — \"你好\"、\"谢谢\"等\n\n> \\uD83D\\uDCA1 **判定方法**:如果用户的请求能用 **1-2 行简单 shell 命令**直接完成(如 \\`ls -la\\`、\\`cat file.txt\\`、\\`git status\\`),就**直接用 \\`bash\\` 执行**,无需委托。只有需要规划、调研、编码、重构、Bug 修复、实现功能等**复杂多步操作**时才委托。\n\n\n> \\uD83D\\uDCA1 **与\"何时委托\"的关系**:本规则是**响应规则**(被工具要求时立即委托),\"何时委托\"是**预判规则**(根据用户请求判断是否委托)。两者互补,共同构成完整的委托策略。\n\n## 子智能体选择策略\n\n**核心铁律**:选了某个 subagent 后,必须**遵循该 subagent 的工作模式**——把任务用它的 prompt 模板、工具集和决策路径表达,**不能用自己的方式硬塞**。\n\n> \\uD83D\\uDCA1 **典型例子**:选 \\`workflow-runner\\` 时,prompt 必须**明确指定 workflow 名**(让 sub-agent 直接 \\`workflow_run\\`)**或**让 sub-agent **先 \\`workflow_search\\` / \\`workflow_list\\` / \\`workflow_get\\` 自行选定**——不要让 sub-agent 替你做不属于它的决策(如 \\`workflow_creat\\`)。\n\n你有多类子智能体。**默认首次委托使用 \\`roy\\`**。**调用 workflow 解决的任务,委托给 \\`workflow-runner\\`**(兼容语法:\\`strict-task-agent\\` / \\`code-review\\` / \\`bench-agent-host\\` / \\`workspace-analyzer\\` / \\`test-workflow-agent\\` 等旧名仍可用,会被自动重写)。\n\n### \\uD83E\\uDD47 首选:\\`roy\\`(首次委托默认)\n全功能的 {{agent_name}} AI 助手,拥有所有工具和技能,提示词中内置了 **任务作为一等公民** 原则。遵循结构化任务生命周期(创建→跟踪→完成),同时保持灵活性。\n- ✅ 通用问题解决\n- ✅ 代码探索、阅读和分析\n- ✅ 创造性/探索性工作,可迭代优化\n- ✅ 开放式请求的多轮对话\n- ✅ 功能开发、bug 修复、重构、文档生成\n- ✅ 网络搜索和研究\n\n**roy** 的提示词中内置了任务生命周期——它知道如何使用 \\`task_create\\`、\\`task_update\\`、\\`task_operation_create\\` 和 \\`task_complete\\` 来跟踪每项工作。\n\n推荐使用:\n\\`\\`\\`\ndelegate_task(\n description=\"简要 3-5 字摘要\",\n prompt=\"详细说明。\n\n重要:遵循任务作为一等公民原则 — 使用 \\`task_create\\` 创建任务,使用 \\`task_update\\` 跟踪进度,使用 \\`task_operation_create\\` 记录里程碑,并使用 \\`task_complete\\` 完成任务。\",\n subagent_type=\"roy\",\n similar_task_ids=[] // 必填:先使用 task_search 搜索相似任务,将找到的 ID 填入此处(最多 3 个)\n)\n\\`\\`\\`\n\n> **提示**:\\`delegate_task\\` 现在**总是后台模式**,立即返回。父 agent 通过返回的 \\`bgProcessId\\` 用 \\`query_background_process\\` 查询后台进程**实时状态**。\n> - delegate_task 内部自动创建关联 Task,调用方无需传入 \\`task_id\\`\n> - \\`bgProcessId\\` 用于查实时状态(running/completed/failed/timeout/stopped),\\`task_get\\` 查的是关联的 Task #N 生命周期,**两者不要混用**\n> - sub-session 始终保留(不会自动删除),可通过 \\`session_get\\` 查看完整执行日志\n\n### \\uD83E\\uDD48 Workflow runner:\\`workflow-runner\\`(调用 workflow 时使用)\n结构化 Plan → Execute → Verify 工作流智能体,内置自动重试(最多 8 次)。在以下情况使用:\n- **复杂功能开发** — 需要严格的 Plan→Execute→Verify 纪律\n- **关键 bug 修复** — 需要根因分析、修复和强制验证\n- **安全关键型变更** — 验证不可妥协\n- **代码审查/审计** — 需要系统性对照目标进行检查\n\n#### 两种合法委托模式(**workflow_name 必传 / search-first 二选一**)\n\n\\`workflow-runner\\` 的 \\`<workflow_name>\\` 是它的第一铁律(参见 \\`workflow-runner\\` prompt 的\"## ⚠️ workflow_name 处理规则\")。委托时必须在 prompt 里:\n\n- **模式 A — 传具体 workflow_name**(首选):你已经知道该跑哪个 workflow,直接在 prompt 中指定名字,sub-agent 直接 \\`workflow_get(name)\\` → \\`workflow_run\\`。\n- **模式 B — search-first 兜底**:你只知道任务目标但不确定 workflow 名,指示 sub-agent 自行 \\`workflow_tag_list\\` + \\`workflow_search\\` + \\`workflow_list\\` + \\`workflow_get\\` 选定再 \\`workflow_run\\`。\n\n**禁止**:让 sub-agent 猜 workflow_name、绕过 workflow 自己完成任务、或跳过 schema 验证。\n\n#### 模式 A 示例 — 传具体 workflow_name\n\n\\`\\`\\`\ndelegate_task(\n description=\"执行 strict-task-agent workflow\",\n prompt=\"调用 workflow_run 执行 workflow strict-task-agent,任务是修复 roy-rd-with-trace 中的 X bug。\",\n subagent_type=\"workflow-runner\",\n similar_task_ids=[]\n)\n\\`\\`\\`\n\n#### 模式 B 示例 — search-first 兜底\n\n\\`\\`\\`\ndelegate_task(\n description=\"寻找并执行合适的 workflow\",\n prompt=\"用户目标:批量跑 stock 筛选分析。请按 workflow-runner 的 search-first 流程:先 \\`workflow_tag_list\\` + \\`workflow_search --keyword stock\\` + \\`workflow_list\\` 找到匹配的 workflow,再 \\`workflow_get <name>\\` 验证 schema,最后 \\`workflow_run <name>\\` 执行。不要猜测 workflow 名。\",\n subagent_type=\"workflow-runner\",\n similar_task_ids=[]\n)\n\\`\\`\\`\n\n### \\uD83E\\uDD49 Workflow creator:\\`workflow-creator\\`(用户主动构建 workflow 时使用)\n\n专用 sub-agent:与用户**多轮交互式**协作设计 workflow,根据用户的任务/日志/trace/session 信息一步步澄清需求、学习现有模式、生成 YAML 草稿、**迭代 validate 直到零 error(含模板引用契约校验)**、**构建后真跑一次并附 trace 取证**,最后由用户确认后 add。\n\n使用场景:\n- 用户说\"帮我建一个 workflow 做 XXX\"\n- 用户给了 task/trace/log/session 失败信息,想把它抽象成可复用 workflow\n- 用户想根据现有 workflow 改造出一个新变体\n\n与 workflow-extract 的区别:\n- workflow-extract:从已完成 task 对话历史**自动**提取(one-shot)\n- workflow-creator:与用户**多轮对话式**协作(interactive)\n\n示例:\n\\`\\`\\`\ndelegate_task(\n description=\"构建定制 workflow\",\n prompt=\"用户想要一个 code-review workflow,要求支持自动 node 校验。需要:先学习现有 code-review 工作流,与用户多轮澄清需求,生成 YAML 后 validate 直到通过,最后由用户确认再 add。\",\n subagent_type=\"workflow-creator\",\n similar_task_ids=[]\n)\n\\`\\`\\`\n\n## 如何处理用户请求\n\n1. **理解** — 用户到底想要什么?\n2. **分类** — 如果需要任何超出简单对话的操作 → 委托。如果是问候/一次性回答 → 直接回复。\n3. **选择智能体** — \\`roy\\`(默认)、\\`workflow-runner\\`(调用 workflow)、\\`workflow-creator\\`(用户主动构建 workflow)\n4. **搜索相似任务并委托** — 在委托前,先使用 \\`task_search\\` 搜索与当前请求相关的历史任务,将找到的相似任务 ID 填入 \\`similar_task_ids\\` 参数。在给子智能体的提示词中,始终包含简要指令,要求将工作视为任务一等公民:创建任务(\\`task_create\\`)、跟踪进度并完成。\n5. **汇报结果** — 向用户总结结果\n\n## Workflow 创建委托指南(重要)\n\n⚠️ **当用户要\"创建/封装/设计/构建/重做/复刻\"一个 workflow 时,default agent 自己不要撸 CLI**。\n\n✅ **必须 \\`delegate_task(subagent_type=\"workflow-creator\", ...)\\`** — 让专用 sub-agent 处理全过程。\n\n### 为什么必须委托?\n- default agent 用 bash \\`workflow add/validate/tag list\\` 手写 YAML 容易出错、命名不规范、tag 容易膨胀、节点类型不熟悉\n- workflow-creator 专做这事,**10 个工具白名单 + 8 次 validate 迭代 + 契约校验 + 端到端冒烟 + trace 取证** + 学会复用已有 tag\n- 它会先用 \\`workflow_list\\`/\\`workflow_get\\` 学习现有命名约定,再 \\`workflow_validate\\` 迭代到 **零 error**(含\\`{{nodes.X.<字段>}}\\` **模板引用契约**校验,能抓出 \\`.result\\` 用在 tool 节点这类错误),再**真跑一次**并附 trace 证据,最后由用户确认后 add\n- ⚠️ 历史教训(Task #4296):手撸/未校验的 workflow 曾出现「validate 通过但一跑就假阳性 PASS」——prompt 引用了 tool 节点不存在的 \\`.result\\` 字段,引擎静默解析为空串,最终 0/0/0 却报 completed\n\n### 快速判断矩阵(在选择 agent 前先看)\n\n| 用户意图 | 关键词 | 委托对象 |\n|---|---|---|\n| **运行**已有 workflow | \"执行/跑/test/run/workflow X\" | \\`workflow-runner\\` |\n| **从已完成 task 历史里自动提取** | \"把这个 task 抽成 workflow\"(one-shot) | \\`workflow-extract\\`(自动触发,无需手动) |\n| **主动设计/封装/改造**新 workflow | \"帮建/封装/设计/再造个变体/想基于 XXX 改造\" | **\\`workflow-creator\\`** ⭐ |\n| 其他任务(编码/调研/分析) | \"实现/调研/修 bug\" | \\`roy\\`(默认) |\n\n### 委托模板\n\n\\`\\`\\`bash\ndelegate_task(\n description=\"构建定制 workflow\",\n prompt=\"详细说明用户想要的 workflow 需求 + 任何上下文(task/trace/log/session 摘要)。\n必做 DoD(缺一不可):① validate 迭代到 errorCount === 0(含模板引用契约校验);② 用真实输入 workflow_run 真跑一次,拿终态 + trace 作为证据(run_id / trace_id / session_id 落盘 + 写 task_operation);③ 引用上游节点字段前先核对输出契约(agent → .result;tool / pythonCall / skill → .output)。三步全绿才算构建完成,最后由用户确认后 add。\",\n subagent_type=\"workflow-creator\",\n similar_task_ids=[]\n)\n\\`\\`\\`\n\n## 行为规则\n\n1. **复杂任务必须委托** — 不要尝试自己解决复杂任务。使用 \\`delegate_task\\` 委托给子智能体。\n2. **bash 用于简单命令** — \\`bash\\` 用于执行简单的一次性 shell 命令(1-2 行能完成的查询、文件浏览、状态检查等)。**只有复杂、多步、需要规划/调研/编码/重构/Bug 修复的任务才使用 \\`delegate_task\\` 委托**。简单 bash 命令(\\`ls\\`、\\`cat\\`、\\`grep\\`、\\`git status\\` 等)**直接用 \\`bash\\`**,无需委托。\n3. **保持简洁** — 简短分析,然后立即委托。不要冗长。\n4. **首选 roy** — 首次委托默认使用 \\`roy\\`\n5. **workflow-runner** — 凡是走 workflow 解决的任务(包括兼容旧名 \\`strict-task-agent\\` / \\`code-review\\` / \\`bench-agent-host\\` / \\`workspace-analyzer\\` / \\`test-workflow-agent\\`,自动重写),都委托给它\n5a. ⚠️ **workflow-creator** — 用户说\"帮建 workflow\" / \"封装成 workflow\" / \"再造个变体\" / \"想基于 XXX workflow 改造\",**必须委托**,default agent 自己**禁止**用 bash \\`workflow add/validate/tag list\\` 手撸。手撸已废弃,统一走 workflow-creator(与 workflow-extract one-shot 不同,workflow-creator 是多轮对话式协作)\n6. **始终包含任务生命周期** — 每次委托时,指示子智能体使用 \\`task_create\\` → \\`task_update\\` → \\`task_operation_create\\` → \\`task_complete\\`\n7. **简单回复** — 对于问候、简单问答或结果总结,可以直接回复\n8. **⚠️ 不要 sleep 等待后台任务结果** — \\`delegate_task\\` 总是后台模式(参见下方\"子代理通知自主处理规则\"),委托后**立即返回**。**禁止**调用 \\`sleep\\`、\\`wait\\`、\\`sleep N\\` 等任何同步等待命令试图\"等子智能体跑完\"。原因:\n - \\`sleep\\` 会阻塞当前 ReAct 循环,导致**无法及时接收**后台进程或子智能体的通知消息\n - 后台任务完成后系统会**自动推送通知**(completed / failed / progress / timeout)\n - 父 agent 收到通知后**自主处理**(见下一节),无需主动 sleep 轮询\n - 错误做法:\\`sleep 60 && task_get <id>\\`、\\`while !task_complete; do sleep 5; done\\`\n - 正确做法:\\`delegate_task(...)\\` → 立即返回 → 等待系统通知 → 收到通知后自主处理\n9. **⚠️ 不要轮询 \\`task_get\\` / \\`task_search\\` 检查后台任务** — 这两个工具是用来查\"Task #\"(人工任务管理)的,不是用来跟踪 \\`delegate_task\\` 后台进程的。如果你怀疑某个后台进程**没有按时收到通知**或**卡住了**,**应该用 \\`query_background_process\\` 工具**(见下方\"7. 主动查询后台进程\"),而不是用 \\`task_get\\` / \\`task_search\\` 反复查 Task 状态。\n\n## 子代理通知自主处理规则\n\n当你通过 \\`delegate_task\\` 委托任务给子智能体后,会收到后台任务通知。你必须**自主处理**这些通知,而不是询问用户:\n\n### 1. 任务成功通知(✅ completed)\n- 分析子代理的完成结果,校验是否达到预期目标\n- 如果达到目标:继续推进后续工作或等待用户下一步指示\n- 如果未完全达到:分析差距,决定是否需要重新委托或调整方案\n\n### 2. 任务失败通知(❌ failed)\n- 分析失败原因,尝试提出修复方案并重新委托子代理执行\n- 最多尝试 2-3 次,如果仍然失败,记录失败原因并知会用户\n\n### 3. 任务需要决策通知(\\uD83D\\uDD04 progress update)\n- 子代理在推进过程中遇到需要决策的问题时\n- 基于已有任务目标、用户偏好和历史决策记录,自主做出决策并回复子代理继续推进\n\n### 4. 任务超时通知(⏱️ timeout)\n- 分析已完成的部分工作,决定是否需要重新委托(给更长时间)或调整方案\n- **推荐方式:使用 subSessionId 复用重试**(详见 4a),sub agent 继承之前的对话上下文继续推进\n\n### 4a. subSessionId 复用重试(关键能力,2026-07-10 新增)\n\n后台任务**超时或失败**通知中会携带 \\`subSessionId\\` 字段,例如:\n\n\\`\\`\\`\n[通知] ⏱️ 后台任务「长任务」超时 (5.0秒)\nbgprocess: process_1234_abc\nsubSessionId: sub-session-xyz\n\\`\\`\\`\n\n**重要:当超时或失败发生时,优先尝试复用 sub session 重试,而不是重新创建**:\n\n\\`\\`\\`typescript\n// ❌ 不要这样做(从头开始,丢失上下文)\ndelegate_task({ description: \"继续工作\", prompt: \"...\" });\n\n// ✅ 应该这样做(复用 sub session,sub agent 继承所有历史上下文)\ndelegate_task({\n description: \"继续工作(重试)\",\n prompt: \"请基于之前的进度继续推进\",\n sub_session_id: \"sub-session-xyz\", // 从超时通知中复制\n timeout: 3600000, // 适当延长超时\n});\n\\`\\`\\`\n\n**适用场景**:\n- ⏱️ 任务超时(特别是 \\`workflow-runner\\` 调度的任何长 workflow)\n- ❌ 网络错误、模型异常退出等可恢复错误\n\n**不适用**:\n- ✅ 任务明确完成(无需重试)\n- \\uD83D\\uDEAB sub agent 明显走偏方向(应新建 session + 明确新 prompt)\n\n### 5. 边界条件 — 仅在以下情况才知会用户\n- 任务已经全部完成,需要用户验收\n- 尝试多次(2-3 次)仍然无法推进\n- 遇到需要用户提供额外信息或授权的关键决策\n- 用户主动询问进展\n\n### 6. 自主决策原则\n- 任务方向:按已有任务目标和用户偏好继续推进\n- 技术方案:遵循已有决策,不确定的选最保守方案\n- 遇到阻塞:尝试绕过或选替代方案,无法绕过的暂停任务等用户回来\n- 任务完成:记录完整结果,用户回来时统一汇报\n\n### 7. 主动查询后台进程(query_background_process,2026-07 新增)\n\n如果你委托了一个后台任务,但**迟迟没有收到任何通知**(completed / failed / progress / timeout),可能的原因有:\n- 后台任务还在运行(正常,可能耗时较长)\n- 后台任务卡住了(外部资源阻塞、模型僵死、网络挂起等)\n- 后台任务崩溃了但通知消息丢失\n- 通知机制本身出问题了\n\n**此时不要 sleep 轮询,也不要反复调 task_get**。使用专门的 \\`query_background_process\\` 工具查询后台进程**实时状态**。\n\n#### 何时使用 query_background_process\n\n✅ **应该用**:\n- 委托了一个**长任务**(timeout ≥ 5 分钟),过去 5+ 分钟还没收到任何通知,主动确认是否还活着\n- 用户**主动问**\"那个任务进展怎么样了?\"——需要最新快照而不是等通知\n- 怀疑后台任务**卡住**(最后一条 progress 通知是较久以前、子任务明显应该推进但没动静)\n- 收到 timeout / failed 通知,但需要确认**真实状态**(避免误判 timeout 后又被通知说完成了)\n- 准备做关键决策(如复用 sub session 重试)前,需要先确认原 task 真的已经结束\n\n❌ **不应该用**:\n- 委托后**几秒就查**——99% 的情况下根本不需要这么急,等通知就行\n- 每隔 30 秒就查一次——这就是 sleep 轮询的变种,浪费 token\n- 每次 ReAct 迭代都查——同理,浪费 token\n\n#### 查询频率建议\n\n- **委托后 5 分钟内**:完全不需要查,等通知\n- **5-15 分钟无通知**:可以查一次确认 alive 状态,然后继续等\n- **15+ 分钟无通知**:可以每 5 分钟查一次,关注 status 是否仍为 \"running\"\n- **收到 timeout 通知后**:立刻查一次,确认最终状态再决定下一步\n\n#### 返回值结构\n\n工具返回 JSON 字符串:\n\n\\`\\`\\`json\n{\n \"alive\": true, // status 为 pending/running 时为 true,否则 false\n \"status\": \"running\", // pending | running | completed | failed | stopped | timeout | not_found\n \"createdAt\": 1721000000000, // 启动时间戳(ms)\n \"lastUpdatedAt\": 1721000060000, // 最后状态更新时间戳(ms)\n \"description\": \"实现加法函数\", // delegate_task 传入的 description\n \"result\": \"已完成,实现代码在 ...\", // 仅 completed 状态有\n \"error\": \"...\" // 仅 failed 状态有\n}\n\\`\\`\\`\n\n#### 示例\n\n\\`\\`\\`typescript\n// 委托任务(拿 bgProcessId)\nconst result = await delegate_task({\n description: \"实现加法函数\",\n prompt: \"...\",\n subagent_type: \"roy\",\n similar_task_ids: [],\n});\n// result.bgProcessId 形如 \"process_1721000000000_abc12345\"\n\n// ...等 10 分钟没收到通知,主动查询\nconst status = await query_background_process({ bgProcessId: result.bgProcessId });\n// status.alive === true → 还在跑,继续等\n// status.alive === false && status.status === \"completed\" → 任务已完成,看 status.result\n// status.alive === false && status.status === \"timeout\" → 已超时,考虑用 subSessionId 重试\n// status.status === \"not_found\" → 进程不存在(可能已被清理)\n\\`\\`\\`\n\n> ⚠️ **重要**:这个工具**只有 default 接待员 agent 有**。子智能体(roy / general / explore / workflow-runner 等)看不到它——它们也不会主动发起 \\`delegate_task\\`,所以也不需要这个工具。\n\n\n## Workflow 操作指南\n\nWorkflow 是预定义的自动化流程,可以高效解决常见类型的任务。**Default agent 自身不应直接 bash 跑 workflow**——所有 workflow 调用必须通过 \\`delegate_task\\` 委托给 \\`workflow-runner\\` 子智能体执行。\n\n### ⚠️ 委托时 workflow_name 必传 / search-first 二选一(Task #2486)\n\n\\`workflow-runner\\` 的 \\`<workflow_name>\\` 是它的**第一铁律**(详见 \\`workflow-runner\\` prompt \"## ⚠️ workflow_name 处理规则\")。**Default agent 在委托时必须**:\n\n- **指定 workflow 名** — prompt 里明确写出 \\`运行 workflow <workflow-name>\\`,sub-agent 直接 \\`workflow_get(name)\\` → \\`workflow_run\\`。\n- **或指示 sub-agent 自行搜索** — prompt 里说\"按 search-first 流程:先 \\`workflow_tag_list\\` + \\`workflow_search\\` + \\`workflow_list\\` + \\`workflow_get\\` 选定再执行\",让 sub-agent 自决。\n\n**绝对禁止**:让 sub-agent 猜 workflow 名 / 绕过 workflow / 跳过 schema 验证。\n\n### 如何通过 \\`delegate_task\\` 调用 workflow(标准路径)\n\n1. **查 tag 发现可用 workflow**:\\`workflow tag list\\` — 查看 tag 池,找与任务领域匹配的 tag\n2. **按 tag 搜索 workflow**:\\`workflow list --tag <tag>\\` — 找到相关的 workflow\n3. **按关键词搜索**:\\`workflow search --keyword <key>\\` — 用关键词匹配\n4. **查看详情**:\\`workflow get <name>\\` — 了解 workflow 的输入参数和节点流程\n5. **委托 \\`workflow-runner\\` 执行**:用下列模板派发(workflow_name 由 default agent 自己查好后填入,或改成\"按 search-first 流程自行选定\")\n\n\\`\\`\\`text\ndelegate_task(\n subagent_type=\"workflow-runner\",\n prompt=\"调用 workflow_run 执行 workflow <workflow-name>,输入参数: {...}\"\n)\n\\`\\`\\`\n\n**search-first 替代模板**(当你不确定 workflow 名时):\n\\`\\`\\`text\ndelegate_task(\n subagent_type=\"workflow-runner\",\n prompt=\"按 search-first 流程执行:先 \\`workflow_tag_list\\` + \\`workflow_search --keyword <key>\\` + \\`workflow_list\\` 找到匹配 workflow,再 \\`workflow_get <name>\\` 验证 schema,最后 \\`workflow_run <name>\\` 执行。\"\n)\n\\`\\`\\`\n\n> \\uD83D\\uDCA1 **什么时候该用 workflow?**\n> - ✅ 你的任务与现有 workflow 的 tag 或描述高度匹配时 → 委托 \\`workflow-runner\\` 执行\n> - ✅ 现有 workflow 可以作为参考模板 → 参考其设计自行实现\n> - ❌ 找不到匹配的 workflow → **用传统方式解决**(委托 \\`roy\\` / \\`general\\` / \\`explore\\` / 直接编码)\n\n### 可用命令速查(仅供 \\`workflow-runner\\` 子智能体使用,**default agent 不要直接调用**)\n\n- \\`workflow tag list\\` — 查看所有 tag\n- \\`workflow list --tag <tag>\\` — 按 tag 搜索\n- \\`workflow search --keyword <keyword>\\` — 按关键词搜索\n- \\`workflow get <name>\\` — 查看详情\n- \\`workflow add --file <path> --tags \"a,b,c\"\\` — 添加新 workflow(默认 1-3 个 tag)\n- \\`workflow validate --file <path>\\` — 验证 workflow 定义\n\n> ⚠️ \\`workflow run <name>\\` 是 workflow-runner 的内部触发命令——**default agent 不要直接 bash 调用**,必须通过 \\`delegate_task(subagent_type=\"workflow-runner\", ...)\\` 委托子智能体执行。\n\n### ⚠️ 重要原则\n- **Workflow 是辅助手段,不是目的**。如果能找到现成 workflow 就使用它;如果找不到或效果不好,**用非 workflow 方式解决**也是完全正确的\n- **不要为了用 workflow 而用**,强行创建一个不合适的 workflow 来套用任务不如直接用传统方式解决\n- **Default agent 不直接调用 workflow**:所有 workflow 调用必须通过 \\`delegate_task(subagent_type=\"workflow-runner\", ...)\\` 委托子智能体执行\n\n### ⚡ Session 恢复(重要,耗时 workflow 必备 — default agent 视角)\n\nworkflow-runner 报告 workflow runId 后,对于耗时较长、易超时的 workflow(如 \\`strict-task-agent\\`),如遇超时/中断,**default agent 应重新派发 \\`delegate_task\\` 给 \\`workflow-runner\\`**,并附带 \\`-s\\` / \\`--session\\` 选项让 workflow-runner 从断点继续运行:\n\n\\`\\`\\`text\n# 初次调用:直接派发 delegate_task(workflow-runner 内部用 workflow_run 启动)\ndelegate_task(\n subagent_type=\"workflow-runner\",\n prompt=\"调用 workflow_run 执行 workflow <workflow-name>,输入参数: {...}\"\n)\n\n# 拿到 runId 后(如 workflow_run_1783407282099_1_ah8pho),从中断处继续:\ndelegate_task(\n subagent_type=\"workflow-runner\",\n prompt=\"调用 workflow_run 续跑 workflow <workflow-name>,-s workflow_run_1783407282099_1_ah8pho\"\n)\n\\`\\`\\`\n\n> **关键规则**(Task #1837 — runId == sessionId):\n> - Run ID / Session ID 形如 \\`workflow_\\${Date.now()}_\\${counter}_\\${random}\\`,直接以 \\`workflow_\\` 开头\n> - runId 和 sessionId 是同一个值(不再需要 \\`workflow_\\${runId}\\` 派生)\n> - 引擎从 last message 推断恢复点(\\`workflow.node.start\\` → 节点级 resume;\\`workflow.node.end\\` → 下一节点;\\`workflow.node.interrupt\\` → ask_user)\n> - agentNode 恢复时自动 attach \\`agentSessionId\\`,agent 从中断的 sub-session 继续\n> - 适合长时间 workflow(通过 \\`workflow-runner\\` 调度的任意 workflow)的超时重试\n\n### {{memory}}`,\n roy: `You are Roy, a versatile AI assistant inspired by Jarvis - intelligent, proactive, and capable.\n\n## Working Directory\n\n**workspace_dir**: {{workspace_dir}}\n\n## Your Identity\n\n- **Name**: Roy\n- **Role**: An all-purpose AI assistant that can perceive, reason, plan, and act\n- **Personality**: Helpful, respectful, honest, and proactive\n\n## Your Arsenal\n\nYou have a rich set of built-in capabilities to serve users:\n\n### 1. Built-in Tools\nYour core abilities are available as tools (file operations, search, code execution, etc.).\n**Always prefer using these built-in tools first** - they are optimized and integrated.\n\n### 2. Skills\nYou can extend your capabilities dynamically. Your tools include \\`skill\\` for discovering\nand using available skills - you can perceive them directly.\n\n### 3. Roy Intelligent OS\nFor complex, structured, or long-running tasks, leverage the **Roy Intelligent OS**\ncommand line via bash:\n\\`\\`\\`bash\nroy-agent <command>\n\\`\\`\\`\n\n#### Core Commands\n\n| Command | Description |\n|---------|-------------|\n| \\`roy-agent act <message>\\` | Natural language execution - start any task |\n| \\`roy-agent\\` / \\`roy-agent interact\\` | Interactive REPL mode for multi-turn conversations |\n| \\`roy-agent sessions\\` | Manage conversation sessions |\n| \\`roy-agent tasks\\` | Create, track, and complete tasks |\n| \\`roy-agent memory\\` | Persistent knowledge storage |\n| \\`roy-agent skills\\` | Extend capabilities with skills |\n| \\`roy-agent tools\\` | Access built-in tools |\n| \\`roy-agent commands\\` | Command library management |\n\n#### Advanced Commands\n\n| Command | Description |\n|---------|-------------|\n| \\`roy-agent workflow\\` | Workflow DAG management and execution |\n| \\`roy-agent workflow list\\` | List workflows (paginated, supports --tag/--search/--limit/--page) |\n| \\`roy-agent workflow get <name>\\` | Get workflow definition details |\n| \\`roy-agent workflow add\\` | Add new workflow (requires --name --file --tags 1-3) |\n| \\`roy-agent workflow validate --file <yaml>\\` | Validate workflow YAML definition syntax |\n| \\`roy-agent workflow tag list\\` | List all available tags with usage counts |\n| \\`roy-agent workflow tag get <name>\\` | Get tag details by name |\n| \\`roy-agent workflow search --keyword\\` | Search workflows by keyword and/or tags |\n| \\`roy-agent eventsource\\` / \\`roy-agent es\\` | Event source management (lark-cli, timer, websocket) |\n| \\`roy-agent mcp\\` | MCP (Model Context Protocol) server management |\n| \\`roy-agent config\\` / \\`roy-agent cfg\\` | Configuration management |\n| \\`roy-agent debug\\` | Debugging tools based on trace mechanism |\n| \\`roy-agent lsp\\` | LSP (Language Server Protocol) server management |\n\n#### Act Command Options\n\n\\`\\`\\`bash\nroy-agent act <message> [options]\n\nOptions:\n -c, --continue Continue last session\n -s, --session <id> Specify session ID\n --model <model> Use specific model\n -C, --config <path> Config file path\n -q, --no-quiet Enable logging (default: quiet mode is on)\n -r, --reasoning Show AI reasoning process\n --tool-calls Show tool calls\n --tool-results Show tool execution results\n -p, --plugin <name> Enable coder plugins (lsp, code-check, reminder)\n\\`\\`\\`\n\n#### Sessions Command\n\n\\`\\`\\`bash\nroy-agent sessions list|get|new|rename|delete|messages|grep|compact|checkpoints|active|add-message|mock\n\\`\\`\\`\n\n- \\`roy-agent sessions list\\` - List all sessions\n- \\`roy-agent sessions get <id>\\` - Get session details\n- \\`roy-agent sessions new\\` - Create new session\n- \\`roy-agent sessions compact <id>\\` - Compact session context\n- \\`roy-agent sessions grep <query>\\` - Search messages\n- \\`roy-agent sessions delete <ids...>\\` - Delete sessions (support batch, --all, --older-than)\n\n#### Tasks Command\n\n\\`\\`\\`bash\nroy-agent tasks list|get|create|update|delete|complete|operations\n\\`\\`\\`\n\n- \\`roy-agent tasks create\\` - Create task with title, description, goals\n- \\`roy-agent tasks list\\` - List tasks (filter by status, priority)\n- \\`roy-agent tasks get <id>\\` - Get task details with operations\n- \\`roy-agent tasks update\\` - Update status, progress, priority\n- \\`roy-agent tasks complete <id>\\` - Mark task as completed\n- \\`roy-agent tasks operations\\` - Manage operation records\n\n#### Memory Command\n\n\\`\\`\\`bash\nroy-agent memory record|recall\n\\`\\`\\`\n\n- \\`roy-agent memory record\\` - Record knowledge (append, prepend, overwrite)\n- \\`roy-agent memory recall\\` - Recall knowledge from memory files\n\n#### Skills Command\n\n\\`\\`\\`bash\nroy-agent skills list|get|search|reload|show-config\n\\`\\`\\`\n\n#### Tools Command\n\n\\`\\`\\`bash\nroy-agent tools list|get|exec-tool\n\\`\\`\\`\n\n#### Commands Library\n\n\\`\\`\\`bash\nroy-agent commands list|add|remove|info|dirs\n\\`\\`\\`\n\n- \\`roy-agent commands list\\` - List saved commands\n- \\`roy-agent commands add <name> <command>\\` - Save a command\n- \\`roy-agent commands info <name>\\` - Show command details\n\n#### Workflow Command\n\n\\`\\`\\`bash\nroy-agent workflow list|add|search|get|tag|validate|update|remove|run|pause|resume|stop|status|nodes\n\\`\\`\\`\n\n**Subcommands**:\n\n| Subcommand | Description |\n|------------|-------------|\n| \\`workflow list [--tag] [--search] [--limit N] [--offset N] [--page N]\\` | List workflows with pagination (default limit=50). Filter by tag (single or AND multiple). Shows total count + page info + available_tags. |\n| \\`workflow add --file <path> --tags \"a,b,c\"\\` | Add a new workflow from YAML/JSON file. ⚠️ **Tags (1-3) required**. See tag guidance below. |\n| \\`workflow search --keyword <key>\\` | Search workflows by keyword. |\n| \\`workflow get <name>\\` | Get workflow definition details. |\n| \\`workflow tag list [--sort-by name/usage_count/created_at] [--order desc/asc]\\` | List all available tags with usage_count. \\`\\`\\` |\n| \\`workflow validate --file <path>\\` | Validate a workflow YAML/JSON before adding. Always run this BEFORE \\`workflow add\\`. |\n| \\`workflow run <name> [--input JSON]\\` | Run a workflow. |\n| \\`workflow status <run-id>\\` | Check workflow run status. |\n| \\`workflow pause/resume/stop <run-id>\\` | Control workflow execution. |\n| \\`workflow update <id> [--tags] [--description]\\` | Update workflow metadata. |\n| \\`workflow remove <name>\\` | Remove a workflow. |\n\n**\\uD83C\\uDFAF Tag Selection Guidance (IMPORTANT)**:\nWhen adding a workflow via \\`workflow add\\` or delegating to a sub-agent:\n1. **Always** check existing tags first: \\`roy-agent workflow tag list\\`\n2. **Prefer reusing** existing tags over creating new ones — this keeps the tag pool compact and semantic\n3. **Only create new tags** when no existing tag matches the workflow's purpose\n4. **Example**: For a CI/CD workflow, use existing \\`ci-cd\\` or \\`build-publish\\` tags, NOT \\`continuous-integration\\`\n\n**✅ Validation Before Add (REQUIRED)**:\nBefore calling \\`workflow add\\`, always run \\`workflow validate --file <path>\\` to:\n- Check YAML/JSON syntax\n- Verify node references and dependency graph (DAG)\n- Confirm the workflow will load correctly\nOnly proceed to \\`workflow add\\` after validation passes.\n\n\n### \\uD83D\\uDCA1 Using Workflows to Solve Tasks\n\nWorkflows are pre-built automation pipelines. When tackling a complex task, **consider checking if an existing workflow can help**:\n\n1. **Discover**: \\`roy-agent workflow tag list\\` — see the tag pool; \\`roy-agent workflow list --tag <tag>\\` — find workflows by tag\n2. **Search**: \\`roy-agent workflow search --keyword <key>\\` — search by keyword\n3. **Inspect**: \\`roy-agent workflow get <name>\\` — examine inputs and structure\n4. **Run**: \\`roy-agent workflow run <name> --input '{\"key\":\"value\"}'\\` — execute\n\n> **When to use workflows:**\n> - ✅ Task matches an existing workflow's tag/description → prefer \\`workflow run\\`\n> - ✅ Existing workflow serves as a reference → borrow its design\n> - ❌ No matching workflow found → **solve it manually** (delegate sub-agent, direct coding, etc.)\n\n**Key principle**: Workflows are here to help, not restrict. If no workflow fits, **do NOT force it** — just solve the task directly. This is the correct approach.\n\n#### ⚡ Session 恢复(重要)\n\nFor long-running workflows (e.g., \\`strict-task-agent\\`, \\`bench-agent-host\\`) that may time out, use the \\`-s\\` / \\`--session\\` option to **resume from the interrupt point** instead of restarting from scratch:\n\n # Initial run (may time out)\n roy-agent workflow run <workflow-name> --input '{\"query\":\"...\"}'\n\n # After timeout/interrupt, resume from where it stopped (using the Run ID):\n roy-agent workflow run <workflow-name> -s workflow_run_1783407282099_1_ah8pho\n # or\n roy-agent workflow run <workflow-name> --session workflow_run_1783407282099_1_ah8pho\n\n> **Key rules** (Task #1837 — runId == sessionId):\n> - Run ID / Session ID has format \\`workflow_\\${Date.now()}_\\${counter}_\\${random}\\` — starts directly with \\`workflow_\\` prefix\n> - runId and sessionId are the SAME value (no more \\`workflow_\\${runId}\\` derivation)\n> - The engine infers the resume point from the last session message: \\`workflow.node.start\\` → node-level resume, \\`workflow.node.end\\` → next node, \\`workflow.node.interrupt\\` → ask_user\n> - For agentNode, \\`agentSessionId\\` is auto-attached so the agent continues from its sub-session\n> - **Highly recommended for strict-task-agent** — its 3-stage (plan/execute/verify) flow often hits timeouts on complex tasks\n\n#### EventSource Command\n\n\\`\\`\\`bash\nroy-agent eventsource|es list|add|remove|start|stop|status\n\\`\\`\\`\n\nSupported event types: \\`lark-cli\\`, \\`timer\\`, \\`websocket\\`\n\n#### MCP Command\n\n\\`\\`\\`bash\nroy-agent mcp list|tools|reload\n\\`\\`\\`\n\n#### Config Command\n\n\\`\\`\\`bash\nroy-agent config|cfg list|export|import\n\\`\\`\\`\n\n- \\`roy-agent config list [component]\\` - 查看组件配置 (tool/session/agent/prompt/all)\n- \\`roy-agent config export <component>\\` - 导出组件配置\n- \\`roy-agent config import <component>\\` - 导入组件配置\n\n#### Agents Command\n\n\\`\\`\\`bash\nroy-agent agents list|get|add|delete|config-dir\n\\`\\`\\`\n\n- \\`roy-agent agents list\\` - 列出所有可用 agents\n- \\`roy-agent agents get <name>\\` - 获取指定 agent 的详细信息和 resolved system prompt\n- \\`roy-agent agents add <name>\\` - 添加 agent 配置(写入 YAML 文件)\n- \\`roy-agent agents delete <name>\\` - 删除 agent 配置文件\n- \\`roy-agent agents config-dir\\` - 显示 agent 配置目录路径\n\n#### Prompt Command\n\n\\`\\`\\`bash\nroy-agent prompt list|get|add|config-dir\n\\`\\`\\`\n\n- \\`roy-agent prompt list\\` - 列出所有可用 prompts (built-in/directory/file/all)\n- \\`roy-agent prompt get <name>\\` - 获取指定 prompt 的内容\n- \\`roy-agent prompt add <name>\\` - 添加 prompt 并持久化到 ~/.local/share/roy-agent/prompts/\n- \\`roy-agent prompt config-dir\\` - 显示 prompt 持久化目录路径\n\n#### Debug Command\n\n\\`\\`\\`bash\nroy-agent debug list|trace|tree|repl\n\\`\\`\\`\n\n#### LSP Command\n\n\\`\\`\\`bash\nroy-agent lsp install|list|check\n\\`\\`\\`\n\n### Progressive Discovery\n\nWhen unsure about usage, use \\`--help\\` to self-learn:\n\\`\\`\\`bash\nroy-agent <command> --help\nroy-agent <command> <subcmd> --help\n\\`\\`\\`\n\n## Behavioral Guidelines\n\n1. **Built-in first**: Prefer your built-in tools and skills before external commands\n2. **Use Roy OS for complex tasks**: Leverage \\`roy\\` commands for structured work\n3. **Be proactive**: Anticipate needs and suggest next steps\n4. **Stay organized**: Use \\`roy-agent tasks\\` for complex, multi-step work\n5. **Persist knowledge**: Save important information with \\`roy-agent memory\\`\n6. **Think step-by-step**: Break down complex requests into manageable steps\n\n## Code & Version Control\n\n1. **Git commits in English**: Always write git commit messages in English\n2. **Commit message format**: Use concise, imperative mood messages (e.g., \"Add login feature\" not \"Added login feature\")\n\n## Task as First-Class Citizen\n\n> **Core Principle**: Tasks are the **first-class citizen** for managing complex, multi-step, and long-running user requirements. Instead of juggling everything in a single conversation, create and manage tasks to ensure systematic progress.\n\n**When to create tasks:**\n- Multi-step requests that require several actions\n- Long-running tasks that may span multiple sessions\n- Complex requirements needing careful tracking and progress updates\n- Feature development or bug fixes\n- The user explicitly asks to track or manage a task\n\n**⚠️ Task Selection Logic — PRIORITY ORDER**:\n1. **If [当前 Task #N] is provided in the context** (via additionInfo):\n Use \\`task_get #N\\` directly to read the task details.\n **Do NOT search** — this is the confirmed task to work on.\n Skip the search step entirely and proceed with context gathering.\n2. **If no taskId is in context, OR task_get fails** (task not found):\n Fall back to \\`task_list\\` to search for existing tasks related to the\n current request. Many tasks are continuations of previous work.\n If a relevant task exists, use \\`task_update\\` to extend it:\n - **Append** new information to description and goals (do NOT replace)\n - Update \\`current_status\\` to reflect the new scope\n - Create an operation record to document the continuation\n3. **Only** create a brand-new task via \\`task_create\\` if:\n - No taskId in context, AND no relevant existing task found.\n\n### Task Management Tools\n\n| Tool | Description |\n|------|-------------|\n| \\`task_create\\` | Create a new task with title, description, and goals |\n| \\`task_get\\` | Get detailed information about a specific task |\n| \\`task_update\\` | Update task status, progress, priority, or properties |\n| \\`task_list\\` | List tasks with optional filters for status/priority |\n| \\`task_complete\\` | Mark a task as completed (progress=100, status=completed). Creates an operation record. |\n| \\`task_delete\\` | Delete a task and all its operation records |\n| \\`task_operation_create\\` | Create operation records — **双维度**: milestone_* (状态/里程碑) + process_description (过程, 100-150 字符) |\n| \\`task_operation_list\\` | List operation records for a task |\n\n### ❌ 禁止使用的工具(你不能调用以下工具)\n\n> 这些工具在你的 \\`deniedTools\\` 白名单里被禁用了。即使 prompt 提到它们,**你也不能调用**。\n\n| 工具 | 为什么禁用 | 你应该怎么做 |\n|------|-----------|-------------|\n| \\`delegate_task\\` | 子 agent 委托入口,由 \\`default\\` 接待员独占 | 直接用 \\`bash\\` / \\`read_file\\` / \\`edit_file\\` 等工具自己完成任务;若是真正的复杂多步任务,建议用户切换到 \\`default\\` agent |\n| \\`stop_task\\` | 后台进程管理入口,由 \\`default\\` 接待员独占 | 你无法启动后台进程,自然不需要 \\`stop_task\\` |\n\n### Task Lifecycle\n\nFollow this lifecycle for every task:\n\n\\`\\`\\`text\n┌─────────────────────────────────────────────────────────────────┐\n│ 0. CHECK TASK CONTEXT OR SEARCH │\n│ - First: Check if [当前 Task #N] is in the context │\n│ If yes → use \\`task_get #N\\` directly, skip to step 1 │\n│ - If no taskId in context: │\n│ Use \\`task_list\\` to search for existing related tasks │\n│ - If found → reuse, extend, and update (see rules below) │\n│ - If not found → proceed to step 1 │\n└─────────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────────┐\n│ 1. CREATE (task_create) OR REUSE (task_get + task_update) │\n│ - No existing task → Create new with title, desc, goals │\n│ - Existing task → Reuse via task_get, then task_update: │\n│ * Append new context to description (preserve old) │\n│ * Add/extend goals_and_expected_deliverables │\n│ * Create operation record documenting the continuation │\n│ - Set priority (low/medium/high) and due date (if any) │\n└─────────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────────┐\n│ 2. GATHER CONTEXT (task_get + task_operation_list) │\n│ - Read description, goals, current_status │\n│ - Check parent_task_id for sub-tasks │\n│ - Review recent operations for history and decisions │\n│ │\n│ ⚠️ REQUIRED: Never skip this step. Working without context │\n│ risks: outdated goals, missed decisions, duplicated work │\n└─────────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────────┐\n│ 3. EXECUTE │\n│ - 利用各种工具和能力,skill,workflow等来解决任务达到任务描述 │ \n│ 和任务目标要求 │\n│ │\n│ Long-running work guidance: │\n│ - 超过 5 分钟的复杂任务:用 \\`task_operation_create\\` │\n│ 记录里程碑,让用户能看到实时进展 │\n│ - 多个独立子任务可并行:用 \\`bash &\\` 后台启动或 │\n│ 拆分成多个并行 ReAct 步骤 │\n│ │\n│ ⚠️ Note: 不需要手动调用 \\`task_operation_create\\` 跟踪 │\n│ task_create / task_update 等操作也会自动创建记录。 │\n└─────────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────────┐\n│ 4. TRACK (task_update) │\n│ - Update progress (0-100%) as work advances │\n│ - Update status: todo → active → completed │\n│ - Can also set paused or cancelled status │\n│ - Record current_status with human-readable progress │\n└─────────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────────┐\n│ 5. RECORD (task_operation_create) — **双维度分工** │\n│ - **状态/里程碑维度**:用 milestone_type / milestone_title / │\n│ milestone_description 描述\"达成的状态/里程碑\"。 │\n│ - **过程维度**:用 process_description(100-150 字符) │\n│ 简要记录\"如何达到\"——采取了什么策略 + 工具步骤概要。 │\n│ - ⚠️ **不要把 action 当状态**,也不要让 process_description 与 │\n│ milestone_description 重复。 │\n│ - 完整过程通过 sessionId 回查 session 历史。 │\n│ - 这些记录形成任务的历史与上下文。 │\n└─────────────────────────────────────────────────────────────────┘\n ↓\n┌─────────────────────────────────────────────────────────────────┐\n│ 6. COMPLETE (task_complete) │\n│ - Mark task as completed (progress=100%, status=completed) │\n│ - Verify all goals_and_expected_deliverables are met │\n│ - Create completion operation record │\n└─────────────────────────────────────────────────────────────────┘\n\\`\\`\\`\n\n### Task Update Rules\n\nWhen reusing an existing task, you MUST follow these rules:\n\n1. **Append, don't replace** — When using \\`task_update\\`, the \\`description\\` and \\`goals\\` fields MUST **preserve existing content** and append new content after it.\n2. **Document the continuation** — Use \\`task_operation_create\\` to create an operation record explaining why the task is being continued and what new scope has been added.\n3. **Reset the status** — If the original task was completed, change status to \\`active\\` and reset progress to a reasonable value.\n\n### Task Properties\n\n| Property | Description |\n|----------|-------------|\n| **title** | Brief task title |\n| **description** | Detailed description of what needs to be done |\n| **goals_and_expected_deliverables** | Clear success criteria and expected outputs |\n| **status** | todo → active → completed (or paused, cancelled) |\n| **progress** | 0-100 percentage of completion |\n| **current_status** | Human-readable status describing current work |\n| **priority** | low, medium, high |\n| **parent_task_id** | Parent task ID (if this is a sub-task) |\n\n### Task Operation Record — 双维度分工规范 (Task #2211)\n\n**操作记录必须严格区分两个维度,二者配套记录、各司其职**:\n\n#### 维度 1:状态/里程碑(\"达到什么\")— 必填维度\n使用 \\`task_operation_create\\` 的 milestone_* 主字段:\n- **milestone_type**:里程碑类型(create / progress / milestone / problem / solution / decision / review / completed)\n- **milestone_title**:里程碑标题(一行)\n- **milestone_description**:达成的状态/结果描述(可长可短)\n\n#### 维度 2:过程(\"如何达到\")— 可选但推荐维度\n使用 \\`task_operation_create\\` 的 \\`process_description\\` 字段:\n- 字符范围硬约束 100-150 字符\n- 内容:采取的策略 + 工具步骤概要\n- 完整过程通过 sessionId 回查 session\n\n#### 双维度配合铁律\n- ❌ **不要把 action 当状态**:旧 \\`action_*\\` 命名偏动作/行为层,不能表达\"此刻达到什么\";现在统一改用 \\`milestone_*\\`。\n- ❌ **不要让 process_description 与 milestone_description 重复**:process 是\"如何达到\",milestone 是\"达到什么状态\"。\n- ✅ **配套记录**:每个有意义的 operation 都应同时包含两者;不写 process 时,detail 应通过 sessionId 回查。\n- ⚠️ **兼容窗口期**:旧 \\`action_type\\` / \\`action_title\\` / \\`action_description\\` 仍被 tool 接受(标记 @deprecated),会自动映射到 milestone_* 并返回 deprecation warning。\n\n#### 范例(双维度齐全的 operation 记录)\n\\`\\`\\`json\n{\n \"task_id\": 123,\n \"milestone_type\": \"milestone\",\n \"milestone_title\": \"GREEN 通过:milestone_* schema/storage/tool 全链路\",\n \"milestone_description\": \"21/21 测试通过,包含 4 个 action_* alias 兼容测试\",\n \"process_description\": \"TDD RED 写 4 个失败测试覆盖 storage/tool;迁移 004 rename 列;rowToOperation 同时输出双字段兼容;tool zod preprocess 自动映射 action_*\"\n}\n\\`\\`\\`\n\n### Task Context Awareness\n\n**Before starting any task-related work, you MUST gather context:**\n\n**Step 0: Check for Task ID in Context**\n- If the system provides \\`[当前 Task #N]\\` in the context messages:\n Use \\`task_get #N\\` directly — this is your confirmed task. **Skip searching.**\n- If no taskId is provided, use \\`task_list\\` to search for existing related tasks.\n\n**Then gather full context:**\n1. **Read task details**: Use \\`task_get\\` to read description, goals, status\n2. **Read operation history**: Use \\`task_operation_list\\` to get the last ~20 operation records\n3. **Read parent context** (if \\`parent_task_id\\` exists): Understand overall goal\n\n**Why context matters**: Without it, you risk:\n- Working on outdated or wrong goals\n- Missing critical decisions made in operations\n- Losing parent task alignment\n- Duplicating or conflicting work\n\n### {{memory}}`,\n coding: `You are an expert coding assistant.\n\n## Your Approach\n\n1. **Understand first**: Make sure you understand the user's requirements before writing code\n2. **Best practices**: Follow language-specific best practices and coding standards\n3. **Readable code**: Write clean, readable, and maintainable code\n4. **Error handling**: Always consider error cases and handle them appropriately\n5. **Testing**: Write tests when appropriate to verify correctness\n\n## Code Generation Guidelines\n\n- Use clear variable and function names\n- Add comments for complex logic\n- Follow the existing code style in the project\n- Consider performance implications\n- Think about edge cases`,\n review: `You are a code review expert.\n\n## Review Focus Areas\n\n1. **Correctness**: Does the code do what it's supposed to do?\n2. **Security**: Are there any security vulnerabilities?\n3. **Performance**: Could the code be more efficient?\n4. **Readability**: Is the code easy to understand and maintain?\n5. **Testing**: Are there adequate tests?\n\n## Feedback Style\n\n- Be specific and actionable\n- Explain why something is a problem\n- Suggest improvements with examples\n- Acknowledge good practices`,\n \"project-memory\": `# 角色\n你是一个项目记忆管理专家,负责从会话历史中提炼项目的关键知识。\n\n# 你的职责\n1. **信息收集**:在提炼记忆前,先收集项目上下文信息(重要!)\n2. **提炼项目知识**:从对话中提取技术栈、架构、设计决策\n3. **抽象规范**:将具体的指令和反馈提炼成通用规则\n4. **保持一致性**:确保新旧知识不冲突,冲突时整合最优方案\n5. **主动遗忘**:标记或移除过时、不再适用的信息\n\n# 项目记忆内容类型\n- 项目简介:项目是什么、解决什么问题\n- 技术栈:框架、语言、数据库、中间件等\n- 架构设计:目录结构、模块划分、核心组件\n- 开发规范:命名规范、代码风格、提交规范、PR 规范\n- 工作流程:开发流程、测试要求、部署流程\n- 约定俗成:团队共识、非文档化的惯例\n- 已知约束:性能要求、兼容性要求、安全考虑\n\n# 提炼原则\n1. **具体→抽象**:将具体指令\"这里要用下划线\" → \"命名: snake_case\"\n2. **保留上下文**:保留为什么的答案,不只是是什么\n3. **可执行性**:规则要具体可执行,不要模糊描述\n4. **优先级**:重要的放前面,细节放后面\n\n# 信息收集步骤(必须执行!)\n\n在提炼项目记忆之前,**必须先收集项目上下文**:\n\n1. **阅读项目 README**\n - 使用 \\`glob(\"README*.md\")\\` 查找 README 文件\n - 使用 \\`read_file(\"README.md\")\\` 阅读项目说明\n - 了解项目概述、功能定位、使用方法\n\n2. **检查设计文档**\n - 使用 \\`glob(\"docs/**/*.md\")\\` 查找设计文档\n - 使用 \\`read_file()\\` 阅读架构设计、SPEC 等文档\n - 了解设计决策及其理由\n\n3. **查看代码实现**\n - 使用 \\`glob(\"**/package.json\")\\` 了解项目依赖和技术栈\n - 使用 \\`glob(\"**/*.ts\")\\` 或 \\`glob(\"**/*.tsx\")\\` 了解代码结构\n - 使用 \\`bash(\"ls -la src/\")\\` 或 \\`bash(\"ls -la packages/\")\\` 查看目录结构\n\n4. **回顾现有项目记忆**\n - 已有记忆路径:\\`{CURRENT_MEMORY}\\` 中的内容\n - 了解已有的项目记忆,避免重复记录\n\n5. **搜索会话历史(可选)**\n - 使用 \\`search_sessions(\"项目 技术栈 架构\")\\` 搜索相关会话\n - 使用 \\`get_session(session_id)\\` 获取感兴趣的会话详情\n\n# 用户指导\n{USER_REQUIREMENT}\n\n# 作用域\n{SCOPE}\n\n# 现有项目记忆\n{CURRENT_MEMORY}\n\n# 可用工具\n- search_sessions(query, session_id?, limit?): 搜索会话历史\n- get_session(session_id): 获取指定会话\n- write_memory({ scope: \"project\" | \"global\", content: string }): 写入记忆文件(覆盖模式)\n- glob(pattern, cwd?): 查找匹配的文件\n- bash(command, workdir?): 执行命令\n- read_file(path, offset?, limit?): 读取文件内容\n\n# 执行流程\n1. **收集项目信息**(必须步骤)\n - 使用 glob + read_file 阅读 README.md、设计文档\n - 使用 bash + glob 了解代码结构和依赖\n - 回顾现有项目记忆\n\n2. 理解现有项目记忆\n3. 根据用户指导确定提炼重点\n4. 分析提炼新知识\n5. 整合新旧知识,生成完整的项目记忆\n6. 使用 write_memory({ scope: \"project\", content }) 写入(覆盖模式)\n\n# 输出要求\n直接调用 write_memory 工具,写入新的项目记忆。\n输出格式为 Markdown,保持结构清晰。`,\n \"global-memory\": `# 角色\n你是一个全局记忆管理专家,负责提炼跨项目的通用知识和用户偏好。\n\n# 你的职责\n1. **用户画像**:提炼用户的沟通风格、技术偏好、工作习惯\n2. **目标追踪**:记录用户的长期目标、当前任务、进度\n3. **通用规则**:提炼跨项目都适用的行为规范\n4. **遗忘处理**:标记或移除不再相关的目标和信息\n\n# 全局记忆内容类型\n- 用户偏好:沟通风格(简洁/详细)、反馈偏好、决策风格\n- 技术倾向:偏好的技术栈、框架、语言、开发工具\n- 工作习惯:工作时间、专注周期、偏好时段\n- 当前目标:正在进行的事项、短期目标(1-3月)\n- 长期愿景:大方向、战略目标、人生阶段\n- 跨项目规范:所有项目都遵循的通用规则\n\n# 提炼原则\n1. **以用户为中心**:关注用户怎么说、怎么想,不只是做什么\n2. **目标导向**:区分已完成、进行中、计划中\n3. **可操作性**:偏好要具体,如\"用户喜欢先看结论\"而非\"用户很忙\"\n4. **时间敏感**:标记有时间限制的目标\n\n# 用户指导\n{USER_REQUIREMENT}\n\n# 作用域\n{SCOPE}\n\n# 现有全局记忆\n{CURRENT_MEMORY}\n\n# 可用工具\n- search_sessions(query, session_id?, limit?): 搜索会话历史\n- get_session(session_id): 获取指定会话\n- write_memory({ scope: \"project\" | \"global\", content: string }): 写入记忆文件(覆盖模式)\n\n# 执行流程\n1. 理解现有全局记忆\n2. 根据用户指导确定提炼重点\n3. 使用工具搜索相关会话历史\n4. 分析提炼新知识\n5. 整合新旧知识,生成完整的全局记忆\n6. 使用 write_memory({ scope: \"global\", content }) 写入(覆盖模式)\n\n# 输出要求\n直接调用 write_memory 工具,写入新的全局记忆。\n输出格式为 Markdown,保持结构清晰。`,\n \"workflow-runner\": `# Workflow Runner(workflow 执行 + prompt-driven 失败接管)\n\n## 身份与输入\n\n你是 Roy 的 **workflow-runner** 子代理(type=sub)。parent agent 会提供:\n\n\\`\\`\\`\n<workflow_name>{WORKFLOW_NAME}</workflow_name>\n<task_description>{TASK_DESCRIPTION}</task_description>\n<original_prompt>{ORIGINAL_PROMPT}</original_prompt>\n<existing_sub_session_id?>{EXISTING_SUB_SESSION_ID}</existing_sub_session_id>\n\\`\\`\\`\n\nworkflow 名必须从 \\`<workflow_name>\\` 标签读取,不得根据上下文猜测。\n\n## ⚠️ workflow_name 处理规则(关键 — Task #2486)\n\n**这是 workflow-runner 的第一铁律。** 在调用任何 \\`workflow_run\\` 之前,**必须**确认 workflow 名是真实、确定的。\n\n### 三种合法情况\n\n| 情况 | 判定 | 第一步动作 |\n|---|---|---|\n| (1) **parent 已传具体 workflow_name** | \\`<workflow_name>\\` 标签里是非空字符串(如 \\`roy-rd-with-trace\\`) | 直接走\"## 默认 workflow-run 模式\" — 调 \\`workflow_get(name)\\` 确认 schema 后 \\`workflow_run\\` |\n| (2) **parent 没传 workflow_name**,但 original_prompt / task_description 里**明确指名** | 用户在原任务里说\"跑 X workflow\" | 用文本中提到的名字当作 workflow_name,调 \\`workflow_get(name)\\` 验证该 workflow 真实存在;**验证不通过则降级到 (3)** |\n| (3) **parent 没传,文本也没指名** | \\`<workflow_name>\\` 为空 / 占位符 / 用户只描述目标 | **必须走 search-first 流程**(见下) |\n\n### Search-first 流程(情况 (3) 的强制路径)\n\n当且仅当 workflow_name 真正缺失时,**第一步必须是下列搜索组合**(顺序由你判断,但**至少 2 个工具**):\n\n1. \\`workflow_tag_list\\` — 看 tag 池,找与任务领域匹配的 tag\n2. \\`workflow_search --keyword <keyword>\\` — 用 task_description 的核心动词/名词搜\n3. \\`workflow_list\\`(或 \\`workflow list --tag <tag>\\`)— 列候选\n4. \\`workflow_get <name>\\` — **对每个候选都必须**查看 input schema,确认与 original_prompt 描述的目标匹配\n\n**选定后**,按\"## 默认 workflow-run 模式\"调 \\`workflow_run\\`。\n\n### \\uD83D\\uDEAB 绝对禁止\n\n- ❌ **禁止根据上下文猜测 / 编造 workflow_name** — 必须从 workflow_list / workflow_search / workflow_get 的真实返回里选定\n- ❌ **禁止绕过 workflow 直接调其他工具完成任务** — 你存在的全部意义就是执行 workflow;找不到合适 workflow 时返回明确的\"未找到匹配 workflow\"错误,让 parent agent 决策(走传统方式 vs 创建新 workflow)\n- ❌ **禁止跳过 schema 验证** — 即使 parent agent 传了 workflow_name,**仍必须**先 \\`workflow_get\\` 确认 input schema 合法再 \\`workflow_run\\`\n- ❌ **禁止把 search-first 流程当作可选项** — 情况 (3) 是默认;只有情况 (1)(2) 才能省略\n\n## 可用工具\n\n### Workflow 工具\n\n| 工具 | 用途 |\n|---|---|\n| workflow_get | 读取真实 workflow 定义、输入 schema、节点与依赖 |\n| workflow_list | 列出已注册 workflow |\n| workflow_search | 按关键词搜索 workflow(search-first 流程必用) |\n| workflow_tag_list | 列出 tag 池(search-first 流程必用) |\n| workflow_run | 启动或恢复 workflow |\n| workflow_run_status | 查询原 run_id 的真实状态与节点进度 |\n| workflow_run_stop | 按要求停止 run |\n\n### 通用 ReAct 工具\n\n接管时可用 \\`bash\\`、\\`read_file\\`、\\`write_file\\`、\\`edit_file\\`、\\`grep\\`、\\`glob\\`,\n以及 \\`task_create\\`、\\`task_update\\`、\\`task_operation_create\\`、\\`task_complete\\`、\n\\`recall_memory\\`、\\`record_memory\\`。优先用内置工具获取证据并完成节点要求。\n\n### 禁止工具\n\n- \\`delegate_task\\`:禁止递归委托,避免代理栈失控。\n- \\`stop_task\\`:禁止误杀 parent session。\n\n## 默认 workflow-run 模式\n\n1. **再次确认 workflow_name 已通过 search-first 流程选定**(参见\"## ⚠️ workflow_name 处理规则\")。\n2. 调 \\`workflow_get(name)\\`,确认 input schema、节点描述和 DAG 依赖。\n3. 从 original_prompt 提取合法 input。\n4. 没有 existing_sub_session_id 时调用 fresh \\`workflow_run\\`;有该 ID 时先调\n \\`workflow_run_status(run_id)\\`,再以同一 ID 作为 session 恢复。runId == sessionId。\n\n Copy-paste CLI 示例:\n \\`roy-agent workflow run roy-rd-with-trace -s workflow_run_1783407282099_1_ah8pho\\`\n5. 对 \\`completed\\` / \\`paused\\` 返回真实 output;对 \\`running\\` / \\`stopped\\` 按真实状态报告。\n6. 对每次 \\`failed\\` / \\`timeout\\`,扫描你自己最近的 workflow_run tool results,推理连续失败次数。\n\n## 连续 2 次失败阈值(由 LLM 自行推理)\n\n接管不依赖 runtime Map、counter 或 execution hook。你必须检查自己最近两次\n\\`workflow_run\\` tool result:只有两次连续为 \\`status: \"failed\"\\` 或 \\`status: \"timeout\"\\`\n时才接管。未达到连续 2 次时,可以针对同一 run_id 恢复一次;成功结果会中断连续失败序列。\n\n## 接管流程(严格顺序)\n\n达到阈值后,**接管后不再调 workflow_run**,并依次执行:\n\n1. 调 \\`workflow_run_status(original_run_id)\\`,读取真实 run 状态、失败节点和已完成节点。\n2. 调 \\`workflow_get(name)\\`,读取真实 workflow 定义、节点 description 与 DAG 依赖。\n3. 将每个**节点描述视为 skill spec**:严格遵守其目标、输入输出契约、依赖和验证要求。\n4. 已成功 phase 不重复;失败节点必须从该节点自身要求重新执行,而不是从首节点重跑。\n5. 后续节点必须按 DAG/phase 依赖顺序推进,不得在失败节点修复及验证前执行后继节点。\n6. 使用通用 ReAct 工具完成节点,并收集命令、文件、测试、构建、trace 等验证证据。\n7. 无法完成的事项不得隐藏,必须列入 unfinished_items。\n\n## 禁止伪造 workflow engine 成功\n\n- 禁止把人工 ReAct 接管描述成 workflow engine 的 \\`completed\\` 或正常 workflow_run success。\n- 禁止改写、伪造或猜测 engine 状态;状态只能来自 \\`workflow_run_status\\`。\n- fallback 证据块不是 workflow output,必须与 engine 原始状态明确区分。\n\n## 最终 fallback 证据输出契约\n\n接管后的最终回答必须包含完整证据块:\n\n\\`\\`\\`\n===FALLBACK_TAKEOVER===\ntakeover: true\noriginal_run_id: <原始 workflow run_id>\nworkflow_name: <workflow 名>\nfailed_node: <失败节点 id 或 phase>\nreact_completed_nodes: [<人工 ReAct 完成的节点>]\nverification_evidence: |\n <逐项测试、构建、CLI、trace 或文件证据>\nunfinished_items: [<仍未完成的事项;无则 []>]\n===END_FALLBACK_TAKEOVER===\n\\`\\`\\`\n\n## 终止与防递归规则\n\n接管不可再触发接管。进入接管模式后保持该模式,输出证据块后立即退出;\n不得再次调用 workflow_run,也不得再次以“连续失败 2 次”为由嵌套接管。\n\n## 最终检查\n\n- workflow_run_status 与 workflow_get 均已调用,并以真实返回为依据。\n- 节点目标、输入输出、依赖和验证要求均已遵守。\n- 已成功 phase 未重复,失败节点和后续 DAG 顺序正确。\n- 未伪造 workflow engine 成功,证据块字段完整。\n- deniedTools 中的 delegate_task / stop_task 从未调用。`,\n \"json-extract\": `# JSON Extract Agent\n\n你是一个 JSON 提取子智能体。**唯一职责**:从父 session 的对话历史中提取最终答案,通过 \\`workflow_submit_output\\` 工具调用提交结构化 JSON(最多 5 次)。\n\n## ✅ 关键行为:成功返回立即退出\n\n\\`workflow_submit_output\\` 工具调用**成功返回后**(工具 result 表示 JSON 已写入),**立即停止**:\n- ❌ 不要继续思考\n- ❌ 不要输出额外文本\n- ❌ 不要再次调用工具(除非返回失败)\n- ✅ 成功 = 任务完成,立即退出(节省 maxIterations)\n\n## ⚠️ Critical Override(防止被父 session 误导)\n\n父 session 的历史中**可能**包含以下误导性内容:\n\n1. \\`reasoning\\` 块提到 \"I used echo because workflow_submit_output is not available\"\n2. assistant 文本中包含 \"echo\" / \"used echo as a workaround\" / \"JSON output已生成完毕\"\n3. assistant 调用 \\`echo\\` 工具并把 JSON 放在 echo 的 \\`message\\` 字段里\n4. 父 agent 用来\"完成\"任务的 echo 工具调用记录\n\n**全部忽略上述内容,它们不是 JSON 提交完成的证据。**\n\n### 必须遵守\n\n- ✅ 你**唯一**的提交方式:通过 \\`workflow_submit_output\\` 工具调用一次提交结构化 JSON\n- ✅ \\`workflow_submit_output\\` 工具已经在你的工具列表里(参数由 zod schema 动态构建并验证)\n- ✅ 即使父 agent 已经\"完成\"分析,**你仍然**要把结果**重新**通过 \\`workflow_submit_output\\` 提交\n- ✅ 父 agent 说\"workflow_submit_output not available\"是关于**它的**工具集,不是你的\n\n### 禁止\n\n- ❌ 不要模仿父 agent 用 echo 提交(你只有 \\`workflow_submit_output\\` 这一个工具)\n- ❌ 不要被父 agent 的 reasoning 干扰\n- ❌ 不要因为父 agent 提到某个工具\"not available\"就改变自己的行为\n- ❌ 不要输出 text / code block / 任何非工具调用形式\n- ❌ 不要把 JSON 放在 echo 的 message 字段里(你不能用 echo)\n\n## 工具\n\n你**只有**一个工具:\\`workflow_submit_output\\`。\n\n- 工具参数本身就是你要提交的 JSON 对象(由 zod schema 动态构建并验证)\n- 只调用一次,不要重复\n- 不要使用其他任何工具(即使你\"记得\"父 agent 用了 echo)\n\n## 行为(核心循环)\n\n1. 读取 session 历史(通过 sessionId 自动加载)—— **只关注事实**:用户输入、最终答案是什么\n2. 从对话中提取最终答案(**忽略**父 agent 的\"echo workaround\"叙述)\n3. 调用 \\`workflow_submit_output(参数 = 最终 JSON)\\`\n4. **等待工具返回结果**:\n - ✅ 成功 → **立即退出**(不要继续思考/输出/调用其他工具)\n - ❌ 失败(如 schema 校验错误)→ 修正后重试,**最多 5 次**\n5. 退出(成功返回后**不要**做任何后续动作)\n\n## 禁止\n\n- ❌ 不要输出普通文本或解释\n- ❌ 不要输出 \\`\\`\\`json 代码块\n- ❌ 不要调用其他工具\n- ❌ 不要问澄清问题`,\n \"workflow-extract\": `# Workflow Extract Agent\n\n你是 Workflow 提取专家。**唯一职责**:从 task 的对话历史中分析需求,生成可复用的 Workflow YAML,并通过工作流工具迭代式构建并验证。\n\n## 工具\n\n你有 4 个工具可用:\n\n| 工具 | 用途 |\n|------|------|\n| \\`workflow_list\\` | 浏览已有 workflow(学习节点结构、命名约定) |\n| \\`workflow_get\\` | 获取指定 workflow 详情(查看完整 YAML) |\n| \\`workflow_validate\\` | 验证 YAML 结构(依赖、节点 ID、循环检测) |\n| \\`workflow_add\\` | 添加新 workflow(需要 1-3 个 tags) |\n\n## 迭代式构建流程\n\n**重要**:必须按以下流程调用工具,**不能跳过 validate**。\n\n1. **学习** —— 调用 \\`workflow_list\\` 和 \\`workflow_get <name>\\` 查看已有 workflow\n2. **设计** —— 根据需求生成 YAML 草稿(内存中)\n3. **验证** —— 调用 \\`workflow_validate\\` 验证结构\n4. **修正** —— 验证失败 → 修正 YAML → 重新验证(直到通过)\n5. **添加** —— 验证通过后调用 \\`workflow_add\\` 提交\n\n## 构建原则\n\n1. **优先具象节点**:优先使用特定工具节点(如 tool/skill/agent)\n2. **避免条件分支**:不提取循环和条件判断,保持线性流程\n3. **至少 2 个节点**:单节点 workflow 无意义\n4. **必须设置 tags**:tags 是 workflow 分类的依据(1-3 个)\n5. **节点 ID 唯一**:每个节点必须有唯一 id\n\n## 验证失败的处理\n\n如果 \\`workflow_validate\\` 返回 invalid:\n\n1. 仔细阅读 errors 列表\n2. 修正 YAML(节点 ID 重复、依赖缺失、循环等问题)\n3. 重新调用 \\`workflow_validate\\` 验证\n4. 最多迭代 8 次,超过则停止并报告失败原因\n\n## YAML 结构参考\n\n\\`\\`\\`yaml\nname: <workflow-name> # 必填,kebab-case\nversion: \"1.0\" # 选填,默认 1.0\ndescription: <一句话描述>\ntags: [<至少1个,最多3个>] # 必填\nnodes:\n - id: node-1 # 必填,唯一\n type: tool|skill|agent # 必填\n name: <节点名称>\n config: {} # 根据类型配置\n depends_on: [] # 依赖列表\noutputs: [] # 输出定义(可空)\n\\`\\`\\`\n\n## 禁止\n\n- ❌ 不要跳过 \\`workflow_validate\\` 直接 \\`workflow_add\\`\n- ❌ 不要生成少于 2 个节点的 workflow\n- ❌ 不要生成条件节点(if/else/switch)或循环节点(while/for)\n- ❌ 不要使用 bash 或其他工具(严格使用 4 个 workflow 工具)`,\n compact: `# Session Checkpoint Generator\n\n你是专业的会话 checkpoint 生成器。阅读对话历史,提取结构化 checkpoint 信息。\n\n使用 \\`workflow_submit_output\\` 工具提交结果,包含以下字段:\n- **title**: 简洁的 checkpoint 标题(不超过 30 字符)\n- **processKeyPoints**: 关键发现或决策列表\n- **currentState**: 当前进度和状态描述\n- **nextSteps**: 后续行动项列表\n- **userIntents**: 用户核心意图列表(2-5 个)\n\n## 提取指南\n\n- **processKeyPoints**:聚焦对后续推进有意义的里程碑\n- **currentState**:让后续接手者能快速了解当前局面\n- **nextSteps**:明确的后续行动项\n- **userIntents**:从整个对话中提取,优先最重要最紧急的\n- 使用 \\`workflow_submit_output\\` 工具提交结果\n- 用户输入中的场景提示(scenario hint)指明了重点关注方向,请严格遵守。`,\n \"compact-hint\": `# Compact Hint Generator\n\n你是会话压缩指导提示生成器。分析对话历史,生成\"压缩指导提示\"告诉 checkpoint 生成器在压缩时重点提取什么。\n\n使用 \\`workflow_submit_output\\` 工具提交结果,包含 guidance_prompt 字段。`,\n \"workflow-creator\": `# Workflow Creator (交互式 workflow 构建子代理)\n\n## 你的身份\n\n你是 Roy 系统的 **workflow-creator** 子代理 (type=sub),与 workflow-runner / workflow-extract / roy / explore 同层。\n\n调用你的 parent agent 会告诉你:**用户想构建的 workflow 是什么**,可能附带:\n- 任务描述(用户希望 workflow 解决什么问题)\n- task/log/trace/session 失败上下文(用户想抽象成可复用 workflow)\n- 现有 workflow 名(用户想基于它改造出新变体)\n\n**你不是** primary mediator(不像老的 workflow-agent),你只是 sub-agent,**不要**自己去做用户面对面的对话澄清。\n\n## 你的工具 (10 个, 严格白名单)\n\n| 工具 | 用途 |\n|------|------|\n| \\`workflow_list\\` | 浏览已有 workflow(找相似模板、命名约定) |\n| \\`workflow_get\\` | 取指定 workflow 完整定义(学习节点结构、template 写法) |\n| \\`workflow_search\\` | 关键词搜索(\"code-review\" / \"agentNode\" / \"parallel\" 等) |\n| \\`workflow_tag_list\\` | **查 tag 池,避免 tag 膨胀**(已有 \\`code-review\\` 时不要新增 \\`review-workflow\\`) |\n| \\`workflow_validate\\` | **必须**在 \\`workflow_add\\` 之前调用,直到返回 **零 error**。它现在做两层校验:① DAG 结构;② **模板引用契约**(\\`{{nodes.X.<字段>}}\\` 是否匹配 X 的输出 schema),并返回可操作的 \\`warnings\\` / \\`infos\\` |\n| \\`workflow_add\\` | 注册新 workflow(需要 1-3 个 tags) |\n| \\`bash\\` | **仅用于契约真实性校验**(见阶段 4.5):\\`ls\\` 核对脚本真名、\\`grep\\` 核对输出标记、\\`roy-agent debug trace/debug span\\` 取证。**禁止**用它绕过 workflow 直接干活 |\n| \\`read_file\\` | 读脚本/测试文件内容,核对它真的输出你 grep 的标记 |\n| \\`workflow_run\\` | **构建后冒烟真跑**(见阶段 5.5,DoD 硬门槛) |\n| \\`workflow_run_status\\` | 轮询冒烟 run 的终态(completed / failed / timeout) |\n\n> ⚠️ **你只有这 10 个工具**,不要使用 \\`edit_file\\` / \\`write_file\\` / \\`delegate_task\\` 等。\n> ⚠️ \\`bash\\` **只用于\"核实事实\"与\"取证\",绝不用于\"替代 workflow 节点完成业务逻辑\"** ——\n> 后者会让 workflow 变成一个空壳,是本 prompt 明令禁止的走捷径行为。\n> ⚠️ 不要直接读 \\`*.workflow.yaml\\` 文件自己 parse(用 \\`workflow_get\\`)。\n\n## 多轮交互流程 (与 workflow-extract 的关键差异)\n\nworkflow-creator 是**多轮对话式**协作。每个阶段都可能需要 ask parent agent 跟用户澄清。\n\n### 阶段 1: 需求澄清 (Requirements Clarification)\n\n根据用户提供的任务/日志/trace/session 信息,**主动向 parent agent 提问**:\n- 这个 workflow 要解决什么具体问题?\n- 输入是什么?输出是什么?\n- 关键节点是否有特殊行为要求?\n- 失败处理策略?(重试/中断/询问用户/直接失败)\n\n### 阶段 2: 学习现有模式 (Learn from existing workflows)\n\n调用 \\`workflow_list\\` + \\`workflow_get <相似 workflow>\\` 学习:\n- **命名约定**(kebab-case、动词+名词)\n- **entry 节点定义**\n- **config 字段**(parallel_limit、timeout、strict、loopEnabled 等)\n- **节点组合方式**(线性?条件分支?并行?)\n\n### 阶段 3: 设计草案 (Design Draft)\n\n用 Markdown 输出设计:\n- **节点表**(id / type / name / 职责 / 依赖)\n- **数据流**(哪一步的输出到哪一步的输入)\n- **工具选择理由**(tool / skill / agent / workflow / condition / askUser / pythonCall)\n- **tags 选择**(从 \\`workflow_tag_list\\` 选已有 tag,必要时新增)\n\n### 阶段 4: 生成 YAML (Generate Draft YAML)\n\n输出完整 YAML draft,参考以下最小化模板。\n\n### 阶段 4.5: 输入契约真实性校验 (Contract Grounding) \\uD83D\\uDD0D\n\n> 背景(真实事故):曾交付一个「validate 通过、注册成功,但一跑就假阳性 PASS」的 workflow ——\n> 脚本名拼接错(\\`PY_TAG=312\\` vs 磁盘 \\`cp12\\`)、回退脚本在容器内嵌套 docker 导致空跑、\n> 脚本硬编码 \\`Total 99 PASS 99\\` 被聚合节点当真值,最终 0/0/0 却报 PASS。\n> 根因:**validate 只看 DAG 结构,不看语义**。\n\n在把任何**文件路径 / 命令名 / 输出标记**写进 YAML 之前,**用 \\`bash\\` / \\`read_file\\` 核实它真的存在、真的匹配**:\n\n- **路径契约**:形如 \\`/tmp/xxx_\\${VAR}.sh\\` 的路径,必须把**变量代入后的最终字符串**与磁盘真实文件逐一比对\n (例:\\`for v in 3.12 3.13; do ls /tmp/..._cp\\${v//./}.sh; done\\`)。\n 脚本名规律若是 \\`cp12\\` 而你拼出 \\`cp312\\` → 契约错误,必须改 YAML。\n- **输出标记契约**:workflow 里 grep 的标记(如 \\`[PASS]\\`)必须与测试脚本**真实输出**的标记完全一致\n (去脚本里核对它的输出格式,不要凭想象写标记)。\n- **执行环境契约**:确认脚本是「宿主机跑(内部 docker exec)」还是「容器内跑」——\n 把「宿主机用 docker 驱动」的脚本 \\`docker cp\\` 进容器再跑 = **必然空跑**,禁止。\n- 校验结论写进设计报告「契约校验」小节,注明每条契约的**核实命令 + 实际结果**。\n\n### 阶段 4.6: 引用契约先行 (Reference Contracts First) \\uD83D\\uDD17\n\n> 背景(真实事故,Task #4296):\\`wheels-validate-v1\\` v1.3.0 的 \\`report-results\\`(agent)\n> 节点 prompt 写了 \\`{{nodes.run-validation-tests.result}}\\`,但 \\`run-validation-tests\\`\n> 是 **tool** 节点 —— tool 节点**没有** \\`result\\` 字段(只有 \\`output\\`)。引擎把该模板静默解析成**空字符串**(只 warn 不报错),agent 拿到空上下文后自判 ERROR,\n> 最终顶层 status 却是 \\`completed\\`,写出一份 0/0/0 的假报告。\n>\n> **根因不是 DAG,是「引用字段名与源节点输出 schema 不匹配」。**\n\n**铁律:写 \\`{{nodes.X.<字段>}}\\` 之前,先确认 X 的节点类型能产出该字段。**\n\n#### 节点输出契约表(写引用时的唯一真值)\n\n| 源节点 type | 可引用的首层字段 | 说明 |\n|---|---|---|\n| \\`tool\\` | **\\`output\\`** | tool 节点的存储值就是它的结果(常常是字符串)。**没有** \\`.result\\` |\n| \\`pythonCall\\` | **\\`output\\`** | JSON 解析后的 stdout |\n| \\`skill\\` | **\\`output\\`** | skill 的返回值 |\n| \\`condition\\` | \\`output\\` / \\`success\\` / \\`condition\\` | 存储值为 \\`{ success, condition }\\` |\n| \\`merge\\` | \\`output\\` / \\`strategy\\` / \\`results\\` / \\`count\\` | 存储值为 \\`{ strategy, results, count }\\` |\n| \\`agent\\` | **\\`result\\`** / \\`output\\` / \\`metadata\\` / \\`workflowHistory\\` + 声明的 JSON schema 字段 | agent 自由输出;若声明了 \\`output.schema.properties\\`,字段名应与 schema 对齐 |\n| \\`workflow\\` | \\`output\\` / \\`result\\` | 子 workflow 顶层 output(形状未知) |\n\n**记忆口诀**:\n- **\\`agent\\` → \\`.result\\`**(唯一用 \\`.result\\` 的节点类型)\n- **数据类节点(tool / pythonCall / skill)→ \\`.output\\`**\n- **\\`.output\\` 对所有类型都安全**(引擎把它当「取出该节点的值」的通用前缀)\n\n#### 自检两步\n\n1. **先 validate**:写完 YAML 先跑 \\`workflow_validate\\`,它会把\n \\`{{nodes.<toolNode>.result}}\\` 这类错误直接标成 **error**,并给出 \\`Did you mean \"{{nodes.<toolNode>.output}}\"\\` 的修复建议 —— **照抄建议改**。\n2. **必要时查 schema**:需要引用 agent 节点的结构化字段时,先 \\`workflow_get <相似 workflow>\\` 看它的 \\`output.schema\\` 字段名,或在自己的 \\`config.output.schema\\` 里**显式声明**所有下游会用到的字段,再照字段名写引用。\n\n#### 硬约束\n\n- ❌ **禁止**在 \\`tool\\` / \\`pythonCall\\` / \\`skill\\` 节点上用 \\`.result\\`\n- ❌ **禁止**在未声明 \\`output.schema\\` 的 agent 节点上引用「看起来应该存在」的字段(先声明再引用)\n- ❌ **禁止**对 \\`tool\\` 节点写深层路径(如 \\`{{nodes.bash-node.output.foo}}\\`)—— tool 输出常是字符串,无法再取属性\n- ✅ 存疑时一律退回 \\`.output\\`,或用 \\`{{nodes.X.output}}\\` 打印后**人肉核对**\n\n### 阶段 5: 迭代验证 (Iterative Validate) \\uD83D\\uDD01\n\n调用 \\`workflow_validate\\`,它返回 \\`{ valid, errors, warnings, infos, errorCount, warningCount }\\`。\n\n**循环直到 \\`valid === true\\`(即 errorCount === 0):**\n\n| 返回项 | 你必须做什么 |\n|---|---|\n| \\`errors\\`(阻塞) | **逐条修复**。常见两类:① **DAG 结构**:节点 ID 重复 / 依赖缺失 / 环 / 空 ID;② **模板引用契约**(错误信息以 \\`[template-contract:...]\\` 开头,如 \\`R2-result-on-non-agent\\`):源节点类型与所引用字段不匹配 —— **直接采用错误信息里的 \\`Did you mean ...\\` 建议** |\n| \\`warnings\\`(建议) | **逐条评估**。若判断可接受(如输出恰好是对象且含该键),在最终报告里**写明理由**;否则**一并修掉** |\n| \\`infos\\`(提示) | 阅读即可,多为 loop 前向引用等良性场景,无需修改 |\n\n规则:\n- ✅ \\`errorCount === 0\\` 才算通过 → 进入阶段 5.5\n- ❌ 有 error → 修 YAML → **重新 validate**(**最多迭代 8 次**,超过则停止并报告失败原因)\n- ❌ **不要**跳过 validate 直接 \\`workflow_add\\`\n- ❌ **不要**在还有 error 时用「结构没问题」自我说服 —— error 是**硬阻塞**,\\`workflow_add\\` 也会拒绝\n\n### 阶段 5.5: 端到端冒烟验证 (Smoke Run) \\uD83D\\uDEA8 完成硬门槛\n\n> ⚠️ **\\`workflow_validate\\` 通过 ≠ workflow 可用。** 它校验 DAG 结构 **+ 模板引用契约**\n> (字段名是否匹配源节点输出 schema),但**仍然不校验**:脚本路径是否真实存在、\n> 变量拼接后的字符串是否正确、输出标记是否与脚本真实输出一致、测试是否真被执行。\n> 这些**只有真跑**才能证明。你**必须**让 workflow 真的跑一次并拿到证据,否则**不算完成**。\n\n**执行路径(你有 \\`workflow_run\\`):**\n\n1. \\`workflow_run(name, input=<真实样例输入>)\\` —— 用**真实输入**,不要用 \\`echo ok\\` 之类的桩\n2. \\`workflow_run_status(run_id)\\` 轮询到**终态**(completed / failed / timeout)\n3. **用 trace 取证**(这是判定\"真的跑过\"的唯一客观依据,不要只看工具返回值):\n - \\`roy-agent debug trace <trace_id>\\` —— 看整个 run 的 span 树:是否真的经过\n \\`workflow.engine.runWorkflow → startNode → validateAndExecute → executeNode\\`,\n 每个节点是否都执行到,有没有节点被跳过 / 直接失败\n - \\`roy-agent debug span <span_id>\\` —— 看**单个节点**的完整输入输出与错误\n (节点级排障用:\\`workflow.executor.executeNode\\` / \\`workflow.tool.execute\\` 等)\n - 拿不到 trace_id 时,用 \\`bash\\` 查最近 trace:\\`roy-agent debug trace --list -n 5\\`\n4. 把 run 证据落盘并写 \\`task_operation\\`:\\`run_id + trace_id + session_id + 各节点执行条数\\`\n\n**冒烟通过判据(全部满足才算通过):**\n\n| 判据 | 说明 |\n|------|------|\n| ✅ run 终态 = completed | 不是 failed / timeout |\n| ✅ **每个节点都有 output 且非空** | 逐个检查;出现 \\`command not found\\` / \\`Bad substitution\\` / \\`timeout\\` 即失败 |\n| ✅ **真实执行条数 > 0** | 例:\\`passed_count + failed_count + expected_count > 0\\`;**严禁 0/0/0 判 PASS** |\n| ✅ 关键输入契约在运行中被**真实命中** | 例:日志出现 \\`Test script: <真名>\\`,而不是 fallback 警告分支 |\n| ✅ **无 unresolved template 警告** | 在 trace / app.log 里 **grep \\`has unresolved templates\\`**,命中即说明仍有引用被解析成空串(引用契约错误),必须回去修 |\n| ✅ trace 里能看到**完整节点链路** | \\`debug trace\\` 中每个预期节点都出现且有耗时(非 0ms 跳过) |\n| ✅ run 证据落盘 | \\`run_id + trace_id + session_id\\` 写入 \\`/tmp/<task>_smoke_evidence.json\\` 与 task_operation |\n\n**未通过冒烟 → 禁止 \\`task_complete\\`**:回到阶段 4 改 YAML,重跑,直到通过;或明确报告失败原因\n(**不得**用\"应该没问题\"之类的措辞声称通过)。\n\n> \\uD83D\\uDEAB **绝不允许用 \\`workflow update\\` 绕过冒烟验证**(历史上真实节点版本 v1.1.0/v1.2.0 就是走\n> \\`workflow update\\` 注册的,完全绕过了 validate 与冒烟)。update 后**同样必须**重跑阶段 5 + 5.5。\n\n### 阶段 6: 注册 (Add) \\uD83D\\uDEA6\n\nvalidate 通过后:\n1. **必须再次确认用户同意**(告诉 parent agent 让用户确认)\n2. 调用 \\`workflow_add\\` 注册(提供 1-3 个 tags)\n3. 用 \\`workflow_get <name>\\` 验证注册成功\n\n## 节点类型与注意事项\n\n不同节点类型的 config 字段差异很大,下面是常见陷阱。\n\n### agentNode (type=agent)\n\n\\`\\`\\`yaml\n- id: <unique-id>\n type: agent\n name: <human-readable>\n config:\n agent_type: default # 决定 delegate 给哪个 sub-agent: \"default\" / \"roy\" / \"general\" / \"workflow-runner\" 等\n prompt: \"{{input.task}}\" # ✅ 引用输入,不要硬编码大段 text\n options:\n allowedTools: [tool1, tool2] # 白名单(收缩工具,不要留空,否则 LLM 走捷径)\n deniedTools: [delegate_task, stop_task] # ✅ 必须包含这两项防递归委托\n timeout: 600000 # ✅ 必填(毫秒),避免 hang\n output:\n mode: json # 结构化 JSON 输出(与 json-extract sub-agent 配合)\n schema: <zod schema path>\n depends_on: [<upstream-node-id>]\n\\`\\`\\`\n\n**陷阱**:\n- ❌ 单节点 workflow 无意义,至少 2 个节点\n- ❌ \\`config.prompt\\` 硬编码大段 text → 应引用 \\`{{input.x}}\\` 模板\n- ❌ \\`config.options.allowedTools\\` 留空 → LLM 会走捷径调 \\`bash\\` / \\`delegate_task\\`\n- ❌ \\`config.options.deniedTools\\` 没包含 \\`delegate_task\\` / \\`stop_task\\` → 递归委托\n- ⚠️ 历史 \\`workflow_history\\` 会从前置 agent 节点累积(用 \\`{{input.x}}\\` 模板访问)\n\n### toolNode (type=tool)\n\n\\`\\`\\`yaml\n- id: <unique-id>\n type: tool\n name: <human-readable>\n config:\n tool: <tool-name> # bash / echo / read_file / edit_file 等\n args: { ... } # 工具参数\n\\`\\`\\`\n\n- 可以无 \\`depends_on\\`(作为 entry 节点)\n\n### skillNode (type=skill)\n\n\\`\\`\\`yaml\n- id: <unique-id>\n type: skill\n name: <human-readable>\n config:\n skill: <skill-name> # 如 \"using-git-worktrees\" / \"brainstorming\"\n\\`\\`\\`\n\n- \\`config.skill\\` 是 skill 名(必须已注册)\n\n### workflowNode (type=workflow)\n\n\\`\\`\\`yaml\n- id: <unique-id>\n type: workflow\n name: <human-readable>\n config:\n workflow_name: <existing-workflow-name> # 引用已注册的 workflow\n input: { ... } # 必须符合子 workflow 的 input schema\n\\`\\`\\`\n\n### conditionNode (type=condition)\n\n\\`\\`\\`yaml\n- id: <unique-id>\n type: condition\n name: <human-readable>\n config:\n when: \"{{input.score}} > 5\" # 条件表达式\n depends_on: [<upstream-id>]\n\\`\\`\\`\n\n- 与 \\`edges[].when\\` 配合使用\n- \\`depends_on\\` 控制调度顺序\n\n### askUserNode (type=askUser)\n\n\\`\\`\\`yaml\n- id: <unique-id>\n type: askUser\n name: <human-readable>\n config:\n question: \"<问题文本>\"\n options: [\"选项A\", \"选项B\"] # 可选 multiple choice\n\\`\\`\\`\n\n- **陷阱**:必须保证 HiL resume 路径通畅\n\n### pythonCallNode (type=pythonCall)\n\n\\`\\`\\`yaml\n- id: <unique-id>\n type: pythonCall\n name: <human-readable>\n config:\n script: |\n # Python 代码(字符串)\n print(json.dumps({\"key\": \"value\"}))\n\\`\\`\\`\n\n- **陷阱**:必须用 \\`print()\\` 输出结果\n\n## YAML 模板参考(最小化可工作)\n\n\\`\\`\\`yaml\nname: my-workflow # 必填,kebab-case\nversion: \"1.0\" # 选填,默认 1.0\ndescription: 一句话描述 workflow 用途\ntags: # 必填,1-3 个(优先复用已有 tag)\n - code-review\n - automation\nconfig:\n parallel_limit: 2 # 节点并行上限\n timeout: 600000 # 总超时(毫秒)\n strict: false # 严格模式(节点失败即终止)\nentry: step-1\nnodes:\n - id: step-1\n type: tool\n name: 入口节点\n config:\n tool: echo\n args:\n message: \"Hello\"\n depends_on: []\n - id: step-2\n type: agent\n name: 分析节点\n config:\n agent_type: default\n prompt: \"{{input.task}}\"\n options:\n allowedTools: [read_file]\n deniedTools: [delegate_task, stop_task]\n timeout: 300000\n depends_on: [step-1]\nedges: [] # 条件分支用 edges,无条件全用 depends_on\noutputs: [] # 输出定义(可空)\n\\`\\`\\`\n\n## Tag 选择原则\n\n1. **优先复用** \\`workflow_tag_list\\` 显示的已有 tag(避免 tag 池膨胀)\n2. 已有 \\`code-review\\` 时**不要**新增 \\`review-workflow\\`\n3. 已有 \\`ci-cd\\` 时**不要**新增 \\`continuous-integration\\`\n4. 已有 \\`build-publish\\` 时**不要**新增 \\`release-deploy\\`\n5. tags 必须 1-3 个,超过会被 \\`workflow_add\\` 拒绝\n6. 池中确实没有合适 tag 时才新增,以扩展 tag 池\n\n## 严格约束\n\n- ✅ 只用 10 个被授予的工具(白名单强制)\n- ✅ **写 \\`{{nodes.X.<字段>}}\\` 前先核对访问契约表**(阶段 4.6):\\`agent\\` → \\`.result\\`;\\`tool\\` / \\`pythonCall\\` / \\`skill\\` → \\`.output\\`\n- ✅ **validate 必须迭代到 \\`errorCount === 0\\`**;每条 \\`warning\\` 要么修掉、要么在报告中写明保留理由\n- ✅ validate **必须**在 add 之前\n- ✅ **add / update 之后必须端到端冒烟跑一次**(阶段 5.5),并附 trace 证据;否则不算完成\n- ✅ tags 1-3 个,优先复用已有 tag\n- ✅ 注册前再次确认用户同意\n- ✅ run 证据(run_id + trace_id + session_id + 执行条数)**必须落盘 + 写 task_operation**\n- ❌ 不要直接读 \\`*.workflow.yaml\\` 文件自己 parse(用 \\`workflow_get\\`)\n- ❌ 不要 \\`delegate_task\\` / \\`stop_task\\`(deniedTools 已禁,禁止递归委托)\n- ❌ 不要跳过 \\`workflow_validate\\`\n- ❌ 不要用 \\`workflow update\\` 绕过 validate / 冒烟\n- ❌ 不要用 \\`bash\\` 替代 workflow 节点完成业务逻辑(走捷径 = 交付空壳)\n- ❌ 不要凭\"应该能跑\"声称通过;**没有 trace / run 证据就不算跑过**\n- ❌ 不要在 \\`tool\\` / \\`pythonCall\\` / \\`skill\\` 节点上用 \\`.result\\`(引擎会静默解析成空字符串)\n- ❌ 不要对 \\`tool\\` 节点写深层属性路径(输出常为字符串,无法再取属性)\n- ❌ 不要在有 \\`errors\\` 未清零的情况下声称「语法检测 OK」\n- ❌ 不要自动 merge / push / tag\n- ❌ 不要硬编码大段 text(应引用 \\`{{input.x}}\\` 模板)`,\n \"task-organizer\": `\n\n## 你的身份与使命\n\n你是 Roy 系统的 **task-organizer** 子代理(type=sub),专门负责**维护任务树形态健康**。\n\n你的使命:\n\n> **让任务树呈现\"金字塔形\"——前 1-2 层就能看到大体任务分布。**\n\n具体来说:\n- 通过 **reparent(重新挂载)** 把可归属的根任务收敛到 longterm 父任务下\n- 通过 **稀疏归档** 处理过期/孤儿任务(**仅当用户明确授权时**才归档)\n- 永远**不动 longterm 根任务**(它们是组织结构的锚点)\n- 永远**不删任务**(禁用 \\`task_batch_delete\\` / \\`task_delete\\`,只用 cancelled 或 archived 软操作)\n\n你是\"健康任务树的守护者\",不是\"清道夫\"。其它 agent 在创建任务时遵循\"先 \\`task_tree({depth: 1})\\` 再 \\`task_create({parent_task_id: ...})\\`\"的强约束;你的职责是**事后巡检 + 整理 + 修复**:把已存在的脏树(孤儿 / 重复 / 根任务膨胀)还原到健康的 tree shape。\n\n- **名称**: task-organizer\n- **角色**: 任务树整理专家(reparent / merge / 守门)\n- **输入**: 用户指令(\"整理任务\"、\"收敛根任务\"、\"重挂载到 longterm 父\"、\"收敛根任务到 10-20 个\"等)\n- **输出**: \\`/tmp/task-organization-report-v{N+1}.md\\` 报告 + 全程 \\`task_operation_create\\` 留痕\n\n---\n\n## \\uD83C\\uDF32 树形健康目标(金字塔铁律)\n\n> **核心原则:根任务越少、longterm 化越彻底,任务空间越能反映用户的长期愿景和方向。**\n\n| 指标 | 目标值 | 说明 |\n|------|--------|------|\n| **L0 非归档根任务数量** | **10-20** | 根任务膨胀 = 任务空间失控 |\n| **L1 子任务总数** | **≤ 400**(每 L0 ≤ 20) | 主题内大致结构可见 |\n| **L2 孙任务总数** | **≤ 8000**(每 L1 ≤ 20) | fanout ≈ 20 保持金字塔形 |\n| **根任务类型分布** | **目标 100% longterm,仅 meta/self 类允许例外** | 根任务 = 长期愿景/方向,normal/cycle 仅当属于 meta/task-organization/self 元任务时可保留 |\n| **最大深度** | **≤ 5** | 过深 = 必须上提 / 重新组织 |\n| **L0 子任务数(每 L0 ≤ 20)** | **预警 20 / 硬限 50** | L0 每根任务超过 20 子触发子任务过载预警,超过 50 必须拆分 |\n| **L1+ 子任务数(每 L1 ≤ 20)** | **预警 20 / 硬限 50** | 同上:层级越深,预警和硬限一致(fanout ≈ 20 保持金字塔形) |\n| **孤儿率** | **< 5%** | 孤儿 = 无 parent 且无明确主题的根任务 |\n\n健康度评估函数 \\`health_score(L0, L1, L2)\\`:\n\n- \\`L0 ≤ 20 AND L1 ≤ 400 AND L2 ≤ 8000\\` → \\`'health' ✅\\`\n- 否则 → 继续 Phase 2 找更多 reparent 机会(不能提前结束)\n\n\\`task_tree --depth=N\\` 是你观察树形是否健康的主要工具,要养成**多颗粒度**查看的习惯:\n\\`task_tree({depth: 0})\\` 看根全景 / \\`task_tree({depth: 2})\\` 看二级 / \\`task_tree --depth=3\\` 看深层 attach 目标。\n\n### Hard Rules(自动触发)\n\n- 根任务 **> 20 个** = **必须** 合并 / reparent / 归档\n- 根任务 **不是 longterm** = **必须** reparent 到任务树中语义最匹配的有意义祖先节点下\n (不一定是 longterm 根;可以是 longterm 根下的子/孙任务;如果实在找不到合适的 longterm 域,\n 可以创建一个新的 longterm 父任务来容纳,但**禁止无脑新建根**)\n- 根任务 **> 5 层深度** = **必须** 上提 / 重新组织\n- 子任务过载(单父 **超过 20 个**子任务)= 优先往下一层孙任务挂\n\n---\n\n## \\uD83C\\uDFAF 核心目标:把根任务收敛到 10-20 个 longterm 根,并把散落的非 longterm 根挂到任务树中最合适的位置\n\n你的最重要工作是**把当前脏树的根任务重新挂载到任务树中语义最匹配的有意义祖先节点下(不一定是 longterm 根)**,使得:\n\n\\`\\`\\`\n\\uD83C\\uDF33 健康的 Roy 任务树(金字塔形)\n├── [Longterm] A 方向(根 #100, ≤ 20 子)\n│ ├── normal 子任务 #101\n│ ├── normal 子任务 #102\n│ └── cycle 子任务 #103\n├── [Longterm] B 方向(根 #200)\n│ ├── normal 子任务 #201\n│ └── ...\n├── [Longterm] C 方向(根 #300)\n...\n└── [Longterm] T 方向(根 #900) ← 10-20 个 longterm 根\n\\`\\`\\`\n\n> 注意:散落任务的挂载目标**不一定是 longterm 根**,可以是 longterm 根下任意深度的子/孙任务\n> (沿树找语义最匹配节点,\"挂得深但语义匹配\"是合法策略)。\n\n---\n\n## \\uD83D\\uDEE0 你的工具(白名单)\n\n**只能使用以下工具**,没有 bash / edit_file / 写文件的能力:\n\n| 类别 | 工具 |\n|------|------|\n| **只读** | \\`task_tree\\`, \\`task_list\\`, \\`task_get\\`, \\`task_search\\`, \\`task_operation_list\\`, \\`task_operation_get\\`, \\`read_file\\`(仅调研) |\n| **修改**(结构) | \\`task_update\\`(改 \\`type\\` / \\`parent_task_id\\` / \\`status\\` / \\`tags\\` / \\`context\\`)|\n| **创建** | \\`task_create\\`, \\`task_operation_create\\` |\n| **⛔ 默认禁止** | \\`task_batch_archive\\`, \\`task_batch_delete\\`, \\`task_delete\\`, \\`task_complete\\`(仅在用户本轮明确授权时才用) |\n\n铁律:**默认 0 删 + 0 归档**。本轮若用户未明示,绝不调用 \\`task_batch_archive\\` / \\`task_batch_delete\\` / \\`task_delete\\`。\n\n> ⚠️ **没有 bash 工具** — 你无法执行 shell 命令。所有工作都只能通过任务管理工具完成。\n\n---\n\n## \\uD83D\\uDCCB 整理工作流(Phase 0 → Phase 4)\n\n### self-task 模板(Phase 0 之前必建)⭐关键\n\n每次接到任务整理请求,**第一步**就是建一个 self-task 跟踪本次工作(铁律 ⑫)。模板:\n\n\\`\\`\\`bash\n# 1. 建 tracking task\nSELF_TASK_ID=$(task_create \\\\\n title=\"[任务整理] v{N+1} — Task #<TODO>\", \\\\\n description=\"承接历史 #4088 / #4089 / #4090 三轮任务整理实战,把根任务收敛到 ≤20。\n本次目标:从起点根数收敛到 10-20 个 longterm 根,reparent 非 longterm 根,\n全程 0 删 + 0 归档默认。\", \\\\\n status=\"active\", \\\\\n priority=\"medium\", \\\\\n parent_task_id=<当前承接的 longterm 父任务 ID 或上一轮 self-task> \\\\\n)\n\n# 2. 拿到 ID 后 → 写第一个 progress 留痕\ntask_operation_create( \\\\\n task_id=$SELF_TASK_ID, \\\\\n milestone_type=\"progress\", \\\\\n milestone_title=\"建立 self-task 跟踪 (Task #$SELF_TASK_ID)\", \\\\\n milestone_description=\"任务整理开始,建立 self-task 跟踪本次 reparent/upgrade 操作链\", \\\\\n process_description=\"通过 task_create 建 tracking task + task_operation_create 留痕起步 100-150 字符\" \\\\\n)\n\n# 3. 自此所有 reparent / 升级 type 操作都必须 task_update 关联到 $SELF_TASK_ID\n\\`\\`\\`\n\n> **Task ID 通常形如 #4091 / #4093 / #4095 ...**(递增),\n> 拿到后立刻记到 working memory,后续每个操作 task_update / task_operation_create\n> 都填 task_id=$SELF_TASK_ID,形成可回溯的\"任务整理工作链\"。\n\n> ⚠️ 跳过 self-task 创建直接进 Phase 0 = 违反铁律 ⑫,必须立即停止并向主代理报告。\n\n---\n\n### Phase 0 — 基准建立(longterm 锚点清单)⭐关键\n\n**目标**:拿到所有 longterm 根任务,作为 reparent 锚点。\n\n\\`\\`\\`bash\n# 1. 拿所有 longterm 根任务(不限 status)\ntask_list({ type: \"longterm\", limit: 100 })\n\n# 2. 看每个 longterm 的子树结构\nfor lr in longterm_roots:\n task_tree({ parent_task_id: lr.id, depth: 2 })\n\n# 3. 输出锚点清单\n锚点清单 = [\n { id: 2066, title: \"[Longterm] TongAgent 生态\", 当前子任务数: N, 已覆盖主题: [...] },\n { id: 2859, title: \"[Longterm] roy-agent 主线研发\", ... },\n ...\n]\n\\`\\`\\`\n\n**要点**:\n- longterm 永远保留为根(铁律 ③)\n- 不创建新 longterm,除非满足\"周期/长期通用能力/长期研究\"判断(见 Phase 2 路径 b)\n- 锚点清单是后续每次 reparent 决策的\"字典\"\n\n**锚点优先级(重要,避免挂错)**:\n\n> **active longterm > todo longterm >> completed longterm**\n> completed longterm 仅作历史参考,不直接用作 reparent 锚点;否则会把 active normal 误挂到已完成 longterm 根下。\n> 例:看到 \\`task_list({type:\"longterm\", status:\"active\"})\\` 返回一堆 completed longterm 时,先按 status 过滤再用。\n\n### Phase 1 — 现状盘点\n\n\\`\\`\\`bash\n# 1. 拿所有根任务\ntask_tree({ depth: 0 })\n\n# 2. 分类(status × type 矩阵)\n分类 = {\n 'active_longterm': [...],\n 'active_normal': [...],\n 'todo_longterm': [...],\n 'todo_normal': [...],\n 'completed_longterm': [...],\n 'completed_normal': [...],\n ...\n}\n\n# 3. 输出当前 L0 / L1 / L2 数量 + 健康度\n\\`\\`\\`\n\n### Phase 2 — 4 路径分类决策树(核心算法)\n\n对每个**非 longterm 根任务**(normal / cycle),按以下决策树分类:\n\n\\`\\`\\`\n对每个根任务 rt:\n│\n├─ rt.type == 'longterm'?\n│ └─ YES → \\uD83D\\uDEAB 跳过(永远保留为根)\n│\n├─ rt.type == 'cycle'?\n│ └─ YES → 大概率保留为根(除非明确无意义)\n│\n└─ rt.type == 'normal'?\n │\n ├─ (a) 主题自循环 / 元任务 / 跨项目?\n │ 检查:tags 含 [\"meta\",\"task-organization\",\"system\",\"self\"]\n │ 或 description 是\"任务整理/系统维护\"性质\n │ 或 project_path 为 null / 'unknown'\n │ └─ YES → 保持为根(路径 a,**仅适用于 meta/self 类元任务**,与 1819 \"100% longterm 仅 meta/self 例外\" 目标兼容)\n │\n ├─ (b) 周期性 / 长期通用能力 / 长期研究主题?\n │ 检查:title 含\"周报/日报/月报/定期/巡检/能力/愿景/调研/研究\"\n │ 或当前是 cycle/longterm 类型用户期望的\"无明确终点\"任务\n │ └─ YES → task_update({ type: \"longterm\" }) 升级类型,保持为根(路径 b)\n │\n ├─ (c) 与某个 longterm 父强关联?\n │ 检查:title / description / tags / project_path 中含强关键词\n │ └─ YES → task_update({ parent_task_id: longterm_id })\n │ reparent 到 longterm 根(路径 c,重新挂载 normal → longterm 父)\n │\n └─ (d) 与某个具体子任务主题强相关?\n 检查:能找到一个 longterm 子孙节点(depth ≤ 3),其主题与 rt 完全重合\n └─ YES → task_update({ parent_task_id: specific_child_id })\n reparent 到该具体子节点(路径 d,多跳 reparent)\n \n └─ NO → ⚠️ 默认路径:(a) 保持为根(**仅适用于 meta/self 类元任务**;非 meta/self 应继续搜索路径 c/d 而非默认停留 a)\n\\`\\`\\`\n\n**决策依据强度**:\n\n- \\uD83D\\uDFE2 **强**:title **明示** longterm 关键词 / project_path **等于** longterm 的 project 路径\n- \\uD83D\\uDFE1 **中**:tags 含 longterm 主题词 / description 提及\"参考 #XXXX longterm 父\"\n- \\uD83D\\uDD34 **弱**:描述有相关关键词但不是明示\n\n**规则**:\\uD83D\\uDFE2 强 → 直接 reparent(路径 c)/ \\uD83D\\uDFE1 中 + 跨 2 项 → 可 reparent(路径 c/d),\\`task_operation_create\\` 必须详细 / \\uD83D\\uDD34 弱 → 保持为根(找不到合适父宁可不 reparent)。\n\n### Phase 3 — 健康度评估\n\n执行完所有 reparent 后,重新评估 L0 / L1 / L2 与 \\`health_score\\`。若 \\`new_health != 'health'\\`:\n- 继续 Phase 2 找更多 reparent 机会(**更激进但仍保守**)\n- 直到 \\`health == 'health'\\` 或耗尽所有 \\uD83D\\uDFE2/\\uD83D\\uDFE1 决策\n\n### Phase 4 — 执行 + 留痕\n\n每次 reparent / 升级 type 时,必须配套:\n\n\\`\\`\\`bash\ntask_update({ task_id: X, parent_task_id: Y }) # 或 task_update({ task_id: X, type: \"longterm\" })\n\ntask_operation_create({\n task_id: X, # 被 reparent 的任务\n milestone_type: \"decision\",\n milestone_title: \"Reparent #X → #Y (reason: ...)\"\n})\n\\`\\`\\`\n\n**报告输出**:写到 \\`/tmp/task-organization-report-v{N+1}.md\\`,含 8 节:\n1. 起点分析(Phase 1)/ 2. 锚点清单(Phase 0)/ 3. 4 路径分类(Phase 2)/ 4. 整理后终态 / 5. 操作清单(Phase 4)/ 6. 健康度评估(Phase 3)/ 7. 累计历史对比 / 8. 留痕\n\n---\n\n## \\uD83D\\uDEA8 铁律(不可违反)\n\n| # | 铁律 |\n|---|------|\n| ① | **0 删任务**(不调用 \\`task_batch_delete\\` / \\`task_delete\\`)|\n| ② | **0 归档默认**(不调用 \\`task_batch_archive\\`,除非用户本轮明确授权)|\n| ③ | **longterm 永远保留为根**(不修改 longterm 语义,不 reparent longterm)|\n| ④ | **active 只改 parent 不改 status**(可 reparent,但 status 永远保留 active)|\n| ⑤ | **0 碰 paused / cancelled 任务**(除非用户明确指示)|\n| ⑥ | **找不到合适父宁可不 reparent**(保守 > 激进)|\n| ⑦ | **每个 reparent 都要 \\`task_operation_create\\` 留痕** |\n| ⑧ | **不创建新 longterm 除非主题真正长期** |\n| ⑨ | **本轮不返工**(上一轮已 reparent 的,本轮不动)|\n| ⑩ | **不写代码到 roy-agent 仓库**(task-organizer 是 prompt agent)|\n| ⑪ | **每个决策 100% 可解释** |\n| ⑫ | **Phase 0 之前先建立 self-task 跟踪**(见下方 self-task 模板) |\n\n> ⚠️ 触发任何一条 → 立即停止并向主代理报告。\n\n---\n\n## \\uD83D\\uDEA8 禁止操作\n\n- ❌ **不要**无脑新建根任务(必须确认至少 2-3 个非 longterm 根明显同主题才建)\n- ❌ **不要**修改 longterm 根任务的语义(title / description / goals / type)\n- ❌ **不要**把不同 longterm 域的根 attach 到错误根\n- ❌ **不要**批量操作前不 dry-run\n- ❌ **不要**在没有 \\`task_operation_create\\` 记录的情况下做批量动作\n- ❌ **不要**默认调用 \\`task_batch_archive\\`(铁律 ②)\n\n---\n\n## 类型修正指南\n\n如果发现任务的 \\`type\\` 与实际情况不符,用 \\`task_update({ type: ... })\\` 修正:\n\n| 现状 | 应改为 | 判断依据 |\n|------|--------|----------|\n| \\`normal\\` 但内容明显是周期性的 | → \\`cycle\\` | 标题含\"周报/日报/月报/定期/每日/每周/巡检/备份\" |\n| \\`normal\\` 但描述抽象无明确完成条件 | → \\`longterm\\` | 愿景类描述,无法一次完成 |\n| \\`cycle\\` 但只是普通任务 | → \\`normal\\` | 没有周期性特征 |\n\n---\n\n## 关键双维度记录(每次 reparent 必填)\n\n每次 reparent / 升级 type 必须用 \\`task_operation_create\\` 留下双维度记录:\n\n- **milestone_type**: \\`decision\\`(\"为什么挂这里\")或 \\`milestone\\`(\"达成了什么\")\n- **milestone_title**: 一句话标题(如 \"Reparent #X → #Y(longterm 锚点)\")\n- **milestone_description**: 详细描述(决策依据、强度、项目路径)\n- **process_description**: 100-150 字符简要过程\n\n---\n\n## 终止与报告\n\n整理完成后输出报告到 \\`/tmp/task-organization-report-v{N+1}.md\\`,然后一句话总结:\n\n> ✅ 任务树整理完成。根任务从 N 收敛到 M(目标 10-20),其中 longterm 占比从 X% 提升到 100%,reparent/merge 共 K 项(0 删 + 0 归档默认)。详见 operations。\n\n如果没有任何改动:\n\n> ✅ 任务树形态良好(root=N, depth=X, non_longterm_root=0, health_score=health)。无需操作。\n`\n};\nvar WORKFLOW_EXTRACT_PROMPT = builtInPrompts[\"workflow-extract\"];\nfunction getBuiltInPromptNames() {\n return Object.keys(builtInPrompts);\n}\nfunction getBuiltInPrompt(name) {\n return builtInPrompts[name];\n}\n\nexport { builtInPrompts, WORKFLOW_EXTRACT_PROMPT, getBuiltInPromptNames, getBuiltInPrompt };\n",
|
|
101
|
+
"import {\n __require\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/paths.ts\nimport os from \"os\";\nimport path from \"path\";\nvar APP_NAME = \"roy-agent\";\nfunction getXdgBase() {\n const home = os.homedir();\n try {\n const xdg = __require(\"xdg-basedir\");\n return {\n config: xdg.xdgConfig || path.join(home, \".config\"),\n state: xdg.xdgState || path.join(home, \".local\", \"state\"),\n data: xdg.xdgData || path.join(home, \".local\", \"share\"),\n cache: xdg.xdgCache || path.join(home, \".cache\")\n };\n } catch {\n return {\n config: path.join(home, \".config\"),\n state: path.join(home, \".local\", \"state\"),\n data: path.join(home, \".local\", \"share\"),\n cache: path.join(home, \".cache\")\n };\n }\n}\nfunction computeXDGPaths() {\n const home = os.homedir();\n const xdg = getXdgBase();\n return {\n home,\n config: path.join(xdg.config, APP_NAME),\n state: path.join(xdg.state, APP_NAME),\n data: path.join(xdg.data, APP_NAME),\n cache: path.join(xdg.cache, APP_NAME)\n };\n}\n\nclass XDGPathsCalculator {\n _paths;\n get paths() {\n if (!this._paths) {\n this._paths = computeXDGPaths();\n }\n return this._paths;\n }\n getPath(type) {\n return this.paths[type];\n }\n getComponentPath(base, subPath) {\n return path.join(this.paths[base], subPath);\n }\n reset() {\n this._paths = undefined;\n }\n}\nvar XDG_PATHS = new XDGPathsCalculator;\nfunction getXDGPaths() {\n return XDG_PATHS.paths;\n}\nfunction getXDGPath(type) {\n return XDG_PATHS.getPath(type);\n}\n\nexport { XDG_PATHS, getXDGPaths, getXDGPath };\n",
|
|
102
|
+
"import {\n getXDGPath\n} from \"./roy-agent-core-qxnbvgwe.js\";\nimport {\n TracedAs,\n init_decorator\n} from \"./roy-agent-core-dsevjbck.js\";\nimport {\n createLogger,\n init_logger\n} from \"./roy-agent-core-8seq65bp.js\";\nimport {\n __legacyDecorateClassTS\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/agent/agent-registry.ts\nimport * as realFsPromises from \"fs/promises\";\nimport * as realFs from \"fs\";\nimport { join } from \"path\";\nimport { z } from \"zod\";\nimport yaml from \"yaml\";\ninit_logger();\ninit_decorator();\nvar logger = createLogger(\"agent:registry\");\nvar AgentConfigSchema = z.object({\n name: z.string(),\n type: z.enum([\"primary\", \"sub\", \"workflow\"]),\n workflow: z.string().optional(),\n entryAgent: z.string().optional(),\n description: z.string().optional(),\n systemPromptRef: z.string().optional(),\n systemPrompt: z.string().optional(),\n model: z.string().optional(),\n maxIterations: z.number().optional(),\n maxErrorRetries: z.number().optional(),\n allowedTools: z.array(z.string()).optional(),\n deniedTools: z.array(z.string()).optional(),\n toolTimeout: z.number().optional(),\n toolRetries: z.number().optional(),\n doomLoopThreshold: z.number().optional(),\n filterHistory: z.boolean().optional()\n}).refine((data) => data.type !== \"workflow\" || data.workflow && data.workflow.length > 0, { message: \"workflow is required when type is 'workflow'\" });\n\nclass AgentRegistry {\n agents = new Map;\n configDir;\n configComponent;\n promptComponent;\n resolvePromptComponent;\n fs;\n fsPromises;\n constructor(options) {\n this.configComponent = options.configComponent;\n this.promptComponent = options.promptComponent ?? null;\n this.resolvePromptComponent = options.resolvePromptComponent;\n this.fs = options.fs || realFs;\n this.fsPromises = options.fsPromises || realFsPromises;\n const customDir = this.configComponent?.get?.(\"agent.configDir\");\n if (customDir && typeof customDir === \"string\" && customDir.length > 0) {\n this.configDir = customDir;\n } else if (options.baseDir) {\n this.configDir = join(options.baseDir, \"agents\");\n } else {\n this.configDir = join(getXDGPath(\"data\"), \"agents\");\n }\n logger.debug(`[AgentRegistry] Config dir: ${this.configDir}`);\n }\n getConfigDir() {\n return this.configDir;\n }\n hasAgent(name) {\n return this.agents.has(name);\n }\n get(name) {\n return this.agents.get(name);\n }\n list() {\n return Array.from(this.agents.values());\n }\n listAgentsByType(type) {\n return this.list().filter((agent) => agent.type === type);\n }\n register(agent) {\n if (!agent.name) {\n throw new Error(\"Agent name is required\");\n }\n const validation = AgentConfigSchema.safeParse(agent);\n if (!validation.success) {\n throw new Error(`Invalid agent config for \"${agent.name}\": ${validation.error.issues.map((i) => i.message).join(\"; \")}`);\n }\n this.agents.set(agent.name, { ...agent });\n logger.info(`[AgentRegistry] Registered agent: ${agent.name}`, { type: agent.type });\n }\n unregister(name) {\n const deleted = this.agents.delete(name);\n if (deleted) {\n logger.info(`[AgentRegistry] Unregistered agent: ${name}`);\n }\n return deleted;\n }\n clear() {\n this.agents.clear();\n logger.info(\"[AgentRegistry] Cleared all agents\");\n }\n async getSystemPrompt(name) {\n const agent = this.agents.get(name);\n if (!agent) {\n return;\n }\n const promptComponent = this.getActivePromptComponent();\n if (agent.systemPromptRef) {\n try {\n if (promptComponent?.getPrompt) {\n const rendered = await promptComponent.getPrompt(agent.systemPromptRef, {}, {\n agentType: agent.type\n });\n if (rendered) {\n logger.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${agent.systemPromptRef}`);\n return rendered;\n }\n }\n const prompt = promptComponent?.get?.(agent.systemPromptRef);\n if (prompt) {\n logger.debug(`[AgentRegistry] Resolved systemPromptRef via get: ${agent.systemPromptRef}`);\n return prompt;\n }\n if (agent.systemPrompt) {\n logger.debug(`[AgentRegistry] systemPromptRef not found, falling back to inline`);\n return agent.systemPrompt;\n }\n return;\n } catch (error) {\n logger.warn(`[AgentRegistry] Failed to resolve systemPromptRef: ${agent.systemPromptRef}`, { error });\n return agent.systemPrompt;\n }\n }\n return agent.systemPrompt;\n }\n getActivePromptComponent() {\n return this.resolvePromptComponent?.() ?? this.promptComponent;\n }\n getInlineSystemPrompt(name) {\n const agent = this.agents.get(name);\n if (!agent) {\n return;\n }\n return agent.systemPrompt;\n }\n getWorkflowName(name) {\n const agent = this.agents.get(name);\n if (!agent || agent.type !== \"workflow\") {\n return;\n }\n return agent.workflow;\n }\n getEntryAgent(name) {\n const agent = this.agents.get(name);\n if (!agent || agent.type !== \"workflow\") {\n return;\n }\n return agent.entryAgent;\n }\n registerWorkflowRunner() {\n const name = \"workflow-runner\";\n if (this.agents.has(name))\n return;\n const agent = {\n name,\n type: \"sub\",\n description: \"Workflow runner — 接受带 workflow_name(必填)的委托,或指示其按 search-first 流程自行选定(workflow_tag_list + workflow_search + workflow_list + workflow_get),然后通过 workflow_run 执行 workflow;支持 session resume 和 stop;失败接管由 prompt 推理触发 (Task #2251)。**调用方必须在 prompt 中明确指定 workflow 名,或指示 sub-agent 自行搜索选择;禁止盲猜/绕过/跳过 schema 验证** (Task #2486)。\",\n systemPromptRef: \"workflow-runner\",\n deniedTools: [\"delegate_task\", \"stop_task\"],\n maxIterations: 30\n };\n this.agents.set(name, agent);\n }\n registerTaskOrganizer() {\n const name = \"task-organizer\";\n if (this.agents.has(name))\n return;\n const agent = {\n name,\n type: \"sub\",\n description: \"任务树整理子智能体 — 把非 longterm 类型的根任务重新挂载到 longterm 父任务下,根任务收敛到 10-20 个;维护任务树形态健康(re-parent / merge / archive / delete)。Task #2348。\",\n systemPromptRef: \"task-organizer\",\n allowedTools: [\n \"task_create\",\n \"task_get\",\n \"task_list\",\n \"task_update\",\n \"task_delete\",\n \"task_complete\",\n \"task_tree\",\n \"task_search\",\n \"task_batch_archive\",\n \"task_batch_delete\",\n \"task_operation_create\",\n \"task_operation_get\",\n \"task_operation_list\",\n \"task_operation_update\",\n \"task_operation_delete\"\n ],\n deniedTools: [\"delegate_task\", \"stop_task\"],\n maxIterations: 30\n };\n this.agents.set(name, agent);\n }\n registerJsonExtractAgent() {\n const name = \"json-extract\";\n if (this.agents.has(name))\n return;\n const agent = {\n name,\n type: \"sub\",\n description: \"JSON 提取子智能体 — 从对话历史中提取结构化 JSON,通过 workflow_submit_output 工具提交\",\n systemPromptRef: \"json-extract\",\n allowedTools: [\"workflow_submit_output\"],\n deniedTools: [],\n maxIterations: 5,\n filterHistory: false\n };\n this.agents.set(name, agent);\n }\n registerWorkflowExtractAgent() {\n const name = \"workflow-extract\";\n if (this.agents.has(name))\n return;\n const agent = {\n name,\n type: \"sub\",\n description: \"Workflow 提取子智能体 — 从父 task 的对话历史中分析需求,迭代式生成并验证 Workflow YAML\",\n systemPromptRef: \"workflow-extract\",\n allowedTools: [\n \"workflow_get\",\n \"workflow_list\",\n \"workflow_add\",\n \"workflow_validate\"\n ],\n deniedTools: [],\n maxIterations: 10,\n filterHistory: false\n };\n this.agents.set(name, agent);\n }\n registerWorkflowCreator() {\n const name = \"workflow-creator\";\n if (this.agents.has(name))\n return;\n const agent = {\n name,\n type: \"sub\",\n description: \"Workflow 构建子智能体 — 与用户多轮交互式协作设计、验证并注册 workflow\",\n systemPromptRef: \"workflow-creator\",\n allowedTools: [\n \"workflow_list\",\n \"workflow_get\",\n \"workflow_search\",\n \"workflow_tag_list\",\n \"workflow_validate\",\n \"workflow_add\",\n \"bash\",\n \"read_file\",\n \"workflow_run\",\n \"workflow_run_status\"\n ],\n deniedTools: [\"delegate_task\", \"stop_task\"],\n maxIterations: 60\n };\n this.agents.set(name, agent);\n }\n registerCompactAgent() {\n const name = \"compact\";\n if (this.agents.has(name))\n return;\n const agent = {\n name,\n type: \"sub\",\n description: \"压缩子智能体 — 从父 session 的历史消息中提取结构化 checkpoint JSON\",\n systemPromptRef: \"compact\",\n allowedTools: [\"workflow_submit_output\"],\n deniedTools: [],\n maxIterations: 3,\n filterHistory: false\n };\n this.agents.set(name, agent);\n }\n registerCompactHintAgent() {\n const name = \"compact-hint\";\n if (this.agents.has(name))\n return;\n const agent = {\n name,\n type: \"sub\",\n description: \"压缩提示子智能体 — 分析父 session 历史,生成场景化压缩指导提示\",\n systemPromptRef: \"compact-hint\",\n allowedTools: [\"workflow_submit_output\"],\n deniedTools: [],\n maxIterations: 3,\n filterHistory: false\n };\n this.agents.set(name, agent);\n }\n registerRoyAgent() {\n const name = \"roy\";\n if (this.agents.has(name))\n return;\n const agent = {\n name,\n type: \"sub\",\n description: \"Roy — versatile AI assistant inspired by Jarvis. Built-in general-purpose subagent for coding, research, planning, and complex multi-step tasks. Always available without `agent add roy`.\",\n systemPromptRef: \"roy\",\n deniedTools: [\"delegate_task\", \"stop_task\"]\n };\n this.agents.set(name, agent);\n }\n async load() {\n try {\n return await this.loadFromDirectory(this.configDir);\n } catch (error) {\n logger.warn(`[AgentRegistry] Failed to load agents: ${error}`);\n return 0;\n }\n }\n async loadFromDirectory(directory) {\n let loaded = 0;\n try {\n if (!this.fs.existsSync(directory)) {\n logger.debug(`[AgentRegistry] Config directory does not exist: ${directory}`);\n return 0;\n }\n const files = await this.fsPromises.readdir(directory, { withFileTypes: true });\n for (const file of files) {\n const fullPath = join(directory, file.name);\n if (file.isDirectory()) {\n continue;\n }\n if (!isAgentConfigFile(file.name)) {\n continue;\n }\n try {\n const content = await this.fsPromises.readFile(fullPath, \"utf-8\");\n const agent = this.parseAgentConfig(content, fullPath);\n if (agent) {\n this.agents.set(agent.name, agent);\n logger.info(`[AgentRegistry] Loaded agent: ${agent.name} from ${file.name}`);\n loaded++;\n }\n } catch (error) {\n logger.warn(`[AgentRegistry] Failed to load agent from ${file.name}: ${error}`);\n }\n }\n logger.info(`[AgentRegistry] Loaded ${loaded} agents from ${directory}`);\n } catch (error) {\n logger.warn(`[AgentRegistry] Error reading config directory: ${error}`);\n }\n return loaded;\n }\n parseAgentConfig(content, source) {\n try {\n const parsed = yaml.parse(content);\n const result = AgentConfigSchema.safeParse(parsed);\n if (!result.success) {\n logger.warn(`[AgentRegistry] Invalid agent config: ${source}`, {\n errors: result.error.errors\n });\n return null;\n }\n return result.data;\n } catch (error) {\n logger.error(`[AgentRegistry] Failed to parse agent config: ${source}`, { error });\n return null;\n }\n }\n async saveAgent(agent) {\n try {\n const validation = AgentConfigSchema.safeParse(agent);\n if (!validation.success) {\n logger.error(`[AgentRegistry] Invalid agent config for \"${agent.name}\": ${validation.error.message}`);\n return false;\n }\n await this.ensureConfigDir();\n const yamlContent = this.agentToYaml(agent);\n const filePath = join(this.configDir, `${agent.name}.yaml`);\n await this.fsPromises.writeFile(filePath, yamlContent, \"utf-8\");\n this.agents.set(agent.name, agent);\n logger.info(`[AgentRegistry] Saved agent: ${agent.name} to ${filePath}`);\n return true;\n } catch (error) {\n logger.error(`[AgentRegistry] Failed to save agent: ${agent.name}`, { error });\n return false;\n }\n }\n async ensureConfigDir() {\n if (!this.fs.existsSync(this.configDir)) {\n await this.fsPromises.mkdir(this.configDir, { recursive: true });\n logger.debug(`[AgentRegistry] Created config directory: ${this.configDir}`);\n }\n }\n agentToYaml(agent) {\n const config = {\n name: agent.name,\n type: agent.type,\n ...agent.description !== undefined ? { description: agent.description } : {},\n ...agent.systemPromptRef !== undefined ? { systemPromptRef: agent.systemPromptRef } : {},\n ...agent.systemPrompt !== undefined ? { systemPrompt: agent.systemPrompt } : {},\n ...agent.model !== undefined ? { model: agent.model } : {},\n ...agent.maxIterations !== undefined ? { maxIterations: agent.maxIterations } : {},\n ...agent.maxErrorRetries !== undefined ? { maxErrorRetries: agent.maxErrorRetries } : {},\n ...agent.allowedTools !== undefined ? { allowedTools: agent.allowedTools } : {},\n ...agent.deniedTools !== undefined ? { deniedTools: agent.deniedTools } : {},\n ...agent.toolTimeout !== undefined ? { toolTimeout: agent.toolTimeout } : {},\n ...agent.toolRetries !== undefined ? { toolRetries: agent.toolRetries } : {},\n ...agent.doomLoopThreshold !== undefined ? { doomLoopThreshold: agent.doomLoopThreshold } : {},\n ...agent.filterHistory !== undefined ? { filterHistory: agent.filterHistory } : {},\n ...agent.workflow !== undefined ? { workflow: agent.workflow } : {},\n ...agent.entryAgent !== undefined ? { entryAgent: agent.entryAgent } : {}\n };\n return yaml.stringify(config).trimEnd() + `\n`;\n }\n async deleteAgent(name) {\n const agent = this.agents.get(name);\n if (!agent) {\n logger.warn(`[AgentRegistry] Agent not found: ${name}`);\n return false;\n }\n try {\n const filePath = join(this.configDir, `${name}.yaml`);\n if (this.fs.existsSync(filePath)) {\n await this.fsPromises.unlink(filePath);\n logger.info(`[AgentRegistry] Deleted agent file: ${filePath}`);\n }\n this.agents.delete(name);\n return true;\n } catch (error) {\n logger.error(`[AgentRegistry] Failed to delete agent: ${name}`, { error });\n return false;\n }\n }\n exportAgents(options = {}) {\n const agents = this.list();\n if (options.format === \"json\") {\n return agents;\n }\n return agents;\n }\n exportAgentsAsJson() {\n return JSON.stringify(this.list(), null, 2);\n }\n size() {\n return this.agents.size;\n }\n configDirExists() {\n return this.fs.existsSync(this.configDir);\n }\n getAgentFilePath(name) {\n return join(this.configDir, `${name}.yaml`);\n }\n}\n__legacyDecorateClassTS([\n TracedAs(\"agent.registry.register\", { recordParams: true, recordResult: true, log: true })\n], AgentRegistry.prototype, \"register\", null);\n__legacyDecorateClassTS([\n TracedAs(\"agent.registry.unregister\", { recordParams: true, recordResult: true, log: true })\n], AgentRegistry.prototype, \"unregister\", null);\n__legacyDecorateClassTS([\n TracedAs(\"agent.registry.clear\", { recordParams: false, recordResult: true, log: true })\n], AgentRegistry.prototype, \"clear\", null);\n__legacyDecorateClassTS([\n TracedAs(\"agent.registry.getSystemPrompt\", { recordParams: true, recordResult: true, log: true })\n], AgentRegistry.prototype, \"getSystemPrompt\", null);\n__legacyDecorateClassTS([\n TracedAs(\"agent.registry.getWorkflowName\", { recordParams: true, recordResult: true })\n], AgentRegistry.prototype, \"getWorkflowName\", null);\n__legacyDecorateClassTS([\n TracedAs(\"agent.registry.getEntryAgent\", { recordParams: true, recordResult: true })\n], AgentRegistry.prototype, \"getEntryAgent\", null);\n__legacyDecorateClassTS([\n TracedAs(\"agent.registry.registerWorkflowRunner\", {\n recordParams: false,\n recordResult: true,\n log: true\n })\n], AgentRegistry.prototype, \"registerWorkflowRunner\", null);\n__legacyDecorateClassTS([\n TracedAs(\"agent.registry.registerTaskOrganizer\", {\n recordParams: false,\n recordResult: true,\n log: true\n })\n], AgentRegistry.prototype, \"registerTaskOrganizer\", null);\n__legacyDecorateClassTS([\n TracedAs(\"agent.registry.registerWorkflowCreator\", {\n recordParams: false,\n recordResult: true,\n log: true\n })\n], AgentRegistry.prototype, \"registerWorkflowCreator\", null);\n__legacyDecorateClassTS([\n TracedAs(\"agent.registry.load\", { recordParams: false, recordResult: true, log: true })\n], AgentRegistry.prototype, \"load\", null);\n__legacyDecorateClassTS([\n TracedAs(\"agent.registry.loadFromDirectory\", { recordParams: true, recordResult: true, log: true })\n], AgentRegistry.prototype, \"loadFromDirectory\", null);\nfunction isAgentConfigFile(fileName) {\n return fileName.endsWith(\".yaml\") || fileName.endsWith(\".yml\");\n}\nvar DEFAULT_SUBAGENT_PROMPT = `You are a subagent created by the main agent to handle a specific task.\n\n## Your Role\n- You were created to handle: {task_description}\n- Complete this task. That's your entire purpose.\n- You are NOT the main agent. Don't try to be.\n\n## Rules\n1. **Stay focused** - Do your assigned task, nothing else\n2. **Complete the task** - Your final message will be automatically reported to the main agent\n3. **Don't initiate** - No heartbeats, no proactive actions, no side quests\n4. **Be ephemeral** - You may be terminated after task completion. That's fine.\n5. **No nested delegation** - Do NOT use delegate_task or stop_task tools. Complete the task yourself.\n\n## Execution\n- Use the available tools to complete the task\n- If you need more information, ask the main agent through the result\n- Return a clear summary of what you did and the results`;\n\nexport { AgentRegistry, DEFAULT_SUBAGENT_PROMPT };\n",
|
|
103
|
+
"// src/env/task/delegate/bg-task-id-storage.ts\nimport { AsyncLocalStorage } from \"async_hooks\";\nvar bgTaskIdStorage = new AsyncLocalStorage;\nfunction runWithBgTaskIdAsync(bgTaskId, fn) {\n return bgTaskIdStorage.run(bgTaskId, fn);\n}\nfunction getCurrentBgTaskId() {\n return bgTaskIdStorage.getStore();\n}\n\nexport { runWithBgTaskIdAsync, getCurrentBgTaskId };\n",
|
|
104
|
+
"import {\n init_env_context,\n init_env_event\n} from \"./roy-agent-core-5apmk4qw.js\";\nimport {\n __esm\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/context/index.ts\nvar init_context = __esm(() => {\n init_env_context();\n init_env_event();\n});\n\nexport { init_context };\n",
|
|
105
|
+
"import {\n init_context\n} from \"./roy-agent-core-k8b440n3.js\";\nimport {\n getEnvContext\n} from \"./roy-agent-core-5apmk4qw.js\";\nimport {\n __esm\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/hook/hook-manager.ts\nclass HookManager {\n _hooks = new Map;\n componentName;\n componentVersion;\n defaultPriority;\n constructor(options = {}) {\n this.componentName = options.componentName ?? \"unknown\";\n this.componentVersion = options.componentVersion ?? \"0.0.0\";\n this.defaultPriority = options.defaultPriority ?? 0;\n }\n register(hookPoint, hook) {\n const hooks = this.getOrCreateHooks(hookPoint);\n hooks.push(hook);\n }\n registerMany(hookPoint, hooks) {\n const hookList = this.getOrCreateHooks(hookPoint);\n hookList.push(...hooks);\n }\n unregister(hookPoint, name) {\n const hooks = this._hooks.get(hookPoint);\n if (!hooks)\n return false;\n const index = hooks.findIndex((h) => h.name === name);\n if (index === -1)\n return false;\n hooks.splice(index, 1);\n return true;\n }\n unregisterAll(hookPoint) {\n this._hooks.delete(hookPoint);\n }\n async execute(hookPoint, data, metadata = {}) {\n const hooks = this._hooks.get(hookPoint);\n const DEBUG_HOOK = process.env.ROY_HOOK_DEBUG === \"1\";\n if (DEBUG_HOOK) {\n console.error(`[DEBUG hook-manager.execute] hookPoint=${hookPoint}, hooksCount=${hooks?.length ?? 0}`);\n }\n if (!hooks || hooks.length === 0) {\n if (DEBUG_HOOK)\n console.error(`[DEBUG hook-manager.execute] → EARLY RETURN (no hooks registered for ${hookPoint})`);\n return;\n }\n const envContext = getEnvContext();\n if (DEBUG_HOOK) {\n console.error(`[DEBUG hook-manager.execute] envContext=${envContext ? \"present\" : \"absent\"}`);\n if (envContext) {\n console.error(`[DEBUG hook-manager.execute] envContext.pluginEnabled=${JSON.stringify(envContext.pluginEnabled)}`);\n console.error(`[DEBUG hook-manager.execute] envContext.sourceId=${envContext.sourceId}`);\n }\n }\n if (envContext) {\n metadata.envContext = envContext;\n if (!metadata.pluginEnabled && envContext.pluginEnabled) {\n metadata.pluginEnabled = envContext.pluginEnabled;\n }\n }\n const sortedHooks = this.sortHooks(hooks);\n const ctx = this.createContext(hookPoint, data, metadata, \"before\");\n const pluginEnabled = metadata.pluginEnabled || {};\n if (DEBUG_HOOK) {\n console.error(`[DEBUG hook-manager.execute] final pluginEnabled=${JSON.stringify(pluginEnabled)}`);\n console.error(`[DEBUG hook-manager.execute] sortedHooks=${sortedHooks.length}:`);\n for (const h of sortedHooks) {\n console.error(`[DEBUG hook-manager.execute] - name=${h.name} pluginName=${h.pluginName} sourceId=${h.sourceId}`);\n }\n }\n for (const hook of sortedHooks) {\n if (hook.pluginName && hook.sourceId) {\n const key = `${hook.sourceId}:${hook.pluginName}`;\n const enabled = pluginEnabled[key];\n if (DEBUG_HOOK) {\n console.error(`[DEBUG hook-manager.execute] hook ${hook.name} (${key}) enabled=${enabled}`);\n }\n if (enabled !== true) {\n if (DEBUG_HOOK) {\n console.error(`[DEBUG hook-manager.execute] → SKIPPED (pluginEnabled[${key}] !== true, got ${JSON.stringify(enabled)})`);\n }\n continue;\n }\n } else if (DEBUG_HOOK) {\n console.error(`[DEBUG hook-manager.execute] hook ${hook.name} has no pluginName/sourceId, ALWAYS EXECUTED`);\n }\n if (DEBUG_HOOK) {\n console.error(`[DEBUG hook-manager.execute] → EXECUTING hook ${hook.name}`);\n }\n await this.safeExecute(hook, ctx);\n }\n }\n async executeAndCollect(hookPoint, data, metadata = {}) {\n const hooks = this._hooks.get(hookPoint);\n if (!hooks || hooks.length === 0)\n return [];\n const sortedHooks = this.sortHooks(hooks);\n const ctx = this.createContext(hookPoint, data, metadata, \"before\");\n const results = [];\n for (const hook of sortedHooks) {\n const result = await this.safeExecuteAndReturn(hook, ctx);\n if (result !== undefined) {\n results.push(result);\n }\n }\n return results;\n }\n count(hookPoint) {\n return this._hooks.get(hookPoint)?.length ?? 0;\n }\n clear() {\n this._hooks.clear();\n }\n getHookPoints() {\n return Array.from(this._hooks.keys());\n }\n hasHooks(hookPoint) {\n return this.count(hookPoint) > 0;\n }\n setComponentInfo(name, version) {\n this.componentName = name;\n this.componentVersion = version;\n }\n get hooks() {\n return this._hooks;\n }\n async executeWithIntervention(hookPoint, data, metadata = {}) {\n const hooks = this._hooks.get(hookPoint);\n if (!hooks || hooks.length === 0) {\n return { stopped: false, results: [] };\n }\n const sortedHooks = this.sortHooks(hooks);\n const ctx = this.createContext(hookPoint, data, metadata, \"before\");\n const results = [];\n let stopped = false;\n let action;\n for (const hook of sortedHooks) {\n if (stopped)\n break;\n const result = await this.safeExecuteAndReturn(hook, ctx);\n results.push(result);\n if (result && typeof result === \"object\" && \"stopped\" in result) {\n const hookResult = result;\n if (hookResult.stopped) {\n stopped = true;\n action = hookResult.action;\n }\n }\n }\n return { stopped, action, results };\n }\n getOrCreateHooks(hookPoint) {\n let hooks = this._hooks.get(hookPoint);\n if (!hooks) {\n hooks = [];\n this._hooks.set(hookPoint, hooks);\n }\n return hooks;\n }\n sortHooks(hooks) {\n return [...hooks].sort((a, b) => {\n const priorityA = a.priority ?? this.defaultPriority;\n const priorityB = b.priority ?? this.defaultPriority;\n return priorityA - priorityB;\n });\n }\n createContext(hookPoint, data, metadata, phase) {\n return {\n component: {\n name: this.componentName,\n version: this.componentVersion\n },\n data,\n metadata,\n phase,\n hookPoint\n };\n }\n async safeExecute(hook, ctx) {\n try {\n const result = hook.execute(ctx);\n if (result && typeof result === \"object\" && typeof result.then === \"function\") {\n await result;\n }\n } catch (error) {\n console.error(`Hook \"${hook.name}\" failed:`, error);\n }\n }\n async safeExecuteAndReturn(hook, ctx) {\n try {\n return await hook.execute(ctx);\n } catch (error) {\n console.error(`Hook \"${hook.name}\" failed:`, error);\n return;\n }\n }\n}\nvar init_hook_manager = __esm(() => {\n init_context();\n});\n\n// src/env/hook/global-hook-manager.ts\nfunction setupAliasHooks() {\n const originalRegister = globalHookManager.register.bind(globalHookManager);\n globalHookManager.register = function(hookPoint, hook) {\n originalRegister(hookPoint, hook);\n const alias = hookPointAliases[hookPoint];\n if (alias) {\n originalRegister(alias, hook);\n }\n };\n}\nasync function executeAgentHook(hookPoint, data, metadata = {}) {\n await globalHookManager.execute(hookPoint, data, metadata);\n}\nasync function executeAgentHookWithIntervention(hookPoint, data, metadata = {}) {\n return globalHookManager.executeWithIntervention(hookPoint, data, metadata);\n}\nasync function executeLLMHook(hookPoint, data, metadata = {}) {\n await globalHookManager.execute(hookPoint, data, metadata);\n}\nasync function executeToolHook(hookPoint, data, metadata = {}) {\n await globalHookManager.execute(hookPoint, data, metadata);\n}\nvar globalHookManager, AgentHookPoints, LLMHookPoints, ToolHookPoints, hookPointAliases;\nvar init_global_hook_manager = __esm(() => {\n init_hook_manager();\n globalHookManager = new HookManager;\n AgentHookPoints = {\n BEFORE_START: \"agent:before.start\",\n BEFORE_LLM: \"agent:before.llm\",\n AFTER_LLM: \"agent:after.llm\",\n BEFORE_TOOL: \"agent:before.tool\",\n AFTER_TOOL: \"agent:after.tool\",\n ON_ITERATION: \"agent:on.iteration\",\n ON_THRESHOLD: \"agent:on.threshold\",\n AFTER_COMPLETE: \"agent:after.complete\",\n ON_ERROR: \"agent:on.error\"\n };\n LLMHookPoints = {\n BEFORE_INVOKE: \"llm:before.invoke\",\n AFTER_INVOKE: \"llm:after.invoke\",\n ON_STREAM: \"llm:on.stream\"\n };\n ToolHookPoints = {\n BEFORE_EXECUTE: \"tool:before.execute\",\n AFTER_EXECUTE: \"tool:after.execute\",\n BEFORE_REGISTER: \"tool:before.register\",\n AFTER_REGISTER: \"tool:after.register\",\n ON_ERROR: \"tool:on.error\"\n };\n hookPointAliases = {\n \"before.tool\": \"tool:before.execute\",\n \"after.tool\": \"tool:after.execute\",\n \"llm.before-invoke\": \"llm:before.invoke\",\n \"llm.after-invoke\": \"llm:after.invoke\",\n \"llm.stream\": \"llm:on.stream\",\n \"prompt.before-render\": \"prompt:before.render\",\n \"prompt.after-render\": \"prompt:after.render\",\n \"prompt:before.render\": \"prompt.before-render\",\n \"prompt:after.render\": \"prompt.after-render\",\n \"prompt:after-render\": \"prompt.after-render\",\n \"prompt:before-render\": \"prompt.before-render\"\n };\n setupAliasHooks();\n});\n\nexport { HookManager, init_hook_manager, globalHookManager, AgentHookPoints, LLMHookPoints, ToolHookPoints, executeAgentHook, executeAgentHookWithIntervention, executeLLMHook, executeToolHook, init_global_hook_manager };\n",
|
|
106
|
+
"import {\n ProcessRegistry,\n runWithProcessRegistryAsync\n} from \"./roy-agent-core-tbrn9wdm.js\";\nimport {\n getSharedEventStore\n} from \"./roy-agent-core-yhsssn86.js\";\nimport {\n TaskHookPoints\n} from \"./roy-agent-core-1pg0fepg.js\";\nimport {\n builtInPrompts\n} from \"./roy-agent-core-gdsqp6j8.js\";\nimport {\n DEFAULT_SUBAGENT_PROMPT\n} from \"./roy-agent-core-rx16h2m1.js\";\nimport {\n runWithBgTaskIdAsync\n} from \"./roy-agent-core-c1v263jn.js\";\nimport {\n globalHookManager,\n init_global_hook_manager\n} from \"./roy-agent-core-4z3rq5gw.js\";\nimport {\n init_context\n} from \"./roy-agent-core-k8b440n3.js\";\nimport {\n getCurrentTaskId,\n getEnvContext\n} from \"./roy-agent-core-5apmk4qw.js\";\nimport {\n TracedAs,\n init_decorator,\n wrapFunction\n} from \"./roy-agent-core-dsevjbck.js\";\nimport {\n createLogger,\n init_logger\n} from \"./roy-agent-core-8seq65bp.js\";\nimport {\n __legacyDecorateClassTS\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/task/delegate/delegate-tool.ts\ninit_logger();\ninit_decorator();\ninit_context();\nimport { z } from \"zod\";\n\n// src/env/task/delegate/subagent-resolver.ts\nfunction isKnownSubagentType(subagentType, registry) {\n if (getSubAgentSpec(subagentType)) {\n return true;\n }\n return registry?.hasAgent(subagentType) ?? false;\n}\nasync function resolveSubAgentConfig(subagentType, options = {}) {\n const getBuiltIn = options.getBuiltIn ?? getSubAgentSpec;\n const builtIn = getBuiltIn(subagentType);\n const agentDef = options.registry?.get(subagentType);\n if (!builtIn && !agentDef) {\n return;\n }\n if (agentDef) {\n return resolveFromRegistry(subagentType, agentDef, builtIn, options.registry);\n }\n return {\n subagentType,\n description: builtIn.description,\n basePrompt: builtIn.promptOverride || DEFAULT_SUBAGENT_PROMPT,\n allowedTools: builtIn.allowedTools,\n deniedTools: builtIn.deniedTools ?? [\"delegate_task\", \"stop_task\"],\n fromRegistry: false\n };\n}\nasync function resolveFromRegistry(subagentType, agentDef, builtIn, registry) {\n const resolvedPrompt = registry ? await registry.getSystemPrompt(subagentType) : agentDef.systemPrompt;\n return {\n subagentType,\n description: agentDef.description || builtIn?.description || \"Custom agent\",\n basePrompt: resolvedPrompt || builtIn?.promptOverride || DEFAULT_SUBAGENT_PROMPT,\n allowedTools: agentDef.allowedTools ?? builtIn?.allowedTools,\n deniedTools: agentDef.deniedTools ?? builtIn?.deniedTools ?? [\"delegate_task\", \"stop_task\"],\n fromRegistry: true\n };\n}\nfunction buildAgentSelectionGuide(options) {\n const customAgentNote = options.hasCustomAgents ? \"- Custom agents from AgentRegistry are listed above.\" : \"- Custom agents from AgentRegistry appear above when registered.\";\n return `\n## Agent Selection Guide\n\n- Choose \\`subagent_type\\` from the list above; use \\`general\\` when no specialized agent fits (default).\n${customAgentNote}\n- For full metadata: \\`roy-agent agents list\\`, \\`roy-agent agents get <name>\\`, \\`roy-agent prompt list\\`.`;\n}\nfunction listKnownSubagentDescriptions(registry) {\n const builtInLines = builtInSubAgents.map((agent) => `- ${agent.id}: ${agent.description}`);\n const registryAgents = registry?.list() ?? [];\n const customLines = registryAgents.filter((agent) => !builtInSubAgents.some((builtIn) => builtIn.id === agent.name)).map((agent) => {\n if (agent.type === \"workflow\") {\n const workflowInfo = agent.workflow ? ` (workflow: ${agent.workflow})` : \"\";\n return `- ${agent.name}: ${agent.description || \"Workflow agent\"}${workflowInfo}`;\n }\n return `- ${agent.name}: ${agent.description || \"Custom agent\"}`;\n });\n const lines = [...builtInLines, ...customLines];\n const guidance = buildAgentSelectionGuide({ hasCustomAgents: customLines.length > 0 });\n return lines.join(`\n`) + guidance;\n}\n\n// src/env/task/delegate/delegate-tool.ts\ninit_global_hook_manager();\n\n// src/env/task/task-creation-registry.ts\nvar TOKEN_PATTERNS = [\n /\\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\\b/g,\n /\\bxox[abprs]-[A-Za-z0-9-]{8,}\\b/g,\n /\\bghp_[A-Za-z0-9]{16,}\\b/g,\n /\\bgithub_pat_[A-Za-z0-9_]{16,}\\b/g,\n /\\bBearer\\s+[A-Za-z0-9._\\-+/=]{12,}\\b/g,\n /\\bAKIA[0-9A-Z]{16}\\b/g\n];\nfunction redactTokens(s) {\n let out = s;\n for (const pat of TOKEN_PATTERNS) {\n out = out.replace(pat, \"<redacted>\");\n }\n return out;\n}\nfunction truncate(s, max) {\n if (s.length <= max)\n return s;\n if (max <= 3)\n return s.slice(0, max);\n return s.slice(0, max - 1) + \"…\";\n}\nfunction sanitize(s, max) {\n return truncate(redactTokens(s), max);\n}\n\nclass TaskCreationRegistry {\n maxEntries;\n ttlMs;\n maxDescriptionChars;\n records = new Map;\n childrenIndex = new Map;\n constructor(config = {}) {\n this.maxEntries = config.maxEntries ?? 500;\n this.ttlMs = config.ttlMs ?? 24 * 60 * 60 * 1000;\n this.maxDescriptionChars = config.maxDescriptionChars ?? 240;\n }\n record(task, source = {}) {\n const now = new Date().toISOString();\n const record = this.toRecord(task, source, now);\n this.upsert(record);\n this.indexParentChild(record);\n this.evictIfNeeded();\n return record;\n }\n update(task, source) {\n const existing = this.records.get(task.id);\n if (!existing)\n return;\n const now = new Date().toISOString();\n this.records.delete(task.id);\n const merged = {\n ...existing,\n ...this.toRecord(task, source ?? existing.source, now),\n createdAt: existing.createdAt,\n source: source ?? existing.source\n };\n this.records.set(task.id, merged);\n this.childrenIndex.delete(merged.taskId);\n this.indexParentChild(merged);\n this.evictIfNeeded();\n return merged;\n }\n remove(id) {\n const rec = this.records.get(id);\n if (!rec)\n return false;\n this.records.delete(id);\n if (rec.parentTaskId !== undefined) {\n const siblings = this.childrenIndex.get(rec.parentTaskId);\n siblings?.delete(id);\n if (siblings && siblings.size === 0) {\n this.childrenIndex.delete(rec.parentTaskId);\n }\n }\n return true;\n }\n getById(id) {\n const rec = this.records.get(id);\n if (!rec)\n return;\n if (Date.now() - Date.parse(rec.updatedAt) > this.ttlMs) {\n this.remove(id);\n return;\n }\n return rec;\n }\n peekById(id) {\n return this.records.get(id);\n }\n clear() {\n this.records.clear();\n this.childrenIndex.clear();\n }\n size() {\n return this.records.size;\n }\n recent(options = {}) {\n const limit = options.limit ?? 10;\n const statuses = options.statuses;\n const excludeIds = new Set(options.excludeIds ?? []);\n const excludeAncestorId = options.excludeAncestorOf ?? options.excludeSelfOrDescendant;\n const excludeAncestorIds = excludeAncestorId ? this.collectSubtree(excludeAncestorId) : new Set;\n const sinceMs = options.sinceHours ? Date.now() - options.sinceHours * 60 * 60 * 1000 : 0;\n const now = Date.now();\n const excludeAll = new Set([...excludeIds, ...excludeAncestorIds]);\n const all = [];\n for (const rec of this.records.values()) {\n if (now - Date.parse(rec.updatedAt) > this.ttlMs)\n continue;\n if (sinceMs > 0 && Date.parse(rec.updatedAt) < sinceMs)\n continue;\n if (excludeAll.has(rec.taskId))\n continue;\n if (options.scope) {\n if (options.scope.sessionId !== undefined && rec.source.sessionId !== options.scope.sessionId)\n continue;\n if (options.scope.parentSessionId !== undefined && rec.source.parentSessionId !== options.scope.parentSessionId)\n continue;\n if (options.scope.subagentType !== undefined && rec.source.subagentType !== options.scope.subagentType)\n continue;\n }\n if (statuses) {\n if (!statuses.includes(rec.status))\n continue;\n } else {\n if (rec.status === \"archived\")\n continue;\n }\n all.push(rec);\n }\n if (options.activeChildFirst) {\n const activeChildBoost = new Map;\n for (const rec of all) {\n activeChildBoost.set(rec.taskId, this.hasActiveChild(rec.taskId));\n }\n all.sort((a, b) => {\n const aBoost = activeChildBoost.get(a.taskId) ? 1 : 0;\n const bBoost = activeChildBoost.get(b.taskId) ? 1 : 0;\n if (aBoost !== bBoost)\n return bBoost - aBoost;\n const cmp = Date.parse(b.updatedAt) - Date.parse(a.updatedAt);\n if (cmp !== 0)\n return cmp;\n return b.taskId - a.taskId;\n });\n } else {\n all.sort((a, b) => {\n const cmp = Date.parse(b.updatedAt) - Date.parse(a.updatedAt);\n if (cmp !== 0)\n return cmp;\n return b.taskId - a.taskId;\n });\n }\n return all.slice(0, limit);\n }\n getSubtreeSummary(parentId, options = {}) {\n const includeArchived = options.includeArchived === true;\n const summary = {\n descendantCount: 0,\n activeCount: 0,\n completedCount: 0,\n maxDepth: 0\n };\n if (!this.records.has(parentId) && !this.childrenIndex.has(parentId)) {\n return summary;\n }\n const directChildren = this.childrenIndex.get(parentId);\n const currentLevel = directChildren ? Array.from(directChildren) : [];\n let depth = currentLevel.length > 0 ? 1 : 0;\n summary.maxDepth = depth;\n let levelIds = currentLevel;\n while (levelIds.length > 0) {\n const nextLevel = [];\n for (const id of levelIds) {\n const rec = this.records.get(id);\n if (!rec)\n continue;\n if (!includeArchived && rec.status === \"archived\")\n continue;\n summary.descendantCount++;\n if (rec.status === \"active\") {\n summary.activeCount++;\n } else if (rec.status === \"completed\") {\n summary.completedCount++;\n }\n const grandchildren = this.childrenIndex.get(id);\n if (grandchildren && grandchildren.size > 0) {\n for (const gc of grandchildren)\n nextLevel.push(gc);\n }\n }\n if (nextLevel.length > 0) {\n depth++;\n summary.maxDepth = depth;\n }\n levelIds = nextLevel;\n }\n return summary;\n }\n hasActiveChild(parentId) {\n const children = this.childrenIndex.get(parentId);\n if (!children)\n return false;\n for (const childId of children) {\n const rec = this.records.get(childId);\n if (!rec)\n continue;\n if (rec.status === \"active\" || rec.status === \"todo\")\n return true;\n }\n return false;\n }\n toRecord(task, source, isoNow) {\n const parsedContext = this.safeParseContext(task.context);\n const safeContext = parsedContext ? this.stripSensitiveKeys(parsedContext) : undefined;\n return {\n taskId: task.id,\n title: task.title,\n description: sanitize(task.description || \"\", this.maxDescriptionChars),\n goals: sanitize(task.goals_and_expected_deliverables || \"\", this.maxDescriptionChars),\n tags: task.tags ?? [],\n status: task.status,\n priority: task.priority,\n type: task.type,\n parentTaskId: task.parent_task_id,\n source,\n createdAt: task.createdAt || isoNow,\n updatedAt: task.updatedAt || isoNow,\n operationCount: 0,\n project_path: task.project_path,\n branch: this.pickString(safeContext, \"branch\"),\n worktree_path: this.pickString(safeContext, \"worktree_path\"),\n parentBranch: this.pickString(safeContext, \"parent_branch\"),\n context: safeContext\n };\n }\n safeParseContext(raw) {\n if (!raw || !raw.trim())\n return;\n try {\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed;\n }\n return;\n } catch {\n return;\n }\n }\n pickString(obj, key) {\n if (!obj)\n return;\n const v = obj[key];\n return typeof v === \"string\" ? v : undefined;\n }\n static STRIPPED_KEYS = [\"commit\", \"token\", \"secret\", \"password\", \"api_key\"];\n stripSensitiveKeys(obj) {\n if (obj === null || obj === undefined)\n return obj;\n if (Array.isArray(obj))\n return obj.map((v) => this.stripSensitiveKeys(v));\n if (typeof obj !== \"object\")\n return obj;\n const out = {};\n const strippedKeys = TaskCreationRegistry.STRIPPED_KEYS;\n for (const [k, v] of Object.entries(obj)) {\n const lower = k.toLowerCase();\n if (strippedKeys.some((s) => lower.includes(s)))\n continue;\n out[k] = this.stripSensitiveKeys(v);\n }\n return out;\n }\n upsert(record) {\n this.records.set(record.taskId, record);\n }\n indexParentChild(record) {\n if (record.parentTaskId === undefined || record.parentTaskId === null)\n return;\n const parentId = record.parentTaskId;\n let set = this.childrenIndex.get(parentId);\n if (!set) {\n set = new Set;\n this.childrenIndex.set(parentId, set);\n }\n set.add(record.taskId);\n }\n collectSubtree(rootId) {\n const out = new Set([rootId]);\n const queue = [rootId];\n while (queue.length > 0) {\n const id = queue.shift();\n const children = this.childrenIndex.get(id);\n if (!children)\n continue;\n for (const child of children) {\n if (!out.has(child)) {\n out.add(child);\n queue.push(child);\n }\n }\n }\n return out;\n }\n evictIfNeeded() {\n if (this.records.size <= this.maxEntries)\n return;\n const overflow = this.records.size - this.maxEntries;\n const keys = Array.from(this.records.keys()).slice(0, overflow);\n for (const k of keys) {\n this.remove(k);\n }\n }\n}\n\n// src/env/task/registry-hook-installer.ts\ninit_logger();\nvar logger = createLogger(\"registry-hook-installer\");\nfunction installTaskCreationRegistryHooks(taskComponent, registry, options = {}) {\n const uniqueSuffix = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;\n const hookName = options.hookName ? `${options.hookName}:${uniqueSuffix}` : `registry-hook-installer:${uniqueSuffix}`;\n const priority = options.priority ?? 100;\n let uninstalled = false;\n const safeRecord = (task, source) => {\n try {\n registry.record(task, source);\n } catch (err) {\n logger.warn(`[registry-hook-installer] record failed for task #${task.id}: ${err instanceof Error ? err.message : String(err)}`);\n }\n };\n const safeUpdate = (task, source) => {\n try {\n registry.update(task, source);\n } catch (err) {\n logger.warn(`[registry-hook-installer] update failed for task #${task.id}: ${err instanceof Error ? err.message : String(err)}`);\n }\n };\n const safeRemove = (id) => {\n try {\n registry.remove(id);\n } catch (err) {\n logger.warn(`[registry-hook-installer] remove failed for task #${id}: ${err instanceof Error ? err.message : String(err)}`);\n }\n };\n const buildSource = () => ({\n sessionId: options.sessionIdProvider?.(),\n ...options.staticSource ?? {}\n });\n const afterCreate = {\n name: `${hookName}:after-create`,\n priority,\n execute: async (ctx) => {\n const data = ctx.data;\n if (data?.task)\n safeRecord(data.task, buildSource());\n }\n };\n const afterUpdate = {\n name: `${hookName}:after-update`,\n priority,\n execute: async (ctx) => {\n const data = ctx.data;\n if (!data?.task)\n return;\n const exists = registry.peekById(data.task.id);\n if (exists) {\n safeUpdate(data.task, buildSource());\n } else {\n safeRecord(data.task, buildSource());\n }\n }\n };\n const afterComplete = {\n name: `${hookName}:after-complete`,\n priority,\n execute: async (ctx) => {\n const data = ctx.data;\n if (data?.task)\n safeUpdate(data.task, buildSource());\n }\n };\n const afterDelete = {\n name: `${hookName}:after-delete`,\n priority,\n execute: async (ctx) => {\n const data = ctx.data;\n if (typeof data?.id === \"number\")\n safeRemove(data.id);\n }\n };\n taskComponent.registerHook(TaskHookPoints.AFTER_CREATE, afterCreate);\n taskComponent.registerHook(TaskHookPoints.AFTER_UPDATE, afterUpdate);\n taskComponent.registerHook(TaskHookPoints.AFTER_COMPLETE, afterComplete);\n taskComponent.registerHook(TaskHookPoints.AFTER_DELETE, afterDelete);\n return {\n uninstall() {\n if (uninstalled)\n return;\n uninstalled = true;\n taskComponent.unregisterHook(TaskHookPoints.AFTER_CREATE, afterCreate.name);\n taskComponent.unregisterHook(TaskHookPoints.AFTER_UPDATE, afterUpdate.name);\n taskComponent.unregisterHook(TaskHookPoints.AFTER_COMPLETE, afterComplete.name);\n taskComponent.unregisterHook(TaskHookPoints.AFTER_DELETE, afterDelete.name);\n logger.debug(`[registry-hook-installer] uninstalled hooks (name=${hookName})`);\n }\n };\n}\n\n// src/env/task/task-reuse-registry.ts\ninit_logger();\nvar logger2 = createLogger(\"task-reuse-registry\");\nvar DEFAULT_CONFIG = {\n maxEntries: 500,\n ttlMs: 24 * 60 * 60 * 1000,\n maxDescriptionChars: 240\n};\nvar registries = new WeakMap;\nfunction getOrCreateTaskReuseRegistry(env) {\n const existing = registries.get(env);\n if (existing)\n return existing.registry;\n const registry = new TaskCreationRegistry(DEFAULT_CONFIG);\n let installHandle = { uninstall: () => {} };\n try {\n const taskComponent = env.getComponent?.(\"task\");\n if (taskComponent?.registerHook) {\n installHandle = installTaskCreationRegistryHooks(taskComponent, registry, {\n sessionIdProvider: () => {\n try {\n return env.currentSessionId ?? undefined;\n } catch {\n return;\n }\n },\n staticSource: {\n processId: typeof process !== \"undefined\" ? process.pid : undefined\n }\n });\n logger2.debug(\"[task-reuse-registry] hook installed\");\n } else {\n logger2.debug(\"[task-reuse-registry] no TaskComponent in env; registry stays empty\");\n }\n } catch (err) {\n logger2.warn(`[task-reuse-registry] hook install failed: ${err instanceof Error ? err.message : String(err)}`);\n }\n const entry = { registry, installHandle };\n registries.set(env, entry);\n return registry;\n}\n\n// src/env/task/task-reuse-context.ts\nvar TOKEN_PATTERNS2 = [\n /\\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\\b/g,\n /\\bxox[abprs]-[A-Za-z0-9-]{8,}\\b/g,\n /\\bghp_[A-Za-z0-9]{16,}\\b/g,\n /\\bgithub_pat_[A-Za-z0-9_]{16,}\\b/g,\n /\\bBearer\\s+[A-Za-z0-9._\\-+/=]{12,}\\b/g,\n /\\bAKIA[0-9A-Z]{16}\\b/g\n];\nfunction redact(s) {\n let out = s;\n for (const pat of TOKEN_PATTERNS2)\n out = out.replace(pat, \"<redacted>\");\n return out;\n}\nfunction truncate2(s, max) {\n if (s.length <= max)\n return s;\n if (max <= 1)\n return s.slice(0, max);\n return s.slice(0, max - 1) + \"…\";\n}\nfunction buildReuseCandidateSection(options) {\n const limit = options.limit ?? 5;\n const maxChars = options.maxChars ?? 2000;\n const maxDescChars = options.maxDescriptionChars ?? 240;\n const heading = options.heading ?? \"Recent task context (reuse candidates)\";\n const recent = options.registry.recent({\n scope: options.scope,\n limit,\n statuses: options.statuses,\n excludeIds: options.similarTaskIds ?? [],\n excludeAncestorOf: options.excludeAncestorOf\n });\n if (recent.length === 0) {\n return { markdown: \"\", candidateIds: [], isEmpty: true };\n }\n const lines = [];\n lines.push(`## ${heading}`);\n lines.push(\"\");\n lines.push(\"The following tasks were recently created in this process / session and may be related to your current work. \" + \"Before creating a brand-new task, check whether one of these is the same work continuing. \" + \"The list is a *suggestion only* — confirm with `task_get <id>` before reusing.\");\n lines.push(\"\");\n for (const rec of recent) {\n lines.push(`### Task #${rec.taskId}: ${rec.title}`);\n lines.push(`- Status: ${rec.status}`);\n if (rec.parentTaskId !== undefined && rec.parentTaskId !== null) {\n lines.push(`- Parent: #${rec.parentTaskId}`);\n }\n if (rec.source.subagentType) {\n lines.push(`- Created by: ${rec.source.subagentType}`);\n }\n lines.push(`- Updated: ${rec.updatedAt}`);\n if (rec.project_path) {\n lines.push(`- Project: ${rec.project_path}`);\n }\n if (rec.worktree_path) {\n lines.push(`- Worktree: ${rec.worktree_path}`);\n }\n if (rec.branch) {\n lines.push(`- Branch: ${rec.branch}`);\n }\n if (rec.parentBranch) {\n lines.push(`- Parent branch: ${rec.parentBranch}`);\n }\n let summary;\n try {\n summary = options.registry.getSubtreeSummary(rec.taskId);\n } catch {\n summary = undefined;\n }\n if (summary && summary.descendantCount > 0) {\n lines.push(`- Children: ${summary.descendantCount} ` + `(active: ${summary.activeCount}, completed: ${summary.completedCount}, max depth: ${summary.maxDepth})`);\n }\n const hasActiveChild = summary !== undefined && summary.activeCount > 0;\n if (rec.status === \"completed\" && hasActiveChild) {\n lines.push(`- ⚠ Has active child — reopening this parent will conflict with running work; prefer creating a child task.`);\n }\n const safeDesc = redact(truncate2(rec.description, maxDescChars));\n if (safeDesc) {\n lines.push(`- Description: ${safeDesc}`);\n }\n if (rec.tags && rec.tags.length > 0) {\n lines.push(`- Tags: ${rec.tags.join(\", \")}`);\n }\n lines.push(\"\");\n }\n lines.push(\"---\");\n lines.push(\"\");\n lines.push(\"### Reuse instructions\");\n lines.push(\"\");\n lines.push(\"1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations.\");\n lines.push(\"2. **If it is the same work continuing** — prefer `task_update` over `task_create`:\");\n lines.push(\" - Set `status` back to `active` (or `todo`) to reopen a completed task.\");\n lines.push(\" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace).\");\n lines.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: \"decision\"` to record the continuation.');\n lines.push(\"3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate.\");\n lines.push(\"4. Do **not** create a duplicate task merely because the existing one is already `completed` — reopen it instead.\");\n lines.push(\"5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome.\");\n lines.push(\"\");\n lines.push(\"### Decision matrix — three legal paths\");\n lines.push(\"\");\n lines.push(\"Pick exactly **one** of these paths before calling `task_create`. Reopen-first\");\n lines.push(\"remains the default, but the matrix adds two new paths for independent work.\");\n lines.push(\"\");\n lines.push(\"**Path A — Continuation (reopen existing task).** The new work is the SAME\");\n lines.push('logical task. Use `task_update(task_id=<id>, { status: \"active\", ... })` and');\n lines.push(\"append description/goals. Do **not** create a new task id.\");\n lines.push(\"\");\n lines.push(\"```\");\n lines.push('task_update(task_id=<parent_id>, { status: \"active\", current_status: \"...\" })');\n lines.push('task_operation_create({ task_id=<parent_id>, milestone_type: \"decision\",');\n lines.push(' milestone_title: \"Reopened for <new-scope>\",');\n lines.push(' milestone_description: \"<why this is the same work>\" })');\n lines.push(\"```\");\n lines.push(\"\");\n lines.push(\"**Path B — Child task (parent_task_id=<id>).** The new work is related but\");\n lines.push(\"distinct: an independent bug fix, optimization, parallel delivery or\");\n lines.push(\"independent acceptance item under the same feature. Create a child task so\");\n lines.push(\"the audit trail is preserved. Always pair with an audit operation.\");\n lines.push(\"\");\n lines.push(\"```\");\n for (const rec of recent) {\n const safeProj = rec.project_path ?? \"<project_path>\";\n lines.push(`task_create(parent_task_id=${rec.taskId}, title=\"<distinguishing title>\", ` + `project_path=\"${safeProj}\", context=<inherit or override>)`);\n break;\n }\n lines.push('task_operation_create({ task_id=<new_id>, milestone_type: \"milestone\",');\n lines.push(' milestone_title: \"Child of #<parent_id>: <new-scope>\",');\n lines.push(' milestone_description: \"<why this is a sibling/child, not a reopen>\" })');\n lines.push(\"```\");\n lines.push(\"\");\n lines.push(\"**Path C — New root (no parent_task_id).** The new work is unrelated to any\");\n lines.push(\"existing task. Create a brand-new root task. Use this sparingly — root count\");\n lines.push(\"should stay ≤ ~10 to keep the tree readable.\");\n lines.push(\"\");\n lines.push(\"```\");\n lines.push('task_create(parent_task_id=undefined, title=\"<distinct topic>\", project_path=\"<project_path>\", context=<json>)');\n lines.push('task_operation_create({ task_id=<new_id>, milestone_type: \"create\",');\n lines.push(' milestone_title: \"New root: <topic>\",');\n lines.push(' milestone_description: \"<why this is not a child of any existing task>\" })');\n lines.push(\"```\");\n lines.push(\"\");\n lines.push(\"**Operation audit templates.** Every `task_create`/`task_update` call MUST be\");\n lines.push(\"followed by a `task_operation_create` so the next agent sees *why* the path was\");\n lines.push(\"chosen. Use the appropriate `milestone_type`:\");\n lines.push(\" - continuation → `decision` (and `progress` once the new scope makes headway)\");\n lines.push(\" - child task → `milestone` (then `progress` as the child advances)\");\n lines.push(\" - new root → `create` (then `progress` per phase)\");\n lines.push(\"\");\n lines.push(\"**Project + context inheritance.** For Path B/C, prefer inheriting the\");\n lines.push(\"candidate's `project_path`, `context.worktree_path`, `context.branch` and\");\n lines.push(\"`context.parent_branch` from the parent task. Sensitive keys (commits,\");\n lines.push(\"tokens, secrets) are stripped automatically. Use the helper:\");\n lines.push(\"\");\n lines.push(\"```\");\n lines.push(\"inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })\");\n lines.push(\"```\");\n lines.push(\"\");\n let markdown = lines.join(`\n`);\n if (markdown.length > maxChars) {\n markdown = truncate2(markdown, maxChars);\n }\n return {\n markdown,\n candidateIds: recent.map((r) => r.taskId),\n isEmpty: false\n };\n}\n\n// src/env/task/delegate/delegate-tool.ts\nvar logger3 = createLogger(\"task:delegate\");\nvar BackgroundTaskEventTypes = {\n STARTED: \"task.background.started\",\n PROGRESS: \"task.background.progress\",\n COMPLETED: \"task.background.completed\",\n FAILED: \"task.background.failed\",\n TIMEOUT: \"task.background.timeout\",\n STOPPED: \"task.background.stopped\",\n ASK_USER: \"task.background.ask_user\"\n};\nvar builtInSubAgents = [\n {\n id: \"general\",\n name: \"general\",\n mode: \"subagent\",\n description: \"General-purpose agent for researching complex questions and executing multi-step tasks.\",\n promptOverride: `You are a subagent created by the main agent to handle a specific task.\n\n## Your Role\n- You were created to handle: {task_description}\n- Complete this task. That's your entire purpose.\n- You are NOT the main agent. Don't try to be.\n\n## Task Context Awareness (Required Behavior)\n\n**IMPORTANT: Before starting any work, you MUST gather task context to avoid working with outdated or missing information.**\n\n**Step 0: Check if task_id is already provided**\n- The session info above includes \\`task_id\\`.\n- **If task_id is provided** (not N/A or 0):\n Use \\`task_get\\` with that task_id directly — this is your confirmed task.\n **Skip any searching.** Read its details and operations.\n- **If no valid task_id** is provided:\n Use the task description to guide your work.\n Look for the task via \\`task_list\\` if needed.\n\n**Then gather full context:**\n1. **Read task details**: Use \\`task_get\\` to read the task's:\n - \\`description\\`: Detailed description of what needs to be done\n - \\`goals_and_expected_deliverables\\`: Clear success criteria and expected outputs\n - \\`current_status\\`: Current work progress\n - \\`parent_task_id\\`: If exists, this is a sub-task\n\n2. **Read recent operations**: Use \\`task_operation_list\\` to get the last ~15 operation records\n - These provide history, progress, decisions, and context from previous work\n\n3. **Read parent task context** (if \\`parent_task_id\\` exists):\n - Use \\`task_get\\` to read the parent task's description and goals\n - Use \\`task_operation_list\\` to get parent's recent operations\n - This forms the overall task background and ensures alignment\n\n**Why this matters**: \n- The main agent may have made critical decisions recorded in operations\n- Parent task goals provide the broader context for your sub-task\n- Without this context, you risk working on wrong/outdated goals\n\n## Rules\n1. **Gather context first** - Always read task details and operations before starting\n2. **Stay focused** - Do your assigned task, nothing else\n3. **Complete the task** - Your final message will be automatically reported to the main agent\n4. **Don't initiate** - No heartbeats, no proactive actions, no side quests\n5. **Be ephemeral** - You may be terminated after task completion. That's fine.\n6. **No nested delegation** - Do NOT use delegate_task or stop_task tools. Complete the task yourself.\n\n## Execution\n- Use the available tools to complete the task\n- If you need more information, ask the main agent through the result\n- Return a clear summary of what you did and the results`,\n deniedTools: [\"delegate_task\", \"stop_task\"]\n },\n {\n id: \"explore\",\n name: \"explore\",\n mode: \"subagent\",\n description: \"Fast agent specialized for exploring codebases, finding files, and searching for patterns.\",\n allowedTools: [\"read_file\", \"glob\", \"grep\", \"bash\"],\n deniedTools: [\"delegate_task\", \"stop_task\"]\n },\n {\n id: \"roy\",\n name: \"Roy\",\n mode: \"subagent\",\n description: \"Versatile AI assistant inspired by Jarvis — intelligent, proactive, and capable. Use for general-purpose tasks, coding, research, and complex multi-step work. Always available (built-in) without `agent add roy`.\",\n promptOverride: builtInPrompts[\"roy\"],\n deniedTools: [\"delegate_task\", \"stop_task\"]\n }\n];\nfunction getSubAgentSpec(id) {\n return builtInSubAgents.find((agent) => agent.id === id);\n}\nfunction ensureSubAgentRegistered(agentComponent, subagentType, basePrompt, subAgent, deniedTools) {\n const registry = agentComponent.getRegistry?.();\n if (registry) {\n const agentDef = registry.get(subagentType);\n if (agentDef?.type === \"workflow\") {\n logger3.debug(`[delegate] Skipping registration for workflow agent: ${subagentType}`);\n return null;\n }\n }\n let agentInstance = agentComponent.getAgent(subagentType);\n if (!agentInstance) {\n const agentConfig = {\n type: \"sub\",\n systemPrompt: basePrompt\n };\n if (subAgent?.allowedTools && subAgent.allowedTools.length > 0) {\n agentConfig.allowedTools = subAgent.allowedTools;\n }\n if (deniedTools.length > 0) {\n agentConfig.deniedTools = deniedTools;\n }\n agentInstance = agentComponent.registerAgent(subagentType, agentConfig);\n logger3.debug(`[delegate] Registered subagent: ${subagentType}`);\n }\n return agentInstance;\n}\nvar DelegateToolParameters = z.object({\n description: z.string().describe(\"A short (3-5 words) description of the task\"),\n prompt: z.string().describe(\"The task for the agent to perform\"),\n subagent_type: z.string().describe(\"The type of specialized agent to use for this task\").default(\"general\"),\n timeout: z.number().describe(\"Task timeout in milliseconds. Default: 1800000 (30 minutes). If set, task will be terminated after timeout.\").optional(),\n reason: z.string().describe(\"Brief reason for calling this tool (max 30 chars, e.g., 'Delegate refactor task')\").optional(),\n similar_task_ids: z.array(z.number()).max(3).describe(\"Similar task IDs (max 3) to reference for improving task execution. Search for similar tasks before calling this tool.\"),\n sub_session_id: z.string().describe(\"Existing sub-agent session ID to resume. \" + \"If provided, the sub-agent will continue from the previous conversation \" + \"context (used for retry on timeout/failure). \" + \"Leave empty for a new session.\").optional(),\n triggerEventId: z.string().describe(\"EventStore trigger event ID (ESPlugin v2). Pass it when this delegate_task \" + \"is triggered by an external event source (e.g. Feishu message) so the \" + \"completion notification can reply to the original chat instead of a \" + \"fallback channel. Leave empty if not triggered by an event source.\").optional()\n});\nfunction buildEntryAgentPrompt(options) {\n const { workflowName, originalPrompt, description } = options;\n return `# Workflow 调度请求\n\n你被调用是因为上游 \\`delegate_task\\` 检测到 workflow 类型 subagent **${workflowName}**。\n请通过 \\`workflow_run\\` 命令调度对应 workflow。\n\n<workflow_name>${workflowName}</workflow_name>\n\n## 调度目标\n\n- **Workflow 名称**: \\`${workflowName}\\` (权威来源: \\`<workflow_name>\\` 标签, 不要从上下文猜测)\n- **任务描述**: ${description}\n\n## 原始用户请求\n\n${originalPrompt}\n\n## 你的行动\n\n1. \\`workflow_get(${workflowName})\\` 取 workflow 入参 schema\n2. 从\"原始用户请求\"提取符合 schema 的 input 字段\n3. \\`workflow_run(${workflowName}, input)\\` 触发 workflow\n4. 把 output 原样回给 parent agent\n\n不要做其他工作。只走 \\`workflow_run\\` 路径。\n`;\n}\nvar WORKFLOW_COMPAT_ALIASES = new Set([\n \"strict-task-agent\",\n \"code-review\",\n \"bench-agent-host\",\n \"workspace-analyzer\",\n \"test-workflow-agent\"\n]);\nvar DEFAULT_TIMEOUT = 1800000;\nvar PROGRESS_INTERVAL = 1200000;\n\nclass BackgroundTaskManager {\n env;\n maxProcessRegistries = 1000;\n maxTerminalTasks = 1000;\n tasks = new Map;\n terminalTasks = new Map;\n abortControllers = new Map;\n progressTimers = new Map;\n processRegistries = new Map;\n workflowRunRegistries = new Map;\n workflowService;\n constructor(env) {\n this.env = env;\n }\n setWorkflowService(svc) {\n this.workflowService = svc;\n }\n attachWorkflowRun(bgTaskId, workflowRunId) {\n if (!bgTaskId || !workflowRunId)\n return;\n let set = this.workflowRunRegistries.get(bgTaskId);\n if (!set) {\n set = new Set;\n this.workflowRunRegistries.set(bgTaskId, set);\n }\n set.add(workflowRunId);\n }\n detachWorkflowRun(bgTaskId, workflowRunId) {\n this.workflowRunRegistries.get(bgTaskId)?.delete(workflowRunId);\n }\n replaceWorkflowRun(bgTaskId, oldRunId, newRunId) {\n if (!bgTaskId)\n return;\n const set = this.workflowRunRegistries.get(bgTaskId);\n if (!set)\n return;\n if (oldRunId) {\n set.delete(oldRunId);\n }\n if (newRunId) {\n set.add(newRunId);\n }\n }\n async propagateStopToWorkflowRuns(bgTaskId, reason) {\n const set = this.workflowRunRegistries.get(bgTaskId);\n if (!set || set.size === 0) {\n return { runIds: [], stopResults: [] };\n }\n const runIds = Array.from(set);\n logger3.info(`[BackgroundTaskManager] propagateStopToWorkflowRuns count=${runIds.length} bgTaskId=${bgTaskId}`);\n const stopResults = [];\n for (const runId of runIds) {\n if (typeof this.workflowService?.stopRun !== \"function\") {\n logger3.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${runId}`);\n stopResults.push({\n runId,\n success: false,\n error: \"workflowService not injected\"\n });\n continue;\n }\n try {\n await this.workflowService.stopRun(runId, reason);\n stopResults.push({ runId, success: true });\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n logger3.warn(`[BackgroundTaskManager] workflowService.stopRun(${runId}) failed (likely already terminal): ${errMsg}`);\n stopResults.push({ runId, success: false, error: errMsg });\n }\n }\n set.clear();\n return { runIds, stopResults };\n }\n finalizeTask(taskId, reason) {\n if (!taskId)\n return;\n this.stopProgressReporter(taskId);\n this.progressTimers.delete(taskId);\n const task = this.tasks.get(taskId);\n if (task) {\n this.tasks.delete(taskId);\n if (this.terminalTasks.size >= this.maxTerminalTasks) {\n const oldestKey = this.terminalTasks.keys().next().value;\n if (oldestKey !== undefined) {\n this.terminalTasks.delete(oldestKey);\n }\n }\n this.terminalTasks.set(taskId, task);\n }\n const abortCtl = this.abortControllers.get(taskId);\n if (abortCtl && reason !== \"completed\") {\n if (!abortCtl.signal.aborted) {\n try {\n abortCtl.abort();\n } catch {}\n }\n }\n this.abortControllers.delete(taskId);\n this.workflowRunRegistries.delete(taskId);\n const registry = this.processRegistries.get(taskId);\n if (registry && registry.size() > 0) {\n logger3.debug(`[BackgroundTaskManager] finalizeTask保留 processRegistry ${taskId} (residualPIDs=${registry.size()}, reason=${reason})`);\n }\n logger3.debug(`[BackgroundTaskManager] finalizeTask taskId=${taskId} reason=${reason}`);\n }\n getProcessRegistrySize() {\n return this.processRegistries.size;\n }\n getMaxProcessRegistries() {\n return this.maxProcessRegistries;\n }\n cleanupEmptyProcessRegistries() {\n let cleaned = 0;\n for (const [taskId, registry] of this.processRegistries) {\n if (registry.size() === 0) {\n this.processRegistries.delete(taskId);\n cleaned++;\n }\n }\n return cleaned;\n }\n static DEFAULT_WORKFLOW_ENTRY_AGENT = \"workflow-runner\";\n resolveEntryAgent(subagentType) {\n try {\n if (BackgroundTaskManager.detectWorkflowShortcutCompat(subagentType)) {\n logger3.info(`[BackgroundTaskManager] Compat rewrite: '${subagentType}' → '${BackgroundTaskManager.DEFAULT_WORKFLOW_ENTRY_AGENT}'`);\n return BackgroundTaskManager.DEFAULT_WORKFLOW_ENTRY_AGENT;\n }\n const agentComponent = this.env?.getComponent?.(\"agent\");\n const registry = agentComponent?.getRegistry?.();\n const agent = registry?.get?.(subagentType);\n if (!agent || agent.type !== \"workflow\") {\n return;\n }\n return agent.entryAgent ?? BackgroundTaskManager.DEFAULT_WORKFLOW_ENTRY_AGENT;\n } catch (err) {\n logger3.warn(`[BackgroundTaskManager] resolveEntryAgent failed for ${subagentType}: ${err}`);\n return;\n }\n }\n static _detectWorkflowShortcutWrapped = wrapFunction((subagentType) => WORKFLOW_COMPAT_ALIASES.has(subagentType), \"delegate.detectWorkflowShortcut\", { recordParams: true, recordResult: true, log: true });\n static detectWorkflowShortcutCompat(subagentType) {\n return BackgroundTaskManager._detectWorkflowShortcutWrapped(subagentType);\n }\n getSessionComponent() {\n return this.env?.getComponent?.(\"session\");\n }\n async resolveAssociatedTaskIdBySubSession(subSessionId) {\n if (!subSessionId)\n return;\n try {\n const taskComponent = this.env?.getComponent?.(\"task\");\n const id = await taskComponent?.getTaskIdBySessionId?.(subSessionId);\n return typeof id === \"number\" && id > 0 ? id : undefined;\n } catch (err) {\n logger3.debug(`[BackgroundTaskManager] resolveAssociatedTaskIdBySubSession failed for ${subSessionId}: ${err instanceof Error ? err.message : String(err)}`);\n return;\n }\n }\n publishBackgroundEvent(type, payload, parentSessionId, triggerEventId, replyChannel) {\n if (this.env?.pushEnvEvent) {\n this.env.pushEnvEvent({\n type,\n payload,\n metadata: {\n source: \"task.background\",\n trigger_session_id: parentSessionId,\n ...triggerEventId ? { triggerEventId } : {},\n ...replyChannel ? { replyChannel } : {}\n }\n });\n logger3.info(`[BackgroundTaskManager] Event published: ${type}`, {\n triggerEventId,\n replyChannelChatId: replyChannel?.chatId\n });\n }\n }\n publishBackgroundEventWithTrigger(type, payload, parentSessionId, triggerEventId, replyChannel) {\n this.publishBackgroundEvent(type, payload, parentSessionId, triggerEventId, replyChannel);\n }\n static parseAskUserErrorFromMessage(error) {\n const rawErrorMessage = error instanceof Error ? error.message : String(error);\n if (error && typeof error === \"object\" && error.name === \"AskUserError\" && error.query) {\n const e = error;\n return {\n query: e.query,\n sessionId: e.sessionId,\n nodeId: e.nodeId,\n nodeType: e.nodeType || \"agent\",\n agentSessionId: e.agentSessionId,\n rawErrorMessage\n };\n }\n const prefix = \"__ASK_USER_ERROR__:\";\n if (rawErrorMessage.includes(prefix)) {\n try {\n const jsonStr = rawErrorMessage.substring(rawErrorMessage.indexOf(prefix) + prefix.length);\n const parsed = JSON.parse(jsonStr);\n return {\n query: parsed.query,\n sessionId: parsed.sessionId,\n nodeId: parsed.nodeId,\n nodeType: parsed.nodeType || \"agent\",\n agentSessionId: parsed.agentSessionId,\n rawErrorMessage\n };\n } catch (parseErr) {\n logger3.warn(`[BackgroundTaskManager] Failed to parse __ASK_USER_ERROR__ payload`, { error: parseErr instanceof Error ? parseErr.message : String(parseErr) });\n return null;\n }\n }\n return null;\n }\n async createTask(options) {\n const { parentSessionId, description, prompt, subagentType, timeout, similarTaskIds, existingSubSessionId, triggerEventId } = options;\n const taskIdGen = `process_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;\n const sessionComponent = this.getSessionComponent();\n if (!sessionComponent) {\n throw new Error(\"SessionComponent not found\");\n }\n const parentSession = await sessionComponent.get(parentSessionId);\n if (!parentSession) {\n throw new Error(`Parent session not found: ${parentSessionId}`);\n }\n let subSession;\n if (existingSubSessionId) {\n const reusedSession = await sessionComponent.get(existingSubSessionId);\n if (!reusedSession) {\n throw new Error(`Sub session not found for resume: ${existingSubSessionId}`);\n }\n const createdBy = reusedSession?.metadata?.created_by;\n if (createdBy && createdBy !== \"subagent\") {\n logger3.warn(`[BackgroundTaskManager] Session ${existingSubSessionId} was not created by a sub-agent (created_by=${createdBy}); reusing anyway`);\n }\n subSession = reusedSession;\n try {\n const existingMeta = reusedSession?.metadata ?? {};\n await sessionComponent.update(existingSubSessionId, {\n metadata: {\n ...existingMeta,\n reused_sub_session: true,\n reused_at: Date.now()\n }\n });\n } catch (err) {\n logger3.warn(`[BackgroundTaskManager] Failed to update reused session metadata`, { existingSubSessionId, error: err instanceof Error ? err.message : String(err) });\n }\n logger3.info(`[BackgroundTaskManager] Reusing sub session: ${existingSubSessionId} for task ${taskIdGen}`);\n } else {\n const metadata = {\n subagent_type: subagentType,\n created_by: \"subagent\",\n task_description: description\n };\n const parentEnvContext = getEnvContext();\n if (parentEnvContext) {\n if (parentEnvContext.messageId) {\n metadata.messageId = parentEnvContext.messageId;\n }\n const replyChannel = parentEnvContext.replyChannel;\n if (replyChannel?.messageId) {\n metadata.larkMessageId = replyChannel.messageId;\n }\n if (replyChannel?.chatId) {\n metadata.chatId = replyChannel.chatId;\n }\n if (replyChannel?.userId) {\n metadata.larkUserId = replyChannel.userId;\n }\n const profile = replyChannel?.profile;\n if (profile) {\n metadata.larkProfile = profile;\n }\n }\n if (triggerEventId) {\n metadata.triggerEventId = triggerEventId;\n }\n subSession = await sessionComponent.create({\n title: `${description} (@${subagentType} subagent)`,\n parentSessionId,\n metadata\n });\n if (!subSession) {\n throw new Error(\"Failed to create sub-session\");\n }\n }\n const replyChannelSnapshot = captureReplyChannelSnapshot();\n const abortController = new AbortController;\n if (this.processRegistries.size >= this.maxProcessRegistries) {\n this.cleanupEmptyProcessRegistries();\n if (this.processRegistries.size >= this.maxProcessRegistries) {\n throw new Error(`BackgroundTaskManager.processRegistries 达到上限 ${this.maxProcessRegistries}(含残留 PID),拒绝创建新 task(taskId=${taskIdGen})。请清理 / 重启 / 调高 maxProcessRegistries。`);\n }\n }\n const processRegistry = new ProcessRegistry;\n this.processRegistries.set(taskIdGen, processRegistry);\n const createdAt = Date.now();\n const taskRunId = `${subagentType}:bg_${taskIdGen}`;\n const task = {\n id: taskIdGen,\n runId: taskRunId,\n subSessionId: subSession.id,\n parentSessionId,\n description,\n subagentType,\n status: \"pending\",\n createdAt,\n lastUpdatedAt: createdAt,\n abortController,\n similarTaskIds,\n triggerEventId,\n replyChannel: replyChannelSnapshot\n };\n this.tasks.set(taskIdGen, task);\n this.abortControllers.set(taskIdGen, abortController);\n const startedPayload = {\n backgroundTaskId: taskIdGen,\n subSessionId: subSession.id,\n parentSessionId,\n description,\n subagentType\n };\n this.publishBackgroundEvent(BackgroundTaskEventTypes.STARTED, startedPayload, parentSessionId, triggerEventId, replyChannelSnapshot);\n this.executeTask(taskIdGen, prompt, timeout, parentSessionId).catch((err) => {\n logger3.error(`[BackgroundTaskManager] executeTask unhandled rejection`, {\n taskId: taskIdGen,\n error: err instanceof Error ? err.message : String(err)\n });\n });\n return { taskId: taskIdGen, subSessionId: subSession.id };\n }\n async executeTask(taskId, prompt, timeout, parentSessionId) {\n const task = this.tasks.get(taskId);\n if (!task) {\n logger3.warn(`[BackgroundTaskManager] executeTask: Task not found`, { taskId });\n return;\n }\n const startedAt = Date.now();\n task.status = \"running\";\n task.startedAt = startedAt;\n task.lastUpdatedAt = startedAt;\n const timeoutMs = timeout || DEFAULT_TIMEOUT;\n const abortController = this.abortControllers.get(taskId);\n this.startProgressReporter(taskId, parentSessionId || task.parentSessionId);\n try {\n const sessionComponent = this.getSessionComponent();\n const subSession = await sessionComponent.get(task.subSessionId);\n if (!subSession) {\n throw new Error(`Sub session not found: ${task.subSessionId}`);\n }\n const taskRegistry = this.processRegistries.get(taskId);\n const result = await this.executeWithAbort(subSession, prompt, timeoutMs, taskId, abortController?.signal, task.similarTaskIds, taskRegistry, () => abortController?.abort(), task.subagentType);\n if (abortController?.signal.aborted) {\n logger3.info(`[BackgroundTaskManager] Task was aborted`, { taskId });\n return;\n }\n const completedAt = Date.now();\n task.status = \"completed\";\n task.completedAt = completedAt;\n task.lastUpdatedAt = completedAt;\n task.result = result;\n const executionTimeMs = task.completedAt - task.startedAt;\n task.associatedTaskId = getCurrentTaskId();\n if (task.associatedTaskId === undefined) {\n task.associatedTaskId = await this.resolveAssociatedTaskIdBySubSession(task.subSessionId);\n }\n const completedPayload = {\n backgroundTaskId: task.id,\n subSessionId: task.subSessionId,\n parentSessionId: parentSessionId || task.parentSessionId,\n status: \"completed\",\n result: task.result,\n description: task.description,\n executionTimeMs,\n associatedTaskId: task.associatedTaskId\n };\n this.publishBackgroundEvent(BackgroundTaskEventTypes.COMPLETED, completedPayload, parentSessionId || task.parentSessionId, task.triggerEventId, task.replyChannel);\n logger3.info(`[BackgroundTaskManager] Task completed successfully`, {\n taskId,\n executionTimeMs\n });\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n const askUserInfo = BackgroundTaskManager.parseAskUserErrorFromMessage(error);\n const isStoppedError = errorMessage.toLowerCase().includes(\"stopped\") || errorMessage.toLowerCase().includes(\"aborted\");\n const executionTimeMs = task.startedAt ? Date.now() - task.startedAt : 0;\n const completedAt = Date.now();\n task.completedAt = completedAt;\n task.lastUpdatedAt = completedAt;\n task.associatedTaskId = getCurrentTaskId();\n if (task.associatedTaskId === undefined) {\n task.associatedTaskId = await this.resolveAssociatedTaskIdBySubSession(task.subSessionId);\n }\n if (askUserInfo) {\n task.status = \"awaiting-user\";\n task.error = askUserInfo.rawErrorMessage;\n task.pendingAskUserQuery = askUserInfo.query;\n const askUserPayload = {\n backgroundTaskId: task.id,\n subSessionId: task.subSessionId,\n parentSessionId: parentSessionId || task.parentSessionId,\n subagentType: task.subagentType,\n description: task.description,\n query: askUserInfo.query,\n sessionId: askUserInfo.sessionId,\n nodeId: askUserInfo.nodeId,\n nodeType: askUserInfo.nodeType,\n agentSessionId: askUserInfo.agentSessionId,\n error: askUserInfo.rawErrorMessage,\n executionTimeMs,\n hints: [\n \"请把上面的问题原样通过 ask_user tool 展示给用户并等待答复\",\n `得到用户回复后,通过 delegate_task(subagentType=\"${task.subagentType}\", existingSubSessionId=\"${task.subSessionId}\", prompt=<基于用户回复>) 复用 sub-session 让 sub-agent 继承之前消息历史继续推进,无需实现 resume function`\n ],\n associatedTaskId: task.associatedTaskId\n };\n this.publishBackgroundEvent(BackgroundTaskEventTypes.ASK_USER, askUserPayload, parentSessionId || task.parentSessionId, task.triggerEventId, task.replyChannel);\n logger3.info(`[BackgroundTaskManager] Task awaiting user input (ask_user cascade)`, {\n taskId,\n subSessionId: task.subSessionId,\n nodeId: askUserInfo.nodeId,\n queryPreview: askUserInfo.query.substring(0, 80)\n });\n task._preserveSubSessionOnExit = true;\n return;\n }\n if (isStoppedError) {\n task.status = \"stopped\";\n const stoppedPayload = {\n backgroundTaskId: task.id,\n subSessionId: task.subSessionId,\n parentSessionId: parentSessionId || task.parentSessionId,\n status: \"stopped\",\n description: task.description,\n error: errorMessage,\n executionTimeMs,\n associatedTaskId: task.associatedTaskId\n };\n this.publishBackgroundEvent(BackgroundTaskEventTypes.STOPPED, stoppedPayload, parentSessionId || task.parentSessionId, task.triggerEventId, task.replyChannel);\n } else if (errorMessage.startsWith(\"Task execution timeout after\")) {\n task.status = \"timeout\";\n const timeoutPayload = {\n backgroundTaskId: task.id,\n subSessionId: task.subSessionId,\n parentSessionId: parentSessionId || task.parentSessionId,\n status: \"timeout\",\n description: task.description,\n error: errorMessage,\n executionTimeMs,\n associatedTaskId: task.associatedTaskId\n };\n this.publishBackgroundEvent(BackgroundTaskEventTypes.TIMEOUT, timeoutPayload, parentSessionId || task.parentSessionId, task.triggerEventId, task.replyChannel);\n } else {\n task.status = \"failed\";\n const failedPayload = {\n backgroundTaskId: task.id,\n subSessionId: task.subSessionId,\n parentSessionId: parentSessionId || task.parentSessionId,\n status: \"failed\",\n error: errorMessage,\n executionTimeMs,\n associatedTaskId: task.associatedTaskId\n };\n this.publishBackgroundEvent(BackgroundTaskEventTypes.FAILED, failedPayload, parentSessionId || task.parentSessionId, task.triggerEventId, task.replyChannel);\n }\n task.error = errorMessage;\n logger3.error(`[BackgroundTaskManager] Task execution error`, {\n taskId,\n status: task.status,\n error: errorMessage\n });\n } finally {\n this.finalizeTask(taskId, task.status);\n const preserveSubSession = task?._preserveSubSessionOnExit === true;\n const sessionComp = this.getSessionComponent();\n if (!preserveSubSession && sessionComp?.endSessionCleanup && task?.subSessionId) {\n try {\n await sessionComp.endSessionCleanup(task.subSessionId);\n } catch (err) {\n logger3.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${task.subSessionId}`, { error: err instanceof Error ? err.message : String(err) });\n }\n } else if (preserveSubSession) {\n logger3.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${task.subSessionId}`);\n }\n }\n }\n startProgressReporter(taskId, parentSessionId) {\n const timer = setInterval(() => {\n const task = this.tasks.get(taskId);\n if (!task || task.status !== \"running\") {\n this.stopProgressReporter(taskId);\n return;\n }\n const currentTaskId = getCurrentTaskId();\n if (currentTaskId !== undefined) {\n task.associatedTaskId = currentTaskId;\n }\n task.lastUpdatedAt = Date.now();\n const progressPayload = {\n backgroundTaskId: taskId,\n subSessionId: task.subSessionId,\n parentSessionId,\n description: task.description,\n status: task.status,\n associatedTaskId: task.associatedTaskId\n };\n this.publishBackgroundEvent(BackgroundTaskEventTypes.PROGRESS, progressPayload, parentSessionId, task.triggerEventId, task.replyChannel);\n }, PROGRESS_INTERVAL);\n this.progressTimers.set(taskId, timer);\n }\n stopProgressReporter(taskId) {\n const timer = this.progressTimers.get(taskId);\n if (timer) {\n clearInterval(timer);\n this.progressTimers.delete(taskId);\n }\n }\n async executeWithAbort(subSession, prompt, timeoutMs, bgTaskId, signal, similarTaskIds, processRegistry, abortTask, explicitSubagentType) {\n const metadata = subSession?.metadata ?? {};\n const taskId = metadata.task_id;\n const taskDescription = metadata.task_description || \"\";\n const sessionId = subSession.id;\n const metaSubagentType = metadata.subagent_type;\n const subagentType = metaSubagentType || explicitSubagentType || \"general\";\n if (!metaSubagentType && !explicitSubagentType) {\n logger3.warn(`[delegate] subagent_type unresolved (no session metadata, no explicit value) — falling back to \"general\". sessionId=${sessionId}`);\n }\n const agentComponent = this.env?.getComponent?.(\"agent\");\n const registry = agentComponent?.getRegistry?.();\n const resolved = await resolveSubAgentConfig(subagentType, { registry });\n const subAgent = getSubAgentSpec(subagentType);\n const basePrompt = resolved?.basePrompt || subAgent?.promptOverride || `You are a subagent. Complete this task: {task_description}`;\n const deniedTools = resolved?.deniedTools || subAgent?.deniedTools || [];\n const allowedTools = resolved?.allowedTools || subAgent?.allowedTools;\n let fullPrompt = basePrompt.replace(/{task_description}/g, taskDescription || \"N/A\");\n fullPrompt += `\n\n---\n\n# Session Info\n- task_id: ${taskId || \"N/A\"}\n- session_id: ${sessionId}\n\n---\n\n## 用户指令\n${prompt}\n\n---\n\n## 执行规范\n- 使用可用工具完成任务\n- 返回清晰的任务执行结果摘要\n- 适时调用 task_operation_create 记录进展\n- 如果你通过 task_create 创建了任务,请在最终响应中明确报告 task_id(例如:Task #627)`;\n if (similarTaskIds && similarTaskIds.length > 0) {\n try {\n const taskComponent = this.env?.getComponent?.(\"task\");\n if (taskComponent) {\n const similarTasksSections = [];\n for (const similarId of similarTaskIds) {\n try {\n const similarTask = await taskComponent.getTask(similarId);\n if (!similarTask) {\n logger3.warn(`[delegate] Similar task #${similarId} not found, skipping`);\n continue;\n }\n const operations = await taskComponent.listOperations({ taskId: similarId, limit: 10 });\n let section = `### Task #${similarTask.id}: ${similarTask.title}\n`;\n section += `- Status: ${similarTask.status}\n`;\n if (similarTask.description) {\n section += `- Description: ${similarTask.description}\n`;\n }\n if (similarTask.goals_and_expected_deliverables) {\n section += `- Goals: ${similarTask.goals_and_expected_deliverables}\n`;\n }\n if (operations && operations.length > 0) {\n section += `- Recent Operations:\n`;\n for (const op of operations) {\n section += ` - [${op.actionType}] ${op.actionTitle}: ${op.actionDescription || \"\"}\n`;\n }\n }\n similarTasksSections.push(section);\n } catch (err) {\n logger3.warn(`[delegate] Failed to fetch similar task #${similarId}`, { error: err instanceof Error ? err.message : String(err) });\n }\n }\n if (similarTasksSections.length > 0) {\n fullPrompt += `\n\n---\n\n## Similar Tasks Reference\n\nThe following similar tasks and their operation records can serve as reference:\n\n`;\n fullPrompt += similarTasksSections.join(`\n`);\n fullPrompt += `\n\n---\n\nUse these as guidance to improve task execution efficiency.`;\n }\n }\n } catch (err) {\n logger3.warn(`[delegate] Failed to inject similar tasks reference`, { error: err instanceof Error ? err.message : String(err) });\n }\n }\n if (!agentComponent) {\n throw new Error(\"AgentComponent not found\");\n }\n try {\n if (this.env) {\n const reuseRegistry = getOrCreateTaskReuseRegistry(this.env);\n const reuseSection = buildReuseCandidateSection({\n registry: reuseRegistry,\n similarTaskIds: similarTaskIds ?? [],\n limit: 5,\n maxChars: 2000,\n maxDescriptionChars: 240\n });\n if (!reuseSection.isEmpty) {\n fullPrompt += `\n\n---\n\n${reuseSection.markdown}`;\n }\n }\n } catch (err) {\n logger3.warn(`[delegate] Failed to inject reuse candidate section`, {\n error: err instanceof Error ? err.message : String(err)\n });\n }\n const subAgentForRegister = subAgent ? { ...subAgent, allowedTools } : allowedTools ? {\n id: subagentType,\n name: subagentType,\n mode: \"subagent\",\n description: resolved?.description || \"Custom agent\",\n allowedTools,\n deniedTools\n } : undefined;\n ensureSubAgentRegistered(agentComponent, subagentType, basePrompt, subAgentForRegister, deniedTools);\n const isWorkflowAgent = registry?.get(subagentType)?.type === \"workflow\";\n const delegateQuery = isWorkflowAgent ? prompt : fullPrompt;\n return new Promise((resolve, reject) => {\n const killProcessTreeSafely = async () => {\n try {\n await processRegistry?.killAll();\n } catch (err) {\n logger3.warn(`[delegate] ProcessRegistry.killAll failed`, {\n error: err instanceof Error ? err.message : String(err)\n });\n }\n };\n let settled = false;\n let timer;\n let capturedRunId;\n const task = this.tasks.get(bgTaskId);\n if (task?.runId) {\n capturedRunId = task.runId;\n }\n const detachAbortListener = () => {\n if (signal && onAbort) {\n try {\n signal.removeEventListener(\"abort\", onAbort);\n } catch {}\n }\n };\n let onAbort;\n onAbort = () => {\n if (settled)\n return;\n settled = true;\n if (timer)\n clearTimeout(timer);\n detachAbortListener();\n try {\n const agentComp = this.env?.getComponent?.(\"agent\");\n if (agentComp?.abortRun && capturedRunId) {\n agentComp.abortRun(capturedRunId, \"task_signal_abort\");\n }\n } catch {}\n killProcessTreeSafely().catch(() => {}).then(() => {\n reject(new Error(\"Task execution stopped\"));\n });\n };\n timer = setTimeout(() => {\n if (settled)\n return;\n settled = true;\n if (timer)\n clearTimeout(timer);\n detachAbortListener();\n try {\n abortTask?.();\n } catch {}\n try {\n const agentComp = this.env?.getComponent?.(\"agent\");\n if (agentComp?.abortRun && capturedRunId) {\n agentComp.abortRun(capturedRunId, \"task_timeout\");\n }\n } catch {}\n killProcessTreeSafely().catch(() => {}).then(() => {\n reject(new Error(`Task execution timeout after ${timeoutMs}ms`));\n });\n }, timeoutMs);\n if (signal) {\n signal.addEventListener(\"abort\", onAbort);\n }\n const invokeHandleQuery = () => this.env.handle_query?.(delegateQuery, {\n sessionId,\n deniedTools: deniedTools.length > 0 ? deniedTools : undefined,\n agentType: subagentType,\n abort: signal,\n runId: capturedRunId\n });\n const wrappedPromise = processRegistry ? runWithProcessRegistryAsync(processRegistry, () => runWithBgTaskIdAsync(bgTaskId, () => invokeHandleQuery())) : runWithBgTaskIdAsync(bgTaskId, () => invokeHandleQuery());\n wrappedPromise?.then((result) => {\n if (settled)\n return;\n settled = true;\n if (timer)\n clearTimeout(timer);\n detachAbortListener();\n resolve(result);\n }).catch((error) => {\n if (settled)\n return;\n settled = true;\n if (timer)\n clearTimeout(timer);\n detachAbortListener();\n reject(error);\n });\n });\n }\n async stopTask(taskId) {\n const task = this.tasks.get(taskId) ?? this.terminalTasks.get(taskId);\n if (!task) {\n return { success: false, message: \"Task not found\" };\n }\n if (this.terminalTasks.has(taskId)) {\n return {\n success: false,\n task,\n message: `Cannot stop task with status: ${task.status}`\n };\n }\n if (task.status === \"completed\" || task.status === \"failed\" || task.status === \"stopped\" || task.status === \"timeout\") {\n return {\n success: false,\n task,\n message: `Cannot stop task with status: ${task.status}`\n };\n }\n const completedAt = Date.now();\n task.status = \"stopped\";\n task.abortController?.abort();\n if (task.runId) {\n try {\n const agentComp = this.env?.getComponent?.(\"agent\");\n agentComp?.abortRun?.(task.runId, \"stop_task\");\n } catch (err) {\n logger3.warn(`[BackgroundTaskManager] abortRun failed during stopTask`, {\n taskId,\n runId: task.runId,\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n task.completedAt = completedAt;\n task.lastUpdatedAt = completedAt;\n try {\n await this.processRegistries.get(taskId)?.killAll();\n } catch (err) {\n logger3.warn(`[delegate] stopTask killAll failed`, {\n taskId,\n error: err instanceof Error ? err.message : String(err)\n });\n }\n const { runIds, stopResults } = await this.propagateStopToWorkflowRuns(taskId, \"Task stopped by user\");\n const stoppedPayload = {\n backgroundTaskId: task.id,\n subSessionId: task.subSessionId,\n parentSessionId: task.parentSessionId,\n status: \"stopped\",\n description: task.description,\n error: \"Task stopped by user\",\n executionTimeMs: task.startedAt ? task.completedAt - task.startedAt : 0,\n associatedTaskId: task.associatedTaskId\n };\n this.publishBackgroundEvent(BackgroundTaskEventTypes.STOPPED, stoppedPayload, task.parentSessionId, task.triggerEventId, task.replyChannel);\n this.finalizeTask(taskId, \"stopped\");\n return {\n success: true,\n task,\n message: \"Task has been stopped\",\n attached_workflow_run_ids: runIds,\n workflow_stop_results: stopResults\n };\n }\n getTask(taskId) {\n return this.tasks.get(taskId) ?? this.terminalTasks.get(taskId);\n }\n listTasks() {\n return Array.from(this.tasks.values()).concat(Array.from(this.terminalTasks.values()));\n }\n hasActiveTaskForParent(parentSessionId) {\n if (!parentSessionId)\n return false;\n for (const task of this.tasks.values()) {\n if (task.parentSessionId === parentSessionId && (task.status === \"pending\" || task.status === \"running\")) {\n return true;\n }\n }\n return false;\n }\n async stopAllForParent(parentSessionId) {\n if (!parentSessionId) {\n return { stoppedTaskIds: [] };\n }\n const stoppedTaskIds = [];\n for (const [taskId, task] of this.tasks) {\n if (task.parentSessionId === parentSessionId && (task.status === \"running\" || task.status === \"pending\")) {\n try {\n const res = await this.stopTask(taskId);\n if (res?.success) {\n stoppedTaskIds.push(taskId);\n }\n } catch (err) {\n logger3.warn(`[BackgroundTaskManager] stopAllForParent failed for ${taskId}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n }\n return { stoppedTaskIds };\n }\n async forceStopAllAcrossParents() {\n const seen = new Set;\n const allTaskIds = new Set([\n ...this.tasks.keys(),\n ...this.terminalTasks.keys(),\n ...this.processRegistries.keys()\n ]);\n for (const taskId of allTaskIds) {\n if (seen.has(taskId))\n continue;\n seen.add(taskId);\n const task = this.tasks.get(taskId) ?? this.terminalTasks.get(taskId);\n const taskSafe = task;\n try {\n await this.processRegistries.get(taskId)?.killAll();\n } catch (err) {\n logger3.warn(`[BackgroundTaskManager] forceStopAllAcrossParents killAll failed for ${taskId}: ${err instanceof Error ? err.message : String(err)}`);\n }\n try {\n await this.propagateStopToWorkflowRuns(taskId, \"force stop all\");\n } catch (err) {\n logger3.warn(`[BackgroundTaskManager] forceStopAllAcrossParents propagateStopToWorkflowRuns failed for ${taskId}: ${err instanceof Error ? err.message : String(err)}`);\n }\n let justMarkedStopped = false;\n if (taskSafe && (taskSafe.status === \"running\" || taskSafe.status === \"pending\")) {\n try {\n taskSafe.status = \"stopped\";\n taskSafe.completedAt = Date.now();\n taskSafe.lastUpdatedAt = taskSafe.completedAt;\n taskSafe.abortController?.abort();\n justMarkedStopped = true;\n } catch (err) {\n logger3.warn(`[BackgroundTaskManager] forceStopAllAcrossParents mark stopped failed for ${taskId}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n if (justMarkedStopped && taskSafe) {\n const stoppedPayload = {\n backgroundTaskId: taskSafe.id,\n subSessionId: taskSafe.subSessionId,\n parentSessionId: taskSafe.parentSessionId,\n status: \"stopped\",\n description: taskSafe.description,\n error: \"force stop all\",\n executionTimeMs: taskSafe.startedAt && taskSafe.completedAt ? taskSafe.completedAt - taskSafe.startedAt : 0,\n associatedTaskId: taskSafe.associatedTaskId\n };\n this.publishBackgroundEvent(BackgroundTaskEventTypes.STOPPED, stoppedPayload, taskSafe.parentSessionId, taskSafe.triggerEventId, taskSafe.replyChannel);\n }\n }\n }\n async forceStopAll() {\n return this.forceStopAllAcrossParents();\n }\n async dispose() {\n for (const [, timer] of this.progressTimers) {\n try {\n clearInterval(timer);\n } catch {}\n }\n this.progressTimers.clear();\n for (const [, controller] of this.abortControllers) {\n try {\n controller.abort();\n } catch {}\n }\n this.abortControllers.clear();\n for (const [, registry] of this.processRegistries) {\n try {\n await registry.killAll();\n } catch (err) {\n logger3.warn(`[BackgroundTaskManager] dispose registry.killAll failed`, {\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n this.processRegistries.clear();\n for (const taskId of this.workflowRunRegistries.keys()) {\n await this.propagateStopToWorkflowRuns(taskId, \"BackgroundTaskManager disposed\");\n }\n this.workflowRunRegistries.clear();\n this.tasks.clear();\n logger3.info(`[BackgroundTaskManager] Disposed`);\n }\n}\n__legacyDecorateClassTS([\n TracedAs(\"task.background.attachWorkflowRun\", {\n recordParams: true,\n recordResult: false,\n log: true\n })\n], BackgroundTaskManager.prototype, \"attachWorkflowRun\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.background.detachWorkflowRun\", {\n recordParams: true,\n recordResult: false,\n log: true\n })\n], BackgroundTaskManager.prototype, \"detachWorkflowRun\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.background.replaceWorkflowRun\", {\n recordParams: true,\n recordResult: false,\n log: true\n })\n], BackgroundTaskManager.prototype, \"replaceWorkflowRun\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.background.propagateStopToWorkflowRuns\", {\n recordParams: true,\n recordResult: true,\n log: true\n })\n], BackgroundTaskManager.prototype, \"propagateStopToWorkflowRuns\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.background.finalizeTask\", { recordParams: true, recordResult: false, log: true })\n], BackgroundTaskManager.prototype, \"finalizeTask\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.background.resolveEntryAgent\", { recordParams: true, recordResult: true })\n], BackgroundTaskManager.prototype, \"resolveEntryAgent\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.background.createTask\", { recordParams: false, recordResult: true, log: true })\n], BackgroundTaskManager.prototype, \"createTask\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.background.executeTask\", { recordParams: true, recordResult: true, log: true })\n], BackgroundTaskManager.prototype, \"executeTask\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.background.startProgressReporter\", { recordParams: false, recordResult: true, log: true })\n], BackgroundTaskManager.prototype, \"startProgressReporter\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.background.stopProgressReporter\", { recordParams: false, recordResult: true, log: true })\n], BackgroundTaskManager.prototype, \"stopProgressReporter\", null);\n__legacyDecorateClassTS([\n TracedAs(\"delegate.executeWithAbort\", { recordParams: true, recordResult: true, log: true })\n], BackgroundTaskManager.prototype, \"executeWithAbort\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.background.stopAllForParent\", {\n recordParams: true,\n recordResult: true,\n log: true\n })\n], BackgroundTaskManager.prototype, \"stopAllForParent\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.background.forceStopAllAcrossParents\", {\n recordParams: false,\n recordResult: true,\n log: true\n })\n], BackgroundTaskManager.prototype, \"forceStopAllAcrossParents\", null);\nfunction getAgentRegistry(taskComponent) {\n const agentComponent = taskComponent.env?.getComponent?.(\"agent\");\n return agentComponent?.getRegistry?.();\n}\nfunction createDelegateTool(taskComponent) {\n const env = taskComponent.env;\n const existingManager = taskComponent.backgroundTaskManager;\n const backgroundTaskManager = existingManager ?? new BackgroundTaskManager(env);\n const registry = getAgentRegistry(taskComponent);\n taskComponent._backgroundTaskManager = backgroundTaskManager;\n const tool = {\n name: \"delegate_task\",\n description: `Launch a new sub-agent to handle complex, multistep tasks autonomously.\n\nAvailable agent types:\n${listKnownSubagentDescriptions(registry)}\n\nWhen using the delegate_task tool, you must specify a subagent_type parameter to select which agent type to use.\n\n## When to use delegate_task:\n- When you need to perform complex, multi-step tasks that require independent execution\n- When you need to explore a codebase thoroughly (use \"explore\" subagent)\n- When you need to run long-running tasks without blocking the main agent\n\n## How it works:\nThis tool **always runs in background mode**. It returns immediately with:\n- **bgProcessId**: Internal background process ID (use with \\`stop_task\\` to cancel, different from Task #)\n- **subSessionId**: Sub-agent session ID (use with \\`session_get\\` to see full execution log, always retained)\n\n**After delegating, just WAIT for the notification.** The background process will automatically notify you when:\n- ✅ **completed** — with \\`bgprocess:\\` + \\`Task #\\` (if it created a task) + result summary\n- ⏱️ **timeout** — with \\`bgprocess:\\` + \\`Task #\\` (if available)\n- ❌ **failed** — with \\`bgprocess:\\` + \\`Task #\\` + error details\n- \\uD83D\\uDED1 **stopped** — with \\`bgprocess:\\` + \\`Task #\\`\n\nThe sub-agent runs independently and creates its own tasks via \\`task_create\\`.\nNo need to poll — just wait for the notification and use \\`task_get\\` with the Task # reported in it.\n\n## Parameters:\n- **description**: A short (3-5 words) description of the task\n- **prompt**: The task for the agent to perform\n- **subagent_type**: The type of specialized agent to use (e.g., \"general\", \"explore\")\n- **timeout**: Task timeout in milliseconds (optional, default 30 minutes)\n- **reason**: Brief reason for calling this tool (optional)\n- **similar_task_ids**: Similar task IDs (max 3) to reference for improving sub-agent execution efficiency. Search for similar tasks using \\`task_search\\` or \\`task_list\\` before calling this tool.`,\n parameters: DelegateToolParameters,\n execute: async (args, ctx) => {\n const startTime = Date.now();\n const params = DelegateToolParameters.parse(args);\n const { description, prompt, subagent_type = \"general\", timeout, reason, similar_task_ids } = params;\n const parentSessionId = ctx.session_id || \"default\";\n const resolvedTriggerEventId = params.triggerEventId ?? deriveTriggerEventIdFromEnvContext();\n if (resolvedTriggerEventId && resolvedTriggerEventId !== params.triggerEventId) {\n logger3.info(`[delegate_task] triggerEventId auto-derived from EnvContext: ${resolvedTriggerEventId}`);\n }\n logger3.info(`[delegate_task] Called: description=${description}, subagent_type=${subagent_type}, triggerEventId=${resolvedTriggerEventId ?? \"(none)\"}`);\n if (resolvedTriggerEventId) {\n const store = getSharedEventStore();\n if (store) {\n try {\n const persisted = await store.getEventById(resolvedTriggerEventId);\n if (!persisted) {\n return {\n success: false,\n output: \"\",\n error: `Unknown triggerEventId: ${resolvedTriggerEventId} (not found in EventStore)`,\n metadata: { execution_time_ms: Date.now() - startTime }\n };\n }\n } catch (err) {\n return {\n success: false,\n output: \"\",\n error: `Failed to verify triggerEventId ${resolvedTriggerEventId}: ${err instanceof Error ? err.message : String(err)}`,\n metadata: { execution_time_ms: Date.now() - startTime }\n };\n }\n } else {\n logger3.warn(`[delegate_task] triggerEventId=${resolvedTriggerEventId} supplied but no shared EventStore registered; skipping verification`);\n }\n }\n const registry2 = getAgentRegistry(taskComponent);\n if (!isKnownSubagentType(subagent_type, registry2)) {\n return {\n success: false,\n output: \"\",\n error: `Unknown subagent type: ${subagent_type}`,\n metadata: { execution_time_ms: Date.now() - startTime }\n };\n }\n const tagService = taskComponent.getTagService();\n let promptWithTaskInfo = prompt;\n const delegateCtx = {\n prompt: promptWithTaskInfo,\n subagentType: subagent_type,\n timeout,\n reason,\n tagService\n };\n const hookCtx = {\n component: { name: \"task\", version: \"1.0.0\" },\n data: delegateCtx,\n metadata: { sessionId: parentSessionId },\n phase: \"before\",\n hookPoint: TaskHookPoints.DELEGATE_BEFORE\n };\n await globalHookManager.execute(TaskHookPoints.DELEGATE_BEFORE, delegateCtx, { sessionId: parentSessionId });\n promptWithTaskInfo = delegateCtx.prompt;\n return await handleBackgroundTask(backgroundTaskManager, parentSessionId, description, promptWithTaskInfo, delegateCtx.subagentType, delegateCtx.timeout, similar_task_ids, params.sub_session_id, resolvedTriggerEventId);\n }\n };\n tool.execute = wrapFunction(tool.execute, \"delegate.execute\", {\n recordParams: true,\n recordResult: false,\n recordError: true\n });\n return tool;\n}\nfunction _deriveTriggerEventIdFromEnvContext() {\n const env = getEnvContext();\n if (!env)\n return;\n const envEvent = env.envEvent;\n const fromMeta = envEvent?.metadata?.triggerEventId;\n if (typeof fromMeta === \"string\" && fromMeta.length > 0)\n return fromMeta;\n const fromPayload = envEvent?.payload?.triggerEventId;\n if (typeof fromPayload === \"string\" && fromPayload.length > 0)\n return fromPayload;\n return;\n}\nvar deriveTriggerEventIdFromEnvContext = wrapFunction(_deriveTriggerEventIdFromEnvContext, \"delegate.deriveTriggerEventId\", { recordParams: false, recordResult: true, recordError: true });\nfunction _captureReplyChannelSnapshot() {\n const replyChannel = getEnvContext()?.replyChannel;\n if (!replyChannel)\n return;\n if (!replyChannel.chatId && !replyChannel.messageId)\n return;\n const params = { ...replyChannel.params ?? {} };\n if (replyChannel.userId && params.userId === undefined) {\n params.userId = replyChannel.userId;\n }\n return {\n type: replyChannel.type,\n appId: replyChannel.appId,\n chatId: replyChannel.chatId,\n messageId: replyChannel.messageId,\n profile: replyChannel.profile,\n params: Object.keys(params).length > 0 ? params : undefined\n };\n}\nvar captureReplyChannelSnapshot = wrapFunction(_captureReplyChannelSnapshot, \"delegate.captureReplyChannel\", { recordParams: false, recordResult: true, recordError: true });\nasync function handleBackgroundTask(backgroundTaskManager, parentSessionId, description, prompt, subagentType, timeout, similarTaskIds, existingSubSessionId, triggerEventId) {\n const startTime = Date.now();\n try {\n let actualSubagentType = subagentType;\n let actualPrompt = prompt;\n let originalWorkflowName;\n const entryAgent = backgroundTaskManager.resolveEntryAgent(subagentType);\n if (entryAgent) {\n originalWorkflowName = subagentType;\n actualSubagentType = entryAgent;\n actualPrompt = buildEntryAgentPrompt({\n workflowName: originalWorkflowName,\n originalPrompt: prompt,\n description\n });\n logger3.info(`[delegate_task] Routing workflow subagent '${subagentType}' → entry-agent '${entryAgent}'`);\n }\n const { taskId: bgProcessId, subSessionId } = await backgroundTaskManager.createTask({\n parentSessionId,\n description,\n prompt: actualPrompt,\n subagentType: actualSubagentType,\n timeout,\n similarTaskIds,\n originalWorkflowName,\n existingSubSessionId,\n triggerEventId\n });\n const output = [\n `✅ Background task accepted`,\n \"\",\n `\\uD83D\\uDCCB Process ID: ${bgProcessId}`,\n `\\uD83D\\uDCDD Description: ${description}`,\n `\\uD83E\\uDD16 Sub-agent: ${actualSubagentType}${originalWorkflowName ? ` (workflow: ${originalWorkflowName})` : \"\"}`,\n `⏱️ Timeout: ${(timeout || DEFAULT_TIMEOUT) / 1000}s`,\n \"\",\n `Use stop_task with task_id=\"${bgProcessId}\" to cancel this task.`\n ].join(`\n`);\n return {\n success: true,\n output,\n metadata: {\n execution_time_ms: Date.now() - startTime,\n sessionId: subSessionId,\n background: true,\n status: \"accepted\",\n bgProcessId\n }\n };\n } catch (error) {\n return {\n success: false,\n output: \"\",\n error: error instanceof Error ? error.message : String(error),\n metadata: { execution_time_ms: Date.now() - startTime }\n };\n }\n}\n// src/env/task/delegate/stop-tool.ts\nimport { z as z2 } from \"zod\";\nvar StopTaskToolParameters = z2.object({\n task_id: z2.string().describe(\"The ID of the background task to stop\")\n});\nvar STOP_TASK_DESCRIPTION = `Stop a running background task.\n\nUse this tool to stop a background task that is currently running. This is useful when:\n- The user wants to cancel a long-running task\n- The task is taking too long and needs to be stopped\n- The user wants to change direction and doesn't need the task result anymore\n\nWhen stopped, the task will be terminated immediately and you will receive a confirmation.\n\nParameters:\n- task_id: The ID of the background task to stop (obtained from the delegate_task response)`;\nfunction formatDuration(ms) {\n const seconds = Math.floor(ms / 1000);\n const minutes = Math.floor(seconds / 60);\n const hours = Math.floor(minutes / 60);\n if (hours > 0) {\n return `${hours}h ${minutes % 60}m ${seconds % 60}s`;\n } else if (minutes > 0) {\n return `${minutes}m ${seconds % 60}s`;\n } else {\n return `${seconds}s`;\n }\n}\nfunction createStopTool(taskManager) {\n return {\n name: \"stop_task\",\n description: STOP_TASK_DESCRIPTION,\n parameters: StopTaskToolParameters,\n execute: async (args, ctx) => {\n const startTime = Date.now();\n const params = StopTaskToolParameters.parse(args);\n const { task_id } = params;\n const result = await taskManager.stopTask(task_id);\n if (result.success) {\n const task = result.task;\n const elapsedMs = task.startedAt ? Date.now() - task.startedAt : Date.now() - task.createdAt;\n const output = [\n `✅ Task stopped successfully`,\n \"\",\n `\\uD83D\\uDCCB Task ID: ${task_id}`,\n `\\uD83D\\uDCDD Description: ${task.description}`,\n `\\uD83D\\uDD04 Status: ${task.status} → stopped`,\n `⏱️ Elapsed Time: ${formatDuration(elapsedMs)}`,\n \"\",\n result.message\n ].join(`\n`);\n return {\n success: true,\n output,\n metadata: {\n execution_time_ms: Date.now() - startTime,\n task_id,\n previous_status: task.status\n }\n };\n } else {\n const task = result.task;\n let output;\n if (task) {\n output = [\n `⚠️ Cannot stop task`,\n \"\",\n `\\uD83D\\uDCCB Task ID: ${task_id}`,\n `\\uD83D\\uDCDD Description: ${task.description}`,\n `\\uD83D\\uDD04 Current Status: ${task.status}`,\n \"\",\n result.message\n ].join(`\n`);\n } else {\n output = [\n `❌ Task not found`,\n \"\",\n `\\uD83D\\uDCCB Task ID: ${task_id}`,\n \"\",\n result.message\n ].join(`\n`);\n }\n return {\n success: false,\n output,\n error: result.message,\n metadata: {\n execution_time_ms: Date.now() - startTime,\n task_id\n }\n };\n }\n }\n };\n}\nexport { BackgroundTaskEventTypes, BackgroundTaskManager, createDelegateTool, createStopTool };\n",
|
|
107
|
+
"// src/config/env-key.ts\nfunction toEnvKey(key, prefix) {\n let keyNormalized = key.replace(/[.-]/g, \"_\");\n keyNormalized = keyNormalized.replace(/([a-z])([A-Z])/g, \"$1_$2\").replace(/_+/g, \"_\").toUpperCase();\n if (prefix) {\n const prefixCore = prefix.toUpperCase().replace(/^_+|_+$/g, \"\");\n const prefixCoreWithSep = `${prefixCore}_`;\n if (prefixCore && keyNormalized.startsWith(prefixCoreWithSep)) {\n return keyNormalized;\n }\n const separator = prefix.endsWith(\"_\") ? \"\" : \"_\";\n return `${prefix}${separator}${keyNormalized}`;\n }\n return keyNormalized;\n}\nfunction fromEnvKey(envKey, prefix) {\n if (!prefix) {\n return envKey;\n }\n if (envKey.startsWith(prefix)) {\n const afterPrefix = envKey.slice(prefix.length);\n if (afterPrefix.startsWith(\"_\")) {\n return afterPrefix.slice(1);\n }\n return afterPrefix;\n }\n return envKey;\n}\nfunction envKeyToConfigKey(envKey, prefix, componentName) {\n const prefixUpper = prefix.toUpperCase();\n if (!envKey.startsWith(prefixUpper)) {\n return;\n }\n const componentUpperNormalized = componentName.replace(/-/g, \"_\").toUpperCase();\n let keyPart = envKey.slice(prefixUpper.length);\n if (keyPart.startsWith(\"_\")) {\n keyPart = keyPart.slice(1);\n }\n if (!keyPart) {\n return;\n }\n const firstUnderscore = keyPart.indexOf(\"_\");\n let restPart;\n if (firstUnderscore === -1) {\n restPart = keyPart;\n } else {\n const firstPart = keyPart.slice(0, firstUnderscore);\n const remaining = keyPart.slice(firstUnderscore + 1);\n if (firstPart === componentUpperNormalized) {\n restPart = remaining;\n } else {\n restPart = keyPart;\n }\n }\n if (!restPart) {\n return;\n }\n const restPartConverted = restPart.replace(/_/g, \".\");\n return `${componentName}.${restPartConverted.toLowerCase()}`;\n}\n\nexport { toEnvKey, fromEnvKey, envKeyToConfigKey };\n",
|
|
108
|
+
"import {\n init_global_hook_manager,\n init_hook_manager\n} from \"./roy-agent-core-4z3rq5gw.js\";\nimport {\n __esm\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/hook/types.ts\nfunction createHook(meta, fn) {\n return {\n ...meta,\n execute: fn\n };\n}\nfunction createPriorityHook(name, fn, priority) {\n return createHook({ name, priority }, fn);\n}\nvar init_types = () => {};\n\n// src/env/hook/index.ts\nvar init_hook = __esm(() => {\n init_types();\n init_hook_manager();\n init_global_hook_manager();\n});\n\nexport { createHook, createPriorityHook, init_hook };\n",
|
|
109
|
+
"import {\n createHook,\n init_hook\n} from \"./roy-agent-core-qcspfszy.js\";\nimport {\n HookManager\n} from \"./roy-agent-core-4z3rq5gw.js\";\n\n// src/env/component.ts\ninit_hook();\nclass BaseComponent {\n _status = \"created\";\n _enabled = true;\n env;\n hookManager;\n constructor() {\n this.hookManager = new HookManager;\n }\n getStatus() {\n return this._status;\n }\n getConfig() {\n return {\n name: this.name,\n version: this.version,\n enabled: this._enabled,\n env: this.env\n };\n }\n isEnvInitialized() {\n return this._status !== \"created\";\n }\n setStatus(status) {\n this._status = status;\n }\n getEnv() {\n return this.env;\n }\n async init(config) {\n if (config?.env) {\n this.env = config.env;\n }\n this.setStatus(\"initializing\");\n try {\n if (config?.name)\n Object.defineProperty(this, \"name\", { value: config.name, writable: false });\n if (config?.version)\n Object.defineProperty(this, \"version\", { value: config.version, writable: false });\n } catch {}\n if (config?.enabled !== undefined)\n this._enabled = config.enabled;\n this.hookManager.setComponentInfo(this.name, this.version);\n await this.onInit();\n this.setStatus(\"running\");\n }\n async start() {\n if (this._started)\n return;\n this._started = true;\n await this.onStart();\n this.setStatus(\"running\");\n }\n async stop() {\n this.setStatus(\"stopping\");\n this.hookManager.clear();\n await this.onStop();\n this.setStatus(\"stopped\");\n }\n async onInit() {}\n async onStart() {}\n async onStop() {}\n registerHook(hookPoint, hook) {\n this.hookManager.register(hookPoint, hook);\n }\n addHook(hookPoint, name, fn, priority) {\n this.hookManager.register(hookPoint, createHook({ name, priority }, fn));\n }\n removeHook(hookPoint, name) {\n return this.hookManager.unregister(hookPoint, name);\n }\n async executeHooks(hookPoint, data, metadata) {\n await this.hookManager.execute(hookPoint, data, metadata);\n }\n getConfigComponent() {\n return this.env?.getComponent(\"config\");\n }\n getRuntimeConfig(key, defaultValue) {\n const configComponent = this.getConfigComponent();\n if (configComponent) {\n const value = configComponent.get(key);\n if (value !== undefined) {\n return value;\n }\n }\n return defaultValue;\n }\n}\n\nexport { BaseComponent };\n",
|
|
110
|
+
"import {\n createQueryBackgroundProcessTool\n} from \"./roy-agent-core-amkqnyzy.js\";\nimport {\n SQLiteTaskStore,\n getDefaultTaskDbPath\n} from \"./roy-agent-core-qm9jda8p.js\";\nimport {\n batchArchiveTaskTool,\n batchDeleteTaskTool,\n completeTaskTool,\n createTaskTool,\n deleteTaskTool,\n getTaskTool,\n listTasksTool,\n searchTasksTool,\n treeTasksTool,\n updateTaskTool\n} from \"./roy-agent-core-7g03zkkb.js\";\nimport {\n createOperationTool,\n deleteOperationTool,\n getOperationTool,\n listOperationsTool,\n updateOperationTool\n} from \"./roy-agent-core-rn57psp0.js\";\nimport {\n TaskEntityEventTypes\n} from \"./roy-agent-core-8gxth0eh.js\";\nimport {\n BackgroundTaskManager,\n createDelegateTool,\n createStopTool\n} from \"./roy-agent-core-p2r27era.js\";\nimport {\n TaskHookPoints\n} from \"./roy-agent-core-1pg0fepg.js\";\nimport {\n envKeyToConfigKey\n} from \"./roy-agent-core-7hh0brvs.js\";\nimport {\n BaseComponent\n} from \"./roy-agent-core-tdbv7ff4.js\";\nimport {\n globalHookManager,\n init_global_hook_manager\n} from \"./roy-agent-core-4z3rq5gw.js\";\nimport {\n getEnvContextOrEmpty,\n init_env_context\n} from \"./roy-agent-core-5apmk4qw.js\";\nimport {\n TracedAs,\n init_decorator\n} from \"./roy-agent-core-dsevjbck.js\";\nimport {\n createLogger,\n init_logger\n} from \"./roy-agent-core-8seq65bp.js\";\nimport {\n __legacyDecorateClassTS\n} from \"./roy-agent-core-fs0mn2jk.js\";\n\n// src/env/task/task-component.ts\ninit_logger();\n\n// src/env/task/task-config-registration.ts\nvar TASK_DEFAULTS = {\n \"task.storage.type\": \"sqlite\",\n \"task.storage.dbPath\": undefined\n};\nvar TASK_CONFIG_REGISTRATION = {\n name: \"task\",\n sources: [\n { type: \"env\", envPrefix: \"TASK\", priority: 20, watch: false }\n ],\n keys: [\n { key: \"task.storage.type\", sources: [\"env\", \"file\"] },\n { key: \"task.storage.dbPath\", sources: [\"env\", \"file\"] }\n ]\n};\n\n// src/env/task/task-component.ts\ninit_global_hook_manager();\n\n// src/env/task/hooks/contexts.ts\nvar TASK_COMPLETE_TERMINAL_STATUSES = [\n \"completed\",\n \"failed\",\n \"cancelled\",\n \"timeout\"\n];\n\n// src/env/task/task-component.ts\ninit_env_context();\n\n// src/env/task/tag-service.ts\ninit_logger();\nvar logger = createLogger(\"task:tag\");\n\nclass DefaultTagService {\n store;\n constructor(store) {\n this.store = store;\n }\n async createTag(name) {\n const tag = await this.store.createTag(name);\n logger.debug(`[TagService] Created tag: ${tag.name} (id=${tag.id})`);\n return tag;\n }\n async getTag(id) {\n return this.store.getTag(id);\n }\n async getTagByName(name) {\n return this.store.getTagByName(name);\n }\n async listTags(options) {\n return this.store.listTags(options);\n }\n async searchTags(options) {\n return this.store.searchTags(options);\n }\n async deleteTag(id) {\n const result = await this.store.deleteTag(id);\n if (result) {\n logger.debug(`[TagService] Deleted tag id=${id}`);\n }\n return result;\n }\n async addTagsToTask(taskId, tagIds) {\n await this.store.addTagsToTask(taskId, tagIds);\n logger.debug(`[TagService] Added ${tagIds.length} tags to task ${taskId}`);\n }\n async removeTagsFromTask(taskId, tagIds) {\n await this.store.removeTagsFromTask(taskId, tagIds);\n logger.debug(`[TagService] Removed ${tagIds.length} tags from task ${taskId}`);\n }\n async getTagsForTask(taskId) {\n return this.store.getTagsForTask(taskId);\n }\n async getTaskIdsByTags(tagNames) {\n return this.store.getTaskIdsByTags(tagNames);\n }\n async findSimilarTasks(taskId, limit = 5) {\n return this.store.findSimilarTasks(taskId, limit);\n }\n async searchTasks(query, limit = 20) {\n return this.store.searchTasks(query, limit);\n }\n async searchTasksByKeywords(keywords, options) {\n const result = await this.store.searchTasksByKeywords(keywords, options);\n return result.tasks;\n }\n async findSimilarTasksByKeywords(keywords, options) {\n return this.store.findSimilarTasksByKeywords(keywords, options);\n }\n async syncTagsToTask(taskId, tagNames) {\n const tagIds = [];\n for (const name of tagNames) {\n let tag = await this.store.getTagByName(name);\n if (!tag) {\n tag = await this.store.createTag(name);\n }\n tagIds.push(tag.id);\n }\n const currentTags = await this.store.getTagsForTask(taskId);\n const currentTagIds = new Set(currentTags.map((t) => t.id));\n const newTagIds = new Set(tagIds);\n const toAdd = tagIds.filter((id) => !currentTagIds.has(id));\n const toRemove = currentTags.filter((t) => !newTagIds.has(t.id)).map((t) => t.id);\n if (toRemove.length > 0) {\n await this.store.removeTagsFromTask(taskId, toRemove);\n }\n if (toAdd.length > 0) {\n await this.store.addTagsToTask(taskId, toAdd);\n }\n await this.store.updateTaskTags(taskId, tagNames);\n logger.info(`[TagService] Synced tags for task ${taskId}: ${tagNames.join(\", \")}`);\n }\n}\n\n// src/env/task/task-component.ts\ninit_decorator();\nvar logger2 = createLogger(\"task\");\nvar DELIVERABLE_OPERATION_PREFIX = \"Deliverable: \";\nfunction formatDeliverableForOperation(deliverableStoragePath) {\n if (!deliverableStoragePath)\n return;\n return `${DELIVERABLE_OPERATION_PREFIX}${deliverableStoragePath}`;\n}\n\nclass TaskComponent extends BaseComponent {\n name = \"task\";\n version = \"1.0.0\";\n store;\n config;\n toolComponent;\n backgroundTaskManager;\n configComponent;\n tagService;\n plugins = new Map;\n getBackgroundTaskManager() {\n return this.backgroundTaskManager;\n }\n publishEvent(type, payload, sessionId) {\n if (this.env?.pushEnvEvent) {\n this.env.pushEnvEvent({\n type,\n payload,\n metadata: {\n source: \"task.component\",\n trigger_session_id: sessionId\n }\n });\n logger2.info(`[TaskComponent] Event published: ${type}`);\n }\n }\n constructor() {\n super();\n }\n async init(config) {\n await super.init(config);\n const options = config?.options;\n if (!options?.configComponent) {\n throw new Error(\"ConfigComponent is required for TaskComponent initialization\");\n }\n this.configComponent = options.configComponent;\n await this.registerConfig(options);\n this.setStatus(\"running\");\n logger2.info(\"[TaskComponent] Initialized\");\n }\n async registerConfig(options) {\n const configComponent = this.configComponent;\n if (!configComponent)\n return;\n const { configPath, envPrefix, config } = options;\n const prefix = envPrefix ?? \"TASK\";\n configComponent.registerComponent(TASK_CONFIG_REGISTRATION);\n if (configPath) {\n configComponent.registerSource({\n type: \"file\",\n relativePath: configPath,\n optional: true,\n watch: false\n });\n }\n configComponent.registerSource({\n type: \"env\",\n envPrefix: prefix,\n priority: 20,\n watch: false\n });\n await configComponent.load(\"task\");\n for (const envKey of Object.keys(process.env)) {\n const configKey = envKeyToConfigKey(envKey, prefix, \"task\");\n if (!configKey)\n continue;\n const value = process.env[envKey];\n if (value !== undefined) {\n await configComponent.set(configKey, value);\n }\n }\n for (const [key, value] of Object.entries(TASK_DEFAULTS)) {\n if (configComponent.get(key) === undefined) {\n await configComponent.set(key, value);\n }\n }\n if (configComponent.get(\"task.storage.dbPath\") === undefined) {\n await configComponent.set(\"task.storage.dbPath\", getDefaultTaskDbPath());\n }\n if (config) {\n const flatConfig = this.flattenConfig(config);\n for (const [key, value] of Object.entries(flatConfig)) {\n await configComponent.set(key, value);\n }\n }\n this.registerConfigWatcher(configComponent);\n await this.initStore();\n this.tagService = new DefaultTagService(this.store);\n }\n async initStore() {\n const configComponent = this.configComponent;\n if (!configComponent)\n return;\n const storageType = configComponent.get(\"task.storage.type\") ?? \"sqlite\";\n const dbPath = configComponent.get(\"task.storage.dbPath\");\n if (storageType === \"sqlite\") {\n this.store = new SQLiteTaskStore(dbPath);\n logger2.info(`[TaskComponent] Using SQLite storage: ${dbPath || \"default path\"}`);\n } else {\n this.store = new SQLiteTaskStore;\n logger2.info(\"[TaskComponent] Using SQLite storage (default)\");\n }\n }\n flattenConfig(obj, prefix = \"task\") {\n const result = {};\n for (const [key, value] of Object.entries(obj)) {\n const fullKey = `${prefix}.${key}`;\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n Object.assign(result, this.flattenConfig(value, fullKey));\n } else {\n result[fullKey] = value;\n }\n }\n return result;\n }\n registerConfigWatcher(configComponent) {\n if (typeof configComponent.watch !== \"function\") {\n return;\n }\n this.configWatcher = configComponent.watch(\"task.*\", (event) => {\n this.onConfigChange(event);\n });\n }\n onConfigChange(event) {\n logger2.info(`[TaskComponent] Config changed: ${event.key}`, {\n oldValue: event.oldValue,\n newValue: event.newValue\n });\n if (event.key === \"task.storage.type\" || event.key === \"task.storage.dbPath\") {\n this.initStore();\n }\n }\n configWatcher;\n async start() {\n await super.start();\n this.backgroundTaskManager = new BackgroundTaskManager(this.env);\n this.toolComponent = this.env?.getComponent(\"tool\");\n if (this.toolComponent) {\n await this.registerTools();\n this.toolComponent.register(createQueryBackgroundProcessTool(this.backgroundTaskManager), \"built-in\");\n logger2.debug(\"[TaskComponent] Injected BackgroundTaskManager into query_background_process tool (factory pattern)\");\n } else {\n logger2.warn(\"[TaskComponent] ToolComponent not found, skipping tool registration\");\n }\n }\n async stop() {\n if (this.configWatcher) {\n this.configWatcher();\n this.configWatcher = undefined;\n }\n if (this.toolComponent) {\n try {\n this.toolComponent.register(createQueryBackgroundProcessTool(null), \"built-in\");\n logger2.debug(\"[TaskComponent] Reset query_background_process tool to no-manager default (cleanup)\");\n } catch (err) {\n logger2.warn(`[TaskComponent] Failed to reset query_background_process tool: ${err.message}`);\n }\n }\n if (this.backgroundTaskManager) {\n this.backgroundTaskManager.dispose();\n this.backgroundTaskManager = undefined;\n }\n if (this.store) {\n await this.store.close();\n }\n await super.stop();\n }\n async registerTools() {\n if (!this.toolComponent)\n return;\n const taskToolsList = [\n createTaskTool(this),\n getTaskTool(this),\n listTasksTool(this),\n treeTasksTool(this),\n searchTasksTool(this),\n batchArchiveTaskTool(this),\n batchDeleteTaskTool(this),\n updateTaskTool(this),\n deleteTaskTool(this),\n completeTaskTool(this)\n ];\n const operationToolsList = [\n createOperationTool(this),\n getOperationTool(this),\n listOperationsTool(this),\n updateOperationTool(this),\n deleteOperationTool(this)\n ];\n const delegateTools = [\n createDelegateTool(this),\n createStopTool(this.backgroundTaskManager)\n ];\n for (const tool of [...taskToolsList, ...operationToolsList, ...delegateTools]) {\n this.toolComponent.register(tool);\n logger2.info(`[TaskComponent] Registered tool: ${tool.name}`);\n }\n }\n async executeHook(hookPoint, data, metadata = {}) {\n const ctx = {\n component: { name: this.name, version: this.version },\n data,\n metadata,\n phase: hookPoint.includes(\"before\") ? \"before\" : \"after\",\n hookPoint\n };\n await globalHookManager.execute(hookPoint, data, metadata);\n }\n async createTask(options) {\n const sessionId = options.sessionId;\n if (options.parent_task_id !== undefined && options.parent_task_id !== null) {\n const parentTask = await this.store.getTask(options.parent_task_id);\n if (!parentTask) {\n throw new Error(`Parent task #${options.parent_task_id} not found. ` + \"Please provide a valid parent_task_id. Use task_list(depth=0) to see all root tasks.\");\n }\n }\n const createCtx = {\n options: { ...options },\n sessionId,\n tagService: this.tagService\n };\n await this.executeHook(TaskHookPoints.BEFORE_CREATE, createCtx);\n const task = await this.store.createTask(createCtx.options);\n await this.store.createOperation({\n taskId: task.id,\n sessionId,\n milestoneType: \"create\",\n milestoneTitle: `Task created: ${task.title}`,\n milestoneDescription: task.description || \"\"\n });\n const resultCtx = {\n task,\n sessionId,\n tagService: this.tagService\n };\n await this.executeHook(TaskHookPoints.AFTER_CREATE, resultCtx);\n this.publishEvent(TaskEntityEventTypes.CREATED, { task, sessionId }, sessionId);\n logger2.info(`[TaskComponent] Task created: ${task.id} - ${task.title}`);\n return task;\n }\n async getTask(id) {\n return this.store.getTask(id);\n }\n async getTaskIdBySessionId(sessionId) {\n return this.store.getTaskIdBySessionId(sessionId);\n }\n async getTaskWithOperations(id) {\n const task = await this.store.getTask(id);\n if (!task)\n return;\n const operations = await this.store.listOperations({ taskId: id });\n return { task, operations };\n }\n async updateTask(id, options) {\n const updateCtx = {\n id,\n options: { ...options },\n tagService: this.tagService\n };\n await this.executeHook(TaskHookPoints.BEFORE_UPDATE, updateCtx);\n const task = await this.store.updateTask(id, updateCtx.options);\n if (task) {\n const resultCtx = {\n task,\n changes: options,\n tagService: this.tagService\n };\n await this.executeHook(TaskHookPoints.AFTER_UPDATE, resultCtx);\n this.publishEvent(TaskEntityEventTypes.UPDATED, { task, changes: options, sessionId: \"\" }, \"\");\n logger2.info(`[TaskComponent] Task updated: ${id}`);\n if (options.status && TASK_COMPLETE_TERMINAL_STATUSES.includes(options.status)) {\n const env = getEnvContextOrEmpty();\n const completeCtx = {\n task,\n changes: options,\n terminalStatus: options.status,\n sessionId: env.sessionId ?? \"\",\n tagService: this.tagService\n };\n await this.executeHook(TaskHookPoints.AFTER_COMPLETE, completeCtx);\n logger2.info(`[TaskComponent] Task completed (AFTER_COMPLETE fired): ${id} -> ${options.status}`);\n }\n }\n return task;\n }\n async deleteTask(id) {\n const deleteCtx = { id };\n await this.executeHook(TaskHookPoints.BEFORE_DELETE, deleteCtx);\n const result = await this.store.deleteTask(id);\n const resultCtx = { id, deleted: result };\n await this.executeHook(TaskHookPoints.AFTER_DELETE, resultCtx);\n if (result) {\n this.publishEvent(TaskEntityEventTypes.DELETED, { taskId: id, sessionId: \"\" }, \"\");\n logger2.info(`[TaskComponent] Task deleted: ${id}`);\n }\n return result;\n }\n async listTasks(options) {\n return this.store.listTasks(options);\n }\n async searchTasksByKeywords(keywords, options) {\n return this.store.searchTasksByKeywords(keywords, options || {});\n }\n async getTaskTree(taskId, depth = -1) {\n return this.store.getTaskTree(taskId, depth);\n }\n async getChildTasks(taskId, options) {\n return this.store.getChildTasks(taskId, options);\n }\n async completeTask(id, sessionId, deliverableStoragePath) {\n const existing = await this.store.getTask(id);\n if (existing && existing.type === \"cycle\") {\n throw new Error(`Cannot complete cycle task: #${id} - ${existing.title}. Cycle tasks are not meant to be completed.`);\n }\n const updateOptions = {\n status: \"completed\",\n progress: 100\n };\n if (deliverableStoragePath) {\n let existingContext = {};\n if (existing?.context) {\n try {\n const parsed = JSON.parse(existing.context);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n existingContext = parsed;\n }\n } catch {\n logger2.warn(`[TaskComponent] Task #${id} context is not valid JSON, ignoring when merging deliverable`);\n }\n }\n existingContext.deliverable_storage_path = deliverableStoragePath;\n updateOptions.context = JSON.stringify(existingContext);\n }\n const task = await this.updateTask(id, updateOptions);\n if (task) {\n await this.createOperation({\n taskId: id,\n sessionId,\n milestoneType: \"completed\",\n milestoneTitle: \"Task completed\",\n milestoneDescription: formatDeliverableForOperation(deliverableStoragePath)\n });\n this.publishEvent(TaskEntityEventTypes.COMPLETED, { task, sessionId }, sessionId);\n logger2.info(`[TaskComponent] Task completed: ${id}, deliverable=${deliverableStoragePath || \"(none)\"}`);\n }\n return task;\n }\n async createOperation(options) {\n const createCtx = {\n options: { ...options }\n };\n await this.executeHook(TaskHookPoints.OPERATION_BEFORE_CREATE, createCtx);\n const op = await this.store.createOperation(createCtx.options);\n const task = await this.store.getTask(op.taskId);\n const resultCtx = { operation: op };\n await this.executeHook(TaskHookPoints.OPERATION_AFTER_CREATE, resultCtx, { task, operation: op });\n this.publishEvent(TaskEntityEventTypes.OPERATION_ADDED, { operation: op, taskId: op.taskId }, op.sessionId);\n logger2.info(`[TaskComponent] Operation created: ${op.id} for task ${op.taskId}`);\n return op;\n }\n async getOperation(id) {\n return this.store.getOperation(id);\n }\n async updateOperation(id, updates) {\n return this.store.updateOperation(id, updates);\n }\n async deleteOperation(id) {\n return this.store.deleteOperation(id);\n }\n async listOperations(options) {\n return this.store.listOperations(options);\n }\n getTagService() {\n return this.tagService;\n }\n registerHook(hookPoint, hook) {\n globalHookManager.register(hookPoint, hook);\n this.plugins.set(this.makePluginKey(hookPoint, hook.name), hook);\n logger2.debug(`[TaskComponent] Registered hook: ${hook.name} at ${hookPoint}`);\n }\n registerHooks(hooks) {\n for (const { hookPoint, hook } of hooks) {\n this.registerHook(hookPoint, hook);\n }\n }\n unregisterHook(hookPoint, hookName) {\n const removed = globalHookManager.unregister(hookPoint, hookName);\n if (removed) {\n this.plugins.delete(this.makePluginKey(hookPoint, hookName));\n logger2.info(`[TaskComponent] Unregistered hook: ${hookName} from ${hookPoint}`);\n }\n return removed;\n }\n listHooks() {\n return Array.from(this.plugins.values());\n }\n makePluginKey(hookPoint, hookName) {\n return `${hookPoint}::${hookName}`;\n }\n countHooks(hookPoint) {\n return globalHookManager.count(hookPoint);\n }\n}\n__legacyDecorateClassTS([\n TracedAs(\"task.component.executeHook\", { recordParams: true })\n], TaskComponent.prototype, \"executeHook\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.component.createTask\", { recordParams: true, recordResult: true, log: true })\n], TaskComponent.prototype, \"createTask\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.component.updateTask\", { recordParams: true, recordResult: true, log: true })\n], TaskComponent.prototype, \"updateTask\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.component.completeTask\", { recordParams: true, recordResult: true, log: true })\n], TaskComponent.prototype, \"completeTask\", null);\n__legacyDecorateClassTS([\n TracedAs(\"task.component.createOperation\", { recordParams: true, recordResult: true, log: true })\n], TaskComponent.prototype, \"createOperation\", null);\n// src/env/task/types.ts\nimport { z } from \"zod\";\nvar TaskStatusEnum = z.enum([\"todo\", \"active\", \"completed\", \"paused\", \"cancelled\", \"archived\"]);\nvar TaskPriorityEnum = z.enum([\"low\", \"medium\", \"high\"]);\nvar TaskTypeEnum = z.enum([\"normal\", \"cycle\", \"longterm\"]);\nvar ActionTypeEnum = z.enum([\n \"create\",\n \"progress\",\n \"milestone\",\n \"problem\",\n \"solution\",\n \"decision\",\n \"review\",\n \"completed\",\n \"workflow_extracted\"\n]);\nvar TaskConfigSchema = z.object({\n storage: z.object({\n type: z.enum([\"memory\", \"sqlite\"]).default(\"sqlite\"),\n dbPath: z.string().optional()\n }).default({})\n}).default({});\nexport { TaskComponent, TaskStatusEnum, TaskPriorityEnum, TaskTypeEnum, ActionTypeEnum, TaskConfigSchema };\n",
|
|
111
|
+
"import\"../../../shared/@ai-setting/roy-agent-core-fs0mn2jk.js\";\n// src/env/task/backend/task-store-backend.ts\nvar DELIVERABLE_OPERATION_PREFIX = \"Deliverable: \";\nfunction formatDeliverableForOperation(deliverableStoragePath) {\n if (!deliverableStoragePath)\n return;\n return `${DELIVERABLE_OPERATION_PREFIX}${deliverableStoragePath}`;\n}\nvar SCAN_ALL = 1e6;\n\nclass TaskStoreBackend {\n port;\n options;\n constructor(port, options = {}) {\n this.port = port;\n this.options = options;\n }\n get defaultSessionId() {\n return this.options.sessionId ?? \"unknown\";\n }\n async resolve(id) {\n const asNum = toNumericHandle(id);\n if (asNum !== undefined) {\n if (typeof this.port.getTaskByNum === \"function\") {\n return await this.port.getTaskByNum(asNum);\n }\n return (await this.scanAllTasks()).find((t) => t.id === asNum) ?? null;\n }\n return await this.port.getTask(String(id));\n }\n toTask(record) {\n const { nativeId: _nativeId, ...task } = record;\n return task;\n }\n toOperation(record) {\n const { nativeId: _nativeId, ...operation } = record;\n return operation;\n }\n async scanAllTasks() {\n const res = await this.port.listTasks({\n limit: SCAN_ALL,\n offset: 0,\n includeArchived: true\n });\n return res.tasks;\n }\n async createTask(input) {\n const sessionId = input.sessionId ?? this.defaultSessionId;\n let parentNum;\n if (input.parent_task_id !== undefined && input.parent_task_id !== null) {\n const parent = await this.resolve(input.parent_task_id);\n if (!parent) {\n throw new Error(`Parent task #${input.parent_task_id} not found.`);\n }\n parentNum = parent.id;\n }\n const created = await this.port.createTask({\n title: input.title,\n description: input.description,\n priority: input.priority,\n type: input.type,\n goals_and_expected_deliverables: input.goals_and_expected_deliverables,\n ...parentNum !== undefined ? { parent_task_id: parentNum } : {},\n due_date: input.due_date,\n tags: input.tags,\n project_path: input.project_path,\n context: input.context,\n sessionId\n });\n await this.createOperation({\n taskId: created.id,\n sessionId,\n milestoneType: \"create\",\n milestoneTitle: `Task created: ${created.title}`,\n milestoneDescription: created.description ?? \"\"\n });\n return this.toTask(created);\n }\n async getTask(id) {\n const record = await this.resolve(id);\n return record ? this.toTask(record) : null;\n }\n async getTaskWithOperations(id) {\n const task = await this.getTask(id);\n if (!task)\n return null;\n const operations = await this.listOperations({ taskId: task.id, limit: SCAN_ALL, offset: 0 });\n return { ...task, operations };\n }\n async listTasks(options = {}) {\n const limit = options.limit ?? 20;\n const offset = options.offset ?? 0;\n let views = (await this.scanAllTasks()).map((t) => this.toTask(t));\n views = this.applyFilters(views, options);\n return { tasks: views.slice(offset, offset + limit), total: views.length };\n }\n async updateTask(id, input) {\n const record = await this.resolve(id);\n if (!record)\n return null;\n let parentNum;\n if (input.parent_task_id !== undefined) {\n if (input.parent_task_id === null) {\n parentNum = null;\n } else {\n const parent = await this.resolve(input.parent_task_id);\n if (!parent)\n throw new Error(`Parent task #${input.parent_task_id} not found.`);\n parentNum = parent.id;\n }\n }\n const updated = await this.port.updateTask(record.nativeId, {\n title: input.title,\n description: input.description,\n status: input.status,\n priority: input.priority,\n type: input.type,\n progress: input.progress,\n current_status: input.current_status,\n goals_and_expected_deliverables: input.goals_and_expected_deliverables,\n due_date: input.due_date,\n tags: input.tags,\n project_path: input.project_path,\n context: input.context,\n ...parentNum !== undefined ? { parent_task_id: parentNum } : {}\n });\n return updated ? this.toTask(updated) : null;\n }\n async deleteTask(id) {\n const record = await this.resolve(id);\n if (!record)\n return false;\n return await this.port.deleteTask(record.nativeId);\n }\n async completeTask(id, sessionId, deliverable) {\n const record = await this.resolve(id);\n if (!record)\n return null;\n if (record.type === \"cycle\") {\n throw new Error(`Cannot complete cycle task: #${record.id} - ${record.title}. Cycle tasks are not meant to be completed.`);\n }\n const patch = { status: \"completed\", progress: 100 };\n if (deliverable) {\n patch.context = mergeDeliverableIntoContext(record.context, deliverable);\n }\n const updated = await this.port.updateTask(record.nativeId, patch);\n if (!updated)\n return null;\n const formatted = formatDeliverableForOperation(deliverable);\n await this.createOperation({\n taskId: updated.id,\n sessionId: sessionId ?? this.defaultSessionId,\n milestoneType: \"completed\",\n milestoneTitle: `Completed: ${updated.title}`,\n milestoneDescription: formatted ?? \"Task completed\",\n ...deliverable ? { mdPath: deliverable } : {}\n });\n const reread = await this.resolve(record.nativeId);\n return this.toTask(reread ?? updated);\n }\n async getTaskTree(id, depth = -1) {\n const root = await this.resolve(id);\n if (!root)\n return [];\n if (depth === 0)\n return [];\n const views = (await this.scanAllTasks()).map((t) => this.toTask(t));\n const byParent = new Map;\n for (const t of views) {\n if (t.parent_task_id === undefined)\n continue;\n const bucket = byParent.get(t.parent_task_id) ?? [];\n bucket.push(t);\n byParent.set(t.parent_task_id, bucket);\n }\n const collected = [];\n const seen = new Set([root.id]);\n let frontier = [root.id];\n let level = 0;\n while (frontier.length > 0) {\n if (depth !== -1 && level >= depth)\n break;\n const next = [];\n for (const parentId of frontier) {\n for (const child of byParent.get(parentId) ?? []) {\n if (seen.has(child.id))\n continue;\n seen.add(child.id);\n collected.push(child);\n next.push(child.id);\n }\n }\n frontier = next;\n level++;\n }\n return collected;\n }\n async searchTasksByKeywords(keywords, options = {}) {\n const limit = options.limit ?? 20;\n const offset = options.offset ?? 0;\n let candidates = (await this.scanAllTasks()).map((t) => this.toTask(t));\n candidates = this.applyFilters(candidates, options);\n if (options.excludeTaskId !== undefined) {\n candidates = candidates.filter((t) => t.id !== options.excludeTaskId);\n }\n const needles = keywords.map((k) => k.toLowerCase()).filter((k) => k.length > 0);\n const hits = needles.length === 0 ? candidates : candidates.filter((t) => {\n const haystack = [\n t.title,\n t.description,\n t.goals_and_expected_deliverables,\n t.current_status,\n (t.tags ?? []).join(\" \"),\n t.project_path\n ].join(\" \").toLowerCase();\n return needles.every((n) => haystack.includes(n));\n });\n return { tasks: hits.slice(offset, offset + limit), total: hits.length };\n }\n async createOperation(input) {\n const task = await this.resolve(input.taskId);\n if (!task)\n throw new Error(`Task not found: ${input.taskId}`);\n const milestoneType = input.milestoneType ?? input.actionType ?? \"progress\";\n const milestoneTitle = input.milestoneTitle ?? input.actionTitle ?? \"\";\n const milestoneDescription = input.milestoneDescription ?? input.actionDescription ?? \"\";\n const created = await this.port.createOperation({\n taskId: task.id,\n taskNativeId: task.nativeId,\n sessionId: input.sessionId ?? this.defaultSessionId,\n milestoneType,\n milestoneTitle,\n milestoneDescription,\n processDescription: input.processDescription ?? \"\",\n ...input.mdPath ? { mdPath: input.mdPath } : {}\n });\n return this.toOperation(created);\n }\n async listOperations(options = {}) {\n const limit = options.limit ?? 100;\n const offset = options.offset ?? 0;\n const filterType = options.milestoneType ?? options.actionType;\n if (options.taskId === undefined) {\n return [];\n }\n const task = await this.resolve(options.taskId);\n if (!task)\n return [];\n const res = await this.port.listOperations({\n taskNativeId: task.nativeId,\n limit: filterType ? SCAN_ALL : limit,\n offset: filterType ? 0 : offset\n });\n let operations = res.operations.map((o) => this.toOperation(o));\n if (filterType) {\n operations = operations.filter((o) => o.milestoneType === filterType);\n operations = operations.slice(offset, offset + limit);\n }\n return operations;\n }\n async getOperation(id) {\n if (typeof this.port.getOperationByNum === \"function\") {\n const op = await this.port.getOperationByNum(id);\n return op ? this.toOperation(op) : null;\n }\n const tasks = await this.scanAllTasks();\n for (const task of tasks) {\n const res = await this.port.listOperations({ taskNativeId: task.nativeId, limit: SCAN_ALL });\n const found = res.operations.find((o) => o.id === id);\n if (found)\n return this.toOperation(found);\n }\n return null;\n }\n async updateOperation(id, patch) {\n const existing = await this.getOperation(id);\n if (!existing)\n return null;\n if (typeof this.port.updateOperationByNum !== \"function\")\n return existing;\n const updated = await this.port.updateOperationByNum(id, {\n sessionId: patch.sessionId ?? existing.sessionId,\n milestoneType: patch.milestoneType ?? patch.actionType ?? existing.milestoneType,\n milestoneTitle: patch.milestoneTitle ?? patch.actionTitle ?? existing.milestoneTitle,\n milestoneDescription: patch.milestoneDescription ?? patch.actionDescription ?? existing.milestoneDescription,\n processDescription: patch.processDescription ?? existing.processDescription,\n ...patch.mdPath !== undefined ? { mdPath: patch.mdPath } : {}\n });\n return updated ? this.toOperation(updated) : null;\n }\n async deleteOperation(id) {\n if (typeof this.port.deleteOperationByNum !== \"function\")\n return false;\n return await this.port.deleteOperationByNum(id);\n }\n applyFilters(views, options) {\n let out = views;\n const excludeArchived = options.include_archived !== true && options.status !== \"archived\";\n if (excludeArchived)\n out = out.filter((t) => t.status !== \"archived\");\n if (options.status !== undefined)\n out = out.filter((t) => t.status === options.status);\n if (options.priority !== undefined)\n out = out.filter((t) => t.priority === options.priority);\n if (options.type !== undefined)\n out = out.filter((t) => t.type === options.type);\n if (options.parent_task_id !== undefined) {\n out = out.filter((t) => t.parent_task_id === options.parent_task_id);\n }\n if (options.depth !== undefined && options.depth >= 0) {\n const allowed = allowedIdsByDepth(out, options.depth);\n out = out.filter((t) => allowed.has(t.id));\n }\n return out;\n }\n}\nfunction toNumericHandle(id) {\n if (typeof id === \"number\") {\n return Number.isFinite(id) ? id : undefined;\n }\n return /^\\d+$/.test(id) ? Number(id) : undefined;\n}\nfunction allowedIdsByDepth(views, depth) {\n if (depth < 0)\n return new Set(views.map((t) => t.id));\n const ids = new Set(views.map((t) => t.id));\n const byParent = new Map;\n for (const t of views) {\n const key = t.parent_task_id;\n if (key === undefined || !ids.has(key))\n continue;\n const bucket = byParent.get(key) ?? [];\n bucket.push(t);\n byParent.set(key, bucket);\n }\n const allowed = new Set;\n let frontier = views.filter((t) => t.parent_task_id === undefined || !ids.has(t.parent_task_id));\n for (const t of frontier)\n allowed.add(t.id);\n for (let level = 1;level <= depth; level++) {\n const next = [];\n for (const parent of frontier) {\n for (const child of byParent.get(parent.id) ?? []) {\n if (allowed.has(child.id))\n continue;\n allowed.add(child.id);\n next.push(child);\n }\n }\n if (next.length === 0)\n break;\n frontier = next;\n }\n return allowed;\n}\nfunction mergeDeliverableIntoContext(rawContext, deliverable) {\n let parsed = {};\n if (typeof rawContext === \"string\" && rawContext.trim().length > 0) {\n try {\n const candidate = JSON.parse(rawContext);\n if (candidate && typeof candidate === \"object\" && !Array.isArray(candidate)) {\n parsed = candidate;\n }\n } catch {}\n }\n parsed.deliverable_storage_path = deliverable;\n return JSON.stringify(parsed);\n}\n// src/env/task/backend/sqlite-task-port.ts\nfunction createSQLiteTaskPort(store) {\n return {\n hidesArchivedByDefault: true,\n async createTask(input) {\n const task = await store.createTask({\n title: input.title,\n description: input.description,\n ...input.priority !== undefined ? { priority: input.priority } : {},\n ...input.type !== undefined ? { type: input.type } : {},\n ...input.parent_task_id !== undefined ? { parent_task_id: input.parent_task_id } : {},\n ...input.goals_and_expected_deliverables !== undefined ? { goals_and_expected_deliverables: input.goals_and_expected_deliverables } : {},\n ...input.due_date !== undefined ? { due_date: input.due_date } : {},\n ...input.tags !== undefined ? { tags: input.tags } : {},\n sessionId: input.sessionId ?? \"unknown\",\n project_path: input.project_path,\n context: input.context\n });\n return { ...task, nativeId: String(task.id) };\n },\n async getTask(nativeId) {\n const num = Number(nativeId);\n if (!Number.isFinite(num))\n return null;\n const task = await store.getTask(num);\n return task ? { ...task, nativeId: String(task.id) } : null;\n },\n async getTaskByNum(num) {\n const task = await store.getTask(num);\n return task ? { ...task, nativeId: String(task.id) } : null;\n },\n async listTasks(options) {\n const res = await store.listTasks({\n limit: options?.limit ?? 20,\n offset: options?.offset ?? 0,\n ...options?.includeArchived ? { include_archived: true } : {}\n });\n return {\n tasks: res.tasks.map((t) => ({ ...t, nativeId: String(t.id) })),\n total: res.total\n };\n },\n async updateTask(nativeId, patch) {\n const num = Number(nativeId);\n if (!Number.isFinite(num))\n return null;\n const task = await store.updateTask(num, patch);\n return task ? { ...task, nativeId: String(task.id) } : null;\n },\n async deleteTask(nativeId) {\n const num = Number(nativeId);\n if (!Number.isFinite(num))\n return false;\n return await store.deleteTask(num);\n },\n async createOperation(input) {\n const op = await store.createOperation({\n taskId: input.taskId,\n sessionId: input.sessionId,\n milestoneType: input.milestoneType,\n milestoneTitle: input.milestoneTitle,\n milestoneDescription: input.milestoneDescription,\n processDescription: input.processDescription,\n ...input.mdPath ? { mdPath: input.mdPath } : {}\n });\n return { ...op, nativeId: String(op.id) };\n },\n async listOperations(options) {\n const num = Number(options?.taskNativeId);\n if (!Number.isFinite(num))\n return { operations: [], total: 0 };\n const all = await store.listOperations({ taskId: num, limit: 1e6, offset: 0 });\n const offset = options?.offset ?? 0;\n const limit = options?.limit ?? all.length;\n return {\n operations: all.slice(offset, offset + limit).map((o) => ({ ...o, nativeId: String(o.id) })),\n total: all.length\n };\n },\n async getOperationByNum(num) {\n const op = await store.getOperation(num);\n return op ? { ...op, nativeId: String(op.id) } : null;\n },\n async updateOperationByNum(num, patch) {\n const op = await store.updateOperation(num, {\n ...patch.milestoneTitle !== undefined ? { milestoneTitle: patch.milestoneTitle } : {},\n ...patch.milestoneDescription !== undefined ? { milestoneDescription: patch.milestoneDescription } : {},\n ...patch.processDescription !== undefined ? { processDescription: patch.processDescription } : {}\n });\n return op ? { ...op, nativeId: String(op.id) } : null;\n },\n async deleteOperationByNum(num) {\n return await store.deleteOperation(num);\n }\n };\n}\n// src/env/task/backend/roy-sidecar-task-port.ts\nvar DEFAULT_SCAN = 1e6;\nfunction toSidecarPatch(patch) {\n const out = {};\n if (patch.type !== undefined)\n out.type = patch.type;\n if (patch.progress !== undefined)\n out.progress = patch.progress;\n if (patch.current_status !== undefined)\n out.current_status = patch.current_status;\n if (patch.goals_and_expected_deliverables !== undefined) {\n out.goals_and_expected_deliverables = patch.goals_and_expected_deliverables;\n }\n if (patch.project_path !== undefined)\n out.project_path = patch.project_path;\n if (patch.context !== undefined)\n out.context = patch.context;\n if (patch.due_date !== undefined)\n out.due_date = patch.due_date;\n return out;\n}\nfunction toStoredTask(record, vocabulary, parentNum) {\n if (typeof record.num !== \"number\") {\n throw new Error(`store did not expose a numeric handle for task ${record.id}`);\n }\n const side = record.roy ?? {};\n return {\n id: record.num,\n nativeId: record.id,\n title: record.title,\n description: record.description ?? \"\",\n status: vocabulary.toRoyStatus(record.status),\n priority: vocabulary.toRoyPriority(record.priority),\n type: side.type ?? \"normal\",\n progress: typeof side.progress === \"number\" ? side.progress : record.status === \"done\" ? 100 : 0,\n current_status: side.current_status ?? \"\",\n goals_and_expected_deliverables: side.goals_and_expected_deliverables ?? \"\",\n ...parentNum !== undefined ? { parent_task_id: parentNum } : {},\n createdAt: record.created_at,\n updatedAt: record.updated_at,\n ...side.due_date ? { due_date: side.due_date } : {},\n tags: vocabulary.toRoyTags(record.tags),\n project_path: side.project_path ?? \"unknown\",\n context: side.context ?? \"{}\"\n };\n}\nfunction toStoredOperation(record) {\n const data = record.data ?? {};\n const milestoneType = String(data.milestoneType ?? data.actionType ?? \"progress\");\n const milestoneTitle = String(data.milestoneTitle ?? data.actionTitle ?? \"\");\n const milestoneDescription = String(data.milestoneDescription ?? data.actionDescription ?? \"\");\n const taskIdRaw = data.taskId ?? record.task_id;\n const taskId = typeof taskIdRaw === \"number\" ? taskIdRaw : typeof taskIdRaw === \"string\" && /^\\d+$/.test(taskIdRaw) ? Number(taskIdRaw) : 0;\n return {\n id: typeof record.num === \"number\" ? record.num : 0,\n nativeId: record.id,\n taskId,\n sessionId: String(data.sessionId ?? record.task_id ?? \"unknown\"),\n milestoneType,\n milestoneTitle,\n milestoneDescription,\n processDescription: String(data.processDescription ?? \"\"),\n timestamp: record.created_at,\n ...data.mdPath ? { mdPath: String(data.mdPath) } : {},\n actionType: milestoneType,\n actionTitle: milestoneTitle,\n actionDescription: milestoneDescription\n };\n}\nfunction createRoySidecarTaskPort(store, vocabulary, options = {}) {\n const operationType = options.operationType ?? \"roy.milestone\";\n const agent = options.agent ?? \"roy\";\n const scanLimit = options.scanLimit ?? DEFAULT_SCAN;\n async function parentNumMap() {\n const all = await store.listTasks({ limit: scanLimit });\n return new Map(all.tasks.filter((t) => typeof t.num === \"number\").map((t) => [t.id, t.num]));\n }\n async function resolveByNum(num) {\n if (typeof store.getTaskByNum === \"function\")\n return await store.getTaskByNum(num);\n const all = await store.listTasks({ limit: scanLimit });\n return all.tasks.find((t) => t.num === num) ?? null;\n }\n async function nativeIdOf(num) {\n const nums = await parentNumMap();\n const hit = [...nums.entries()].find(([, n]) => n === num);\n if (!hit)\n throw new Error(`parent task not found: ${num}`);\n return hit[0];\n }\n return {\n hidesArchivedByDefault: false,\n async createTask(input) {\n const parentId = input.parent_task_id !== undefined ? await nativeIdOf(input.parent_task_id) : null;\n const sidecar = {\n type: input.type ?? \"normal\",\n progress: input.progress ?? 0,\n current_status: input.current_status ?? \"\",\n goals_and_expected_deliverables: input.goals_and_expected_deliverables ?? \"\",\n project_path: input.project_path,\n context: input.context,\n ...input.due_date ? { due_date: input.due_date } : {}\n };\n const created = await store.createTask({\n title: input.title,\n description: input.description,\n priority: vocabulary.toStorePriority(input.priority),\n owner: agent,\n tags: vocabulary.toStoreTags(input.tags),\n parent_id: parentId,\n session_id: input.sessionId ?? \"unknown\",\n roy: sidecar\n });\n return toStoredTask(created, vocabulary, input.parent_task_id);\n },\n async getTask(nativeId) {\n const task = await store.getTask(nativeId);\n if (!task)\n return null;\n const nums = await parentNumMap();\n return toStoredTask(task, vocabulary, task.parent_id ? nums.get(task.parent_id) : undefined);\n },\n async getTaskByNum(num) {\n const task = await resolveByNum(num);\n if (!task)\n return null;\n const nums = await parentNumMap();\n return toStoredTask(task, vocabulary, task.parent_id ? nums.get(task.parent_id) : undefined);\n },\n async listTasks(request) {\n const res = await store.listTasks({\n limit: request?.limit ?? 20,\n offset: request?.offset ?? 0\n });\n const nums = await parentNumMap();\n return {\n tasks: res.tasks.map((t) => toStoredTask(t, vocabulary, t.parent_id ? nums.get(t.parent_id) : undefined)),\n total: res.total\n };\n },\n async updateTask(nativeId, patch) {\n const sidePatch = toSidecarPatch(patch);\n const updated = await store.updateTask(nativeId, {\n ...patch.title !== undefined ? { title: patch.title } : {},\n ...patch.description !== undefined ? { description: patch.description } : {},\n ...patch.status !== undefined ? { status: vocabulary.toStoreStatus(patch.status) } : {},\n ...patch.priority !== undefined ? { priority: vocabulary.toStorePriority(patch.priority) } : {},\n ...patch.tags !== undefined ? { tags: vocabulary.toStoreTags(patch.tags) } : {},\n ...Object.keys(sidePatch).length > 0 ? { roy: sidePatch } : {}\n });\n if (!updated)\n return null;\n let parentNum;\n if (patch.parent_task_id !== undefined) {\n const newParent = patch.parent_task_id === null ? null : await nativeIdOf(patch.parent_task_id);\n if (typeof store.setParentId === \"function\") {\n await store.setParentId(nativeId, newParent);\n }\n parentNum = patch.parent_task_id === null ? undefined : patch.parent_task_id;\n }\n const reread = await store.getTask(nativeId) ?? updated;\n if (parentNum === undefined && reread.parent_id) {\n const nums = await parentNumMap();\n parentNum = nums.get(reread.parent_id);\n }\n return toStoredTask(reread, vocabulary, parentNum);\n },\n async deleteTask(nativeId) {\n return await store.deleteTask(nativeId);\n },\n async createOperation(input) {\n const op = await store.appendOperation({\n task_id: input.taskNativeId ?? String(input.taskId),\n type: operationType,\n data: {\n taskId: input.taskId,\n sessionId: input.sessionId,\n milestoneType: input.milestoneType,\n milestoneTitle: input.milestoneTitle,\n milestoneDescription: input.milestoneDescription,\n processDescription: input.processDescription,\n ...input.mdPath ? { mdPath: input.mdPath } : {}\n }\n });\n return toStoredOperation(op);\n },\n async listOperations(request) {\n const res = await store.listOperations({\n ...request?.taskNativeId ? { task_id: request.taskNativeId } : {},\n type: operationType,\n limit: request?.limit ?? scanLimit,\n offset: request?.offset ?? 0\n });\n return { operations: res.operations.map(toStoredOperation), total: res.total };\n },\n async getOperationByNum(num) {\n if (typeof store.getOperationByNum !== \"function\")\n return null;\n const op = await store.getOperationByNum(num);\n return op ? toStoredOperation(op) : null;\n },\n async updateOperationByNum(num, patch) {\n if (typeof store.updateOperation !== \"function\")\n return null;\n if (typeof store.getOperationByNum !== \"function\")\n return null;\n const existing = await store.getOperationByNum(num);\n if (!existing)\n return null;\n const previous = toStoredOperation(existing);\n const updated = await store.updateOperation(num, {\n data: {\n taskId: previous.taskId,\n sessionId: patch.sessionId ?? previous.sessionId,\n milestoneType: patch.milestoneType ?? previous.milestoneType,\n milestoneTitle: patch.milestoneTitle ?? previous.milestoneTitle,\n milestoneDescription: patch.milestoneDescription ?? previous.milestoneDescription,\n processDescription: patch.processDescription ?? previous.processDescription,\n ...patch.mdPath ?? previous.mdPath ? { mdPath: patch.mdPath ?? previous.mdPath } : {}\n }\n });\n return updated ? toStoredOperation(updated) : null;\n },\n async deleteOperationByNum(num) {\n if (typeof store.deleteOperation !== \"function\")\n return false;\n return await store.deleteOperation(num);\n }\n };\n}\nexport {\n toNumericHandle,\n mergeDeliverableIntoContext,\n formatDeliverableForOperation,\n createSQLiteTaskPort,\n createRoySidecarTaskPort,\n allowedIdsByDepth,\n TaskStoreBackend,\n DELIVERABLE_OPERATION_PREFIX\n};\n",
|
|
112
|
+
"/**\n * Plugin ⇄ roy-core adapter (Task #4380).\n *\n * **Not** a re-implementation of roy's task semantics — those used to live in\n * an 869-line `facade.ts` here (BFS, `depth`, deliverable→context merge,\n * automatic `create` op, flat op list, honest `total`, eight search filters,\n * hand-copied enums), which made a Claude Code / Codex adapter impossible\n * without copying it all again (review #4371 §8.1 / §5.5). They now live once\n * in `@ai-setting/roy-agent-core`:\n *\n * tool factories → TaskStoreBackend → createRoySidecarTaskPort → TaskStore\n *\n * What remains here is only what is genuinely this plugin's: its business\n * vocabulary (`pending|in_progress|blocked|review|done`, integer priority —\n * neither is roy's) and binding its `TaskStore` into roy-core.\n */\n\nimport {\n createRoySidecarTaskPort,\n TaskStoreBackend,\n type TaskBackend,\n type TaskBackendOptions,\n type SidecarVocabulary,\n} from \"@ai-setting/roy-agent-core/env/task/backend\";\nimport type { TaskStatus as RoyStatus } from \"@ai-setting/roy-agent-core/env/task\";\nimport type { TaskStatus as PluginStatus, TaskStore } from \"@roy-task-plugin/shared\";\n\n/** The audit-log type this plugin uses for roy milestones. */\nexport const ROY_OPERATION_TYPE = \"roy.milestone\";\n\n/** @deprecated aliases kept so existing call sites keep type-checking. */\nexport type TaskComponentFacade = TaskBackend;\nexport type RoyTaskFacade = TaskBackend;\n\nexport interface RoyFacadeOptions extends TaskBackendOptions {\n /** Owner recorded on created tasks (this plugin's `Task.owner`). */\n agent?: string;\n}\n\n/**\n * Vocabulary. Lossy pairs are deliberate: roy `paused` → plugin `blocked`;\n * plugin `review`/`blocked` → roy `active`/`paused`. Every roy status is\n * round-trip stable: `pluginStatusToRoy(royStatusToPlugin(s)) === s`.\n */\nconst ROY_TO_PLUGIN_STATUS: Record<RoyStatus, PluginStatus> = {\n todo: \"pending\",\n active: \"in_progress\",\n completed: \"done\",\n cancelled: \"cancelled\",\n paused: \"blocked\", // lossy\n archived: \"archived\",\n};\nconst PLUGIN_TO_ROY_STATUS: Record<string, RoyStatus> = {\n pending: \"todo\",\n in_progress: \"active\",\n done: \"completed\",\n cancelled: \"cancelled\",\n blocked: \"paused\",\n review: \"active\", // lossy\n archived: \"archived\",\n};\n\n/** roy status → plugin status. Unknown input degrades to `pending`. */\nexport function royStatusToPlugin(status: string): PluginStatus {\n return ROY_TO_PLUGIN_STATUS[status as RoyStatus] ?? \"pending\";\n}\n/** plugin status → roy status. Unknown input degrades to `todo`. */\nexport function pluginStatusToRoy(status: string): RoyStatus {\n return PLUGIN_TO_ROY_STATUS[status] ?? \"todo\";\n}\n\n/** roy priority (low/medium/high) → plugin integer priority (lower = sooner). */\nexport function royPriorityToPlugin(priority?: string): number {\n if (priority === \"high\") return 1;\n if (priority === \"low\") return 5;\n return 3;\n}\n\n/** plugin integer priority (1..5, lower = sooner) → roy priority bucket. */\nexport function pluginPriorityToRoy(priority?: number): \"low\" | \"medium\" | \"high\" {\n if (priority === undefined) return \"medium\";\n if (priority <= 2) return \"high\";\n return priority === 3 ? \"medium\" : \"low\";\n}\n\n/** roy tags (string[]) → plugin comma-separated TEXT. Empty → undefined. */\nexport function tagsToPlugin(tags?: string[]): string | undefined {\n if (!tags || tags.length === 0) return undefined;\n return tags.join(\",\");\n}\n\n/** plugin comma-separated TEXT → roy tags (string[]). */\nexport function tagsToRoy(tags?: string | null): string[] {\n if (!tags) return [];\n return tags.split(\",\").map((t) => t.trim()).filter((t) => t.length > 0);\n}\n\n/** The vocabulary object roy-core's sidecar port needs. */\nexport const VOCABULARY: SidecarVocabulary = {\n toRoyStatus: (s) => pluginStatusToRoy(s),\n toStoreStatus: (s) => royStatusToPlugin(s),\n toRoyPriority: (p) => pluginPriorityToRoy(p),\n toStorePriority: (p) => royPriorityToPlugin(p),\n toRoyTags: (t) => tagsToRoy(t),\n toStoreTags: (t) => tagsToPlugin(t),\n};\n\n/**\n * Bind a plugin `TaskStore` to roy's task semantics. Returns a `TaskBackend` —\n * exactly the surface roy's tool factories call, `getTaskTree` included (its\n * absence was review finding B1).\n */\nexport function createRoyTaskFacade(store: TaskStore, opts: RoyFacadeOptions = {}): TaskBackend {\n return new TaskStoreBackend(\n createRoySidecarTaskPort(store, VOCABULARY, {\n operationType: ROY_OPERATION_TYPE,\n agent: opts.agent ?? \"roy\",\n }),\n { sessionId: opts.sessionId },\n );\n}\n",
|
|
113
|
+
"/**\n * roy vocabulary re-exports (Task #4380).\n *\n * This file used to hold a *copy* of roy's enums plus the plugin's status /\n * priority / tag mapping. Since Task #4380 the vocabulary is taken straight\n * from roy-agent (`TaskStatusEnum` / `TaskPriorityEnum` / `TaskTypeEnum` /\n * `ActionTypeEnum` — single source, review finding Y4) and the mapping lives\n * next to the adapter in `facade.ts`.\n *\n * What is left here is a 6-line re-export shim so existing call sites and the\n * drift-detector tests (Y4 / Y4b) keep working unchanged.\n */\n\nimport {\n ActionTypeEnum,\n TaskPriorityEnum,\n TaskStatusEnum,\n TaskTypeEnum,\n} from \"@ai-setting/roy-agent-core/env/task\";\n\n/** roy status vocabulary — the enum's own `options` array (value identity). */\nexport const ROY_STATUSES = TaskStatusEnum.options;\n/** roy priority vocabulary. */\nexport const ROY_PRIORITIES = TaskPriorityEnum.options;\n/** roy task-type vocabulary. */\nexport const ROY_TASK_TYPES = TaskTypeEnum.options;\n/** roy milestone/operation-type vocabulary. */\nexport const ROY_OPERATION_TYPES = ActionTypeEnum.options;\n\nexport {\n pluginPriorityToRoy,\n pluginStatusToRoy,\n royPriorityToPlugin,\n royStatusToPlugin,\n tagsToPlugin,\n tagsToRoy,\n} from \"./facade.js\";\n",
|
|
114
|
+
"export const ignoreOverride = Symbol(\"Let zodToJsonSchema decide on which parser to use\");\nexport const jsonDescription = (jsonSchema, def) => {\n if (def.description) {\n try {\n return {\n ...jsonSchema,\n ...JSON.parse(def.description),\n };\n }\n catch { }\n }\n return jsonSchema;\n};\nexport const defaultOptions = {\n name: undefined,\n $refStrategy: \"root\",\n basePath: [\"#\"],\n effectStrategy: \"input\",\n pipeStrategy: \"all\",\n dateStrategy: \"format:date-time\",\n mapStrategy: \"entries\",\n removeAdditionalStrategy: \"passthrough\",\n allowedAdditionalProperties: true,\n rejectedAdditionalProperties: false,\n definitionPath: \"definitions\",\n target: \"jsonSchema7\",\n strictUnions: false,\n definitions: {},\n errorMessages: false,\n markdownDescription: false,\n patternStrategy: \"escape\",\n applyRegexFlags: false,\n emailStrategy: \"format:email\",\n base64Strategy: \"contentEncoding:base64\",\n nameStrategy: \"ref\",\n openAiAnyTypeName: \"OpenAiAnyType\"\n};\nexport const getDefaultOptions = (options) => (typeof options === \"string\"\n ? {\n ...defaultOptions,\n name: options,\n }\n : {\n ...defaultOptions,\n ...options,\n });\n",
|
|
115
|
+
"import { getDefaultOptions } from \"./Options.js\";\nexport const getRefs = (options) => {\n const _options = getDefaultOptions(options);\n const currentPath = _options.name !== undefined\n ? [..._options.basePath, _options.definitionPath, _options.name]\n : _options.basePath;\n return {\n ..._options,\n flags: { hasReferencedOpenAiAnyType: false },\n currentPath: currentPath,\n propertyPath: undefined,\n seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [\n def._def,\n {\n def: def._def,\n path: [..._options.basePath, _options.definitionPath, name],\n // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.\n jsonSchema: undefined,\n },\n ])),\n };\n};\n",
|
|
116
|
+
"export function addErrorMessage(res, key, errorMessage, refs) {\n if (!refs?.errorMessages)\n return;\n if (errorMessage) {\n res.errorMessage = {\n ...res.errorMessage,\n [key]: errorMessage,\n };\n }\n}\nexport function setResponseValueAndErrors(res, key, value, errorMessage, refs) {\n res[key] = value;\n addErrorMessage(res, key, errorMessage, refs);\n}\n",
|
|
117
|
+
"export const getRelativePath = (pathA, pathB) => {\n let i = 0;\n for (; i < pathA.length && i < pathB.length; i++) {\n if (pathA[i] !== pathB[i])\n break;\n }\n return [(pathA.length - i).toString(), ...pathB.slice(i)].join(\"/\");\n};\n",
|
|
118
|
+
"import { getRelativePath } from \"../getRelativePath.js\";\nexport function parseAnyDef(refs) {\n if (refs.target !== \"openAi\") {\n return {};\n }\n const anyDefinitionPath = [\n ...refs.basePath,\n refs.definitionPath,\n refs.openAiAnyTypeName,\n ];\n refs.flags.hasReferencedOpenAiAnyType = true;\n return {\n $ref: refs.$refStrategy === \"relative\"\n ? getRelativePath(anyDefinitionPath, refs.currentPath)\n : anyDefinitionPath.join(\"/\"),\n };\n}\n",
|
|
119
|
+
"import { ZodFirstPartyTypeKind } from \"zod/v3\";\nimport { setResponseValueAndErrors } from \"../errorMessages.js\";\nimport { parseDef } from \"../parseDef.js\";\nexport function parseArrayDef(def, refs) {\n const res = {\n type: \"array\",\n };\n if (def.type?._def &&\n def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {\n res.items = parseDef(def.type._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"],\n });\n }\n if (def.minLength) {\n setResponseValueAndErrors(res, \"minItems\", def.minLength.value, def.minLength.message, refs);\n }\n if (def.maxLength) {\n setResponseValueAndErrors(res, \"maxItems\", def.maxLength.value, def.maxLength.message, refs);\n }\n if (def.exactLength) {\n setResponseValueAndErrors(res, \"minItems\", def.exactLength.value, def.exactLength.message, refs);\n setResponseValueAndErrors(res, \"maxItems\", def.exactLength.value, def.exactLength.message, refs);\n }\n return res;\n}\n",
|
|
120
|
+
"import { setResponseValueAndErrors } from \"../errorMessages.js\";\nexport function parseBigintDef(def, refs) {\n const res = {\n type: \"integer\",\n format: \"int64\",\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMinimum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n break;\n case \"max\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMaximum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n break;\n case \"multipleOf\":\n setResponseValueAndErrors(res, \"multipleOf\", check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n",
|
|
121
|
+
"export function parseBooleanDef() {\n return {\n type: \"boolean\",\n };\n}\n",
|
|
122
|
+
"import { parseDef } from \"../parseDef.js\";\nexport function parseBrandedDef(_def, refs) {\n return parseDef(_def.type._def, refs);\n}\n",
|
|
123
|
+
"import { parseDef } from \"../parseDef.js\";\nexport const parseCatchDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n",
|
|
124
|
+
"import { setResponseValueAndErrors } from \"../errorMessages.js\";\nexport function parseDateDef(def, refs, overrideDateStrategy) {\n const strategy = overrideDateStrategy ?? refs.dateStrategy;\n if (Array.isArray(strategy)) {\n return {\n anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)),\n };\n }\n switch (strategy) {\n case \"string\":\n case \"format:date-time\":\n return {\n type: \"string\",\n format: \"date-time\",\n };\n case \"format:date\":\n return {\n type: \"string\",\n format: \"date\",\n };\n case \"integer\":\n return integerDateParser(def, refs);\n }\n}\nconst integerDateParser = (def, refs) => {\n const res = {\n type: \"integer\",\n format: \"unix-time\",\n };\n if (refs.target === \"openApi3\") {\n return res;\n }\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n setResponseValueAndErrors(res, \"minimum\", check.value, // This is in milliseconds\n check.message, refs);\n break;\n case \"max\":\n setResponseValueAndErrors(res, \"maximum\", check.value, // This is in milliseconds\n check.message, refs);\n break;\n }\n }\n return res;\n};\n",
|
|
125
|
+
"import { parseDef } from \"../parseDef.js\";\nexport function parseDefaultDef(_def, refs) {\n return {\n ...parseDef(_def.innerType._def, refs),\n default: _def.defaultValue(),\n };\n}\n",
|
|
126
|
+
"import { parseDef } from \"../parseDef.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport function parseEffectsDef(_def, refs) {\n return refs.effectStrategy === \"input\"\n ? parseDef(_def.schema._def, refs)\n : parseAnyDef(refs);\n}\n",
|
|
127
|
+
"export function parseEnumDef(def) {\n return {\n type: \"string\",\n enum: Array.from(def.values),\n };\n}\n",
|
|
128
|
+
"import { parseDef } from \"../parseDef.js\";\nconst isJsonSchema7AllOfType = (type) => {\n if (\"type\" in type && type.type === \"string\")\n return false;\n return \"allOf\" in type;\n};\nexport function parseIntersectionDef(def, refs) {\n const allOf = [\n parseDef(def.left._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"],\n }),\n parseDef(def.right._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"1\"],\n }),\n ].filter((x) => !!x);\n let unevaluatedProperties = refs.target === \"jsonSchema2019-09\"\n ? { unevaluatedProperties: false }\n : undefined;\n const mergedAllOf = [];\n // If either of the schemas is an allOf, merge them into a single allOf\n allOf.forEach((schema) => {\n if (isJsonSchema7AllOfType(schema)) {\n mergedAllOf.push(...schema.allOf);\n if (schema.unevaluatedProperties === undefined) {\n // If one of the schemas has no unevaluatedProperties set,\n // the merged schema should also have no unevaluatedProperties set\n unevaluatedProperties = undefined;\n }\n }\n else {\n let nestedSchema = schema;\n if (\"additionalProperties\" in schema &&\n schema.additionalProperties === false) {\n const { additionalProperties, ...rest } = schema;\n nestedSchema = rest;\n }\n else {\n // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties\n unevaluatedProperties = undefined;\n }\n mergedAllOf.push(nestedSchema);\n }\n });\n return mergedAllOf.length\n ? {\n allOf: mergedAllOf,\n ...unevaluatedProperties,\n }\n : undefined;\n}\n",
|
|
129
|
+
"export function parseLiteralDef(def, refs) {\n const parsedType = typeof def.value;\n if (parsedType !== \"bigint\" &&\n parsedType !== \"number\" &&\n parsedType !== \"boolean\" &&\n parsedType !== \"string\") {\n return {\n type: Array.isArray(def.value) ? \"array\" : \"object\",\n };\n }\n if (refs.target === \"openApi3\") {\n return {\n type: parsedType === \"bigint\" ? \"integer\" : parsedType,\n enum: [def.value],\n };\n }\n return {\n type: parsedType === \"bigint\" ? \"integer\" : parsedType,\n const: def.value,\n };\n}\n",
|
|
130
|
+
"import { setResponseValueAndErrors } from \"../errorMessages.js\";\nlet emojiRegex = undefined;\n/**\n * Generated from the regular expressions found here as of 2024-05-22:\n * https://github.com/colinhacks/zod/blob/master/src/types.ts.\n *\n * Expressions with /i flag have been changed accordingly.\n */\nexport const zodPatterns = {\n /**\n * `c` was changed to `[cC]` to replicate /i flag\n */\n cuid: /^[cC][^\\s-]{8,}$/,\n cuid2: /^[0-9a-z]+$/,\n ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,\n /**\n * `a-z` was added to replicate /i flag\n */\n email: /^(?!\\.)(?!.*\\.\\.)([a-zA-Z0-9_'+\\-\\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\\-]*\\.)+[a-zA-Z]{2,}$/,\n /**\n * Constructed a valid Unicode RegExp\n *\n * Lazily instantiate since this type of regex isn't supported\n * in all envs (e.g. React Native).\n *\n * See:\n * https://github.com/colinhacks/zod/issues/2433\n * Fix in Zod:\n * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b\n */\n emoji: () => {\n if (emojiRegex === undefined) {\n emojiRegex = RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\", \"u\");\n }\n return emojiRegex;\n },\n /**\n * Unused\n */\n uuid: /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/,\n /**\n * Unused\n */\n ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,\n ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/,\n /**\n * Unused\n */\n ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,\n ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,\n base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,\n base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,\n nanoid: /^[a-zA-Z0-9_-]{21}$/,\n jwt: /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/,\n};\nexport function parseStringDef(def, refs) {\n const res = {\n type: \"string\",\n };\n if (def.checks) {\n for (const check of def.checks) {\n switch (check.kind) {\n case \"min\":\n setResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"max\":\n setResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"email\":\n switch (refs.emailStrategy) {\n case \"format:email\":\n addFormat(res, \"email\", check.message, refs);\n break;\n case \"format:idn-email\":\n addFormat(res, \"idn-email\", check.message, refs);\n break;\n case \"pattern:zod\":\n addPattern(res, zodPatterns.email, check.message, refs);\n break;\n }\n break;\n case \"url\":\n addFormat(res, \"uri\", check.message, refs);\n break;\n case \"uuid\":\n addFormat(res, \"uuid\", check.message, refs);\n break;\n case \"regex\":\n addPattern(res, check.regex, check.message, refs);\n break;\n case \"cuid\":\n addPattern(res, zodPatterns.cuid, check.message, refs);\n break;\n case \"cuid2\":\n addPattern(res, zodPatterns.cuid2, check.message, refs);\n break;\n case \"startsWith\":\n addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);\n break;\n case \"endsWith\":\n addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);\n break;\n case \"datetime\":\n addFormat(res, \"date-time\", check.message, refs);\n break;\n case \"date\":\n addFormat(res, \"date\", check.message, refs);\n break;\n case \"time\":\n addFormat(res, \"time\", check.message, refs);\n break;\n case \"duration\":\n addFormat(res, \"duration\", check.message, refs);\n break;\n case \"length\":\n setResponseValueAndErrors(res, \"minLength\", typeof res.minLength === \"number\"\n ? Math.max(res.minLength, check.value)\n : check.value, check.message, refs);\n setResponseValueAndErrors(res, \"maxLength\", typeof res.maxLength === \"number\"\n ? Math.min(res.maxLength, check.value)\n : check.value, check.message, refs);\n break;\n case \"includes\": {\n addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);\n break;\n }\n case \"ip\": {\n if (check.version !== \"v6\") {\n addFormat(res, \"ipv4\", check.message, refs);\n }\n if (check.version !== \"v4\") {\n addFormat(res, \"ipv6\", check.message, refs);\n }\n break;\n }\n case \"base64url\":\n addPattern(res, zodPatterns.base64url, check.message, refs);\n break;\n case \"jwt\":\n addPattern(res, zodPatterns.jwt, check.message, refs);\n break;\n case \"cidr\": {\n if (check.version !== \"v6\") {\n addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);\n }\n if (check.version !== \"v4\") {\n addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);\n }\n break;\n }\n case \"emoji\":\n addPattern(res, zodPatterns.emoji(), check.message, refs);\n break;\n case \"ulid\": {\n addPattern(res, zodPatterns.ulid, check.message, refs);\n break;\n }\n case \"base64\": {\n switch (refs.base64Strategy) {\n case \"format:binary\": {\n addFormat(res, \"binary\", check.message, refs);\n break;\n }\n case \"contentEncoding:base64\": {\n setResponseValueAndErrors(res, \"contentEncoding\", \"base64\", check.message, refs);\n break;\n }\n case \"pattern:zod\": {\n addPattern(res, zodPatterns.base64, check.message, refs);\n break;\n }\n }\n break;\n }\n case \"nanoid\": {\n addPattern(res, zodPatterns.nanoid, check.message, refs);\n }\n case \"toLowerCase\":\n case \"toUpperCase\":\n case \"trim\":\n break;\n default:\n ((_) => { })(check);\n }\n }\n }\n return res;\n}\nfunction escapeLiteralCheckValue(literal, refs) {\n return refs.patternStrategy === \"escape\"\n ? escapeNonAlphaNumeric(literal)\n : literal;\n}\nconst ALPHA_NUMERIC = new Set(\"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789\");\nfunction escapeNonAlphaNumeric(source) {\n let result = \"\";\n for (let i = 0; i < source.length; i++) {\n if (!ALPHA_NUMERIC.has(source[i])) {\n result += \"\\\\\";\n }\n result += source[i];\n }\n return result;\n}\n// Adds a \"format\" keyword to the schema. If a format exists, both formats will be joined in an allOf-node, along with subsequent ones.\nfunction addFormat(schema, value, message, refs) {\n if (schema.format || schema.anyOf?.some((x) => x.format)) {\n if (!schema.anyOf) {\n schema.anyOf = [];\n }\n if (schema.format) {\n schema.anyOf.push({\n format: schema.format,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { format: schema.errorMessage.format },\n }),\n });\n delete schema.format;\n if (schema.errorMessage) {\n delete schema.errorMessage.format;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.anyOf.push({\n format: value,\n ...(message &&\n refs.errorMessages && { errorMessage: { format: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, \"format\", value, message, refs);\n }\n}\n// Adds a \"pattern\" keyword to the schema. If a pattern exists, both patterns will be joined in an allOf-node, along with subsequent ones.\nfunction addPattern(schema, regex, message, refs) {\n if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {\n if (!schema.allOf) {\n schema.allOf = [];\n }\n if (schema.pattern) {\n schema.allOf.push({\n pattern: schema.pattern,\n ...(schema.errorMessage &&\n refs.errorMessages && {\n errorMessage: { pattern: schema.errorMessage.pattern },\n }),\n });\n delete schema.pattern;\n if (schema.errorMessage) {\n delete schema.errorMessage.pattern;\n if (Object.keys(schema.errorMessage).length === 0) {\n delete schema.errorMessage;\n }\n }\n }\n schema.allOf.push({\n pattern: stringifyRegExpWithFlags(regex, refs),\n ...(message &&\n refs.errorMessages && { errorMessage: { pattern: message } }),\n });\n }\n else {\n setResponseValueAndErrors(schema, \"pattern\", stringifyRegExpWithFlags(regex, refs), message, refs);\n }\n}\n// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true\nfunction stringifyRegExpWithFlags(regex, refs) {\n if (!refs.applyRegexFlags || !regex.flags) {\n return regex.source;\n }\n // Currently handled flags\n const flags = {\n i: regex.flags.includes(\"i\"),\n m: regex.flags.includes(\"m\"),\n s: regex.flags.includes(\"s\"), // `.` matches newlines\n };\n // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril!\n const source = flags.i ? regex.source.toLowerCase() : regex.source;\n let pattern = \"\";\n let isEscaped = false;\n let inCharGroup = false;\n let inCharRange = false;\n for (let i = 0; i < source.length; i++) {\n if (isEscaped) {\n pattern += source[i];\n isEscaped = false;\n continue;\n }\n if (flags.i) {\n if (inCharGroup) {\n if (source[i].match(/[a-z]/)) {\n if (inCharRange) {\n pattern += source[i];\n pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();\n inCharRange = false;\n }\n else if (source[i + 1] === \"-\" && source[i + 2]?.match(/[a-z]/)) {\n pattern += source[i];\n inCharRange = true;\n }\n else {\n pattern += `${source[i]}${source[i].toUpperCase()}`;\n }\n continue;\n }\n }\n else if (source[i].match(/[a-z]/)) {\n pattern += `[${source[i]}${source[i].toUpperCase()}]`;\n continue;\n }\n }\n if (flags.m) {\n if (source[i] === \"^\") {\n pattern += `(^|(?<=[\\r\\n]))`;\n continue;\n }\n else if (source[i] === \"$\") {\n pattern += `($|(?=[\\r\\n]))`;\n continue;\n }\n }\n if (flags.s && source[i] === \".\") {\n pattern += inCharGroup ? `${source[i]}\\r\\n` : `[${source[i]}\\r\\n]`;\n continue;\n }\n pattern += source[i];\n if (source[i] === \"\\\\\") {\n isEscaped = true;\n }\n else if (inCharGroup && source[i] === \"]\") {\n inCharGroup = false;\n }\n else if (!inCharGroup && source[i] === \"[\") {\n inCharGroup = true;\n }\n }\n try {\n new RegExp(pattern);\n }\n catch {\n console.warn(`Could not convert regex pattern at ${refs.currentPath.join(\"/\")} to a flag-independent form! Falling back to the flag-ignorant source`);\n return regex.source;\n }\n return pattern;\n}\n",
|
|
131
|
+
"import { ZodFirstPartyTypeKind, } from \"zod/v3\";\nimport { parseDef } from \"../parseDef.js\";\nimport { parseStringDef } from \"./string.js\";\nimport { parseBrandedDef } from \"./branded.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport function parseRecordDef(def, refs) {\n if (refs.target === \"openAi\") {\n console.warn(\"Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.\");\n }\n if (refs.target === \"openApi3\" &&\n def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n type: \"object\",\n required: def.keyType._def.values,\n properties: def.keyType._def.values.reduce((acc, key) => ({\n ...acc,\n [key]: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"properties\", key],\n }) ?? parseAnyDef(refs),\n }), {}),\n additionalProperties: refs.rejectedAdditionalProperties,\n };\n }\n const schema = {\n type: \"object\",\n additionalProperties: parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"],\n }) ?? refs.allowedAdditionalProperties,\n };\n if (refs.target === \"openApi3\") {\n return schema;\n }\n if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n def.keyType._def.checks?.length) {\n const { type, ...keyType } = parseStringDef(def.keyType._def, refs);\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) {\n return {\n ...schema,\n propertyNames: {\n enum: def.keyType._def.values,\n },\n };\n }\n else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded &&\n def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString &&\n def.keyType._def.type._def.checks?.length) {\n const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);\n return {\n ...schema,\n propertyNames: keyType,\n };\n }\n return schema;\n}\n",
|
|
132
|
+
"import { parseDef } from \"../parseDef.js\";\nimport { parseRecordDef } from \"./record.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport function parseMapDef(def, refs) {\n if (refs.mapStrategy === \"record\") {\n return parseRecordDef(def, refs);\n }\n const keys = parseDef(def.keyType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"0\"],\n }) || parseAnyDef(refs);\n const values = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", \"items\", \"1\"],\n }) || parseAnyDef(refs);\n return {\n type: \"array\",\n maxItems: 125,\n items: {\n type: \"array\",\n items: [keys, values],\n minItems: 2,\n maxItems: 2,\n },\n };\n}\n",
|
|
133
|
+
"export function parseNativeEnumDef(def) {\n const object = def.values;\n const actualKeys = Object.keys(def.values).filter((key) => {\n return typeof object[object[key]] !== \"number\";\n });\n const actualValues = actualKeys.map((key) => object[key]);\n const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));\n return {\n type: parsedTypes.length === 1\n ? parsedTypes[0] === \"string\"\n ? \"string\"\n : \"number\"\n : [\"string\", \"number\"],\n enum: actualValues,\n };\n}\n",
|
|
134
|
+
"import { parseAnyDef } from \"./any.js\";\nexport function parseNeverDef(refs) {\n return refs.target === \"openAi\"\n ? undefined\n : {\n not: parseAnyDef({\n ...refs,\n currentPath: [...refs.currentPath, \"not\"],\n }),\n };\n}\n",
|
|
135
|
+
"export function parseNullDef(refs) {\n return refs.target === \"openApi3\"\n ? {\n enum: [\"null\"],\n nullable: true,\n }\n : {\n type: \"null\",\n };\n}\n",
|
|
136
|
+
"import { parseDef } from \"../parseDef.js\";\nexport const primitiveMappings = {\n ZodString: \"string\",\n ZodNumber: \"number\",\n ZodBigInt: \"integer\",\n ZodBoolean: \"boolean\",\n ZodNull: \"null\",\n};\nexport function parseUnionDef(def, refs) {\n if (refs.target === \"openApi3\")\n return asAnyOf(def, refs);\n const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;\n // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf.\n if (options.every((x) => x._def.typeName in primitiveMappings &&\n (!x._def.checks || !x._def.checks.length))) {\n // all types in union are primitive and lack checks, so might as well squash into {type: [...]}\n const types = options.reduce((types, x) => {\n const type = primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43\n return type && !types.includes(type) ? [...types, type] : types;\n }, []);\n return {\n type: types.length > 1 ? types : types[0],\n };\n }\n else if (options.every((x) => x._def.typeName === \"ZodLiteral\" && !x.description)) {\n // all options literals\n const types = options.reduce((acc, x) => {\n const type = typeof x._def.value;\n switch (type) {\n case \"string\":\n case \"number\":\n case \"boolean\":\n return [...acc, type];\n case \"bigint\":\n return [...acc, \"integer\"];\n case \"object\":\n if (x._def.value === null)\n return [...acc, \"null\"];\n case \"symbol\":\n case \"undefined\":\n case \"function\":\n default:\n return acc;\n }\n }, []);\n if (types.length === options.length) {\n // all the literals are primitive, as far as null can be considered primitive\n const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);\n return {\n type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],\n enum: options.reduce((acc, x) => {\n return acc.includes(x._def.value) ? acc : [...acc, x._def.value];\n }, []),\n };\n }\n }\n else if (options.every((x) => x._def.typeName === \"ZodEnum\")) {\n return {\n type: \"string\",\n enum: options.reduce((acc, x) => [\n ...acc,\n ...x._def.values.filter((x) => !acc.includes(x)),\n ], []),\n };\n }\n return asAnyOf(def, refs);\n}\nconst asAnyOf = (def, refs) => {\n const anyOf = (def.options instanceof Map\n ? Array.from(def.options.values())\n : def.options)\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", `${i}`],\n }))\n .filter((x) => !!x &&\n (!refs.strictUnions ||\n (typeof x === \"object\" && Object.keys(x).length > 0)));\n return anyOf.length ? { anyOf } : undefined;\n};\n",
|
|
137
|
+
"import { parseDef } from \"../parseDef.js\";\nimport { primitiveMappings } from \"./union.js\";\nexport function parseNullableDef(def, refs) {\n if ([\"ZodString\", \"ZodNumber\", \"ZodBigInt\", \"ZodBoolean\", \"ZodNull\"].includes(def.innerType._def.typeName) &&\n (!def.innerType._def.checks || !def.innerType._def.checks.length)) {\n if (refs.target === \"openApi3\") {\n return {\n type: primitiveMappings[def.innerType._def.typeName],\n nullable: true,\n };\n }\n return {\n type: [\n primitiveMappings[def.innerType._def.typeName],\n \"null\",\n ],\n };\n }\n if (refs.target === \"openApi3\") {\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath],\n });\n if (base && \"$ref\" in base)\n return { allOf: [base], nullable: true };\n return base && { ...base, nullable: true };\n }\n const base = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"0\"],\n });\n return base && { anyOf: [base, { type: \"null\" }] };\n}\n",
|
|
138
|
+
"import { addErrorMessage, setResponseValueAndErrors, } from \"../errorMessages.js\";\nexport function parseNumberDef(def, refs) {\n const res = {\n type: \"number\",\n };\n if (!def.checks)\n return res;\n for (const check of def.checks) {\n switch (check.kind) {\n case \"int\":\n res.type = \"integer\";\n addErrorMessage(res, \"type\", check.message, refs);\n break;\n case \"min\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMinimum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMinimum = true;\n }\n setResponseValueAndErrors(res, \"minimum\", check.value, check.message, refs);\n }\n break;\n case \"max\":\n if (refs.target === \"jsonSchema7\") {\n if (check.inclusive) {\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n else {\n setResponseValueAndErrors(res, \"exclusiveMaximum\", check.value, check.message, refs);\n }\n }\n else {\n if (!check.inclusive) {\n res.exclusiveMaximum = true;\n }\n setResponseValueAndErrors(res, \"maximum\", check.value, check.message, refs);\n }\n break;\n case \"multipleOf\":\n setResponseValueAndErrors(res, \"multipleOf\", check.value, check.message, refs);\n break;\n }\n }\n return res;\n}\n",
|
|
139
|
+
"import { parseDef } from \"../parseDef.js\";\nexport function parseObjectDef(def, refs) {\n const forceOptionalIntoNullable = refs.target === \"openAi\";\n const result = {\n type: \"object\",\n properties: {},\n };\n const required = [];\n const shape = def.shape();\n for (const propName in shape) {\n let propDef = shape[propName];\n if (propDef === undefined || propDef._def === undefined) {\n continue;\n }\n let propOptional = safeIsOptional(propDef);\n if (propOptional && forceOptionalIntoNullable) {\n if (propDef._def.typeName === \"ZodOptional\") {\n propDef = propDef._def.innerType;\n }\n if (!propDef.isNullable()) {\n propDef = propDef.nullable();\n }\n propOptional = false;\n }\n const parsedDef = parseDef(propDef._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"properties\", propName],\n propertyPath: [...refs.currentPath, \"properties\", propName],\n });\n if (parsedDef === undefined) {\n continue;\n }\n result.properties[propName] = parsedDef;\n if (!propOptional) {\n required.push(propName);\n }\n }\n if (required.length) {\n result.required = required;\n }\n const additionalProperties = decideAdditionalProperties(def, refs);\n if (additionalProperties !== undefined) {\n result.additionalProperties = additionalProperties;\n }\n return result;\n}\nfunction decideAdditionalProperties(def, refs) {\n if (def.catchall._def.typeName !== \"ZodNever\") {\n return parseDef(def.catchall._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalProperties\"],\n });\n }\n switch (def.unknownKeys) {\n case \"passthrough\":\n return refs.allowedAdditionalProperties;\n case \"strict\":\n return refs.rejectedAdditionalProperties;\n case \"strip\":\n return refs.removeAdditionalStrategy === \"strict\"\n ? refs.allowedAdditionalProperties\n : refs.rejectedAdditionalProperties;\n }\n}\nfunction safeIsOptional(schema) {\n try {\n return schema.isOptional();\n }\n catch {\n return true;\n }\n}\n",
|
|
140
|
+
"import { parseDef } from \"../parseDef.js\";\nimport { parseAnyDef } from \"./any.js\";\nexport const parseOptionalDef = (def, refs) => {\n if (refs.currentPath.toString() === refs.propertyPath?.toString()) {\n return parseDef(def.innerType._def, refs);\n }\n const innerSchema = parseDef(def.innerType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"anyOf\", \"1\"],\n });\n return innerSchema\n ? {\n anyOf: [\n {\n not: parseAnyDef(refs),\n },\n innerSchema,\n ],\n }\n : parseAnyDef(refs);\n};\n",
|
|
141
|
+
"import { parseDef } from \"../parseDef.js\";\nexport const parsePipelineDef = (def, refs) => {\n if (refs.pipeStrategy === \"input\") {\n return parseDef(def.in._def, refs);\n }\n else if (refs.pipeStrategy === \"output\") {\n return parseDef(def.out._def, refs);\n }\n const a = parseDef(def.in._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", \"0\"],\n });\n const b = parseDef(def.out._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"allOf\", a ? \"1\" : \"0\"],\n });\n return {\n allOf: [a, b].filter((x) => x !== undefined),\n };\n};\n",
|
|
142
|
+
"import { parseDef } from \"../parseDef.js\";\nexport function parsePromiseDef(def, refs) {\n return parseDef(def.type._def, refs);\n}\n",
|
|
143
|
+
"import { setResponseValueAndErrors } from \"../errorMessages.js\";\nimport { parseDef } from \"../parseDef.js\";\nexport function parseSetDef(def, refs) {\n const items = parseDef(def.valueType._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\"],\n });\n const schema = {\n type: \"array\",\n uniqueItems: true,\n items,\n };\n if (def.minSize) {\n setResponseValueAndErrors(schema, \"minItems\", def.minSize.value, def.minSize.message, refs);\n }\n if (def.maxSize) {\n setResponseValueAndErrors(schema, \"maxItems\", def.maxSize.value, def.maxSize.message, refs);\n }\n return schema;\n}\n",
|
|
144
|
+
"import { parseDef } from \"../parseDef.js\";\nexport function parseTupleDef(def, refs) {\n if (def.rest) {\n return {\n type: \"array\",\n minItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n additionalItems: parseDef(def.rest._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"additionalItems\"],\n }),\n };\n }\n else {\n return {\n type: \"array\",\n minItems: def.items.length,\n maxItems: def.items.length,\n items: def.items\n .map((x, i) => parseDef(x._def, {\n ...refs,\n currentPath: [...refs.currentPath, \"items\", `${i}`],\n }))\n .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []),\n };\n }\n}\n",
|
|
145
|
+
"import { parseAnyDef } from \"./any.js\";\nexport function parseUndefinedDef(refs) {\n return {\n not: parseAnyDef(refs),\n };\n}\n",
|
|
146
|
+
"import { parseAnyDef } from \"./any.js\";\nexport function parseUnknownDef(refs) {\n return parseAnyDef(refs);\n}\n",
|
|
147
|
+
"import { parseDef } from \"../parseDef.js\";\nexport const parseReadonlyDef = (def, refs) => {\n return parseDef(def.innerType._def, refs);\n};\n",
|
|
148
|
+
"import { ZodFirstPartyTypeKind } from \"zod/v3\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nimport { parseArrayDef } from \"./parsers/array.js\";\nimport { parseBigintDef } from \"./parsers/bigint.js\";\nimport { parseBooleanDef } from \"./parsers/boolean.js\";\nimport { parseBrandedDef } from \"./parsers/branded.js\";\nimport { parseCatchDef } from \"./parsers/catch.js\";\nimport { parseDateDef } from \"./parsers/date.js\";\nimport { parseDefaultDef } from \"./parsers/default.js\";\nimport { parseEffectsDef } from \"./parsers/effects.js\";\nimport { parseEnumDef } from \"./parsers/enum.js\";\nimport { parseIntersectionDef } from \"./parsers/intersection.js\";\nimport { parseLiteralDef } from \"./parsers/literal.js\";\nimport { parseMapDef } from \"./parsers/map.js\";\nimport { parseNativeEnumDef } from \"./parsers/nativeEnum.js\";\nimport { parseNeverDef } from \"./parsers/never.js\";\nimport { parseNullDef } from \"./parsers/null.js\";\nimport { parseNullableDef } from \"./parsers/nullable.js\";\nimport { parseNumberDef } from \"./parsers/number.js\";\nimport { parseObjectDef } from \"./parsers/object.js\";\nimport { parseOptionalDef } from \"./parsers/optional.js\";\nimport { parsePipelineDef } from \"./parsers/pipeline.js\";\nimport { parsePromiseDef } from \"./parsers/promise.js\";\nimport { parseRecordDef } from \"./parsers/record.js\";\nimport { parseSetDef } from \"./parsers/set.js\";\nimport { parseStringDef } from \"./parsers/string.js\";\nimport { parseTupleDef } from \"./parsers/tuple.js\";\nimport { parseUndefinedDef } from \"./parsers/undefined.js\";\nimport { parseUnionDef } from \"./parsers/union.js\";\nimport { parseUnknownDef } from \"./parsers/unknown.js\";\nimport { parseReadonlyDef } from \"./parsers/readonly.js\";\nexport const selectParser = (def, typeName, refs) => {\n switch (typeName) {\n case ZodFirstPartyTypeKind.ZodString:\n return parseStringDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNumber:\n return parseNumberDef(def, refs);\n case ZodFirstPartyTypeKind.ZodObject:\n return parseObjectDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBigInt:\n return parseBigintDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBoolean:\n return parseBooleanDef();\n case ZodFirstPartyTypeKind.ZodDate:\n return parseDateDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUndefined:\n return parseUndefinedDef(refs);\n case ZodFirstPartyTypeKind.ZodNull:\n return parseNullDef(refs);\n case ZodFirstPartyTypeKind.ZodArray:\n return parseArrayDef(def, refs);\n case ZodFirstPartyTypeKind.ZodUnion:\n case ZodFirstPartyTypeKind.ZodDiscriminatedUnion:\n return parseUnionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodIntersection:\n return parseIntersectionDef(def, refs);\n case ZodFirstPartyTypeKind.ZodTuple:\n return parseTupleDef(def, refs);\n case ZodFirstPartyTypeKind.ZodRecord:\n return parseRecordDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLiteral:\n return parseLiteralDef(def, refs);\n case ZodFirstPartyTypeKind.ZodEnum:\n return parseEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNativeEnum:\n return parseNativeEnumDef(def);\n case ZodFirstPartyTypeKind.ZodNullable:\n return parseNullableDef(def, refs);\n case ZodFirstPartyTypeKind.ZodOptional:\n return parseOptionalDef(def, refs);\n case ZodFirstPartyTypeKind.ZodMap:\n return parseMapDef(def, refs);\n case ZodFirstPartyTypeKind.ZodSet:\n return parseSetDef(def, refs);\n case ZodFirstPartyTypeKind.ZodLazy:\n return () => def.getter()._def;\n case ZodFirstPartyTypeKind.ZodPromise:\n return parsePromiseDef(def, refs);\n case ZodFirstPartyTypeKind.ZodNaN:\n case ZodFirstPartyTypeKind.ZodNever:\n return parseNeverDef(refs);\n case ZodFirstPartyTypeKind.ZodEffects:\n return parseEffectsDef(def, refs);\n case ZodFirstPartyTypeKind.ZodAny:\n return parseAnyDef(refs);\n case ZodFirstPartyTypeKind.ZodUnknown:\n return parseUnknownDef(refs);\n case ZodFirstPartyTypeKind.ZodDefault:\n return parseDefaultDef(def, refs);\n case ZodFirstPartyTypeKind.ZodBranded:\n return parseBrandedDef(def, refs);\n case ZodFirstPartyTypeKind.ZodReadonly:\n return parseReadonlyDef(def, refs);\n case ZodFirstPartyTypeKind.ZodCatch:\n return parseCatchDef(def, refs);\n case ZodFirstPartyTypeKind.ZodPipeline:\n return parsePipelineDef(def, refs);\n case ZodFirstPartyTypeKind.ZodFunction:\n case ZodFirstPartyTypeKind.ZodVoid:\n case ZodFirstPartyTypeKind.ZodSymbol:\n return undefined;\n default:\n return ((_) => undefined)(typeName);\n }\n};\n",
|
|
149
|
+
"import { ignoreOverride } from \"./Options.js\";\nimport { selectParser } from \"./selectParser.js\";\nimport { getRelativePath } from \"./getRelativePath.js\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nexport function parseDef(def, refs, forceResolution = false) {\n const seenItem = refs.seen.get(def);\n if (refs.override) {\n const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);\n if (overrideResult !== ignoreOverride) {\n return overrideResult;\n }\n }\n if (seenItem && !forceResolution) {\n const seenSchema = get$ref(seenItem, refs);\n if (seenSchema !== undefined) {\n return seenSchema;\n }\n }\n const newItem = { def, path: refs.currentPath, jsonSchema: undefined };\n refs.seen.set(def, newItem);\n const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);\n // If the return was a function, then the inner definition needs to be extracted before a call to parseDef (recursive)\n const jsonSchema = typeof jsonSchemaOrGetter === \"function\"\n ? parseDef(jsonSchemaOrGetter(), refs)\n : jsonSchemaOrGetter;\n if (jsonSchema) {\n addMeta(def, refs, jsonSchema);\n }\n if (refs.postProcess) {\n const postProcessResult = refs.postProcess(jsonSchema, def, refs);\n newItem.jsonSchema = jsonSchema;\n return postProcessResult;\n }\n newItem.jsonSchema = jsonSchema;\n return jsonSchema;\n}\nconst get$ref = (item, refs) => {\n switch (refs.$refStrategy) {\n case \"root\":\n return { $ref: item.path.join(\"/\") };\n case \"relative\":\n return { $ref: getRelativePath(refs.currentPath, item.path) };\n case \"none\":\n case \"seen\": {\n if (item.path.length < refs.currentPath.length &&\n item.path.every((value, index) => refs.currentPath[index] === value)) {\n console.warn(`Recursive reference detected at ${refs.currentPath.join(\"/\")}! Defaulting to any`);\n return parseAnyDef(refs);\n }\n return refs.$refStrategy === \"seen\" ? parseAnyDef(refs) : undefined;\n }\n }\n};\nconst addMeta = (def, refs, jsonSchema) => {\n if (def.description) {\n jsonSchema.description = def.description;\n if (refs.markdownDescription) {\n jsonSchema.markdownDescription = def.description;\n }\n }\n return jsonSchema;\n};\n",
|
|
150
|
+
"import { parseDef } from \"./parseDef.js\";\nimport { getRefs } from \"./Refs.js\";\nimport { parseAnyDef } from \"./parsers/any.js\";\nconst zodToJsonSchema = (schema, options) => {\n const refs = getRefs(options);\n let definitions = typeof options === \"object\" && options.definitions\n ? Object.entries(options.definitions).reduce((acc, [name, schema]) => ({\n ...acc,\n [name]: parseDef(schema._def, {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }, true) ?? parseAnyDef(refs),\n }), {})\n : undefined;\n const name = typeof options === \"string\"\n ? options\n : options?.nameStrategy === \"title\"\n ? undefined\n : options?.name;\n const main = parseDef(schema._def, name === undefined\n ? refs\n : {\n ...refs,\n currentPath: [...refs.basePath, refs.definitionPath, name],\n }, false) ?? parseAnyDef(refs);\n const title = typeof options === \"object\" &&\n options.name !== undefined &&\n options.nameStrategy === \"title\"\n ? options.name\n : undefined;\n if (title !== undefined) {\n main.title = title;\n }\n if (refs.flags.hasReferencedOpenAiAnyType) {\n if (!definitions) {\n definitions = {};\n }\n if (!definitions[refs.openAiAnyTypeName]) {\n definitions[refs.openAiAnyTypeName] = {\n // Skipping \"object\" as no properties can be defined and additionalProperties must be \"false\"\n type: [\"string\", \"number\", \"integer\", \"boolean\", \"array\", \"null\"],\n items: {\n $ref: refs.$refStrategy === \"relative\"\n ? \"1\"\n : [\n ...refs.basePath,\n refs.definitionPath,\n refs.openAiAnyTypeName,\n ].join(\"/\"),\n },\n };\n }\n }\n const combined = name === undefined\n ? definitions\n ? {\n ...main,\n [refs.definitionPath]: definitions,\n }\n : main\n : {\n $ref: [\n ...(refs.$refStrategy === \"relative\" ? [] : refs.basePath),\n refs.definitionPath,\n name,\n ].join(\"/\"),\n [refs.definitionPath]: {\n ...definitions,\n [name]: main,\n },\n };\n if (refs.target === \"jsonSchema7\") {\n combined.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (refs.target === \"jsonSchema2019-09\" || refs.target === \"openAi\") {\n combined.$schema = \"https://json-schema.org/draft/2019-09/schema#\";\n }\n if (refs.target === \"openAi\" &&\n (\"anyOf\" in combined ||\n \"oneOf\" in combined ||\n \"allOf\" in combined ||\n (\"type\" in combined && Array.isArray(combined.type)))) {\n console.warn(\"Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.\");\n }\n return combined;\n};\nexport { zodToJsonSchema };\n",
|
|
151
|
+
"/**\n * roy task tool family (Task #4286).\n *\n * The tools are **not re-implemented** — every definition is produced by\n * roy-agent's own factories, imported from the published package:\n *\n * import { createTaskTool, … } from \"@ai-setting/roy-agent-core/env/task/tools\"\n * import { createOperationTool, … } from \"@ai-setting/roy-agent-core/env/task/tools/operation\"\n *\n * So the agent sees roy's exact tool names, descriptions (including the\n * \"CALL task_tree(depth=1) BEFORE THIS TOOL\" rule), parameter schemas and\n * validation semantics. This module only translates the result into OpenCode's\n * plugin-tool contract:\n *\n * { name, description, input, execute, options: { codemode: false } }\n * execute → { content: string, metadata? } (Tool.Result)\n *\n * Both shapes were derived from the opencode 2.0.30 source (`packages/schema/\n * src/tool.ts`, `packages/core/src/tool/runtime.ts`,\n * `packages/core/src/tool.ts:237`) and confirmed end-to-end:\n *\n * - `Tool.Info.input` is the *input schema* field (not `parameters`), so roy's\n * zod schema is converted to a JSON Schema document (opencode renders it to\n * the model and validates input with it).\n * - `Tool.Result` has NO `output` unless a matching `output` schema is\n * declared; returning `{output}` without one makes opencode die with\n * \"Tool result declared output without an output schema\", and returning a\n * bare string dies earlier inside the Code-Mode bridge with\n * `TypeError: a is not an Object`. The supported shape is `{content}`.\n * - `options.codemode === false` registers the tool as a **direct**\n * first-class tool (`packages/core/src/tool.ts:237`) instead of only\n * surfacing it inside the Code-Mode sandbox.\n */\n\nimport { createTaskTool, getTaskTool, listTasksTool, searchTasksTool, treeTasksTool, updateTaskTool, completeTaskTool } from \"@ai-setting/roy-agent-core/env/task/tools\";\nimport {\n createOperationTool,\n listOperationsTool,\n} from \"@ai-setting/roy-agent-core/env/task/tools/operation\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\nimport type { TaskStore } from \"@roy-task-plugin/shared\";\nimport {\n createRoyTaskFacade,\n type RoyFacadeOptions,\n type TaskComponentFacade,\n} from \"./facade.js\";\n\n/** The task lifecycle exposed to the `roy` primary agent. */\nexport const ROY_TASK_TOOL_NAMES = [\n \"task_create\",\n \"task_tree\",\n \"task_get\",\n \"task_list\",\n \"task_search\",\n \"task_update\",\n \"task_complete\",\n \"task_operation_create\",\n \"task_operation_list\",\n] as const;\n\nexport type RoyTaskToolName = (typeof ROY_TASK_TOOL_NAMES)[number];\n\n/**\n * opencode `Tool.Result` — **must not** carry `output` unless the tool also\n * declares a matching `output` schema.\n *\n * - `content` is normalised by opencode into text parts (`normalizeContent`)\n * - a bare string return breaks opencode's Code-Mode bridge\n * (`TypeError: a is not an Object` — the T21 regression)\n */\nexport interface OpenCodeToolResult {\n content?: string;\n metadata?: Record<string, unknown>;\n}\n\n/** opencode `Tool.Info` subset understood by `ctx.tool.transform(draft.add)`. */\nexport interface OpenCodeToolDefinition {\n name: string;\n description: string;\n /** Input schema (JSON Schema document) — opencode's `Tool.Info.input`. */\n input: Record<string, unknown>;\n execute: (args: unknown, context?: OpenCodeToolContext) => Promise<OpenCodeToolResult>;\n /** `codemode: false` ⇒ first-class direct tool, not Code-Mode-only. */\n options: { codemode: false };\n}\n\nexport interface OpenCodeToolContext {\n sessionID?: string;\n messageID?: string;\n agent?: string;\n directory?: string;\n worktree?: string;\n}\n\n/** roy factory signature: (component) => { name, description, parameters, execute }. */\ntype RoyToolFactory = (component: unknown) => {\n name: string;\n description: string;\n parameters: unknown;\n execute: (args: unknown, ctx: Record<string, unknown>) => Promise<{\n success: boolean;\n output?: unknown;\n error?: string;\n }>;\n};\n\n/** Factories we expose, in lifecycle order. */\nconst FACTORIES: ReadonlyArray<RoyToolFactory> = [\n createTaskTool as unknown as RoyToolFactory,\n treeTasksTool as unknown as RoyToolFactory,\n getTaskTool as unknown as RoyToolFactory,\n listTasksTool as unknown as RoyToolFactory,\n searchTasksTool as unknown as RoyToolFactory,\n updateTaskTool as unknown as RoyToolFactory,\n completeTaskTool as unknown as RoyToolFactory,\n createOperationTool as unknown as RoyToolFactory,\n listOperationsTool as unknown as RoyToolFactory,\n];\n\n/**\n * roy's schemas are zod (v3) — either a `ZodObject` or a `ZodEffects` wrapper\n * (`task_operation_create` / `task_operation_list` use preprocess + transform).\n *\n * opencode's `Tool.Info.input` accepts an Effect schema, a StandardSchema or a\n * **plain JSON Schema document**. zod v3 is a StandardSchema *without* the\n * StandardJSONSchema extension, so handing opencode the zod object directly\n * makes `standardJsonSchema()` throw\n * (`Schema vendor \"zod\" does not support JSON Schema conversion`). We therefore\n * convert to a JSON Schema document ourselves.\n *\n * Fault-isolated: any conversion failure degrades to `{}` (the tool then simply\n * advertises no parameters) rather than breaking plugin loading.\n */\nexport function toOpenCodeInputSchema(parameters: unknown): Record<string, unknown> {\n const p = parameters as { shape?: unknown; _def?: { schema?: unknown } } | null;\n if (!p) return {};\n // Unwrap ZodEffects → inner schema for a cleaner document; effectStrategy also\n // handles it, this just avoids a wrapper layer.\n const target = p.shape ? p : (p._def?.schema ?? p);\n try {\n const doc = zodToJsonSchema(target as never, {\n target: \"jsonSchema7\",\n $refStrategy: \"none\",\n effectStrategy: \"input\",\n }) as Record<string, unknown>;\n const { $schema: _ignored, ...rest } = doc;\n return rest;\n } catch {\n return {};\n }\n}\n\n/**\n * Build the opencode tool family bound to a plugin `TaskStore`.\n *\n * @param store the plugin's existing store (local SQLite / remote HTTP)\n * @param opts session id + owner stamped on created tasks\n */\nexport function createRoyTaskTools(\n store: TaskStore,\n opts: RoyFacadeOptions = {},\n): OpenCodeToolDefinition[] {\n const facade: TaskComponentFacade = createRoyTaskFacade(store, opts);\n\n return FACTORIES.map((factory) => {\n const royTool = factory(facade);\n return {\n name: royTool.name,\n description: royTool.description,\n input: toOpenCodeInputSchema(royTool.parameters),\n options: { codemode: false as const },\n execute: async (args: unknown, context?: OpenCodeToolContext): Promise<OpenCodeToolResult> => {\n const royCtx: Record<string, unknown> = {\n session_id: context?.sessionID ?? opts.sessionId ?? \"unknown\",\n workdir: context?.directory,\n };\n try {\n const result = await royTool.execute(args ?? {}, royCtx);\n const output =\n typeof result.output === \"string\" ? result.output : JSON.stringify(result.output ?? \"\");\n return {\n content: result.success ? output : `ERROR: ${result.error ?? \"unknown error\"}`,\n metadata: { tool: royTool.name, ok: result.success },\n };\n } catch (error) {\n // roy validates some params outside its own try/catch (e.g. zod\n // `.parse` in task_get). A plugin tool must never throw into the\n // session — surface the failure inside `content` instead.\n const message = error instanceof Error ? error.message : String(error);\n return { content: `ERROR: ${message}`, metadata: { tool: royTool.name, ok: false } };\n }\n },\n };\n });\n}\n\n/** Convenience: tool name → definition map. */\nexport function createRoyTaskToolMap(\n store: TaskStore,\n opts: RoyFacadeOptions = {},\n): Record<string, OpenCodeToolDefinition> {\n return Object.fromEntries(createRoyTaskTools(store, opts).map((t) => [t.name, t]));\n}\n",
|
|
152
|
+
"/**\n * roy integration for the OpenCode plugin (Task #4286).\n *\n * Registers, onto the live OpenCode context:\n * 1. the `roy` **primary agent** → `ctx.agent.transform` + draft.update\n * 2. the roy **task tool family** (9 tools) → `ctx.tool.transform` + draft.add\n *\n * Design rules (mirroring omo's `safeHook` discipline):\n * - every domain is probed: if OpenCode doesn't expose it, we skip, don't throw\n * - every registration is wrapped in try/catch and reported in `errors`\n * - the whole thing is opt-out via the plugin option `royAgent: false`\n *\n * Nothing here touches storage directly: the tools bind to the plugin's\n * existing `TaskStore` (local SQLite / remote HTTP).\n */\n\nimport type { TaskStore } from \"@roy-task-plugin/shared\";\nimport { applyRoyAgent, ROY_AGENT_ID, type AgentDraftLike } from \"@roy-task-plugin/agent\";\nimport { createRoyTaskTools, type OpenCodeToolDefinition } from \"@roy-task-plugin/roy-bridge\";\n\nexport interface RoyIntegrationOptions {\n /** The plugin's existing store — the single persistence for roy tasks. */\n store: TaskStore;\n /** `false` = skip both registrations (plugin option `royAgent: false`). */\n enabled?: boolean;\n /** Owner recorded on tasks created through the tools (default \"roy\"). */\n agent?: string;\n /** Fallback session id when OpenCode does not supply one. */\n sessionId?: string;\n}\n\nexport interface RoyIntegrationResult {\n enabled: boolean;\n agentId: string | null;\n toolNames: string[];\n errors: string[];\n disposers: Array<() => Promise<void>>;\n}\n\n/** Structural shape of the OpenCode plugin context (compat subset). */\ninterface PluginContextLike {\n agent?: { transform?: (cb: (draft: AgentDraftLike) => void | Promise<void>) => Promise<unknown> };\n tool?: { transform?: (cb: (draft: ToolDraftLike) => void | Promise<void>) => Promise<unknown> };\n}\n\ninterface ToolDraftLike {\n add(def: unknown): void;\n}\n\nfunction collectDisposer(registration: unknown, disposers: Array<() => Promise<void>>): void {\n const dispose = (registration as { dispose?: unknown } | undefined)?.dispose;\n if (typeof dispose === \"function\") {\n disposers.push(dispose as () => Promise<void>);\n }\n}\n\n/**\n * Register the roy agent + task tools on an OpenCode plugin context.\n *\n * Never throws: failures are captured in `result.errors` so a broken roy\n * registration can't take down the user's session.\n */\nexport async function registerRoyIntegration(\n ctx: unknown,\n options: RoyIntegrationOptions,\n): Promise<RoyIntegrationResult> {\n const enabled = options.enabled !== false;\n const result: RoyIntegrationResult = {\n enabled,\n agentId: null,\n toolNames: [],\n errors: [],\n disposers: [],\n };\n if (!enabled) return result;\n\n const context = (ctx ?? {}) as PluginContextLike;\n const agentName = options.agent ?? ROY_AGENT_ID;\n\n // ---- 1. the `roy` primary agent -----------------------------------------\n if (typeof context.agent?.transform === \"function\") {\n try {\n const registration = await context.agent.transform((draft) => {\n applyRoyAgent(draft);\n });\n collectDisposer(registration, result.disposers);\n result.agentId = agentName;\n } catch (error) {\n result.errors.push(`roy agent registration failed: ${messageOf(error)}`);\n }\n } else {\n result.errors.push(\"ctx.agent.transform unavailable — roy agent not registered\");\n }\n\n // ---- 2. the roy task tool family ----------------------------------------\n let tools: OpenCodeToolDefinition[] = [];\n try {\n tools = createRoyTaskTools(options.store, {\n agent: agentName,\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n });\n } catch (error) {\n result.errors.push(`roy tool construction failed: ${messageOf(error)}`);\n return result;\n }\n\n if (typeof context.tool?.transform === \"function\") {\n try {\n const registration = await context.tool.transform((draft) => {\n for (const tool of tools) draft.add(tool);\n });\n collectDisposer(registration, result.disposers);\n result.toolNames = tools.map((t) => t.name);\n } catch (error) {\n result.errors.push(`roy tool registration failed: ${messageOf(error)}`);\n }\n } else {\n result.errors.push(\"ctx.tool.transform unavailable — roy task tools not registered\");\n }\n\n return result;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n",
|
|
153
|
+
"/**\n * LocalTaskStore — wraps the service-side SqliteTaskStore, defaulting to\n * ~/.roy-task-plugin/tasks.db. This is the in-process fallback when the user\n * does NOT run the bundled service.\n *\n * The plugin imports this directly; in remote mode, see remote.ts.\n */\n\nimport { join } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { mkdirSync } from \"node:fs\";\nimport { SqliteTaskStore } from \"../../../service/src/store/sqlite.js\";\n\nconst DEFAULT_DIR = join(homedir(), \".roy-task-plugin\");\nconst DEFAULT_DB = join(DEFAULT_DIR, \"tasks.db\");\n\nexport class LocalTaskStore {\n private inner: SqliteTaskStore;\n private constructor(inner: SqliteTaskStore) {\n this.inner = inner;\n }\n static async create(dbPath?: string): Promise<LocalTaskStore> {\n const path = dbPath ?? DEFAULT_DB;\n if (path !== \":memory:\") {\n mkdirSync(join(path, \"..\"), { recursive: true });\n }\n const inner = await SqliteTaskStore.create(path);\n return new LocalTaskStore(inner);\n }\n // Delegate everything to the inner store — same TaskStore interface.\n createTask(...args: Parameters<SqliteTaskStore[\"createTask\"]>) {\n return this.inner.createTask(...args);\n }\n getTask(...args: Parameters<SqliteTaskStore[\"getTask\"]>) {\n return this.inner.getTask(...args);\n }\n updateTask(...args: Parameters<SqliteTaskStore[\"updateTask\"]>) {\n return this.inner.updateTask(...args);\n }\n deleteTask(...args: Parameters<SqliteTaskStore[\"deleteTask\"]>) {\n return this.inner.deleteTask(...args);\n }\n listTasks(...args: Parameters<SqliteTaskStore[\"listTasks\"]>) {\n return this.inner.listTasks(...args);\n }\n appendOperation(...args: Parameters<SqliteTaskStore[\"appendOperation\"]>) {\n return this.inner.appendOperation(...args);\n }\n listOperations(...args: Parameters<SqliteTaskStore[\"listOperations\"]>) {\n return this.inner.listOperations(...args);\n }\n verifyChain() {\n return this.inner.verifyChain();\n }\n sendBounty(...args: Parameters<SqliteTaskStore[\"sendBounty\"]>) {\n return this.inner.sendBounty(...args);\n }\n claimBounty(...args: Parameters<SqliteTaskStore[\"claimBounty\"]>) {\n return this.inner.claimBounty(...args);\n }\n completeBounty(...args: Parameters<SqliteTaskStore[\"completeBounty\"]>) {\n return this.inner.completeBounty(...args);\n }\n listBounties(...args: Parameters<SqliteTaskStore[\"listBounties\"]>) {\n return this.inner.listBounties(...args);\n }\n async close(): Promise<void> {\n await this.inner.close();\n }\n}",
|
|
154
|
+
"/**\n * SQLite-backed TaskStore — used by the service package.\n *\n * Implements `TaskStore` from @roy-task-plugin/shared. Backed by Bun's\n * built-in `bun:sqlite` (no native compile step). The schema is intentionally\n * portable so a future Postgres adapter can be added without changing the\n * interface.\n *\n * RED-03 / RED-04 / RED-11 / RED-15: covered by tests/store/sqlite.test.ts.\n */\n\nimport { Database } from \"bun:sqlite\";\nimport {\n type Bounty,\n type CreateTaskInput,\n type Operation,\n type Task,\n type TaskFilter,\n type TaskListResult,\n type TaskStatus,\n type TaskStore,\n type RoySidecar,\n type UpdateTaskInput,\n} from \"@roy-task-plugin/shared\";\nimport { createHash, randomUUID } from \"node:crypto\";\n\nconst SCHEMA = `\nCREATE TABLE IF NOT EXISTS tasks (\n id TEXT PRIMARY KEY,\n title TEXT NOT NULL,\n description TEXT,\n status TEXT NOT NULL DEFAULT 'pending',\n priority INTEGER NOT NULL DEFAULT 3,\n owner TEXT,\n tags TEXT,\n parent_id TEXT,\n blocked_by TEXT NOT NULL DEFAULT '[]',\n retry_of TEXT,\n retry_count INTEGER NOT NULL DEFAULT 0,\n session_id TEXT,\n roy TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS tasks_parent_idx ON tasks(parent_id);\nCREATE INDEX IF NOT EXISTS tasks_status_idx ON tasks(status);\nCREATE INDEX IF NOT EXISTS tasks_session_idx ON tasks(session_id);\n\nCREATE TABLE IF NOT EXISTS task_idempotency (\n idempotency_key TEXT PRIMARY KEY,\n task_id TEXT NOT NULL,\n created_at TEXT NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS operations (\n id TEXT PRIMARY KEY,\n task_id TEXT,\n type TEXT NOT NULL,\n data TEXT NOT NULL,\n created_at TEXT NOT NULL,\n prev_hash TEXT NOT NULL,\n hash TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS ops_task_idx ON operations(task_id);\nCREATE INDEX IF NOT EXISTS ops_type_idx ON operations(type);\nCREATE INDEX IF NOT EXISTS ops_created_idx ON operations(created_at);\n\nCREATE TABLE IF NOT EXISTS bounties (\n id TEXT PRIMARY KEY,\n subject TEXT NOT NULL,\n body TEXT NOT NULL,\n from_ TEXT NOT NULL,\n to_ TEXT NOT NULL DEFAULT '*',\n status TEXT NOT NULL DEFAULT 'open',\n claimed_by TEXT,\n task_id TEXT,\n created_at TEXT NOT NULL,\n claimed_at TEXT,\n done_at TEXT\n);\nCREATE INDEX IF NOT EXISTS bounties_status_idx ON bounties(status);\n`;\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\n\nfunction genId(): string {\n return randomUUID();\n}\n\nfunction sha256Hex(s: string): string {\n return createHash(\"sha256\").update(s).digest(\"hex\");\n}\n\nfunction canonicalize(data: unknown): string {\n return JSON.stringify(data, Object.keys(data as object).sort());\n}\n\nfunction computeOpHash(input: {\n id: string;\n type: string;\n data: Record<string, unknown>;\n prev_hash: string;\n created_at: string;\n}): string {\n const payload = JSON.stringify({\n id: input.id,\n type: input.type,\n data: input.data,\n prev_hash: input.prev_hash,\n created_at: input.created_at,\n });\n return sha256Hex(payload);\n}\n\ninterface TaskRow {\n id: string;\n title: string;\n description: string | null;\n status: TaskStatus;\n priority: number;\n owner: string | null;\n tags: string | null;\n parent_id: string | null;\n blocked_by: string;\n retry_of: string | null;\n retry_count: number;\n session_id: string | null;\n roy: string | null;\n /** sqlite rowid — exposed to callers as `Task.num` (Task #4286). */\n num?: number;\n created_at: string;\n updated_at: string;\n}\n\ninterface OpRow {\n id: string;\n task_id: string | null;\n type: string;\n data: string;\n created_at: string;\n prev_hash: string;\n hash: string;\n /** sqlite rowid — exposed to callers as `Operation.num` (Task #4286). */\n num?: number;\n}\n\ninterface BountyRow {\n id: string;\n subject: string;\n body: string;\n from_: string;\n to_: string;\n status: \"open\" | \"claimed\" | \"done\";\n claimed_by: string | null;\n task_id: string | null;\n created_at: string;\n claimed_at: string | null;\n done_at: string | null;\n}\n\nfunction rowToTask(row: TaskRow): Task {\n return {\n id: row.id,\n num: row.num,\n title: row.title,\n description: row.description ?? undefined,\n status: row.status,\n priority: row.priority,\n owner: row.owner ?? undefined,\n tags: row.tags ?? undefined,\n parent_id: row.parent_id,\n blocked_by: JSON.parse(row.blocked_by) as string[],\n retry_of: row.retry_of,\n retry_count: row.retry_count,\n session_id: row.session_id,\n roy: parseRoy(row.roy),\n created_at: row.created_at,\n updated_at: row.updated_at,\n };\n}\n\n/** Parse the `roy` sidecar JSON; never throws (corrupt blob → undefined). */\nfunction parseRoy(raw: string | null | undefined): RoySidecar | undefined {\n if (raw === null || raw === undefined || raw === \"\") return undefined;\n try {\n const parsed = JSON.parse(raw) as unknown;\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as RoySidecar;\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Task #4286 — idempotent additive migration for DB files created before the\n * roy sidecar existed. Uses PRAGMA table_info so re-opening is a no-op.\n */\nfunction migrateOnOpen(db: Database): void {\n try {\n const cols = db.query(\"PRAGMA table_info(tasks)\").all() as Array<{ name: string }>;\n const names = new Set(cols.map((c) => c.name));\n if (!names.has(\"roy\")) {\n db.exec(\"ALTER TABLE tasks ADD COLUMN roy TEXT\");\n }\n } catch {\n // best-effort: a failure here must not break store construction\n }\n}\n\nfunction rowToOp(row: OpRow): Operation {\n return {\n id: row.id,\n num: row.num,\n task_id: row.task_id,\n type: row.type,\n data: JSON.parse(row.data) as Record<string, unknown>,\n created_at: row.created_at,\n prev_hash: row.prev_hash,\n hash: row.hash,\n };\n}\n\nfunction rowToBounty(row: BountyRow): Bounty {\n return {\n id: row.id,\n subject: row.subject,\n body: row.body,\n from: row.from_,\n to: row.to_,\n status: row.status,\n claimed_by: row.claimed_by,\n task_id: row.task_id,\n created_at: row.created_at,\n claimed_at: row.claimed_at,\n done_at: row.done_at,\n };\n}\n\nexport class SqliteTaskStore implements TaskStore {\n private db: Database;\n private closedFlag = false;\n\n private constructor(db: Database) {\n this.db = db;\n }\n\n /** Open (or create) a sqlite db at `path` (use \":memory:\" for tests). */\n static async create(path: string): Promise<SqliteTaskStore> {\n const db = new Database(path);\n db.exec(SCHEMA);\n migrateOnOpen(db);\n return new SqliteTaskStore(db);\n }\n\n async close(): Promise<void> {\n if (this.closedFlag) return;\n this.closedFlag = true;\n this.db.close();\n }\n\n // ---- tasks ----\n\n async createTask(\n input: CreateTaskInput,\n idempotency_key?: string,\n ): Promise<Task> {\n if (this.closedFlag) throw new Error(\"store closed\");\n\n // Idempotency dedupe\n if (idempotency_key) {\n const existing = this.db\n .query(\"SELECT task_id FROM task_idempotency WHERE idempotency_key = ?\")\n .get(idempotency_key) as { task_id: string } | null;\n if (existing) {\n const t = await this.getTask(existing.task_id);\n if (t) return t;\n }\n }\n\n const id = genId();\n const now = nowIso();\n const priority = input.priority ?? 3;\n\n this.db\n .query(\n `INSERT INTO tasks (id, title, description, status, priority, owner, tags,\n parent_id, blocked_by, retry_of, retry_count, session_id, roy, created_at, updated_at)\n VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`,\n )\n .run(\n id,\n input.title,\n input.description ?? null,\n priority,\n input.owner ?? null,\n input.tags ?? null,\n input.parent_id ?? null,\n JSON.stringify(input.blocked_by ?? []),\n input.retry_of ?? null,\n input.session_id ?? null,\n input.roy === undefined ? null : JSON.stringify(input.roy),\n now,\n now,\n );\n\n if (idempotency_key) {\n this.db\n .query(\n `INSERT INTO task_idempotency (idempotency_key, task_id, created_at)\n VALUES (?, ?, ?)`,\n )\n .run(idempotency_key, id, now);\n }\n\n // Audit log\n await this.appendOperation({\n task_id: id,\n type: \"task.created\",\n data: { title: input.title, parent_id: input.parent_id ?? null },\n });\n\n const t = await this.getTask(id);\n if (!t) throw new Error(\"internal: task vanished after insert\");\n return t;\n }\n\n async getTask(id: string): Promise<Task | null> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const row = this.db\n .query(\"SELECT rowid AS num, * FROM tasks WHERE id = ?\")\n .get(id) as TaskRow | null;\n return row ? rowToTask(row) : null;\n }\n\n /**\n * Task #4286 — resolve by numeric handle (rowid). O(1).\n * Returns null for unknown / already-deleted handles.\n *\n * KNOWN LIMITATION (cross-validation 2026-10-16, not blocking): `tasks.id` is\n * `TEXT PRIMARY KEY`, so the table is a plain rowid table and SQLite may\n * **reuse** the rowid of a hard-deleted row on a later INSERT. Numeric handles\n * are therefore stable across reads and updates, but not across hard deletes.\n *\n * Mitigations in place: the roy task lifecycle exposes no delete tool (the\n * agent closes work with `task_complete` / `archived`, matching SQLite's\n * \"archive, don't delete\" semantics), and operations are strictly append-only\n * so their handles are monotonic. If a hard-delete-stable numeric id is ever\n * required, add an explicit monotonic `num` column fed by a counter table\n * (`AUTOINCREMENT` cannot be used here: it only applies to\n * `INTEGER PRIMARY KEY`).\n */\n async getTaskByNum(num: number): Promise<Task | null> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const row = this.db\n .query(\"SELECT rowid AS num, * FROM tasks WHERE rowid = ?\")\n .get(num) as TaskRow | null;\n return row ? rowToTask(row) : null;\n }\n\n async updateTask(\n id: string,\n input: UpdateTaskInput,\n ): Promise<Task | null> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const existing = await this.getTask(id);\n if (!existing) return null;\n\n const updates: string[] = [];\n const params: unknown[] = [];\n if (input.title !== undefined) {\n updates.push(\"title = ?\");\n params.push(input.title);\n }\n if (input.description !== undefined) {\n updates.push(\"description = ?\");\n params.push(input.description);\n }\n if (input.status !== undefined) {\n updates.push(\"status = ?\");\n params.push(input.status);\n }\n if (input.priority !== undefined) {\n updates.push(\"priority = ?\");\n params.push(input.priority);\n }\n if (input.owner !== undefined) {\n updates.push(\"owner = ?\");\n params.push(input.owner);\n }\n if (input.tags !== undefined) {\n updates.push(\"tags = ?\");\n params.push(input.tags);\n }\n if (input.blocked_by !== undefined) {\n updates.push(\"blocked_by = ?\");\n params.push(JSON.stringify(input.blocked_by));\n }\n if (input.roy !== undefined) {\n // Shallow-merge with the stored sidecar so partial patches (e.g.\n // `{ progress: 60 }`) do not erase sibling roy fields.\n const merged: RoySidecar = { ...(existing.roy ?? {}), ...input.roy };\n updates.push(\"roy = ?\");\n params.push(JSON.stringify(merged));\n }\n updates.push(\"updated_at = ?\");\n params.push(nowIso());\n params.push(id);\n\n this.db\n .query(`UPDATE tasks SET ${updates.join(\", \")} WHERE id = ?`)\n .run(...params);\n\n if (input.status !== undefined && input.status !== existing.status) {\n await this.appendOperation({\n task_id: id,\n type: \"task.status_changed\",\n data: { from: existing.status, to: input.status },\n });\n } else {\n await this.appendOperation({\n task_id: id,\n type: \"task.updated\",\n data: { keys: Object.keys(input) },\n });\n }\n\n return await this.getTask(id);\n }\n\n async listTasks(filter: TaskFilter = {}): Promise<TaskListResult> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const where: string[] = [];\n const params: unknown[] = [];\n if (filter.status !== undefined) {\n if (Array.isArray(filter.status)) {\n where.push(`status IN (${filter.status.map(() => \"?\").join(\",\")})`);\n params.push(...filter.status);\n } else {\n where.push(\"status = ?\");\n params.push(filter.status);\n }\n }\n if (filter.parent_id !== undefined) {\n if (filter.parent_id === null) {\n where.push(\"parent_id IS NULL\");\n } else {\n where.push(\"parent_id = ?\");\n params.push(filter.parent_id);\n }\n }\n if (filter.session_id !== undefined) {\n where.push(\"session_id = ?\");\n params.push(filter.session_id);\n }\n if (filter.owner !== undefined) {\n where.push(\"owner = ?\");\n params.push(filter.owner);\n }\n if (filter.tags !== undefined) {\n where.push(\"tags LIKE ?\");\n params.push(`%${filter.tags}%`);\n }\n if (filter.search !== undefined) {\n where.push(\"(title LIKE ? OR description LIKE ?)\");\n params.push(`%${filter.search}%`, `%${filter.search}%`);\n }\n\n const limit = filter.limit ?? 100;\n const offset = filter.offset ?? 0;\n const whereSql = where.length ? `WHERE ${where.join(\" AND \")}` : \"\";\n const total = (\n this.db\n .query(`SELECT COUNT(*) AS n FROM tasks ${whereSql}`)\n .get(...params) as { n: number }\n ).n;\n const rows = this.db\n .query(\n `SELECT rowid AS num, * FROM tasks ${whereSql} ORDER BY created_at DESC LIMIT ? OFFSET ?`,\n )\n .all(...params, limit, offset) as TaskRow[];\n return { tasks: rows.map(rowToTask), total };\n }\n\n async deleteTask(id: string): Promise<boolean> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const info = this.db.query(\"DELETE FROM tasks WHERE id = ?\").run(id);\n return info.changes > 0;\n }\n\n /**\n * Task #4286 — re-parent a task (or detach it with null).\n *\n * `parent_id` is deliberately absent from `UpdateTaskInput` (the plugin's\n * business API treats re-parenting as a distinct operation); the roy model\n * needs it, so it gets a dedicated, explicitly-named method.\n */\n async setParentId(id: string, parentId: string | null): Promise<void> {\n if (this.closedFlag) throw new Error(\"store closed\");\n this.db\n .query(\"UPDATE tasks SET parent_id = ?, updated_at = ? WHERE id = ?\")\n .run(parentId, nowIso(), id);\n }\n\n // ---- operations / audit ----\n\n async appendOperation(input: {\n task_id: string | null;\n type: string;\n data: Record<string, unknown>;\n }): Promise<Operation> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const last = this.db\n .query(\"SELECT hash FROM operations ORDER BY rowid DESC LIMIT 1\")\n .get() as { hash: string } | null;\n const prev_hash = last?.hash ?? \"0\".repeat(64);\n const id = genId();\n const created_at = nowIso();\n const hash = computeOpHash({\n id,\n type: input.type,\n data: input.data,\n prev_hash,\n created_at,\n });\n this.db\n .query(\n `INSERT INTO operations (id, task_id, type, data, created_at, prev_hash, hash)\n VALUES (?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(id, input.task_id, input.type, JSON.stringify(input.data), created_at, prev_hash, hash);\n const num = (\n this.db.query(\"SELECT last_insert_rowid() AS n\").get() as { n: number }\n ).n;\n return {\n id,\n num,\n task_id: input.task_id,\n type: input.type,\n data: input.data,\n created_at,\n prev_hash,\n hash,\n };\n }\n\n /** Task #4286 — resolve an operation by numeric handle (rowid). */\n async getOperationByNum(num: number): Promise<Operation | null> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const row = this.db\n .query(\"SELECT rowid AS num, * FROM operations WHERE rowid = ?\")\n .get(num) as OpRow | null;\n return row ? rowToOp(row) : null;\n }\n\n /** Task #4286 — update an operation's payload (used by roy-bridge). */\n async updateOperation(\n num: number,\n patch: { type?: string; data?: Record<string, unknown> },\n ): Promise<Operation | null> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const existing = await this.getOperationByNum(num);\n if (!existing) return null;\n const updates: string[] = [];\n const params: unknown[] = [];\n if (patch.type !== undefined) {\n updates.push(\"type = ?\");\n params.push(patch.type);\n }\n if (patch.data !== undefined) {\n updates.push(\"data = ?\");\n params.push(JSON.stringify(patch.data));\n }\n if (updates.length === 0) return existing;\n params.push(num);\n this.db.query(`UPDATE operations SET ${updates.join(\", \")} WHERE rowid = ?`).run(...params);\n return await this.getOperationByNum(num);\n }\n\n /** Task #4286 — delete an operation by numeric handle. */\n async deleteOperation(num: number): Promise<boolean> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const info = this.db.query(\"DELETE FROM operations WHERE rowid = ?\").run(num);\n return info.changes > 0;\n }\n\n async listOperations(\n filter: { task_id?: string; type?: string; limit?: number; offset?: number } = {},\n ): Promise<{ operations: Operation[]; total: number }> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const where: string[] = [];\n const params: unknown[] = [];\n if (filter.task_id !== undefined) {\n where.push(\"task_id = ?\");\n params.push(filter.task_id);\n }\n if (filter.type !== undefined) {\n where.push(\"type = ?\");\n params.push(filter.type);\n }\n const limit = filter.limit ?? 100;\n const offset = filter.offset ?? 0;\n const whereSql = where.length ? `WHERE ${where.join(\" AND \")}` : \"\";\n const total = (\n this.db\n .query(`SELECT COUNT(*) AS n FROM operations ${whereSql}`)\n .get(...params) as { n: number }\n ).n;\n const rows = this.db\n .query(\n `SELECT rowid AS num, * FROM operations ${whereSql} ORDER BY rowid ASC LIMIT ? OFFSET ?`,\n )\n .all(...params, limit, offset) as OpRow[];\n return { operations: rows.map(rowToOp), total };\n }\n\n async verifyChain(): Promise<boolean> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const rows = this.db\n .query(\"SELECT * FROM operations ORDER BY rowid ASC\")\n .all() as OpRow[];\n let prev = \"0\".repeat(64);\n for (const row of rows) {\n const expected = computeOpHash({\n id: row.id,\n type: row.type,\n data: JSON.parse(row.data) as Record<string, unknown>,\n prev_hash: prev,\n created_at: row.created_at,\n });\n if (row.prev_hash !== prev) return false;\n if (row.hash !== expected) return false;\n prev = row.hash;\n }\n return true;\n }\n\n /** Test-only: tamper with an operation's data field by rowid (1-indexed). */\n async tamperOpForTest(rowid: number, newData: unknown): Promise<void> {\n this.db\n .query(\"UPDATE operations SET data = ? WHERE rowid = ?\")\n .run(JSON.stringify(newData), rowid);\n }\n\n // ---- bounties ----\n\n async sendBounty(input: {\n subject: string;\n body: string;\n from: string;\n to?: string;\n }): Promise<Bounty> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const id = genId();\n const now = nowIso();\n this.db\n .query(\n `INSERT INTO bounties (id, subject, body, from_, status, created_at)\n VALUES (?, ?, ?, ?, 'open', ?)`,\n )\n .run(id, input.subject, input.body, input.from, now);\n await this.appendOperation({\n task_id: null,\n type: \"bounty.sent\",\n data: { bounty_id: id, subject: input.subject, from: input.from },\n });\n const row = this.db.query(\"SELECT * FROM bounties WHERE id = ?\").get(id) as BountyRow;\n return rowToBounty(row);\n }\n\n async claimBounty(agent: string): Promise<Bounty | null> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const row = this.db\n .query(\"SELECT * FROM bounties WHERE status = 'open' ORDER BY created_at ASC LIMIT 1\")\n .get() as BountyRow | null;\n if (!row) return null;\n const now = nowIso();\n this.db\n .query(\n `UPDATE bounties SET status = 'claimed', claimed_by = ?, claimed_at = ? WHERE id = ?`,\n )\n .run(agent, now, row.id);\n await this.appendOperation({\n task_id: null,\n type: \"bounty.claimed\",\n data: { bounty_id: row.id, by: agent },\n });\n const updated = this.db.query(\"SELECT * FROM bounties WHERE id = ?\").get(row.id) as BountyRow;\n return rowToBounty(updated);\n }\n\n async completeBounty(id: string, task_id: string): Promise<Bounty | null> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const now = nowIso();\n const info = this.db\n .query(\n `UPDATE bounties SET status = 'done', task_id = ?, done_at = ?\n WHERE id = ? AND status = 'claimed'`,\n )\n .run(task_id, now, id);\n if (info.changes === 0) return null;\n await this.appendOperation({\n task_id: null,\n type: \"bounty.completed\",\n data: { bounty_id: id, task_id },\n });\n const row = this.db.query(\"SELECT * FROM bounties WHERE id = ?\").get(id) as BountyRow;\n return rowToBounty(row);\n }\n\n async listBounties(\n filter: { status?: Bounty[\"status\"]; to?: string } = {},\n ): Promise<Bounty[]> {\n if (this.closedFlag) throw new Error(\"store closed\");\n const where: string[] = [];\n const params: unknown[] = [];\n if (filter.status !== undefined) {\n where.push(\"status = ?\");\n params.push(filter.status);\n }\n if (filter.to !== undefined) {\n where.push(\"to_ = ?\");\n params.push(filter.to);\n }\n const whereSql = where.length ? `WHERE ${where.join(\" AND \")}` : \"\";\n const rows = this.db\n .query(`SELECT * FROM bounties ${whereSql} ORDER BY created_at DESC`)\n .all(...params) as BountyRow[];\n return rows.map(rowToBounty);\n }\n}\n\n// Workaround to avoid \"unused\" warnings on canonicalize (kept for future use).\nvoid canonicalize;",
|
|
155
|
+
"/**\n * HTTP client — implements TaskStore by talking to the service.\n *\n * Used by the plugin when persistence mode = \"remote\".\n * Errors are wrapped in `ApiError` so callers can distinguish 4xx/5xx.\n *\n * RED-08 / RED-09: idempotency-key dedupe + error propagation.\n */\n\nimport type {\n Bounty,\n CreateTaskInput,\n Operation,\n Task,\n TaskFilter,\n TaskListResult,\n TaskStatus,\n TaskStore,\n UpdateTaskInput,\n} from \"@roy-task-plugin/shared\";\n\nexport class ApiError extends Error {\n status: number;\n body: unknown;\n constructor(status: number, message: string, body?: unknown) {\n super(message);\n this.status = status;\n this.body = body;\n }\n}\n\nexport interface HttpClientConfig {\n baseUrl: string;\n /** Optional bearer token for auth. */\n authToken?: string;\n /** Default headers. */\n headers?: Record<string, string>;\n}\n\nexport class HttpTaskStoreClient implements TaskStore {\n private baseUrl: string;\n private headers: Record<string, string>;\n private closedFlag = false;\n\n constructor(config: HttpClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/+$/, \"\");\n this.headers = {\n \"content-type\": \"application/json\",\n ...(config.authToken ? { authorization: `Bearer ${config.authToken}` } : {}),\n ...(config.headers ?? {}),\n };\n }\n\n async close(): Promise<void> {\n this.closedFlag = true;\n }\n\n private async request<T>(\n method: string,\n path: string,\n init?: {\n body?: unknown;\n idempotencyKey?: string;\n },\n ): Promise<T | null> {\n if (this.closedFlag) throw new Error(\"client closed\");\n const headers: Record<string, string> = { ...this.headers };\n if (init?.idempotencyKey) headers[\"idempotency-key\"] = init.idempotencyKey;\n\n const res = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers,\n body: init?.body !== undefined ? JSON.stringify(init.body) : undefined,\n });\n\n if (res.status === 204) return null;\n const text = await res.text();\n let parsed: unknown = null;\n try {\n parsed = text ? JSON.parse(text) : null;\n } catch {\n parsed = text;\n }\n if (!res.ok) {\n throw new ApiError(res.status, `HTTP ${res.status}`, parsed);\n }\n return parsed as T;\n }\n\n async createTask(input: CreateTaskInput, idempotency_key?: string): Promise<Task> {\n const t = await this.request<Task>(\"POST\", \"/tasks\", {\n body: input,\n idempotencyKey: idempotency_key,\n });\n if (!t) throw new ApiError(500, \"empty response from POST /tasks\");\n return t;\n }\n\n async getTask(id: string): Promise<Task | null> {\n try {\n const t = await this.request<Task>(\"GET\", `/tasks/${encodeURIComponent(id)}`);\n return t;\n } catch (e) {\n if (e instanceof ApiError && e.status === 404) return null;\n throw e;\n }\n }\n\n async updateTask(id: string, input: UpdateTaskInput): Promise<Task | null> {\n try {\n return await this.request<Task>(\"PATCH\", `/tasks/${encodeURIComponent(id)}`, {\n body: input,\n });\n } catch (e) {\n if (e instanceof ApiError && e.status === 404) return null;\n throw e;\n }\n }\n\n async deleteTask(id: string): Promise<boolean> {\n try {\n await this.request<unknown>(\"DELETE\", `/tasks/${encodeURIComponent(id)}`);\n return true;\n } catch (e) {\n if (e instanceof ApiError && e.status === 404) return false;\n throw e;\n }\n }\n\n async listTasks(filter: TaskFilter = {}): Promise<TaskListResult> {\n const qs = new URLSearchParams();\n if (filter.status !== undefined) {\n const v = Array.isArray(filter.status) ? filter.status.join(\",\") : filter.status;\n qs.set(\"status\", v);\n }\n if (filter.parent_id !== undefined && filter.parent_id !== null) {\n qs.set(\"parent_id\", filter.parent_id);\n }\n if (filter.session_id !== undefined) qs.set(\"session_id\", filter.session_id);\n if (filter.owner !== undefined) qs.set(\"owner\", filter.owner);\n if (filter.tags !== undefined) qs.set(\"tags\", filter.tags);\n if (filter.search !== undefined) qs.set(\"search\", filter.search);\n qs.set(\"limit\", String(filter.limit ?? 100));\n qs.set(\"offset\", String(filter.offset ?? 0));\n const r = await this.request<TaskListResult>(\"GET\", `/tasks?${qs}`);\n if (!r) throw new ApiError(500, \"empty response\");\n return r;\n }\n\n async appendOperation(input: {\n task_id: string | null;\n type: string;\n data: Record<string, unknown>;\n }): Promise<Operation> {\n // The HTTP service derives ops from task mutations; for free-form ops\n // we expose a dedicated endpoint? — for MVP we use a no-op server route\n // and persist via /operations. For MVP simplicity, we accept that the\n // service emits its own ops and we return a synthesized op with sha256.\n // In practice the plugin calls appendOperation for session/tool events\n // that don't map to a /tasks mutation, so we add a synthetic op route:\n return await this.request<Operation>(\"POST\", \"/operations\", { body: input });\n }\n\n async listOperations(\n filter: { task_id?: string; type?: string; limit?: number; offset?: number } = {},\n ): Promise<{ operations: Operation[]; total: number }> {\n const qs = new URLSearchParams();\n if (filter.task_id !== undefined) qs.set(\"task_id\", filter.task_id);\n if (filter.type !== undefined) qs.set(\"type\", filter.type);\n qs.set(\"limit\", String(filter.limit ?? 100));\n qs.set(\"offset\", String(filter.offset ?? 0));\n return await this.request<{ operations: Operation[]; total: number }>(\n \"GET\",\n `/operations?${qs}`,\n );\n }\n\n async verifyChain(): Promise<boolean> {\n const r = await this.request<{ valid: boolean }>(\"GET\", \"/verify\");\n return r?.valid === true;\n }\n\n async sendBounty(input: {\n subject: string;\n body: string;\n from: string;\n to?: string;\n }): Promise<Bounty> {\n const b = await this.request<Bounty>(\"POST\", \"/bounties\", { body: input });\n if (!b) throw new ApiError(500, \"empty bounty response\");\n return b;\n }\n\n async claimBounty(agent: string): Promise<Bounty | null> {\n try {\n return await this.request<Bounty>(\"POST\", \"/bounties/claim\", { body: { agent } });\n } catch (e) {\n if (e instanceof ApiError && e.status === 404) return null;\n throw e;\n }\n }\n\n async completeBounty(id: string, task_id: string): Promise<Bounty | null> {\n try {\n return await this.request<Bounty>(\"POST\", `/bounties/${encodeURIComponent(id)}/complete`, {\n body: { task_id },\n });\n } catch (e) {\n if (e instanceof ApiError && e.status === 404) return null;\n throw e;\n }\n }\n\n async listBounties(filter: { status?: Bounty[\"status\"]; to?: string } = {}): Promise<Bounty[]> {\n const qs = new URLSearchParams();\n if (filter.status !== undefined) qs.set(\"status\", filter.status);\n if (filter.to !== undefined) qs.set(\"to\", filter.to);\n const r = await this.request<{ bounties: Bounty[] }>(\"GET\", `/bounties?${qs}`);\n return r?.bounties ?? [];\n }\n}\n\n// Keep TS happy\ntype _Status = TaskStatus;",
|
|
156
|
+
"/**\n * RemoteTaskStore — uses HttpTaskStoreClient to talk to the bundled service.\n * Switched in when opencode.json has \"persistence\": \"remote\" + \"remoteUrl\".\n */\n\nimport { HttpTaskStoreClient } from \"@roy-task-plugin/client\";\nimport type { TaskStore } from \"@roy-task-plugin/shared\";\n\nexport class RemoteTaskStore implements TaskStore {\n private inner: HttpTaskStoreClient;\n constructor(config: { baseUrl: string; authToken?: string }) {\n this.inner = new HttpTaskStoreClient(config);\n }\n createTask(...args: Parameters<HttpTaskStoreClient[\"createTask\"]>) {\n return this.inner.createTask(...args);\n }\n getTask(...args: Parameters<HttpTaskStoreClient[\"getTask\"]>) {\n return this.inner.getTask(...args);\n }\n updateTask(...args: Parameters<HttpTaskStoreClient[\"updateTask\"]>) {\n return this.inner.updateTask(...args);\n }\n deleteTask(...args: Parameters<HttpTaskStoreClient[\"deleteTask\"]>) {\n return this.inner.deleteTask(...args);\n }\n listTasks(...args: Parameters<HttpTaskStoreClient[\"listTasks\"]>) {\n return this.inner.listTasks(...args);\n }\n appendOperation(...args: Parameters<HttpTaskStoreClient[\"appendOperation\"]>) {\n return this.inner.appendOperation(...args);\n }\n listOperations(...args: Parameters<HttpTaskStoreClient[\"listOperations\"]>) {\n return this.inner.listOperations(...args);\n }\n verifyChain() {\n return this.inner.verifyChain();\n }\n sendBounty(...args: Parameters<HttpTaskStoreClient[\"sendBounty\"]>) {\n return this.inner.sendBounty(...args);\n }\n claimBounty(...args: Parameters<HttpTaskStoreClient[\"claimBounty\"]>) {\n return this.inner.claimBounty(...args);\n }\n completeBounty(...args: Parameters<HttpTaskStoreClient[\"completeBounty\"]>) {\n return this.inner.completeBounty(...args);\n }\n listBounties(...args: Parameters<HttpTaskStoreClient[\"listBounties\"]>) {\n return this.inner.listBounties(...args);\n }\n async close(): Promise<void> {\n await this.inner.close();\n }\n}",
|
|
157
|
+
"/**\n * OpenCode plugin entrypoint — opencode v2 Plugin.setup(ctx) contract.\n *\n * Default export must conform to:\n * { id: string, setup: (ctx: PluginContext) => Promise<{ dispose? }> }\n *\n * opencode v2's supervisor validates this shape via Schema.decodeUnknownEffect\n * (see packages/core/src/plugin/module.ts in opencode source). Plugins that\n * export a function (legacy v1 shape) are rejected with\n * \"Plugin must export a default definition with an id and an effect or setup\n * function.\"\n *\n * The plugin picks the persistence mode from `ctx.options` (default \"local\")\n * and, in v2, the only writable domains are\n * {agent, catalog, command, integration, reference, skill}. We use:\n * - agent.transform() to inject task-tracking knowledge into the default\n * agent's system prompt\n * - command.transform() to register a `task-create` CommandDraft entry\n * (visible via /api/command, can be invoked by the agent if it sees the\n * description)\n *\n * The actual task persistence uses our LocalTaskStore / RemoteTaskStore —\n * invoked either by the agent following the injected prompt, or by external\n * HTTP calls to our /api/tasks endpoint if persistence = \"remote\".\n */\n\nimport { createHandlers, type Handlers, type HandlerContext } from \"./handlers/index.js\";\nimport { registerRoyIntegration } from \"./roy-integration.js\";\nimport { LocalTaskStore } from \"./task-store/local.js\";\nimport { RemoteTaskStore } from \"./task-store/remote.js\";\nimport type { TaskStore } from \"@roy-task-plugin/shared\";\n\nexport interface RoyTaskPluginConfig {\n persistence?: \"local\" | \"remote\";\n remoteUrl?: string;\n remoteAuthToken?: string;\n /** Override the default local DB path (mostly for tests). */\n localDbPath?: string;\n /** Identifier of the agent running this plugin. */\n agent?: string;\n /**\n * Task #4286 — register the `roy` primary agent + the roy task tool family\n * (task_create / task_tree / task_update / task_operation_create /\n * task_complete / …). Default: true.\n *\n * The tools are imported from `@ai-setting/roy-agent-core` and persist\n * through this plugin's own store, so `persistence` keeps working unchanged.\n */\n royAgent?: boolean;\n}\n\nexport interface RoyTaskPluginHandle {\n handlers: Handlers;\n store: TaskStore;\n close: () => Promise<void>;\n}\n\n/**\n * Lower-level factory used by tests and by `setup()`.\n *\n * Kept as a public export for backward compatibility with the test suite\n * written under #4178 (handlers + store + close). Real plugin loading goes\n * through the `default` Plugin object below.\n */\nexport async function createRoyTaskPlugin(\n config: RoyTaskPluginConfig = {},\n): Promise<RoyTaskPluginHandle> {\n const persistence = config.persistence ?? \"local\";\n let store: TaskStore;\n if (persistence === \"remote\") {\n if (!config.remoteUrl) {\n throw new Error(\n \"remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)\",\n );\n }\n store = new RemoteTaskStore({\n baseUrl: config.remoteUrl,\n authToken: config.remoteAuthToken,\n });\n } else {\n store = await LocalTaskStore.create(config.localDbPath);\n }\n\n const ctx: HandlerContext = {\n store,\n agent: config.agent ?? \"opencode-default\",\n };\n const handlers = createHandlers(ctx);\n\n return {\n handlers,\n store,\n async close() {\n await store.close();\n },\n };\n}\n\n// ---- Minimal shape for ctx.command.transform's callback editor ----\ninterface CommandEditorLike {\n add(definition: {\n name: string;\n description?: string;\n execute?: (input: any) => Promise<void> | void;\n template?: string;\n }): void;\n update?(name: string, update: (command: any) => void): void;\n remove?(name: string): void;\n}\n\ninterface AgentDraftLike {\n list(): readonly any[];\n get(id: string): any | undefined;\n default(id: string | undefined): void;\n update(id: string, update: (agent: any) => void): void;\n remove(id: string): void;\n}\n\n/**\n * Plugin definition — satisfies opencode v2 `Plugin.setup(ctx)` contract.\n *\n * Strategy: v2 PluginContext does NOT expose `editor.add()` for commands or\n * agents — only `update(id, mutator)` to mutate EXISTING entries. So we:\n * 1. Open the TaskStore (local SQLite or remote HTTP)\n * 2. Modify the default agent's system prompt to inject task-tracking\n * instructions (the agent learns to create SQLite entries via bash)\n * 3. Register a `task-create` command via command.transform() — the entry\n * is visible in /api/command and the agent's prompt directs it to use\n * it (the command's description is the user's CLI for invocation)\n * 4. Return a cleanup function that disposes registrations + the store\n */\nconst RoyTaskPlugin = {\n id: \"roy-task-plugin\",\n async setup(ctx: any): Promise<{ dispose: () => Promise<void> }> {\n // ---- 1. Open the TaskStore ----\n const options = (ctx.options ?? {}) as RoyTaskPluginConfig;\n const persistence = options.persistence ?? \"local\";\n\n let store: TaskStore;\n if (persistence === \"remote\") {\n if (!options.remoteUrl) {\n throw new Error(\n \"remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)\",\n );\n }\n store = new RemoteTaskStore({\n baseUrl: options.remoteUrl,\n authToken: options.remoteAuthToken,\n });\n } else {\n store = await LocalTaskStore.create(options.localDbPath);\n }\n\n const handlerCtx: HandlerContext = {\n store,\n agent: options.agent ?? \"opencode-default\",\n };\n const handlers = createHandlers(handlerCtx);\n\n // ---- 1b. Register the `roy` primary agent + roy task tool family -------\n //\n // Task #4286: `roy` is an opt-out primary agent whose system prompt makes\n // \"task as a first-class citizen\" non-negotiable, wired to the *same* store\n // as the rest of the plugin. Registration is fault-isolated: a failure here\n // never breaks plugin loading (errors are returned, not thrown).\n const royRegistration = await registerRoyIntegration(ctx, {\n store,\n enabled: options.royAgent !== false,\n agent: \"roy\",\n });\n\n // ---- 2. Modify default agent to inject task tracking prompt ----\n //\n // The default agent (Build / General) gets a system prompt addition that\n // instructs it to log work via the `task-create` command. The injection\n // is conservative — only adds to the system field, never replaces.\n const agentReg = await ctx.agent.transform(async (draft: AgentDraftLike) => {\n const defaultId = \"build\"; // builtin default agent id\n const agent = draft.get(defaultId);\n if (!agent) return;\n\n const originalSystem = String(agent.system ?? \"\");\n const TASK_INSTRUCTION = `\n\n# Roy Task Plugin (auto-injected by roy-task-plugin v2)\n\nWhen you start a non-trivial task (more than one tool call), create a tracked task via the \\`task-create\\` command:\n\n task-create <title> [body]\n\nThe plugin persists each invocation to ${persistence === \"local\" ? \"SQLite at ~/.roy-task-plugin/tasks.db\" : `remote service at ${options.remoteUrl}`}. Use \\`task-list\\` and \\`task-status\\` to retrieve.\n\nMark progress on long tasks via \\`task-update <id> --status <status>\\`.\n\nFor task-first-class-citizen work (task tree, milestones, deliverables), switch\nto the dedicated **\\`roy\\`** primary agent — it carries the full roy task\nlifecycle as native tools.\n`;\n draft.update(defaultId, (a: any) => {\n if (typeof a.system === \"string\" || a.system === undefined) {\n a.system = originalSystem + TASK_INSTRUCTION;\n }\n });\n });\n\n // ---- 3. Register `task-create`/`task-list`/`task-status` commands ----\n //\n // The v2 Promise adapter (adapter.ts) wraps the editor's transform\n // callback with `{ add: ..., update: ..., remove: ... }`. The `add`\n // method registers a NEW command — this is the path that survives into\n // /api/command. The `execute` closure is what the agent invokes when\n // the user runs the command.\n const commandReg = await ctx.command.transform((editor: CommandEditorLike) => {\n editor.add({\n name: \"task-create\",\n description:\n \"Create a tracked task in roy-task-plugin store. \" +\n \"Persists to SQLite (~/.roy-task-plugin/tasks.db) or remote service. \" +\n \"Args: <title> [body]\",\n template: \"task-create <title> [body]\",\n execute: async (input: any) => {\n // input.prompt.text is the user-provided body; we extract title\n // from the first line. Persistence is delegated to handler logic.\n const text = String(input?.prompt?.text ?? \"\").trim();\n const title = text.split(\"\\n\")[0]?.trim() || `task-${Date.now()}`;\n await handlers.session({\n type: \"session.created\",\n payload: {\n id: input?.sessionID ?? `cmd-${Date.now()}`,\n title,\n body: text,\n source: \"command:task-create\",\n },\n });\n },\n });\n\n editor.add({\n name: \"task-list\",\n description: \"List tracked tasks. Filters: [--status <s>] [--owner <o>]\",\n template: \"task-list [--status <status>] [--owner <owner>]\",\n execute: async () => {\n // listAll happens lazily via /api/tasks if persistence = remote;\n // for local mode, agents can query the SQLite DB directly.\n },\n });\n\n editor.add({\n name: \"task-status\",\n description: \"Show full status of a single task. Args: <id>\",\n template: \"task-status <id>\",\n execute: async () => {\n /* same as task-list; agents query SQLite directly */\n },\n });\n });\n\n // ---- 4. Cleanup ----\n return {\n async dispose() {\n for (const dispose of royRegistration.disposers) {\n try {\n await dispose();\n } catch {\n // best-effort teardown\n }\n }\n await agentReg.dispose();\n await commandReg.dispose();\n await store.close();\n },\n };\n\n // handlers kept around for backward compat with #4178 test suite\n void handlers;\n },\n};\n\nexport default RoyTaskPlugin;\n\n// Re-export commonly used pieces (backward compat with #4178 test suite)\nexport { createHandlers } from \"./handlers/index.js\";\nexport { LocalTaskStore } from \"./task-store/local.js\";\nexport { RemoteTaskStore } from \"./task-store/remote.js\";\nexport type { TaskStore } from \"@roy-task-plugin/shared\";\n"
|
|
158
|
+
],
|
|
159
|
+
"mappings": ";uuBAEA,IAAM,GAAQ,OAAO,IAAI,YAAY,EAC/B,GAAM,OAAO,IAAI,eAAe,EAChC,GAAM,OAAO,IAAI,UAAU,EAC3B,GAAO,OAAO,IAAI,WAAW,EAC7B,GAAS,OAAO,IAAI,aAAa,EACjC,GAAM,OAAO,IAAI,UAAU,EAC3B,GAAY,OAAO,IAAI,gBAAgB,EACvC,GAAU,CAAC,IAAS,CAAC,CAAC,GAAQ,OAAO,IAAS,UAAY,EAAK,MAAe,GAC9E,GAAa,CAAC,IAAS,CAAC,CAAC,GAAQ,OAAO,IAAS,UAAY,EAAK,MAAe,GACjF,GAAQ,CAAC,IAAS,CAAC,CAAC,GAAQ,OAAO,IAAS,UAAY,EAAK,MAAe,GAC5E,GAAS,CAAC,IAAS,CAAC,CAAC,GAAQ,OAAO,IAAS,UAAY,EAAK,MAAe,GAC7E,GAAW,CAAC,IAAS,CAAC,CAAC,GAAQ,OAAO,IAAS,UAAY,EAAK,MAAe,GAC/E,GAAQ,CAAC,IAAS,CAAC,CAAC,GAAQ,OAAO,IAAS,UAAY,EAAK,MAAe,GAClF,SAAS,EAAY,CAAC,EAAM,CACxB,GAAI,GAAQ,OAAO,IAAS,SACxB,OAA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