agent-whisker 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/.claude-plugin/marketplace.json +12 -0
- package/LICENSE +21 -0
- package/README.md +164 -2
- package/README.zh-CN.md +165 -0
- package/node_modules/jieba-wasm/LICENSE +25 -0
- package/node_modules/jieba-wasm/README.md +134 -0
- package/node_modules/jieba-wasm/package.json +129 -0
- package/node_modules/jieba-wasm/pkg/nodejs/jieba_rs_wasm.d.ts +24 -0
- package/node_modules/jieba-wasm/pkg/nodejs/jieba_rs_wasm.js +341 -0
- package/node_modules/jieba-wasm/pkg/nodejs/jieba_rs_wasm_bg.wasm +0 -0
- package/node_modules/jieba-wasm/pkg/nodejs/jieba_rs_wasm_bg.wasm.d.ts +25 -0
- package/node_modules/yaml/LICENSE +13 -0
- package/node_modules/yaml/README.md +172 -0
- package/node_modules/yaml/bin.mjs +11 -0
- package/node_modules/yaml/browser/dist/compose/compose-collection.js +88 -0
- package/node_modules/yaml/browser/dist/compose/compose-doc.js +43 -0
- package/node_modules/yaml/browser/dist/compose/compose-node.js +109 -0
- package/node_modules/yaml/browser/dist/compose/compose-scalar.js +86 -0
- package/node_modules/yaml/browser/dist/compose/composer.js +219 -0
- package/node_modules/yaml/browser/dist/compose/resolve-block-map.js +115 -0
- package/node_modules/yaml/browser/dist/compose/resolve-block-scalar.js +198 -0
- package/node_modules/yaml/browser/dist/compose/resolve-block-seq.js +49 -0
- package/node_modules/yaml/browser/dist/compose/resolve-end.js +37 -0
- package/node_modules/yaml/browser/dist/compose/resolve-flow-collection.js +207 -0
- package/node_modules/yaml/browser/dist/compose/resolve-flow-scalar.js +226 -0
- package/node_modules/yaml/browser/dist/compose/resolve-props.js +146 -0
- package/node_modules/yaml/browser/dist/compose/util-contains-newline.js +34 -0
- package/node_modules/yaml/browser/dist/compose/util-empty-scalar-position.js +26 -0
- package/node_modules/yaml/browser/dist/compose/util-flow-indent-check.js +15 -0
- package/node_modules/yaml/browser/dist/compose/util-map-includes.js +13 -0
- package/node_modules/yaml/browser/dist/doc/Document.js +335 -0
- package/node_modules/yaml/browser/dist/doc/anchors.js +71 -0
- package/node_modules/yaml/browser/dist/doc/applyReviver.js +55 -0
- package/node_modules/yaml/browser/dist/doc/createNode.js +88 -0
- package/node_modules/yaml/browser/dist/doc/directives.js +176 -0
- package/node_modules/yaml/browser/dist/errors.js +57 -0
- package/node_modules/yaml/browser/dist/index.js +17 -0
- package/node_modules/yaml/browser/dist/log.js +11 -0
- package/node_modules/yaml/browser/dist/nodes/Alias.js +118 -0
- package/node_modules/yaml/browser/dist/nodes/Collection.js +147 -0
- package/node_modules/yaml/browser/dist/nodes/Node.js +38 -0
- package/node_modules/yaml/browser/dist/nodes/Pair.js +36 -0
- package/node_modules/yaml/browser/dist/nodes/Scalar.js +24 -0
- package/node_modules/yaml/browser/dist/nodes/YAMLMap.js +144 -0
- package/node_modules/yaml/browser/dist/nodes/YAMLSeq.js +113 -0
- package/node_modules/yaml/browser/dist/nodes/addPairToJSMap.js +63 -0
- package/node_modules/yaml/browser/dist/nodes/identity.js +36 -0
- package/node_modules/yaml/browser/dist/nodes/toJS.js +37 -0
- package/node_modules/yaml/browser/dist/parse/cst-scalar.js +214 -0
- package/node_modules/yaml/browser/dist/parse/cst-stringify.js +61 -0
- package/node_modules/yaml/browser/dist/parse/cst-visit.js +97 -0
- package/node_modules/yaml/browser/dist/parse/cst.js +98 -0
- package/node_modules/yaml/browser/dist/parse/lexer.js +721 -0
- package/node_modules/yaml/browser/dist/parse/line-counter.js +39 -0
- package/node_modules/yaml/browser/dist/parse/parser.js +975 -0
- package/node_modules/yaml/browser/dist/public-api.js +102 -0
- package/node_modules/yaml/browser/dist/schema/Schema.js +37 -0
- package/node_modules/yaml/browser/dist/schema/common/map.js +17 -0
- package/node_modules/yaml/browser/dist/schema/common/null.js +15 -0
- package/node_modules/yaml/browser/dist/schema/common/seq.js +17 -0
- package/node_modules/yaml/browser/dist/schema/common/string.js +14 -0
- package/node_modules/yaml/browser/dist/schema/core/bool.js +19 -0
- package/node_modules/yaml/browser/dist/schema/core/float.js +43 -0
- package/node_modules/yaml/browser/dist/schema/core/int.js +38 -0
- package/node_modules/yaml/browser/dist/schema/core/schema.js +23 -0
- package/node_modules/yaml/browser/dist/schema/json/schema.js +62 -0
- package/node_modules/yaml/browser/dist/schema/tags.js +96 -0
- package/node_modules/yaml/browser/dist/schema/yaml-1.1/binary.js +58 -0
- package/node_modules/yaml/browser/dist/schema/yaml-1.1/bool.js +26 -0
- package/node_modules/yaml/browser/dist/schema/yaml-1.1/float.js +46 -0
- package/node_modules/yaml/browser/dist/schema/yaml-1.1/int.js +71 -0
- package/node_modules/yaml/browser/dist/schema/yaml-1.1/merge.js +67 -0
- package/node_modules/yaml/browser/dist/schema/yaml-1.1/omap.js +74 -0
- package/node_modules/yaml/browser/dist/schema/yaml-1.1/pairs.js +78 -0
- package/node_modules/yaml/browser/dist/schema/yaml-1.1/schema.js +39 -0
- package/node_modules/yaml/browser/dist/schema/yaml-1.1/set.js +93 -0
- package/node_modules/yaml/browser/dist/schema/yaml-1.1/timestamp.js +101 -0
- package/node_modules/yaml/browser/dist/stringify/foldFlowLines.js +146 -0
- package/node_modules/yaml/browser/dist/stringify/stringify.js +129 -0
- package/node_modules/yaml/browser/dist/stringify/stringifyCollection.js +153 -0
- package/node_modules/yaml/browser/dist/stringify/stringifyComment.js +20 -0
- package/node_modules/yaml/browser/dist/stringify/stringifyDocument.js +85 -0
- package/node_modules/yaml/browser/dist/stringify/stringifyNumber.js +25 -0
- package/node_modules/yaml/browser/dist/stringify/stringifyPair.js +150 -0
- package/node_modules/yaml/browser/dist/stringify/stringifyString.js +336 -0
- package/node_modules/yaml/browser/dist/util.js +11 -0
- package/node_modules/yaml/browser/dist/visit.js +233 -0
- package/node_modules/yaml/browser/index.js +5 -0
- package/node_modules/yaml/browser/package.json +3 -0
- package/node_modules/yaml/dist/cli.d.ts +8 -0
- package/node_modules/yaml/dist/cli.mjs +201 -0
- package/node_modules/yaml/dist/compose/compose-collection.d.ts +11 -0
- package/node_modules/yaml/dist/compose/compose-collection.js +90 -0
- package/node_modules/yaml/dist/compose/compose-doc.d.ts +7 -0
- package/node_modules/yaml/dist/compose/compose-doc.js +45 -0
- package/node_modules/yaml/dist/compose/compose-node.d.ts +29 -0
- package/node_modules/yaml/dist/compose/compose-node.js +112 -0
- package/node_modules/yaml/dist/compose/compose-scalar.d.ts +5 -0
- package/node_modules/yaml/dist/compose/compose-scalar.js +88 -0
- package/node_modules/yaml/dist/compose/composer.d.ts +63 -0
- package/node_modules/yaml/dist/compose/composer.js +224 -0
- package/node_modules/yaml/dist/compose/resolve-block-map.d.ts +6 -0
- package/node_modules/yaml/dist/compose/resolve-block-map.js +117 -0
- package/node_modules/yaml/dist/compose/resolve-block-scalar.d.ts +11 -0
- package/node_modules/yaml/dist/compose/resolve-block-scalar.js +200 -0
- package/node_modules/yaml/dist/compose/resolve-block-seq.d.ts +6 -0
- package/node_modules/yaml/dist/compose/resolve-block-seq.js +51 -0
- package/node_modules/yaml/dist/compose/resolve-end.d.ts +6 -0
- package/node_modules/yaml/dist/compose/resolve-end.js +39 -0
- package/node_modules/yaml/dist/compose/resolve-flow-collection.d.ts +7 -0
- package/node_modules/yaml/dist/compose/resolve-flow-collection.js +209 -0
- package/node_modules/yaml/dist/compose/resolve-flow-scalar.d.ts +10 -0
- package/node_modules/yaml/dist/compose/resolve-flow-scalar.js +228 -0
- package/node_modules/yaml/dist/compose/resolve-props.d.ts +23 -0
- package/node_modules/yaml/dist/compose/resolve-props.js +148 -0
- package/node_modules/yaml/dist/compose/util-contains-newline.d.ts +2 -0
- package/node_modules/yaml/dist/compose/util-contains-newline.js +36 -0
- package/node_modules/yaml/dist/compose/util-empty-scalar-position.d.ts +2 -0
- package/node_modules/yaml/dist/compose/util-empty-scalar-position.js +28 -0
- package/node_modules/yaml/dist/compose/util-flow-indent-check.d.ts +3 -0
- package/node_modules/yaml/dist/compose/util-flow-indent-check.js +17 -0
- package/node_modules/yaml/dist/compose/util-map-includes.d.ts +4 -0
- package/node_modules/yaml/dist/compose/util-map-includes.js +15 -0
- package/node_modules/yaml/dist/doc/Document.d.ts +141 -0
- package/node_modules/yaml/dist/doc/Document.js +337 -0
- package/node_modules/yaml/dist/doc/anchors.d.ts +24 -0
- package/node_modules/yaml/dist/doc/anchors.js +76 -0
- package/node_modules/yaml/dist/doc/applyReviver.d.ts +9 -0
- package/node_modules/yaml/dist/doc/applyReviver.js +57 -0
- package/node_modules/yaml/dist/doc/createNode.d.ts +17 -0
- package/node_modules/yaml/dist/doc/createNode.js +90 -0
- package/node_modules/yaml/dist/doc/directives.d.ts +49 -0
- package/node_modules/yaml/dist/doc/directives.js +178 -0
- package/node_modules/yaml/dist/errors.d.ts +21 -0
- package/node_modules/yaml/dist/errors.js +62 -0
- package/node_modules/yaml/dist/index.d.ts +25 -0
- package/node_modules/yaml/dist/index.js +50 -0
- package/node_modules/yaml/dist/log.d.ts +3 -0
- package/node_modules/yaml/dist/log.js +19 -0
- package/node_modules/yaml/dist/nodes/Alias.d.ts +29 -0
- package/node_modules/yaml/dist/nodes/Alias.js +120 -0
- package/node_modules/yaml/dist/nodes/Collection.d.ts +73 -0
- package/node_modules/yaml/dist/nodes/Collection.js +151 -0
- package/node_modules/yaml/dist/nodes/Node.d.ts +53 -0
- package/node_modules/yaml/dist/nodes/Node.js +40 -0
- package/node_modules/yaml/dist/nodes/Pair.d.ts +22 -0
- package/node_modules/yaml/dist/nodes/Pair.js +39 -0
- package/node_modules/yaml/dist/nodes/Scalar.d.ts +47 -0
- package/node_modules/yaml/dist/nodes/Scalar.js +27 -0
- package/node_modules/yaml/dist/nodes/YAMLMap.d.ts +53 -0
- package/node_modules/yaml/dist/nodes/YAMLMap.js +147 -0
- package/node_modules/yaml/dist/nodes/YAMLSeq.d.ts +60 -0
- package/node_modules/yaml/dist/nodes/YAMLSeq.js +115 -0
- package/node_modules/yaml/dist/nodes/addPairToJSMap.d.ts +4 -0
- package/node_modules/yaml/dist/nodes/addPairToJSMap.js +65 -0
- package/node_modules/yaml/dist/nodes/identity.d.ts +23 -0
- package/node_modules/yaml/dist/nodes/identity.js +53 -0
- package/node_modules/yaml/dist/nodes/toJS.d.ts +29 -0
- package/node_modules/yaml/dist/nodes/toJS.js +39 -0
- package/node_modules/yaml/dist/options.d.ts +350 -0
- package/node_modules/yaml/dist/parse/cst-scalar.d.ts +64 -0
- package/node_modules/yaml/dist/parse/cst-scalar.js +218 -0
- package/node_modules/yaml/dist/parse/cst-stringify.d.ts +8 -0
- package/node_modules/yaml/dist/parse/cst-stringify.js +63 -0
- package/node_modules/yaml/dist/parse/cst-visit.d.ts +39 -0
- package/node_modules/yaml/dist/parse/cst-visit.js +99 -0
- package/node_modules/yaml/dist/parse/cst.d.ts +109 -0
- package/node_modules/yaml/dist/parse/cst.js +112 -0
- package/node_modules/yaml/dist/parse/lexer.d.ts +87 -0
- package/node_modules/yaml/dist/parse/lexer.js +723 -0
- package/node_modules/yaml/dist/parse/line-counter.d.ts +22 -0
- package/node_modules/yaml/dist/parse/line-counter.js +41 -0
- package/node_modules/yaml/dist/parse/parser.d.ts +84 -0
- package/node_modules/yaml/dist/parse/parser.js +980 -0
- package/node_modules/yaml/dist/public-api.d.ts +44 -0
- package/node_modules/yaml/dist/public-api.js +107 -0
- package/node_modules/yaml/dist/schema/Schema.d.ts +17 -0
- package/node_modules/yaml/dist/schema/Schema.js +39 -0
- package/node_modules/yaml/dist/schema/common/map.d.ts +2 -0
- package/node_modules/yaml/dist/schema/common/map.js +19 -0
- package/node_modules/yaml/dist/schema/common/null.d.ts +4 -0
- package/node_modules/yaml/dist/schema/common/null.js +17 -0
- package/node_modules/yaml/dist/schema/common/seq.d.ts +2 -0
- package/node_modules/yaml/dist/schema/common/seq.js +19 -0
- package/node_modules/yaml/dist/schema/common/string.d.ts +2 -0
- package/node_modules/yaml/dist/schema/common/string.js +16 -0
- package/node_modules/yaml/dist/schema/core/bool.d.ts +4 -0
- package/node_modules/yaml/dist/schema/core/bool.js +21 -0
- package/node_modules/yaml/dist/schema/core/float.d.ts +4 -0
- package/node_modules/yaml/dist/schema/core/float.js +47 -0
- package/node_modules/yaml/dist/schema/core/int.d.ts +4 -0
- package/node_modules/yaml/dist/schema/core/int.js +42 -0
- package/node_modules/yaml/dist/schema/core/schema.d.ts +1 -0
- package/node_modules/yaml/dist/schema/core/schema.js +25 -0
- package/node_modules/yaml/dist/schema/json/schema.d.ts +2 -0
- package/node_modules/yaml/dist/schema/json/schema.js +64 -0
- package/node_modules/yaml/dist/schema/json-schema.d.ts +69 -0
- package/node_modules/yaml/dist/schema/tags.d.ts +48 -0
- package/node_modules/yaml/dist/schema/tags.js +99 -0
- package/node_modules/yaml/dist/schema/types.d.ts +92 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/binary.d.ts +2 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/binary.js +70 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/bool.d.ts +7 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/bool.js +29 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/float.d.ts +4 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/float.js +50 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/int.d.ts +5 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/int.js +76 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/merge.d.ts +9 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/merge.js +71 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/omap.d.ts +22 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/omap.js +77 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/pairs.d.ts +10 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/pairs.js +82 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/schema.d.ts +1 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/schema.js +41 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/set.d.ts +28 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/set.js +96 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/timestamp.d.ts +6 -0
- package/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js +105 -0
- package/node_modules/yaml/dist/stringify/foldFlowLines.d.ts +34 -0
- package/node_modules/yaml/dist/stringify/foldFlowLines.js +151 -0
- package/node_modules/yaml/dist/stringify/stringify.d.ts +21 -0
- package/node_modules/yaml/dist/stringify/stringify.js +132 -0
- package/node_modules/yaml/dist/stringify/stringifyCollection.d.ts +17 -0
- package/node_modules/yaml/dist/stringify/stringifyCollection.js +155 -0
- package/node_modules/yaml/dist/stringify/stringifyComment.d.ts +10 -0
- package/node_modules/yaml/dist/stringify/stringifyComment.js +24 -0
- package/node_modules/yaml/dist/stringify/stringifyDocument.d.ts +4 -0
- package/node_modules/yaml/dist/stringify/stringifyDocument.js +87 -0
- package/node_modules/yaml/dist/stringify/stringifyNumber.d.ts +2 -0
- package/node_modules/yaml/dist/stringify/stringifyNumber.js +27 -0
- package/node_modules/yaml/dist/stringify/stringifyPair.d.ts +3 -0
- package/node_modules/yaml/dist/stringify/stringifyPair.js +152 -0
- package/node_modules/yaml/dist/stringify/stringifyString.d.ts +9 -0
- package/node_modules/yaml/dist/stringify/stringifyString.js +338 -0
- package/node_modules/yaml/dist/test-events.d.ts +4 -0
- package/node_modules/yaml/dist/test-events.js +134 -0
- package/node_modules/yaml/dist/util.d.ts +16 -0
- package/node_modules/yaml/dist/util.js +28 -0
- package/node_modules/yaml/dist/visit.d.ts +102 -0
- package/node_modules/yaml/dist/visit.js +236 -0
- package/node_modules/yaml/package.json +97 -0
- package/node_modules/yaml/util.js +2 -0
- package/package.json +54 -4
- package/packages/antigravity-plugin/README.md +27 -0
- package/packages/antigravity-plugin/README.zh-CN.md +27 -0
- package/packages/antigravity-plugin/agents/review.md +36 -0
- package/packages/antigravity-plugin/hooks.json +24 -0
- package/packages/antigravity-plugin/package.json +7 -0
- package/packages/antigravity-plugin/plugin.json +5 -0
- package/packages/antigravity-plugin/review-perspectives.md +14 -0
- package/packages/antigravity-plugin/rules/agent-whisker.md +7 -0
- package/packages/antigravity-plugin/skills/task-state/SKILL.md +93 -0
- package/packages/claude-plugin/.claude-plugin/plugin.json +8 -0
- package/packages/claude-plugin/.codex-plugin/plugin.json +8 -0
- package/packages/claude-plugin/README.md +242 -0
- package/packages/claude-plugin/README.zh-CN.md +88 -0
- package/packages/claude-plugin/agents/recall.md +28 -0
- package/packages/claude-plugin/agents/review.md +33 -0
- package/packages/claude-plugin/bin/taskstate +1274 -0
- package/packages/claude-plugin/bin/windows-launch.mjs +71 -0
- package/packages/claude-plugin/hooks/codex.json +95 -0
- package/packages/claude-plugin/hooks/hooks.json +80 -0
- package/packages/claude-plugin/package.json +7 -0
- package/packages/claude-plugin/review-perspectives.md +14 -0
- package/packages/claude-plugin/skills/task-state/SKILL.md +93 -0
- package/packages/cli/README.md +294 -0
- package/packages/cli/README.zh-CN.md +294 -0
- package/packages/cli/package.json +16 -0
- package/packages/cli/src/command.js +325 -0
- package/packages/cli/src/commands/catalog.js +101 -0
- package/packages/cli/src/commands/doctor.js +1773 -0
- package/packages/cli/src/commands/document.js +38 -0
- package/packages/cli/src/commands/exclude.js +156 -0
- package/packages/cli/src/commands/extract.js +63 -0
- package/packages/cli/src/commands/grep.js +139 -0
- package/packages/cli/src/commands/hook.js +342 -0
- package/packages/cli/src/commands/index-command.js +199 -0
- package/packages/cli/src/commands/index.js +49 -0
- package/packages/cli/src/commands/ingest.js +332 -0
- package/packages/cli/src/commands/init.js +208 -0
- package/packages/cli/src/commands/install.js +225 -0
- package/packages/cli/src/commands/mcp.js +54 -0
- package/packages/cli/src/commands/nudge.js +83 -0
- package/packages/cli/src/commands/project.js +228 -0
- package/packages/cli/src/commands/read.js +158 -0
- package/packages/cli/src/commands/search.js +283 -0
- package/packages/cli/src/commands/service.js +241 -0
- package/packages/cli/src/commands/sessions.js +611 -0
- package/packages/cli/src/commands/status.js +194 -0
- package/packages/cli/src/commands/tui.js +62 -0
- package/packages/cli/src/commands/version.js +25 -0
- package/packages/cli/src/exclusion.js +88 -0
- package/packages/cli/src/grep-options.js +133 -0
- package/packages/cli/src/index.js +18 -0
- package/packages/cli/src/install/agents.js +99 -0
- package/packages/cli/src/install/antigravity-plugin.js +221 -0
- package/packages/cli/src/install/claude-plugin.js +167 -0
- package/packages/cli/src/install/clients.js +515 -0
- package/packages/cli/src/install/codex-plugin.js +207 -0
- package/packages/cli/src/install/dsh.js +599 -0
- package/packages/cli/src/install/external.js +659 -0
- package/packages/cli/src/install/handlers.js +76 -0
- package/packages/cli/src/install/herdr-mod.js +411 -0
- package/packages/cli/src/install/mcp.js +266 -0
- package/packages/cli/src/install/remove.js +913 -0
- package/packages/cli/src/install/rules.js +669 -0
- package/packages/cli/src/install/steps.js +1767 -0
- package/packages/cli/src/install/wrapper.js +558 -0
- package/packages/cli/src/keystore.js +530 -0
- package/packages/cli/src/launcher.js +184 -0
- package/packages/cli/src/main.js +11 -0
- package/packages/cli/src/node-version.js +25 -0
- package/packages/cli/src/paths.js +16 -0
- package/packages/cli/src/pointer.js +330 -0
- package/packages/cli/src/run.js +254 -0
- package/packages/cli/src/session-wait.js +365 -0
- package/packages/cli/src/store-access.js +51 -0
- package/packages/cli/src/tui/app.js +1430 -0
- package/packages/cli/src/tui/data/call.js +83 -0
- package/packages/cli/src/tui/data/poll.js +24 -0
- package/packages/cli/src/tui/glyphs.js +93 -0
- package/packages/cli/src/tui/i18n.js +342 -0
- package/packages/cli/src/tui/model.js +251 -0
- package/packages/cli/src/tui/pages/common.js +71 -0
- package/packages/cli/src/tui/pages/library.js +154 -0
- package/packages/cli/src/tui/pages/sessions.js +96 -0
- package/packages/cli/src/tui/pages/system.js +124 -0
- package/packages/cli/src/tui/pages/tasks.js +297 -0
- package/packages/cli/src/tui/run.js +216 -0
- package/packages/cli/src/tui/term/keys.js +152 -0
- package/packages/cli/src/tui/term/screen.js +88 -0
- package/packages/cli/src/tui/term/term.js +157 -0
- package/packages/cli/src/tui/term/width.js +290 -0
- package/packages/cli/src/tui/ui/widgets.js +247 -0
- package/packages/core/README.md +53 -0
- package/packages/core/README.zh-CN.md +53 -0
- package/packages/core/package.json +13 -0
- package/packages/core/src/antigravity.js +471 -0
- package/packages/core/src/append.js +309 -0
- package/packages/core/src/atomic-file.js +127 -0
- package/packages/core/src/barrier.js +359 -0
- package/packages/core/src/blobs.js +423 -0
- package/packages/core/src/catalog.js +513 -0
- package/packages/core/src/chunk.js +371 -0
- package/packages/core/src/clairic.js +518 -0
- package/packages/core/src/compact.js +194 -0
- package/packages/core/src/context.js +65 -0
- package/packages/core/src/convert.js +168 -0
- package/packages/core/src/crashpoints.js +59 -0
- package/packages/core/src/db.js +1318 -0
- package/packages/core/src/doc-kind.js +30 -0
- package/packages/core/src/dsh.js +494 -0
- package/packages/core/src/encoding.js +175 -0
- package/packages/core/src/errors.js +139 -0
- package/packages/core/src/excerpt.js +93 -0
- package/packages/core/src/exclude.js +102 -0
- package/packages/core/src/extract.js +708 -0
- package/packages/core/src/extractors.js +170 -0
- package/packages/core/src/format.js +18 -0
- package/packages/core/src/grep.js +623 -0
- package/packages/core/src/host.js +590 -0
- package/packages/core/src/ids.js +242 -0
- package/packages/core/src/index-db.js +1040 -0
- package/packages/core/src/index-view.js +201 -0
- package/packages/core/src/index.js +89 -0
- package/packages/core/src/ingest-file.js +854 -0
- package/packages/core/src/json.js +127 -0
- package/packages/core/src/library-filters.js +126 -0
- package/packages/core/src/library-read.js +751 -0
- package/packages/core/src/nudge.js +129 -0
- package/packages/core/src/observers.js +175 -0
- package/packages/core/src/pages.js +95 -0
- package/packages/core/src/pattern.js +433 -0
- package/packages/core/src/pdf-bookmarks.js +231 -0
- package/packages/core/src/project.js +1073 -0
- package/packages/core/src/protobuf.js +112 -0
- package/packages/core/src/ranking.js +13 -0
- package/packages/core/src/reclassify.js +78 -0
- package/packages/core/src/recovery.js +179 -0
- package/packages/core/src/reducers/library.js +559 -0
- package/packages/core/src/reducers/registry.js +180 -0
- package/packages/core/src/replay.js +525 -0
- package/packages/core/src/rerank.js +1263 -0
- package/packages/core/src/schema.js +479 -0
- package/packages/core/src/search.js +1241 -0
- package/packages/core/src/session-files.js +2320 -0
- package/packages/core/src/session-grep.js +270 -0
- package/packages/core/src/session-reader.js +201 -0
- package/packages/core/src/sessions-read.js +888 -0
- package/packages/core/src/sessions-search.js +1142 -0
- package/packages/core/src/sessions-sync.js +886 -0
- package/packages/core/src/sessions.js +958 -0
- package/packages/core/src/sources.js +558 -0
- package/packages/core/src/state.js +172 -0
- package/packages/core/src/store.js +1039 -0
- package/packages/core/src/tokenize.js +187 -0
- package/packages/core/src/validation.js +127 -0
- package/packages/dsh-plugin/README.md +64 -0
- package/packages/dsh-plugin/README.zh-CN.md +64 -0
- package/packages/dsh-plugin/checked.json +3 -0
- package/packages/dsh-plugin/index.js +520 -0
- package/packages/dsh-plugin/package.json +7 -0
- package/packages/dsh-plugin/skills/task-state/SKILL.md +93 -0
- package/packages/herdr-plugin/README.md +15 -0
- package/packages/herdr-plugin/README.zh-CN.md +15 -0
- package/packages/herdr-plugin/app-mod/main.js +189 -0
- package/packages/herdr-plugin/app-mod/mod.json +1 -0
- package/packages/herdr-plugin/app-mod/status.js +275 -0
- package/packages/herdr-plugin/herdr-plugin.toml +15 -0
- package/packages/herdr-plugin/package.json +7 -0
- package/packages/mcp/README.md +106 -0
- package/packages/mcp/README.zh-CN.md +106 -0
- package/packages/mcp/package.json +13 -0
- package/packages/mcp/src/framing.js +101 -0
- package/packages/mcp/src/index.js +13 -0
- package/packages/mcp/src/instructions.js +378 -0
- package/packages/mcp/src/reload.js +141 -0
- package/packages/mcp/src/roots.js +185 -0
- package/packages/mcp/src/server.js +779 -0
- package/packages/mcp/src/tools/arguments.js +482 -0
- package/packages/mcp/src/tools/context.js +21 -0
- package/packages/mcp/src/tools/definitions.js +343 -0
- package/packages/mcp/src/tools/document-sessions.js +262 -0
- package/packages/mcp/src/tools/extract.js +57 -0
- package/packages/mcp/src/tools/grep.js +39 -0
- package/packages/mcp/src/tools/library.js +716 -0
- package/packages/mcp/src/tools/other-store.js +159 -0
- package/packages/mcp/src/tools/results.js +32 -0
- package/packages/mcp/src/tools/session-entries.js +49 -0
- package/packages/mcp/src/tools/sessions.js +730 -0
- package/packages/mcp/src/tools/text.js +47 -0
- package/packages/mcp/src/tools.js +125 -0
- package/packages/mcp/src/whisker.js +132 -0
- package/packages/pi-extension/LICENSE +21 -0
- package/packages/pi-extension/README.md +29 -0
- package/packages/pi-extension/README.zh-CN.md +29 -0
- package/packages/pi-extension/agents/review.md +33 -0
- package/packages/pi-extension/package.json +20 -0
- package/packages/pi-extension/review-perspectives.md +14 -0
- package/packages/pi-extension/skills/task-state/SKILL.md +93 -0
- package/packages/pi-extension/src/extension.ts +857 -0
- package/packages/pi-extension/src/index.ts +6 -0
- package/packages/service/README.md +22 -0
- package/packages/service/README.zh-CN.md +22 -0
- package/packages/service/package.json +13 -0
- package/packages/service/src/errors.js +38 -0
- package/packages/service/src/files.js +289 -0
- package/packages/service/src/index.js +16 -0
- package/packages/service/src/launch-agent.js +387 -0
- package/packages/service/src/on-demand.js +93 -0
- package/packages/service/src/runtime.js +477 -0
- package/packages/service/src/types.js +119 -0
|
@@ -0,0 +1,1263 @@
|
|
|
1
|
+
// Reranks library search candidates for MCP and CLI. Synchronous search captures
|
|
2
|
+
// results while the store is open; asynchronous reranking uses only those results.
|
|
3
|
+
// Missing configuration, reranker failure, and timeouts fall back to original order.
|
|
4
|
+
// The leading passages are widened after the final order is known, so widening never changes ranking.
|
|
5
|
+
//
|
|
6
|
+
// Two request formats, chosen by the URL: a judge gateway scores the pool in one batch with optional choice finals;
|
|
7
|
+
// a rerank server (a path ending in /rerank) gets one request for the pool. Requests use Host.fetch and send
|
|
8
|
+
// only open-tier document passages and the question, never sessions. The key for the request header is the
|
|
9
|
+
// environment's, or when the environment sets none Host.rerankKey's, kept for the URL's address; never include it in
|
|
10
|
+
// results, errors, or logs.
|
|
11
|
+
|
|
12
|
+
import { invalidArgument } from "./errors.js";
|
|
13
|
+
import { densestWord } from "./excerpt.js";
|
|
14
|
+
import { clipBytes } from "./extract.js";
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
checkSearchLimit,
|
|
19
|
+
|
|
20
|
+
limitSearchResult,
|
|
21
|
+
SEARCH_CANDIDATES,
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
widenHits,
|
|
26
|
+
} from "./search.js";
|
|
27
|
+
import { isPlainObject } from "./validation.js";
|
|
28
|
+
|
|
29
|
+
// ---------------------------------------------------------------------------
|
|
30
|
+
// Configuration
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
|
|
33
|
+
/** Maximum number of passing passages compared in the choice question. */
|
|
34
|
+
const RERANK_FINALISTS = 8;
|
|
35
|
+
|
|
36
|
+
/** Maximum passages per choice slice when a local gateway rejects multi-question noul batches. */
|
|
37
|
+
const RERANK_CHOICE_SLICE = 10;
|
|
38
|
+
|
|
39
|
+
/** Per-request deadline. A timeout aborts the request and counts as a failure. */
|
|
40
|
+
const RERANK_CALL_TIMEOUT_MS = 5_000;
|
|
41
|
+
|
|
42
|
+
/** Shared gateway deadline. A timeout during the optional finals keeps the batch scores. */
|
|
43
|
+
const RERANK_TOTAL_TIMEOUT_MS = 6_000;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Default threshold of the judge gateway, whose scores run from 0 to 1: passage candidates scored below it are
|
|
47
|
+
* discarded. AGENT_WHISKER_RERANK_THRESHOLD replaces it (thresholdOf).
|
|
48
|
+
*/
|
|
49
|
+
const RERANK_THRESHOLD = 0.5;
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Open candidates either format scores: the first this many in lexical order. Later ones are not sent and keep their
|
|
53
|
+
* lexical slots after the reranked ones. Chosen from a local trial: one listwise pass over 20 passages took about a
|
|
54
|
+
* second, over 50 about four.
|
|
55
|
+
*/
|
|
56
|
+
const RERANK_POOL = 20;
|
|
57
|
+
|
|
58
|
+
/** Deadline of the one rerank-server request, from sending to the parsed answer. A timeout falls back. */
|
|
59
|
+
const RERANK_POOL_TIMEOUT_MS = 10_000;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Maximum number of full passages after reranking; later matches contain only locations. A widened search widens the
|
|
63
|
+
* same number of leading passages in either mode, so with reranking every passage that carries text is widened.
|
|
64
|
+
*/
|
|
65
|
+
export const RERANK_FULL_HITS = 3;
|
|
66
|
+
|
|
67
|
+
/** Maximum number of weak locations in more when no score reaches the threshold. */
|
|
68
|
+
const RERANK_UNSURE_HITS = 3;
|
|
69
|
+
|
|
70
|
+
/** Fall back when more than one fifth of the batch's passage scores are missing or invalid. */
|
|
71
|
+
const RERANK_FAILED_FRACTION = 5;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Bytes of one answer's body read at most; a longer body is read no further and the call fails. The largest valid
|
|
75
|
+
* answer is a rerank server's for RERANK_POOL documents that echoes each one (some servers do unless asked not to):
|
|
76
|
+
* a document is a 2,000-byte chunk, six 200-byte headings and a title, about 3.5 KB, and JSON escaping at most triples
|
|
77
|
+
* text, so about 210 KB. 1 MiB leaves room five times over; a gateway returns only scores or choice probabilities.
|
|
78
|
+
*/
|
|
79
|
+
const ANSWER_MAX_BYTES = 1_048_576;
|
|
80
|
+
|
|
81
|
+
/** UTF-8 question limit. The original question is sent once per request. */
|
|
82
|
+
const QUESTION_MAX_BYTES = 4096;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Environment keys for reranking. The URL and model must be configured explicitly. Exported for the CLI, which carries
|
|
86
|
+
* these settings in the launcher, keeps the key and reports them, and must spell the names as core reads them.
|
|
87
|
+
*/
|
|
88
|
+
export const RERANK_ENV = {
|
|
89
|
+
/** off, 0, false or no (OFF_WORDS) disable scoring but keep deduplication and source references. */
|
|
90
|
+
enabled: "AGENT_WHISKER_RERANK",
|
|
91
|
+
/** Request URL; a last path segment of rerank selects the rerank-server format (formatOf). */
|
|
92
|
+
url: "AGENT_WHISKER_RERANK_URL",
|
|
93
|
+
/** Scoring model. */
|
|
94
|
+
model: "AGENT_WHISKER_RERANK_MODEL",
|
|
95
|
+
/** API key, sent as a bearer token when not empty, for either format; when unset, Host.rerankKey gives it. */
|
|
96
|
+
key: "AGENT_WHISKER_RERANK_KEY",
|
|
97
|
+
/** Optional score threshold, a finite number; unset or blank: RERANK_THRESHOLD for a gateway, none for a rerank server. */
|
|
98
|
+
threshold: "AGENT_WHISKER_RERANK_THRESHOLD",
|
|
99
|
+
} ;
|
|
100
|
+
|
|
101
|
+
/** Fixed model prompt. The noul response is a number from 0 to 1. */
|
|
102
|
+
export const JUDGE_QUESTION = "The passage contains the information needed to answer the query";
|
|
103
|
+
|
|
104
|
+
/** Environment variable map from Host.env. */
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
/** Request format: a judge gateway or a rerank server. Both receive a bounded pool. */
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
/** Reranker request configuration. The key stays inside this module. */
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
/** The configured URL and model, or null when either is missing or blank. The key is read later (keyOf). */
|
|
114
|
+
function gatewayOf(env ) {
|
|
115
|
+
const url = env[RERANK_ENV.url];
|
|
116
|
+
const model = env[RERANK_ENV.model];
|
|
117
|
+
if (!url?.trim() || !model?.trim()) return null;
|
|
118
|
+
const fragment = url.indexOf("#");
|
|
119
|
+
const endpoint = fragment < 0 ? url : url.slice(0, fragment);
|
|
120
|
+
return {
|
|
121
|
+
url: endpoint,
|
|
122
|
+
model,
|
|
123
|
+
format: formatOf(endpoint),
|
|
124
|
+
choice: fragment >= 0 && url.slice(fragment).toLowerCase() === "#choice",
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Fallback reason, and doctor's, when Host.rerankKey throws. */
|
|
129
|
+
const KEY_UNREADABLE = "the gateway key could not be read from the key store";
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* The key to send to url: the environment's when AGENT_WHISKER_RERANK_KEY is set (an empty value included, which sends
|
|
133
|
+
* none), otherwise host.rerankKey(url)'s, the key kept for url's address ("" for null or without rerankKey); null when
|
|
134
|
+
* rerankKey throws. What it throws is not looked at, so nothing of it reaches a result.
|
|
135
|
+
*/
|
|
136
|
+
function keyOf(host , url ) {
|
|
137
|
+
const set = host.env[RERANK_ENV.key];
|
|
138
|
+
if (set !== undefined) return set;
|
|
139
|
+
try {
|
|
140
|
+
return host.rerankKey?.(url) ?? "";
|
|
141
|
+
} catch {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* "rerank" when the URL's last path segment, trailing slashes ignored, is exactly rerank; otherwise "gateway",
|
|
148
|
+
* including an unparseable URL, whose request then fails as before. No setting is needed, and a wrong choice is never
|
|
149
|
+
* silent: a server sent the other format's body answers a 4xx or an unreadable body, which falls back with its reason.
|
|
150
|
+
*/
|
|
151
|
+
function formatOf(url ) {
|
|
152
|
+
let path ;
|
|
153
|
+
try {
|
|
154
|
+
path = new URL(url).pathname;
|
|
155
|
+
} catch {
|
|
156
|
+
return "gateway";
|
|
157
|
+
}
|
|
158
|
+
return path.replace(/\/+$/u, "").split("/").at(-1) === "rerank" ? "rerank" : "gateway";
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Fallback reason for an AGENT_WHISKER_RERANK_THRESHOLD that is not a finite number. */
|
|
162
|
+
const BAD_THRESHOLD = `the threshold in ${RERANK_ENV.threshold} is not a number`;
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* The score threshold: AGENT_WHISKER_RERANK_THRESHOLD as a number when it is set and not blank, otherwise
|
|
166
|
+
* RERANK_THRESHOLD for a gateway and null (none) for a rerank server, whose score scale core cannot know: it differs
|
|
167
|
+
* between servers of one model. undefined when the variable holds anything but a finite number (Number's syntax,
|
|
168
|
+
* surrounding space ignored); the caller then falls back with BAD_THRESHOLD and sends nothing.
|
|
169
|
+
*/
|
|
170
|
+
function thresholdOf(env , format ) {
|
|
171
|
+
const raw = env[RERANK_ENV.threshold]?.trim();
|
|
172
|
+
if (!raw) return format === "gateway" ? RERANK_THRESHOLD : null;
|
|
173
|
+
const value = Number(raw);
|
|
174
|
+
return Number.isFinite(value) ? value : undefined;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The values of AGENT_WHISKER_RERANK that switch reranking off, compared trimmed and in lower case. */
|
|
178
|
+
const OFF_WORDS = new Set(["off", "0", "false", "no"]);
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Reranking is enabled unless the environment value, surrounding space trimmed and in lower case, is one of OFF_WORDS.
|
|
182
|
+
* Unset, blank, on and every other value leave it on: only a word that clearly means off stops the requests, and
|
|
183
|
+
* doctor's rerank row names any other value than on.
|
|
184
|
+
*/
|
|
185
|
+
function switchedOn(env ) {
|
|
186
|
+
return !OFF_WORDS.has((env[RERANK_ENV.enabled] ?? "").trim().toLowerCase());
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// ---------------------------------------------------------------------------
|
|
190
|
+
// Types
|
|
191
|
+
// ---------------------------------------------------------------------------
|
|
192
|
+
|
|
193
|
+
/** Shared library search arguments: core search options, a question, and a per-call reranking switch. */
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Search snapshot to pass unchanged from startLibrarySearch to finishLibrarySearch. Callers read only found.hits, which
|
|
221
|
+
* names every document the finished result can hold (for store.documentSources while the store is still open).
|
|
222
|
+
*/
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
/** A core hit, with relevance when reranking ran. */
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Passage location without its text. Pass docId, version, start, and end to
|
|
266
|
+
* readSection, or use pages for a page read.
|
|
267
|
+
*/
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Reranking outcome. On success, report candidates sent (at most RERANK_POOL), any failed passage scores, the
|
|
292
|
+
* scored candidates the result does not return by why (underThreshold: rated under the threshold, passage mode only,
|
|
293
|
+
* where the threshold drops candidates, and 0 when there is none; overLimit: the rest, which the limit left out; 0
|
|
294
|
+
* included), elapsed milliseconds from the first request, and input tokens for successful calls. Unscored candidates
|
|
295
|
+
* left out (not open, not sent, or failed) are not counted, so candidates - failed - underThreshold - overLimit scored
|
|
296
|
+
* candidates are in the result. On fallback, reason explains why scoring was skipped or could not finish.
|
|
297
|
+
*/
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Passage mode with reranking returns full text for leading hits and locations
|
|
312
|
+
* for the rest in more, up to limit in total. When no score meets the threshold,
|
|
313
|
+
* return no hits, keep only the best few locations in more, and mark confident: false. Fallback returns the original
|
|
314
|
+
* leading hits with full text, no more, and no relevance.
|
|
315
|
+
*
|
|
316
|
+
* Document mode returns locations, counts, and excerpts with no threshold
|
|
317
|
+
* filter or passage lists, and marks confident: false when no document's score,
|
|
318
|
+
* a pinned exact-title one's included, meets the threshold. Relevance is null on fallback.
|
|
319
|
+
* stale and dropped follow SearchResult.
|
|
320
|
+
*/
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Document result with a readable location, candidate chunk count, same-version
|
|
341
|
+
* copies, and an excerpt of at most 200 UTF-8 bytes. Document mode is never
|
|
342
|
+
* widened, so it has no context.
|
|
343
|
+
*/
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Reranking diagnostic for doctor. Display URLs omit credentials and query strings. format is present, as "rerank",
|
|
354
|
+
* when a rerank server answered; a gateway's result has none.
|
|
355
|
+
*/
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
// ---------------------------------------------------------------------------
|
|
363
|
+
// Search and reranking
|
|
364
|
+
// ---------------------------------------------------------------------------
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Validate query and capture results using the open store's search method.
|
|
368
|
+
* Read the reranking switch from env. Forward core options to store.search;
|
|
369
|
+
* only document is accepted if group is set. Request the full candidate window
|
|
370
|
+
* when reranking, or just limit otherwise. The leading slots agree across
|
|
371
|
+
* both paths, though the larger window can find additional copies.
|
|
372
|
+
*
|
|
373
|
+
* Return PendingLibrarySearch for finishLibrarySearch; the caller may now close
|
|
374
|
+
* the handle. This call may catch up the index but does not access the network.
|
|
375
|
+
* Widening reads the blobs pinned for the hit objects store.search returned, so a
|
|
376
|
+
* store wrapper must pass those objects through: copies come back unwidened.
|
|
377
|
+
* Throw InvalidArgument for invalid input, including question, rerank, limit, or
|
|
378
|
+
* group; propagate store.search errors such as Busy and Corrupt.
|
|
379
|
+
*/
|
|
380
|
+
export function startLibrarySearch(
|
|
381
|
+
store ,
|
|
382
|
+
query ,
|
|
383
|
+
env ,
|
|
384
|
+
) {
|
|
385
|
+
if (typeof query !== "object" || query === null || Array.isArray(query))
|
|
386
|
+
throw invalidArgument("search needs a query object");
|
|
387
|
+
const { question, rerank, maxExcerptBytes, widen, ...rest } = query;
|
|
388
|
+
const asked = checkQuestion(question);
|
|
389
|
+
if (rerank !== undefined && typeof rerank !== "boolean") throw invalidArgument("rerank must be a boolean");
|
|
390
|
+
if (widen !== undefined && typeof widen !== "boolean") throw invalidArgument("widen must be a boolean");
|
|
391
|
+
if (maxExcerptBytes !== undefined && (!Number.isSafeInteger(maxExcerptBytes) || maxExcerptBytes < 0)) {
|
|
392
|
+
throw invalidArgument("maxExcerptBytes must be a non-negative integer");
|
|
393
|
+
}
|
|
394
|
+
const limit = checkSearchLimit(rest.limit === undefined && rest.group === "document" ? 20 : rest.limit);
|
|
395
|
+
const wanted = rerank !== false && switchedOn(env);
|
|
396
|
+
const found = store.search(wanted ? { ...rest, limit: SEARCH_CANDIDATES } : rest);
|
|
397
|
+
// store.search has already checked that queries contains at least one string.
|
|
398
|
+
return {
|
|
399
|
+
found,
|
|
400
|
+
fallback: limitSearchResult(found, limit),
|
|
401
|
+
limit,
|
|
402
|
+
query: asked ?? rest.queries[0] ?? "",
|
|
403
|
+
queries: rest.queries,
|
|
404
|
+
wanted,
|
|
405
|
+
...(maxExcerptBytes === undefined ? {} : { maxExcerptBytes }),
|
|
406
|
+
...(rest.group === undefined ? {} : { group: rest.group }),
|
|
407
|
+
widen: widen === true && rest.group === undefined,
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Rerank a pending search asynchronously using Host env, fetch, and now. Optional
|
|
413
|
+
* Host timeouts override the per-request and overall deadlines. No database access;
|
|
414
|
+
* a widened search reads the pinned text blobs of its leading passages (widenHits).
|
|
415
|
+
*
|
|
416
|
+
* Skip requests when disabled, unconfigured, the threshold is not a number, or there are no open-tier candidates;
|
|
417
|
+
* only then is the key read (keyOf), and a key that cannot be read falls back too.
|
|
418
|
+
* Both formats receive the first RERANK_POOL open candidates. A gateway scores them in one noul batch and, in
|
|
419
|
+
* passage mode, compares up to RERANK_FINALISTS passing passages in one optional choice question. A failed final
|
|
420
|
+
* leaves the batch scores intact. A rerank server receives one request and falls back on any failure.
|
|
421
|
+
*
|
|
422
|
+
* Reorder scored candidates only within their former slots so unscored private notes, and open candidates not sent,
|
|
423
|
+
* stay in place. Filter scores under the threshold (thresholdOf; none for a rerank server unless set) and apply the
|
|
424
|
+
* requested cap. If no score passes, passage mode returns only the best scored locations in more and flags low confidence.
|
|
425
|
+
* Otherwise passage results include full text for leading hits and locations for the rest.
|
|
426
|
+
* Document results bypass threshold filtering. When the pending search asked to widen,
|
|
427
|
+
* the first RERANK_FULL_HITS passages with text get a context (widenHits) once their
|
|
428
|
+
* order is final, and later hits and locations inside a widened text point to it;
|
|
429
|
+
* order and membership do not change.
|
|
430
|
+
*
|
|
431
|
+
* Return LibrarySearchResult. Reranker failures produce a fallback, not a rejection.
|
|
432
|
+
* Timers and in-flight request waits are released before returning.
|
|
433
|
+
*/
|
|
434
|
+
export async function finishLibrarySearch(
|
|
435
|
+
pending ,
|
|
436
|
+
host ,
|
|
437
|
+
) {
|
|
438
|
+
const { found, fallback, limit, maxExcerptBytes } = pending;
|
|
439
|
+
const unranked = (reason ) => ({
|
|
440
|
+
...(pending.group === "document"
|
|
441
|
+
? { documents: fallback.hits.map((hit) => documentOf(hit, null, pending.queries, maxExcerptBytes)) }
|
|
442
|
+
: widened(
|
|
443
|
+
pending,
|
|
444
|
+
fallback.hits,
|
|
445
|
+
fallback.hits.map((hit) => clipHit(hit, maxExcerptBytes, pending.queries)),
|
|
446
|
+
)),
|
|
447
|
+
rerank: { applied: false, reason },
|
|
448
|
+
stale: found.stale,
|
|
449
|
+
dropped: fallback.dropped,
|
|
450
|
+
});
|
|
451
|
+
if (!pending.wanted) return unranked("switched off");
|
|
452
|
+
const gateway = gatewayOf(host.env);
|
|
453
|
+
if (gateway === null) return unranked("not configured");
|
|
454
|
+
const threshold = thresholdOf(host.env, gateway.format);
|
|
455
|
+
if (threshold === undefined) return unranked(BAD_THRESHOLD);
|
|
456
|
+
if (found.hits.length === 0) return unranked("no candidates");
|
|
457
|
+
const open = [];
|
|
458
|
+
found.hits.forEach((hit, position) => {
|
|
459
|
+
if (hit.tier === "open") open.push(position);
|
|
460
|
+
});
|
|
461
|
+
if (open.length === 0) return unranked("no open candidates");
|
|
462
|
+
const key = keyOf(host, gateway.url);
|
|
463
|
+
if (key === null) return unranked(KEY_UNREADABLE);
|
|
464
|
+
|
|
465
|
+
const sent = open.slice(0, RERANK_POOL);
|
|
466
|
+
const passages = sent.map((position) => passageOf(found.hits[position]));
|
|
467
|
+
const started = host.now();
|
|
468
|
+
const judged =
|
|
469
|
+
gateway.format === "rerank"
|
|
470
|
+
? await rankPool(host.fetch, { ...gateway, key }, pending.query, passages, host.rerankTimeouts?.totalMs)
|
|
471
|
+
: await judgeAll(
|
|
472
|
+
host.fetch,
|
|
473
|
+
{ ...gateway, key },
|
|
474
|
+
pending.query,
|
|
475
|
+
passages,
|
|
476
|
+
pending.group === "document" ? null : threshold,
|
|
477
|
+
host.rerankTimeouts,
|
|
478
|
+
);
|
|
479
|
+
if ("reason" in judged) return unranked(judged.reason);
|
|
480
|
+
const ms = host.now() - started;
|
|
481
|
+
|
|
482
|
+
// Use null for candidates that were not sent or whose scoring failed.
|
|
483
|
+
const scores = found.hits.map(() => null);
|
|
484
|
+
sent.forEach((position, index) => {
|
|
485
|
+
scores[position] = judged.scores[index] ?? null;
|
|
486
|
+
});
|
|
487
|
+
// Without a threshold every score passes: nothing is dropped and the answer is never unsure.
|
|
488
|
+
const passes = (score ) => threshold === null || score >= threshold;
|
|
489
|
+
const scoreAt = (position ) => scores[position] ?? Number.NEGATIVE_INFINITY;
|
|
490
|
+
|
|
491
|
+
// Only an explicit choice breaks a score tie; otherwise preserve retrieval order.
|
|
492
|
+
const scored = found.hits
|
|
493
|
+
.map((_, position) => position)
|
|
494
|
+
.filter(
|
|
495
|
+
(position) => scores[position] !== null && !(pending.group === "document" && found.hits[position]?.titleMatch),
|
|
496
|
+
);
|
|
497
|
+
const winner = judged.winner === undefined ? undefined : sent[judged.winner];
|
|
498
|
+
const byScore = [...scored].sort((a, b) => scoreAt(b) - scoreAt(a) || Number(b === winner) - Number(a === winner));
|
|
499
|
+
const order = found.hits.map((_, position) => position);
|
|
500
|
+
scored.forEach((slot, index) => {
|
|
501
|
+
order[slot] = byScore[index] ?? slot;
|
|
502
|
+
});
|
|
503
|
+
|
|
504
|
+
// Pinned exact-title documents keep their slots, but their scores still count toward confidence.
|
|
505
|
+
const confident = scores.some((score) => score !== null && passes(score));
|
|
506
|
+
// Scored candidates the result leaves out, by why: under the threshold (passage mode only, where it drops
|
|
507
|
+
// candidates; 0 without one), else the limit. Candidates not sent are unscored and not counted.
|
|
508
|
+
const report = (returned ) => {
|
|
509
|
+
const kept = new Set(returned);
|
|
510
|
+
const left = scores.flatMap((score, position) => (score === null || kept.has(position) ? [] : [score]));
|
|
511
|
+
const under = pending.group === "document" ? null : left.filter((score) => !passes(score)).length;
|
|
512
|
+
return {
|
|
513
|
+
applied: true,
|
|
514
|
+
candidates: sent.length,
|
|
515
|
+
...(judged.failed > 0 ? { failed: judged.failed } : {}),
|
|
516
|
+
...(under === null ? {} : { underThreshold: under }),
|
|
517
|
+
overLimit: left.length - (under ?? 0),
|
|
518
|
+
ms,
|
|
519
|
+
inputTokens: judged.inputTokens,
|
|
520
|
+
};
|
|
521
|
+
};
|
|
522
|
+
if (pending.group === "document") {
|
|
523
|
+
const returned = order.slice(0, limit).filter((position) => found.hits[position] !== undefined);
|
|
524
|
+
return {
|
|
525
|
+
documents: returned.flatMap((position) => {
|
|
526
|
+
const hit = found.hits[position];
|
|
527
|
+
return hit === undefined ? [] : [documentOf(hit, scores[position] ?? null, pending.queries, maxExcerptBytes)];
|
|
528
|
+
}),
|
|
529
|
+
...(confident ? {} : { confident: false }),
|
|
530
|
+
rerank: report(returned),
|
|
531
|
+
stale: found.stale,
|
|
532
|
+
dropped: found.dropped,
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
const slots = limit - fallback.dropped;
|
|
536
|
+
const kept = confident
|
|
537
|
+
? order
|
|
538
|
+
.filter((position) => {
|
|
539
|
+
const score = scores[position] ?? null;
|
|
540
|
+
return score === null ? fallback.hits.some((hit) => hit === found.hits[position]) : passes(score);
|
|
541
|
+
})
|
|
542
|
+
.slice(0, slots)
|
|
543
|
+
: byScore.slice(0, Math.min(RERANK_UNSURE_HITS, slots));
|
|
544
|
+
|
|
545
|
+
const hits = [];
|
|
546
|
+
const shown = [];
|
|
547
|
+
const more = [];
|
|
548
|
+
const returned = [];
|
|
549
|
+
for (const position of kept) {
|
|
550
|
+
const hit = found.hits[position];
|
|
551
|
+
if (hit === undefined) continue;
|
|
552
|
+
returned.push(position);
|
|
553
|
+
const score = scores[position] ?? null;
|
|
554
|
+
const relevance = score === null ? null : Math.round(score * 100) / 100;
|
|
555
|
+
if (confident && hits.length < RERANK_FULL_HITS) {
|
|
556
|
+
hits.push(clipHit({ ...hit, relevance }, maxExcerptBytes, pending.queries));
|
|
557
|
+
shown.push(hit);
|
|
558
|
+
} else more.push(locationOf(hit, relevance));
|
|
559
|
+
}
|
|
560
|
+
return {
|
|
561
|
+
...(confident ? widened(pending, shown, hits, more) : { hits, more, confident: false }),
|
|
562
|
+
rerank: report(returned),
|
|
563
|
+
stale: found.stale,
|
|
564
|
+
dropped: fallback.dropped,
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** Most UTF-8 bytes of a document-mode excerpt. */
|
|
569
|
+
const DOCUMENT_EXCERPT_BYTES = 200;
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Most UTF-8 bytes a text cut to a budget shows before the query word it opens at, and never more than a fifth of the
|
|
573
|
+
* budget: bytes, not characters, so multibyte text before the word cannot take the room the word needs.
|
|
574
|
+
*/
|
|
575
|
+
const EXCERPT_LEAD_BYTES = 40;
|
|
576
|
+
|
|
577
|
+
/** UTF-8 bytes of the `…` that marks a cut start. */
|
|
578
|
+
const ELLIPSIS_BYTES = 3;
|
|
579
|
+
|
|
580
|
+
/** A document entry of hit, its kept chunk: locators, score, copies and excerpt (documentExcerpt). */
|
|
581
|
+
function documentOf(
|
|
582
|
+
hit ,
|
|
583
|
+
score ,
|
|
584
|
+
queries ,
|
|
585
|
+
maxExcerptBytes = DOCUMENT_EXCERPT_BYTES,
|
|
586
|
+
) {
|
|
587
|
+
return {
|
|
588
|
+
...locationOf(hit, score === null ? null : Math.round(score * 100) / 100),
|
|
589
|
+
...(hit.titleMatch ? { titleMatch: true } : {}),
|
|
590
|
+
chunks: hit.chunks ?? 1,
|
|
591
|
+
also: hit.also ?? [],
|
|
592
|
+
excerpt: documentExcerpt(hit.text, queries, Math.min(DOCUMENT_EXCERPT_BYTES, maxExcerptBytes)),
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** A chunk's excerpt for a document entry: excerptWithin of its text with whitespace collapsed, or "". Pure. */
|
|
597
|
+
function documentExcerpt(text , queries , maxBytes ) {
|
|
598
|
+
return excerptWithin(text.replace(/\s+/gu, " ").trim(), queries, maxBytes)?.trimEnd() ?? "";
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* At most maxBytes UTF-8 bytes of text that hold the query word opening the stretch with the most distinct query words
|
|
603
|
+
* (densestWord, over the code points the budget holds at the text's mean bytes per character): the whole text when it
|
|
604
|
+
* fits; else from up to EXCERPT_LEAD_BYTES before that word (a fifth of the budget at most, whole characters), and
|
|
605
|
+
* earlier while what follows still fits, so the end of a text is shown whole, to where the budget ends at a character
|
|
606
|
+
* boundary, with `…` (counted in maxBytes) in front when it starts after the text's start. A text holding no query
|
|
607
|
+
* word is cut from its start. null when the budget cannot hold that word, with its `…` when it does not open the text:
|
|
608
|
+
* showing other text instead would pass it off as the match. Pure.
|
|
609
|
+
*/
|
|
610
|
+
function excerptWithin(text , queries , maxBytes ) {
|
|
611
|
+
const total = Buffer.byteLength(text);
|
|
612
|
+
if (total <= maxBytes) return text;
|
|
613
|
+
const points = Array.from(text);
|
|
614
|
+
const sizes = points.map((point) => Buffer.byteLength(point));
|
|
615
|
+
const lead = Math.min(EXCERPT_LEAD_BYTES, Math.floor(maxBytes / 5));
|
|
616
|
+
const word = densestWord(text, queries, Math.floor(((maxBytes - lead) * points.length) / total));
|
|
617
|
+
if (word === null) return clipBytes(text, maxBytes);
|
|
618
|
+
let wordBytes = 0;
|
|
619
|
+
for (let i = word.at; i < word.at + word.length; i++) wordBytes += sizes[i] ?? 0;
|
|
620
|
+
const room = maxBytes - wordBytes - (word.at === 0 ? 0 : ELLIPSIS_BYTES);
|
|
621
|
+
if (room < 0) return null;
|
|
622
|
+
let start = word.at;
|
|
623
|
+
let before = 0;
|
|
624
|
+
while (start > 0 && before + (sizes[start - 1] ?? 0) <= Math.min(lead, room)) {
|
|
625
|
+
start--;
|
|
626
|
+
before += sizes[start] ?? 0;
|
|
627
|
+
}
|
|
628
|
+
let tail = 0;
|
|
629
|
+
for (let i = start; i < points.length; i++) tail += sizes[i] ?? 0;
|
|
630
|
+
while (start > 0 && tail + (sizes[start - 1] ?? 0) <= maxBytes - ELLIPSIS_BYTES) {
|
|
631
|
+
start--;
|
|
632
|
+
tail += sizes[start] ?? 0;
|
|
633
|
+
}
|
|
634
|
+
if (start === 0) return clipBytes(text, maxBytes);
|
|
635
|
+
return `…${clipBytes(points.slice(start).join(""), maxBytes - ELLIPSIS_BYTES)}`;
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/**
|
|
639
|
+
* Widen a passage result when the pending search asked to: the first RERANK_FULL_HITS hits get widenHits contexts,
|
|
640
|
+
* and every later hit or more location of the same document whose matched range lies wholly inside one of those
|
|
641
|
+
* widened texts gets `context: { in }` naming the hit that holds it (partial overlap is left alone). originals are the
|
|
642
|
+
* storeSearch hit objects the shown hits were made from, in the same order. A context whose text is longer than
|
|
643
|
+
* pending.maxExcerptBytes is dropped together with the contexts pointing to it. Hits keep their own text and ranges;
|
|
644
|
+
* only the agent-facing shape leaves out text that another hit already returns. Returns new arrays; inputs unchanged.
|
|
645
|
+
*/
|
|
646
|
+
function widened(
|
|
647
|
+
pending ,
|
|
648
|
+
originals ,
|
|
649
|
+
hits ,
|
|
650
|
+
more ,
|
|
651
|
+
) {
|
|
652
|
+
if (!pending.widen) return { hits, ...(more === undefined ? {} : { more }) };
|
|
653
|
+
const contexts = widenHits(originals.slice(0, RERANK_FULL_HITS));
|
|
654
|
+
const cap = pending.maxExcerptBytes;
|
|
655
|
+
const tooLong = (context ) =>
|
|
656
|
+
cap !== undefined && context !== undefined && "text" in context && Buffer.byteLength(context.text) > cap;
|
|
657
|
+
const kept = contexts.map((context) =>
|
|
658
|
+
context === undefined || tooLong(context) || ("in" in context && tooLong(contexts[context.in]))
|
|
659
|
+
? undefined
|
|
660
|
+
: context,
|
|
661
|
+
);
|
|
662
|
+
// Carriers: kept contexts with text, with their hit's document. A later entry inside one points to it.
|
|
663
|
+
const carriers = kept.flatMap((context, index) => {
|
|
664
|
+
const hit = hits[index];
|
|
665
|
+
return context !== undefined && "text" in context && hit !== undefined
|
|
666
|
+
? [{ index, scope: hit.scope, docId: hit.docId, start: context.start, end: context.end }]
|
|
667
|
+
: [];
|
|
668
|
+
});
|
|
669
|
+
const holder = (entry ) =>
|
|
670
|
+
carriers.find(
|
|
671
|
+
(carrier) =>
|
|
672
|
+
carrier.scope === entry.scope &&
|
|
673
|
+
carrier.docId === entry.docId &&
|
|
674
|
+
carrier.start <= entry.start &&
|
|
675
|
+
entry.end <= carrier.end,
|
|
676
|
+
)?.index;
|
|
677
|
+
const widenedHits = hits.map((hit, index) => {
|
|
678
|
+
const context = kept[index];
|
|
679
|
+
if (context !== undefined) return { ...hit, context };
|
|
680
|
+
const holding = index < RERANK_FULL_HITS ? undefined : holder(hit);
|
|
681
|
+
return holding === undefined ? hit : { ...hit, context: { in: holding } };
|
|
682
|
+
});
|
|
683
|
+
const widenedMore = more?.map((item) => {
|
|
684
|
+
const holding = holder(item);
|
|
685
|
+
return holding === undefined ? item : { ...item, context: { in: holding } };
|
|
686
|
+
});
|
|
687
|
+
return { hits: widenedHits, ...(widenedMore === undefined ? {} : { more: widenedMore }) };
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/**
|
|
691
|
+
* Cut only displayed text to bytes, around the query words that made the hit (excerptWithin, "" when bytes cannot hold
|
|
692
|
+
* them), so the original byte range can still be read. Pure.
|
|
693
|
+
*/
|
|
694
|
+
function clipHit(hit , bytes , queries ) {
|
|
695
|
+
if (bytes === undefined) return hit;
|
|
696
|
+
const text = excerptWithin(hit.text, queries, bytes) ?? "";
|
|
697
|
+
return text === hit.text ? hit : { ...hit, text, textTruncated: true };
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Probe the configured scoring model for doctor using a fixed synthetic passage.
|
|
702
|
+
* Skip network I/O when disabled or unconfigured, and when the threshold is not a number or the key cannot be read
|
|
703
|
+
* (failed). Return RerankProbe without rejecting. A gateway gets one request under the per-request Host override
|
|
704
|
+
* (the overall timeout does not apply); a rerank server gets the passage as its one document under the overall
|
|
705
|
+
* override or RERANK_POOL_TIMEOUT_MS, and its ok result carries format: "rerank".
|
|
706
|
+
*/
|
|
707
|
+
export async function probeRerank(
|
|
708
|
+
host ,
|
|
709
|
+
) {
|
|
710
|
+
if (!switchedOn(host.env)) return { state: "off" };
|
|
711
|
+
const gateway = gatewayOf(host.env);
|
|
712
|
+
if (gateway === null) return { state: "not-configured" };
|
|
713
|
+
const shown = { url: displayUrl(gateway.url), model: gateway.model };
|
|
714
|
+
if (thresholdOf(host.env, gateway.format) === undefined) return { state: "failed", reason: BAD_THRESHOLD, ...shown };
|
|
715
|
+
const key = keyOf(host, gateway.url);
|
|
716
|
+
if (key === null) return { state: "failed", reason: KEY_UNREADABLE, ...shown };
|
|
717
|
+
const started = host.now();
|
|
718
|
+
if (gateway.format === "rerank") {
|
|
719
|
+
const timeoutMs = host.rerankTimeouts?.totalMs ?? RERANK_POOL_TIMEOUT_MS;
|
|
720
|
+
const ranked = await withDeadline(
|
|
721
|
+
(signal) => exchangePool(host.fetch, { ...gateway, key }, PROBE_PASSAGE.query, [PROBE_PASSAGE], signal),
|
|
722
|
+
new AbortController().signal,
|
|
723
|
+
timeoutMs,
|
|
724
|
+
);
|
|
725
|
+
if (!ranked.ok) return { state: "failed", reason: describeFailure(ranked, timeoutMs, "rerank"), ...shown };
|
|
726
|
+
return { state: "ok", ms: host.now() - started, ...shown, format: "rerank" };
|
|
727
|
+
}
|
|
728
|
+
const outcome = await withDeadline(
|
|
729
|
+
(signal) =>
|
|
730
|
+
gatewayAnswers(
|
|
731
|
+
host.fetch,
|
|
732
|
+
{ ...gateway, key },
|
|
733
|
+
PROBE_PASSAGE,
|
|
734
|
+
{ a: { type: "noul", instructions: JUDGE_QUESTION } },
|
|
735
|
+
signal,
|
|
736
|
+
),
|
|
737
|
+
new AbortController().signal,
|
|
738
|
+
host.rerankTimeouts?.callMs ?? RERANK_CALL_TIMEOUT_MS,
|
|
739
|
+
);
|
|
740
|
+
if (!outcome.ok) return { state: "failed", reason: describeFailure(outcome, host.rerankTimeouts?.callMs), ...shown };
|
|
741
|
+
if (probability(field(outcome.answers.a, "noul")) === null) {
|
|
742
|
+
return { state: "failed", reason: describeFailure({ ok: false, kind: "malformed" }), ...shown };
|
|
743
|
+
}
|
|
744
|
+
return { state: "ok", ms: host.now() - started, ...shown };
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/** Synthetic probe text, independent of user documents. */
|
|
748
|
+
const PROBE_PASSAGE = {
|
|
749
|
+
query: "What color is the sky?",
|
|
750
|
+
document: "Weather",
|
|
751
|
+
section: "Sky",
|
|
752
|
+
passage: "On a clear day, the sky is blue.",
|
|
753
|
+
};
|
|
754
|
+
|
|
755
|
+
// ---------------------------------------------------------------------------
|
|
756
|
+
// Scoring: the judge gateway and the rerank server
|
|
757
|
+
// ---------------------------------------------------------------------------
|
|
758
|
+
|
|
759
|
+
/** Only these open-tier fields leave the process; the query is shared by the entire batch. */
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
/** A failed exchange: a network, status, timeout, response-format, response-size, or cancellation failure. */
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
/** One rerank-server outcome: a score per passage, in passage order, or a failure. */
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
/** Fallback reason for a rerank server's 200 answer that parseRanking cannot read. */
|
|
774
|
+
const UNREADABLE_RANKING = "the rerank server's answer did not score every document";
|
|
775
|
+
|
|
776
|
+
function passageOf(hit ) {
|
|
777
|
+
return { document: hit?.title ?? "", section: (hit?.headings ?? []).join(" > "), passage: hit?.text ?? "" };
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
function choiceQuestion(keys ) {
|
|
781
|
+
return {
|
|
782
|
+
best: {
|
|
783
|
+
type: "choice",
|
|
784
|
+
instructions:
|
|
785
|
+
"Select the single passage in state.passages that most completely and authoritatively answers state.query, or 'none' if no passage answers it.",
|
|
786
|
+
criteria: {
|
|
787
|
+
...Object.fromEntries(keys.map((key) => [key, `Passage ${key} answers state.query`])),
|
|
788
|
+
none: "No passage in state.passages contains the information needed to answer state.query",
|
|
789
|
+
},
|
|
790
|
+
},
|
|
791
|
+
};
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* Score the batch once, then compare the strongest passing passages under the same overall deadline. A positive
|
|
796
|
+
* verdict blends scores above both the threshold and the next non-finalist. The winner receives the highest score
|
|
797
|
+
* and wins exact ties (even at threshold 1). A dominant none discounts only passages the choice actually saw.
|
|
798
|
+
* When a gateway rejects a multi-question noul batch with HTTP 400/413/500 (such as local llama-server overflowing
|
|
799
|
+
* unshared per-question prompts), fall back to single-question choice slices before giving up.
|
|
800
|
+
*/
|
|
801
|
+
async function judgeAll(
|
|
802
|
+
fetchFn ,
|
|
803
|
+
gateway ,
|
|
804
|
+
query ,
|
|
805
|
+
passages ,
|
|
806
|
+
threshold ,
|
|
807
|
+
timeouts ,
|
|
808
|
+
) {
|
|
809
|
+
const stop = new AbortController();
|
|
810
|
+
const callMs = timeouts?.callMs ?? RERANK_CALL_TIMEOUT_MS;
|
|
811
|
+
const totalTimeoutMs = timeouts?.totalMs ?? RERANK_TOTAL_TIMEOUT_MS;
|
|
812
|
+
const candidates = passages.map((passage, index) => ({ key: `p${index}`, index, passage }));
|
|
813
|
+
const ask = (items , questions ) => {
|
|
814
|
+
const state = { query, passages: Object.fromEntries(items.map(({ key, passage }) => [key, passage])) };
|
|
815
|
+
return withDeadline((signal) => gatewayAnswers(fetchFn, gateway, state, questions, signal), stop.signal, callMs);
|
|
816
|
+
};
|
|
817
|
+
const timer = setTimeout(() => stop.abort(), totalTimeoutMs);
|
|
818
|
+
try {
|
|
819
|
+
if (gateway.choice && candidates.length > 0) {
|
|
820
|
+
const tournament = await judgeByChoice(ask, candidates, threshold);
|
|
821
|
+
if ("scores" in tournament) return tournament;
|
|
822
|
+
return {
|
|
823
|
+
reason: stop.signal.aborted ? `timed out after ${totalTimeoutMs} ms` : describeFailure(tournament, callMs),
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
const batch = await ask(
|
|
827
|
+
candidates,
|
|
828
|
+
Object.fromEntries(
|
|
829
|
+
candidates.map(({ key }) => [
|
|
830
|
+
key,
|
|
831
|
+
{
|
|
832
|
+
type: "noul",
|
|
833
|
+
instructions: `Passage ${key} in state.passages contains the information needed to answer state.query`,
|
|
834
|
+
},
|
|
835
|
+
]),
|
|
836
|
+
),
|
|
837
|
+
);
|
|
838
|
+
if (!batch.ok) {
|
|
839
|
+
if (
|
|
840
|
+
!stop.signal.aborted &&
|
|
841
|
+
batch.kind === "status" &&
|
|
842
|
+
(batch.status === 400 || batch.status === 413 || batch.status === 500) &&
|
|
843
|
+
candidates.length > 1
|
|
844
|
+
) {
|
|
845
|
+
const tournament = await judgeByChoice(ask, candidates, threshold);
|
|
846
|
+
if ("scores" in tournament) return tournament;
|
|
847
|
+
}
|
|
848
|
+
return { reason: stop.signal.aborted ? `timed out after ${totalTimeoutMs} ms` : describeFailure(batch, callMs) };
|
|
849
|
+
}
|
|
850
|
+
const scores = candidates.map(({ key }) => probability(field(batch.answers[key], "noul")));
|
|
851
|
+
const failed = scores.filter((score) => score === null).length;
|
|
852
|
+
if (failed === scores.length) return { reason: describeFailure({ ok: false, kind: "malformed" }) };
|
|
853
|
+
if (failed * RERANK_FAILED_FRACTION > scores.length) {
|
|
854
|
+
return { reason: `more than a fifth of the judge calls failed (${failed} of ${scores.length})` };
|
|
855
|
+
}
|
|
856
|
+
const result = { scores, failed, inputTokens: batch.inputTokens };
|
|
857
|
+
if (threshold === null) return result;
|
|
858
|
+
const passing = candidates
|
|
859
|
+
.flatMap((candidate) => {
|
|
860
|
+
const score = scores[candidate.index];
|
|
861
|
+
return score != null && score >= threshold ? [{ ...candidate, score }] : [];
|
|
862
|
+
})
|
|
863
|
+
.sort((left, right) => right.score - left.score);
|
|
864
|
+
if (passing.length < 2) return result;
|
|
865
|
+
const finalists = passing.slice(0, RERANK_FINALISTS);
|
|
866
|
+
const keys = finalists.map(({ key }) => key);
|
|
867
|
+
const final = await ask(finalists, choiceQuestion(keys));
|
|
868
|
+
if (!final.ok) return result;
|
|
869
|
+
const verdict = parseChoice(final.answers.best, keys);
|
|
870
|
+
if (!verdict) return result;
|
|
871
|
+
result.inputTokens += final.inputTokens;
|
|
872
|
+
const { choice, probabilities } = verdict;
|
|
873
|
+
const none = probabilities.get("none") ?? 0;
|
|
874
|
+
const floor = Math.max(0, threshold, passing[RERANK_FINALISTS]?.score ?? 0);
|
|
875
|
+
for (const { index, key, score } of finalists) {
|
|
876
|
+
scores[index] =
|
|
877
|
+
choice === "none" && none >= 0.8
|
|
878
|
+
? score * (1 - none)
|
|
879
|
+
: floor + ((1 - floor) * (score + (probabilities.get(key) ?? 0))) / 2;
|
|
880
|
+
if (key === choice) result.winner = index;
|
|
881
|
+
}
|
|
882
|
+
if (result.winner !== undefined) scores[result.winner] = Math.max(...scores.map((score) => score ?? 0));
|
|
883
|
+
return result;
|
|
884
|
+
} finally {
|
|
885
|
+
clearTimeout(timer);
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* Fallback tournament using single-question choice slices of at most RERANK_CHOICE_SLICE candidates. Each request has
|
|
891
|
+
* one question, avoiding per-question prompt duplication in local systemone servers. Return the failure when any
|
|
892
|
+
* slice fails or does not answer a valid choice.
|
|
893
|
+
*/
|
|
894
|
+
async function judgeByChoice(
|
|
895
|
+
ask
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
,
|
|
899
|
+
candidates ,
|
|
900
|
+
threshold ,
|
|
901
|
+
) {
|
|
902
|
+
const slices = [];
|
|
903
|
+
for (let start = 0; start < candidates.length; start += RERANK_CHOICE_SLICE) {
|
|
904
|
+
slices.push(candidates.slice(start, start + RERANK_CHOICE_SLICE));
|
|
905
|
+
}
|
|
906
|
+
const semis = await Promise.all(slices.map((slice) => ask(slice, choiceQuestion(slice.map(({ key }) => key)))));
|
|
907
|
+
const scores = candidates.map(() => 0);
|
|
908
|
+
const advancing = [];
|
|
909
|
+
const floor = Math.min(0.95, Math.max(0.5, threshold ?? 0.5));
|
|
910
|
+
let inputTokens = 0;
|
|
911
|
+
let winner ;
|
|
912
|
+
for (const [sliceIndex, slice] of slices.entries()) {
|
|
913
|
+
const semi = semis[sliceIndex];
|
|
914
|
+
if (!semi) return { ok: false, kind: "malformed" };
|
|
915
|
+
if (!semi.ok) return semi;
|
|
916
|
+
const verdict = parseChoice(
|
|
917
|
+
semi.answers.best,
|
|
918
|
+
slice.map(({ key }) => key),
|
|
919
|
+
);
|
|
920
|
+
if (!verdict) return { ok: false, kind: "malformed" };
|
|
921
|
+
inputTokens += semi.inputTokens;
|
|
922
|
+
const none = verdict.probabilities.get("none") ?? 0;
|
|
923
|
+
const rejected = threshold !== null && verdict.choice === "none" && none >= 0.8;
|
|
924
|
+
for (const item of slice) {
|
|
925
|
+
const prob = verdict.probabilities.get(item.key) ?? 0;
|
|
926
|
+
if (rejected) {
|
|
927
|
+
scores[item.index] = Math.min(threshold * 0.98, prob * (1 - none));
|
|
928
|
+
} else if (threshold === null || item.key === verdict.choice || prob >= 0.1) {
|
|
929
|
+
const score = floor + (1 - floor) * prob;
|
|
930
|
+
scores[item.index] = score;
|
|
931
|
+
advancing.push({ ...item, score });
|
|
932
|
+
if (slices.length === 1 && item.key === verdict.choice) winner = item.index;
|
|
933
|
+
} else {
|
|
934
|
+
scores[item.index] = Math.min(threshold * 0.98, prob);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
advancing.sort((left, right) => right.score - left.score);
|
|
939
|
+
if (slices.length > 1 && threshold !== null && advancing.length >= 2) {
|
|
940
|
+
const finalists = advancing.slice(0, RERANK_FINALISTS);
|
|
941
|
+
const keys = finalists.map(({ key }) => key);
|
|
942
|
+
const final = await ask(finalists, choiceQuestion(keys));
|
|
943
|
+
if (final.ok) {
|
|
944
|
+
const verdict = parseChoice(final.answers.best, keys);
|
|
945
|
+
if (verdict) {
|
|
946
|
+
inputTokens += final.inputTokens;
|
|
947
|
+
const none = verdict.probabilities.get("none") ?? 0;
|
|
948
|
+
for (const { index, key, score } of finalists) {
|
|
949
|
+
scores[index] =
|
|
950
|
+
verdict.choice === "none" && none >= 0.8
|
|
951
|
+
? Math.min(threshold * 0.98, score * (1 - none))
|
|
952
|
+
: floor + ((1 - floor) * (score + (verdict.probabilities.get(key) ?? 0))) / 2;
|
|
953
|
+
if (key === verdict.choice) winner = index;
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
if (winner !== undefined) scores[winner] = Math.max(...scores.map((score) => score ?? 0));
|
|
959
|
+
return { scores, failed: 0, inputTokens, ...(winner === undefined ? {} : { winner }) };
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
function probability(value ) {
|
|
963
|
+
return typeof value === "number" && value >= 0 && value <= 1 ? value : null;
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
function parseChoice(best , keys ) {
|
|
967
|
+
const choice = field(best, "choice");
|
|
968
|
+
const values = field(best, "probabilities");
|
|
969
|
+
const options = [...keys, "none"];
|
|
970
|
+
if (
|
|
971
|
+
typeof choice !== "string" ||
|
|
972
|
+
!options.includes(choice) ||
|
|
973
|
+
!isPlainObject(values) ||
|
|
974
|
+
Object.keys(values).length !== options.length
|
|
975
|
+
) {
|
|
976
|
+
return null;
|
|
977
|
+
}
|
|
978
|
+
const probabilities = new Map ();
|
|
979
|
+
for (const key of options) {
|
|
980
|
+
const value = probability(field(values, key));
|
|
981
|
+
if (value === null) return null;
|
|
982
|
+
probabilities.set(key, value);
|
|
983
|
+
}
|
|
984
|
+
return { choice, probabilities };
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* Score the pool in one rerank-server request within timeoutMs (default RERANK_POOL_TIMEOUT_MS), returning a score
|
|
989
|
+
* per passage in passage order and the server's token count, or the fallback reason: `timed out after <ms> ms`, or
|
|
990
|
+
* the failure's description. All or nothing, so failed is always 0. Requires at least one passage.
|
|
991
|
+
*/
|
|
992
|
+
async function rankPool(
|
|
993
|
+
fetchFn ,
|
|
994
|
+
gateway ,
|
|
995
|
+
query ,
|
|
996
|
+
passages ,
|
|
997
|
+
timeoutMs = RERANK_POOL_TIMEOUT_MS,
|
|
998
|
+
) {
|
|
999
|
+
const outcome = await withDeadline(
|
|
1000
|
+
(signal) => exchangePool(fetchFn, gateway, query, passages, signal),
|
|
1001
|
+
new AbortController().signal,
|
|
1002
|
+
timeoutMs,
|
|
1003
|
+
);
|
|
1004
|
+
if (outcome.ok) return { scores: outcome.scores, failed: 0, inputTokens: outcome.inputTokens };
|
|
1005
|
+
return {
|
|
1006
|
+
reason:
|
|
1007
|
+
outcome.kind === "timeout" ? `timed out after ${timeoutMs} ms` : describeFailure(outcome, timeoutMs, "rerank"),
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
/**
|
|
1012
|
+
* Run one exchange with a deadline and a shared stop signal; return its outcome, or a Failure instead of rejecting.
|
|
1013
|
+
* Race the abort because a fetch implementation may ignore its signal. Promise.race handles a later rejection from
|
|
1014
|
+
* the losing promise. Clear the timer, detach the stop listener, and abort the request before returning.
|
|
1015
|
+
*/
|
|
1016
|
+
async function withDeadline (
|
|
1017
|
+
send ,
|
|
1018
|
+
stop ,
|
|
1019
|
+
timeoutMs ,
|
|
1020
|
+
) {
|
|
1021
|
+
if (stop.aborted) return { ok: false, kind: "stopped" };
|
|
1022
|
+
const controller = new AbortController();
|
|
1023
|
+
let cause = null;
|
|
1024
|
+
const abort = (why ) => {
|
|
1025
|
+
cause ??= why;
|
|
1026
|
+
controller.abort();
|
|
1027
|
+
};
|
|
1028
|
+
const timer = setTimeout(() => abort("timeout"), timeoutMs);
|
|
1029
|
+
const onStop = () => abort("stopped");
|
|
1030
|
+
stop.addEventListener("abort", onStop, { once: true });
|
|
1031
|
+
const aborted = new Promise ((_, reject) => {
|
|
1032
|
+
controller.signal.addEventListener("abort", () => reject(new Error("aborted")), { once: true });
|
|
1033
|
+
});
|
|
1034
|
+
try {
|
|
1035
|
+
return await Promise.race([send(controller.signal), aborted]);
|
|
1036
|
+
} catch (error) {
|
|
1037
|
+
if (cause !== null) return { ok: false, kind: cause };
|
|
1038
|
+
return { ok: false, kind: "unreachable", code: errorCode(error) };
|
|
1039
|
+
} finally {
|
|
1040
|
+
clearTimeout(timer);
|
|
1041
|
+
stop.removeEventListener("abort", onStop);
|
|
1042
|
+
// A non-200 response still needs to release its body and connection.
|
|
1043
|
+
controller.abort();
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/** Read a bounded JSON reply. Fetch and response-read errors propagate to withDeadline. */
|
|
1048
|
+
async function postJson(
|
|
1049
|
+
fetchFn ,
|
|
1050
|
+
gateway ,
|
|
1051
|
+
payload ,
|
|
1052
|
+
signal ,
|
|
1053
|
+
) {
|
|
1054
|
+
const response = await fetchFn(gateway.url, {
|
|
1055
|
+
method: "POST",
|
|
1056
|
+
headers: headersOf(gateway),
|
|
1057
|
+
body: JSON.stringify({ model: gateway.model, ...payload }),
|
|
1058
|
+
signal,
|
|
1059
|
+
});
|
|
1060
|
+
if (response.status !== 200) return { ok: false, kind: "status", status: response.status };
|
|
1061
|
+
const body = await answerText(response.body);
|
|
1062
|
+
if (body === null) return { ok: false, kind: "large" };
|
|
1063
|
+
try {
|
|
1064
|
+
return { ok: true, value: JSON.parse(body) };
|
|
1065
|
+
} catch {
|
|
1066
|
+
return { ok: false, kind: "malformed" };
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
async function gatewayAnswers(
|
|
1071
|
+
fetchFn ,
|
|
1072
|
+
gateway ,
|
|
1073
|
+
state ,
|
|
1074
|
+
questions ,
|
|
1075
|
+
signal ,
|
|
1076
|
+
) {
|
|
1077
|
+
const reply = await postJson(fetchFn, gateway, { state, questions }, signal);
|
|
1078
|
+
if (!reply.ok) return reply;
|
|
1079
|
+
const answers = field(reply.value, "answers");
|
|
1080
|
+
if (!isPlainObject(answers)) return { ok: false, kind: "malformed" };
|
|
1081
|
+
return { ok: true, answers, inputTokens: tokenCount(field(field(reply.value, "usage"), "input_tokens")) };
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
/**
|
|
1085
|
+
* POST the model, the question once, and one document per passage (rerankDocument), with a bearer key when set, and
|
|
1086
|
+
* nothing else: some servers refuse unknown fields, and without top_n every document is scored. Return a status
|
|
1087
|
+
* failure for a non-200 response, large for a body over ANSWER_MAX_BYTES, or malformed for an answer parseRanking
|
|
1088
|
+
* cannot read. Fetch and response-read errors propagate to withDeadline.
|
|
1089
|
+
*/
|
|
1090
|
+
async function exchangePool(
|
|
1091
|
+
fetchFn ,
|
|
1092
|
+
gateway ,
|
|
1093
|
+
query ,
|
|
1094
|
+
passages ,
|
|
1095
|
+
signal ,
|
|
1096
|
+
) {
|
|
1097
|
+
const reply = await postJson(fetchFn, gateway, { query, documents: passages.map(rerankDocument) }, signal);
|
|
1098
|
+
if (!reply.ok) return reply;
|
|
1099
|
+
const answer = parseRanking(reply.value, passages.length);
|
|
1100
|
+
return answer === null ? { ok: false, kind: "malformed" } : { ok: true, ...answer };
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
/**
|
|
1104
|
+
* A 200 answer's body as text, decoded as Response.text() decodes it (a leading BOM dropped, invalid UTF-8
|
|
1105
|
+
* replaced), or null once it is longer than ANSWER_MAX_BYTES: leaving the loop there cancels the rest of the stream.
|
|
1106
|
+
* A stream error rejects, for withDeadline to report.
|
|
1107
|
+
*/
|
|
1108
|
+
export async function answerText(body ) {
|
|
1109
|
+
if (body === null) return "";
|
|
1110
|
+
const decoder = new TextDecoder();
|
|
1111
|
+
let bytes = 0;
|
|
1112
|
+
let text = "";
|
|
1113
|
+
for await (const chunk of body) {
|
|
1114
|
+
bytes += chunk.byteLength;
|
|
1115
|
+
if (bytes > ANSWER_MAX_BYTES) return null;
|
|
1116
|
+
text += decoder.decode(chunk, { stream: true });
|
|
1117
|
+
}
|
|
1118
|
+
return text + decoder.decode();
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
/**
|
|
1122
|
+
* The text a rerank server reads for one passage: title, section path and chunk, joined by newlines, the empty line
|
|
1123
|
+
* kept when there is no section. evals/content/tools/score_candidates.py --backend rerank sends the same string, so
|
|
1124
|
+
* scores saved with the eval tools are scores of what core sends.
|
|
1125
|
+
*/
|
|
1126
|
+
function rerankDocument(passage ) {
|
|
1127
|
+
return `${passage.document}\n${passage.section}\n${passage.passage}`;
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
/**
|
|
1131
|
+
* Read one finite relevance_score per document from results, in any order, each index an integer below count given
|
|
1132
|
+
* exactly once, and usage.total_tokens (0 when absent or not a positive number). Return null for any other shape.
|
|
1133
|
+
*/
|
|
1134
|
+
function parseRanking(parsed , count ) {
|
|
1135
|
+
const results = field(parsed, "results");
|
|
1136
|
+
if (!Array.isArray(results) || results.length !== count) return null;
|
|
1137
|
+
const scores = Array.from({ length: count }, () => 0);
|
|
1138
|
+
const seen = new Set ();
|
|
1139
|
+
for (const item of results) {
|
|
1140
|
+
const index = field(item, "index");
|
|
1141
|
+
const score = field(item, "relevance_score");
|
|
1142
|
+
if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= count || seen.has(index)) {
|
|
1143
|
+
return null;
|
|
1144
|
+
}
|
|
1145
|
+
if (typeof score !== "number" || !Number.isFinite(score)) return null;
|
|
1146
|
+
seen.add(index);
|
|
1147
|
+
scores[index] = score;
|
|
1148
|
+
}
|
|
1149
|
+
return { scores, inputTokens: tokenCount(field(field(parsed, "usage"), "total_tokens")) };
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
/** Request headers: a bearer key when one is set and not empty, and the JSON content type. */
|
|
1153
|
+
function headersOf(gateway ) {
|
|
1154
|
+
return {
|
|
1155
|
+
...(gateway.key === "" ? {} : { authorization: `Bearer ${gateway.key}` }),
|
|
1156
|
+
"content-type": "application/json",
|
|
1157
|
+
};
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
/** A reported token count: a finite positive number, otherwise 0. */
|
|
1161
|
+
function tokenCount(value ) {
|
|
1162
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
/** Read key from a plain object, or return undefined. */
|
|
1166
|
+
function field(value , key ) {
|
|
1167
|
+
if (!isPlainObject(value)) return undefined;
|
|
1168
|
+
return (value )[key];
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
/**
|
|
1172
|
+
* Describe a scoring failure using only status and error codes. Raw errors may
|
|
1173
|
+
* contain URLs or headers. Keep the 401, 403, and 404 guidance distinct because
|
|
1174
|
+
* credentials, the endpoint, and the model may need different fixes; a redirect names the setting to change, not the
|
|
1175
|
+
* address it names, whose query string may hold a key. Only an unreadable or
|
|
1176
|
+
* too long answer is described by format; the other reasons are the gateway's, for either format.
|
|
1177
|
+
*/
|
|
1178
|
+
function describeFailure(outcome , callTimeoutMs = RERANK_CALL_TIMEOUT_MS, format = "gateway") {
|
|
1179
|
+
switch (outcome.kind) {
|
|
1180
|
+
case "unreachable":
|
|
1181
|
+
return `the gateway is unreachable (${outcome.code})`;
|
|
1182
|
+
case "status":
|
|
1183
|
+
if (outcome.status === 401 || outcome.status === 403) {
|
|
1184
|
+
return `the gateway rejected the key (HTTP ${outcome.status})`;
|
|
1185
|
+
}
|
|
1186
|
+
if (outcome.status === 404) return "the gateway has no such model or path (HTTP 404)";
|
|
1187
|
+
if (outcome.status >= 300 && outcome.status < 400) {
|
|
1188
|
+
return `the gateway answered a redirect (HTTP ${outcome.status}), which is not followed; set ${RERANK_ENV.url} to the final address`;
|
|
1189
|
+
}
|
|
1190
|
+
return `the gateway answered HTTP ${outcome.status}`;
|
|
1191
|
+
case "timeout":
|
|
1192
|
+
return `the judge model did not answer within ${callTimeoutMs} ms`;
|
|
1193
|
+
case "malformed":
|
|
1194
|
+
return format === "rerank" ? UNREADABLE_RANKING : "the gateway's answer was not a judge score";
|
|
1195
|
+
case "large":
|
|
1196
|
+
return `${format === "rerank" ? "the rerank server's" : "the gateway's"} answer was longer than ${ANSWER_MAX_BYTES} bytes`;
|
|
1197
|
+
case "stopped":
|
|
1198
|
+
return "stopped";
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
|
|
1202
|
+
/**
|
|
1203
|
+
* Extract a network error code from cause.code, code, or the error name.
|
|
1204
|
+
* Allow only short alphanumeric or underscore codes; otherwise use unknown.
|
|
1205
|
+
*/
|
|
1206
|
+
function errorCode(error ) {
|
|
1207
|
+
const cause = error instanceof Error ? error.cause : undefined;
|
|
1208
|
+
const name = error instanceof Error ? error.name : undefined;
|
|
1209
|
+
for (const candidate of [field(cause, "code"), field(error, "code"), name]) {
|
|
1210
|
+
if (typeof candidate === "string" && /^[A-Za-z0-9_]{1,40}$/.test(candidate)) return candidate;
|
|
1211
|
+
}
|
|
1212
|
+
return "unknown";
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
/**
|
|
1216
|
+
* Keep only scheme, host, port, and path for display. Credentials and query
|
|
1217
|
+
* strings may contain secrets. Never echo an unparseable URL.
|
|
1218
|
+
*/
|
|
1219
|
+
export function displayUrl(url ) {
|
|
1220
|
+
try {
|
|
1221
|
+
const parsed = new URL(url);
|
|
1222
|
+
return `${parsed.protocol}//${parsed.host}${parsed.pathname}`;
|
|
1223
|
+
} catch {
|
|
1224
|
+
return "(not a valid URL)";
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
// ---------------------------------------------------------------------------
|
|
1229
|
+
// Validation
|
|
1230
|
+
// ---------------------------------------------------------------------------
|
|
1231
|
+
|
|
1232
|
+
/**
|
|
1233
|
+
* Return the original question, or undefined if absent or blank.
|
|
1234
|
+
* Throw InvalidArgument for invalid input, as described in startLibrarySearch.
|
|
1235
|
+
*/
|
|
1236
|
+
function checkQuestion(question ) {
|
|
1237
|
+
if (question === undefined) return undefined;
|
|
1238
|
+
if (typeof question !== "string") throw invalidArgument("question must be a string");
|
|
1239
|
+
if (!question.isWellFormed()) throw invalidArgument("question must be well-formed Unicode");
|
|
1240
|
+
if (Buffer.byteLength(question) > QUESTION_MAX_BYTES) {
|
|
1241
|
+
throw invalidArgument(`question must be at most ${QUESTION_MAX_BYTES} bytes of UTF-8`);
|
|
1242
|
+
}
|
|
1243
|
+
return question.trim() === "" ? undefined : question;
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
function locationOf(hit , relevance ) {
|
|
1247
|
+
return {
|
|
1248
|
+
docId: hit.docId,
|
|
1249
|
+
version: hit.version,
|
|
1250
|
+
scope: hit.scope,
|
|
1251
|
+
title: hit.title,
|
|
1252
|
+
source: hit.source,
|
|
1253
|
+
ordinal: hit.ordinal,
|
|
1254
|
+
section: hit.section,
|
|
1255
|
+
headings: hit.headings,
|
|
1256
|
+
start: hit.start,
|
|
1257
|
+
end: hit.end,
|
|
1258
|
+
score: hit.score,
|
|
1259
|
+
matchedQueries: hit.matchedQueries,
|
|
1260
|
+
...(hit.pages === undefined ? {} : { pages: hit.pages }),
|
|
1261
|
+
relevance,
|
|
1262
|
+
};
|
|
1263
|
+
}
|