@midscene/core 1.17.2 → 1.17.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/es/agent/utils.mjs +1 -1
- package/dist/es/ai-model/model-adapter/resolve.mjs +2 -2
- package/dist/es/ai-model/model-adapter/resolve.mjs.map +1 -1
- package/dist/es/ai-model/models/ant-ling/adapter.mjs +51 -0
- package/dist/es/ai-model/models/ant-ling/adapter.mjs.map +1 -0
- package/dist/es/ai-model/models/jev/adapter.mjs +1 -1
- package/dist/es/ai-model/models/jev/adapter.mjs.map +1 -1
- package/dist/es/ai-model/models/model-fallback.mjs +2 -2
- package/dist/es/ai-model/models/model-fallback.mjs.map +1 -1
- package/dist/es/ai-model/models/registry.mjs +2 -0
- package/dist/es/ai-model/models/registry.mjs.map +1 -1
- package/dist/es/dump/execution-recorder.mjs +70 -0
- package/dist/es/dump/execution-recorder.mjs.map +1 -0
- package/dist/es/dump/html-utils.mjs +51 -1
- package/dist/es/dump/html-utils.mjs.map +1 -1
- package/dist/es/dump/report-artifact-reader.mjs +85 -0
- package/dist/es/dump/report-artifact-reader.mjs.map +1 -0
- package/dist/es/dump/report-artifact-store.mjs +164 -0
- package/dist/es/dump/report-artifact-store.mjs.map +1 -0
- package/dist/es/dump/screenshot-store.mjs +40 -15
- package/dist/es/dump/screenshot-store.mjs.map +1 -1
- package/dist/es/dump/test-report-images.mjs +120 -0
- package/dist/es/dump/test-report-images.mjs.map +1 -0
- package/dist/es/report-cli.mjs +8 -7
- package/dist/es/report-cli.mjs.map +1 -1
- package/dist/es/report-generator.mjs +56 -47
- package/dist/es/report-generator.mjs.map +1 -1
- package/dist/es/report-html-template.mjs +1 -1
- package/dist/es/report.mjs +29 -55
- package/dist/es/report.mjs.map +1 -1
- package/dist/es/test-run-report.mjs.map +1 -1
- package/dist/es/utils.mjs +1 -1
- package/dist/lib/agent/utils.js +1 -1
- package/dist/lib/ai-model/model-adapter/resolve.js +2 -2
- package/dist/lib/ai-model/model-adapter/resolve.js.map +1 -1
- package/dist/lib/ai-model/models/ant-ling/adapter.js +85 -0
- package/dist/lib/ai-model/models/ant-ling/adapter.js.map +1 -0
- package/dist/lib/ai-model/models/jev/adapter.js +1 -1
- package/dist/lib/ai-model/models/jev/adapter.js.map +1 -1
- package/dist/lib/ai-model/models/model-fallback.js +2 -2
- package/dist/lib/ai-model/models/model-fallback.js.map +1 -1
- package/dist/lib/ai-model/models/registry.js +4 -2
- package/dist/lib/ai-model/models/registry.js.map +1 -1
- package/dist/lib/dump/execution-recorder.js +104 -0
- package/dist/lib/dump/execution-recorder.js.map +1 -0
- package/dist/lib/dump/html-utils.js +67 -5
- package/dist/lib/dump/html-utils.js.map +1 -1
- package/dist/lib/dump/report-artifact-reader.js +134 -0
- package/dist/lib/dump/report-artifact-reader.js.map +1 -0
- package/dist/lib/dump/report-artifact-store.js +204 -0
- package/dist/lib/dump/report-artifact-store.js.map +1 -0
- package/dist/lib/dump/screenshot-store.js +42 -14
- package/dist/lib/dump/screenshot-store.js.map +1 -1
- package/dist/lib/dump/test-report-images.js +154 -0
- package/dist/lib/dump/test-report-images.js.map +1 -0
- package/dist/lib/report-cli.js +8 -7
- package/dist/lib/report-cli.js.map +1 -1
- package/dist/lib/report-generator.js +54 -45
- package/dist/lib/report-generator.js.map +1 -1
- package/dist/lib/report-html-template.js +1 -1
- package/dist/lib/report.js +54 -56
- package/dist/lib/report.js.map +1 -1
- package/dist/lib/test-run-report.js.map +1 -1
- package/dist/lib/utils.js +1 -1
- package/dist/types/ai-model/model-adapter/resolve.d.ts +1 -1
- package/dist/types/ai-model/model-adapter/resolve.d.ts.map +1 -1
- package/dist/types/ai-model/model-adapter/types.d.ts +4 -2
- package/dist/types/ai-model/model-adapter/types.d.ts.map +1 -1
- package/dist/types/ai-model/models/ant-ling/adapter.d.ts +23 -0
- package/dist/types/ai-model/models/ant-ling/adapter.d.ts.map +1 -0
- package/dist/types/ai-model/models/jev/adapter.d.ts +1 -1
- package/dist/types/ai-model/models/registry.d.ts +20 -1
- package/dist/types/ai-model/models/registry.d.ts.map +1 -1
- package/dist/types/dump/execution-recorder.d.ts +23 -0
- package/dist/types/dump/execution-recorder.d.ts.map +1 -0
- package/dist/types/dump/html-utils.d.ts +9 -0
- package/dist/types/dump/html-utils.d.ts.map +1 -1
- package/dist/types/dump/report-artifact-reader.d.ts +19 -0
- package/dist/types/dump/report-artifact-reader.d.ts.map +1 -0
- package/dist/types/dump/report-artifact-store.d.ts +22 -0
- package/dist/types/dump/report-artifact-store.d.ts.map +1 -0
- package/dist/types/dump/screenshot-store.d.ts +6 -0
- package/dist/types/dump/screenshot-store.d.ts.map +1 -1
- package/dist/types/dump/test-report-images.d.ts +14 -0
- package/dist/types/dump/test-report-images.d.ts.map +1 -0
- package/dist/types/report-cli.d.ts.map +1 -1
- package/dist/types/report-generator.d.ts +4 -3
- package/dist/types/report-generator.d.ts.map +1 -1
- package/dist/types/report.d.ts +3 -0
- package/dist/types/report.d.ts.map +1 -1
- package/dist/types/test-run-report.d.ts +2 -0
- package/dist/types/test-run-report.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/es/agent/utils.mjs
CHANGED
|
@@ -153,7 +153,7 @@ async function matchElementFromCache(context, cacheEntry, cachePrompt, cacheable
|
|
|
153
153
|
return;
|
|
154
154
|
}
|
|
155
155
|
}
|
|
156
|
-
const getMidsceneVersion = ()=>"1.17.
|
|
156
|
+
const getMidsceneVersion = ()=>"1.17.3";
|
|
157
157
|
const parsePrompt = (prompt)=>{
|
|
158
158
|
if ('string' == typeof prompt) return {
|
|
159
159
|
textPrompt: prompt,
|
|
@@ -29,7 +29,7 @@ function resolveImagePreprocess(imagePreprocess) {
|
|
|
29
29
|
class ResolvedModelAdapter {
|
|
30
30
|
constructor(config, modelFamily){
|
|
31
31
|
_define_property(this, "modelType", void 0);
|
|
32
|
-
_define_property(this, "
|
|
32
|
+
_define_property(this, "allowedTaskTypes", void 0);
|
|
33
33
|
_define_property(this, "supportedProtocols", void 0);
|
|
34
34
|
_define_property(this, "jsonParser", void 0);
|
|
35
35
|
_define_property(this, "chatCompletion", void 0);
|
|
@@ -41,7 +41,7 @@ class ResolvedModelAdapter {
|
|
|
41
41
|
_define_property(this, "planning", void 0);
|
|
42
42
|
_define_property(this, "locate", void 0);
|
|
43
43
|
this.modelType = config.modelType ?? 'generative';
|
|
44
|
-
this.
|
|
44
|
+
this.allowedTaskTypes = config.allowedTaskTypes;
|
|
45
45
|
this.supportedProtocols = config.supportedProtocols ?? [
|
|
46
46
|
'openai-chat'
|
|
47
47
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-model/model-adapter/resolve.mjs","sources":["../../../../src/ai-model/model-adapter/resolve.ts"],"sourcesContent":["import { parseModelResponseJson } from '../shared/json';\nimport { resolveChatCompletion } from './chat-completion';\nimport { buildDefaultCodexAppServerParams } from './codex-app-server';\nimport { resolveInsight } from './insight';\nimport type { InsightAdapter } from './insight-protocol';\nimport { resolveLocate } from './locate';\nimport { resolveCustomPlanningDefinition, resolvePlanning } from './planning';\nimport { resolveResponses } from './responses';\nimport type {\n BuildCodexAppServerParams,\n ChatCompletionAdapter,\n ImagePreprocessPolicy,\n JsonParser,\n LocateAdapter,\n ModelAdapter,\n ModelAdapterDefinition,\n PlanningAdapter,\n ResolveImageDetail,\n ResponsesAdapter,\n} from './types';\n\nconst defaultImageDetail: ResolveImageDetail = ({ imageDetail }) =>\n imageDetail ?? 'high';\n\nfunction resolveJsonParser(\n jsonParser: ModelAdapterDefinition['jsonParser'],\n): JsonParser {\n if (!jsonParser || jsonParser === 'lenient-json') {\n return parseModelResponseJson;\n }\n\n if (typeof jsonParser === 'function') {\n return jsonParser;\n }\n\n throw new Error(`Unknown json parser preset: ${jsonParser}`);\n}\n\nfunction resolveImagePreprocess(\n imagePreprocess: ModelAdapterDefinition['imagePreprocess'],\n): ImagePreprocessPolicy {\n return {\n padBlockSize: imagePreprocess?.padBlockSize,\n };\n}\n\nexport class ResolvedModelAdapter implements ModelAdapter {\n readonly modelType: ModelAdapter['modelType'];\n readonly
|
|
1
|
+
{"version":3,"file":"ai-model/model-adapter/resolve.mjs","sources":["../../../../src/ai-model/model-adapter/resolve.ts"],"sourcesContent":["import { parseModelResponseJson } from '../shared/json';\nimport { resolveChatCompletion } from './chat-completion';\nimport { buildDefaultCodexAppServerParams } from './codex-app-server';\nimport { resolveInsight } from './insight';\nimport type { InsightAdapter } from './insight-protocol';\nimport { resolveLocate } from './locate';\nimport { resolveCustomPlanningDefinition, resolvePlanning } from './planning';\nimport { resolveResponses } from './responses';\nimport type {\n BuildCodexAppServerParams,\n ChatCompletionAdapter,\n ImagePreprocessPolicy,\n JsonParser,\n LocateAdapter,\n ModelAdapter,\n ModelAdapterDefinition,\n PlanningAdapter,\n ResolveImageDetail,\n ResponsesAdapter,\n} from './types';\n\nconst defaultImageDetail: ResolveImageDetail = ({ imageDetail }) =>\n imageDetail ?? 'high';\n\nfunction resolveJsonParser(\n jsonParser: ModelAdapterDefinition['jsonParser'],\n): JsonParser {\n if (!jsonParser || jsonParser === 'lenient-json') {\n return parseModelResponseJson;\n }\n\n if (typeof jsonParser === 'function') {\n return jsonParser;\n }\n\n throw new Error(`Unknown json parser preset: ${jsonParser}`);\n}\n\nfunction resolveImagePreprocess(\n imagePreprocess: ModelAdapterDefinition['imagePreprocess'],\n): ImagePreprocessPolicy {\n return {\n padBlockSize: imagePreprocess?.padBlockSize,\n };\n}\n\nexport class ResolvedModelAdapter implements ModelAdapter {\n readonly modelType: ModelAdapter['modelType'];\n readonly allowedTaskTypes: ModelAdapter['allowedTaskTypes'];\n readonly supportedProtocols: ModelAdapter['supportedProtocols'];\n readonly jsonParser: JsonParser;\n readonly chatCompletion: ChatCompletionAdapter;\n readonly resolveImageDetail: ResolveImageDetail;\n readonly responses: ResponsesAdapter;\n readonly buildCodexAppServerParams: BuildCodexAppServerParams;\n readonly imagePreprocess: ImagePreprocessPolicy;\n readonly insight: InsightAdapter;\n readonly planning: PlanningAdapter;\n readonly locate: LocateAdapter;\n\n constructor(config: ModelAdapterDefinition, modelFamily: string) {\n this.modelType = config.modelType ?? 'generative';\n this.allowedTaskTypes = config.allowedTaskTypes;\n this.supportedProtocols = config.supportedProtocols ?? ['openai-chat'];\n this.jsonParser = resolveJsonParser(config.jsonParser);\n this.chatCompletion = resolveChatCompletion(config.chatCompletion);\n this.resolveImageDetail = config.resolveImageDetail ?? defaultImageDetail;\n this.responses = resolveResponses(config.responses);\n this.buildCodexAppServerParams =\n config.buildCodexAppServerParams ?? buildDefaultCodexAppServerParams;\n this.imagePreprocess = resolveImagePreprocess(config.imagePreprocess);\n this.insight = resolveInsight(config.insight, {\n jsonParser: this.jsonParser,\n });\n const customPlanner =\n config.planning?.kind === 'custom' ? config.planning.planner : undefined;\n const resolvedCustomPlanner = customPlanner\n ? resolveCustomPlanningDefinition(customPlanner)\n : undefined;\n this.locate = resolveLocate(config.locate, resolvedCustomPlanner, {\n jsonParser: this.jsonParser,\n });\n this.planning = resolvePlanning(\n config.planning,\n resolvedCustomPlanner,\n { jsonParser: this.jsonParser },\n this.locate.kind === 'standard'\n ? this.locate.element.resultCodec\n : undefined,\n );\n }\n}\n"],"names":["defaultImageDetail","imageDetail","resolveJsonParser","jsonParser","parseModelResponseJson","Error","resolveImagePreprocess","imagePreprocess","ResolvedModelAdapter","config","modelFamily","resolveChatCompletion","resolveResponses","buildDefaultCodexAppServerParams","resolveInsight","customPlanner","undefined","resolvedCustomPlanner","resolveCustomPlanningDefinition","resolveLocate","resolvePlanning"],"mappings":";;;;;;;;;;;;;;;;;AAqBA,MAAMA,qBAAyC,CAAC,EAAEC,WAAW,EAAE,GAC7DA,eAAe;AAEjB,SAASC,kBACPC,UAAgD;IAEhD,IAAI,CAACA,cAAcA,AAAe,mBAAfA,YACjB,OAAOC;IAGT,IAAI,AAAsB,cAAtB,OAAOD,YACT,OAAOA;IAGT,MAAM,IAAIE,MAAM,CAAC,4BAA4B,EAAEF,YAAY;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EACfQ,uBACA;YAAE,YAAY,IAAI,CAAC,UAAU;QAAC,GAC9B,AAAqB,eAArB,IAAI,CAAC,MAAM,CAAC,IAAI,GACZ,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,WAAW,GAC/BD;IAER;AACF"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const buildAntLingChatCompletionParams = (input)=>{
|
|
2
|
+
const { midsceneDefaults, userConfig } = input;
|
|
3
|
+
const { reasoningEnabled } = userConfig;
|
|
4
|
+
return {
|
|
5
|
+
config: {
|
|
6
|
+
...midsceneDefaults,
|
|
7
|
+
...void 0 !== userConfig.temperature ? {
|
|
8
|
+
temperature: userConfig.temperature
|
|
9
|
+
} : {},
|
|
10
|
+
...'none' !== userConfig.responseFormat && input.expectedJsonObjectResponse ? {
|
|
11
|
+
response_format: {
|
|
12
|
+
type: 'json_object'
|
|
13
|
+
}
|
|
14
|
+
} : {},
|
|
15
|
+
...'default' !== reasoningEnabled ? {
|
|
16
|
+
thinking: {
|
|
17
|
+
type: reasoningEnabled ?? false ? 'enabled' : 'disabled'
|
|
18
|
+
}
|
|
19
|
+
} : {}
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
};
|
|
23
|
+
const antLingAdapters = {
|
|
24
|
+
'ant-ling': {
|
|
25
|
+
supportedProtocols: [
|
|
26
|
+
'openai-chat'
|
|
27
|
+
],
|
|
28
|
+
chatCompletion: {
|
|
29
|
+
unsupportedUserConfig: [
|
|
30
|
+
'reasoningEffort',
|
|
31
|
+
'reasoningBudget'
|
|
32
|
+
],
|
|
33
|
+
buildChatCompletionParams: buildAntLingChatCompletionParams
|
|
34
|
+
},
|
|
35
|
+
locate: {
|
|
36
|
+
element: {
|
|
37
|
+
resultFormat: {
|
|
38
|
+
resultKey: 'point',
|
|
39
|
+
coordinates: {
|
|
40
|
+
shape: 'point',
|
|
41
|
+
order: 'xy',
|
|
42
|
+
normalizedBy: 1000
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
export { antLingAdapters };
|
|
50
|
+
|
|
51
|
+
//# sourceMappingURL=adapter.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ai-model/models/ant-ling/adapter.mjs","sources":["../../../../../src/ai-model/models/ant-ling/adapter.ts"],"sourcesContent":["import type { TModelFamily } from '@midscene/shared/env';\nimport type {\n ChatCompletionCallContext,\n ChatCompletionParamsResult,\n ModelAdapterDefinition,\n} from '../../model-adapter/types';\n\nconst buildAntLingChatCompletionParams = (\n input: ChatCompletionCallContext,\n): ChatCompletionParamsResult => {\n const { midsceneDefaults, userConfig } = input;\n const { reasoningEnabled } = userConfig;\n\n return {\n config: {\n ...midsceneDefaults,\n ...(userConfig.temperature !== undefined\n ? { temperature: userConfig.temperature }\n : {}),\n // https://developer.ant-ling.com/en/docs/tutorials/structured-outputs/\n ...(userConfig.responseFormat !== 'none' &&\n input.expectedJsonObjectResponse\n ? { response_format: { type: 'json_object' } }\n : {}),\n ...(reasoningEnabled !== 'default'\n ? {\n thinking: {\n type: (reasoningEnabled ?? false) ? 'enabled' : 'disabled',\n },\n }\n : {}),\n },\n };\n};\n\nexport const antLingAdapters = {\n 'ant-ling': {\n supportedProtocols: ['openai-chat'],\n chatCompletion: {\n unsupportedUserConfig: ['reasoningEffort', 'reasoningBudget'],\n buildChatCompletionParams: buildAntLingChatCompletionParams,\n },\n locate: {\n element: {\n resultFormat: {\n resultKey: 'point',\n coordinates: {\n shape: 'point',\n order: 'xy',\n normalizedBy: 1000,\n },\n },\n },\n },\n },\n} satisfies Pick<Record<TModelFamily, ModelAdapterDefinition>, 'ant-ling'>;\n"],"names":["buildAntLingChatCompletionParams","input","midsceneDefaults","userConfig","reasoningEnabled","undefined","antLingAdapters"],"mappings":"AAOA,MAAMA,mCAAmC,CACvCC;IAEA,MAAM,EAAEC,gBAAgB,EAAEC,UAAU,EAAE,GAAGF;IACzC,MAAM,EAAEG,gBAAgB,EAAE,GAAGD;IAE7B,OAAO;QACL,QAAQ;YACN,GAAGD,gBAAgB;YACnB,GAAIC,AAA2BE,WAA3BF,WAAW,WAAW,GACtB;gBAAE,aAAaA,WAAW,WAAW;YAAC,IACtC,CAAC,CAAC;YAEN,GAAIA,AAA8B,WAA9BA,WAAW,cAAc,IAC7BF,MAAM,0BAA0B,GAC5B;gBAAE,iBAAiB;oBAAE,MAAM;gBAAc;YAAE,IAC3C,CAAC,CAAC;YACN,GAAIG,AAAqB,cAArBA,mBACA;gBACE,UAAU;oBACR,MAAOA,oBAAoB,QAAS,YAAY;gBAClD;YACF,IACA,CAAC,CAAC;QACR;IACF;AACF;AAEO,MAAME,kBAAkB;IAC7B,YAAY;QACV,oBAAoB;YAAC;SAAc;QACnC,gBAAgB;YACd,uBAAuB;gBAAC;gBAAmB;aAAkB;YAC7D,2BAA2BN;QAC7B;QACA,QAAQ;YACN,SAAS;gBACP,cAAc;oBACZ,WAAW;oBACX,aAAa;wBACX,OAAO;wBACP,OAAO;wBACP,cAAc;oBAChB;gBACF;YACF;QACF;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-model/models/jev/adapter.mjs","sources":["../../../../../src/ai-model/models/jev/adapter.ts"],"sourcesContent":["import type { TModelFamily } from '@midscene/shared/env';\nimport type { ModelAdapterDefinition } from '../../model-adapter/types';\nimport { jevBoolean } from './boolean';\nimport { jevLocate } from './locate';\nimport { jevPlan } from './planning';\n\nexport const jevAdapters = {\n jev: {\n modelType: 'system-one',\n
|
|
1
|
+
{"version":3,"file":"ai-model/models/jev/adapter.mjs","sources":["../../../../../src/ai-model/models/jev/adapter.ts"],"sourcesContent":["import type { TModelFamily } from '@midscene/shared/env';\nimport type { ModelAdapterDefinition } from '../../model-adapter/types';\nimport { jevBoolean } from './boolean';\nimport { jevLocate } from './locate';\nimport { jevPlan } from './planning';\n\nexport const jevAdapters = {\n jev: {\n modelType: 'system-one',\n allowedTaskTypes: ['locate', 'boolean', 'planning'],\n supportedProtocols: [],\n locate: { kind: 'custom', locateFn: jevLocate },\n insight: { booleanFn: jevBoolean },\n planning: {\n kind: 'custom',\n planFn: jevPlan,\n cacheEnabled: false,\n supportsActionDeepLocate: false,\n defaultReplanningCycleLimit: 20,\n },\n },\n} satisfies Pick<Record<TModelFamily, ModelAdapterDefinition>, 'jev'>;\n"],"names":["jevAdapters","jevLocate","jevBoolean","jevPlan"],"mappings":";;;AAMO,MAAMA,cAAc;IACzB,KAAK;QACH,WAAW;QACX,kBAAkB;YAAC;YAAU;YAAW;SAAW;QACnD,oBAAoB,EAAE;QACtB,QAAQ;YAAE,MAAM;YAAU,UAAUC;QAAU;QAC9C,SAAS;YAAE,WAAWC;QAAW;QACjC,UAAU;YACR,MAAM;YACN,QAAQC;YACR,cAAc;YACd,0BAA0B;YAC1B,6BAA6B;QAC/B;IACF;AACF"}
|
|
@@ -2,13 +2,13 @@ import { getDebug } from "@midscene/shared/logger";
|
|
|
2
2
|
import { getModelRuntime } from "./registry.mjs";
|
|
3
3
|
function resolveModelForTaskType(configs, intent, taskType) {
|
|
4
4
|
const requested = getModelRuntime(configs.getModelConfig(intent));
|
|
5
|
-
if (!requested.adapter.
|
|
5
|
+
if (!requested.adapter.allowedTaskTypes || requested.adapter.allowedTaskTypes.includes(taskType)) return requested;
|
|
6
6
|
const config = configs.getModelConfig('default');
|
|
7
7
|
const runtime = getModelRuntime({
|
|
8
8
|
...config,
|
|
9
9
|
intent
|
|
10
10
|
});
|
|
11
|
-
if (runtime.adapter.
|
|
11
|
+
if (runtime.adapter.allowedTaskTypes && !runtime.adapter.allowedTaskTypes.includes(taskType)) throw new Error(`The default model cannot perform ${taskType}. Configure a general-purpose default model.`);
|
|
12
12
|
const reason = `${requested.config.modelFamily} does not support ${taskType}; using the default model`;
|
|
13
13
|
getDebug('ai:model-fallback', {
|
|
14
14
|
console: true
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-model/models/model-fallback.mjs","sources":["../../../../src/ai-model/models/model-fallback.ts"],"sourcesContent":["import type { IModelConfig, TIntent } from '@midscene/shared/env';\nimport { getDebug } from '@midscene/shared/logger';\nimport type { ModelRuntime, ModelTaskType } from '../model-adapter/types';\nimport { getModelRuntime } from './registry';\n\nexport function resolveModelForTaskType(\n configs: { getModelConfig(intent: TIntent): IModelConfig },\n intent: TIntent,\n taskType: ModelTaskType,\n): ModelRuntime {\n const requested = getModelRuntime(configs.getModelConfig(intent));\n if (\n !requested.adapter.
|
|
1
|
+
{"version":3,"file":"ai-model/models/model-fallback.mjs","sources":["../../../../src/ai-model/models/model-fallback.ts"],"sourcesContent":["import type { IModelConfig, TIntent } from '@midscene/shared/env';\nimport { getDebug } from '@midscene/shared/logger';\nimport type { ModelRuntime, ModelTaskType } from '../model-adapter/types';\nimport { getModelRuntime } from './registry';\n\nexport function resolveModelForTaskType(\n configs: { getModelConfig(intent: TIntent): IModelConfig },\n intent: TIntent,\n taskType: ModelTaskType,\n): ModelRuntime {\n const requested = getModelRuntime(configs.getModelConfig(intent));\n if (\n !requested.adapter.allowedTaskTypes ||\n requested.adapter.allowedTaskTypes.includes(taskType)\n ) {\n return requested;\n }\n const config = configs.getModelConfig('default');\n const runtime = getModelRuntime({ ...config, intent });\n if (\n runtime.adapter.allowedTaskTypes &&\n !runtime.adapter.allowedTaskTypes.includes(taskType)\n ) {\n throw new Error(\n `The default model cannot perform ${taskType}. Configure a general-purpose default model.`,\n );\n }\n const reason = `${requested.config.modelFamily} does not support ${taskType}; using the default model`;\n getDebug('ai:model-fallback', { console: true })(reason);\n return {\n ...runtime,\n modelFallback: {\n requestedModel: requested.config.modelName,\n requestedSlot: requested.config.slot,\n taskType,\n reason,\n },\n };\n}\n"],"names":["resolveModelForTaskType","configs","intent","taskType","requested","getModelRuntime","config","runtime","Error","reason","getDebug"],"mappings":";;AAKO,SAASA,wBACdC,OAA0D,EAC1DC,MAAe,EACfC,QAAuB;IAEvB,MAAMC,YAAYC,gBAAgBJ,QAAQ,cAAc,CAACC;IACzD,IACE,CAACE,UAAU,OAAO,CAAC,gBAAgB,IACnCA,UAAU,OAAO,CAAC,gBAAgB,CAAC,QAAQ,CAACD,WAE5C,OAAOC;IAET,MAAME,SAASL,QAAQ,cAAc,CAAC;IACtC,MAAMM,UAAUF,gBAAgB;QAAE,GAAGC,MAAM;QAAEJ;IAAO;IACpD,IACEK,QAAQ,OAAO,CAAC,gBAAgB,IAChC,CAACA,QAAQ,OAAO,CAAC,gBAAgB,CAAC,QAAQ,CAACJ,WAE3C,MAAM,IAAIK,MACR,CAAC,iCAAiC,EAAEL,SAAS,4CAA4C,CAAC;IAG9F,MAAMM,SAAS,GAAGL,UAAU,MAAM,CAAC,WAAW,CAAC,kBAAkB,EAAED,SAAS,yBAAyB,CAAC;IACtGO,SAAS,qBAAqB;QAAE,SAAS;IAAK,GAAGD;IACjD,OAAO;QACL,GAAGF,OAAO;QACV,eAAe;YACb,gBAAgBH,UAAU,MAAM,CAAC,SAAS;YAC1C,eAAeA,UAAU,MAAM,CAAC,IAAI;YACpCD;YACAM;QACF;IACF;AACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { getDebug } from "@midscene/shared/logger";
|
|
2
2
|
import { ResolvedModelAdapter } from "../model-adapter/resolve.mjs";
|
|
3
|
+
import { antLingAdapters } from "./ant-ling/adapter.mjs";
|
|
3
4
|
import { autoGlmAdapters } from "./auto-glm/adapter.mjs";
|
|
4
5
|
import { deepSeekAdapters } from "./deepseek/adapter.mjs";
|
|
5
6
|
import { defaultOpenAICompatibleAdapterConfig } from "./default.mjs";
|
|
@@ -13,6 +14,7 @@ import { mimoAdapters } from "./mimo.mjs";
|
|
|
13
14
|
import { qwenAdapters } from "./qwen.mjs";
|
|
14
15
|
import { uiTarsAdapters } from "./ui-tars/adapter.mjs";
|
|
15
16
|
const MODEL_ADAPTER_CONFIGS = {
|
|
17
|
+
...antLingAdapters,
|
|
16
18
|
...jevAdapters,
|
|
17
19
|
...qwenAdapters,
|
|
18
20
|
...deepSeekAdapters,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai-model/models/registry.mjs","sources":["../../../../src/ai-model/models/registry.ts"],"sourcesContent":["import type { IModelConfig, TModelFamily } from '@midscene/shared/env';\nimport { getDebug } from '@midscene/shared/logger';\nimport { ResolvedModelAdapter } from '../model-adapter/resolve';\nimport type {\n ModelAdapter,\n ModelAdapterDefinition,\n ModelRuntime,\n} from '../model-adapter/types';\nimport { autoGlmAdapters } from './auto-glm/adapter';\nimport { deepSeekAdapters } from './deepseek/adapter';\nimport { defaultOpenAICompatibleAdapterConfig } from './default';\nimport { doubaoAdapters } from './doubao';\nimport { geminiAdapters } from './gemini';\nimport { glmAdapters } from './glm';\nimport { gptAdapters } from './gpt';\nimport { jevAdapters } from './jev/adapter';\nimport { kimiAdapters } from './kimi';\nimport { mimoAdapters } from './mimo';\nimport { qwenAdapters } from './qwen';\nimport { uiTarsAdapters } from './ui-tars/adapter';\n\nexport const MODEL_ADAPTER_CONFIGS = {\n ...jevAdapters,\n ...qwenAdapters,\n ...deepSeekAdapters,\n ...doubaoAdapters,\n ...geminiAdapters,\n ...uiTarsAdapters,\n ...glmAdapters,\n ...autoGlmAdapters,\n ...gptAdapters,\n ...kimiAdapters,\n ...mimoAdapters,\n} satisfies Record<TModelFamily, ModelAdapterDefinition>;\n\ntype ModelAdapterCacheKey = TModelFamily | 'default';\n\nconst modelAdapterCache = new Map<ModelAdapterCacheKey, ModelAdapter>();\nconst debugModelAdapter = getDebug('ai:model-adapter');\n\nfunction debugAdapterUnsupportedUserConfig(\n modelFamily: ModelAdapterCacheKey,\n adapter: ModelAdapter,\n): void {\n if (adapter.chatCompletion.unsupportedUserConfig.length > 0) {\n debugModelAdapter(\n `model adapter \"${modelFamily}\" (chat-completion) unsupportedUserConfig: ${JSON.stringify(adapter.chatCompletion.unsupportedUserConfig)}`,\n );\n }\n if (adapter.responses.unsupportedUserConfig.length > 0) {\n debugModelAdapter(\n `model adapter \"${modelFamily}\" (responses) unsupportedUserConfig: ${JSON.stringify(adapter.responses.unsupportedUserConfig)}`,\n );\n }\n}\n\nexport function getModelAdapter(modelFamily?: TModelFamily): ModelAdapter {\n const cacheKey: ModelAdapterCacheKey = modelFamily ?? 'default';\n let adapter = modelAdapterCache.get(cacheKey);\n if (adapter) {\n return adapter;\n }\n\n const config = modelFamily\n ? MODEL_ADAPTER_CONFIGS[modelFamily]\n : defaultOpenAICompatibleAdapterConfig;\n if (!config) {\n throw new Error(\n `No model adapter registered for modelFamily: ${modelFamily}`,\n );\n }\n\n adapter = new ResolvedModelAdapter(config, cacheKey);\n modelAdapterCache.set(cacheKey, adapter);\n debugAdapterUnsupportedUserConfig(cacheKey, adapter);\n\n return adapter;\n}\n\nexport function getModelRuntime(config: IModelConfig): ModelRuntime {\n return {\n config,\n adapter: getModelAdapter(config.modelFamily),\n };\n}\n"],"names":["MODEL_ADAPTER_CONFIGS","jevAdapters","qwenAdapters","deepSeekAdapters","doubaoAdapters","geminiAdapters","uiTarsAdapters","glmAdapters","autoGlmAdapters","gptAdapters","kimiAdapters","mimoAdapters","modelAdapterCache","Map","debugModelAdapter","getDebug","debugAdapterUnsupportedUserConfig","modelFamily","adapter","JSON","getModelAdapter","cacheKey","config","defaultOpenAICompatibleAdapterConfig","Error","ResolvedModelAdapter","getModelRuntime"],"mappings":"
|
|
1
|
+
{"version":3,"file":"ai-model/models/registry.mjs","sources":["../../../../src/ai-model/models/registry.ts"],"sourcesContent":["import type { IModelConfig, TModelFamily } from '@midscene/shared/env';\nimport { getDebug } from '@midscene/shared/logger';\nimport { ResolvedModelAdapter } from '../model-adapter/resolve';\nimport type {\n ModelAdapter,\n ModelAdapterDefinition,\n ModelRuntime,\n} from '../model-adapter/types';\nimport { antLingAdapters } from './ant-ling/adapter';\nimport { autoGlmAdapters } from './auto-glm/adapter';\nimport { deepSeekAdapters } from './deepseek/adapter';\nimport { defaultOpenAICompatibleAdapterConfig } from './default';\nimport { doubaoAdapters } from './doubao';\nimport { geminiAdapters } from './gemini';\nimport { glmAdapters } from './glm';\nimport { gptAdapters } from './gpt';\nimport { jevAdapters } from './jev/adapter';\nimport { kimiAdapters } from './kimi';\nimport { mimoAdapters } from './mimo';\nimport { qwenAdapters } from './qwen';\nimport { uiTarsAdapters } from './ui-tars/adapter';\n\nexport const MODEL_ADAPTER_CONFIGS = {\n ...antLingAdapters,\n ...jevAdapters,\n ...qwenAdapters,\n ...deepSeekAdapters,\n ...doubaoAdapters,\n ...geminiAdapters,\n ...uiTarsAdapters,\n ...glmAdapters,\n ...autoGlmAdapters,\n ...gptAdapters,\n ...kimiAdapters,\n ...mimoAdapters,\n} satisfies Record<TModelFamily, ModelAdapterDefinition>;\n\ntype ModelAdapterCacheKey = TModelFamily | 'default';\n\nconst modelAdapterCache = new Map<ModelAdapterCacheKey, ModelAdapter>();\nconst debugModelAdapter = getDebug('ai:model-adapter');\n\nfunction debugAdapterUnsupportedUserConfig(\n modelFamily: ModelAdapterCacheKey,\n adapter: ModelAdapter,\n): void {\n if (adapter.chatCompletion.unsupportedUserConfig.length > 0) {\n debugModelAdapter(\n `model adapter \"${modelFamily}\" (chat-completion) unsupportedUserConfig: ${JSON.stringify(adapter.chatCompletion.unsupportedUserConfig)}`,\n );\n }\n if (adapter.responses.unsupportedUserConfig.length > 0) {\n debugModelAdapter(\n `model adapter \"${modelFamily}\" (responses) unsupportedUserConfig: ${JSON.stringify(adapter.responses.unsupportedUserConfig)}`,\n );\n }\n}\n\nexport function getModelAdapter(modelFamily?: TModelFamily): ModelAdapter {\n const cacheKey: ModelAdapterCacheKey = modelFamily ?? 'default';\n let adapter = modelAdapterCache.get(cacheKey);\n if (adapter) {\n return adapter;\n }\n\n const config = modelFamily\n ? MODEL_ADAPTER_CONFIGS[modelFamily]\n : defaultOpenAICompatibleAdapterConfig;\n if (!config) {\n throw new Error(\n `No model adapter registered for modelFamily: ${modelFamily}`,\n );\n }\n\n adapter = new ResolvedModelAdapter(config, cacheKey);\n modelAdapterCache.set(cacheKey, adapter);\n debugAdapterUnsupportedUserConfig(cacheKey, adapter);\n\n return adapter;\n}\n\nexport function getModelRuntime(config: IModelConfig): ModelRuntime {\n return {\n config,\n adapter: getModelAdapter(config.modelFamily),\n };\n}\n"],"names":["MODEL_ADAPTER_CONFIGS","antLingAdapters","jevAdapters","qwenAdapters","deepSeekAdapters","doubaoAdapters","geminiAdapters","uiTarsAdapters","glmAdapters","autoGlmAdapters","gptAdapters","kimiAdapters","mimoAdapters","modelAdapterCache","Map","debugModelAdapter","getDebug","debugAdapterUnsupportedUserConfig","modelFamily","adapter","JSON","getModelAdapter","cacheKey","config","defaultOpenAICompatibleAdapterConfig","Error","ResolvedModelAdapter","getModelRuntime"],"mappings":";;;;;;;;;;;;;;;AAsBO,MAAMA,wBAAwB;IACnC,GAAGC,eAAe;IAClB,GAAGC,WAAW;IACd,GAAGC,YAAY;IACf,GAAGC,gBAAgB;IACnB,GAAGC,cAAc;IACjB,GAAGC,cAAc;IACjB,GAAGC,cAAc;IACjB,GAAGC,WAAW;IACd,GAAGC,eAAe;IAClB,GAAGC,WAAW;IACd,GAAGC,YAAY;IACf,GAAGC,YAAY;AACjB;AAIA,MAAMC,oBAAoB,IAAIC;AAC9B,MAAMC,oBAAoBC,SAAS;AAEnC,SAASC,kCACPC,WAAiC,EACjCC,OAAqB;IAErB,IAAIA,QAAQ,cAAc,CAAC,qBAAqB,CAAC,MAAM,GAAG,GACxDJ,kBACE,CAAC,eAAe,EAAEG,YAAY,2CAA2C,EAAEE,KAAK,SAAS,CAACD,QAAQ,cAAc,CAAC,qBAAqB,GAAG;IAG7I,IAAIA,QAAQ,SAAS,CAAC,qBAAqB,CAAC,MAAM,GAAG,GACnDJ,kBACE,CAAC,eAAe,EAAEG,YAAY,qCAAqC,EAAEE,KAAK,SAAS,CAACD,QAAQ,SAAS,CAAC,qBAAqB,GAAG;AAGpI;AAEO,SAASE,gBAAgBH,WAA0B;IACxD,MAAMI,WAAiCJ,eAAe;IACtD,IAAIC,UAAUN,kBAAkB,GAAG,CAACS;IACpC,IAAIH,SACF,OAAOA;IAGT,MAAMI,SAASL,cACXlB,qBAAqB,CAACkB,YAAY,GAClCM;IACJ,IAAI,CAACD,QACH,MAAM,IAAIE,MACR,CAAC,6CAA6C,EAAEP,aAAa;IAIjEC,UAAU,IAAIO,qBAAqBH,QAAQD;IAC3CT,kBAAkB,GAAG,CAACS,UAAUH;IAChCF,kCAAkCK,UAAUH;IAE5C,OAAOA;AACT;AAEO,SAASQ,gBAAgBJ,MAAoB;IAClD,OAAO;QACLA;QACA,SAASF,gBAAgBE,OAAO,WAAW;IAC7C;AACF"}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { ReportActionDump } from "../types.mjs";
|
|
2
|
+
function _define_property(obj, key, value) {
|
|
3
|
+
if (key in obj) Object.defineProperty(obj, key, {
|
|
4
|
+
value: value,
|
|
5
|
+
enumerable: true,
|
|
6
|
+
configurable: true,
|
|
7
|
+
writable: true
|
|
8
|
+
});
|
|
9
|
+
else obj[key] = value;
|
|
10
|
+
return obj;
|
|
11
|
+
}
|
|
12
|
+
class ExecutionRecorder {
|
|
13
|
+
record(execution, meta) {
|
|
14
|
+
this.meta = meta;
|
|
15
|
+
let key = execution.id ? `id:${execution.id}` : this.anonymousKeys.get(execution);
|
|
16
|
+
if (!key) {
|
|
17
|
+
key = `anonymous:${++this.nextAnonymousKey}`;
|
|
18
|
+
this.anonymousKeys.set(execution, key);
|
|
19
|
+
}
|
|
20
|
+
this.records.set(key, execution);
|
|
21
|
+
return key;
|
|
22
|
+
}
|
|
23
|
+
get executions() {
|
|
24
|
+
return [
|
|
25
|
+
...this.records.values()
|
|
26
|
+
];
|
|
27
|
+
}
|
|
28
|
+
get reportMeta() {
|
|
29
|
+
return this.meta;
|
|
30
|
+
}
|
|
31
|
+
toDump(meta = this.meta) {
|
|
32
|
+
if (!meta) throw new Error('Cannot create a report without execution metadata');
|
|
33
|
+
return new ReportActionDump({
|
|
34
|
+
...meta,
|
|
35
|
+
executions: this.executions
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
capture(executionIds, meta = this.meta) {
|
|
39
|
+
const selected = executionIds ? new Set(executionIds) : void 0;
|
|
40
|
+
const executions = this.executions.filter((execution)=>!selected || execution.id && selected.has(execution.id));
|
|
41
|
+
if (!meta) throw new Error('Cannot capture a report without execution metadata');
|
|
42
|
+
return {
|
|
43
|
+
capturedAt: new Date().toISOString(),
|
|
44
|
+
screenshots: executions.flatMap((execution)=>execution.collectScreenshots()),
|
|
45
|
+
referenceImageUrls: [
|
|
46
|
+
...new Set(executions.flatMap((execution)=>[
|
|
47
|
+
...execution.getReferenceImageUrls()
|
|
48
|
+
]))
|
|
49
|
+
],
|
|
50
|
+
dump: ReportActionDump.fromSerializedString(new ReportActionDump({
|
|
51
|
+
...meta,
|
|
52
|
+
executions
|
|
53
|
+
}).serialize())
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
clear() {
|
|
57
|
+
this.records.clear();
|
|
58
|
+
this.anonymousKeys = new WeakMap();
|
|
59
|
+
this.meta = void 0;
|
|
60
|
+
}
|
|
61
|
+
constructor(){
|
|
62
|
+
_define_property(this, "records", new Map());
|
|
63
|
+
_define_property(this, "anonymousKeys", new WeakMap());
|
|
64
|
+
_define_property(this, "nextAnonymousKey", 0);
|
|
65
|
+
_define_property(this, "meta", void 0);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export { ExecutionRecorder };
|
|
69
|
+
|
|
70
|
+
//# sourceMappingURL=execution-recorder.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dump/execution-recorder.mjs","sources":["../../../src/dump/execution-recorder.ts"],"sourcesContent":["import type { ScreenshotItem } from '../screenshot-item';\nimport {\n type ExecutionDump,\n ReportActionDump,\n type ReportMeta,\n} from '../types';\n\nexport interface ExecutionRecordSnapshot {\n capturedAt: string;\n dump: ReportActionDump;\n screenshots: ScreenshotItem[];\n referenceImageUrls: string[];\n}\n\n/** Execution facts and immutable cutoffs, independent of HTML and file I/O. */\nexport class ExecutionRecorder {\n private readonly records = new Map<string, ExecutionDump>();\n private anonymousKeys = new WeakMap<ExecutionDump, string>();\n private nextAnonymousKey = 0;\n private meta?: ReportMeta;\n\n record(execution: ExecutionDump, meta: ReportMeta): string {\n this.meta = meta;\n let key = execution.id\n ? `id:${execution.id}`\n : this.anonymousKeys.get(execution);\n if (!key) {\n key = `anonymous:${++this.nextAnonymousKey}`;\n this.anonymousKeys.set(execution, key);\n }\n this.records.set(key, execution);\n return key;\n }\n\n get executions(): ExecutionDump[] {\n return [...this.records.values()];\n }\n\n get reportMeta(): ReportMeta | undefined {\n return this.meta;\n }\n\n toDump(meta = this.meta): ReportActionDump {\n if (!meta)\n throw new Error('Cannot create a report without execution metadata');\n return new ReportActionDump({ ...meta, executions: this.executions });\n }\n\n /** Freeze facts before any asynchronous asset writes or subsequent progress. */\n capture(\n executionIds?: readonly string[],\n meta = this.meta,\n ): ExecutionRecordSnapshot {\n const selected = executionIds ? new Set(executionIds) : undefined;\n const executions = this.executions.filter(\n (execution) => !selected || (execution.id && selected.has(execution.id)),\n );\n if (!meta)\n throw new Error('Cannot capture a report without execution metadata');\n return {\n capturedAt: new Date().toISOString(),\n screenshots: executions.flatMap((execution) =>\n execution.collectScreenshots(),\n ),\n referenceImageUrls: [\n ...new Set(\n executions.flatMap((execution) => [\n ...execution.getReferenceImageUrls(),\n ]),\n ),\n ],\n dump: ReportActionDump.fromSerializedString(\n new ReportActionDump({ ...meta, executions }).serialize(),\n ),\n };\n }\n\n clear(): void {\n this.records.clear();\n this.anonymousKeys = new WeakMap();\n this.meta = undefined;\n }\n}\n"],"names":["ExecutionRecorder","execution","meta","key","Error","ReportActionDump","executionIds","selected","Set","undefined","executions","Date","WeakMap","Map"],"mappings":";;;;;;;;;;;AAeO,MAAMA;IAMX,OAAOC,SAAwB,EAAEC,IAAgB,E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BAAEQ;YAAW,GAAG,SAAS;QAE3D;IACF;IAEA,QAAc;QACZ,IAAI,CAAC,OAAO,CAAC,KAAK;QAClB,IAAI,CAAC,aAAa,GAAG,IAAIE;QACzB,IAAI,CAAC,IAAI,GAAGH;IACd;;QAjEA,uBAAiB,WAAU,IAAII;QAC/B,uBAAQ,iBAAgB,IAAID;QAC5B,uBAAQ,oBAAmB;QAC3B,uBAAQ,QAAR;;AA+DF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as __rspack_external_node_fs_5ea92f0c from "node:fs";
|
|
2
2
|
import { open as promises_open } from "node:fs/promises";
|
|
3
3
|
import { StringDecoder } from "node:string_decoder";
|
|
4
|
+
import { REPORT_ARTIFACT_SCRIPT_TYPE, assertReportArtifactPath } from "@midscene/shared/report-artifact";
|
|
4
5
|
import { antiEscapeScriptTag, escapeScriptTag } from "@midscene/shared/utils";
|
|
5
6
|
import { TEST_RUN_REPORT_SCRIPT_TYPE } from "../test-run-report.mjs";
|
|
6
7
|
var __webpack_modules__ = {
|
|
@@ -96,6 +97,55 @@ function generateAgentReportComment(report) {
|
|
|
96
97
|
function htmlScriptCloseTag() {
|
|
97
98
|
return String.fromCharCode(60) + "/script>";
|
|
98
99
|
}
|
|
100
|
+
function generateReportArtifactScriptTag(path) {
|
|
101
|
+
assertReportArtifactPath(path);
|
|
102
|
+
return [
|
|
103
|
+
String.fromCharCode(60),
|
|
104
|
+
'script type="',
|
|
105
|
+
REPORT_ARTIFACT_SCRIPT_TYPE,
|
|
106
|
+
'">',
|
|
107
|
+
JSON.stringify(path),
|
|
108
|
+
htmlScriptCloseTag()
|
|
109
|
+
].join('');
|
|
110
|
+
}
|
|
111
|
+
function reportArtifactPathExtractor(filePath) {
|
|
112
|
+
let result;
|
|
113
|
+
return {
|
|
114
|
+
get path () {
|
|
115
|
+
return result;
|
|
116
|
+
},
|
|
117
|
+
visit: (content)=>{
|
|
118
|
+
const tagEnd = content.indexOf('>');
|
|
119
|
+
const type = content.slice(0, tagEnd).match(/(?:^|\s)type\s*=\s*["']([^"']+)["']/i)?.[1];
|
|
120
|
+
if (type !== REPORT_ARTIFACT_SCRIPT_TYPE) return false;
|
|
121
|
+
if (void 0 !== result) throw new Error(`Report contains multiple artifact entries: ${filePath}`);
|
|
122
|
+
const path = JSON.parse(unescapeContent(content.slice(tagEnd + 1)));
|
|
123
|
+
assertReportArtifactPath(path);
|
|
124
|
+
result = path;
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
function extractReportArtifactPathSync(filePath) {
|
|
130
|
+
const extractor = reportArtifactPathExtractor(filePath);
|
|
131
|
+
streamScanTags(filePath, `${String.fromCharCode(60)}script`, htmlScriptCloseTag(), extractor.visit);
|
|
132
|
+
return extractor.path;
|
|
133
|
+
}
|
|
134
|
+
async function extractReportArtifactPathAsync(filePath) {
|
|
135
|
+
const extractor = reportArtifactPathExtractor(filePath);
|
|
136
|
+
await streamScanTagsAsync(filePath, `${String.fromCharCode(60)}script`, htmlScriptCloseTag(), extractor.visit);
|
|
137
|
+
return extractor.path;
|
|
138
|
+
}
|
|
139
|
+
async function streamDumpScriptsAsync(filePath, visitor) {
|
|
140
|
+
await streamScanTagsAsync(filePath, `${String.fromCharCode(60)}script`, htmlScriptCloseTag(), (content)=>{
|
|
141
|
+
const tagEnd = content.indexOf('>');
|
|
142
|
+
const type = content.slice(0, tagEnd).match(/(?:^|\s)type\s*=\s*["']([^"']+)["']/i)?.[1];
|
|
143
|
+
return 'midscene_web_dump' === type ? visitor({
|
|
144
|
+
openTag: content.slice(0, tagEnd + 1),
|
|
145
|
+
content: content.slice(tagEnd + 1)
|
|
146
|
+
}) : false;
|
|
147
|
+
});
|
|
148
|
+
}
|
|
99
149
|
function generateTestRunReportScriptTag(dump) {
|
|
100
150
|
return [
|
|
101
151
|
String.fromCharCode(60),
|
|
@@ -442,6 +492,6 @@ function generateDumpScriptTag(json, attributes) {
|
|
|
442
492
|
if (attributes && Object.keys(attributes).length > 0) attrString = ' ' + Object.entries(attributes).map(([k, v])=>k + '="' + encodeURIComponent(v) + '"').join(' ');
|
|
443
493
|
return '<script type="midscene_web_dump"' + attrString + '>' + escapeContent(json) + closeTag;
|
|
444
494
|
}
|
|
445
|
-
export { DATA_SCREENSHOT_MODE_ATTR, STREAMING_CHUNK_SIZE, collectImageScriptIds, escapeContent, extractAllDumpScriptsSync, extractImageByIdSync, extractLastDumpScriptSync, extractTestRunReportDumpSync, generateAgentReportComment, generateDumpScriptTag, generateImageScriptTag, generateTestRunReportScriptTag, getBaseUrlFixScript, parseDumpScript, parseDumpScriptAttributes, parseImageScripts, streamDumpScriptsSync, streamImageScriptsToFile, streamScanTags, streamScanTagsAsync, unescapeContent };
|
|
495
|
+
export { DATA_SCREENSHOT_MODE_ATTR, STREAMING_CHUNK_SIZE, collectImageScriptIds, escapeContent, extractAllDumpScriptsSync, extractImageByIdSync, extractLastDumpScriptSync, extractReportArtifactPathAsync, extractReportArtifactPathSync, extractTestRunReportDumpSync, generateAgentReportComment, generateDumpScriptTag, generateImageScriptTag, generateReportArtifactScriptTag, generateTestRunReportScriptTag, getBaseUrlFixScript, parseDumpScript, parseDumpScriptAttributes, parseImageScripts, streamDumpScriptsAsync, streamDumpScriptsSync, streamImageScriptsToFile, streamScanTags, streamScanTagsAsync, unescapeContent };
|
|
446
496
|
|
|
447
497
|
//# sourceMappingURL=html-utils.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dump/html-utils.mjs","sources":["../../../src/dump/html-utils.ts"],"sourcesContent":["import { closeSync, openSync, readSync, statSync } from 'node:fs';\nimport { open as openAsync } from 'node:fs/promises';\nimport { StringDecoder } from 'node:string_decoder';\nimport { antiEscapeScriptTag, escapeScriptTag } from '@midscene/shared/utils';\nimport {\n TEST_RUN_REPORT_SCRIPT_TYPE,\n type TestRunReportDump,\n} from '../test-run-report';\nimport type { AIUsageInfo, IReportActionDump, ModelBrief } from '../types';\n\nexport const escapeContent = escapeScriptTag;\nexport const unescapeContent = antiEscapeScriptTag;\n\nfunction cleanHtmlCommentValue(value: unknown): string {\n return String(value ?? 'N/A')\n .replace(/\\0/g, '')\n .replace(/--/g, '- -');\n}\n\nfunction formatModelBriefForAgent(brief: ModelBrief): string {\n const intent = brief.intent || 'default';\n const model = brief.name || 'unknown';\n const description = brief.modelDescription\n ? ` (${brief.modelDescription})`\n : '';\n return `${intent}: ${model}${description}`;\n}\n\nfunction hasUsageModelInfo(usage?: AIUsageInfo): usage is AIUsageInfo {\n return Boolean(\n usage &&\n (usage.model_name ||\n usage.response_model_name ||\n usage.model_description ||\n usage.intent),\n );\n}\n\nfunction formatUsageModelForAgent(source: string, usage: AIUsageInfo): string {\n const intent = usage.intent || source;\n const model = usage.model_name || usage.response_model_name || 'unknown';\n const description = usage.model_description\n ? ` (${usage.model_description})`\n : '';\n return `${intent}: ${model}${description}`;\n}\n\nfunction collectUsageModelsForAgent(report: IReportActionDump): string {\n const models = new Map<string, string>();\n const executions = Array.isArray(report.executions) ? report.executions : [];\n for (const execution of executions) {\n const tasks = Array.isArray(execution.tasks) ? execution.tasks : [];\n for (const task of tasks) {\n const taskWithUsage = task as {\n usage?: AIUsageInfo;\n searchAreaUsage?: AIUsageInfo;\n };\n const usages: Array<[string, AIUsageInfo | undefined]> = [\n ['main', taskWithUsage.usage],\n ['searchArea', taskWithUsage.searchAreaUsage],\n ];\n\n for (const [source, usage] of usages) {\n if (!hasUsageModelInfo(usage)) {\n continue;\n }\n const formatted = formatUsageModelForAgent(source, usage);\n models.set(formatted, formatted);\n }\n }\n }\n\n return Array.from(models.values()).join('; ');\n}\n\nexport function generateAgentReportComment(report: IReportActionDump): string {\n const executions = Array.isArray(report.executions) ? report.executions : [];\n const taskCount = executions.reduce(\n (sum, execution) =>\n sum + (Array.isArray(execution.tasks) ? execution.tasks.length : 0),\n 0,\n );\n const modelBriefs = report.modelBriefs?.length\n ? report.modelBriefs.map(formatModelBriefForAgent).join('; ')\n : collectUsageModelsForAgent(report) || 'No model metadata recorded';\n\n const lines = [\n 'For Agent Analysis:',\n `Report: ${cleanHtmlCommentValue(report.groupName)}`,\n `SDK: ${cleanHtmlCommentValue(report.sdkVersion)}`,\n `Device: ${cleanHtmlCommentValue(report.deviceType)}`,\n `Executions: ${executions.length}; Tasks: ${taskCount}`,\n `Models: ${cleanHtmlCommentValue(modelBriefs)}`,\n 'Structured report JSON is stored in script[type=\"midscene_web_dump\"] tags near this comment.',\n 'Screenshots are stored as script[type=\"midscene-image\"] tags or files referenced by screenshot refs.',\n 'For AI analysis, inspect each execution task for type, status, timing, param, output, usage, searchAreaUsage, recorder, and screenshot refs.',\n 'Use the Markdown export when available; it contains the same report context plus image links for agent review.',\n ];\n\n return `\\n<!--\\n${lines.join('\\n')}\\n-->\\n`;\n}\n\nfunction htmlScriptCloseTag(): string {\n // biome-ignore lint/style/useTemplate: keep this token runtime-built for inline report bundles\n return String.fromCharCode(60) + '/script>';\n}\n\n/** Avoid raw close tokens: this writer itself is bundled into report HTML. */\nexport function generateTestRunReportScriptTag(\n dump: TestRunReportDump,\n): string {\n return [\n String.fromCharCode(60),\n 'script type=\"',\n TEST_RUN_REPORT_SCRIPT_TYPE,\n '\">\\n',\n escapeScriptTag(JSON.stringify(dump)),\n '\\n',\n htmlScriptCloseTag(),\n '\\n',\n ].join('');\n}\n\nexport function extractTestRunReportDumpSync(\n filePath: string,\n): TestRunReportDump | undefined {\n let result: TestRunReportDump | undefined;\n // Consume executable scripts as whole elements: the embedded viewer itself\n // contains report-writer source with data-tag strings that are not payloads.\n const openTag = `${String.fromCharCode(60)}script`;\n streamScanTags(filePath, openTag, htmlScriptCloseTag(), (content) => {\n const tagEnd = content.indexOf('>');\n const attributes = content.slice(0, tagEnd);\n const type = attributes.match(/(?:^|\\s)type\\s*=\\s*[\"']([^\"']+)[\"']/i)?.[1];\n if (type !== TEST_RUN_REPORT_SCRIPT_TYPE) return false;\n if (result)\n throw new Error(\n `Report contains multiple Midscene Test dumps: ${filePath}`,\n );\n const parsed = JSON.parse(unescapeContent(content.slice(tagEnd + 1)));\n if (\n parsed?.schemaVersion !== 1 ||\n parsed?.kind !== 'test-runner' ||\n !Array.isArray(parsed.projects)\n )\n throw new Error(`Invalid Midscene Test report dump: ${filePath}`);\n result = parsed;\n return false;\n });\n return result;\n}\n\n/** Chunk size for streaming file operations (64KB) */\nexport const STREAMING_CHUNK_SIZE = 64 * 1024;\n\n/**\n * Callback for processing matched tags during streaming.\n * @param content - The content between open and close tags\n * @returns true to stop scanning, false to continue\n */\ntype TagMatchCallback = (content: string) => boolean;\n\nclass StreamingTagMatcher {\n private leftover = '';\n private capturing = false;\n private currentContent = '';\n\n constructor(\n private readonly openTag: string,\n private readonly closeTag: string,\n private readonly onMatch: TagMatchCallback,\n ) {}\n\n push(nextChunk: string): boolean {\n const chunk = this.leftover + nextChunk;\n this.leftover = '';\n let searchStart = 0;\n\n while (searchStart < chunk.length) {\n if (!this.capturing) {\n const startIndex = chunk.indexOf(this.openTag, searchStart);\n if (startIndex === -1) {\n const retainedSuffixLength = Math.max(0, this.openTag.length - 1);\n this.leftover = retainedSuffixLength\n ? chunk.slice(-retainedSuffixLength)\n : '';\n return false;\n }\n this.capturing = true;\n searchStart = startIndex + this.openTag.length;\n }\n\n const endIndex = chunk.indexOf(this.closeTag, searchStart);\n if (endIndex !== -1) {\n this.currentContent += chunk.slice(searchStart, endIndex);\n if (this.onMatch(this.currentContent)) return true;\n this.capturing = false;\n this.currentContent = '';\n searchStart = endIndex + this.closeTag.length;\n continue;\n }\n\n const retainedSuffixLength = Math.max(0, this.closeTag.length - 1);\n const contentEnd = Math.max(\n searchStart,\n chunk.length - retainedSuffixLength,\n );\n this.currentContent += chunk.slice(searchStart, contentEnd);\n this.leftover = chunk.slice(contentEnd);\n return false;\n }\n\n return false;\n }\n}\n\n/**\n * Stream through a file and find tags matching the pattern.\n * Memory usage: O(chunk_size + tag_size), not O(file_size).\n *\n * @param filePath - Absolute path to the file\n * @param openTag - Opening tag to search for\n * @param closeTag - Closing tag\n * @param onMatch - Callback for each matched tag content\n */\nexport function streamScanTags(\n filePath: string,\n openTag: string,\n closeTag: string,\n onMatch: TagMatchCallback,\n): void {\n const fd = openSync(filePath, 'r');\n const fileSize = statSync(filePath).size;\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n const decoder = new StringDecoder('utf8');\n const matcher = new StreamingTagMatcher(openTag, closeTag, onMatch);\n let position = 0;\n\n try {\n while (position < fileSize) {\n const bytesRead = readSync(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);\n position += bytesRead;\n if (matcher.push(decoder.write(buffer.subarray(0, bytesRead)))) return;\n }\n matcher.push(decoder.end());\n } finally {\n closeSync(fd);\n }\n}\n\n/** Asynchronously stream tags without blocking the Node.js event loop. */\nexport async function streamScanTagsAsync(\n filePath: string,\n openTag: string,\n closeTag: string,\n onMatch: TagMatchCallback,\n): Promise<void> {\n const handle = await openAsync(filePath, 'r');\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n const decoder = new StringDecoder('utf8');\n let position = 0;\n const matcher = new StreamingTagMatcher(openTag, closeTag, onMatch);\n\n try {\n while (true) {\n const { bytesRead } = await handle.read(\n buffer,\n 0,\n STREAMING_CHUNK_SIZE,\n position,\n );\n if (bytesRead === 0) {\n matcher.push(decoder.end());\n return;\n }\n position += bytesRead;\n if (matcher.push(decoder.write(buffer.subarray(0, bytesRead)))) return;\n }\n } finally {\n await handle.close();\n }\n}\n\n/**\n * Synchronously extract a specific image's base64 data from an HTML file by its id.\n * Uses streaming to avoid loading the entire file into memory.\n *\n * @param htmlPath - Absolute path to the HTML file\n * @param imageId - The id of the image to extract\n * @returns The base64 data string, or null if not found\n */\nexport function extractImageByIdSync(\n htmlPath: string,\n imageId: string,\n): string | null {\n const targetTag = `<script type=\"midscene-image\" data-id=\"${imageId}\">`;\n const closeTag = htmlScriptCloseTag();\n\n let result: string | null = null;\n\n streamScanTags(htmlPath, targetTag, closeTag, (content) => {\n result = unescapeContent(content);\n return true; // Stop after first match\n });\n\n return result;\n}\n\n/**\n * Stream image script tags from source file directly to output file.\n * Memory usage: O(single_image_size), not O(all_images_size).\n *\n * @param srcFilePath - Source HTML file path\n * @param destFilePath - Destination file path to append to\n * @param writtenImageIds - IDs already written to the destination\n */\nexport function streamImageScriptsToFile(\n srcFilePath: string,\n destFilePath: string,\n writtenImageIds: Set<string> = new Set(),\n): void {\n const { appendFileSync } = require('node:fs');\n const openTag = '<script type=\"midscene-image\"';\n const closeTag = htmlScriptCloseTag();\n\n streamScanTags(srcFilePath, openTag, closeTag, (content) => {\n const imageId = parseImageScriptId(content);\n if (!imageId || writtenImageIds.has(imageId)) {\n return false;\n }\n // Write complete tag immediately to destination, don't accumulate\n appendFileSync(destFilePath, `${openTag}${content}${closeTag}\\n`);\n writtenImageIds.add(imageId);\n return false; // Continue scanning for more tags\n });\n}\n\nfunction parseImageScriptId(contentAfterType: string): string | null {\n const match = /^ data-id=\"([a-z0-9_-]{1,128})\">/i.exec(contentAfterType);\n return match?.[1] ?? null;\n}\n\n/** Collect IDs of real inline image script tags without blocking on a large report. */\nexport async function collectImageScriptIds(\n filePath: string,\n): Promise<Set<string>> {\n const imageIds = new Set<string>();\n const openTag = '<script type=\"midscene-image\"';\n const closeTag = htmlScriptCloseTag();\n\n await streamScanTagsAsync(filePath, openTag, closeTag, (content) => {\n const imageId = parseImageScriptId(content);\n if (imageId) imageIds.add(imageId);\n return false;\n });\n return imageIds;\n}\n\n/**\n * Extract the LAST dump script content from HTML file using streaming.\n * Memory usage: O(dump_size), not O(file_size).\n *\n * @param filePath - Absolute path to the HTML file\n * @returns The dump script content (trimmed), or empty string if not found\n */\nexport function extractLastDumpScriptSync(filePath: string): string {\n const openTagPrefix = '<script type=\"midscene_web_dump\"';\n const closeTag = htmlScriptCloseTag();\n\n let lastContent = '';\n\n // Custom streaming to handle the special case where open tag has variable attributes\n const fd = openSync(filePath, 'r');\n const fileSize = statSync(filePath).size;\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n\n let position = 0;\n let leftover = '';\n let capturing = false;\n let currentContent = '';\n\n try {\n while (position < fileSize) {\n const bytesRead = readSync(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);\n const chunk = leftover + buffer.toString('utf-8', 0, bytesRead);\n position += bytesRead;\n\n let searchStart = 0;\n\n while (searchStart < chunk.length) {\n if (!capturing) {\n const startIdx = chunk.indexOf(openTagPrefix, searchStart);\n if (startIdx !== -1) {\n // Find the end of the opening tag (the '>' character)\n const tagEndIdx = chunk.indexOf('>', startIdx);\n if (tagEndIdx !== -1) {\n capturing = true;\n currentContent = chunk.slice(tagEndIdx + 1);\n const endIdx = currentContent.indexOf(closeTag);\n if (endIdx !== -1) {\n lastContent = currentContent.slice(0, endIdx).trim();\n capturing = false;\n currentContent = '';\n searchStart = tagEndIdx + 1 + endIdx + closeTag.length;\n } else {\n leftover = currentContent.slice(-closeTag.length);\n currentContent = currentContent.slice(0, -closeTag.length);\n break;\n }\n } else {\n leftover = chunk.slice(startIdx);\n break;\n }\n } else {\n leftover = chunk.slice(-openTagPrefix.length);\n break;\n }\n } else {\n const endIdx = chunk.indexOf(closeTag, searchStart);\n if (endIdx !== -1) {\n currentContent += chunk.slice(searchStart, endIdx);\n lastContent = currentContent.trim();\n capturing = false;\n currentContent = '';\n searchStart = endIdx + closeTag.length;\n } else {\n currentContent += chunk.slice(searchStart, -closeTag.length);\n leftover = chunk.slice(-closeTag.length);\n break;\n }\n }\n }\n }\n } finally {\n closeSync(fd);\n }\n\n return lastContent;\n}\n\n/**\n * Extract ALL dump script contents from an HTML file using streaming.\n * Each entry includes the full opening tag (for attribute extraction) and the content.\n *\n * @param filePath - Absolute path to the HTML file\n * @returns Array of { openTag, content } for each dump script found\n */\nexport function extractAllDumpScriptsSync(\n filePath: string,\n): { openTag: string; content: string }[] {\n const results: { openTag: string; content: string }[] = [];\n streamDumpScriptsSync(filePath, (dumpScript) => {\n results.push(dumpScript);\n return false;\n });\n return results;\n}\n\n/**\n * Stream ALL dump scripts from an HTML file.\n * Calls onMatch for each dump script and keeps memory bounded to a single\n * dump script payload instead of accumulating every dump in memory.\n *\n * @param filePath - Absolute path to the HTML file\n * @param onMatch - Callback for each dump script; return true to stop early\n */\nexport function streamDumpScriptsSync(\n filePath: string,\n onMatch: (dumpScript: { openTag: string; content: string }) => boolean,\n): void {\n const openTagPrefix = '<script type=\"midscene_web_dump\"';\n const closeTag = htmlScriptCloseTag();\n\n const fd = openSync(filePath, 'r');\n const fileSize = statSync(filePath).size;\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n\n let position = 0;\n let leftover = '';\n let capturing = false;\n let currentContent = '';\n let currentOpenTag = '';\n\n try {\n while (position < fileSize) {\n const bytesRead = readSync(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);\n const chunk = leftover + buffer.toString('utf-8', 0, bytesRead);\n position += bytesRead;\n\n let searchStart = 0;\n\n while (searchStart < chunk.length) {\n if (!capturing) {\n const startIdx = chunk.indexOf(openTagPrefix, searchStart);\n if (startIdx !== -1) {\n const tagEndIdx = chunk.indexOf('>', startIdx);\n if (tagEndIdx !== -1) {\n capturing = true;\n currentOpenTag = chunk.slice(startIdx, tagEndIdx + 1);\n currentContent = chunk.slice(tagEndIdx + 1);\n const endIdx = currentContent.indexOf(closeTag);\n if (endIdx !== -1) {\n const shouldStop = onMatch({\n openTag: currentOpenTag,\n content: currentContent.slice(0, endIdx).trim(),\n });\n if (shouldStop) return;\n capturing = false;\n currentContent = '';\n currentOpenTag = '';\n searchStart = tagEndIdx + 1 + endIdx + closeTag.length;\n } else {\n leftover = currentContent.slice(-closeTag.length);\n currentContent = currentContent.slice(0, -closeTag.length);\n break;\n }\n } else {\n leftover = chunk.slice(startIdx);\n break;\n }\n } else {\n leftover = chunk.slice(-openTagPrefix.length);\n break;\n }\n } else {\n const endIdx = chunk.indexOf(closeTag, searchStart);\n if (endIdx !== -1) {\n currentContent += chunk.slice(searchStart, endIdx);\n const shouldStop = onMatch({\n openTag: currentOpenTag,\n content: currentContent.trim(),\n });\n if (shouldStop) return;\n capturing = false;\n currentContent = '';\n currentOpenTag = '';\n searchStart = endIdx + closeTag.length;\n } else {\n currentContent += chunk.slice(searchStart, -closeTag.length);\n leftover = chunk.slice(-closeTag.length);\n break;\n }\n }\n }\n }\n } finally {\n closeSync(fd);\n }\n}\n\nexport function parseImageScripts(html: string): Record<string, string> {\n const imageMap: Record<string, string> = {};\n const regex =\n /<script type=\"midscene-image\" data-id=\"([^\"]+)\">([\\s\\S]*?)<\\/script>/g;\n\n for (const match of html.matchAll(regex)) {\n const [, id, content] = match;\n imageMap[id] = unescapeContent(content);\n }\n\n return imageMap;\n}\n\nexport function parseDumpScript(html: string): string {\n // Use string search instead of regex to avoid ReDoS vulnerability\n // Find the LAST dump script tag (template may contain similar patterns in bundled JS)\n const scriptOpenTag = '<script type=\"midscene_web_dump\"';\n const closeTag = htmlScriptCloseTag();\n\n // Find the last occurrence of the opening tag\n const lastOpenIndex = html.lastIndexOf(scriptOpenTag);\n if (lastOpenIndex === -1) {\n throw new Error('No dump script found in HTML');\n }\n\n // Find the end of the opening tag (the '>' character)\n const tagEndIndex = html.indexOf('>', lastOpenIndex);\n if (tagEndIndex === -1) {\n throw new Error('No dump script found in HTML');\n }\n\n // Find the closing tag after the opening tag\n const closeIndex = html.indexOf(closeTag, tagEndIndex);\n if (closeIndex === -1) {\n throw new Error('No dump script found in HTML');\n }\n\n // Extract content between opening and closing tags\n const content = html.substring(tagEndIndex + 1, closeIndex);\n return unescapeContent(content);\n}\n\nexport function parseDumpScriptAttributes(\n html: string,\n): Record<string, string> {\n const regex = /<script type=\"midscene_web_dump\"([^>]*)>/;\n const match = regex.exec(html);\n\n if (!match) {\n return {};\n }\n\n const attrString = match[1];\n const attributes: Record<string, string> = {};\n const attrRegex = /(\\w+)=\"([^\"]*)\"/g;\n\n for (const attrMatch of attrString.matchAll(attrRegex)) {\n const [, key, value] = attrMatch;\n if (key !== 'type') {\n attributes[key] = decodeURIComponent(value);\n }\n }\n\n return attributes;\n}\n\nexport function generateImageScriptTag(id: string, data: string): string {\n // Do not use template string here, will cause bundle error with <script\n const closeTag = htmlScriptCloseTag();\n return (\n // biome-ignore lint/style/useTemplate: <explanation>\n '<script type=\"midscene-image\" data-id=\"' +\n id +\n '\">' +\n escapeContent(data) +\n closeTag\n );\n}\n\n/**\n * Inline script that fixes relative URL resolution for directory-mode reports.\n *\n * Problem: when a static server (e.g. `npx serve`) serves `name/index.html`\n * at URL `/name` (without trailing slash), relative paths like\n * `./screenshots/xxx.png` resolve to `/screenshots/xxx.png` instead of\n * `/name/screenshots/xxx.png`.\n *\n * Fix: dynamically insert a <base> tag so relative URLs resolve correctly.\n */\n// Do not use template string here, will cause bundle error with <script\n//\n// The closing script tag is built at runtime so bundlers cannot inline the\n// token that would prematurely close the report template's inline app bundle.\n//\n// Do NOT replace this with a string constant, hex escape (\\x3c), or literal\n// string concatenation. Bundlers may optimise those forms back to the unsafe\n// token.\nlet _baseUrlFixScript: string;\nexport function getBaseUrlFixScript(): string {\n if (!_baseUrlFixScript) {\n const close = htmlScriptCloseTag();\n _baseUrlFixScript =\n // biome-ignore lint/style/useTemplate: see above\n '\\n<script>(function(){' +\n 'var p=window.location.pathname;' +\n 'if(p.endsWith(\"/\")||/\\\\.\\\\w+$/.test(p))return;' +\n 'var b=document.createElement(\"base\");' +\n 'b.href=p+\"/\";' +\n 'document.head.insertBefore(b,document.head.firstChild)' +\n '})()' +\n close +\n '\\n';\n }\n return _baseUrlFixScript;\n}\n\n/**\n * Dump-script attribute that records how the report file stores screenshots.\n * Written by the report generator and the merger, read back when deciding\n * whether a report is in directory mode. Kept here, next to dump-tag\n * generation, so the writer and reader share one source of truth.\n */\nexport const DATA_SCREENSHOT_MODE_ATTR = 'data-screenshot-mode';\n\nexport function generateDumpScriptTag(\n json: string,\n attributes?: Record<string, string | number | boolean>,\n): string {\n const closeTag = htmlScriptCloseTag();\n let attrString = '';\n if (attributes && Object.keys(attributes).length > 0) {\n // Do not use template string here, will cause bundle error with <script\n attrString =\n // biome-ignore lint/style/useTemplate: <explanation>\n ' ' +\n Object.entries(attributes)\n // biome-ignore lint/style/useTemplate: <explanation>\n .map(([k, v]) => k + '=\"' + encodeURIComponent(v) + '\"')\n .join(' ');\n }\n\n // Do not use template string here, will cause bundle error with <script\n return (\n // biome-ignore lint/style/useTemplate: <explanation>\n '<script type=\"midscene_web_dump\"' +\n attrString +\n '>' +\n escapeContent(json) +\n closeTag\n );\n}\n"],"names":["escapeContent","escapeScriptTag","unescapeContent","antiEscapeScriptTag","cleanHtmlCommentValue","value","String","formatModelBriefForAgent","brief","intent","model","description","hasUsageModelInfo","usage","Boolean","formatUsageModelForAgent","source","collectUsageModelsForAgent","report","models","Map","executions","Array","execution","tasks","task","taskWithUsage","usages","formatted","generateAgentReportComment","taskCount","sum","modelBriefs","lines","htmlScriptCloseTag","generateTestRunReportScriptTag","dump","TEST_RUN_REPORT_SCRIPT_TYPE","JSON","extractTestRunReportDumpSync","filePath","result","openTag","streamScanTags","content","tagEnd","attributes","type","Error","parsed","STREAMING_CHUNK_SIZE","StreamingTagMatcher","nextChunk","chunk","searchStart","startIndex","retainedSuffixLength","Math","endIndex","contentEnd","closeTag","onMatch","fd","openSync","fileSize","statSync","buffer","Buffer","decoder","StringDecoder","matcher","position","bytesRead","readSync","closeSync","streamScanTagsAsync","handle","openAsync","extractImageByIdSync","htmlPath","imageId","targetTag","streamImageScriptsToFile","srcFilePath","destFilePath","writtenImageIds","Set","appendFileSync","require","parseImageScriptId","contentAfterType","match","collectImageScriptIds","imageIds","extractLastDumpScriptSync","openTagPrefix","lastContent","leftover","capturing","currentContent","endIdx","startIdx","tagEndIdx","extractAllDumpScriptsSync","results","streamDumpScriptsSync","dumpScript","currentOpenTag","shouldStop","parseImageScripts","html","imageMap","regex","id","parseDumpScript","scriptOpenTag","lastOpenIndex","tagEndIndex","closeIndex","parseDumpScriptAttributes","attrString","attrRegex","attrMatch","key","decodeURIComponent","generateImageScriptTag","data","_baseUrlFixScript","getBaseUrlFixScript","close","DATA_SCREENSHOT_MODE_ATTR","generateDumpScriptTag","json","Object","k","v","encodeURIComponent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUO,MAAMA,gBAAgBC;AACtB,MAAMC,kBAAkBC;AAE/B,SAASC,sBAAsBC,KAAc;IAC3C,OAAOC,OAAOD,SAAS,OACpB,OAAO,CAAC,OAAO,IACf,OAAO,CAAC,OAAO;AACpB;AAEA,SAASE,yBAAyBC,KAAiB;IACjD,MAAMC,SAASD,MAAM,MAAM,IAAI;IAC/B,MAAME,QAAQF,MAAM,IAAI,IAAI;IAC5B,MAAMG,cAAcH,MAAM,gBAAgB,GACtC,CAAC,EAAE,EAAEA,MAAM,gBAAgB,CAAC,CAAC,CAAC,GAC9B;IACJ,OAAO,GAAGC,OAAO,EAAE,EAAEC,QAAQC,aAAa;AAC5C;AAEA,SAASC,kBAAkBC,KAAmB;IAC5C,OAAOC,QACLD,SACGA,CAAAA,MAAM,UAAU,IACfA,MAAM,mBAAmB,IACzBA,MAAM,iBAAiB,IACvBA,MAAM,MAAK;AAEnB;AAEA,SAASE,yBAAyBC,MAAc,EAAEH,KAAkB;IAClE,MAAMJ,SAASI,MAAM,MAAM,IAAIG;IAC/B,MAAMN,QAAQG,MAAM,UAAU,IAAIA,MAAM,mBAAmB,IAAI;IAC/D,MAAMF,cAAcE,MAAM,iBAAiB,GACvC,CAAC,EAAE,EAAEA,MAAM,iBAAiB,CAAC,CAAC,CAAC,GAC/B;IACJ,OAAO,GAAGJ,OAAO,EAAE,EAAEC,QAAQC,aAAa;AAC5C;AAEA,SAASM,2BAA2BC,MAAyB;IAC3D,MAAMC,SAAS,IAAIC;IACnB,MAAMC,aAAaC,MAAM,OAAO,CAACJ,OAAO,UAAU,IAAIA,OAAO,UAAU,GAAG,EAAE;IAC5E,KAAK,MAAMK,aAAaF,WAAY;QAClC,MAAMG,QA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,MAAM,GAAGqH;QACvB,IAAIC,AAAQ,WAARA,KACF7E,UAAU,CAAC6E,IAAI,GAAGC,mBAAmBvH;IAEzC;IAEA,OAAOyC;AACT;AAEO,SAAS+E,uBAAuBZ,EAAU,EAAEa,IAAY;IAE7D,MAAMlE,WAAW1B;IACjB,OAEE,4CACA+E,KACA,OACAjH,cAAc8H,QACdlE;AAEJ;AAoBA,IAAImE;AACG,SAASC;IACd,IAAI,CAACD,mBAAmB;QACtB,MAAME,QAAQ/F;QACd6F,oBAEE,oNAOAE,QACA;IACJ;IACA,OAAOF;AACT;AAQO,MAAMG,4BAA4B;AAElC,SAASC,sBACdC,IAAY,EACZtF,UAAsD;IAEtD,MAAMc,WAAW1B;IACjB,IAAIsF,aAAa;IACjB,IAAI1E,cAAcuF,OAAO,IAAI,CAACvF,YAAY,MAAM,GAAG,GAEjD0E,aAEE,MACAa,OAAO,OAAO,CAACvF,YAEZ,GAAG,CAAC,CAAC,CAACwF,GAAGC,EAAE,GAAKD,IAAI,OAAOE,mBAAmBD,KAAK,KACnD,IAAI,CAAC;IAIZ,OAEE,qCACAf,aACA,MACAxH,cAAcoI,QACdxE;AAEJ"}
|
|
1
|
+
{"version":3,"file":"dump/html-utils.mjs","sources":["../../../src/dump/html-utils.ts"],"sourcesContent":["import { closeSync, openSync, readSync, statSync } from 'node:fs';\nimport { open as openAsync } from 'node:fs/promises';\nimport { StringDecoder } from 'node:string_decoder';\nimport {\n REPORT_ARTIFACT_SCRIPT_TYPE,\n assertReportArtifactPath,\n} from '@midscene/shared/report-artifact';\nimport { antiEscapeScriptTag, escapeScriptTag } from '@midscene/shared/utils';\nimport {\n TEST_RUN_REPORT_SCRIPT_TYPE,\n type TestRunReportDump,\n} from '../test-run-report';\nimport type { AIUsageInfo, IReportActionDump, ModelBrief } from '../types';\n\nexport const escapeContent = escapeScriptTag;\nexport const unescapeContent = antiEscapeScriptTag;\n\nfunction cleanHtmlCommentValue(value: unknown): string {\n return String(value ?? 'N/A')\n .replace(/\\0/g, '')\n .replace(/--/g, '- -');\n}\n\nfunction formatModelBriefForAgent(brief: ModelBrief): string {\n const intent = brief.intent || 'default';\n const model = brief.name || 'unknown';\n const description = brief.modelDescription\n ? ` (${brief.modelDescription})`\n : '';\n return `${intent}: ${model}${description}`;\n}\n\nfunction hasUsageModelInfo(usage?: AIUsageInfo): usage is AIUsageInfo {\n return Boolean(\n usage &&\n (usage.model_name ||\n usage.response_model_name ||\n usage.model_description ||\n usage.intent),\n );\n}\n\nfunction formatUsageModelForAgent(source: string, usage: AIUsageInfo): string {\n const intent = usage.intent || source;\n const model = usage.model_name || usage.response_model_name || 'unknown';\n const description = usage.model_description\n ? ` (${usage.model_description})`\n : '';\n return `${intent}: ${model}${description}`;\n}\n\nfunction collectUsageModelsForAgent(report: IReportActionDump): string {\n const models = new Map<string, string>();\n const executions = Array.isArray(report.executions) ? report.executions : [];\n for (const execution of executions) {\n const tasks = Array.isArray(execution.tasks) ? execution.tasks : [];\n for (const task of tasks) {\n const taskWithUsage = task as {\n usage?: AIUsageInfo;\n searchAreaUsage?: AIUsageInfo;\n };\n const usages: Array<[string, AIUsageInfo | undefined]> = [\n ['main', taskWithUsage.usage],\n ['searchArea', taskWithUsage.searchAreaUsage],\n ];\n\n for (const [source, usage] of usages) {\n if (!hasUsageModelInfo(usage)) {\n continue;\n }\n const formatted = formatUsageModelForAgent(source, usage);\n models.set(formatted, formatted);\n }\n }\n }\n\n return Array.from(models.values()).join('; ');\n}\n\nexport function generateAgentReportComment(report: IReportActionDump): string {\n const executions = Array.isArray(report.executions) ? report.executions : [];\n const taskCount = executions.reduce(\n (sum, execution) =>\n sum + (Array.isArray(execution.tasks) ? execution.tasks.length : 0),\n 0,\n );\n const modelBriefs = report.modelBriefs?.length\n ? report.modelBriefs.map(formatModelBriefForAgent).join('; ')\n : collectUsageModelsForAgent(report) || 'No model metadata recorded';\n\n const lines = [\n 'For Agent Analysis:',\n `Report: ${cleanHtmlCommentValue(report.groupName)}`,\n `SDK: ${cleanHtmlCommentValue(report.sdkVersion)}`,\n `Device: ${cleanHtmlCommentValue(report.deviceType)}`,\n `Executions: ${executions.length}; Tasks: ${taskCount}`,\n `Models: ${cleanHtmlCommentValue(modelBriefs)}`,\n 'Structured report JSON is stored in script[type=\"midscene_web_dump\"] tags near this comment.',\n 'Screenshots are stored as script[type=\"midscene-image\"] tags or files referenced by screenshot refs.',\n 'For AI analysis, inspect each execution task for type, status, timing, param, output, usage, searchAreaUsage, recorder, and screenshot refs.',\n 'Use the Markdown export when available; it contains the same report context plus image links for agent review.',\n ];\n\n return `\\n<!--\\n${lines.join('\\n')}\\n-->\\n`;\n}\n\nfunction htmlScriptCloseTag(): string {\n // biome-ignore lint/style/useTemplate: keep this token runtime-built for inline report bundles\n return String.fromCharCode(60) + '/script>';\n}\n\n/** Directory reports declare their data entry separately from the Viewer. */\nexport function generateReportArtifactScriptTag(path: string): string {\n assertReportArtifactPath(path);\n return [\n String.fromCharCode(60),\n 'script type=\"',\n REPORT_ARTIFACT_SCRIPT_TYPE,\n '\">',\n JSON.stringify(path),\n htmlScriptCloseTag(),\n ].join('');\n}\n\nfunction reportArtifactPathExtractor(filePath: string) {\n let result: string | undefined;\n return {\n get path() {\n return result;\n },\n visit: (content: string) => {\n const tagEnd = content.indexOf('>');\n const type = content\n .slice(0, tagEnd)\n .match(/(?:^|\\s)type\\s*=\\s*[\"']([^\"']+)[\"']/i)?.[1];\n if (type !== REPORT_ARTIFACT_SCRIPT_TYPE) return false;\n if (result !== undefined)\n throw new Error(\n `Report contains multiple artifact entries: ${filePath}`,\n );\n const path: unknown = JSON.parse(\n unescapeContent(content.slice(tagEnd + 1)),\n );\n assertReportArtifactPath(path);\n result = path;\n return false;\n },\n };\n}\n\nexport function extractReportArtifactPathSync(\n filePath: string,\n): string | undefined {\n const extractor = reportArtifactPathExtractor(filePath);\n streamScanTags(\n filePath,\n `${String.fromCharCode(60)}script`,\n htmlScriptCloseTag(),\n extractor.visit,\n );\n return extractor.path;\n}\n\nexport async function extractReportArtifactPathAsync(\n filePath: string,\n): Promise<string | undefined> {\n const extractor = reportArtifactPathExtractor(filePath);\n await streamScanTagsAsync(\n filePath,\n `${String.fromCharCode(60)}script`,\n htmlScriptCloseTag(),\n extractor.visit,\n );\n return extractor.path;\n}\n\n/** Consume complete elements so dump-tag strings in the Viewer are never payloads. */\nexport async function streamDumpScriptsAsync(\n filePath: string,\n visitor: (dump: { openTag: string; content: string }) => boolean,\n): Promise<void> {\n await streamScanTagsAsync(\n filePath,\n `${String.fromCharCode(60)}script`,\n htmlScriptCloseTag(),\n (content) => {\n const tagEnd = content.indexOf('>');\n const type = content\n .slice(0, tagEnd)\n .match(/(?:^|\\s)type\\s*=\\s*[\"']([^\"']+)[\"']/i)?.[1];\n return type === 'midscene_web_dump'\n ? visitor({\n openTag: content.slice(0, tagEnd + 1),\n content: content.slice(tagEnd + 1),\n })\n : false;\n },\n );\n}\n\n/** Avoid raw close tokens: this writer itself is bundled into report HTML. */\nexport function generateTestRunReportScriptTag(\n dump: TestRunReportDump,\n): string {\n return [\n String.fromCharCode(60),\n 'script type=\"',\n TEST_RUN_REPORT_SCRIPT_TYPE,\n '\">\\n',\n escapeScriptTag(JSON.stringify(dump)),\n '\\n',\n htmlScriptCloseTag(),\n '\\n',\n ].join('');\n}\n\nexport function extractTestRunReportDumpSync(\n filePath: string,\n): TestRunReportDump | undefined {\n let result: TestRunReportDump | undefined;\n // Consume executable scripts as whole elements: the embedded viewer itself\n // contains report-writer source with data-tag strings that are not payloads.\n const openTag = `${String.fromCharCode(60)}script`;\n streamScanTags(filePath, openTag, htmlScriptCloseTag(), (content) => {\n const tagEnd = content.indexOf('>');\n const attributes = content.slice(0, tagEnd);\n const type = attributes.match(/(?:^|\\s)type\\s*=\\s*[\"']([^\"']+)[\"']/i)?.[1];\n if (type !== TEST_RUN_REPORT_SCRIPT_TYPE) return false;\n if (result)\n throw new Error(\n `Report contains multiple Midscene Test dumps: ${filePath}`,\n );\n const parsed = JSON.parse(unescapeContent(content.slice(tagEnd + 1)));\n if (\n parsed?.schemaVersion !== 1 ||\n parsed?.kind !== 'test-runner' ||\n !Array.isArray(parsed.projects)\n )\n throw new Error(`Invalid Midscene Test report dump: ${filePath}`);\n result = parsed;\n return false;\n });\n return result;\n}\n\n/** Chunk size for streaming file operations (64KB) */\nexport const STREAMING_CHUNK_SIZE = 64 * 1024;\n\n/**\n * Callback for processing matched tags during streaming.\n * @param content - The content between open and close tags\n * @returns true to stop scanning, false to continue\n */\ntype TagMatchCallback = (content: string) => boolean;\n\nclass StreamingTagMatcher {\n private leftover = '';\n private capturing = false;\n private currentContent = '';\n\n constructor(\n private readonly openTag: string,\n private readonly closeTag: string,\n private readonly onMatch: TagMatchCallback,\n ) {}\n\n push(nextChunk: string): boolean {\n const chunk = this.leftover + nextChunk;\n this.leftover = '';\n let searchStart = 0;\n\n while (searchStart < chunk.length) {\n if (!this.capturing) {\n const startIndex = chunk.indexOf(this.openTag, searchStart);\n if (startIndex === -1) {\n const retainedSuffixLength = Math.max(0, this.openTag.length - 1);\n this.leftover = retainedSuffixLength\n ? chunk.slice(-retainedSuffixLength)\n : '';\n return false;\n }\n this.capturing = true;\n searchStart = startIndex + this.openTag.length;\n }\n\n const endIndex = chunk.indexOf(this.closeTag, searchStart);\n if (endIndex !== -1) {\n this.currentContent += chunk.slice(searchStart, endIndex);\n if (this.onMatch(this.currentContent)) return true;\n this.capturing = false;\n this.currentContent = '';\n searchStart = endIndex + this.closeTag.length;\n continue;\n }\n\n const retainedSuffixLength = Math.max(0, this.closeTag.length - 1);\n const contentEnd = Math.max(\n searchStart,\n chunk.length - retainedSuffixLength,\n );\n this.currentContent += chunk.slice(searchStart, contentEnd);\n this.leftover = chunk.slice(contentEnd);\n return false;\n }\n\n return false;\n }\n}\n\n/**\n * Stream through a file and find tags matching the pattern.\n * Memory usage: O(chunk_size + tag_size), not O(file_size).\n *\n * @param filePath - Absolute path to the file\n * @param openTag - Opening tag to search for\n * @param closeTag - Closing tag\n * @param onMatch - Callback for each matched tag content\n */\nexport function streamScanTags(\n filePath: string,\n openTag: string,\n closeTag: string,\n onMatch: TagMatchCallback,\n): void {\n const fd = openSync(filePath, 'r');\n const fileSize = statSync(filePath).size;\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n const decoder = new StringDecoder('utf8');\n const matcher = new StreamingTagMatcher(openTag, closeTag, onMatch);\n let position = 0;\n\n try {\n while (position < fileSize) {\n const bytesRead = readSync(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);\n position += bytesRead;\n if (matcher.push(decoder.write(buffer.subarray(0, bytesRead)))) return;\n }\n matcher.push(decoder.end());\n } finally {\n closeSync(fd);\n }\n}\n\n/** Asynchronously stream tags without blocking the Node.js event loop. */\nexport async function streamScanTagsAsync(\n filePath: string,\n openTag: string,\n closeTag: string,\n onMatch: TagMatchCallback,\n): Promise<void> {\n const handle = await openAsync(filePath, 'r');\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n const decoder = new StringDecoder('utf8');\n let position = 0;\n const matcher = new StreamingTagMatcher(openTag, closeTag, onMatch);\n\n try {\n while (true) {\n const { bytesRead } = await handle.read(\n buffer,\n 0,\n STREAMING_CHUNK_SIZE,\n position,\n );\n if (bytesRead === 0) {\n matcher.push(decoder.end());\n return;\n }\n position += bytesRead;\n if (matcher.push(decoder.write(buffer.subarray(0, bytesRead)))) return;\n }\n } finally {\n await handle.close();\n }\n}\n\n/**\n * Synchronously extract a specific image's base64 data from an HTML file by its id.\n * Uses streaming to avoid loading the entire file into memory.\n *\n * @param htmlPath - Absolute path to the HTML file\n * @param imageId - The id of the image to extract\n * @returns The base64 data string, or null if not found\n */\nexport function extractImageByIdSync(\n htmlPath: string,\n imageId: string,\n): string | null {\n const targetTag = `<script type=\"midscene-image\" data-id=\"${imageId}\">`;\n const closeTag = htmlScriptCloseTag();\n\n let result: string | null = null;\n\n streamScanTags(htmlPath, targetTag, closeTag, (content) => {\n result = unescapeContent(content);\n return true; // Stop after first match\n });\n\n return result;\n}\n\n/**\n * Stream image script tags from source file directly to output file.\n * Memory usage: O(single_image_size), not O(all_images_size).\n *\n * @param srcFilePath - Source HTML file path\n * @param destFilePath - Destination file path to append to\n * @param writtenImageIds - IDs already written to the destination\n */\nexport function streamImageScriptsToFile(\n srcFilePath: string,\n destFilePath: string,\n writtenImageIds: Set<string> = new Set(),\n): void {\n const { appendFileSync } = require('node:fs');\n const openTag = '<script type=\"midscene-image\"';\n const closeTag = htmlScriptCloseTag();\n\n streamScanTags(srcFilePath, openTag, closeTag, (content) => {\n const imageId = parseImageScriptId(content);\n if (!imageId || writtenImageIds.has(imageId)) {\n return false;\n }\n // Write complete tag immediately to destination, don't accumulate\n appendFileSync(destFilePath, `${openTag}${content}${closeTag}\\n`);\n writtenImageIds.add(imageId);\n return false; // Continue scanning for more tags\n });\n}\n\nfunction parseImageScriptId(contentAfterType: string): string | null {\n const match = /^ data-id=\"([a-z0-9_-]{1,128})\">/i.exec(contentAfterType);\n return match?.[1] ?? null;\n}\n\n/** Collect IDs of real inline image script tags without blocking on a large report. */\nexport async function collectImageScriptIds(\n filePath: string,\n): Promise<Set<string>> {\n const imageIds = new Set<string>();\n const openTag = '<script type=\"midscene-image\"';\n const closeTag = htmlScriptCloseTag();\n\n await streamScanTagsAsync(filePath, openTag, closeTag, (content) => {\n const imageId = parseImageScriptId(content);\n if (imageId) imageIds.add(imageId);\n return false;\n });\n return imageIds;\n}\n\n/**\n * Extract the LAST dump script content from HTML file using streaming.\n * Memory usage: O(dump_size), not O(file_size).\n *\n * @param filePath - Absolute path to the HTML file\n * @returns The dump script content (trimmed), or empty string if not found\n */\nexport function extractLastDumpScriptSync(filePath: string): string {\n const openTagPrefix = '<script type=\"midscene_web_dump\"';\n const closeTag = htmlScriptCloseTag();\n\n let lastContent = '';\n\n // Custom streaming to handle the special case where open tag has variable attributes\n const fd = openSync(filePath, 'r');\n const fileSize = statSync(filePath).size;\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n\n let position = 0;\n let leftover = '';\n let capturing = false;\n let currentContent = '';\n\n try {\n while (position < fileSize) {\n const bytesRead = readSync(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);\n const chunk = leftover + buffer.toString('utf-8', 0, bytesRead);\n position += bytesRead;\n\n let searchStart = 0;\n\n while (searchStart < chunk.length) {\n if (!capturing) {\n const startIdx = chunk.indexOf(openTagPrefix, searchStart);\n if (startIdx !== -1) {\n // Find the end of the opening tag (the '>' character)\n const tagEndIdx = chunk.indexOf('>', startIdx);\n if (tagEndIdx !== -1) {\n capturing = true;\n currentContent = chunk.slice(tagEndIdx + 1);\n const endIdx = currentContent.indexOf(closeTag);\n if (endIdx !== -1) {\n lastContent = currentContent.slice(0, endIdx).trim();\n capturing = false;\n currentContent = '';\n searchStart = tagEndIdx + 1 + endIdx + closeTag.length;\n } else {\n leftover = currentContent.slice(-closeTag.length);\n currentContent = currentContent.slice(0, -closeTag.length);\n break;\n }\n } else {\n leftover = chunk.slice(startIdx);\n break;\n }\n } else {\n leftover = chunk.slice(-openTagPrefix.length);\n break;\n }\n } else {\n const endIdx = chunk.indexOf(closeTag, searchStart);\n if (endIdx !== -1) {\n currentContent += chunk.slice(searchStart, endIdx);\n lastContent = currentContent.trim();\n capturing = false;\n currentContent = '';\n searchStart = endIdx + closeTag.length;\n } else {\n currentContent += chunk.slice(searchStart, -closeTag.length);\n leftover = chunk.slice(-closeTag.length);\n break;\n }\n }\n }\n }\n } finally {\n closeSync(fd);\n }\n\n return lastContent;\n}\n\n/**\n * Extract ALL dump script contents from an HTML file using streaming.\n * Each entry includes the full opening tag (for attribute extraction) and the content.\n *\n * @param filePath - Absolute path to the HTML file\n * @returns Array of { openTag, content } for each dump script found\n */\nexport function extractAllDumpScriptsSync(\n filePath: string,\n): { openTag: string; content: string }[] {\n const results: { openTag: string; content: string }[] = [];\n streamDumpScriptsSync(filePath, (dumpScript) => {\n results.push(dumpScript);\n return false;\n });\n return results;\n}\n\n/**\n * Stream ALL dump scripts from an HTML file.\n * Calls onMatch for each dump script and keeps memory bounded to a single\n * dump script payload instead of accumulating every dump in memory.\n *\n * @param filePath - Absolute path to the HTML file\n * @param onMatch - Callback for each dump script; return true to stop early\n */\nexport function streamDumpScriptsSync(\n filePath: string,\n onMatch: (dumpScript: { openTag: string; content: string }) => boolean,\n): void {\n const openTagPrefix = '<script type=\"midscene_web_dump\"';\n const closeTag = htmlScriptCloseTag();\n\n const fd = openSync(filePath, 'r');\n const fileSize = statSync(filePath).size;\n const buffer = Buffer.alloc(STREAMING_CHUNK_SIZE);\n\n let position = 0;\n let leftover = '';\n let capturing = false;\n let currentContent = '';\n let currentOpenTag = '';\n\n try {\n while (position < fileSize) {\n const bytesRead = readSync(fd, buffer, 0, STREAMING_CHUNK_SIZE, position);\n const chunk = leftover + buffer.toString('utf-8', 0, bytesRead);\n position += bytesRead;\n\n let searchStart = 0;\n\n while (searchStart < chunk.length) {\n if (!capturing) {\n const startIdx = chunk.indexOf(openTagPrefix, searchStart);\n if (startIdx !== -1) {\n const tagEndIdx = chunk.indexOf('>', startIdx);\n if (tagEndIdx !== -1) {\n capturing = true;\n currentOpenTag = chunk.slice(startIdx, tagEndIdx + 1);\n currentContent = chunk.slice(tagEndIdx + 1);\n const endIdx = currentContent.indexOf(closeTag);\n if (endIdx !== -1) {\n const shouldStop = onMatch({\n openTag: currentOpenTag,\n content: currentContent.slice(0, endIdx).trim(),\n });\n if (shouldStop) return;\n capturing = false;\n currentContent = '';\n currentOpenTag = '';\n searchStart = tagEndIdx + 1 + endIdx + closeTag.length;\n } else {\n leftover = currentContent.slice(-closeTag.length);\n currentContent = currentContent.slice(0, -closeTag.length);\n break;\n }\n } else {\n leftover = chunk.slice(startIdx);\n break;\n }\n } else {\n leftover = chunk.slice(-openTagPrefix.length);\n break;\n }\n } else {\n const endIdx = chunk.indexOf(closeTag, searchStart);\n if (endIdx !== -1) {\n currentContent += chunk.slice(searchStart, endIdx);\n const shouldStop = onMatch({\n openTag: currentOpenTag,\n content: currentContent.trim(),\n });\n if (shouldStop) return;\n capturing = false;\n currentContent = '';\n currentOpenTag = '';\n searchStart = endIdx + closeTag.length;\n } else {\n currentContent += chunk.slice(searchStart, -closeTag.length);\n leftover = chunk.slice(-closeTag.length);\n break;\n }\n }\n }\n }\n } finally {\n closeSync(fd);\n }\n}\n\nexport function parseImageScripts(html: string): Record<string, string> {\n const imageMap: Record<string, string> = {};\n const regex =\n /<script type=\"midscene-image\" data-id=\"([^\"]+)\">([\\s\\S]*?)<\\/script>/g;\n\n for (const match of html.matchAll(regex)) {\n const [, id, content] = match;\n imageMap[id] = unescapeContent(content);\n }\n\n return imageMap;\n}\n\nexport function parseDumpScript(html: string): string {\n // Use string search instead of regex to avoid ReDoS vulnerability\n // Find the LAST dump script tag (template may contain similar patterns in bundled JS)\n const scriptOpenTag = '<script type=\"midscene_web_dump\"';\n const closeTag = htmlScriptCloseTag();\n\n // Find the last occurrence of the opening tag\n const lastOpenIndex = html.lastIndexOf(scriptOpenTag);\n if (lastOpenIndex === -1) {\n throw new Error('No dump script found in HTML');\n }\n\n // Find the end of the opening tag (the '>' character)\n const tagEndIndex = html.indexOf('>', lastOpenIndex);\n if (tagEndIndex === -1) {\n throw new Error('No dump script found in HTML');\n }\n\n // Find the closing tag after the opening tag\n const closeIndex = html.indexOf(closeTag, tagEndIndex);\n if (closeIndex === -1) {\n throw new Error('No dump script found in HTML');\n }\n\n // Extract content between opening and closing tags\n const content = html.substring(tagEndIndex + 1, closeIndex);\n return unescapeContent(content);\n}\n\nexport function parseDumpScriptAttributes(\n html: string,\n): Record<string, string> {\n const regex = /<script type=\"midscene_web_dump\"([^>]*)>/;\n const match = regex.exec(html);\n\n if (!match) {\n return {};\n }\n\n const attrString = match[1];\n const attributes: Record<string, string> = {};\n const attrRegex = /(\\w+)=\"([^\"]*)\"/g;\n\n for (const attrMatch of attrString.matchAll(attrRegex)) {\n const [, key, value] = attrMatch;\n if (key !== 'type') {\n attributes[key] = decodeURIComponent(value);\n }\n }\n\n return attributes;\n}\n\nexport function generateImageScriptTag(id: string, data: string): string {\n // Do not use template string here, will cause bundle error with <script\n const closeTag = htmlScriptCloseTag();\n return (\n // biome-ignore lint/style/useTemplate: <explanation>\n '<script type=\"midscene-image\" data-id=\"' +\n id +\n '\">' +\n escapeContent(data) +\n closeTag\n );\n}\n\n/**\n * Inline script that fixes relative URL resolution for directory-mode reports.\n *\n * Problem: when a static server (e.g. `npx serve`) serves `name/index.html`\n * at URL `/name` (without trailing slash), relative paths like\n * `./screenshots/xxx.png` resolve to `/screenshots/xxx.png` instead of\n * `/name/screenshots/xxx.png`.\n *\n * Fix: dynamically insert a <base> tag so relative URLs resolve correctly.\n */\n// Do not use template string here, will cause bundle error with <script\n//\n// The closing script tag is built at runtime so bundlers cannot inline the\n// token that would prematurely close the report template's inline app bundle.\n//\n// Do NOT replace this with a string constant, hex escape (\\x3c), or literal\n// string concatenation. Bundlers may optimise those forms back to the unsafe\n// token.\nlet _baseUrlFixScript: string;\nexport function getBaseUrlFixScript(): string {\n if (!_baseUrlFixScript) {\n const close = htmlScriptCloseTag();\n _baseUrlFixScript =\n // biome-ignore lint/style/useTemplate: see above\n '\\n<script>(function(){' +\n 'var p=window.location.pathname;' +\n 'if(p.endsWith(\"/\")||/\\\\.\\\\w+$/.test(p))return;' +\n 'var b=document.createElement(\"base\");' +\n 'b.href=p+\"/\";' +\n 'document.head.insertBefore(b,document.head.firstChild)' +\n '})()' +\n close +\n '\\n';\n }\n return _baseUrlFixScript;\n}\n\n/**\n * Dump-script attribute that records how the report file stores screenshots.\n * Written by the report generator and the merger, read back when deciding\n * whether a report is in directory mode. Kept here, next to dump-tag\n * generation, so the writer and reader share one source of truth.\n */\nexport const DATA_SCREENSHOT_MODE_ATTR = 'data-screenshot-mode';\n\nexport function generateDumpScriptTag(\n json: string,\n attributes?: Record<string, string | number | boolean>,\n): string {\n const closeTag = htmlScriptCloseTag();\n let attrString = '';\n if (attributes && Object.keys(attributes).length > 0) {\n // Do not use template string here, will cause bundle error with <script\n attrString =\n // biome-ignore lint/style/useTemplate: <explanation>\n ' ' +\n Object.entries(attributes)\n // biome-ignore lint/style/useTemplate: <explanation>\n .map(([k, v]) => k + '=\"' + encodeURIComponent(v) + '\"')\n .join(' ');\n }\n\n // Do not use template string here, will cause bundle error with <script\n return (\n // biome-ignore lint/style/useTemplate: <explanation>\n '<script type=\"midscene_web_dump\"' +\n attrString +\n '>' +\n escapeContent(json) +\n closeTag\n );\n}\n"],"names":["escapeContent","escapeScriptTag","unescapeContent","antiEscapeScriptTag","cleanHtmlCommentValue","value","String","formatModelBriefForAgent","brief","intent","model","description","hasUsageModelInfo","usage","Boolean","formatUsageModelForAgent","source","collectUsageModelsForAgent","report","models","Map","executions","Array","execution","tasks","task","taskWithUsage","usages","formatted","generateAgentReportComment","taskCount","sum","modelBriefs","lines","htmlScriptCloseTag","generateReportArtifactScriptTag","path","assertReportArtifactPath","REPORT_ARTIFACT_SCRIPT_TYPE","JSON","reportArtifactPathExtractor","filePath","result","content","tagEnd","type","undefined","Error","extractReportArtifactPathSync","extractor","streamScanTags","extractReportArtifactPathAsync","streamScanTagsAsync","streamDumpScriptsAsync","visitor","generateTestRunReportScriptTag","dump","TEST_RUN_REPORT_SCRIPT_TYPE","extractTestRunReportDumpSync","openTag","attributes","parsed","STREAMING_CHUNK_SIZE","StreamingTagMatcher","nextChunk","chunk","searchStart","startIndex","retainedSuffixLength","Math","endIndex","contentEnd","closeTag","onMatch","fd","openSync","fileSize","statSync","buffer","Buffer","decoder","StringDecoder","matcher","position","bytesRead","readSync","closeSync","handle","openAsync","extractImageByIdSync","htmlPath","imageId","targetTag","streamImageScriptsToFile","srcFilePath","destFilePath","writtenImageIds","Set","appendFileSync","require","parseImageScriptId","contentAfterType","match","collectImageScriptIds","imageIds","extractLastDumpScriptSync","openTagPrefix","lastContent","leftover","capturing","currentContent","endIdx","startIdx","tagEndIdx","extractAllDumpScriptsSync","results","streamDumpScriptsSync","dumpScript","currentOpenTag","shouldStop","parseImageScripts","html","imageMap","regex","id","parseDumpScript","scriptOpenTag","lastOpenIndex","tagEndIndex","closeIndex","parseDumpScriptAttributes","attrString","attrRegex","attrMatch","key","decodeURIComponent","generateImageScriptTag","data","_baseUrlFixScript","getBaseUrlFixScript","close","DATA_SCREENSHOT_MODE_ATTR","generateDumpScriptTag","json","Object","k","v","encodeURIComponent"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcO,MAAMA,gBAAgBC;AACtB,MAAMC,kBAAkBC;AAE/B,SAASC,sBAAsBC,KAAc;IAC3C,OAAOC,OAAOD,SAAS,OACpB,OAAO,CAAC,OAAO,IACf,OAAO,CAAC,OAAO;AACpB;AAEA,SAASE,yBAAyBC,KAAiB;IACjD,MAAMC,SAASD,MAAM,MAAM,IAAI;IAC/B,MAAME,QAAQF,MAAM,IAAI,IAAI;IAC5B,MAAMG,cAAcH,MAAM,gBAAgB,GACtC,CAAC,EAAE,EAAEA,MAAM,gBAAgB,CAAC,CAAC,CAAC,GAC9B;IACJ,OAAO,GAAGC,OAAO,EAAE,EAAEC,QAAQC,aAAa;AAC5C;AAEA,SAASC,kBAAkBC,KAAmB;IAC5C,OAAOC,QACLD,SACGA,CAAAA,MAAM,UAAU,IACfA,MAAM,mBAAmB,IACzBA,MAAM,iBAAiB,IACvBA,MAAM,MAAK;AAEnB;AAEA,SAASE,yBAAyBC,MAAc,EAAEH,KAAkB;IAClE,MAAMJ,SAASI,MAAM,MAAM,IAAIG;IAC/B,MAAMN,QAAQG,MAAM,UAAU,IAAIA,MAAM,mBAAmB,IAAI;IAC/D,MAAMF,cAAcE,MAAM,iBAAiB,GACvC,CAAC,EAAE,EAAEA,MAAM,iBAAiB,CAAC,CAAC,CAAC,GAC/B;IACJ,OAAO,GAAGJ,OAAO,EAAE,EAAEC,QAAQC,aAAa;AAC5C;AAEA,SAASM,2BAA2BC,MAAyB;IAC3D,MAAMC,SAAS,IAAIC;IACnB,MAAMC,aAAaC,MAAM,OA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