wave3d-agent-sdk 0.2.8 → 0.2.9

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 CHANGED
@@ -21,19 +21,19 @@ Vocabulary:
21
21
  - Project: user workspace content. Reading a project is not opening/replacing live workspace.
22
22
 
23
23
  ```bash
24
- npx -y wave3d-agent-sdk@0.2.8 start
24
+ npx -y wave3d-agent-sdk@0.2.9 start
25
25
  ```
26
26
 
27
- After Copy to Agent, restart stale SDK processes with MCP_TOKEN preserved as the local pairing secret. Keep it hidden:
27
+ After Copy to Agent, run the exact start command with MCP_TOKEN preserved as the local pairing secret. Keep it hidden:
28
28
 
29
29
  ```bash
30
- WAVE3D_MCP_TOKEN="$MCP_TOKEN" npx -y wave3d-agent-sdk@0.2.8 start
30
+ WAVE3D_MCP_TOKEN="$MCP_TOKEN" npx -y wave3d-agent-sdk@0.2.9 start
31
31
  ```
32
32
 
33
33
  Check SDK build before trusting a running SDK process:
34
34
 
35
35
  ```bash
36
- npx -y wave3d-agent-sdk@0.2.8 --version
36
+ npx -y wave3d-agent-sdk@0.2.9 --version
37
37
  ```
38
38
 
39
39
  The package bundles the WaveEngine SDK lookup corpus. No normal session needs a separate protected zip download.
@@ -43,12 +43,12 @@ The package bundles the WaveEngine SDK lookup corpus. No normal session needs a
43
43
  Wave Studio Copy to Agent defaults same-machine live MCP transport to this SDK:
44
44
 
45
45
  ```bash
46
- npx -y wave3d-agent-sdk@0.2.8 start
46
+ npx -y wave3d-agent-sdk@0.2.9 start
47
47
  ```
48
48
 
49
49
  Agents choose topology first:
50
50
 
51
- - Same computer as Wave Studio browser: try copied localhost `MCP_URL`, call `self_check_wave_mcp` with copied `expectedVersion` and `expectedBuildHash`, and restart exact SDK command from Copy to Agent if `self_check_wave_mcp` is missing, SDK is stale, tools are missing, or the SDK prints secrets before fallback. If restart happens after Copy to Agent, preserve MCP_TOKEN with `WAVE3D_MCP_TOKEN="$MCP_TOKEN"` so the new SDK process can authorize that local pairing secret. HTTP Gateway is degraded fallback only after SDK cannot run, update, or adopt; successful Gateway auth or convenience is not a same-machine fallback reason.
51
+ - Same computer as Wave Studio browser: try copied localhost `MCP_URL`, call `self_check_wave_mcp` with copied `expectedVersion` and `expectedBuildHash`, and run the exact SDK command from Copy to Agent if `self_check_wave_mcp` is missing, SDK is stale, tools are missing, or the SDK prints secrets before fallback. Current SDK starts self-heal stale peers on the same localhost port: it reuses a current same-token SDK, replaces verified stale/different-token SDK peers, and refuses to kill non-SDK port owners. If restart happens after Copy to Agent, preserve MCP_TOKEN with `WAVE3D_MCP_TOKEN="$MCP_TOKEN"` so the SDK process can authorize that local pairing secret. HTTP Gateway is degraded fallback only after SDK cannot run, update, or adopt; successful Gateway auth or convenience is not a same-machine fallback reason.
52
52
  - Different machine, remote container, cloud agent, sandbox without shell/Node/npm, or localhost points to agent machine instead of user browser machine: use `MCP_HTTP_GATEWAY_FALLBACK_URL` directly. Do not start WaveEngine Agent SDK on wrong machine.
53
53
 
54
54
  Call `get_wave_mcp_health` (aliases: `mcp_health`, `mcp_status`) whenever transport, SDK, or session status is unclear. It reports endpoint kind, SDK version/build, tool catalog hash/count, paired sessions, and WaveEngine SDK Cache state.
@@ -58,13 +58,13 @@ Use `MCP_HTTP_GATEWAY_FALLBACK_URL` only for topology mismatch, remote/sandboxed
58
58
  For unfamiliar authoring, use the local SDK tools:
59
59
 
60
60
  ```bash
61
- npx -y wave3d-agent-sdk@0.2.8 cache search "continuous left rotation"
61
+ npx -y wave3d-agent-sdk@0.2.9 cache search "continuous left rotation"
62
62
  ```
63
63
 
64
64
  `cache refresh` without MCP arguments reinstalls the bundled SDK into `~/.wave3d/agent-cache`:
65
65
 
66
66
  ```bash
67
- npx -y wave3d-agent-sdk@0.2.8 cache refresh
67
+ npx -y wave3d-agent-sdk@0.2.9 cache refresh
68
68
  ```
69
69
 
70
70
  Old `cache refresh --mcp-url <url> --token <token>` arguments are ignored. Normal users update the npm package; no separate zip download exists.
package/dist/cli.js CHANGED
@@ -3,10 +3,12 @@
3
3
  // src/cli.ts
