From b55054ea317f040398a0396c739305f8464e29cd Mon Sep 17 00:00:00 2001 From: bread-lxy <2022200058@ruc.edu.cn> Date: Sun, 22 Nov 2026 10:58:44 +0800 Subject: [PATCH 01/15] [feat] Quote fixed media inputs and complete candidate batches --- apps/api/src/opendirector_api/creation.py | 2 +- apps/api/src/opendirector_api/main.py | 6 + apps/api/src/opendirector_api/models.py | 2 + packages/core/src/opendirector/agent/tools.py | 2 +- .../application/creation_canvas.py | 8 +- .../application/creation_generation.py | 215 +++++--- .../opendirector/domain/creation/commands.py | 11 +- .../opendirector/domain/creation/models.py | 2 + .../src/opendirector/domain/creation/spend.py | 79 +++ .../infrastructure/model_configs.py | 30 +- scripts/generate_contracts.py | 2 +- src/contracts/creation.schema.json | 522 +++++++++++++++++- src/contracts/generated.ts | 68 ++- tests/test_creation_parameters.py | 19 +- tests/test_spend_prices.py | 22 + 15 files changed, 901 insertions(+), 89 deletions(-) create mode 100644 packages/core/src/opendirector/domain/creation/spend.py create mode 100644 tests/test_spend_prices.py diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index c1de28496..3d3f6d354 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) diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index 724b1806a..d705ecd14 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, @@ -285,6 +287,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)) diff --git a/apps/api/src/opendirector_api/models.py b/apps/api/src/opendirector_api/models.py index e74d6338e..9e64a2ee2 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' diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index 82468bc1f..4439bf871 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -352,7 +352,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) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 99bfcbfcb..077a34886 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,11 @@ 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 == '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) + return dict(quote=quote.model_dump(mode='json'), fingerprint=quote.fingerprint()) 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_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 52b12bc1d..a7c8ca660 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 @@ -18,6 +19,8 @@ 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 +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 +29,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 @@ -324,6 +327,125 @@ async def _run(self, task, pinned, config, mode='submit'): remote.release() claim.release() + + 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 = {} + 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 params.get('duration') is not None: + quantities.update(requested_second=params['duration'], output_second=params['duration']) + lines.append(price_line(config, operation, quantities)) + 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 prepare(self, command, *, session=None, source='ui', agent_origin=None): replay = self.projects.replay(command) if replay is not None: @@ -351,82 +473,23 @@ 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 + checks = voice_spec, voice_config, voice_failure, capability_identity, capability_failure 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')) + 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.') + 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')) return ProjectSnapshot.model_validate(data) return self.projects.commit(command, accept, session=session, source=source) diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index e79902c46..cf11c8e21 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -210,6 +210,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.') @@ -461,6 +463,13 @@ class QueryBase(Contract): projectId: UUID = Field(description='Owning project ID.') +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 ProjectQuery(QueryBase): type: Literal['project.get'] = Field(description='Read the current project.') @@ -501,7 +510,7 @@ class AssetPreviewQuery(QueryBase): objectId: UUID = Field(description='Asset ID.') -Query = Annotated[ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | +Query = Annotated[GenerationQuoteQuery | ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | AssetPreviewQuery, Field(discriminator='type')] diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index e0aef2457..0db6ec0d4 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/spend.py b/packages/core/src/opendirector/domain/creation/spend.py new file mode 100644 index 000000000..de4813e00 --- /dev/null +++ b/packages/core/src/opendirector/domain/creation/spend.py @@ -0,0 +1,79 @@ +"""Service prices are decimal amounts in their original currency.""" +from decimal import Decimal +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import Field + +from .base import Contract, Digest, digest + +Currency = Literal['USD', 'CNY'] +Money = Annotated[Decimal, Field(ge=0, max_digits=24, decimal_places=12, allow_inf_nan=False)] +Unit = Literal['request', 'input_character', 'input_second', 'requested_second', 'output_second'] + + +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.') + source: Literal['connection', 'official', 'local', 'unknown'] = Field(description='Origin of the 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.') + quantity: Money | None = Field(default=None, description='Billing units or bounded maximum for one candidate.') + amount: Money | None = Field(default=None, description='Estimated amount for this step of one candidate.') + + +class SpendQuote(Contract): + 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 + return sum((line.amount for line in self.lines), Decimal(0)) * self.count + + def fingerprint(self): + return digest(self) + + +# 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#2026-11-22' +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 price_line(config, operation, quantities): + """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', OFFICIAL_SOURCE + 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 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'], + source=source, sourceVersion=version, price=price, quantity=units, amount=amount) 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/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/contracts/creation.schema.json b/src/contracts/creation.schema.json index cd5f01137..3298950f3 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -3738,6 +3738,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": { @@ -4233,6 +4279,7 @@ "asset.usage": "#/$defs/AssetUsageQuery", "canvas.status": "#/$defs/CanvasStatusQuery", "canvas.versions": "#/$defs/VersionsQuery", + "generation.quote": "#/$defs/GenerationQuoteQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", "object.get": "#/$defs/ObjectQuery", @@ -4241,6 +4288,9 @@ "propertyName": "type" }, "oneOf": [ + { + "$ref": "#/$defs/GenerationQuoteQuery" + }, { "$ref": "#/$defs/ProjectQuery" }, @@ -5628,6 +5678,65 @@ "title": "GenerationFailure", "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": { @@ -5759,6 +5868,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", @@ -8657,7 +8774,6 @@ }, "ModelConfigPublic": { "additionalProperties": false, - "description": "Application-level, never embedded in an editable project's credential data.", "properties": { "kind": { "description": "Business object or media type.", @@ -8775,6 +8891,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", @@ -9880,6 +10008,105 @@ "title": "Point", "type": "object" }, + "PriceLine": { + "additionalProperties": false, + "properties": { + "operation": { + "description": "Model operation being priced.", + "title": "Operation", + "type": "string" + }, + "modelConfigId": { + "description": "Selected model connection.", + "format": "uuid", + "title": "Modelconfigid", + "type": "string" + }, + "modelId": { + "description": "Provider model receiving the request.", + "title": "Modelid", + "type": "string" + }, + "source": { + "description": "Origin of the price.", + "enum": [ + "connection", + "official", + "local", + "unknown" + ], + "title": "Source", + "type": "string" + }, + "sourceVersion": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Price revision or dated official source.", + "title": "Sourceversion" + }, + "price": { + "anyOf": [ + { + "$ref": "#/$defs/ConnectionPrice" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Native unit price, when known." + }, + "quantity": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Billing units or bounded maximum for one candidate.", + "title": "Quantity" + }, + "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": [ + "operation", + "modelConfigId", + "modelId", + "source" + ], + "title": "PriceLine", + "type": "object" + }, "Project": { "additionalProperties": false, "properties": { @@ -11879,6 +12106,39 @@ "title": "SpecWrite", "type": "object" }, + "SpendQuote": { + "additionalProperties": false, + "properties": { + "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" + }, "StackCanvasItem": { "additionalProperties": false, "properties": { @@ -15821,6 +16081,7 @@ "asset.usage": "#/$defs/AssetUsageQuery", "canvas.status": "#/$defs/CanvasStatusQuery", "canvas.versions": "#/$defs/VersionsQuery", + "generation.quote": "#/$defs/GenerationQuoteQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", "object.get": "#/$defs/ObjectQuery", @@ -15829,6 +16090,9 @@ "propertyName": "type" }, "oneOf": [ + { + "$ref": "#/$defs/GenerationQuoteQuery" + }, { "$ref": "#/$defs/ProjectQuery" }, @@ -19830,6 +20094,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": { @@ -20327,6 +20629,7 @@ "asset.usage": "#/$defs/AssetUsageQuery", "canvas.status": "#/$defs/CanvasStatusQuery", "canvas.versions": "#/$defs/VersionsQuery", + "generation.quote": "#/$defs/GenerationQuoteQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", "object.get": "#/$defs/ObjectQuery", @@ -20335,6 +20638,9 @@ "propertyName": "type" }, "oneOf": [ + { + "$ref": "#/$defs/GenerationQuoteQuery" + }, { "$ref": "#/$defs/ProjectQuery" }, @@ -21778,6 +22084,67 @@ "title": "GenerationFailure", "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": { @@ -21916,6 +22283,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", @@ -24956,7 +25331,6 @@ }, "ModelConfigPublic": { "additionalProperties": false, - "description": "Application-level, never embedded in an editable project's credential data.", "properties": { "kind": { "description": "Business object or media type.", @@ -25074,6 +25448,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", @@ -26199,6 +26585,101 @@ "title": "Point", "type": "object" }, + "PriceLine": { + "additionalProperties": false, + "properties": { + "operation": { + "description": "Model operation being priced.", + "title": "Operation", + "type": "string" + }, + "modelConfigId": { + "description": "Selected model connection.", + "format": "uuid", + "title": "Modelconfigid", + "type": "string" + }, + "modelId": { + "description": "Provider model receiving the request.", + "title": "Modelid", + "type": "string" + }, + "source": { + "description": "Origin of the price.", + "enum": [ + "connection", + "official", + "local", + "unknown" + ], + "title": "Source", + "type": "string" + }, + "sourceVersion": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Price revision or dated official source.", + "title": "Sourceversion" + }, + "price": { + "anyOf": [ + { + "$ref": "#/$defs/ConnectionPrice" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Native unit price, when known." + }, + "quantity": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Billing units or bounded maximum for one candidate.", + "title": "Quantity" + }, + "amount": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Estimated amount for this step of one candidate.", + "title": "Amount" + } + }, + "required": [ + "operation", + "modelConfigId", + "modelId", + "source", + "sourceVersion", + "price", + "quantity", + "amount" + ], + "title": "PriceLine", + "type": "object" + }, "Project": { "additionalProperties": false, "properties": { @@ -28254,6 +28735,39 @@ "title": "SpecWrite", "type": "object" }, + "SpendQuote": { + "additionalProperties": false, + "properties": { + "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" + }, "StackCanvasItem": { "additionalProperties": false, "properties": { @@ -32373,6 +32887,7 @@ "asset.usage": "#/$defs/AssetUsageQuery", "canvas.status": "#/$defs/CanvasStatusQuery", "canvas.versions": "#/$defs/VersionsQuery", + "generation.quote": "#/$defs/GenerationQuoteQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", "object.get": "#/$defs/ObjectQuery", @@ -32381,6 +32896,9 @@ "propertyName": "type" }, "oneOf": [ + { + "$ref": "#/$defs/GenerationQuoteQuery" + }, { "$ref": "#/$defs/ProjectQuery" }, diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index b50ffd4b4..e4207edb1 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -413,6 +413,12 @@ export interface CommandReceiptInput extends ContractInput { 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"; } @@ -435,7 +441,7 @@ export interface CreationContractsInput extends ContractInput { 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 receipt: CommandReceiptInput; - readonly query: ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | AssetPreviewQueryInput; + readonly query: GenerationQuoteQueryInput | ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | AssetPreviewQueryInput; readonly event: ProjectEventInput; readonly job: JobInput; readonly result: ResultVersionInput; @@ -569,6 +575,13 @@ export interface GenerationFailureInput { readonly providerStatus?: "failed" | "cancelled" | "expired" | null; } +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 +596,7 @@ export interface GenerationSpecRefInput extends ContractInput { } export interface GenerationSubmitInput extends ContractInput { + readonly count?: number; readonly specId: string; readonly expectedSpecRevision: number; readonly originItemId?: string | null; @@ -865,6 +879,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; @@ -992,6 +1007,17 @@ export interface PointInput extends ContractInput { readonly y?: number; } +export interface PriceLineInput extends ContractInput { + readonly operation: string; + readonly modelConfigId: string; + readonly modelId: string; + readonly source: "connection" | "official" | "local" | "unknown"; + readonly sourceVersion?: string | null; + readonly price?: ConnectionPriceInput | null; + readonly quantity?: number | string | null; + readonly amount?: number | string | null; +} + export interface ProjectInput extends ContractInput { readonly id: string; readonly revision?: number; @@ -1238,6 +1264,12 @@ export interface SpecWriteInput extends ContractInput { readonly spec: TextGenerationSpecInput | ImageGenerationSpecInput | VideoGenerationSpecInput | AudioGenerationSpecInput; } +export interface SpendQuoteInput extends ContractInput { + readonly count: number; + readonly inputFingerprint: string; + readonly lines: ReadonlyArray; +} + export interface StackCanvasItemInput extends EditorCanvasItemInput { readonly kind: "stack"; } @@ -2062,6 +2094,12 @@ export interface CommandReceipt extends Contract { 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"; } @@ -2084,7 +2122,7 @@ export interface CreationContracts extends Contract { 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 receipt: CommandReceipt; - readonly query: ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | AssetPreviewQuery; + readonly query: GenerationQuoteQuery | ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | AssetPreviewQuery; readonly event: ProjectEvent; readonly job: Job; readonly result: ResultVersion; @@ -2218,6 +2256,13 @@ export interface GenerationFailure { readonly providerStatus?: "failed" | "cancelled" | "expired" | null; } +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 +2277,7 @@ export interface GenerationSpecRef extends Contract { } export interface GenerationSubmit extends Contract { + readonly count?: number; readonly specId: string; readonly expectedSpecRevision: number; readonly originItemId: string | null; @@ -2514,6 +2560,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; @@ -2640,6 +2687,17 @@ export interface Point extends Contract { readonly y: number; } +export interface PriceLine extends Contract { + readonly operation: string; + readonly modelConfigId: string; + readonly modelId: string; + readonly source: "connection" | "official" | "local" | "unknown"; + readonly sourceVersion: string | null; + readonly price: ConnectionPrice | null; + readonly quantity: string | null; + readonly amount: string | null; +} + export interface Project extends Contract { readonly id: string; readonly revision: number; @@ -2886,6 +2944,12 @@ export interface SpecWrite extends Contract { readonly spec: TextGenerationSpec | ImageGenerationSpec | VideoGenerationSpec | AudioGenerationSpec; } +export interface SpendQuote extends Contract { + readonly count: number; + readonly inputFingerprint: string; + readonly lines: ReadonlyArray; +} + export interface StackCanvasItem extends EditorCanvasItem { readonly kind: "stack"; } diff --git a/tests/test_creation_parameters.py b/tests/test_creation_parameters.py index bc4be6da8..9b992df65 100644 --- a/tests/test_creation_parameters.py +++ b/tests/test_creation_parameters.py @@ -364,7 +364,13 @@ 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) + # PCM has an exact measured duration across ffprobe versions; MP3 has encoder padding. + reference = BytesIO() + import wave + with wave.open(reference, 'wb') as audio: + audio.setparams((1, 2, 8000, 0, 'NONE', 'not compressed')) + audio.writeframes(bytes(20 * 8000 * 2)) + reference = reference.getvalue() def handler(request): if request.url.path=='/v1/audio/transcriptions': assert request.url.host=='score.invalid' @@ -379,7 +385,16 @@ 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) + 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 == [] _,receipt=await submit(project,runner,target,spec_id) assert receipt.status=='accepted',receipt await done(runner) diff --git a/tests/test_spend_prices.py b/tests/test_spend_prices.py new file mode 100644 index 000000000..dcd37bb1e --- /dev/null +++ b/tests/test_spend_prices.py @@ -0,0 +1,22 @@ +from decimal import Decimal +from uuid import uuid4 + +from opendirector.domain.creation.spend import OFFICIAL_URL, SpendQuote, price_line + + +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_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 From f9ab71f46076b6c2ab7062137a64562684f016af Mon Sep 17 00:00:00 2001 From: bread-lxy <2022200058@ruc.edu.cn> Date: Sun, 22 Nov 2026 11:03:45 +0800 Subject: [PATCH 02/15] [feat] Admit reviewed batches and project reservations atomically --- apps/api/src/opendirector_api/creation.py | 4 +- packages/core/src/opendirector/agent/tools.py | 2 +- .../application/creation_canvas.py | 3 + .../application/creation_commands.py | 2 +- .../application/creation_generation.py | 48 +- .../application/creation_spend.py | 72 + .../src/opendirector/domain/creation/base.py | 2 +- .../opendirector/domain/creation/commands.py | 16 +- .../src/opendirector/domain/creation/index.py | 3 +- .../opendirector/domain/creation/project.py | 6 +- .../src/opendirector/domain/creation/spend.py | 78 +- .../domain/creation/validation.py | 3 +- .../infrastructure/creation_publication.py | 6 +- .../infrastructure/creation_records.py | 2 +- src/contracts/creation.schema.json | 2033 +++++++++++++---- src/contracts/generated.ts | 128 +- tests/test_spend_admission.py | 112 + 17 files changed, 2014 insertions(+), 506 deletions(-) create mode 100644 packages/core/src/opendirector/application/creation_spend.py create mode 100644 tests/test_spend_admission.py diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index 3d3f6d354..19d884bc9 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -138,7 +138,9 @@ async def execute(project_id: UUID, value: Command, request: Request, x_opendire 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', '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/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index 4439bf871..efc38e9c3 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -28,7 +28,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.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]) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 077a34886..cfadd7bab 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -843,6 +843,9 @@ 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 + return to_jsonable_python(await asyncio.to_thread(lambda: review_status(self.projects.snapshot(query.projectId)))) if query.type == 'generation.quote': if self.generation is None: raise ProjectError('Generation service unavailable.', 503) 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 a7c8ca660..fed335b36 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -14,6 +14,7 @@ from filelock import FileLock, Timeout +from opendirector.application import 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 @@ -446,8 +447,8 @@ def quote(self, project_id, spec_id, count=1, origin=None): _, job, config, task, records = self._propose_job(before, command) return self._quote_job(job, config, task, records, count) - def prepare(self, command, *, session=None, source='ui', agent_origin=None): - replay = self.projects.replay(command) + 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 # Voice registries are remote services. Probe outside the catalog/file @@ -475,9 +476,18 @@ def prepare(self, command, *, session=None, source='ui', agent_origin=None): voice_failure = error checks = voice_spec, voice_config, voice_failure, capability_identity, capability_failure def accept(before): + if review is not None: + validate_command(command, before) 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 + calls = list(before.spendCalls) for index in range(command.payload.count): candidate = job if index: @@ -490,12 +500,40 @@ def accept(before): 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) - return self.projects.commit(command, accept, session=session, source=source) + 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('Review spending in the project window.', 403) + 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('Review spending in the project window.', 403) + 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('This request has already been reviewed.', 409) + 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 == '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 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..fe55959e6 --- /dev/null +++ b/packages/core/src/opendirector/application/creation_spend.py @@ -0,0 +1,72 @@ +"""Project-scoped admission. All callers invoke these decisions under the project commit lock.""" +from datetime import datetime, timezone +from uuid import uuid5 + +from opendirector.domain.creation.spend import SpendCall, SpendPolicy, SpendRequest, spend_decision, spend_summary +from opendirector.domain.creation.validation import ContractError + + +def review_status(snapshot): + summary = spend_summary(snapshot) + policy = summary['policy'] + pending = [] + for request in snapshot.spendRequests: + if request.status != 'pending': + continue + total = request.quote.total(policy.currency) + reason = spend_decision(summary, request.quote) + pending.append(dict(request=request, fingerprint=request.quote.fingerprint(), reason=reason, amount=total, + shortfall=total-summary['available'] if reason == 'over_cap' else None)) + return dict(**summary, projectRevision=snapshot.project.revision, pending=pending) + + +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 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, + 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.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 == '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 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/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 cf11c8e21..addf0b66b 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 SpendPolicy, SpendReview from .editors import EditorDocument from opendirector.domain.rule_facts import PROMPT_MAX_LENGTH from .generation import GenerationSpec, Job, PromptPart, Reference @@ -291,7 +292,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]] @@ -358,6 +359,8 @@ 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.'), + ('SpendPolicyCommand', 'spend.policy', SpendPolicy, 'Set project service spending controls.'), + ('SpendReviewCommand', 'spend.review', SpendReview, 'Record a human decision on a fixed request.'), ('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.'), @@ -409,7 +412,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', @@ -440,7 +443,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.') @@ -470,6 +474,10 @@ class GenerationQuoteQuery(QueryBase): count: int = Field(default=1, strict=True, ge=1, le=8, description='Requested candidates.') +class SpendStatusQuery(QueryBase): + 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.') @@ -510,7 +518,7 @@ class AssetPreviewQuery(QueryBase): objectId: UUID = Field(description='Asset ID.') -Query = Annotated[GenerationQuoteQuery | ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | +Query = Annotated[SpendStatusQuery | GenerationQuoteQuery | 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/project.py b/packages/core/src/opendirector/domain/creation/project.py index 95294f240..ff3c6d961 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 index de4813e00..cfde53f7e 100644 --- a/packages/core/src/opendirector/domain/creation/spend.py +++ b/packages/core/src/opendirector/domain/creation/spend.py @@ -1,11 +1,12 @@ """Service prices are decimal amounts in their original currency.""" +from datetime import datetime from decimal import Decimal from typing import Annotated, Literal from uuid import UUID from pydantic import Field -from .base import Contract, Digest, digest +from .base import Contract, Digest, ObjectVersion, ProjectEntity, digest Currency = Literal['USD', 'CNY'] Money = Annotated[Decimal, Field(ge=0, max_digits=24, decimal_places=12, allow_inf_nan=False)] @@ -43,6 +44,81 @@ 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 SpendRequest(ProjectEntity): + 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.') + calculated: Money | 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.') + + +def spend_summary(snapshot): + policy = snapshot.project.spendPolicy or SpendPolicy() + settled, held = Decimal(0), Decimal(0) + missing = 0 + owners = set() + for call in snapshot.spendCalls: + owners.add(call.ownerId) + amount = call.accounted() + if amount is None or (amount and call.line.price.currency != policy.currency): + missing += 1 + elif call.state == 'completed' and (call.calculated is not None or call.reported is not None): + settled += amount + else: + held += amount + legacy = sum(j.execution.kind != 'text' and j.id not in owners for j in snapshot.jobs) + return dict(policy=policy, settled=settled, held=held, available=None if policy.cap is None else policy.cap-settled-held, + unknown=missing, legacy=legacy, since=min((c.createdAt for c in snapshot.spendCalls), default=None)) + + +def spend_decision(summary, quote): + policy = summary['policy'] + amount = quote.total(policy.currency) + if amount == 0: + return '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 amount > summary['available']: + return 'over_cap' + if policy.threshold is not None and amount > policy.threshold: + return 'confirmation' + return 'ready' + + # 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' 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..e93a0059d 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'), 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/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 3298950f3..87fcc393a 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -3681,11 +3681,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.", @@ -3829,6 +3844,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", @@ -4138,6 +4156,8 @@ "reference.restore": "#/$defs/ReferenceRestoreCommand", "reference.update": "#/$defs/ReferenceUpdateCommand", "result.select": "#/$defs/ResultSelectCommand", + "spend.policy": "#/$defs/SpendPolicyCommand", + "spend.review": "#/$defs/SpendReviewCommand", "timeline.publishRender": "#/$defs/TimelinePublishRenderCommand" }, "propertyName": "type" @@ -4233,6 +4253,12 @@ { "$ref": "#/$defs/ReferenceRemoveCommand" }, + { + "$ref": "#/$defs/SpendPolicyCommand" + }, + { + "$ref": "#/$defs/SpendReviewCommand" + }, { "$ref": "#/$defs/GenerationSubmitCommand" }, @@ -4283,11 +4309,15 @@ "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" }, @@ -9637,7 +9667,9 @@ "canvas_item", "editor_document", "job", - "result" + "result", + "spend_request", + "spend_call" ], "title": "Objecttype", "type": "string" @@ -10110,6 +10142,18 @@ "Project": { "additionalProperties": false, "properties": { + "spendPolicy": { + "anyOf": [ + { + "$ref": "#/$defs/SpendPolicy" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional service spend controls." + }, "id": { "description": "Stable object ID.", "format": "uuid", @@ -10731,6 +10775,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.", @@ -12106,40 +12168,7 @@ "title": "SpecWrite", "type": "object" }, - "SpendQuote": { - "additionalProperties": false, - "properties": { - "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" - }, - "StackCanvasItem": { + "SpendCall": { "additionalProperties": false, "properties": { "id": { @@ -12161,53 +12190,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" }, { @@ -12215,19 +12232,16 @@ } ], "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": { + "calculated": { "anyOf": [ { - "format": "uuid", + "minimum": 0.0, + "type": "number" + }, + { "type": "string" }, { @@ -12235,66 +12249,96 @@ } ], "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" + "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": { + "SpendPolicy": { "additionalProperties": false, "properties": { - "nodeIds": { - "default": [], - "description": "Ordered member canvas item IDs.", - "items": { - "format": "uuid", - "type": "string" - }, - "title": "Nodeids", - "type": "array" + "currency": { + "default": "USD", + "description": "Currency of the project spending limits.", + "enum": [ + "USD", + "CNY" + ], + "title": "Currency", + "type": "string" }, - "activeIndex": { - "default": 0, - "description": "Index of the active member.", - "minimum": 0, - "title": "Activeindex", - "type": "integer" + "threshold": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Require confirmation strictly above this batch amount.", + "title": "Threshold" + }, + "cap": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Maximum settled and reserved service spend.", + "title": "Cap" } }, - "title": "StackData", + "title": "SpendPolicy", "type": "object" }, - "StackDocument": { + "SpendPolicyCommand": { "additionalProperties": false, + "description": "Set project service spending controls.", "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": { @@ -12303,32 +12347,520 @@ "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.policy", + "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.", + "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", + "payload" + ], + "title": "SpendPolicyCommand", + "type": "object" + }, + "SpendQuote": { + "additionalProperties": false, + "properties": { + "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" + }, + "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", + "versions", + "quote", + "createdAt" + ], + "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": [ + { + "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": [ + "requestId", + "fingerprint", + "decision" + ], + "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": [ + "commandId", + "projectId", + "type", + "payload" + ], + "title": "SpendReviewCommand", + "type": "object" + }, + "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" + }, + "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": { + "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": "stack", + "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": "StackCanvasItem", + "type": "object" + }, + "StackData": { + "additionalProperties": false, + "properties": { + "nodeIds": { + "default": [], + "description": "Ordered member canvas item IDs.", + "items": { + "format": "uuid", + "type": "string" + }, + "title": "Nodeids", + "type": "array" + }, + "activeIndex": { + "default": 0, + "description": "Index of the active member.", + "minimum": 0, + "title": "Activeindex", + "type": "integer" + } + }, + "title": "StackData", + "type": "object" + }, + "StackDocument": { + "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": "stack", + "description": "Business object or media type.", "title": "Kind", "type": "string" }, @@ -15940,6 +16472,8 @@ "reference.restore": "#/$defs/ReferenceRestoreCommand", "reference.update": "#/$defs/ReferenceUpdateCommand", "result.select": "#/$defs/ResultSelectCommand", + "spend.policy": "#/$defs/SpendPolicyCommand", + "spend.review": "#/$defs/SpendReviewCommand", "timeline.publishRender": "#/$defs/TimelinePublishRenderCommand" }, "propertyName": "type" @@ -16035,6 +16569,12 @@ { "$ref": "#/$defs/ReferenceRemoveCommand" }, + { + "$ref": "#/$defs/SpendPolicyCommand" + }, + { + "$ref": "#/$defs/SpendReviewCommand" + }, { "$ref": "#/$defs/GenerationSubmitCommand" }, @@ -16085,11 +16625,15 @@ "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" }, @@ -20033,11 +20577,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.", @@ -20177,6 +20736,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", @@ -20488,6 +21050,8 @@ "reference.restore": "#/$defs/ReferenceRestoreCommand", "reference.update": "#/$defs/ReferenceUpdateCommand", "result.select": "#/$defs/ResultSelectCommand", + "spend.policy": "#/$defs/SpendPolicyCommand", + "spend.review": "#/$defs/SpendReviewCommand", "timeline.publishRender": "#/$defs/TimelinePublishRenderCommand" }, "propertyName": "type" @@ -20583,6 +21147,12 @@ { "$ref": "#/$defs/ReferenceRemoveCommand" }, + { + "$ref": "#/$defs/SpendPolicyCommand" + }, + { + "$ref": "#/$defs/SpendReviewCommand" + }, { "$ref": "#/$defs/GenerationSubmitCommand" }, @@ -20633,11 +21203,15 @@ "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" }, @@ -26199,7 +26773,9 @@ "canvas_item", "editor_document", "job", - "result" + "result", + "spend_request", + "spend_call" ], "title": "Objecttype", "type": "string" @@ -26683,6 +27259,18 @@ "Project": { "additionalProperties": false, "properties": { + "spendPolicy": { + "anyOf": [ + { + "$ref": "#/$defs/SpendPolicy" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional service spend controls." + }, "id": { "description": "Stable object ID.", "format": "uuid", @@ -27316,6 +27904,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.", @@ -28077,57 +28683,315 @@ "title": "Status", "type": "string" }, - "facts": { - "additionalProperties": true, - "description": "Observed technical validation facts.", - "title": "Facts", - "type": "object" + "facts": { + "additionalProperties": true, + "description": "Observed technical validation facts.", + "title": "Facts", + "type": "object" + }, + "message": { + "description": "Human-readable issue description.", + "title": "Message", + "type": "string" + }, + "humanReviewRequired": { + "default": true, + "description": "Whether creative quality still requires human review.", + "title": "Humanreviewrequired", + "type": "boolean" + } + }, + "required": [ + "status", + "message" + ], + "title": "ResultCheck", + "type": "object" + }, + "ResultSelect": { + "additionalProperties": false, + "properties": { + "specId": { + "description": "Generation configuration ID.", + "format": "uuid", + "title": "Specid", + "type": "string" + }, + "resultId": { + "description": "Generation result ID.", + "format": "uuid", + "title": "Resultid", + "type": "string" + } + }, + "required": [ + "specId", + "resultId" + ], + "title": "ResultSelect", + "type": "object" + }, + "ResultSelectCommand": { + "additionalProperties": false, + "description": "Adopt an existing generation result.", + "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": "result.select", + "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/ResultSelect", + "description": "Adopt an existing generation result." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" + ], + "title": "ResultSelectCommand", + "type": "object" + }, + "ResultSelectCommandOperation": { + "additionalProperties": false, + "description": "Adopt an existing generation result.", + "properties": { + "type": { + "const": "result.select", + "description": "Operation discriminator.", + "title": "Type", + "type": "string" + }, + "payload": { + "$ref": "#/$defs/ResultSelect", + "description": "Adopt an existing generation result." + } + }, + "required": [ + "type", + "payload" + ], + "title": "ResultSelectCommandOperation", + "type": "object" + }, + "ResultVersion": { + "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" + }, + "specId": { + "description": "Generation configuration ID.", + "format": "uuid", + "title": "Specid", + "type": "string" + }, + "jobId": { + "description": "Generation job ID.", + "format": "uuid", + "title": "Jobid", + "type": "string" + }, + "asset": { + "$ref": "#/$defs/AssetRef", + "description": "Immutable asset version." + }, + "inputFingerprint": { + "description": "Fingerprint of the fixed execution input.", + "pattern": "^[0-9a-f]{64}$", + "title": "Inputfingerprint", + "type": "string" + } + }, + "required": [ + "id", + "projectId", + "revision", + "specId", + "jobId", + "asset", + "inputFingerprint" + ], + "title": "ResultVersion", + "type": "object" + }, + "SelectionBox": { + "additionalProperties": false, + "properties": { + "x": { + "description": "Horizontal coordinate.", + "title": "X", + "type": "number" + }, + "y": { + "description": "Vertical coordinate.", + "title": "Y", + "type": "number" + }, + "width": { + "description": "Width in pixels.", + "exclusiveMinimum": 0, + "title": "Width", + "type": "number" + }, + "height": { + "description": "Height in pixels.", + "exclusiveMinimum": 0, + "title": "Height", + "type": "number" + } + }, + "required": [ + "x", + "y", + "width", + "height" + ], + "title": "SelectionBox", + "type": "object" + }, + "SpecCreateCommand": { + "additionalProperties": false, + "description": "Create a generation configuration without submitting a job.", + "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.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" }, - "message": { - "description": "Human-readable issue description.", - "title": "Message", - "type": "string" + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" }, - "humanReviewRequired": { - "default": true, - "description": "Whether creative quality still requires human review.", - "title": "Humanreviewrequired", - "type": "boolean" + "payload": { + "$ref": "#/$defs/SpecWrite", + "description": "Create a generation configuration without submitting a job." } }, "required": [ - "status", - "message" + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" ], - "title": "ResultCheck", + "title": "SpecCreateCommand", "type": "object" }, - "ResultSelect": { + "SpecCreateCommandOperation": { "additionalProperties": false, + "description": "Create a generation configuration without submitting a job.", "properties": { - "specId": { - "description": "Generation configuration ID.", - "format": "uuid", - "title": "Specid", + "type": { + "const": "generationSpec.create", + "description": "Operation discriminator.", + "title": "Type", "type": "string" }, - "resultId": { - "description": "Generation result ID.", - "format": "uuid", - "title": "Resultid", - "type": "string" + "payload": { + "$ref": "#/$defs/SpecWrite", + "description": "Create a generation configuration without submitting a job." } }, "required": [ - "specId", - "resultId" + "type", + "payload" ], - "title": "ResultSelect", + "title": "SpecCreateCommandOperation", "type": "object" }, - "ResultSelectCommand": { + "SpecPromptCommand": { "additionalProperties": false, - "description": "Adopt an existing generation result.", + "description": "Update prompt text and structured references.", "properties": { "commandId": { "description": "Stable command ID for idempotent replay.", @@ -28142,7 +29006,7 @@ "type": "string" }, "type": { - "const": "result.select", + "const": "generationSpec.setPrompt", "description": "Command discriminator.", "title": "Type", "type": "string" @@ -28171,8 +29035,8 @@ "title": "Expectedpreview" }, "payload": { - "$ref": "#/$defs/ResultSelect", - "description": "Adopt an existing generation result." + "$ref": "#/$defs/SpecPromptWrite", + "description": "Update prompt text and structured references." } }, "required": [ @@ -28183,126 +29047,183 @@ "expectedPreview", "payload" ], - "title": "ResultSelectCommand", + "title": "SpecPromptCommand", "type": "object" }, - "ResultSelectCommandOperation": { + "SpecPromptCommandOperation": { "additionalProperties": false, - "description": "Adopt an existing generation result.", + "description": "Update prompt text and structured references.", "properties": { "type": { - "const": "result.select", + "const": "generationSpec.setPrompt", "description": "Operation discriminator.", "title": "Type", "type": "string" }, "payload": { - "$ref": "#/$defs/ResultSelect", - "description": "Adopt an existing generation result." + "$ref": "#/$defs/SpecPromptWrite", + "description": "Update prompt text and structured references." } }, "required": [ "type", "payload" ], - "title": "ResultSelectCommandOperation", + "title": "SpecPromptCommandOperation", "type": "object" }, - "ResultVersion": { + "SpecPromptWrite": { "additionalProperties": false, "properties": { - "id": { - "description": "Stable identity of this project-owned object.", + "specId": { + "description": "Generation configuration ID.", "format": "uuid", - "title": "Id", + "title": "Specid", "type": "string" }, - "projectId": { - "description": "Owning project ID.", - "format": "uuid", - "title": "Projectid", + "prompt": { + "description": "Generation prompt text.", + "maxLength": 20000, + "title": "Prompt", "type": "string" }, - "revision": { - "default": 1, - "description": "Current object revision for optimistic concurrency.", - "minimum": 1, - "title": "Revision", - "type": "integer" - }, + "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" }, - "jobId": { - "description": "Generation job ID.", + "commandId": { + "description": "Historical command providing the settings to restore.", "format": "uuid", - "title": "Jobid", + "title": "Commandid", "type": "string" }, - "asset": { - "$ref": "#/$defs/AssetRef", - "description": "Immutable asset version." - }, - "inputFingerprint": { - "description": "Fingerprint of the fixed execution input.", - "pattern": "^[0-9a-f]{64}$", - "title": "Inputfingerprint", + "referencePolicy": { + "default": "follow_current", + "description": "Policy for restoring associated reference bindings.", + "enum": [ + "follow_current", + "pinned" + ], + "title": "Referencepolicy", "type": "string" } }, "required": [ - "id", - "projectId", - "revision", "specId", - "jobId", - "asset", - "inputFingerprint" + "commandId", + "referencePolicy" ], - "title": "ResultVersion", + "title": "SpecRestore", "type": "object" }, - "SelectionBox": { + "SpecRestoreCommand": { "additionalProperties": false, + "description": "Restore generation settings from a historical command.", "properties": { - "x": { - "description": "Horizontal coordinate.", - "title": "X", - "type": "number" + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" }, - "y": { - "description": "Vertical coordinate.", - "title": "Y", - "type": "number" + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" }, - "width": { - "description": "Width in pixels.", - "exclusiveMinimum": 0, - "title": "Width", - "type": "number" + "type": { + "const": "generationSpec.restore", + "description": "Command discriminator.", + "title": "Type", + "type": "string" }, - "height": { - "description": "Height in pixels.", - "exclusiveMinimum": 0, - "title": "Height", - "type": "number" + "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": [ - "x", - "y", - "width", - "height" + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" ], - "title": "SelectionBox", + "title": "SpecRestoreCommand", "type": "object" }, - "SpecCreateCommand": { + "SpecUpdateCommand": { "additionalProperties": false, - "description": "Create a generation configuration without submitting a job.", + "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.", @@ -28317,7 +29238,7 @@ "type": "string" }, "type": { - "const": "generationSpec.create", + "const": "generationSpec.update", "description": "Command discriminator.", "title": "Type", "type": "string" @@ -28347,7 +29268,7 @@ }, "payload": { "$ref": "#/$defs/SpecWrite", - "description": "Create a generation configuration without submitting a job." + "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged." } }, "required": [ @@ -28358,34 +29279,224 @@ "expectedPreview", "payload" ], - "title": "SpecCreateCommand", + "title": "SpecUpdateCommand", "type": "object" }, - "SpecCreateCommandOperation": { + "SpecUpdateCommandOperation": { "additionalProperties": false, - "description": "Create a generation configuration without submitting a job.", + "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged.", "properties": { "type": { - "const": "generationSpec.create", + "const": "generationSpec.update", "description": "Operation discriminator.", "title": "Type", "type": "string" }, "payload": { "$ref": "#/$defs/SpecWrite", - "description": "Create a generation configuration without submitting a job." + "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged." } }, "required": [ "type", "payload" ], - "title": "SpecCreateCommandOperation", + "title": "SpecUpdateCommandOperation", "type": "object" }, - "SpecPromptCommand": { + "SpecWrite": { "additionalProperties": false, - "description": "Update prompt text and structured references.", + "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" + }, + "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", + "calculated", + "reported" + ], + "title": "SpendCall", + "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.", @@ -28400,7 +29511,7 @@ "type": "string" }, "type": { - "const": "generationSpec.setPrompt", + "const": "spend.policy", "description": "Command discriminator.", "title": "Type", "type": "string" @@ -28429,8 +29540,8 @@ "title": "Expectedpreview" }, "payload": { - "$ref": "#/$defs/SpecPromptWrite", - "description": "Update prompt text and structured references." + "$ref": "#/$defs/SpendPolicy", + "description": "Set project service spending controls." } }, "required": [ @@ -28441,154 +29552,183 @@ "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", + "title": "SpendPolicyCommand", "type": "object" }, - "SpecPromptWrite": { + "SpendQuote": { "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" + "count": { + "description": "Number of fixed candidates in this action.", + "maximum": 8, + "minimum": 1, + "title": "Count", + "type": "integer" }, - "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" + "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": [ - "specId", - "prompt", - "promptContent" + "count", + "inputFingerprint", + "lines" ], - "title": "SpecPromptWrite", + "title": "SpendQuote", "type": "object" }, - "SpecRestore": { + "SpendRequest": { "additionalProperties": false, "properties": { - "specId": { - "description": "Generation configuration ID.", + "id": { + "description": "Stable identity of this project-owned object.", "format": "uuid", - "title": "Specid", + "title": "Id", "type": "string" }, - "commandId": { - "description": "Historical command providing the settings to restore.", + "projectId": { + "description": "Owning project ID.", "format": "uuid", - "title": "Commandid", + "title": "Projectid", "type": "string" }, - "referencePolicy": { - "default": "follow_current", - "description": "Policy for restoring associated reference bindings.", + "revision": { + "default": 1, + "description": "Current object revision for optimistic concurrency.", + "minimum": 1, + "title": "Revision", + "type": "integer" + }, + "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": [ - "follow_current", - "pinned" + "pending", + "accepted", + "cancelled" ], - "title": "Referencepolicy", + "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": [ - "specId", - "commandId", - "referencePolicy" + "id", + "projectId", + "revision", + "versions", + "quote", + "createdAt", + "status", + "agentRunId", + "agentCallId", + "decisionId" ], - "title": "SpecRestore", + "title": "SpendRequest", "type": "object" }, - "SpecRestoreCommand": { + "SpendReview": { "additionalProperties": false, - "description": "Restore generation settings from a historical command.", "properties": { - "commandId": { - "description": "Stable command ID for idempotent replay.", + "requestId": { + "description": "Original batch request.", "format": "uuid", - "title": "Commandid", + "title": "Requestid", "type": "string" }, - "projectId": { - "description": "Owning project ID.", - "format": "uuid", - "title": "Projectid", + "fingerprint": { + "description": "Reviewed input and price fingerprint.", + "pattern": "^[0-9a-f]{64}$", + "title": "Fingerprint", "type": "string" }, - "type": { - "const": "generationSpec.restore", - "description": "Command discriminator.", - "title": "Type", + "decision": { + "description": "Human decision for this exact action.", + "enum": [ + "approve", + "cancel" + ], + "title": "Decision", "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" + "acceptUnknown": { + "default": false, + "description": "Explicitly accepts this unpriced action with no project cap.", + "title": "Acceptunknown", + "type": "boolean" }, - "expectedPreview": { + "newCap": { "anyOf": [ { - "pattern": "^[0-9a-f]{64}$", "type": "string" }, { @@ -28596,28 +29736,23 @@ } ], "default": null, - "description": "Fingerprint of the confirmed impact preview.", - "title": "Expectedpreview" - }, - "payload": { - "$ref": "#/$defs/SpecRestore", - "description": "Restore generation settings from a historical command." + "description": "Raise the project cap in the same transaction as admission.", + "title": "Newcap" } }, "required": [ - "commandId", - "projectId", - "type", - "expectedVersions", - "expectedPreview", - "payload" + "requestId", + "fingerprint", + "decision", + "acceptUnknown", + "newCap" ], - "title": "SpecRestoreCommand", + "title": "SpendReview", "type": "object" }, - "SpecUpdateCommand": { + "SpendReviewCommand": { "additionalProperties": false, - "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged.", + "description": "Record a human decision on a fixed request.", "properties": { "commandId": { "description": "Stable command ID for idempotent replay.", @@ -28632,7 +29767,7 @@ "type": "string" }, "type": { - "const": "generationSpec.update", + "const": "spend.review", "description": "Command discriminator.", "title": "Type", "type": "string" @@ -28661,8 +29796,8 @@ "title": "Expectedpreview" }, "payload": { - "$ref": "#/$defs/SpecWrite", - "description": "Replace the complete generation configuration; preserve unedited fields and use the current version. Jobs are unchanged." + "$ref": "#/$defs/SpendReview", + "description": "Record a human decision on a fixed request." } }, "required": [ @@ -28673,99 +29808,37 @@ "expectedPreview", "payload" ], - "title": "SpecUpdateCommand", + "title": "SpendReviewCommand", "type": "object" }, - "SpecUpdateCommandOperation": { + "SpendStatusQuery": { "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", + "queryId": { + "description": "Caller-supplied query ID.", + "format": "uuid", + "title": "Queryid", "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" - }, - "SpendQuote": { - "additionalProperties": false, - "properties": { - "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", + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", "type": "string" }, - "lines": { - "description": "Individual provider calls per candidate, in execution order.", - "items": { - "$ref": "#/$defs/PriceLine" - }, - "title": "Lines", - "type": "array" + "type": { + "const": "spend.status", + "description": "Read policy, totals, coverage and pending human decisions.", + "title": "Type", + "type": "string" } }, "required": [ - "count", - "inputFingerprint", - "lines" + "queryId", + "projectId", + "type" ], - "title": "SpendQuote", + "title": "SpendStatusQuery", "type": "object" }, "StackCanvasItem": { @@ -32746,6 +33819,8 @@ "reference.restore": "#/$defs/ReferenceRestoreCommand", "reference.update": "#/$defs/ReferenceUpdateCommand", "result.select": "#/$defs/ResultSelectCommand", + "spend.policy": "#/$defs/SpendPolicyCommand", + "spend.review": "#/$defs/SpendReviewCommand", "timeline.publishRender": "#/$defs/TimelinePublishRenderCommand" }, "propertyName": "type" @@ -32841,6 +33916,12 @@ { "$ref": "#/$defs/ReferenceRemoveCommand" }, + { + "$ref": "#/$defs/SpendPolicyCommand" + }, + { + "$ref": "#/$defs/SpendReviewCommand" + }, { "$ref": "#/$defs/GenerationSubmitCommand" }, @@ -32891,11 +33972,15 @@ "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" }, diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index e4207edb1..598321587 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -406,7 +406,8 @@ 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; @@ -427,7 +428,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; @@ -439,9 +440,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 | SpendPolicyCommandInput | SpendReviewCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; readonly receipt: CommandReceiptInput; - readonly query: GenerationQuoteQueryInput | ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | AssetPreviewQueryInput; + readonly query: SpendStatusQueryInput | GenerationQuoteQueryInput | ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | AssetPreviewQueryInput; readonly event: ProjectEventInput; readonly job: JobInput; readonly result: ResultVersionInput; @@ -954,7 +955,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; } @@ -1019,6 +1020,7 @@ export interface PriceLineInput extends ContractInput { } export interface ProjectInput extends ContractInput { + readonly spendPolicy?: SpendPolicyInput | null; readonly id: string; readonly revision?: number; readonly name: string; @@ -1081,6 +1083,8 @@ export interface ProjectSnapshotInput extends ContractInput { readonly jobs?: ReadonlyArray; readonly results?: ReadonlyArray; readonly eventCursor?: number; + readonly spendRequests?: ReadonlyArray; + readonly spendCalls?: ReadonlyArray; readonly undoClearedThrough?: number; } @@ -1264,12 +1268,60 @@ 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 calculated?: number | string | null; + readonly reported?: number | string | null; +} + +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 count: number; readonly inputFingerprint: string; readonly lines: ReadonlyArray; } +export interface SpendRequestInput extends ProjectEntityInput { + 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 type: "spend.status"; +} + export interface StackCanvasItemInput extends EditorCanvasItemInput { readonly kind: "stack"; } @@ -1669,7 +1721,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 | SpendPolicyCommandInput | SpendReviewCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; export type ExecutionParametersInput = TextExecutionInput | ImageExecutionInput | VideoExecutionInput | AudioExecutionInput; @@ -2087,7 +2139,8 @@ 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; @@ -2108,7 +2161,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; @@ -2120,9 +2173,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 | SpendPolicyCommand | SpendReviewCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; readonly receipt: CommandReceipt; - readonly query: GenerationQuoteQuery | ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | AssetPreviewQuery; + readonly query: SpendStatusQuery | GenerationQuoteQuery | ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | AssetPreviewQuery; readonly event: ProjectEvent; readonly job: Job; readonly result: ResultVersion; @@ -2634,7 +2687,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; } @@ -2699,6 +2752,7 @@ export interface PriceLine extends Contract { } export interface Project extends Contract { + readonly spendPolicy?: SpendPolicy | null; readonly id: string; readonly revision: number; readonly name: string; @@ -2761,6 +2815,8 @@ export interface ProjectSnapshot extends Contract { readonly jobs: ReadonlyArray; readonly results: ReadonlyArray; readonly eventCursor: number; + readonly spendRequests?: ReadonlyArray; + readonly spendCalls?: ReadonlyArray; readonly undoClearedThrough: number; } @@ -2944,12 +3000,60 @@ 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 calculated: string | null; + readonly reported: string | null; +} + +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 count: number; readonly inputFingerprint: string; readonly lines: ReadonlyArray; } +export interface SpendRequest extends ProjectEntity { + 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 type: "spend.status"; +} + export interface StackCanvasItem extends EditorCanvasItem { readonly kind: "stack"; } @@ -3349,7 +3453,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 | SpendPolicyCommand | SpendReviewCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; export type ExecutionParameters = TextExecution | ImageExecution | VideoExecution | AudioExecution; diff --git a/tests/test_spend_admission.py b/tests/test_spend_admission.py new file mode 100644 index 000000000..2bfe6bf26 --- /dev/null +++ b/tests/test_spend_admission.py @@ -0,0 +1,112 @@ +import asyncio +import base64 +from decimal import Decimal +from uuid import uuid4 + +import httpx +import pytest + +from generation_helpers import command +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.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, ver +from test_creation_generation_service import anyio_backend +from test_creation_parameters import done, png + + +@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' + 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() + + +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)) + + +@pytest.mark.anyio +async def test_atomic_batch_approval_race_replay_and_cap_raise(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) + 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 + 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') + 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='2.4') + 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') + finally: + gate.set() + await runner.close() From 1e2cf81dfcbb4c650f6d2f5362afe58c8a114e65 Mon Sep 17 00:00:00 2001 From: bread-lxy <2022200058@ruc.edu.cn> Date: Sun, 22 Nov 2026 11:15:48 +0800 Subject: [PATCH 03/15] [feat] Show batch estimates and project approvals across creative entry points --- .../application/creation_canvas.py | 7 +- packages/core/src/opendirector/cli.py | 3 + src/backend/creationClient.ts | 5 +- src/backend/rules.ts | 1 + src/backend/spend.ts | 37 ++++ src/canvas/AssistantPanel.tsx | 2 + src/canvas/ModelSettings.tsx | 4 + src/canvas/NodeComposer.tsx | 6 + src/canvas/ProjectSpend.tsx | 196 ++++++++++++++++++ src/canvas/project-spend.css | 20 ++ src/canvas/workspace/WorkspaceView.tsx | 3 + .../workspace/useWorkspaceGeneration.ts | 16 +- src/i18n/messages/en-US/generation.ts | 49 +++++ src/i18n/messages/zh-CN/generation.ts | 49 +++++ tests/browser/manifest.json | 2 + tests/browser/project_spend.mjs | 105 ++++++++++ 16 files changed, 492 insertions(+), 13 deletions(-) create mode 100644 src/backend/spend.ts create mode 100644 src/canvas/ProjectSpend.tsx create mode 100644 src/canvas/project-spend.css create mode 100644 tests/browser/project_spend.mjs diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index cfadd7bab..ba8965ae0 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -850,7 +850,12 @@ async def query(self, query: Query) -> JsonValue: 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) - return dict(quote=quote.model_dump(mode='json'), fingerprint=quote.fingerprint()) + from opendirector.domain.creation.spend import spend_summary, spend_decision + summary = spend_summary(await asyncio.to_thread(self.projects.snapshot, query.projectId)) + total = quote.total(summary['policy'].currency) + return to_jsonable_python(dict(quote=quote, fingerprint=quote.fingerprint(), amount=total, + projectAfter=None if total is None else summary['settled'] + summary['held'] + total, + currency=summary['policy'].currency, reason=spend_decision(summary, 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/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/src/backend/creationClient.ts b/src/backend/creationClient.ts index 56e05c494..99adcc6a3 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/rules.ts b/src/backend/rules.ts index bef7aa375..0f78247cd 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..f996bedb0 --- /dev/null +++ b/src/backend/spend.ts @@ -0,0 +1,37 @@ +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; +} + +export interface PendingSpend { + request: SpendRequest; + fingerprint: string; + reason: "ready" | "confirmation" | "unknown_confirmation" | "unpriced" | "over_cap"; + amount: string | null; + shortfall: string | null; +} + +export interface SpendStatus { + policy: SpendPolicy; + held: string; + settled: string; + available: string | null; + unknown: number; + legacy: number; + since: string | null; + projectRevision: number; + pending: PendingSpend[]; +} + +export function spendQuery(projectId: string, type: "spend.status" | "generation.quote", fields = {}, signal?: AbortSignal) { + return request(creationPath(projectId) + "/queries", { + ...json("POST", { type, projectId, queryId: crypto.randomUUID(), ...fields }), signal, + }); +} diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index ad1350f23..d583bd7f5 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 { ProjectSpend } from "./ProjectSpend"; import { AssistantReply } from "./AssistantReply"; import { AssistantConversations } from "./AssistantConversations"; import { AgentPicker } from "./AgentPicker"; @@ -412,6 +413,7 @@ export function AssistantPanel({

)} + {open && } {value.messages.map((message, index) => { const previous = value.messages[index - 1]; const trace = message.role === "assistant" && message !== latestReply && message.status !== "streaming" && diff --git a/src/canvas/ModelSettings.tsx b/src/canvas/ModelSettings.tsx index cecabaa39..f22023be8 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, modelSetupMissing, type SetupKind } from "./ModelSetup"; import { ModelLogo } from "./ModelLogo"; @@ -198,6 +199,9 @@ export function ModelSettings({ catalog, onClose, guided = false }: { catalog: B error={member.availability?.reasonCode === "query_failed" ? catalog.availabilityError || undefined : undefined} onRefresh={() => void catalog.refreshAvailability([member.id], true)} />)} + {model.kind !== "agent" &&
{t("spend.price")} + {members.map(member => )} +
}
{providerLabel(model)}{" "} diff --git a/src/canvas/NodeComposer.tsx b/src/canvas/NodeComposer.tsx index 4de28081b..24f345fa0 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. */ @@ -84,7 +85,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, @@ -283,6 +287,8 @@ export function NodeComposer({ onEscape={() => setPanel(null)} >
+ {projectId && config && canRun && m.price))} />} {firstLast && (
{( diff --git a/src/canvas/ProjectSpend.tsx b/src/canvas/ProjectSpend.tsx new file mode 100644 index 000000000..3f2369132 --- /dev/null +++ b/src/canvas/ProjectSpend.tsx @@ -0,0 +1,196 @@ +import { useCallback, useEffect, 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 "./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 money(value: string, currency: string, locale: string) { + return new Intl.NumberFormat(locale, { style: "currency", currency, currencyDisplay: "code", maximumFractionDigits: 12 }).format(Number(value)); +} + +function QuoteLines({ quote }: { quote: SpendQuote }) { + const { t, locale } = useI18n(); + return
    {quote.lines.map((line, index) =>
  • + {t(`spend.operation.${line.operation}` as "spend.operation.image")} · {line.modelId} + {line.price && line.amount != null ? money(line.amount, line.price.currency, locale) : t("spend.unknown")} + {line.price && {t(`spend.source.${line.source}`)} · {line.quantity ?? "?"} × {line.price.rate} {line.price.currency} / {t(`spend.unit.${line.price.unit}`)}} +
  • )}
; +} + +export function GenerationEstimate({ projectId, itemId, count, modelId, prompt, priceRevision }: { + projectId: string; itemId: string; count: number; modelId: string; prompt: string; priceRevision: string; +}) { + const { t, locale } = useI18n(); + const snapshot = useSnapshot(projectId); + const [result, setResult] = useState<{ key: string; value: QuoteView }>(); + 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; + 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(undefined); }); + }, 180); + return () => { clearTimeout(timer); abort.abort(); }; + }, [projectId, itemId, specId, count, matches, key]); + if (!matches || result?.key !== key) return null; + const { amount, currency, projectAfter, quote } = result.value; + return
+ {t("spend.estimate", { count, amount: amount == null ? t("spend.unknown") : money(amount, currency, locale) })} + {projectAfter != null && <> · {t("spend.after", { amount: money(projectAfter, currency, locale) })}} + +
; +} + +function ReviewCard({ projectId, entry, status, onSettings, onChange }: { + projectId: string; entry: PendingSpend; status: SpendStatus; onSettings?: () => void; onChange: () => void; +}) { + const { t, locale } = useI18n(); + const [newCap, setNewCap] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const { request: batch, reason } = entry; + const currency = status.policy.currency; + const decide = async (decision: "approve" | "cancel") => { + setBusy(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 } : {}), + }, versions); + } catch (failure) { setError(errorMessage(failure)); } + finally { setBusy(false); onChange(); } + }; + return
+ {t("spend.estimate", { count: batch.quote.count, amount: entry.amount == null ? t("spend.unknown") : money(entry.amount, currency, locale) })} + + {reason === "over_cap" && <> +

{t("spend.shortfall", { cap: money(status.policy.cap!, currency, locale), available: money(status.available!, currency, locale), missing: money(entry.shortfall!, currency, locale) })}

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

{t("spend.needPrice")}

} +
+ {reason === "unpriced" ? onSettings && : + } + +
+ {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, placement, onSettings }: { + projectId: string; placement: "canvas" | "chat"; onSettings?: () => void; +}) { + const { t, locale } = useI18n(); + const snapshot = useSnapshot(projectId); + const pendingCount = snapshot?.spendRequests?.filter(r => r.status === "pending").length ?? 0; + const [open, setOpen] = useState(() => placement === "canvas" && new URLSearchParams(window.location.search).has("spendReview")); + const [status, setStatus] = useState(); + const [error, setError] = useState(""); + const [revision, reload] = useState(0); + const shown = open || (placement === "chat" && pendingCount > 0); + 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]); + if (placement === "chat" && !pendingCount) return null; + return
+ {placement === "canvas" && } + {shown &&
+

{t("spend.title")}

+ {error &&

{error}

} + {status && <> +

{t("spend.summary", { settled: money(status.settled, status.policy.currency, locale), held: money(status.held, status.policy.currency, locale) })}

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

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

} + {status.pending.map(entry => reload(r => r + 1)} />)} + {placement !== "chat" && <> +
{t("spend.controls")}
+
{t("spend.log")} + {status.since && {t("spend.since", { date: new Date(status.since).toLocaleString(locale) })}} +
    {[...(snapshot?.spendCalls ?? [])].reverse().map(call =>
  • + {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.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/project-spend.css b/src/canvas/project-spend.css new file mode 100644 index 000000000..2ce91bada --- /dev/null +++ b/src/canvas/project-spend.css @@ -0,0 +1,20 @@ +.cw-spend { position: relative; font-size: 13px; } +.cw-spend-toggle, .cw-spend-panel, .cw-spend-form input, .cw-spend-form select, .cw-spend-card input { + border: 1px solid #cad0d7; border-radius: 8px; background: white; color: #283240; +} +.cw-spend-toggle { min-height: 36px; padding: 0 10px; cursor: pointer; } +.cw-spend-panel { padding: 14px; box-shadow: 0 5px 20px #2736471a; } +.cw-spend-canvas .cw-spend-panel { position: absolute; bottom: 44px; left: 0; width: min(350px, 82vw); max-height: 72vh; overflow: auto; z-index: 12; } +.cw-spend-panel h3, .cw-spend-panel p { margin: 0 0 8px; } +.cw-spend-panel details, .cw-spend-estimate { margin: 6px 0; } +.cw-spend-panel summary, .cw-spend-estimate summary { cursor: pointer; } +.cw-spend-card { border-top: 1px solid #d7dce2; padding: 10px 0; } +.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: #515f70; } +.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, .cw-spend-card label { display: flex; align-items: center; justify-content: space-between; gap: 8px; } +.cw-spend-form input, .cw-spend-form select, .cw-spend-card input { width: 9em; padding: 4px; } +.cw-spend-actions button, .cw-spend-form button { background: #edf1f5; color: #233245; padding: 5px 10px; border: 0; border-radius: 6px; cursor: pointer; } +.cw-spend-estimate { font-size: 12px; color: #465363; } diff --git a/src/canvas/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx index 3e1828f0c..e1a169864 100644 --- a/src/canvas/workspace/WorkspaceView.tsx +++ b/src/canvas/workspace/WorkspaceView.tsx @@ -1,4 +1,5 @@ import { projectDisplayName } from "../projectDisplayName"; +import { ProjectSpend } from "../ProjectSpend"; import { DesktopSidebar } from "./DesktopSidebar"; import { Background, BackgroundVariant, MiniMap, SelectionMode, ViewportPortal } from "@xyflow/react"; @@ -1203,6 +1204,7 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { {!ready &&
}
+ {ready && { setSettingsCategory("models"); setSettingsOpen(true); }} />}
) : ( => { const id = crypto.randomUUID(); let jobIds: string[] = []; @@ -179,12 +180,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")); @@ -550,17 +554,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) diff --git a/src/i18n/messages/en-US/generation.ts b/src/i18n/messages/en-US/generation.ts index 542afa478..f6d889a9e 100644 --- a/src/i18n/messages/en-US/generation.ts +++ b/src/i18n/messages/en-US/generation.ts @@ -1,5 +1,54 @@ /** Composer, generation state, model choice and generation rules. */ export const generation = { + "spend.title": "Project spend", + "spend.estimate": "{count} candidate(s) · {amount} estimated", + "spend.after": "Project total {amount}", + "spend.unknown": "Unknown price", + "spend.newCap": "New project cap", + "spend.shortfall": "Cap {cap}. Available {available}. This batch needs {missing} more.", + "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 and run this batch", + "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": "Settled {settled} · Reserved {held}", + "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.unit": "Billing unit", + "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.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 4e6184e66..3b42819bf 100644 --- a/src/i18n/messages/zh-CN/generation.ts +++ b/src/i18n/messages/zh-CN/generation.ts @@ -1,5 +1,54 @@ /** Composer, generation state, model choice and generation rules. */ export const generation = { + "spend.title": "工程费用", + "spend.estimate": "{count} 个候选 · 预计 {amount}", + "spend.after": "工程预计合计 {amount}", + "spend.unknown": "价格未知", + "spend.newCap": "新的工程上限", + "spend.shortfall": "上限 {cap},可用 {available},本批还差 {missing}。", + "spend.needPrice": "请配置工程币种的单价或选择其他模型,然后重新询价。", + "spend.connections": "模型接入", + "spend.raiseRun": "提高上限并运行本批", + "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.coverage": "有 {count} 项调用缺少该币种的可核验金额。", + "spend.controls": "费用设置", + "spend.log": "费用记录", + "spend.since": "记录始于 {date}", + "spend.estimateAmount": "预计", + "spend.calculated": "按用量计算", + "spend.reported": "服务报告金额", + "spend.price": "单价", + "spend.automatic": "自动", + "spend.unit": "计费单位", + "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.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 345d6b701..1f416b1eb 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..26bd481e3 --- /dev/null +++ b/tests/browser/project_spend.mjs @@ -0,0 +1,105 @@ +/** 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 { 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; +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 }); + await call(`/api/model-configs/${model.id}/price`, { unit: "request", rate: "0.40", currency: "USD" }, "PUT"); + 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.modelSetup.v1", "dismissed"); + }, locale); + await page.goto(`${web}/ai-tool/ai-canvas/${pid}`); + const toggle = page.locator(".cw-spend-toggle"); + 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 toggle.click(); + 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"); + 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 composer.locator(".cw-spend-estimate summary").filter({ hasText: "1.20" }).waitFor(); + const before = posts.length; + await composer.locator("button.cw-run-button").click(); + await toggle.filter({ hasText: "(1)" }).or(toggle.filter({ hasText: "(1)" })).waitFor(); + const pending = await call(path); + assert.equal(pending.jobs.length, 0); + assert.equal(pending.spendCalls?.length ?? 0, 0); + assert.equal(posts.length, before); + await toggle.click(); + const approve = page.getByRole("button", { name: en ? "Run this batch" : "确认运行本批", exact: true }); + await approve.click(); + 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.deepEqual(errors, []); + console.log(locale, "USD 1.20 shown; 0 calls pending; 3 jobs and 3 provider requests"); + await page.close(); + } +} finally { + await browser.close(); + service.close(); + if (model) await call(`/api/model-configs/${model.id}`, null, "DELETE"); +} From 96b407bf0716d91d656cb2a0078062e81b193bab Mon Sep 17 00:00:00 2001 From: bread-lxy <2022200058@ruc.edu.cn> Date: Sun, 22 Nov 2026 11:46:54 +0800 Subject: [PATCH 04/15] [feat] Account for provider calls and resume reviewed media workflows --- apps/api/src/opendirector_api/creation.py | 4 +- apps/api/src/opendirector_api/localization.py | 6 +- apps/api/src/opendirector_api/main.py | 9 + apps/api/src/opendirector_api/models.py | 1 + packages/core/src/opendirector/agent/tools.py | 18 +- .../application/creation_canvas.py | 10 +- .../application/creation_generation.py | 99 +- .../application/creation_groups.py | 151 ++ .../application/creation_spend.py | 48 +- .../opendirector/application/tool_context.py | 8 +- .../opendirector/application/tool_spend.py | 127 ++ .../application/tool_task_lifecycle.py | 48 + .../opendirector/application/tool_tasks.py | 159 +- .../application/tool_video_inputs.py | 10 +- .../opendirector/domain/creation/commands.py | 34 +- .../src/opendirector/domain/creation/spend.py | 99 +- .../infrastructure/creation_publication.py | 2 +- .../integrations/model_adapters.py | 5 +- .../opendirector/integrations/providers.py | 12 +- src/contracts/creation.schema.json | 1338 ++++++++++++++++- src/contracts/generated.ts | 134 +- tests/generation_helpers.py | 11 + tests/test_creation_parameters.py | 42 +- tests/test_minimax_speech.py | 6 +- tests/test_spend_admission.py | 39 +- tests/test_spend_cli.py | 49 + tests/test_spend_prices.py | 17 +- tests/test_spend_workflows.py | 186 +++ 28 files changed, 2534 insertions(+), 138 deletions(-) create mode 100644 packages/core/src/opendirector/application/creation_groups.py create mode 100644 packages/core/src/opendirector/application/tool_spend.py create mode 100644 tests/test_spend_cli.py create mode 100644 tests/test_spend_workflows.py diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index 19d884bc9..9fb940bce 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -131,7 +131,7 @@ 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) @@ -140,7 +140,7 @@ async def execute(project_id: UUID, value: Command, request: Request, x_opendire raise ProjectError('归档来源必须是 generated 或 edited。', 400) 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', 'spend.review', 'spend.policy', 'job.cancel', 'job.recover'}: + 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 5018e4146..76114ec65 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -14,6 +14,9 @@ from opendirector.domain.capability_messages import english_capability_message, missing_tool_model_message ENGLISH_BY_CODE = { + '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.', @@ -147,7 +150,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.startswith(('capability_', 'image_input_', 'tool_source_')): diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index d705ecd14..4234610d1 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -80,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)) @@ -300,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()): @@ -332,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 9e64a2ee2..c66f76db7 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -117,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/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index efc38e9c3..1c79b9c19 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 = {'spend.policy', 'spend.review', '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 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. @@ -381,6 +384,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() @@ -431,7 +436,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') @@ -451,4 +456,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 ba8965ae0..c655fb5f4 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -845,17 +845,13 @@ def projection(self, project_id, snapshot=None): async def query(self, query: Query) -> JsonValue: if query.type == 'spend.status': from opendirector.application.creation_spend import review_status - return to_jsonable_python(await asyncio.to_thread(lambda: review_status(self.projects.snapshot(query.projectId)))) + return to_jsonable_python(await asyncio.to_thread(lambda: review_status(self.projects.snapshot(query.projectId), query.agentRunId))) 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.domain.creation.spend import spend_summary, spend_decision - summary = spend_summary(await asyncio.to_thread(self.projects.snapshot, query.projectId)) - total = quote.total(summary['policy'].currency) - return to_jsonable_python(dict(quote=quote, fingerprint=quote.fingerprint(), amount=total, - projectAfter=None if total is None else summary['settled'] + summary['held'] + total, - currency=summary['policy'].currency, reason=spend_decision(summary, quote))) + 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_generation.py b/packages/core/src/opendirector/application/creation_generation.py index fed335b36..62a71959c 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -14,7 +14,7 @@ from filelock import FileLock, Timeout -from opendirector.application import creation_spend +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 @@ -80,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']) @@ -101,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) @@ -415,6 +422,7 @@ def _quote_job(self, job, config, task, records, count): 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') @@ -425,9 +433,13 @@ def _quote_job(self, job, config, task, records, count): 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 params.get('duration') is not None: quantities.update(requested_second=params['duration'], output_second=params['duration']) - lines.append(price_line(config, operation, quantities)) + 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): @@ -447,14 +459,10 @@ def quote(self, project_id, spec_id, count=1, origin=None): _, job, config, task, records = self._propose_job(before, command) return self._quote_job(job, config, task, records, count) - 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 + 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 @@ -474,10 +482,39 @@ def prepare(self, command, *, session=None, source='ui', agent_origin=None, revi self.voices.validate_selection(voice_config, prepared_spec.parameters.voice, prepared_spec.parameters.voiceSelection) except (ValueError, ProjectError) as error: voice_failure = error - checks = voice_spec, voice_config, voice_failure, capability_identity, capability_failure + 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): if review is not None: validate_command(command, before) + elif 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.') @@ -487,22 +524,7 @@ def accept(before): return decision data['project'] = decision.project.model_dump(mode='json') data['spendRequests'] = decision.spendRequests - 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) + 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): @@ -531,6 +553,11 @@ def cancel_request(before): 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)) @@ -573,6 +600,16 @@ 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') + if task.get('status') in {'cancelled', 'failed', 'interrupted'}: + 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} @@ -693,6 +730,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 @@ -795,14 +837,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..f1f86c302 --- /dev/null +++ b/packages/core/src/opendirector/application/creation_groups.py @@ -0,0 +1,151 @@ +"""Price runnable workflow members together and continue from their adopted outputs.""" +import asyncio +import logging +from datetime import datetime, timezone +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) + 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 _wave(snapshot, plan): + workflow = plan.commandId + items = {m.itemId for m in plan.payload.members} + decisions = [r for r in snapshot.spendRequests if r.workflowId == workflow] + if any(r.status != 'accepted' for r in decisions): + return [], [] + admitted = {i for r in decisions for i in r.groupItems} + jobs = [j for j in snapshot.jobs if j.batchId == workflow and j.originItemId in items] + if any(j.status in {'queued', 'running'} for j in jobs): + return [], [] + finished = {j.originItemId for j in jobs if j.adopted and j.status == 'succeeded'} + remaining = [m for m in plan.payload.members if m.itemId not in admitted] + ready = [m for m in remaining if set(m.after) <= finished] + return ready, [m.itemId for m in remaining if m not in ready] + + +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 = request.quote.deferred + else: + members, deferred = _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 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 = before + lines, prints = [], [] + candidates = 0 + for m in members: + member = _member(before, m, plan.commandId) + validate_command(member, before) + data, job, config, task, records = runtime._propose_job(draft, member, agent_origin=origin, checks=checks[m.itemId]) + 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) + 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, fromUpstream=command.type == 'spend.advanceGroup', + inputFingerprint=sha256('|'.join(prints).encode()).hexdigest(), lines=lines) + 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 index fe55959e6..579451e17 100644 --- a/packages/core/src/opendirector/application/creation_spend.py +++ b/packages/core/src/opendirector/application/creation_spend.py @@ -1,12 +1,23 @@ """Project-scoped admission. All callers invoke these decisions under the project commit lock.""" from datetime import datetime, timezone -from uuid import uuid5 +from uuid import uuid4, uuid5 -from opendirector.domain.creation.spend import SpendCall, SpendPolicy, SpendRequest, spend_decision, spend_summary +from opendirector.domain.creation.spend import SpendCall, SpendPolicy, SpendRequest, call_totals, spend_decision, 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 review_status(snapshot): +def quote_view(snapshot, quote): + summary = spend_summary(snapshot) + total = quote.total(summary['policy'].currency) + return dict(quote=quote, fingerprint=quote.fingerprint(), amount=total, subtotals=quote.subtotals(), + projectAfter=None if total is None else summary['settled'] + summary['held'] + total, + currency=summary['policy'].currency, reason=spend_decision(summary, quote)) + + +def review_status(snapshot, agent_run_id=None): summary = spend_summary(snapshot) policy = summary['policy'] pending = [] @@ -15,9 +26,14 @@ def review_status(snapshot): continue total = request.quote.total(policy.currency) reason = spend_decision(summary, request.quote) - pending.append(dict(request=request, fingerprint=request.quote.fingerprint(), reason=reason, amount=total, + pending.append(dict(request=request, fingerprint=request.quote.fingerprint(), reason='stale' if request.currency and request.currency != policy.currency else reason, amount=total, subtotals=request.quote.subtotals(), shortfall=total-summary['available'] if reason == 'over_cap' else None)) - return dict(**summary, projectRevision=snapshot.project.revision, pending=pending) + result = dict(**summary, projectRevision=snapshot.project.revision, pending=pending) + 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): @@ -41,11 +57,14 @@ def decide(before, command, quote, agent_origin, review=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 == 'unpriced' or (reason == 'unknown_confirmation' and not selection.acceptUnknown): @@ -66,6 +85,25 @@ def resolve(before, request, decision_id, 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, 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..d69e02f5e --- /dev/null +++ b/packages/core/src/opendirector/application/tool_spend.py @@ -0,0 +1,127 @@ +"""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 +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']) + pieces = (task.get('videoExecution') or {}).get('pieces', ()) + 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 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'] = units['requested_second'] = Decimal(str(round(end-start, 6))) + elif capability == 'video.first_frame' and tool == 'dynamic-poster': + units['requested_second'] = 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('The tool needs an additional model call outside its accepted estimate.', 409, code='spend_quote_changed') + call = calls[ordinal] + if call.state != 'reserved': + raise ProjectError('This tool model call has already been submitted.', 409) + 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..3d1cabca1 100644 --- a/packages/core/src/opendirector/application/tool_task_lifecycle.py +++ b/packages/core/src/opendirector/application/tool_task_lifecycle.py @@ -12,6 +12,8 @@ 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 +86,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 +116,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) @@ -337,8 +346,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..3d82249c3 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('This request has already been cancelled.', 409) + 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('The selection preview has already started. Check project spending before retrying.', 409) + 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 ------------------------------------------------------------------- @@ -213,6 +285,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 +316,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 +333,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 +360,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 @@ -357,6 +432,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 +462,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('This request has already been cancelled.', 409) + 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 +523,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/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index addf0b66b..fab80041b 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -7,7 +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 SpendPolicy, SpendReview +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 @@ -231,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.') @@ -318,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': @@ -359,8 +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.'), @@ -475,6 +506,7 @@ class GenerationQuoteQuery(QueryBase): 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.') diff --git a/packages/core/src/opendirector/domain/creation/spend.py b/packages/core/src/opendirector/domain/creation/spend.py index cfde53f7e..a6887e4a4 100644 --- a/packages/core/src/opendirector/domain/creation/spend.py +++ b/packages/core/src/opendirector/domain/creation/spend.py @@ -4,7 +4,7 @@ from typing import Annotated, Literal from uuid import UUID -from pydantic import Field +from pydantic import Field, JsonValue from .base import Contract, Digest, ObjectVersion, ProjectEntity, digest @@ -23,14 +23,20 @@ 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: Money | 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.') + 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.') @@ -40,6 +46,10 @@ def total(self, currency): return None 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} + 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) @@ -50,7 +60,18 @@ class SpendPolicy(Contract): 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.') @@ -66,6 +87,7 @@ class SpendCall(ProjectEntity): 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: Money | 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.') @@ -86,34 +108,74 @@ class SpendReview(Contract): newCap: Money | None = Field(default=None, description='Raise the project cap in the same transaction as admission.') -def spend_summary(snapshot): - policy = snapshot.project.spendPolicy or SpendPolicy() - settled, held = Decimal(0), Decimal(0) - missing = 0 - owners = set() - for call in snapshot.spendCalls: - owners.add(call.ownerId) +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=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 + for call in calls: amount = call.accounted() - if amount is None or (amount and call.line.price.currency != policy.currency): + 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 - legacy = sum(j.execution.kind != 'text' and j.id not in owners for j in snapshot.jobs) - return dict(policy=policy, settled=settled, held=held, available=None if policy.cap is None else policy.cap-settled-held, - unknown=missing, legacy=legacy, since=min((c.createdAt for c in snapshot.spendCalls), default=None)) + 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} + return dict(policy=policy, **totals, + available=None if policy.cap is None else policy.cap - totals['settled'] - totals['held'], + 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 'ready' + 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 'unpriced' 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' @@ -122,7 +184,7 @@ def spend_decision(summary, quote): # 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#2026-11-22' +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'), @@ -130,7 +192,7 @@ def spend_decision(summary, quote): } -def price_line(config, operation, quantities): +def price_line(config, operation, quantities, *, bounded=()): """Count only units for which the effective request supplies a bound.""" version = None price = None @@ -143,7 +205,7 @@ def price_line(config, operation, quantities): 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', OFFICIAL_SOURCE + source, version = 'official', '2026-11-22' else: source = 'unknown' quantity = None if price is None else {'request': 1, **quantities}.get(price.unit) @@ -151,5 +213,6 @@ def price_line(config, operation, quantities): amount = None if price is None or units is None else 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'], - source=source, sourceVersion=version, price=price, quantity=units, amount=amount) + 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/infrastructure/creation_publication.py b/packages/core/src/opendirector/infrastructure/creation_publication.py index e93a0059d..0c3a19d28 100644 --- a/packages/core/src/opendirector/infrastructure/creation_publication.py +++ b/packages/core/src/opendirector/infrastructure/creation_publication.py @@ -102,7 +102,7 @@ def _make_record(command, head, snapshot, changed, source, issue=None): event = ProjectEvent(projectId=command.projectId, cursor=snapshot.eventCursor, commandId=command.commandId, source=source, changed=changed, jobIds=job_ids) if changed else None waiting = next((item['version'].id for item in changed if item['version'].objectType == 'spend_request' - and item['change'] == 'created'), None) + 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) 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 c33704716..6e918518b 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) @@ -221,6 +223,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'))) @@ -271,11 +275,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/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 87fcc393a..df88e68b4 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.", @@ -4137,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", @@ -4156,8 +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" @@ -4253,12 +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" }, @@ -5708,6 +5783,85 @@ "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": { @@ -6045,6 +6199,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": { @@ -6169,6 +6350,47 @@ "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" + }, "HistoryRedoCommand": { "additionalProperties": false, "description": "Reapply an undone command.", @@ -10059,6 +10281,19 @@ "title": "Modelid", "type": "string" }, + "providerUrl": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Endpoint for this quoted connection.", + "title": "Providerurl" + }, "source": { "description": "Origin of the price.", "enum": [ @@ -10070,6 +10305,19 @@ "title": "Source", "type": "string" }, + "sourceUrl": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Published source for an official price.", + "title": "Sourceurl" + }, "sourceVersion": { "anyOf": [ { @@ -10095,6 +10343,16 @@ "default": null, "description": "Native unit price, when known." }, + "quantityBasis": { + "default": "fixed", + "description": "Whether the quoted quantity is an upper bound.", + "enum": [ + "fixed", + "maximum" + ], + "title": "Quantitybasis", + "type": "string" + }, "quantity": { "anyOf": [ { @@ -12235,6 +12493,24 @@ "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": [ { @@ -12280,20 +12556,46 @@ "title": "SpendCall", "type": "object" }, - "SpendPolicy": { + "SpendObservation": { "additionalProperties": false, "properties": { - "currency": { - "default": "USD", - "description": "Currency of the project spending limits.", + "callId": { + "description": "Stable physical call receiving evidence.", + "format": "uuid", + "title": "Callid", + "type": "string" + }, + "state": { + "description": "Observed execution state.", "enum": [ - "USD", - "CNY" + "submitted", + "completed", + "released" ], - "title": "Currency", + "title": "State", "type": "string" }, - "threshold": { + "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, @@ -12307,10 +12609,10 @@ } ], "default": null, - "description": "Require confirmation strictly above this batch amount.", - "title": "Threshold" + "description": "Provider units or measured output length.", + "title": "Usage" }, - "cap": { + "reported": { "anyOf": [ { "minimum": 0.0, @@ -12324,16 +12626,31 @@ } ], "default": null, - "description": "Maximum settled and reserved service spend.", - "title": "Cap" + "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": "SpendPolicy", + "required": [ + "callId", + "state" + ], + "title": "SpendObservation", "type": "object" }, - "SpendPolicyCommand": { + "SpendObservationCommand": { "additionalProperties": false, - "description": "Set project service spending controls.", + "description": "Record evidence from a model operation.", "properties": { "commandId": { "description": "Stable command ID for idempotent replay.", @@ -12348,7 +12665,117 @@ "type": "string" }, "type": { - "const": "spend.policy", + "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", + "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": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Require confirmation strictly above this batch amount.", + "title": "Threshold" + }, + "cap": { + "anyOf": [ + { + "minimum": 0.0, + "type": "number" + }, + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Maximum settled and reserved service spend.", + "title": "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" @@ -12393,6 +12820,35 @@ "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" + }, + "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, @@ -12445,6 +12901,91 @@ "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": { @@ -12656,6 +13197,20 @@ "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.", @@ -15195,6 +15750,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": { @@ -16453,6 +17085,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", @@ -16472,8 +17105,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" @@ -16569,12 +17205,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" }, @@ -16785,6 +17433,67 @@ }, "output": { "$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", + "expectedVersions", + "expectedPreview", + "payload" + ], + "title": "AdvanceGroupCommand", + "type": "object" + }, "ArtifactPublish": { "additionalProperties": false, "description": "Publish a file from a server-owned execution context without generating media.", @@ -21031,6 +21740,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", @@ -21050,8 +21760,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" @@ -21147,12 +21860,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" }, @@ -22658,6 +23383,87 @@ "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": { @@ -23011,6 +23817,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": { @@ -23146,6 +23979,49 @@ "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" + }, "HistoryRedoCommand": { "additionalProperties": false, "description": "Reapply an undone command.", @@ -27180,6 +28056,19 @@ "title": "Modelid", "type": "string" }, + "providerUrl": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Endpoint for this quoted connection.", + "title": "Providerurl" + }, "source": { "description": "Origin of the price.", "enum": [ @@ -27191,6 +28080,19 @@ "title": "Source", "type": "string" }, + "sourceUrl": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Published source for an official price.", + "title": "Sourceurl" + }, "sourceVersion": { "anyOf": [ { @@ -27216,6 +28118,16 @@ "default": null, "description": "Native unit price, when known." }, + "quantityBasis": { + "default": "fixed", + "description": "Whether the quoted quantity is an upper bound.", + "enum": [ + "fixed", + "maximum" + ], + "title": "Quantitybasis", + "type": "string" + }, "quantity": { "anyOf": [ { @@ -29404,6 +30316,24 @@ "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": [ { @@ -29440,12 +30370,162 @@ "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": { @@ -29558,6 +30638,35 @@ "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" + }, + "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, @@ -29610,6 +30719,91 @@ "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": { @@ -29826,6 +31020,20 @@ "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.", @@ -29836,6 +31044,7 @@ "required": [ "queryId", "projectId", + "agentRunId", "type" ], "title": "SpendStatusQuery", @@ -32485,6 +33694,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": { @@ -33800,6 +35088,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", @@ -33819,8 +35108,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" @@ -33916,12 +35208,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" }, diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 598321587..28ca90a72 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; @@ -440,7 +445,7 @@ 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 | SpendPolicyCommandInput | SpendReviewCommandInput | 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: SpendStatusQueryInput | GenerationQuoteQueryInput | ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | AssetPreviewQueryInput; readonly event: ProjectEventInput; @@ -576,6 +581,15 @@ 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; @@ -612,11 +626,23 @@ 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 HistoryRedoCommandInput extends CommandBaseInput { readonly type: "history.redo"; readonly payload: HistoryReplayInput; @@ -1012,9 +1038,12 @@ 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; } @@ -1274,10 +1303,25 @@ export interface SpendCallInput extends ProjectEntityInput { 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; @@ -1290,12 +1334,21 @@ export interface SpendPolicyCommandInput extends CommandBaseInput { } export interface SpendQuoteInput extends ContractInput { + readonly fromUpstream?: boolean; + readonly candidates?: number | null; + 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; @@ -1319,6 +1372,7 @@ export interface SpendReviewCommandInput extends CommandBaseInput { } export interface SpendStatusQueryInput extends QueryBaseInput { + readonly agentRunId?: string | null; readonly type: "spend.status"; } @@ -1601,6 +1655,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; @@ -1721,7 +1784,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 | SpendPolicyCommandInput | SpendReviewCommandInput | 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; @@ -1735,6 +1798,11 @@ export type ModelKindInput = "agent" | "image" | "video" | "audio" | "vision"; export type VideoModeInput = "first_frame" | "reference" | "continuation"; +export interface AdvanceGroupCommand extends CommandBase { + readonly type: "spend.advanceGroup"; + readonly payload: GroupAdvance; +} + export interface ArtifactPublish extends Contract { readonly path: string; readonly name: string; @@ -2173,7 +2241,7 @@ 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 | SpendPolicyCommand | SpendReviewCommand | 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: SpendStatusQuery | GenerationQuoteQuery | ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | AssetPreviewQuery; readonly event: ProjectEvent; @@ -2309,6 +2377,15 @@ 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; @@ -2345,11 +2422,23 @@ 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 HistoryRedoCommand extends CommandBase { readonly type: "history.redo"; readonly payload: HistoryReplay; @@ -2744,9 +2833,12 @@ 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; } @@ -3006,10 +3098,25 @@ export interface SpendCall extends ProjectEntity { 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; @@ -3022,12 +3129,21 @@ export interface SpendPolicyCommand extends CommandBase { } export interface SpendQuote extends Contract { + readonly fromUpstream?: boolean; + readonly candidates?: number | null; + 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; @@ -3051,6 +3167,7 @@ export interface SpendReviewCommand extends CommandBase { } export interface SpendStatusQuery extends QueryBase { + readonly agentRunId: string | null; readonly type: "spend.status"; } @@ -3333,6 +3450,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; @@ -3453,7 +3579,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 | SpendPolicyCommand | SpendReviewCommand | 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/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/test_creation_parameters.py b/tests/test_creation_parameters.py index 9b992df65..769493196 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 def png(size=(32, 24), color='blue'): @@ -395,7 +395,11 @@ def handler(request): ('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 == [] - _,receipt=await submit(project,runner,target,spec_id) + 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] @@ -416,6 +420,40 @@ def handler(request): 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_minimax_speech.py b/tests/test_minimax_speech.py index 28d4032e4..83704914e 100644 --- a/tests/test_minimax_speech.py +++ b/tests/test_minimax_speech.py @@ -380,11 +380,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) @@ -392,6 +393,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 @@ -412,6 +415,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 index 2bfe6bf26..bddabdb2e 100644 --- a/tests/test_spend_admission.py +++ b/tests/test_spend_admission.py @@ -1,12 +1,13 @@ import asyncio import base64 +import shutil from decimal import Decimal from uuid import uuid4 import httpx import pytest -from generation_helpers import command +from generation_helpers import 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 @@ -14,7 +15,7 @@ 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, ver +from test_creation_canvas_service import project, send, ver from test_creation_generation_service import anyio_backend from test_creation_parameters import done, png @@ -51,19 +52,8 @@ async def no_dispatch(*args, **kwargs): await runner.close() -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)) - - @pytest.mark.anyio -async def test_atomic_batch_approval_race_replay_and_cap_raise(project): +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') @@ -85,6 +75,9 @@ async def provider(request): 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] @@ -107,6 +100,24 @@ async def provider(request): 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') + 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..f9b52d96d --- /dev/null +++ b/tests/test_spend_cli.py @@ -0,0 +1,49 @@ +import json +from decimal import Decimal +from uuid import uuid4 + +import httpx +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 + + +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 index dcd37bb1e..c36c8b33a 100644 --- a/tests/test_spend_prices.py +++ b/tests/test_spend_prices.py @@ -1,7 +1,8 @@ +from datetime import datetime, timezone from decimal import Decimal from uuid import uuid4 -from opendirector.domain.creation.spend import OFFICIAL_URL, SpendQuote, price_line +from opendirector.domain.creation.spend import OFFICIAL_URL, SpendCall, SpendObservation, SpendQuote, observed_call, price_line def test_connection_price_takes_precedence_and_an_alias_is_unpriced(): @@ -20,3 +21,17 @@ def test_connection_price_takes_precedence_and_an_alias_is_unpriced(): 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_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..e3f4bd6d4 --- /dev/null +++ b/tests/test_spend_workflows.py @@ -0,0 +1,186 @@ +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 +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_tasks import ToolTasks +from opendirector.domain.creation.commands import 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 SAM3, ZIMAGE, configure, images_server, segmentation_server, upload + + +@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 [])]))) + 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 waiting.quote.total('USD') == (Decimal('.4') if dependent else Decimal('.8')) + 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] + 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_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() + + +@pytest.mark.anyio +async def test_selection_review_reuses_masks_and_accounts_physical_calls(project): + store, pid, session = project + configs = configure(store, SAM3) + model = configs.list()[0] + configs.set_price(model['id'], dict(unit='request', rate='.40', currency='USD')) + asset = upload(store, str(pid), session, 'source.png', png()) + requests = [] + service = ToolTasks(store.local, configs, CreationToolAssets(store), projects=store, + transport=httpx.MockTransport(segmentation_server(requests, {'person':[(.9, (0, 0, 12, 16))]}))) + 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, animal') + answer = await service.selection_preview(str(pid), value, session) + assert answer['status'] == 'awaiting_confirmation' and not requests and not store.snapshot(pid).spendCalls + waiting = store.snapshot(pid).spendRequests[-1] + assert waiting.quote.total('USD') == Decimal('.80') + await runner.execute(review(pid, waiting), session=session) + result = await service.selection_preview(str(pid), value, session) + assert result['instances'] and len(requests) == 2 and not service.list(str(pid)) + assert review_status(store.snapshot(pid))['settled'] == Decimal('.80') + 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') + finally: + await restored.close() From 92efc613db5af00ca73c40b65d62cba63ba68ab9 Mon Sep 17 00:00:00 2001 From: bread-lxy <2022200058@ruc.edu.cn> Date: Sun, 22 Nov 2026 11:47:36 +0800 Subject: [PATCH 05/15] [feat] Review workflow charges and settled usage in the canvas and chat --- README.md | 1 + README.zh-CN.md | 1 + docs/guides/user-guide.md | 10 ++ docs/guides/user-guide.zh-CN.md | 10 ++ src/backend/imageSelections.ts | 20 +++- src/backend/spend.ts | 5 +- src/backend/tools.ts | 6 +- src/canvas/AssistantPanel.tsx | 3 +- src/canvas/NodeComposer.tsx | 2 +- src/canvas/ProjectSpend.tsx | 95 ++++++++++++++++--- src/canvas/groupWorkflow.ts | 25 +++-- src/canvas/workspace/WorkspaceView.tsx | 4 +- .../workspace/useWorkspaceGeneration.ts | 32 ++++++- src/i18n/messages/en-US/generation.ts | 26 +++++ src/i18n/messages/zh-CN/generation.ts | 26 +++++ tests/browser/project_spend.mjs | 31 +++++- 16 files changed, 266 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 78f8f7cdd..dfdf34e04 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Use it to explore visual ideas, refine assets, and make short films. Projects st - **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 1cb915efc..495db914c 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -31,6 +31,7 @@ OpenDirector 是一个在本地运行、通过浏览器使用的 AI 视频创作 - **与 AI 协作**:描述创作要求,引用画布素材,让助手保存文本并调用已配置的模型生成内容。 - **画布与参考素材**:上传文件、连接节点或用 `@` 添加参考,集中整理素材并查看生成历史。 +- **工程费用**。查看整批候选的预计服务费,设置工程上限,在画布或助手对话中确认费用。[费用设置](docs/guides/user-guide.zh-CN.md#工程费用) - **媒体编辑**:裁剪、调色、处理图层和片段;扩图、消除、抠图等 AI 工具按已接入模型的能力提供。 - **图像预设**:选中图片后,从「预设」选择人物三视图、人物四视图、面部三视图、产品三视图、连续分镜图或多机位,再点「生成」。人物四视图在正面、侧面和背面全身图的右侧加入正脸特写;勾选「脸部强调」后,会提示模型只拍摄正面和侧面从下巴到鞋底的部分,保留完整的背面全身和正脸特写。三视图和四视图各输出一张参考板;连续分镜图和多机位各输出四张独立图片,并关联原图。 - **时间线编排**:安排素材顺序、起止点、速度和音量,预览并合成 MP4,也可导出 JSON、FCPXML 和素材包。 diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index ac928883a..f098189c5 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -123,6 +123,16 @@ 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 + +Open **Project spend** on the canvas. A generation estimate lists the selected model, pricing unit, candidate 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. This 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. + +Set **Confirm above** for human review when an entire batch exceeds that amount. **Project cap** also counts accepted calls awaiting settlement. Review the batch in the canvas or chat. When the cap is insufficient, the card shows the balance and shortfall. Raising the cap and starting the batch is one action. With a cap enabled, calls with an unknown maximum require a price in the project currency. 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 8b4a0f1ef..9cda8c336 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -123,6 +123,16 @@ MiniMax 配音使用[同步语音合成接口](https://platform.minimax.cn/docs/ Agent 通过 `voice_list`、`voice_create`、`voice_delete` 使用同一套校验;[业务 CLI](cli.md) 也提供 `voice list`、`voice create`、`voice delete`。 +## 工程费用 + +在画布打开「工程费用」。生成报价列出模型、计价单位、候选数量和整批金额。使用参考录音生成音乐时,转谱和音乐生成各有一笔报价。开启跟随参考时长后,音乐生成使用模型实际采用的时长上限。展开媒体编辑工具的报价,可以看到各次模型调用。 + +在「模型接入」中可以给单个模型设置计价单位、单价和币种。连接单价优先于内置官方价格。官方价格只适用于明确对应的服务地址和模型。自托管连接默认服务费为零。缺价步骤和不同币种分别显示。工程费用记录涵盖媒体服务调用,设备开支和助手订阅单独计算。 + +整批估价超过「单批确认阈值」时,用户可以在画布或助手对话中批准或取消。「工程上限」同时计算已结算费用和已受理调用的预留金额。余额不足时,确认卡显示余额和差额,可以一次提高上限并运行整批。开启上限后,最高费用未知的调用需要先配置使用工程币种的价格。有依赖的分组可以先批准已报价的上游步骤,取得素材后再查看下游报价。命令行返回本地确认页面地址,使用 `query spend.status` 可查看当前决定。 + +费用记录保留原估价、根据已确认用量计算的金额,以及服务明确报告的金额。服务响应丢失时,相应调用等待核实。恢复完整工程备份会保留费用记录。将素材导入新工程时,新工程独立记录自己的调用。撤销画布编辑会保留已经发生的费用。 + ## 查看和处理生成任务 打开右上角“生成历史”,查看任务进度、结果和失败原因。 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/spend.ts b/src/backend/spend.ts index f996bedb0..896ec070d 100644 --- a/src/backend/spend.ts +++ b/src/backend/spend.ts @@ -8,14 +8,16 @@ export interface QuoteView { currency: SpendPolicy["currency"]; amount: string | null; projectAfter: string | null; + subtotals: Record; } export interface PendingSpend { request: SpendRequest; fingerprint: string; - reason: "ready" | "confirmation" | "unknown_confirmation" | "unpriced" | "over_cap"; + reason: "ready" | "stale" | "upstream_confirmation" | "confirmation" | "unknown_confirmation" | "unpriced" | "over_cap"; amount: string | null; shortfall: string | null; + subtotals: Record; } export interface SpendStatus { @@ -28,6 +30,7 @@ export interface SpendStatus { since: string | null; projectRevision: number; pending: PendingSpend[]; + turn?: { callCount: number; settled: string; held: string; unknown: number }; } export function spendQuery(projectId: string, type: "spend.status" | "generation.quote", fields = {}, signal?: AbortSignal) { 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 d583bd7f5..7e0a3f628 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -8,7 +8,7 @@ import { loadReferenceCatalog } from "../backend/referenceCatalog.ts"; import "./assistant-panel.css"; import "./assistant-experience.css"; import { AttachmentStrip, AttachmentHover } from "./AssistantMedia"; -import { ProjectSpend } from "./ProjectSpend"; +import { ProjectSpend, TurnSpend } from "./ProjectSpend"; import { AssistantReply } from "./AssistantReply"; import { AssistantConversations } from "./AssistantConversations"; import { AgentPicker } from "./AgentPicker"; @@ -438,6 +438,7 @@ export function AssistantPanel({ : message.model}}
)} + {open && message.role === "assistant" && previous?.role === "user" && }
{message.role === "assistant" ? ( diff --git a/src/canvas/NodeComposer.tsx b/src/canvas/NodeComposer.tsx index 24f345fa0..bcb4e4051 100644 --- a/src/canvas/NodeComposer.tsx +++ b/src/canvas/NodeComposer.tsx @@ -288,7 +288,7 @@ export function NodeComposer({ >
{projectId && config && canRun && m.price))} />} + draft={settings} prompt={settings.prompt ?? ""} count={mode === "audio" ? 1 : settings.count ?? 1} priceRevision={JSON.stringify(backendModels.map(m => m.price))} />} {firstLast && (
{( diff --git a/src/canvas/ProjectSpend.tsx b/src/canvas/ProjectSpend.tsx index 3f2369132..e8b0049ee 100644 --- a/src/canvas/ProjectSpend.tsx +++ b/src/canvas/ProjectSpend.tsx @@ -1,3 +1,4 @@ +import type { GenerationSettings } from "./model.ts"; import { useCallback, useEffect, useState, useSyncExternalStore } from "react"; import { errorMessage, json, request } from "../backend/api.ts"; import { creationClient, objectVersion } from "../backend/creationClient.ts"; @@ -22,12 +23,39 @@ function QuoteLines({ quote }: { quote: SpendQuote }) { return
    {quote.lines.map((line, index) =>
  • {t(`spend.operation.${line.operation}` as "spend.operation.image")} · {line.modelId} {line.price && line.amount != null ? money(line.amount, line.price.currency, locale) : t("spend.unknown")} - {line.price && {t(`spend.source.${line.source}`)} · {line.quantity ?? "?"} × {line.price.rate} {line.price.currency} / {t(`spend.unit.${line.price.unit}`)}} + {line.price == null && {t("spend.noRate")}} + {line.price && line.amount == null && {t("spend.missingUnits")}} + {line.price && {t(`spend.source.${line.source}`)} · {line.quantityBasis === "maximum" && "≤ "}{line.quantity ?? "?"} × {line.price.rate} {line.price.currency} / {t(`spend.unit.${line.price.unit}`)}{line.sourceUrl && <> · {line.sourceVersion}}}
  • )}
; } -export function GenerationEstimate({ projectId, itemId, count, modelId, prompt, priceRevision }: { - projectId: string; itemId: string; count: number; modelId: string; prompt: string; priceRevision: string; +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); @@ -37,7 +65,12 @@ export function GenerationEstimate({ projectId, itemId, count, modelId, prompt, 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; + 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(); @@ -53,10 +86,41 @@ export function GenerationEstimate({ projectId, itemId, count, modelId, prompt, return
{t("spend.estimate", { 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 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 } = saved.value; + return
{t("spend.toolQuote", { amount: amount == null ? t("spend.unknown") : money(amount, currency, locale) })} + {amount == null && }
; +} + function ReviewCard({ projectId, entry, status, onSettings, onChange }: { projectId: string; entry: PendingSpend; status: SpendStatus; onSettings?: () => void; onChange: () => void; }) { @@ -82,17 +146,19 @@ function ReviewCard({ projectId, entry, status, onSettings, onChange }: { finally { setBusy(false); onChange(); } }; return
- {t("spend.estimate", { count: batch.quote.count, amount: entry.amount == null ? t("spend.unknown") : money(entry.amount, currency, locale) })} - + {t("spend.estimate", { count: batch.quote.candidates ?? batch.quote.count, amount: entry.amount == null ? t("spend.unknown") : money(entry.amount, currency, locale) })} + {entry.amount == null && } + {!!batch.quote.deferred?.length &&

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

} {reason === "over_cap" && <>

{t("spend.shortfall", { cap: money(status.policy.cap!, currency, locale), available: money(status.available!, currency, locale), missing: money(entry.shortfall!, currency, locale) })}

} {reason === "unpriced" &&

{t("spend.needPrice")}

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

{t("spend.stale")}

}
- {reason === "unpriced" ? onSettings && : + {reason === "stale" ? null : reason === "unpriced" ? onSettings && : }
@@ -131,6 +197,12 @@ export function ProjectSpend({ projectId, placement, onSettings }: { const [status, setStatus] = useState(); const [error, setError] = useState(""); const [revision, reload] = useState(0); + useEffect(() => { + if (placement !== "canvas") return; + const reveal = (event: Event) => { if ((event as CustomEvent).detail === projectId) setOpen(true); }; + window.addEventListener("opendirector:spend-review", reveal); + return () => window.removeEventListener("opendirector:spend-review", reveal); + }, [placement, projectId]); const shown = open || (placement === "chat" && pendingCount > 0); useEffect(() => { if (!shown || !snapshot) return; @@ -151,16 +223,17 @@ export function ProjectSpend({ projectId, placement, onSettings }: { {status && <>

{t("spend.summary", { settled: money(status.settled, status.policy.currency, locale), held: money(status.held, status.policy.currency, locale) })}

{(status.legacy > 0 || status.unknown > 0) &&

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

} - {status.pending.map(entry => snapshot?.spendRequests?.some(r => r.id === entry.request.id && r.status === "pending")).map(entry => reload(r => r + 1)} />)} {placement !== "chat" && <>
{t("spend.controls")}
{t("spend.log")} {status.since && {t("spend.since", { date: new Date(status.since).toLocaleString(locale) })}}
    {[...(snapshot?.spendCalls ?? [])].reverse().map(call =>
  • - {call.line.modelId} · {t(`spend.state.${call.state}`)} + {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}}
  • )}
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/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx index e1a169864..d05d6c756 100644 --- a/src/canvas/workspace/WorkspaceView.tsx +++ b/src/canvas/workspace/WorkspaceView.tsx @@ -1,5 +1,6 @@ import { projectDisplayName } from "../projectDisplayName"; -import { ProjectSpend } from "../ProjectSpend"; +import type { ModelConfig } from "../../backend/rules.ts"; +import { ProjectSpend, ToolEstimate } from "../ProjectSpend"; import { DesktopSidebar } from "./DesktopSidebar"; import { Background, BackgroundVariant, MiniMap, SelectionMode, ViewportPortal } from "@xyflow/react"; @@ -1725,6 +1726,7 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { onGenerate={(task) => void runToolTask(activeAction, task)} /> )} + m.price))} />
)} diff --git a/src/canvas/workspace/useWorkspaceGeneration.ts b/src/canvas/workspace/useWorkspaceGeneration.ts index 84430b7b4..5c71d093a 100644 --- a/src/canvas/workspace/useWorkspaceGeneration.ts +++ b/src/canvas/workspace/useWorkspaceGeneration.ts @@ -1,6 +1,6 @@ import { useEffect, useRef } from "react"; import { errorMessage } from "../../backend/api.ts"; -import { creationClient } from "../../backend/creationClient.ts"; +import { creationClient, objectVersion } from "../../backend/creationClient.ts"; import { type GenerationRequest } from "../../backend/generation.ts"; import { modelLabel } from "../../backend/rules.ts"; import { workspaceProjection } from "../../backend/workspace.ts"; @@ -16,7 +16,7 @@ import { imageAnnotationPayload } from "../imageActionPayload"; import { appendPendingResult, removePendingResult, validateNodeActionSource, type GenerationResultMode, type LinkedMediaResult, type ResultSource } from "../linkedResults"; import { type CanvasNode } from "../model"; import { groupDescendants } from "../operations"; -import { runWorkflowSteps } from "../groupWorkflow"; +import { runWorkflowSteps, workflowDependencies } from "../groupWorkflow"; import { getNodeGenerationSettings } from "../NodeComposer"; import { serviceGenerationPlan, textGenerationPlan } from "../workspaceInteraction.ts"; import { generationPrepareBlock } from "./entryPoints.ts"; @@ -384,6 +384,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()); @@ -731,6 +736,29 @@ export function useWorkspaceGeneration(rt: WorkspaceRuntime) { notify(t("canvas.workspace.group.noRunnableNodes")); return; } + const client = creationClient(document.id); + const policy = client.snapshot.project.spendPolicy; + if (policy && (policy.cap != null || policy.threshold != null)) { + try { + if (!await persist(document)) return; + const snapshot = await client.refresh(); + const dependencies = workflowDependencies(steps.map(node => node.id), document.edges); + const members = steps.map(node => { + 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) throw new Error(t("errors.backend.noGenerationConfig")); + const count = node.type === "image" || node.type === "video" ? getNodeGenerationSettings(node, backendCatalog.models).count ?? 1 : 1; + return { item, spec, count }; + }); + const receipt = await client.command("generation.group", { + members: members.map(({item, spec, count}) => ({ itemId: item.id, specId: spec.id, count, after: [...dependencies.get(item.id)!] })), + }, members.flatMap(({item, spec}) => [objectVersion("canvas_item", item), objectVersion("generation_spec", spec)])); + notify(receipt.status === "awaiting_confirmation" ? t("spend.waiting") : t("canvas.workspace.group.workflowStarted", { count: steps.length })); + } catch (failure) { notify(errorMessage(failure)); } + return; + } notify(t("canvas.workspace.group.workflowStarted", { count: steps.length })); let submissions: Promise = Promise.resolve(); const result = await runWorkflowSteps( diff --git a/src/i18n/messages/en-US/generation.ts b/src/i18n/messages/en-US/generation.ts index f6d889a9e..cfdcf14db 100644 --- a/src/i18n/messages/en-US/generation.ts +++ b/src/i18n/messages/en-US/generation.ts @@ -30,6 +30,10 @@ export const generation = { "spend.price": "Unit price", "spend.automatic": "Automatic", "spend.unit": "Billing unit", + "spend.previewStopped": "The selection preview stopped. Check its call history in Project spend.", + "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.waiting": "The batch is waiting for spend review.", "spend.unit.request": "request", "spend.unit.input_character": "input character", @@ -40,6 +44,28 @@ export const generation = { "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", diff --git a/src/i18n/messages/zh-CN/generation.ts b/src/i18n/messages/zh-CN/generation.ts index 3b42819bf..bbc062605 100644 --- a/src/i18n/messages/zh-CN/generation.ts +++ b/src/i18n/messages/zh-CN/generation.ts @@ -30,6 +30,10 @@ export const generation = { "spend.price": "单价", "spend.automatic": "自动", "spend.unit": "计费单位", + "spend.previewStopped": "选区预览已停止,可在工程费用中查看调用记录。", + "spend.deferred": "还有 {count} 个下游步骤需要先取得上游结果,才能估算费用。", + "spend.runUpstream": "运行已报价的上游步骤", + "spend.stale": "工程币种已变更。请取消此申请并重新报价。", "spend.waiting": "本批正在等待费用确认。", "spend.unit.request": "次", "spend.unit.input_character": "输入字符", @@ -40,6 +44,28 @@ export const generation = { "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": "语音合成", diff --git a/tests/browser/project_spend.mjs b/tests/browser/project_spend.mjs index 26bd481e3..a45d69892 100644 --- a/tests/browser/project_spend.mjs +++ b/tests/browser/project_spend.mjs @@ -94,8 +94,37 @@ try { 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 second batch above the remaining cap, then review it from chat. + const controls = page.locator(".cw-spend-canvas"); + 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); + 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"); + const assistant = page.locator("#canvas-assistant"); + if (!await assistant.isVisible()) await page.locator(".cw-chat-button").click(); + const card = assistant.locator(".cw-spend-card"); + await card.getByText(/0\.80/).waitFor(); + await card.getByRole("button", {name: en ? "Cancel request" : "取消申请"}).click(); + await until(() => call(path), s => s.spendRequests.at(-1).status === "cancelled"); + assert.equal(posts.length - before, 3); + const third = await second(); + assert.equal(third.status, "awaiting_confirmation"); + const current = assistant.locator(`[data-spend-request="${third.spendRequestId}"]`); + await current.getByLabel(en ? "New project cap" : "新的工程上限").fill("2.40"); + await current.getByRole("button", {name: en ? "Raise cap and run this batch" : "提高上限并运行本批"}).click(); + 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, "USD 1.20 shown; 0 calls pending; 3 jobs and 3 provider requests"); + console.log(locale, "USD 1.20 batch, zero calls pending, cancellation, USD 0.40 shortfall, chat approval, six settled calls"); await page.close(); } } finally { From 27278d2f86bb891f1fdffa0dcf19a585f6a09808 Mon Sep 17 00:00:00 2001 From: bread-lxy <2022200058@ruc.edu.cn> Date: Sun, 22 Nov 2026 12:07:54 +0800 Subject: [PATCH 06/15] [fix] Price canvas workflows together against the saved project budget --- docs/guides/user-guide.md | 2 +- docs/guides/user-guide.zh-CN.md | 2 +- packages/core/src/opendirector/agent/tools.py | 2 +- .../application/creation_canvas.py | 14 +- .../application/creation_generation.py | 2 +- .../application/creation_groups.py | 101 ++++++++--- .../application/creation_spend.py | 52 +++++- .../opendirector/application/tool_tasks.py | 9 + .../opendirector/domain/creation/commands.py | 7 +- .../src/opendirector/domain/creation/spend.py | 5 +- src/backend/spend.ts | 5 +- src/canvas/NodeSelectionToolbar.tsx | 6 +- src/canvas/ProjectSpend.tsx | 38 +++- src/canvas/project-spend.css | 1 + src/canvas/workspace/WorkspaceView.tsx | 14 +- .../workspace/useWorkspaceGeneration.ts | 167 ++---------------- src/canvas/workspace/workflowMembers.ts | 35 ++++ src/contracts/creation.schema.json | 106 +++++++++++ src/contracts/generated.ts | 16 +- src/i18n/messages/en-US/generation.ts | 9 + src/i18n/messages/zh-CN/generation.ts | 9 + tests/browser/project_spend.mjs | 40 +++++ tests/test_creation_parameters.py | 49 ++++- tests/test_spend_prices.py | 8 +- tests/test_spend_workflows.py | 52 +++++- 25 files changed, 539 insertions(+), 212 deletions(-) create mode 100644 src/canvas/workspace/workflowMembers.ts diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index f098189c5..8b3a58417 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -129,7 +129,7 @@ Open **Project spend** on the canvas. A generation estimate lists the selected m In **Model connections**, set a unit price and currency for an individual model. This 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. -Set **Confirm above** for human review when an entire batch exceeds that amount. **Project cap** also counts accepted calls awaiting settlement. Review the batch in the canvas or chat. When the cap is insufficient, the card shows the balance and shortfall. Raising the cap and starting the batch is one action. With a cap enabled, calls with an unknown maximum require a price in the project currency. 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`. +Set **Confirm above** for human review when an entire batch exceeds that amount. **Project cap** also counts accepted calls awaiting settlement. Review the batch in the canvas or chat. When the cap is insufficient, the card shows the balance and shortfall. Raising the cap and starting the batch is one action. 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. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 9cda8c336..e12aefe2d 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -129,7 +129,7 @@ Agent 通过 `voice_list`、`voice_create`、`voice_delete` 使用同一套校 在「模型接入」中可以给单个模型设置计价单位、单价和币种。连接单价优先于内置官方价格。官方价格只适用于明确对应的服务地址和模型。自托管连接默认服务费为零。缺价步骤和不同币种分别显示。工程费用记录涵盖媒体服务调用,设备开支和助手订阅单独计算。 -整批估价超过「单批确认阈值」时,用户可以在画布或助手对话中批准或取消。「工程上限」同时计算已结算费用和已受理调用的预留金额。余额不足时,确认卡显示余额和差额,可以一次提高上限并运行整批。开启上限后,最高费用未知的调用需要先配置使用工程币种的价格。有依赖的分组可以先批准已报价的上游步骤,取得素材后再查看下游报价。命令行返回本地确认页面地址,使用 `query spend.status` 可查看当前决定。 +整批估价超过「单批确认阈值」时,用户可以在画布或助手对话中批准或取消。「工程上限」同时计算已结算费用和已受理调用的预留金额。余额不足时,确认卡显示余额和差额,可以一次提高上限并运行整批。开启上限后,最高费用未知的调用需要先配置使用工程币种的价格。选择分组即可查看可执行步骤的小计和仍在等待输入的步骤数。有依赖的分组可以先批准已报价的上游步骤,取得素材后再查看下游报价。命令行返回本地确认页面地址,使用 `query spend.status` 可查看当前决定。 费用记录保留原估价、根据已确认用量计算的金额,以及服务明确报告的金额。服务响应丢失时,相应调用等待核实。恢复完整工程备份会保留费用记录。将素材导入新工程时,新工程独立记录自己的调用。撤销画布编辑会保留已经发生的费用。 diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index 1c79b9c19..14f2c779c 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -60,7 +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 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. +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. diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index c655fb5f4..97eae1142 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -845,7 +845,19 @@ def projection(self, project_id, snapshot=None): async def query(self, query: Query) -> JsonValue: if query.type == 'spend.status': from opendirector.application.creation_spend import review_status - return to_jsonable_python(await asyncio.to_thread(lambda: review_status(self.projects.snapshot(query.projectId), query.agentRunId))) + 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) diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 62a71959c..856dbe785 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -510,7 +510,7 @@ def prepare(self, command, *, session=None, source='ui', agent_origin=None, revi def accept(before): if review is not None: validate_command(command, before) - elif any(r.status == 'pending' and ( + 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): diff --git a/packages/core/src/opendirector/application/creation_groups.py b/packages/core/src/opendirector/application/creation_groups.py index f1f86c302..da2a15a12 100644 --- a/packages/core/src/opendirector/application/creation_groups.py +++ b/packages/core/src/opendirector/application/creation_groups.py @@ -2,6 +2,7 @@ import asyncio import logging from datetime import datetime, timezone +from graphlib import CycleError, TopologicalSorter from hashlib import sha256 from uuid import uuid5 @@ -16,26 +17,74 @@ def _member(snapshot, member, workflow): 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 - items = {m.itemId for m in plan.payload.members} decisions = [r for r in snapshot.spendRequests if r.workflowId == workflow] - if any(r.status != 'accepted' for r in decisions): - return [], [] - admitted = {i for r in decisions for i in r.groupItems} - jobs = [j for j in snapshot.jobs if j.batchId == workflow and j.originItemId in items] - if any(j.status in {'queued', 'running'} for j in jobs): - return [], [] + 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'} - remaining = [m for m in plan.payload.members if m.itemId not in admitted] - ready = [m for m in remaining if set(m.after) <= finished] - return ready, [m.itemId for m in remaining if m not in ready] + 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): @@ -47,34 +96,28 @@ def _prepare(runtime, command, plan, session, source, origin, review): 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 = request.quote.deferred + deferred, skipped = request.quote.deferred, request.quote.skipped else: - members, deferred = _wave(initial, plan) + 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 = before - lines, prints = [], [] - candidates = 0 - for m in members: - member = _member(before, m, plan.commandId) - validate_command(member, before) - data, job, config, task, records = runtime._propose_job(draft, member, agent_origin=origin, checks=checks[m.itemId]) - 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) - 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, fromUpstream=command.type == 'spend.advanceGroup', - inputFingerprint=sha256('|'.join(prints).encode()).hexdigest(), lines=lines) + 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)) @@ -129,7 +172,7 @@ async def advance(): else: await asyncio.sleep(1) continue - members, _ = _wave(snapshot, plan) + members, _, _ = _wave(snapshot, plan) if not members: return ids = [m.itemId for m in members] diff --git a/packages/core/src/opendirector/application/creation_spend.py b/packages/core/src/opendirector/application/creation_spend.py index 579451e17..51bfe5af2 100644 --- a/packages/core/src/opendirector/application/creation_spend.py +++ b/packages/core/src/opendirector/application/creation_spend.py @@ -1,4 +1,5 @@ """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 @@ -13,10 +14,42 @@ def quote_view(snapshot, quote): summary = spend_summary(snapshot) total = quote.total(summary['policy'].currency) return dict(quote=quote, fingerprint=quote.fingerprint(), amount=total, subtotals=quote.subtotals(), - projectAfter=None if total is None else summary['settled'] + summary['held'] + total, + projectAfter=None if total is None or summary['unknown'] else summary['settled'] + summary['held'] + total, 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'] @@ -28,7 +61,7 @@ def review_status(snapshot, agent_run_id=None): reason = spend_decision(summary, request.quote) pending.append(dict(request=request, fingerprint=request.quote.fingerprint(), reason='stale' if request.currency and request.currency != policy.currency else reason, amount=total, subtotals=request.quote.subtotals(), shortfall=total-summary['available'] if reason == 'over_cap' else None)) - result = dict(**summary, projectRevision=snapshot.project.revision, pending=pending) + result = dict(**summary, projectRevision=snapshot.project.revision, pending=pending, workflows=workflow_status(snapshot, agent_run_id)) 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] @@ -50,6 +83,19 @@ def get_request(snapshot, 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) @@ -67,6 +113,8 @@ def decide(before, command, quote, agent_origin, review=None): 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: diff --git a/packages/core/src/opendirector/application/tool_tasks.py b/packages/core/src/opendirector/application/tool_tasks.py index 3d82249c3..f12bbcad4 100644 --- a/packages/core/src/opendirector/application/tool_tasks.py +++ b/packages/core/src/opendirector/application/tool_tasks.py @@ -260,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. diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index fab80041b..f8767e64a 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -498,6 +498,11 @@ 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.') @@ -550,7 +555,7 @@ class AssetPreviewQuery(QueryBase): objectId: UUID = Field(description='Asset ID.') -Query = Annotated[SpendStatusQuery | GenerationQuoteQuery | 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/spend.py b/packages/core/src/opendirector/domain/creation/spend.py index a6887e4a4..0491e6988 100644 --- a/packages/core/src/opendirector/domain/creation/spend.py +++ b/packages/core/src/opendirector/domain/creation/spend.py @@ -36,6 +36,7 @@ class PriceLine(Contract): 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.') @@ -155,7 +156,7 @@ def spend_summary(snapshot): totals = call_totals(snapshot.spendCalls, policy.currency) owners = {call.ownerId for call in snapshot.spendCalls} return dict(policy=policy, **totals, - available=None if policy.cap is None else policy.cap - totals['settled'] - totals['held'], + available=None if policy.cap is None or totals['unknown'] else policy.cap - totals['settled'] - totals['held'], 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)) @@ -169,7 +170,7 @@ def spend_decision(summary, quote): 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 'unpriced' + return 'prior_unknown' if policy.cap is not None and amount > summary['available']: return 'over_cap' if controlled and quote.deferred: diff --git a/src/backend/spend.ts b/src/backend/spend.ts index 896ec070d..08ca41fbb 100644 --- a/src/backend/spend.ts +++ b/src/backend/spend.ts @@ -14,7 +14,7 @@ export interface QuoteView { export interface PendingSpend { request: SpendRequest; fingerprint: string; - reason: "ready" | "stale" | "upstream_confirmation" | "confirmation" | "unknown_confirmation" | "unpriced" | "over_cap"; + reason: "ready" | "stale" | "upstream_confirmation" | "confirmation" | "unknown_confirmation" | "unpriced" | "prior_unknown" | "over_cap"; amount: string | null; shortfall: string | null; subtotals: Record; @@ -30,10 +30,11 @@ export interface SpendStatus { 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", fields = {}, signal?: AbortSignal) { +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/canvas/NodeSelectionToolbar.tsx b/src/canvas/NodeSelectionToolbar.tsx index 29641e0fa..0eec0a86c 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 index e8b0049ee..264d38340 100644 --- a/src/canvas/ProjectSpend.tsx +++ b/src/canvas/ProjectSpend.tsx @@ -1,4 +1,5 @@ -import type { GenerationSettings } from "./model.ts"; +import { workflowRequest } from "./workspace/workflowMembers.ts"; +import type { CanvasDocument, GenerationSettings } from "./model.ts"; import { useCallback, useEffect, useState, useSyncExternalStore } from "react"; import { errorMessage, json, request } from "../backend/api.ts"; import { creationClient, objectVersion } from "../backend/creationClient.ts"; @@ -90,6 +91,34 @@ export function GenerationEstimate({ projectId, itemId, count, modelId, prompt, ; } +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 } = result.value; + return
+ {t("spend.estimate", {count: quote.candidates ?? quote.count, amount: amount == null ? t("spend.unknown") : money(amount, 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; }) { @@ -149,14 +178,16 @@ function ReviewCard({ projectId, entry, status, onSettings, onChange }: { {t("spend.estimate", { count: batch.quote.candidates ?? batch.quote.count, amount: entry.amount == null ? t("spend.unknown") : money(entry.amount, currency, locale) })} {entry.amount == null && } {!!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", { cap: money(status.policy.cap!, currency, locale), available: money(status.available!, currency, locale), missing: money(entry.shortfall!, currency, locale) })}

} {reason === "unpriced" &&

{t("spend.needPrice")}

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

{t("spend.priorUnknown")}

} {reason === "stale" &&

{t("spend.stale")}

}
- {reason === "stale" ? null : reason === "unpriced" ? onSettings && : + {reason === "stale" || reason === "prior_unknown" ? null : reason === "unpriced" ? onSettings && : } @@ -228,6 +259,9 @@ export function ProjectSpend({ projectId, placement, onSettings }: { {placement !== "chat" && <>
{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}`)} diff --git a/src/canvas/project-spend.css b/src/canvas/project-spend.css index 2ce91bada..8783fd709 100644 --- a/src/canvas/project-spend.css +++ b/src/canvas/project-spend.css @@ -17,4 +17,5 @@ .cw-spend-form label, .cw-spend-card label { display: flex; align-items: center; justify-content: space-between; gap: 8px; } .cw-spend-form input, .cw-spend-form select, .cw-spend-card input { width: 9em; padding: 4px; } .cw-spend-actions button, .cw-spend-form button { background: #edf1f5; color: #233245; padding: 5px 10px; border: 0; border-radius: 6px; cursor: pointer; } +.cw-group-estimate { width: max-content; max-width: 320px; max-height: 32vh; overflow: auto; background: white; border: 1px solid #cad0d7; border-radius: 8px; padding: 5px 9px; pointer-events: auto; } .cw-spend-estimate { font-size: 12px; color: #465363; } diff --git a/src/canvas/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx index d05d6c756..1ba92d420 100644 --- a/src/canvas/workspace/WorkspaceView.tsx +++ b/src/canvas/workspace/WorkspaceView.tsx @@ -1,6 +1,6 @@ import { projectDisplayName } from "../projectDisplayName"; import type { ModelConfig } from "../../backend/rules.ts"; -import { ProjectSpend, ToolEstimate } from "../ProjectSpend"; +import { GroupEstimate, ProjectSpend, ToolEstimate } from "../ProjectSpend"; import { DesktopSidebar } from "./DesktopSidebar"; import { Background, BackgroundVariant, MiniMap, SelectionMode, ViewportPortal } from "@xyflow/react"; @@ -80,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"; @@ -399,6 +399,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)); @@ -1534,7 +1540,8 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { single.type === "group" ? void downloadGroup(single) : downloadNode(single) } onRunWorkflow={single.type === "group" ? () => 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" @@ -1565,6 +1572,7 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { } onDuplicate={() => paste(true)} /> + {single.type === "group" && }
)} {activeAction && actionNode && ( diff --git a/src/canvas/workspace/useWorkspaceGeneration.ts b/src/canvas/workspace/useWorkspaceGeneration.ts index 5c71d093a..5b812c975 100644 --- a/src/canvas/workspace/useWorkspaceGeneration.ts +++ b/src/canvas/workspace/useWorkspaceGeneration.ts @@ -1,6 +1,6 @@ import { useEffect, useRef } from "react"; import { errorMessage } from "../../backend/api.ts"; -import { creationClient, objectVersion } from "../../backend/creationClient.ts"; +import { creationClient } from "../../backend/creationClient.ts"; import { type GenerationRequest } from "../../backend/generation.ts"; import { modelLabel } from "../../backend/rules.ts"; import { workspaceProjection } from "../../backend/workspace.ts"; @@ -15,9 +15,8 @@ import { lockedNodeIds } from "../hierarchy"; import { imageAnnotationPayload } from "../imageActionPayload"; import { appendPendingResult, removePendingResult, validateNodeActionSource, type GenerationResultMode, type LinkedMediaResult, type ResultSource } from "../linkedResults"; import { type CanvasNode } from "../model"; -import { groupDescendants } from "../operations"; -import { runWorkflowSteps, workflowDependencies } from "../groupWorkflow"; -import { getNodeGenerationSettings } from "../NodeComposer"; +import { workflowRequest, workflowSteps } from "./workflowMembers.ts"; +import { getNodeGenerationSettings } from "../generationSettings.ts"; import { serviceGenerationPlan, textGenerationPlan } from "../workspaceInteraction.ts"; import { generationPrepareBlock } from "./entryPoints.ts"; import { JobFailureNotifications } from "./jobFailureNotifications.ts"; @@ -643,149 +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; } - const client = creationClient(document.id); - const policy = client.snapshot.project.spendPolicy; - if (policy && (policy.cap != null || policy.threshold != null)) { - try { - if (!await persist(document)) return; - const snapshot = await client.refresh(); - const dependencies = workflowDependencies(steps.map(node => node.id), document.edges); - const members = steps.map(node => { - 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) throw new Error(t("errors.backend.noGenerationConfig")); - const count = node.type === "image" || node.type === "video" ? getNodeGenerationSettings(node, backendCatalog.models).count ?? 1 : 1; - return { item, spec, count }; - }); - const receipt = await client.command("generation.group", { - members: members.map(({item, spec, count}) => ({ itemId: item.id, specId: spec.id, count, after: [...dependencies.get(item.id)!] })), - }, members.flatMap(({item, spec}) => [objectVersion("canvas_item", item), objectVersion("generation_spec", spec)])); - notify(receipt.status === "awaiting_confirmation" ? t("spend.waiting") : t("canvas.workspace.group.workflowStarted", { count: steps.length })); - } catch (failure) { notify(errorMessage(failure)); } - 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; @@ -863,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 df88e68b4..947396b42 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4380,6 +4380,7 @@ "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", @@ -4396,6 +4397,9 @@ { "$ref": "#/$defs/GenerationQuoteQuery" }, + { + "$ref": "#/$defs/GroupQuoteQuery" + }, { "$ref": "#/$defs/ProjectQuery" }, @@ -6391,6 +6395,41 @@ "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.", @@ -12839,6 +12878,16 @@ "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.", @@ -17269,6 +17318,7 @@ "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", @@ -17285,6 +17335,9 @@ { "$ref": "#/$defs/GenerationQuoteQuery" }, + { + "$ref": "#/$defs/GroupQuoteQuery" + }, { "$ref": "#/$defs/ProjectQuery" }, @@ -21924,6 +21977,7 @@ "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", @@ -21940,6 +21994,9 @@ { "$ref": "#/$defs/GenerationQuoteQuery" }, + { + "$ref": "#/$defs/GroupQuoteQuery" + }, { "$ref": "#/$defs/ProjectQuery" }, @@ -24022,6 +24079,41 @@ "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.", @@ -30657,6 +30749,16 @@ "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.", @@ -35272,6 +35374,7 @@ "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", @@ -35288,6 +35391,9 @@ { "$ref": "#/$defs/GenerationQuoteQuery" }, + { + "$ref": "#/$defs/GroupQuoteQuery" + }, { "$ref": "#/$defs/ProjectQuery" }, diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 28ca90a72..c47ad6c36 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -447,7 +447,7 @@ export interface CreationContractsInput extends ContractInput { 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 | ToolSpendCommandInput | SpendObservationCommandInput | SpendPolicyCommandInput | SpendReviewCommandInput | GenerationGroupCommandInput | AdvanceGroupCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; readonly receipt: CommandReceiptInput; - readonly query: SpendStatusQueryInput | GenerationQuoteQueryInput | 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; @@ -643,6 +643,11 @@ export interface GroupMemberInput extends ContractInput { 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; @@ -1336,6 +1341,7 @@ export interface SpendPolicyCommandInput extends CommandBaseInput { export interface SpendQuoteInput extends ContractInput { readonly fromUpstream?: boolean; readonly candidates?: number | null; + readonly skipped?: ReadonlyArray; readonly deferred?: ReadonlyArray; readonly count: number; readonly inputFingerprint: string; @@ -2243,7 +2249,7 @@ export interface CreationContracts extends Contract { 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 | ToolSpendCommand | SpendObservationCommand | SpendPolicyCommand | SpendReviewCommand | GenerationGroupCommand | AdvanceGroupCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; readonly receipt: CommandReceipt; - readonly query: SpendStatusQuery | GenerationQuoteQuery | 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; @@ -2439,6 +2445,11 @@ export interface GroupMember extends Contract { 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; @@ -3131,6 +3142,7 @@ export interface SpendPolicyCommand extends CommandBase { export interface SpendQuote extends Contract { readonly fromUpstream?: boolean; readonly candidates?: number | null; + readonly skipped?: ReadonlyArray; readonly deferred?: ReadonlyArray; readonly count: number; readonly inputFingerprint: string; diff --git a/src/i18n/messages/en-US/generation.ts b/src/i18n/messages/en-US/generation.ts index cfdcf14db..24e0743b6 100644 --- a/src/i18n/messages/en-US/generation.ts +++ b/src/i18n/messages/en-US/generation.ts @@ -31,6 +31,15 @@ export const generation = { "spend.automatic": "Automatic", "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.", diff --git a/src/i18n/messages/zh-CN/generation.ts b/src/i18n/messages/zh-CN/generation.ts index bbc062605..082837b62 100644 --- a/src/i18n/messages/zh-CN/generation.ts +++ b/src/i18n/messages/zh-CN/generation.ts @@ -31,6 +31,15 @@ export const generation = { "spend.automatic": "自动", "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": "工程币种已变更。请取消此申请并重新报价。", diff --git a/tests/browser/project_spend.mjs b/tests/browser/project_spend.mjs index a45d69892..4d8170196 100644 --- a/tests/browser/project_spend.mjs +++ b/tests/browser/project_spend.mjs @@ -125,6 +125,46 @@ try { assert.equal(posts.length - before, 6); assert.deepEqual(errors, []); console.log(locale, "USD 1.20 batch, zero calls pending, cancellation, USD 0.40 shortfall, chat approval, 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.equal(await page.locator(".cw-group-estimate li").count(), 2); + 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 page.locator(".cw-spend-toggle").click(); + await page.locator(".cw-spend-canvas .cw-spend-card").getByRole("button", {name: en ? "Cancel request" : "取消申请"}).click(); + 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"); await page.close(); } } finally { diff --git a/tests/test_creation_parameters.py b/tests/test_creation_parameters.py index 769493196..99d66b35f 100644 --- a/tests/test_creation_parameters.py +++ b/tests/test_creation_parameters.py @@ -338,6 +338,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 @@ -364,13 +374,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=[] - # PCM has an exact measured duration across ffprobe versions; MP3 has encoder padding. - reference = BytesIO() - import wave - with wave.open(reference, 'wb') as audio: - audio.setparams((1, 2, 8000, 0, 'NONE', 'not compressed')) - audio.writeframes(bytes(20 * 8000 * 2)) - reference = reference.getvalue() + reference = pcm_recording(20) def handler(request): if request.url.path=='/v1/audio/transcriptions': assert request.url.host=='score.invalid' @@ -420,6 +424,37 @@ 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): diff --git a/tests/test_spend_prices.py b/tests/test_spend_prices.py index c36c8b33a..714865ac0 100644 --- a/tests/test_spend_prices.py +++ b/tests/test_spend_prices.py @@ -2,7 +2,7 @@ from decimal import Decimal from uuid import uuid4 -from opendirector.domain.creation.spend import OFFICIAL_URL, SpendCall, SpendObservation, SpendQuote, observed_call, price_line +from opendirector.domain.creation.spend import OFFICIAL_URL, SpendCall, SpendObservation, SpendPolicy, SpendQuote, observed_call, price_line, spend_decision def test_connection_price_takes_precedence_and_an_alias_is_unpriced(): @@ -23,6 +23,12 @@ def test_missing_metered_quantity_is_unknown_even_with_a_price(): 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), diff --git a/tests/test_spend_workflows.py b/tests/test_spend_workflows.py index e3f4bd6d4..c57de031e 100644 --- a/tests/test_spend_workflows.py +++ b/tests/test_spend_workflows.py @@ -9,11 +9,12 @@ from generation_helpers import command, policy, review from opendirector.agent.tools import AgentTools +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_tasks import ToolTasks -from opendirector.domain.creation.commands import parse_command +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 @@ -58,10 +59,24 @@ def provider(request): 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) @@ -81,12 +96,41 @@ def provider(request): 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() + + @pytest.mark.anyio async def test_agent_receives_price_and_human_approval_resumes_its_original_action(project): store, pid, session = project @@ -182,5 +226,11 @@ def interrupted(*args): 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() From d7dc6c751e8ffed469460788e64e6b548abe04aa Mon Sep 17 00:00:00 2001 From: bread-lxy <2022200058@ruc.edu.cn> Date: Sun, 22 Nov 2026 12:13:41 +0800 Subject: [PATCH 07/15] [fix] Meter video costs using submitted frames and returned media --- .../application/creation_generation.py | 6 ++++-- .../src/opendirector/application/tool_spend.py | 13 ++++++++----- .../application/tool_task_lifecycle.py | 13 +++++++++++++ .../src/opendirector/application/tool_tasks.py | 6 +++--- .../src/opendirector/domain/creation/spend.py | 17 ++++++++++++++--- tests/test_spend_prices.py | 5 +++++ tests/test_spend_workflows.py | 13 +++++++++++++ tests/test_tool_tasks.py | 5 +++++ 8 files changed, 65 insertions(+), 13 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 856dbe785..1b6c0d9c0 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -20,7 +20,7 @@ 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 +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 @@ -437,7 +437,9 @@ def _quote_job(self, job, config, task, records, count): # MiniMax reports its billable character count in the response. quantities['input_character'] += sum(not char.isascii() for char in text) bounded = ('input_character',) - if params.get('duration') is not None: + 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) diff --git a/packages/core/src/opendirector/application/tool_spend.py b/packages/core/src/opendirector/application/tool_spend.py index d69e02f5e..cabcffcc8 100644 --- a/packages/core/src/opendirector/application/tool_spend.py +++ b/packages/core/src/opendirector/application/tool_spend.py @@ -9,7 +9,7 @@ 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 +from opendirector.domain.creation.spend import SpendCall, SpendQuote, SpendRequest, ToolSpendInput, price_line, video_units from opendirector.domain.projects import ProjectError @@ -41,7 +41,9 @@ def tool_quote(task, records): counts['image.edit'] = len(preset.prompts) if tool == 'image-hd' and 'image.edit' in counts: counts['image.edit'] = len(task['sourceAssetIds']) - pieces = (task.get('videoExecution') or {}).get('pieces', ()) + 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]] @@ -49,13 +51,14 @@ def tool_quote(task, records): for capability, count in counts.items(): for index in range(count): units = {} - if source.get('durationMs') is not None: + 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'] = units['requested_second'] = Decimal(str(round(end-start, 6))) + 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['requested_second'] = 5 + 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', diff --git a/packages/core/src/opendirector/application/tool_task_lifecycle.py b/packages/core/src/opendirector/application/tool_task_lifecycle.py index 3d1cabca1..6b1fd84a8 100644 --- a/packages/core/src/opendirector/application/tool_task_lifecycle.py +++ b/packages/core/src/opendirector/application/tool_task_lifecycle.py @@ -1,11 +1,14 @@ """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 @@ -144,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 diff --git a/packages/core/src/opendirector/application/tool_tasks.py b/packages/core/src/opendirector/application/tool_tasks.py index f12bbcad4..f4691f1b2 100644 --- a/packages/core/src/opendirector/application/tool_tasks.py +++ b/packages/core/src/opendirector/application/tool_tasks.py @@ -419,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': diff --git a/packages/core/src/opendirector/domain/creation/spend.py b/packages/core/src/opendirector/domain/creation/spend.py index 0491e6988..4fe6d5d17 100644 --- a/packages/core/src/opendirector/domain/creation/spend.py +++ b/packages/core/src/opendirector/domain/creation/spend.py @@ -1,6 +1,6 @@ """Service prices are decimal amounts in their original currency.""" from datetime import datetime -from decimal import Decimal +from decimal import Decimal, ROUND_CEILING from typing import Annotated, Literal from uuid import UUID @@ -9,6 +9,7 @@ from .base import Contract, Digest, ObjectVersion, ProjectEntity, digest Currency = Literal['USD', 'CNY'] +Amount = Annotated[Decimal, Field(ge=0, allow_inf_nan=False)] Money = Annotated[Decimal, Field(ge=0, max_digits=24, decimal_places=12, allow_inf_nan=False)] Unit = Literal['request', 'input_character', 'input_second', 'requested_second', 'output_second'] @@ -30,7 +31,7 @@ class PriceLine(Contract): 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: Money | None = Field(default=None, description='Estimated amount for this step of one candidate.') + amount: Amount | None = Field(default=None, description='Estimated amount for this step of one candidate.') class SpendQuote(Contract): @@ -89,7 +90,7 @@ class SpendCall(ProjectEntity): 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: Money | None = Field(default=None, description='Amount calculated from confirmed usage and the agreed rate.') + 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): @@ -193,6 +194,16 @@ def spend_decision(summary, quote): } +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 diff --git a/tests/test_spend_prices.py b/tests/test_spend_prices.py index 714865ac0..ec713b803 100644 --- a/tests/test_spend_prices.py +++ b/tests/test_spend_prices.py @@ -18,6 +18,11 @@ def test_connection_price_takes_precedence_and_an_alias_is_unpriced(): 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_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 diff --git a/tests/test_spend_workflows.py b/tests/test_spend_workflows.py index c57de031e..e8b8c1018 100644 --- a/tests/test_spend_workflows.py +++ b/tests/test_spend_workflows.py @@ -13,6 +13,7 @@ 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 @@ -162,6 +163,18 @@ async def tool(name, values, key): 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 diff --git a/tests/test_tool_tasks.py b/tests/test_tool_tasks.py index d2908feae..03b2e29a0 100644 --- a/tests/test_tool_tasks.py +++ b/tests/test_tool_tasks.py @@ -356,6 +356,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'}) @@ -368,12 +369,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() From 86a243f4bd27876ce17cc5522ab77b08a3215c48 Mon Sep 17 00:00:00 2001 From: bread-lxy <2022200058@ruc.edu.cn> Date: Sun, 22 Nov 2026 12:21:36 +0800 Subject: [PATCH 08/15] [fix] Show each candidate price and verify standalone CLI review --- src/canvas/ProjectSpend.tsx | 7 ++++-- src/canvas/project-spend.css | 14 ++++++----- src/i18n/messages/en-US/generation.ts | 3 ++- src/i18n/messages/zh-CN/generation.ts | 3 ++- tests/browser/project_spend.mjs | 34 ++++++++++++++++++++++++++- 5 files changed, 50 insertions(+), 11 deletions(-) diff --git a/src/canvas/ProjectSpend.tsx b/src/canvas/ProjectSpend.tsx index 264d38340..591b24f3d 100644 --- a/src/canvas/ProjectSpend.tsx +++ b/src/canvas/ProjectSpend.tsx @@ -16,14 +16,17 @@ function useSnapshot(projectId: string) { } function money(value: string, currency: string, locale: string) { - return new Intl.NumberFormat(locale, { style: "currency", currency, currencyDisplay: "code", maximumFractionDigits: 12 }).format(Number(value)); + return new Intl.NumberFormat(locale, { style: "currency", currency, currencyDisplay: "code", maximumFractionDigits: 20 }).format(Number(value)); } function QuoteLines({ quote }: { quote: SpendQuote }) { const { t, locale } = useI18n(); return