@aiscene/shared 8.0.2 → 8.0.4

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.
Files changed (177) hide show
  1. package/dist/es/agent-tools/agent-behavior-init-args.mjs +44 -0
  2. package/dist/es/agent-tools/base-tools.mjs +163 -0
  3. package/dist/es/agent-tools/chrome-path.mjs +50 -0
  4. package/dist/es/agent-tools/cli-report-session.mjs +78 -0
  5. package/dist/es/agent-tools/error-formatter.mjs +106 -0
  6. package/dist/es/agent-tools/index.mjs +9 -0
  7. package/dist/es/agent-tools/init-arg-utils.mjs +38 -0
  8. package/dist/es/agent-tools/observation-artifact.mjs +5 -0
  9. package/dist/es/agent-tools/observation-record.mjs +248 -0
  10. package/dist/es/agent-tools/tool-defaults.mjs +54 -0
  11. package/dist/es/agent-tools/tool-generator.mjs +529 -0
  12. package/dist/es/agent-tools/types.mjs +3 -0
  13. package/dist/es/agent-tools/user-prompt.mjs +66 -0
  14. package/dist/es/cli/cli-args.mjs +95 -0
  15. package/dist/es/cli/cli-error.mjs +24 -0
  16. package/dist/es/cli/cli-runner.mjs +10 -40
  17. package/dist/es/cli/index.mjs +4 -2
  18. package/dist/es/cli/interrupt.mjs +116 -0
  19. package/dist/es/cli/record-command.mjs +130 -0
  20. package/dist/es/cli/screenshot-file.mjs +24 -0
  21. package/dist/es/cli/verbose-ai-act.mjs +230 -0
  22. package/dist/es/cli/verbose-screenshot.mjs +134 -0
  23. package/dist/es/cli/verbose.mjs +404 -0
  24. package/dist/es/constants/example-code.mjs +2 -2
  25. package/dist/es/constants/index.mjs +6 -1
  26. package/dist/es/env/model-config-manager.mjs +3 -0
  27. package/dist/es/env/parse-model-config.mjs +6 -1
  28. package/dist/es/env/types.mjs +4 -1
  29. package/dist/es/env/utils.mjs +1 -9
  30. package/dist/es/extractor/index.mjs +2 -2
  31. package/dist/es/img/index.mjs +2 -2
  32. package/dist/es/img/info.mjs +58 -17
  33. package/dist/es/img/photon-loader.mjs +4 -0
  34. package/dist/es/key-alias-utils.mjs +19 -0
  35. package/dist/es/mcp/base-server.mjs +10 -9
  36. package/dist/es/mcp/base-tools.mjs +72 -4
  37. package/dist/es/mcp/cli-report-session.mjs +78 -0
  38. package/dist/es/mcp/error-formatter.mjs +19 -0
  39. package/dist/es/mcp/index.mjs +2 -0
  40. package/dist/es/mcp/init-arg-utils.mjs +38 -0
  41. package/dist/es/mcp/inject-report-html-plugin.mjs +1 -1
  42. package/dist/es/mcp/tool-generator.mjs +65 -17
  43. package/dist/es/node/fs.mjs +1 -1
  44. package/dist/es/recorder.mjs +249 -0
  45. package/dist/lib/agent-tools/agent-behavior-init-args.js +87 -0
  46. package/dist/lib/agent-tools/base-tools.js +197 -0
  47. package/dist/lib/agent-tools/chrome-path.js +87 -0
  48. package/dist/lib/agent-tools/cli-report-session.js +121 -0
  49. package/dist/lib/agent-tools/error-formatter.js +149 -0
  50. package/dist/lib/agent-tools/index.js +114 -0
  51. package/dist/lib/agent-tools/init-arg-utils.js +78 -0
  52. package/dist/lib/agent-tools/observation-artifact.js +42 -0
  53. package/dist/lib/agent-tools/observation-record.js +297 -0
  54. package/dist/lib/agent-tools/tool-defaults.js +97 -0
  55. package/dist/lib/agent-tools/tool-generator.js +569 -0
  56. package/dist/lib/agent-tools/types.js +40 -0
  57. package/dist/lib/agent-tools/user-prompt.js +103 -0
  58. package/dist/lib/cli/cli-args.js +138 -0
  59. package/dist/lib/cli/cli-error.js +61 -0
  60. package/dist/lib/cli/cli-runner.js +19 -46
  61. package/dist/lib/cli/index.js +8 -3
  62. package/dist/lib/cli/interrupt.js +156 -0
  63. package/dist/lib/cli/record-command.js +164 -0
  64. package/dist/lib/cli/screenshot-file.js +58 -0
  65. package/dist/lib/cli/verbose-ai-act.js +273 -0
  66. package/dist/lib/cli/verbose-screenshot.js +177 -0
  67. package/dist/lib/cli/verbose.js +465 -0
  68. package/dist/lib/constants/example-code.js +2 -2
  69. package/dist/lib/constants/index.js +23 -3
  70. package/dist/lib/env/model-config-manager.js +3 -0
  71. package/dist/lib/env/parse-model-config.js +6 -1
  72. package/dist/lib/env/types.js +9 -0
  73. package/dist/lib/env/utils.js +0 -11
  74. package/dist/lib/extractor/index.js +3 -0
  75. package/dist/lib/img/index.js +3 -0
  76. package/dist/lib/img/info.js +65 -18
  77. package/dist/lib/img/photon-loader.js +38 -0
  78. package/dist/lib/key-alias-utils.js +62 -0
  79. package/dist/lib/mcp/base-server.js +11 -10
  80. package/dist/lib/mcp/base-tools.js +74 -6
  81. package/dist/lib/mcp/cli-report-session.js +121 -0
  82. package/dist/lib/mcp/error-formatter.js +53 -0
  83. package/dist/lib/mcp/index.js +24 -10
  84. package/dist/lib/mcp/init-arg-utils.js +78 -0
  85. package/dist/lib/mcp/inject-report-html-plugin.js +1 -1
  86. package/dist/lib/mcp/tool-generator.js +74 -26
  87. package/dist/lib/node/fs.js +1 -1
  88. package/dist/lib/recorder.js +307 -0
  89. package/dist/types/agent-tools/agent-behavior-init-args.d.ts +17 -0
  90. package/dist/types/agent-tools/base-tools.d.ts +158 -0
  91. package/dist/types/agent-tools/chrome-path.d.ts +2 -0
  92. package/dist/types/agent-tools/cli-report-session.d.ts +12 -0
  93. package/dist/types/agent-tools/error-formatter.d.ts +30 -0
  94. package/dist/types/agent-tools/index.d.ts +9 -0
  95. package/dist/types/agent-tools/init-arg-utils.d.ts +13 -0
  96. package/dist/types/agent-tools/observation-artifact.d.ts +10 -0
  97. package/dist/types/agent-tools/observation-record.d.ts +38 -0
  98. package/dist/types/agent-tools/tool-defaults.d.ts +63 -0
  99. package/dist/types/agent-tools/tool-generator.d.ts +13 -0
  100. package/dist/types/agent-tools/types.d.ts +213 -0
  101. package/dist/types/agent-tools/user-prompt.d.ts +13 -0
  102. package/dist/types/cli/cli-args.d.ts +8 -0
  103. package/dist/types/cli/cli-error.d.ts +5 -0
  104. package/dist/types/cli/cli-runner.d.ts +4 -7
  105. package/dist/types/cli/index.d.ts +3 -1
  106. package/dist/types/cli/interrupt.d.ts +49 -0
  107. package/dist/types/cli/record-command.d.ts +3 -0
  108. package/dist/types/cli/screenshot-file.d.ts +10 -0
  109. package/dist/types/cli/verbose-ai-act.d.ts +44 -0
  110. package/dist/types/cli/verbose-screenshot.d.ts +10 -0
  111. package/dist/types/cli/verbose.d.ts +40 -0
  112. package/dist/types/constants/example-code.d.ts +1 -1
  113. package/dist/types/constants/index.d.ts +5 -0
  114. package/dist/types/env/types.d.ts +14 -5
  115. package/dist/types/env/utils.d.ts +0 -31
  116. package/dist/types/extractor/index.d.ts +1 -1
  117. package/dist/types/img/index.d.ts +1 -1
  118. package/dist/types/img/info.d.ts +7 -0
  119. package/dist/types/img/photon-loader.d.ts +2 -0
  120. package/dist/types/key-alias-utils.d.ts +9 -0
  121. package/dist/types/mcp/base-tools.d.ts +74 -5
  122. package/dist/types/mcp/cli-report-session.d.ts +12 -0
  123. package/dist/types/mcp/error-formatter.d.ts +12 -0
  124. package/dist/types/mcp/index.d.ts +2 -0
  125. package/dist/types/mcp/init-arg-utils.d.ts +13 -0
  126. package/dist/types/mcp/inject-report-html-plugin.d.ts +2 -2
  127. package/dist/types/mcp/launcher-helper.d.ts +3 -3
  128. package/dist/types/mcp/tool-generator.d.ts +3 -3
  129. package/dist/types/mcp/types.d.ts +10 -0
  130. package/dist/types/recorder.d.ts +113 -0
  131. package/package.json +1 -1
  132. package/src/agent-tools/agent-behavior-init-args.ts +109 -0
  133. package/src/agent-tools/base-tools.ts +399 -0
  134. package/src/agent-tools/chrome-path.ts +74 -0
  135. package/src/agent-tools/cli-report-session.ts +130 -0
  136. package/src/agent-tools/error-formatter.ts +177 -0
  137. package/src/agent-tools/index.ts +9 -0
  138. package/src/agent-tools/init-arg-utils.ts +105 -0
  139. package/src/agent-tools/observation-artifact.ts +29 -0
  140. package/src/agent-tools/observation-record.ts +331 -0
  141. package/src/agent-tools/tool-defaults.ts +119 -0
  142. package/src/agent-tools/tool-generator.ts +866 -0
  143. package/src/agent-tools/types.ts +250 -0
  144. package/src/agent-tools/user-prompt.ts +102 -0
  145. package/src/cli/cli-args.ts +173 -0
  146. package/src/cli/cli-error.ts +24 -0
  147. package/src/cli/cli-runner.ts +37 -56
  148. package/src/cli/index.ts +3 -7
  149. package/src/cli/interrupt.ts +207 -0
  150. package/src/cli/record-command.ts +177 -0
  151. package/src/cli/screenshot-file.ts +61 -0
  152. package/src/cli/verbose-ai-act.ts +387 -0
  153. package/src/cli/verbose-screenshot.ts +269 -0
  154. package/src/cli/verbose.ts +753 -0
  155. package/src/constants/example-code.ts +2 -2
  156. package/src/constants/index.ts +10 -0
  157. package/src/env/model-config-manager.ts +3 -0
  158. package/src/env/parse-model-config.ts +19 -1
  159. package/src/env/types.ts +13 -2
  160. package/src/env/utils.ts +0 -50
  161. package/src/extractor/index.ts +1 -1
  162. package/src/img/index.ts +14 -0
  163. package/src/img/info.ts +97 -45
  164. package/src/img/photon-loader.ts +5 -0
  165. package/src/img/transform.ts +261 -2
  166. package/src/key-alias-utils.ts +23 -0
  167. package/src/mcp/base-server.ts +10 -12
  168. package/src/mcp/base-tools.ts +218 -11
  169. package/src/mcp/cli-report-session.ts +130 -0
  170. package/src/mcp/error-formatter.ts +52 -0
  171. package/src/mcp/index.ts +2 -0
  172. package/src/mcp/init-arg-utils.ts +105 -0
  173. package/src/mcp/inject-report-html-plugin.ts +3 -3
  174. package/src/mcp/launcher-helper.ts +3 -3
  175. package/src/mcp/tool-generator.ts +98 -20
  176. package/src/mcp/types.ts +18 -1
  177. package/src/recorder.ts +625 -0
