diff --git a/README.md b/README.md index 2d3c755c9..1d5bc373b 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ Welcome to follow our official Bilibili account, which includes tutorials and sh - **Work with AI**: Describe what you want to create, reference canvas assets, and ask the assistant to save text or generate content with your configured models. - **Canvas and reference assets**: Upload files, connect nodes, or use `@` to add references. Organize assets in one place and review generation history. +- **Project spend**. Preview service costs for a candidate batch, set a project cap, and review requests on the canvas or in chat. [Spending controls](docs/guides/user-guide.md#project-spending) - **Media editing**: Crop, adjust colors, and work with layers and clips. AI tools such as image extension, erasing, and background removal depend on the connected models' capabilities. - **Image presets**: Select an image, choose Character three-view, Character four-view, Face three-view, Product three-view, Storyboard, or Multi-camera from **Presets**, then click **Generate**. Character four-view adds a frontal close-up to the right of the full-body front, side, and rear views. Enable **Face emphasis** to ask the model to frame the front and side views from the chin down, keeping the full rear view and frontal close-up. The view presets each produce one reference sheet; Storyboard and Multi-camera each produce four separate images connected to the source. - **Timeline editing**: Arrange assets, adjust start and end points, speed, and volume, then preview and render an MP4. You can also export JSON, FCPXML, and asset bundles. diff --git a/README.zh-CN.md b/README.zh-CN.md index 7b4d4894c..e6682114f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -30,7 +30,7 @@ OpenDirector 是一个在本地运行、通过浏览器使用的 AI 视频创作 OpenDirector 官方 B 站账号 -

+

## 最新动态 @@ -40,6 +40,7 @@ OpenDirector 是一个在本地运行、通过浏览器使用的 AI 视频创作 - **与 AI 协作**:描述创作要求,引用画布素材,让助手保存文本并调用已配置的模型生成内容。 - **画布与参考素材**:上传文件、连接节点或用 `@` 添加参考,集中整理素材并查看生成历史。 +- **工程费用**。查看整批候选的预计服务费,设置工程上限,在画布或助手对话中确认费用。[费用设置](docs/guides/user-guide.zh-CN.md#工程费用) - **媒体编辑**:裁剪、调色、处理图层和片段;扩图、消除、抠图等 AI 工具按已接入模型的能力提供。 - **图像预设**:选中图片后,从「预设」选择人物三视图、人物四视图、面部三视图、产品三视图、连续分镜图或多机位,再点「生成」。人物四视图在正面、侧面和背面全身图的右侧加入正脸特写;勾选「脸部强调」后,会提示模型只拍摄正面和侧面从下巴到鞋底的部分,保留完整的背面全身和正脸特写。三视图和四视图各输出一张参考板;连续分镜图和多机位各输出四张独立图片,并关联原图。 - **时间线编排**:安排素材顺序、起止点、速度和音量,预览并合成 MP4,也可导出 JSON、FCPXML 和素材包。 diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index c1de28496..9fb940bce 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -62,7 +62,7 @@ async def __call__(self, scope, receive, send): def creation_routes(projects: CreationProjects, generation=None): router = APIRouter(prefix='/api/creation', tags=['Unified creation projects']) assets = CreationAssets(projects) - canvas = CreationCanvas(projects) + canvas = CreationCanvas(projects, generation) history = CreationHistory(projects, assets=assets) timeline_packages = CreationTimelinePackages(projects) @@ -131,14 +131,16 @@ async def execute(project_id: UUID, value: Command, request: Request, x_opendire session = str(x_opendirector_session) if x_opendirector_session else None if value.type == 'artifact.publish': raise ProjectError('产物发布需要服务端执行上下文,不能通过路径直接访问本机文件。', 403) - if value.type == 'job.checkpoint': + if value.type in {'job.checkpoint', 'spend.observe', 'spend.tool', 'spend.advanceGroup'}: raise ProjectError('任务执行事实只能由后台写入。', 403) if x_canvas_import is not None and value.type != 'asset.import': raise ProjectError('归档来源只能随素材导入声明。', 400) imported_from = x_canvas_import if x_canvas_import in {'generated', 'edited'} else None if x_canvas_import is not None and imported_from is None: raise ProjectError('归档来源必须是 generated 或 edited。', 400) - if value.type in {'generation.submit', 'job.cancel', 'job.recover'}: + if value.type in {'spend.review', 'spend.policy'} and request.headers.get('sec-fetch-site') != 'same-origin': + raise ProjectError('Review spending in the local project window.', 403) + if value.type in {'generation.submit', 'generation.group', 'spend.review', 'spend.policy', 'job.cancel', 'job.recover'}: if generation is None: raise ProjectError('任务服务不可用。', 503) receipt = await generation.execute(value, session=session) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index eb3efb1fd..5833587f5 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -16,6 +16,14 @@ from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message ENGLISH_BY_CODE = { + 'spend_human_review': 'Review spending in the project window.', + 'spend_reviewed': 'This spending request has already been reviewed. Check project spending history.', + 'spend_cancelled': 'This spending request was cancelled. Start a new task.', + 'selection_preview_started': 'The selection preview has already started. Check project spending history before retrying.', + 'spend_call_submitted': 'This tool model call has already been submitted. Check project spending history.', + 'spend_quote_changed': 'The request, price or balance changed. Review the current batch.', + 'spend_cap': 'This batch exceeds the available project budget.', + 'spend_unknown': 'Set a price in the project currency to determine the maximum cost.', "desktop_auth_required": "The desktop connection has expired. Reopen the application.", 'image_quality_unsupported': 'This model does not support the selected image quality. Choose Auto or select another model.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', @@ -151,7 +159,8 @@ def localized_error_for_language( if specific is not None: return specific if not wants_english_language(language): - return chinese + return {'spend_quote_changed': '请求、价格或余额已变更,请重新核对本批报价。', 'spend_cap': '本批费用超过工程可用预算。', + 'spend_unknown': '请设置使用工程币种的单价,以确定本批费用上限。'}.get(code, chinese) if code == 'tool_model_missing': return missing_tool_model_message(required_capability, english=True) if code == 'model_list_http_error': diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index 724b1806a..4234610d1 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -31,6 +31,8 @@ from opendirector_api.voices import voice_routes from opendirector_api.examples import router as example_routes from opendirector_api.localization import localized_error +from fastapi import Body +from opendirector.domain.creation.spend import ConnectionPrice from opendirector_api.models import (ModelConfigInput, ModelConfigPublic, AgentModelTest, ModelCapabilityRequest, ModelDiscoveryRequest, ModelBatchInput, ToolTaskCreate, ToolPlacement, ImageSelectionCreate, AvailabilityRefresh, AvailabilityCatalog, @@ -78,6 +80,7 @@ async def lifespan(app): availability.probe.close() app = FastAPI(title="OpenDirector Local API", version="0.1.5", lifespan=lifespan) + creation_generation.tools = creation_tools app.include_router(creation_routes(creation_projects, creation_generation)) app.include_router(agent_routes(creation_projects, creation_generation, model_configs, chat_provider, active=active_agents)) app.include_router(library_routes(creation_projects)) @@ -285,6 +288,10 @@ def update_model_config(config_id: UUID, value: ModelConfigInput): capabilities_supplied='videoCapabilities' in value.model_fields_set, input_modalities=value.inputModalities, capability_auto_check=value.capabilityAutoCheck) + @app.put('/api/model-configs/{config_id}/price', response_model=ModelConfigPublic) + def update_connection_price(config_id: UUID, value: ConnectionPrice | None = Body()): + return model_configs.set_price(str(config_id), value) + @app.delete("/api/model-configs/{config_id}", status_code=204) def delete_model_config(config_id: UUID): catalog.delete(str(config_id)) @@ -294,6 +301,10 @@ def tool_catalog(): return creation_tools.catalog() def register_selection_route(service, prefix): + @app.get(prefix + '/{task_id}') + def selection_result(project_id: UUID, task_id: UUID, x_opendirector_session: str = Header()): + return service.selection_result(str(project_id), str(task_id), identifier(x_opendirector_session)) + @app.post(prefix) async def image_selection(project_id: UUID, value: ImageSelectionCreate, request: Request, x_opendirector_session: str = Header()): @@ -326,6 +337,10 @@ def register_tool_routes(service, prefix): def tool_tasks(project_id: UUID): return {'tasks': service.list(str(project_id))} + @app.post(prefix + '/quote') + def quote_tool(project_id: UUID, value: ToolTaskCreate, x_opendirector_session: str = Header()): + return service.quote(str(project_id), value.model_dump(mode='json', exclude_none=True), identifier(x_opendirector_session)) + @app.post(prefix, status_code=202) async def submit(project_id: UUID, value: ToolTaskCreate, x_opendirector_session: str = Header()): return await service.submit(str(project_id), value.model_dump(mode='json', exclude_none=True), identifier(x_opendirector_session)) diff --git a/apps/api/src/opendirector_api/models.py b/apps/api/src/opendirector_api/models.py index e74d6338e..c66f76db7 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -2,6 +2,7 @@ from uuid import UUID from pydantic import model_validator, BaseModel, ConfigDict, Field, SecretStr +from opendirector.domain.creation.spend import ConnectionPrice from opendirector.domain.creation.editors import ToolDraftBinding from opendirector.domain.capabilities import AgentInputModality from opendirector.domain.video_capabilities import VideoAdapter, VideoCapabilities @@ -75,6 +76,7 @@ class ModelCapabilityRequest(ModelConfigInput): class ModelConfigPublic(ModelConnection): + price: ConnectionPrice | None = Field(default=None, exclude_if=lambda value: value is None) availability: ModelAvailability | None = Field(default=None, exclude_if=lambda value: value is None) providerId: UUID | None = Field(default=None, exclude_if=lambda value: value is None) videoAdapter: VideoAdapter = 'auto' @@ -115,6 +117,7 @@ def bounded_parameters(self): class ImageSelectionCreate(Model): + id: UUID | None = None sourceAssetId: UUID prompt: str = Field(default='', max_length=2000) boxes: list[ToolBox] = Field(default_factory=list, max_length=64) diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 2dcd68807..5ca931a5a 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -127,6 +127,20 @@ Selected voices are saved in the project; favorites are saved as browser prefere Agents use the same validation through `voice_list`, `voice_create`, and `voice_delete`. The [business CLI](cli.md) also exposes `voice list`, `voice create`, and `voice delete`. +## Project spending + +Click the wallet icon at the bottom left of the canvas to open **Project spend**, including spending controls and history. A generation estimate lists the selected model, pricing unit, output count and batch total. Reference music lists transcription of the source recording and generation of the music separately. Following the recording uses the effective duration limit shown by the music model. For editing tools, expand the estimate to see each model call. + +In **Model connections**, set a unit price and currency for an individual model. Media tools that translate prompts use the chat model’s **Media tool call price**. A connection price takes precedence over the built-in official price for an exact service endpoint and model. A self-hosted connection defaults to zero service fees. Unknown charges and different currencies remain visible separately. The ledger covers media service calls. Equipment costs and assistant subscriptions are separate expenses. + +When a batch exceeds **Confirm above** or needs another spending decision, a confirmation dialog shows the action, quantity and estimated total. Canvas actions and assistant tasks use the same dialog. **Spent so far** is the amount already recorded. **Reserved for tasks** is the budget held for approved work. Hover over either amount for details. When the remaining budget is too low, the confirmation button shows the new project cap needed to run the batch. Click it once to raise the cap and start the work. + +Approving or cancelling closes the dialog; multiple new requests are reviewed one at a time. Closing it or pressing Esc leaves the request waiting for approval. A dot on the wallet icon indicates pending requests; click it to reopen the review. **Spending controls and history** in the dialog opens project totals and past calls. + +With a cap enabled, calls with an unknown maximum require a price in the project currency. Select a group to see the subtotal for runnable steps and how many are waiting for inputs. If a workflow needs an upstream result, review its runnable steps first and then the downstream estimate based on the saved result. The CLI returns the local review link and supports `query spend.status`. + +Spend history retains the original estimate, any charge calculated from confirmed usage, and any amount explicitly reported by the service. A lost response leaves the call pending verification. Restoring a full project backup retains these records. Importing an asset into a new project starts with that project's own usage history. Undo applies to creative edits. + ## Monitor and manage generation tasks Open **Generation history** at the top right to view task progress, results, and failure details. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 7d32c5a06..0879c1db4 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -127,6 +127,20 @@ MiniMax 配音使用[同步语音合成接口](https://platform.minimax.cn/docs/ Agent 通过 `voice_list`、`voice_create`、`voice_delete` 使用同一套校验;[业务 CLI](cli.md) 也提供 `voice list`、`voice create`、`voice delete`。 +## 工程费用 + +点击画布左下角的钱包图标打开「工程费用」,查看费用设置与记录。生成报价列出模型、计价单位、生成数量和整批金额。使用参考录音生成音乐时,转谱和音乐生成各有一笔报价。开启跟随参考时长后,音乐生成使用模型实际采用的时长上限。展开媒体编辑工具的报价,可以看到各次模型调用。 + +在「模型接入」中可以给单个模型设置计价单位、单价和币种。媒体工具调用对话模型翻译提示词时,使用该对话模型的「媒体工具调用单价」。连接单价优先于内置官方价格。官方价格只适用于明确对应的服务地址和模型。自托管连接默认服务费为零。缺价步骤和不同币种分别显示。工程费用记录涵盖媒体服务调用,设备开支和助手订阅单独计算。 + +整批估价超过「单批确认阈值」或需要其他费用决定时,确认弹窗会显示本次操作、数量和预计总价。画布操作和助手发起的任务共用此弹窗。「已用金额」是已计入工程的费用,「任务占用」是已批准任务尚在占用的预算。把指针移到这两项上可以查看说明。剩余预算不足时,确认按钮会列出运行本批所需的新工程上限,点击一次即可提高上限并运行。 + +批准或取消后,弹窗关闭;同时存在多项新申请时,依次确认。点击关闭或按 Esc 会保留申请,任务继续等待批准。钱包图标上的小圆点表示仍有申请待处理,点击图标可重新打开。弹窗中的「费用设置与记录」可查看工程总额和历史调用。 + +开启上限后,最高费用未知的调用需要先配置使用工程币种的价格。选择分组即可查看可执行步骤的小计和仍在等待输入的步骤数。有依赖的分组可以先批准已报价的上游步骤,取得素材后再查看下游报价。命令行返回本地确认页面地址,使用 `query spend.status` 可查看当前决定。 + +费用记录保留原估价、根据已确认用量计算的金额,以及服务明确报告的金额。服务响应丢失时,相应调用等待核实。恢复完整工程备份会保留费用记录。将素材导入新工程时,新工程独立记录自己的调用。撤销画布编辑会保留已经发生的费用。 + ## 查看和处理生成任务 打开右上角“生成历史”,查看任务进度、结果和失败原因。 diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index 4753be1d8..0b88691d7 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -7,6 +7,8 @@ from typing import get_args from uuid import UUID, uuid5 +from pydantic_core import to_jsonable_python +from opendirector.application.creation_spend import review_status from pydantic import JsonValue, TypeAdapter, ValidationError from opendirector.domain.creation.base import agent_command_id from opendirector.application.creation_artifacts import publish_artifact @@ -28,7 +30,7 @@ from opendirector.installation import SOURCE_ROOT, BUNDLED ROOT = SOURCE_ROOT or BUNDLED -EXCLUDED = {'project.create', 'project.trash', 'project.restore', 'asset.import', 'job.checkpoint', +EXCLUDED = {'spend.advanceGroup', 'spend.tool', 'spend.observe', 'spend.policy', 'spend.review', 'project.create', 'project.trash', 'project.restore', 'asset.import', 'job.checkpoint', 'canvas.applyEdit', 'canvas.publishMedia', 'timeline.publishRender'} QUERY_MODELS = get_args(get_args(Query)[0]) @@ -58,6 +60,7 @@ def query_guidance(failure): for command_name, command_model in COMMANDS.items(): assert command_model.__doc__ and command_model.__doc__.strip(), f'Missing command metadata: {command_name}' SYSTEM = '''You are OpenDirector, a video creation assistant. +Before paid media generation query generation.quote for the complete candidate count and describe the estimated service cost and project total. Use generation.submit with that count. For a workflow, use generation.groupQuote and generation.group with the same members and dependencies. For awaiting_confirmation, report the batch, amounts and any shortfall from spend.status. Wait for a human decision in this project's canvas or chat. Never split a batch to avoid confirmation. Respond directly when the user's request can be answered without project state or tool execution. When the task needs project capabilities, use the harness's native shell tool to discover and run the opendirector executable on PATH. Before using the project CLI, locate opendirector through the shell (Get-Command opendirector in PowerShell, command -v opendirector in POSIX shells), then execute opendirector --help. @@ -257,7 +260,9 @@ def tools() -> list[dict]: 'additionalProperties': False})) query_schema = TypeAdapter(Query).json_schema() query_schema['type'] = 'object' - for definition in query_schema['$defs'].values(): + # The host supplies IDs on the query envelope. Nested workflow members keep their own schema. + for branch in query_schema['oneOf']: + definition = query_schema['$defs'][branch['$ref'].rsplit('/', 1)[-1]] for field in ('queryId', 'projectId'): definition['properties'].pop(field) definition['required'].remove(field) @@ -365,7 +370,7 @@ def recording(): # A rejected query must name the accepted types rather than echo a # tag list the model has to reinterpret. raise ProjectError(query_guidance(failure)) from None - result = await CreationCanvas(self.projects).query(query) + result = await CreationCanvas(self.projects, self.generation).query(query) if query.type == 'asset.preview' and 'preview' in result: with self.projects.local.transaction() as db: project_directory, _, _ = self.projects._load(db, project_id) @@ -394,6 +399,8 @@ def recording(): raise ProjectError('技能资源必须是不超过 64 KB 的文本文件。') return await asyncio.to_thread(resolved.read_text, encoding='utf-8') command_type = TypeAdapter(str).validate_python(arguments['type'], strict=True) + if command_type not in COMMANDS: + raise ProjectError('This action requires the project window.', 403) model = COMMANDS[command_type] if name == 'command_schema': schema = model.model_json_schema() @@ -444,7 +451,7 @@ def narrow(value: JsonValue) -> None: 'commandId': str(agent_command_id(turn_id, call_id))}) if command.type == 'creation.batch' and any(operation.type not in COMMANDS for operation in command.payload.operations): raise ProjectError('批量命令包含未开放的 Agent 操作。', 403) - if command.type == 'generation.submit': + if command.type in {'generation.submit', 'generation.group'}: receipt = await self.generation.execute(command, session=session, source='agent', agent_origin=(turn_id, call_id)) elif command.type in {'job.cancel', 'job.recover'}: receipt = await self.generation.execute(command, session=session, source='agent') @@ -464,4 +471,11 @@ def narrow(value: JsonValue) -> None: receipt = await asyncio.to_thread(self.assets.execute, command, session=session, source='agent', provenance=provenance) else: receipt = await asyncio.to_thread(self.projects.execute, command, session=session, source='agent') - return receipt.model_dump(mode='json') + result = receipt.model_dump(mode='json') + if command.type in {'generation.submit', 'generation.group'} and receipt.status != 'rejected': + summary = await asyncio.to_thread(lambda: review_status(self.projects.snapshot(project_id))) + pending = next((entry for entry in summary['pending'] if entry['request'].id == receipt.spendRequestId), None) + result['spend'] = to_jsonable_python(dict(currency=summary['policy'].currency, settled=summary['settled'], + held=summary['held'], available=summary['available'], review=( + {k: v for k, v in pending.items() if k != 'request'} | {'quote': pending['request'].quote} if pending else None))) + return result diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index aab824957..39e3baddd 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -290,8 +290,9 @@ def bind_unique_timeline_sources(data, document, *, new_slot_ids): class CreationCanvas: - def __init__(self, projects): + def __init__(self, projects, generation=None): self.projects = projects + self.generation = generation from opendirector.application.creation_assets import CreationAssets self.assets = CreationAssets(projects) @@ -842,6 +843,27 @@ def projection(self, project_id, snapshot=None): hiddenItemIds=[i.id for i in snapshot.canvasItems if i.id not in visible], edges=edges, capabilities=capabilities) async def query(self, query: Query) -> JsonValue: + if query.type == 'spend.status': + from opendirector.application.creation_spend import review_status + def status(): + snapshot = self.projects.snapshot(query.projectId) + result = review_status(snapshot, query.agentRunId) + if query.agentRunId is None and self.generation is not None and self.generation.tools is not None: + owners = {str(call.ownerId) for call in snapshot.spendCalls} + result['legacy'] += self.generation.tools.untracked_calls(str(query.projectId), owners) + return result + return to_jsonable_python(await asyncio.to_thread(status)) + if query.type == 'generation.groupQuote': + if self.generation is None: + raise ProjectError('Generation service unavailable.', 503) + from opendirector.application.creation_groups import preview + return to_jsonable_python(await asyncio.to_thread(preview, self.generation, query)) + if query.type == 'generation.quote': + if self.generation is None: + raise ProjectError('Generation service unavailable.', 503) + quote = await asyncio.to_thread(self.generation.quote, query.projectId, query.specId, query.count, query.originItemId) + from opendirector.application.creation_spend import quote_view + return to_jsonable_python(quote_view(await asyncio.to_thread(self.projects.snapshot, query.projectId), quote)) if query.type == 'canvas.status': return await self.wait_item_status(query.projectId, query.objectId, query.waitSeconds) if query.type == 'asset.preview': diff --git a/packages/core/src/opendirector/application/creation_commands.py b/packages/core/src/opendirector/application/creation_commands.py index e3d9bb72d..3dcda8e52 100644 --- a/packages/core/src/opendirector/application/creation_commands.py +++ b/packages/core/src/opendirector/application/creation_commands.py @@ -39,7 +39,7 @@ def rename(snapshot): if snapshot.project.name == name and snapshot.project.defaultNameIndex is None: return snapshot data = snapshot.model_dump() - data['project'] = dict(id=snapshot.project.id, name=name, revision=snapshot.project.revision + 1) + data['project'].update(name=name, defaultNameIndex=None, revision=snapshot.project.revision + 1) return ProjectSnapshot.model_validate(data) return projects.commit(command, rename, session=session, source=source) diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index f05de01e8..71d029918 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -5,6 +5,7 @@ """ import asyncio from contextvars import ContextVar +from decimal import Decimal from datetime import datetime, timezone import hashlib import re @@ -13,11 +14,14 @@ from filelock import FileLock, Timeout +from opendirector.application import creation_groups, creation_spend from opendirector.application.creation_assets import CreationAssets from opendirector.application.creation_canvas import CreationCanvas, asset_ref, current_generation_inputs, visible_item_ids from opendirector.application.voice_library import VoiceLibrary from opendirector.application.model_availability import ModelAvailability, generation_request from opendirector.application.generation_runtime import GenerationRuntime, _self_hosted_video +from opendirector.domain.creation.spend import SpendQuote, price_line, video_units +from opendirector.domain.references import project_content from opendirector.domain.creation.assets import AssetProvenance from opendirector.domain.creation.canvas import TextCanvasItem, ImageCanvasItem, VideoCanvasItem, AudioCanvasItem from opendirector.domain.creation.base import ObjectVersion @@ -26,7 +30,7 @@ reference_music_seconds, validate_generation) from opendirector.domain.creation.models import ModelConfigPublic, ModelSnapshot from opendirector.domain.creation.project import ProjectSnapshot -from opendirector.domain.creation.validation import ContractError +from opendirector.domain.creation.validation import ContractError, validate_command from opendirector.domain.input_rules import input_rules from opendirector.domain.minimax_speech import is_minimax_speech from opendirector.domain.projects import ProjectError @@ -76,6 +80,11 @@ def asset(self, project_id, asset_id): def generation_task(self, project_id, job_id): return self.runtime.task(self.runtime.get_job(project_id, job_id)) + def observe_spend(self, slot, state, **facts): + job = _INPUTS.get() + if job is not None: + creation_spend.observe(self.runtime.projects, job.projectId, uuid5(job.id, f'spend:{slot}'), state, **facts) + def frozen_model(self, frozen): """Credentials for a helper model an accepted job froze, while its connection is unchanged.""" config = self.runtime.configs.resolve(frozen['id'], frozen['kind']) @@ -97,6 +106,8 @@ class CreationGeneration(GenerationRuntime): def __init__(self, projects, configs, provider=None, *, availability=None): super().__init__() self.projects, self.configs = projects, configs + self.group_workers = {} + self.tools = None self.assets = CreationAssets(projects) self.store = ProviderMedia(self) self.settings = gateway().settings(projects.local.repository) @@ -331,14 +342,136 @@ async def _run(self, task, pinned, config, mode='submit'): remote.release() claim.release() - def prepare(self, command, *, session=None, source='ui', agent_origin=None): - replay = self.projects.replay(command) - if replay is not None: - return replay + + def _propose_job(self, before, command, *, agent_origin=None, checks=None): + """Prepare exact inputs on a private copy. Only admission publishes it.""" + voice_spec, voice_config, voice_failure, capability_identity, capability_failure = checks or (None,) * 5 + data = before.model_dump(mode='json') + spec_data = CreationCanvas._get(data, 'generation_spec', command.payload.specId) + if sum(j.inputSnapshot.spec.id == command.payload.specId and j.status in {'queued', 'running'} for j in before.jobs) + command.payload.count > 8: + raise ContractError('revision_conflict', '该配置的排队任务已达上限,请等待或取消原任务。', command.payload.specId) + if command.payload.previousJobId: + previous = next((j for j in before.jobs if j.id == command.payload.previousJobId), None) + if previous is None or previous.inputSnapshot.spec.id != command.payload.specId: + raise ContractError('invalid_input', '新尝试必须关联同一生成配置的原任务。', command.payload.previousJobId) + origin = command.payload.originItemId + material = None + if origin: + item = CreationCanvas._editable(data, origin) + material = item['binding'].get('materialOverride') + spec_data['purpose'] = 'generation' + item['binding'] = dict(role='generation', objectRef=dict(objectType='generation_spec', id=spec_data['id']), materialOverride=material) + if item != next(i.model_dump(mode='json') for i in before.canvasItems if i.id == origin): + item['revision'] += 1 + elif spec_data['purpose'] == 'draft': + spec_data['purpose'] = 'generation' + # Promote every owner of this draft together, including hidden ones. + for item in data['canvasItems']: + # An empty binding serialises draftSpec as null, not absent. + if (item['binding'].get('draftSpec') or {}).get('id') == spec_data['id']: + item['binding'] = dict(role='generation', objectRef=dict(objectType='generation_spec', id=spec_data['id'])) + item['revision'] += 1 + old = next(s for s in before.generationSpecs if s.id == command.payload.specId) + if spec_data['purpose'] != old.purpose: + spec_data['revision'] += 1 + intermediate = ProjectSnapshot.model_validate(data) + spec = next(s for s in intermediate.generationSpecs if s.id == old.id) + config = self.configs.resolve(str(spec.modelConfigId), 'agent' if spec.kind == 'text' else spec.kind) + public = ModelConfigPublic.model_validate({key: value for key, value in config.items() if key != 'apiKey'} | {'inputRules': self.availability.effective_input_rules(config)}) + spec, resolved = current_generation_inputs(intermediate, spec, public.inputRules) + spec = execution_spec(spec, resolved, public.inputRules) + try: + validate_generation(spec, public, resolved, submitting=True) + if spec.kind == 'audio' and spec.parameters.creationType == 'audio': + if checks and (old != voice_spec or config != voice_config): + raise ContractError('revision_conflict', '音色验证期间生成配置或模型服务已变化,请重新提交。', spec.id) + if voice_failure is not None: + raise voice_failure + if capability_failure is not None: + raise capability_failure + if capability_identity is not None: + self.availability.require(config, generation_request(config, spec, resolved), capability_identity) + except (ValueError, ProjectError) as error: + raise ContractError.from_error(error, spec.id) from error + for reference in resolved: + if reference.transmission != 'context_only': + self.assets.reference_available(command.projectId, reference.asset.assetId) + self.provider.validate(spec.kind, config) + snapshot = InputSnapshot(spec=spec.model_copy(update={'currentResultId': None}), + model=ModelSnapshot(modelConfigId=public.id, inputRules=public.inputRules, + **{k: getattr(public, k) for k in ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'proxyMode', 'videoAdapter')}), references=resolved) + # Use the same rendering, protocol validation and parameter resolver + # as the established adapters, with immutable media from the facade. + stub = Job(id=uuid5(command.commandId, 'job'), projectId=command.projectId, inputSnapshot=snapshot, + createdAt=datetime.now(timezone.utc), + inputFingerprint=snapshot.fingerprint(), execution={'kind': spec.kind, **({'size': '2K'} if spec.kind == 'image' else {'format': 'mp3', 'sampleRate': 24000} if spec.kind == 'audio' else {})}, + originItemId=origin, previousJobId=command.payload.previousJobId, + **({'agentRunId': agent_origin[0], 'agentCallId': agent_origin[1]} if agent_origin else {}), + adoptionPolicy=command.payload.adoptionPolicy, adoptionResultId=old.currentResultId, adoptionMaterial=material, + batchId=command.payload.batchId, showAdditionalResult=command.payload.showAdditionalResult) + task = self.task(stub) + records = {str(a.id): media_record(a) for a in before.assets} + try: + if hasattr(self.provider, 'prepare_inputs'): + self.provider.prepare_inputs(str(command.projectId), task, config) + parameters = self._parameters(spec, config, task, records) + if capability_identity is not None: + self.availability.require(config, generation_request(config, spec, resolved, parameters=parameters), capability_identity) + except ProjectError as error: + raise ContractError.from_error(error, spec.id) from error + job = Job.model_validate({**stub.model_dump(), 'adapterParameters': parameters, 'execution': self._execution(spec.kind, parameters, config)}) + return data, job, config, task, records + + def _quote_job(self, job, config, task, records, count): + spec = job.inputSnapshot.spec + params = job.adapterParameters + lines = [] + if spec.kind != 'text': + operation = spec.kind + quantities = {} + bounded = () + if params.get('score_model'): + score = self.store.frozen_model(params['score_model']) + recording = next(records[key] for key in task['referenceIds'] if records[key]['kind'] == 'audio') + seconds = recording['durationMs'] + lines.append(price_line(score, 'score', {'input_second': Decimal(seconds) / 1000 if seconds is not None else None})) + if spec.kind == 'audio': + operation = 'music' if params.get('creation_type') == 'music' else 'speech' + if operation == 'speech': + text = project_content(task['promptContent'], speech=True)[0] if task['promptContent'] is not None else task['prompt'] + quantities['input_character'] = len(text) + if is_minimax_speech(config) and not text.isascii(): + # MiniMax reports its billable character count in the response. + quantities['input_character'] += sum(not char.isascii() for char in text) + bounded = ('input_character',) + if spec.kind == 'video': + quantities.update(video_units(params)) + elif params.get('duration') is not None: + quantities.update(requested_second=params['duration'], output_second=params['duration']) + lines.append(price_line(config, operation, quantities, bounded=bounded)) + return SpendQuote(count=count, lines=lines, inputFingerprint=job.inputFingerprint) + + def quote(self, project_id, spec_id, count=1, origin=None): + before = self.projects.snapshot(project_id) + spec = next((s for s in before.generationSpecs if s.id == spec_id), None) + if not spec: + raise ProjectError('Generation configuration not found.', 404) + versions = [version('generation_spec', spec)] + if origin is not None: + item = next((i for i in before.canvasItems if i.id == origin), None) + if not item: + raise ProjectError('Canvas item not found.', 404) + versions.append(version('canvas_item', item)) + command = parse_command(dict(type='generation.submit', commandId=uuid4(), projectId=project_id, expectedVersions=versions, + payload=dict(specId=spec.id, expectedSpecRevision=spec.revision, originItemId=origin, count=count))) + validate_command(command, before) + _, job, config, task, records = self._propose_job(before, command) + return self._quote_job(job, config, task, records, count) + + def _submission_checks(self, command, initial): # Voice registries are remote services. Probe outside the catalog/file # transaction, then compare the exact spec and private configuration # again under commit so a slow/offline provider cannot freeze editing. - initial = self.projects.snapshot(command.projectId) voice_spec = next((spec for spec in initial.generationSpecs if spec.id == command.payload.specId), None) capability_identity = None capability_failure = None @@ -358,88 +491,85 @@ def prepare(self, command, *, session=None, source='ui', agent_origin=None): self.voices.validate_selection(voice_config, prepared_spec.parameters.voice, prepared_spec.parameters.voiceSelection) except (ValueError, ProjectError) as error: voice_failure = error + return voice_spec, voice_config, voice_failure, capability_identity, capability_failure + + def _append_candidates(self, before, data, command, job, config, quote): + calls = list(before.spendCalls) + for index in range(command.payload.count): + candidate = job + if index: + params = dict(job.adapterParameters) + if 'seed' in params: + params['seed'] = new_seed() + candidate = job.model_copy(update=dict(id=uuid5(command.commandId, f'job:{index}'), + adoptionPolicy='candidate_only', showAdditionalResult=bool(job.originItemId), adapterParameters=params, + execution=type(job.execution).model_validate(self._execution(job.execution.kind, params, config)))) + if command.payload.count > 1: + candidate = candidate.model_copy(update=dict(batchId=job.batchId or command.commandId)) + data['jobs'].append(candidate.model_dump(mode='json')) + calls.extend(creation_spend.reserve_calls(candidate.id, candidate.projectId, quote)) + data['spendCalls'] = calls + return ProjectSnapshot.model_validate(data) + + def prepare(self, command, *, session=None, source='ui', agent_origin=None, review=None): + replay = self.projects.replay(review or command) + if replay is not None: + return replay + checks = self._submission_checks(command, self.projects.snapshot(command.projectId)) def accept(before): - data = before.model_dump(mode='json') - spec_data = CreationCanvas._get(data, 'generation_spec', command.payload.specId) - if sum(j.inputSnapshot.spec.id == command.payload.specId and j.status in {'queued', 'running'} for j in before.jobs) >= 8: - raise ContractError('revision_conflict', '该配置的排队任务已达上限,请等待或取消原任务。', command.payload.specId) - if command.payload.previousJobId: - previous = next((j for j in before.jobs if j.id == command.payload.previousJobId), None) - if previous is None or previous.inputSnapshot.spec.id != command.payload.specId: - raise ContractError('invalid_input', '新尝试必须关联同一生成配置的原任务。', command.payload.previousJobId) - origin = command.payload.originItemId - material = None - if origin: - item = CreationCanvas._editable(data, origin) - material = item['binding'].get('materialOverride') - spec_data['purpose'] = 'generation' - item['binding'] = dict(role='generation', objectRef=dict(objectType='generation_spec', id=spec_data['id']), materialOverride=material) - if item != next(i.model_dump(mode='json') for i in before.canvasItems if i.id == origin): - item['revision'] += 1 - elif spec_data['purpose'] == 'draft': - spec_data['purpose'] = 'generation' - # Promote every owner of this draft together, including hidden ones. - for item in data['canvasItems']: - # An empty binding serialises draftSpec as null, not absent. - if (item['binding'].get('draftSpec') or {}).get('id') == spec_data['id']: - item['binding'] = dict(role='generation', objectRef=dict(objectType='generation_spec', id=spec_data['id'])) - item['revision'] += 1 - old = next(s for s in before.generationSpecs if s.id == command.payload.specId) - if spec_data['purpose'] != old.purpose: - spec_data['revision'] += 1 - intermediate = ProjectSnapshot.model_validate(data) - spec = next(s for s in intermediate.generationSpecs if s.id == old.id) - config = self.configs.resolve(str(spec.modelConfigId), 'agent' if spec.kind == 'text' else spec.kind) - public = ModelConfigPublic.model_validate({key: value for key, value in config.items() if key != 'apiKey'} | {'inputRules': self.availability.effective_input_rules(config)}) - spec, resolved = current_generation_inputs(intermediate, spec, public.inputRules) - spec = execution_spec(spec, resolved, public.inputRules) - try: - validate_generation(spec, public, resolved, submitting=True) - if spec.kind == 'audio' and spec.parameters.creationType == 'audio': - if old != voice_spec or config != voice_config: - raise ContractError('revision_conflict', '音色验证期间生成配置或模型服务已变化,请重新提交。', spec.id) - if voice_failure is not None: - raise voice_failure - if capability_failure is not None: - raise capability_failure - if capability_identity is not None: - self.availability.require(config, generation_request(config, spec, resolved), capability_identity) - except (ValueError, ProjectError) as error: - raise ContractError.from_error(error, spec.id) from error - for reference in resolved: - if reference.transmission != 'context_only': - self.assets.reference_available(command.projectId, reference.asset.assetId) - self.provider.validate(spec.kind, config) - snapshot = InputSnapshot(spec=spec.model_copy(update={'currentResultId': None}), - model=ModelSnapshot(modelConfigId=public.id, inputRules=public.inputRules, - **{k: getattr(public, k) for k in ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'proxyMode', 'videoAdapter')}), references=resolved) - # Use the same rendering, protocol validation and parameter resolver - # as the established adapters, with immutable media from the facade. - stub = Job(id=uuid5(command.commandId, 'job'), projectId=command.projectId, inputSnapshot=snapshot, - createdAt=datetime.now(timezone.utc), - inputFingerprint=snapshot.fingerprint(), execution={'kind': spec.kind, **({'size': '2K'} if spec.kind == 'image' else {'format': 'mp3', 'sampleRate': 24000} if spec.kind == 'audio' else {})}, - originItemId=origin, previousJobId=command.payload.previousJobId, - **({'agentRunId': agent_origin[0], 'agentCallId': agent_origin[1]} if agent_origin else {}), - adoptionPolicy=command.payload.adoptionPolicy, adoptionResultId=old.currentResultId, adoptionMaterial=material, - batchId=command.payload.batchId, showAdditionalResult=command.payload.showAdditionalResult) - task = self.task(stub) - records = {str(a.id): media_record(a) for a in before.assets} - try: - if hasattr(self.provider, 'prepare_inputs'): - self.provider.prepare_inputs(str(command.projectId), task, config) - parameters = self._parameters(spec, config, task, records) - if capability_identity is not None: - self.availability.require(config, generation_request(config, spec, resolved, parameters=parameters), capability_identity) - except ProjectError as error: - raise ContractError.from_error(error, spec.id) from error - job = Job.model_validate({**stub.model_dump(), 'adapterParameters': parameters, 'execution': self._execution(spec.kind, parameters, config)}) - data['jobs'].append(job.model_dump(mode='json')) - return ProjectSnapshot.model_validate(data) - return self.projects.commit(command, accept, session=session, source=source) + if review is not None: + validate_command(command, before) + elif command.payload.specId in creation_spend.pending_workflow_specs(before) or any(r.status == 'pending' and ( + command.payload.batchId is not None and command.payload.batchId in (r.id, r.batchId, r.workflowId) + or r.specId == command.payload.specId and command.payload.count < r.quote.count + ) for r in before.spendRequests): + raise ContractError('spend_quote_changed', 'Review or cancel the pending batch before submitting one of its members.') + data, job, config, task, records = self._propose_job(before, command, agent_origin=agent_origin, checks=checks) + if command.payload.count > 1 and job.inputSnapshot.spec.kind not in {'image', 'video'}: + raise ContractError('invalid_input', 'Multiple candidates require an image or video model.') + quote = self._quote_job(job, config, task, records, command.payload.count) + decision = creation_spend.decide(before, command, quote, agent_origin, review) + if review is None and decision is not before: + return decision + data['project'] = decision.project.model_dump(mode='json') + data['spendRequests'] = decision.spendRequests + return self._append_candidates(before, data, command, job, config, quote) + return self.projects.commit(review or command, accept, session=session, source=source) async def execute(self, command, *, session=None, source='ui', agent_origin=None): - if command.type == 'generation.submit': - pending = asyncio.create_task(asyncio.to_thread(self.prepare, command, session=session, source=source, agent_origin=agent_origin)) + if command.type == 'spend.policy': + if source != 'ui': + raise ProjectError('请在工程窗口中确认费用。', 403, code='spend_human_review') + return await asyncio.to_thread(self.projects.commit, command, + lambda before: creation_spend.save_policy(before, command.payload), session=session) + original, review = command, None + if command.type == 'spend.review': + if source != 'ui': + raise ProjectError('请在工程窗口中确认费用。', 403, code='spend_human_review') + replay = self.projects.replay(command) + if replay: + return replay + request = creation_spend.get_request(self.projects.snapshot(command.projectId), command.payload.requestId) + if request.status != 'pending': + raise ProjectError('该费用请求已经处理,请查看工程费用记录。', 409, code='spend_reviewed') + if command.payload.decision == 'cancel': + def cancel_request(before): + current = creation_spend.get_request(before, request.id) + if current.status != 'pending' or current.quote.fingerprint() != command.payload.fingerprint: + raise ContractError('spend_quote_changed', 'The request changed.') + return creation_spend.resolve(before, current, command.commandId, 'cancelled') + return await asyncio.to_thread(self.projects.commit, command, cancel_request, session=session) + original = next(r.command for r in self.projects.records(command.projectId) if r.command.commandId == request.id) + agent_origin = (request.agentRunId, request.agentCallId) if request.agentRunId else None + review = command + if original.type == 'spend.tool' and self.tools is not None: + await self.tools.resume_spend(str(command.projectId), original.payload.request, session, review) + return self.projects.replay(review) + if original.type in {'generation.group', 'spend.advanceGroup'}: + return await creation_groups.execute(self, original, session=session, source=source, agent_origin=agent_origin, review=review) + if original.type == 'generation.submit': + pending = asyncio.create_task(asyncio.to_thread(self.prepare, original, session=session, source=source, + agent_origin=agent_origin, review=review)) async def finish(): try: receipt = await pending @@ -479,6 +609,19 @@ def control(before): def checkpoint(self, project_id, task, pinned): before = self.projects.snapshot(project_id) job = next(j for j in before.jobs if str(j.id) == task['id']) + calls = [call for call in before.spendCalls if call.ownerId == job.id] + if calls: + if not job.adapterParameters.get('score_model') and task.get('status') == 'running' and task.get('phase') in {'submit', 'poll'}: + creation_spend.observe(self.projects, project_id, calls[0].id, 'submitted') + if task.get('phase') in {'download', 'save', 'adopt', 'complete'} and task.get('status') in {'running', 'succeeded'}: + creation_spend.observe(self.projects, project_id, calls[-1].id, 'completed') + # A queued task can still submit after restart or model configuration + # repair. Keep its accepted budget until execution or explicit cancellation. + recoverable_queue = task.get('phase') == 'queued' and task.get('status') != 'cancelled' and not job.cancelRequested + if task.get('status') in {'cancelled', 'failed', 'interrupted'} and not recoverable_queue: + for call in calls: + if call.state == 'reserved': + creation_spend.observe(self.projects, project_id, call.id, 'released') if job.status == 'succeeded': return changes = {key: task[key] for key in ('status', 'phase', 'recovery', 'resumeAllowed', 'externalTaskId', 'errorDetails', 'technicalCheck') if key in task} @@ -599,6 +742,11 @@ def apply(current, asset): code='revision_conflict' if conflict else 'operation_rejected') result = self._result_asset(task, pinned) task['adopted'] = self.get_job(job.projectId, job.id).adopted + duration = result.get('durationMs') if result else None + if duration is not None: + slot = int(bool(job.adapterParameters.get('score_model'))) + creation_spend.observe(self.projects, job.projectId, uuid5(job.id, f'spend:{slot}'), 'completed', + evidence='media', unit='output_second', usage=Decimal(duration) / 1000) return result @staticmethod @@ -693,7 +841,8 @@ async def cancel(self, project_id, job_id, session): category='temporary', stage='cancel', message='供应商取消未确认。', suggestion='请在服务控制台核对原任务和费用。').model_dump(mode='json')) self.checkpoint(project_id, task, str(self.directory(project_id))) job = self.get_job(project_id, job_id) - if job and job.status in {'queued', 'running'} and job_id not in self.committing: + if job and job_id not in self.committing and (job.status in {'queued', 'running'} or + job.phase == 'queued' and job.status in {'interrupted', 'failed'}): task = self.task(job) task.update(status='cancelled', recovery=self.recovery(task, str(self.directory(project_id))), resumeAllowed=False) self.checkpoint(project_id, task, str(self.directory(project_id))) @@ -701,14 +850,21 @@ async def cancel(self, project_id, job_id, session): async def start(self): for project in self.projects.list_projects()['projects']: - for job in self.projects.snapshot(project['id']).jobs: + snapshot = self.projects.snapshot(project['id']) + for job in snapshot.jobs: if job.status in {'queued', 'running', 'interrupted'} or job.status == 'failed' and job.resumeAllowed: if job.cancelRequested: await self.cancel(project['id'], str(job.id), None) else: await self.recover(project['id'], str(job.id)) + for workflow in {r.workflowId for r in snapshot.spendRequests if r.workflowId}: + creation_groups.watch(self, snapshot.project.id, workflow) + async def close(self): + for worker in list(self.group_workers.values()): + worker.cancel() + await asyncio.gather(*list(self.group_workers.values()), return_exceptions=True) await asyncio.gather(*list(self.accepting.values()), return_exceptions=True) workers = list(self.jobs.values()) for worker in workers: diff --git a/packages/core/src/opendirector/application/creation_groups.py b/packages/core/src/opendirector/application/creation_groups.py new file mode 100644 index 000000000..da2a15a12 --- /dev/null +++ b/packages/core/src/opendirector/application/creation_groups.py @@ -0,0 +1,194 @@ +"""Price runnable workflow members together and continue from their adopted outputs.""" +import asyncio +import logging +from datetime import datetime, timezone +from graphlib import CycleError, TopologicalSorter +from hashlib import sha256 +from uuid import uuid5 + +from opendirector.application import creation_spend +from opendirector.domain.creation.commands import parse_command +from opendirector.domain.creation.spend import SpendQuote, SpendRequest +from opendirector.domain.creation.validation import ContractError, validate_command + + +def _member(snapshot, member, workflow): + spec = next((s for s in snapshot.generationSpecs if s.id == member.specId), None) + item = next((i for i in snapshot.canvasItems if i.id == member.itemId), None) + if item is None or spec is None: + raise ContractError('missing_object', 'A workflow member no longer exists.', member.itemId) + binding = item.binding + spec_ref = binding.objectRef if binding.role == 'generation' else getattr(binding, 'draftSpec', None) + if spec_ref is None or spec_ref.id != spec.id: + raise ContractError('invalid_input', 'Workflow member does not own this generation specification.', item.id) + return parse_command(dict(type='generation.submit', projectId=snapshot.project.id, commandId=uuid5(workflow, str(item.id)), + expectedVersions=[dict(objectType='generation_spec', id=spec.id, revision=spec.revision), + dict(objectType='canvas_item', id=item.id, revision=item.revision)], + payload=dict(specId=spec.id, expectedSpecRevision=spec.revision, originItemId=item.id, count=member.count, batchId=workflow))) + + +def _next_members(members, admitted=(), finished=()): + # graphlib still yields every reachable node after detecting a cycle. + graph = TopologicalSorter({m.itemId: m.after for m in members}) + try: + graph.prepare() + except CycleError: + pass + finished = set(finished) + failed = set(admitted) - finished + reachable = set() + while nodes := graph.get_ready(): + ready = [item for item in nodes if item not in failed] + reachable.update(ready) + graph.done(*ready) + remaining = [m for m in members if m.itemId not in admitted] + ready = [m for m in remaining if m.itemId in reachable and set(m.after) <= finished] + ready_ids = {m.itemId for m in ready} + return (ready, [m.itemId for m in remaining if m.itemId in reachable and m.itemId not in ready_ids], + [m.itemId for m in remaining if m.itemId not in reachable]) + + +def _wave(snapshot, plan): + workflow = plan.commandId + decisions = [r for r in snapshot.spendRequests if r.workflowId == workflow] + jobs = [j for j in snapshot.jobs if j.batchId == workflow] + if any(r.status != 'accepted' for r in decisions) or any(j.status in {'queued', 'running'} for j in jobs): + return [], [], [] + admitted = {item for request in decisions for item in request.groupItems} + finished = {j.originItemId for j in jobs if j.adopted and j.status == 'succeeded'} + return _next_members(plan.payload.members, admitted, finished) + + +def _price_members(runtime, before, workflow, members, deferred, skipped, *, checks=None, origin=None, from_upstream=False): + draft = before + lines, prints = [], [] + candidates = 0 + for m in members: + member = _member(before, m, workflow) + validate_command(member, before) + data, job, config, task, records = runtime._propose_job(draft, member, agent_origin=origin, checks=checks.get(m.itemId) if checks is not None else None) + if m.count > 1 and job.inputSnapshot.spec.kind not in {'image', 'video'}: + raise ContractError('invalid_input', 'Multiple candidates require an image or video model.', m.specId) + quote = runtime._quote_job(job, config, task, records, m.count) + if checks is not None: + draft = runtime._append_candidates(draft, data, member, job, config, quote) + lines.extend(quote.lines * m.count) + prints.append(str(m.itemId) + ':' + quote.fingerprint()) + candidates += m.count + quote = SpendQuote(count=1, candidates=candidates, deferred=deferred, skipped=skipped, fromUpstream=from_upstream, + inputFingerprint=sha256('|'.join(prints).encode()).hexdigest(), lines=lines) + return draft, quote + + +def preview(runtime, query): + before = runtime.projects.snapshot(query.projectId) + ready, deferred, skipped = _next_members(query.workflow.members) + _, quote = _price_members(runtime, before, query.queryId, ready, deferred, skipped) + return creation_spend.quote_view(before, quote) + + +def _prepare(runtime, command, plan, session, source, origin, review): + projects = runtime.projects + replay = projects.replay(review or command) + if replay is not None: + return replay + initial = projects.snapshot(command.projectId) + if review: + request = creation_spend.get_request(initial, review.payload.requestId) + members = [m for m in plan.payload.members if m.itemId in request.groupItems] + deferred, skipped = request.quote.deferred, request.quote.skipped + else: + members, deferred, skipped = _wave(initial, plan) + checks = {m.itemId: runtime._submission_checks(_member(initial, m, plan.commandId), initial) for m in members} + def apply(before): + if review: + validate_command(command, before) + if review is None: + spec_ids = {m.specId for m in plan.payload.members} + pending_specs = creation_spend.pending_workflow_specs(before) + pending_specs.update(r.specId for r in before.spendRequests if r.status == 'pending') + if command.type == 'generation.group': + pending_specs.update(j.inputSnapshot.spec.id for j in before.jobs if j.batchId and j.status in {'queued', 'running'}) + if spec_ids.intersection(pending_specs): + raise ContractError('spend_quote_changed', 'Review the pending request for these workflow members first.') + if not members: + raise ContractError('invalid_input', 'No workflow step has all its upstream results.') + ready_ids = tuple(m.itemId for m in members) + if command.type == 'spend.advanceGroup' and set(ready_ids) != set(command.payload.items): + raise ContractError('revision_conflict', 'The runnable workflow steps have changed.') + draft, quote = _price_members(runtime, before, plan.commandId, members, deferred, skipped, checks=checks, + origin=origin, from_upstream=command.type == 'spend.advanceGroup') + decision = creation_spend.decide(before, command, quote, origin, review) + if review is None and decision is not before: + waiting = decision.spendRequests[-1].model_copy(update=dict(workflowId=plan.commandId, groupItems=ready_ids)) + return decision.model_copy(update={'spendRequests': (*decision.spendRequests[:-1], waiting)}) + requests = decision.spendRequests + if review is None: + requests = (*requests, SpendRequest(id=command.commandId, projectId=command.projectId, versions=command.expectedVersions, + createdAt=datetime.now(timezone.utc), status='accepted', workflowId=plan.commandId, groupItems=ready_ids, + agentRunId=origin[0] if origin else None, agentCallId=origin[1] if origin else None, quote=quote)) + return draft.model_copy(update={'project': decision.project, 'spendRequests': requests}) + return projects.commit(review or command, apply, session=session, source=source) + + +def _plan(projects, project_id, workflow): + return next(r.command for r in projects.records(project_id) if r.command.commandId == workflow) + + +async def execute(runtime, command, *, session, source, agent_origin=None, review=None): + plan = command if command.type == 'generation.group' else await asyncio.to_thread( + _plan, runtime.projects, command.projectId, command.payload.workflowId) + async def accept(): + receipt = await asyncio.to_thread(_prepare, runtime, command, plan, session, source, agent_origin, review) + for job in receipt.jobIds: + await runtime.recover(str(command.projectId), str(job)) + if receipt.jobIds: + watch(runtime, command.projectId, plan.commandId) + return receipt + key = (str(command.projectId), str((review or command).commandId)) + work = asyncio.create_task(accept()) + runtime.accepting[key] = work + def completed(done): + if runtime.accepting.get(key) is done: + runtime.accepting.pop(key) + if not done.cancelled(): + done.exception() + work.add_done_callback(completed) + return await asyncio.shield(work) + + +def watch(runtime, project_id, workflow): + if workflow in runtime.group_workers: + return + async def advance(): + plan = await asyncio.to_thread(_plan, runtime.projects, project_id, workflow) + while True: + snapshot = await asyncio.to_thread(runtime.projects.snapshot, project_id) + current = [j for j in snapshot.jobs if j.batchId == workflow and j.status in {'queued', 'running'}] + if current: + futures = [runtime.jobs[str(j.id)].future for j in current if str(j.id) in runtime.jobs] + if futures: + await asyncio.gather(*(asyncio.shield(f) for f in futures), return_exceptions=True) + else: + await asyncio.sleep(1) + continue + members, _, _ = _wave(snapshot, plan) + if not members: + return + ids = [m.itemId for m in members] + versions = [v for m in members for v in _member(snapshot, m, workflow).expectedVersions] + command = parse_command(dict(type='spend.advanceGroup', projectId=project_id, + commandId=uuid5(workflow, 'advance:' + ','.join(map(str, ids))), expectedVersions=versions, + payload=dict(workflowId=workflow, items=ids))) + initial = creation_spend.get_request(snapshot, workflow) + origin = (initial.agentRunId, initial.agentCallId) if initial.agentRunId else None + receipt = await execute(runtime, command, session=None, source='background', agent_origin=origin) + if not receipt.jobIds: + return + worker = asyncio.create_task(advance()) + runtime.group_workers[workflow] = worker + def finished(done): + runtime.group_workers.pop(workflow, None) + if not done.cancelled() and (error := done.exception()) is not None: + logging.getLogger(__name__).error('Workflow continuation failed: %s', workflow, exc_info=error) + worker.add_done_callback(finished) diff --git a/packages/core/src/opendirector/application/creation_spend.py b/packages/core/src/opendirector/application/creation_spend.py new file mode 100644 index 000000000..2f8b5e0ba --- /dev/null +++ b/packages/core/src/opendirector/application/creation_spend.py @@ -0,0 +1,174 @@ +"""Project-scoped admission. All callers invoke these decisions under the project commit lock.""" +from collections import defaultdict +from datetime import datetime, timezone +from uuid import uuid4, uuid5 + +from opendirector.domain.creation.index import object_index +from opendirector.domain.creation.spend import SpendCall, SpendPolicy, SpendRequest, call_totals, cap_adjustment, spend_decision, spend_math, spend_summary +from opendirector.domain.creation.validation import ContractError +from opendirector.domain.creation.commands import parse_command +from opendirector.domain.creation.spend import SpendObservation, observed_call +from opendirector.domain.projects import ProjectError + + +def quote_view(snapshot, quote): + summary = spend_summary(snapshot) + total = quote.total(summary['policy'].currency) + with spend_math(): + after = None if total is None or summary['unknown'] else summary['settled'] + summary['held'] + total + return dict(quote=quote, fingerprint=quote.fingerprint(), amount=total, subtotals=quote.subtotals(), projectAfter=after, + currency=summary['policy'].currency, reason=spend_decision(summary, quote)) + + +def workflow_status(snapshot, agent_run_id=None): + requests = defaultdict(list) + for request in snapshot.spendRequests: + if request.workflowId and (agent_run_id is None or request.agentRunId == agent_run_id): + requests[request.workflowId].append(request) + jobs = defaultdict(list) + for job in snapshot.jobs: + if job.batchId in requests: + jobs[job.batchId].append(job) + results = [] + for workflow_id, decisions in requests.items(): + first, latest = decisions[0], decisions[-1] + members = set((*first.groupItems, *first.quote.deferred, *first.quote.skipped)) + admitted = {item for decision in decisions if decision.status == 'accepted' for item in decision.groupItems} + completed = {job.originItemId for job in jobs[workflow_id] if job.adopted and job.status == 'succeeded'} + active = {job.originItemId for job in jobs[workflow_id] if job.status in {'queued', 'running'}} + failed = admitted - completed - active + skipped = set(latest.quote.skipped) + if latest.status in {'pending', 'cancelled'}: + state = 'waiting' if latest.status == 'pending' else 'cancelled' + elif active or (members - admitted - skipped and not failed): + state = 'running' + elif failed or skipped: + state = 'incomplete' + skipped = members - admitted + else: + state = 'completed' + results.append(dict(id=workflow_id, items=sorted(members), state=state, completed=len(completed), + failed=len(failed), skipped=len(skipped), total=len(members))) + return results + + +def review_status(snapshot, agent_run_id=None): + summary = spend_summary(snapshot) + policy = summary['policy'] + pending = [] + requests = [request for request in snapshot.spendRequests if request.status == 'pending'] + objects = object_index(snapshot) if any(request.versions for request in requests) else {} + for request in requests: + total = request.quote.total(policy.currency) + reason = spend_decision(summary, request.quote) + if request.currency and request.currency != policy.currency: + reason = 'stale' + elif any(getattr(objects.get((v.objectType, v.id)), 'revision', None) != v.revision for v in request.versions): + reason = 'stale_inputs' + shortfall, suggested = cap_adjustment(policy.cap, summary['available'], total) if reason == 'over_cap' else (None, None) + pending.append(dict(request=request, fingerprint=request.quote.fingerprint(), reason=reason, amount=total, + subtotals=request.quote.subtotals(), shortfall=shortfall, + suggestedCap=suggested)) + result = dict(**summary, projectRevision=snapshot.project.revision, pending=pending, workflows=workflow_status(snapshot, agent_run_id)) + settled_owners = {c.ownerId for c in snapshot.spendCalls if c.state == 'completed' and c.line.price is not None + and c.line.price.currency == policy.currency and (c.reported is not None or c.calculated is not None)} + settled_jobs = [job for job in snapshot.jobs if job.id in settled_owners] + if (settled_jobs and len(settled_jobs) == len(settled_owners) + and len({job.batchId or job.id for job in settled_jobs}) == 1 + and len({job.execution.kind for job in settled_jobs}) == 1 + and all(job.status == 'succeeded' for job in settled_jobs)): + result['settledBatch'] = dict(kind=settled_jobs[0].execution.kind, count=len(settled_jobs)) + if agent_run_id is not None: + owners = {j.id for j in snapshot.jobs if j.agentRunId == agent_run_id} + calls = [call for call in snapshot.spendCalls if call.ownerId in owners] + result['turn'] = dict(callCount=len(calls), **call_totals(calls, policy.currency)) + return result + + +def save_policy(before, policy): + if policy == (before.project.spendPolicy or SpendPolicy()): + return before + return before.model_copy(update={'project': before.project.model_copy(update={ + 'spendPolicy': policy, 'revision': before.project.revision + 1})}) + + +def get_request(snapshot, request_id): + request = next((r for r in snapshot.spendRequests if r.id == request_id), None) + if request is None: + raise ContractError('missing_object', 'Spend request does not exist.', request_id) + return request + + +def pending_workflow_specs(snapshot): + item_ids = {item_id for request in snapshot.spendRequests if request.workflowId and request.status == 'pending' + for item_id in (*request.groupItems, *request.quote.deferred)} + specs = set() + for item in snapshot.canvasItems: + if item.id in item_ids: + binding = item.binding + ref = binding.objectRef if binding.role == 'generation' else getattr(binding, 'draftSpec', None) + if ref: + specs.add(ref.id) + return specs + + +def decide(before, command, quote, agent_origin, review=None): + summary = spend_summary(before) + reason = spend_decision(summary, quote) + if review is None: + if reason == 'ready': + return before + request = SpendRequest(id=command.commandId, projectId=command.projectId, quote=quote, versions=command.expectedVersions, + currency=summary['policy'].currency, specId=getattr(command.payload, 'specId', None), batchId=getattr(command.payload, 'batchId', None), + createdAt=datetime.now(timezone.utc), agentRunId=agent_origin[0] if agent_origin else None, + agentCallId=agent_origin[1] if agent_origin else None) + return before.model_copy(update={'spendRequests': (*before.spendRequests, request)}) + selection = review.payload + request = get_request(before, selection.requestId) + if request.currency is not None and request.currency != summary['policy'].currency: + raise ContractError('spend_quote_changed', 'The project currency changed. Request a new estimate.') + if request.status != 'pending' or selection.fingerprint != request.quote.fingerprint() or selection.fingerprint != quote.fingerprint(): + raise ContractError('spend_quote_changed', 'The request or its price changed. Request a new estimate.') + if reason == 'prior_unknown': + raise ContractError('spend_unknown', 'Earlier charges cannot be totalled in the project currency.') + if reason == 'unpriced' or (reason == 'unknown_confirmation' and not selection.acceptUnknown): + raise ContractError('spend_unknown', 'A bounded price in the project currency is required.') + if selection.newCap is not None: + policy = summary['policy'] + if reason != 'over_cap' or policy.cap is None or selection.newCap <= policy.cap: + raise ContractError('spend_quote_changed', 'The available budget changed. Review the current balance.') + before = save_policy(before, policy.model_copy(update={'cap': selection.newCap})) + reason = spend_decision(spend_summary(before), quote) + if reason == 'over_cap': + raise ContractError('spend_cap', 'The batch exceeds the available project budget.') + return resolve(before, request, review.commandId, 'accepted') + + +def resolve(before, request, decision_id, status): + updated = request.model_copy(update=dict(revision=request.revision + 1, decisionId=decision_id, status=status)) + return before.model_copy(update={'spendRequests': tuple(updated if r.id == request.id else r for r in before.spendRequests)}) + + +def observe(projects, project_id, call_id, state, **facts): + observation = SpendObservation(callId=call_id, state=state, **facts) + with projects.local.transaction(): + snapshot = projects.snapshot(project_id) + call = next((c for c in snapshot.spendCalls if c.id == observation.callId), None) + if call is None: + return # Historical jobs have no agreed rate. + edited = observed_call(call, observation) + if edited == call: + return + command = parse_command(dict(commandId=uuid4(), projectId=project_id, type='spend.observe', payload=observation, + expectedVersions=[dict(objectType='spend_call', id=call.id, revision=call.revision)])) + def apply(current): + return current.model_copy(update={'spendCalls': tuple(edited if c.id == call.id else c for c in current.spendCalls)}) + receipt = projects.commit(command, apply, source='background') + if receipt.status == 'rejected': + raise ProjectError(receipt.issues[0].message, 409) + + +def reserve_calls(owner_id, project_id, quote): + now = datetime.now(timezone.utc) + return tuple(SpendCall(id=uuid5(owner_id, f'spend:{slot}'), ownerId=owner_id, + projectId=project_id, line=line, createdAt=now) for slot, line in enumerate(quote.lines)) diff --git a/packages/core/src/opendirector/application/tool_context.py b/packages/core/src/opendirector/application/tool_context.py index 6fdce8f5b..00975841c 100644 --- a/packages/core/src/opendirector/application/tool_context.py +++ b/packages/core/src/opendirector/application/tool_context.py @@ -39,6 +39,10 @@ def __init__(self, message, *, code, label): super().__init__(message, 422, code=code) self.params = {'label': label} +def concept_parts(text): + return list(dict.fromkeys(item.strip() for item in re.split(r'[,,、;;\n]+', text) if item.strip()))[:16] + + class ToolContext: """What a recipe may use: inputs, model capabilities and progress reporting.""" @@ -121,11 +125,11 @@ async def depth(self, clip: bytes) -> bytes: async def concepts(self, text: str, default: tuple[str, ...]) -> list[tuple[str, str]]: """(English concept, label) pairs from a comma-separated description; segmentation models read English.""" - parts = list(dict.fromkeys(item.strip() for item in re.split(r'[,,、;;\n]+', text) if item.strip())) + parts = concept_parts(text) if not parts: return [(CONCEPTS.get(item, item), item) for item in default] pairs = [] - for part in parts[:16]: + for part in parts: english = CONCEPTS.get(part) or (part if part.isascii() else None) if english is None and self._chat is not None: try: diff --git a/packages/core/src/opendirector/application/tool_spend.py b/packages/core/src/opendirector/application/tool_spend.py new file mode 100644 index 000000000..3ad23ae72 --- /dev/null +++ b/packages/core/src/opendirector/application/tool_spend.py @@ -0,0 +1,130 @@ +"""Price the model calls in a frozen tool recipe, including optional translation.""" +from datetime import datetime, timezone +from decimal import Decimal +from uuid import UUID, uuid5 + +from opendirector.application import creation_spend +from opendirector.application.tool_context import CONCEPTS, concept_parts +from opendirector.application.tool_image_edits import PRESETS +from opendirector.application.tool_image_segments import SMART_LAYERS +from opendirector.domain.creation.base import digest +from opendirector.domain.creation.commands import parse_command +from opendirector.domain.creation.spend import SpendCall, SpendQuote, SpendRequest, ToolSpendInput, price_line, video_units +from opendirector.domain.projects import ProjectError + + +def tool_quote(task, records): + models = task['modelSnapshots'] + parameters = task['parameters'] + tool = task['tool'] + prompt = parameters.get('prompt', '') + prompt = prompt.strip() if isinstance(prompt, str) else '' + parts = concept_parts(prompt) + boxes = task.get('boxes') or [] + counts = {capability: 1 for capability in models} + if 'text.chat' in counts: + counts['text.chat'] = 0 + if tool in {'cutout', 'layer-decompose', 'video-matting', 'selection-preview'}: + if tool == 'layer-decompose': + mode = parameters.get('mode', 'smart') + parts = parts if mode == 'description' else [] + boxes = boxes if mode == 'boxes' else [] + if 'image.segment' in counts: + counts['image.segment'] = len(boxes) or len(parts) or len(SMART_LAYERS) + if 'text.chat' in counts and not boxes: + counts['text.chat'] = sum(not part.isascii() and part not in CONCEPTS for part in parts) + elif tool in {'video-edit', 'video-partial-reshoot', 'video-subtitle-erasure', 'dynamic-poster'} and 'text.chat' in counts: + counts['text.chat'] = int(bool(prompt) and not prompt.isascii()) + if tool == 'image-presets' and 'image.edit' in counts: + preset = PRESETS.get(parameters.get('preset', 'three-view')) + if preset is not None: + counts['image.edit'] = len(preset.prompts) + if tool == 'image-hd' and 'image.edit' in counts: + counts['image.edit'] = len(task['sourceAssetIds']) + execution = task.get('videoExecution') or {} + pieces = execution.get('pieces', ()) + wire_requests = execution.get('requests', ()) + if pieces and 'video.edit' in counts: + counts['video.edit'] = len(pieces) + source = records[task['sourceAssetIds'][0]] + lines = [] + for capability, count in counts.items(): + for index in range(count): + units = {} + if capability in {'video.matting', 'video.motion_capture'} and source.get('durationMs') is not None: + units['input_second'] = Decimal(source['durationMs']) / 1000 + if capability == 'video.edit' and pieces: + start, end = pieces[index] + units['input_second'] = Decimal(str(round(end-start, 6))) + units.update(video_units(wire_requests[index], units['input_second'])) + elif capability == 'video.first_frame' and tool == 'dynamic-poster': + units.update(video_units(wire_requests[0] if wire_requests else {}, 5)) + lines.append(price_line(models[capability], capability, units)) + inputs = {key: value for key, value in task.items() if key in { + 'id', 'tool', 'sourceAssetIds', 'maskAssetId', 'annotationAssetId', 'boxes', 'parameters', 'modelConfigIds', + 'modelSnapshots', 'imageExecution', 'videoExecution', 'inputSnapshot', 'draftBinding', 'canvas'}} + inputs['fingerprints'] = {key: records[key]['fingerprint'] for key in + [*task['sourceAssetIds'], task.get('maskAssetId'), task.get('annotationAssetId')] if key} + return SpendQuote(count=1, inputFingerprint=digest(ToolSpendInput(request=inputs)), lines=lines) + + +def pending_receipt(task, admission): + return dict(id=task['id'], projectId=task['projectId'], status='awaiting_confirmation', spendRequestId=str(admission.id)) + + +def admit(projects, value, task, records, session, review=None): + owner = UUID(task['id']) + pid = UUID(task['projectId']) + command = parse_command(dict(type='spend.tool', projectId=pid, commandId=uuid5(owner, 'tool-spend'), + payload=dict(request=value))) + quote = tool_quote(task, records) + if not quote.lines and review is None: + return None + def apply(before): + decided = creation_spend.decide(before, command, quote, None, review) + if review is not None: + return decided.model_copy(update={'spendCalls': (*decided.spendCalls, *creation_spend.reserve_calls(owner, pid, quote))}) + if decided is before: + record = SpendRequest(id=command.commandId, projectId=pid, versions=(), quote=quote, toolTask=task, + status='accepted', createdAt=datetime.now(timezone.utc)) + return before.model_copy(update={'spendRequests': (*before.spendRequests, record), + 'spendCalls': (*before.spendCalls, *creation_spend.reserve_calls(owner, pid, quote))}) + queued = decided.spendRequests[-1].model_copy(update={'toolTask': task}) + return decided.model_copy(update={'spendRequests': (*decided.spendRequests[:-1], queued)}) + receipt = projects.commit(review or command, apply, session=session) + if receipt.status == 'rejected': + raise ProjectError(receipt.issues[0].message, 409, code=receipt.issues[0].code) + return creation_spend.get_request(projects.snapshot(pid), command.commandId) + + +def begin_call(projects, project_id, task_id, capability, ordinal, model=None): + snapshot = projects.snapshot(project_id) + calls = [call for call in snapshot.spendCalls if str(call.ownerId) == task_id and call.line.operation == capability] + if not calls and not any(r.id == uuid5(UUID(task_id), 'tool-spend') for r in snapshot.spendRequests): + return None + if ordinal >= len(calls) and model is not None: + line = price_line(model(), capability, {}) + if line.amount == 0: + # A free extension can arise in older tool recipes. Keep the physical call visible. + owner = UUID(task_id) + call = SpendCall(id=uuid5(owner, f'extra:{capability}:{ordinal}'), projectId=project_id, ownerId=owner, + line=line, state='submitted', createdAt=datetime.now(timezone.utc)) + record = parse_command(dict(type='spend.observe', projectId=project_id, commandId=uuid5(call.id, 'submitted'), + payload=dict(callId=call.id, state='submitted'))) + receipt = projects.commit(record, lambda before: before.model_copy(update={'spendCalls': (*before.spendCalls, call)}), + source='background') + if receipt.status != 'rejected': + return call.id + if ordinal >= len(calls): + raise ProjectError('工具需要执行超出已确认报价的模型调用,请重新核对费用。', 409, code='spend_quote_changed') + call = calls[ordinal] + if call.state != 'reserved': + raise ProjectError('该工具的模型调用已经提交,请查看工程费用记录。', 409, code='spend_call_submitted') + creation_spend.observe(projects, project_id, call.id, 'submitted') + return call.id + + +def release_unused(projects, project_id, task_id): + for call in projects.snapshot(project_id).spendCalls: + if str(call.ownerId) == task_id and call.state == 'reserved': + creation_spend.observe(projects, project_id, call.id, 'released') diff --git a/packages/core/src/opendirector/application/tool_task_lifecycle.py b/packages/core/src/opendirector/application/tool_task_lifecycle.py index c11f47df8..6b1fd84a8 100644 --- a/packages/core/src/opendirector/application/tool_task_lifecycle.py +++ b/packages/core/src/opendirector/application/tool_task_lifecycle.py @@ -1,17 +1,22 @@ """Control and recovery of tool executions, separate from read-only queries.""" import asyncio from copy import deepcopy +from decimal import Decimal import logging from uuid import UUID, uuid4, uuid5 from filelock import FileLock, Timeout +from opendirector.domain.capabilities import MediaResult +from opendirector.media.probe import probe from opendirector.domain.generation import GenerationError from opendirector.domain.projects import ProjectError from opendirector.ports.gateway import gateway from opendirector.integrations.model_adapters import adapter_for from opendirector.media.async_work import blocking +from . import creation_spend, tool_spend + logger = logging.getLogger(__name__) TERMINAL = {'succeeded', 'failed', 'cancelled', 'interrupted'} @@ -84,6 +89,8 @@ def _change_call(self, project_id, task_id, call_id, changes): call = next(value for value in calls if value['id'] == call_id) if call['state'] in {'succeeded', 'failed', 'cancelled'}: return task + if changes.get('state') == 'succeeded' and call.get('spendCallId'): + creation_spend.observe(self.projects, project_id, call['spendCallId'], 'completed') call.update(changes) updates = {'modelCalls': calls} if task.get('cancelRequested'): @@ -112,6 +119,11 @@ def begin(): call = dict(id=str(uuid5(UUID(task_id), f'model-call-{len(calls)}')), capability=capability, kind='video' if capability in {'video.generate', 'video.first_frame', 'video.edit'} else 'request', state='submitting', externalTaskId=None, cancellation='not_requested') + ordinal = sum(c['capability'] == capability for c in calls) + spend_id = tool_spend.begin_call(self.projects, project_id, task_id, capability, ordinal, + lambda: self._model(capability, task.get('modelConfigIds', {}).get(capability))[0]) + if spend_id is not None: + call['spendCallId'] = str(spend_id) self._change(project_id, task_id, {'modelCalls': [*calls, call]}) return call call = await blocking(begin) @@ -135,6 +147,16 @@ async def submitted(external_id): or error.details.stage in {'poll', 'download'} and error.details.providerStatus is None) await blocking(self._change_call, project_id, task_id, call['id'], {'state': 'unknown' if unknown else 'failed'}) raise + price = task.get('modelSnapshots', {}).get(capability, {}).get('price') or {} + if (call.get('spendCallId') and price.get('unit') == 'output_second' and + capability in {'video.first_frame', 'video.edit'} and isinstance(result, MediaResult)): + try: + metadata = await blocking(probe, result.data, '.mp4', 'video') + except ProjectError: + metadata = {} + if metadata.get('durationMs') is not None: + await blocking(creation_spend.observe, self.projects, project_id, call['spendCallId'], 'completed', + unit='output_second', usage=Decimal(metadata['durationMs']) / 1000, evidence='media') await blocking(self._change_call, project_id, task_id, call['id'], {'state': 'succeeded'}) return result @@ -337,8 +359,47 @@ async def recover(self): except (OSError, ProjectError): logger.warning('工具远端状态核对未完成:%s', tid, exc_info=True) + def _restore_admissions(self): + """Restore a tool if the worker stopped after the project commit and before the task file.""" + ready = [] + for project in self.projects.list_projects()['projects']: + pid = str(project['id']) + with self.store.transaction(): + directory = self._directory(pid) + snapshot = self.projects.snapshot(pid) + for request in snapshot.spendRequests: + task = request.toolTask + if request.status != 'accepted' or not task: + continue + task_id = task['id'] + if task['tool'] == 'selection-preview': + folder = self.store.state_dir / 'selection-previews' / pid + path = folder / (task_id + '.json') + cached = gateway().read_json(path) if path.is_file() else {} + if cached.get('status') not in {'completed', 'interrupted'} and not self._owner_alive({**task, 'workerId': cached.get('workerId')}): + folder.mkdir(parents=True, exist_ok=True) + gateway().write_json(path, {'status': 'interrupted'}) + tool_spend.release_unused(self.projects, pid, task_id) + continue + if gateway().child(self._folder(directory, create=False), task_id + '.json').is_file(): + continue + task = {**task, 'workerId': self.worker_id} + records = self.assets._records(directory, pid) + calls = [c for c in snapshot.spendCalls if str(c.ownerId) == task_id] + if all(c.state == 'reserved' for c in calls) and all(a in records for a in task['sourceAssetIds']): + self.accepting.add((pid, task_id)) + ready.append((task, directory, records)) + else: + task.update(status='interrupted', localState='stopped', phase=None) + tool_spend.release_unused(self.projects, pid, task_id) + self._write(directory, task) + return ready + async def start(self): await blocking(self._ensure_owner) + for task, directory, records in await blocking(self._restore_admissions): + self._schedule(task, directory, records) + self.accepting.discard((task['projectId'], task['id'])) await self.recover() async def maintain(): while True: diff --git a/packages/core/src/opendirector/application/tool_tasks.py b/packages/core/src/opendirector/application/tool_tasks.py index 68f483efa..88a04b1bf 100644 --- a/packages/core/src/opendirector/application/tool_tasks.py +++ b/packages/core/src/opendirector/application/tool_tasks.py @@ -9,9 +9,10 @@ import base64 from dataclasses import replace from datetime import datetime, timezone -from uuid import UUID, uuid5 +from uuid import UUID, uuid4, uuid5 from PIL import Image +from pydantic_core import to_jsonable_python from opendirector.application.tool_operations import TOOLS, Source, ToolContext, select_image_objects from opendirector.application.model_availability import ModelAvailability, tool_request @@ -27,6 +28,7 @@ from opendirector.media import processing as media from opendirector.media.filenames import with_extension from opendirector.media.async_work import blocking +from . import creation_spend, tool_spend from .tool_task_lifecycle import ToolTaskLifecycle from .tool_video_inputs import video_execution @@ -119,39 +121,99 @@ def _model(self, capability, chosen): config = self.configs.resolve(public['id'], public['kind']) return config, adapter_for(config, self.transport, self.poll_interval) - async def selection_preview(self, project_id, value, session): + def selection_result(self, project_id, task_id, session): + self._directory(project_id, session) + record = creation_spend.get_request(self.projects.snapshot(project_id), uuid5(UUID(task_id), 'tool-spend')) + if (record.toolTask or {}).get('tool') != 'selection-preview': + raise ProjectError('Selection preview not found.', 404) + path = self.store.state_dir / 'selection-previews' / project_id / (task_id + '.json') + cached = gateway().read_json(path) if path.is_file() else {'status': record.status} + return self._cached_selection(path, cached) + + @staticmethod + def _cached_selection(path, cached): + if cached.get('status') == 'completed': + result = path.with_suffix('.mask.json') + return gateway().read_json(result) if result.is_file() else {'status': 'expired'} + return cached + + async def selection_preview(self, project_id, value, session, review=None): """Transient masks for one owned source asset; never creates tasks or output assets.""" source_id = identifier(str(value['sourceAssetId'])) - def read(): + value = {**value, 'id': str(value.get('id') or uuid4())} + task_id = identifier(value['id']) + self._ensure_owner() + config, adapter = self._model('image.segment', value.get('modelConfigId')) + models = {'image.segment': config} + if self.providers().get('text.chat'): + models['text.chat'] = self._model('text.chat', None)[0] + + def prepare(): directory = self._directory(project_id, session) records = self.assets._records(directory, project_id) if source_id not in records or records[source_id]['kind'] != 'image': raise ProjectError('来源图片不存在,请重新上传。', 409) - return media.open_image(self.assets.read_bytes(project_id, source_id)) - - image = await asyncio.to_thread(read) - config, adapter = self._model('image.segment', value.get('modelConfigId')) + task = dict(id=task_id, projectId=project_id, tool='selection-preview', sourceAssetIds=[source_id], + boxes=value.get('boxes') or [], parameters={'prompt': value.get('prompt', '')}, + modelSnapshots={key: {k: v for k, v in model.items() if k not in {'apiKey', 'capabilityAutoCheck', 'availability'}} + for key, model in models.items()}) + with self.store.transaction(): + admission = tool_spend.admit(self.projects, value, task, records, session, review) + if admission.status == 'pending': + return tool_spend.pending_receipt(task, admission), None + if admission.status == 'cancelled': + raise ProjectError('该费用请求已取消,请重新发起任务。', 409, code='spend_cancelled') + folder = self.store.state_dir / 'selection-previews' / project_id + folder.mkdir(parents=True, exist_ok=True) + path = gateway().child(folder, task_id + '.json') + if path.exists(): + saved = gateway().read_json(path) + if saved.get('status') == 'completed': + return self._cached_selection(path, saved), None + raise ProjectError('选区预览已经启动,请先查看工程费用记录再重试。', 409, code='selection_preview_started') + gateway().write_json(path, {'status': 'started', 'workerId': self.worker_id}) + return None, path + + result, path = await blocking(prepare) + if result is not None: + return result + ordinals = {} + async def invoke(capability, fn): + ordinal = ordinals.get(capability, 0) + call_id = await blocking(tool_spend.begin_call, self.projects, project_id, task_id, capability, ordinal) + ordinals[capability] = ordinal + 1 + result = await fn() + await blocking(creation_spend.observe, self.projects, project_id, call_id, 'completed') + return result async def segment(request): - return await adapter.segment(config, request) + return await invoke('image.segment', lambda: adapter.segment(config, request)) async def progress(_): pass chat = None - if self.providers().get('text.chat'): + if 'text.chat' in models: async def chat(request): - chat_config, chat_adapter = self._model('text.chat', None) + chat_config = models['text.chat'] + chat_adapter = adapter_for(chat_config, self.transport, self.poll_interval) prepared = await asyncio.to_thread(self.availability.prepare, chat_config) current, _ = self._model('text.chat', chat_config['id']) self.availability.require(current, tool_request(current, 'text.chat', actual=True), prepared) - return await chat_adapter.chat(chat_config, request) + return await invoke('text.chat', lambda: chat_adapter.chat(chat_config, request)) context = ToolContext(sources=[], mask=None, boxes=[], parameters={}, image_model=None, video_model=None, progress=progress, segment_model=segment, chat_model=chat) - async with self.limit: - instances = await select_image_objects(context, image, value.get('prompt', ''), value.get('boxes') or []) + try: + image = await blocking(lambda: media.open_image(self.assets.read_bytes(project_id, source_id))) + async with self.limit: + instances = await select_image_objects(context, image, value.get('prompt', ''), value.get('boxes') or []) + except (Exception, asyncio.CancelledError): + await blocking(gateway().write_json, path, {'status': 'interrupted'}) + raise + finally: + await blocking(tool_spend.release_unused, self.projects, project_id, task_id) def encode(): result = [] @@ -164,7 +226,17 @@ def encode(): 'box': {'x': box[0], 'y': box[1], 'width': box[2] - box[0], 'height': box[3] - box[1]}, 'maskDataUrl': 'data:image/png;base64,' + base64.b64encode(media.png(rgba)).decode()}) return {'sourceAssetId': source_id, 'width': image.width, 'height': image.height, 'instances': result} - return await asyncio.to_thread(encode) + preview = await blocking(encode) + def store_preview(): + with self.store.transaction(): + gateway().write_json(path.with_suffix('.mask.json'), preview) + gateway().write_json(path, {'status': 'completed'}) + cutoff = datetime.now(timezone.utc).timestamp() - 86400 + for previous in path.parent.glob('*.mask.json'): + if previous.stat().st_mtime < cutoff: + gateway().child(path.parent, previous.name).unlink(missing_ok=True) + await blocking(store_preview) + return preview # Storage ------------------------------------------------------------------- @@ -188,6 +260,15 @@ def list(self, project_id): tasks = [self._read_task(project_id, gateway().child(folder, path.name)) for path in folder.glob('*.json')] return sorted(tasks, key=lambda task: (task['createdAt'], task['id']), reverse=True) + def untracked_calls(self, project_id, tracked_owners): + folder = self._folder(self._directory(project_id), create=False) + total = 0 + for path in folder.glob('*.json'): + if path.stem not in tracked_owners: + task = gateway().read_json(gateway().child(folder, path.name)) + total += len(task.get('modelCalls', ())) + return total + def placement(self, project_id, task_id, state, session, *, policy="if_current"): # Serialize acknowledgement with task writes/project moves. This never # adopts a GenerationSpec result or changes a terminal execution state. @@ -213,6 +294,8 @@ def _settle_terminal(self, project_id, task_id, session=None): with self.store.transaction(): directory = self._directory(project_id, session) task = gateway().read_json(gateway().child(self._folder(directory), task_id + '.json')) + if task['status'] in {'failed', 'cancelled', 'interrupted'}: + tool_spend.release_unused(self.projects, project_id, task_id) if task['status'] in {'failed', 'cancelled', 'interrupted'} and task.get('placement') == 'pending': task = self._change(project_id, task_id, {'placement': 'unplaced'}) return task @@ -242,11 +325,11 @@ def _read_task(self, project_id, path, session=None): # Submission ---------------------------------------------------------------- - def _prepare(self, project_id, value, session): + def _prepare(self, project_id, value, session, review=None, *, quote_only=False): # Snapshot validation and accepted ledger publication share the project # lock. A source cannot be replaced between checking and acceptance. with self.store.transaction(): - initial = self._prepare_locked(project_id, value, session, inspect=True) + initial = self._prepare_locked(project_id, value, session, inspect=True, quote_only=quote_only) if isinstance(initial, tuple): return initial # A replay does not query or reaccept its frozen job. uses_mask = (value.get('tool') == 'inpainting-remove' or @@ -259,14 +342,15 @@ def _prepare(self, project_id, value, session): (source.metadata.width, source.metadata.height)) selected = {capability: config for capability, config in initial.items() if tool_request(config, capability) is not None} - prepared = dict(zip(selected, self.availability.prepare_many(selected.values()), strict=True)) + prepared = {} if quote_only else dict(zip(selected, self.availability.prepare_many(selected.values()), strict=True)) with self.store.transaction(): - return self._prepare_locked(project_id, value, session, prepared=prepared) + return self._prepare_locked(project_id, value, session, prepared=prepared, review=review, quote_only=quote_only) - def _prepare_locked(self, project_id, value, session, *, inspect=False, prepared=None): + def _prepare_locked(self, project_id, value, session, *, inspect=False, prepared=None, review=None, quote_only=False): if self.closing: raise ProjectError('工具服务正在关闭,请稍后查询原任务。', 503) - self._ensure_owner() + if not quote_only: + self._ensure_owner() identifier(project_id) task_id = identifier(str(value['id'])) spec = TOOLS.get(value.get('tool')) @@ -285,7 +369,7 @@ def _prepare_locked(self, project_id, value, session, *, inspect=False, prepared if not source_ids or len(source_ids) > MAX_SOURCES or len(set(source_ids)) != len(source_ids): raise ProjectError('请提供 1–20 个不重复的来源素材。', 422) directory = self._directory(project_id, session) - path = gateway().child(self._folder(directory), task_id + '.json') + path = gateway().child(self._folder(directory, create=False), task_id + '.json') if path.is_file(): existing = gateway().read_json(path) if (existing['tool'] != spec.id or existing['sourceAssetIds'] != source_ids @@ -335,15 +419,15 @@ def _prepare_locked(self, project_id, value, session, *, inspect=False, prepared if image_capability == 'image.generate': image_plan['roles'] = [] for capability, config in list(models.items()): - request = tool_request(config, capability, actual=True) - if request is None: - continue parameters_to_check = [{}] if capability in {'video.first_frame', 'video.edit'}: video_plan = video_execution(spec.id, parameters, records[source_ids[0]], adapter=adapter_for(config), capability=capability) if video_plan is not None: parameters_to_check = video_plan['requests'] + request = tool_request(config, capability, actual=True) + if request is None: + continue if capability == image_capability: counts = {'text': 1, 'image': sum(role in {'image', 'annotation'} for role in image_plan['roles'])} if image_plan['mode'] == 'native_mask': @@ -357,6 +441,8 @@ def _prepare_locked(self, project_id, value, session, *, inspect=False, prepared contract = self.availability.request_constraints(config, request) if contract is not None: image_policy['requestConstraints'] = contract.model_dump(mode='json', exclude_none=True) + if quote_only: + continue if capability not in (prepared or {}): raise ProjectError('能力检查期间模型服务已变化,请重新提交。', 409, code='capability_connection_changed') self.availability.assert_identity(config, prepared[capability]) @@ -385,19 +471,47 @@ def _prepare_locked(self, project_id, value, session, *, inspect=False, prepared task.update(imageExecutionPolicy=image_policy, imageExecution=image_plan) if video_plan is not None: task['videoExecution'] = video_plan + task = to_jsonable_python(task) + if quote_only: + return task, directory, records + admission = tool_spend.admit(self.projects, value, task, records, session, review) + if admission is not None: + if admission.status == 'cancelled': + raise ProjectError('该费用请求已取消,请重新发起任务。', 409, code='spend_cancelled') + if admission.status == 'pending': + return tool_spend.pending_receipt(task, admission), directory, None + task = dict(admission.toolTask) self._write(directory, task) return task, directory, records - async def submit(self, project_id, value, session): + async def resume_spend(self, project_id, value, session, review): + if 'sourceAssetId' in value: + work = asyncio.create_task(self.selection_preview(project_id, value, session, review)) + self.admissions.add(work) + work.add_done_callback(self.admissions.discard) + await asyncio.shield(work) + else: + await self.submit(project_id, value, session, review) + + def quote(self, project_id, value, session): + task, directory, records = self._prepare(project_id, value, session, quote_only=True) + records = records if records is not None else self.assets._records(directory, project_id) + return creation_spend.quote_view(self.projects.snapshot(project_id), tool_spend.tool_quote(task, records)) + + def _schedule(self, task, directory, records): + key = (task['projectId'], task['id']) + job = asyncio.create_task(self._run(task, directory, records)) + self.jobs[key] = job + job.add_done_callback(lambda done: self.jobs.pop(key, None) if self.jobs.get(key) is done else None) + + async def submit(self, project_id, value, session, review=None): key = (project_id, identifier(str(value['id']))) self.accepting.add(key) async def accept(): try: - task, directory, records = await blocking(self._prepare, project_id, value, session) + task, directory, records = await blocking(self._prepare, project_id, value, session, review) if records is not None and key not in self.jobs: - job = asyncio.create_task(self._run(task, directory, records)) - self.jobs[key] = job - job.add_done_callback(lambda done: self.jobs.pop(key, None) if self.jobs.get(key) is done else None) + self._schedule(task, directory, records) return task finally: self.accepting.discard(key) @@ -418,6 +532,8 @@ def save(): return current if changes.get('status') == 'succeeded' and current.get('cancelRequested'): return current + if changes.get('status') == 'succeeded': + tool_spend.release_unused(self.projects, task['projectId'], task['id']) return self._change(task['projectId'], task['id'], changes) current = await blocking(save) task.clear() diff --git a/packages/core/src/opendirector/application/tool_video_inputs.py b/packages/core/src/opendirector/application/tool_video_inputs.py index 0bbf852ea..ca4dee823 100644 --- a/packages/core/src/opendirector/application/tool_video_inputs.py +++ b/packages/core/src/opendirector/application/tool_video_inputs.py @@ -6,15 +6,13 @@ def video_execution(tool, parameters, source, *, adapter, capability): - if not isinstance(adapter, VllmOmniVideo): - return None - if capability == 'video.first_frame' and tool == 'dynamic-poster': + if capability == 'video.first_frame' and tool == 'dynamic-poster' and isinstance(adapter, VllmOmniVideo): return {'requests': [capability_parameters(*adapter.video_parameters(5, first_frame=True))]} if capability != 'video.edit': return None duration = source['durationMs'] / 1000 window = reshoot_window(parameters) if tool == 'video-partial-reshoot' else None - pieces = redraw_intervals(duration, 4.0, float(adapter.MAX_SECONDS), window) - requests = [capability_parameters(*adapter.edit_parameters(last - first, source['width'], source['height'])) - for first, last in pieces] + pieces = redraw_intervals(duration, 4.0, float(getattr(adapter, 'MAX_SECONDS', 15)), window) + requests = ([capability_parameters(*adapter.edit_parameters(last - first, source['width'], source['height'])) + for first, last in pieces] if isinstance(adapter, VllmOmniVideo) else [{} for _ in pieces]) return {'pieces': pieces, 'requests': requests} diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index 5824189b1..e810041cd 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -219,6 +219,9 @@ def execute(self, kind, payload, versions=(), preview=None, *, identity=None): if value.get("status") == "rejected": emit(value) raise typer.Exit(1) + if value.get("status") == "awaiting_confirmation": + value["reviewUrl"] = f"{str(self.http.base_url).rstrip('/')}/ai-tool/ai-canvas/{self.project}?spendReview={value['spendRequestId']}" + value["next"] = {"description": "Review the batch in the project window. Query spend.status to read the current decision."} if value.get("status") == "accepted" and value.get("jobIds"): value = {**value, "next": { "description": "Wait for each accepted job to finish. On timeout, run the same wait command again.", diff --git a/packages/core/src/opendirector/domain/creation/base.py b/packages/core/src/opendirector/domain/creation/base.py index 42c5108cd..89b628c61 100644 --- a/packages/core/src/opendirector/domain/creation/base.py +++ b/packages/core/src/opendirector/domain/creation/base.py @@ -53,7 +53,7 @@ class ProjectEntity(Contract): class ObjectVersion(Contract): - objectType: Literal['project', 'asset', 'generation_spec', 'reference', 'canvas_item', 'editor_document', 'job', 'result'] = Field(description='Referenced business object type.') + objectType: Literal['project', 'asset', 'generation_spec', 'reference', 'canvas_item', 'editor_document', 'job', 'result', 'spend_request', 'spend_call'] = Field(description='Referenced business object type.') id: UUID = Field(description='Stable object ID.') revision: Revision = Field(description='Current object revision for optimistic concurrency.') diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index e79902c46..f8767e64a 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -7,6 +7,7 @@ from .assets import AssetRef, MediaMetadata from .base import CanvasColor, Contract, Digest, GenerationKind, MediaKind, ObjectVersion, Point, Positive, Revision, digest, unique from .canvas import CanvasItem +from .spend import SpendObservation, SpendPolicy, SpendReview, ToolSpendInput from .editors import EditorDocument from opendirector.domain.rule_facts import PROMPT_MAX_LENGTH from .generation import GenerationSpec, Job, PromptPart, Reference @@ -210,6 +211,8 @@ class ReferenceRemove(Contract): class GenerationSubmit(Contract): + count: int = Field(default=1, strict=True, ge=1, le=8, exclude_if=lambda value: value == 1, + description='Number of candidates admitted together at the whole-action price.') specId: UUID = Field(description='Include its current generation_spec revision in expectedVersions.', json_schema_extra={'x-version-object-type': 'generation_spec'}) expectedSpecRevision: Revision = Field(description='Must match the specId revision in expectedVersions.') @@ -228,6 +231,31 @@ def presentation(self): return self +class GroupMember(Contract): + itemId: UUID = Field(description='Canvas item to run.') + specId: UUID = Field(description='Generation specification owned by the item.') + count: int = Field(default=1, strict=True, ge=1, le=8, description='Candidates requested for this item.') + after: tuple[UUID, ...] = Field(default=(), description='Upstream group items whose adopted results this input needs.') + + +class GenerationGroup(Contract): + members: tuple[GroupMember, ...] = Field(min_length=1, max_length=500, description='Workflow members in canvas order.') + + @model_validator(mode='after') + def members_match(self): + ids = {member.itemId for member in self.members} + unique([m.itemId for m in self.members], 'workflow items') + unique([m.specId for m in self.members], 'workflow specifications') + if any(member.itemId in member.after or not set(member.after) <= ids for member in self.members): + raise ValueError('Group dependencies must be other members of this action') + return self + + +class GroupAdvance(Contract): + workflowId: UUID = Field(description='Original group instruction.') + items: tuple[UUID, ...] = Field(min_length=1, description='Newly runnable items.') + + class JobControl(Contract): jobId: UUID = Field(description='Generation job ID.') @@ -289,7 +317,7 @@ def scope_and_versions(self): def required_versions(self) -> list[tuple[str, UUID]]: payload = self.payload required = [] - if self.type in {'project.rename', 'project.trash', 'project.restore'}: + if self.type in {'project.rename', 'project.trash', 'project.restore', 'spend.policy'}: required = [('project', self.projectId)] elif self.type == 'canvas.publishMedia': required = [('canvas_item', payload.itemId), *[('asset', o.asset.assetId) for o in payload.outputs]] @@ -315,6 +343,8 @@ def required_versions(self) -> list[tuple[str, UUID]]: required = [('reference', payload.referenceId if self.type == 'reference.remove' else payload.reference.id)] elif self.type == 'reference.add': required = [('generation_spec', payload.reference.targetSpecId)] + elif self.type == 'generation.group': + required = [('generation_spec', m.specId) for m in payload.members] + [('canvas_item', m.itemId) for m in payload.members] elif self.type == 'generation.submit': required = [('generation_spec', payload.specId)] elif self.type == 'result.select': @@ -356,6 +386,12 @@ def required_versions(self) -> list[tuple[str, UUID]]: ('ReferenceUpdateCommand', 'reference.update', ReferenceWrite, 'Update a generation reference.'), ('ReferenceRestoreCommand', 'reference.restore', ReferenceWrite, 'Restore a generation reference.'), ('ReferenceRemoveCommand', 'reference.remove', ReferenceRemove, 'Deactivate a generation reference.'), + ('ToolSpendCommand', 'spend.tool', ToolSpendInput, 'Admit a frozen media tool recipe with its service costs.'), + ('SpendObservationCommand', 'spend.observe', SpendObservation, 'Record evidence from a model operation.'), + ('SpendPolicyCommand', 'spend.policy', SpendPolicy, 'Set project service spending controls.'), + ('SpendReviewCommand', 'spend.review', SpendReview, 'Record a human decision on a fixed request.'), + ('GenerationGroupCommand', 'generation.group', GenerationGroup, 'Quote and run a complete canvas workflow.'), + ('AdvanceGroupCommand', 'spend.advanceGroup', GroupAdvance, 'Continue an accepted workflow with its completed results.'), ('GenerationSubmitCommand', 'generation.submit', GenerationSubmit, 'Submit a generation job with fixed inputs and an adoption policy.'), ('JobCancelCommand', 'job.cancel', JobControl, 'Request cancellation of an existing job.'), ('JobRecoverCommand', 'job.recover', JobControl, 'Recover an existing job without creating a new attempt.'), @@ -407,7 +443,7 @@ def command_fingerprint(command: Command) -> str: from opendirector.domain.timeline_errors import TimelineIssueCode -IssueCode = Literal[TimelineIssueCode, 'invalid_input', 'revision_conflict', 'role_restricted', 'missing_object', 'reference_invalid', 'image_quality_unsupported', +IssueCode = Literal[TimelineIssueCode, 'spend_quote_changed', 'spend_cap', 'spend_unknown', 'invalid_input', 'revision_conflict', 'role_restricted', 'missing_object', 'reference_invalid', 'image_quality_unsupported', 'bigmodel_video_model', 'bigmodel_video_output', 'bigmodel_video_image', 'bigmodel_video_frames', 'bigmodel_video_prompt', 'bigmodel_video_cancel', 'kling_model', 'kling_mode', 'kling_image', 'kling_frames', 'kling_prompt', 'kling_aspect', 'kling_output', 'kling_cancel', @@ -438,7 +474,8 @@ class CommandReceipt(Contract): commandId: UUID = Field(description='Stable command ID for idempotent replay.') projectId: UUID = Field(description='Owning project ID.') inputFingerprint: Digest = Field(description='Fingerprint of the fixed execution input.') - status: Literal['applied', 'accepted', 'noop', 'rejected'] = Field(description='Current operation lifecycle state.') + status: Literal['applied', 'accepted', 'noop', 'rejected', 'awaiting_confirmation'] = Field(description='Current operation lifecycle state.') + spendRequestId: UUID | None = Field(default=None, exclude_if=lambda v: v is None, description='Batch awaiting a human spend decision.') changed: tuple[ObjectVersion, ...] = Field(default=(), description='Business objects changed by the operation.') jobIds: tuple[UUID, ...] = Field(default=(), description='Generation jobs associated with this operation.') issues: tuple[ContractIssue, ...] = Field(default=(), description='Validation or execution issues.') @@ -461,6 +498,23 @@ class QueryBase(Contract): projectId: UUID = Field(description='Owning project ID.') +class GroupQuoteQuery(QueryBase): + type: Literal['generation.groupQuote'] = Field(description='Estimate runnable workflow members and list the steps waiting for upstream results.') + workflow: GenerationGroup = Field(description='The same workflow members and dependencies used for submission.') + + +class GenerationQuoteQuery(QueryBase): + type: Literal['generation.quote'] = Field(description='Estimate the entire action without creating jobs.') + specId: UUID = Field(description='Generation specification to price.') + originItemId: UUID | None = Field(default=None, description='Canvas item that owns the draft.') + count: int = Field(default=1, strict=True, ge=1, le=8, description='Requested candidates.') + + +class SpendStatusQuery(QueryBase): + agentRunId: UUID | None = Field(default=None, description='Include the media service calls for this assistant turn.') + type: Literal['spend.status'] = Field(description='Read policy, totals, coverage and pending human decisions.') + + class ProjectQuery(QueryBase): type: Literal['project.get'] = Field(description='Read the current project.') @@ -501,7 +555,7 @@ class AssetPreviewQuery(QueryBase): objectId: UUID = Field(description='Asset ID.') -Query = Annotated[ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | +Query = Annotated[SpendStatusQuery | GenerationQuoteQuery | GroupQuoteQuery | ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | AssetPreviewQuery, Field(discriminator='type')] diff --git a/packages/core/src/opendirector/domain/creation/index.py b/packages/core/src/opendirector/domain/creation/index.py index 30ab06e17..a5d84ef47 100644 --- a/packages/core/src/opendirector/domain/creation/index.py +++ b/packages/core/src/opendirector/domain/creation/index.py @@ -5,6 +5,7 @@ def object_index(snapshot): result = {('project', snapshot.project.id): snapshot.project} for kind, collection in [('asset', snapshot.assets), ('generation_spec', snapshot.generationSpecs), ('reference', snapshot.references), ('canvas_item', snapshot.canvasItems), - ('editor_document', snapshot.editorDocuments), ('job', snapshot.jobs), ('result', snapshot.results)]: + ('editor_document', snapshot.editorDocuments), ('job', snapshot.jobs), ('result', snapshot.results), + ('spend_request', snapshot.spendRequests), ('spend_call', snapshot.spendCalls)]: result.update({(kind, item.id): item for item in collection}) return result diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index 225190ba7..bcdcd70a5 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -11,6 +11,7 @@ from opendirector.domain.projects import ProjectError from opendirector.domain.rule_facts import SERVICE_VOICE_PATTERN from .base import Contract +from .spend import ConnectionPrice ModelKind = Literal['agent', 'image', 'video', 'audio', 'vision'] Protocol = Literal['openai', 'volcengine', 'bigmodel_video', 'kling_video', 'minimax_video_v2', 'vllm_omni', 'vllm_omni_segmentation', 'vllm_omni_music', 'vllm_omni_depth', 'vllm_omni_score'] @@ -212,6 +213,7 @@ class AvailabilityCatalog(Contract): class ModelConfigPublic(ModelConnection): + price: ConnectionPrice | None = Field(default=None, exclude_if=lambda value: value is None, description='User-specified price for this exact model connection.') """Application-level, never embedded in an editable project's credential data.""" id: UUID = Field(description='Stable object ID.') providerId: UUID | None = Field(default=None, exclude=True, description='Shared provider connection ID.') diff --git a/packages/core/src/opendirector/domain/creation/project.py b/packages/core/src/opendirector/domain/creation/project.py index bd0de3c82..4b99f9099 100644 --- a/packages/core/src/opendirector/domain/creation/project.py +++ b/packages/core/src/opendirector/domain/creation/project.py @@ -5,6 +5,7 @@ from pydantic import BaseModel, Field, model_validator from .assets import Asset, AssetRef +from .spend import SpendCall, SpendPolicy, SpendRequest from .base import Contract, NonNegative, ObjectVersion, Point, ProjectEntity, Revision, unique from .canvas import CanvasItem, EditorBinding, GenerationBinding, MaterialBinding, MediaCanvasItem from .editors import EditorDocument, MediaEditDocument, LayerDocument, StackDocument, SubjectDocument, TimelineDocument @@ -13,6 +14,7 @@ class Project(Contract): + spendPolicy: SpendPolicy | None = Field(default=None, exclude_if=lambda v: v is None, description='Optional service spend controls.') id: UUID = Field(description='Stable object ID.') revision: Revision = Field(default=1, description='Current object revision for optimistic concurrency.') name: str = Field(min_length=1, max_length=100, pattern=r'\S', description='User-visible name.') @@ -62,6 +64,8 @@ class ProjectSnapshot(Contract): jobs: tuple[Job, ...] = Field(default=(), description='Immutable generation execution records.') results: tuple[ResultVersion, ...] = Field(default=(), description='Generated result candidates and adoption history.') eventCursor: int = Field(default=0, strict=True, ge=0, description='Latest committed project event cursor.') + spendRequests: tuple[SpendRequest, ...] = Field(default=(), exclude_if=lambda v: not v, description='Recorded decisions on fixed generation batches.') + spendCalls: tuple[SpendCall, ...] = Field(default=(), exclude_if=lambda v: not v, description='One reservation and its subsequent evidence per model call.') undoClearedThrough: int = Field(default=0, strict=True, ge=0, description='Event cursor through which undo history was cleared.') @model_validator(mode='after') @@ -69,7 +73,7 @@ def project_relations(self): if self.undoClearedThrough > self.eventCursor: raise ValueError('Undo clearing cannot point beyond the committed cursor') collections = (self.assets, self.generationSpecs, self.references, self.canvasItems, - self.editorDocuments, self.jobs, self.results) + self.editorDocuments, self.jobs, self.results, self.spendRequests, self.spendCalls) objects = [obj for collection in collections for obj in collection] unique([self.project.id, *(obj.id for obj in objects)], 'project object IDs') if any(obj.projectId != self.project.id for obj in objects): diff --git a/packages/core/src/opendirector/domain/creation/spend.py b/packages/core/src/opendirector/domain/creation/spend.py new file mode 100644 index 000000000..587169039 --- /dev/null +++ b/packages/core/src/opendirector/domain/creation/spend.py @@ -0,0 +1,260 @@ +"""Service prices are decimal amounts in their original currency.""" +from datetime import datetime +from decimal import Decimal, ROUND_CEILING, localcontext +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import Field, JsonValue + +from .base import Contract, Digest, ObjectVersion, ProjectEntity, digest + +Currency = Literal['USD', 'CNY'] +Amount = Annotated[Decimal, Field(ge=0, allow_inf_nan=False)] +MONEY_DIGITS = 24 +MONEY_PLACES = 12 +Money = Annotated[Decimal, Field(ge=0, max_digits=MONEY_DIGITS, decimal_places=MONEY_PLACES, allow_inf_nan=False)] +Unit = Literal['request', 'input_character', 'input_second', 'requested_second', 'output_second'] + + +def spend_math(): + # Rate × quantity needs up to 48 digits. Another 24 carry digits cover + # every call in a project, including an eight-candidate batch. + return localcontext(prec=3 * MONEY_DIGITS) + + +def service_charge(rate, quantity): + with spend_math(): + return rate * quantity + + +class ConnectionPrice(Contract): + unit: Unit = Field(description='What the configured service bills for.') + rate: Money = Field(description='Price for one billing unit.') + currency: Currency = Field(description='Currency of the service price.') + + +class PriceLine(Contract): + operation: str = Field(description='Model operation being priced.') + modelConfigId: UUID = Field(description='Selected model connection.') + modelId: str = Field(description='Provider model receiving the request.') + providerUrl: str | None = Field(default=None, exclude_if=lambda v: v is None, description='Endpoint for this quoted connection.') + source: Literal['connection', 'official', 'local', 'unknown'] = Field(description='Origin of the price.') + sourceUrl: str | None = Field(default=None, exclude_if=lambda v: v is None, description='Published source for an official price.') + sourceVersion: str | None = Field(default=None, description='Price revision or dated official source.') + price: ConnectionPrice | None = Field(default=None, description='Native unit price, when known.') + quantityBasis: Literal['fixed', 'maximum'] = Field(default='fixed', exclude_if=lambda v: v == 'fixed', description='Whether the quoted quantity is an upper bound.') + quantity: Money | None = Field(default=None, description='Billing units or bounded maximum for one candidate.') + amount: Amount | None = Field(default=None, description='Estimated amount for this step of one candidate.') + + +class SpendQuote(Contract): + fromUpstream: bool = Field(default=False, exclude_if=lambda v: not v, description='Inputs are newly resolved upstream results.') + candidates: int | None = Field(default=None, exclude_if=lambda v: v is None, description='Total candidates across distinct group members.') + skipped: tuple[UUID, ...] = Field(default=(), exclude_if=lambda v: not v, description='Workflow items blocked by a failed dependency or reference cycle.') + deferred: tuple[UUID, ...] = Field(default=(), exclude_if=lambda v: not v, description='Workflow items awaiting upstream inputs.') + count: int = Field(ge=1, le=8, description='Number of fixed candidates in this action.') + inputFingerprint: Digest = Field(description='Identity of the effective model inputs.') + lines: tuple[PriceLine, ...] = Field(description='Individual provider calls per candidate, in execution order.') + + def total(self, currency): + if any(line.amount is None or (line.amount and line.price.currency != currency) for line in self.lines): + return None + with spend_math(): + return sum((line.amount for line in self.lines), Decimal(0)) * self.count + + def subtotals(self): + currencies = {line.price.currency for line in self.lines if line.price is not None and line.amount is not None} + with spend_math(): + return {c: sum((line.amount for line in self.lines if line.price and line.price.currency == c and line.amount is not None), Decimal(0)) * self.count for c in sorted(currencies)} + + def fingerprint(self): + return digest(self) + + +class SpendPolicy(Contract): + currency: Currency = Field(default='USD', description='Currency of the project spending limits.') + threshold: Money | None = Field(default=None, description='Require confirmation strictly above this batch amount.') + cap: Money | None = Field(default=None, description='Maximum settled and reserved service spend.') + + +class ToolSpendInput(Contract): + request: dict[str, JsonValue] = Field(description='Validated media tool submission, including its stable task ID.') + + +class SpendRequest(ProjectEntity): + currency: Currency | None = Field(default=None, exclude_if=lambda v: v is None, description='Project currency when this quote was requested.') + specId: UUID | None = Field(default=None, exclude_if=lambda v: v is None, description='Fixed generation specification for a candidate batch.') + batchId: UUID | None = Field(default=None, exclude_if=lambda v: v is None, description='Canvas batch identity for member validation.') + workflowId: UUID | None = Field(default=None, exclude_if=lambda v: v is None, description='Original group action owning this decision.') + groupItems: tuple[UUID, ...] = Field(default=(), exclude_if=lambda v: not v, description='Fixed workflow items included in this decision.') + toolTask: dict[str, JsonValue] | None = Field(default=None, exclude_if=lambda v: v is None, + description='Frozen media tool dispatch, without credentials. The project journal owns its acceptance.') + versions: tuple[ObjectVersion, ...] = Field(description='Input object versions fixed when the request was made.') + quote: SpendQuote = Field(description='Exact batch covered by this request.') + createdAt: datetime = Field(description='Time the project requested a review.') + status: Literal['pending', 'accepted', 'cancelled'] = Field(default='pending', description='Human review status.') + agentRunId: UUID | None = Field(default=None, description='Originating assistant turn.') + agentCallId: str | None = Field(default=None, description='Originating assistant tool call.') + decisionId: UUID | None = Field(default=None, description='Durable command that resolved this request.') + + +class SpendCall(ProjectEntity): + ownerId: UUID = Field(description='Generation job or media tool task that owns this call.') + line: PriceLine = Field(description='Original native-currency estimate for this physical call.') + createdAt: datetime = Field(description='Time the reservation was created.') + state: Literal['reserved', 'submitted', 'completed', 'released'] = Field(default='reserved', description='State of the provider call.') + usage: Money | None = Field(default=None, description='Metered units reported for the call.') + usageSource: Literal['execution', 'provider', 'media'] | None = Field(default=None, description='Origin of the quantity used for settlement.') + calculated: Amount | None = Field(default=None, description='Amount calculated from confirmed usage and the agreed rate.') + reported: Money | None = Field(default=None, description='Charge explicitly reported by the provider in the line currency.') + + def accounted(self): + if self.state == 'released': + return Decimal(0) + for amount in (self.reported, self.calculated, self.line.amount): + if amount is not None: + return amount + return None + + +class SpendReview(Contract): + requestId: UUID = Field(description='Original batch request.') + fingerprint: Digest = Field(description='Reviewed input and price fingerprint.') + decision: Literal['approve', 'cancel'] = Field(description='Human decision for this exact action.') + acceptUnknown: bool = Field(default=False, description='Explicitly accepts this unpriced action with no project cap.') + newCap: Money | None = Field(default=None, description='Raise the project cap in the same transaction as admission.') + + +class SpendObservation(Contract): + callId: UUID = Field(description='Stable physical call receiving evidence.') + state: Literal['submitted', 'completed', 'released'] = Field(description='Observed execution state.') + unit: Unit | None = Field(default=None, description='Unit of observed provider usage.') + usage: Money | None = Field(default=None, description='Provider units or measured output length.') + reported: Money | None = Field(default=None, description='Verified provider amount in the quoted currency.') + evidence: Literal['execution', 'provider', 'media'] = Field(default='execution', description='Source of the observation.') + + +def observed_call(call, observation): + """Repeated transfer and download events cannot charge or release a call twice.""" + state = observation.state + if ((state in {'released', 'submitted'} and call.state != 'reserved') or + (call.state == 'released' and observation.evidence != 'provider')): + return call + changes = dict(state=state) + price = call.line.price + if state == 'completed' and price is not None: + if observation.reported is not None: + changes['reported'] = observation.reported + if observation.unit == price.unit and observation.usage is not None: + if call.usageSource != 'provider' or observation.evidence == 'provider': + changes.update(usage=observation.usage, usageSource=observation.evidence, calculated=service_charge(price.rate, observation.usage)) + elif call.calculated is None and call.line.quantityBasis == 'fixed' and price.unit != 'output_second' and call.line.quantity is not None: + changes.update(usage=call.line.quantity, usageSource='execution', calculated=call.line.amount) + edited = call.model_copy(update=changes) + return call if edited == call else edited.model_copy(update={'revision': call.revision + 1}) + + +def call_totals(calls, currency): + settled, held, missing = Decimal(0), Decimal(0), 0 + with spend_math(): + for call in calls: + amount = call.accounted() + if amount is None or (amount and call.line.price.currency != currency): + missing += 1 + elif call.state == 'completed' and (call.calculated is not None or call.reported is not None): + settled += amount + else: + held += amount + return dict(settled=settled, held=held, unknown=missing) + + +def spend_summary(snapshot): + policy = snapshot.project.spendPolicy or SpendPolicy() + totals = call_totals(snapshot.spendCalls, policy.currency) + owners = {call.ownerId for call in snapshot.spendCalls} + with spend_math(): + available = None if policy.cap is None or totals['unknown'] else policy.cap - totals['settled'] - totals['held'] + return dict(policy=policy, **totals, available=available, + legacy=sum(j.execution.kind != 'text' and j.id not in owners for j in snapshot.jobs), + since=min((c.createdAt for c in snapshot.spendCalls), default=None)) + + +def spend_decision(summary, quote): + policy = summary['policy'] + amount = quote.total(policy.currency) + controlled = policy.cap is not None or policy.threshold is not None + if amount == 0: + return 'upstream_confirmation' if controlled and quote.deferred else 'ready' + if amount is None: + return 'unpriced' if policy.cap is not None else 'unknown_confirmation' if policy.threshold is not None else 'ready' + if policy.cap is not None and summary['unknown']: + return 'prior_unknown' + if policy.cap is not None and amount > summary['available']: + return 'over_cap' + if controlled and quote.deferred: + return 'upstream_confirmation' + if controlled and quote.fromUpstream: + return 'confirmation' + if policy.threshold is not None and amount > policy.threshold: + return 'confirmation' + return 'ready' + + +def cap_adjustment(current_cap, available, amount): + """Return the shortfall and the smallest policy cap that covers this batch.""" + with spend_math(): + missing = amount - available + required = current_cap + missing + upper_bound = Decimal(10) ** (MONEY_DIGITS - MONEY_PLACES) + if required >= upper_bound: + return missing, None + if required.as_tuple().exponent < -MONEY_PLACES: + required = required.quantize(Decimal(1).scaleb(-MONEY_PLACES), rounding=ROUND_CEILING) + return missing, required if required < upper_bound else None + + +# These synchronous retail prices cover every supported output specification +# on the mainland endpoint. A proxy or a different API receives no default. +OFFICIAL_URL = 'https://open.bigmodel.cn/api/paas/v4' +OFFICIAL_SOURCE = 'https://docs.bigmodel.cn/cn/guide/start/pricing' +OFFICIAL_PRICES = { + ('openai', 'glm-image', 'image'): ('request', '0.10'), + ('bigmodel_video', 'cogvideox-3', 'video'): ('request', '1'), + ('openai', 'glm-tts', 'speech'): ('input_character', '0.0002'), +} + + +def video_units(fields, fallback_seconds=None): + """Frame-based APIs receive their aligned frame count, including any padding.""" + frames, fps = fields.get('num_frames'), fields.get('fps') + if frames and fps: + seconds = (Decimal(frames) / Decimal(str(fps))).quantize(Decimal('0.000000000001'), rounding=ROUND_CEILING) + else: + seconds = fields.get('duration', fallback_seconds) + return {} if seconds is None else {'requested_second': seconds, 'output_second': seconds} + + +def price_line(config, operation, quantities, *, bounded=()): + """Count only units for which the effective request supplies a bound.""" + version = None + price = None + if config.get('price') is not None: + price = ConnectionPrice.model_validate(config['price']) + source, version = 'connection', digest(price) + elif config['connectionType'] == 'self_hosted': + price = ConnectionPrice(unit='request', currency='USD', rate=0) + source = 'local' + elif (config['url'].rstrip('/') == OFFICIAL_URL and + (row := OFFICIAL_PRICES.get((config['protocol'], config['modelId'], operation)))): + price = ConnectionPrice(unit=row[0], rate=row[1], currency='CNY') + source, version = 'official', '2026-11-22' + else: + source = 'unknown' + quantity = None if price is None else {'request': 1, **quantities}.get(price.unit) + units = Decimal(str(quantity)) if quantity is not None else None + amount = None if price is None or units is None else service_charge(price.rate, units) + if price is not None and price.rate == 0: + amount = Decimal(0) + return PriceLine(operation=operation, modelConfigId=config['id'], modelId=config['modelId'], providerUrl=config.get('url'), + source=source, sourceVersion=version, sourceUrl=OFFICIAL_SOURCE if source == 'official' else None, price=price, + quantityBasis='maximum' if price and (price.unit == 'output_second' or price.unit in bounded) else 'fixed', quantity=units, amount=amount) diff --git a/packages/core/src/opendirector/domain/creation/validation.py b/packages/core/src/opendirector/domain/creation/validation.py index 8a3a7af9f..4f7d257e7 100644 --- a/packages/core/src/opendirector/domain/creation/validation.py +++ b/packages/core/src/opendirector/domain/creation/validation.py @@ -33,7 +33,8 @@ def validate_command(command: Command, project: ProjectSnapshot): index = {('project', project.project.id): project.project} for kind, collection in [('asset', project.assets), ('generation_spec', project.generationSpecs), ('reference', project.references), ('canvas_item', project.canvasItems), - ('editor_document', project.editorDocuments), ('job', project.jobs), ('result', project.results)]: + ('editor_document', project.editorDocuments), ('job', project.jobs), ('result', project.results), + ('spend_request', project.spendRequests), ('spend_call', project.spendCalls)]: index.update({(kind, obj.id): obj for obj in collection}) expected = {(version.objectType, version.id): version.revision for version in command.expectedVersions} for key, version in expected.items(): diff --git a/packages/core/src/opendirector/infrastructure/creation_publication.py b/packages/core/src/opendirector/infrastructure/creation_publication.py index a43ec088a..0c3a19d28 100644 --- a/packages/core/src/opendirector/infrastructure/creation_publication.py +++ b/packages/core/src/opendirector/infrastructure/creation_publication.py @@ -101,8 +101,10 @@ def _make_record(command, head, snapshot, changed, source, issue=None): and next(job for job in snapshot.jobs if job.id == item['version'].id).status == 'queued') event = ProjectEvent(projectId=command.projectId, cursor=snapshot.eventCursor, commandId=command.commandId, source=source, changed=changed, jobIds=job_ids) if changed else None - receipt = CommandReceipt(commandId=command.commandId, projectId=command.projectId, - inputFingerprint=command_fingerprint(command), status='rejected' if issue else 'accepted' if job_ids else 'applied' if changed else 'noop', + waiting = next((item['version'].id for item in changed if item['version'].objectType == 'spend_request' + and item['change'] == 'created' and any(r.id == item['version'].id and r.status == 'pending' for r in snapshot.spendRequests)), None) + receipt = CommandReceipt(spendRequestId=waiting, commandId=command.commandId, projectId=command.projectId, + inputFingerprint=command_fingerprint(command), status='rejected' if issue else 'awaiting_confirmation' if waiting else 'accepted' if job_ids else 'applied' if changed else 'noop', changed=[item['version'] for item in changed], jobIds=job_ids, issues=[issue] if issue else [], eventCursor=snapshot.eventCursor) return CommitRecord(command=command, previousHead=head, snapshot=snapshot, receipt=receipt, event=event) diff --git a/packages/core/src/opendirector/infrastructure/creation_records.py b/packages/core/src/opendirector/infrastructure/creation_records.py index c759fbd8b..2999ec734 100644 --- a/packages/core/src/opendirector/infrastructure/creation_records.py +++ b/packages/core/src/opendirector/infrastructure/creation_records.py @@ -45,7 +45,7 @@ def consistent(self): or self.receipt.inputFingerprint != command_fingerprint(self.command) or self.receipt.eventCursor != self.snapshot.eventCursor): raise ValueError('Commit identity is inconsistent') - applied = self.receipt.status in {'applied', 'accepted'} + applied = self.receipt.status in {'applied', 'accepted', 'awaiting_confirmation'} if applied != (self.event is not None): raise ValueError('Only applied commits have outbox events') if self.event is not None: diff --git a/packages/core/src/opendirector/infrastructure/model_configs.py b/packages/core/src/opendirector/infrastructure/model_configs.py index 9494704c4..391fd330b 100644 --- a/packages/core/src/opendirector/infrastructure/model_configs.py +++ b/packages/core/src/opendirector/infrastructure/model_configs.py @@ -9,6 +9,7 @@ from filelock import FileLock from opendirector.domain.projects import ProjectError, identifier +from opendirector.domain.creation.spend import ConnectionPrice from opendirector.domain.input_rules import input_rules from opendirector.domain.capabilities import agent_input_modalities from opendirector.domain.model_connection import connection_fields, model_fields @@ -48,10 +49,12 @@ def _read(self) -> list[dict]: item.update(services[item['providerId']]) seen = set() for item in value["models"]: - if not {'id', 'kind', 'url', 'modelId', 'apiKey'} <= set(item) or set(item) - {'id', 'kind', 'url', 'modelId', 'apiKey', 'connectionType', 'protocol', 'authMode', 'proxyMode', 'videoAdapter', 'videoCapabilities', 'providerId', 'inputModalities', 'capabilityAutoCheck'}: + if not {'id', 'kind', 'url', 'modelId', 'apiKey'} <= set(item) or set(item) - {'id', 'kind', 'url', 'modelId', 'apiKey', 'connectionType', 'protocol', 'authMode', 'proxyMode', 'videoAdapter', 'videoCapabilities', 'providerId', 'inputModalities', 'capabilityAutoCheck', 'price'}: raise ValueError() if 'capabilityAutoCheck' in item and type(item['capabilityAutoCheck']) is not bool: raise ValueError() + if 'price' in item: + ConnectionPrice.model_validate(item['price']) identifier(item["id"]) if item["id"] in seen or item["kind"] not in MODEL_KINDS: raise ValueError() @@ -73,7 +76,8 @@ def _read(self) -> list[dict]: @staticmethod def _public(item: dict) -> dict: - return {**({'providerId': item['providerId']} if 'providerId' in item else {}), + return {**({'price': item['price']} if 'price' in item else {}), + **({'providerId': item['providerId']} if 'providerId' in item else {}), **({'capabilityAutoCheck': item['capabilityAutoCheck']} if 'capabilityAutoCheck' in item else {}), **{key: item[key] for key in ("id", "kind", "url", "modelId", "connectionType", "protocol", "authMode", "proxyMode", "videoAdapter", "videoCapabilities", "inputModalities")}, 'inputRules': input_rules(item)} @@ -137,6 +141,7 @@ def save(self, kind: str, url: str, model_id: str, api_key: str, config_id: str profile = input_rules(item)['profile'] if item['videoCapabilities'] is not None and profile in {'fasth3-omni', 'vllm-omni-h3'}: check_video_config(kind, 'vllm_omni', 'fasth3' if profile == 'fasth3-omni' else 'minimax_h3', item['videoCapabilities']) + self._retain_price(item, existing) if existing: models[models.index(existing)] = item else: @@ -145,12 +150,32 @@ def save(self, kind: str, url: str, model_id: str, api_key: str, config_id: str item['providerId'] = existing['providerId'] for peer in models: if peer.get('providerId') == item['providerId']: + if (peer['url'], peer['connectionType']) != (item['url'], item['connectionType']): + peer.pop('price', None) peer.update({key: item[key] for key in ('url', 'apiKey', 'connectionType', 'authMode', 'proxyMode')}) if auto_check is not None: peer['capabilityAutoCheck'] = auto_check self._write(models) return self._public(item) + def set_price(self, config_id, price): + with self.lock: + models = self._read() + item = next((model for model in models if model['id'] == config_id), None) + if item is None: + raise ProjectError('Model connection no longer exists.', 404) + if price is None: + item.pop('price', None) + else: + item['price'] = ConnectionPrice.model_validate(price).model_dump(mode='json') + self._write(models) + return self._public(item) + + @staticmethod + def _retain_price(item, old): + if old and 'price' in old and all(item[key] == old[key] for key in ('kind', 'url', 'modelId', 'protocol', 'connectionType')): + item['price'] = old['price'] + def delete(self, config_id: str) -> None: with self.lock: models = self._read() @@ -224,6 +249,7 @@ def save_many(self, kind: str, url: str, model_ids: list[str], api_key: str, profile = input_rules(item)['profile'] if item['videoCapabilities'] is not None and profile in {'fasth3-omni', 'vllm-omni-h3'}: check_video_config(kind, 'vllm_omni', 'fasth3' if profile == 'fasth3-omni' else 'minimax_h3', item['videoCapabilities']) + self._retain_price(item, old) saved.append(item) remaining = [item for item in models if item not in previous] for item in remaining: diff --git a/packages/core/src/opendirector/integrations/model_adapters.py b/packages/core/src/opendirector/integrations/model_adapters.py index 560269231..a0104dd21 100644 --- a/packages/core/src/opendirector/integrations/model_adapters.py +++ b/packages/core/src/opendirector/integrations/model_adapters.py @@ -287,7 +287,7 @@ class MinimaxSpeech(ModelAdapter): """MiniMax synchronous T2A v2, non-streaming, answering with a result URL.""" capabilities = frozenset({'audio.speech'}) - async def speech(self, config, request: SpeechRequest, *, result_ready=None) -> MediaResult: + async def speech(self, config, request: SpeechRequest, *, result_ready=None, usage_ready=None) -> MediaResult: validate_minimax_speech_input(request.text, request.voice) payload = {'model': config['modelId'], 'text': request.text, 'stream': False, 'voice_setting': {'voice_id': request.voice}, 'audio_setting': {'format': 'mp3'}, @@ -308,6 +308,9 @@ async def submit(): http_status=200, secrets=secrets, provider='minimax') if type(value['data']['status']) is not int or value['data']['status'] != 2: raise protocol_failure('submit') + usage = (value.get('extra_info') or {}).get('usage_characters') if isinstance(value.get('extra_info'), dict) else None + if usage_ready and type(usage) is int and 0 <= usage <= 10 ** 12: + await usage_ready(usage) return _result_url(value['data']['audio'], 'submit') url = await _call('submit', submit) diff --git a/packages/core/src/opendirector/integrations/providers.py b/packages/core/src/opendirector/integrations/providers.py index 2073864e1..5812659d7 100644 --- a/packages/core/src/opendirector/integrations/providers.py +++ b/packages/core/src/opendirector/integrations/providers.py @@ -154,8 +154,10 @@ async def generate(self, config, task, submitted, *, result_ready=None): return result.suffix, result.data if input_rules(config)['profile'] == 'minimax-speech': prepared = await asyncio.to_thread(generation_references, self.store, task, config) + async def usage(characters): + await self._spend(0, 'completed', unit='input_character', usage=characters, evidence='provider') result = await self.minimax_speech.speech(config, SpeechRequest(prepared['prompt'], task['parameters'].get('voice')), - result_ready=result_ready) + result_ready=result_ready, usage_ready=usage) return result.suffix, result.data if input_rules(config)['profile'] == 'zhipu-speech': prepared = await asyncio.to_thread(generation_references, self.store, task, config) @@ -224,6 +226,8 @@ async def generate(self, config, task, submitted, *, result_ready=None): score = '' if params.get('score_model'): score = await self._score(task, params) + await self._spend(0, 'completed') + await self._spend(1, 'submitted') result = await VllmOmniMusic(self.transport).music(config, MusicRequest( task['prompt'], params.get('lyrics', ''), params['duration'], score=score, score_mode=params.get('score_mode', 'melody'), seed=params.get('seed'))) @@ -274,11 +278,17 @@ async def generate(self, config, task, submitted, *, result_ready=None): except (ValueError, KeyError, TypeError, IndexError, AttributeError): raise protocol_failure(stage) from None + async def _spend(self, slot, state, **facts): + observer = getattr(self.store, 'observe_spend', None) + if observer is not None: + await asyncio.to_thread(observer, slot, state, **facts) + async def _score(self, task, params): """Transcribe the job's one reference recording with the transcription model it froze.""" config = await asyncio.to_thread(self.store.frozen_model, params['score_model']) loaded = await asyncio.to_thread(lambda: list(references(self.store, task['projectId'], task['referenceIds']))) data, meta = next((data, meta) for data, meta, source_kind in loaded if source_kind == 'audio') + await self._spend(0, 'submitted') return await VllmOmniScore(self.transport).score(config, ScoreRequest( data, meta['name'], melody_only=params['score_mode'] == 'melody')) diff --git a/scripts/generate_contracts.py b/scripts/generate_contracts.py index 20426da25..a3f52cc27 100644 --- a/scripts/generate_contracts.py +++ b/scripts/generate_contracts.py @@ -17,7 +17,7 @@ from opendirector.domain.creation.schema import ALIASES, CreationContracts from opendirector.domain.rule_facts import typescript_module -MODULES = ('base', 'assets', 'models', 'generation', 'editors', 'canvas', 'project', 'commands', 'timeline_packages', 'schema') +MODULES = ('base', 'spend', 'assets', 'models', 'generation', 'editors', 'canvas', 'project', 'commands', 'timeline_packages', 'schema') def models(): diff --git a/src/backend/creationClient.ts b/src/backend/creationClient.ts index 3f769045a..30114340a 100644 --- a/src/backend/creationClient.ts +++ b/src/backend/creationClient.ts @@ -610,10 +610,11 @@ export class CreationClient { policy: "if_current" | "candidate_only" = "if_current", batchId?: string, signal?: AbortSignal, + count = 1, ) { const run = () => { signal?.throwIfAborted(); - return this.submitCurrent(itemId, policy, batchId, signal); + return this.submitCurrent(itemId, policy, batchId, signal, count); }; const pending = this.submissions.then(run, run); this.submissions = pending; @@ -624,6 +625,7 @@ export class CreationClient { policy: "if_current" | "candidate_only", batchId?: string, signal?: AbortSignal, + count = 1, ) { await this.refresh(); signal?.throwIfAborted(); @@ -647,6 +649,7 @@ export class CreationClient { originItemId: item.id, adoptionPolicy: policy, batchId, + count, showAdditionalResult: policy === "candidate_only", }, [ diff --git a/src/backend/imageSelections.ts b/src/backend/imageSelections.ts index e73aaa9a0..fdccc1eed 100644 --- a/src/backend/imageSelections.ts +++ b/src/backend/imageSelections.ts @@ -1,3 +1,5 @@ +import { readDelay } from "./resilientRead.ts"; +import { creationClient } from "./creationClient.ts"; import { json, request } from "./api.ts"; import type { BackendAsset } from "./generation.ts"; import { requireActiveBackendProject } from "./projects.ts"; @@ -57,15 +59,27 @@ export async function previewImageSelection( ); } signal.throwIfAborted(); - return request( - `/creation/projects/${projectId}/image-selections`, + const id = crypto.randomUUID(); + const path = `/creation/projects/${projectId}/image-selections`; + let result = await request( + path, { ...json("POST", { - sourceAssetId, + id, sourceAssetId, prompt: value.prompt ?? "", boxes: value.boxes ?? [], }), signal, }, ); + if ('status' in result) { + await creationClient(projectId).refresh(); + window.dispatchEvent(new CustomEvent('opendirector:spend-review', { detail: projectId })); + } + while ('status' in result) { + if (['cancelled', 'interrupted', 'expired'].includes(result.status)) throw new Error(tNow('spend.previewStopped')); + await readDelay(750, signal); + result = await request(`${path}/${id}`, {signal}); + } + return result; } diff --git a/src/backend/rules.ts b/src/backend/rules.ts index 675f16d59..d03f13b84 100644 --- a/src/backend/rules.ts +++ b/src/backend/rules.ts @@ -64,6 +64,7 @@ export interface InputRules { } export interface ModelConfig { + price?: import("../contracts/generated.ts").ConnectionPrice | null; capabilityAutoCheck?: boolean | null; availability?: ModelAvailability | null; providerId?: string | null; diff --git a/src/backend/spend.ts b/src/backend/spend.ts new file mode 100644 index 000000000..341a21b76 --- /dev/null +++ b/src/backend/spend.ts @@ -0,0 +1,43 @@ +import { json, request } from "./api.ts"; +import { creationPath } from "./creationClient.ts"; +import type { SpendPolicy, SpendQuote, SpendRequest } from "../contracts/generated.ts"; + +export interface QuoteView { + quote: SpendQuote; + fingerprint: string; + currency: SpendPolicy["currency"]; + amount: string | null; + projectAfter: string | null; + subtotals: Record; +} + +export interface PendingSpend { + request: SpendRequest; + fingerprint: string; + reason: "ready" | "stale" | "stale_inputs" | "upstream_confirmation" | "confirmation" | "unknown_confirmation" | "unpriced" | "prior_unknown" | "over_cap"; + amount: string | null; + shortfall: string | null; + suggestedCap: string | null; + subtotals: Record; +} + +export interface SpendStatus { + policy: SpendPolicy; + held: string; + settled: string; + settledBatch?: { kind: string; count: number }; + available: string | null; + unknown: number; + legacy: number; + since: string | null; + projectRevision: number; + pending: PendingSpend[]; + workflows: { id: string; items: string[]; state: "waiting" | "running" | "cancelled" | "completed" | "incomplete"; completed: number; failed: number; skipped: number; total: number }[]; + turn?: { callCount: number; settled: string; held: string; unknown: number }; +} + +export function spendQuery(projectId: string, type: "spend.status" | "generation.quote" | "generation.groupQuote", fields = {}, signal?: AbortSignal) { + return request(creationPath(projectId) + "/queries", { + ...json("POST", { type, projectId, queryId: crypto.randomUUID(), ...fields }), signal, + }); +} diff --git a/src/backend/tools.ts b/src/backend/tools.ts index 6ae2cb5b7..4614539cf 100644 --- a/src/backend/tools.ts +++ b/src/backend/tools.ts @@ -327,7 +327,11 @@ export async function submitToolTask(value: ToolRequest, signal: AbortSignal) { boxes: value.boxes ?? [], parameters: value.parameters, }; - const task = await deliverTool(projectId, owner!.id, body); + const task = await deliverTool(projectId, owner!.id, body); + if (task.status === "awaiting_confirmation") { + await client.refresh(); + return { projectId, taskId: task.id, spendRequestId: task.spendRequestId }; + } if (signal.aborted) { // Acceptance may race a click on Cancel. Once the identity is known, // cancel the accepted task too; aborting a browser request is not enough. diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index d9a80f845..d855df62a 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -8,6 +8,7 @@ import { loadReferenceCatalog } from "../backend/referenceCatalog.ts"; import "./assistant-panel.css"; import "./assistant-experience.css"; import { AttachmentStrip, AttachmentHover } from "./AssistantMedia"; +import { TurnSpend } from "./ProjectSpend"; import { AssistantReply } from "./AssistantReply"; import { AssistantConversations } from "./AssistantConversations"; import { AgentPicker } from "./AgentPicker"; @@ -493,6 +494,7 @@ export function AssistantPanel({ : t("assistant.reply.empty")) )} + {open && message.role === "assistant" && previous?.role === "user" && } {trace && ( diff --git a/src/canvas/CanvasIcon.tsx b/src/canvas/CanvasIcon.tsx index 2180452c1..ed95bdbc9 100644 --- a/src/canvas/CanvasIcon.tsx +++ b/src/canvas/CanvasIcon.tsx @@ -7,6 +7,7 @@ export interface CanvasIconProps extends Omit, "name"> { /** One shape per content type, shared by creation tools, nodes and pickers. */ const icons: Record = { + wallet: <>, text: , image: ( <> diff --git a/src/canvas/ModelSettings.tsx b/src/canvas/ModelSettings.tsx index 0dc2096ec..9b81aa773 100644 --- a/src/canvas/ModelSettings.tsx +++ b/src/canvas/ModelSettings.tsx @@ -1,3 +1,4 @@ +import { ModelPriceEditor } from "./ProjectSpend"; import { ModelAvailabilityCard } from "./ModelAvailabilityCard"; import { ModelSetup } from "./ModelSetup"; import { ModelLogo } from "./ModelLogo"; @@ -189,6 +190,10 @@ export function ModelSettings({ error={member.availability?.reasonCode === "query_failed" ? catalog.availabilityError || undefined : undefined} onRefresh={() => void catalog.refreshAvailability([member.id], true)} />)} +
+ {t(model.kind === "agent" ? "spend.mediaToolPrice" : "spend.price")} + {members.map(member => )} +
{providerLabel(model)}{" "} diff --git a/src/canvas/NodeComposer.tsx b/src/canvas/NodeComposer.tsx index 5792c93e1..d2c34d62a 100644 --- a/src/canvas/NodeComposer.tsx +++ b/src/canvas/NodeComposer.tsx @@ -56,6 +56,7 @@ import { import { composerReferenceVisibility } from "./composerReferenceVisibility.ts"; export interface NodeComposerProps { + projectId?: string; selectedNode: CanvasNode | null; incomingNodes: CanvasNode[]; /** Pinned assets included in run-before reference checks, not frame-slot limits. */ @@ -86,7 +87,10 @@ function clockTime(seconds: number) { /** Built-in demo voice id; the visible label is localized separately. */ const DEMO_VOICE = "动漫海绵"; +import { GenerationEstimate } from "./ProjectSpend"; + export function NodeComposer({ + projectId, selectedNode, incomingNodes, pinnedPrecheck, @@ -507,6 +511,19 @@ export function NodeComposer({ {t("generation.bigmodel.watermarkWaiver")}

)} + {projectId && config && canRun && ( +
+ model.price))} + /> +
+ )}
{!serviceModels.length && onConfigureModel ? ( diff --git a/src/canvas/NodeSelectionToolbar.tsx b/src/canvas/NodeSelectionToolbar.tsx index e7b4859f9..426740742 100644 --- a/src/canvas/NodeSelectionToolbar.tsx +++ b/src/canvas/NodeSelectionToolbar.tsx @@ -50,6 +50,7 @@ export interface NodeSelectionToolbarProps { /** Group actions: run the members' generation workflow, ungroup, arrange, recolor. */ onRunWorkflow?: () => void; workflowRunning?: boolean; + workflowWaiting?: boolean; onUngroup?: () => void; onLayout?: (layout: GroupLayout) => void; onGroupColor?: (color: string) => void; @@ -147,6 +148,7 @@ export function NodeSelectionToolbar({ onDelete, onRunWorkflow, workflowRunning = false, + workflowWaiting = false, onUngroup, onLayout, onGroupColor, @@ -222,10 +224,10 @@ export function NodeSelectionToolbar({ if (onRunWorkflow) editing.push({ id: "run-workflow", - label: workflowRunning ? t("canvas.selection.group.running") : t("canvas.selection.group.run"), + label: workflowWaiting ? t("spend.workflowState.waiting") : workflowRunning ? t("canvas.selection.group.running") : t("canvas.selection.group.run"), icon: "play", run: onRunWorkflow, - disabled: workflowRunning || locked, + disabled: workflowRunning || workflowWaiting || locked, }); if (onUngroup) editing.push({ id: "ungroup", label: t("canvas.selection.group.ungroup"), icon: "group", run: onUngroup, disabled: locked }); diff --git a/src/canvas/ProjectSpend.tsx b/src/canvas/ProjectSpend.tsx new file mode 100644 index 000000000..8bfda4643 --- /dev/null +++ b/src/canvas/ProjectSpend.tsx @@ -0,0 +1,400 @@ +import { workflowRequest } from "./workspace/workflowMembers.ts"; +import { generationOutput, money, uniformOutputPrice } from "./spendPresentation.ts"; +import { TooltipButton } from "./TooltipButton.tsx"; +import { CANVAS_TOOLS } from "./toolCatalog.ts"; +import { translateToolText } from "./toolText.ts"; +import type { CanvasDocument, GenerationSettings } from "./model.ts"; +import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react"; +import { errorMessage, json, request } from "../backend/api.ts"; +import { creationClient, objectVersion } from "../backend/creationClient.ts"; +import type { ModelConfig } from "../backend/rules.ts"; +import { spendQuery, type PendingSpend, type QuoteView, type SpendStatus } from "../backend/spend.ts"; +import type { ConnectionPrice, SpendPolicy, SpendQuote } from "../contracts/generated.ts"; +import { useI18n, useT } from "../i18n/I18nProvider"; +import { CanvasIcon } from "./CanvasIcon"; +import { SpendDialog } from "./SpendDialog"; +import "./project-spend.css"; + +function useSnapshot(projectId: string) { + const client = creationClient(projectId); + const subscribe = useCallback((notify: () => void) => client.listen(notify), [client]); + return useSyncExternalStore(subscribe, () => client.snapshot); +} + +function QuoteLines({ quote }: { quote: SpendQuote }) { + const { t, locale } = useI18n(); + return ; +} + +function Subtotals({ values }: { values: Record }) { + const { t, locale } = useI18n(); + return <>{Object.entries(values).map(([currency, amount]) =>

{t("spend.knownSubtotal", { amount: money(amount, currency, locale) })}

)}; +} + +export function TurnSpend({ projectId, turnId }: { projectId: string; turnId: string }) { + const { t, locale } = useI18n(); + const snapshot = useSnapshot(projectId); + const hasJobs = snapshot?.jobs.some(job => job.agentRunId === turnId); + const [status, setStatus] = useState(); + useEffect(() => { + if (!hasJobs) return; + const abort = new AbortController(); + void spendQuery(projectId, "spend.status", {agentRunId: turnId}, abort.signal) + .then(value => { if (!abort.signal.aborted) setStatus(value); }).catch(() => {}); + return () => abort.abort(); + }, [hasJobs, projectId, turnId, snapshot?.eventCursor]); + if (!hasJobs || !status?.turn?.callCount) return null; + const { settled, held, unknown } = status.turn; + return
{t("spend.turn")} + {t("spend.summary", { settled: money(settled, status.policy.currency, locale), held: money(held, status.policy.currency, locale) })} + {unknown > 0 &&

{t("spend.coverage", { count: unknown })}

} +
; +} + +export function GenerationEstimate({ projectId, itemId, count, modelId, prompt, priceRevision, draft }: { + projectId: string; itemId: string; count: number; modelId: string; prompt: string; priceRevision: string; draft: GenerationSettings; +}) { + const { t, locale } = useI18n(); + const snapshot = useSnapshot(projectId); + const [result, setResult] = useState<{ key: string; value: QuoteView | null }>(); + const item = snapshot?.canvasItems.find(i => i.id === itemId); + const specId = item?.binding.role === "generation" ? item.binding.objectRef.id : + item && "draftSpec" in item.binding ? item.binding.draftSpec?.id : undefined; + const spec = snapshot?.generationSpecs.find(s => s.id === specId); + const key = JSON.stringify([projectId, itemId, specId, snapshot?.eventCursor, count, modelId, prompt, priceRevision]); + const matches = spec?.modelConfigId === modelId && spec.prompt === prompt && + (spec.kind !== "audio" || (spec.parameters.creationType ?? "audio") === (draft.audioCreationType ?? "audio")) && + (spec.kind !== "audio" || spec.parameters.creationType !== "music" || + ((draft.durationSeconds == null || spec.parameters.durationSeconds === draft.durationSeconds) && + (spec.parameters.durationFromReference ?? true) === (draft.durationFromReference ?? true))) && + (spec.kind !== "video" || draft.durationSeconds == null || spec.parameters.durationSeconds === draft.durationSeconds); + useEffect(() => { + if (!specId || !matches) return; + const abort = new AbortController(); + const timer = window.setTimeout(() => { + void spendQuery(projectId, "generation.quote", { specId, originItemId: itemId, count }, abort.signal) + .then(value => { if (!abort.signal.aborted) setResult({ key, value }); }) + .catch(() => { if (!abort.signal.aborted) setResult({ key, value: null }); }); + }, 180); + return () => { clearTimeout(timer); abort.abort(); }; + }, [projectId, itemId, specId, count, matches, key]); + if (!matches) return null; + if (result?.key !== key) return {t("spend.estimating")}; + if (!result.value) return {t("spend.estimateUnavailable")}; + const { amount, currency, projectAfter, quote } = result.value; + return
+ {t("spend.estimate", { action: t(`spend.action.${generationOutput(quote)}`, {count}), amount: amount == null ? t("spend.unknown") : money(amount, currency, locale) })} + {projectAfter != null && <> · {t("spend.after", { amount: money(projectAfter, currency, locale) })}} + {amount == null && } +
; +} + +export function GroupEstimate({ document, groupId, models }: { + document: CanvasDocument; groupId: string; models: readonly ModelConfig[]; +}) { + const { t, locale } = useI18n(); + const snapshot = useSnapshot(document.id); + const workflow = snapshot && workflowRequest(document, groupId, snapshot, models); + const members = workflow && JSON.stringify(workflow.members); + const key = JSON.stringify([document.id, members, snapshot?.eventCursor, models.map(model => model.price)]); + const [result, setResult] = useState<{ key: string; value: QuoteView }>(); + useEffect(() => { + if (!members) return; + const abort = new AbortController(); + const timer = window.setTimeout(() => { + void spendQuery(document.id, "generation.groupQuote", {workflow: {members: JSON.parse(members)}}, abort.signal) + .then(value => { if (!abort.signal.aborted) setResult({ key, value }); }).catch(() => {}); + }, 180); + return () => { clearTimeout(timer); abort.abort(); }; + }, [document.id, members, key]); + if (!result || result.key !== key) return null; + const { quote, currency, amount, subtotals, projectAfter } = result.value; + return
+ {t("spend.estimate", {action: t(`spend.action.${generationOutput(quote)}`, {count: quote.candidates ?? quote.count}), amount: amount == null ? t("spend.unknown") : money(amount, currency, locale)})} + {projectAfter != null && <> · {t("spend.after", {amount: money(projectAfter, currency, locale)})}} + {!!quote.deferred?.length && <> · {t("spend.awaitingInputs", {count: quote.deferred.length})}} + {!!quote.skipped?.length && <> · {t("spend.skippedSteps", {count: quote.skipped.length})}} + {amount == null && } +
; +} + +export function ToolEstimate({ projectId, itemId, tool, priceRevision }: { + projectId: string; itemId: string; tool: string; priceRevision: string; +}) { + const snapshot = useSnapshot(projectId); + const { t, locale } = useI18n(); + const item = snapshot?.canvasItems.find(i => i.id === itemId); + const ref = item && "editors" in item ? item.editors.find(e => e.kind === "media_edit") : undefined; + const editor = snapshot?.editorDocuments.find(e => e.id === ref?.id); + const key = JSON.stringify([projectId, itemId, item?.revision, editor?.id, editor?.revision, tool, priceRevision, snapshot?.project.revision]); + const [saved, setSaved] = useState<{ key: string; value: QuoteView }>(); + useEffect(() => { + if (!item || editor?.kind !== "media_edit" || editor.data.tool !== tool || !editor.data.sources.length) return; + const { sources, parameters, selection } = editor.data; + const abort = new AbortController(); + const timer = setTimeout(() => { + void request(`/creation/projects/${projectId}/tool-tasks/quote`, { + ...json("POST", { id: crypto.randomUUID(), tool, parameters, sourceAssetIds: sources.map(s => s.assetId), + boxes: selection?.boxes ?? [], maskAssetId: selection?.mask?.assetId, + modelConfigIds: typeof parameters.imageModelConfigId === "string" && parameters.imageModelConfigId ? {"image.edit": parameters.imageModelConfigId} : {}, + draft: { itemId, itemRevision: item.revision, editorId: editor.id, editorRevision: editor.revision } }), + signal: abort.signal, + }).then(value => { if (!abort.signal.aborted) setSaved({key, value}); }).catch(() => {}); + }, 250); + return () => { clearTimeout(timer); abort.abort(); }; + }, [key]); + if (saved?.key !== key || !saved.value.quote.lines.length) return null; + const { amount, currency, quote, subtotals, projectAfter } = saved.value; + return
{t("spend.toolQuote", { amount: amount == null ? t("spend.unknown") : money(amount, currency, locale) })} + {projectAfter != null && <> · {t("spend.after", {amount: money(projectAfter, currency, locale)})}} + + {amount == null && }
; +} + +function SpendBalances({ status }: { status: SpendStatus }) { + const { t, locale } = useI18n(); + const { currency, cap } = status.policy; + const spent = money(status.settled, currency, locale); + const held = money(status.held, currency, locale); + const batch = status.settledBatch; + const spentHelp = batch && (batch.kind === "image" || batch.kind === "video") + ? t(`spend.spentHelp.${batch.kind}`, {count: batch.count, amount: spent}) + : t("spend.spentHelp"); + const heldHelp = status.unknown ? t("spend.heldHelp.unknown") : Number(status.held) === 0 + ? t("spend.heldHelp.zero") : t("spend.heldHelp.active", {amount: held}); + return
+
{t("spend.cap")}{cap == null ? t("spend.off") : money(cap, currency, locale)}
+ {([["spend.spent", spent, spentHelp], ["spend.held", held, heldHelp]] as const).map(([label, amount, help]) => + + {t(label)} {amount} + )} +
; +} + +function ReviewCard({ projectId, entry, status, onSettings, onChange, onBusyChange }: { + projectId: string; entry: PendingSpend; status: SpendStatus; onSettings?: () => void; onChange: (decision?: "approve" | "cancel") => void; + onBusyChange: (busy: boolean) => void; +}) { + const { t, locale } = useI18n(); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const { request: batch, reason } = entry; + const currency = status.policy.currency; + const { quote } = batch; + const output = generationOutput(quote); + const count = quote.candidates ?? quote.count; + const tool = batch.toolTask?.tool; + const toolName = CANVAS_TOOLS.find(item => item.id === tool)?.title; + const title = batch.toolTask + ? toolName ? translateToolText(locale, toolName) : t(tool === "selection-preview" ? "spend.selectionPreview" : "spend.mediaTool") + : t(`spend.action.${output}`, {count}); + const unit = uniformOutputPrice(quote); + const unitPrice = unit && !batch.toolTask && output !== "tasks" + ? t(`spend.each.${output}`, {amount: money(unit.amount, unit.currency, locale), model: unit.model}) : undefined; + const runsSteps = Boolean(batch.toolTask || quote.deferred?.length); + const cap = entry.suggestedCap == null ? null : money(entry.suggestedCap, currency, locale); + let approvalLabel; + switch (reason) { + case "stale": case "stale_inputs": case "prior_unknown": case "unpriced": break; + case "over_cap": + if (cap != null) approvalLabel = t(runsSteps ? "spend.raiseRun" : "spend.raiseGenerate", {amount: cap}); + break; + case "unknown_confirmation": approvalLabel = t("spend.allowUnknown"); break; + default: + approvalLabel = t(quote.deferred?.length ? "spend.runUpstream" : runsSteps ? "spend.approve" : "spend.generate"); + } + const decide = async (decision: "approve" | "cancel") => { + if (busy) return; + setBusy(true); + onBusyChange(true); + setError(""); + try { + const raising = decision === "approve" && reason === "over_cap"; + const versions = [...(decision === "approve" ? batch.versions : []), objectVersion("spend_request", batch)]; + if (raising) versions.push({ objectType: "project", id: projectId, revision: status.projectRevision }); + await creationClient(projectId).command("spend.review", { + requestId: batch.id, fingerprint: entry.fingerprint, decision, + acceptUnknown: decision === "approve" && reason === "unknown_confirmation", + ...(raising ? { newCap: entry.suggestedCap } : {}), + }, versions); + onChange(decision); + } catch (failure) { setError(errorMessage(failure)); onChange(); } + finally { setBusy(false); onBusyChange(false); } + }; + return
+
+

{title}

{unitPrice &&
{unitPrice}
}
+
{t("spend.batchEstimate")} + {entry.amount == null ? t("spend.unknown") : money(entry.amount, currency, locale)} +
+
+ {entry.amount == null && } + {quote.lines.length > 0 &&
+ {t("spend.priceDetails")} +
} + {!!batch.quote.deferred?.length &&

{t("spend.deferred", { count: batch.quote.deferred.length })}

} + {!!batch.quote.skipped?.length &&

{t("spend.skippedSteps", {count: batch.quote.skipped.length})}

} + {reason === "over_cap" &&

{t("spend.shortfall", {available: money(status.available!, currency, locale), missing: money(entry.shortfall!, currency, locale)})} + {cap == null && <> {t("spend.capOutOfRange")}}

} + {reason === "unpriced" &&

{t("spend.needPrice")}

} + {reason === "prior_unknown" &&

{t("spend.priorUnknown")}

} + {reason === "stale" &&

{t("spend.stale")}

} + {reason === "stale_inputs" &&

{t("spend.staleInputs")}

} + +
+ {reason === "unpriced" && onSettings && } + {approvalLabel && } + +
+ {error &&

{error}

} +
; +} + +function PolicyForm({ projectId, status }: { projectId: string; status: SpendStatus }) { + const t = useT(); + const [currency, setCurrency] = useState(status.policy.currency); + const [threshold, setThreshold] = useState(status.policy.threshold ?? ""); + const [cap, setCap] = useState(status.policy.cap ?? ""); + const [error, setError] = useState(""); + return
{ + e.preventDefault(); + try { + await creationClient(projectId).command("spend.policy", { currency, threshold: threshold || null, cap: cap || null }, + [{ objectType: "project", id: projectId, revision: status.projectRevision }]); + setError(""); + } catch (failure) { setError(errorMessage(failure)); } + }}> + + + + {error &&

{error}

} +
; +} + +export function ProjectSpend({ projectId, onSettings, onNotify }: { + projectId: string; onSettings?: () => void; onNotify: (message: string) => void; +}) { + const { t, locale } = useI18n(); + const snapshot = useSnapshot(projectId); + const pendingIds = new Set(snapshot?.spendRequests?.filter(r => r.status === "pending").map(r => r.id)); + const pendingCount = pendingIds.size; + const pendingKey = [...pendingIds].join(","); + const [view, setView] = useState(() => { + const reviewId = new URLSearchParams(window.location.search).get("spendReview"); + return reviewId && pendingIds.has(reviewId) ? reviewId : null; + }); + const seen = useRef(new Set()); + const [busy, setBusy] = useState(false); + const [status, setStatus] = useState(); + const [error, setError] = useState(""); + const [revision, reload] = useState(0); + const dismiss = () => { + pendingIds.forEach(id => seen.current.add(id)); + setView(null); + }; + useEffect(() => { + const reveal = (event: Event) => { + if ((event as CustomEvent).detail === projectId && pendingCount) setView([...pendingIds][0]); + }; + window.addEventListener("opendirector:spend-review", reveal); + return () => window.removeEventListener("opendirector:spend-review", reveal); + }, [projectId, pendingKey]); + // Both canvas and Agent requests arrive through the project snapshot. Show each + // new request once; closing the dialog keeps it pending without reopening it. + useEffect(() => { + if (view && pendingIds.has(view)) { seen.current.add(view); return; } + const next = [...pendingIds].find(id => !seen.current.has(id)); + if (next) { seen.current.add(next); setView(next); } + else if (view !== "overview") setView(null); + }, [pendingKey, view]); + const shown = view != null; + useEffect(() => { + if (!shown || !snapshot) return; + const abort = new AbortController(); + void spendQuery(projectId, "spend.status", {}, abort.signal).then(value => { + if (!abort.signal.aborted) { setStatus(value); setError(""); } + }).catch(failure => { if (!abort.signal.aborted) setError(errorMessage(failure)); }); + return () => abort.abort(); + }, [shown, projectId, snapshot, revision]); + const reviewed = (decision?: "approve" | "cancel") => { + reload(r => r + 1); + if (!decision) return; + onNotify(t(decision === "approve" ? "spend.reviewSubmitted" : "spend.reviewCancelled")); + }; + const review = status?.pending.find(entry => entry.request.id === view && pendingIds.has(view)); + return
+ setView(pendingCount ? [...pendingIds][0] : "overview")}> + + {pendingCount > 0 && + {shown && + {error &&

{error}

} + {(!status || (view !== "overview" && !review)) && !error &&

{t("spend.estimating")}

} + {status && <> + {(status.legacy > 0 || status.unknown > 0) &&

{t("spend.coverage", { count: status.legacy + status.unknown })}

} + {review && { dismiss(); onSettings(); })} onChange={reviewed} onBusyChange={setBusy} />} + {view === "overview" ? <> + + {pendingCount > 0 &&
} +
{t("spend.controls")}
+
{t("spend.log")} + {(status.workflows ?? []).map(run =>

{t("spend.workflowProgress", { + completed: run.completed, total: run.total, state: t(`spend.workflowState.${run.state}`), + })}{run.skipped > 0 && <> · {t("spend.skippedSteps", {count: run.skipped})}}

)} + {status.since && {t("spend.since", { date: new Date(status.since).toLocaleString(locale) })}} +
    {[...(snapshot?.spendCalls ?? [])].reverse().map(call =>
  • + {t(`spend.operation.${call.line.operation}` as "spend.operation.image")} · {call.line.modelId} · {t(`spend.state.${call.state}`)} + {t("spend.estimateAmount")} {call.line.amount ?? t("spend.unknown")} {call.line.price?.currency} + {call.calculated != null && <> · {t("spend.calculated")} {call.calculated}} + {call.usage != null && call.usageSource && call.line.price && <> · {t(`spend.usage.${call.usageSource}`)} {call.usage} {t(`spend.unit.${call.line.price.unit}`)}} + {call.reported != null && <> · {t("spend.reported")} {call.reported}} + +
  • )}
+
+ : } + } +
} +
; +} + +export function ModelPriceEditor({ model, refresh }: { model: ModelConfig; refresh: () => Promise }) { + const t = useT(); + const [unit, setUnit] = useState(model.price?.unit ?? "request"); + const [currency, setCurrency] = useState(model.price?.currency ?? "USD"); + const [rate, setRate] = useState(model.price?.rate ?? ""); + const [message, setMessage] = useState(""); + return
{ + event.preventDefault(); + try { + await request(`/model-configs/${model.id}/price`, json("PUT", rate ? { currency, unit, rate } : null)); + await refresh(); setMessage(t("spend.saved")); + } catch (failure) { setMessage(errorMessage(failure)); } + }}> + {model.modelId} + + + + {message && {message}} +
; +} diff --git a/src/canvas/SpendDialog.tsx b/src/canvas/SpendDialog.tsx new file mode 100644 index 000000000..e6f13037c --- /dev/null +++ b/src/canvas/SpendDialog.tsx @@ -0,0 +1,57 @@ +import { useLayoutEffect, useRef, type ReactNode } from "react"; +import { createPortal } from "react-dom"; +import { useT } from "../i18n/I18nProvider"; +import { CanvasIcon } from "./CanvasIcon"; + +/** A review waits for an existing modal, then keeps keyboard focus on the decision. */ +export function SpendDialog({ title, focusKey, busy, onClose, children }: { + title: string; focusKey: string; busy: boolean; onClose: () => void; children: ReactNode; +}) { + const t = useT(); + const dialog = useRef(null); + const close = useRef(null); + useLayoutEffect(() => { + const element = dialog.current!; + const observer = new MutationObserver(show); + function show() { + if (element.open || document.querySelector("dialog:modal")) return; + element.showModal(); + close.current?.focus({preventScroll: true}); + observer.disconnect(); + } + // Initial setup or model settings must finish before a pending review opens. + observer.observe(document.body, { subtree: true, childList: true, attributes: true, attributeFilter: ["open"] }); + show(); + // Close before React removes the element so the browser restores the opener's focus. + return () => { observer.disconnect(); element.close(); }; + }, []); + useLayoutEffect(() => { + const element = dialog.current!; + if (element.open && !busy && !element.contains(document.activeElement)) close.current?.focus({preventScroll: true}); + }, [focusKey, busy]); + useLayoutEffect(() => { + const escape = (event: KeyboardEvent) => { + const element = dialog.current!; + if (event.key !== "Escape" || event.defaultPrevented || event.isComposing || + !element.open || !element.contains(document.activeElement)) return; + // Canvas popovers listen on document capture. The modal owns this Escape. + event.preventDefault(); + event.stopPropagation(); + if (!busy) onClose(); + }; + window.addEventListener("keydown", escape, true); + return () => window.removeEventListener("keydown", escape, true); + }, [busy, onClose]); + return createPortal( event.stopPropagation()} onCancel={event => { + event.preventDefault(); + if (!busy) onClose(); + }}> +
+

{title}

+ +
+
{children}
+
, document.body); +} diff --git a/src/canvas/TooltipButton.tsx b/src/canvas/TooltipButton.tsx index 0f788261d..3fc78e31f 100644 --- a/src/canvas/TooltipButton.tsx +++ b/src/canvas/TooltipButton.tsx @@ -38,6 +38,7 @@ export function TooltipButton({ tooltipCompact = false, tooltipDelay = 200, showTooltip = true, + showOnClick = false, children, onPointerEnter, onPointerLeave, @@ -55,6 +56,8 @@ export function TooltipButton({ tooltipDelay?: number; /** Off when the button already shows its label as text. */ showTooltip?: boolean; + /** An informational trigger can also reveal its description on touch. */ + showOnClick?: boolean; }) { const id = useId(); const context = useContext(TooltipContext); @@ -162,19 +165,23 @@ export function TooltipButton({ } dismiss(); }; + const press = (event: PointerEvent) => { + if (showOnClick && event.target instanceof Node && button.current?.contains(event.target)) return; + dismiss(); + }; window.addEventListener("keydown", escape, true); - window.addEventListener("pointerdown", dismiss, true); + window.addEventListener("pointerdown", press, true); window.addEventListener("blur", dismiss); window.addEventListener("resize", dismiss); window.addEventListener("scroll", dismiss, true); return () => { window.removeEventListener("keydown", escape, true); - window.removeEventListener("pointerdown", dismiss, true); + window.removeEventListener("pointerdown", press, true); window.removeEventListener("blur", dismiss); window.removeEventListener("resize", dismiss); window.removeEventListener("scroll", dismiss, true); }; - }, [open, pending]); + }, [open, pending, showOnClick]); return ( <> @@ -205,9 +212,10 @@ export function TooltipButton({ onBlur?.(event); close(); }} - onPointerDownCapture={close} + onPointerDownCapture={showOnClick ? undefined : close} onClick={(event) => { - close(); + if (showOnClick && !open) show(0); + else close(); onClick?.(event); }} > @@ -225,7 +233,7 @@ export function TooltipButton({ {label} {shortcut && {shortcut}}
, - document.body, + button.current?.closest("dialog") ?? document.body, )} ); diff --git a/src/canvas/groupWorkflow.ts b/src/canvas/groupWorkflow.ts index 24b69f543..954b3d3ff 100644 --- a/src/canvas/groupWorkflow.ts +++ b/src/canvas/groupWorkflow.ts @@ -7,16 +7,10 @@ export interface WorkflowOutcome { skipped: string[]; } -/** - * Runs workflow steps in reference order. A step starts once every step it - * references, directly or through non-step nodes, has succeeded; steps without pending references run - * concurrently. A failure skips everything downstream of it. - */ -export async function runWorkflowSteps( +export function workflowDependencies( stepIds: readonly string[], edges: readonly Pick[], - runStep: (id: string) => Promise, -): Promise { +) { const ids = new Set(stepIds); const sources = new Map(); for (const edge of edges) @@ -24,7 +18,7 @@ export async function runWorkflowSteps( sources.set(edge.target, [...(sources.get(edge.target) ?? []), edge.source]); // A step depends on the nearest steps upstream of it, also through // non-step nodes such as a subject or stack that carries a result onward. - const upstream = new Map( + return new Map( stepIds.map((id) => { const found = new Set(); const seen = new Set([id]); @@ -39,6 +33,19 @@ export async function runWorkflowSteps( return [id, found]; }), ); +} + +/** + * Runs workflow steps in reference order. A step starts once every step it + * references, directly or through non-step nodes, has succeeded; steps without pending references run + * concurrently. A failure skips everything downstream of it. + */ +export async function runWorkflowSteps( + stepIds: readonly string[], + edges: readonly Pick[], + runStep: (id: string) => Promise, +): Promise { + const upstream = workflowDependencies(stepIds, edges); const outcome = new Map(); const started = new Set(); let running = 0; diff --git a/src/canvas/project-spend.css b/src/canvas/project-spend.css new file mode 100644 index 000000000..9d4decc32 --- /dev/null +++ b/src/canvas/project-spend.css @@ -0,0 +1,128 @@ +.cw-spend { position: relative; font-size: 13px; } +.cw-spend-panel, .cw-spend-form input, .cw-spend-form select { + border: 1px solid var(--settings-border); border-radius: 8px; background: var(--settings-surface); color: var(--settings-text); +} +.cw-spend-toggle { position: relative; } +.cw-spend-dot { position: absolute; top: 2px; right: 2px; width: 6px; height: 6px; border-radius: 50%; background: var(--cw-control-accent); } +.cw-spend-panel { + padding: 14px; + font-size: 14px; + line-height: 1.45; + font-variant-numeric: tabular-nums; + box-shadow: 0 5px 20px #2736471a; +} +.cw-spend-dialog { + position: fixed; + inset: 0; + box-sizing: border-box; + width: min(460px, calc(100vw - 32px)); + max-width: none; + max-height: calc(100dvh - 32px); + margin: auto; + overflow: visible; +} +.cw-spend-dialog[open] { display: flex; flex-direction: column; } +.cw-spend-dialog::backdrop { background: #0006; } +:root[data-theme="light"] .cw-spend-dialog::backdrop { background: #29456b30; } +.cw-spend-body { min-height: 0; overflow: auto; container-type: inline-size; } +.cw-spend-dialog .cw-spend-heading { flex: none; } +.cw-spend-overview { + padding: 3px 0; + border: 0; + background: transparent; + color: var(--settings-muted); + text-decoration: underline; + text-underline-offset: 3px; + cursor: pointer; +} +.cw-spend-panel :is(button, input, select, small, summary) { font: inherit; } +.cw-spend-panel p { margin: 0 0 8px; } +.cw-spend-heading { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 8px; } +.cw-spend-heading h3 { margin: 0; font-size: inherit; font-weight: 600; } +.cw-spend-heading .cw-spend-close { + display: grid; + place-items: center; + inline-size: 32px; + block-size: 32px; + flex: none; + border: 0; + border-radius: 6px; + background: transparent; + color: inherit; + cursor: pointer; +} +.cw-spend-heading .cw-spend-close:hover { background: var(--settings-hover); } +.cw-spend-panel details, .cw-spend-estimate { margin: 6px 0; } +.cw-spend-panel summary, .cw-spend-estimate summary { cursor: pointer; } +.cw-spend-card { padding: 6px 0 10px; overflow-wrap: anywhere; } +.cw-spend-card + .cw-spend-card { border-top: 1px solid var(--settings-border); padding-top: 12px; } +.cw-spend-offer { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; } +.cw-spend-offer > * { min-width: 0; } +.cw-spend-offer > :last-child { text-align: end; } +.cw-spend-title, .cw-spend-amount { + display: block; + margin: 0; + font-size: 18px; + line-height: 1.35; + font-weight: 600; +} +.cw-spend-unit, .cw-spend-quote-label, .cw-spend-price-details > summary { color: var(--settings-muted); } +.cw-spend-card .cw-spend-unit { margin: 3px 0 0; } +.cw-spend-card .cw-spend-reason { + margin: 10px 0; + padding: 7px 10px; + border-radius: 6px; + background: var(--settings-active); +} +.cw-spend-balances { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; margin: 8px 0; } +.cw-spend-balances .cw-spend-metric { + min-width: 0; + padding: 3px 0; + border: 0; + border-radius: 4px; + background: transparent; + color: inherit; + text-align: start; + overflow-wrap: anywhere; +} +.cw-spend-metric > span { display: inline-flex; align-items: center; gap: 3px; color: var(--settings-muted); } +.cw-spend-metric strong { display: block; font-weight: 500; } +.cw-spend-balances button.cw-spend-metric { cursor: help; } +.cw-spend-balances button.cw-spend-metric:hover { background: var(--settings-hover); } +.cw-spend-lines { list-style: none; padding: 0; margin: 5px 0 9px; } +.cw-spend-lines li { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 3px 8px; padding: 3px 0; overflow-wrap: anywhere; } +.cw-spend-lines small { width: 100%; color: var(--settings-muted); } +.cw-spend-actions, .cw-spend-form { display: flex; flex-wrap: wrap; gap: 7px; margin: 7px 0; } +.cw-spend-form { flex-direction: column; align-items: stretch; } +.cw-spend-form label { display: flex; align-items: center; justify-content: space-between; gap: 8px; } +.cw-spend-form input, .cw-spend-form select { width: 9em; padding: 4px; } +.cw-spend-actions button, .cw-spend-form button { background: var(--settings-active); color: var(--settings-text); padding: 5px 10px; border: 0; border-radius: 6px; cursor: pointer; } +.cw-composer-quote { + flex: 0 0 auto; + min-height: 1.5em; + max-height: 28vh; + overflow: auto; + margin: 6px 0; + font-size: 12px; + line-height: 1.5; + color: var(--settings-muted); +} +.cw-composer-quote .cw-spend-estimate { margin: 0; } +.cw-group-estimate { width: max-content; max-width: 320px; max-height: 32vh; overflow: auto; background: var(--settings-surface); border: 1px solid var(--settings-border); border-radius: 8px; padding: 5px 9px; pointer-events: auto; } +.cw-spend-actions button:hover, .cw-spend-form button:hover { background: var(--settings-hover); } +.cw-spend-actions button:disabled { opacity: .55; cursor: default; } +.cw-spend-card .cw-spend-actions { border-top: 1px solid var(--settings-border); padding-top: 10px; gap: 8px; } +.cw-spend-actions :is(.cw-spend-confirm, .cw-spend-cancel) { min-height: 36px; } +.cw-spend-actions .cw-spend-confirm { flex: 1 1 auto; font-weight: 600; color: var(--cw-control-on-accent); background: var(--cw-control-accent); } +.cw-spend-actions .cw-spend-confirm:hover { background: var(--cw-control-accent-hover); } +.cw-spend-actions .cw-spend-cancel { background: transparent; border: 1px solid var(--settings-border); } +@container (max-width: 315px) { + .cw-spend-balances { grid-template-columns: 1fr; gap: 2px; } + .cw-spend-balances .cw-spend-metric { display: flex; align-items: center; justify-content: space-between; gap: 8px; } + .cw-spend-card .cw-spend-actions > button { width: 100%; } +} +@media (pointer: coarse) { + .cw-spend-heading .cw-spend-close, .cw-spend-balances button, .cw-spend-card .cw-spend-actions button { min-height: 44px; } + .cw-spend-heading .cw-spend-close { min-width: 44px; } +} +.cw-spend-estimate { font-size: 12px; color: var(--settings-text); } diff --git a/src/canvas/spendPresentation.ts b/src/canvas/spendPresentation.ts new file mode 100644 index 000000000..6aa5a2f97 --- /dev/null +++ b/src/canvas/spendPresentation.ts @@ -0,0 +1,33 @@ +/// +import type { SpendQuote } from "../contracts/generated.ts"; +import type { Locale } from "../i18n/types.ts"; + +export function money(value: string, currency: string, locale: Locale): string { + // Intl accepts decimal strings without first rounding them to JavaScript numbers. + const parts = new Intl.NumberFormat(locale, { style: "currency", currency, + currencyDisplay: locale === "zh-CN" ? "name" : "code", maximumFractionDigits: 24, + }).formatToParts(value as `${number}`); + return parts.map(part => locale === "zh-CN" && part.type === "currency" ? " " + part.value : part.value).join(""); +} + +/** A workflow flattens all quoted provider calls; one piece of music may use two. */ +export function generationOutput(quote: SpendQuote) { + const operation = quote.lines.at(-1)?.operation; + if (quote.candidates != null && (quote.lines.length !== quote.candidates || + !quote.lines.every(line => line.operation === operation))) return "tasks"; + switch (operation) { + case "image": case "video": case "music": case "speech": return operation; + default: return "tasks"; + } +} + +/** Only a single fixed-price call per output can be summarized as a unit price. */ +export function uniformOutputPrice(quote: SpendQuote) { + const first = quote.lines[0]; + if (!first?.price || first.amount == null || quote.lines.length !== (quote.candidates ?? 1)) return; + const { currency } = first.price; + if (quote.lines.every(line => line.quantityBasis !== "maximum" && line.operation === first.operation && + line.modelId === first.modelId && line.price?.currency === currency && line.amount === first.amount)) { + return {amount: first.amount, currency, model: first.modelId}; + } +} diff --git a/src/canvas/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx index 1e15801be..b2b4b5cf1 100644 --- a/src/canvas/workspace/WorkspaceView.tsx +++ b/src/canvas/workspace/WorkspaceView.tsx @@ -1,4 +1,6 @@ import { projectDisplayName } from "../projectDisplayName"; +import type { ModelConfig } from "../../backend/rules.ts"; +import { GroupEstimate, ProjectSpend, ToolEstimate } from "../ProjectSpend"; import { DesktopSidebar } from "./DesktopSidebar"; import { Background, BackgroundVariant, MiniMap, SelectionMode, ViewportPortal } from "@xyflow/react"; @@ -78,7 +80,7 @@ import { NodeSelectionToolbar } from "../NodeSelectionToolbar"; import { TextNodeWindow } from "../TextNodeWindow"; import { SelectionBarAnchor } from "../SelectionBarAnchor"; import { NodeTaskPanel } from "../NodeTaskPanel"; -import { layoutGroup, orderNodesForCanvas, unstackSelection, type GroupLayout } from "../operations"; +import { groupDescendants, layoutGroup, orderNodesForCanvas, unstackSelection, type GroupLayout } from "../operations"; import { ProjectSelector } from "../ProjectSelector"; import "../settings.css"; @@ -439,6 +441,12 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { }, [outputState?.output.id]); const [workflowGroups, setWorkflowGroups] = useState>(() => new Set()); + const groupSnapshot = ready && single?.type === "group" ? creationClient(doc.id).snapshot : undefined; + const memberIds = new Set(groupSnapshot && single ? groupDescendants(doc.nodes, single.id).map(node => node.id) : []); + const workflowWaiting = groupSnapshot?.spendRequests?.some(request => request.status === "pending" && request.workflowId && + [...(request.groupItems ?? []), ...(request.quote.deferred ?? [])].some(id => memberIds.has(id))); + const workflowActive = groupSnapshot?.jobs.some(job => job.batchId && job.originItemId && memberIds.has(job.originItemId) && + (job.status === "running" || job.status === "queued")); const runWorkflow = (groupId: string) => { if (workflowGroups.has(groupId)) return; setWorkflowGroups((current) => new Set(current).add(groupId)); @@ -1245,6 +1253,7 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { {!ready &&
}
+ {ready && !welcomeOpen && { setSettingsCategory("models"); setSettingsOpen(true); }} />}
runWorkflow(single.id) : undefined} - workflowRunning={workflowGroups.has(single.id)} + workflowRunning={workflowGroups.has(single.id) || workflowActive} + workflowWaiting={workflowWaiting} onUngroup={single.type === "group" ? ungroup : undefined} onLayout={ single.type === "group" @@ -1604,6 +1614,7 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { } onDuplicate={() => paste(true)} /> + {single.type === "group" && }
)} {activeAction && actionNode && ( @@ -1766,6 +1777,7 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { onGenerate={(task) => void runToolTask(activeAction, task)} /> )} + m.price))} />
)} @@ -1915,6 +1927,7 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { /> ) : ( => { const id = crypto.randomUUID(); let jobIds: string[] = []; @@ -179,12 +179,15 @@ export function useWorkspaceGeneration(rt: WorkspaceRuntime) { resultMode === "additional" ? "candidate_only" : "if_current", request.batchId, run.controller.signal, + count, ); if (run.controller.signal.aborted) { // Once sent, await the original receipt before cancelling its jobs. // Never abort delivery and mint a replacement command. for (const jobId of receipt.jobIds) await creationClient(origin.documentId).control(jobId, "cancel"); + } else if (receipt.status === "awaiting_confirmation") { + notify(t("spend.waiting")); } else if (receipt.status === "accepted") { jobIds = [...(receipt.jobIds ?? [])]; notify(t("canvas.workspace.toast.generationSubmitted")); @@ -380,6 +383,11 @@ export function useWorkspaceGeneration(rt: WorkspaceRuntime) { }, run.controller.signal, ); + if (submitted.spendRequestId) { + setJobs(await readJobs()); + notify(t("spend.waiting")); + return; + } Object.assign(run, submitted); updateJob(id, { taskId: submitted.taskId }); setJobs(await readJobs()); @@ -550,17 +558,7 @@ export function useWorkspaceGeneration(rt: WorkspaceRuntime) { return Promise.resolve([]); } const batchId = plan.count > 1 ? crypto.randomUUID() : undefined; - const runs: Promise[] = []; - for (let index = 0; index < plan.count; index++) - runs.push( - runServiceTask( - { ...plan.request, batchId, executionSlot: index }, - plan.origin, - plan.label, - index === 0 ? "replace" : "additional", - ), - ); - return Promise.all(runs).then((ids) => ids.flat()); + return runServiceTask({ ...plan.request, batchId }, plan.origin, plan.label, "replace", plan.count); }; const cancelServiceRuns = (nodeId: string) => { for (const job of jobs) @@ -644,126 +642,22 @@ export function useWorkspaceGeneration(rt: WorkspaceRuntime) { ); return none; }; - /** Latest render's generation entry point; a workflow outlives the render that started it. */ - const prepareLatest = useRef(prepareGeneration); - prepareLatest.current = prepareGeneration; - /** - * Resolves once every job is terminal (true when one succeeded), or false - * when the canvas has switched to another project. - */ - const awaitJobs = (documentId: string, jobIds: readonly string[]) => - new Promise((resolve) => { - const client = creationClient(documentId); - const terminal = ["succeeded", "failed", "cancelled", "interrupted"]; - let finish = () => {}; - const check = () => { - if (!mounted.current || historyRef.current.present.id !== documentId) { - finish(); - resolve(false); - return; - } - const states = jobIds.map( - (id) => client.snapshot.jobs.find((job) => job.id === id)?.status, - ); - if (!states.every((status) => status && terminal.includes(status))) return; - finish(); - resolve(states.includes("succeeded")); - }; - const stop = client.listen(check); - const poll = setInterval(check, 1000); - finish = () => { - stop(); - clearInterval(poll); - }; - check(); - }); - /** - * Waits until the canvas shows the result the service adopted for the node, - * so a downstream step reads the new content (for example generated text - * used as its prompt). Resolves false when no result was adopted (a - * candidate-only result, or inputs edited while running), after three - * minutes, or when the canvas switched project. - */ - const awaitDisplayed = (documentId: string, nodeId: string, jobIds: readonly string[]) => - new Promise((resolve) => { - const snapshot = creationClient(documentId).snapshot; - const adopted = new Set( - snapshot.jobs.filter((job) => jobIds.includes(job.id) && job.adopted).map((job) => job.id), - ); - const assets = new Set( - snapshot.results - .filter((result) => adopted.has(result.jobId)) - .map((result) => result.asset.assetId), - ); - if (!assets.size) { - resolve(false); - return; - } - const started = Date.now(); - const check = () => { - const present = historyRef.current.present; - const node = present.nodes.find((candidate) => candidate.id === nodeId); - const done = - present.id === documentId && node && assets.has(node.data.backendAssetId ?? "") - ? true - : !mounted.current || present.id !== documentId || !node || Date.now() - started > 180_000 - ? false - : undefined; - if (done === undefined) return; - clearInterval(poll); - resolve(done); - }; - const poll = setInterval(check, 200); - check(); - }); - /** - * Runs a group's generation nodes. A node waits for the members it - * references, directly or through non-generating nodes, and is skipped when - * one of them fails; independent nodes run concurrently. Submissions go one - * at a time, as the project's command queue would serialize them anyway, so - * each starts from the canvas the previous one left behind. - */ const runGroupWorkflow = async (groupId: string) => { const document = historyRef.current.present; - const steps = groupDescendants(document.nodes, groupId).filter((node) => - isWorkflowStep( - node, - document.edges.some( - (edge) => edge.target === node.id && edge.intent !== "post_edit_result", - ), - ), - ); - if (!steps.length) { + if (!workflowSteps(document, groupId).length) { notify(t("canvas.workspace.group.noRunnableNodes")); return; } - notify(t("canvas.workspace.group.workflowStarted", { count: steps.length })); - let submissions: Promise = Promise.resolve(); - const result = await runWorkflowSteps( - steps.map((node) => node.id), - document.edges, - async (id) => { - const submitted = submissions.then(() => - historyRef.current.present.id === document.id - ? prepareLatest.current(id) - : [], - ); - submissions = submitted.catch(() => undefined); - const jobIds = await submitted; - if (!jobIds.length || !(await awaitJobs(document.id, jobIds))) return false; - return awaitDisplayed(document.id, id, jobIds); - }, - ); - if (historyRef.current.present.id !== document.id) return; - notify( - result.failed.length || result.skipped.length - ? t("canvas.workspace.group.workflowIncomplete", { - succeeded: result.succeeded.length, - failed: result.failed.length, - skipped: result.skipped.length, - }) - : t("canvas.workspace.group.workflowDone", { count: steps.length }), - ); + try { + if (!await persist(document)) return; + const client = creationClient(document.id); + const workflow = workflowRequest(document, groupId, await client.refresh(), backendCatalog.models); + if (!workflow) throw new Error(t("errors.backend.noGenerationConfig")); + // The project budget may have changed in another window since this render. + const receipt = await client.command("generation.group", {members: workflow.members}, workflow.versions); + notify(receipt.status === "awaiting_confirmation" ? t("spend.waiting") : + t("canvas.workspace.group.workflowStarted", {count: workflow.members.length})); + } catch (failure) { notify(errorMessage(failure)); } }; const importActionResultFiles = async (files: File[]) => { const binding = resultBinding.current; @@ -841,14 +735,3 @@ export function useWorkspaceGeneration(rt: WorkspaceRuntime) { rt.importActionResultFiles = importActionResultFiles; rt.cancelResultImport = cancelResultImport; } - -/** - * Group members a workflow run generates: nodes with a configured model and a - * prompt (media may instead take their prompt from connected references). - */ -function isWorkflowStep(node: CanvasNode, referenced: boolean): boolean { - const prompt = Boolean(node.data.prompt?.trim() || node.data.promptContent?.length); - if (node.type === "text") return Boolean(node.data.agentSettings?.modelConfigId && prompt); - if (!["image", "video", "audio"].includes(node.type)) return false; - return Boolean(node.data.settings?.modelConfigId && (prompt || referenced)); -} diff --git a/src/canvas/workspace/workflowMembers.ts b/src/canvas/workspace/workflowMembers.ts new file mode 100644 index 000000000..cc54912d5 --- /dev/null +++ b/src/canvas/workspace/workflowMembers.ts @@ -0,0 +1,35 @@ +import { objectVersion } from "../../backend/creationClient.ts"; +import type { ModelConfig } from "../../backend/rules.ts"; +import type { ProjectSnapshot } from "../../contracts/generated.ts"; +import { getNodeGenerationSettings } from "../generationSettings.ts"; +import { workflowDependencies } from "../groupWorkflow.ts"; +import type { CanvasDocument } from "../model.ts"; +import { groupDescendants } from "../operations"; + +export function workflowSteps(document: CanvasDocument, groupId: string) { + return groupDescendants(document.nodes, groupId).filter(node => { + const prompt = Boolean(node.data.prompt?.trim() || node.data.promptContent?.length); + if (node.type === "text") return Boolean(node.data.agentSettings?.modelConfigId && prompt); + if (!["image", "video", "audio"].includes(node.type) || !node.data.settings?.modelConfigId) return false; + return prompt || document.edges.some(edge => edge.target === node.id && edge.intent !== "post_edit_result"); + }); +} + +/** Preview and submission use the same saved specifications, dependencies and candidate counts. */ +export function workflowRequest(document: CanvasDocument, groupId: string, snapshot: ProjectSnapshot, models: readonly ModelConfig[]) { + const steps = workflowSteps(document, groupId); + const dependencies = workflowDependencies(steps.map(node => node.id), document.edges); + const members = []; + const versions = []; + for (const node of steps) { + const item = snapshot.canvasItems.find(i => i.id === node.id); + const specId = item?.binding.role === "generation" ? item.binding.objectRef.id : + item && "draftSpec" in item.binding ? item.binding.draftSpec?.id : undefined; + const spec = snapshot.generationSpecs.find(s => s.id === specId); + if (!item || !spec) return undefined; + const count = node.type === "image" || node.type === "video" ? getNodeGenerationSettings(node, models).count ?? 1 : 1; + members.push({ itemId: item.id, specId: spec.id, count, after: [...dependencies.get(item.id)!] }); + versions.push(objectVersion("canvas_item", item), objectVersion("generation_spec", spec)); + } + return members.length ? { members, versions } : undefined; +} diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 4bf548140..097121a9d 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4,6 +4,65 @@ "projectFormatVersion": 2, "input": { "$defs": { + "AdvanceGroupCommand": { + "additionalProperties": false, + "description": "Continue an accepted workflow with its completed results.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "spend.advanceGroup", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/GroupAdvance", + "description": "Continue an accepted workflow with its completed results." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "payload" + ], + "title": "AdvanceGroupCommand", + "type": "object" + }, "ArtifactPublish": { "additionalProperties": false, "description": "Publish a file from a server-owned execution context without generating media.", @@ -3681,11 +3740,26 @@ "applied", "accepted", "noop", - "rejected" + "rejected", + "awaiting_confirmation" ], "title": "Status", "type": "string" }, + "spendRequestId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Batch awaiting a human spend decision.", + "title": "Spendrequestid" + }, "changed": { "default": [], "description": "Business objects changed by the operation.", @@ -3738,6 +3812,52 @@ "title": "CommandReceipt", "type": "object" }, + "ConnectionPrice": { + "additionalProperties": false, + "properties": { + "unit": { + "description": "What the configured service bills for.", + "enum": [ + "request", + "input_character", + "input_second", + "requested_second", + "output_second" + ], + "title": "Unit", + "type": "string" + }, + "rate": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + } + ], + "description": "Price for one billing unit.", + "title": "Rate" + }, + "currency": { + "description": "Currency of the service price.", + "enum": [ + "USD", + "CNY" + ], + "title": "Currency", + "type": "string" + } + }, + "required": [ + "unit", + "rate", + "currency" + ], + "title": "ConnectionPrice", + "type": "object" + }, "ContainerBinding": { "additionalProperties": false, "properties": { @@ -3783,6 +3903,9 @@ "timeline_font_mime", "timeline_bundled_font_fingerprint", "timeline_bundled_font_unavailable", + "spend_quote_changed", + "spend_cap", + "spend_unknown", "invalid_input", "revision_conflict", "role_restricted", @@ -4073,6 +4196,7 @@ "creation.batch": "#/$defs/BatchCommand", "editor.create": "#/$defs/EditorCreateCommand", "editor.save": "#/$defs/EditorSaveCommand", + "generation.group": "#/$defs/GenerationGroupCommand", "generation.submit": "#/$defs/GenerationSubmitCommand", "generationSpec.create": "#/$defs/SpecCreateCommand", "generationSpec.restore": "#/$defs/SpecRestoreCommand", @@ -4092,6 +4216,11 @@ "reference.restore": "#/$defs/ReferenceRestoreCommand", "reference.update": "#/$defs/ReferenceUpdateCommand", "result.select": "#/$defs/ResultSelectCommand", + "spend.advanceGroup": "#/$defs/AdvanceGroupCommand", + "spend.observe": "#/$defs/SpendObservationCommand", + "spend.policy": "#/$defs/SpendPolicyCommand", + "spend.review": "#/$defs/SpendReviewCommand", + "spend.tool": "#/$defs/ToolSpendCommand", "timeline.publishRender": "#/$defs/TimelinePublishRenderCommand" }, "propertyName": "type" @@ -4187,6 +4316,24 @@ { "$ref": "#/$defs/ReferenceRemoveCommand" }, + { + "$ref": "#/$defs/ToolSpendCommand" + }, + { + "$ref": "#/$defs/SpendObservationCommand" + }, + { + "$ref": "#/$defs/SpendPolicyCommand" + }, + { + "$ref": "#/$defs/SpendReviewCommand" + }, + { + "$ref": "#/$defs/GenerationGroupCommand" + }, + { + "$ref": "#/$defs/AdvanceGroupCommand" + }, { "$ref": "#/$defs/GenerationSubmitCommand" }, @@ -4233,14 +4380,26 @@ "asset.usage": "#/$defs/AssetUsageQuery", "canvas.status": "#/$defs/CanvasStatusQuery", "canvas.versions": "#/$defs/VersionsQuery", + "generation.groupQuote": "#/$defs/GroupQuoteQuery", + "generation.quote": "#/$defs/GenerationQuoteQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", "object.get": "#/$defs/ObjectQuery", - "project.get": "#/$defs/ProjectQuery" + "project.get": "#/$defs/ProjectQuery", + "spend.status": "#/$defs/SpendStatusQuery" }, "propertyName": "type" }, "oneOf": [ + { + "$ref": "#/$defs/SpendStatusQuery" + }, + { + "$ref": "#/$defs/GenerationQuoteQuery" + }, + { + "$ref": "#/$defs/GroupQuoteQuery" + }, { "$ref": "#/$defs/ProjectQuery" }, @@ -5629,6 +5788,144 @@ "title": "GenerationFailure", "type": "object" }, + "GenerationGroup": { + "additionalProperties": false, + "properties": { + "members": { + "description": "Workflow members in canvas order.", + "items": { + "$ref": "#/$defs/GroupMember" + }, + "maxItems": 500, + "minItems": 1, + "title": "Members", + "type": "array" + } + }, + "required": [ + "members" + ], + "title": "GenerationGroup", + "type": "object" + }, + "GenerationGroupCommand": { + "additionalProperties": false, + "description": "Quote and run a complete canvas workflow.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "generation.group", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/GenerationGroup", + "description": "Quote and run a complete canvas workflow." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "payload" + ], + "title": "GenerationGroupCommand", + "type": "object" + }, + "GenerationQuoteQuery": { + "additionalProperties": false, + "properties": { + "queryId": { + "description": "Caller-supplied query ID.", + "format": "uuid", + "title": "Queryid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "generation.quote", + "description": "Estimate the entire action without creating jobs.", + "title": "Type", + "type": "string" + }, + "specId": { + "description": "Generation specification to price.", + "format": "uuid", + "title": "Specid", + "type": "string" + }, + "originItemId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Canvas item that owns the draft.", + "title": "Originitemid" + }, + "count": { + "default": 1, + "description": "Requested candidates.", + "maximum": 8, + "minimum": 1, + "title": "Count", + "type": "integer" + } + }, + "required": [ + "queryId", + "projectId", + "type", + "specId" + ], + "title": "GenerationQuoteQuery", + "type": "object" + }, "GenerationSpecBase": { "additionalProperties": false, "properties": { @@ -5760,6 +6057,14 @@ "GenerationSubmit": { "additionalProperties": false, "properties": { + "count": { + "default": 1, + "description": "Number of candidates admitted together at the whole-action price.", + "maximum": 8, + "minimum": 1, + "title": "Count", + "type": "integer" + }, "specId": { "description": "Include its current generation_spec revision in expectedVersions.", "format": "uuid", @@ -5899,6 +6204,33 @@ "title": "GenerationSubmitCommand", "type": "object" }, + "GroupAdvance": { + "additionalProperties": false, + "properties": { + "workflowId": { + "description": "Original group instruction.", + "format": "uuid", + "title": "Workflowid", + "type": "string" + }, + "items": { + "description": "Newly runnable items.", + "items": { + "format": "uuid", + "type": "string" + }, + "minItems": 1, + "title": "Items", + "type": "array" + } + }, + "required": [ + "workflowId", + "items" + ], + "title": "GroupAdvance", + "type": "object" + }, "GroupCanvasItem": { "additionalProperties": false, "properties": { @@ -6023,6 +6355,82 @@ "title": "GroupCanvasItem", "type": "object" }, + "GroupMember": { + "additionalProperties": false, + "properties": { + "itemId": { + "description": "Canvas item to run.", + "format": "uuid", + "title": "Itemid", + "type": "string" + }, + "specId": { + "description": "Generation specification owned by the item.", + "format": "uuid", + "title": "Specid", + "type": "string" + }, + "count": { + "default": 1, + "description": "Candidates requested for this item.", + "maximum": 8, + "minimum": 1, + "title": "Count", + "type": "integer" + }, + "after": { + "default": [], + "description": "Upstream group items whose adopted results this input needs.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "After", + "type": "array" + } + }, + "required": [ + "itemId", + "specId" + ], + "title": "GroupMember", + "type": "object" + }, + "GroupQuoteQuery": { + "additionalProperties": false, + "properties": { + "queryId": { + "description": "Caller-supplied query ID.", + "format": "uuid", + "title": "Queryid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "generation.groupQuote", + "description": "Estimate runnable workflow members and list the steps waiting for upstream results.", + "title": "Type", + "type": "string" + }, + "workflow": { + "$ref": "#/$defs/GenerationGroup", + "description": "The same workflow members and dependencies used for submission." + } + }, + "required": [ + "queryId", + "projectId", + "type", + "workflow" + ], + "title": "GroupQuoteQuery", + "type": "object" + }, "HistoryRedoCommand": { "additionalProperties": false, "description": "Reapply an undone command.", @@ -8660,7 +9068,6 @@ }, "ModelConfigPublic": { "additionalProperties": false, - "description": "Application-level, never embedded in an editable project's credential data.", "properties": { "kind": { "description": "Business object or media type.", @@ -8778,6 +9185,18 @@ "default": null, "description": "Supported video generation capabilities." }, + "price": { + "anyOf": [ + { + "$ref": "#/$defs/ConnectionPrice" + }, + { + "type": "null" + } + ], + "default": null, + "description": "User-specified price for this exact model connection." + }, "id": { "description": "Stable object ID.", "format": "uuid", @@ -9512,7 +9931,9 @@ "canvas_item", "editor_document", "job", - "result" + "result", + "spend_request", + "spend_call" ], "title": "Objecttype", "type": "string" @@ -9884,119 +10305,104 @@ "title": "Point", "type": "object" }, - "Project": { + "PriceLine": { "additionalProperties": false, "properties": { - "id": { - "description": "Stable object ID.", - "format": "uuid", - "title": "Id", + "operation": { + "description": "Model operation being priced.", + "title": "Operation", "type": "string" }, - "revision": { - "default": 1, - "description": "Current object revision for optimistic concurrency.", - "minimum": 1, - "title": "Revision", - "type": "integer" + "modelConfigId": { + "description": "Selected model connection.", + "format": "uuid", + "title": "Modelconfigid", + "type": "string" }, - "name": { - "description": "User-visible name.", - "maxLength": 100, - "minLength": 1, - "pattern": "\\S", - "title": "Name", + "modelId": { + "description": "Provider model receiving the request.", + "title": "Modelid", "type": "string" }, - "defaultNameIndex": { + "providerUrl": { "anyOf": [ { - "minimum": 1, - "type": "integer" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Index of the automatically named initial project.", - "title": "Defaultnameindex" - } - }, - "required": [ - "id", - "name" - ], - "title": "Project", - "type": "object" - }, - "ProjectCreate": { - "additionalProperties": false, - "properties": { - "name": { - "description": "User-visible name.", - "maxLength": 100, - "minLength": 1, - "pattern": "\\S", - "title": "Name", + "description": "Endpoint for this quoted connection.", + "title": "Providerurl" + }, + "source": { + "description": "Origin of the price.", + "enum": [ + "connection", + "official", + "local", + "unknown" + ], + "title": "Source", "type": "string" }, - "defaultNameIndex": { + "sourceUrl": { "anyOf": [ { - "exclusiveMinimum": 0, - "type": "number" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Index for an automatically named initial project.", - "title": "Defaultnameindex" - } - }, - "required": [ - "name" - ], - "title": "ProjectCreate", - "type": "object" - }, - "ProjectCreateCommand": { - "additionalProperties": false, - "description": "Create a project.", - "properties": { - "commandId": { - "description": "Stable command ID for idempotent replay.", - "format": "uuid", - "title": "Commandid", - "type": "string" + "description": "Published source for an official price.", + "title": "Sourceurl" }, - "projectId": { - "description": "Owning project ID.", - "format": "uuid", - "title": "Projectid", - "type": "string" + "sourceVersion": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Price revision or dated official source.", + "title": "Sourceversion" }, - "type": { - "const": "project.create", - "description": "Command discriminator.", - "title": "Type", - "type": "string" + "price": { + "anyOf": [ + { + "$ref": "#/$defs/ConnectionPrice" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Native unit price, when known." }, - "expectedVersions": { - "default": [], - "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", - "items": { - "$ref": "#/$defs/ObjectVersion" - }, - "title": "Expectedversions", - "type": "array" + "quantityBasis": { + "default": "fixed", + "description": "Whether the quoted quantity is an upper bound.", + "enum": [ + "fixed", + "maximum" + ], + "title": "Quantitybasis", + "type": "string" }, - "expectedPreview": { + "quantity": { "anyOf": [ { - "pattern": "^[0-9a-f]{64}$", + "minimum": 0.0, + "type": "number" + }, + { "type": "string" }, { @@ -10004,159 +10410,95 @@ } ], "default": null, - "description": "Fingerprint of the confirmed impact preview.", - "title": "Expectedpreview" + "description": "Billing units or bounded maximum for one candidate.", + "title": "Quantity" }, - "payload": { - "$ref": "#/$defs/ProjectCreate", - "description": "Create a project." + "amount": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Estimated amount for this step of one candidate.", + "title": "Amount" } }, "required": [ - "commandId", - "projectId", - "type", - "payload" + "operation", + "modelConfigId", + "modelId", + "source" ], - "title": "ProjectCreateCommand", + "title": "PriceLine", "type": "object" }, - "ProjectEntity": { + "Project": { "additionalProperties": false, "properties": { + "spendPolicy": { + "anyOf": [ + { + "$ref": "#/$defs/SpendPolicy" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional service spend controls." + }, "id": { - "description": "Stable identity of this project-owned object.", + "description": "Stable object ID.", "format": "uuid", "title": "Id", "type": "string" }, - "projectId": { - "description": "Owning project ID.", - "format": "uuid", - "title": "Projectid", - "type": "string" - }, "revision": { "default": 1, "description": "Current object revision for optimistic concurrency.", "minimum": 1, "title": "Revision", "type": "integer" - } - }, - "required": [ - "id", - "projectId" - ], - "title": "ProjectEntity", - "type": "object" - }, - "ProjectEvent": { - "additionalProperties": false, - "properties": { - "schemaVersion": { - "const": 1, - "default": 1, - "description": "Record schema version.", - "title": "Schemaversion", - "type": "integer" }, - "projectId": { - "description": "Owning project ID.", - "format": "uuid", - "title": "Projectid", + "name": { + "description": "User-visible name.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Name", "type": "string" }, - "cursor": { - "description": "Monotonically increasing project event cursor.", - "minimum": 1, - "title": "Cursor", - "type": "integer" - }, - "commandId": { + "defaultNameIndex": { "anyOf": [ { - "format": "uuid", - "type": "string" + "minimum": 1, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "Stable command ID for idempotent replay.", - "title": "Commandid" - }, - "source": { - "description": "Input source or recorded provenance.", - "enum": [ - "ui", - "agent", - "background", - "external" - ], - "title": "Source", - "type": "string" - }, - "changed": { - "default": [], - "description": "Business objects changed by the operation.", - "items": { - "$ref": "#/$defs/ChangedObject" - }, - "title": "Changed", - "type": "array" - }, - "jobIds": { - "default": [], - "description": "Generation jobs associated with this operation.", - "items": { - "format": "uuid", - "type": "string" - }, - "title": "Jobids", - "type": "array" - } - }, - "required": [ - "projectId", - "cursor", - "source" - ], - "title": "ProjectEvent", - "type": "object" - }, - "ProjectQuery": { - "additionalProperties": false, - "properties": { - "queryId": { - "description": "Caller-supplied query ID.", - "format": "uuid", - "title": "Queryid", - "type": "string" - }, - "projectId": { - "description": "Owning project ID.", - "format": "uuid", - "title": "Projectid", - "type": "string" - }, - "type": { - "const": "project.get", - "description": "Read the current project.", - "title": "Type", - "type": "string" + "description": "Index of the automatically named initial project.", + "title": "Defaultnameindex" } }, "required": [ - "queryId", - "projectId", - "type" + "id", + "name" ], - "title": "ProjectQuery", + "title": "Project", "type": "object" }, - "ProjectRename": { + "ProjectCreate": { "additionalProperties": false, "properties": { "name": { @@ -10166,17 +10508,31 @@ "pattern": "\\S", "title": "Name", "type": "string" + }, + "defaultNameIndex": { + "anyOf": [ + { + "exclusiveMinimum": 0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Index for an automatically named initial project.", + "title": "Defaultnameindex" } }, "required": [ "name" ], - "title": "ProjectRename", + "title": "ProjectCreate", "type": "object" }, - "ProjectRenameCommand": { + "ProjectCreateCommand": { "additionalProperties": false, - "description": "Rename the project.", + "description": "Create a project.", "properties": { "commandId": { "description": "Stable command ID for idempotent replay.", @@ -10191,7 +10547,219 @@ "type": "string" }, "type": { - "const": "project.rename", + "const": "project.create", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/ProjectCreate", + "description": "Create a project." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "payload" + ], + "title": "ProjectCreateCommand", + "type": "object" + }, + "ProjectEntity": { + "additionalProperties": false, + "properties": { + "id": { + "description": "Stable identity of this project-owned object.", + "format": "uuid", + "title": "Id", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "revision": { + "default": 1, + "description": "Current object revision for optimistic concurrency.", + "minimum": 1, + "title": "Revision", + "type": "integer" + } + }, + "required": [ + "id", + "projectId" + ], + "title": "ProjectEntity", + "type": "object" + }, + "ProjectEvent": { + "additionalProperties": false, + "properties": { + "schemaVersion": { + "const": 1, + "default": 1, + "description": "Record schema version.", + "title": "Schemaversion", + "type": "integer" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "cursor": { + "description": "Monotonically increasing project event cursor.", + "minimum": 1, + "title": "Cursor", + "type": "integer" + }, + "commandId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stable command ID for idempotent replay.", + "title": "Commandid" + }, + "source": { + "description": "Input source or recorded provenance.", + "enum": [ + "ui", + "agent", + "background", + "external" + ], + "title": "Source", + "type": "string" + }, + "changed": { + "default": [], + "description": "Business objects changed by the operation.", + "items": { + "$ref": "#/$defs/ChangedObject" + }, + "title": "Changed", + "type": "array" + }, + "jobIds": { + "default": [], + "description": "Generation jobs associated with this operation.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Jobids", + "type": "array" + } + }, + "required": [ + "projectId", + "cursor", + "source" + ], + "title": "ProjectEvent", + "type": "object" + }, + "ProjectQuery": { + "additionalProperties": false, + "properties": { + "queryId": { + "description": "Caller-supplied query ID.", + "format": "uuid", + "title": "Queryid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "project.get", + "description": "Read the current project.", + "title": "Type", + "type": "string" + } + }, + "required": [ + "queryId", + "projectId", + "type" + ], + "title": "ProjectQuery", + "type": "object" + }, + "ProjectRename": { + "additionalProperties": false, + "properties": { + "name": { + "description": "User-visible name.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Name", + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "ProjectRename", + "type": "object" + }, + "ProjectRenameCommand": { + "additionalProperties": false, + "description": "Rename the project.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "project.rename", "description": "Command discriminator.", "title": "Type", "type": "string" @@ -10508,6 +11076,24 @@ "title": "Eventcursor", "type": "integer" }, + "spendRequests": { + "default": [], + "description": "Recorded decisions on fixed generation batches.", + "items": { + "$ref": "#/$defs/SpendRequest" + }, + "title": "Spendrequests", + "type": "array" + }, + "spendCalls": { + "default": [], + "description": "One reservation and its subsequent evidence per model call.", + "items": { + "$ref": "#/$defs/SpendCall" + }, + "title": "Spendcalls", + "type": "array" + }, "undoClearedThrough": { "default": 0, "description": "Event cursor through which undo history was cleared.", @@ -11885,7 +12471,7 @@ "title": "SpecWrite", "type": "object" }, - "StackCanvasItem": { + "SpendCall": { "additionalProperties": false, "properties": { "id": { @@ -11907,53 +12493,41 @@ "title": "Revision", "type": "integer" }, - "kind": { - "const": "stack", - "description": "Business object or media type.", - "title": "Kind", - "type": "string" - }, - "title": { - "default": "", - "description": "User-visible title.", - "maxLength": 255, - "title": "Title", + "ownerId": { + "description": "Generation job or media tool task that owns this call.", + "format": "uuid", + "title": "Ownerid", "type": "string" }, - "position": { - "$ref": "#/$defs/Point", - "description": "Position in the owning canvas or stage." - }, - "width": { - "default": 352, - "description": "Width in pixels.", - "exclusiveMinimum": 0, - "title": "Width", - "type": "number" - }, - "height": { - "default": 198, - "description": "Height in pixels.", - "exclusiveMinimum": 0, - "title": "Height", - "type": "number" + "line": { + "$ref": "#/$defs/PriceLine", + "description": "Original native-currency estimate for this physical call." }, - "zIndex": { - "default": 0, - "description": "Canvas stacking order.", - "title": "Zindex", - "type": "integer" + "createdAt": { + "description": "Time the reservation was created.", + "format": "date-time", + "title": "Createdat", + "type": "string" }, - "locked": { - "default": false, - "description": "Whether edits to this object are blocked.", - "title": "Locked", - "type": "boolean" + "state": { + "default": "reserved", + "description": "State of the provider call.", + "enum": [ + "reserved", + "submitted", + "completed", + "released" + ], + "title": "State", + "type": "string" }, - "color": { + "usage": { "anyOf": [ { - "pattern": "^(#[0-9a-fA-F]{6})?$", + "minimum": 0.0, + "type": "number" + }, + { "type": "string" }, { @@ -11961,19 +12535,17 @@ } ], "default": null, - "description": "Group background color in #RRGGBB format.", - "title": "Color" - }, - "visible": { - "default": true, - "description": "Whether this object is displayed.", - "title": "Visible", - "type": "boolean" + "description": "Metered units reported for the call.", + "title": "Usage" }, - "parentId": { + "usageSource": { "anyOf": [ { - "format": "uuid", + "enum": [ + "execution", + "provider", + "media" + ], "type": "string" }, { @@ -11981,66 +12553,154 @@ } ], "default": null, - "description": "Parent canvas group ID, or null for the root.", - "title": "Parentid" + "description": "Origin of the quantity used for settlement.", + "title": "Usagesource" }, - "tags": { - "default": [], - "description": "User-defined search tags.", - "items": { - "maxLength": 100, - "minLength": 1, - "pattern": "\\S", - "type": "string" - }, - "title": "Tags", - "type": "array" + "calculated": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Amount calculated from confirmed usage and the agreed rate.", + "title": "Calculated" }, - "binding": { - "$ref": "#/$defs/EditorBinding", - "description": "Business object displayed by this canvas item." + "reported": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Charge explicitly reported by the provider in the line currency.", + "title": "Reported" } }, "required": [ "id", "projectId", - "kind", - "binding" + "ownerId", + "line", + "createdAt" ], - "title": "StackCanvasItem", + "title": "SpendCall", "type": "object" }, - "StackData": { + "SpendObservation": { "additionalProperties": false, "properties": { - "nodeIds": { - "default": [], - "description": "Ordered member canvas item IDs.", - "items": { - "format": "uuid", - "type": "string" - }, - "title": "Nodeids", - "type": "array" + "callId": { + "description": "Stable physical call receiving evidence.", + "format": "uuid", + "title": "Callid", + "type": "string" }, - "activeIndex": { - "default": 0, - "description": "Index of the active member.", - "minimum": 0, - "title": "Activeindex", - "type": "integer" + "state": { + "description": "Observed execution state.", + "enum": [ + "submitted", + "completed", + "released" + ], + "title": "State", + "type": "string" + }, + "unit": { + "anyOf": [ + { + "enum": [ + "request", + "input_character", + "input_second", + "requested_second", + "output_second" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Unit of observed provider usage.", + "title": "Unit" + }, + "usage": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Provider units or measured output length.", + "title": "Usage" + }, + "reported": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Verified provider amount in the quoted currency.", + "title": "Reported" + }, + "evidence": { + "default": "execution", + "description": "Source of the observation.", + "enum": [ + "execution", + "provider", + "media" + ], + "title": "Evidence", + "type": "string" } }, - "title": "StackData", + "required": [ + "callId", + "state" + ], + "title": "SpendObservation", "type": "object" }, - "StackDocument": { + "SpendObservationCommand": { "additionalProperties": false, + "description": "Record evidence from a model operation.", "properties": { - "id": { - "description": "Stable identity of this project-owned object.", + "commandId": { + "description": "Stable command ID for idempotent replay.", "format": "uuid", - "title": "Id", + "title": "Commandid", "type": "string" }, "projectId": { @@ -12049,254 +12709,579 @@ "title": "Projectid", "type": "string" }, - "revision": { - "default": 1, - "description": "Current object revision for optimistic concurrency.", - "minimum": 1, - "title": "Revision", - "type": "integer" - }, - "schemaVersion": { - "const": 1, - "default": 1, - "description": "Record schema version.", - "title": "Schemaversion", - "type": "integer" + "type": { + "const": "spend.observe", + "description": "Command discriminator.", + "title": "Type", + "type": "string" }, - "inputConnections": { + "expectedVersions": { "default": [], - "description": "Persisted connections to source assets.", + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", "items": { - "$ref": "#/$defs/EditorInputConnection" + "$ref": "#/$defs/ObjectVersion" }, - "title": "Inputconnections", + "title": "Expectedversions", "type": "array" }, - "kind": { - "const": "stack", - "description": "Business object or media type.", - "title": "Kind", - "type": "string" + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" }, - "data": { - "$ref": "#/$defs/StackData", - "description": "Typed editable document contents." + "payload": { + "$ref": "#/$defs/SpendObservation", + "description": "Record evidence from a model operation." } }, "required": [ - "id", + "commandId", "projectId", - "kind", - "data" + "type", + "payload" ], - "title": "StackDocument", + "title": "SpendObservationCommand", "type": "object" }, - "StageCamera": { + "SpendPolicy": { "additionalProperties": false, "properties": { - "position": { - "$ref": "#/$defs/Vector3", - "description": "Position in the owning canvas or stage." + "currency": { + "default": "USD", + "description": "Currency of the project spending limits.", + "enum": [ + "USD", + "CNY" + ], + "title": "Currency", + "type": "string" }, - "target": { - "$ref": "#/$defs/Vector3", - "description": "Camera look-at position." + "threshold": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Require confirmation strictly above this batch amount.", + "title": "Threshold" }, - "fov": { - "description": "Camera vertical field of view in degrees.", - "exclusiveMaximum": 180, - "exclusiveMinimum": 0, - "title": "Fov", - "type": "number" + "cap": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Maximum settled and reserved service spend.", + "title": "Cap" } }, - "required": [ - "position", - "target", - "fov" - ], - "title": "StageCamera", + "title": "SpendPolicy", "type": "object" }, - "StageMotion": { + "SpendPolicyCommand": { "additionalProperties": false, + "description": "Set project service spending controls.", "properties": { - "preset": { - "description": "Selected generation or motion preset.", - "enum": [ - "idle", - "walk", - "run", - "wave" - ], - "title": "Preset", + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", "type": "string" }, - "speed": { - "description": "Playback or motion speed multiplier.", - "exclusiveMinimum": 0, - "title": "Speed", - "type": "number" + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" }, - "amount": { - "description": "Magnitude of the procedural motion.", - "maximum": 1, - "minimum": 0, - "title": "Amount", - "type": "number" + "type": { + "const": "spend.policy", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/SpendPolicy", + "description": "Set project service spending controls." } }, "required": [ - "preset", - "speed", - "amount" + "commandId", + "projectId", + "type", + "payload" ], - "title": "StageMotion", + "title": "SpendPolicyCommand", "type": "object" }, - "StageObject": { + "SpendQuote": { "additionalProperties": false, "properties": { - "position": { - "$ref": "#/$defs/Vector3", - "description": "Position in the owning canvas or stage." + "fromUpstream": { + "default": false, + "description": "Inputs are newly resolved upstream results.", + "title": "Fromupstream", + "type": "boolean" }, - "rotation": { - "$ref": "#/$defs/Vector3", - "description": "Rotation in radians around each stage axis." + "candidates": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Total candidates across distinct group members.", + "title": "Candidates" }, - "scale": { - "$ref": "#/$defs/Vector3", - "description": "Positive scale along each stage axis." + "skipped": { + "default": [], + "description": "Workflow items blocked by a failed dependency or reference cycle.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Skipped", + "type": "array" + }, + "deferred": { + "default": [], + "description": "Workflow items awaiting upstream inputs.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Deferred", + "type": "array" + }, + "count": { + "description": "Number of fixed candidates in this action.", + "maximum": 8, + "minimum": 1, + "title": "Count", + "type": "integer" + }, + "inputFingerprint": { + "description": "Identity of the effective model inputs.", + "pattern": "^[0-9a-f]{64}$", + "title": "Inputfingerprint", + "type": "string" }, + "lines": { + "description": "Individual provider calls per candidate, in execution order.", + "items": { + "$ref": "#/$defs/PriceLine" + }, + "title": "Lines", + "type": "array" + } + }, + "required": [ + "count", + "inputFingerprint", + "lines" + ], + "title": "SpendQuote", + "type": "object" + }, + "SpendRequest": { + "additionalProperties": false, + "properties": { "id": { - "description": "Stable object ID.", - "maxLength": 100, - "minLength": 1, - "pattern": "\\S", + "description": "Stable identity of this project-owned object.", + "format": "uuid", "title": "Id", "type": "string" }, - "kind": { - "description": "Business object or media type.", - "enum": [ - "person", - "box", - "sphere" - ], - "title": "Kind", + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", "type": "string" }, - "name": { - "description": "User-visible name.", - "maxLength": 255, - "title": "Name", - "type": "string" + "revision": { + "default": 1, + "description": "Current object revision for optimistic concurrency.", + "minimum": 1, + "title": "Revision", + "type": "integer" }, - "color": { - "description": "Serialized display color.", - "pattern": "^#[0-9a-fA-F]{6}$", - "title": "Color", - "type": "string" + "currency": { + "anyOf": [ + { + "enum": [ + "USD", + "CNY" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Project currency when this quote was requested.", + "title": "Currency" }, - "keyframes": { + "specId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fixed generation specification for a candidate batch.", + "title": "Specid" + }, + "batchId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Canvas batch identity for member validation.", + "title": "Batchid" + }, + "workflowId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Original group action owning this decision.", + "title": "Workflowid" + }, + "groupItems": { "default": [], - "description": "Ordered animation keyframes.", + "description": "Fixed workflow items included in this decision.", "items": { - "$ref": "#/$defs/TransformFrame" + "format": "uuid", + "type": "string" }, - "title": "Keyframes", + "title": "Groupitems", "type": "array" }, - "motionClips": { - "default": [], - "description": "Ordered procedural motion intervals.", + "toolTask": { + "anyOf": [ + { + "additionalProperties": { + "$ref": "#/$defs/JsonValue" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Frozen media tool dispatch, without credentials. The project journal owns its acceptance.", + "title": "Tooltask" + }, + "versions": { + "description": "Input object versions fixed when the request was made.", "items": { - "$ref": "#/$defs/MotionClip" + "$ref": "#/$defs/ObjectVersion" }, - "title": "Motionclips", + "title": "Versions", "type": "array" + }, + "quote": { + "$ref": "#/$defs/SpendQuote", + "description": "Exact batch covered by this request." + }, + "createdAt": { + "description": "Time the project requested a review.", + "format": "date-time", + "title": "Createdat", + "type": "string" + }, + "status": { + "default": "pending", + "description": "Human review status.", + "enum": [ + "pending", + "accepted", + "cancelled" + ], + "title": "Status", + "type": "string" + }, + "agentRunId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Originating assistant turn.", + "title": "Agentrunid" + }, + "agentCallId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Originating assistant tool call.", + "title": "Agentcallid" + }, + "decisionId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Durable command that resolved this request.", + "title": "Decisionid" } }, "required": [ - "position", - "rotation", - "scale", "id", - "kind", - "name", - "color" + "projectId", + "versions", + "quote", + "createdAt" ], - "title": "StageObject", + "title": "SpendRequest", "type": "object" }, - "StageShot": { + "SpendReview": { "additionalProperties": false, "properties": { - "id": { - "description": "Stable object ID.", - "maxLength": 100, - "minLength": 1, - "pattern": "\\S", - "title": "Id", + "requestId": { + "description": "Original batch request.", + "format": "uuid", + "title": "Requestid", "type": "string" }, - "cameraId": { - "description": "Stage camera ID.", - "maxLength": 100, - "minLength": 1, - "pattern": "\\S", - "title": "Cameraid", + "fingerprint": { + "description": "Reviewed input and price fingerprint.", + "pattern": "^[0-9a-f]{64}$", + "title": "Fingerprint", "type": "string" }, - "start": { - "description": "Start time in seconds.", - "minimum": 0, - "title": "Start", - "type": "number" + "decision": { + "description": "Human decision for this exact action.", + "enum": [ + "approve", + "cancel" + ], + "title": "Decision", + "type": "string" }, - "duration": { - "description": "Interval duration in seconds.", - "exclusiveMinimum": 0, - "title": "Duration", - "type": "number" + "acceptUnknown": { + "default": false, + "description": "Explicitly accepts this unpriced action with no project cap.", + "title": "Acceptunknown", + "type": "boolean" + }, + "newCap": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Raise the project cap in the same transaction as admission.", + "title": "Newcap" } }, "required": [ - "id", - "cameraId", - "start", - "duration" + "requestId", + "fingerprint", + "decision" ], - "title": "StageShot", + "title": "SpendReview", "type": "object" }, - "StageTransform": { + "SpendReviewCommand": { "additionalProperties": false, + "description": "Record a human decision on a fixed request.", "properties": { - "position": { - "$ref": "#/$defs/Vector3", - "description": "Position in the owning canvas or stage." + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" }, - "rotation": { - "$ref": "#/$defs/Vector3", - "description": "Rotation in radians around each stage axis." + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" }, - "scale": { - "$ref": "#/$defs/Vector3", - "description": "Positive scale along each stage axis." + "type": { + "const": "spend.review", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/SpendReview", + "description": "Record a human decision on a fixed request." } }, "required": [ - "position", - "rotation", - "scale" + "commandId", + "projectId", + "type", + "payload" ], - "title": "StageTransform", + "title": "SpendReviewCommand", "type": "object" }, - "SubjectCanvasItem": { + "SpendStatusQuery": { + "additionalProperties": false, + "properties": { + "queryId": { + "description": "Caller-supplied query ID.", + "format": "uuid", + "title": "Queryid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "agentRunId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Include the media service calls for this assistant turn.", + "title": "Agentrunid" + }, + "type": { + "const": "spend.status", + "description": "Read policy, totals, coverage and pending human decisions.", + "title": "Type", + "type": "string" + } + }, + "required": [ + "queryId", + "projectId", + "type" + ], + "title": "SpendStatusQuery", + "type": "object" + }, + "StackCanvasItem": { "additionalProperties": false, "properties": { "id": { @@ -12319,7 +13304,7 @@ "type": "integer" }, "kind": { - "const": "subject", + "const": "stack", "description": "Business object or media type.", "title": "Kind", "type": "string" @@ -12418,77 +13403,34 @@ "kind", "binding" ], - "title": "SubjectCanvasItem", + "title": "StackCanvasItem", "type": "object" }, - "SubjectData": { + "StackData": { "additionalProperties": false, "properties": { - "description": { - "default": "", - "description": "User-facing annotation only; not subject media or a generation reference", - "maxLength": 20000, - "title": "Description", - "type": "string" - }, - "category": { - "default": "", - "description": "Subject category.", - "maxLength": 100, - "title": "Category", - "type": "string" - }, - "main": { - "anyOf": [ - { - "$ref": "#/$defs/AssetRef" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Primary subject media." - }, - "auxiliaries": { + "nodeIds": { "default": [], - "description": "Ordered auxiliary subject media.", + "description": "Ordered member canvas item IDs.", "items": { - "$ref": "#/$defs/AssetRef" + "format": "uuid", + "type": "string" }, - "maxItems": 3, - "title": "Auxiliaries", + "title": "Nodeids", "type": "array" }, - "voice": { - "anyOf": [ - { - "$ref": "#/$defs/AssetRef" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Subject voice asset version." - }, - "librarySource": { - "anyOf": [ - { - "$ref": "#/$defs/SubjectLibrarySource" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Immutable source library version." + "activeIndex": { + "default": 0, + "description": "Index of the active member.", + "minimum": 0, + "title": "Activeindex", + "type": "integer" } }, - "title": "SubjectData", + "title": "StackData", "type": "object" }, - "SubjectDocument": { + "StackDocument": { "additionalProperties": false, "properties": { "id": { @@ -12527,13 +13469,13 @@ "type": "array" }, "kind": { - "const": "subject", + "const": "stack", "description": "Business object or media type.", "title": "Kind", "type": "string" }, "data": { - "$ref": "#/$defs/SubjectData", + "$ref": "#/$defs/StackData", "description": "Typed editable document contents." } }, @@ -12543,17 +13485,471 @@ "kind", "data" ], - "title": "SubjectDocument", + "title": "StackDocument", "type": "object" }, - "SubjectLibrarySource": { + "StageCamera": { "additionalProperties": false, - "description": "Frozen import provenance; subsequent editing never follows the library.", "properties": { - "itemId": { - "description": "Canvas item ID.", - "format": "uuid", - "title": "Itemid", + "position": { + "$ref": "#/$defs/Vector3", + "description": "Position in the owning canvas or stage." + }, + "target": { + "$ref": "#/$defs/Vector3", + "description": "Camera look-at position." + }, + "fov": { + "description": "Camera vertical field of view in degrees.", + "exclusiveMaximum": 180, + "exclusiveMinimum": 0, + "title": "Fov", + "type": "number" + } + }, + "required": [ + "position", + "target", + "fov" + ], + "title": "StageCamera", + "type": "object" + }, + "StageMotion": { + "additionalProperties": false, + "properties": { + "preset": { + "description": "Selected generation or motion preset.", + "enum": [ + "idle", + "walk", + "run", + "wave" + ], + "title": "Preset", + "type": "string" + }, + "speed": { + "description": "Playback or motion speed multiplier.", + "exclusiveMinimum": 0, + "title": "Speed", + "type": "number" + }, + "amount": { + "description": "Magnitude of the procedural motion.", + "maximum": 1, + "minimum": 0, + "title": "Amount", + "type": "number" + } + }, + "required": [ + "preset", + "speed", + "amount" + ], + "title": "StageMotion", + "type": "object" + }, + "StageObject": { + "additionalProperties": false, + "properties": { + "position": { + "$ref": "#/$defs/Vector3", + "description": "Position in the owning canvas or stage." + }, + "rotation": { + "$ref": "#/$defs/Vector3", + "description": "Rotation in radians around each stage axis." + }, + "scale": { + "$ref": "#/$defs/Vector3", + "description": "Positive scale along each stage axis." + }, + "id": { + "description": "Stable object ID.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Id", + "type": "string" + }, + "kind": { + "description": "Business object or media type.", + "enum": [ + "person", + "box", + "sphere" + ], + "title": "Kind", + "type": "string" + }, + "name": { + "description": "User-visible name.", + "maxLength": 255, + "title": "Name", + "type": "string" + }, + "color": { + "description": "Serialized display color.", + "pattern": "^#[0-9a-fA-F]{6}$", + "title": "Color", + "type": "string" + }, + "keyframes": { + "default": [], + "description": "Ordered animation keyframes.", + "items": { + "$ref": "#/$defs/TransformFrame" + }, + "title": "Keyframes", + "type": "array" + }, + "motionClips": { + "default": [], + "description": "Ordered procedural motion intervals.", + "items": { + "$ref": "#/$defs/MotionClip" + }, + "title": "Motionclips", + "type": "array" + } + }, + "required": [ + "position", + "rotation", + "scale", + "id", + "kind", + "name", + "color" + ], + "title": "StageObject", + "type": "object" + }, + "StageShot": { + "additionalProperties": false, + "properties": { + "id": { + "description": "Stable object ID.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Id", + "type": "string" + }, + "cameraId": { + "description": "Stage camera ID.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Cameraid", + "type": "string" + }, + "start": { + "description": "Start time in seconds.", + "minimum": 0, + "title": "Start", + "type": "number" + }, + "duration": { + "description": "Interval duration in seconds.", + "exclusiveMinimum": 0, + "title": "Duration", + "type": "number" + } + }, + "required": [ + "id", + "cameraId", + "start", + "duration" + ], + "title": "StageShot", + "type": "object" + }, + "StageTransform": { + "additionalProperties": false, + "properties": { + "position": { + "$ref": "#/$defs/Vector3", + "description": "Position in the owning canvas or stage." + }, + "rotation": { + "$ref": "#/$defs/Vector3", + "description": "Rotation in radians around each stage axis." + }, + "scale": { + "$ref": "#/$defs/Vector3", + "description": "Positive scale along each stage axis." + } + }, + "required": [ + "position", + "rotation", + "scale" + ], + "title": "StageTransform", + "type": "object" + }, + "SubjectCanvasItem": { + "additionalProperties": false, + "properties": { + "id": { + "description": "Stable identity of this project-owned object.", + "format": "uuid", + "title": "Id", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "revision": { + "default": 1, + "description": "Current object revision for optimistic concurrency.", + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "kind": { + "const": "subject", + "description": "Business object or media type.", + "title": "Kind", + "type": "string" + }, + "title": { + "default": "", + "description": "User-visible title.", + "maxLength": 255, + "title": "Title", + "type": "string" + }, + "position": { + "$ref": "#/$defs/Point", + "description": "Position in the owning canvas or stage." + }, + "width": { + "default": 352, + "description": "Width in pixels.", + "exclusiveMinimum": 0, + "title": "Width", + "type": "number" + }, + "height": { + "default": 198, + "description": "Height in pixels.", + "exclusiveMinimum": 0, + "title": "Height", + "type": "number" + }, + "zIndex": { + "default": 0, + "description": "Canvas stacking order.", + "title": "Zindex", + "type": "integer" + }, + "locked": { + "default": false, + "description": "Whether edits to this object are blocked.", + "title": "Locked", + "type": "boolean" + }, + "color": { + "anyOf": [ + { + "pattern": "^(#[0-9a-fA-F]{6})?$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Group background color in #RRGGBB format.", + "title": "Color" + }, + "visible": { + "default": true, + "description": "Whether this object is displayed.", + "title": "Visible", + "type": "boolean" + }, + "parentId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Parent canvas group ID, or null for the root.", + "title": "Parentid" + }, + "tags": { + "default": [], + "description": "User-defined search tags.", + "items": { + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "type": "string" + }, + "title": "Tags", + "type": "array" + }, + "binding": { + "$ref": "#/$defs/EditorBinding", + "description": "Business object displayed by this canvas item." + } + }, + "required": [ + "id", + "projectId", + "kind", + "binding" + ], + "title": "SubjectCanvasItem", + "type": "object" + }, + "SubjectData": { + "additionalProperties": false, + "properties": { + "description": { + "default": "", + "description": "User-facing annotation only; not subject media or a generation reference", + "maxLength": 20000, + "title": "Description", + "type": "string" + }, + "category": { + "default": "", + "description": "Subject category.", + "maxLength": 100, + "title": "Category", + "type": "string" + }, + "main": { + "anyOf": [ + { + "$ref": "#/$defs/AssetRef" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Primary subject media." + }, + "auxiliaries": { + "default": [], + "description": "Ordered auxiliary subject media.", + "items": { + "$ref": "#/$defs/AssetRef" + }, + "maxItems": 3, + "title": "Auxiliaries", + "type": "array" + }, + "voice": { + "anyOf": [ + { + "$ref": "#/$defs/AssetRef" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Subject voice asset version." + }, + "librarySource": { + "anyOf": [ + { + "$ref": "#/$defs/SubjectLibrarySource" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Immutable source library version." + } + }, + "title": "SubjectData", + "type": "object" + }, + "SubjectDocument": { + "additionalProperties": false, + "properties": { + "id": { + "description": "Stable identity of this project-owned object.", + "format": "uuid", + "title": "Id", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "revision": { + "default": 1, + "description": "Current object revision for optimistic concurrency.", + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "schemaVersion": { + "const": 1, + "default": 1, + "description": "Record schema version.", + "title": "Schemaversion", + "type": "integer" + }, + "inputConnections": { + "default": [], + "description": "Persisted connections to source assets.", + "items": { + "$ref": "#/$defs/EditorInputConnection" + }, + "title": "Inputconnections", + "type": "array" + }, + "kind": { + "const": "subject", + "description": "Business object or media type.", + "title": "Kind", + "type": "string" + }, + "data": { + "$ref": "#/$defs/SubjectData", + "description": "Typed editable document contents." + } + }, + "required": [ + "id", + "projectId", + "kind", + "data" + ], + "title": "SubjectDocument", + "type": "object" + }, + "SubjectLibrarySource": { + "additionalProperties": false, + "description": "Frozen import provenance; subsequent editing never follows the library.", + "properties": { + "itemId": { + "description": "Canvas item ID.", + "format": "uuid", + "title": "Itemid", "type": "string" }, "revision": { @@ -14409,6 +15805,83 @@ "title": "ToolSelection", "type": "object" }, + "ToolSpendCommand": { + "additionalProperties": false, + "description": "Admit a frozen media tool recipe with its service costs.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "spend.tool", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/ToolSpendInput", + "description": "Admit a frozen media tool recipe with its service costs." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "payload" + ], + "title": "ToolSpendCommand", + "type": "object" + }, + "ToolSpendInput": { + "additionalProperties": false, + "properties": { + "request": { + "additionalProperties": { + "$ref": "#/$defs/JsonValue" + }, + "description": "Validated media tool submission, including its stable task ID.", + "title": "Request", + "type": "object" + } + }, + "required": [ + "request" + ], + "title": "ToolSpendInput", + "type": "object" + }, "TransformFrame": { "additionalProperties": false, "properties": { @@ -15668,6 +17141,7 @@ "creation.batch": "#/$defs/BatchCommand", "editor.create": "#/$defs/EditorCreateCommand", "editor.save": "#/$defs/EditorSaveCommand", + "generation.group": "#/$defs/GenerationGroupCommand", "generation.submit": "#/$defs/GenerationSubmitCommand", "generationSpec.create": "#/$defs/SpecCreateCommand", "generationSpec.restore": "#/$defs/SpecRestoreCommand", @@ -15687,6 +17161,11 @@ "reference.restore": "#/$defs/ReferenceRestoreCommand", "reference.update": "#/$defs/ReferenceUpdateCommand", "result.select": "#/$defs/ResultSelectCommand", + "spend.advanceGroup": "#/$defs/AdvanceGroupCommand", + "spend.observe": "#/$defs/SpendObservationCommand", + "spend.policy": "#/$defs/SpendPolicyCommand", + "spend.review": "#/$defs/SpendReviewCommand", + "spend.tool": "#/$defs/ToolSpendCommand", "timeline.publishRender": "#/$defs/TimelinePublishRenderCommand" }, "propertyName": "type" @@ -15782,6 +17261,24 @@ { "$ref": "#/$defs/ReferenceRemoveCommand" }, + { + "$ref": "#/$defs/ToolSpendCommand" + }, + { + "$ref": "#/$defs/SpendObservationCommand" + }, + { + "$ref": "#/$defs/SpendPolicyCommand" + }, + { + "$ref": "#/$defs/SpendReviewCommand" + }, + { + "$ref": "#/$defs/GenerationGroupCommand" + }, + { + "$ref": "#/$defs/AdvanceGroupCommand" + }, { "$ref": "#/$defs/GenerationSubmitCommand" }, @@ -15828,14 +17325,26 @@ "asset.usage": "#/$defs/AssetUsageQuery", "canvas.status": "#/$defs/CanvasStatusQuery", "canvas.versions": "#/$defs/VersionsQuery", + "generation.groupQuote": "#/$defs/GroupQuoteQuery", + "generation.quote": "#/$defs/GenerationQuoteQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", "object.get": "#/$defs/ObjectQuery", - "project.get": "#/$defs/ProjectQuery" + "project.get": "#/$defs/ProjectQuery", + "spend.status": "#/$defs/SpendStatusQuery" }, "propertyName": "type" }, "oneOf": [ + { + "$ref": "#/$defs/SpendStatusQuery" + }, + { + "$ref": "#/$defs/GenerationQuoteQuery" + }, + { + "$ref": "#/$defs/GroupQuoteQuery" + }, { "$ref": "#/$defs/ProjectQuery" }, @@ -15984,73 +17493,9 @@ }, "output": { "$defs": { - "ArtifactPublish": { - "additionalProperties": false, - "description": "Publish a file from a server-owned execution context without generating media.", - "examples": [ - { - "name": "片段 01", - "path": "clips/segment-01.mp4" - } - ], - "properties": { - "path": { - "description": "Artifact path relative to the server-owned execution directory.", - "maxLength": 4096, - "minLength": 1, - "title": "Path", - "type": "string" - }, - "name": { - "description": "User-visible name.", - "maxLength": 255, - "minLength": 1, - "title": "Name", - "type": "string" - }, - "expectedKind": { - "anyOf": [ - { - "enum": [ - "text", - "image", - "video", - "audio", - "file" - ], - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Required media kind, when specified.", - "title": "Expectedkind" - }, - "sources": { - "default": [], - "description": "Ordered source asset versions.", - "items": { - "$ref": "#/$defs/AssetRef" - }, - "maxItems": 100, - "title": "Sources", - "type": "array" - } - }, - "required": [ - "path", - "name", - "expectedKind", - "sources" - ], - "title": "ArtifactPublish", - "type": "object" - }, - "ArtifactPublishCommand": { + "AdvanceGroupCommand": { "additionalProperties": false, - "description": "Register an execution file as a project asset.", + "description": "Continue an accepted workflow with its completed results.", "properties": { "commandId": { "description": "Stable command ID for idempotent replay.", @@ -16065,7 +17510,7 @@ "type": "string" }, "type": { - "const": "artifact.publish", + "const": "spend.advanceGroup", "description": "Command discriminator.", "title": "Type", "type": "string" @@ -16094,8 +17539,8 @@ "title": "Expectedpreview" }, "payload": { - "$ref": "#/$defs/ArtifactPublish", - "description": "Register an execution file as a project asset." + "$ref": "#/$defs/GroupAdvance", + "description": "Continue an accepted workflow with its completed results." } }, "required": [ @@ -16106,41 +17551,24 @@ "expectedPreview", "payload" ], - "title": "ArtifactPublishCommand", + "title": "AdvanceGroupCommand", "type": "object" }, - "Asset": { + "ArtifactPublish": { "additionalProperties": false, + "description": "Publish a file from a server-owned execution context without generating media.", + "examples": [ + { + "name": "片段 01", + "path": "clips/segment-01.mp4" + } + ], "properties": { - "id": { - "description": "Stable identity of this project-owned object.", - "format": "uuid", - "title": "Id", - "type": "string" - }, - "projectId": { - "description": "Owning project ID.", - "format": "uuid", - "title": "Projectid", - "type": "string" - }, - "revision": { - "default": 1, - "description": "Current object revision for optimistic concurrency.", - "minimum": 1, - "title": "Revision", - "type": "integer" - }, - "kind": { - "description": "Business object or media type.", - "enum": [ - "text", - "image", - "video", - "audio", - "file" - ], - "title": "Kind", + "path": { + "description": "Artifact path relative to the server-owned execution directory.", + "maxLength": 4096, + "minLength": 1, + "title": "Path", "type": "string" }, "name": { @@ -16150,71 +17578,49 @@ "title": "Name", "type": "string" }, - "fingerprint": { - "description": "Immutable content fingerprint.", - "pattern": "^sha256:[0-9a-f]{64}$", - "title": "Fingerprint", - "type": "string" - }, - "path": { - "description": "Immutable asset path relative to the project directory.", - "title": "Path", - "type": "string" - }, - "metadata": { - "$ref": "#/$defs/MediaMetadata", - "description": "Verified media properties." + "expectedKind": { + "anyOf": [ + { + "enum": [ + "text", + "image", + "video", + "audio", + "file" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Required media kind, when specified.", + "title": "Expectedkind" }, - "provenance": { - "$ref": "#/$defs/AssetProvenance", - "description": "Recorded origin and execution context." - } - }, - "required": [ - "id", - "projectId", - "revision", - "kind", - "name", - "fingerprint", - "path", - "metadata", - "provenance" - ], - "title": "Asset", - "type": "object" - }, - "AssetDelete": { - "additionalProperties": false, - "properties": { - "assetIds": { - "description": "Target asset IDs.", + "sources": { + "default": [], + "description": "Ordered source asset versions.", "items": { - "format": "uuid", - "type": "string" + "$ref": "#/$defs/AssetRef" }, "maxItems": 100, - "minItems": 1, - "title": "Assetids", + "title": "Sources", "type": "array" - }, - "clearHistory": { - "default": false, - "description": "Whether the confirmed deletion also clears dependent history.", - "title": "Clearhistory", - "type": "boolean" } }, "required": [ - "assetIds", - "clearHistory" + "path", + "name", + "expectedKind", + "sources" ], - "title": "AssetDelete", + "title": "ArtifactPublish", "type": "object" }, - "AssetDeleteCommand": { + "ArtifactPublishCommand": { "additionalProperties": false, - "description": "Delete assets after an impact preview.", + "description": "Register an execution file as a project asset.", "properties": { "commandId": { "description": "Stable command ID for idempotent replay.", @@ -16229,7 +17635,171 @@ "type": "string" }, "type": { - "const": "asset.delete", + "const": "artifact.publish", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/ArtifactPublish", + "description": "Register an execution file as a project asset." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" + ], + "title": "ArtifactPublishCommand", + "type": "object" + }, + "Asset": { + "additionalProperties": false, + "properties": { + "id": { + "description": "Stable identity of this project-owned object.", + "format": "uuid", + "title": "Id", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "revision": { + "default": 1, + "description": "Current object revision for optimistic concurrency.", + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "kind": { + "description": "Business object or media type.", + "enum": [ + "text", + "image", + "video", + "audio", + "file" + ], + "title": "Kind", + "type": "string" + }, + "name": { + "description": "User-visible name.", + "maxLength": 255, + "minLength": 1, + "title": "Name", + "type": "string" + }, + "fingerprint": { + "description": "Immutable content fingerprint.", + "pattern": "^sha256:[0-9a-f]{64}$", + "title": "Fingerprint", + "type": "string" + }, + "path": { + "description": "Immutable asset path relative to the project directory.", + "title": "Path", + "type": "string" + }, + "metadata": { + "$ref": "#/$defs/MediaMetadata", + "description": "Verified media properties." + }, + "provenance": { + "$ref": "#/$defs/AssetProvenance", + "description": "Recorded origin and execution context." + } + }, + "required": [ + "id", + "projectId", + "revision", + "kind", + "name", + "fingerprint", + "path", + "metadata", + "provenance" + ], + "title": "Asset", + "type": "object" + }, + "AssetDelete": { + "additionalProperties": false, + "properties": { + "assetIds": { + "description": "Target asset IDs.", + "items": { + "format": "uuid", + "type": "string" + }, + "maxItems": 100, + "minItems": 1, + "title": "Assetids", + "type": "array" + }, + "clearHistory": { + "default": false, + "description": "Whether the confirmed deletion also clears dependent history.", + "title": "Clearhistory", + "type": "boolean" + } + }, + "required": [ + "assetIds", + "clearHistory" + ], + "title": "AssetDelete", + "type": "object" + }, + "AssetDeleteCommand": { + "additionalProperties": false, + "description": "Delete assets after an impact preview.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "asset.delete", "description": "Command discriminator.", "title": "Type", "type": "string" @@ -19776,11 +21346,26 @@ "applied", "accepted", "noop", - "rejected" + "rejected", + "awaiting_confirmation" ], "title": "Status", "type": "string" }, + "spendRequestId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Batch awaiting a human spend decision.", + "title": "Spendrequestid" + }, "changed": { "default": [], "description": "Business objects changed by the operation.", @@ -19837,6 +21422,44 @@ "title": "CommandReceipt", "type": "object" }, + "ConnectionPrice": { + "additionalProperties": false, + "properties": { + "unit": { + "description": "What the configured service bills for.", + "enum": [ + "request", + "input_character", + "input_second", + "requested_second", + "output_second" + ], + "title": "Unit", + "type": "string" + }, + "rate": { + "description": "Price for one billing unit.", + "title": "Rate", + "type": "string" + }, + "currency": { + "description": "Currency of the service price.", + "enum": [ + "USD", + "CNY" + ], + "title": "Currency", + "type": "string" + } + }, + "required": [ + "unit", + "rate", + "currency" + ], + "title": "ConnectionPrice", + "type": "object" + }, "ContainerBinding": { "additionalProperties": false, "properties": { @@ -19882,6 +21505,9 @@ "timeline_font_mime", "timeline_bundled_font_fingerprint", "timeline_bundled_font_unavailable", + "spend_quote_changed", + "spend_cap", + "spend_unknown", "invalid_input", "revision_conflict", "role_restricted", @@ -20174,6 +21800,7 @@ "creation.batch": "#/$defs/BatchCommand", "editor.create": "#/$defs/EditorCreateCommand", "editor.save": "#/$defs/EditorSaveCommand", + "generation.group": "#/$defs/GenerationGroupCommand", "generation.submit": "#/$defs/GenerationSubmitCommand", "generationSpec.create": "#/$defs/SpecCreateCommand", "generationSpec.restore": "#/$defs/SpecRestoreCommand", @@ -20193,6 +21820,11 @@ "reference.restore": "#/$defs/ReferenceRestoreCommand", "reference.update": "#/$defs/ReferenceUpdateCommand", "result.select": "#/$defs/ResultSelectCommand", + "spend.advanceGroup": "#/$defs/AdvanceGroupCommand", + "spend.observe": "#/$defs/SpendObservationCommand", + "spend.policy": "#/$defs/SpendPolicyCommand", + "spend.review": "#/$defs/SpendReviewCommand", + "spend.tool": "#/$defs/ToolSpendCommand", "timeline.publishRender": "#/$defs/TimelinePublishRenderCommand" }, "propertyName": "type" @@ -20288,6 +21920,24 @@ { "$ref": "#/$defs/ReferenceRemoveCommand" }, + { + "$ref": "#/$defs/ToolSpendCommand" + }, + { + "$ref": "#/$defs/SpendObservationCommand" + }, + { + "$ref": "#/$defs/SpendPolicyCommand" + }, + { + "$ref": "#/$defs/SpendReviewCommand" + }, + { + "$ref": "#/$defs/GenerationGroupCommand" + }, + { + "$ref": "#/$defs/AdvanceGroupCommand" + }, { "$ref": "#/$defs/GenerationSubmitCommand" }, @@ -20334,14 +21984,26 @@ "asset.usage": "#/$defs/AssetUsageQuery", "canvas.status": "#/$defs/CanvasStatusQuery", "canvas.versions": "#/$defs/VersionsQuery", + "generation.groupQuote": "#/$defs/GroupQuoteQuery", + "generation.quote": "#/$defs/GenerationQuoteQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", "object.get": "#/$defs/ObjectQuery", - "project.get": "#/$defs/ProjectQuery" + "project.get": "#/$defs/ProjectQuery", + "spend.status": "#/$defs/SpendStatusQuery" }, "propertyName": "type" }, "oneOf": [ + { + "$ref": "#/$defs/SpendStatusQuery" + }, + { + "$ref": "#/$defs/GenerationQuoteQuery" + }, + { + "$ref": "#/$defs/GroupQuoteQuery" + }, { "$ref": "#/$defs/ProjectQuery" }, @@ -21786,6 +23448,148 @@ "title": "GenerationFailure", "type": "object" }, + "GenerationGroup": { + "additionalProperties": false, + "properties": { + "members": { + "description": "Workflow members in canvas order.", + "items": { + "$ref": "#/$defs/GroupMember" + }, + "maxItems": 500, + "minItems": 1, + "title": "Members", + "type": "array" + } + }, + "required": [ + "members" + ], + "title": "GenerationGroup", + "type": "object" + }, + "GenerationGroupCommand": { + "additionalProperties": false, + "description": "Quote and run a complete canvas workflow.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "generation.group", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/GenerationGroup", + "description": "Quote and run a complete canvas workflow." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" + ], + "title": "GenerationGroupCommand", + "type": "object" + }, + "GenerationQuoteQuery": { + "additionalProperties": false, + "properties": { + "queryId": { + "description": "Caller-supplied query ID.", + "format": "uuid", + "title": "Queryid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "generation.quote", + "description": "Estimate the entire action without creating jobs.", + "title": "Type", + "type": "string" + }, + "specId": { + "description": "Generation specification to price.", + "format": "uuid", + "title": "Specid", + "type": "string" + }, + "originItemId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Canvas item that owns the draft.", + "title": "Originitemid" + }, + "count": { + "default": 1, + "description": "Requested candidates.", + "maximum": 8, + "minimum": 1, + "title": "Count", + "type": "integer" + } + }, + "required": [ + "queryId", + "projectId", + "type", + "specId", + "originItemId", + "count" + ], + "title": "GenerationQuoteQuery", + "type": "object" + }, "GenerationSpecBase": { "additionalProperties": false, "properties": { @@ -21924,6 +23728,14 @@ "GenerationSubmit": { "additionalProperties": false, "properties": { + "count": { + "default": 1, + "description": "Number of candidates admitted together at the whole-action price.", + "maximum": 8, + "minimum": 1, + "title": "Count", + "type": "integer" + }, "specId": { "description": "Include its current generation_spec revision in expectedVersions.", "format": "uuid", @@ -22070,6 +23882,33 @@ "title": "GenerationSubmitCommand", "type": "object" }, + "GroupAdvance": { + "additionalProperties": false, + "properties": { + "workflowId": { + "description": "Original group instruction.", + "format": "uuid", + "title": "Workflowid", + "type": "string" + }, + "items": { + "description": "Newly runnable items.", + "items": { + "format": "uuid", + "type": "string" + }, + "minItems": 1, + "title": "Items", + "type": "array" + } + }, + "required": [ + "workflowId", + "items" + ], + "title": "GroupAdvance", + "type": "object" + }, "GroupCanvasItem": { "additionalProperties": false, "properties": { @@ -22205,6 +24044,84 @@ "title": "GroupCanvasItem", "type": "object" }, + "GroupMember": { + "additionalProperties": false, + "properties": { + "itemId": { + "description": "Canvas item to run.", + "format": "uuid", + "title": "Itemid", + "type": "string" + }, + "specId": { + "description": "Generation specification owned by the item.", + "format": "uuid", + "title": "Specid", + "type": "string" + }, + "count": { + "default": 1, + "description": "Candidates requested for this item.", + "maximum": 8, + "minimum": 1, + "title": "Count", + "type": "integer" + }, + "after": { + "default": [], + "description": "Upstream group items whose adopted results this input needs.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "After", + "type": "array" + } + }, + "required": [ + "itemId", + "specId", + "count", + "after" + ], + "title": "GroupMember", + "type": "object" + }, + "GroupQuoteQuery": { + "additionalProperties": false, + "properties": { + "queryId": { + "description": "Caller-supplied query ID.", + "format": "uuid", + "title": "Queryid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "generation.groupQuote", + "description": "Estimate runnable workflow members and list the steps waiting for upstream results.", + "title": "Type", + "type": "string" + }, + "workflow": { + "$ref": "#/$defs/GenerationGroup", + "description": "The same workflow members and dependencies used for submission." + } + }, + "required": [ + "queryId", + "projectId", + "type", + "workflow" + ], + "title": "GroupQuoteQuery", + "type": "object" + }, "HistoryRedoCommand": { "additionalProperties": false, "description": "Reapply an undone command.", @@ -24966,7 +26883,6 @@ }, "ModelConfigPublic": { "additionalProperties": false, - "description": "Application-level, never embedded in an editable project's credential data.", "properties": { "kind": { "description": "Business object or media type.", @@ -25084,6 +27000,18 @@ "default": null, "description": "Supported video generation capabilities." }, + "price": { + "anyOf": [ + { + "$ref": "#/$defs/ConnectionPrice" + }, + { + "type": "null" + } + ], + "default": null, + "description": "User-specified price for this exact model connection." + }, "id": { "description": "Stable object ID.", "format": "uuid", @@ -25823,7 +27751,9 @@ "canvas_item", "editor_document", "job", - "result" + "result", + "spend_request", + "spend_call" ], "title": "Objecttype", "type": "string" @@ -26210,120 +28140,100 @@ "title": "Point", "type": "object" }, - "Project": { + "PriceLine": { "additionalProperties": false, "properties": { - "id": { - "description": "Stable object ID.", - "format": "uuid", - "title": "Id", + "operation": { + "description": "Model operation being priced.", + "title": "Operation", "type": "string" }, - "revision": { - "default": 1, - "description": "Current object revision for optimistic concurrency.", - "minimum": 1, - "title": "Revision", - "type": "integer" + "modelConfigId": { + "description": "Selected model connection.", + "format": "uuid", + "title": "Modelconfigid", + "type": "string" }, - "name": { - "description": "User-visible name.", - "maxLength": 100, - "minLength": 1, - "pattern": "\\S", - "title": "Name", + "modelId": { + "description": "Provider model receiving the request.", + "title": "Modelid", "type": "string" }, - "defaultNameIndex": { + "providerUrl": { "anyOf": [ { - "minimum": 1, - "type": "integer" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Index of the automatically named initial project.", - "title": "Defaultnameindex" - } - }, - "required": [ - "id", - "revision", - "name" - ], - "title": "Project", - "type": "object" - }, - "ProjectCreate": { - "additionalProperties": false, - "properties": { - "name": { - "description": "User-visible name.", - "maxLength": 100, - "minLength": 1, - "pattern": "\\S", - "title": "Name", + "description": "Endpoint for this quoted connection.", + "title": "Providerurl" + }, + "source": { + "description": "Origin of the price.", + "enum": [ + "connection", + "official", + "local", + "unknown" + ], + "title": "Source", "type": "string" }, - "defaultNameIndex": { + "sourceUrl": { "anyOf": [ { - "exclusiveMinimum": 0, - "type": "number" + "type": "string" }, { "type": "null" } ], "default": null, - "description": "Index for an automatically named initial project.", - "title": "Defaultnameindex" - } - }, - "required": [ - "name" - ], - "title": "ProjectCreate", - "type": "object" - }, - "ProjectCreateCommand": { - "additionalProperties": false, - "description": "Create a project.", - "properties": { - "commandId": { - "description": "Stable command ID for idempotent replay.", - "format": "uuid", - "title": "Commandid", - "type": "string" + "description": "Published source for an official price.", + "title": "Sourceurl" }, - "projectId": { - "description": "Owning project ID.", - "format": "uuid", - "title": "Projectid", - "type": "string" + "sourceVersion": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Price revision or dated official source.", + "title": "Sourceversion" }, - "type": { - "const": "project.create", - "description": "Command discriminator.", - "title": "Type", - "type": "string" + "price": { + "anyOf": [ + { + "$ref": "#/$defs/ConnectionPrice" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Native unit price, when known." }, - "expectedVersions": { - "default": [], - "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", - "items": { - "$ref": "#/$defs/ObjectVersion" - }, - "title": "Expectedversions", - "type": "array" + "quantityBasis": { + "default": "fixed", + "description": "Whether the quoted quantity is an upper bound.", + "enum": [ + "fixed", + "maximum" + ], + "title": "Quantitybasis", + "type": "string" }, - "expectedPreview": { + "quantity": { "anyOf": [ { - "pattern": "^[0-9a-f]{64}$", "type": "string" }, { @@ -26331,166 +28241,96 @@ } ], "default": null, - "description": "Fingerprint of the confirmed impact preview.", - "title": "Expectedpreview" + "description": "Billing units or bounded maximum for one candidate.", + "title": "Quantity" }, - "payload": { - "$ref": "#/$defs/ProjectCreate", - "description": "Create a project." + "amount": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Estimated amount for this step of one candidate.", + "title": "Amount" } }, "required": [ - "commandId", - "projectId", - "type", - "expectedVersions", - "expectedPreview", - "payload" + "operation", + "modelConfigId", + "modelId", + "source", + "sourceVersion", + "price", + "quantity", + "amount" ], - "title": "ProjectCreateCommand", + "title": "PriceLine", "type": "object" }, - "ProjectEntity": { + "Project": { "additionalProperties": false, "properties": { + "spendPolicy": { + "anyOf": [ + { + "$ref": "#/$defs/SpendPolicy" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional service spend controls." + }, "id": { - "description": "Stable identity of this project-owned object.", + "description": "Stable object ID.", "format": "uuid", "title": "Id", "type": "string" }, - "projectId": { - "description": "Owning project ID.", - "format": "uuid", - "title": "Projectid", - "type": "string" - }, "revision": { "default": 1, "description": "Current object revision for optimistic concurrency.", "minimum": 1, "title": "Revision", "type": "integer" - } - }, - "required": [ - "id", - "projectId", - "revision" - ], - "title": "ProjectEntity", - "type": "object" - }, - "ProjectEvent": { - "additionalProperties": false, - "properties": { - "schemaVersion": { - "const": 1, - "default": 1, - "description": "Record schema version.", - "title": "Schemaversion", - "type": "integer" }, - "projectId": { - "description": "Owning project ID.", - "format": "uuid", - "title": "Projectid", + "name": { + "description": "User-visible name.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Name", "type": "string" }, - "cursor": { - "description": "Monotonically increasing project event cursor.", - "minimum": 1, - "title": "Cursor", - "type": "integer" - }, - "commandId": { + "defaultNameIndex": { "anyOf": [ { - "format": "uuid", - "type": "string" + "minimum": 1, + "type": "integer" }, { "type": "null" } ], "default": null, - "description": "Stable command ID for idempotent replay.", - "title": "Commandid" - }, - "source": { - "description": "Input source or recorded provenance.", - "enum": [ - "ui", - "agent", - "background", - "external" - ], - "title": "Source", - "type": "string" - }, - "changed": { - "default": [], - "description": "Business objects changed by the operation.", - "items": { - "$ref": "#/$defs/ChangedObject" - }, - "title": "Changed", - "type": "array" - }, - "jobIds": { - "default": [], - "description": "Generation jobs associated with this operation.", - "items": { - "format": "uuid", - "type": "string" - }, - "title": "Jobids", - "type": "array" - } - }, - "required": [ - "schemaVersion", - "projectId", - "cursor", - "commandId", - "source", - "changed", - "jobIds" - ], - "title": "ProjectEvent", - "type": "object" - }, - "ProjectQuery": { - "additionalProperties": false, - "properties": { - "queryId": { - "description": "Caller-supplied query ID.", - "format": "uuid", - "title": "Queryid", - "type": "string" - }, - "projectId": { - "description": "Owning project ID.", - "format": "uuid", - "title": "Projectid", - "type": "string" - }, - "type": { - "const": "project.get", - "description": "Read the current project.", - "title": "Type", - "type": "string" + "description": "Index of the automatically named initial project.", + "title": "Defaultnameindex" } }, "required": [ - "queryId", - "projectId", - "type" + "id", + "revision", + "name" ], - "title": "ProjectQuery", + "title": "Project", "type": "object" }, - "ProjectRename": { + "ProjectCreate": { "additionalProperties": false, "properties": { "name": { @@ -26500,17 +28340,31 @@ "pattern": "\\S", "title": "Name", "type": "string" + }, + "defaultNameIndex": { + "anyOf": [ + { + "exclusiveMinimum": 0, + "type": "number" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Index for an automatically named initial project.", + "title": "Defaultnameindex" } }, "required": [ "name" ], - "title": "ProjectRename", + "title": "ProjectCreate", "type": "object" }, - "ProjectRenameCommand": { + "ProjectCreateCommand": { "additionalProperties": false, - "description": "Rename the project.", + "description": "Create a project.", "properties": { "commandId": { "description": "Stable command ID for idempotent replay.", @@ -26525,7 +28379,226 @@ "type": "string" }, "type": { - "const": "project.rename", + "const": "project.create", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/ProjectCreate", + "description": "Create a project." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" + ], + "title": "ProjectCreateCommand", + "type": "object" + }, + "ProjectEntity": { + "additionalProperties": false, + "properties": { + "id": { + "description": "Stable identity of this project-owned object.", + "format": "uuid", + "title": "Id", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "revision": { + "default": 1, + "description": "Current object revision for optimistic concurrency.", + "minimum": 1, + "title": "Revision", + "type": "integer" + } + }, + "required": [ + "id", + "projectId", + "revision" + ], + "title": "ProjectEntity", + "type": "object" + }, + "ProjectEvent": { + "additionalProperties": false, + "properties": { + "schemaVersion": { + "const": 1, + "default": 1, + "description": "Record schema version.", + "title": "Schemaversion", + "type": "integer" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "cursor": { + "description": "Monotonically increasing project event cursor.", + "minimum": 1, + "title": "Cursor", + "type": "integer" + }, + "commandId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stable command ID for idempotent replay.", + "title": "Commandid" + }, + "source": { + "description": "Input source or recorded provenance.", + "enum": [ + "ui", + "agent", + "background", + "external" + ], + "title": "Source", + "type": "string" + }, + "changed": { + "default": [], + "description": "Business objects changed by the operation.", + "items": { + "$ref": "#/$defs/ChangedObject" + }, + "title": "Changed", + "type": "array" + }, + "jobIds": { + "default": [], + "description": "Generation jobs associated with this operation.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Jobids", + "type": "array" + } + }, + "required": [ + "schemaVersion", + "projectId", + "cursor", + "commandId", + "source", + "changed", + "jobIds" + ], + "title": "ProjectEvent", + "type": "object" + }, + "ProjectQuery": { + "additionalProperties": false, + "properties": { + "queryId": { + "description": "Caller-supplied query ID.", + "format": "uuid", + "title": "Queryid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "project.get", + "description": "Read the current project.", + "title": "Type", + "type": "string" + } + }, + "required": [ + "queryId", + "projectId", + "type" + ], + "title": "ProjectQuery", + "type": "object" + }, + "ProjectRename": { + "additionalProperties": false, + "properties": { + "name": { + "description": "User-visible name.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Name", + "type": "string" + } + }, + "required": [ + "name" + ], + "title": "ProjectRename", + "type": "object" + }, + "ProjectRenameCommand": { + "additionalProperties": false, + "description": "Rename the project.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "project.rename", "description": "Command discriminator.", "title": "Type", "type": "string" @@ -26846,6 +28919,24 @@ "title": "Eventcursor", "type": "integer" }, + "spendRequests": { + "default": [], + "description": "Recorded decisions on fixed generation batches.", + "items": { + "$ref": "#/$defs/SpendRequest" + }, + "title": "Spendrequests", + "type": "array" + }, + "spendCalls": { + "default": [], + "description": "One reservation and its subsequent evidence per model call.", + "items": { + "$ref": "#/$defs/SpendCall" + }, + "title": "Spendcalls", + "type": "array" + }, "undoClearedThrough": { "default": 0, "description": "Event cursor through which undo history was cleared.", @@ -27961,8 +30052,1061 @@ "title": "Expectedpreview" }, "payload": { - "$ref": "#/$defs/SpecPromptWrite", - "description": "Update prompt text and structured references." + "$ref": "#/$defs/SpecPromptWrite", + "description": "Update prompt text and structured references." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" + ], + "title": "SpecPromptCommand", + "type": "object" + }, + "SpecPromptCommandOperation": { + "additionalProperties": false, + "description": "Update prompt text and structured references.", + "properties": { + "type": { + "const": "generationSpec.setPrompt", + "description": "Operation discriminator.", + "title": "Type", + "type": "string" + }, + "payload": { + "$ref": "#/$defs/SpecPromptWrite", + "description": "Update prompt text and structured references." + } + }, + "required": [ + "type", + "payload" + ], + "title": "SpecPromptCommandOperation", + "type": "object" + }, + "SpecPromptWrite": { + "additionalProperties": false, + "properties": { + "specId": { + "description": "Generation configuration ID.", + "format": "uuid", + "title": "Specid", + "type": "string" + }, + "prompt": { + "description": "Generation prompt text.", + "maxLength": 20000, + "title": "Prompt", + "type": "string" + }, + "promptContent": { + "anyOf": [ + { + "items": { + "discriminator": { + "mapping": { + "reference": "#/$defs/PromptReference", + "text": "#/$defs/PromptText" + }, + "propertyName": "type" + }, + "oneOf": [ + { + "$ref": "#/$defs/PromptText" + }, + { + "$ref": "#/$defs/PromptReference" + } + ] + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Structured prompt text and reference tokens.", + "title": "Promptcontent" + } + }, + "required": [ + "specId", + "prompt", + "promptContent" + ], + "title": "SpecPromptWrite", + "type": "object" + }, + "SpecRestore": { + "additionalProperties": false, + "properties": { + "specId": { + "description": "Generation configuration ID.", + "format": "uuid", + "title": "Specid", + "type": "string" + }, + "commandId": { + "description": "Historical command providing the settings to restore.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "referencePolicy": { + "default": "follow_current", + "description": "Policy for restoring associated reference bindings.", + "enum": [ + "follow_current", + "pinned" + ], + "title": "Referencepolicy", + "type": "string" + } + }, + "required": [ + "specId", + "commandId", + "referencePolicy" + ], + "title": "SpecRestore", + "type": "object" + }, + "SpecRestoreCommand": { + "additionalProperties": false, + "description": "Restore generation settings from a historical command.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "generationSpec.restore", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/SpecRestore", + "description": "Restore generation settings from a historical command." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" + ], + "title": "SpecRestoreCommand", + "type": "object" + }, + "SpecUpdateCommand": { + "additionalProperties": false, + "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "generationSpec.update", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/SpecWrite", + "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" + ], + "title": "SpecUpdateCommand", + "type": "object" + }, + "SpecUpdateCommandOperation": { + "additionalProperties": false, + "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged.", + "properties": { + "type": { + "const": "generationSpec.update", + "description": "Operation discriminator.", + "title": "Type", + "type": "string" + }, + "payload": { + "$ref": "#/$defs/SpecWrite", + "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged." + } + }, + "required": [ + "type", + "payload" + ], + "title": "SpecUpdateCommandOperation", + "type": "object" + }, + "SpecWrite": { + "additionalProperties": false, + "properties": { + "spec": { + "description": "Complete configuration with its current revision; the server increments it on commit. For updates, read the current spec, preserve unedited fields and submit its current expected version. Accepted job snapshots never change.", + "discriminator": { + "mapping": { + "audio": "#/$defs/AudioGenerationSpec", + "image": "#/$defs/ImageGenerationSpec", + "text": "#/$defs/TextGenerationSpec", + "video": "#/$defs/VideoGenerationSpec" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/$defs/TextGenerationSpec" + }, + { + "$ref": "#/$defs/ImageGenerationSpec" + }, + { + "$ref": "#/$defs/VideoGenerationSpec" + }, + { + "$ref": "#/$defs/AudioGenerationSpec" + } + ], + "title": "Spec" + } + }, + "required": [ + "spec" + ], + "title": "SpecWrite", + "type": "object" + }, + "SpendCall": { + "additionalProperties": false, + "properties": { + "id": { + "description": "Stable identity of this project-owned object.", + "format": "uuid", + "title": "Id", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "revision": { + "default": 1, + "description": "Current object revision for optimistic concurrency.", + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "ownerId": { + "description": "Generation job or media tool task that owns this call.", + "format": "uuid", + "title": "Ownerid", + "type": "string" + }, + "line": { + "$ref": "#/$defs/PriceLine", + "description": "Original native-currency estimate for this physical call." + }, + "createdAt": { + "description": "Time the reservation was created.", + "format": "date-time", + "title": "Createdat", + "type": "string" + }, + "state": { + "default": "reserved", + "description": "State of the provider call.", + "enum": [ + "reserved", + "submitted", + "completed", + "released" + ], + "title": "State", + "type": "string" + }, + "usage": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Metered units reported for the call.", + "title": "Usage" + }, + "usageSource": { + "anyOf": [ + { + "enum": [ + "execution", + "provider", + "media" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Origin of the quantity used for settlement.", + "title": "Usagesource" + }, + "calculated": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Amount calculated from confirmed usage and the agreed rate.", + "title": "Calculated" + }, + "reported": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Charge explicitly reported by the provider in the line currency.", + "title": "Reported" + } + }, + "required": [ + "id", + "projectId", + "revision", + "ownerId", + "line", + "createdAt", + "state", + "usage", + "usageSource", + "calculated", + "reported" + ], + "title": "SpendCall", + "type": "object" + }, + "SpendObservation": { + "additionalProperties": false, + "properties": { + "callId": { + "description": "Stable physical call receiving evidence.", + "format": "uuid", + "title": "Callid", + "type": "string" + }, + "state": { + "description": "Observed execution state.", + "enum": [ + "submitted", + "completed", + "released" + ], + "title": "State", + "type": "string" + }, + "unit": { + "anyOf": [ + { + "enum": [ + "request", + "input_character", + "input_second", + "requested_second", + "output_second" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Unit of observed provider usage.", + "title": "Unit" + }, + "usage": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Provider units or measured output length.", + "title": "Usage" + }, + "reported": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Verified provider amount in the quoted currency.", + "title": "Reported" + }, + "evidence": { + "default": "execution", + "description": "Source of the observation.", + "enum": [ + "execution", + "provider", + "media" + ], + "title": "Evidence", + "type": "string" + } + }, + "required": [ + "callId", + "state", + "unit", + "usage", + "reported", + "evidence" + ], + "title": "SpendObservation", + "type": "object" + }, + "SpendObservationCommand": { + "additionalProperties": false, + "description": "Record evidence from a model operation.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "spend.observe", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/SpendObservation", + "description": "Record evidence from a model operation." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" + ], + "title": "SpendObservationCommand", + "type": "object" + }, + "SpendPolicy": { + "additionalProperties": false, + "properties": { + "currency": { + "default": "USD", + "description": "Currency of the project spending limits.", + "enum": [ + "USD", + "CNY" + ], + "title": "Currency", + "type": "string" + }, + "threshold": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Require confirmation strictly above this batch amount.", + "title": "Threshold" + }, + "cap": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Maximum settled and reserved service spend.", + "title": "Cap" + } + }, + "required": [ + "currency", + "threshold", + "cap" + ], + "title": "SpendPolicy", + "type": "object" + }, + "SpendPolicyCommand": { + "additionalProperties": false, + "description": "Set project service spending controls.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "spend.policy", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/SpendPolicy", + "description": "Set project service spending controls." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" + ], + "title": "SpendPolicyCommand", + "type": "object" + }, + "SpendQuote": { + "additionalProperties": false, + "properties": { + "fromUpstream": { + "default": false, + "description": "Inputs are newly resolved upstream results.", + "title": "Fromupstream", + "type": "boolean" + }, + "candidates": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Total candidates across distinct group members.", + "title": "Candidates" + }, + "skipped": { + "default": [], + "description": "Workflow items blocked by a failed dependency or reference cycle.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Skipped", + "type": "array" + }, + "deferred": { + "default": [], + "description": "Workflow items awaiting upstream inputs.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Deferred", + "type": "array" + }, + "count": { + "description": "Number of fixed candidates in this action.", + "maximum": 8, + "minimum": 1, + "title": "Count", + "type": "integer" + }, + "inputFingerprint": { + "description": "Identity of the effective model inputs.", + "pattern": "^[0-9a-f]{64}$", + "title": "Inputfingerprint", + "type": "string" + }, + "lines": { + "description": "Individual provider calls per candidate, in execution order.", + "items": { + "$ref": "#/$defs/PriceLine" + }, + "title": "Lines", + "type": "array" + } + }, + "required": [ + "count", + "inputFingerprint", + "lines" + ], + "title": "SpendQuote", + "type": "object" + }, + "SpendRequest": { + "additionalProperties": false, + "properties": { + "id": { + "description": "Stable identity of this project-owned object.", + "format": "uuid", + "title": "Id", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "revision": { + "default": 1, + "description": "Current object revision for optimistic concurrency.", + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "currency": { + "anyOf": [ + { + "enum": [ + "USD", + "CNY" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Project currency when this quote was requested.", + "title": "Currency" + }, + "specId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fixed generation specification for a candidate batch.", + "title": "Specid" + }, + "batchId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Canvas batch identity for member validation.", + "title": "Batchid" + }, + "workflowId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Original group action owning this decision.", + "title": "Workflowid" + }, + "groupItems": { + "default": [], + "description": "Fixed workflow items included in this decision.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Groupitems", + "type": "array" + }, + "toolTask": { + "anyOf": [ + { + "additionalProperties": { + "$ref": "#/$defs/JsonValue" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Frozen media tool dispatch, without credentials. The project journal owns its acceptance.", + "title": "Tooltask" + }, + "versions": { + "description": "Input object versions fixed when the request was made.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Versions", + "type": "array" + }, + "quote": { + "$ref": "#/$defs/SpendQuote", + "description": "Exact batch covered by this request." + }, + "createdAt": { + "description": "Time the project requested a review.", + "format": "date-time", + "title": "Createdat", + "type": "string" + }, + "status": { + "default": "pending", + "description": "Human review status.", + "enum": [ + "pending", + "accepted", + "cancelled" + ], + "title": "Status", + "type": "string" + }, + "agentRunId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Originating assistant turn.", + "title": "Agentrunid" + }, + "agentCallId": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Originating assistant tool call.", + "title": "Agentcallid" + }, + "decisionId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Durable command that resolved this request.", + "title": "Decisionid" + } + }, + "required": [ + "id", + "projectId", + "revision", + "versions", + "quote", + "createdAt", + "status", + "agentRunId", + "agentCallId", + "decisionId" + ], + "title": "SpendRequest", + "type": "object" + }, + "SpendReview": { + "additionalProperties": false, + "properties": { + "requestId": { + "description": "Original batch request.", + "format": "uuid", + "title": "Requestid", + "type": "string" + }, + "fingerprint": { + "description": "Reviewed input and price fingerprint.", + "pattern": "^[0-9a-f]{64}$", + "title": "Fingerprint", + "type": "string" + }, + "decision": { + "description": "Human decision for this exact action.", + "enum": [ + "approve", + "cancel" + ], + "title": "Decision", + "type": "string" + }, + "acceptUnknown": { + "default": false, + "description": "Explicitly accepts this unpriced action with no project cap.", + "title": "Acceptunknown", + "type": "boolean" + }, + "newCap": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Raise the project cap in the same transaction as admission.", + "title": "Newcap" + } + }, + "required": [ + "requestId", + "fingerprint", + "decision", + "acceptUnknown", + "newCap" + ], + "title": "SpendReview", + "type": "object" + }, + "SpendReviewCommand": { + "additionalProperties": false, + "description": "Record a human decision on a fixed request.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "spend.review", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/SpendReview", + "description": "Record a human decision on a fixed request." } }, "required": [ @@ -27973,127 +31117,16 @@ "expectedPreview", "payload" ], - "title": "SpecPromptCommand", - "type": "object" - }, - "SpecPromptCommandOperation": { - "additionalProperties": false, - "description": "Update prompt text and structured references.", - "properties": { - "type": { - "const": "generationSpec.setPrompt", - "description": "Operation discriminator.", - "title": "Type", - "type": "string" - }, - "payload": { - "$ref": "#/$defs/SpecPromptWrite", - "description": "Update prompt text and structured references." - } - }, - "required": [ - "type", - "payload" - ], - "title": "SpecPromptCommandOperation", - "type": "object" - }, - "SpecPromptWrite": { - "additionalProperties": false, - "properties": { - "specId": { - "description": "Generation configuration ID.", - "format": "uuid", - "title": "Specid", - "type": "string" - }, - "prompt": { - "description": "Generation prompt text.", - "maxLength": 20000, - "title": "Prompt", - "type": "string" - }, - "promptContent": { - "anyOf": [ - { - "items": { - "discriminator": { - "mapping": { - "reference": "#/$defs/PromptReference", - "text": "#/$defs/PromptText" - }, - "propertyName": "type" - }, - "oneOf": [ - { - "$ref": "#/$defs/PromptText" - }, - { - "$ref": "#/$defs/PromptReference" - } - ] - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Structured prompt text and reference tokens.", - "title": "Promptcontent" - } - }, - "required": [ - "specId", - "prompt", - "promptContent" - ], - "title": "SpecPromptWrite", + "title": "SpendReviewCommand", "type": "object" }, - "SpecRestore": { + "SpendStatusQuery": { "additionalProperties": false, "properties": { - "specId": { - "description": "Generation configuration ID.", - "format": "uuid", - "title": "Specid", - "type": "string" - }, - "commandId": { - "description": "Historical command providing the settings to restore.", - "format": "uuid", - "title": "Commandid", - "type": "string" - }, - "referencePolicy": { - "default": "follow_current", - "description": "Policy for restoring associated reference bindings.", - "enum": [ - "follow_current", - "pinned" - ], - "title": "Referencepolicy", - "type": "string" - } - }, - "required": [ - "specId", - "commandId", - "referencePolicy" - ], - "title": "SpecRestore", - "type": "object" - }, - "SpecRestoreCommand": { - "additionalProperties": false, - "description": "Restore generation settings from a historical command.", - "properties": { - "commandId": { - "description": "Stable command ID for idempotent replay.", + "queryId": { + "description": "Caller-supplied query ID.", "format": "uuid", - "title": "Commandid", + "title": "Queryid", "type": "string" }, "projectId": { @@ -28102,25 +31135,10 @@ "title": "Projectid", "type": "string" }, - "type": { - "const": "generationSpec.restore", - "description": "Command discriminator.", - "title": "Type", - "type": "string" - }, - "expectedVersions": { - "default": [], - "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", - "items": { - "$ref": "#/$defs/ObjectVersion" - }, - "title": "Expectedversions", - "type": "array" - }, - "expectedPreview": { + "agentRunId": { "anyOf": [ { - "pattern": "^[0-9a-f]{64}$", + "format": "uuid", "type": "string" }, { @@ -28128,143 +31146,23 @@ } ], "default": null, - "description": "Fingerprint of the confirmed impact preview.", - "title": "Expectedpreview" - }, - "payload": { - "$ref": "#/$defs/SpecRestore", - "description": "Restore generation settings from a historical command." - } - }, - "required": [ - "commandId", - "projectId", - "type", - "expectedVersions", - "expectedPreview", - "payload" - ], - "title": "SpecRestoreCommand", - "type": "object" - }, - "SpecUpdateCommand": { - "additionalProperties": false, - "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged.", - "properties": { - "commandId": { - "description": "Stable command ID for idempotent replay.", - "format": "uuid", - "title": "Commandid", - "type": "string" - }, - "projectId": { - "description": "Owning project ID.", - "format": "uuid", - "title": "Projectid", - "type": "string" + "description": "Include the media service calls for this assistant turn.", + "title": "Agentrunid" }, "type": { - "const": "generationSpec.update", - "description": "Command discriminator.", + "const": "spend.status", + "description": "Read policy, totals, coverage and pending human decisions.", "title": "Type", "type": "string" - }, - "expectedVersions": { - "default": [], - "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", - "items": { - "$ref": "#/$defs/ObjectVersion" - }, - "title": "Expectedversions", - "type": "array" - }, - "expectedPreview": { - "anyOf": [ - { - "pattern": "^[0-9a-f]{64}$", - "type": "string" - }, - { - "type": "null" - } - ], - "default": null, - "description": "Fingerprint of the confirmed impact preview.", - "title": "Expectedpreview" - }, - "payload": { - "$ref": "#/$defs/SpecWrite", - "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged." } }, "required": [ - "commandId", + "queryId", "projectId", - "type", - "expectedVersions", - "expectedPreview", - "payload" - ], - "title": "SpecUpdateCommand", - "type": "object" - }, - "SpecUpdateCommandOperation": { - "additionalProperties": false, - "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged.", - "properties": { - "type": { - "const": "generationSpec.update", - "description": "Operation discriminator.", - "title": "Type", - "type": "string" - }, - "payload": { - "$ref": "#/$defs/SpecWrite", - "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged." - } - }, - "required": [ - "type", - "payload" - ], - "title": "SpecUpdateCommandOperation", - "type": "object" - }, - "SpecWrite": { - "additionalProperties": false, - "properties": { - "spec": { - "description": "Complete configuration with its current revision; the server increments it on commit. For updates, read the current spec, preserve unedited fields and submit its current expected version. Accepted job snapshots never change.", - "discriminator": { - "mapping": { - "audio": "#/$defs/AudioGenerationSpec", - "image": "#/$defs/ImageGenerationSpec", - "text": "#/$defs/TextGenerationSpec", - "video": "#/$defs/VideoGenerationSpec" - }, - "propertyName": "kind" - }, - "oneOf": [ - { - "$ref": "#/$defs/TextGenerationSpec" - }, - { - "$ref": "#/$defs/ImageGenerationSpec" - }, - { - "$ref": "#/$defs/VideoGenerationSpec" - }, - { - "$ref": "#/$defs/AudioGenerationSpec" - } - ], - "title": "Spec" - } - }, - "required": [ - "spec" + "agentRunId", + "type" ], - "title": "SpecWrite", + "title": "SpendStatusQuery", "type": "object" }, "StackCanvasItem": { @@ -30911,6 +33809,85 @@ "title": "ToolSelection", "type": "object" }, + "ToolSpendCommand": { + "additionalProperties": false, + "description": "Admit a frozen media tool recipe with its service costs.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "spend.tool", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/ToolSpendInput", + "description": "Admit a frozen media tool recipe with its service costs." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" + ], + "title": "ToolSpendCommand", + "type": "object" + }, + "ToolSpendInput": { + "additionalProperties": false, + "properties": { + "request": { + "additionalProperties": { + "$ref": "#/$defs/JsonValue" + }, + "description": "Validated media tool submission, including its stable task ID.", + "title": "Request", + "type": "object" + } + }, + "required": [ + "request" + ], + "title": "ToolSpendInput", + "type": "object" + }, "TransformFrame": { "additionalProperties": false, "properties": { @@ -32227,6 +35204,7 @@ "creation.batch": "#/$defs/BatchCommand", "editor.create": "#/$defs/EditorCreateCommand", "editor.save": "#/$defs/EditorSaveCommand", + "generation.group": "#/$defs/GenerationGroupCommand", "generation.submit": "#/$defs/GenerationSubmitCommand", "generationSpec.create": "#/$defs/SpecCreateCommand", "generationSpec.restore": "#/$defs/SpecRestoreCommand", @@ -32246,6 +35224,11 @@ "reference.restore": "#/$defs/ReferenceRestoreCommand", "reference.update": "#/$defs/ReferenceUpdateCommand", "result.select": "#/$defs/ResultSelectCommand", + "spend.advanceGroup": "#/$defs/AdvanceGroupCommand", + "spend.observe": "#/$defs/SpendObservationCommand", + "spend.policy": "#/$defs/SpendPolicyCommand", + "spend.review": "#/$defs/SpendReviewCommand", + "spend.tool": "#/$defs/ToolSpendCommand", "timeline.publishRender": "#/$defs/TimelinePublishRenderCommand" }, "propertyName": "type" @@ -32341,6 +35324,24 @@ { "$ref": "#/$defs/ReferenceRemoveCommand" }, + { + "$ref": "#/$defs/ToolSpendCommand" + }, + { + "$ref": "#/$defs/SpendObservationCommand" + }, + { + "$ref": "#/$defs/SpendPolicyCommand" + }, + { + "$ref": "#/$defs/SpendReviewCommand" + }, + { + "$ref": "#/$defs/GenerationGroupCommand" + }, + { + "$ref": "#/$defs/AdvanceGroupCommand" + }, { "$ref": "#/$defs/GenerationSubmitCommand" }, @@ -32387,14 +35388,26 @@ "asset.usage": "#/$defs/AssetUsageQuery", "canvas.status": "#/$defs/CanvasStatusQuery", "canvas.versions": "#/$defs/VersionsQuery", + "generation.groupQuote": "#/$defs/GroupQuoteQuery", + "generation.quote": "#/$defs/GenerationQuoteQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", "object.get": "#/$defs/ObjectQuery", - "project.get": "#/$defs/ProjectQuery" + "project.get": "#/$defs/ProjectQuery", + "spend.status": "#/$defs/SpendStatusQuery" }, "propertyName": "type" }, "oneOf": [ + { + "$ref": "#/$defs/SpendStatusQuery" + }, + { + "$ref": "#/$defs/GenerationQuoteQuery" + }, + { + "$ref": "#/$defs/GroupQuoteQuery" + }, { "$ref": "#/$defs/ProjectQuery" }, diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 772d869f9..27e7a68a0 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -2,6 +2,11 @@ // Names without Input describe normalized JSON output; Input permits declared defaults. // Runtime constraints and cross-object validation are enforced by the Python contracts. +export interface AdvanceGroupCommandInput extends CommandBaseInput { + readonly type: "spend.advanceGroup"; + readonly payload: GroupAdvanceInput; +} + export interface ArtifactPublishInput extends ContractInput { readonly path: string; readonly name: string; @@ -406,13 +411,20 @@ export interface CommandReceiptInput extends ContractInput { readonly commandId: string; readonly projectId: string; readonly inputFingerprint: string; - readonly status: "applied" | "accepted" | "noop" | "rejected"; + readonly status: "applied" | "accepted" | "noop" | "rejected" | "awaiting_confirmation"; + readonly spendRequestId?: string | null; readonly changed?: ReadonlyArray; readonly jobIds?: ReadonlyArray; readonly issues?: ReadonlyArray; readonly eventCursor?: number | null; } +export interface ConnectionPriceInput extends ContractInput { + readonly unit: "request" | "input_character" | "input_second" | "requested_second" | "output_second"; + readonly rate: number | string; + readonly currency: "USD" | "CNY"; +} + export interface ContainerBindingInput extends ContractInput { readonly role: "container"; } @@ -421,7 +433,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "spend_quote_changed" | "spend_cap" | "spend_unknown" | "invalid_input" | "revision_conflict" | "role_restricted" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -433,9 +445,9 @@ export interface CreationContractsInput extends ContractInput { readonly generationSpec: TextGenerationSpecInput | ImageGenerationSpecInput | VideoGenerationSpecInput | AudioGenerationSpecInput; readonly reference: PinnedReferenceInput | FollowingReferenceInput; readonly editorDocument: TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput; - readonly command: ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | NodeVersionApplyCommandInput | CanvasConfigureCommandInput | CanvasEditorAttachCommandInput | CanvasEditorDetachCommandInput | SpecCreateCommandInput | SpecUpdateCommandInput | SpecRestoreCommandInput | SpecPromptCommandInput | ReferenceAddCommandInput | ReferenceUpdateCommandInput | ReferenceRestoreCommandInput | ReferenceRemoveCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; + readonly command: ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | NodeVersionApplyCommandInput | CanvasConfigureCommandInput | CanvasEditorAttachCommandInput | CanvasEditorDetachCommandInput | SpecCreateCommandInput | SpecUpdateCommandInput | SpecRestoreCommandInput | SpecPromptCommandInput | ReferenceAddCommandInput | ReferenceUpdateCommandInput | ReferenceRestoreCommandInput | ReferenceRemoveCommandInput | ToolSpendCommandInput | SpendObservationCommandInput | SpendPolicyCommandInput | SpendReviewCommandInput | GenerationGroupCommandInput | AdvanceGroupCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; readonly receipt: CommandReceiptInput; - readonly query: ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | AssetPreviewQueryInput; + readonly query: SpendStatusQueryInput | GenerationQuoteQueryInput | GroupQuoteQueryInput | ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | AssetPreviewQueryInput; readonly event: ProjectEventInput; readonly job: JobInput; readonly result: ResultVersionInput; @@ -569,6 +581,22 @@ export interface GenerationFailureInput { readonly providerStatus?: "failed" | "cancelled" | "expired" | null; } +export interface GenerationGroupInput extends ContractInput { + readonly members: ReadonlyArray; +} + +export interface GenerationGroupCommandInput extends CommandBaseInput { + readonly type: "generation.group"; + readonly payload: GenerationGroupInput; +} + +export interface GenerationQuoteQueryInput extends QueryBaseInput { + readonly type: "generation.quote"; + readonly specId: string; + readonly originItemId?: string | null; + readonly count?: number; +} + export interface GenerationSpecBaseInput extends ProjectEntityInput { readonly purpose?: "draft" | "generation"; readonly modelConfigId?: string | null; @@ -583,6 +611,7 @@ export interface GenerationSpecRefInput extends ContractInput { } export interface GenerationSubmitInput extends ContractInput { + readonly count?: number; readonly specId: string; readonly expectedSpecRevision: number; readonly originItemId?: string | null; @@ -597,11 +626,28 @@ export interface GenerationSubmitCommandInput extends CommandBaseInput { readonly payload: GenerationSubmitInput; } +export interface GroupAdvanceInput extends ContractInput { + readonly workflowId: string; + readonly items: ReadonlyArray; +} + export interface GroupCanvasItemInput extends CanvasItemBaseInput { readonly kind: "group"; readonly binding?: ContainerBindingInput; } +export interface GroupMemberInput extends ContractInput { + readonly itemId: string; + readonly specId: string; + readonly count?: number; + readonly after?: ReadonlyArray; +} + +export interface GroupQuoteQueryInput extends QueryBaseInput { + readonly type: "generation.groupQuote"; + readonly workflow: GenerationGroupInput; +} + export interface HistoryRedoCommandInput extends CommandBaseInput { readonly type: "history.redo"; readonly payload: HistoryReplayInput; @@ -865,6 +911,7 @@ export interface ModelAvailabilityInput extends ContractInput { } export interface ModelConfigPublicInput extends ModelConnectionInput { + readonly price?: ConnectionPriceInput | null; readonly id: string; readonly providerId?: string | null; readonly inputRules: InputRulesInput; @@ -939,7 +986,7 @@ export interface ObjectQueryInput extends QueryBaseInput { } export interface ObjectVersionInput extends ContractInput { - readonly objectType: "project" | "asset" | "generation_spec" | "reference" | "canvas_item" | "editor_document" | "job" | "result"; + readonly objectType: "project" | "asset" | "generation_spec" | "reference" | "canvas_item" | "editor_document" | "job" | "result" | "spend_request" | "spend_call"; readonly id: string; readonly revision: number; } @@ -992,7 +1039,22 @@ export interface PointInput extends ContractInput { readonly y?: number; } +export interface PriceLineInput extends ContractInput { + readonly operation: string; + readonly modelConfigId: string; + readonly modelId: string; + readonly providerUrl?: string | null; + readonly source: "connection" | "official" | "local" | "unknown"; + readonly sourceUrl?: string | null; + readonly sourceVersion?: string | null; + readonly price?: ConnectionPriceInput | null; + readonly quantityBasis?: "fixed" | "maximum"; + readonly quantity?: number | string | null; + readonly amount?: number | string | null; +} + export interface ProjectInput extends ContractInput { + readonly spendPolicy?: SpendPolicyInput | null; readonly id: string; readonly revision?: number; readonly name: string; @@ -1055,6 +1117,8 @@ export interface ProjectSnapshotInput extends ContractInput { readonly jobs?: ReadonlyArray; readonly results?: ReadonlyArray; readonly eventCursor?: number; + readonly spendRequests?: ReadonlyArray; + readonly spendCalls?: ReadonlyArray; readonly undoClearedThrough?: number; } @@ -1238,6 +1302,86 @@ export interface SpecWriteInput extends ContractInput { readonly spec: TextGenerationSpecInput | ImageGenerationSpecInput | VideoGenerationSpecInput | AudioGenerationSpecInput; } +export interface SpendCallInput extends ProjectEntityInput { + readonly ownerId: string; + readonly line: PriceLineInput; + readonly createdAt: string; + readonly state?: "reserved" | "submitted" | "completed" | "released"; + readonly usage?: number | string | null; + readonly usageSource?: "execution" | "provider" | "media" | null; + readonly calculated?: number | string | null; + readonly reported?: number | string | null; +} + +export interface SpendObservationInput extends ContractInput { + readonly callId: string; + readonly state: "submitted" | "completed" | "released"; + readonly unit?: "request" | "input_character" | "input_second" | "requested_second" | "output_second" | null; + readonly usage?: number | string | null; + readonly reported?: number | string | null; + readonly evidence?: "execution" | "provider" | "media"; +} + +export interface SpendObservationCommandInput extends CommandBaseInput { + readonly type: "spend.observe"; + readonly payload: SpendObservationInput; +} + +export interface SpendPolicyInput extends ContractInput { + readonly currency?: "USD" | "CNY"; + readonly threshold?: number | string | null; + readonly cap?: number | string | null; +} + +export interface SpendPolicyCommandInput extends CommandBaseInput { + readonly type: "spend.policy"; + readonly payload: SpendPolicyInput; +} + +export interface SpendQuoteInput extends ContractInput { + readonly fromUpstream?: boolean; + readonly candidates?: number | null; + readonly skipped?: ReadonlyArray; + readonly deferred?: ReadonlyArray; + readonly count: number; + readonly inputFingerprint: string; + readonly lines: ReadonlyArray; +} + +export interface SpendRequestInput extends ProjectEntityInput { + readonly currency?: "USD" | "CNY" | null; + readonly specId?: string | null; + readonly batchId?: string | null; + readonly workflowId?: string | null; + readonly groupItems?: ReadonlyArray; + readonly toolTask?: Readonly> | null; + readonly versions: ReadonlyArray; + readonly quote: SpendQuoteInput; + readonly createdAt: string; + readonly status?: "pending" | "accepted" | "cancelled"; + readonly agentRunId?: string | null; + readonly agentCallId?: string | null; + readonly decisionId?: string | null; +} + +export interface SpendReviewInput extends ContractInput { + readonly requestId: string; + readonly fingerprint: string; + readonly decision: "approve" | "cancel"; + readonly acceptUnknown?: boolean; + readonly newCap?: number | string | null; +} + +export interface SpendReviewCommandInput extends CommandBaseInput { + readonly type: "spend.review"; + readonly payload: SpendReviewInput; +} + +export interface SpendStatusQueryInput extends QueryBaseInput { + readonly agentRunId?: string | null; + readonly type: "spend.status"; +} + export interface StackCanvasItemInput extends EditorCanvasItemInput { readonly kind: "stack"; } @@ -1517,6 +1661,15 @@ export interface ToolSelectionInput extends ContractInput { readonly boxes?: ReadonlyArray; } +export interface ToolSpendCommandInput extends CommandBaseInput { + readonly type: "spend.tool"; + readonly payload: ToolSpendInputInput; +} + +export interface ToolSpendInputInput extends ContractInput { + readonly request: Readonly>; +} + export interface TransformFrameInput extends ContractInput { readonly id: string; readonly time: number; @@ -1637,7 +1790,7 @@ export type ReferenceInput = PinnedReferenceInput | FollowingReferenceInput; export type EditorDocumentInput = TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput; -export type CommandInput = ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | NodeVersionApplyCommandInput | CanvasConfigureCommandInput | CanvasEditorAttachCommandInput | CanvasEditorDetachCommandInput | SpecCreateCommandInput | SpecUpdateCommandInput | SpecRestoreCommandInput | SpecPromptCommandInput | ReferenceAddCommandInput | ReferenceUpdateCommandInput | ReferenceRestoreCommandInput | ReferenceRemoveCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; +export type CommandInput = ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | NodeVersionApplyCommandInput | CanvasConfigureCommandInput | CanvasEditorAttachCommandInput | CanvasEditorDetachCommandInput | SpecCreateCommandInput | SpecUpdateCommandInput | SpecRestoreCommandInput | SpecPromptCommandInput | ReferenceAddCommandInput | ReferenceUpdateCommandInput | ReferenceRestoreCommandInput | ReferenceRemoveCommandInput | ToolSpendCommandInput | SpendObservationCommandInput | SpendPolicyCommandInput | SpendReviewCommandInput | GenerationGroupCommandInput | AdvanceGroupCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; export type ExecutionParametersInput = TextExecutionInput | ImageExecutionInput | VideoExecutionInput | AudioExecutionInput; @@ -1651,6 +1804,11 @@ export type ModelKindInput = "agent" | "image" | "video" | "audio" | "vision"; export type VideoModeInput = "first_frame" | "reference" | "continuation" | "control"; +export interface AdvanceGroupCommand extends CommandBase { + readonly type: "spend.advanceGroup"; + readonly payload: GroupAdvance; +} + export interface ArtifactPublish extends Contract { readonly path: string; readonly name: string; @@ -2055,13 +2213,20 @@ export interface CommandReceipt extends Contract { readonly commandId: string; readonly projectId: string; readonly inputFingerprint: string; - readonly status: "applied" | "accepted" | "noop" | "rejected"; + readonly status: "applied" | "accepted" | "noop" | "rejected" | "awaiting_confirmation"; + readonly spendRequestId?: string | null; readonly changed: ReadonlyArray; readonly jobIds: ReadonlyArray; readonly issues: ReadonlyArray; readonly eventCursor: number | null; } +export interface ConnectionPrice extends Contract { + readonly unit: "request" | "input_character" | "input_second" | "requested_second" | "output_second"; + readonly rate: string; + readonly currency: "USD" | "CNY"; +} + export interface ContainerBinding extends Contract { readonly role: "container"; } @@ -2070,7 +2235,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "role_restricted" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "spend_quote_changed" | "spend_cap" | "spend_unknown" | "invalid_input" | "revision_conflict" | "role_restricted" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId: string | null; readonly field: string | null; @@ -2082,9 +2247,9 @@ export interface CreationContracts extends Contract { readonly generationSpec: TextGenerationSpec | ImageGenerationSpec | VideoGenerationSpec | AudioGenerationSpec; readonly reference: PinnedReference | FollowingReference; readonly editorDocument: TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument; - readonly command: ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | NodeVersionApplyCommand | CanvasConfigureCommand | CanvasEditorAttachCommand | CanvasEditorDetachCommand | SpecCreateCommand | SpecUpdateCommand | SpecRestoreCommand | SpecPromptCommand | ReferenceAddCommand | ReferenceUpdateCommand | ReferenceRestoreCommand | ReferenceRemoveCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; + readonly command: ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | NodeVersionApplyCommand | CanvasConfigureCommand | CanvasEditorAttachCommand | CanvasEditorDetachCommand | SpecCreateCommand | SpecUpdateCommand | SpecRestoreCommand | SpecPromptCommand | ReferenceAddCommand | ReferenceUpdateCommand | ReferenceRestoreCommand | ReferenceRemoveCommand | ToolSpendCommand | SpendObservationCommand | SpendPolicyCommand | SpendReviewCommand | GenerationGroupCommand | AdvanceGroupCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; readonly receipt: CommandReceipt; - readonly query: ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | AssetPreviewQuery; + readonly query: SpendStatusQuery | GenerationQuoteQuery | GroupQuoteQuery | ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | AssetPreviewQuery; readonly event: ProjectEvent; readonly job: Job; readonly result: ResultVersion; @@ -2218,6 +2383,22 @@ export interface GenerationFailure { readonly providerStatus?: "failed" | "cancelled" | "expired" | null; } +export interface GenerationGroup extends Contract { + readonly members: ReadonlyArray; +} + +export interface GenerationGroupCommand extends CommandBase { + readonly type: "generation.group"; + readonly payload: GenerationGroup; +} + +export interface GenerationQuoteQuery extends QueryBase { + readonly type: "generation.quote"; + readonly specId: string; + readonly originItemId: string | null; + readonly count: number; +} + export interface GenerationSpecBase extends ProjectEntity { readonly purpose: "draft" | "generation"; readonly modelConfigId: string | null; @@ -2232,6 +2413,7 @@ export interface GenerationSpecRef extends Contract { } export interface GenerationSubmit extends Contract { + readonly count?: number; readonly specId: string; readonly expectedSpecRevision: number; readonly originItemId: string | null; @@ -2246,11 +2428,28 @@ export interface GenerationSubmitCommand extends CommandBase { readonly payload: GenerationSubmit; } +export interface GroupAdvance extends Contract { + readonly workflowId: string; + readonly items: ReadonlyArray; +} + export interface GroupCanvasItem extends CanvasItemBase { readonly kind: "group"; readonly binding: ContainerBinding; } +export interface GroupMember extends Contract { + readonly itemId: string; + readonly specId: string; + readonly count: number; + readonly after: ReadonlyArray; +} + +export interface GroupQuoteQuery extends QueryBase { + readonly type: "generation.groupQuote"; + readonly workflow: GenerationGroup; +} + export interface HistoryRedoCommand extends CommandBase { readonly type: "history.redo"; readonly payload: HistoryReplay; @@ -2514,6 +2713,7 @@ export interface ModelAvailability extends Contract { } export interface ModelConfigPublic extends ModelConnection { + readonly price?: ConnectionPrice | null; readonly id: string; readonly inputRules: InputRules; readonly capabilityAutoCheck?: boolean | null; @@ -2587,7 +2787,7 @@ export interface ObjectQuery extends QueryBase { } export interface ObjectVersion extends Contract { - readonly objectType: "project" | "asset" | "generation_spec" | "reference" | "canvas_item" | "editor_document" | "job" | "result"; + readonly objectType: "project" | "asset" | "generation_spec" | "reference" | "canvas_item" | "editor_document" | "job" | "result" | "spend_request" | "spend_call"; readonly id: string; readonly revision: number; } @@ -2640,7 +2840,22 @@ export interface Point extends Contract { readonly y: number; } +export interface PriceLine extends Contract { + readonly operation: string; + readonly modelConfigId: string; + readonly modelId: string; + readonly providerUrl?: string | null; + readonly source: "connection" | "official" | "local" | "unknown"; + readonly sourceUrl?: string | null; + readonly sourceVersion: string | null; + readonly price: ConnectionPrice | null; + readonly quantityBasis?: "fixed" | "maximum"; + readonly quantity: string | null; + readonly amount: string | null; +} + export interface Project extends Contract { + readonly spendPolicy?: SpendPolicy | null; readonly id: string; readonly revision: number; readonly name: string; @@ -2703,6 +2918,8 @@ export interface ProjectSnapshot extends Contract { readonly jobs: ReadonlyArray; readonly results: ReadonlyArray; readonly eventCursor: number; + readonly spendRequests?: ReadonlyArray; + readonly spendCalls?: ReadonlyArray; readonly undoClearedThrough: number; } @@ -2886,6 +3103,86 @@ export interface SpecWrite extends Contract { readonly spec: TextGenerationSpec | ImageGenerationSpec | VideoGenerationSpec | AudioGenerationSpec; } +export interface SpendCall extends ProjectEntity { + readonly ownerId: string; + readonly line: PriceLine; + readonly createdAt: string; + readonly state: "reserved" | "submitted" | "completed" | "released"; + readonly usage: string | null; + readonly usageSource: "execution" | "provider" | "media" | null; + readonly calculated: string | null; + readonly reported: string | null; +} + +export interface SpendObservation extends Contract { + readonly callId: string; + readonly state: "submitted" | "completed" | "released"; + readonly unit: "request" | "input_character" | "input_second" | "requested_second" | "output_second" | null; + readonly usage: string | null; + readonly reported: string | null; + readonly evidence: "execution" | "provider" | "media"; +} + +export interface SpendObservationCommand extends CommandBase { + readonly type: "spend.observe"; + readonly payload: SpendObservation; +} + +export interface SpendPolicy extends Contract { + readonly currency: "USD" | "CNY"; + readonly threshold: string | null; + readonly cap: string | null; +} + +export interface SpendPolicyCommand extends CommandBase { + readonly type: "spend.policy"; + readonly payload: SpendPolicy; +} + +export interface SpendQuote extends Contract { + readonly fromUpstream?: boolean; + readonly candidates?: number | null; + readonly skipped?: ReadonlyArray; + readonly deferred?: ReadonlyArray; + readonly count: number; + readonly inputFingerprint: string; + readonly lines: ReadonlyArray; +} + +export interface SpendRequest extends ProjectEntity { + readonly currency?: "USD" | "CNY" | null; + readonly specId?: string | null; + readonly batchId?: string | null; + readonly workflowId?: string | null; + readonly groupItems?: ReadonlyArray; + readonly toolTask?: Readonly> | null; + readonly versions: ReadonlyArray; + readonly quote: SpendQuote; + readonly createdAt: string; + readonly status: "pending" | "accepted" | "cancelled"; + readonly agentRunId: string | null; + readonly agentCallId: string | null; + readonly decisionId: string | null; +} + +export interface SpendReview extends Contract { + readonly requestId: string; + readonly fingerprint: string; + readonly decision: "approve" | "cancel"; + readonly acceptUnknown: boolean; + readonly newCap: string | null; +} + +export interface SpendReviewCommand extends CommandBase { + readonly type: "spend.review"; + readonly payload: SpendReview; +} + +export interface SpendStatusQuery extends QueryBase { + readonly agentRunId: string | null; + readonly type: "spend.status"; +} + export interface StackCanvasItem extends EditorCanvasItem { readonly kind: "stack"; } @@ -3165,6 +3462,15 @@ export interface ToolSelection extends Contract { readonly boxes: ReadonlyArray; } +export interface ToolSpendCommand extends CommandBase { + readonly type: "spend.tool"; + readonly payload: ToolSpendInput; +} + +export interface ToolSpendInput extends Contract { + readonly request: Readonly>; +} + export interface TransformFrame extends Contract { readonly id: string; readonly time: number; @@ -3285,7 +3591,7 @@ export type Reference = PinnedReference | FollowingReference; export type EditorDocument = TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument; -export type Command = ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | NodeVersionApplyCommand | CanvasConfigureCommand | CanvasEditorAttachCommand | CanvasEditorDetachCommand | SpecCreateCommand | SpecUpdateCommand | SpecRestoreCommand | SpecPromptCommand | ReferenceAddCommand | ReferenceUpdateCommand | ReferenceRestoreCommand | ReferenceRemoveCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; +export type Command = ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | NodeVersionApplyCommand | CanvasConfigureCommand | CanvasEditorAttachCommand | CanvasEditorDetachCommand | SpecCreateCommand | SpecUpdateCommand | SpecRestoreCommand | SpecPromptCommand | ReferenceAddCommand | ReferenceUpdateCommand | ReferenceRestoreCommand | ReferenceRemoveCommand | ToolSpendCommand | SpendObservationCommand | SpendPolicyCommand | SpendReviewCommand | GenerationGroupCommand | AdvanceGroupCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; export type ExecutionParameters = TextExecution | ImageExecution | VideoExecution | AudioExecution; diff --git a/src/i18n/messages/en-US/generation.ts b/src/i18n/messages/en-US/generation.ts index c89c2c9c1..07ebeea33 100644 --- a/src/i18n/messages/en-US/generation.ts +++ b/src/i18n/messages/en-US/generation.ts @@ -1,5 +1,123 @@ /** Composer, generation state, model choice and generation rules. */ export const generation = { + "spend.title": "Project spend", + "spend.confirmTitle": "Confirm this cost", + "spend.overview": "Spending controls and history", + "spend.pendingHint": "Project spend · {count} awaiting review", + "spend.estimate": "{action} · {amount} estimated", + "spend.action.image": { one: "Generate {count} image", other: "Generate {count} images" }, + "spend.action.video": { one: "Generate {count} video", other: "Generate {count} videos" }, + "spend.action.music": { one: "Generate {count} music track", other: "Generate {count} music tracks" }, + "spend.action.speech": { one: "Synthesize {count} speech clip", other: "Synthesize {count} speech clips" }, + "spend.action.tasks": { one: "Run {count} generation task", other: "Run {count} generation tasks" }, + "spend.each.image": "{amount} per image · {model}", + "spend.each.video": "{amount} per video · {model}", + "spend.each.music": "{amount} per track · {model}", + "spend.each.speech": "{amount} per clip · {model}", + "spend.selectionPreview": "Preview selection", + "spend.mediaTool": "Run media tool", + "spend.batchEstimate": "Batch estimate", + "spend.priceDetails": "Price details", + "spend.estimating": "Calculating estimate…", + "spend.estimateUnavailable": "Estimate unavailable", + "spend.batchLine": "{amount} each × {count}", + "spend.after": "Project total {amount}", + "spend.unknown": "Unknown price", + "spend.shortfall": "{available} available. This batch needs {missing} more.", + "spend.capOutOfRange": "This batch requires more than the largest supported project cap.", + "spend.needPrice": "Set a price in the project currency or choose another model, then request a new estimate.", + "spend.connections": "Model connections", + "spend.raiseRun": "Raise cap to {amount} and run", + "spend.raiseGenerate": "Raise cap to {amount} and generate", + "spend.generate": "Confirm generation", + "spend.cancelGeneration": "Cancel generation", + "spend.reviewSubmitted": "Batch submitted.", + "spend.reviewCancelled": "Request cancelled.", + "spend.allowUnknown": "Accept unknown cost for this batch", + "spend.approve": "Run this batch", + "spend.cancel": "Cancel request", + "spend.currency": "Currency", + "spend.threshold": "Confirm above", + "spend.cap": "Project cap", + "spend.off": "No limit", + "spend.save": "Save", + "spend.saved": "Saved", + "spend.pending": "Spend review ({count})", + "spend.summary": "Spent so far {settled} · Reserved for tasks {held}", + "spend.spent": "Spent so far", + "spend.held": "Reserved for tasks", + "spend.spentHelp": "Model costs already counted toward this project. Spend history shows the individual calls.", + "spend.spentHelp.image": { one: "This amount covers {count} image generated for {amount}.", other: "This amount covers {count} images from one batch, totaling {amount}." }, + "spend.spentHelp.video": { one: "This amount covers {count} video generated for {amount}.", other: "This amount covers {count} videos from one batch, totaling {amount}." }, + "spend.heldHelp.zero": "Approved tasks reserve budget until their costs are known. No tasks are reserving budget now.", + "spend.heldHelp.active": "Approved tasks are reserving {amount}. Their costs move to spent once confirmed.", + "spend.heldHelp.unknown": "This is the amount that approved tasks can reserve in the project currency. Some call costs are still unknown.", + "spend.coverage": "{count} call(s) have no verified amount in this currency.", + "spend.controls": "Spending controls", + "spend.log": "Spend history", + "spend.since": "Records since {date}", + "spend.estimateAmount": "Estimated", + "spend.calculated": "Calculated", + "spend.reported": "Provider charge", + "spend.price": "Unit price", + "spend.automatic": "Automatic", + "spend.mediaToolPrice": "Media tool call price", + "spend.unit": "Billing unit", + "spend.previewStopped": "The selection preview stopped. Check its call history in Project spend.", + "spend.priorUnknown": "Earlier calls have no confirmed amount in the project currency. The available budget for this batch is unknown.", + "spend.workflowProgress": "Workflow · {state} · {completed}/{total} steps completed", + "spend.workflowState.waiting": "Awaiting review", + "spend.workflowState.running": "Running", + "spend.workflowState.cancelled": "Cancelled", + "spend.workflowState.completed": "Completed", + "spend.workflowState.incomplete": "Incomplete", + "spend.skippedSteps": "{count} step(s) skipped due to a dependency", + "spend.awaitingInputs": "{count} step(s) awaiting inputs", + "spend.deferred": "{count} downstream step(s) need the upstream outputs before their inputs can be priced.", + "spend.runUpstream": "Run the quoted upstream steps", + "spend.stale": "The project currency changed. Cancel this request and get a new estimate.", + "spend.staleInputs": "The project content used for this estimate has changed. Cancel this request, then submit the task again for a new estimate.", + "spend.waiting": "The batch is waiting for spend review.", + "spend.unit.request": "request", + "spend.unit.input_character": "input character", + "spend.unit.input_second": "input second", + "spend.unit.requested_second": "requested second", + "spend.unit.output_second": "output second", + "spend.source.local": "Local service", + "spend.source.connection": "Connection price", + "spend.source.official": "Official price", + "spend.source.unknown": "Unknown source", + "spend.operation.text.chat": "Prompt translation", + "spend.operation.image.edit": "Image editing", + "spend.operation.image.generate": "Image generation", + "spend.operation.image.cutout": "Image cutout", + "spend.operation.image.segment": "Object segmentation", + "spend.operation.video.generate": "Video generation", + "spend.operation.video.first_frame": "Image-to-video generation", + "spend.operation.video.edit": "Video editing", + "spend.operation.video.matting": "Video matting", + "spend.operation.video.motion_capture": "Depth capture", + "spend.operation.audio.separate": "Audio separation", + "spend.operation.audio.speech": "Speech synthesis", + "spend.operation.audio.music": "Music generation", + "spend.operation.audio.score": "Score transcription", + "spend.knownSubtotal": "Known subtotal {amount}", + "spend.noRate": "No applicable price for this connection and model.", + "spend.missingUnits": "Billable units cannot be determined before this call.", + "spend.usage.provider": "Provider usage", + "spend.usage.execution": "Confirmed request units", + "spend.usage.media": "Measured output duration", + "spend.turn": "Media for this turn", + "spend.toolQuote": "Estimated tool cost {amount}", + "spend.operation.image": "Image generation", + "spend.operation.video": "Video generation", + "spend.operation.speech": "Speech synthesis", + "spend.operation.music": "Music generation", + "spend.operation.score": "Score transcription", + "spend.state.reserved": "Reserved", + "spend.state.submitted": "Awaiting provider evidence", + "spend.state.completed": "Completed", + "spend.state.released": "Released", "generation.duration.fractionalHint": "H3 accepts fractional seconds and aligns output frames upward to 17k+5 at 24 fps.", "generation.duration.aligned": "Output: {frames} frames · {seconds} s", "generation.bigmodel.watermarkWaiver": diff --git a/src/i18n/messages/zh-CN/generation.ts b/src/i18n/messages/zh-CN/generation.ts index 8008099b8..ac0307ff2 100644 --- a/src/i18n/messages/zh-CN/generation.ts +++ b/src/i18n/messages/zh-CN/generation.ts @@ -1,5 +1,123 @@ /** Composer, generation state, model choice and generation rules. */ export const generation = { + "spend.title": "工程费用", + "spend.confirmTitle": "确认本次费用", + "spend.overview": "费用设置与记录", + "spend.pendingHint": "工程费用 · {count} 项待确认", + "spend.estimate": "{action} · 预计 {amount}", + "spend.action.image": "生成 {count} 张图片", + "spend.action.video": "生成 {count} 段视频", + "spend.action.music": "生成 {count} 首音乐", + "spend.action.speech": "合成 {count} 段语音", + "spend.action.tasks": "运行 {count} 项生成任务", + "spend.each.image": "每张 {amount} · {model}", + "spend.each.video": "每段 {amount} · {model}", + "spend.each.music": "每首 {amount} · {model}", + "spend.each.speech": "每段 {amount} · {model}", + "spend.selectionPreview": "预览选区", + "spend.mediaTool": "运行媒体工具", + "spend.batchEstimate": "本次预计", + "spend.priceDetails": "计价明细", + "spend.estimating": "正在估算费用…", + "spend.estimateUnavailable": "暂时无法估价", + "spend.batchLine": "每个 {amount} × {count}", + "spend.after": "工程预计合计 {amount}", + "spend.unknown": "价格未知", + "spend.shortfall": "可用预算为 {available},还差 {missing}。", + "spend.capOutOfRange": "本次所需金额超过可设置的工程上限。", + "spend.needPrice": "请配置工程币种的单价或选择其他模型,然后重新询价。", + "spend.connections": "模型接入", + "spend.raiseRun": "将上限提高到 {amount}并运行", + "spend.raiseGenerate": "将上限提高到 {amount}并生成", + "spend.generate": "确认生成", + "spend.cancelGeneration": "取消本次生成", + "spend.reviewSubmitted": "本批任务已提交。", + "spend.reviewCancelled": "本次申请已取消。", + "spend.allowUnknown": "接受本批未知费用", + "spend.approve": "确认运行本批", + "spend.cancel": "取消申请", + "spend.currency": "币种", + "spend.threshold": "单批确认阈值", + "spend.cap": "工程上限", + "spend.off": "未设置", + "spend.save": "保存", + "spend.saved": "已保存", + "spend.pending": "费用待确认({count})", + "spend.summary": "已用金额 {settled} · 任务占用 {held}", + "spend.spent": "已用金额", + "spend.held": "任务占用", + "spend.spentHelp": "工程中已计入的模型费用。可以在费用记录中查看每次调用的金额。", + "spend.spentHelp.image": "这笔费用来自同一批生成的 {count} 张图片,共 {amount}。", + "spend.spentHelp.video": "这笔费用来自同一批生成的 {count} 段视频,共 {amount}。", + "spend.heldHelp.zero": "已批准的任务在费用确定前会占用预算。目前没有任务占用预算。", + "spend.heldHelp.active": "已批准的任务正在占用 {amount}。费用确定后会计入已用金额。", + "spend.heldHelp.unknown": "这里显示已批准任务中能够按工程币种估算的占用金额。部分调用的费用仍未确定。", + "spend.coverage": "有 {count} 项调用缺少该币种的可核验金额。", + "spend.controls": "费用设置", + "spend.log": "费用记录", + "spend.since": "记录始于 {date}", + "spend.estimateAmount": "预计", + "spend.calculated": "按用量计算", + "spend.reported": "服务报告金额", + "spend.price": "单价", + "spend.automatic": "自动", + "spend.mediaToolPrice": "媒体工具调用单价", + "spend.unit": "计费单位", + "spend.previewStopped": "选区预览已停止,可在工程费用中查看调用记录。", + "spend.priorUnknown": "先前的调用仍有费用无法用工程币种合计,暂时无法确定本批的可用预算。", + "spend.workflowProgress": "分组工作流 · {state} · 已完成 {completed}/{total} 个步骤", + "spend.workflowState.waiting": "等待确认", + "spend.workflowState.running": "运行中", + "spend.workflowState.cancelled": "已取消", + "spend.workflowState.completed": "已完成", + "spend.workflowState.incomplete": "部分步骤未完成", + "spend.skippedSteps": "{count} 个步骤因依赖关系无法执行", + "spend.awaitingInputs": "{count} 个步骤等待输入", + "spend.deferred": "还有 {count} 个下游步骤需要先取得上游结果,才能估算费用。", + "spend.runUpstream": "运行已报价的上游步骤", + "spend.stale": "工程币种已变更。请取消此申请并重新报价。", + "spend.staleInputs": "本次估价使用的工程内容已变更。请取消本次申请,重新发起任务以获取最新报价。", + "spend.waiting": "本批正在等待费用确认。", + "spend.unit.request": "次", + "spend.unit.input_character": "输入字符", + "spend.unit.input_second": "输入秒数", + "spend.unit.requested_second": "请求秒数", + "spend.unit.output_second": "输出秒数", + "spend.source.local": "本地服务", + "spend.source.connection": "连接单价", + "spend.source.official": "官方单价", + "spend.source.unknown": "来源未知", + "spend.operation.text.chat": "提示词翻译", + "spend.operation.image.edit": "图片编辑", + "spend.operation.image.generate": "图片生成", + "spend.operation.image.cutout": "主体抠图", + "spend.operation.image.segment": "对象分割", + "spend.operation.video.generate": "视频生成", + "spend.operation.video.first_frame": "首帧生成视频", + "spend.operation.video.edit": "视频编辑", + "spend.operation.video.matting": "视频抠像", + "spend.operation.video.motion_capture": "深度动作捕捉", + "spend.operation.audio.separate": "音轨分离", + "spend.operation.audio.speech": "语音合成", + "spend.operation.audio.music": "音乐生成", + "spend.operation.audio.score": "录音转谱", + "spend.knownSubtotal": "已知小计 {amount}", + "spend.noRate": "此连接和模型尚无适用的价格。", + "spend.missingUnits": "调用前无法确定计费用量。", + "spend.usage.provider": "服务报告用量", + "spend.usage.execution": "已完成请求用量", + "spend.usage.media": "保存媒体的实测时长", + "spend.turn": "本轮媒体费用", + "spend.toolQuote": "工具预计费用 {amount}", + "spend.operation.image": "图片生成", + "spend.operation.video": "视频生成", + "spend.operation.speech": "语音合成", + "spend.operation.music": "音乐生成", + "spend.operation.score": "录音转谱", + "spend.state.reserved": "已预留", + "spend.state.submitted": "等待服务结果", + "spend.state.completed": "已完成", + "spend.state.released": "已释放", "generation.duration.fractionalHint": "H3 支持小数秒,输出帧数向上对齐至 17k+5,帧率为 24 fps。", "generation.duration.aligned": "实际输出:{frames} 帧 · {seconds} 秒", "generation.bigmodel.watermarkWaiver": diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index da72ffc51..f478b8def 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -1,5 +1,7 @@ { "scripts": [ + { "file": "project_spend.mjs", "httpGenerationFixture": true, "lanes": ["extendedHttpFixture"], + "note": "Bilingual batch pricing and confirmation with a loopback image provider." }, { "file": "fasth3_capability_flow.mjs", "helper": true diff --git a/tests/browser/project_spend.mjs b/tests/browser/project_spend.mjs new file mode 100644 index 000000000..1350384a0 --- /dev/null +++ b/tests/browser/project_spend.mjs @@ -0,0 +1,363 @@ +/** Full batch review against a loopback image provider, in both UI languages. */ +import assert from "node:assert/strict"; +import { once } from "node:events"; +import { createServer } from "node:http"; +import { execFile, spawnSync } from "node:child_process"; +import { launchBrowser } from "./engine.mjs"; + +const web = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179"; +const api = process.env.CREATION_API_URL ?? "http://127.0.0.1:8019"; +async function call(path, payload, method = payload ? "POST" : "GET") { + const response = await fetch(api + path, { + method, headers: { "X-OpenDirector-Request": "1", "Content-Type": "application/json" }, + ...(payload ? { body: JSON.stringify(payload) } : {}), + }); + assert.ok(response.ok, await response.clone().text()); + return response.status === 204 ? null : response.json(); +} +async function until(read, matches) { + const deadline = Date.now() + 45000; + let value; + do { + value = await read(); + if (matches(value)) return value; + await new Promise(resolve => setTimeout(resolve, 100)); + } while (Date.now() < deadline); + throw Error("Timed out waiting for project state: " + JSON.stringify(value.jobs?.map(j => [j.status, j.errorDetails]))); +} +assert.ok((await call("/api/creation-test-health")).httpGenerationFixture); +const picture = spawnSync("ffmpeg", ["-v", "error", "-f", "lavfi", "-i", "color=c=blue:s=1024x1024", + "-frames:v", "1", "-threads", "1", "-f", "image2pipe", "-c:v", "png", "pipe:1"]); +assert.equal(picture.status, 0); +const posts = []; +const service = createServer(async (req, res) => { + if (req.url !== "/v1/images/generations") { res.writeHead(404).end(); return; } + const chunks = []; + for await (const chunk of req) chunks.push(chunk); + posts.push(JSON.parse(Buffer.concat(chunks))); + res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ data: [{ b64_json: picture.stdout.toString("base64") }] })); +}); +service.listen(0, "127.0.0.1"); +await once(service, "listening"); +const browser = await launchBrowser(); +let model, translator; +try { + model = await call("/api/model-configs", { kind: "image", modelId: "review-image", url: `http://127.0.0.1:${service.address().port}/v1`, + authMode: "none", connectionType: "api", protocol: "openai", capabilityAutoCheck: false }); + translator = await call("/api/model-configs", { kind: "agent", modelId: "review-translation", url: `http://127.0.0.1:${service.address().port}/v1`, + authMode: "none", connectionType: "api", protocol: "openai", capabilityAutoCheck: false }); + for (const locale of ["zh-CN", "en-US"]) { + const en = locale === "en-US", pid = crypto.randomUUID(), path = `/api/creation/projects/${pid}`; + await call(path + "/commands", { type: "project.create", commandId: crypto.randomUUID(), projectId: pid, payload: { name: "Spend " + pid.slice(0, 8) } }); + const page = await browser.newPage({ locale, viewport: { width: 1480, height: 940 } }); + page.setDefaultTimeout(20000); + const errors = []; + page.on("pageerror", error => errors.push(error.message)); + await page.addInitScript(locale => { + localStorage.setItem("opendirector.locale.v1", locale); + localStorage.setItem("opendirector.theme.v1", locale === "en-US" ? "light" : "dark"); + localStorage.setItem("opendirector.modelSetup.v1", "dismissed"); + }, locale); + await page.goto(`${web}/ai-tool/ai-canvas/${pid}`); + await page.getByRole("button", {name: en ? "Settings" : "设置", exact: true}).click(); + await page.getByRole("button", {name: en ? "Model connections" : "模型接入", exact: true}).click(); + await page.locator(".cw-model-setup-row").filter({hasText: en ? "Image model" : "图片模型"}).getByRole("button").click(); + for (const [connection, rate] of [[model, "0.40"], [translator, "0.03"]]) { + const label = en ? "Unit price" : "单价"; + const helper = connection.id === translator.id; + if (helper) await page.locator(".cw-model-categories").getByRole("button", {name: en ? "Chat" : "对话", exact: true}).click(); + const serviceCard = page.locator(".cw-model-service").filter({has: page.locator(".cw-model-chip", {hasText: connection.modelId})}); + await serviceCard.locator("summary").filter({hasText: helper ? (en ? "Media tool call price" : "媒体工具调用单价") : label}).click(); + const form = serviceCard.locator(".cw-spend-form").filter({hasText: connection.modelId}); + await form.getByLabel(label, {exact: true}).fill(rate); + await form.getByRole("button", {name: en ? "Save" : "保存", exact: true}).click(); + await form.getByRole("status").filter({hasText: en ? "Saved" : "已保存"}).waitFor(); + const saved = (await call("/api/model-configs")).find(value => value.id === connection.id); + assert.equal(Number(saved.price.rate), Number(rate)); + assert.equal(saved.price.unit, "request"); + assert.equal(saved.price.currency, "USD"); + } + await page.getByRole("button", {name: en ? "Close settings" : "关闭设置", exact: true}).click(); + const toggle = page.locator(".cw-spend-toggle"); + const dialog = page.locator("dialog.cw-spend-dialog[open]"); + const closeDialog = () => dialog.locator(".cw-spend-close").click(); + const collapsed = page.locator('.cw-spend-toggle[aria-expanded="false"]'); + assert.equal(await toggle.innerText(), ""); + const size = await toggle.boundingBox(); + const settingsSize = await page.getByRole("button", {name: en ? "Settings" : "设置", exact: true}).boundingBox(); + assert.deepEqual([size.width, size.height], [settingsSize.width, settingsSize.height]); + await toggle.click(); + await page.getByText(en ? "Spending controls" : "费用设置", { exact: true }).click(); + await page.getByLabel(en ? "Confirm above" : "单批确认阈值").fill("1"); + await page.getByRole("button", { name: en ? "Save" : "保存", exact: true }).click(); + await until(() => call(path), s => Number(s.project.spendPolicy?.threshold) === 1); + await closeDialog(); + const itemId = await page.evaluate(async ({ pid, modelId }) => { + const { creationClient } = await import("/src/backend/creationClient.ts"); + const specId = crypto.randomUUID(), itemId = crypto.randomUUID(); + await creationClient(pid).command("canvas.createGeneration", { + spec: { id: specId, projectId: pid, kind: "image", purpose: "generation", modelConfigId: modelId, prompt: "Blue", parameters: { size: "1024x1024" } }, + item: { id: itemId, projectId: pid, kind: "image", position: { x: 0, y: 0 }, binding: { role: "generation", objectRef: { id: specId } } }, + }); + return itemId; + }, { pid, modelId: model.id }); + await page.locator(`.react-flow__node[data-id="${itemId}"]`).click(); + const composer = page.locator(".cw-generation-composer"); + // Let the real quotation reach the browser between pointer down and pointer up. + let releaseQuote; + const waitForRelease = new Promise(resolve => { releaseQuote = resolve; }); + const quotePath = "**" + path + "/queries"; + const isBatchQuote = request => { + const body = request.postDataJSON(); + return body?.type === "generation.quote" && body.count === 3; + }; + await page.route(quotePath, async route => { + if (!isBatchQuote(route.request())) return route.continue(); + const response = await route.fetch(); + await waitForRelease; + await route.fulfill({response}); + }); + const pendingQuote = page.waitForRequest(request => request.url().endsWith(path + "/queries") && isBatchQuote(request)); + await composer.locator(".cw-parameter-trigger").click(); + await page.locator(".cw-count-options").getByRole("button", { name: "3", exact: true }).click(); + await composer.locator(".cw-parameter-trigger").click(); + await pendingQuote; + const run = composer.locator("button.cw-run-button"); + await run.click({trial: true}); + const initial = await run.boundingBox(); + await page.mouse.move(initial.x + initial.width / 2, initial.y + initial.height / 2); + const before = posts.length; + await page.mouse.down(); + releaseQuote(); + await composer.locator(".cw-spend-estimate summary").filter({ hasText: "1.20" }).waitFor(); + const quoted = await run.boundingBox(); + await page.mouse.up(); + const movement = Math.hypot(quoted.x - initial.x, quoted.y - initial.y); + assert.ok(movement <= 1, `Run moved by ${movement}px as the quote arrived`); + await page.unroute(quotePath); + await dialog.waitFor(); + await toggle.locator(".cw-spend-dot").waitFor(); + if (process.env.CREATION_SCREENSHOTS && await composer.isVisible()) + await composer.screenshot({path: `${process.env.CREATION_SCREENSHOTS}/spend-composer-${locale}.png`}); + const pending = await call(path); + assert.equal(pending.jobs.length, 0); + assert.equal(pending.spendCalls?.length ?? 0, 0); + assert.equal(posts.length, before); + const controls = dialog; + const canvasCard = dialog.locator(".cw-spend-card"); + await canvasCard.waitFor(); + assert.equal(await page.locator("dialog:modal").count(), 1); + assert.equal(await dialog.locator(".cw-spend-close").evaluate(el => el === document.activeElement), true); + await page.keyboard.press("Shift+Tab"); + // Native dialogs may tab into browser chrome, but never into the inert canvas. + assert.equal(await dialog.evaluate(el => document.activeElement === document.body || el.contains(document.activeElement)), true); + await page.keyboard.press("Tab"); + assert.equal(await dialog.evaluate(el => el.contains(document.activeElement)), true); + await page.keyboard.press("Escape"); + await collapsed.waitFor(); + await toggle.click(); + await closeDialog(); + await collapsed.waitFor(); + assert.equal(await toggle.evaluate(el => el === document.activeElement), true); + // Background project refreshes must not reopen a dismissed request or fill a new chat. + await page.evaluate(async pid => { + const { creationClient } = await import("/src/backend/creationClient.ts"); + await creationClient(pid).refresh(); + }, pid); + await collapsed.waitFor(); + const assistant = page.locator("#canvas-assistant"); + if (!await assistant.isVisible()) await page.locator(".cw-chat-button").click(); + await assistant.locator(".cw-assistant-welcome").waitFor(); + assert.equal(await assistant.locator(".cw-spend-card, .cw-spend-panel").count(), 0); + if (process.env.CREATION_SCREENSHOTS) await page.screenshot({path: `${process.env.CREATION_SCREENSHOTS}/spend-chat-${locale}.png`}); + assert.equal((await call(path)).spendRequests.at(-1).status, "pending"); + assert.equal(posts.length, before); + // A review can arrive while a canvas popover owns a document-level Escape handler. + await composer.locator(".cw-parameter-trigger").click(); + await page.locator(".cw-count-options").waitFor(); + await page.evaluate(pid => window.dispatchEvent(new CustomEvent("opendirector:spend-review", {detail: pid})), pid); + await canvasCard.waitFor(); + await page.keyboard.press("Escape"); + await collapsed.waitFor(); + await page.locator(".cw-count-options").waitFor(); + await composer.locator(".cw-parameter-trigger").click(); + await toggle.click(); + await canvasCard.locator(".cw-spend-confirm").click(); + await collapsed.waitFor(); + await page.locator(".cw-toast-stack").getByText(en ? "Batch submitted." : "本批任务已提交。", {exact: true}).waitFor(); + const completed = await until(() => call(path), s => s.jobs.length === 3 && s.jobs.every(j => j.status === "succeeded")); + assert.equal(completed.spendCalls.length, 3); + assert.equal(new Set(completed.jobs.map(job => job.id)).size, 3); + assert.equal(posts.length - before, 3); + assert.ok(posts.slice(before).every(post => post.prompt === "Blue" && post.n === 1)); + assert.ok(completed.spendCalls.every(c => c.state === "completed" && Number(c.calculated) === 0.4)); + // Put the next batch above the remaining cap. A background request must wait + // for model settings to close before asking for approval. + await toggle.click(); + const cap = controls.getByLabel(en ? "Project cap" : "工程上限", {exact: true}); + if (!await cap.isVisible()) await controls.getByText(en ? "Spending controls" : "费用设置", {exact:true}).click(); + await cap.fill("2"); + await controls.getByRole("button", {name: en ? "Save" : "保存", exact: true}).click(); + await until(() => call(path), s => Number(s.project.spendPolicy?.cap) === 2); + await closeDialog(); + await page.getByRole("button", {name: en ? "Settings" : "设置", exact: true}).click(); + const second = () => page.evaluate(async ({pid, itemId}) => { + const {creationClient} = await import("/src/backend/creationClient.ts"); + return creationClient(pid).submit(itemId, "if_current", undefined, undefined, 3); + }, {pid, itemId}); + assert.equal((await second()).status, "awaiting_confirmation"); + await page.locator("dialog.cw-spend-dialog:not([open])").waitFor({state: "attached"}); + assert.equal(await page.locator("dialog:modal").count(), 1); + await page.getByRole("button", {name: en ? "Close settings" : "关闭设置", exact: true}).click(); + const card = dialog.locator(".cw-spend-card"); + await card.getByText(en ? "Generate 3 images" : "生成 3 张图片", {exact: true}).waitFor(); + assert.match(await card.locator(".cw-spend-unit").innerText(), /0\.40.*review-image/); + assert.match(await card.locator(".cw-spend-amount").innerText(), /1\.20/); + assert.match(await card.locator(".cw-spend-reason").innerText(), /0\.80.*0\.40/); + const sizes = await card.evaluate(el => { + const size = selector => getComputedStyle(el.querySelector(selector)).fontSize; + return { + title: size(".cw-spend-title"), amount: size(".cw-spend-amount"), + unit: size(".cw-spend-unit"), reason: size(".cw-spend-reason"), + balance: size(".cw-spend-metric strong"), action: size(".cw-spend-confirm"), + }; + }); + assert.equal(sizes.title, sizes.amount); + assert.deepEqual([sizes.unit, sizes.reason, sizes.balance], Array(3).fill(sizes.action)); + await card.getByRole("button", {name: en ? /Spent so far/ : /已用金额/}).hover(); + const tooltip = dialog.getByRole("tooltip"); + await tooltip.waitFor(); + assert.match(await tooltip.innerText(), /3.*1\.20/); + const tip = await tooltip.boundingBox(); + assert.ok(tip.x >= 0 && tip.y >= 0 && tip.x + tip.width <= 1480 && tip.y + tip.height <= 940); + await card.locator(".cw-spend-title").hover(); + await tooltip.waitFor({state: "hidden"}); + // Queue another request while this one is open; there is still only one modal. + const third = await second(); + assert.equal(third.status, "awaiting_confirmation"); + assert.equal(await page.locator("dialog:modal").count(), 1); + await card.locator(".cw-spend-cancel").click(); + await until(() => call(path), s => s.spendRequests.at(-2).status === "cancelled"); + assert.equal(posts.length - before, 3); + const current = dialog.locator(`[data-spend-request="${third.spendRequestId}"]`); + const raise = current.getByRole("button", {name: en ? /Raise.*2\.40.*generate/i : /将上限提高到.*2\.40.*并生成/}); + await raise.waitFor(); + assert.equal(await current.getByRole("spinbutton").count(), 0); + if (process.env.CREATION_SCREENSHOTS) { + await page.screenshot({path: `${process.env.CREATION_SCREENSHOTS}/spend-review-${locale}.png`}); + await dialog.screenshot({path: `${process.env.CREATION_SCREENSHOTS}/spend-card-${locale}.png`}); + } + await page.setViewportSize({width: 360, height: 740}); + const bounds = await dialog.boundingBox(); + assert.ok(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.y >= 0 && bounds.y + bounds.height <= 740); + assert.equal(await dialog.evaluate(el => el.scrollWidth > el.clientWidth), false); + await raise.scrollIntoViewIfNeeded(); + if (process.env.CREATION_SCREENSHOTS) await page.screenshot({path: `${process.env.CREATION_SCREENSHOTS}/spend-narrow-${locale}.png`}); + await page.setViewportSize({width: 1480, height: 940}); + await raise.click(); + await collapsed.waitFor(); + assert.equal(await assistant.locator(".cw-spend-card, .cw-spend-panel").count(), 0); + const raised = await until(() => call(path), s => s.jobs.length === 6 && s.jobs.every(j => j.status === "succeeded")); + assert.equal(Number(raised.project.spendPolicy.cap), 2.4); + assert.equal(raised.spendCalls.length, 6); + assert.equal(posts.length - before, 6); + assert.deepEqual(errors, []); + console.log(locale, `Run moved ${movement}px; icon matches toolbar, automatic modal, focus, dismiss/reopen, unchanged new chat, queued review, narrow layout, USD 2.40 cap and six settled calls`); + const grouped = crypto.randomUUID(), groupPath = `/api/creation/projects/${grouped}`; + await call(groupPath + "/commands", {type: "project.create", commandId: crypto.randomUUID(), projectId: grouped, payload: {name: "Workflow " + grouped.slice(0, 8)}}); + await page.goto(`${web}/ai-tool/ai-canvas/${grouped}`); + await page.locator(".cw-spend-toggle").waitFor(); + const groupId = await page.evaluate(async ({pid, modelId}) => { + const {creationClient, objectVersion} = await import("/src/backend/creationClient.ts"); + const client = creationClient(pid), groupId = crypto.randomUUID(); + await client.command("canvas.show", {item: {id: groupId, projectId: pid, kind: "group", title: "Workflow", width: 820, height: 420, position: {x: 0, y: 0}}}); + for (const [i, prompt] of ["First panel", "Second panel"].entries()) { + const specId = crypto.randomUUID(); + const parent = client.snapshot.canvasItems.find(item => item.id === groupId); + await client.command("canvas.createGeneration", { + spec: {id: specId, projectId: pid, kind: "image", purpose: "generation", modelConfigId: modelId, prompt, parameters: {size: "1024x1024"}}, + item: {id: crypto.randomUUID(), projectId: pid, kind: "image", parentId: groupId, position: {x: 60 + i * 360, y: 80}, + binding: {role: "generation", objectRef: {id: specId}}}, + }, [objectVersion("canvas_item", parent)]); + } + return groupId; + }, {pid: grouped, modelId: model.id}); + const groupNode = page.locator(`.react-flow__node[data-id="${groupId}"]`); + await groupNode.click({position: {x: 12, y: 14}}); + await page.locator(".cw-group-estimate summary").filter({hasText: "0.80"}).click(); + assert.match(await page.locator(".cw-group-estimate summary").innerText(), en ? /Project total.*0\.80/ : /工程预计合计.*0\.80/); + assert.equal(await page.locator(".cw-group-estimate li").count(), 2); + if (process.env.CREATION_SCREENSHOTS) await page.screenshot({path: `${process.env.CREATION_SCREENSHOTS}/spend-workflow-${locale}.png`}); + assert.equal((await call(groupPath)).jobs.length, 0); + assert.equal(posts.length - before, 6); + await page.evaluate(async pid => { + const {creationClient, objectVersion} = await import("/src/backend/creationClient.ts"); + const client = creationClient(pid); + await client.command("spend.policy", {threshold: "0.60", currency: "USD"}, [objectVersion("project", client.snapshot.project)]); + }, grouped); + await page.getByRole("button", {name: en ? "Run workflow" : "运行工作流", exact: true}).click(); + const groupPending = await until(() => call(groupPath), s => s.spendRequests?.some(r => r.status === "pending")); + assert.equal(groupPending.spendRequests.at(-1).groupItems.length, 2); + assert.equal(groupPending.jobs.length, 0); + await dialog.waitFor(); + await canvasCard.locator(".cw-spend-cancel").click(); + await collapsed.waitFor(); + await until(() => call(groupPath), s => s.spendRequests.at(-1).status === "cancelled"); + assert.equal(posts.length - before, 6); + assert.deepEqual(errors, []); + console.log(locale, "two-step workflow preview USD 0.80, entire workflow cancelled with zero calls"); + if (en) { + const session = await page.evaluate(() => sessionStorage.getItem("opendirector.session.v1")); + const cli = (args, input) => new Promise((resolve, reject) => { + const child = execFile(process.env.PYTHON ?? "python", ["-m", "opendirector.cli", "--url", api, "--project", grouped, + "--session", session, ...args], {encoding: "utf8", timeout: 20000}, (error, stdout, stderr) => { + if (error) reject(new Error(stderr || stdout || error.message)); + else resolve(stdout); + }); + child.stdin.end(JSON.stringify(input)); + }).then(JSON.parse); + const saved = await call(groupPath); + const spec = saved.generationSpecs[0], item = saved.canvasItems.find(i => i.binding.objectRef?.id === spec.id); + const quote = await cli(["query", "generation.quote", "--file", "-"], {specId: spec.id, originItemId: item.id, count: 3}); + assert.equal(Number(quote.amount), 1.2); + const body = {expectedVersions: [{objectType:"canvas_item", id:item.id, revision:item.revision}, {objectType:"generation_spec", id:spec.id, revision:spec.revision}], + payload:{specId:spec.id, expectedSpecRevision:spec.revision, originItemId:item.id, count:3}}; + const args = ["--operation-id", crypto.randomUUID(), "generation", "submit", "--file", "-"]; + const waiting = await cli(args, body); + assert.equal(waiting.status, "awaiting_confirmation"); + assert.equal((await cli(args, body)).spendRequestId, waiting.spendRequestId); + assert.ok(waiting.reviewUrl.endsWith(`/ai-tool/ai-canvas/${grouped}?spendReview=${waiting.spendRequestId}`)); + // Release the editing lease before opening the CLI link in a fresh browser session. + await page.evaluate(async () => (await import("/src/backend/projects.ts")).releaseBackendProject()); + await page.goto("about:blank"); + const reviewPath = new URL(waiting.reviewUrl, web); + const reviewPage = await browser.newPage({locale: "en-US"}); + await reviewPage.goto(web + reviewPath.pathname + reviewPath.search); + const selector = `dialog.cw-spend-dialog[open] [data-spend-request="${waiting.spendRequestId}"]`; + const welcome = reviewPage.locator("dialog.cw-welcome[open]"); + await welcome.waitFor(); + assert.equal(await reviewPage.locator(selector).count(), 0, "Review waits until initial setup finishes"); + await welcome.getByRole("button", {name: "Get started", exact: true}).click(); + await welcome.getByRole("button", {name: "Set up a language model", exact: true}).click(); + await welcome.getByRole("button", {name: "review-translation Use this saved language model", exact: true}).click(); + await welcome.getByRole("checkbox", {name: "Generate an image", exact: true}).check(); + const imagePicker = welcome.getByRole("combobox", {name: "Choose a text-to-image model", exact: true}); + if (await imagePicker.count()) await imagePicker.selectOption(model.id); + await welcome.getByRole("button", {name: "Start creating", exact: true}).click(); + await welcome.waitFor({state: "hidden"}); + await reviewPage.locator(selector).getByRole("button", {name: "Cancel generation"}).click(); + await until(() => call(groupPath), s => s.spendRequests.at(-1).status === "cancelled"); + await reviewPage.close(); + assert.equal((await call(groupPath)).jobs.length, 0); + assert.equal(posts.length - before, 6); + console.log("Standalone CLI over HTTP: USD 1.20, replayed request, browser cancellation and zero calls"); + } + await page.close(); + } +} finally { + await browser.close(); + service.close(); + for (const connection of [model, translator]) { + if (connection) await call(`/api/model-configs/${connection.id}`, null, "DELETE"); + } +} diff --git a/tests/generation_helpers.py b/tests/generation_helpers.py index c028719fd..8fc0edb8c 100644 --- a/tests/generation_helpers.py +++ b/tests/generation_helpers.py @@ -10,6 +10,17 @@ from test_creation_canvas_service import media, send, ver +def policy(store, pid, **values): + return parse_command(dict(type='spend.policy', commandId=uuid4(), projectId=pid, + expectedVersions=[ver('project', store.snapshot(pid).project)], payload=values)) + + +def review(pid, request, *, project_record=None, **values): + return parse_command(dict(type='spend.review', commandId=uuid4(), projectId=pid, + expectedVersions=[*request.versions, ver('spend_request', request), *([ver('project', project_record)] if project_record else [])], + payload=dict(requestId=request.id, fingerprint=request.quote.fingerprint(), decision='approve') | values)) + + def new_project(path, name='Generation test'): projects = CreationProjects(LocalProjects(path)) pid, session = uuid4(), str(uuid4()) diff --git a/tests/spendPresentation.test.ts b/tests/spendPresentation.test.ts new file mode 100644 index 000000000..1e52542d8 --- /dev/null +++ b/tests/spendPresentation.test.ts @@ -0,0 +1,36 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import type { PriceLine, SpendQuote } from "../src/contracts/generated.ts"; +import { generationOutput, money, uniformOutputPrice } from "../src/canvas/spendPresentation.ts"; + +function quote(operations: string[], count: number, candidates?: number): SpendQuote { + const lines: PriceLine[] = operations.map(operation => ({ + operation, modelConfigId: "model", modelId: "model", source: "unknown", + sourceVersion: null, price: null, quantity: null, amount: null, + })); + return {inputFingerprint: "0".repeat(64), count, candidates, lines}; +} + +test("the requested output determines the action even when reference music uses two calls", () => { + assert.equal(generationOutput(quote(["image"], 3)), "image"); + assert.equal(generationOutput(quote(["score", "music"], 1)), "music"); + assert.equal(generationOutput(quote(["video", "video"], 1, 2)), "video"); + assert.equal(generationOutput(quote(["image", "video"], 1, 2)), "tasks"); + // A text-generation member contributes to the candidate count without a priced call. + assert.equal(generationOutput(quote(["image"], 1, 2)), "tasks"); +}); + +test("monetary labels preserve exact decimal rates and the project currency in both locales", () => { + assert.equal(money("1.2", "USD", "zh-CN"), "1.20 美元"); + assert.equal(money("2.4", "CNY", "zh-CN"), "2.40 人民币"); + assert.match(money("0.000000000000000000000001", "USD", "en-US"), /^USD\s0\.000000000000000000000001$/); + assert.match(money("999999999999.999999999999", "CNY", "en-US"), /^CNY\s999,999,999,999\.999999999999$/); +}); + +test("the unit-price shortcut preserves upper bounds and multi-call price details", () => { + const original = quote(["image"], 3); + const line: PriceLine = {...original.lines[0], amount: "0.40", price: {currency: "USD", rate: "0.40", unit: "request"}}; + assert.deepEqual(uniformOutputPrice({...original, lines: [line]}), {amount: "0.40", currency: "USD", model: "model"}); + assert.equal(uniformOutputPrice({...original, lines: [{...line, quantityBasis: "maximum"}]}), undefined); + assert.equal(uniformOutputPrice({...original, lines: [line, line]}), undefined); +}); diff --git a/tests/test_creation_parameters.py b/tests/test_creation_parameters.py index 0faeabfdd..562ffda1a 100644 --- a/tests/test_creation_parameters.py +++ b/tests/test_creation_parameters.py @@ -24,7 +24,7 @@ from opendirector.integrations.providers import GenerationProviders from test_creation_canvas_service import project, media, send, ver from test_creation_generation_service import anyio_backend -from generation_helpers import prepared +from generation_helpers import policy, prepared, review pytestmark = pytest.mark.cpu @@ -341,6 +341,16 @@ def recording(seconds=3): return subprocess.run(['ffmpeg','-v','error','-f','lavfi','-i',f'sine=frequency=330:sample_rate=48000','-t',str(seconds),'-ac','2','-threads','1','-f','mp3','pipe:1'],capture_output=True,check=True).stdout +def pcm_recording(seconds): + # PCM gives ffprobe the same exact duration on every supported platform. + import wave + buffer = BytesIO() + with wave.open(buffer, 'wb') as audio: + audio.setparams((1, 2, 8000, 0, 'NONE', 'not compressed')) + audio.writeframes(bytes(seconds * 8000 * 2)) + return buffer.getvalue() + + def follow_recording(project, target, spec_id, data, name='reference.mp3'): """Connect an imported recording to the music node, as a canvas edge does.""" store, pid, session = project @@ -367,7 +377,7 @@ def score_model(project, url='http://score.invalid/v1'): async def test_music_follows_a_reference_recording_through_its_transcribed_score(project,mode): store,pid,_=project calls=[] - reference=recording(20) + reference = pcm_recording(20) def handler(request): if request.url.path=='/v1/audio/transcriptions': assert request.url.host=='score.invalid' @@ -382,8 +392,21 @@ def handler(request): runner,target,spec_id=setup(project,'audio',parameters,handler,protocol='vllm_omni_music',model='m-a-p/YuE2-3B') score=score_model(project) try: - target,asset=follow_recording(project,target,spec_id,reference) - _,receipt=await submit(project,runner,target,spec_id) + target,asset=follow_recording(project,target,spec_id,reference,'reference.wav') + runner.configs.set_price(score['id'], dict(currency='USD', rate='0.01', unit='input_second')) + music_id = next(s.modelConfigId for s in store.snapshot(pid).generationSpecs if s.id == spec_id) + runner.configs.set_price(str(music_id), dict(currency='USD', rate='0.02', unit='requested_second')) + before = store.snapshot(pid) + quote = runner.quote(pid, spec_id, origin=target.id) + assert [(line.operation, float(line.amount)) for line in quote.lines] == [ + ('score', 0.20), ('music', 0.44 if mode == 'melody' else 1.20)] + assert float(quote.total('USD')) == (0.64 if mode == 'melody' else 1.40) + assert store.snapshot(pid) == before and calls == [] + await runner.execute(policy(store, pid, threshold='0.50'), session=project[2]) + _, waiting = await submit(project, runner, target, spec_id) + snapshot = store.snapshot(pid) + assert waiting.status == 'awaiting_confirmation' and not snapshot.jobs and not snapshot.spendCalls and calls == [] + receipt = await runner.execute(review(pid, snapshot.spendRequests[-1]), session=project[2]) assert receipt.status=='accepted',receipt await done(runner) job=store.snapshot(pid).jobs[-1] @@ -404,6 +427,71 @@ def handler(request): finally: await runner.close() +@pytest.mark.anyio +async def test_music_quote_preserves_known_subtotals_and_omits_unused_score(project): + store, pid, session = project + runner, item, spec_id = setup(project, 'audio', dict(creationType='music', durationSeconds=60), + lambda request: pytest.fail('A price query contacted the provider'), protocol='vllm_omni_music', model='m-a-p/YuE2-3B') + score = score_model(project) + music = next(s.modelConfigId for s in store.snapshot(pid).generationSpecs if s.id == spec_id) + try: + runner.configs.set_price(str(music), dict(currency='USD', rate='.02', unit='requested_second')) + solo = runner.quote(pid, spec_id, origin=item.id) + assert [line.operation for line in solo.lines] == ['music'] and float(solo.total('USD')) == 1.20 + item, _ = follow_recording(project, item, spec_id, pcm_recording(20), 'reference.wav') + free_score = runner.quote(pid, spec_id, origin=item.id) + assert free_score.lines[0].source == 'local' and free_score.lines[0].amount == 0 and float(free_score.total('USD')) == .44 + runner.configs.set_price(score['id'], dict(currency='USD', rate='.01', unit='input_second')) + runner.configs.set_price(str(music), dict(currency='CNY', rate='.02', unit='requested_second')) + mixed = runner.quote(pid, spec_id, origin=item.id) + assert mixed.total('USD') is None and {c: float(v) for c, v in mixed.subtotals().items()} == {'USD': .2, 'CNY': .44} + runner.configs.set_price(str(music), dict(currency='USD', rate='.02', unit='input_character')) + partial = runner.quote(pid, spec_id, origin=item.id) + assert partial.lines[1].amount is None and float(partial.subtotals()['USD']) == .20 and partial.total('USD') is None + await runner.execute(policy(store, pid, cap='10'), session=session) + _, waiting = await submit(project, runner, item, spec_id) + assert waiting.status == 'awaiting_confirmation' + snapshot = store.snapshot(pid) + denied = await runner.execute(review(pid, snapshot.spendRequests[-1], acceptUnknown=True), session=session) + assert denied.status == 'rejected' and not store.snapshot(pid).jobs and not store.snapshot(pid).spendCalls + finally: + await runner.close() + + +@pytest.mark.anyio +@pytest.mark.parametrize('fail_at', ['score', 'music']) +async def test_reference_music_keeps_separate_evidence_when_a_request_times_out(project, fail_at): + store, pid, session = project + requests = [] + def provider(request): + step = 'score' if request.url.path.endswith('/transcriptions') else 'music' + requests.append(step) + if step == fail_at: + raise httpx.ReadTimeout('response lost', request=request) + return httpx.Response(200, json={'text': SCORE}) + runner, item, spec_id = setup(project, 'audio', dict(creationType='music'), provider, + protocol='vllm_omni_music', model='m-a-p/YuE2-3B') + score = score_model(project) + try: + item, _ = follow_recording(project, item, spec_id, recording()) + music = next(s.modelConfigId for s in store.snapshot(pid).generationSpecs if s.id == spec_id) + for config_id, rate in ((score['id'], '.20'), (music, '.44')): + runner.configs.set_price(str(config_id), dict(unit='request', rate=rate, currency='USD')) + await runner.execute(policy(store, pid, threshold='.50'), session=session) + await submit(project, runner, item, spec_id) + waiting = store.snapshot(pid).spendRequests[-1] + assert not requests + await runner.execute(review(pid, waiting), session=session) + await done(runner) + assert requests == (['score'] if fail_at == 'score' else ['score', 'music']) + calls = store.snapshot(pid).spendCalls + assert [c.state for c in calls] == (['submitted', 'released'] if fail_at == 'score' else ['completed', 'submitted']) + if fail_at == 'music': + assert str(calls[0].calculated) == '0.20' and calls[1].calculated is None + finally: + await runner.close() + + @pytest.mark.anyio async def test_reference_music_requires_a_transcription_model_and_a_model_that_follows_scores(project): calls=[] diff --git a/tests/test_localization.py b/tests/test_localization.py index e96c4c824..462a37240 100644 --- a/tests/test_localization.py +++ b/tests/test_localization.py @@ -16,6 +16,18 @@ def request(language: str): return SimpleNamespace(headers={"accept-language": language}) +@pytest.mark.parametrize('code, chinese, english, status', [ + ('spend_human_review', '请在工程窗口中确认费用。', 'Review spending in the project window.', 403), + ('spend_reviewed', '该费用请求已经处理,请查看工程费用记录。', 'This spending request has already been reviewed. Check project spending history.', 409), + ('spend_cancelled', '该费用请求已取消,请重新发起任务。', 'This spending request was cancelled. Start a new task.', 409), + ('selection_preview_started', '选区预览已经启动,请先查看工程费用记录再重试。', 'The selection preview has already started. Check project spending history before retrying.', 409), + ('spend_call_submitted', '该工具的模型调用已经提交,请查看工程费用记录。', 'This tool model call has already been submitted. Check project spending history.', 409), +]) +def test_spend_errors_preserve_specific_recovery_guidance(code, chinese, english, status): + assert localized_error(request('zh-CN'), chinese=chinese, status=status, code=code) == chinese + assert localized_error(request('en-US'), chinese=chinese, status=status, code=code) == english + + def test_capability_messages_preserve_the_specific_input_failure(): cases = [ ('capability_unavailable', '该模型不支持文字回复。', 'This model does not support text replies.'), diff --git a/tests/test_minimax_speech.py b/tests/test_minimax_speech.py index b2b0ccc82..1e7e78446 100644 --- a/tests/test_minimax_speech.py +++ b/tests/test_minimax_speech.py @@ -383,11 +383,12 @@ def handle(request): async def test_failed_download_recovers_after_model_removal_without_resubmitting(context, mp3, monkeypatch, configuration_change): project, configs, saved = context store, pid, session = project + configs.set_price(saved['id'], dict(unit='input_character', rate='0.01', currency='USD')) calls, healthy = [], False def handle(request): calls.append(request) if request.url.path == '/v1/get_voice': return httpx.Response(200, json=VOICES) - if request.method == 'POST': return httpx.Response(200, json=SUCCESS) + if request.method == 'POST': return httpx.Response(200, json={**SUCCESS, 'extra_info': {'usage_characters': 7}}) assert str(request.url) == RESULT and 'authorization' not in request.headers if not healthy: raise httpx.ReadTimeout('download outage', request=request) return httpx.Response(200, content=mp3) @@ -395,6 +396,8 @@ def handle(request): try: first._launch(*prepared(first, project, saved, prompt='Read this', parameters=selection(saved))) await settled(first) + [usage] = store.snapshot(pid).spendCalls + assert usage.usage == 7 and usage.usageSource == 'provider' and str(usage.calculated) == '0.07' [failed] = store.snapshot(pid).jobs assert failed.recovery == 'download' and failed.resumeAllowed assert not store.snapshot(pid).assets @@ -415,6 +418,7 @@ def handle(request): await settled(restarted) snapshot = reopened.snapshot(pid) assert snapshot.jobs[0].id == failed.id and snapshot.jobs[0].status == 'succeeded' + assert len(snapshot.spendCalls) == 1 and snapshot.spendCalls[0].calculated == usage.calculated assert len(snapshot.assets) == len(snapshot.results) == 1 assert sum(call.url.path == '/v1/t2a_v2' for call in calls) == 1 finally: diff --git a/tests/test_spend_admission.py b/tests/test_spend_admission.py new file mode 100644 index 000000000..6f8cfffad --- /dev/null +++ b/tests/test_spend_admission.py @@ -0,0 +1,230 @@ +import asyncio +import base64 +import shutil +from decimal import Decimal +from uuid import uuid4 + +import httpx +import pytest + +from generation_helpers import cancel, command, policy, review +from opendirector.application.creation_generation import CreationGeneration +from opendirector.application.creation_spend import review_status +from opendirector.domain.creation.commands import parse_command +from opendirector.domain.projects import ProjectError +from opendirector.infrastructure.creation_projects import CreationProjects +from opendirector.infrastructure.local_projects import LocalProjects +from opendirector.infrastructure.model_configs import ModelConfigs +from opendirector.integrations.providers import GenerationProviders +from test_creation_canvas_service import project, send, ver +from test_creation_generation_service import anyio_backend +from test_creation_parameters import done, png + +pytestmark = pytest.mark.cpu + + +@pytest.mark.anyio +@pytest.mark.parametrize('cancel_queued', [False, True]) +async def test_restart_retains_queued_budget_until_execution_or_cancellation(project, cancel_queued): + store, pid, session = project + configs = ModelConfigs(store.local.repository) + model = configs.save('image', 'http://fixture.invalid/v1', 'fixture', '', connection_type='self_hosted', auth_mode='none') + configs.set_price(model['id'], dict(rate='0.40', unit='request', currency='USD')) + runner = CreationGeneration(store, configs) + entered, hold = asyncio.Event(), asyncio.Event() + calls = [] + async def provider(request): + calls.append(request.url.path) + if len(calls) == 2: + entered.set() + await hold.wait() + return httpx.Response(200, json={'data': [dict(b64_json=base64.b64encode(png((1024,1024))).decode())]}) + runner.provider = GenerationProviders(runner.store, transport=httpx.MockTransport(provider)) + restarted = None + try: + await runner.execute(policy(store, pid, cap='1.20'), session=session) + draft = command(project, model, parameters=dict(size='1024x1024')) + batch = draft.model_copy(update={'payload': draft.payload.model_copy(update={'count': 3})}) + receipt = await runner.execute(batch, session=session) + assert receipt.status == 'accepted' + async with asyncio.timeout(10): + await entered.wait() + queued = next(j for j in store.snapshot(pid).jobs if j.phase == 'queued') + await runner.close() + reopened = CreationProjects(LocalProjects(store.local.repository)) + snapshot = reopened.snapshot(pid) + assert [c.state for c in snapshot.spendCalls].count('reserved') == 1 + assert review_status(snapshot)['held'] == Decimal('1.20') + assert review_status(snapshot)['available'] == 0 + restarted = CreationGeneration(reopened, configs) + restarted.provider = GenerationProviders(restarted.store, transport=httpx.MockTransport(provider)) + if cancel_queued: + await cancel(restarted, pid, str(queued.id), session) + await restarted.recover(str(pid), str(queued.id), explicit=True) + hold.set() + await restarted.start() + await done(restarted) + final = reopened.snapshot(pid) + status = review_status(final) + assert len(calls) == (2 if cancel_queued else 3) + assert len(final.jobs) == len(final.spendCalls) == 3 + assert status['held'] == Decimal('0.80') # Submitted calls still require provider reconciliation. + assert status['settled'] == (0 if cancel_queued else Decimal('0.40')) + assert status['available'] == (Decimal('0.40') if cancel_queued else 0) + call = next(c for c in final.spendCalls if c.ownerId == queued.id) + assert call.state == ('released' if cancel_queued else 'completed') + if not cancel_queued: + extra = command((reopened, pid, session), model) + assert (await restarted.execute(extra, session=session)).status == 'awaiting_confirmation' + assert len(calls) == 3 + finally: + hold.set() + await runner.close() + if restarted: + await restarted.close() + + +@pytest.mark.anyio +async def test_threshold_equality_unknown_cancellation_and_price_changes(project): + store, pid, session = project + configs = ModelConfigs(store.local.repository) + model = configs.save('image', 'https://example.invalid/v1', 'fixture', 'key', protocol='openai') + runner = CreationGeneration(store, configs) + # This test observes durable admission only. Never dispatch to a model. + async def no_dispatch(*args, **kwargs): + pass + runner.recover = no_dispatch + try: + await runner.execute(policy(store, pid, threshold='0.40'), session=session) + draft = command(project, model) + assert (await runner.execute(draft, session=session)).status == 'awaiting_confirmation' + request = store.snapshot(pid).spendRequests[-1] + assert (await runner.execute(review(pid, request), session=session)).status == 'rejected' + assert (await runner.execute(review(pid, request, decision='cancel'), session=session)).status == 'applied' + with pytest.raises(ProjectError) as repeated_review: + await runner.execute(review(pid, request), session=session) + assert repeated_review.value.code == 'spend_reviewed' + assert not store.snapshot(pid).jobs and not store.snapshot(pid).spendCalls + fresh = draft.model_copy(update={'commandId': uuid4()}) + await runner.execute(fresh, session=session) + unknown = store.snapshot(pid).spendRequests[-1] + await runner.execute(policy(store, pid, cap='1'), session=session) + assert (await runner.execute(review(pid, unknown, acceptUnknown=True), session=session)).status == 'rejected' + configs.set_price(model['id'], dict(unit='request', currency='USD', rate='0.40')) + stale = await runner.execute(review(pid, unknown), session=session) + assert stale.issues[0].code == 'spend_quote_changed' + await runner.execute(policy(store, pid, threshold='0.40'), session=session) + assert (await runner.execute(draft.model_copy(update={'commandId': uuid4()}), session=session)).status == 'accepted' + finally: + await runner.close() + + +@pytest.mark.anyio +async def test_changed_review_inputs_require_a_new_quote_but_still_allow_cancellation(project): + store, pid, session = project + configs = ModelConfigs(store.local.repository) + model = configs.save('image', 'http://fixture.invalid/v1', 'fixture', '', connection_type='self_hosted', auth_mode='none') + configs.set_price(model['id'], dict(rate='0.40', unit='request', currency='USD')) + runner = CreationGeneration(store, configs) + try: + await runner.execute(policy(store, pid, cap='0'), session=session) + first, second = command(project, model), command(project, model) + for draft in (first, second): + assert (await runner.execute(draft, session=session)).status == 'awaiting_confirmation' + before = store.snapshot(pid) + item = next(i for i in before.canvasItems if i.id == first.payload.originItemId) + missing = before.model_copy(update={'canvasItems': tuple(i for i in before.canvasItems if i.id != item.id)}) + assert [p['reason'] for p in review_status(missing)['pending']] == ['stale_inputs', 'over_cap'] + edit = send(store, pid, 'canvas.update', session=session, versions=[ver('canvas_item', item)], + itemId=item.id, title='Revised shot') + assert edit.status == 'applied' + entries = review_status(store.snapshot(pid))['pending'] + assert [p['reason'] for p in entries] == ['stale_inputs', 'over_cap'] + assert entries[0]['suggestedCap'] is None and entries[1]['suggestedCap'] == Decimal('0.40') + await runner.execute(policy(store, pid, currency='CNY', cap='0'), session=session) + assert [p['reason'] for p in review_status(store.snapshot(pid))['pending']] == ['stale', 'stale'] + await runner.execute(policy(store, pid, currency='USD', cap='0'), session=session) + request = entries[0]['request'] + cancel = parse_command(dict(type='spend.review', commandId=uuid4(), projectId=pid, + expectedVersions=[ver('spend_request', request)], + payload=dict(requestId=request.id, fingerprint=entries[0]['fingerprint'], decision='cancel'))) + assert (await runner.execute(cancel, session=session)).status == 'applied' + final = store.snapshot(pid) + assert [r.status for r in final.spendRequests] == ['cancelled', 'pending'] + assert not final.jobs and not final.spendCalls + finally: + await runner.close() + + +@pytest.mark.anyio +async def test_atomic_batch_approval_race_replay_and_cap_raise(project, tmp_path): + store, pid, session = project + configs = ModelConfigs(store.local.repository) + model = configs.save('image', 'http://fixture.invalid/v1', 'fixture', '', connection_type='self_hosted', auth_mode='none') + configs.set_price(model['id'], dict(rate='0.40', unit='request', currency='USD')) + runner = CreationGeneration(store, configs) + calls = [] + gate = asyncio.Event() + async def provider(request): + calls.append(request.url.path) + await gate.wait() + return httpx.Response(200, json={'data': [dict(b64_json=base64.b64encode(png((1024,1024))).decode())]}) + runner.provider = GenerationProviders(runner.store, transport=httpx.MockTransport(provider)) + try: + await runner.execute(policy(store, pid, cap='2', threshold='1'), session=session) + for _ in range(2): + draft = command(project, model, parameters=dict(size='1024x1024')) + batch = draft.model_copy(update={'payload': draft.payload.model_copy(update={'count': 3})}) + waiting = await runner.execute(batch, session=session) + assert waiting.status == 'awaiting_confirmation' and not waiting.jobIds + snap = store.snapshot(pid) + assert not snap.jobs and not snap.spendCalls and not calls + member = batch.model_copy(update={'commandId': uuid4(), 'payload': batch.payload.model_copy(update={'count': 1, 'batchId': batch.commandId})}) + assert (await runner.execute(member, session=session)).status == 'rejected' + assert not calls and not store.snapshot(pid).jobs + first, second = [review(pid, request) for request in snap.spendRequests] + answers = await asyncio.gather(*(runner.execute(r, session=session) for r in (first, second))) + assert sorted(r.status for r in answers) == ['accepted', 'rejected'], [r.issues for r in answers] + winner = next(r for r in answers if r.status == 'accepted') + repeated = await runner.execute(first if first.commandId == winner.commandId else second, session=session) + assert repeated.jobIds == winner.jobIds and len(set(repeated.jobIds)) == 3 + status = review_status(store.snapshot(pid)) + assert status['held'] == Decimal('1.20') and status['available'] == Decimal('0.80') + assert len(status['pending']) == 1 and status['pending'][0]['shortfall'] == Decimal('0.40') + assert status['pending'][0]['suggestedCap'] == Decimal('2.40') + assert 'settledBatch' not in status + request = status['pending'][0]['request'] + too_low = await runner.execute(review(pid, request, project_record=store.snapshot(pid).project, newCap='2.1'), session=session) + assert too_low.status == 'rejected' and store.snapshot(pid).project.spendPolicy.cap == 2 + raised = review(pid, request, project_record=store.snapshot(pid).project, newCap=status['pending'][0]['suggestedCap']) + accepted = await runner.execute(raised, session=session) + assert accepted.status == 'accepted' and len(accepted.jobIds) == 3 + assert (await runner.execute(raised, session=session)).jobIds == accepted.jobIds + assert (await runner.execute(batch, session=session)) == waiting + gate.set() + await done(runner) + reopened = CreationProjects(LocalProjects(store.local.repository)).snapshot(pid) + assert len(calls) == len(reopened.jobs) == len(reopened.spendCalls) == 6 + assert reopened.project.spendPolicy.cap == Decimal('2.4') + assert review_status(reopened)['held'] == 0 + assert review_status(reopened)['settled'] == Decimal('2.40') + assert 'settledBatch' not in review_status(reopened) + item = reopened.canvasItems[0] + changed = send(store, pid, 'canvas.update', session=session, versions=[ver('canvas_item', item)], + itemId=item.id, title='Archive check') + assert changed.status == 'applied' + item = next(i for i in store.snapshot(pid).canvasItems if i.id == item.id) + assert send(store, pid, 'history.undo', session=session, versions=[ver('canvas_item', item)], + targetCommandId=changed.commandId).status == 'applied' + assert store.snapshot(pid).spendCalls == reopened.spendCalls + # A complete project backup retains its identity and historical amounts. + archive = CreationProjects(LocalProjects(tmp_path / 'restored')) + original_dir = runner.directory(pid) + archive.root.mkdir(parents=True, exist_ok=True) + shutil.copytree(original_dir, archive.root / original_dir.name) + assert archive.snapshot(pid).spendCalls == reopened.spendCalls + shutil.copytree(original_dir, archive.root / (original_dir.name + ' copy')) + assert not archive.list_projects()['projects'] + finally: + gate.set() + await runner.close() diff --git a/tests/test_spend_cli.py b/tests/test_spend_cli.py new file mode 100644 index 000000000..15fd4d6f2 --- /dev/null +++ b/tests/test_spend_cli.py @@ -0,0 +1,52 @@ +import json +from decimal import Decimal +from uuid import uuid4 + +import httpx +import pytest +from fastapi.testclient import TestClient +from typer.testing import CliRunner + +from generation_helpers import command, new_project, policy +from opendirector import cli +from opendirector.application.creation_spend import save_policy +from opendirector.infrastructure.model_configs import ModelConfigs +from opendirector_api.main import create_app + +pytestmark = pytest.mark.cpu + + +def test_standalone_cli_quotes_submits_and_returns_the_local_review_link(tmp_path, monkeypatch): + store, pid, session = project = new_project(tmp_path) + configs = ModelConfigs(tmp_path) + model = configs.save('image', 'http://fixture.invalid/v1', 'fixture', '', connection_type='self_hosted', auth_mode='none') + configs.set_price(model['id'], dict(unit='request', rate='.40', currency='USD')) + draft = command(project, model, parameters={'size': '1024x1024'}) + controls = policy(store, pid, threshold='1') + store.commit(controls, lambda before: save_policy(before, controls.payload), session=session) + api = TestClient(create_app(store.local)) + original = httpx.Client + def forward(request): + response = api.request(request.method, request.url.path, headers=dict(request.headers), content=request.read()) + return httpx.Response(response.status_code, json=response.json()) + monkeypatch.setattr(cli.httpx, 'Client', lambda **kwargs: original(**kwargs, transport=httpx.MockTransport(forward))) + monkeypatch.delenv('OPENDIRECTOR_AGENT_SOCKET', raising=False) + monkeypatch.delenv('OPENDIRECTOR_AGENT_HOST', raising=False) + def invoke(args, stdin=None): + result = CliRunner().invoke(cli.app, ['--url', 'http://localhost:18188', '--project', str(pid), '--session', session, *args], + input=json.dumps(stdin) if stdin else None) + assert result.exit_code == 0, (result.output, result.exception) + return json.loads(result.output) + quote = invoke(['query', 'generation.quote', '--file', '-'], {'specId':str(draft.payload.specId), 'count':3}) + assert Decimal(quote['amount']) == Decimal('1.20') + body = {'expectedVersions':[v.model_dump(mode='json') for v in draft.expectedVersions], + 'payload':{**draft.payload.model_dump(mode='json'), 'count':3}} + args = ['--operation-id', str(uuid4()), 'generation', 'submit', '--file', '-'] + waiting = invoke(args, body) + assert waiting == invoke(args, body) + assert waiting['reviewUrl'] == f'http://localhost:18188/ai-tool/ai-canvas/{pid}?spendReview={waiting["spendRequestId"]}' + status = invoke(['query', 'spend.status']) + assert len(status['pending']) == 1 and Decimal(status['held']) == 0 and not store.snapshot(pid).jobs + denied = api.post(f'/api/creation/projects/{pid}/commands', headers={'X-OpenDirector-Request':'1', 'X-OpenDirector-Session':session}, + json=controls.model_copy(update={'commandId': uuid4()}).model_dump(mode='json')) + assert denied.status_code == 403 diff --git a/tests/test_spend_prices.py b/tests/test_spend_prices.py new file mode 100644 index 000000000..ac80a089a --- /dev/null +++ b/tests/test_spend_prices.py @@ -0,0 +1,102 @@ +from datetime import datetime, timezone +from decimal import Decimal +from uuid import uuid4 + +import pytest + +from opendirector.application.creation_spend import quote_view, review_status +from opendirector.domain.creation.project import Project, ProjectSnapshot +from opendirector.domain.creation.spend import OFFICIAL_URL, SpendCall, SpendObservation, SpendPolicy, SpendQuote, cap_adjustment, observed_call, price_line, spend_decision + +pytestmark = pytest.mark.cpu + + +def test_connection_price_takes_precedence_and_an_alias_is_unpriced(): + config = dict(id=uuid4(), connectionType='api', url=OFFICIAL_URL, protocol='openai', modelId='glm-image') + assert price_line(config, 'image', {}).amount == Decimal('0.10') + mirror = dict(config, url='https://proxy.invalid/v1') + assert price_line(mirror, 'image', {}).amount is None + custom = dict(mirror, price=dict(unit='request', rate='0.40', currency='USD')) + quote = SpendQuote(count=3, inputFingerprint='0' * 64, lines=[price_line(custom, 'image', {})]) + assert quote.total('USD') == Decimal('1.20') + assert quote.total('CNY') is None + assert price_line(dict(custom, connectionType='self_hosted'), 'image', {}).amount == Decimal('0.40') + assert price_line(dict(mirror, connectionType='self_hosted'), 'image', {}).amount == 0 + + +def test_fractional_recording_cost_preserves_a_valid_subcent_rate(): + config = dict(id=uuid4(), modelId='score', price=dict(unit='input_second', rate='0.000000000001', currency='USD')) + assert price_line(config, 'score', {'input_second': Decimal('3.001')}).amount == Decimal('0.000000000003001') + + +def test_suggested_limit_rounds_up_only_if_the_policy_requires_it(): + assert cap_adjustment(Decimal('2.00'), Decimal('0.80'), Decimal('1.20')) == (Decimal('0.40'), Decimal('2.40')) + assert cap_adjustment(Decimal(0), Decimal(0), Decimal('3.001e-12'))[1] == Decimal('4e-12') + assert cap_adjustment(Decimal(0), Decimal('-10000'), Decimal('1e-24')) == ( + Decimal('10000.000000000000000000000001'), Decimal('10000.000000000001')) + largest = SpendPolicy(cap='999999999999.999999999999').cap + assert cap_adjustment(largest - Decimal('1e-12'), Decimal(0), Decimal('1e-24'))[1] == largest + assert cap_adjustment(largest, Decimal(0), Decimal('1e-24'))[1] is None + assert cap_adjustment(Decimal(0), Decimal(0), Decimal('1e28'))[1] is None + + +@pytest.mark.parametrize('state,field', [('completed', 'settled'), ('reserved', 'held')]) +def test_preflight_and_review_retain_tiny_charges_in_the_existing_balance(state, field): + project = Project(id=uuid4(), name='Budget', spendPolicy=SpendPolicy(cap='10000')) + config = dict(id=uuid4(), modelId='music', price=dict(unit='output_second', rate='1e-12', currency='USD')) + tiny = price_line(config, 'music', {'output_second': '1e-12'}) + large = price_line(dict(config, price=dict(unit='request', rate='10000', currency='USD')), 'image', {}) + batch = SpendQuote(count=3, inputFingerprint='0' * 64, lines=[large, tiny]) + assert batch.total('USD') == Decimal('30000.000000000000000000000003') + assert batch.subtotals() == {'USD': batch.total('USD')} + at = datetime.now(timezone.utc) + calls = [SpendCall(id=uuid4(), projectId=project.id, ownerId=uuid4(), line=line, state=state, + calculated=line.amount if state == 'completed' else None, createdAt=at) for line in (large, tiny)] + next_batch = SpendQuote(count=1, inputFingerprint='1' * 64, lines=[price_line(config, 'music', {'output_second': 1})]) + snapshot = ProjectSnapshot(project=project, spendCalls=calls, spendRequests=[ + dict(id=uuid4(), projectId=project.id, quote=next_batch, versions=[], createdAt=at)]) + summary = review_status(snapshot) + assert summary[field] == Decimal('10000.000000000000000000000001') + assert summary['available'] == Decimal('-1e-24') + assert quote_view(snapshot, next_batch)['projectAfter'] == Decimal('10000.000000000001000000000001') + pending = summary['pending'][0] + assert pending['shortfall'] == Decimal('1.000000000001e-12') + assert pending['suggestedCap'] == Decimal('10000.000000000002') + raised = snapshot.model_copy(update={'project': project.model_copy(update={'spendPolicy': SpendPolicy(cap=pending['suggestedCap'])})}) + assert quote_view(raised, next_batch)['reason'] == 'ready' + + +def test_estimate_and_confirmed_usage_agree_on_a_full_precision_product(): + value = Decimal('999999999999.999999999999') + expected = Decimal('999999999999999999999998.000000000000000000000001') + config = dict(id=uuid4(), modelId='music', price=dict(unit='output_second', rate=value, currency='USD')) + line = price_line(config, 'music', {'output_second': value}) + assert line.amount == expected + call = SpendCall(id=uuid4(), projectId=uuid4(), ownerId=uuid4(), createdAt=datetime.now(timezone.utc), line=line) + actual = SpendObservation(callId=call.id, state='completed', unit='output_second', usage=value) + assert observed_call(call, actual).calculated == expected + + +def test_missing_metered_quantity_is_unknown_even_with_a_price(): + config = dict(id=uuid4(), modelId='speech', price=dict(unit='output_second', rate='0.01', currency='USD')) + assert price_line(config, 'speech', {}).amount is None + + +def test_prior_unpriced_calls_explain_why_a_known_charge_cannot_use_the_cap(): + model = dict(id=uuid4(), modelId='image', price=dict(unit='request', rate='.4', currency='USD')) + batch = SpendQuote(count=1, inputFingerprint='0' * 64, lines=[price_line(model, 'image', {})]) + assert spend_decision(dict(policy=SpendPolicy(cap='4'), unknown=1, available=Decimal(4)), batch) == 'prior_unknown' + + +def test_output_usage_and_late_provider_charge_replace_only_the_same_call(): + model = dict(id=uuid4(), modelId='music', price=dict(unit='output_second', rate='0.02', currency='USD')) + call = SpendCall(id=uuid4(), projectId=uuid4(), ownerId=uuid4(), createdAt=datetime.now(timezone.utc), + line=price_line(model, 'music', {'output_second': 22})) + def observation(**facts): + return SpendObservation(callId=call.id, state='completed', **facts) + measured = observed_call(call, observation(unit='output_second', usage=18, evidence='media')) + assert measured.line.amount == Decimal('0.44') and measured.calculated == Decimal('0.36') + reported = observation(unit='output_second', usage=18, evidence='provider', reported='0.35') + corrected = observed_call(measured, reported) + assert corrected.usageSource == 'provider' and corrected.accounted() == Decimal('0.35') + assert observed_call(corrected, reported) == observed_call(corrected, observation(unit='output_second', usage=19, evidence='media')) == corrected diff --git a/tests/test_spend_workflows.py b/tests/test_spend_workflows.py new file mode 100644 index 000000000..92f3420c8 --- /dev/null +++ b/tests/test_spend_workflows.py @@ -0,0 +1,273 @@ +import asyncio +import base64 +import json +from decimal import Decimal +from uuid import UUID, uuid4 + +import httpx +import pytest + +from generation_helpers import command, policy, review +from opendirector.agent.tools import AgentTools, tools as agent_tool_schemas +from opendirector.application.creation_canvas import CreationCanvas +from opendirector.application.creation_generation import CreationGeneration +from opendirector.application.creation_spend import review_status +from opendirector.application.creation_tool_assets import CreationToolAssets +from opendirector.application.tool_spend import tool_quote +from opendirector.application.tool_tasks import ToolTasks +from opendirector.domain.creation.commands import GroupQuoteQuery, SpendStatusQuery, parse_command +from opendirector.domain.projects import ProjectError +from opendirector.infrastructure.model_configs import ModelConfigs +from opendirector.integrations.providers import GenerationProviders +from test_creation_canvas_service import project, send, ver +from test_creation_generation_service import anyio_backend +from test_creation_parameters import done, png +from test_tool_tasks import CHAT, SAM3, ZIMAGE, configure, images_server, segmentation_server, upload + +pytestmark = pytest.mark.cpu + + +@pytest.mark.anyio +@pytest.mark.parametrize('dependent', [True, False]) +async def test_workflow_prices_the_whole_ready_set_and_keeps_completed_upstream(project, dependent): + store, pid, session = project + configs = ModelConfigs(store.local.repository) + config = configs.save('image', 'http://fixture.invalid/v1', 'fixture', '', connection_type='self_hosted', auth_mode='none') + configs.set_price(config['id'], dict(unit='request', rate='0.40', currency='USD')) + runner = CreationGeneration(store, configs) + posts = [] + def provider(request): + posts.append(request) + return httpx.Response(200, json={'data': [{'b64_json': base64.b64encode(png((1024, 1024))).decode()}]}) + runner.provider = GenerationProviders(runner.store, transport=httpx.MockTransport(provider)) + try: + await runner.execute(policy(store, pid, cap='2', threshold='0.60'), session=session) + first, second = [command(project, config, prompt=p, parameters={'size': '1024x1024'}) for p in ('first', 'second')] + a, b = first.payload, second.payload + if dependent: + configs.set_price(config['id'], dict(unit='request', rate='0', currency='USD')) + await runner.execute(first, session=session) + await done(runner) + posts.clear() + configs.set_price(config['id'], dict(unit='request', rate='0.40', currency='USD')) + before = store.snapshot(pid) + added = send(store, pid, 'reference.add', session=session, versions=[ + ver('generation_spec', next(s for s in before.generationSpecs if s.id == b.specId)), + ver('canvas_item', next(i for i in before.canvasItems if i.id == b.originItemId))], + reference=dict(id=uuid4(), projectId=pid, targetSpecId=b.specId, binding='follow_current', + source=dict(id=a.originItemId), role='reference')) + assert added.status == 'applied', added + before = store.snapshot(pid) + group = parse_command(dict(type='generation.group', projectId=pid, commandId=uuid4(), + expectedVersions=[ver('generation_spec', s) for s in before.generationSpecs] + [ver('canvas_item', i) for i in before.canvasItems], + payload=dict(members=[dict(itemId=a.originItemId, specId=a.specId), + dict(itemId=b.originItemId, specId=b.specId, after=[a.originItemId] if dependent else [])]))) + query = GroupQuoteQuery(type='generation.groupQuote', queryId=uuid4(), projectId=pid, workflow=group.payload) + preview = await CreationCanvas(store, runner).query(query) + assert float(preview['amount']) == (.40 if dependent else .80) + assert preview['quote'].get('deferred', []) == ([str(b.originItemId)] if dependent else []) + assert not posts and store.snapshot(pid) == before + response = await runner.execute(group, session=session) + assert response.status == 'awaiting_confirmation' and not posts and store.snapshot(pid).jobs == before.jobs, response + waiting = store.snapshot(pid).spendRequests[-1] + assert review_status(store.snapshot(pid))['workflows'][0]['state'] == 'waiting' + assert waiting.quote.total('USD') == (Decimal('.4') if dependent else Decimal('.8')) + assert preview['fingerprint'] == waiting.quote.fingerprint() + item = next(i for i in before.canvasItems if i.id == b.originItemId) + spec = next(s for s in before.generationSpecs if s.id == b.specId) + separate = parse_command(dict(type='generation.submit', commandId=uuid4(), projectId=pid, + expectedVersions=[ver('generation_spec', spec), ver('canvas_item', item)], + payload=dict(specId=spec.id, expectedSpecRevision=spec.revision, originItemId=item.id))) + blocked = await runner.execute(separate, session=session) + assert blocked.issues[0].code == 'spend_quote_changed' and not posts + accepted = await runner.execute(review(pid, waiting), session=session) + assert len(accepted.jobIds) == (1 if dependent else 2), accepted + await done(runner) + await asyncio.gather(*list(runner.group_workers.values())) + if dependent: + before = store.snapshot(pid) + assert len(posts) == 1 and before.jobs[-1].adopted + downstream = before.spendRequests[-1] + assert downstream.groupItems == (b.originItemId,) and downstream.status == 'pending' + await runner.close() + runner = CreationGeneration(store, configs) + runner.provider = GenerationProviders(runner.store, transport=httpx.MockTransport(provider)) + await runner.start() + approved = await runner.execute(review(pid, downstream), session=session) + assert len(approved.jobIds) == 1, approved + await done(runner) + assert posts[1].url.path.endswith('/edits') + final = store.snapshot(pid) + members = [j for j in final.jobs if j.batchId == group.commandId] + status = review_status(final)['workflows'] + assert len(status) == 1 and status[0]['completed'] == 2 and status[0]['state'] == 'completed' + assert len(posts) == len(members) == len([c for c in final.spendCalls if c.ownerId in {j.id for j in members}]) == 2 + assert review_status(final)['settled'] == Decimal('.80') + finally: + await runner.close() + + +@pytest.mark.anyio +async def test_no_budget_runs_independent_group_members_even_when_other_members_form_a_cycle(project): + store, pid, session = project + configs = ModelConfigs(store.local.repository) + config = configs.save('image', 'http://fixture.invalid/v1', 'fixture', '', connection_type='self_hosted', auth_mode='none') + posts = [] + runner = CreationGeneration(store, configs) + def provider(request): + posts.append(request) + return httpx.Response(200, json={'data': [{'b64_json': base64.b64encode(png((1024,1024))).decode()}]}) + runner.provider = GenerationProviders(runner.store, transport=httpx.MockTransport(provider)) + try: + items = [command(project, config, parameters={'size': '1024x1024'}).payload for _ in range(3)] + snapshot = store.snapshot(pid) + deps = [[], [items[2].originItemId], [items[1].originItemId]] + plan = parse_command(dict(type='generation.group', commandId=uuid4(), projectId=pid, + expectedVersions=[ver('generation_spec', s) for s in snapshot.generationSpecs] + [ver('canvas_item', i) for i in snapshot.canvasItems], + payload=dict(members=[dict(specId=m.specId, itemId=m.originItemId, after=after) for m, after in zip(items, deps)]))) + reply = await runner.execute(plan, session=session) + assert len(reply.jobIds) == 1, reply + await done(runner) + run = review_status(store.snapshot(pid))['workflows'][0] + assert len(posts) == run['completed'] == 1 and run['skipped'] == 2 and run['state'] == 'incomplete' + finally: + await runner.close() + + +def test_agent_can_discover_the_complete_workflow_quote_schema(): + query = next(t['function']['parameters'] for t in agent_tool_schemas() if t['function']['name'] == 'query') + group = query['$defs']['GroupQuoteQuery'] + assert 'workflow' in group['required'] + assert 'projectId' not in group['properties'] and 'queryId' not in group['properties'] + assert set(query['$defs']['GroupMember']['required']) == {'itemId', 'specId'} + + +@pytest.mark.anyio +async def test_agent_receives_price_and_human_approval_resumes_its_original_action(project): + store, pid, session = project + configs = ModelConfigs(store.local.repository) + model = configs.save('image', 'http://fixture.invalid/v1', 'fixture', '', connection_type='self_hosted', auth_mode='none') + configs.set_price(model['id'], dict(unit='request', rate='0.40', currency='USD')) + runner = CreationGeneration(store, configs) + async def no_dispatch(*args, **kwargs): + pass + runner.recover = no_dispatch + agent, turn = AgentTools(store, runner, configs), uuid4() + await runner.execute(policy(store, pid, threshold='1'), session=session) + spec = command(project, model, parameters={'size': '1024x1024'}) + args = dict(type='generation.submit', payload={**spec.payload.model_dump(mode='json'), 'count': 3}, + expectedVersions=[v.model_dump(mode='json') for v in spec.expectedVersions]) + async def tool(name, values, key): + return await agent.execute(pid, turn, session, key, name, values, [], None) + quote = await tool('query', dict(type='generation.quote', specId=str(spec.payload.specId), count=3), 'quote') + pending = await tool('execute_command', args, 'generate') + assert Decimal(quote['amount']) == Decimal(pending['spend']['review']['amount']) == Decimal('1.20') + decision = review(pid, store.snapshot(pid).spendRequests[-1]) + with pytest.raises(ProjectError): + await tool('execute_command', dict(type='spend.review', payload=decision.payload.model_dump(mode='json')), 'approve') + assert not store.snapshot(pid).jobs + allowed = await runner.execute(decision, session=session) + assert len(allowed.jobIds) == 3 + assert all(j.agentRunId == turn and j.agentCallId == 'generate' for j in store.snapshot(pid).jobs) + assert Decimal((await tool('query', {'type':'spend.status'}, 'status'))['held']) == Decimal('1.20') + await runner.close() + + +def test_a_translation_request_does_not_receive_the_tool_source_video(): + data = dict(unit='input_second', rate='.02', currency='USD') + def priced(name): + return dict(id=str(uuid4()), modelId=name, price=data) + asset = str(uuid4()) + task = dict(id=str(uuid4()), tool='video-matting', sourceAssetIds=[asset], parameters={'prompt': '帆船'}, + modelSnapshots={'video.matting': priced('tracking'), 'text.chat': priced('translation')}) + quote = tool_quote(task, {asset: dict(fingerprint='0' * 64, durationMs=20000)}) + assert [(line.operation, line.amount) for line in quote.lines] == [('video.matting', Decimal('.40')), ('text.chat', None)] + assert quote.total('USD') is None + + +@pytest.mark.anyio +async def test_selection_review_reuses_masks_and_accounts_physical_calls(project): + store, pid, session = project + configs = configure(store, SAM3, CHAT) + for model in configs.list(): + rate = '.03' if model['kind'] == 'agent' else '.40' + configs.set_price(model['id'], dict(unit='request', rate=rate, currency='USD')) + asset = upload(store, str(pid), session, 'source.png', png()) + requests, translations = [], [] + segment = segmentation_server(requests, {'person': [(.9, (0, 0, 12, 16))]}) + + def provider(request): + if request.url.path == '/v1/chat/completions': + translations.append(json.loads(request.content)['messages'][-1]['content']) + return httpx.Response(200, json={'choices': [{'message': {'content': 'guitar'}}]}) + return segment(request) + + service = ToolTasks(store.local, configs, CreationToolAssets(store), projects=store, + transport=httpx.MockTransport(provider)) + runner = CreationGeneration(store, configs) + runner.tools = service + try: + await runner.execute(policy(store, pid, threshold='.50'), session=session) + value = dict(id=str(uuid4()), sourceAssetId=asset, prompt='person, 吉他') + answer = await service.selection_preview(str(pid), value, session) + assert answer['status'] == 'awaiting_confirmation' and not requests and not translations + assert not store.snapshot(pid).spendCalls + waiting = store.snapshot(pid).spendRequests[-1] + assert waiting.quote.total('USD') == Decimal('.83') + await runner.execute(review(pid, waiting), session=session) + result = await service.selection_preview(str(pid), value, session) + assert result['instances'] and requests == ['person', 'guitar'] and not service.list(str(pid)) + assert len(translations) == 1 and '吉他' in translations[0] + calls = store.snapshot(pid).spendCalls + assert [(call.line.operation, call.calculated) for call in calls] == [ + ('image.segment', Decimal('.40')), ('image.segment', Decimal('.40')), ('text.chat', Decimal('.03'))] + assert review_status(store.snapshot(pid))['settled'] == Decimal('.83') + finally: + await service.close() + await runner.close() + + +@pytest.mark.anyio +async def test_four_edit_calls_survive_a_crash_between_admission_and_task_publication(project, monkeypatch): + store, pid, session = project + configs = configure(store, ZIMAGE) + configs.set_price(configs.list()[0]['id'], dict(unit='request', rate='.40', currency='USD')) + source = upload(store, str(pid), session, 'source.png', png()) + posts = [] + make = lambda: ToolTasks(store.local, configs, CreationToolAssets(store), projects=store, transport=httpx.MockTransport(images_server(posts))) + old, runner = make(), CreationGeneration(store, configs) + runner.tools = old + value = dict(id=str(uuid4()), tool='image-presets', sourceAssetIds=[source], parameters={'preset':'storyboard'}) + try: + await runner.execute(policy(store, pid, threshold='1'), session=session) + before = store.snapshot(pid) + assert old.quote(str(pid), value, session)['amount'] == Decimal('1.60') + assert store.snapshot(pid) == before and not old.list(str(pid)) + waiting = await old.submit(str(pid), value, session) + assert waiting['status'] == 'awaiting_confirmation' and not posts and not store.snapshot(pid).spendCalls + def interrupted(*args): + raise OSError('injected worker interruption') + monkeypatch.setattr(old, '_write', interrupted) + decision = review(pid, store.snapshot(pid).spendRequests[-1]) + with pytest.raises(OSError, match='interruption'): + await runner.execute(decision, session=session) + assert review_status(store.snapshot(pid))['held'] == Decimal('1.60') and not old.list(str(pid)) and not posts + finally: + await old.close() + await runner.close() + restored = make() + try: + await restored.start() + await asyncio.gather(*list(restored.jobs.values())) + task = restored.get(str(pid), value['id']) + assert len(task['outputs']) == len(posts) == len(task['modelCalls']) == 4 + assert {c['spendCallId'] for c in task['modelCalls']} == {str(c.id) for c in store.snapshot(pid).spendCalls} + assert review_status(store.snapshot(pid))['settled'] == Decimal('1.60') + # A task written by an older release can have provider call records without a paid rate. + legacy = dict(task, id=str(uuid4()), modelCalls=[{'id': 'old-physical-call'}]) + restored._write(restored._directory(str(pid)), legacy) + runner.tools = restored + status = await CreationCanvas(store, runner).query(SpendStatusQuery(type='spend.status', queryId=uuid4(), projectId=pid)) + assert status['legacy'] == 1 and Decimal(status['settled']) == Decimal('1.60') + finally: + await restored.close() diff --git a/tests/test_tool_tasks.py b/tests/test_tool_tasks.py index 404e6e8e6..1e89eb14a 100644 --- a/tests/test_tool_tasks.py +++ b/tests/test_tool_tasks.py @@ -359,6 +359,7 @@ def handle(request): if request.method == 'POST': body = request.read() assert b'fl2va' in body and b'name="input_reference"' in body + assert b'name="num_frames"\r\n\r\n124\r\n' in body and b'name="fps"\r\n\r\n24\r\n' in body return httpx.Response(200, json={'id': 'video_1', 'status': 'queued'}) if request.method == 'DELETE': return httpx.Response(200, json={'id': 'video_1', 'status': 'cancelled'}) @@ -371,12 +372,16 @@ def handle(request): def test_dynamic_poster_runs_first_frame_video_and_cancel_reaches_the_service(project): store, project_id, session = project configs = configure(store, H3) + configs.set_price(configs.list()[0]['id'], dict(unit='output_second', rate='.02', currency='USD')) source = upload(store, project_id, session, 'poster.png', png((64, 36))) log = [] task = run(store, configs, httpx.MockTransport(video_server(log)), project_id, session, {'tool': 'dynamic-poster', 'sourceAssetIds': [source], 'parameters': {'prompt': '霓虹闪烁'}}) assert task['status'] == 'succeeded', task['error'] assert task['outputs'][0]['kind'] == 'video' and ('GET', '/v1/videos/video_1/content') in log + call = store.snapshot(project_id).spendCalls[0] + assert float(call.line.quantity) == pytest.approx(124 / 24) and call.line.quantityBasis == 'maximum' + assert call.usageSource == 'media' and float(call.usage) == 1 and float(call.calculated) == .02 async def cancel(): log.clear()