makaron-cli 0.17.0 → 0.18.0

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 (146) hide show
  1. package/.claude-plugin/plugin.json +2 -2
  2. package/.codex-plugin/plugin.json +5 -4
  3. package/README.md +47 -1
  4. package/bin/makaron.mjs +22 -8
  5. package/craft/manifest.json +2877 -0
  6. package/craft/prompts/agent-coding.md +220 -0
  7. package/craft/prompts/agent.md +86 -0
  8. package/craft/prompts/animate.md +448 -0
  9. package/craft/prompts/audio.md +261 -0
  10. package/craft/prompts/captions.md +220 -0
  11. package/craft/prompts/coding-submission.md +31 -0
  12. package/craft/prompts/coding-workflow.md +26 -0
  13. package/craft/prompts/creative.md +108 -0
  14. package/craft/prompts/cutout.md +81 -0
  15. package/craft/prompts/enhance.md +123 -0
  16. package/craft/prompts/generate_image_tool.md +26 -0
  17. package/craft/prompts/image.md +222 -0
  18. package/craft/prompts/legacy/agent.md +123 -0
  19. package/craft/prompts/legacy/coding-tool.md +31 -0
  20. package/craft/prompts/legacy/video-tool.md +38 -0
  21. package/craft/prompts/legacy/workspace-authoring.md +13 -0
  22. package/craft/prompts/niji.md +117 -0
  23. package/craft/prompts/pony_translate.md +42 -0
  24. package/craft/prompts/remotion-composition.md +405 -0
  25. package/craft/prompts/video-reverse.md +170 -0
  26. package/craft/prompts/video-submission.md +44 -0
  27. package/craft/prompts/video-workflow.md +42 -0
  28. package/craft/prompts/wai_translate.md +28 -0
  29. package/craft/prompts/web-search.md +1 -0
  30. package/craft/prompts/wild.md +119 -0
  31. package/craft/prompts/workspace-authoring.md +13 -0
  32. package/craft/skills/SKILL_README.md +249 -0
  33. package/craft/skills/_shared/aesthetic-lens-contract.md +68 -0
  34. package/craft/skills/_shared/native-audiovisual.md +44 -0
  35. package/craft/skills/_shared/remotion-director-contract.md +133 -0
  36. package/craft/skills/_shared/remotion-video-director/README.md +140 -0
  37. package/craft/skills/_shared/remotion-video-director/SKILL.md +391 -0
  38. package/craft/skills/_shared/remotion-video-director/references/component-library.md +608 -0
  39. package/craft/skills/_shared/remotion-video-director/references/expert-definitions.md +214 -0
  40. package/craft/skills/_shared/remotion-video-director/references/music-and-audio.md +186 -0
  41. package/craft/skills/_shared/remotion-video-director/references/remotion-patterns.md +439 -0
  42. package/craft/skills/_shared/remotion-video-director/references/video-archetypes.md +395 -0
  43. package/craft/skills/_shared/speech-clock.md +63 -0
  44. package/craft/skills/_shared/spoken-caption.md +75 -0
  45. package/craft/skills/_shared/studio-production/audio-direction.md +60 -0
  46. package/craft/skills/_shared/studio-production/production-contract.md +188 -0
  47. package/craft/skills/_shared/studio-production/reference-analysis.md +37 -0
  48. package/craft/skills/_shared/studio-production/review-contract.md +77 -0
  49. package/craft/skills/_shared/studio-production/taste-direction.md +114 -0
  50. package/craft/skills/_shared/visual-asset-bridge/SKILL.md +57 -0
  51. package/craft/skills/_shared/visual-direction/SKILL.md +98 -0
  52. package/craft/skills/_shared/voice-translation.md +55 -0
  53. package/craft/skills/aesthetic-disney-character-motion/SKILL.md +66 -0
  54. package/craft/skills/aesthetic-lottiefiles-motion/SKILL.md +78 -0
  55. package/craft/skills/aesthetic-rampstack-direction/SKILL.md +68 -0
  56. package/craft/skills/ai-video-gen/SKILL.md +48 -0
  57. package/craft/skills/animated-explainer/SKILL.md +53 -0
  58. package/craft/skills/animation/SKILL.md +53 -0
  59. package/craft/skills/avatar-spokesperson/SKILL.md +66 -0
  60. package/craft/skills/canvas-procedural-animation/SKILL.md +48 -0
  61. package/craft/skills/character-animation/SKILL.md +57 -0
  62. package/craft/skills/character-animation-qa/SKILL.md +48 -0
  63. package/craft/skills/character-rigging/SKILL.md +48 -0
  64. package/craft/skills/cinematic/SKILL.md +53 -0
  65. package/craft/skills/cinematic-video/SKILL.md +65 -0
  66. package/craft/skills/clip-factory/SKILL.md +53 -0
  67. package/craft/skills/comfyui/SKILL.md +48 -0
  68. package/craft/skills/content-repurpose/SKILL.md +54 -0
  69. package/craft/skills/create-video/SKILL.md +48 -0
  70. package/craft/skills/documentary-montage/SKILL.md +53 -0
  71. package/craft/skills/doubao-tts/SKILL.md +51 -0
  72. package/craft/skills/explainer-aesthetic-disney/SKILL.md +33 -0
  73. package/craft/skills/explainer-aesthetic-lottiefiles/SKILL.md +33 -0
  74. package/craft/skills/explainer-aesthetic-rampstack/SKILL.md +33 -0
  75. package/craft/skills/explainer-video/SKILL.md +423 -0
  76. package/craft/skills/ffmpeg/SKILL.md +48 -0
  77. package/craft/skills/grok-media/SKILL.md +47 -0
  78. package/craft/skills/hybrid/SKILL.md +53 -0
  79. package/craft/skills/localization-dub/SKILL.md +59 -0
  80. package/craft/skills/long-video-anchor/SKILL.md +111 -0
  81. package/craft/skills/long-video-director/SKILL.md +217 -0
  82. package/craft/skills/long-video-storyboard/SKILL.md +102 -0
  83. package/craft/skills/makaron-mascot/SKILL.md +83 -0
  84. package/craft/skills/makaron-mascot/assets/character-sheet.jpg +0 -0
  85. package/craft/skills/makaron-mascot/assets/makaron-spark-pixel-wizard-concepts.png +0 -0
  86. package/craft/skills/media-use/SKILL.md +47 -0
  87. package/craft/skills/motion-design-video/SKILL.md +64 -0
  88. package/craft/skills/motion-graphics/SKILL.md +48 -0
  89. package/craft/skills/multi-angle-video/SKILL.md +533 -0
  90. package/craft/skills/music/SKILL.md +47 -0
  91. package/craft/skills/music-to-video/SKILL.md +60 -0
  92. package/craft/skills/photo-to-video/SKILL.md +60 -0
  93. package/craft/skills/podcast-repurpose/SKILL.md +53 -0
  94. package/craft/skills/pose-library-design/SKILL.md +48 -0
  95. package/craft/skills/reference-video-studio/SKILL.md +55 -0
  96. package/craft/skills/remotion/SKILL.md +48 -0
  97. package/craft/skills/remotion-best-practices/SKILL.md +48 -0
  98. package/craft/skills/screen-demo/SKILL.md +61 -0
  99. package/craft/skills/seedance-2-0/SKILL.md +48 -0
  100. package/craft/skills/seedance-2-5/SKILL.md +48 -0
  101. package/craft/skills/sound-effects/SKILL.md +47 -0
  102. package/craft/skills/source-video-studio/SKILL.md +68 -0
  103. package/craft/skills/speech-to-text/SKILL.md +47 -0
  104. package/craft/skills/sticker-maker/SKILL.md +178 -0
  105. package/craft/skills/svg-character-animation/SKILL.md +48 -0
  106. package/craft/skills/synthetic-screen-recording/SKILL.md +48 -0
  107. package/craft/skills/talking-head/SKILL.md +106 -0
  108. package/craft/skills/text-to-speech/SKILL.md +50 -0
  109. package/craft/skills/threejs-animation/SKILL.md +48 -0
  110. package/craft/skills/threejs-fundamentals/SKILL.md +48 -0
  111. package/craft/skills/threejs-geometry/SKILL.md +48 -0
  112. package/craft/skills/threejs-lighting/SKILL.md +48 -0
  113. package/craft/skills/threejs-materials/SKILL.md +48 -0
  114. package/craft/skills/threejs-shaders/SKILL.md +48 -0
  115. package/craft/skills/threejs-textures/SKILL.md +48 -0
  116. package/craft/skills/tiktok-video/SKILL.md +188 -0
  117. package/craft/skills/tiktok-video/references/audio-sync.md +58 -0
  118. package/craft/skills/tiktok-video/references/caption-direction.md +36 -0
  119. package/craft/skills/tiktok-video/references/delivery-qa.md +84 -0
  120. package/craft/skills/tiktok-video/references/platform-layout.md +62 -0
  121. package/craft/skills/video-edit/SKILL.md +144 -0
  122. package/craft/skills/video-edit/references/direct-reference-route.md +141 -0
  123. package/craft/skills/video-edit/references/editing-protocol.md +79 -0
  124. package/craft/skills/video-edit/references/frame-location.md +85 -0
  125. package/craft/skills/video-edit/references/replication-protocol.md +67 -0
  126. package/craft/skills/video-edit/references/shot-blueprint.md +116 -0
  127. package/craft/skills/video-edit/references/shot-blueprint.schema.json +143 -0
  128. package/craft/skills/video-edit/references/similarity-qa.md +47 -0
  129. package/craft/skills/video-edit/scripts/extract-shot-blueprint.mjs +313 -0
  130. package/craft/skills/video-ffmpeg-lab/SKILL.md +220 -0
  131. package/craft/skills/video-mature-themes/SKILL.md +175 -0
  132. package/craft/skills/video-segment-edit/SKILL.md +16 -0
  133. package/craft/skills/video-translate/SKILL.md +148 -0
  134. package/craft/skills/video-understand/SKILL.md +48 -0
  135. package/craft/skills/visual-style/SKILL.md +47 -0
  136. package/craft/skills/wan-3-0/SKILL.md +59 -0
  137. package/craft/skills/web-design-guidelines/SKILL.md +47 -0
  138. package/craft/skills/website-to-video/SKILL.md +61 -0
  139. package/craft-source.json +7 -0
  140. package/package.json +12 -5
  141. package/runtime/adapter.mjs +615 -0
  142. package/runtime/configure.mjs +28 -0
  143. package/runtime/tool-catalog.json +807 -0
  144. package/runtime/tool-cli.mjs +98 -0
  145. package/skills/makaron/SKILL.md +12 -0
  146. package/skills/makaron-native/SKILL.md +89 -0