@@ -1,6 +1,8 @@
1
+ import { Buffer } from 'node:buffer';
1
2
  import type { Size } from '../types';
2
3
  export interface ImageInfo extends Size {
3
4
  }
5
+ export declare function encodedImageInfoOfBuffer(imageBuffer: Buffer): ImageInfo;
4
6
  /**
5
7
  * Retrieves the dimensions of an image from a base64-encoded string
6
8
  *
@@ -27,3 +29,8 @@ export declare function isValidJPEGImageBuffer(buffer: Buffer): boolean;
27
29
  * @returns true if the Buffer is a valid PNG or JPEG image, otherwise false
28
30
  */
29
31
  export declare function isValidImageBuffer(buffer: Buffer): boolean;
32
+ export interface ValidateScreenshotBufferOptions {
33
+ label: string;
34
+ minBufferSize?: number;
35
+ }
36
+ export declare function validateScreenshotBuffer(screenshotBuffer: Buffer | undefined, { label, minBufferSize }: ValidateScreenshotBufferOptions): asserts screenshotBuffer is Buffer;
@@ -0,0 +1,2 @@
1
+ export type PhotonModule = typeof import('@silvia-odwyer/photon');
2
+ export declare function loadPhotonModule(): Promise<PhotonModule>;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Internal-only helpers for CLI/MCP argument key aliasing.
3
+ * Not re-exported from the package entry point — keep consumers within
4
+ * `cli/` and `mcp/`.
5
+ */
6
+ export declare function kebabToCamel(str: string): string;
7
+ export declare function camelToKebab(str: string): string;
8
+ export declare function getKeyAliases(key: string): string[];
9
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
@@ -1,13 +1,53 @@
1
1
  import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- import type { BaseAgent, BaseDevice, IMidsceneTools, ToolDefinition } from './types';
