@midscene/shared 1.16.1 → 1.16.2

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.
@@ -0,0 +1,3 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const createConsoleContext = ()=>new AsyncLocalStorage();
3
+ export { createConsoleContext };
@@ -0,0 +1,5 @@
1
+ const createConsoleContext = ()=>({
2
+ getStore: ()=>void 0,
3
+ run: (_store, callback)=>callback()
4
+ });
5
+ export { createConsoleContext };
@@ -18,7 +18,7 @@ class ModelConfigManager {
18
18
  configMap = this.normalizeModelConfig(this.modelConfig);
19
19
  } else configMap = this.globalConfigManager?.getAllEnvConfig() || {};
20
20
  const defaultConfig = decideModelConfigFromIntentConfig('default', configMap);
21
- if (!defaultConfig) throw new Error('Model configuration is incomplete: model name (MIDSCENE_MODEL_NAME) is required. See https://midscenejs.com/model-strategy.html');
21
+ if (!defaultConfig) throw new Error('Model configuration is incomplete: model name (MIDSCENE_MODEL_NAME) is required. See https://midscenejs.com/model-api-setup');
22
22
  if ('jev' === defaultConfig.modelFamily) throw new Error('Jev cannot be the default model. Configure a general-purpose MIDSCENE_MODEL_FAMILY and use Jev in Locate, Planning, or Insight.');
23
23
  const insightConfig = decideModelConfigFromIntentConfig('insight', configMap);
24
24
  const planningConfig = decideModelConfigFromIntentConfig('planning', configMap);
@@ -77,7 +77,7 @@ class ModelConfigManager {
77
77
  }
78
78
  throwErrorIfNonVLModel() {
79
79
  const modelConfig = this.getModelConfig('locate');
80
- if (!modelConfig.modelFamily) throw new Error(`${'locate' === modelConfig.slot ? 'MIDSCENE_LOCATE_MODEL_FAMILY' : 'MIDSCENE_MODEL_FAMILY'} is not set to a multimodal model with UI localization, so element localization cannot be achieved. Check your model configuration. See https://midscenejs.com/model-strategy.html`);
80
+ if (!modelConfig.modelFamily) throw new Error(`${'locate' === modelConfig.slot ? 'MIDSCENE_LOCATE_MODEL_FAMILY' : 'MIDSCENE_MODEL_FAMILY'} is not set to a multimodal model with UI localization, so element localization cannot be achieved. Check your model configuration. See https://midscenejs.com/model-api-setup`);
81
81
  }
