mirror of
https://github.com/nexu-io/openmotion.git
synced 2026-12-02 17:49:31 +08:00
* feat: add north-star tracking evidence * fix(distribution): ship the tracking task ledger in packaged applications phase1.ts and server.ts import tracking/task-ledger.ts, but the packaged application file list never gained the new module, so npm artifacts failed to load with ERR_MODULE_NOT_FOUND and the distribution lane failed. Add the module to the positive distribution list so both profiles keep a loadable application. Generated-By: looper 0.16.2 (runner=fixer, agent=pi) * fix(tracking): attribute worker evidence and ledger every accepted export Queue snapshots, heartbeats and technical-export checks now pass the worker entrypoint instead of inheriting the MCP tracker default. Host run failures and cancellations read the recorded work-round mode, and a failure only reports a failed run state after it actually closed the round. Every accepted export is now ledgered inside the shared export entry, so the Studio and legacy routes produce the same evidence as the MCP adapter, and an unreadable ledger is recorded as a diagnostic instead of failing an export that already started rendering. Repeating an identical terminal result keeps the recorded terminal time, and quality-check version ids follow the public version-id contract instead of requiring a v4 UUID. Generated-By: looper 0.16.2 (runner=fixer, agent=pi) * fix: correct instrumentation evidence semantics * fix: preserve work round failure evidence * fix: close interrupted exports with one terminal outcome Preview delivery now needs the confirmed current version and the originating round's fixed version, and preview evidence is emitted only after recordDisplay passes its version guard, so a rejected display no longer claims an observation and a delivery for the same run. Technical export checks report cancelled or unfinished jobs as unreviewed instead of error; only a completed job without a verification report stays an error. The export ledger entry for an interrupted export is now closed once with outcome unknown, and the worker tick that owns that transition emits the matching task_terminal evidence. A second tick or a status read sees the closed record and claim nothing. The tracking README describes that reconciliation path. Generated-By: looper 0.16.2 (runner=fixer, agent=pi) * fix: keep interrupted-export reconciliation out of live renders The worker tick reconciled before taking the working-set guard, so a later tick could close a job this process was still rendering, the local render was left running, and the owning worker then stated a second task_terminal for the same task. Reconciliation now runs only for a tick that does not own the render, it aborts any local controller of a job it closes, and the claiming worker states its terminal evidence through one helper that skips a job the reconciler already closed as unknown. Generated-By: looper 0.16.2 (runner=fixer, agent=pi) * fix: state terminal evidence from the caller that reconciles an export Coalesce interrupted-export reconciliation into one owner so every path that closes a task also reports it: the read path now records the same task_terminal evidence as the worker tick, keeps the ledger terminal time and never restates the outcome on a later read. Stores carry the service tracker, including project-scoped stores and the MCP read paths. Generated-By: looper 0.16.2 (runner=fixer, agent=pi) * fix: preserve provider preview schema --------- Co-authored-by: qindong <qindong@qindongs-MBP.lan> Co-authored-by: 罗高 <luogao@users.noreply.github.com> Co-authored-by: qindong <qindong@qindongs-MacBook-Pro.local>
101 lines
19 KiB
TypeScript
101 lines
19 KiB
TypeScript
import { inlineVideoUri } from './inline-video.ts';
|
|
import { publicToolName, legacyToolName } from './public-names.mjs';
|
|
import { templateDiscoveryGuide } from './workflow-entry.js';
|
|
import { assetLibraryTool, assetUseTool } from './asset-tools.ts';
|
|
const id = { type: 'string', minLength: 1, maxLength: 100 };
|
|
const projectId = { type: 'string', pattern: '^(project|[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12})$' };
|
|
const workId = { type: 'string', pattern: '^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$' };
|
|
const revision = { type: 'string', pattern: '^[a-f0-9]{64}$' };
|
|
const text = { type: 'string', minLength: 1, maxLength: 8000 };
|
|
const presentation = { enum: ['foreground', 'background', 'now'], description: 'Default foreground shows the calling chat panel when active and queues only while inactive, without switching chats. Use now only for an explicit request to display immediately in this turn; background skips presentation.' };
|
|
const object = (properties: Record<string, unknown>, required: string[] = []) => ({ type: 'object', properties, required, additionalProperties: false });
|
|
const review = object({ objectId: id, versionId: id, range: object({ start: { type: 'number', minimum: 0 }, end: { type: 'number', minimum: 0 } }, ['start', 'end']),
|
|
conclusion: { enum: ['passed', 'failed', 'pending', 'unable_to_view'] }, evidence: text, source: { enum: ['agent', 'user'] } }, ['objectId', 'versionId', 'conclusion', 'evidence', 'source']);
|
|
const display = object({ revision, versionId: id, previewUrl: { type: 'string', minLength: 1, maxLength: 4000 },
|
|
visibility: { enum: ['visible', 'queued', 'hidden', 'unavailable'], description: 'Observed native panel visibility. Use queued only when the host confirms the calling chat is inactive; a queued acknowledgment alone is insufficient. Otherwise use hidden or unavailable and report the display failure.' }, hostStatus: { type: 'string', minLength: 1, maxLength: 80, description: 'Host action acknowledgment, such as queued; independent of observed panel visibility.' }, hostTabId: { ...id, description: 'Actual native host Tab ID, such as providerTabId; never the CUA wrapper id. A reuse hint, not proof of current visibility.' }, contentVerified: { type: 'boolean' }, evidence: text },
|
|
['revision', 'versionId', 'previewUrl', 'visibility', 'contentVerified', 'evidence']);
|
|
const read = { readOnlyHint: true, openWorldHint: false };
|
|
const write = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
export const phase1Tools = [
|
|
assetUseTool,
|
|
assetLibraryTool,
|
|
{ name: 'openmotion_media_use', title: 'OpenMotion · Media Use', description: 'Use configured media providers, OpenDesign account models and registered OpenAI-compatible image/speech APIs to generate files. Start with action=inspect to discover enabled providers and their reference URIs. Before model discovery or generation, call action=reference with the selected provider to read its bundled guide: model-list API, supported modality request templates, authentication/input mapping, polling, error meanings and retry limits. Reference reading needs no projectId, key or local filesystem access; the same guides are discoverable through MCP resources/list and resources/read. Then query action=models with provider and refresh=true, select the provider-native model and check its schema. Generate requires explicit projectId, stable requestId, provider, model, modality and prompt; returns queued, not media. Poll action=status with the same projectId/jobId. The local service injects credentials; never pass or read keys. Connect an account or configure a provider in Settings > Model providers. Language/embedding selections do not run through this media tool. Completed results are automatically saved to the local workspace asset library and copied into the original project paths. job.libraryAssets pins assetId/versionId; job.assets retains project paths. If savePending is true, use action=retry_save with the same projectId/jobId and a stable requestId to save retained local outputs without a model call. Composition editing is separate. No automatic paid fallback or resubmission.',
|
|
inputSchema: object({ action: { enum: ['inspect', 'reference', 'models', 'generate', 'status', 'cancel', 'retry_save'], description: 'inspect returns provider setup state and reference URIs; reference returns the selected provider guide; models discovers capabilities; generate submits a job; status reads that original job; cancel requests cancellation; retry_save retries only local saving.' }, provider: { type: 'string', pattern: '^[a-z0-9][a-z0-9-]{0,80}$', description: 'Required for reference and generate; optional provider filter for models. Read this provider reference before constructing model queries or generation inputs.' },
|
|
projectId, requestId: id, jobId: id, model: { type: 'string', minLength: 1, maxLength: 180 }, modality: { enum: ['image', 'video', 'audio'] },
|
|
mode: { enum: ['text-to-image', 'text-to-video', 'text-to-audio', 'text-to-speech'] }, prompt: { type: 'string', minLength: 1, maxLength: 20000 },
|
|
parameters: { type: 'object', additionalProperties: true }, refresh: { type: 'boolean' }, query: { type: 'string', maxLength: 200 },
|
|
offset: { type: 'integer', minimum: 0 }, limit: { type: 'integer', minimum: 1, maximum: 100 } }, ['action']),
|
|
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true } },
|
|
{ name: 'openmotion_list_templates', title: 'OpenMotion · List Templates', description: 'Index templates from the loaded local repository; installations without a repository catalog use the configured CMS. Returns source, indexPath (local JSONL, one summary per template), total and catalogVersion, not search results. Read or grep/jq the file to select a template, then call openmotion_get_template. Repository summaries include localSource paths. No query or pagination arguments. ' + templateDiscoveryGuide, inputSchema: object({}), annotations: { ...read, openWorldHint: true } },
|
|
{ name: 'openmotion_get_template', title: 'OpenMotion · Get Template', description: 'Read one exact template ID and its TEMPLATE.md guidance. Repository entries include localSource absolute paths and the local motionDocument content. Guidance-only examples remain distinct from editable Studio projects. Use openmotion_create_project with projectType=template only when hasHtmlProject is true; otherwise apply the guidance while authoring a new project. Known IDs do not require listing first.', inputSchema: object({ templateId: id }, ['templateId']), annotations: { ...read, openWorldHint: true } },
|
|
{ name: 'openmotion_create_project', title: 'OpenMotion · Create Project', description: 'Create an independent editable native OpenMotion project from a prompt, an editable template ID or reference-video ID. The host Agent authors the film; creation does not generate a finished video. Persist requirements and source, return project/session IDs and the initial content version. A requestId is required for safe retries.',
|
|
inputSchema: object({ requestId: id, projectType: { enum: ['natural_language', 'template', 'reference_video'] }, title: { type: 'string', minLength: 1, maxLength: 100 }, requirements: text,
|
|
sessionId: projectId, templateId: id, referenceVideoId: id, referenceUrl: { type: 'string', maxLength: 2000 } }, ['requestId', 'projectType', 'title', 'requirements']), annotations: write },
|
|
{ name: 'openmotion_open_preview', title: 'OpenMotion · Open Preview', description: 'For video production, action=begin with explicit projectId, stable requestId and mode=create|modify creates a business work round silently before authoring. No production or editor action mounts an inline component. Open the editor only after the final authored video is ready for preview; use the separately discovered openmotion_show_video only after its MP4 export completes and passes verification. Carry its workId through saves and the final export; begin does not open Studio or render. Explicit editor-only requests, unchanged template browsing and review flows do not begin a round. Prepare the named project in the shared editable Studio; this Tool does not open the host browser. Use target=templates for the template library or target=providers for Settings > Model providers without creating/selecting a project; either target accepts only action=open, embedded and presentation and returns a page handoff without a project/version identity. Without projectId use only an explicitly bound OpenMotion session, never the global most-recent project. Follow previewHandoff to present the native panel and verify visibility plus latest content for first delivery and continued edits. Default foreground shows the active calling chat panel without switching chats; wait for return only when the host confirms that chat is inactive. A queued acknowledgment, hidden automation tab or markDeliverable does not complete delivery. Only an explicit show-now request uses presentation=now to permit switching for this turn. action=record_display records the current revision/version observation; queued or unverified content stays pending. Report a still-hidden panel as a display failure. action=record_review records evidence about a previously viewed frozen version without changing source.',
|
|
inputSchema: object({ target: { enum: ['project', 'templates', 'providers'] }, action: { enum: ['open', 'record_review', 'record_display', 'begin'] }, mode: { enum: ['create', 'modify'] }, projectId, sessionId: projectId, workId, embedded: { type: 'boolean' }, presentation, expectedRevision: revision, expectedVersionId: id, requestId: id, review, display }, []), annotations: write },
|
|
{ name: 'openmotion_import_assets', title: 'OpenMotion · Import Assets', description: 'Persist a batch of real local attachments into this project, at most 500 MB (500000000 bytes) per file. Probe media or parse TTF/OTF/TTC/WOFF fonts and return per-item asset IDs, types, sizes, paths and errors. Fonts include actual family/weight/style and project-relative @font-face CSS; an optional licensePath is copied in the same version. Successful items survive other failures. Existing history is not overwritten. Import does not place media on the timeline. Reuse the same requestId/itemId to retry without duplicate assets.',
|
|
inputSchema: object({ projectId, requestId: id, items: { type: 'array', minItems: 1, maxItems: 100, items: object({ itemId: id, sourcePath: { type: 'string', minLength: 1, maxLength: 4096 }, licensePath: { type: 'string', minLength: 1, maxLength: 4096, description: 'Optional absolute path to the font license text; copied with a font only.' }, name: { type: 'string', maxLength: 200 } }, ['itemId', 'sourcePath']) } }, ['projectId', 'requestId', 'items']), annotations: write },
|
|
{ name: 'openmotion_get_project', title: 'OpenMotion · Get Project', description: 'Without projectId list projects in the current workspace, newest creation first, exactly five per page (except the last); use nextCursor. With projectId read that project, current revision/version, requirements, native file inventory, asset references and associated export state. file supports bounded UTF-8 reads; exportJobId reads a historical task. With workId read one fixed work round; includeVideo=true returns its verified media privately to the component. This does not switch Studio or create projects.',
|
|
inputSchema: object({ projectId, sessionId: projectId, cursor: { type: 'string', maxLength: 2000 }, file: object({ path: { type: 'string', minLength: 1, maxLength: 240 }, offset: { type: 'integer', minimum: 0 }, length: { type: 'integer', minimum: 1, maximum: 2097152 } }, ['path']), expectedRevision: revision, exportJobId: id, workId, includeVideo: { type: 'boolean' } }, []), annotations: read },
|
|
{ name: 'openmotion_edit_project', title: 'OpenMotion · Edit Project', description: 'Save the host Agent\'s native text-file batch and associated requirements into the explicitly named project. Check both expectedRevision and expectedVersionId, commit all files or none, protect GUI writes, record one complete content version and let Studio refresh. Production saves with workId defer editor presentation until the final video is ready. Every save returns a version-bound previewHandoff: preserve the current chat by default, queue when inactive and confirm the latest content on return. An accepted queued preview may be reported as saved and waiting for return. Only an explicit show-now request permits presentation=now for this turn; background skips presentation. The service does not generate code. Read project/version again after conflicts.',
|
|
inputSchema: object({ projectId, requestId: id, workId, expectedRevision: revision, expectedVersionId: id, presentation, requirements: text, summary: { type: 'string', maxLength: 300 },
|
|
files: { type: 'array', maxItems: 100, items: object({ path: { type: 'string', minLength: 1, maxLength: 240 }, content: { type: 'string' } }, ['path', 'content']) } }, ['projectId', 'requestId', 'expectedRevision', 'expectedVersionId', 'files']), annotations: write },
|
|
{ name: 'openmotion_export_request', title: 'OpenMotion · Export Request', description: 'Queue a background MP4 of the explicit project version and immutable source/media snapshot. Automatically lint and fully technically verify the result. Return jobId; read progress/results with openmotion_get_project exportJobId. Export does not open the editor or complete an outstanding editable-preview handoff; follow openmotion_open_preview separately for creation/edit delivery. Repeated requestId returns the original task. action=record_review only records actual playback/visual/audio evidence for an existing job; it never starts another render.',
|
|
inputSchema: object({ action: { enum: ['request', 'record_review'] }, projectId, requestId: id, workId, expectedRevision: revision, versionId: id, jobId: id,
|
|
audio: { enum: ['required', 'silent', 'optional'] }, review }, ['projectId', 'requestId']), annotations: write },
|
|
{ name: 'openmotion_list_versions', title: 'OpenMotion · List Versions', description: 'List consistent project content snapshots, not individual file save counts. Return current-version identity and five snapshots per page with a cursor for older pages, including stable IDs, vN labels, source, summary and restorability. Five is a page size, not a retention limit.',
|
|
inputSchema: object({ projectId, cursor: { type: 'string', maxLength: 2000 } }, ['projectId']), annotations: read },
|
|
{ name: 'openmotion_restore_version', title: 'OpenMotion · Restore Version', description: 'Restore the explicitly selected project snapshot as a NEW version. Restoring v3 while current is v5 produces v6 with v3 content; v4 and v5 remain. Check current version/revision, restore native source, styles, timing and retained media together, and reject missing historical resources without changing the current project. Returns the same previewHandoff as a source edit; explicit background requests use presentation=background.',
|
|
inputSchema: object({ projectId, requestId: id, versionId: id, expectedRevision: revision, expectedVersionId: id, presentation }, ['projectId', 'requestId', 'versionId', 'expectedRevision', 'expectedVersionId']), annotations: write },
|
|
{ name: 'openmotion_export_cancel', title: 'OpenMotion · Export Cancel', description: 'Cancel the specified export owned by this project. Distinguish cancellation accepted/cancelling from a confirmed cancelled terminal state. A completed task stays completed. Cancellation does not restore source, delete older results or promise a refund. Stopping a host conversation does not automatically call this tool.',
|
|
inputSchema: object({ projectId, requestId: id, jobId: id }, ['projectId', 'requestId', 'jobId']), annotations: write },
|
|
];
|
|
|
|
// Increment for incompatible request/response semantics; optional fields and new Tools are additive.
|
|
export const phase1McpCapabilities = { protocol: 1, tools: phase1Tools.map(tool => tool.name) };
|
|
|
|
export function phase1TransportTool(health: { mcp?: { protocol?: unknown; tools?: unknown } }, tool?: string): string | undefined {
|
|
const name = publicToolName(tool);
|
|
if (typeof name !== 'string' || !phase1McpCapabilities.tools.includes(name)
|
|
|| health.mcp?.protocol !== phase1McpCapabilities.protocol || !Array.isArray(health.mcp.tools)) return;
|
|
// An older asset handler does not advertise the new read contract.
|
|
if (name === 'openmotion_assets_use') return health.mcp.tools.includes(name) ? name : undefined;
|
|
return [name, legacyToolName(name)].find(candidate => (health.mcp!.tools as unknown[]).includes(candidate));
|
|
}
|
|
|
|
export function supportsPhase1Tool(health: { mcp?: { protocol?: unknown; tools?: unknown } }, tool?: string): boolean {
|
|
return phase1TransportTool(health, tool) !== undefined;
|
|
}
|
|
|
|
export function validateInput(schema: any, value: any, field = 'arguments'): void {
|
|
if (schema.oneOf && schema.oneOf.filter((variant: any) => {
|
|
try { validateInput(variant, value, field); return true; } catch { return false; }
|
|
}).length !== 1) throw new Error('INVALID_ARGUMENT: ' + field + ' must match one action and its required fields');
|
|
if (schema.enum && !schema.enum.includes(value)) throw new Error('INVALID_ARGUMENT: ' + field);
|
|
if (schema.type === 'object') {
|
|
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('INVALID_ARGUMENT: ' + field + ' must be an object');
|
|
for (const key of schema.required ?? []) if (!Object.hasOwn(value, key)) throw new Error('INVALID_ARGUMENT: ' + field + '.' + key + ' is required');
|
|
for (const [key, child] of Object.entries(value)) {
|
|
if (!Object.hasOwn(schema.properties ?? {}, key)) {
|
|
if (schema.additionalProperties === true) continue;
|
|
throw new Error('INVALID_ARGUMENT: unknown ' + field + '.' + key);
|
|
}
|
|
validateInput(schema.properties[key], child, field + '.' + key);
|
|
}
|
|
} else if (schema.type === 'array') {
|
|
if (!Array.isArray(value) || value.length < (schema.minItems ?? 0) || value.length > (schema.maxItems ?? Infinity)) throw new Error('INVALID_ARGUMENT: ' + field);
|
|
value.forEach((item, i) => validateInput(schema.items, item, field + '[' + i + ']'));
|
|
} else if (schema.type === 'string') {
|
|
if (typeof value !== 'string' || value.length < (schema.minLength ?? 0) || value.length > (schema.maxLength ?? Infinity) || schema.pattern && !new RegExp(schema.pattern).test(value)) throw new Error('INVALID_ARGUMENT: ' + field);
|
|
} else if (schema.type === 'boolean' && typeof value !== 'boolean') throw new Error('INVALID_ARGUMENT: ' + field);
|
|
else if (['number', 'integer'].includes(schema.type) && (typeof value !== 'number' || !Number.isFinite(value) || schema.type === 'integer' && !Number.isSafeInteger(value) || value < (schema.minimum ?? -Infinity) || value > (schema.maximum ?? Infinity))) throw new Error('INVALID_ARGUMENT: ' + field);
|
|
}
|
|
|
|
/** Presentation is separate from business operations so authoring never mounts an App. */
|
|
export const finalVideoTool = {
|
|
name: 'openmotion_show_video', title: 'OpenMotion · Final Video',
|
|
description: 'Display only the final completed, technically verified MP4 for an explicit project/work round. Call once after export completes, never during generation or editing. This read-only presentation creates no project, work round, render or editor page. Keep workId from the silent openmotion_open_preview(action=begin) through saves and export. Old final videos remain bound to their own immutable export. A ready editable Studio handoff is separate; use only discovered Tools.',
|
|
inputSchema: object({ projectId, workId }, ['projectId', 'workId']), annotations: read,
|
|
_meta: { ui: { resourceUri: inlineVideoUri }, 'openai/ui': { preferredModelDisplayMode: 'inline' } },
|
|
};
|