miniapp.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. import {
  2. defineRuntimeTool,
  3. type AgentExtension,
  4. type ModelContextAssemblyCtx,
  5. } from '@mavis/agent-runtime';
  6. import { Type, type Static } from '@sinclair/typebox';
  7. import { Value } from '@sinclair/typebox/value';
  8. import {
  9. projectMiniAppFailure,
  10. type MiniAppFailureDiagnostic,
  11. type MiniAppFailureReasonCode,
  12. } from './miniapp-diagnostics.js';
  13. export type {
  14. MiniAppFailureDiagnostic,
  15. MiniAppFailureReasonCode,
  16. MiniAppFailureRecovery,
  17. MiniAppFailureStage,
  18. } from './miniapp-diagnostics.js';
  19. const TARGET_ACTIONS = ['init', 'open', 'inspect', 'publish', 'restart', 'stop'] as const;
  20. const MINIAPP_ACTIONS = ['list', ...TARGET_ACTIONS] as const;
  21. const PluginId = Type.String({
  22. minLength: 1,
  23. maxLength: 80,
  24. pattern: '^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$',
  25. description: 'Required for every Mini App action except list.',
  26. });
  27. const SourcePath = Type.String({
  28. minLength: 1,
  29. maxLength: 4096,
  30. pattern: '^[^\\u0000]*$',
  31. description:
  32. 'Publish only: path to a finished Mini App package directory, absolute or relative to the current Session workspace. Omit to publish the workspace package.',
  33. });
  34. // Keep the provider-facing input as one concrete object. Exact action/input pairing
  35. // remains a runtime concern below; exposing the action contracts as a root object
  36. // union produces a top-level anyOf that some OpenAI-compatible providers reject.
  37. const MiniAppProviderInputSchema = Type.Object(
  38. {
  39. action: Type.String({
  40. enum: [...MINIAPP_ACTIONS],
  41. pattern: `^(?:${MINIAPP_ACTIONS.join('|')})$`,
  42. description: 'Mini App lifecycle action.',
  43. }),
  44. pluginId: Type.Optional(PluginId),
  45. sourcePath: Type.Optional(SourcePath),
  46. },
  47. {
  48. additionalProperties: false,
  49. description:
  50. 'pluginId is required for every Mini App action except list. sourcePath is accepted only for publish.',
  51. },
  52. );
  53. const MiniAppActionInputSchema = Type.Union([
  54. Type.Object({ action: Type.Literal('list') }, { additionalProperties: false }),
  55. Type.Object(
  56. {
  57. action: Type.Literal('publish'),
  58. pluginId: PluginId,
  59. sourcePath: Type.Optional(SourcePath),
  60. },
  61. { additionalProperties: false },
  62. ),
  63. ...TARGET_ACTIONS.filter((action) => action !== 'publish').map((action) =>
  64. Type.Object(
  65. { action: Type.Literal(action), pluginId: PluginId },
  66. { additionalProperties: false },
  67. ),
  68. ),
  69. ]);
  70. export interface MiniAppSummary {
  71. readonly pluginId: string;
  72. /** Installation source reported by the Host, not declared by the package. */
  73. readonly source: 'official' | 'local';
  74. readonly displayName?: string;
  75. readonly runtime: {
  76. readonly kind: 'process';
  77. readonly status: 'stopped' | 'starting' | 'running' | 'stopping' | 'failed';
  78. readonly errorCode?: string;
  79. };
  80. }
  81. export interface MiniAppListResult {
  82. readonly miniApps: readonly MiniAppSummary[];
  83. }
  84. export interface MiniAppInitResult {
  85. readonly pluginId: string;
  86. readonly mode: 'create' | 'update';
  87. readonly packagePath: `miniapps/${string}` | `liveboards/${string}`;
  88. }
  89. export interface MiniAppTargetResult {
  90. readonly miniApp: MiniAppSummary;
  91. }
  92. export type MiniAppRunningSummary = Omit<MiniAppSummary, 'runtime'> & {
  93. readonly runtime: {
  94. readonly kind: 'process';
  95. readonly status: 'running';
  96. };
  97. };
  98. export interface MiniAppOpenResult extends MiniAppTargetResult {
  99. readonly miniApp: MiniAppRunningSummary;
  100. readonly opened: true;
  101. }
  102. export interface MiniAppActionContext {
  103. readonly sessionId: string;
  104. readonly turnId: string;
  105. readonly signal?: AbortSignal;
  106. }
  107. export interface MiniAppTargetActionContext extends MiniAppActionContext {
  108. readonly pluginId: string;
  109. }
  110. export interface MiniAppPublishActionContext extends MiniAppTargetActionContext {
  111. readonly sourcePath?: string;
  112. }
  113. /** Consumer-owned seam implemented only by a Host that owns a real Mini App lifecycle. */
  114. export interface MiniAppLifecycle {
  115. /** Returns accepted, enabled Mini Apps with their current runtime state. */
  116. list(input: MiniAppActionContext): Promise<MiniAppListResult>;
  117. /** Scaffolds or binds the deterministic package root in the current Session workspace for authoring. */
  118. init(input: MiniAppTargetActionContext): Promise<MiniAppInitResult>;
  119. open(input: MiniAppTargetActionContext): Promise<MiniAppOpenResult>;
  120. /** Returns the installed Mini App and runtime lifecycle summary, without reading its surface. */
  121. inspect(input: MiniAppTargetActionContext): Promise<MiniAppTargetResult>;
  122. /** Accepts the specified finished package directory or current Session workspace package and starts its runtime. */
  123. publish(input: MiniAppPublishActionContext): Promise<MiniAppTargetResult>;
  124. /** Restarts an already installed Mini App runtime without adopting workspace changes. */
  125. restart(input: MiniAppTargetActionContext): Promise<MiniAppTargetResult>;
  126. /** Stops an installed Mini App runtime without deleting its package. */
  127. stop(input: MiniAppTargetActionContext): Promise<MiniAppTargetResult>;
  128. }
  129. export type MiniAppLifecycleErrorCode =
  130. | 'NOT_FOUND'
  131. | 'NOT_ENABLED'
  132. | 'PLUGIN_ALREADY_EXISTS'
  133. | 'BUSY'
  134. | 'SERVICE_RESTARTED'
  135. | 'PREPARATION_FAILED'
  136. | 'RUNTIME_FAILED'
  137. | 'OPEN_UNAVAILABLE'
  138. | 'OPEN_FAILED'
  139. | 'INTERNAL_ERROR'
  140. | 'CANCELLED';
  141. export type MiniAppBusyReason = 'operation_busy' | 'capacity_busy';
  142. export interface MiniAppRuntimeErrorDetail {
  143. readonly errorText: string;
  144. readonly stderr?: string;
  145. }
  146. type MiniAppLifecycleErrorInput = {
  147. readonly message: string;
  148. readonly retryable: boolean;
  149. readonly diagnosticReason?: MiniAppFailureReasonCode;
  150. readonly runtimeError?: MiniAppRuntimeErrorDetail;
  151. } & (
  152. | { readonly code: 'BUSY'; readonly busyReason: MiniAppBusyReason }
  153. | {
  154. readonly code: 'INTERNAL_ERROR';
  155. readonly busyReason?: never;
  156. readonly diagnosticId: string;
  157. readonly lastGoodAvailable?: boolean;
  158. }
  159. | {
  160. readonly code: Exclude<MiniAppLifecycleErrorCode, 'BUSY' | 'INTERNAL_ERROR'>;
  161. readonly busyReason?: never;
  162. readonly diagnosticId?: never;
  163. readonly lastGoodAvailable?: never;
  164. }
  165. );
  166. export class MiniAppLifecycleError extends Error {
  167. override readonly name = 'MiniAppLifecycleError';
  168. readonly code: MiniAppLifecycleErrorCode;
  169. readonly retryable: boolean;
  170. readonly busyReason?: MiniAppBusyReason;
  171. readonly diagnosticReason?: MiniAppFailureReasonCode;
  172. readonly runtimeError?: MiniAppRuntimeErrorDetail;
  173. readonly diagnosticId?: string;
  174. readonly lastGoodAvailable?: boolean;
  175. constructor(input: MiniAppLifecycleErrorInput) {
  176. super(input.message);
  177. this.code = input.code;
  178. const projection = projectMiniAppFailure(input.code, input.diagnosticReason);
  179. this.retryable =
  180. input.busyReason === 'capacity_busy' ? false : (projection?.retryable ?? input.retryable);
  181. if (input.code === 'BUSY') this.busyReason = input.busyReason;
  182. if (input.code === 'INTERNAL_ERROR') {
  183. this.diagnosticId = input.diagnosticId;
  184. if (input.lastGoodAvailable !== undefined) {
  185. this.lastGoodAvailable = input.lastGoodAvailable;
  186. }
  187. }
  188. if (projection) this.diagnosticReason = projection.diagnostic.reasonCode;
  189. if (input.runtimeError) this.runtimeError = input.runtimeError;
  190. }
  191. }
  192. type MiniAppInput = Static<typeof MiniAppActionInputSchema>;
  193. type MiniAppAction = MiniAppInput['action'];
  194. type MiniAppReportedAction = MiniAppAction | 'unknown';
  195. /** Creates the host extension only when a real Mini App lifecycle adapter is available. */
  196. export function createMiniAppControlExtension(lifecycle: MiniAppLifecycle): AgentExtension {
  197. const tool = createMiniAppTool(lifecycle);
  198. return {
  199. id: 'miniapp-control',
  200. description: 'Host-owned Mini App bootstrap and runtime lifecycle control.',
  201. init(api) {
  202. api.registerTool((context) => (isMiniAppTurn(context) ? tool : null));
  203. },
  204. };
  205. }
  206. function createMiniAppTool(lifecycle: MiniAppLifecycle) {
  207. return defineRuntimeTool({
  208. name: 'miniapp',
  209. description:
  210. "Initialize, list, open, inspect, publish, restart, or stop a Mini App. Init scaffolds or binds the package root in the current Session workspace for authoring without publishing it. Inspect returns the installed Mini App's source (official or local) and runtime state. Before editing an installed Mini App, inspect its source; official Plugin implementations do not support local editing or republishing. Use miniapp-creator for authoring and recovery guidance. Publish starts or replaces the runtime. Init is not required for a complete package directory. Restart restarts an installed runtime. Stop releases an installed runtime without deleting its Mini App package; use the Mini App Plugin's own Skills, MCP servers, and Connectors for business operations.",
  211. schema: MiniAppProviderInputSchema,
  212. source: 'builtin',
  213. operationClassifier: {
  214. allowedValues: MINIAPP_ACTIONS,
  215. classify: (input) => readRecord(input).action as string | undefined,
  216. },
  217. execute: async (context, rawInput, signal) => {
  218. const action = readMiniAppAction(rawInput);
  219. if (signal?.aborted) return errorResult(action, cancelledError());
  220. if (!Value.Check(MiniAppActionInputSchema, rawInput)) {
  221. return errorResult(action, invalidArgumentsError(action, rawInput));
  222. }
  223. const input = rawInput as MiniAppInput;
  224. try {
  225. const result = await dispatch(lifecycle, input, {
  226. sessionId: context.sessionId,
  227. turnId: context.turnId,
  228. ...(signal ? { signal } : {}),
  229. });
  230. return successResult(input.action, result);
  231. } catch (error) {
  232. return errorResult(input.action, normalizeError(error, signal));
  233. }
  234. },
  235. });
  236. }
  237. async function dispatch(
  238. lifecycle: MiniAppLifecycle,
  239. input: MiniAppInput,
  240. context: MiniAppActionContext,
  241. ): Promise<MiniAppListResult | MiniAppInitResult | MiniAppOpenResult | MiniAppTargetResult> {
  242. if (input.action === 'list') return lifecycle.list(context);
  243. const target = { ...context, pluginId: input.pluginId };
  244. switch (input.action) {
  245. case 'init':
  246. return lifecycle.init(target);
  247. case 'open':
  248. return lifecycle.open(target);
  249. case 'inspect':
  250. return lifecycle.inspect(target);
  251. case 'publish':
  252. return lifecycle.publish({
  253. ...target,
  254. ...(input.sourcePath !== undefined ? { sourcePath: input.sourcePath } : {}),
  255. });
  256. case 'restart':
  257. return lifecycle.restart(target);
  258. case 'stop':
  259. return lifecycle.stop(target);
  260. }
  261. }
  262. function successResult(
  263. action: MiniAppAction,
  264. result: MiniAppListResult | MiniAppInitResult | MiniAppOpenResult | MiniAppTargetResult,
  265. ) {
  266. const response = { ok: true as const, action, result };
  267. const text = JSON.stringify(response);
  268. return {
  269. tool_name: 'miniapp',
  270. text,
  271. content: [{ type: 'text' as const, text }],
  272. details: response,
  273. };
  274. }
  275. interface StableToolError {
  276. readonly code: MiniAppLifecycleErrorCode | 'INVALID_ARGUMENTS';
  277. readonly message: string;
  278. readonly retryable: boolean;
  279. readonly busyReason?: MiniAppBusyReason;
  280. readonly diagnostic?: MiniAppFailureDiagnostic;
  281. readonly runtimeError?: MiniAppRuntimeErrorDetail;
  282. readonly diagnosticId?: string;
  283. readonly lastGoodAvailable?: boolean;
  284. }
  285. function errorResult(action: MiniAppReportedAction, error: StableToolError) {
  286. const response = { ok: false as const, action, error };
  287. const text = JSON.stringify(response);
  288. return {
  289. tool_name: 'miniapp',
  290. text,
  291. content: [{ type: 'text' as const, text }],
  292. details: response,
  293. isError: true as const,
  294. };
  295. }
  296. function normalizeError(error: unknown, signal: AbortSignal | undefined): StableToolError {
  297. if (signal?.aborted || (error instanceof Error && error.name === 'AbortError')) {
  298. return cancelledError();
  299. }
  300. if (isKnownLifecycleError(error)) {
  301. const projection = projectMiniAppFailure(error.code, error.diagnosticReason);
  302. const runtimeError = error instanceof MiniAppLifecycleError ? error.runtimeError : undefined;
  303. if (projection) {
  304. return {
  305. code: error.code,
  306. ...projection,
  307. ...(runtimeError ? { runtimeError } : {}),
  308. };
  309. }
  310. if (error.code === 'INTERNAL_ERROR') {
  311. return {
  312. code: error.code,
  313. message: MINIAPP_RECORDED_INTERNAL_ERROR_MESSAGE,
  314. retryable: false,
  315. diagnosticId: error.diagnosticId,
  316. ...(error.lastGoodAvailable !== undefined
  317. ? { lastGoodAvailable: error.lastGoodAvailable }
  318. : {}),
  319. };
  320. }
  321. return {
  322. code: error.code,
  323. message: MINIAPP_PUBLIC_ERROR_MESSAGES[error.code],
  324. retryable:
  325. error.busyReason === 'capacity_busy'
  326. ? false
  327. : stableRetryability(error.code, error.retryable),
  328. ...(error.busyReason ? { busyReason: error.busyReason } : {}),
  329. ...(runtimeError ? { runtimeError } : {}),
  330. };
  331. }
  332. return {
  333. code: 'INTERNAL_ERROR',
  334. message: MINIAPP_PUBLIC_ERROR_MESSAGES.INTERNAL_ERROR,
  335. retryable: false,
  336. };
  337. }
  338. const MINIAPP_PUBLIC_ERROR_MESSAGES: Readonly<Record<MiniAppLifecycleErrorCode, string>> = {
  339. NOT_FOUND: 'Mini App was not found.',
  340. NOT_ENABLED: 'Mini App is not enabled.',
  341. PLUGIN_ALREADY_EXISTS: 'Mini App Plugin is already installed.',
  342. BUSY: 'Mini App is busy.',
  343. SERVICE_RESTARTED: 'Mini App service restarted.',
  344. PREPARATION_FAILED: 'Mini App preparation failed.',
  345. RUNTIME_FAILED: 'Mini App runtime failed.',
  346. OPEN_UNAVAILABLE: 'Mini App open is unavailable.',
  347. OPEN_FAILED: 'Mini App could not be opened.',
  348. INTERNAL_ERROR: 'The Mini App host could not complete the action.',
  349. CANCELLED: 'The Mini App action was cancelled.',
  350. };
  351. const MINIAPP_RECORDED_INTERNAL_ERROR_MESSAGE =
  352. 'The Mini App Host could not complete this action. A diagnostic ID was created automatically.';
  353. function stableRetryability(code: MiniAppLifecycleErrorCode, fallback: boolean): boolean {
  354. if (code === 'BUSY' || code === 'SERVICE_RESTARTED') return true;
  355. if (code === 'PLUGIN_ALREADY_EXISTS' || code === 'PREPARATION_FAILED') return false;
  356. return fallback;
  357. }
  358. function cancelledError(): StableToolError {
  359. return {
  360. code: 'CANCELLED',
  361. message: 'The Mini App action was cancelled.',
  362. retryable: false,
  363. };
  364. }
  365. function invalidArgumentsError(action: MiniAppReportedAction, input: unknown): StableToolError {
  366. const record = readRecord(input);
  367. let message = 'Mini App arguments are invalid for the selected action.';
  368. if (action === 'list' && Object.prototype.hasOwnProperty.call(record, 'pluginId')) {
  369. message = 'pluginId must be omitted for the list action.';
  370. } else if (
  371. action !== 'unknown' &&
  372. action !== 'publish' &&
  373. Object.prototype.hasOwnProperty.call(record, 'sourcePath')
  374. ) {
  375. message = 'sourcePath is only accepted for the publish action.';
  376. } else if (
  377. action !== 'unknown' &&
  378. action !== 'list' &&
  379. !Object.prototype.hasOwnProperty.call(record, 'pluginId')
  380. ) {
  381. message = 'pluginId is required for this Mini App action.';
  382. }
  383. return {
  384. code: 'INVALID_ARGUMENTS',
  385. message,
  386. retryable: false,
  387. };
  388. }
  389. function readMiniAppAction(input: unknown): MiniAppReportedAction {
  390. const action = readRecord(input).action;
  391. return typeof action === 'string' && (MINIAPP_ACTIONS as readonly string[]).includes(action)
  392. ? (action as MiniAppAction)
  393. : 'unknown';
  394. }
  395. function isMiniAppTurn(context: ModelContextAssemblyCtx): boolean {
  396. const config = readRecord(context.agentConfig);
  397. const profile = readRecord(config.agent_profile);
  398. return profile.surface === 'interactive';
  399. }
  400. function isKnownLifecycleError(error: unknown): error is {
  401. readonly code: MiniAppLifecycleErrorCode;
  402. readonly retryable: boolean;
  403. readonly busyReason?: MiniAppBusyReason;
  404. readonly diagnosticReason?: unknown;
  405. readonly diagnosticId?: string;
  406. readonly lastGoodAvailable?: boolean;
  407. } {
  408. if (!(error instanceof Error) || error.name !== 'MiniAppLifecycleError') return false;
  409. const candidate = error as Error & {
  410. readonly code?: unknown;
  411. readonly retryable?: unknown;
  412. readonly busyReason?: unknown;
  413. readonly diagnosticReason?: unknown;
  414. readonly diagnosticId?: unknown;
  415. readonly lastGoodAvailable?: unknown;
  416. };
  417. return (
  418. typeof candidate.code === 'string' &&
  419. candidate.code in MINIAPP_PUBLIC_ERROR_MESSAGES &&
  420. typeof candidate.retryable === 'boolean' &&
  421. validBusyReason(candidate.code, candidate.busyReason) &&
  422. validInternalDiagnostic(candidate.code, candidate.diagnosticId, candidate.lastGoodAvailable)
  423. );
  424. }
  425. function validBusyReason(code: string, value: unknown): value is MiniAppBusyReason | undefined {
  426. if (code === 'BUSY') return value === 'operation_busy' || value === 'capacity_busy';
  427. return value === undefined;
  428. }
  429. function validInternalDiagnostic(
  430. code: string,
  431. diagnosticId: unknown,
  432. lastGoodAvailable: unknown,
  433. ): boolean {
  434. if (code === 'INTERNAL_ERROR') {
  435. return (
  436. typeof diagnosticId === 'string' &&
  437. diagnosticId.length > 0 &&
  438. (lastGoodAvailable === undefined || typeof lastGoodAvailable === 'boolean')
  439. );
  440. }
  441. return diagnosticId === undefined && lastGoodAvailable === undefined;
  442. }
  443. function readRecord(value: unknown): Readonly<Record<string, unknown>> {
  444. return value !== null && typeof value === 'object' && !Array.isArray(value)
  445. ? (value as Readonly<Record<string, unknown>>)
  446. : {};
  447. }