@playcraft/cli 0.1.36-beta1 → 0.1.37-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -3
- package/SKILLS_REGISTRY.md +149 -0
- package/dist/agent/local-backend.js +1 -1
- package/dist/auth/account-activation.js +157 -0
- package/dist/auth/messages.js +30 -0
- package/dist/cli-root-help.js +2 -0
- package/dist/commands/build-all.js +5 -19
- package/dist/commands/build-temp.js +26 -0
- package/dist/commands/build.js +15 -28
- package/dist/commands/create.js +26 -33
- package/dist/commands/image.js +2 -6
- package/dist/commands/login.js +84 -42
- package/dist/commands/platform-skills.generated.js +19 -0
- package/dist/commands/playable.js +53 -0
- package/dist/commands/skills.js +4 -0
- package/dist/commands/tools-3d.js +11 -0
- package/dist/commands/tools-batch.js +87 -0
- package/dist/commands/tools-generation.js +68 -109
- package/dist/commands/tools.js +2 -2
- package/dist/commands/video.js +111 -0
- package/dist/commands/workspace-runtime.js +54 -0
- package/dist/commands/workspace.js +35 -0
- package/dist/config.js +59 -4
- package/dist/index.js +40 -3
- package/dist/project-skills/builtin-import.js +225 -0
- package/dist/project-skills/commands.js +77 -0
- package/dist/project-skills/lifecycle.js +28 -0
- package/dist/project-skills/local-run.js +112 -0
- package/dist/project-skills/local-store.js +221 -0
- package/dist/project-skills/messages.js +80 -0
- package/dist/project-skills/reconcile.js +62 -0
- package/dist/project-skills/remote-cache.js +51 -0
- package/dist/project-skills/validation.js +19 -0
- package/dist/recording/messages.js +40 -0
- package/dist/recording/project-digest.js +85 -0
- package/dist/recording/recorder.js +293 -0
- package/dist/recording/scenario.js +50 -0
- package/dist/remix/clone.js +2 -0
- package/dist/remix/init-template.js +2 -0
- package/dist/remix/pull.js +2 -0
- package/dist/remix/push.js +21 -1
- package/dist/skill-registry/client.js +345 -0
- package/dist/skill-registry/commands.js +180 -0
- package/dist/skill-registry/evaluation-client.js +156 -0
- package/dist/skill-registry/evaluation-commands.js +174 -0
- package/dist/skill-registry/messages.js +177 -0
- package/dist/skill-registry/package.js +275 -0
- package/dist/skill-registry/platform-package.js +100 -0
- package/dist/utils/agent-api-client.js +185 -30
- package/dist/utils/environment-endpoints.js +17 -0
- package/dist/utils/playcraft-http-client.js +6 -4
- package/dist/utils/tool-operation-journal.js +124 -0
- package/dist/utils/video-evidence-git.js +81 -0
- package/dist/video-replication/client.js +222 -0
- package/dist/video-replication/comparison-evidence.js +149 -0
- package/dist/video-replication/comparison-files.js +57 -0
- package/dist/video-replication/comparison-log.js +72 -0
- package/dist/video-replication/comparison-messages.js +104 -0
- package/dist/video-replication/comparison-output.js +63 -0
- package/dist/video-replication/comparison-preflight.js +66 -0
- package/dist/video-replication/comparison.js +216 -0
- package/dist/video-replication/evidence.js +165 -0
- package/dist/video-replication/media.js +111 -0
- package/dist/video-replication/messages.js +89 -0
- package/dist/workspace/messages.js +35 -0
- package/dist/workspace/transfer-client.js +174 -0
- package/dist/workspace-runtime/codex/app-server.js +1040 -0
- package/dist/workspace-runtime/codex/compact.js +46 -0
- package/dist/workspace-runtime/codex/config-toml.js +107 -0
- package/dist/workspace-runtime/codex/jsonrpc-stdio.js +145 -0
- package/dist/workspace-runtime/codex/launcher-client.js +177 -0
- package/dist/workspace-runtime/codex/loopback.js +146 -0
- package/dist/workspace-runtime/codex/mcp-config.js +39 -0
- package/dist/workspace-runtime/codex/model-broker.js +263 -0
- package/dist/workspace-runtime/codex/native-adapter.js +9 -0
- package/dist/workspace-runtime/codex/permissions.js +70 -0
- package/dist/workspace-runtime/codex/thread-image.js +38 -0
- package/dist/workspace-runtime/codex/ui-instructions.js +4 -0
- package/dist/workspace-runtime/codex/ui-tools.js +183 -0
- package/dist/workspace-runtime/codex/work-mode.js +15 -0
- package/dist/workspace-runtime/main.js +10 -0
- package/dist/workspace-runtime/persistence/journal.js +358 -0
- package/dist/workspace-runtime/persistence/native-subagents.js +162 -0
- package/dist/workspace-runtime/persistence/sqlite-client.js +77 -0
- package/dist/workspace-runtime/persistence/sqlite-worker.js +1161 -0
- package/dist/workspace-runtime/persistence/stopped-execution.js +77 -0
- package/dist/workspace-runtime/previews/output.js +36 -0
- package/dist/workspace-runtime/previews/publish.js +262 -0
- package/dist/workspace-runtime/previews/single-file.js +43 -0
- package/dist/workspace-runtime/processes/managed-writes.js +69 -0
- package/dist/workspace-runtime/production/contracts.js +19 -0
- package/dist/workspace-runtime/production/controller.js +218 -0
- package/dist/workspace-runtime/production/dependencies.js +60 -0
- package/dist/workspace-runtime/production/native.js +212 -0
- package/dist/workspace-runtime/production/processes.js +102 -0
- package/dist/workspace-runtime/production/save-command.js +35 -0
- package/dist/workspace-runtime/production/source-archive.js +137 -0
- package/dist/workspace-runtime/production/source-copy.js +91 -0
- package/dist/workspace-runtime/production/stages.js +303 -0
- package/dist/workspace-runtime/production/storage.js +60 -0
- package/dist/workspace-runtime/serve.js +214 -0
- package/dist/workspace-runtime/server/auth.js +21 -0
- package/dist/workspace-runtime/server/connectivity.js +201 -0
- package/dist/workspace-runtime/server/desktop-host.js +429 -0
- package/dist/workspace-runtime/server/desktop-preview-config.js +81 -0
- package/dist/workspace-runtime/server/desktop-preview-service.js +157 -0
- package/dist/workspace-runtime/server/desktop-preview-static.js +53 -0
- package/dist/workspace-runtime/server/desktop-preview.js +189 -0
- package/dist/workspace-runtime/server/dispatch.js +1217 -0
- package/dist/workspace-runtime/server/endpoints.js +21 -0
- package/dist/workspace-runtime/server/execution-group.js +90 -0
- package/dist/workspace-runtime/server/http.js +1243 -0
- package/dist/workspace-runtime/server/lock.js +53 -0
- package/dist/workspace-runtime/server/rfb-watch-gate.js +168 -0
- package/dist/workspace-runtime/server/source-uploader.js +138 -0
- package/dist/workspace-runtime/server/terminal-host.js +366 -0
- package/dist/workspace-runtime/server/types.js +1 -0
- package/dist/workspace-runtime/server/workspace-transfer.js +99 -0
- package/dist/workspace-runtime/workspaces/archive.js +207 -0
- package/dist/workspace-runtime/workspaces/artifact-events.js +55 -0
- package/dist/workspace-runtime/workspaces/artifact-files.js +197 -0
- package/dist/workspace-runtime/workspaces/artifact-receipts.js +89 -0
- package/dist/workspace-runtime/workspaces/artifacts.js +282 -0
- package/dist/workspace-runtime/workspaces/attachment-content.js +123 -0
- package/dist/workspace-runtime/workspaces/attachments.js +185 -0
- package/dist/workspace-runtime/workspaces/batch-commit.js +142 -0
- package/dist/workspace-runtime/workspaces/cli-context.js +23 -0
- package/dist/workspace-runtime/workspaces/cli-credentials.js +111 -0
- package/dist/workspace-runtime/workspaces/composer-context.js +147 -0
- package/dist/workspace-runtime/workspaces/context-error.js +2 -0
- package/dist/workspace-runtime/workspaces/dependencies.js +264 -0
- package/dist/workspace-runtime/workspaces/developer-command.js +64 -0
- package/dist/workspace-runtime/workspaces/directories.js +133 -0
- package/dist/workspace-runtime/workspaces/directory-access.js +37 -0
- package/dist/workspace-runtime/workspaces/directory-attachments.js +245 -0
- package/dist/workspace-runtime/workspaces/directory-maintenance.js +111 -0
- package/dist/workspace-runtime/workspaces/directory-stats.js +49 -0
- package/dist/workspace-runtime/workspaces/disk-snapshot.js +31 -0
- package/dist/workspace-runtime/workspaces/empty-template.js +42 -0
- package/dist/workspace-runtime/workspaces/files-search.js +116 -0
- package/dist/workspace-runtime/workspaces/files.js +120 -0
- package/dist/workspace-runtime/workspaces/git-credential-broker.js +312 -0
- package/dist/workspace-runtime/workspaces/git-credential-helper.js +68 -0
- package/dist/workspace-runtime/workspaces/git-direct-store.js +155 -0
- package/dist/workspace-runtime/workspaces/git.js +670 -0
- package/dist/workspace-runtime/workspaces/instructions.js +56 -0
- package/dist/workspace-runtime/workspaces/json5-edit.js +170 -0
- package/dist/workspace-runtime/workspaces/library-attachments.js +268 -0
- package/dist/workspace-runtime/workspaces/optional-platform-skills.js +14 -0
- package/dist/workspace-runtime/workspaces/parameters.js +272 -0
- package/dist/workspace-runtime/workspaces/prepare.js +278 -0
- package/dist/workspace-runtime/workspaces/registry.js +251 -0
- package/dist/workspace-runtime/workspaces/remix-references.js +301 -0
- package/dist/workspace-runtime/workspaces/revisions.js +31 -0
- package/dist/workspace-runtime/workspaces/session-image.js +104 -0
- package/dist/workspace-runtime/workspaces/shared-git.js +40 -0
- package/dist/workspace-runtime/workspaces/skill-artifact-loader.js +95 -0
- package/dist/workspace-runtime/workspaces/skills.js +191 -0
- package/dist/workspace-runtime/workspaces/transfer.js +288 -0
- package/dist/workspace-runtime/workspaces/turn-changes.js +75 -0
- package/dist/workspace-runtime/workspaces/video-attachments.js +49 -0
- package/package.json +15 -5
- package/project-template/.claude/agents/refs/ta-image-generation-detail.md +123 -67
- package/project-template/.claude/skills/playcraft-image-generation/SKILL.md +44 -105
- package/project-template/.claude/skills/playcraft-image-generation/reference/gen-batch-sprite.template.mjs +33 -42
- package/project-template/.claude/skills/playcraft-image-generation/reference/gen-batch.template.mjs +20 -18
- package/project-template/.claude/skills/playcraft-image-generation/reference/process-batch.template.mjs +7 -6
- package/project-template/.claude/skills/playcraft-image-generation/reference/prompt-cookbook.md +39 -36
- package/project-template/.claude/skills/playcraft-replica-validation/SKILL.md +25 -0
- package/project-template/.claude/skills/playcraft-replica-validation/references/contracts.md +79 -0
- package/project-template/.claude/skills/playcraft-video-understanding/SKILL.md +29 -0
- package/project-template/.claude/skills/playcraft-video-understanding/references/contracts.md +37 -0
- package/project-template-v2/.claude/agents/artist.md +82 -0
- package/project-template-v2/.claude/agents/developer.md +153 -0
- package/project-template-v2/.claude/agents/game-designer.md +264 -0
- package/project-template-v2/.claude/agents/refs/artist-art-style-catalog.md +533 -0
- package/project-template-v2/.claude/agents/refs/artist-color-audio-recipes.md +153 -0
- package/project-template-v2/.claude/agents/refs/artist-dimension-axis.md +27 -0
- package/project-template-v2/.claude/agents/refs/artist-master-composite-recipes.md +208 -0
- package/project-template-v2/.claude/agents/refs/atom-skill-library.md +81 -0
- package/project-template-v2/.claude/agents/refs/developer-impl-cookbook.md +432 -0
- package/project-template-v2/.claude/agents/refs/framework-5-component-filter.md +252 -0
- package/project-template-v2/.claude/agents/refs/framework-game-feel-juice.md +266 -0
- package/project-template-v2/.claude/agents/refs/framework-mda.md +147 -0
- package/project-template-v2/.claude/agents/refs/game-designer-gameplay-sufficiency.md +123 -0
- package/project-template-v2/.claude/agents/refs/ta-3d-flip-recipe.md +88 -0
- package/project-template-v2/.claude/agents/refs/ta-atlas-deliverable-standard.md +67 -0
- package/project-template-v2/.claude/agents/refs/ta-batch-pipeline-recipes.md +120 -0
- package/project-template-v2/.claude/agents/refs/ta-image-generation-detail.md +300 -0
- package/project-template-v2/.claude/agents/refs/ta-image-ops-reference.md +495 -0
- package/project-template-v2/.claude/agents/refs/ta-pipeline-cookbook.md +1141 -0
- package/project-template-v2/.claude/agents/refs/ta-tools-reference.md +111 -0
- package/project-template-v2/.claude/agents/refs/ta-vfx-preset-catalog.md +365 -0
- package/project-template-v2/.claude/agents/refs/threejs-cannon-pitfalls.md +412 -0
- package/project-template-v2/.claude/agents/reviewer.md +75 -0
- package/project-template-v2/.claude/agents/technical-artist.md +86 -0
- package/project-template-v2/.claude/hooks/snapshot-milestone.mjs +243 -0
- package/project-template-v2/.claude/hooks/user-prompt.mjs +133 -0
- package/project-template-v2/.claude/settings.json +33 -0
- package/project-template-v2/.claude/skills/brainstorming/SKILL.md +161 -0
- package/project-template-v2/.claude/skills/brainstorming/scripts/frame-template.html +270 -0
- package/project-template-v2/.claude/skills/brainstorming/scripts/helper.js +177 -0
- package/project-template-v2/.claude/skills/brainstorming/scripts/server.cjs +354 -0
- package/project-template-v2/.claude/skills/brainstorming/scripts/start-server.sh +148 -0
- package/project-template-v2/.claude/skills/brainstorming/scripts/stop-server.sh +56 -0
- package/project-template-v2/.claude/skills/brainstorming/scripts/wait-for-selection.sh +62 -0
- package/project-template-v2/.claude/skills/brainstorming/spec-document-reviewer-prompt.md +49 -0
- package/project-template-v2/.claude/skills/brainstorming/visual-companion.md +309 -0
- package/project-template-v2/.claude/skills/playcraft-ad-psychology/SKILL.md +182 -0
- package/project-template-v2/.claude/skills/playcraft-art-style-guide/SKILL.md +123 -0
- package/project-template-v2/.claude/skills/playcraft-asset-state-sheet/SKILL.md +205 -0
- package/project-template-v2/.claude/skills/playcraft-audio-generation/SKILL.md +280 -0
- package/project-template-v2/.claude/skills/playcraft-batch-pipeline/SKILL.md +184 -0
- package/project-template-v2/.claude/skills/playcraft-build-optimizer/SKILL.md +306 -0
- package/project-template-v2/.claude/skills/playcraft-image-generation/SKILL.md +298 -0
- package/project-template-v2/.claude/skills/playcraft-image-generation/reference/build-sprite-sheet.template.mjs +123 -0
- package/project-template-v2/.claude/skills/playcraft-image-generation/reference/compare-style.template.mjs +254 -0
- package/project-template-v2/.claude/skills/playcraft-image-generation/reference/gen-batch-sprite.template.mjs +324 -0
- package/project-template-v2/.claude/skills/playcraft-image-generation/reference/gen-batch.template.mjs +97 -0
- package/project-template-v2/.claude/skills/playcraft-image-generation/reference/gen-edit-variants.template.mjs +118 -0
- package/project-template-v2/.claude/skills/playcraft-image-generation/reference/process-batch.template.mjs +137 -0
- package/project-template-v2/.claude/skills/playcraft-image-generation/reference/prompt-cookbook.md +397 -0
- package/project-template-v2/.claude/skills/playcraft-image-generation/reference/validate-sprite-sheet.template.mjs +296 -0
- package/project-template-v2/.claude/skills/playcraft-image-ops/SKILL.md +122 -0
- package/project-template-v2/.claude/skills/playcraft-image-processing/SKILL.md +219 -0
- package/project-template-v2/.claude/skills/playcraft-masking/SKILL.md +373 -0
- package/project-template-v2/.claude/skills/playcraft-playable-optimization/SKILL.md +161 -0
- package/project-template-v2/.claude/skills/playcraft-research/SKILL.md +215 -0
- package/project-template-v2/.claude/skills/playcraft-skill-recommender/SKILL.md +382 -0
- package/project-template-v2/.claude/skills/playcraft-sprite-generation/SKILL.md +423 -0
- package/project-template-v2/.claude/skills/playcraft-sprite-remix/SKILL.md +158 -0
- package/project-template-v2/.claude/skills/playcraft-sprite-sheet/SKILL.md +100 -0
- package/project-template-v2/.claude/skills/playcraft-storyboard/SKILL.md +167 -0
- package/project-template-v2/.claude/skills/playcraft-style-qa/SKILL.md +270 -0
- package/project-template-v2/.claude/skills/playcraft-text-rendering/SKILL.md +236 -0
- package/project-template-v2/.claude/skills/playcraft-vfx-animation/SKILL.md +130 -0
- package/project-template-v2/.claude/skills/playwright-cli/SKILL.md +390 -0
- package/project-template-v2/.claude/skills/playwright-cli/references/element-attributes.md +23 -0
- package/project-template-v2/.claude/skills/playwright-cli/references/playwright-tests.md +39 -0
- package/project-template-v2/.claude/skills/playwright-cli/references/request-mocking.md +87 -0
- package/project-template-v2/.claude/skills/playwright-cli/references/running-code.md +240 -0
- package/project-template-v2/.claude/skills/playwright-cli/references/session-management.md +226 -0
- package/project-template-v2/.claude/skills/playwright-cli/references/spec-driven-testing.md +308 -0
- package/project-template-v2/.claude/skills/playwright-cli/references/storage-state.md +275 -0
- package/project-template-v2/.claude/skills/playwright-cli/references/test-generation.md +134 -0
- package/project-template-v2/.claude/skills/playwright-cli/references/tracing.md +142 -0
- package/project-template-v2/.claude/skills/playwright-cli/references/video-recording.md +153 -0
- package/project-template-v2/.claude/skills/session-analyzer/SKILL.md +386 -0
- package/project-template-v2/.claude/skills/session-analyzer/scripts/execution-breakdown.mjs +182 -0
- package/project-template-v2/.claude/skills/session-analyzer/scripts/find-turns.mjs +72 -0
- package/project-template-v2/.claude/skills/session-analyzer/scripts/heavy-output.mjs +121 -0
- package/project-template-v2/.claude/skills/session-analyzer/scripts/resolve-session.mjs +102 -0
- package/project-template-v2/.claude/skills/session-analyzer/scripts/subagent-stats.mjs +127 -0
- package/project-template-v2/.claude/skills/session-analyzer/scripts/subagent-tool-timeline.mjs +106 -0
- package/project-template-v2/.claude/skills/session-analyzer/scripts/time-gaps.mjs +128 -0
- package/project-template-v2/.claude/skills/session-analyzer/scripts/turn-timeline.mjs +67 -0
- package/project-template-v2/.claude/snapshot.mjs +263 -0
- package/project-template-v2/.playcraft/skills.lock.json +152 -0
- package/project-template-v2/CLAUDE.md +146 -0
- package/project-template-v2/assets/audio/bgm/.gitkeep +0 -0
- package/project-template-v2/assets/audio/sfx/.gitkeep +0 -0
- package/project-template-v2/assets/bundles/.gitkeep +0 -0
- package/project-template-v2/assets/images/bg/.gitkeep +0 -0
- package/project-template-v2/assets/images/reference/.gitkeep +0 -0
- package/project-template-v2/assets/images/storyboard/.gitkeep +0 -0
- package/project-template-v2/assets/images/tiles/.gitkeep +0 -0
- package/project-template-v2/assets/images/ui/.gitkeep +0 -0
- package/project-template-v2/assets/images/vfx/.gitkeep +0 -0
- package/project-template-v2/assets/models/.gitkeep +0 -0
- package/project-template-v2/docs/harness/iteration-1/context-flow.md +254 -0
- package/project-template-v2/docs/harness/iteration-1/generate-flow.md +91 -0
- package/project-template-v2/docs/harness/iteration-1/ideate-flow.md +214 -0
- package/project-template-v2/docs/harness/iteration-1/optimize-flow.md +75 -0
- package/project-template-v2/docs/harness/iteration-1/wrapup-flow.md +63 -0
- package/project-template-v2/docs/harness/iteration-2/context-flow.md +223 -0
- package/project-template-v2/docs/harness/iteration-2/generate-flow.md +129 -0
- package/project-template-v2/docs/harness/iteration-2/ideate-flow.md +267 -0
- package/project-template-v2/docs/harness/iteration-2/optimize-flow.md +164 -0
- package/project-template-v2/docs/harness/iteration-2/wrapup-flow.md +115 -0
- package/project-template-v2/docs/harness/orchestrator-flow.md +364 -0
- package/project-template-v2/docs/project-state.json +60 -0
- package/project-template-v2/docs/project-state.md +72 -0
- package/project-template-v2/docs/standards/README.md +225 -0
- package/project-template-v2/docs/standards/agent-behavior-standards.md +174 -0
- package/project-template-v2/docs/standards/artifacts/design-brief.md +19 -0
- package/project-template-v2/docs/standards/artifacts/design.md +22 -0
- package/project-template-v2/docs/standards/artifacts/game-code.md +41 -0
- package/project-template-v2/docs/standards/artifacts/todo-list.md +41 -0
- package/project-template-v2/docs/standards/iter1-agent-behavior-standards.md +343 -0
- package/project-template-v2/game/index.ts +18 -0
- package/project-template-v2/globals.d.ts +51 -0
- package/project-template-v2/index.css +34 -0
- package/project-template-v2/index.html +18 -0
- package/project-template-v2/main.ts +9 -0
- package/project-template-v2/package.json +46 -0
- package/project-template-v2/skills/_shared/scripts/dispatch-clear.mjs +31 -0
- package/project-template-v2/skills/_shared/scripts/dispatch-set.mjs +86 -0
- package/project-template-v2/skills/_shared/scripts/dod-check.mjs +153 -0
- package/project-template-v2/skills/_shared/scripts/handoff-append.mjs +70 -0
- package/project-template-v2/skills/_shared/scripts/lib/validator-artifacts.mjs +91 -0
- package/project-template-v2/skills/_shared/scripts/pipeline/dod-config.mjs +131 -0
- package/project-template-v2/skills/_shared/scripts/pipeline/index.mjs +80 -0
- package/project-template-v2/skills/_shared/scripts/pipeline/iteration-1-core.mjs +90 -0
- package/project-template-v2/skills/_shared/scripts/pipeline/iteration-2-wrap.mjs +93 -0
- package/project-template-v2/skills/_shared/scripts/pipeline/iteration-3-visual.mjs +23 -0
- package/project-template-v2/skills/_shared/scripts/render-project-state.mjs +230 -0
- package/project-template-v2/skills/_shared/scripts/state-advance-stage.mjs +58 -0
- package/project-template-v2/skills/_shared/scripts/state-get.mjs +339 -0
- package/project-template-v2/skills/_shared/scripts/state-handoff.mjs +39 -0
- package/project-template-v2/skills/_shared/scripts/state-set.mjs +94 -0
- package/project-template-v2/skills/_shared/scripts/state-store.mjs +783 -0
- package/project-template-v2/skills/_shared/scripts/todo-add.mjs +88 -0
- package/project-template-v2/skills/_shared/scripts/todo-get.mjs +130 -0
- package/project-template-v2/skills/_shared/scripts/todo-remove.mjs +33 -0
- package/project-template-v2/skills/_shared/scripts/todo-set.mjs +47 -0
- package/project-template-v2/skills/_shared/scripts/verify-asset-code-sync.mjs +268 -0
- package/project-template-v2/skills/_shared/scripts/verify-env.mjs +285 -0
- package/project-template-v2/skills/_shared/scripts/verify-placeholders.mjs +161 -0
- package/project-template-v2/skills/playable-autoplay/SKILL.md +176 -0
- package/project-template-v2/skills/playable-autoplay/agents/openai.yaml +4 -0
- package/project-template-v2/skills/playable-debug/SKILL.md +116 -0
- package/project-template-v2/skills/playable-debug/agents/openai.yaml +4 -0
- package/project-template-v2/skills/playable-debug/references/debug-config.md +40 -0
- package/project-template-v2/skills/playable-record/SKILL.md +140 -0
- package/project-template-v2/skills/playable-record/scripts/lib/dev-server.mjs +104 -0
- package/project-template-v2/skills/playable-record/scripts/lib/record-audio-bridge.js +141 -0
- package/project-template-v2/skills/playable-record/scripts/record-playable.mjs +425 -0
- package/project-template-v2/skills/playable-record/scripts/verify-contract.mjs +261 -0
- package/project-template-v2/skills/playable-record/scripts/verify-firstwin.mjs +398 -0
- package/project-template-v2/skills/playable-record/scripts/verify-fusion.mjs +322 -0
- package/project-template-v2/skills/playable-record/scripts/verify-lifecycle.mjs +105 -0
- package/project-template-v2/skills/playable-record/scripts/verify-vlm-video.mjs +230 -0
- package/project-template-v2/skills/playable-validate/SKILL.md +61 -0
- package/project-template-v2/skills/playable-validate/validation-rules.md +14 -0
- package/project-template-v2/skills/playable-verify-ui/SKILL.md +63 -0
- package/project-template-v2/skills/playable-verify-ui/scripts/lib/__init__.py +1 -0
- package/project-template-v2/skills/playable-verify-ui/scripts/lib/config_expr.js +218 -0
- package/project-template-v2/skills/playable-verify-ui/scripts/lib/node_utils.js +51 -0
- package/project-template-v2/skills/playable-verify-ui/scripts/lib/profile_loader.py +59 -0
- package/project-template-v2/skills/playable-verify-ui/scripts/lib/report.py +106 -0
- package/project-template-v2/skills/playable-verify-ui/scripts/lib/runtime_contract.js +116 -0
- package/project-template-v2/skills/playable-verify-ui/scripts/verify_fetch_antipatterns.py +59 -0
- package/project-template-v2/skills/playable-verify-ui/scripts/verify_hardcoded_layout.js +64 -0
- package/project-template-v2/skills/playable-verify-ui/scripts/verify_runtime_contract.js +58 -0
- package/project-template-v2/skills/playable-verify-ui/scripts/verify_text_overlap.py +333 -0
- package/project-template-v2/ta-workspace/scripts/.gitkeep +0 -0
- package/project-template-v2/tsconfig.json +20 -0
- package/project-template-v2/vite.config.ts +27 -0
- package/project-templates/batch-locks/phaser.yaml +922 -0
- package/project-templates/batch-locks/threejs.yaml +978 -0
- package/project-templates/empty/AGENTS.md +41 -0
- package/project-templates/empty/gitignore +33 -0
- package/project-templates/phaser/.claude/agents/refs/ta-image-generation-detail.md +59 -59
- package/project-templates/phaser/.claude/skills/playcraft-image-generation/SKILL.md +44 -105
- package/project-templates/phaser/.claude/skills/playcraft-image-generation/reference/gen-batch-sprite.template.mjs +33 -42
- package/project-templates/phaser/.claude/skills/playcraft-image-generation/reference/gen-batch.template.mjs +20 -18
- package/project-templates/phaser/.claude/skills/playcraft-image-generation/reference/process-batch.template.mjs +7 -6
- package/project-templates/phaser/.claude/skills/playcraft-image-generation/reference/prompt-cookbook.md +39 -36
- package/project-templates/threejs/.claude/agents/refs/ta-image-generation-detail.md +59 -59
- package/project-templates/threejs/.claude/skills/playcraft-image-generation/SKILL.md +44 -105
- package/project-templates/threejs/.claude/skills/playcraft-image-generation/reference/gen-batch-sprite.template.mjs +33 -42
- package/project-templates/threejs/.claude/skills/playcraft-image-generation/reference/gen-batch.template.mjs +20 -18
- package/project-templates/threejs/.claude/skills/playcraft-image-generation/reference/process-batch.template.mjs +7 -6
- package/project-templates/threejs/.claude/skills/playcraft-image-generation/reference/prompt-cookbook.md +39 -36
- package/dist/commands/tools-image-context.js +0 -23
- package/dist/utils/image-asset-context.js +0 -105
|
@@ -0,0 +1,1243 @@
|
|
|
1
|
+
import { readObservedFile, withObservedFile } from '../workspaces/revisions.js';
|
|
2
|
+
import { registerWorkspace, revisionScope, sessionWorkspaceRoot, workspaceRoot, WorkspaceContextError } from '../workspaces/registry.js';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { constants } from 'node:fs';
|
|
5
|
+
import { access as accessDirectory, stat } from 'node:fs/promises';
|
|
6
|
+
import { workspaceRegistrationRequestSchema, workspaceFileSearchQuerySchema, HTTP_STATUS_BY_ERROR, assertLeaseFence, buildHandshakeDocument, capability, findUntrustedRuntimeFields, gitFileRefSchema, hashOperationPayload, isLostThreadError, sourceAckSchema, operationAcceptRequestSchema, operationKindSchema, operationScopeKey, productionSessionAttemptId, isWorkspaceMutation, resolveIdempotentAccept, nativeHistoryReadSchema, runtimeError, runtimeConnectivityDocumentSchema, unavailableRuntimeCapabilities, workspaceUiResultSchema, workspaceRemixReferenceImportRequestSchema, WORKSPACE_REMIX_REFERENCE_BODY_MAX_BYTES, } from '@playcraft/common/cloud-workspace/runtime';
|
|
7
|
+
import { controlTokenMatches, extractControlToken } from './auth.js';
|
|
8
|
+
import { applyRuntimeEndpointPatch } from './endpoints.js';
|
|
9
|
+
import { wakeSourceEventUploader } from './source-uploader.js';
|
|
10
|
+
import { canExecuteKind, executeOperation } from './dispatch.js';
|
|
11
|
+
import { InvalidWorkspacePathError, listWorkspaceFiles, } from '../workspaces/files.js';
|
|
12
|
+
import { GitWorkspaceError, readWorkspaceGitDiff, readWorkspaceGitFile, readWorkspaceGitGraph, readWorkspaceGitStatus, } from '../workspaces/git.js';
|
|
13
|
+
import { readWorkspaceParameters } from '../workspaces/parameters.js';
|
|
14
|
+
import { readDependencies } from '../workspaces/dependencies.js';
|
|
15
|
+
import { desktopHost, desktopRoute } from './desktop-host.js';
|
|
16
|
+
import { ensureCliCredentials } from '../workspaces/cli-credentials.js';
|
|
17
|
+
import { readAttachmentUpload, uploadWorkspaceAttachment, uploadWorkspaceVideoAttachment } from '../workspaces/attachments.js';
|
|
18
|
+
import { serveWorkspaceAttachment } from '../workspaces/attachment-content.js';
|
|
19
|
+
import { importWorkspaceLibraryAttachment, listWorkspaceLibraryAttachments, listWorkspaceLibraryImportReceipts, readLibraryAttachmentUpload } from '../workspaces/library-attachments.js';
|
|
20
|
+
import { beginWorkspaceDirectoryAttachment, uploadWorkspaceDirectoryFile, completeWorkspaceDirectoryAttachment, cancelWorkspaceDirectoryAttachment } from '../workspaces/directory-attachments.js';
|
|
21
|
+
import { readWorkspaceSkills } from '../workspaces/skills.js';
|
|
22
|
+
import { listWorkspaceRemixReferences, RemixReferenceError } from '../workspaces/remix-references.js';
|
|
23
|
+
import { loadWorkspaceSkillArtifact } from '../workspaces/skill-artifact-loader.js';
|
|
24
|
+
import { join } from 'node:path';
|
|
25
|
+
import { terminalHost } from './terminal-host.js';
|
|
26
|
+
import { productionCapability, productionDirectoryBusy, executeSandboxProduction, sandboxProductionReceipt } from '../production/controller.js';
|
|
27
|
+
import { cleanupWorkspaceDirectories, syncWorkspaceDirectories } from '../workspaces/directory-maintenance.js';
|
|
28
|
+
import { registerWorkspaceDirectory, restoreWorkspaceDirectory } from '../workspaces/directories.js';
|
|
29
|
+
import { readWorkspaceDirectoryStats } from '../workspaces/directory-stats.js';
|
|
30
|
+
import { probeRuntimeConnectivity } from './connectivity.js';
|
|
31
|
+
import { refreshWorkspaceArtifacts } from '../workspaces/artifact-events.js';
|
|
32
|
+
import { WorkspaceArtifactStore } from '../workspaces/artifacts.js';
|
|
33
|
+
import { workspaceArtifactContentQuerySchema } from '@playcraft/common/cloud-workspace/runtime';
|
|
34
|
+
import { searchWorkspaceFiles } from '../workspaces/files-search.js';
|
|
35
|
+
import { serveWorkspaceArchive } from '../workspaces/archive.js';
|
|
36
|
+
import { handleWorkspaceTransfer } from './workspace-transfer.js';
|
|
37
|
+
import { serveSessionImage } from '../workspaces/session-image.js';
|
|
38
|
+
export async function handleRuntimeRequest(state, request, response) {
|
|
39
|
+
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
|
|
40
|
+
const directoryName = url.searchParams.get('directoryName') ?? 'basic';
|
|
41
|
+
const access = authorizeRuntime(state, request);
|
|
42
|
+
if (!access) {
|
|
43
|
+
writeError(response, runtimeError('unauthenticated', 'control_token_required'));
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
if (access === 'read' && !readSourcePath(request.method ?? 'GET', url.pathname)) {
|
|
47
|
+
writeJson(response, 403, { error: 'source_read_only' });
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
if (request.method === 'GET' && url.pathname === '/runtime/production/capability') {
|
|
52
|
+
writeJson(response, 200, await productionCapability(state));
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (request.method === 'POST' && ['/runtime/production/stages', '/runtime/production/stop', '/runtime/production/reconcile'].includes(url.pathname)) {
|
|
56
|
+
writeJson(response, 200, await executeSandboxProduction(state, await readJson(request)));
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
if (request.method === 'GET' && url.pathname.startsWith('/runtime/production/stages/')) {
|
|
60
|
+
writeJson(response, 200, await sandboxProductionReceipt(state, decodeURIComponent(url.pathname.slice('/runtime/production/stages/'.length)), {
|
|
61
|
+
workspaceId: url.searchParams.get('workspaceId') ?? '', directoryName, taskId: url.searchParams.get('taskId') ?? '',
|
|
62
|
+
attemptId: url.searchParams.get('attemptId') ?? '', owner: url.searchParams.get('owner') ?? '', fence: Number(url.searchParams.get('fence')),
|
|
63
|
+
}));
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
if (request.method === 'GET' && url.pathname === '/runtime/health') {
|
|
67
|
+
writeJson(response, 200, { status: 'ok', handshake: handshake(state) });
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (request.method === 'GET' && url.pathname === '/runtime/connectivity') {
|
|
71
|
+
if (writeDestroyed(state, response))
|
|
72
|
+
return;
|
|
73
|
+
const parsed = runtimeConnectivityDocumentSchema.shape.workspaceId.safeParse(url.searchParams.get('workspaceId'));
|
|
74
|
+
if (!parsed.success) {
|
|
75
|
+
writeJson(response, 400, { error: 'invalid_workspace' });
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const workspaceId = parsed.data;
|
|
79
|
+
const root = await sessionWorkspaceRoot(state, workspaceId, directoryName);
|
|
80
|
+
const rootStat = await stat(root).catch(error => {
|
|
81
|
+
if (['ENOENT', 'ENOTDIR'].includes(error.code))
|
|
82
|
+
throw new WorkspaceContextError('workspace_not_prepared', { cause: error });
|
|
83
|
+
throw error;
|
|
84
|
+
});
|
|
85
|
+
if (!rootStat.isDirectory())
|
|
86
|
+
throw new WorkspaceContextError('workspace_not_prepared');
|
|
87
|
+
await accessDirectory(root, constants.R_OK | constants.X_OK);
|
|
88
|
+
writeJson(response, 200, await probeRuntimeConnectivity(state, workspaceId));
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
if (request.method === 'GET' && url.pathname === '/runtime/identity') {
|
|
92
|
+
const { runtimeId, userId, environment, generation } = state.config;
|
|
93
|
+
writeJson(response, 200, {
|
|
94
|
+
runtimeId,
|
|
95
|
+
userId,
|
|
96
|
+
environment,
|
|
97
|
+
generation,
|
|
98
|
+
runtimeEpoch: state.runtimeEpoch,
|
|
99
|
+
instanceToken: state.instanceToken,
|
|
100
|
+
permissionsVersion: 1,
|
|
101
|
+
composerContextVersion: 1,
|
|
102
|
+
remixReferencesVersion: 1,
|
|
103
|
+
...(state.native?.workspaceUi ? { workspaceUiVersion: 1 } : {}),
|
|
104
|
+
...(state.native?.startReview && state.native?.steer ? { turnControlVersion: 1 } : {}),
|
|
105
|
+
...(state.native?.startCompact ? { compactionVersion: 1 } : {}),
|
|
106
|
+
sourceReadToken: state.journal.sourceReadToken(),
|
|
107
|
+
workspaceMode: state.config.workspaceMode,
|
|
108
|
+
executionGroup: {
|
|
109
|
+
replaced: state.journal.executionGroup().replaced,
|
|
110
|
+
stopConfirmed: state.journal.executionGroup().stopConfirmed,
|
|
111
|
+
...(state.journal.stoppedRuntimeEpochs().length ? { stoppedRuntimeEpochs: state.journal.stoppedRuntimeEpochs() } : {}),
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (request.method === 'GET' && url.pathname === '/runtime/approvals') {
|
|
117
|
+
writeJson(response, 200, { approvals: state.journal.listApprovals() });
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
const uiResultRoute = /^\/runtime\/sessions\/([^/]+)\/ui-results$/.exec(url.pathname);
|
|
121
|
+
if (request.method === 'POST' && uiResultRoute) {
|
|
122
|
+
if (writeDestroyed(state, response))
|
|
123
|
+
return;
|
|
124
|
+
const sessionId = decodeURIComponent(uiResultRoute[1]);
|
|
125
|
+
const parsed = workspaceUiResultSchema.safeParse(await readJson(request));
|
|
126
|
+
if (!parsed.success) {
|
|
127
|
+
writeJson(response, 400, { error: 'invalid_ui_result' });
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
const session = state.journal.getSession(sessionId);
|
|
131
|
+
if (!session || productionSessionAttemptId(sessionId) || session.workspaceId !== url.searchParams.get('workspaceId')
|
|
132
|
+
|| (session.directoryName ?? 'basic') !== directoryName) {
|
|
133
|
+
writeJson(response, 404, { error: 'session_not_found' });
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
if (!state.native?.workspaceUi || !state.native.respondUiTool) {
|
|
137
|
+
writeJson(response, 409, { error: 'ui_tools_unavailable' });
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const result = await state.native.respondUiTool({ sessionId, ...parsed.data });
|
|
141
|
+
writeJson(response, result.outcome === 'accepted' ? 200 : 409, result);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (request.method === 'POST' && url.pathname === '/runtime/workspaces/register') {
|
|
145
|
+
if (writeDestroyed(state, response))
|
|
146
|
+
return;
|
|
147
|
+
const parsed = workspaceRegistrationRequestSchema.safeParse(await readJson(request));
|
|
148
|
+
if (!parsed.success || parsed.data.generation !== state.config.generation || parsed.data.runtimeEpoch !== state.runtimeEpoch) {
|
|
149
|
+
writeJson(response, 409, { error: 'invalid_workspace_registration' });
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const binding = await registerWorkspace(state, parsed.data.binding, parsed.data.leaseFence, parsed.data.preparation, parsed.data.cliCredentials === false, parsed.data.sourceSnapshot);
|
|
153
|
+
if (parsed.data.cliCredentials)
|
|
154
|
+
await ensureCliCredentials(state);
|
|
155
|
+
writeJson(response, 200, { workspaceId: binding.workspaceId, status: 'registered' });
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (request.method === 'POST' && url.pathname === '/runtime/workspaces/directories/register') {
|
|
159
|
+
if (writeDestroyed(state, response))
|
|
160
|
+
return;
|
|
161
|
+
const body = asRecord(await readJson(request));
|
|
162
|
+
if (body.generation !== state.config.generation || body.runtimeEpoch !== state.runtimeEpoch || !Number.isSafeInteger(body.leaseFence)) {
|
|
163
|
+
writeJson(response, 409, { error: 'invalid_workspace_registration' });
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
writeJson(response, 200, await registerWorkspaceDirectory(state, body.directory, Number(body.leaseFence)));
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const maintenance = /^\/runtime\/workspaces\/([a-f0-9-]{36})\/directories\/(cleanup|sync|stats)$/.exec(url.pathname);
|
|
170
|
+
if ((request.method === 'GET' || request.method === 'POST') && maintenance?.[2] === 'stats') {
|
|
171
|
+
if (writeDestroyed(state, response))
|
|
172
|
+
return;
|
|
173
|
+
writeJson(response, 200, await readWorkspaceDirectoryStats(state, maintenance[1]));
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (request.method === 'POST' && maintenance) {
|
|
177
|
+
if (writeDestroyed(state, response))
|
|
178
|
+
return;
|
|
179
|
+
const body = asRecord(await readJson(request));
|
|
180
|
+
const workspaceId = maintenance[1];
|
|
181
|
+
writeJson(response, 200, maintenance[2] === 'cleanup'
|
|
182
|
+
? await cleanupWorkspaceDirectories(state, workspaceId, body.directoryNames)
|
|
183
|
+
: await syncWorkspaceDirectories(state, workspaceId, body.commitHash, body.targetDirectoryNames));
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (request.method === 'POST' && url.pathname === '/runtime/endpoints') {
|
|
187
|
+
try {
|
|
188
|
+
writeJson(response, 200, await applyRuntimeEndpointPatch(state, await readJson(request)));
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
writeError(response, runtimeError('invalid_config', 'endpoint_patch_rejected'));
|
|
192
|
+
}
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (request.method === 'GET' && url.pathname === '/runtime/handshake') {
|
|
196
|
+
writeJson(response, 200, handshake(state));
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
const historyPath = sessionHistoryPath(url.pathname);
|
|
200
|
+
if (request.method === 'GET' && historyPath) {
|
|
201
|
+
await handleSessionHistory(state, response, historyPath.workspaceId, historyPath.sessionId);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
if (['GET', 'HEAD', 'POST'].includes(request.method ?? '') && url.pathname === '/runtime/session-image') {
|
|
205
|
+
let recordedPath;
|
|
206
|
+
if (request.method === 'POST') {
|
|
207
|
+
const body = asRecord(await readJson(request));
|
|
208
|
+
if (Object.keys(body).length !== 1 || typeof body.path !== 'string' || !body.path || body.path.length > 4096) {
|
|
209
|
+
writeJson(response, 404, { error: 'image_not_found' });
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
recordedPath = body.path;
|
|
213
|
+
}
|
|
214
|
+
await serveSessionImage(state, request, response, url.searchParams, recordedPath);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (isUnimplementedWorkbenchPath(url.pathname)) {
|
|
218
|
+
if (writeDestroyed(state, response))
|
|
219
|
+
return;
|
|
220
|
+
writeError(response, runtimeError('capability_unavailable', 'capability_not_implemented'));
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
if (url.pathname === '/runtime/events' || url.pathname.startsWith('/runtime/events/')) {
|
|
224
|
+
await handleSourceEvents(state, request, response, url);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (url.pathname === '/runtime/attachments/library' && ['GET', 'POST'].includes(request.method ?? '')) {
|
|
228
|
+
if (writeDestroyed(state, response))
|
|
229
|
+
return;
|
|
230
|
+
const workspaceId = url.searchParams.get('workspaceId') ?? '';
|
|
231
|
+
const root = await workspaceRoot(state, workspaceId, directoryName);
|
|
232
|
+
if (request.method === 'GET') {
|
|
233
|
+
const sessionId = url.searchParams.get('sessionId') ?? undefined;
|
|
234
|
+
writeJson(response, 200, { attachments: await listWorkspaceLibraryAttachments(root, sessionId),
|
|
235
|
+
importReceipts: await listWorkspaceLibraryImportReceipts(root, sessionId) });
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
if (await productionDirectoryBusy(state, workspaceId, directoryName)) {
|
|
239
|
+
writeJson(response, 409, { error: 'batch_workspace_readonly' });
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
try {
|
|
243
|
+
const attachment = await importWorkspaceLibraryAttachment(root, await readLibraryAttachmentUpload(request));
|
|
244
|
+
await state.journal.allocateSourceEvent({
|
|
245
|
+
runtimeId: state.config.runtimeId, generation: state.config.generation, runtimeEpoch: state.runtimeEpoch,
|
|
246
|
+
workspaceId, type: 'attachments.imported', occurredAt: new Date().toISOString(),
|
|
247
|
+
payload: { workspaceId, directoryName, attachmentId: attachment.id },
|
|
248
|
+
});
|
|
249
|
+
writeJson(response, 200, attachment);
|
|
250
|
+
}
|
|
251
|
+
catch (error) {
|
|
252
|
+
const code = error instanceof Error && ['library_asset_too_large', 'library_asset_changed', 'library_attachment_limit'].includes(error.message)
|
|
253
|
+
? error.message : 'invalid_library_attachment';
|
|
254
|
+
writeJson(response, 400, { error: code });
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
const directoryUpload = /^\/runtime\/attachments\/directory(?:\/([^/]+)(?:\/(file|complete))?)?$/.exec(url.pathname);
|
|
260
|
+
if (directoryUpload && ['POST', 'PUT', 'DELETE'].includes(request.method ?? '')) {
|
|
261
|
+
if (writeDestroyed(state, response))
|
|
262
|
+
return;
|
|
263
|
+
const workspaceId = url.searchParams.get('workspaceId') ?? '';
|
|
264
|
+
if (await productionDirectoryBusy(state, workspaceId, directoryName)) {
|
|
265
|
+
writeJson(response, 409, { error: 'batch_workspace_readonly' });
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const root = await workspaceRoot(state, workspaceId, directoryName);
|
|
269
|
+
const [, uploadId, action] = directoryUpload;
|
|
270
|
+
try {
|
|
271
|
+
if (!uploadId && request.method === 'POST')
|
|
272
|
+
writeJson(response, 200, await beginWorkspaceDirectoryAttachment(root, await readAttachmentUpload(request)));
|
|
273
|
+
else if (uploadId && action === 'file' && request.method === 'PUT')
|
|
274
|
+
writeJson(response, 200, await uploadWorkspaceDirectoryFile(root, uploadId, url.searchParams.get('path') ?? '', request));
|
|
275
|
+
else if (uploadId && action === 'complete' && request.method === 'POST') {
|
|
276
|
+
const attachment = await completeWorkspaceDirectoryAttachment(root, uploadId);
|
|
277
|
+
await state.journal.allocateSourceEvent({
|
|
278
|
+
runtimeId: state.config.runtimeId, generation: state.config.generation, runtimeEpoch: state.runtimeEpoch,
|
|
279
|
+
workspaceId, type: 'attachments.imported', occurredAt: new Date().toISOString(),
|
|
280
|
+
payload: { workspaceId, directoryName, attachmentId: attachment.id },
|
|
281
|
+
});
|
|
282
|
+
writeJson(response, 200, attachment);
|
|
283
|
+
}
|
|
284
|
+
else if (uploadId && !action && request.method === 'DELETE')
|
|
285
|
+
writeJson(response, 200, await cancelWorkspaceDirectoryAttachment(root, uploadId));
|
|
286
|
+
else
|
|
287
|
+
writeJson(response, 400, { error: 'invalid_attachment' });
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
writeJson(response, 400, { error: error instanceof Error && error.message === 'video_probe_unavailable' ? 'video_probe_unavailable' : 'invalid_attachment' });
|
|
291
|
+
}
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
if (request.method === 'POST' && url.pathname === '/runtime/attachments/video') {
|
|
295
|
+
if (writeDestroyed(state, response))
|
|
296
|
+
return;
|
|
297
|
+
const workspaceId = url.searchParams.get('workspaceId') ?? '';
|
|
298
|
+
if (await productionDirectoryBusy(state, workspaceId, directoryName)) {
|
|
299
|
+
writeJson(response, 409, { error: 'batch_workspace_readonly' });
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
const root = await workspaceRoot(state, workspaceId, directoryName);
|
|
303
|
+
try {
|
|
304
|
+
writeJson(response, 200, await uploadWorkspaceVideoAttachment(root, request, { name: url.searchParams.get('name') }));
|
|
305
|
+
}
|
|
306
|
+
catch (error) {
|
|
307
|
+
writeJson(response, 400, { error: error instanceof Error && error.message === 'video_probe_unavailable' ? 'video_probe_unavailable' : 'invalid_attachment' });
|
|
308
|
+
}
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
if (request.method === 'POST' && url.pathname === '/runtime/attachments') {
|
|
312
|
+
if (writeDestroyed(state, response))
|
|
313
|
+
return;
|
|
314
|
+
const workspaceId = url.searchParams.get('workspaceId') ?? '';
|
|
315
|
+
if (await productionDirectoryBusy(state, workspaceId, directoryName)) {
|
|
316
|
+
writeJson(response, 409, { error: 'batch_workspace_readonly' });
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
const root = await workspaceRoot(state, workspaceId, directoryName);
|
|
320
|
+
try {
|
|
321
|
+
writeJson(response, 200, await uploadWorkspaceAttachment(root, await readAttachmentUpload(request)));
|
|
322
|
+
}
|
|
323
|
+
catch {
|
|
324
|
+
writeJson(response, 400, { error: 'invalid_attachment' });
|
|
325
|
+
}
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
if (['GET', 'HEAD'].includes(request.method ?? '') && url.pathname === '/runtime/attachment-content') {
|
|
329
|
+
if (writeDestroyed(state, response))
|
|
330
|
+
return;
|
|
331
|
+
const root = await workspaceRoot(state, url.searchParams.get('workspaceId') ?? '', directoryName);
|
|
332
|
+
await serveWorkspaceAttachment(root, url.searchParams.get('attachmentId') ?? '', request, response, url.searchParams.get('filePath') ?? undefined);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (request.method === 'GET' && url.pathname === '/runtime/artifacts') {
|
|
336
|
+
if (writeDestroyed(state, response))
|
|
337
|
+
return;
|
|
338
|
+
const workspaceId = url.searchParams.get('workspaceId');
|
|
339
|
+
if (!workspaceId) {
|
|
340
|
+
writeJson(response, 400, { error: 'invalid_workspace' });
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
await workspaceRoot(state, workspaceId);
|
|
344
|
+
writeJson(response, 200, url.searchParams.get('refresh') === 'false'
|
|
345
|
+
? await new WorkspaceArtifactStore(state.config.stateDir, workspaceId).list()
|
|
346
|
+
: await refreshWorkspaceArtifacts(state, workspaceId));
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (request.method === 'GET' && url.pathname === '/runtime/artifact-content') {
|
|
350
|
+
if (writeDestroyed(state, response))
|
|
351
|
+
return;
|
|
352
|
+
const workspaceId = url.searchParams.get('workspaceId');
|
|
353
|
+
if (!workspaceId) {
|
|
354
|
+
writeJson(response, 400, { error: 'invalid_workspace' });
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
await workspaceRoot(state, workspaceId);
|
|
358
|
+
const parsed = workspaceArtifactContentQuerySchema.safeParse({
|
|
359
|
+
artifactId: url.searchParams.get('artifactId'), versionId: url.searchParams.get('versionId'),
|
|
360
|
+
...(url.searchParams.has('path') ? { path: url.searchParams.get('path') } : {}),
|
|
361
|
+
...(url.searchParams.has('offset') ? { offset: Number(url.searchParams.get('offset')) } : {}),
|
|
362
|
+
...(url.searchParams.has('length') ? { length: Number(url.searchParams.get('length')) } : {}),
|
|
363
|
+
});
|
|
364
|
+
if (!parsed.success) {
|
|
365
|
+
writeJson(response, 400, { error: 'invalid_artifact_query' });
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
try {
|
|
369
|
+
writeJson(response, 200, await new WorkspaceArtifactStore(state.config.stateDir, workspaceId).content(parsed.data));
|
|
370
|
+
}
|
|
371
|
+
catch (error) {
|
|
372
|
+
const reason = error instanceof Error ? error.message : 'artifact_unavailable';
|
|
373
|
+
writeJson(response, reason === 'artifact_not_found' ? 404 : reason === 'artifact_range_invalid' ? 416 : 409, { error: reason });
|
|
374
|
+
}
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
if (['GET', 'POST'].includes(request.method ?? '') && url.pathname === '/runtime/git-bundle') {
|
|
378
|
+
if (writeDestroyed(state, response))
|
|
379
|
+
return;
|
|
380
|
+
await handleWorkspaceTransfer(state, request, response, url);
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
if (['GET', 'HEAD'].includes(request.method ?? '') && url.pathname === '/runtime/archive') {
|
|
384
|
+
if (writeDestroyed(state, response))
|
|
385
|
+
return;
|
|
386
|
+
const root = await sessionWorkspaceRoot(state, url.searchParams.get('workspaceId') ?? undefined, directoryName);
|
|
387
|
+
await serveWorkspaceArchive(root, request, response, { excludedRoots: [state.config.stateDir] });
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
if (request.method === 'GET' && url.pathname === '/runtime/files') {
|
|
391
|
+
if (writeDestroyed(state, response))
|
|
392
|
+
return;
|
|
393
|
+
const workspaceId = url.searchParams.get('workspaceId') ?? undefined;
|
|
394
|
+
const root = await workspaceRoot(state, workspaceId, directoryName);
|
|
395
|
+
const listed = await listWorkspaceFiles(root, state.journal.fileRevisions(revisionScope(state, workspaceId, directoryName)));
|
|
396
|
+
console.log(`[workspace-files] GET /runtime/files workspaceId=${workspaceId ?? '-'} root=${root} files=${listed.files.length}`);
|
|
397
|
+
writeJson(response, 200, listed);
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
if (request.method === 'GET' && url.pathname === '/runtime/files/search') {
|
|
401
|
+
if (writeDestroyed(state, response))
|
|
402
|
+
return;
|
|
403
|
+
if (directoryName === 'root') {
|
|
404
|
+
writeJson(response, 400, { error: 'invalid_workspace_search' });
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
const parsed = workspaceFileSearchQuerySchema.safeParse({
|
|
408
|
+
query: url.searchParams.get('q') ?? '',
|
|
409
|
+
...(url.searchParams.has('limit') ? { limit: Number(url.searchParams.get('limit')) } : {}),
|
|
410
|
+
...(url.searchParams.has('cursor') ? { cursor: url.searchParams.get('cursor') } : {}),
|
|
411
|
+
});
|
|
412
|
+
if (!parsed.success) {
|
|
413
|
+
writeJson(response, 400, { error: 'invalid_workspace_search' });
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
const controller = new AbortController();
|
|
417
|
+
const abort = () => controller.abort();
|
|
418
|
+
const closedRequest = () => { if (request.aborted || !request.complete)
|
|
419
|
+
abort(); };
|
|
420
|
+
request.once('aborted', abort);
|
|
421
|
+
request.once('close', closedRequest);
|
|
422
|
+
response.once('close', abort);
|
|
423
|
+
try {
|
|
424
|
+
const root = await workspaceRoot(state, url.searchParams.get('workspaceId') ?? undefined, directoryName);
|
|
425
|
+
const result = await searchWorkspaceFiles(root, parsed.data, { signal: controller.signal });
|
|
426
|
+
if (!controller.signal.aborted)
|
|
427
|
+
writeJson(response, 200, result);
|
|
428
|
+
}
|
|
429
|
+
catch (error) {
|
|
430
|
+
if (error instanceof Error && error.name === 'AbortError')
|
|
431
|
+
return;
|
|
432
|
+
if (error instanceof Error && ['invalid_workspace_search', 'invalid_workspace_search_cursor'].includes(error.message))
|
|
433
|
+
writeJson(response, 400, { error: error.message });
|
|
434
|
+
else
|
|
435
|
+
throw error;
|
|
436
|
+
}
|
|
437
|
+
finally {
|
|
438
|
+
request.off('aborted', abort);
|
|
439
|
+
request.off('close', closedRequest);
|
|
440
|
+
response.off('close', abort);
|
|
441
|
+
}
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
if (request.method === 'GET' && url.pathname === '/runtime/file') {
|
|
445
|
+
if (writeDestroyed(state, response))
|
|
446
|
+
return;
|
|
447
|
+
const relativePath = url.searchParams.get('path') ?? '';
|
|
448
|
+
try {
|
|
449
|
+
writeJson(response, 200, await readObservedFile(state, url.searchParams.get('workspaceId') ?? undefined, relativePath, directoryName));
|
|
450
|
+
}
|
|
451
|
+
catch (error) {
|
|
452
|
+
if (error instanceof InvalidWorkspacePathError) {
|
|
453
|
+
writeJson(response, 400, { error: 'invalid_workspace_path' });
|
|
454
|
+
return;
|
|
455
|
+
}
|
|
456
|
+
if (error.code === 'ENOENT') {
|
|
457
|
+
writeJson(response, 404, { error: 'file_not_found' });
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
throw error;
|
|
461
|
+
}
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
if (request.method === 'GET' && url.pathname === '/runtime/git/status') {
|
|
465
|
+
await writeGitRead(state, response, async () => readWorkspaceGitStatus(await workspaceRoot(state, url.searchParams.get('workspaceId') ?? undefined, directoryName)));
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
if (request.method === 'GET' && url.pathname === '/runtime/git/diff') {
|
|
469
|
+
await writeGitRead(state, response, async () => readWorkspaceGitDiff(await workspaceRoot(state, url.searchParams.get('workspaceId') ?? undefined, directoryName)));
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
if (request.method === 'GET' && url.pathname === '/runtime/git/file') {
|
|
473
|
+
const ref = gitFileRefSchema.safeParse(url.searchParams.get('ref'));
|
|
474
|
+
if (!ref.success) {
|
|
475
|
+
writeJson(response, 400, { error: 'invalid_git_ref' });
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
await writeGitRead(state, response, async () => readWorkspaceGitFile(await workspaceRoot(state, url.searchParams.get('workspaceId') ?? undefined, directoryName), url.searchParams.get('path') ?? '', ref.data));
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
if (request.method === 'GET' && url.pathname === '/runtime/dependencies') {
|
|
482
|
+
if (writeDestroyed(state, response))
|
|
483
|
+
return;
|
|
484
|
+
const workspaceId = url.searchParams.get('workspaceId') ?? undefined;
|
|
485
|
+
await workspaceRoot(state, workspaceId, directoryName);
|
|
486
|
+
writeJson(response, 200, readDependencies(state, revisionScope(state, workspaceId, directoryName) ?? 'workspace'));
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
if (request.method === 'GET' && url.pathname === '/runtime/remix-references') {
|
|
490
|
+
if (writeDestroyed(state, response))
|
|
491
|
+
return;
|
|
492
|
+
const workspaceId = url.searchParams.get('workspaceId') ?? undefined;
|
|
493
|
+
try {
|
|
494
|
+
const items = await state.journal.exclusive(`workspace:${revisionScope(state, workspaceId, directoryName) ?? 'single'}`, async () => listWorkspaceRemixReferences(await workspaceRoot(state, workspaceId, directoryName), directoryName));
|
|
495
|
+
writeJson(response, 200, { items });
|
|
496
|
+
}
|
|
497
|
+
catch (error) {
|
|
498
|
+
if (error instanceof WorkspaceContextError)
|
|
499
|
+
throw error;
|
|
500
|
+
writeJson(response, 409, { error: error instanceof RemixReferenceError ? error.message : 'remix_reference_unavailable' });
|
|
501
|
+
}
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
if (request.method === 'GET' && url.pathname === '/runtime/skills') {
|
|
505
|
+
if (writeDestroyed(state, response))
|
|
506
|
+
return;
|
|
507
|
+
const workspaceId = url.searchParams.get('workspaceId') ?? undefined;
|
|
508
|
+
try {
|
|
509
|
+
const view = await state.journal.exclusive(`workspace:${revisionScope(state, workspaceId, directoryName) ?? 'single'}`, async () => readWorkspaceSkills(await workspaceRoot(state, workspaceId, directoryName), join(state.config.stateDir, 'skill-artifacts'), entry => loadWorkspaceSkillArtifact(state, workspaceId ?? 'workspace', entry, directoryName)));
|
|
510
|
+
writeJson(response, 200, view);
|
|
511
|
+
}
|
|
512
|
+
catch (error) {
|
|
513
|
+
if (error instanceof WorkspaceContextError)
|
|
514
|
+
throw error;
|
|
515
|
+
writeJson(response, 409, { error: error instanceof Error && error.message.startsWith('workspace_skills_') ? error.message : 'workspace_skills_unavailable' });
|
|
516
|
+
}
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
if (request.method === 'GET' && url.pathname === '/runtime/git/graph') {
|
|
520
|
+
await writeGitRead(state, response, async () => readWorkspaceGitGraph(await workspaceRoot(state, url.searchParams.get('workspaceId') ?? undefined, directoryName)));
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
if (request.method === 'GET' && url.pathname === '/runtime/parameters') {
|
|
524
|
+
if (writeDestroyed(state, response))
|
|
525
|
+
return;
|
|
526
|
+
writeJson(response, 200, await readObservedParameters(state, url.searchParams.get('workspaceId') ?? undefined, directoryName));
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
if (request.method === 'GET' && url.pathname === '/runtime/terminals') {
|
|
530
|
+
if (writeDestroyed(state, response))
|
|
531
|
+
return;
|
|
532
|
+
writeJson(response, 200, {
|
|
533
|
+
terminals: state.journal.listTerminals(url.searchParams.get('workspaceId') ?? undefined).filter(terminal => (terminal.directoryName ?? 'basic') === directoryName),
|
|
534
|
+
});
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
if (url.pathname.startsWith('/runtime/terminals/')) {
|
|
538
|
+
await handleTerminalIdentity(state, request, response, url.pathname.slice('/runtime/terminals/'.length));
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
if (desktopRoute(url.pathname)) {
|
|
542
|
+
await desktopHost(state).handleHttp(request, response, url);
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
if (request.method === 'GET' && url.pathname === '/runtime/operations') {
|
|
546
|
+
const kind = operationKindSchema.safeParse(url.searchParams.get('kind'));
|
|
547
|
+
const clientRequestId = url.searchParams.get('clientRequestId');
|
|
548
|
+
if (!kind.success || !clientRequestId) {
|
|
549
|
+
writeJson(response, 400, { error: 'invalid_operation_lookup' });
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
const operation = state.journal.getOperation(operationScopeKey({
|
|
553
|
+
environment: state.config.environment,
|
|
554
|
+
userId: state.config.userId,
|
|
555
|
+
kind: kind.data,
|
|
556
|
+
clientRequestId,
|
|
557
|
+
workspaceId: url.searchParams.get('workspaceId') ?? undefined,
|
|
558
|
+
directoryName,
|
|
559
|
+
sessionId: url.searchParams.get('sessionId') ?? undefined,
|
|
560
|
+
}));
|
|
561
|
+
writeJson(response, operation ? 200 : 404, operation ?? { error: 'operation_not_found' });
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
if (request.method === 'GET' && url.pathname.startsWith('/runtime/operations/')) {
|
|
565
|
+
const operationId = url.pathname.slice('/runtime/operations/'.length);
|
|
566
|
+
const operation = state.journal.getOperationById(operationId);
|
|
567
|
+
if (!operation) {
|
|
568
|
+
writeJson(response, 404, { error: 'operation_not_found' });
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
writeJson(response, 200, operation);
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
if (request.method === 'POST' && url.pathname === '/runtime/operations') {
|
|
575
|
+
// Track creation before accepting it, so a new unconnected terminal is known not to have spawned.
|
|
576
|
+
terminalHost(state);
|
|
577
|
+
await acceptOperation(state, request, response);
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
writeJson(response, 404, { error: 'not_found' });
|
|
581
|
+
}
|
|
582
|
+
catch (error) {
|
|
583
|
+
if (request.method === 'GET' && ['/runtime/connectivity', '/runtime/files'].includes(url.pathname)) {
|
|
584
|
+
const cause = error instanceof Error && error.cause ? error.cause : error;
|
|
585
|
+
if (['EACCES', 'EPERM'].includes(String(cause?.code))) {
|
|
586
|
+
writeJson(response, 409, { error: 'workspace_permission_denied' });
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
if (url.pathname === '/runtime/connectivity' && error instanceof WorkspaceContextError && error.cause && !['ENOENT', 'ENOTDIR'].includes(String(cause?.code))) {
|
|
590
|
+
writeJson(response, 500, { error: 'workspace_access_failed' });
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
if (error instanceof Error && error.message === 'request_body_too_large') {
|
|
595
|
+
writeJson(response, 413, { error: 'request_body_too_large' });
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
if (error instanceof WorkspaceContextError) {
|
|
599
|
+
writeJson(response, 409, { error: error.message });
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
writeJson(response, 500, {
|
|
603
|
+
error: 'internal_error',
|
|
604
|
+
reason: error instanceof Error ? error.message : 'unknown',
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
function handshake(state) {
|
|
609
|
+
const destroyed = state.journal.destroyed();
|
|
610
|
+
const conversationReady = Boolean(state.native?.ready()) && !destroyed;
|
|
611
|
+
const filesReady = !destroyed;
|
|
612
|
+
const gitReady = state.gitAvailable && !destroyed;
|
|
613
|
+
const capabilities = unavailableRuntimeCapabilities('adapter_not_started').map((item) => {
|
|
614
|
+
if (item.name === 'conversation') {
|
|
615
|
+
if (conversationReady)
|
|
616
|
+
return capability('conversation', true);
|
|
617
|
+
return capability('conversation', false, destroyed ? 'runtime_destroyed' : state.nativeError ?? 'adapter_not_started');
|
|
618
|
+
}
|
|
619
|
+
if (item.name === 'files') {
|
|
620
|
+
return filesReady
|
|
621
|
+
? capability('files', true)
|
|
622
|
+
: capability('files', false, 'runtime_destroyed');
|
|
623
|
+
}
|
|
624
|
+
if (item.name === 'git') {
|
|
625
|
+
if (gitReady)
|
|
626
|
+
return capability('git', true);
|
|
627
|
+
if (destroyed)
|
|
628
|
+
return capability('git', false, 'runtime_destroyed');
|
|
629
|
+
if (!state.gitAvailable)
|
|
630
|
+
return capability('git', false, 'git_binary_missing');
|
|
631
|
+
return item;
|
|
632
|
+
}
|
|
633
|
+
if (item.name === 'terminal') {
|
|
634
|
+
return destroyed
|
|
635
|
+
? capability('terminal', false, 'runtime_destroyed')
|
|
636
|
+
: capability('terminal', true);
|
|
637
|
+
}
|
|
638
|
+
if (item.name === 'desktop') {
|
|
639
|
+
if (destroyed)
|
|
640
|
+
return capability('desktop', false, 'runtime_destroyed');
|
|
641
|
+
const status = desktopHost(state).snapshot().status;
|
|
642
|
+
return status === 'ready' ? capability('desktop', true) : capability('desktop', false, status);
|
|
643
|
+
}
|
|
644
|
+
if (item.name === 'parameters') {
|
|
645
|
+
return destroyed
|
|
646
|
+
? capability('parameters', false, 'runtime_destroyed')
|
|
647
|
+
: capability('parameters', true);
|
|
648
|
+
}
|
|
649
|
+
if (item.name === 'artifacts.singleFile') {
|
|
650
|
+
return destroyed
|
|
651
|
+
? capability('artifacts.singleFile', false, 'runtime_destroyed')
|
|
652
|
+
: capability('artifacts.singleFile', true);
|
|
653
|
+
}
|
|
654
|
+
return item;
|
|
655
|
+
});
|
|
656
|
+
return buildHandshakeDocument({
|
|
657
|
+
protocolMajor: state.config.protocolMajor,
|
|
658
|
+
protocolMinor: state.config.protocolMinor,
|
|
659
|
+
cliVersion: state.config.cliVersion,
|
|
660
|
+
codexVersion: state.config.codexVersion,
|
|
661
|
+
imageDigest: state.config.imageDigest,
|
|
662
|
+
phase: destroyed ? 'unavailable' : conversationReady ? 'ready' : 'awaiting_native',
|
|
663
|
+
generations: {
|
|
664
|
+
generation: state.config.generation,
|
|
665
|
+
runtimeEpoch: state.runtimeEpoch,
|
|
666
|
+
leaseFence: state.acceptedLeaseFence,
|
|
667
|
+
},
|
|
668
|
+
capabilities,
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
async function acceptOperation(state, request, response) {
|
|
672
|
+
const body = await readJson(request, WORKSPACE_REMIX_REFERENCE_BODY_MAX_BYTES);
|
|
673
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
674
|
+
writeJson(response, 400, { error: 'invalid_operation' });
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
// leaseFence 由 Runtime Server 派发,本控制面单独校验;其余代次/身份/根目录字段仍只来自引导配置。
|
|
678
|
+
const untrusted = findUntrustedRuntimeFields(body).filter((field) => field !== 'leaseFence');
|
|
679
|
+
if (untrusted.length > 0) {
|
|
680
|
+
writeError(response, runtimeError('untrusted_runtime_field', untrusted.join(',')));
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
const incomingFence = Number(body.leaseFence ?? state.acceptedLeaseFence);
|
|
684
|
+
if (!Number.isInteger(incomingFence) || incomingFence < 0) {
|
|
685
|
+
writeJson(response, 400, { error: 'invalid_lease_fence' });
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
if (assertLeaseFence(incomingFence, state.acceptedLeaseFence) !== 'ok') {
|
|
689
|
+
writeError(response, runtimeError('stale_lease', 'leaseFence is behind the accepted dispatcher'));
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
const { leaseFence: _leaseFence, ...requestBody } = body;
|
|
693
|
+
const parsed = operationAcceptRequestSchema.safeParse(requestBody);
|
|
694
|
+
if (!parsed.success) {
|
|
695
|
+
writeJson(response, 400, { error: 'invalid_operation', issues: parsed.error.issues });
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
if (parsed.data.kind === 'workspace.references.import') {
|
|
699
|
+
const source = workspaceRemixReferenceImportRequestSchema.safeParse(parsed.data.payload);
|
|
700
|
+
const snapshot = parsed.data.remixReferenceSnapshot;
|
|
701
|
+
if (!source.success || (snapshot && (snapshot.source.projectUuid !== source.data.source.projectUuid ||
|
|
702
|
+
snapshot.source.branchName !== source.data.source.branchName || snapshot.source.environment !== state.config.environment))) {
|
|
703
|
+
writeJson(response, 400, { error: 'invalid_remix_reference' });
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
if (parsed.data.kind.startsWith('session.') && !parsed.data.sessionId) {
|
|
708
|
+
writeJson(response, 400, { error: 'invalid_operation', reason: 'sessionId_required' });
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
if (parsed.data.directoryName === 'root' && !parsed.data.kind.startsWith('session.') && !['runtime.ensure', 'terminal.create'].includes(parsed.data.kind)) {
|
|
712
|
+
writeJson(response, 400, { error: 'invalid_workspace_directory' });
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
if (state.config.workspaceMode === 'multi' && parsed.data.kind === 'runtime.ensure' && parsed.data.workspaceId)
|
|
716
|
+
await restoreWorkspaceDirectory(state, parsed.data.workspaceId, parsed.data.directoryName);
|
|
717
|
+
if (state.config.workspaceMode === 'multi')
|
|
718
|
+
await sessionWorkspaceRoot(state, parsed.data.workspaceId, parsed.data.directoryName);
|
|
719
|
+
const mutation = isWorkspaceMutation(parsed.data.kind);
|
|
720
|
+
const occupiesDirectory = mutation || parsed.data.kind === 'session.compact';
|
|
721
|
+
if (occupiesDirectory && await productionDirectoryBusy(state, parsed.data.workspaceId, parsed.data.directoryName)) {
|
|
722
|
+
writeJson(response, 409, { error: 'batch_workspace_readonly' });
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
const payloadHash = hashOperationPayload(parsed.data.payload);
|
|
726
|
+
const scopeKey = operationScopeKey({
|
|
727
|
+
environment: state.config.environment,
|
|
728
|
+
userId: state.config.userId,
|
|
729
|
+
kind: parsed.data.kind,
|
|
730
|
+
clientRequestId: parsed.data.clientRequestId,
|
|
731
|
+
workspaceId: parsed.data.workspaceId,
|
|
732
|
+
directoryName: parsed.data.directoryName,
|
|
733
|
+
sessionId: parsed.data.sessionId,
|
|
734
|
+
});
|
|
735
|
+
const accept = () => state.journal.exclusive(scopeKey, async () => {
|
|
736
|
+
// Recheck after a concurrent dispatcher may have advanced the fence while this request waited.
|
|
737
|
+
if (assertLeaseFence(incomingFence, state.acceptedLeaseFence) !== 'ok') {
|
|
738
|
+
writeError(response, runtimeError('stale_lease', 'leaseFence is behind the accepted dispatcher'));
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
const existing = state.journal.getOperation(scopeKey);
|
|
742
|
+
const decision = resolveIdempotentAccept(existing, payloadHash);
|
|
743
|
+
if (decision.action === 'conflict') {
|
|
744
|
+
writeError(response, runtimeError('idempotency_conflict', 'clientRequestId reused with a different payload', {
|
|
745
|
+
operationId: decision.operation.operationId,
|
|
746
|
+
}));
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
// A turn refused for a lost thread never reached Codex. Sent again with the conversation, it
|
|
750
|
+
// runs afresh under the same request, so the message is shown and answered only once.
|
|
751
|
+
const retryWithRecovery = decision.action === 'reuse' && parsed.data.kind === 'session.turn'
|
|
752
|
+
&& Boolean(parsed.data.sessionRecovery) && decision.operation.status === 'failed'
|
|
753
|
+
&& isLostThreadError(decision.operation.error);
|
|
754
|
+
if (decision.action === 'reuse' && !retryWithRecovery) {
|
|
755
|
+
if (decision.operation.status === 'uncertain') {
|
|
756
|
+
writeError(response, runtimeError('uncertain_operation', decision.operation.error ?? 'native_receipt_lost', {
|
|
757
|
+
operationId: decision.operation.operationId,
|
|
758
|
+
}));
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
writeJson(response, 200, decision.operation);
|
|
762
|
+
return;
|
|
763
|
+
}
|
|
764
|
+
if (parsed.data.kind.startsWith('session.') && parsed.data.sessionId && productionSessionAttemptId(parsed.data.sessionId)) {
|
|
765
|
+
writeError(response, runtimeError('capability_unavailable', 'production_session_readonly'));
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
if (parsed.data.kind === 'session.create') {
|
|
769
|
+
const creation = state.journal.findSessionCreation(parsed.data.sessionId);
|
|
770
|
+
const session = state.journal.getSession(parsed.data.sessionId);
|
|
771
|
+
if (creation || session) {
|
|
772
|
+
writeJson(response, 409, { error: 'session_already_bound' });
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
else if (parsed.data.kind === 'terminal.create') {
|
|
777
|
+
const payload = asRecord(parsed.data.payload);
|
|
778
|
+
const terminalId = typeof payload.terminalId === 'string' ? payload.terminalId.trim() : '';
|
|
779
|
+
if (!terminalId) {
|
|
780
|
+
writeJson(response, 400, { error: 'invalid_operation', reason: 'terminalId_required' });
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
const creation = state.journal.findTerminalCreation(terminalId);
|
|
784
|
+
const terminal = state.journal.getTerminal(terminalId);
|
|
785
|
+
if (creation && operationScopeKey(creation) !== scopeKey) {
|
|
786
|
+
writeJson(response, 409, { error: 'terminal_already_bound' });
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
if (terminal && !creation) {
|
|
790
|
+
writeJson(response, 409, { error: 'terminal_already_bound' });
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
else if (parsed.data.kind.startsWith('session.') && state.config.workspaceMode === 'multi') {
|
|
795
|
+
const session = state.journal.getSession(parsed.data.sessionId);
|
|
796
|
+
// A replaced sandbox has no binding yet; the recovering turn creates it.
|
|
797
|
+
const rebinding = !session && parsed.data.kind === 'session.turn' && parsed.data.sessionRecovery;
|
|
798
|
+
if (!rebinding && (!session || session.workspaceId !== parsed.data.workspaceId
|
|
799
|
+
|| (session.directoryName ?? 'basic') !== (parsed.data.directoryName ?? 'basic'))) {
|
|
800
|
+
writeJson(response, 409, { error: 'session_workspace_mismatch' });
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
if (parsed.data.kind === 'workspace.references.import' && !parsed.data.remixReferenceSnapshot) {
|
|
805
|
+
writeJson(response, 400, { error: 'remix_reference_snapshot_required' });
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
const now = new Date().toISOString();
|
|
809
|
+
const executable = canExecuteKind(state, parsed.data.kind);
|
|
810
|
+
const payloadRecord = asRecord(parsed.data.payload);
|
|
811
|
+
const operation = {
|
|
812
|
+
operationId: randomUUID(),
|
|
813
|
+
environment: state.config.environment,
|
|
814
|
+
userId: state.config.userId,
|
|
815
|
+
clientRequestId: parsed.data.clientRequestId,
|
|
816
|
+
kind: parsed.data.kind,
|
|
817
|
+
status: executable ? 'queued' : 'failed',
|
|
818
|
+
payloadHash,
|
|
819
|
+
workspaceId: parsed.data.workspaceId,
|
|
820
|
+
directoryName: parsed.data.directoryName,
|
|
821
|
+
sessionId: parsed.data.sessionId,
|
|
822
|
+
expectedRevision: parsed.data.expectedRevision,
|
|
823
|
+
generation: state.config.generation,
|
|
824
|
+
runtimeEpoch: state.runtimeEpoch,
|
|
825
|
+
leaseFence: incomingFence,
|
|
826
|
+
terminalId: parsed.data.kind === 'terminal.create' && typeof payloadRecord.terminalId === 'string'
|
|
827
|
+
? payloadRecord.terminalId.trim()
|
|
828
|
+
: undefined,
|
|
829
|
+
cwd: parsed.data.kind === 'terminal.create' && typeof payloadRecord.cwd === 'string'
|
|
830
|
+
? payloadRecord.cwd
|
|
831
|
+
: undefined,
|
|
832
|
+
error: executable ? undefined : 'capability_unavailable',
|
|
833
|
+
createdAt: now,
|
|
834
|
+
updatedAt: now,
|
|
835
|
+
};
|
|
836
|
+
if (!executable) {
|
|
837
|
+
const saved = await state.journal.putOperation(scopeKey, operation);
|
|
838
|
+
writeError(response, runtimeError('capability_unavailable', unavailableReason(state, parsed.data.kind), {
|
|
839
|
+
operationId: saved.operationId,
|
|
840
|
+
}));
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
state.acceptedLeaseFence = Math.max(state.acceptedLeaseFence, incomingFence);
|
|
844
|
+
await state.journal.setAcceptedLeaseFence(state.acceptedLeaseFence);
|
|
845
|
+
const queued = await state.journal.putOperation(scopeKey, operation);
|
|
846
|
+
const executionPayload = parsed.data.kind === 'workspace.references.import'
|
|
847
|
+
? { snapshot: parsed.data.remixReferenceSnapshot } : parsed.data.payload;
|
|
848
|
+
const executed = await executeOperation(state, scopeKey, queued, executionPayload, parsed.data.sessionRecovery);
|
|
849
|
+
if (executed.status === 'uncertain') {
|
|
850
|
+
writeError(response, runtimeError('uncertain_operation', executed.error ?? 'native_receipt_lost', {
|
|
851
|
+
operationId: executed.operationId,
|
|
852
|
+
}));
|
|
853
|
+
return;
|
|
854
|
+
}
|
|
855
|
+
writeJson(response, executed.status === 'failed' ? 409 : 202, executed);
|
|
856
|
+
});
|
|
857
|
+
const acceptBound = async () => {
|
|
858
|
+
if (occupiesDirectory && await productionDirectoryBusy(state, parsed.data.workspaceId, parsed.data.directoryName)) {
|
|
859
|
+
writeJson(response, 409, { error: 'batch_workspace_readonly' });
|
|
860
|
+
return;
|
|
861
|
+
}
|
|
862
|
+
if (state.config.workspaceMode === 'multi')
|
|
863
|
+
await sessionWorkspaceRoot(state, parsed.data.workspaceId, parsed.data.directoryName);
|
|
864
|
+
if (parsed.data.kind === 'session.create')
|
|
865
|
+
await state.journal.exclusive(`session:${parsed.data.sessionId}`, accept);
|
|
866
|
+
else if (parsed.data.kind === 'terminal.create') {
|
|
867
|
+
const terminalId = typeof asRecord(parsed.data.payload).terminalId === 'string'
|
|
868
|
+
? String(asRecord(parsed.data.payload).terminalId).trim()
|
|
869
|
+
: '';
|
|
870
|
+
if (terminalId)
|
|
871
|
+
await state.journal.exclusive(`terminal:${terminalId}`, accept);
|
|
872
|
+
else
|
|
873
|
+
await accept();
|
|
874
|
+
}
|
|
875
|
+
else
|
|
876
|
+
await accept();
|
|
877
|
+
};
|
|
878
|
+
// Production admission and maintenance use this same lock before checking durable occupancy.
|
|
879
|
+
if (occupiesDirectory && state.config.workspaceMode === 'multi')
|
|
880
|
+
await state.journal.exclusive(`directory:${parsed.data.workspaceId}:${parsed.data.directoryName ?? 'basic'}`, acceptBound);
|
|
881
|
+
else
|
|
882
|
+
await acceptBound();
|
|
883
|
+
}
|
|
884
|
+
async function writeGitRead(state, response, read) {
|
|
885
|
+
if (writeDestroyed(state, response))
|
|
886
|
+
return;
|
|
887
|
+
if (!state.gitAvailable) {
|
|
888
|
+
writeError(response, runtimeError('capability_unavailable', 'git_binary_missing'));
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
try {
|
|
892
|
+
writeJson(response, 200, await read());
|
|
893
|
+
}
|
|
894
|
+
catch (error) {
|
|
895
|
+
if (error instanceof GitWorkspaceError && error.code === 'invalid_workspace_path') {
|
|
896
|
+
writeJson(response, 400, { error: 'invalid_workspace_path' });
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
const reason = error instanceof GitWorkspaceError ? error.code : 'git_command_failed';
|
|
900
|
+
writeError(response, runtimeError('capability_unavailable', reason));
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
async function readJson(request, maxBytes = Infinity) {
|
|
904
|
+
const chunks = [];
|
|
905
|
+
let size = 0;
|
|
906
|
+
for await (const chunk of request) {
|
|
907
|
+
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
908
|
+
size += bytes.length;
|
|
909
|
+
if (size > maxBytes)
|
|
910
|
+
throw new Error('request_body_too_large');
|
|
911
|
+
chunks.push(bytes);
|
|
912
|
+
}
|
|
913
|
+
if (chunks.length === 0)
|
|
914
|
+
return {};
|
|
915
|
+
try {
|
|
916
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
917
|
+
}
|
|
918
|
+
catch {
|
|
919
|
+
return null;
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
function writeDestroyed(state, response) {
|
|
923
|
+
if (!state.journal.destroyed())
|
|
924
|
+
return false;
|
|
925
|
+
writeError(response, runtimeError('capability_unavailable', 'runtime_destroyed'));
|
|
926
|
+
return true;
|
|
927
|
+
}
|
|
928
|
+
async function handleTerminalIdentity(state, request, response, remainder) {
|
|
929
|
+
if (writeDestroyed(state, response))
|
|
930
|
+
return;
|
|
931
|
+
const [terminalId, action] = remainder.split('/');
|
|
932
|
+
if (!terminalId || action && action !== 'connect') {
|
|
933
|
+
writeJson(response, 404, { error: 'not_found' });
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
936
|
+
const terminal = state.journal.getTerminal(terminalId);
|
|
937
|
+
if (!terminal) {
|
|
938
|
+
writeJson(response, 404, { error: 'terminal_not_found' });
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
if (request.method === 'GET' && action === 'connect') {
|
|
942
|
+
if (terminal.status === 'destroyed') {
|
|
943
|
+
writeError(response, runtimeError('capability_unavailable', 'terminal_destroyed'));
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
writeError(response, runtimeError('capability_unavailable', 'websocket_required'));
|
|
947
|
+
return;
|
|
948
|
+
}
|
|
949
|
+
if (request.method === 'GET' && !action) {
|
|
950
|
+
writeJson(response, 200, terminal);
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
if (request.method === 'DELETE' && !action) {
|
|
954
|
+
try {
|
|
955
|
+
const destroyed = await terminalHost(state).destroy(terminalId);
|
|
956
|
+
writeJson(response, 200, { terminalId: destroyed.terminalId, status: destroyed.status });
|
|
957
|
+
}
|
|
958
|
+
catch {
|
|
959
|
+
writeError(response, runtimeError('capability_unavailable', 'terminal_stop_unconfirmed'));
|
|
960
|
+
}
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
writeJson(response, 404, { error: 'not_found' });
|
|
964
|
+
}
|
|
965
|
+
function unavailableReason(state, kind) {
|
|
966
|
+
if (state.journal.destroyed())
|
|
967
|
+
return 'runtime_destroyed';
|
|
968
|
+
return state.nativeError ?? 'adapter_not_started';
|
|
969
|
+
}
|
|
970
|
+
function sessionHistoryPath(pathname) {
|
|
971
|
+
const match = pathname.match(/^\/runtime\/workspaces\/([^/]+)\/sessions\/([^/]+)\/history$/);
|
|
972
|
+
if (!match?.[1] || !match[2])
|
|
973
|
+
return undefined;
|
|
974
|
+
try {
|
|
975
|
+
return {
|
|
976
|
+
workspaceId: decodeURIComponent(match[1]),
|
|
977
|
+
sessionId: decodeURIComponent(match[2]),
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
catch {
|
|
981
|
+
return undefined;
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
function isUnimplementedWorkbenchPath(pathname) {
|
|
985
|
+
const parts = pathname.split('/').filter(Boolean);
|
|
986
|
+
return parts[0] === 'runtime' && parts.includes('previews');
|
|
987
|
+
}
|
|
988
|
+
async function handleSessionHistory(state, response, workspaceId, sessionId) {
|
|
989
|
+
if (writeDestroyed(state, response))
|
|
990
|
+
return;
|
|
991
|
+
const session = state.journal.getSession(sessionId);
|
|
992
|
+
if (!session || (session.workspaceId && session.workspaceId !== workspaceId)) {
|
|
993
|
+
writeJson(response, 404, { error: 'session_not_found' });
|
|
994
|
+
return;
|
|
995
|
+
}
|
|
996
|
+
if (state.config.workspaceMode === 'multi' && session.workspaceId !== workspaceId) {
|
|
997
|
+
writeJson(response, 404, { error: 'session_not_found' });
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
const readThread = state.native?.readThread;
|
|
1001
|
+
if (!readThread) {
|
|
1002
|
+
writeError(response, runtimeError('capability_unavailable', 'native_history_unavailable'));
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
let read;
|
|
1006
|
+
try {
|
|
1007
|
+
read = await readThread({ threadId: session.threadId, sessionId });
|
|
1008
|
+
}
|
|
1009
|
+
catch {
|
|
1010
|
+
writeError(response, runtimeError('capability_unavailable', 'native_history_unavailable'));
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
if (!read || read.threadId !== session.threadId) {
|
|
1014
|
+
writeError(response, runtimeError('capability_unavailable', 'native_history_unavailable'));
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
const body = nativeHistoryReadSchema.safeParse({
|
|
1018
|
+
source: 'native',
|
|
1019
|
+
sessionId,
|
|
1020
|
+
workspaceId,
|
|
1021
|
+
threadId: read.threadId,
|
|
1022
|
+
...(read.threadName ? { threadName: read.threadName } : {}),
|
|
1023
|
+
truncated: read.truncated,
|
|
1024
|
+
items: read.items,
|
|
1025
|
+
});
|
|
1026
|
+
if (!body.success) {
|
|
1027
|
+
writeError(response, runtimeError('capability_unavailable', 'native_history_unavailable'));
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
1030
|
+
writeJson(response, 200, body.data);
|
|
1031
|
+
}
|
|
1032
|
+
async function readObservedParameters(state, workspaceId, directoryName = 'basic') {
|
|
1033
|
+
const root = await workspaceRoot(state, workspaceId, directoryName);
|
|
1034
|
+
const scope = revisionScope(state, workspaceId, directoryName);
|
|
1035
|
+
const first = await readWorkspaceParameters(root, state.journal.fileRevisions(scope));
|
|
1036
|
+
for (const path of [first.schemaPath, first.dataPath]) {
|
|
1037
|
+
if (path)
|
|
1038
|
+
await withObservedFile(state, workspaceId, path, async () => undefined, directoryName);
|
|
1039
|
+
}
|
|
1040
|
+
return readWorkspaceParameters(root, state.journal.fileRevisions(scope));
|
|
1041
|
+
}
|
|
1042
|
+
function writeError(response, error) {
|
|
1043
|
+
writeJson(response, HTTP_STATUS_BY_ERROR[error.code], error);
|
|
1044
|
+
}
|
|
1045
|
+
function writeJson(response, status, body) {
|
|
1046
|
+
const payload = JSON.stringify(body);
|
|
1047
|
+
response.writeHead(status, {
|
|
1048
|
+
'content-type': 'application/json; charset=utf-8',
|
|
1049
|
+
'content-length': Buffer.byteLength(payload),
|
|
1050
|
+
});
|
|
1051
|
+
response.end(payload);
|
|
1052
|
+
}
|
|
1053
|
+
function authorizeRuntime(state, request) {
|
|
1054
|
+
const presented = extractControlToken(request.headers);
|
|
1055
|
+
if (controlTokenMatches(state.config.controlToken, presented))
|
|
1056
|
+
return 'control';
|
|
1057
|
+
const dedicated = headerValue(request.headers['x-playcraft-source-read-token']);
|
|
1058
|
+
const candidate = dedicated || presented;
|
|
1059
|
+
if (candidate && controlTokenMatches(state.journal.sourceReadToken(), candidate))
|
|
1060
|
+
return 'read';
|
|
1061
|
+
return null;
|
|
1062
|
+
}
|
|
1063
|
+
function readSourcePath(method, pathname) {
|
|
1064
|
+
if (method === 'GET' && pathname === '/runtime/events')
|
|
1065
|
+
return true;
|
|
1066
|
+
if (method === 'POST' && pathname === '/runtime/events/replay-pins')
|
|
1067
|
+
return true;
|
|
1068
|
+
if (method === 'DELETE' && pathname.startsWith('/runtime/events/replay-pins/'))
|
|
1069
|
+
return true;
|
|
1070
|
+
return false;
|
|
1071
|
+
}
|
|
1072
|
+
async function handleSourceEvents(state, request, response, url) {
|
|
1073
|
+
if (request.method === 'POST' && url.pathname === '/runtime/events/replay-pins') {
|
|
1074
|
+
const pin = await state.journal.createReplayPin({
|
|
1075
|
+
runtimeId: state.config.runtimeId,
|
|
1076
|
+
generation: state.config.generation,
|
|
1077
|
+
runtimeEpoch: state.runtimeEpoch,
|
|
1078
|
+
ttlMs: Number(asRecord(await readJson(request)).ttlMs) || undefined,
|
|
1079
|
+
});
|
|
1080
|
+
writeJson(response, 201, pin);
|
|
1081
|
+
return;
|
|
1082
|
+
}
|
|
1083
|
+
if (request.method === 'DELETE' && url.pathname.startsWith('/runtime/events/replay-pins/')) {
|
|
1084
|
+
await state.journal.deleteReplayPin(decodeURIComponent(url.pathname.slice('/runtime/events/replay-pins/'.length)));
|
|
1085
|
+
writeJson(response, 200, { deleted: true });
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
if (request.method === 'POST' && url.pathname === '/runtime/events/ack') {
|
|
1089
|
+
const parsed = sourceAckSchema.safeParse(await readJson(request));
|
|
1090
|
+
if (!parsed.success) {
|
|
1091
|
+
writeJson(response, 400, { error: 'invalid_source_ack' });
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
try {
|
|
1095
|
+
await state.journal.acknowledgeSource(parsed.data);
|
|
1096
|
+
state.acceptedLeaseFence = Math.max(state.acceptedLeaseFence, state.journal.acceptedLeaseFence());
|
|
1097
|
+
wakeSourceEventUploader(state);
|
|
1098
|
+
}
|
|
1099
|
+
catch (error) {
|
|
1100
|
+
writeJson(response, 409, { code: error instanceof Error ? error.message : 'ack_rejected' });
|
|
1101
|
+
return;
|
|
1102
|
+
}
|
|
1103
|
+
writeJson(response, 200, { ok: true, acceptedLeaseFence: state.journal.acceptedLeaseFence() });
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
1106
|
+
if (request.method === 'GET' && url.pathname === '/runtime/events') {
|
|
1107
|
+
const after = Number(url.searchParams.get('after') ?? '0');
|
|
1108
|
+
const safeAfter = Number.isInteger(after) && after >= 0 ? after : 0;
|
|
1109
|
+
const epochQuery = url.searchParams.get('runtimeEpoch');
|
|
1110
|
+
const runtimeEpoch = epochQuery === null ? state.runtimeEpoch : Number(epochQuery);
|
|
1111
|
+
const runtimeId = url.searchParams.get('runtimeId') ?? state.config.runtimeId;
|
|
1112
|
+
const generation = Number(url.searchParams.get('generation') ?? state.config.generation);
|
|
1113
|
+
if (runtimeId !== state.config.runtimeId || generation !== state.config.generation || !Number.isInteger(runtimeEpoch) || runtimeEpoch < 0) {
|
|
1114
|
+
writeJson(response, 403, { error: 'source_identity_mismatch' });
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
const query = {
|
|
1118
|
+
runtimeId,
|
|
1119
|
+
generation,
|
|
1120
|
+
runtimeEpoch,
|
|
1121
|
+
after: safeAfter,
|
|
1122
|
+
};
|
|
1123
|
+
if (!state.journal.epochsSnapshot().some(epoch => epoch.runtime_id === runtimeId && epoch.generation === generation && epoch.runtime_epoch === runtimeEpoch)) {
|
|
1124
|
+
writeJson(response, 409, { code: 'source_gap', retainedFrom: 1, highWater: 0, coveredThrough: safeAfter });
|
|
1125
|
+
return;
|
|
1126
|
+
}
|
|
1127
|
+
if (String(request.headers.accept ?? '').includes('text/event-stream')) {
|
|
1128
|
+
writeSourceStream(state, request, response, query);
|
|
1129
|
+
return;
|
|
1130
|
+
}
|
|
1131
|
+
if (epochQuery === null && !url.searchParams.has('runtimeId') && !url.searchParams.has('generation')) {
|
|
1132
|
+
const events = state.journal.listEvents(safeAfter);
|
|
1133
|
+
const page = state.journal.readSourcePage({ ...query, limit: 1 });
|
|
1134
|
+
writeJson(response, 200, {
|
|
1135
|
+
events,
|
|
1136
|
+
retainedFrom: page.ok ? page.retainedFrom : page.retainedFrom,
|
|
1137
|
+
highWater: page.ok ? page.highWater : page.highWater,
|
|
1138
|
+
nextAfter: events.at(-1)?.source.sourceSequence ?? safeAfter,
|
|
1139
|
+
runtimeId: query.runtimeId,
|
|
1140
|
+
generation: query.generation,
|
|
1141
|
+
runtimeEpoch: query.runtimeEpoch,
|
|
1142
|
+
});
|
|
1143
|
+
return;
|
|
1144
|
+
}
|
|
1145
|
+
const page = state.journal.readSourcePage(query);
|
|
1146
|
+
if (!page.ok) {
|
|
1147
|
+
writeJson(response, 409, {
|
|
1148
|
+
code: page.code,
|
|
1149
|
+
retainedFrom: page.retainedFrom,
|
|
1150
|
+
highWater: page.highWater,
|
|
1151
|
+
coveredThrough: page.coveredThrough,
|
|
1152
|
+
});
|
|
1153
|
+
return;
|
|
1154
|
+
}
|
|
1155
|
+
writeJson(response, 200, {
|
|
1156
|
+
events: page.events,
|
|
1157
|
+
retainedFrom: page.retainedFrom,
|
|
1158
|
+
highWater: page.highWater,
|
|
1159
|
+
nextAfter: page.nextAfter,
|
|
1160
|
+
runtimeId: page.runtimeId,
|
|
1161
|
+
generation: page.generation,
|
|
1162
|
+
runtimeEpoch: page.runtimeEpoch,
|
|
1163
|
+
});
|
|
1164
|
+
return;
|
|
1165
|
+
}
|
|
1166
|
+
writeJson(response, 404, { error: 'not_found' });
|
|
1167
|
+
}
|
|
1168
|
+
function writeSourceStream(state, request, response, query) {
|
|
1169
|
+
let cursor = query.after;
|
|
1170
|
+
const buffered = [];
|
|
1171
|
+
const matches = (event) => event.source.runtimeId === query.runtimeId &&
|
|
1172
|
+
event.source.generation === query.generation &&
|
|
1173
|
+
event.source.runtimeEpoch === query.runtimeEpoch &&
|
|
1174
|
+
event.source.sourceSequence > cursor;
|
|
1175
|
+
const unsubscribe = state.journal.onSourceEvent((event) => {
|
|
1176
|
+
if (matches(event))
|
|
1177
|
+
buffered.push(event);
|
|
1178
|
+
});
|
|
1179
|
+
const page = state.journal.readSourcePage({ ...query, limit: 500 });
|
|
1180
|
+
response.writeHead(200, {
|
|
1181
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
1182
|
+
'cache-control': 'no-cache, no-transform',
|
|
1183
|
+
connection: 'keep-alive',
|
|
1184
|
+
'x-accel-buffering': 'no',
|
|
1185
|
+
});
|
|
1186
|
+
const writeEvent = (name, data) => {
|
|
1187
|
+
response.write(`event: ${name}\ndata: ${JSON.stringify(data)}\n\n`);
|
|
1188
|
+
};
|
|
1189
|
+
if (!page.ok) {
|
|
1190
|
+
writeEvent('source.gap', {
|
|
1191
|
+
code: page.code,
|
|
1192
|
+
retainedFrom: page.retainedFrom,
|
|
1193
|
+
highWater: page.highWater,
|
|
1194
|
+
coveredThrough: page.coveredThrough,
|
|
1195
|
+
});
|
|
1196
|
+
response.end();
|
|
1197
|
+
unsubscribe();
|
|
1198
|
+
return;
|
|
1199
|
+
}
|
|
1200
|
+
writeEvent('source.ready', {
|
|
1201
|
+
runtimeId: page.runtimeId,
|
|
1202
|
+
generation: page.generation,
|
|
1203
|
+
runtimeEpoch: page.runtimeEpoch,
|
|
1204
|
+
retainedFrom: page.retainedFrom,
|
|
1205
|
+
highWater: page.highWater,
|
|
1206
|
+
nextAfter: page.nextAfter,
|
|
1207
|
+
});
|
|
1208
|
+
for (const event of page.events) {
|
|
1209
|
+
writeEvent('source', event);
|
|
1210
|
+
cursor = event.source.sourceSequence;
|
|
1211
|
+
}
|
|
1212
|
+
for (const event of buffered) {
|
|
1213
|
+
if (!matches(event))
|
|
1214
|
+
continue;
|
|
1215
|
+
writeEvent('source', event);
|
|
1216
|
+
cursor = event.source.sourceSequence;
|
|
1217
|
+
}
|
|
1218
|
+
unsubscribe();
|
|
1219
|
+
const follow = state.journal.onSourceEvent((event) => {
|
|
1220
|
+
if (!matches(event))
|
|
1221
|
+
return;
|
|
1222
|
+
writeEvent('source', event);
|
|
1223
|
+
cursor = event.source.sourceSequence;
|
|
1224
|
+
});
|
|
1225
|
+
const heartbeat = setInterval(() => {
|
|
1226
|
+
response.write(`: ping\n\n`);
|
|
1227
|
+
}, 10_000);
|
|
1228
|
+
heartbeat.unref?.();
|
|
1229
|
+
const stop = () => {
|
|
1230
|
+
clearInterval(heartbeat);
|
|
1231
|
+
follow();
|
|
1232
|
+
};
|
|
1233
|
+
request.on('close', stop);
|
|
1234
|
+
response.on('close', stop);
|
|
1235
|
+
}
|
|
1236
|
+
function headerValue(value) {
|
|
1237
|
+
return Array.isArray(value) ? value[0] : value;
|
|
1238
|
+
}
|
|
1239
|
+
function asRecord(value) {
|
|
1240
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
1241
|
+
? value
|
|
1242
|
+
: {};
|
|
1243
|
+
}
|