@nativestudio/cli 0.3.0-rc.2 → 0.3.0-rc.4
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/COMPATIBILITY.json +7 -7
- package/README.md +27 -3
- package/components/runtime.json +3 -3
- package/components/runtime.tgz +0 -0
- package/dist/_chunks/{chunk-BVSTJQJI.js → chunk-6LU6GJKW.js} +1 -1
- package/dist/_chunks/chunk-CA54SKBO.js +1 -0
- package/dist/_chunks/chunk-D533YC7J.js +1 -0
- package/dist/_chunks/{chunk-C33A2DW4.js → chunk-DXJQWTLG.js} +1 -1
- package/dist/_chunks/{chunk-7S3DJ2QE.js → chunk-FU3524Z6.js} +1 -1
- package/dist/_chunks/chunk-JLOHTDP6.js +1 -0
- package/dist/_chunks/chunk-KB2GVAN7.js +1 -0
- package/dist/_chunks/{chunk-C753RRRA.js → chunk-KNFUMWDY.js} +1 -1
- package/dist/_chunks/chunk-PBEHCYR7.js +1 -0
- package/dist/_chunks/chunk-RNOIRNC3.js +1 -0
- package/dist/_chunks/chunk-VDQOSVZY.js +1 -0
- package/dist/_chunks/chunk-XZP6RNGC.js +1 -0
- package/dist/_chunks/chunk-YKOJPJZR.js +1 -0
- package/dist/_chunks/{files-FZEK2ZZJ.js → files-TTIQ7LYJ.js} +1 -1
- package/dist/_chunks/local-main-GSL2FQOG.js +1 -0
- package/dist/_chunks/local-mcp-VYHO4ZE3.js +1 -0
- package/dist/_chunks/{main-VRIQTI6R.js → main-KLXOK7QK.js} +2 -2
- package/dist/_chunks/mcp-P7W623FE.js +1 -0
- package/dist/_chunks/oauth-WJ36KWAC.js +1 -0
- package/dist/_chunks/project-connect-W7V3OALV.js +1 -0
- package/dist/_chunks/render-main-ZW6UJHGN.js +1 -0
- package/dist/_chunks/src-BXLFLNRG.js +1 -0
- package/dist/_chunks/{stdio-main-KOGQ5OWF.js → stdio-main-4Z2JVCMO.js} +1 -1
- package/dist/_types/cli/local/desktop-contract.d.ts +1382 -0
- package/dist/_types/cli/local/desktop-device-contract.d.ts +1165 -0
- package/dist/_types/cli/local/desktop-device-navigation.d.ts +3 -0
- package/dist/_types/cli/local/desktop-device-owner.d.ts +275 -0
- package/dist/_types/cli/local/desktop-device-state.d.ts +230 -0
- package/dist/_types/cli/local/desktop-owner.d.ts +552 -1
- package/dist/_types/cli/local/ledger.d.ts +62 -10
- package/dist/_types/cli/local/manager.d.ts +485 -20
- package/dist/_types/cli/local/mcp-tools.d.ts +75 -12
- package/dist/_types/cli/local/project-render-tools.d.ts +522 -0
- package/dist/_types/cli/local/releases.d.ts +10 -2
- package/dist/_types/cli/local-management.d.ts +3 -0
- package/dist/_types/cli/local-navigation.d.ts +1 -0
- package/dist/_types/contracts/delivery-manifest.d.ts +63 -27
- package/dist/_types/contracts/delivery-operations.d.ts +21 -9
- package/dist/_types/contracts/device-render.d.ts +10 -0
- package/dist/_types/contracts/exploration-recommendation.d.ts +84 -36
- package/dist/_types/contracts/final-render.d.ts +9 -0
- package/dist/_types/contracts/index.d.ts +1 -0
- package/dist/_types/contracts/local-execution/agent-context.d.ts +365 -0
- package/dist/_types/contracts/local-execution/agent-evidence.d.ts +79 -0
- package/dist/_types/contracts/local-execution/agent-grant.d.ts +31 -0
- package/dist/_types/contracts/local-execution/agent-review.d.ts +733 -46
- package/dist/_types/contracts/local-execution/device.d.ts +10 -2
- package/dist/_types/contracts/local-execution/index.d.ts +6 -0
- package/dist/_types/contracts/local-execution/ipc.d.ts +1759 -37
- package/dist/_types/contracts/local-execution/lifecycle.d.ts +48 -6
- package/dist/_types/contracts/local-execution/local-navigation.d.ts +112 -10
- package/dist/_types/contracts/local-execution/management.d.ts +394 -0
- package/dist/_types/contracts/local-execution/media-recipe.d.ts +203 -0
- package/dist/_types/contracts/local-execution/offline.d.ts +59 -0
- package/dist/_types/contracts/local-execution/preview.d.ts +7607 -159
- package/dist/_types/contracts/local-execution/work.d.ts +7674 -294
- package/dist/_types/contracts/local-execution/workspace.d.ts +136 -0
- package/dist/_types/contracts/programmatic-exploration.d.ts +42 -18
- package/dist/_types/contracts/repair-strategy.d.ts +42 -18
- package/dist/_types/contracts/review-intelligence-final-output.d.ts +42 -18
- package/dist/_types/contracts/review-intelligence.d.ts +84 -36
- package/dist/_types/contracts/rough-cut-manifest.d.ts +7 -3
- package/dist/_types/contracts/rough-cut-profile.d.ts +12 -3
- package/dist/_types/contracts/rough-cut-review.d.ts +126 -54
- package/dist/_types/contracts/rough-cut.d.ts +85 -32
- package/dist/_types/contracts/visual-layer-render.d.ts +21 -9
- package/dist/_types/sdk/local-runtime/device-client.d.ts +138 -2
- package/dist/_types/sdk/local-runtime/workspace.d.ts +181 -0
- package/dist/_types/sdk/local-runtime-client.d.ts +1294 -56
- package/dist/entry.js +1 -1
- package/dist/local-management.js +1 -1
- package/dist/local-navigation.js +1 -1
- package/dist/native/JobNative.cs +10 -0
- package/dist/native/JobRunner.cs +24 -3
- package/dist/native/NativeMain.cs +15 -0
- package/package.json +1 -1
- package/dist/_chunks/chunk-66CUOZVI.js +0 -1
- package/dist/_chunks/chunk-E57YVMQ4.js +0 -1
- package/dist/_chunks/chunk-HLKERZIE.js +0 -1
- package/dist/_chunks/chunk-K6LVS2IN.js +0 -1
- package/dist/_chunks/chunk-KHKUJXQX.js +0 -1
- package/dist/_chunks/chunk-VC3ODN3M.js +0 -1
- package/dist/_chunks/local-main-NLFS74Q4.js +0 -1
- package/dist/_chunks/local-mcp-OLHBBVNN.js +0 -1
- package/dist/_chunks/mcp-EIMXNRH3.js +0 -1
- package/dist/_chunks/oauth-F7EZGVME.js +0 -1
- package/dist/_chunks/project-connect-MXM7IY55.js +0 -1
- package/dist/_chunks/src-7F6ZEU3U.js +0 -1
package/COMPATIBILITY.json
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"protocol": "NVS_PRODUCT_COMPATIBILITY_V1",
|
|
3
3
|
"product": "@nativestudio/cli",
|
|
4
|
-
"version": "0.3.0-rc.
|
|
4
|
+
"version": "0.3.0-rc.4",
|
|
5
5
|
"source": {
|
|
6
|
-
"head": "
|
|
7
|
-
"fileDigest": "
|
|
6
|
+
"head": "156d7b90b50cbf3ed812352a2b21db1dfa7524b6",
|
|
7
|
+
"fileDigest": "cf7b7897ce82570be1b639f1e35f8b7f4f59cca2903b6d1cb75d59b83b3061d0",
|
|
8
8
|
"dirty": false,
|
|
9
|
-
"remoteMainHead": "
|
|
9
|
+
"remoteMainHead": "156d7b90b50cbf3ed812352a2b21db1dfa7524b6"
|
|
10
10
|
},
|
|
11
11
|
"node": ">=24.12 <25",
|
|
12
12
|
"discoveryProfile": "contextual-v1",
|
|
13
13
|
"accountProtocol": "NVS_CLI_ACCOUNT_V1",
|
|
14
14
|
"component": {
|
|
15
15
|
"protocol": "NVS_PRODUCT_COMPONENT_V1",
|
|
16
|
-
"version": "0.3.0-rc.
|
|
17
|
-
"byteSize":
|
|
18
|
-
"sha512": "
|
|
16
|
+
"version": "0.3.0-rc.4",
|
|
17
|
+
"byteSize": 17920699,
|
|
18
|
+
"sha512": "623e215bc98de8fa9bb41fa2afbfd832063c1410c489d1912481b4790cd5467afa8794e7386ea798ab1fd31225615b8d1c17419f64f9f4930ff5691d63a9bca8"
|
|
19
19
|
}
|
|
20
20
|
}
|
package/README.md
CHANGED
|
@@ -26,10 +26,10 @@ support NativeStudio account handoff. Registration/reset additionally requires i
|
|
|
26
26
|
configured email service. Account sessions expire; an unavailable server capability
|
|
27
27
|
is not bypassed by this package. Account login is separate from Project Agent consent.
|
|
28
28
|
|
|
29
|
-
|
|
29
|
+
Connect to the selected Project; its verified MCP URL is resolved automatically:
|
|
30
30
|
|
|
31
31
|
```sh
|
|
32
|
-
nvs connect
|
|
32
|
+
nvs connect
|
|
33
33
|
nvs status
|
|
34
34
|
nvs find --query "查找我的制作"
|
|
35
35
|
nvs capabilities search --query "找参考素材" --group materials
|
|
@@ -57,7 +57,11 @@ bootstrap, implicit PATH discovery or activation merely because npm installed co
|
|
|
57
57
|
Check first, inspect the exact plan, then approve that plan's fingerprint. Existing
|
|
58
58
|
Runtime state, SQLite recovery data, pending results and previous working slots stay
|
|
59
59
|
outside npm/npx directories. Updating CLI does not automatically upgrade the daemon.
|
|
60
|
-
|
|
60
|
+
Managed FFmpeg/ffprobe are selected from the signed catalogue when a qualified
|
|
61
|
+
distribution exists for the requested media profile. The older silent-preview
|
|
62
|
+
tools do not qualify for `STUDIO_MEDIA_V2` device preview/final rendering. That
|
|
63
|
+
profile currently requires an explicitly selected, qualified installed tool pair;
|
|
64
|
+
the Runtime checks the actual encoders, decoders, filters and hashes before use.
|
|
61
65
|
To switch deliberately, prepare a tools plan for the exact installed Runtime version:
|
|
62
66
|
|
|
63
67
|
```sh
|
|
@@ -93,3 +97,23 @@ Windows C#/PowerShell helper resources are intentional scoped execution assets.
|
|
|
93
97
|
`COMPATIBILITY.json` records protocol and component identities. The local navigation
|
|
94
98
|
and management export subpaths are experimental host integrations, not general Agent
|
|
95
99
|
permission to control installation or execute shell commands.
|
|
100
|
+
|
|
101
|
+
With a workspace and Project selected, `nvs connect` resolves the first-party
|
|
102
|
+
Project endpoint. To render, request `nvs connect --scope 'nvs:read nvs:write'`.
|
|
103
|
+
A matching current consent is reused. Device enrollment and Project consent
|
|
104
|
+
remain separate; the Agent does not receive the device key or account password.
|
|
105
|
+
|
|
106
|
+
nvs render preview --production PRODUCTION_UUID --request STABLE_REQUEST_UUID
|
|
107
|
+
nvs render final --production PRODUCTION_UUID --request ANOTHER_REQUEST_UUID
|
|
108
|
+
|
|
109
|
+
The CLI reads the native basis and stores the exact command before sending it.
|
|
110
|
+
Keep the request UUID. A repeat reads the original local receipt or reports an
|
|
111
|
+
unknown outcome without submitting a second render. You can specify `--device
|
|
112
|
+
DEVICE_UUID` where several devices are authorized. Offline or missing capacity
|
|
113
|
+
does not start a server render. The receipt identifies the device, Runtime Job,
|
|
114
|
+
Operation and render; use `nvs resume` for subsequent native status.
|
|
115
|
+
|
|
116
|
+
For an Agent running on the tenant computer, `nvs local mcp` discovers an
|
|
117
|
+
already-approved connector for the selected account when available. Its default
|
|
118
|
+
tools are read-only. Add `--with-project-renders` to expose `local_render_prepare`
|
|
119
|
+
and `local_render_start` after the separate write grant has been obtained.
|
package/components/runtime.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"protocol": "NVS_PRODUCT_COMPONENT_V1",
|
|
3
|
-
"version": "0.3.0-rc.
|
|
4
|
-
"byteSize":
|
|
5
|
-
"sha512": "
|
|
3
|
+
"version": "0.3.0-rc.4",
|
|
4
|
+
"byteSize": 17920699,
|
|
5
|
+
"sha512": "623e215bc98de8fa9bb41fa2afbfd832063c1410c489d1912481b4790cd5467afa8794e7386ea798ab1fd31225615b8d1c17419f64f9f4930ff5691d63a9bca8"
|
|
6
6
|
}
|
package/components/runtime.tgz
CHANGED
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{privateAccess}from"./chunk-
|
|
1
|
+
import{privateAccess}from"./chunk-KB2GVAN7.js";import{open,constants}from"node:fs/promises";import{resolve}from"node:path";var limit=18*1024*1024;async function readInput(path,stdin){let bytes;if(path==="-"){const chunks=[];let size=0;for await(const chunk of stdin){size+=chunk.byteLength;if(size>limit)throw Error();chunks.push(Buffer.from(chunk))}bytes=Buffer.concat(chunks)}else{const handle=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await handle.stat();if(!stat.isFile()||stat.size>limit)throw Error();bytes=Buffer.alloc(limit+1);let used=0;while(used<bytes.byteLength){const read=await handle.read(bytes,used,bytes.byteLength-used,null);if(!read.bytesRead)break;used+=read.bytesRead}if(used>limit)throw Error();bytes=bytes.subarray(0,used)}finally{await handle.close()}}const value=JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes));if(!value||typeof value!=="object"||Array.isArray(value))throw Error();return value}async function readCredential(options,environment){if(options.has("--token-file")===options.has("--token-env"))throw Error();let token;const key=options.get("--token-env");if(key){if(!/^[A-Z][A-Z0-9_]{0,127}$/.test(key))throw Error();token=environment[key]??""}else{if(process.platform==="win32")await privateAccess(resolve(options.get("--token-file")),"file");const handle=await open(options.get("--token-file"),constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await handle.stat();if(!stat.isFile()||process.platform!=="win32"&&(stat.mode&63)!==0||stat.size>8192)throw Error();const bytes=Buffer.alloc(8193);const{bytesRead}=await handle.read(bytes,0,bytes.length,0);if(bytesRead>8192)throw Error();token=bytes.subarray(0,bytesRead).toString("utf8").trim()}finally{await handle.close()}}if(!/^[A-Za-z0-9._~-]{1,8192}$/.test(token))throw Error();return"Bearer "+token}export{readInput,readCredential};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{localCliVersion}from"./chunk-2UYKJ6YN.js";import{NativeStudioMcpClient}from"./chunk-YKOJPJZR.js";import{remoteFetch,secureEndpoint}from"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{Client,StreamableHTTPClientTransport}from"@modelcontextprotocol/client";async function connectRemoteMcp(endpoint,authorization,tenantId){const url=secureEndpoint(endpoint);const client=new Client({name:"native-studio-remote-cli",version:(await localCliVersion()).version},{versionNegotiation:{mode:"auto"}});try{const transport=new StreamableHTTPClientTransport(url,{requestInit:{headers:{authorization}},fetch:remoteFetch});await client.connect(transport);return{studio:new NativeStudioMcpClient({tenantId,client}),close:()=>client.close()}}catch{await client.close();throw new NativeStudioSdkError("TRANSPORT_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","NO_WRITE")}}export{connectRemoteMcp};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{loadConnection,projectConnection}from"./chunk-KNFUMWDY.js";import{profileAuthorization}from"./chunk-DXJQWTLG.js";import{readCredential}from"./chunk-6LU6GJKW.js";import{sha256}from"./chunk-KB2GVAN7.js";import{connectRemoteMcp}from"./chunk-CA54SKBO.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";async function renderConnection(env,signal){const scope=await loadConnection(env,true);if(!scope?.scope.split(/\s+/).includes("nvs:write"))throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");const auth=await profileAuthorization(scope.profile,signal);if(auth.resource!==scope.resource)throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");return{scope,...await connectRemoteMcp(scope.resource,auth.authorization,scope.tenantId)}}async function callerRenderConnection(env,flags){const url=flags.get("--mcp-url");if(!url&&!flags.has("--token-file"))return renderConnection(env);if(!url||!flags.has("--token-file"))throw new NativeStudioSdkError("AUTHORIZATION_REQUIRED","BLOCKED","NO_WRITE");const scope=projectConnection(url),auth=await readCredential(flags,env);return{scope:{...scope,profile:"grant:"+sha256(auth)},...await connectRemoteMcp(scope.resource,auth,scope.tenantId)}}export{renderConnection,callerRenderConnection};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FileOAuthProvider,withProfileLock}from"./chunk-
|
|
1
|
+
import{FileOAuthProvider,withProfileLock}from"./chunk-FU3524Z6.js";import{readInput}from"./chunk-6LU6GJKW.js";import{remoteFetch,remoteResponse}from"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{auth}from"@modelcontextprotocol/client";import{extractWWWAuthenticateParams}from"@modelcontextprotocol/client";async function oauthResourceMetadataUrl(resource,signal){const response=await remoteResponse(resource,{method:"GET",headers:{accept:"application/json, text/event-stream"},...signal?{signal}:{}});try{if(response.status===401)return extractWWWAuthenticateParams(response).resourceMetadataUrl;if(![200,204,405,406].includes(response.status))throw Error();return void 0}finally{await response.body?.cancel()}}function uncertainExchange(){throw new NativeStudioSdkError("OAUTH_OUTCOME_UNKNOWN","INTERNAL_OPERATIONAL_FAILURE","UNKNOWN")}async function beginExchange(provider,kind){if(provider.data.pendingExchange)uncertainExchange();provider.data.version=2;provider.data.pendingExchange=kind;await provider.save()}async function runOAuthCommand(argv,stdin,signal){const fetchFn=(input,init)=>remoteFetch(input,{...init,...signal?{signal:AbortSignal.any([signal,...init?.signal?[init.signal]:[]])}:{}});const[command,...args]=argv,options=new Map;for(let i=0;i<args.length;i+=2){const key=args[i],value=args[i+1];if(!key||!["--profile","--mcp-url","--callback","--scope","--input"].includes(key)||!value||value.startsWith("--")||options.has(key))throw Error();options.set(key,value)}const path=options.get("--profile");if(!path)throw Error();return withProfileLock(path,async()=>{if(command==="auth-start"){if(!options.has("--mcp-url")||!options.has("--callback")||options.has("--input"))throw Error();const provider2=await FileOAuthProvider.create(path,options.get("--mcp-url"),options.get("--callback"),options.get("--scope")??"nvs:read nvs:write");const resourceMetadataUrl=await oauthResourceMetadataUrl(provider2.data.resource,signal);await auth(provider2,{serverUrl:provider2.data.resource,scope:provider2.data.scope,...resourceMetadataUrl?{resourceMetadataUrl}:{},fetchFn});return{exitCode:0,output:{semanticStatus:"NEEDS_INPUT",authorizationUrl:provider2.data.authorizationUrl,profileSaved:true}}}if(!options.has("--input")||options.size!==2||command!=="auth-complete")throw Error();const provider=await FileOAuthProvider.load(path),raw=await readInput(options.get("--input"),stdin);if(typeof raw.callbackUrl!=="string"||Object.keys(raw).some(k=>k!=="callbackUrl"))throw Error();const url=new URL(raw.callbackUrl),expected=new URL(provider.data.redirect);if(url.origin!==expected.origin||url.pathname!==expected.pathname||url.searchParams.getAll("code").length!==1||url.searchParams.getAll("state").length!==1||url.searchParams.getAll("iss").length!==1||url.searchParams.get("state")!==provider.data.state)throw Error();const code=url.searchParams.get("code"),iss=url.searchParams.get("iss");const issuer=provider.data.discovery?.authorizationServerMetadata?.issuer??provider.data.discovery?.authorizationServerUrl;if(issuer&&issuer!==iss)throw Error();await beginExchange(provider,"CODE");try{const result=await auth(provider,{serverUrl:provider.data.resource,authorizationCode:code,iss,fetchFn});if(result!=="AUTHORIZED"||provider.data.pendingExchange||!provider.data.token)uncertainExchange()}catch{uncertainExchange()}return{exitCode:0,output:{semanticStatus:"SUCCESS",connected:true,expiresAt:provider.data.expiresAt}}})}async function profileAuthorization(path,signal){return withProfileLock(path,async()=>{const provider=await FileOAuthProvider.load(path);if(provider.data.pendingExchange)uncertainExchange();if(!provider.data.token)throw Error();if(!provider.data.expiresAt||provider.data.expiresAt<Date.now()+3e4){await beginExchange(provider,"REFRESH");try{const result=await auth(provider,{serverUrl:provider.data.resource,fetchFn:(input,init)=>remoteFetch(input,{...init,...signal?{signal:AbortSignal.any([signal,...init?.signal?[init.signal]:[]])}:{}})});if(result!=="AUTHORIZED"||provider.data.pendingExchange)uncertainExchange()}catch{uncertainExchange()}}return{resource:provider.data.resource,authorization:"Bearer "+provider.data.token.access_token}})}export{runOAuthCommand,profileAuthorization};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{privateAccess,privateDirectory,write}from"./chunk-KB2GVAN7.js";import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{randomBytes}from"node:crypto";import{open,unlink,constants}from"node:fs/promises";import{dirname,resolve}from"node:path";var FileOAuthProvider=class _FileOAuthProvider{constructor(path,data){this.path=path;this.data=data}path;data;static async create(path,resource,redirect,scope){secureEndpoint(resource);secureEndpoint(redirect);if(!["nvs:read","nvs:read nvs:write"].includes(scope))throw Error();if(process.platform==="win32")await privateDirectory(dirname(resolve(path)));const data={version:1,resource,redirect,scope,state:randomBytes(24).toString("base64url")};await write(resolve(path),JSON.stringify(data),true);return new _FileOAuthProvider(path,data)}static async load(path){if(process.platform==="win32")await privateAccess(resolve(path),"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);let data;try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||(stat.mode&63)!==0)||stat.size>65536)throw Error();const bytes=Buffer.alloc(65537);const{bytesRead}=await file.read(bytes,0,bytes.length,0);if(bytesRead>65536)throw Error();data=JSON.parse(bytes.subarray(0,bytesRead).toString("utf8"))}finally{await file.close()}if(![1,2].includes(data.version)||typeof data.state!=="string"||data.state.length<16)throw Error();if(data.pendingExchange!==void 0&&!["CODE","REFRESH"].includes(data.pendingExchange))throw Error();if(data.version===2!==(data.pendingExchange!==void 0))throw Error();secureEndpoint(data.resource);secureEndpoint(data.redirect);if(!["nvs:read","nvs:read nvs:write"].includes(data.scope))throw Error();return new _FileOAuthProvider(path,data)}async save(){if(process.platform==="win32")await privateDirectory(dirname(resolve(this.path)));await write(resolve(this.path),JSON.stringify(this.data))}get redirectUrl(){return this.data.redirect}get clientMetadata(){return{client_name:"NativeStudio CLI",redirect_uris:[this.data.redirect],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],scope:this.data.scope,application_type:"native"}}state(){return this.data.state}clientInformation(){return this.data.client}async saveClientInformation(value){this.data.client=value;await this.save()}tokens(){return this.data.token}async saveTokens(value){this.data.token=value;this.data.expiresAt=Date.now()+(value.expires_in??600)*1e3;this.data.version=1;delete this.data.pendingExchange;await this.save()}async redirectToAuthorization(url){this.data.authorizationUrl=url.href;await this.save()}async saveCodeVerifier(value){this.data.verifier=value;await this.save()}codeVerifier(){if(!this.data.verifier)throw Error();return this.data.verifier}async saveDiscoveryState(value){this.data.discovery=value;await this.save()}discoveryState(){return this.data.discovery}};async function withProfileLock(path,action){if(process.platform==="win32")await privateDirectory(dirname(resolve(path)));const file=await open(path+".lock","wx",384);try{return await action()}finally{await file.close();await unlink(path+".lock")}}export{FileOAuthProvider,withProfileLock};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{fail,localSocketPath,privateAccess,privateDirectory,read,sha256,sha512}from"./chunk-KB2GVAN7.js";import{CaptionRenderStyleSchema,FinalRenderAdmissionSchema,FinalRenderManifestReaderSchema,FinalRenderStartSchema,KeyframeObservationSchema,NativeRuntimePublicKeySchema,ReviewEvidenceMediaSchema,ReviewIntelligenceBasisSchema,ReviewIntelligenceContextResultSchema,RoughCutAdmissionSchema,RoughCutManifestReaderSchema,RoughCutRequirementSchema,RoughCutStartSchema,RoughCutTechnicalSchema,ValidateReviewIntelligenceSchema,VideoReviewRequirementSchema,VideoTechnicalMetadataSchema,VisualLayerCompositionSchema,VisualRequirementSchema}from"./chunk-PBEHCYR7.js";import{OperationIdSchema}from"./chunk-VPYAXWXY.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{z as z2}from"zod";import{z}from"zod";var LocalIdSchema=z.uuid().transform(v=>v.toLowerCase());var LocalDigestSchema=z.string().length(64).regex(/^[0-9a-f]{64}$/);var LocalRevisionSchema=z.int().positive();var LocalTimeSchema=z.iso.datetime({offset:true});var LocalPackageVersionSchema=z.string().max(120).regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/).refine(v=>v===v.trim());var LocalProjectScopeSchema=z.strictObject({tenantId:LocalIdSchema,projectId:LocalIdSchema});var LocalWorkScopeSchema=LocalProjectScopeSchema.extend({productionId:LocalIdSchema,runtimeJobId:LocalIdSchema});var LocalPlacementPolicySchema=z.discriminatedUnion("mode",[z.strictObject({mode:z.literal("local-only"),deviceId:LocalIdSchema}),z.strictObject({mode:z.literal("local-preferred"),deviceId:LocalIdSchema}),z.strictObject({mode:z.literal("cloud-only")})]);var LocalPlacementAvailabilitySchema=z.discriminatedUnion("status",[z.strictObject({status:z.literal("AVAILABLE"),deviceId:LocalIdSchema}),z.strictObject({status:z.literal("UNAVAILABLE"),deviceId:LocalIdSchema,reason:z.enum(["OFFLINE","UNQUALIFIED","BUSY"])}),z.strictObject({status:z.literal("DENIED"),reason:z.enum(["FORBIDDEN","APPROVAL_REQUIRED","INVALID_INPUT"])})]);var LocalDevicePlatformSchema=z2.strictObject({os:z2.enum(["darwin","linux","win32"]),architecture:z2.enum(["x64","arm64"])});var EnrollLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,requestId:LocalIdSchema,label:z2.string().trim().min(1).max(120),platform:LocalDevicePlatformSchema,runtimeVersion:LocalPackageVersionSchema,publicKey:NativeRuntimePublicKeySchema});var LocalDeviceViewSchema=EnrollLocalDeviceSchema.omit({requestId:true}).extend({deviceId:LocalIdSchema,revision:LocalRevisionSchema,enrolledByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,verifiedAt:LocalTimeSchema.nullable(),revokedAt:LocalTimeSchema.nullable()}).refine(v=>[v.verifiedAt,v.revokedAt].every(time=>time===null||Date.parse(time)>=Date.parse(v.createdAt)));var LocalDeviceChallengeSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z2.string().min(1).max(2048),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>{const ttl=Date.parse(v.expiresAt)-Date.parse(v.issuedAt);return ttl>0&&ttl<=3e5});var LocalDeviceProofClaimsSchema=z2.strictObject({protocol:z2.literal("NVS_LOCAL_DEVICE_PROOF_V1"),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,audience:z2.string().min(1).max(2048),jti:LocalIdSchema,iat:z2.int().nonnegative(),exp:z2.int().positive()}).refine(v=>v.exp>v.iat&&v.exp-v.iat<=60);var ProveLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,challengeId:LocalIdSchema,assertion:z2.string().max(4096).regex(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var GrantLocalDeviceSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,executionPolicy:z2.literal("DEVICE_ONLY").optional(),deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,expectedRevision:z2.int().nonnegative(),expiresAt:LocalTimeSchema,capability:z2.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2"])});var LocalDeviceGrantSchema=GrantLocalDeviceSchema.omit({requestId:true,expectedRevision:true}).extend({grantId:LocalIdSchema,revision:LocalRevisionSchema,approvedByPrincipalId:LocalIdSchema,createdAt:LocalTimeSchema,revokedAt:LocalTimeSchema.nullable()}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.createdAt));var RevokeLocalDeviceGrantSchema=LocalProjectScopeSchema.extend({grantId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});var RevokeLocalDeviceSchema=z2.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema,requestId:LocalIdSchema,expectedRevision:LocalRevisionSchema});import{z as z5}from"zod";import{z as z4}from"zod";import{z as z3}from"zod";var pixel=z3.int().nonnegative().max(4096);var dimension=z3.int().positive().max(4096);var frame=z3.int().nonnegative().max(1800);var sample=z3.int().nonnegative().max(288e4);var rectangle=z3.strictObject({x:pixel,y:pixel,width:dimension,height:dimension});var window=z3.strictObject({start:sample,count:sample});var source=z3.strictObject({representationId:z3.uuid(),checksum:LocalDigestSchema,byteSize:z3.int().positive().max(134217728)});var LocalMediaRecipeSchema=z3.strictObject({protocol:z3.literal("NVS_RESOLVED_MEDIA_RECIPE_V2"),family:z3.enum(["ROUGH_CUT_RENDER","FINAL_RENDER"]),width:dimension,height:dimension,totalFrames:z3.int().min(900).max(1800),crf:z3.union([z3.literal(18),z3.literal(23)]),algorithm:z3.enum(["ORDERED_TRIM_CUT_V1","ORDERED_COMPOSE_V2"]),clips:z3.array(z3.strictObject({representationId:z3.uuid(),technical:VideoTechnicalMetadataSchema,sourceInMs:z3.int().nonnegative().max(6e4),sourceOutMs:z3.int().positive().max(6e4),startFrame:frame,frameCount:z3.int().positive().max(1800),overlapFrames:frame,crop:rectangle.nullable(),viewport:rectangle})).min(1).max(32),caption:z3.strictObject({style:CaptionRenderStyleSchema,references:z3.array(z3.strictObject({representationId:z3.uuid(),expectedUtf8:z3.string().max(65536)})).length(2),cues:z3.array(z3.strictObject({ordinal:z3.int().nonnegative().max(512),startFrame:frame,endFrame:frame,fontSize:z3.int().min(16).max(256),margin:pixel,text:z3.string().min(1).max(2e3)})).min(1).max(512)}).nullable(),audio:z3.strictObject({algorithm:z3.literal("PCM_WINDOW_MIX_AAC_V1"),tracks:z3.array(source.extend({channels:z3.union([z3.literal(1),z3.literal(2)]),sampleCount:z3.int().positive().max(288e4),sourceIn:sample,sourceOut:sample,start:sample,count:sample,gain:z3.int().nonnegative().max(1e3),duck:z3.int().nonnegative().max(1e3),duckWindows:z3.array(window).max(512)})).min(1).max(266)}).nullable(),graphics:z3.array(source.extend({contentType:z3.enum(["image/png","image/webp"]),sourceWidth:dimension,sourceHeight:dimension,width:dimension,height:dimension,x:pixel,y:pixel,startFrame:frame,endFrame:frame,opacity:z3.number().min(.1).max(1)})).max(8),visual:z3.strictObject({composition:VisualLayerCompositionSchema,plans:z3.array(z3.strictObject({id:z3.uuid(),startFrame:frame,endFrame:frame,width:dimension,height:dimension,x:pixel,y:pixel,opacityPermille:z3.int().min(0).max(1e3)})).max(8)}).nullable()}).superRefine((r,ctx)=>{if(r.width%2||r.height%2||r.clips.some(c=>c.viewport.x+c.viewport.width>r.width||c.viewport.y+c.viewport.height>r.height||c.sourceOutMs<=c.sourceInMs)||r.audio?.tracks.some(t=>t.sourceIn>=t.sourceOut||t.sourceOut>t.sampleCount||t.start+t.count>r.totalFrames*1600))ctx.addIssue({code:"custom",message:"Invalid bounded execution geometry or sample window"})});var previewProfile=z4.strictObject({kind:z4.literal("ROUGH_CUT_PREVIEW_V1"),profileId:z4.literal("PREVIEW_H264_480P_V1"),contractDigest:LocalDigestSchema});var studioProfile=z4.strictObject({kind:z4.literal("STUDIO_MEDIA_V2"),profileId:z4.literal("STUDIO_MEDIA_V2"),contractDigest:LocalDigestSchema});var LocalExecutionProfileSchema=z4.discriminatedUnion("kind",[previewProfile,studioProfile]);var LocalToolchainSchema=z4.strictObject({platform:LocalDevicePlatformSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema,ffmpeg:z4.strictObject({version:z4.string().min(1).max(160),binaryDigest:LocalDigestSchema}),ffprobe:z4.strictObject({version:z4.string().min(1).max(160),binaryDigest:LocalDigestSchema}),profile:LocalExecutionProfileSchema,supported:z4.array(z4.strictObject({profile:LocalExecutionProfileSchema,rendererVersion:LocalPackageVersionSchema,rendererDigest:LocalDigestSchema})).max(4).optional()});var frozen=LocalWorkScopeSchema.extend({protocol:z4.literal("NVS_LOCAL_WORK_V1"),operationId:OperationIdSchema,renderId:LocalIdSchema,productionRevision:LocalRevisionSchema,executionClass:z4.enum(["LIVE","TEST_ONLY"]),policy:LocalPlacementPolicySchema,profile:previewProfile,manifest:RoughCutManifestReaderSchema,manifestFingerprint:LocalDigestSchema,sources:z4.array(z4.strictObject({artifactId:LocalIdSchema,representationId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z4.int().positive(),contentType:z4.string().min(1).max(100)})).min(1).max(512)});var studio=frozen.extend({protocol:z4.literal("NVS_LOCAL_WORK_V2"),profile:studioProfile,manifest:z4.union([RoughCutManifestReaderSchema,FinalRenderManifestReaderSchema]),recipe:LocalMediaRecipeSchema,recipeFingerprint:LocalDigestSchema});var LocalFrozenWorkSchema=z4.discriminatedUnion("protocol",[frozen,studio]).superRefine((v,ctx)=>{const t=v.manifest.timeline;if(t.tenantId!==v.tenantId||t.projectId!==v.projectId||t.productionId!==v.productionId||t.executionClass!==v.executionClass)ctx.addIssue({code:"custom",message:"Frozen manifest scope/class mismatch"});if(new Set(v.sources.map(s=>s.representationId)).size!==v.sources.length)ctx.addIssue({code:"custom",message:"Duplicate source representation"});if(v.protocol==="NVS_LOCAL_WORK_V2"&&(v.recipe.width!==v.manifest.profile.width||v.recipe.height!==v.manifest.profile.height||v.recipe.totalFrames!==v.manifest.totalFrames||v.recipe.family==="FINAL_RENDER"!=="selection"in v.manifest))ctx.addIssue({code:"custom",message:"Recipe must match its native render family and geometry"})});var LocalLeaseBindingSchema=LocalWorkScopeSchema.extend({attemptId:LocalIdSchema,assignmentRevision:LocalRevisionSchema,workerId:z4.string().min(1).max(200),workFingerprint:LocalDigestSchema,toolchainFingerprint:LocalDigestSchema});var target=z4.discriminatedUnion("kind",[z4.strictObject({kind:z4.literal("DEVICE"),deviceId:LocalIdSchema,deviceRevision:LocalRevisionSchema,grantId:LocalIdSchema,grantRevision:LocalRevisionSchema}),z4.strictObject({kind:z4.literal("SERVER")})]);var LocalExecutionLeaseSchema=LocalLeaseBindingSchema.extend({target,issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt));var LocalWorkAssignmentSchema=z4.strictObject({work:LocalFrozenWorkSchema,lease:LocalExecutionLeaseSchema,toolchain:LocalToolchainSchema}).superRefine(({work,lease,toolchain},ctx)=>{if(["tenantId","projectId","productionId","runtimeJobId"].some(k=>work[k]!==lease[k]))ctx.addIssue({code:"custom",message:"Assignment work scope mismatch"});const p=work.policy,t=lease.target;if(p.mode==="cloud-only"&&t.kind!=="SERVER"||p.mode==="local-only"&&t.kind!=="DEVICE"||t.kind==="DEVICE"&&(p.mode==="cloud-only"||p.deviceId!==t.deviceId))ctx.addIssue({code:"custom",message:"Assignment contradicts placement policy"});if(work.profile.contractDigest!==toolchain.profile.contractDigest)ctx.addIssue({code:"custom",message:"Unqualified execution profile"})});var StartLocalPreviewSchema=RoughCutStartSchema.omit({deviceExecution:true}).extend({placement:LocalPlacementPolicySchema,localProfile:z5.literal("STUDIO_MEDIA_V2").optional()});var LocalDeviceScopeSchema=z5.strictObject({tenantId:LocalIdSchema,deviceId:LocalIdSchema});var LocalDeviceSessionSchema=z5.strictObject({...LocalDeviceScopeSchema.shape,expiresAt:LocalTimeSchema,credential:z5.string().length(43).regex(/^[A-Za-z0-9_-]+$/).meta({writeOnly:true})});var LocalDeviceHeartbeatSchema=LocalDeviceScopeSchema.extend({toolchain:LocalToolchainSchema,available:z5.boolean(),maxConcurrentJobs:z5.int().min(1).max(2).optional()});var ClaimLocalPreviewSchema=LocalProjectScopeSchema.extend({requestId:LocalIdSchema,deviceId:LocalIdSchema});var LocalOutputStageSchema=LocalLeaseBindingSchema.extend({uploadRequestId:LocalIdSchema,role:z5.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z5.int().positive().max(128*1024*1024)});var LocalOutputTicketSchema=z5.strictObject({receiptId:LocalIdSchema,role:z5.enum(["VIDEO","POSTER"]),checksumSha256:LocalDigestSchema,byteSize:z5.int().positive(),uploaded:z5.boolean()});var LocalSourceRequestSchema=LocalLeaseBindingSchema.extend({representationId:LocalIdSchema});var LocalProofChallengeRequestSchema=LocalDeviceScopeSchema.extend({deviceRevision:z5.int().positive()});var LocalPreviewPlacementViewSchema=z5.strictObject({target:z5.enum(["DEVICE","SERVER"]),reason:z5.enum(["LOCAL_AVAILABLE","CLOUD_ONLY","OFFLINE","UNQUALIFIED","BUSY","LEASE_RECOVERY"]),policy:LocalPlacementPolicySchema});var LocalDeviceTransportConfigurationSchema=z5.strictObject({endpoint:z5.string().url().max(2048),tenantId:LocalIdSchema,deviceId:LocalIdSchema,deviceRevision:z5.int().positive(),projects:z5.array(LocalProjectScopeSchema).min(1).max(20),privateKeyFile:z5.string().min(1).max(4096),platform:LocalDevicePlatformSchema});var LocalPreviewAdmissionSchema=RoughCutAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var StartLocalFinalRenderSchema=FinalRenderStartSchema.omit({deviceExecution:true}).extend({placement:LocalPlacementPolicySchema});var LocalFinalRenderAdmissionSchema=FinalRenderAdmissionSchema.extend({placement:LocalPreviewPlacementViewSchema});var LocalClaimReceiptSchema=z5.strictObject({found:z5.boolean(),assignment:LocalWorkAssignmentSchema.nullable()});var LocalWorkStateSchema=z5.strictObject({binding:LocalLeaseBindingSchema,status:z5.enum(["ACTIVE","FENCED","OUTCOME_UNKNOWN"]),assignment:LocalWorkAssignmentSchema.nullable()});import{z as z14}from"zod";import{z as z7}from"zod";import{z as z6}from"zod";var executable=z6.strictObject({path:z6.string().min(1).max(4096),digest:LocalDigestSchema});var LocalToolSelectionSchema=z6.strictObject({mode:z6.enum(["MANAGED","INSTALLED"]),ffmpeg:executable,ffprobe:executable});var LocalRuntimeDescriptorSchema=z7.strictObject({protocol:z7.literal("NVS_RUNTIME_DESCRIPTOR_V1"),version:LocalPackageVersionSchema,node:z7.strictObject({major:z7.literal(24),minMinor:z7.literal(12)}),platform:LocalDevicePlatformSchema,ipcProtocol:z7.literal("NVS_LOCAL_IPC_V1"),workProtocol:z7.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"]),journalSchema:z7.literal(1),rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema,compatibleRenderers:z7.array(z7.strictObject({rendererDigest:LocalDigestSchema,profileDigest:LocalDigestSchema})).max(4).optional()});var LocalSessionConnectorSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_CONNECTOR_V1"),stateDirectory:z7.string().min(1).max(4096),credential:z7.string().length(43).regex(/^[A-Za-z0-9_-]{43}$/),expiresAt:LocalTimeSchema,projects:z7.array(LocalProjectScopeSchema).min(1).max(100)});var LocalManagementInventorySchema=z7.strictObject({runtimeRevision:z7.int().positive(),descriptor:LocalRuntimeDescriptorSchema,activeProcesses:z7.int().nonnegative(),pendingExecutions:z7.int().nonnegative(),pendingRequests:z7.int().nonnegative(),pendingRenderers:z7.array(LocalDigestSchema).max(64)});var LocalReleaseAssetSchema=z7.strictObject({url:z7.string().url().max(2048),byteSize:z7.int().positive().max(256*1024*1024),sha512:z7.string().length(128).regex(/^[0-9a-f]{128}$/)});var LocalReleaseSchema=z7.strictObject({descriptor:LocalRuntimeDescriptorSchema,package:LocalReleaseAssetSchema,tools:z7.strictObject({ffmpeg:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema}),ffprobe:LocalReleaseAssetSchema.extend({sha256:LocalDigestSchema})}).nullable()});var LocalReleaseCatalogueSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_RELEASE_CATALOGUE_V1"),issuedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,releases:z7.array(LocalReleaseSchema).min(1).max(32)}).refine(v=>Date.parse(v.expiresAt)>Date.parse(v.issuedAt)&&Date.parse(v.expiresAt)-Date.parse(v.issuedAt)<=7*864e5&&new Set(v.releases.map(r=>[r.descriptor.version,r.descriptor.platform.os,r.descriptor.platform.architecture].join(":"))).size===v.releases.length);var LocalSignedCatalogueSchema=z7.strictObject({catalogue:LocalReleaseCatalogueSchema,signature:z7.string().length(86).regex(/^[A-Za-z0-9_-]{85}[AQgw]$/)});var LocalToolChoiceSchema=z7.discriminatedUnion("mode",[z7.strictObject({mode:z7.literal("MANAGED")}),LocalToolSelectionSchema.extend({mode:z7.literal("INSTALLED")})]);var LocalUpdatePlanSchema=z7.strictObject({protocol:z7.literal("NVS_LOCAL_UPDATE_PLAN_V1"),planId:LocalIdSchema,installationRevision:z7.int().nonnegative(),runtimeRevision:z7.int().positive().nullable(),catalogueFingerprint:LocalDigestSchema,trustFingerprint:LocalDigestSchema.optional(),release:LocalReleaseSchema,toolSelection:LocalToolChoiceSchema.optional(),fingerprint:LocalDigestSchema,createdAt:LocalTimeSchema,expiresAt:LocalTimeSchema});var LocalClientNextActionSchema=z7.strictObject({surface:z7.enum(["CLI","LOCAL_IPC","REMOTE"]),operation:z7.enum(["runtime.status","local.configure","local.install","local.start","local.connect","local.grant","local.status","local.doctor","local.stop","local.update.check","local.update.prepare","local.update.apply","local.update.reconcile","execution.inspect","rough_cut_get","operation_get"]),availability:z7.enum(["AVAILABLE","BLOCKED"]),reason:z7.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED","USER_APPROVAL_REQUIRED","TRUST_REQUIRED","UNAVAILABLE"])});import{z as z13}from"zod";import{z as z8}from"zod";var LocalOfflineSnapshotSchema=z8.strictObject({projectId:z8.uuid(),title:z8.string().min(1).max(200),savedAt:LocalTimeSchema,expiresAt:LocalTimeSchema,productions:z8.array(z8.strictObject({id:z8.uuid(),title:z8.string().max(200)})).max(40),possiblyTruncated:z8.boolean()}).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var text=z8.string().max(4e3).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=8192);var LocalOfflineCallSchema=z8.discriminatedUnion("action",[z8.strictObject({action:z8.enum(["list","forget"]),key:LocalDigestSchema}),z8.strictObject({action:z8.literal("retain"),key:LocalDigestSchema,snapshot:LocalOfflineSnapshotSchema}),z8.strictObject({action:z8.literal("draft"),key:LocalDigestSchema,projectId:z8.uuid(),text,expectedRevision:z8.int().nonnegative()})]);var LocalOfflinePageSchema=z8.strictObject({historical:z8.literal(true),items:z8.array(z8.strictObject({snapshot:LocalOfflineSnapshotSchema,draft:z8.strictObject({text,revision:z8.int().nonnegative()})})).max(3)});import{z as z10}from"zod";import{z as z9}from"zod";var QualifiedLocalAgentVersionSchema=z9.enum(["0.164.0","0.165.0"]);var LocalAgentGrantSchema=z9.strictObject({protocol:z9.literal("NVS_CODEX_REVIEW_GRANT_V1"),binary:z9.string().min(1).max(4096).refine(v=>/^(?:\/|[A-Za-z]:[\\/])/.test(v)),binaryDigest:z9.string().regex(/^[a-f0-9]{64}$/),version:QualifiedLocalAgentVersionSchema,model:z9.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$/),reasoningEffort:z9.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z9.string().trim().min(1).max(100),inference:z9.literal("REMOTE_OPENAI"),remoteUseApproved:z9.literal(true),imageDisclosureApproved:z9.literal(true).optional(),mediaDisclosureApproved:z9.literal(true).optional(),projects:z9.array(LocalProjectScopeSchema).min(1).max(100),expiresAt:z9.iso.datetime({offset:true})});var LocalAgentMediaInputSchema=z10.strictObject({profile:z10.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),contentType:z10.enum(["image/png","image/jpeg","image/webp","video/mp4"]),byteSize:z10.int().positive().max(134217728),width:z10.int().positive().max(4096),height:z10.int().positive().max(4096),durationMs:z10.int().positive().max(6e4).optional(),frameRate:z10.union([z10.literal(24),z10.literal(30)]).optional(),hasAudio:z10.boolean().optional()}).refine(v=>v.contentType==="video/mp4"?!!v.durationMs&&!!v.frameRate:!v.durationMs&&!v.frameRate&&v.hasAudio===void 0);var sha=z10.string().regex(/^[a-f0-9]{64}$/);var LocalAgentEvidenceReceiptSchema=z10.strictObject({protocol:z10.literal("NVS_AGENT_DERIVED_EVIDENCE_V1"),draftId:z10.uuid(),media:ReviewEvidenceMediaSchema,ffmpegDigest:sha,ffprobeDigest:sha,attachment:z10.strictObject({checksumSha256:sha,byteSize:z10.int().positive().max(8388608),width:z10.int().positive().max(4096),height:z10.int().positive().max(4096)}),timestampsMs:z10.array(z10.number().nonnegative().max(6e4)).max(6),audio:z10.strictObject({sampleRateHz:z10.literal(48e3),channels:z10.literal(1),samples:z10.int().positive().max(2881024),peak:z10.number().min(0).max(1),rms:z10.number().min(0).max(1),clippedSamples:z10.int().nonnegative().max(2881024)}).nullable(),limitations:z10.tuple([z10.literal("SAMPLED_FRAMES_ARE_NOT_FULL_PLAYBACK"),z10.literal("AUDIO_STATISTICS_ARE_NOT_LISTENING_OR_TRANSCRIPTION")])});var LocalAgentDiscoverySchema=z10.strictObject({candidate:z10.strictObject({binary:z10.string().min(1).max(4096),binaryDigest:sha,version:z10.string().regex(/^\d+\.\d+\.\d+$/),qualified:z10.boolean()}).nullable(),configured:LocalAgentGrantSchema.nullable()});import{z as z11}from"zod";var LocalResourcePolicySchema=z11.strictObject({mode:z11.enum(["CONTINUOUS","IDLE_ONLY"]).default("CONTINUOUS"),idleAfterSeconds:z11.int().min(30).max(3600).default(300),maxConcurrentJobs:z11.int().min(1).max(2).default(1),cpuCores:z11.union([z11.literal(1),z11.literal(2)]).default(2),memoryMiB:z11.int().min(512).max(4096).default(4096),cacheQuotaBytes:z11.int().min(512*1024*1024).max(32*1024*1024*1024).default(1024*1024*1024)});var LocalResourceSettingsSchema=z11.strictObject({revision:z11.int().nonnegative(),policy:LocalResourcePolicySchema});var LocalExecutionProgressSchema=z11.strictObject({stage:z11.enum(["WAITING","DOWNLOADING","EXECUTING","UPLOADING","AWAITING_ACCEPTANCE","COMPLETE","RECOVERY_REQUIRED","FENCED"]),downloadedBytes:z11.int().nonnegative(),sourceBytes:z11.int().nonnegative(),uploadedBytes:z11.int().nonnegative(),outputBytes:z11.int().nonnegative(),lastError:z11.strictObject({code:z11.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema}).nullable()});var LocalStorageInspectionSchema=z11.strictObject({cacheBytes:z11.int().nonnegative(),protectedBytes:z11.int().nonnegative(),reclaimableBytes:z11.int().nonnegative(),transferBytes:z11.int().nonnegative(),journalBytes:z11.int().nonnegative(),reviewBytes:z11.int().nonnegative().optional(),ownerStagingBytes:z11.int().nonnegative().optional(),availableDiskBytes:z11.int().nonnegative(),quotaBytes:z11.int().positive(),overQuota:z11.boolean()});var LocalWorkspaceInspectionSchema=z11.strictObject({settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,scheduling:z11.strictObject({state:z11.enum(["READY","WAITING_FOR_IDLE","AT_CAPACITY","DRAINING"]),activeJobs:z11.int().nonnegative(),idleObservationCurrent:z11.boolean()})});var LocalDiagnosticsSchema=z11.strictObject({protocol:z11.literal("NVS_LOCAL_DIAGNOSTICS_V1"),createdAt:LocalTimeSchema,runtimeVersion:z11.string().min(1).max(80),runtimeRevision:LocalRevisionSchema,settings:LocalResourceSettingsSchema,storage:LocalStorageInspectionSchema,recordCounts:z11.record(z11.string().regex(/^[A-Z_]{1,40}$/),z11.int().nonnegative()),failures:z11.array(z11.strictObject({taskFingerprint:z11.string().regex(/^[a-f0-9]{64}$/),code:z11.string().regex(/^[A-Z][A-Z0-9_]{0,79}$/),observedAt:LocalTimeSchema})).max(32)});import{z as z12}from"zod";function canonicalLocalJson(value){if(value===null||typeof value==="string"||typeof value==="boolean")return JSON.stringify(value);if(typeof value==="number"&&Number.isFinite(value))return JSON.stringify(value);if(Array.isArray(value))return"["+value.map(canonicalLocalJson).join(",")+"]";if(typeof value==="object")return"{"+Object.entries(value).filter(([,v])=>v!==void 0).sort(([a],[b])=>a<b?-1:a>b?1:0).map(([k,v])=>JSON.stringify(k)+":"+canonicalLocalJson(v)).join(",")+"}";throw new Error("Fingerprint input must be finite JSON data")}var sha2=z12.string().regex(/^[a-f0-9]{64}$/);var qualifiedVersion=QualifiedLocalAgentVersionSchema;var LocalAgentSnapshotSchema=z12.strictObject({basis:ReviewIntelligenceBasisSchema,productionRevision:z12.int().positive(),reviewVersion:z12.int().nonnegative(),executionClass:z12.enum(["LIVE","TEST_ONLY"]),media:ReviewEvidenceMediaSchema,requirements:z12.array(z12.union([VisualRequirementSchema,VideoReviewRequirementSchema,RoughCutRequirementSchema])).min(1).max(64),evidence:LocalAgentMediaInputSchema.optional(),image:z12.strictObject({contentType:z12.literal("image/png"),byteSize:z12.int().positive().max(8388608),width:z12.int().positive().max(4096),height:z12.int().positive().max(4096)}).optional()}).refine(v=>!v.image||!v.evidence&&v.basis.target.kind==="IMAGE").refine(v=>v.basis.target.kind==="IMAGE"||!v.evidence||v.evidence.contentType==="video/mp4").refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=32768).refine(v=>new Set(v.requirements.map(r=>r.key)).size===v.requirements.length);var LocalAgentProbeSchema=z12.strictObject({configured:z12.boolean(),available:z12.boolean(),reason:z12.enum(["GRANT_REQUIRED","READY","RUNTIME_UNAVAILABLE","GRANT_EXPIRED"]),grantFingerprint:sha2.nullable(),inference:z12.literal("REMOTE_OPENAI")});var LocalAgentPlanSchema=z12.strictObject({protocol:z12.enum(["NVS_LOCAL_AGENT_REVIEW_V1","NVS_LOCAL_AGENT_REVIEW_V2"]),id:z12.uuid(),grantFingerprint:sha2,snapshot:LocalAgentSnapshotSchema,expiresAt:z12.iso.datetime({offset:true}),fingerprint:sha2});var LocalAgentMetadataAnswerSchema=z12.strictObject({summary:z12.string().trim().min(1).max(1500),observations:z12.array(z12.strictObject({key:z12.string().min(1).max(220),observed:z12.string().trim().min(1).max(1e3)})).min(1).max(64)});var LocalAgentPixelAnswerSchema=z12.strictObject({summary:z12.string().trim().min(1).max(1500),imageReadback:z12.string().trim().min(1).max(800),observations:z12.array(KeyframeObservationSchema.omit({region:true}).extend({key:z12.string().min(1).max(220)})).min(1).max(64)});var LocalAgentAnswerSchema=z12.union([LocalAgentMetadataAnswerSchema,LocalAgentPixelAnswerSchema]).refine(v=>new TextEncoder().encode(JSON.stringify(v)).length<=96*1024);var LocalAgentImageReceiptSchema=z12.strictObject({protocol:z12.literal("NVS_LOCAL_AGENT_IMAGE_V1"),draftId:z12.uuid(),media:ReviewEvidenceMediaSchema,byteSize:z12.int().positive().max(8388608),contentType:z12.literal("image/png"),width:z12.int().positive().max(4096),height:z12.int().positive().max(4096)});var LocalAgentReviewViewSchema=z12.strictObject({plan:LocalAgentPlanSchema,revision:z12.int().positive(),phase:z12.enum(["PREPARED","RUNNING","RESULT_PENDING","UNKNOWN"]),answer:LocalAgentAnswerSchema.nullable(),imageReceipt:LocalAgentImageReceiptSchema.optional(),evidenceReceipt:LocalAgentEvidenceReceiptSchema.optional(),provenance:z12.strictObject({adapter:z12.enum(["CODEX_METADATA_V1","CODEX_MEDIA_V2"]),binaryDigest:sha2,version:qualifiedVersion,model:z12.string().max(100),reasoningEffort:z12.enum(["low","medium","high","xhigh"]).optional(),reviewerLabel:z12.string().max(100),inference:z12.literal("REMOTE_OPENAI"),evidence:z12.enum(["METADATA_ONLY","IMAGE_PIXELS","VIDEO_FRAMES"])})}).refine(v=>{const image=v.plan.snapshot.image,receipt=v.imageReceipt;if(receipt&&(!image||receipt.draftId!==v.plan.id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(v.plan.snapshot.media)||canonicalLocalJson({contentType:receipt.contentType,byteSize:receipt.byteSize,width:receipt.width,height:receipt.height})!==canonicalLocalJson(image)))return false;if(v.phase==="RESULT_PENDING"!==!!v.answer)return false;const derived=v.plan.snapshot.evidence,receipt2=v.evidenceReceipt;if(v.provenance.adapter!==(derived?"CODEX_MEDIA_V2":"CODEX_METADATA_V1"))return false;if(receipt2&&(!derived||receipt2.draftId!==v.plan.id||canonicalLocalJson(receipt2.media)!==canonicalLocalJson(v.plan.snapshot.media)))return false;if(v.answer&&!!(image||derived)!=="imageReadback"in v.answer)return false;const pixels=v.phase==="RESULT_PENDING"&&!!(image||derived);return v.provenance.evidence===(pixels?derived?.contentType==="video/mp4"?"VIDEO_FRAMES":"IMAGE_PIXELS":"METADATA_ONLY")&&(!pixels||(derived?!!receipt2:!!receipt))});function localAgentSnapshotFromContext(raw,includeImage=false){const c=ReviewIntelligenceContextResultSchema.parse(raw);if(c.reviewTarget.kind!=="IMAGE"||c.basis.target.kind!=="IMAGE"||c.ownerContext.semanticStatus!=="SUCCESS")throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");const t=c.reviewTarget.target,scope=c.basis.scope;if(!t.runtimeSucceeded||t.candidate.availability!=="AVAILABLE"||t.candidate.freshness!=="CURRENT_BASIS"||!t.productionRunnable||t.freshness!=="CURRENT_BASIS"||t.generationId!==c.basis.target.generationId||t.tenantId!==scope.tenantId||t.projectId!==scope.projectId||t.productionId!==scope.productionId||c.ownerContext.basis.tenantId!==scope.tenantId||c.ownerContext.basis.projectId!==scope.projectId||c.ownerContext.basis.productionId!==scope.productionId)throw Error("LOCAL_AGENT_CONTEXT_UNAVAILABLE");return LocalAgentSnapshotSchema.parse({basis:c.basis,productionRevision:c.ownerContext.basis.productionRevision,reviewVersion:t.reviewVersion,executionClass:t.executionClass,media:{artifactId:t.candidate.artifactId,representationId:t.candidate.representationId,checksumSha256:t.candidate.checksumSha256},requirements:t.requirements,...includeImage?{image:{contentType:t.candidate.contentType,byteSize:t.candidate.byteSize,width:t.candidate.width,height:t.candidate.height}}:{}})}function localAgentNativeProposal(raw){const v=LocalAgentReviewViewSchema.parse(raw);if(v.plan.snapshot.basis.target.kind!=="IMAGE"||v.plan.snapshot.evidence)throw Error("LOCAL_AGENT_MEDIA_PROPOSAL_REQUIRED");if(v.phase!=="RESULT_PENDING"||!v.answer)throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const keys=new Set(v.answer.observations.map(o=>o.key));if(keys.size!==v.answer.observations.length||keys.size!==v.plan.snapshot.requirements.length||v.plan.snapshot.requirements.some(r=>!keys.has(r.key)))throw Error("LOCAL_AGENT_RESULT_UNAVAILABLE");const p=v.provenance;const pixels=p.evidence==="IMAGE_PIXELS";return ValidateReviewIntelligenceSchema.parse({basis:v.plan.snapshot.basis,proposal:{origin:{kind:"EXTERNAL_AGENT_HOST",label:p.reviewerLabel},summary:`${pixels?"IMAGE_PIXELS":"METADATA_ONLY; no visual inspection"}. Codex ${p.version}; model ${p.model}; effort ${p.reasoningEffort??"DEFAULT"}; binary ${p.binaryDigest}; draft ${v.plan.id}; plan ${v.plan.fingerprint}. ${v.answer.summary}`,evidence:pixels?[{id:"original_image",label:"Verified ORIGINAL PNG attachment",producer:"EXTERNAL_AGENT_HOST",kind:"IMAGE_PIXELS",media:v.plan.snapshot.media}]:[],review:{kind:"IMAGE",observations:v.answer.observations.map(o=>({...o,status:pixels&&"status"in o?o.status:"NOT_OBSERVABLE",confidence:pixels&&"confidence"in o?o.confidence:"UNCERTAIN",evidenceIds:pixels?["original_image"]:[]}))}}})}var projectInput=LocalProjectScopeSchema;var LocalExecutionListInputSchema=LocalProjectScopeSchema.extend({after:z13.string().length(64).regex(/^[0-9a-f]{64}$/).nullable().default(null),limit:z13.int().min(1).max(16).default(8),includeCompleted:z13.boolean().optional(),includeProgress:z13.boolean().optional()});var LocalExecutionInspectInputSchema=LocalWorkScopeSchema.extend({includeProgress:z13.boolean().optional()});var LocalIpcCallSchema=z13.discriminatedUnion("operation",[z13.strictObject({operation:z13.literal("agent.discover"),binary:z13.string().min(1).max(4096).optional()}),z13.strictObject({operation:z13.literal("offline.workspace"),input:LocalOfflineCallSchema}),z13.strictObject({operation:z13.literal("workspace.inspect")}),z13.strictObject({operation:z13.literal("workspace.configure"),policy:LocalResourcePolicySchema,expectedRevision:z13.int().nonnegative()}),z13.strictObject({operation:z13.literal("workspace.activity"),idleSeconds:z13.int().min(0).max(86400),observedAt:z13.iso.datetime()}),z13.strictObject({operation:z13.literal("storage.clean")}),z13.strictObject({operation:z13.literal("diagnostics.read")}),z13.strictObject({operation:z13.literal("agent.grant"),grant:LocalAgentGrantSchema,approval:z13.string().regex(/^[a-f0-9]{64}$/)}),z13.strictObject({operation:z13.literal("agent.probe")}),z13.strictObject({operation:z13.literal("agent.revoke"),approval:z13.string().regex(/^[a-f0-9]{64}$/)}),z13.strictObject({operation:z13.literal("agent.prepare"),snapshot:LocalAgentSnapshotSchema}),z13.strictObject({operation:z13.literal("agent.start"),id:z13.uuid(),expectedRevision:LocalRevisionSchema,approval:z13.string().regex(/^[a-f0-9]{64}$/)}),z13.strictObject({operation:z13.literal("agent.inspect"),id:z13.uuid()}),z13.strictObject({operation:z13.literal("runtime.status"),includeDevice:z13.literal(true).optional()}),z13.strictObject({operation:z13.literal("runtime.doctor")}),z13.strictObject({operation:z13.literal("runtime.inventory")}),z13.strictObject({operation:z13.literal("session.issue"),projects:z13.array(projectInput).min(1).max(100),expiresAt:z13.iso.datetime({offset:true})}),z13.strictObject({operation:z13.literal("runtime.stop"),expectedRuntimeRevision:LocalRevisionSchema}),z13.strictObject({operation:z13.literal("execution.inspect"),input:LocalExecutionInspectInputSchema}),z13.strictObject({operation:z13.literal("execution.list"),input:LocalExecutionListInputSchema}),z13.strictObject({operation:z13.literal("update.check")}),z13.strictObject({operation:z13.literal("update.prepare"),targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema}),z13.strictObject({operation:z13.literal("update.apply"),planId:LocalIdSchema,targetVersion:LocalPackageVersionSchema,expectedRuntimeRevision:LocalRevisionSchema})]);var LocalNextActionSchema=z13.strictObject({call:LocalIpcCallSchema,availability:z13.enum(["AVAILABLE","BLOCKED"]),reason:z13.enum(["READY","INSTALL_REQUIRED","AUTHORIZATION_REQUIRED","VERSION_INCOMPATIBLE","UPDATE_AVAILABLE","RECOVERY_REQUIRED"])});var LocalIpcRequestSchema=z13.strictObject({protocol:z13.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,call:LocalIpcCallSchema});var LocalVersionReportSchema=z13.strictObject({component:z13.enum(["CLI","SDK","MCP","RUNTIME","MEDIA_TOOLS"]),installedVersion:LocalPackageVersionSchema.nullable(),runningVersion:LocalPackageVersionSchema.nullable(),availableVersion:LocalPackageVersionSchema.nullable(),executablePath:z13.string().min(1).max(4096).nullable(),installOwner:z13.enum(["NPM_GLOBAL","PROJECT","NPX","MANAGED","TARBALL","UNKNOWN"])});var LocalRuntimeStatusSchema=z13.strictObject({protocol:z13.literal("NVS_LOCAL_IPC_V1"),runtimeRevision:LocalRevisionSchema,state:z13.enum(["IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),journalSchemaVersion:z13.literal(1),workProtocols:z13.array(z13.enum(["NVS_LOCAL_WORK_V1","NVS_LOCAL_WORK_V2"])).min(1).max(2),versions:z13.array(LocalVersionReportSchema).max(8),authorizedProjects:z13.array(projectInput).max(100),deviceAuthority:z13.strictObject({tenantId:z13.uuid(),deviceId:z13.uuid(),origin:z13.url()}).optional(),nextActions:z13.array(LocalNextActionSchema).max(8)});var LocalDoctorReportSchema=z13.strictObject({mode:z13.enum(["MANAGED","INSTALLED"]),availability:z13.enum(["AVAILABLE","UNAVAILABLE"]),reason:z13.enum(["QUALIFIED_PROCESS_TOOLS","MANAGED_TOOLS_MISSING","TOOL_QUALIFICATION_FAILED"]),nativeExecutionReady:z13.boolean(),executionProfiles:z13.array(z13.enum(["ROUGH_CUT_PREVIEW_V1","STUDIO_MEDIA_V2"])).max(2).optional(),tools:z13.array(z13.strictObject({name:z13.enum(["FFMPEG","FFPROBE"]),path:z13.string().min(1).max(4096),version:z13.string().min(1).max(200),digest:z13.string().regex(/^[0-9a-f]{64}$/)})).max(2)});var LocalExecutionInspectionSchema=z13.strictObject({binding:LocalLeaseBindingSchema,revision:LocalRevisionSchema,phase:z13.enum(["STAGED","RUNNING","RECOVERY_REQUIRED","OUTPUT_PENDING","RECEIPT_RECORDED","FENCED"]),checkpoint:z13.enum(["ADOPTED","SOURCES_READY","PROCESS_STARTED","OUTPUT_STAGED"]),progress:LocalExecutionProgressSchema.optional()});var LocalExecutionPageSchema=z13.strictObject({items:z13.array(LocalExecutionInspectionSchema).max(16),nextCursor:z13.string().length(64).regex(/^[0-9a-f]{64}$/).nullable()});var LocalIpcErrorCodeSchema=z13.enum(["FORBIDDEN","INVALID_INPUT","FRAME_LIMIT","BUSY","AUTHORIZATION_REQUIRED","REVISION_CONFLICT","CAPABILITY_UNAVAILABLE","INTERNAL_OPERATIONAL_FAILURE","AGENT_APPROVAL_REQUIRED","AGENT_RUNTIME_UNAVAILABLE","AGENT_LOGIN_REQUIRED","AGENT_VERSION_UNQUALIFIED","AGENT_GRANT_REQUIRED","AGENT_OUTCOME_UNKNOWN","AGENT_IMAGE_REQUIRED","AGENT_IMAGE_INVALID","AGENT_IMAGE_BUDGET_EXCEEDED","AGENT_IMAGE_AUTHORIZATION_REQUIRED","CACHE_QUOTA_EXCEEDED"]);var LocalIpcResponseSchema=z13.discriminatedUnion("semanticStatus",[z13.strictObject({protocol:z13.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema,semanticStatus:z13.literal("SUCCESS"),data:z13.union([LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,LocalOfflinePageSchema,LocalRuntimeStatusSchema,LocalDoctorReportSchema,LocalExecutionInspectionSchema.nullable(),z13.strictObject({state:z13.literal("DRAINING"),inventory:LocalManagementInventorySchema.optional(),backupPath:z13.string().min(1).max(4096).optional()}),LocalSessionConnectorSchema,LocalManagementInventorySchema,LocalExecutionPageSchema,LocalAgentProbeSchema,LocalAgentDiscoverySchema,LocalAgentReviewViewSchema])}),z13.strictObject({protocol:z13.literal("NVS_LOCAL_IPC_V1"),requestId:LocalIdSchema.nullable(),semanticStatus:z13.enum(["BLOCKED","INVALID_INPUT"]),error:z13.strictObject({code:LocalIpcErrorCodeSchema})})]);var LocalMcpToolNameSchema=z14.enum(["local_navigate","local_capability_describe","local_runtime_status","local_execution_list","local_execution_inspect","local_update_check"]);var LocalMcpActionSchema=z14.strictObject({tool:LocalMcpToolNameSchema,arguments:z14.record(z14.string(),z14.unknown()),availability:z14.enum(["AVAILABLE","BLOCKED"]).optional(),reason:z14.string().max(100).optional()});var LocalMcpNavigationSchema=z14.strictObject({location:z14.literal("LOCAL"),state:z14.enum(["UNAVAILABLE","IDLE","EXECUTING","DRAINING","RECOVERY_REQUIRED"]),authorizedProjects:z14.array(LocalProjectScopeSchema).max(100).optional(),groups:z14.array(z14.strictObject({id:z14.string().max(40),label:z14.string().max(100),tools:z14.array(LocalMcpToolNameSchema).max(6)})).max(4),nextActions:z14.array(z14.union([LocalMcpActionSchema,LocalClientNextActionSchema])).max(16)});var LocalMcpExecutionPageSchema=LocalExecutionPageSchema.extend({nextActions:z14.array(LocalMcpActionSchema).max(16)});var LocalMcpInspectionSchema=z14.strictObject({location:z14.literal("LOCAL"),execution:LocalExecutionInspectionSchema.nullable(),nextActions:z14.array(LocalMcpActionSchema).max(4)});var LocalMcpUpdateSchema=z14.strictObject({location:z14.literal("LOCAL"),running:z14.array(LocalVersionReportSchema).max(8),available:z14.array(LocalRuntimeDescriptorSchema).max(32),nextActions:z14.array(LocalClientNextActionSchema).max(4)});var LocalMcpDescriptionSchema=z14.strictObject({location:z14.literal("LOCAL"),tool:LocalMcpToolNameSchema,schema:z14.object({name:LocalMcpToolNameSchema,description:z14.string(),inputSchema:z14.record(z14.string(),z14.unknown())}).passthrough()});var LocalMcpFailureSchema=z14.strictObject({semanticStatus:z14.enum(["BLOCKED","INVALID_INPUT"]),error:z14.strictObject({code:z14.enum(["AUTHORIZATION_REQUIRED","FORBIDDEN","LOCAL_RUNTIME_UNAVAILABLE","RELEASE_UNAVAILABLE","VERSION_INCOMPATIBLE","INVALID_INPUT","LOCAL_CAPABILITY_UNAVAILABLE"]),outcome:z14.literal("NO_WRITE")}),nextActions:z14.array(LocalClientNextActionSchema).max(4)});var LocalMcpOutputSchemas={local_navigate:LocalMcpNavigationSchema,local_capability_describe:LocalMcpDescriptionSchema,local_runtime_status:LocalRuntimeStatusSchema.omit({nextActions:true}).extend({nextActions:z14.array(LocalMcpActionSchema).max(8)}),local_execution_list:LocalMcpExecutionPageSchema,local_execution_inspect:LocalMcpInspectionSchema,local_update_check:LocalMcpUpdateSchema};import{z as z15}from"zod";var LocalManagementCommandSchema=z15.discriminatedUnion("kind",[z15.strictObject({kind:z15.literal("ENROLL"),input:EnrollLocalDeviceSchema}),z15.strictObject({kind:z15.literal("GRANT"),input:GrantLocalDeviceSchema}),z15.strictObject({kind:z15.literal("REVOKE_GRANT"),input:RevokeLocalDeviceGrantSchema}),z15.strictObject({kind:z15.literal("PREVIEW"),input:StartLocalPreviewSchema}),z15.strictObject({kind:z15.literal("FINAL_RENDER"),input:StartLocalFinalRenderSchema})]);var LocalManagementResultSchema=z15.union([LocalDeviceViewSchema,LocalDeviceGrantSchema,LocalPreviewAdmissionSchema,LocalFinalRenderAdmissionSchema,z15.strictObject({semanticStatus:z15.literal("SUCCESS")})]);var LocalManagementReceiptSchema=z15.strictObject({fingerprint:z15.string().regex(/^[a-f0-9]{64}$/),result:LocalManagementResultSchema.nullable()});import{z as z17}from"zod";import{createHash}from"node:crypto";function localBudget(timeoutMs,parent,ceiling=6e4){if(!Number.isInteger(timeoutMs)||timeoutMs<1||timeoutMs>ceiling)throw Error("LOCAL_DEADLINE_INVALID");const controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);return{signal:parent?AbortSignal.any([parent,controller.signal]):controller.signal,close:()=>clearTimeout(timer)}}async function localAbortable(work,signal){if(signal.aborted)void work.catch(()=>{});signal.throwIfAborted();return new Promise((resolve,reject)=>{const abort=()=>reject(Error("LOCAL_DEADLINE"));signal.addEventListener("abort",abort,{once:true});work.then(v=>{signal.removeEventListener("abort",abort);resolve(v)},e=>{signal.removeEventListener("abort",abort);reject(e)});if(signal.aborted)abort()})}import{z as z16}from"zod";var output=z16.discriminatedUnion("role",[z16.strictObject({role:z16.literal("VIDEO"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z16.int().positive().max(128*1024*1024),contentType:z16.literal("video/mp4")}),z16.strictObject({role:z16.literal("POSTER"),receiptId:LocalIdSchema,checksumSha256:LocalDigestSchema,byteSize:z16.int().positive().max(2*1024*1024),contentType:z16.literal("image/png")})]);var LocalCompletionSubmissionSchema=LocalLeaseBindingSchema.extend({requestId:LocalIdSchema,outputs:z16.array(output).length(2),technical:RoughCutTechnicalSchema}).superRefine((v,ctx)=>{const video=v.outputs.find(o=>o.role==="VIDEO");if(new Set(v.outputs.map(o=>o.role)).size!==2||new Set(v.outputs.map(o=>o.receiptId)).size!==2||!video||video.checksumSha256!==v.technical.checksumSha256||video.byteSize!==v.technical.byteSize)ctx.addIssue({code:"custom",message:"Exact video/poster receipts required"})});var LocalVerifiedUploadSchema=z16.strictObject({binding:LocalLeaseBindingSchema,output,verifiedAt:LocalTimeSchema});var LocalCompletionReceiptSchema=LocalLeaseBindingSchema.extend({submissionFingerprint:LocalDigestSchema.optional(),semanticStatus:z16.literal("SUCCESS"),requestId:LocalIdSchema,renderId:LocalIdSchema,operationId:OperationIdSchema,artifactId:LocalIdSchema,videoRepresentationId:LocalIdSchema,posterRepresentationId:LocalIdSchema,checksumSha256:LocalDigestSchema,acceptedAt:LocalTimeSchema});var GetLocalCompletionReceiptSchema=LocalLeaseBindingSchema.pick({tenantId:true,projectId:true,productionId:true,runtimeJobId:true}).extend({requestId:LocalIdSchema});var NativeStudioLocalDeviceClient=class{constructor(options){this.options=options;const u=new URL(options.baseUrl);if(u.username||u.password||u.search||u.hash||u.pathname!=="/"||u.protocol!=="https:"&&!(u.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(u.hostname)))throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");this.origin=u.origin}options;origin;async command(route,raw,input,output2,signal,readOnly=false){let started=false;const budget=localBudget(15e3,signal);try{const i=input.parse(raw);if((i.tenantId??i.input?.tenantId)!==this.options.tenantId)throw Error();budget.signal.throwIfAborted();const authorization=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);if(authorization!==authorization.trim()||!/^Bearer [A-Za-z0-9._~-]{1,8192}$/.test(authorization))throw Error();const body=JSON.stringify(i);if(Buffer.byteLength(body)>65536)throw Error();budget.signal.throwIfAborted();started=true;const r=await fetch(this.origin+"/v1/local-execution/"+route,{method:"POST",headers:{authorization,"content-type":"application/json"},body,redirect:"error",signal:budget.signal});if(!r.ok){await r.body?.cancel();throw new NativeStudioSdkError(r.status===403||r.status===401?"FORBIDDEN":"LOCAL_COMMAND_REFUSED","BLOCKED",readOnly?"NO_WRITE":r.status>=500?"UNKNOWN":"REJECTED",r.status)}const parts=[];let size=0;for await(const b of r.body??[]){size+=b.length;if(size>262144)throw Error();parts.push(b)}const value=output2.parse(JSON.parse(Buffer.concat(parts).toString()));if(value&&typeof value==="object"){const result=value,request3=i;for(const key of["tenantId","projectId","deviceId"])if(key in result&&key in request3&&result[key]!==request3[key])throw Error()}return value}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError(started?readOnly?"LOCAL_QUERY_UNAVAILABLE":"LOCAL_COMMAND_UNKNOWN":"INVALID_INPUT",started?"BLOCKED":"INVALID_INPUT",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}enroll(input,signal){return this.command("devices/enroll",input,EnrollLocalDeviceSchema,LocalDeviceViewSchema,signal)}async managementReceipt(input,signal){const parsedInput=LocalManagementCommandSchema.safeParse(input);if(!parsedInput.success)throw new NativeStudioSdkError("INVALID_INPUT","INVALID_INPUT","NO_WRITE");const parsed=parsedInput.data;const value=await this.command("management-receipt",input,LocalManagementCommandSchema,LocalManagementReceiptSchema,signal,true);if(value.fingerprint!==createHash("sha256").update(canonicalLocalJson(parsed)).digest("hex"))throw new NativeStudioSdkError("LOCAL_RECEIPT_INVALID","BLOCKED","NO_WRITE");if(value.result){const result=value.result,original=parsed.input;for(const key of["tenantId","projectId","deviceId","productionId","timelineVersionId"])if(key in original&&key in result&&result[key]!==original[key])throw new NativeStudioSdkError("LOCAL_RECEIPT_INVALID","BLOCKED","NO_WRITE")}return value}grant(input,signal){return this.command("devices/grant",input,GrantLocalDeviceSchema,LocalDeviceGrantSchema,signal)}revokeDevice(input,signal){return this.command("devices/revoke",input,RevokeLocalDeviceSchema,z17.strictObject({semanticStatus:z17.literal("SUCCESS")}),signal)}revokeGrant(input,signal){return this.command("devices/revoke-grant",input,RevokeLocalDeviceGrantSchema,z17.strictObject({semanticStatus:z17.literal("SUCCESS")}),signal)}startPreview(input,signal){return this.command("previews",input,StartLocalPreviewSchema,LocalPreviewAdmissionSchema,signal)}startFinal(input,signal){return this.command("final-renders",input,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,signal)}};import{randomUUID,createHash as createHash2}from"node:crypto";import{request}from"node:http";import{z as z18}from"zod";import{constants}from"node:fs";import{open,realpath}from"node:fs/promises";async function checkedLocalDirectory(path){await privateDirectory(path);return realpath(path)}async function readLocalCredential(path,maximum=32768){await privateAccess(path,"file");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await file.stat();if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");const bytes=Buffer.alloc(Math.min(maximum+1,stat.size+1));let used=0;while(used<bytes.length){const part=await file.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>stat.size)throw Error("LOCAL_CREDENTIAL_INVALID");if(used>maximum)throw Error("LOCAL_CREDENTIAL_INVALID");return bytes.subarray(0,used)}finally{await file.close()}}async function stageAgentImage(options,view,input,signal){const budget=localBudget(view.plan.snapshot.evidence?18e4:options.timeoutMs??1e4,signal,view.plan.snapshot.evidence?18e4:6e4);let dispatched=false;try{budget.signal.throwIfAborted();if(input.byteLength>134217728)throw Error();const bytes=Buffer.from(input),snapshot=view.plan.snapshot,id=z18.uuid().parse(view.plan.id),requestId=randomUUID();if(!snapshot.image&&!snapshot.evidence||bytes.length!==(snapshot.evidence??snapshot.image).byteSize||bytes.length>(snapshot.evidence?134217728:8388608)||createHash2("sha256").update(bytes).digest("hex")!==snapshot.media.checksumSha256)throw Error();const root=await checkedLocalDirectory(options.stateDirectory),path=localSocketPath(root);await privateAccess(path,"pipe");const auth=await localAbortable(Promise.resolve().then(options.authorization),budget.signal);budget.signal.throwIfAborted();if(!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const reply=await new Promise((resolve,reject)=>{const req=request({socketPath:path,path:"/ipc/v1/agent-images/"+id,method:"PUT",signal:budget.signal,headers:{authorization:auth,"content-type":snapshot.evidence?"application/octet-stream":"image/png","content-length":bytes.length,"x-nvs-request-id":requestId}},res=>{let size=0;const chunks=[];res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{size+=b.length;if(size>262144)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);dispatched=true;req.end(bytes)});const response=LocalIpcResponseSchema.parse(reply);if(response.requestId!==requestId&&!(response.requestId===null&&response.semanticStatus!=="SUCCESS"&&["BUSY","FORBIDDEN"].includes(response.error.code)))throw Error();if(response.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(response.error.code,response.semanticStatus,response.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");const v=LocalAgentReviewViewSchema.parse(response.data),receipt=v.evidenceReceipt??v.imageReceipt;if(v.plan.id!==id||canonicalLocalJson(v.plan)!==canonicalLocalJson(view.plan)||v.revision<view.revision||v.phase!=="PREPARED"||!receipt||receipt.draftId!==id||canonicalLocalJson(receipt.media)!==canonicalLocalJson(snapshot.media)||!snapshot.evidence&&canonicalLocalJson({contentType:v.imageReceipt?.contentType,byteSize:v.imageReceipt?.byteSize,width:v.imageReceipt?.width,height:v.imageReceipt?.height})!==canonicalLocalJson(snapshot.image))throw Error();return v}catch(e){if(e instanceof NativeStudioSdkError)throw e;throw new NativeStudioSdkError("LOCAL_AGENT_IMAGE_TRANSFER_FAILED","BLOCKED",dispatched?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}var NativeStudioLocalWorkspaceClient=class{constructor(client){this.client=client}client;async offline(raw,signal){return LocalOfflinePageSchema.parse(await this.client.call({operation:"offline.workspace",input:LocalOfflineCallSchema.parse(raw)},signal))}async inspect(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.inspect"},signal))}async configure(raw,expectedRevision,signal){const policy=LocalResourcePolicySchema.parse(raw);return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.configure",policy,expectedRevision},signal))}async observeActivity(idleSeconds,observedAt,signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"workspace.activity",idleSeconds,observedAt},signal))}async clean(signal){return LocalWorkspaceInspectionSchema.parse(await this.client.call({operation:"storage.clean"},signal))}async diagnostics(signal){return LocalDiagnosticsSchema.parse(await this.client.call({operation:"diagnostics.read"},signal))}};import{randomUUID as randomUUID2}from"node:crypto";import{request as request2}from"node:http";var NativeStudioLocalRuntimeClient=class _NativeStudioLocalRuntimeClient{constructor(options){this.options=options}options;workspace=new NativeStudioLocalWorkspaceClient(this);static async fromConnector(path){const initial=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));return new _NativeStudioLocalRuntimeClient({stateDirectory:initial.stateDirectory,projects:initial.projects,authorization:async()=>{const current=LocalSessionConnectorSchema.parse(JSON.parse((await readLocalCredential(path)).toString()));if(current.stateDirectory!==initial.stateDirectory||canonicalLocalJson(current.projects)!==canonicalLocalJson(initial.projects)||Date.parse(current.expiresAt)>Date.parse(initial.expiresAt)||Date.parse(current.expiresAt)<=Date.now())throw Error("LOCAL_AUTHORIZATION_REQUIRED");return"Bearer "+current.credential}})}async call(call,signal){let started=false;const budget=localBudget(this.options.timeoutMs??(["runtime.doctor","agent.probe","agent.grant","agent.start"].includes(call.operation)?6e4:1e4),signal);const readOnly=["runtime.status","runtime.doctor","runtime.inventory","execution.inspect","execution.list","update.check","agent.probe","agent.discover","agent.inspect","workspace.inspect","diagnostics.read"].includes(call.operation);try{const input=LocalIpcRequestSchema.parse({protocol:"NVS_LOCAL_IPC_V1",requestId:randomUUID2(),call});const root=await checkedLocalDirectory(this.options.stateDirectory);const path=localSocketPath(root);await privateAccess(path,"pipe");budget.signal.throwIfAborted();const auth=await localAbortable(Promise.resolve().then(()=>this.options.authorization()),budget.signal);budget.signal.throwIfAborted();if(auth.length!==50||!/^Bearer [A-Za-z0-9_-]{43}$/.test(auth))throw Error();const body=JSON.stringify(input);const reply=await new Promise((resolve,reject)=>{const abort=budget.signal;const req=request2({socketPath:path,method:"POST",path:"/ipc/v1",signal:abort,headers:{authorization:auth,"content-type":"application/json","content-length":Buffer.byteLength(body)}},res=>{const chunks=[];let length=0;res.on("error",reject);res.on("aborted",()=>reject(Error()));res.on("data",b=>{length+=b.length;if(length>256*1024)req.destroy(Error());else chunks.push(b)});res.on("end",()=>{try{resolve(JSON.parse(Buffer.concat(chunks).toString()))}catch{reject(Error())}})});req.on("error",reject);started=true;req.end(body)});const value=LocalIpcResponseSchema.parse(reply);if(value.requestId!==input.requestId&&!(value.requestId===null&&value.semanticStatus!=="SUCCESS"&&["FORBIDDEN","BUSY","INVALID_INPUT"].includes(value.error.code)))throw Error();if(value.semanticStatus!=="SUCCESS")throw new NativeStudioSdkError(value.error.code,value.semanticStatus,readOnly?"NO_WRITE":value.error.code==="INTERNAL_OPERATIONAL_FAILURE"?"UNKNOWN":"REJECTED");if(value.requestId!==input.requestId)throw Error();return value.data}catch(error){if(error instanceof NativeStudioSdkError)throw error;throw new NativeStudioSdkError("LOCAL_RUNTIME_UNAVAILABLE","BLOCKED",started&&!readOnly?"UNKNOWN":"NO_WRITE")}finally{budget.close()}}response(schema,raw){const result=schema.safeParse(raw);if(!result.success)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return result.data}async status(signal,includeDevice=false){const value=this.response(LocalRuntimeStatusSchema,await this.call({operation:"runtime.status",...includeDevice?{includeDevice:true}:{}},signal));if(this.options.projects&&value.authorizedProjects.some(p=>!this.options.projects.some(q=>q.tenantId===p.tenantId&&q.projectId===p.projectId)))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}async doctor(signal){return this.response(LocalDoctorReportSchema,await this.call({operation:"runtime.doctor"},signal))}async inventory(signal){return this.response(LocalManagementInventorySchema,await this.call({operation:"runtime.inventory"},signal))}async grantAgent(raw,approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.grant",grant:LocalAgentGrantSchema.parse(raw),approval}))}async revokeAgent(approval){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.revoke",approval}))}async probeAgent(){return this.response(LocalAgentProbeSchema,await this.call({operation:"agent.probe"}))}async discoverAgent(binary){return this.response(LocalAgentDiscoverySchema,await this.call({operation:"agent.discover",...binary?{binary}:{}}))}async prepareAgentReview(snapshot){const input=LocalAgentSnapshotSchema.parse(snapshot);const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.prepare",snapshot:input}));if(canonicalLocalJson(v.plan.snapshot)!==canonicalLocalJson(input))throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async startAgentReview(id,expectedRevision,approval){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.start",id,expectedRevision,approval}));if(v.plan.id!==id||v.plan.fingerprint!==approval)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","UNKNOWN");return v}async stageAgentImage(id,bytes,signal){const budget=localBudget(18e4,signal,18e4);try{return await stageAgentImage(this.options,await this.inspectAgentReview(id,budget.signal),bytes,budget.signal)}finally{budget.close()}}async inspectAgentReview(id,signal){const v=this.response(LocalAgentReviewViewSchema,await this.call({operation:"agent.inspect",id},signal));if(v.plan.id!==id)throw new NativeStudioSdkError("LOCAL_RESPONSE_INVALID","BLOCKED","NO_WRITE");return v}async executions(input,signal){const i=LocalExecutionListInputSchema.parse(input);if(this.options.projects&&!this.options.projects.some(p=>p.tenantId===i.tenantId&&p.projectId===i.projectId))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const page=this.response(LocalExecutionPageSchema,await this.call({operation:"execution.list",input:i},signal));if(page.items.some(e=>e.binding.tenantId!==i.tenantId||e.binding.projectId!==i.projectId))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return page}async inspect(raw,signal){const input=LocalExecutionInspectInputSchema.parse(raw);if(this.options.projects&&!this.options.projects.some(p=>p.tenantId===input.tenantId&&p.projectId===input.projectId))throw new NativeStudioSdkError("FORBIDDEN","BLOCKED","NO_WRITE");const value=this.response(LocalExecutionInspectionSchema.nullable(),await this.call({operation:"execution.inspect",input},signal));if(value&&["tenantId","projectId","productionId","runtimeJobId"].some(k=>value.binding[k]!==input[k]))throw new NativeStudioSdkError("LOCAL_SCOPE_INVALID","BLOCKED","NO_WRITE");return value}};import{createPublicKey,verify}from"node:crypto";function endpoint(raw){const u=new URL(raw);if(u.username||u.password||u.search||u.hash||u.protocol!=="https:"&&!(u.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(u.hostname)))fail("RELEASE_ORIGIN_INVALID");return u}async function fetchBytes(raw,maximum,origin,signal=AbortSignal.timeout(3e4)){const u=endpoint(raw);if(u.origin!==origin)fail("RELEASE_ORIGIN_INVALID");const r=await fetch(u,{redirect:"error",signal,headers:{accept:"application/octet-stream"}});if(!r.ok||Number(r.headers.get("content-length"))>maximum){await r.body?.cancel();fail("RELEASE_UNAVAILABLE")}const parts=[];let size=0;for await(const part of r.body??[]){size+=part.byteLength;if(size>maximum){await r.body?.cancel().catch(()=>{});fail("RELEASE_LIMIT")}parts.push(part)}return Buffer.concat(parts)}async function catalogue(trust,signal){const origin=endpoint(trust.catalogueUrl).origin;const bytes=await fetchBytes(trust.catalogueUrl,65536,origin,signal??AbortSignal.timeout(3e4));const signed=LocalSignedCatalogueSchema.parse(JSON.parse(bytes.toString()));const key=createPublicKey((await read(trust.publicKeyFile,16384)).toString());if(key.asymmetricKeyType!=="ed25519"||!verify(null,Buffer.from(canonicalLocalJson(signed.catalogue)),key,Buffer.from(signed.signature,"base64url")))fail("RELEASE_SIGNATURE_INVALID");const now=Date.now();if(Date.parse(signed.catalogue.issuedAt)>now||Date.parse(signed.catalogue.expiresAt)<=now)fail("RELEASE_EXPIRED");for(const release of signed.catalogue.releases){for(const a of[release.package,...release.tools?Object.values(release.tools):[]])if(endpoint(a.url).origin!==origin)fail("RELEASE_ORIGIN_INVALID")}return{signed,fingerprint:sha256(canonicalLocalJson(signed.catalogue)),origin,trustFingerprint:sha256(canonicalLocalJson({catalogueUrl:endpoint(trust.catalogueUrl).href,publicKey:key.export({type:"spki",format:"der"}).toString("base64")}))}}function select(signed,version){const r=signed.catalogue.releases.find(r2=>r2.descriptor.version===version&&r2.descriptor.platform.os===process.platform&&r2.descriptor.platform.architecture===process.arch);if(!r)fail("VERSION_INCOMPATIBLE");const[major,minor]=process.versions.node.split(".").map(Number);if(major!==r.descriptor.node.major||minor<r.descriptor.node.minMinor)fail("NODE_VERSION_INCOMPATIBLE");return r}async function asset(a,origin){const bytes=await fetchBytes(a.url,a.byteSize,origin,AbortSignal.timeout(12e4));if(bytes.length!==a.byteSize||sha512(bytes)!==a.sha512)fail("RELEASE_INTEGRITY_INVALID");return bytes}export{EnrollLocalDeviceSchema,LocalDeviceViewSchema,LocalDeviceChallengeSchema,GrantLocalDeviceSchema,LocalDeviceGrantSchema,RevokeLocalDeviceGrantSchema,RevokeLocalDeviceSchema,LocalOfflineCallSchema,LocalOfflinePageSchema,LocalAgentGrantSchema,LocalAgentDiscoverySchema,LocalToolSelectionSchema,LocalRuntimeDescriptorSchema,LocalManagementInventorySchema,LocalReleaseSchema,LocalToolChoiceSchema,LocalUpdatePlanSchema,LocalResourcePolicySchema,LocalWorkspaceInspectionSchema,LocalDiagnosticsSchema,canonicalLocalJson,LocalAgentSnapshotSchema,LocalAgentProbeSchema,LocalAgentReviewViewSchema,localAgentSnapshotFromContext,localAgentNativeProposal,LocalExecutionListInputSchema,LocalExecutionInspectInputSchema,LocalDoctorReportSchema,StartLocalPreviewSchema,LocalDeviceSessionSchema,LocalDeviceTransportConfigurationSchema,LocalPreviewAdmissionSchema,StartLocalFinalRenderSchema,LocalFinalRenderAdmissionSchema,LocalMcpFailureSchema,LocalMcpOutputSchemas,LocalManagementCommandSchema,LocalManagementResultSchema,NativeStudioLocalDeviceClient,NativeStudioLocalRuntimeClient,endpoint,catalogue,select,asset};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{lstat as lstat2,mkdir,open,rename,link,unlink}from"node:fs/promises";import{dirname,isAbsolute as isAbsolute2,join as join2}from"node:path";import{createHash as createHash2}from"node:crypto";import{execFile,spawn}from"node:child_process";import{once}from"node:events";import{readFile,realpath,lstat}from"node:fs/promises";import{createHash,randomUUID}from"node:crypto";import{fileURLToPath}from"node:url";import{join,win32,isAbsolute}from"node:path";var nativeAssetNames=["Bootstrap.ps1","NativeMain.cs","PrivateAccess.cs","PipeBridge.cs","JobNative.cs","JobRunner.cs"];var executable;var assetDirectory;async function windowsHelper(){if(process.platform!=="win32"||process.arch!=="x64")throw Error("WINDOWS_PLATFORM_REQUIRED");return executable??=bootstrap().catch(error=>{executable=void 0;throw error})}async function bootstrap(){const directory2=assetDirectory??fileURLToPath(new URL("./dist/native/",import.meta.resolve("@nativestudio/cli/package.json")));const hash=createHash("sha256");for(const name of nativeAssetNames){hash.update(name+"\n");hash.update(await readFile(join(directory2,name)))}const sourceDigest=hash.digest("hex"),system=process.env.SystemRoot??process.env.SYSTEMROOT;if(!system||!win32.isAbsolute(system)||system.startsWith("\\\\"))throw Error("WINDOWS_SYSTEM_UNAVAILABLE");const shell=join(system,"System32/WindowsPowerShell/v1.0/powershell.exe"),script=(await readFile(join(directory2,"Bootstrap.ps1"))).toString("utf8");const result=await new Promise((resolve,reject)=>{const child=execFile(shell,["-NoLogo","-NoProfile","-NonInteractive","-EncodedCommand",Buffer.from(script,"utf16le").toString("base64")],{timeout:15e3,maxBuffer:32768,windowsHide:true},(error,stdout)=>error?reject(Error("WINDOWS_HELPER_UNAVAILABLE")):resolve(stdout));child.stdin.on("error",()=>{});child.stdin.end(JSON.stringify({directory:directory2,sourceDigest}))});const value=JSON.parse(result);if(value.sourceDigest!==sourceDigest||!/^[a-f0-9]{64}$/.test(value.sha256)||!win32.isAbsolute(value.path))throw Error("WINDOWS_HELPER_INVALID");const path=await realpath(value.path),stat=await lstat(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||stat.size>2*1024*1024||createHash("sha256").update(await readFile(path)).digest("hex")!==value.sha256)throw Error("WINDOWS_HELPER_INVALID");return path}var service;async function connection(){return service??=(async()=>{const child=spawn(await windowsHelper(),["service",String(process.pid)],{shell:false,windowsHide:true,stdio:["pipe","pipe","pipe"]});const pending=new Map;let bytes=Buffer.alloc(0),stderr=0;const close=()=>{for(const item of pending.values()){clearTimeout(item.timer);item.reject(Error("WINDOWS_HELPER_UNAVAILABLE"))}pending.clear();service=void 0};child.stdout.on("data",part=>{bytes=Buffer.concat([bytes,part]);if(bytes.length>2*1024*1024)return child.kill();for(;;){const end=bytes.indexOf(10);if(end<0)break;const line=bytes.subarray(0,end);bytes=bytes.subarray(end+1);try{const value=JSON.parse(line.toString());const item=pending.get(value.id);if(!item)continue;pending.delete(value.id);clearTimeout(item.timer);if(value.ok)item.resolve(value.data);else item.reject(Error(["EXISTS","RESOURCE_BUDGET_EXCEEDED"].includes(value.error??"")?value.error:"WINDOWS_ACCESS_DENIED"))}catch{child.kill()}}});child.stderr.on("data",b=>{if((stderr+=b.length)>65536)child.kill()});child.on("error",close);child.on("close",close);child.stdin.on("error",close);await once(child,"spawn");child.unref();child.stdout.unref();child.stderr.unref();child.stdin.unref();return{child,pending}})().catch(error=>{service=void 0;throw error})}async function windowsRequest(request,timeoutMs=1e4,signal){signal?.throwIfAborted();const{child,pending}=await connection();signal?.throwIfAborted();if(child.exitCode!==null||child.signalCode!==null||child.stdin.destroyed)throw Error("WINDOWS_HELPER_UNAVAILABLE");if(pending.size>=32)throw Error("WINDOWS_HELPER_BUSY");const id=randomUUID(),data=JSON.stringify({...request,id});if(Buffer.byteLength(data)>1024*1024)throw Error("WINDOWS_HELPER_INPUT_LIMIT");return new Promise((resolve,reject)=>{const abort=()=>{child.stdin.write(JSON.stringify({operation:"cancel",target:id})+"\n")};const timer=setTimeout(()=>{abort();pending.delete(id);signal?.removeEventListener("abort",abort);reject(Error("WINDOWS_HELPER_TIMEOUT"))},timeoutMs);pending.set(id,{timer,resolve:v=>{signal?.removeEventListener("abort",abort);resolve(v)},reject:e=>{signal?.removeEventListener("abort",abort);reject(e)}});signal?.addEventListener("abort",abort,{once:true});child.stdin.write(data+"\n");if(signal?.aborted)abort()})}function localSocketPath(root,platform=process.platform){if(platform!=="win32")return join2(root,"runtime.sock");return"\\\\.\\pipe\\nvs-"+createHash2("sha256").update(root.toLowerCase()).digest("hex")}async function privateAccess(path,kind){if(process.platform==="win32"){if(kind!=="pipe")await lstat2(path);await windowsRequest({operation:"check",path,kind});return}const s=await lstat2(path);if(s.isSymbolicLink()||s.uid!==process.getuid?.()||s.mode&63||(kind==="directory"?!s.isDirectory():kind==="pipe"?!s.isSocket():!s.isFile()))throw Error("LOCAL_PERMISSIONS_INVALID")}async function privateDirectory(path,create=false){if(!isAbsolute2(path)||!["win32","darwin","linux"].includes(process.platform))throw Error("LOCAL_LOCATION_INVALID");if(process.platform==="win32")await windowsRequest({operation:create?"directory":"check",path,kind:"directory"});else{if(create)await mkdir(path,{recursive:true,mode:448});await privateAccess(path,"directory")}}async function syncDirectory(path){if(process.platform==="win32")return;const d=await open(path,"r");try{await d.sync()}finally{await d.close()}}async function atomicMove(source,target,exclusive=false){if(dirname(source)!==dirname(target))throw Error("LOCAL_ATOMIC_MOVE_INVALID");if(process.platform==="win32"){try{await windowsRequest({operation:"move",source,target,exclusive})}catch(error){if(error.message==="EXISTS")throw Object.assign(Error("EXISTS"),{code:"EEXIST"});throw error}}else{if(exclusive){await link(source,target);await unlink(source)}else await rename(source,target);await syncDirectory(dirname(target))}}async function assertExecutable(path){const s=await lstat2(path);if(!isAbsolute2(path)||!s.isFile()||s.isSymbolicLink()||s.nlink!==1)throw Error("LOCAL_EXECUTABLE_INVALID");if(process.platform==="win32"){if(!path.toLowerCase().endsWith(".exe"))throw Error("LOCAL_EXECUTABLE_INVALID");await windowsRequest({operation:"executable",path})}else if(!(s.mode&73)||s.mode&18)throw Error("LOCAL_EXECUTABLE_INVALID")}import{spawn as spawn2}from"node:child_process";import{Duplex}from"node:stream";import{constants}from"node:fs";import{open as open2,realpath as realpath2,rename as rename2,unlink as unlink2,link as link2,readdir}from"node:fs/promises";import{isAbsolute as isAbsolute3,join as join3,dirname as dirname2}from"node:path";import{randomUUID as randomUUID2,createHash as createHash3}from"node:crypto";var sha256=v=>createHash3("sha256").update(v).digest("hex");var sha512=v=>createHash3("sha512").update(v).digest("hex");var LocalClientError=class extends Error{constructor(code){super("NativeStudio local "+code);this.code=code}code};function fail(code){throw new LocalClientError(code)}async function directory(path){if(!isAbsolute3(path))fail("LOCATION_UNSUPPORTED");try{await privateDirectory(path,true)}catch{fail("PRIVATE_LOCATION_REQUIRED")}const root=await realpath2(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))fail("PRIVATE_LOCATION_REQUIRED");return root}async function read(path,maximum=65536,ledger=false){try{await privateAccess(path,"file")}catch(e){if(e.code==="ENOENT")throw e;fail("PRIVATE_FILE_REQUIRED")}const f=await open2(path,constants.O_RDONLY|constants.O_NOFOLLOW);try{const s=await f.stat();if(!s.isFile()||process.platform!=="win32"&&(s.uid!==process.getuid?.()||s.mode&63)||s.size>maximum||(ledger?s.nlink>2:s.nlink!==1))fail("PRIVATE_FILE_REQUIRED");const bytes=Buffer.alloc(Math.min(maximum+1,s.size+1));let used=0;while(used<bytes.length){const part=await f.read(bytes,used,bytes.length-used,null);if(!part.bytesRead)break;used+=part.bytesRead}if(used>s.size)fail("FILE_CHANGED");if(used>maximum)fail("FILE_LIMIT");return bytes.subarray(0,used)}finally{await f.close()}}async function write(path,value,exclusive=false){const temporary=join3(dirname2(path),".tmp-"+randomUUID2());const f=await open2(temporary,"wx",384);try{await f.writeFile(value);await f.sync()}finally{await f.close()}try{if(process.platform==="win32")await atomicMove(temporary,path,exclusive);else if(exclusive)await link2(temporary,path);else{try{await read(path,64*1024*1024)}catch(e){if(e.code!=="ENOENT")throw e}await rename2(temporary,path)}}finally{await unlink2(temporary).catch(e=>{if(e.code!=="ENOENT")throw e})}await syncDirectory(dirname2(path))}async function entries(path){const values=await readdir(path);if(values.length>1e4)fail("HISTORY_LIMIT");return values}async function optional(path){try{return JSON.parse((await read(path)).toString())}catch(e){if(e.code==="ENOENT")return null;throw e}}async function verifyBackup(path,stateDirectory){const base=await realpath2(join3(stateDirectory,"backups")),actual=await realpath2(path);if(dirname2(actual)!==base||!/[0-9a-f-]{36}\.sqlite$/.test(actual))fail("JOURNAL_BACKUP_REQUIRED");try{await privateAccess(actual,"file")}catch{fail("JOURNAL_BACKUP_REQUIRED")}const f=await open2(actual,constants.O_RDONLY|constants.O_NOFOLLOW);try{const stat=await f.stat(),header=Buffer.alloc(16);if(!stat.isFile()||stat.nlink!==1||process.platform!=="win32"&&(stat.uid!==process.getuid?.()||stat.mode&63)||stat.size<100)fail("JOURNAL_BACKUP_REQUIRED");const n=await f.read(header,0,16,0);if(n.bytesRead!==16||header.toString()!=="SQLite format 3\0")fail("JOURNAL_BACKUP_REQUIRED")}finally{await f.close()}}export{localSocketPath,privateAccess,privateDirectory,atomicMove,assertExecutable,sha256,sha512,LocalClientError,fail,directory,read,write,entries,optional,verifyBackup};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CliAccountExchangeSchema,CliAccountIdentitySchema,CliAccountSessionSchema,CliAccountStartSchema,CliAccountStartedSchema,ProjectLibraryPageSchema,ProjectWorkspaceSchema}from"./chunk-GJ7BZJLW.js";import{FileOAuthProvider,withProfileLock}from"./chunk-7S3DJ2QE.js";import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{directory,optional,privateDirectory,write}from"./chunk-66CUOZVI.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{homedir}from"node:os";import{isAbsolute,join}from"node:path";import{realpath}from"node:fs/promises";function connectionError(code){throw new NativeStudioSdkError(code,"INVALID_INPUT","NO_WRITE")}async function clientHome(environment,create=false){const path=environment.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio","client");if(!isAbsolute(path))connectionError("CLIENT_HOME_ABSOLUTE_REQUIRED");if(create)return directory(path);await privateDirectory(path);const root=await realpath(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))connectionError("CLIENT_HOME_PRIVATE_REQUIRED");return root}import{join as join2}from"node:path";import{z as z2}from"zod";import{z}from"zod";function accountServerOrigin(value){const url=new URL(value);if(url.pathname!=="/"||url.search||url.hash||url.username||url.password||!(url.protocol==="https:"||url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)))throw new NativeStudioSdkError("ACCOUNT_SERVER_ORIGIN_REQUIRED","INVALID_INPUT","NO_WRITE");return url.origin}var NativeStudioAccountClient=class{constructor(options){this.options=options;this.serverOrigin=accountServerOrigin(options.serverOrigin);if(options.accessToken&&!/^nvsh_[A-Za-z0-9_-]{43}$/.test(options.accessToken))throw new NativeStudioSdkError("INVALID_ACCOUNT_CREDENTIAL","INVALID_INPUT","NO_WRITE")}options;serverOrigin;async request(action,schema,options={}){if(options.credential&&!this.options.accessToken)throw new NativeStudioSdkError("ACCOUNT_LOGIN_REQUIRED","INVALID_INPUT","NO_WRITE");const write2=options.body!==void 0;let response;try{response=await(this.options.fetch??fetch)(`${this.serverOrigin}/api/cli-account/${action}${options.query?"?"+options.query:""}`,{method:write2?"POST":"GET",cache:"no-store",redirect:"error",credentials:"omit",signal:AbortSignal.any([AbortSignal.timeout(15e3),...options.signal?[options.signal]:[]]),headers:{...write2?{"content-type":"application/json"}:{},...options.credential?{authorization:"Bearer "+this.options.accessToken}:{}},...write2?{body:JSON.stringify(options.body)}:{}})}catch{throw new NativeStudioSdkError("ACCOUNT_TRANSPORT_FAILED","BLOCKED",write2?"UNKNOWN":"NO_WRITE")}if(!response.ok){await response.body?.cancel();throw new NativeStudioSdkError(response.status===401?"ACCOUNT_SESSION_EXPIRED_OR_REVOKED":"ACCOUNT_REQUEST_REJECTED","BLOCKED",write2&&response.status>=500?"UNKNOWN":"REJECTED",response.status)}try{if(!(response.headers.get("content-type")??"").startsWith("application/json"))throw Error();const reader=response.body?.getReader();if(!reader)throw Error();const chunks=[];let size=0;try{while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>1024*1024){await reader.cancel();throw Error()}chunks.push(part.value)}}finally{reader.releaseLock()}const bytes=new Uint8Array(size);let offset=0;for(const part of chunks){bytes.set(part,offset);offset+=part.length}return schema.parse(JSON.parse(new TextDecoder().decode(bytes)))}catch{throw new NativeStudioSdkError("ACCOUNT_RESPONSE_INVALID","BLOCKED",write2?"UNKNOWN":"NO_WRITE")}}async metadata(signal){return this.request("metadata",z.strictObject({protocol:z.literal("NVS_CLI_ACCOUNT_V1"),serverOrigin:z.literal(this.serverOrigin)}),{signal})}start(input,signal){return this.request("start",CliAccountStartedSchema,{body:CliAccountStartSchema.parse(input),signal})}exchange(input,signal){return this.request("exchange",CliAccountSessionSchema,{body:CliAccountExchangeSchema.parse(input),signal})}me(signal){return this.request("me",CliAccountIdentitySchema,{credential:true,signal})}logout(signal){return this.request("logout",z.strictObject({changed:z.literal(true)}),{credential:true,body:{},signal})}async projects(input,signal){const value=z.strictObject({tenantId:z.uuid(),limit:z.number().int().min(1).max(100).optional(),next:z.string().min(1).max(8192).optional()}).parse(input);const result=await this.request("projects",ProjectLibraryPageSchema,{credential:true,signal,query:new URLSearchParams({tenantId:value.tenantId,...value.limit?{limit:String(value.limit)}:{},...value.next?{next:value.next}:{}})});if(result.items.some(p=>p.tenantId!==value.tenantId))throw new NativeStudioSdkError("ACCOUNT_RESPONSE_SCOPE_MISMATCH","BLOCKED","NO_WRITE");return result}async project(input,signal){const value=z.strictObject({tenantId:z.uuid(),projectId:z.uuid()}).parse(input);const result=await this.request("project",ProjectWorkspaceSchema,{credential:true,signal,query:new URLSearchParams(value)});if(result.project.id!==value.projectId||result.project.tenantId!==value.tenantId)throw new NativeStudioSdkError("ACCOUNT_RESPONSE_SCOPE_MISMATCH","BLOCKED","NO_WRITE");return result}};var AccountStateSchema=z2.strictObject({version:z2.literal(1),epoch:z2.uuid(),serverOrigin:z2.string().refine(v=>{try{return accountServerOrigin(v)===v}catch{return false}}),principalId:z2.uuid(),expiresAt:z2.iso.datetime(),workspaceId:z2.uuid().nullable(),projectId:z2.uuid().nullable(),state:z2.enum(["ACTIVE","REVOKE_PENDING","SIGNED_OUT"]),accessToken:z2.string().regex(/^nvsh_[A-Za-z0-9_-]{43}$/).nullable()}).refine(v=>v.state==="SIGNED_OUT"===(v.accessToken===null)&&(!v.projectId||Boolean(v.workspaceId)));function accountError(code,outcome="NO_WRITE"){throw new NativeStudioSdkError(code,outcome==="UNKNOWN"?"INTERNAL_OPERATIONAL_FAILURE":["ACCOUNT_LOGIN_INPUT_INVALID","ACCOUNT_COMMAND_INPUT_INVALID"].includes(code)?"INVALID_INPUT":"BLOCKED",outcome)}async function readAccount(root){const value=await optional(join2(root,"account.json"));if(value===null)return null;const parsed=AccountStateSchema.safeParse(value);if(!parsed.success)accountError("ACCOUNT_STATE_INVALID");return parsed.data}async function saveAccount(root,value){const account=AccountStateSchema.parse(value);const pointer=z2.object({version:z2.literal(1)}).passthrough().safeParse(await optional(join2(root,"connection.json")));if(pointer.success)await write(join2(root,"connection.json"),JSON.stringify({...pointer.data,version:2,accountEpoch:account.epoch}));await write(join2(root,"account.json"),JSON.stringify(account))}async function withAccountLock(root,action){try{return await withProfileLock(join2(root,"account.json"),action)}catch(error){if(error.code==="EEXIST")accountError("ACCOUNT_COMMAND_BUSY");throw error}}function requireAccount(value){if(!value)accountError("ACCOUNT_LOGIN_REQUIRED");if(value.state==="REVOKE_PENDING")accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN");if(value.state!=="ACTIVE"||Date.parse(value.expiresAt)<=Date.now())accountError("ACCOUNT_LOGIN_REQUIRED");return value}import{join as join3}from"node:path";var uuid="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";var projectPath=new RegExp(`^/mcp/external/v1/tenants/(${uuid})/projects/(${uuid})$`,"i");function projectConnection(resource){const url=secureEndpoint(resource),match=projectPath.exec(url.pathname);if(!match)connectionError("PROJECT_MCP_URL_REQUIRED");return{resource:url.href,tenantId:match[1],projectId:match[2]}}async function saveConnection(root,profile,expectedEpoch){return withAccountLock(root,()=>saveConnectionLocked(root,profile,expectedEpoch))}async function saveConnectionLocked(root,profile,expectedEpoch){if(!/^profile-[0-9a-f-]{36}\.json$/.test(profile))throw Error();const provider=await FileOAuthProvider.load(join3(root,profile));const scope=projectConnection(provider.data.resource);if(!provider.data.token?.access_token||provider.data.pendingExchange)throw Error();const account=await readAccount(root);if(account?.epoch!==expectedEpoch)connectionError("ACCOUNT_CHANGED_DURING_CONNECTION");if(account&&(account.state!=="ACTIVE"||Date.parse(account.expiresAt)<=Date.now()||account.workspaceId!==scope.tenantId||account.projectId!==scope.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");await write(join3(root,"connection.json"),JSON.stringify({version:account?2:1,profile,...scope,...account?{accountEpoch:account.epoch}:{}}));return{scope:provider.data.token.scope??provider.data.scope,expiresAt:provider.data.expiresAt}}async function loadConnection(environment,verifyAccount=false){let root;try{root=await clientHome(environment)}catch(e){if(e.code==="ENOENT")return null;throw e}const value=await optional(join3(root,"connection.json"));if(value===null)return null;if(value.version!==1&&value.version!==2||typeof value.profile!=="string"||!/^profile-[0-9a-f-]{36}\.json$/.test(value.profile)||typeof value.resource!=="string")connectionError("CONNECTION_INVALID");const scope=projectConnection(value.resource);if(scope.tenantId!==value.tenantId||scope.projectId!==value.projectId)connectionError("CONNECTION_SCOPE_MISMATCH");const account=await readAccount(root);if(value.version===2&&(!account||typeof value.accountEpoch!=="string"))connectionError("PROJECT_CONNECTION_ACCOUNT_MISMATCH");if(account&&(value.version!==2||account.state!=="ACTIVE"||Date.parse(account.expiresAt)<=Date.now()||value.accountEpoch!==account.epoch||scope.tenantId!==account.workspaceId||scope.projectId!==account.projectId))connectionError("PROJECT_CONNECTION_ACCOUNT_MISMATCH");if(account&&verifyAccount){const identity=await new NativeStudioAccountClient({serverOrigin:account.serverOrigin,accessToken:account.accessToken}).me();if(identity.account.principalId!==account.principalId||!identity.account.tenants.some(t=>t.id===scope.tenantId))connectionError("PROJECT_CONNECTION_ACCOUNT_MISMATCH")}const profile=join3(root,value.profile),provider=await FileOAuthProvider.load(profile);if(provider.data.resource!==scope.resource||!provider.data.token?.access_token)connectionError("CONNECTION_PROFILE_MISMATCH");return{...scope,profile,scope:provider.data.token.scope??provider.data.scope,requestedScope:provider.data.scope,expiresAt:provider.data.expiresAt,exchangeUnresolved:Boolean(provider.data.pendingExchange)}}var authentication=["--profile","--origin","--mcp-url","--token-env","--token-file"];async function defaultConnection(options,environment,tenant){if(authentication.some(key=>options.has(key)))return;const connection=await loadConnection(environment,true);if(!connection)connectionError("PROJECT_CONNECTION_REQUIRED");if(options.has("--tenant")&&options.get("--tenant")!==connection.tenantId)connectionError("CONNECTION_SCOPE_MISMATCH");options.set("--profile",connection.profile);if(tenant)options.set("--tenant",connection.tenantId)}async function connectionStatus(environment){const value=await loadConnection(environment);return{exitCode:0,output:value?{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"PROJECT_MCP",accountSessionVerified:false,verification:"LOCAL_METADATA_ONLY",resource:value.resource,tenantId:value.tenantId,projectId:value.projectId,scope:value.scope,requestedScope:value.requestedScope,expiresAt:value.expiresAt,credentialState:value.exchangeUnresolved?"EXCHANGE_UNRESOLVED":typeof value.expiresAt==="number"&&value.expiresAt>Date.now()+3e4?"CACHED":"REFRESH_REQUIRED",nextSteps:value.exchangeUnresolved?["Wait for the active authorization command. If it returned OAUTH_OUTCOME_UNKNOWN, run nvs connect --mcp-url <project-connection-url>."]:["nvs find --query <intent>","nvs capabilities","nvs mcp"]}:{semanticStatus:"NEEDS_INPUT",connected:false,credentialPurpose:"PROJECT_MCP",accountSessionVerified:false,nextSteps:["Sign in/register your account on Web or Electron, then select a workspace/project and open its Agent connection page.","nvs connect --mcp-url <project-connection-url>"]}}}export{connectionError,clientHome,accountServerOrigin,NativeStudioAccountClient,accountError,readAccount,saveAccount,withAccountLock,requireAccount,projectConnection,saveConnection,defaultConnection,connectionStatus};
|
|
1
|
+
import{FileOAuthProvider,withProfileLock}from"./chunk-FU3524Z6.js";import{directory,optional,privateDirectory,write}from"./chunk-KB2GVAN7.js";import{CliAccountExchangeSchema,CliAccountIdentitySchema,CliAccountSessionSchema,CliAccountStartSchema,CliAccountStartedSchema,ProjectLibraryPageSchema,ProjectWorkspaceSchema}from"./chunk-GJ7BZJLW.js";import{secureEndpoint}from"./chunk-PUNG4ND7.js";import{NativeStudioSdkError}from"./chunk-6NVIN2NI.js";import{homedir}from"node:os";import{isAbsolute,join}from"node:path";import{realpath}from"node:fs/promises";function connectionError(code){throw new NativeStudioSdkError(code,"INVALID_INPUT","NO_WRITE")}async function clientHome(environment,create=false){const path=environment.NATIVESTUDIO_CLIENT_HOME??join(homedir(),".nativestudio","client");if(!isAbsolute(path))connectionError("CLIENT_HOME_ABSOLUTE_REQUIRED");if(create)return directory(path);await privateDirectory(path);const root=await realpath(path);if(/(?:^|[\\/])(?:node_modules|_npx)(?:[\\/]|$)/.test(root))connectionError("CLIENT_HOME_PRIVATE_REQUIRED");return root}import{join as join2}from"node:path";import{z as z2}from"zod";import{z}from"zod";function accountServerOrigin(value){const url=new URL(value);if(url.pathname!=="/"||url.search||url.hash||url.username||url.password||!(url.protocol==="https:"||url.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(url.hostname)))throw new NativeStudioSdkError("ACCOUNT_SERVER_ORIGIN_REQUIRED","INVALID_INPUT","NO_WRITE");return url.origin}var NativeStudioAccountClient=class{constructor(options){this.options=options;this.serverOrigin=accountServerOrigin(options.serverOrigin);if(options.accessToken&&!/^nvsh_[A-Za-z0-9_-]{43}$/.test(options.accessToken))throw new NativeStudioSdkError("INVALID_ACCOUNT_CREDENTIAL","INVALID_INPUT","NO_WRITE")}options;serverOrigin;async request(action,schema,options={}){if(options.credential&&!this.options.accessToken)throw new NativeStudioSdkError("ACCOUNT_LOGIN_REQUIRED","INVALID_INPUT","NO_WRITE");const write2=options.body!==void 0;let response;try{response=await(this.options.fetch??fetch)(`${this.serverOrigin}/api/cli-account/${action}${options.query?"?"+options.query:""}`,{method:write2?"POST":"GET",cache:"no-store",redirect:"error",credentials:"omit",signal:AbortSignal.any([AbortSignal.timeout(15e3),...options.signal?[options.signal]:[]]),headers:{...write2?{"content-type":"application/json"}:{},...options.credential?{authorization:"Bearer "+this.options.accessToken}:{}},...write2?{body:JSON.stringify(options.body)}:{}})}catch{throw new NativeStudioSdkError("ACCOUNT_TRANSPORT_FAILED","BLOCKED",write2?"UNKNOWN":"NO_WRITE")}if(!response.ok){await response.body?.cancel();throw new NativeStudioSdkError(response.status===401?"ACCOUNT_SESSION_EXPIRED_OR_REVOKED":"ACCOUNT_REQUEST_REJECTED","BLOCKED",write2&&response.status>=500?"UNKNOWN":"REJECTED",response.status)}try{if(!(response.headers.get("content-type")??"").startsWith("application/json"))throw Error();const reader=response.body?.getReader();if(!reader)throw Error();const chunks=[];let size=0;try{while(true){const part=await reader.read();if(part.done)break;size+=part.value.byteLength;if(size>1024*1024){await reader.cancel();throw Error()}chunks.push(part.value)}}finally{reader.releaseLock()}const bytes=new Uint8Array(size);let offset=0;for(const part of chunks){bytes.set(part,offset);offset+=part.length}return schema.parse(JSON.parse(new TextDecoder().decode(bytes)))}catch{throw new NativeStudioSdkError("ACCOUNT_RESPONSE_INVALID","BLOCKED",write2?"UNKNOWN":"NO_WRITE")}}async metadata(signal){return this.request("metadata",z.strictObject({protocol:z.literal("NVS_CLI_ACCOUNT_V1"),serverOrigin:z.literal(this.serverOrigin)}),{signal})}start(input,signal){return this.request("start",CliAccountStartedSchema,{body:CliAccountStartSchema.parse(input),signal})}exchange(input,signal){return this.request("exchange",CliAccountSessionSchema,{body:CliAccountExchangeSchema.parse(input),signal})}me(signal){return this.request("me",CliAccountIdentitySchema,{credential:true,signal})}logout(signal){return this.request("logout",z.strictObject({changed:z.literal(true)}),{credential:true,body:{},signal})}async projects(input,signal){const value=z.strictObject({tenantId:z.uuid(),limit:z.number().int().min(1).max(100).optional(),next:z.string().min(1).max(8192).optional()}).parse(input);const result=await this.request("projects",ProjectLibraryPageSchema,{credential:true,signal,query:new URLSearchParams({tenantId:value.tenantId,...value.limit?{limit:String(value.limit)}:{},...value.next?{next:value.next}:{}})});if(result.items.some(p=>p.tenantId!==value.tenantId))throw new NativeStudioSdkError("ACCOUNT_RESPONSE_SCOPE_MISMATCH","BLOCKED","NO_WRITE");return result}async project(input,signal){const value=z.strictObject({tenantId:z.uuid(),projectId:z.uuid()}).parse(input);const result=await this.request("project",ProjectWorkspaceSchema,{credential:true,signal,query:new URLSearchParams(value)});if(result.project.id!==value.projectId||result.project.tenantId!==value.tenantId)throw new NativeStudioSdkError("ACCOUNT_RESPONSE_SCOPE_MISMATCH","BLOCKED","NO_WRITE");return result}};var AccountStateSchema=z2.strictObject({version:z2.literal(1),epoch:z2.uuid(),serverOrigin:z2.string().refine(v=>{try{return accountServerOrigin(v)===v}catch{return false}}),principalId:z2.uuid(),expiresAt:z2.iso.datetime(),workspaceId:z2.uuid().nullable(),projectId:z2.uuid().nullable(),state:z2.enum(["ACTIVE","REVOKE_PENDING","SIGNED_OUT"]),accessToken:z2.string().regex(/^nvsh_[A-Za-z0-9_-]{43}$/).nullable()}).refine(v=>v.state==="SIGNED_OUT"===(v.accessToken===null)&&(!v.projectId||Boolean(v.workspaceId)));function accountError(code,outcome="NO_WRITE"){throw new NativeStudioSdkError(code,outcome==="UNKNOWN"?"INTERNAL_OPERATIONAL_FAILURE":["ACCOUNT_LOGIN_INPUT_INVALID","ACCOUNT_COMMAND_INPUT_INVALID"].includes(code)?"INVALID_INPUT":"BLOCKED",outcome)}async function readAccount(root){const value=await optional(join2(root,"account.json"));if(value===null)return null;const parsed=AccountStateSchema.safeParse(value);if(!parsed.success)accountError("ACCOUNT_STATE_INVALID");return parsed.data}async function saveAccount(root,value){const account=AccountStateSchema.parse(value);const pointer=z2.object({version:z2.literal(1)}).passthrough().safeParse(await optional(join2(root,"connection.json")));if(pointer.success)await write(join2(root,"connection.json"),JSON.stringify({...pointer.data,version:2,accountEpoch:account.epoch}));await write(join2(root,"account.json"),JSON.stringify(account))}async function withAccountLock(root,action){try{return await withProfileLock(join2(root,"account.json"),action)}catch(error){if(error.code==="EEXIST")accountError("ACCOUNT_COMMAND_BUSY");throw error}}function requireAccount(value){if(!value)accountError("ACCOUNT_LOGIN_REQUIRED");if(value.state==="REVOKE_PENDING")accountError("ACCOUNT_LOGOUT_OUTCOME_UNKNOWN","UNKNOWN");if(value.state!=="ACTIVE"||Date.parse(value.expiresAt)<=Date.now())accountError("ACCOUNT_LOGIN_REQUIRED");return value}import{join as join3}from"node:path";var uuid="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";var projectPath=new RegExp(`^/mcp/external/v1/tenants/(${uuid})/projects/(${uuid})$`,"i");function projectConnection(resource){const url=secureEndpoint(resource),match=projectPath.exec(url.pathname);if(!match)connectionError("PROJECT_MCP_URL_REQUIRED");return{resource:url.href,tenantId:match[1],projectId:match[2]}}async function saveConnection(root,profile,expectedEpoch){return withAccountLock(root,()=>saveConnectionLocked(root,profile,expectedEpoch))}async function saveConnectionLocked(root,profile,expectedEpoch){if(!/^profile-[0-9a-f-]{36}\.json$/.test(profile))throw Error();const provider=await FileOAuthProvider.load(join3(root,profile));const scope=projectConnection(provider.data.resource);if(!provider.data.token?.access_token||provider.data.pendingExchange)throw Error();const account=await readAccount(root);if(account?.epoch!==expectedEpoch)connectionError("ACCOUNT_CHANGED_DURING_CONNECTION");if(account&&(account.state!=="ACTIVE"||Date.parse(account.expiresAt)<=Date.now()||account.workspaceId!==scope.tenantId||account.projectId!==scope.projectId))connectionError("ACCOUNT_PROJECT_SELECTION_REQUIRED");await write(join3(root,"connection.json"),JSON.stringify({version:account?2:1,profile,...scope,...account?{accountEpoch:account.epoch}:{}}));return{scope:provider.data.token.scope??provider.data.scope,expiresAt:provider.data.expiresAt}}async function loadConnection(environment,verifyAccount=false){let root;try{root=await clientHome(environment)}catch(e){if(e.code==="ENOENT")return null;throw e}const value=await optional(join3(root,"connection.json"));if(value===null)return null;if(value.version!==1&&value.version!==2||typeof value.profile!=="string"||!/^profile-[0-9a-f-]{36}\.json$/.test(value.profile)||typeof value.resource!=="string")connectionError("CONNECTION_INVALID");const scope=projectConnection(value.resource);if(scope.tenantId!==value.tenantId||scope.projectId!==value.projectId)connectionError("CONNECTION_SCOPE_MISMATCH");const account=await readAccount(root);if(value.version===2&&(!account||typeof value.accountEpoch!=="string"))connectionError("PROJECT_CONNECTION_ACCOUNT_MISMATCH");if(account&&(value.version!==2||account.state!=="ACTIVE"||Date.parse(account.expiresAt)<=Date.now()||value.accountEpoch!==account.epoch||scope.tenantId!==account.workspaceId||scope.projectId!==account.projectId))connectionError("PROJECT_CONNECTION_ACCOUNT_MISMATCH");if(account&&verifyAccount){const identity=await new NativeStudioAccountClient({serverOrigin:account.serverOrigin,accessToken:account.accessToken}).me();if(identity.account.principalId!==account.principalId||!identity.account.tenants.some(t=>t.id===scope.tenantId))connectionError("PROJECT_CONNECTION_ACCOUNT_MISMATCH")}const profile=join3(root,value.profile),provider=await FileOAuthProvider.load(profile);if(provider.data.resource!==scope.resource||!provider.data.token?.access_token)connectionError("CONNECTION_PROFILE_MISMATCH");return{...scope,profile,scope:provider.data.token.scope??provider.data.scope,requestedScope:provider.data.scope,expiresAt:provider.data.expiresAt,exchangeUnresolved:Boolean(provider.data.pendingExchange)}}var authentication=["--profile","--origin","--mcp-url","--token-env","--token-file"];async function defaultConnection(options,environment,tenant){if(authentication.some(key=>options.has(key)))return;const connection=await loadConnection(environment,true);if(!connection)connectionError("PROJECT_CONNECTION_REQUIRED");if(options.has("--tenant")&&options.get("--tenant")!==connection.tenantId)connectionError("CONNECTION_SCOPE_MISMATCH");options.set("--profile",connection.profile);if(tenant)options.set("--tenant",connection.tenantId)}async function connectionStatus(environment){const value=await loadConnection(environment);return{exitCode:0,output:value?{semanticStatus:"SUCCESS",connected:true,credentialPurpose:"PROJECT_MCP",accountSessionVerified:false,verification:"LOCAL_METADATA_ONLY",resource:value.resource,tenantId:value.tenantId,projectId:value.projectId,scope:value.scope,requestedScope:value.requestedScope,expiresAt:value.expiresAt,credentialState:value.exchangeUnresolved?"EXCHANGE_UNRESOLVED":typeof value.expiresAt==="number"&&value.expiresAt>Date.now()+3e4?"CACHED":"REFRESH_REQUIRED",nextSteps:value.exchangeUnresolved?["Wait for the active authorization command. If it returned OAUTH_OUTCOME_UNKNOWN, run nvs connect --mcp-url <project-connection-url>."]:["nvs find --query <intent>","nvs capabilities","nvs mcp"]}:{semanticStatus:"NEEDS_INPUT",connected:false,credentialPurpose:"PROJECT_MCP",accountSessionVerified:false,nextSteps:["Sign in/register your account on Web or Electron, then select a workspace/project and open its Agent connection page.","nvs connect --mcp-url <project-connection-url>"]}}}export{connectionError,clientHome,accountServerOrigin,NativeStudioAccountClient,accountError,readAccount,saveAccount,withAccountLock,requireAccount,projectConnection,saveConnection,loadConnection,defaultConnection,connectionStatus};
|