合并远端master并保留角色动作正式契约
保留外部生成异步提交、幂等轮询与托管MCP能力 融合角色动作正式序列帧资源与素材持久化契约 保留内部处理元数据脱敏与图集批量持久化门禁 补齐画布资源权威恢复、测试与Skill文档
This commit is contained in:
@@ -1,93 +1,70 @@
|
||||
---
|
||||
name: genarrative-external-editor-api
|
||||
description: Guide use of Genarrative's external editor/canvas OpenAPI. Use when a user describes a canvas/editor integration need and Codex must infer the right `/api/external/v1` API automatically, prepare canvas and asset-library context, abstract reusable art specs before generating assets, upload references, draft curl/HTTP/SDK requests, or set up and safely handle a Genarrative developer API Key.
|
||||
description: Guide use of Genarrative's hosted external editor/canvas MCP or asynchronous `/api/external/v1` OpenAPI. Use when an Agent needs to discover the hosted integration, choose a canvas or asset operation, upload local reference media, create or update projects and asset-library records, submit and poll image/video/audio generation, interpret generated artifacts and warnings, draft HTTP/Python calls, or securely handle a Genarrative developer API Key.
|
||||
---
|
||||
|
||||
# Genarrative External Editor API
|
||||
|
||||
Use the live OpenAPI contract as the source of truth: `GET https://www.genarrative.world/api/external/v1/openapi.json`. In this repository, the same contract is `docs/openapi/genarrative-external-v1.openapi.json`. If exact fields or enums matter, read the contract before emitting final code.
|
||||
Discover the live integration through `GET https://www.genarrative.world/api/external/v1/agent-integration.json`. Treat `GET https://www.genarrative.world/api/external/v1/openapi.json` as the field-level source of truth. In this repository, the same contract is `docs/openapi/genarrative-external-v1.openapi.json`.
|
||||
|
||||
Prefer the bundled Python helper for runnable examples: `scripts/genarrative_external_api.py`. It uses only Python stdlib, reads the local JSON API Key file, fixes the production base URL, and wraps upload/confirm/generation routes.
|
||||
Prefer the hosted Streamable HTTP MCP at `https://www.genarrative.world/api/external/v1/mcp` when the Agent supports remote MCP with a custom Bearer token. It exposes the External v1 operations as tools and the Skill documentation as resources; it does not require a local MCP server. Use this complete Skill package when remote MCP is unavailable or local-file upload needs client-side orchestration.
|
||||
|
||||
Prefer `scripts/genarrative_external_api.py` for runnable REST calls. It uses only Python stdlib, reads the local private API Key file, keeps the production base URL fixed, uploads local references, and wraps asynchronous submission, polling, and result retrieval.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. At the start of a new conversation, ask the user for the canvas name before the first generation call unless an existing session is already provided. Create or use a project with that name and an asset-library folder with the same name. Keep `canvasName`, `projectId`, `assetFolderId`, and the current art spec in conversation state.
|
||||
2. Before any art asset generation, abstract the user's request into a reusable art spec. Ask only for missing spec fields required by the selected asset type. If a current spec already exists and the user does not request a new style/spec, reuse it automatically.
|
||||
3. Classify the user's natural-language intent. Do not ask the user to choose an API:
|
||||
- "生成/生图/做一张图" -> image generation
|
||||
- "重绘/修改这张图" -> image edit
|
||||
- "用这张参考图/基于本地图生成" -> upload local reference image, then generation or edit
|
||||
- "上传本地素材" -> upload ticket, OSS form upload, object confirm
|
||||
- "保存画板/更新布局" -> canvas save
|
||||
- "读取私有素材" -> signed read URL
|
||||
4. Ask only for missing inputs that affect the request body or an actually ambiguous route:
|
||||
- credentials JSON path only if the user cannot use the default local path
|
||||
- canvas name when no current canvas session exists; existing `projectId`, folder/resource IDs only when resuming a known project
|
||||
- media type, prompt, references, dimensions, model, ratio, duration, and resolution
|
||||
- whether referenced media is already uploaded as `objectKey` or still local
|
||||
5. Every external generation must write to both the canvas and the asset library. Include `projectId`, `assetFolderId`, a display label, and `canvasCompletion` whenever the target endpoint supports them. Character animation writes both the preview video and final transparent image sequence in the generation request and returns the final `resource` / `asset`; use their IDs directly and do not create a duplicate first-frame resource or asset.
|
||||
6. If the user lacks an API Key, guide setup before request design.
|
||||
7. Read `references/api-selection.md` before finalizing any request. Use the core table below for fast routing, then verify details in the reference.
|
||||
8. Use `scripts/genarrative_external_api.py` when the user wants runnable Python, reference image upload, canvas/folder session setup, art-spec carrying, or a chain that should execute with fewer hand-written curl steps.
|
||||
9. Keep to `/api/external/v1` unless the user explicitly asks for internal profile/admin APIs.
|
||||
1. Discover the integration manifest. Choose hosted MCP when supported; otherwise use the helper or direct REST.
|
||||
2. Before the first generation in a new conversation, obtain a canvas name unless an existing `projectId` and `assetFolderId` were supplied. Create or reuse a project and a same-name asset-library folder. Retain `canvasName`, `projectId`, `assetFolderId`, and the current art spec.
|
||||
3. Normalize art requests into a reusable spec. Ask only for missing values that block the selected operation. Reuse the spec until the user changes its style, subject family, palette, format, or constraints.
|
||||
4. Infer the operation from the user's intent. Do not ask the user to select an API unless two operations would produce materially different artifacts.
|
||||
5. If a reference exists only as a local file, upload and confirm it first. Pass the stable returned `objectKey` to generation; never substitute a temporary signed URL.
|
||||
6. For generation endpoints that support the fields, include `projectId`, `assetFolderId`, an asset label, and `canvasCompletion` so the result enters both the canvas and its same-name library folder.
|
||||
7. Treat every generation POST as asynchronous. Send one stable `Idempotency-Key` per logical request, retain the returned `operationId`, and poll the returned `statusUrl` or `GET /api/external/v1/generations/{operationId}` according to `pollAfterMs`.
|
||||
8. Consume `result` only after `status=completed`. On `failed`, surface the safe error. On a client timeout or lost response, retain the operation/key; do not create a replacement request.
|
||||
9. Reload the normal project or asset-library read endpoint when the caller needs complete authoritative state. Generation results are intentionally compact.
|
||||
10. Stay within `/api/external/v1`. Never call internal workers, queues, admin/profile APIs, or SpacetimeDB endpoints unless the user explicitly changes scope.
|
||||
|
||||
## Core Routes
|
||||
## Essential Invariants
|
||||
|
||||
| Intent | Method and path | Required fields |
|
||||
| --- | --- | --- |
|
||||
| List/create projects | `GET/POST /api/external/v1/editor/projects` | create: optional `title` |
|
||||
| Save canvas | `PATCH /api/external/v1/editor/projects/{projectId}/canvas` | `viewport`, `layers`, `expectedRevision` |
|
||||
| Upload local media | `POST /api/external/v1/assets/direct-upload-tickets` -> OSS form -> `POST /api/external/v1/assets/objects/confirm` | ticket: `legacyPrefix`, `fileName`; confirm: `objectKey`, `assetKind` |
|
||||
| Read private media | `GET /api/external/v1/assets/read-url` | `objectKey` or `legacyPublicPath` |
|
||||
| Image generation | `POST /api/external/v1/editor/images/generations` | `prompt` |
|
||||
| Image edit/redraw | `POST /api/external/v1/editor/images/edits` | `prompt`, `sourceImageSrc` |
|
||||
| Icon spritesheet | `POST /api/external/v1/editor/icon-spritesheets/generations` | `referenceImageSrc`, `iconDescriptions` |
|
||||
| UI asset extraction | `POST /api/external/v1/editor/ui-designs/assets/extractions` | `sourceImageSrc`, `aspectRatio`, `imageSize`; use `assetFolderId` for library folder |
|
||||
| Character animation | `POST /api/external/v1/editor/character-animations/generations` | `sourceLayerId`, `sourceImageSrc`, `sourceWidth`, `sourceHeight`, `promptText`, `resolution`, `ratio`, `frameCount`, `durationSeconds`, `model` |
|
||||
| Video generation | `POST /api/external/v1/editor/videos/generations` | `prompt`, `model`, `aspectRatio`, `durationSeconds`, `resolution`, `mode`, `sound` |
|
||||
| Sound effect | `POST /api/external/v1/editor/audios/sound-effects/generations` | `prompt`, `duration` |
|
||||
| Background music | `POST /api/external/v1/editor/audios/background-music/generations` | `gptDescriptionPrompt`, `makeInstrumental` |
|
||||
- Authenticate MCP and business API calls with `Authorization: Bearer <tnr_sk_...>`. Never ask the user to paste a key into chat or place one in repository files.
|
||||
- All eight generation POST routes require `Idempotency-Key` and return HTTP `202`; `202` is durable acceptance, not a media result.
|
||||
- Retry an uncertain submission only with the exact same body and the same idempotency key. A polling timeout is not permission to generate again.
|
||||
- Use stable references such as `objectKey`, project resource ID, or asset ID in generation requests. Use `/assets/read-url` only for temporary preview/download access.
|
||||
- Preserve both warning channels after completion. A general `warning` can coexist with `sliceWarning`; do not discard either.
|
||||
- Do not invent missing derivatives. A source-preserved warning means the main source remains usable but requested post-processing failed. A slice warning means the complete transparent sheet is usable but individual slices are absent.
|
||||
- Keep generated artifacts in the canvas and asset library together. Character animation accepts `assetFolderId` and `assetLabel`; its completed result directly returns the final `assetKind="character-animation"` resource and asset with formal sequence fields. Do not create a duplicate first-frame record.
|
||||
|
||||
## Art Spec Interface
|
||||
## Documentation Navigation
|
||||
|
||||
Maintain one current art spec per conversation. A compact spec is enough:
|
||||
Read only the references needed for the task, but always verify exact schemas and enums against live OpenAPI:
|
||||
|
||||
```json
|
||||
{
|
||||
"assetType": "character | background | prop | ui | icon | animation | video | audio",
|
||||
"subject": "要生成的主体",
|
||||
"style": "画风/材质/时代/参考风格",
|
||||
"palette": "主色与禁用色",
|
||||
"composition": "构图、镜头、姿态或布局",
|
||||
"format": "比例、尺寸、分辨率、帧数、时长",
|
||||
"constraints": "必须保留/禁止出现/透明或绿幕要求",
|
||||
"references": ["objectKey 或本地路径说明"]
|
||||
}
|
||||
```
|
||||
- `references/capability-routing.md`: read before selecting an MCP tool or REST operation, creating a canvas session, or working in the AI game creator visual DAG.
|
||||
- `references/api-operations.md`: read when constructing project, canvas, asset-library, upload, generation, or generation-status calls.
|
||||
- `references/authentication-and-safety.md`: read before handling credentials, local files, OSS form upload, retries, private media, or logs.
|
||||
- `references/requests-and-outputs.md`: read before building generation payloads, polling, interpreting compact results, applying canvas completion, or handling post-processing warnings.
|
||||
|
||||
For a first spec, infer fields from the user's words and ask only for missing fields that block the selected API. Examples: character animation needs source image/layer, dimensions, motion, ratio, frame count, and duration; UI extraction needs source design image plus target density; icon spritesheet needs reference image and icon descriptions. After a spec exists, reuse it for later assets unless the user changes style, subject family, palette, format, or constraints.
|
||||
The hosted MCP exposes the same documents through:
|
||||
|
||||
## API Key
|
||||
- `genarrative://external-editor/skill`
|
||||
- `genarrative://external-editor/skill/references/capability-routing.md`
|
||||
- `genarrative://external-editor/skill/references/api-operations.md`
|
||||
- `genarrative://external-editor/skill/references/authentication-and-safety.md`
|
||||
- `genarrative://external-editor/skill/references/requests-and-outputs.md`
|
||||
- `genarrative://external-editor/openapi`
|
||||
|
||||
The external OpenAPI uses:
|
||||
## Hosted Integration Discovery
|
||||
|
||||
```text
|
||||
Authorization: Bearer <tnr_sk_...>
|
||||
```
|
||||
- Manifest: `GET /api/external/v1/agent-integration.json`.
|
||||
- Hosted MCP: `POST /api/external/v1/mcp`, Streamable HTTP, same Bearer API Key.
|
||||
- OpenAPI: `GET /api/external/v1/openapi.json`.
|
||||
- Raw Skill entry: `GET /api/external/v1/skill/SKILL.md`.
|
||||
- Complete Skill archive: `GET /api/external/v1/skill.zip`.
|
||||
|
||||
The OpenAPI JSON endpoint is public; every other external endpoint requires the Bearer API Key.
|
||||
The archive contains this main file, four one-level references, the Python helper, and `agents/openai.yaml`. Verify its SHA-256 against `agent-integration.json` before installing. Discovery, OpenAPI, and Skill downloads are public; MCP and business operations require authentication.
|
||||
|
||||
Use this fixed production base URL:
|
||||
## Python Helper
|
||||
|
||||
```text
|
||||
https://www.genarrative.world/
|
||||
```
|
||||
|
||||
Guide the user to create a key from the logged-in product UI under `开发者 API Key`. The raw key is shown only once; never ask the user to paste it into chat. Tell them to store it in this local private JSON file, outside the repository:
|
||||
|
||||
```text
|
||||
~/.config/genarrative/external-editor-api.json
|
||||
```
|
||||
Store the API Key outside the repository at `~/.config/genarrative/external-editor-api.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -95,273 +72,47 @@ Guide the user to create a key from the logged-in product UI under `开发者 AP
|
||||
}
|
||||
```
|
||||
|
||||
Set the file readable only by the current user where possible: `chmod 600 ~/.config/genarrative/external-editor-api.json`. Do not use environment variables for this API.
|
||||
|
||||
Smoke test by reading the JSON file, without printing the key:
|
||||
|
||||
```bash
|
||||
api_key="$(node -e 'const fs=require("fs"); const p=process.argv[1]; const c=JSON.parse(fs.readFileSync(p,"utf8")); process.stdout.write(c.apiKey || "");' "$HOME/.config/genarrative/external-editor-api.json")"
|
||||
curl -fsS "https://www.genarrative.world/api/external/v1/editor/projects" \
|
||||
-H "Authorization: Bearer $api_key"
|
||||
```
|
||||
|
||||
For generated client code, read `apiKey` from the JSON file, fail with a clear missing-config error, and redact keys in logs.
|
||||
|
||||
Python smoke without printing the key:
|
||||
Set restrictive permissions where possible, then smoke-test without printing the key:
|
||||
|
||||
```bash
|
||||
chmod 600 ~/.config/genarrative/external-editor-api.json
|
||||
python3 .codex/skills/genarrative-external-editor-api/scripts/genarrative_external_api.py list-projects
|
||||
```
|
||||
|
||||
## Request Patterns
|
||||
|
||||
For image and icon generation, the request-body top-level `style` field controls deterministic post-processing and is distinct from `generationInputs.artSpec.style`, which describes visual style for prompting. Pass `style="pixelArt"` in Python or `"style": "pixelArt"` in JSON to enable pixel-art snapping on supported generation types; use `"none"` or omit the field otherwise. Verify compatibility and fallback semantics in `references/api-selection.md`.
|
||||
|
||||
For Python callers, prefer:
|
||||
For a canvas-backed generation:
|
||||
|
||||
```python
|
||||
from genarrative_external_api import GenarrativeExternalClient
|
||||
|
||||
client = GenarrativeExternalClient()
|
||||
session = client.prepare_canvas_session("新画板")
|
||||
art_spec = {
|
||||
"assetType": "background",
|
||||
"subject": "幻想森林主视觉",
|
||||
"style": "手绘游戏概念图",
|
||||
"palette": "翡翠绿、金色光斑,避免低饱和灰",
|
||||
"composition": "16:9 横版,中心留出角色站位",
|
||||
"format": "16:9, 1K",
|
||||
"constraints": "无文字、无 UI 按钮",
|
||||
"references": [],
|
||||
}
|
||||
client.generate_image(
|
||||
"生成幻想森林背景",
|
||||
"生成一张 16:9 幻想森林游戏背景",
|
||||
canvasSession=session,
|
||||
assetLabel="森林背景",
|
||||
aspectRatio="16:9",
|
||||
imageSize="1K",
|
||||
artSpec=art_spec,
|
||||
artSpec={
|
||||
"assetType": "background",
|
||||
"subject": "幻想森林主视觉",
|
||||
"style": "手绘游戏概念图",
|
||||
"palette": "翡翠绿与金色光斑",
|
||||
"composition": "横版,中心留出角色站位",
|
||||
"format": "16:9, 1K",
|
||||
"constraints": "无文字、无 UI 按钮",
|
||||
"references": [],
|
||||
},
|
||||
)
|
||||
```
|
||||
|
||||
For a transparent game/UI atlas, call the dedicated helper instead of ordinary image generation:
|
||||
Helper convenience methods wait locally, but the server still uses short asynchronous submit/status requests. For durable caller-controlled orchestration, call `submit_generation`, persist its `operationId` and idempotency key, then call `get_generation` or `wait_for_generation`.
|
||||
|
||||
```python
|
||||
client.generate_icon_spritesheet(
|
||||
"editor-resource-current-art-spec",
|
||||
["蛇头四方向", "直身与四种转角", "尾部四方向", "四类可区分食物"],
|
||||
canvasSession=session,
|
||||
assetLabel="贪吃蛇透明图集",
|
||||
screenColor="auto",
|
||||
)
|
||||
```
|
||||
|
||||
Pass the registered visual-spec resource ID as `reference_image_src`; do not pass the UI prototype or a local path.
|
||||
|
||||
Use the helper directly from this skill path, or copy it into the caller's project. Do not change the fixed base URL or move the API Key into environment variables.
|
||||
|
||||
Use this shared base:
|
||||
|
||||
```bash
|
||||
api="https://www.genarrative.world"
|
||||
credentials_file="$HOME/.config/genarrative/external-editor-api.json"
|
||||
api_key="$(node -e 'const fs=require("fs"); const p=process.argv[1]; const c=JSON.parse(fs.readFileSync(p,"utf8")); process.stdout.write(c.apiKey || "");' "$credentials_file")"
|
||||
auth=(-H "Authorization: Bearer $api_key")
|
||||
json=(-H "Content-Type: application/json")
|
||||
```
|
||||
|
||||
Create a project:
|
||||
|
||||
```bash
|
||||
curl -fsS "$api/api/external/v1/editor/projects" \
|
||||
"${auth[@]}" "${json[@]}" \
|
||||
-d '{"title":"新画板"}'
|
||||
```
|
||||
|
||||
Generate an image and save it into both the canvas and the asset-library folder:
|
||||
|
||||
```json
|
||||
{
|
||||
"prompt": "一张横版幻想森林背景,适合游戏主视觉",
|
||||
"kind": "spec",
|
||||
"aspectRatio": "16:9",
|
||||
"imageSize": "1K",
|
||||
"projectId": "<projectId>",
|
||||
"assetFolderId": "<assetFolderId>",
|
||||
"assetLabel": "森林背景",
|
||||
"generationInputs": {
|
||||
"artSpec": {
|
||||
"assetType": "background",
|
||||
"style": "手绘游戏概念图"
|
||||
}
|
||||
},
|
||||
"canvasCompletion": {
|
||||
"title": "森林背景",
|
||||
"placeholder": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"width": 1024,
|
||||
"height": 576,
|
||||
"originalWidth": 1024,
|
||||
"originalHeight": 576
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Then call `POST /api/external/v1/editor/images/generations`.
|
||||
|
||||
For direct HTTP/curl, create or find the folder first with `GET /api/external/v1/editor/assets/library` and `POST /api/external/v1/editor/assets/folders`. The folder label should match the canvas name.
|
||||
|
||||
## Reference Images
|
||||
|
||||
When the user provides a local reference image path/file, upload it first; do not ask the user to convert it to base64.
|
||||
|
||||
Python helper path:
|
||||
|
||||
```python
|
||||
from genarrative_external_api import GenarrativeExternalClient
|
||||
|
||||
client = GenarrativeExternalClient()
|
||||
session = client.prepare_canvas_session("新画板")
|
||||
ref = client.upload_reference_image("/path/to/reference.png")
|
||||
client.generate_image(
|
||||
"基于参考图生成一张 16:9 游戏背景",
|
||||
canvasSession=session,
|
||||
assetLabel="参考图背景",
|
||||
aspectRatio="16:9",
|
||||
imageSize="1K",
|
||||
referenceImageSrcs=[ref["objectKey"]],
|
||||
)
|
||||
```
|
||||
|
||||
Use the normal upload flow with:
|
||||
|
||||
```json
|
||||
{
|
||||
"legacyPrefix": "generated-character-drafts",
|
||||
"pathSegments": ["editor", "external-editor-references"],
|
||||
"fileName": "<original-file-name>",
|
||||
"contentType": "image/png",
|
||||
"access": "private"
|
||||
}
|
||||
```
|
||||
|
||||
After OSS form upload, confirm the object with `assetKind: "editor_reference_image"`. Put the returned `objectKey` into the generation request:
|
||||
|
||||
- image generation: `referenceImageSrcs`
|
||||
- image edit/redraw: `sourceImageSrc`; extra references go in `referenceImageSrcs`
|
||||
- icon spritesheet: `referenceImageSrc`
|
||||
- UI asset extraction: `sourceImageSrc`; extra references go in `referenceImageSrcs`
|
||||
- character animation: `sourceImageSrc`
|
||||
- video generation image references: `referenceImageSrcs`
|
||||
|
||||
Use `signedUrl` only for display/download. For generation requests, use `objectKey`, project resource ID, asset ID, public URL, or Data URL as the endpoint allows; prefer uploaded `objectKey` for local/private reference images.
|
||||
|
||||
OSS form upload shape, using the ticket response saved as `ticket.json`. The default response has `upload`; if the caller explicitly requested the API response envelope, use `data.upload`:
|
||||
|
||||
```bash
|
||||
node - <<'NODE' ticket.json /path/to/reference.png
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
(async () => {
|
||||
const body = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
|
||||
const ticket = body.upload || body.data?.upload;
|
||||
if (!ticket) throw new Error('Upload ticket response missing upload payload');
|
||||
const filePath = process.argv[3];
|
||||
const form = new FormData();
|
||||
for (const [key, value] of Object.entries(ticket.formFields)) {
|
||||
if (value != null) form.append(key, value);
|
||||
}
|
||||
const bytes = fs.readFileSync(filePath);
|
||||
form.append(
|
||||
'file',
|
||||
new Blob([bytes], { type: ticket.contentType || 'application/octet-stream' }),
|
||||
path.basename(filePath),
|
||||
);
|
||||
const response = await fetch(ticket.host, { method: 'POST', body: form });
|
||||
if (!response.ok) {
|
||||
throw new Error(`OSS upload failed: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
})().catch((error) => {
|
||||
console.error(error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
NODE
|
||||
```
|
||||
|
||||
Then confirm with `contentLength`:
|
||||
|
||||
```json
|
||||
{
|
||||
"objectKey": "<ticket upload.objectKey>",
|
||||
"contentType": "image/png",
|
||||
"contentLength": 12345,
|
||||
"assetKind": "editor_reference_image",
|
||||
"accessPolicy": "private"
|
||||
}
|
||||
```
|
||||
|
||||
`contentLength` is a JSON number from the local file byte size, not a quoted string.
|
||||
|
||||
For character animation from an uploaded local image, set:
|
||||
|
||||
```json
|
||||
{
|
||||
"sourceLayerId": "external-reference-hero",
|
||||
"sourceImageSrc": "<uploaded objectKey>",
|
||||
"sourceWidth": 720,
|
||||
"sourceHeight": 1280,
|
||||
"promptText": "让角色自然呼吸并轻微转身",
|
||||
"resolution": "720p",
|
||||
"ratio": "9:16",
|
||||
"frameCount": 40,
|
||||
"durationSeconds": 5,
|
||||
"model": "seedance2.0-fast"
|
||||
}
|
||||
```
|
||||
|
||||
Use an existing canvas layer ID when the image came from a project layer. If it came only from a local upload, derive a stable synthetic `sourceLayerId` from the file name, for example `external-reference-hero`. Read `sourceWidth` and `sourceHeight` from the actual image before upload; ask the user only if the dimensions cannot be determined.
|
||||
|
||||
The helper uses a 420 second timeout for generation calls, including character animation and video. Direct HTTP clients should not use a 70 second request timeout for animation.
|
||||
|
||||
Character animation returns both canvas completion data and the canonical final `resource` / `asset` payloads. Call `client.animate_character(..., canvasSession=session, canvasTitle="...")`; the helper sends the project, folder, label, and canvas completion context directly to the generation endpoint. The generation response includes `frames`, `previewVideoPath`, `frameCount`, `fps`, and `durationSeconds`; `frames` and the final resource / asset `imageSequenceFrames` both use array position as the only playback order and never carry `frameIndex`. The preview is persisted separately with `assetKind: "video"`. The final transparent action has `assetKind: "character-animation"` plus `imageSequenceFrames` and `imageSequenceDurationMs`. When project context is present, the canvas layer must use the returned final `resource.resourceId`, whose `sourceResourceId` records the preview-resource lineage. Derive rendering behavior from `assetKind`;
|
||||
For video generation, always include `mode: "std"`. When using image/video/audio references, default to `model: "seedance2.0-fast"` unless the user asks for another listed model, because reference media support is limited to the Seedance 2.0 family.
|
||||
|
||||
For image edit/redraw that should replace an existing canvas layer, pass `projectId` and `targetLayerId`. If the user instead gives an explicit `canvasCompletion`, let that placement win.
|
||||
|
||||
For sound effects and BGM, `assetFolderId` and `assetLabel` can write the generated audio to the account asset library, same as image/video generation.
|
||||
|
||||
## Successful Responses with Warnings
|
||||
|
||||
Character image generation (including character redraw through `kind: "character"`), icon spritesheet generation, and UI asset extraction can return HTTP 2xx with an optional structured `warning`. A 2xx response means the task completed, but it does not guarantee that every requested post-processed derivative exists.
|
||||
|
||||
- Apply the returned `project` and media snapshots before interpreting optional derivatives: character responses use `resource` / `asset`, while icon spritesheet and UI extraction responses use `spritesheetResource` / `spritesheetAsset`. When `warning.code` is `postprocess-failed-source-preserved`, the saved provider source image is the authoritative main result. Character output has no transparent derivative; icon spritesheet and UI extraction output have neither a transparent spritesheet nor slices. Display `warning.reason` directly, and do not synthesize missing derivatives or restart generation.
|
||||
- `sliceWarning` is a separate condition used only when transparent spritesheet post-processing succeeded but automatic slicing failed. Keep `sliceWarning.reason` as the original diagnostic and continue using the complete transparent spritesheet; a UI may add context when displaying it, but must not rewrite the stored reason.
|
||||
- `warning` and `sliceWarning` are mutually exclusive only for `postprocess-failed-source-preserved`, because a failed transparent post-process never reaches slicing. Since 2026-07-29 a general `warning` may also come from image-style normalization (`unsupported-image-style`) or pixel-art snapping, and those can coexist with `sliceWarning` in the same response. Display both reasons; do not drop either one and do not misclassify a source-preserved result as a slicing-only warning.
|
||||
|
||||
For reusable transparent game/UI sheets, do not substitute ordinary image generation merely because it can draw several objects in one image. Use icon spritesheet generation when a stable visual-spec reference and `iconDescriptions` exist; use UI extraction only for an existing annotated UI design. Pass `screenColor: "auto"` unless the art direction requires one of the supported solid chroma colors. A client must verify the returned full sheet really contains transparency before treating it as a transparent spritesheet. If a source-preserved `warning` is present, do not register the opaque provider source as the requested transparent deliverable. When only `sliceWarning` is present, the full transparent sheet remains usable, but no individual slices may be claimed.
|
||||
|
||||
## AI Game Creator Canonical Visual DAG
|
||||
|
||||
The AI game creator reuses its existing 16-task manifest; do not add a parallel task system or collapse the following artifacts into one ordinary generation request:
|
||||
|
||||
1. `art-director` generates `assets/art-spec.png` with `POST /api/external/v1/editor/images/generations`, `kind: "spec"`, and registers it as `assetKind: "icon-spec"`. This is the real visual-spec image. The JSON value in `generationInputs.artSpec` is supporting structured context and does not replace this image.
|
||||
2. `design-foundation` uses the registered External Editor resource ID for `assets/art-spec.png` in `referenceImageSrcs`, then generates the complete `assets/ui-prototype.png` through `POST /api/external/v1/editor/images/generations` with `kind: "ui-design"`.
|
||||
3. `art-asset-plan` uses the same registered `assets/art-spec.png` resource ID as the required `referenceImageSrc` for `POST /api/external/v1/editor/icon-spritesheets/generations`, supplies concrete `iconDescriptions`, and registers the transparent full result as `assets/art-spritesheet.png`.
|
||||
|
||||
Never use `assets/ui-prototype.png` as the icon spritesheet's visual-spec reference. `POST /api/external/v1/editor/ui-designs/assets/extractions` requires an existing UI design image with red-box annotations; it is not UI generation and is not part of this canonical DAG.
|
||||
For character animation, pass the canvas session and asset label to `animate_character`. The helper submits asynchronously and returns the completed compact result containing the authoritative formal `resource` and `asset`; do not synthesize a library asset from the first frame.
|
||||
|
||||
## Guardrails
|
||||
|
||||
- Do not invent endpoints outside the OpenAPI, especially internal worker or runtime task-list routes.
|
||||
- Do not omit canvas/library context for generation. New generated assets should enter both the canvas and the asset-library folder named after the canvas.
|
||||
- Do not put API Keys in repository files, generated project files, command history snippets with literal secrets, logs, docs, commits, or screenshots. The only default storage is the user's local private JSON credentials file.
|
||||
- Do not use account JWT endpoints as the default external integration path. The profile API can create/revoke keys for logged-in product users, but it is not part of the external editor OpenAPI.
|
||||
- When an endpoint returns `project`, `resource`, or `asset`, treat those as the authoritative updated project/resource/asset snapshots.
|
||||
|
||||
## Resources
|
||||
|
||||
- `references/api-selection.md`: intent routing and required-field cheat sheet.
|
||||
- `scripts/genarrative_external_api.py`: stdlib Python helper for OpenAPI fetch, API Key loading, local reference upload, object confirm, project/canvas calls, and generation requests.
|
||||
- Do not change the fixed production base URL in generated examples.
|
||||
- Do not move the API Key into environment variables, source files, generated projects, logs, docs, screenshots, or shell snippets containing literal secrets.
|
||||
- Do not treat a Data URL, Blob URL, expiring signed URL, worker lease, or provider diagnostic as a durable result.
|
||||
- Do not reconstruct authoritative canvas, resource, or library snapshots from a compact generation response.
|
||||
- Do not replace icon-spritesheet generation with ordinary image generation when the deliverable requires a reusable transparent atlas.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
interface:
|
||||
display_name: "Genarrative External Editor API"
|
||||
short_description: "Auto-route canvas API generation"
|
||||
default_prompt: "Use $genarrative-external-editor-api to prepare a canvas session, infer the right API, and generate assets into the canvas and library."
|
||||
short_description: "Route async canvas generation safely"
|
||||
default_prompt: "Use $genarrative-external-editor-api to discover the hosted integration, prepare a canvas session, and submit and poll asset generation into the canvas and library."
|
||||
policy:
|
||||
allow_implicit_invocation: true
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# API Operations
|
||||
|
||||
Use this reference after selecting a capability. Treat `GET /api/external/v1/openapi.json` as authoritative for exact request/response schemas, required fields, constraints, and operation IDs.
|
||||
|
||||
All paths below are relative to `https://www.genarrative.world`. Discovery and Skill download routes are public. Project, asset, upload, generation, and generation-query operations require the Bearer API Key.
|
||||
|
||||
## Project and Canvas Operations
|
||||
|
||||
| Operation | Method and path | Minimum input |
|
||||
| --- | --- | --- |
|
||||
| List projects | `GET /api/external/v1/editor/projects` | Authentication |
|
||||
| Create project | `POST /api/external/v1/editor/projects` | Optional `title` |
|
||||
| Load recent project | `GET /api/external/v1/editor/projects/recent` | Authentication |
|
||||
| Get project | `GET /api/external/v1/editor/projects/{projectId}` | `projectId` |
|
||||
| Delete project | `DELETE /api/external/v1/editor/projects/{projectId}` | `projectId` |
|
||||
| Rename project | `PATCH /api/external/v1/editor/projects/{projectId}/metadata` | `title` |
|
||||
| Save canvas | `PATCH /api/external/v1/editor/projects/{projectId}/canvas` | `viewport`, `layers`, `expectedRevision` |
|
||||
| Add project resource | `POST /api/external/v1/editor/projects/{projectId}/resources` | `imageSrc`, `width`, `height`, `sourceType` |
|
||||
|
||||
Canvas save uses optimistic revision control. Pass the last authoritative `expectedRevision`; on conflict, reload instead of replaying a stale full layout.
|
||||
|
||||
## Asset and Upload Operations
|
||||
|
||||
| Operation | Method and path | Minimum input |
|
||||
| --- | --- | --- |
|
||||
| Create direct-upload ticket | `POST /api/external/v1/assets/direct-upload-tickets` | `legacyPrefix`, `fileName` |
|
||||
| Confirm uploaded object | `POST /api/external/v1/assets/objects/confirm` | `objectKey`, `assetKind` |
|
||||
| Get signed read URL | `GET /api/external/v1/assets/read-url` | `objectKey` or `legacyPublicPath` |
|
||||
| Read asset library | `GET /api/external/v1/editor/assets/library` | Authentication |
|
||||
| Create folder | `POST /api/external/v1/editor/assets/folders` | `label` |
|
||||
| Update folder | `PATCH /api/external/v1/editor/assets/folders/{folderId}` | `label` or `collapsed` |
|
||||
| Delete folder | `DELETE /api/external/v1/editor/assets/folders/{folderId}` | `folderId` |
|
||||
| Create asset record | `POST /api/external/v1/editor/assets` | `folderId`, `label`, `imageSrc`, `width`, `height`, `sourceType` |
|
||||
| Update asset record | `PATCH /api/external/v1/editor/assets/{assetId}` | `label` or `folderId` |
|
||||
| Delete asset record | `DELETE /api/external/v1/editor/assets/{assetId}` | `assetId` |
|
||||
|
||||
Upload is a three-step client flow: create a ticket, POST the file and returned fields directly to the OSS form endpoint, then confirm the returned `objectKey`. See `authentication-and-safety.md` before implementing this flow.
|
||||
|
||||
## Generation Operations
|
||||
|
||||
Every generation row requires a stable `Idempotency-Key` header and returns HTTP `202` with an asynchronous submission, not the generated media.
|
||||
|
||||
| Capability | POST path | Required body fields | Common optional body fields |
|
||||
| --- | --- | --- | --- |
|
||||
| Image generation | `/api/external/v1/editor/images/generations` | `prompt` | `kind`, `style`, `model`, `aspectRatio`, `imageSize`, `size`, `referenceImageSrcs`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
|
||||
| Image edit/redraw | `/api/external/v1/editor/images/edits` | `prompt`, `sourceImageSrc` | `referenceImageSrcs`, `model`, `size`, `projectId`, `assetFolderId`, `assetLabel`, `sourceResourceId`, `targetLayerId`, `canvasCompletion` |
|
||||
| Icon spritesheet | `/api/external/v1/editor/icon-spritesheets/generations` | `referenceImageSrc`, `iconDescriptions` | `style`, `referenceImageSrcs`, `screenColor`, `model`, `aspectRatio`, `imageSize`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
|
||||
| UI asset extraction | `/api/external/v1/editor/ui-designs/assets/extractions` | `sourceImageSrc`, `aspectRatio`, `imageSize` | `screenColor`, `model`, `referenceImageSrcs`, `projectId`, `assetFolderId`, `spritesheetLabel`, `canvasCompletion` |
|
||||
| Character animation | `/api/external/v1/editor/character-animations/generations` | `sourceLayerId`, `sourceImageSrc`, `sourceWidth`, `sourceHeight`, `promptText`, `resolution`, `ratio`, `frameCount`, `durationSeconds`, `model` | `projectId`, `sourceResourceId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
|
||||
| Video generation | `/api/external/v1/editor/videos/generations` | `prompt`, `model`, `aspectRatio`, `durationSeconds`, `resolution`, `mode`, `sound` | `referenceImageSrcs`, `referenceVideoSrcs`, `referenceAudioSrcs`, `webSearchEnabled`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
|
||||
| Sound effect | `/api/external/v1/editor/audios/sound-effects/generations` | `prompt`, `duration` | `model`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
|
||||
| Background music | `/api/external/v1/editor/audios/background-music/generations` | `gptDescriptionPrompt`, `makeInstrumental` | `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
|
||||
|
||||
Poll all eight through:
|
||||
|
||||
```text
|
||||
GET /api/external/v1/generations/{operationId}
|
||||
```
|
||||
|
||||
Supply the `operationId` returned by submission. Poll no faster than `pollAfterMs` and retain the ID after a caller-side timeout.
|
||||
|
||||
## Canvas and Library Field Rules
|
||||
|
||||
- Pass `projectId` and `canvasCompletion` to write generated output into the canvas.
|
||||
- Pass `assetFolderId` plus `assetLabel` for image, edit, icon spritesheet, video, sound effect, and BGM operations when supported.
|
||||
- UI extraction uses `assetFolderId` and `spritesheetLabel`.
|
||||
- Character animation accepts `assetFolderId` and `assetLabel`. Its completed compact result directly returns the final `assetKind="character-animation"` resource and asset with `imageSequenceFrames` and `imageSequenceDurationMs`; never create a duplicate first-frame resource or asset.
|
||||
- Reload project/library state after completion when full current state is required.
|
||||
|
||||
## Reference Field Mapping
|
||||
|
||||
After confirming a local upload, pass its stable `objectKey` into:
|
||||
|
||||
| Target capability | Field |
|
||||
| --- | --- |
|
||||
| Image generation | `referenceImageSrcs` |
|
||||
| Image edit/redraw | `sourceImageSrc`; additional references in `referenceImageSrcs` |
|
||||
| Icon spritesheet | `referenceImageSrc`; additional style references in `referenceImageSrcs` |
|
||||
| UI design extraction | `sourceImageSrc`; additional references in `referenceImageSrcs` |
|
||||
| Character animation | `sourceImageSrc` |
|
||||
| Video with image references | `referenceImageSrcs` |
|
||||
|
||||
Use video/audio reference arrays only with models that support them. Do not pass an expiring signed read URL as a generation reference.
|
||||
|
||||
## Common Values
|
||||
|
||||
Use OpenAPI as the final authority; these common values are a routing aid:
|
||||
|
||||
- Image `kind`: `spec`, `character`, `quick-edit`, `ui-design`, `publication-material`; ordinary image generation may omit it.
|
||||
- Image `model`: `gpt-image-2`, `gemini-3.1-flash-image-preview`, `nanobanana2`, `nano-banana`.
|
||||
- Image `aspectRatio`: `1:1`, `2:3`, `3:2`, `9:16`, `16:9`.
|
||||
- Image `imageSize`: `0.5K`, `1K`, `2K`.
|
||||
- Video `model`: `seedance2.0`, `seedance2.0-fast`, `kling3.0`, `kling3.0-omni`, `veo3.1`, `veo3.1-fast`.
|
||||
- Video `aspectRatio`: `16:9`, `9:16`, `1:1`, `4:3`, `3:4`, `21:9`.
|
||||
- Video `resolution`: `480p`, `720p`, `1080p`; `mode`: `std`; `sound`: `on` or `off`.
|
||||
- Character animation uses `model: "seedance2.0-fast"`; `resolution`: `480p` or `720p`; `frameCount`: `32`, `40`, or `48`; `durationSeconds`: `4`, `5`, or `6`; `ratio`: `same`, `1:1`, `4:3`, `16:9`, `9:16`, or `3:4`.
|
||||
- UI extraction uses `aspectRatio: "1:1"`; use `imageSize: "1K"` for normal/small extraction and `2K` for dense designs.
|
||||
|
||||
Do not hard-code this list as a replacement client schema. In particular, the top-level image `style` field is intentionally extensible; see `requests-and-outputs.md` for its fallback behavior.
|
||||
@@ -1,239 +0,0 @@
|
||||
# External Editor API Routing
|
||||
|
||||
Source of truth: `docs/openapi/genarrative-external-v1.openapi.json`.
|
||||
|
||||
## Base
|
||||
|
||||
- Fixed base URL: `https://www.genarrative.world/`.
|
||||
- Public contract: `GET /api/external/v1/openapi.json`.
|
||||
- Authenticated calls: `Authorization: Bearer <tnr_sk_...>`.
|
||||
- Default credentials file: `~/.config/genarrative/external-editor-api.json` with an `apiKey` string.
|
||||
- Generation clients should allow long-running responses. Use at least 420 seconds for character animation and video; 70 seconds is too short for animation.
|
||||
|
||||
## Canvas Session and Art Spec
|
||||
|
||||
At the start of a new conversation, ask for a canvas name before the first generation call unless the user already supplied `projectId` and `assetFolderId`. Create or reuse:
|
||||
|
||||
1. `POST /api/external/v1/editor/projects` with `title` = canvas name.
|
||||
2. `GET /api/external/v1/editor/assets/library`; if no folder has the same label, `POST /api/external/v1/editor/assets/folders` with `label` = canvas name.
|
||||
3. Keep `canvasName`, `projectId`, `assetFolderId`, and the current art spec in conversation state.
|
||||
|
||||
Before generating art assets, normalize the user's request into a current art spec with `assetType`, `subject`, `style`, `palette`, `composition`, `format`, `constraints`, and `references`. Ask follow-up questions only for missing fields that block the selected endpoint. Reuse the current spec automatically when the user asks for another asset without changing style/spec requirements. Put the spec in `generationInputs.artSpec` and summarize it in the prompt when useful.
|
||||
|
||||
For the AI game creator's existing 16-task autonomous build, distinguish that JSON art spec from the required visual-spec image and keep this dependency chain:
|
||||
|
||||
1. `art-director` -> `assets/art-spec.png` via `POST /api/external/v1/editor/images/generations`, with `kind=spec` and registered `assetKind=icon-spec`.
|
||||
2. `design-foundation` -> `assets/ui-prototype.png` via the same image generation endpoint with `kind=ui-design`, using the registered art-spec resource ID in `referenceImageSrcs`.
|
||||
3. `art-asset-plan` -> transparent `assets/art-spritesheet.png` via `POST /api/external/v1/editor/icon-spritesheets/generations`, using the registered art-spec resource ID as `referenceImageSrc` and providing `iconDescriptions`.
|
||||
|
||||
Do not use the UI prototype as the spritesheet specification. UI extraction requires a stable source image with red-box annotations and is outside this canonical DAG.
|
||||
|
||||
## Intent Routing
|
||||
|
||||
Infer the endpoint from the user's description. Do not present this as a menu unless the request is genuinely ambiguous.
|
||||
|
||||
| User says | Route |
|
||||
| --- | --- |
|
||||
| "生成图片", "生图", "做一张背景/角色/宣发图" | `POST /api/external/v1/editor/images/generations` |
|
||||
| "重绘", "调整这张图", "基于这张图修改" | `POST /api/external/v1/editor/images/edits` |
|
||||
| "用这张参考图", "参考本地图片生成", "基于本地图做图" | Upload local image first, then pass returned `objectKey` into the generation/edit reference field |
|
||||
| "按规范图生成图标", "拆图标" | `POST /api/external/v1/editor/icon-spritesheets/generations` |
|
||||
| "从 UI 设计图提取素材" | `POST /api/external/v1/editor/ui-designs/assets/extractions` |
|
||||
| "让角色动起来", "生成角色动画帧" | `POST /api/external/v1/editor/character-animations/generations` |
|
||||
| "生成视频" | `POST /api/external/v1/editor/videos/generations` |
|
||||
| "生成音效" | `POST /api/external/v1/editor/audios/sound-effects/generations` |
|
||||
| "生成背景音乐/BGM" | `POST /api/external/v1/editor/audios/background-music/generations` |
|
||||
| "上传本地素材/图片/音频/视频" | Upload flow: direct upload ticket -> OSS form upload -> object confirm |
|
||||
| "保存画板布局" | `PATCH /api/external/v1/editor/projects/{projectId}/canvas` |
|
||||
| "创建/读取/删除画板项目" | Project endpoints |
|
||||
| "素材库/文件夹/素材记录" | Asset library endpoints |
|
||||
| "读取私有素材/拿可访问链接" | `GET /api/external/v1/assets/read-url` |
|
||||
|
||||
Ask a follow-up only when two routes could both be correct and produce different artifacts, for example "处理这张图" without saying edit, extract UI assets, or use it as a reference for new generation.
|
||||
|
||||
## Endpoint Map
|
||||
|
||||
| User intent | Endpoint | Minimum request |
|
||||
| --- | --- | --- |
|
||||
| Read contract | `GET /api/external/v1/openapi.json` | No auth required |
|
||||
| List projects | `GET /api/external/v1/editor/projects` | API Key |
|
||||
| Create project | `POST /api/external/v1/editor/projects` | Optional `title` |
|
||||
| Load recent project | `GET /api/external/v1/editor/projects/recent` | API Key |
|
||||
| Get/delete project | `GET` or `DELETE /api/external/v1/editor/projects/{projectId}` | `projectId` |
|
||||
| Rename project | `PATCH /api/external/v1/editor/projects/{projectId}/metadata` | `title` |
|
||||
| Save canvas layout | `PATCH /api/external/v1/editor/projects/{projectId}/canvas` | `viewport`, `layers`, `expectedRevision` |
|
||||
| Add project resource | `POST /api/external/v1/editor/projects/{projectId}/resources` | `imageSrc`, `width`, `height`, `sourceType` |
|
||||
| Create upload ticket | `POST /api/external/v1/assets/direct-upload-tickets` | `legacyPrefix`, `fileName` |
|
||||
| Confirm uploaded object | `POST /api/external/v1/assets/objects/confirm` | `objectKey`, `assetKind` |
|
||||
| Get signed read URL | `GET /api/external/v1/assets/read-url` | `objectKey` or `legacyPublicPath` |
|
||||
| Read asset library | `GET /api/external/v1/editor/assets/library` | API Key |
|
||||
| Create/update/delete folder | `POST /api/external/v1/editor/assets/folders`, `PATCH`/`DELETE /api/external/v1/editor/assets/folders/{folderId}` | create: `label`; update: `label` or `collapsed` |
|
||||
| Create asset record | `POST /api/external/v1/editor/assets` | `folderId`, `label`, `imageSrc`, `width`, `height`, `sourceType` |
|
||||
| Update/delete asset | `PATCH`/`DELETE /api/external/v1/editor/assets/{assetId}` | update: `label` or `folderId` |
|
||||
|
||||
## Generation Endpoints
|
||||
|
||||
| User intent | Endpoint | Required fields | Common optional fields |
|
||||
| --- | --- | --- | --- |
|
||||
| Generate image/spec/character/UI/publication material | `POST /api/external/v1/editor/images/generations` | `prompt` | `kind`, `style`, `model`, `aspectRatio`, `imageSize`, `size`, `referenceImageSrcs`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
|
||||
| Edit/redraw image | `POST /api/external/v1/editor/images/edits` | `prompt`, `sourceImageSrc` | `referenceImageSrcs`, `model`, `size`, `projectId`, `assetFolderId`, `assetLabel`, `sourceResourceId`, `targetLayerId`, `canvasCompletion` |
|
||||
| Generate icon spritesheet | `POST /api/external/v1/editor/icon-spritesheets/generations` | `referenceImageSrc`, `iconDescriptions` | `style`, `referenceImageSrcs`, `screenColor`, `model`, `aspectRatio`, `imageSize`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
|
||||
| Extract assets from UI design | `POST /api/external/v1/editor/ui-designs/assets/extractions` | `sourceImageSrc`, `aspectRatio`, `imageSize` | `screenColor`, `model`, `referenceImageSrcs`, `projectId`, `assetFolderId`, `spritesheetLabel`, `canvasCompletion` |
|
||||
| Generate character animation | `POST /api/external/v1/editor/character-animations/generations` | `sourceLayerId`, `sourceImageSrc`, `sourceWidth`, `sourceHeight`, `promptText`, `resolution`, `ratio`, `frameCount`, `durationSeconds`, `model` | `projectId`, `sourceResourceId`, `assetFolderId`, `assetLabel`, `canvasCompletion`; response includes transient generation timing plus the final `assetKind="character-animation"` resource / asset with `imageSequenceFrames` and `imageSequenceDurationMs` |
|
||||
| Generate video | `POST /api/external/v1/editor/videos/generations` | `prompt`, `model`, `aspectRatio`, `durationSeconds`, `resolution`, `mode`, `sound` | `referenceImageSrcs`, `referenceVideoSrcs`, `referenceAudioSrcs`, `webSearchEnabled`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion` |
|
||||
| Generate sound effect | `POST /api/external/v1/editor/audios/sound-effects/generations` | `prompt`, `duration` | `model`, `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
|
||||
| Generate background music | `POST /api/external/v1/editor/audios/background-music/generations` | `gptDescriptionPrompt`, `makeInstrumental` | `projectId`, `assetFolderId`, `assetLabel`, `canvasCompletion`, `generationInputs` |
|
||||
|
||||
## Image Post-processing Style
|
||||
|
||||
The request-body top-level `style` field controls deterministic image post-processing. It is separate from `generationInputs.artSpec.style`, which only describes the requested visual language for prompting.
|
||||
|
||||
- Omitted, `null`, an empty string, and `"none"` all disable post-processing without a warning.
|
||||
- `"pixelArt"` enables deterministic pixel-art snapping for ordinary image generation (omit `kind`), `kind: "character"`, and icon spritesheet generation.
|
||||
- Unknown strings, or `"pixelArt"` on unsupported image kinds such as `spec`, `quick-edit`, `ui-design`, or `publication-material`, continue without style processing and return `warning.code: "unsupported-image-style"`.
|
||||
- A non-string JSON value is malformed and returns HTTP `400`. Keep the field extensible; do not treat the current examples as a closed client-side enum.
|
||||
|
||||
Image or character generation with pixel-art snapping:
|
||||
|
||||
```json
|
||||
{
|
||||
"prompt": "生成一个正面站立的像素风冒险者角色",
|
||||
"kind": "character",
|
||||
"style": "pixelArt"
|
||||
}
|
||||
```
|
||||
|
||||
Icon spritesheet generation with pixel-art snapping:
|
||||
|
||||
```json
|
||||
{
|
||||
"referenceImageSrc": "generated-character-drafts/editor/external-editor-references/icon-spec.png",
|
||||
"iconDescriptions": ["木剑", "圆盾", "红色药水"],
|
||||
"style": "pixelArt"
|
||||
}
|
||||
```
|
||||
|
||||
All generation requests should be placed into both the current canvas and its same-name asset-library folder. For endpoints that support `assetLabel`, pass it. For UI extraction, use `spritesheetLabel`. For icon spritesheet, the folder is enough. For character animation, pass `assetFolderId` and `assetLabel` to the generation endpoint and use the returned final `resource` / `asset`; never create another resource or asset from its first frame.
|
||||
|
||||
## HTTP 2xx Warning Handling
|
||||
|
||||
Character image generation (including character redraw through `kind: "character"`), icon spritesheet generation, and UI asset extraction may return HTTP 2xx while carrying a structured `warning`; completion does not imply that all post-processed derivatives exist.
|
||||
|
||||
- Consume the returned `project` and media snapshots as authoritative: character responses use `resource` / `asset`, while icon spritesheet and UI extraction responses use `spritesheetResource` / `spritesheetAsset`. `warning.code: "postprocess-failed-source-preserved"` means the saved provider source is the main result. Character output has no transparent derivative, while icon spritesheet and UI extraction have no transparent spritesheet and no slices. Display `warning.reason` directly; do not construct missing assets or retry the provider generation from scratch.
|
||||
- `sliceWarning` is only for a transparent spritesheet that was created successfully but could not be split automatically. Use the complete transparent spritesheet and preserve `sliceWarning.reason` as the original diagnostic; it is not a post-processing/source-preserved warning.
|
||||
- `warning` and `sliceWarning` are mutually exclusive only for `postprocess-failed-source-preserved`, because that failure never reaches slicing. A general `warning` produced by image-style normalization (`unsupported-image-style`) or pixel-art snapping can coexist with `sliceWarning`; render both reasons instead of picking one.
|
||||
|
||||
## Reference Image Upload
|
||||
|
||||
If the user provides a local file as a reference image, run upload before the generation request:
|
||||
|
||||
1. `POST /api/external/v1/assets/direct-upload-tickets`.
|
||||
Use `legacyPrefix: "generated-character-drafts"`, `pathSegments: ["editor", "external-editor-references"]`, original `fileName`, detected image `contentType`, and `access: "private"`.
|
||||
2. Upload the file to the returned OSS form endpoint with all returned `formFields`.
|
||||
3. `POST /api/external/v1/assets/objects/confirm` with returned `objectKey`, detected `contentType`, `contentLength` if known, `assetKind: "editor_reference_image"`, and `accessPolicy: "private"`.
|
||||
4. Use the returned `objectKey` in the actual editor request.
|
||||
|
||||
OSS form upload uses `upload.host` and every non-null `upload.formFields` entry, then the file part named `file`. Default responses expose `upload`; envelope responses expose `data.upload`. Save the upload ticket response as `ticket.json`:
|
||||
|
||||
```bash
|
||||
node - <<'NODE' ticket.json /path/to/reference.png
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
(async () => {
|
||||
const body = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
|
||||
const ticket = body.upload || body.data?.upload;
|
||||
if (!ticket) throw new Error('Upload ticket response missing upload payload');
|
||||
const filePath = process.argv[3];
|
||||
const form = new FormData();
|
||||
for (const [key, value] of Object.entries(ticket.formFields)) {
|
||||
if (value != null) form.append(key, value);
|
||||
}
|
||||
const bytes = fs.readFileSync(filePath);
|
||||
form.append(
|
||||
'file',
|
||||
new Blob([bytes], { type: ticket.contentType || 'application/octet-stream' }),
|
||||
path.basename(filePath),
|
||||
);
|
||||
const response = await fetch(ticket.host, { method: 'POST', body: form });
|
||||
if (!response.ok) {
|
||||
throw new Error(`OSS upload failed: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
})().catch((error) => {
|
||||
console.error(error.message);
|
||||
process.exit(1);
|
||||
});
|
||||
NODE
|
||||
```
|
||||
|
||||
Field mapping after upload:
|
||||
|
||||
| Target API | Put uploaded `objectKey` in |
|
||||
| --- | --- |
|
||||
| Image generation | `referenceImageSrcs` |
|
||||
| Image edit/redraw | `sourceImageSrc`; additional references in `referenceImageSrcs` |
|
||||
| Icon spritesheet | `referenceImageSrc`; additional style refs in `referenceImageSrcs` |
|
||||
| UI design extraction | `sourceImageSrc`; additional refs in `referenceImageSrcs` |
|
||||
| Character animation | `sourceImageSrc` |
|
||||
| Video generation with image references | `referenceImageSrcs` |
|
||||
|
||||
Do not put the signed read URL into generation fields. Signed URLs are for user-visible preview/download; generation fields should use the stable `objectKey` for uploaded private references.
|
||||
|
||||
## Common Enums
|
||||
|
||||
- Image `kind`: `spec`, `character`, `quick-edit`, `ui-design`, `publication-material`.
|
||||
- Image `model`: `gpt-image-2`, `gemini-3.1-flash-image-preview`, `nanobanana2`, `nano-banana`.
|
||||
- Image `aspectRatio`: `1:1`, `2:3`, `3:2`, `9:16`, `16:9`.
|
||||
- Image `imageSize`: `0.5K`, `1K`, `2K`.
|
||||
- Video `model`: `seedance2.0`, `seedance2.0-fast`, `kling3.0`, `kling3.0-omni`, `veo3.1`, `veo3.1-fast`.
|
||||
- Video `aspectRatio`: `16:9`, `9:16`, `1:1`, `4:3`, `3:4`, `21:9`.
|
||||
- Video `resolution`: `480p`, `720p`, `1080p`.
|
||||
- Video `mode`: always `std`.
|
||||
- Video `sound`: `on`, `off`.
|
||||
- Character animation `model`: always `seedance2.0-fast`.
|
||||
- Character animation `resolution`: `480p`, `720p`; `frameCount`: `32`, `40`, `48`; `durationSeconds`: `4`, `5`, `6`; `ratio`: `same`, `1:1`, `4:3`, `16:9`, `9:16`, `3:4`.
|
||||
|
||||
## Local Reference Media Details
|
||||
|
||||
- `contentLength` in object confirm is a JSON number from local byte size, not a string.
|
||||
- For character animation, use an existing project layer ID as `sourceLayerId` when available.
|
||||
- If the source is only an uploaded local image, derive `sourceLayerId` from the file name, such as `external-reference-hero`, and keep it stable across retries.
|
||||
- Read `sourceWidth` and `sourceHeight` from the local image. If dimensions cannot be read, ask instead of inventing dimensions.
|
||||
- UI design extraction uses fixed `aspectRatio: "1:1"`; choose `imageSize: "1K"` for normal/small extractions and `2K` for dense designs.
|
||||
- Video image/video/audio references are supported only by the Seedance 2.0 family; default referenced-media video requests to `model: "seedance2.0-fast"`, `mode: "std"`, and explicit `sound`.
|
||||
- Image edit/redraw can pass `targetLayerId` with `projectId` to replace an existing canvas layer when no explicit `canvasCompletion` is supplied.
|
||||
- Image, edit, video, sound effect, and BGM generation can pass `assetFolderId` and `assetLabel`; response `asset` is the created/updated library record.
|
||||
- Icon spritesheet and UI extraction can pass `assetFolderId`; UI extraction can also pass `spritesheetLabel`.
|
||||
|
||||
## Canvas Completion
|
||||
|
||||
Use `canvasCompletion` for generation in this skill so the generated result is written back into the project canvas by the backend.
|
||||
|
||||
Required:
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "素材名称",
|
||||
"placeholder": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"width": 512,
|
||||
"height": 512,
|
||||
"originalWidth": 512,
|
||||
"originalHeight": 512
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`dialogId` is optional. If the response includes `project`, `resource`, or `asset`, use those snapshots instead of reconstructing canvas/resource/library state locally.
|
||||
|
||||
## Upload Flow
|
||||
|
||||
For a local file that should become a project resource or library asset:
|
||||
|
||||
1. `POST /api/external/v1/assets/direct-upload-tickets` with `legacyPrefix`, `fileName`, and optional `contentType`, `access`, `maxSizeBytes`.
|
||||
2. Submit the file to the returned OSS form endpoint with returned `formFields`.
|
||||
3. `POST /api/external/v1/assets/objects/confirm` with returned `objectKey` and an `assetKind`.
|
||||
4. Create a project resource or library asset with the confirmed `assetObjectId`/`objectKey`.
|
||||
|
||||
For reading private/generated assets, call `GET /api/external/v1/assets/read-url?objectKey=...` and use the returned `signedUrl`.
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
# Authentication and Safety
|
||||
|
||||
Read this reference before handling credentials, local files, private objects, uploads, retries, or logs.
|
||||
|
||||
## Contents
|
||||
|
||||
- [API Key Setup](#api-key-setup)
|
||||
- [Idempotency and Unknown Outcomes](#idempotency-and-unknown-outcomes)
|
||||
- [Local Reference Upload](#local-reference-upload)
|
||||
- [Stable and Temporary Media References](#stable-and-temporary-media-references)
|
||||
- [Logging and Command Safety](#logging-and-command-safety)
|
||||
- [Scope and Retry Guardrails](#scope-and-retry-guardrails)
|
||||
|
||||
## API Key Setup
|
||||
|
||||
Authenticated calls use:
|
||||
|
||||
```text
|
||||
Authorization: Bearer <tnr_sk_...>
|
||||
```
|
||||
|
||||
Guide a logged-in user to create a key in the product UI under `开发者 API Key`. The raw key is shown only once. Never ask the user to paste it into chat.
|
||||
|
||||
Store it outside repositories in the user's private JSON file:
|
||||
|
||||
```text
|
||||
~/.config/genarrative/external-editor-api.json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"apiKey": "tnr_sk_..."
|
||||
}
|
||||
```
|
||||
|
||||
Set the file readable only by the current user where supported:
|
||||
|
||||
```bash
|
||||
chmod 600 ~/.config/genarrative/external-editor-api.json
|
||||
```
|
||||
|
||||
Use this fixed production base URL:
|
||||
|
||||
```text
|
||||
https://www.genarrative.world/
|
||||
```
|
||||
|
||||
Do not use environment variables as the default API Key storage for this integration. Generated clients must load the JSON file, fail clearly when it is absent or malformed, and redact credentials from errors and logs.
|
||||
|
||||
Smoke-test without printing the key:
|
||||
|
||||
```bash
|
||||
api_key="$(node -e 'const fs=require("fs"); const p=process.argv[1]; const c=JSON.parse(fs.readFileSync(p,"utf8")); process.stdout.write(c.apiKey || "");' "$HOME/.config/genarrative/external-editor-api.json")"
|
||||
curl -fsS "https://www.genarrative.world/api/external/v1/editor/projects" \
|
||||
-H "Authorization: Bearer $api_key"
|
||||
```
|
||||
|
||||
The OpenAPI document, integration manifest, raw Skill entry, and Skill archive are public. Hosted MCP and all project, asset, upload, generation, and generation-query operations require the Bearer API Key.
|
||||
|
||||
## Idempotency and Unknown Outcomes
|
||||
|
||||
For each logical generation:
|
||||
|
||||
1. Create one printable ASCII `Idempotency-Key` of 1-128 bytes.
|
||||
2. Persist the key with the exact request body and returned `operationId`.
|
||||
3. If submission transport fails or the response is lost, resend only the exact same body with the same key.
|
||||
4. Never allocate a new key merely because the outcome is unknown.
|
||||
5. On a polling timeout, retain `operationId` and query later. Do not submit another generation.
|
||||
|
||||
Treat a different body under the same key as invalid. Do not automatically replay a failed terminal generation unless the user intentionally requests a new logical generation.
|
||||
|
||||
## Local Reference Upload
|
||||
|
||||
Do not ask the user to convert local files to base64. Upload from the Agent/client machine:
|
||||
|
||||
1. Detect the original filename, MIME type, byte length, and image dimensions when relevant.
|
||||
2. Create a ticket with `POST /api/external/v1/assets/direct-upload-tickets`.
|
||||
3. POST all returned non-null `formFields` and the file part named `file` directly to `upload.host`.
|
||||
4. Confirm the object with `POST /api/external/v1/assets/objects/confirm`.
|
||||
5. Pass the confirmed stable `objectKey` to the selected editor operation.
|
||||
|
||||
For a private reference image, use a ticket body shaped like:
|
||||
|
||||
```json
|
||||
{
|
||||
"legacyPrefix": "generated-character-drafts",
|
||||
"pathSegments": ["editor", "external-editor-references"],
|
||||
"fileName": "<original-file-name>",
|
||||
"contentType": "image/png",
|
||||
"access": "private"
|
||||
}
|
||||
```
|
||||
|
||||
The default response exposes `upload`; an explicitly enveloped response exposes `data.upload`. Treat the returned host and form fields as opaque. Do not log the entire ticket or persist it longer than needed.
|
||||
|
||||
Confirm with the actual file metadata:
|
||||
|
||||
```json
|
||||
{
|
||||
"objectKey": "<upload.objectKey>",
|
||||
"contentType": "image/png",
|
||||
"contentLength": 12345,
|
||||
"assetKind": "editor_reference_image",
|
||||
"accessPolicy": "private"
|
||||
}
|
||||
```
|
||||
|
||||
`contentLength` is a JSON number in bytes, not a quoted string. Never invent `sourceWidth` or `sourceHeight`; read them from the local image or ask the user if they cannot be determined.
|
||||
|
||||
For character animation, reuse a real canvas layer ID when available. For a local-only source, derive a stable synthetic `sourceLayerId`, such as `external-reference-hero`, from the filename and keep it unchanged across retries.
|
||||
|
||||
The bundled helper implements ticket creation, a stdlib multipart upload, confirmation, dimension detection for common formats, and stable source-layer IDs:
|
||||
|
||||
```python
|
||||
from genarrative_external_api import GenarrativeExternalClient
|
||||
|
||||
client = GenarrativeExternalClient()
|
||||
reference = client.upload_reference_image("/path/to/reference.png")
|
||||
print(reference["objectKey"])
|
||||
```
|
||||
|
||||
Do not print the complete confirmation response if it may contain temporary access data. Prefer passing the returned `objectKey` directly to the next call.
|
||||
|
||||
## Stable and Temporary Media References
|
||||
|
||||
- Use `objectKey`, project resource ID, asset ID, or an allowed durable public URL for generation input.
|
||||
- Use a Data URL only when the endpoint explicitly allows it and the caller has a deliberate reason; do not persist it as a durable output.
|
||||
- Never use a Blob URL outside the browser process that created it.
|
||||
- Use `GET /api/external/v1/assets/read-url` to obtain a short-lived `signedUrl` for display/download.
|
||||
- Never store or feed an expiring signed URL back into generation when a stable `objectKey` exists.
|
||||
|
||||
## Logging and Command Safety
|
||||
|
||||
- Never place an API Key in repository files, generated projects, command arguments containing a literal key, docs, commits, screenshots, stack traces, test fixtures, or telemetry.
|
||||
- Redact `Authorization`, API Key values, upload signatures, cookies, signed URL query strings, and private absolute paths from logs and user-visible errors.
|
||||
- Do not print credentials while diagnosing JSON configuration. Report only presence/absence and safe validation errors.
|
||||
- Do not commit the credentials file or copy it into the Skill archive.
|
||||
- Do not expose provider diagnostics, worker leases, queue internals, or server filesystem paths returned by an unexpected error.
|
||||
|
||||
## Scope and Retry Guardrails
|
||||
|
||||
- Do not use account JWT/profile endpoints as the default external integration. Logged-in profile APIs may create/revoke developer keys, but they are outside this external editor contract.
|
||||
- Do not call internal workers, queues, SpacetimeDB, or admin endpoints.
|
||||
- Do not bypass upload confirmation or invent an object key.
|
||||
- Do not retry post-processing locally by fabricating assets. Respect completed warning semantics from `requests-and-outputs.md`.
|
||||
- Use bounded polling. A local wait budget ending does not cancel or fail the server operation.
|
||||
@@ -0,0 +1,87 @@
|
||||
# Capability Routing
|
||||
|
||||
Use this reference to translate user intent into a hosted MCP tool or its corresponding External v1 REST operation. Use `genarrative://external-editor/openapi` or `GET /api/external/v1/openapi.json` for exact schemas.
|
||||
|
||||
## Integration Surface
|
||||
|
||||
- Fixed production base URL: `https://www.genarrative.world/`.
|
||||
- Discovery manifest: `GET /api/external/v1/agent-integration.json`.
|
||||
- Hosted MCP: `/api/external/v1/mcp`, Streamable HTTP, authenticated with the same Bearer API Key as REST.
|
||||
- Public contract: `GET /api/external/v1/openapi.json`.
|
||||
- Skill fallback: `GET /api/external/v1/skill/SKILL.md` or `GET /api/external/v1/skill.zip`.
|
||||
|
||||
Prefer MCP when the Agent supports a remote endpoint plus a custom Bearer token. Prefer the complete Skill and Python helper when MCP is unavailable or a client-side local-file upload must be orchestrated. The MCP tool names are derived from OpenAPI `operationId` values in snake case; select by capability instead of memorizing the name.
|
||||
|
||||
## Canvas Session
|
||||
|
||||
Before the first generation in a new conversation, obtain a canvas name unless the user already supplied an existing `projectId` and `assetFolderId`.
|
||||
|
||||
1. List or create a project. When creating one, use the canvas name as `title`.
|
||||
2. Read the asset library. Reuse a folder with the same label or create one with the canvas name.
|
||||
3. Retain `canvasName`, `projectId`, `assetFolderId`, and the current art spec in conversation state.
|
||||
|
||||
Generated artifacts must enter both the current canvas and its same-name library folder whenever the endpoint supports that invariant. Pass `projectId`, `assetFolderId`, the endpoint's label field, and `canvasCompletion`. Character animation returns the final formal resource and asset directly; use those records and never create a duplicate from the first frame.
|
||||
|
||||
## Art Spec Routing
|
||||
|
||||
Before art generation, normalize the user's request into:
|
||||
|
||||
```json
|
||||
{
|
||||
"assetType": "character | background | prop | ui | icon | animation | video | audio",
|
||||
"subject": "要生成的主体",
|
||||
"style": "画风、材质、时代或参考风格",
|
||||
"palette": "主色与禁用色",
|
||||
"composition": "构图、镜头、姿态或布局",
|
||||
"format": "比例、尺寸、分辨率、帧数或时长",
|
||||
"constraints": "必须保留、禁止出现、透明或绿幕要求",
|
||||
"references": ["objectKey、资源 ID 或本地文件说明"]
|
||||
}
|
||||
```
|
||||
|
||||
Infer what is already clear and ask only for missing fields that block the selected endpoint. Reuse the current spec unless the user changes style, subject family, palette, format, or constraints. Store structured context under `generationInputs.artSpec` where supported and summarize it in the prompt when useful.
|
||||
|
||||
## Intent Map
|
||||
|
||||
| User intent | MCP/REST capability |
|
||||
| --- | --- |
|
||||
| Generate a background, character, spec, UI mockup, or publication image | Image generation |
|
||||
| Redraw, retouch, or replace an existing image | Image edit |
|
||||
| Generate from a local reference | Upload and confirm the local file, then image generation or edit |
|
||||
| Build a reusable transparent icon/game atlas from a visual spec | Icon spritesheet generation |
|
||||
| Extract marked assets from an existing UI design | UI design asset extraction |
|
||||
| Animate a character into frames | Character animation generation |
|
||||
| Generate video | Video generation |
|
||||
| Generate a sound effect | Sound-effect generation |
|
||||
| Generate background music/BGM | Background-music generation |
|
||||
| Upload a local image/audio/video asset | Upload ticket -> OSS form upload -> object confirm |
|
||||
| Save viewport/layers | Canvas save |
|
||||
| Create, load, rename, or delete a canvas | Project operations |
|
||||
| Organize folders and asset records | Asset-library operations |
|
||||
| Obtain temporary access to private media | Signed read URL |
|
||||
| Check generation progress or retrieve its result | Generation query |
|
||||
|
||||
Do not present an API menu unless the request is genuinely ambiguous. Ask a follow-up when two routes create different artifacts, for example “处理这张图” could mean edit, extract marked UI assets, or use it as a reference for a new generation.
|
||||
|
||||
## Route-Specific Decisions
|
||||
|
||||
- Use image edit when the requested output replaces or modifies a source image. With `projectId`, pass `targetLayerId` to replace an existing layer when no explicit `canvasCompletion` is supplied.
|
||||
- Use icon spritesheet generation for a transparent reusable atlas when a stable visual-spec reference and concrete `iconDescriptions` exist. Do not use ordinary image generation just because it can draw several objects.
|
||||
- Use UI extraction only for an existing UI design image with red-box annotations. It is not UI generation.
|
||||
- Use a project layer ID as character animation `sourceLayerId` when one exists. For a local-only source, derive a stable synthetic ID from the filename.
|
||||
- For video with image/video/audio references, use a Seedance 2.0-family model; default to `seedance2.0-fast`, `mode: "std"`, and explicit `sound`.
|
||||
- Use `signedUrl` only for preview/download. Feed stable `objectKey` or registered resource/asset identifiers into generation.
|
||||
|
||||
## AI Game Creator Canonical Visual DAG
|
||||
|
||||
Keep the existing autonomous-build task graph. Do not add a parallel task system or collapse these artifacts into one ordinary generation request:
|
||||
|
||||
1. `art-director` generates `assets/art-spec.png` with image generation, `kind: "spec"`, then registers it as `assetKind: "icon-spec"`. This image is the authoritative visual spec; `generationInputs.artSpec` is supporting structured context.
|
||||
2. `design-foundation` generates `assets/ui-prototype.png` with `kind: "ui-design"`, using the registered art-spec resource ID in `referenceImageSrcs`.
|
||||
3. `art-asset-plan` generates transparent `assets/art-spritesheet.png` through icon spritesheet generation, using the same registered art-spec resource ID as `referenceImageSrc` plus concrete `iconDescriptions`.
|
||||
|
||||
Never use `assets/ui-prototype.png` as the spritesheet visual-spec reference. UI extraction is outside this canonical DAG.
|
||||
|
||||
## Scope Boundary
|
||||
|
||||
Stay within `/api/external/v1`. Do not invent worker, queue, runtime task-list, admin, profile, or SpacetimeDB calls. The only external generation query is `GET /api/external/v1/generations/{operationId}`.
|
||||
@@ -0,0 +1,238 @@
|
||||
# Requests and Outputs
|
||||
|
||||
Use this reference to build generation payloads, carry canvas/library context, poll asynchronous jobs, and interpret compact completed results. Verify exact schemas against `GET /api/external/v1/openapi.json`.
|
||||
|
||||
## Contents
|
||||
|
||||
- [Asynchronous Submission](#asynchronous-submission)
|
||||
- [Polling State Machine](#polling-state-machine)
|
||||
- [Canvas and Asset-Library Completion](#canvas-and-asset-library-completion)
|
||||
- [Art Spec and Image Request](#art-spec-and-image-request)
|
||||
- [Local Reference Requests](#local-reference-requests)
|
||||
- [Compact Completed Result](#compact-completed-result)
|
||||
- [Warning Semantics](#warning-semantics)
|
||||
- [Output Handling Checklist](#output-handling-checklist)
|
||||
|
||||
## Asynchronous Submission
|
||||
|
||||
All eight generation POST routes require `Idempotency-Key` and return HTTP `202` with an `ExternalEditorGenerationSubmissionResponse` shaped like:
|
||||
|
||||
```json
|
||||
{
|
||||
"operationId": "task-...",
|
||||
"kind": "editor_image_generation",
|
||||
"status": "queued",
|
||||
"statusUrl": "/api/external/v1/generations/task-...",
|
||||
"pollAfterMs": 1500,
|
||||
"updatedAtMicros": 1785456000000000
|
||||
}
|
||||
```
|
||||
|
||||
The response acknowledges durable submission only. It is never the completed media response.
|
||||
|
||||
Submit with one stable key per logical request:
|
||||
|
||||
```bash
|
||||
api="https://www.genarrative.world"
|
||||
credentials_file="$HOME/.config/genarrative/external-editor-api.json"
|
||||
api_key="$(node -e 'const fs=require("fs"); const p=process.argv[1]; const c=JSON.parse(fs.readFileSync(p,"utf8")); process.stdout.write(c.apiKey || "");' "$credentials_file")"
|
||||
idempotency_key="$(node -e 'process.stdout.write(require("node:crypto").randomUUID())')"
|
||||
|
||||
submission="$(curl -fsS "$api/api/external/v1/editor/images/generations" \
|
||||
-H "Authorization: Bearer $api_key" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Idempotency-Key: $idempotency_key" \
|
||||
-d @request.json)"
|
||||
operation_id="$(node -e 'const v=JSON.parse(process.argv[1]); process.stdout.write(v.operationId || v.data?.operationId || "")' "$submission")"
|
||||
```
|
||||
|
||||
Persist the key, exact request body, and `operationId`. If submission outcome is uncertain, reuse the same body and key; do not submit a replacement key.
|
||||
|
||||
## Polling State Machine
|
||||
|
||||
Poll `statusUrl`, or `GET /api/external/v1/generations/{operationId}`, no faster than `pollAfterMs`:
|
||||
|
||||
- `queued` / `running`: retain `operationId`; show `phaseLabel`, `phaseDetail`, and `progress` when present; wait before querying again.
|
||||
- `completed`: consume the compact `result` and all warning fields, then stop polling.
|
||||
- `failed`: surface the safe `error`, stop polling, and do not infer provider or worker internals.
|
||||
|
||||
A caller-side timeout leaves the operation pending. Persist the ID for later query. Do not keep the original POST connection open and do not infer failure from a local wait budget.
|
||||
|
||||
The helper's convenience generation methods block only in the local process while sending short submit and status requests. Its default overall wait budget is 1800 seconds. For explicit orchestration:
|
||||
|
||||
```python
|
||||
submission = client.submit_generation(
|
||||
"/api/external/v1/editor/images/generations",
|
||||
request_body,
|
||||
idempotency_key=stable_key,
|
||||
)
|
||||
operation_id = submission["operationId"]
|
||||
status = client.get_generation(operation_id)
|
||||
completed = client.wait_for_generation(operation_id)
|
||||
```
|
||||
|
||||
## Canvas and Asset-Library Completion
|
||||
|
||||
For endpoints that support these fields, include:
|
||||
|
||||
- `projectId`: target canvas project.
|
||||
- `assetFolderId`: folder whose label matches the canvas name.
|
||||
- `assetLabel` or UI extraction's `spritesheetLabel`: user-visible library label.
|
||||
- `canvasCompletion`: backend canvas placement instructions.
|
||||
|
||||
A minimal `canvasCompletion` is:
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "素材名称",
|
||||
"placeholder": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"width": 1024,
|
||||
"height": 576,
|
||||
"originalWidth": 1024,
|
||||
"originalHeight": 576
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`dialogId` is optional. Do not reconstruct canvas state from completion results. Reload the project and asset library when complete authoritative snapshots are needed.
|
||||
|
||||
Character animation accepts `assetFolderId` and `assetLabel` and persists the final transparent sequence directly. Its completed compact result includes the authoritative `assetKind="character-animation"` resource and asset with `imageSequenceFrames` and `imageSequenceDurationMs`. Use those records directly and never synthesize a duplicate asset from the first frame.
|
||||
|
||||
## Art Spec and Image Request
|
||||
|
||||
Carry the current art spec in `generationInputs.artSpec` and reflect important constraints in the prompt:
|
||||
|
||||
```json
|
||||
{
|
||||
"prompt": "一张横版幻想森林背景,适合游戏主视觉,无文字",
|
||||
"aspectRatio": "16:9",
|
||||
"imageSize": "1K",
|
||||
"projectId": "<projectId>",
|
||||
"assetFolderId": "<assetFolderId>",
|
||||
"assetLabel": "森林背景",
|
||||
"generationInputs": {
|
||||
"artSpec": {
|
||||
"assetType": "background",
|
||||
"subject": "幻想森林主视觉",
|
||||
"style": "手绘游戏概念图",
|
||||
"palette": "翡翠绿与金色光斑",
|
||||
"composition": "横版,中心留出角色站位",
|
||||
"format": "16:9, 1K",
|
||||
"constraints": "无文字、无 UI 按钮",
|
||||
"references": []
|
||||
}
|
||||
},
|
||||
"canvasCompletion": {
|
||||
"title": "森林背景",
|
||||
"placeholder": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"width": 1024,
|
||||
"height": 576,
|
||||
"originalWidth": 1024,
|
||||
"originalHeight": 576
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The top-level `style` field is not the art spec's visual-style prose. It controls deterministic post-processing:
|
||||
|
||||
- Omitted, `null`, empty string, or `"none"`: disable post-processing without warning.
|
||||
- `"pixelArt"`: enable pixel-art snapping for ordinary image generation, `kind: "character"`, and icon spritesheet generation.
|
||||
- Unknown strings, or `"pixelArt"` on unsupported kinds such as `spec`, `quick-edit`, `ui-design`, or `publication-material`: continue without style processing and return `warning.code: "unsupported-image-style"`.
|
||||
- Non-string JSON values: malformed request, HTTP `400`.
|
||||
|
||||
Keep this field extensible. Do not impose a closed client enum beyond the server contract.
|
||||
|
||||
## Local Reference Requests
|
||||
|
||||
Upload and confirm a local file before generation, then use the stable `objectKey`:
|
||||
|
||||
```python
|
||||
client = GenarrativeExternalClient()
|
||||
session = client.prepare_canvas_session("新画板")
|
||||
reference = client.upload_reference_image("/path/to/reference.png")
|
||||
client.generate_image(
|
||||
"基于参考图生成一张 16:9 游戏背景",
|
||||
canvasSession=session,
|
||||
assetLabel="参考图背景",
|
||||
aspectRatio="16:9",
|
||||
imageSize="1K",
|
||||
referenceImageSrcs=[reference["objectKey"]],
|
||||
)
|
||||
```
|
||||
|
||||
For character animation from a local-only source, use actual dimensions and a stable synthetic layer ID:
|
||||
|
||||
```json
|
||||
{
|
||||
"sourceLayerId": "external-reference-hero",
|
||||
"sourceImageSrc": "<confirmed objectKey>",
|
||||
"sourceWidth": 720,
|
||||
"sourceHeight": 1280,
|
||||
"promptText": "让角色自然呼吸并轻微转身",
|
||||
"resolution": "720p",
|
||||
"ratio": "9:16",
|
||||
"frameCount": 40,
|
||||
"durationSeconds": 5,
|
||||
"model": "seedance2.0-fast",
|
||||
"assetFolderId": "<assetFolderId>",
|
||||
"assetLabel": "角色呼吸动画"
|
||||
}
|
||||
```
|
||||
|
||||
Do not guess dimensions or pass a temporary signed read URL. See `authentication-and-safety.md` for upload and credential rules.
|
||||
|
||||
## Compact Completed Result
|
||||
|
||||
The completed `result` may contain stable artifact fields such as:
|
||||
|
||||
- `objectKey`, media type, dimensions, or task ID.
|
||||
- `resource`, `resourceId`, or equivalent canvas reference.
|
||||
- `asset`, `assetId`, or equivalent library reference.
|
||||
- `spritesheetResource`, `spritesheetAsset`, and stable spritesheet metadata.
|
||||
- `warning` and `sliceWarning` structures.
|
||||
|
||||
It deliberately excludes a complete project/canvas/library snapshot, Data URL, Blob URL, expiring signed URL, worker lease, queue state, and internal provider diagnostics. Use `/assets/read-url` for temporary access to a stable `objectKey`.
|
||||
|
||||
## Warning Semantics
|
||||
|
||||
Interpret warnings only after the query reaches `status=completed`. The query-level `warning` is display-ready text. Compact `result.warning` and `result.sliceWarning` preserve structured artifact semantics.
|
||||
|
||||
### Source-preserved post-processing failure
|
||||
|
||||
When `result.warning.code` is `postprocess-failed-source-preserved`:
|
||||
|
||||
- Treat the saved provider source as the authoritative main result.
|
||||
- For character output, do not claim a transparent derivative.
|
||||
- For icon spritesheet or UI extraction, do not claim a transparent spritesheet or individual slices.
|
||||
- Display the safe reason.
|
||||
- Do not fabricate derivatives or restart generation automatically.
|
||||
|
||||
Use `resource` / `asset` for character results and `spritesheetResource` / `spritesheetAsset` for icon/UI results, then reload authoritative project/library state.
|
||||
|
||||
### Slice failure after transparent-sheet success
|
||||
|
||||
`result.sliceWarning` means transparent spritesheet post-processing succeeded but automatic splitting failed:
|
||||
|
||||
- Continue using the complete transparent spritesheet.
|
||||
- Do not claim individual slices.
|
||||
- Display the slice reason.
|
||||
|
||||
### Coexisting warnings
|
||||
|
||||
`warning` and `sliceWarning` are mutually exclusive only for `postprocess-failed-source-preserved`, because that path never reaches slicing. A general warning from unsupported style normalization or pixel-art snapping can coexist with `sliceWarning`. Render both reasons.
|
||||
|
||||
Before registering a requested transparent deliverable, verify the full sheet actually contains transparency. If source-preserved warning is present, do not register the opaque provider source as the requested transparent atlas. If only `sliceWarning` is present, the transparent full sheet remains valid.
|
||||
|
||||
## Output Handling Checklist
|
||||
|
||||
1. Require terminal `completed` before consuming artifacts.
|
||||
2. Preserve stable IDs and `objectKey` values.
|
||||
3. Surface all warning channels without downgrading completion to failure.
|
||||
4. Avoid claiming absent transparent derivatives or slices.
|
||||
5. Obtain temporary preview/download URLs only through `/assets/read-url`.
|
||||
6. Reload authoritative project and library state when downstream logic needs complete records.
|
||||
+145
-37
@@ -11,6 +11,7 @@ import re
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
@@ -22,7 +23,7 @@ from typing import Any
|
||||
BASE_URL = "https://www.genarrative.world/"
|
||||
DEFAULT_CREDENTIALS_FILE = Path.home() / ".config/genarrative/external-editor-api.json"
|
||||
DEFAULT_REQUEST_TIMEOUT_SECONDS = 60
|
||||
GENERATION_REQUEST_TIMEOUT_SECONDS = 420
|
||||
GENERATION_WAIT_TIMEOUT_SECONDS = 1800
|
||||
|
||||
|
||||
class GenarrativeApiError(RuntimeError):
|
||||
@@ -125,17 +126,18 @@ class GenarrativeExternalClient:
|
||||
query: dict[str, Any] | None = None,
|
||||
auth: bool = True,
|
||||
timeout: int = DEFAULT_REQUEST_TIMEOUT_SECONDS,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> Any:
|
||||
url = f"{self.base_url}{path}"
|
||||
if query:
|
||||
url = f"{url}?{urllib.parse.urlencode({k: v for k, v in query.items() if v is not None})}"
|
||||
data = None if body is None else json.dumps(body).encode("utf-8")
|
||||
headers = {"Accept": "application/json"}
|
||||
request_headers = {"Accept": "application/json", **(headers or {})}
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
request_headers["Content-Type"] = "application/json"
|
||||
if auth:
|
||||
headers["Authorization"] = f"Bearer {self.api_key}"
|
||||
request = urllib.request.Request(url, data=data, headers=headers, method=method.upper())
|
||||
request_headers["Authorization"] = f"Bearer {self.api_key}"
|
||||
request = urllib.request.Request(url, data=data, headers=request_headers, method=method.upper())
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
payload = response.read()
|
||||
@@ -440,24 +442,120 @@ class GenarrativeExternalClient:
|
||||
def read_url(self, object_key: str) -> Any:
|
||||
return self.request_json("GET", "/api/external/v1/assets/read-url", query={"objectKey": object_key})
|
||||
|
||||
def submit_generation(
|
||||
self,
|
||||
path: str,
|
||||
body: dict[str, Any],
|
||||
idempotency_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
key = normalize_optional_text(idempotency_key) or str(uuid.uuid4())
|
||||
submission = None
|
||||
for attempt in range(2):
|
||||
try:
|
||||
submission = self.request_json(
|
||||
"POST",
|
||||
path,
|
||||
body,
|
||||
headers={"Idempotency-Key": key},
|
||||
)
|
||||
break
|
||||
except (urllib.error.URLError, TimeoutError) as error:
|
||||
if attempt == 0:
|
||||
time.sleep(0.5)
|
||||
continue
|
||||
raise GenarrativeApiError(
|
||||
"Generation submission transport outcome is unknown. "
|
||||
f"Retry the same body with Idempotency-Key {key}; do not create a new key."
|
||||
) from error
|
||||
if not isinstance(submission, dict) or not normalize_optional_text(submission.get("operationId")):
|
||||
raise GenarrativeApiError("Generation submission response missing operationId.")
|
||||
submission.setdefault("idempotencyKey", key)
|
||||
return submission
|
||||
|
||||
def get_generation(self, operation_id: str) -> dict[str, Any]:
|
||||
result = self.request_json(
|
||||
"GET",
|
||||
f"/api/external/v1/generations/{urllib.parse.quote(operation_id, safe='')}",
|
||||
)
|
||||
if not isinstance(result, dict):
|
||||
raise GenarrativeApiError("Generation status response must be an object.")
|
||||
return result
|
||||
|
||||
def wait_for_generation(
|
||||
self,
|
||||
submission_or_operation_id: dict[str, Any] | str,
|
||||
timeout_seconds: int = GENERATION_WAIT_TIMEOUT_SECONDS,
|
||||
) -> dict[str, Any]:
|
||||
operation_id = (
|
||||
submission_or_operation_id.get("operationId")
|
||||
if isinstance(submission_or_operation_id, dict)
|
||||
else submission_or_operation_id
|
||||
)
|
||||
operation_id = normalize_optional_text(operation_id)
|
||||
if not operation_id:
|
||||
raise GenarrativeApiError("Generation operationId is required.")
|
||||
deadline = time.monotonic() + max(1, timeout_seconds)
|
||||
while True:
|
||||
try:
|
||||
job = self.get_generation(operation_id)
|
||||
except GenarrativeApiError as error:
|
||||
if any(f"HTTP {status}" in str(error) for status in (429, 502, 503, 504)):
|
||||
if time.monotonic() >= deadline:
|
||||
raise GenarrativeApiError(
|
||||
f"Generation {operation_id} is still running; keep this operationId and continue polling."
|
||||
) from error
|
||||
time.sleep(1.5)
|
||||
continue
|
||||
raise
|
||||
status = job.get("status")
|
||||
if status == "completed":
|
||||
result = job.get("result")
|
||||
if not isinstance(result, dict):
|
||||
raise GenarrativeApiError(
|
||||
f"Generation {operation_id} completed without a result payload."
|
||||
)
|
||||
return result
|
||||
if status == "failed":
|
||||
raise GenarrativeApiError(
|
||||
f"Generation {operation_id} failed: {job.get('error') or 'unknown error'}"
|
||||
)
|
||||
if time.monotonic() >= deadline:
|
||||
raise GenarrativeApiError(
|
||||
f"Generation {operation_id} is still running; keep this operationId and continue polling."
|
||||
)
|
||||
poll_after_ms = job.get("pollAfterMs", 1500)
|
||||
if not isinstance(poll_after_ms, (int, float)):
|
||||
poll_after_ms = 1500
|
||||
time.sleep(max(0.25, min(float(poll_after_ms) / 1000.0, 5.0)))
|
||||
|
||||
def submit_and_wait_generation(
|
||||
self,
|
||||
path: str,
|
||||
body: dict[str, Any],
|
||||
idempotency_key: str | None = None,
|
||||
timeout_seconds: int = GENERATION_WAIT_TIMEOUT_SECONDS,
|
||||
) -> dict[str, Any]:
|
||||
submission = self.submit_generation(path, body, idempotency_key=idempotency_key)
|
||||
return self.wait_for_generation(submission, timeout_seconds=timeout_seconds)
|
||||
|
||||
def generate_image(self, prompt: str, **fields: Any) -> Any:
|
||||
self._apply_canvas_session_fields(fields, prompt, 1024, 1024)
|
||||
prompt = self._apply_art_spec(fields, prompt)
|
||||
return self.request_json(
|
||||
"POST",
|
||||
idempotency_key = fields.pop("idempotencyKey", None)
|
||||
return self.submit_and_wait_generation(
|
||||
"/api/external/v1/editor/images/generations",
|
||||
{"prompt": prompt, **fields},
|
||||
timeout=GENERATION_REQUEST_TIMEOUT_SECONDS,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
|
||||
def edit_image(self, prompt: str, source_image_src: str, **fields: Any) -> Any:
|
||||
self._apply_canvas_session_fields(fields, prompt, 1024, 1024)
|
||||
prompt = self._apply_art_spec(fields, prompt)
|
||||
return self.request_json(
|
||||
"POST",
|
||||
idempotency_key = fields.pop("idempotencyKey", None)
|
||||
return self.submit_and_wait_generation(
|
||||
"/api/external/v1/editor/images/edits",
|
||||
{"prompt": prompt, "sourceImageSrc": source_image_src, **fields},
|
||||
timeout=GENERATION_REQUEST_TIMEOUT_SECONDS,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
|
||||
def generate_icon_spritesheet(
|
||||
@@ -472,25 +570,25 @@ class GenarrativeExternalClient:
|
||||
label = fields.get("assetLabel", "图标图集")
|
||||
self._apply_canvas_session_fields(fields, label, 1024, 1024)
|
||||
fields.setdefault("screenColor", "auto")
|
||||
return self.request_json(
|
||||
"POST",
|
||||
idempotency_key = fields.pop("idempotencyKey", None)
|
||||
return self.submit_and_wait_generation(
|
||||
"/api/external/v1/editor/icon-spritesheets/generations",
|
||||
{
|
||||
"referenceImageSrc": reference_image_src,
|
||||
"iconDescriptions": descriptions,
|
||||
**fields,
|
||||
},
|
||||
timeout=GENERATION_REQUEST_TIMEOUT_SECONDS,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
|
||||
def extract_ui_assets(self, source_image_src: str, image_size: str = "1K", **fields: Any) -> Any:
|
||||
fields.pop("aspectRatio", None)
|
||||
self._apply_canvas_session_fields(fields, fields.get("spritesheetLabel", "UI 素材拆分"), 1024, 1024, "spritesheetLabel")
|
||||
return self.request_json(
|
||||
"POST",
|
||||
idempotency_key = fields.pop("idempotencyKey", None)
|
||||
return self.submit_and_wait_generation(
|
||||
"/api/external/v1/editor/ui-designs/assets/extractions",
|
||||
{"sourceImageSrc": source_image_src, "imageSize": image_size, **fields, "aspectRatio": "1:1"},
|
||||
timeout=GENERATION_REQUEST_TIMEOUT_SECONDS,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
|
||||
def animate_character(
|
||||
@@ -510,6 +608,7 @@ class GenarrativeExternalClient:
|
||||
asset_label_field="assetLabel",
|
||||
)
|
||||
prompt_text = self._apply_art_spec(fields, prompt_text)
|
||||
idempotency_key = fields.pop("idempotencyKey", None)
|
||||
body = {
|
||||
"sourceLayerId": source_layer_id,
|
||||
"sourceImageSrc": source_image_src,
|
||||
@@ -523,17 +622,17 @@ class GenarrativeExternalClient:
|
||||
**fields,
|
||||
"model": "seedance2.0-fast",
|
||||
}
|
||||
return self.request_json(
|
||||
"POST",
|
||||
return self.submit_and_wait_generation(
|
||||
"/api/external/v1/editor/character-animations/generations",
|
||||
body,
|
||||
timeout=GENERATION_REQUEST_TIMEOUT_SECONDS,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
|
||||
def generate_video(self, prompt: str, **fields: Any) -> Any:
|
||||
fields.pop("mode", None)
|
||||
self._apply_canvas_session_fields(fields, prompt, 1280, 720)
|
||||
prompt = self._apply_art_spec(fields, prompt)
|
||||
idempotency_key = fields.pop("idempotencyKey", None)
|
||||
body = {
|
||||
"prompt": prompt,
|
||||
"model": fields.pop("model", "seedance2.0-fast"),
|
||||
@@ -544,31 +643,30 @@ class GenarrativeExternalClient:
|
||||
**fields,
|
||||
"mode": "std",
|
||||
}
|
||||
return self.request_json(
|
||||
"POST",
|
||||
return self.submit_and_wait_generation(
|
||||
"/api/external/v1/editor/videos/generations",
|
||||
body,
|
||||
timeout=GENERATION_REQUEST_TIMEOUT_SECONDS,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
|
||||
def generate_sound_effect(self, prompt: str, duration: int, **fields: Any) -> Any:
|
||||
self._apply_canvas_session_fields(fields, prompt, 360, 120)
|
||||
prompt = self._apply_art_spec(fields, prompt)
|
||||
return self.request_json(
|
||||
"POST",
|
||||
idempotency_key = fields.pop("idempotencyKey", None)
|
||||
return self.submit_and_wait_generation(
|
||||
"/api/external/v1/editor/audios/sound-effects/generations",
|
||||
{"prompt": prompt, "duration": duration, **fields},
|
||||
timeout=GENERATION_REQUEST_TIMEOUT_SECONDS,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
|
||||
def generate_background_music(self, description: str, **fields: Any) -> Any:
|
||||
self._apply_canvas_session_fields(fields, description, 360, 120)
|
||||
description = self._apply_art_spec(fields, description)
|
||||
return self.request_json(
|
||||
"POST",
|
||||
idempotency_key = fields.pop("idempotencyKey", None)
|
||||
return self.submit_and_wait_generation(
|
||||
"/api/external/v1/editor/audios/background-music/generations",
|
||||
{"gptDescriptionPrompt": description, **fields, "makeInstrumental": True},
|
||||
timeout=GENERATION_REQUEST_TIMEOUT_SECONDS,
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
|
||||
|
||||
@@ -600,9 +698,16 @@ def _self_test() -> None:
|
||||
query: dict[str, Any] | None = None,
|
||||
auth: bool = True,
|
||||
timeout: int = DEFAULT_REQUEST_TIMEOUT_SECONDS,
|
||||
headers: dict[str, str] | None = None,
|
||||
) -> Any:
|
||||
calls.append({"method": method, "path": path, "body": body, "timeout": timeout})
|
||||
return {
|
||||
calls.append({
|
||||
"method": method,
|
||||
"path": path,
|
||||
"body": body,
|
||||
"timeout": timeout,
|
||||
"headers": headers,
|
||||
})
|
||||
generated = {
|
||||
"taskId": "task-demo",
|
||||
"model": "seedance2.0-fast",
|
||||
"prompt": "角色呼吸",
|
||||
@@ -628,6 +733,11 @@ def _self_test() -> None:
|
||||
"imageSequenceDurationMs": 4000,
|
||||
},
|
||||
}
|
||||
if method == "POST":
|
||||
return {"operationId": "task-operation-demo", "status": "queued", "pollAfterMs": 1}
|
||||
if path == "/api/external/v1/generations/task-operation-demo":
|
||||
return {"operationId": "task-operation-demo", "status": "completed", "result": generated}
|
||||
return generated
|
||||
|
||||
client.request_json = fake_request_json # type: ignore[method-assign]
|
||||
result = client.animate_character(
|
||||
@@ -639,16 +749,13 @@ def _self_test() -> None:
|
||||
canvasSession=session,
|
||||
canvasTitle="角色呼吸动画",
|
||||
)
|
||||
assert calls[0]["timeout"] == GENERATION_REQUEST_TIMEOUT_SECONDS
|
||||
assert calls[0]["timeout"] == DEFAULT_REQUEST_TIMEOUT_SECONDS
|
||||
assert calls[0]["headers"]["Idempotency-Key"]
|
||||
assert calls[0]["body"]["projectId"] == "proj-demo"
|
||||
assert calls[0]["body"]["assetFolderId"] == "editor-asset-folder-demo"
|
||||
assert calls[0]["body"]["assetLabel"] == "角色呼吸动画"
|
||||
assert calls[0]["body"]["canvasCompletion"]["title"] == "角色呼吸动画"
|
||||
assert len(calls) == 1
|
||||
assert "frameIndex" not in result["frames"][0]
|
||||
assert result["resource"]["resourceId"] == "editor-resource-demo"
|
||||
assert result["resource"]["sourceResourceId"] == "editor-resource-preview-demo"
|
||||
assert "frameIndex" not in result["resource"]["imageSequenceFrames"][0]
|
||||
assert calls[1]["path"] == "/api/external/v1/generations/task-operation-demo"
|
||||
assert result["asset"]["assetId"] == "editor-asset-demo"
|
||||
assert result["asset"]["assetKind"] == "character-animation"
|
||||
assert len(result["asset"]["imageSequenceFrames"]) == 2
|
||||
@@ -664,6 +771,7 @@ def _self_test() -> None:
|
||||
assert calls[0]["body"]["referenceImageSrc"] == "editor-resource-spec"
|
||||
assert calls[0]["body"]["screenColor"] == "auto"
|
||||
assert calls[0]["body"]["iconDescriptions"][0] == "蛇头向上"
|
||||
assert calls[1]["path"] == "/api/external/v1/generations/task-operation-demo"
|
||||
print("self-test ok")
|
||||
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
- DDD 分层边界按总纲执行:领域规则沉到 `module-*`,SpacetimeDB 表和事务编排留在 `spacetime-module`,后端访问 SpacetimeDB 统一经 `spacetime-client` facade,HTTP/SSE/BFF 留在 `api-server`,外部副作用留在 `platform-*`,前后端 DTO 留在 `shared-contracts`。
|
||||
- 前端只做表现、交互和临时 UI 状态,不承接正式业务真相,不绕过后端投影或后端 API 直接实现业务规则。
|
||||
- 契约、路由、DTO 去留和 breaking change 以当前后端架构文档、`server-rs/crates/api-server/src/app.rs`、`shared-contracts` 和 `packages/shared` 为准;不得在前端、`api-server` 或临时兼容层中重新发明旧接口。
|
||||
- 凡修改 `/api/external/v1` 的路由、HTTP 方法、请求 / 响应 DTO、请求头、状态码、鉴权或异步语义,必须在同一次变更中同步更新权威契约 [`docs/openapi/genarrative-external-v1.openapi.json`](docs/openapi/genarrative-external-v1.openapi.json) 及对应契约测试;Rust 实现与 OpenAPI 未保持一致时任务不得视为完成。
|
||||
- SpacetimeDB 已有表新增字段时,字段必须放在 Rust 表结构体最后,并设置明确默认值;需要删除、改名、重排或改类型时,必须先询问用户并确认迁移计划。
|
||||
- 修改 SpacetimeDB schema 后必须同步 `migration.rs`、表目录和生成绑定,并运行 `npm run check:spacetime-schema`。
|
||||
- 除 CI/CD 脚本内部受控用法外,人工命令、本地联调、排障步骤和文档示例禁止继续使用 `spacetime --root-dir`。
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
updateAdminAccount,
|
||||
uploadAdminEditorShowcaseCampaignImage,
|
||||
upsertAdminFeatureGateConfig,
|
||||
upsertProfileWalletConfig,
|
||||
} from './adminApiClient';
|
||||
|
||||
afterEach(() => {
|
||||
@@ -71,6 +72,33 @@ test('后台账号创建和更新同时携带 Tab 与独立操作权限', async
|
||||
);
|
||||
});
|
||||
|
||||
test('账号配置一次提交初始和每日免费泥点', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(
|
||||
new Response(JSON.stringify({configId: 'profile_wallet'}), {
|
||||
status: 200,
|
||||
headers: {'content-type': 'application/json'},
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await upsertProfileWalletConfig('owner-token', {
|
||||
initialMudPoints: 100,
|
||||
dailyFreePointsPerDay: 35,
|
||||
});
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/admin/api/profile/wallet-config',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
headers: expect.objectContaining({Authorization: 'Bearer owner-token'}),
|
||||
body: JSON.stringify({
|
||||
initialMudPoints: 100,
|
||||
dailyFreePointsPerDay: 35,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test('灰度配置读写只使用通用 feature-gates 管理接口', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation(() =>
|
||||
Promise.resolve(
|
||||
|
||||
@@ -572,6 +572,7 @@ export interface AdminUpsertProfileRechargeProductRequest {
|
||||
|
||||
export interface AdminUpsertProfileWalletConfigRequest {
|
||||
initialMudPoints: number;
|
||||
dailyFreePointsPerDay: number;
|
||||
}
|
||||
|
||||
export interface ProfileRedeemCodeAdminResponse {
|
||||
@@ -673,6 +674,7 @@ export interface ProfileRechargeProductConfigAdminListResponse {
|
||||
export interface ProfileWalletConfigAdminResponse {
|
||||
configId: string;
|
||||
initialMudPoints: number;
|
||||
dailyFreePointsPerDay: number;
|
||||
createdBy: string;
|
||||
createdByDisplayName: string;
|
||||
createdAt: string;
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/* @vitest-environment jsdom */
|
||||
|
||||
import {fireEvent, render, screen, waitFor} from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {beforeEach, expect, test, vi} from 'vitest';
|
||||
|
||||
import {getProfileWalletConfig, upsertProfileWalletConfig} from '../api/adminApiClient';
|
||||
import type {ProfileWalletConfigAdminResponse} from '../api/adminApiTypes';
|
||||
import {AdminProfileWalletConfigPage} from './AdminProfileWalletConfigPage';
|
||||
|
||||
vi.mock('../api/adminApiClient', () => ({
|
||||
formatAdminApiError: vi.fn((error: unknown) => error instanceof Error ? error.message : '请求失败'),
|
||||
getProfileWalletConfig: vi.fn(),
|
||||
isAdminApiError: vi.fn(() => false),
|
||||
upsertProfileWalletConfig: vi.fn(),
|
||||
}));
|
||||
|
||||
const configResponse: ProfileWalletConfigAdminResponse = {
|
||||
configId: 'profile_wallet', initialMudPoints: 100, dailyFreePointsPerDay: 20,
|
||||
createdBy: 'owner-1', createdByDisplayName: '管理员',
|
||||
createdAt: '2026-07-31T01:00:00Z', updatedBy: 'owner-1',
|
||||
updatedByDisplayName: '管理员', updatedAt: '2026-07-31T01:00:00Z',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getProfileWalletConfig).mockResolvedValue(configResponse);
|
||||
vi.mocked(upsertProfileWalletConfig).mockResolvedValue({...configResponse, initialMudPoints: 120, dailyFreePointsPerDay: 35});
|
||||
});
|
||||
|
||||
test('账号配置页加载并展示每日免费泥点', async () => {
|
||||
render(<AdminProfileWalletConfigPage token="admin-token" result={configResponse} onUnauthorized={vi.fn()} onResultChange={vi.fn()} />);
|
||||
expect((await screen.findByLabelText('每日免费泥点数') as HTMLInputElement).value).toBe('20');
|
||||
expect(getProfileWalletConfig).toHaveBeenCalledWith('admin-token');
|
||||
expect(screen.getByText('每日免费泥点')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('账号配置页一次保存初始和每日免费泥点', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onResultChange = vi.fn();
|
||||
render(<AdminProfileWalletConfigPage token="admin-token" result={configResponse} onUnauthorized={vi.fn()} onResultChange={onResultChange} />);
|
||||
await screen.findByLabelText('每日免费泥点数');
|
||||
fireEvent.change(screen.getByLabelText('账号初始泥点数'), {target: {value: '120'}});
|
||||
fireEvent.change(screen.getByLabelText('每日免费泥点数'), {target: {value: '35'}});
|
||||
await user.click(screen.getByRole('button', {name: '保存'}));
|
||||
expect(screen.getByText('初始 120 泥点,每日免费 35 泥点')).toBeTruthy();
|
||||
await user.click(screen.getByRole('button', {name: '确认'}));
|
||||
await waitFor(() => expect(upsertProfileWalletConfig).toHaveBeenCalledWith('admin-token', {initialMudPoints: 120, dailyFreePointsPerDay: 35}));
|
||||
expect(onResultChange).toHaveBeenLastCalledWith(expect.objectContaining({initialMudPoints: 120, dailyFreePointsPerDay: 35}));
|
||||
});
|
||||
|
||||
test('账号配置页拒绝非正整数每日免费额度', async () => {
|
||||
render(<AdminProfileWalletConfigPage token="admin-token" result={configResponse} onUnauthorized={vi.fn()} onResultChange={vi.fn()} />);
|
||||
const input = await screen.findByLabelText('每日免费泥点数');
|
||||
fireEvent.change(input, {target: {value: '1.5'}});
|
||||
expect((screen.getByRole('button', {name: '保存'}) as HTMLButtonElement).disabled).toBe(true);
|
||||
expect(upsertProfileWalletConfig).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -23,6 +23,7 @@ export function AdminProfileWalletConfigPage({
|
||||
onResultChange,
|
||||
}: AdminProfileWalletConfigPageProps) {
|
||||
const [initialMudPoints, setInitialMudPoints] = useState('100');
|
||||
const [dailyFreePointsPerDay, setDailyFreePointsPerDay] = useState('20');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [loadErrorMessage, setLoadErrorMessage] = useState('');
|
||||
@@ -41,6 +42,7 @@ export function AdminProfileWalletConfigPage({
|
||||
const response = await getProfileWalletConfig(token);
|
||||
onResultChange(response);
|
||||
setInitialMudPoints(String(response.initialMudPoints));
|
||||
setDailyFreePointsPerDay(String(response.dailyFreePointsPerDay));
|
||||
} catch (error: unknown) {
|
||||
handlePageError(error, onUnauthorized, setLoadErrorMessage);
|
||||
} finally {
|
||||
@@ -53,6 +55,13 @@ export function AdminProfileWalletConfigPage({
|
||||
if (isSaving) {
|
||||
return;
|
||||
}
|
||||
const normalizedDailyFreePointsPerDay = parsePositiveInteger(
|
||||
dailyFreePointsPerDay,
|
||||
);
|
||||
if (!normalizedDailyFreePointsPerDay) {
|
||||
setErrorMessage('每日免费泥点数必须是大于 0 的整数');
|
||||
return;
|
||||
}
|
||||
|
||||
const normalizedInitialMudPoints = parsePositiveInteger(initialMudPoints);
|
||||
if (!normalizedInitialMudPoints) {
|
||||
@@ -63,7 +72,7 @@ export function AdminProfileWalletConfigPage({
|
||||
setErrorMessage('');
|
||||
const confirmed = await confirmWrite({
|
||||
action: '保存账号配置',
|
||||
target: `${normalizedInitialMudPoints}泥点`,
|
||||
target: `初始 ${normalizedInitialMudPoints} 泥点,每日免费 ${normalizedDailyFreePointsPerDay} 泥点`,
|
||||
});
|
||||
if (!confirmed) {
|
||||
return;
|
||||
@@ -73,9 +82,11 @@ export function AdminProfileWalletConfigPage({
|
||||
try {
|
||||
const response = await upsertProfileWalletConfig(token, {
|
||||
initialMudPoints: normalizedInitialMudPoints,
|
||||
dailyFreePointsPerDay: normalizedDailyFreePointsPerDay,
|
||||
});
|
||||
onResultChange(response);
|
||||
setInitialMudPoints(String(response.initialMudPoints));
|
||||
setDailyFreePointsPerDay(String(response.dailyFreePointsPerDay));
|
||||
} catch (error: unknown) {
|
||||
handlePageError(error, onUnauthorized, setErrorMessage);
|
||||
} finally {
|
||||
@@ -120,6 +131,17 @@ export function AdminProfileWalletConfigPage({
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="admin-field">
|
||||
<span>每日免费泥点数</span>
|
||||
<input
|
||||
min={1}
|
||||
step={1}
|
||||
type="number"
|
||||
value={dailyFreePointsPerDay}
|
||||
onChange={(event) => setDailyFreePointsPerDay(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
|
||||
{errorMessage ? (
|
||||
<div className="admin-alert" role="status">
|
||||
{errorMessage}
|
||||
@@ -128,7 +150,11 @@ export function AdminProfileWalletConfigPage({
|
||||
|
||||
<button
|
||||
className="admin-primary-button"
|
||||
disabled={isSaving || !parsePositiveInteger(initialMudPoints)}
|
||||
disabled={
|
||||
isSaving ||
|
||||
!parsePositiveInteger(initialMudPoints) ||
|
||||
!parsePositiveInteger(dailyFreePointsPerDay)
|
||||
}
|
||||
type="submit"
|
||||
>
|
||||
<Save size={17} aria-hidden="true" />
|
||||
@@ -147,6 +173,10 @@ export function AdminProfileWalletConfigPage({
|
||||
<dt>初始泥点</dt>
|
||||
<dd>{result.initialMudPoints}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>每日免费泥点</dt>
|
||||
<dd>{result.dailyFreePointsPerDay}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>更新人</dt>
|
||||
<dd>{result.updatedByDisplayName || '-'}</dd>
|
||||
@@ -169,6 +199,6 @@ export function AdminProfileWalletConfigPage({
|
||||
}
|
||||
|
||||
function parsePositiveInteger(value: string) {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : 0;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"autoCompactTokenLimit": 64000,
|
||||
"toolOutputTokenLimit": 12000,
|
||||
"requestTimeoutMs": 180000,
|
||||
"maxRetries": 0,
|
||||
"maxRetries": 2,
|
||||
"retryBackoffMs": 500
|
||||
},
|
||||
"agentLlm": {},
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "npm --prefix ../.. exec tauri -- dev",
|
||||
"game-chat": "npm --prefix ../.. exec tauri -- dev -- -- --game-chat",
|
||||
"dev": "node scripts/start-tauri-dev.mjs",
|
||||
"game-chat": "node scripts/start-tauri-dev.mjs --game-chat",
|
||||
"dev-server": "node scripts/start-dev-server.mjs",
|
||||
"dev-stack": "node scripts/start-dev-stack.mjs",
|
||||
"build": "npm --prefix ../.. exec tauri -- build",
|
||||
"build:game-chat-release": "npm --prefix ../.. exec tauri -- build --config src-tauri/tauri.game-chat-release.conf.json --bundles nsis --features game-chat-release",
|
||||
"llm-status": "node scripts/run-cli-with-config.mjs --llm-status",
|
||||
"agent-task": "node scripts/run-cli-with-config.mjs --agent-task",
|
||||
"chat": "node scripts/run-cli-with-config.mjs --swarm-chat",
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const appRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const repoRoot = resolve(appRoot, '../..');
|
||||
const npmCli =
|
||||
process.env.npm_execpath ??
|
||||
resolve(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js');
|
||||
|
||||
function run(args, extraEnv = {}) {
|
||||
const result = spawnSync(process.execPath, [npmCli, ...args], {
|
||||
cwd: appRoot,
|
||||
env: { ...process.env, ...extraEnv },
|
||||
stdio: 'inherit',
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
if (result.status !== 0) {
|
||||
process.exit(result.status ?? 1);
|
||||
}
|
||||
}
|
||||
|
||||
run(['--prefix', repoRoot, 'run', 'ai-game-creator-shell:typecheck']);
|
||||
run(
|
||||
[
|
||||
'--prefix',
|
||||
repoRoot,
|
||||
'exec',
|
||||
'vite',
|
||||
'--',
|
||||
'build',
|
||||
'--config',
|
||||
'vite.config.ts',
|
||||
],
|
||||
{ VITE_AGC_GAME_CHAT_ONLY: 'true' },
|
||||
);
|
||||
@@ -27,6 +27,20 @@ const tauriConfig = JSON.parse(
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const gameChatReleaseTauriConfig = JSON.parse(
|
||||
fs.readFileSync(
|
||||
new URL('../src-tauri/tauri.game-chat-release.conf.json', import.meta.url),
|
||||
'utf8',
|
||||
),
|
||||
);
|
||||
const cargoManifestSource = fs.readFileSync(
|
||||
new URL('../src-tauri/Cargo.toml', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const cargoPackageVersion = cargoManifestSource
|
||||
.split(/\r?\n(?=\[)/u)
|
||||
.find((section) => section.startsWith('[package]'))
|
||||
?.match(/^version\s*=\s*"([^"]+)"\s*$/mu)?.[1];
|
||||
const eventCapabilityPath = new URL(
|
||||
'../src-tauri/capabilities/events.json',
|
||||
import.meta.url,
|
||||
@@ -57,6 +71,14 @@ const appEntrypointSource = fs.readFileSync(
|
||||
new URL('../src/main.tsx', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const appModuleSource = fs.readFileSync(
|
||||
new URL('../src/App.tsx', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const gameChatReleaseBuildSource = fs.readFileSync(
|
||||
new URL('../scripts/build-game-chat-release.mjs', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
const tauriHandlerSource = fs.readFileSync(
|
||||
new URL('../src-tauri/src/main.rs', import.meta.url),
|
||||
'utf8',
|
||||
@@ -414,6 +436,25 @@ async function runConfigWizardRegressionChecks() {
|
||||
path.join(os.tmpdir(), 'genarrative-agc-config-check-'),
|
||||
);
|
||||
try {
|
||||
const canonicalTestRoot = fs.realpathSync.native(testRoot);
|
||||
const realConfigAncestor = path.join(testRoot, 'real-config-ancestor');
|
||||
const linkedConfigAncestor = path.join(testRoot, 'linked-config-ancestor');
|
||||
fs.mkdirSync(realConfigAncestor);
|
||||
fs.symlinkSync(
|
||||
realConfigAncestor,
|
||||
linkedConfigAncestor,
|
||||
process.platform === 'win32' ? 'junction' : 'dir',
|
||||
);
|
||||
const missingLinkedConfigDir = path.join(
|
||||
linkedConfigAncestor,
|
||||
'missing-appdata',
|
||||
);
|
||||
assert.equal(fs.existsSync(missingLinkedConfigDir), false);
|
||||
assert.equal(
|
||||
await assertSafeGameCreatorConfigDestination(missingLinkedConfigDir),
|
||||
path.join(fs.realpathSync.native(realConfigAncestor), 'missing-appdata'),
|
||||
);
|
||||
|
||||
const gitRoot = path.join(testRoot, 'tracked-repository');
|
||||
const trackedConfigDir = path.join(gitRoot, 'runtime-config');
|
||||
fs.mkdirSync(trackedConfigDir, { recursive: true });
|
||||
@@ -441,7 +482,7 @@ async function runConfigWizardRegressionChecks() {
|
||||
const outsideConfigDir = path.join(testRoot, 'outside-appdata');
|
||||
assert.equal(
|
||||
await assertSafeGameCreatorConfigDestination(outsideConfigDir),
|
||||
outsideConfigDir,
|
||||
path.join(canonicalTestRoot, 'outside-appdata'),
|
||||
);
|
||||
await assert.rejects(
|
||||
assertSafeGameCreatorConfigDestination(outsideConfigDir, {
|
||||
@@ -454,7 +495,7 @@ async function runConfigWizardRegressionChecks() {
|
||||
await assertSafeGameCreatorConfigDestination(dedicatedConfigDir, {
|
||||
requireDedicatedLeaf: true,
|
||||
}),
|
||||
dedicatedConfigDir,
|
||||
path.join(canonicalTestRoot, appIdentifier),
|
||||
);
|
||||
|
||||
const injectedNonGitConfigDir = path.join(testRoot, 'injected-non-git');
|
||||
@@ -467,7 +508,7 @@ async function runConfigWizardRegressionChecks() {
|
||||
'fatal: not a git repository (or any of the parent directories): .git\n',
|
||||
}),
|
||||
}),
|
||||
injectedNonGitConfigDir,
|
||||
path.join(canonicalTestRoot, 'injected-non-git'),
|
||||
);
|
||||
await assert.rejects(
|
||||
assertSafeGameCreatorConfigDestination(
|
||||
@@ -916,6 +957,29 @@ if (
|
||||
);
|
||||
}
|
||||
|
||||
const gameChatReleaseAppIndex = appModuleSource.indexOf(
|
||||
'export function GameChatReleaseApp(',
|
||||
);
|
||||
const gameChatReleaseBranchIndex = appEntrypointSource.indexOf(
|
||||
'{gameChatReleaseMode ? (',
|
||||
);
|
||||
const authenticatedClientIndex = appEntrypointSource.indexOf(
|
||||
'<AuthenticatedClient>',
|
||||
gameChatReleaseBranchIndex,
|
||||
);
|
||||
if (
|
||||
gameChatReleaseAppIndex === -1 ||
|
||||
gameChatReleaseBranchIndex === -1 ||
|
||||
!appEntrypointSource
|
||||
.slice(gameChatReleaseBranchIndex, authenticatedClientIndex)
|
||||
.includes('gameChatApp') ||
|
||||
authenticatedClientIndex < gameChatReleaseBranchIndex
|
||||
) {
|
||||
throw new Error(
|
||||
'AI game creator game-chat release must render the local chat App before the platform authentication boundary',
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
packageConfig.scripts?.['agent-run'] !==
|
||||
'node scripts/run-cli-with-config.mjs --agent-run'
|
||||
@@ -1193,6 +1257,21 @@ if (
|
||||
);
|
||||
}
|
||||
|
||||
if (packageConfig.scripts?.dev !== 'node scripts/start-tauri-dev.mjs') {
|
||||
throw new Error(
|
||||
'AI game creator shell dev must run through the managed Tauri dev launcher',
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
packageConfig.scripts?.['game-chat'] !==
|
||||
'node scripts/start-tauri-dev.mjs --game-chat'
|
||||
) {
|
||||
throw new Error(
|
||||
'AI game creator shell game-chat must run through the managed Tauri dev launcher',
|
||||
);
|
||||
}
|
||||
|
||||
const gameChatInitialUrlApply =
|
||||
'apply_game_chat_initial_window_url(tauri_context.config_mut(), options)';
|
||||
const gameChatInitialUrlApplyIndexes = Array.from(
|
||||
@@ -1271,8 +1350,6 @@ for (const requiredSnippet of [
|
||||
'fn apply_game_chat_initial_window_url(',
|
||||
'.find(|window| window.label == "client")',
|
||||
'client.url = game_chat_window_url(',
|
||||
'.build(tauri_context)',
|
||||
'app.run(|_, event| handle_game_creator_gui_run_event(&event))',
|
||||
]) {
|
||||
if (
|
||||
!`${tauriHandlerSource}\n${tauriWindowSource}`.includes(requiredSnippet)
|
||||
@@ -1283,6 +1360,15 @@ for (const requiredSnippet of [
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!tauriHandlerSource.includes('.build(tauri_context)') ||
|
||||
!tauriHandlerSource.includes('handle_game_creator_gui_run_event(&event)')
|
||||
) {
|
||||
throw new Error(
|
||||
'AI game creator Tauri runtime must build from the prepared Context and preserve the generic GUI exit hook',
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
!tauriConfig.build?.beforeBuildCommand?.includes('--config vite.config.ts')
|
||||
) {
|
||||
@@ -1291,6 +1377,66 @@ if (
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
!appEntrypointSource.includes(
|
||||
"import.meta.env.VITE_AGC_GAME_CHAT_ONLY === 'true'",
|
||||
) ||
|
||||
!appEntrypointSource.includes(
|
||||
"import.meta.env.DEV && initialSearchParams.has('game-chat')",
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'AI game creator game-chat release must be compile-time fixed while preserving the dev query entry',
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
packageConfig.scripts?.['build:game-chat-release'] !==
|
||||
'npm --prefix ../.. exec tauri -- build --config src-tauri/tauri.game-chat-release.conf.json --bundles nsis --features game-chat-release' ||
|
||||
rootPackageConfig.scripts?.['agc:build:game-chat-release'] !==
|
||||
'npm --prefix apps/ai-game-creator-shell run build:game-chat-release --'
|
||||
) {
|
||||
throw new Error(
|
||||
'AI game creator game-chat release build commands must stay wired through the dedicated Tauri config',
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
gameChatReleaseTauriConfig.productName !== 'Genarrative Game Chat' ||
|
||||
gameChatReleaseTauriConfig.version !== '0.1.1' ||
|
||||
gameChatReleaseTauriConfig.identifier === tauriConfig.identifier ||
|
||||
gameChatReleaseTauriConfig.build?.beforeBuildCommand !==
|
||||
'node scripts/build-game-chat-release.mjs' ||
|
||||
!gameChatReleaseTauriConfig.bundle?.targets?.includes('nsis')
|
||||
) {
|
||||
throw new Error(
|
||||
'AI game creator game-chat release must keep version 0.1.1, its independent identity, frontend build, and NSIS target',
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
tauriConfig.version !== '0.1.0' ||
|
||||
packageConfig.version !== '0.1.0' ||
|
||||
cargoPackageVersion !== '0.1.0'
|
||||
) {
|
||||
throw new Error(
|
||||
'AI game creator standard release must remain version 0.1.0 while game-chat uses its dedicated version',
|
||||
);
|
||||
}
|
||||
|
||||
for (const requiredSnippet of [
|
||||
"'ai-game-creator-shell:typecheck'",
|
||||
"VITE_AGC_GAME_CHAT_ONLY: 'true'",
|
||||
"'--config'",
|
||||
"'vite.config.ts'",
|
||||
]) {
|
||||
if (!gameChatReleaseBuildSource.includes(requiredSnippet)) {
|
||||
throw new Error(
|
||||
`AI game creator game-chat release build guardrail drifted: ${requiredSnippet}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const devServerSource = fs.readFileSync(
|
||||
new URL('../scripts/start-dev-server.mjs', import.meta.url),
|
||||
'utf8',
|
||||
@@ -1339,8 +1485,15 @@ for (const snippet of [
|
||||
'assertSafeGameCreatorConfigDestination',
|
||||
'readGameCreatorWizardConfigState',
|
||||
'$security.SetAccessRuleProtection($true, $false)',
|
||||
'$targetItem = Get-Item -LiteralPath $target -Force',
|
||||
'$targetItem.SetAccessControl($security)',
|
||||
'$verified = $targetItem.GetAccessControl()',
|
||||
'$rules.Count -ne 1',
|
||||
'[System.Security.AccessControl.FileSystemRights]::FullControl',
|
||||
"runChildCapture('powershell.exe'",
|
||||
"'-NoProfile'",
|
||||
"'-Command'",
|
||||
'windowsPrivateAclScript',
|
||||
'await secureWindowsPath(temporaryPath, { isDirectory: false })',
|
||||
'await temporaryFile.writeFile',
|
||||
]) {
|
||||
@@ -1350,6 +1503,11 @@ for (const snippet of [
|
||||
);
|
||||
}
|
||||
}
|
||||
if (/\bGet-Acl\b/u.test(configWizardSource)) {
|
||||
throw new Error(
|
||||
'AI game creator config wizard must not rely on Get-Acl module auto-loading',
|
||||
);
|
||||
}
|
||||
|
||||
await runConfigWizardRegressionChecks();
|
||||
await runHiddenInputRegressionChecks();
|
||||
@@ -1380,7 +1538,6 @@ for (const snippet of [
|
||||
'fn merge_game_creator_config_file(',
|
||||
'.join("apps")',
|
||||
'.join("ai-game-creator-shell")',
|
||||
'configure_game_creator_runtime_config_dir(app.handle())?',
|
||||
'read_game_creator_app_config,',
|
||||
'write_game_creator_app_config,',
|
||||
'resolve_game_creator_llm_config_for_agent(app_config, "planner")',
|
||||
@@ -1400,6 +1557,31 @@ for (const snippet of [
|
||||
}
|
||||
}
|
||||
|
||||
const runtimeConfigSetupStart = tauriHandlerSource.indexOf(
|
||||
'configure_game_creator_runtime_config_dir(app.handle()).inspect_err(|error| {',
|
||||
);
|
||||
const runtimeConfigSetupEnd = tauriHandlerSource.indexOf(
|
||||
'})?;',
|
||||
runtimeConfigSetupStart,
|
||||
);
|
||||
const runtimeConfigSetupSource = tauriHandlerSource.slice(
|
||||
runtimeConfigSetupStart,
|
||||
runtimeConfigSetupEnd,
|
||||
);
|
||||
if (
|
||||
runtimeConfigSetupStart === -1 ||
|
||||
runtimeConfigSetupEnd === -1 ||
|
||||
!runtimeConfigSetupSource.includes('sanitize_diagnostic_message(') ||
|
||||
!runtimeConfigSetupSource.includes('append_bounded_diagnostic_line(') ||
|
||||
!runtimeConfigSetupSource.includes(
|
||||
'startup.appdata.configure.failed details={details}',
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
'AI game creator setup must configure the runtime AppData directory and log sanitized setup failures',
|
||||
);
|
||||
}
|
||||
|
||||
for (const snippet of [
|
||||
'import.meta.env.DEV',
|
||||
'#[cfg(all(debug_assertions, not(test)))]',
|
||||
|
||||
@@ -120,7 +120,7 @@ export function deterministicLaneDefenseInitialHtml() {
|
||||
*{box-sizing:border-box}body{margin:0;min-height:100vh;background:#f4f8ee;color:#18351f;font:16px system-ui,sans-serif}main{width:min(960px,100%);margin:auto;padding:18px}h1{margin:0 0 4px;font-size:clamp(28px,7vw,46px)}p{margin:4px 0 14px}.toolbar,.plants{display:flex;flex-wrap:wrap;gap:8px;margin:10px 0}button{min-height:44px;border:1px solid #315d35;background:#fff;color:#18351f;padding:9px 14px;font:inherit;font-weight:700;cursor:pointer}button:hover{background:#e6f3dc}.board{display:grid;gap:10px;background:#d9edc8;border:2px solid #315d35;padding:10px}.lane{display:grid;grid-template-columns:repeat(5,1fr);gap:6px}.cell{min-height:54px;background:#eef8e7}.status{font-weight:700;min-height:24px}#game{display:none;width:100%;height:auto;aspect-ratio:20/9;background:#18351f;border:2px solid #315d35}@media(max-width:520px){main{padding:12px}button{flex:1 1 44%}.cell{min-height:44px}}
|
||||
</style>
|
||||
</head>
|
||||
<body><main>
|
||||
<body><main><img src="assets/art-spritesheet.png" alt="Garden defenders" width="96" height="96">
|
||||
<h1>灵露花园</h1><p>GENARRATIVE_REAL_E2E_VISIBLE</p><p>Goal: defend the garden and win every wave.</p>
|
||||
<div class="toolbar"><button data-playtest-id="start">Start Game</button><button data-playtest-id="speed-up">Speed Up</button><button data-playtest-id="next-level">Next Level</button><button data-playtest-id="restart">Restart</button></div>
|
||||
<div class="plants"><button data-playtest-id="defender-option">露华花</button><button id="thorn">棘刺芽</button></div>
|
||||
@@ -2370,6 +2370,7 @@ function createDeterministicCanvasFixture(apiKey) {
|
||||
const projectId = 'deterministic-canvas-project';
|
||||
const folderId = 'deterministic-canvas-folder';
|
||||
const images = new Map();
|
||||
const generationOperations = new Map();
|
||||
const imageCache = new Map();
|
||||
const stats = {
|
||||
canvasApiRequestCount: 0,
|
||||
@@ -2476,6 +2477,16 @@ function createDeterministicCanvasFixture(apiKey) {
|
||||
request.method === 'POST' &&
|
||||
parsed.pathname === '/api/external/v1/editor/images/generations'
|
||||
) {
|
||||
const idempotencyKey = request.headers['idempotency-key'];
|
||||
if (
|
||||
typeof idempotencyKey !== 'string' ||
|
||||
!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
|
||||
idempotencyKey,
|
||||
)
|
||||
) {
|
||||
request.resume();
|
||||
return json(400, { error: { message: 'invalid idempotency key' } });
|
||||
}
|
||||
const body = await readJsonBody(request);
|
||||
const image = imageForAspectRatio(body?.aspectRatio);
|
||||
generationSequence += 1;
|
||||
@@ -2489,8 +2500,22 @@ function createDeterministicCanvasFixture(apiKey) {
|
||||
const assetKind =
|
||||
typeof body?.assetKind === 'string' ? body.assetKind : 'game-art';
|
||||
images.set(imageId, { ...image, objectKey });
|
||||
return json(200, {
|
||||
data: {
|
||||
const operationId = `task-${imageId}`;
|
||||
generationOperations.set(operationId, {
|
||||
imageSrc: `/${objectKey}`,
|
||||
objectKey,
|
||||
assetObjectId,
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
sourceType: 'generated',
|
||||
prompt: body?.prompt ?? 'deterministic canvas fixture',
|
||||
actualPrompt: body?.prompt ?? 'deterministic canvas fixture',
|
||||
model: 'deterministic-canvas-v1',
|
||||
provider: 'deterministic-loopback',
|
||||
taskId: `task-${imageId}`,
|
||||
resource: {
|
||||
resourceId,
|
||||
projectId,
|
||||
imageSrc: `/${objectKey}`,
|
||||
objectKey,
|
||||
assetObjectId,
|
||||
@@ -2502,22 +2527,45 @@ function createDeterministicCanvasFixture(apiKey) {
|
||||
model: 'deterministic-canvas-v1',
|
||||
provider: 'deterministic-loopback',
|
||||
taskId: `task-${imageId}`,
|
||||
resource: {
|
||||
resourceId,
|
||||
projectId,
|
||||
imageSrc: `/${objectKey}`,
|
||||
objectKey,
|
||||
assetObjectId,
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
sourceType: 'generated',
|
||||
assetKind,
|
||||
},
|
||||
asset: {
|
||||
assetId: `asset-${imageId}`,
|
||||
assetObjectId,
|
||||
assetKind,
|
||||
},
|
||||
assetKind,
|
||||
},
|
||||
asset: {
|
||||
assetId: `asset-${imageId}`,
|
||||
assetObjectId,
|
||||
assetKind,
|
||||
},
|
||||
});
|
||||
return json(202, {
|
||||
data: {
|
||||
operationId,
|
||||
kind: 'editor_image_generation',
|
||||
status: 'queued',
|
||||
statusUrl: `/api/external/v1/generations/${operationId}`,
|
||||
pollAfterMs: 1,
|
||||
updatedAtMicros: generationSequence,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (
|
||||
request.method === 'GET' &&
|
||||
parsed.pathname.startsWith('/api/external/v1/generations/')
|
||||
) {
|
||||
request.resume();
|
||||
const operationId = parsed.pathname.slice(
|
||||
'/api/external/v1/generations/'.length,
|
||||
);
|
||||
const result = generationOperations.get(operationId);
|
||||
if (!result) return json(404, { error: { message: 'operation not found' } });
|
||||
return json(200, {
|
||||
data: {
|
||||
operationId,
|
||||
kind: 'editor_image_generation',
|
||||
status: 'completed',
|
||||
phaseLabel: '图片画布生成图片',
|
||||
phaseDetail: '生成已完成。',
|
||||
progress: 100,
|
||||
result,
|
||||
updatedAtMicros: generationSequence,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -51,9 +51,10 @@ $rule = [System.Security.AccessControl.FileSystemAccessRule]::new(
|
||||
[System.Security.AccessControl.AccessControlType]::Allow
|
||||
)
|
||||
$security.AddAccessRule($rule) | Out-Null
|
||||
(Get-Item -LiteralPath $target -Force).SetAccessControl($security)
|
||||
$targetItem = Get-Item -LiteralPath $target -Force
|
||||
$targetItem.SetAccessControl($security)
|
||||
|
||||
$verified = Get-Acl -LiteralPath $target
|
||||
$verified = $targetItem.GetAccessControl()
|
||||
$owner = $verified.GetOwner([System.Security.Principal.SecurityIdentifier])
|
||||
$rules = @($verified.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]))
|
||||
if (-not $owner.Equals($currentSid) -or -not $verified.AreAccessRulesProtected -or $rules.Count -ne 1) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import net from 'node:net';
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
@@ -134,6 +135,21 @@ async function readExistingViteServer() {
|
||||
return httpGetText(viteUrl);
|
||||
}
|
||||
|
||||
function isVitePortListening() {
|
||||
return new Promise((resolveRequest) => {
|
||||
const socket = net.connect({ host: viteHost, port: vitePort });
|
||||
socket.once('connect', () => {
|
||||
socket.destroy();
|
||||
resolveRequest(true);
|
||||
});
|
||||
socket.once('error', () => resolveRequest(false));
|
||||
socket.setTimeout(1000, () => {
|
||||
socket.destroy();
|
||||
resolveRequest(true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function isAiGameCreatorServer(response) {
|
||||
return (
|
||||
response &&
|
||||
@@ -144,17 +160,6 @@ function isAiGameCreatorServer(response) {
|
||||
);
|
||||
}
|
||||
|
||||
async function isExistingViteProxyReady() {
|
||||
const response = await httpGetText(`${viteUrl}api/auth/me`, 2000);
|
||||
return Boolean(
|
||||
response &&
|
||||
response.statusCode >= 200 &&
|
||||
response.statusCode < 500 &&
|
||||
!response.body.includes('<title>AI 游戏创作</title>') &&
|
||||
!response.body.includes('/src/main.tsx'),
|
||||
);
|
||||
}
|
||||
|
||||
async function readExistingViteMarker() {
|
||||
const response = await httpGetText(viteMarkerUrl, 2000);
|
||||
if (!response || response.statusCode !== 200) {
|
||||
@@ -167,24 +172,49 @@ async function readExistingViteMarker() {
|
||||
}
|
||||
}
|
||||
|
||||
async function isExistingVitePairedWithBackend(apiTarget) {
|
||||
const marker = await readExistingViteMarker();
|
||||
return Boolean(
|
||||
marker &&
|
||||
marker.schemaVersion === 1 &&
|
||||
marker.app === 'ai-game-creator-shell' &&
|
||||
marker.apiTarget === apiTarget,
|
||||
async function preflightExistingVite({
|
||||
readServer = readExistingViteServer,
|
||||
portListening = isVitePortListening,
|
||||
readMarker = readExistingViteMarker,
|
||||
} = {}) {
|
||||
const existing = await readServer();
|
||||
if (!existing) {
|
||||
if (await portListening()) {
|
||||
throw new Error(
|
||||
`${viteUrl} is already in use by a non-HTTP or unrecognized server. Stop it before starting Tauri dev.`,
|
||||
);
|
||||
}
|
||||
return { status: 'available', apiTarget: '' };
|
||||
}
|
||||
|
||||
if (!isAiGameCreatorServer(existing)) {
|
||||
throw new Error(
|
||||
`${viteUrl} is already in use by another server. Stop it before starting Tauri dev.`,
|
||||
);
|
||||
}
|
||||
|
||||
const marker = await readMarker();
|
||||
const markerApiTarget =
|
||||
marker?.schemaVersion === 1 &&
|
||||
marker?.app === 'ai-game-creator-shell' &&
|
||||
typeof marker?.apiTarget === 'string'
|
||||
? marker.apiTarget
|
||||
: '';
|
||||
const actualTarget = markerApiTarget || 'unknown';
|
||||
throw new Error(
|
||||
`${viteUrl} is already running with API target ${actualTarget}. Its owning worktree cannot be proven, so it will not be reused. Stop that Vite dev server before starting Tauri dev.`,
|
||||
);
|
||||
}
|
||||
|
||||
function spawnChild(command, args, options, spawnImpl = spawn) {
|
||||
const useShell = process.platform === 'win32';
|
||||
const isPosix = process.platform !== 'win32';
|
||||
const useShell = options.shell ?? !isPosix;
|
||||
const child = spawnImpl(command, args, {
|
||||
...options,
|
||||
shell: useShell,
|
||||
// POSIX 下让每个长驻服务拥有独立进程组,退出时可以连同 npm、
|
||||
// Node、Cargo 及其子进程一起清理,避免残留订阅任务持续刷日志。
|
||||
detached: !useShell,
|
||||
detached: isPosix,
|
||||
stdio: 'inherit',
|
||||
});
|
||||
const lifecycle = {
|
||||
@@ -192,7 +222,7 @@ function spawnChild(command, args, options, spawnImpl = spawn) {
|
||||
promise: null,
|
||||
// detached 子进程在 POSIX 下以自身 PID 作为 PGID。leader 退出后
|
||||
// child.pid 仍是清理其后代的唯一稳定句柄,必须随生命周期保留。
|
||||
processGroupId: !useShell && Number.isInteger(child.pid) ? child.pid : null,
|
||||
processGroupId: isPosix && Number.isInteger(child.pid) ? child.pid : null,
|
||||
};
|
||||
lifecycle.promise = new Promise((resolveLifecycle) => {
|
||||
child.once('error', (error) => {
|
||||
@@ -270,6 +300,195 @@ function stopChild(child, signal = 'SIGTERM') {
|
||||
}
|
||||
}
|
||||
|
||||
function readLinuxProcessGroupAlive(
|
||||
processGroupId,
|
||||
{ readdirImpl = readdirSync, readFileImpl = readFileSync } = {},
|
||||
) {
|
||||
let processIds;
|
||||
try {
|
||||
processIds = readdirImpl('/proc');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const processId of processIds) {
|
||||
if (!/^\d+$/.test(processId)) {
|
||||
continue;
|
||||
}
|
||||
let stat;
|
||||
try {
|
||||
stat = readFileImpl(`/proc/${processId}/stat`, 'utf8');
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
const commandEnd = stat.lastIndexOf(') ');
|
||||
if (commandEnd < 0) {
|
||||
continue;
|
||||
}
|
||||
const [state, , processGroup] = stat
|
||||
.slice(commandEnd + 2)
|
||||
.trim()
|
||||
.split(/\s+/);
|
||||
if (
|
||||
Number(processGroup) === processGroupId &&
|
||||
state !== 'Z' &&
|
||||
state !== 'X'
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isProcessGroupAlive(
|
||||
processGroupId,
|
||||
{
|
||||
platform = process.platform,
|
||||
killImpl = process.kill,
|
||||
readLinuxGroupAlive = readLinuxProcessGroupAlive,
|
||||
} = {},
|
||||
) {
|
||||
if (!Number.isInteger(processGroupId)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
killImpl(-processGroupId, 0);
|
||||
} catch (error) {
|
||||
return error?.code !== 'ESRCH';
|
||||
}
|
||||
if (platform === 'linux') {
|
||||
const linuxGroupAlive = readLinuxGroupAlive(processGroupId);
|
||||
if (typeof linuxGroupAlive === 'boolean') {
|
||||
return linuxGroupAlive;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async function waitUntil(check, timeoutMs, pollIntervalMs = 25) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
if (await check()) {
|
||||
return true;
|
||||
}
|
||||
await new Promise((resolveWait) => setTimeout(resolveWait, pollIntervalMs));
|
||||
}
|
||||
return check();
|
||||
}
|
||||
|
||||
function runWindowsTaskkill(
|
||||
processId,
|
||||
{ spawnImpl = spawn, timeoutMs = 5000 } = {},
|
||||
) {
|
||||
return new Promise((resolveRequest) => {
|
||||
const taskkill = spawnImpl(
|
||||
'taskkill.exe',
|
||||
['/PID', String(processId), '/T', '/F'],
|
||||
{
|
||||
shell: false,
|
||||
stdio: 'ignore',
|
||||
windowsHide: true,
|
||||
},
|
||||
);
|
||||
let settled = false;
|
||||
const timeout = setTimeout(() => {
|
||||
try {
|
||||
taskkill.kill('SIGKILL');
|
||||
} catch {
|
||||
// ignore taskkill timeout races
|
||||
}
|
||||
finish({ timedOut: true, code: null, error: null });
|
||||
}, timeoutMs);
|
||||
const finish = (result) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
clearTimeout(timeout);
|
||||
resolveRequest(result);
|
||||
};
|
||||
taskkill.once('error', (error) =>
|
||||
finish({ timedOut: false, code: null, error }),
|
||||
);
|
||||
taskkill.once('exit', (code) =>
|
||||
finish({ timedOut: false, code: code ?? 0, error: null }),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function terminateChildTree(
|
||||
child,
|
||||
{
|
||||
platform = process.platform,
|
||||
gracefulTimeoutMs = 2500,
|
||||
forceTimeoutMs = 2000,
|
||||
killImpl = process.kill,
|
||||
taskkillImpl = runWindowsTaskkill,
|
||||
} = {},
|
||||
) {
|
||||
if (!child) {
|
||||
return { stopped: true, forced: false };
|
||||
}
|
||||
|
||||
if (platform === 'win32') {
|
||||
if (!Number.isInteger(child.pid)) {
|
||||
stopChild(child, 'SIGTERM');
|
||||
return { stopped: true, forced: false };
|
||||
}
|
||||
const result = await taskkillImpl(child.pid);
|
||||
return {
|
||||
stopped:
|
||||
!result?.timedOut &&
|
||||
!result?.error &&
|
||||
[0, 128].includes(result?.code ?? 0),
|
||||
forced: true,
|
||||
result,
|
||||
};
|
||||
}
|
||||
|
||||
const processGroupId = childLifecycles.get(child)?.processGroupId;
|
||||
if (!Number.isInteger(processGroupId)) {
|
||||
stopChild(child, 'SIGTERM');
|
||||
const lifecycle = childLifecycles.get(child);
|
||||
if (lifecycle) {
|
||||
await Promise.race([
|
||||
lifecycle.promise,
|
||||
new Promise((resolveWait) =>
|
||||
setTimeout(resolveWait, gracefulTimeoutMs),
|
||||
),
|
||||
]);
|
||||
}
|
||||
if (child.exitCode == null && child.signalCode == null) {
|
||||
stopChild(child, 'SIGKILL');
|
||||
return { stopped: false, forced: true };
|
||||
}
|
||||
return { stopped: true, forced: false };
|
||||
}
|
||||
|
||||
stopChild(child, 'SIGTERM');
|
||||
if (
|
||||
await waitUntil(
|
||||
() => !isProcessGroupAlive(processGroupId, { platform, killImpl }),
|
||||
gracefulTimeoutMs,
|
||||
)
|
||||
) {
|
||||
return { stopped: true, forced: false };
|
||||
}
|
||||
|
||||
try {
|
||||
killImpl(-processGroupId, 'SIGKILL');
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ESRCH') {
|
||||
return { stopped: false, forced: true, error };
|
||||
}
|
||||
}
|
||||
const stopped = await waitUntil(
|
||||
() => !isProcessGroupAlive(processGroupId, { platform, killImpl }),
|
||||
forceTimeoutMs,
|
||||
);
|
||||
return { stopped, forced: true };
|
||||
}
|
||||
|
||||
async function waitForBackendReady(backendChild, timeoutMs = 600_000) {
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
@@ -340,19 +559,9 @@ async function startVite(apiTarget) {
|
||||
|
||||
const existing = await readExistingViteServer();
|
||||
if (existing) {
|
||||
if (
|
||||
isAiGameCreatorServer(existing) &&
|
||||
(await isExistingVitePairedWithBackend(apiTarget)) &&
|
||||
(await isExistingViteProxyReady())
|
||||
) {
|
||||
console.log(
|
||||
`[ai-game-creator-shell] reuse existing Vite dev server ${viteUrl}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
if (isAiGameCreatorServer(existing)) {
|
||||
throw new Error(
|
||||
`${viteUrl} is already running, but its /api proxy is not connected to the paired backend. Stop it before starting Tauri dev.`,
|
||||
`${viteUrl} is already running and cannot be safely reused. Stop it before starting Tauri dev.`,
|
||||
);
|
||||
}
|
||||
throw new Error(
|
||||
@@ -384,6 +593,7 @@ async function main() {
|
||||
}
|
||||
|
||||
try {
|
||||
await preflightExistingVite();
|
||||
const backend = await ensureBackend({
|
||||
onBackendChild(child) {
|
||||
backendChild = child;
|
||||
@@ -422,6 +632,10 @@ async function main() {
|
||||
);
|
||||
return 1;
|
||||
} finally {
|
||||
await Promise.all([
|
||||
terminateChildTree(viteChild),
|
||||
terminateChildTree(backendChild),
|
||||
]);
|
||||
for (const [signal, handler] of signalHandlers) {
|
||||
process.off(signal, handler);
|
||||
}
|
||||
@@ -439,10 +653,15 @@ export {
|
||||
ensureBackend,
|
||||
formatChildFailure,
|
||||
isDirectModuleExecution,
|
||||
isProcessGroupAlive,
|
||||
preflightExistingVite,
|
||||
readChildFailure,
|
||||
readLinuxProcessGroupAlive,
|
||||
resolveBackendTargetsFromState,
|
||||
runWindowsTaskkill,
|
||||
spawnChild,
|
||||
stopChild,
|
||||
terminateChildTree,
|
||||
waitForBackendReady,
|
||||
waitForChildTermination,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import {
|
||||
preflightExistingVite,
|
||||
spawnChild,
|
||||
stopChild,
|
||||
terminateChildTree,
|
||||
waitForChildTermination,
|
||||
} from './start-dev-stack.mjs';
|
||||
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = resolve(appRoot, '../..');
|
||||
const tauriCliPath = resolve(repoRoot, 'node_modules/@tauri-apps/cli/tauri.js');
|
||||
|
||||
function parseLauncherArguments(argv) {
|
||||
const args = [...argv];
|
||||
const gameChat = args[0] === '--game-chat';
|
||||
if (gameChat) {
|
||||
args.shift();
|
||||
}
|
||||
return { gameChat, args };
|
||||
}
|
||||
|
||||
function buildTauriArguments(argv) {
|
||||
const { gameChat, args } = parseLauncherArguments(argv);
|
||||
if (gameChat) {
|
||||
return ['dev', '--', '--', '--game-chat', ...args];
|
||||
}
|
||||
return ['dev', ...args];
|
||||
}
|
||||
|
||||
function spawnTauriCli(argv) {
|
||||
return spawnChild(process.execPath, [tauriCliPath, ...argv], {
|
||||
cwd: appRoot,
|
||||
shell: false,
|
||||
});
|
||||
}
|
||||
|
||||
async function runTauriDev(
|
||||
argv = process.argv.slice(2),
|
||||
{
|
||||
preflight = preflightExistingVite,
|
||||
spawnCli = spawnTauriCli,
|
||||
waitForCli = waitForChildTermination,
|
||||
terminateTree = terminateChildTree,
|
||||
} = {},
|
||||
) {
|
||||
await preflight();
|
||||
|
||||
const tauriArguments = buildTauriArguments(argv);
|
||||
const child = spawnCli(tauriArguments);
|
||||
let resolveShutdown;
|
||||
let shutdownSignal = '';
|
||||
let repeatedSignal = false;
|
||||
const shutdownRequested = new Promise((resolveRequest) => {
|
||||
resolveShutdown = resolveRequest;
|
||||
});
|
||||
const signalHandlers = new Map();
|
||||
|
||||
for (const signal of ['SIGINT', 'SIGTERM']) {
|
||||
const handler = () => {
|
||||
if (!shutdownSignal) {
|
||||
shutdownSignal = signal;
|
||||
stopChild(child, 'SIGTERM');
|
||||
resolveShutdown(signal);
|
||||
return;
|
||||
}
|
||||
repeatedSignal = true;
|
||||
stopChild(child, 'SIGKILL');
|
||||
};
|
||||
signalHandlers.set(signal, handler);
|
||||
process.on(signal, handler);
|
||||
}
|
||||
|
||||
try {
|
||||
const childResult = waitForCli(child);
|
||||
const outcome = await Promise.race([
|
||||
childResult.then((failure) => ({ type: 'exit', failure })),
|
||||
shutdownRequested.then((signal) => ({ type: 'signal', signal })),
|
||||
]);
|
||||
const cleanup = await terminateTree(child, {
|
||||
gracefulTimeoutMs: repeatedSignal ? 0 : 2500,
|
||||
});
|
||||
if (!cleanup.stopped) {
|
||||
console.error(
|
||||
'[ai-game-creator-shell] Tauri dev exited, but its process tree could not be fully stopped.',
|
||||
);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (outcome.type === 'signal') {
|
||||
return 1;
|
||||
}
|
||||
const { failure } = outcome;
|
||||
return failure.type === 'error' || failure.signal ? 1 : (failure.code ?? 0);
|
||||
} finally {
|
||||
for (const [signal, handler] of signalHandlers) {
|
||||
process.off(signal, handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isDirectModuleExecution() {
|
||||
return Boolean(
|
||||
process.argv[1] &&
|
||||
resolve(process.argv[1]) === fileURLToPath(import.meta.url),
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
buildTauriArguments,
|
||||
isDirectModuleExecution,
|
||||
parseLauncherArguments,
|
||||
runTauriDev,
|
||||
spawnTauriCli,
|
||||
};
|
||||
|
||||
if (isDirectModuleExecution()) {
|
||||
try {
|
||||
process.exitCode = await runTauriDev();
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[ai-game-creator-shell] ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
+1
@@ -1507,6 +1507,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"unicode-normalization",
|
||||
"url",
|
||||
"uuid",
|
||||
"windows-sys 0.61.2",
|
||||
"zip",
|
||||
]
|
||||
|
||||
@@ -4,6 +4,10 @@ version = "0.1.0"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[features]
|
||||
default = []
|
||||
game-chat-release = []
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2.6.2", features = [] }
|
||||
|
||||
@@ -32,6 +36,7 @@ tempfile = "3"
|
||||
tokio = { version = "1", features = ["io-util", "macros", "process", "rt-multi-thread", "signal", "sync", "time"] }
|
||||
url = "2"
|
||||
unicode-normalization = "0.1"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
tauri-plugin-clipboard-manager = "2.3.2"
|
||||
|
||||
@@ -39,4 +44,4 @@ tauri-plugin-clipboard-manager = "2.3.2"
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Wdk_Storage_FileSystem", "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_JobObjects"] }
|
||||
windows-sys = { version = "0.61", features = ["Wdk_Storage_FileSystem", "Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_UI_WindowsAndMessaging"] }
|
||||
|
||||
@@ -3,6 +3,7 @@ use super::*;
|
||||
mod canvas_generation;
|
||||
mod draft_validation;
|
||||
mod draft_writer;
|
||||
mod external_generation_state;
|
||||
mod loop_orchestration;
|
||||
mod pass_artifacts;
|
||||
mod prompt_context;
|
||||
@@ -13,9 +14,22 @@ mod tests;
|
||||
mod trace;
|
||||
|
||||
pub(in crate::agent) use canvas_generation::{
|
||||
commit_prepared_platform_art_asset_at, request_platform_art_asset_with_options_at,
|
||||
commit_prepared_platform_art_asset_at, platform_art_generation_error_needs_reconciliation,
|
||||
request_platform_art_asset_with_runtime_options_at,
|
||||
};
|
||||
pub(in crate::agent) use draft_validation::validate_closed_game_script_blocks;
|
||||
pub(in crate::agent) use external_generation_state::{
|
||||
game_creator_agent_runtime_external_generation_exists,
|
||||
platform_art_generation_runtime_context_from_pending,
|
||||
platform_art_generation_runtime_recovery_at, remove_platform_art_generation_runtime_state_at,
|
||||
PlatformArtGenerationRuntimeContext, PlatformArtGenerationRuntimeRecovery,
|
||||
PLATFORM_ART_GENERATION_RUNTIME_SCHEMA_VERSION,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use external_generation_state::{
|
||||
setup_platform_art_generation_runtime_accepted_for_recovery_test,
|
||||
write_platform_art_generation_runtime_accepted_for_test,
|
||||
};
|
||||
pub(in crate::agent) use loop_orchestration::build_game_creator_agent_runtime_llm_client;
|
||||
pub(in crate::agent) use trace::game_creation_agent_group_id;
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user