82
82
  constructor(modelConfig, createOpenAIClientFn){
83
83
  _define_property(this, "modelConfigMap", void 0);
@@ -4,8 +4,8 @@ import { getDebug } from "../logger.mjs";
4
4
  import { assert } from "../utils.mjs";
5
5
  import { maskConfig, parseJson } from "./helper.mjs";
6
6
  import { initDebugConfig } from "./init-debug.mjs";
7
- const MODEL_CONFIG_DOC_URL = 'https://midscenejs.com/model-common-config.html';
8
- const getCurrentVersion = ()=>"1.16.1";
7
+ const MODEL_CONFIG_DOC_URL = 'https://midscenejs.com/model-api-setup.html';
8
+ const getCurrentVersion = ()=>"1.16.2";
9
9
  const getInvalidModelFamilyMessage = (modelFamily)=>`Invalid MIDSCENE_MODEL_FAMILY value: ${modelFamily}. Current version v${getCurrentVersion()} accepts the following model families: ${MODEL_FAMILY_VALUES.join(', ')}. You can also visit ${MODEL_CONFIG_DOC_URL} for the latest configuration information.`;
10
10
  const KEYS_MAP = {
11
11
  locate: LOCATE_MODEL_CONFIG_KEYS,
@@ -170,8 +170,8 @@ const decideModelConfigFromIntentConfig = (intent, configMap)=>{
170
170
  debugLog('decideModelConfig result by agent.modelConfig() with intent', intent, maskConfig({
171
171
  ...finalResult
172
172
  }));
173
- assert(finalResult.openaiBaseURL, `failed to get base URL of model (intent=${intent}). See https://midscenejs.com/model-strategy`);
174
- if (!finalResult.modelName) console.warn(`modelName is not set for intent ${intent}, this may cause unexpected behavior. See https://midscenejs.com/model-strategy`);
173
+ assert(finalResult.openaiBaseURL, `failed to get base URL of model (intent=${intent}). See https://midscenejs.com/model-api-setup`);
174
+ if (!finalResult.modelName) console.warn(`modelName is not set for intent ${intent}, this may cause unexpected behavior. See https://midscenejs.com/model-api-setup`);
175
175
  return finalResult;
176
176
  };
177
177
  export { decideModelConfigFromIntentConfig, getUITarsModelVersion, legacyConfigToModelFamily, parseOpenaiSdkConfig, validateModelFamily };
@@ -2,9 +2,35 @@ import node_fs from "node:fs";
2
2
  import node_path from "node:path";
3
3
  import node_util from "node:util";
4
4
  import debug from "debug";
5
+ import { createConsoleContext } from "#console-context";
5
6
  import { getMidsceneRunSubDir } from "./common.mjs";
6
7
  import { ifInNode } from "./utils.mjs";
7
8
  const topicPrefix = 'midscene';
9
+ const consoleContextKey = Symbol.for('@midscene/shared/console-context');
10
+ const consoleHost = globalThis;
11
+ consoleHost[consoleContextKey] ??= createConsoleContext();
12
+ const consoleContext = consoleHost[consoleContextKey];
13
+ const runWithConsoleLogHandler = (handler, run)=>consoleContext.run(handler, run);
14
+ const runWithConsoleLogScope = (scope, run)=>{
15
+ const handler = consoleContext.getStore();
16
+ if (!handler) return run();
17
+ return consoleContext.run((entry)=>handler({
18
+ ...entry,
19
+ scope: {
20
+ ...scope,
21
+ ...entry.scope
22
+ }
23
+ }), run);
24
+ };
25
+ function logReport(message) {
26
+ const handler = consoleContext.getStore();
27
+ if (handler) handler({
28
+ type: 'report',
29
+ topic: 'midscene:report',
30
+ message
31
+ });
32
+ else console.log(message);
33
+ }
8
34
  const logStreams = new Map();
9
35
  const logStreamPaths = new Map();
10
36
  let logDirectoryResolver;
@@ -78,17 +104,38 @@ function writeLogToFile(topic, message) {
78
104
  backpressuredLogStreams.delete(topicFileName);
79
105
  }
80
106
  }
107
+ function printConsoleWarning(topic, args, warning) {
108
+ const handler = consoleContext.getStore();
109
+ if (handler) return void handler({
110
+ type: 'warning',
111
+ topic,
112
+ message: node_util.format(...args),
113
+ args,
114
+ ...warning ? {
115
+ warning
116
+ } : {}
117
+ });
118
+ try {
119
+ console.warn('[Midscene]', ...args);
120
+ } catch {}
121
+ }
81
122
  function getDebug(topic, options) {
82
123
  const fullTopic = `${topicPrefix}:${topic}`;
83
124
  const withConsole = options?.console ?? false;
84
125
  const cacheKey = withConsole ? `${fullTopic}:withConsole` : fullTopic;
126
+ if (withConsole && options?.warning) {
127
+ const baseFn = getDebug(topic);
128
+ const warning = options.warning;
129
+ return (...args)=>{
130
+ baseFn(...args);
131
+ printConsoleWarning(fullTopic, args, warning);
132
+ };
133
+ }
85
134
  if (!debugInstances.has(cacheKey)) if (withConsole) {
86
135
  const baseFn = getDebug(topic);
87
136
  const wrapper = (...args)=>{
88
137
  baseFn(...args);
89
- try {
90
- console.warn('[Midscene]', ...args);
91
- } catch {}
138
+ printConsoleWarning(fullTopic, args);
92
139
  };
93
140
  debugInstances.set(cacheKey, wrapper);
94
141
  } else {
@@ -108,4 +155,4 @@ function enableDebug(topic) {
108
155
  if (ifInNode) return;
109
156
  debug.enable(`${topicPrefix}:${topic}`);
110
157
  }
111
- export { enableDebug, getDebug, setLogDirectoryResolver };
158
+ export { enableDebug, getDebug, logReport, runWithConsoleLogHandler, runWithConsoleLogScope, setLogDirectoryResolver };
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ createConsoleContext: ()=>createConsoleContext
28
+ });
29
+ const external_node_async_hooks_namespaceObject = require("node:async_hooks");
30
+ const createConsoleContext = ()=>new external_node_async_hooks_namespaceObject.AsyncLocalStorage();
31
+ exports.createConsoleContext = __webpack_exports__.createConsoleContext;
32
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
33
+ "createConsoleContext"
34
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
35
+ Object.defineProperty(exports, '__esModule', {
36
+ value: true
37
+ });
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ createConsoleContext: ()=>createConsoleContext
28
+ });
29
+ const createConsoleContext = ()=>({
30
+ getStore: ()=>void 0,
31
+ run: (_store, callback)=>callback()
32
+ });
33
+ exports.createConsoleContext = __webpack_exports__.createConsoleContext;
34
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
35
+ "createConsoleContext"
36
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
37
+ Object.defineProperty(exports, '__esModule', {
38
+ value: true
39
+ });
@@ -46,7 +46,7 @@ class ModelConfigManager {
46
46
  configMap = this.normalizeModelConfig(this.modelConfig);
47
47
  } else configMap = this.globalConfigManager?.getAllEnvConfig() || {};