2
+ import type { z } from 'zod';
3
+ import { type CliReportSession } from './cli-report-session';
4
+ import type { BaseAgent, BaseDevice, IMidsceneTools, ToolCliMetadata, ToolDefinition, ToolSchema } from './types';
3
5
  /**
4
- * Base class for platform-specific MCP tools
5
- * Generic type TAgent allows subclasses to use their specific agent types
6
+ * Declarative description of a platform's agent init args.
7
+ * Collapses the `extractAgentInitParam` / `sanitizeToolArgs` /
8
+ * `getAgentInitArgSchema` trio into a single data declaration.
6
9
  */
7
- export declare abstract class BaseMidsceneTools<TAgent extends BaseAgent = BaseAgent> implements IMidsceneTools {
10
+ export interface InitArgSpec<TInitParam> {
11
+ /** Arg namespace, e.g. `android`, `ios`. */
12
+ namespace: string;
13
+ /** Zod shape describing the init args. Field names drive the MCP schema. */
14
+ shape: Record<string, z.ZodTypeAny>;
15
+ /**
16
+ * Optional CLI presentation hints. These affect `--help` output for
17
+ * single-platform CLIs but do not alter MCP/YAML protocol keys.
18
+ */
19
+ cli?: {
20
+ /** Prefer bare `--device-id`-style options in platform CLI help output. */
21
+ preferBareKeys?: boolean;
22
+ /** Override the displayed option name for specific init arg fields. */
23
+ preferredNames?: Record<string, string>;
24
+ };
25
+ /**
26
+ * Adapt extracted namespaced args into the concrete `TInitParam` passed to
27
+ * `ensureAgent`. Defaults to returning the raw extracted record.
28
+ */
29
+ adapt?: (extracted: Record<string, unknown> | undefined) => TInitParam | undefined;
30
+ }
31
+ /**
32
+ * Base class for platform-specific MCP tools.
33
+ * @typeParam TAgent - Platform-specific agent type.
34
+ * @typeParam TInitParam - Platform-specific init parameter consumed by
35
+ * `ensureAgent`. Defaults to `undefined` for platforms that take no args.
36
+ */
37
+ export declare abstract class BaseMidsceneTools<TAgent extends BaseAgent = BaseAgent, TInitParam = unknown> implements IMidsceneTools {
8
38
  protected mcpServer?: McpServer;
9
39
  protected agent?: TAgent;
10
40
  protected toolDefinitions: ToolDefinition[];
41
+ /**
42
+ * Declarative init-arg spec. Subclasses that accept CLI/MCP init args should
43
+ * set this once and get `extractAgentInitParam` / `sanitizeToolArgs` /
44
+ * `getAgentInitArgSchema` auto-implemented.
45
+ *
46
+ * Declared with `declare` so that TS doesn't emit an `Object.defineProperty`
47
+ * for this field on the base constructor, which would otherwise overwrite
48
+ * a subclass field initializer under `useDefineForClassFields`.
49
+ */
50
+ protected readonly initArgSpec?: InitArgSpec<TInitParam>;
11
51
  /**
12
52
  * Ensure agent is initialized and ready for use.
13
53
  * Must be implemented by subclasses to create platform-specific agent.
@@ -15,11 +55,40 @@ export declare abstract class BaseMidsceneTools<TAgent extends BaseAgent = BaseA
15
55
  * @returns Promise resolving to initialized agent instance
16
56
  * @throws Error if agent initialization fails
17
57
  */
18
- protected abstract ensureAgent(initParam?: string): Promise<TAgent>;
58
+ protected abstract ensureAgent(initParam?: TInitParam): Promise<TAgent>;
59
+ private getInitArgKeys;
60
+ /**
61
+ * Extract a platform-specific agent init parameter from CLI/MCP tool args.
62
+ */
63
+ protected extractAgentInitParam(args: Record<string, unknown>): TInitParam | undefined;
64
+ /**
65
+ * Remove platform-specific init args before dispatching a tool payload to the action itself.
66
+ */
67
+ protected sanitizeToolArgs(args: Record<string, unknown>): Record<string, unknown>;
68
+ /**
69
+ * Expose platform-specific init args on action/common tool schemas.
70
+ */
71
+ protected getAgentInitArgSchema(): ToolSchema;
72
+ /**
73
+ * Expose CLI-only metadata for platform init args so single-platform help can
74
+ * show ergonomic bare flags while the underlying schema stays namespaced.
75
+ * When `preferBareKeys` is enabled, single-platform CLIs only accept the
76
+ * bare spellings; namespaced dotted spellings remain available through the
77
+ * MCP/YAML schema instead of the platform CLI surface.
78
+ */
79
+ protected getAgentInitArgCliMetadata(): ToolCliMetadata | undefined;
19
80
  /**
20
81
  * Optional: prepare platform-specific tools (e.g., device connection)
21
82
  */
22
83
  protected preparePlatformTools(): ToolDefinition[];
84
+ protected getCliReportSessionName(): string | undefined;
85
+ protected createNewCliReportSession(targetIdentity?: string): CliReportSession | undefined;
86
+ protected commitCliReportSession(session?: CliReportSession): void;
87
+ protected readCliReportFileName(): string | undefined;
88
+ protected readCliReportAgentOptions(): {
89
+ reportFileName: string;
90
+ reportAttributes: Record<string, string>;
91
+ } | undefined;
23
92
  /**
24
93
  * Must be implemented by subclasses to create a temporary device instance
25
94
  * This allows getting real actionSpace without connecting to device
@@ -0,0 +1,12 @@
1
+ export interface CliReportSession {
2
+ version: 1;
3
+ sessionName: string;
4
+ targetIdentity?: string;
5
+ reportFileName: string;
6
+ reportPath: string;
7
+ createdAt: number;
8
+ }
9
+ export declare function generateCliReportSession(sessionName: string, targetIdentity?: string): CliReportSession;
10
+ export declare function writeCliReportSession(session: CliReportSession): void;
11
+ export declare function createCliReportSession(sessionName: string, targetIdentity?: string): CliReportSession;
12
+ export declare function readCliReportSession(sessionName: string): CliReportSession | undefined;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Extract a human-readable message from an unknown thrown value.
3
+ *
4
+ * Many SDK/transport layers reject with structured objects (e.g.
5
+ * `{ code, message }`, `{ error: { message } }`, `{ cause: { message } }`)
6
+ * rather than `Error` instances. `String(obj)` collapses those to
7
+ * `"[object Object]"`, which is useless for diagnostics. This helper walks
8
+ * the common shapes, falls back to `JSON.stringify`, and finally to
9
+ * `Object.prototype.toString.call` so that callers always get something
10
+ * actionable in logs and surfaced tool results.
11
+ */
12
+ export declare function getErrorMessage(error: unknown): string;
@@ -1,5 +1,7 @@
1
1
  export * from './base-server';
2
2
  export * from './base-tools';
3
+ export * from './init-arg-utils';
4
+ export * from './error-formatter';
3
5
  export * from './tool-generator';
4
6
  export * from './types';
5
7
  export * from './inject-report-html-plugin';
@@ -0,0 +1,13 @@
1
+ import type { z } from 'zod';
2
+ import type { ToolSchema } from './types';
3
+ export declare function extractNamespacedArgs<TFieldName extends string, TArgs extends Record<string, unknown> = Record<string, unknown>>(args: Record<string, unknown>, namespace: string, keys: readonly TFieldName[]): TArgs | undefined;
4
+ export declare function sanitizeNamespacedArgs(args: Record<string, unknown>, namespace: string, keys: readonly string[]): Record<string, unknown>;
5
+ /**
6
+ * Build a flat MCP tool schema whose keys are dotted `"<namespace>.<field>"`.
7
+ *
8
+ * We intentionally stay flat (rather than `{ namespace: z.object({...}) }`) so
9
+ * that CLI (`--android.device-id`), MCP clients, and `--help` output all share
10
+ * the same spelling. `readNamespacedArg` understands all three input shapes:
11
+ * nested namespace object, dotted flat key, and bare key fallback.
12
+ */
13
+ export declare function createNamespacedInitArgSchema(namespace: string, shape: Record<string, z.ZodTypeAny>): ToolSchema;
@@ -2,12 +2,12 @@ interface RslibPluginApi {
2
2
  onAfterBuild: (callback: () => void) => void;
3
3
  }
4
4
  /**
5
- * Rslib plugin to inject report HTML from @midscene/core dist into MCP bundle.
5
+ * Rslib plugin to inject report HTML from @aiscene/core dist into MCP bundle.
6
6
  * This runs after build and reads the already-injected HTML from core.
7
7
  *
8
8
  * Prerequisites:
9
9
  * - @midscene/report must be in devDependencies to ensure correct build order
10
- * - @midscene/core dist must exist with injected HTML
10
+ * - @aiscene/core dist must exist with injected HTML
11
11
  *
12
12
  * @param packageDir - The directory of the MCP package (use __dirname)
13
13
  */
@@ -9,7 +9,7 @@ export interface LaunchMCPServerOptions extends HttpLaunchOptions {
9
9
  verbose?: boolean;
10
10
  }
11
11
  /**
12
- * Generic agent type (avoid importing from @midscene/core to prevent circular deps)
12
+ * Generic agent type (avoid importing from @aiscene/core to prevent circular deps)
13
13
  */
14
14
  export interface GenericAgent<TDevice = any> {
15
15
  interface: TDevice;
@@ -58,8 +58,8 @@ export interface MCPServerLauncherConfig<AgentType extends GenericAgent = Generi
58
58
  *
59
59
  * @example
60
60
  * ```typescript
61
- * import { createMCPServerLauncher } from '@midscene/shared/mcp';
62
- * import { Agent } from '@midscene/core/agent';
61
+ * import { createMCPServerLauncher } from '@aiscene/shared/mcp';
62
+ * import { Agent } from '@aiscene/core/agent';
63
63
  * import { WebMidsceneTools } from './web-tools';
64
64
  * import { WebMCPServer } from './server';
65
65
  *
@@ -1,10 +1,10 @@
1
- import type { ActionSpaceItem, BaseAgent, ToolDefinition } from './types';
1
+ import type { ActionSpaceItem, BaseAgent, ToolCliMetadata, ToolDefinition, ToolSchema } from './types';
2
2
  /**
3
3
  * Converts DeviceAction from actionSpace into MCP ToolDefinition
4
4
  * This is the core logic that removes need for hardcoded tool definitions
5
5
  */
6
- export declare function generateToolsFromActionSpace(actionSpace: ActionSpaceItem[], getAgent: () => Promise<BaseAgent>): ToolDefinition[];
6
+ export declare function generateToolsFromActionSpace(actionSpace: ActionSpaceItem[], getAgent: (args?: Record<string, unknown>) => Promise<BaseAgent>, sanitizeArgs?: (args: Record<string, unknown>) => Record<string, unknown>, initArgSchema?: ToolSchema, initArgCliMetadata?: ToolCliMetadata): ToolDefinition[];
7
7
  /**
8
8
  * Generate common tools (screenshot, act)
9
9
  */
10
- export declare function generateCommonTools(getAgent: () => Promise<BaseAgent>): ToolDefinition[];
10
+ export declare function generateCommonTools(getAgent: (args?: Record<string, unknown>) => Promise<BaseAgent>, initArgSchema?: ToolSchema, initArgCliMetadata?: ToolCliMetadata): ToolDefinition[];
@@ -49,6 +49,13 @@ export type ToolHandler<T = Record<string, unknown>> = (args: T) => Promise<Tool
49
49
  * Tool schema type using Zod
50
50
  */
51
51
  export type ToolSchema = Record<string, z.ZodTypeAny>;
52
+ export interface ToolCliOption {
53
+ preferredName?: string;
54
+ aliases?: string[];
55
+ }
56
+ export interface ToolCliMetadata {
57
+ options?: Record<string, ToolCliOption>;
58
+ }
52
59
  /**
53
60
  * Tool definition for MCP server
54
61
  */
@@ -57,6 +64,7 @@ export interface ToolDefinition<T = Record<string, unknown>> {
57
64
  description: string;
58
65
  schema: ToolSchema;
59
66
  handler: ToolHandler<T>;
67
+ cli?: ToolCliMetadata;
60
68
  }
61
69
  /**
62
70
  * Tool type for mcpKitForAgent return value
@@ -86,6 +94,8 @@ export interface BaseAgent {
86
94
  callActionInActionSpace?: (actionName: string, params?: unknown) => Promise<unknown>;
87
95
  aiAction?: (description: string, params?: Record<string, unknown>) => Promise<unknown>;
88
96
  aiWaitFor?: (assertion: string, options: Record<string, unknown>) => Promise<unknown>;
97
+ aiAssert?: (assertion: string, msg?: string, options?: Record<string, unknown>) => Promise<unknown>;
98
+ aiQuery?: (demand: any, opt?: any) => Promise<any>;
89
99
  }
90
100
  /**
91
101
  * Base device interface for temporary device instances
@@ -0,0 +1,113 @@
1
+ export type MidsceneRecorderEventType = 'click' | 'drag' | 'scroll' | 'input' | 'navigation' | 'setViewport' | 'keydown';
2
+ export type MidsceneRecorderSourceKind = 'studio-preview' | 'unsupported' | (string & {});
3
+ export type MidsceneRecorderPlatformId = 'web' | 'android' | 'ios' | 'computer' | 'harmony' | (string & {});
4
+ export interface MidsceneRecorderElementRect {
5
+ left?: number;
6
+ top?: number;
7
+ width?: number;
8
+ height?: number;
9
+ x?: number;
10
+ y?: number;
11
+ }
12
+ export interface MidsceneRecorderPageInfo {
13
+ width: number;
14
+ height: number;
15
+ }
16
+ /**
17
+ * A screenshot stored outside the recording event payload.
18
+ *
19
+ * Recorder events are persisted in the Studio renderer. Keeping full data
20
+ * URLs there makes long recordings retain every screenshot in the renderer
21
+ * heap, so screenshot bytes live in the Playground run directory instead.
22
+ */
23
+ export interface MidsceneRecorderScreenshotAssetRef {
24
+ id: string;
25
+ mimeType: string;
26
+ bytes: number;
27
+ }
28
+ export interface MidsceneRecorderEvent {
29
+ type: MidsceneRecorderEventType;
30
+ source?: MidsceneRecorderSourceKind;
31
+ actionType?: string;
32
+ rawPayload?: Record<string, unknown>;
33
+ url?: string;
34
+ title?: string;
35
+ value?: string;
36
+ elementRect?: MidsceneRecorderElementRect;
37
+ pageInfo: MidsceneRecorderPageInfo;
38
+ screenshotBefore?: string;
39
+ screenshotAfter?: string;
40
+ /** The single screenshot retained for AI description and Markdown export. */
41
+ screenshotAsset?: MidsceneRecorderScreenshotAssetRef;
42
+ semantic?: MidsceneRecorderSemantic;
43
+ elementDescription?: string;
44
+ descriptionLoading?: boolean;
45
+ screenshotWithBox?: string;
46
+ timestamp: number;
47
+ hashId: string;
48
+ mergedHashIds?: string[];
49
+ }
50
+ export type MidsceneRecorderSemanticSource = 'aiDescribe' | 'recorderAI' | 'heuristic';
51
+ export type MidsceneRecorderSemanticStatus = 'pending' | 'ready' | 'failed';
52
+ export type MidsceneRecorderSemanticConfidence = 'high' | 'medium' | 'low';
53
+ export interface MidsceneRecorderSemanticAiDescribe {
54
+ verifyPrompt: boolean;
55
+ verifyPassed?: boolean;
56
+ deepLocate?: boolean;
57
+ centerDistance?: number;
58
+ expectedCenter?: [number, number];
59
+ actualCenter?: [number, number];
60
+ annotatedScreenshotPath?: string;
61
+ }
62
+ export interface MidsceneRecorderSemantic {
63
+ source: MidsceneRecorderSemanticSource;
64
+ status: MidsceneRecorderSemanticStatus;
65
+ elementDescription?: string;
66
+ replayInstruction?: string;
67
+ actionSummary?: string;
68
+ confidence?: MidsceneRecorderSemanticConfidence;
69
+ error?: string;
70
+ aiDescribe?: MidsceneRecorderSemanticAiDescribe;
71
+ fallbackFrom?: MidsceneRecorderSemantic;
72
+ }
73
+ export interface MidsceneRecorderSemanticAction {
74
+ type: MidsceneRecorderEventType;
75
+ actionType?: string;
76
+ value?: string;
77
+ url?: string;
78
+ scrollDestinationDescription?: string;
79
+ }
80
+ export interface MidsceneRecorderTarget {
81
+ platformId: MidsceneRecorderPlatformId;
82
+ deviceId?: string;
83
+ label?: string;
84
+ values: Record<string, string | number | boolean>;
85
+ }
86
+ export interface MidsceneRecorderGeneratedCode {
87
+ markdown?: string;
88
+ yaml?: string;
89
+ playwright?: string;
90
+ updatedAt?: number;
91
+ }
92
+ export interface MidsceneRecorderMarkdownScreenshotAsset {
93
+ eventIndex: number;
94
+ eventHashId: string;
95
+ eventType: MidsceneRecorderEventType;
96
+ relativePath: string;
97
+ dataUrl: string;
98
+ base64Data: string;
99
+ mimeType: string;
100
+ }
101
+ export interface MidsceneRecorderMarkdownScreenshotOptions {
102
+ baseDir?: string;
103
+ maxScreenshots?: number;
104
+ }
105
+ export declare const DEFAULT_MIDSCENE_RECORDER_MARKDOWN_MAX_SCREENSHOTS = 20;
106
+ export declare function getMidsceneRecorderSemantic(event: Pick<MidsceneRecorderEvent, 'semantic'>): MidsceneRecorderSemantic | undefined;
107
+ export declare function buildMidsceneRecorderReplayInstruction(event: MidsceneRecorderSemanticAction, elementDescription: string): string;
108
+ export declare function buildMidsceneRecorderActionSummary(event: MidsceneRecorderSemanticAction, elementDescription: string): string;
109
+ export declare function getMidsceneRecorderEventDescription(event: MidsceneRecorderEvent): string;
110
+ export declare function getMidsceneRecorderScreenshotsForLLM(events: MidsceneRecorderEvent[], maxScreenshots?: number): string[];
111
+ export declare function sanitizeMidsceneRecorderFileName(value: string): string;
112
+ export declare function createMidsceneRecorderMarkdownScreenshotAssets(events: MidsceneRecorderEvent[], options?: MidsceneRecorderMarkdownScreenshotOptions): MidsceneRecorderMarkdownScreenshotAsset[];
113
+ export declare function stringifyMidsceneRecorderTargetBlock(target: MidsceneRecorderTarget): string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiscene/shared",
3
- "version": "8.0.2",
3
+ "version": "8.0.4",
4
4
  "repository": "https://github.com/web-infra-dev/midscene",
5
5
  "homepage": "https://midscenejs.com/",
6
6
  "types": "./dist/types/index.d.ts",
@@ -0,0 +1,109 @@
1
+ import { z } from 'zod';
2
+
3
+ export interface AgentBehaviorInitArgs {
4
+ aiActContext?: string;
5
+ aiActionContext?: string;
6
+ replanningCycleLimit?: number;
7
+ waitAfterAction?: number;
8
+ screenshotShrinkFactor?: number;
9
+ }
10
+
11
+ type ExposedAgentBehaviorInitArgKey = Exclude<
12
+ keyof AgentBehaviorInitArgs,
13
+ 'aiActionContext'
14
+ >;
15
+
16
+ export const agentBehaviorInitArgShape = {
17
+ aiActContext: z
18
+ .string()
19
+ .optional()
20
+ .describe(
21
+ 'Background knowledge passed to aiAct. Default: no extra context.',
22
+ ),
23
+ replanningCycleLimit: z
24
+ .number()
25
+ .int()
26
+ .nonnegative()
27
+ .optional()
28
+ .describe(
29
+ 'Maximum number of replanning cycles for aiAct. Default: model adapter default.',
30
+ ),
31
+ waitAfterAction: z
32
+ .number()
33
+ .nonnegative()
34
+ .optional()
35
+ .describe(
36
+ 'Wait time in milliseconds after each action execution. Default: 300ms.',
37
+ ),
38
+ screenshotShrinkFactor: z
39
+ .number()
40
+ .min(1)
41
+ .optional()
42
+ .describe(
43
+ 'Screenshot shrink factor before sending images to AI. Default: 1; high values may reduce recognition quality, especially on mobile.',
44
+ ),
45
+ } satisfies Record<ExposedAgentBehaviorInitArgKey, z.ZodTypeAny>;
46
+
47
+ export function extractAgentBehaviorInitArgs(
48
+ extracted: Partial<AgentBehaviorInitArgs> | undefined,
49
+ ): AgentBehaviorInitArgs | undefined {
50
+ if (!extracted) {
51
+ return undefined;
52
+ }
53
+
54
+ const agentOptions: AgentBehaviorInitArgs = {
55
+ ...(typeof extracted.aiActContext === 'string'
56
+ ? { aiActContext: extracted.aiActContext }
57
+ : {}),
58
+ ...(typeof extracted.aiActionContext === 'string'
59
+ ? { aiActionContext: extracted.aiActionContext }
60
+ : {}),
61
+ ...(typeof extracted.replanningCycleLimit === 'number'
62
+ ? { replanningCycleLimit: extracted.replanningCycleLimit }
63
+ : {}),
64
+ ...(typeof extracted.waitAfterAction === 'number'
65
+ ? { waitAfterAction: extracted.waitAfterAction }
66
+ : {}),
67
+ ...(typeof extracted.screenshotShrinkFactor === 'number'
68
+ ? { screenshotShrinkFactor: extracted.screenshotShrinkFactor }
69
+ : {}),
70
+ };
71
+
72
+ return Object.keys(agentOptions).length > 0 ? agentOptions : undefined;
73
+ }
74
+
75
+ function stableJsonValue(value: unknown): unknown {
76
+ if (Array.isArray(value)) {
77
+ return value.map(stableJsonValue);
78
+ }
79
+
80
+ if (value && typeof value === 'object') {
81
+ return Object.fromEntries(
82
+ Object.entries(value as Record<string, unknown>)
83
+ .sort(([left], [right]) => left.localeCompare(right))
84
+ .map(([key, nestedValue]) => [key, stableJsonValue(nestedValue)]),
85
+ );
86
+ }
87
+
88
+ return value;
89
+ }
90
+
91
+ export function getAgentInitArgsSignature(
92
+ initArgs: object | undefined,
93
+ ): string | undefined {
94
+ if (!initArgs || Object.keys(initArgs).length === 0) {
95
+ return undefined;
96
+ }
97
+
98
+ return JSON.stringify(stableJsonValue(initArgs));
99
+ }
100
+
101
+ export function shouldRebuildAgentForInitArgs(
102
+ currentSignature: string | undefined,
103
+ nextSignature: string | undefined,
104
+ ): boolean {
105
+ return (
106
+ currentSignature !== nextSignature &&
107
+ (currentSignature !== undefined || nextSignature !== undefined)
108
+ );
109
+ }