4
4
  import { mkdir as mkdir3, readFile as readFile2, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
5
5
  import { existsSync as existsSync2 } from "node:fs";
6
- import { createHash as createHash5 } from "node:crypto";
6
+ import { execFile } from "node:child_process";
7
+ import { createHash as createHash6 } from "node:crypto";
7
8
  import { homedir as homedir2 } from "node:os";
8
9
  import path4 from "node:path";
9
10
  import { fileURLToPath } from "node:url";
11
+ import { promisify } from "node:util";
10
12
  import JSZip from "jszip";
11
13
  import MiniSearch2 from "minisearch";
12
14
 
@@ -35,10 +37,13 @@ function createWaveGenieError(code, message, details) {
35
37
  }
36
38
 
37
39
  // ../../scripts/wavegenie-sdk/auth.ts
38
- import { randomBytes, timingSafeEqual } from "node:crypto";
40
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
39
41
  function createWaveGenieBridgeToken() {
40
42
  return randomBytes(24).toString("hex");
41
43
  }
44
+ function createWaveGenieBridgeTokenFingerprint(token) {
45
+ return createHash("sha256").update("waveengine-agent-sdk-local-pairing-secret:").update(token).digest("base64url").slice(0, 16);
46
+ }
42
47
  function extractWaveGenieBearerToken(authorizationHeader) {
43
48
  if (!authorizationHeader) return null;
44
49
  const [scheme, ...rest] = authorizationHeader.trim().split(/\s+/);
@@ -42483,8 +42488,8 @@ function normalizeWaveGenieAssetUploadRequest(request) {
42483
42488
 
42484
42489
  // ../../src/lib/waveStudio/aiAssist/bridge/localAgentSdkContract.ts
42485
42490
  var WAVE3D_AGENT_SDK_PACKAGE_NAME = "wave3d-agent-sdk";
42486
- var WAVE3D_AGENT_SDK_REQUIRED_VERSION = "0.2.8";
42487
- var WAVE3D_AGENT_SDK_REQUIRED_BUILD = "agent-sdk-20260620.3";
42491
+ var WAVE3D_AGENT_SDK_REQUIRED_VERSION = "0.2.9";
42492
+ var WAVE3D_AGENT_SDK_REQUIRED_BUILD = "agent-sdk-20260620.4";
42488
42493
  var WAVE3D_AGENT_SDK_PACKAGE_SPEC = `${WAVE3D_AGENT_SDK_PACKAGE_NAME}@${WAVE3D_AGENT_SDK_REQUIRED_VERSION}`;
42489
42494
  var WAVE3D_AGENT_SDK_START_COMMAND = `npx -y ${WAVE3D_AGENT_SDK_PACKAGE_SPEC} start`;
42490
42495
  var WAVE3D_AGENT_SDK_TOKEN_ENV_VAR = "WAVE3D_MCP_TOKEN";
@@ -44390,7 +44395,7 @@ var WAVE_MCP_AGENT_BRIEF = [
44390
44395
  '0-role. Roleplay lock: you are the Wave Studio authoring agent for this session. Stay in that role, follow Wave authoring strategy, use concrete MCP tools, and briefly confirm "Wave Studio authoring role accepted" after onboarding acceptance.',
44391
44396
  "0. Think in skills, act with tools. `studio.*` names are routing families, not callable tool names; call the real MCP tools listed under each family.",
44392
44397
  "0a. Do not invent MCP tool names. After onboarding, call `tools/list` (or read the returned tool catalog) and use concrete names. Common aliases and safe high-confidence typos are tolerated; destructive/write fuzzy matches require an exact follow-up call. There is no `get_wave_current_project`; use `get_wave_session` for current project/session/active-file context.",
44393
- `0b. Transport rule: choose topology first. Same-machine agent + same Wave Studio browser computer -> use copied \`MCP_URL\` WaveEngine Agent SDK (\`http://127.0.0.1:47231/mcp\`). On localhost, MCP_TOKEN is a local pairing secret, not account/cloud auth. If localhost is refused/unreachable, start exact SDK \`${WAVE3D_AGENT_SDK_START_COMMAND}\` when your runtime allows shell/Node/npm. If SDK is stale, missing tools, printing secrets, or local 401 follows an SDK restart, stop it and restart while preserving MCP_TOKEN as the local pairing secret with \`${WAVE3D_AGENT_SDK_TOKEN_PRESERVING_START_COMMAND}\`; use the current MCP_TOKEN value without printing it. Then recheck /health and tools/list. Same-machine stale/missing tools/401-with-Gateway-success means repair local SDK first, do not use HTTP Gateway first. Same-machine HTTP Gateway is degraded fallback only after SDK cannot run, update, or adopt; convenience, habit, or successful Gateway auth is not a valid fallback reason. Different machine, remote container, cloud agent, sandbox without shell/Node/npm, or localhost points to the agent machine -> use \`MCP_HTTP_GATEWAY_FALLBACK_URL\` directly, where MCP_TOKEN is an HTTP Gateway bearer. Do not start WaveEngine Agent SDK on the wrong machine.`,
44398
+ `0b. Transport rule: choose topology first. Same-machine agent + same Wave Studio browser computer -> use copied \`MCP_URL\` WaveEngine Agent SDK (\`http://127.0.0.1:47231/mcp\`). On localhost, MCP_TOKEN is a local pairing secret, not account/cloud auth. If localhost is refused/unreachable, start exact SDK \`${WAVE3D_AGENT_SDK_START_COMMAND}\` when your runtime allows shell/Node/npm. If SDK is stale, missing tools, printing secrets, or local 401 follows an SDK restart, run the exact token-preserving command \`${WAVE3D_AGENT_SDK_TOKEN_PRESERVING_START_COMMAND}\`; use the current MCP_TOKEN value without printing it. Current SDK start self-heals verified stale/different-token SDK peers on localhost and refuses to kill non-SDK port owners. Then recheck /health and tools/list. Same-machine stale/missing tools/401-with-Gateway-success means repair local SDK first, do not use HTTP Gateway first. Same-machine HTTP Gateway is degraded fallback only after SDK cannot run, update, or adopt; convenience, habit, or successful Gateway auth is not a valid fallback reason. Different machine, remote container, cloud agent, sandbox without shell/Node/npm, or localhost points to the agent machine -> use \`MCP_HTTP_GATEWAY_FALLBACK_URL\` directly, where MCP_TOKEN is an HTTP Gateway bearer. Do not start WaveEngine Agent SDK on the wrong machine.`,
44394
44399
  "0b-recovery. If connection/session/onboarding/cache/mirror/timeout state is unclear, call `get_wave_mcp_health` (aliases `mcp_health`, `mcp_status`) first for status, then call `recover_wave_connection({ lastErrorCode?, failedTool?, symptom? })` and follow its `nextAction` exactly. Use recovery after `agent_onboarding_required`, `session_not_found`, `command_timeout`, `command_lease_expired`, `workspace_mirror_not_ready`, `hosted_mcp_proxy_failed`, local/HTTP Gateway fallback confusion, or sleeping-tab symptoms. If local HTTP returns 401 but HTTP Gateway accepts the same MCP_TOKEN, update/restart WaveEngine Agent SDK first. If every endpoint returns 401/bridge_auth_invalid before any tool result, ask user for fresh Copy to Agent.",
44395
44400
  `0c. Cache priorities: Priority 1 is active role/context cache. Keep the role, coding guardrails, authoring workflow, full intent taxonomy (${WAVE_MCP_TASK_INTENT_KIND_VALUES.join(", ")}), Studio tool policy, assets/VFS/hot-reload rules, prompt version, and prompt hash in active LLM context as system-prompt-like rules. Priority 2 is WaveEngine SDK Cache. Production HTTP Gateway/local-SDK onboarding must not claim normal cached success until SDK cache is prepared or explicit accept proof passes. If cache cannot work because sandbox/no filesystem/no Node/npm/user refusal/refresh failure, accept degraded fallback explicitly with \`waveEngineSdkFallbackMode:"studio_ops_only"\` plus \`waveEngineSdkUnavailableReason\` plus \`studioOpsOnlyFallbackAccepted:true\`, and warn user HTTP Gateway is Studio-ops-only and skill/API lookup requires local SDK/cache repair. Keep live transport and retrieval cache separate: \`wave3d-agent-sdk start\` is long-running MCP transport; \`wave3d-agent-sdk cache refresh\` reinstalls the package-bundled SDK locally. Never use cache refresh to switch MCP transport, and never treat cache failure as local transport failure. Use SDK Cache for unfamiliar authoring skill/API lookup when Node/npm/local cache are allowed.`,
44396
44401
  '0d. Local parity rule: WaveEngine Agent SDK `tools/list` mirrors the HTTP Gateway Studio-operation catalog, then adds local SDK lookup/session-discovery extras. Live-session tools run through the paired browser. Local calls wait directly for browser results. Only call `get_wave_command_result` when a tool response actually includes `status:"pending"` and `requestId`; on local it is normally catalog parity only.',
@@ -44633,7 +44638,7 @@ var WAVE_MCP_STUDIO_TOOL_GUIDE = [
44633
44638
  "- MCP names: HTTP Gateway = Next/Vercel endpoint for remote/sandbox Studio operations; WaveEngine Agent SDK = same-machine live MCP transport from long-running `wave3d-agent-sdk start`; WaveEngine SDK Cache = package-bundled local skill/API docs retrieval; VFS Mirror = HTTP Gateway workspace snapshot. Do not confuse these modules. On same machine, HTTP Gateway is degraded fallback only after SDK cannot run/update/adopt; do not choose it because it is already reachable or easier.",
44634
44639
  "- MCP recovery: when connection/session/onboarding/cache/mirror/timeout state is unclear, call `recover_wave_connection({ lastErrorCode?, failedTool?, symptom? })` first and follow its returned `nextAction`. This is the explicit recovery path for sleeping tabs, local/HTTP Gateway confusion, mirror-not-ready, onboarding-required, command timeout/lease expiry, and hosted proxy/cache failures.",
44635
44640
  '- Local parity rule: WaveEngine Agent SDK `tools/list` mirrors the HTTP Gateway Studio-operation catalog, then adds local SDK lookup/session-discovery extras. Direct local live-session tools include VFS edits, assets/uploads, project save/open/new/read/share, preview run/hot reload/pause/resume, diagnostics, performance, screenshots, entity snapshots, and runtime markers. Local browser-backed calls wait directly for browser results. Only call `get_wave_command_result` if a tool returns `status:"pending"` plus `requestId`; on local it normally exists only for catalog parity and reports no local pending-command queue.',
44636
- `- MCP topology: same-machine agents should run \`${WAVE3D_AGENT_SDK_START_COMMAND}\`, check /health, and update/restart SDK if version is stale, tools are missing, or SDK prints secrets; after restart recheck /health and tools/list. If restart happens after Copy-to-Agent, preserve MCP_TOKEN with \`${WAVE3D_AGENT_SDK_TOKEN_PRESERVING_START_COMMAND}\` using the current MCP_TOKEN value without printing it, otherwise the new SDK may be healthy but unable to authorize the copied local pairing secret. Same-machine stale/missing tools/401-with-Gateway-success means repair local SDK first, not HTTP Gateway first. Same-machine HTTP Gateway is degraded fallback only after SDK cannot run, update, or adopt. Different-machine/cloud/sandbox agents should use \`MCP_HTTP_GATEWAY_FALLBACK_URL\` directly; starting WaveEngine Agent SDK there binds localhost beside the agent, not beside the user browser. Stale SDK/cache are not reasons to use HTTP Gateway fallback; wrong-machine localhost is a topology mismatch.`,
44641
+ `- MCP topology: same-machine agents should run \`${WAVE3D_AGENT_SDK_START_COMMAND}\`, check /health, and update/restart SDK if version is stale, tools are missing, or SDK prints secrets; after restart recheck /health and tools/list. If restart happens after Copy-to-Agent, preserve MCP_TOKEN with \`${WAVE3D_AGENT_SDK_TOKEN_PRESERVING_START_COMMAND}\` using the current MCP_TOKEN value without printing it, otherwise the SDK may be healthy but unable to authorize the copied local pairing secret. Current SDK start reuses a current same-token peer, replaces verified stale/different-token SDK peers on localhost, and refuses to kill non-SDK port owners. Same-machine stale/missing tools/401-with-Gateway-success means repair local SDK first, not HTTP Gateway first. Same-machine HTTP Gateway is degraded fallback only after SDK cannot run, update, or adopt. Different-machine/cloud/sandbox agents should use \`MCP_HTTP_GATEWAY_FALLBACK_URL\` directly; starting WaveEngine Agent SDK there binds localhost beside the agent, not beside the user browser. Stale SDK/cache are not reasons to use HTTP Gateway fallback; wrong-machine localhost is a topology mismatch.`,
44637
44642
  `- MCP cache priorities: Priority 1 is active role/context cache: keep role, guardrails, authoring workflow, asset/VFS/hot-reload rules, prompt version, and prompt hash in active LLM context. Priority 2 is WaveEngine SDK Cache: production HTTP Gateway/local-SDK onboarding must not claim normal cached success until SDK cache is prepared or accept proof passes. If accept returns \`wave_engine_sdk_cache_not_ready\`, update/restart \`wave3d-agent-sdk\` or run \`${WAVE_MCP_CORPUS_CACHE_COMMAND_TEMPLATE}\`, then retry accept. If local cache cannot work because sandbox/no filesystem/no Node/npm/user refusal/refresh failure, explicitly accept degraded fallback with \`waveEngineSdkFallbackMode:"studio_ops_only"\`, a valid \`waveEngineSdkUnavailableReason\`, and \`studioOpsOnlyFallbackAccepted:true\`; warn user HTTP Gateway is Studio-ops-only and skill/API lookup requires local SDK/cache repair. This cache command reinstalls the package-bundled SDK locally; it is not WaveEngine Agent SDK transport. Never run it to switch MCP transport; never treat cache failure as local transport failure.`,
44638
44643
  "- Main-file globals include `myScene`, `assetManager`, `waveEngine`, `waveStudio`, and direct asset maps such as `models`, `gaussianSplats`, `textures`, `materials`, `animations`, `audios`, `hdr`, `cubeMaps`, `fonts`, `serializedData`, `terrains`, `fx`, `particles`. Availability is not endorsement: choose the intent-owned facade/skill before using a global.",
44639
44644
  `- Bare authoring globals: common examples include ${WAVE_AUTHORING_COMMON_GLOBAL_EXAMPLES_TEXT}, \`waveMaterial\`, \`waveFx\`, \`waveValueCurve\`, and \`waveParam\`. Use them directly in \`main.ts\`; do not import or namespace-qualify them. If the task is unfamiliar, retrieve the relevant local-SDK \`wave.*\` skill first; for the full generated exact-global surface, call local-SDK \`query_wave_api\`.`,
@@ -44677,7 +44682,7 @@ var WAVE_MCP_TOOL_CATALOG_GUIDE = [
44677
44682
  "- `get_wave_coding_guardrails`: call after onboarding acceptance; returns policy, file context, tool catalog, and recipes.",
44678
44683
  '- `get_wave_mcp_health` (aliases `mcp_health`, `mcp_status`): read-only self diagnostic for endpoint kind, SDK version/build, tool catalog hash/count, onboarding, session/VFS, and WaveEngine SDK Cache state. Use when the agent asks "am I local/cloud/current/cached?" or any MCP state is unclear.',
44679
44684
  "- `get_wave_tool_map`: stable complete concrete MCP tool menu grouped by family plus policy flags. Use only when `tools/list` feels truncated or unclear.",
44680
- `- Transport topology rule: same-machine agents should run \`${WAVE3D_AGENT_SDK_START_COMMAND}\`, check /health, and update/restart SDK if version is stale, tools are missing, or SDK prints secrets; after Copy-to-Agent, restart with \`${WAVE3D_AGENT_SDK_TOKEN_PRESERVING_START_COMMAND}\` using the current MCP_TOKEN value without printing it so the copied local pairing secret still works. After restart recheck /health and tools/list. Same-machine stale/missing tools/401-with-Gateway-success means repair local SDK first, not HTTP Gateway first. Same-machine HTTP Gateway is degraded fallback only after SDK cannot run, update, or adopt; never use it because it is familiar, already authenticated, or avoids SDK repair. Different-machine/cloud/sandbox agents should use \`MCP_HTTP_GATEWAY_FALLBACK_URL\` directly. Stale SDK/cache are local setup issues, not fallback triggers; wrong-machine localhost is a topology mismatch.`,
44685
+ `- Transport topology rule: same-machine agents should run \`${WAVE3D_AGENT_SDK_START_COMMAND}\`, check /health, and update/restart SDK if version is stale, tools are missing, or SDK prints secrets; after Copy-to-Agent, restart with \`${WAVE3D_AGENT_SDK_TOKEN_PRESERVING_START_COMMAND}\` using the current MCP_TOKEN value without printing it so the copied local pairing secret still works. Current SDK start self-heals localhost SDK peers: reuse current same-token, replace verified stale/different-token SDK, refuse non-SDK port owners. After restart recheck /health and tools/list. Same-machine stale/missing tools/401-with-Gateway-success means repair local SDK first, not HTTP Gateway first. Same-machine HTTP Gateway is degraded fallback only after SDK cannot run, update, or adopt; never use it because it is familiar, already authenticated, or avoids SDK repair. Different-machine/cloud/sandbox agents should use \`MCP_HTTP_GATEWAY_FALLBACK_URL\` directly. Stale SDK/cache are local setup issues, not fallback triggers; wrong-machine localhost is a topology mismatch.`,
44681
44686
  "- `recover_wave_connection`: direct Observe recovery tool. Call after onboarding required, session missing, command timeout/lease expired, mirror not ready, hosted proxy/cache failure, local/HTTP Gateway confusion, or sleeping-tab symptoms. It returns exact next action: re-onboard, get session, wake tab, update/restart SDK, wait mirror, retry, use HTTP Gateway fallback, or ask fresh Copy to Agent.",
44682
44687
  '- WaveEngine SDK Cache: normal skill/API lookup lives inside the local `wave3d-agent-sdk` SDK package. Update/restart SDK when SDK is stale or missing. HTTP Gateway is Studio-ops-only and does not provide cloud skill/API lookup. If local SDK cannot work because sandbox/no filesystem/no Node/npm/user refusal/refresh failure, explicitly accept degraded fallback with `waveEngineSdkFallbackMode:"studio_ops_only"`, a valid `waveEngineSdkUnavailableReason`, and `studioOpsOnlyFallbackAccepted:true`; warn user skill/API lookup requires local SDK repair. This is retrieval cache, not WaveEngine Agent SDK transport. Never treat SDK cache failure as local transport failure. Keep Priority 1 role, guardrails, workflow, assets/VFS/hot-reload rules, prompt version, and prompt hash in active LLM context.',
44683
44688
  "- Work-mode rule: Observe reads directly; Operate direct Studio commands directly; Author/Diagnose routes through `start_wave_task`; General avoids Wave tools. Operate tools include run/hot reload, save/share, VFS create/rename/delete exact files, asset upload/rename/delete exact assets, new project, project rename, and open project by exact projectId.",
@@ -44849,7 +44854,7 @@ var LOCAL_MCP_AGENT_ONBOARDING_PROMPT = [
44849
44854
  `The WaveEngine Agent SDK answers skill/API/guardrail tools from the bundled WaveEngine SDK Cache. The SDK ships inside \`wave3d-agent-sdk\`; \`start\`, \`cache status\`, and \`cache search\` auto-prepare it locally. During \`accept_wave_agent_onboarding\`, production/HTTP-Gateway pairings must verify this local SDK cache before normal success. If missing, stale, or unverified, accept returns \`wave_engine_sdk_cache_not_ready\`; update/restart the exact SDK package or run the local bundled repair command \`${WAVE_MCP_CORPUS_CACHE_COMMAND_TEMPLATE}\`, then retry accept. If the agent is sandboxed, has no filesystem/Node/npm, or user refuses local SDK/cache, explicitly accept degraded Studio-ops-only fallback with \`waveEngineSdkFallbackMode:"studio_ops_only"\`, a valid \`waveEngineSdkUnavailableReason\`, and \`studioOpsOnlyFallbackAccepted:true\`; warn user HTTP Gateway can still do VFS/assets/project/preview/capture, but exact API lookup is unavailable until local SDK works. Keep the exact SDK command in active context as \`waveEngineSdkCacheCommandCached\`. Use local skill onion retrieval: \`list_wave_skill_families\` -> choose family ids -> \`query_wave_skills\` with \`families\`/\`familyId\` -> \`get_wave_skill\` -> \`query_wave_api\` only for exact signature/global/value uncertainty. HTTP Gateway is not an API lookup fallback.`,
44850
44855
  "",
44851
44856
  "Mandatory phased handshake:",
44852
- `Phase 0 WaveEngine Agent SDK preflight is not optional. Do these phases in order before user work: 1 initialize endpoint; 2 call \`self_check_wave_mcp\` with the exact \`expectedVersion\` and \`expectedBuildHash\` from Copy-to-Agent; hard-stop if stale/hardStop is true or tool count/hash looks missing, then restart SDK while preserving the copied MCP_TOKEN/local pairing secret with \`${WAVE3D_AGENT_SDK_TOKEN_PRESERVING_START_COMMAND}\` using the current MCP_TOKEN value hidden; same-machine HTTP Gateway is degraded fallback only after SDK cannot run, update, or adopt, never because Gateway is familiar/easier; 2a when status is unclear, call \`get_wave_mcp_health\`/\`mcp_status\` to read endpoint/SDK/tool/SDK/session state; 3 call \`get_wave_agent_onboarding\` and cache Priority 1 rules in active context; 4 call \`accept_wave_agent_onboarding\` with acceptedRole true, current promptVersion/promptHash, all required cachedSections, full intentKindsCached list, exact waveEngineSdkCacheCommandCached template, and every context-cache confirmation true; if it returns \`wave_engine_sdk_cache_not_ready\`, update/restart SDK or run the bundled SDK repair command and retry accept; if local SDK cannot work, explicitly accept Studio-ops-only fallback and do not do unfamiliar API authoring; 5 call \`tools/list\` and prefer concrete tool names from the returned catalog; 6 call \`get_wave_session\`; 7 call \`list_wave_files\`; 8 if the tool menu is unclear, call \`get_wave_tool_map\`. Observe tools such as file reads, assets, diagnostics, screenshots, snapshots, performance, and markers stay open. Operate tools such as run preview, hot reload, save/share/rename/open/new project, VFS create/rename/delete, and asset upload/rename/delete are direct Studio commands when the user asks for that operation. Author/Diagnose tools such as \`query_wave_api\`, \`edit_wave_file\`, \`apply_wave_patch\`, and code behavior changes use \`start_wave_task\`. After startup, report phase status briefly. If a required phase fails or any later MCP state is unclear, call \`get_wave_mcp_health\` for state and \`recover_wave_connection({ lastErrorCode?, failedTool?, symptom? })\` for nextAction before asking user for a fresh copy; do not skip ahead.`,
44857
+ `Phase 0 WaveEngine Agent SDK preflight is not optional. Do these phases in order before user work: 1 initialize endpoint; 2 call \`self_check_wave_mcp\` with the exact \`expectedVersion\` and \`expectedBuildHash\` from Copy-to-Agent; hard-stop if stale/hardStop is true or tool count/hash looks missing, then run the SDK while preserving the copied MCP_TOKEN/local pairing secret with \`${WAVE3D_AGENT_SDK_TOKEN_PRESERVING_START_COMMAND}\` using the current MCP_TOKEN value hidden; current SDK start reuses a current same-token peer, replaces verified stale/different-token SDK peers on localhost, and refuses to kill non-SDK port owners; same-machine HTTP Gateway is degraded fallback only after SDK cannot run, update, or adopt, never because Gateway is familiar/easier; 2a when status is unclear, call \`get_wave_mcp_health\`/\`mcp_status\` to read endpoint/SDK/tool/SDK/session state; 3 call \`get_wave_agent_onboarding\` and cache Priority 1 rules in active context; 4 call \`accept_wave_agent_onboarding\` with acceptedRole true, current promptVersion/promptHash, all required cachedSections, full intentKindsCached list, exact waveEngineSdkCacheCommandCached template, and every context-cache confirmation true; if it returns \`wave_engine_sdk_cache_not_ready\`, update/restart SDK or run the bundled SDK repair command and retry accept; if local SDK cannot work, explicitly accept Studio-ops-only fallback and do not do unfamiliar API authoring; 5 call \`tools/list\` and prefer concrete tool names from the returned catalog; 6 call \`get_wave_session\`; 7 call \`list_wave_files\`; 8 if the tool menu is unclear, call \`get_wave_tool_map\`. Observe tools such as file reads, assets, diagnostics, screenshots, snapshots, performance, and markers stay open. Operate tools such as run preview, hot reload, save/share/rename/open/new project, VFS create/rename/delete, and asset upload/rename/delete are direct Studio commands when the user asks for that operation. Author/Diagnose tools such as \`query_wave_api\`, \`edit_wave_file\`, \`apply_wave_patch\`, and code behavior changes use \`start_wave_task\`. After startup, report phase status briefly. If a required phase fails or any later MCP state is unclear, call \`get_wave_mcp_health\` for state and \`recover_wave_connection({ lastErrorCode?, failedTool?, symptom? })\` for nextAction before asking user for a fresh copy; do not skip ahead.`,
44853
44858
  "Tool-name tolerance: concrete names from tools/list remain preferred. Common aliases and safe high-confidence typos are tolerated. Destructive/write fuzzy matches return did-you-mean instead of executing.",
44854
44859
  "Glossary: WaveEngine Agent SDK = same-machine live MCP transport plus bundled SDK lookup; Local Pairing Secret = MCP_TOKEN on localhost, not account/cloud auth; HTTP Gateway Bearer = MCP_TOKEN on HTTP Gateway; WaveEngine SDK Cache = package-bundled public docs/API/skill retrieval; MCP Session = browser pairing state; VFS Mirror = HTTP Gateway read/edit hash snapshot; Project = user workspace content. Do not merge these concepts.",
44855
44860
  "",
@@ -44877,7 +44882,7 @@ var LOCAL_MCP_AGENT_ONBOARDING_PROMPT = [
44877
44882
  ].join("\n");
44878
44883
 
44879
44884
  // ../../scripts/wavegenie-sdk/mcp/referenceTools.ts
44880
- import { createHash } from "node:crypto";
44885
+ import { createHash as createHash2 } from "node:crypto";
44881
44886
  import { existsSync } from "node:fs";
44882
44887
  import { readFile } from "node:fs/promises";
44883
44888
  import { homedir } from "node:os";
@@ -45262,7 +45267,7 @@ function isLocalCorpusManifest(value) {
45262
45267
  return isRecord2(value) && typeof value.version === "string" && (typeof value.formatVersion === "undefined" || typeof value.formatVersion === "string") && typeof value.cacheKey === "string" && typeof value.bundleFileName === "string" && typeof value.bundleHash === "string" && (typeof value.generatedAt === "undefined" || typeof value.generatedAt === "string") && (typeof value.sourceVersions === "undefined" || isRecord2(value.sourceVersions)) && Array.isArray(value.files) && value.files.every(isLocalCorpusFileManifestEntry);
45263
45268
  }
45264
45269
  function corpusFileHash(content) {
45265
- return createHash("sha256").update(JSON.stringify(content)).digest("base64url").slice(0, 32);
45270
+ return createHash2("sha256").update(JSON.stringify(content)).digest("base64url").slice(0, 32);
45266
45271
  }
45267
45272
  function stableJson(value) {
45268
45273
  if (Array.isArray(value)) return `[${value.map((item) => stableJson(item)).join(",")}]`;
@@ -47429,7 +47434,7 @@ async function handleVfsTool(input) {
47429
47434
  }
47430
47435
 
47431
47436
  // ../../scripts/wavegenie-sdk/mcp/toolDefinitions.ts
47432
- import { createHash as createHash2 } from "node:crypto";
47437
+ import { createHash as createHash3 } from "node:crypto";
47433
47438
 
47434
47439
  // ../../src/lib/waveStudio/authoring/workspace/vfs/vfsImportAnalysis.ts
47435
47440
  var VFS_CODE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
@@ -49764,7 +49769,7 @@ function getLocalToolCatalogHash() {
49764
49769
  description: definition.description,
49765
49770
  inputSchema: definition.inputSchema
49766
49771
  })).sort((left, right) => left.name.localeCompare(right.name));
49767
- return createHash2("sha256").update(JSON.stringify(tools)).digest("base64url").slice(0, 24);
49772
+ return createHash3("sha256").update(JSON.stringify(tools)).digest("base64url").slice(0, 24);
49768
49773
  }
49769
49774
 
49770
49775
  // ../../scripts/wavegenie-sdk/mcp.ts
@@ -49963,7 +49968,7 @@ function localConnectionRecoveryResult(args, context) {
49963
49968
  nextAction = "Wave Studio tab is paired but not actively polling commands, or browser-backed command timed out. Ask user to focus/wake the tab and verify MCP is live; retry the same tool once on the same local endpoint and MCP_TOKEN pairing secret.";
49964
49969
  nextTool = failedTool || "get_wave_session";
49965
49970
  requiresUserAction = true;
49966
- steps.push(`If SDK /health is down before pairing, start \`${WAVE3D_AGENT_SDK_START_COMMAND}\`; after Copy-to-Agent, restart stale SDK with \`${WAVE3D_AGENT_SDK_TOKEN_PRESERVING_START_COMMAND}\` using the current MCP_TOKEN value hidden. If /health is OK and version matches Copy to Agent, do not restart SDK first.`);
49971
+ steps.push(`If SDK /health is down before pairing, start \`${WAVE3D_AGENT_SDK_START_COMMAND}\`; after Copy-to-Agent, run \`${WAVE3D_AGENT_SDK_TOKEN_PRESERVING_START_COMMAND}\` using the current MCP_TOKEN value hidden. Current SDK start self-heals verified stale/different-token SDK peers and refuses non-SDK port owners. If /health is OK and version/token match Copy to Agent, do not restart SDK first.`);
49967
49972
  } else if (lastErrorCode === "session_write_not_allowed" || selectedSession?.accessMode !== "readwrite") {
49968
49973
  state = "write_access_not_ready";
49969
49974
  nextAction = "Read tools can continue. For write/run/hot reload, user must make the Studio MCP session read-write/adopt WaveEngine Agent SDK, then retry same local endpoint and MCP_TOKEN pairing secret or paste fresh Copy to Agent if the secret changed.";
@@ -50023,7 +50028,7 @@ function localConnectionRecoveryResult(args, context) {
50023
50028
  steps,
50024
50029
  hardStopRules: [
50025
50030
  "Local HTTP refused/unreachable before MCP response: start WaveEngine Agent SDK, retry localhost for up to 10 seconds.",
50026
- "Local HTTP 401/bridge_auth_invalid: if HTTP Gateway accepts the same MCP_TOKEN, SDK is stale/not adopted: restart exact WaveEngine Agent SDK so it adopts MCP_TOKEN as the local pairing secret, then retry local. If every endpoint rejects MCP_TOKEN, ask user for fresh Copy to Agent.",
50031
+ "Local HTTP 401/bridge_auth_invalid: if HTTP Gateway accepts the same MCP_TOKEN, SDK is stale/not adopted: run the exact token-preserving WaveEngine Agent SDK command so it adopts MCP_TOKEN as the local pairing secret, then retry local. If every endpoint rejects MCP_TOKEN, ask user for fresh Copy to Agent.",
50027
50032
  "No paired session or stale command poll: wake/reopen Wave Studio tab; keep same local endpoint and MCP_TOKEN pairing secret first.",
50028
50033
  "WaveEngine SDK Cache failure is not live transport failure."
50029
50034
  ]
@@ -51378,7 +51383,7 @@ async function handleWaveGenieMcpRequest(request, context) {
51378
51383
  }
51379
51384
 
51380
51385
  // ../../scripts/wavegenie-sdk/sessionRegistry.ts
51381
- import { createHash as createHash3, randomUUID as randomUUID2, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
51386
+ import { createHash as createHash4, randomUUID as randomUUID2, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
51382
51387
  function createSessionId() {
51383
51388
  return `wgb_${randomUUID2()}`;
51384
51389
  }
@@ -51386,7 +51391,7 @@ function nowIso2() {
51386
51391
  return (/* @__PURE__ */ new Date()).toISOString();
51387
51392
  }
51388
51393
  function hashAgentToken(token) {
51389
- return createHash3("sha256").update(token).digest("hex");
51394
+ return createHash4("sha256").update(token).digest("hex");
51390
51395
  }
51391
51396
  function tokenHashMatches(left, right) {
51392
51397
  const leftBuffer = Buffer.from(left, "hex");
@@ -51520,7 +51525,7 @@ var WaveGenieBridgeSessionRegistry = class {
51520
51525
  };
51521
51526
 
51522
51527
  // ../../scripts/wavegenie-sdk/assetStaging.ts
51523
- import { createHash as createHash4, randomBytes as randomBytes2, randomUUID as randomUUID3 } from "node:crypto";
51528
+ import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID3 } from "node:crypto";
51524
51529
  import { createWriteStream } from "node:fs";
51525
51530
  import { mkdir as mkdir2, rm, writeFile as writeFile2 } from "node:fs/promises";
51526
51531
  import { tmpdir as tmpdir2 } from "node:os";
@@ -51537,7 +51542,7 @@ function createSecret() {
51537
51542
  return randomBytes2(24).toString("base64url");
51538
51543
  }
51539
51544
  function hashPathPart(value) {
51540
- return createHash4("sha256").update(value).digest("hex").slice(0, 20);
51545
+ return createHash5("sha256").update(value).digest("hex").slice(0, 20);
51541
51546
  }
51542
51547
  function decodeBase64(dataBase64) {
51543
51548
  const normalized = dataBase64.trim();
@@ -51997,8 +52002,10 @@ async function startWaveEngineAgentSdkServer(options = {}) {
51997
52002
  bridgeId,
51998
52003
  version: MCP_SERVER_VERSION,
51999
52004
  packageVersion: MCP_SERVER_VERSION,
52005
+ processId: process.pid,
52000
52006
  protocolVersion: "waveengine-agent-sdk-http-v1",
52001
52007
  buildHash: WAVE3D_AGENT_SDK_REQUIRED_BUILD,
52008
+ tokenFingerprint: createWaveGenieBridgeTokenFingerprint(token),
52002
52009
  requiredPackage: WAVE3D_AGENT_SDK_PACKAGE_SPEC,
52003
52010
  requiredVersion: WAVE3D_AGENT_SDK_REQUIRED_VERSION,
52004
52011
  requiredBuildHash: WAVE3D_AGENT_SDK_REQUIRED_BUILD,
@@ -52285,6 +52292,7 @@ var BUNDLED_SDK_DIR_NAME = "sdk";
52285
52292
  var MAX_CORPUS_ZIP_BYTES2 = 50 * 1024 * 1024;
52286
52293
  var MAX_CORPUS_EXTRACTED_BYTES2 = 100 * 1024 * 1024;
52287
52294
  var MAX_CORPUS_FILE_COUNT = 5e3;
52295
+ var execFileAsync = promisify(execFile);
52288
52296
  function parseArgs(argv) {
52289
52297
  const flags = /* @__PURE__ */ new Map();
52290
52298
  const positionals = [];
@@ -52382,6 +52390,307 @@ function requireSafePathSegment(value, label) {
52382
52390
  function isRecord4(value) {
52383
52391
  return !!value && typeof value === "object" && !Array.isArray(value);
52384
52392
  }
52393
+ function formatLoopbackHttpUrl(host, port, pathname) {
52394
+ const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
52395
+ return `http://${urlHost}:${port}${pathname}`;
52396
+ }
52397
+ function readNumberProperty(record, name) {
52398
+ const value = record[name];
52399
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
52400
+ }
52401
+ function readStringProperty(record, name) {
52402
+ const value = record[name];
52403
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
52404
+ }
52405
+ function readLocalSdkPeerHealth(value) {
52406
+ if (!isRecord4(value)) return null;
52407
+ const data = isRecord4(value.data) ? value.data : value;
52408
+ const bridgeId = readStringProperty(data, "bridgeId");
52409
+ const protocolVersion = readStringProperty(data, "protocolVersion");
52410
+ const requiredPackage = readStringProperty(data, "requiredPackage");
52411
+ const isCurrentSdkProtocol = protocolVersion === "waveengine-agent-sdk-http-v1";
52412
+ const isLegacyHelperProtocol = protocolVersion === "local-agent-helper-http-v1" && typeof requiredPackage === "string" && requiredPackage.startsWith("wave3d-agent-bridge@");
52413
+ if (!bridgeId || !bridgeId.startsWith("wgbridge_") || !isCurrentSdkProtocol && !isLegacyHelperProtocol) {
52414
+ return null;
52415
+ }
52416
+ return {
52417
+ bridgeId,
52418
+ packageVersion: readStringProperty(data, "packageVersion"),
52419
+ protocolVersion,
52420
+ buildHash: readStringProperty(data, "buildHash"),
52421
+ processId: readNumberProperty(data, "processId"),
52422
+ tokenFingerprint: readStringProperty(data, "tokenFingerprint")
52423
+ };
52424
+ }
52425
+ function parseProcessIds(output) {
52426
+ const ids = /* @__PURE__ */ new Set();
52427
+ for (const match of output.matchAll(/\b\d+\b/g)) {
52428
+ const pid = Number(match[0]);
52429
+ if (Number.isInteger(pid) && pid > 0 && pid !== process.pid) ids.add(pid);
52430
+ }
52431
+ return [...ids];
52432
+ }
52433
+ async function execProcessIdCommand(command, args) {
52434
+ try {
52435
+ const { stdout } = await execFileAsync(command, args, {
52436
+ timeout: 2500,
52437
+ maxBuffer: 128 * 1024,
52438
+ windowsHide: true
52439
+ });
52440
+ return parseProcessIds(stdout);
52441
+ } catch {
52442
+ return [];
52443
+ }
52444
+ }
52445
+ async function findListenerProcessIds(port) {
52446
+ if (process.platform === "win32") {
52447
+ return execProcessIdCommand("powershell.exe", [
52448
+ "-NoProfile",
52449
+ "-Command",
52450
+ `(Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue | Select-Object -ExpandProperty OwningProcess | Sort-Object -Unique) -join "
52451
+ "`
52452
+ ]);
52453
+ }
52454
+ return execProcessIdCommand("lsof", ["-nP", `-tiTCP:${port}`, "-sTCP:LISTEN"]);
52455
+ }
52456
+ async function readProcessInfo(pid) {
52457
+ if (pid === process.pid) return null;
52458
+ try {
52459
+ if (process.platform === "win32") {
52460
+ const { stdout: stdout2 } = await execFileAsync("powershell.exe", [
52461
+ "-NoProfile",
52462
+ "-Command",
52463
+ `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}" | Select-Object ProcessId,ParentProcessId,CommandLine | ConvertTo-Json -Compress)`
52464
+ ], {
52465
+ timeout: 2500,
52466
+ maxBuffer: 128 * 1024,
52467
+ windowsHide: true
52468
+ });
52469
+ const parsed = JSON.parse(stdout2);
52470
+ if (!isRecord4(parsed)) return null;
52471
+ const parsedPid = readNumberProperty(parsed, "ProcessId");
52472
+ const parentPid = readNumberProperty(parsed, "ParentProcessId");
52473
+ const command = readStringProperty(parsed, "CommandLine");
52474
+ if (!parsedPid || !parentPid || !command) return null;
52475
+ return { pid: parsedPid, parentPid, command };
52476
+ }
52477
+ const { stdout } = await execFileAsync("ps", [
52478
+ "-o",
52479
+ "pid=",
52480
+ "-o",
52481
+ "ppid=",
52482
+ "-o",
52483
+ "command=",
52484
+ "-p",
52485
+ String(pid)
52486
+ ], {
52487
+ timeout: 2500,
52488
+ maxBuffer: 128 * 1024,
52489
+ windowsHide: true
52490
+ });
52491
+ const match = stdout.trim().match(/^(\d+)\s+(\d+)\s+(.+)$/);
52492
+ if (!match) return null;
52493
+ return {
52494
+ pid: Number(match[1]),
52495
+ parentPid: Number(match[2]),
52496
+ command: match[3]
52497
+ };
52498
+ } catch {
52499
+ return null;
52500
+ }
52501
+ }
52502
+ async function findChildProcessIds(parentPid) {
52503
+ if (parentPid <= 0 || parentPid === process.pid) return [];
52504
+ if (process.platform === "win32") {
52505
+ return execProcessIdCommand("powershell.exe", [
52506
+ "-NoProfile",
52507
+ "-Command",
52508
+ `(Get-CimInstance Win32_Process -Filter "ParentProcessId = ${parentPid}" | Select-Object -ExpandProperty ProcessId | Sort-Object -Unique) -join "
52509
+ "`
52510
+ ]);
52511
+ }
52512
+ try {
52513
+ const { stdout } = await execFileAsync("ps", ["-axo", "pid=", "-o", "ppid="], {
52514
+ timeout: 2500,
52515
+ maxBuffer: 512 * 1024,
52516
+ windowsHide: true
52517
+ });
52518
+ const ids = [];
52519
+ for (const line of stdout.split("\n")) {
52520
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
52521
+ if (!match) continue;
52522
+ const pid = Number(match[1]);
52523
+ const ppid = Number(match[2]);
52524
+ if (ppid === parentPid && pid !== process.pid) ids.push(pid);
52525
+ }
52526
+ return ids;
52527
+ } catch {
52528
+ return [];
52529
+ }
52530
+ }
52531
+ function isWaveEngineAgentProcessCommand(command) {
52532
+ return /\bwave3d-agent-(sdk|bridge)\b/.test(command);
52533
+ }
52534
+ function isLegacyBridgePeer(health) {
52535
+ return health.protocolVersion === "local-agent-helper-http-v1";
52536
+ }
52537
+ async function stopLegacyBridgeLaunchAgent(health) {
52538
+ if (!isLegacyBridgePeer(health) || process.platform !== "darwin") return;
52539
+ const getuid = process.getuid;
52540
+ if (typeof getuid !== "function") return;
52541
+ const uid = getuid();
52542
+ const launchTarget = `gui/${uid}/com.wave3d.agent-bridge`;
52543
+ console.log("[WaveEngine Agent SDK] Stopping legacy wave3d-agent-bridge launch agent before replacement.");
52544
+ try {
52545
+ await execFileAsync("launchctl", ["bootout", launchTarget], {
52546
+ timeout: 2500,
52547
+ maxBuffer: 128 * 1024,
52548
+ windowsHide: true
52549
+ });
52550
+ } catch {
52551
+ }
52552
+ try {
52553
+ await execFileAsync("launchctl", ["remove", "com.wave3d.agent-bridge"], {
52554
+ timeout: 2500,
52555
+ maxBuffer: 128 * 1024,
52556
+ windowsHide: true
52557
+ });
52558
+ } catch {
52559
+ }
52560
+ }
52561
+ async function collectVerifiedSdkPeerProcessIds(seedPids) {
52562
+ const targetPids = /* @__PURE__ */ new Set();
52563
+ const parentPids = /* @__PURE__ */ new Set();
52564
+ for (const seedPid of seedPids) {
52565
+ if (seedPid <= 0 || seedPid === process.pid) continue;
52566
+ targetPids.add(seedPid);
52567
+ const processInfo = await readProcessInfo(seedPid);
52568
+ if (!processInfo) continue;
52569
+ if (isWaveEngineAgentProcessCommand(processInfo.command)) {
52570
+ for (const childPid of await findChildProcessIds(processInfo.pid)) targetPids.add(childPid);
52571
+ }
52572
+ if (processInfo.parentPid > 1 && processInfo.parentPid !== process.pid) {
52573
+ const parentInfo = await readProcessInfo(processInfo.parentPid);
52574
+ if (parentInfo && isWaveEngineAgentProcessCommand(parentInfo.command)) {
52575
+ parentPids.add(parentInfo.pid);
52576
+ for (const childPid of await findChildProcessIds(parentInfo.pid)) targetPids.add(childPid);
52577
+ }
52578
+ }
52579
+ }
52580
+ for (const parentPid of parentPids) targetPids.delete(parentPid);
52581
+ return [...parentPids, ...targetPids].filter((pid) => pid !== process.pid);
52582
+ }
52583
+ async function readLocalSdkPeerProbe(host, port) {
52584
+ const healthUrl = formatLoopbackHttpUrl(host, port, "/health");
52585
+ let response;
52586
+ try {
52587
+ response = await fetch(healthUrl, { signal: AbortSignal.timeout(1500) });
52588
+ } catch {
52589
+ return { kind: "none" };
52590
+ }
52591
+ let parsed;
52592
+ try {
52593
+ parsed = await response.json();
52594
+ } catch {
52595
+ return {
52596
+ kind: "non-sdk",
52597
+ message: `Port ${port} is occupied by an HTTP server, but /health did not return JSON.`
52598
+ };
52599
+ }
52600
+ const health = readLocalSdkPeerHealth(parsed);
52601
+ if (!health) {
52602
+ return {
52603
+ kind: "non-sdk",
52604
+ message: `Port ${port} is occupied, but /health is not a WaveEngine Agent SDK health response.`
52605
+ };
52606
+ }
52607
+ return { kind: "sdk", health };
52608
+ }
52609
+ function isCurrentSdkPeer(health) {
52610
+ return health.packageVersion === WAVE3D_AGENT_SDK_REQUIRED_VERSION && health.buildHash === WAVE3D_AGENT_SDK_REQUIRED_BUILD;
52611
+ }
52612
+ function shouldReplaceCurrentSdkPeer(health, token) {
52613
+ if (!isCurrentSdkPeer(health)) return true;
52614
+ if (!token) return false;
52615
+ const expectedFingerprint = createWaveGenieBridgeTokenFingerprint(token);
52616
+ return health.tokenFingerprint !== expectedFingerprint;
52617
+ }
52618
+ async function waitForSdkPeerExit(pids, deadlineMs) {
52619
+ const deadline = Date.now() + deadlineMs;
52620
+ while (Date.now() < deadline) {
52621
+ const alive = pids.some((pid) => {
52622
+ try {
52623
+ process.kill(pid, 0);
52624
+ return true;
52625
+ } catch {
52626
+ return false;
52627
+ }
52628
+ });
52629
+ if (!alive) return true;
52630
+ await new Promise((resolve) => setTimeout(resolve, 150));
52631
+ }
52632
+ return false;
52633
+ }
52634
+ async function waitForSdkPeerPortRelease(port, deadlineMs) {
52635
+ const deadline = Date.now() + deadlineMs;
52636
+ while (Date.now() < deadline) {
52637
+ const listenerPids = await findListenerProcessIds(port);
52638
+ if (listenerPids.every((pid) => pid === process.pid)) return true;
52639
+ await new Promise((resolve) => setTimeout(resolve, 150));
52640
+ }
52641
+ return false;
52642
+ }
52643
+ async function terminateVerifiedSdkPeer(health, port) {
52644
+ await stopLegacyBridgeLaunchAgent(health);
52645
+ const seedPids = /* @__PURE__ */ new Set();
52646
+ if (health.processId && health.processId !== process.pid) seedPids.add(health.processId);
52647
+ for (const pid of await findListenerProcessIds(port)) seedPids.add(pid);
52648
+ if (seedPids.size === 0) {
52649
+ if (await waitForSdkPeerPortRelease(port, 250)) return;
52650
+ throw new Error(`WaveEngine Agent SDK peer on port ${port} is stale, but no listener PID could be found.`);
52651
+ }
52652
+ let targetPids = await collectVerifiedSdkPeerProcessIds([...seedPids]);
52653
+ if (targetPids.length === 0) {
52654
+ throw new Error("Refusing to terminate current SDK process.");
52655
+ }
52656
+ for (const pid of targetPids) {
52657
+ try {
52658
+ process.kill(pid, "SIGTERM");
52659
+ } catch {
52660
+ }
52661
+ }
52662
+ const exitedAfterTerm = await waitForSdkPeerExit(targetPids, 2500);
52663
+ if (exitedAfterTerm && await waitForSdkPeerPortRelease(port, 1500)) return;
52664
+ targetPids = await collectVerifiedSdkPeerProcessIds(await findListenerProcessIds(port));
52665
+ for (const pid of targetPids) {
52666
+ try {
52667
+ process.kill(pid, "SIGKILL");
52668
+ } catch {
52669
+ }
52670
+ }
52671
+ const exitedAfterKill = await waitForSdkPeerExit(targetPids, 2500);
52672
+ if (!exitedAfterKill || !await waitForSdkPeerPortRelease(port, 1500)) {
52673
+ throw new Error(`WaveEngine Agent SDK peer on port ${port} did not exit after termination.`);
52674
+ }
52675
+ }
52676
+ async function prepareLocalSdkPeerForStart(input) {
52677
+ if (!isLoopbackHost(input.host)) return false;
52678
+ if (input.allowNetwork) return false;
52679
+ const probe = await readLocalSdkPeerProbe(input.host, input.port);
52680
+ if (probe.kind === "none") return false;
52681
+ if (probe.kind === "non-sdk") {
52682
+ throw new Error(`${probe.message} Refusing to kill a non-SDK process.`);
52683
+ }
52684
+ if (!shouldReplaceCurrentSdkPeer(probe.health, input.token)) {
52685
+ console.log(`[WaveEngine Agent SDK] Existing SDK on ${formatLoopbackHttpUrl(input.host, input.port, "")} is current; reusing it.`);
52686
+ console.log("[WaveEngine Agent SDK] If a new Copy-to-Agent token fails later, restart with WAVE3D_MCP_TOKEN from that copy.");
52687
+ return true;
52688
+ }
52689
+ const reason = isCurrentSdkPeer(probe.health) ? "local pairing secret does not match this start request" : `stale version/build (${probe.health.packageVersion ?? "unknown"} ${probe.health.buildHash ?? "unknown"})`;
52690
+ console.log(`[WaveEngine Agent SDK] Replacing existing SDK on port ${input.port}: ${reason}.`);
52691
+ await terminateVerifiedSdkPeer(probe.health, input.port);
52692
+ return false;
52693
+ }
52385
52694
  function isCorpusFileManifestEntry(value) {
52386
52695
  if (!isRecord4(value)) return false;
52387
52696
  return typeof value.path === "string" && typeof value.mediaType === "string" && typeof value.role === "string" && typeof value.bytes === "number" && Number.isFinite(value.bytes) && Number.isInteger(value.bytes) && value.bytes >= 0 && typeof value.hash === "string";
@@ -52391,7 +52700,7 @@ function isCorpusManifest(value) {
52391
52700
  return typeof value.version === "string" && (typeof value.formatVersion === "undefined" || typeof value.formatVersion === "string") && typeof value.cacheKey === "string" && typeof value.bundleFileName === "string" && typeof value.bundleHash === "string" && (typeof value.generatedAt === "undefined" || typeof value.generatedAt === "string") && (typeof value.sourceVersions === "undefined" || isRecord4(value.sourceVersions)) && Array.isArray(value.files) && value.files.every(isCorpusFileManifestEntry);
52392
52701
  }
52393
52702
  function corpusFileHash2(content) {
52394
- return createHash5("sha256").update(JSON.stringify(content)).digest("base64url").slice(0, 32);
52703
+ return createHash6("sha256").update(JSON.stringify(content)).digest("base64url").slice(0, 32);
52395
52704
  }
52396
52705
  function stableJson2(value) {
52397
52706
  if (Array.isArray(value)) return `[${value.map((item) => stableJson2(item)).join(",")}]`;
@@ -52541,14 +52850,24 @@ function printUsage() {
52541
52850
  }
52542
52851
  async function commandStart(options) {
52543
52852
  const host = readStringFlag(options, "host") ?? DEFAULT_HOST2;
52544
- assertSafeListenHost(host, readBooleanFlag(options, "allow-network"));
52853
+ const port = readNumberFlag(options, "port") ?? DEFAULT_PORT2;
52854
+ const token = readStringFlag(options, "token") ?? process.env.WAVE3D_MCP_TOKEN ?? process.env.WAVESTUDIO_MCP_TOKEN;
52855
+ const allowNetwork = readBooleanFlag(options, "allow-network");
52856
+ assertSafeListenHost(host, allowNetwork);
52545
52857
  await ensureBundledSdkCache(options).catch((error) => {
52546
52858
  console.warn(`[WaveEngine Agent SDK] Bundled WaveEngine SDK cache prepare failed: ${error instanceof Error ? error.message : String(error)}`);
52547
52859
  });
52860
+ const reusedExistingPeer = await prepareLocalSdkPeerForStart({
52861
+ host,
52862
+ port,
52863
+ token,
52864
+ allowNetwork
52865
+ });
52866
+ if (reusedExistingPeer) return;
52548
52867
  const handle = await startWaveEngineAgentSdkServer({
52549
52868
  host,
52550
- port: readNumberFlag(options, "port") ?? DEFAULT_PORT2,
52551
- token: readStringFlag(options, "token") ?? process.env.WAVE3D_MCP_TOKEN ?? process.env.WAVESTUDIO_MCP_TOKEN,
52869
+ port,
52870
+ token,
52552
52871
  sessionTtlMs: readNumberFlag(options, "session-ttl-ms")
52553
52872
  });
52554
52873
  console.log(`[WaveEngine Agent SDK] sdkId=${handle.bridgeId}`);
@@ -3,6 +3,6 @@
3
3
  Bundled public-safe WaveEngine SDK lookup cache for wave3d-agent-sdk.
4
4
  Generated from sanitized public API/skill corpus during package build.
5
5
 
6
- cacheKey: 2026-06-17.1.p4vUxjKn3o8fS2orbJ9I0RNBdO0G6_Dg
7
- bundleHash: p4vUxjKn3o8fS2orbJ9I0RNBdO0G6_Dg
8
- zip: wave-engine-sdk-2026-06-17.1.p4vUxjKn3o8fS2orbJ9I0RNBdO0G6_Dg.zip
6
+ cacheKey: 2026-06-17.1.TzPhd-nl78ioHZ5HHdOLeV95c3YCuOJf
7
+ bundleHash: TzPhd-nl78ioHZ5HHdOLeV95c3YCuOJf
8
+ zip: wave-engine-sdk-2026-06-17.1.TzPhd-nl78ioHZ5HHdOLeV95c3YCuOJf.zip
@@ -1,21 +1,21 @@
1
1
  {
2
- "version": "2026-06-17.1.p4vUxjKn3o8fS2orbJ9I0RNBdO0G6_Dg",
2
+ "version": "2026-06-17.1.TzPhd-nl78ioHZ5HHdOLeV95c3YCuOJf",
3
3
  "formatVersion": "2026-06-17.1",
4
- "cacheKey": "2026-06-17.1.p4vUxjKn3o8fS2orbJ9I0RNBdO0G6_Dg",
5
- "bundleFileName": "wave-engine-sdk-2026-06-17.1.p4vUxjKn3o8fS2orbJ9I0RNBdO0G6_Dg.zip",
6
- "bundleHash": "p4vUxjKn3o8fS2orbJ9I0RNBdO0G6_Dg",
4
+ "cacheKey": "2026-06-17.1.TzPhd-nl78ioHZ5HHdOLeV95c3YCuOJf",
5
+ "bundleFileName": "wave-engine-sdk-2026-06-17.1.TzPhd-nl78ioHZ5HHdOLeV95c3YCuOJf.zip",
6
+ "bundleHash": "TzPhd-nl78ioHZ5HHdOLeV95c3YCuOJf",
7
7
  "generatedAt": "2026-06-06T00:00:00.000Z",
8
8
  "sourceVersions": {
9
9
  "onboarding": {
10
10
  "promptVersion": "2026-06-15.2",
11
- "promptHash": "S1t3TsiBEK-L5oyOlh3M-2aFvaLyaZ_u"
11
+ "promptHash": "YyLcFG8-h779ReTOG7GOz4mjgutRtKZw"
12
12
  },
13
13
  "apiHandbook": {
14
14
  "version": "1",
15
15
  "contentHash": "edf117cbd2b09857"
16
16
  },
17
17
  "waveSkillCorpusHash": "nhg-WfsotIdN1pRO41g97bff6RrKujrN",
18
- "sdkLookupCorpusHash": "PIjMZyPz-ALuRLJcccp75RQqxQAi3oDV"
18
+ "sdkLookupCorpusHash": "1DUg8-FDFbzXLOMm12TB3-S_y4c6Z74H"
19
19
  },
20
20
  "cacheContract": {
21
21
  "llmContextCacheOnly": [
@@ -35,7 +35,7 @@
35
35
  "searchDocuments"
36
36
  ],
37
37
  "rule": "Priority 1 always-on sections must stay in LLM chat/system context. The WaveEngine SDK local cache is public-safe retrieval data, never the only memory for core policy.",
38
- "defaultRefreshCommand": "npx -y wave3d-agent-sdk@0.2.8 cache refresh",
38
+ "defaultRefreshCommand": "npx -y wave3d-agent-sdk@0.2.9 cache refresh",
39
39
  "refreshRule": "When using WaveEngine SDK local cache, compare cacheKey, bundleHash, and sourceVersions before trusting local lookup. If any value differs, update the SDK package or reinstall its bundled SDK cache and rebuild local indexes. Do not fetch a remote SDK zip.",
40
40
  "onlineFallback": "HTTP Gateway does not provide cloud API lookup. If local Node/npm or cache is refused/unavailable, use only concrete Studio operations and already-known code; repair the local WaveEngine SDK before unfamiliar API authoring."
41
41
  },
@@ -51,7 +51,7 @@
51
51
  "mediaType": "application/json",
52
52
  "role": "lookup-guide",
53
53
  "bytes": 1310,
54
- "hash": "_bPlWbDd1MsHtcdVNv44Gh_XgmdtIYHw"
54
+ "hash": "PCkIsr75VpI_nQ4ufjVs-j13jCuh_YUL"
55
55
  },
56
56
  {
57
57
  "path": "skills/wave-skills.jsonl",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wave3d-agent-sdk",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "description": "WaveEngine Agent SDK for same-machine Wave Studio MCP plus bundled WaveEngine lookup.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",