48
48
  const defaultConfig = (0, external_parse_model_config_js_namespaceObject.decideModelConfigFromIntentConfig)('default', configMap);
49
- if (!defaultConfig) throw new Error('Model configuration is incomplete: model name (MIDSCENE_MODEL_NAME) is required. See https://midscenejs.com/model-strategy.html');
49
+ if (!defaultConfig) throw new Error('Model configuration is incomplete: model name (MIDSCENE_MODEL_NAME) is required. See https://midscenejs.com/model-api-setup');
50
50
  if ('jev' === defaultConfig.modelFamily) throw new Error('Jev cannot be the default model. Configure a general-purpose MIDSCENE_MODEL_FAMILY and use Jev in Locate, Planning, or Insight.');
51
51
  const insightConfig = (0, external_parse_model_config_js_namespaceObject.decideModelConfigFromIntentConfig)('insight', configMap);
52
52
  const planningConfig = (0, external_parse_model_config_js_namespaceObject.decideModelConfigFromIntentConfig)('planning', configMap);
@@ -105,7 +105,7 @@ class ModelConfigManager {
105
105
  }
106
106
  throwErrorIfNonVLModel() {
107
107
  const modelConfig = this.getModelConfig('locate');
108
- if (!modelConfig.modelFamily) throw new Error(`${'locate' === modelConfig.slot ? 'MIDSCENE_LOCATE_MODEL_FAMILY' : 'MIDSCENE_MODEL_FAMILY'} is not set to a multimodal model with UI localization, so element localization cannot be achieved. Check your model configuration. See https://midscenejs.com/model-strategy.html`);
108
+ if (!modelConfig.modelFamily) throw new Error(`${'locate' === modelConfig.slot ? 'MIDSCENE_LOCATE_MODEL_FAMILY' : 'MIDSCENE_MODEL_FAMILY'} is not set to a multimodal model with UI localization, so element localization cannot be achieved. Check your model configuration. See https://midscenejs.com/model-api-setup`);
109
109
  }
