local-native-tools.test.ts 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. import { access, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
  2. import { tmpdir } from 'node:os';
  3. import { dirname, join } from 'node:path';
  4. import { fileURLToPath } from 'node:url';
  5. import { describe, expect, it, vi } from 'vitest';
  6. import { resolveAgentCapabilities } from '@mavis/config';
  7. import type { IRuntimeEvent } from '@mavis/protocol';
  8. import {
  9. buildLocalNativeRuntimeTools,
  10. buildLocalTurnToolSources,
  11. } from '../../src/api/local-native-tools.js';
  12. import { withoutLocalMavisCronGuidance } from '../../src/api/local-mavis-cron-guidance.js';
  13. import { LocalEventSink } from '../../src/events/sink.js';
  14. import { LocalMcpService } from '../../../local-runtime-v2/src/service/mcp/index.js';
  15. import { LocalMemoryFacade } from '../../src/memory/local-memory-facade.js';
  16. import { initSkillService } from '../../src/skills/skill-service.js';
  17. const packageRoot = join(dirname(fileURLToPath(import.meta.url)), '../..');
  18. describe('local native turn tools', () => {
  19. it('exposes native web_search only when the local product owner gate is enabled', () => {
  20. const base = {
  21. workspaceRoot: '/workspace',
  22. agentName: 'mavis',
  23. webSearchAdapter: { search: vi.fn() },
  24. };
  25. expect(buildLocalNativeRuntimeTools(base).map((tool) => tool.def.name)).not.toContain(
  26. 'web_search',
  27. );
  28. expect(
  29. buildLocalNativeRuntimeTools({ ...base, webSearchEnabled: true }).map(
  30. (tool) => tool.def.name,
  31. ),
  32. ).toContain('web_search');
  33. });
  34. it('executes native search through the authenticated gateway without a Matrix MCP server', async () => {
  35. vi.stubEnv('MAVIS_BUILD_ENV', 'test');
  36. const dataDir = await mkdtemp(join(tmpdir(), 'native-search-'));
  37. const mcpService = new LocalMcpService(() => dataDir);
  38. const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(
  39. new Response(
  40. JSON.stringify({
  41. code: 0,
  42. results: [{ title: 'Result', link: 'https://example.test', snippet: 'Evidence' }],
  43. total: 1,
  44. }),
  45. { status: 200 },
  46. ),
  47. );
  48. const input = {
  49. dataDir,
  50. workspaceRoot: dataDir,
  51. agentName: 'mavis',
  52. sessionId: 'search-session',
  53. toolsDisabled: false,
  54. nativeWebSearchEnabled: true,
  55. mcpService,
  56. emitBusEvent: vi.fn(),
  57. threadGoal: { runtimeToolsFor: async () => [] } as never,
  58. authContext: { accessToken: 'test-search-token' },
  59. fetchImpl,
  60. routingContextGetter: () => ({ bedrockLane: 'search-lane' }),
  61. };
  62. try {
  63. const sources = await buildLocalTurnToolSources(input);
  64. expect(sources.mcpEntries).toEqual([]);
  65. expect(await mcpService.listServers()).toEqual([]);
  66. const searches = sources.nativeTools.filter((tool) => tool.def.name === 'web_search');
  67. expect(searches).toHaveLength(1);
  68. const result = await searches[0]!.impl.execute(
  69. { sessionId: 'search-session', turnId: 'search-turn' },
  70. { query: 'MiniMax' },
  71. );
  72. expect(JSON.parse(result.text)).toMatchObject({ total: 1 });
  73. expect(result.details).toMatchObject({
  74. server: 'matrix',
  75. tool: 'web_search',
  76. mcp: { isError: false },
  77. });
  78. const [url, request] = fetchImpl.mock.calls[0]!;
  79. expect(String(url)).toMatch(/\/mavis\/api\/v1\/mcp\/web_search$/);
  80. expect(new Headers(request?.headers).get('authorization')).toBe('Bearer test-search-token');
  81. expect(new Headers(request?.headers).get('bedrock-lane')).toBe('search-lane');
  82. expect(JSON.parse(request!.body as string)).toEqual({ query: 'MiniMax' });
  83. const noTools = await buildLocalTurnToolSources({ ...input, toolsDisabled: true });
  84. expect(noTools.nativeTools).toEqual([]);
  85. } finally {
  86. vi.unstubAllEnvs();
  87. await mcpService.close();
  88. await rm(dataDir, { recursive: true, force: true });
  89. }
  90. });
  91. it('omits Memory from Custom and factless tool catalogs while retaining full Mavis Memory', async () => {
  92. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-memory-scope-'));
  93. try {
  94. const facade = new LocalMemoryFacade({
  95. config: () => ({ dataDir, enabled: true }),
  96. nowMs: () => 1_700_000_000_000,
  97. });
  98. const customTools = buildLocalNativeRuntimeTools({
  99. dataDir,
  100. workspaceRoot: dataDir,
  101. agentName: 'writer',
  102. memoryFacade: facade,
  103. memoryAgentScopeEnabled: false,
  104. });
  105. const factlessTools = buildLocalNativeRuntimeTools({
  106. dataDir,
  107. workspaceRoot: dataDir,
  108. agentName: 'mavis',
  109. memoryFacade: facade,
  110. });
  111. expect(customTools.map((tool) => tool.def.name)).not.toContain('memory');
  112. expect(factlessTools.map((tool) => tool.def.name)).not.toContain('memory');
  113. await expect(access(join(dataDir, 'agents', 'writer', 'memory'))).rejects.toThrow();
  114. const primaryMemory = buildLocalNativeRuntimeTools({
  115. dataDir,
  116. workspaceRoot: dataDir,
  117. agentName: 'mavis',
  118. memoryFacade: facade,
  119. memoryAgentScopeEnabled: true,
  120. memoryReadAgentNames: ['mavis', 'main'],
  121. }).find((tool) => tool.def.name === 'memory');
  122. if (!primaryMemory) throw new Error('primary memory tool not found');
  123. const primaryResult = await primaryMemory.impl.execute(
  124. { sessionId: 'ses_mavis', turnId: 'turn_mavis', agentName: 'mavis' },
  125. { target: 'main', operation: 'append', content: 'PRIMARY_SENTINEL' },
  126. );
  127. expect(primaryResult.details).toMatchObject({ ok: true });
  128. const userResult = await primaryMemory.impl.execute(
  129. { sessionId: 'ses_mavis', turnId: 'turn_mavis', agentName: 'mavis' },
  130. {
  131. target: 'user',
  132. operation: 'append',
  133. content: 'shared preference',
  134. reason: 'requested',
  135. },
  136. );
  137. expect(userResult.details).toMatchObject({ ok: true });
  138. await expect(facade.getAgentMemory('mavis')).resolves.toMatchObject({
  139. content: expect.stringContaining('PRIMARY_SENTINEL'),
  140. });
  141. await expect(facade.getUserMemory()).resolves.toMatchObject({
  142. content: expect.stringContaining('shared preference'),
  143. });
  144. } finally {
  145. await rm(dataDir, { recursive: true, force: true });
  146. }
  147. });
  148. it('removes Cron from the Mavis Tool contract when the Cron adapter is absent', () => {
  149. const base = {
  150. workspaceRoot: '/workspace',
  151. agentName: 'mavis',
  152. mavisAgentAdapter: {} as never,
  153. };
  154. const withoutCron = buildLocalNativeRuntimeTools(base).find(
  155. (tool) => tool.def.name === 'mavis',
  156. );
  157. const withCron = buildLocalNativeRuntimeTools({
  158. ...base,
  159. mavisCronAdapter: {} as never,
  160. }).find((tool) => tool.def.name === 'mavis');
  161. expect(withoutCron?.def.description).toContain('agent — local desktop agent roster');
  162. expect(withoutCron?.def.description).toContain('session — local desktop conversations');
  163. expect(withoutCron?.def.description).not.toContain('cron — local desktop scheduled tasks');
  164. expect(withoutCron?.def.description).not.toContain('command: "cron');
  165. expect(withoutCron?.def.description).not.toMatch(/scheduled tasks/i);
  166. expect(JSON.stringify(withoutCron?.def.schema)).not.toMatch(/cron/i);
  167. expect(withCron?.def.description).toContain('cron — local desktop scheduled tasks');
  168. });
  169. it('strips Cron-only args from the model-visible Mavis schema when Cron is absent', () => {
  170. // Description-only stripping still leaked the capability: `cron_id`,
  171. // `schedule`, `every` and friends stayed in the args schema, which is
  172. // enough for a model to infer Cron exists and call into an error.
  173. const base = {
  174. workspaceRoot: '/workspace',
  175. agentName: 'mavis',
  176. mavisAgentAdapter: {} as never,
  177. };
  178. const argsOf = (tool: { def: { schema: unknown } } | undefined) =>
  179. (tool?.def.schema as { properties: { args: { properties: Record<string, unknown> } } })
  180. .properties.args.properties;
  181. const withoutCron = argsOf(
  182. buildLocalNativeRuntimeTools(base).find((tool) => tool.def.name === 'mavis'),
  183. );
  184. const withCron = argsOf(
  185. buildLocalNativeRuntimeTools({ ...base, mavisCronAdapter: {} as never }).find(
  186. (tool) => tool.def.name === 'mavis',
  187. ),
  188. );
  189. for (const field of [
  190. 'cron_id',
  191. 'cron_name',
  192. 'schedule',
  193. 'every',
  194. 'after',
  195. 'at',
  196. 'active_hours',
  197. 'quiet_on_skip',
  198. 'timezone',
  199. 'model',
  200. 'prompt',
  201. 'session',
  202. ]) {
  203. expect(withoutCron).not.toHaveProperty(field);
  204. expect(withCron).toHaveProperty(field);
  205. }
  206. // Session and MCP command arguments remain available.
  207. for (const field of ['session_id', 'mode', 'agent_name', 'limit', 'cursor', 'enabled']) {
  208. expect(withoutCron).toHaveProperty(field);
  209. }
  210. expect(withoutCron.enabled).toMatchObject({
  211. type: 'boolean',
  212. description: expect.stringContaining('mcp create/update'),
  213. });
  214. expect(withoutCron.agent_name).toMatchObject({
  215. description: expect.stringContaining('Required for agent get/update/delete'),
  216. });
  217. expect(withoutCron.transport).toMatchObject({
  218. anyOf: [{ const: 'stdio' }, { const: 'http' }, { const: 'streamable-http' }, { const: 'sse' }],
  219. description: expect.stringContaining('Do not mix stdio and remote fields.'),
  220. });
  221. // No residual Cron wording in retained field descriptions either.
  222. for (const field of Object.values(withoutCron)) {
  223. const description = (field as { description?: string }).description;
  224. if (typeof description === 'string') expect(description).not.toMatch(/cron/i);
  225. }
  226. });
  227. it('derives the Cron-less Mavis contract without mutating the frozen definition', () => {
  228. // `LocalMavisToolDef` is contract-frozen by a snapshot test; stripping must
  229. // copy rather than edit it in place, or the desktop host loses Cron too.
  230. const base = {
  231. workspaceRoot: '/workspace',
  232. agentName: 'mavis',
  233. mavisAgentAdapter: {} as never,
  234. };
  235. const withoutCron = buildLocalNativeRuntimeTools(base).find(
  236. (tool) => tool.def.name === 'mavis',
  237. );
  238. if (!withoutCron) throw new Error('mavis tool not found');
  239. expect(withoutLocalMavisCronGuidance(withoutCron).def).toEqual(withoutCron.def);
  240. const stillHasCron = buildLocalNativeRuntimeTools({
  241. ...base,
  242. mavisCronAdapter: {} as never,
  243. }).find((tool) => tool.def.name === 'mavis');
  244. expect(stillHasCron?.def.description).toContain('cron — local desktop scheduled tasks');
  245. const schema = stillHasCron?.def.schema as {
  246. properties: { command: { description: string }; args: { description: string; properties: Record<string, unknown> } };
  247. };
  248. expect(schema.properties.command.description).toContain('cron resolve-model');
  249. expect(schema.properties.args.description).toContain('cron once requires exactly one');
  250. expect(schema.properties.args.properties).toHaveProperty('cron_id');
  251. expect(schema.properties.args.properties).toHaveProperty('model');
  252. });
  253. it('keeps the Memory tool read-only when a session disables memory writes', async () => {
  254. const getUserMemory = vi.fn(async () => ({ content: 'saved user memory' }));
  255. const appendMemory = vi.fn();
  256. const memory = buildLocalNativeRuntimeTools({
  257. workspaceRoot: '/workspace',
  258. agentName: 'mavis',
  259. memoryFacade: { getUserMemory, appendMemory } as never,
  260. memoryEnabled: true,
  261. memoryReadEnabled: true,
  262. memoryWriteEnabled: false,
  263. memoryAgentScopeEnabled: true,
  264. }).find((tool) => tool.def.name === 'memory');
  265. expect(memory).toBeDefined();
  266. expect(memory?.def.description).toBe(
  267. 'Read and search local memory. Supports target=user|main|topic.',
  268. );
  269. const schema = memory?.def.schema as {
  270. properties: {
  271. target: { anyOf: Array<{ const: string }> };
  272. operation: { anyOf: Array<{ const: string }> };
  273. };
  274. };
  275. expect(schema.properties.target.anyOf.map(({ const: value }) => value)).toEqual([
  276. 'user',
  277. 'main',
  278. 'topic',
  279. ]);
  280. expect(schema.properties.operation.anyOf.map(({ const: value }) => value)).toEqual([
  281. 'read',
  282. 'search',
  283. ]);
  284. const context = { sessionId: 'read-only-memory', turnId: 'turn-1', agentName: 'mavis' };
  285. const read = await memory!.impl.execute(context, { target: 'user', operation: 'read' });
  286. const write = await memory!.impl.execute(context, {
  287. target: 'main',
  288. operation: 'append',
  289. content: 'blocked memory',
  290. });
  291. expect(read.text).toBe('saved user memory');
  292. expect(write.details).toMatchObject({
  293. kind: 'memory',
  294. ok: false,
  295. code: 'MEMORY_WRITE_DISABLED',
  296. });
  297. expect(appendMemory).not.toHaveBeenCalled();
  298. });
  299. it('filters configurable built-in tools and only the delegation entry point', async () => {
  300. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-capability-tools-'));
  301. try {
  302. const { nativeTools: tools } = await buildLocalTurnToolSources({
  303. toolsDisabled: false,
  304. workspaceRoot: process.cwd(),
  305. agentName: 'mavis',
  306. dataDir,
  307. eventWriter: new LocalEventSink(),
  308. sessionId: 'capability-session',
  309. mcpService: new LocalMcpService(() => dataDir),
  310. threadGoal: { runtimeToolsFor: () => [] } as never,
  311. emitBusEvent: () => {},
  312. builtinCapabilities: resolveAgentCapabilities({
  313. tools: ['read', 'task_query', 'task_output', 'task_stop'],
  314. features: { mavis: false, delegation: false },
  315. }),
  316. taskAdapter: {} as never,
  317. taskControlAdapter: {} as never,
  318. mavisAgentAdapter: {} as never,
  319. });
  320. const names = tools.map((tool) => tool.def.name);
  321. expect(names).toContain('read');
  322. expect(names).toContain('skill');
  323. expect(names).toEqual(expect.arrayContaining(['task_query', 'task_output', 'task_stop']));
  324. for (const hidden of [
  325. 'write',
  326. 'edit',
  327. 'bash',
  328. 'grep',
  329. 'glob',
  330. 'todowrite',
  331. 'web_fetch',
  332. 'mavis',
  333. 'website_deploy',
  334. 'workspace_semantic_search',
  335. 'task',
  336. 'task_append',
  337. ]) {
  338. expect(names).not.toContain(hidden);
  339. }
  340. } finally {
  341. await rm(dataDir, { recursive: true, force: true });
  342. }
  343. });
  344. it('removes Mavis-only guidance from task schema when Mavis is not available', async () => {
  345. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-capability-tools-'));
  346. try {
  347. const { nativeTools: tools } = await buildLocalTurnToolSources({
  348. toolsDisabled: false,
  349. workspaceRoot: process.cwd(),
  350. agentName: 'mavis',
  351. dataDir,
  352. eventWriter: new LocalEventSink(),
  353. sessionId: 'task-without-mavis-session',
  354. mcpService: new LocalMcpService(() => dataDir),
  355. threadGoal: { runtimeToolsFor: () => [] } as never,
  356. emitBusEvent: () => {},
  357. builtinCapabilities: resolveAgentCapabilities({
  358. tools: ['read'],
  359. features: { mavis: false, delegation: true },
  360. }),
  361. taskAdapter: {} as never,
  362. });
  363. const task = tools.find((tool) => tool.def.name === 'task');
  364. expect(task).toBeDefined();
  365. const schema = task!.def.schema as {
  366. properties: { agent_name: { description: string } };
  367. };
  368. expect(schema.properties.agent_name.description).toContain(
  369. 'Use explore, worker, or verifier',
  370. );
  371. expect(schema.properties.agent_name.description).not.toContain('general');
  372. expect(schema.properties.agent_name.description).not.toContain('coder');
  373. expect(schema.properties.agent_name.description).toContain(
  374. 'For a known custom Agent, use its stable `requestRef`',
  375. );
  376. expect(schema.properties.agent_name.description).toContain('agent:<stable-name>');
  377. expect(schema.properties.agent_name.description).toContain(
  378. 'ordinary custom names use their raw stable name',
  379. );
  380. expect(schema.properties.agent_name.description).not.toMatch(/\bmavis\b/i);
  381. } finally {
  382. await rm(dataDir, { recursive: true, force: true });
  383. }
  384. });
  385. it('exposes the complete task family when delegation is enabled', async () => {
  386. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-delegation-tools-'));
  387. try {
  388. const { nativeTools: tools } = await buildLocalTurnToolSources({
  389. toolsDisabled: false,
  390. workspaceRoot: process.cwd(),
  391. agentName: 'mavis',
  392. dataDir,
  393. eventWriter: new LocalEventSink(),
  394. sessionId: 'delegation-enabled',
  395. mcpService: new LocalMcpService(() => dataDir),
  396. threadGoal: { runtimeToolsFor: () => [] } as never,
  397. emitBusEvent: () => {},
  398. builtinCapabilities: resolveAgentCapabilities({
  399. tools: ['bash', 'task_query', 'task_output', 'task_stop'],
  400. features: { mavis: false, delegation: true },
  401. }),
  402. taskAdapter: {} as never,
  403. taskControlAdapter: {} as never,
  404. taskAppendAdapter: {} as never,
  405. });
  406. const names = tools.map((tool) => tool.def.name);
  407. expect(names).toContain('bash');
  408. expect(names).toEqual(
  409. expect.arrayContaining(['task', 'task_append', 'task_query', 'task_output', 'task_stop']),
  410. );
  411. } finally {
  412. await rm(dataDir, { recursive: true, force: true });
  413. }
  414. });
  415. it('uses the turn reporter for todo event identity without reusing it as the message id', async () => {
  416. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-sources-'));
  417. const events: IRuntimeEvent[] = [];
  418. const nextEventId = vi.fn(() => 'evt_hosted-turn_todo_updated_39');
  419. const nextRuntimeSeq = vi.fn(() => 39);
  420. const runtimeToolsFor = vi.fn(async () => []);
  421. try {
  422. const sources = await buildLocalTurnToolSources({
  423. toolsDisabled: false,
  424. workspaceRoot: process.cwd(),
  425. agentName: 'mavis',
  426. dataDir,
  427. sessionId: 'hosted-session',
  428. mcpService: new LocalMcpService(() => dataDir),
  429. threadGoal: { runtimeToolsFor } as never,
  430. emitBusEvent: () => {},
  431. });
  432. const todo = sources.nativeTools.find((tool) => tool.def.name === 'todowrite');
  433. if (!todo) throw new Error('todowrite tool was not assembled');
  434. await todo.impl.execute(
  435. {
  436. sessionId: 'hosted-session',
  437. turnId: 'hosted-turn',
  438. agentName: 'mavis',
  439. eventWriter: {
  440. pushRuntime: async () => undefined,
  441. appendEvents: async () => {
  442. throw new Error('legacy writer must not own todo event identity');
  443. },
  444. },
  445. reporter: {
  446. nextEventId,
  447. nextRuntimeSeq,
  448. appendEvents: async (next) => {
  449. events.push(...next);
  450. },
  451. },
  452. },
  453. { todos: [{ content: 'wire host', status: 'in_progress' }] },
  454. );
  455. expect(events).toHaveLength(1);
  456. expect(events[0]).toMatchObject({
  457. event_id: 'evt_hosted-turn_todo_updated_39',
  458. runtime_seq: 39,
  459. });
  460. expect(nextEventId).toHaveBeenCalledWith('todo_updated');
  461. expect(nextRuntimeSeq).toHaveBeenCalledOnce();
  462. const event = events[0];
  463. if (!event) throw new Error('todo_updated event was not emitted');
  464. const streamResp = JSON.parse(event.payload.stream_resp ?? '{}') as {
  465. agent_message?: { msg_id?: string };
  466. };
  467. expect(streamResp.agent_message?.msg_id).toMatch(/^todo_/u);
  468. expect(streamResp.agent_message?.msg_id).not.toBe(event.event_id);
  469. expect(sources.mcpEntries).toEqual([]);
  470. expect(sources.threadGoalTools).toEqual([]);
  471. expect(runtimeToolsFor).toHaveBeenCalledWith(false, 'hosted-session');
  472. } finally {
  473. await rm(dataDir, { recursive: true, force: true });
  474. }
  475. });
  476. it('degrades todo event emission when the turn reporter is unavailable', async () => {
  477. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-sources-'));
  478. const emitBusEvent = vi.fn();
  479. try {
  480. const sources = await buildLocalTurnToolSources({
  481. toolsDisabled: false,
  482. workspaceRoot: process.cwd(),
  483. agentName: 'mavis',
  484. dataDir,
  485. sessionId: 'hosted-session',
  486. mcpService: new LocalMcpService(() => dataDir),
  487. threadGoal: { runtimeToolsFor: () => [] } as never,
  488. emitBusEvent,
  489. });
  490. const todo = sources.nativeTools.find((tool) => tool.def.name === 'todowrite');
  491. if (!todo) throw new Error('todowrite tool was not assembled');
  492. const result = await todo.impl.execute(
  493. {
  494. sessionId: 'hosted-session',
  495. turnId: 'hosted-turn',
  496. agentName: 'mavis',
  497. },
  498. { todos: [{ content: 'keep working', status: 'in_progress' }] },
  499. );
  500. expect(result.details).toMatchObject({ event_emitted: false });
  501. expect(emitBusEvent).toHaveBeenCalledWith(
  502. 'todo.event_emit_failed',
  503. expect.objectContaining({
  504. sessionId: 'hosted-session',
  505. turnId: 'hosted-turn',
  506. reason: 'turn_reporter_unavailable',
  507. }),
  508. );
  509. } finally {
  510. await rm(dataDir, { recursive: true, force: true });
  511. }
  512. });
  513. it('degrades a rejected todo event append even when failure diagnostics throw', async () => {
  514. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-sources-'));
  515. const emitBusEvent = vi.fn((type: string) => {
  516. if (type === 'todo.event_emit_failed') {
  517. throw new Error('diagnostic delivery unavailable');
  518. }
  519. });
  520. try {
  521. const sources = await buildLocalTurnToolSources({
  522. toolsDisabled: false,
  523. workspaceRoot: process.cwd(),
  524. agentName: 'mavis',
  525. dataDir,
  526. sessionId: 'hosted-session',
  527. mcpService: new LocalMcpService(() => dataDir),
  528. threadGoal: { runtimeToolsFor: () => [] } as never,
  529. emitBusEvent,
  530. });
  531. const todo = sources.nativeTools.find((tool) => tool.def.name === 'todowrite');
  532. if (!todo) throw new Error('todowrite tool was not assembled');
  533. const result = await todo.impl.execute(
  534. {
  535. sessionId: 'hosted-session',
  536. turnId: 'hosted-turn',
  537. agentName: 'mavis',
  538. reporter: {
  539. nextEventId: () => 'evt_hosted-turn_todo_updated_1',
  540. nextRuntimeSeq: () => 1,
  541. appendEvents: async () => {
  542. throw new Error('strict delivery rejected event');
  543. },
  544. },
  545. },
  546. { todos: [{ content: 'keep working', status: 'in_progress' }] },
  547. );
  548. expect(result.details).toMatchObject({ event_emitted: false });
  549. expect(emitBusEvent).toHaveBeenCalledWith(
  550. 'todo.event_emit_failed',
  551. expect.objectContaining({
  552. sessionId: 'hosted-session',
  553. turnId: 'hosted-turn',
  554. reason: 'strict delivery rejected event',
  555. }),
  556. );
  557. } finally {
  558. await rm(dataDir, { recursive: true, force: true });
  559. }
  560. });
  561. it('keeps task control tools available when nested task creation is disabled', async () => {
  562. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-tools-'));
  563. try {
  564. const { nativeTools: tools } = await buildLocalTurnToolSources({
  565. toolsDisabled: false,
  566. workspaceRoot: process.cwd(),
  567. agentName: 'mavis',
  568. dataDir,
  569. eventWriter: new LocalEventSink(),
  570. sessionId: 'task-session',
  571. mcpService: new LocalMcpService(() => dataDir),
  572. threadGoal: { runtimeToolsFor: () => [] } as never,
  573. emitBusEvent: () => {},
  574. enableTaskTool: false,
  575. taskAdapter: {} as never,
  576. taskAppendAdapter: {} as never,
  577. taskControlAdapter: {
  578. get: async () => undefined,
  579. list: async () => ({ items: [] }),
  580. readOutput: async () => ({ content: '', nextOffset: 0 }),
  581. stop: async () => undefined,
  582. },
  583. });
  584. const toolNames = tools.map((tool) => tool.def.name);
  585. expect(toolNames).toEqual(expect.arrayContaining(['bash']));
  586. expect(toolNames).not.toContain('task');
  587. // A task child may neither start nor continue a delegation, so the raw
  588. // v1 source never injects `task_append` there either. The read/control
  589. // handles stay and are removed later by the final catalog gate.
  590. expect(toolNames).not.toContain('task_append');
  591. expect(toolNames).toEqual(expect.arrayContaining(['task_query', 'task_output', 'task_stop']));
  592. } finally {
  593. await rm(dataDir, { recursive: true, force: true });
  594. }
  595. });
  596. it('includes todowrite for regular turns (default)', async () => {
  597. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-tools-'));
  598. try {
  599. const { nativeTools: tools } = await buildLocalTurnToolSources({
  600. toolsDisabled: false,
  601. workspaceRoot: process.cwd(),
  602. agentName: 'mavis',
  603. dataDir,
  604. eventWriter: new LocalEventSink(),
  605. sessionId: 'todo-default-session',
  606. mcpService: new LocalMcpService(() => dataDir),
  607. threadGoal: { runtimeToolsFor: () => [] } as never,
  608. emitBusEvent: () => {},
  609. });
  610. expect(tools.map((tool) => tool.def.name)).toContain('todowrite');
  611. } finally {
  612. await rm(dataDir, { recursive: true, force: true });
  613. }
  614. });
  615. it('drops todowrite for subagent turns (enableTodoWriteTool: false)', async () => {
  616. // Subagent turns run in hidden child sessions; their todowrite calls would
  617. // pollute the parent-facing task list stream, so the assembly gates it off
  618. // the same way enableTaskTool gates nested task creation.
  619. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-tools-'));
  620. try {
  621. const { nativeTools: tools } = await buildLocalTurnToolSources({
  622. toolsDisabled: false,
  623. workspaceRoot: process.cwd(),
  624. agentName: 'mavis',
  625. dataDir,
  626. eventWriter: new LocalEventSink(),
  627. sessionId: 'todo-gated-session',
  628. mcpService: new LocalMcpService(() => dataDir),
  629. threadGoal: { runtimeToolsFor: () => [] } as never,
  630. emitBusEvent: () => {},
  631. enableTodoWriteTool: false,
  632. });
  633. const toolNames = tools.map((tool) => tool.def.name);
  634. expect(toolNames).not.toContain('todowrite');
  635. expect(toolNames).toEqual(expect.arrayContaining(['bash', 'read'])); // siblings survive
  636. } finally {
  637. await rm(dataDir, { recursive: true, force: true });
  638. }
  639. });
  640. it('wires injected fetchImpl into the local web_fetch tool', async () => {
  641. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-tools-web-fetch-'));
  642. const fetchImpl = vi.fn(async () => {
  643. return new Response('hello from injected fetch', {
  644. status: 200,
  645. headers: { 'Content-Type': 'text/plain' },
  646. });
  647. });
  648. try {
  649. const { nativeTools: tools } = await buildLocalTurnToolSources({
  650. toolsDisabled: false,
  651. workspaceRoot: process.cwd(),
  652. agentName: 'mavis',
  653. dataDir,
  654. eventWriter: new LocalEventSink(),
  655. sessionId: 'web-fetch-session',
  656. mcpService: new LocalMcpService(() => dataDir),
  657. threadGoal: { runtimeToolsFor: () => [] } as never,
  658. emitBusEvent: () => {},
  659. fetchImpl: fetchImpl as unknown as typeof fetch,
  660. });
  661. const webFetch = tools.find((tool) => tool.def.name === 'web_fetch');
  662. expect(webFetch).toBeDefined();
  663. const result = await webFetch!.impl.execute(
  664. { sessionId: 'web-fetch-session', turnId: 'turn-web-fetch', agentName: 'mavis' },
  665. { url: 'https://example.test/page' },
  666. );
  667. expect(fetchImpl).toHaveBeenCalledTimes(1);
  668. expect(fetchImpl.mock.calls[0]?.[0]).toBe('https://example.test/page');
  669. expect(result.text).toContain('hello from injected fetch');
  670. } finally {
  671. await rm(dataDir, { recursive: true, force: true });
  672. }
  673. });
  674. it('wires the local mavis tool to agent, cron, session, and MCP adapters', async () => {
  675. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-tools-'));
  676. const cronCalls: unknown[] = [];
  677. const cronSessionCalls: unknown[] = [];
  678. const sessionCalls: unknown[] = [];
  679. const busEvents: unknown[] = [];
  680. try {
  681. const { nativeTools: tools } = await buildLocalTurnToolSources({
  682. toolsDisabled: false,
  683. workspaceRoot: process.cwd(),
  684. agentName: 'mavis',
  685. dataDir,
  686. eventWriter: new LocalEventSink(),
  687. sessionId: 'session-current',
  688. mcpService: new LocalMcpService(() => dataDir),
  689. threadGoal: { runtimeToolsFor: () => [] } as never,
  690. emitBusEvent: (type, payload) => busEvents.push({ type, payload }),
  691. mavisAgentAdapter: {
  692. listAgents: async () => ({ agents: [] }),
  693. createAgent: async () => ({ name: 'created' }),
  694. getAgent: async (req) => ({ agent: { name: req.name, displayName: req.name } }),
  695. updateAgent: async (req) => ({ success: true, agent: { name: req.name } }),
  696. deleteAgent: async () => ({ success: true }),
  697. },
  698. mavisCronAdapter: {
  699. listCrons: async (req) => {
  700. cronCalls.push(req);
  701. return { tasks: [{ cronId: 'cron-1', agentName: req.agentName }] };
  702. },
  703. getCron: async (req) => ({ task: { cronId: req.cronId } }),
  704. createCron: async (req) => ({ task: { cronId: 'created', cronName: req.cronName } }),
  705. updateCron: async (req) => ({ task: { cronId: req.cronId } }),
  706. deleteCron: async () => ({ success: true }),
  707. triggerCron: async () => ({ success: true }),
  708. listCronSessions: async (req) => {
  709. cronSessionCalls.push(req);
  710. return {
  711. sessions: [{ sessionId: 'sess-1', createdAt: 1700000000000 }],
  712. hasMore: true,
  713. nextCursor: 'sess-1',
  714. };
  715. },
  716. },
  717. mavisSessionAdapter: {
  718. listSessions: async () => ({ sessions: [] }),
  719. getSession: async (req) => ({
  720. session: { sessionId: req.sessionId, agentName: 'mavis' },
  721. }),
  722. updateSession: async (req) => ({ success: true, session: { sessionId: req.sessionId } }),
  723. deleteSession: async () => ({ success: true }),
  724. listMessages: async (req) => {
  725. sessionCalls.push(req);
  726. return { messages: [{ content: 'ok' }] };
  727. },
  728. },
  729. });
  730. const mavis = tools.find((tool) => tool.def.name === 'mavis');
  731. expect(mavis).toBeDefined();
  732. const cronResult = await mavis!.impl.execute(
  733. { sessionId: 'session-current', turnId: 'turn-1', agentName: 'mavis' },
  734. { command: 'cron list', args: { agent_name: 'me', limit: 1 } },
  735. );
  736. expect(JSON.parse(cronResult.text)).toMatchObject({
  737. ok: true,
  738. command: 'cron list',
  739. response: { tasks: [{ cronId: 'cron-1', agentName: 'mavis' }] },
  740. });
  741. expect(cronCalls).toEqual([{ agentName: 'mavis', limit: 1 }]);
  742. const cronSessionsResult = await mavis!.impl.execute(
  743. { sessionId: 'session-current', turnId: 'turn-1', agentName: 'mavis' },
  744. {
  745. command: 'cron sessions',
  746. args: { cron_id: 'cron-1', cursor: 'sess-0', limit: 1 },
  747. },
  748. );
  749. expect(JSON.parse(cronSessionsResult.text)).toMatchObject({
  750. ok: true,
  751. command: 'cron sessions',
  752. response: {
  753. sessions: [{ sessionId: 'sess-1', createdAt: 1700000000000 }],
  754. hasMore: true,
  755. nextCursor: 'sess-1',
  756. },
  757. });
  758. expect(cronSessionCalls).toEqual([{ cronId: 'cron-1', cursor: 'sess-0', limit: 1 }]);
  759. const sessionResult = await mavis!.impl.execute(
  760. { sessionId: 'session-current', turnId: 'turn-1', agentName: 'mavis' },
  761. { command: 'session messages', args: { session_id: 'me' } },
  762. );
  763. expect(JSON.parse(sessionResult.text)).toMatchObject({
  764. ok: true,
  765. command: 'session messages',
  766. response: { messages: [{ content: 'ok' }] },
  767. });
  768. expect(sessionCalls).toEqual([{ sessionId: 'session-current' }]);
  769. const mcpResult = await mavis!.impl.execute(
  770. { sessionId: 'session-current', turnId: 'turn-1', agentName: 'mavis' },
  771. {
  772. command: 'mcp create',
  773. args: { name: 'docs', transport: 'stdio', command: 'npx', enabled: false },
  774. },
  775. );
  776. expect(JSON.parse(mcpResult.text)).toMatchObject({
  777. ok: true,
  778. command: 'mcp create',
  779. response: { server: { name: 'docs', enabled: false } },
  780. });
  781. expect(busEvents).toContainEqual({
  782. type: 'mcp.settings.changed',
  783. payload: { operation: 'create', name: 'docs' },
  784. });
  785. } finally {
  786. await rm(dataDir, { recursive: true, force: true });
  787. }
  788. });
  789. it('blocks a disabled built-in Skill from known-name reads without hiding other Skills', async () => {
  790. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-disabled-skill-'));
  791. try {
  792. initSkillService({
  793. configGetter: () => ({ dataDir, defaultModel: 'test/model' }),
  794. skillRegistryRoots: [
  795. {
  796. id: 'builtin-disabled-skill-test',
  797. kind: 'builtin',
  798. rootPath: join(packageRoot, 'assets/skills'),
  799. },
  800. ],
  801. });
  802. const commonInput = {
  803. toolsDisabled: false,
  804. workspaceRoot: process.cwd(),
  805. agentName: 'mavis',
  806. dataDir,
  807. eventWriter: new LocalEventSink(),
  808. sessionId: 'disabled-skill-session',
  809. mcpService: new LocalMcpService(() => dataDir),
  810. threadGoal: { runtimeToolsFor: () => [] } as never,
  811. emitBusEvent: () => {},
  812. };
  813. const { nativeTools: unrestrictedTools } = await buildLocalTurnToolSources(commonInput);
  814. const unrestrictedSkill = unrestrictedTools.find((tool) => tool.def.name === 'skill');
  815. const context = {
  816. sessionId: 'disabled-skill-session',
  817. turnId: 'turn-skill',
  818. agentName: 'mavis',
  819. };
  820. const available = await unrestrictedSkill!.impl.execute(context, { name: 'lark-tools' });
  821. expect(available.text).toContain('# Feishu / Lark Tools');
  822. const { nativeTools: restrictedTools } = await buildLocalTurnToolSources({
  823. ...commonInput,
  824. disabledBuiltinSkillNames: ['lark-tools'],
  825. });
  826. const restrictedSkill = restrictedTools.find((tool) => tool.def.name === 'skill');
  827. const blocked = await restrictedSkill!.impl.execute(context, { name: 'lark-tools' });
  828. const unrelated = await restrictedSkill!.impl.execute(context, { name: 'skill-creator' });
  829. expect(blocked.text).toBe('Local skill not found: lark-tools');
  830. expect(unrelated.text).toContain('name: skill-creator');
  831. } finally {
  832. await rm(dataDir, { recursive: true, force: true });
  833. }
  834. });
  835. it('does not read a recreated Agent private skill through a frozen model tool', async () => {
  836. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-frozen-private-'));
  837. try {
  838. const root = join(dataDir, 'agents', 'deleted-agent', 'skills', 'private-skill');
  839. await mkdir(root, { recursive: true });
  840. await writeFile(
  841. join(root, 'SKILL.md'),
  842. '---\nname: private-skill\ndescription: Private skill\n---\nRECREATED AGENT',
  843. );
  844. const resolveAgentReadScope = vi.fn(async () => {
  845. throw new Error('Unexpected live Agent lookup');
  846. });
  847. initSkillService({
  848. configGetter: () => ({ dataDir, defaultModel: 'test/model' }),
  849. resolveAgentReadScope,
  850. });
  851. const { nativeTools } = await buildLocalTurnToolSources({
  852. toolsDisabled: false,
  853. workspaceRoot: dataDir,
  854. agentName: 'deleted-agent',
  855. dataDir,
  856. sessionId: 'frozen-private-session',
  857. skipAgentResolution: true,
  858. expectedAgentInstanceId: '1a28d970-1f50-488b-84c5-df039713632a',
  859. mcpService: new LocalMcpService(() => dataDir),
  860. threadGoal: { runtimeToolsFor: () => [] } as never,
  861. emitBusEvent: () => {},
  862. });
  863. const skill = nativeTools.find((tool) => tool.def.name === 'skill');
  864. const context = {
  865. sessionId: 'frozen-private-session',
  866. turnId: 'turn-2',
  867. agentName: 'deleted-agent',
  868. };
  869. const marker = join(dataDir, 'agents', 'deleted-agent', '.agent-instance-id');
  870. await writeFile(marker, '1a28d970-1f50-488b-84c5-df039713632a');
  871. expect((await skill!.impl.execute(context, { name: 'private-skill' })).text).toContain(
  872. 'RECREATED AGENT',
  873. );
  874. await writeFile(marker, '2a28d970-1f50-488b-84c5-df039713632a');
  875. const result = await skill!.impl.execute(context, { name: 'private-skill' });
  876. expect(result.text).toBe('Local skill not found: private-skill');
  877. expect(resolveAgentReadScope).not.toHaveBeenCalled();
  878. } finally {
  879. await rm(dataDir, { recursive: true, force: true });
  880. }
  881. });
  882. it('blocks a Skill known from historical messages when the frozen selector closes it', async () => {
  883. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-frozen-skill-'));
  884. try {
  885. initSkillService({
  886. configGetter: () => ({ dataDir, defaultModel: 'test/model' }),
  887. skillRegistryRoots: [
  888. {
  889. id: 'builtin-frozen-skill-test',
  890. kind: 'builtin',
  891. rootPath: join(packageRoot, 'assets/skills'),
  892. },
  893. ],
  894. });
  895. const { nativeTools } = await buildLocalTurnToolSources({
  896. toolsDisabled: false,
  897. workspaceRoot: process.cwd(),
  898. agentName: 'mavis',
  899. dataDir,
  900. eventWriter: new LocalEventSink(),
  901. sessionId: 'frozen-skill-session',
  902. mcpService: new LocalMcpService(() => dataDir),
  903. threadGoal: { runtimeToolsFor: () => [] } as never,
  904. emitBusEvent: () => {},
  905. allowedSkillNames: [],
  906. allowedExtensionSkillNames: [],
  907. });
  908. const skill = nativeTools.find((tool) => tool.def.name === 'skill');
  909. const blocked = await skill!.impl.execute(
  910. { sessionId: 'frozen-skill-session', turnId: 'turn-2', agentName: 'mavis' },
  911. { name: 'lark-tools' },
  912. );
  913. expect(blocked.text).toBe('Local skill not found: lark-tools');
  914. expect(blocked.details).toMatchObject({ found: false });
  915. expect(blocked.text).not.toContain('SKILL.md');
  916. } finally {
  917. await rm(dataDir, { recursive: true, force: true });
  918. }
  919. });
  920. it('reads Plugin skill content from the capability view captured for this turn', async () => {
  921. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-tools-plugin-skill-'));
  922. try {
  923. initSkillService({
  924. configGetter: () => ({ dataDir, defaultModel: 'test/model' }),
  925. skillRegistryRoots: [],
  926. });
  927. const commonInput = {
  928. toolsDisabled: false,
  929. workspaceRoot: process.cwd(),
  930. agentName: 'mavis',
  931. dataDir,
  932. eventWriter: new LocalEventSink(),
  933. sessionId: 'plugin-skill-session',
  934. mcpService: new LocalMcpService(() => dataDir),
  935. threadGoal: { runtimeToolsFor: () => [] } as never,
  936. emitBusEvent: () => {},
  937. desktopCapabilities: {
  938. revision: 'plugin-r1',
  939. plugins: [{ name: 'notes', appProviders: [] }],
  940. skills: [
  941. {
  942. pluginName: 'notes',
  943. name: 'notes:plugin-notes',
  944. description: 'Plugin notes workflow',
  945. content: '# Captured Plugin notes body',
  946. location: join(dataDir, 'plugins', 'notes', 'skills', 'plugin-notes', 'SKILL.md'),
  947. sourceKind: 'desktop-plugin',
  948. },
  949. ],
  950. runtimeTools: [],
  951. runtimeToolBindings: [],
  952. },
  953. };
  954. const { nativeTools: blockedTools } = await buildLocalTurnToolSources({
  955. ...commonInput,
  956. allowedSkillNames: [],
  957. allowedExtensionSkillNames: ['notes:plugin-notes'],
  958. });
  959. const blockedSkill = blockedTools.find((tool) => tool.def.name === 'skill');
  960. const blocked = await blockedSkill!.impl.execute(
  961. { sessionId: 'plugin-skill-session', turnId: 'turn-1', agentName: 'mavis' },
  962. { name: 'notes:plugin-notes' },
  963. );
  964. expect(blocked.text).toBe('Local skill not found: notes:plugin-notes');
  965. const { nativeTools: tools } = await buildLocalTurnToolSources({
  966. ...commonInput,
  967. allowedSkillNames: [' NOTES:PLUGIN-NOTES '],
  968. allowedExtensionSkillNames: [' NOTES:PLUGIN-NOTES '],
  969. });
  970. const skill = tools.find((tool) => tool.def.name === 'skill');
  971. const loaded = await skill!.impl.execute(
  972. { sessionId: 'plugin-skill-session', turnId: 'turn-1', agentName: 'mavis' },
  973. { name: 'notes:plugin-notes' },
  974. );
  975. expect(loaded.text).toContain('# Captured Plugin notes body');
  976. expect(loaded.details).toMatchObject({
  977. found: true,
  978. source: 'desktop-plugin',
  979. });
  980. } finally {
  981. await rm(dataDir, { recursive: true, force: true });
  982. }
  983. });
  984. it('does not load the CU skill through the model skill tool when the turn snapshot is inactive', async () => {
  985. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-cu-skill-'));
  986. try {
  987. initSkillService({
  988. configGetter: () => ({
  989. dataDir,
  990. defaultModel: 'test/model',
  991. beta: { cuMode: true },
  992. }),
  993. skillRegistryRoots: [
  994. {
  995. id: 'builtin-cu-skill-test',
  996. kind: 'builtin',
  997. rootPath: join(packageRoot, 'assets/skills'),
  998. },
  999. ],
  1000. });
  1001. const commonInput = {
  1002. toolsDisabled: false,
  1003. workspaceRoot: process.cwd(),
  1004. agentName: 'mavis',
  1005. dataDir,
  1006. eventWriter: new LocalEventSink(),
  1007. sessionId: 'cu-skill-session',
  1008. mcpService: new LocalMcpService(() => dataDir),
  1009. threadGoal: { runtimeToolsFor: () => [] } as never,
  1010. emitBusEvent: () => {},
  1011. };
  1012. const { nativeTools: inactiveTools } = await buildLocalTurnToolSources({
  1013. ...commonInput,
  1014. cuModeActive: false,
  1015. });
  1016. const inactiveSkill = inactiveTools.find((tool) => tool.def.name === 'skill');
  1017. const blocked = await inactiveSkill!.impl.execute(
  1018. { sessionId: 'cu-skill-session', turnId: 'turn-skill-off', agentName: 'mavis' },
  1019. { name: 'cu-desktop' },
  1020. );
  1021. expect(blocked.text).toBe('Local skill not found: cu-desktop');
  1022. const { nativeTools: activeTools } = await buildLocalTurnToolSources({
  1023. ...commonInput,
  1024. cuModeActive: true,
  1025. });
  1026. const activeSkill = activeTools.find((tool) => tool.def.name === 'skill');
  1027. const loaded = await activeSkill!.impl.execute(
  1028. { sessionId: 'cu-skill-session', turnId: 'turn-skill-on', agentName: 'mavis' },
  1029. { name: 'cu-desktop' },
  1030. );
  1031. expect(loaded.text).toContain('# Computer Use — Desktop Operation Guide');
  1032. } finally {
  1033. await rm(dataDir, { recursive: true, force: true });
  1034. }
  1035. });
  1036. it('blocks direct skill reads when the owning capability is disabled', async () => {
  1037. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-owned-skills-'));
  1038. try {
  1039. initSkillService({
  1040. configGetter: () => ({
  1041. dataDir,
  1042. defaultModel: 'test/model',
  1043. }),
  1044. skillRegistryRoots: [
  1045. {
  1046. id: 'builtin-owned-skill-test',
  1047. kind: 'builtin',
  1048. rootPath: join(packageRoot, 'assets/skills'),
  1049. },
  1050. {
  1051. id: 'agent-owned-skill-test',
  1052. kind: 'builtin',
  1053. scope: 'mavis',
  1054. rootPath: join(packageRoot, '../local-runtime-v2/assets/agents/mavis/skills'),
  1055. },
  1056. ],
  1057. });
  1058. const { nativeTools: tools } = await buildLocalTurnToolSources({
  1059. toolsDisabled: false,
  1060. workspaceRoot: process.cwd(),
  1061. agentName: 'mavis',
  1062. dataDir,
  1063. eventWriter: new LocalEventSink(),
  1064. sessionId: 'owned-skill-session',
  1065. mcpService: new LocalMcpService(() => dataDir),
  1066. threadGoal: { runtimeToolsFor: () => [] } as never,
  1067. emitBusEvent: () => {},
  1068. builtinCapabilities: resolveAgentCapabilities({
  1069. tools: ['read', 'write'],
  1070. skills: ['visual-page'],
  1071. features: { mavis: false, delegation: false },
  1072. }),
  1073. memoryEnabled: false,
  1074. });
  1075. const skill = tools.find((tool) => tool.def.name === 'skill');
  1076. const context = {
  1077. sessionId: 'owned-skill-session',
  1078. turnId: 'owned-skill-turn',
  1079. agentName: 'mavis',
  1080. };
  1081. for (const name of ['mavis', 'create-agent', 'mavis-team']) {
  1082. const blocked = await skill!.impl.execute(context, { name });
  1083. expect(blocked.text).toBe(`Local skill not found: ${name}`);
  1084. }
  1085. const allowed = await skill!.impl.execute(context, { name: 'visual-page' });
  1086. expect(allowed.text).toContain('# Visual Page Skill');
  1087. } finally {
  1088. await rm(dataDir, { recursive: true, force: true });
  1089. }
  1090. });
  1091. it('keeps Mavis-owned skill reads when the Mavis feature owner is selected', async () => {
  1092. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-mavis-skills-'));
  1093. try {
  1094. initSkillService({
  1095. configGetter: () => ({
  1096. dataDir,
  1097. defaultModel: 'test/model',
  1098. }),
  1099. skillRegistryRoots: [
  1100. {
  1101. id: 'builtin-mavis-skill-test',
  1102. kind: 'builtin',
  1103. rootPath: await createSyntheticSkills(dataDir),
  1104. },
  1105. ],
  1106. });
  1107. const { nativeTools: tools } = await buildLocalTurnToolSources({
  1108. toolsDisabled: false,
  1109. workspaceRoot: process.cwd(),
  1110. agentName: 'mavis',
  1111. dataDir,
  1112. eventWriter: new LocalEventSink(),
  1113. sessionId: 'mavis-skill-session',
  1114. mcpService: new LocalMcpService(() => dataDir),
  1115. threadGoal: { runtimeToolsFor: () => [] } as never,
  1116. emitBusEvent: () => {},
  1117. builtinCapabilities: resolveAgentCapabilities({
  1118. tools: [],
  1119. skills: [],
  1120. features: { mavis: true, delegation: false },
  1121. }),
  1122. memoryEnabled: false,
  1123. });
  1124. const skill = tools.find((tool) => tool.def.name === 'skill');
  1125. const context = {
  1126. sessionId: 'mavis-skill-session',
  1127. turnId: 'mavis-skill-turn',
  1128. agentName: 'mavis',
  1129. };
  1130. const mavis = await skill!.impl.execute(context, { name: 'mavis' });
  1131. expect(mavis.text).toContain('# Mavis');
  1132. const createAgent = await skill!.impl.execute(context, { name: 'create-agent' });
  1133. expect(createAgent.text).toContain('# Create Agent');
  1134. expect(createAgent.text).toContain(
  1135. 'Only proceed after the user explicitly asks for or approves creating an agent.',
  1136. );
  1137. } finally {
  1138. await rm(dataDir, { recursive: true, force: true });
  1139. }
  1140. });
  1141. it('reads miniapp-creator through the generic Skill allowlist only when Host lifecycle is available', async () => {
  1142. const dataDir = await mkdtemp(join(tmpdir(), 'local-native-miniapp-skill-'));
  1143. try {
  1144. initSkillService({
  1145. configGetter: () => ({ dataDir, defaultModel: 'test/model' }),
  1146. skillRegistryRoots: [
  1147. {
  1148. id: 'builtin-miniapp-skill-read-test',
  1149. kind: 'builtin',
  1150. rootPath: await createSyntheticSkills(dataDir),
  1151. },
  1152. ],
  1153. });
  1154. const buildSkill = async (miniappAvailable: boolean) => {
  1155. const sessionId = `miniapp-skill-${miniappAvailable ? 'available' : 'unavailable'}`;
  1156. const { nativeTools } = await buildLocalTurnToolSources({
  1157. toolsDisabled: false,
  1158. workspaceRoot: process.cwd(),
  1159. agentName: 'mavis',
  1160. dataDir,
  1161. eventWriter: new LocalEventSink(),
  1162. sessionId,
  1163. mcpService: new LocalMcpService(() => dataDir),
  1164. threadGoal: { runtimeToolsFor: () => [] } as never,
  1165. emitBusEvent: () => {},
  1166. builtinCapabilities: resolveAgentCapabilities({
  1167. tools: ['read', 'write', 'edit', 'bash'],
  1168. skills: [],
  1169. features: { mavis: false, delegation: false, webSearch: false },
  1170. }),
  1171. ...(miniappAvailable ? { miniappAvailable: true } : {}),
  1172. memoryEnabled: false,
  1173. });
  1174. return { sessionId, skill: nativeTools.find((tool) => tool.def.name === 'skill')! };
  1175. };
  1176. const available = await buildSkill(true);
  1177. const availableResult = await available.skill.impl.execute(
  1178. {
  1179. sessionId: available.sessionId,
  1180. turnId: 'miniapp-skill-available-turn',
  1181. agentName: 'mavis',
  1182. },
  1183. { name: 'miniapp-creator' },
  1184. );
  1185. expect(availableResult.text).toContain('# Mini App Creator');
  1186. const unavailable = await buildSkill(false);
  1187. const unavailableResult = await unavailable.skill.impl.execute(
  1188. {
  1189. sessionId: unavailable.sessionId,
  1190. turnId: 'miniapp-skill-unavailable-turn',
  1191. agentName: 'mavis',
  1192. },
  1193. { name: 'miniapp-creator' },
  1194. );
  1195. expect(unavailableResult.text).toBe('Local skill not found: miniapp-creator');
  1196. } finally {
  1197. await rm(dataDir, { recursive: true, force: true });
  1198. }
  1199. });
  1200. });
  1201. // Exercise generic skill ownership with synthetic assets; desktop-only builtins
  1202. // are deliberately absent from the standalone distribution.
  1203. async function createSyntheticSkills(dataDir: string): Promise<string> {
  1204. const root = join(dataDir, 'fixture-skills');
  1205. for (const [name, title] of [['mavis', 'Mavis'], ['create-agent', 'Create Agent'], ['miniapp-creator', 'Mini App Creator']]) {
  1206. const dir = join(root, name!);
  1207. await mkdir(dir, { recursive: true });
  1208. await writeFile(join(dir, 'SKILL.md'), `---\nname: ${name}\ndescription: Synthetic test skill.\n---\n# ${title}\nOnly proceed after the user explicitly asks for or approves creating an agent.\n`);
  1209. }
  1210. return root;
  1211. }