@@ -0,0 +1,615 @@
1
+ import { readFile, writeFile, mkdir, lstat, rename, readdir, rm, realpath } from 'node:fs/promises';
2
+ import { readFileSync, lstatSync, existsSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import { createHash } from 'node:crypto';
6
+
7
+ // OpenClaw's synchronous Jiti plugin loader cannot evaluate top-level await.
8
+ const catalog = JSON.parse(readFileSync(new URL('./tool-catalog.json', import.meta.url), 'utf8'));
9
+ const readonlyRemote = new Set(['makaron_get_video_status', 'makaron_get_music_status']);
10
+ const paidHelpers = new Set(['makaron_service_submit', 'makaron_design_export']);
11
+ const hash = value => createHash('sha256').update(value).digest('hex');
12
+ const stable = value => JSON.stringify(value, (_, v) => v && typeof v === 'object' && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a.localeCompare(b))) : v);
13
+ const str = description => ({ type: 'string', minLength: 1, description });
14
+ const uuid = { type: 'string', pattern: '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$' };
15
+ const requestId = str('Caller-chosen stable identifier for this exact authorized submission. Reuse only to inspect/replay its receipt. Changed arguments require a new explicitly authorized submission. Unknown outcomes never auto-resubmit.');
16
+ const schema = (properties, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
17
+ const helper = (name, description, properties, required) => ({ name, description, inputSchema: schema(properties, required) });
18
+
19
+ const nativePaid = new Set(['generate_image', 'generate_animation', 'analyze_image', 'analyze_video', 'transcribe_audio', 'prepare_visual_asset', 'preview_frame', 'materialize_media', 'rotate_camera', 'run_code', 'generate_audio']);
20
+ const nativeQueues = new Map();
21
+ const helpers = [
22
+ helper('makaron_craft', 'Read bundled Makaron professional Skills, prompts and dependencies on demand. Omit path for the 72-Skill index. Paths are bundle-relative (skills/... or prompts/...), never local/backend file paths. Canonical tool names in these documents are names for makaron_native_tool; use live native tools/list schemas. Numeric Media List aliases are absent. Binary image assets return native image content.', { path: str('Exact bundle-relative path from the index or a previously read guide.') }, []),
23
+ helper('makaron_native_run', 'HOST-NATIVE project facade; no Makaron planner is started. tools reads live canonical schemas; start binds an owned project to a stable sessionKey; status refreshes the SAME run/context/operations and async media; finish records completed/aborted only after final outputs are ready. Publish the QA-approved editable draft with publish_draft before final export/finish; a run-scoped draft alone is not cross-run editable continuation. Native backend must be configured by the operator. Source file paths and snapshot IDs replace Media List. Every mutation requires a stable client_request_id.', { action: { type: 'string', enum: ['tools', 'start', 'status', 'finish'] }, projectId: uuid, runId: uuid, sessionKey: str('Stable host session identity for this logical creative run.'), objective: str('Authorized creative objective.'), status: { type:'string',enum:['completed','aborted'] }, summary: {type:'string',maxLength:20000}, client_request_id: requestId }, ['action','projectId']),
24
+ helper('makaron_native_tool', 'Execute ONE canonical project capability in the host-owned creative loop. Read makaron_native_run(action=tools) first for current tool names, schemas and semantics. name is the canonical name (run_code, preview_frame, materialize_media, etc.); arguments uses its current schema. Uses durable server operations plus account-scoped local receipts; stable client_request_id required, no automatic retry after unknown outcomes. Explicit sourceSnapshotId/referenceSnapshotIds/sourceDesignPath are bound in native-files mode; positional indices and legacy markers are rejected. For composition code_path in the verified legacy Preview, write a pure JS body returning {type:render,code:JSX-string,width,height,props,animation}; outer JSX/import modules are not yet compatible. run_code renders/validates code written by this host; it never delegates planning to /api/agent/run. Download only final/preview outputs, and keep source internally unless requested.', { projectId:uuid, runId:uuid, name:str('Canonical live project tool name.'), arguments:{type:'object',description:'Arguments matching the exact schema returned by native tools/list.'}, sourceSnapshotId:uuid, referenceSnapshotIds:{type:'array',items:uuid,maxItems:20}, sourceDesignPath:str('Explicit saved project composition JSON path returned by an earlier tool.'), client_request_id:requestId }, ['projectId','runId','name','arguments','client_request_id']),
25
+ helper('makaron_account', 'Read the authenticated Makaron account credit balance and subscription. No generation. Credentials are read privately from environment or auth file; never put a key in tool arguments.', {}, []),
26
+ helper('makaron_discover', 'Read the live 12-tool HTTP MCP catalog and schemas. This adapter exposes those atomic tools plus local/project/service helpers. Live schemas govern provider/model limits; this is not the full App tool factory.', {}, []),
27
+ helper('makaron_upload_source', 'Upload one explicitly provided local image/video/audio to the authenticated account via signed storage upload. Returns public URL, source SHA256, byte size and MIME. No generation. Local paths are not remote URLs. Do not upload unrelated private files.', { path: str('Absolute source file path, or a path within configured workspace.'), projectId: uuid }, ['path']),
28
+ helper('makaron_project', 'Create/list/read owned persistent Makaron projects. Newly created projects are set private and owner-read verified before success. Existing projects keep their original sharing policy. status returns stable snapshot IDs, URLs, design paths and task metadata without Media List/index aliases. create/import are local-receipted mutations, not a creative Agent run. import adds one explicit image/video/audio to an existing owner-verified project and returns its canonical identity for native source binding.', { action: { type: 'string', enum: ['create', 'list', 'status', 'import'] }, projectId: uuid, title: str('Project title'), client_request_id: requestId, imageUrls: { type: 'array', items: str('Explicit public image URL') }, videoUrls: { type: 'array', items: str('Explicit public video URL') }, sourcePath: str('Explicit local source for import; supply one of sourcePath/url.'), url: str('Explicit HTTPS source URL for import; remote imports also require mediaType.'), mediaType: {type:'string',enum:['image','video','audio']}, duration:{type:'number',exclusiveMinimum:0} }, ['action']),
29
+ helper('makaron_service_submit', 'SERVICE MODE: submit an authorized brief to the existing Makaron project Agent. Makaron performs the planning/tool loop (not native host design tools). Returns runId immediately; poll only that run. Existing active project runs may append this input. Do not resubmit on timeout/unknown. For design, request editable dynamic composition, preview and saved project; export is separate.', { client_request_id: requestId, projectId: uuid, prompt: str('Original authorized creative brief including duration, editable title and acceptance criteria.'), agentModel: str('Optional explicit current Makaron Agent model; omit for service default.'), sourceSnapshotIds: { type: 'array', items: uuid, description: 'Explicit existing project source snapshot IDs for this request only.' } }, ['client_request_id', 'projectId', 'prompt']),
30
+ helper('makaron_service_status', 'Read the SAME existing service run status, progress, outputs and authoritative credit usage. No new creative run/export. completed is project readiness, not local/native delivery; download returned outputs separately. Failed/aborted/unknown never authorize automatic resubmission.', { runId: uuid }, ['runId']),
31
+ helper('makaron_design_export', 'Export an existing owned editable design once to MP4/image through Makaron Remotion. This is service mode, not host-native run_code. Supply exactly one of snapshotId, designPath or design. Returns jobId; poll the same job, then download the completed URL. Do not export a second job after timeout.', { client_request_id: requestId, projectId: uuid, snapshotId: uuid, designPath: str('Exact owned project workspace design JSON path returned by project/service status.'), design: { type: 'object', description: 'Explicit composition JSON supported by the service; prefer an already saved design.' }, outputType: { type: 'string', enum: ['video', 'image'] }, renderProfile: { type: 'string', enum: ['source', 'fast_720p'] }, publish: { type: 'boolean' }, name: str('Artifact name') }, ['client_request_id', 'projectId']),
32
+ helper('makaron_design_export_status', 'Read the SAME existing export job; returns status, progress, media URL or failure. No rendering resubmission. A completed URL must be downloaded/checked before claiming local delivery.', { jobId: uuid }, ['jobId']),
33
+ helper('makaron_download_artifact', 'Download an explicit final public media URL to configured persistent workspace. Returns actual absolute artifactPath, SHA256, MIME and byte size; images also return native image content. No API credential is sent to the media host. This is download evidence, not quality/decode verification.', { url: str('Public HTTPS final media URL from a successful tool/service/job result.'), filename: str('Optional leaf filename; no directory separators. Extension follows actual MIME if omitted.') }, ['url']),
34
+ helper('makaron_receipt', 'Inspect a local submission receipt by stable client_request_id. Returned receipts can replay the same result without a new paid call. pending/unknown receipts require existing-task status or human decision; never automatically re-submit. Receipts do not replace server billing truth.', { client_request_id: requestId }, ['client_request_id']),
35
+ ];
36
+
37
+ function decorate(tool) {
38
+ const result = structuredClone(tool);
39
+ if (!readonlyRemote.has(tool.name)) {
40
+ result.inputSchema.properties.client_request_id = requestId;
41
+ result.inputSchema.required = [...new Set([...(result.inputSchema.required || []), 'client_request_id'])];
42
+ result.description += '\nLocal adapter: client_request_id is required and removed before remote invocation. Unknown outcomes are not retried. Explicit local source paths are uploaded privately before the atomic call; taskId/URLs and artifactPath are delivery handles. No project Media List is injected.';
43
+ }
44
+ result.inputSchema.additionalProperties = false;
45
+ return result;
46
+ }
47
+ export const bundledTools = Object.freeze([...catalog.tools.map(decorate), ...helpers]);
48
+
49
+ class AdapterError extends Error {
50
+ constructor(code, message, details) { super(message); this.code = code; this.details = details; }
51
+ }
52
+ function fail(code, message, details) { throw new AdapterError(code, message, details); }
53
+ function result(value, extra = {}) { return { content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value, ...extra }; }
54
+ function clean(value, key, field = '') {
55
+ if (/^(authorization|api.?key|token|uploadUrl|signedUrl|headers|cookie)$/i.test(field)) return '[redacted]';
56
+ if (typeof value === 'string') {
57
+ let text = key ? value.split(key).join('[redacted]') : value;
58
+ text = text.replace(/mk_live_[A-Za-z0-9_-]+/g, '[redacted]').replace(/([?&](?:token|signature|X-Amz-[^= &]+)=)[^&\s]+/gi, '$1[redacted]');
59
+ return text;
60
+ }
61
+ if (Array.isArray(value)) return value.map(v => clean(v, key));
62
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, clean(v, key, k)]));
63
+ return value;
64
+ }
65
+ function validate(value, def, label = 'arguments') {
66
+ if (def.anyOf) {
67
+ if (!def.anyOf.some(s => { try { validate(value, s, label); return true; } catch { return false; } })) fail('INVALID_ARGUMENTS', `${label} does not match the tool schema`);
68
+ return;
69
+ }
70
+ if ('const' in def && value !== def.const) fail('INVALID_ARGUMENTS', `${label} has an invalid value`);
71
+ if (def.enum && !def.enum.includes(value)) fail('INVALID_ARGUMENTS', `${label} has an invalid enum value`);
72
+ const types = Array.isArray(def.type) ? def.type : def.type ? [def.type] : [];
73
+ const actual = value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value === 'number' && Number.isInteger(value) ? 'integer' : typeof value;
74
+ if (types.length && !types.includes(actual) && !(actual === 'integer' && types.includes('number'))) fail('INVALID_ARGUMENTS', `${label} has the wrong type`);
75
+ if (typeof value === 'string') {
76
+ if (def.minLength && value.length < def.minLength || def.maxLength && value.length > def.maxLength || def.pattern && !new RegExp(def.pattern).test(value)) fail('INVALID_ARGUMENTS', `${label} is invalid`);
77
+ }
78
+ if (typeof value === 'number' && (!Number.isFinite(value) || def.minimum != null && value < def.minimum || def.maximum != null && value > def.maximum || typeof def.exclusiveMinimum === 'number' && value <= def.exclusiveMinimum)) fail('INVALID_ARGUMENTS', `${label} is outside the allowed range`);
79
+ if (Array.isArray(value)) {
80
+ if (def.maxItems != null && value.length > def.maxItems) fail('INVALID_ARGUMENTS', `${label} has too many items`);
81
+ if (def.items) value.forEach((v, i) => validate(v, def.items, `${label}[${i}]`));
82
+ } else if (value && typeof value === 'object') {
83
+ for (const k of def.required || []) if (!(k in value)) fail('INVALID_ARGUMENTS', `${label}.${k} is required`);
84
+ for (const [k, v] of Object.entries(value)) {
85
+ if (def.properties?.[k]) validate(v, def.properties[k], `${label}.${k}`);
86
+ else if (def.additionalProperties === false) fail('INVALID_ARGUMENTS', `${label} contains an unsupported field`);
87
+ }
88
+ }
89
+ }
90
+ function safeUrl(raw, { local = false } = {}) {
91
+ let url; try { url = new URL(raw); } catch { fail('INVALID_URL', 'An absolute public HTTPS URL is required'); }
92
+ if (url.username || url.password || !(url.protocol === 'https:' || local && url.protocol === 'http:')) fail('INVALID_URL', 'An HTTPS URL without embedded credentials is required');
93
+ if (!local && (/^(localhost|.*\.localhost|.*\.local)$/i.test(url.hostname) || /^127\.|^10\.|^192\.168\.|^169\.254\.|^172\.(1[6-9]|2\d|3[01])\./.test(url.hostname) || url.hostname.includes(':'))) fail('INVALID_URL', 'Local/private network media URLs are not accepted');
94
+ return url;
95
+ }
96
+ function uuidFrom(value) { const h = hash(value); return `${h.slice(0, 8)}-${h.slice(8, 12)}-5${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`; }
97
+ const signedMediaUrl = raw => /[?&](?:token|signature|sig|X-Amz-[^= &]+)=/i.test(raw);
98
+ function returnedTaskId(text) {
99
+ // Provider summaries may mention "Task ID: id." inline before the canonical standalone line.
100
+ const lines = [...text.matchAll(/^[ \t]*Task ID:[ \t]*(\S+)[ \t]*$/gim)];
101
+ const raw = lines.at(-1)?.[1] || /Task ID:[ \t]*([^\s]+)/i.exec(text)?.[1];
102
+ return raw?.replace(/[.,;:!?,。;:!?]+$/u, '');
103
+ }
104
+ function creditHeaders(headers) {
105
+ const billing = {};
106
+ for (const [header, field] of [['x-credits-charged', 'creditsCharged'], ['x-credits-remaining', 'creditsRemaining']]) {
107
+ const raw = headers.get(header);
108
+ if (raw !== null && /^\d+(?:\.\d+)?$/.test(raw.trim()) && Number.isFinite(Number(raw))) billing[field] = Number(raw);
109
+ }
110
+ return Object.keys(billing).length ? billing : undefined;
111
+ }
112
+ function mimeOf(bytes) {
113
+ if (bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]))) return ['image/png', 'png'];
114
+ if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return ['image/jpeg', 'jpg'];
115
+ if (bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP') return ['image/webp', 'webp'];
116
+ if (bytes.toString('ascii', 4, 8) === 'ftyp') return ['video/mp4', 'mp4'];
117
+ if (bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WAVE') return ['audio/wav', 'wav'];
118
+ if (bytes.toString('ascii', 0, 4) === 'OggS') return ['audio/ogg', 'ogg'];
119
+ if (bytes.toString('ascii', 0, 3) === 'ID3' || bytes[0] === 255 && (bytes[1] & 224) === 224) return ['audio/mpeg', 'mp3'];
120
+ if (bytes.toString('ascii', 0, 4) === 'fLaC') return ['audio/flac', 'flac'];
121
+ return null;
122
+ }
123
+ async function privateDir(dir) {
124
+ await mkdir(dir, { recursive: true, mode: 0o700 });
125
+ const stat = await lstat(dir);
126
+ if (!stat.isDirectory() || stat.isSymbolicLink()) fail('UNSAFE_DIRECTORY', 'The adapter data directory must be a regular directory');
127
+ return realpath(dir);
128
+ }
129
+ async function atomicJson(file, value) {
130
+ const tmp = `${file}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`;
131
+ await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
132
+ await rename(tmp, file);
133
+ }
134
+ function stripMediaAliases(value) {
135
+ if (Array.isArray(value)) return value.map(stripMediaAliases);
136
+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).filter(([k, v]) => !/^(index|ref|media_index|mediaIndex|currentSnapshotIndex|selectedMediaIndex)$/.test(k) && !(k === 'id' && typeof v === 'string' && /^media_\d+$/.test(v))).map(([k, v]) => [k, stripMediaAliases(v)]));
137
+ return value;
138
+ }
139
+
140
+ export function createAdapter(options = {}) {
141
+ const env = options.env || process.env;
142
+ const clientName = options.clientName || 'makaron-creative-plugin/0.3.0';
143
+ if (!/^[a-zA-Z0-9._/-]{1,100}$/.test(clientName)) fail('CLIENT_INVALID', 'Invalid client identity');
144
+ const fetchImpl = options.fetchImpl || globalThis.fetch;
145
+ const dataRoot = env.PLUGIN_DATA ? path.resolve(env.PLUGIN_DATA) : path.join(os.homedir(), '.makaron', 'plugin');
146
+ const workspaceDir = path.resolve(options.workspaceDir || env.MAKARON_WORKSPACE || path.join(dataRoot, 'artifacts'));
147
+ const stateDir = path.resolve(options.stateDir || env.MAKARON_STATE_DIR || path.join(dataRoot, 'receipts'));
148
+ const authFile = options.authFile || env.MAKARON_AUTH_FILE || path.join(os.homedir(), '.makaron', 'auth.json');
149
+ if (!path.isAbsolute(authFile)) fail('AUTH_FILE_INVALID', 'MAKARON_AUTH_FILE must be absolute');
150
+ const allowLocalHttp = options.allowLocalHttp === true; // test fixtures only; never an Agent tool argument
151
+ const base = safeUrl(env.MAKARON_URL || 'https://www.makaron.app', { local: allowLocalHttp });
152
+ if (base.pathname !== '/' || base.search || base.hash) fail('ENDPOINT_INVALID', 'MAKARON_URL must be an origin, without a path or query');
153
+ const origin = base.origin;
154
+ const connectionFile = env.MAKARON_CONNECTION_FILE || path.resolve(stateDir, '../connection.json');
155
+ let connection = {};
156
+ if (existsSync(connectionFile)) {
157
+ const stat = lstatSync(connectionFile);
158
+ if (!stat.isFile() || stat.isSymbolicLink()) fail('CONNECTION_INVALID', 'Plugin connection profile must be a regular file');
159
+ connection = JSON.parse(readFileSync(connectionFile, 'utf8'));
160
+ }
161
+ const facade = safeUrl(env.MAKARON_HARNESS_ENDPOINT || connection.harnessEndpoint || `${origin}/api/harness`, { local: allowLocalHttp });
162
+ if (facade.search || facade.hash || facade.pathname !== '/api/harness') fail('ENDPOINT_INVALID', 'Native endpoint must end in /api/harness without a query');
163
+ const nativeEndpoint = facade.href;
164
+ const craftRoot = path.resolve(options.craftRoot || new URL('../craft/', import.meta.url).pathname);
165
+ const requestTimeoutMs = options.requestTimeoutMs || 180000;
166
+ const maxArtifactBytes = options.maxArtifactBytes || 250 * 1024 * 1024;
167
+ let key, scope, defs = bundledTools;
168
+ async function auth() {
169
+ if (key) return key;
170
+ let candidate = env.MAKARON_API_KEY;
171
+ if (!candidate) {
172
+ try {
173
+ const stat = await lstat(authFile);
174
+ if (!stat.isFile() || stat.isSymbolicLink()) fail('AUTH_FILE_INVALID', 'Auth file must be a regular private file');
175
+ candidate = JSON.parse(await readFile(authFile, 'utf8'))._apiKey;
176
+ } catch (error) {
177
+ if (error instanceof AdapterError) throw error;
178
+ fail('AUTH_MISSING', 'Set MAKARON_API_KEY or authenticate Makaron CLI; no credential was loaded');
179
+ }
180
+ }
181
+ if (typeof candidate !== 'string' || !/^mk_live_[A-Za-z0-9_-]+$/.test(candidate.trim())) fail('AUTH_INVALID', 'A per-user Makaron mk_live API key is required');
182
+ key = candidate.trim(); scope = hash(`${origin}\n${key}`).slice(0, 32); return key;
183
+ }
184
+ async function request(url, init = {}, { signal, authenticated = true, limit = 32 * 1024 * 1024, allowMediaRedirect = false } = {}) {
185
+ const activeKey = authenticated ? await auth() : undefined;
186
+ const timeout = AbortSignal.timeout(requestTimeoutMs);
187
+ const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
188
+ let response, currentUrl = url;
189
+ if (allowMediaRedirect && (authenticated || init.method && init.method !== 'GET' || init.headers?.Authorization)) fail('CONFIG_INVALID', 'Only unauthenticated media GET may follow redirects');
190
+ for (let redirectCount = 0; ; redirectCount++) {
191
+ try {
192
+ response = await fetchImpl(currentUrl, { ...init, redirect: allowMediaRedirect ? 'manual' : 'error', signal: combined, headers: { ...(authenticated ? { Authorization: `Bearer ${activeKey}`, 'X-Makaron-Client': clientName } : {}), ...init.headers } });
193
+ } catch { fail('NETWORK_UNKNOWN', 'The request did not return a reliable response; inspect the existing receipt/task before any new submission'); }
194
+ if (!allowMediaRedirect || ![301, 302, 303, 307, 308].includes(response.status)) break;
195
+ await response.body?.cancel();
196
+ if (redirectCount >= 4) fail('MEDIA_REDIRECT_LIMIT', 'Media download exceeded the safe redirect limit');
197
+ const location = response.headers.get('location');
198
+ if (!location) fail('MEDIA_REDIRECT_INVALID', 'Media redirect has no destination');
199
+ currentUrl = safeUrl(new URL(location, currentUrl).href, { local: allowLocalHttp }).href;
200
+ }
201
+ const announced = Number(response.headers.get('content-length'));
202
+ if (announced > limit) { await response.body?.cancel(); fail('RESPONSE_TOO_LARGE', 'The response exceeds the configured byte limit'); }
203
+ const chunks = []; let size = 0;
204
+ if (response.body) for await (const chunk of response.body) { size += chunk.byteLength; if (size > limit) { await response.body.cancel().catch(() => {}); fail('RESPONSE_TOO_LARGE', 'The response exceeds the configured byte limit'); } chunks.push(Buffer.from(chunk)); }
205
+ const bytes = Buffer.concat(chunks);
206
+ return { response, bytes };
207
+ }
208
+ async function jsonRequest(route, body, signal, method) {
209
+ const { response, bytes } = await request(`${origin}${route}`, { method: method || (body === undefined ? 'GET' : 'POST'), ...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) }, { signal });
210
+ let data; try { data = JSON.parse(bytes.toString('utf8')); } catch { fail('INVALID_RESPONSE', 'Makaron returned an unreadable response'); }
211
+ if (!response.ok) fail('REMOTE_REJECTED', `Makaron returned HTTP ${response.status}`, { httpStatus: response.status, response: clean(data, key) });
212
+ return data;
213
+ }
214
+ async function rpc(method, params, signal) {
215
+ const { response, bytes } = await request(`${origin}/api/mcp`, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) }, { signal });
216
+ let data; const text = bytes.toString('utf8');
217
+ try { data = JSON.parse(text); } catch {
218
+ for (const block of text.split(/\r?\n\r?\n/)) { const lines = block.split(/\r?\n/).filter(l => l.startsWith('data:')).map(l => l.slice(5).trim()).join('\n'); try { const candidate = JSON.parse(lines); if (candidate.id === 1) data = candidate; } catch {} }
219
+ }
220
+ const billing = creditHeaders(response.headers);
221
+ if (!response.ok) fail('REMOTE_REJECTED', `Makaron MCP returned HTTP ${response.status}`, { httpStatus: response.status, response: clean(data || {}, key), ...(billing ? { billing } : {}) });
222
+ if (!data || data.id !== 1) fail('INVALID_RESPONSE', 'Makaron MCP returned no matching JSON-RPC response');
223
+ if (data.error) fail('REMOTE_RPC_ERROR', 'Makaron rejected the tool request', { response: clean(data.error, key), ...(billing ? { billing } : {}) });
224
+ return method === 'tools/call' && billing ? { ...data.result, structuredContent: { ...(data.result?.structuredContent || {}), billing } } : data.result;
225
+ }
226
+ async function receiptPath(id) { await auth(); const dir = await privateDir(stateDir); return path.join(dir, `${scope}-${hash(id)}.json`); }
227
+ async function loadReceipt(id) { const file = await receiptPath(id); try { const stat = await lstat(file); if (!stat.isFile() || stat.isSymbolicLink()) fail('RECEIPT_UNSAFE', 'Receipt is not a regular file'); return JSON.parse(await readFile(file, 'utf8')); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } }
228
+ async function restoreImages(value) {
229
+ const output = await materializeNativePreview(structuredClone(value));
230
+ for (const item of output.content || []) if (item.type === 'image' && item._artifact) {
231
+ const bytes = await readFile(item._artifact.artifactPath);
232
+ if (hash(bytes) !== item._artifact.sha256) fail('ARTIFACT_CHANGED', 'Cached artifact no longer matches its saved SHA256');
233
+ item.data = bytes.toString('base64'); delete item._artifact;
234
+ }
235
+ // Old receipts retain their original bytes; canonicalize this known parsing error only on replay.
236
+ const taskId = returnedTaskId((output.content || []).filter(c => c.type === 'text').map(c => c.text).join('\n'));
237
+ if (taskId && taskId !== 'n/a') output.structuredContent = { ...(output.structuredContent || {}), taskId };
238
+ const native = output.structuredContent?.mode === 'host-native' && output.structuredContent?.output;
239
+ if (native && (native.success === false || typeof native.error === 'string' && native.error.length > 0)) output.isError = true;
240
+ return output;
241
+ }
242
+ function journalResult(value) {
243
+ const output = structuredClone(value);
244
+ for (const item of output.content || []) if (item.type === 'image') {
245
+ const artifact = output.structuredContent?.artifacts?.find(a => a.sha256 === hash(Buffer.from(item.data || '', 'base64')));
246
+ if (artifact) { delete item.data; item._artifact = artifact; }
247
+ }
248
+ return output;
249
+ }
250
+ async function once(name, args, paid, execute) {
251
+ const id = args.client_request_id;
252
+ if (typeof id !== 'string' || !id.trim() || id.length > 200) fail('REQUEST_ID_REQUIRED', 'A stable client_request_id (1–200 characters) is required');
253
+ const file = await receiptPath(id), requestHash = hash(stable({ name, args, ...(name.startsWith('makaron_native_') ? { nativeEndpoint } : {}) }));
254
+ const previous = await loadReceipt(id);
255
+ if (previous) {
256
+ if (previous.requestHash !== requestHash) fail('REQUEST_ID_CONFLICT', 'This client_request_id already belongs to different arguments');
257
+ if (previous.response) return restoreImages(previous.response);
258
+ fail('SUBMISSION_UNKNOWN', 'This submission was already reserved. Inspect its receipt/existing task; no automatic retry is permitted', { client_request_id: id, state: previous.state });
259
+ }
260
+ const guard = path.join(stateDir, `${scope}.lock`);
261
+ try { await mkdir(guard, { mode: 0o700 }); } catch (e) { if (e.code === 'EEXIST') fail('STATE_BUSY', 'Another submission is reserving a receipt; no remote call was made'); throw e; }
262
+ let entry;
263
+ try {
264
+ if (paid && String(env.MAKARON_ALLOW_PAID_TOOLS ?? '1') === '0') fail('PAID_TOOLS_DISABLED', 'Paid media/planning/export calls are disabled by the host');
265
+ const capRaw = env.MAKARON_MAX_PAID_CALLS;
266
+ if (capRaw !== undefined && (!/^\d+$/.test(String(capRaw)) || !Number.isSafeInteger(Number(capRaw)))) fail('CONFIG_INVALID', 'MAKARON_MAX_PAID_CALLS must be a nonnegative integer');
267
+ if (paid && capRaw !== undefined) {
268
+ let count = 0;
269
+ for (const filename of await readdir(stateDir)) if (filename.startsWith(`${scope}-`) && filename.endsWith('.json')) { const item = JSON.parse(await readFile(path.join(stateDir, filename), 'utf8')); if (item.paid) count++; }
270
+ if (count >= Number(capRaw)) fail('PAID_CALL_LIMIT', 'The cumulative paid submission attempt limit has been reached; do not retry', { paidAttempts: count, maxPaidCalls: Number(capRaw) });
271
+ }
272
+ entry = { schemaVersion: 1, endpoint: origin, authScope: scope, client_request_id: id, tool: name, requestHash, paid, state: 'pending', createdAt: new Date().toISOString() };
273
+ try { await writeFile(file, `${JSON.stringify(entry, null, 2)}\n`, { mode: 0o600, flag: 'wx' }); } catch (e) { if (e.code === 'EEXIST') fail('SUBMISSION_UNKNOWN', 'This submission was concurrently reserved; inspect its receipt'); throw e; }
274
+ } finally { await rm(guard, { recursive: true, force: true }); }
275
+ try {
276
+ const output = clean(await execute(), key);
277
+ entry.state = 'returned'; entry.response = journalResult(output); entry.updatedAt = new Date().toISOString();
278
+ if (output.structuredContent?.billing) entry.billing = output.structuredContent.billing;
279
+ await atomicJson(file, entry);
280
+ return output;
281
+ } catch (error) {
282
+ entry.state = ['REMOTE_REJECTED', 'REMOTE_RPC_ERROR', 'INVALID_ARGUMENTS', 'SOURCE_INVALID', 'SOURCE_TOO_LARGE', 'SOURCE_SYMLINK'].includes(error.code) ? 'rejected' : 'unknown';
283
+ entry.error = { code: error.code || 'INTERNAL_ERROR', message: error instanceof AdapterError ? clean(error.message, key) : 'The submission did not produce a reliable saved response' };
284
+ if (error.details?.billing) entry.billing = error.details.billing;
285
+ entry.updatedAt = new Date().toISOString(); await atomicJson(file, entry); throw error;
286
+ }
287
+ }
288
+ async function saveArtifact(bytes, declaredMime, filename) {
289
+ if (!bytes.length || bytes.length > maxArtifactBytes) fail('ARTIFACT_SIZE_INVALID', 'Artifact is empty or exceeds the configured size limit');
290
+ const detected = mimeOf(bytes);
291
+ const mimeType = detected?.[0] || (typeof declaredMime === 'string' && /^(image|video|audio)\//.test(declaredMime) ? declaredMime.split(';')[0] : 'application/octet-stream');
292
+ const extension = detected?.[1] || ({ 'audio/ogg': 'ogg', 'image/png': 'png', 'video/mp4': 'mp4' }[mimeType] || 'bin');
293
+ const digest = hash(bytes), root = await privateDir(workspaceDir);
294
+ if (filename && (filename !== path.basename(filename) || filename === '.' || filename === '..' || /[\x00-\x1f]/.test(filename))) fail('ARTIFACT_PATH_INVALID', 'filename must be a plain leaf filename');
295
+ const artifactPath = path.join(root, filename || `${digest}.${extension}`);
296
+ try { const stat = await lstat(artifactPath); if (!stat.isFile() || stat.isSymbolicLink()) fail('ARTIFACT_PATH_INVALID', 'Artifact output must be a regular file'); if (hash(await readFile(artifactPath)) !== digest) fail('ARTIFACT_EXISTS', 'A different existing artifact has this filename; preserve it and use another name'); } catch (e) { if (e.code !== 'ENOENT') throw e; await writeFile(artifactPath, bytes, { flag: 'wx', mode: 0o600 }); }
297
+ return { artifactPath, path: artifactPath, sha256: digest, sizeBytes: bytes.length, mimeType };
298
+ }
299
+ async function upload(rawPath, projectId, signal) {
300
+ const sourcePath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(workspaceDir, rawPath);
301
+ if (!path.isAbsolute(rawPath) && !(sourcePath.startsWith(`${workspaceDir}${path.sep}`))) fail('SOURCE_INVALID', 'Relative source paths must stay within the configured workspace');
302
+ let stat; try { stat = await lstat(sourcePath); } catch { fail('SOURCE_INVALID', 'The explicitly supplied source file does not exist'); }
303
+ if (stat.isSymbolicLink()) fail('SOURCE_SYMLINK', 'Source must be an actual regular media file, not a symbolic link');
304
+ if (!stat.isFile() || !stat.size) fail('SOURCE_INVALID', 'Source must be a nonempty regular media file');
305
+ if (stat.size > 50 * 1024 * 1024) fail('SOURCE_TOO_LARGE', 'Local source exceeds the 50 MiB adapter upload limit');
306
+ const bytes = await readFile(sourcePath), detected = mimeOf(bytes);
307
+ if (!detected) fail('SOURCE_INVALID', 'Only recognized JPEG/PNG/WebP, MP4, WAV/MP3/OGG/FLAC media files can be uploaded');
308
+ const [mimeType, ext] = detected, digest = hash(bytes);
309
+ if (mimeType.startsWith('image/') && bytes.length > 10 * 1024 * 1024 || mimeType.startsWith('audio/') && bytes.length > 15 * 1024 * 1024) fail('SOURCE_TOO_LARGE', 'Image/audio exceeds the 10/15 MiB adapter source limit');
310
+ await auth(); const root = await privateDir(stateDir), cachePath = path.join(root, `${scope}-upload-${hash(`${projectId || ''}:${digest}`)}.json`);
311
+ try { const cached = JSON.parse(await readFile(cachePath, 'utf8')); if (cached.sha256 === digest) return cached; } catch (e) { if (e.code !== 'ENOENT') throw e; }
312
+ const signed = await jsonRequest('/api/storage/upload-url', { ...(projectId ? { projectId } : {}), filename: `${digest}.${ext}`, contentType: mimeType, ...(mimeType.startsWith('audio/') ? { uploadKind: 'audio' } : {}) }, signal);
313
+ safeUrl(signed.uploadUrl, { local: allowLocalHttp }); const publicUrl = safeUrl(signed.publicUrl, { local: allowLocalHttp }).href;
314
+ if (typeof signed.token !== 'string' || !signed.token) fail('INVALID_RESPONSE', 'Storage did not return a signed upload token');
315
+ const { response } = await request(signed.uploadUrl, { method: 'PUT', headers: { 'Content-Type': mimeType, Authorization: `Bearer ${signed.token}` }, body: bytes }, { signal, authenticated: false, limit: 1024 * 1024 });
316
+ if (!response.ok) fail('UPLOAD_FAILED', `Signed media upload returned HTTP ${response.status}`);
317
+ const output = { sourcePath: await realpath(sourcePath), url: publicUrl, publicUrl, sha256: digest, sizeBytes: bytes.length, mimeType };
318
+ await atomicJson(cachePath, output); return output;
319
+ }
320
+ async function normalizeSources(args, signal) {
321
+ const output = structuredClone(args);
322
+ const fields = ['image', 'referenceImages', 'images', 'video_url', 'videoUrl', 'videoUrls', 'audioUrls', 'audio_references', 'image_urls'];
323
+ async function one(value) { if (typeof value !== 'string') return value; if (path.isAbsolute(value) || value.startsWith('./') || value.startsWith('../')) return (await upload(value, undefined, signal)).url; return value; }
324
+ for (const field of fields) if (field in output) output[field] = Array.isArray(output[field]) ? await Promise.all(output[field].map(one)) : await one(output[field]);
325
+ return output;
326
+ }
327
+ async function download(url, filename, signal) {
328
+ const checked = safeUrl(url, { local: allowLocalHttp }).href;
329
+ const { response, bytes } = await request(checked, {}, { signal, authenticated: false, limit: maxArtifactBytes, allowMediaRedirect: true });
330
+ if (!response.ok) fail('DOWNLOAD_FAILED', `Media download returned HTTP ${response.status}`);
331
+ return { artifact: await saveArtifact(bytes, response.headers.get('content-type'), filename), bytes };
332
+ }
333
+ async function decorateResult(raw, signal) {
334
+ const output = structuredClone(raw || { content: [] });
335
+ if (!Array.isArray(output.content)) fail('INVALID_RESPONSE', 'Tool response contains no content array');
336
+ const artifacts = [];
337
+ for (const item of output.content) if (item.type === 'image' && typeof item.data === 'string') {
338
+ const bytes = Buffer.from(item.data, 'base64');
339
+ const detected = mimeOf(bytes);
340
+ if (!detected?.[0].startsWith('image/')) fail('ARTIFACT_INVALID', 'Tool returned an invalid image payload');
341
+ const artifact = await saveArtifact(bytes, item.mimeType); artifacts.push(artifact); item.mimeType = artifact.mimeType;
342
+ }
343
+ const text = output.content.filter(c => c.type === 'text').map(c => c.text).join('\n');
344
+ // Older analysis endpoints return this explicit failure without MCP isError.
345
+ if (/^Video analysis error:/i.test(text.trim())) {
346
+ output.isError = true;
347
+ output.structuredContent = { ...output.structuredContent, error: { code: 'REMOTE_ANALYSIS_FAILED', message: text } };
348
+ }
349
+ const taskId = returnedTaskId(text);
350
+ const urls = [...new Set([...text.matchAll(/^(?:Video|Audio|Image) URL:\s*(https?:\/\/[^\s]+)/gim)].map(m => m[1]))];
351
+ const publicUrls = [], deliveryErrors = [];
352
+ for (const url of urls) {
353
+ if (!signedMediaUrl(url)) { publicUrls.push(url); continue; }
354
+ try {
355
+ const { artifact, bytes } = await download(url, undefined, signal); artifacts.push(artifact);
356
+ for (const item of output.content) if (item.type === 'text') item.text = item.text.split(url).join(`[local artifact: ${artifact.artifactPath}]`);
357
+ if (artifact.mimeType.startsWith('image/')) output.content.push({ type: 'image', mimeType: artifact.mimeType, data: bytes.toString('base64') });
358
+ } catch (error) {
359
+ // Preserve the known returned task/result; delivery failure never authorizes another paid submit.
360
+ for (const item of output.content) if (item.type === 'text') item.text = item.text.split(url).join('[signed media download failed; recheck the same task]');
361
+ deliveryErrors.push({ code: error.code || 'DOWNLOAD_FAILED', message: error instanceof AdapterError ? error.message : 'The signed final media could not be downloaded' });
362
+ output.isError = true;
363
+ }
364
+ }
365
+ if (artifacts.length || publicUrls.length || taskId || deliveryErrors.length) output.structuredContent = { ...(output.structuredContent || {}), ...(artifacts.length ? { artifacts } : {}), ...(publicUrls.length ? { outputUrls: publicUrls } : {}), ...(taskId && taskId !== 'n/a' ? { taskId } : {}), ...(deliveryErrors.length ? { deliveryErrors } : {}) };
366
+ return output;
367
+ }
368
+ async function decorateExportStatus(raw, signal) {
369
+ const metadata = structuredClone(raw);
370
+ if (metadata.status !== 'completed') return result(metadata);
371
+ const signedUrls = [...new Set(['url', 'storageUrl', 'storage_url'].map(field => metadata[field]).filter(url => typeof url === 'string' && signedMediaUrl(url)))];
372
+ if (!signedUrls.length) return result(metadata);
373
+ // Signed capabilities remain request-local; the Agent receives usable files, never broken redacted URLs.
374
+ for (const field of ['url', 'storageUrl', 'storage_url']) if (signedUrls.includes(metadata[field])) delete metadata[field];
375
+ const artifacts = [], deliveryErrors = [];
376
+ for (const url of signedUrls) {
377
+ try {
378
+ const { artifact } = await download(url, undefined, signal);
379
+ if (!artifacts.some(existing => existing.sha256 === artifact.sha256)) artifacts.push(artifact);
380
+ } catch (error) {
381
+ deliveryErrors.push({ code: error.code || 'DOWNLOAD_FAILED', message: error instanceof AdapterError ? error.message : 'The completed export file could not be downloaded' });
382
+ }
383
+ }
384
+ return result({ ...metadata, ...(artifacts.length ? { artifacts, artifactPath: artifacts[0].artifactPath } : {}), ...(deliveryErrors.length ? { deliveryErrors, recovery: 'Recheck this same jobId; the export is already completed. Do not submit another export.' } : {}) }, deliveryErrors.length ? { isError: true } : {});
385
+ }
386
+ async function recordedAudioStatus(taskId) {
387
+ await auth();
388
+ const root = await privateDir(stateDir);
389
+ for (const filename of (await readdir(root)).sort()) {
390
+ // Only this account+endpoint scope is inspected; other-account receipts are never opened.
391
+ if (!filename.startsWith(`${scope}-`) || !filename.endsWith('.json')) continue;
392
+ const file = path.join(root, filename), stat = await lstat(file);
393
+ if (!stat.isFile() || stat.isSymbolicLink()) fail('RECEIPT_UNSAFE', 'A matching account receipt is not a regular file');
394
+ const entry = JSON.parse(await readFile(file, 'utf8'));
395
+ if (entry.authScope !== scope || entry.endpoint !== origin || entry.state !== 'returned' || !['makaron_create_music', 'makaron_create_audio'].includes(entry.tool) || !entry.response || entry.response.isError === true) continue;
396
+ const response = entry.response, text = (response.content || []).filter(c => c.type === 'text').map(c => c.text).join('\n');
397
+ if ((response.structuredContent?.taskId || returnedTaskId(text)) !== taskId) continue;
398
+ const outputUrls = [...new Set([...text.matchAll(/^[ \t]*Audio URL:[ \t]*(https:\/\/[^\s]+)/gim)].map(match => match[1]))];
399
+ for (const url of outputUrls) safeUrl(url);
400
+ const artifacts = [];
401
+ for (const artifact of response.structuredContent?.artifacts || []) {
402
+ if (!artifact.mimeType?.startsWith('audio/')) continue;
403
+ const actual = await lstat(artifact.artifactPath);
404
+ if (!actual.isFile() || actual.isSymbolicLink()) fail('ARTIFACT_CHANGED', 'Recorded audio artifact is no longer a regular file');
405
+ const bytes = await readFile(artifact.artifactPath);
406
+ if (hash(bytes) !== artifact.sha256 || bytes.length !== artifact.sizeBytes) fail('ARTIFACT_CHANGED', 'Recorded audio artifact no longer matches its saved SHA256/size');
407
+ artifacts.push(artifact);
408
+ }
409
+ if (!outputUrls.length && !artifacts.length) continue;
410
+ return result({ taskId, status: 'completed', source: 'recorded-generation-receipt', providerRechecked: false,
411
+ evidence: 'This account previously returned a final audio URL or a verified local audio artifact. This is durable recovery, not a new provider-status observation.',
412
+ client_request_id: entry.client_request_id, recordedAt: entry.updatedAt || entry.createdAt,
413
+ ...(outputUrls.length ? { outputUrls } : {}), ...(artifacts.length ? { artifacts } : {}),
414
+ ...(entry.billing ? { recordedGenerationBilling: entry.billing } : {}), billing: { creditsCharged: 0 },
415
+ });
416
+ }
417
+ return null;
418
+ }
419
+ async function nativeRpc(method, params, signal) {
420
+ const {response,bytes} = await request(nativeEndpoint,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({jsonrpc:'2.0',id:1,method,params})},{signal});
421
+ let data;try{data=JSON.parse(bytes.toString('utf8'));}catch{fail('NATIVE_UNAVAILABLE', 'The native project facade is unavailable. Configure a verified Makaron /api/harness endpoint; no service Agent was started.',{httpStatus:response.status});}
422
+ if (!response.ok || data.error) fail('NATIVE_REJECTED','Native project capability returned a structured failure. Inspect this same run and operation before recovery.',{httpStatus:response.status,response:data.error});
423
+ if(data.jsonrpc!=='2.0'||data.id!==1||!data.result)fail('INVALID_RESPONSE','Native facade returned no matching result');
424
+ return stripMediaAliases(data.result);
425
+ }
426
+ const nativeCompatibility = new Map();
427
+ async function ensureNative(args, signal) {
428
+ const binding = `${args.projectId}:${args.runId}`;
429
+ if (!nativeCompatibility.has(binding)) nativeCompatibility.set(binding, (async()=>{
430
+ try {
431
+ await nativeRpc('tools/call',{projectId:args.projectId,runId:args.runId,name:'__makaron_native_files_preflight__',arguments:{},idempotencyKey:'native-files-readonly-preflight',sourceBindings:{mode:'native-files'}},signal);
432
+ fail('NATIVE_CONTRACT_MISMATCH','Native facade accepted an unknown capability; no creative operation was submitted');
433
+ } catch(error) {
434
+ if(error.code === 'NATIVE_REJECTED' && error.details?.response?.data?.code === 'tool_not_found')return;
435
+ fail('NATIVE_CONTRACT_MISMATCH','Native-files compatibility could not be verified. No creative operation was submitted. Inspect the configured endpoint and this same run.',{nativeEndpoint,cause:error.details || {code:error.code}});
436
+ }
437
+ })());
438
+ return nativeCompatibility.get(binding);
439
+ }
440
+ async function materializeNativePreview(output) {
441
+ const value=output.structuredContent;
442
+ if(!value || value.mode!=='host-native')return output;
443
+ const candidates=[];
444
+ if(typeof value.output?.base64Data==='string')candidates.push(Buffer.from(value.output.base64Data,'base64'));
445
+ for(const block of Array.isArray(value.modelOutput?.value)?value.modelOutput.value:[]) {
446
+ if(!/^(image-data|file)$/.test(block.type)||!/^image\//.test(block.mediaType||block.mimeType||''))continue;
447
+ if(typeof block.data==='string')candidates.push(Buffer.from(block.data,'base64'));
448
+ else if(Array.isArray(block.data?.data))candidates.push(Buffer.from(block.data.data));
449
+ }
450
+ for(const bytes of candidates) {
451
+ if(!mimeOf(bytes)?.[0].startsWith('image/'))continue;
452
+ const artifact=await saveArtifact(bytes,mimeOf(bytes)[0]);
453
+ value.artifacts||=[];
454
+ if(value.artifacts.some(a=>a.sha256===artifact.sha256))continue;
455
+ value.artifacts.push(artifact);output.content.push({type:'image',data:bytes.toString('base64'),mimeType:artifact.mimeType});
456
+ }
457
+ if(value.artifacts?.length && candidates.length) {
458
+ if(value.output)delete value.output.base64Data;
459
+ if(value.modelOutput)value.modelOutput={type:'json',value:{artifacts:value.artifacts,text:(Array.isArray(value.modelOutput.value)?value.modelOutput.value:[]).filter(b=>b.type==='text').map(b=>b.text)}};
460
+ output.content=output.content.filter(b=>b.type!=='text');output.content.unshift({type:'text',text:JSON.stringify(value)});
461
+ }
462
+ return output;
463
+ }
464
+ async function nativeTool(args, signal) {
465
+ if (['media_index','media_indices','reference_media_indices','media_refs','image_media_index'].some(k=>k in args.arguments) || /<<<(?:media|image|video|audio)_/.test(JSON.stringify(args.arguments))) fail('INVALID_ARGUMENTS','Use explicit snapshot IDs, URLs or sourceDesignPath, not Media List aliases');
466
+ const queueKey = `${scope}:${nativeEndpoint}:${args.projectId}:${args.runId}`;
467
+ const preceding = nativeQueues.get(queueKey) || Promise.resolve();
468
+ const promise = preceding.catch(()=>{}).then(async()=>{
469
+ const sourceBindings={mode:'native-files',...Object.fromEntries(['sourceSnapshotId','referenceSnapshotIds','sourceDesignPath'].filter(k=>args[k]!==undefined).map(k=>[k,args[k]]))};
470
+ const value=await nativeRpc('tools/call',{projectId:args.projectId,runId:args.runId,name:args.name,arguments:args.arguments,idempotencyKey:args.client_request_id,sourceBindings},signal);
471
+ const failed = value.operation?.status === 'failed' || value.output?.success === false || typeof value.output?.error === 'string' && value.output.error.length > 0;
472
+ const output=result({...value,mode:'host-native',nativeEndpoint}, failed ? {isError:true} : {});
473
+ await materializeNativePreview(output);
474
+ const terminal = value.output?.success !== false && !['failed','queued','processing','rendering','pending'].includes(value.output?.status);
475
+ if(terminal) for(const field of ['videoUrl','audioUrl','url','storageUrl','imageUrl']) {
476
+ const url=value.output?.[field];
477
+ if(typeof url!=='string'||!signedMediaUrl(url))continue;
478
+ try {
479
+ const {artifact,bytes}=await download(url,undefined,signal);
480
+ output.structuredContent.artifacts||=[];output.structuredContent.artifacts.push(artifact);
481
+ if(artifact.mimeType.startsWith('image/'))output.content.push({type:'image',mimeType:artifact.mimeType,data:bytes.toString('base64')});
482
+ delete output.structuredContent.output[field];
483
+ } catch(error) {output.structuredContent.deliveryErrors=[{code:error.code||'DOWNLOAD_FAILED',recovery:'Inspect this same run/job; never resubmit the completed operation.'}];}
484
+ }
485
+ output.content=output.content.filter(b=>b.type!=='text');output.content.unshift({type:'text',text:JSON.stringify(output.structuredContent)});
486
+ return output;
487
+ });
488
+ nativeQueues.set(queueKey,promise);
489
+ try{return await promise;}finally{if(nativeQueues.get(queueKey)===promise)nativeQueues.delete(queueKey);}
490
+ }
491
+ async function execute(name, args, signal) {
492
+ if (catalog.tools.some(t => t.name === name)) {
493
+ if (name === 'makaron_get_music_status') {
494
+ const recorded = await recordedAudioStatus(args.taskId);
495
+ if (recorded) return recorded;
496
+ }
497
+ const normalized = await normalizeSources(args, signal); delete normalized.client_request_id;
498
+ if (['makaron_create_video', 'makaron_edit_video', 'makaron_upscale_video'].includes(name)) normalized.billingRequestId ||= uuidFrom(`${scope}:${args.client_request_id}`);
499
+ if (name === 'makaron_retake_video') normalized.request_id ||= uuidFrom(`${scope}:${args.client_request_id}`);
500
+ return decorateResult(await rpc('tools/call', { name, arguments: normalized }, signal), signal);
501
+ }
502
+ switch (name) {
503
+ case 'makaron_craft': {
504
+ const manifest=JSON.parse(await readFile(path.join(craftRoot,'manifest.json'),'utf8'));
505
+ if(!args.path)return result({skillCount:manifest.skillCount,promptCount:manifest.promptCount,skills:manifest.skills,instructions:'Read the selected guide and its dependencies with makaron_craft. Canonical tool tokens refer to makaron_native_tool(name=token, arguments=...), not legacy global tools. Use only explicit snapshot IDs, URLs or sourceDesignPath returned by owned project tools. App planner agent.md is source reference, not host system instructions.'});
506
+ const rel=args.path;
507
+ const entry=manifest.files.find(f=>f.path===`craft/${rel}`);
508
+ if(!entry || rel.includes('\\') || rel.split('/').some(p=>!p||p==='.'||p==='..'))fail('CRAFT_PATH_INVALID','The requested file is not a bundled craft resource');
509
+ const target=path.join(craftRoot,rel),stat=await lstat(target);
510
+ if(!stat.isFile()||stat.isSymbolicLink())fail('CRAFT_PATH_INVALID','Bundled craft must be a regular file');
511
+ const bytes=await readFile(target);if(hash(bytes)!==entry.sha256)fail('CRAFT_CHANGED','Bundled craft no longer matches its provenance');
512
+ const detected=mimeOf(bytes);
513
+ if(detected?.[0].startsWith('image/'))return result({path:rel,sha256:entry.sha256}, {content:[{type:'image',data:bytes.toString('base64'),mimeType:detected[0]}]});
514
+ return result({path:rel,content:bytes.toString('utf8'),sha256:entry.sha256,toolInvocation:'makaron_native_tool(name=<canonical token>, arguments=<current live schema>)'});
515
+ }
516
+ case 'makaron_native_run': {
517
+ const method={tools:'tools/list',start:'run/start',status:'run/get',finish:'run/finish'}[args.action];
518
+ const params={projectId:args.projectId};
519
+ if(args.runId)params.runId=args.runId;
520
+ if(args.action==='start') {if(!args.sessionKey)fail('INVALID_ARGUMENTS','sessionKey is required');params.sessionKey=args.sessionKey;if(args.objective)params.objective=args.objective;}
521
+ if(['status','finish'].includes(args.action)&&!args.runId)fail('INVALID_ARGUMENTS','runId is required');
522
+ if(args.action==='finish'){params.status=args.status||'completed';if(args.summary)params.summary=args.summary;}
523
+ return result({mode:'host-native',nativeEndpoint,...await nativeRpc(method,params,signal)});
524
+ }
525
+ case 'makaron_native_tool': return nativeTool(args,signal);
526
+ case 'makaron_account': return result(await jsonRequest('/api/billing/credits', undefined, signal));
527
+ case 'makaron_discover': {
528
+ const live = await rpc('tools/list', {}, signal); const names = live?.tools?.map(t => t.name);
529
+ if (!names || names.some(n => !catalog.tools.some(t => t.name === n)) || catalog.tools.some(t => !names.includes(t.name))) fail('CATALOG_DRIFT', 'Live MCP tool names differ from this adapter catalog; refresh the adapter before paid submissions');
530
+ return result({ atomicTools: live.tools, helperTools: helpers, capabilities: { atomicMedia: ['image', 'video', 'audio'], design: 'host-native-project-facade', nativeEndpoint, hostNativeAppTools: 'discover-with-makaron_native_run', serviceMode: 'explicit-only' } });
531
+ }
532
+ case 'makaron_upload_source': return result(await upload(args.path, args.projectId, signal));
533
+ case 'makaron_project': {
534
+ if (args.action === 'list') return result(await jsonRequest('/api/projects/list', undefined, signal));
535
+ if (args.action === 'status') { if (!args.projectId) fail('INVALID_ARGUMENTS', 'projectId is required for status'); return result(stripMediaAliases(await jsonRequest(`/api/projects/${args.projectId}/media`, undefined, signal))); }
536
+ if(args.action==='import') {
537
+ if(!args.projectId||[args.sourcePath,args.url].filter(v=>v!==undefined).length!==1)fail('INVALID_ARGUMENTS','Import needs projectId and exactly one sourcePath/url');
538
+ await jsonRequest(`/api/projects/${args.projectId}/share`,undefined,signal); // Owner-only route; verify before transfer/mutation.
539
+ const source=args.sourcePath ? await upload(args.sourcePath,args.projectId,signal) : {url:safeUrl(args.url,{local:allowLocalHttp}).href};
540
+ const kind=source.mimeType?.split('/')[0] || args.mediaType;
541
+ if(!['image','video','audio'].includes(kind)||args.mediaType&&kind!==args.mediaType)fail('INVALID_ARGUMENTS','Import mediaType must match actual bytes; URL imports need an explicit type');
542
+ const imported=kind==='audio'
543
+ ? await jsonRequest('/api/music/import',{projectId:args.projectId,audios:[{audioUrl:source.url,title:args.title||'Reference audio',duration:args.duration,mimeType:source.mimeType,fileSizeBytes:source.sizeBytes,source:args.sourcePath?'cli_upload':'cli_url'}]},signal)
544
+ : await jsonRequest('/api/projects/create',{_addToProject:args.projectId,...(kind==='image'?{imageUrls:[source.url]}:{videoUrls:[source.url]}),idempotencyKey:args.client_request_id},signal);
545
+ if(kind==='audio'?!imported.tracks?.length:imported.projectId!==args.projectId||!imported.snapshots?.length)fail('IMPORT_UNCONFIRMED','Import returned no canonical identity; inspect this project instead of importing again');
546
+ return result(stripMediaAliases({projectId:args.projectId,mediaType:kind,source,...imported}));
547
+ }
548
+ const body = { title: args.title || 'Makaron Plugin Project' , clientProjectId: args.projectId || uuidFrom(`${scope}:${args.client_request_id}`), idempotencyKey: args.client_request_id, ...(args.imageUrls ? { imageUrls: args.imageUrls } : {}), ...(args.videoUrls ? { videoUrls: args.videoUrls } : {}) };
549
+ let existingSharing;
550
+ try { existingSharing = await jsonRequest(`/api/projects/${body.clientProjectId}/share`, undefined, signal); }
551
+ catch (error) { if (!(error.code === 'REMOTE_REJECTED' && error.details?.httpStatus === 404)) throw error; }
552
+ const created = await jsonRequest('/api/projects/create', body, signal);
553
+ if (created.projectId !== body.clientProjectId) fail('PROJECT_ID_MISMATCH', 'Project creation returned an unexpected identity; sharing was not changed');
554
+ if (existingSharing) return result({ ...created, is_public: existingSharing.is_public, sharingPolicy: 'existing-unchanged' });
555
+ try {
556
+ await jsonRequest(`/api/projects/${created.projectId}/share`, { is_public: false }, signal, 'PATCH');
557
+ const verified = await jsonRequest(`/api/projects/${created.projectId}/share`, undefined, signal);
558
+ if (verified.is_public !== false) fail('PROJECT_PRIVACY_UNVERIFIED', 'The new project private sharing setting was not verified');
559
+ return result({ ...created, is_public: false, sharingPolicy: 'new-private-owner-verified' });
560
+ } catch (error) { fail('PROJECT_PRIVACY_UNVERIFIED', 'New project exists but private sharing could not be verified; inspect this project before service submission', { projectId: created.projectId, cause: error.code || 'INTERNAL_ERROR' }); }
561
+ }
562
+ case 'makaron_service_submit': return result({ mode: 'service', ...await jsonRequest('/api/agent/run', { projectId: args.projectId, prompt: args.prompt, ...(args.agentModel ? { agentModel: args.agentModel } : {}), ...(args.sourceSnapshotIds ? { turnMediaSnapshotIds: args.sourceSnapshotIds, turnMediaCount: args.sourceSnapshotIds.length } : {}) }, signal) });
563
+ case 'makaron_service_status': return result(stripMediaAliases({ mode: 'service', ...await jsonRequest(`/api/agent/run/${args.runId}?usage=true`, undefined, signal) }));
564
+ case 'makaron_design_export': {
565
+ if ([args.snapshotId, args.designPath, args.design].filter(v => v !== undefined).length !== 1) fail('INVALID_ARGUMENTS', 'Supply exactly one of snapshotId, designPath or design');
566
+ const body = { ...args }; delete body.client_request_id;
567
+ if (body.publish) body.publishSnapshotId = uuidFrom(`${scope}:${args.client_request_id}:publish`);
568
+ return result(await jsonRequest('/api/remotion/export', body, signal));
569
+ }
570
+ case 'makaron_design_export_status': return decorateExportStatus(await jsonRequest(`/api/remotion/export/${args.jobId}`, undefined, signal), signal);
571
+ case 'makaron_download_artifact': {
572
+ const { artifact, bytes } = await download(args.url, args.filename, signal);
573
+ const output = result({ ...artifact, ...(signedMediaUrl(args.url) ? { sourceUrlSigned: true } : { url: args.url }) });
574
+ if (artifact.mimeType.startsWith('image/')) output.content.unshift({ type: 'image', mimeType: artifact.mimeType, data: bytes.toString('base64') });
575
+ return output;
576
+ }
577
+ case 'makaron_receipt': {
578
+ const receipt = await loadReceipt(args.client_request_id);
579
+ if (!receipt) fail('RECEIPT_NOT_FOUND', 'No saved submission matches this identifier');
580
+ return result(receipt);
581
+ }
582
+ default: fail('TOOL_NOT_FOUND', 'This adapter does not expose the requested tool');
583
+ }
584
+ }
585
+ return {
586
+ workspaceDir, stateDir,
587
+ async listTools({ refresh = false, signal } = {}) {
588
+ if (refresh) {
589
+ const live = await rpc('tools/list', {}, signal);
590
+ if (!Array.isArray(live?.tools) || live.tools.length !== catalog.tools.length || live.tools.some(t => !catalog.tools.some(c => c.name === t.name))) fail('CATALOG_DRIFT', 'Live tool catalog names differ from the packaged adapter');
591
+ defs = [...live.tools.map(decorate), ...helpers];
592
+ }
593
+ return structuredClone(defs);
594
+ },
595
+ async invokeTool(name, args = {}, { signal } = {}) {
596
+ try {
597
+ const definition = defs.find(t => t.name === name);
598
+ if (!definition) fail('TOOL_NOT_FOUND', 'This adapter does not expose the requested tool');
599
+ validate(args, definition.inputSchema);
600
+ if(name === 'makaron_craft') return clean(await execute(name,args,signal),key);
601
+ await auth();
602
+ if(name === 'makaron_native_tool' && !await loadReceipt(args.client_request_id)) await ensureNative(args, signal);
603
+ const paid = catalog.tools.some(t => t.name === name) && !readonlyRemote.has(name) || paidHelpers.has(name) || name === 'makaron_native_tool' && (nativePaid.has(args.name) || !['list_files','read_file','write_code_file','write_file','delete_file','execution_checkpoint','studio_run','publish_draft'].includes(args.name));
604
+ const onceNeeded = paid || name === 'makaron_project' && ['create','import'].includes(args.action) || name === 'makaron_native_tool' || name === 'makaron_native_run' && ['start','finish'].includes(args.action);
605
+ const output = onceNeeded ? await once(name, args, paid, () => execute(name, args, signal)) : await execute(name, args, signal);
606
+ return clean(output, key);
607
+ } catch (error) {
608
+ return result({ error: { code: error.code || 'INTERNAL_ERROR', message: error instanceof AdapterError ? clean(error.message, key) : 'The adapter could not complete this operation', ...(error.details ? { details: clean(error.details, key) } : {}) } }, { isError: true });
609
+ }
610
+ },
611
+ };
612
+ }
613
+ let defaultAdapter;
614
+ export async function listTools(options = {}) { defaultAdapter ||= createAdapter(); return defaultAdapter.listTools(options); }
615
+ export async function invokeTool(name, args, options = {}) { defaultAdapter ||= createAdapter(); return defaultAdapter.invokeTool(name, args, options); }