110
110
  constructor(modelConfig, createOpenAIClientFn){
111
111
  _define_property(this, "modelConfigMap", void 0);
@@ -36,8 +36,8 @@ const external_logger_js_namespaceObject = require("../logger.js");
36
36
  const external_utils_js_namespaceObject = require("../utils.js");
37
37
  const external_helper_js_namespaceObject = require("./helper.js");
38
38
  const external_init_debug_js_namespaceObject = require("./init-debug.js");
39
- const MODEL_CONFIG_DOC_URL = 'https://midscenejs.com/model-common-config.html';
40
- const getCurrentVersion = ()=>"1.16.1";
39
+ const MODEL_CONFIG_DOC_URL = 'https://midscenejs.com/model-api-setup.html';
40
+ const getCurrentVersion = ()=>"1.16.2";
41
41
  const getInvalidModelFamilyMessage = (modelFamily)=>`Invalid MIDSCENE_MODEL_FAMILY value: ${modelFamily}. Current version v${getCurrentVersion()} accepts the following model families: ${external_types_js_namespaceObject.MODEL_FAMILY_VALUES.join(', ')}. You can also visit ${MODEL_CONFIG_DOC_URL} for the latest configuration information.`;
42
42
  const KEYS_MAP = {
43
43
  locate: external_constants_js_namespaceObject.LOCATE_MODEL_CONFIG_KEYS,
@@ -202,8 +202,8 @@ const decideModelConfigFromIntentConfig = (intent, configMap)=>{
202
202
  debugLog('decideModelConfig result by agent.modelConfig() with intent', intent, (0, external_helper_js_namespaceObject.maskConfig)({
203
203
  ...finalResult
204
204
  }));
205
- (0, external_utils_js_namespaceObject.assert)(finalResult.openaiBaseURL, `failed to get base URL of model (intent=${intent}). See https://midscenejs.com/model-strategy`);
206
- if (!finalResult.modelName) console.warn(`modelName is not set for intent ${intent}, this may cause unexpected behavior. See https://midscenejs.com/model-strategy`);
205
+ (0, external_utils_js_namespaceObject.assert)(finalResult.openaiBaseURL, `failed to get base URL of model (intent=${intent}). See https://midscenejs.com/model-api-setup`);
206
+ if (!finalResult.modelName) console.warn(`modelName is not set for intent ${intent}, this may cause unexpected behavior. See https://midscenejs.com/model-api-setup`);
207
207
  return finalResult;
208
208
  };
209
209
  exports.decideModelConfigFromIntentConfig = __webpack_exports__.decideModelConfigFromIntentConfig;
@@ -33,7 +33,10 @@ var __webpack_require__ = {};
33
33
  var __webpack_exports__ = {};
34
34
  __webpack_require__.r(__webpack_exports__);
35
35
  __webpack_require__.d(__webpack_exports__, {
36
+ logReport: ()=>logReport,
36
37
  enableDebug: ()=>enableDebug,
38
+ runWithConsoleLogHandler: ()=>runWithConsoleLogHandler,
39
+ runWithConsoleLogScope: ()=>runWithConsoleLogScope,
37
40
  setLogDirectoryResolver: ()=>setLogDirectoryResolver,
38
41
  getDebug: ()=>getDebug
39
42
  });
@@ -45,9 +48,35 @@ const external_node_util_namespaceObject = require("node:util");
45
48
  var external_node_util_default = /*#__PURE__*/ __webpack_require__.n(external_node_util_namespaceObject);
46
49
  const external_debug_namespaceObject = require("debug");
47
50
  var external_debug_default = /*#__PURE__*/ __webpack_require__.n(external_debug_namespaceObject);
51
+ const external_console_context_namespaceObject = require("#console-context");
48
52
  const external_common_js_namespaceObject = require("./common.js");
49
53
  const external_utils_js_namespaceObject = require("./utils.js");
50
54
  const topicPrefix = 'midscene';
55
+ const consoleContextKey = Symbol.for('@midscene/shared/console-context');
56
+ const consoleHost = globalThis;
57
+ consoleHost[consoleContextKey] ??= (0, external_console_context_namespaceObject.createConsoleContext)();
58
+ const consoleContext = consoleHost[consoleContextKey];
59
+ const runWithConsoleLogHandler = (handler, run)=>consoleContext.run(handler, run);
60
+ const runWithConsoleLogScope = (scope, run)=>{
61
+ const handler = consoleContext.getStore();
62
+ if (!handler) return run();
63
+ return consoleContext.run((entry)=>handler({
64
+ ...entry,
65
+ scope: {
66
+ ...scope,
67
+ ...entry.scope
68
+ }
69
+ }), run);
70
+ };
71
+ function logReport(message) {
72
+ const handler = consoleContext.getStore();
73
+ if (handler) handler({
74
+ type: 'report',
75
+ topic: 'midscene:report',
76
+ message
77
+ });
78
+ else console.log(message);
79
+ }
51
80
  const logStreams = new Map();
52
81
  const logStreamPaths = new Map();
53
82
  let logDirectoryResolver;
@@ -121,17 +150,38 @@ function writeLogToFile(topic, message) {
121
150
  backpressuredLogStreams.delete(topicFileName);
122
151
  }
123
152
  }
153
+ function printConsoleWarning(topic, args, warning) {
154
+ const handler = consoleContext.getStore();
155
+ if (handler) return void handler({
156
+ type: 'warning',
157
+ topic,
158
+ message: external_node_util_default().format(...args),
159
+ args,
160
+ ...warning ? {
161
+ warning
162
+ } : {}
163
+ });
164
+ try {
165
+ console.warn('[Midscene]', ...args);
166
+ } catch {}
167
+ }
124
168
  function getDebug(topic, options) {
125
169
  const fullTopic = `${topicPrefix}:${topic}`;
126
170
  const withConsole = options?.console ?? false;
127
171
  const cacheKey = withConsole ? `${fullTopic}:withConsole` : fullTopic;
172
+ if (withConsole && options?.warning) {
173
+ const baseFn = getDebug(topic);
174
+ const warning = options.warning;
175
+ return (...args)=>{
176
+ baseFn(...args);
177
+ printConsoleWarning(fullTopic, args, warning);
178
+ };
179
+ }
128
180
  if (!debugInstances.has(cacheKey)) if (withConsole) {
129
181
  const baseFn = getDebug(topic);
130
182
  const wrapper = (...args)=>{
131
183
  baseFn(...args);
132
- try {
133
- console.warn('[Midscene]', ...args);
134
- } catch {}
184
+ printConsoleWarning(fullTopic, args);
135
185
  };
136
186
  debugInstances.set(cacheKey, wrapper);
137
187
  } else {
@@ -153,10 +203,16 @@ function enableDebug(topic) {
153
203
  }
154
204
  exports.enableDebug = __webpack_exports__.enableDebug;
155
205
  exports.getDebug = __webpack_exports__.getDebug;
206
+ exports.logReport = __webpack_exports__.logReport;
207
+ exports.runWithConsoleLogHandler = __webpack_exports__.runWithConsoleLogHandler;
208
+ exports.runWithConsoleLogScope = __webpack_exports__.runWithConsoleLogScope;
156
209
  exports.setLogDirectoryResolver = __webpack_exports__.setLogDirectoryResolver;
157
210
  for(var __rspack_i in __webpack_exports__)if (-1 === [
158
211
  "enableDebug",
159
212
  "getDebug",
213
+ "logReport",
214
+ "runWithConsoleLogHandler",
215
+ "runWithConsoleLogScope",
160
216
  "setLogDirectoryResolver"
161
217
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
162
218
  Object.defineProperty(exports, '__esModule', {
@@ -0,0 +1,3 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ export declare const createConsoleContext: <T>() => AsyncLocalStorage<T>;
3
+ //# sourceMappingURL=console-context.node.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console-context.node.d.ts","sourceRoot":"","sources":["../../src/console-context.node.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,eAAO,MAAM,oBAAoB,GAAI,CAAC,2BAAiC,CAAC"}
@@ -0,0 +1,5 @@
1
+ export declare const createConsoleContext: <T>() => {
2
+ getStore: () => T | undefined;
3
+ run: <R>(_store: T, callback: () => R) => R;
4
+ };
5
+ //# sourceMappingURL=console-context.stub.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"console-context.stub.d.ts","sourceRoot":"","sources":["../../src/console-context.stub.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,oBAAoB,GAAI,CAAC;oBACtB,CAAC,GAAG,SAAS;UACrB,CAAC,UAAU,CAAC,YAAY,MAAM,CAAC,KAAG,CAAC;CACzC,CAAC"}
@@ -1,3 +1,39 @@
1
+ export interface ConsoleLogScope {
2
+ projectName: string;
3
+ sourcePath?: string;
4
+ caseId?: string;
5
+ caseName?: string;
6
+ runId?: string;
7
+ phase?: string;
8
+ stepIndex?: number;
9
+ node?: string;
10
+ }
11
+ export type ConsoleWarningDetails = {
12
+ kind: 'model-request-detail';
13
+ modelName: string;
14
+ error: unknown;
15
+ } | {
16
+ kind: 'model-request-retry';
17
+ modelName: string;
18
+ error: unknown;
19
+ callId: string;
20
+ attempt: number;
21
+ maxAttempts: number;
22
+ delayMs: number;
23
+ };
24
+ export interface ConsoleLogEntry {
25
+ type: 'warning' | 'report';
26
+ topic: string;
27
+ message: string;
28
+ scope?: ConsoleLogScope;
29
+ args?: readonly unknown[];
30
+ warning?: ConsoleWarningDetails;
31
+ }
32
+ /** Route SDK console messages within one run, without changing other runs or file logs. */
33
+ export declare const runWithConsoleLogHandler: <T>(handler: (entry: ConsoleLogEntry) => void, run: () => T) => T;
34
+ /** Capture the actual async execution scope, including concurrent and late logs. */
35
+ export declare const runWithConsoleLogScope: <T>(scope: ConsoleLogScope, run: () => T) => T;
36
+ export declare function logReport(message: string): void;
1
37
  /**
2
38
  * Overrides the directory used by file logs in the current process.
3
39
  *
@@ -9,6 +45,7 @@ export declare function setLogDirectoryResolver(resolver: (() => string) | undef
9
45
  export type DebugFunction = (...args: unknown[]) => void;
10
46
  export declare function getDebug(topic: string, options?: {
11
47
  console?: boolean;
48
+ warning?: ConsoleWarningDetails;
12
49
  }): DebugFunction;
13
50
  export declare function enableDebug(topic: string): void;
14
51
  //# sourceMappingURL=logger.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAqBA;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACrC,QAAQ,EAAE,CAAC,MAAM,MAAM,CAAC,GAAG,SAAS,GACnC,IAAI,CAWN;AA+ED,MAAM,MAAM,aAAa,GAAG,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;AAEzD,wBAAgB,QAAQ,CACtB,KAAK,EAAE,MAAM,EACb,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,GAC9B,aAAa,CAmCf;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAM/C"}
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/logger.ts"],"names":[],"mappings":"AAUA,MAAM,WAAW,eAAe;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,MAAM,qBAAqB,GAC7B;IAAE,IAAI,EAAE,sBAAsB,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,GACnE;IACE,IAAI,EAAE,qBAAqB,CAAC;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,OAAO,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEN,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,SAAS,GAAG,QAAQ,CAAC;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,eAAe,CAAC;IACxB,IAAI,CAAC,EAAE,SAAS,OAAO,EAAE,CAAC;IAC1B,OAAO,CAAC,EAAE,qBAAqB,CAAC;CACjC;AAaD,2FAA2F;AAC3F,eAAO,MAAM,wBAAwB,GAAI,CAAC,EACxC,SAAS,CAAC,KAAK,EAAE,eAAe,KAAK,IAAI,EACzC,KAAK,MAAM,CAAC,KACX,CAAqC,CAAC;AAEzC,oFAAoF;AACpF,eAAO,MAAM,sBAAsB,GAAI,CAAC,EACtC,OAAO,eAAe,EACtB,KAAK,MAAM,CAAC,KACX,CAOF,CAAC;AAEF,wBAAgB,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAI/C;AAcD;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACrC,QAAQ,EAAE,CAAC,MAAM,MAAM,CAAC,GAAG,SAAS,GACnC,IAAI,CAWN;AA+ED,MAAM,MAAM,aAAa,GAAG,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,CAAC;AA0BzD,wBAAgB,QAAQ,CACtB,KAAK,EAAE,MAAM,EACb,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,qBAAqB,CAAA;CAAE,GAC/D,aAAa,CAwCf;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAM/C"}
package/package.json CHANGED
@@ -1,11 +1,24 @@
1
1
  {
2
2
  "name": "@midscene/shared",
3
- "version": "1.16.1",
3
+ "version": "1.16.2",
4
4
  "repository": "https://github.com/web-infra-dev/midscene",
5
5
  "homepage": "https://midscenejs.com/",
6
6
  "types": "./dist/types/index.d.ts",
7
7
  "main": "./dist/lib/index.js",
8
8
  "module": "./dist/es/index.mjs",
9
+ "imports": {
10
+ "#console-context": {
11
+ "types": "./src/console-context.d.ts",
12
+ "node": {
13
+ "import": "./dist/es/console-context.node.mjs",
14
+ "require": "./dist/lib/console-context.node.js"
15
+ },
16
+ "default": {
17
+ "import": "./dist/es/console-context.stub.mjs",
18
+ "require": "./dist/lib/console-context.stub.js"
19
+ }
20
+ }
21
+ },
9
22
  "exports": {
10
23
  ".": {
11
24
  "types": "./dist/types/index.d.ts",
@@ -0,0 +1,4 @@
1
+ export function createConsoleContext<T>(): {
2
+ getStore(): T | undefined;
3
+ run<R>(store: T, callback: () => R): R;
4
+ };
@@ -0,0 +1,3 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+
3
+ export const createConsoleContext = <T>() => new AsyncLocalStorage<T>();
@@ -0,0 +1,5 @@
1
+ // Browser consumers have no CLI output scope and retain normal console output.
2
+ export const createConsoleContext = <T>() => ({
3
+ getStore: (): T | undefined => undefined,
4
+ run: <R>(_store: T, callback: () => R): R => callback(),
5
+ });
@@ -49,7 +49,7 @@ export class ModelConfigManager {
49
49
  );
50
50
  if (!defaultConfig) {
51
51
  throw new Error(
52
- 'Model configuration is incomplete: model name (MIDSCENE_MODEL_NAME) is required. See https://midscenejs.com/model-strategy.html',
52
+ 'Model configuration is incomplete: model name (MIDSCENE_MODEL_NAME) is required. See https://midscenejs.com/model-api-setup',
53
53
  );
54
54
  }
55
55
 
@@ -162,7 +162,7 @@ export class ModelConfigManager {
162
162
 
163
163
  if (!modelConfig.modelFamily) {
164
164
  throw new Error(
165
- `${modelConfig.slot === 'locate' ? 'MIDSCENE_LOCATE_MODEL_FAMILY' : 'MIDSCENE_MODEL_FAMILY'} is not set to a multimodal model with UI localization, so element localization cannot be achieved. Check your model configuration. See https://midscenejs.com/model-strategy.html`,
165
+ `${modelConfig.slot === 'locate' ? 'MIDSCENE_LOCATE_MODEL_FAMILY' : 'MIDSCENE_MODEL_FAMILY'} is not set to a multimodal model with UI localization, so element localization cannot be achieved. Check your model configuration. See https://midscenejs.com/model-api-setup`,
166
166
  );
167
167
  }
168
168
  }
@@ -32,7 +32,7 @@ import { initDebugConfig } from './init-debug';
32
32
 
33
33
  declare const __VERSION__: string | undefined;
34
34
 
35
- const MODEL_CONFIG_DOC_URL = 'https://midscenejs.com/model-common-config.html';
35
+ const MODEL_CONFIG_DOC_URL = 'https://midscenejs.com/model-api-setup.html';
36
36
 
37
37
  const getCurrentVersion = (): string => {
38
38
  if (typeof __VERSION__ !== 'undefined' && __VERSION__) {
@@ -369,12 +369,12 @@ export const decideModelConfigFromIntentConfig = (
369
369
 
370
370
  assert(
371
371
  finalResult.openaiBaseURL,
372
- `failed to get base URL of model (intent=${intent}). See https://midscenejs.com/model-strategy`,
372
+ `failed to get base URL of model (intent=${intent}). See https://midscenejs.com/model-api-setup`,
373
373
  );
374
374
 
375
375
  if (!finalResult.modelName) {
376
376
  console.warn(
377
- `modelName is not set for intent ${intent}, this may cause unexpected behavior. See https://midscenejs.com/model-strategy`,
377
+ `modelName is not set for intent ${intent}, this may cause unexpected behavior. See https://midscenejs.com/model-api-setup`,
378
378
  );
379
379
  }
380
380
 
package/src/logger.ts CHANGED
@@ -2,10 +2,79 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import util from 'node:util';
4
4
  import debug from 'debug';
5
+ import { createConsoleContext } from '#console-context';
5
6
  import { getMidsceneRunSubDir } from './common';
6
7
  import { ifInNode } from './utils';
7
8
 
8
9
  const topicPrefix = 'midscene';
10
+
11
+ export interface ConsoleLogScope {
12
+ projectName: string;
13
+ sourcePath?: string;
14
+ caseId?: string;
15
+ caseName?: string;
16
+ runId?: string;
17
+ phase?: string;
18
+ stepIndex?: number;
19
+ node?: string;
20
+ }
21
+
22
+ export type ConsoleWarningDetails =
23
+ | { kind: 'model-request-detail'; modelName: string; error: unknown }
24
+ | {
25
+ kind: 'model-request-retry';
26
+ modelName: string;
27
+ error: unknown;
28
+ callId: string;
29
+ attempt: number;
30
+ maxAttempts: number;
31
+ delayMs: number;
32
+ };
33
+
34
+ export interface ConsoleLogEntry {
35
+ type: 'warning' | 'report';
36
+ topic: string;
37
+ message: string;
38
+ scope?: ConsoleLogScope;
39
+ args?: readonly unknown[];
40
+ warning?: ConsoleWarningDetails;
41
+ }
42
+
43
+ type ConsoleLogHandler = (entry: ConsoleLogEntry) => void;
44
+ const consoleContextKey = Symbol.for('@midscene/shared/console-context');
45
+ const consoleHost = globalThis as typeof globalThis & {
46
+ [consoleContextKey]?: ReturnType<
47
+ typeof createConsoleContext<ConsoleLogHandler>
48
+ >;
49
+ };
50
+ // Configs can load ESM SDKs while the CLI loads CJS; both must share the scope.
51
+ consoleHost[consoleContextKey] ??= createConsoleContext<ConsoleLogHandler>();
52
+ const consoleContext = consoleHost[consoleContextKey];
53
+
54
+ /** Route SDK console messages within one run, without changing other runs or file logs. */
55
+ export const runWithConsoleLogHandler = <T>(
56
+ handler: (entry: ConsoleLogEntry) => void,
57
+ run: () => T,
58
+ ): T => consoleContext.run(handler, run);
59
+
60
+ /** Capture the actual async execution scope, including concurrent and late logs. */
61
+ export const runWithConsoleLogScope = <T>(
62
+ scope: ConsoleLogScope,
63
+ run: () => T,
64
+ ): T => {
65
+ const handler = consoleContext.getStore();
66
+ if (!handler) return run();
67
+ return consoleContext.run(
68
+ (entry) => handler({ ...entry, scope: { ...scope, ...entry.scope } }),
69
+ run,
70
+ );
71
+ };
72
+
73
+ export function logReport(message: string): void {
74
+ const handler = consoleContext.getStore();
75
+ if (handler) handler({ type: 'report', topic: 'midscene:report', message });
76
+ else console.log(message);
77
+ }
9
78
  // Map to store file streams
10
79
  const logStreams = new Map<string, fs.WriteStream>();
11
80
  const logStreamPaths = new Map<string, string>();
@@ -120,25 +189,54 @@ function writeLogToFile(topic: string, message: string): void {
120
189
 
121
190
  export type DebugFunction = (...args: unknown[]) => void;
122
191
 
192
+ function printConsoleWarning(
193
+ topic: string,
194
+ args: unknown[],
195
+ warning?: ConsoleWarningDetails,
196
+ ): void {
197
+ const handler = consoleContext.getStore();
198
+ if (handler) {
199
+ handler({
200
+ type: 'warning',
201
+ topic,
202
+ message: util.format(...args),
203
+ args,
204
+ ...(warning ? { warning } : {}),
205
+ });
206
+ return;
207
+ }
208
+ try {
209
+ console.warn('[Midscene]', ...args);
210
+ } catch {
211
+ // Packaged Electron apps can have closed stdio streams. Debug logging
212
+ // must not crash callers just because console output cannot write.
213
+ }
214
+ }
215
+
123
216
  export function getDebug(
124
217
  topic: string,
125
- options?: { console?: boolean },
218
+ options?: { console?: boolean; warning?: ConsoleWarningDetails },
126
219
  ): DebugFunction {
127
220
  const fullTopic = `${topicPrefix}:${topic}`;
128
221
  const withConsole = options?.console ?? false;
129
222
  const cacheKey = withConsole ? `${fullTopic}:withConsole` : fullTopic;
130
223
 
224
+ // Warning metadata belongs to this call, never to a cached topic logger.
225
+ if (withConsole && options?.warning) {
226
+ const baseFn = getDebug(topic);
227
+ const warning = options.warning;
228
+ return (...args) => {
229
+ baseFn(...args);
230
+ printConsoleWarning(fullTopic, args, warning);
231
+ };
232
+ }
233
+
131
234
  if (!debugInstances.has(cacheKey)) {
132
235
  if (withConsole) {
133
236
  const baseFn = getDebug(topic);
134
237
  const wrapper = (...args: unknown[]): void => {
135
238
  baseFn(...args);
136
- try {
137
- console.warn('[Midscene]', ...args);
138
- } catch {
139
- // Packaged Electron apps can have closed stdio streams. Debug logging
140
- // must not crash callers just because console output cannot write.
141
- }
239
+ printConsoleWarning(fullTopic, args);
142
240
  };
143
241
  debugInstances.set(cacheKey, wrapper);
144
242
  } else {